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 unsigned short mn_flags; /**< @ref mdb_node */
603 unsigned short mn_ksize; /**< key size */
604 char mn_data[1]; /**< key and data are appended here */
607 /** Size of the node header, excluding dynamic data at the end */
608 #define NODESIZE offsetof(MDB_node, mn_data)
610 /** Bit position of top word in page number, for shifting mn_flags */
611 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
613 /** Size of a node in a branch page with a given key.
614 * This is just the node header plus the key, there is no data.
616 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
618 /** Size of a node in a leaf page with a given key and data.
619 * This is node header plus key plus data size.
621 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
623 /** Address of node \b i in page \b p */
624 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
626 /** Address of the key for the node */
627 #define NODEKEY(node) (void *)((node)->mn_data)
629 /** Address of the data for a node */
630 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
632 /** Get the page number pointed to by a branch node */
633 #define NODEPGNO(node) \
634 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
635 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
636 /** Set the page number in a branch node */
637 #define SETPGNO(node,pgno) do { \
638 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
639 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
641 /** Get the size of the data in a leaf node */
642 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
643 /** Set the size of the data for a leaf node */
644 #define SETDSZ(node,size) do { \
645 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
646 /** The size of a key in a node */
647 #define NODEKSZ(node) ((node)->mn_ksize)
649 /** The address of a key in a LEAF2 page.
650 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
651 * There are no node headers, keys are stored contiguously.
653 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
655 /** Set the \b node's key into \b key, if requested. */
656 #define MDB_SET_KEY(node, key) { if ((key) != NULL) { \
657 (key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node); } }
659 /** Information about a single database in the environment. */
660 typedef struct MDB_db {
661 uint32_t md_pad; /**< also ksize for LEAF2 pages */
662 uint16_t md_flags; /**< @ref mdb_open */
663 uint16_t md_depth; /**< depth of this tree */
664 pgno_t md_branch_pages; /**< number of internal pages */
665 pgno_t md_leaf_pages; /**< number of leaf pages */
666 pgno_t md_overflow_pages; /**< number of overflow pages */
667 size_t md_entries; /**< number of data items */
668 pgno_t md_root; /**< the root page of this tree */
671 /** Handle for the DB used to track free pages. */
673 /** Handle for the default DB. */
676 /** Meta page content. */
677 typedef struct MDB_meta {
678 /** Stamp identifying this as an MDB data file. It must be set
681 /** Version number of this lock file. Must be set to #MDB_VERSION. */
683 void *mm_address; /**< address for fixed mapping */
684 size_t mm_mapsize; /**< size of mmap region */
685 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
686 /** The size of pages used in this DB */
687 #define mm_psize mm_dbs[0].md_pad
688 /** Any persistent environment flags. @ref mdb_env */
689 #define mm_flags mm_dbs[0].md_flags
690 pgno_t mm_last_pg; /**< last used page in file */
691 txnid_t mm_txnid; /**< txnid that committed this page */
694 /** Auxiliary DB info.
695 * The information here is mostly static/read-only. There is
696 * only a single copy of this record in the environment.
698 typedef struct MDB_dbx {
699 MDB_val md_name; /**< name of the database */
700 MDB_cmp_func *md_cmp; /**< function for comparing keys */
701 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
702 MDB_rel_func *md_rel; /**< user relocate function */
703 void *md_relctx; /**< user-provided context for md_rel */
706 /** A database transaction.
707 * Every operation requires a transaction handle.
710 MDB_txn *mt_parent; /**< parent of a nested txn */
711 MDB_txn *mt_child; /**< nested txn under this txn */
712 pgno_t mt_next_pgno; /**< next unallocated page */
713 /** The ID of this transaction. IDs are integers incrementing from 1.
714 * Only committed write transactions increment the ID. If a transaction
715 * aborts, the ID may be re-used by the next writer.
718 MDB_env *mt_env; /**< the DB environment */
719 /** The list of pages that became unused during this transaction.
723 ID2L dirty_list; /**< modified pages */
724 MDB_reader *reader; /**< this thread's slot in the reader table */
726 /** Array of records for each DB known in the environment. */
728 /** Array of MDB_db records for each known DB */
730 /** @defgroup mt_dbflag Transaction DB Flags
734 #define DB_DIRTY 0x01 /**< DB was written in this txn */
735 #define DB_STALE 0x02 /**< DB record is older than txnID */
737 /** Array of cursors for each DB */
738 MDB_cursor **mt_cursors;
739 /** Array of flags for each DB */
740 unsigned char *mt_dbflags;
741 /** Number of DB records in use. This number only ever increments;
742 * we don't decrement it when individual DB handles are closed.
746 /** @defgroup mdb_txn Transaction Flags
750 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
751 #define MDB_TXN_ERROR 0x02 /**< an error has occurred */
753 unsigned int mt_flags; /**< @ref mdb_txn */
754 /** Tracks which of the two meta pages was used at the start
755 * of this transaction.
757 unsigned int mt_toggle;
760 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
761 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
762 * raise this on a 64 bit machine.
764 #define CURSOR_STACK 32
768 /** Cursors are used for all DB operations */
770 /** Next cursor on this DB in this txn */
772 /** Original cursor if this is a shadow */
774 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
775 struct MDB_xcursor *mc_xcursor;
776 /** The transaction that owns this cursor */
778 /** The database handle this cursor operates on */
780 /** The database record for this cursor */
782 /** The database auxiliary record for this cursor */
784 /** The @ref mt_dbflag for this database */
785 unsigned char *mc_dbflag;
786 unsigned short mc_snum; /**< number of pushed pages */
787 unsigned short mc_top; /**< index of top page, mc_snum-1 */
788 /** @defgroup mdb_cursor Cursor Flags
790 * Cursor state flags.
793 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
794 #define C_EOF 0x02 /**< No more data */
795 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
796 #define C_SHADOW 0x08 /**< Cursor is a dup from a parent txn */
797 #define C_ALLOCD 0x10 /**< Cursor was malloc'd */
799 unsigned int mc_flags; /**< @ref mdb_cursor */
800 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
801 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
804 /** Context for sorted-dup records.
805 * We could have gone to a fully recursive design, with arbitrarily
806 * deep nesting of sub-databases. But for now we only handle these
807 * levels - main DB, optional sub-DB, sorted-duplicate DB.
809 typedef struct MDB_xcursor {
810 /** A sub-cursor for traversing the Dup DB */
811 MDB_cursor mx_cursor;
812 /** The database record for this Dup DB */
814 /** The auxiliary DB record for this Dup DB */
816 /** The @ref mt_dbflag for this Dup DB */
817 unsigned char mx_dbflag;
820 /** A set of pages freed by an earlier transaction. */
821 typedef struct MDB_oldpages {
822 /** Usually we only read one record from the FREEDB at a time, but
823 * in case we read more, this will chain them together.
825 struct MDB_oldpages *mo_next;
826 /** The ID of the transaction in which these pages were freed. */
828 /** An #IDL of the pages */
829 pgno_t mo_pages[1]; /* dynamic */
832 /** The database environment. */
834 HANDLE me_fd; /**< The main data file */
835 HANDLE me_lfd; /**< The lock file */
836 HANDLE me_mfd; /**< just for writing the meta pages */
837 /** Failed to update the meta page. Probably an I/O error. */
838 #define MDB_FATAL_ERROR 0x80000000U
839 uint32_t me_flags; /**< @ref mdb_env */
840 uint32_t me_extrapad; /**< unused for now */
841 unsigned int me_maxreaders; /**< size of the reader table */
842 MDB_dbi me_numdbs; /**< number of DBs opened */
843 MDB_dbi me_maxdbs; /**< size of the DB table */
844 char *me_path; /**< path to the DB files */
845 char *me_map; /**< the memory map of the data file */
846 MDB_txninfo *me_txns; /**< the memory map of the lock file */
847 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
848 MDB_txn *me_txn; /**< current write transaction */
849 size_t me_mapsize; /**< size of the data memory map */
850 off_t me_size; /**< current file size */
851 pgno_t me_maxpg; /**< me_mapsize / me_psize */
852 unsigned int me_psize; /**< size of a page, from #GET_PAGESIZE */
853 unsigned int me_db_toggle; /**< which DB table is current */
854 txnid_t me_wtxnid; /**< ID of last txn we committed */
855 MDB_dbx *me_dbxs; /**< array of static DB info */
856 MDB_db *me_dbs[2]; /**< two arrays of MDB_db info */
857 MDB_oldpages *me_pghead; /**< list of old page records */
858 pthread_key_t me_txkey; /**< thread-key for readers */
859 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
860 /** IDL of pages that became unused in a write txn */
862 /** ID2L of pages that were written during a write txn */
863 ID2 me_dirty_list[MDB_IDL_UM_SIZE];
864 /** rwlock for the DB tables, if #LAZY_LOCKS is false */
865 LAZY_RWLOCK_DEF(me_dblock)
867 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
871 sem_t *me_rmutex; /* Apple doesn't support shared mutexes */
875 /** max number of pages to commit in one writev() call */
876 #define MDB_COMMIT_PAGES 64
878 static MDB_page *mdb_page_alloc(MDB_cursor *mc, int num);
879 static MDB_page *mdb_page_new(MDB_cursor *mc, uint32_t flags, int num);
880 static int mdb_page_touch(MDB_cursor *mc);
882 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
883 static int mdb_page_search_root(MDB_cursor *mc,
884 MDB_val *key, int modify);
885 static int mdb_page_search(MDB_cursor *mc,
886 MDB_val *key, int modify);
887 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
888 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
891 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
892 static int mdb_env_read_meta(MDB_env *env, int *which);
893 static int mdb_env_write_meta(MDB_txn *txn);
895 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
896 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
897 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags);
898 static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
899 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
900 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
901 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
902 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
903 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
905 static int mdb_rebalance(MDB_cursor *mc);
906 static int mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
908 static void mdb_cursor_pop(MDB_cursor *mc);
909 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
911 static int mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
912 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
913 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
914 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
915 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
917 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
918 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
920 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
921 static void mdb_xcursor_init0(MDB_cursor *mc);
922 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
924 static int mdb_drop0(MDB_cursor *mc, int subs);
925 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
928 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
932 static SECURITY_DESCRIPTOR mdb_null_sd;
933 static SECURITY_ATTRIBUTES mdb_all_sa;
934 static int mdb_sec_inited;
937 /** Return the library version info. */
939 mdb_version(int *major, int *minor, int *patch)
941 if (major) *major = MDB_VERSION_MAJOR;
942 if (minor) *minor = MDB_VERSION_MINOR;
943 if (patch) *patch = MDB_VERSION_PATCH;
944 return MDB_VERSION_STRING;
947 /** Table of descriptions for MDB @ref errors */
948 static char *const mdb_errstr[] = {
949 "MDB_KEYEXIST: Key/data pair already exists",
950 "MDB_NOTFOUND: No matching key/data pair found",
951 "MDB_PAGE_NOTFOUND: Requested page not found",
952 "MDB_CORRUPTED: Located page was wrong type",
953 "MDB_PANIC: Update of meta page failed",
954 "MDB_VERSION_MISMATCH: Database environment version mismatch"
958 mdb_strerror(int err)
961 return ("Successful return: 0");
963 if (err >= MDB_KEYEXIST && err <= MDB_VERSION_MISMATCH)
964 return mdb_errstr[err - MDB_KEYEXIST];
966 return strerror(err);
970 /** Display a key in hexadecimal and return the address of the result.
971 * @param[in] key the key to display
972 * @param[in] buf the buffer to write into. Should always be #DKBUF.
973 * @return The key in hexadecimal form.
976 mdb_dkey(MDB_val *key, char *buf)
979 unsigned char *c = key->mv_data;
981 if (key->mv_size > MAXKEYSIZE)
983 /* may want to make this a dynamic check: if the key is mostly
984 * printable characters, print it as-is instead of converting to hex.
987 for (i=0; i<key->mv_size; i++)
988 ptr += sprintf(ptr, "%02x", *c++);
990 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
997 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
999 return txn->mt_dbxs[dbi].md_cmp(a, b);
1003 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1005 if (txn->mt_dbxs[dbi].md_dcmp)
1006 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1008 return EINVAL; /* too bad you can't distinguish this from a valid result */
1011 /** Allocate a single page.
1012 * Re-use old malloc'd pages first, otherwise just malloc.
1015 mdb_page_malloc(MDB_cursor *mc) {
1017 if (mc->mc_txn->mt_env->me_dpages) {
1018 ret = mc->mc_txn->mt_env->me_dpages;
1019 mc->mc_txn->mt_env->me_dpages = ret->mp_next;
1021 ret = malloc(mc->mc_txn->mt_env->me_psize);
1026 /** Allocate pages for writing.
1027 * If there are free pages available from older transactions, they
1028 * will be re-used first. Otherwise a new page will be allocated.
1029 * @param[in] mc cursor A cursor handle identifying the transaction and
1030 * database for which we are allocating.
1031 * @param[in] num the number of pages to allocate.
1032 * @return Address of the allocated page(s). Requests for multiple pages
1033 * will always be satisfied by a single contiguous chunk of memory.
1036 mdb_page_alloc(MDB_cursor *mc, int num)
1038 MDB_txn *txn = mc->mc_txn;
1040 pgno_t pgno = P_INVALID;
1043 if (txn->mt_txnid > 2) {
1045 if (!txn->mt_env->me_pghead && mc->mc_dbi != FREE_DBI &&
1046 txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
1047 /* See if there's anything in the free DB */
1050 txnid_t *kptr, oldest;
1052 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1053 mdb_page_search(&m2, NULL, 0);
1054 leaf = NODEPTR(m2.mc_pg[m2.mc_top], 0);
1055 kptr = (txnid_t *)NODEKEY(leaf);
1059 oldest = txn->mt_txnid - 1;
1060 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
1061 txnid_t mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
1062 if (mr && mr < oldest)
1067 if (oldest > *kptr) {
1068 /* It's usable, grab it.
1074 mdb_node_read(txn, leaf, &data);
1075 idl = (ID *) data.mv_data;
1076 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
1077 mop->mo_next = txn->mt_env->me_pghead;
1078 mop->mo_txnid = *kptr;
1079 txn->mt_env->me_pghead = mop;
1080 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
1085 DPRINTF("IDL read txn %zu root %zu num %zu",
1086 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1087 for (i=0; i<idl[0]; i++) {
1088 DPRINTF("IDL %zu", idl[i+1]);
1092 /* drop this IDL from the DB */
1093 m2.mc_ki[m2.mc_top] = 0;
1094 m2.mc_flags = C_INITIALIZED;
1095 mdb_cursor_del(&m2, 0);
1098 if (txn->mt_env->me_pghead) {
1099 MDB_oldpages *mop = txn->mt_env->me_pghead;
1101 /* FIXME: For now, always use fresh pages. We
1102 * really ought to search the free list for a
1107 /* peel pages off tail, so we only have to truncate the list */
1108 pgno = MDB_IDL_LAST(mop->mo_pages);
1109 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
1111 if (mop->mo_pages[2] > mop->mo_pages[1])
1112 mop->mo_pages[0] = 0;
1116 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
1117 txn->mt_env->me_pghead = mop->mo_next;
1124 if (pgno == P_INVALID) {
1125 /* DB size is maxed out */
1126 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg) {
1127 DPRINTF("DB size maxed out");
1131 if (txn->mt_env->me_dpages && num == 1) {
1132 np = txn->mt_env->me_dpages;
1133 txn->mt_env->me_dpages = np->mp_next;
1135 if ((np = malloc(txn->mt_env->me_psize * num )) == NULL)
1138 if (pgno == P_INVALID) {
1139 np->mp_pgno = txn->mt_next_pgno;
1140 txn->mt_next_pgno += num;
1144 mid.mid = np->mp_pgno;
1146 mdb_mid2l_insert(txn->mt_u.dirty_list, &mid);
1151 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1152 * @param[in] mc cursor pointing to the page to be touched
1153 * @return 0 on success, non-zero on failure.
1156 mdb_page_touch(MDB_cursor *mc)
1158 MDB_page *mp = mc->mc_pg[mc->mc_top];
1161 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1163 if ((np = mdb_page_alloc(mc, 1)) == NULL)
1165 DPRINTF("touched db %u page %zu -> %zu", mc->mc_dbi, mp->mp_pgno, np->mp_pgno);
1166 assert(mp->mp_pgno != np->mp_pgno);
1167 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
1169 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1172 mp->mp_flags |= P_DIRTY;
1175 /* Adjust other cursors pointing to mp */
1176 if (mc->mc_flags & C_SUB) {
1177 MDB_cursor *m2, *m3;
1178 MDB_dbi dbi = mc->mc_dbi-1;
1180 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
1181 m3 = &m2->mc_xcursor->mx_cursor;
1182 if (m3->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1183 m3->mc_pg[mc->mc_top] = mp;
1189 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
1190 if (m2->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1191 m2->mc_pg[mc->mc_top] = mp;
1195 mc->mc_pg[mc->mc_top] = mp;
1196 /** If this page has a parent, update the parent to point to
1200 SETPGNO(NODEPTR(mc->mc_pg[mc->mc_top-1], mc->mc_ki[mc->mc_top-1]), mp->mp_pgno);
1202 mc->mc_db->md_root = mp->mp_pgno;
1203 } else if (mc->mc_txn->mt_parent) {
1206 /* If txn has a parent, make sure the page is in our
1209 if (mc->mc_txn->mt_u.dirty_list[0].mid) {
1210 unsigned x = mdb_mid2l_search(mc->mc_txn->mt_u.dirty_list, mp->mp_pgno);
1211 if (x <= mc->mc_txn->mt_u.dirty_list[0].mid &&
1212 mc->mc_txn->mt_u.dirty_list[x].mid == mp->mp_pgno) {
1213 if (mc->mc_txn->mt_u.dirty_list[x].mptr != mp) {
1214 mp = mc->mc_txn->mt_u.dirty_list[x].mptr;
1215 mc->mc_pg[mc->mc_top] = mp;
1221 np = mdb_page_malloc(mc);
1222 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1223 mid.mid = np->mp_pgno;
1225 mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &mid);
1233 mdb_env_sync(MDB_env *env, int force)
1236 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1237 if (fdatasync(env->me_fd))
1243 /** Make shadow copies of all of parent txn's cursors */
1245 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
1247 MDB_cursor *mc, *m2;
1248 unsigned int i, j, size;
1250 for (i=0;i<src->mt_numdbs; i++) {
1251 if (src->mt_cursors[i]) {
1252 size = sizeof(MDB_cursor);
1253 if (src->mt_cursors[i]->mc_xcursor)
1254 size += sizeof(MDB_xcursor);
1255 for (m2 = src->mt_cursors[i]; m2; m2=m2->mc_next) {
1262 mc->mc_db = &dst->mt_dbs[i];
1263 mc->mc_dbx = m2->mc_dbx;
1264 mc->mc_dbflag = &dst->mt_dbflags[i];
1265 mc->mc_snum = m2->mc_snum;
1266 mc->mc_top = m2->mc_top;
1267 mc->mc_flags = m2->mc_flags | C_SHADOW;
1268 for (j=0; j<mc->mc_snum; j++) {
1269 mc->mc_pg[j] = m2->mc_pg[j];
1270 mc->mc_ki[j] = m2->mc_ki[j];
1272 if (m2->mc_xcursor) {
1273 MDB_xcursor *mx, *mx2;
1274 mx = (MDB_xcursor *)(mc+1);
1275 mc->mc_xcursor = mx;
1276 mx2 = m2->mc_xcursor;
1277 mx->mx_db = mx2->mx_db;
1278 mx->mx_dbx = mx2->mx_dbx;
1279 mx->mx_dbflag = mx2->mx_dbflag;
1280 mx->mx_cursor.mc_txn = dst;
1281 mx->mx_cursor.mc_dbi = mx2->mx_cursor.mc_dbi;
1282 mx->mx_cursor.mc_db = &mx->mx_db;
1283 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
1284 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
1285 mx->mx_cursor.mc_snum = mx2->mx_cursor.mc_snum;
1286 mx->mx_cursor.mc_top = mx2->mx_cursor.mc_top;
1287 mx->mx_cursor.mc_flags = mx2->mx_cursor.mc_flags | C_SHADOW;
1288 for (j=0; j<mx2->mx_cursor.mc_snum; j++) {
1289 mx->mx_cursor.mc_pg[j] = mx2->mx_cursor.mc_pg[j];
1290 mx->mx_cursor.mc_ki[j] = mx2->mx_cursor.mc_ki[j];
1293 mc->mc_xcursor = NULL;
1295 mc->mc_next = dst->mt_cursors[i];
1296 dst->mt_cursors[i] = mc;
1303 /** Merge shadow cursors back into parent's */
1305 mdb_cursor_merge(MDB_txn *txn)
1308 for (i=0; i<txn->mt_numdbs; i++) {
1309 if (txn->mt_cursors[i]) {
1311 while ((mc = txn->mt_cursors[i])) {
1312 txn->mt_cursors[i] = mc->mc_next;
1313 if (mc->mc_flags & C_SHADOW) {
1314 MDB_cursor *m2 = mc->mc_orig;
1316 m2->mc_snum = mc->mc_snum;
1317 m2->mc_top = mc->mc_top;
1318 for (j=0; j<mc->mc_snum; j++) {
1319 m2->mc_pg[j] = mc->mc_pg[j];
1320 m2->mc_ki[j] = mc->mc_ki[j];
1323 if (mc->mc_flags & C_ALLOCD)
1331 mdb_txn_reset0(MDB_txn *txn);
1333 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
1334 * @param[in] txn the transaction handle to initialize
1335 * @return 0 on success, non-zero on failure. This can only
1336 * fail for read-only transactions, and then only if the
1337 * reader table is full.
1340 mdb_txn_renew0(MDB_txn *txn)
1342 MDB_env *env = txn->mt_env;
1345 if (txn->mt_flags & MDB_TXN_RDONLY) {
1346 MDB_reader *r = pthread_getspecific(env->me_txkey);
1349 pid_t pid = getpid();
1350 pthread_t tid = pthread_self();
1353 for (i=0; i<env->me_txns->mti_numreaders; i++)
1354 if (env->me_txns->mti_readers[i].mr_pid == 0)
1356 if (i == env->me_maxreaders) {
1357 UNLOCK_MUTEX_R(env);
1360 env->me_txns->mti_readers[i].mr_pid = pid;
1361 env->me_txns->mti_readers[i].mr_tid = tid;
1362 if (i >= env->me_txns->mti_numreaders)
1363 env->me_txns->mti_numreaders = i+1;
1364 UNLOCK_MUTEX_R(env);
1365 r = &env->me_txns->mti_readers[i];
1366 pthread_setspecific(env->me_txkey, r);
1368 txn->mt_toggle = env->me_txns->mti_me_toggle;
1369 txn->mt_txnid = env->me_txns->mti_txnid;
1370 /* This happens if a different process was the
1371 * last writer to the DB.
1373 if (env->me_wtxnid < txn->mt_txnid)
1374 mt_dbflag = DB_STALE;
1375 r->mr_txnid = txn->mt_txnid;
1376 txn->mt_u.reader = r;
1380 txn->mt_txnid = env->me_txns->mti_txnid;
1381 if (env->me_wtxnid < txn->mt_txnid)
1382 mt_dbflag = DB_STALE;
1384 txn->mt_toggle = env->me_txns->mti_me_toggle;
1385 txn->mt_u.dirty_list = env->me_dirty_list;
1386 txn->mt_u.dirty_list[0].mid = 0;
1387 txn->mt_free_pgs = env->me_free_pgs;
1388 txn->mt_free_pgs[0] = 0;
1389 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1393 /* Copy the DB arrays */
1394 LAZY_RWLOCK_RDLOCK(&env->me_dblock);
1395 txn->mt_numdbs = env->me_numdbs;
1396 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
1397 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
1398 if (txn->mt_numdbs > 2)
1399 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
1400 (txn->mt_numdbs - 2) * sizeof(MDB_db));
1401 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1403 memset(txn->mt_dbflags, mt_dbflag, env->me_numdbs);
1409 mdb_txn_renew(MDB_txn *txn)
1416 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
1417 DPUTS("environment had fatal error, must shutdown!");
1421 rc = mdb_txn_renew0(txn);
1422 if (rc == MDB_SUCCESS) {
1423 DPRINTF("renew txn %zu%c %p on mdbenv %p, root page %zu",
1424 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1425 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1431 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
1436 if (env->me_flags & MDB_FATAL_ERROR) {
1437 DPUTS("environment had fatal error, must shutdown!");
1441 /* parent already has an active child txn */
1442 if (parent->mt_child) {
1446 size = sizeof(MDB_txn) + env->me_maxdbs * (sizeof(MDB_db)+1);
1447 if (!(flags & MDB_RDONLY))
1448 size += env->me_maxdbs * sizeof(MDB_cursor *);
1450 if ((txn = calloc(1, size)) == NULL) {
1451 DPRINTF("calloc: %s", strerror(ErrCode()));
1454 txn->mt_dbs = (MDB_db *)(txn+1);
1455 if (flags & MDB_RDONLY) {
1456 txn->mt_flags |= MDB_TXN_RDONLY;
1457 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
1459 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
1460 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
1465 txn->mt_free_pgs = mdb_midl_alloc();
1466 if (!txn->mt_free_pgs) {
1470 txn->mt_u.dirty_list = malloc(sizeof(ID2)*MDB_IDL_UM_SIZE);
1471 if (!txn->mt_u.dirty_list) {
1472 free(txn->mt_free_pgs);
1476 txn->mt_txnid = parent->mt_txnid;
1477 txn->mt_toggle = parent->mt_toggle;
1478 txn->mt_u.dirty_list[0].mid = 0;
1479 txn->mt_free_pgs[0] = 0;
1480 txn->mt_next_pgno = parent->mt_next_pgno;
1481 parent->mt_child = txn;
1482 txn->mt_parent = parent;
1483 txn->mt_numdbs = parent->mt_numdbs;
1484 txn->mt_dbxs = parent->mt_dbxs;
1485 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
1486 memcpy(txn->mt_dbflags, parent->mt_dbflags, txn->mt_numdbs);
1487 mdb_cursor_shadow(parent, txn);
1490 rc = mdb_txn_renew0(txn);
1496 DPRINTF("begin txn %zu%c %p on mdbenv %p, root page %zu",
1497 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1498 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
1504 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
1505 * @param[in] txn the transaction handle to reset
1508 mdb_txn_reset0(MDB_txn *txn)
1510 MDB_env *env = txn->mt_env;
1512 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1513 txn->mt_u.reader->mr_txnid = 0;
1519 /* close(free) all cursors */
1520 for (i=0; i<txn->mt_numdbs; i++) {
1521 if (txn->mt_cursors[i]) {
1523 while ((mc = txn->mt_cursors[i])) {
1524 txn->mt_cursors[i] = mc->mc_next;
1525 if (mc->mc_flags & C_ALLOCD)
1531 /* return all dirty pages to dpage list */
1532 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1533 dp = txn->mt_u.dirty_list[i].mptr;
1534 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1535 dp->mp_next = txn->mt_env->me_dpages;
1536 txn->mt_env->me_dpages = dp;
1538 /* large pages just get freed directly */
1543 if (txn->mt_parent) {
1544 txn->mt_parent->mt_child = NULL;
1545 free(txn->mt_free_pgs);
1546 free(txn->mt_u.dirty_list);
1549 if (mdb_midl_shrink(&txn->mt_free_pgs))
1550 env->me_free_pgs = txn->mt_free_pgs;
1553 while ((mop = txn->mt_env->me_pghead)) {
1554 txn->mt_env->me_pghead = mop->mo_next;
1559 /* The writer mutex was locked in mdb_txn_begin. */
1560 UNLOCK_MUTEX_W(env);
1565 mdb_txn_reset(MDB_txn *txn)
1570 DPRINTF("reset txn %zu%c %p on mdbenv %p, root page %zu",
1571 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1572 (void *) txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1574 mdb_txn_reset0(txn);
1578 mdb_txn_abort(MDB_txn *txn)
1583 DPRINTF("abort txn %zu%c %p on mdbenv %p, root page %zu",
1584 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1585 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1588 mdb_txn_abort(txn->mt_child);
1590 mdb_txn_reset0(txn);
1595 mdb_txn_commit(MDB_txn *txn)
1606 assert(txn != NULL);
1607 assert(txn->mt_env != NULL);
1609 if (txn->mt_child) {
1610 mdb_txn_commit(txn->mt_child);
1611 txn->mt_child = NULL;
1616 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1617 if (txn->mt_numdbs > env->me_numdbs) {
1618 /* update the DB tables */
1619 int toggle = !env->me_db_toggle;
1623 ip = &env->me_dbs[toggle][env->me_numdbs];
1624 jp = &txn->mt_dbs[env->me_numdbs];
1625 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1626 for (i = env->me_numdbs; i < txn->mt_numdbs; i++) {
1630 env->me_db_toggle = toggle;
1631 env->me_numdbs = txn->mt_numdbs;
1632 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1638 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1639 DPUTS("error flag is set, can't commit");
1641 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
1646 /* Merge (and close) our cursors with parent's */
1647 mdb_cursor_merge(txn);
1649 if (txn->mt_parent) {
1655 /* Update parent's DB table */
1656 ip = &txn->mt_parent->mt_dbs[2];
1657 jp = &txn->mt_dbs[2];
1658 for (i = 2; i < txn->mt_numdbs; i++) {
1659 if (ip->md_root != jp->md_root)
1663 txn->mt_parent->mt_numdbs = txn->mt_numdbs;
1665 /* Append our free list to parent's */
1666 mdb_midl_append_list(&txn->mt_parent->mt_free_pgs,
1668 mdb_midl_free(txn->mt_free_pgs);
1670 /* Merge our dirty list with parent's */
1671 dst = txn->mt_parent->mt_u.dirty_list;
1672 src = txn->mt_u.dirty_list;
1673 x = mdb_mid2l_search(dst, src[1].mid);
1674 for (y=1; y<=src[0].mid; y++) {
1675 while (x <= dst[0].mid && dst[x].mid != src[y].mid) x++;
1679 dst[x].mptr = src[y].mptr;
1682 for (; y<=src[0].mid; y++) {
1683 if (++x >= MDB_IDL_UM_MAX)
1688 free(txn->mt_u.dirty_list);
1689 txn->mt_parent->mt_child = NULL;
1694 if (txn != env->me_txn) {
1695 DPUTS("attempt to commit unknown transaction");
1700 if (!txn->mt_u.dirty_list[0].mid)
1703 DPRINTF("committing txn %zu %p on mdbenv %p, root page %zu",
1704 txn->mt_txnid, (void *)txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
1706 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1708 /* should only be one record now */
1709 if (env->me_pghead) {
1710 /* make sure first page of freeDB is touched and on freelist */
1711 mdb_page_search(&mc, NULL, 1);
1713 /* save to free list */
1714 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
1718 /* make sure last page of freeDB is touched and on freelist */
1719 key.mv_size = MAXKEYSIZE+1;
1721 mdb_page_search(&mc, &key, 1);
1723 mdb_midl_sort(txn->mt_free_pgs);
1727 ID *idl = txn->mt_free_pgs;
1728 DPRINTF("IDL write txn %zu root %zu num %zu",
1729 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1730 for (i=0; i<idl[0]; i++) {
1731 DPRINTF("IDL %zu", idl[i+1]);
1735 /* write to last page of freeDB */
1736 key.mv_size = sizeof(pgno_t);
1737 key.mv_data = &txn->mt_txnid;
1738 data.mv_data = txn->mt_free_pgs;
1739 /* The free list can still grow during this call,
1740 * despite the pre-emptive touches above. So check
1741 * and make sure the entire thing got written.
1744 i = txn->mt_free_pgs[0];
1745 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
1746 rc = mdb_cursor_put(&mc, &key, &data, 0);
1751 } while (i != txn->mt_free_pgs[0]);
1752 if (mdb_midl_shrink(&txn->mt_free_pgs))
1753 env->me_free_pgs = txn->mt_free_pgs;
1755 /* should only be one record now */
1756 if (env->me_pghead) {
1760 mop = env->me_pghead;
1761 key.mv_size = sizeof(pgno_t);
1762 key.mv_data = &mop->mo_txnid;
1763 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
1764 data.mv_data = mop->mo_pages;
1765 mdb_cursor_put(&mc, &key, &data, 0);
1766 free(env->me_pghead);
1767 env->me_pghead = NULL;
1770 /* Update DB root pointers. Their pages have already been
1771 * touched so this is all in-place and cannot fail.
1776 data.mv_size = sizeof(MDB_db);
1778 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
1779 for (i = 2; i < txn->mt_numdbs; i++) {
1780 if (txn->mt_dbflags[i] & DB_DIRTY) {
1781 data.mv_data = &txn->mt_dbs[i];
1782 mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
1787 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
1793 /* Windows actually supports scatter/gather I/O, but only on
1794 * unbuffered file handles. Since we're relying on the OS page
1795 * cache for all our data, that's self-defeating. So we just
1796 * write pages one at a time. We use the ov structure to set
1797 * the write offset, to at least save the overhead of a Seek
1801 memset(&ov, 0, sizeof(ov));
1802 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1804 dp = txn->mt_u.dirty_list[i].mptr;
1805 DPRINTF("committing page %zu", dp->mp_pgno);
1806 size = dp->mp_pgno * env->me_psize;
1807 ov.Offset = size & 0xffffffff;
1808 ov.OffsetHigh = size >> 16;
1809 ov.OffsetHigh >>= 16;
1810 /* clear dirty flag */
1811 dp->mp_flags &= ~P_DIRTY;
1812 wsize = env->me_psize;
1813 if (IS_OVERFLOW(dp)) wsize *= dp->mp_pages;
1814 rc = WriteFile(env->me_fd, dp, wsize, NULL, &ov);
1817 DPRINTF("WriteFile: %d", n);
1824 struct iovec iov[MDB_COMMIT_PAGES];
1828 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1829 dp = txn->mt_u.dirty_list[i].mptr;
1830 if (dp->mp_pgno != next) {
1832 DPRINTF("committing %u dirty pages", n);
1833 rc = writev(env->me_fd, iov, n);
1837 DPUTS("short write, filesystem full?");
1839 DPRINTF("writev: %s", strerror(n));
1846 lseek(env->me_fd, dp->mp_pgno * env->me_psize, SEEK_SET);
1849 DPRINTF("committing page %zu", dp->mp_pgno);
1850 iov[n].iov_len = env->me_psize;
1851 if (IS_OVERFLOW(dp)) iov[n].iov_len *= dp->mp_pages;
1852 iov[n].iov_base = dp;
1853 size += iov[n].iov_len;
1854 next = dp->mp_pgno + (IS_OVERFLOW(dp) ? dp->mp_pages : 1);
1855 /* clear dirty flag */
1856 dp->mp_flags &= ~P_DIRTY;
1857 if (++n >= MDB_COMMIT_PAGES) {
1867 DPRINTF("committing %u dirty pages", n);
1868 rc = writev(env->me_fd, iov, n);
1872 DPUTS("short write, filesystem full?");
1874 DPRINTF("writev: %s", strerror(n));
1881 /* Drop the dirty pages.
1883 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1884 dp = txn->mt_u.dirty_list[i].mptr;
1885 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1886 dp->mp_next = txn->mt_env->me_dpages;
1887 txn->mt_env->me_dpages = dp;
1891 txn->mt_u.dirty_list[i].mid = 0;
1893 txn->mt_u.dirty_list[0].mid = 0;
1895 if ((n = mdb_env_sync(env, 0)) != 0 ||
1896 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
1900 env->me_wtxnid = txn->mt_txnid;
1904 /* update the DB tables */
1906 int toggle = !env->me_db_toggle;
1910 ip = &env->me_dbs[toggle][2];
1911 jp = &txn->mt_dbs[2];
1912 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1913 for (i = 2; i < txn->mt_numdbs; i++) {
1914 if (ip->md_root != jp->md_root)
1919 env->me_db_toggle = toggle;
1920 env->me_numdbs = txn->mt_numdbs;
1921 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1924 UNLOCK_MUTEX_W(env);
1930 /** Read the environment parameters of a DB environment before
1931 * mapping it into memory.
1932 * @param[in] env the environment handle
1933 * @param[out] meta address of where to store the meta information
1934 * @return 0 on success, non-zero on failure.
1937 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
1939 char page[PAGESIZE];
1944 /* We don't know the page size yet, so use a minimum value.
1948 if (!ReadFile(env->me_fd, page, PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
1950 if ((rc = read(env->me_fd, page, PAGESIZE)) == 0)
1955 else if (rc != PAGESIZE) {
1959 DPRINTF("read: %s", strerror(err));
1963 p = (MDB_page *)page;
1965 if (!F_ISSET(p->mp_flags, P_META)) {
1966 DPRINTF("page %zu not a meta page", p->mp_pgno);
1971 if (m->mm_magic != MDB_MAGIC) {
1972 DPUTS("meta has invalid magic");
1976 if (m->mm_version != MDB_VERSION) {
1977 DPRINTF("database is version %u, expected version %u",
1978 m->mm_version, MDB_VERSION);
1979 return MDB_VERSION_MISMATCH;
1982 memcpy(meta, m, sizeof(*m));
1986 /** Write the environment parameters of a freshly created DB environment.
1987 * @param[in] env the environment handle
1988 * @param[out] meta address of where to store the meta information
1989 * @return 0 on success, non-zero on failure.
1992 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
1999 DPUTS("writing new meta page");
2001 GET_PAGESIZE(psize);
2003 meta->mm_magic = MDB_MAGIC;
2004 meta->mm_version = MDB_VERSION;
2005 meta->mm_psize = psize;
2006 meta->mm_last_pg = 1;
2007 meta->mm_flags = env->me_flags & 0xffff;
2008 meta->mm_flags |= MDB_INTEGERKEY;
2009 meta->mm_dbs[0].md_root = P_INVALID;
2010 meta->mm_dbs[1].md_root = P_INVALID;
2012 p = calloc(2, psize);
2014 p->mp_flags = P_META;
2017 memcpy(m, meta, sizeof(*meta));
2019 q = (MDB_page *)((char *)p + psize);
2022 q->mp_flags = P_META;
2025 memcpy(m, meta, sizeof(*meta));
2030 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
2031 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
2034 rc = write(env->me_fd, p, psize * 2);
2035 rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
2041 /** Update the environment info to commit a transaction.
2042 * @param[in] txn the transaction that's being committed
2043 * @return 0 on success, non-zero on failure.
2046 mdb_env_write_meta(MDB_txn *txn)
2049 MDB_meta meta, metab;
2051 int rc, len, toggle;
2057 assert(txn != NULL);
2058 assert(txn->mt_env != NULL);
2060 toggle = !txn->mt_toggle;
2061 DPRINTF("writing meta page %d for root page %zu",
2062 toggle, txn->mt_dbs[MAIN_DBI].md_root);
2066 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
2067 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
2069 ptr = (char *)&meta;
2070 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
2071 len = sizeof(MDB_meta) - off;
2074 meta.mm_dbs[0] = txn->mt_dbs[0];
2075 meta.mm_dbs[1] = txn->mt_dbs[1];
2076 meta.mm_last_pg = txn->mt_next_pgno - 1;
2077 meta.mm_txnid = txn->mt_txnid;
2080 off += env->me_psize;
2083 /* Write to the SYNC fd */
2086 memset(&ov, 0, sizeof(ov));
2088 WriteFile(env->me_mfd, ptr, len, (DWORD *)&rc, &ov);
2091 rc = pwrite(env->me_mfd, ptr, len, off);
2096 DPUTS("write failed, disk error?");
2097 /* On a failure, the pagecache still contains the new data.
2098 * Write some old data back, to prevent it from being used.
2099 * Use the non-SYNC fd; we know it will fail anyway.
2101 meta.mm_last_pg = metab.mm_last_pg;
2102 meta.mm_txnid = metab.mm_txnid;
2104 WriteFile(env->me_fd, ptr, len, NULL, &ov);
2106 r2 = pwrite(env->me_fd, ptr, len, off);
2108 env->me_flags |= MDB_FATAL_ERROR;
2111 /* Memory ordering issues are irrelevant; since the entire writer
2112 * is wrapped by wmutex, all of these changes will become visible
2113 * after the wmutex is unlocked. Since the DB is multi-version,
2114 * readers will get consistent data regardless of how fresh or
2115 * how stale their view of these values is.
2117 LAZY_MUTEX_LOCK(&env->me_txns->mti_mutex);
2118 txn->mt_env->me_txns->mti_me_toggle = toggle;
2119 txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
2120 LAZY_MUTEX_UNLOCK(&env->me_txns->mti_mutex);
2125 /** Check both meta pages to see which one is newer.
2126 * @param[in] env the environment handle
2127 * @param[out] which address of where to store the meta toggle ID
2128 * @return 0 on success, non-zero on failure.
2131 mdb_env_read_meta(MDB_env *env, int *which)
2135 assert(env != NULL);
2137 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
2140 DPRINTF("Using meta page %d", toggle);
2147 mdb_env_create(MDB_env **env)
2151 e = calloc(1, sizeof(MDB_env));
2155 e->me_free_pgs = mdb_midl_alloc();
2156 if (!e->me_free_pgs) {
2160 e->me_maxreaders = DEFAULT_READERS;
2162 e->me_fd = INVALID_HANDLE_VALUE;
2163 e->me_lfd = INVALID_HANDLE_VALUE;
2164 e->me_mfd = INVALID_HANDLE_VALUE;
2170 mdb_env_set_mapsize(MDB_env *env, size_t size)
2174 env->me_mapsize = size;
2176 env->me_maxpg = env->me_mapsize / env->me_psize;
2181 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
2185 env->me_maxdbs = dbs;
2190 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
2192 if (env->me_map || readers < 1)
2194 env->me_maxreaders = readers;
2199 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
2201 if (!env || !readers)
2203 *readers = env->me_maxreaders;
2207 /** Further setup required for opening an MDB environment
2210 mdb_env_open2(MDB_env *env, unsigned int flags)
2212 int i, newenv = 0, toggle;
2216 env->me_flags = flags;
2218 memset(&meta, 0, sizeof(meta));
2220 if ((i = mdb_env_read_header(env, &meta)) != 0) {
2223 DPUTS("new mdbenv");
2227 if (!env->me_mapsize) {
2228 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
2234 LONG sizelo, sizehi;
2235 sizelo = env->me_mapsize & 0xffffffff;
2236 sizehi = env->me_mapsize >> 16; /* pointless on WIN32, only needed on W64 */
2238 /* Windows won't create mappings for zero length files.
2239 * Just allocate the maxsize right now.
2242 SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
2243 if (!SetEndOfFile(env->me_fd))
2245 SetFilePointer(env->me_fd, 0, NULL, 0);
2247 mh = CreateFileMapping(env->me_fd, NULL, PAGE_READONLY,
2248 sizehi, sizelo, NULL);
2251 env->me_map = MapViewOfFileEx(mh, FILE_MAP_READ, 0, 0, env->me_mapsize,
2259 if (meta.mm_address && (flags & MDB_FIXEDMAP))
2261 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
2263 if (env->me_map == MAP_FAILED)
2268 meta.mm_mapsize = env->me_mapsize;
2269 if (flags & MDB_FIXEDMAP)
2270 meta.mm_address = env->me_map;
2271 i = mdb_env_init_meta(env, &meta);
2272 if (i != MDB_SUCCESS) {
2273 munmap(env->me_map, env->me_mapsize);
2277 env->me_psize = meta.mm_psize;
2279 env->me_maxpg = env->me_mapsize / env->me_psize;
2281 p = (MDB_page *)env->me_map;
2282 env->me_metas[0] = METADATA(p);
2283 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
2285 if ((i = mdb_env_read_meta(env, &toggle)) != 0)
2288 DPRINTF("opened database version %u, pagesize %u",
2289 env->me_metas[toggle]->mm_version, env->me_psize);
2290 DPRINTF("depth: %u", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_depth);
2291 DPRINTF("entries: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_entries);
2292 DPRINTF("branch pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_branch_pages);
2293 DPRINTF("leaf pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_leaf_pages);
2294 DPRINTF("overflow pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_overflow_pages);
2295 DPRINTF("root: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_root);
2301 /** Release a reader thread's slot in the reader lock table.
2302 * This function is called automatically when a thread exits.
2303 * Windows doesn't support destructor callbacks for thread-specific storage,
2304 * so this function is not compiled there.
2305 * @param[in] ptr This points to the slot in the reader lock table.
2308 mdb_env_reader_dest(void *ptr)
2310 MDB_reader *reader = ptr;
2312 reader->mr_txnid = 0;
2318 /** Downgrade the exclusive lock on the region back to shared */
2320 mdb_env_share_locks(MDB_env *env)
2324 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
2326 env->me_txns->mti_me_toggle = toggle;
2327 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
2332 /* First acquire a shared lock. The Unlock will
2333 * then release the existing exclusive lock.
2335 memset(&ov, 0, sizeof(ov));
2336 LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov);
2337 UnlockFile(env->me_lfd, 0, 0, 1, 0);
2341 struct flock lock_info;
2342 /* The shared lock replaces the existing lock */
2343 memset((void *)&lock_info, 0, sizeof(lock_info));
2344 lock_info.l_type = F_RDLCK;
2345 lock_info.l_whence = SEEK_SET;
2346 lock_info.l_start = 0;
2347 lock_info.l_len = 1;
2348 fcntl(env->me_lfd, F_SETLK, &lock_info);
2352 #if defined(_WIN32) || defined(__APPLE__)
2354 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
2356 * @(#) $Revision: 5.1 $
2357 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
2358 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
2360 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
2364 * Please do not copyright this code. This code is in the public domain.
2366 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
2367 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
2368 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
2369 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
2370 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
2371 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
2372 * PERFORMANCE OF THIS SOFTWARE.
2375 * chongo <Landon Curt Noll> /\oo/\
2376 * http://www.isthe.com/chongo/
2378 * Share and Enjoy! :-)
2381 typedef unsigned long long mdb_hash_t;
2382 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
2384 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
2385 * @param[in] str string to hash
2386 * @param[in] hval initial value for hash
2387 * @return 64 bit hash
2389 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
2390 * hval arg on the first call.
2393 mdb_hash_str(char *str, mdb_hash_t hval)
2395 unsigned char *s = (unsigned char *)str; /* unsigned string */
2397 * FNV-1a hash each octet of the string
2400 /* xor the bottom with the current octet */
2401 hval ^= (mdb_hash_t)*s++;
2403 /* multiply by the 64 bit FNV magic prime mod 2^64 */
2404 hval += (hval << 1) + (hval << 4) + (hval << 5) +
2405 (hval << 7) + (hval << 8) + (hval << 40);
2407 /* return our new hash value */
2411 /** Hash the string and output the hash in hex.
2412 * @param[in] str string to hash
2413 * @param[out] hexbuf an array of 17 chars to hold the hash
2416 mdb_hash_hex(char *str, char *hexbuf)
2419 mdb_hash_t h = mdb_hash_str(str, MDB_HASH_INIT);
2420 for (i=0; i<8; i++) {
2421 hexbuf += sprintf(hexbuf, "%02x", (unsigned int)h & 0xff);
2427 /** Open and/or initialize the lock region for the environment.
2428 * @param[in] env The MDB environment.
2429 * @param[in] lpath The pathname of the file used for the lock region.
2430 * @param[in] mode The Unix permissions for the file, if we create it.
2431 * @param[out] excl Set to true if we got an exclusive lock on the region.
2432 * @return 0 on success, non-zero on failure.
2435 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
2443 if ((env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
2444 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
2445 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
2449 /* Try to get exclusive lock. If we succeed, then
2450 * nobody is using the lock region and we should initialize it.
2453 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
2457 memset(&ov, 0, sizeof(ov));
2458 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
2464 size = GetFileSize(env->me_lfd, NULL);
2466 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
2470 /* Try to get exclusive lock. If we succeed, then
2471 * nobody is using the lock region and we should initialize it.
2474 struct flock lock_info;
2475 memset((void *)&lock_info, 0, sizeof(lock_info));
2476 lock_info.l_type = F_WRLCK;
2477 lock_info.l_whence = SEEK_SET;
2478 lock_info.l_start = 0;
2479 lock_info.l_len = 1;
2480 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
2484 lock_info.l_type = F_RDLCK;
2485 rc = fcntl(env->me_lfd, F_SETLKW, &lock_info);
2492 size = lseek(env->me_lfd, 0, SEEK_END);
2494 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
2495 if (size < rsize && *excl) {
2497 SetFilePointer(env->me_lfd, rsize, NULL, 0);
2498 if (!SetEndOfFile(env->me_lfd)) {
2503 if (ftruncate(env->me_lfd, rsize) != 0) {
2510 size = rsize - sizeof(MDB_txninfo);
2511 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
2516 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
2522 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
2524 if (!env->me_txns) {
2530 env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
2532 if (env->me_txns == MAP_FAILED) {
2540 if (!mdb_sec_inited) {
2541 InitializeSecurityDescriptor(&mdb_null_sd,
2542 SECURITY_DESCRIPTOR_REVISION);
2543 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
2544 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2545 mdb_all_sa.bInheritHandle = FALSE;
2546 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
2549 mdb_hash_hex(lpath, hexbuf);
2550 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", hexbuf);
2551 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
2552 if (!env->me_rmutex) {
2556 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", hexbuf);
2557 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
2558 if (!env->me_wmutex) {
2565 mdb_hash_hex(lpath, hexbuf);
2566 sprintf(env->me_txns->mti_rmname, "MDBr%s", hexbuf);
2567 if (sem_unlink(env->me_txns->mti_rmname)) {
2569 if (rc != ENOENT && rc != EINVAL)
2572 env->me_rmutex = sem_open(env->me_txns->mti_rmname, O_CREAT, mode, 1);
2573 if (!env->me_rmutex) {
2577 sprintf(env->me_txns->mti_wmname, "MDBw%s", hexbuf);
2578 if (sem_unlink(env->me_txns->mti_wmname)) {
2580 if (rc != ENOENT && rc != EINVAL)
2583 env->me_wmutex = sem_open(env->me_txns->mti_wmname, O_CREAT, mode, 1);
2584 if (!env->me_wmutex) {
2588 #else /* __APPLE__ */
2589 pthread_mutexattr_t mattr;
2591 pthread_mutexattr_init(&mattr);
2592 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
2596 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
2597 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
2598 #endif /* __APPLE__ */
2600 env->me_txns->mti_version = MDB_VERSION;
2601 env->me_txns->mti_magic = MDB_MAGIC;
2602 env->me_txns->mti_txnid = 0;
2603 env->me_txns->mti_numreaders = 0;
2604 env->me_txns->mti_me_toggle = 0;
2607 if (env->me_txns->mti_magic != MDB_MAGIC) {
2608 DPUTS("lock region has invalid magic");
2612 if (env->me_txns->mti_version != MDB_VERSION) {
2613 DPRINTF("lock region is version %u, expected version %u",
2614 env->me_txns->mti_version, MDB_VERSION);
2615 rc = MDB_VERSION_MISMATCH;
2619 if (rc != EACCES && rc != EAGAIN) {
2623 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
2624 if (!env->me_rmutex) {
2628 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
2629 if (!env->me_wmutex) {
2635 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
2636 if (!env->me_rmutex) {
2640 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
2641 if (!env->me_wmutex) {
2651 env->me_lfd = INVALID_HANDLE_VALUE;
2656 /** The name of the lock file in the DB environment */
2657 #define LOCKNAME "/lock.mdb"
2658 /** The name of the data file in the DB environment */
2659 #define DATANAME "/data.mdb"
2660 /** The suffix of the lock file when no subdir is used */
2661 #define LOCKSUFF "-lock"
2664 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
2666 int oflags, rc, len, excl;
2667 char *lpath, *dpath;
2670 if (flags & MDB_NOSUBDIR) {
2671 rc = len + sizeof(LOCKSUFF) + len + 1;
2673 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
2678 if (flags & MDB_NOSUBDIR) {
2679 dpath = lpath + len + sizeof(LOCKSUFF);
2680 sprintf(lpath, "%s" LOCKSUFF, path);
2681 strcpy(dpath, path);
2683 dpath = lpath + len + sizeof(LOCKNAME);
2684 sprintf(lpath, "%s" LOCKNAME, path);
2685 sprintf(dpath, "%s" DATANAME, path);
2688 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
2693 if (F_ISSET(flags, MDB_RDONLY)) {
2694 oflags = GENERIC_READ;
2695 len = OPEN_EXISTING;
2697 oflags = GENERIC_READ|GENERIC_WRITE;
2700 mode = FILE_ATTRIBUTE_NORMAL;
2701 if ((env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2702 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2707 if (F_ISSET(flags, MDB_RDONLY))
2710 oflags = O_RDWR | O_CREAT;
2712 if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
2718 if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
2719 /* synchronous fd for meta writes */
2721 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2722 mode |= FILE_FLAG_WRITE_THROUGH;
2723 if ((env->me_mfd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2724 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2729 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2730 oflags |= MDB_DSYNC;
2731 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
2736 env->me_path = strdup(path);
2737 DPRINTF("opened dbenv %p", (void *) env);
2738 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
2739 LAZY_RWLOCK_INIT(&env->me_dblock, NULL);
2741 mdb_env_share_locks(env);
2742 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
2743 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
2744 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
2750 if (env->me_fd != INVALID_HANDLE_VALUE) {
2752 env->me_fd = INVALID_HANDLE_VALUE;
2754 if (env->me_lfd != INVALID_HANDLE_VALUE) {
2756 env->me_lfd = INVALID_HANDLE_VALUE;
2764 mdb_env_close(MDB_env *env)
2771 while (env->me_dpages) {
2772 dp = env->me_dpages;
2773 env->me_dpages = dp->mp_next;
2777 free(env->me_dbs[1]);
2778 free(env->me_dbs[0]);
2782 LAZY_RWLOCK_DESTROY(&env->me_dblock);
2783 pthread_key_delete(env->me_txkey);
2786 munmap(env->me_map, env->me_mapsize);
2791 pid_t pid = getpid();
2793 for (i=0; i<env->me_txns->mti_numreaders; i++)
2794 if (env->me_txns->mti_readers[i].mr_pid == pid)
2795 env->me_txns->mti_readers[i].mr_pid = 0;
2796 munmap(env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
2799 mdb_midl_free(env->me_free_pgs);
2803 /** Compare two items pointing at aligned size_t's */
2805 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
2807 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
2808 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
2811 /** Compare two items pointing at aligned int's */
2813 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
2815 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
2816 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
2819 /** Compare two items pointing at ints of unknown alignment.
2820 * Nodes and keys are guaranteed to be 2-byte aligned.
2823 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
2825 #if BYTE_ORDER == LITTLE_ENDIAN
2826 unsigned short *u, *c;
2829 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
2830 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
2833 } while(!x && u > (unsigned short *)a->mv_data);
2836 return memcmp(a->mv_data, b->mv_data, a->mv_size);
2840 /** Compare two items lexically */
2842 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
2849 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
2855 diff = memcmp(a->mv_data, b->mv_data, len);
2856 return diff ? diff : len_diff<0 ? -1 : len_diff;
2859 /** Compare two items in reverse byte order */
2861 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
2863 const unsigned char *p1, *p2, *p1_lim;
2867 p1_lim = (const unsigned char *)a->mv_data;
2868 p1 = (const unsigned char *)a->mv_data + a->mv_size;
2869 p2 = (const unsigned char *)b->mv_data + b->mv_size;
2871 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
2877 while (p1 > p1_lim) {
2878 diff = *--p1 - *--p2;
2882 return len_diff<0 ? -1 : len_diff;
2885 /** Search for key within a page, using binary search.
2886 * Returns the smallest entry larger or equal to the key.
2887 * If exactp is non-null, stores whether the found entry was an exact match
2888 * in *exactp (1 or 0).
2889 * Updates the cursor index with the index of the found entry.
2890 * If no entry larger or equal to the key is found, returns NULL.
2893 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
2895 unsigned int i = 0, nkeys;
2898 MDB_page *mp = mc->mc_pg[mc->mc_top];
2899 MDB_node *node = NULL;
2904 nkeys = NUMKEYS(mp);
2906 DPRINTF("searching %u keys in %s %spage %zu",
2907 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
2912 low = IS_LEAF(mp) ? 0 : 1;
2914 cmp = mc->mc_dbx->md_cmp;
2916 /* Branch pages have no data, so if using integer keys,
2917 * alignment is guaranteed. Use faster mdb_cmp_int.
2919 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
2920 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
2927 nodekey.mv_size = mc->mc_db->md_pad;
2928 node = NODEPTR(mp, 0); /* fake */
2929 while (low <= high) {
2930 i = (low + high) >> 1;
2931 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
2932 rc = cmp(key, &nodekey);
2933 DPRINTF("found leaf index %u [%s], rc = %i",
2934 i, DKEY(&nodekey), rc);
2943 while (low <= high) {
2944 i = (low + high) >> 1;
2946 node = NODEPTR(mp, i);
2947 nodekey.mv_size = NODEKSZ(node);
2948 nodekey.mv_data = NODEKEY(node);
2950 rc = cmp(key, &nodekey);
2953 DPRINTF("found leaf index %u [%s], rc = %i",
2954 i, DKEY(&nodekey), rc);
2956 DPRINTF("found branch index %u [%s -> %zu], rc = %i",
2957 i, DKEY(&nodekey), NODEPGNO(node), rc);
2968 if (rc > 0) { /* Found entry is less than the key. */
2969 i++; /* Skip to get the smallest entry larger than key. */
2971 node = NODEPTR(mp, i);
2974 *exactp = (rc == 0);
2975 /* store the key index */
2976 mc->mc_ki[mc->mc_top] = i;
2978 /* There is no entry larger or equal to the key. */
2981 /* nodeptr is fake for LEAF2 */
2987 mdb_cursor_adjust(MDB_cursor *mc, func)
2991 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
2992 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
2999 /** Pop a page off the top of the cursor's stack. */
3001 mdb_cursor_pop(MDB_cursor *mc)
3006 top = mc->mc_pg[mc->mc_top];
3011 DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
3012 mc->mc_dbi, (void *) mc);
3016 /** Push a page onto the top of the cursor's stack. */
3018 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
3020 DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
3021 mc->mc_dbi, (void *) mc);
3023 if (mc->mc_snum >= CURSOR_STACK) {
3024 assert(mc->mc_snum < CURSOR_STACK);
3028 mc->mc_top = mc->mc_snum++;
3029 mc->mc_pg[mc->mc_top] = mp;
3030 mc->mc_ki[mc->mc_top] = 0;
3035 /** Find the address of the page corresponding to a given page number.
3036 * @param[in] txn the transaction for this access.
3037 * @param[in] pgno the page number for the page to retrieve.
3038 * @param[out] ret address of a pointer where the page's address will be stored.
3039 * @return 0 on success, non-zero on failure.
3042 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
3046 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
3048 x = mdb_mid2l_search(txn->mt_u.dirty_list, pgno);
3049 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
3050 p = txn->mt_u.dirty_list[x].mptr;
3054 if (pgno <= txn->mt_env->me_metas[txn->mt_toggle]->mm_last_pg)
3055 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
3059 DPRINTF("page %zu not found", pgno);
3062 return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
3065 /** Search for the page a given key should be in.
3066 * Pushes parent pages on the cursor stack. This function continues a
3067 * search on a cursor that has already been initialized. (Usually by
3068 * #mdb_page_search() but also by #mdb_node_move().)
3069 * @param[in,out] mc the cursor for this operation.
3070 * @param[in] key the key to search for. If NULL, search for the lowest
3071 * page. (This is used by #mdb_cursor_first().)
3072 * @param[in] modify If true, visited pages are updated with new page numbers.
3073 * @return 0 on success, non-zero on failure.
3076 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
3078 MDB_page *mp = mc->mc_pg[mc->mc_top];
3083 while (IS_BRANCH(mp)) {
3087 DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
3088 assert(NUMKEYS(mp) > 1);
3089 DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
3091 if (key == NULL) /* Initialize cursor to first page. */
3093 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
3094 /* cursor to last page */
3098 node = mdb_node_search(mc, key, &exact);
3100 i = NUMKEYS(mp) - 1;
3102 i = mc->mc_ki[mc->mc_top];
3111 DPRINTF("following index %u for key [%s]",
3113 assert(i < NUMKEYS(mp));
3114 node = NODEPTR(mp, i);
3116 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp)))
3119 mc->mc_ki[mc->mc_top] = i;
3120 if ((rc = mdb_cursor_push(mc, mp)))
3124 if ((rc = mdb_page_touch(mc)) != 0)
3126 mp = mc->mc_pg[mc->mc_top];
3131 DPRINTF("internal error, index points to a %02X page!?",
3133 return MDB_CORRUPTED;
3136 DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
3137 key ? DKEY(key) : NULL);
3142 /** Search for the page a given key should be in.
3143 * Pushes parent pages on the cursor stack. This function just sets up
3144 * the search; it finds the root page for \b mc's database and sets this
3145 * as the root of the cursor's stack. Then #mdb_page_search_root() is
3146 * called to complete the search.
3147 * @param[in,out] mc the cursor for this operation.
3148 * @param[in] key the key to search for. If NULL, search for the lowest
3149 * page. (This is used by #mdb_cursor_first().)
3150 * @param[in] modify If true, visited pages are updated with new page numbers.
3151 * @return 0 on success, non-zero on failure.
3154 mdb_page_search(MDB_cursor *mc, MDB_val *key, int modify)
3159 /* Make sure the txn is still viable, then find the root from
3160 * the txn's db table.
3162 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
3163 DPUTS("transaction has failed, must abort");
3166 /* Make sure we're using an up-to-date root */
3167 if (mc->mc_dbi > MAIN_DBI) {
3168 if ((*mc->mc_dbflag & DB_STALE) ||
3169 (modify && !(*mc->mc_dbflag & DB_DIRTY))) {
3171 unsigned char dbflag = 0;
3172 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
3173 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, modify);
3176 if (*mc->mc_dbflag & DB_STALE) {
3179 MDB_node *leaf = mdb_node_search(&mc2,
3180 &mc->mc_dbx->md_name, &exact);
3182 return MDB_NOTFOUND;
3183 mdb_node_read(mc->mc_txn, leaf, &data);
3184 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
3188 *mc->mc_dbflag = dbflag;
3191 root = mc->mc_db->md_root;
3193 if (root == P_INVALID) { /* Tree is empty. */
3194 DPUTS("tree is empty");
3195 return MDB_NOTFOUND;
3199 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0])))
3205 DPRINTF("db %u root page %zu has flags 0x%X",
3206 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
3209 if ((rc = mdb_page_touch(mc)))
3213 return mdb_page_search_root(mc, key, modify);
3216 /** Return the data associated with a given node.
3217 * @param[in] txn The transaction for this operation.
3218 * @param[in] leaf The node being read.
3219 * @param[out] data Updated to point to the node's data.
3220 * @return 0 on success, non-zero on failure.
3223 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
3225 MDB_page *omp; /* overflow page */
3229 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
3230 data->mv_size = NODEDSZ(leaf);
3231 data->mv_data = NODEDATA(leaf);
3235 /* Read overflow data.
3237 data->mv_size = NODEDSZ(leaf);
3238 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
3239 if ((rc = mdb_page_get(txn, pgno, &omp))) {
3240 DPRINTF("read overflow page %zu failed", pgno);
3243 data->mv_data = METADATA(omp);
3249 mdb_get(MDB_txn *txn, MDB_dbi dbi,
3250 MDB_val *key, MDB_val *data)
3259 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
3261 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3264 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3268 mdb_cursor_init(&mc, txn, dbi, &mx);
3269 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
3272 /** Find a sibling for a page.
3273 * Replaces the page at the top of the cursor's stack with the
3274 * specified sibling, if one exists.
3275 * @param[in] mc The cursor for this operation.
3276 * @param[in] move_right Non-zero if the right sibling is requested,
3277 * otherwise the left sibling.
3278 * @return 0 on success, non-zero on failure.
3281 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
3287 if (mc->mc_snum < 2) {
3288 return MDB_NOTFOUND; /* root has no siblings */
3292 DPRINTF("parent page is page %zu, index %u",
3293 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]);
3295 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
3296 : (mc->mc_ki[mc->mc_top] == 0)) {
3297 DPRINTF("no more keys left, moving to %s sibling",
3298 move_right ? "right" : "left");
3299 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS)
3303 mc->mc_ki[mc->mc_top]++;
3305 mc->mc_ki[mc->mc_top]--;
3306 DPRINTF("just moving to %s index key %u",
3307 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]);
3309 assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
3311 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3312 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp)))
3315 mdb_cursor_push(mc, mp);
3320 /** Move the cursor to the next data item. */
3322 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3328 if (mc->mc_flags & C_EOF) {
3329 return MDB_NOTFOUND;
3332 assert(mc->mc_flags & C_INITIALIZED);
3334 mp = mc->mc_pg[mc->mc_top];
3336 if (mc->mc_db->md_flags & MDB_DUPSORT) {
3337 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3338 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3339 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
3340 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
3341 if (op != MDB_NEXT || rc == MDB_SUCCESS)
3345 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3346 if (op == MDB_NEXT_DUP)
3347 return MDB_NOTFOUND;
3351 DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3353 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
3354 DPUTS("=====> move to next sibling page");
3355 if (mdb_cursor_sibling(mc, 1) != MDB_SUCCESS) {
3356 mc->mc_flags |= C_EOF;
3357 mc->mc_flags &= ~C_INITIALIZED;
3358 return MDB_NOTFOUND;
3360 mp = mc->mc_pg[mc->mc_top];
3361 DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3363 mc->mc_ki[mc->mc_top]++;
3365 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3366 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3369 key->mv_size = mc->mc_db->md_pad;
3370 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3374 assert(IS_LEAF(mp));
3375 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3377 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3378 mdb_xcursor_init1(mc, leaf);
3381 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3384 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3385 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3386 if (rc != MDB_SUCCESS)
3391 MDB_SET_KEY(leaf, key);
3395 /** Move the cursor to the previous data item. */
3397 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3403 assert(mc->mc_flags & C_INITIALIZED);
3405 mp = mc->mc_pg[mc->mc_top];
3407 if (mc->mc_db->md_flags & MDB_DUPSORT) {
3408 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3409 if (op == MDB_PREV || op == MDB_PREV_DUP) {
3410 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3411 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
3412 if (op != MDB_PREV || rc == MDB_SUCCESS)
3415 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3416 if (op == MDB_PREV_DUP)
3417 return MDB_NOTFOUND;
3422 DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3424 if (mc->mc_ki[mc->mc_top] == 0) {
3425 DPUTS("=====> move to prev sibling page");
3426 if (mdb_cursor_sibling(mc, 0) != MDB_SUCCESS) {
3427 mc->mc_flags &= ~C_INITIALIZED;
3428 return MDB_NOTFOUND;
3430 mp = mc->mc_pg[mc->mc_top];
3431 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
3432 DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3434 mc->mc_ki[mc->mc_top]--;
3436 mc->mc_flags &= ~C_EOF;
3438 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3439 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3442 key->mv_size = mc->mc_db->md_pad;
3443 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3447 assert(IS_LEAF(mp));
3448 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3450 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3451 mdb_xcursor_init1(mc, leaf);
3454 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3457 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3458 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3459 if (rc != MDB_SUCCESS)
3464 MDB_SET_KEY(leaf, key);
3468 /** Set the cursor on a specific data item. */
3470 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3471 MDB_cursor_op op, int *exactp)
3480 assert(key->mv_size > 0);
3482 /* See if we're already on the right page */
3483 if (mc->mc_flags & C_INITIALIZED) {
3486 mp = mc->mc_pg[mc->mc_top];
3488 mc->mc_ki[mc->mc_top] = 0;
3489 return MDB_NOTFOUND;
3491 if (mp->mp_flags & P_LEAF2) {
3492 nodekey.mv_size = mc->mc_db->md_pad;
3493 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
3495 leaf = NODEPTR(mp, 0);
3496 MDB_SET_KEY(leaf, &nodekey);
3498 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3500 /* Probably happens rarely, but first node on the page
3501 * was the one we wanted.
3503 mc->mc_ki[mc->mc_top] = 0;
3504 leaf = NODEPTR(mp, 0);
3511 unsigned int nkeys = NUMKEYS(mp);
3513 if (mp->mp_flags & P_LEAF2) {
3514 nodekey.mv_data = LEAF2KEY(mp,
3515 nkeys-1, nodekey.mv_size);
3517 leaf = NODEPTR(mp, nkeys-1);
3518 MDB_SET_KEY(leaf, &nodekey);
3520 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3522 /* last node was the one we wanted */
3523 mc->mc_ki[mc->mc_top] = nkeys-1;
3524 leaf = NODEPTR(mp, nkeys-1);
3530 /* This is definitely the right page, skip search_page */
3535 /* If any parents have right-sibs, search.
3536 * Otherwise, there's nothing further.
3538 for (i=0; i<mc->mc_top; i++)
3540 NUMKEYS(mc->mc_pg[i])-1)
3542 if (i == mc->mc_top) {
3543 /* There are no other pages */
3544 mc->mc_ki[mc->mc_top] = nkeys;
3545 return MDB_NOTFOUND;
3549 /* There are no other pages */
3550 mc->mc_ki[mc->mc_top] = 0;
3551 return MDB_NOTFOUND;
3555 rc = mdb_page_search(mc, key, 0);
3556 if (rc != MDB_SUCCESS)
3559 mp = mc->mc_pg[mc->mc_top];
3560 assert(IS_LEAF(mp));
3563 leaf = mdb_node_search(mc, key, exactp);
3564 if (exactp != NULL && !*exactp) {
3565 /* MDB_SET specified and not an exact match. */
3566 return MDB_NOTFOUND;
3570 DPUTS("===> inexact leaf not found, goto sibling");
3571 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
3572 return rc; /* no entries matched */
3573 mp = mc->mc_pg[mc->mc_top];
3574 assert(IS_LEAF(mp));
3575 leaf = NODEPTR(mp, 0);
3579 mc->mc_flags |= C_INITIALIZED;
3580 mc->mc_flags &= ~C_EOF;
3583 key->mv_size = mc->mc_db->md_pad;
3584 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3588 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3589 mdb_xcursor_init1(mc, leaf);
3592 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3593 if (op == MDB_SET || op == MDB_SET_RANGE) {
3594 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3597 if (op == MDB_GET_BOTH) {
3603 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
3604 if (rc != MDB_SUCCESS)
3607 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
3609 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
3611 rc = mc->mc_dbx->md_dcmp(data, &d2);
3613 if (op == MDB_GET_BOTH || rc > 0)
3614 return MDB_NOTFOUND;
3619 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3620 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3625 /* The key already matches in all other cases */
3626 if (op == MDB_SET_RANGE)
3627 MDB_SET_KEY(leaf, key);
3628 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
3633 /** Move the cursor to the first item in the database. */
3635 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3640 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3641 rc = mdb_page_search(mc, NULL, 0);
3642 if (rc != MDB_SUCCESS)
3645 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3647 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
3648 mc->mc_flags |= C_INITIALIZED;
3649 mc->mc_flags &= ~C_EOF;
3651 mc->mc_ki[mc->mc_top] = 0;
3653 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3654 key->mv_size = mc->mc_db->md_pad;
3655 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
3660 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3661 mdb_xcursor_init1(mc, leaf);
3662 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3667 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3668 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3672 MDB_SET_KEY(leaf, key);
3676 /** Move the cursor to the last item in the database. */
3678 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3684 lkey.mv_size = MAXKEYSIZE+1;
3685 lkey.mv_data = NULL;
3687 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3688 rc = mdb_page_search(mc, &lkey, 0);
3689 if (rc != MDB_SUCCESS)
3692 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3694 leaf = NODEPTR(mc->mc_pg[mc->mc_top], NUMKEYS(mc->mc_pg[mc->mc_top])-1);
3695 mc->mc_flags |= C_INITIALIZED;
3696 mc->mc_flags &= ~C_EOF;
3698 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
3700 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3701 key->mv_size = mc->mc_db->md_pad;
3702 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
3707 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3708 mdb_xcursor_init1(mc, leaf);
3709 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3714 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3715 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3720 MDB_SET_KEY(leaf, key);
3725 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3735 case MDB_GET_BOTH_RANGE:
3736 if (data == NULL || mc->mc_xcursor == NULL) {
3743 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3745 } else if (op == MDB_SET_RANGE)
3746 rc = mdb_cursor_set(mc, key, data, op, NULL);
3748 rc = mdb_cursor_set(mc, key, data, op, &exact);
3750 case MDB_GET_MULTIPLE:
3752 !(mc->mc_db->md_flags & MDB_DUPFIXED) ||
3753 !(mc->mc_flags & C_INITIALIZED)) {
3758 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
3759 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
3762 case MDB_NEXT_MULTIPLE:
3764 !(mc->mc_db->md_flags & MDB_DUPFIXED)) {
3768 if (!(mc->mc_flags & C_INITIALIZED))
3769 rc = mdb_cursor_first(mc, key, data);
3771 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
3772 if (rc == MDB_SUCCESS) {
3773 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
3776 mx = &mc->mc_xcursor->mx_cursor;
3777 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
3779 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
3780 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
3788 case MDB_NEXT_NODUP:
3789 if (!(mc->mc_flags & C_INITIALIZED))
3790 rc = mdb_cursor_first(mc, key, data);
3792 rc = mdb_cursor_next(mc, key, data, op);
3796 case MDB_PREV_NODUP:
3797 if (!(mc->mc_flags & C_INITIALIZED) || (mc->mc_flags & C_EOF))
3798 rc = mdb_cursor_last(mc, key, data);
3800 rc = mdb_cursor_prev(mc, key, data, op);
3803 rc = mdb_cursor_first(mc, key, data);
3807 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
3808 !(mc->mc_flags & C_INITIALIZED) ||
3809 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3813 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3816 rc = mdb_cursor_last(mc, key, data);
3820 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
3821 !(mc->mc_flags & C_INITIALIZED) ||
3822 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3826 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3829 DPRINTF("unhandled/unimplemented cursor operation %u", op);
3837 /** Touch all the pages in the cursor stack.
3838 * Makes sure all the pages are writable, before attempting a write operation.
3839 * @param[in] mc The cursor to operate on.
3842 mdb_cursor_touch(MDB_cursor *mc)
3846 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
3848 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
3849 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 1);
3852 *mc->mc_dbflag = DB_DIRTY;
3854 for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
3855 rc = mdb_page_touch(mc);
3859 mc->mc_top = mc->mc_snum-1;
3864 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3867 MDB_node *leaf = NULL;
3868 MDB_val xdata, *rdata, dkey;
3874 char pbuf[PAGESIZE];
3875 char dbuf[MAXKEYSIZE+1];
3878 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
3881 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
3882 mc->mc_dbi, DKEY(key), key ? key->mv_size:0, data->mv_size);
3886 if (flags == MDB_CURRENT) {
3887 if (!(mc->mc_flags & C_INITIALIZED))
3890 } else if (mc->mc_db->md_root == P_INVALID) {
3892 /* new database, write a root leaf page */
3893 DPUTS("allocating new root leaf page");
3894 if ((np = mdb_page_new(mc, P_LEAF, 1)) == NULL) {
3898 mdb_cursor_push(mc, np);
3899 mc->mc_db->md_root = np->mp_pgno;
3900 mc->mc_db->md_depth++;
3901 *mc->mc_dbflag = DB_DIRTY;
3902 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
3904 np->mp_flags |= P_LEAF2;
3905 mc->mc_flags |= C_INITIALIZED;
3911 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
3912 if (flags == MDB_NOOVERWRITE && rc == 0) {
3913 DPRINTF("duplicate key [%s]", DKEY(key));
3915 return MDB_KEYEXIST;
3917 if (rc && rc != MDB_NOTFOUND)
3921 /* Cursor is positioned, now make sure all pages are writable */
3922 rc2 = mdb_cursor_touch(mc);
3927 /* The key already exists */
3928 if (rc == MDB_SUCCESS) {
3929 /* there's only a key anyway, so this is a no-op */
3930 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3931 unsigned int ksize = mc->mc_db->md_pad;
3932 if (key->mv_size != ksize)
3934 if (flags == MDB_CURRENT) {
3935 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
3936 memcpy(ptr, key->mv_data, ksize);
3941 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3944 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
3945 /* Was a single item before, must convert now */
3946 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3947 /* Just overwrite the current item */
3948 if (flags == MDB_CURRENT)
3951 dkey.mv_size = NODEDSZ(leaf);
3952 dkey.mv_data = NODEDATA(leaf);
3953 /* data matches, ignore it */
3954 if (!mc->mc_dbx->md_dcmp(data, &dkey))
3955 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
3957 /* create a fake page for the dup items */
3958 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
3959 dkey.mv_data = dbuf;
3960 fp = (MDB_page *)pbuf;
3961 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
3962 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
3963 fp->mp_lower = PAGEHDRSZ;
3964 fp->mp_upper = PAGEHDRSZ + dkey.mv_size + data->mv_size;
3965 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
3966 fp->mp_flags |= P_LEAF2;
3967 fp->mp_pad = data->mv_size;
3969 fp->mp_upper += 2 * sizeof(indx_t) + 2 * NODESIZE +
3970 (dkey.mv_size & 1) + (data->mv_size & 1);
3972 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
3975 xdata.mv_size = fp->mp_upper;
3976 xdata.mv_data = pbuf;
3980 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
3981 /* See if we need to convert from fake page to subDB */
3983 unsigned int offset;
3986 fp = NODEDATA(leaf);
3987 if (flags == MDB_CURRENT) {
3988 fp->mp_flags |= P_DIRTY;
3989 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
3990 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
3994 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
3995 offset = fp->mp_pad;
3997 offset = NODESIZE + sizeof(indx_t) + data->mv_size;
3999 offset += offset & 1;
4000 if (NODESIZE + sizeof(indx_t) + NODEKSZ(leaf) + NODEDSZ(leaf) +
4001 offset >= (mc->mc_txn->mt_env->me_psize - PAGEHDRSZ) /
4003 /* yes, convert it */
4005 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4006 dummy.md_pad = fp->mp_pad;
4007 dummy.md_flags = MDB_DUPFIXED;
4008 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
4009 dummy.md_flags |= MDB_INTEGERKEY;
4012 dummy.md_branch_pages = 0;
4013 dummy.md_leaf_pages = 1;
4014 dummy.md_overflow_pages = 0;
4015 dummy.md_entries = NUMKEYS(fp);
4017 xdata.mv_size = sizeof(MDB_db);
4018 xdata.mv_data = &dummy;
4019 mp = mdb_page_alloc(mc, 1);
4022 offset = mc->mc_txn->mt_env->me_psize - NODEDSZ(leaf);
4023 flags |= F_DUPDATA|F_SUBDATA;
4024 dummy.md_root = mp->mp_pgno;
4026 /* no, just grow it */
4028 xdata.mv_size = NODEDSZ(leaf) + offset;
4029 xdata.mv_data = pbuf;
4030 mp = (MDB_page *)pbuf;
4031 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4034 mp->mp_flags = fp->mp_flags | P_DIRTY;
4035 mp->mp_pad = fp->mp_pad;
4036 mp->mp_lower = fp->mp_lower;
4037 mp->mp_upper = fp->mp_upper + offset;
4039 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
4041 nsize = NODEDSZ(leaf) - fp->mp_upper;
4042 memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper, nsize);
4043 for (i=0; i<NUMKEYS(fp); i++)
4044 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
4046 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4050 /* data is on sub-DB, just store it */
4051 flags |= F_DUPDATA|F_SUBDATA;
4055 /* same size, just replace it */
4056 if (!F_ISSET(leaf->mn_flags, F_BIGDATA) &&
4057 NODEDSZ(leaf) == data->mv_size) {
4058 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
4061 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4063 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
4069 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
4070 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
4071 rc = mdb_page_split(mc, key, rdata, P_INVALID);
4073 /* There is room already in this leaf page. */
4074 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, 0);
4075 if (rc == 0 && !do_sub) {
4076 /* Adjust other cursors pointing to mp */
4077 MDB_cursor *m2, *m3;
4078 MDB_dbi dbi = mc->mc_dbi;
4079 unsigned i = mc->mc_top;
4080 MDB_page *mp = mc->mc_pg[i];
4082 if (mc->mc_flags & C_SUB)
4085 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
4086 if (mc->mc_flags & C_SUB)
4087 m3 = &m2->mc_xcursor->mx_cursor;
4090 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
4097 if (rc != MDB_SUCCESS)
4098 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4100 /* Remember if we just added a subdatabase */
4101 if (flags & (F_SUBDATA|F_DUPDATA)) {
4102 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4103 leaf->mn_flags |= (flags & (F_SUBDATA|F_DUPDATA));
4106 /* Now store the actual data in the child DB. Note that we're
4107 * storing the user data in the keys field, so there are strict
4108 * size limits on dupdata. The actual data fields of the child
4109 * DB are all zero size.
4117 if (flags & MDB_CURRENT) {
4118 xflags = MDB_CURRENT;
4120 mdb_xcursor_init1(mc, leaf);
4121 xflags = (flags & MDB_NODUPDATA) ? MDB_NOOVERWRITE : 0;
4123 /* converted, write the original data first */
4125 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
4129 /* Adjust other cursors pointing to mp */
4131 unsigned i = mc->mc_top;
4132 MDB_page *mp = mc->mc_pg[i];
4134 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4135 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
4136 mdb_xcursor_init1(m2, leaf);
4141 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
4142 if (flags & F_SUBDATA) {
4143 db = NODEDATA(leaf);
4144 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4147 /* sub-writes might have failed so check rc again.
4148 * Don't increment count if we just replaced an existing item.
4150 if (!rc && !(flags & MDB_CURRENT))
4151 mc->mc_db->md_entries++;
4158 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
4163 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
4166 if (!mc->mc_flags & C_INITIALIZED)
4169 rc = mdb_cursor_touch(mc);
4173 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4175 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4176 if (flags != MDB_NODUPDATA) {
4177 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
4178 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
4180 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
4181 /* If sub-DB still has entries, we're done */
4182 if (mc->mc_xcursor->mx_db.md_entries) {
4183 if (leaf->mn_flags & F_SUBDATA) {
4184 /* update subDB info */
4185 MDB_db *db = NODEDATA(leaf);
4186 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4188 /* shrink fake page */
4189 mdb_node_shrink(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4191 mc->mc_db->md_entries--;
4194 /* otherwise fall thru and delete the sub-DB */
4197 if (leaf->mn_flags & F_SUBDATA) {
4198 /* add all the child DB's pages to the free list */
4199 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
4200 if (rc == MDB_SUCCESS) {
4201 mc->mc_db->md_entries -=
4202 mc->mc_xcursor->mx_db.md_entries;
4207 return mdb_cursor_del0(mc, leaf);
4210 /** Allocate and initialize new pages for a database.
4211 * @param[in] mc a cursor on the database being added to.
4212 * @param[in] flags flags defining what type of page is being allocated.
4213 * @param[in] num the number of pages to allocate. This is usually 1,
4214 * unless allocating overflow pages for a large record.
4215 * @return Address of a page, or NULL on failure.
4218 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num)
4222 if ((np = mdb_page_alloc(mc, num)) == NULL)
4224 DPRINTF("allocated new mpage %zu, page size %u",
4225 np->mp_pgno, mc->mc_txn->mt_env->me_psize);
4226 np->mp_flags = flags | P_DIRTY;
4227 np->mp_lower = PAGEHDRSZ;
4228 np->mp_upper = mc->mc_txn->mt_env->me_psize;
4231 mc->mc_db->md_branch_pages++;
4232 else if (IS_LEAF(np))
4233 mc->mc_db->md_leaf_pages++;
4234 else if (IS_OVERFLOW(np)) {
4235 mc->mc_db->md_overflow_pages += num;
4242 /** Calculate the size of a leaf node.
4243 * The size depends on the environment's page size; if a data item
4244 * is too large it will be put onto an overflow page and the node
4245 * size will only include the key and not the data. Sizes are always
4246 * rounded up to an even number of bytes, to guarantee 2-byte alignment
4247 * of the #MDB_node headers.
4248 * @param[in] env The environment handle.
4249 * @param[in] key The key for the node.
4250 * @param[in] data The data for the node.
4251 * @return The number of bytes needed to store the node.
4254 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
4258 sz = LEAFSIZE(key, data);
4259 if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
4260 /* put on overflow page */
4261 sz -= data->mv_size - sizeof(pgno_t);
4265 return sz + sizeof(indx_t);
4268 /** Calculate the size of a branch node.
4269 * The size should depend on the environment's page size but since
4270 * we currently don't support spilling large keys onto overflow
4271 * pages, it's simply the size of the #MDB_node header plus the
4272 * size of the key. Sizes are always rounded up to an even number
4273 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
4274 * @param[in] env The environment handle.
4275 * @param[in] key The key for the node.
4276 * @return The number of bytes needed to store the node.
4279 mdb_branch_size(MDB_env *env, MDB_val *key)
4284 if (sz >= env->me_psize / MDB_MINKEYS) {
4285 /* put on overflow page */
4286 /* not implemented */
4287 /* sz -= key->size - sizeof(pgno_t); */
4290 return sz + sizeof(indx_t);
4293 /** Add a node to the page pointed to by the cursor.
4294 * @param[in] mc The cursor for this operation.
4295 * @param[in] indx The index on the page where the new node should be added.
4296 * @param[in] key The key for the new node.
4297 * @param[in] data The data for the new node, if any.
4298 * @param[in] pgno The page number, if adding a branch node.
4299 * @param[in] flags Flags for the node.
4300 * @return 0 on success, non-zero on failure. Possible errors are:
4302 * <li>ENOMEM - failed to allocate overflow pages for the node.
4303 * <li>ENOSPC - there is insufficient room in the page. This error
4304 * should never happen since all callers already calculate the
4305 * page's free space before calling this function.
4309 mdb_node_add(MDB_cursor *mc, indx_t indx,
4310 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags)
4313 size_t node_size = NODESIZE;
4316 MDB_page *mp = mc->mc_pg[mc->mc_top];
4317 MDB_page *ofp = NULL; /* overflow page */
4320 assert(mp->mp_upper >= mp->mp_lower);
4322 DPRINTF("add to %s %spage %zu index %i, data size %zu key size %zu [%s]",
4323 IS_LEAF(mp) ? "leaf" : "branch",
4324 IS_SUBP(mp) ? "sub-" : "",
4325 mp->mp_pgno, indx, data ? data->mv_size : 0,
4326 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
4329 /* Move higher keys up one slot. */
4330 int ksize = mc->mc_db->md_pad, dif;
4331 char *ptr = LEAF2KEY(mp, indx, ksize);
4332 dif = NUMKEYS(mp) - indx;
4334 memmove(ptr+ksize, ptr, dif*ksize);
4335 /* insert new key */
4336 memcpy(ptr, key->mv_data, ksize);
4338 /* Just using these for counting */
4339 mp->mp_lower += sizeof(indx_t);
4340 mp->mp_upper -= ksize - sizeof(indx_t);
4345 node_size += key->mv_size;
4349 if (F_ISSET(flags, F_BIGDATA)) {
4350 /* Data already on overflow page. */
4351 node_size += sizeof(pgno_t);
4352 } else if (data->mv_size >= mc->mc_txn->mt_env->me_psize / MDB_MINKEYS) {
4353 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
4354 /* Put data on overflow page. */
4355 DPRINTF("data size is %zu, put on overflow page",
4357 node_size += sizeof(pgno_t);
4358 if ((ofp = mdb_page_new(mc, P_OVERFLOW, ovpages)) == NULL)
4360 DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
4363 node_size += data->mv_size;
4366 node_size += node_size & 1;
4368 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
4369 DPRINTF("not enough room in page %zu, got %u ptrs",
4370 mp->mp_pgno, NUMKEYS(mp));
4371 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
4372 mp->mp_upper - mp->mp_lower);
4373 DPRINTF("node size = %zu", node_size);
4377 /* Move higher pointers up one slot. */
4378 for (i = NUMKEYS(mp); i > indx; i--)
4379 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
4381 /* Adjust free space offsets. */
4382 ofs = mp->mp_upper - node_size;
4383 assert(ofs >= mp->mp_lower + sizeof(indx_t));
4384 mp->mp_ptrs[indx] = ofs;
4386 mp->mp_lower += sizeof(indx_t);
4388 /* Write the node data. */
4389 node = NODEPTR(mp, indx);
4390 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
4391 node->mn_flags = flags;
4393 SETDSZ(node,data->mv_size);
4398 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
4403 if (F_ISSET(flags, F_BIGDATA))
4404 memcpy(node->mn_data + key->mv_size, data->mv_data,
4407 memcpy(node->mn_data + key->mv_size, data->mv_data,
4410 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
4412 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
4419 /** Delete the specified node from a page.
4420 * @param[in] mp The page to operate on.
4421 * @param[in] indx The index of the node to delete.
4422 * @param[in] ksize The size of a node. Only used if the page is
4423 * part of a #MDB_DUPFIXED database.
4426 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
4429 indx_t i, j, numkeys, ptr;
4433 DPRINTF("delete node %u on %s page %zu", indx,
4434 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
4435 assert(indx < NUMKEYS(mp));
4438 int x = NUMKEYS(mp) - 1 - indx;
4439 base = LEAF2KEY(mp, indx, ksize);
4441 memmove(base, base + ksize, x * ksize);
4442 mp->mp_lower -= sizeof(indx_t);
4443 mp->mp_upper += ksize - sizeof(indx_t);
4447 node = NODEPTR(mp, indx);
4448 sz = NODESIZE + node->mn_ksize;
4450 if (F_ISSET(node->mn_flags, F_BIGDATA))
4451 sz += sizeof(pgno_t);
4453 sz += NODEDSZ(node);
4457 ptr = mp->mp_ptrs[indx];
4458 numkeys = NUMKEYS(mp);
4459 for (i = j = 0; i < numkeys; i++) {
4461 mp->mp_ptrs[j] = mp->mp_ptrs[i];
4462 if (mp->mp_ptrs[i] < ptr)
4463 mp->mp_ptrs[j] += sz;
4468 base = (char *)mp + mp->mp_upper;
4469 memmove(base + sz, base, ptr - mp->mp_upper);
4471 mp->mp_lower -= sizeof(indx_t);
4475 /** Compact the main page after deleting a node on a subpage.
4476 * @param[in] mp The main page to operate on.
4477 * @param[in] indx The index of the subpage on the main page.
4480 mdb_node_shrink(MDB_page *mp, indx_t indx)
4487 indx_t i, numkeys, ptr;
4489 node = NODEPTR(mp, indx);
4490 sp = (MDB_page *)NODEDATA(node);
4491 osize = NODEDSZ(node);
4493 delta = sp->mp_upper - sp->mp_lower;
4494 SETDSZ(node, osize - delta);
4495 xp = (MDB_page *)((char *)sp + delta);
4497 /* shift subpage upward */
4499 nsize = NUMKEYS(sp) * sp->mp_pad;
4500 memmove(METADATA(xp), METADATA(sp), nsize);
4503 nsize = osize - sp->mp_upper;
4504 numkeys = NUMKEYS(sp);
4505 for (i=numkeys-1; i>=0; i--)
4506 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
4508 xp->mp_upper = sp->mp_lower;
4509 xp->mp_lower = sp->mp_lower;
4510 xp->mp_flags = sp->mp_flags;
4511 xp->mp_pad = sp->mp_pad;
4512 xp->mp_pgno = mp->mp_pgno;
4514 /* shift lower nodes upward */
4515 ptr = mp->mp_ptrs[indx];
4516 numkeys = NUMKEYS(mp);
4517 for (i = 0; i < numkeys; i++) {
4518 if (mp->mp_ptrs[i] <= ptr)
4519 mp->mp_ptrs[i] += delta;
4522 base = (char *)mp + mp->mp_upper;
4523 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
4524 mp->mp_upper += delta;
4527 /** Initial setup of a sorted-dups cursor.
4528 * Sorted duplicates are implemented as a sub-database for the given key.
4529 * The duplicate data items are actually keys of the sub-database.
4530 * Operations on the duplicate data items are performed using a sub-cursor
4531 * initialized when the sub-database is first accessed. This function does
4532 * the preliminary setup of the sub-cursor, filling in the fields that
4533 * depend only on the parent DB.
4534 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4537 mdb_xcursor_init0(MDB_cursor *mc)
4539 MDB_xcursor *mx = mc->mc_xcursor;
4541 mx->mx_cursor.mc_xcursor = NULL;
4542 mx->mx_cursor.mc_txn = mc->mc_txn;
4543 mx->mx_cursor.mc_db = &mx->mx_db;
4544 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
4545 mx->mx_cursor.mc_dbi = mc->mc_dbi+1;
4546 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
4547 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
4548 mx->mx_dbx.md_dcmp = NULL;
4549 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
4552 /** Final setup of a sorted-dups cursor.
4553 * Sets up the fields that depend on the data from the main cursor.
4554 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4555 * @param[in] node The data containing the #MDB_db record for the
4556 * sorted-dup database.
4559 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
4561 MDB_xcursor *mx = mc->mc_xcursor;
4563 if (node->mn_flags & F_SUBDATA) {
4564 MDB_db *db = NODEDATA(node);
4566 mx->mx_cursor.mc_snum = 0;
4567 mx->mx_cursor.mc_flags = C_SUB;
4569 MDB_page *fp = NODEDATA(node);
4570 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
4571 mx->mx_db.md_flags = 0;
4572 mx->mx_db.md_depth = 1;
4573 mx->mx_db.md_branch_pages = 0;
4574 mx->mx_db.md_leaf_pages = 1;
4575 mx->mx_db.md_overflow_pages = 0;
4576 mx->mx_db.md_entries = NUMKEYS(fp);
4577 mx->mx_db.md_root = fp->mp_pgno;
4578 mx->mx_cursor.mc_snum = 1;
4579 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
4580 mx->mx_cursor.mc_top = 0;
4581 mx->mx_cursor.mc_pg[0] = fp;
4582 mx->mx_cursor.mc_ki[0] = 0;
4583 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4584 mx->mx_db.md_flags = MDB_DUPFIXED;
4585 mx->mx_db.md_pad = fp->mp_pad;
4586 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
4587 mx->mx_db.md_flags |= MDB_INTEGERKEY;
4590 DPRINTF("Sub-db %u for db %u root page %zu", mx->mx_cursor.mc_dbi, mc->mc_dbi,
4592 mx->mx_dbflag = (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY)) ?
4594 mx->mx_dbx.md_name.mv_data = NODEKEY(node);
4595 mx->mx_dbx.md_name.mv_size = node->mn_ksize;
4596 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
4597 mx->mx_dbx.md_cmp = mdb_cmp_long;
4600 /** Initialize a cursor for a given transaction and database. */
4602 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
4607 mc->mc_db = &txn->mt_dbs[dbi];
4608 mc->mc_dbx = &txn->mt_dbxs[dbi];
4609 mc->mc_dbflag = &txn->mt_dbflags[dbi];
4612 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4614 mc->mc_xcursor = mx;
4615 mdb_xcursor_init0(mc);
4617 mc->mc_xcursor = NULL;
4622 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
4625 MDB_xcursor *mx = NULL;
4626 size_t size = sizeof(MDB_cursor);
4628 if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
4631 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
4632 size += sizeof(MDB_xcursor);
4634 if ((mc = malloc(size)) != NULL) {
4635 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4636 mx = (MDB_xcursor *)(mc + 1);
4638 mdb_cursor_init(mc, txn, dbi, mx);
4639 if (txn->mt_cursors) {
4640 mc->mc_next = txn->mt_cursors[dbi];
4641 txn->mt_cursors[dbi] = mc;
4643 mc->mc_flags |= C_ALLOCD;
4653 /* Return the count of duplicate data items for the current key */
4655 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
4659 if (mc == NULL || countp == NULL)
4662 if (!(mc->mc_db->md_flags & MDB_DUPSORT))
4665 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4666 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4669 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
4672 *countp = mc->mc_xcursor->mx_db.md_entries;
4678 mdb_cursor_close(MDB_cursor *mc)
4681 /* remove from txn, if tracked */
4682 if (mc->mc_txn->mt_cursors) {
4683 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
4684 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
4686 *prev = mc->mc_next;
4688 if (mc->mc_flags & C_ALLOCD)
4693 /** Replace the key for a node with a new key.
4694 * @param[in] mp The page containing the node to operate on.
4695 * @param[in] indx The index of the node to operate on.
4696 * @param[in] key The new key to use.
4697 * @return 0 on success, non-zero on failure.
4700 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
4702 indx_t ptr, i, numkeys;
4709 node = NODEPTR(mp, indx);
4710 ptr = mp->mp_ptrs[indx];
4711 DPRINTF("update key %u (ofs %u) [%.*s] to [%s] on page %zu",
4713 (int)node->mn_ksize, (char *)NODEKEY(node),
4717 delta = key->mv_size - node->mn_ksize;
4719 if (delta > 0 && SIZELEFT(mp) < delta) {
4720 DPRINTF("OUCH! Not enough room, delta = %d", delta);
4724 numkeys = NUMKEYS(mp);
4725 for (i = 0; i < numkeys; i++) {
4726 if (mp->mp_ptrs[i] <= ptr)
4727 mp->mp_ptrs[i] -= delta;
4730 base = (char *)mp + mp->mp_upper;
4731 len = ptr - mp->mp_upper + NODESIZE;
4732 memmove(base - delta, base, len);
4733 mp->mp_upper -= delta;
4735 node = NODEPTR(mp, indx);
4736 node->mn_ksize = key->mv_size;
4739 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
4744 /** Move a node from csrc to cdst.
4747 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
4754 /* Mark src and dst as dirty. */
4755 if ((rc = mdb_page_touch(csrc)) ||
4756 (rc = mdb_page_touch(cdst)))
4759 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4760 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
4761 key.mv_size = csrc->mc_db->md_pad;
4762 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
4764 data.mv_data = NULL;
4766 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
4767 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
4768 unsigned int snum = csrc->mc_snum;
4770 /* must find the lowest key below src */
4771 mdb_page_search_root(csrc, NULL, 0);
4772 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
4773 key.mv_size = NODEKSZ(s2);
4774 key.mv_data = NODEKEY(s2);
4775 csrc->mc_snum = snum--;
4776 csrc->mc_top = snum;
4778 key.mv_size = NODEKSZ(srcnode);
4779 key.mv_data = NODEKEY(srcnode);
4781 data.mv_size = NODEDSZ(srcnode);
4782 data.mv_data = NODEDATA(srcnode);
4784 DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
4785 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
4786 csrc->mc_ki[csrc->mc_top],
4788 csrc->mc_pg[csrc->mc_top]->mp_pgno,
4789 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
4791 /* Add the node to the destination page.
4793 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, NODEPGNO(srcnode),
4795 if (rc != MDB_SUCCESS)
4798 /* Delete the node from the source page.
4800 mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
4803 /* Adjust other cursors pointing to mp */
4804 MDB_cursor *m2, *m3;
4805 MDB_dbi dbi = csrc->mc_dbi;
4806 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
4808 if (csrc->mc_flags & C_SUB)
4811 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
4812 if (csrc->mc_flags & C_SUB)
4813 m3 = &m2->mc_xcursor->mx_cursor;
4816 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
4817 csrc->mc_ki[csrc->mc_top]) {
4818 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
4819 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
4824 /* Update the parent separators.
4826 if (csrc->mc_ki[csrc->mc_top] == 0) {
4827 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
4828 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4829 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
4831 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
4832 key.mv_size = NODEKSZ(srcnode);
4833 key.mv_data = NODEKEY(srcnode);
4835 DPRINTF("update separator for source page %zu to [%s]",
4836 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
4837 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1],
4838 &key)) != MDB_SUCCESS)
4841 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
4843 nullkey.mv_size = 0;
4844 rc = mdb_update_key(csrc->mc_pg[csrc->mc_top], 0, &nullkey);
4845 assert(rc == MDB_SUCCESS);
4849 if (cdst->mc_ki[cdst->mc_top] == 0) {
4850 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
4851 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4852 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
4854 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
4855 key.mv_size = NODEKSZ(srcnode);
4856 key.mv_data = NODEKEY(srcnode);
4858 DPRINTF("update separator for destination page %zu to [%s]",
4859 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
4860 if ((rc = mdb_update_key(cdst->mc_pg[cdst->mc_top-1], cdst->mc_ki[cdst->mc_top-1],
4861 &key)) != MDB_SUCCESS)
4864 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
4866 nullkey.mv_size = 0;
4867 rc = mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &nullkey);
4868 assert(rc == MDB_SUCCESS);
4875 /** Merge one page into another.
4876 * The nodes from the page pointed to by \b csrc will
4877 * be copied to the page pointed to by \b cdst and then
4878 * the \b csrc page will be freed.
4879 * @param[in] csrc Cursor pointing to the source page.
4880 * @param[in] cdst Cursor pointing to the destination page.
4883 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
4891 DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
4892 cdst->mc_pg[cdst->mc_top]->mp_pgno);
4894 assert(csrc->mc_snum > 1); /* can't merge root page */
4895 assert(cdst->mc_snum > 1);
4897 /* Mark dst as dirty. */
4898 if ((rc = mdb_page_touch(cdst)))
4901 /* Move all nodes from src to dst.
4903 j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
4904 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4905 key.mv_size = csrc->mc_db->md_pad;
4906 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
4907 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
4908 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
4909 if (rc != MDB_SUCCESS)
4911 key.mv_data = (char *)key.mv_data + key.mv_size;
4914 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
4915 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
4917 key.mv_size = srcnode->mn_ksize;
4918 key.mv_data = NODEKEY(srcnode);
4919 data.mv_size = NODEDSZ(srcnode);
4920 data.mv_data = NODEDATA(srcnode);
4921 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
4922 if (rc != MDB_SUCCESS)
4927 DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
4928 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);
4930 /* Unlink the src page from parent and add to free list.
4932 mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
4933 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
4935 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], 0, &key)) != MDB_SUCCESS)
4939 mdb_midl_append(&csrc->mc_txn->mt_free_pgs, csrc->mc_pg[csrc->mc_top]->mp_pgno);
4940 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
4941 csrc->mc_db->md_leaf_pages--;
4943 csrc->mc_db->md_branch_pages--;
4945 /* Adjust other cursors pointing to mp */
4946 MDB_cursor *m2, *m3;
4947 MDB_dbi dbi = csrc->mc_dbi;
4948 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
4950 if (csrc->mc_flags & C_SUB)
4953 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
4954 if (csrc->mc_flags & C_SUB)
4955 m3 = &m2->mc_xcursor->mx_cursor;
4958 if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
4959 m3->mc_pg[csrc->mc_top] = mp;
4960 m3->mc_ki[csrc->mc_top] += nkeys;
4964 mdb_cursor_pop(csrc);
4966 return mdb_rebalance(csrc);
4969 /** Copy the contents of a cursor.
4970 * @param[in] csrc The cursor to copy from.
4971 * @param[out] cdst The cursor to copy to.
4974 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
4978 cdst->mc_txn = csrc->mc_txn;
4979 cdst->mc_dbi = csrc->mc_dbi;
4980 cdst->mc_db = csrc->mc_db;
4981 cdst->mc_dbx = csrc->mc_dbx;
4982 cdst->mc_snum = csrc->mc_snum;
4983 cdst->mc_top = csrc->mc_top;
4984 cdst->mc_flags = csrc->mc_flags;
4986 for (i=0; i<csrc->mc_snum; i++) {
4987 cdst->mc_pg[i] = csrc->mc_pg[i];
4988 cdst->mc_ki[i] = csrc->mc_ki[i];
4992 /** Rebalance the tree after a delete operation.
4993 * @param[in] mc Cursor pointing to the page where rebalancing
4995 * @return 0 on success, non-zero on failure.
4998 mdb_rebalance(MDB_cursor *mc)
5005 DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
5006 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
5007 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);
5009 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD) {
5010 DPRINTF("no need to rebalance page %zu, above fill threshold",
5011 mc->mc_pg[mc->mc_top]->mp_pgno);
5015 if (mc->mc_snum < 2) {
5016 MDB_page *mp = mc->mc_pg[0];
5017 if (NUMKEYS(mp) == 0) {
5018 DPUTS("tree is completely empty");
5019 mc->mc_db->md_root = P_INVALID;
5020 mc->mc_db->md_depth = 0;
5021 mc->mc_db->md_leaf_pages = 0;
5022 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5026 /* Adjust other cursors pointing to mp */
5027 MDB_cursor *m2, *m3;
5028 MDB_dbi dbi = mc->mc_dbi;
5030 if (mc->mc_flags & C_SUB)
5033 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5034 if (mc->mc_flags & C_SUB)
5035 m3 = &m2->mc_xcursor->mx_cursor;
5038 if (m3->mc_pg[0] == mp) {
5044 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
5045 DPUTS("collapsing root page!");
5046 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5047 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
5048 if ((rc = mdb_page_get(mc->mc_txn, mc->mc_db->md_root,
5051 mc->mc_db->md_depth--;
5052 mc->mc_db->md_branch_pages--;
5054 /* Adjust other cursors pointing to mp */
5055 MDB_cursor *m2, *m3;
5056 MDB_dbi dbi = mc->mc_dbi;
5058 if (mc->mc_flags & C_SUB)
5061 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5062 if (mc->mc_flags & C_SUB)
5063 m3 = &m2->mc_xcursor->mx_cursor;
5066 if (m3->mc_pg[0] == mp) {
5067 m3->mc_pg[0] = mc->mc_pg[0];
5072 DPUTS("root page doesn't need rebalancing");
5076 /* The parent (branch page) must have at least 2 pointers,
5077 * otherwise the tree is invalid.
5079 ptop = mc->mc_top-1;
5080 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
5082 /* Leaf page fill factor is below the threshold.
5083 * Try to move keys from left or right neighbor, or
5084 * merge with a neighbor page.
5089 mdb_cursor_copy(mc, &mn);
5090 mn.mc_xcursor = NULL;
5092 if (mc->mc_ki[ptop] == 0) {
5093 /* We're the leftmost leaf in our parent.
5095 DPUTS("reading right neighbor");
5097 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5098 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5100 mn.mc_ki[mn.mc_top] = 0;
5101 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
5103 /* There is at least one neighbor to the left.
5105 DPUTS("reading left neighbor");
5107 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5108 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5110 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
5111 mc->mc_ki[mc->mc_top] = 0;
5114 DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
5115 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);
5117 /* If the neighbor page is above threshold and has at least two
5118 * keys, move one key from it.
5120 * Otherwise we should try to merge them.
5122 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) >= 2)
5123 return mdb_node_move(&mn, mc);
5124 else { /* FIXME: if (has_enough_room()) */
5125 mc->mc_flags &= ~C_INITIALIZED;
5126 if (mc->mc_ki[ptop] == 0)
5127 return mdb_page_merge(&mn, mc);
5129 return mdb_page_merge(mc, &mn);
5133 /** Complete a delete operation started by #mdb_cursor_del(). */
5135 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
5139 /* add overflow pages to free list */
5140 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5144 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
5145 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
5146 for (i=0; i<ovpages; i++) {
5147 DPRINTF("freed ov page %zu", pg);
5148 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
5152 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], mc->mc_db->md_pad);
5153 mc->mc_db->md_entries--;
5154 rc = mdb_rebalance(mc);
5155 if (rc != MDB_SUCCESS)
5156 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5162 mdb_del(MDB_txn *txn, MDB_dbi dbi,
5163 MDB_val *key, MDB_val *data)
5168 MDB_val rdata, *xdata;
5172 assert(key != NULL);
5174 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
5176 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5179 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
5183 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
5187 mdb_cursor_init(&mc, txn, dbi, &mx);
5198 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
5200 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
5204 /** Split a page and insert a new node.
5205 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
5206 * The cursor will be updated to point to the actual page and index where
5207 * the node got inserted after the split.
5208 * @param[in] newkey The key for the newly inserted node.
5209 * @param[in] newdata The data for the newly inserted node.
5210 * @param[in] newpgno The page number, if the new node is a branch node.
5211 * @return 0 on success, non-zero on failure.
5214 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno)
5217 int rc = MDB_SUCCESS, ins_new = 0, new_root = 0;
5220 unsigned int i, j, split_indx, nkeys, pmax;
5222 MDB_val sepkey, rkey, rdata;
5224 MDB_page *mp, *rp, *pp;
5229 mp = mc->mc_pg[mc->mc_top];
5230 newindx = mc->mc_ki[mc->mc_top];
5232 DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
5233 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
5234 DKEY(newkey), mc->mc_ki[mc->mc_top]);
5236 if (mc->mc_snum < 2) {
5237 if ((pp = mdb_page_new(mc, P_BRANCH, 1)) == NULL)
5239 /* shift current top to make room for new parent */
5240 mc->mc_pg[1] = mc->mc_pg[0];
5241 mc->mc_ki[1] = mc->mc_ki[0];
5244 mc->mc_db->md_root = pp->mp_pgno;
5245 DPRINTF("root split! new root = %zu", pp->mp_pgno);
5246 mc->mc_db->md_depth++;
5249 /* Add left (implicit) pointer. */
5250 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
5251 /* undo the pre-push */
5252 mc->mc_pg[0] = mc->mc_pg[1];
5253 mc->mc_ki[0] = mc->mc_ki[1];
5254 mc->mc_db->md_root = mp->mp_pgno;
5255 mc->mc_db->md_depth--;
5262 ptop = mc->mc_top-1;
5263 DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
5266 /* Create a right sibling. */
5267 if ((rp = mdb_page_new(mc, mp->mp_flags, 1)) == NULL)
5269 mdb_cursor_copy(mc, &mn);
5270 mn.mc_pg[mn.mc_top] = rp;
5271 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
5272 DPRINTF("new right sibling: page %zu", rp->mp_pgno);
5274 nkeys = NUMKEYS(mp);
5275 split_indx = nkeys / 2 + 1;
5280 unsigned int lsize, rsize, ksize;
5281 /* Move half of the keys to the right sibling */
5283 x = mc->mc_ki[mc->mc_top] - split_indx;
5284 ksize = mc->mc_db->md_pad;
5285 split = LEAF2KEY(mp, split_indx, ksize);
5286 rsize = (nkeys - split_indx) * ksize;
5287 lsize = (nkeys - split_indx) * sizeof(indx_t);
5288 mp->mp_lower -= lsize;
5289 rp->mp_lower += lsize;
5290 mp->mp_upper += rsize - lsize;
5291 rp->mp_upper -= rsize - lsize;
5292 sepkey.mv_size = ksize;
5293 if (newindx == split_indx) {
5294 sepkey.mv_data = newkey->mv_data;
5296 sepkey.mv_data = split;
5299 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
5300 memcpy(rp->mp_ptrs, split, rsize);
5301 sepkey.mv_data = rp->mp_ptrs;
5302 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
5303 memcpy(ins, newkey->mv_data, ksize);
5304 mp->mp_lower += sizeof(indx_t);
5305 mp->mp_upper -= ksize - sizeof(indx_t);
5308 memcpy(rp->mp_ptrs, split, x * ksize);
5309 ins = LEAF2KEY(rp, x, ksize);
5310 memcpy(ins, newkey->mv_data, ksize);
5311 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
5312 rp->mp_lower += sizeof(indx_t);
5313 rp->mp_upper -= ksize - sizeof(indx_t);
5314 mc->mc_ki[mc->mc_top] = x;
5315 mc->mc_pg[mc->mc_top] = rp;
5320 /* For leaf pages, check the split point based on what
5321 * fits where, since otherwise add_node can fail.
5324 unsigned int psize, nsize;
5325 /* Maximum free space in an empty page */
5326 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
5327 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
5328 if (newindx < split_indx) {
5330 for (i=0; i<split_indx; i++) {
5331 node = NODEPTR(mp, i);
5332 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
5333 if (F_ISSET(node->mn_flags, F_BIGDATA))
5334 psize += sizeof(pgno_t);
5336 psize += NODEDSZ(node);
5345 for (i=nkeys-1; i>=split_indx; i--) {
5346 node = NODEPTR(mp, i);
5347 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
5348 if (F_ISSET(node->mn_flags, F_BIGDATA))
5349 psize += sizeof(pgno_t);
5351 psize += NODEDSZ(node);
5361 /* First find the separating key between the split pages.
5363 if (newindx == split_indx) {
5364 sepkey.mv_size = newkey->mv_size;
5365 sepkey.mv_data = newkey->mv_data;
5367 node = NODEPTR(mp, split_indx);
5368 sepkey.mv_size = node->mn_ksize;
5369 sepkey.mv_data = NODEKEY(node);
5373 DPRINTF("separator is [%s]", DKEY(&sepkey));
5375 /* Copy separator key to the parent.
5377 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
5380 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno);
5382 /* Right page might now have changed parent.
5383 * Check if left page also changed parent.
5385 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
5386 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
5387 mc->mc_pg[ptop] = mn.mc_pg[ptop];
5388 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
5392 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
5395 if (rc != MDB_SUCCESS) {
5402 /* Move half of the keys to the right sibling. */
5404 /* grab a page to hold a temporary copy */
5405 copy = mdb_page_malloc(mc);
5409 copy->mp_pgno = mp->mp_pgno;
5410 copy->mp_flags = mp->mp_flags;
5411 copy->mp_lower = PAGEHDRSZ;
5412 copy->mp_upper = mc->mc_txn->mt_env->me_psize;
5413 mc->mc_pg[mc->mc_top] = copy;
5414 for (i = j = 0; i <= nkeys; j++) {
5415 if (i == split_indx) {
5416 /* Insert in right sibling. */
5417 /* Reset insert index for right sibling. */
5418 j = (i == newindx && ins_new);
5419 mc->mc_pg[mc->mc_top] = rp;
5422 if (i == newindx && !ins_new) {
5423 /* Insert the original entry that caused the split. */
5424 rkey.mv_data = newkey->mv_data;
5425 rkey.mv_size = newkey->mv_size;
5427 rdata.mv_data = newdata->mv_data;
5428 rdata.mv_size = newdata->mv_size;
5435 /* Update page and index for the new key. */
5436 mc->mc_ki[mc->mc_top] = j;
5437 } else if (i == nkeys) {
5440 node = NODEPTR(mp, i);
5441 rkey.mv_data = NODEKEY(node);
5442 rkey.mv_size = node->mn_ksize;
5444 rdata.mv_data = NODEDATA(node);
5445 rdata.mv_size = NODEDSZ(node);
5447 pgno = NODEPGNO(node);
5448 flags = node->mn_flags;
5453 if (!IS_LEAF(mp) && j == 0) {
5454 /* First branch index doesn't need key data. */
5458 rc = mdb_node_add(mc, j, &rkey, &rdata, pgno, flags);
5461 /* reset back to original page */
5462 if (newindx < split_indx)
5463 mc->mc_pg[mc->mc_top] = mp;
5465 nkeys = NUMKEYS(copy);
5466 for (i=0; i<nkeys; i++)
5467 mp->mp_ptrs[i] = copy->mp_ptrs[i];
5468 mp->mp_lower = copy->mp_lower;
5469 mp->mp_upper = copy->mp_upper;
5470 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
5471 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
5473 /* return tmp page to freelist */
5474 copy->mp_next = mc->mc_txn->mt_env->me_dpages;
5475 mc->mc_txn->mt_env->me_dpages = copy;
5478 /* Adjust other cursors pointing to mp */
5479 MDB_cursor *m2, *m3;
5480 MDB_dbi dbi = mc->mc_dbi;
5482 if (mc->mc_flags & C_SUB)
5485 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5486 if (mc->mc_flags & C_SUB)
5487 m3 = &m2->mc_xcursor->mx_cursor;
5492 for (i=m3->mc_top; i>0; i--) {
5493 m3->mc_ki[i+1] = m3->mc_ki[i];
5494 m3->mc_pg[i+1] = m3->mc_pg[i];
5496 m3->mc_ki[0] = mc->mc_ki[0];
5497 m3->mc_pg[0] = mc->mc_pg[0];
5501 if (m3->mc_pg[mc->mc_top] == mp) {
5502 if (m3->mc_ki[m3->mc_top] >= split_indx) {
5503 m3->mc_pg[m3->mc_top] = rp;
5504 m3->mc_ki[m3->mc_top] -= split_indx;
5513 mdb_put(MDB_txn *txn, MDB_dbi dbi,
5514 MDB_val *key, MDB_val *data, unsigned int flags)
5519 assert(key != NULL);
5520 assert(data != NULL);
5522 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5525 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
5529 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
5533 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA)) != flags)
5536 mdb_cursor_init(&mc, txn, dbi, &mx);
5537 return mdb_cursor_put(&mc, key, data, flags);
5540 /** Only a subset of the @ref mdb_env flags can be changed
5541 * at runtime. Changing other flags requires closing the environment
5542 * and re-opening it with the new flags.
5544 #define CHANGEABLE (MDB_NOSYNC)
5546 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
5548 if ((flag & CHANGEABLE) != flag)
5551 env->me_flags |= flag;
5553 env->me_flags &= ~flag;
5558 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
5563 *arg = env->me_flags;
5568 mdb_env_get_path(MDB_env *env, const char **arg)
5573 *arg = env->me_path;
5577 /** Common code for #mdb_stat() and #mdb_env_stat().
5578 * @param[in] env the environment to operate in.
5579 * @param[in] db the #MDB_db record containing the stats to return.
5580 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
5581 * @return 0, this function always succeeds.
5584 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
5586 arg->ms_psize = env->me_psize;
5587 arg->ms_depth = db->md_depth;
5588 arg->ms_branch_pages = db->md_branch_pages;
5589 arg->ms_leaf_pages = db->md_leaf_pages;
5590 arg->ms_overflow_pages = db->md_overflow_pages;
5591 arg->ms_entries = db->md_entries;
5596 mdb_env_stat(MDB_env *env, MDB_stat *arg)
5600 if (env == NULL || arg == NULL)
5603 mdb_env_read_meta(env, &toggle);
5605 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
5608 /** Set the default comparison functions for a database.
5609 * Called immediately after a database is opened to set the defaults.
5610 * The user can then override them with #mdb_set_compare() or
5611 * #mdb_set_dupsort().
5612 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
5613 * @param[in] dbi A database handle returned by #mdb_open()
5616 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
5618 if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEKEY)
5619 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memnr;
5620 else if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERKEY)
5621 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_cint;
5623 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memn;
5625 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
5626 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP) {
5627 if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED)
5628 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_int;
5630 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_cint;
5631 } else if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEDUP) {
5632 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memnr;
5634 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memn;
5637 txn->mt_dbxs[dbi].md_dcmp = NULL;
5641 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
5646 int rc, dbflag, exact;
5649 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
5650 mdb_default_cmp(txn, FREE_DBI);
5656 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
5657 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
5658 mdb_default_cmp(txn, MAIN_DBI);
5662 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
5663 mdb_default_cmp(txn, MAIN_DBI);
5666 /* Is the DB already open? */
5668 for (i=2; i<txn->mt_numdbs; i++) {
5669 if (len == txn->mt_dbxs[i].md_name.mv_size &&
5670 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
5676 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
5679 /* Find the DB info */
5683 key.mv_data = (void *)name;
5684 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
5685 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
5686 if (rc == MDB_SUCCESS) {
5687 /* make sure this is actually a DB */
5688 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
5689 if (!(node->mn_flags & F_SUBDATA))
5691 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
5692 /* Create if requested */
5694 data.mv_size = sizeof(MDB_db);
5695 data.mv_data = &dummy;
5696 memset(&dummy, 0, sizeof(dummy));
5697 dummy.md_root = P_INVALID;
5698 dummy.md_flags = flags & 0xffff;
5699 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
5703 /* OK, got info, add to table */
5704 if (rc == MDB_SUCCESS) {
5705 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
5706 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
5707 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
5708 txn->mt_dbflags[txn->mt_numdbs] = dbflag;
5709 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
5710 *dbi = txn->mt_numdbs;
5711 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
5712 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
5713 mdb_default_cmp(txn, txn->mt_numdbs);
5720 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
5722 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
5725 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
5728 void mdb_close(MDB_env *env, MDB_dbi dbi)
5731 if (dbi <= MAIN_DBI || dbi >= env->me_numdbs)
5733 ptr = env->me_dbxs[dbi].md_name.mv_data;
5734 env->me_dbxs[dbi].md_name.mv_data = NULL;
5735 env->me_dbxs[dbi].md_name.mv_size = 0;
5739 /** Add all the DB's pages to the free list.
5740 * @param[in] mc Cursor on the DB to free.
5741 * @param[in] subs non-Zero to check for sub-DBs in this DB.
5742 * @return 0 on success, non-zero on failure.
5745 mdb_drop0(MDB_cursor *mc, int subs)
5749 rc = mdb_page_search(mc, NULL, 0);
5750 if (rc == MDB_SUCCESS) {
5755 /* LEAF2 pages have no nodes, cannot have sub-DBs */
5756 if (!subs || IS_LEAF2(mc->mc_pg[mc->mc_top]))
5759 mdb_cursor_copy(mc, &mx);
5760 while (mc->mc_snum > 0) {
5761 if (IS_LEAF(mc->mc_pg[mc->mc_top])) {
5762 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
5763 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
5764 if (ni->mn_flags & F_SUBDATA) {
5765 mdb_xcursor_init1(mc, ni);
5766 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
5772 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
5774 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
5777 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
5782 rc = mdb_cursor_sibling(mc, 1);
5784 /* no more siblings, go back to beginning
5785 * of previous level. (stack was already popped
5786 * by mdb_cursor_sibling)
5788 for (i=1; i<mc->mc_top; i++)
5789 mc->mc_pg[i] = mx.mc_pg[i];
5793 mdb_midl_append(&mc->mc_txn->mt_free_pgs,
5794 mc->mc_db->md_root);
5799 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
5804 if (!txn || !dbi || dbi >= txn->mt_numdbs)
5807 rc = mdb_cursor_open(txn, dbi, &mc);
5811 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
5813 mdb_cursor_close(mc);
5816 /* Can't delete the main DB */
5817 if (del && dbi > MAIN_DBI) {
5818 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
5820 mdb_close(txn->mt_env, dbi);
5822 txn->mt_dbflags[dbi] |= DB_DIRTY;
5823 txn->mt_dbs[dbi].md_depth = 0;
5824 txn->mt_dbs[dbi].md_branch_pages = 0;
5825 txn->mt_dbs[dbi].md_leaf_pages = 0;
5826 txn->mt_dbs[dbi].md_overflow_pages = 0;
5827 txn->mt_dbs[dbi].md_entries = 0;
5828 txn->mt_dbs[dbi].md_root = P_INVALID;
5830 mdb_cursor_close(mc);
5834 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
5836 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5839 txn->mt_dbxs[dbi].md_cmp = cmp;
5843 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
5845 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5848 txn->mt_dbxs[dbi].md_dcmp = cmp;
5852 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
5854 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5857 txn->mt_dbxs[dbi].md_rel = rel;
5861 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
5863 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5866 txn->mt_dbxs[dbi].md_relctx = ctx;