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 / 3).
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 psize = env->me_psize, sz = psize, off;
1326 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1327 * For a single page alloc, we init everything after the page header.
1328 * For multi-page, we init the final page; if the caller needed that
1329 * many pages they will be filling in at least up to the last page.
1333 VGMEMP_ALLOC(env, ret, sz);
1334 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1335 env->me_dpages = ret->mp_next;
1338 psize -= off = PAGEHDRSZ;
1343 if ((ret = malloc(sz)) != NULL) {
1344 if (!(env->me_flags & MDB_NOMEMINIT)) {
1345 memset((char *)ret + off, 0, psize);
1348 VGMEMP_ALLOC(env, ret, sz);
1353 /** Free a single page.
1354 * Saves single pages to a list, for future reuse.
1355 * (This is not used for multi-page overflow pages.)
1358 mdb_page_free(MDB_env *env, MDB_page *mp)
1360 mp->mp_next = env->me_dpages;
1361 VGMEMP_FREE(env, mp);
1362 env->me_dpages = mp;
1365 /** Free a dirty page */
1367 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1369 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1370 mdb_page_free(env, dp);
1372 /* large pages just get freed directly */
1373 VGMEMP_FREE(env, dp);
1378 /** Return all dirty pages to dpage list */
1380 mdb_dlist_free(MDB_txn *txn)
1382 MDB_env *env = txn->mt_env;
1383 MDB_ID2L dl = txn->mt_u.dirty_list;
1384 unsigned i, n = dl[0].mid;
1386 for (i = 1; i <= n; i++) {
1387 mdb_dpage_free(env, dl[i].mptr);
1392 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
1393 * @param[in] mc A cursor handle for the current operation.
1394 * @param[in] pflags Flags of the pages to update:
1395 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1396 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
1397 * @return 0 on success, non-zero on failure.
1400 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
1402 enum { Mask = P_SUBP|P_DIRTY|P_KEEP };
1403 MDB_txn *txn = mc->mc_txn;
1409 int rc = MDB_SUCCESS, level;
1411 /* Mark pages seen by cursors */
1412 if (mc->mc_flags & C_UNTRACK)
1413 mc = NULL; /* will find mc in mt_cursors */
1414 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1415 for (; mc; mc=mc->mc_next) {
1416 if (!(mc->mc_flags & C_INITIALIZED))
1418 for (m3 = mc;; m3 = &mx->mx_cursor) {
1420 for (j=0; j<m3->mc_snum; j++) {
1422 if ((mp->mp_flags & Mask) == pflags)
1423 mp->mp_flags ^= P_KEEP;
1425 mx = m3->mc_xcursor;
1426 /* Proceed to mx if it is at a sub-database */
1427 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
1429 if (! (mp && (mp->mp_flags & P_LEAF)))
1431 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
1432 if (!(leaf->mn_flags & F_SUBDATA))
1441 /* Mark dirty root pages */
1442 for (i=0; i<txn->mt_numdbs; i++) {
1443 if (txn->mt_dbflags[i] & DB_DIRTY) {
1444 pgno_t pgno = txn->mt_dbs[i].md_root;
1445 if (pgno == P_INVALID)
1447 if ((rc = mdb_page_get(txn, pgno, &dp, &level)) != MDB_SUCCESS)
1449 if ((dp->mp_flags & Mask) == pflags && level <= 1)
1450 dp->mp_flags ^= P_KEEP;
1458 static int mdb_page_flush(MDB_txn *txn, int keep);
1460 /** Spill pages from the dirty list back to disk.
1461 * This is intended to prevent running into #MDB_TXN_FULL situations,
1462 * but note that they may still occur in a few cases:
1463 * 1) our estimate of the txn size could be too small. Currently this
1464 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
1465 * 2) child txns may run out of space if their parents dirtied a
1466 * lot of pages and never spilled them. TODO: we probably should do
1467 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1468 * the parent's dirty_room is below a given threshold.
1470 * Otherwise, if not using nested txns, it is expected that apps will
1471 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1472 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1473 * If the txn never references them again, they can be left alone.
1474 * If the txn only reads them, they can be used without any fuss.
1475 * If the txn writes them again, they can be dirtied immediately without
1476 * going thru all of the work of #mdb_page_touch(). Such references are
1477 * handled by #mdb_page_unspill().
1479 * Also note, we never spill DB root pages, nor pages of active cursors,
1480 * because we'll need these back again soon anyway. And in nested txns,
1481 * we can't spill a page in a child txn if it was already spilled in a
1482 * parent txn. That would alter the parent txns' data even though
1483 * the child hasn't committed yet, and we'd have no way to undo it if
1484 * the child aborted.
1486 * @param[in] m0 cursor A cursor handle identifying the transaction and
1487 * database for which we are checking space.
1488 * @param[in] key For a put operation, the key being stored.
1489 * @param[in] data For a put operation, the data being stored.
1490 * @return 0 on success, non-zero on failure.
1493 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1495 MDB_txn *txn = m0->mc_txn;
1497 MDB_ID2L dl = txn->mt_u.dirty_list;
1498 unsigned int i, j, need;
1501 if (m0->mc_flags & C_SUB)
1504 /* Estimate how much space this op will take */
1505 i = m0->mc_db->md_depth;
1506 /* Named DBs also dirty the main DB */
1507 if (m0->mc_dbi > MAIN_DBI)
1508 i += txn->mt_dbs[MAIN_DBI].md_depth;
1509 /* For puts, roughly factor in the key+data size */
1511 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
1512 i += i; /* double it for good measure */
1515 if (txn->mt_dirty_room > i)
1518 if (!txn->mt_spill_pgs) {
1519 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
1520 if (!txn->mt_spill_pgs)
1523 /* purge deleted slots */
1524 MDB_IDL sl = txn->mt_spill_pgs;
1525 unsigned int num = sl[0];
1527 for (i=1; i<=num; i++) {
1534 /* Preserve pages which may soon be dirtied again */
1535 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
1538 /* Less aggressive spill - we originally spilled the entire dirty list,
1539 * with a few exceptions for cursor pages and DB root pages. But this
1540 * turns out to be a lot of wasted effort because in a large txn many
1541 * of those pages will need to be used again. So now we spill only 1/8th
1542 * of the dirty pages. Testing revealed this to be a good tradeoff,
1543 * better than 1/2, 1/4, or 1/10.
1545 if (need < MDB_IDL_UM_MAX / 8)
1546 need = MDB_IDL_UM_MAX / 8;
1548 /* Save the page IDs of all the pages we're flushing */
1549 /* flush from the tail forward, this saves a lot of shifting later on. */
1550 for (i=dl[0].mid; i && need; i--) {
1551 MDB_ID pn = dl[i].mid << 1;
1553 if (dp->mp_flags & P_KEEP)
1555 /* Can't spill twice, make sure it's not already in a parent's
1558 if (txn->mt_parent) {
1560 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1561 if (tx2->mt_spill_pgs) {
1562 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
1563 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
1564 dp->mp_flags |= P_KEEP;
1572 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
1576 mdb_midl_sort(txn->mt_spill_pgs);
1578 /* Flush the spilled part of dirty list */
1579 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
1582 /* Reset any dirty pages we kept that page_flush didn't see */
1583 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
1586 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
1590 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
1592 mdb_find_oldest(MDB_txn *txn)
1595 txnid_t mr, oldest = txn->mt_txnid - 1;
1596 if (txn->mt_env->me_txns) {
1597 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
1598 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
1609 /** Add a page to the txn's dirty list */
1611 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
1614 int (*insert)(MDB_ID2L, MDB_ID2 *);
1616 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1617 insert = mdb_mid2l_append;
1619 insert = mdb_mid2l_insert;
1621 mid.mid = mp->mp_pgno;
1623 insert(txn->mt_u.dirty_list, &mid);
1624 txn->mt_dirty_room--;
1627 /** Allocate page numbers and memory for writing. Maintain me_pglast,
1628 * me_pghead and mt_next_pgno.
1630 * If there are free pages available from older transactions, they
1631 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
1632 * Do not modify the freedB, just merge freeDB records into me_pghead[]
1633 * and move me_pglast to say which records were consumed. Only this
1634 * function can create me_pghead and move me_pglast/mt_next_pgno.
1635 * @param[in] mc cursor A cursor handle identifying the transaction and
1636 * database for which we are allocating.
1637 * @param[in] num the number of pages to allocate.
1638 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
1639 * will always be satisfied by a single contiguous chunk of memory.
1640 * @return 0 on success, non-zero on failure.
1643 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
1645 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
1646 /* Get at most <Max_retries> more freeDB records once me_pghead
1647 * has enough pages. If not enough, use new pages from the map.
1648 * If <Paranoid> and mc is updating the freeDB, only get new
1649 * records if me_pghead is empty. Then the freelist cannot play
1650 * catch-up with itself by growing while trying to save it.
1652 enum { Paranoid = 1, Max_retries = 500 };
1654 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
1656 int rc, n2 = num-1, retry = Max_retries;
1657 MDB_txn *txn = mc->mc_txn;
1658 MDB_env *env = txn->mt_env;
1659 pgno_t pgno, *mop = env->me_pghead;
1660 unsigned i, j, k, mop_len = mop ? mop[0] : 0;
1662 txnid_t oldest = 0, last;
1668 /* If our dirty list is already full, we can't do anything */
1669 if (txn->mt_dirty_room == 0)
1670 return MDB_TXN_FULL;
1672 for (op = MDB_FIRST;; op = MDB_NEXT) {
1675 pgno_t *idl, old_id, new_id;
1677 /* Seek a big enough contiguous page range. Prefer
1678 * pages at the tail, just truncating the list.
1680 if (mop_len >= (unsigned)num) {
1684 if (mop[i-n2] == pgno+n2)
1686 } while (--i >= (unsigned)num);
1687 if (Max_retries < INT_MAX && --retry < 0)
1691 if (op == MDB_FIRST) { /* 1st iteration */
1692 /* Prepare to fetch more and coalesce */
1693 oldest = mdb_find_oldest(txn);
1694 last = env->me_pglast;
1695 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1698 key.mv_data = &last; /* will look up last+1 */
1699 key.mv_size = sizeof(last);
1701 if (Paranoid && mc->mc_dbi == FREE_DBI)
1704 if (Paranoid && retry < 0 && mop_len)
1708 /* Do not fetch more if the record will be too recent */
1711 rc = mdb_cursor_get(&m2, &key, NULL, op);
1713 if (rc == MDB_NOTFOUND)
1717 last = *(txnid_t*)key.mv_data;
1720 np = m2.mc_pg[m2.mc_top];
1721 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
1722 if ((rc = mdb_node_read(txn, leaf, &data)) != MDB_SUCCESS)
1725 idl = (MDB_ID *) data.mv_data;
1728 if (!(env->me_pghead = mop = mdb_midl_alloc(i)))
1731 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
1733 mop = env->me_pghead;
1735 env->me_pglast = last;
1737 DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
1738 last, txn->mt_dbs[FREE_DBI].md_root, i));
1740 DPRINTF(("IDL %"Z"u", idl[k]));
1742 /* Merge in descending sorted order */
1745 mop[0] = (pgno_t)-1;
1749 for (; old_id < new_id; old_id = mop[--j])
1756 /* Use new pages from the map when nothing suitable in the freeDB */
1758 pgno = txn->mt_next_pgno;
1759 if (pgno + num >= env->me_maxpg) {
1760 DPUTS("DB size maxed out");
1761 return MDB_MAP_FULL;
1765 if (env->me_flags & MDB_WRITEMAP) {
1766 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
1768 if (!(np = mdb_page_malloc(txn, num)))
1772 mop[0] = mop_len -= num;
1773 /* Move any stragglers down */
1774 for (j = i-num; j < mop_len; )
1775 mop[++j] = mop[++i];
1777 txn->mt_next_pgno = pgno + num;
1780 mdb_page_dirty(txn, np);
1786 /** Copy the used portions of a non-overflow page.
1787 * @param[in] dst page to copy into
1788 * @param[in] src page to copy from
1789 * @param[in] psize size of a page
1792 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
1794 enum { Align = sizeof(pgno_t) };
1795 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
1797 /* If page isn't full, just copy the used portion. Adjust
1798 * alignment so memcpy may copy words instead of bytes.
1800 if ((unused &= -Align) && !IS_LEAF2(src)) {
1802 memcpy(dst, src, (lower + (Align-1)) & -Align);
1803 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
1806 memcpy(dst, src, psize - unused);
1810 /** Pull a page off the txn's spill list, if present.
1811 * If a page being referenced was spilled to disk in this txn, bring
1812 * it back and make it dirty/writable again.
1813 * @param[in] txn the transaction handle.
1814 * @param[in] mp the page being referenced.
1815 * @param[out] ret the writable page, if any. ret is unchanged if
1816 * mp wasn't spilled.
1819 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
1821 MDB_env *env = txn->mt_env;
1824 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
1826 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
1827 if (!tx2->mt_spill_pgs)
1829 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
1830 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
1833 if (txn->mt_dirty_room == 0)
1834 return MDB_TXN_FULL;
1835 if (IS_OVERFLOW(mp))
1839 if (env->me_flags & MDB_WRITEMAP) {
1842 np = mdb_page_malloc(txn, num);
1846 memcpy(np, mp, num * env->me_psize);
1848 mdb_page_copy(np, mp, env->me_psize);
1851 /* If in current txn, this page is no longer spilled.
1852 * If it happens to be the last page, truncate the spill list.
1853 * Otherwise mark it as deleted by setting the LSB.
1855 if (x == txn->mt_spill_pgs[0])
1856 txn->mt_spill_pgs[0]--;
1858 txn->mt_spill_pgs[x] |= 1;
1859 } /* otherwise, if belonging to a parent txn, the
1860 * page remains spilled until child commits
1863 mdb_page_dirty(txn, np);
1864 np->mp_flags |= P_DIRTY;
1872 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1873 * @param[in] mc cursor pointing to the page to be touched
1874 * @return 0 on success, non-zero on failure.
1877 mdb_page_touch(MDB_cursor *mc)
1879 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
1880 MDB_txn *txn = mc->mc_txn;
1881 MDB_cursor *m2, *m3;
1885 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1886 if (txn->mt_flags & MDB_TXN_SPILLS) {
1888 rc = mdb_page_unspill(txn, mp, &np);
1894 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
1895 (rc = mdb_page_alloc(mc, 1, &np)))
1898 DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
1899 mp->mp_pgno, pgno));
1900 assert(mp->mp_pgno != pgno);
1901 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
1902 /* Update the parent page, if any, to point to the new page */
1904 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
1905 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
1906 SETPGNO(node, pgno);
1908 mc->mc_db->md_root = pgno;
1910 } else if (txn->mt_parent && !IS_SUBP(mp)) {
1911 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
1913 /* If txn has a parent, make sure the page is in our
1917 unsigned x = mdb_mid2l_search(dl, pgno);
1918 if (x <= dl[0].mid && dl[x].mid == pgno) {
1919 if (mp != dl[x].mptr) { /* bad cursor? */
1920 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1921 return MDB_CORRUPTED;
1926 assert(dl[0].mid < MDB_IDL_UM_MAX);
1928 np = mdb_page_malloc(txn, 1);
1933 mdb_mid2l_insert(dl, &mid);
1938 mdb_page_copy(np, mp, txn->mt_env->me_psize);
1940 np->mp_flags |= P_DIRTY;
1943 /* Adjust cursors pointing to mp */
1944 mc->mc_pg[mc->mc_top] = np;
1945 m2 = txn->mt_cursors[mc->mc_dbi];
1946 if (mc->mc_flags & C_SUB) {
1947 for (; m2; m2=m2->mc_next) {
1948 m3 = &m2->mc_xcursor->mx_cursor;
1949 if (m3->mc_snum < mc->mc_snum) continue;
1950 if (m3->mc_pg[mc->mc_top] == mp)
1951 m3->mc_pg[mc->mc_top] = np;
1954 for (; m2; m2=m2->mc_next) {
1955 if (m2->mc_snum < mc->mc_snum) continue;
1956 if (m2->mc_pg[mc->mc_top] == mp) {
1957 m2->mc_pg[mc->mc_top] = np;
1958 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
1959 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
1961 MDB_node *leaf = NODEPTR(np, mc->mc_ki[mc->mc_top]);
1962 if (!(leaf->mn_flags & F_SUBDATA))
1963 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
1972 mdb_env_sync(MDB_env *env, int force)
1975 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1976 if (env->me_flags & MDB_WRITEMAP) {
1977 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
1978 ? MS_ASYNC : MS_SYNC;
1979 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
1982 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
1986 if (MDB_FDATASYNC(env->me_fd))
1993 /** Back up parent txn's cursors, then grab the originals for tracking */
1995 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
1997 MDB_cursor *mc, *bk;
2002 for (i = src->mt_numdbs; --i >= 0; ) {
2003 if ((mc = src->mt_cursors[i]) != NULL) {
2004 size = sizeof(MDB_cursor);
2006 size += sizeof(MDB_xcursor);
2007 for (; mc; mc = bk->mc_next) {
2013 mc->mc_db = &dst->mt_dbs[i];
2014 /* Kill pointers into src - and dst to reduce abuse: The
2015 * user may not use mc until dst ends. Otherwise we'd...
2017 mc->mc_txn = NULL; /* ...set this to dst */
2018 mc->mc_dbflag = NULL; /* ...and &dst->mt_dbflags[i] */
2019 if ((mx = mc->mc_xcursor) != NULL) {
2020 *(MDB_xcursor *)(bk+1) = *mx;
2021 mx->mx_cursor.mc_txn = NULL; /* ...and dst. */
2023 mc->mc_next = dst->mt_cursors[i];
2024 dst->mt_cursors[i] = mc;
2031 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2032 * @param[in] txn the transaction handle.
2033 * @param[in] merge true to keep changes to parent cursors, false to revert.
2034 * @return 0 on success, non-zero on failure.
2037 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2039 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2043 for (i = txn->mt_numdbs; --i >= 0; ) {
2044 for (mc = cursors[i]; mc; mc = next) {
2046 if ((bk = mc->mc_backup) != NULL) {
2048 /* Commit changes to parent txn */
2049 mc->mc_next = bk->mc_next;
2050 mc->mc_backup = bk->mc_backup;
2051 mc->mc_txn = bk->mc_txn;
2052 mc->mc_db = bk->mc_db;
2053 mc->mc_dbflag = bk->mc_dbflag;
2054 if ((mx = mc->mc_xcursor) != NULL)
2055 mx->mx_cursor.mc_txn = bk->mc_txn;
2057 /* Abort nested txn */
2059 if ((mx = mc->mc_xcursor) != NULL)
2060 *mx = *(MDB_xcursor *)(bk+1);
2064 /* Only malloced cursors are permanently tracked. */
2072 #define mdb_txn_reset0(txn, act) mdb_txn_reset0(txn)
2075 mdb_txn_reset0(MDB_txn *txn, const char *act);
2077 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2083 Pidset = F_SETLK, Pidcheck = F_GETLK
2087 /** Set or check a pid lock. Set returns 0 on success.
2088 * Check returns 0 if the process is certainly dead, nonzero if it may
2089 * be alive (the lock exists or an error happened so we do not know).
2091 * On Windows Pidset is a no-op, we merely check for the existence
2092 * of the process with the given pid. On POSIX we use a single byte
2093 * lock on the lockfile, set at an offset equal to the pid.
2096 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, pid_t pid)
2098 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2101 if (op == Pidcheck) {
2102 h = OpenProcess(env->me_pidquery, FALSE, pid);
2103 /* No documented "no such process" code, but other program use this: */
2105 return ErrCode() != ERROR_INVALID_PARAMETER;
2106 /* A process exists until all handles to it close. Has it exited? */
2107 ret = WaitForSingleObject(h, 0) != 0;
2114 struct flock lock_info;
2115 memset(&lock_info, 0, sizeof(lock_info));
2116 lock_info.l_type = F_WRLCK;
2117 lock_info.l_whence = SEEK_SET;
2118 lock_info.l_start = pid;
2119 lock_info.l_len = 1;
2120 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2121 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2123 } else if ((rc = ErrCode()) == EINTR) {
2131 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2132 * @param[in] txn the transaction handle to initialize
2133 * @return 0 on success, non-zero on failure.
2136 mdb_txn_renew0(MDB_txn *txn)
2138 MDB_env *env = txn->mt_env;
2139 MDB_txninfo *ti = env->me_txns;
2143 int rc, new_notls = 0;
2146 txn->mt_numdbs = env->me_numdbs;
2147 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
2149 if (txn->mt_flags & MDB_TXN_RDONLY) {
2151 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2152 txn->mt_txnid = meta->mm_txnid;
2153 txn->mt_u.reader = NULL;
2155 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2156 pthread_getspecific(env->me_txkey);
2158 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2159 return MDB_BAD_RSLOT;
2161 pid_t pid = env->me_pid;
2162 pthread_t tid = pthread_self();
2164 if (!(env->me_flags & MDB_LIVE_READER)) {
2165 rc = mdb_reader_pid(env, Pidset, pid);
2167 UNLOCK_MUTEX_R(env);
2170 env->me_flags |= MDB_LIVE_READER;
2174 nr = ti->mti_numreaders;
2175 for (i=0; i<nr; i++)
2176 if (ti->mti_readers[i].mr_pid == 0)
2178 if (i == env->me_maxreaders) {
2179 UNLOCK_MUTEX_R(env);
2180 return MDB_READERS_FULL;
2182 ti->mti_readers[i].mr_pid = pid;
2183 ti->mti_readers[i].mr_tid = tid;
2185 ti->mti_numreaders = ++nr;
2186 /* Save numreaders for un-mutexed mdb_env_close() */
2187 env->me_numreaders = nr;
2188 UNLOCK_MUTEX_R(env);
2190 r = &ti->mti_readers[i];
2191 new_notls = (env->me_flags & MDB_NOTLS);
2192 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2197 txn->mt_txnid = r->mr_txnid = ti->mti_txnid;
2198 txn->mt_u.reader = r;
2199 meta = env->me_metas[txn->mt_txnid & 1];
2205 txn->mt_txnid = ti->mti_txnid;
2206 meta = env->me_metas[txn->mt_txnid & 1];
2208 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2209 txn->mt_txnid = meta->mm_txnid;
2213 if (txn->mt_txnid == mdb_debug_start)
2216 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2217 txn->mt_u.dirty_list = env->me_dirty_list;
2218 txn->mt_u.dirty_list[0].mid = 0;
2219 txn->mt_free_pgs = env->me_free_pgs;
2220 txn->mt_free_pgs[0] = 0;
2221 txn->mt_spill_pgs = NULL;
2225 /* Copy the DB info and flags */
2226 memcpy(txn->mt_dbs, meta->mm_dbs, 2 * sizeof(MDB_db));
2228 /* Moved to here to avoid a data race in read TXNs */
2229 txn->mt_next_pgno = meta->mm_last_pg+1;
2231 for (i=2; i<txn->mt_numdbs; i++) {
2232 x = env->me_dbflags[i];
2233 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2234 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_STALE : 0;
2236 txn->mt_dbflags[0] = txn->mt_dbflags[1] = DB_VALID;
2238 if (env->me_maxpg < txn->mt_next_pgno) {
2239 mdb_txn_reset0(txn, "renew0-mapfail");
2241 txn->mt_u.reader->mr_pid = 0;
2242 txn->mt_u.reader = NULL;
2244 return MDB_MAP_RESIZED;
2251 mdb_txn_renew(MDB_txn *txn)
2255 if (!txn || txn->mt_dbxs) /* A reset txn has mt_dbxs==NULL */
2258 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
2259 DPUTS("environment had fatal error, must shutdown!");
2263 rc = mdb_txn_renew0(txn);
2264 if (rc == MDB_SUCCESS) {
2265 DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2266 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2267 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2273 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2277 int rc, size, tsize = sizeof(MDB_txn);
2279 if (env->me_flags & MDB_FATAL_ERROR) {
2280 DPUTS("environment had fatal error, must shutdown!");
2283 if ((env->me_flags & MDB_RDONLY) && !(flags & MDB_RDONLY))
2286 /* Nested transactions: Max 1 child, write txns only, no writemap */
2287 if (parent->mt_child ||
2288 (flags & MDB_RDONLY) ||
2289 (parent->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR)) ||
2290 (env->me_flags & MDB_WRITEMAP))
2292 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
2294 tsize = sizeof(MDB_ntxn);
2296 size = tsize + env->me_maxdbs * (sizeof(MDB_db)+1);
2297 if (!(flags & MDB_RDONLY))
2298 size += env->me_maxdbs * sizeof(MDB_cursor *);
2300 if ((txn = calloc(1, size)) == NULL) {
2301 DPRINTF(("calloc: %s", strerror(ErrCode())));
2304 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2305 if (flags & MDB_RDONLY) {
2306 txn->mt_flags |= MDB_TXN_RDONLY;
2307 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
2309 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2310 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
2316 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2317 if (!txn->mt_u.dirty_list ||
2318 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2320 free(txn->mt_u.dirty_list);
2324 txn->mt_txnid = parent->mt_txnid;
2325 txn->mt_dirty_room = parent->mt_dirty_room;
2326 txn->mt_u.dirty_list[0].mid = 0;
2327 txn->mt_spill_pgs = NULL;
2328 txn->mt_next_pgno = parent->mt_next_pgno;
2329 parent->mt_child = txn;
2330 txn->mt_parent = parent;
2331 txn->mt_numdbs = parent->mt_numdbs;
2332 txn->mt_flags = parent->mt_flags;
2333 txn->mt_dbxs = parent->mt_dbxs;
2334 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2335 /* Copy parent's mt_dbflags, but clear DB_NEW */
2336 for (i=0; i<txn->mt_numdbs; i++)
2337 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2339 ntxn = (MDB_ntxn *)txn;
2340 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2341 if (env->me_pghead) {
2342 size = MDB_IDL_SIZEOF(env->me_pghead);
2343 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2345 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2350 rc = mdb_cursor_shadow(parent, txn);
2352 mdb_txn_reset0(txn, "beginchild-fail");
2354 rc = mdb_txn_renew0(txn);
2360 DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2361 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2362 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
2369 mdb_txn_env(MDB_txn *txn)
2371 if(!txn) return NULL;
2375 /** Export or close DBI handles opened in this txn. */
2377 mdb_dbis_update(MDB_txn *txn, int keep)
2380 MDB_dbi n = txn->mt_numdbs;
2381 MDB_env *env = txn->mt_env;
2382 unsigned char *tdbflags = txn->mt_dbflags;
2384 for (i = n; --i >= 2;) {
2385 if (tdbflags[i] & DB_NEW) {
2387 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2389 char *ptr = env->me_dbxs[i].md_name.mv_data;
2390 env->me_dbxs[i].md_name.mv_data = NULL;
2391 env->me_dbxs[i].md_name.mv_size = 0;
2392 env->me_dbflags[i] = 0;
2397 if (keep && env->me_numdbs < n)
2401 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
2402 * May be called twice for readonly txns: First reset it, then abort.
2403 * @param[in] txn the transaction handle to reset
2404 * @param[in] act why the transaction is being reset
2407 mdb_txn_reset0(MDB_txn *txn, const char *act)
2409 MDB_env *env = txn->mt_env;
2411 /* Close any DBI handles opened in this txn */
2412 mdb_dbis_update(txn, 0);
2414 DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2415 act, txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2416 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
2418 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2419 if (txn->mt_u.reader) {
2420 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2421 if (!(env->me_flags & MDB_NOTLS))
2422 txn->mt_u.reader = NULL; /* txn does not own reader */
2424 txn->mt_numdbs = 0; /* close nothing if called again */
2425 txn->mt_dbxs = NULL; /* mark txn as reset */
2427 mdb_cursors_close(txn, 0);
2429 if (!(env->me_flags & MDB_WRITEMAP)) {
2430 mdb_dlist_free(txn);
2432 mdb_midl_free(env->me_pghead);
2434 if (txn->mt_parent) {
2435 txn->mt_parent->mt_child = NULL;
2436 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2437 mdb_midl_free(txn->mt_free_pgs);
2438 mdb_midl_free(txn->mt_spill_pgs);
2439 free(txn->mt_u.dirty_list);
2443 if (mdb_midl_shrink(&txn->mt_free_pgs))
2444 env->me_free_pgs = txn->mt_free_pgs;
2445 env->me_pghead = NULL;
2449 /* The writer mutex was locked in mdb_txn_begin. */
2451 UNLOCK_MUTEX_W(env);
2456 mdb_txn_reset(MDB_txn *txn)
2461 /* This call is only valid for read-only txns */
2462 if (!(txn->mt_flags & MDB_TXN_RDONLY))
2465 mdb_txn_reset0(txn, "reset");
2469 mdb_txn_abort(MDB_txn *txn)
2475 mdb_txn_abort(txn->mt_child);
2477 mdb_txn_reset0(txn, "abort");
2478 /* Free reader slot tied to this txn (if MDB_NOTLS && writable FS) */
2479 if ((txn->mt_flags & MDB_TXN_RDONLY) && txn->mt_u.reader)
2480 txn->mt_u.reader->mr_pid = 0;
2485 /** Save the freelist as of this transaction to the freeDB.
2486 * This changes the freelist. Keep trying until it stabilizes.
2489 mdb_freelist_save(MDB_txn *txn)
2491 /* env->me_pghead[] can grow and shrink during this call.
2492 * env->me_pglast and txn->mt_free_pgs[] can only grow.
2493 * Page numbers cannot disappear from txn->mt_free_pgs[].
2496 MDB_env *env = txn->mt_env;
2497 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
2498 txnid_t pglast = 0, head_id = 0;
2499 pgno_t freecnt = 0, *free_pgs, *mop;
2500 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
2502 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
2504 if (env->me_pghead) {
2505 /* Make sure first page of freeDB is touched and on freelist */
2506 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
2507 if (rc && rc != MDB_NOTFOUND)
2511 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
2512 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
2513 ? SSIZE_MAX : maxfree_1pg;
2516 /* Come back here after each Put() in case freelist changed */
2521 /* If using records from freeDB which we have not yet
2522 * deleted, delete them and any we reserved for me_pghead.
2524 while (pglast < env->me_pglast) {
2525 rc = mdb_cursor_first(&mc, &key, NULL);
2528 pglast = head_id = *(txnid_t *)key.mv_data;
2529 total_room = head_room = 0;
2530 assert(pglast <= env->me_pglast);
2531 rc = mdb_cursor_del(&mc, 0);
2536 /* Save the IDL of pages freed by this txn, to a single record */
2537 if (freecnt < txn->mt_free_pgs[0]) {
2539 /* Make sure last page of freeDB is touched and on freelist */
2540 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
2541 if (rc && rc != MDB_NOTFOUND)
2544 free_pgs = txn->mt_free_pgs;
2545 /* Write to last page of freeDB */
2546 key.mv_size = sizeof(txn->mt_txnid);
2547 key.mv_data = &txn->mt_txnid;
2549 freecnt = free_pgs[0];
2550 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
2551 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2554 /* Retry if mt_free_pgs[] grew during the Put() */
2555 free_pgs = txn->mt_free_pgs;
2556 } while (freecnt < free_pgs[0]);
2557 mdb_midl_sort(free_pgs);
2558 memcpy(data.mv_data, free_pgs, data.mv_size);
2561 unsigned int i = free_pgs[0];
2562 DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
2563 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
2565 DPRINTF(("IDL %"Z"u", free_pgs[i]));
2571 mop = env->me_pghead;
2572 mop_len = mop ? mop[0] : 0;
2574 /* Reserve records for me_pghead[]. Split it if multi-page,
2575 * to avoid searching freeDB for a page range. Use keys in
2576 * range [1,me_pglast]: Smaller than txnid of oldest reader.
2578 if (total_room >= mop_len) {
2579 if (total_room == mop_len || --more < 0)
2581 } else if (head_room >= maxfree_1pg && head_id > 1) {
2582 /* Keep current record (overflow page), add a new one */
2586 /* (Re)write {key = head_id, IDL length = head_room} */
2587 total_room -= head_room;
2588 head_room = mop_len - total_room;
2589 if (head_room > maxfree_1pg && head_id > 1) {
2590 /* Overflow multi-page for part of me_pghead */
2591 head_room /= head_id; /* amortize page sizes */
2592 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
2593 } else if (head_room < 0) {
2594 /* Rare case, not bothering to delete this record */
2597 key.mv_size = sizeof(head_id);
2598 key.mv_data = &head_id;
2599 data.mv_size = (head_room + 1) * sizeof(pgno_t);
2600 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2603 /* IDL is initially empty, zero out at least the length */
2604 pgs = (pgno_t *)data.mv_data;
2605 j = head_room > clean_limit ? head_room : 0;
2609 total_room += head_room;
2612 /* Fill in the reserved me_pghead records */
2618 rc = mdb_cursor_first(&mc, &key, &data);
2619 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
2620 unsigned flags = MDB_CURRENT;
2621 txnid_t id = *(txnid_t *)key.mv_data;
2622 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
2625 assert(len >= 0 && id <= env->me_pglast);
2627 if (len > mop_len) {
2629 data.mv_size = (len + 1) * sizeof(MDB_ID);
2632 data.mv_data = mop -= len;
2635 rc = mdb_cursor_put(&mc, &key, &data, flags);
2637 if (rc || !(mop_len -= len))
2644 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
2645 * @param[in] txn the transaction that's being committed
2646 * @param[in] keep number of initial pages in dirty_list to keep dirty.
2647 * @return 0 on success, non-zero on failure.
2650 mdb_page_flush(MDB_txn *txn, int keep)
2652 MDB_env *env = txn->mt_env;
2653 MDB_ID2L dl = txn->mt_u.dirty_list;
2654 unsigned psize = env->me_psize, j;
2655 int i, pagecount = dl[0].mid, rc;
2656 size_t size = 0, pos = 0;
2658 MDB_page *dp = NULL;
2662 struct iovec iov[MDB_COMMIT_PAGES];
2663 ssize_t wpos = 0, wsize = 0, wres;
2664 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
2670 if (env->me_flags & MDB_WRITEMAP) {
2671 /* Clear dirty flags */
2672 while (++i <= pagecount) {
2674 /* Don't flush this page yet */
2675 if (dp->mp_flags & P_KEEP) {
2676 dp->mp_flags ^= P_KEEP;
2680 dp->mp_flags &= ~P_DIRTY;
2685 /* Write the pages */
2687 if (++i <= pagecount) {
2689 /* Don't flush this page yet */
2690 if (dp->mp_flags & P_KEEP) {
2691 dp->mp_flags ^= P_KEEP;
2696 /* clear dirty flag */
2697 dp->mp_flags &= ~P_DIRTY;
2700 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
2705 /* Windows actually supports scatter/gather I/O, but only on
2706 * unbuffered file handles. Since we're relying on the OS page
2707 * cache for all our data, that's self-defeating. So we just
2708 * write pages one at a time. We use the ov structure to set
2709 * the write offset, to at least save the overhead of a Seek
2712 DPRINTF(("committing page %"Z"u", pgno));
2713 memset(&ov, 0, sizeof(ov));
2714 ov.Offset = pos & 0xffffffff;
2715 ov.OffsetHigh = pos >> 16 >> 16;
2716 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
2718 DPRINTF(("WriteFile: %d", rc));
2722 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
2723 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
2725 /* Write previous page(s) */
2726 #ifdef MDB_USE_PWRITEV
2727 wres = pwritev(env->me_fd, iov, n, wpos);
2730 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
2732 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
2734 DPRINTF(("lseek: %s", strerror(rc)));
2737 wres = writev(env->me_fd, iov, n);
2740 if (wres != wsize) {
2743 DPRINTF(("Write error: %s", strerror(rc)));
2745 rc = EIO; /* TODO: Use which error code? */
2746 DPUTS("short write, filesystem full?");
2757 DPRINTF(("committing page %"Z"u", pgno));
2758 next_pos = pos + size;
2759 iov[n].iov_len = size;
2760 iov[n].iov_base = (char *)dp;
2766 for (i = keep; ++i <= pagecount; ) {
2768 /* This is a page we skipped above */
2771 dl[j].mid = dp->mp_pgno;
2774 mdb_dpage_free(env, dp);
2779 txn->mt_dirty_room += i - j;
2785 mdb_txn_commit(MDB_txn *txn)
2791 assert(txn != NULL);
2792 assert(txn->mt_env != NULL);
2794 if (txn->mt_child) {
2795 rc = mdb_txn_commit(txn->mt_child);
2796 txn->mt_child = NULL;
2803 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2804 mdb_dbis_update(txn, 1);
2805 txn->mt_numdbs = 2; /* so txn_abort() doesn't close any new handles */
2810 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
2811 DPUTS("error flag is set, can't commit");
2813 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
2818 if (txn->mt_parent) {
2819 MDB_txn *parent = txn->mt_parent;
2822 unsigned x, y, len, ps_len;
2824 /* Append our free list to parent's */
2825 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
2828 mdb_midl_free(txn->mt_free_pgs);
2829 /* Failures after this must either undo the changes
2830 * to the parent or set MDB_TXN_ERROR in the parent.
2833 parent->mt_next_pgno = txn->mt_next_pgno;
2834 parent->mt_flags = txn->mt_flags;
2836 /* Merge our cursors into parent's and close them */
2837 mdb_cursors_close(txn, 1);
2839 /* Update parent's DB table. */
2840 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2841 parent->mt_numdbs = txn->mt_numdbs;
2842 parent->mt_dbflags[0] = txn->mt_dbflags[0];
2843 parent->mt_dbflags[1] = txn->mt_dbflags[1];
2844 for (i=2; i<txn->mt_numdbs; i++) {
2845 /* preserve parent's DB_NEW status */
2846 x = parent->mt_dbflags[i] & DB_NEW;
2847 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
2850 dst = parent->mt_u.dirty_list;
2851 src = txn->mt_u.dirty_list;
2852 /* Remove anything in our dirty list from parent's spill list */
2853 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
2855 pspill[0] = (pgno_t)-1;
2856 /* Mark our dirty pages as deleted in parent spill list */
2857 for (i=0, len=src[0].mid; ++i <= len; ) {
2858 MDB_ID pn = src[i].mid << 1;
2859 while (pn > pspill[x])
2861 if (pn == pspill[x]) {
2866 /* Squash deleted pagenums if we deleted any */
2867 for (x=y; ++x <= ps_len; )
2868 if (!(pspill[x] & 1))
2869 pspill[++y] = pspill[x];
2873 /* Find len = length of merging our dirty list with parent's */
2875 dst[0].mid = 0; /* simplify loops */
2876 if (parent->mt_parent) {
2877 len = x + src[0].mid;
2878 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
2879 for (i = x; y && i; y--) {
2880 pgno_t yp = src[y].mid;
2881 while (yp < dst[i].mid)
2883 if (yp == dst[i].mid) {
2888 } else { /* Simplify the above for single-ancestor case */
2889 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
2891 /* Merge our dirty list with parent's */
2893 for (i = len; y; dst[i--] = src[y--]) {
2894 pgno_t yp = src[y].mid;
2895 while (yp < dst[x].mid)
2896 dst[i--] = dst[x--];
2897 if (yp == dst[x].mid)
2898 free(dst[x--].mptr);
2902 free(txn->mt_u.dirty_list);
2903 parent->mt_dirty_room = txn->mt_dirty_room;
2904 if (txn->mt_spill_pgs) {
2905 if (parent->mt_spill_pgs) {
2906 /* TODO: Prevent failure here, so parent does not fail */
2907 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
2909 parent->mt_flags |= MDB_TXN_ERROR;
2910 mdb_midl_free(txn->mt_spill_pgs);
2911 mdb_midl_sort(parent->mt_spill_pgs);
2913 parent->mt_spill_pgs = txn->mt_spill_pgs;
2917 parent->mt_child = NULL;
2918 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
2923 if (txn != env->me_txn) {
2924 DPUTS("attempt to commit unknown transaction");
2929 mdb_cursors_close(txn, 0);
2931 if (!txn->mt_u.dirty_list[0].mid &&
2932 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
2935 DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
2936 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
2938 /* Update DB root pointers */
2939 if (txn->mt_numdbs > 2) {
2943 data.mv_size = sizeof(MDB_db);
2945 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
2946 for (i = 2; i < txn->mt_numdbs; i++) {
2947 if (txn->mt_dbflags[i] & DB_DIRTY) {
2948 data.mv_data = &txn->mt_dbs[i];
2949 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
2956 rc = mdb_freelist_save(txn);
2960 mdb_midl_free(env->me_pghead);
2961 env->me_pghead = NULL;
2962 if (mdb_midl_shrink(&txn->mt_free_pgs))
2963 env->me_free_pgs = txn->mt_free_pgs;
2969 if ((rc = mdb_page_flush(txn, 0)) ||
2970 (rc = mdb_env_sync(env, 0)) ||
2971 (rc = mdb_env_write_meta(txn)))
2977 mdb_dbis_update(txn, 1);
2980 UNLOCK_MUTEX_W(env);
2990 /** Read the environment parameters of a DB environment before
2991 * mapping it into memory.
2992 * @param[in] env the environment handle
2993 * @param[out] meta address of where to store the meta information
2994 * @return 0 on success, non-zero on failure.
2997 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3003 enum { Size = sizeof(pbuf) };
3005 /* We don't know the page size yet, so use a minimum value.
3006 * Read both meta pages so we can use the latest one.
3009 for (i=off=0; i<2; i++, off = meta->mm_psize) {
3013 memset(&ov, 0, sizeof(ov));
3015 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3016 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3019 rc = pread(env->me_fd, &pbuf, Size, off);
3022 if (rc == 0 && off == 0)
3024 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3025 DPRINTF(("read: %s", mdb_strerror(rc)));
3029 p = (MDB_page *)&pbuf;
3031 if (!F_ISSET(p->mp_flags, P_META)) {
3032 DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
3037 if (m->mm_magic != MDB_MAGIC) {
3038 DPUTS("meta has invalid magic");
3042 if (m->mm_version != MDB_DATA_VERSION) {
3043 DPRINTF(("database is version %u, expected version %u",
3044 m->mm_version, MDB_DATA_VERSION));
3045 return MDB_VERSION_MISMATCH;
3048 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3054 /** Write the environment parameters of a freshly created DB environment.
3055 * @param[in] env the environment handle
3056 * @param[out] meta address of where to store the meta information
3057 * @return 0 on success, non-zero on failure.
3060 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3068 memset(&ov, 0, sizeof(ov));
3069 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3071 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3074 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3075 len = pwrite(fd, ptr, size, pos); \
3076 rc = (len >= 0); } while(0)
3079 DPUTS("writing new meta page");
3081 psize = env->me_psize;
3083 meta->mm_magic = MDB_MAGIC;
3084 meta->mm_version = MDB_DATA_VERSION;
3085 meta->mm_mapsize = env->me_mapsize;
3086 meta->mm_psize = psize;
3087 meta->mm_last_pg = 1;
3088 meta->mm_flags = env->me_flags & 0xffff;
3089 meta->mm_flags |= MDB_INTEGERKEY;
3090 meta->mm_dbs[0].md_root = P_INVALID;
3091 meta->mm_dbs[1].md_root = P_INVALID;
3093 p = calloc(2, psize);
3095 p->mp_flags = P_META;
3096 *(MDB_meta *)METADATA(p) = *meta;
3098 q = (MDB_page *)((char *)p + psize);
3100 q->mp_flags = P_META;
3101 *(MDB_meta *)METADATA(q) = *meta;
3103 DO_PWRITE(rc, env->me_fd, p, psize * 2, len, 0);
3106 else if ((unsigned) len == psize * 2)
3114 /** Update the environment info to commit a transaction.
3115 * @param[in] txn the transaction that's being committed
3116 * @return 0 on success, non-zero on failure.
3119 mdb_env_write_meta(MDB_txn *txn)
3122 MDB_meta meta, metab, *mp;
3124 int rc, len, toggle;
3133 assert(txn != NULL);
3134 assert(txn->mt_env != NULL);
3136 toggle = txn->mt_txnid & 1;
3137 DPRINTF(("writing meta page %d for root page %"Z"u",
3138 toggle, txn->mt_dbs[MAIN_DBI].md_root));
3141 mp = env->me_metas[toggle];
3143 if (env->me_flags & MDB_WRITEMAP) {
3144 /* Persist any increases of mapsize config */
3145 if (env->me_mapsize > mp->mm_mapsize)
3146 mp->mm_mapsize = env->me_mapsize;
3147 mp->mm_dbs[0] = txn->mt_dbs[0];
3148 mp->mm_dbs[1] = txn->mt_dbs[1];
3149 mp->mm_last_pg = txn->mt_next_pgno - 1;
3150 mp->mm_txnid = txn->mt_txnid;
3151 if (!(env->me_flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3152 unsigned meta_size = env->me_psize;
3153 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3156 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
3157 if (meta_size < env->me_os_psize)
3158 meta_size += meta_size;
3163 if (MDB_MSYNC(ptr, meta_size, rc)) {
3170 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
3171 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
3173 ptr = (char *)&meta;
3174 if (env->me_mapsize > mp->mm_mapsize) {
3175 /* Persist any increases of mapsize config */
3176 meta.mm_mapsize = env->me_mapsize;
3177 off = offsetof(MDB_meta, mm_mapsize);
3179 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
3181 len = sizeof(MDB_meta) - off;
3184 meta.mm_dbs[0] = txn->mt_dbs[0];
3185 meta.mm_dbs[1] = txn->mt_dbs[1];
3186 meta.mm_last_pg = txn->mt_next_pgno - 1;
3187 meta.mm_txnid = txn->mt_txnid;
3190 off += env->me_psize;
3193 /* Write to the SYNC fd */
3194 mfd = env->me_flags & (MDB_NOSYNC|MDB_NOMETASYNC) ?
3195 env->me_fd : env->me_mfd;
3198 memset(&ov, 0, sizeof(ov));
3200 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3204 rc = pwrite(mfd, ptr, len, off);
3207 rc = rc < 0 ? ErrCode() : EIO;
3208 DPUTS("write failed, disk error?");
3209 /* On a failure, the pagecache still contains the new data.
3210 * Write some old data back, to prevent it from being used.
3211 * Use the non-SYNC fd; we know it will fail anyway.
3213 meta.mm_last_pg = metab.mm_last_pg;
3214 meta.mm_txnid = metab.mm_txnid;
3216 memset(&ov, 0, sizeof(ov));
3218 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3220 r2 = pwrite(env->me_fd, ptr, len, off);
3221 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
3224 env->me_flags |= MDB_FATAL_ERROR;
3228 /* Memory ordering issues are irrelevant; since the entire writer
3229 * is wrapped by wmutex, all of these changes will become visible
3230 * after the wmutex is unlocked. Since the DB is multi-version,
3231 * readers will get consistent data regardless of how fresh or
3232 * how stale their view of these values is.
3235 env->me_txns->mti_txnid = txn->mt_txnid;
3240 /** Check both meta pages to see which one is newer.
3241 * @param[in] env the environment handle
3242 * @return meta toggle (0 or 1).
3245 mdb_env_pick_meta(const MDB_env *env)
3247 return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
3251 mdb_env_create(MDB_env **env)
3255 e = calloc(1, sizeof(MDB_env));
3259 e->me_maxreaders = DEFAULT_READERS;
3260 e->me_maxdbs = e->me_numdbs = 2;
3261 e->me_fd = INVALID_HANDLE_VALUE;
3262 e->me_lfd = INVALID_HANDLE_VALUE;
3263 e->me_mfd = INVALID_HANDLE_VALUE;
3264 #ifdef MDB_USE_POSIX_SEM
3265 e->me_rmutex = SEM_FAILED;
3266 e->me_wmutex = SEM_FAILED;
3268 e->me_pid = getpid();
3269 GET_PAGESIZE(e->me_os_psize);
3270 VGMEMP_CREATE(e,0,0);
3276 mdb_env_map(MDB_env *env, void *addr, int newsize)
3279 unsigned int flags = env->me_flags;
3283 LONG sizelo, sizehi;
3284 sizelo = env->me_mapsize & 0xffffffff;
3285 sizehi = env->me_mapsize >> 16 >> 16; /* only needed on Win64 */
3287 /* Windows won't create mappings for zero length files.
3288 * Just allocate the maxsize right now.
3291 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3292 || !SetEndOfFile(env->me_fd)
3293 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3296 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3297 PAGE_READWRITE : PAGE_READONLY,
3298 sizehi, sizelo, NULL);
3301 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3302 FILE_MAP_WRITE : FILE_MAP_READ,
3303 0, 0, env->me_mapsize, addr);
3304 rc = env->me_map ? 0 : ErrCode();
3309 int prot = PROT_READ;
3310 if (flags & MDB_WRITEMAP) {
3312 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3315 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
3317 if (env->me_map == MAP_FAILED) {
3322 if (flags & MDB_NORDAHEAD) {
3323 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3325 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3327 #ifdef POSIX_MADV_RANDOM
3328 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3329 #endif /* POSIX_MADV_RANDOM */
3330 #endif /* MADV_RANDOM */
3334 /* Can happen because the address argument to mmap() is just a
3335 * hint. mmap() can pick another, e.g. if the range is in use.
3336 * The MAP_FIXED flag would prevent that, but then mmap could
3337 * instead unmap existing pages to make room for the new map.
3339 if (addr && env->me_map != addr)
3340 return EBUSY; /* TODO: Make a new MDB_* error code? */
3342 p = (MDB_page *)env->me_map;
3343 env->me_metas[0] = METADATA(p);
3344 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
3350 mdb_env_set_mapsize(MDB_env *env, size_t size)
3352 /* If env is already open, caller is responsible for making
3353 * sure there are no active txns.
3361 size = env->me_metas[mdb_env_pick_meta(env)]->mm_mapsize;
3362 else if (size < env->me_mapsize) {
3363 /* If the configured size is smaller, make sure it's
3364 * still big enough. Silently round up to minimum if not.
3366 size_t minsize = (env->me_metas[mdb_env_pick_meta(env)]->mm_last_pg + 1) * env->me_psize;
3370 munmap(env->me_map, env->me_mapsize);
3371 env->me_mapsize = size;
3372 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
3373 rc = mdb_env_map(env, old, 1);
3377 env->me_mapsize = size;
3379 env->me_maxpg = env->me_mapsize / env->me_psize;
3384 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
3388 env->me_maxdbs = dbs + 2; /* Named databases + main and free DB */
3393 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
3395 if (env->me_map || readers < 1)
3397 env->me_maxreaders = readers;
3402 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
3404 if (!env || !readers)
3406 *readers = env->me_maxreaders;
3410 /** Further setup required for opening an MDB environment
3413 mdb_env_open2(MDB_env *env)
3415 unsigned int flags = env->me_flags;
3416 int i, newenv = 0, rc;
3420 /* See if we should use QueryLimited */
3422 if ((rc & 0xff) > 5)
3423 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
3425 env->me_pidquery = PROCESS_QUERY_INFORMATION;
3428 memset(&meta, 0, sizeof(meta));
3430 if ((i = mdb_env_read_header(env, &meta)) != 0) {
3433 DPUTS("new mdbenv");
3435 env->me_psize = env->me_os_psize;
3436 if (env->me_psize > MAX_PAGESIZE)
3437 env->me_psize = MAX_PAGESIZE;
3439 env->me_psize = meta.mm_psize;
3442 /* Was a mapsize configured? */
3443 if (!env->me_mapsize) {
3444 /* If this is a new environment, take the default,
3445 * else use the size recorded in the existing env.
3447 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
3448 } else if (env->me_mapsize < meta.mm_mapsize) {
3449 /* If the configured size is smaller, make sure it's
3450 * still big enough. Silently round up to minimum if not.
3452 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
3453 if (env->me_mapsize < minsize)
3454 env->me_mapsize = minsize;
3457 rc = mdb_env_map(env, meta.mm_address, newenv);
3462 if (flags & MDB_FIXEDMAP)
3463 meta.mm_address = env->me_map;
3464 i = mdb_env_init_meta(env, &meta);
3465 if (i != MDB_SUCCESS) {
3469 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
3470 env->me_nodemax = (env->me_psize - PAGEHDRSZ) / MDB_MINKEYS;
3472 env->me_maxpg = env->me_mapsize / env->me_psize;
3475 int toggle = mdb_env_pick_meta(env);
3476 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
3478 DPRINTF(("opened database version %u, pagesize %u",
3479 env->me_metas[0]->mm_version, env->me_psize));
3480 DPRINTF(("using meta page %d", toggle));
3481 DPRINTF(("depth: %u", db->md_depth));
3482 DPRINTF(("entries: %"Z"u", db->md_entries));
3483 DPRINTF(("branch pages: %"Z"u", db->md_branch_pages));
3484 DPRINTF(("leaf pages: %"Z"u", db->md_leaf_pages));
3485 DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
3486 DPRINTF(("root: %"Z"u", db->md_root));
3494 /** Release a reader thread's slot in the reader lock table.
3495 * This function is called automatically when a thread exits.
3496 * @param[in] ptr This points to the slot in the reader lock table.
3499 mdb_env_reader_dest(void *ptr)
3501 MDB_reader *reader = ptr;
3507 /** Junk for arranging thread-specific callbacks on Windows. This is
3508 * necessarily platform and compiler-specific. Windows supports up
3509 * to 1088 keys. Let's assume nobody opens more than 64 environments
3510 * in a single process, for now. They can override this if needed.
3512 #ifndef MAX_TLS_KEYS
3513 #define MAX_TLS_KEYS 64
3515 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
3516 static int mdb_tls_nkeys;
3518 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
3522 case DLL_PROCESS_ATTACH: break;
3523 case DLL_THREAD_ATTACH: break;
3524 case DLL_THREAD_DETACH:
3525 for (i=0; i<mdb_tls_nkeys; i++) {
3526 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
3527 mdb_env_reader_dest(r);
3530 case DLL_PROCESS_DETACH: break;
3535 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3537 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3541 /* Force some symbol references.
3542 * _tls_used forces the linker to create the TLS directory if not already done
3543 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
3545 #pragma comment(linker, "/INCLUDE:_tls_used")
3546 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
3547 #pragma const_seg(".CRT$XLB")
3548 extern const PIMAGE_TLS_CALLBACK mdb_tls_callback;
3549 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3552 #pragma comment(linker, "/INCLUDE:__tls_used")
3553 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
3554 #pragma data_seg(".CRT$XLB")
3555 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3557 #endif /* WIN 32/64 */
3558 #endif /* !__GNUC__ */
3561 /** Downgrade the exclusive lock on the region back to shared */
3563 mdb_env_share_locks(MDB_env *env, int *excl)
3565 int rc = 0, toggle = mdb_env_pick_meta(env);
3567 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
3572 /* First acquire a shared lock. The Unlock will
3573 * then release the existing exclusive lock.
3575 memset(&ov, 0, sizeof(ov));
3576 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3579 UnlockFile(env->me_lfd, 0, 0, 1, 0);
3585 struct flock lock_info;
3586 /* The shared lock replaces the existing lock */
3587 memset((void *)&lock_info, 0, sizeof(lock_info));
3588 lock_info.l_type = F_RDLCK;
3589 lock_info.l_whence = SEEK_SET;
3590 lock_info.l_start = 0;
3591 lock_info.l_len = 1;
3592 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3593 (rc = ErrCode()) == EINTR) ;
3594 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
3601 /** Try to get exlusive lock, otherwise shared.
3602 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
3605 mdb_env_excl_lock(MDB_env *env, int *excl)
3609 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
3613 memset(&ov, 0, sizeof(ov));
3614 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3621 struct flock lock_info;
3622 memset((void *)&lock_info, 0, sizeof(lock_info));
3623 lock_info.l_type = F_WRLCK;
3624 lock_info.l_whence = SEEK_SET;
3625 lock_info.l_start = 0;
3626 lock_info.l_len = 1;
3627 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3628 (rc = ErrCode()) == EINTR) ;
3632 # ifdef MDB_USE_POSIX_SEM
3633 if (*excl < 0) /* always true when !MDB_USE_POSIX_SEM */
3636 lock_info.l_type = F_RDLCK;
3637 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
3638 (rc = ErrCode()) == EINTR) ;
3648 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
3650 * @(#) $Revision: 5.1 $
3651 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
3652 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
3654 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
3658 * Please do not copyright this code. This code is in the public domain.
3660 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
3661 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
3662 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
3663 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
3664 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
3665 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
3666 * PERFORMANCE OF THIS SOFTWARE.
3669 * chongo <Landon Curt Noll> /\oo/\
3670 * http://www.isthe.com/chongo/
3672 * Share and Enjoy! :-)
3675 typedef unsigned long long mdb_hash_t;
3676 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
3678 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
3679 * @param[in] val value to hash
3680 * @param[in] hval initial value for hash
3681 * @return 64 bit hash
3683 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
3684 * hval arg on the first call.
3687 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
3689 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
3690 unsigned char *end = s + val->mv_size;
3692 * FNV-1a hash each octet of the string
3695 /* xor the bottom with the current octet */
3696 hval ^= (mdb_hash_t)*s++;
3698 /* multiply by the 64 bit FNV magic prime mod 2^64 */
3699 hval += (hval << 1) + (hval << 4) + (hval << 5) +
3700 (hval << 7) + (hval << 8) + (hval << 40);
3702 /* return our new hash value */
3706 /** Hash the string and output the encoded hash.
3707 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
3708 * very short name limits. We don't care about the encoding being reversible,
3709 * we just want to preserve as many bits of the input as possible in a
3710 * small printable string.
3711 * @param[in] str string to hash
3712 * @param[out] encbuf an array of 11 chars to hold the hash
3714 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
3717 mdb_pack85(unsigned long l, char *out)
3721 for (i=0; i<5; i++) {
3722 *out++ = mdb_a85[l % 85];
3728 mdb_hash_enc(MDB_val *val, char *encbuf)
3730 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
3732 mdb_pack85(h, encbuf);
3733 mdb_pack85(h>>32, encbuf+5);
3738 /** Open and/or initialize the lock region for the environment.
3739 * @param[in] env The MDB environment.
3740 * @param[in] lpath The pathname of the file used for the lock region.
3741 * @param[in] mode The Unix permissions for the file, if we create it.
3742 * @param[out] excl Resulting file lock type: -1 none, 0 shared, 1 exclusive
3743 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
3744 * @return 0 on success, non-zero on failure.
3747 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
3750 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
3752 # define MDB_ERRCODE_ROFS EROFS
3753 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
3754 # define MDB_CLOEXEC O_CLOEXEC
3757 # define MDB_CLOEXEC 0
3764 env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
3765 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
3766 FILE_ATTRIBUTE_NORMAL, NULL);
3768 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
3770 if (env->me_lfd == INVALID_HANDLE_VALUE) {
3772 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
3777 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
3778 /* Lose record locks when exec*() */
3779 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
3780 fcntl(env->me_lfd, F_SETFD, fdflags);
3783 if (!(env->me_flags & MDB_NOTLS)) {
3784 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
3787 env->me_flags |= MDB_ENV_TXKEY;
3789 /* Windows TLS callbacks need help finding their TLS info. */
3790 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
3794 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
3798 /* Try to get exclusive lock. If we succeed, then
3799 * nobody is using the lock region and we should initialize it.
3801 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
3804 size = GetFileSize(env->me_lfd, NULL);
3806 size = lseek(env->me_lfd, 0, SEEK_END);
3807 if (size == -1) goto fail_errno;
3809 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
3810 if (size < rsize && *excl > 0) {
3812 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != rsize
3813 || !SetEndOfFile(env->me_lfd))
3816 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
3820 size = rsize - sizeof(MDB_txninfo);
3821 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
3826 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
3828 if (!mh) goto fail_errno;
3829 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
3831 if (!env->me_txns) goto fail_errno;
3833 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
3835 if (m == MAP_FAILED) goto fail_errno;
3841 BY_HANDLE_FILE_INFORMATION stbuf;
3850 if (!mdb_sec_inited) {
3851 InitializeSecurityDescriptor(&mdb_null_sd,
3852 SECURITY_DESCRIPTOR_REVISION);
3853 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
3854 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
3855 mdb_all_sa.bInheritHandle = FALSE;
3856 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
3859 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
3860 idbuf.volume = stbuf.dwVolumeSerialNumber;
3861 idbuf.nhigh = stbuf.nFileIndexHigh;
3862 idbuf.nlow = stbuf.nFileIndexLow;
3863 val.mv_data = &idbuf;
3864 val.mv_size = sizeof(idbuf);
3865 mdb_hash_enc(&val, encbuf);
3866 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
3867 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
3868 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
3869 if (!env->me_rmutex) goto fail_errno;
3870 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
3871 if (!env->me_wmutex) goto fail_errno;
3872 #elif defined(MDB_USE_POSIX_SEM)
3881 #if defined(__NetBSD__)
3882 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
3884 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
3885 idbuf.dev = stbuf.st_dev;
3886 idbuf.ino = stbuf.st_ino;
3887 val.mv_data = &idbuf;
3888 val.mv_size = sizeof(idbuf);
3889 mdb_hash_enc(&val, encbuf);
3890 #ifdef MDB_SHORT_SEMNAMES
3891 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
3893 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
3894 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
3895 /* Clean up after a previous run, if needed: Try to
3896 * remove both semaphores before doing anything else.
3898 sem_unlink(env->me_txns->mti_rmname);
3899 sem_unlink(env->me_txns->mti_wmname);
3900 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
3901 O_CREAT|O_EXCL, mode, 1);
3902 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3903 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
3904 O_CREAT|O_EXCL, mode, 1);
3905 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3906 #else /* MDB_USE_POSIX_SEM */
3907 pthread_mutexattr_t mattr;
3909 if ((rc = pthread_mutexattr_init(&mattr))
3910 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
3911 || (rc = pthread_mutex_init(&env->me_txns->mti_mutex, &mattr))
3912 || (rc = pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr)))
3914 pthread_mutexattr_destroy(&mattr);
3915 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
3917 env->me_txns->mti_magic = MDB_MAGIC;
3918 env->me_txns->mti_format = MDB_LOCK_FORMAT;
3919 env->me_txns->mti_txnid = 0;
3920 env->me_txns->mti_numreaders = 0;
3923 if (env->me_txns->mti_magic != MDB_MAGIC) {
3924 DPUTS("lock region has invalid magic");
3928 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
3929 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
3930 env->me_txns->mti_format, MDB_LOCK_FORMAT));
3931 rc = MDB_VERSION_MISMATCH;
3935 if (rc && rc != EACCES && rc != EAGAIN) {
3939 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
3940 if (!env->me_rmutex) goto fail_errno;
3941 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
3942 if (!env->me_wmutex) goto fail_errno;
3943 #elif defined(MDB_USE_POSIX_SEM)
3944 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
3945 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3946 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
3947 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3958 /** The name of the lock file in the DB environment */
3959 #define LOCKNAME "/lock.mdb"
3960 /** The name of the data file in the DB environment */
3961 #define DATANAME "/data.mdb"
3962 /** The suffix of the lock file when no subdir is used */
3963 #define LOCKSUFF "-lock"
3964 /** Only a subset of the @ref mdb_env flags can be changed
3965 * at runtime. Changing other flags requires closing the
3966 * environment and re-opening it with the new flags.
3968 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
3969 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY|MDB_WRITEMAP| \
3970 MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
3973 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
3975 int oflags, rc, len, excl = -1;
3976 char *lpath, *dpath;
3978 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
3982 if (flags & MDB_NOSUBDIR) {
3983 rc = len + sizeof(LOCKSUFF) + len + 1;
3985 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
3990 if (flags & MDB_NOSUBDIR) {
3991 dpath = lpath + len + sizeof(LOCKSUFF);
3992 sprintf(lpath, "%s" LOCKSUFF, path);
3993 strcpy(dpath, path);
3995 dpath = lpath + len + sizeof(LOCKNAME);
3996 sprintf(lpath, "%s" LOCKNAME, path);
3997 sprintf(dpath, "%s" DATANAME, path);
4001 flags |= env->me_flags;
4002 if (flags & MDB_RDONLY) {
4003 /* silently ignore WRITEMAP when we're only getting read access */
4004 flags &= ~MDB_WRITEMAP;
4006 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
4007 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
4010 env->me_flags = flags |= MDB_ENV_ACTIVE;
4014 env->me_path = strdup(path);
4015 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
4016 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
4017 if (!(env->me_dbxs && env->me_path && env->me_dbflags)) {
4022 /* For RDONLY, get lockfile after we know datafile exists */
4023 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
4024 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4030 if (F_ISSET(flags, MDB_RDONLY)) {
4031 oflags = GENERIC_READ;
4032 len = OPEN_EXISTING;
4034 oflags = GENERIC_READ|GENERIC_WRITE;
4037 mode = FILE_ATTRIBUTE_NORMAL;
4038 env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
4039 NULL, len, mode, NULL);
4041 if (F_ISSET(flags, MDB_RDONLY))
4044 oflags = O_RDWR | O_CREAT;
4046 env->me_fd = open(dpath, oflags, mode);
4048 if (env->me_fd == INVALID_HANDLE_VALUE) {
4053 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
4054 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4059 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
4060 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
4061 env->me_mfd = env->me_fd;
4063 /* Synchronous fd for meta writes. Needed even with
4064 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
4067 len = OPEN_EXISTING;
4068 env->me_mfd = CreateFile(dpath, oflags,
4069 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
4070 mode | FILE_FLAG_WRITE_THROUGH, NULL);
4073 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
4075 if (env->me_mfd == INVALID_HANDLE_VALUE) {
4080 DPRINTF(("opened dbenv %p", (void *) env));
4082 rc = mdb_env_share_locks(env, &excl);
4086 if (!((flags & MDB_RDONLY) ||
4087 (env->me_pbuf = calloc(1, env->me_psize))))
4093 mdb_env_close0(env, excl);
4099 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
4101 mdb_env_close0(MDB_env *env, int excl)
4105 if (!(env->me_flags & MDB_ENV_ACTIVE))
4108 /* Doing this here since me_dbxs may not exist during mdb_env_close */
4109 for (i = env->me_maxdbs; --i > MAIN_DBI; )
4110 free(env->me_dbxs[i].md_name.mv_data);
4113 free(env->me_dbflags);
4116 free(env->me_dirty_list);
4117 mdb_midl_free(env->me_free_pgs);
4119 if (env->me_flags & MDB_ENV_TXKEY) {
4120 pthread_key_delete(env->me_txkey);
4122 /* Delete our key from the global list */
4123 for (i=0; i<mdb_tls_nkeys; i++)
4124 if (mdb_tls_keys[i] == env->me_txkey) {
4125 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
4133 munmap(env->me_map, env->me_mapsize);
4135 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
4136 (void) close(env->me_mfd);
4137 if (env->me_fd != INVALID_HANDLE_VALUE)
4138 (void) close(env->me_fd);
4140 pid_t pid = env->me_pid;
4141 /* Clearing readers is done in this function because
4142 * me_txkey with its destructor must be disabled first.
4144 for (i = env->me_numreaders; --i >= 0; )
4145 if (env->me_txns->mti_readers[i].mr_pid == pid)
4146 env->me_txns->mti_readers[i].mr_pid = 0;
4148 if (env->me_rmutex) {
4149 CloseHandle(env->me_rmutex);
4150 if (env->me_wmutex) CloseHandle(env->me_wmutex);
4152 /* Windows automatically destroys the mutexes when
4153 * the last handle closes.
4155 #elif defined(MDB_USE_POSIX_SEM)
4156 if (env->me_rmutex != SEM_FAILED) {
4157 sem_close(env->me_rmutex);
4158 if (env->me_wmutex != SEM_FAILED)
4159 sem_close(env->me_wmutex);
4160 /* If we have the filelock: If we are the
4161 * only remaining user, clean up semaphores.
4164 mdb_env_excl_lock(env, &excl);
4166 sem_unlink(env->me_txns->mti_rmname);
4167 sem_unlink(env->me_txns->mti_wmname);
4171 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
4173 if (env->me_lfd != INVALID_HANDLE_VALUE) {
4176 /* Unlock the lockfile. Windows would have unlocked it
4177 * after closing anyway, but not necessarily at once.
4179 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4182 (void) close(env->me_lfd);
4185 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
4189 mdb_env_copyfd(MDB_env *env, HANDLE fd)
4191 MDB_txn *txn = NULL;
4197 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
4201 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
4204 /* Do the lock/unlock of the reader mutex before starting the
4205 * write txn. Otherwise other read txns could block writers.
4207 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
4212 /* We must start the actual read txn after blocking writers */
4213 mdb_txn_reset0(txn, "reset-stage1");
4215 /* Temporarily block writers until we snapshot the meta pages */
4218 rc = mdb_txn_renew0(txn);
4220 UNLOCK_MUTEX_W(env);
4225 wsize = env->me_psize * 2;
4229 DO_WRITE(rc, fd, ptr, w2, len);
4233 } else if (len > 0) {
4239 /* Non-blocking or async handles are not supported */
4245 UNLOCK_MUTEX_W(env);
4250 wsize = txn->mt_next_pgno * env->me_psize - wsize;
4252 if (wsize > MAX_WRITE)
4256 DO_WRITE(rc, fd, ptr, w2, len);
4260 } else if (len > 0) {
4277 mdb_env_copy(MDB_env *env, const char *path)
4281 HANDLE newfd = INVALID_HANDLE_VALUE;
4283 if (env->me_flags & MDB_NOSUBDIR) {
4284 lpath = (char *)path;
4287 len += sizeof(DATANAME);
4288 lpath = malloc(len);
4291 sprintf(lpath, "%s" DATANAME, path);
4294 /* The destination path must exist, but the destination file must not.
4295 * We don't want the OS to cache the writes, since the source data is
4296 * already in the OS cache.
4299 newfd = CreateFile(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
4300 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
4302 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
4304 if (newfd == INVALID_HANDLE_VALUE) {
4310 /* Set O_DIRECT if the file system supports it */
4311 if ((rc = fcntl(newfd, F_GETFL)) != -1)
4312 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
4314 #ifdef F_NOCACHE /* __APPLE__ */
4315 rc = fcntl(newfd, F_NOCACHE, 1);
4322 rc = mdb_env_copyfd(env, newfd);
4325 if (!(env->me_flags & MDB_NOSUBDIR))
4327 if (newfd != INVALID_HANDLE_VALUE)
4328 if (close(newfd) < 0 && rc == MDB_SUCCESS)
4335 mdb_env_close(MDB_env *env)
4342 VGMEMP_DESTROY(env);
4343 while ((dp = env->me_dpages) != NULL) {
4344 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
4345 env->me_dpages = dp->mp_next;
4349 mdb_env_close0(env, 0);
4353 /** Compare two items pointing at aligned size_t's */
4355 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
4357 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
4358 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
4361 /** Compare two items pointing at aligned unsigned int's */
4363 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
4365 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
4366 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
4369 /** Compare two items pointing at unsigned ints of unknown alignment.
4370 * Nodes and keys are guaranteed to be 2-byte aligned.
4373 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
4375 #if BYTE_ORDER == LITTLE_ENDIAN
4376 unsigned short *u, *c;
4379 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4380 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
4383 } while(!x && u > (unsigned short *)a->mv_data);
4386 return memcmp(a->mv_data, b->mv_data, a->mv_size);
4390 /** Compare two items lexically */
4392 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
4399 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4405 diff = memcmp(a->mv_data, b->mv_data, len);
4406 return diff ? diff : len_diff<0 ? -1 : len_diff;
4409 /** Compare two items in reverse byte order */
4411 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
4413 const unsigned char *p1, *p2, *p1_lim;
4417 p1_lim = (const unsigned char *)a->mv_data;
4418 p1 = (const unsigned char *)a->mv_data + a->mv_size;
4419 p2 = (const unsigned char *)b->mv_data + b->mv_size;
4421 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4427 while (p1 > p1_lim) {
4428 diff = *--p1 - *--p2;
4432 return len_diff<0 ? -1 : len_diff;
4435 /** Search for key within a page, using binary search.
4436 * Returns the smallest entry larger or equal to the key.
4437 * If exactp is non-null, stores whether the found entry was an exact match
4438 * in *exactp (1 or 0).
4439 * Updates the cursor index with the index of the found entry.
4440 * If no entry larger or equal to the key is found, returns NULL.
4443 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
4445 unsigned int i = 0, nkeys;
4448 MDB_page *mp = mc->mc_pg[mc->mc_top];
4449 MDB_node *node = NULL;
4454 nkeys = NUMKEYS(mp);
4459 COPY_PGNO(pgno, mp->mp_pgno);
4460 DPRINTF(("searching %u keys in %s %spage %"Z"u",
4461 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
4468 low = IS_LEAF(mp) ? 0 : 1;
4470 cmp = mc->mc_dbx->md_cmp;
4472 /* Branch pages have no data, so if using integer keys,
4473 * alignment is guaranteed. Use faster mdb_cmp_int.
4475 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
4476 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
4483 nodekey.mv_size = mc->mc_db->md_pad;
4484 node = NODEPTR(mp, 0); /* fake */
4485 while (low <= high) {
4486 i = (low + high) >> 1;
4487 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
4488 rc = cmp(key, &nodekey);
4489 DPRINTF(("found leaf index %u [%s], rc = %i",
4490 i, DKEY(&nodekey), rc));
4499 while (low <= high) {
4500 i = (low + high) >> 1;
4502 node = NODEPTR(mp, i);
4503 nodekey.mv_size = NODEKSZ(node);
4504 nodekey.mv_data = NODEKEY(node);
4506 rc = cmp(key, &nodekey);
4509 DPRINTF(("found leaf index %u [%s], rc = %i",
4510 i, DKEY(&nodekey), rc));
4512 DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
4513 i, DKEY(&nodekey), NODEPGNO(node), rc));
4524 if (rc > 0) { /* Found entry is less than the key. */
4525 i++; /* Skip to get the smallest entry larger than key. */
4527 node = NODEPTR(mp, i);
4530 *exactp = (rc == 0);
4531 /* store the key index */
4532 mc->mc_ki[mc->mc_top] = i;
4534 /* There is no entry larger or equal to the key. */
4537 /* nodeptr is fake for LEAF2 */
4543 mdb_cursor_adjust(MDB_cursor *mc, func)
4547 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4548 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
4555 /** Pop a page off the top of the cursor's stack. */
4557 mdb_cursor_pop(MDB_cursor *mc)
4561 MDB_page *top = mc->mc_pg[mc->mc_top];
4567 DPRINTF(("popped page %"Z"u off db %d cursor %p", top->mp_pgno,
4568 DDBI(mc), (void *) mc));
4572 /** Push a page onto the top of the cursor's stack. */
4574 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
4576 DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
4577 DDBI(mc), (void *) mc));
4579 if (mc->mc_snum >= CURSOR_STACK) {
4580 assert(mc->mc_snum < CURSOR_STACK);
4581 return MDB_CURSOR_FULL;
4584 mc->mc_top = mc->mc_snum++;
4585 mc->mc_pg[mc->mc_top] = mp;
4586 mc->mc_ki[mc->mc_top] = 0;
4591 /** Find the address of the page corresponding to a given page number.
4592 * @param[in] txn the transaction for this access.
4593 * @param[in] pgno the page number for the page to retrieve.
4594 * @param[out] ret address of a pointer where the page's address will be stored.
4595 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
4596 * @return 0 on success, non-zero on failure.
4599 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
4601 MDB_env *env = txn->mt_env;
4605 if (!((txn->mt_flags & MDB_TXN_RDONLY) | (env->me_flags & MDB_WRITEMAP))) {
4609 MDB_ID2L dl = tx2->mt_u.dirty_list;
4611 /* Spilled pages were dirtied in this txn and flushed
4612 * because the dirty list got full. Bring this page
4613 * back in from the map (but don't unspill it here,
4614 * leave that unless page_touch happens again).
4616 if (tx2->mt_spill_pgs) {
4617 MDB_ID pn = pgno << 1;
4618 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
4619 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
4620 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
4625 unsigned x = mdb_mid2l_search(dl, pgno);
4626 if (x <= dl[0].mid && dl[x].mid == pgno) {
4632 } while ((tx2 = tx2->mt_parent) != NULL);
4635 if (pgno < txn->mt_next_pgno) {
4637 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
4639 DPRINTF(("page %"Z"u not found", pgno));
4641 return MDB_PAGE_NOTFOUND;
4651 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
4652 * The cursor is at the root page, set up the rest of it.
4655 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
4657 MDB_page *mp = mc->mc_pg[mc->mc_top];
4661 while (IS_BRANCH(mp)) {
4665 DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
4666 assert(NUMKEYS(mp) > 1);
4667 DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
4669 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
4671 if (flags & MDB_PS_LAST)
4672 i = NUMKEYS(mp) - 1;
4675 node = mdb_node_search(mc, key, &exact);
4677 i = NUMKEYS(mp) - 1;
4679 i = mc->mc_ki[mc->mc_top];
4685 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
4688 assert(i < NUMKEYS(mp));
4689 node = NODEPTR(mp, i);
4691 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4694 mc->mc_ki[mc->mc_top] = i;
4695 if ((rc = mdb_cursor_push(mc, mp)))
4698 if (flags & MDB_PS_MODIFY) {
4699 if ((rc = mdb_page_touch(mc)) != 0)
4701 mp = mc->mc_pg[mc->mc_top];
4706 DPRINTF(("internal error, index points to a %02X page!?",
4708 return MDB_CORRUPTED;
4711 DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
4712 key ? DKEY(key) : "null"));
4713 mc->mc_flags |= C_INITIALIZED;
4714 mc->mc_flags &= ~C_EOF;
4719 /** Search for the lowest key under the current branch page.
4720 * This just bypasses a NUMKEYS check in the current page
4721 * before calling mdb_page_search_root(), because the callers
4722 * are all in situations where the current page is known to
4726 mdb_page_search_lowest(MDB_cursor *mc)
4728 MDB_page *mp = mc->mc_pg[mc->mc_top];
4729 MDB_node *node = NODEPTR(mp, 0);
4732 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4735 mc->mc_ki[mc->mc_top] = 0;
4736 if ((rc = mdb_cursor_push(mc, mp)))
4738 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
4741 /** Search for the page a given key should be in.
4742 * Push it and its parent pages on the cursor stack.
4743 * @param[in,out] mc the cursor for this operation.
4744 * @param[in] key the key to search for, or NULL for first/last page.
4745 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
4746 * are touched (updated with new page numbers).
4747 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
4748 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
4749 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
4750 * @return 0 on success, non-zero on failure.
4753 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
4758 /* Make sure the txn is still viable, then find the root from
4759 * the txn's db table and set it as the root of the cursor's stack.
4761 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
4762 DPUTS("transaction has failed, must abort");
4765 /* Make sure we're using an up-to-date root */
4766 if (*mc->mc_dbflag & DB_STALE) {
4768 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
4769 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
4776 MDB_node *leaf = mdb_node_search(&mc2,
4777 &mc->mc_dbx->md_name, &exact);
4779 return MDB_NOTFOUND;
4780 rc = mdb_node_read(mc->mc_txn, leaf, &data);
4783 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
4785 /* The txn may not know this DBI, or another process may
4786 * have dropped and recreated the DB with other flags.
4788 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
4789 return MDB_INCOMPATIBLE;
4790 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
4792 *mc->mc_dbflag &= ~DB_STALE;
4794 root = mc->mc_db->md_root;
4796 if (root == P_INVALID) { /* Tree is empty. */
4797 DPUTS("tree is empty");
4798 return MDB_NOTFOUND;
4803 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
4804 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0], NULL)) != 0)
4810 DPRINTF(("db %d root page %"Z"u has flags 0x%X",
4811 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
4813 if (flags & MDB_PS_MODIFY) {
4814 if ((rc = mdb_page_touch(mc)))
4818 if (flags & MDB_PS_ROOTONLY)
4821 return mdb_page_search_root(mc, key, flags);
4825 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
4827 MDB_txn *txn = mc->mc_txn;
4828 pgno_t pg = mp->mp_pgno;
4829 unsigned x = 0, ovpages = mp->mp_pages;
4830 MDB_env *env = txn->mt_env;
4831 MDB_IDL sl = txn->mt_spill_pgs;
4832 MDB_ID pn = pg << 1;
4835 DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
4836 /* If the page is dirty or on the spill list we just acquired it,
4837 * so we should give it back to our current free list, if any.
4838 * Otherwise put it onto the list of pages we freed in this txn.
4840 * Won't create me_pghead: me_pglast must be inited along with it.
4841 * Unsupported in nested txns: They would need to hide the page
4842 * range in ancestor txns' dirty and spilled lists.
4844 if (env->me_pghead &&
4846 ((mp->mp_flags & P_DIRTY) ||
4847 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
4851 MDB_ID2 *dl, ix, iy;
4852 rc = mdb_midl_need(&env->me_pghead, ovpages);
4855 if (!(mp->mp_flags & P_DIRTY)) {
4856 /* This page is no longer spilled */
4863 /* Remove from dirty list */
4864 dl = txn->mt_u.dirty_list;
4866 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
4874 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
4875 txn->mt_flags |= MDB_TXN_ERROR;
4876 return MDB_CORRUPTED;
4879 if (!(env->me_flags & MDB_WRITEMAP))
4880 mdb_dpage_free(env, mp);
4882 /* Insert in me_pghead */
4883 mop = env->me_pghead;
4884 j = mop[0] + ovpages;
4885 for (i = mop[0]; i && mop[i] < pg; i--)
4891 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
4895 mc->mc_db->md_overflow_pages -= ovpages;
4899 /** Return the data associated with a given node.
4900 * @param[in] txn The transaction for this operation.
4901 * @param[in] leaf The node being read.
4902 * @param[out] data Updated to point to the node's data.
4903 * @return 0 on success, non-zero on failure.
4906 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
4908 MDB_page *omp; /* overflow page */
4912 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
4913 data->mv_size = NODEDSZ(leaf);
4914 data->mv_data = NODEDATA(leaf);
4918 /* Read overflow data.
4920 data->mv_size = NODEDSZ(leaf);
4921 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
4922 if ((rc = mdb_page_get(txn, pgno, &omp, NULL)) != 0) {
4923 DPRINTF(("read overflow page %"Z"u failed", pgno));
4926 data->mv_data = METADATA(omp);
4932 mdb_get(MDB_txn *txn, MDB_dbi dbi,
4933 MDB_val *key, MDB_val *data)
4942 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
4944 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
4947 if (txn->mt_flags & MDB_TXN_ERROR)
4950 if (key->mv_size > MDB_MAXKEYSIZE) {
4951 return MDB_BAD_VALSIZE;
4954 mdb_cursor_init(&mc, txn, dbi, &mx);
4955 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
4958 /** Find a sibling for a page.
4959 * Replaces the page at the top of the cursor's stack with the
4960 * specified sibling, if one exists.
4961 * @param[in] mc The cursor for this operation.
4962 * @param[in] move_right Non-zero if the right sibling is requested,
4963 * otherwise the left sibling.
4964 * @return 0 on success, non-zero on failure.
4967 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
4973 if (mc->mc_snum < 2) {
4974 return MDB_NOTFOUND; /* root has no siblings */
4978 DPRINTF(("parent page is page %"Z"u, index %u",
4979 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
4981 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
4982 : (mc->mc_ki[mc->mc_top] == 0)) {
4983 DPRINTF(("no more keys left, moving to %s sibling",
4984 move_right ? "right" : "left"));
4985 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
4986 /* undo cursor_pop before returning */
4993 mc->mc_ki[mc->mc_top]++;
4995 mc->mc_ki[mc->mc_top]--;
4996 DPRINTF(("just moving to %s index key %u",
4997 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
4999 assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
5001 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5002 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL)) != 0) {
5003 /* mc will be inconsistent if caller does mc_snum++ as above */
5004 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
5008 mdb_cursor_push(mc, mp);
5010 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
5015 /** Move the cursor to the next data item. */
5017 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5023 if (mc->mc_flags & C_EOF) {
5024 return MDB_NOTFOUND;
5027 assert(mc->mc_flags & C_INITIALIZED);
5029 mp = mc->mc_pg[mc->mc_top];
5031 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5032 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5033 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5034 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
5035 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
5036 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
5037 if (rc == MDB_SUCCESS)
5038 MDB_GET_KEY(leaf, key);
5043 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5044 if (op == MDB_NEXT_DUP)
5045 return MDB_NOTFOUND;
5049 DPRINTF(("cursor_next: top page is %"Z"u in cursor %p", mp->mp_pgno, (void *) mc));
5050 if (mc->mc_flags & C_DEL)
5053 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
5054 DPUTS("=====> move to next sibling page");
5055 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5056 mc->mc_flags |= C_EOF;
5059 mp = mc->mc_pg[mc->mc_top];
5060 DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5062 mc->mc_ki[mc->mc_top]++;
5065 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5066 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5069 key->mv_size = mc->mc_db->md_pad;
5070 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5074 assert(IS_LEAF(mp));
5075 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5077 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5078 mdb_xcursor_init1(mc, leaf);
5081 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5084 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5085 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5086 if (rc != MDB_SUCCESS)
5091 MDB_GET_KEY(leaf, key);
5095 /** Move the cursor to the previous data item. */
5097 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5103 assert(mc->mc_flags & C_INITIALIZED);
5105 mp = mc->mc_pg[mc->mc_top];
5107 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5108 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5109 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5110 if (op == MDB_PREV || op == MDB_PREV_DUP) {
5111 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
5112 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
5113 if (rc == MDB_SUCCESS)
5114 MDB_GET_KEY(leaf, key);
5118 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5119 if (op == MDB_PREV_DUP)
5120 return MDB_NOTFOUND;
5125 DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p", mp->mp_pgno, (void *) mc));
5127 if (mc->mc_ki[mc->mc_top] == 0) {
5128 DPUTS("=====> move to prev sibling page");
5129 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
5132 mp = mc->mc_pg[mc->mc_top];
5133 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
5134 DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5136 mc->mc_ki[mc->mc_top]--;
5138 mc->mc_flags &= ~C_EOF;
5140 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5141 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5144 key->mv_size = mc->mc_db->md_pad;
5145 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5149 assert(IS_LEAF(mp));
5150 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5152 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5153 mdb_xcursor_init1(mc, leaf);
5156 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5159 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5160 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5161 if (rc != MDB_SUCCESS)
5166 MDB_GET_KEY(leaf, key);
5170 /** Set the cursor on a specific data item. */
5172 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5173 MDB_cursor_op op, int *exactp)
5177 MDB_node *leaf = NULL;
5182 if (key->mv_size == 0)
5183 return MDB_BAD_VALSIZE;
5186 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5188 /* See if we're already on the right page */
5189 if (mc->mc_flags & C_INITIALIZED) {
5192 mp = mc->mc_pg[mc->mc_top];
5194 mc->mc_ki[mc->mc_top] = 0;
5195 return MDB_NOTFOUND;
5197 if (mp->mp_flags & P_LEAF2) {
5198 nodekey.mv_size = mc->mc_db->md_pad;
5199 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
5201 leaf = NODEPTR(mp, 0);
5202 MDB_GET_KEY2(leaf, nodekey);
5204 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5206 /* Probably happens rarely, but first node on the page
5207 * was the one we wanted.
5209 mc->mc_ki[mc->mc_top] = 0;
5216 unsigned int nkeys = NUMKEYS(mp);
5218 if (mp->mp_flags & P_LEAF2) {
5219 nodekey.mv_data = LEAF2KEY(mp,
5220 nkeys-1, nodekey.mv_size);
5222 leaf = NODEPTR(mp, nkeys-1);
5223 MDB_GET_KEY2(leaf, nodekey);
5225 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5227 /* last node was the one we wanted */
5228 mc->mc_ki[mc->mc_top] = nkeys-1;
5234 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
5235 /* This is definitely the right page, skip search_page */
5236 if (mp->mp_flags & P_LEAF2) {
5237 nodekey.mv_data = LEAF2KEY(mp,
5238 mc->mc_ki[mc->mc_top], nodekey.mv_size);
5240 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5241 MDB_GET_KEY2(leaf, nodekey);
5243 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5245 /* current node was the one we wanted */
5255 /* If any parents have right-sibs, search.
5256 * Otherwise, there's nothing further.
5258 for (i=0; i<mc->mc_top; i++)
5260 NUMKEYS(mc->mc_pg[i])-1)
5262 if (i == mc->mc_top) {
5263 /* There are no other pages */
5264 mc->mc_ki[mc->mc_top] = nkeys;
5265 return MDB_NOTFOUND;
5269 /* There are no other pages */
5270 mc->mc_ki[mc->mc_top] = 0;
5271 if (op == MDB_SET_RANGE) {
5275 return MDB_NOTFOUND;
5279 rc = mdb_page_search(mc, key, 0);
5280 if (rc != MDB_SUCCESS)
5283 mp = mc->mc_pg[mc->mc_top];
5284 assert(IS_LEAF(mp));
5287 leaf = mdb_node_search(mc, key, exactp);
5288 if (exactp != NULL && !*exactp) {
5289 /* MDB_SET specified and not an exact match. */
5290 return MDB_NOTFOUND;
5294 DPUTS("===> inexact leaf not found, goto sibling");
5295 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
5296 return rc; /* no entries matched */
5297 mp = mc->mc_pg[mc->mc_top];
5298 assert(IS_LEAF(mp));
5299 leaf = NODEPTR(mp, 0);
5303 mc->mc_flags |= C_INITIALIZED;
5304 mc->mc_flags &= ~C_EOF;
5307 key->mv_size = mc->mc_db->md_pad;
5308 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5312 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5313 mdb_xcursor_init1(mc, leaf);
5316 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5317 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
5318 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5321 if (op == MDB_GET_BOTH) {
5327 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
5328 if (rc != MDB_SUCCESS)
5331 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
5333 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
5335 rc = mc->mc_dbx->md_dcmp(data, &d2);
5337 if (op == MDB_GET_BOTH || rc > 0)
5338 return MDB_NOTFOUND;
5344 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5345 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5350 /* The key already matches in all other cases */
5351 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
5352 MDB_GET_KEY(leaf, key);
5353 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
5358 /** Move the cursor to the first item in the database. */
5360 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5366 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5368 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5369 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
5370 if (rc != MDB_SUCCESS)
5373 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
5375 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
5376 mc->mc_flags |= C_INITIALIZED;
5377 mc->mc_flags &= ~C_EOF;
5379 mc->mc_ki[mc->mc_top] = 0;
5381 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5382 key->mv_size = mc->mc_db->md_pad;
5383 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
5388 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5389 mdb_xcursor_init1(mc, leaf);
5390 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5394 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5398 MDB_GET_KEY(leaf, key);
5402 /** Move the cursor to the last item in the database. */
5404 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5410 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5412 if (!(mc->mc_flags & C_EOF)) {
5414 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5415 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
5416 if (rc != MDB_SUCCESS)
5419 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
5422 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
5423 mc->mc_flags |= C_INITIALIZED|C_EOF;
5424 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5426 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5427 key->mv_size = mc->mc_db->md_pad;
5428 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
5433 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5434 mdb_xcursor_init1(mc, leaf);
5435 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5439 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5444 MDB_GET_KEY(leaf, key);
5449 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5454 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
5458 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
5462 case MDB_GET_CURRENT:
5463 if (!(mc->mc_flags & C_INITIALIZED)) {
5466 MDB_page *mp = mc->mc_pg[mc->mc_top];
5467 int nkeys = NUMKEYS(mp);
5468 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
5469 mc->mc_ki[mc->mc_top] = nkeys;
5475 key->mv_size = mc->mc_db->md_pad;
5476 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5478 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5479 MDB_GET_KEY(leaf, key);
5481 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5482 if (mc->mc_flags & C_DEL)
5483 mdb_xcursor_init1(mc, leaf);
5484 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
5486 rc = mdb_node_read(mc->mc_txn, leaf, data);
5493 case MDB_GET_BOTH_RANGE:
5498 if (mc->mc_xcursor == NULL) {
5499 rc = MDB_INCOMPATIBLE;
5508 } else if (key->mv_size > MDB_MAXKEYSIZE) {
5509 rc = MDB_BAD_VALSIZE;
5510 } else if (op == MDB_SET_RANGE)
5511 rc = mdb_cursor_set(mc, key, data, op, NULL);
5513 rc = mdb_cursor_set(mc, key, data, op, &exact);
5515 case MDB_GET_MULTIPLE:
5516 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5520 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5521 rc = MDB_INCOMPATIBLE;
5525 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
5526 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
5529 case MDB_NEXT_MULTIPLE:
5534 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5535 rc = MDB_INCOMPATIBLE;
5538 if (!(mc->mc_flags & C_INITIALIZED))
5539 rc = mdb_cursor_first(mc, key, data);
5541 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
5542 if (rc == MDB_SUCCESS) {
5543 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
5546 mx = &mc->mc_xcursor->mx_cursor;
5547 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
5549 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
5550 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
5558 case MDB_NEXT_NODUP:
5559 if (!(mc->mc_flags & C_INITIALIZED))
5560 rc = mdb_cursor_first(mc, key, data);
5562 rc = mdb_cursor_next(mc, key, data, op);
5566 case MDB_PREV_NODUP:
5567 if (!(mc->mc_flags & C_INITIALIZED)) {
5568 rc = mdb_cursor_last(mc, key, data);
5571 mc->mc_flags |= C_INITIALIZED;
5572 mc->mc_ki[mc->mc_top]++;
5574 rc = mdb_cursor_prev(mc, key, data, op);
5577 rc = mdb_cursor_first(mc, key, data);
5580 mfunc = mdb_cursor_first;
5582 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5586 if (mc->mc_xcursor == NULL) {
5587 rc = MDB_INCOMPATIBLE;
5590 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
5594 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
5597 rc = mdb_cursor_last(mc, key, data);
5600 mfunc = mdb_cursor_last;
5603 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
5608 if (mc->mc_flags & C_DEL)
5609 mc->mc_flags ^= C_DEL;
5614 /** Touch all the pages in the cursor stack. Set mc_top.
5615 * Makes sure all the pages are writable, before attempting a write operation.
5616 * @param[in] mc The cursor to operate on.
5619 mdb_cursor_touch(MDB_cursor *mc)
5621 int rc = MDB_SUCCESS;
5623 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
5626 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
5627 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
5630 *mc->mc_dbflag |= DB_DIRTY;
5635 rc = mdb_page_touch(mc);
5636 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
5637 mc->mc_top = mc->mc_snum-1;
5642 /** Do not spill pages to disk if txn is getting full, may fail instead */
5643 #define MDB_NOSPILL 0x8000
5646 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5649 enum { MDB_NO_ROOT = MDB_LAST_ERRCODE+10 }; /* internal code */
5650 MDB_env *env = mc->mc_txn->mt_env;
5651 MDB_node *leaf = NULL;
5652 MDB_val xdata, *rdata, dkey;
5654 int do_sub = 0, insert = 0;
5655 unsigned int mcount = 0, dcount = 0, nospill;
5658 char dbuf[MDB_MAXKEYSIZE+1];
5659 unsigned int nflags;
5662 /* Check this first so counter will always be zero on any
5665 if (flags & MDB_MULTIPLE) {
5666 dcount = data[1].mv_size;
5667 data[1].mv_size = 0;
5668 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
5669 return MDB_INCOMPATIBLE;
5672 nospill = flags & MDB_NOSPILL;
5673 flags &= ~MDB_NOSPILL;
5675 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
5676 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
5678 if (flags != MDB_CURRENT && (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE))
5679 return MDB_BAD_VALSIZE;
5681 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT) && data->mv_size > MDB_MAXKEYSIZE)
5682 return MDB_BAD_VALSIZE;
5684 #if SIZE_MAX > MAXDATASIZE
5685 if (data->mv_size > MAXDATASIZE)
5686 return MDB_BAD_VALSIZE;
5689 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
5690 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
5694 if (flags == MDB_CURRENT) {
5695 if (!(mc->mc_flags & C_INITIALIZED))
5698 } else if (mc->mc_db->md_root == P_INVALID) {
5699 /* new database, cursor has nothing to point to */
5702 mc->mc_flags &= ~C_INITIALIZED;
5707 if (flags & MDB_APPEND) {
5709 rc = mdb_cursor_last(mc, &k2, &d2);
5711 rc = mc->mc_dbx->md_cmp(key, &k2);
5714 mc->mc_ki[mc->mc_top]++;
5716 /* new key is <= last key */
5721 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
5723 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
5724 DPRINTF(("duplicate key [%s]", DKEY(key)));
5726 return MDB_KEYEXIST;
5728 if (rc && rc != MDB_NOTFOUND)
5732 if (mc->mc_flags & C_DEL)
5733 mc->mc_flags ^= C_DEL;
5735 /* Cursor is positioned, check for room in the dirty list */
5737 if (flags & MDB_MULTIPLE) {
5739 xdata.mv_size = data->mv_size * dcount;
5743 if ((rc2 = mdb_page_spill(mc, key, rdata)))
5747 if (rc == MDB_NO_ROOT) {
5749 /* new database, write a root leaf page */
5750 DPUTS("allocating new root leaf page");
5751 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
5754 mdb_cursor_push(mc, np);
5755 mc->mc_db->md_root = np->mp_pgno;
5756 mc->mc_db->md_depth++;
5757 *mc->mc_dbflag |= DB_DIRTY;
5758 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
5760 np->mp_flags |= P_LEAF2;
5761 mc->mc_flags |= C_INITIALIZED;
5763 /* make sure all cursor pages are writable */
5764 rc2 = mdb_cursor_touch(mc);
5769 /* The key already exists */
5770 if (rc == MDB_SUCCESS) {
5774 /* there's only a key anyway, so this is a no-op */
5775 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5776 unsigned int ksize = mc->mc_db->md_pad;
5777 if (key->mv_size != ksize)
5778 return MDB_BAD_VALSIZE;
5779 if (flags == MDB_CURRENT) {
5780 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
5781 memcpy(ptr, key->mv_data, ksize);
5787 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5788 olddata.mv_size = NODEDSZ(leaf);
5789 olddata.mv_data = NODEDATA(leaf);
5792 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
5793 mp = fp = xdata.mv_data = env->me_pbuf;
5794 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
5796 /* Was a single item before, must convert now */
5797 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5798 /* Just overwrite the current item */
5799 if (flags == MDB_CURRENT)
5803 #if UINT_MAX < SIZE_MAX
5804 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && dkey.mv_size == sizeof(size_t))
5805 #ifdef MISALIGNED_OK
5806 mc->mc_dbx->md_dcmp = mdb_cmp_long;
5808 mc->mc_dbx->md_dcmp = mdb_cmp_cint;
5811 /* if data matches, skip it */
5812 if (!mc->mc_dbx->md_dcmp(data, &dkey)) {
5813 if (flags & MDB_NODUPDATA)
5815 else if (flags & MDB_MULTIPLE)
5822 /* create a fake page for the dup items */
5823 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
5824 dkey.mv_data = dbuf;
5825 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
5826 fp->mp_lower = PAGEHDRSZ;
5827 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
5828 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5829 fp->mp_flags |= P_LEAF2;
5830 fp->mp_pad = data->mv_size;
5831 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
5833 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
5834 (dkey.mv_size & 1) + (data->mv_size & 1);
5836 fp->mp_upper = xdata.mv_size;
5837 } else if (leaf->mn_flags & F_SUBDATA) {
5838 /* Data is on sub-DB, just store it */
5839 flags |= F_DUPDATA|F_SUBDATA;
5842 /* See if we need to convert from fake page to subDB */
5843 unsigned int offset;
5847 fp = olddata.mv_data;
5850 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5851 offset = NODESIZE + sizeof(indx_t) + data->mv_size;
5852 offset += offset & 1;
5855 offset = fp->mp_pad;
5856 if (SIZELEFT(fp) < offset) {
5857 offset *= 4; /* space for 4 more */
5860 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
5862 fp->mp_flags |= P_DIRTY;
5863 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
5864 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
5868 fp_flags = fp->mp_flags;
5869 xdata.mv_size = olddata.mv_size + offset;
5870 if (NODESIZE + sizeof(indx_t) + NODEKSZ(leaf) + xdata.mv_size
5871 >= env->me_nodemax) {
5872 /* yes, convert it */
5873 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5874 dummy.md_pad = fp->mp_pad;
5875 dummy.md_flags = MDB_DUPFIXED;
5876 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
5877 dummy.md_flags |= MDB_INTEGERKEY;
5883 dummy.md_branch_pages = 0;
5884 dummy.md_leaf_pages = 1;
5885 dummy.md_overflow_pages = 0;
5886 dummy.md_entries = NUMKEYS(fp);
5887 xdata.mv_size = sizeof(MDB_db);
5888 xdata.mv_data = &dummy;
5889 if ((rc = mdb_page_alloc(mc, 1, &mp)))
5891 offset = env->me_psize - olddata.mv_size;
5892 flags |= F_DUPDATA|F_SUBDATA;
5893 dummy.md_root = mp->mp_pgno;
5894 fp_flags &= ~P_SUBP;
5896 mp->mp_flags = fp_flags | P_DIRTY;
5897 mp->mp_pad = fp->mp_pad;
5898 mp->mp_lower = fp->mp_lower;
5899 mp->mp_upper = fp->mp_upper + offset;
5901 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
5903 memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper,
5904 olddata.mv_size - fp->mp_upper);
5905 for (i=0; i<NUMKEYS(fp); i++)
5906 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
5913 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5917 /* overflow page overwrites need special handling */
5918 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5921 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
5923 memcpy(&pg, olddata.mv_data, sizeof(pg));
5924 if ((rc2 = mdb_page_get(mc->mc_txn, pg, &omp, &level)) != 0)
5926 ovpages = omp->mp_pages;
5928 /* Is the ov page large enough? */
5929 if (ovpages >= dpages) {
5930 if (!(omp->mp_flags & P_DIRTY) &&
5931 (level || (env->me_flags & MDB_WRITEMAP)))
5933 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
5936 level = 0; /* dirty in this txn or clean */
5939 if (omp->mp_flags & P_DIRTY) {
5940 /* yes, overwrite it. Note in this case we don't
5941 * bother to try shrinking the page if the new data
5942 * is smaller than the overflow threshold.
5945 /* It is writable only in a parent txn */
5946 size_t sz = (size_t) env->me_psize * ovpages, off;
5947 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
5953 mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
5954 if (!(flags & MDB_RESERVE)) {
5955 /* Copy end of page, adjusting alignment so
5956 * compiler may copy words instead of bytes.
5958 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
5959 memcpy((size_t *)((char *)np + off),
5960 (size_t *)((char *)omp + off), sz - off);
5963 memcpy(np, omp, sz); /* Copy beginning of page */
5966 SETDSZ(leaf, data->mv_size);
5967 if (F_ISSET(flags, MDB_RESERVE))
5968 data->mv_data = METADATA(omp);
5970 memcpy(METADATA(omp), data->mv_data, data->mv_size);
5974 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
5976 } else if (data->mv_size == olddata.mv_size) {
5977 /* same size, just replace it. Note that we could
5978 * also reuse this node if the new data is smaller,
5979 * but instead we opt to shrink the node in that case.
5981 if (F_ISSET(flags, MDB_RESERVE))
5982 data->mv_data = olddata.mv_data;
5983 else if (data->mv_size)
5984 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
5986 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
5989 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5990 mc->mc_db->md_entries--;
5992 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
5999 nflags = flags & NODE_ADD_FLAGS;
6000 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
6001 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
6002 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
6003 nflags &= ~MDB_APPEND;
6005 nflags |= MDB_SPLIT_REPLACE;
6006 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
6008 /* There is room already in this leaf page. */
6009 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
6010 if (rc == 0 && !do_sub && insert) {
6011 /* Adjust other cursors pointing to mp */
6012 MDB_cursor *m2, *m3;
6013 MDB_dbi dbi = mc->mc_dbi;
6014 unsigned i = mc->mc_top;
6015 MDB_page *mp = mc->mc_pg[i];
6017 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6018 if (mc->mc_flags & C_SUB)
6019 m3 = &m2->mc_xcursor->mx_cursor;
6022 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
6023 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
6030 if (rc != MDB_SUCCESS)
6031 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6033 /* Now store the actual data in the child DB. Note that we're
6034 * storing the user data in the keys field, so there are strict
6035 * size limits on dupdata. The actual data fields of the child
6036 * DB are all zero size.
6043 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6044 if (flags & MDB_CURRENT) {
6045 xflags = MDB_CURRENT|MDB_NOSPILL;
6047 mdb_xcursor_init1(mc, leaf);
6048 xflags = (flags & MDB_NODUPDATA) ?
6049 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
6051 /* converted, write the original data first */
6053 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
6057 /* Adjust other cursors pointing to mp */
6059 unsigned i = mc->mc_top;
6060 MDB_page *mp = mc->mc_pg[i];
6062 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6063 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6064 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6065 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
6066 mdb_xcursor_init1(m2, leaf);
6070 /* we've done our job */
6073 if (flags & MDB_APPENDDUP)
6074 xflags |= MDB_APPEND;
6075 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
6076 if (flags & F_SUBDATA) {
6077 void *db = NODEDATA(leaf);
6078 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6081 /* sub-writes might have failed so check rc again.
6082 * Don't increment count if we just replaced an existing item.
6084 if (!rc && !(flags & MDB_CURRENT))
6085 mc->mc_db->md_entries++;
6086 if (flags & MDB_MULTIPLE) {
6090 /* let caller know how many succeeded, if any */
6091 data[1].mv_size = mcount;
6092 if (mcount < dcount) {
6093 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
6100 /* If we succeeded and the key didn't exist before, make sure
6101 * the cursor is marked valid.
6104 mc->mc_flags |= C_INITIALIZED;
6109 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
6115 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
6116 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6118 if (!(mc->mc_flags & C_INITIALIZED))
6121 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6122 return MDB_NOTFOUND;
6124 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
6127 rc = mdb_cursor_touch(mc);
6131 mp = mc->mc_pg[mc->mc_top];
6132 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6134 if (!IS_LEAF2(mp) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6135 if (!(flags & MDB_NODUPDATA)) {
6136 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
6137 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6139 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
6140 /* If sub-DB still has entries, we're done */
6141 if (mc->mc_xcursor->mx_db.md_entries) {
6142 if (leaf->mn_flags & F_SUBDATA) {
6143 /* update subDB info */
6144 void *db = NODEDATA(leaf);
6145 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6148 /* shrink fake page */
6149 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
6150 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6151 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6152 /* fix other sub-DB cursors pointed at this fake page */
6153 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6154 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6155 if (m2->mc_pg[mc->mc_top] == mp &&
6156 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
6157 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6160 mc->mc_db->md_entries--;
6161 mc->mc_flags |= C_DEL;
6164 /* otherwise fall thru and delete the sub-DB */
6167 if (leaf->mn_flags & F_SUBDATA) {
6168 /* add all the child DB's pages to the free list */
6169 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6170 if (rc == MDB_SUCCESS) {
6171 mc->mc_db->md_entries -=
6172 mc->mc_xcursor->mx_db.md_entries;
6177 return mdb_cursor_del0(mc, leaf);
6180 /** Allocate and initialize new pages for a database.
6181 * @param[in] mc a cursor on the database being added to.
6182 * @param[in] flags flags defining what type of page is being allocated.
6183 * @param[in] num the number of pages to allocate. This is usually 1,
6184 * unless allocating overflow pages for a large record.
6185 * @param[out] mp Address of a page, or NULL on failure.
6186 * @return 0 on success, non-zero on failure.
6189 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
6194 if ((rc = mdb_page_alloc(mc, num, &np)))
6196 DPRINTF(("allocated new mpage %"Z"u, page size %u",
6197 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
6198 np->mp_flags = flags | P_DIRTY;
6199 np->mp_lower = PAGEHDRSZ;
6200 np->mp_upper = mc->mc_txn->mt_env->me_psize;
6203 mc->mc_db->md_branch_pages++;
6204 else if (IS_LEAF(np))
6205 mc->mc_db->md_leaf_pages++;
6206 else if (IS_OVERFLOW(np)) {
6207 mc->mc_db->md_overflow_pages += num;
6215 /** Calculate the size of a leaf node.
6216 * The size depends on the environment's page size; if a data item
6217 * is too large it will be put onto an overflow page and the node
6218 * size will only include the key and not the data. Sizes are always
6219 * rounded up to an even number of bytes, to guarantee 2-byte alignment
6220 * of the #MDB_node headers.
6221 * @param[in] env The environment handle.
6222 * @param[in] key The key for the node.
6223 * @param[in] data The data for the node.
6224 * @return The number of bytes needed to store the node.
6227 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
6231 sz = LEAFSIZE(key, data);
6232 if (sz >= env->me_nodemax) {
6233 /* put on overflow page */
6234 sz -= data->mv_size - sizeof(pgno_t);
6238 return sz + sizeof(indx_t);
6241 /** Calculate the size of a branch node.
6242 * The size should depend on the environment's page size but since
6243 * we currently don't support spilling large keys onto overflow
6244 * pages, it's simply the size of the #MDB_node header plus the
6245 * size of the key. Sizes are always rounded up to an even number
6246 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
6247 * @param[in] env The environment handle.
6248 * @param[in] key The key for the node.
6249 * @return The number of bytes needed to store the node.
6252 mdb_branch_size(MDB_env *env, MDB_val *key)
6257 if (sz >= env->me_nodemax) {
6258 /* put on overflow page */
6259 /* not implemented */
6260 /* sz -= key->size - sizeof(pgno_t); */
6263 return sz + sizeof(indx_t);
6266 /** Add a node to the page pointed to by the cursor.
6267 * @param[in] mc The cursor for this operation.
6268 * @param[in] indx The index on the page where the new node should be added.
6269 * @param[in] key The key for the new node.
6270 * @param[in] data The data for the new node, if any.
6271 * @param[in] pgno The page number, if adding a branch node.
6272 * @param[in] flags Flags for the node.
6273 * @return 0 on success, non-zero on failure. Possible errors are:
6275 * <li>ENOMEM - failed to allocate overflow pages for the node.
6276 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
6277 * should never happen since all callers already calculate the
6278 * page's free space before calling this function.
6282 mdb_node_add(MDB_cursor *mc, indx_t indx,
6283 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
6286 size_t node_size = NODESIZE;
6290 MDB_page *mp = mc->mc_pg[mc->mc_top];
6291 MDB_page *ofp = NULL; /* overflow page */
6294 assert(mp->mp_upper >= mp->mp_lower);
6296 DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
6297 IS_LEAF(mp) ? "leaf" : "branch",
6298 IS_SUBP(mp) ? "sub-" : "",
6299 mp->mp_pgno, indx, data ? data->mv_size : 0,
6300 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
6303 /* Move higher keys up one slot. */
6304 int ksize = mc->mc_db->md_pad, dif;
6305 char *ptr = LEAF2KEY(mp, indx, ksize);
6306 dif = NUMKEYS(mp) - indx;
6308 memmove(ptr+ksize, ptr, dif*ksize);
6309 /* insert new key */
6310 memcpy(ptr, key->mv_data, ksize);
6312 /* Just using these for counting */
6313 mp->mp_lower += sizeof(indx_t);
6314 mp->mp_upper -= ksize - sizeof(indx_t);
6318 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
6320 node_size += key->mv_size;
6323 if (F_ISSET(flags, F_BIGDATA)) {
6324 /* Data already on overflow page. */
6325 node_size += sizeof(pgno_t);
6326 } else if (node_size + data->mv_size >= mc->mc_txn->mt_env->me_nodemax) {
6327 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
6329 /* Put data on overflow page. */
6330 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
6331 data->mv_size, node_size+data->mv_size));
6332 node_size += sizeof(pgno_t) + (node_size & 1);
6333 if ((ssize_t)node_size > room)
6335 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
6337 DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
6341 node_size += data->mv_size;
6344 node_size += node_size & 1;
6345 if ((ssize_t)node_size > room)
6349 /* Move higher pointers up one slot. */
6350 for (i = NUMKEYS(mp); i > indx; i--)
6351 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
6353 /* Adjust free space offsets. */
6354 ofs = mp->mp_upper - node_size;
6355 assert(ofs >= mp->mp_lower + sizeof(indx_t));
6356 mp->mp_ptrs[indx] = ofs;
6358 mp->mp_lower += sizeof(indx_t);
6360 /* Write the node data. */
6361 node = NODEPTR(mp, indx);
6362 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
6363 node->mn_flags = flags;
6365 SETDSZ(node,data->mv_size);
6370 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6375 if (F_ISSET(flags, F_BIGDATA))
6376 memcpy(node->mn_data + key->mv_size, data->mv_data,
6378 else if (F_ISSET(flags, MDB_RESERVE))
6379 data->mv_data = node->mn_data + key->mv_size;
6381 memcpy(node->mn_data + key->mv_size, data->mv_data,
6384 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
6386 if (F_ISSET(flags, MDB_RESERVE))
6387 data->mv_data = METADATA(ofp);
6389 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
6396 DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
6397 mp->mp_pgno, NUMKEYS(mp)));
6398 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
6399 DPRINTF(("node size = %"Z"u", node_size));
6400 return MDB_PAGE_FULL;
6403 /** Delete the specified node from a page.
6404 * @param[in] mp The page to operate on.
6405 * @param[in] indx The index of the node to delete.
6406 * @param[in] ksize The size of a node. Only used if the page is
6407 * part of a #MDB_DUPFIXED database.
6410 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
6413 indx_t i, j, numkeys, ptr;
6420 COPY_PGNO(pgno, mp->mp_pgno);
6421 DPRINTF(("delete node %u on %s page %"Z"u", indx,
6422 IS_LEAF(mp) ? "leaf" : "branch", pgno));
6425 assert(indx < NUMKEYS(mp));
6428 int x = NUMKEYS(mp) - 1 - indx;
6429 base = LEAF2KEY(mp, indx, ksize);
6431 memmove(base, base + ksize, x * ksize);
6432 mp->mp_lower -= sizeof(indx_t);
6433 mp->mp_upper += ksize - sizeof(indx_t);
6437 node = NODEPTR(mp, indx);
6438 sz = NODESIZE + node->mn_ksize;
6440 if (F_ISSET(node->mn_flags, F_BIGDATA))
6441 sz += sizeof(pgno_t);
6443 sz += NODEDSZ(node);
6447 ptr = mp->mp_ptrs[indx];
6448 numkeys = NUMKEYS(mp);
6449 for (i = j = 0; i < numkeys; i++) {
6451 mp->mp_ptrs[j] = mp->mp_ptrs[i];
6452 if (mp->mp_ptrs[i] < ptr)
6453 mp->mp_ptrs[j] += sz;
6458 base = (char *)mp + mp->mp_upper;
6459 memmove(base + sz, base, ptr - mp->mp_upper);
6461 mp->mp_lower -= sizeof(indx_t);
6465 /** Compact the main page after deleting a node on a subpage.
6466 * @param[in] mp The main page to operate on.
6467 * @param[in] indx The index of the subpage on the main page.
6470 mdb_node_shrink(MDB_page *mp, indx_t indx)
6477 indx_t i, numkeys, ptr;
6479 node = NODEPTR(mp, indx);
6480 sp = (MDB_page *)NODEDATA(node);
6481 osize = NODEDSZ(node);
6483 delta = sp->mp_upper - sp->mp_lower;
6484 SETDSZ(node, osize - delta);
6485 xp = (MDB_page *)((char *)sp + delta);
6487 /* shift subpage upward */
6489 nsize = NUMKEYS(sp) * sp->mp_pad;
6490 memmove(METADATA(xp), METADATA(sp), nsize);
6493 nsize = osize - sp->mp_upper;
6494 numkeys = NUMKEYS(sp);
6495 for (i=numkeys-1; i>=0; i--)
6496 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
6498 xp->mp_upper = sp->mp_lower;
6499 xp->mp_lower = sp->mp_lower;
6500 xp->mp_flags = sp->mp_flags;
6501 xp->mp_pad = sp->mp_pad;
6502 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
6504 /* shift lower nodes upward */
6505 ptr = mp->mp_ptrs[indx];
6506 numkeys = NUMKEYS(mp);
6507 for (i = 0; i < numkeys; i++) {
6508 if (mp->mp_ptrs[i] <= ptr)
6509 mp->mp_ptrs[i] += delta;
6512 base = (char *)mp + mp->mp_upper;
6513 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
6514 mp->mp_upper += delta;
6517 /** Initial setup of a sorted-dups cursor.
6518 * Sorted duplicates are implemented as a sub-database for the given key.
6519 * The duplicate data items are actually keys of the sub-database.
6520 * Operations on the duplicate data items are performed using a sub-cursor
6521 * initialized when the sub-database is first accessed. This function does
6522 * the preliminary setup of the sub-cursor, filling in the fields that
6523 * depend only on the parent DB.
6524 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6527 mdb_xcursor_init0(MDB_cursor *mc)
6529 MDB_xcursor *mx = mc->mc_xcursor;
6531 mx->mx_cursor.mc_xcursor = NULL;
6532 mx->mx_cursor.mc_txn = mc->mc_txn;
6533 mx->mx_cursor.mc_db = &mx->mx_db;
6534 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
6535 mx->mx_cursor.mc_dbi = mc->mc_dbi;
6536 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
6537 mx->mx_cursor.mc_snum = 0;
6538 mx->mx_cursor.mc_top = 0;
6539 mx->mx_cursor.mc_flags = C_SUB;
6540 mx->mx_dbx.md_name.mv_size = 0;
6541 mx->mx_dbx.md_name.mv_data = NULL;
6542 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
6543 mx->mx_dbx.md_dcmp = NULL;
6544 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
6547 /** Final setup of a sorted-dups cursor.
6548 * Sets up the fields that depend on the data from the main cursor.
6549 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6550 * @param[in] node The data containing the #MDB_db record for the
6551 * sorted-dup database.
6554 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
6556 MDB_xcursor *mx = mc->mc_xcursor;
6558 if (node->mn_flags & F_SUBDATA) {
6559 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
6560 mx->mx_cursor.mc_pg[0] = 0;
6561 mx->mx_cursor.mc_snum = 0;
6562 mx->mx_cursor.mc_top = 0;
6563 mx->mx_cursor.mc_flags = C_SUB;
6565 MDB_page *fp = NODEDATA(node);
6566 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
6567 mx->mx_db.md_flags = 0;
6568 mx->mx_db.md_depth = 1;
6569 mx->mx_db.md_branch_pages = 0;
6570 mx->mx_db.md_leaf_pages = 1;
6571 mx->mx_db.md_overflow_pages = 0;
6572 mx->mx_db.md_entries = NUMKEYS(fp);
6573 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
6574 mx->mx_cursor.mc_snum = 1;
6575 mx->mx_cursor.mc_top = 0;
6576 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
6577 mx->mx_cursor.mc_pg[0] = fp;
6578 mx->mx_cursor.mc_ki[0] = 0;
6579 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6580 mx->mx_db.md_flags = MDB_DUPFIXED;
6581 mx->mx_db.md_pad = fp->mp_pad;
6582 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6583 mx->mx_db.md_flags |= MDB_INTEGERKEY;
6586 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
6587 mx->mx_db.md_root));
6588 mx->mx_dbflag = DB_VALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
6589 #if UINT_MAX < SIZE_MAX
6590 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
6591 #ifdef MISALIGNED_OK
6592 mx->mx_dbx.md_cmp = mdb_cmp_long;
6594 mx->mx_dbx.md_cmp = mdb_cmp_cint;
6599 /** Initialize a cursor for a given transaction and database. */
6601 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
6604 mc->mc_backup = NULL;
6607 mc->mc_db = &txn->mt_dbs[dbi];
6608 mc->mc_dbx = &txn->mt_dbxs[dbi];
6609 mc->mc_dbflag = &txn->mt_dbflags[dbi];
6614 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
6616 mc->mc_xcursor = mx;
6617 mdb_xcursor_init0(mc);
6619 mc->mc_xcursor = NULL;
6621 if (*mc->mc_dbflag & DB_STALE) {
6622 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
6627 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
6630 size_t size = sizeof(MDB_cursor);
6632 if (txn == NULL || ret == NULL || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
6635 if (txn->mt_flags & MDB_TXN_ERROR)
6638 /* Allow read access to the freelist */
6639 if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
6642 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
6643 size += sizeof(MDB_xcursor);
6645 if ((mc = malloc(size)) != NULL) {
6646 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
6647 if (txn->mt_cursors) {
6648 mc->mc_next = txn->mt_cursors[dbi];
6649 txn->mt_cursors[dbi] = mc;
6650 mc->mc_flags |= C_UNTRACK;
6662 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
6664 if (txn == NULL || mc == NULL || mc->mc_dbi >= txn->mt_numdbs)
6667 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
6670 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
6674 /* Return the count of duplicate data items for the current key */
6676 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
6680 if (mc == NULL || countp == NULL)
6683 if (mc->mc_xcursor == NULL)
6684 return MDB_INCOMPATIBLE;
6686 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6687 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6690 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
6693 *countp = mc->mc_xcursor->mx_db.md_entries;
6699 mdb_cursor_close(MDB_cursor *mc)
6701 if (mc && !mc->mc_backup) {
6702 /* remove from txn, if tracked */
6703 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
6704 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
6705 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
6707 *prev = mc->mc_next;
6714 mdb_cursor_txn(MDB_cursor *mc)
6716 if (!mc) return NULL;
6721 mdb_cursor_dbi(MDB_cursor *mc)
6727 /** Replace the key for a node with a new key.
6728 * @param[in] mc Cursor pointing to the node to operate on.
6729 * @param[in] key The new key to use.
6730 * @return 0 on success, non-zero on failure.
6733 mdb_update_key(MDB_cursor *mc, MDB_val *key)
6740 indx_t ptr, i, numkeys, indx;
6743 indx = mc->mc_ki[mc->mc_top];
6744 mp = mc->mc_pg[mc->mc_top];
6745 node = NODEPTR(mp, indx);
6746 ptr = mp->mp_ptrs[indx];
6750 char kbuf2[(MDB_MAXKEYSIZE*2+1)];
6751 k2.mv_data = NODEKEY(node);
6752 k2.mv_size = node->mn_ksize;
6753 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
6755 mdb_dkey(&k2, kbuf2),
6761 delta0 = delta = key->mv_size - node->mn_ksize;
6763 /* Must be 2-byte aligned. If new key is
6764 * shorter by 1, the shift will be skipped.
6766 delta += (delta & 1);
6768 if (delta > 0 && SIZELEFT(mp) < delta) {
6770 /* not enough space left, do a delete and split */
6771 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
6772 pgno = NODEPGNO(node);
6773 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
6774 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
6777 numkeys = NUMKEYS(mp);
6778 for (i = 0; i < numkeys; i++) {
6779 if (mp->mp_ptrs[i] <= ptr)
6780 mp->mp_ptrs[i] -= delta;
6783 base = (char *)mp + mp->mp_upper;
6784 len = ptr - mp->mp_upper + NODESIZE;
6785 memmove(base - delta, base, len);
6786 mp->mp_upper -= delta;
6788 node = NODEPTR(mp, indx);
6791 /* But even if no shift was needed, update ksize */
6793 node->mn_ksize = key->mv_size;
6796 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6802 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
6804 /** Move a node from csrc to cdst.
6807 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
6814 unsigned short flags;
6818 /* Mark src and dst as dirty. */
6819 if ((rc = mdb_page_touch(csrc)) ||
6820 (rc = mdb_page_touch(cdst)))
6823 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6824 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
6825 key.mv_size = csrc->mc_db->md_pad;
6826 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
6828 data.mv_data = NULL;
6832 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
6833 assert(!((long)srcnode&1));
6834 srcpg = NODEPGNO(srcnode);
6835 flags = srcnode->mn_flags;
6836 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6837 unsigned int snum = csrc->mc_snum;
6839 /* must find the lowest key below src */
6840 mdb_page_search_lowest(csrc);
6841 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6842 key.mv_size = csrc->mc_db->md_pad;
6843 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6845 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6846 key.mv_size = NODEKSZ(s2);
6847 key.mv_data = NODEKEY(s2);
6849 csrc->mc_snum = snum--;
6850 csrc->mc_top = snum;
6852 key.mv_size = NODEKSZ(srcnode);
6853 key.mv_data = NODEKEY(srcnode);
6855 data.mv_size = NODEDSZ(srcnode);
6856 data.mv_data = NODEDATA(srcnode);
6858 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
6859 unsigned int snum = cdst->mc_snum;
6862 /* must find the lowest key below dst */
6863 mdb_page_search_lowest(cdst);
6864 if (IS_LEAF2(cdst->mc_pg[cdst->mc_top])) {
6865 bkey.mv_size = cdst->mc_db->md_pad;
6866 bkey.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, bkey.mv_size);
6868 s2 = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
6869 bkey.mv_size = NODEKSZ(s2);
6870 bkey.mv_data = NODEKEY(s2);
6872 cdst->mc_snum = snum--;
6873 cdst->mc_top = snum;
6874 mdb_cursor_copy(cdst, &mn);
6876 rc = mdb_update_key(&mn, &bkey);
6881 DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
6882 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
6883 csrc->mc_ki[csrc->mc_top],
6885 csrc->mc_pg[csrc->mc_top]->mp_pgno,
6886 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
6888 /* Add the node to the destination page.
6890 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
6891 if (rc != MDB_SUCCESS)
6894 /* Delete the node from the source page.
6896 mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
6899 /* Adjust other cursors pointing to mp */
6900 MDB_cursor *m2, *m3;
6901 MDB_dbi dbi = csrc->mc_dbi;
6902 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
6904 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6905 if (csrc->mc_flags & C_SUB)
6906 m3 = &m2->mc_xcursor->mx_cursor;
6909 if (m3 == csrc) continue;
6910 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
6911 csrc->mc_ki[csrc->mc_top]) {
6912 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
6913 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
6918 /* Update the parent separators.
6920 if (csrc->mc_ki[csrc->mc_top] == 0) {
6921 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
6922 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6923 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6925 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6926 key.mv_size = NODEKSZ(srcnode);
6927 key.mv_data = NODEKEY(srcnode);
6929 DPRINTF(("update separator for source page %"Z"u to [%s]",
6930 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
6931 mdb_cursor_copy(csrc, &mn);
6934 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
6937 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6939 indx_t ix = csrc->mc_ki[csrc->mc_top];
6940 nullkey.mv_size = 0;
6941 csrc->mc_ki[csrc->mc_top] = 0;
6942 rc = mdb_update_key(csrc, &nullkey);
6943 csrc->mc_ki[csrc->mc_top] = ix;
6944 assert(rc == MDB_SUCCESS);
6948 if (cdst->mc_ki[cdst->mc_top] == 0) {
6949 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
6950 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6951 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
6953 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
6954 key.mv_size = NODEKSZ(srcnode);
6955 key.mv_data = NODEKEY(srcnode);
6957 DPRINTF(("update separator for destination page %"Z"u to [%s]",
6958 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
6959 mdb_cursor_copy(cdst, &mn);
6962 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
6965 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
6967 indx_t ix = cdst->mc_ki[cdst->mc_top];
6968 nullkey.mv_size = 0;
6969 cdst->mc_ki[cdst->mc_top] = 0;
6970 rc = mdb_update_key(cdst, &nullkey);
6971 cdst->mc_ki[cdst->mc_top] = ix;
6972 assert(rc == MDB_SUCCESS);
6979 /** Merge one page into another.
6980 * The nodes from the page pointed to by \b csrc will
6981 * be copied to the page pointed to by \b cdst and then
6982 * the \b csrc page will be freed.
6983 * @param[in] csrc Cursor pointing to the source page.
6984 * @param[in] cdst Cursor pointing to the destination page.
6987 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
6995 DPRINTF(("merging page %"Z"u into %"Z"u", csrc->mc_pg[csrc->mc_top]->mp_pgno,
6996 cdst->mc_pg[cdst->mc_top]->mp_pgno));
6998 assert(csrc->mc_snum > 1); /* can't merge root page */
6999 assert(cdst->mc_snum > 1);
7001 /* Mark dst as dirty. */
7002 if ((rc = mdb_page_touch(cdst)))
7005 /* Move all nodes from src to dst.
7007 j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
7008 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7009 key.mv_size = csrc->mc_db->md_pad;
7010 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
7011 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
7012 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
7013 if (rc != MDB_SUCCESS)
7015 key.mv_data = (char *)key.mv_data + key.mv_size;
7018 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
7019 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
7020 if (i == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7021 unsigned int snum = csrc->mc_snum;
7023 /* must find the lowest key below src */
7024 mdb_page_search_lowest(csrc);
7025 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7026 key.mv_size = csrc->mc_db->md_pad;
7027 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7029 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7030 key.mv_size = NODEKSZ(s2);
7031 key.mv_data = NODEKEY(s2);
7033 csrc->mc_snum = snum--;
7034 csrc->mc_top = snum;
7036 key.mv_size = srcnode->mn_ksize;
7037 key.mv_data = NODEKEY(srcnode);
7040 data.mv_size = NODEDSZ(srcnode);
7041 data.mv_data = NODEDATA(srcnode);
7042 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
7043 if (rc != MDB_SUCCESS)
7048 DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
7049 cdst->mc_pg[cdst->mc_top]->mp_pgno, NUMKEYS(cdst->mc_pg[cdst->mc_top]),
7050 (float)PAGEFILL(cdst->mc_txn->mt_env, cdst->mc_pg[cdst->mc_top]) / 10));
7052 /* Unlink the src page from parent and add to free list.
7054 mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
7055 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
7058 rc = mdb_update_key(csrc, &key);
7064 rc = mdb_midl_append(&csrc->mc_txn->mt_free_pgs,
7065 csrc->mc_pg[csrc->mc_top]->mp_pgno);
7068 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
7069 csrc->mc_db->md_leaf_pages--;
7071 csrc->mc_db->md_branch_pages--;
7073 /* Adjust other cursors pointing to mp */
7074 MDB_cursor *m2, *m3;
7075 MDB_dbi dbi = csrc->mc_dbi;
7076 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
7078 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7079 if (csrc->mc_flags & C_SUB)
7080 m3 = &m2->mc_xcursor->mx_cursor;
7083 if (m3 == csrc) continue;
7084 if (m3->mc_snum < csrc->mc_snum) continue;
7085 if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
7086 m3->mc_pg[csrc->mc_top] = mp;
7087 m3->mc_ki[csrc->mc_top] += nkeys;
7091 mdb_cursor_pop(csrc);
7093 return mdb_rebalance(csrc);
7096 /** Copy the contents of a cursor.
7097 * @param[in] csrc The cursor to copy from.
7098 * @param[out] cdst The cursor to copy to.
7101 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
7105 cdst->mc_txn = csrc->mc_txn;
7106 cdst->mc_dbi = csrc->mc_dbi;
7107 cdst->mc_db = csrc->mc_db;
7108 cdst->mc_dbx = csrc->mc_dbx;
7109 cdst->mc_snum = csrc->mc_snum;
7110 cdst->mc_top = csrc->mc_top;
7111 cdst->mc_flags = csrc->mc_flags;
7113 for (i=0; i<csrc->mc_snum; i++) {
7114 cdst->mc_pg[i] = csrc->mc_pg[i];
7115 cdst->mc_ki[i] = csrc->mc_ki[i];
7119 /** Rebalance the tree after a delete operation.
7120 * @param[in] mc Cursor pointing to the page where rebalancing
7122 * @return 0 on success, non-zero on failure.
7125 mdb_rebalance(MDB_cursor *mc)
7129 unsigned int ptop, minkeys;
7132 minkeys = 1 + (IS_BRANCH(mc->mc_pg[mc->mc_top]));
7136 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
7137 DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
7138 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
7139 pgno, NUMKEYS(mc->mc_pg[mc->mc_top]),
7140 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
7144 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD &&
7145 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
7148 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
7149 DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
7155 if (mc->mc_snum < 2) {
7156 MDB_page *mp = mc->mc_pg[0];
7158 DPUTS("Can't rebalance a subpage, ignoring");
7161 if (NUMKEYS(mp) == 0) {
7162 DPUTS("tree is completely empty");
7163 mc->mc_db->md_root = P_INVALID;
7164 mc->mc_db->md_depth = 0;
7165 mc->mc_db->md_leaf_pages = 0;
7166 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7169 /* Adjust cursors pointing to mp */
7172 mc->mc_flags &= ~C_INITIALIZED;
7174 MDB_cursor *m2, *m3;
7175 MDB_dbi dbi = mc->mc_dbi;
7177 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7178 if (mc->mc_flags & C_SUB)
7179 m3 = &m2->mc_xcursor->mx_cursor;
7182 if (m3->mc_snum < mc->mc_snum) continue;
7183 if (m3->mc_pg[0] == mp) {
7186 m3->mc_flags &= ~C_INITIALIZED;
7190 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
7191 DPUTS("collapsing root page!");
7192 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7195 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
7196 rc = mdb_page_get(mc->mc_txn,mc->mc_db->md_root,&mc->mc_pg[0],NULL);
7199 mc->mc_db->md_depth--;
7200 mc->mc_db->md_branch_pages--;
7201 mc->mc_ki[0] = mc->mc_ki[1];
7203 /* Adjust other cursors pointing to mp */
7204 MDB_cursor *m2, *m3;
7205 MDB_dbi dbi = mc->mc_dbi;
7207 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7208 if (mc->mc_flags & C_SUB)
7209 m3 = &m2->mc_xcursor->mx_cursor;
7212 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
7213 if (m3->mc_pg[0] == mp) {
7217 for (i=0; i<m3->mc_snum; i++) {
7218 m3->mc_pg[i] = m3->mc_pg[i+1];
7219 m3->mc_ki[i] = m3->mc_ki[i+1];
7225 DPUTS("root page doesn't need rebalancing");
7229 /* The parent (branch page) must have at least 2 pointers,
7230 * otherwise the tree is invalid.
7232 ptop = mc->mc_top-1;
7233 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
7235 /* Leaf page fill factor is below the threshold.
7236 * Try to move keys from left or right neighbor, or
7237 * merge with a neighbor page.
7242 mdb_cursor_copy(mc, &mn);
7243 mn.mc_xcursor = NULL;
7245 if (mc->mc_ki[ptop] == 0) {
7246 /* We're the leftmost leaf in our parent.
7248 DPUTS("reading right neighbor");
7250 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7251 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7254 mn.mc_ki[mn.mc_top] = 0;
7255 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
7257 /* There is at least one neighbor to the left.
7259 DPUTS("reading left neighbor");
7261 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7262 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7265 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
7266 mc->mc_ki[mc->mc_top] = 0;
7269 DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
7270 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
7271 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
7273 /* If the neighbor page is above threshold and has enough keys,
7274 * move one key from it. Otherwise we should try to merge them.
7275 * (A branch page must never have less than 2 keys.)
7277 minkeys = 1 + (IS_BRANCH(mn.mc_pg[mn.mc_top]));
7278 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys)
7279 return mdb_node_move(&mn, mc);
7281 if (mc->mc_ki[ptop] == 0)
7282 rc = mdb_page_merge(&mn, mc);
7284 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
7285 rc = mdb_page_merge(mc, &mn);
7286 mdb_cursor_copy(&mn, mc);
7288 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
7293 /** Complete a delete operation started by #mdb_cursor_del(). */
7295 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
7302 mp = mc->mc_pg[mc->mc_top];
7303 ki = mc->mc_ki[mc->mc_top];
7305 /* add overflow pages to free list */
7306 if (!IS_LEAF2(mp) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7310 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
7311 if ((rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL)) ||
7312 (rc = mdb_ovpage_free(mc, omp)))
7315 mdb_node_del(mp, ki, mc->mc_db->md_pad);
7316 mc->mc_db->md_entries--;
7317 rc = mdb_rebalance(mc);
7318 if (rc != MDB_SUCCESS)
7319 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7322 MDB_dbi dbi = mc->mc_dbi;
7324 mp = mc->mc_pg[mc->mc_top];
7325 nkeys = NUMKEYS(mp);
7327 /* if mc points past last node in page, find next sibling */
7328 if (mc->mc_ki[mc->mc_top] >= nkeys)
7329 mdb_cursor_sibling(mc, 1);
7331 /* Adjust other cursors pointing to mp */
7332 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7333 if (m2 == mc || m2->mc_snum < mc->mc_snum)
7335 if (!(m2->mc_flags & C_INITIALIZED))
7337 if (m2->mc_pg[mc->mc_top] == mp) {
7338 if (m2->mc_ki[mc->mc_top] >= ki) {
7339 m2->mc_flags |= C_DEL;
7340 if (m2->mc_ki[mc->mc_top] > ki)
7341 m2->mc_ki[mc->mc_top]--;
7343 if (m2->mc_ki[mc->mc_top] >= nkeys)
7344 mdb_cursor_sibling(m2, 1);
7347 mc->mc_flags |= C_DEL;
7354 mdb_del(MDB_txn *txn, MDB_dbi dbi,
7355 MDB_val *key, MDB_val *data)
7360 MDB_val rdata, *xdata;
7364 assert(key != NULL);
7366 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
7368 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7371 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
7372 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7374 if (key->mv_size > MDB_MAXKEYSIZE) {
7375 return MDB_BAD_VALSIZE;
7378 mdb_cursor_init(&mc, txn, dbi, &mx);
7381 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
7382 /* must ignore any data */
7393 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
7395 /* let mdb_page_split know about this cursor if needed:
7396 * delete will trigger a rebalance; if it needs to move
7397 * a node from one page to another, it will have to
7398 * update the parent's separator key(s). If the new sepkey
7399 * is larger than the current one, the parent page may
7400 * run out of space, triggering a split. We need this
7401 * cursor to be consistent until the end of the rebalance.
7403 mc.mc_flags |= C_UNTRACK;
7404 mc.mc_next = txn->mt_cursors[dbi];
7405 txn->mt_cursors[dbi] = &mc;
7406 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
7407 txn->mt_cursors[dbi] = mc.mc_next;
7412 /** Split a page and insert a new node.
7413 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
7414 * The cursor will be updated to point to the actual page and index where
7415 * the node got inserted after the split.
7416 * @param[in] newkey The key for the newly inserted node.
7417 * @param[in] newdata The data for the newly inserted node.
7418 * @param[in] newpgno The page number, if the new node is a branch node.
7419 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
7420 * @return 0 on success, non-zero on failure.
7423 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
7424 unsigned int nflags)
7427 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
7430 int i, j, split_indx, nkeys, pmax;
7431 MDB_env *env = mc->mc_txn->mt_env;
7433 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
7434 MDB_page *copy = NULL;
7435 MDB_page *mp, *rp, *pp;
7440 mp = mc->mc_pg[mc->mc_top];
7441 newindx = mc->mc_ki[mc->mc_top];
7442 nkeys = NUMKEYS(mp);
7444 DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i/%i",
7445 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
7446 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
7448 /* Create a right sibling. */
7449 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
7451 DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
7453 if (mc->mc_snum < 2) {
7454 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
7456 /* shift current top to make room for new parent */
7457 mc->mc_pg[1] = mc->mc_pg[0];
7458 mc->mc_ki[1] = mc->mc_ki[0];
7461 mc->mc_db->md_root = pp->mp_pgno;
7462 DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
7463 mc->mc_db->md_depth++;
7466 /* Add left (implicit) pointer. */
7467 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
7468 /* undo the pre-push */
7469 mc->mc_pg[0] = mc->mc_pg[1];
7470 mc->mc_ki[0] = mc->mc_ki[1];
7471 mc->mc_db->md_root = mp->mp_pgno;
7472 mc->mc_db->md_depth--;
7479 ptop = mc->mc_top-1;
7480 DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
7483 mc->mc_flags |= C_SPLITTING;
7484 mdb_cursor_copy(mc, &mn);
7485 mn.mc_pg[mn.mc_top] = rp;
7486 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
7488 if (nflags & MDB_APPEND) {
7489 mn.mc_ki[mn.mc_top] = 0;
7491 split_indx = newindx;
7495 split_indx = (nkeys+1) / 2;
7500 unsigned int lsize, rsize, ksize;
7501 /* Move half of the keys to the right sibling */
7503 x = mc->mc_ki[mc->mc_top] - split_indx;
7504 ksize = mc->mc_db->md_pad;
7505 split = LEAF2KEY(mp, split_indx, ksize);
7506 rsize = (nkeys - split_indx) * ksize;
7507 lsize = (nkeys - split_indx) * sizeof(indx_t);
7508 mp->mp_lower -= lsize;
7509 rp->mp_lower += lsize;
7510 mp->mp_upper += rsize - lsize;
7511 rp->mp_upper -= rsize - lsize;
7512 sepkey.mv_size = ksize;
7513 if (newindx == split_indx) {
7514 sepkey.mv_data = newkey->mv_data;
7516 sepkey.mv_data = split;
7519 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
7520 memcpy(rp->mp_ptrs, split, rsize);
7521 sepkey.mv_data = rp->mp_ptrs;
7522 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
7523 memcpy(ins, newkey->mv_data, ksize);
7524 mp->mp_lower += sizeof(indx_t);
7525 mp->mp_upper -= ksize - sizeof(indx_t);
7528 memcpy(rp->mp_ptrs, split, x * ksize);
7529 ins = LEAF2KEY(rp, x, ksize);
7530 memcpy(ins, newkey->mv_data, ksize);
7531 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
7532 rp->mp_lower += sizeof(indx_t);
7533 rp->mp_upper -= ksize - sizeof(indx_t);
7534 mc->mc_ki[mc->mc_top] = x;
7535 mc->mc_pg[mc->mc_top] = rp;
7538 int psize, nsize, k;
7539 /* Maximum free space in an empty page */
7540 pmax = env->me_psize - PAGEHDRSZ;
7542 nsize = mdb_leaf_size(env, newkey, newdata);
7544 nsize = mdb_branch_size(env, newkey);
7547 /* grab a page to hold a temporary copy */
7548 copy = mdb_page_malloc(mc->mc_txn, 1);
7551 copy->mp_pgno = mp->mp_pgno;
7552 copy->mp_flags = mp->mp_flags;
7553 copy->mp_lower = PAGEHDRSZ;
7554 copy->mp_upper = env->me_psize;
7556 /* prepare to insert */
7557 for (i=0, j=0; i<nkeys; i++) {
7559 copy->mp_ptrs[j++] = 0;
7561 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
7564 /* When items are relatively large the split point needs
7565 * to be checked, because being off-by-one will make the
7566 * difference between success or failure in mdb_node_add.
7568 * It's also relevant if a page happens to be laid out
7569 * such that one half of its nodes are all "small" and
7570 * the other half of its nodes are "large." If the new
7571 * item is also "large" and falls on the half with
7572 * "large" nodes, it also may not fit.
7574 * As a final tweak, if the new item goes on the last
7575 * spot on the page (and thus, onto the new page), bias
7576 * the split so the new page is emptier than the old page.
7577 * This yields better packing during sequential inserts.
7579 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
7580 /* Find split point */
7582 if (newindx <= split_indx || newindx >= nkeys) {
7584 k = newindx >= nkeys ? nkeys : split_indx+2;
7589 for (; i!=k; i+=j) {
7594 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i]);
7595 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
7597 if (F_ISSET(node->mn_flags, F_BIGDATA))
7598 psize += sizeof(pgno_t);
7600 psize += NODEDSZ(node);
7604 if (psize > pmax || i == k-j) {
7605 split_indx = i + (j<0);
7610 if (split_indx == newindx) {
7611 sepkey.mv_size = newkey->mv_size;
7612 sepkey.mv_data = newkey->mv_data;
7614 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx]);
7615 sepkey.mv_size = node->mn_ksize;
7616 sepkey.mv_data = NODEKEY(node);
7621 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
7623 /* Copy separator key to the parent.
7625 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
7629 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
7632 if (mn.mc_snum == mc->mc_snum) {
7633 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
7634 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
7635 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
7636 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
7641 /* Right page might now have changed parent.
7642 * Check if left page also changed parent.
7644 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7645 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7646 for (i=0; i<ptop; i++) {
7647 mc->mc_pg[i] = mn.mc_pg[i];
7648 mc->mc_ki[i] = mn.mc_ki[i];
7650 mc->mc_pg[ptop] = mn.mc_pg[ptop];
7651 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
7655 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
7658 mc->mc_flags ^= C_SPLITTING;
7659 if (rc != MDB_SUCCESS) {
7662 if (nflags & MDB_APPEND) {
7663 mc->mc_pg[mc->mc_top] = rp;
7664 mc->mc_ki[mc->mc_top] = 0;
7665 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
7668 for (i=0; i<mc->mc_top; i++)
7669 mc->mc_ki[i] = mn.mc_ki[i];
7670 } else if (!IS_LEAF2(mp)) {
7672 mc->mc_pg[mc->mc_top] = rp;
7677 rkey.mv_data = newkey->mv_data;
7678 rkey.mv_size = newkey->mv_size;
7684 /* Update index for the new key. */
7685 mc->mc_ki[mc->mc_top] = j;
7687 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i]);
7688 rkey.mv_data = NODEKEY(node);
7689 rkey.mv_size = node->mn_ksize;
7691 xdata.mv_data = NODEDATA(node);
7692 xdata.mv_size = NODEDSZ(node);
7695 pgno = NODEPGNO(node);
7696 flags = node->mn_flags;
7699 if (!IS_LEAF(mp) && j == 0) {
7700 /* First branch index doesn't need key data. */
7704 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
7706 /* return tmp page to freelist */
7707 mdb_page_free(env, copy);
7713 mc->mc_pg[mc->mc_top] = copy;
7718 } while (i != split_indx);
7720 nkeys = NUMKEYS(copy);
7721 for (i=0; i<nkeys; i++)
7722 mp->mp_ptrs[i] = copy->mp_ptrs[i];
7723 mp->mp_lower = copy->mp_lower;
7724 mp->mp_upper = copy->mp_upper;
7725 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
7726 env->me_psize - copy->mp_upper);
7728 /* reset back to original page */
7729 if (newindx < split_indx) {
7730 mc->mc_pg[mc->mc_top] = mp;
7731 if (nflags & MDB_RESERVE) {
7732 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7733 if (!(node->mn_flags & F_BIGDATA))
7734 newdata->mv_data = NODEDATA(node);
7737 mc->mc_pg[mc->mc_top] = rp;
7739 /* Make sure mc_ki is still valid.
7741 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7742 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7743 for (i=0; i<ptop; i++) {
7744 mc->mc_pg[i] = mn.mc_pg[i];
7745 mc->mc_ki[i] = mn.mc_ki[i];
7747 mc->mc_pg[ptop] = mn.mc_pg[ptop];
7748 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
7751 /* return tmp page to freelist */
7752 mdb_page_free(env, copy);
7756 /* Adjust other cursors pointing to mp */
7757 MDB_cursor *m2, *m3;
7758 MDB_dbi dbi = mc->mc_dbi;
7759 int fixup = NUMKEYS(mp);
7761 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7762 if (mc->mc_flags & C_SUB)
7763 m3 = &m2->mc_xcursor->mx_cursor;
7768 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
7770 if (m3->mc_flags & C_SPLITTING)
7775 for (k=m3->mc_top; k>=0; k--) {
7776 m3->mc_ki[k+1] = m3->mc_ki[k];
7777 m3->mc_pg[k+1] = m3->mc_pg[k];
7779 if (m3->mc_ki[0] >= split_indx) {
7784 m3->mc_pg[0] = mc->mc_pg[0];
7788 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
7789 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
7790 m3->mc_ki[mc->mc_top]++;
7791 if (m3->mc_ki[mc->mc_top] >= fixup) {
7792 m3->mc_pg[mc->mc_top] = rp;
7793 m3->mc_ki[mc->mc_top] -= fixup;
7794 m3->mc_ki[ptop] = mn.mc_ki[ptop];
7796 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
7797 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
7802 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
7807 mdb_put(MDB_txn *txn, MDB_dbi dbi,
7808 MDB_val *key, MDB_val *data, unsigned int flags)
7813 assert(key != NULL);
7814 assert(data != NULL);
7816 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7819 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP)) != flags)
7822 mdb_cursor_init(&mc, txn, dbi, &mx);
7823 return mdb_cursor_put(&mc, key, data, flags);
7827 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
7829 if ((flag & CHANGEABLE) != flag)
7832 env->me_flags |= flag;
7834 env->me_flags &= ~flag;
7839 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
7844 *arg = env->me_flags;
7849 mdb_env_get_path(MDB_env *env, const char **arg)
7854 *arg = env->me_path;
7859 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
7868 /** Common code for #mdb_stat() and #mdb_env_stat().
7869 * @param[in] env the environment to operate in.
7870 * @param[in] db the #MDB_db record containing the stats to return.
7871 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
7872 * @return 0, this function always succeeds.
7875 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
7877 arg->ms_psize = env->me_psize;
7878 arg->ms_depth = db->md_depth;
7879 arg->ms_branch_pages = db->md_branch_pages;
7880 arg->ms_leaf_pages = db->md_leaf_pages;
7881 arg->ms_overflow_pages = db->md_overflow_pages;
7882 arg->ms_entries = db->md_entries;
7887 mdb_env_stat(MDB_env *env, MDB_stat *arg)
7891 if (env == NULL || arg == NULL)
7894 toggle = mdb_env_pick_meta(env);
7896 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
7900 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
7904 if (env == NULL || arg == NULL)
7907 toggle = mdb_env_pick_meta(env);
7908 arg->me_mapaddr = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : 0;
7909 arg->me_mapsize = env->me_mapsize;
7910 arg->me_maxreaders = env->me_maxreaders;
7912 /* me_numreaders may be zero if this process never used any readers. Use
7913 * the shared numreader count if it exists.
7915 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : env->me_numreaders;
7917 arg->me_last_pgno = env->me_metas[toggle]->mm_last_pg;
7918 arg->me_last_txnid = env->me_metas[toggle]->mm_txnid;
7922 /** Set the default comparison functions for a database.
7923 * Called immediately after a database is opened to set the defaults.
7924 * The user can then override them with #mdb_set_compare() or
7925 * #mdb_set_dupsort().
7926 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
7927 * @param[in] dbi A database handle returned by #mdb_dbi_open()
7930 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
7932 uint16_t f = txn->mt_dbs[dbi].md_flags;
7934 txn->mt_dbxs[dbi].md_cmp =
7935 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
7936 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
7938 txn->mt_dbxs[dbi].md_dcmp =
7939 !(f & MDB_DUPSORT) ? 0 :
7940 ((f & MDB_INTEGERDUP)
7941 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
7942 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
7945 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
7950 int rc, dbflag, exact;
7951 unsigned int unused = 0;
7954 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
7955 mdb_default_cmp(txn, FREE_DBI);
7958 if ((flags & VALID_FLAGS) != flags)
7960 if (txn->mt_flags & MDB_TXN_ERROR)
7966 if (flags & PERSISTENT_FLAGS) {
7967 uint16_t f2 = flags & PERSISTENT_FLAGS;
7968 /* make sure flag changes get committed */
7969 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
7970 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
7971 txn->mt_flags |= MDB_TXN_DIRTY;
7974 mdb_default_cmp(txn, MAIN_DBI);
7978 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
7979 mdb_default_cmp(txn, MAIN_DBI);
7982 /* Is the DB already open? */
7984 for (i=2; i<txn->mt_numdbs; i++) {
7985 if (!txn->mt_dbxs[i].md_name.mv_size) {
7986 /* Remember this free slot */
7987 if (!unused) unused = i;
7990 if (len == txn->mt_dbxs[i].md_name.mv_size &&
7991 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
7997 /* If no free slot and max hit, fail */
7998 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
7999 return MDB_DBS_FULL;
8001 /* Cannot mix named databases with some mainDB flags */
8002 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
8003 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
8005 /* Find the DB info */
8006 dbflag = DB_NEW|DB_VALID;
8009 key.mv_data = (void *)name;
8010 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
8011 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
8012 if (rc == MDB_SUCCESS) {
8013 /* make sure this is actually a DB */
8014 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
8015 if (!(node->mn_flags & F_SUBDATA))
8016 return MDB_INCOMPATIBLE;
8017 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
8018 /* Create if requested */
8020 data.mv_size = sizeof(MDB_db);
8021 data.mv_data = &dummy;
8022 memset(&dummy, 0, sizeof(dummy));
8023 dummy.md_root = P_INVALID;
8024 dummy.md_flags = flags & PERSISTENT_FLAGS;
8025 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
8029 /* OK, got info, add to table */
8030 if (rc == MDB_SUCCESS) {
8031 unsigned int slot = unused ? unused : txn->mt_numdbs;
8032 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
8033 txn->mt_dbxs[slot].md_name.mv_size = len;
8034 txn->mt_dbxs[slot].md_rel = NULL;
8035 txn->mt_dbflags[slot] = dbflag;
8036 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
8038 mdb_default_cmp(txn, slot);
8047 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
8049 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
8052 if (txn->mt_dbflags[dbi] & DB_STALE) {
8055 /* Stale, must read the DB's root. cursor_init does it for us. */
8056 mdb_cursor_init(&mc, txn, dbi, &mx);
8058 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
8061 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
8064 if (dbi <= MAIN_DBI || dbi >= env->me_maxdbs)
8066 ptr = env->me_dbxs[dbi].md_name.mv_data;
8067 env->me_dbxs[dbi].md_name.mv_data = NULL;
8068 env->me_dbxs[dbi].md_name.mv_size = 0;
8069 env->me_dbflags[dbi] = 0;
8073 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
8075 /* We could return the flags for the FREE_DBI too but what's the point? */
8076 if (txn == NULL || dbi < MAIN_DBI || dbi >= txn->mt_numdbs)
8078 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
8082 /** Add all the DB's pages to the free list.
8083 * @param[in] mc Cursor on the DB to free.
8084 * @param[in] subs non-Zero to check for sub-DBs in this DB.
8085 * @return 0 on success, non-zero on failure.
8088 mdb_drop0(MDB_cursor *mc, int subs)
8092 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
8093 if (rc == MDB_SUCCESS) {
8094 MDB_txn *txn = mc->mc_txn;
8099 /* LEAF2 pages have no nodes, cannot have sub-DBs */
8100 if (IS_LEAF2(mc->mc_pg[mc->mc_top]))
8103 mdb_cursor_copy(mc, &mx);
8104 while (mc->mc_snum > 0) {
8105 MDB_page *mp = mc->mc_pg[mc->mc_top];
8106 unsigned n = NUMKEYS(mp);
8108 for (i=0; i<n; i++) {
8109 ni = NODEPTR(mp, i);
8110 if (ni->mn_flags & F_BIGDATA) {
8113 memcpy(&pg, NODEDATA(ni), sizeof(pg));
8114 rc = mdb_page_get(txn, pg, &omp, NULL);
8117 assert(IS_OVERFLOW(omp));
8118 rc = mdb_midl_append_range(&txn->mt_free_pgs,
8122 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
8123 mdb_xcursor_init1(mc, ni);
8124 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
8130 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
8132 for (i=0; i<n; i++) {
8134 ni = NODEPTR(mp, i);
8137 mdb_midl_xappend(txn->mt_free_pgs, pg);
8142 mc->mc_ki[mc->mc_top] = i;
8143 rc = mdb_cursor_sibling(mc, 1);
8145 /* no more siblings, go back to beginning
8146 * of previous level.
8150 for (i=1; i<mc->mc_snum; i++) {
8152 mc->mc_pg[i] = mx.mc_pg[i];
8157 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
8158 } else if (rc == MDB_NOTFOUND) {
8164 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
8166 MDB_cursor *mc, *m2;
8169 if (!txn || !dbi || dbi >= txn->mt_numdbs || (unsigned)del > 1 || !(txn->mt_dbflags[dbi] & DB_VALID))
8172 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
8175 rc = mdb_cursor_open(txn, dbi, &mc);
8179 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
8180 /* Invalidate the dropped DB's cursors */
8181 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
8182 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
8186 /* Can't delete the main DB */
8187 if (del && dbi > MAIN_DBI) {
8188 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
8190 txn->mt_dbflags[dbi] = DB_STALE;
8191 mdb_dbi_close(txn->mt_env, dbi);
8194 /* reset the DB record, mark it dirty */
8195 txn->mt_dbflags[dbi] |= DB_DIRTY;
8196 txn->mt_dbs[dbi].md_depth = 0;
8197 txn->mt_dbs[dbi].md_branch_pages = 0;
8198 txn->mt_dbs[dbi].md_leaf_pages = 0;
8199 txn->mt_dbs[dbi].md_overflow_pages = 0;
8200 txn->mt_dbs[dbi].md_entries = 0;
8201 txn->mt_dbs[dbi].md_root = P_INVALID;
8203 txn->mt_flags |= MDB_TXN_DIRTY;
8206 mdb_cursor_close(mc);
8210 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
8212 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8215 txn->mt_dbxs[dbi].md_cmp = cmp;
8219 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
8221 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8224 txn->mt_dbxs[dbi].md_dcmp = cmp;
8228 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
8230 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8233 txn->mt_dbxs[dbi].md_rel = rel;
8237 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
8239 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8242 txn->mt_dbxs[dbi].md_relctx = ctx;
8246 int mdb_env_get_maxkeysize(MDB_env *env)
8248 return MDB_MAXKEYSIZE;
8251 int mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
8253 unsigned int i, rdrs;
8260 if (!env->me_txns) {
8261 return func("(no reader locks)\n", ctx);
8263 rdrs = env->me_txns->mti_numreaders;
8264 mr = env->me_txns->mti_readers;
8265 for (i=0; i<rdrs; i++) {
8270 if (mr[i].mr_txnid == (txnid_t)-1) {
8271 sprintf(buf, "%10d %"Z"x -\n", mr[i].mr_pid, tid);
8273 sprintf(buf, "%10d %"Z"x %"Z"u\n", mr[i].mr_pid, tid, mr[i].mr_txnid);
8277 func(" pid thread txnid\n", ctx);
8279 rc = func(buf, ctx);
8285 func("(no active readers)\n", ctx);
8290 /** Insert pid into list if not already present.
8291 * return -1 if already present.
8293 static int mdb_pid_insert(pid_t *ids, pid_t pid)
8295 /* binary search of pid in list */
8297 unsigned cursor = 1;
8299 unsigned n = ids[0];
8302 unsigned pivot = n >> 1;
8303 cursor = base + pivot + 1;
8304 val = pid - ids[cursor];
8309 } else if ( val > 0 ) {
8314 /* found, so it's a duplicate */
8323 for (n = ids[0]; n > cursor; n--)
8329 int mdb_reader_check(MDB_env *env, int *dead)
8331 unsigned int i, j, rdrs;
8342 rdrs = env->me_txns->mti_numreaders;
8343 pids = malloc((rdrs+1) * sizeof(pid_t));
8347 mr = env->me_txns->mti_readers;
8349 for (i=0; i<rdrs; i++) {
8350 if (mr[i].mr_pid && mr[i].mr_pid != env->me_pid) {
8352 if (mdb_pid_insert(pids, pid) == 0) {
8353 if (!mdb_reader_pid(env, Pidcheck, pid)) {
8355 /* Recheck, a new process may have reused pid */
8356 if (!mdb_reader_pid(env, Pidcheck, pid)) {
8357 for (j=i; j<rdrs; j++)
8358 if (mr[j].mr_pid == pid) {
8359 DPRINTF(("clear stale reader pid %u txn %"Z"d",
8360 (unsigned) pid, mr[j].mr_txnid));
8365 UNLOCK_MUTEX_R(env);