2 * @brief memory-mapped database library
4 * A Btree-based database management library modeled loosely on the
5 * BerkeleyDB API, but much simplified.
8 * Copyright 2011-2013 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.
38 #include <sys/types.h>
40 #include <sys/param.h>
46 #ifdef HAVE_SYS_FILE_H
63 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
64 #include <netinet/in.h>
65 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
68 #if defined(__APPLE__) || defined (BSD)
69 # define MDB_USE_POSIX_SEM 1
70 # define MDB_FDATASYNC fsync
71 #elif defined(ANDROID)
72 # define MDB_FDATASYNC fsync
77 #ifdef MDB_USE_POSIX_SEM
78 # define MDB_USE_HASH 1
79 #include <semaphore.h>
84 #include <valgrind/memcheck.h>
85 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
86 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
87 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
88 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
89 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
91 #define VGMEMP_CREATE(h,r,z)
92 #define VGMEMP_ALLOC(h,a,s)
93 #define VGMEMP_FREE(h,a)
94 #define VGMEMP_DESTROY(h)
95 #define VGMEMP_DEFINED(a,s)
99 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
100 /* Solaris just defines one or the other */
101 # define LITTLE_ENDIAN 1234
102 # define BIG_ENDIAN 4321
103 # ifdef _LITTLE_ENDIAN
104 # define BYTE_ORDER LITTLE_ENDIAN
106 # define BYTE_ORDER BIG_ENDIAN
109 # define BYTE_ORDER __BYTE_ORDER
113 #ifndef LITTLE_ENDIAN
114 #define LITTLE_ENDIAN __LITTLE_ENDIAN
117 #define BIG_ENDIAN __BIG_ENDIAN
120 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
121 #define MISALIGNED_OK 1
127 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
128 # error "Unknown or unsupported endianness (BYTE_ORDER)"
129 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
130 # error "Two's complement, reasonably sized integer types, please"
133 /** @defgroup internal MDB Internals
136 /** @defgroup compat Windows Compatibility Macros
137 * A bunch of macros to minimize the amount of platform-specific ifdefs
138 * needed throughout the rest of the code. When the features this library
139 * needs are similar enough to POSIX to be hidden in a one-or-two line
140 * replacement, this macro approach is used.
144 #define MDB_USE_HASH 1
145 #define MDB_PIDLOCK 0
146 #define pthread_t DWORD
147 #define pthread_mutex_t HANDLE
148 #define pthread_key_t DWORD
149 #define pthread_self() GetCurrentThreadId()
150 #define pthread_key_create(x,y) \
151 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
152 #define pthread_key_delete(x) TlsFree(x)
153 #define pthread_getspecific(x) TlsGetValue(x)
154 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
155 #define pthread_mutex_unlock(x) ReleaseMutex(x)
156 #define pthread_mutex_lock(x) WaitForSingleObject(x, INFINITE)
157 #define LOCK_MUTEX_R(env) pthread_mutex_lock((env)->me_rmutex)
158 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock((env)->me_rmutex)
159 #define LOCK_MUTEX_W(env) pthread_mutex_lock((env)->me_wmutex)
160 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock((env)->me_wmutex)
161 #define getpid() GetCurrentProcessId()
162 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
163 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
164 #define ErrCode() GetLastError()
165 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
166 #define close(fd) (CloseHandle(fd) ? 0 : -1)
167 #define munmap(ptr,len) UnmapViewOfFile(ptr)
168 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
169 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
171 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
176 #define Z "z" /**< printf format modifier for size_t */
178 /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
179 #define MDB_PIDLOCK 1
181 #ifdef MDB_USE_POSIX_SEM
183 #define LOCK_MUTEX_R(env) mdb_sem_wait((env)->me_rmutex)
184 #define UNLOCK_MUTEX_R(env) sem_post((env)->me_rmutex)
185 #define LOCK_MUTEX_W(env) mdb_sem_wait((env)->me_wmutex)
186 #define UNLOCK_MUTEX_W(env) sem_post((env)->me_wmutex)
189 mdb_sem_wait(sem_t *sem)
192 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
197 /** Lock the reader mutex.
199 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
200 /** Unlock the reader mutex.
202 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
204 /** Lock the writer mutex.
205 * Only a single write transaction is allowed at a time. Other writers
206 * will block waiting for this mutex.
208 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
209 /** Unlock the writer mutex.
211 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
212 #endif /* MDB_USE_POSIX_SEM */
214 /** Get the error code for the last failed system function.
216 #define ErrCode() errno
218 /** An abstraction for a file handle.
219 * On POSIX systems file handles are small integers. On Windows
220 * they're opaque pointers.
224 /** A value for an invalid file handle.
225 * Mainly used to initialize file variables and signify that they are
228 #define INVALID_HANDLE_VALUE (-1)
230 /** Get the size of a memory page for the system.
231 * This is the basic size that the platform's memory manager uses, and is
232 * fundamental to the use of memory-mapped files.
234 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
237 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
240 #define MNAME_LEN (sizeof(pthread_mutex_t))
246 /** A flag for opening a file and requesting synchronous data writes.
247 * This is only used when writing a meta page. It's not strictly needed;
248 * we could just do a normal write and then immediately perform a flush.
249 * But if this flag is available it saves us an extra system call.
251 * @note If O_DSYNC is undefined but exists in /usr/include,
252 * preferably set some compiler flag to get the definition.
253 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
256 # define MDB_DSYNC O_DSYNC
260 /** Function for flushing the data of a file. Define this to fsync
261 * if fdatasync() is not supported.
263 #ifndef MDB_FDATASYNC
264 # define MDB_FDATASYNC fdatasync
268 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
279 /** A page number in the database.
280 * Note that 64 bit page numbers are overkill, since pages themselves
281 * already represent 12-13 bits of addressable memory, and the OS will
282 * always limit applications to a maximum of 63 bits of address space.
284 * @note In the #MDB_node structure, we only store 48 bits of this value,
285 * which thus limits us to only 60 bits of addressable data.
287 typedef MDB_ID pgno_t;
289 /** A transaction ID.
290 * See struct MDB_txn.mt_txnid for details.
292 typedef MDB_ID txnid_t;
294 /** @defgroup debug Debug Macros
298 /** Enable debug output. Needs variable argument macros (a C99 feature).
299 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
300 * read from and written to the database (used for free space management).
306 static int mdb_debug;
307 static txnid_t mdb_debug_start;
309 /** Print a debug message with printf formatting.
310 * Requires double parenthesis around 2 or more args.
312 # define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
313 # define DPRINTF0(fmt, ...) \
314 fprintf(stderr, "%s:%d " fmt "\n", __func__, __LINE__, __VA_ARGS__)
316 # define DPRINTF(args) ((void) 0)
318 /** Print a debug string.
319 * The string is printed literally, with no format processing.
321 #define DPUTS(arg) DPRINTF(("%s", arg))
322 /** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
324 (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
327 /** @brief The maximum size of a database page.
329 * This is 32k, since it must fit in #MDB_page.#mp_upper.
331 * LMDB will use database pages < OS pages if needed.
332 * That causes more I/O in write transactions: The OS must
333 * know (read) the whole page before writing a partial page.
335 * Note that we don't currently support Huge pages. On Linux,
336 * regular data files cannot use Huge pages, and in general
337 * Huge pages aren't actually pageable. We rely on the OS
338 * demand-pager to read our data and page it out when memory
339 * pressure from other processes is high. So until OSs have
340 * actual paging support for Huge pages, they're not viable.
342 #define MAX_PAGESIZE 0x8000
344 /** The minimum number of keys required in a database page.
345 * Setting this to a larger value will place a smaller bound on the
346 * maximum size of a data item. Data items larger than this size will
347 * be pushed into overflow pages instead of being stored directly in
348 * the B-tree node. This value used to default to 4. With a page size
349 * of 4096 bytes that meant that any item larger than 1024 bytes would
350 * go into an overflow page. That also meant that on average 2-3KB of
351 * each overflow page was wasted space. The value cannot be lower than
352 * 2 because then there would no longer be a tree structure. With this
353 * value, items larger than 2KB will go into overflow pages, and on
354 * average only 1KB will be wasted.
356 #define MDB_MINKEYS 2
358 /** A stamp that identifies a file as an MDB file.
359 * There's nothing special about this value other than that it is easily
360 * recognizable, and it will reflect any byte order mismatches.
362 #define MDB_MAGIC 0xBEEFC0DE
364 /** The version number for a database's datafile format. */
365 #define MDB_DATA_VERSION 1
366 /** The version number for a database's lockfile format. */
367 #define MDB_LOCK_VERSION 1
369 /** @brief The maximum size of a key in the database.
371 * The library rejects bigger keys, and cannot deal with records
372 * with bigger keys stored by a library with bigger max keysize.
374 * We require that keys all fit onto a regular page. This limit
375 * could be raised a bit further if needed; to something just
376 * under (page size / #MDB_MINKEYS).
378 * Note that data items in an #MDB_DUPSORT database are actually keys
379 * of a subDB, so they're also limited to this size.
381 #ifndef MDB_MAXKEYSIZE
382 #define MDB_MAXKEYSIZE 511
385 /** @brief The maximum size of a data item.
387 * We only store a 32 bit value for node sizes.
389 #define MAXDATASIZE 0xffffffffUL
394 * This is used for printing a hex dump of a key's contents.
396 #define DKBUF char kbuf[(MDB_MAXKEYSIZE*2+1)]
397 /** Display a key in hex.
399 * Invoke a function to display a key in hex.
401 #define DKEY(x) mdb_dkey(x, kbuf)
407 /** An invalid page number.
408 * Mainly used to denote an empty tree.
410 #define P_INVALID (~(pgno_t)0)
412 /** Test if the flags \b f are set in a flag word \b w. */
413 #define F_ISSET(w, f) (((w) & (f)) == (f))
415 /** Used for offsets within a single page.
416 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
419 typedef uint16_t indx_t;
421 /** Default size of memory map.
422 * This is certainly too small for any actual applications. Apps should always set
423 * the size explicitly using #mdb_env_set_mapsize().
425 #define DEFAULT_MAPSIZE 1048576
427 /** @defgroup readers Reader Lock Table
428 * Readers don't acquire any locks for their data access. Instead, they
429 * simply record their transaction ID in the reader table. The reader
430 * mutex is needed just to find an empty slot in the reader table. The
431 * slot's address is saved in thread-specific data so that subsequent read
432 * transactions started by the same thread need no further locking to proceed.
434 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
436 * No reader table is used if the database is on a read-only filesystem, or
437 * if #MDB_NOLOCK is set.
439 * Since the database uses multi-version concurrency control, readers don't
440 * actually need any locking. This table is used to keep track of which
441 * readers are using data from which old transactions, so that we'll know
442 * when a particular old transaction is no longer in use. Old transactions
443 * that have discarded any data pages can then have those pages reclaimed
444 * for use by a later write transaction.
446 * The lock table is constructed such that reader slots are aligned with the
447 * processor's cache line size. Any slot is only ever used by one thread.
448 * This alignment guarantees that there will be no contention or cache
449 * thrashing as threads update their own slot info, and also eliminates
450 * any need for locking when accessing a slot.
452 * A writer thread will scan every slot in the table to determine the oldest
453 * outstanding reader transaction. Any freed pages older than this will be
454 * reclaimed by the writer. The writer doesn't use any locks when scanning
455 * this table. This means that there's no guarantee that the writer will
456 * see the most up-to-date reader info, but that's not required for correct
457 * operation - all we need is to know the upper bound on the oldest reader,
458 * we don't care at all about the newest reader. So the only consequence of
459 * reading stale information here is that old pages might hang around a
460 * while longer before being reclaimed. That's actually good anyway, because
461 * the longer we delay reclaiming old pages, the more likely it is that a
462 * string of contiguous pages can be found after coalescing old pages from
463 * many old transactions together.
466 /** Number of slots in the reader table.
467 * This value was chosen somewhat arbitrarily. 126 readers plus a
468 * couple mutexes fit exactly into 8KB on my development machine.
469 * Applications should set the table size using #mdb_env_set_maxreaders().
471 #define DEFAULT_READERS 126
473 /** The size of a CPU cache line in bytes. We want our lock structures
474 * aligned to this size to avoid false cache line sharing in the
476 * This value works for most CPUs. For Itanium this should be 128.
482 /** The information we store in a single slot of the reader table.
483 * In addition to a transaction ID, we also record the process and
484 * thread ID that owns a slot, so that we can detect stale information,
485 * e.g. threads or processes that went away without cleaning up.
486 * @note We currently don't check for stale records. We simply re-init
487 * the table when we know that we're the only process opening the
490 typedef struct MDB_rxbody {
491 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
492 * Multiple readers that start at the same time will probably have the
493 * same ID here. Again, it's not important to exclude them from
494 * anything; all we need to know is which version of the DB they
495 * started from so we can avoid overwriting any data used in that
496 * particular version.
499 /** The process ID of the process owning this reader txn. */
501 /** The thread ID of the thread owning this txn. */
505 /** The actual reader record, with cacheline padding. */
506 typedef struct MDB_reader {
509 /** shorthand for mrb_txnid */
510 #define mr_txnid mru.mrx.mrb_txnid
511 #define mr_pid mru.mrx.mrb_pid
512 #define mr_tid mru.mrx.mrb_tid
513 /** cache line alignment */
514 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
518 /** The header for the reader table.
519 * The table resides in a memory-mapped file. (This is a different file
520 * than is used for the main database.)
522 * For POSIX the actual mutexes reside in the shared memory of this
523 * mapped file. On Windows, mutexes are named objects allocated by the
524 * kernel; we store the mutex names in this mapped file so that other
525 * processes can grab them. This same approach is also used on
526 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
527 * process-shared POSIX mutexes. For these cases where a named object
528 * is used, the object name is derived from a 64 bit FNV hash of the
529 * environment pathname. As such, naming collisions are extremely
530 * unlikely. If a collision occurs, the results are unpredictable.
532 typedef struct MDB_txbody {
533 /** Stamp identifying this as an MDB file. It must be set
536 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
538 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
539 char mtb_rmname[MNAME_LEN];
541 /** Mutex protecting access to this table.
542 * This is the reader lock that #LOCK_MUTEX_R acquires.
544 pthread_mutex_t mtb_mutex;
546 /** The ID of the last transaction committed to the database.
547 * This is recorded here only for convenience; the value can always
548 * be determined by reading the main database meta pages.
551 /** The number of slots that have been used in the reader table.
552 * This always records the maximum count, it is not decremented
553 * when readers release their slots.
555 unsigned mtb_numreaders;
558 /** The actual reader table definition. */
559 typedef struct MDB_txninfo {
562 #define mti_magic mt1.mtb.mtb_magic
563 #define mti_format mt1.mtb.mtb_format
564 #define mti_mutex mt1.mtb.mtb_mutex
565 #define mti_rmname mt1.mtb.mtb_rmname
566 #define mti_txnid mt1.mtb.mtb_txnid
567 #define mti_numreaders mt1.mtb.mtb_numreaders
568 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
571 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
572 char mt2_wmname[MNAME_LEN];
573 #define mti_wmname mt2.mt2_wmname
575 pthread_mutex_t mt2_wmutex;
576 #define mti_wmutex mt2.mt2_wmutex
578 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
580 MDB_reader mti_readers[1];
583 /** Lockfile format signature: version, features and field layout */
584 #define MDB_LOCK_FORMAT \
586 ((MDB_LOCK_VERSION) \
587 /* Flags which describe functionality */ \
588 + (((MDB_PIDLOCK) != 0) << 16)))
591 /** Common header for all page types.
592 * Overflow records occupy a number of contiguous pages with no
593 * headers on any page after the first.
595 typedef struct MDB_page {
596 #define mp_pgno mp_p.p_pgno
597 #define mp_next mp_p.p_next
599 pgno_t p_pgno; /**< page number */
600 void * p_next; /**< for in-memory list of freed structs */
603 /** @defgroup mdb_page Page Flags
605 * Flags for the page headers.
608 #define P_BRANCH 0x01 /**< branch page */
609 #define P_LEAF 0x02 /**< leaf page */
610 #define P_OVERFLOW 0x04 /**< overflow page */
611 #define P_META 0x08 /**< meta page */
612 #define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
613 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
614 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
615 #define P_KEEP 0x8000 /**< leave this page alone during spill */
617 uint16_t mp_flags; /**< @ref mdb_page */
618 #define mp_lower mp_pb.pb.pb_lower
619 #define mp_upper mp_pb.pb.pb_upper
620 #define mp_pages mp_pb.pb_pages
623 indx_t pb_lower; /**< lower bound of free space */
624 indx_t pb_upper; /**< upper bound of free space */
626 uint32_t pb_pages; /**< number of overflow pages */
628 indx_t mp_ptrs[1]; /**< dynamic size */
631 /** Size of the page header, excluding dynamic data at the end */
632 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
634 /** Address of first usable data byte in a page, after the header */
635 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
637 /** Number of nodes on a page */
638 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
640 /** The amount of space remaining in the page */
641 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
643 /** The percentage of space used in the page, in tenths of a percent. */
644 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
645 ((env)->me_psize - PAGEHDRSZ))
646 /** The minimum page fill factor, in tenths of a percent.
647 * Pages emptier than this are candidates for merging.
649 #define FILL_THRESHOLD 250
651 /** Test if a page is a leaf page */
652 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
653 /** Test if a page is a LEAF2 page */
654 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
655 /** Test if a page is a branch page */
656 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
657 /** Test if a page is an overflow page */
658 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
659 /** Test if a page is a sub page */
660 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
662 /** The number of overflow pages needed to store the given size. */
663 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
665 /** Header for a single key/data pair within a page.
666 * We guarantee 2-byte alignment for nodes.
668 typedef struct MDB_node {
669 /** lo and hi are used for data size on leaf nodes and for
670 * child pgno on branch nodes. On 64 bit platforms, flags
671 * is also used for pgno. (Branch nodes have no flags).
672 * They are in host byte order in case that lets some
673 * accesses be optimized into a 32-bit word access.
675 #define mn_lo mn_offset[BYTE_ORDER!=LITTLE_ENDIAN]
676 #define mn_hi mn_offset[BYTE_ORDER==LITTLE_ENDIAN] /**< part of dsize or pgno */
677 unsigned short mn_offset[2]; /**< storage for #mn_lo and #mn_hi */
678 /** @defgroup mdb_node Node Flags
680 * Flags for node headers.
683 #define F_BIGDATA 0x01 /**< data put on overflow page */
684 #define F_SUBDATA 0x02 /**< data is a sub-database */
685 #define F_DUPDATA 0x04 /**< data has duplicates */
687 /** valid flags for #mdb_node_add() */
688 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
691 unsigned short mn_flags; /**< @ref mdb_node */
692 unsigned short mn_ksize; /**< key size */
693 char mn_data[1]; /**< key and data are appended here */
696 /** Size of the node header, excluding dynamic data at the end */
697 #define NODESIZE offsetof(MDB_node, mn_data)
699 /** Bit position of top word in page number, for shifting mn_flags */
700 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
702 /** Size of a node in a branch page with a given key.
703 * This is just the node header plus the key, there is no data.
705 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
707 /** Size of a node in a leaf page with a given key and data.
708 * This is node header plus key plus data size.
710 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
712 /** Address of node \b i in page \b p */
713 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
715 /** Address of the key for the node */
716 #define NODEKEY(node) (void *)((node)->mn_data)
718 /** Address of the data for a node */
719 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
721 /** Get the page number pointed to by a branch node */
722 #define NODEPGNO(node) \
723 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
724 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
725 /** Set the page number in a branch node */
726 #define SETPGNO(node,pgno) do { \
727 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
728 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
730 /** Get the size of the data in a leaf node */
731 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
732 /** Set the size of the data for a leaf node */
733 #define SETDSZ(node,size) do { \
734 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
735 /** The size of a key in a node */
736 #define NODEKSZ(node) ((node)->mn_ksize)
738 /** Copy a page number from src to dst */
740 #define COPY_PGNO(dst,src) dst = src
742 #if SIZE_MAX > 4294967295UL
743 #define COPY_PGNO(dst,src) do { \
744 unsigned short *s, *d; \
745 s = (unsigned short *)&(src); \
746 d = (unsigned short *)&(dst); \
753 #define COPY_PGNO(dst,src) do { \
754 unsigned short *s, *d; \
755 s = (unsigned short *)&(src); \
756 d = (unsigned short *)&(dst); \
762 /** The address of a key in a LEAF2 page.
763 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
764 * There are no node headers, keys are stored contiguously.
766 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
768 /** Set the \b node's key into \b keyptr, if requested. */
769 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
770 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
772 /** Set the \b node's key into \b key. */
773 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
775 /** Information about a single database in the environment. */
776 typedef struct MDB_db {
777 uint32_t md_pad; /**< also ksize for LEAF2 pages */
778 uint16_t md_flags; /**< @ref mdb_dbi_open */
779 uint16_t md_depth; /**< depth of this tree */
780 pgno_t md_branch_pages; /**< number of internal pages */
781 pgno_t md_leaf_pages; /**< number of leaf pages */
782 pgno_t md_overflow_pages; /**< number of overflow pages */
783 size_t md_entries; /**< number of data items */
784 pgno_t md_root; /**< the root page of this tree */
787 /** mdb_dbi_open flags */
788 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
789 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
790 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
791 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
793 /** Handle for the DB used to track free pages. */
795 /** Handle for the default DB. */
798 /** Meta page content.
799 * A meta page is the start point for accessing a database snapshot.
800 * Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
802 typedef struct MDB_meta {
803 /** Stamp identifying this as an MDB file. It must be set
806 /** Version number of this lock file. Must be set to #MDB_DATA_VERSION. */
808 void *mm_address; /**< address for fixed mapping */
809 size_t mm_mapsize; /**< size of mmap region */
810 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
811 /** The size of pages used in this DB */
812 #define mm_psize mm_dbs[0].md_pad
813 /** Any persistent environment flags. @ref mdb_env */
814 #define mm_flags mm_dbs[0].md_flags
815 pgno_t mm_last_pg; /**< last used page in file */
816 txnid_t mm_txnid; /**< txnid that committed this page */
819 /** Buffer for a stack-allocated meta page.
820 * The members define size and alignment, and silence type
821 * aliasing warnings. They are not used directly; that could
822 * mean incorrectly using several union members in parallel.
824 typedef union MDB_metabuf {
827 char mm_pad[PAGEHDRSZ];
832 /** Auxiliary DB info.
833 * The information here is mostly static/read-only. There is
834 * only a single copy of this record in the environment.
836 typedef struct MDB_dbx {
837 MDB_val md_name; /**< name of the database */
838 MDB_cmp_func *md_cmp; /**< function for comparing keys */
839 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
840 MDB_rel_func *md_rel; /**< user relocate function */
841 void *md_relctx; /**< user-provided context for md_rel */
844 /** A database transaction.
845 * Every operation requires a transaction handle.
848 MDB_txn *mt_parent; /**< parent of a nested txn */
849 MDB_txn *mt_child; /**< nested txn under this txn */
850 pgno_t mt_next_pgno; /**< next unallocated page */
851 /** The ID of this transaction. IDs are integers incrementing from 1.
852 * Only committed write transactions increment the ID. If a transaction
853 * aborts, the ID may be re-used by the next writer.
856 MDB_env *mt_env; /**< the DB environment */
857 /** The list of pages that became unused during this transaction.
860 /** The sorted list of dirty pages we temporarily wrote to disk
861 * because the dirty list was full. page numbers in here are
862 * shifted left by 1, deleted slots have the LSB set.
864 MDB_IDL mt_spill_pgs;
866 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
868 /** For read txns: This thread/txn's reader table slot, or NULL. */
871 /** Array of records for each DB known in the environment. */
873 /** Array of MDB_db records for each known DB */
875 /** @defgroup mt_dbflag Transaction DB Flags
879 #define DB_DIRTY 0x01 /**< DB was modified or is DUPSORT data */
880 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
881 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
882 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
884 /** In write txns, array of cursors for each DB */
885 MDB_cursor **mt_cursors;
886 /** Array of flags for each DB */
887 unsigned char *mt_dbflags;
888 /** Number of DB records in use. This number only ever increments;
889 * we don't decrement it when individual DB handles are closed.
893 /** @defgroup mdb_txn Transaction Flags
897 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
898 #define MDB_TXN_ERROR 0x02 /**< an error has occurred */
899 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
900 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
902 unsigned int mt_flags; /**< @ref mdb_txn */
903 /** dirty_list room: Array size - #dirty pages visible to this txn.
904 * Includes ancestor txns' dirty pages not hidden by other txns'
905 * dirty/spilled pages. Thus commit(nested txn) has room to merge
906 * dirty_list into mt_parent after freeing hidden mt_parent pages.
908 unsigned int mt_dirty_room;
911 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
912 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
913 * raise this on a 64 bit machine.
915 #define CURSOR_STACK 32
919 /** Cursors are used for all DB operations.
920 * A cursor holds a path of (page pointer, key index) from the DB
921 * root to a position in the DB, plus other state. #MDB_DUPSORT
922 * cursors include an xcursor to the current data item. Write txns
923 * track their cursors and keep them up to date when data moves.
924 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
925 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
928 /** Next cursor on this DB in this txn */
930 /** Backup of the original cursor if this cursor is a shadow */
931 MDB_cursor *mc_backup;
932 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
933 struct MDB_xcursor *mc_xcursor;
934 /** The transaction that owns this cursor */
936 /** The database handle this cursor operates on */
938 /** The database record for this cursor */
940 /** The database auxiliary record for this cursor */
942 /** The @ref mt_dbflag for this database */
943 unsigned char *mc_dbflag;
944 unsigned short mc_snum; /**< number of pushed pages */
945 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
946 /** @defgroup mdb_cursor Cursor Flags
948 * Cursor state flags.
951 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
952 #define C_EOF 0x02 /**< No more data */
953 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
954 #define C_DEL 0x08 /**< last op was a cursor_del */
955 #define C_SPLITTING 0x20 /**< Cursor is in page_split */
956 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
958 unsigned int mc_flags; /**< @ref mdb_cursor */
959 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
960 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
963 /** Context for sorted-dup records.
964 * We could have gone to a fully recursive design, with arbitrarily
965 * deep nesting of sub-databases. But for now we only handle these
966 * levels - main DB, optional sub-DB, sorted-duplicate DB.
968 typedef struct MDB_xcursor {
969 /** A sub-cursor for traversing the Dup DB */
970 MDB_cursor mx_cursor;
971 /** The database record for this Dup DB */
973 /** The auxiliary DB record for this Dup DB */
975 /** The @ref mt_dbflag for this Dup DB */
976 unsigned char mx_dbflag;
979 /** State of FreeDB old pages, stored in the MDB_env */
980 typedef struct MDB_pgstate {
981 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
982 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
985 /** The database environment. */
987 HANDLE me_fd; /**< The main data file */
988 HANDLE me_lfd; /**< The lock file */
989 HANDLE me_mfd; /**< just for writing the meta pages */
990 /** Failed to update the meta page. Probably an I/O error. */
991 #define MDB_FATAL_ERROR 0x80000000U
992 /** Some fields are initialized. */
993 #define MDB_ENV_ACTIVE 0x20000000U
994 /** me_txkey is set */
995 #define MDB_ENV_TXKEY 0x10000000U
996 /** Have liveness lock in reader table */
997 #define MDB_LIVE_READER 0x08000000U
998 uint32_t me_flags; /**< @ref mdb_env */
999 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1000 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1001 unsigned int me_maxreaders; /**< size of the reader table */
1002 unsigned int me_numreaders; /**< max numreaders set by this env */
1003 MDB_dbi me_numdbs; /**< number of DBs opened */
1004 MDB_dbi me_maxdbs; /**< size of the DB table */
1005 pid_t me_pid; /**< process ID of this env */
1006 char *me_path; /**< path to the DB files */
1007 char *me_map; /**< the memory map of the data file */
1008 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1009 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
1010 void *me_pbuf; /**< scratch area for DUPSORT put() */
1011 MDB_txn *me_txn; /**< current write transaction */
1012 size_t me_mapsize; /**< size of the data memory map */
1013 off_t me_size; /**< current file size */
1014 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1015 MDB_dbx *me_dbxs; /**< array of static DB info */
1016 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1017 pthread_key_t me_txkey; /**< thread-key for readers */
1018 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1019 # define me_pglast me_pgstate.mf_pglast
1020 # define me_pghead me_pgstate.mf_pghead
1021 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1022 /** IDL of pages that became unused in a write txn */
1023 MDB_IDL me_free_pgs;
1024 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1025 MDB_ID2L me_dirty_list;
1026 /** Max number of freelist items that can fit in a single overflow page */
1028 /** Max size of a node on a page */
1029 unsigned int me_nodemax;
1031 int me_pidquery; /**< Used in OpenProcess */
1032 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
1034 #elif defined(MDB_USE_POSIX_SEM)
1035 sem_t *me_rmutex; /* Shared mutexes are not supported */
1040 /** Nested transaction */
1041 typedef struct MDB_ntxn {
1042 MDB_txn mnt_txn; /**< the transaction */
1043 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1046 /** max number of pages to commit in one writev() call */
1047 #define MDB_COMMIT_PAGES 64
1048 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1049 #undef MDB_COMMIT_PAGES
1050 #define MDB_COMMIT_PAGES IOV_MAX
1053 /* max bytes to write in one call */
1054 #define MAX_WRITE (0x80000000U >> (sizeof(ssize_t) == 4))
1056 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1057 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1058 static int mdb_page_touch(MDB_cursor *mc);
1060 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp, int *lvl);
1061 static int mdb_page_search_root(MDB_cursor *mc,
1062 MDB_val *key, int modify);
1063 #define MDB_PS_MODIFY 1
1064 #define MDB_PS_ROOTONLY 2
1065 #define MDB_PS_FIRST 4
1066 #define MDB_PS_LAST 8
1067 static int mdb_page_search(MDB_cursor *mc,
1068 MDB_val *key, int flags);
1069 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1071 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1072 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1073 pgno_t newpgno, unsigned int nflags);
1075 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1076 static int mdb_env_pick_meta(const MDB_env *env);
1077 static int mdb_env_write_meta(MDB_txn *txn);
1078 #if !(defined(_WIN32) || defined(MDB_USE_POSIX_SEM)) /* Drop unused excl arg */
1079 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1081 static void mdb_env_close0(MDB_env *env, int excl);
1083 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1084 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1085 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1086 static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
1087 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1088 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
1089 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1090 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1091 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1093 static int mdb_rebalance(MDB_cursor *mc);
1094 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1096 static void mdb_cursor_pop(MDB_cursor *mc);
1097 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1099 static int mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
1100 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1101 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1102 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1103 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1105 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1106 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1108 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1109 static void mdb_xcursor_init0(MDB_cursor *mc);
1110 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1112 static int mdb_drop0(MDB_cursor *mc, int subs);
1113 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1116 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1120 static SECURITY_DESCRIPTOR mdb_null_sd;
1121 static SECURITY_ATTRIBUTES mdb_all_sa;
1122 static int mdb_sec_inited;
1125 /** Return the library version info. */
1127 mdb_version(int *major, int *minor, int *patch)
1129 if (major) *major = MDB_VERSION_MAJOR;
1130 if (minor) *minor = MDB_VERSION_MINOR;
1131 if (patch) *patch = MDB_VERSION_PATCH;
1132 return MDB_VERSION_STRING;
1135 /** Table of descriptions for MDB @ref errors */
1136 static char *const mdb_errstr[] = {
1137 "MDB_KEYEXIST: Key/data pair already exists",
1138 "MDB_NOTFOUND: No matching key/data pair found",
1139 "MDB_PAGE_NOTFOUND: Requested page not found",
1140 "MDB_CORRUPTED: Located page was wrong type",
1141 "MDB_PANIC: Update of meta page failed",
1142 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1143 "MDB_INVALID: File is not an MDB file",
1144 "MDB_MAP_FULL: Environment mapsize limit reached",
1145 "MDB_DBS_FULL: Environment maxdbs limit reached",
1146 "MDB_READERS_FULL: Environment maxreaders limit reached",
1147 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1148 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1149 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1150 "MDB_PAGE_FULL: Internal error - page has no more space",
1151 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1152 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1153 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1154 "MDB_BAD_TXN: Transaction cannot recover - it must be aborted",
1155 "MDB_BAD_VALSIZE: Too big key/data, key is empty, or wrong DUPFIXED size",
1159 mdb_strerror(int err)
1163 return ("Successful return: 0");
1165 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1166 i = err - MDB_KEYEXIST;
1167 return mdb_errstr[i];
1170 return strerror(err);
1174 /** Display a key in hexadecimal and return the address of the result.
1175 * @param[in] key the key to display
1176 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1177 * @return The key in hexadecimal form.
1180 mdb_dkey(MDB_val *key, char *buf)
1183 unsigned char *c = key->mv_data;
1189 if (key->mv_size > MDB_MAXKEYSIZE)
1190 return "MDB_MAXKEYSIZE";
1191 /* may want to make this a dynamic check: if the key is mostly
1192 * printable characters, print it as-is instead of converting to hex.
1196 for (i=0; i<key->mv_size; i++)
1197 ptr += sprintf(ptr, "%02x", *c++);
1199 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1204 /** Display all the keys in the page. */
1206 mdb_page_list(MDB_page *mp)
1209 unsigned int i, nkeys, nsize;
1213 nkeys = NUMKEYS(mp);
1214 fprintf(stderr, "Page %"Z"u numkeys %d\n", mp->mp_pgno, nkeys);
1215 for (i=0; i<nkeys; i++) {
1216 node = NODEPTR(mp, i);
1217 key.mv_size = node->mn_ksize;
1218 key.mv_data = node->mn_data;
1219 nsize = NODESIZE + NODEKSZ(node) + sizeof(indx_t);
1220 if (IS_BRANCH(mp)) {
1221 fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
1224 if (F_ISSET(node->mn_flags, F_BIGDATA))
1225 nsize += sizeof(pgno_t);
1227 nsize += NODEDSZ(node);
1228 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1234 mdb_cursor_chk(MDB_cursor *mc)
1240 if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1241 for (i=0; i<mc->mc_top; i++) {
1243 node = NODEPTR(mp, mc->mc_ki[i]);
1244 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1247 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1253 /** Count all the pages in each DB and in the freelist
1254 * and make sure it matches the actual number of pages
1257 static void mdb_audit(MDB_txn *txn)
1261 MDB_ID freecount, count;
1266 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1267 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1268 freecount += *(MDB_ID *)data.mv_data;
1271 for (i = 0; i<txn->mt_numdbs; i++) {
1273 mdb_cursor_init(&mc, txn, i, &mx);
1274 if (txn->mt_dbs[i].md_root == P_INVALID)
1276 count += txn->mt_dbs[i].md_branch_pages +
1277 txn->mt_dbs[i].md_leaf_pages +
1278 txn->mt_dbs[i].md_overflow_pages;
1279 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1280 mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1284 mp = mc.mc_pg[mc.mc_top];
1285 for (j=0; j<NUMKEYS(mp); j++) {
1286 MDB_node *leaf = NODEPTR(mp, j);
1287 if (leaf->mn_flags & F_SUBDATA) {
1289 memcpy(&db, NODEDATA(leaf), sizeof(db));
1290 count += db.md_branch_pages + db.md_leaf_pages +
1291 db.md_overflow_pages;
1295 while (mdb_cursor_sibling(&mc, 1) == 0);
1298 if (freecount + count + 2 /* metapages */ != txn->mt_next_pgno) {
1299 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1300 txn->mt_txnid, freecount, count+2, freecount+count+2, txn->mt_next_pgno);
1306 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1308 return txn->mt_dbxs[dbi].md_cmp(a, b);
1312 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1314 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1317 /** Allocate memory for a page.
1318 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1321 mdb_page_malloc(MDB_txn *txn, unsigned num)
1323 MDB_env *env = txn->mt_env;
1324 MDB_page *ret = env->me_dpages;
1325 size_t sz = env->me_psize;
1328 VGMEMP_ALLOC(env, ret, sz);
1329 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1330 env->me_dpages = ret->mp_next;
1336 if ((ret = malloc(sz)) != NULL) {
1337 VGMEMP_ALLOC(env, ret, sz);
1342 /** Free a single page.
1343 * Saves single pages to a list, for future reuse.
1344 * (This is not used for multi-page overflow pages.)
1347 mdb_page_free(MDB_env *env, MDB_page *mp)
1349 mp->mp_next = env->me_dpages;
1350 VGMEMP_FREE(env, mp);
1351 env->me_dpages = mp;
1354 /** Free a dirty page */
1356 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1358 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1359 mdb_page_free(env, dp);
1361 /* large pages just get freed directly */
1362 VGMEMP_FREE(env, dp);
1367 /** Return all dirty pages to dpage list */
1369 mdb_dlist_free(MDB_txn *txn)
1371 MDB_env *env = txn->mt_env;
1372 MDB_ID2L dl = txn->mt_u.dirty_list;
1373 unsigned i, n = dl[0].mid;
1375 for (i = 1; i <= n; i++) {
1376 mdb_dpage_free(env, dl[i].mptr);
1381 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
1382 * @param[in] mc A cursor handle for the current operation.
1383 * @param[in] pflags Flags of the pages to update:
1384 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1385 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
1386 * @return 0 on success, non-zero on failure.
1389 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
1391 enum { Mask = P_SUBP|P_DIRTY|P_KEEP };
1392 MDB_txn *txn = mc->mc_txn;
1398 int rc = MDB_SUCCESS, level;
1400 /* Mark pages seen by cursors */
1401 if (mc->mc_flags & C_UNTRACK)
1402 mc = NULL; /* will find mc in mt_cursors */
1403 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1404 for (; mc; mc=mc->mc_next) {
1405 if (!(mc->mc_flags & C_INITIALIZED))
1407 for (m3 = mc;; m3 = &mx->mx_cursor) {
1409 for (j=0; j<m3->mc_snum; j++) {
1411 if ((mp->mp_flags & Mask) == pflags)
1412 mp->mp_flags ^= P_KEEP;
1414 mx = m3->mc_xcursor;
1415 /* Proceed to mx if it is at a sub-database */
1416 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
1418 if (! (mp && (mp->mp_flags & P_LEAF)))
1420 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
1421 if (!(leaf->mn_flags & F_SUBDATA))
1430 /* Mark dirty root pages */
1431 for (i=0; i<txn->mt_numdbs; i++) {
1432 if (txn->mt_dbflags[i] & DB_DIRTY) {
1433 pgno_t pgno = txn->mt_dbs[i].md_root;
1434 if (pgno == P_INVALID)
1436 if ((rc = mdb_page_get(txn, pgno, &dp, &level)) != MDB_SUCCESS)
1438 if ((dp->mp_flags & Mask) == pflags && level <= 1)
1439 dp->mp_flags ^= P_KEEP;
1447 static int mdb_page_flush(MDB_txn *txn, int keep);
1449 /** Spill pages from the dirty list back to disk.
1450 * This is intended to prevent running into #MDB_TXN_FULL situations,
1451 * but note that they may still occur in a few cases:
1452 * 1) our estimate of the txn size could be too small. Currently this
1453 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
1454 * 2) child txns may run out of space if their parents dirtied a
1455 * lot of pages and never spilled them. TODO: we probably should do
1456 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1457 * the parent's dirty_room is below a given threshold.
1459 * Otherwise, if not using nested txns, it is expected that apps will
1460 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1461 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1462 * If the txn never references them again, they can be left alone.
1463 * If the txn only reads them, they can be used without any fuss.
1464 * If the txn writes them again, they can be dirtied immediately without
1465 * going thru all of the work of #mdb_page_touch(). Such references are
1466 * handled by #mdb_page_unspill().
1468 * Also note, we never spill DB root pages, nor pages of active cursors,
1469 * because we'll need these back again soon anyway. And in nested txns,
1470 * we can't spill a page in a child txn if it was already spilled in a
1471 * parent txn. That would alter the parent txns' data even though
1472 * the child hasn't committed yet, and we'd have no way to undo it if
1473 * the child aborted.
1475 * @param[in] m0 cursor A cursor handle identifying the transaction and
1476 * database for which we are checking space.
1477 * @param[in] key For a put operation, the key being stored.
1478 * @param[in] data For a put operation, the data being stored.
1479 * @return 0 on success, non-zero on failure.
1482 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1484 MDB_txn *txn = m0->mc_txn;
1486 MDB_ID2L dl = txn->mt_u.dirty_list;
1487 unsigned int i, j, need;
1490 if (m0->mc_flags & C_SUB)
1493 /* Estimate how much space this op will take */
1494 i = m0->mc_db->md_depth;
1495 /* Named DBs also dirty the main DB */
1496 if (m0->mc_dbi > MAIN_DBI)
1497 i += txn->mt_dbs[MAIN_DBI].md_depth;
1498 /* For puts, roughly factor in the key+data size */
1500 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
1501 i += i; /* double it for good measure */
1504 if (txn->mt_dirty_room > i)
1507 if (!txn->mt_spill_pgs) {
1508 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
1509 if (!txn->mt_spill_pgs)
1512 /* purge deleted slots */
1513 MDB_IDL sl = txn->mt_spill_pgs;
1514 unsigned int num = sl[0];
1516 for (i=1; i<=num; i++) {
1523 /* Preserve pages which may soon be dirtied again */
1524 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
1527 /* Less aggressive spill - we originally spilled the entire dirty list,
1528 * with a few exceptions for cursor pages and DB root pages. But this
1529 * turns out to be a lot of wasted effort because in a large txn many
1530 * of those pages will need to be used again. So now we spill only 1/8th
1531 * of the dirty pages. Testing revealed this to be a good tradeoff,
1532 * better than 1/2, 1/4, or 1/10.
1534 if (need < MDB_IDL_UM_MAX / 8)
1535 need = MDB_IDL_UM_MAX / 8;
1537 /* Save the page IDs of all the pages we're flushing */
1538 /* flush from the tail forward, this saves a lot of shifting later on. */
1539 for (i=dl[0].mid; i && need; i--) {
1540 MDB_ID pn = dl[i].mid << 1;
1542 if (dp->mp_flags & P_KEEP)
1544 /* Can't spill twice, make sure it's not already in a parent's
1547 if (txn->mt_parent) {
1549 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1550 if (tx2->mt_spill_pgs) {
1551 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
1552 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
1553 dp->mp_flags |= P_KEEP;
1561 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
1565 mdb_midl_sort(txn->mt_spill_pgs);
1567 /* Flush the spilled part of dirty list */
1568 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
1571 /* Reset any dirty pages we kept that page_flush didn't see */
1572 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
1575 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
1579 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
1581 mdb_find_oldest(MDB_txn *txn)
1584 txnid_t mr, oldest = txn->mt_txnid - 1;
1585 if (txn->mt_env->me_txns) {
1586 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
1587 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
1598 /** Add a page to the txn's dirty list */
1600 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
1603 int (*insert)(MDB_ID2L, MDB_ID2 *);
1605 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1606 insert = mdb_mid2l_append;
1608 insert = mdb_mid2l_insert;
1610 mid.mid = mp->mp_pgno;
1612 insert(txn->mt_u.dirty_list, &mid);
1613 txn->mt_dirty_room--;
1616 /** Allocate page numbers and memory for writing. Maintain me_pglast,
1617 * me_pghead and mt_next_pgno.
1619 * If there are free pages available from older transactions, they
1620 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
1621 * Do not modify the freedB, just merge freeDB records into me_pghead[]
1622 * and move me_pglast to say which records were consumed. Only this
1623 * function can create me_pghead and move me_pglast/mt_next_pgno.
1624 * @param[in] mc cursor A cursor handle identifying the transaction and
1625 * database for which we are allocating.
1626 * @param[in] num the number of pages to allocate.
1627 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
1628 * will always be satisfied by a single contiguous chunk of memory.
1629 * @return 0 on success, non-zero on failure.
1632 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
1634 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
1635 /* Get at most <Max_retries> more freeDB records once me_pghead
1636 * has enough pages. If not enough, use new pages from the map.
1637 * If <Paranoid> and mc is updating the freeDB, only get new
1638 * records if me_pghead is empty. Then the freelist cannot play
1639 * catch-up with itself by growing while trying to save it.
1641 enum { Paranoid = 1, Max_retries = 500 };
1643 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
1645 int rc, n2 = num-1, retry = Max_retries;
1646 MDB_txn *txn = mc->mc_txn;
1647 MDB_env *env = txn->mt_env;
1648 pgno_t pgno, *mop = env->me_pghead;
1649 unsigned i, j, k, mop_len = mop ? mop[0] : 0;
1651 txnid_t oldest = 0, last;
1657 /* If our dirty list is already full, we can't do anything */
1658 if (txn->mt_dirty_room == 0)
1659 return MDB_TXN_FULL;
1661 for (op = MDB_FIRST;; op = MDB_NEXT) {
1664 pgno_t *idl, old_id, new_id;
1666 /* Seek a big enough contiguous page range. Prefer
1667 * pages at the tail, just truncating the list.
1669 if (mop_len >= (unsigned)num) {
1673 if (mop[i-n2] == pgno+n2)
1675 } while (--i >= (unsigned)num);
1676 if (Max_retries < INT_MAX && --retry < 0)
1680 if (op == MDB_FIRST) { /* 1st iteration */
1681 /* Prepare to fetch more and coalesce */
1682 oldest = mdb_find_oldest(txn);
1683 last = env->me_pglast;
1684 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1687 key.mv_data = &last; /* will look up last+1 */
1688 key.mv_size = sizeof(last);
1690 if (Paranoid && mc->mc_dbi == FREE_DBI)
1693 if (Paranoid && retry < 0 && mop_len)
1697 /* Do not fetch more if the record will be too recent */
1700 rc = mdb_cursor_get(&m2, &key, NULL, op);
1702 if (rc == MDB_NOTFOUND)
1706 last = *(txnid_t*)key.mv_data;
1709 np = m2.mc_pg[m2.mc_top];
1710 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
1711 if ((rc = mdb_node_read(txn, leaf, &data)) != MDB_SUCCESS)
1714 idl = (MDB_ID *) data.mv_data;
1717 if (!(env->me_pghead = mop = mdb_midl_alloc(i)))
1720 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
1722 mop = env->me_pghead;
1724 env->me_pglast = last;
1726 DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
1727 last, txn->mt_dbs[FREE_DBI].md_root, i));
1729 DPRINTF(("IDL %"Z"u", idl[k]));
1731 /* Merge in descending sorted order */
1734 mop[0] = (pgno_t)-1;
1738 for (; old_id < new_id; old_id = mop[--j])
1745 /* Use new pages from the map when nothing suitable in the freeDB */
1747 pgno = txn->mt_next_pgno;
1748 if (pgno + num >= env->me_maxpg) {
1749 DPUTS("DB size maxed out");
1750 return MDB_MAP_FULL;
1754 if (env->me_flags & MDB_WRITEMAP) {
1755 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
1757 if (!(np = mdb_page_malloc(txn, num)))
1761 mop[0] = mop_len -= num;
1762 /* Move any stragglers down */
1763 for (j = i-num; j < mop_len; )
1764 mop[++j] = mop[++i];
1766 txn->mt_next_pgno = pgno + num;
1769 mdb_page_dirty(txn, np);
1775 /** Copy the used portions of a non-overflow page.
1776 * @param[in] dst page to copy into
1777 * @param[in] src page to copy from
1778 * @param[in] psize size of a page
1781 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
1783 enum { Align = sizeof(pgno_t) };
1784 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
1786 /* If page isn't full, just copy the used portion. Adjust
1787 * alignment so memcpy may copy words instead of bytes.
1789 if ((unused &= -Align) && !IS_LEAF2(src)) {
1791 memcpy(dst, src, (lower + (Align-1)) & -Align);
1792 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
1795 memcpy(dst, src, psize - unused);
1799 /** Pull a page off the txn's spill list, if present.
1800 * If a page being referenced was spilled to disk in this txn, bring
1801 * it back and make it dirty/writable again.
1802 * @param[in] txn the transaction handle.
1803 * @param[in] mp the page being referenced.
1804 * @param[out] ret the writable page, if any. ret is unchanged if
1805 * mp wasn't spilled.
1808 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
1810 MDB_env *env = txn->mt_env;
1813 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
1815 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
1816 if (!tx2->mt_spill_pgs)
1818 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
1819 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
1822 if (txn->mt_dirty_room == 0)
1823 return MDB_TXN_FULL;
1824 if (IS_OVERFLOW(mp))
1828 if (env->me_flags & MDB_WRITEMAP) {
1831 np = mdb_page_malloc(txn, num);
1835 memcpy(np, mp, num * env->me_psize);
1837 mdb_page_copy(np, mp, env->me_psize);
1840 /* If in current txn, this page is no longer spilled.
1841 * If it happens to be the last page, truncate the spill list.
1842 * Otherwise mark it as deleted by setting the LSB.
1844 if (x == txn->mt_spill_pgs[0])
1845 txn->mt_spill_pgs[0]--;
1847 txn->mt_spill_pgs[x] |= 1;
1848 } /* otherwise, if belonging to a parent txn, the
1849 * page remains spilled until child commits
1852 mdb_page_dirty(txn, np);
1853 np->mp_flags |= P_DIRTY;
1861 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1862 * @param[in] mc cursor pointing to the page to be touched
1863 * @return 0 on success, non-zero on failure.
1866 mdb_page_touch(MDB_cursor *mc)
1868 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
1869 MDB_txn *txn = mc->mc_txn;
1870 MDB_cursor *m2, *m3;
1874 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1875 if (txn->mt_flags & MDB_TXN_SPILLS) {
1877 rc = mdb_page_unspill(txn, mp, &np);
1883 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
1884 (rc = mdb_page_alloc(mc, 1, &np)))
1887 DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
1888 mp->mp_pgno, pgno));
1889 assert(mp->mp_pgno != pgno);
1890 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
1891 /* Update the parent page, if any, to point to the new page */
1893 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
1894 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
1895 SETPGNO(node, pgno);
1897 mc->mc_db->md_root = pgno;
1899 } else if (txn->mt_parent && !IS_SUBP(mp)) {
1900 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
1902 /* If txn has a parent, make sure the page is in our
1906 unsigned x = mdb_mid2l_search(dl, pgno);
1907 if (x <= dl[0].mid && dl[x].mid == pgno) {
1908 if (mp != dl[x].mptr) { /* bad cursor? */
1909 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1910 return MDB_CORRUPTED;
1915 assert(dl[0].mid < MDB_IDL_UM_MAX);
1917 np = mdb_page_malloc(txn, 1);
1922 mdb_mid2l_insert(dl, &mid);
1927 mdb_page_copy(np, mp, txn->mt_env->me_psize);
1929 np->mp_flags |= P_DIRTY;
1932 /* Adjust cursors pointing to mp */
1933 mc->mc_pg[mc->mc_top] = np;
1934 m2 = txn->mt_cursors[mc->mc_dbi];
1935 if (mc->mc_flags & C_SUB) {
1936 for (; m2; m2=m2->mc_next) {
1937 m3 = &m2->mc_xcursor->mx_cursor;
1938 if (m3->mc_snum < mc->mc_snum) continue;
1939 if (m3->mc_pg[mc->mc_top] == mp)
1940 m3->mc_pg[mc->mc_top] = np;
1943 for (; m2; m2=m2->mc_next) {
1944 if (m2->mc_snum < mc->mc_snum) continue;
1945 if (m2->mc_pg[mc->mc_top] == mp) {
1946 m2->mc_pg[mc->mc_top] = np;
1947 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
1948 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
1950 MDB_node *leaf = NODEPTR(np, mc->mc_ki[mc->mc_top]);
1951 if (!(leaf->mn_flags & F_SUBDATA))
1952 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
1961 mdb_env_sync(MDB_env *env, int force)
1964 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1965 if (env->me_flags & MDB_WRITEMAP) {
1966 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
1967 ? MS_ASYNC : MS_SYNC;
1968 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
1971 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
1975 if (MDB_FDATASYNC(env->me_fd))
1982 /** Back up parent txn's cursors, then grab the originals for tracking */
1984 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
1986 MDB_cursor *mc, *bk;
1991 for (i = src->mt_numdbs; --i >= 0; ) {
1992 if ((mc = src->mt_cursors[i]) != NULL) {
1993 size = sizeof(MDB_cursor);
1995 size += sizeof(MDB_xcursor);
1996 for (; mc; mc = bk->mc_next) {
2002 mc->mc_db = &dst->mt_dbs[i];
2003 /* Kill pointers into src - and dst to reduce abuse: The
2004 * user may not use mc until dst ends. Otherwise we'd...
2006 mc->mc_txn = NULL; /* ...set this to dst */
2007 mc->mc_dbflag = NULL; /* ...and &dst->mt_dbflags[i] */
2008 if ((mx = mc->mc_xcursor) != NULL) {
2009 *(MDB_xcursor *)(bk+1) = *mx;
2010 mx->mx_cursor.mc_txn = NULL; /* ...and dst. */
2012 mc->mc_next = dst->mt_cursors[i];
2013 dst->mt_cursors[i] = mc;
2020 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2021 * @param[in] txn the transaction handle.
2022 * @param[in] merge true to keep changes to parent cursors, false to revert.
2023 * @return 0 on success, non-zero on failure.
2026 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2028 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2032 for (i = txn->mt_numdbs; --i >= 0; ) {
2033 for (mc = cursors[i]; mc; mc = next) {
2035 if ((bk = mc->mc_backup) != NULL) {
2037 /* Commit changes to parent txn */
2038 mc->mc_next = bk->mc_next;
2039 mc->mc_backup = bk->mc_backup;
2040 mc->mc_txn = bk->mc_txn;
2041 mc->mc_db = bk->mc_db;
2042 mc->mc_dbflag = bk->mc_dbflag;
2043 if ((mx = mc->mc_xcursor) != NULL)
2044 mx->mx_cursor.mc_txn = bk->mc_txn;
2046 /* Abort nested txn */
2048 if ((mx = mc->mc_xcursor) != NULL)
2049 *mx = *(MDB_xcursor *)(bk+1);
2053 /* Only malloced cursors are permanently tracked. */
2061 #define mdb_txn_reset0(txn, act) mdb_txn_reset0(txn)
2064 mdb_txn_reset0(MDB_txn *txn, const char *act);
2066 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2072 Pidset = F_SETLK, Pidcheck = F_GETLK
2076 /** Set or check a pid lock. Set returns 0 on success.
2077 * Check returns 0 if the process is certainly dead, nonzero if it may
2078 * be alive (the lock exists or an error happened so we do not know).
2080 * On Windows Pidset is a no-op, we merely check for the existence
2081 * of the process with the given pid. On POSIX we use a single byte
2082 * lock on the lockfile, set at an offset equal to the pid.
2085 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, pid_t pid)
2087 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2090 if (op == Pidcheck) {
2091 h = OpenProcess(env->me_pidquery, FALSE, pid);
2092 /* No documented "no such process" code, but other program use this: */
2094 return ErrCode() != ERROR_INVALID_PARAMETER;
2095 /* A process exists until all handles to it close. Has it exited? */
2096 ret = WaitForSingleObject(h, 0) != 0;
2103 struct flock lock_info;
2104 memset(&lock_info, 0, sizeof(lock_info));
2105 lock_info.l_type = F_WRLCK;
2106 lock_info.l_whence = SEEK_SET;
2107 lock_info.l_start = pid;
2108 lock_info.l_len = 1;
2109 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2110 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2112 } else if ((rc = ErrCode()) == EINTR) {
2120 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2121 * @param[in] txn the transaction handle to initialize
2122 * @return 0 on success, non-zero on failure.
2125 mdb_txn_renew0(MDB_txn *txn)
2127 MDB_env *env = txn->mt_env;
2128 MDB_txninfo *ti = env->me_txns;
2132 int rc, new_notls = 0;
2135 txn->mt_numdbs = env->me_numdbs;
2136 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
2138 if (txn->mt_flags & MDB_TXN_RDONLY) {
2140 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2141 txn->mt_txnid = meta->mm_txnid;
2142 txn->mt_u.reader = NULL;
2144 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2145 pthread_getspecific(env->me_txkey);
2147 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2148 return MDB_BAD_RSLOT;
2150 pid_t pid = env->me_pid;
2151 pthread_t tid = pthread_self();
2153 if (!(env->me_flags & MDB_LIVE_READER)) {
2154 rc = mdb_reader_pid(env, Pidset, pid);
2156 UNLOCK_MUTEX_R(env);
2159 env->me_flags |= MDB_LIVE_READER;
2163 nr = ti->mti_numreaders;
2164 for (i=0; i<nr; i++)
2165 if (ti->mti_readers[i].mr_pid == 0)
2167 if (i == env->me_maxreaders) {
2168 UNLOCK_MUTEX_R(env);
2169 return MDB_READERS_FULL;
2171 ti->mti_readers[i].mr_pid = pid;
2172 ti->mti_readers[i].mr_tid = tid;
2174 ti->mti_numreaders = ++nr;
2175 /* Save numreaders for un-mutexed mdb_env_close() */
2176 env->me_numreaders = nr;
2177 UNLOCK_MUTEX_R(env);
2179 r = &ti->mti_readers[i];
2180 new_notls = (env->me_flags & MDB_NOTLS);
2181 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2186 txn->mt_txnid = r->mr_txnid = ti->mti_txnid;
2187 txn->mt_u.reader = r;
2188 meta = env->me_metas[txn->mt_txnid & 1];
2194 txn->mt_txnid = ti->mti_txnid;
2195 meta = env->me_metas[txn->mt_txnid & 1];
2197 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2198 txn->mt_txnid = meta->mm_txnid;
2202 if (txn->mt_txnid == mdb_debug_start)
2205 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2206 txn->mt_u.dirty_list = env->me_dirty_list;
2207 txn->mt_u.dirty_list[0].mid = 0;
2208 txn->mt_free_pgs = env->me_free_pgs;
2209 txn->mt_free_pgs[0] = 0;
2210 txn->mt_spill_pgs = NULL;
2214 /* Copy the DB info and flags */
2215 memcpy(txn->mt_dbs, meta->mm_dbs, 2 * sizeof(MDB_db));
2217 /* Moved to here to avoid a data race in read TXNs */
2218 txn->mt_next_pgno = meta->mm_last_pg+1;
2220 for (i=2; i<txn->mt_numdbs; i++) {
2221 x = env->me_dbflags[i];
2222 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2223 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_STALE : 0;
2225 txn->mt_dbflags[0] = txn->mt_dbflags[1] = DB_VALID;
2227 if (env->me_maxpg < txn->mt_next_pgno) {
2228 mdb_txn_reset0(txn, "renew0-mapfail");
2230 txn->mt_u.reader->mr_pid = 0;
2231 txn->mt_u.reader = NULL;
2233 return MDB_MAP_RESIZED;
2240 mdb_txn_renew(MDB_txn *txn)
2244 if (!txn || txn->mt_dbxs) /* A reset txn has mt_dbxs==NULL */
2247 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
2248 DPUTS("environment had fatal error, must shutdown!");
2252 rc = mdb_txn_renew0(txn);
2253 if (rc == MDB_SUCCESS) {
2254 DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2255 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2256 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2262 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2266 int rc, size, tsize = sizeof(MDB_txn);
2268 if (env->me_flags & MDB_FATAL_ERROR) {
2269 DPUTS("environment had fatal error, must shutdown!");
2272 if ((env->me_flags & MDB_RDONLY) && !(flags & MDB_RDONLY))
2275 /* Nested transactions: Max 1 child, write txns only, no writemap */
2276 if (parent->mt_child ||
2277 (flags & MDB_RDONLY) ||
2278 (parent->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR)) ||
2279 (env->me_flags & MDB_WRITEMAP))
2281 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
2283 tsize = sizeof(MDB_ntxn);
2285 size = tsize + env->me_maxdbs * (sizeof(MDB_db)+1);
2286 if (!(flags & MDB_RDONLY))
2287 size += env->me_maxdbs * sizeof(MDB_cursor *);
2289 if ((txn = calloc(1, size)) == NULL) {
2290 DPRINTF(("calloc: %s", strerror(ErrCode())));
2293 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2294 if (flags & MDB_RDONLY) {
2295 txn->mt_flags |= MDB_TXN_RDONLY;
2296 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
2298 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2299 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
2305 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2306 if (!txn->mt_u.dirty_list ||
2307 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2309 free(txn->mt_u.dirty_list);
2313 txn->mt_txnid = parent->mt_txnid;
2314 txn->mt_dirty_room = parent->mt_dirty_room;
2315 txn->mt_u.dirty_list[0].mid = 0;
2316 txn->mt_spill_pgs = NULL;
2317 txn->mt_next_pgno = parent->mt_next_pgno;
2318 parent->mt_child = txn;
2319 txn->mt_parent = parent;
2320 txn->mt_numdbs = parent->mt_numdbs;
2321 txn->mt_flags = parent->mt_flags;
2322 txn->mt_dbxs = parent->mt_dbxs;
2323 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2324 /* Copy parent's mt_dbflags, but clear DB_NEW */
2325 for (i=0; i<txn->mt_numdbs; i++)
2326 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2328 ntxn = (MDB_ntxn *)txn;
2329 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2330 if (env->me_pghead) {
2331 size = MDB_IDL_SIZEOF(env->me_pghead);
2332 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2334 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2339 rc = mdb_cursor_shadow(parent, txn);
2341 mdb_txn_reset0(txn, "beginchild-fail");
2343 rc = mdb_txn_renew0(txn);
2349 DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2350 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2351 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
2358 mdb_txn_env(MDB_txn *txn)
2360 if(!txn) return NULL;
2364 /** Export or close DBI handles opened in this txn. */
2366 mdb_dbis_update(MDB_txn *txn, int keep)
2369 MDB_dbi n = txn->mt_numdbs;
2370 MDB_env *env = txn->mt_env;
2371 unsigned char *tdbflags = txn->mt_dbflags;
2373 for (i = n; --i >= 2;) {
2374 if (tdbflags[i] & DB_NEW) {
2376 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2378 char *ptr = env->me_dbxs[i].md_name.mv_data;
2379 env->me_dbxs[i].md_name.mv_data = NULL;
2380 env->me_dbxs[i].md_name.mv_size = 0;
2381 env->me_dbflags[i] = 0;
2386 if (keep && env->me_numdbs < n)
2390 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
2391 * May be called twice for readonly txns: First reset it, then abort.
2392 * @param[in] txn the transaction handle to reset
2393 * @param[in] act why the transaction is being reset
2396 mdb_txn_reset0(MDB_txn *txn, const char *act)
2398 MDB_env *env = txn->mt_env;
2400 /* Close any DBI handles opened in this txn */
2401 mdb_dbis_update(txn, 0);
2403 DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2404 act, txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2405 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
2407 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2408 if (txn->mt_u.reader) {
2409 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2410 if (!(env->me_flags & MDB_NOTLS))
2411 txn->mt_u.reader = NULL; /* txn does not own reader */
2413 txn->mt_numdbs = 0; /* close nothing if called again */
2414 txn->mt_dbxs = NULL; /* mark txn as reset */
2416 mdb_cursors_close(txn, 0);
2418 if (!(env->me_flags & MDB_WRITEMAP)) {
2419 mdb_dlist_free(txn);
2421 mdb_midl_free(env->me_pghead);
2423 if (txn->mt_parent) {
2424 txn->mt_parent->mt_child = NULL;
2425 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2426 mdb_midl_free(txn->mt_free_pgs);
2427 mdb_midl_free(txn->mt_spill_pgs);
2428 free(txn->mt_u.dirty_list);
2432 if (mdb_midl_shrink(&txn->mt_free_pgs))
2433 env->me_free_pgs = txn->mt_free_pgs;
2434 env->me_pghead = NULL;
2438 /* The writer mutex was locked in mdb_txn_begin. */
2440 UNLOCK_MUTEX_W(env);
2445 mdb_txn_reset(MDB_txn *txn)
2450 /* This call is only valid for read-only txns */
2451 if (!(txn->mt_flags & MDB_TXN_RDONLY))
2454 mdb_txn_reset0(txn, "reset");
2458 mdb_txn_abort(MDB_txn *txn)
2464 mdb_txn_abort(txn->mt_child);
2466 mdb_txn_reset0(txn, "abort");
2467 /* Free reader slot tied to this txn (if MDB_NOTLS && writable FS) */
2468 if ((txn->mt_flags & MDB_TXN_RDONLY) && txn->mt_u.reader)
2469 txn->mt_u.reader->mr_pid = 0;
2474 /** Save the freelist as of this transaction to the freeDB.
2475 * This changes the freelist. Keep trying until it stabilizes.
2478 mdb_freelist_save(MDB_txn *txn)
2480 /* env->me_pghead[] can grow and shrink during this call.
2481 * env->me_pglast and txn->mt_free_pgs[] can only grow.
2482 * Page numbers cannot disappear from txn->mt_free_pgs[].
2485 MDB_env *env = txn->mt_env;
2486 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
2487 txnid_t pglast = 0, head_id = 0;
2488 pgno_t freecnt = 0, *free_pgs, *mop;
2489 ssize_t head_room = 0, total_room = 0, mop_len;
2491 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
2493 if (env->me_pghead) {
2494 /* Make sure first page of freeDB is touched and on freelist */
2495 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
2496 if (rc && rc != MDB_NOTFOUND)
2501 /* Come back here after each Put() in case freelist changed */
2504 /* If using records from freeDB which we have not yet
2505 * deleted, delete them and any we reserved for me_pghead.
2507 while (pglast < env->me_pglast) {
2508 rc = mdb_cursor_first(&mc, &key, NULL);
2511 pglast = head_id = *(txnid_t *)key.mv_data;
2512 total_room = head_room = 0;
2513 assert(pglast <= env->me_pglast);
2514 rc = mdb_cursor_del(&mc, 0);
2519 /* Save the IDL of pages freed by this txn, to a single record */
2520 if (freecnt < txn->mt_free_pgs[0]) {
2522 /* Make sure last page of freeDB is touched and on freelist */
2523 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
2524 if (rc && rc != MDB_NOTFOUND)
2527 free_pgs = txn->mt_free_pgs;
2528 /* Write to last page of freeDB */
2529 key.mv_size = sizeof(txn->mt_txnid);
2530 key.mv_data = &txn->mt_txnid;
2532 freecnt = free_pgs[0];
2533 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
2534 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2537 /* Retry if mt_free_pgs[] grew during the Put() */
2538 free_pgs = txn->mt_free_pgs;
2539 } while (freecnt < free_pgs[0]);
2540 mdb_midl_sort(free_pgs);
2541 memcpy(data.mv_data, free_pgs, data.mv_size);
2544 unsigned int i = free_pgs[0];
2545 DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
2546 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
2548 DPRINTF(("IDL %"Z"u", free_pgs[i]));
2554 mop = env->me_pghead;
2555 mop_len = mop ? mop[0] : 0;
2557 /* Reserve records for me_pghead[]. Split it if multi-page,
2558 * to avoid searching freeDB for a page range. Use keys in
2559 * range [1,me_pglast]: Smaller than txnid of oldest reader.
2561 if (total_room >= mop_len) {
2562 if (total_room == mop_len || --more < 0)
2564 } else if (head_room >= maxfree_1pg && head_id > 1) {
2565 /* Keep current record (overflow page), add a new one */
2569 /* (Re)write {key = head_id, IDL length = head_room} */
2570 total_room -= head_room;
2571 head_room = mop_len - total_room;
2572 if (head_room > maxfree_1pg && head_id > 1) {
2573 /* Overflow multi-page for part of me_pghead */
2574 head_room /= head_id; /* amortize page sizes */
2575 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
2576 } else if (head_room < 0) {
2577 /* Rare case, not bothering to delete this record */
2580 key.mv_size = sizeof(head_id);
2581 key.mv_data = &head_id;
2582 data.mv_size = (head_room + 1) * sizeof(pgno_t);
2583 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2586 *(MDB_ID *)data.mv_data = 0; /* IDL is initially empty */
2587 total_room += head_room;
2590 /* Fill in the reserved me_pghead records */
2596 rc = mdb_cursor_first(&mc, &key, &data);
2597 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
2598 unsigned flags = MDB_CURRENT;
2599 txnid_t id = *(txnid_t *)key.mv_data;
2600 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
2603 assert(len >= 0 && id <= env->me_pglast);
2605 if (len > mop_len) {
2607 data.mv_size = (len + 1) * sizeof(MDB_ID);
2610 data.mv_data = mop -= len;
2613 rc = mdb_cursor_put(&mc, &key, &data, flags);
2615 if (rc || !(mop_len -= len))
2622 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
2623 * @param[in] txn the transaction that's being committed
2624 * @param[in] keep number of initial pages in dirty_list to keep dirty.
2625 * @return 0 on success, non-zero on failure.
2628 mdb_page_flush(MDB_txn *txn, int keep)
2630 MDB_env *env = txn->mt_env;
2631 MDB_ID2L dl = txn->mt_u.dirty_list;
2632 unsigned psize = env->me_psize, j;
2633 int i, pagecount = dl[0].mid, rc;
2634 size_t size = 0, pos = 0;
2636 MDB_page *dp = NULL;
2640 struct iovec iov[MDB_COMMIT_PAGES];
2641 ssize_t wpos = 0, wsize = 0, wres;
2642 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
2648 if (env->me_flags & MDB_WRITEMAP) {
2649 /* Clear dirty flags */
2650 while (++i <= pagecount) {
2652 /* Don't flush this page yet */
2653 if (dp->mp_flags & P_KEEP) {
2654 dp->mp_flags ^= P_KEEP;
2658 dp->mp_flags &= ~P_DIRTY;
2663 /* Write the pages */
2665 if (++i <= pagecount) {
2667 /* Don't flush this page yet */
2668 if (dp->mp_flags & P_KEEP) {
2669 dp->mp_flags ^= P_KEEP;
2674 /* clear dirty flag */
2675 dp->mp_flags &= ~P_DIRTY;
2678 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
2683 /* Windows actually supports scatter/gather I/O, but only on
2684 * unbuffered file handles. Since we're relying on the OS page
2685 * cache for all our data, that's self-defeating. So we just
2686 * write pages one at a time. We use the ov structure to set
2687 * the write offset, to at least save the overhead of a Seek
2690 DPRINTF(("committing page %"Z"u", pgno));
2691 memset(&ov, 0, sizeof(ov));
2692 ov.Offset = pos & 0xffffffff;
2693 ov.OffsetHigh = pos >> 16 >> 16;
2694 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
2696 DPRINTF(("WriteFile: %d", rc));
2700 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
2701 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
2703 /* Write previous page(s) */
2704 #ifdef MDB_USE_PWRITEV
2705 wres = pwritev(env->me_fd, iov, n, wpos);
2708 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
2710 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
2712 DPRINTF(("lseek: %s", strerror(rc)));
2715 wres = writev(env->me_fd, iov, n);
2718 if (wres != wsize) {
2721 DPRINTF(("Write error: %s", strerror(rc)));
2723 rc = EIO; /* TODO: Use which error code? */
2724 DPUTS("short write, filesystem full?");
2735 DPRINTF(("committing page %"Z"u", pgno));
2736 next_pos = pos + size;
2737 iov[n].iov_len = size;
2738 iov[n].iov_base = (char *)dp;
2744 for (i = keep; ++i <= pagecount; ) {
2746 /* This is a page we skipped above */
2749 dl[j].mid = dp->mp_pgno;
2752 mdb_dpage_free(env, dp);
2757 txn->mt_dirty_room += i - j;
2763 mdb_txn_commit(MDB_txn *txn)
2769 assert(txn != NULL);
2770 assert(txn->mt_env != NULL);
2772 if (txn->mt_child) {
2773 rc = mdb_txn_commit(txn->mt_child);
2774 txn->mt_child = NULL;
2781 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2782 mdb_dbis_update(txn, 1);
2783 txn->mt_numdbs = 2; /* so txn_abort() doesn't close any new handles */
2788 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
2789 DPUTS("error flag is set, can't commit");
2791 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
2796 if (txn->mt_parent) {
2797 MDB_txn *parent = txn->mt_parent;
2800 unsigned x, y, len, ps_len;
2802 /* Append our free list to parent's */
2803 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
2806 mdb_midl_free(txn->mt_free_pgs);
2807 /* Failures after this must either undo the changes
2808 * to the parent or set MDB_TXN_ERROR in the parent.
2811 parent->mt_next_pgno = txn->mt_next_pgno;
2812 parent->mt_flags = txn->mt_flags;
2814 /* Merge our cursors into parent's and close them */
2815 mdb_cursors_close(txn, 1);
2817 /* Update parent's DB table. */
2818 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2819 parent->mt_numdbs = txn->mt_numdbs;
2820 parent->mt_dbflags[0] = txn->mt_dbflags[0];
2821 parent->mt_dbflags[1] = txn->mt_dbflags[1];
2822 for (i=2; i<txn->mt_numdbs; i++) {
2823 /* preserve parent's DB_NEW status */
2824 x = parent->mt_dbflags[i] & DB_NEW;
2825 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
2828 dst = parent->mt_u.dirty_list;
2829 src = txn->mt_u.dirty_list;
2830 /* Remove anything in our dirty list from parent's spill list */
2831 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
2833 pspill[0] = (pgno_t)-1;
2834 /* Mark our dirty pages as deleted in parent spill list */
2835 for (i=0, len=src[0].mid; ++i <= len; ) {
2836 MDB_ID pn = src[i].mid << 1;
2837 while (pn > pspill[x])
2839 if (pn == pspill[x]) {
2844 /* Squash deleted pagenums if we deleted any */
2845 for (x=y; ++x <= ps_len; )
2846 if (!(pspill[x] & 1))
2847 pspill[++y] = pspill[x];
2851 /* Find len = length of merging our dirty list with parent's */
2853 dst[0].mid = 0; /* simplify loops */
2854 if (parent->mt_parent) {
2855 len = x + src[0].mid;
2856 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
2857 for (i = x; y && i; y--) {
2858 pgno_t yp = src[y].mid;
2859 while (yp < dst[i].mid)
2861 if (yp == dst[i].mid) {
2866 } else { /* Simplify the above for single-ancestor case */
2867 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
2869 /* Merge our dirty list with parent's */
2871 for (i = len; y; dst[i--] = src[y--]) {
2872 pgno_t yp = src[y].mid;
2873 while (yp < dst[x].mid)
2874 dst[i--] = dst[x--];
2875 if (yp == dst[x].mid)
2876 free(dst[x--].mptr);
2880 free(txn->mt_u.dirty_list);
2881 parent->mt_dirty_room = txn->mt_dirty_room;
2882 if (txn->mt_spill_pgs) {
2883 if (parent->mt_spill_pgs) {
2884 /* TODO: Prevent failure here, so parent does not fail */
2885 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
2887 parent->mt_flags |= MDB_TXN_ERROR;
2888 mdb_midl_free(txn->mt_spill_pgs);
2889 mdb_midl_sort(parent->mt_spill_pgs);
2891 parent->mt_spill_pgs = txn->mt_spill_pgs;
2895 parent->mt_child = NULL;
2896 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
2901 if (txn != env->me_txn) {
2902 DPUTS("attempt to commit unknown transaction");
2907 mdb_cursors_close(txn, 0);
2909 if (!txn->mt_u.dirty_list[0].mid &&
2910 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
2913 DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
2914 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
2916 /* Update DB root pointers */
2917 if (txn->mt_numdbs > 2) {
2921 data.mv_size = sizeof(MDB_db);
2923 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
2924 for (i = 2; i < txn->mt_numdbs; i++) {
2925 if (txn->mt_dbflags[i] & DB_DIRTY) {
2926 data.mv_data = &txn->mt_dbs[i];
2927 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
2934 rc = mdb_freelist_save(txn);
2938 mdb_midl_free(env->me_pghead);
2939 env->me_pghead = NULL;
2940 if (mdb_midl_shrink(&txn->mt_free_pgs))
2941 env->me_free_pgs = txn->mt_free_pgs;
2947 if ((rc = mdb_page_flush(txn, 0)) ||
2948 (rc = mdb_env_sync(env, 0)) ||
2949 (rc = mdb_env_write_meta(txn)))
2955 mdb_dbis_update(txn, 1);
2958 UNLOCK_MUTEX_W(env);
2968 /** Read the environment parameters of a DB environment before
2969 * mapping it into memory.
2970 * @param[in] env the environment handle
2971 * @param[out] meta address of where to store the meta information
2972 * @return 0 on success, non-zero on failure.
2975 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
2981 enum { Size = sizeof(pbuf) };
2983 /* We don't know the page size yet, so use a minimum value.
2984 * Read both meta pages so we can use the latest one.
2987 for (i=off=0; i<2; i++, off = meta->mm_psize) {
2991 memset(&ov, 0, sizeof(ov));
2993 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
2994 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
2997 rc = pread(env->me_fd, &pbuf, Size, off);
3000 if (rc == 0 && off == 0)
3002 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3003 DPRINTF(("read: %s", mdb_strerror(rc)));
3007 p = (MDB_page *)&pbuf;
3009 if (!F_ISSET(p->mp_flags, P_META)) {
3010 DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
3015 if (m->mm_magic != MDB_MAGIC) {
3016 DPUTS("meta has invalid magic");
3020 if (m->mm_version != MDB_DATA_VERSION) {
3021 DPRINTF(("database is version %u, expected version %u",
3022 m->mm_version, MDB_DATA_VERSION));
3023 return MDB_VERSION_MISMATCH;
3026 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3032 /** Write the environment parameters of a freshly created DB environment.
3033 * @param[in] env the environment handle
3034 * @param[out] meta address of where to store the meta information
3035 * @return 0 on success, non-zero on failure.
3038 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3046 memset(&ov, 0, sizeof(ov));
3047 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3049 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3052 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3053 len = pwrite(fd, ptr, size, pos); \
3054 rc = (len >= 0); } while(0)
3057 DPUTS("writing new meta page");
3059 psize = env->me_psize;
3061 meta->mm_magic = MDB_MAGIC;
3062 meta->mm_version = MDB_DATA_VERSION;
3063 meta->mm_mapsize = env->me_mapsize;
3064 meta->mm_psize = psize;
3065 meta->mm_last_pg = 1;
3066 meta->mm_flags = env->me_flags & 0xffff;
3067 meta->mm_flags |= MDB_INTEGERKEY;
3068 meta->mm_dbs[0].md_root = P_INVALID;
3069 meta->mm_dbs[1].md_root = P_INVALID;
3071 p = calloc(2, psize);
3073 p->mp_flags = P_META;
3074 *(MDB_meta *)METADATA(p) = *meta;
3076 q = (MDB_page *)((char *)p + psize);
3078 q->mp_flags = P_META;
3079 *(MDB_meta *)METADATA(q) = *meta;
3081 DO_PWRITE(rc, env->me_fd, p, psize * 2, len, 0);
3084 else if ((unsigned) len == psize * 2)
3092 /** Update the environment info to commit a transaction.
3093 * @param[in] txn the transaction that's being committed
3094 * @return 0 on success, non-zero on failure.
3097 mdb_env_write_meta(MDB_txn *txn)
3100 MDB_meta meta, metab, *mp;
3102 int rc, len, toggle;
3111 assert(txn != NULL);
3112 assert(txn->mt_env != NULL);
3114 toggle = txn->mt_txnid & 1;
3115 DPRINTF(("writing meta page %d for root page %"Z"u",
3116 toggle, txn->mt_dbs[MAIN_DBI].md_root));
3119 mp = env->me_metas[toggle];
3121 if (env->me_flags & MDB_WRITEMAP) {
3122 /* Persist any increases of mapsize config */
3123 if (env->me_mapsize > mp->mm_mapsize)
3124 mp->mm_mapsize = env->me_mapsize;
3125 mp->mm_dbs[0] = txn->mt_dbs[0];
3126 mp->mm_dbs[1] = txn->mt_dbs[1];
3127 mp->mm_last_pg = txn->mt_next_pgno - 1;
3128 mp->mm_txnid = txn->mt_txnid;
3129 if (!(env->me_flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3130 unsigned meta_size = env->me_psize;
3131 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3134 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
3135 if (meta_size < env->me_os_psize)
3136 meta_size += meta_size;
3141 if (MDB_MSYNC(ptr, meta_size, rc)) {
3148 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
3149 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
3151 ptr = (char *)&meta;
3152 if (env->me_mapsize > mp->mm_mapsize) {
3153 /* Persist any increases of mapsize config */
3154 meta.mm_mapsize = env->me_mapsize;
3155 off = offsetof(MDB_meta, mm_mapsize);
3157 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
3159 len = sizeof(MDB_meta) - off;
3162 meta.mm_dbs[0] = txn->mt_dbs[0];
3163 meta.mm_dbs[1] = txn->mt_dbs[1];
3164 meta.mm_last_pg = txn->mt_next_pgno - 1;
3165 meta.mm_txnid = txn->mt_txnid;
3168 off += env->me_psize;
3171 /* Write to the SYNC fd */
3172 mfd = env->me_flags & (MDB_NOSYNC|MDB_NOMETASYNC) ?
3173 env->me_fd : env->me_mfd;
3176 memset(&ov, 0, sizeof(ov));
3178 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3182 rc = pwrite(mfd, ptr, len, off);
3185 rc = rc < 0 ? ErrCode() : EIO;
3186 DPUTS("write failed, disk error?");
3187 /* On a failure, the pagecache still contains the new data.
3188 * Write some old data back, to prevent it from being used.
3189 * Use the non-SYNC fd; we know it will fail anyway.
3191 meta.mm_last_pg = metab.mm_last_pg;
3192 meta.mm_txnid = metab.mm_txnid;
3194 memset(&ov, 0, sizeof(ov));
3196 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3198 r2 = pwrite(env->me_fd, ptr, len, off);
3199 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
3202 env->me_flags |= MDB_FATAL_ERROR;
3206 /* Memory ordering issues are irrelevant; since the entire writer
3207 * is wrapped by wmutex, all of these changes will become visible
3208 * after the wmutex is unlocked. Since the DB is multi-version,
3209 * readers will get consistent data regardless of how fresh or
3210 * how stale their view of these values is.
3213 env->me_txns->mti_txnid = txn->mt_txnid;
3218 /** Check both meta pages to see which one is newer.
3219 * @param[in] env the environment handle
3220 * @return meta toggle (0 or 1).
3223 mdb_env_pick_meta(const MDB_env *env)
3225 return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
3229 mdb_env_create(MDB_env **env)
3233 e = calloc(1, sizeof(MDB_env));
3237 e->me_maxreaders = DEFAULT_READERS;
3238 e->me_maxdbs = e->me_numdbs = 2;
3239 e->me_fd = INVALID_HANDLE_VALUE;
3240 e->me_lfd = INVALID_HANDLE_VALUE;
3241 e->me_mfd = INVALID_HANDLE_VALUE;
3242 #ifdef MDB_USE_POSIX_SEM
3243 e->me_rmutex = SEM_FAILED;
3244 e->me_wmutex = SEM_FAILED;
3246 e->me_pid = getpid();
3247 GET_PAGESIZE(e->me_os_psize);
3248 VGMEMP_CREATE(e,0,0);
3254 mdb_env_map(MDB_env *env, void *addr, int newsize)
3257 unsigned int flags = env->me_flags;
3261 LONG sizelo, sizehi;
3262 sizelo = env->me_mapsize & 0xffffffff;
3263 sizehi = env->me_mapsize >> 16 >> 16; /* only needed on Win64 */
3265 /* Windows won't create mappings for zero length files.
3266 * Just allocate the maxsize right now.
3269 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3270 || !SetEndOfFile(env->me_fd)
3271 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3274 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3275 PAGE_READWRITE : PAGE_READONLY,
3276 sizehi, sizelo, NULL);
3279 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3280 FILE_MAP_WRITE : FILE_MAP_READ,
3281 0, 0, env->me_mapsize, addr);
3282 rc = env->me_map ? 0 : ErrCode();
3287 int prot = PROT_READ;
3288 if (flags & MDB_WRITEMAP) {
3290 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3293 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
3295 if (env->me_map == MAP_FAILED) {
3300 if (flags & MDB_NORDAHEAD) {
3301 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3303 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3305 #ifdef POSIX_MADV_RANDOM
3306 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3307 #endif /* POSIX_MADV_RANDOM */
3308 #endif /* MADV_RANDOM */
3312 /* Can happen because the address argument to mmap() is just a
3313 * hint. mmap() can pick another, e.g. if the range is in use.
3314 * The MAP_FIXED flag would prevent that, but then mmap could
3315 * instead unmap existing pages to make room for the new map.
3317 if (addr && env->me_map != addr)
3318 return EBUSY; /* TODO: Make a new MDB_* error code? */
3320 p = (MDB_page *)env->me_map;
3321 env->me_metas[0] = METADATA(p);
3322 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
3328 mdb_env_set_mapsize(MDB_env *env, size_t size)
3330 /* If env is already open, caller is responsible for making
3331 * sure there are no active txns.
3339 size = env->me_metas[mdb_env_pick_meta(env)]->mm_mapsize;
3340 else if (size < env->me_mapsize) {
3341 /* If the configured size is smaller, make sure it's
3342 * still big enough. Silently round up to minimum if not.
3344 size_t minsize = (env->me_metas[mdb_env_pick_meta(env)]->mm_last_pg + 1) * env->me_psize;
3348 munmap(env->me_map, env->me_mapsize);
3349 env->me_mapsize = size;
3350 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
3351 rc = mdb_env_map(env, old, 1);
3355 env->me_mapsize = size;
3357 env->me_maxpg = env->me_mapsize / env->me_psize;
3362 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
3366 env->me_maxdbs = dbs + 2; /* Named databases + main and free DB */
3371 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
3373 if (env->me_map || readers < 1)
3375 env->me_maxreaders = readers;
3380 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
3382 if (!env || !readers)
3384 *readers = env->me_maxreaders;
3388 /** Further setup required for opening an MDB environment
3391 mdb_env_open2(MDB_env *env)
3393 unsigned int flags = env->me_flags;
3394 int i, newenv = 0, rc;
3398 /* See if we should use QueryLimited */
3400 if ((rc & 0xff) > 5)
3401 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
3403 env->me_pidquery = PROCESS_QUERY_INFORMATION;
3406 memset(&meta, 0, sizeof(meta));
3408 if ((i = mdb_env_read_header(env, &meta)) != 0) {
3411 DPUTS("new mdbenv");
3413 env->me_psize = env->me_os_psize;
3414 if (env->me_psize > MAX_PAGESIZE)
3415 env->me_psize = MAX_PAGESIZE;
3417 env->me_psize = meta.mm_psize;
3420 /* Was a mapsize configured? */
3421 if (!env->me_mapsize) {
3422 /* If this is a new environment, take the default,
3423 * else use the size recorded in the existing env.
3425 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
3426 } else if (env->me_mapsize < meta.mm_mapsize) {
3427 /* If the configured size is smaller, make sure it's
3428 * still big enough. Silently round up to minimum if not.
3430 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
3431 if (env->me_mapsize < minsize)
3432 env->me_mapsize = minsize;
3435 rc = mdb_env_map(env, meta.mm_address, newenv);
3440 if (flags & MDB_FIXEDMAP)
3441 meta.mm_address = env->me_map;
3442 i = mdb_env_init_meta(env, &meta);
3443 if (i != MDB_SUCCESS) {
3447 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
3448 env->me_nodemax = (env->me_psize - PAGEHDRSZ) / MDB_MINKEYS;
3450 env->me_maxpg = env->me_mapsize / env->me_psize;
3453 int toggle = mdb_env_pick_meta(env);
3454 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
3456 DPRINTF(("opened database version %u, pagesize %u",
3457 env->me_metas[0]->mm_version, env->me_psize));
3458 DPRINTF(("using meta page %d", toggle));
3459 DPRINTF(("depth: %u", db->md_depth));
3460 DPRINTF(("entries: %"Z"u", db->md_entries));
3461 DPRINTF(("branch pages: %"Z"u", db->md_branch_pages));
3462 DPRINTF(("leaf pages: %"Z"u", db->md_leaf_pages));
3463 DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
3464 DPRINTF(("root: %"Z"u", db->md_root));
3472 /** Release a reader thread's slot in the reader lock table.
3473 * This function is called automatically when a thread exits.
3474 * @param[in] ptr This points to the slot in the reader lock table.
3477 mdb_env_reader_dest(void *ptr)
3479 MDB_reader *reader = ptr;
3485 /** Junk for arranging thread-specific callbacks on Windows. This is
3486 * necessarily platform and compiler-specific. Windows supports up
3487 * to 1088 keys. Let's assume nobody opens more than 64 environments
3488 * in a single process, for now. They can override this if needed.
3490 #ifndef MAX_TLS_KEYS
3491 #define MAX_TLS_KEYS 64
3493 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
3494 static int mdb_tls_nkeys;
3496 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
3500 case DLL_PROCESS_ATTACH: break;
3501 case DLL_THREAD_ATTACH: break;
3502 case DLL_THREAD_DETACH:
3503 for (i=0; i<mdb_tls_nkeys; i++) {
3504 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
3505 mdb_env_reader_dest(r);
3508 case DLL_PROCESS_DETACH: break;
3513 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3515 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3519 /* Force some symbol references.
3520 * _tls_used forces the linker to create the TLS directory if not already done
3521 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
3523 #pragma comment(linker, "/INCLUDE:_tls_used")
3524 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
3525 #pragma const_seg(".CRT$XLB")
3526 extern const PIMAGE_TLS_CALLBACK mdb_tls_callback;
3527 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3530 #pragma comment(linker, "/INCLUDE:__tls_used")
3531 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
3532 #pragma data_seg(".CRT$XLB")
3533 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3535 #endif /* WIN 32/64 */
3536 #endif /* !__GNUC__ */
3539 /** Downgrade the exclusive lock on the region back to shared */
3541 mdb_env_share_locks(MDB_env *env, int *excl)
3543 int rc = 0, toggle = mdb_env_pick_meta(env);
3545 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
3550 /* First acquire a shared lock. The Unlock will
3551 * then release the existing exclusive lock.
3553 memset(&ov, 0, sizeof(ov));
3554 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3557 UnlockFile(env->me_lfd, 0, 0, 1, 0);
3563 struct flock lock_info;
3564 /* The shared lock replaces the existing lock */
3565 memset((void *)&lock_info, 0, sizeof(lock_info));
3566 lock_info.l_type = F_RDLCK;
3567 lock_info.l_whence = SEEK_SET;
3568 lock_info.l_start = 0;
3569 lock_info.l_len = 1;
3570 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3571 (rc = ErrCode()) == EINTR) ;
3572 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
3579 /** Try to get exlusive lock, otherwise shared.
3580 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
3583 mdb_env_excl_lock(MDB_env *env, int *excl)
3587 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
3591 memset(&ov, 0, sizeof(ov));
3592 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3599 struct flock lock_info;
3600 memset((void *)&lock_info, 0, sizeof(lock_info));
3601 lock_info.l_type = F_WRLCK;
3602 lock_info.l_whence = SEEK_SET;
3603 lock_info.l_start = 0;
3604 lock_info.l_len = 1;
3605 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3606 (rc = ErrCode()) == EINTR) ;
3610 # ifdef MDB_USE_POSIX_SEM
3611 if (*excl < 0) /* always true when !MDB_USE_POSIX_SEM */
3614 lock_info.l_type = F_RDLCK;
3615 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
3616 (rc = ErrCode()) == EINTR) ;
3626 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
3628 * @(#) $Revision: 5.1 $
3629 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
3630 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
3632 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
3636 * Please do not copyright this code. This code is in the public domain.
3638 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
3639 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
3640 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
3641 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
3642 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
3643 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
3644 * PERFORMANCE OF THIS SOFTWARE.
3647 * chongo <Landon Curt Noll> /\oo/\
3648 * http://www.isthe.com/chongo/
3650 * Share and Enjoy! :-)
3653 typedef unsigned long long mdb_hash_t;
3654 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
3656 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
3657 * @param[in] val value to hash
3658 * @param[in] hval initial value for hash
3659 * @return 64 bit hash
3661 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
3662 * hval arg on the first call.
3665 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
3667 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
3668 unsigned char *end = s + val->mv_size;
3670 * FNV-1a hash each octet of the string
3673 /* xor the bottom with the current octet */
3674 hval ^= (mdb_hash_t)*s++;
3676 /* multiply by the 64 bit FNV magic prime mod 2^64 */
3677 hval += (hval << 1) + (hval << 4) + (hval << 5) +
3678 (hval << 7) + (hval << 8) + (hval << 40);
3680 /* return our new hash value */
3684 /** Hash the string and output the encoded hash.
3685 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
3686 * very short name limits. We don't care about the encoding being reversible,
3687 * we just want to preserve as many bits of the input as possible in a
3688 * small printable string.
3689 * @param[in] str string to hash
3690 * @param[out] encbuf an array of 11 chars to hold the hash
3692 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
3695 mdb_pack85(unsigned long l, char *out)
3699 for (i=0; i<5; i++) {
3700 *out++ = mdb_a85[l % 85];
3706 mdb_hash_enc(MDB_val *val, char *encbuf)
3708 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
3710 mdb_pack85(h, encbuf);
3711 mdb_pack85(h>>32, encbuf+5);
3716 /** Open and/or initialize the lock region for the environment.
3717 * @param[in] env The MDB environment.
3718 * @param[in] lpath The pathname of the file used for the lock region.
3719 * @param[in] mode The Unix permissions for the file, if we create it.
3720 * @param[out] excl Resulting file lock type: -1 none, 0 shared, 1 exclusive
3721 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
3722 * @return 0 on success, non-zero on failure.
3725 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
3728 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
3730 # define MDB_ERRCODE_ROFS EROFS
3731 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
3732 # define MDB_CLOEXEC O_CLOEXEC
3735 # define MDB_CLOEXEC 0
3742 env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
3743 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
3744 FILE_ATTRIBUTE_NORMAL, NULL);
3746 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
3748 if (env->me_lfd == INVALID_HANDLE_VALUE) {
3750 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
3755 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
3756 /* Lose record locks when exec*() */
3757 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
3758 fcntl(env->me_lfd, F_SETFD, fdflags);
3761 if (!(env->me_flags & MDB_NOTLS)) {
3762 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
3765 env->me_flags |= MDB_ENV_TXKEY;
3767 /* Windows TLS callbacks need help finding their TLS info. */
3768 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
3772 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
3776 /* Try to get exclusive lock. If we succeed, then
3777 * nobody is using the lock region and we should initialize it.
3779 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
3782 size = GetFileSize(env->me_lfd, NULL);
3784 size = lseek(env->me_lfd, 0, SEEK_END);
3785 if (size == -1) goto fail_errno;
3787 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
3788 if (size < rsize && *excl > 0) {
3790 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != rsize
3791 || !SetEndOfFile(env->me_lfd))
3794 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
3798 size = rsize - sizeof(MDB_txninfo);
3799 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
3804 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
3806 if (!mh) goto fail_errno;
3807 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
3809 if (!env->me_txns) goto fail_errno;
3811 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
3813 if (m == MAP_FAILED) goto fail_errno;
3819 BY_HANDLE_FILE_INFORMATION stbuf;
3828 if (!mdb_sec_inited) {
3829 InitializeSecurityDescriptor(&mdb_null_sd,
3830 SECURITY_DESCRIPTOR_REVISION);
3831 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
3832 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
3833 mdb_all_sa.bInheritHandle = FALSE;
3834 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
3837 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
3838 idbuf.volume = stbuf.dwVolumeSerialNumber;
3839 idbuf.nhigh = stbuf.nFileIndexHigh;
3840 idbuf.nlow = stbuf.nFileIndexLow;
3841 val.mv_data = &idbuf;
3842 val.mv_size = sizeof(idbuf);
3843 mdb_hash_enc(&val, encbuf);
3844 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
3845 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
3846 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
3847 if (!env->me_rmutex) goto fail_errno;
3848 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
3849 if (!env->me_wmutex) goto fail_errno;
3850 #elif defined(MDB_USE_POSIX_SEM)
3859 #if defined(__NetBSD__)
3860 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
3862 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
3863 idbuf.dev = stbuf.st_dev;
3864 idbuf.ino = stbuf.st_ino;
3865 val.mv_data = &idbuf;
3866 val.mv_size = sizeof(idbuf);
3867 mdb_hash_enc(&val, encbuf);
3868 #ifdef MDB_SHORT_SEMNAMES
3869 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
3871 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
3872 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
3873 /* Clean up after a previous run, if needed: Try to
3874 * remove both semaphores before doing anything else.
3876 sem_unlink(env->me_txns->mti_rmname);
3877 sem_unlink(env->me_txns->mti_wmname);
3878 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
3879 O_CREAT|O_EXCL, mode, 1);
3880 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3881 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
3882 O_CREAT|O_EXCL, mode, 1);
3883 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3884 #else /* MDB_USE_POSIX_SEM */
3885 pthread_mutexattr_t mattr;
3887 if ((rc = pthread_mutexattr_init(&mattr))
3888 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
3889 || (rc = pthread_mutex_init(&env->me_txns->mti_mutex, &mattr))
3890 || (rc = pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr)))
3892 pthread_mutexattr_destroy(&mattr);
3893 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
3895 env->me_txns->mti_magic = MDB_MAGIC;
3896 env->me_txns->mti_format = MDB_LOCK_FORMAT;
3897 env->me_txns->mti_txnid = 0;
3898 env->me_txns->mti_numreaders = 0;
3901 if (env->me_txns->mti_magic != MDB_MAGIC) {
3902 DPUTS("lock region has invalid magic");
3906 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
3907 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
3908 env->me_txns->mti_format, MDB_LOCK_FORMAT));
3909 rc = MDB_VERSION_MISMATCH;
3913 if (rc && rc != EACCES && rc != EAGAIN) {
3917 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
3918 if (!env->me_rmutex) goto fail_errno;
3919 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
3920 if (!env->me_wmutex) goto fail_errno;
3921 #elif defined(MDB_USE_POSIX_SEM)
3922 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
3923 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3924 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
3925 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3936 /** The name of the lock file in the DB environment */
3937 #define LOCKNAME "/lock.mdb"
3938 /** The name of the data file in the DB environment */
3939 #define DATANAME "/data.mdb"
3940 /** The suffix of the lock file when no subdir is used */
3941 #define LOCKSUFF "-lock"
3942 /** Only a subset of the @ref mdb_env flags can be changed
3943 * at runtime. Changing other flags requires closing the
3944 * environment and re-opening it with the new flags.
3946 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC)
3947 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY|MDB_WRITEMAP|MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
3950 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
3952 int oflags, rc, len, excl = -1;
3953 char *lpath, *dpath;
3955 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
3959 if (flags & MDB_NOSUBDIR) {
3960 rc = len + sizeof(LOCKSUFF) + len + 1;
3962 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
3967 if (flags & MDB_NOSUBDIR) {
3968 dpath = lpath + len + sizeof(LOCKSUFF);
3969 sprintf(lpath, "%s" LOCKSUFF, path);
3970 strcpy(dpath, path);
3972 dpath = lpath + len + sizeof(LOCKNAME);
3973 sprintf(lpath, "%s" LOCKNAME, path);
3974 sprintf(dpath, "%s" DATANAME, path);
3978 flags |= env->me_flags;
3979 if (flags & MDB_RDONLY) {
3980 /* silently ignore WRITEMAP when we're only getting read access */
3981 flags &= ~MDB_WRITEMAP;
3983 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
3984 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
3987 env->me_flags = flags |= MDB_ENV_ACTIVE;
3991 env->me_path = strdup(path);
3992 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
3993 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
3994 if (!(env->me_dbxs && env->me_path && env->me_dbflags)) {
3999 /* For RDONLY, get lockfile after we know datafile exists */
4000 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
4001 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4007 if (F_ISSET(flags, MDB_RDONLY)) {
4008 oflags = GENERIC_READ;
4009 len = OPEN_EXISTING;
4011 oflags = GENERIC_READ|GENERIC_WRITE;
4014 mode = FILE_ATTRIBUTE_NORMAL;
4015 env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
4016 NULL, len, mode, NULL);
4018 if (F_ISSET(flags, MDB_RDONLY))
4021 oflags = O_RDWR | O_CREAT;
4023 env->me_fd = open(dpath, oflags, mode);
4025 if (env->me_fd == INVALID_HANDLE_VALUE) {
4030 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
4031 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4036 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
4037 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
4038 env->me_mfd = env->me_fd;
4040 /* Synchronous fd for meta writes. Needed even with
4041 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
4044 len = OPEN_EXISTING;
4045 env->me_mfd = CreateFile(dpath, oflags,
4046 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
4047 mode | FILE_FLAG_WRITE_THROUGH, NULL);
4050 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
4052 if (env->me_mfd == INVALID_HANDLE_VALUE) {
4057 DPRINTF(("opened dbenv %p", (void *) env));
4059 rc = mdb_env_share_locks(env, &excl);
4063 if (!((flags & MDB_RDONLY) ||
4064 (env->me_pbuf = calloc(1, env->me_psize))))
4070 mdb_env_close0(env, excl);
4076 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
4078 mdb_env_close0(MDB_env *env, int excl)
4082 if (!(env->me_flags & MDB_ENV_ACTIVE))
4085 /* Doing this here since me_dbxs may not exist during mdb_env_close */
4086 for (i = env->me_maxdbs; --i > MAIN_DBI; )
4087 free(env->me_dbxs[i].md_name.mv_data);
4090 free(env->me_dbflags);
4093 free(env->me_dirty_list);
4094 mdb_midl_free(env->me_free_pgs);
4096 if (env->me_flags & MDB_ENV_TXKEY) {
4097 pthread_key_delete(env->me_txkey);
4099 /* Delete our key from the global list */
4100 for (i=0; i<mdb_tls_nkeys; i++)
4101 if (mdb_tls_keys[i] == env->me_txkey) {
4102 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
4110 munmap(env->me_map, env->me_mapsize);
4112 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
4113 (void) close(env->me_mfd);
4114 if (env->me_fd != INVALID_HANDLE_VALUE)
4115 (void) close(env->me_fd);
4117 pid_t pid = env->me_pid;
4118 /* Clearing readers is done in this function because
4119 * me_txkey with its destructor must be disabled first.
4121 for (i = env->me_numreaders; --i >= 0; )
4122 if (env->me_txns->mti_readers[i].mr_pid == pid)
4123 env->me_txns->mti_readers[i].mr_pid = 0;
4125 if (env->me_rmutex) {
4126 CloseHandle(env->me_rmutex);
4127 if (env->me_wmutex) CloseHandle(env->me_wmutex);
4129 /* Windows automatically destroys the mutexes when
4130 * the last handle closes.
4132 #elif defined(MDB_USE_POSIX_SEM)
4133 if (env->me_rmutex != SEM_FAILED) {
4134 sem_close(env->me_rmutex);
4135 if (env->me_wmutex != SEM_FAILED)
4136 sem_close(env->me_wmutex);
4137 /* If we have the filelock: If we are the
4138 * only remaining user, clean up semaphores.
4141 mdb_env_excl_lock(env, &excl);
4143 sem_unlink(env->me_txns->mti_rmname);
4144 sem_unlink(env->me_txns->mti_wmname);
4148 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
4150 if (env->me_lfd != INVALID_HANDLE_VALUE) {
4153 /* Unlock the lockfile. Windows would have unlocked it
4154 * after closing anyway, but not necessarily at once.
4156 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4159 (void) close(env->me_lfd);
4162 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
4166 mdb_env_copyfd(MDB_env *env, HANDLE fd)
4168 MDB_txn *txn = NULL;
4174 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
4178 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
4181 /* Do the lock/unlock of the reader mutex before starting the
4182 * write txn. Otherwise other read txns could block writers.
4184 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
4189 /* We must start the actual read txn after blocking writers */
4190 mdb_txn_reset0(txn, "reset-stage1");
4192 /* Temporarily block writers until we snapshot the meta pages */
4195 rc = mdb_txn_renew0(txn);
4197 UNLOCK_MUTEX_W(env);
4202 wsize = env->me_psize * 2;
4206 DO_WRITE(rc, fd, ptr, w2, len);
4210 } else if (len > 0) {
4216 /* Non-blocking or async handles are not supported */
4222 UNLOCK_MUTEX_W(env);
4227 wsize = txn->mt_next_pgno * env->me_psize - wsize;
4229 if (wsize > MAX_WRITE)
4233 DO_WRITE(rc, fd, ptr, w2, len);
4237 } else if (len > 0) {
4254 mdb_env_copy(MDB_env *env, const char *path)
4258 HANDLE newfd = INVALID_HANDLE_VALUE;
4260 if (env->me_flags & MDB_NOSUBDIR) {
4261 lpath = (char *)path;
4264 len += sizeof(DATANAME);
4265 lpath = malloc(len);
4268 sprintf(lpath, "%s" DATANAME, path);
4271 /* The destination path must exist, but the destination file must not.
4272 * We don't want the OS to cache the writes, since the source data is
4273 * already in the OS cache.
4276 newfd = CreateFile(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
4277 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
4279 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
4281 if (newfd == INVALID_HANDLE_VALUE) {
4287 /* Set O_DIRECT if the file system supports it */
4288 if ((rc = fcntl(newfd, F_GETFL)) != -1)
4289 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
4291 #ifdef F_NOCACHE /* __APPLE__ */
4292 rc = fcntl(newfd, F_NOCACHE, 1);
4299 rc = mdb_env_copyfd(env, newfd);
4302 if (!(env->me_flags & MDB_NOSUBDIR))
4304 if (newfd != INVALID_HANDLE_VALUE)
4305 if (close(newfd) < 0 && rc == MDB_SUCCESS)
4312 mdb_env_close(MDB_env *env)
4319 VGMEMP_DESTROY(env);
4320 while ((dp = env->me_dpages) != NULL) {
4321 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
4322 env->me_dpages = dp->mp_next;
4326 mdb_env_close0(env, 0);
4330 /** Compare two items pointing at aligned size_t's */
4332 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
4334 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
4335 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
4338 /** Compare two items pointing at aligned unsigned int's */
4340 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
4342 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
4343 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
4346 /** Compare two items pointing at unsigned ints of unknown alignment.
4347 * Nodes and keys are guaranteed to be 2-byte aligned.
4350 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
4352 #if BYTE_ORDER == LITTLE_ENDIAN
4353 unsigned short *u, *c;
4356 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4357 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
4360 } while(!x && u > (unsigned short *)a->mv_data);
4363 return memcmp(a->mv_data, b->mv_data, a->mv_size);
4367 /** Compare two items lexically */
4369 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
4376 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4382 diff = memcmp(a->mv_data, b->mv_data, len);
4383 return diff ? diff : len_diff<0 ? -1 : len_diff;
4386 /** Compare two items in reverse byte order */
4388 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
4390 const unsigned char *p1, *p2, *p1_lim;
4394 p1_lim = (const unsigned char *)a->mv_data;
4395 p1 = (const unsigned char *)a->mv_data + a->mv_size;
4396 p2 = (const unsigned char *)b->mv_data + b->mv_size;
4398 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4404 while (p1 > p1_lim) {
4405 diff = *--p1 - *--p2;
4409 return len_diff<0 ? -1 : len_diff;
4412 /** Search for key within a page, using binary search.
4413 * Returns the smallest entry larger or equal to the key.
4414 * If exactp is non-null, stores whether the found entry was an exact match
4415 * in *exactp (1 or 0).
4416 * Updates the cursor index with the index of the found entry.
4417 * If no entry larger or equal to the key is found, returns NULL.
4420 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
4422 unsigned int i = 0, nkeys;
4425 MDB_page *mp = mc->mc_pg[mc->mc_top];
4426 MDB_node *node = NULL;
4431 nkeys = NUMKEYS(mp);
4436 COPY_PGNO(pgno, mp->mp_pgno);
4437 DPRINTF(("searching %u keys in %s %spage %"Z"u",
4438 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
4445 low = IS_LEAF(mp) ? 0 : 1;
4447 cmp = mc->mc_dbx->md_cmp;
4449 /* Branch pages have no data, so if using integer keys,
4450 * alignment is guaranteed. Use faster mdb_cmp_int.
4452 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
4453 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
4460 nodekey.mv_size = mc->mc_db->md_pad;
4461 node = NODEPTR(mp, 0); /* fake */
4462 while (low <= high) {
4463 i = (low + high) >> 1;
4464 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
4465 rc = cmp(key, &nodekey);
4466 DPRINTF(("found leaf index %u [%s], rc = %i",
4467 i, DKEY(&nodekey), rc));
4476 while (low <= high) {
4477 i = (low + high) >> 1;
4479 node = NODEPTR(mp, i);
4480 nodekey.mv_size = NODEKSZ(node);
4481 nodekey.mv_data = NODEKEY(node);
4483 rc = cmp(key, &nodekey);
4486 DPRINTF(("found leaf index %u [%s], rc = %i",
4487 i, DKEY(&nodekey), rc));
4489 DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
4490 i, DKEY(&nodekey), NODEPGNO(node), rc));
4501 if (rc > 0) { /* Found entry is less than the key. */
4502 i++; /* Skip to get the smallest entry larger than key. */
4504 node = NODEPTR(mp, i);
4507 *exactp = (rc == 0);
4508 /* store the key index */
4509 mc->mc_ki[mc->mc_top] = i;
4511 /* There is no entry larger or equal to the key. */
4514 /* nodeptr is fake for LEAF2 */
4520 mdb_cursor_adjust(MDB_cursor *mc, func)
4524 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4525 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
4532 /** Pop a page off the top of the cursor's stack. */
4534 mdb_cursor_pop(MDB_cursor *mc)
4538 MDB_page *top = mc->mc_pg[mc->mc_top];
4544 DPRINTF(("popped page %"Z"u off db %d cursor %p", top->mp_pgno,
4545 DDBI(mc), (void *) mc));
4549 /** Push a page onto the top of the cursor's stack. */
4551 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
4553 DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
4554 DDBI(mc), (void *) mc));
4556 if (mc->mc_snum >= CURSOR_STACK) {
4557 assert(mc->mc_snum < CURSOR_STACK);
4558 return MDB_CURSOR_FULL;
4561 mc->mc_top = mc->mc_snum++;
4562 mc->mc_pg[mc->mc_top] = mp;
4563 mc->mc_ki[mc->mc_top] = 0;
4568 /** Find the address of the page corresponding to a given page number.
4569 * @param[in] txn the transaction for this access.
4570 * @param[in] pgno the page number for the page to retrieve.
4571 * @param[out] ret address of a pointer where the page's address will be stored.
4572 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
4573 * @return 0 on success, non-zero on failure.
4576 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
4578 MDB_env *env = txn->mt_env;
4582 if (!((txn->mt_flags & MDB_TXN_RDONLY) | (env->me_flags & MDB_WRITEMAP))) {
4586 MDB_ID2L dl = tx2->mt_u.dirty_list;
4588 /* Spilled pages were dirtied in this txn and flushed
4589 * because the dirty list got full. Bring this page
4590 * back in from the map (but don't unspill it here,
4591 * leave that unless page_touch happens again).
4593 if (tx2->mt_spill_pgs) {
4594 MDB_ID pn = pgno << 1;
4595 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
4596 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
4597 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
4602 unsigned x = mdb_mid2l_search(dl, pgno);
4603 if (x <= dl[0].mid && dl[x].mid == pgno) {
4609 } while ((tx2 = tx2->mt_parent) != NULL);
4612 if (pgno < txn->mt_next_pgno) {
4614 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
4616 DPRINTF(("page %"Z"u not found", pgno));
4618 return MDB_PAGE_NOTFOUND;
4628 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
4629 * The cursor is at the root page, set up the rest of it.
4632 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
4634 MDB_page *mp = mc->mc_pg[mc->mc_top];
4638 while (IS_BRANCH(mp)) {
4642 DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
4643 assert(NUMKEYS(mp) > 1);
4644 DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
4646 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
4648 if (flags & MDB_PS_LAST)
4649 i = NUMKEYS(mp) - 1;
4652 node = mdb_node_search(mc, key, &exact);
4654 i = NUMKEYS(mp) - 1;
4656 i = mc->mc_ki[mc->mc_top];
4662 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
4665 assert(i < NUMKEYS(mp));
4666 node = NODEPTR(mp, i);
4668 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4671 mc->mc_ki[mc->mc_top] = i;
4672 if ((rc = mdb_cursor_push(mc, mp)))
4675 if (flags & MDB_PS_MODIFY) {
4676 if ((rc = mdb_page_touch(mc)) != 0)
4678 mp = mc->mc_pg[mc->mc_top];
4683 DPRINTF(("internal error, index points to a %02X page!?",
4685 return MDB_CORRUPTED;
4688 DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
4689 key ? DKEY(key) : "null"));
4690 mc->mc_flags |= C_INITIALIZED;
4691 mc->mc_flags &= ~C_EOF;
4696 /** Search for the lowest key under the current branch page.
4697 * This just bypasses a NUMKEYS check in the current page
4698 * before calling mdb_page_search_root(), because the callers
4699 * are all in situations where the current page is known to
4703 mdb_page_search_lowest(MDB_cursor *mc)
4705 MDB_page *mp = mc->mc_pg[mc->mc_top];
4706 MDB_node *node = NODEPTR(mp, 0);
4709 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4712 mc->mc_ki[mc->mc_top] = 0;
4713 if ((rc = mdb_cursor_push(mc, mp)))
4715 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
4718 /** Search for the page a given key should be in.
4719 * Push it and its parent pages on the cursor stack.
4720 * @param[in,out] mc the cursor for this operation.
4721 * @param[in] key the key to search for, or NULL for first/last page.
4722 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
4723 * are touched (updated with new page numbers).
4724 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
4725 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
4726 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
4727 * @return 0 on success, non-zero on failure.
4730 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
4735 /* Make sure the txn is still viable, then find the root from
4736 * the txn's db table and set it as the root of the cursor's stack.
4738 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
4739 DPUTS("transaction has failed, must abort");
4742 /* Make sure we're using an up-to-date root */
4743 if (*mc->mc_dbflag & DB_STALE) {
4745 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
4746 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
4753 MDB_node *leaf = mdb_node_search(&mc2,
4754 &mc->mc_dbx->md_name, &exact);
4756 return MDB_NOTFOUND;
4757 rc = mdb_node_read(mc->mc_txn, leaf, &data);
4760 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
4762 /* The txn may not know this DBI, or another process may
4763 * have dropped and recreated the DB with other flags.
4765 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
4766 return MDB_INCOMPATIBLE;
4767 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
4769 *mc->mc_dbflag &= ~DB_STALE;
4771 root = mc->mc_db->md_root;
4773 if (root == P_INVALID) { /* Tree is empty. */
4774 DPUTS("tree is empty");
4775 return MDB_NOTFOUND;
4780 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
4781 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0], NULL)) != 0)
4787 DPRINTF(("db %d root page %"Z"u has flags 0x%X",
4788 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
4790 if (flags & MDB_PS_MODIFY) {
4791 if ((rc = mdb_page_touch(mc)))
4795 if (flags & MDB_PS_ROOTONLY)
4798 return mdb_page_search_root(mc, key, flags);
4802 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
4804 MDB_txn *txn = mc->mc_txn;
4805 pgno_t pg = mp->mp_pgno;
4806 unsigned x = 0, ovpages = mp->mp_pages;
4807 MDB_env *env = txn->mt_env;
4808 MDB_IDL sl = txn->mt_spill_pgs;
4809 MDB_ID pn = pg << 1;
4812 DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
4813 /* If the page is dirty or on the spill list we just acquired it,
4814 * so we should give it back to our current free list, if any.
4815 * Otherwise put it onto the list of pages we freed in this txn.
4817 * Won't create me_pghead: me_pglast must be inited along with it.
4818 * Unsupported in nested txns: They would need to hide the page
4819 * range in ancestor txns' dirty and spilled lists.
4821 if (env->me_pghead &&
4823 ((mp->mp_flags & P_DIRTY) ||
4824 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
4828 MDB_ID2 *dl, ix, iy;
4829 rc = mdb_midl_need(&env->me_pghead, ovpages);
4832 if (!(mp->mp_flags & P_DIRTY)) {
4833 /* This page is no longer spilled */
4840 /* Remove from dirty list */
4841 dl = txn->mt_u.dirty_list;
4843 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
4851 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
4852 txn->mt_flags |= MDB_TXN_ERROR;
4853 return MDB_CORRUPTED;
4856 if (!(env->me_flags & MDB_WRITEMAP))
4857 mdb_dpage_free(env, mp);
4859 /* Insert in me_pghead */
4860 mop = env->me_pghead;
4861 j = mop[0] + ovpages;
4862 for (i = mop[0]; i && mop[i] < pg; i--)
4868 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
4872 mc->mc_db->md_overflow_pages -= ovpages;
4876 /** Return the data associated with a given node.
4877 * @param[in] txn The transaction for this operation.
4878 * @param[in] leaf The node being read.
4879 * @param[out] data Updated to point to the node's data.
4880 * @return 0 on success, non-zero on failure.
4883 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
4885 MDB_page *omp; /* overflow page */
4889 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
4890 data->mv_size = NODEDSZ(leaf);
4891 data->mv_data = NODEDATA(leaf);
4895 /* Read overflow data.
4897 data->mv_size = NODEDSZ(leaf);
4898 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
4899 if ((rc = mdb_page_get(txn, pgno, &omp, NULL)) != 0) {
4900 DPRINTF(("read overflow page %"Z"u failed", pgno));
4903 data->mv_data = METADATA(omp);
4909 mdb_get(MDB_txn *txn, MDB_dbi dbi,
4910 MDB_val *key, MDB_val *data)
4919 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
4921 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
4924 if (txn->mt_flags & MDB_TXN_ERROR)
4927 if (key->mv_size > MDB_MAXKEYSIZE) {
4928 return MDB_BAD_VALSIZE;
4931 mdb_cursor_init(&mc, txn, dbi, &mx);
4932 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
4935 /** Find a sibling for a page.
4936 * Replaces the page at the top of the cursor's stack with the
4937 * specified sibling, if one exists.
4938 * @param[in] mc The cursor for this operation.
4939 * @param[in] move_right Non-zero if the right sibling is requested,
4940 * otherwise the left sibling.
4941 * @return 0 on success, non-zero on failure.
4944 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
4950 if (mc->mc_snum < 2) {
4951 return MDB_NOTFOUND; /* root has no siblings */
4955 DPRINTF(("parent page is page %"Z"u, index %u",
4956 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
4958 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
4959 : (mc->mc_ki[mc->mc_top] == 0)) {
4960 DPRINTF(("no more keys left, moving to %s sibling",
4961 move_right ? "right" : "left"));
4962 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
4963 /* undo cursor_pop before returning */
4970 mc->mc_ki[mc->mc_top]++;
4972 mc->mc_ki[mc->mc_top]--;
4973 DPRINTF(("just moving to %s index key %u",
4974 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
4976 assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
4978 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4979 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL)) != 0) {
4980 /* mc will be inconsistent if caller does mc_snum++ as above */
4981 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
4985 mdb_cursor_push(mc, mp);
4987 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
4992 /** Move the cursor to the next data item. */
4994 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5000 if (mc->mc_flags & C_EOF) {
5001 return MDB_NOTFOUND;
5004 assert(mc->mc_flags & C_INITIALIZED);
5006 mp = mc->mc_pg[mc->mc_top];
5008 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5009 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5010 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5011 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
5012 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
5013 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
5014 if (rc == MDB_SUCCESS)
5015 MDB_GET_KEY(leaf, key);
5020 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5021 if (op == MDB_NEXT_DUP)
5022 return MDB_NOTFOUND;
5026 DPRINTF(("cursor_next: top page is %"Z"u in cursor %p", mp->mp_pgno, (void *) mc));
5027 if (mc->mc_flags & C_DEL)
5030 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
5031 DPUTS("=====> move to next sibling page");
5032 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5033 mc->mc_flags |= C_EOF;
5036 mp = mc->mc_pg[mc->mc_top];
5037 DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5039 mc->mc_ki[mc->mc_top]++;
5042 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5043 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5046 key->mv_size = mc->mc_db->md_pad;
5047 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5051 assert(IS_LEAF(mp));
5052 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5054 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5055 mdb_xcursor_init1(mc, leaf);
5058 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5061 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5062 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5063 if (rc != MDB_SUCCESS)
5068 MDB_GET_KEY(leaf, key);
5072 /** Move the cursor to the previous data item. */
5074 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5080 assert(mc->mc_flags & C_INITIALIZED);
5082 mp = mc->mc_pg[mc->mc_top];
5084 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5085 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5086 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5087 if (op == MDB_PREV || op == MDB_PREV_DUP) {
5088 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
5089 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
5090 if (rc == MDB_SUCCESS)
5091 MDB_GET_KEY(leaf, key);
5095 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5096 if (op == MDB_PREV_DUP)
5097 return MDB_NOTFOUND;
5102 DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p", mp->mp_pgno, (void *) mc));
5104 if (mc->mc_ki[mc->mc_top] == 0) {
5105 DPUTS("=====> move to prev sibling page");
5106 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
5109 mp = mc->mc_pg[mc->mc_top];
5110 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
5111 DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5113 mc->mc_ki[mc->mc_top]--;
5115 mc->mc_flags &= ~C_EOF;
5117 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5118 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5121 key->mv_size = mc->mc_db->md_pad;
5122 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5126 assert(IS_LEAF(mp));
5127 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5129 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5130 mdb_xcursor_init1(mc, leaf);
5133 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5136 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5137 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5138 if (rc != MDB_SUCCESS)
5143 MDB_GET_KEY(leaf, key);
5147 /** Set the cursor on a specific data item. */
5149 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5150 MDB_cursor_op op, int *exactp)
5154 MDB_node *leaf = NULL;
5159 if (key->mv_size == 0)
5160 return MDB_BAD_VALSIZE;
5163 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5165 /* See if we're already on the right page */
5166 if (mc->mc_flags & C_INITIALIZED) {
5169 mp = mc->mc_pg[mc->mc_top];
5171 mc->mc_ki[mc->mc_top] = 0;
5172 return MDB_NOTFOUND;
5174 if (mp->mp_flags & P_LEAF2) {
5175 nodekey.mv_size = mc->mc_db->md_pad;
5176 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
5178 leaf = NODEPTR(mp, 0);
5179 MDB_GET_KEY2(leaf, nodekey);
5181 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5183 /* Probably happens rarely, but first node on the page
5184 * was the one we wanted.
5186 mc->mc_ki[mc->mc_top] = 0;
5193 unsigned int nkeys = NUMKEYS(mp);
5195 if (mp->mp_flags & P_LEAF2) {
5196 nodekey.mv_data = LEAF2KEY(mp,
5197 nkeys-1, nodekey.mv_size);
5199 leaf = NODEPTR(mp, nkeys-1);
5200 MDB_GET_KEY2(leaf, nodekey);
5202 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5204 /* last node was the one we wanted */
5205 mc->mc_ki[mc->mc_top] = nkeys-1;
5211 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
5212 /* This is definitely the right page, skip search_page */
5213 if (mp->mp_flags & P_LEAF2) {
5214 nodekey.mv_data = LEAF2KEY(mp,
5215 mc->mc_ki[mc->mc_top], nodekey.mv_size);
5217 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5218 MDB_GET_KEY2(leaf, nodekey);
5220 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5222 /* current node was the one we wanted */
5232 /* If any parents have right-sibs, search.
5233 * Otherwise, there's nothing further.
5235 for (i=0; i<mc->mc_top; i++)
5237 NUMKEYS(mc->mc_pg[i])-1)
5239 if (i == mc->mc_top) {
5240 /* There are no other pages */
5241 mc->mc_ki[mc->mc_top] = nkeys;
5242 return MDB_NOTFOUND;
5246 /* There are no other pages */
5247 mc->mc_ki[mc->mc_top] = 0;
5248 if (op == MDB_SET_RANGE) {
5252 return MDB_NOTFOUND;
5256 rc = mdb_page_search(mc, key, 0);
5257 if (rc != MDB_SUCCESS)
5260 mp = mc->mc_pg[mc->mc_top];
5261 assert(IS_LEAF(mp));
5264 leaf = mdb_node_search(mc, key, exactp);
5265 if (exactp != NULL && !*exactp) {
5266 /* MDB_SET specified and not an exact match. */
5267 return MDB_NOTFOUND;
5271 DPUTS("===> inexact leaf not found, goto sibling");
5272 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
5273 return rc; /* no entries matched */
5274 mp = mc->mc_pg[mc->mc_top];
5275 assert(IS_LEAF(mp));
5276 leaf = NODEPTR(mp, 0);
5280 mc->mc_flags |= C_INITIALIZED;
5281 mc->mc_flags &= ~C_EOF;
5284 key->mv_size = mc->mc_db->md_pad;
5285 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5289 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5290 mdb_xcursor_init1(mc, leaf);
5293 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5294 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
5295 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5298 if (op == MDB_GET_BOTH) {
5304 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
5305 if (rc != MDB_SUCCESS)
5308 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
5310 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
5312 rc = mc->mc_dbx->md_dcmp(data, &d2);
5314 if (op == MDB_GET_BOTH || rc > 0)
5315 return MDB_NOTFOUND;
5321 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5322 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5327 /* The key already matches in all other cases */
5328 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
5329 MDB_GET_KEY(leaf, key);
5330 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
5335 /** Move the cursor to the first item in the database. */
5337 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5343 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5345 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5346 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
5347 if (rc != MDB_SUCCESS)
5350 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
5352 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
5353 mc->mc_flags |= C_INITIALIZED;
5354 mc->mc_flags &= ~C_EOF;
5356 mc->mc_ki[mc->mc_top] = 0;
5358 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5359 key->mv_size = mc->mc_db->md_pad;
5360 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
5365 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5366 mdb_xcursor_init1(mc, leaf);
5367 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5371 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5375 MDB_GET_KEY(leaf, key);
5379 /** Move the cursor to the last item in the database. */
5381 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5387 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5389 if (!(mc->mc_flags & C_EOF)) {
5391 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5392 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
5393 if (rc != MDB_SUCCESS)
5396 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
5399 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
5400 mc->mc_flags |= C_INITIALIZED|C_EOF;
5401 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5403 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5404 key->mv_size = mc->mc_db->md_pad;
5405 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
5410 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5411 mdb_xcursor_init1(mc, leaf);
5412 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5416 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5421 MDB_GET_KEY(leaf, key);
5426 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5431 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
5435 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
5439 case MDB_GET_CURRENT:
5440 if (!(mc->mc_flags & C_INITIALIZED)) {
5443 MDB_page *mp = mc->mc_pg[mc->mc_top];
5444 int nkeys = NUMKEYS(mp);
5445 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
5446 mc->mc_ki[mc->mc_top] = nkeys;
5452 key->mv_size = mc->mc_db->md_pad;
5453 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5455 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5456 MDB_GET_KEY(leaf, key);
5458 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5459 if (mc->mc_flags & C_DEL)
5460 mdb_xcursor_init1(mc, leaf);
5461 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
5463 rc = mdb_node_read(mc->mc_txn, leaf, data);
5470 case MDB_GET_BOTH_RANGE:
5475 if (mc->mc_xcursor == NULL) {
5476 rc = MDB_INCOMPATIBLE;
5485 } else if (key->mv_size > MDB_MAXKEYSIZE) {
5486 rc = MDB_BAD_VALSIZE;
5487 } else if (op == MDB_SET_RANGE)
5488 rc = mdb_cursor_set(mc, key, data, op, NULL);
5490 rc = mdb_cursor_set(mc, key, data, op, &exact);
5492 case MDB_GET_MULTIPLE:
5493 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5497 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5498 rc = MDB_INCOMPATIBLE;
5502 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
5503 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
5506 case MDB_NEXT_MULTIPLE:
5511 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5512 rc = MDB_INCOMPATIBLE;
5515 if (!(mc->mc_flags & C_INITIALIZED))
5516 rc = mdb_cursor_first(mc, key, data);
5518 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
5519 if (rc == MDB_SUCCESS) {
5520 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
5523 mx = &mc->mc_xcursor->mx_cursor;
5524 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
5526 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
5527 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
5535 case MDB_NEXT_NODUP:
5536 if (!(mc->mc_flags & C_INITIALIZED))
5537 rc = mdb_cursor_first(mc, key, data);
5539 rc = mdb_cursor_next(mc, key, data, op);
5543 case MDB_PREV_NODUP:
5544 if (!(mc->mc_flags & C_INITIALIZED)) {
5545 rc = mdb_cursor_last(mc, key, data);
5548 mc->mc_flags |= C_INITIALIZED;
5549 mc->mc_ki[mc->mc_top]++;
5551 rc = mdb_cursor_prev(mc, key, data, op);
5554 rc = mdb_cursor_first(mc, key, data);
5557 mfunc = mdb_cursor_first;
5559 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5563 if (mc->mc_xcursor == NULL) {
5564 rc = MDB_INCOMPATIBLE;
5567 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
5571 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
5574 rc = mdb_cursor_last(mc, key, data);
5577 mfunc = mdb_cursor_last;
5580 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
5585 if (mc->mc_flags & C_DEL)
5586 mc->mc_flags ^= C_DEL;
5591 /** Touch all the pages in the cursor stack. Set mc_top.
5592 * Makes sure all the pages are writable, before attempting a write operation.
5593 * @param[in] mc The cursor to operate on.
5596 mdb_cursor_touch(MDB_cursor *mc)
5598 int rc = MDB_SUCCESS;
5600 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
5603 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
5604 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
5607 *mc->mc_dbflag |= DB_DIRTY;
5612 rc = mdb_page_touch(mc);
5613 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
5614 mc->mc_top = mc->mc_snum-1;
5619 /** Do not spill pages to disk if txn is getting full, may fail instead */
5620 #define MDB_NOSPILL 0x8000
5623 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5626 enum { MDB_NO_ROOT = MDB_LAST_ERRCODE+10 }; /* internal code */
5627 MDB_env *env = mc->mc_txn->mt_env;
5628 MDB_node *leaf = NULL;
5629 MDB_val xdata, *rdata, dkey;
5631 int do_sub = 0, insert = 0;
5632 unsigned int mcount = 0, dcount = 0, nospill;
5635 char dbuf[MDB_MAXKEYSIZE+1];
5636 unsigned int nflags;
5639 /* Check this first so counter will always be zero on any
5642 if (flags & MDB_MULTIPLE) {
5643 dcount = data[1].mv_size;
5644 data[1].mv_size = 0;
5645 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
5646 return MDB_INCOMPATIBLE;
5649 nospill = flags & MDB_NOSPILL;
5650 flags &= ~MDB_NOSPILL;
5652 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
5653 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
5655 if (flags != MDB_CURRENT && (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE))
5656 return MDB_BAD_VALSIZE;
5658 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT) && data->mv_size > MDB_MAXKEYSIZE)
5659 return MDB_BAD_VALSIZE;
5661 #if SIZE_MAX > MAXDATASIZE
5662 if (data->mv_size > MAXDATASIZE)
5663 return MDB_BAD_VALSIZE;
5666 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
5667 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
5671 if (flags == MDB_CURRENT) {
5672 if (!(mc->mc_flags & C_INITIALIZED))
5675 } else if (mc->mc_db->md_root == P_INVALID) {
5676 /* new database, cursor has nothing to point to */
5679 mc->mc_flags &= ~C_INITIALIZED;
5684 if (flags & MDB_APPEND) {
5686 rc = mdb_cursor_last(mc, &k2, &d2);
5688 rc = mc->mc_dbx->md_cmp(key, &k2);
5691 mc->mc_ki[mc->mc_top]++;
5693 /* new key is <= last key */
5698 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
5700 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
5701 DPRINTF(("duplicate key [%s]", DKEY(key)));
5703 return MDB_KEYEXIST;
5705 if (rc && rc != MDB_NOTFOUND)
5709 if (mc->mc_flags & C_DEL)
5710 mc->mc_flags ^= C_DEL;
5712 /* Cursor is positioned, check for room in the dirty list */
5714 if (flags & MDB_MULTIPLE) {
5716 xdata.mv_size = data->mv_size * dcount;
5720 if ((rc2 = mdb_page_spill(mc, key, rdata)))
5724 if (rc == MDB_NO_ROOT) {
5726 /* new database, write a root leaf page */
5727 DPUTS("allocating new root leaf page");
5728 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
5731 mdb_cursor_push(mc, np);
5732 mc->mc_db->md_root = np->mp_pgno;
5733 mc->mc_db->md_depth++;
5734 *mc->mc_dbflag |= DB_DIRTY;
5735 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
5737 np->mp_flags |= P_LEAF2;
5738 mc->mc_flags |= C_INITIALIZED;
5740 /* make sure all cursor pages are writable */
5741 rc2 = mdb_cursor_touch(mc);
5746 /* The key already exists */
5747 if (rc == MDB_SUCCESS) {
5751 /* there's only a key anyway, so this is a no-op */
5752 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5753 unsigned int ksize = mc->mc_db->md_pad;
5754 if (key->mv_size != ksize)
5755 return MDB_BAD_VALSIZE;
5756 if (flags == MDB_CURRENT) {
5757 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
5758 memcpy(ptr, key->mv_data, ksize);
5764 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5765 olddata.mv_size = NODEDSZ(leaf);
5766 olddata.mv_data = NODEDATA(leaf);
5769 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
5770 mp = fp = xdata.mv_data = env->me_pbuf;
5771 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
5773 /* Was a single item before, must convert now */
5774 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5775 /* Just overwrite the current item */
5776 if (flags == MDB_CURRENT)
5780 #if UINT_MAX < SIZE_MAX
5781 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && dkey.mv_size == sizeof(size_t))
5782 #ifdef MISALIGNED_OK
5783 mc->mc_dbx->md_dcmp = mdb_cmp_long;
5785 mc->mc_dbx->md_dcmp = mdb_cmp_cint;
5788 /* if data matches, skip it */
5789 if (!mc->mc_dbx->md_dcmp(data, &dkey)) {
5790 if (flags & MDB_NODUPDATA)
5792 else if (flags & MDB_MULTIPLE)
5799 /* create a fake page for the dup items */
5800 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
5801 dkey.mv_data = dbuf;
5802 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
5803 fp->mp_lower = PAGEHDRSZ;
5804 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
5805 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5806 fp->mp_flags |= P_LEAF2;
5807 fp->mp_pad = data->mv_size;
5808 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
5810 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
5811 (dkey.mv_size & 1) + (data->mv_size & 1);
5813 fp->mp_upper = xdata.mv_size;
5814 } else if (leaf->mn_flags & F_SUBDATA) {
5815 /* Data is on sub-DB, just store it */
5816 flags |= F_DUPDATA|F_SUBDATA;
5819 /* See if we need to convert from fake page to subDB */
5820 unsigned int offset;
5824 fp = olddata.mv_data;
5827 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5828 offset = NODESIZE + sizeof(indx_t) + data->mv_size;
5829 offset += offset & 1;
5832 offset = fp->mp_pad;
5833 if (SIZELEFT(fp) < offset) {
5834 offset *= 4; /* space for 4 more */
5837 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
5839 fp->mp_flags |= P_DIRTY;
5840 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
5841 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
5845 fp_flags = fp->mp_flags;
5846 xdata.mv_size = olddata.mv_size + offset;
5847 if (NODESIZE + sizeof(indx_t) + NODEKSZ(leaf) + xdata.mv_size
5848 >= env->me_nodemax) {
5849 /* yes, convert it */
5851 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5852 dummy.md_pad = fp->mp_pad;
5853 dummy.md_flags = MDB_DUPFIXED;
5854 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
5855 dummy.md_flags |= MDB_INTEGERKEY;
5858 dummy.md_branch_pages = 0;
5859 dummy.md_leaf_pages = 1;
5860 dummy.md_overflow_pages = 0;
5861 dummy.md_entries = NUMKEYS(fp);
5862 xdata.mv_size = sizeof(MDB_db);
5863 xdata.mv_data = &dummy;
5864 if ((rc = mdb_page_alloc(mc, 1, &mp)))
5866 offset = env->me_psize - olddata.mv_size;
5867 flags |= F_DUPDATA|F_SUBDATA;
5868 dummy.md_root = mp->mp_pgno;
5869 fp_flags &= ~P_SUBP;
5871 mp->mp_flags = fp_flags | P_DIRTY;
5872 mp->mp_pad = fp->mp_pad;
5873 mp->mp_lower = fp->mp_lower;
5874 mp->mp_upper = fp->mp_upper + offset;
5876 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
5878 memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper,
5879 olddata.mv_size - fp->mp_upper);
5880 for (i=0; i<NUMKEYS(fp); i++)
5881 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
5888 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5892 /* overflow page overwrites need special handling */
5893 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5896 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
5898 memcpy(&pg, olddata.mv_data, sizeof(pg));
5899 if ((rc2 = mdb_page_get(mc->mc_txn, pg, &omp, &level)) != 0)
5901 ovpages = omp->mp_pages;
5903 /* Is the ov page large enough? */
5904 if (ovpages >= dpages) {
5905 if (!(omp->mp_flags & P_DIRTY) &&
5906 (level || (env->me_flags & MDB_WRITEMAP)))
5908 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
5911 level = 0; /* dirty in this txn or clean */
5914 if (omp->mp_flags & P_DIRTY) {
5915 /* yes, overwrite it. Note in this case we don't
5916 * bother to try shrinking the page if the new data
5917 * is smaller than the overflow threshold.
5920 /* It is writable only in a parent txn */
5921 size_t sz = (size_t) env->me_psize * ovpages, off;
5922 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
5928 mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
5929 if (!(flags & MDB_RESERVE)) {
5930 /* Copy end of page, adjusting alignment so
5931 * compiler may copy words instead of bytes.
5933 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
5934 memcpy((size_t *)((char *)np + off),
5935 (size_t *)((char *)omp + off), sz - off);
5938 memcpy(np, omp, sz); /* Copy beginning of page */
5941 SETDSZ(leaf, data->mv_size);
5942 if (F_ISSET(flags, MDB_RESERVE))
5943 data->mv_data = METADATA(omp);
5945 memcpy(METADATA(omp), data->mv_data, data->mv_size);
5949 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
5951 } else if (data->mv_size == olddata.mv_size) {
5952 /* same size, just replace it. Note that we could
5953 * also reuse this node if the new data is smaller,
5954 * but instead we opt to shrink the node in that case.
5956 if (F_ISSET(flags, MDB_RESERVE))
5957 data->mv_data = olddata.mv_data;
5958 else if (data->mv_size)
5959 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
5961 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
5964 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5965 mc->mc_db->md_entries--;
5967 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
5974 nflags = flags & NODE_ADD_FLAGS;
5975 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
5976 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
5977 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
5978 nflags &= ~MDB_APPEND;
5980 nflags |= MDB_SPLIT_REPLACE;
5981 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
5983 /* There is room already in this leaf page. */
5984 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
5985 if (rc == 0 && !do_sub && insert) {
5986 /* Adjust other cursors pointing to mp */
5987 MDB_cursor *m2, *m3;
5988 MDB_dbi dbi = mc->mc_dbi;
5989 unsigned i = mc->mc_top;
5990 MDB_page *mp = mc->mc_pg[i];
5992 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5993 if (mc->mc_flags & C_SUB)
5994 m3 = &m2->mc_xcursor->mx_cursor;
5997 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
5998 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
6005 if (rc != MDB_SUCCESS)
6006 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6008 /* Now store the actual data in the child DB. Note that we're
6009 * storing the user data in the keys field, so there are strict
6010 * size limits on dupdata. The actual data fields of the child
6011 * DB are all zero size.
6018 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6019 if (flags & MDB_CURRENT) {
6020 xflags = MDB_CURRENT|MDB_NOSPILL;
6022 mdb_xcursor_init1(mc, leaf);
6023 xflags = (flags & MDB_NODUPDATA) ?
6024 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
6026 /* converted, write the original data first */
6028 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
6032 /* Adjust other cursors pointing to mp */
6034 unsigned i = mc->mc_top;
6035 MDB_page *mp = mc->mc_pg[i];
6037 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6038 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6039 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6040 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
6041 mdb_xcursor_init1(m2, leaf);
6045 /* we've done our job */
6048 if (flags & MDB_APPENDDUP)
6049 xflags |= MDB_APPEND;
6050 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
6051 if (flags & F_SUBDATA) {
6052 void *db = NODEDATA(leaf);
6053 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6056 /* sub-writes might have failed so check rc again.
6057 * Don't increment count if we just replaced an existing item.
6059 if (!rc && !(flags & MDB_CURRENT))
6060 mc->mc_db->md_entries++;
6061 if (flags & MDB_MULTIPLE) {
6065 /* let caller know how many succeeded, if any */
6066 data[1].mv_size = mcount;
6067 if (mcount < dcount) {
6068 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
6075 /* If we succeeded and the key didn't exist before, make sure
6076 * the cursor is marked valid.
6079 mc->mc_flags |= C_INITIALIZED;
6084 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
6090 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
6091 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6093 if (!(mc->mc_flags & C_INITIALIZED))
6096 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6097 return MDB_NOTFOUND;
6099 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
6102 rc = mdb_cursor_touch(mc);
6106 mp = mc->mc_pg[mc->mc_top];
6107 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6109 if (!IS_LEAF2(mp) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6110 if (!(flags & MDB_NODUPDATA)) {
6111 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
6112 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6114 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
6115 /* If sub-DB still has entries, we're done */
6116 if (mc->mc_xcursor->mx_db.md_entries) {
6117 if (leaf->mn_flags & F_SUBDATA) {
6118 /* update subDB info */
6119 void *db = NODEDATA(leaf);
6120 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6123 /* shrink fake page */
6124 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
6125 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6126 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6127 /* fix other sub-DB cursors pointed at this fake page */
6128 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6129 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6130 if (m2->mc_pg[mc->mc_top] == mp &&
6131 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
6132 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6135 mc->mc_db->md_entries--;
6136 mc->mc_flags |= C_DEL;
6139 /* otherwise fall thru and delete the sub-DB */
6142 if (leaf->mn_flags & F_SUBDATA) {
6143 /* add all the child DB's pages to the free list */
6144 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6145 if (rc == MDB_SUCCESS) {
6146 mc->mc_db->md_entries -=
6147 mc->mc_xcursor->mx_db.md_entries;
6152 return mdb_cursor_del0(mc, leaf);
6155 /** Allocate and initialize new pages for a database.
6156 * @param[in] mc a cursor on the database being added to.
6157 * @param[in] flags flags defining what type of page is being allocated.
6158 * @param[in] num the number of pages to allocate. This is usually 1,
6159 * unless allocating overflow pages for a large record.
6160 * @param[out] mp Address of a page, or NULL on failure.
6161 * @return 0 on success, non-zero on failure.
6164 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
6169 if ((rc = mdb_page_alloc(mc, num, &np)))
6171 DPRINTF(("allocated new mpage %"Z"u, page size %u",
6172 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
6173 np->mp_flags = flags | P_DIRTY;
6174 np->mp_lower = PAGEHDRSZ;
6175 np->mp_upper = mc->mc_txn->mt_env->me_psize;
6178 mc->mc_db->md_branch_pages++;
6179 else if (IS_LEAF(np))
6180 mc->mc_db->md_leaf_pages++;
6181 else if (IS_OVERFLOW(np)) {
6182 mc->mc_db->md_overflow_pages += num;
6190 /** Calculate the size of a leaf node.
6191 * The size depends on the environment's page size; if a data item
6192 * is too large it will be put onto an overflow page and the node
6193 * size will only include the key and not the data. Sizes are always
6194 * rounded up to an even number of bytes, to guarantee 2-byte alignment
6195 * of the #MDB_node headers.
6196 * @param[in] env The environment handle.
6197 * @param[in] key The key for the node.
6198 * @param[in] data The data for the node.
6199 * @return The number of bytes needed to store the node.
6202 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
6206 sz = LEAFSIZE(key, data);
6207 if (sz >= env->me_nodemax) {
6208 /* put on overflow page */
6209 sz -= data->mv_size - sizeof(pgno_t);
6213 return sz + sizeof(indx_t);
6216 /** Calculate the size of a branch node.
6217 * The size should depend on the environment's page size but since
6218 * we currently don't support spilling large keys onto overflow
6219 * pages, it's simply the size of the #MDB_node header plus the
6220 * size of the key. Sizes are always rounded up to an even number
6221 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
6222 * @param[in] env The environment handle.
6223 * @param[in] key The key for the node.
6224 * @return The number of bytes needed to store the node.
6227 mdb_branch_size(MDB_env *env, MDB_val *key)
6232 if (sz >= env->me_nodemax) {
6233 /* put on overflow page */
6234 /* not implemented */
6235 /* sz -= key->size - sizeof(pgno_t); */
6238 return sz + sizeof(indx_t);
6241 /** Add a node to the page pointed to by the cursor.
6242 * @param[in] mc The cursor for this operation.
6243 * @param[in] indx The index on the page where the new node should be added.
6244 * @param[in] key The key for the new node.
6245 * @param[in] data The data for the new node, if any.
6246 * @param[in] pgno The page number, if adding a branch node.
6247 * @param[in] flags Flags for the node.
6248 * @return 0 on success, non-zero on failure. Possible errors are:
6250 * <li>ENOMEM - failed to allocate overflow pages for the node.
6251 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
6252 * should never happen since all callers already calculate the
6253 * page's free space before calling this function.
6257 mdb_node_add(MDB_cursor *mc, indx_t indx,
6258 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
6261 size_t node_size = NODESIZE;
6265 MDB_page *mp = mc->mc_pg[mc->mc_top];
6266 MDB_page *ofp = NULL; /* overflow page */
6269 assert(mp->mp_upper >= mp->mp_lower);
6271 DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
6272 IS_LEAF(mp) ? "leaf" : "branch",
6273 IS_SUBP(mp) ? "sub-" : "",
6274 mp->mp_pgno, indx, data ? data->mv_size : 0,
6275 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
6278 /* Move higher keys up one slot. */
6279 int ksize = mc->mc_db->md_pad, dif;
6280 char *ptr = LEAF2KEY(mp, indx, ksize);
6281 dif = NUMKEYS(mp) - indx;
6283 memmove(ptr+ksize, ptr, dif*ksize);
6284 /* insert new key */
6285 memcpy(ptr, key->mv_data, ksize);
6287 /* Just using these for counting */
6288 mp->mp_lower += sizeof(indx_t);
6289 mp->mp_upper -= ksize - sizeof(indx_t);
6293 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
6295 node_size += key->mv_size;
6298 if (F_ISSET(flags, F_BIGDATA)) {
6299 /* Data already on overflow page. */
6300 node_size += sizeof(pgno_t);
6301 } else if (node_size + data->mv_size >= mc->mc_txn->mt_env->me_nodemax) {
6302 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
6304 /* Put data on overflow page. */
6305 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
6306 data->mv_size, node_size+data->mv_size));
6307 node_size += sizeof(pgno_t) + (node_size & 1);
6308 if ((ssize_t)node_size > room)
6310 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
6312 DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
6316 node_size += data->mv_size;
6319 node_size += node_size & 1;
6320 if ((ssize_t)node_size > room)
6324 /* Move higher pointers up one slot. */
6325 for (i = NUMKEYS(mp); i > indx; i--)
6326 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
6328 /* Adjust free space offsets. */
6329 ofs = mp->mp_upper - node_size;
6330 assert(ofs >= mp->mp_lower + sizeof(indx_t));
6331 mp->mp_ptrs[indx] = ofs;
6333 mp->mp_lower += sizeof(indx_t);
6335 /* Write the node data. */
6336 node = NODEPTR(mp, indx);
6337 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
6338 node->mn_flags = flags;
6340 SETDSZ(node,data->mv_size);
6345 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6350 if (F_ISSET(flags, F_BIGDATA))
6351 memcpy(node->mn_data + key->mv_size, data->mv_data,
6353 else if (F_ISSET(flags, MDB_RESERVE))
6354 data->mv_data = node->mn_data + key->mv_size;
6356 memcpy(node->mn_data + key->mv_size, data->mv_data,
6359 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
6361 if (F_ISSET(flags, MDB_RESERVE))
6362 data->mv_data = METADATA(ofp);
6364 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
6371 DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
6372 mp->mp_pgno, NUMKEYS(mp)));
6373 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
6374 DPRINTF(("node size = %"Z"u", node_size));
6375 return MDB_PAGE_FULL;
6378 /** Delete the specified node from a page.
6379 * @param[in] mp The page to operate on.
6380 * @param[in] indx The index of the node to delete.
6381 * @param[in] ksize The size of a node. Only used if the page is
6382 * part of a #MDB_DUPFIXED database.
6385 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
6388 indx_t i, j, numkeys, ptr;
6395 COPY_PGNO(pgno, mp->mp_pgno);
6396 DPRINTF(("delete node %u on %s page %"Z"u", indx,
6397 IS_LEAF(mp) ? "leaf" : "branch", pgno));
6400 assert(indx < NUMKEYS(mp));
6403 int x = NUMKEYS(mp) - 1 - indx;
6404 base = LEAF2KEY(mp, indx, ksize);
6406 memmove(base, base + ksize, x * ksize);
6407 mp->mp_lower -= sizeof(indx_t);
6408 mp->mp_upper += ksize - sizeof(indx_t);
6412 node = NODEPTR(mp, indx);
6413 sz = NODESIZE + node->mn_ksize;
6415 if (F_ISSET(node->mn_flags, F_BIGDATA))
6416 sz += sizeof(pgno_t);
6418 sz += NODEDSZ(node);
6422 ptr = mp->mp_ptrs[indx];
6423 numkeys = NUMKEYS(mp);
6424 for (i = j = 0; i < numkeys; i++) {
6426 mp->mp_ptrs[j] = mp->mp_ptrs[i];
6427 if (mp->mp_ptrs[i] < ptr)
6428 mp->mp_ptrs[j] += sz;
6433 base = (char *)mp + mp->mp_upper;
6434 memmove(base + sz, base, ptr - mp->mp_upper);
6436 mp->mp_lower -= sizeof(indx_t);
6440 /** Compact the main page after deleting a node on a subpage.
6441 * @param[in] mp The main page to operate on.
6442 * @param[in] indx The index of the subpage on the main page.
6445 mdb_node_shrink(MDB_page *mp, indx_t indx)
6452 indx_t i, numkeys, ptr;
6454 node = NODEPTR(mp, indx);
6455 sp = (MDB_page *)NODEDATA(node);
6456 osize = NODEDSZ(node);
6458 delta = sp->mp_upper - sp->mp_lower;
6459 SETDSZ(node, osize - delta);
6460 xp = (MDB_page *)((char *)sp + delta);
6462 /* shift subpage upward */
6464 nsize = NUMKEYS(sp) * sp->mp_pad;
6465 memmove(METADATA(xp), METADATA(sp), nsize);
6468 nsize = osize - sp->mp_upper;
6469 numkeys = NUMKEYS(sp);
6470 for (i=numkeys-1; i>=0; i--)
6471 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
6473 xp->mp_upper = sp->mp_lower;
6474 xp->mp_lower = sp->mp_lower;
6475 xp->mp_flags = sp->mp_flags;
6476 xp->mp_pad = sp->mp_pad;
6477 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
6479 /* shift lower nodes upward */
6480 ptr = mp->mp_ptrs[indx];
6481 numkeys = NUMKEYS(mp);
6482 for (i = 0; i < numkeys; i++) {
6483 if (mp->mp_ptrs[i] <= ptr)
6484 mp->mp_ptrs[i] += delta;
6487 base = (char *)mp + mp->mp_upper;
6488 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
6489 mp->mp_upper += delta;
6492 /** Initial setup of a sorted-dups cursor.
6493 * Sorted duplicates are implemented as a sub-database for the given key.
6494 * The duplicate data items are actually keys of the sub-database.
6495 * Operations on the duplicate data items are performed using a sub-cursor
6496 * initialized when the sub-database is first accessed. This function does
6497 * the preliminary setup of the sub-cursor, filling in the fields that
6498 * depend only on the parent DB.
6499 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6502 mdb_xcursor_init0(MDB_cursor *mc)
6504 MDB_xcursor *mx = mc->mc_xcursor;
6506 mx->mx_cursor.mc_xcursor = NULL;
6507 mx->mx_cursor.mc_txn = mc->mc_txn;
6508 mx->mx_cursor.mc_db = &mx->mx_db;
6509 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
6510 mx->mx_cursor.mc_dbi = mc->mc_dbi;
6511 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
6512 mx->mx_cursor.mc_snum = 0;
6513 mx->mx_cursor.mc_top = 0;
6514 mx->mx_cursor.mc_flags = C_SUB;
6515 mx->mx_dbx.md_name.mv_size = 0;
6516 mx->mx_dbx.md_name.mv_data = NULL;
6517 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
6518 mx->mx_dbx.md_dcmp = NULL;
6519 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
6522 /** Final setup of a sorted-dups cursor.
6523 * Sets up the fields that depend on the data from the main cursor.
6524 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6525 * @param[in] node The data containing the #MDB_db record for the
6526 * sorted-dup database.
6529 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
6531 MDB_xcursor *mx = mc->mc_xcursor;
6533 if (node->mn_flags & F_SUBDATA) {
6534 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
6535 mx->mx_cursor.mc_pg[0] = 0;
6536 mx->mx_cursor.mc_snum = 0;
6537 mx->mx_cursor.mc_top = 0;
6538 mx->mx_cursor.mc_flags = C_SUB;
6540 MDB_page *fp = NODEDATA(node);
6541 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
6542 mx->mx_db.md_flags = 0;
6543 mx->mx_db.md_depth = 1;
6544 mx->mx_db.md_branch_pages = 0;
6545 mx->mx_db.md_leaf_pages = 1;
6546 mx->mx_db.md_overflow_pages = 0;
6547 mx->mx_db.md_entries = NUMKEYS(fp);
6548 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
6549 mx->mx_cursor.mc_snum = 1;
6550 mx->mx_cursor.mc_top = 0;
6551 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
6552 mx->mx_cursor.mc_pg[0] = fp;
6553 mx->mx_cursor.mc_ki[0] = 0;
6554 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6555 mx->mx_db.md_flags = MDB_DUPFIXED;
6556 mx->mx_db.md_pad = fp->mp_pad;
6557 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6558 mx->mx_db.md_flags |= MDB_INTEGERKEY;
6561 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
6562 mx->mx_db.md_root));
6563 mx->mx_dbflag = DB_VALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
6564 #if UINT_MAX < SIZE_MAX
6565 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
6566 #ifdef MISALIGNED_OK
6567 mx->mx_dbx.md_cmp = mdb_cmp_long;
6569 mx->mx_dbx.md_cmp = mdb_cmp_cint;
6574 /** Initialize a cursor for a given transaction and database. */
6576 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
6579 mc->mc_backup = NULL;
6582 mc->mc_db = &txn->mt_dbs[dbi];
6583 mc->mc_dbx = &txn->mt_dbxs[dbi];
6584 mc->mc_dbflag = &txn->mt_dbflags[dbi];
6589 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
6591 mc->mc_xcursor = mx;
6592 mdb_xcursor_init0(mc);
6594 mc->mc_xcursor = NULL;
6596 if (*mc->mc_dbflag & DB_STALE) {
6597 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
6602 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
6605 size_t size = sizeof(MDB_cursor);
6607 if (txn == NULL || ret == NULL || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
6610 if (txn->mt_flags & MDB_TXN_ERROR)
6613 /* Allow read access to the freelist */
6614 if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
6617 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
6618 size += sizeof(MDB_xcursor);
6620 if ((mc = malloc(size)) != NULL) {
6621 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
6622 if (txn->mt_cursors) {
6623 mc->mc_next = txn->mt_cursors[dbi];
6624 txn->mt_cursors[dbi] = mc;
6625 mc->mc_flags |= C_UNTRACK;
6637 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
6639 if (txn == NULL || mc == NULL || mc->mc_dbi >= txn->mt_numdbs)
6642 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
6645 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
6649 /* Return the count of duplicate data items for the current key */
6651 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
6655 if (mc == NULL || countp == NULL)
6658 if (mc->mc_xcursor == NULL)
6659 return MDB_INCOMPATIBLE;
6661 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6662 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6665 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
6668 *countp = mc->mc_xcursor->mx_db.md_entries;
6674 mdb_cursor_close(MDB_cursor *mc)
6676 if (mc && !mc->mc_backup) {
6677 /* remove from txn, if tracked */
6678 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
6679 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
6680 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
6682 *prev = mc->mc_next;
6689 mdb_cursor_txn(MDB_cursor *mc)
6691 if (!mc) return NULL;
6696 mdb_cursor_dbi(MDB_cursor *mc)
6702 /** Replace the key for a node with a new key.
6703 * @param[in] mc Cursor pointing to the node to operate on.
6704 * @param[in] key The new key to use.
6705 * @return 0 on success, non-zero on failure.
6708 mdb_update_key(MDB_cursor *mc, MDB_val *key)
6715 indx_t ptr, i, numkeys, indx;
6718 indx = mc->mc_ki[mc->mc_top];
6719 mp = mc->mc_pg[mc->mc_top];
6720 node = NODEPTR(mp, indx);
6721 ptr = mp->mp_ptrs[indx];
6725 char kbuf2[(MDB_MAXKEYSIZE*2+1)];
6726 k2.mv_data = NODEKEY(node);
6727 k2.mv_size = node->mn_ksize;
6728 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
6730 mdb_dkey(&k2, kbuf2),
6736 delta0 = delta = key->mv_size - node->mn_ksize;
6738 /* Must be 2-byte aligned. If new key is
6739 * shorter by 1, the shift will be skipped.
6741 delta += (delta & 1);
6743 if (delta > 0 && SIZELEFT(mp) < delta) {
6745 /* not enough space left, do a delete and split */
6746 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
6747 pgno = NODEPGNO(node);
6748 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
6749 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
6752 numkeys = NUMKEYS(mp);
6753 for (i = 0; i < numkeys; i++) {
6754 if (mp->mp_ptrs[i] <= ptr)
6755 mp->mp_ptrs[i] -= delta;
6758 base = (char *)mp + mp->mp_upper;
6759 len = ptr - mp->mp_upper + NODESIZE;
6760 memmove(base - delta, base, len);
6761 mp->mp_upper -= delta;
6763 node = NODEPTR(mp, indx);
6766 /* But even if no shift was needed, update ksize */
6768 node->mn_ksize = key->mv_size;
6771 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6777 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
6779 /** Move a node from csrc to cdst.
6782 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
6789 unsigned short flags;
6793 /* Mark src and dst as dirty. */
6794 if ((rc = mdb_page_touch(csrc)) ||
6795 (rc = mdb_page_touch(cdst)))
6798 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6799 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
6800 key.mv_size = csrc->mc_db->md_pad;
6801 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
6803 data.mv_data = NULL;
6807 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
6808 assert(!((long)srcnode&1));
6809 srcpg = NODEPGNO(srcnode);
6810 flags = srcnode->mn_flags;
6811 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6812 unsigned int snum = csrc->mc_snum;
6814 /* must find the lowest key below src */
6815 mdb_page_search_lowest(csrc);
6816 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6817 key.mv_size = csrc->mc_db->md_pad;
6818 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6820 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6821 key.mv_size = NODEKSZ(s2);
6822 key.mv_data = NODEKEY(s2);
6824 csrc->mc_snum = snum--;
6825 csrc->mc_top = snum;
6827 key.mv_size = NODEKSZ(srcnode);
6828 key.mv_data = NODEKEY(srcnode);
6830 data.mv_size = NODEDSZ(srcnode);
6831 data.mv_data = NODEDATA(srcnode);
6833 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
6834 unsigned int snum = cdst->mc_snum;
6837 /* must find the lowest key below dst */
6838 mdb_page_search_lowest(cdst);
6839 if (IS_LEAF2(cdst->mc_pg[cdst->mc_top])) {
6840 bkey.mv_size = cdst->mc_db->md_pad;
6841 bkey.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, bkey.mv_size);
6843 s2 = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
6844 bkey.mv_size = NODEKSZ(s2);
6845 bkey.mv_data = NODEKEY(s2);
6847 cdst->mc_snum = snum--;
6848 cdst->mc_top = snum;
6849 mdb_cursor_copy(cdst, &mn);
6851 rc = mdb_update_key(&mn, &bkey);
6856 DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
6857 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
6858 csrc->mc_ki[csrc->mc_top],
6860 csrc->mc_pg[csrc->mc_top]->mp_pgno,
6861 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
6863 /* Add the node to the destination page.
6865 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
6866 if (rc != MDB_SUCCESS)
6869 /* Delete the node from the source page.
6871 mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
6874 /* Adjust other cursors pointing to mp */
6875 MDB_cursor *m2, *m3;
6876 MDB_dbi dbi = csrc->mc_dbi;
6877 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
6879 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6880 if (csrc->mc_flags & C_SUB)
6881 m3 = &m2->mc_xcursor->mx_cursor;
6884 if (m3 == csrc) continue;
6885 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
6886 csrc->mc_ki[csrc->mc_top]) {
6887 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
6888 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
6893 /* Update the parent separators.
6895 if (csrc->mc_ki[csrc->mc_top] == 0) {
6896 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
6897 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6898 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6900 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6901 key.mv_size = NODEKSZ(srcnode);
6902 key.mv_data = NODEKEY(srcnode);
6904 DPRINTF(("update separator for source page %"Z"u to [%s]",
6905 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
6906 mdb_cursor_copy(csrc, &mn);
6909 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
6912 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6914 indx_t ix = csrc->mc_ki[csrc->mc_top];
6915 nullkey.mv_size = 0;
6916 csrc->mc_ki[csrc->mc_top] = 0;
6917 rc = mdb_update_key(csrc, &nullkey);
6918 csrc->mc_ki[csrc->mc_top] = ix;
6919 assert(rc == MDB_SUCCESS);
6923 if (cdst->mc_ki[cdst->mc_top] == 0) {
6924 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
6925 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6926 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
6928 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
6929 key.mv_size = NODEKSZ(srcnode);
6930 key.mv_data = NODEKEY(srcnode);
6932 DPRINTF(("update separator for destination page %"Z"u to [%s]",
6933 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
6934 mdb_cursor_copy(cdst, &mn);
6937 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
6940 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
6942 indx_t ix = cdst->mc_ki[cdst->mc_top];
6943 nullkey.mv_size = 0;
6944 cdst->mc_ki[cdst->mc_top] = 0;
6945 rc = mdb_update_key(cdst, &nullkey);
6946 cdst->mc_ki[cdst->mc_top] = ix;
6947 assert(rc == MDB_SUCCESS);
6954 /** Merge one page into another.
6955 * The nodes from the page pointed to by \b csrc will
6956 * be copied to the page pointed to by \b cdst and then
6957 * the \b csrc page will be freed.
6958 * @param[in] csrc Cursor pointing to the source page.
6959 * @param[in] cdst Cursor pointing to the destination page.
6962 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
6970 DPRINTF(("merging page %"Z"u into %"Z"u", csrc->mc_pg[csrc->mc_top]->mp_pgno,
6971 cdst->mc_pg[cdst->mc_top]->mp_pgno));
6973 assert(csrc->mc_snum > 1); /* can't merge root page */
6974 assert(cdst->mc_snum > 1);
6976 /* Mark dst as dirty. */
6977 if ((rc = mdb_page_touch(cdst)))
6980 /* Move all nodes from src to dst.
6982 j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
6983 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6984 key.mv_size = csrc->mc_db->md_pad;
6985 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
6986 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
6987 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
6988 if (rc != MDB_SUCCESS)
6990 key.mv_data = (char *)key.mv_data + key.mv_size;
6993 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
6994 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
6995 if (i == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6996 unsigned int snum = csrc->mc_snum;
6998 /* must find the lowest key below src */
6999 mdb_page_search_lowest(csrc);
7000 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7001 key.mv_size = csrc->mc_db->md_pad;
7002 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7004 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7005 key.mv_size = NODEKSZ(s2);
7006 key.mv_data = NODEKEY(s2);
7008 csrc->mc_snum = snum--;
7009 csrc->mc_top = snum;
7011 key.mv_size = srcnode->mn_ksize;
7012 key.mv_data = NODEKEY(srcnode);
7015 data.mv_size = NODEDSZ(srcnode);
7016 data.mv_data = NODEDATA(srcnode);
7017 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
7018 if (rc != MDB_SUCCESS)
7023 DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
7024 cdst->mc_pg[cdst->mc_top]->mp_pgno, NUMKEYS(cdst->mc_pg[cdst->mc_top]),
7025 (float)PAGEFILL(cdst->mc_txn->mt_env, cdst->mc_pg[cdst->mc_top]) / 10));
7027 /* Unlink the src page from parent and add to free list.
7029 mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
7030 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
7033 rc = mdb_update_key(csrc, &key);
7039 rc = mdb_midl_append(&csrc->mc_txn->mt_free_pgs,
7040 csrc->mc_pg[csrc->mc_top]->mp_pgno);
7043 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
7044 csrc->mc_db->md_leaf_pages--;
7046 csrc->mc_db->md_branch_pages--;
7048 /* Adjust other cursors pointing to mp */
7049 MDB_cursor *m2, *m3;
7050 MDB_dbi dbi = csrc->mc_dbi;
7051 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
7053 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7054 if (csrc->mc_flags & C_SUB)
7055 m3 = &m2->mc_xcursor->mx_cursor;
7058 if (m3 == csrc) continue;
7059 if (m3->mc_snum < csrc->mc_snum) continue;
7060 if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
7061 m3->mc_pg[csrc->mc_top] = mp;
7062 m3->mc_ki[csrc->mc_top] += nkeys;
7066 mdb_cursor_pop(csrc);
7068 return mdb_rebalance(csrc);
7071 /** Copy the contents of a cursor.
7072 * @param[in] csrc The cursor to copy from.
7073 * @param[out] cdst The cursor to copy to.
7076 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
7080 cdst->mc_txn = csrc->mc_txn;
7081 cdst->mc_dbi = csrc->mc_dbi;
7082 cdst->mc_db = csrc->mc_db;
7083 cdst->mc_dbx = csrc->mc_dbx;
7084 cdst->mc_snum = csrc->mc_snum;
7085 cdst->mc_top = csrc->mc_top;
7086 cdst->mc_flags = csrc->mc_flags;
7088 for (i=0; i<csrc->mc_snum; i++) {
7089 cdst->mc_pg[i] = csrc->mc_pg[i];
7090 cdst->mc_ki[i] = csrc->mc_ki[i];
7094 /** Rebalance the tree after a delete operation.
7095 * @param[in] mc Cursor pointing to the page where rebalancing
7097 * @return 0 on success, non-zero on failure.
7100 mdb_rebalance(MDB_cursor *mc)
7104 unsigned int ptop, minkeys;
7107 minkeys = 1 + (IS_BRANCH(mc->mc_pg[mc->mc_top]));
7111 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
7112 DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
7113 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
7114 pgno, NUMKEYS(mc->mc_pg[mc->mc_top]),
7115 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
7119 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD &&
7120 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
7123 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
7124 DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
7130 if (mc->mc_snum < 2) {
7131 MDB_page *mp = mc->mc_pg[0];
7133 DPUTS("Can't rebalance a subpage, ignoring");
7136 if (NUMKEYS(mp) == 0) {
7137 DPUTS("tree is completely empty");
7138 mc->mc_db->md_root = P_INVALID;
7139 mc->mc_db->md_depth = 0;
7140 mc->mc_db->md_leaf_pages = 0;
7141 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7144 /* Adjust cursors pointing to mp */
7147 mc->mc_flags &= ~C_INITIALIZED;
7149 MDB_cursor *m2, *m3;
7150 MDB_dbi dbi = mc->mc_dbi;
7152 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7153 if (mc->mc_flags & C_SUB)
7154 m3 = &m2->mc_xcursor->mx_cursor;
7157 if (m3->mc_snum < mc->mc_snum) continue;
7158 if (m3->mc_pg[0] == mp) {
7161 m3->mc_flags &= ~C_INITIALIZED;
7165 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
7166 DPUTS("collapsing root page!");
7167 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7170 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
7171 rc = mdb_page_get(mc->mc_txn,mc->mc_db->md_root,&mc->mc_pg[0],NULL);
7174 mc->mc_db->md_depth--;
7175 mc->mc_db->md_branch_pages--;
7176 mc->mc_ki[0] = mc->mc_ki[1];
7178 /* Adjust other cursors pointing to mp */
7179 MDB_cursor *m2, *m3;
7180 MDB_dbi dbi = mc->mc_dbi;
7182 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7183 if (mc->mc_flags & C_SUB)
7184 m3 = &m2->mc_xcursor->mx_cursor;
7187 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
7188 if (m3->mc_pg[0] == mp) {
7192 for (i=0; i<m3->mc_snum; i++) {
7193 m3->mc_pg[i] = m3->mc_pg[i+1];
7194 m3->mc_ki[i] = m3->mc_ki[i+1];
7200 DPUTS("root page doesn't need rebalancing");
7204 /* The parent (branch page) must have at least 2 pointers,
7205 * otherwise the tree is invalid.
7207 ptop = mc->mc_top-1;
7208 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
7210 /* Leaf page fill factor is below the threshold.
7211 * Try to move keys from left or right neighbor, or
7212 * merge with a neighbor page.
7217 mdb_cursor_copy(mc, &mn);
7218 mn.mc_xcursor = NULL;
7220 if (mc->mc_ki[ptop] == 0) {
7221 /* We're the leftmost leaf in our parent.
7223 DPUTS("reading right neighbor");
7225 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7226 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7229 mn.mc_ki[mn.mc_top] = 0;
7230 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
7232 /* There is at least one neighbor to the left.
7234 DPUTS("reading left neighbor");
7236 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7237 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7240 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
7241 mc->mc_ki[mc->mc_top] = 0;
7244 DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
7245 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
7246 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
7248 /* If the neighbor page is above threshold and has enough keys,
7249 * move one key from it. Otherwise we should try to merge them.
7250 * (A branch page must never have less than 2 keys.)
7252 minkeys = 1 + (IS_BRANCH(mn.mc_pg[mn.mc_top]));
7253 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys)
7254 return mdb_node_move(&mn, mc);
7256 if (mc->mc_ki[ptop] == 0)
7257 rc = mdb_page_merge(&mn, mc);
7259 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
7260 rc = mdb_page_merge(mc, &mn);
7261 mdb_cursor_copy(&mn, mc);
7263 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
7268 /** Complete a delete operation started by #mdb_cursor_del(). */
7270 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
7277 mp = mc->mc_pg[mc->mc_top];
7278 ki = mc->mc_ki[mc->mc_top];
7280 /* add overflow pages to free list */
7281 if (!IS_LEAF2(mp) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7285 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
7286 if ((rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL)) ||
7287 (rc = mdb_ovpage_free(mc, omp)))
7290 mdb_node_del(mp, ki, mc->mc_db->md_pad);
7291 mc->mc_db->md_entries--;
7292 rc = mdb_rebalance(mc);
7293 if (rc != MDB_SUCCESS)
7294 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7297 MDB_dbi dbi = mc->mc_dbi;
7299 mp = mc->mc_pg[mc->mc_top];
7300 nkeys = NUMKEYS(mp);
7302 /* if mc points past last node in page, find next sibling */
7303 if (mc->mc_ki[mc->mc_top] >= nkeys)
7304 mdb_cursor_sibling(mc, 1);
7306 /* Adjust other cursors pointing to mp */
7307 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7308 if (m2 == mc || m2->mc_snum < mc->mc_snum)
7310 if (!(m2->mc_flags & C_INITIALIZED))
7312 if (m2->mc_pg[mc->mc_top] == mp) {
7313 if (m2->mc_ki[mc->mc_top] >= ki) {
7314 m2->mc_flags |= C_DEL;
7315 if (m2->mc_ki[mc->mc_top] > ki)
7316 m2->mc_ki[mc->mc_top]--;
7318 if (m2->mc_ki[mc->mc_top] >= nkeys)
7319 mdb_cursor_sibling(m2, 1);
7322 mc->mc_flags |= C_DEL;
7329 mdb_del(MDB_txn *txn, MDB_dbi dbi,
7330 MDB_val *key, MDB_val *data)
7335 MDB_val rdata, *xdata;
7339 assert(key != NULL);
7341 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
7343 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7346 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
7347 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7349 if (key->mv_size > MDB_MAXKEYSIZE) {
7350 return MDB_BAD_VALSIZE;
7353 mdb_cursor_init(&mc, txn, dbi, &mx);
7356 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
7357 /* must ignore any data */
7368 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
7370 /* let mdb_page_split know about this cursor if needed:
7371 * delete will trigger a rebalance; if it needs to move
7372 * a node from one page to another, it will have to
7373 * update the parent's separator key(s). If the new sepkey
7374 * is larger than the current one, the parent page may
7375 * run out of space, triggering a split. We need this
7376 * cursor to be consistent until the end of the rebalance.
7378 mc.mc_flags |= C_UNTRACK;
7379 mc.mc_next = txn->mt_cursors[dbi];
7380 txn->mt_cursors[dbi] = &mc;
7381 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
7382 txn->mt_cursors[dbi] = mc.mc_next;
7387 /** Split a page and insert a new node.
7388 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
7389 * The cursor will be updated to point to the actual page and index where
7390 * the node got inserted after the split.
7391 * @param[in] newkey The key for the newly inserted node.
7392 * @param[in] newdata The data for the newly inserted node.
7393 * @param[in] newpgno The page number, if the new node is a branch node.
7394 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
7395 * @return 0 on success, non-zero on failure.
7398 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
7399 unsigned int nflags)
7402 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
7405 int i, j, split_indx, nkeys, pmax;
7406 MDB_env *env = mc->mc_txn->mt_env;
7408 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
7409 MDB_page *copy = NULL;
7410 MDB_page *mp, *rp, *pp;
7415 mp = mc->mc_pg[mc->mc_top];
7416 newindx = mc->mc_ki[mc->mc_top];
7417 nkeys = NUMKEYS(mp);
7419 DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i/%i",
7420 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
7421 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
7423 /* Create a right sibling. */
7424 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
7426 DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
7428 if (mc->mc_snum < 2) {
7429 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
7431 /* shift current top to make room for new parent */
7432 mc->mc_pg[1] = mc->mc_pg[0];
7433 mc->mc_ki[1] = mc->mc_ki[0];
7436 mc->mc_db->md_root = pp->mp_pgno;
7437 DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
7438 mc->mc_db->md_depth++;
7441 /* Add left (implicit) pointer. */
7442 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
7443 /* undo the pre-push */
7444 mc->mc_pg[0] = mc->mc_pg[1];
7445 mc->mc_ki[0] = mc->mc_ki[1];
7446 mc->mc_db->md_root = mp->mp_pgno;
7447 mc->mc_db->md_depth--;
7454 ptop = mc->mc_top-1;
7455 DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
7458 mc->mc_flags |= C_SPLITTING;
7459 mdb_cursor_copy(mc, &mn);
7460 mn.mc_pg[mn.mc_top] = rp;
7461 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
7463 if (nflags & MDB_APPEND) {
7464 mn.mc_ki[mn.mc_top] = 0;
7466 split_indx = newindx;
7470 split_indx = (nkeys+1) / 2;
7475 unsigned int lsize, rsize, ksize;
7476 /* Move half of the keys to the right sibling */
7478 x = mc->mc_ki[mc->mc_top] - split_indx;
7479 ksize = mc->mc_db->md_pad;
7480 split = LEAF2KEY(mp, split_indx, ksize);
7481 rsize = (nkeys - split_indx) * ksize;
7482 lsize = (nkeys - split_indx) * sizeof(indx_t);
7483 mp->mp_lower -= lsize;
7484 rp->mp_lower += lsize;
7485 mp->mp_upper += rsize - lsize;
7486 rp->mp_upper -= rsize - lsize;
7487 sepkey.mv_size = ksize;
7488 if (newindx == split_indx) {
7489 sepkey.mv_data = newkey->mv_data;
7491 sepkey.mv_data = split;
7494 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
7495 memcpy(rp->mp_ptrs, split, rsize);
7496 sepkey.mv_data = rp->mp_ptrs;
7497 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
7498 memcpy(ins, newkey->mv_data, ksize);
7499 mp->mp_lower += sizeof(indx_t);
7500 mp->mp_upper -= ksize - sizeof(indx_t);
7503 memcpy(rp->mp_ptrs, split, x * ksize);
7504 ins = LEAF2KEY(rp, x, ksize);
7505 memcpy(ins, newkey->mv_data, ksize);
7506 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
7507 rp->mp_lower += sizeof(indx_t);
7508 rp->mp_upper -= ksize - sizeof(indx_t);
7509 mc->mc_ki[mc->mc_top] = x;
7510 mc->mc_pg[mc->mc_top] = rp;
7513 int psize, nsize, k;
7514 /* Maximum free space in an empty page */
7515 pmax = env->me_psize - PAGEHDRSZ;
7517 nsize = mdb_leaf_size(env, newkey, newdata);
7519 nsize = mdb_branch_size(env, newkey);
7522 /* grab a page to hold a temporary copy */
7523 copy = mdb_page_malloc(mc->mc_txn, 1);
7526 copy->mp_pgno = mp->mp_pgno;
7527 copy->mp_flags = mp->mp_flags;
7528 copy->mp_lower = PAGEHDRSZ;
7529 copy->mp_upper = env->me_psize;
7531 /* prepare to insert */
7532 for (i=0, j=0; i<nkeys; i++) {
7534 copy->mp_ptrs[j++] = 0;
7536 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
7539 /* When items are relatively large the split point needs
7540 * to be checked, because being off-by-one will make the
7541 * difference between success or failure in mdb_node_add.
7543 * It's also relevant if a page happens to be laid out
7544 * such that one half of its nodes are all "small" and
7545 * the other half of its nodes are "large." If the new
7546 * item is also "large" and falls on the half with
7547 * "large" nodes, it also may not fit.
7549 * As a final tweak, if the new item goes on the last
7550 * spot on the page (and thus, onto the new page), bias
7551 * the split so the new page is emptier than the old page.
7552 * This yields better packing during sequential inserts.
7554 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
7555 /* Find split point */
7557 if (newindx <= split_indx || newindx >= nkeys) {
7559 k = newindx >= nkeys ? nkeys : split_indx+2;
7564 for (; i!=k; i+=j) {
7569 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i]);
7570 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
7572 if (F_ISSET(node->mn_flags, F_BIGDATA))
7573 psize += sizeof(pgno_t);
7575 psize += NODEDSZ(node);
7579 if (psize > pmax || i == k-j) {
7580 split_indx = i + (j<0);
7585 if (split_indx == newindx) {
7586 sepkey.mv_size = newkey->mv_size;
7587 sepkey.mv_data = newkey->mv_data;
7589 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx]);
7590 sepkey.mv_size = node->mn_ksize;
7591 sepkey.mv_data = NODEKEY(node);
7596 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
7598 /* Copy separator key to the parent.
7600 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
7604 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
7607 if (mn.mc_snum == mc->mc_snum) {
7608 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
7609 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
7610 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
7611 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
7616 /* Right page might now have changed parent.
7617 * Check if left page also changed parent.
7619 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7620 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7621 for (i=0; i<ptop; i++) {
7622 mc->mc_pg[i] = mn.mc_pg[i];
7623 mc->mc_ki[i] = mn.mc_ki[i];
7625 mc->mc_pg[ptop] = mn.mc_pg[ptop];
7626 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
7630 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
7633 mc->mc_flags ^= C_SPLITTING;
7634 if (rc != MDB_SUCCESS) {
7637 if (nflags & MDB_APPEND) {
7638 mc->mc_pg[mc->mc_top] = rp;
7639 mc->mc_ki[mc->mc_top] = 0;
7640 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
7643 for (i=0; i<mc->mc_top; i++)
7644 mc->mc_ki[i] = mn.mc_ki[i];
7645 } else if (!IS_LEAF2(mp)) {
7647 mc->mc_pg[mc->mc_top] = rp;
7652 rkey.mv_data = newkey->mv_data;
7653 rkey.mv_size = newkey->mv_size;
7659 /* Update index for the new key. */
7660 mc->mc_ki[mc->mc_top] = j;
7662 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i]);
7663 rkey.mv_data = NODEKEY(node);
7664 rkey.mv_size = node->mn_ksize;
7666 xdata.mv_data = NODEDATA(node);
7667 xdata.mv_size = NODEDSZ(node);
7670 pgno = NODEPGNO(node);
7671 flags = node->mn_flags;
7674 if (!IS_LEAF(mp) && j == 0) {
7675 /* First branch index doesn't need key data. */
7679 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
7681 /* return tmp page to freelist */
7682 mdb_page_free(env, copy);
7688 mc->mc_pg[mc->mc_top] = copy;
7693 } while (i != split_indx);
7695 nkeys = NUMKEYS(copy);
7696 for (i=0; i<nkeys; i++)
7697 mp->mp_ptrs[i] = copy->mp_ptrs[i];
7698 mp->mp_lower = copy->mp_lower;
7699 mp->mp_upper = copy->mp_upper;
7700 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
7701 env->me_psize - copy->mp_upper);
7703 /* reset back to original page */
7704 if (newindx < split_indx) {
7705 mc->mc_pg[mc->mc_top] = mp;
7706 if (nflags & MDB_RESERVE) {
7707 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7708 if (!(node->mn_flags & F_BIGDATA))
7709 newdata->mv_data = NODEDATA(node);
7712 mc->mc_pg[mc->mc_top] = rp;
7714 /* Make sure mc_ki is still valid.
7716 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7717 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7718 for (i=0; i<ptop; i++) {
7719 mc->mc_pg[i] = mn.mc_pg[i];
7720 mc->mc_ki[i] = mn.mc_ki[i];
7722 mc->mc_pg[ptop] = mn.mc_pg[ptop];
7723 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
7726 /* return tmp page to freelist */
7727 mdb_page_free(env, copy);
7731 /* Adjust other cursors pointing to mp */
7732 MDB_cursor *m2, *m3;
7733 MDB_dbi dbi = mc->mc_dbi;
7734 int fixup = NUMKEYS(mp);
7736 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7737 if (mc->mc_flags & C_SUB)
7738 m3 = &m2->mc_xcursor->mx_cursor;
7743 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
7745 if (m3->mc_flags & C_SPLITTING)
7750 for (k=m3->mc_top; k>=0; k--) {
7751 m3->mc_ki[k+1] = m3->mc_ki[k];
7752 m3->mc_pg[k+1] = m3->mc_pg[k];
7754 if (m3->mc_ki[0] >= split_indx) {
7759 m3->mc_pg[0] = mc->mc_pg[0];
7763 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
7764 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
7765 m3->mc_ki[mc->mc_top]++;
7766 if (m3->mc_ki[mc->mc_top] >= fixup) {
7767 m3->mc_pg[mc->mc_top] = rp;
7768 m3->mc_ki[mc->mc_top] -= fixup;
7769 m3->mc_ki[ptop] = mn.mc_ki[ptop];
7771 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
7772 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
7777 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
7782 mdb_put(MDB_txn *txn, MDB_dbi dbi,
7783 MDB_val *key, MDB_val *data, unsigned int flags)
7788 assert(key != NULL);
7789 assert(data != NULL);
7791 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7794 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP)) != flags)
7797 mdb_cursor_init(&mc, txn, dbi, &mx);
7798 return mdb_cursor_put(&mc, key, data, flags);
7802 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
7804 if ((flag & CHANGEABLE) != flag)
7807 env->me_flags |= flag;
7809 env->me_flags &= ~flag;
7814 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
7819 *arg = env->me_flags;
7824 mdb_env_get_path(MDB_env *env, const char **arg)
7829 *arg = env->me_path;
7834 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
7843 /** Common code for #mdb_stat() and #mdb_env_stat().
7844 * @param[in] env the environment to operate in.
7845 * @param[in] db the #MDB_db record containing the stats to return.
7846 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
7847 * @return 0, this function always succeeds.
7850 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
7852 arg->ms_psize = env->me_psize;
7853 arg->ms_depth = db->md_depth;
7854 arg->ms_branch_pages = db->md_branch_pages;
7855 arg->ms_leaf_pages = db->md_leaf_pages;
7856 arg->ms_overflow_pages = db->md_overflow_pages;
7857 arg->ms_entries = db->md_entries;
7862 mdb_env_stat(MDB_env *env, MDB_stat *arg)
7866 if (env == NULL || arg == NULL)
7869 toggle = mdb_env_pick_meta(env);
7871 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
7875 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
7879 if (env == NULL || arg == NULL)
7882 toggle = mdb_env_pick_meta(env);
7883 arg->me_mapaddr = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : 0;
7884 arg->me_mapsize = env->me_mapsize;
7885 arg->me_maxreaders = env->me_maxreaders;
7887 /* me_numreaders may be zero if this process never used any readers. Use
7888 * the shared numreader count if it exists.
7890 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : env->me_numreaders;
7892 arg->me_last_pgno = env->me_metas[toggle]->mm_last_pg;
7893 arg->me_last_txnid = env->me_metas[toggle]->mm_txnid;
7897 /** Set the default comparison functions for a database.
7898 * Called immediately after a database is opened to set the defaults.
7899 * The user can then override them with #mdb_set_compare() or
7900 * #mdb_set_dupsort().
7901 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
7902 * @param[in] dbi A database handle returned by #mdb_dbi_open()
7905 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
7907 uint16_t f = txn->mt_dbs[dbi].md_flags;
7909 txn->mt_dbxs[dbi].md_cmp =
7910 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
7911 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
7913 txn->mt_dbxs[dbi].md_dcmp =
7914 !(f & MDB_DUPSORT) ? 0 :
7915 ((f & MDB_INTEGERDUP)
7916 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
7917 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
7920 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
7925 int rc, dbflag, exact;
7926 unsigned int unused = 0;
7929 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
7930 mdb_default_cmp(txn, FREE_DBI);
7933 if ((flags & VALID_FLAGS) != flags)
7935 if (txn->mt_flags & MDB_TXN_ERROR)
7941 if (flags & PERSISTENT_FLAGS) {
7942 uint16_t f2 = flags & PERSISTENT_FLAGS;
7943 /* make sure flag changes get committed */
7944 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
7945 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
7946 txn->mt_flags |= MDB_TXN_DIRTY;
7949 mdb_default_cmp(txn, MAIN_DBI);
7953 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
7954 mdb_default_cmp(txn, MAIN_DBI);
7957 /* Is the DB already open? */
7959 for (i=2; i<txn->mt_numdbs; i++) {
7960 if (!txn->mt_dbxs[i].md_name.mv_size) {
7961 /* Remember this free slot */
7962 if (!unused) unused = i;
7965 if (len == txn->mt_dbxs[i].md_name.mv_size &&
7966 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
7972 /* If no free slot and max hit, fail */
7973 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
7974 return MDB_DBS_FULL;
7976 /* Cannot mix named databases with some mainDB flags */
7977 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
7978 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
7980 /* Find the DB info */
7981 dbflag = DB_NEW|DB_VALID;
7984 key.mv_data = (void *)name;
7985 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
7986 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
7987 if (rc == MDB_SUCCESS) {
7988 /* make sure this is actually a DB */
7989 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
7990 if (!(node->mn_flags & F_SUBDATA))
7991 return MDB_INCOMPATIBLE;
7992 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
7993 /* Create if requested */
7995 data.mv_size = sizeof(MDB_db);
7996 data.mv_data = &dummy;
7997 memset(&dummy, 0, sizeof(dummy));
7998 dummy.md_root = P_INVALID;
7999 dummy.md_flags = flags & PERSISTENT_FLAGS;
8000 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
8004 /* OK, got info, add to table */
8005 if (rc == MDB_SUCCESS) {
8006 unsigned int slot = unused ? unused : txn->mt_numdbs;
8007 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
8008 txn->mt_dbxs[slot].md_name.mv_size = len;
8009 txn->mt_dbxs[slot].md_rel = NULL;
8010 txn->mt_dbflags[slot] = dbflag;
8011 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
8013 mdb_default_cmp(txn, slot);
8022 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
8024 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
8027 if (txn->mt_dbflags[dbi] & DB_STALE) {
8030 /* Stale, must read the DB's root. cursor_init does it for us. */
8031 mdb_cursor_init(&mc, txn, dbi, &mx);
8033 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
8036 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
8039 if (dbi <= MAIN_DBI || dbi >= env->me_maxdbs)
8041 ptr = env->me_dbxs[dbi].md_name.mv_data;
8042 env->me_dbxs[dbi].md_name.mv_data = NULL;
8043 env->me_dbxs[dbi].md_name.mv_size = 0;
8044 env->me_dbflags[dbi] = 0;
8048 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
8050 /* We could return the flags for the FREE_DBI too but what's the point? */
8051 if (txn == NULL || dbi < MAIN_DBI || dbi >= txn->mt_numdbs)
8053 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
8057 /** Add all the DB's pages to the free list.
8058 * @param[in] mc Cursor on the DB to free.
8059 * @param[in] subs non-Zero to check for sub-DBs in this DB.
8060 * @return 0 on success, non-zero on failure.
8063 mdb_drop0(MDB_cursor *mc, int subs)
8067 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
8068 if (rc == MDB_SUCCESS) {
8069 MDB_txn *txn = mc->mc_txn;
8074 /* LEAF2 pages have no nodes, cannot have sub-DBs */
8075 if (IS_LEAF2(mc->mc_pg[mc->mc_top]))
8078 mdb_cursor_copy(mc, &mx);
8079 while (mc->mc_snum > 0) {
8080 MDB_page *mp = mc->mc_pg[mc->mc_top];
8081 unsigned n = NUMKEYS(mp);
8083 for (i=0; i<n; i++) {
8084 ni = NODEPTR(mp, i);
8085 if (ni->mn_flags & F_BIGDATA) {
8088 memcpy(&pg, NODEDATA(ni), sizeof(pg));
8089 rc = mdb_page_get(txn, pg, &omp, NULL);
8092 assert(IS_OVERFLOW(omp));
8093 rc = mdb_midl_append_range(&txn->mt_free_pgs,
8097 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
8098 mdb_xcursor_init1(mc, ni);
8099 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
8105 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
8107 for (i=0; i<n; i++) {
8109 ni = NODEPTR(mp, i);
8112 mdb_midl_xappend(txn->mt_free_pgs, pg);
8117 mc->mc_ki[mc->mc_top] = i;
8118 rc = mdb_cursor_sibling(mc, 1);
8120 /* no more siblings, go back to beginning
8121 * of previous level.
8125 for (i=1; i<mc->mc_snum; i++) {
8127 mc->mc_pg[i] = mx.mc_pg[i];
8132 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
8133 } else if (rc == MDB_NOTFOUND) {
8139 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
8141 MDB_cursor *mc, *m2;
8144 if (!txn || !dbi || dbi >= txn->mt_numdbs || (unsigned)del > 1 || !(txn->mt_dbflags[dbi] & DB_VALID))
8147 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
8150 rc = mdb_cursor_open(txn, dbi, &mc);
8154 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
8155 /* Invalidate the dropped DB's cursors */
8156 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
8157 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
8161 /* Can't delete the main DB */
8162 if (del && dbi > MAIN_DBI) {
8163 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
8165 txn->mt_dbflags[dbi] = DB_STALE;
8166 mdb_dbi_close(txn->mt_env, dbi);
8169 /* reset the DB record, mark it dirty */
8170 txn->mt_dbflags[dbi] |= DB_DIRTY;
8171 txn->mt_dbs[dbi].md_depth = 0;
8172 txn->mt_dbs[dbi].md_branch_pages = 0;
8173 txn->mt_dbs[dbi].md_leaf_pages = 0;
8174 txn->mt_dbs[dbi].md_overflow_pages = 0;
8175 txn->mt_dbs[dbi].md_entries = 0;
8176 txn->mt_dbs[dbi].md_root = P_INVALID;
8178 txn->mt_flags |= MDB_TXN_DIRTY;
8181 mdb_cursor_close(mc);
8185 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
8187 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8190 txn->mt_dbxs[dbi].md_cmp = cmp;
8194 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
8196 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8199 txn->mt_dbxs[dbi].md_dcmp = cmp;
8203 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
8205 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8208 txn->mt_dbxs[dbi].md_rel = rel;
8212 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
8214 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8217 txn->mt_dbxs[dbi].md_relctx = ctx;
8221 int mdb_env_get_maxkeysize(MDB_env *env)
8223 return MDB_MAXKEYSIZE;
8226 int mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
8228 unsigned int i, rdrs;
8235 if (!env->me_txns) {
8236 return func("(no reader locks)\n", ctx);
8238 rdrs = env->me_txns->mti_numreaders;
8239 mr = env->me_txns->mti_readers;
8240 for (i=0; i<rdrs; i++) {
8245 if (mr[i].mr_txnid == (txnid_t)-1) {
8246 sprintf(buf, "%10d %"Z"x -\n", mr[i].mr_pid, tid);
8248 sprintf(buf, "%10d %"Z"x %"Z"u\n", mr[i].mr_pid, tid, mr[i].mr_txnid);
8252 func(" pid thread txnid\n", ctx);
8254 rc = func(buf, ctx);
8260 func("(no active readers)\n", ctx);
8265 /** Insert pid into list if not already present.
8266 * return -1 if already present.
8268 static int mdb_pid_insert(pid_t *ids, pid_t pid)
8270 /* binary search of pid in list */
8272 unsigned cursor = 1;
8274 unsigned n = ids[0];
8277 unsigned pivot = n >> 1;
8278 cursor = base + pivot + 1;
8279 val = pid - ids[cursor];
8284 } else if ( val > 0 ) {
8289 /* found, so it's a duplicate */
8298 for (n = ids[0]; n > cursor; n--)
8304 int mdb_reader_check(MDB_env *env, int *dead)
8306 unsigned int i, j, rdrs;
8317 rdrs = env->me_txns->mti_numreaders;
8318 pids = malloc((rdrs+1) * sizeof(pid_t));
8322 mr = env->me_txns->mti_readers;
8324 for (i=0; i<rdrs; i++) {
8325 if (mr[i].mr_pid && mr[i].mr_pid != env->me_pid) {
8327 if (mdb_pid_insert(pids, pid) == 0) {
8328 if (!mdb_reader_pid(env, Pidcheck, pid)) {
8330 /* Recheck, a new process may have reused pid */
8331 if (!mdb_reader_pid(env, Pidcheck, pid)) {
8332 for (j=i; j<rdrs; j++)
8333 if (mr[j].mr_pid == pid) {
8334 DPRINTF(("clear stale reader pid %u txn %"Z"d",
8335 (unsigned) pid, mr[j].mr_txnid));
8340 UNLOCK_MUTEX_R(env);