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 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
69 /* Solaris just defines one or the other */
70 # define LITTLE_ENDIAN 1234
71 # define BIG_ENDIAN 4321
72 # ifdef _LITTLE_ENDIAN
73 # define BYTE_ORDER LITTLE_ENDIAN
75 # define BYTE_ORDER BIG_ENDIAN
78 # define BYTE_ORDER __BYTE_ORDER
83 #define LITTLE_ENDIAN __LITTLE_ENDIAN
86 #define BIG_ENDIAN __BIG_ENDIAN
89 #if defined(__i386) || defined(__x86_64)
90 #define MISALIGNED_OK 1
96 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
97 # error "Unknown or unsupported endianness (BYTE_ORDER)"
98 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
99 # error "Two's complement, reasonably sized integer types, please"
102 /** @defgroup internal MDB Internals
105 /** @defgroup compat Windows Compatibility Macros
106 * A bunch of macros to minimize the amount of platform-specific ifdefs
107 * needed throughout the rest of the code. When the features this library
108 * needs are similar enough to POSIX to be hidden in a one-or-two line
109 * replacement, this macro approach is used.
113 #define pthread_t DWORD
114 #define pthread_mutex_t HANDLE
115 #define pthread_key_t DWORD
116 #define pthread_self() GetCurrentThreadId()
117 #define pthread_key_create(x,y) (*(x) = TlsAlloc())
118 #define pthread_key_delete(x) TlsFree(x)
119 #define pthread_getspecific(x) TlsGetValue(x)
120 #define pthread_setspecific(x,y) TlsSetValue(x,y)
121 #define pthread_mutex_unlock(x) ReleaseMutex(x)
122 #define pthread_mutex_lock(x) WaitForSingleObject(x, INFINITE)
123 #define LOCK_MUTEX_R(env) pthread_mutex_lock((env)->me_rmutex)
124 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock((env)->me_rmutex)
125 #define LOCK_MUTEX_W(env) pthread_mutex_lock((env)->me_wmutex)
126 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock((env)->me_wmutex)
127 #define getpid() GetCurrentProcessId()
128 #define fdatasync(fd) (!FlushFileBuffers(fd))
129 #define ErrCode() GetLastError()
130 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
131 #define close(fd) CloseHandle(fd)
132 #define munmap(ptr,len) UnmapViewOfFile(ptr)
135 #define LOCK_MUTEX_R(env) sem_wait((env)->me_rmutex)
136 #define UNLOCK_MUTEX_R(env) sem_post((env)->me_rmutex)
137 #define LOCK_MUTEX_W(env) sem_wait((env)->me_wmutex)
138 #define UNLOCK_MUTEX_W(env) sem_post((env)->me_wmutex)
139 #define fdatasync(fd) fsync(fd)
142 #define fdatasync(fd) fsync(fd)
144 /** Lock the reader mutex.
146 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
147 /** Unlock the reader mutex.
149 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
151 /** Lock the writer mutex.
152 * Only a single write transaction is allowed at a time. Other writers
153 * will block waiting for this mutex.
155 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
156 /** Unlock the writer mutex.
158 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
159 #endif /* __APPLE__ */
161 /** Get the error code for the last failed system function.
163 #define ErrCode() errno
165 /** An abstraction for a file handle.
166 * On POSIX systems file handles are small integers. On Windows
167 * they're opaque pointers.
171 /** A value for an invalid file handle.
172 * Mainly used to initialize file variables and signify that they are
175 #define INVALID_HANDLE_VALUE (-1)
177 /** Get the size of a memory page for the system.
178 * This is the basic size that the platform's memory manager uses, and is
179 * fundamental to the use of memory-mapped files.
181 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
184 #if defined(_WIN32) || defined(__APPLE__)
191 /** A flag for opening a file and requesting synchronous data writes.
192 * This is only used when writing a meta page. It's not strictly needed;
193 * we could just do a normal write and then immediately perform a flush.
194 * But if this flag is available it saves us an extra system call.
196 * @note If O_DSYNC is undefined but exists in /usr/include,
197 * preferably set some compiler flag to get the definition.
198 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
201 # define MDB_DSYNC O_DSYNC
205 /** A page number in the database.
206 * Note that 64 bit page numbers are overkill, since pages themselves
207 * already represent 12-13 bits of addressable memory, and the OS will
208 * always limit applications to a maximum of 63 bits of address space.
210 * @note In the #MDB_node structure, we only store 48 bits of this value,
211 * which thus limits us to only 60 bits of addressable data.
215 /** A transaction ID.
216 * See struct MDB_txn.mt_txnid for details.
220 /** @defgroup debug Debug Macros
224 /** Enable debug output.
225 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
226 * read from and written to the database (used for free space management).
231 #if !(__STDC_VERSION__ >= 199901L || defined(__GNUC__))
232 # define DPRINTF (void) /* Vararg macros may be unsupported */
234 /** Print a debug message with printf formatting. */
235 # define DPRINTF(fmt, ...) /**< Requires 2 or more args */ \
236 fprintf(stderr, "%s:%d " fmt "\n", __func__, __LINE__, __VA_ARGS__)
238 # define DPRINTF(fmt, ...) ((void) 0)
240 /** Print a debug string.
241 * The string is printed literally, with no format processing.
243 #define DPUTS(arg) DPRINTF("%s", arg)
246 /** A default memory page size.
247 * The actual size is platform-dependent, but we use this for
248 * boot-strapping. We probably should not be using this any more.
249 * The #GET_PAGESIZE() macro is used to get the actual size.
251 * Note that we don't currently support Huge pages. On Linux,
252 * regular data files cannot use Huge pages, and in general
253 * Huge pages aren't actually pageable. We rely on the OS
254 * demand-pager to read our data and page it out when memory
255 * pressure from other processes is high. So until OSs have
256 * actual paging support for Huge pages, they're not viable.
258 #define PAGESIZE 4096
260 /** The minimum number of keys required in a database page.
261 * Setting this to a larger value will place a smaller bound on the
262 * maximum size of a data item. Data items larger than this size will
263 * be pushed into overflow pages instead of being stored directly in
264 * the B-tree node. This value used to default to 4. With a page size
265 * of 4096 bytes that meant that any item larger than 1024 bytes would
266 * go into an overflow page. That also meant that on average 2-3KB of
267 * each overflow page was wasted space. The value cannot be lower than
268 * 2 because then there would no longer be a tree structure. With this
269 * value, items larger than 2KB will go into overflow pages, and on
270 * average only 1KB will be wasted.
272 #define MDB_MINKEYS 2
274 /** A stamp that identifies a file as an MDB file.
275 * There's nothing special about this value other than that it is easily
276 * recognizable, and it will reflect any byte order mismatches.
278 #define MDB_MAGIC 0xBEEFC0DE
280 /** The version number for a database's file format. */
281 #define MDB_VERSION 1
283 /** The maximum size of a key in the database.
284 * While data items have essentially unbounded size, we require that
285 * keys all fit onto a regular page. This limit could be raised a bit
286 * further if needed; to something just under #PAGESIZE / #MDB_MINKEYS.
288 #define MAXKEYSIZE 511
293 * This is used for printing a hex dump of a key's contents.
295 #define DKBUF char kbuf[(MAXKEYSIZE*2+1)]
296 /** Display a key in hex.
298 * Invoke a function to display a key in hex.
300 #define DKEY(x) mdb_dkey(x, kbuf)
302 #define DKBUF typedef int dummy_kbuf /* so we can put ';' after */
306 /** @defgroup lazylock Lazy Locking
307 * Macros for locks that are't actually needed.
308 * The DB view is always consistent because all writes are wrapped in
309 * the wmutex. Finer-grained locks aren't necessary.
313 /** Use lazy locking. I.e., don't lock these accesses at all. */
317 /** Grab the reader lock */
318 #define LAZY_MUTEX_LOCK(x)
319 /** Release the reader lock */
320 #define LAZY_MUTEX_UNLOCK(x)
321 /** Release the DB table reader/writer lock */
322 #define LAZY_RWLOCK_UNLOCK(x)
323 /** Grab the DB table write lock */
324 #define LAZY_RWLOCK_WRLOCK(x)
325 /** Grab the DB table read lock */
326 #define LAZY_RWLOCK_RDLOCK(x)
327 /** Declare the DB table rwlock. Should not be followed by ';'. */
328 #define LAZY_RWLOCK_DEF(x)
329 /** Initialize the DB table rwlock */
330 #define LAZY_RWLOCK_INIT(x,y)
331 /** Destroy the DB table rwlock */
332 #define LAZY_RWLOCK_DESTROY(x)
334 #define LAZY_MUTEX_LOCK(x) pthread_mutex_lock(x)
335 #define LAZY_MUTEX_UNLOCK(x) pthread_mutex_unlock(x)
336 #define LAZY_RWLOCK_UNLOCK(x) pthread_rwlock_unlock(x)
337 #define LAZY_RWLOCK_WRLOCK(x) pthread_rwlock_wrlock(x)
338 #define LAZY_RWLOCK_RDLOCK(x) pthread_rwlock_rdlock(x)
339 #define LAZY_RWLOCK_DEF(x) pthread_rwlock_t x;
340 #define LAZY_RWLOCK_INIT(x,y) pthread_rwlock_init(x,y)
341 #define LAZY_RWLOCK_DESTROY(x) pthread_rwlock_destroy(x)
345 /** An invalid page number.
346 * Mainly used to denote an empty tree.
348 #define P_INVALID (~0UL)
350 /** Test if a flag \b f is set in a flag word \b w. */
351 #define F_ISSET(w, f) (((w) & (f)) == (f))
353 /** Used for offsets within a single page.
354 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
357 typedef uint16_t indx_t;
359 /** Default size of memory map.
360 * This is certainly too small for any actual applications. Apps should always set
361 * the size explicitly using #mdb_env_set_mapsize().
363 #define DEFAULT_MAPSIZE 1048576
365 /** @defgroup readers Reader Lock Table
366 * Readers don't acquire any locks for their data access. Instead, they
367 * simply record their transaction ID in the reader table. The reader
368 * mutex is needed just to find an empty slot in the reader table. The
369 * slot's address is saved in thread-specific data so that subsequent read
370 * transactions started by the same thread need no further locking to proceed.
372 * Since the database uses multi-version concurrency control, readers don't
373 * actually need any locking. This table is used to keep track of which
374 * readers are using data from which old transactions, so that we'll know
375 * when a particular old transaction is no longer in use. Old transactions
376 * that have discarded any data pages can then have those pages reclaimed
377 * for use by a later write transaction.
379 * The lock table is constructed such that reader slots are aligned with the
380 * processor's cache line size. Any slot is only ever used by one thread.
381 * This alignment guarantees that there will be no contention or cache
382 * thrashing as threads update their own slot info, and also eliminates
383 * any need for locking when accessing a slot.
385 * A writer thread will scan every slot in the table to determine the oldest
386 * outstanding reader transaction. Any freed pages older than this will be
387 * reclaimed by the writer. The writer doesn't use any locks when scanning
388 * this table. This means that there's no guarantee that the writer will
389 * see the most up-to-date reader info, but that's not required for correct
390 * operation - all we need is to know the upper bound on the oldest reader,
391 * we don't care at all about the newest reader. So the only consequence of
392 * reading stale information here is that old pages might hang around a
393 * while longer before being reclaimed. That's actually good anyway, because
394 * the longer we delay reclaiming old pages, the more likely it is that a
395 * string of contiguous pages can be found after coalescing old pages from
396 * many old transactions together.
398 * @todo We don't actually do such coalescing yet, we grab pages from one
399 * old transaction at a time.
402 /** Number of slots in the reader table.
403 * This value was chosen somewhat arbitrarily. 126 readers plus a
404 * couple mutexes fit exactly into 8KB on my development machine.
405 * Applications should set the table size using #mdb_env_set_maxreaders().
407 #define DEFAULT_READERS 126
409 /** The size of a CPU cache line in bytes. We want our lock structures
410 * aligned to this size to avoid false cache line sharing in the
412 * This value works for most CPUs. For Itanium this should be 128.
418 /** The information we store in a single slot of the reader table.
419 * In addition to a transaction ID, we also record the process and
420 * thread ID that owns a slot, so that we can detect stale information,
421 * e.g. threads or processes that went away without cleaning up.
422 * @note We currently don't check for stale records. We simply re-init
423 * the table when we know that we're the only process opening the
426 typedef struct MDB_rxbody {
427 /** The current Transaction ID when this transaction began.
428 * Multiple readers that start at the same time will probably have the
429 * same ID here. Again, it's not important to exclude them from
430 * anything; all we need to know is which version of the DB they
431 * started from so we can avoid overwriting any data used in that
432 * particular version.
435 /** The process ID of the process owning this reader txn. */
437 /** The thread ID of the thread owning this txn. */
441 /** The actual reader record, with cacheline padding. */
442 typedef struct MDB_reader {
445 /** shorthand for mrb_txnid */
446 #define mr_txnid mru.mrx.mrb_txnid
447 #define mr_pid mru.mrx.mrb_pid
448 #define mr_tid mru.mrx.mrb_tid
449 /** cache line alignment */
450 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
454 /** The header for the reader table.
455 * The table resides in a memory-mapped file. (This is a different file
456 * than is used for the main database.)
458 * For POSIX the actual mutexes reside in the shared memory of this
459 * mapped file. On Windows, mutexes are named objects allocated by the
460 * kernel; we store the mutex names in this mapped file so that other
461 * processes can grab them. This same approach is also used on
462 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
463 * process-shared POSIX mutexes. For these cases where a named object
464 * is used, the object name is derived from a 64 bit FNV hash of the
465 * environment pathname. As such, naming collisions are extremely
466 * unlikely. If a collision occurs, the results are unpredictable.
468 typedef struct MDB_txbody {
469 /** Stamp identifying this as an MDB lock file. It must be set
472 /** Version number of this lock file. Must be set to #MDB_VERSION. */
473 uint32_t mtb_version;
474 #if defined(_WIN32) || defined(__APPLE__)
475 char mtb_rmname[MNAME_LEN];
477 /** Mutex protecting access to this table.
478 * This is the reader lock that #LOCK_MUTEX_R acquires.
480 pthread_mutex_t mtb_mutex;
482 /** The ID of the last transaction committed to the database.
483 * This is recorded here only for convenience; the value can always
484 * be determined by reading the main database meta pages.
487 /** The number of slots that have been used in the reader table.
488 * This always records the maximum count, it is not decremented
489 * when readers release their slots.
491 unsigned mtb_numreaders;
492 /** The ID of the most recent meta page in the database.
493 * This is recorded here only for convenience; the value can always
494 * be determined by reading the main database meta pages.
496 uint32_t mtb_me_toggle;
499 /** The actual reader table definition. */
500 typedef struct MDB_txninfo {
503 #define mti_magic mt1.mtb.mtb_magic
504 #define mti_version mt1.mtb.mtb_version
505 #define mti_mutex mt1.mtb.mtb_mutex
506 #define mti_rmname mt1.mtb.mtb_rmname
507 #define mti_txnid mt1.mtb.mtb_txnid
508 #define mti_numreaders mt1.mtb.mtb_numreaders
509 #define mti_me_toggle mt1.mtb.mtb_me_toggle
510 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
513 #if defined(_WIN32) || defined(__APPLE__)
514 char mt2_wmname[MNAME_LEN];
515 #define mti_wmname mt2.mt2_wmname
517 pthread_mutex_t mt2_wmutex;
518 #define mti_wmutex mt2.mt2_wmutex
520 char pad[(sizeof(pthread_mutex_t)+CACHELINE-1) & ~(CACHELINE-1)];
522 MDB_reader mti_readers[1];
526 /** Common header for all page types.
527 * Overflow records occupy a number of contiguous pages with no
528 * headers on any page after the first.
530 typedef struct MDB_page {
531 #define mp_pgno mp_p.p_pgno
532 #define mp_next mp_p.p_next
534 pgno_t p_pgno; /**< page number */
535 void * p_next; /**< for in-memory list of freed structs */
538 /** @defgroup mdb_page Page Flags
540 * Flags for the page headers.
543 #define P_BRANCH 0x01 /**< branch page */
544 #define P_LEAF 0x02 /**< leaf page */
545 #define P_OVERFLOW 0x04 /**< overflow page */
546 #define P_META 0x08 /**< meta page */
547 #define P_DIRTY 0x10 /**< dirty page */
548 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
549 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
551 uint16_t mp_flags; /**< @ref mdb_page */
552 #define mp_lower mp_pb.pb.pb_lower
553 #define mp_upper mp_pb.pb.pb_upper
554 #define mp_pages mp_pb.pb_pages
557 indx_t pb_lower; /**< lower bound of free space */
558 indx_t pb_upper; /**< upper bound of free space */
560 uint32_t pb_pages; /**< number of overflow pages */
562 indx_t mp_ptrs[1]; /**< dynamic size */
565 /** Size of the page header, excluding dynamic data at the end */
566 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
568 /** Address of first usable data byte in a page, after the header */
569 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
571 /** Number of nodes on a page */
572 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
574 /** The amount of space remaining in the page */
575 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
577 /** The percentage of space used in the page, in tenths of a percent. */
578 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
579 ((env)->me_psize - PAGEHDRSZ))
580 /** The minimum page fill factor, in tenths of a percent.
581 * Pages emptier than this are candidates for merging.
583 #define FILL_THRESHOLD 250
585 /** Test if a page is a leaf page */
586 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
587 /** Test if a page is a LEAF2 page */
588 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
589 /** Test if a page is a branch page */
590 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
591 /** Test if a page is an overflow page */
592 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
593 /** Test if a page is a sub page */
594 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
596 /** The number of overflow pages needed to store the given size. */
597 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
599 /** Header for a single key/data pair within a page.
600 * We guarantee 2-byte alignment for nodes.
602 typedef struct MDB_node {
603 /** lo and hi are used for data size on leaf nodes and for
604 * child pgno on branch nodes. On 64 bit platforms, flags
605 * is also used for pgno. (Branch nodes have no flags).
606 * They are in host byte order in case that lets some
607 * accesses be optimized into a 32-bit word access.
609 #define mn_lo mn_offset[BYTE_ORDER!=LITTLE_ENDIAN]
610 #define mn_hi mn_offset[BYTE_ORDER==LITTLE_ENDIAN] /**< part of dsize or pgno */
611 unsigned short mn_offset[2]; /**< storage for #mn_lo and #mn_hi */
612 /** @defgroup mdb_node Node Flags
614 * Flags for node headers.
617 #define F_BIGDATA 0x01 /**< data put on overflow page */
618 #define F_SUBDATA 0x02 /**< data is a sub-database */
619 #define F_DUPDATA 0x04 /**< data has duplicates */
621 /** valid flags for #mdb_node_add() */
622 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
625 unsigned short mn_flags; /**< @ref mdb_node */
626 unsigned short mn_ksize; /**< key size */
627 char mn_data[1]; /**< key and data are appended here */
630 /** Size of the node header, excluding dynamic data at the end */
631 #define NODESIZE offsetof(MDB_node, mn_data)
633 /** Bit position of top word in page number, for shifting mn_flags */
634 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
636 /** Size of a node in a branch page with a given key.
637 * This is just the node header plus the key, there is no data.
639 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
641 /** Size of a node in a leaf page with a given key and data.
642 * This is node header plus key plus data size.
644 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
646 /** Address of node \b i in page \b p */
647 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
649 /** Address of the key for the node */
650 #define NODEKEY(node) (void *)((node)->mn_data)
652 /** Address of the data for a node */
653 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
655 /** Get the page number pointed to by a branch node */
656 #define NODEPGNO(node) \
657 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
658 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
659 /** Set the page number in a branch node */
660 #define SETPGNO(node,pgno) do { \
661 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
662 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
664 /** Get the size of the data in a leaf node */
665 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
666 /** Set the size of the data for a leaf node */
667 #define SETDSZ(node,size) do { \
668 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
669 /** The size of a key in a node */
670 #define NODEKSZ(node) ((node)->mn_ksize)
672 /** The address of a key in a LEAF2 page.
673 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
674 * There are no node headers, keys are stored contiguously.
676 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
678 /** Set the \b node's key into \b key, if requested. */
679 #define MDB_SET_KEY(node, key) { if ((key) != NULL) { \
680 (key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node); } }
682 /** Information about a single database in the environment. */
683 typedef struct MDB_db {
684 uint32_t md_pad; /**< also ksize for LEAF2 pages */
685 uint16_t md_flags; /**< @ref mdb_open */
686 uint16_t md_depth; /**< depth of this tree */
687 pgno_t md_branch_pages; /**< number of internal pages */
688 pgno_t md_leaf_pages; /**< number of leaf pages */
689 pgno_t md_overflow_pages; /**< number of overflow pages */
690 size_t md_entries; /**< number of data items */
691 pgno_t md_root; /**< the root page of this tree */
694 /** Handle for the DB used to track free pages. */
696 /** Handle for the default DB. */
699 /** Meta page content. */
700 typedef struct MDB_meta {
701 /** Stamp identifying this as an MDB data file. It must be set
704 /** Version number of this lock file. Must be set to #MDB_VERSION. */
706 void *mm_address; /**< address for fixed mapping */
707 size_t mm_mapsize; /**< size of mmap region */
708 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
709 /** The size of pages used in this DB */
710 #define mm_psize mm_dbs[0].md_pad
711 /** Any persistent environment flags. @ref mdb_env */
712 #define mm_flags mm_dbs[0].md_flags
713 pgno_t mm_last_pg; /**< last used page in file */
714 txnid_t mm_txnid; /**< txnid that committed this page */
717 /** Auxiliary DB info.
718 * The information here is mostly static/read-only. There is
719 * only a single copy of this record in the environment.
721 typedef struct MDB_dbx {
722 MDB_val md_name; /**< name of the database */
723 MDB_cmp_func *md_cmp; /**< function for comparing keys */
724 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
725 MDB_rel_func *md_rel; /**< user relocate function */
726 void *md_relctx; /**< user-provided context for md_rel */
729 /** A database transaction.
730 * Every operation requires a transaction handle.
733 MDB_txn *mt_parent; /**< parent of a nested txn */
734 MDB_txn *mt_child; /**< nested txn under this txn */
735 pgno_t mt_next_pgno; /**< next unallocated page */
736 /** The ID of this transaction. IDs are integers incrementing from 1.
737 * Only committed write transactions increment the ID. If a transaction
738 * aborts, the ID may be re-used by the next writer.
741 MDB_env *mt_env; /**< the DB environment */
742 /** The list of pages that became unused during this transaction.
746 ID2L dirty_list; /**< modified pages */
747 MDB_reader *reader; /**< this thread's slot in the reader table */
749 /** Array of records for each DB known in the environment. */
751 /** Array of MDB_db records for each known DB */
753 /** @defgroup mt_dbflag Transaction DB Flags
757 #define DB_DIRTY 0x01 /**< DB was written in this txn */
758 #define DB_STALE 0x02 /**< DB record is older than txnID */
760 /** Array of cursors for each DB */
761 MDB_cursor **mt_cursors;
762 /** Array of flags for each DB */
763 unsigned char *mt_dbflags;
764 /** Number of DB records in use. This number only ever increments;
765 * we don't decrement it when individual DB handles are closed.
769 /** @defgroup mdb_txn Transaction Flags
773 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
774 #define MDB_TXN_ERROR 0x02 /**< an error has occurred */
776 unsigned int mt_flags; /**< @ref mdb_txn */
777 /** Tracks which of the two meta pages was used at the start
778 * of this transaction.
780 unsigned int mt_toggle;
783 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
784 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
785 * raise this on a 64 bit machine.
787 #define CURSOR_STACK 32
791 /** Cursors are used for all DB operations */
793 /** Next cursor on this DB in this txn */
795 /** Original cursor if this is a shadow */
797 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
798 struct MDB_xcursor *mc_xcursor;
799 /** The transaction that owns this cursor */
801 /** The database handle this cursor operates on */
803 /** The database record for this cursor */
805 /** The database auxiliary record for this cursor */
807 /** The @ref mt_dbflag for this database */
808 unsigned char *mc_dbflag;
809 unsigned short mc_snum; /**< number of pushed pages */
810 unsigned short mc_top; /**< index of top page, mc_snum-1 */
811 /** @defgroup mdb_cursor Cursor Flags
813 * Cursor state flags.
816 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
817 #define C_EOF 0x02 /**< No more data */
818 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
819 #define C_SHADOW 0x08 /**< Cursor is a dup from a parent txn */
820 #define C_ALLOCD 0x10 /**< Cursor was malloc'd */
822 unsigned int mc_flags; /**< @ref mdb_cursor */
823 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
824 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
827 /** Context for sorted-dup records.
828 * We could have gone to a fully recursive design, with arbitrarily
829 * deep nesting of sub-databases. But for now we only handle these
830 * levels - main DB, optional sub-DB, sorted-duplicate DB.
832 typedef struct MDB_xcursor {
833 /** A sub-cursor for traversing the Dup DB */
834 MDB_cursor mx_cursor;
835 /** The database record for this Dup DB */
837 /** The auxiliary DB record for this Dup DB */
839 /** The @ref mt_dbflag for this Dup DB */
840 unsigned char mx_dbflag;
843 /** A set of pages freed by an earlier transaction. */
844 typedef struct MDB_oldpages {
845 /** Usually we only read one record from the FREEDB at a time, but
846 * in case we read more, this will chain them together.
848 struct MDB_oldpages *mo_next;
849 /** The ID of the transaction in which these pages were freed. */
851 /** An #IDL of the pages */
852 pgno_t mo_pages[1]; /* dynamic */
855 /** The database environment. */
857 HANDLE me_fd; /**< The main data file */
858 HANDLE me_lfd; /**< The lock file */
859 HANDLE me_mfd; /**< just for writing the meta pages */
860 /** Failed to update the meta page. Probably an I/O error. */
861 #define MDB_FATAL_ERROR 0x80000000U
862 uint32_t me_flags; /**< @ref mdb_env */
863 uint32_t me_extrapad; /**< unused for now */
864 unsigned int me_maxreaders; /**< size of the reader table */
865 MDB_dbi me_numdbs; /**< number of DBs opened */
866 MDB_dbi me_maxdbs; /**< size of the DB table */
867 char *me_path; /**< path to the DB files */
868 char *me_map; /**< the memory map of the data file */
869 MDB_txninfo *me_txns; /**< the memory map of the lock file */
870 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
871 MDB_txn *me_txn; /**< current write transaction */
872 size_t me_mapsize; /**< size of the data memory map */
873 off_t me_size; /**< current file size */
874 pgno_t me_maxpg; /**< me_mapsize / me_psize */
875 unsigned int me_psize; /**< size of a page, from #GET_PAGESIZE */
876 unsigned int me_db_toggle; /**< which DB table is current */
877 txnid_t me_wtxnid; /**< ID of last txn we committed */
878 MDB_dbx *me_dbxs; /**< array of static DB info */
879 MDB_db *me_dbs[2]; /**< two arrays of MDB_db info */
880 MDB_oldpages *me_pghead; /**< list of old page records */
881 pthread_key_t me_txkey; /**< thread-key for readers */
882 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
883 /** IDL of pages that became unused in a write txn */
885 /** ID2L of pages that were written during a write txn */
886 ID2 me_dirty_list[MDB_IDL_UM_SIZE];
887 /** rwlock for the DB tables, if #LAZY_LOCKS is false */
888 LAZY_RWLOCK_DEF(me_dblock)
890 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
894 sem_t *me_rmutex; /* Apple doesn't support shared mutexes */
898 /** max number of pages to commit in one writev() call */
899 #define MDB_COMMIT_PAGES 64
901 static MDB_page *mdb_page_alloc(MDB_cursor *mc, int num);
902 static MDB_page *mdb_page_new(MDB_cursor *mc, uint32_t flags, int num);
903 static int mdb_page_touch(MDB_cursor *mc);
905 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
906 static int mdb_page_search_root(MDB_cursor *mc,
907 MDB_val *key, int modify);
908 static int mdb_page_search(MDB_cursor *mc,
909 MDB_val *key, int modify);
910 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
911 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
912 pgno_t newpgno, unsigned int nflags);
914 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
915 static int mdb_env_read_meta(MDB_env *env, int *which);
916 static int mdb_env_write_meta(MDB_txn *txn);
918 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
919 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
920 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
921 static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
922 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
923 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
924 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
925 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
926 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
928 static int mdb_rebalance(MDB_cursor *mc);
929 static int mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
931 static void mdb_cursor_pop(MDB_cursor *mc);
932 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
934 static int mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
935 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
936 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
937 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
938 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
940 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
941 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
943 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
944 static void mdb_xcursor_init0(MDB_cursor *mc);
945 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
947 static int mdb_drop0(MDB_cursor *mc, int subs);
948 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
951 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
955 static SECURITY_DESCRIPTOR mdb_null_sd;
956 static SECURITY_ATTRIBUTES mdb_all_sa;
957 static int mdb_sec_inited;
960 /** Return the library version info. */
962 mdb_version(int *major, int *minor, int *patch)
964 if (major) *major = MDB_VERSION_MAJOR;
965 if (minor) *minor = MDB_VERSION_MINOR;
966 if (patch) *patch = MDB_VERSION_PATCH;
967 return MDB_VERSION_STRING;
970 /** Table of descriptions for MDB @ref errors */
971 static char *const mdb_errstr[] = {
972 "MDB_KEYEXIST: Key/data pair already exists",
973 "MDB_NOTFOUND: No matching key/data pair found",
974 "MDB_PAGE_NOTFOUND: Requested page not found",
975 "MDB_CORRUPTED: Located page was wrong type",
976 "MDB_PANIC: Update of meta page failed",
977 "MDB_VERSION_MISMATCH: Database environment version mismatch"
981 mdb_strerror(int err)
984 return ("Successful return: 0");
986 if (err >= MDB_KEYEXIST && err <= MDB_VERSION_MISMATCH)
987 return mdb_errstr[err - MDB_KEYEXIST];
989 return strerror(err);
993 /** Display a key in hexadecimal and return the address of the result.
994 * @param[in] key the key to display
995 * @param[in] buf the buffer to write into. Should always be #DKBUF.
996 * @return The key in hexadecimal form.
999 mdb_dkey(MDB_val *key, char *buf)
1002 unsigned char *c = key->mv_data;
1004 if (key->mv_size > MAXKEYSIZE)
1005 return "MAXKEYSIZE";
1006 /* may want to make this a dynamic check: if the key is mostly
1007 * printable characters, print it as-is instead of converting to hex.
1010 for (i=0; i<key->mv_size; i++)
1011 ptr += sprintf(ptr, "%02x", *c++);
1013 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1020 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1022 return txn->mt_dbxs[dbi].md_cmp(a, b);
1026 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1028 if (txn->mt_dbxs[dbi].md_dcmp)
1029 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1031 return EINVAL; /* too bad you can't distinguish this from a valid result */
1034 /** Allocate a single page.
1035 * Re-use old malloc'd pages first, otherwise just malloc.
1038 mdb_page_malloc(MDB_cursor *mc) {
1040 if (mc->mc_txn->mt_env->me_dpages) {
1041 ret = mc->mc_txn->mt_env->me_dpages;
1042 mc->mc_txn->mt_env->me_dpages = ret->mp_next;
1044 ret = malloc(mc->mc_txn->mt_env->me_psize);
1049 /** Allocate pages for writing.
1050 * If there are free pages available from older transactions, they
1051 * will be re-used first. Otherwise a new page will be allocated.
1052 * @param[in] mc cursor A cursor handle identifying the transaction and
1053 * database for which we are allocating.
1054 * @param[in] num the number of pages to allocate.
1055 * @return Address of the allocated page(s). Requests for multiple pages
1056 * will always be satisfied by a single contiguous chunk of memory.
1059 mdb_page_alloc(MDB_cursor *mc, int num)
1061 MDB_txn *txn = mc->mc_txn;
1063 pgno_t pgno = P_INVALID;
1066 if (txn->mt_txnid > 2) {
1068 if (!txn->mt_env->me_pghead && mc->mc_dbi != FREE_DBI &&
1069 txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
1070 /* See if there's anything in the free DB */
1073 txnid_t *kptr, oldest;
1075 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1076 mdb_page_search(&m2, NULL, 0);
1077 leaf = NODEPTR(m2.mc_pg[m2.mc_top], 0);
1078 kptr = (txnid_t *)NODEKEY(leaf);
1082 oldest = txn->mt_txnid - 1;
1083 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
1084 txnid_t mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
1085 if (mr && mr < oldest)
1090 if (oldest > *kptr) {
1091 /* It's usable, grab it.
1097 mdb_node_read(txn, leaf, &data);
1098 idl = (ID *) data.mv_data;
1099 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
1100 mop->mo_next = txn->mt_env->me_pghead;
1101 mop->mo_txnid = *kptr;
1102 txn->mt_env->me_pghead = mop;
1103 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
1108 DPRINTF("IDL read txn %zu root %zu num %zu",
1109 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1110 for (i=0; i<idl[0]; i++) {
1111 DPRINTF("IDL %zu", idl[i+1]);
1115 /* drop this IDL from the DB */
1116 m2.mc_ki[m2.mc_top] = 0;
1117 m2.mc_flags = C_INITIALIZED;
1118 mdb_cursor_del(&m2, 0);
1121 if (txn->mt_env->me_pghead) {
1122 MDB_oldpages *mop = txn->mt_env->me_pghead;
1124 /* FIXME: For now, always use fresh pages. We
1125 * really ought to search the free list for a
1130 /* peel pages off tail, so we only have to truncate the list */
1131 pgno = MDB_IDL_LAST(mop->mo_pages);
1132 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
1134 if (mop->mo_pages[2] > mop->mo_pages[1])
1135 mop->mo_pages[0] = 0;
1139 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
1140 txn->mt_env->me_pghead = mop->mo_next;
1147 if (pgno == P_INVALID) {
1148 /* DB size is maxed out */
1149 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg) {
1150 DPUTS("DB size maxed out");
1154 if (txn->mt_env->me_dpages && num == 1) {
1155 np = txn->mt_env->me_dpages;
1156 txn->mt_env->me_dpages = np->mp_next;
1158 if ((np = malloc(txn->mt_env->me_psize * num )) == NULL)
1161 if (pgno == P_INVALID) {
1162 np->mp_pgno = txn->mt_next_pgno;
1163 txn->mt_next_pgno += num;
1167 mid.mid = np->mp_pgno;
1169 mdb_mid2l_insert(txn->mt_u.dirty_list, &mid);
1174 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1175 * @param[in] mc cursor pointing to the page to be touched
1176 * @return 0 on success, non-zero on failure.
1179 mdb_page_touch(MDB_cursor *mc)
1181 MDB_page *mp = mc->mc_pg[mc->mc_top];
1184 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1186 if ((np = mdb_page_alloc(mc, 1)) == NULL)
1188 DPRINTF("touched db %u page %zu -> %zu", mc->mc_dbi, mp->mp_pgno, np->mp_pgno);
1189 assert(mp->mp_pgno != np->mp_pgno);
1190 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
1192 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1195 mp->mp_flags |= P_DIRTY;
1198 /* Adjust other cursors pointing to mp */
1199 if (mc->mc_flags & C_SUB) {
1200 MDB_cursor *m2, *m3;
1201 MDB_dbi dbi = mc->mc_dbi-1;
1203 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
1204 if (m2 == mc) continue;
1205 m3 = &m2->mc_xcursor->mx_cursor;
1206 if (m3->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1207 m3->mc_pg[mc->mc_top] = mp;
1213 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
1214 if (m2 == mc) continue;
1215 if (m2->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1216 m2->mc_pg[mc->mc_top] = mp;
1220 mc->mc_pg[mc->mc_top] = mp;
1221 /** If this page has a parent, update the parent to point to
1225 SETPGNO(NODEPTR(mc->mc_pg[mc->mc_top-1], mc->mc_ki[mc->mc_top-1]), mp->mp_pgno);
1227 mc->mc_db->md_root = mp->mp_pgno;
1228 } else if (mc->mc_txn->mt_parent) {
1231 /* If txn has a parent, make sure the page is in our
1234 if (mc->mc_txn->mt_u.dirty_list[0].mid) {
1235 unsigned x = mdb_mid2l_search(mc->mc_txn->mt_u.dirty_list, mp->mp_pgno);
1236 if (x <= mc->mc_txn->mt_u.dirty_list[0].mid &&
1237 mc->mc_txn->mt_u.dirty_list[x].mid == mp->mp_pgno) {
1238 if (mc->mc_txn->mt_u.dirty_list[x].mptr != mp) {
1239 mp = mc->mc_txn->mt_u.dirty_list[x].mptr;
1240 mc->mc_pg[mc->mc_top] = mp;
1246 np = mdb_page_malloc(mc);
1247 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1248 mid.mid = np->mp_pgno;
1250 mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &mid);
1258 mdb_env_sync(MDB_env *env, int force)
1261 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1262 if (fdatasync(env->me_fd))
1268 /** Make shadow copies of all of parent txn's cursors */
1270 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
1272 MDB_cursor *mc, *m2;
1273 unsigned int i, j, size;
1275 for (i=0;i<src->mt_numdbs; i++) {
1276 if (src->mt_cursors[i]) {
1277 size = sizeof(MDB_cursor);
1278 if (src->mt_cursors[i]->mc_xcursor)
1279 size += sizeof(MDB_xcursor);
1280 for (m2 = src->mt_cursors[i]; m2; m2=m2->mc_next) {
1287 mc->mc_db = &dst->mt_dbs[i];
1288 mc->mc_dbx = m2->mc_dbx;
1289 mc->mc_dbflag = &dst->mt_dbflags[i];
1290 mc->mc_snum = m2->mc_snum;
1291 mc->mc_top = m2->mc_top;
1292 mc->mc_flags = m2->mc_flags | C_SHADOW;
1293 for (j=0; j<mc->mc_snum; j++) {
1294 mc->mc_pg[j] = m2->mc_pg[j];
1295 mc->mc_ki[j] = m2->mc_ki[j];
1297 if (m2->mc_xcursor) {
1298 MDB_xcursor *mx, *mx2;
1299 mx = (MDB_xcursor *)(mc+1);
1300 mc->mc_xcursor = mx;
1301 mx2 = m2->mc_xcursor;
1302 mx->mx_db = mx2->mx_db;
1303 mx->mx_dbx = mx2->mx_dbx;
1304 mx->mx_dbflag = mx2->mx_dbflag;
1305 mx->mx_cursor.mc_txn = dst;
1306 mx->mx_cursor.mc_dbi = mx2->mx_cursor.mc_dbi;
1307 mx->mx_cursor.mc_db = &mx->mx_db;
1308 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
1309 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
1310 mx->mx_cursor.mc_snum = mx2->mx_cursor.mc_snum;
1311 mx->mx_cursor.mc_top = mx2->mx_cursor.mc_top;
1312 mx->mx_cursor.mc_flags = mx2->mx_cursor.mc_flags | C_SHADOW;
1313 for (j=0; j<mx2->mx_cursor.mc_snum; j++) {
1314 mx->mx_cursor.mc_pg[j] = mx2->mx_cursor.mc_pg[j];
1315 mx->mx_cursor.mc_ki[j] = mx2->mx_cursor.mc_ki[j];
1318 mc->mc_xcursor = NULL;
1320 mc->mc_next = dst->mt_cursors[i];
1321 dst->mt_cursors[i] = mc;
1328 /** Merge shadow cursors back into parent's */
1330 mdb_cursor_merge(MDB_txn *txn)
1333 for (i=0; i<txn->mt_numdbs; i++) {
1334 if (txn->mt_cursors[i]) {
1336 while ((mc = txn->mt_cursors[i])) {
1337 txn->mt_cursors[i] = mc->mc_next;
1338 if (mc->mc_flags & C_SHADOW) {
1339 MDB_cursor *m2 = mc->mc_orig;
1341 m2->mc_snum = mc->mc_snum;
1342 m2->mc_top = mc->mc_top;
1343 for (j=0; j<mc->mc_snum; j++) {
1344 m2->mc_pg[j] = mc->mc_pg[j];
1345 m2->mc_ki[j] = mc->mc_ki[j];
1348 if (mc->mc_flags & C_ALLOCD)
1356 mdb_txn_reset0(MDB_txn *txn);
1358 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
1359 * @param[in] txn the transaction handle to initialize
1360 * @return 0 on success, non-zero on failure. This can only
1361 * fail for read-only transactions, and then only if the
1362 * reader table is full.
1365 mdb_txn_renew0(MDB_txn *txn)
1367 MDB_env *env = txn->mt_env;
1370 if (txn->mt_flags & MDB_TXN_RDONLY) {
1371 MDB_reader *r = pthread_getspecific(env->me_txkey);
1374 pid_t pid = getpid();
1375 pthread_t tid = pthread_self();
1378 for (i=0; i<env->me_txns->mti_numreaders; i++)
1379 if (env->me_txns->mti_readers[i].mr_pid == 0)
1381 if (i == env->me_maxreaders) {
1382 UNLOCK_MUTEX_R(env);
1385 env->me_txns->mti_readers[i].mr_pid = pid;
1386 env->me_txns->mti_readers[i].mr_tid = tid;
1387 if (i >= env->me_txns->mti_numreaders)
1388 env->me_txns->mti_numreaders = i+1;
1389 UNLOCK_MUTEX_R(env);
1390 r = &env->me_txns->mti_readers[i];
1391 pthread_setspecific(env->me_txkey, r);
1393 txn->mt_toggle = env->me_txns->mti_me_toggle;
1394 txn->mt_txnid = env->me_txns->mti_txnid;
1395 /* This happens if a different process was the
1396 * last writer to the DB.
1398 if (env->me_wtxnid < txn->mt_txnid)
1399 mt_dbflag = DB_STALE;
1400 r->mr_txnid = txn->mt_txnid;
1401 txn->mt_u.reader = r;
1405 txn->mt_txnid = env->me_txns->mti_txnid;
1406 if (env->me_wtxnid < txn->mt_txnid)
1407 mt_dbflag = DB_STALE;
1409 txn->mt_toggle = env->me_txns->mti_me_toggle;
1410 txn->mt_u.dirty_list = env->me_dirty_list;
1411 txn->mt_u.dirty_list[0].mid = 0;
1412 txn->mt_free_pgs = env->me_free_pgs;
1413 txn->mt_free_pgs[0] = 0;
1414 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1418 /* Copy the DB arrays */
1419 LAZY_RWLOCK_RDLOCK(&env->me_dblock);
1420 txn->mt_numdbs = env->me_numdbs;
1421 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
1422 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
1423 if (txn->mt_numdbs > 2)
1424 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
1425 (txn->mt_numdbs - 2) * sizeof(MDB_db));
1426 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1428 memset(txn->mt_dbflags, mt_dbflag, env->me_numdbs);
1434 mdb_txn_renew(MDB_txn *txn)
1441 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
1442 DPUTS("environment had fatal error, must shutdown!");
1446 rc = mdb_txn_renew0(txn);
1447 if (rc == MDB_SUCCESS) {
1448 DPRINTF("renew txn %zu%c %p on mdbenv %p, root page %zu",
1449 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1450 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1456 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
1461 if (env->me_flags & MDB_FATAL_ERROR) {
1462 DPUTS("environment had fatal error, must shutdown!");
1466 /* parent already has an active child txn */
1467 if (parent->mt_child) {
1471 size = sizeof(MDB_txn) + env->me_maxdbs * (sizeof(MDB_db)+1);
1472 if (!(flags & MDB_RDONLY))
1473 size += env->me_maxdbs * sizeof(MDB_cursor *);
1475 if ((txn = calloc(1, size)) == NULL) {
1476 DPRINTF("calloc: %s", strerror(ErrCode()));
1479 txn->mt_dbs = (MDB_db *)(txn+1);
1480 if (flags & MDB_RDONLY) {
1481 txn->mt_flags |= MDB_TXN_RDONLY;
1482 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
1484 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
1485 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
1490 txn->mt_free_pgs = mdb_midl_alloc();
1491 if (!txn->mt_free_pgs) {
1495 txn->mt_u.dirty_list = malloc(sizeof(ID2)*MDB_IDL_UM_SIZE);
1496 if (!txn->mt_u.dirty_list) {
1497 free(txn->mt_free_pgs);
1501 txn->mt_txnid = parent->mt_txnid;
1502 txn->mt_toggle = parent->mt_toggle;
1503 txn->mt_u.dirty_list[0].mid = 0;
1504 txn->mt_free_pgs[0] = 0;
1505 txn->mt_next_pgno = parent->mt_next_pgno;
1506 parent->mt_child = txn;
1507 txn->mt_parent = parent;
1508 txn->mt_numdbs = parent->mt_numdbs;
1509 txn->mt_dbxs = parent->mt_dbxs;
1510 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
1511 memcpy(txn->mt_dbflags, parent->mt_dbflags, txn->mt_numdbs);
1512 mdb_cursor_shadow(parent, txn);
1515 rc = mdb_txn_renew0(txn);
1521 DPRINTF("begin txn %zu%c %p on mdbenv %p, root page %zu",
1522 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1523 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
1529 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
1530 * @param[in] txn the transaction handle to reset
1533 mdb_txn_reset0(MDB_txn *txn)
1535 MDB_env *env = txn->mt_env;
1537 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1538 txn->mt_u.reader->mr_txnid = 0;
1544 /* close(free) all cursors */
1545 for (i=0; i<txn->mt_numdbs; i++) {
1546 if (txn->mt_cursors[i]) {
1548 while ((mc = txn->mt_cursors[i])) {
1549 txn->mt_cursors[i] = mc->mc_next;
1550 if (mc->mc_flags & C_ALLOCD)
1556 /* return all dirty pages to dpage list */
1557 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1558 dp = txn->mt_u.dirty_list[i].mptr;
1559 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1560 dp->mp_next = txn->mt_env->me_dpages;
1561 txn->mt_env->me_dpages = dp;
1563 /* large pages just get freed directly */
1568 if (txn->mt_parent) {
1569 txn->mt_parent->mt_child = NULL;
1570 free(txn->mt_free_pgs);
1571 free(txn->mt_u.dirty_list);
1574 if (mdb_midl_shrink(&txn->mt_free_pgs))
1575 env->me_free_pgs = txn->mt_free_pgs;
1578 while ((mop = txn->mt_env->me_pghead)) {
1579 txn->mt_env->me_pghead = mop->mo_next;
1584 /* The writer mutex was locked in mdb_txn_begin. */
1585 UNLOCK_MUTEX_W(env);
1590 mdb_txn_reset(MDB_txn *txn)
1595 DPRINTF("reset txn %zu%c %p on mdbenv %p, root page %zu",
1596 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1597 (void *) txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1599 mdb_txn_reset0(txn);
1603 mdb_txn_abort(MDB_txn *txn)
1608 DPRINTF("abort txn %zu%c %p on mdbenv %p, root page %zu",
1609 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1610 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1613 mdb_txn_abort(txn->mt_child);
1615 mdb_txn_reset0(txn);
1620 mdb_txn_commit(MDB_txn *txn)
1631 assert(txn != NULL);
1632 assert(txn->mt_env != NULL);
1634 if (txn->mt_child) {
1635 mdb_txn_commit(txn->mt_child);
1636 txn->mt_child = NULL;
1641 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1642 if (txn->mt_numdbs > env->me_numdbs) {
1643 /* update the DB tables */
1644 int toggle = !env->me_db_toggle;
1648 ip = &env->me_dbs[toggle][env->me_numdbs];
1649 jp = &txn->mt_dbs[env->me_numdbs];
1650 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1651 for (i = env->me_numdbs; i < txn->mt_numdbs; i++) {
1655 env->me_db_toggle = toggle;
1656 env->me_numdbs = txn->mt_numdbs;
1657 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1663 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1664 DPUTS("error flag is set, can't commit");
1666 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
1671 /* Merge (and close) our cursors with parent's */
1672 mdb_cursor_merge(txn);
1674 if (txn->mt_parent) {
1680 /* Update parent's DB table */
1681 ip = &txn->mt_parent->mt_dbs[2];
1682 jp = &txn->mt_dbs[2];
1683 for (i = 2; i < txn->mt_numdbs; i++) {
1684 if (ip->md_root != jp->md_root)
1688 txn->mt_parent->mt_numdbs = txn->mt_numdbs;
1690 /* Append our free list to parent's */
1691 mdb_midl_append_list(&txn->mt_parent->mt_free_pgs,
1693 mdb_midl_free(txn->mt_free_pgs);
1695 /* Merge our dirty list with parent's */
1696 dst = txn->mt_parent->mt_u.dirty_list;
1697 src = txn->mt_u.dirty_list;
1698 x = mdb_mid2l_search(dst, src[1].mid);
1699 for (y=1; y<=src[0].mid; y++) {
1700 while (x <= dst[0].mid && dst[x].mid != src[y].mid) x++;
1704 dst[x].mptr = src[y].mptr;
1707 for (; y<=src[0].mid; y++) {
1708 if (++x >= MDB_IDL_UM_MAX)
1713 free(txn->mt_u.dirty_list);
1714 txn->mt_parent->mt_child = NULL;
1719 if (txn != env->me_txn) {
1720 DPUTS("attempt to commit unknown transaction");
1725 if (!txn->mt_u.dirty_list[0].mid)
1728 DPRINTF("committing txn %zu %p on mdbenv %p, root page %zu",
1729 txn->mt_txnid, (void *)txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
1731 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1733 /* should only be one record now */
1734 if (env->me_pghead) {
1735 /* make sure first page of freeDB is touched and on freelist */
1736 mdb_page_search(&mc, NULL, 1);
1738 /* save to free list */
1739 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
1743 /* make sure last page of freeDB is touched and on freelist */
1744 key.mv_size = MAXKEYSIZE+1;
1746 mdb_page_search(&mc, &key, 1);
1748 mdb_midl_sort(txn->mt_free_pgs);
1752 ID *idl = txn->mt_free_pgs;
1753 DPRINTF("IDL write txn %zu root %zu num %zu",
1754 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1755 for (i=0; i<idl[0]; i++) {
1756 DPRINTF("IDL %zu", idl[i+1]);
1760 /* write to last page of freeDB */
1761 key.mv_size = sizeof(pgno_t);
1762 key.mv_data = &txn->mt_txnid;
1763 data.mv_data = txn->mt_free_pgs;
1764 /* The free list can still grow during this call,
1765 * despite the pre-emptive touches above. So check
1766 * and make sure the entire thing got written.
1769 i = txn->mt_free_pgs[0];
1770 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
1771 rc = mdb_cursor_put(&mc, &key, &data, 0);
1776 } while (i != txn->mt_free_pgs[0]);
1777 if (mdb_midl_shrink(&txn->mt_free_pgs))
1778 env->me_free_pgs = txn->mt_free_pgs;
1780 /* should only be one record now */
1781 if (env->me_pghead) {
1785 mop = env->me_pghead;
1786 env->me_pghead = NULL;
1787 key.mv_size = sizeof(pgno_t);
1788 key.mv_data = &mop->mo_txnid;
1789 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
1790 data.mv_data = mop->mo_pages;
1791 mdb_cursor_put(&mc, &key, &data, 0);
1795 /* Update DB root pointers. Their pages have already been
1796 * touched so this is all in-place and cannot fail.
1801 data.mv_size = sizeof(MDB_db);
1803 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
1804 for (i = 2; i < txn->mt_numdbs; i++) {
1805 if (txn->mt_dbflags[i] & DB_DIRTY) {
1806 data.mv_data = &txn->mt_dbs[i];
1807 mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
1812 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
1818 /* Windows actually supports scatter/gather I/O, but only on
1819 * unbuffered file handles. Since we're relying on the OS page
1820 * cache for all our data, that's self-defeating. So we just
1821 * write pages one at a time. We use the ov structure to set
1822 * the write offset, to at least save the overhead of a Seek
1826 memset(&ov, 0, sizeof(ov));
1827 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1829 dp = txn->mt_u.dirty_list[i].mptr;
1830 DPRINTF("committing page %zu", dp->mp_pgno);
1831 size = dp->mp_pgno * env->me_psize;
1832 ov.Offset = size & 0xffffffff;
1833 ov.OffsetHigh = size >> 16;
1834 ov.OffsetHigh >>= 16;
1835 /* clear dirty flag */
1836 dp->mp_flags &= ~P_DIRTY;
1837 wsize = env->me_psize;
1838 if (IS_OVERFLOW(dp)) wsize *= dp->mp_pages;
1839 rc = WriteFile(env->me_fd, dp, wsize, NULL, &ov);
1842 DPRINTF("WriteFile: %d", n);
1849 struct iovec iov[MDB_COMMIT_PAGES];
1853 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1854 dp = txn->mt_u.dirty_list[i].mptr;
1855 if (dp->mp_pgno != next) {
1857 DPRINTF("committing %u dirty pages", n);
1858 rc = writev(env->me_fd, iov, n);
1862 DPUTS("short write, filesystem full?");
1864 DPRINTF("writev: %s", strerror(n));
1871 lseek(env->me_fd, dp->mp_pgno * env->me_psize, SEEK_SET);
1874 DPRINTF("committing page %zu", dp->mp_pgno);
1875 iov[n].iov_len = env->me_psize;
1876 if (IS_OVERFLOW(dp)) iov[n].iov_len *= dp->mp_pages;
1877 iov[n].iov_base = dp;
1878 size += iov[n].iov_len;
1879 next = dp->mp_pgno + (IS_OVERFLOW(dp) ? dp->mp_pages : 1);
1880 /* clear dirty flag */
1881 dp->mp_flags &= ~P_DIRTY;
1882 if (++n >= MDB_COMMIT_PAGES) {
1892 DPRINTF("committing %u dirty pages", n);
1893 rc = writev(env->me_fd, iov, n);
1897 DPUTS("short write, filesystem full?");
1899 DPRINTF("writev: %s", strerror(n));
1906 /* Drop the dirty pages.
1908 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1909 dp = txn->mt_u.dirty_list[i].mptr;
1910 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1911 dp->mp_next = txn->mt_env->me_dpages;
1912 txn->mt_env->me_dpages = dp;
1916 txn->mt_u.dirty_list[i].mid = 0;
1918 txn->mt_u.dirty_list[0].mid = 0;
1920 if ((n = mdb_env_sync(env, 0)) != 0 ||
1921 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
1925 env->me_wtxnid = txn->mt_txnid;
1929 /* update the DB tables */
1931 int toggle = !env->me_db_toggle;
1935 ip = &env->me_dbs[toggle][2];
1936 jp = &txn->mt_dbs[2];
1937 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1938 for (i = 2; i < txn->mt_numdbs; i++) {
1939 if (ip->md_root != jp->md_root)
1944 env->me_db_toggle = toggle;
1945 env->me_numdbs = txn->mt_numdbs;
1946 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1949 UNLOCK_MUTEX_W(env);
1955 /** Read the environment parameters of a DB environment before
1956 * mapping it into memory.
1957 * @param[in] env the environment handle
1958 * @param[out] meta address of where to store the meta information
1959 * @return 0 on success, non-zero on failure.
1962 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
1964 char page[PAGESIZE];
1969 /* We don't know the page size yet, so use a minimum value.
1973 if (!ReadFile(env->me_fd, page, PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
1975 if ((rc = read(env->me_fd, page, PAGESIZE)) == 0)
1980 else if (rc != PAGESIZE) {
1984 DPRINTF("read: %s", strerror(err));
1988 p = (MDB_page *)page;
1990 if (!F_ISSET(p->mp_flags, P_META)) {
1991 DPRINTF("page %zu not a meta page", p->mp_pgno);
1996 if (m->mm_magic != MDB_MAGIC) {
1997 DPUTS("meta has invalid magic");
2001 if (m->mm_version != MDB_VERSION) {
2002 DPRINTF("database is version %u, expected version %u",
2003 m->mm_version, MDB_VERSION);
2004 return MDB_VERSION_MISMATCH;
2007 memcpy(meta, m, sizeof(*m));
2011 /** Write the environment parameters of a freshly created DB environment.
2012 * @param[in] env the environment handle
2013 * @param[out] meta address of where to store the meta information
2014 * @return 0 on success, non-zero on failure.
2017 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
2024 DPUTS("writing new meta page");
2026 GET_PAGESIZE(psize);
2028 meta->mm_magic = MDB_MAGIC;
2029 meta->mm_version = MDB_VERSION;
2030 meta->mm_psize = psize;
2031 meta->mm_last_pg = 1;
2032 meta->mm_flags = env->me_flags & 0xffff;
2033 meta->mm_flags |= MDB_INTEGERKEY;
2034 meta->mm_dbs[0].md_root = P_INVALID;
2035 meta->mm_dbs[1].md_root = P_INVALID;
2037 p = calloc(2, psize);
2039 p->mp_flags = P_META;
2042 memcpy(m, meta, sizeof(*meta));
2044 q = (MDB_page *)((char *)p + psize);
2047 q->mp_flags = P_META;
2050 memcpy(m, meta, sizeof(*meta));
2055 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
2056 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
2059 rc = write(env->me_fd, p, psize * 2);
2060 rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
2066 /** Update the environment info to commit a transaction.
2067 * @param[in] txn the transaction that's being committed
2068 * @return 0 on success, non-zero on failure.
2071 mdb_env_write_meta(MDB_txn *txn)
2074 MDB_meta meta, metab;
2076 int rc, len, toggle;
2082 assert(txn != NULL);
2083 assert(txn->mt_env != NULL);
2085 toggle = !txn->mt_toggle;
2086 DPRINTF("writing meta page %d for root page %zu",
2087 toggle, txn->mt_dbs[MAIN_DBI].md_root);
2091 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
2092 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
2094 ptr = (char *)&meta;
2095 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
2096 len = sizeof(MDB_meta) - off;
2099 meta.mm_dbs[0] = txn->mt_dbs[0];
2100 meta.mm_dbs[1] = txn->mt_dbs[1];
2101 meta.mm_last_pg = txn->mt_next_pgno - 1;
2102 meta.mm_txnid = txn->mt_txnid;
2105 off += env->me_psize;
2108 /* Write to the SYNC fd */
2111 memset(&ov, 0, sizeof(ov));
2113 WriteFile(env->me_mfd, ptr, len, (DWORD *)&rc, &ov);
2116 rc = pwrite(env->me_mfd, ptr, len, off);
2121 DPUTS("write failed, disk error?");
2122 /* On a failure, the pagecache still contains the new data.
2123 * Write some old data back, to prevent it from being used.
2124 * Use the non-SYNC fd; we know it will fail anyway.
2126 meta.mm_last_pg = metab.mm_last_pg;
2127 meta.mm_txnid = metab.mm_txnid;
2129 WriteFile(env->me_fd, ptr, len, NULL, &ov);
2131 r2 = pwrite(env->me_fd, ptr, len, off);
2133 env->me_flags |= MDB_FATAL_ERROR;
2136 /* Memory ordering issues are irrelevant; since the entire writer
2137 * is wrapped by wmutex, all of these changes will become visible
2138 * after the wmutex is unlocked. Since the DB is multi-version,
2139 * readers will get consistent data regardless of how fresh or
2140 * how stale their view of these values is.
2142 LAZY_MUTEX_LOCK(&env->me_txns->mti_mutex);
2143 txn->mt_env->me_txns->mti_me_toggle = toggle;
2144 txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
2145 LAZY_MUTEX_UNLOCK(&env->me_txns->mti_mutex);
2150 /** Check both meta pages to see which one is newer.
2151 * @param[in] env the environment handle
2152 * @param[out] which address of where to store the meta toggle ID
2153 * @return 0 on success, non-zero on failure.
2156 mdb_env_read_meta(MDB_env *env, int *which)
2160 assert(env != NULL);
2162 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
2165 DPRINTF("Using meta page %d", toggle);
2172 mdb_env_create(MDB_env **env)
2176 e = calloc(1, sizeof(MDB_env));
2180 e->me_free_pgs = mdb_midl_alloc();
2181 if (!e->me_free_pgs) {
2185 e->me_maxreaders = DEFAULT_READERS;
2187 e->me_fd = INVALID_HANDLE_VALUE;
2188 e->me_lfd = INVALID_HANDLE_VALUE;
2189 e->me_mfd = INVALID_HANDLE_VALUE;
2195 mdb_env_set_mapsize(MDB_env *env, size_t size)
2199 env->me_mapsize = size;
2201 env->me_maxpg = env->me_mapsize / env->me_psize;
2206 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
2210 env->me_maxdbs = dbs;
2215 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
2217 if (env->me_map || readers < 1)
2219 env->me_maxreaders = readers;
2224 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
2226 if (!env || !readers)
2228 *readers = env->me_maxreaders;
2232 /** Further setup required for opening an MDB environment
2235 mdb_env_open2(MDB_env *env, unsigned int flags)
2237 int i, newenv = 0, toggle;
2241 env->me_flags = flags;
2243 memset(&meta, 0, sizeof(meta));
2245 if ((i = mdb_env_read_header(env, &meta)) != 0) {
2248 DPUTS("new mdbenv");
2252 if (!env->me_mapsize) {
2253 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
2259 LONG sizelo, sizehi;
2260 sizelo = env->me_mapsize & 0xffffffff;
2261 sizehi = env->me_mapsize >> 16; /* pointless on WIN32, only needed on W64 */
2263 /* Windows won't create mappings for zero length files.
2264 * Just allocate the maxsize right now.
2267 SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
2268 if (!SetEndOfFile(env->me_fd))
2270 SetFilePointer(env->me_fd, 0, NULL, 0);
2272 mh = CreateFileMapping(env->me_fd, NULL, PAGE_READONLY,
2273 sizehi, sizelo, NULL);
2276 env->me_map = MapViewOfFileEx(mh, FILE_MAP_READ, 0, 0, env->me_mapsize,
2284 if (meta.mm_address && (flags & MDB_FIXEDMAP))
2286 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
2288 if (env->me_map == MAP_FAILED)
2293 meta.mm_mapsize = env->me_mapsize;
2294 if (flags & MDB_FIXEDMAP)
2295 meta.mm_address = env->me_map;
2296 i = mdb_env_init_meta(env, &meta);
2297 if (i != MDB_SUCCESS) {
2298 munmap(env->me_map, env->me_mapsize);
2302 env->me_psize = meta.mm_psize;
2304 env->me_maxpg = env->me_mapsize / env->me_psize;
2306 p = (MDB_page *)env->me_map;
2307 env->me_metas[0] = METADATA(p);
2308 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
2310 if ((i = mdb_env_read_meta(env, &toggle)) != 0)
2313 DPRINTF("opened database version %u, pagesize %u",
2314 env->me_metas[toggle]->mm_version, env->me_psize);
2315 DPRINTF("depth: %u", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_depth);
2316 DPRINTF("entries: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_entries);
2317 DPRINTF("branch pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_branch_pages);
2318 DPRINTF("leaf pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_leaf_pages);
2319 DPRINTF("overflow pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_overflow_pages);
2320 DPRINTF("root: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_root);
2326 /** Release a reader thread's slot in the reader lock table.
2327 * This function is called automatically when a thread exits.
2328 * Windows doesn't support destructor callbacks for thread-specific storage,
2329 * so this function is not compiled there.
2330 * @param[in] ptr This points to the slot in the reader lock table.
2333 mdb_env_reader_dest(void *ptr)
2335 MDB_reader *reader = ptr;
2337 reader->mr_txnid = 0;
2343 /** Downgrade the exclusive lock on the region back to shared */
2345 mdb_env_share_locks(MDB_env *env)
2349 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
2351 env->me_txns->mti_me_toggle = toggle;
2352 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
2357 /* First acquire a shared lock. The Unlock will
2358 * then release the existing exclusive lock.
2360 memset(&ov, 0, sizeof(ov));
2361 LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov);
2362 UnlockFile(env->me_lfd, 0, 0, 1, 0);
2366 struct flock lock_info;
2367 /* The shared lock replaces the existing lock */
2368 memset((void *)&lock_info, 0, sizeof(lock_info));
2369 lock_info.l_type = F_RDLCK;
2370 lock_info.l_whence = SEEK_SET;
2371 lock_info.l_start = 0;
2372 lock_info.l_len = 1;
2373 fcntl(env->me_lfd, F_SETLK, &lock_info);
2377 #if defined(_WIN32) || defined(__APPLE__)
2379 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
2381 * @(#) $Revision: 5.1 $
2382 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
2383 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
2385 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
2389 * Please do not copyright this code. This code is in the public domain.
2391 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
2392 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
2393 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
2394 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
2395 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
2396 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
2397 * PERFORMANCE OF THIS SOFTWARE.
2400 * chongo <Landon Curt Noll> /\oo/\
2401 * http://www.isthe.com/chongo/
2403 * Share and Enjoy! :-)
2406 typedef unsigned long long mdb_hash_t;
2407 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
2409 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
2410 * @param[in] str string to hash
2411 * @param[in] hval initial value for hash
2412 * @return 64 bit hash
2414 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
2415 * hval arg on the first call.
2418 mdb_hash_str(char *str, mdb_hash_t hval)
2420 unsigned char *s = (unsigned char *)str; /* unsigned string */
2422 * FNV-1a hash each octet of the string
2425 /* xor the bottom with the current octet */
2426 hval ^= (mdb_hash_t)*s++;
2428 /* multiply by the 64 bit FNV magic prime mod 2^64 */
2429 hval += (hval << 1) + (hval << 4) + (hval << 5) +
2430 (hval << 7) + (hval << 8) + (hval << 40);
2432 /* return our new hash value */
2436 /** Hash the string and output the hash in hex.
2437 * @param[in] str string to hash
2438 * @param[out] hexbuf an array of 17 chars to hold the hash
2441 mdb_hash_hex(char *str, char *hexbuf)
2444 mdb_hash_t h = mdb_hash_str(str, MDB_HASH_INIT);
2445 for (i=0; i<8; i++) {
2446 hexbuf += sprintf(hexbuf, "%02x", (unsigned int)h & 0xff);
2452 /** Open and/or initialize the lock region for the environment.
2453 * @param[in] env The MDB environment.
2454 * @param[in] lpath The pathname of the file used for the lock region.
2455 * @param[in] mode The Unix permissions for the file, if we create it.
2456 * @param[out] excl Set to true if we got an exclusive lock on the region.
2457 * @return 0 on success, non-zero on failure.
2460 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
2468 if ((env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
2469 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
2470 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
2474 /* Try to get exclusive lock. If we succeed, then
2475 * nobody is using the lock region and we should initialize it.
2478 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
2482 memset(&ov, 0, sizeof(ov));
2483 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
2489 size = GetFileSize(env->me_lfd, NULL);
2491 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
2495 /* Try to get exclusive lock. If we succeed, then
2496 * nobody is using the lock region and we should initialize it.
2499 struct flock lock_info;
2500 memset((void *)&lock_info, 0, sizeof(lock_info));
2501 lock_info.l_type = F_WRLCK;
2502 lock_info.l_whence = SEEK_SET;
2503 lock_info.l_start = 0;
2504 lock_info.l_len = 1;
2505 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
2509 lock_info.l_type = F_RDLCK;
2510 rc = fcntl(env->me_lfd, F_SETLKW, &lock_info);
2517 size = lseek(env->me_lfd, 0, SEEK_END);
2519 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
2520 if (size < rsize && *excl) {
2522 SetFilePointer(env->me_lfd, rsize, NULL, 0);
2523 if (!SetEndOfFile(env->me_lfd)) {
2528 if (ftruncate(env->me_lfd, rsize) != 0) {
2535 size = rsize - sizeof(MDB_txninfo);
2536 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
2541 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
2547 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
2549 if (!env->me_txns) {
2555 env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
2557 if (env->me_txns == MAP_FAILED) {
2565 if (!mdb_sec_inited) {
2566 InitializeSecurityDescriptor(&mdb_null_sd,
2567 SECURITY_DESCRIPTOR_REVISION);
2568 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
2569 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2570 mdb_all_sa.bInheritHandle = FALSE;
2571 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
2574 mdb_hash_hex(lpath, hexbuf);
2575 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", hexbuf);
2576 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
2577 if (!env->me_rmutex) {
2581 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", hexbuf);
2582 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
2583 if (!env->me_wmutex) {
2590 mdb_hash_hex(lpath, hexbuf);
2591 sprintf(env->me_txns->mti_rmname, "MDBr%s", hexbuf);
2592 if (sem_unlink(env->me_txns->mti_rmname)) {
2594 if (rc != ENOENT && rc != EINVAL)
2597 env->me_rmutex = sem_open(env->me_txns->mti_rmname, O_CREAT, mode, 1);
2598 if (!env->me_rmutex) {
2602 sprintf(env->me_txns->mti_wmname, "MDBw%s", hexbuf);
2603 if (sem_unlink(env->me_txns->mti_wmname)) {
2605 if (rc != ENOENT && rc != EINVAL)
2608 env->me_wmutex = sem_open(env->me_txns->mti_wmname, O_CREAT, mode, 1);
2609 if (!env->me_wmutex) {
2613 #else /* __APPLE__ */
2614 pthread_mutexattr_t mattr;
2616 pthread_mutexattr_init(&mattr);
2617 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
2621 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
2622 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
2623 #endif /* __APPLE__ */
2625 env->me_txns->mti_version = MDB_VERSION;
2626 env->me_txns->mti_magic = MDB_MAGIC;
2627 env->me_txns->mti_txnid = 0;
2628 env->me_txns->mti_numreaders = 0;
2629 env->me_txns->mti_me_toggle = 0;
2632 if (env->me_txns->mti_magic != MDB_MAGIC) {
2633 DPUTS("lock region has invalid magic");
2637 if (env->me_txns->mti_version != MDB_VERSION) {
2638 DPRINTF("lock region is version %u, expected version %u",
2639 env->me_txns->mti_version, MDB_VERSION);
2640 rc = MDB_VERSION_MISMATCH;
2644 if (rc != EACCES && rc != EAGAIN) {
2648 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
2649 if (!env->me_rmutex) {
2653 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
2654 if (!env->me_wmutex) {
2660 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
2661 if (!env->me_rmutex) {
2665 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
2666 if (!env->me_wmutex) {
2676 env->me_lfd = INVALID_HANDLE_VALUE;
2681 /** The name of the lock file in the DB environment */
2682 #define LOCKNAME "/lock.mdb"
2683 /** The name of the data file in the DB environment */
2684 #define DATANAME "/data.mdb"
2685 /** The suffix of the lock file when no subdir is used */
2686 #define LOCKSUFF "-lock"
2689 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
2691 int oflags, rc, len, excl;
2692 char *lpath, *dpath;
2695 if (flags & MDB_NOSUBDIR) {
2696 rc = len + sizeof(LOCKSUFF) + len + 1;
2698 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
2703 if (flags & MDB_NOSUBDIR) {
2704 dpath = lpath + len + sizeof(LOCKSUFF);
2705 sprintf(lpath, "%s" LOCKSUFF, path);
2706 strcpy(dpath, path);
2708 dpath = lpath + len + sizeof(LOCKNAME);
2709 sprintf(lpath, "%s" LOCKNAME, path);
2710 sprintf(dpath, "%s" DATANAME, path);
2713 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
2718 if (F_ISSET(flags, MDB_RDONLY)) {
2719 oflags = GENERIC_READ;
2720 len = OPEN_EXISTING;
2722 oflags = GENERIC_READ|GENERIC_WRITE;
2725 mode = FILE_ATTRIBUTE_NORMAL;
2726 if ((env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2727 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2732 if (F_ISSET(flags, MDB_RDONLY))
2735 oflags = O_RDWR | O_CREAT;
2737 if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
2743 if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
2744 /* synchronous fd for meta writes */
2746 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2747 mode |= FILE_FLAG_WRITE_THROUGH;
2748 if ((env->me_mfd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2749 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2754 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2755 oflags |= MDB_DSYNC;
2756 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
2761 env->me_path = strdup(path);
2762 DPRINTF("opened dbenv %p", (void *) env);
2763 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
2764 LAZY_RWLOCK_INIT(&env->me_dblock, NULL);
2766 mdb_env_share_locks(env);
2767 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
2768 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
2769 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
2775 if (env->me_fd != INVALID_HANDLE_VALUE) {
2777 env->me_fd = INVALID_HANDLE_VALUE;
2779 if (env->me_lfd != INVALID_HANDLE_VALUE) {
2781 env->me_lfd = INVALID_HANDLE_VALUE;
2789 mdb_env_close(MDB_env *env)
2796 while (env->me_dpages) {
2797 dp = env->me_dpages;
2798 env->me_dpages = dp->mp_next;
2802 free(env->me_dbs[1]);
2803 free(env->me_dbs[0]);
2807 LAZY_RWLOCK_DESTROY(&env->me_dblock);
2808 pthread_key_delete(env->me_txkey);
2811 munmap(env->me_map, env->me_mapsize);
2816 pid_t pid = getpid();
2818 for (i=0; i<env->me_txns->mti_numreaders; i++)
2819 if (env->me_txns->mti_readers[i].mr_pid == pid)
2820 env->me_txns->mti_readers[i].mr_pid = 0;
2821 munmap(env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
2824 mdb_midl_free(env->me_free_pgs);
2828 /** Compare two items pointing at aligned size_t's */
2830 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
2832 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
2833 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
2836 /** Compare two items pointing at aligned int's */
2838 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
2840 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
2841 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
2844 /** Compare two items pointing at ints of unknown alignment.
2845 * Nodes and keys are guaranteed to be 2-byte aligned.
2848 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
2850 #if BYTE_ORDER == LITTLE_ENDIAN
2851 unsigned short *u, *c;
2854 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
2855 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
2858 } while(!x && u > (unsigned short *)a->mv_data);
2861 return memcmp(a->mv_data, b->mv_data, a->mv_size);
2865 /** Compare two items lexically */
2867 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
2874 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
2880 diff = memcmp(a->mv_data, b->mv_data, len);
2881 return diff ? diff : len_diff<0 ? -1 : len_diff;
2884 /** Compare two items in reverse byte order */
2886 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
2888 const unsigned char *p1, *p2, *p1_lim;
2892 p1_lim = (const unsigned char *)a->mv_data;
2893 p1 = (const unsigned char *)a->mv_data + a->mv_size;
2894 p2 = (const unsigned char *)b->mv_data + b->mv_size;
2896 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
2902 while (p1 > p1_lim) {
2903 diff = *--p1 - *--p2;
2907 return len_diff<0 ? -1 : len_diff;
2910 /** Search for key within a page, using binary search.
2911 * Returns the smallest entry larger or equal to the key.
2912 * If exactp is non-null, stores whether the found entry was an exact match
2913 * in *exactp (1 or 0).
2914 * Updates the cursor index with the index of the found entry.
2915 * If no entry larger or equal to the key is found, returns NULL.
2918 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
2920 unsigned int i = 0, nkeys;
2923 MDB_page *mp = mc->mc_pg[mc->mc_top];
2924 MDB_node *node = NULL;
2929 nkeys = NUMKEYS(mp);
2931 DPRINTF("searching %u keys in %s %spage %zu",
2932 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
2937 low = IS_LEAF(mp) ? 0 : 1;
2939 cmp = mc->mc_dbx->md_cmp;
2941 /* Branch pages have no data, so if using integer keys,
2942 * alignment is guaranteed. Use faster mdb_cmp_int.
2944 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
2945 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
2952 nodekey.mv_size = mc->mc_db->md_pad;
2953 node = NODEPTR(mp, 0); /* fake */
2954 while (low <= high) {
2955 i = (low + high) >> 1;
2956 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
2957 rc = cmp(key, &nodekey);
2958 DPRINTF("found leaf index %u [%s], rc = %i",
2959 i, DKEY(&nodekey), rc);
2968 while (low <= high) {
2969 i = (low + high) >> 1;
2971 node = NODEPTR(mp, i);
2972 nodekey.mv_size = NODEKSZ(node);
2973 nodekey.mv_data = NODEKEY(node);
2975 rc = cmp(key, &nodekey);
2978 DPRINTF("found leaf index %u [%s], rc = %i",
2979 i, DKEY(&nodekey), rc);
2981 DPRINTF("found branch index %u [%s -> %zu], rc = %i",
2982 i, DKEY(&nodekey), NODEPGNO(node), rc);
2993 if (rc > 0) { /* Found entry is less than the key. */
2994 i++; /* Skip to get the smallest entry larger than key. */
2996 node = NODEPTR(mp, i);
2999 *exactp = (rc == 0);
3000 /* store the key index */
3001 mc->mc_ki[mc->mc_top] = i;
3003 /* There is no entry larger or equal to the key. */
3006 /* nodeptr is fake for LEAF2 */
3012 mdb_cursor_adjust(MDB_cursor *mc, func)
3016 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
3017 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
3024 /** Pop a page off the top of the cursor's stack. */
3026 mdb_cursor_pop(MDB_cursor *mc)
3031 top = mc->mc_pg[mc->mc_top];
3036 DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
3037 mc->mc_dbi, (void *) mc);
3041 /** Push a page onto the top of the cursor's stack. */
3043 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
3045 DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
3046 mc->mc_dbi, (void *) mc);
3048 if (mc->mc_snum >= CURSOR_STACK) {
3049 assert(mc->mc_snum < CURSOR_STACK);
3053 mc->mc_top = mc->mc_snum++;
3054 mc->mc_pg[mc->mc_top] = mp;
3055 mc->mc_ki[mc->mc_top] = 0;
3060 /** Find the address of the page corresponding to a given page number.
3061 * @param[in] txn the transaction for this access.
3062 * @param[in] pgno the page number for the page to retrieve.
3063 * @param[out] ret address of a pointer where the page's address will be stored.
3064 * @return 0 on success, non-zero on failure.
3067 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
3071 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
3073 x = mdb_mid2l_search(txn->mt_u.dirty_list, pgno);
3074 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
3075 p = txn->mt_u.dirty_list[x].mptr;
3079 if (pgno <= txn->mt_env->me_metas[txn->mt_toggle]->mm_last_pg)
3080 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
3084 DPRINTF("page %zu not found", pgno);
3087 return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
3090 /** Search for the page a given key should be in.
3091 * Pushes parent pages on the cursor stack. This function continues a
3092 * search on a cursor that has already been initialized. (Usually by
3093 * #mdb_page_search() but also by #mdb_node_move().)
3094 * @param[in,out] mc the cursor for this operation.
3095 * @param[in] key the key to search for. If NULL, search for the lowest
3096 * page. (This is used by #mdb_cursor_first().)
3097 * @param[in] modify If true, visited pages are updated with new page numbers.
3098 * @return 0 on success, non-zero on failure.
3101 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
3103 MDB_page *mp = mc->mc_pg[mc->mc_top];
3108 while (IS_BRANCH(mp)) {
3112 DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
3113 assert(NUMKEYS(mp) > 1);
3114 DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
3116 if (key == NULL) /* Initialize cursor to first page. */
3118 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
3119 /* cursor to last page */
3123 node = mdb_node_search(mc, key, &exact);
3125 i = NUMKEYS(mp) - 1;
3127 i = mc->mc_ki[mc->mc_top];
3136 DPRINTF("following index %u for key [%s]",
3138 assert(i < NUMKEYS(mp));
3139 node = NODEPTR(mp, i);
3141 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp)))
3144 mc->mc_ki[mc->mc_top] = i;
3145 if ((rc = mdb_cursor_push(mc, mp)))
3149 if ((rc = mdb_page_touch(mc)) != 0)
3151 mp = mc->mc_pg[mc->mc_top];
3156 DPRINTF("internal error, index points to a %02X page!?",
3158 return MDB_CORRUPTED;
3161 DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
3162 key ? DKEY(key) : NULL);
3167 /** Search for the page a given key should be in.
3168 * Pushes parent pages on the cursor stack. This function just sets up
3169 * the search; it finds the root page for \b mc's database and sets this
3170 * as the root of the cursor's stack. Then #mdb_page_search_root() is
3171 * called to complete the search.
3172 * @param[in,out] mc the cursor for this operation.
3173 * @param[in] key the key to search for. If NULL, search for the lowest
3174 * page. (This is used by #mdb_cursor_first().)
3175 * @param[in] modify If true, visited pages are updated with new page numbers.
3176 * @return 0 on success, non-zero on failure.
3179 mdb_page_search(MDB_cursor *mc, MDB_val *key, int modify)
3184 /* Make sure the txn is still viable, then find the root from
3185 * the txn's db table.
3187 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
3188 DPUTS("transaction has failed, must abort");
3191 /* Make sure we're using an up-to-date root */
3192 if (mc->mc_dbi > MAIN_DBI) {
3193 if ((*mc->mc_dbflag & DB_STALE) ||
3194 (modify && !(*mc->mc_dbflag & DB_DIRTY))) {
3196 unsigned char dbflag = 0;
3197 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
3198 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, modify);
3201 if (*mc->mc_dbflag & DB_STALE) {
3204 MDB_node *leaf = mdb_node_search(&mc2,
3205 &mc->mc_dbx->md_name, &exact);
3207 return MDB_NOTFOUND;
3208 mdb_node_read(mc->mc_txn, leaf, &data);
3209 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
3213 *mc->mc_dbflag = dbflag;
3216 root = mc->mc_db->md_root;
3218 if (root == P_INVALID) { /* Tree is empty. */
3219 DPUTS("tree is empty");
3220 return MDB_NOTFOUND;
3225 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0])))
3231 DPRINTF("db %u root page %zu has flags 0x%X",
3232 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
3235 if ((rc = mdb_page_touch(mc)))
3239 return mdb_page_search_root(mc, key, modify);
3242 /** Return the data associated with a given node.
3243 * @param[in] txn The transaction for this operation.
3244 * @param[in] leaf The node being read.
3245 * @param[out] data Updated to point to the node's data.
3246 * @return 0 on success, non-zero on failure.
3249 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
3251 MDB_page *omp; /* overflow page */
3255 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
3256 data->mv_size = NODEDSZ(leaf);
3257 data->mv_data = NODEDATA(leaf);
3261 /* Read overflow data.
3263 data->mv_size = NODEDSZ(leaf);
3264 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
3265 if ((rc = mdb_page_get(txn, pgno, &omp))) {
3266 DPRINTF("read overflow page %zu failed", pgno);
3269 data->mv_data = METADATA(omp);
3275 mdb_get(MDB_txn *txn, MDB_dbi dbi,
3276 MDB_val *key, MDB_val *data)
3285 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
3287 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3290 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3294 mdb_cursor_init(&mc, txn, dbi, &mx);
3295 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
3298 /** Find a sibling for a page.
3299 * Replaces the page at the top of the cursor's stack with the
3300 * specified sibling, if one exists.
3301 * @param[in] mc The cursor for this operation.
3302 * @param[in] move_right Non-zero if the right sibling is requested,
3303 * otherwise the left sibling.
3304 * @return 0 on success, non-zero on failure.
3307 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
3313 if (mc->mc_snum < 2) {
3314 return MDB_NOTFOUND; /* root has no siblings */
3318 DPRINTF("parent page is page %zu, index %u",
3319 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]);
3321 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
3322 : (mc->mc_ki[mc->mc_top] == 0)) {
3323 DPRINTF("no more keys left, moving to %s sibling",
3324 move_right ? "right" : "left");
3325 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS)
3329 mc->mc_ki[mc->mc_top]++;
3331 mc->mc_ki[mc->mc_top]--;
3332 DPRINTF("just moving to %s index key %u",
3333 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]);
3335 assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
3337 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3338 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp)))
3341 mdb_cursor_push(mc, mp);
3346 /** Move the cursor to the next data item. */
3348 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3354 if (mc->mc_flags & C_EOF) {
3355 return MDB_NOTFOUND;
3358 assert(mc->mc_flags & C_INITIALIZED);
3360 mp = mc->mc_pg[mc->mc_top];
3362 if (mc->mc_db->md_flags & MDB_DUPSORT) {
3363 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3364 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3365 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
3366 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
3367 if (op != MDB_NEXT || rc == MDB_SUCCESS)
3371 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3372 if (op == MDB_NEXT_DUP)
3373 return MDB_NOTFOUND;
3377 DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3379 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
3380 DPUTS("=====> move to next sibling page");
3381 if (mdb_cursor_sibling(mc, 1) != MDB_SUCCESS) {
3382 mc->mc_flags |= C_EOF;
3383 mc->mc_flags &= ~C_INITIALIZED;
3384 return MDB_NOTFOUND;
3386 mp = mc->mc_pg[mc->mc_top];
3387 DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3389 mc->mc_ki[mc->mc_top]++;
3391 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3392 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3395 key->mv_size = mc->mc_db->md_pad;
3396 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3400 assert(IS_LEAF(mp));
3401 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3403 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3404 mdb_xcursor_init1(mc, leaf);
3407 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3410 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3411 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3412 if (rc != MDB_SUCCESS)
3417 MDB_SET_KEY(leaf, key);
3421 /** Move the cursor to the previous data item. */
3423 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3429 assert(mc->mc_flags & C_INITIALIZED);
3431 mp = mc->mc_pg[mc->mc_top];
3433 if (mc->mc_db->md_flags & MDB_DUPSORT) {
3434 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3435 if (op == MDB_PREV || op == MDB_PREV_DUP) {
3436 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3437 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
3438 if (op != MDB_PREV || rc == MDB_SUCCESS)
3441 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3442 if (op == MDB_PREV_DUP)
3443 return MDB_NOTFOUND;
3448 DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3450 if (mc->mc_ki[mc->mc_top] == 0) {
3451 DPUTS("=====> move to prev sibling page");
3452 if (mdb_cursor_sibling(mc, 0) != MDB_SUCCESS) {
3453 mc->mc_flags &= ~C_INITIALIZED;
3454 return MDB_NOTFOUND;
3456 mp = mc->mc_pg[mc->mc_top];
3457 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
3458 DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3460 mc->mc_ki[mc->mc_top]--;
3462 mc->mc_flags &= ~C_EOF;
3464 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3465 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3468 key->mv_size = mc->mc_db->md_pad;
3469 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3473 assert(IS_LEAF(mp));
3474 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3476 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3477 mdb_xcursor_init1(mc, leaf);
3480 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3483 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3484 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3485 if (rc != MDB_SUCCESS)
3490 MDB_SET_KEY(leaf, key);
3494 /** Set the cursor on a specific data item. */
3496 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3497 MDB_cursor_op op, int *exactp)
3506 assert(key->mv_size > 0);
3508 /* See if we're already on the right page */
3509 if (mc->mc_flags & C_INITIALIZED) {
3512 mp = mc->mc_pg[mc->mc_top];
3514 mc->mc_ki[mc->mc_top] = 0;
3515 return MDB_NOTFOUND;
3517 if (mp->mp_flags & P_LEAF2) {
3518 nodekey.mv_size = mc->mc_db->md_pad;
3519 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
3521 leaf = NODEPTR(mp, 0);
3522 MDB_SET_KEY(leaf, &nodekey);
3524 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3526 /* Probably happens rarely, but first node on the page
3527 * was the one we wanted.
3529 mc->mc_ki[mc->mc_top] = 0;
3530 leaf = NODEPTR(mp, 0);
3537 unsigned int nkeys = NUMKEYS(mp);
3539 if (mp->mp_flags & P_LEAF2) {
3540 nodekey.mv_data = LEAF2KEY(mp,
3541 nkeys-1, nodekey.mv_size);
3543 leaf = NODEPTR(mp, nkeys-1);
3544 MDB_SET_KEY(leaf, &nodekey);
3546 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3548 /* last node was the one we wanted */
3549 mc->mc_ki[mc->mc_top] = nkeys-1;
3550 leaf = NODEPTR(mp, nkeys-1);
3556 /* This is definitely the right page, skip search_page */
3561 /* If any parents have right-sibs, search.
3562 * Otherwise, there's nothing further.
3564 for (i=0; i<mc->mc_top; i++)
3566 NUMKEYS(mc->mc_pg[i])-1)
3568 if (i == mc->mc_top) {
3569 /* There are no other pages */
3570 mc->mc_ki[mc->mc_top] = nkeys;
3571 return MDB_NOTFOUND;
3575 /* There are no other pages */
3576 mc->mc_ki[mc->mc_top] = 0;
3577 return MDB_NOTFOUND;
3581 rc = mdb_page_search(mc, key, 0);
3582 if (rc != MDB_SUCCESS)
3585 mp = mc->mc_pg[mc->mc_top];
3586 assert(IS_LEAF(mp));
3589 leaf = mdb_node_search(mc, key, exactp);
3590 if (exactp != NULL && !*exactp) {
3591 /* MDB_SET specified and not an exact match. */
3592 return MDB_NOTFOUND;
3596 DPUTS("===> inexact leaf not found, goto sibling");
3597 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
3598 return rc; /* no entries matched */
3599 mp = mc->mc_pg[mc->mc_top];
3600 assert(IS_LEAF(mp));
3601 leaf = NODEPTR(mp, 0);
3605 mc->mc_flags |= C_INITIALIZED;
3606 mc->mc_flags &= ~C_EOF;
3609 key->mv_size = mc->mc_db->md_pad;
3610 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3614 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3615 mdb_xcursor_init1(mc, leaf);
3618 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3619 if (op == MDB_SET || op == MDB_SET_RANGE) {
3620 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3623 if (op == MDB_GET_BOTH) {
3629 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
3630 if (rc != MDB_SUCCESS)
3633 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
3635 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
3637 rc = mc->mc_dbx->md_dcmp(data, &d2);
3639 if (op == MDB_GET_BOTH || rc > 0)
3640 return MDB_NOTFOUND;
3645 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3646 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3651 /* The key already matches in all other cases */
3652 if (op == MDB_SET_RANGE)
3653 MDB_SET_KEY(leaf, key);
3654 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
3659 /** Move the cursor to the first item in the database. */
3661 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3666 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3667 rc = mdb_page_search(mc, NULL, 0);
3668 if (rc != MDB_SUCCESS)
3671 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3673 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
3674 mc->mc_flags |= C_INITIALIZED;
3675 mc->mc_flags &= ~C_EOF;
3677 mc->mc_ki[mc->mc_top] = 0;
3679 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3680 key->mv_size = mc->mc_db->md_pad;
3681 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
3686 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3687 mdb_xcursor_init1(mc, leaf);
3688 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3693 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3694 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3698 MDB_SET_KEY(leaf, key);
3702 /** Move the cursor to the last item in the database. */
3704 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3710 lkey.mv_size = MAXKEYSIZE+1;
3711 lkey.mv_data = NULL;
3713 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3714 rc = mdb_page_search(mc, &lkey, 0);
3715 if (rc != MDB_SUCCESS)
3718 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3720 leaf = NODEPTR(mc->mc_pg[mc->mc_top], NUMKEYS(mc->mc_pg[mc->mc_top])-1);
3721 mc->mc_flags |= C_INITIALIZED;
3722 mc->mc_flags &= ~C_EOF;
3724 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
3726 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3727 key->mv_size = mc->mc_db->md_pad;
3728 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
3733 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3734 mdb_xcursor_init1(mc, leaf);
3735 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3740 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3741 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3746 MDB_SET_KEY(leaf, key);
3751 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3761 case MDB_GET_BOTH_RANGE:
3762 if (data == NULL || mc->mc_xcursor == NULL) {
3769 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3771 } else if (op == MDB_SET_RANGE)
3772 rc = mdb_cursor_set(mc, key, data, op, NULL);
3774 rc = mdb_cursor_set(mc, key, data, op, &exact);
3776 case MDB_GET_MULTIPLE:
3778 !(mc->mc_db->md_flags & MDB_DUPFIXED) ||
3779 !(mc->mc_flags & C_INITIALIZED)) {
3784 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
3785 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
3788 case MDB_NEXT_MULTIPLE:
3790 !(mc->mc_db->md_flags & MDB_DUPFIXED)) {
3794 if (!(mc->mc_flags & C_INITIALIZED))
3795 rc = mdb_cursor_first(mc, key, data);
3797 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
3798 if (rc == MDB_SUCCESS) {
3799 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
3802 mx = &mc->mc_xcursor->mx_cursor;
3803 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
3805 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
3806 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
3814 case MDB_NEXT_NODUP:
3815 if (!(mc->mc_flags & C_INITIALIZED))
3816 rc = mdb_cursor_first(mc, key, data);
3818 rc = mdb_cursor_next(mc, key, data, op);
3822 case MDB_PREV_NODUP:
3823 if (!(mc->mc_flags & C_INITIALIZED) || (mc->mc_flags & C_EOF))
3824 rc = mdb_cursor_last(mc, key, data);
3826 rc = mdb_cursor_prev(mc, key, data, op);
3829 rc = mdb_cursor_first(mc, key, data);
3833 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
3834 !(mc->mc_flags & C_INITIALIZED) ||
3835 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3839 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3842 rc = mdb_cursor_last(mc, key, data);
3846 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
3847 !(mc->mc_flags & C_INITIALIZED) ||
3848 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3852 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3855 DPRINTF("unhandled/unimplemented cursor operation %u", op);
3863 /** Touch all the pages in the cursor stack.
3864 * Makes sure all the pages are writable, before attempting a write operation.
3865 * @param[in] mc The cursor to operate on.
3868 mdb_cursor_touch(MDB_cursor *mc)
3872 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
3874 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
3875 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 1);
3878 *mc->mc_dbflag = DB_DIRTY;
3880 for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
3881 rc = mdb_page_touch(mc);
3885 mc->mc_top = mc->mc_snum-1;
3890 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3893 MDB_node *leaf = NULL;
3894 MDB_val xdata, *rdata, dkey;
3898 unsigned int mcount = 0;
3901 char pbuf[PAGESIZE];
3902 char dbuf[MAXKEYSIZE+1];
3903 unsigned int nflags;
3906 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
3909 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
3910 mc->mc_dbi, DKEY(key), key ? key->mv_size:0, data->mv_size);
3914 if (flags == MDB_CURRENT) {
3915 if (!(mc->mc_flags & C_INITIALIZED))
3918 } else if (mc->mc_db->md_root == P_INVALID) {
3920 /* new database, write a root leaf page */
3921 DPUTS("allocating new root leaf page");
3922 if ((np = mdb_page_new(mc, P_LEAF, 1)) == NULL) {
3926 mdb_cursor_push(mc, np);
3927 mc->mc_db->md_root = np->mp_pgno;
3928 mc->mc_db->md_depth++;
3929 *mc->mc_dbflag = DB_DIRTY;
3930 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
3932 np->mp_flags |= P_LEAF2;
3933 mc->mc_flags |= C_INITIALIZED;
3939 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
3940 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
3941 DPRINTF("duplicate key [%s]", DKEY(key));
3943 return MDB_KEYEXIST;
3945 if (rc && rc != MDB_NOTFOUND)
3949 /* Cursor is positioned, now make sure all pages are writable */
3950 rc2 = mdb_cursor_touch(mc);
3955 /* The key already exists */
3956 if (rc == MDB_SUCCESS) {
3957 /* there's only a key anyway, so this is a no-op */
3958 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3959 unsigned int ksize = mc->mc_db->md_pad;
3960 if (key->mv_size != ksize)
3962 if (flags == MDB_CURRENT) {
3963 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
3964 memcpy(ptr, key->mv_data, ksize);
3969 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3972 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
3973 /* Was a single item before, must convert now */
3975 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3976 /* Just overwrite the current item */
3977 if (flags == MDB_CURRENT)
3980 dkey.mv_size = NODEDSZ(leaf);
3981 dkey.mv_data = NODEDATA(leaf);
3982 /* data matches, ignore it */
3983 if (!mc->mc_dbx->md_dcmp(data, &dkey))
3984 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
3986 /* create a fake page for the dup items */
3987 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
3988 dkey.mv_data = dbuf;
3989 fp = (MDB_page *)pbuf;
3990 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
3991 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
3992 fp->mp_lower = PAGEHDRSZ;
3993 fp->mp_upper = PAGEHDRSZ + dkey.mv_size + data->mv_size;
3994 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
3995 fp->mp_flags |= P_LEAF2;
3996 fp->mp_pad = data->mv_size;
3998 fp->mp_upper += 2 * sizeof(indx_t) + 2 * NODESIZE +
3999 (dkey.mv_size & 1) + (data->mv_size & 1);
4001 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4004 xdata.mv_size = fp->mp_upper;
4005 xdata.mv_data = pbuf;
4009 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
4010 /* See if we need to convert from fake page to subDB */
4012 unsigned int offset;
4015 fp = NODEDATA(leaf);
4016 if (flags == MDB_CURRENT) {
4017 fp->mp_flags |= P_DIRTY;
4018 #ifdef MISALIGNED_OK
4019 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4022 unsigned short *src, *dst;
4024 dst = (unsigned short *)&fp->mp_pgno;
4025 src = (unsigned short *)&mc->mc_pg[mc->mc_top]->mp_pgno;
4026 for (i=0; i<sizeof(fp->mp_pgno)/sizeof(unsigned short); i++)
4030 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
4034 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4035 offset = fp->mp_pad;
4037 offset = NODESIZE + sizeof(indx_t) + data->mv_size;
4039 offset += offset & 1;
4040 if (NODESIZE + sizeof(indx_t) + NODEKSZ(leaf) + NODEDSZ(leaf) +
4041 offset >= (mc->mc_txn->mt_env->me_psize - PAGEHDRSZ) /
4043 /* yes, convert it */
4045 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4046 dummy.md_pad = fp->mp_pad;
4047 dummy.md_flags = MDB_DUPFIXED;
4048 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
4049 dummy.md_flags |= MDB_INTEGERKEY;
4052 dummy.md_branch_pages = 0;
4053 dummy.md_leaf_pages = 1;
4054 dummy.md_overflow_pages = 0;
4055 dummy.md_entries = NUMKEYS(fp);
4057 xdata.mv_size = sizeof(MDB_db);
4058 xdata.mv_data = &dummy;
4059 mp = mdb_page_alloc(mc, 1);
4062 offset = mc->mc_txn->mt_env->me_psize - NODEDSZ(leaf);
4063 flags |= F_DUPDATA|F_SUBDATA;
4064 dummy.md_root = mp->mp_pgno;
4066 /* no, just grow it */
4068 xdata.mv_size = NODEDSZ(leaf) + offset;
4069 xdata.mv_data = pbuf;
4070 mp = (MDB_page *)pbuf;
4071 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4074 mp->mp_flags = fp->mp_flags | P_DIRTY;
4075 mp->mp_pad = fp->mp_pad;
4076 mp->mp_lower = fp->mp_lower;
4077 mp->mp_upper = fp->mp_upper + offset;
4079 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
4081 nsize = NODEDSZ(leaf) - fp->mp_upper;
4082 memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper, nsize);
4083 for (i=0; i<NUMKEYS(fp); i++)
4084 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
4086 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4090 /* data is on sub-DB, just store it */
4091 flags |= F_DUPDATA|F_SUBDATA;
4095 /* same size, just replace it */
4096 if (!F_ISSET(leaf->mn_flags, F_BIGDATA) &&
4097 NODEDSZ(leaf) == data->mv_size) {
4098 if (F_ISSET(flags, MDB_RESERVE))
4099 data->mv_data = NODEDATA(leaf);
4101 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
4104 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4106 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
4112 nflags = flags & NODE_ADD_FLAGS;
4113 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
4114 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
4115 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
4116 nflags &= ~MDB_APPEND;
4117 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
4119 /* There is room already in this leaf page. */
4120 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
4121 if (rc == 0 && !do_sub) {
4122 /* Adjust other cursors pointing to mp */
4123 MDB_cursor *m2, *m3;
4124 MDB_dbi dbi = mc->mc_dbi;
4125 unsigned i = mc->mc_top;
4126 MDB_page *mp = mc->mc_pg[i];
4128 if (mc->mc_flags & C_SUB)
4131 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
4132 if (mc->mc_flags & C_SUB)
4133 m3 = &m2->mc_xcursor->mx_cursor;
4136 if (m3 == mc) continue;
4137 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
4144 if (rc != MDB_SUCCESS)
4145 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4147 /* Now store the actual data in the child DB. Note that we're
4148 * storing the user data in the keys field, so there are strict
4149 * size limits on dupdata. The actual data fields of the child
4150 * DB are all zero size.
4158 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4159 if (flags & MDB_CURRENT) {
4160 xflags = MDB_CURRENT;
4162 mdb_xcursor_init1(mc, leaf);
4163 xflags = (flags & MDB_NODUPDATA) ? MDB_NOOVERWRITE : 0;
4165 /* converted, write the original data first */
4167 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
4171 /* Adjust other cursors pointing to mp */
4173 unsigned i = mc->mc_top;
4174 MDB_page *mp = mc->mc_pg[i];
4176 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4177 if (m2 == mc) continue;
4178 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
4179 mdb_xcursor_init1(m2, leaf);
4184 xflags |= (flags & MDB_APPEND);
4185 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
4186 if (flags & F_SUBDATA) {
4187 db = NODEDATA(leaf);
4188 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4191 /* sub-writes might have failed so check rc again.
4192 * Don't increment count if we just replaced an existing item.
4194 if (!rc && !(flags & MDB_CURRENT))
4195 mc->mc_db->md_entries++;
4196 if (flags & MDB_MULTIPLE) {
4198 if (mcount < data[1].mv_size) {
4199 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
4200 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4210 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
4215 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
4218 if (!mc->mc_flags & C_INITIALIZED)
4221 rc = mdb_cursor_touch(mc);
4225 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4227 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4228 if (flags != MDB_NODUPDATA) {
4229 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
4230 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
4232 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
4233 /* If sub-DB still has entries, we're done */
4234 if (mc->mc_xcursor->mx_db.md_entries) {
4235 if (leaf->mn_flags & F_SUBDATA) {
4236 /* update subDB info */
4237 MDB_db *db = NODEDATA(leaf);
4238 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4240 /* shrink fake page */
4241 mdb_node_shrink(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4243 mc->mc_db->md_entries--;
4246 /* otherwise fall thru and delete the sub-DB */
4249 if (leaf->mn_flags & F_SUBDATA) {
4250 /* add all the child DB's pages to the free list */
4251 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
4252 if (rc == MDB_SUCCESS) {
4253 mc->mc_db->md_entries -=
4254 mc->mc_xcursor->mx_db.md_entries;
4259 return mdb_cursor_del0(mc, leaf);
4262 /** Allocate and initialize new pages for a database.
4263 * @param[in] mc a cursor on the database being added to.
4264 * @param[in] flags flags defining what type of page is being allocated.
4265 * @param[in] num the number of pages to allocate. This is usually 1,
4266 * unless allocating overflow pages for a large record.
4267 * @return Address of a page, or NULL on failure.
4270 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num)
4274 if ((np = mdb_page_alloc(mc, num)) == NULL)
4276 DPRINTF("allocated new mpage %zu, page size %u",
4277 np->mp_pgno, mc->mc_txn->mt_env->me_psize);
4278 np->mp_flags = flags | P_DIRTY;
4279 np->mp_lower = PAGEHDRSZ;
4280 np->mp_upper = mc->mc_txn->mt_env->me_psize;
4283 mc->mc_db->md_branch_pages++;
4284 else if (IS_LEAF(np))
4285 mc->mc_db->md_leaf_pages++;
4286 else if (IS_OVERFLOW(np)) {
4287 mc->mc_db->md_overflow_pages += num;
4294 /** Calculate the size of a leaf node.
4295 * The size depends on the environment's page size; if a data item
4296 * is too large it will be put onto an overflow page and the node
4297 * size will only include the key and not the data. Sizes are always
4298 * rounded up to an even number of bytes, to guarantee 2-byte alignment
4299 * of the #MDB_node headers.
4300 * @param[in] env The environment handle.
4301 * @param[in] key The key for the node.
4302 * @param[in] data The data for the node.
4303 * @return The number of bytes needed to store the node.
4306 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
4310 sz = LEAFSIZE(key, data);
4311 if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
4312 /* put on overflow page */
4313 sz -= data->mv_size - sizeof(pgno_t);
4317 return sz + sizeof(indx_t);
4320 /** Calculate the size of a branch node.
4321 * The size should depend on the environment's page size but since
4322 * we currently don't support spilling large keys onto overflow
4323 * pages, it's simply the size of the #MDB_node header plus the
4324 * size of the key. Sizes are always rounded up to an even number
4325 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
4326 * @param[in] env The environment handle.
4327 * @param[in] key The key for the node.
4328 * @return The number of bytes needed to store the node.
4331 mdb_branch_size(MDB_env *env, MDB_val *key)
4336 if (sz >= env->me_psize / MDB_MINKEYS) {
4337 /* put on overflow page */
4338 /* not implemented */
4339 /* sz -= key->size - sizeof(pgno_t); */
4342 return sz + sizeof(indx_t);
4345 /** Add a node to the page pointed to by the cursor.
4346 * @param[in] mc The cursor for this operation.
4347 * @param[in] indx The index on the page where the new node should be added.
4348 * @param[in] key The key for the new node.
4349 * @param[in] data The data for the new node, if any.
4350 * @param[in] pgno The page number, if adding a branch node.
4351 * @param[in] flags Flags for the node.
4352 * @return 0 on success, non-zero on failure. Possible errors are:
4354 * <li>ENOMEM - failed to allocate overflow pages for the node.
4355 * <li>ENOSPC - there is insufficient room in the page. This error
4356 * should never happen since all callers already calculate the
4357 * page's free space before calling this function.
4361 mdb_node_add(MDB_cursor *mc, indx_t indx,
4362 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
4365 size_t node_size = NODESIZE;
4368 MDB_page *mp = mc->mc_pg[mc->mc_top];
4369 MDB_page *ofp = NULL; /* overflow page */
4372 assert(mp->mp_upper >= mp->mp_lower);
4374 DPRINTF("add to %s %spage %zu index %i, data size %zu key size %zu [%s]",
4375 IS_LEAF(mp) ? "leaf" : "branch",
4376 IS_SUBP(mp) ? "sub-" : "",
4377 mp->mp_pgno, indx, data ? data->mv_size : 0,
4378 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
4381 /* Move higher keys up one slot. */
4382 int ksize = mc->mc_db->md_pad, dif;
4383 char *ptr = LEAF2KEY(mp, indx, ksize);
4384 dif = NUMKEYS(mp) - indx;
4386 memmove(ptr+ksize, ptr, dif*ksize);
4387 /* insert new key */
4388 memcpy(ptr, key->mv_data, ksize);
4390 /* Just using these for counting */
4391 mp->mp_lower += sizeof(indx_t);
4392 mp->mp_upper -= ksize - sizeof(indx_t);
4397 node_size += key->mv_size;
4401 if (F_ISSET(flags, F_BIGDATA)) {
4402 /* Data already on overflow page. */
4403 node_size += sizeof(pgno_t);
4404 } else if (data->mv_size >= mc->mc_txn->mt_env->me_psize / MDB_MINKEYS) {
4405 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
4406 /* Put data on overflow page. */
4407 DPRINTF("data size is %zu, put on overflow page",
4409 node_size += sizeof(pgno_t);
4410 if ((ofp = mdb_page_new(mc, P_OVERFLOW, ovpages)) == NULL)
4412 DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
4415 node_size += data->mv_size;
4418 node_size += node_size & 1;
4420 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
4421 DPRINTF("not enough room in page %zu, got %u ptrs",
4422 mp->mp_pgno, NUMKEYS(mp));
4423 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
4424 mp->mp_upper - mp->mp_lower);
4425 DPRINTF("node size = %zu", node_size);
4429 /* Move higher pointers up one slot. */
4430 for (i = NUMKEYS(mp); i > indx; i--)
4431 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
4433 /* Adjust free space offsets. */
4434 ofs = mp->mp_upper - node_size;
4435 assert(ofs >= mp->mp_lower + sizeof(indx_t));
4436 mp->mp_ptrs[indx] = ofs;
4438 mp->mp_lower += sizeof(indx_t);
4440 /* Write the node data. */
4441 node = NODEPTR(mp, indx);
4442 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
4443 node->mn_flags = flags;
4445 SETDSZ(node,data->mv_size);
4450 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
4455 if (F_ISSET(flags, F_BIGDATA))
4456 memcpy(node->mn_data + key->mv_size, data->mv_data,
4458 else if (F_ISSET(flags, MDB_RESERVE))
4459 data->mv_data = node->mn_data + key->mv_size;
4461 memcpy(node->mn_data + key->mv_size, data->mv_data,
4464 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
4466 if (F_ISSET(flags, MDB_RESERVE))
4467 data->mv_data = METADATA(ofp);
4469 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
4476 /** Delete the specified node from a page.
4477 * @param[in] mp The page to operate on.
4478 * @param[in] indx The index of the node to delete.
4479 * @param[in] ksize The size of a node. Only used if the page is
4480 * part of a #MDB_DUPFIXED database.
4483 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
4486 indx_t i, j, numkeys, ptr;
4490 DPRINTF("delete node %u on %s page %zu", indx,
4491 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
4492 assert(indx < NUMKEYS(mp));
4495 int x = NUMKEYS(mp) - 1 - indx;
4496 base = LEAF2KEY(mp, indx, ksize);
4498 memmove(base, base + ksize, x * ksize);
4499 mp->mp_lower -= sizeof(indx_t);
4500 mp->mp_upper += ksize - sizeof(indx_t);
4504 node = NODEPTR(mp, indx);
4505 sz = NODESIZE + node->mn_ksize;
4507 if (F_ISSET(node->mn_flags, F_BIGDATA))
4508 sz += sizeof(pgno_t);
4510 sz += NODEDSZ(node);
4514 ptr = mp->mp_ptrs[indx];
4515 numkeys = NUMKEYS(mp);
4516 for (i = j = 0; i < numkeys; i++) {
4518 mp->mp_ptrs[j] = mp->mp_ptrs[i];
4519 if (mp->mp_ptrs[i] < ptr)
4520 mp->mp_ptrs[j] += sz;
4525 base = (char *)mp + mp->mp_upper;
4526 memmove(base + sz, base, ptr - mp->mp_upper);
4528 mp->mp_lower -= sizeof(indx_t);
4532 /** Compact the main page after deleting a node on a subpage.
4533 * @param[in] mp The main page to operate on.
4534 * @param[in] indx The index of the subpage on the main page.
4537 mdb_node_shrink(MDB_page *mp, indx_t indx)
4544 indx_t i, numkeys, ptr;
4546 node = NODEPTR(mp, indx);
4547 sp = (MDB_page *)NODEDATA(node);
4548 osize = NODEDSZ(node);
4550 delta = sp->mp_upper - sp->mp_lower;
4551 SETDSZ(node, osize - delta);
4552 xp = (MDB_page *)((char *)sp + delta);
4554 /* shift subpage upward */
4556 nsize = NUMKEYS(sp) * sp->mp_pad;
4557 memmove(METADATA(xp), METADATA(sp), nsize);
4560 nsize = osize - sp->mp_upper;
4561 numkeys = NUMKEYS(sp);
4562 for (i=numkeys-1; i>=0; i--)
4563 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
4565 xp->mp_upper = sp->mp_lower;
4566 xp->mp_lower = sp->mp_lower;
4567 xp->mp_flags = sp->mp_flags;
4568 xp->mp_pad = sp->mp_pad;
4569 xp->mp_pgno = mp->mp_pgno;
4571 /* shift lower nodes upward */
4572 ptr = mp->mp_ptrs[indx];
4573 numkeys = NUMKEYS(mp);
4574 for (i = 0; i < numkeys; i++) {
4575 if (mp->mp_ptrs[i] <= ptr)
4576 mp->mp_ptrs[i] += delta;
4579 base = (char *)mp + mp->mp_upper;
4580 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
4581 mp->mp_upper += delta;
4584 /** Initial setup of a sorted-dups cursor.
4585 * Sorted duplicates are implemented as a sub-database for the given key.
4586 * The duplicate data items are actually keys of the sub-database.
4587 * Operations on the duplicate data items are performed using a sub-cursor
4588 * initialized when the sub-database is first accessed. This function does
4589 * the preliminary setup of the sub-cursor, filling in the fields that
4590 * depend only on the parent DB.
4591 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4594 mdb_xcursor_init0(MDB_cursor *mc)
4596 MDB_xcursor *mx = mc->mc_xcursor;
4598 mx->mx_cursor.mc_xcursor = NULL;
4599 mx->mx_cursor.mc_txn = mc->mc_txn;
4600 mx->mx_cursor.mc_db = &mx->mx_db;
4601 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
4602 mx->mx_cursor.mc_dbi = mc->mc_dbi+1;
4603 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
4604 mx->mx_cursor.mc_snum = 0;
4605 mx->mx_cursor.mc_flags = C_SUB;
4606 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
4607 mx->mx_dbx.md_dcmp = NULL;
4608 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
4611 /** Final setup of a sorted-dups cursor.
4612 * Sets up the fields that depend on the data from the main cursor.
4613 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4614 * @param[in] node The data containing the #MDB_db record for the
4615 * sorted-dup database.
4618 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
4620 MDB_xcursor *mx = mc->mc_xcursor;
4622 if (node->mn_flags & F_SUBDATA) {
4623 MDB_db *db = NODEDATA(node);
4625 mx->mx_cursor.mc_snum = 0;
4626 mx->mx_cursor.mc_flags = C_SUB;
4628 MDB_page *fp = NODEDATA(node);
4629 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
4630 mx->mx_db.md_flags = 0;
4631 mx->mx_db.md_depth = 1;
4632 mx->mx_db.md_branch_pages = 0;
4633 mx->mx_db.md_leaf_pages = 1;
4634 mx->mx_db.md_overflow_pages = 0;
4635 mx->mx_db.md_entries = NUMKEYS(fp);
4636 #ifdef MISALIGNED_OK
4637 mx->mx_db.md_root = fp->mp_pgno;
4640 unsigned short *src, *dst;
4642 dst = (unsigned short *)&mx->mx_db.md_root;
4643 src = (unsigned short *)&fp->mp_pgno;
4644 for (i=0; i<sizeof(fp->mp_pgno)/sizeof(unsigned short); i++)
4648 mx->mx_cursor.mc_snum = 1;
4649 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
4650 mx->mx_cursor.mc_top = 0;
4651 mx->mx_cursor.mc_pg[0] = fp;
4652 mx->mx_cursor.mc_ki[0] = 0;
4653 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4654 mx->mx_db.md_flags = MDB_DUPFIXED;
4655 mx->mx_db.md_pad = fp->mp_pad;
4656 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
4657 mx->mx_db.md_flags |= MDB_INTEGERKEY;
4660 DPRINTF("Sub-db %u for db %u root page %zu", mx->mx_cursor.mc_dbi, mc->mc_dbi,
4662 mx->mx_dbflag = (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY)) ?
4664 mx->mx_dbx.md_name.mv_data = NODEKEY(node);
4665 mx->mx_dbx.md_name.mv_size = node->mn_ksize;
4666 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
4667 mx->mx_dbx.md_cmp = mdb_cmp_long;
4670 /** Initialize a cursor for a given transaction and database. */
4672 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
4677 mc->mc_db = &txn->mt_dbs[dbi];
4678 mc->mc_dbx = &txn->mt_dbxs[dbi];
4679 mc->mc_dbflag = &txn->mt_dbflags[dbi];
4682 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4684 mc->mc_xcursor = mx;
4685 mdb_xcursor_init0(mc);
4687 mc->mc_xcursor = NULL;
4692 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
4695 MDB_xcursor *mx = NULL;
4696 size_t size = sizeof(MDB_cursor);
4698 if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
4701 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
4702 size += sizeof(MDB_xcursor);
4704 if ((mc = malloc(size)) != NULL) {
4705 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4706 mx = (MDB_xcursor *)(mc + 1);
4708 mdb_cursor_init(mc, txn, dbi, mx);
4709 if (txn->mt_cursors) {
4710 mc->mc_next = txn->mt_cursors[dbi];
4711 txn->mt_cursors[dbi] = mc;
4713 mc->mc_flags |= C_ALLOCD;
4723 /* Return the count of duplicate data items for the current key */
4725 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
4729 if (mc == NULL || countp == NULL)
4732 if (!(mc->mc_db->md_flags & MDB_DUPSORT))
4735 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4736 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4739 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
4742 *countp = mc->mc_xcursor->mx_db.md_entries;
4748 mdb_cursor_close(MDB_cursor *mc)
4751 /* remove from txn, if tracked */
4752 if (mc->mc_txn->mt_cursors) {
4753 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
4754 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
4756 *prev = mc->mc_next;
4758 if (mc->mc_flags & C_ALLOCD)
4764 mdb_cursor_txn(MDB_cursor *mc)
4766 if (!mc) return NULL;
4771 mdb_cursor_dbi(MDB_cursor *mc)
4777 /** Replace the key for a node with a new key.
4778 * @param[in] mp The page containing the node to operate on.
4779 * @param[in] indx The index of the node to operate on.
4780 * @param[in] key The new key to use.
4781 * @return 0 on success, non-zero on failure.
4784 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
4786 indx_t ptr, i, numkeys;
4793 node = NODEPTR(mp, indx);
4794 ptr = mp->mp_ptrs[indx];
4795 DPRINTF("update key %u (ofs %u) [%.*s] to [%s] on page %zu",
4797 (int)node->mn_ksize, (char *)NODEKEY(node),
4801 delta = key->mv_size - node->mn_ksize;
4803 if (delta > 0 && SIZELEFT(mp) < delta) {
4804 DPRINTF("OUCH! Not enough room, delta = %d", delta);
4808 numkeys = NUMKEYS(mp);
4809 for (i = 0; i < numkeys; i++) {
4810 if (mp->mp_ptrs[i] <= ptr)
4811 mp->mp_ptrs[i] -= delta;
4814 base = (char *)mp + mp->mp_upper;
4815 len = ptr - mp->mp_upper + NODESIZE;
4816 memmove(base - delta, base, len);
4817 mp->mp_upper -= delta;
4819 node = NODEPTR(mp, indx);
4820 node->mn_ksize = key->mv_size;
4823 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
4828 /** Move a node from csrc to cdst.
4831 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
4838 /* Mark src and dst as dirty. */
4839 if ((rc = mdb_page_touch(csrc)) ||
4840 (rc = mdb_page_touch(cdst)))
4843 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4844 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
4845 key.mv_size = csrc->mc_db->md_pad;
4846 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
4848 data.mv_data = NULL;
4850 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
4851 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
4852 unsigned int snum = csrc->mc_snum;
4854 /* must find the lowest key below src */
4855 mdb_page_search_root(csrc, NULL, 0);
4856 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
4857 key.mv_size = NODEKSZ(s2);
4858 key.mv_data = NODEKEY(s2);
4859 csrc->mc_snum = snum--;
4860 csrc->mc_top = snum;
4862 key.mv_size = NODEKSZ(srcnode);
4863 key.mv_data = NODEKEY(srcnode);
4865 data.mv_size = NODEDSZ(srcnode);
4866 data.mv_data = NODEDATA(srcnode);
4868 DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
4869 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
4870 csrc->mc_ki[csrc->mc_top],
4872 csrc->mc_pg[csrc->mc_top]->mp_pgno,
4873 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
4875 /* Add the node to the destination page.
4877 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, NODEPGNO(srcnode),
4879 if (rc != MDB_SUCCESS)
4882 /* Delete the node from the source page.
4884 mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
4887 /* Adjust other cursors pointing to mp */
4888 MDB_cursor *m2, *m3;
4889 MDB_dbi dbi = csrc->mc_dbi;
4890 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
4892 if (csrc->mc_flags & C_SUB)
4895 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
4896 if (m2 == csrc) continue;
4897 if (csrc->mc_flags & C_SUB)
4898 m3 = &m2->mc_xcursor->mx_cursor;
4901 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
4902 csrc->mc_ki[csrc->mc_top]) {
4903 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
4904 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
4909 /* Update the parent separators.
4911 if (csrc->mc_ki[csrc->mc_top] == 0) {
4912 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
4913 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4914 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
4916 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
4917 key.mv_size = NODEKSZ(srcnode);
4918 key.mv_data = NODEKEY(srcnode);
4920 DPRINTF("update separator for source page %zu to [%s]",
4921 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
4922 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1],
4923 &key)) != MDB_SUCCESS)
4926 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
4928 nullkey.mv_size = 0;
4929 rc = mdb_update_key(csrc->mc_pg[csrc->mc_top], 0, &nullkey);
4930 assert(rc == MDB_SUCCESS);
4934 if (cdst->mc_ki[cdst->mc_top] == 0) {
4935 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
4936 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4937 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
4939 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
4940 key.mv_size = NODEKSZ(srcnode);
4941 key.mv_data = NODEKEY(srcnode);
4943 DPRINTF("update separator for destination page %zu to [%s]",
4944 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
4945 if ((rc = mdb_update_key(cdst->mc_pg[cdst->mc_top-1], cdst->mc_ki[cdst->mc_top-1],
4946 &key)) != MDB_SUCCESS)
4949 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
4951 nullkey.mv_size = 0;
4952 rc = mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &nullkey);
4953 assert(rc == MDB_SUCCESS);
4960 /** Merge one page into another.
4961 * The nodes from the page pointed to by \b csrc will
4962 * be copied to the page pointed to by \b cdst and then
4963 * the \b csrc page will be freed.
4964 * @param[in] csrc Cursor pointing to the source page.
4965 * @param[in] cdst Cursor pointing to the destination page.
4968 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
4976 DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
4977 cdst->mc_pg[cdst->mc_top]->mp_pgno);
4979 assert(csrc->mc_snum > 1); /* can't merge root page */
4980 assert(cdst->mc_snum > 1);
4982 /* Mark dst as dirty. */
4983 if ((rc = mdb_page_touch(cdst)))
4986 /* Move all nodes from src to dst.
4988 j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
4989 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4990 key.mv_size = csrc->mc_db->md_pad;
4991 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
4992 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
4993 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
4994 if (rc != MDB_SUCCESS)
4996 key.mv_data = (char *)key.mv_data + key.mv_size;
4999 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
5000 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
5002 key.mv_size = srcnode->mn_ksize;
5003 key.mv_data = NODEKEY(srcnode);
5004 data.mv_size = NODEDSZ(srcnode);
5005 data.mv_data = NODEDATA(srcnode);
5006 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
5007 if (rc != MDB_SUCCESS)
5012 DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
5013 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);
5015 /* Unlink the src page from parent and add to free list.
5017 mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
5018 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
5020 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], 0, &key)) != MDB_SUCCESS)
5024 mdb_midl_append(&csrc->mc_txn->mt_free_pgs, csrc->mc_pg[csrc->mc_top]->mp_pgno);
5025 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
5026 csrc->mc_db->md_leaf_pages--;
5028 csrc->mc_db->md_branch_pages--;
5030 /* Adjust other cursors pointing to mp */
5031 MDB_cursor *m2, *m3;
5032 MDB_dbi dbi = csrc->mc_dbi;
5033 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
5035 if (csrc->mc_flags & C_SUB)
5038 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5039 if (m2 == csrc) continue;
5040 if (csrc->mc_flags & C_SUB)
5041 m3 = &m2->mc_xcursor->mx_cursor;
5044 if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
5045 m3->mc_pg[csrc->mc_top] = mp;
5046 m3->mc_ki[csrc->mc_top] += nkeys;
5050 mdb_cursor_pop(csrc);
5052 return mdb_rebalance(csrc);
5055 /** Copy the contents of a cursor.
5056 * @param[in] csrc The cursor to copy from.
5057 * @param[out] cdst The cursor to copy to.
5060 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
5064 cdst->mc_txn = csrc->mc_txn;
5065 cdst->mc_dbi = csrc->mc_dbi;
5066 cdst->mc_db = csrc->mc_db;
5067 cdst->mc_dbx = csrc->mc_dbx;
5068 cdst->mc_snum = csrc->mc_snum;
5069 cdst->mc_top = csrc->mc_top;
5070 cdst->mc_flags = csrc->mc_flags;
5072 for (i=0; i<csrc->mc_snum; i++) {
5073 cdst->mc_pg[i] = csrc->mc_pg[i];
5074 cdst->mc_ki[i] = csrc->mc_ki[i];
5078 /** Rebalance the tree after a delete operation.
5079 * @param[in] mc Cursor pointing to the page where rebalancing
5081 * @return 0 on success, non-zero on failure.
5084 mdb_rebalance(MDB_cursor *mc)
5091 DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
5092 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
5093 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);
5095 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD) {
5096 DPRINTF("no need to rebalance page %zu, above fill threshold",
5097 mc->mc_pg[mc->mc_top]->mp_pgno);
5101 if (mc->mc_snum < 2) {
5102 MDB_page *mp = mc->mc_pg[0];
5103 if (NUMKEYS(mp) == 0) {
5104 DPUTS("tree is completely empty");
5105 mc->mc_db->md_root = P_INVALID;
5106 mc->mc_db->md_depth = 0;
5107 mc->mc_db->md_leaf_pages = 0;
5108 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5112 /* Adjust other cursors pointing to mp */
5113 MDB_cursor *m2, *m3;
5114 MDB_dbi dbi = mc->mc_dbi;
5116 if (mc->mc_flags & C_SUB)
5119 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5120 if (m2 == mc) continue;
5121 if (mc->mc_flags & C_SUB)
5122 m3 = &m2->mc_xcursor->mx_cursor;
5125 if (m3->mc_pg[0] == mp) {
5131 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
5132 DPUTS("collapsing root page!");
5133 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5134 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
5135 if ((rc = mdb_page_get(mc->mc_txn, mc->mc_db->md_root,
5138 mc->mc_db->md_depth--;
5139 mc->mc_db->md_branch_pages--;
5141 /* Adjust other cursors pointing to mp */
5142 MDB_cursor *m2, *m3;
5143 MDB_dbi dbi = mc->mc_dbi;
5145 if (mc->mc_flags & C_SUB)
5148 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5149 if (m2 == mc) continue;
5150 if (mc->mc_flags & C_SUB)
5151 m3 = &m2->mc_xcursor->mx_cursor;
5154 if (m3->mc_pg[0] == mp) {
5155 m3->mc_pg[0] = mc->mc_pg[0];
5160 DPUTS("root page doesn't need rebalancing");
5164 /* The parent (branch page) must have at least 2 pointers,
5165 * otherwise the tree is invalid.
5167 ptop = mc->mc_top-1;
5168 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
5170 /* Leaf page fill factor is below the threshold.
5171 * Try to move keys from left or right neighbor, or
5172 * merge with a neighbor page.
5177 mdb_cursor_copy(mc, &mn);
5178 mn.mc_xcursor = NULL;
5180 if (mc->mc_ki[ptop] == 0) {
5181 /* We're the leftmost leaf in our parent.
5183 DPUTS("reading right neighbor");
5185 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5186 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5188 mn.mc_ki[mn.mc_top] = 0;
5189 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
5191 /* There is at least one neighbor to the left.
5193 DPUTS("reading left neighbor");
5195 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5196 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5198 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
5199 mc->mc_ki[mc->mc_top] = 0;
5202 DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
5203 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);
5205 /* If the neighbor page is above threshold and has at least two
5206 * keys, move one key from it.
5208 * Otherwise we should try to merge them.
5210 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) >= 2)
5211 return mdb_node_move(&mn, mc);
5212 else { /* FIXME: if (has_enough_room()) */
5213 mc->mc_flags &= ~C_INITIALIZED;
5214 if (mc->mc_ki[ptop] == 0)
5215 return mdb_page_merge(&mn, mc);
5217 return mdb_page_merge(mc, &mn);
5221 /** Complete a delete operation started by #mdb_cursor_del(). */
5223 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
5227 /* add overflow pages to free list */
5228 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5232 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
5233 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
5234 for (i=0; i<ovpages; i++) {
5235 DPRINTF("freed ov page %zu", pg);
5236 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
5240 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], mc->mc_db->md_pad);
5241 mc->mc_db->md_entries--;
5242 rc = mdb_rebalance(mc);
5243 if (rc != MDB_SUCCESS)
5244 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5250 mdb_del(MDB_txn *txn, MDB_dbi dbi,
5251 MDB_val *key, MDB_val *data)
5256 MDB_val rdata, *xdata;
5260 assert(key != NULL);
5262 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
5264 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5267 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
5271 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
5275 mdb_cursor_init(&mc, txn, dbi, &mx);
5286 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
5288 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
5292 /** Split a page and insert a new node.
5293 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
5294 * The cursor will be updated to point to the actual page and index where
5295 * the node got inserted after the split.
5296 * @param[in] newkey The key for the newly inserted node.
5297 * @param[in] newdata The data for the newly inserted node.
5298 * @param[in] newpgno The page number, if the new node is a branch node.
5299 * @return 0 on success, non-zero on failure.
5302 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
5303 unsigned int nflags)
5306 int rc = MDB_SUCCESS, ins_new = 0, new_root = 0;
5309 unsigned int i, j, split_indx, nkeys, pmax;
5311 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
5313 MDB_page *mp, *rp, *pp;
5318 mp = mc->mc_pg[mc->mc_top];
5319 newindx = mc->mc_ki[mc->mc_top];
5321 DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
5322 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
5323 DKEY(newkey), mc->mc_ki[mc->mc_top]);
5325 if (mc->mc_snum < 2) {
5326 if ((pp = mdb_page_new(mc, P_BRANCH, 1)) == NULL)
5328 /* shift current top to make room for new parent */
5329 mc->mc_pg[1] = mc->mc_pg[0];
5330 mc->mc_ki[1] = mc->mc_ki[0];
5333 mc->mc_db->md_root = pp->mp_pgno;
5334 DPRINTF("root split! new root = %zu", pp->mp_pgno);
5335 mc->mc_db->md_depth++;
5338 /* Add left (implicit) pointer. */
5339 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
5340 /* undo the pre-push */
5341 mc->mc_pg[0] = mc->mc_pg[1];
5342 mc->mc_ki[0] = mc->mc_ki[1];
5343 mc->mc_db->md_root = mp->mp_pgno;
5344 mc->mc_db->md_depth--;
5351 ptop = mc->mc_top-1;
5352 DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
5355 /* Create a right sibling. */
5356 if ((rp = mdb_page_new(mc, mp->mp_flags, 1)) == NULL)
5358 DPRINTF("new right sibling: page %zu", rp->mp_pgno);
5360 mdb_cursor_copy(mc, &mn);
5361 mn.mc_pg[mn.mc_top] = rp;
5362 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
5364 if (nflags & MDB_APPEND) {
5365 mn.mc_ki[mn.mc_top] = 0;
5372 nkeys = NUMKEYS(mp);
5373 split_indx = nkeys / 2 + 1;
5378 unsigned int lsize, rsize, ksize;
5379 /* Move half of the keys to the right sibling */
5381 x = mc->mc_ki[mc->mc_top] - split_indx;
5382 ksize = mc->mc_db->md_pad;
5383 split = LEAF2KEY(mp, split_indx, ksize);
5384 rsize = (nkeys - split_indx) * ksize;
5385 lsize = (nkeys - split_indx) * sizeof(indx_t);
5386 mp->mp_lower -= lsize;
5387 rp->mp_lower += lsize;
5388 mp->mp_upper += rsize - lsize;
5389 rp->mp_upper -= rsize - lsize;
5390 sepkey.mv_size = ksize;
5391 if (newindx == split_indx) {
5392 sepkey.mv_data = newkey->mv_data;
5394 sepkey.mv_data = split;
5397 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
5398 memcpy(rp->mp_ptrs, split, rsize);
5399 sepkey.mv_data = rp->mp_ptrs;
5400 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
5401 memcpy(ins, newkey->mv_data, ksize);
5402 mp->mp_lower += sizeof(indx_t);
5403 mp->mp_upper -= ksize - sizeof(indx_t);
5406 memcpy(rp->mp_ptrs, split, x * ksize);
5407 ins = LEAF2KEY(rp, x, ksize);
5408 memcpy(ins, newkey->mv_data, ksize);
5409 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
5410 rp->mp_lower += sizeof(indx_t);
5411 rp->mp_upper -= ksize - sizeof(indx_t);
5412 mc->mc_ki[mc->mc_top] = x;
5413 mc->mc_pg[mc->mc_top] = rp;
5418 /* For leaf pages, check the split point based on what
5419 * fits where, since otherwise add_node can fail.
5422 unsigned int psize, nsize;
5423 /* Maximum free space in an empty page */
5424 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
5425 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
5426 if (newindx < split_indx) {
5428 for (i=0; i<split_indx; i++) {
5429 node = NODEPTR(mp, i);
5430 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
5431 if (F_ISSET(node->mn_flags, F_BIGDATA))
5432 psize += sizeof(pgno_t);
5434 psize += NODEDSZ(node);
5443 for (i=nkeys-1; i>=split_indx; i--) {
5444 node = NODEPTR(mp, i);
5445 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
5446 if (F_ISSET(node->mn_flags, F_BIGDATA))
5447 psize += sizeof(pgno_t);
5449 psize += NODEDSZ(node);
5459 /* First find the separating key between the split pages.
5461 if (newindx == split_indx) {
5462 sepkey.mv_size = newkey->mv_size;
5463 sepkey.mv_data = newkey->mv_data;
5465 node = NODEPTR(mp, split_indx);
5466 sepkey.mv_size = node->mn_ksize;
5467 sepkey.mv_data = NODEKEY(node);
5471 DPRINTF("separator is [%s]", DKEY(&sepkey));
5473 /* Copy separator key to the parent.
5475 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
5478 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
5480 /* Right page might now have changed parent.
5481 * Check if left page also changed parent.
5483 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
5484 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
5485 mc->mc_pg[ptop] = mn.mc_pg[ptop];
5486 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
5490 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
5493 if (rc != MDB_SUCCESS) {
5496 if (nflags & MDB_APPEND) {
5497 mc->mc_pg[mc->mc_top] = rp;
5498 mc->mc_ki[mc->mc_top] = 0;
5499 return mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
5505 /* Move half of the keys to the right sibling. */
5507 /* grab a page to hold a temporary copy */
5508 copy = mdb_page_malloc(mc);
5512 copy->mp_pgno = mp->mp_pgno;
5513 copy->mp_flags = mp->mp_flags;
5514 copy->mp_lower = PAGEHDRSZ;
5515 copy->mp_upper = mc->mc_txn->mt_env->me_psize;
5516 mc->mc_pg[mc->mc_top] = copy;
5517 for (i = j = 0; i <= nkeys; j++) {
5518 if (i == split_indx) {
5519 /* Insert in right sibling. */
5520 /* Reset insert index for right sibling. */
5521 j = (i == newindx && ins_new);
5522 mc->mc_pg[mc->mc_top] = rp;
5525 if (i == newindx && !ins_new) {
5526 /* Insert the original entry that caused the split. */
5527 rkey.mv_data = newkey->mv_data;
5528 rkey.mv_size = newkey->mv_size;
5537 /* Update page and index for the new key. */
5538 mc->mc_ki[mc->mc_top] = j;
5539 } else if (i == nkeys) {
5542 node = NODEPTR(mp, i);
5543 rkey.mv_data = NODEKEY(node);
5544 rkey.mv_size = node->mn_ksize;
5546 xdata.mv_data = NODEDATA(node);
5547 xdata.mv_size = NODEDSZ(node);
5550 pgno = NODEPGNO(node);
5551 flags = node->mn_flags;
5556 if (!IS_LEAF(mp) && j == 0) {
5557 /* First branch index doesn't need key data. */
5561 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
5564 nkeys = NUMKEYS(copy);
5565 for (i=0; i<nkeys; i++)
5566 mp->mp_ptrs[i] = copy->mp_ptrs[i];
5567 mp->mp_lower = copy->mp_lower;
5568 mp->mp_upper = copy->mp_upper;
5569 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
5570 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
5572 /* reset back to original page */
5573 if (newindx < split_indx) {
5574 mc->mc_pg[mc->mc_top] = mp;
5575 if (nflags & MDB_RESERVE) {
5576 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5577 if (!(node->mn_flags & F_BIGDATA))
5578 newdata->mv_data = NODEDATA(node);
5582 /* return tmp page to freelist */
5583 copy->mp_next = mc->mc_txn->mt_env->me_dpages;
5584 mc->mc_txn->mt_env->me_dpages = copy;
5587 /* Adjust other cursors pointing to mp */
5588 MDB_cursor *m2, *m3;
5589 MDB_dbi dbi = mc->mc_dbi;
5591 if (mc->mc_flags & C_SUB)
5594 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5595 if (m2 == mc) continue;
5596 if (mc->mc_flags & C_SUB)
5597 m3 = &m2->mc_xcursor->mx_cursor;
5600 if (!(m3->mc_flags & C_INITIALIZED))
5604 for (i=m3->mc_top; i>0; i--) {
5605 m3->mc_ki[i+1] = m3->mc_ki[i];
5606 m3->mc_pg[i+1] = m3->mc_pg[i];
5608 m3->mc_ki[0] = mc->mc_ki[0];
5609 m3->mc_pg[0] = mc->mc_pg[0];
5613 if (m3->mc_pg[mc->mc_top] == mp) {
5614 if (m3->mc_ki[m3->mc_top] >= split_indx) {
5615 m3->mc_pg[m3->mc_top] = rp;
5616 m3->mc_ki[m3->mc_top] -= split_indx;
5625 mdb_put(MDB_txn *txn, MDB_dbi dbi,
5626 MDB_val *key, MDB_val *data, unsigned int flags)
5631 assert(key != NULL);
5632 assert(data != NULL);
5634 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5637 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
5641 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
5645 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND)) != flags)
5648 mdb_cursor_init(&mc, txn, dbi, &mx);
5649 return mdb_cursor_put(&mc, key, data, flags);
5652 /** Only a subset of the @ref mdb_env flags can be changed
5653 * at runtime. Changing other flags requires closing the environment
5654 * and re-opening it with the new flags.
5656 #define CHANGEABLE (MDB_NOSYNC)
5658 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
5660 if ((flag & CHANGEABLE) != flag)
5663 env->me_flags |= flag;
5665 env->me_flags &= ~flag;
5670 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
5675 *arg = env->me_flags;
5680 mdb_env_get_path(MDB_env *env, const char **arg)
5685 *arg = env->me_path;
5689 /** Common code for #mdb_stat() and #mdb_env_stat().
5690 * @param[in] env the environment to operate in.
5691 * @param[in] db the #MDB_db record containing the stats to return.
5692 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
5693 * @return 0, this function always succeeds.
5696 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
5698 arg->ms_psize = env->me_psize;
5699 arg->ms_depth = db->md_depth;
5700 arg->ms_branch_pages = db->md_branch_pages;
5701 arg->ms_leaf_pages = db->md_leaf_pages;
5702 arg->ms_overflow_pages = db->md_overflow_pages;
5703 arg->ms_entries = db->md_entries;
5708 mdb_env_stat(MDB_env *env, MDB_stat *arg)
5712 if (env == NULL || arg == NULL)
5715 mdb_env_read_meta(env, &toggle);
5717 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
5720 /** Set the default comparison functions for a database.
5721 * Called immediately after a database is opened to set the defaults.
5722 * The user can then override them with #mdb_set_compare() or
5723 * #mdb_set_dupsort().
5724 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
5725 * @param[in] dbi A database handle returned by #mdb_open()
5728 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
5730 if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEKEY)
5731 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memnr;
5732 else if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERKEY)
5733 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_cint;
5735 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memn;
5737 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
5738 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP) {
5739 if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED)
5740 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_int;
5742 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_cint;
5743 } else if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEDUP) {
5744 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memnr;
5746 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memn;
5749 txn->mt_dbxs[dbi].md_dcmp = NULL;
5753 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
5758 int rc, dbflag, exact;
5761 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
5762 mdb_default_cmp(txn, FREE_DBI);
5768 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
5769 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
5770 mdb_default_cmp(txn, MAIN_DBI);
5774 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
5775 mdb_default_cmp(txn, MAIN_DBI);
5778 /* Is the DB already open? */
5780 for (i=2; i<txn->mt_numdbs; i++) {
5781 if (len == txn->mt_dbxs[i].md_name.mv_size &&
5782 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
5788 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
5791 /* Find the DB info */
5795 key.mv_data = (void *)name;
5796 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
5797 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
5798 if (rc == MDB_SUCCESS) {
5799 /* make sure this is actually a DB */
5800 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
5801 if (!(node->mn_flags & F_SUBDATA))
5803 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
5804 /* Create if requested */
5806 data.mv_size = sizeof(MDB_db);
5807 data.mv_data = &dummy;
5808 memset(&dummy, 0, sizeof(dummy));
5809 dummy.md_root = P_INVALID;
5810 dummy.md_flags = flags & 0xffff;
5811 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
5815 /* OK, got info, add to table */
5816 if (rc == MDB_SUCCESS) {
5817 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
5818 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
5819 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
5820 txn->mt_dbflags[txn->mt_numdbs] = dbflag;
5821 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
5822 *dbi = txn->mt_numdbs;
5823 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
5824 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
5825 mdb_default_cmp(txn, txn->mt_numdbs);
5832 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
5834 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
5837 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
5840 void mdb_close(MDB_env *env, MDB_dbi dbi)
5843 if (dbi <= MAIN_DBI || dbi >= env->me_numdbs)
5845 ptr = env->me_dbxs[dbi].md_name.mv_data;
5846 env->me_dbxs[dbi].md_name.mv_data = NULL;
5847 env->me_dbxs[dbi].md_name.mv_size = 0;
5851 /** Add all the DB's pages to the free list.
5852 * @param[in] mc Cursor on the DB to free.
5853 * @param[in] subs non-Zero to check for sub-DBs in this DB.
5854 * @return 0 on success, non-zero on failure.
5857 mdb_drop0(MDB_cursor *mc, int subs)
5861 rc = mdb_page_search(mc, NULL, 0);
5862 if (rc == MDB_SUCCESS) {
5867 /* LEAF2 pages have no nodes, cannot have sub-DBs */
5868 if (!subs || IS_LEAF2(mc->mc_pg[mc->mc_top]))
5871 mdb_cursor_copy(mc, &mx);
5872 while (mc->mc_snum > 0) {
5873 if (IS_LEAF(mc->mc_pg[mc->mc_top])) {
5874 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
5875 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
5876 if (ni->mn_flags & F_SUBDATA) {
5877 mdb_xcursor_init1(mc, ni);
5878 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
5884 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
5886 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
5889 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
5894 rc = mdb_cursor_sibling(mc, 1);
5896 /* no more siblings, go back to beginning
5897 * of previous level. (stack was already popped
5898 * by mdb_cursor_sibling)
5900 for (i=1; i<mc->mc_top; i++)
5901 mc->mc_pg[i] = mx.mc_pg[i];
5905 mdb_midl_append(&mc->mc_txn->mt_free_pgs,
5906 mc->mc_db->md_root);
5911 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
5916 if (!txn || !dbi || dbi >= txn->mt_numdbs)
5919 rc = mdb_cursor_open(txn, dbi, &mc);
5923 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
5927 /* Can't delete the main DB */
5928 if (del && dbi > MAIN_DBI) {
5929 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
5931 mdb_close(txn->mt_env, dbi);
5933 txn->mt_dbflags[dbi] |= DB_DIRTY;
5934 txn->mt_dbs[dbi].md_depth = 0;
5935 txn->mt_dbs[dbi].md_branch_pages = 0;
5936 txn->mt_dbs[dbi].md_leaf_pages = 0;
5937 txn->mt_dbs[dbi].md_overflow_pages = 0;
5938 txn->mt_dbs[dbi].md_entries = 0;
5939 txn->mt_dbs[dbi].md_root = P_INVALID;
5942 mdb_cursor_close(mc);
5946 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
5948 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5951 txn->mt_dbxs[dbi].md_cmp = cmp;
5955 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
5957 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5960 txn->mt_dbxs[dbi].md_dcmp = cmp;
5964 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
5966 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5969 txn->mt_dbxs[dbi].md_rel = rel;
5973 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
5975 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5978 txn->mt_dbxs[dbi].md_relctx = ctx;