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 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.
35 #include <sys/types.h>
37 #include <sys/param.h>
43 #ifdef HAVE_SYS_FILE_H
63 #include <semaphore.h>
68 #define BYTE_ORDER __BYTE_ORDER
71 #define LITTLE_ENDIAN __LITTLE_ENDIAN
74 #define BIG_ENDIAN __BIG_ENDIAN
80 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
81 # error "Unknown or unsupported endianness (BYTE_ORDER)"
82 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
83 # error "Two's complement, reasonably sized integer types, please"
86 /** @defgroup internal MDB Internals
89 /** @defgroup compat Windows Compatibility Macros
90 * A bunch of macros to minimize the amount of platform-specific ifdefs
91 * needed throughout the rest of the code. When the features this library
92 * needs are similar enough to POSIX to be hidden in a one-or-two line
93 * replacement, this macro approach is used.
97 #define pthread_t DWORD
98 #define pthread_mutex_t HANDLE
99 #define pthread_key_t DWORD
100 #define pthread_self() GetCurrentThreadId()
101 #define pthread_key_create(x,y) (*(x) = TlsAlloc())
102 #define pthread_key_delete(x) TlsFree(x)
103 #define pthread_getspecific(x) TlsGetValue(x)
104 #define pthread_setspecific(x,y) TlsSetValue(x,y)
105 #define pthread_mutex_unlock(x) ReleaseMutex(x)
106 #define pthread_mutex_lock(x) WaitForSingleObject(x, INFINITE)
107 #define LOCK_MUTEX_R(env) pthread_mutex_lock((env)->me_rmutex)
108 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock((env)->me_rmutex)
109 #define LOCK_MUTEX_W(env) pthread_mutex_lock((env)->me_wmutex)
110 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock((env)->me_wmutex)
111 #define getpid() GetCurrentProcessId()
112 #define fdatasync(fd) (!FlushFileBuffers(fd))
113 #define ErrCode() GetLastError()
114 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
115 #define close(fd) CloseHandle(fd)
116 #define munmap(ptr,len) UnmapViewOfFile(ptr)
119 #define LOCK_MUTEX_R(env) sem_wait((env)->me_rmutex)
120 #define UNLOCK_MUTEX_R(env) sem_post((env)->me_rmutex)
121 #define LOCK_MUTEX_W(env) sem_wait((env)->me_wmutex)
122 #define UNLOCK_MUTEX_W(env) sem_post((env)->me_wmutex)
123 #define fdatasync(fd) fsync(fd)
125 /** Lock the reader mutex.
127 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
128 /** Unlock the reader mutex.
130 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
132 /** Lock the writer mutex.
133 * Only a single write transaction is allowed at a time. Other writers
134 * will block waiting for this mutex.
136 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
137 /** Unlock the writer mutex.
139 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
140 #endif /* __APPLE__ */
142 /** Get the error code for the last failed system function.
144 #define ErrCode() errno
146 /** An abstraction for a file handle.
147 * On POSIX systems file handles are small integers. On Windows
148 * they're opaque pointers.
152 /** A value for an invalid file handle.
153 * Mainly used to initialize file variables and signify that they are
156 #define INVALID_HANDLE_VALUE (-1)
158 /** Get the size of a memory page for the system.
159 * This is the basic size that the platform's memory manager uses, and is
160 * fundamental to the use of memory-mapped files.
162 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
165 #if defined(_WIN32) || defined(__APPLE__)
172 /** A flag for opening a file and requesting synchronous data writes.
173 * This is only used when writing a meta page. It's not strictly needed;
174 * we could just do a normal write and then immediately perform a flush.
175 * But if this flag is available it saves us an extra system call.
177 * @note If O_DSYNC is undefined but exists in /usr/include,
178 * preferably set some compiler flag to get the definition.
179 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
182 # define MDB_DSYNC O_DSYNC
186 /** A page number in the database.
187 * Note that 64 bit page numbers are overkill, since pages themselves
188 * already represent 12-13 bits of addressable memory, and the OS will
189 * always limit applications to a maximum of 63 bits of address space.
191 * @note In the #MDB_node structure, we only store 48 bits of this value,
192 * which thus limits us to only 60 bits of addressable data.
196 /** A transaction ID.
197 * See struct MDB_txn.mt_txnid for details.
201 /** @defgroup debug Debug Macros
205 /** Enable debug output.
206 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
207 * read from and written to the database (used for free space management).
212 #if !(__STDC_VERSION__ >= 199901L || defined(__GNUC__))
213 # define DPRINTF (void) /* Vararg macros may be unsupported */
215 /** Print a debug message with printf formatting. */
216 # define DPRINTF(fmt, ...) /**< Requires 2 or more args */ \
217 fprintf(stderr, "%s:%d " fmt "\n", __func__, __LINE__, __VA_ARGS__)
219 # define DPRINTF(fmt, ...) ((void) 0)
221 /** Print a debug string.
222 * The string is printed literally, with no format processing.
224 #define DPUTS(arg) DPRINTF("%s", arg)
227 /** A default memory page size.
228 * The actual size is platform-dependent, but we use this for
229 * boot-strapping. We probably should not be using this any more.
230 * The #GET_PAGESIZE() macro is used to get the actual size.
232 * Note that we don't currently support Huge pages. On Linux,
233 * regular data files cannot use Huge pages, and in general
234 * Huge pages aren't actually pageable. We rely on the OS
235 * demand-pager to read our data and page it out when memory
236 * pressure from other processes is high. So until OSs have
237 * actual paging support for Huge pages, they're not viable.
239 #define PAGESIZE 4096
241 /** The minimum number of keys required in a database page.
242 * Setting this to a larger value will place a smaller bound on the
243 * maximum size of a data item. Data items larger than this size will
244 * be pushed into overflow pages instead of being stored directly in
245 * the B-tree node. This value used to default to 4. With a page size
246 * of 4096 bytes that meant that any item larger than 1024 bytes would
247 * go into an overflow page. That also meant that on average 2-3KB of
248 * each overflow page was wasted space. The value cannot be lower than
249 * 2 because then there would no longer be a tree structure. With this
250 * value, items larger than 2KB will go into overflow pages, and on
251 * average only 1KB will be wasted.
253 #define MDB_MINKEYS 2
255 /** A stamp that identifies a file as an MDB file.
256 * There's nothing special about this value other than that it is easily
257 * recognizable, and it will reflect any byte order mismatches.
259 #define MDB_MAGIC 0xBEEFC0DE
261 /** The version number for a database's file format. */
262 #define MDB_VERSION 1
264 /** The maximum size of a key in the database.
265 * While data items have essentially unbounded size, we require that
266 * keys all fit onto a regular page. This limit could be raised a bit
267 * further if needed; to something just under #PAGESIZE / #MDB_MINKEYS.
269 #define MAXKEYSIZE 511
274 * This is used for printing a hex dump of a key's contents.
276 #define DKBUF char kbuf[(MAXKEYSIZE*2+1)]
277 /** Display a key in hex.
279 * Invoke a function to display a key in hex.
281 #define DKEY(x) mdb_dkey(x, kbuf)
283 #define DKBUF typedef int dummy_kbuf /* so we can put ';' after */
287 /** @defgroup lazylock Lazy Locking
288 * Macros for locks that are't actually needed.
289 * The DB view is always consistent because all writes are wrapped in
290 * the wmutex. Finer-grained locks aren't necessary.
294 /** Use lazy locking. I.e., don't lock these accesses at all. */
298 /** Grab the reader lock */
299 #define LAZY_MUTEX_LOCK(x)
300 /** Release the reader lock */
301 #define LAZY_MUTEX_UNLOCK(x)
302 /** Release the DB table reader/writer lock */
303 #define LAZY_RWLOCK_UNLOCK(x)
304 /** Grab the DB table write lock */
305 #define LAZY_RWLOCK_WRLOCK(x)
306 /** Grab the DB table read lock */
307 #define LAZY_RWLOCK_RDLOCK(x)
308 /** Declare the DB table rwlock. Should not be followed by ';'. */
309 #define LAZY_RWLOCK_DEF(x)
310 /** Initialize the DB table rwlock */
311 #define LAZY_RWLOCK_INIT(x,y)
312 /** Destroy the DB table rwlock */
313 #define LAZY_RWLOCK_DESTROY(x)
315 #define LAZY_MUTEX_LOCK(x) pthread_mutex_lock(x)
316 #define LAZY_MUTEX_UNLOCK(x) pthread_mutex_unlock(x)
317 #define LAZY_RWLOCK_UNLOCK(x) pthread_rwlock_unlock(x)
318 #define LAZY_RWLOCK_WRLOCK(x) pthread_rwlock_wrlock(x)
319 #define LAZY_RWLOCK_RDLOCK(x) pthread_rwlock_rdlock(x)
320 #define LAZY_RWLOCK_DEF(x) pthread_rwlock_t x;
321 #define LAZY_RWLOCK_INIT(x,y) pthread_rwlock_init(x,y)
322 #define LAZY_RWLOCK_DESTROY(x) pthread_rwlock_destroy(x)
326 /** An invalid page number.
327 * Mainly used to denote an empty tree.
329 #define P_INVALID (~0UL)
331 /** Test if a flag \b f is set in a flag word \b w. */
332 #define F_ISSET(w, f) (((w) & (f)) == (f))
334 /** Used for offsets within a single page.
335 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
338 typedef uint16_t indx_t;
340 /** Default size of memory map.
341 * This is certainly too small for any actual applications. Apps should always set
342 * the size explicitly using #mdb_env_set_mapsize().
344 #define DEFAULT_MAPSIZE 1048576
346 /** @defgroup readers Reader Lock Table
347 * Readers don't acquire any locks for their data access. Instead, they
348 * simply record their transaction ID in the reader table. The reader
349 * mutex is needed just to find an empty slot in the reader table. The
350 * slot's address is saved in thread-specific data so that subsequent read
351 * transactions started by the same thread need no further locking to proceed.
353 * Since the database uses multi-version concurrency control, readers don't
354 * actually need any locking. This table is used to keep track of which
355 * readers are using data from which old transactions, so that we'll know
356 * when a particular old transaction is no longer in use. Old transactions
357 * that have discarded any data pages can then have those pages reclaimed
358 * for use by a later write transaction.
360 * The lock table is constructed such that reader slots are aligned with the
361 * processor's cache line size. Any slot is only ever used by one thread.
362 * This alignment guarantees that there will be no contention or cache
363 * thrashing as threads update their own slot info, and also eliminates
364 * any need for locking when accessing a slot.
366 * A writer thread will scan every slot in the table to determine the oldest
367 * outstanding reader transaction. Any freed pages older than this will be
368 * reclaimed by the writer. The writer doesn't use any locks when scanning
369 * this table. This means that there's no guarantee that the writer will
370 * see the most up-to-date reader info, but that's not required for correct
371 * operation - all we need is to know the upper bound on the oldest reader,
372 * we don't care at all about the newest reader. So the only consequence of
373 * reading stale information here is that old pages might hang around a
374 * while longer before being reclaimed. That's actually good anyway, because
375 * the longer we delay reclaiming old pages, the more likely it is that a
376 * string of contiguous pages can be found after coalescing old pages from
377 * many old transactions together.
379 * @todo We don't actually do such coalescing yet, we grab pages from one
380 * old transaction at a time.
383 /** Number of slots in the reader table.
384 * This value was chosen somewhat arbitrarily. 126 readers plus a
385 * couple mutexes fit exactly into 8KB on my development machine.
386 * Applications should set the table size using #mdb_env_set_maxreaders().
388 #define DEFAULT_READERS 126
390 /** The size of a CPU cache line in bytes. We want our lock structures
391 * aligned to this size to avoid false cache line sharing in the
393 * This value works for most CPUs. For Itanium this should be 128.
399 /** The information we store in a single slot of the reader table.
400 * In addition to a transaction ID, we also record the process and
401 * thread ID that owns a slot, so that we can detect stale information,
402 * e.g. threads or processes that went away without cleaning up.
403 * @note We currently don't check for stale records. We simply re-init
404 * the table when we know that we're the only process opening the
407 typedef struct MDB_rxbody {
408 /** The current Transaction ID when this transaction began.
409 * Multiple readers that start at the same time will probably have the
410 * same ID here. Again, it's not important to exclude them from
411 * anything; all we need to know is which version of the DB they
412 * started from so we can avoid overwriting any data used in that
413 * particular version.
416 /** The process ID of the process owning this reader txn. */
418 /** The thread ID of the thread owning this txn. */
422 /** The actual reader record, with cacheline padding. */
423 typedef struct MDB_reader {
426 /** shorthand for mrb_txnid */
427 #define mr_txnid mru.mrx.mrb_txnid
428 #define mr_pid mru.mrx.mrb_pid
429 #define mr_tid mru.mrx.mrb_tid
430 /** cache line alignment */
431 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
435 /** The header for the reader table.
436 * The table resides in a memory-mapped file. (This is a different file
437 * than is used for the main database.)
439 * For POSIX the actual mutexes reside in the shared memory of this
440 * mapped file. On Windows, mutexes are named objects allocated by the
441 * kernel; we store the mutex names in this mapped file so that other
442 * processes can grab them. This same approach is also used on
443 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
444 * process-shared POSIX mutexes. For these cases where a named object
445 * is used, the object name is derived from a 64 bit FNV hash of the
446 * environment pathname. As such, naming collisions are extremely
447 * unlikely. If a collision occurs, the results are unpredictable.
449 typedef struct MDB_txbody {
450 /** Stamp identifying this as an MDB lock file. It must be set
453 /** Version number of this lock file. Must be set to #MDB_VERSION. */
454 uint32_t mtb_version;
455 #if defined(_WIN32) || defined(__APPLE__)
456 char mtb_rmname[MNAME_LEN];
458 /** Mutex protecting access to this table.
459 * This is the reader lock that #LOCK_MUTEX_R acquires.
461 pthread_mutex_t mtb_mutex;
463 /** The ID of the last transaction committed to the database.
464 * This is recorded here only for convenience; the value can always
465 * be determined by reading the main database meta pages.
468 /** The number of slots that have been used in the reader table.
469 * This always records the maximum count, it is not decremented
470 * when readers release their slots.
472 unsigned mtb_numreaders;
473 /** The ID of the most recent meta page in the database.
474 * This is recorded here only for convenience; the value can always
475 * be determined by reading the main database meta pages.
477 uint32_t mtb_me_toggle;
480 /** The actual reader table definition. */
481 typedef struct MDB_txninfo {
484 #define mti_magic mt1.mtb.mtb_magic
485 #define mti_version mt1.mtb.mtb_version
486 #define mti_mutex mt1.mtb.mtb_mutex
487 #define mti_rmname mt1.mtb.mtb_rmname
488 #define mti_txnid mt1.mtb.mtb_txnid
489 #define mti_numreaders mt1.mtb.mtb_numreaders
490 #define mti_me_toggle mt1.mtb.mtb_me_toggle
491 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
494 #if defined(_WIN32) || defined(__APPLE__)
495 char mt2_wmname[MNAME_LEN];
496 #define mti_wmname mt2.mt2_wmname
498 pthread_mutex_t mt2_wmutex;
499 #define mti_wmutex mt2.mt2_wmutex
501 char pad[(sizeof(pthread_mutex_t)+CACHELINE-1) & ~(CACHELINE-1)];
503 MDB_reader mti_readers[1];
507 /** Common header for all page types.
508 * Overflow records occupy a number of contiguous pages with no
509 * headers on any page after the first.
511 typedef struct MDB_page {
512 #define mp_pgno mp_p.p_pgno
513 #define mp_next mp_p.p_next
515 pgno_t p_pgno; /**< page number */
516 void * p_next; /**< for in-memory list of freed structs */
519 /** @defgroup mdb_page Page Flags
521 * Flags for the page headers.
524 #define P_BRANCH 0x01 /**< branch page */
525 #define P_LEAF 0x02 /**< leaf page */
526 #define P_OVERFLOW 0x04 /**< overflow page */
527 #define P_META 0x08 /**< meta page */
528 #define P_DIRTY 0x10 /**< dirty page */
529 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
530 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
532 uint16_t mp_flags; /**< @ref mdb_page */
533 #define mp_lower mp_pb.pb.pb_lower
534 #define mp_upper mp_pb.pb.pb_upper
535 #define mp_pages mp_pb.pb_pages
538 indx_t pb_lower; /**< lower bound of free space */
539 indx_t pb_upper; /**< upper bound of free space */
541 uint32_t pb_pages; /**< number of overflow pages */
543 indx_t mp_ptrs[1]; /**< dynamic size */
546 /** Size of the page header, excluding dynamic data at the end */
547 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
549 /** Address of first usable data byte in a page, after the header */
550 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
552 /** Number of nodes on a page */
553 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
555 /** The amount of space remaining in the page */
556 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
558 /** The percentage of space used in the page, in tenths of a percent. */
559 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
560 ((env)->me_psize - PAGEHDRSZ))
561 /** The minimum page fill factor, in tenths of a percent.
562 * Pages emptier than this are candidates for merging.
564 #define FILL_THRESHOLD 250
566 /** Test if a page is a leaf page */
567 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
568 /** Test if a page is a LEAF2 page */
569 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
570 /** Test if a page is a branch page */
571 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
572 /** Test if a page is an overflow page */
573 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
574 /** Test if a page is a sub page */
575 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
577 /** The number of overflow pages needed to store the given size. */
578 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
580 /** Header for a single key/data pair within a page.
581 * We guarantee 2-byte alignment for nodes.
583 typedef struct MDB_node {
584 /** lo and hi are used for data size on leaf nodes and for
585 * child pgno on branch nodes. On 64 bit platforms, flags
586 * is also used for pgno. (Branch nodes have no flags).
587 * They are in host byte order in case that lets some
588 * accesses be optimized into a 32-bit word access.
590 #define mn_lo mn_offset[BYTE_ORDER!=LITTLE_ENDIAN]
591 #define mn_hi mn_offset[BYTE_ORDER==LITTLE_ENDIAN] /**< part of dsize or pgno */
592 unsigned short mn_offset[2]; /**< storage for #mn_lo and #mn_hi */
593 /** @defgroup mdb_node Node Flags
595 * Flags for node headers.
598 #define F_BIGDATA 0x01 /**< data put on overflow page */
599 #define F_SUBDATA 0x02 /**< data is a sub-database */
600 #define F_DUPDATA 0x04 /**< data has duplicates */
602 /** valid flags for #mdb_node_add() */
603 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
606 unsigned short mn_flags; /**< @ref mdb_node */
607 unsigned short mn_ksize; /**< key size */
608 char mn_data[1]; /**< key and data are appended here */
611 /** Size of the node header, excluding dynamic data at the end */
612 #define NODESIZE offsetof(MDB_node, mn_data)
614 /** Bit position of top word in page number, for shifting mn_flags */
615 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
617 /** Size of a node in a branch page with a given key.
618 * This is just the node header plus the key, there is no data.
620 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
622 /** Size of a node in a leaf page with a given key and data.
623 * This is node header plus key plus data size.
625 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
627 /** Address of node \b i in page \b p */
628 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
630 /** Address of the key for the node */
631 #define NODEKEY(node) (void *)((node)->mn_data)
633 /** Address of the data for a node */
634 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
636 /** Get the page number pointed to by a branch node */
637 #define NODEPGNO(node) \
638 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
639 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
640 /** Set the page number in a branch node */
641 #define SETPGNO(node,pgno) do { \
642 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
643 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
645 /** Get the size of the data in a leaf node */
646 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
647 /** Set the size of the data for a leaf node */
648 #define SETDSZ(node,size) do { \
649 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
650 /** The size of a key in a node */
651 #define NODEKSZ(node) ((node)->mn_ksize)
653 /** The address of a key in a LEAF2 page.
654 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
655 * There are no node headers, keys are stored contiguously.
657 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
659 /** Set the \b node's key into \b key, if requested. */
660 #define MDB_SET_KEY(node, key) { if ((key) != NULL) { \
661 (key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node); } }
663 /** Information about a single database in the environment. */
664 typedef struct MDB_db {
665 uint32_t md_pad; /**< also ksize for LEAF2 pages */
666 uint16_t md_flags; /**< @ref mdb_open */
667 uint16_t md_depth; /**< depth of this tree */
668 pgno_t md_branch_pages; /**< number of internal pages */
669 pgno_t md_leaf_pages; /**< number of leaf pages */
670 pgno_t md_overflow_pages; /**< number of overflow pages */
671 size_t md_entries; /**< number of data items */
672 pgno_t md_root; /**< the root page of this tree */
675 /** Handle for the DB used to track free pages. */
677 /** Handle for the default DB. */
680 /** Meta page content. */
681 typedef struct MDB_meta {
682 /** Stamp identifying this as an MDB data file. It must be set
685 /** Version number of this lock file. Must be set to #MDB_VERSION. */
687 void *mm_address; /**< address for fixed mapping */
688 size_t mm_mapsize; /**< size of mmap region */
689 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
690 /** The size of pages used in this DB */
691 #define mm_psize mm_dbs[0].md_pad
692 /** Any persistent environment flags. @ref mdb_env */
693 #define mm_flags mm_dbs[0].md_flags
694 pgno_t mm_last_pg; /**< last used page in file */
695 txnid_t mm_txnid; /**< txnid that committed this page */
698 /** Auxiliary DB info.
699 * The information here is mostly static/read-only. There is
700 * only a single copy of this record in the environment.
702 typedef struct MDB_dbx {
703 MDB_val md_name; /**< name of the database */
704 MDB_cmp_func *md_cmp; /**< function for comparing keys */
705 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
706 MDB_rel_func *md_rel; /**< user relocate function */
707 void *md_relctx; /**< user-provided context for md_rel */
710 /** A database transaction.
711 * Every operation requires a transaction handle.
714 MDB_txn *mt_parent; /**< parent of a nested txn */
715 MDB_txn *mt_child; /**< nested txn under this txn */
716 pgno_t mt_next_pgno; /**< next unallocated page */
717 /** The ID of this transaction. IDs are integers incrementing from 1.
718 * Only committed write transactions increment the ID. If a transaction
719 * aborts, the ID may be re-used by the next writer.
722 MDB_env *mt_env; /**< the DB environment */
723 /** The list of pages that became unused during this transaction.
727 ID2L dirty_list; /**< modified pages */
728 MDB_reader *reader; /**< this thread's slot in the reader table */
730 /** Array of records for each DB known in the environment. */
732 /** Array of MDB_db records for each known DB */
734 /** @defgroup mt_dbflag Transaction DB Flags
738 #define DB_DIRTY 0x01 /**< DB was written in this txn */
739 #define DB_STALE 0x02 /**< DB record is older than txnID */
741 /** Array of cursors for each DB */
742 MDB_cursor **mt_cursors;
743 /** Array of flags for each DB */
744 unsigned char *mt_dbflags;
745 /** Number of DB records in use. This number only ever increments;
746 * we don't decrement it when individual DB handles are closed.
750 /** @defgroup mdb_txn Transaction Flags
754 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
755 #define MDB_TXN_ERROR 0x02 /**< an error has occurred */
757 unsigned int mt_flags; /**< @ref mdb_txn */
758 /** Tracks which of the two meta pages was used at the start
759 * of this transaction.
761 unsigned int mt_toggle;
764 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
765 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
766 * raise this on a 64 bit machine.
768 #define CURSOR_STACK 32
772 /** Cursors are used for all DB operations */
774 /** Next cursor on this DB in this txn */
776 /** Original cursor if this is a shadow */
778 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
779 struct MDB_xcursor *mc_xcursor;
780 /** The transaction that owns this cursor */
782 /** The database handle this cursor operates on */
784 /** The database record for this cursor */
786 /** The database auxiliary record for this cursor */
788 /** The @ref mt_dbflag for this database */
789 unsigned char *mc_dbflag;
790 unsigned short mc_snum; /**< number of pushed pages */
791 unsigned short mc_top; /**< index of top page, mc_snum-1 */
792 /** @defgroup mdb_cursor Cursor Flags
794 * Cursor state flags.
797 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
798 #define C_EOF 0x02 /**< No more data */
799 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
800 #define C_SHADOW 0x08 /**< Cursor is a dup from a parent txn */
801 #define C_ALLOCD 0x10 /**< Cursor was malloc'd */
803 unsigned int mc_flags; /**< @ref mdb_cursor */
804 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
805 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
808 /** Context for sorted-dup records.
809 * We could have gone to a fully recursive design, with arbitrarily
810 * deep nesting of sub-databases. But for now we only handle these
811 * levels - main DB, optional sub-DB, sorted-duplicate DB.
813 typedef struct MDB_xcursor {
814 /** A sub-cursor for traversing the Dup DB */
815 MDB_cursor mx_cursor;
816 /** The database record for this Dup DB */
818 /** The auxiliary DB record for this Dup DB */
820 /** The @ref mt_dbflag for this Dup DB */
821 unsigned char mx_dbflag;
824 /** A set of pages freed by an earlier transaction. */
825 typedef struct MDB_oldpages {
826 /** Usually we only read one record from the FREEDB at a time, but
827 * in case we read more, this will chain them together.
829 struct MDB_oldpages *mo_next;
830 /** The ID of the transaction in which these pages were freed. */
832 /** An #IDL of the pages */
833 pgno_t mo_pages[1]; /* dynamic */
836 /** The database environment. */
838 HANDLE me_fd; /**< The main data file */
839 HANDLE me_lfd; /**< The lock file */
840 HANDLE me_mfd; /**< just for writing the meta pages */
841 /** Failed to update the meta page. Probably an I/O error. */
842 #define MDB_FATAL_ERROR 0x80000000U
843 uint32_t me_flags; /**< @ref mdb_env */
844 uint32_t me_extrapad; /**< unused for now */
845 unsigned int me_maxreaders; /**< size of the reader table */
846 MDB_dbi me_numdbs; /**< number of DBs opened */
847 MDB_dbi me_maxdbs; /**< size of the DB table */
848 char *me_path; /**< path to the DB files */
849 char *me_map; /**< the memory map of the data file */
850 MDB_txninfo *me_txns; /**< the memory map of the lock file */
851 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
852 MDB_txn *me_txn; /**< current write transaction */
853 size_t me_mapsize; /**< size of the data memory map */
854 off_t me_size; /**< current file size */
855 pgno_t me_maxpg; /**< me_mapsize / me_psize */
856 unsigned int me_psize; /**< size of a page, from #GET_PAGESIZE */
857 unsigned int me_db_toggle; /**< which DB table is current */
858 txnid_t me_wtxnid; /**< ID of last txn we committed */
859 MDB_dbx *me_dbxs; /**< array of static DB info */
860 MDB_db *me_dbs[2]; /**< two arrays of MDB_db info */
861 MDB_oldpages *me_pghead; /**< list of old page records */
862 pthread_key_t me_txkey; /**< thread-key for readers */
863 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
864 /** IDL of pages that became unused in a write txn */
866 /** ID2L of pages that were written during a write txn */
867 ID2 me_dirty_list[MDB_IDL_UM_SIZE];
868 /** rwlock for the DB tables, if #LAZY_LOCKS is false */
869 LAZY_RWLOCK_DEF(me_dblock)
871 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
875 sem_t *me_rmutex; /* Apple doesn't support shared mutexes */
879 /** max number of pages to commit in one writev() call */
880 #define MDB_COMMIT_PAGES 64
882 static MDB_page *mdb_page_alloc(MDB_cursor *mc, int num);
883 static MDB_page *mdb_page_new(MDB_cursor *mc, uint32_t flags, int num);
884 static int mdb_page_touch(MDB_cursor *mc);
886 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
887 static int mdb_page_search_root(MDB_cursor *mc,
888 MDB_val *key, int modify);
889 static int mdb_page_search(MDB_cursor *mc,
890 MDB_val *key, int modify);
891 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
892 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
893 pgno_t newpgno, unsigned int nflags);
895 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
896 static int mdb_env_read_meta(MDB_env *env, int *which);
897 static int mdb_env_write_meta(MDB_txn *txn);
899 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
900 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
901 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
902 static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
903 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
904 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
905 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
906 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
907 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
909 static int mdb_rebalance(MDB_cursor *mc);
910 static int mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
912 static void mdb_cursor_pop(MDB_cursor *mc);
913 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
915 static int mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
916 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
917 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
918 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
919 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
921 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
922 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
924 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
925 static void mdb_xcursor_init0(MDB_cursor *mc);
926 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
928 static int mdb_drop0(MDB_cursor *mc, int subs);
929 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
932 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
936 static SECURITY_DESCRIPTOR mdb_null_sd;
937 static SECURITY_ATTRIBUTES mdb_all_sa;
938 static int mdb_sec_inited;
941 /** Return the library version info. */
943 mdb_version(int *major, int *minor, int *patch)
945 if (major) *major = MDB_VERSION_MAJOR;
946 if (minor) *minor = MDB_VERSION_MINOR;
947 if (patch) *patch = MDB_VERSION_PATCH;
948 return MDB_VERSION_STRING;
951 /** Table of descriptions for MDB @ref errors */
952 static char *const mdb_errstr[] = {
953 "MDB_KEYEXIST: Key/data pair already exists",
954 "MDB_NOTFOUND: No matching key/data pair found",
955 "MDB_PAGE_NOTFOUND: Requested page not found",
956 "MDB_CORRUPTED: Located page was wrong type",
957 "MDB_PANIC: Update of meta page failed",
958 "MDB_VERSION_MISMATCH: Database environment version mismatch"
962 mdb_strerror(int err)
965 return ("Successful return: 0");
967 if (err >= MDB_KEYEXIST && err <= MDB_VERSION_MISMATCH)
968 return mdb_errstr[err - MDB_KEYEXIST];
970 return strerror(err);
974 /** Display a key in hexadecimal and return the address of the result.
975 * @param[in] key the key to display
976 * @param[in] buf the buffer to write into. Should always be #DKBUF.
977 * @return The key in hexadecimal form.
980 mdb_dkey(MDB_val *key, char *buf)
983 unsigned char *c = key->mv_data;
985 if (key->mv_size > MAXKEYSIZE)
987 /* may want to make this a dynamic check: if the key is mostly
988 * printable characters, print it as-is instead of converting to hex.
991 for (i=0; i<key->mv_size; i++)
992 ptr += sprintf(ptr, "%02x", *c++);
994 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1001 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1003 return txn->mt_dbxs[dbi].md_cmp(a, b);
1007 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1009 if (txn->mt_dbxs[dbi].md_dcmp)
1010 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1012 return EINVAL; /* too bad you can't distinguish this from a valid result */
1015 /** Allocate a single page.
1016 * Re-use old malloc'd pages first, otherwise just malloc.
1019 mdb_page_malloc(MDB_cursor *mc) {
1021 if (mc->mc_txn->mt_env->me_dpages) {
1022 ret = mc->mc_txn->mt_env->me_dpages;
1023 mc->mc_txn->mt_env->me_dpages = ret->mp_next;
1025 ret = malloc(mc->mc_txn->mt_env->me_psize);
1030 /** Allocate pages for writing.
1031 * If there are free pages available from older transactions, they
1032 * will be re-used first. Otherwise a new page will be allocated.
1033 * @param[in] mc cursor A cursor handle identifying the transaction and
1034 * database for which we are allocating.
1035 * @param[in] num the number of pages to allocate.
1036 * @return Address of the allocated page(s). Requests for multiple pages
1037 * will always be satisfied by a single contiguous chunk of memory.
1040 mdb_page_alloc(MDB_cursor *mc, int num)
1042 MDB_txn *txn = mc->mc_txn;
1044 pgno_t pgno = P_INVALID;
1047 if (txn->mt_txnid > 2) {
1049 if (!txn->mt_env->me_pghead && mc->mc_dbi != FREE_DBI &&
1050 txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
1051 /* See if there's anything in the free DB */
1054 txnid_t *kptr, oldest;
1056 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1057 mdb_page_search(&m2, NULL, 0);
1058 leaf = NODEPTR(m2.mc_pg[m2.mc_top], 0);
1059 kptr = (txnid_t *)NODEKEY(leaf);
1063 oldest = txn->mt_txnid - 1;
1064 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
1065 txnid_t mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
1066 if (mr && mr < oldest)
1071 if (oldest > *kptr) {
1072 /* It's usable, grab it.
1078 mdb_node_read(txn, leaf, &data);
1079 idl = (ID *) data.mv_data;
1080 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
1081 mop->mo_next = txn->mt_env->me_pghead;
1082 mop->mo_txnid = *kptr;
1083 txn->mt_env->me_pghead = mop;
1084 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
1089 DPRINTF("IDL read txn %zu root %zu num %zu",
1090 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1091 for (i=0; i<idl[0]; i++) {
1092 DPRINTF("IDL %zu", idl[i+1]);
1096 /* drop this IDL from the DB */
1097 m2.mc_ki[m2.mc_top] = 0;
1098 m2.mc_flags = C_INITIALIZED;
1099 mdb_cursor_del(&m2, 0);
1102 if (txn->mt_env->me_pghead) {
1103 MDB_oldpages *mop = txn->mt_env->me_pghead;
1105 /* FIXME: For now, always use fresh pages. We
1106 * really ought to search the free list for a
1111 /* peel pages off tail, so we only have to truncate the list */
1112 pgno = MDB_IDL_LAST(mop->mo_pages);
1113 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
1115 if (mop->mo_pages[2] > mop->mo_pages[1])
1116 mop->mo_pages[0] = 0;
1120 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
1121 txn->mt_env->me_pghead = mop->mo_next;
1128 if (pgno == P_INVALID) {
1129 /* DB size is maxed out */
1130 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg) {
1131 DPUTS("DB size maxed out");
1135 if (txn->mt_env->me_dpages && num == 1) {
1136 np = txn->mt_env->me_dpages;
1137 txn->mt_env->me_dpages = np->mp_next;
1139 if ((np = malloc(txn->mt_env->me_psize * num )) == NULL)
1142 if (pgno == P_INVALID) {
1143 np->mp_pgno = txn->mt_next_pgno;
1144 txn->mt_next_pgno += num;
1148 mid.mid = np->mp_pgno;
1150 mdb_mid2l_insert(txn->mt_u.dirty_list, &mid);
1155 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1156 * @param[in] mc cursor pointing to the page to be touched
1157 * @return 0 on success, non-zero on failure.
1160 mdb_page_touch(MDB_cursor *mc)
1162 MDB_page *mp = mc->mc_pg[mc->mc_top];
1165 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1167 if ((np = mdb_page_alloc(mc, 1)) == NULL)
1169 DPRINTF("touched db %u page %zu -> %zu", mc->mc_dbi, mp->mp_pgno, np->mp_pgno);
1170 assert(mp->mp_pgno != np->mp_pgno);
1171 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
1173 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1176 mp->mp_flags |= P_DIRTY;
1179 /* Adjust other cursors pointing to mp */
1180 if (mc->mc_flags & C_SUB) {
1181 MDB_cursor *m2, *m3;
1182 MDB_dbi dbi = mc->mc_dbi-1;
1184 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
1185 if (m2 == mc) continue;
1186 m3 = &m2->mc_xcursor->mx_cursor;
1187 if (m3->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1188 m3->mc_pg[mc->mc_top] = mp;
1194 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
1195 if (m2 == mc) continue;
1196 if (m2->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1197 m2->mc_pg[mc->mc_top] = mp;
1201 mc->mc_pg[mc->mc_top] = mp;
1202 /** If this page has a parent, update the parent to point to
1206 SETPGNO(NODEPTR(mc->mc_pg[mc->mc_top-1], mc->mc_ki[mc->mc_top-1]), mp->mp_pgno);
1208 mc->mc_db->md_root = mp->mp_pgno;
1209 } else if (mc->mc_txn->mt_parent) {
1212 /* If txn has a parent, make sure the page is in our
1215 if (mc->mc_txn->mt_u.dirty_list[0].mid) {
1216 unsigned x = mdb_mid2l_search(mc->mc_txn->mt_u.dirty_list, mp->mp_pgno);
1217 if (x <= mc->mc_txn->mt_u.dirty_list[0].mid &&
1218 mc->mc_txn->mt_u.dirty_list[x].mid == mp->mp_pgno) {
1219 if (mc->mc_txn->mt_u.dirty_list[x].mptr != mp) {
1220 mp = mc->mc_txn->mt_u.dirty_list[x].mptr;
1221 mc->mc_pg[mc->mc_top] = mp;
1227 np = mdb_page_malloc(mc);
1228 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1229 mid.mid = np->mp_pgno;
1231 mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &mid);
1239 mdb_env_sync(MDB_env *env, int force)
1242 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1243 if (fdatasync(env->me_fd))
1249 /** Make shadow copies of all of parent txn's cursors */
1251 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
1253 MDB_cursor *mc, *m2;
1254 unsigned int i, j, size;
1256 for (i=0;i<src->mt_numdbs; i++) {
1257 if (src->mt_cursors[i]) {
1258 size = sizeof(MDB_cursor);
1259 if (src->mt_cursors[i]->mc_xcursor)
1260 size += sizeof(MDB_xcursor);
1261 for (m2 = src->mt_cursors[i]; m2; m2=m2->mc_next) {
1268 mc->mc_db = &dst->mt_dbs[i];
1269 mc->mc_dbx = m2->mc_dbx;
1270 mc->mc_dbflag = &dst->mt_dbflags[i];
1271 mc->mc_snum = m2->mc_snum;
1272 mc->mc_top = m2->mc_top;
1273 mc->mc_flags = m2->mc_flags | C_SHADOW;
1274 for (j=0; j<mc->mc_snum; j++) {
1275 mc->mc_pg[j] = m2->mc_pg[j];
1276 mc->mc_ki[j] = m2->mc_ki[j];
1278 if (m2->mc_xcursor) {
1279 MDB_xcursor *mx, *mx2;
1280 mx = (MDB_xcursor *)(mc+1);
1281 mc->mc_xcursor = mx;
1282 mx2 = m2->mc_xcursor;
1283 mx->mx_db = mx2->mx_db;
1284 mx->mx_dbx = mx2->mx_dbx;
1285 mx->mx_dbflag = mx2->mx_dbflag;
1286 mx->mx_cursor.mc_txn = dst;
1287 mx->mx_cursor.mc_dbi = mx2->mx_cursor.mc_dbi;
1288 mx->mx_cursor.mc_db = &mx->mx_db;
1289 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
1290 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
1291 mx->mx_cursor.mc_snum = mx2->mx_cursor.mc_snum;
1292 mx->mx_cursor.mc_top = mx2->mx_cursor.mc_top;
1293 mx->mx_cursor.mc_flags = mx2->mx_cursor.mc_flags | C_SHADOW;
1294 for (j=0; j<mx2->mx_cursor.mc_snum; j++) {
1295 mx->mx_cursor.mc_pg[j] = mx2->mx_cursor.mc_pg[j];
1296 mx->mx_cursor.mc_ki[j] = mx2->mx_cursor.mc_ki[j];
1299 mc->mc_xcursor = NULL;
1301 mc->mc_next = dst->mt_cursors[i];
1302 dst->mt_cursors[i] = mc;
1309 /** Merge shadow cursors back into parent's */
1311 mdb_cursor_merge(MDB_txn *txn)
1314 for (i=0; i<txn->mt_numdbs; i++) {
1315 if (txn->mt_cursors[i]) {
1317 while ((mc = txn->mt_cursors[i])) {
1318 txn->mt_cursors[i] = mc->mc_next;
1319 if (mc->mc_flags & C_SHADOW) {
1320 MDB_cursor *m2 = mc->mc_orig;
1322 m2->mc_snum = mc->mc_snum;
1323 m2->mc_top = mc->mc_top;
1324 for (j=0; j<mc->mc_snum; j++) {
1325 m2->mc_pg[j] = mc->mc_pg[j];
1326 m2->mc_ki[j] = mc->mc_ki[j];
1329 if (mc->mc_flags & C_ALLOCD)
1337 mdb_txn_reset0(MDB_txn *txn);
1339 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
1340 * @param[in] txn the transaction handle to initialize
1341 * @return 0 on success, non-zero on failure. This can only
1342 * fail for read-only transactions, and then only if the
1343 * reader table is full.
1346 mdb_txn_renew0(MDB_txn *txn)
1348 MDB_env *env = txn->mt_env;
1351 if (txn->mt_flags & MDB_TXN_RDONLY) {
1352 MDB_reader *r = pthread_getspecific(env->me_txkey);
1355 pid_t pid = getpid();
1356 pthread_t tid = pthread_self();
1359 for (i=0; i<env->me_txns->mti_numreaders; i++)
1360 if (env->me_txns->mti_readers[i].mr_pid == 0)
1362 if (i == env->me_maxreaders) {
1363 UNLOCK_MUTEX_R(env);
1366 env->me_txns->mti_readers[i].mr_pid = pid;
1367 env->me_txns->mti_readers[i].mr_tid = tid;
1368 if (i >= env->me_txns->mti_numreaders)
1369 env->me_txns->mti_numreaders = i+1;
1370 UNLOCK_MUTEX_R(env);
1371 r = &env->me_txns->mti_readers[i];
1372 pthread_setspecific(env->me_txkey, r);
1374 txn->mt_toggle = env->me_txns->mti_me_toggle;
1375 txn->mt_txnid = env->me_txns->mti_txnid;
1376 /* This happens if a different process was the
1377 * last writer to the DB.
1379 if (env->me_wtxnid < txn->mt_txnid)
1380 mt_dbflag = DB_STALE;
1381 r->mr_txnid = txn->mt_txnid;
1382 txn->mt_u.reader = r;
1386 txn->mt_txnid = env->me_txns->mti_txnid;
1387 if (env->me_wtxnid < txn->mt_txnid)
1388 mt_dbflag = DB_STALE;
1390 txn->mt_toggle = env->me_txns->mti_me_toggle;
1391 txn->mt_u.dirty_list = env->me_dirty_list;
1392 txn->mt_u.dirty_list[0].mid = 0;
1393 txn->mt_free_pgs = env->me_free_pgs;
1394 txn->mt_free_pgs[0] = 0;
1395 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1399 /* Copy the DB arrays */
1400 LAZY_RWLOCK_RDLOCK(&env->me_dblock);
1401 txn->mt_numdbs = env->me_numdbs;
1402 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
1403 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
1404 if (txn->mt_numdbs > 2)
1405 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
1406 (txn->mt_numdbs - 2) * sizeof(MDB_db));
1407 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1409 memset(txn->mt_dbflags, mt_dbflag, env->me_numdbs);
1415 mdb_txn_renew(MDB_txn *txn)
1422 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
1423 DPUTS("environment had fatal error, must shutdown!");
1427 rc = mdb_txn_renew0(txn);
1428 if (rc == MDB_SUCCESS) {
1429 DPRINTF("renew txn %zu%c %p on mdbenv %p, root page %zu",
1430 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1431 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1437 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
1442 if (env->me_flags & MDB_FATAL_ERROR) {
1443 DPUTS("environment had fatal error, must shutdown!");
1447 /* parent already has an active child txn */
1448 if (parent->mt_child) {
1452 size = sizeof(MDB_txn) + env->me_maxdbs * (sizeof(MDB_db)+1);
1453 if (!(flags & MDB_RDONLY))
1454 size += env->me_maxdbs * sizeof(MDB_cursor *);
1456 if ((txn = calloc(1, size)) == NULL) {
1457 DPRINTF("calloc: %s", strerror(ErrCode()));
1460 txn->mt_dbs = (MDB_db *)(txn+1);
1461 if (flags & MDB_RDONLY) {
1462 txn->mt_flags |= MDB_TXN_RDONLY;
1463 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
1465 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
1466 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
1471 txn->mt_free_pgs = mdb_midl_alloc();
1472 if (!txn->mt_free_pgs) {
1476 txn->mt_u.dirty_list = malloc(sizeof(ID2)*MDB_IDL_UM_SIZE);
1477 if (!txn->mt_u.dirty_list) {
1478 free(txn->mt_free_pgs);
1482 txn->mt_txnid = parent->mt_txnid;
1483 txn->mt_toggle = parent->mt_toggle;
1484 txn->mt_u.dirty_list[0].mid = 0;
1485 txn->mt_free_pgs[0] = 0;
1486 txn->mt_next_pgno = parent->mt_next_pgno;
1487 parent->mt_child = txn;
1488 txn->mt_parent = parent;
1489 txn->mt_numdbs = parent->mt_numdbs;
1490 txn->mt_dbxs = parent->mt_dbxs;
1491 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
1492 memcpy(txn->mt_dbflags, parent->mt_dbflags, txn->mt_numdbs);
1493 mdb_cursor_shadow(parent, txn);
1496 rc = mdb_txn_renew0(txn);
1502 DPRINTF("begin txn %zu%c %p on mdbenv %p, root page %zu",
1503 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1504 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
1510 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
1511 * @param[in] txn the transaction handle to reset
1514 mdb_txn_reset0(MDB_txn *txn)
1516 MDB_env *env = txn->mt_env;
1518 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1519 txn->mt_u.reader->mr_txnid = 0;
1525 /* close(free) all cursors */
1526 for (i=0; i<txn->mt_numdbs; i++) {
1527 if (txn->mt_cursors[i]) {
1529 while ((mc = txn->mt_cursors[i])) {
1530 txn->mt_cursors[i] = mc->mc_next;
1531 if (mc->mc_flags & C_ALLOCD)
1537 /* return all dirty pages to dpage list */
1538 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1539 dp = txn->mt_u.dirty_list[i].mptr;
1540 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1541 dp->mp_next = txn->mt_env->me_dpages;
1542 txn->mt_env->me_dpages = dp;
1544 /* large pages just get freed directly */
1549 if (txn->mt_parent) {
1550 txn->mt_parent->mt_child = NULL;
1551 free(txn->mt_free_pgs);
1552 free(txn->mt_u.dirty_list);
1555 if (mdb_midl_shrink(&txn->mt_free_pgs))
1556 env->me_free_pgs = txn->mt_free_pgs;
1559 while ((mop = txn->mt_env->me_pghead)) {
1560 txn->mt_env->me_pghead = mop->mo_next;
1565 /* The writer mutex was locked in mdb_txn_begin. */
1566 UNLOCK_MUTEX_W(env);
1571 mdb_txn_reset(MDB_txn *txn)
1576 DPRINTF("reset txn %zu%c %p on mdbenv %p, root page %zu",
1577 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1578 (void *) txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1580 mdb_txn_reset0(txn);
1584 mdb_txn_abort(MDB_txn *txn)
1589 DPRINTF("abort txn %zu%c %p on mdbenv %p, root page %zu",
1590 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1591 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1594 mdb_txn_abort(txn->mt_child);
1596 mdb_txn_reset0(txn);
1601 mdb_txn_commit(MDB_txn *txn)
1612 assert(txn != NULL);
1613 assert(txn->mt_env != NULL);
1615 if (txn->mt_child) {
1616 mdb_txn_commit(txn->mt_child);
1617 txn->mt_child = NULL;
1622 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1623 if (txn->mt_numdbs > env->me_numdbs) {
1624 /* update the DB tables */
1625 int toggle = !env->me_db_toggle;
1629 ip = &env->me_dbs[toggle][env->me_numdbs];
1630 jp = &txn->mt_dbs[env->me_numdbs];
1631 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1632 for (i = env->me_numdbs; i < txn->mt_numdbs; i++) {
1636 env->me_db_toggle = toggle;
1637 env->me_numdbs = txn->mt_numdbs;
1638 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1644 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1645 DPUTS("error flag is set, can't commit");
1647 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
1652 /* Merge (and close) our cursors with parent's */
1653 mdb_cursor_merge(txn);
1655 if (txn->mt_parent) {
1661 /* Update parent's DB table */
1662 ip = &txn->mt_parent->mt_dbs[2];
1663 jp = &txn->mt_dbs[2];
1664 for (i = 2; i < txn->mt_numdbs; i++) {
1665 if (ip->md_root != jp->md_root)
1669 txn->mt_parent->mt_numdbs = txn->mt_numdbs;
1671 /* Append our free list to parent's */
1672 mdb_midl_append_list(&txn->mt_parent->mt_free_pgs,
1674 mdb_midl_free(txn->mt_free_pgs);
1676 /* Merge our dirty list with parent's */
1677 dst = txn->mt_parent->mt_u.dirty_list;
1678 src = txn->mt_u.dirty_list;
1679 x = mdb_mid2l_search(dst, src[1].mid);
1680 for (y=1; y<=src[0].mid; y++) {
1681 while (x <= dst[0].mid && dst[x].mid != src[y].mid) x++;
1685 dst[x].mptr = src[y].mptr;
1688 for (; y<=src[0].mid; y++) {
1689 if (++x >= MDB_IDL_UM_MAX)
1694 free(txn->mt_u.dirty_list);
1695 txn->mt_parent->mt_child = NULL;
1700 if (txn != env->me_txn) {
1701 DPUTS("attempt to commit unknown transaction");
1706 if (!txn->mt_u.dirty_list[0].mid)
1709 DPRINTF("committing txn %zu %p on mdbenv %p, root page %zu",
1710 txn->mt_txnid, (void *)txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
1712 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1714 /* should only be one record now */
1715 if (env->me_pghead) {
1716 /* make sure first page of freeDB is touched and on freelist */
1717 mdb_page_search(&mc, NULL, 1);
1719 /* save to free list */
1720 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
1724 /* make sure last page of freeDB is touched and on freelist */
1725 key.mv_size = MAXKEYSIZE+1;
1727 mdb_page_search(&mc, &key, 1);
1729 mdb_midl_sort(txn->mt_free_pgs);
1733 ID *idl = txn->mt_free_pgs;
1734 DPRINTF("IDL write txn %zu root %zu num %zu",
1735 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1736 for (i=0; i<idl[0]; i++) {
1737 DPRINTF("IDL %zu", idl[i+1]);
1741 /* write to last page of freeDB */
1742 key.mv_size = sizeof(pgno_t);
1743 key.mv_data = &txn->mt_txnid;
1744 data.mv_data = txn->mt_free_pgs;
1745 /* The free list can still grow during this call,
1746 * despite the pre-emptive touches above. So check
1747 * and make sure the entire thing got written.
1750 i = txn->mt_free_pgs[0];
1751 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
1752 rc = mdb_cursor_put(&mc, &key, &data, 0);
1757 } while (i != txn->mt_free_pgs[0]);
1758 if (mdb_midl_shrink(&txn->mt_free_pgs))
1759 env->me_free_pgs = txn->mt_free_pgs;
1761 /* should only be one record now */
1762 if (env->me_pghead) {
1766 mop = env->me_pghead;
1767 env->me_pghead = NULL;
1768 key.mv_size = sizeof(pgno_t);
1769 key.mv_data = &mop->mo_txnid;
1770 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
1771 data.mv_data = mop->mo_pages;
1772 mdb_cursor_put(&mc, &key, &data, 0);
1776 /* Update DB root pointers. Their pages have already been
1777 * touched so this is all in-place and cannot fail.
1782 data.mv_size = sizeof(MDB_db);
1784 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
1785 for (i = 2; i < txn->mt_numdbs; i++) {
1786 if (txn->mt_dbflags[i] & DB_DIRTY) {
1787 data.mv_data = &txn->mt_dbs[i];
1788 mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
1793 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
1799 /* Windows actually supports scatter/gather I/O, but only on
1800 * unbuffered file handles. Since we're relying on the OS page
1801 * cache for all our data, that's self-defeating. So we just
1802 * write pages one at a time. We use the ov structure to set
1803 * the write offset, to at least save the overhead of a Seek
1807 memset(&ov, 0, sizeof(ov));
1808 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1810 dp = txn->mt_u.dirty_list[i].mptr;
1811 DPRINTF("committing page %zu", dp->mp_pgno);
1812 size = dp->mp_pgno * env->me_psize;
1813 ov.Offset = size & 0xffffffff;
1814 ov.OffsetHigh = size >> 16;
1815 ov.OffsetHigh >>= 16;
1816 /* clear dirty flag */
1817 dp->mp_flags &= ~P_DIRTY;
1818 wsize = env->me_psize;
1819 if (IS_OVERFLOW(dp)) wsize *= dp->mp_pages;
1820 rc = WriteFile(env->me_fd, dp, wsize, NULL, &ov);
1823 DPRINTF("WriteFile: %d", n);
1830 struct iovec iov[MDB_COMMIT_PAGES];
1834 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1835 dp = txn->mt_u.dirty_list[i].mptr;
1836 if (dp->mp_pgno != next) {
1838 DPRINTF("committing %u dirty pages", n);
1839 rc = writev(env->me_fd, iov, n);
1843 DPUTS("short write, filesystem full?");
1845 DPRINTF("writev: %s", strerror(n));
1852 lseek(env->me_fd, dp->mp_pgno * env->me_psize, SEEK_SET);
1855 DPRINTF("committing page %zu", dp->mp_pgno);
1856 iov[n].iov_len = env->me_psize;
1857 if (IS_OVERFLOW(dp)) iov[n].iov_len *= dp->mp_pages;
1858 iov[n].iov_base = dp;
1859 size += iov[n].iov_len;
1860 next = dp->mp_pgno + (IS_OVERFLOW(dp) ? dp->mp_pages : 1);
1861 /* clear dirty flag */
1862 dp->mp_flags &= ~P_DIRTY;
1863 if (++n >= MDB_COMMIT_PAGES) {
1873 DPRINTF("committing %u dirty pages", n);
1874 rc = writev(env->me_fd, iov, n);
1878 DPUTS("short write, filesystem full?");
1880 DPRINTF("writev: %s", strerror(n));
1887 /* Drop the dirty pages.
1889 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1890 dp = txn->mt_u.dirty_list[i].mptr;
1891 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1892 dp->mp_next = txn->mt_env->me_dpages;
1893 txn->mt_env->me_dpages = dp;
1897 txn->mt_u.dirty_list[i].mid = 0;
1899 txn->mt_u.dirty_list[0].mid = 0;
1901 if ((n = mdb_env_sync(env, 0)) != 0 ||
1902 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
1906 env->me_wtxnid = txn->mt_txnid;
1910 /* update the DB tables */
1912 int toggle = !env->me_db_toggle;
1916 ip = &env->me_dbs[toggle][2];
1917 jp = &txn->mt_dbs[2];
1918 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1919 for (i = 2; i < txn->mt_numdbs; i++) {
1920 if (ip->md_root != jp->md_root)
1925 env->me_db_toggle = toggle;
1926 env->me_numdbs = txn->mt_numdbs;
1927 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1930 UNLOCK_MUTEX_W(env);
1936 /** Read the environment parameters of a DB environment before
1937 * mapping it into memory.
1938 * @param[in] env the environment handle
1939 * @param[out] meta address of where to store the meta information
1940 * @return 0 on success, non-zero on failure.
1943 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
1945 char page[PAGESIZE];
1950 /* We don't know the page size yet, so use a minimum value.
1954 if (!ReadFile(env->me_fd, page, PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
1956 if ((rc = read(env->me_fd, page, PAGESIZE)) == 0)
1961 else if (rc != PAGESIZE) {
1965 DPRINTF("read: %s", strerror(err));
1969 p = (MDB_page *)page;
1971 if (!F_ISSET(p->mp_flags, P_META)) {
1972 DPRINTF("page %zu not a meta page", p->mp_pgno);
1977 if (m->mm_magic != MDB_MAGIC) {
1978 DPUTS("meta has invalid magic");
1982 if (m->mm_version != MDB_VERSION) {
1983 DPRINTF("database is version %u, expected version %u",
1984 m->mm_version, MDB_VERSION);
1985 return MDB_VERSION_MISMATCH;
1988 memcpy(meta, m, sizeof(*m));
1992 /** Write the environment parameters of a freshly created DB environment.
1993 * @param[in] env the environment handle
1994 * @param[out] meta address of where to store the meta information
1995 * @return 0 on success, non-zero on failure.
1998 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
2005 DPUTS("writing new meta page");
2007 GET_PAGESIZE(psize);
2009 meta->mm_magic = MDB_MAGIC;
2010 meta->mm_version = MDB_VERSION;
2011 meta->mm_psize = psize;
2012 meta->mm_last_pg = 1;
2013 meta->mm_flags = env->me_flags & 0xffff;
2014 meta->mm_flags |= MDB_INTEGERKEY;
2015 meta->mm_dbs[0].md_root = P_INVALID;
2016 meta->mm_dbs[1].md_root = P_INVALID;
2018 p = calloc(2, psize);
2020 p->mp_flags = P_META;
2023 memcpy(m, meta, sizeof(*meta));
2025 q = (MDB_page *)((char *)p + psize);
2028 q->mp_flags = P_META;
2031 memcpy(m, meta, sizeof(*meta));
2036 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
2037 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
2040 rc = write(env->me_fd, p, psize * 2);
2041 rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
2047 /** Update the environment info to commit a transaction.
2048 * @param[in] txn the transaction that's being committed
2049 * @return 0 on success, non-zero on failure.
2052 mdb_env_write_meta(MDB_txn *txn)
2055 MDB_meta meta, metab;
2057 int rc, len, toggle;
2063 assert(txn != NULL);
2064 assert(txn->mt_env != NULL);
2066 toggle = !txn->mt_toggle;
2067 DPRINTF("writing meta page %d for root page %zu",
2068 toggle, txn->mt_dbs[MAIN_DBI].md_root);
2072 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
2073 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
2075 ptr = (char *)&meta;
2076 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
2077 len = sizeof(MDB_meta) - off;
2080 meta.mm_dbs[0] = txn->mt_dbs[0];
2081 meta.mm_dbs[1] = txn->mt_dbs[1];
2082 meta.mm_last_pg = txn->mt_next_pgno - 1;
2083 meta.mm_txnid = txn->mt_txnid;
2086 off += env->me_psize;
2089 /* Write to the SYNC fd */
2092 memset(&ov, 0, sizeof(ov));
2094 WriteFile(env->me_mfd, ptr, len, (DWORD *)&rc, &ov);
2097 rc = pwrite(env->me_mfd, ptr, len, off);
2102 DPUTS("write failed, disk error?");
2103 /* On a failure, the pagecache still contains the new data.
2104 * Write some old data back, to prevent it from being used.
2105 * Use the non-SYNC fd; we know it will fail anyway.
2107 meta.mm_last_pg = metab.mm_last_pg;
2108 meta.mm_txnid = metab.mm_txnid;
2110 WriteFile(env->me_fd, ptr, len, NULL, &ov);
2112 r2 = pwrite(env->me_fd, ptr, len, off);
2114 env->me_flags |= MDB_FATAL_ERROR;
2117 /* Memory ordering issues are irrelevant; since the entire writer
2118 * is wrapped by wmutex, all of these changes will become visible
2119 * after the wmutex is unlocked. Since the DB is multi-version,
2120 * readers will get consistent data regardless of how fresh or
2121 * how stale their view of these values is.
2123 LAZY_MUTEX_LOCK(&env->me_txns->mti_mutex);
2124 txn->mt_env->me_txns->mti_me_toggle = toggle;
2125 txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
2126 LAZY_MUTEX_UNLOCK(&env->me_txns->mti_mutex);
2131 /** Check both meta pages to see which one is newer.
2132 * @param[in] env the environment handle
2133 * @param[out] which address of where to store the meta toggle ID
2134 * @return 0 on success, non-zero on failure.
2137 mdb_env_read_meta(MDB_env *env, int *which)
2141 assert(env != NULL);
2143 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
2146 DPRINTF("Using meta page %d", toggle);
2153 mdb_env_create(MDB_env **env)
2157 e = calloc(1, sizeof(MDB_env));
2161 e->me_free_pgs = mdb_midl_alloc();
2162 if (!e->me_free_pgs) {
2166 e->me_maxreaders = DEFAULT_READERS;
2168 e->me_fd = INVALID_HANDLE_VALUE;
2169 e->me_lfd = INVALID_HANDLE_VALUE;
2170 e->me_mfd = INVALID_HANDLE_VALUE;
2176 mdb_env_set_mapsize(MDB_env *env, size_t size)
2180 env->me_mapsize = size;
2182 env->me_maxpg = env->me_mapsize / env->me_psize;
2187 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
2191 env->me_maxdbs = dbs;
2196 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
2198 if (env->me_map || readers < 1)
2200 env->me_maxreaders = readers;
2205 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
2207 if (!env || !readers)
2209 *readers = env->me_maxreaders;
2213 /** Further setup required for opening an MDB environment
2216 mdb_env_open2(MDB_env *env, unsigned int flags)
2218 int i, newenv = 0, toggle;
2222 env->me_flags = flags;
2224 memset(&meta, 0, sizeof(meta));
2226 if ((i = mdb_env_read_header(env, &meta)) != 0) {
2229 DPUTS("new mdbenv");
2233 if (!env->me_mapsize) {
2234 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
2240 LONG sizelo, sizehi;
2241 sizelo = env->me_mapsize & 0xffffffff;
2242 sizehi = env->me_mapsize >> 16; /* pointless on WIN32, only needed on W64 */
2244 /* Windows won't create mappings for zero length files.
2245 * Just allocate the maxsize right now.
2248 SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
2249 if (!SetEndOfFile(env->me_fd))
2251 SetFilePointer(env->me_fd, 0, NULL, 0);
2253 mh = CreateFileMapping(env->me_fd, NULL, PAGE_READONLY,
2254 sizehi, sizelo, NULL);
2257 env->me_map = MapViewOfFileEx(mh, FILE_MAP_READ, 0, 0, env->me_mapsize,
2265 if (meta.mm_address && (flags & MDB_FIXEDMAP))
2267 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
2269 if (env->me_map == MAP_FAILED)
2274 meta.mm_mapsize = env->me_mapsize;
2275 if (flags & MDB_FIXEDMAP)
2276 meta.mm_address = env->me_map;
2277 i = mdb_env_init_meta(env, &meta);
2278 if (i != MDB_SUCCESS) {
2279 munmap(env->me_map, env->me_mapsize);
2283 env->me_psize = meta.mm_psize;
2285 env->me_maxpg = env->me_mapsize / env->me_psize;
2287 p = (MDB_page *)env->me_map;
2288 env->me_metas[0] = METADATA(p);
2289 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
2291 if ((i = mdb_env_read_meta(env, &toggle)) != 0)
2294 DPRINTF("opened database version %u, pagesize %u",
2295 env->me_metas[toggle]->mm_version, env->me_psize);
2296 DPRINTF("depth: %u", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_depth);
2297 DPRINTF("entries: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_entries);
2298 DPRINTF("branch pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_branch_pages);
2299 DPRINTF("leaf pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_leaf_pages);
2300 DPRINTF("overflow pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_overflow_pages);
2301 DPRINTF("root: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_root);
2307 /** Release a reader thread's slot in the reader lock table.
2308 * This function is called automatically when a thread exits.
2309 * Windows doesn't support destructor callbacks for thread-specific storage,
2310 * so this function is not compiled there.
2311 * @param[in] ptr This points to the slot in the reader lock table.
2314 mdb_env_reader_dest(void *ptr)
2316 MDB_reader *reader = ptr;
2318 reader->mr_txnid = 0;
2324 /** Downgrade the exclusive lock on the region back to shared */
2326 mdb_env_share_locks(MDB_env *env)
2330 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
2332 env->me_txns->mti_me_toggle = toggle;
2333 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
2338 /* First acquire a shared lock. The Unlock will
2339 * then release the existing exclusive lock.
2341 memset(&ov, 0, sizeof(ov));
2342 LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov);
2343 UnlockFile(env->me_lfd, 0, 0, 1, 0);
2347 struct flock lock_info;
2348 /* The shared lock replaces the existing lock */
2349 memset((void *)&lock_info, 0, sizeof(lock_info));
2350 lock_info.l_type = F_RDLCK;
2351 lock_info.l_whence = SEEK_SET;
2352 lock_info.l_start = 0;
2353 lock_info.l_len = 1;
2354 fcntl(env->me_lfd, F_SETLK, &lock_info);
2358 #if defined(_WIN32) || defined(__APPLE__)
2360 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
2362 * @(#) $Revision: 5.1 $
2363 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
2364 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
2366 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
2370 * Please do not copyright this code. This code is in the public domain.
2372 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
2373 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
2374 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
2375 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
2376 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
2377 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
2378 * PERFORMANCE OF THIS SOFTWARE.
2381 * chongo <Landon Curt Noll> /\oo/\
2382 * http://www.isthe.com/chongo/
2384 * Share and Enjoy! :-)
2387 typedef unsigned long long mdb_hash_t;
2388 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
2390 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
2391 * @param[in] str string to hash
2392 * @param[in] hval initial value for hash
2393 * @return 64 bit hash
2395 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
2396 * hval arg on the first call.
2399 mdb_hash_str(char *str, mdb_hash_t hval)
2401 unsigned char *s = (unsigned char *)str; /* unsigned string */
2403 * FNV-1a hash each octet of the string
2406 /* xor the bottom with the current octet */
2407 hval ^= (mdb_hash_t)*s++;
2409 /* multiply by the 64 bit FNV magic prime mod 2^64 */
2410 hval += (hval << 1) + (hval << 4) + (hval << 5) +
2411 (hval << 7) + (hval << 8) + (hval << 40);
2413 /* return our new hash value */
2417 /** Hash the string and output the hash in hex.
2418 * @param[in] str string to hash
2419 * @param[out] hexbuf an array of 17 chars to hold the hash
2422 mdb_hash_hex(char *str, char *hexbuf)
2425 mdb_hash_t h = mdb_hash_str(str, MDB_HASH_INIT);
2426 for (i=0; i<8; i++) {
2427 hexbuf += sprintf(hexbuf, "%02x", (unsigned int)h & 0xff);
2433 /** Open and/or initialize the lock region for the environment.
2434 * @param[in] env The MDB environment.
2435 * @param[in] lpath The pathname of the file used for the lock region.
2436 * @param[in] mode The Unix permissions for the file, if we create it.
2437 * @param[out] excl Set to true if we got an exclusive lock on the region.
2438 * @return 0 on success, non-zero on failure.
2441 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
2449 if ((env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
2450 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
2451 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
2455 /* Try to get exclusive lock. If we succeed, then
2456 * nobody is using the lock region and we should initialize it.
2459 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
2463 memset(&ov, 0, sizeof(ov));
2464 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
2470 size = GetFileSize(env->me_lfd, NULL);
2472 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
2476 /* Try to get exclusive lock. If we succeed, then
2477 * nobody is using the lock region and we should initialize it.
2480 struct flock lock_info;
2481 memset((void *)&lock_info, 0, sizeof(lock_info));
2482 lock_info.l_type = F_WRLCK;
2483 lock_info.l_whence = SEEK_SET;
2484 lock_info.l_start = 0;
2485 lock_info.l_len = 1;
2486 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
2490 lock_info.l_type = F_RDLCK;
2491 rc = fcntl(env->me_lfd, F_SETLKW, &lock_info);
2498 size = lseek(env->me_lfd, 0, SEEK_END);
2500 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
2501 if (size < rsize && *excl) {
2503 SetFilePointer(env->me_lfd, rsize, NULL, 0);
2504 if (!SetEndOfFile(env->me_lfd)) {
2509 if (ftruncate(env->me_lfd, rsize) != 0) {
2516 size = rsize - sizeof(MDB_txninfo);
2517 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
2522 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
2528 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
2530 if (!env->me_txns) {
2536 env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
2538 if (env->me_txns == MAP_FAILED) {
2546 if (!mdb_sec_inited) {
2547 InitializeSecurityDescriptor(&mdb_null_sd,
2548 SECURITY_DESCRIPTOR_REVISION);
2549 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
2550 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2551 mdb_all_sa.bInheritHandle = FALSE;
2552 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
2555 mdb_hash_hex(lpath, hexbuf);
2556 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", hexbuf);
2557 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
2558 if (!env->me_rmutex) {
2562 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", hexbuf);
2563 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
2564 if (!env->me_wmutex) {
2571 mdb_hash_hex(lpath, hexbuf);
2572 sprintf(env->me_txns->mti_rmname, "MDBr%s", hexbuf);
2573 if (sem_unlink(env->me_txns->mti_rmname)) {
2575 if (rc != ENOENT && rc != EINVAL)
2578 env->me_rmutex = sem_open(env->me_txns->mti_rmname, O_CREAT, mode, 1);
2579 if (!env->me_rmutex) {
2583 sprintf(env->me_txns->mti_wmname, "MDBw%s", hexbuf);
2584 if (sem_unlink(env->me_txns->mti_wmname)) {
2586 if (rc != ENOENT && rc != EINVAL)
2589 env->me_wmutex = sem_open(env->me_txns->mti_wmname, O_CREAT, mode, 1);
2590 if (!env->me_wmutex) {
2594 #else /* __APPLE__ */
2595 pthread_mutexattr_t mattr;
2597 pthread_mutexattr_init(&mattr);
2598 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
2602 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
2603 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
2604 #endif /* __APPLE__ */
2606 env->me_txns->mti_version = MDB_VERSION;
2607 env->me_txns->mti_magic = MDB_MAGIC;
2608 env->me_txns->mti_txnid = 0;
2609 env->me_txns->mti_numreaders = 0;
2610 env->me_txns->mti_me_toggle = 0;
2613 if (env->me_txns->mti_magic != MDB_MAGIC) {
2614 DPUTS("lock region has invalid magic");
2618 if (env->me_txns->mti_version != MDB_VERSION) {
2619 DPRINTF("lock region is version %u, expected version %u",
2620 env->me_txns->mti_version, MDB_VERSION);
2621 rc = MDB_VERSION_MISMATCH;
2625 if (rc != EACCES && rc != EAGAIN) {
2629 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
2630 if (!env->me_rmutex) {
2634 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
2635 if (!env->me_wmutex) {
2641 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
2642 if (!env->me_rmutex) {
2646 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
2647 if (!env->me_wmutex) {
2657 env->me_lfd = INVALID_HANDLE_VALUE;
2662 /** The name of the lock file in the DB environment */
2663 #define LOCKNAME "/lock.mdb"
2664 /** The name of the data file in the DB environment */
2665 #define DATANAME "/data.mdb"
2666 /** The suffix of the lock file when no subdir is used */
2667 #define LOCKSUFF "-lock"
2670 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
2672 int oflags, rc, len, excl;
2673 char *lpath, *dpath;
2676 if (flags & MDB_NOSUBDIR) {
2677 rc = len + sizeof(LOCKSUFF) + len + 1;
2679 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
2684 if (flags & MDB_NOSUBDIR) {
2685 dpath = lpath + len + sizeof(LOCKSUFF);
2686 sprintf(lpath, "%s" LOCKSUFF, path);
2687 strcpy(dpath, path);
2689 dpath = lpath + len + sizeof(LOCKNAME);
2690 sprintf(lpath, "%s" LOCKNAME, path);
2691 sprintf(dpath, "%s" DATANAME, path);
2694 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
2699 if (F_ISSET(flags, MDB_RDONLY)) {
2700 oflags = GENERIC_READ;
2701 len = OPEN_EXISTING;
2703 oflags = GENERIC_READ|GENERIC_WRITE;
2706 mode = FILE_ATTRIBUTE_NORMAL;
2707 if ((env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2708 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2713 if (F_ISSET(flags, MDB_RDONLY))
2716 oflags = O_RDWR | O_CREAT;
2718 if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
2724 if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
2725 /* synchronous fd for meta writes */
2727 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2728 mode |= FILE_FLAG_WRITE_THROUGH;
2729 if ((env->me_mfd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2730 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2735 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2736 oflags |= MDB_DSYNC;
2737 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
2742 env->me_path = strdup(path);
2743 DPRINTF("opened dbenv %p", (void *) env);
2744 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
2745 LAZY_RWLOCK_INIT(&env->me_dblock, NULL);
2747 mdb_env_share_locks(env);
2748 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
2749 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
2750 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
2756 if (env->me_fd != INVALID_HANDLE_VALUE) {
2758 env->me_fd = INVALID_HANDLE_VALUE;
2760 if (env->me_lfd != INVALID_HANDLE_VALUE) {
2762 env->me_lfd = INVALID_HANDLE_VALUE;
2770 mdb_env_close(MDB_env *env)
2777 while (env->me_dpages) {
2778 dp = env->me_dpages;
2779 env->me_dpages = dp->mp_next;
2783 free(env->me_dbs[1]);
2784 free(env->me_dbs[0]);
2788 LAZY_RWLOCK_DESTROY(&env->me_dblock);
2789 pthread_key_delete(env->me_txkey);
2792 munmap(env->me_map, env->me_mapsize);
2797 pid_t pid = getpid();
2799 for (i=0; i<env->me_txns->mti_numreaders; i++)
2800 if (env->me_txns->mti_readers[i].mr_pid == pid)
2801 env->me_txns->mti_readers[i].mr_pid = 0;
2802 munmap(env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
2805 mdb_midl_free(env->me_free_pgs);
2809 /** Compare two items pointing at aligned size_t's */
2811 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
2813 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
2814 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
2817 /** Compare two items pointing at aligned int's */
2819 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
2821 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
2822 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
2825 /** Compare two items pointing at ints of unknown alignment.
2826 * Nodes and keys are guaranteed to be 2-byte aligned.
2829 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
2831 #if BYTE_ORDER == LITTLE_ENDIAN
2832 unsigned short *u, *c;
2835 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
2836 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
2839 } while(!x && u > (unsigned short *)a->mv_data);
2842 return memcmp(a->mv_data, b->mv_data, a->mv_size);
2846 /** Compare two items lexically */
2848 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
2855 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
2861 diff = memcmp(a->mv_data, b->mv_data, len);
2862 return diff ? diff : len_diff<0 ? -1 : len_diff;
2865 /** Compare two items in reverse byte order */
2867 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
2869 const unsigned char *p1, *p2, *p1_lim;
2873 p1_lim = (const unsigned char *)a->mv_data;
2874 p1 = (const unsigned char *)a->mv_data + a->mv_size;
2875 p2 = (const unsigned char *)b->mv_data + b->mv_size;
2877 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
2883 while (p1 > p1_lim) {
2884 diff = *--p1 - *--p2;
2888 return len_diff<0 ? -1 : len_diff;
2891 /** Search for key within a page, using binary search.
2892 * Returns the smallest entry larger or equal to the key.
2893 * If exactp is non-null, stores whether the found entry was an exact match
2894 * in *exactp (1 or 0).
2895 * Updates the cursor index with the index of the found entry.
2896 * If no entry larger or equal to the key is found, returns NULL.
2899 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
2901 unsigned int i = 0, nkeys;
2904 MDB_page *mp = mc->mc_pg[mc->mc_top];
2905 MDB_node *node = NULL;
2910 nkeys = NUMKEYS(mp);
2912 DPRINTF("searching %u keys in %s %spage %zu",
2913 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
2918 low = IS_LEAF(mp) ? 0 : 1;
2920 cmp = mc->mc_dbx->md_cmp;
2922 /* Branch pages have no data, so if using integer keys,
2923 * alignment is guaranteed. Use faster mdb_cmp_int.
2925 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
2926 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
2933 nodekey.mv_size = mc->mc_db->md_pad;
2934 node = NODEPTR(mp, 0); /* fake */
2935 while (low <= high) {
2936 i = (low + high) >> 1;
2937 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
2938 rc = cmp(key, &nodekey);
2939 DPRINTF("found leaf index %u [%s], rc = %i",
2940 i, DKEY(&nodekey), rc);
2949 while (low <= high) {
2950 i = (low + high) >> 1;
2952 node = NODEPTR(mp, i);
2953 nodekey.mv_size = NODEKSZ(node);
2954 nodekey.mv_data = NODEKEY(node);
2956 rc = cmp(key, &nodekey);
2959 DPRINTF("found leaf index %u [%s], rc = %i",
2960 i, DKEY(&nodekey), rc);
2962 DPRINTF("found branch index %u [%s -> %zu], rc = %i",
2963 i, DKEY(&nodekey), NODEPGNO(node), rc);
2974 if (rc > 0) { /* Found entry is less than the key. */
2975 i++; /* Skip to get the smallest entry larger than key. */
2977 node = NODEPTR(mp, i);
2980 *exactp = (rc == 0);
2981 /* store the key index */
2982 mc->mc_ki[mc->mc_top] = i;
2984 /* There is no entry larger or equal to the key. */
2987 /* nodeptr is fake for LEAF2 */
2993 mdb_cursor_adjust(MDB_cursor *mc, func)
2997 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
2998 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
3005 /** Pop a page off the top of the cursor's stack. */
3007 mdb_cursor_pop(MDB_cursor *mc)
3012 top = mc->mc_pg[mc->mc_top];
3017 DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
3018 mc->mc_dbi, (void *) mc);
3022 /** Push a page onto the top of the cursor's stack. */
3024 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
3026 DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
3027 mc->mc_dbi, (void *) mc);
3029 if (mc->mc_snum >= CURSOR_STACK) {
3030 assert(mc->mc_snum < CURSOR_STACK);
3034 mc->mc_top = mc->mc_snum++;
3035 mc->mc_pg[mc->mc_top] = mp;
3036 mc->mc_ki[mc->mc_top] = 0;
3041 /** Find the address of the page corresponding to a given page number.
3042 * @param[in] txn the transaction for this access.
3043 * @param[in] pgno the page number for the page to retrieve.
3044 * @param[out] ret address of a pointer where the page's address will be stored.
3045 * @return 0 on success, non-zero on failure.
3048 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
3052 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
3054 x = mdb_mid2l_search(txn->mt_u.dirty_list, pgno);
3055 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
3056 p = txn->mt_u.dirty_list[x].mptr;
3060 if (pgno <= txn->mt_env->me_metas[txn->mt_toggle]->mm_last_pg)
3061 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
3065 DPRINTF("page %zu not found", pgno);
3068 return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
3071 /** Search for the page a given key should be in.
3072 * Pushes parent pages on the cursor stack. This function continues a
3073 * search on a cursor that has already been initialized. (Usually by
3074 * #mdb_page_search() but also by #mdb_node_move().)
3075 * @param[in,out] mc the cursor for this operation.
3076 * @param[in] key the key to search for. If NULL, search for the lowest
3077 * page. (This is used by #mdb_cursor_first().)
3078 * @param[in] modify If true, visited pages are updated with new page numbers.
3079 * @return 0 on success, non-zero on failure.
3082 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
3084 MDB_page *mp = mc->mc_pg[mc->mc_top];
3089 while (IS_BRANCH(mp)) {
3093 DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
3094 assert(NUMKEYS(mp) > 1);
3095 DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
3097 if (key == NULL) /* Initialize cursor to first page. */
3099 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
3100 /* cursor to last page */
3104 node = mdb_node_search(mc, key, &exact);
3106 i = NUMKEYS(mp) - 1;
3108 i = mc->mc_ki[mc->mc_top];
3117 DPRINTF("following index %u for key [%s]",
3119 assert(i < NUMKEYS(mp));
3120 node = NODEPTR(mp, i);
3122 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp)))
3125 mc->mc_ki[mc->mc_top] = i;
3126 if ((rc = mdb_cursor_push(mc, mp)))
3130 if ((rc = mdb_page_touch(mc)) != 0)
3132 mp = mc->mc_pg[mc->mc_top];
3137 DPRINTF("internal error, index points to a %02X page!?",
3139 return MDB_CORRUPTED;
3142 DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
3143 key ? DKEY(key) : NULL);
3148 /** Search for the page a given key should be in.
3149 * Pushes parent pages on the cursor stack. This function just sets up
3150 * the search; it finds the root page for \b mc's database and sets this
3151 * as the root of the cursor's stack. Then #mdb_page_search_root() is
3152 * called to complete the search.
3153 * @param[in,out] mc the cursor for this operation.
3154 * @param[in] key the key to search for. If NULL, search for the lowest
3155 * page. (This is used by #mdb_cursor_first().)
3156 * @param[in] modify If true, visited pages are updated with new page numbers.
3157 * @return 0 on success, non-zero on failure.
3160 mdb_page_search(MDB_cursor *mc, MDB_val *key, int modify)
3165 /* Make sure the txn is still viable, then find the root from
3166 * the txn's db table.
3168 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
3169 DPUTS("transaction has failed, must abort");
3172 /* Make sure we're using an up-to-date root */
3173 if (mc->mc_dbi > MAIN_DBI) {
3174 if ((*mc->mc_dbflag & DB_STALE) ||
3175 (modify && !(*mc->mc_dbflag & DB_DIRTY))) {
3177 unsigned char dbflag = 0;
3178 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
3179 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, modify);
3182 if (*mc->mc_dbflag & DB_STALE) {
3185 MDB_node *leaf = mdb_node_search(&mc2,
3186 &mc->mc_dbx->md_name, &exact);
3188 return MDB_NOTFOUND;
3189 mdb_node_read(mc->mc_txn, leaf, &data);
3190 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
3194 *mc->mc_dbflag = dbflag;
3197 root = mc->mc_db->md_root;
3199 if (root == P_INVALID) { /* Tree is empty. */
3200 DPUTS("tree is empty");
3201 return MDB_NOTFOUND;
3206 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0])))
3212 DPRINTF("db %u root page %zu has flags 0x%X",
3213 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
3216 if ((rc = mdb_page_touch(mc)))
3220 return mdb_page_search_root(mc, key, modify);
3223 /** Return the data associated with a given node.
3224 * @param[in] txn The transaction for this operation.
3225 * @param[in] leaf The node being read.
3226 * @param[out] data Updated to point to the node's data.
3227 * @return 0 on success, non-zero on failure.
3230 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
3232 MDB_page *omp; /* overflow page */
3236 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
3237 data->mv_size = NODEDSZ(leaf);
3238 data->mv_data = NODEDATA(leaf);
3242 /* Read overflow data.
3244 data->mv_size = NODEDSZ(leaf);
3245 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
3246 if ((rc = mdb_page_get(txn, pgno, &omp))) {
3247 DPRINTF("read overflow page %zu failed", pgno);
3250 data->mv_data = METADATA(omp);
3256 mdb_get(MDB_txn *txn, MDB_dbi dbi,
3257 MDB_val *key, MDB_val *data)
3266 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
3268 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3271 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3275 mdb_cursor_init(&mc, txn, dbi, &mx);
3276 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
3279 /** Find a sibling for a page.
3280 * Replaces the page at the top of the cursor's stack with the
3281 * specified sibling, if one exists.
3282 * @param[in] mc The cursor for this operation.
3283 * @param[in] move_right Non-zero if the right sibling is requested,
3284 * otherwise the left sibling.
3285 * @return 0 on success, non-zero on failure.
3288 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
3294 if (mc->mc_snum < 2) {
3295 return MDB_NOTFOUND; /* root has no siblings */
3299 DPRINTF("parent page is page %zu, index %u",
3300 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]);
3302 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
3303 : (mc->mc_ki[mc->mc_top] == 0)) {
3304 DPRINTF("no more keys left, moving to %s sibling",
3305 move_right ? "right" : "left");
3306 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS)
3310 mc->mc_ki[mc->mc_top]++;
3312 mc->mc_ki[mc->mc_top]--;
3313 DPRINTF("just moving to %s index key %u",
3314 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]);
3316 assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
3318 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3319 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp)))
3322 mdb_cursor_push(mc, mp);
3327 /** Move the cursor to the next data item. */
3329 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3335 if (mc->mc_flags & C_EOF) {
3336 return MDB_NOTFOUND;
3339 assert(mc->mc_flags & C_INITIALIZED);
3341 mp = mc->mc_pg[mc->mc_top];
3343 if (mc->mc_db->md_flags & MDB_DUPSORT) {
3344 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3345 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3346 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
3347 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
3348 if (op != MDB_NEXT || rc == MDB_SUCCESS)
3352 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3353 if (op == MDB_NEXT_DUP)
3354 return MDB_NOTFOUND;
3358 DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3360 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
3361 DPUTS("=====> move to next sibling page");
3362 if (mdb_cursor_sibling(mc, 1) != MDB_SUCCESS) {
3363 mc->mc_flags |= C_EOF;
3364 mc->mc_flags &= ~C_INITIALIZED;
3365 return MDB_NOTFOUND;
3367 mp = mc->mc_pg[mc->mc_top];
3368 DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3370 mc->mc_ki[mc->mc_top]++;
3372 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3373 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3376 key->mv_size = mc->mc_db->md_pad;
3377 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3381 assert(IS_LEAF(mp));
3382 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3384 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3385 mdb_xcursor_init1(mc, leaf);
3388 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3391 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3392 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3393 if (rc != MDB_SUCCESS)
3398 MDB_SET_KEY(leaf, key);
3402 /** Move the cursor to the previous data item. */
3404 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3410 assert(mc->mc_flags & C_INITIALIZED);
3412 mp = mc->mc_pg[mc->mc_top];
3414 if (mc->mc_db->md_flags & MDB_DUPSORT) {
3415 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3416 if (op == MDB_PREV || op == MDB_PREV_DUP) {
3417 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3418 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
3419 if (op != MDB_PREV || rc == MDB_SUCCESS)
3422 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3423 if (op == MDB_PREV_DUP)
3424 return MDB_NOTFOUND;
3429 DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3431 if (mc->mc_ki[mc->mc_top] == 0) {
3432 DPUTS("=====> move to prev sibling page");
3433 if (mdb_cursor_sibling(mc, 0) != MDB_SUCCESS) {
3434 mc->mc_flags &= ~C_INITIALIZED;
3435 return MDB_NOTFOUND;
3437 mp = mc->mc_pg[mc->mc_top];
3438 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
3439 DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3441 mc->mc_ki[mc->mc_top]--;
3443 mc->mc_flags &= ~C_EOF;
3445 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3446 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3449 key->mv_size = mc->mc_db->md_pad;
3450 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3454 assert(IS_LEAF(mp));
3455 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3457 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3458 mdb_xcursor_init1(mc, leaf);
3461 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3464 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3465 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3466 if (rc != MDB_SUCCESS)
3471 MDB_SET_KEY(leaf, key);
3475 /** Set the cursor on a specific data item. */
3477 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3478 MDB_cursor_op op, int *exactp)
3487 assert(key->mv_size > 0);
3489 /* See if we're already on the right page */
3490 if (mc->mc_flags & C_INITIALIZED) {
3493 mp = mc->mc_pg[mc->mc_top];
3495 mc->mc_ki[mc->mc_top] = 0;
3496 return MDB_NOTFOUND;
3498 if (mp->mp_flags & P_LEAF2) {
3499 nodekey.mv_size = mc->mc_db->md_pad;
3500 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
3502 leaf = NODEPTR(mp, 0);
3503 MDB_SET_KEY(leaf, &nodekey);
3505 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3507 /* Probably happens rarely, but first node on the page
3508 * was the one we wanted.
3510 mc->mc_ki[mc->mc_top] = 0;
3511 leaf = NODEPTR(mp, 0);
3518 unsigned int nkeys = NUMKEYS(mp);
3520 if (mp->mp_flags & P_LEAF2) {
3521 nodekey.mv_data = LEAF2KEY(mp,
3522 nkeys-1, nodekey.mv_size);
3524 leaf = NODEPTR(mp, nkeys-1);
3525 MDB_SET_KEY(leaf, &nodekey);
3527 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3529 /* last node was the one we wanted */
3530 mc->mc_ki[mc->mc_top] = nkeys-1;
3531 leaf = NODEPTR(mp, nkeys-1);
3537 /* This is definitely the right page, skip search_page */
3542 /* If any parents have right-sibs, search.
3543 * Otherwise, there's nothing further.
3545 for (i=0; i<mc->mc_top; i++)
3547 NUMKEYS(mc->mc_pg[i])-1)
3549 if (i == mc->mc_top) {
3550 /* There are no other pages */
3551 mc->mc_ki[mc->mc_top] = nkeys;
3552 return MDB_NOTFOUND;
3556 /* There are no other pages */
3557 mc->mc_ki[mc->mc_top] = 0;
3558 return MDB_NOTFOUND;
3562 rc = mdb_page_search(mc, key, 0);
3563 if (rc != MDB_SUCCESS)
3566 mp = mc->mc_pg[mc->mc_top];
3567 assert(IS_LEAF(mp));
3570 leaf = mdb_node_search(mc, key, exactp);
3571 if (exactp != NULL && !*exactp) {
3572 /* MDB_SET specified and not an exact match. */
3573 return MDB_NOTFOUND;
3577 DPUTS("===> inexact leaf not found, goto sibling");
3578 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
3579 return rc; /* no entries matched */
3580 mp = mc->mc_pg[mc->mc_top];
3581 assert(IS_LEAF(mp));
3582 leaf = NODEPTR(mp, 0);
3586 mc->mc_flags |= C_INITIALIZED;
3587 mc->mc_flags &= ~C_EOF;
3590 key->mv_size = mc->mc_db->md_pad;
3591 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3595 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3596 mdb_xcursor_init1(mc, leaf);
3599 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3600 if (op == MDB_SET || op == MDB_SET_RANGE) {
3601 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3604 if (op == MDB_GET_BOTH) {
3610 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
3611 if (rc != MDB_SUCCESS)
3614 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
3616 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
3618 rc = mc->mc_dbx->md_dcmp(data, &d2);
3620 if (op == MDB_GET_BOTH || rc > 0)
3621 return MDB_NOTFOUND;
3626 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3627 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3632 /* The key already matches in all other cases */
3633 if (op == MDB_SET_RANGE)
3634 MDB_SET_KEY(leaf, key);
3635 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
3640 /** Move the cursor to the first item in the database. */
3642 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3647 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3648 rc = mdb_page_search(mc, NULL, 0);
3649 if (rc != MDB_SUCCESS)
3652 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3654 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
3655 mc->mc_flags |= C_INITIALIZED;
3656 mc->mc_flags &= ~C_EOF;
3658 mc->mc_ki[mc->mc_top] = 0;
3660 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3661 key->mv_size = mc->mc_db->md_pad;
3662 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
3667 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3668 mdb_xcursor_init1(mc, leaf);
3669 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3674 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3675 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3679 MDB_SET_KEY(leaf, key);
3683 /** Move the cursor to the last item in the database. */
3685 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3691 lkey.mv_size = MAXKEYSIZE+1;
3692 lkey.mv_data = NULL;
3694 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3695 rc = mdb_page_search(mc, &lkey, 0);
3696 if (rc != MDB_SUCCESS)
3699 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3701 leaf = NODEPTR(mc->mc_pg[mc->mc_top], NUMKEYS(mc->mc_pg[mc->mc_top])-1);
3702 mc->mc_flags |= C_INITIALIZED;
3703 mc->mc_flags &= ~C_EOF;
3705 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
3707 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3708 key->mv_size = mc->mc_db->md_pad;
3709 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
3714 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3715 mdb_xcursor_init1(mc, leaf);
3716 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3721 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3722 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3727 MDB_SET_KEY(leaf, key);
3732 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3742 case MDB_GET_BOTH_RANGE:
3743 if (data == NULL || mc->mc_xcursor == NULL) {
3750 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3752 } else if (op == MDB_SET_RANGE)
3753 rc = mdb_cursor_set(mc, key, data, op, NULL);
3755 rc = mdb_cursor_set(mc, key, data, op, &exact);
3757 case MDB_GET_MULTIPLE:
3759 !(mc->mc_db->md_flags & MDB_DUPFIXED) ||
3760 !(mc->mc_flags & C_INITIALIZED)) {
3765 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
3766 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
3769 case MDB_NEXT_MULTIPLE:
3771 !(mc->mc_db->md_flags & MDB_DUPFIXED)) {
3775 if (!(mc->mc_flags & C_INITIALIZED))
3776 rc = mdb_cursor_first(mc, key, data);
3778 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
3779 if (rc == MDB_SUCCESS) {
3780 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
3783 mx = &mc->mc_xcursor->mx_cursor;
3784 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
3786 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
3787 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
3795 case MDB_NEXT_NODUP:
3796 if (!(mc->mc_flags & C_INITIALIZED))
3797 rc = mdb_cursor_first(mc, key, data);
3799 rc = mdb_cursor_next(mc, key, data, op);
3803 case MDB_PREV_NODUP:
3804 if (!(mc->mc_flags & C_INITIALIZED) || (mc->mc_flags & C_EOF))
3805 rc = mdb_cursor_last(mc, key, data);
3807 rc = mdb_cursor_prev(mc, key, data, op);
3810 rc = mdb_cursor_first(mc, key, data);
3814 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
3815 !(mc->mc_flags & C_INITIALIZED) ||
3816 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3820 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3823 rc = mdb_cursor_last(mc, key, data);
3827 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
3828 !(mc->mc_flags & C_INITIALIZED) ||
3829 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3833 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3836 DPRINTF("unhandled/unimplemented cursor operation %u", op);
3844 /** Touch all the pages in the cursor stack.
3845 * Makes sure all the pages are writable, before attempting a write operation.
3846 * @param[in] mc The cursor to operate on.
3849 mdb_cursor_touch(MDB_cursor *mc)
3853 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
3855 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
3856 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 1);
3859 *mc->mc_dbflag = DB_DIRTY;
3861 for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
3862 rc = mdb_page_touch(mc);
3866 mc->mc_top = mc->mc_snum-1;
3871 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3874 MDB_node *leaf = NULL;
3875 MDB_val xdata, *rdata, dkey;
3879 unsigned int mcount = 0;
3882 char pbuf[PAGESIZE];
3883 char dbuf[MAXKEYSIZE+1];
3884 unsigned int nflags;
3887 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
3890 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
3891 mc->mc_dbi, DKEY(key), key ? key->mv_size:0, data->mv_size);
3895 if (flags == MDB_CURRENT) {
3896 if (!(mc->mc_flags & C_INITIALIZED))
3899 } else if (mc->mc_db->md_root == P_INVALID) {
3901 /* new database, write a root leaf page */
3902 DPUTS("allocating new root leaf page");
3903 if ((np = mdb_page_new(mc, P_LEAF, 1)) == NULL) {
3907 mdb_cursor_push(mc, np);
3908 mc->mc_db->md_root = np->mp_pgno;
3909 mc->mc_db->md_depth++;
3910 *mc->mc_dbflag = DB_DIRTY;
3911 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
3913 np->mp_flags |= P_LEAF2;
3914 mc->mc_flags |= C_INITIALIZED;
3920 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
3921 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
3922 DPRINTF("duplicate key [%s]", DKEY(key));
3924 return MDB_KEYEXIST;
3926 if (rc && rc != MDB_NOTFOUND)
3930 /* Cursor is positioned, now make sure all pages are writable */
3931 rc2 = mdb_cursor_touch(mc);
3936 /* The key already exists */
3937 if (rc == MDB_SUCCESS) {
3938 /* there's only a key anyway, so this is a no-op */
3939 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3940 unsigned int ksize = mc->mc_db->md_pad;
3941 if (key->mv_size != ksize)
3943 if (flags == MDB_CURRENT) {
3944 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
3945 memcpy(ptr, key->mv_data, ksize);
3950 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3953 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
3954 /* Was a single item before, must convert now */
3956 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3957 /* Just overwrite the current item */
3958 if (flags == MDB_CURRENT)
3961 dkey.mv_size = NODEDSZ(leaf);
3962 dkey.mv_data = NODEDATA(leaf);
3963 /* data matches, ignore it */
3964 if (!mc->mc_dbx->md_dcmp(data, &dkey))
3965 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
3967 /* create a fake page for the dup items */
3968 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
3969 dkey.mv_data = dbuf;
3970 fp = (MDB_page *)pbuf;
3971 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
3972 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
3973 fp->mp_lower = PAGEHDRSZ;
3974 fp->mp_upper = PAGEHDRSZ + dkey.mv_size + data->mv_size;
3975 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
3976 fp->mp_flags |= P_LEAF2;
3977 fp->mp_pad = data->mv_size;
3979 fp->mp_upper += 2 * sizeof(indx_t) + 2 * NODESIZE +
3980 (dkey.mv_size & 1) + (data->mv_size & 1);
3982 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
3985 xdata.mv_size = fp->mp_upper;
3986 xdata.mv_data = pbuf;
3990 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
3991 /* See if we need to convert from fake page to subDB */
3993 unsigned int offset;
3996 fp = NODEDATA(leaf);
3997 if (flags == MDB_CURRENT) {
3998 fp->mp_flags |= P_DIRTY;
3999 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4000 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
4004 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4005 offset = fp->mp_pad;
4007 offset = NODESIZE + sizeof(indx_t) + data->mv_size;
4009 offset += offset & 1;
4010 if (NODESIZE + sizeof(indx_t) + NODEKSZ(leaf) + NODEDSZ(leaf) +
4011 offset >= (mc->mc_txn->mt_env->me_psize - PAGEHDRSZ) /
4013 /* yes, convert it */
4015 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4016 dummy.md_pad = fp->mp_pad;
4017 dummy.md_flags = MDB_DUPFIXED;
4018 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
4019 dummy.md_flags |= MDB_INTEGERKEY;
4022 dummy.md_branch_pages = 0;
4023 dummy.md_leaf_pages = 1;
4024 dummy.md_overflow_pages = 0;
4025 dummy.md_entries = NUMKEYS(fp);
4027 xdata.mv_size = sizeof(MDB_db);
4028 xdata.mv_data = &dummy;
4029 mp = mdb_page_alloc(mc, 1);
4032 offset = mc->mc_txn->mt_env->me_psize - NODEDSZ(leaf);
4033 flags |= F_DUPDATA|F_SUBDATA;
4034 dummy.md_root = mp->mp_pgno;
4036 /* no, just grow it */
4038 xdata.mv_size = NODEDSZ(leaf) + offset;
4039 xdata.mv_data = pbuf;
4040 mp = (MDB_page *)pbuf;
4041 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4044 mp->mp_flags = fp->mp_flags | P_DIRTY;
4045 mp->mp_pad = fp->mp_pad;
4046 mp->mp_lower = fp->mp_lower;
4047 mp->mp_upper = fp->mp_upper + offset;
4049 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
4051 nsize = NODEDSZ(leaf) - fp->mp_upper;
4052 memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper, nsize);
4053 for (i=0; i<NUMKEYS(fp); i++)
4054 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
4056 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4060 /* data is on sub-DB, just store it */
4061 flags |= F_DUPDATA|F_SUBDATA;
4065 /* same size, just replace it */
4066 if (!F_ISSET(leaf->mn_flags, F_BIGDATA) &&
4067 NODEDSZ(leaf) == data->mv_size) {
4068 if (F_ISSET(flags, MDB_RESERVE))
4069 data->mv_data = NODEDATA(leaf);
4071 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
4074 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4076 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
4082 nflags = flags & NODE_ADD_FLAGS;
4083 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
4084 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
4085 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
4086 nflags &= ~MDB_APPEND;
4087 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
4089 /* There is room already in this leaf page. */
4090 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
4091 if (rc == 0 && !do_sub) {
4092 /* Adjust other cursors pointing to mp */
4093 MDB_cursor *m2, *m3;
4094 MDB_dbi dbi = mc->mc_dbi;
4095 unsigned i = mc->mc_top;
4096 MDB_page *mp = mc->mc_pg[i];
4098 if (mc->mc_flags & C_SUB)
4101 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
4102 if (mc->mc_flags & C_SUB)
4103 m3 = &m2->mc_xcursor->mx_cursor;
4106 if (m3 == mc) continue;
4107 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
4114 if (rc != MDB_SUCCESS)
4115 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4117 /* Now store the actual data in the child DB. Note that we're
4118 * storing the user data in the keys field, so there are strict
4119 * size limits on dupdata. The actual data fields of the child
4120 * DB are all zero size.
4128 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4129 if (flags & MDB_CURRENT) {
4130 xflags = MDB_CURRENT;
4132 mdb_xcursor_init1(mc, leaf);
4133 xflags = (flags & MDB_NODUPDATA) ? MDB_NOOVERWRITE : 0;
4135 /* converted, write the original data first */
4137 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
4141 /* Adjust other cursors pointing to mp */
4143 unsigned i = mc->mc_top;
4144 MDB_page *mp = mc->mc_pg[i];
4146 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4147 if (m2 == mc) continue;
4148 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
4149 mdb_xcursor_init1(m2, leaf);
4154 xflags |= (flags & MDB_APPEND);
4155 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
4156 if (flags & F_SUBDATA) {
4157 db = NODEDATA(leaf);
4158 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4161 /* sub-writes might have failed so check rc again.
4162 * Don't increment count if we just replaced an existing item.
4164 if (!rc && !(flags & MDB_CURRENT))
4165 mc->mc_db->md_entries++;
4166 if (flags & MDB_MULTIPLE) {
4168 if (mcount < data[1].mv_size) {
4169 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
4170 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4180 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
4185 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
4188 if (!mc->mc_flags & C_INITIALIZED)
4191 rc = mdb_cursor_touch(mc);
4195 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4197 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4198 if (flags != MDB_NODUPDATA) {
4199 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
4200 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
4202 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
4203 /* If sub-DB still has entries, we're done */
4204 if (mc->mc_xcursor->mx_db.md_entries) {
4205 if (leaf->mn_flags & F_SUBDATA) {
4206 /* update subDB info */
4207 MDB_db *db = NODEDATA(leaf);
4208 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4210 /* shrink fake page */
4211 mdb_node_shrink(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4213 mc->mc_db->md_entries--;
4216 /* otherwise fall thru and delete the sub-DB */
4219 if (leaf->mn_flags & F_SUBDATA) {
4220 /* add all the child DB's pages to the free list */
4221 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
4222 if (rc == MDB_SUCCESS) {
4223 mc->mc_db->md_entries -=
4224 mc->mc_xcursor->mx_db.md_entries;
4229 return mdb_cursor_del0(mc, leaf);
4232 /** Allocate and initialize new pages for a database.
4233 * @param[in] mc a cursor on the database being added to.
4234 * @param[in] flags flags defining what type of page is being allocated.
4235 * @param[in] num the number of pages to allocate. This is usually 1,
4236 * unless allocating overflow pages for a large record.
4237 * @return Address of a page, or NULL on failure.
4240 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num)
4244 if ((np = mdb_page_alloc(mc, num)) == NULL)
4246 DPRINTF("allocated new mpage %zu, page size %u",
4247 np->mp_pgno, mc->mc_txn->mt_env->me_psize);
4248 np->mp_flags = flags | P_DIRTY;
4249 np->mp_lower = PAGEHDRSZ;
4250 np->mp_upper = mc->mc_txn->mt_env->me_psize;
4253 mc->mc_db->md_branch_pages++;
4254 else if (IS_LEAF(np))
4255 mc->mc_db->md_leaf_pages++;
4256 else if (IS_OVERFLOW(np)) {
4257 mc->mc_db->md_overflow_pages += num;
4264 /** Calculate the size of a leaf node.
4265 * The size depends on the environment's page size; if a data item
4266 * is too large it will be put onto an overflow page and the node
4267 * size will only include the key and not the data. Sizes are always
4268 * rounded up to an even number of bytes, to guarantee 2-byte alignment
4269 * of the #MDB_node headers.
4270 * @param[in] env The environment handle.
4271 * @param[in] key The key for the node.
4272 * @param[in] data The data for the node.
4273 * @return The number of bytes needed to store the node.
4276 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
4280 sz = LEAFSIZE(key, data);
4281 if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
4282 /* put on overflow page */
4283 sz -= data->mv_size - sizeof(pgno_t);
4287 return sz + sizeof(indx_t);
4290 /** Calculate the size of a branch node.
4291 * The size should depend on the environment's page size but since
4292 * we currently don't support spilling large keys onto overflow
4293 * pages, it's simply the size of the #MDB_node header plus the
4294 * size of the key. Sizes are always rounded up to an even number
4295 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
4296 * @param[in] env The environment handle.
4297 * @param[in] key The key for the node.
4298 * @return The number of bytes needed to store the node.
4301 mdb_branch_size(MDB_env *env, MDB_val *key)
4306 if (sz >= env->me_psize / MDB_MINKEYS) {
4307 /* put on overflow page */
4308 /* not implemented */
4309 /* sz -= key->size - sizeof(pgno_t); */
4312 return sz + sizeof(indx_t);
4315 /** Add a node to the page pointed to by the cursor.
4316 * @param[in] mc The cursor for this operation.
4317 * @param[in] indx The index on the page where the new node should be added.
4318 * @param[in] key The key for the new node.
4319 * @param[in] data The data for the new node, if any.
4320 * @param[in] pgno The page number, if adding a branch node.
4321 * @param[in] flags Flags for the node.
4322 * @return 0 on success, non-zero on failure. Possible errors are:
4324 * <li>ENOMEM - failed to allocate overflow pages for the node.
4325 * <li>ENOSPC - there is insufficient room in the page. This error
4326 * should never happen since all callers already calculate the
4327 * page's free space before calling this function.
4331 mdb_node_add(MDB_cursor *mc, indx_t indx,
4332 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
4335 size_t node_size = NODESIZE;
4338 MDB_page *mp = mc->mc_pg[mc->mc_top];
4339 MDB_page *ofp = NULL; /* overflow page */
4342 assert(mp->mp_upper >= mp->mp_lower);
4344 DPRINTF("add to %s %spage %zu index %i, data size %zu key size %zu [%s]",
4345 IS_LEAF(mp) ? "leaf" : "branch",
4346 IS_SUBP(mp) ? "sub-" : "",
4347 mp->mp_pgno, indx, data ? data->mv_size : 0,
4348 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
4351 /* Move higher keys up one slot. */
4352 int ksize = mc->mc_db->md_pad, dif;
4353 char *ptr = LEAF2KEY(mp, indx, ksize);
4354 dif = NUMKEYS(mp) - indx;
4356 memmove(ptr+ksize, ptr, dif*ksize);
4357 /* insert new key */
4358 memcpy(ptr, key->mv_data, ksize);
4360 /* Just using these for counting */
4361 mp->mp_lower += sizeof(indx_t);
4362 mp->mp_upper -= ksize - sizeof(indx_t);
4367 node_size += key->mv_size;
4371 if (F_ISSET(flags, F_BIGDATA)) {
4372 /* Data already on overflow page. */
4373 node_size += sizeof(pgno_t);
4374 } else if (data->mv_size >= mc->mc_txn->mt_env->me_psize / MDB_MINKEYS) {
4375 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
4376 /* Put data on overflow page. */
4377 DPRINTF("data size is %zu, put on overflow page",
4379 node_size += sizeof(pgno_t);
4380 if ((ofp = mdb_page_new(mc, P_OVERFLOW, ovpages)) == NULL)
4382 DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
4385 node_size += data->mv_size;
4388 node_size += node_size & 1;
4390 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
4391 DPRINTF("not enough room in page %zu, got %u ptrs",
4392 mp->mp_pgno, NUMKEYS(mp));
4393 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
4394 mp->mp_upper - mp->mp_lower);
4395 DPRINTF("node size = %zu", node_size);
4399 /* Move higher pointers up one slot. */
4400 for (i = NUMKEYS(mp); i > indx; i--)
4401 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
4403 /* Adjust free space offsets. */
4404 ofs = mp->mp_upper - node_size;
4405 assert(ofs >= mp->mp_lower + sizeof(indx_t));
4406 mp->mp_ptrs[indx] = ofs;
4408 mp->mp_lower += sizeof(indx_t);
4410 /* Write the node data. */
4411 node = NODEPTR(mp, indx);
4412 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
4413 node->mn_flags = flags;
4415 SETDSZ(node,data->mv_size);
4420 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
4425 if (F_ISSET(flags, F_BIGDATA))
4426 memcpy(node->mn_data + key->mv_size, data->mv_data,
4428 else if (F_ISSET(flags, MDB_RESERVE))
4429 data->mv_data = node->mn_data + key->mv_size;
4431 memcpy(node->mn_data + key->mv_size, data->mv_data,
4434 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
4436 if (F_ISSET(flags, MDB_RESERVE))
4437 data->mv_data = METADATA(ofp);
4439 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
4446 /** Delete the specified node from a page.
4447 * @param[in] mp The page to operate on.
4448 * @param[in] indx The index of the node to delete.
4449 * @param[in] ksize The size of a node. Only used if the page is
4450 * part of a #MDB_DUPFIXED database.
4453 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
4456 indx_t i, j, numkeys, ptr;
4460 DPRINTF("delete node %u on %s page %zu", indx,
4461 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
4462 assert(indx < NUMKEYS(mp));
4465 int x = NUMKEYS(mp) - 1 - indx;
4466 base = LEAF2KEY(mp, indx, ksize);
4468 memmove(base, base + ksize, x * ksize);
4469 mp->mp_lower -= sizeof(indx_t);
4470 mp->mp_upper += ksize - sizeof(indx_t);
4474 node = NODEPTR(mp, indx);
4475 sz = NODESIZE + node->mn_ksize;
4477 if (F_ISSET(node->mn_flags, F_BIGDATA))
4478 sz += sizeof(pgno_t);
4480 sz += NODEDSZ(node);
4484 ptr = mp->mp_ptrs[indx];
4485 numkeys = NUMKEYS(mp);
4486 for (i = j = 0; i < numkeys; i++) {
4488 mp->mp_ptrs[j] = mp->mp_ptrs[i];
4489 if (mp->mp_ptrs[i] < ptr)
4490 mp->mp_ptrs[j] += sz;
4495 base = (char *)mp + mp->mp_upper;
4496 memmove(base + sz, base, ptr - mp->mp_upper);
4498 mp->mp_lower -= sizeof(indx_t);
4502 /** Compact the main page after deleting a node on a subpage.
4503 * @param[in] mp The main page to operate on.
4504 * @param[in] indx The index of the subpage on the main page.
4507 mdb_node_shrink(MDB_page *mp, indx_t indx)
4514 indx_t i, numkeys, ptr;
4516 node = NODEPTR(mp, indx);
4517 sp = (MDB_page *)NODEDATA(node);
4518 osize = NODEDSZ(node);
4520 delta = sp->mp_upper - sp->mp_lower;
4521 SETDSZ(node, osize - delta);
4522 xp = (MDB_page *)((char *)sp + delta);
4524 /* shift subpage upward */
4526 nsize = NUMKEYS(sp) * sp->mp_pad;
4527 memmove(METADATA(xp), METADATA(sp), nsize);
4530 nsize = osize - sp->mp_upper;
4531 numkeys = NUMKEYS(sp);
4532 for (i=numkeys-1; i>=0; i--)
4533 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
4535 xp->mp_upper = sp->mp_lower;
4536 xp->mp_lower = sp->mp_lower;
4537 xp->mp_flags = sp->mp_flags;
4538 xp->mp_pad = sp->mp_pad;
4539 xp->mp_pgno = mp->mp_pgno;
4541 /* shift lower nodes upward */
4542 ptr = mp->mp_ptrs[indx];
4543 numkeys = NUMKEYS(mp);
4544 for (i = 0; i < numkeys; i++) {
4545 if (mp->mp_ptrs[i] <= ptr)
4546 mp->mp_ptrs[i] += delta;
4549 base = (char *)mp + mp->mp_upper;
4550 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
4551 mp->mp_upper += delta;
4554 /** Initial setup of a sorted-dups cursor.
4555 * Sorted duplicates are implemented as a sub-database for the given key.
4556 * The duplicate data items are actually keys of the sub-database.
4557 * Operations on the duplicate data items are performed using a sub-cursor
4558 * initialized when the sub-database is first accessed. This function does
4559 * the preliminary setup of the sub-cursor, filling in the fields that
4560 * depend only on the parent DB.
4561 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4564 mdb_xcursor_init0(MDB_cursor *mc)
4566 MDB_xcursor *mx = mc->mc_xcursor;
4568 mx->mx_cursor.mc_xcursor = NULL;
4569 mx->mx_cursor.mc_txn = mc->mc_txn;
4570 mx->mx_cursor.mc_db = &mx->mx_db;
4571 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
4572 mx->mx_cursor.mc_dbi = mc->mc_dbi+1;
4573 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
4574 mx->mx_cursor.mc_snum = 0;
4575 mx->mx_cursor.mc_flags = C_SUB;
4576 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
4577 mx->mx_dbx.md_dcmp = NULL;
4578 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
4581 /** Final setup of a sorted-dups cursor.
4582 * Sets up the fields that depend on the data from the main cursor.
4583 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4584 * @param[in] node The data containing the #MDB_db record for the
4585 * sorted-dup database.
4588 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
4590 MDB_xcursor *mx = mc->mc_xcursor;
4592 if (node->mn_flags & F_SUBDATA) {
4593 MDB_db *db = NODEDATA(node);
4595 mx->mx_cursor.mc_snum = 0;
4596 mx->mx_cursor.mc_flags = C_SUB;
4598 MDB_page *fp = NODEDATA(node);
4599 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
4600 mx->mx_db.md_flags = 0;
4601 mx->mx_db.md_depth = 1;
4602 mx->mx_db.md_branch_pages = 0;
4603 mx->mx_db.md_leaf_pages = 1;
4604 mx->mx_db.md_overflow_pages = 0;
4605 mx->mx_db.md_entries = NUMKEYS(fp);
4606 mx->mx_db.md_root = fp->mp_pgno;
4607 mx->mx_cursor.mc_snum = 1;
4608 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
4609 mx->mx_cursor.mc_top = 0;
4610 mx->mx_cursor.mc_pg[0] = fp;
4611 mx->mx_cursor.mc_ki[0] = 0;
4612 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4613 mx->mx_db.md_flags = MDB_DUPFIXED;
4614 mx->mx_db.md_pad = fp->mp_pad;
4615 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
4616 mx->mx_db.md_flags |= MDB_INTEGERKEY;
4619 DPRINTF("Sub-db %u for db %u root page %zu", mx->mx_cursor.mc_dbi, mc->mc_dbi,
4621 mx->mx_dbflag = (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY)) ?
4623 mx->mx_dbx.md_name.mv_data = NODEKEY(node);
4624 mx->mx_dbx.md_name.mv_size = node->mn_ksize;
4625 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
4626 mx->mx_dbx.md_cmp = mdb_cmp_long;
4629 /** Initialize a cursor for a given transaction and database. */
4631 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
4636 mc->mc_db = &txn->mt_dbs[dbi];
4637 mc->mc_dbx = &txn->mt_dbxs[dbi];
4638 mc->mc_dbflag = &txn->mt_dbflags[dbi];
4641 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4643 mc->mc_xcursor = mx;
4644 mdb_xcursor_init0(mc);
4646 mc->mc_xcursor = NULL;
4651 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
4654 MDB_xcursor *mx = NULL;
4655 size_t size = sizeof(MDB_cursor);
4657 if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
4660 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
4661 size += sizeof(MDB_xcursor);
4663 if ((mc = malloc(size)) != NULL) {
4664 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4665 mx = (MDB_xcursor *)(mc + 1);
4667 mdb_cursor_init(mc, txn, dbi, mx);
4668 if (txn->mt_cursors) {
4669 mc->mc_next = txn->mt_cursors[dbi];
4670 txn->mt_cursors[dbi] = mc;
4672 mc->mc_flags |= C_ALLOCD;
4682 /* Return the count of duplicate data items for the current key */
4684 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
4688 if (mc == NULL || countp == NULL)
4691 if (!(mc->mc_db->md_flags & MDB_DUPSORT))
4694 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4695 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4698 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
4701 *countp = mc->mc_xcursor->mx_db.md_entries;
4707 mdb_cursor_close(MDB_cursor *mc)
4710 /* remove from txn, if tracked */
4711 if (mc->mc_txn->mt_cursors) {
4712 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
4713 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
4715 *prev = mc->mc_next;
4717 if (mc->mc_flags & C_ALLOCD)
4723 mdb_cursor_txn(MDB_cursor *mc)
4725 if (!mc) return NULL;
4730 mdb_cursor_dbi(MDB_cursor *mc)
4736 /** Replace the key for a node with a new key.
4737 * @param[in] mp The page containing the node to operate on.
4738 * @param[in] indx The index of the node to operate on.
4739 * @param[in] key The new key to use.
4740 * @return 0 on success, non-zero on failure.
4743 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
4745 indx_t ptr, i, numkeys;
4752 node = NODEPTR(mp, indx);
4753 ptr = mp->mp_ptrs[indx];
4754 DPRINTF("update key %u (ofs %u) [%.*s] to [%s] on page %zu",
4756 (int)node->mn_ksize, (char *)NODEKEY(node),
4760 delta = key->mv_size - node->mn_ksize;
4762 if (delta > 0 && SIZELEFT(mp) < delta) {
4763 DPRINTF("OUCH! Not enough room, delta = %d", delta);
4767 numkeys = NUMKEYS(mp);
4768 for (i = 0; i < numkeys; i++) {
4769 if (mp->mp_ptrs[i] <= ptr)
4770 mp->mp_ptrs[i] -= delta;
4773 base = (char *)mp + mp->mp_upper;
4774 len = ptr - mp->mp_upper + NODESIZE;
4775 memmove(base - delta, base, len);
4776 mp->mp_upper -= delta;
4778 node = NODEPTR(mp, indx);
4779 node->mn_ksize = key->mv_size;
4782 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
4787 /** Move a node from csrc to cdst.
4790 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
4797 /* Mark src and dst as dirty. */
4798 if ((rc = mdb_page_touch(csrc)) ||
4799 (rc = mdb_page_touch(cdst)))
4802 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4803 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
4804 key.mv_size = csrc->mc_db->md_pad;
4805 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
4807 data.mv_data = NULL;
4809 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
4810 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
4811 unsigned int snum = csrc->mc_snum;
4813 /* must find the lowest key below src */
4814 mdb_page_search_root(csrc, NULL, 0);
4815 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
4816 key.mv_size = NODEKSZ(s2);
4817 key.mv_data = NODEKEY(s2);
4818 csrc->mc_snum = snum--;
4819 csrc->mc_top = snum;
4821 key.mv_size = NODEKSZ(srcnode);
4822 key.mv_data = NODEKEY(srcnode);
4824 data.mv_size = NODEDSZ(srcnode);
4825 data.mv_data = NODEDATA(srcnode);
4827 DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
4828 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
4829 csrc->mc_ki[csrc->mc_top],
4831 csrc->mc_pg[csrc->mc_top]->mp_pgno,
4832 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
4834 /* Add the node to the destination page.
4836 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, NODEPGNO(srcnode),
4838 if (rc != MDB_SUCCESS)
4841 /* Delete the node from the source page.
4843 mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
4846 /* Adjust other cursors pointing to mp */
4847 MDB_cursor *m2, *m3;
4848 MDB_dbi dbi = csrc->mc_dbi;
4849 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
4851 if (csrc->mc_flags & C_SUB)
4854 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
4855 if (m2 == csrc) continue;
4856 if (csrc->mc_flags & C_SUB)
4857 m3 = &m2->mc_xcursor->mx_cursor;
4860 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
4861 csrc->mc_ki[csrc->mc_top]) {
4862 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
4863 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
4868 /* Update the parent separators.
4870 if (csrc->mc_ki[csrc->mc_top] == 0) {
4871 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
4872 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4873 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
4875 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
4876 key.mv_size = NODEKSZ(srcnode);
4877 key.mv_data = NODEKEY(srcnode);
4879 DPRINTF("update separator for source page %zu to [%s]",
4880 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
4881 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1],
4882 &key)) != MDB_SUCCESS)
4885 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
4887 nullkey.mv_size = 0;
4888 rc = mdb_update_key(csrc->mc_pg[csrc->mc_top], 0, &nullkey);
4889 assert(rc == MDB_SUCCESS);
4893 if (cdst->mc_ki[cdst->mc_top] == 0) {
4894 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
4895 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4896 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
4898 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
4899 key.mv_size = NODEKSZ(srcnode);
4900 key.mv_data = NODEKEY(srcnode);
4902 DPRINTF("update separator for destination page %zu to [%s]",
4903 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
4904 if ((rc = mdb_update_key(cdst->mc_pg[cdst->mc_top-1], cdst->mc_ki[cdst->mc_top-1],
4905 &key)) != MDB_SUCCESS)
4908 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
4910 nullkey.mv_size = 0;
4911 rc = mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &nullkey);
4912 assert(rc == MDB_SUCCESS);
4919 /** Merge one page into another.
4920 * The nodes from the page pointed to by \b csrc will
4921 * be copied to the page pointed to by \b cdst and then
4922 * the \b csrc page will be freed.
4923 * @param[in] csrc Cursor pointing to the source page.
4924 * @param[in] cdst Cursor pointing to the destination page.
4927 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
4935 DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
4936 cdst->mc_pg[cdst->mc_top]->mp_pgno);
4938 assert(csrc->mc_snum > 1); /* can't merge root page */
4939 assert(cdst->mc_snum > 1);
4941 /* Mark dst as dirty. */
4942 if ((rc = mdb_page_touch(cdst)))
4945 /* Move all nodes from src to dst.
4947 j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
4948 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4949 key.mv_size = csrc->mc_db->md_pad;
4950 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
4951 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
4952 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
4953 if (rc != MDB_SUCCESS)
4955 key.mv_data = (char *)key.mv_data + key.mv_size;
4958 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
4959 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
4961 key.mv_size = srcnode->mn_ksize;
4962 key.mv_data = NODEKEY(srcnode);
4963 data.mv_size = NODEDSZ(srcnode);
4964 data.mv_data = NODEDATA(srcnode);
4965 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
4966 if (rc != MDB_SUCCESS)
4971 DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
4972 cdst->mc_pg[cdst->mc_top]->mp_pgno, NUMKEYS(cdst->mc_pg[cdst->mc_top]), (float)PAGEFILL(cdst->mc_txn->mt_env, cdst->mc_pg[cdst->mc_top]) / 10);
4974 /* Unlink the src page from parent and add to free list.
4976 mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
4977 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
4979 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], 0, &key)) != MDB_SUCCESS)
4983 mdb_midl_append(&csrc->mc_txn->mt_free_pgs, csrc->mc_pg[csrc->mc_top]->mp_pgno);
4984 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
4985 csrc->mc_db->md_leaf_pages--;
4987 csrc->mc_db->md_branch_pages--;
4989 /* Adjust other cursors pointing to mp */
4990 MDB_cursor *m2, *m3;
4991 MDB_dbi dbi = csrc->mc_dbi;
4992 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
4994 if (csrc->mc_flags & C_SUB)
4997 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
4998 if (m2 == csrc) continue;
4999 if (csrc->mc_flags & C_SUB)
5000 m3 = &m2->mc_xcursor->mx_cursor;
5003 if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
5004 m3->mc_pg[csrc->mc_top] = mp;
5005 m3->mc_ki[csrc->mc_top] += nkeys;
5009 mdb_cursor_pop(csrc);
5011 return mdb_rebalance(csrc);
5014 /** Copy the contents of a cursor.
5015 * @param[in] csrc The cursor to copy from.
5016 * @param[out] cdst The cursor to copy to.
5019 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
5023 cdst->mc_txn = csrc->mc_txn;
5024 cdst->mc_dbi = csrc->mc_dbi;
5025 cdst->mc_db = csrc->mc_db;
5026 cdst->mc_dbx = csrc->mc_dbx;
5027 cdst->mc_snum = csrc->mc_snum;
5028 cdst->mc_top = csrc->mc_top;
5029 cdst->mc_flags = csrc->mc_flags;
5031 for (i=0; i<csrc->mc_snum; i++) {
5032 cdst->mc_pg[i] = csrc->mc_pg[i];
5033 cdst->mc_ki[i] = csrc->mc_ki[i];
5037 /** Rebalance the tree after a delete operation.
5038 * @param[in] mc Cursor pointing to the page where rebalancing
5040 * @return 0 on success, non-zero on failure.
5043 mdb_rebalance(MDB_cursor *mc)
5050 DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
5051 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
5052 mc->mc_pg[mc->mc_top]->mp_pgno, NUMKEYS(mc->mc_pg[mc->mc_top]), (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10);
5054 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD) {
5055 DPRINTF("no need to rebalance page %zu, above fill threshold",
5056 mc->mc_pg[mc->mc_top]->mp_pgno);
5060 if (mc->mc_snum < 2) {
5061 MDB_page *mp = mc->mc_pg[0];
5062 if (NUMKEYS(mp) == 0) {
5063 DPUTS("tree is completely empty");
5064 mc->mc_db->md_root = P_INVALID;
5065 mc->mc_db->md_depth = 0;
5066 mc->mc_db->md_leaf_pages = 0;
5067 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5071 /* Adjust other cursors pointing to mp */
5072 MDB_cursor *m2, *m3;
5073 MDB_dbi dbi = mc->mc_dbi;
5075 if (mc->mc_flags & C_SUB)
5078 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5079 if (m2 == mc) continue;
5080 if (mc->mc_flags & C_SUB)
5081 m3 = &m2->mc_xcursor->mx_cursor;
5084 if (m3->mc_pg[0] == mp) {
5090 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
5091 DPUTS("collapsing root page!");
5092 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5093 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
5094 if ((rc = mdb_page_get(mc->mc_txn, mc->mc_db->md_root,
5097 mc->mc_db->md_depth--;
5098 mc->mc_db->md_branch_pages--;
5100 /* Adjust other cursors pointing to mp */
5101 MDB_cursor *m2, *m3;
5102 MDB_dbi dbi = mc->mc_dbi;
5104 if (mc->mc_flags & C_SUB)
5107 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5108 if (m2 == mc) continue;
5109 if (mc->mc_flags & C_SUB)
5110 m3 = &m2->mc_xcursor->mx_cursor;
5113 if (m3->mc_pg[0] == mp) {
5114 m3->mc_pg[0] = mc->mc_pg[0];
5119 DPUTS("root page doesn't need rebalancing");
5123 /* The parent (branch page) must have at least 2 pointers,
5124 * otherwise the tree is invalid.
5126 ptop = mc->mc_top-1;
5127 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
5129 /* Leaf page fill factor is below the threshold.
5130 * Try to move keys from left or right neighbor, or
5131 * merge with a neighbor page.
5136 mdb_cursor_copy(mc, &mn);
5137 mn.mc_xcursor = NULL;
5139 if (mc->mc_ki[ptop] == 0) {
5140 /* We're the leftmost leaf in our parent.
5142 DPUTS("reading right neighbor");
5144 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5145 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5147 mn.mc_ki[mn.mc_top] = 0;
5148 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
5150 /* There is at least one neighbor to the left.
5152 DPUTS("reading left neighbor");
5154 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5155 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5157 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
5158 mc->mc_ki[mc->mc_top] = 0;
5161 DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
5162 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]), (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10);
5164 /* If the neighbor page is above threshold and has at least two
5165 * keys, move one key from it.
5167 * Otherwise we should try to merge them.
5169 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) >= 2)
5170 return mdb_node_move(&mn, mc);
5171 else { /* FIXME: if (has_enough_room()) */
5172 mc->mc_flags &= ~C_INITIALIZED;
5173 if (mc->mc_ki[ptop] == 0)
5174 return mdb_page_merge(&mn, mc);
5176 return mdb_page_merge(mc, &mn);
5180 /** Complete a delete operation started by #mdb_cursor_del(). */
5182 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
5186 /* add overflow pages to free list */
5187 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5191 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
5192 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
5193 for (i=0; i<ovpages; i++) {
5194 DPRINTF("freed ov page %zu", pg);
5195 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
5199 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], mc->mc_db->md_pad);
5200 mc->mc_db->md_entries--;
5201 rc = mdb_rebalance(mc);
5202 if (rc != MDB_SUCCESS)
5203 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5209 mdb_del(MDB_txn *txn, MDB_dbi dbi,
5210 MDB_val *key, MDB_val *data)
5215 MDB_val rdata, *xdata;
5219 assert(key != NULL);
5221 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
5223 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5226 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
5230 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
5234 mdb_cursor_init(&mc, txn, dbi, &mx);
5245 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
5247 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
5251 /** Split a page and insert a new node.
5252 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
5253 * The cursor will be updated to point to the actual page and index where
5254 * the node got inserted after the split.
5255 * @param[in] newkey The key for the newly inserted node.
5256 * @param[in] newdata The data for the newly inserted node.
5257 * @param[in] newpgno The page number, if the new node is a branch node.
5258 * @return 0 on success, non-zero on failure.
5261 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
5262 unsigned int nflags)
5265 int rc = MDB_SUCCESS, ins_new = 0, new_root = 0;
5268 unsigned int i, j, split_indx, nkeys, pmax;
5270 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
5272 MDB_page *mp, *rp, *pp;
5277 mp = mc->mc_pg[mc->mc_top];
5278 newindx = mc->mc_ki[mc->mc_top];
5280 DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
5281 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
5282 DKEY(newkey), mc->mc_ki[mc->mc_top]);
5284 if (mc->mc_snum < 2) {
5285 if ((pp = mdb_page_new(mc, P_BRANCH, 1)) == NULL)
5287 /* shift current top to make room for new parent */
5288 mc->mc_pg[1] = mc->mc_pg[0];
5289 mc->mc_ki[1] = mc->mc_ki[0];
5292 mc->mc_db->md_root = pp->mp_pgno;
5293 DPRINTF("root split! new root = %zu", pp->mp_pgno);
5294 mc->mc_db->md_depth++;
5297 /* Add left (implicit) pointer. */
5298 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
5299 /* undo the pre-push */
5300 mc->mc_pg[0] = mc->mc_pg[1];
5301 mc->mc_ki[0] = mc->mc_ki[1];
5302 mc->mc_db->md_root = mp->mp_pgno;
5303 mc->mc_db->md_depth--;
5310 ptop = mc->mc_top-1;
5311 DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
5314 /* Create a right sibling. */
5315 if ((rp = mdb_page_new(mc, mp->mp_flags, 1)) == NULL)
5317 DPRINTF("new right sibling: page %zu", rp->mp_pgno);
5319 mdb_cursor_copy(mc, &mn);
5320 mn.mc_pg[mn.mc_top] = rp;
5321 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
5323 if (nflags & MDB_APPEND) {
5324 mn.mc_ki[mn.mc_top] = 0;
5331 nkeys = NUMKEYS(mp);
5332 split_indx = nkeys / 2 + 1;
5337 unsigned int lsize, rsize, ksize;
5338 /* Move half of the keys to the right sibling */
5340 x = mc->mc_ki[mc->mc_top] - split_indx;
5341 ksize = mc->mc_db->md_pad;
5342 split = LEAF2KEY(mp, split_indx, ksize);
5343 rsize = (nkeys - split_indx) * ksize;
5344 lsize = (nkeys - split_indx) * sizeof(indx_t);
5345 mp->mp_lower -= lsize;
5346 rp->mp_lower += lsize;
5347 mp->mp_upper += rsize - lsize;
5348 rp->mp_upper -= rsize - lsize;
5349 sepkey.mv_size = ksize;
5350 if (newindx == split_indx) {
5351 sepkey.mv_data = newkey->mv_data;
5353 sepkey.mv_data = split;
5356 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
5357 memcpy(rp->mp_ptrs, split, rsize);
5358 sepkey.mv_data = rp->mp_ptrs;
5359 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
5360 memcpy(ins, newkey->mv_data, ksize);
5361 mp->mp_lower += sizeof(indx_t);
5362 mp->mp_upper -= ksize - sizeof(indx_t);
5365 memcpy(rp->mp_ptrs, split, x * ksize);
5366 ins = LEAF2KEY(rp, x, ksize);
5367 memcpy(ins, newkey->mv_data, ksize);
5368 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
5369 rp->mp_lower += sizeof(indx_t);
5370 rp->mp_upper -= ksize - sizeof(indx_t);
5371 mc->mc_ki[mc->mc_top] = x;
5372 mc->mc_pg[mc->mc_top] = rp;
5377 /* For leaf pages, check the split point based on what
5378 * fits where, since otherwise add_node can fail.
5381 unsigned int psize, nsize;
5382 /* Maximum free space in an empty page */
5383 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
5384 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
5385 if (newindx < split_indx) {
5387 for (i=0; i<split_indx; i++) {
5388 node = NODEPTR(mp, i);
5389 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
5390 if (F_ISSET(node->mn_flags, F_BIGDATA))
5391 psize += sizeof(pgno_t);
5393 psize += NODEDSZ(node);
5402 for (i=nkeys-1; i>=split_indx; i--) {
5403 node = NODEPTR(mp, i);
5404 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
5405 if (F_ISSET(node->mn_flags, F_BIGDATA))
5406 psize += sizeof(pgno_t);
5408 psize += NODEDSZ(node);
5418 /* First find the separating key between the split pages.
5420 if (newindx == split_indx) {
5421 sepkey.mv_size = newkey->mv_size;
5422 sepkey.mv_data = newkey->mv_data;
5424 node = NODEPTR(mp, split_indx);
5425 sepkey.mv_size = node->mn_ksize;
5426 sepkey.mv_data = NODEKEY(node);
5430 DPRINTF("separator is [%s]", DKEY(&sepkey));
5432 /* Copy separator key to the parent.
5434 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
5437 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
5439 /* Right page might now have changed parent.
5440 * Check if left page also changed parent.
5442 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
5443 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
5444 mc->mc_pg[ptop] = mn.mc_pg[ptop];
5445 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
5449 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
5452 if (rc != MDB_SUCCESS) {
5455 if (nflags & MDB_APPEND) {
5456 mc->mc_pg[mc->mc_top] = rp;
5457 mc->mc_ki[mc->mc_top] = 0;
5458 return mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
5464 /* Move half of the keys to the right sibling. */
5466 /* grab a page to hold a temporary copy */
5467 copy = mdb_page_malloc(mc);
5471 copy->mp_pgno = mp->mp_pgno;
5472 copy->mp_flags = mp->mp_flags;
5473 copy->mp_lower = PAGEHDRSZ;
5474 copy->mp_upper = mc->mc_txn->mt_env->me_psize;
5475 mc->mc_pg[mc->mc_top] = copy;
5476 for (i = j = 0; i <= nkeys; j++) {
5477 if (i == split_indx) {
5478 /* Insert in right sibling. */
5479 /* Reset insert index for right sibling. */
5480 j = (i == newindx && ins_new);
5481 mc->mc_pg[mc->mc_top] = rp;
5484 if (i == newindx && !ins_new) {
5485 /* Insert the original entry that caused the split. */
5486 rkey.mv_data = newkey->mv_data;
5487 rkey.mv_size = newkey->mv_size;
5496 /* Update page and index for the new key. */
5497 mc->mc_ki[mc->mc_top] = j;
5498 } else if (i == nkeys) {
5501 node = NODEPTR(mp, i);
5502 rkey.mv_data = NODEKEY(node);
5503 rkey.mv_size = node->mn_ksize;
5505 xdata.mv_data = NODEDATA(node);
5506 xdata.mv_size = NODEDSZ(node);
5509 pgno = NODEPGNO(node);
5510 flags = node->mn_flags;
5515 if (!IS_LEAF(mp) && j == 0) {
5516 /* First branch index doesn't need key data. */
5520 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
5523 nkeys = NUMKEYS(copy);
5524 for (i=0; i<nkeys; i++)
5525 mp->mp_ptrs[i] = copy->mp_ptrs[i];
5526 mp->mp_lower = copy->mp_lower;
5527 mp->mp_upper = copy->mp_upper;
5528 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
5529 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
5531 /* reset back to original page */
5532 if (newindx < split_indx) {
5533 mc->mc_pg[mc->mc_top] = mp;
5534 if (nflags & MDB_RESERVE) {
5535 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5536 if (!(node->mn_flags & F_BIGDATA))
5537 newdata->mv_data = NODEDATA(node);
5541 /* return tmp page to freelist */
5542 copy->mp_next = mc->mc_txn->mt_env->me_dpages;
5543 mc->mc_txn->mt_env->me_dpages = copy;
5546 /* Adjust other cursors pointing to mp */
5547 MDB_cursor *m2, *m3;
5548 MDB_dbi dbi = mc->mc_dbi;
5550 if (mc->mc_flags & C_SUB)
5553 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5554 if (m2 == mc) continue;
5555 if (mc->mc_flags & C_SUB)
5556 m3 = &m2->mc_xcursor->mx_cursor;
5559 if (!(m3->mc_flags & C_INITIALIZED))
5563 for (i=m3->mc_top; i>0; i--) {
5564 m3->mc_ki[i+1] = m3->mc_ki[i];
5565 m3->mc_pg[i+1] = m3->mc_pg[i];
5567 m3->mc_ki[0] = mc->mc_ki[0];
5568 m3->mc_pg[0] = mc->mc_pg[0];
5572 if (m3->mc_pg[mc->mc_top] == mp) {
5573 if (m3->mc_ki[m3->mc_top] >= split_indx) {
5574 m3->mc_pg[m3->mc_top] = rp;
5575 m3->mc_ki[m3->mc_top] -= split_indx;
5584 mdb_put(MDB_txn *txn, MDB_dbi dbi,
5585 MDB_val *key, MDB_val *data, unsigned int flags)
5590 assert(key != NULL);
5591 assert(data != NULL);
5593 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5596 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
5600 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
5604 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND)) != flags)
5607 mdb_cursor_init(&mc, txn, dbi, &mx);
5608 return mdb_cursor_put(&mc, key, data, flags);
5611 /** Only a subset of the @ref mdb_env flags can be changed
5612 * at runtime. Changing other flags requires closing the environment
5613 * and re-opening it with the new flags.
5615 #define CHANGEABLE (MDB_NOSYNC)
5617 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
5619 if ((flag & CHANGEABLE) != flag)
5622 env->me_flags |= flag;
5624 env->me_flags &= ~flag;
5629 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
5634 *arg = env->me_flags;
5639 mdb_env_get_path(MDB_env *env, const char **arg)
5644 *arg = env->me_path;
5648 /** Common code for #mdb_stat() and #mdb_env_stat().
5649 * @param[in] env the environment to operate in.
5650 * @param[in] db the #MDB_db record containing the stats to return.
5651 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
5652 * @return 0, this function always succeeds.
5655 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
5657 arg->ms_psize = env->me_psize;
5658 arg->ms_depth = db->md_depth;
5659 arg->ms_branch_pages = db->md_branch_pages;
5660 arg->ms_leaf_pages = db->md_leaf_pages;
5661 arg->ms_overflow_pages = db->md_overflow_pages;
5662 arg->ms_entries = db->md_entries;
5667 mdb_env_stat(MDB_env *env, MDB_stat *arg)
5671 if (env == NULL || arg == NULL)
5674 mdb_env_read_meta(env, &toggle);
5676 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
5679 /** Set the default comparison functions for a database.
5680 * Called immediately after a database is opened to set the defaults.
5681 * The user can then override them with #mdb_set_compare() or
5682 * #mdb_set_dupsort().
5683 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
5684 * @param[in] dbi A database handle returned by #mdb_open()
5687 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
5689 if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEKEY)
5690 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memnr;
5691 else if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERKEY)
5692 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_cint;
5694 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memn;
5696 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
5697 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP) {
5698 if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED)
5699 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_int;
5701 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_cint;
5702 } else if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEDUP) {
5703 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memnr;
5705 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memn;
5708 txn->mt_dbxs[dbi].md_dcmp = NULL;
5712 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
5717 int rc, dbflag, exact;
5720 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
5721 mdb_default_cmp(txn, FREE_DBI);
5727 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
5728 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
5729 mdb_default_cmp(txn, MAIN_DBI);
5733 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
5734 mdb_default_cmp(txn, MAIN_DBI);
5737 /* Is the DB already open? */
5739 for (i=2; i<txn->mt_numdbs; i++) {
5740 if (len == txn->mt_dbxs[i].md_name.mv_size &&
5741 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
5747 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
5750 /* Find the DB info */
5754 key.mv_data = (void *)name;
5755 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
5756 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
5757 if (rc == MDB_SUCCESS) {
5758 /* make sure this is actually a DB */
5759 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
5760 if (!(node->mn_flags & F_SUBDATA))
5762 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
5763 /* Create if requested */
5765 data.mv_size = sizeof(MDB_db);
5766 data.mv_data = &dummy;
5767 memset(&dummy, 0, sizeof(dummy));
5768 dummy.md_root = P_INVALID;
5769 dummy.md_flags = flags & 0xffff;
5770 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
5774 /* OK, got info, add to table */
5775 if (rc == MDB_SUCCESS) {
5776 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
5777 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
5778 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
5779 txn->mt_dbflags[txn->mt_numdbs] = dbflag;
5780 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
5781 *dbi = txn->mt_numdbs;
5782 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
5783 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
5784 mdb_default_cmp(txn, txn->mt_numdbs);
5791 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
5793 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
5796 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
5799 void mdb_close(MDB_env *env, MDB_dbi dbi)
5802 if (dbi <= MAIN_DBI || dbi >= env->me_numdbs)
5804 ptr = env->me_dbxs[dbi].md_name.mv_data;
5805 env->me_dbxs[dbi].md_name.mv_data = NULL;
5806 env->me_dbxs[dbi].md_name.mv_size = 0;
5810 /** Add all the DB's pages to the free list.
5811 * @param[in] mc Cursor on the DB to free.
5812 * @param[in] subs non-Zero to check for sub-DBs in this DB.
5813 * @return 0 on success, non-zero on failure.
5816 mdb_drop0(MDB_cursor *mc, int subs)
5820 rc = mdb_page_search(mc, NULL, 0);
5821 if (rc == MDB_SUCCESS) {
5826 /* LEAF2 pages have no nodes, cannot have sub-DBs */
5827 if (!subs || IS_LEAF2(mc->mc_pg[mc->mc_top]))
5830 mdb_cursor_copy(mc, &mx);
5831 while (mc->mc_snum > 0) {
5832 if (IS_LEAF(mc->mc_pg[mc->mc_top])) {
5833 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
5834 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
5835 if (ni->mn_flags & F_SUBDATA) {
5836 mdb_xcursor_init1(mc, ni);
5837 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
5843 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
5845 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
5848 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
5853 rc = mdb_cursor_sibling(mc, 1);
5855 /* no more siblings, go back to beginning
5856 * of previous level. (stack was already popped
5857 * by mdb_cursor_sibling)
5859 for (i=1; i<mc->mc_top; i++)
5860 mc->mc_pg[i] = mx.mc_pg[i];
5864 mdb_midl_append(&mc->mc_txn->mt_free_pgs,
5865 mc->mc_db->md_root);
5870 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
5875 if (!txn || !dbi || dbi >= txn->mt_numdbs)
5878 rc = mdb_cursor_open(txn, dbi, &mc);
5882 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
5884 mdb_cursor_close(mc);
5887 /* Can't delete the main DB */
5888 if (del && dbi > MAIN_DBI) {
5889 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
5891 mdb_close(txn->mt_env, dbi);
5893 txn->mt_dbflags[dbi] |= DB_DIRTY;
5894 txn->mt_dbs[dbi].md_depth = 0;
5895 txn->mt_dbs[dbi].md_branch_pages = 0;
5896 txn->mt_dbs[dbi].md_leaf_pages = 0;
5897 txn->mt_dbs[dbi].md_overflow_pages = 0;
5898 txn->mt_dbs[dbi].md_entries = 0;
5899 txn->mt_dbs[dbi].md_root = P_INVALID;
5901 mdb_cursor_close(mc);
5905 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
5907 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5910 txn->mt_dbxs[dbi].md_cmp = cmp;
5914 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
5916 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5919 txn->mt_dbxs[dbi].md_dcmp = cmp;
5923 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
5925 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5928 txn->mt_dbxs[dbi].md_rel = rel;
5932 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
5934 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5937 txn->mt_dbxs[dbi].md_relctx = ctx;