2 * @brief memory-mapped database library
4 * A Btree-based database management library modeled loosely on the
5 * BerkeleyDB API, but much simplified.
8 * Copyright 2011 Howard Chu, Symas Corp.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted only as authorized by the OpenLDAP
15 * A copy of this license is available in the file LICENSE in the
16 * top-level directory of the distribution or, alternatively, at
17 * <http://www.OpenLDAP.org/license.html>.
19 * This code is derived from btree.c written by Martin Hedenfalk.
21 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
23 * Permission to use, copy, modify, and distribute this software for any
24 * purpose with or without fee is hereby granted, provided that the above
25 * copyright notice and this permission notice appear in all copies.
27 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
28 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
29 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
30 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
31 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
32 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
33 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
35 #include <sys/types.h>
37 #include <sys/param.h>
43 #ifdef HAVE_SYS_FILE_H
63 #include <semaphore.h>
68 #define BYTE_ORDER __BYTE_ORDER
71 #define LITTLE_ENDIAN __LITTLE_ENDIAN
74 #define BIG_ENDIAN __BIG_ENDIAN
77 #if defined(__i386) || defined(__x86_64)
78 #define MISALIGNED_OK 1
84 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
85 # error "Unknown or unsupported endianness (BYTE_ORDER)"
86 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
87 # error "Two's complement, reasonably sized integer types, please"
90 /** @defgroup internal MDB Internals
93 /** @defgroup compat Windows Compatibility Macros
94 * A bunch of macros to minimize the amount of platform-specific ifdefs
95 * needed throughout the rest of the code. When the features this library
96 * needs are similar enough to POSIX to be hidden in a one-or-two line
97 * replacement, this macro approach is used.
101 #define pthread_t DWORD
102 #define pthread_mutex_t HANDLE
103 #define pthread_key_t DWORD
104 #define pthread_self() GetCurrentThreadId()
105 #define pthread_key_create(x,y) (*(x) = TlsAlloc())
106 #define pthread_key_delete(x) TlsFree(x)
107 #define pthread_getspecific(x) TlsGetValue(x)
108 #define pthread_setspecific(x,y) TlsSetValue(x,y)
109 #define pthread_mutex_unlock(x) ReleaseMutex(x)
110 #define pthread_mutex_lock(x) WaitForSingleObject(x, INFINITE)
111 #define LOCK_MUTEX_R(env) pthread_mutex_lock((env)->me_rmutex)
112 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock((env)->me_rmutex)
113 #define LOCK_MUTEX_W(env) pthread_mutex_lock((env)->me_wmutex)
114 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock((env)->me_wmutex)
115 #define getpid() GetCurrentProcessId()
116 #define fdatasync(fd) (!FlushFileBuffers(fd))
117 #define ErrCode() GetLastError()
118 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
119 #define close(fd) CloseHandle(fd)
120 #define munmap(ptr,len) UnmapViewOfFile(ptr)
123 #define LOCK_MUTEX_R(env) sem_wait((env)->me_rmutex)
124 #define UNLOCK_MUTEX_R(env) sem_post((env)->me_rmutex)
125 #define LOCK_MUTEX_W(env) sem_wait((env)->me_wmutex)
126 #define UNLOCK_MUTEX_W(env) sem_post((env)->me_wmutex)
127 #define fdatasync(fd) fsync(fd)
130 #define fdatasync(fd) fsync(fd)
132 /** Lock the reader mutex.
134 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
135 /** Unlock the reader mutex.
137 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
139 /** Lock the writer mutex.
140 * Only a single write transaction is allowed at a time. Other writers
141 * will block waiting for this mutex.
143 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
144 /** Unlock the writer mutex.
146 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
147 #endif /* __APPLE__ */
149 /** Get the error code for the last failed system function.
151 #define ErrCode() errno
153 /** An abstraction for a file handle.
154 * On POSIX systems file handles are small integers. On Windows
155 * they're opaque pointers.
159 /** A value for an invalid file handle.
160 * Mainly used to initialize file variables and signify that they are
163 #define INVALID_HANDLE_VALUE (-1)
165 /** Get the size of a memory page for the system.
166 * This is the basic size that the platform's memory manager uses, and is
167 * fundamental to the use of memory-mapped files.
169 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
172 #if defined(_WIN32) || defined(__APPLE__)
179 /** A flag for opening a file and requesting synchronous data writes.
180 * This is only used when writing a meta page. It's not strictly needed;
181 * we could just do a normal write and then immediately perform a flush.
182 * But if this flag is available it saves us an extra system call.
184 * @note If O_DSYNC is undefined but exists in /usr/include,
185 * preferably set some compiler flag to get the definition.
186 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
189 # define MDB_DSYNC O_DSYNC
193 /** A page number in the database.
194 * Note that 64 bit page numbers are overkill, since pages themselves
195 * already represent 12-13 bits of addressable memory, and the OS will
196 * always limit applications to a maximum of 63 bits of address space.
198 * @note In the #MDB_node structure, we only store 48 bits of this value,
199 * which thus limits us to only 60 bits of addressable data.
203 /** A transaction ID.
204 * See struct MDB_txn.mt_txnid for details.
208 /** @defgroup debug Debug Macros
212 /** Enable debug output.
213 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
214 * read from and written to the database (used for free space management).
219 #if !(__STDC_VERSION__ >= 199901L || defined(__GNUC__))
220 # define DPRINTF (void) /* Vararg macros may be unsupported */
222 /** Print a debug message with printf formatting. */
223 # define DPRINTF(fmt, ...) /**< Requires 2 or more args */ \
224 fprintf(stderr, "%s:%d " fmt "\n", __func__, __LINE__, __VA_ARGS__)
226 # define DPRINTF(fmt, ...) ((void) 0)
228 /** Print a debug string.
229 * The string is printed literally, with no format processing.
231 #define DPUTS(arg) DPRINTF("%s", arg)
234 /** A default memory page size.
235 * The actual size is platform-dependent, but we use this for
236 * boot-strapping. We probably should not be using this any more.
237 * The #GET_PAGESIZE() macro is used to get the actual size.
239 * Note that we don't currently support Huge pages. On Linux,
240 * regular data files cannot use Huge pages, and in general
241 * Huge pages aren't actually pageable. We rely on the OS
242 * demand-pager to read our data and page it out when memory
243 * pressure from other processes is high. So until OSs have
244 * actual paging support for Huge pages, they're not viable.
246 #define PAGESIZE 4096
248 /** The minimum number of keys required in a database page.
249 * Setting this to a larger value will place a smaller bound on the
250 * maximum size of a data item. Data items larger than this size will
251 * be pushed into overflow pages instead of being stored directly in
252 * the B-tree node. This value used to default to 4. With a page size
253 * of 4096 bytes that meant that any item larger than 1024 bytes would
254 * go into an overflow page. That also meant that on average 2-3KB of
255 * each overflow page was wasted space. The value cannot be lower than
256 * 2 because then there would no longer be a tree structure. With this
257 * value, items larger than 2KB will go into overflow pages, and on
258 * average only 1KB will be wasted.
260 #define MDB_MINKEYS 2
262 /** A stamp that identifies a file as an MDB file.
263 * There's nothing special about this value other than that it is easily
264 * recognizable, and it will reflect any byte order mismatches.
266 #define MDB_MAGIC 0xBEEFC0DE
268 /** The version number for a database's file format. */
269 #define MDB_VERSION 1
271 /** The maximum size of a key in the database.
272 * While data items have essentially unbounded size, we require that
273 * keys all fit onto a regular page. This limit could be raised a bit
274 * further if needed; to something just under #PAGESIZE / #MDB_MINKEYS.
276 #define MAXKEYSIZE 511
281 * This is used for printing a hex dump of a key's contents.
283 #define DKBUF char kbuf[(MAXKEYSIZE*2+1)]
284 /** Display a key in hex.
286 * Invoke a function to display a key in hex.
288 #define DKEY(x) mdb_dkey(x, kbuf)
290 #define DKBUF typedef int dummy_kbuf /* so we can put ';' after */
294 /** @defgroup lazylock Lazy Locking
295 * Macros for locks that are't actually needed.
296 * The DB view is always consistent because all writes are wrapped in
297 * the wmutex. Finer-grained locks aren't necessary.
301 /** Use lazy locking. I.e., don't lock these accesses at all. */
305 /** Grab the reader lock */
306 #define LAZY_MUTEX_LOCK(x)
307 /** Release the reader lock */
308 #define LAZY_MUTEX_UNLOCK(x)
309 /** Release the DB table reader/writer lock */
310 #define LAZY_RWLOCK_UNLOCK(x)
311 /** Grab the DB table write lock */
312 #define LAZY_RWLOCK_WRLOCK(x)
313 /** Grab the DB table read lock */
314 #define LAZY_RWLOCK_RDLOCK(x)
315 /** Declare the DB table rwlock. Should not be followed by ';'. */
316 #define LAZY_RWLOCK_DEF(x)
317 /** Initialize the DB table rwlock */
318 #define LAZY_RWLOCK_INIT(x,y)
319 /** Destroy the DB table rwlock */
320 #define LAZY_RWLOCK_DESTROY(x)
322 #define LAZY_MUTEX_LOCK(x) pthread_mutex_lock(x)
323 #define LAZY_MUTEX_UNLOCK(x) pthread_mutex_unlock(x)
324 #define LAZY_RWLOCK_UNLOCK(x) pthread_rwlock_unlock(x)
325 #define LAZY_RWLOCK_WRLOCK(x) pthread_rwlock_wrlock(x)
326 #define LAZY_RWLOCK_RDLOCK(x) pthread_rwlock_rdlock(x)
327 #define LAZY_RWLOCK_DEF(x) pthread_rwlock_t x;
328 #define LAZY_RWLOCK_INIT(x,y) pthread_rwlock_init(x,y)
329 #define LAZY_RWLOCK_DESTROY(x) pthread_rwlock_destroy(x)
333 /** An invalid page number.
334 * Mainly used to denote an empty tree.
336 #define P_INVALID (~0UL)
338 /** Test if a flag \b f is set in a flag word \b w. */
339 #define F_ISSET(w, f) (((w) & (f)) == (f))
341 /** Used for offsets within a single page.
342 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
345 typedef uint16_t indx_t;
347 /** Default size of memory map.
348 * This is certainly too small for any actual applications. Apps should always set
349 * the size explicitly using #mdb_env_set_mapsize().
351 #define DEFAULT_MAPSIZE 1048576
353 /** @defgroup readers Reader Lock Table
354 * Readers don't acquire any locks for their data access. Instead, they
355 * simply record their transaction ID in the reader table. The reader
356 * mutex is needed just to find an empty slot in the reader table. The
357 * slot's address is saved in thread-specific data so that subsequent read
358 * transactions started by the same thread need no further locking to proceed.
360 * Since the database uses multi-version concurrency control, readers don't
361 * actually need any locking. This table is used to keep track of which
362 * readers are using data from which old transactions, so that we'll know
363 * when a particular old transaction is no longer in use. Old transactions
364 * that have discarded any data pages can then have those pages reclaimed
365 * for use by a later write transaction.
367 * The lock table is constructed such that reader slots are aligned with the
368 * processor's cache line size. Any slot is only ever used by one thread.
369 * This alignment guarantees that there will be no contention or cache
370 * thrashing as threads update their own slot info, and also eliminates
371 * any need for locking when accessing a slot.
373 * A writer thread will scan every slot in the table to determine the oldest
374 * outstanding reader transaction. Any freed pages older than this will be
375 * reclaimed by the writer. The writer doesn't use any locks when scanning
376 * this table. This means that there's no guarantee that the writer will
377 * see the most up-to-date reader info, but that's not required for correct
378 * operation - all we need is to know the upper bound on the oldest reader,
379 * we don't care at all about the newest reader. So the only consequence of
380 * reading stale information here is that old pages might hang around a
381 * while longer before being reclaimed. That's actually good anyway, because
382 * the longer we delay reclaiming old pages, the more likely it is that a
383 * string of contiguous pages can be found after coalescing old pages from
384 * many old transactions together.
386 * @todo We don't actually do such coalescing yet, we grab pages from one
387 * old transaction at a time.
390 /** Number of slots in the reader table.
391 * This value was chosen somewhat arbitrarily. 126 readers plus a
392 * couple mutexes fit exactly into 8KB on my development machine.
393 * Applications should set the table size using #mdb_env_set_maxreaders().
395 #define DEFAULT_READERS 126
397 /** The size of a CPU cache line in bytes. We want our lock structures
398 * aligned to this size to avoid false cache line sharing in the
400 * This value works for most CPUs. For Itanium this should be 128.
406 /** The information we store in a single slot of the reader table.
407 * In addition to a transaction ID, we also record the process and
408 * thread ID that owns a slot, so that we can detect stale information,
409 * e.g. threads or processes that went away without cleaning up.
410 * @note We currently don't check for stale records. We simply re-init
411 * the table when we know that we're the only process opening the
414 typedef struct MDB_rxbody {
415 /** The current Transaction ID when this transaction began.
416 * Multiple readers that start at the same time will probably have the
417 * same ID here. Again, it's not important to exclude them from
418 * anything; all we need to know is which version of the DB they
419 * started from so we can avoid overwriting any data used in that
420 * particular version.
423 /** The process ID of the process owning this reader txn. */
425 /** The thread ID of the thread owning this txn. */
429 /** The actual reader record, with cacheline padding. */
430 typedef struct MDB_reader {
433 /** shorthand for mrb_txnid */
434 #define mr_txnid mru.mrx.mrb_txnid
435 #define mr_pid mru.mrx.mrb_pid
436 #define mr_tid mru.mrx.mrb_tid
437 /** cache line alignment */
438 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
442 /** The header for the reader table.
443 * The table resides in a memory-mapped file. (This is a different file
444 * than is used for the main database.)
446 * For POSIX the actual mutexes reside in the shared memory of this
447 * mapped file. On Windows, mutexes are named objects allocated by the
448 * kernel; we store the mutex names in this mapped file so that other
449 * processes can grab them. This same approach is also used on
450 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
451 * process-shared POSIX mutexes. For these cases where a named object
452 * is used, the object name is derived from a 64 bit FNV hash of the
453 * environment pathname. As such, naming collisions are extremely
454 * unlikely. If a collision occurs, the results are unpredictable.
456 typedef struct MDB_txbody {
457 /** Stamp identifying this as an MDB lock file. It must be set
460 /** Version number of this lock file. Must be set to #MDB_VERSION. */
461 uint32_t mtb_version;
462 #if defined(_WIN32) || defined(__APPLE__)
463 char mtb_rmname[MNAME_LEN];
465 /** Mutex protecting access to this table.
466 * This is the reader lock that #LOCK_MUTEX_R acquires.
468 pthread_mutex_t mtb_mutex;
470 /** The ID of the last transaction committed to the database.
471 * This is recorded here only for convenience; the value can always
472 * be determined by reading the main database meta pages.
475 /** The number of slots that have been used in the reader table.
476 * This always records the maximum count, it is not decremented
477 * when readers release their slots.
479 unsigned mtb_numreaders;
480 /** The ID of the most recent meta page in the database.
481 * This is recorded here only for convenience; the value can always
482 * be determined by reading the main database meta pages.
484 uint32_t mtb_me_toggle;
487 /** The actual reader table definition. */
488 typedef struct MDB_txninfo {
491 #define mti_magic mt1.mtb.mtb_magic
492 #define mti_version mt1.mtb.mtb_version
493 #define mti_mutex mt1.mtb.mtb_mutex
494 #define mti_rmname mt1.mtb.mtb_rmname
495 #define mti_txnid mt1.mtb.mtb_txnid
496 #define mti_numreaders mt1.mtb.mtb_numreaders
497 #define mti_me_toggle mt1.mtb.mtb_me_toggle
498 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
501 #if defined(_WIN32) || defined(__APPLE__)
502 char mt2_wmname[MNAME_LEN];
503 #define mti_wmname mt2.mt2_wmname
505 pthread_mutex_t mt2_wmutex;
506 #define mti_wmutex mt2.mt2_wmutex
508 char pad[(sizeof(pthread_mutex_t)+CACHELINE-1) & ~(CACHELINE-1)];
510 MDB_reader mti_readers[1];
514 /** Common header for all page types.
515 * Overflow records occupy a number of contiguous pages with no
516 * headers on any page after the first.
518 typedef struct MDB_page {
519 #define mp_pgno mp_p.p_pgno
520 #define mp_next mp_p.p_next
522 pgno_t p_pgno; /**< page number */
523 void * p_next; /**< for in-memory list of freed structs */
526 /** @defgroup mdb_page Page Flags
528 * Flags for the page headers.
531 #define P_BRANCH 0x01 /**< branch page */
532 #define P_LEAF 0x02 /**< leaf page */
533 #define P_OVERFLOW 0x04 /**< overflow page */
534 #define P_META 0x08 /**< meta page */
535 #define P_DIRTY 0x10 /**< dirty page */
536 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
537 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
539 uint16_t mp_flags; /**< @ref mdb_page */
540 #define mp_lower mp_pb.pb.pb_lower
541 #define mp_upper mp_pb.pb.pb_upper
542 #define mp_pages mp_pb.pb_pages
545 indx_t pb_lower; /**< lower bound of free space */
546 indx_t pb_upper; /**< upper bound of free space */
548 uint32_t pb_pages; /**< number of overflow pages */
550 indx_t mp_ptrs[1]; /**< dynamic size */
553 /** Size of the page header, excluding dynamic data at the end */
554 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
556 /** Address of first usable data byte in a page, after the header */
557 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
559 /** Number of nodes on a page */
560 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
562 /** The amount of space remaining in the page */
563 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
565 /** The percentage of space used in the page, in tenths of a percent. */
566 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
567 ((env)->me_psize - PAGEHDRSZ))
568 /** The minimum page fill factor, in tenths of a percent.
569 * Pages emptier than this are candidates for merging.
571 #define FILL_THRESHOLD 250
573 /** Test if a page is a leaf page */
574 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
575 /** Test if a page is a LEAF2 page */
576 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
577 /** Test if a page is a branch page */
578 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
579 /** Test if a page is an overflow page */
580 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
581 /** Test if a page is a sub page */
582 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
584 /** The number of overflow pages needed to store the given size. */
585 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
587 /** Header for a single key/data pair within a page.
588 * We guarantee 2-byte alignment for nodes.
590 typedef struct MDB_node {
591 /** lo and hi are used for data size on leaf nodes and for
592 * child pgno on branch nodes. On 64 bit platforms, flags
593 * is also used for pgno. (Branch nodes have no flags).
594 * They are in host byte order in case that lets some
595 * accesses be optimized into a 32-bit word access.
597 #define mn_lo mn_offset[BYTE_ORDER!=LITTLE_ENDIAN]
598 #define mn_hi mn_offset[BYTE_ORDER==LITTLE_ENDIAN] /**< part of dsize or pgno */
599 unsigned short mn_offset[2]; /**< storage for #mn_lo and #mn_hi */
600 /** @defgroup mdb_node Node Flags
602 * Flags for node headers.
605 #define F_BIGDATA 0x01 /**< data put on overflow page */
606 #define F_SUBDATA 0x02 /**< data is a sub-database */
607 #define F_DUPDATA 0x04 /**< data has duplicates */
609 /** valid flags for #mdb_node_add() */
610 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
613 unsigned short mn_flags; /**< @ref mdb_node */
614 unsigned short mn_ksize; /**< key size */
615 char mn_data[1]; /**< key and data are appended here */
618 /** Size of the node header, excluding dynamic data at the end */
619 #define NODESIZE offsetof(MDB_node, mn_data)
621 /** Bit position of top word in page number, for shifting mn_flags */
622 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
624 /** Size of a node in a branch page with a given key.
625 * This is just the node header plus the key, there is no data.
627 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
629 /** Size of a node in a leaf page with a given key and data.
630 * This is node header plus key plus data size.
632 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
634 /** Address of node \b i in page \b p */
635 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
637 /** Address of the key for the node */
638 #define NODEKEY(node) (void *)((node)->mn_data)
640 /** Address of the data for a node */
641 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
643 /** Get the page number pointed to by a branch node */
644 #define NODEPGNO(node) \
645 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
646 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
647 /** Set the page number in a branch node */
648 #define SETPGNO(node,pgno) do { \
649 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
650 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
652 /** Get the size of the data in a leaf node */
653 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
654 /** Set the size of the data for a leaf node */
655 #define SETDSZ(node,size) do { \
656 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
657 /** The size of a key in a node */
658 #define NODEKSZ(node) ((node)->mn_ksize)
660 /** The address of a key in a LEAF2 page.
661 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
662 * There are no node headers, keys are stored contiguously.
664 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
666 /** Set the \b node's key into \b key, if requested. */
667 #define MDB_SET_KEY(node, key) { if ((key) != NULL) { \
668 (key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node); } }
670 /** Information about a single database in the environment. */
671 typedef struct MDB_db {
672 uint32_t md_pad; /**< also ksize for LEAF2 pages */
673 uint16_t md_flags; /**< @ref mdb_open */
674 uint16_t md_depth; /**< depth of this tree */
675 pgno_t md_branch_pages; /**< number of internal pages */
676 pgno_t md_leaf_pages; /**< number of leaf pages */
677 pgno_t md_overflow_pages; /**< number of overflow pages */
678 size_t md_entries; /**< number of data items */
679 pgno_t md_root; /**< the root page of this tree */
682 /** Handle for the DB used to track free pages. */
684 /** Handle for the default DB. */
687 /** Meta page content. */
688 typedef struct MDB_meta {
689 /** Stamp identifying this as an MDB data file. It must be set
692 /** Version number of this lock file. Must be set to #MDB_VERSION. */
694 void *mm_address; /**< address for fixed mapping */
695 size_t mm_mapsize; /**< size of mmap region */
696 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
697 /** The size of pages used in this DB */
698 #define mm_psize mm_dbs[0].md_pad
699 /** Any persistent environment flags. @ref mdb_env */
700 #define mm_flags mm_dbs[0].md_flags
701 pgno_t mm_last_pg; /**< last used page in file */
702 txnid_t mm_txnid; /**< txnid that committed this page */
705 /** Auxiliary DB info.
706 * The information here is mostly static/read-only. There is
707 * only a single copy of this record in the environment.
709 typedef struct MDB_dbx {
710 MDB_val md_name; /**< name of the database */
711 MDB_cmp_func *md_cmp; /**< function for comparing keys */
712 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
713 MDB_rel_func *md_rel; /**< user relocate function */
714 void *md_relctx; /**< user-provided context for md_rel */
717 /** A database transaction.
718 * Every operation requires a transaction handle.
721 MDB_txn *mt_parent; /**< parent of a nested txn */
722 MDB_txn *mt_child; /**< nested txn under this txn */
723 pgno_t mt_next_pgno; /**< next unallocated page */
724 /** The ID of this transaction. IDs are integers incrementing from 1.
725 * Only committed write transactions increment the ID. If a transaction
726 * aborts, the ID may be re-used by the next writer.
729 MDB_env *mt_env; /**< the DB environment */
730 /** The list of pages that became unused during this transaction.
734 ID2L dirty_list; /**< modified pages */
735 MDB_reader *reader; /**< this thread's slot in the reader table */
737 /** Array of records for each DB known in the environment. */
739 /** Array of MDB_db records for each known DB */
741 /** @defgroup mt_dbflag Transaction DB Flags
745 #define DB_DIRTY 0x01 /**< DB was written in this txn */
746 #define DB_STALE 0x02 /**< DB record is older than txnID */
748 /** Array of cursors for each DB */
749 MDB_cursor **mt_cursors;
750 /** Array of flags for each DB */
751 unsigned char *mt_dbflags;
752 /** Number of DB records in use. This number only ever increments;
753 * we don't decrement it when individual DB handles are closed.
757 /** @defgroup mdb_txn Transaction Flags
761 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
762 #define MDB_TXN_ERROR 0x02 /**< an error has occurred */
764 unsigned int mt_flags; /**< @ref mdb_txn */
765 /** Tracks which of the two meta pages was used at the start
766 * of this transaction.
768 unsigned int mt_toggle;
771 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
772 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
773 * raise this on a 64 bit machine.
775 #define CURSOR_STACK 32
779 /** Cursors are used for all DB operations */
781 /** Next cursor on this DB in this txn */
783 /** Original cursor if this is a shadow */
785 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
786 struct MDB_xcursor *mc_xcursor;
787 /** The transaction that owns this cursor */
789 /** The database handle this cursor operates on */
791 /** The database record for this cursor */
793 /** The database auxiliary record for this cursor */
795 /** The @ref mt_dbflag for this database */
796 unsigned char *mc_dbflag;
797 unsigned short mc_snum; /**< number of pushed pages */
798 unsigned short mc_top; /**< index of top page, mc_snum-1 */
799 /** @defgroup mdb_cursor Cursor Flags
801 * Cursor state flags.
804 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
805 #define C_EOF 0x02 /**< No more data */
806 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
807 #define C_SHADOW 0x08 /**< Cursor is a dup from a parent txn */
808 #define C_ALLOCD 0x10 /**< Cursor was malloc'd */
810 unsigned int mc_flags; /**< @ref mdb_cursor */
811 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
812 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
815 /** Context for sorted-dup records.
816 * We could have gone to a fully recursive design, with arbitrarily
817 * deep nesting of sub-databases. But for now we only handle these
818 * levels - main DB, optional sub-DB, sorted-duplicate DB.
820 typedef struct MDB_xcursor {
821 /** A sub-cursor for traversing the Dup DB */
822 MDB_cursor mx_cursor;
823 /** The database record for this Dup DB */
825 /** The auxiliary DB record for this Dup DB */
827 /** The @ref mt_dbflag for this Dup DB */
828 unsigned char mx_dbflag;
831 /** A set of pages freed by an earlier transaction. */
832 typedef struct MDB_oldpages {
833 /** Usually we only read one record from the FREEDB at a time, but
834 * in case we read more, this will chain them together.
836 struct MDB_oldpages *mo_next;
837 /** The ID of the transaction in which these pages were freed. */
839 /** An #IDL of the pages */
840 pgno_t mo_pages[1]; /* dynamic */
843 /** The database environment. */
845 HANDLE me_fd; /**< The main data file */
846 HANDLE me_lfd; /**< The lock file */
847 HANDLE me_mfd; /**< just for writing the meta pages */
848 /** Failed to update the meta page. Probably an I/O error. */
849 #define MDB_FATAL_ERROR 0x80000000U
850 uint32_t me_flags; /**< @ref mdb_env */
851 uint32_t me_extrapad; /**< unused for now */
852 unsigned int me_maxreaders; /**< size of the reader table */
853 MDB_dbi me_numdbs; /**< number of DBs opened */
854 MDB_dbi me_maxdbs; /**< size of the DB table */
855 char *me_path; /**< path to the DB files */
856 char *me_map; /**< the memory map of the data file */
857 MDB_txninfo *me_txns; /**< the memory map of the lock file */
858 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
859 MDB_txn *me_txn; /**< current write transaction */
860 size_t me_mapsize; /**< size of the data memory map */
861 off_t me_size; /**< current file size */
862 pgno_t me_maxpg; /**< me_mapsize / me_psize */
863 unsigned int me_psize; /**< size of a page, from #GET_PAGESIZE */
864 unsigned int me_db_toggle; /**< which DB table is current */
865 txnid_t me_wtxnid; /**< ID of last txn we committed */
866 MDB_dbx *me_dbxs; /**< array of static DB info */
867 MDB_db *me_dbs[2]; /**< two arrays of MDB_db info */
868 MDB_oldpages *me_pghead; /**< list of old page records */
869 pthread_key_t me_txkey; /**< thread-key for readers */
870 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
871 /** IDL of pages that became unused in a write txn */
873 /** ID2L of pages that were written during a write txn */
874 ID2 me_dirty_list[MDB_IDL_UM_SIZE];
875 /** rwlock for the DB tables, if #LAZY_LOCKS is false */
876 LAZY_RWLOCK_DEF(me_dblock)
878 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
882 sem_t *me_rmutex; /* Apple doesn't support shared mutexes */
886 /** max number of pages to commit in one writev() call */
887 #define MDB_COMMIT_PAGES 64
889 static MDB_page *mdb_page_alloc(MDB_cursor *mc, int num);
890 static MDB_page *mdb_page_new(MDB_cursor *mc, uint32_t flags, int num);
891 static int mdb_page_touch(MDB_cursor *mc);
893 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
894 static int mdb_page_search_root(MDB_cursor *mc,
895 MDB_val *key, int modify);
896 static int mdb_page_search(MDB_cursor *mc,
897 MDB_val *key, int modify);
898 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
899 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
900 pgno_t newpgno, unsigned int nflags);
902 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
903 static int mdb_env_read_meta(MDB_env *env, int *which);
904 static int mdb_env_write_meta(MDB_txn *txn);
906 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
907 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
908 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
909 static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
910 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
911 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
912 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
913 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
914 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
916 static int mdb_rebalance(MDB_cursor *mc);
917 static int mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
919 static void mdb_cursor_pop(MDB_cursor *mc);
920 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
922 static int mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
923 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
924 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
925 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
926 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
928 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
929 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
931 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
932 static void mdb_xcursor_init0(MDB_cursor *mc);
933 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
935 static int mdb_drop0(MDB_cursor *mc, int subs);
936 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
939 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
943 static SECURITY_DESCRIPTOR mdb_null_sd;
944 static SECURITY_ATTRIBUTES mdb_all_sa;
945 static int mdb_sec_inited;
948 /** Return the library version info. */
950 mdb_version(int *major, int *minor, int *patch)
952 if (major) *major = MDB_VERSION_MAJOR;
953 if (minor) *minor = MDB_VERSION_MINOR;
954 if (patch) *patch = MDB_VERSION_PATCH;
955 return MDB_VERSION_STRING;
958 /** Table of descriptions for MDB @ref errors */
959 static char *const mdb_errstr[] = {
960 "MDB_KEYEXIST: Key/data pair already exists",
961 "MDB_NOTFOUND: No matching key/data pair found",
962 "MDB_PAGE_NOTFOUND: Requested page not found",
963 "MDB_CORRUPTED: Located page was wrong type",
964 "MDB_PANIC: Update of meta page failed",
965 "MDB_VERSION_MISMATCH: Database environment version mismatch"
969 mdb_strerror(int err)
972 return ("Successful return: 0");
974 if (err >= MDB_KEYEXIST && err <= MDB_VERSION_MISMATCH)
975 return mdb_errstr[err - MDB_KEYEXIST];
977 return strerror(err);
981 /** Display a key in hexadecimal and return the address of the result.
982 * @param[in] key the key to display
983 * @param[in] buf the buffer to write into. Should always be #DKBUF.
984 * @return The key in hexadecimal form.
987 mdb_dkey(MDB_val *key, char *buf)
990 unsigned char *c = key->mv_data;
992 if (key->mv_size > MAXKEYSIZE)
994 /* may want to make this a dynamic check: if the key is mostly
995 * printable characters, print it as-is instead of converting to hex.
998 for (i=0; i<key->mv_size; i++)
999 ptr += sprintf(ptr, "%02x", *c++);
1001 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1008 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1010 return txn->mt_dbxs[dbi].md_cmp(a, b);
1014 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1016 if (txn->mt_dbxs[dbi].md_dcmp)
1017 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1019 return EINVAL; /* too bad you can't distinguish this from a valid result */
1022 /** Allocate a single page.
1023 * Re-use old malloc'd pages first, otherwise just malloc.
1026 mdb_page_malloc(MDB_cursor *mc) {
1028 if (mc->mc_txn->mt_env->me_dpages) {
1029 ret = mc->mc_txn->mt_env->me_dpages;
1030 mc->mc_txn->mt_env->me_dpages = ret->mp_next;
1032 ret = malloc(mc->mc_txn->mt_env->me_psize);
1037 /** Allocate pages for writing.
1038 * If there are free pages available from older transactions, they
1039 * will be re-used first. Otherwise a new page will be allocated.
1040 * @param[in] mc cursor A cursor handle identifying the transaction and
1041 * database for which we are allocating.
1042 * @param[in] num the number of pages to allocate.
1043 * @return Address of the allocated page(s). Requests for multiple pages
1044 * will always be satisfied by a single contiguous chunk of memory.
1047 mdb_page_alloc(MDB_cursor *mc, int num)
1049 MDB_txn *txn = mc->mc_txn;
1051 pgno_t pgno = P_INVALID;
1054 if (txn->mt_txnid > 2) {
1056 if (!txn->mt_env->me_pghead && mc->mc_dbi != FREE_DBI &&
1057 txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
1058 /* See if there's anything in the free DB */
1061 txnid_t *kptr, oldest;
1063 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1064 mdb_page_search(&m2, NULL, 0);
1065 leaf = NODEPTR(m2.mc_pg[m2.mc_top], 0);
1066 kptr = (txnid_t *)NODEKEY(leaf);
1070 oldest = txn->mt_txnid - 1;
1071 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
1072 txnid_t mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
1073 if (mr && mr < oldest)
1078 if (oldest > *kptr) {
1079 /* It's usable, grab it.
1085 mdb_node_read(txn, leaf, &data);
1086 idl = (ID *) data.mv_data;
1087 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
1088 mop->mo_next = txn->mt_env->me_pghead;
1089 mop->mo_txnid = *kptr;
1090 txn->mt_env->me_pghead = mop;
1091 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
1096 DPRINTF("IDL read txn %zu root %zu num %zu",
1097 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1098 for (i=0; i<idl[0]; i++) {
1099 DPRINTF("IDL %zu", idl[i+1]);
1103 /* drop this IDL from the DB */
1104 m2.mc_ki[m2.mc_top] = 0;
1105 m2.mc_flags = C_INITIALIZED;
1106 mdb_cursor_del(&m2, 0);
1109 if (txn->mt_env->me_pghead) {
1110 MDB_oldpages *mop = txn->mt_env->me_pghead;
1112 /* FIXME: For now, always use fresh pages. We
1113 * really ought to search the free list for a
1118 /* peel pages off tail, so we only have to truncate the list */
1119 pgno = MDB_IDL_LAST(mop->mo_pages);
1120 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
1122 if (mop->mo_pages[2] > mop->mo_pages[1])
1123 mop->mo_pages[0] = 0;
1127 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
1128 txn->mt_env->me_pghead = mop->mo_next;
1135 if (pgno == P_INVALID) {
1136 /* DB size is maxed out */
1137 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg) {
1138 DPUTS("DB size maxed out");
1142 if (txn->mt_env->me_dpages && num == 1) {
1143 np = txn->mt_env->me_dpages;
1144 txn->mt_env->me_dpages = np->mp_next;
1146 if ((np = malloc(txn->mt_env->me_psize * num )) == NULL)
1149 if (pgno == P_INVALID) {
1150 np->mp_pgno = txn->mt_next_pgno;
1151 txn->mt_next_pgno += num;
1155 mid.mid = np->mp_pgno;
1157 mdb_mid2l_insert(txn->mt_u.dirty_list, &mid);
1162 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1163 * @param[in] mc cursor pointing to the page to be touched
1164 * @return 0 on success, non-zero on failure.
1167 mdb_page_touch(MDB_cursor *mc)
1169 MDB_page *mp = mc->mc_pg[mc->mc_top];
1172 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1174 if ((np = mdb_page_alloc(mc, 1)) == NULL)
1176 DPRINTF("touched db %u page %zu -> %zu", mc->mc_dbi, mp->mp_pgno, np->mp_pgno);
1177 assert(mp->mp_pgno != np->mp_pgno);
1178 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
1180 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1183 mp->mp_flags |= P_DIRTY;
1186 /* Adjust other cursors pointing to mp */
1187 if (mc->mc_flags & C_SUB) {
1188 MDB_cursor *m2, *m3;
1189 MDB_dbi dbi = mc->mc_dbi-1;
1191 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
1192 if (m2 == mc) continue;
1193 m3 = &m2->mc_xcursor->mx_cursor;
1194 if (m3->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1195 m3->mc_pg[mc->mc_top] = mp;
1201 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
1202 if (m2 == mc) continue;
1203 if (m2->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1204 m2->mc_pg[mc->mc_top] = mp;
1208 mc->mc_pg[mc->mc_top] = mp;
1209 /** If this page has a parent, update the parent to point to
1213 SETPGNO(NODEPTR(mc->mc_pg[mc->mc_top-1], mc->mc_ki[mc->mc_top-1]), mp->mp_pgno);
1215 mc->mc_db->md_root = mp->mp_pgno;
1216 } else if (mc->mc_txn->mt_parent) {
1219 /* If txn has a parent, make sure the page is in our
1222 if (mc->mc_txn->mt_u.dirty_list[0].mid) {
1223 unsigned x = mdb_mid2l_search(mc->mc_txn->mt_u.dirty_list, mp->mp_pgno);
1224 if (x <= mc->mc_txn->mt_u.dirty_list[0].mid &&
1225 mc->mc_txn->mt_u.dirty_list[x].mid == mp->mp_pgno) {
1226 if (mc->mc_txn->mt_u.dirty_list[x].mptr != mp) {
1227 mp = mc->mc_txn->mt_u.dirty_list[x].mptr;
1228 mc->mc_pg[mc->mc_top] = mp;
1234 np = mdb_page_malloc(mc);
1235 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1236 mid.mid = np->mp_pgno;
1238 mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &mid);
1246 mdb_env_sync(MDB_env *env, int force)
1249 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1250 if (fdatasync(env->me_fd))
1256 /** Make shadow copies of all of parent txn's cursors */
1258 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
1260 MDB_cursor *mc, *m2;
1261 unsigned int i, j, size;
1263 for (i=0;i<src->mt_numdbs; i++) {
1264 if (src->mt_cursors[i]) {
1265 size = sizeof(MDB_cursor);
1266 if (src->mt_cursors[i]->mc_xcursor)
1267 size += sizeof(MDB_xcursor);
1268 for (m2 = src->mt_cursors[i]; m2; m2=m2->mc_next) {
1275 mc->mc_db = &dst->mt_dbs[i];
1276 mc->mc_dbx = m2->mc_dbx;
1277 mc->mc_dbflag = &dst->mt_dbflags[i];
1278 mc->mc_snum = m2->mc_snum;
1279 mc->mc_top = m2->mc_top;
1280 mc->mc_flags = m2->mc_flags | C_SHADOW;
1281 for (j=0; j<mc->mc_snum; j++) {
1282 mc->mc_pg[j] = m2->mc_pg[j];
1283 mc->mc_ki[j] = m2->mc_ki[j];
1285 if (m2->mc_xcursor) {
1286 MDB_xcursor *mx, *mx2;
1287 mx = (MDB_xcursor *)(mc+1);
1288 mc->mc_xcursor = mx;
1289 mx2 = m2->mc_xcursor;
1290 mx->mx_db = mx2->mx_db;
1291 mx->mx_dbx = mx2->mx_dbx;
1292 mx->mx_dbflag = mx2->mx_dbflag;
1293 mx->mx_cursor.mc_txn = dst;
1294 mx->mx_cursor.mc_dbi = mx2->mx_cursor.mc_dbi;
1295 mx->mx_cursor.mc_db = &mx->mx_db;
1296 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
1297 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
1298 mx->mx_cursor.mc_snum = mx2->mx_cursor.mc_snum;
1299 mx->mx_cursor.mc_top = mx2->mx_cursor.mc_top;
1300 mx->mx_cursor.mc_flags = mx2->mx_cursor.mc_flags | C_SHADOW;
1301 for (j=0; j<mx2->mx_cursor.mc_snum; j++) {
1302 mx->mx_cursor.mc_pg[j] = mx2->mx_cursor.mc_pg[j];
1303 mx->mx_cursor.mc_ki[j] = mx2->mx_cursor.mc_ki[j];
1306 mc->mc_xcursor = NULL;
1308 mc->mc_next = dst->mt_cursors[i];
1309 dst->mt_cursors[i] = mc;
1316 /** Merge shadow cursors back into parent's */
1318 mdb_cursor_merge(MDB_txn *txn)
1321 for (i=0; i<txn->mt_numdbs; i++) {
1322 if (txn->mt_cursors[i]) {
1324 while ((mc = txn->mt_cursors[i])) {
1325 txn->mt_cursors[i] = mc->mc_next;
1326 if (mc->mc_flags & C_SHADOW) {
1327 MDB_cursor *m2 = mc->mc_orig;
1329 m2->mc_snum = mc->mc_snum;
1330 m2->mc_top = mc->mc_top;
1331 for (j=0; j<mc->mc_snum; j++) {
1332 m2->mc_pg[j] = mc->mc_pg[j];
1333 m2->mc_ki[j] = mc->mc_ki[j];
1336 if (mc->mc_flags & C_ALLOCD)
1344 mdb_txn_reset0(MDB_txn *txn);
1346 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
1347 * @param[in] txn the transaction handle to initialize
1348 * @return 0 on success, non-zero on failure. This can only
1349 * fail for read-only transactions, and then only if the
1350 * reader table is full.
1353 mdb_txn_renew0(MDB_txn *txn)
1355 MDB_env *env = txn->mt_env;
1358 if (txn->mt_flags & MDB_TXN_RDONLY) {
1359 MDB_reader *r = pthread_getspecific(env->me_txkey);
1362 pid_t pid = getpid();
1363 pthread_t tid = pthread_self();
1366 for (i=0; i<env->me_txns->mti_numreaders; i++)
1367 if (env->me_txns->mti_readers[i].mr_pid == 0)
1369 if (i == env->me_maxreaders) {
1370 UNLOCK_MUTEX_R(env);
1373 env->me_txns->mti_readers[i].mr_pid = pid;
1374 env->me_txns->mti_readers[i].mr_tid = tid;
1375 if (i >= env->me_txns->mti_numreaders)
1376 env->me_txns->mti_numreaders = i+1;
1377 UNLOCK_MUTEX_R(env);
1378 r = &env->me_txns->mti_readers[i];
1379 pthread_setspecific(env->me_txkey, r);
1381 txn->mt_toggle = env->me_txns->mti_me_toggle;
1382 txn->mt_txnid = env->me_txns->mti_txnid;
1383 /* This happens if a different process was the
1384 * last writer to the DB.
1386 if (env->me_wtxnid < txn->mt_txnid)
1387 mt_dbflag = DB_STALE;
1388 r->mr_txnid = txn->mt_txnid;
1389 txn->mt_u.reader = r;
1393 txn->mt_txnid = env->me_txns->mti_txnid;
1394 if (env->me_wtxnid < txn->mt_txnid)
1395 mt_dbflag = DB_STALE;
1397 txn->mt_toggle = env->me_txns->mti_me_toggle;
1398 txn->mt_u.dirty_list = env->me_dirty_list;
1399 txn->mt_u.dirty_list[0].mid = 0;
1400 txn->mt_free_pgs = env->me_free_pgs;
1401 txn->mt_free_pgs[0] = 0;
1402 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1406 /* Copy the DB arrays */
1407 LAZY_RWLOCK_RDLOCK(&env->me_dblock);
1408 txn->mt_numdbs = env->me_numdbs;
1409 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
1410 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
1411 if (txn->mt_numdbs > 2)
1412 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
1413 (txn->mt_numdbs - 2) * sizeof(MDB_db));
1414 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1416 memset(txn->mt_dbflags, mt_dbflag, env->me_numdbs);
1422 mdb_txn_renew(MDB_txn *txn)
1429 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
1430 DPUTS("environment had fatal error, must shutdown!");
1434 rc = mdb_txn_renew0(txn);
1435 if (rc == MDB_SUCCESS) {
1436 DPRINTF("renew txn %zu%c %p on mdbenv %p, root page %zu",
1437 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1438 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1444 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
1449 if (env->me_flags & MDB_FATAL_ERROR) {
1450 DPUTS("environment had fatal error, must shutdown!");
1454 /* parent already has an active child txn */
1455 if (parent->mt_child) {
1459 size = sizeof(MDB_txn) + env->me_maxdbs * (sizeof(MDB_db)+1);
1460 if (!(flags & MDB_RDONLY))
1461 size += env->me_maxdbs * sizeof(MDB_cursor *);
1463 if ((txn = calloc(1, size)) == NULL) {
1464 DPRINTF("calloc: %s", strerror(ErrCode()));
1467 txn->mt_dbs = (MDB_db *)(txn+1);
1468 if (flags & MDB_RDONLY) {
1469 txn->mt_flags |= MDB_TXN_RDONLY;
1470 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
1472 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
1473 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
1478 txn->mt_free_pgs = mdb_midl_alloc();
1479 if (!txn->mt_free_pgs) {
1483 txn->mt_u.dirty_list = malloc(sizeof(ID2)*MDB_IDL_UM_SIZE);
1484 if (!txn->mt_u.dirty_list) {
1485 free(txn->mt_free_pgs);
1489 txn->mt_txnid = parent->mt_txnid;
1490 txn->mt_toggle = parent->mt_toggle;
1491 txn->mt_u.dirty_list[0].mid = 0;
1492 txn->mt_free_pgs[0] = 0;
1493 txn->mt_next_pgno = parent->mt_next_pgno;
1494 parent->mt_child = txn;
1495 txn->mt_parent = parent;
1496 txn->mt_numdbs = parent->mt_numdbs;
1497 txn->mt_dbxs = parent->mt_dbxs;
1498 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
1499 memcpy(txn->mt_dbflags, parent->mt_dbflags, txn->mt_numdbs);
1500 mdb_cursor_shadow(parent, txn);
1503 rc = mdb_txn_renew0(txn);
1509 DPRINTF("begin txn %zu%c %p on mdbenv %p, root page %zu",
1510 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1511 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
1517 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
1518 * @param[in] txn the transaction handle to reset
1521 mdb_txn_reset0(MDB_txn *txn)
1523 MDB_env *env = txn->mt_env;
1525 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1526 txn->mt_u.reader->mr_txnid = 0;
1532 /* close(free) all cursors */
1533 for (i=0; i<txn->mt_numdbs; i++) {
1534 if (txn->mt_cursors[i]) {
1536 while ((mc = txn->mt_cursors[i])) {
1537 txn->mt_cursors[i] = mc->mc_next;
1538 if (mc->mc_flags & C_ALLOCD)
1544 /* return all dirty pages to dpage list */
1545 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1546 dp = txn->mt_u.dirty_list[i].mptr;
1547 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1548 dp->mp_next = txn->mt_env->me_dpages;
1549 txn->mt_env->me_dpages = dp;
1551 /* large pages just get freed directly */
1556 if (txn->mt_parent) {
1557 txn->mt_parent->mt_child = NULL;
1558 free(txn->mt_free_pgs);
1559 free(txn->mt_u.dirty_list);
1562 if (mdb_midl_shrink(&txn->mt_free_pgs))
1563 env->me_free_pgs = txn->mt_free_pgs;
1566 while ((mop = txn->mt_env->me_pghead)) {
1567 txn->mt_env->me_pghead = mop->mo_next;
1572 /* The writer mutex was locked in mdb_txn_begin. */
1573 UNLOCK_MUTEX_W(env);
1578 mdb_txn_reset(MDB_txn *txn)
1583 DPRINTF("reset txn %zu%c %p on mdbenv %p, root page %zu",
1584 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1585 (void *) txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1587 mdb_txn_reset0(txn);
1591 mdb_txn_abort(MDB_txn *txn)
1596 DPRINTF("abort txn %zu%c %p on mdbenv %p, root page %zu",
1597 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1598 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1601 mdb_txn_abort(txn->mt_child);
1603 mdb_txn_reset0(txn);
1608 mdb_txn_commit(MDB_txn *txn)
1619 assert(txn != NULL);
1620 assert(txn->mt_env != NULL);
1622 if (txn->mt_child) {
1623 mdb_txn_commit(txn->mt_child);
1624 txn->mt_child = NULL;
1629 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1630 if (txn->mt_numdbs > env->me_numdbs) {
1631 /* update the DB tables */
1632 int toggle = !env->me_db_toggle;
1636 ip = &env->me_dbs[toggle][env->me_numdbs];
1637 jp = &txn->mt_dbs[env->me_numdbs];
1638 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1639 for (i = env->me_numdbs; i < txn->mt_numdbs; i++) {
1643 env->me_db_toggle = toggle;
1644 env->me_numdbs = txn->mt_numdbs;
1645 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1651 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1652 DPUTS("error flag is set, can't commit");
1654 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
1659 /* Merge (and close) our cursors with parent's */
1660 mdb_cursor_merge(txn);
1662 if (txn->mt_parent) {
1668 /* Update parent's DB table */
1669 ip = &txn->mt_parent->mt_dbs[2];
1670 jp = &txn->mt_dbs[2];
1671 for (i = 2; i < txn->mt_numdbs; i++) {
1672 if (ip->md_root != jp->md_root)
1676 txn->mt_parent->mt_numdbs = txn->mt_numdbs;
1678 /* Append our free list to parent's */
1679 mdb_midl_append_list(&txn->mt_parent->mt_free_pgs,
1681 mdb_midl_free(txn->mt_free_pgs);
1683 /* Merge our dirty list with parent's */
1684 dst = txn->mt_parent->mt_u.dirty_list;
1685 src = txn->mt_u.dirty_list;
1686 x = mdb_mid2l_search(dst, src[1].mid);
1687 for (y=1; y<=src[0].mid; y++) {
1688 while (x <= dst[0].mid && dst[x].mid != src[y].mid) x++;
1692 dst[x].mptr = src[y].mptr;
1695 for (; y<=src[0].mid; y++) {
1696 if (++x >= MDB_IDL_UM_MAX)
1701 free(txn->mt_u.dirty_list);
1702 txn->mt_parent->mt_child = NULL;
1707 if (txn != env->me_txn) {
1708 DPUTS("attempt to commit unknown transaction");
1713 if (!txn->mt_u.dirty_list[0].mid)
1716 DPRINTF("committing txn %zu %p on mdbenv %p, root page %zu",
1717 txn->mt_txnid, (void *)txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
1719 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1721 /* should only be one record now */
1722 if (env->me_pghead) {
1723 /* make sure first page of freeDB is touched and on freelist */
1724 mdb_page_search(&mc, NULL, 1);
1726 /* save to free list */
1727 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
1731 /* make sure last page of freeDB is touched and on freelist */
1732 key.mv_size = MAXKEYSIZE+1;
1734 mdb_page_search(&mc, &key, 1);
1736 mdb_midl_sort(txn->mt_free_pgs);
1740 ID *idl = txn->mt_free_pgs;
1741 DPRINTF("IDL write txn %zu root %zu num %zu",
1742 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1743 for (i=0; i<idl[0]; i++) {
1744 DPRINTF("IDL %zu", idl[i+1]);
1748 /* write to last page of freeDB */
1749 key.mv_size = sizeof(pgno_t);
1750 key.mv_data = &txn->mt_txnid;
1751 data.mv_data = txn->mt_free_pgs;
1752 /* The free list can still grow during this call,
1753 * despite the pre-emptive touches above. So check
1754 * and make sure the entire thing got written.
1757 i = txn->mt_free_pgs[0];
1758 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
1759 rc = mdb_cursor_put(&mc, &key, &data, 0);
1764 } while (i != txn->mt_free_pgs[0]);
1765 if (mdb_midl_shrink(&txn->mt_free_pgs))
1766 env->me_free_pgs = txn->mt_free_pgs;
1768 /* should only be one record now */
1769 if (env->me_pghead) {
1773 mop = env->me_pghead;
1774 env->me_pghead = NULL;
1775 key.mv_size = sizeof(pgno_t);
1776 key.mv_data = &mop->mo_txnid;
1777 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
1778 data.mv_data = mop->mo_pages;
1779 mdb_cursor_put(&mc, &key, &data, 0);
1783 /* Update DB root pointers. Their pages have already been
1784 * touched so this is all in-place and cannot fail.
1789 data.mv_size = sizeof(MDB_db);
1791 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
1792 for (i = 2; i < txn->mt_numdbs; i++) {
1793 if (txn->mt_dbflags[i] & DB_DIRTY) {
1794 data.mv_data = &txn->mt_dbs[i];
1795 mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
1800 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
1806 /* Windows actually supports scatter/gather I/O, but only on
1807 * unbuffered file handles. Since we're relying on the OS page
1808 * cache for all our data, that's self-defeating. So we just
1809 * write pages one at a time. We use the ov structure to set
1810 * the write offset, to at least save the overhead of a Seek
1814 memset(&ov, 0, sizeof(ov));
1815 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1817 dp = txn->mt_u.dirty_list[i].mptr;
1818 DPRINTF("committing page %zu", dp->mp_pgno);
1819 size = dp->mp_pgno * env->me_psize;
1820 ov.Offset = size & 0xffffffff;
1821 ov.OffsetHigh = size >> 16;
1822 ov.OffsetHigh >>= 16;
1823 /* clear dirty flag */
1824 dp->mp_flags &= ~P_DIRTY;
1825 wsize = env->me_psize;
1826 if (IS_OVERFLOW(dp)) wsize *= dp->mp_pages;
1827 rc = WriteFile(env->me_fd, dp, wsize, NULL, &ov);
1830 DPRINTF("WriteFile: %d", n);
1837 struct iovec iov[MDB_COMMIT_PAGES];
1841 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1842 dp = txn->mt_u.dirty_list[i].mptr;
1843 if (dp->mp_pgno != next) {
1845 DPRINTF("committing %u dirty pages", n);
1846 rc = writev(env->me_fd, iov, n);
1850 DPUTS("short write, filesystem full?");
1852 DPRINTF("writev: %s", strerror(n));
1859 lseek(env->me_fd, dp->mp_pgno * env->me_psize, SEEK_SET);
1862 DPRINTF("committing page %zu", dp->mp_pgno);
1863 iov[n].iov_len = env->me_psize;
1864 if (IS_OVERFLOW(dp)) iov[n].iov_len *= dp->mp_pages;
1865 iov[n].iov_base = dp;
1866 size += iov[n].iov_len;
1867 next = dp->mp_pgno + (IS_OVERFLOW(dp) ? dp->mp_pages : 1);
1868 /* clear dirty flag */
1869 dp->mp_flags &= ~P_DIRTY;
1870 if (++n >= MDB_COMMIT_PAGES) {
1880 DPRINTF("committing %u dirty pages", n);
1881 rc = writev(env->me_fd, iov, n);
1885 DPUTS("short write, filesystem full?");
1887 DPRINTF("writev: %s", strerror(n));
1894 /* Drop the dirty pages.
1896 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1897 dp = txn->mt_u.dirty_list[i].mptr;
1898 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1899 dp->mp_next = txn->mt_env->me_dpages;
1900 txn->mt_env->me_dpages = dp;
1904 txn->mt_u.dirty_list[i].mid = 0;
1906 txn->mt_u.dirty_list[0].mid = 0;
1908 if ((n = mdb_env_sync(env, 0)) != 0 ||
1909 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
1913 env->me_wtxnid = txn->mt_txnid;
1917 /* update the DB tables */
1919 int toggle = !env->me_db_toggle;
1923 ip = &env->me_dbs[toggle][2];
1924 jp = &txn->mt_dbs[2];
1925 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1926 for (i = 2; i < txn->mt_numdbs; i++) {
1927 if (ip->md_root != jp->md_root)
1932 env->me_db_toggle = toggle;
1933 env->me_numdbs = txn->mt_numdbs;
1934 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1937 UNLOCK_MUTEX_W(env);
1943 /** Read the environment parameters of a DB environment before
1944 * mapping it into memory.
1945 * @param[in] env the environment handle
1946 * @param[out] meta address of where to store the meta information
1947 * @return 0 on success, non-zero on failure.
1950 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
1952 char page[PAGESIZE];
1957 /* We don't know the page size yet, so use a minimum value.
1961 if (!ReadFile(env->me_fd, page, PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
1963 if ((rc = read(env->me_fd, page, PAGESIZE)) == 0)
1968 else if (rc != PAGESIZE) {
1972 DPRINTF("read: %s", strerror(err));
1976 p = (MDB_page *)page;
1978 if (!F_ISSET(p->mp_flags, P_META)) {
1979 DPRINTF("page %zu not a meta page", p->mp_pgno);
1984 if (m->mm_magic != MDB_MAGIC) {
1985 DPUTS("meta has invalid magic");
1989 if (m->mm_version != MDB_VERSION) {
1990 DPRINTF("database is version %u, expected version %u",
1991 m->mm_version, MDB_VERSION);
1992 return MDB_VERSION_MISMATCH;
1995 memcpy(meta, m, sizeof(*m));
1999 /** Write the environment parameters of a freshly created DB environment.
2000 * @param[in] env the environment handle
2001 * @param[out] meta address of where to store the meta information
2002 * @return 0 on success, non-zero on failure.
2005 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
2012 DPUTS("writing new meta page");
2014 GET_PAGESIZE(psize);
2016 meta->mm_magic = MDB_MAGIC;
2017 meta->mm_version = MDB_VERSION;
2018 meta->mm_psize = psize;
2019 meta->mm_last_pg = 1;
2020 meta->mm_flags = env->me_flags & 0xffff;
2021 meta->mm_flags |= MDB_INTEGERKEY;
2022 meta->mm_dbs[0].md_root = P_INVALID;
2023 meta->mm_dbs[1].md_root = P_INVALID;
2025 p = calloc(2, psize);
2027 p->mp_flags = P_META;
2030 memcpy(m, meta, sizeof(*meta));
2032 q = (MDB_page *)((char *)p + psize);
2035 q->mp_flags = P_META;
2038 memcpy(m, meta, sizeof(*meta));
2043 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
2044 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
2047 rc = write(env->me_fd, p, psize * 2);
2048 rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
2054 /** Update the environment info to commit a transaction.
2055 * @param[in] txn the transaction that's being committed
2056 * @return 0 on success, non-zero on failure.
2059 mdb_env_write_meta(MDB_txn *txn)
2062 MDB_meta meta, metab;
2064 int rc, len, toggle;
2070 assert(txn != NULL);
2071 assert(txn->mt_env != NULL);
2073 toggle = !txn->mt_toggle;
2074 DPRINTF("writing meta page %d for root page %zu",
2075 toggle, txn->mt_dbs[MAIN_DBI].md_root);
2079 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
2080 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
2082 ptr = (char *)&meta;
2083 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
2084 len = sizeof(MDB_meta) - off;
2087 meta.mm_dbs[0] = txn->mt_dbs[0];
2088 meta.mm_dbs[1] = txn->mt_dbs[1];
2089 meta.mm_last_pg = txn->mt_next_pgno - 1;
2090 meta.mm_txnid = txn->mt_txnid;
2093 off += env->me_psize;
2096 /* Write to the SYNC fd */
2099 memset(&ov, 0, sizeof(ov));
2101 WriteFile(env->me_mfd, ptr, len, (DWORD *)&rc, &ov);
2104 rc = pwrite(env->me_mfd, ptr, len, off);
2109 DPUTS("write failed, disk error?");
2110 /* On a failure, the pagecache still contains the new data.
2111 * Write some old data back, to prevent it from being used.
2112 * Use the non-SYNC fd; we know it will fail anyway.
2114 meta.mm_last_pg = metab.mm_last_pg;
2115 meta.mm_txnid = metab.mm_txnid;
2117 WriteFile(env->me_fd, ptr, len, NULL, &ov);
2119 r2 = pwrite(env->me_fd, ptr, len, off);
2121 env->me_flags |= MDB_FATAL_ERROR;
2124 /* Memory ordering issues are irrelevant; since the entire writer
2125 * is wrapped by wmutex, all of these changes will become visible
2126 * after the wmutex is unlocked. Since the DB is multi-version,
2127 * readers will get consistent data regardless of how fresh or
2128 * how stale their view of these values is.
2130 LAZY_MUTEX_LOCK(&env->me_txns->mti_mutex);
2131 txn->mt_env->me_txns->mti_me_toggle = toggle;
2132 txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
2133 LAZY_MUTEX_UNLOCK(&env->me_txns->mti_mutex);
2138 /** Check both meta pages to see which one is newer.
2139 * @param[in] env the environment handle
2140 * @param[out] which address of where to store the meta toggle ID
2141 * @return 0 on success, non-zero on failure.
2144 mdb_env_read_meta(MDB_env *env, int *which)
2148 assert(env != NULL);
2150 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
2153 DPRINTF("Using meta page %d", toggle);
2160 mdb_env_create(MDB_env **env)
2164 e = calloc(1, sizeof(MDB_env));
2168 e->me_free_pgs = mdb_midl_alloc();
2169 if (!e->me_free_pgs) {
2173 e->me_maxreaders = DEFAULT_READERS;
2175 e->me_fd = INVALID_HANDLE_VALUE;
2176 e->me_lfd = INVALID_HANDLE_VALUE;
2177 e->me_mfd = INVALID_HANDLE_VALUE;
2183 mdb_env_set_mapsize(MDB_env *env, size_t size)
2187 env->me_mapsize = size;
2189 env->me_maxpg = env->me_mapsize / env->me_psize;
2194 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
2198 env->me_maxdbs = dbs;
2203 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
2205 if (env->me_map || readers < 1)
2207 env->me_maxreaders = readers;
2212 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
2214 if (!env || !readers)
2216 *readers = env->me_maxreaders;
2220 /** Further setup required for opening an MDB environment
2223 mdb_env_open2(MDB_env *env, unsigned int flags)
2225 int i, newenv = 0, toggle;
2229 env->me_flags = flags;
2231 memset(&meta, 0, sizeof(meta));
2233 if ((i = mdb_env_read_header(env, &meta)) != 0) {
2236 DPUTS("new mdbenv");
2240 if (!env->me_mapsize) {
2241 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
2247 LONG sizelo, sizehi;
2248 sizelo = env->me_mapsize & 0xffffffff;
2249 sizehi = env->me_mapsize >> 16; /* pointless on WIN32, only needed on W64 */
2251 /* Windows won't create mappings for zero length files.
2252 * Just allocate the maxsize right now.
2255 SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
2256 if (!SetEndOfFile(env->me_fd))
2258 SetFilePointer(env->me_fd, 0, NULL, 0);
2260 mh = CreateFileMapping(env->me_fd, NULL, PAGE_READONLY,
2261 sizehi, sizelo, NULL);
2264 env->me_map = MapViewOfFileEx(mh, FILE_MAP_READ, 0, 0, env->me_mapsize,
2272 if (meta.mm_address && (flags & MDB_FIXEDMAP))
2274 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
2276 if (env->me_map == MAP_FAILED)
2281 meta.mm_mapsize = env->me_mapsize;
2282 if (flags & MDB_FIXEDMAP)
2283 meta.mm_address = env->me_map;
2284 i = mdb_env_init_meta(env, &meta);
2285 if (i != MDB_SUCCESS) {
2286 munmap(env->me_map, env->me_mapsize);
2290 env->me_psize = meta.mm_psize;
2292 env->me_maxpg = env->me_mapsize / env->me_psize;
2294 p = (MDB_page *)env->me_map;
2295 env->me_metas[0] = METADATA(p);
2296 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
2298 if ((i = mdb_env_read_meta(env, &toggle)) != 0)
2301 DPRINTF("opened database version %u, pagesize %u",
2302 env->me_metas[toggle]->mm_version, env->me_psize);
2303 DPRINTF("depth: %u", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_depth);
2304 DPRINTF("entries: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_entries);
2305 DPRINTF("branch pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_branch_pages);
2306 DPRINTF("leaf pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_leaf_pages);
2307 DPRINTF("overflow pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_overflow_pages);
2308 DPRINTF("root: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_root);
2314 /** Release a reader thread's slot in the reader lock table.
2315 * This function is called automatically when a thread exits.
2316 * Windows doesn't support destructor callbacks for thread-specific storage,
2317 * so this function is not compiled there.
2318 * @param[in] ptr This points to the slot in the reader lock table.
2321 mdb_env_reader_dest(void *ptr)
2323 MDB_reader *reader = ptr;
2325 reader->mr_txnid = 0;
2331 /** Downgrade the exclusive lock on the region back to shared */
2333 mdb_env_share_locks(MDB_env *env)
2337 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
2339 env->me_txns->mti_me_toggle = toggle;
2340 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
2345 /* First acquire a shared lock. The Unlock will
2346 * then release the existing exclusive lock.
2348 memset(&ov, 0, sizeof(ov));
2349 LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov);
2350 UnlockFile(env->me_lfd, 0, 0, 1, 0);
2354 struct flock lock_info;
2355 /* The shared lock replaces the existing lock */
2356 memset((void *)&lock_info, 0, sizeof(lock_info));
2357 lock_info.l_type = F_RDLCK;
2358 lock_info.l_whence = SEEK_SET;
2359 lock_info.l_start = 0;
2360 lock_info.l_len = 1;
2361 fcntl(env->me_lfd, F_SETLK, &lock_info);
2365 #if defined(_WIN32) || defined(__APPLE__)
2367 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
2369 * @(#) $Revision: 5.1 $
2370 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
2371 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
2373 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
2377 * Please do not copyright this code. This code is in the public domain.
2379 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
2380 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
2381 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
2382 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
2383 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
2384 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
2385 * PERFORMANCE OF THIS SOFTWARE.
2388 * chongo <Landon Curt Noll> /\oo/\
2389 * http://www.isthe.com/chongo/
2391 * Share and Enjoy! :-)
2394 typedef unsigned long long mdb_hash_t;
2395 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
2397 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
2398 * @param[in] str string to hash
2399 * @param[in] hval initial value for hash
2400 * @return 64 bit hash
2402 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
2403 * hval arg on the first call.
2406 mdb_hash_str(char *str, mdb_hash_t hval)
2408 unsigned char *s = (unsigned char *)str; /* unsigned string */
2410 * FNV-1a hash each octet of the string
2413 /* xor the bottom with the current octet */
2414 hval ^= (mdb_hash_t)*s++;
2416 /* multiply by the 64 bit FNV magic prime mod 2^64 */
2417 hval += (hval << 1) + (hval << 4) + (hval << 5) +
2418 (hval << 7) + (hval << 8) + (hval << 40);
2420 /* return our new hash value */
2424 /** Hash the string and output the hash in hex.
2425 * @param[in] str string to hash
2426 * @param[out] hexbuf an array of 17 chars to hold the hash
2429 mdb_hash_hex(char *str, char *hexbuf)
2432 mdb_hash_t h = mdb_hash_str(str, MDB_HASH_INIT);
2433 for (i=0; i<8; i++) {
2434 hexbuf += sprintf(hexbuf, "%02x", (unsigned int)h & 0xff);
2440 /** Open and/or initialize the lock region for the environment.
2441 * @param[in] env The MDB environment.
2442 * @param[in] lpath The pathname of the file used for the lock region.
2443 * @param[in] mode The Unix permissions for the file, if we create it.
2444 * @param[out] excl Set to true if we got an exclusive lock on the region.
2445 * @return 0 on success, non-zero on failure.
2448 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
2456 if ((env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
2457 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
2458 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
2462 /* Try to get exclusive lock. If we succeed, then
2463 * nobody is using the lock region and we should initialize it.
2466 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
2470 memset(&ov, 0, sizeof(ov));
2471 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
2477 size = GetFileSize(env->me_lfd, NULL);
2479 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
2483 /* Try to get exclusive lock. If we succeed, then
2484 * nobody is using the lock region and we should initialize it.
2487 struct flock lock_info;
2488 memset((void *)&lock_info, 0, sizeof(lock_info));
2489 lock_info.l_type = F_WRLCK;
2490 lock_info.l_whence = SEEK_SET;
2491 lock_info.l_start = 0;
2492 lock_info.l_len = 1;
2493 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
2497 lock_info.l_type = F_RDLCK;
2498 rc = fcntl(env->me_lfd, F_SETLKW, &lock_info);
2505 size = lseek(env->me_lfd, 0, SEEK_END);
2507 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
2508 if (size < rsize && *excl) {
2510 SetFilePointer(env->me_lfd, rsize, NULL, 0);
2511 if (!SetEndOfFile(env->me_lfd)) {
2516 if (ftruncate(env->me_lfd, rsize) != 0) {
2523 size = rsize - sizeof(MDB_txninfo);
2524 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
2529 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
2535 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
2537 if (!env->me_txns) {
2543 env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
2545 if (env->me_txns == MAP_FAILED) {
2553 if (!mdb_sec_inited) {
2554 InitializeSecurityDescriptor(&mdb_null_sd,
2555 SECURITY_DESCRIPTOR_REVISION);
2556 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
2557 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2558 mdb_all_sa.bInheritHandle = FALSE;
2559 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
2562 mdb_hash_hex(lpath, hexbuf);
2563 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", hexbuf);
2564 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
2565 if (!env->me_rmutex) {
2569 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", hexbuf);
2570 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
2571 if (!env->me_wmutex) {
2578 mdb_hash_hex(lpath, hexbuf);
2579 sprintf(env->me_txns->mti_rmname, "MDBr%s", hexbuf);
2580 if (sem_unlink(env->me_txns->mti_rmname)) {
2582 if (rc != ENOENT && rc != EINVAL)
2585 env->me_rmutex = sem_open(env->me_txns->mti_rmname, O_CREAT, mode, 1);
2586 if (!env->me_rmutex) {
2590 sprintf(env->me_txns->mti_wmname, "MDBw%s", hexbuf);
2591 if (sem_unlink(env->me_txns->mti_wmname)) {
2593 if (rc != ENOENT && rc != EINVAL)
2596 env->me_wmutex = sem_open(env->me_txns->mti_wmname, O_CREAT, mode, 1);
2597 if (!env->me_wmutex) {
2601 #else /* __APPLE__ */
2602 pthread_mutexattr_t mattr;
2604 pthread_mutexattr_init(&mattr);
2605 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
2609 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
2610 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
2611 #endif /* __APPLE__ */
2613 env->me_txns->mti_version = MDB_VERSION;
2614 env->me_txns->mti_magic = MDB_MAGIC;
2615 env->me_txns->mti_txnid = 0;
2616 env->me_txns->mti_numreaders = 0;
2617 env->me_txns->mti_me_toggle = 0;
2620 if (env->me_txns->mti_magic != MDB_MAGIC) {
2621 DPUTS("lock region has invalid magic");
2625 if (env->me_txns->mti_version != MDB_VERSION) {
2626 DPRINTF("lock region is version %u, expected version %u",
2627 env->me_txns->mti_version, MDB_VERSION);
2628 rc = MDB_VERSION_MISMATCH;
2632 if (rc != EACCES && rc != EAGAIN) {
2636 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
2637 if (!env->me_rmutex) {
2641 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
2642 if (!env->me_wmutex) {
2648 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
2649 if (!env->me_rmutex) {
2653 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
2654 if (!env->me_wmutex) {
2664 env->me_lfd = INVALID_HANDLE_VALUE;
2669 /** The name of the lock file in the DB environment */
2670 #define LOCKNAME "/lock.mdb"
2671 /** The name of the data file in the DB environment */
2672 #define DATANAME "/data.mdb"
2673 /** The suffix of the lock file when no subdir is used */
2674 #define LOCKSUFF "-lock"
2677 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
2679 int oflags, rc, len, excl;
2680 char *lpath, *dpath;
2683 if (flags & MDB_NOSUBDIR) {
2684 rc = len + sizeof(LOCKSUFF) + len + 1;
2686 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
2691 if (flags & MDB_NOSUBDIR) {
2692 dpath = lpath + len + sizeof(LOCKSUFF);
2693 sprintf(lpath, "%s" LOCKSUFF, path);
2694 strcpy(dpath, path);
2696 dpath = lpath + len + sizeof(LOCKNAME);
2697 sprintf(lpath, "%s" LOCKNAME, path);
2698 sprintf(dpath, "%s" DATANAME, path);
2701 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
2706 if (F_ISSET(flags, MDB_RDONLY)) {
2707 oflags = GENERIC_READ;
2708 len = OPEN_EXISTING;
2710 oflags = GENERIC_READ|GENERIC_WRITE;
2713 mode = FILE_ATTRIBUTE_NORMAL;
2714 if ((env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2715 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2720 if (F_ISSET(flags, MDB_RDONLY))
2723 oflags = O_RDWR | O_CREAT;
2725 if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
2731 if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
2732 /* synchronous fd for meta writes */
2734 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2735 mode |= FILE_FLAG_WRITE_THROUGH;
2736 if ((env->me_mfd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2737 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2742 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2743 oflags |= MDB_DSYNC;
2744 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
2749 env->me_path = strdup(path);
2750 DPRINTF("opened dbenv %p", (void *) env);
2751 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
2752 LAZY_RWLOCK_INIT(&env->me_dblock, NULL);
2754 mdb_env_share_locks(env);
2755 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
2756 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
2757 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
2763 if (env->me_fd != INVALID_HANDLE_VALUE) {
2765 env->me_fd = INVALID_HANDLE_VALUE;
2767 if (env->me_lfd != INVALID_HANDLE_VALUE) {
2769 env->me_lfd = INVALID_HANDLE_VALUE;
2777 mdb_env_close(MDB_env *env)
2784 while (env->me_dpages) {
2785 dp = env->me_dpages;
2786 env->me_dpages = dp->mp_next;
2790 free(env->me_dbs[1]);
2791 free(env->me_dbs[0]);
2795 LAZY_RWLOCK_DESTROY(&env->me_dblock);
2796 pthread_key_delete(env->me_txkey);
2799 munmap(env->me_map, env->me_mapsize);
2804 pid_t pid = getpid();
2806 for (i=0; i<env->me_txns->mti_numreaders; i++)
2807 if (env->me_txns->mti_readers[i].mr_pid == pid)
2808 env->me_txns->mti_readers[i].mr_pid = 0;
2809 munmap(env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
2812 mdb_midl_free(env->me_free_pgs);
2816 /** Compare two items pointing at aligned size_t's */
2818 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
2820 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
2821 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
2824 /** Compare two items pointing at aligned int's */
2826 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
2828 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
2829 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
2832 /** Compare two items pointing at ints of unknown alignment.
2833 * Nodes and keys are guaranteed to be 2-byte aligned.
2836 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
2838 #if BYTE_ORDER == LITTLE_ENDIAN
2839 unsigned short *u, *c;
2842 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
2843 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
2846 } while(!x && u > (unsigned short *)a->mv_data);
2849 return memcmp(a->mv_data, b->mv_data, a->mv_size);
2853 /** Compare two items lexically */
2855 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
2862 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
2868 diff = memcmp(a->mv_data, b->mv_data, len);
2869 return diff ? diff : len_diff<0 ? -1 : len_diff;
2872 /** Compare two items in reverse byte order */
2874 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
2876 const unsigned char *p1, *p2, *p1_lim;
2880 p1_lim = (const unsigned char *)a->mv_data;
2881 p1 = (const unsigned char *)a->mv_data + a->mv_size;
2882 p2 = (const unsigned char *)b->mv_data + b->mv_size;
2884 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
2890 while (p1 > p1_lim) {
2891 diff = *--p1 - *--p2;
2895 return len_diff<0 ? -1 : len_diff;
2898 /** Search for key within a page, using binary search.
2899 * Returns the smallest entry larger or equal to the key.
2900 * If exactp is non-null, stores whether the found entry was an exact match
2901 * in *exactp (1 or 0).
2902 * Updates the cursor index with the index of the found entry.
2903 * If no entry larger or equal to the key is found, returns NULL.
2906 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
2908 unsigned int i = 0, nkeys;
2911 MDB_page *mp = mc->mc_pg[mc->mc_top];
2912 MDB_node *node = NULL;
2917 nkeys = NUMKEYS(mp);
2919 DPRINTF("searching %u keys in %s %spage %zu",
2920 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
2925 low = IS_LEAF(mp) ? 0 : 1;
2927 cmp = mc->mc_dbx->md_cmp;
2929 /* Branch pages have no data, so if using integer keys,
2930 * alignment is guaranteed. Use faster mdb_cmp_int.
2932 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
2933 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
2940 nodekey.mv_size = mc->mc_db->md_pad;
2941 node = NODEPTR(mp, 0); /* fake */
2942 while (low <= high) {
2943 i = (low + high) >> 1;
2944 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
2945 rc = cmp(key, &nodekey);
2946 DPRINTF("found leaf index %u [%s], rc = %i",
2947 i, DKEY(&nodekey), rc);
2956 while (low <= high) {
2957 i = (low + high) >> 1;
2959 node = NODEPTR(mp, i);
2960 nodekey.mv_size = NODEKSZ(node);
2961 nodekey.mv_data = NODEKEY(node);
2963 rc = cmp(key, &nodekey);
2966 DPRINTF("found leaf index %u [%s], rc = %i",
2967 i, DKEY(&nodekey), rc);
2969 DPRINTF("found branch index %u [%s -> %zu], rc = %i",
2970 i, DKEY(&nodekey), NODEPGNO(node), rc);
2981 if (rc > 0) { /* Found entry is less than the key. */
2982 i++; /* Skip to get the smallest entry larger than key. */
2984 node = NODEPTR(mp, i);
2987 *exactp = (rc == 0);
2988 /* store the key index */
2989 mc->mc_ki[mc->mc_top] = i;
2991 /* There is no entry larger or equal to the key. */
2994 /* nodeptr is fake for LEAF2 */
3000 mdb_cursor_adjust(MDB_cursor *mc, func)
3004 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
3005 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
3012 /** Pop a page off the top of the cursor's stack. */
3014 mdb_cursor_pop(MDB_cursor *mc)
3019 top = mc->mc_pg[mc->mc_top];
3024 DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
3025 mc->mc_dbi, (void *) mc);
3029 /** Push a page onto the top of the cursor's stack. */
3031 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
3033 DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
3034 mc->mc_dbi, (void *) mc);
3036 if (mc->mc_snum >= CURSOR_STACK) {
3037 assert(mc->mc_snum < CURSOR_STACK);
3041 mc->mc_top = mc->mc_snum++;
3042 mc->mc_pg[mc->mc_top] = mp;
3043 mc->mc_ki[mc->mc_top] = 0;
3048 /** Find the address of the page corresponding to a given page number.
3049 * @param[in] txn the transaction for this access.
3050 * @param[in] pgno the page number for the page to retrieve.
3051 * @param[out] ret address of a pointer where the page's address will be stored.
3052 * @return 0 on success, non-zero on failure.
3055 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
3059 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
3061 x = mdb_mid2l_search(txn->mt_u.dirty_list, pgno);
3062 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
3063 p = txn->mt_u.dirty_list[x].mptr;
3067 if (pgno <= txn->mt_env->me_metas[txn->mt_toggle]->mm_last_pg)
3068 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
3072 DPRINTF("page %zu not found", pgno);
3075 return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
3078 /** Search for the page a given key should be in.
3079 * Pushes parent pages on the cursor stack. This function continues a
3080 * search on a cursor that has already been initialized. (Usually by
3081 * #mdb_page_search() but also by #mdb_node_move().)
3082 * @param[in,out] mc the cursor for this operation.
3083 * @param[in] key the key to search for. If NULL, search for the lowest
3084 * page. (This is used by #mdb_cursor_first().)
3085 * @param[in] modify If true, visited pages are updated with new page numbers.
3086 * @return 0 on success, non-zero on failure.
3089 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
3091 MDB_page *mp = mc->mc_pg[mc->mc_top];
3096 while (IS_BRANCH(mp)) {
3100 DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
3101 assert(NUMKEYS(mp) > 1);
3102 DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
3104 if (key == NULL) /* Initialize cursor to first page. */
3106 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
3107 /* cursor to last page */
3111 node = mdb_node_search(mc, key, &exact);
3113 i = NUMKEYS(mp) - 1;
3115 i = mc->mc_ki[mc->mc_top];
3124 DPRINTF("following index %u for key [%s]",
3126 assert(i < NUMKEYS(mp));
3127 node = NODEPTR(mp, i);
3129 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp)))
3132 mc->mc_ki[mc->mc_top] = i;
3133 if ((rc = mdb_cursor_push(mc, mp)))
3137 if ((rc = mdb_page_touch(mc)) != 0)
3139 mp = mc->mc_pg[mc->mc_top];
3144 DPRINTF("internal error, index points to a %02X page!?",
3146 return MDB_CORRUPTED;
3149 DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
3150 key ? DKEY(key) : NULL);
3155 /** Search for the page a given key should be in.
3156 * Pushes parent pages on the cursor stack. This function just sets up
3157 * the search; it finds the root page for \b mc's database and sets this
3158 * as the root of the cursor's stack. Then #mdb_page_search_root() is
3159 * called to complete the search.
3160 * @param[in,out] mc the cursor for this operation.
3161 * @param[in] key the key to search for. If NULL, search for the lowest
3162 * page. (This is used by #mdb_cursor_first().)
3163 * @param[in] modify If true, visited pages are updated with new page numbers.
3164 * @return 0 on success, non-zero on failure.
3167 mdb_page_search(MDB_cursor *mc, MDB_val *key, int modify)
3172 /* Make sure the txn is still viable, then find the root from
3173 * the txn's db table.
3175 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
3176 DPUTS("transaction has failed, must abort");
3179 /* Make sure we're using an up-to-date root */
3180 if (mc->mc_dbi > MAIN_DBI) {
3181 if ((*mc->mc_dbflag & DB_STALE) ||
3182 (modify && !(*mc->mc_dbflag & DB_DIRTY))) {
3184 unsigned char dbflag = 0;
3185 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
3186 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, modify);
3189 if (*mc->mc_dbflag & DB_STALE) {
3192 MDB_node *leaf = mdb_node_search(&mc2,
3193 &mc->mc_dbx->md_name, &exact);
3195 return MDB_NOTFOUND;
3196 mdb_node_read(mc->mc_txn, leaf, &data);
3197 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
3201 *mc->mc_dbflag = dbflag;
3204 root = mc->mc_db->md_root;
3206 if (root == P_INVALID) { /* Tree is empty. */
3207 DPUTS("tree is empty");
3208 return MDB_NOTFOUND;
3213 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0])))
3219 DPRINTF("db %u root page %zu has flags 0x%X",
3220 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
3223 if ((rc = mdb_page_touch(mc)))
3227 return mdb_page_search_root(mc, key, modify);
3230 /** Return the data associated with a given node.
3231 * @param[in] txn The transaction for this operation.
3232 * @param[in] leaf The node being read.
3233 * @param[out] data Updated to point to the node's data.
3234 * @return 0 on success, non-zero on failure.
3237 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
3239 MDB_page *omp; /* overflow page */
3243 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
3244 data->mv_size = NODEDSZ(leaf);
3245 data->mv_data = NODEDATA(leaf);
3249 /* Read overflow data.
3251 data->mv_size = NODEDSZ(leaf);
3252 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
3253 if ((rc = mdb_page_get(txn, pgno, &omp))) {
3254 DPRINTF("read overflow page %zu failed", pgno);
3257 data->mv_data = METADATA(omp);
3263 mdb_get(MDB_txn *txn, MDB_dbi dbi,
3264 MDB_val *key, MDB_val *data)
3273 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
3275 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3278 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3282 mdb_cursor_init(&mc, txn, dbi, &mx);
3283 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
3286 /** Find a sibling for a page.
3287 * Replaces the page at the top of the cursor's stack with the
3288 * specified sibling, if one exists.
3289 * @param[in] mc The cursor for this operation.
3290 * @param[in] move_right Non-zero if the right sibling is requested,
3291 * otherwise the left sibling.
3292 * @return 0 on success, non-zero on failure.
3295 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
3301 if (mc->mc_snum < 2) {
3302 return MDB_NOTFOUND; /* root has no siblings */
3306 DPRINTF("parent page is page %zu, index %u",
3307 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]);
3309 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
3310 : (mc->mc_ki[mc->mc_top] == 0)) {
3311 DPRINTF("no more keys left, moving to %s sibling",
3312 move_right ? "right" : "left");
3313 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS)
3317 mc->mc_ki[mc->mc_top]++;
3319 mc->mc_ki[mc->mc_top]--;
3320 DPRINTF("just moving to %s index key %u",
3321 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]);
3323 assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
3325 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3326 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp)))
3329 mdb_cursor_push(mc, mp);
3334 /** Move the cursor to the next data item. */
3336 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3342 if (mc->mc_flags & C_EOF) {
3343 return MDB_NOTFOUND;
3346 assert(mc->mc_flags & C_INITIALIZED);
3348 mp = mc->mc_pg[mc->mc_top];
3350 if (mc->mc_db->md_flags & MDB_DUPSORT) {
3351 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3352 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3353 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
3354 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
3355 if (op != MDB_NEXT || rc == MDB_SUCCESS)
3359 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3360 if (op == MDB_NEXT_DUP)
3361 return MDB_NOTFOUND;
3365 DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3367 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
3368 DPUTS("=====> move to next sibling page");
3369 if (mdb_cursor_sibling(mc, 1) != MDB_SUCCESS) {
3370 mc->mc_flags |= C_EOF;
3371 mc->mc_flags &= ~C_INITIALIZED;
3372 return MDB_NOTFOUND;
3374 mp = mc->mc_pg[mc->mc_top];
3375 DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3377 mc->mc_ki[mc->mc_top]++;
3379 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3380 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3383 key->mv_size = mc->mc_db->md_pad;
3384 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3388 assert(IS_LEAF(mp));
3389 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3391 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3392 mdb_xcursor_init1(mc, leaf);
3395 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3398 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3399 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3400 if (rc != MDB_SUCCESS)
3405 MDB_SET_KEY(leaf, key);
3409 /** Move the cursor to the previous data item. */
3411 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3417 assert(mc->mc_flags & C_INITIALIZED);
3419 mp = mc->mc_pg[mc->mc_top];
3421 if (mc->mc_db->md_flags & MDB_DUPSORT) {
3422 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3423 if (op == MDB_PREV || op == MDB_PREV_DUP) {
3424 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3425 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
3426 if (op != MDB_PREV || rc == MDB_SUCCESS)
3429 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3430 if (op == MDB_PREV_DUP)
3431 return MDB_NOTFOUND;
3436 DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3438 if (mc->mc_ki[mc->mc_top] == 0) {
3439 DPUTS("=====> move to prev sibling page");
3440 if (mdb_cursor_sibling(mc, 0) != MDB_SUCCESS) {
3441 mc->mc_flags &= ~C_INITIALIZED;
3442 return MDB_NOTFOUND;
3444 mp = mc->mc_pg[mc->mc_top];
3445 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
3446 DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3448 mc->mc_ki[mc->mc_top]--;
3450 mc->mc_flags &= ~C_EOF;
3452 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3453 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3456 key->mv_size = mc->mc_db->md_pad;
3457 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3461 assert(IS_LEAF(mp));
3462 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3464 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3465 mdb_xcursor_init1(mc, leaf);
3468 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3471 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3472 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3473 if (rc != MDB_SUCCESS)
3478 MDB_SET_KEY(leaf, key);
3482 /** Set the cursor on a specific data item. */
3484 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3485 MDB_cursor_op op, int *exactp)
3494 assert(key->mv_size > 0);
3496 /* See if we're already on the right page */
3497 if (mc->mc_flags & C_INITIALIZED) {
3500 mp = mc->mc_pg[mc->mc_top];
3502 mc->mc_ki[mc->mc_top] = 0;
3503 return MDB_NOTFOUND;
3505 if (mp->mp_flags & P_LEAF2) {
3506 nodekey.mv_size = mc->mc_db->md_pad;
3507 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
3509 leaf = NODEPTR(mp, 0);
3510 MDB_SET_KEY(leaf, &nodekey);
3512 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3514 /* Probably happens rarely, but first node on the page
3515 * was the one we wanted.
3517 mc->mc_ki[mc->mc_top] = 0;
3518 leaf = NODEPTR(mp, 0);
3525 unsigned int nkeys = NUMKEYS(mp);
3527 if (mp->mp_flags & P_LEAF2) {
3528 nodekey.mv_data = LEAF2KEY(mp,
3529 nkeys-1, nodekey.mv_size);
3531 leaf = NODEPTR(mp, nkeys-1);
3532 MDB_SET_KEY(leaf, &nodekey);
3534 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3536 /* last node was the one we wanted */
3537 mc->mc_ki[mc->mc_top] = nkeys-1;
3538 leaf = NODEPTR(mp, nkeys-1);
3544 /* This is definitely the right page, skip search_page */
3549 /* If any parents have right-sibs, search.
3550 * Otherwise, there's nothing further.
3552 for (i=0; i<mc->mc_top; i++)
3554 NUMKEYS(mc->mc_pg[i])-1)
3556 if (i == mc->mc_top) {
3557 /* There are no other pages */
3558 mc->mc_ki[mc->mc_top] = nkeys;
3559 return MDB_NOTFOUND;
3563 /* There are no other pages */
3564 mc->mc_ki[mc->mc_top] = 0;
3565 return MDB_NOTFOUND;
3569 rc = mdb_page_search(mc, key, 0);
3570 if (rc != MDB_SUCCESS)
3573 mp = mc->mc_pg[mc->mc_top];
3574 assert(IS_LEAF(mp));
3577 leaf = mdb_node_search(mc, key, exactp);
3578 if (exactp != NULL && !*exactp) {
3579 /* MDB_SET specified and not an exact match. */
3580 return MDB_NOTFOUND;
3584 DPUTS("===> inexact leaf not found, goto sibling");
3585 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
3586 return rc; /* no entries matched */
3587 mp = mc->mc_pg[mc->mc_top];
3588 assert(IS_LEAF(mp));
3589 leaf = NODEPTR(mp, 0);
3593 mc->mc_flags |= C_INITIALIZED;
3594 mc->mc_flags &= ~C_EOF;
3597 key->mv_size = mc->mc_db->md_pad;
3598 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3602 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3603 mdb_xcursor_init1(mc, leaf);
3606 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3607 if (op == MDB_SET || op == MDB_SET_RANGE) {
3608 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3611 if (op == MDB_GET_BOTH) {
3617 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
3618 if (rc != MDB_SUCCESS)
3621 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
3623 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
3625 rc = mc->mc_dbx->md_dcmp(data, &d2);
3627 if (op == MDB_GET_BOTH || rc > 0)
3628 return MDB_NOTFOUND;
3633 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3634 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3639 /* The key already matches in all other cases */
3640 if (op == MDB_SET_RANGE)
3641 MDB_SET_KEY(leaf, key);
3642 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
3647 /** Move the cursor to the first item in the database. */
3649 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3654 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3655 rc = mdb_page_search(mc, NULL, 0);
3656 if (rc != MDB_SUCCESS)
3659 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3661 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
3662 mc->mc_flags |= C_INITIALIZED;
3663 mc->mc_flags &= ~C_EOF;
3665 mc->mc_ki[mc->mc_top] = 0;
3667 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3668 key->mv_size = mc->mc_db->md_pad;
3669 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
3674 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3675 mdb_xcursor_init1(mc, leaf);
3676 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3681 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3682 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3686 MDB_SET_KEY(leaf, key);
3690 /** Move the cursor to the last item in the database. */
3692 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3698 lkey.mv_size = MAXKEYSIZE+1;
3699 lkey.mv_data = NULL;
3701 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3702 rc = mdb_page_search(mc, &lkey, 0);
3703 if (rc != MDB_SUCCESS)
3706 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3708 leaf = NODEPTR(mc->mc_pg[mc->mc_top], NUMKEYS(mc->mc_pg[mc->mc_top])-1);
3709 mc->mc_flags |= C_INITIALIZED;
3710 mc->mc_flags &= ~C_EOF;
3712 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
3714 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3715 key->mv_size = mc->mc_db->md_pad;
3716 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
3721 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3722 mdb_xcursor_init1(mc, leaf);
3723 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3728 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3729 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3734 MDB_SET_KEY(leaf, key);
3739 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3749 case MDB_GET_BOTH_RANGE:
3750 if (data == NULL || mc->mc_xcursor == NULL) {
3757 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3759 } else if (op == MDB_SET_RANGE)
3760 rc = mdb_cursor_set(mc, key, data, op, NULL);
3762 rc = mdb_cursor_set(mc, key, data, op, &exact);
3764 case MDB_GET_MULTIPLE:
3766 !(mc->mc_db->md_flags & MDB_DUPFIXED) ||
3767 !(mc->mc_flags & C_INITIALIZED)) {
3772 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
3773 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
3776 case MDB_NEXT_MULTIPLE:
3778 !(mc->mc_db->md_flags & MDB_DUPFIXED)) {
3782 if (!(mc->mc_flags & C_INITIALIZED))
3783 rc = mdb_cursor_first(mc, key, data);
3785 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
3786 if (rc == MDB_SUCCESS) {
3787 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
3790 mx = &mc->mc_xcursor->mx_cursor;
3791 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
3793 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
3794 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
3802 case MDB_NEXT_NODUP:
3803 if (!(mc->mc_flags & C_INITIALIZED))
3804 rc = mdb_cursor_first(mc, key, data);
3806 rc = mdb_cursor_next(mc, key, data, op);
3810 case MDB_PREV_NODUP:
3811 if (!(mc->mc_flags & C_INITIALIZED) || (mc->mc_flags & C_EOF))
3812 rc = mdb_cursor_last(mc, key, data);
3814 rc = mdb_cursor_prev(mc, key, data, op);
3817 rc = mdb_cursor_first(mc, key, data);
3821 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
3822 !(mc->mc_flags & C_INITIALIZED) ||
3823 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3827 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3830 rc = mdb_cursor_last(mc, key, data);
3834 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
3835 !(mc->mc_flags & C_INITIALIZED) ||
3836 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3840 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3843 DPRINTF("unhandled/unimplemented cursor operation %u", op);
3851 /** Touch all the pages in the cursor stack.
3852 * Makes sure all the pages are writable, before attempting a write operation.
3853 * @param[in] mc The cursor to operate on.
3856 mdb_cursor_touch(MDB_cursor *mc)
3860 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
3862 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
3863 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 1);
3866 *mc->mc_dbflag = DB_DIRTY;
3868 for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
3869 rc = mdb_page_touch(mc);
3873 mc->mc_top = mc->mc_snum-1;
3878 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3881 MDB_node *leaf = NULL;
3882 MDB_val xdata, *rdata, dkey;
3886 unsigned int mcount = 0;
3889 char pbuf[PAGESIZE];
3890 char dbuf[MAXKEYSIZE+1];
3891 unsigned int nflags;
3894 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
3897 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
3898 mc->mc_dbi, DKEY(key), key ? key->mv_size:0, data->mv_size);
3902 if (flags == MDB_CURRENT) {
3903 if (!(mc->mc_flags & C_INITIALIZED))
3906 } else if (mc->mc_db->md_root == P_INVALID) {
3908 /* new database, write a root leaf page */
3909 DPUTS("allocating new root leaf page");
3910 if ((np = mdb_page_new(mc, P_LEAF, 1)) == NULL) {
3914 mdb_cursor_push(mc, np);
3915 mc->mc_db->md_root = np->mp_pgno;
3916 mc->mc_db->md_depth++;
3917 *mc->mc_dbflag = DB_DIRTY;
3918 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
3920 np->mp_flags |= P_LEAF2;
3921 mc->mc_flags |= C_INITIALIZED;
3927 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
3928 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
3929 DPRINTF("duplicate key [%s]", DKEY(key));
3931 return MDB_KEYEXIST;
3933 if (rc && rc != MDB_NOTFOUND)
3937 /* Cursor is positioned, now make sure all pages are writable */
3938 rc2 = mdb_cursor_touch(mc);
3943 /* The key already exists */
3944 if (rc == MDB_SUCCESS) {
3945 /* there's only a key anyway, so this is a no-op */
3946 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3947 unsigned int ksize = mc->mc_db->md_pad;
3948 if (key->mv_size != ksize)
3950 if (flags == MDB_CURRENT) {
3951 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
3952 memcpy(ptr, key->mv_data, ksize);
3957 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3960 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
3961 /* Was a single item before, must convert now */
3963 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3964 /* Just overwrite the current item */
3965 if (flags == MDB_CURRENT)
3968 dkey.mv_size = NODEDSZ(leaf);
3969 dkey.mv_data = NODEDATA(leaf);
3970 /* data matches, ignore it */
3971 if (!mc->mc_dbx->md_dcmp(data, &dkey))
3972 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
3974 /* create a fake page for the dup items */
3975 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
3976 dkey.mv_data = dbuf;
3977 fp = (MDB_page *)pbuf;
3978 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
3979 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
3980 fp->mp_lower = PAGEHDRSZ;
3981 fp->mp_upper = PAGEHDRSZ + dkey.mv_size + data->mv_size;
3982 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
3983 fp->mp_flags |= P_LEAF2;
3984 fp->mp_pad = data->mv_size;
3986 fp->mp_upper += 2 * sizeof(indx_t) + 2 * NODESIZE +
3987 (dkey.mv_size & 1) + (data->mv_size & 1);
3989 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
3992 xdata.mv_size = fp->mp_upper;
3993 xdata.mv_data = pbuf;
3997 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
3998 /* See if we need to convert from fake page to subDB */
4000 unsigned int offset;
4003 fp = NODEDATA(leaf);
4004 if (flags == MDB_CURRENT) {
4005 fp->mp_flags |= P_DIRTY;
4006 #ifdef MISALIGNED_OK
4007 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4010 unsigned short *src, *dst;
4012 dst = (unsigned short *)&fp->mp_pgno;
4013 src = (unsigned short *)&mc->mc_pg[mc->mc_top]->mp_pgno;
4014 for (i=0; i<sizeof(fp->mp_pgno)/sizeof(unsigned short); i++)
4018 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
4022 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4023 offset = fp->mp_pad;
4025 offset = NODESIZE + sizeof(indx_t) + data->mv_size;
4027 offset += offset & 1;
4028 if (NODESIZE + sizeof(indx_t) + NODEKSZ(leaf) + NODEDSZ(leaf) +
4029 offset >= (mc->mc_txn->mt_env->me_psize - PAGEHDRSZ) /
4031 /* yes, convert it */
4033 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4034 dummy.md_pad = fp->mp_pad;
4035 dummy.md_flags = MDB_DUPFIXED;
4036 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
4037 dummy.md_flags |= MDB_INTEGERKEY;
4040 dummy.md_branch_pages = 0;
4041 dummy.md_leaf_pages = 1;
4042 dummy.md_overflow_pages = 0;
4043 dummy.md_entries = NUMKEYS(fp);
4045 xdata.mv_size = sizeof(MDB_db);
4046 xdata.mv_data = &dummy;
4047 mp = mdb_page_alloc(mc, 1);
4050 offset = mc->mc_txn->mt_env->me_psize - NODEDSZ(leaf);
4051 flags |= F_DUPDATA|F_SUBDATA;
4052 dummy.md_root = mp->mp_pgno;
4054 /* no, just grow it */
4056 xdata.mv_size = NODEDSZ(leaf) + offset;
4057 xdata.mv_data = pbuf;
4058 mp = (MDB_page *)pbuf;
4059 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4062 mp->mp_flags = fp->mp_flags | P_DIRTY;
4063 mp->mp_pad = fp->mp_pad;
4064 mp->mp_lower = fp->mp_lower;
4065 mp->mp_upper = fp->mp_upper + offset;
4067 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
4069 nsize = NODEDSZ(leaf) - fp->mp_upper;
4070 memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper, nsize);
4071 for (i=0; i<NUMKEYS(fp); i++)
4072 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
4074 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4078 /* data is on sub-DB, just store it */
4079 flags |= F_DUPDATA|F_SUBDATA;
4083 /* same size, just replace it */
4084 if (!F_ISSET(leaf->mn_flags, F_BIGDATA) &&
4085 NODEDSZ(leaf) == data->mv_size) {
4086 if (F_ISSET(flags, MDB_RESERVE))
4087 data->mv_data = NODEDATA(leaf);
4089 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
4092 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4094 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
4100 nflags = flags & NODE_ADD_FLAGS;
4101 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
4102 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
4103 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
4104 nflags &= ~MDB_APPEND;
4105 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
4107 /* There is room already in this leaf page. */
4108 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
4109 if (rc == 0 && !do_sub) {
4110 /* Adjust other cursors pointing to mp */
4111 MDB_cursor *m2, *m3;
4112 MDB_dbi dbi = mc->mc_dbi;
4113 unsigned i = mc->mc_top;
4114 MDB_page *mp = mc->mc_pg[i];
4116 if (mc->mc_flags & C_SUB)
4119 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
4120 if (mc->mc_flags & C_SUB)
4121 m3 = &m2->mc_xcursor->mx_cursor;
4124 if (m3 == mc) continue;
4125 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
4132 if (rc != MDB_SUCCESS)
4133 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4135 /* Now store the actual data in the child DB. Note that we're
4136 * storing the user data in the keys field, so there are strict
4137 * size limits on dupdata. The actual data fields of the child
4138 * DB are all zero size.
4146 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4147 if (flags & MDB_CURRENT) {
4148 xflags = MDB_CURRENT;
4150 mdb_xcursor_init1(mc, leaf);
4151 xflags = (flags & MDB_NODUPDATA) ? MDB_NOOVERWRITE : 0;
4153 /* converted, write the original data first */
4155 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
4159 /* Adjust other cursors pointing to mp */
4161 unsigned i = mc->mc_top;
4162 MDB_page *mp = mc->mc_pg[i];
4164 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4165 if (m2 == mc) continue;
4166 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
4167 mdb_xcursor_init1(m2, leaf);
4172 xflags |= (flags & MDB_APPEND);
4173 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
4174 if (flags & F_SUBDATA) {
4175 db = NODEDATA(leaf);
4176 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4179 /* sub-writes might have failed so check rc again.
4180 * Don't increment count if we just replaced an existing item.
4182 if (!rc && !(flags & MDB_CURRENT))
4183 mc->mc_db->md_entries++;
4184 if (flags & MDB_MULTIPLE) {
4186 if (mcount < data[1].mv_size) {
4187 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
4188 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4198 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
4203 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
4206 if (!mc->mc_flags & C_INITIALIZED)
4209 rc = mdb_cursor_touch(mc);
4213 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4215 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4216 if (flags != MDB_NODUPDATA) {
4217 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
4218 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
4220 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
4221 /* If sub-DB still has entries, we're done */
4222 if (mc->mc_xcursor->mx_db.md_entries) {
4223 if (leaf->mn_flags & F_SUBDATA) {
4224 /* update subDB info */
4225 MDB_db *db = NODEDATA(leaf);
4226 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4228 /* shrink fake page */
4229 mdb_node_shrink(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4231 mc->mc_db->md_entries--;
4234 /* otherwise fall thru and delete the sub-DB */
4237 if (leaf->mn_flags & F_SUBDATA) {
4238 /* add all the child DB's pages to the free list */
4239 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
4240 if (rc == MDB_SUCCESS) {
4241 mc->mc_db->md_entries -=
4242 mc->mc_xcursor->mx_db.md_entries;
4247 return mdb_cursor_del0(mc, leaf);
4250 /** Allocate and initialize new pages for a database.
4251 * @param[in] mc a cursor on the database being added to.
4252 * @param[in] flags flags defining what type of page is being allocated.
4253 * @param[in] num the number of pages to allocate. This is usually 1,
4254 * unless allocating overflow pages for a large record.
4255 * @return Address of a page, or NULL on failure.
4258 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num)
4262 if ((np = mdb_page_alloc(mc, num)) == NULL)
4264 DPRINTF("allocated new mpage %zu, page size %u",
4265 np->mp_pgno, mc->mc_txn->mt_env->me_psize);
4266 np->mp_flags = flags | P_DIRTY;
4267 np->mp_lower = PAGEHDRSZ;
4268 np->mp_upper = mc->mc_txn->mt_env->me_psize;
4271 mc->mc_db->md_branch_pages++;
4272 else if (IS_LEAF(np))
4273 mc->mc_db->md_leaf_pages++;
4274 else if (IS_OVERFLOW(np)) {
4275 mc->mc_db->md_overflow_pages += num;
4282 /** Calculate the size of a leaf node.
4283 * The size depends on the environment's page size; if a data item
4284 * is too large it will be put onto an overflow page and the node
4285 * size will only include the key and not the data. Sizes are always
4286 * rounded up to an even number of bytes, to guarantee 2-byte alignment
4287 * of the #MDB_node headers.
4288 * @param[in] env The environment handle.
4289 * @param[in] key The key for the node.
4290 * @param[in] data The data for the node.
4291 * @return The number of bytes needed to store the node.
4294 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
4298 sz = LEAFSIZE(key, data);
4299 if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
4300 /* put on overflow page */
4301 sz -= data->mv_size - sizeof(pgno_t);
4305 return sz + sizeof(indx_t);
4308 /** Calculate the size of a branch node.
4309 * The size should depend on the environment's page size but since
4310 * we currently don't support spilling large keys onto overflow
4311 * pages, it's simply the size of the #MDB_node header plus the
4312 * size of the key. Sizes are always rounded up to an even number
4313 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
4314 * @param[in] env The environment handle.
4315 * @param[in] key The key for the node.
4316 * @return The number of bytes needed to store the node.
4319 mdb_branch_size(MDB_env *env, MDB_val *key)
4324 if (sz >= env->me_psize / MDB_MINKEYS) {
4325 /* put on overflow page */
4326 /* not implemented */
4327 /* sz -= key->size - sizeof(pgno_t); */
4330 return sz + sizeof(indx_t);
4333 /** Add a node to the page pointed to by the cursor.
4334 * @param[in] mc The cursor for this operation.
4335 * @param[in] indx The index on the page where the new node should be added.
4336 * @param[in] key The key for the new node.
4337 * @param[in] data The data for the new node, if any.
4338 * @param[in] pgno The page number, if adding a branch node.
4339 * @param[in] flags Flags for the node.
4340 * @return 0 on success, non-zero on failure. Possible errors are:
4342 * <li>ENOMEM - failed to allocate overflow pages for the node.
4343 * <li>ENOSPC - there is insufficient room in the page. This error
4344 * should never happen since all callers already calculate the
4345 * page's free space before calling this function.
4349 mdb_node_add(MDB_cursor *mc, indx_t indx,
4350 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
4353 size_t node_size = NODESIZE;
4356 MDB_page *mp = mc->mc_pg[mc->mc_top];
4357 MDB_page *ofp = NULL; /* overflow page */
4360 assert(mp->mp_upper >= mp->mp_lower);
4362 DPRINTF("add to %s %spage %zu index %i, data size %zu key size %zu [%s]",
4363 IS_LEAF(mp) ? "leaf" : "branch",
4364 IS_SUBP(mp) ? "sub-" : "",
4365 mp->mp_pgno, indx, data ? data->mv_size : 0,
4366 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
4369 /* Move higher keys up one slot. */
4370 int ksize = mc->mc_db->md_pad, dif;
4371 char *ptr = LEAF2KEY(mp, indx, ksize);
4372 dif = NUMKEYS(mp) - indx;
4374 memmove(ptr+ksize, ptr, dif*ksize);
4375 /* insert new key */
4376 memcpy(ptr, key->mv_data, ksize);
4378 /* Just using these for counting */
4379 mp->mp_lower += sizeof(indx_t);
4380 mp->mp_upper -= ksize - sizeof(indx_t);
4385 node_size += key->mv_size;
4389 if (F_ISSET(flags, F_BIGDATA)) {
4390 /* Data already on overflow page. */
4391 node_size += sizeof(pgno_t);
4392 } else if (data->mv_size >= mc->mc_txn->mt_env->me_psize / MDB_MINKEYS) {
4393 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
4394 /* Put data on overflow page. */
4395 DPRINTF("data size is %zu, put on overflow page",
4397 node_size += sizeof(pgno_t);
4398 if ((ofp = mdb_page_new(mc, P_OVERFLOW, ovpages)) == NULL)
4400 DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
4403 node_size += data->mv_size;
4406 node_size += node_size & 1;
4408 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
4409 DPRINTF("not enough room in page %zu, got %u ptrs",
4410 mp->mp_pgno, NUMKEYS(mp));
4411 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
4412 mp->mp_upper - mp->mp_lower);
4413 DPRINTF("node size = %zu", node_size);
4417 /* Move higher pointers up one slot. */
4418 for (i = NUMKEYS(mp); i > indx; i--)
4419 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
4421 /* Adjust free space offsets. */
4422 ofs = mp->mp_upper - node_size;
4423 assert(ofs >= mp->mp_lower + sizeof(indx_t));
4424 mp->mp_ptrs[indx] = ofs;
4426 mp->mp_lower += sizeof(indx_t);
4428 /* Write the node data. */
4429 node = NODEPTR(mp, indx);
4430 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
4431 node->mn_flags = flags;
4433 SETDSZ(node,data->mv_size);
4438 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
4443 if (F_ISSET(flags, F_BIGDATA))
4444 memcpy(node->mn_data + key->mv_size, data->mv_data,
4446 else if (F_ISSET(flags, MDB_RESERVE))
4447 data->mv_data = node->mn_data + key->mv_size;
4449 memcpy(node->mn_data + key->mv_size, data->mv_data,
4452 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
4454 if (F_ISSET(flags, MDB_RESERVE))
4455 data->mv_data = METADATA(ofp);
4457 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
4464 /** Delete the specified node from a page.
4465 * @param[in] mp The page to operate on.
4466 * @param[in] indx The index of the node to delete.
4467 * @param[in] ksize The size of a node. Only used if the page is
4468 * part of a #MDB_DUPFIXED database.
4471 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
4474 indx_t i, j, numkeys, ptr;
4478 DPRINTF("delete node %u on %s page %zu", indx,
4479 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
4480 assert(indx < NUMKEYS(mp));
4483 int x = NUMKEYS(mp) - 1 - indx;
4484 base = LEAF2KEY(mp, indx, ksize);
4486 memmove(base, base + ksize, x * ksize);
4487 mp->mp_lower -= sizeof(indx_t);
4488 mp->mp_upper += ksize - sizeof(indx_t);
4492 node = NODEPTR(mp, indx);
4493 sz = NODESIZE + node->mn_ksize;
4495 if (F_ISSET(node->mn_flags, F_BIGDATA))
4496 sz += sizeof(pgno_t);
4498 sz += NODEDSZ(node);
4502 ptr = mp->mp_ptrs[indx];
4503 numkeys = NUMKEYS(mp);
4504 for (i = j = 0; i < numkeys; i++) {
4506 mp->mp_ptrs[j] = mp->mp_ptrs[i];
4507 if (mp->mp_ptrs[i] < ptr)
4508 mp->mp_ptrs[j] += sz;
4513 base = (char *)mp + mp->mp_upper;
4514 memmove(base + sz, base, ptr - mp->mp_upper);
4516 mp->mp_lower -= sizeof(indx_t);
4520 /** Compact the main page after deleting a node on a subpage.
4521 * @param[in] mp The main page to operate on.
4522 * @param[in] indx The index of the subpage on the main page.
4525 mdb_node_shrink(MDB_page *mp, indx_t indx)
4532 indx_t i, numkeys, ptr;
4534 node = NODEPTR(mp, indx);
4535 sp = (MDB_page *)NODEDATA(node);
4536 osize = NODEDSZ(node);
4538 delta = sp->mp_upper - sp->mp_lower;
4539 SETDSZ(node, osize - delta);
4540 xp = (MDB_page *)((char *)sp + delta);
4542 /* shift subpage upward */
4544 nsize = NUMKEYS(sp) * sp->mp_pad;
4545 memmove(METADATA(xp), METADATA(sp), nsize);
4548 nsize = osize - sp->mp_upper;
4549 numkeys = NUMKEYS(sp);
4550 for (i=numkeys-1; i>=0; i--)
4551 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
4553 xp->mp_upper = sp->mp_lower;
4554 xp->mp_lower = sp->mp_lower;
4555 xp->mp_flags = sp->mp_flags;
4556 xp->mp_pad = sp->mp_pad;
4557 xp->mp_pgno = mp->mp_pgno;
4559 /* shift lower nodes upward */
4560 ptr = mp->mp_ptrs[indx];
4561 numkeys = NUMKEYS(mp);
4562 for (i = 0; i < numkeys; i++) {
4563 if (mp->mp_ptrs[i] <= ptr)
4564 mp->mp_ptrs[i] += delta;
4567 base = (char *)mp + mp->mp_upper;
4568 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
4569 mp->mp_upper += delta;
4572 /** Initial setup of a sorted-dups cursor.
4573 * Sorted duplicates are implemented as a sub-database for the given key.
4574 * The duplicate data items are actually keys of the sub-database.
4575 * Operations on the duplicate data items are performed using a sub-cursor
4576 * initialized when the sub-database is first accessed. This function does
4577 * the preliminary setup of the sub-cursor, filling in the fields that
4578 * depend only on the parent DB.
4579 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4582 mdb_xcursor_init0(MDB_cursor *mc)
4584 MDB_xcursor *mx = mc->mc_xcursor;
4586 mx->mx_cursor.mc_xcursor = NULL;
4587 mx->mx_cursor.mc_txn = mc->mc_txn;
4588 mx->mx_cursor.mc_db = &mx->mx_db;
4589 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
4590 mx->mx_cursor.mc_dbi = mc->mc_dbi+1;
4591 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
4592 mx->mx_cursor.mc_snum = 0;
4593 mx->mx_cursor.mc_flags = C_SUB;
4594 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
4595 mx->mx_dbx.md_dcmp = NULL;
4596 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
4599 /** Final setup of a sorted-dups cursor.
4600 * Sets up the fields that depend on the data from the main cursor.
4601 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4602 * @param[in] node The data containing the #MDB_db record for the
4603 * sorted-dup database.
4606 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
4608 MDB_xcursor *mx = mc->mc_xcursor;
4610 if (node->mn_flags & F_SUBDATA) {
4611 MDB_db *db = NODEDATA(node);
4613 mx->mx_cursor.mc_snum = 0;
4614 mx->mx_cursor.mc_flags = C_SUB;
4616 MDB_page *fp = NODEDATA(node);
4617 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
4618 mx->mx_db.md_flags = 0;
4619 mx->mx_db.md_depth = 1;
4620 mx->mx_db.md_branch_pages = 0;
4621 mx->mx_db.md_leaf_pages = 1;
4622 mx->mx_db.md_overflow_pages = 0;
4623 mx->mx_db.md_entries = NUMKEYS(fp);
4624 #ifdef MISALIGNED_OK
4625 mx->mx_db.md_root = fp->mp_pgno;
4628 unsigned short *src, *dst;
4630 dst = (unsigned short *)&mx->mx_db.md_root;
4631 src = (unsigned short *)&fp->mp_pgno;
4632 for (i=0; i<sizeof(fp->mp_pgno)/sizeof(unsigned short); i++)
4636 mx->mx_cursor.mc_snum = 1;
4637 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
4638 mx->mx_cursor.mc_top = 0;
4639 mx->mx_cursor.mc_pg[0] = fp;
4640 mx->mx_cursor.mc_ki[0] = 0;
4641 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4642 mx->mx_db.md_flags = MDB_DUPFIXED;
4643 mx->mx_db.md_pad = fp->mp_pad;
4644 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
4645 mx->mx_db.md_flags |= MDB_INTEGERKEY;
4648 DPRINTF("Sub-db %u for db %u root page %zu", mx->mx_cursor.mc_dbi, mc->mc_dbi,
4650 mx->mx_dbflag = (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY)) ?
4652 mx->mx_dbx.md_name.mv_data = NODEKEY(node);
4653 mx->mx_dbx.md_name.mv_size = node->mn_ksize;
4654 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
4655 mx->mx_dbx.md_cmp = mdb_cmp_long;
4658 /** Initialize a cursor for a given transaction and database. */
4660 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
4665 mc->mc_db = &txn->mt_dbs[dbi];
4666 mc->mc_dbx = &txn->mt_dbxs[dbi];
4667 mc->mc_dbflag = &txn->mt_dbflags[dbi];
4670 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4672 mc->mc_xcursor = mx;
4673 mdb_xcursor_init0(mc);
4675 mc->mc_xcursor = NULL;
4680 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
4683 MDB_xcursor *mx = NULL;
4684 size_t size = sizeof(MDB_cursor);
4686 if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
4689 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
4690 size += sizeof(MDB_xcursor);
4692 if ((mc = malloc(size)) != NULL) {
4693 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4694 mx = (MDB_xcursor *)(mc + 1);
4696 mdb_cursor_init(mc, txn, dbi, mx);
4697 if (txn->mt_cursors) {
4698 mc->mc_next = txn->mt_cursors[dbi];
4699 txn->mt_cursors[dbi] = mc;
4701 mc->mc_flags |= C_ALLOCD;
4711 /* Return the count of duplicate data items for the current key */
4713 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
4717 if (mc == NULL || countp == NULL)
4720 if (!(mc->mc_db->md_flags & MDB_DUPSORT))
4723 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4724 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4727 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
4730 *countp = mc->mc_xcursor->mx_db.md_entries;
4736 mdb_cursor_close(MDB_cursor *mc)
4739 /* remove from txn, if tracked */
4740 if (mc->mc_txn->mt_cursors) {
4741 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
4742 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
4744 *prev = mc->mc_next;
4746 if (mc->mc_flags & C_ALLOCD)
4752 mdb_cursor_txn(MDB_cursor *mc)
4754 if (!mc) return NULL;
4759 mdb_cursor_dbi(MDB_cursor *mc)
4765 /** Replace the key for a node with a new key.
4766 * @param[in] mp The page containing the node to operate on.
4767 * @param[in] indx The index of the node to operate on.
4768 * @param[in] key The new key to use.
4769 * @return 0 on success, non-zero on failure.
4772 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
4774 indx_t ptr, i, numkeys;
4781 node = NODEPTR(mp, indx);
4782 ptr = mp->mp_ptrs[indx];
4783 DPRINTF("update key %u (ofs %u) [%.*s] to [%s] on page %zu",
4785 (int)node->mn_ksize, (char *)NODEKEY(node),
4789 delta = key->mv_size - node->mn_ksize;
4791 if (delta > 0 && SIZELEFT(mp) < delta) {
4792 DPRINTF("OUCH! Not enough room, delta = %d", delta);
4796 numkeys = NUMKEYS(mp);
4797 for (i = 0; i < numkeys; i++) {
4798 if (mp->mp_ptrs[i] <= ptr)
4799 mp->mp_ptrs[i] -= delta;
4802 base = (char *)mp + mp->mp_upper;
4803 len = ptr - mp->mp_upper + NODESIZE;
4804 memmove(base - delta, base, len);
4805 mp->mp_upper -= delta;
4807 node = NODEPTR(mp, indx);
4808 node->mn_ksize = key->mv_size;
4811 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
4816 /** Move a node from csrc to cdst.
4819 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
4826 /* Mark src and dst as dirty. */
4827 if ((rc = mdb_page_touch(csrc)) ||
4828 (rc = mdb_page_touch(cdst)))
4831 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4832 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
4833 key.mv_size = csrc->mc_db->md_pad;
4834 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
4836 data.mv_data = NULL;
4838 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
4839 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
4840 unsigned int snum = csrc->mc_snum;
4842 /* must find the lowest key below src */
4843 mdb_page_search_root(csrc, NULL, 0);
4844 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
4845 key.mv_size = NODEKSZ(s2);
4846 key.mv_data = NODEKEY(s2);
4847 csrc->mc_snum = snum--;
4848 csrc->mc_top = snum;
4850 key.mv_size = NODEKSZ(srcnode);
4851 key.mv_data = NODEKEY(srcnode);
4853 data.mv_size = NODEDSZ(srcnode);
4854 data.mv_data = NODEDATA(srcnode);
4856 DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
4857 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
4858 csrc->mc_ki[csrc->mc_top],
4860 csrc->mc_pg[csrc->mc_top]->mp_pgno,
4861 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
4863 /* Add the node to the destination page.
4865 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, NODEPGNO(srcnode),
4867 if (rc != MDB_SUCCESS)
4870 /* Delete the node from the source page.
4872 mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
4875 /* Adjust other cursors pointing to mp */
4876 MDB_cursor *m2, *m3;
4877 MDB_dbi dbi = csrc->mc_dbi;
4878 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
4880 if (csrc->mc_flags & C_SUB)
4883 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
4884 if (m2 == csrc) continue;
4885 if (csrc->mc_flags & C_SUB)
4886 m3 = &m2->mc_xcursor->mx_cursor;
4889 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
4890 csrc->mc_ki[csrc->mc_top]) {
4891 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
4892 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
4897 /* Update the parent separators.
4899 if (csrc->mc_ki[csrc->mc_top] == 0) {
4900 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
4901 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4902 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
4904 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
4905 key.mv_size = NODEKSZ(srcnode);
4906 key.mv_data = NODEKEY(srcnode);
4908 DPRINTF("update separator for source page %zu to [%s]",
4909 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
4910 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1],
4911 &key)) != MDB_SUCCESS)
4914 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
4916 nullkey.mv_size = 0;
4917 rc = mdb_update_key(csrc->mc_pg[csrc->mc_top], 0, &nullkey);
4918 assert(rc == MDB_SUCCESS);
4922 if (cdst->mc_ki[cdst->mc_top] == 0) {
4923 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
4924 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4925 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
4927 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
4928 key.mv_size = NODEKSZ(srcnode);
4929 key.mv_data = NODEKEY(srcnode);
4931 DPRINTF("update separator for destination page %zu to [%s]",
4932 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
4933 if ((rc = mdb_update_key(cdst->mc_pg[cdst->mc_top-1], cdst->mc_ki[cdst->mc_top-1],
4934 &key)) != MDB_SUCCESS)
4937 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
4939 nullkey.mv_size = 0;
4940 rc = mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &nullkey);
4941 assert(rc == MDB_SUCCESS);
4948 /** Merge one page into another.
4949 * The nodes from the page pointed to by \b csrc will
4950 * be copied to the page pointed to by \b cdst and then
4951 * the \b csrc page will be freed.
4952 * @param[in] csrc Cursor pointing to the source page.
4953 * @param[in] cdst Cursor pointing to the destination page.
4956 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
4964 DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
4965 cdst->mc_pg[cdst->mc_top]->mp_pgno);
4967 assert(csrc->mc_snum > 1); /* can't merge root page */
4968 assert(cdst->mc_snum > 1);
4970 /* Mark dst as dirty. */
4971 if ((rc = mdb_page_touch(cdst)))
4974 /* Move all nodes from src to dst.
4976 j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
4977 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4978 key.mv_size = csrc->mc_db->md_pad;
4979 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
4980 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
4981 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
4982 if (rc != MDB_SUCCESS)
4984 key.mv_data = (char *)key.mv_data + key.mv_size;
4987 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
4988 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
4990 key.mv_size = srcnode->mn_ksize;
4991 key.mv_data = NODEKEY(srcnode);
4992 data.mv_size = NODEDSZ(srcnode);
4993 data.mv_data = NODEDATA(srcnode);
4994 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
4995 if (rc != MDB_SUCCESS)
5000 DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
5001 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);
5003 /* Unlink the src page from parent and add to free list.
5005 mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
5006 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
5008 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], 0, &key)) != MDB_SUCCESS)
5012 mdb_midl_append(&csrc->mc_txn->mt_free_pgs, csrc->mc_pg[csrc->mc_top]->mp_pgno);
5013 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
5014 csrc->mc_db->md_leaf_pages--;
5016 csrc->mc_db->md_branch_pages--;
5018 /* Adjust other cursors pointing to mp */
5019 MDB_cursor *m2, *m3;
5020 MDB_dbi dbi = csrc->mc_dbi;
5021 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
5023 if (csrc->mc_flags & C_SUB)
5026 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5027 if (m2 == csrc) continue;
5028 if (csrc->mc_flags & C_SUB)
5029 m3 = &m2->mc_xcursor->mx_cursor;
5032 if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
5033 m3->mc_pg[csrc->mc_top] = mp;
5034 m3->mc_ki[csrc->mc_top] += nkeys;
5038 mdb_cursor_pop(csrc);
5040 return mdb_rebalance(csrc);
5043 /** Copy the contents of a cursor.
5044 * @param[in] csrc The cursor to copy from.
5045 * @param[out] cdst The cursor to copy to.
5048 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
5052 cdst->mc_txn = csrc->mc_txn;
5053 cdst->mc_dbi = csrc->mc_dbi;
5054 cdst->mc_db = csrc->mc_db;
5055 cdst->mc_dbx = csrc->mc_dbx;
5056 cdst->mc_snum = csrc->mc_snum;
5057 cdst->mc_top = csrc->mc_top;
5058 cdst->mc_flags = csrc->mc_flags;
5060 for (i=0; i<csrc->mc_snum; i++) {
5061 cdst->mc_pg[i] = csrc->mc_pg[i];
5062 cdst->mc_ki[i] = csrc->mc_ki[i];
5066 /** Rebalance the tree after a delete operation.
5067 * @param[in] mc Cursor pointing to the page where rebalancing
5069 * @return 0 on success, non-zero on failure.
5072 mdb_rebalance(MDB_cursor *mc)
5079 DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
5080 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
5081 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);
5083 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD) {
5084 DPRINTF("no need to rebalance page %zu, above fill threshold",
5085 mc->mc_pg[mc->mc_top]->mp_pgno);
5089 if (mc->mc_snum < 2) {
5090 MDB_page *mp = mc->mc_pg[0];
5091 if (NUMKEYS(mp) == 0) {
5092 DPUTS("tree is completely empty");
5093 mc->mc_db->md_root = P_INVALID;
5094 mc->mc_db->md_depth = 0;
5095 mc->mc_db->md_leaf_pages = 0;
5096 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5100 /* Adjust other cursors pointing to mp */
5101 MDB_cursor *m2, *m3;
5102 MDB_dbi dbi = mc->mc_dbi;
5104 if (mc->mc_flags & C_SUB)
5107 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5108 if (m2 == mc) continue;
5109 if (mc->mc_flags & C_SUB)
5110 m3 = &m2->mc_xcursor->mx_cursor;
5113 if (m3->mc_pg[0] == mp) {
5119 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
5120 DPUTS("collapsing root page!");
5121 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5122 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
5123 if ((rc = mdb_page_get(mc->mc_txn, mc->mc_db->md_root,
5126 mc->mc_db->md_depth--;
5127 mc->mc_db->md_branch_pages--;
5129 /* Adjust other cursors pointing to mp */
5130 MDB_cursor *m2, *m3;
5131 MDB_dbi dbi = mc->mc_dbi;
5133 if (mc->mc_flags & C_SUB)
5136 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5137 if (m2 == mc) continue;
5138 if (mc->mc_flags & C_SUB)
5139 m3 = &m2->mc_xcursor->mx_cursor;
5142 if (m3->mc_pg[0] == mp) {
5143 m3->mc_pg[0] = mc->mc_pg[0];
5148 DPUTS("root page doesn't need rebalancing");
5152 /* The parent (branch page) must have at least 2 pointers,
5153 * otherwise the tree is invalid.
5155 ptop = mc->mc_top-1;
5156 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
5158 /* Leaf page fill factor is below the threshold.
5159 * Try to move keys from left or right neighbor, or
5160 * merge with a neighbor page.
5165 mdb_cursor_copy(mc, &mn);
5166 mn.mc_xcursor = NULL;
5168 if (mc->mc_ki[ptop] == 0) {
5169 /* We're the leftmost leaf in our parent.
5171 DPUTS("reading right neighbor");
5173 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5174 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5176 mn.mc_ki[mn.mc_top] = 0;
5177 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
5179 /* There is at least one neighbor to the left.
5181 DPUTS("reading left neighbor");
5183 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5184 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5186 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
5187 mc->mc_ki[mc->mc_top] = 0;
5190 DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
5191 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);
5193 /* If the neighbor page is above threshold and has at least two
5194 * keys, move one key from it.
5196 * Otherwise we should try to merge them.
5198 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) >= 2)
5199 return mdb_node_move(&mn, mc);
5200 else { /* FIXME: if (has_enough_room()) */
5201 mc->mc_flags &= ~C_INITIALIZED;
5202 if (mc->mc_ki[ptop] == 0)
5203 return mdb_page_merge(&mn, mc);
5205 return mdb_page_merge(mc, &mn);
5209 /** Complete a delete operation started by #mdb_cursor_del(). */
5211 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
5215 /* add overflow pages to free list */
5216 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5220 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
5221 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
5222 for (i=0; i<ovpages; i++) {
5223 DPRINTF("freed ov page %zu", pg);
5224 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
5228 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], mc->mc_db->md_pad);
5229 mc->mc_db->md_entries--;
5230 rc = mdb_rebalance(mc);
5231 if (rc != MDB_SUCCESS)
5232 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5238 mdb_del(MDB_txn *txn, MDB_dbi dbi,
5239 MDB_val *key, MDB_val *data)
5244 MDB_val rdata, *xdata;
5248 assert(key != NULL);
5250 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
5252 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5255 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
5259 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
5263 mdb_cursor_init(&mc, txn, dbi, &mx);
5274 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
5276 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
5280 /** Split a page and insert a new node.
5281 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
5282 * The cursor will be updated to point to the actual page and index where
5283 * the node got inserted after the split.
5284 * @param[in] newkey The key for the newly inserted node.
5285 * @param[in] newdata The data for the newly inserted node.
5286 * @param[in] newpgno The page number, if the new node is a branch node.
5287 * @return 0 on success, non-zero on failure.
5290 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
5291 unsigned int nflags)
5294 int rc = MDB_SUCCESS, ins_new = 0, new_root = 0;
5297 unsigned int i, j, split_indx, nkeys, pmax;
5299 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
5301 MDB_page *mp, *rp, *pp;
5306 mp = mc->mc_pg[mc->mc_top];
5307 newindx = mc->mc_ki[mc->mc_top];
5309 DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
5310 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
5311 DKEY(newkey), mc->mc_ki[mc->mc_top]);
5313 if (mc->mc_snum < 2) {
5314 if ((pp = mdb_page_new(mc, P_BRANCH, 1)) == NULL)
5316 /* shift current top to make room for new parent */
5317 mc->mc_pg[1] = mc->mc_pg[0];
5318 mc->mc_ki[1] = mc->mc_ki[0];
5321 mc->mc_db->md_root = pp->mp_pgno;
5322 DPRINTF("root split! new root = %zu", pp->mp_pgno);
5323 mc->mc_db->md_depth++;
5326 /* Add left (implicit) pointer. */
5327 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
5328 /* undo the pre-push */
5329 mc->mc_pg[0] = mc->mc_pg[1];
5330 mc->mc_ki[0] = mc->mc_ki[1];
5331 mc->mc_db->md_root = mp->mp_pgno;
5332 mc->mc_db->md_depth--;
5339 ptop = mc->mc_top-1;
5340 DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
5343 /* Create a right sibling. */
5344 if ((rp = mdb_page_new(mc, mp->mp_flags, 1)) == NULL)
5346 DPRINTF("new right sibling: page %zu", rp->mp_pgno);
5348 mdb_cursor_copy(mc, &mn);
5349 mn.mc_pg[mn.mc_top] = rp;
5350 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
5352 if (nflags & MDB_APPEND) {
5353 mn.mc_ki[mn.mc_top] = 0;
5360 nkeys = NUMKEYS(mp);
5361 split_indx = nkeys / 2 + 1;
5366 unsigned int lsize, rsize, ksize;
5367 /* Move half of the keys to the right sibling */
5369 x = mc->mc_ki[mc->mc_top] - split_indx;
5370 ksize = mc->mc_db->md_pad;
5371 split = LEAF2KEY(mp, split_indx, ksize);
5372 rsize = (nkeys - split_indx) * ksize;
5373 lsize = (nkeys - split_indx) * sizeof(indx_t);
5374 mp->mp_lower -= lsize;
5375 rp->mp_lower += lsize;
5376 mp->mp_upper += rsize - lsize;
5377 rp->mp_upper -= rsize - lsize;
5378 sepkey.mv_size = ksize;
5379 if (newindx == split_indx) {
5380 sepkey.mv_data = newkey->mv_data;
5382 sepkey.mv_data = split;
5385 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
5386 memcpy(rp->mp_ptrs, split, rsize);
5387 sepkey.mv_data = rp->mp_ptrs;
5388 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
5389 memcpy(ins, newkey->mv_data, ksize);
5390 mp->mp_lower += sizeof(indx_t);
5391 mp->mp_upper -= ksize - sizeof(indx_t);
5394 memcpy(rp->mp_ptrs, split, x * ksize);
5395 ins = LEAF2KEY(rp, x, ksize);
5396 memcpy(ins, newkey->mv_data, ksize);
5397 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
5398 rp->mp_lower += sizeof(indx_t);
5399 rp->mp_upper -= ksize - sizeof(indx_t);
5400 mc->mc_ki[mc->mc_top] = x;
5401 mc->mc_pg[mc->mc_top] = rp;
5406 /* For leaf pages, check the split point based on what
5407 * fits where, since otherwise add_node can fail.
5410 unsigned int psize, nsize;
5411 /* Maximum free space in an empty page */
5412 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
5413 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
5414 if (newindx < split_indx) {
5416 for (i=0; i<split_indx; i++) {
5417 node = NODEPTR(mp, i);
5418 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
5419 if (F_ISSET(node->mn_flags, F_BIGDATA))
5420 psize += sizeof(pgno_t);
5422 psize += NODEDSZ(node);
5431 for (i=nkeys-1; i>=split_indx; i--) {
5432 node = NODEPTR(mp, i);
5433 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
5434 if (F_ISSET(node->mn_flags, F_BIGDATA))
5435 psize += sizeof(pgno_t);
5437 psize += NODEDSZ(node);
5447 /* First find the separating key between the split pages.
5449 if (newindx == split_indx) {
5450 sepkey.mv_size = newkey->mv_size;
5451 sepkey.mv_data = newkey->mv_data;
5453 node = NODEPTR(mp, split_indx);
5454 sepkey.mv_size = node->mn_ksize;
5455 sepkey.mv_data = NODEKEY(node);
5459 DPRINTF("separator is [%s]", DKEY(&sepkey));
5461 /* Copy separator key to the parent.
5463 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
5466 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
5468 /* Right page might now have changed parent.
5469 * Check if left page also changed parent.
5471 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
5472 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
5473 mc->mc_pg[ptop] = mn.mc_pg[ptop];
5474 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
5478 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
5481 if (rc != MDB_SUCCESS) {
5484 if (nflags & MDB_APPEND) {
5485 mc->mc_pg[mc->mc_top] = rp;
5486 mc->mc_ki[mc->mc_top] = 0;
5487 return mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
5493 /* Move half of the keys to the right sibling. */
5495 /* grab a page to hold a temporary copy */
5496 copy = mdb_page_malloc(mc);
5500 copy->mp_pgno = mp->mp_pgno;
5501 copy->mp_flags = mp->mp_flags;
5502 copy->mp_lower = PAGEHDRSZ;
5503 copy->mp_upper = mc->mc_txn->mt_env->me_psize;
5504 mc->mc_pg[mc->mc_top] = copy;
5505 for (i = j = 0; i <= nkeys; j++) {
5506 if (i == split_indx) {
5507 /* Insert in right sibling. */
5508 /* Reset insert index for right sibling. */
5509 j = (i == newindx && ins_new);
5510 mc->mc_pg[mc->mc_top] = rp;
5513 if (i == newindx && !ins_new) {
5514 /* Insert the original entry that caused the split. */
5515 rkey.mv_data = newkey->mv_data;
5516 rkey.mv_size = newkey->mv_size;
5525 /* Update page and index for the new key. */
5526 mc->mc_ki[mc->mc_top] = j;
5527 } else if (i == nkeys) {
5530 node = NODEPTR(mp, i);
5531 rkey.mv_data = NODEKEY(node);
5532 rkey.mv_size = node->mn_ksize;
5534 xdata.mv_data = NODEDATA(node);
5535 xdata.mv_size = NODEDSZ(node);
5538 pgno = NODEPGNO(node);
5539 flags = node->mn_flags;
5544 if (!IS_LEAF(mp) && j == 0) {
5545 /* First branch index doesn't need key data. */
5549 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
5552 nkeys = NUMKEYS(copy);
5553 for (i=0; i<nkeys; i++)
5554 mp->mp_ptrs[i] = copy->mp_ptrs[i];
5555 mp->mp_lower = copy->mp_lower;
5556 mp->mp_upper = copy->mp_upper;
5557 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
5558 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
5560 /* reset back to original page */
5561 if (newindx < split_indx) {
5562 mc->mc_pg[mc->mc_top] = mp;
5563 if (nflags & MDB_RESERVE) {
5564 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5565 if (!(node->mn_flags & F_BIGDATA))
5566 newdata->mv_data = NODEDATA(node);
5570 /* return tmp page to freelist */
5571 copy->mp_next = mc->mc_txn->mt_env->me_dpages;
5572 mc->mc_txn->mt_env->me_dpages = copy;
5575 /* Adjust other cursors pointing to mp */
5576 MDB_cursor *m2, *m3;
5577 MDB_dbi dbi = mc->mc_dbi;
5579 if (mc->mc_flags & C_SUB)
5582 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5583 if (m2 == mc) continue;
5584 if (mc->mc_flags & C_SUB)
5585 m3 = &m2->mc_xcursor->mx_cursor;
5588 if (!(m3->mc_flags & C_INITIALIZED))
5592 for (i=m3->mc_top; i>0; i--) {
5593 m3->mc_ki[i+1] = m3->mc_ki[i];
5594 m3->mc_pg[i+1] = m3->mc_pg[i];
5596 m3->mc_ki[0] = mc->mc_ki[0];
5597 m3->mc_pg[0] = mc->mc_pg[0];
5601 if (m3->mc_pg[mc->mc_top] == mp) {
5602 if (m3->mc_ki[m3->mc_top] >= split_indx) {
5603 m3->mc_pg[m3->mc_top] = rp;
5604 m3->mc_ki[m3->mc_top] -= split_indx;
5613 mdb_put(MDB_txn *txn, MDB_dbi dbi,
5614 MDB_val *key, MDB_val *data, unsigned int flags)
5619 assert(key != NULL);
5620 assert(data != NULL);
5622 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5625 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
5629 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
5633 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND)) != flags)
5636 mdb_cursor_init(&mc, txn, dbi, &mx);
5637 return mdb_cursor_put(&mc, key, data, flags);
5640 /** Only a subset of the @ref mdb_env flags can be changed
5641 * at runtime. Changing other flags requires closing the environment
5642 * and re-opening it with the new flags.
5644 #define CHANGEABLE (MDB_NOSYNC)
5646 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
5648 if ((flag & CHANGEABLE) != flag)
5651 env->me_flags |= flag;
5653 env->me_flags &= ~flag;
5658 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
5663 *arg = env->me_flags;
5668 mdb_env_get_path(MDB_env *env, const char **arg)
5673 *arg = env->me_path;
5677 /** Common code for #mdb_stat() and #mdb_env_stat().
5678 * @param[in] env the environment to operate in.
5679 * @param[in] db the #MDB_db record containing the stats to return.
5680 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
5681 * @return 0, this function always succeeds.
5684 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
5686 arg->ms_psize = env->me_psize;
5687 arg->ms_depth = db->md_depth;
5688 arg->ms_branch_pages = db->md_branch_pages;
5689 arg->ms_leaf_pages = db->md_leaf_pages;
5690 arg->ms_overflow_pages = db->md_overflow_pages;
5691 arg->ms_entries = db->md_entries;
5696 mdb_env_stat(MDB_env *env, MDB_stat *arg)
5700 if (env == NULL || arg == NULL)
5703 mdb_env_read_meta(env, &toggle);
5705 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
5708 /** Set the default comparison functions for a database.
5709 * Called immediately after a database is opened to set the defaults.
5710 * The user can then override them with #mdb_set_compare() or
5711 * #mdb_set_dupsort().
5712 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
5713 * @param[in] dbi A database handle returned by #mdb_open()
5716 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
5718 if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEKEY)
5719 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memnr;
5720 else if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERKEY)
5721 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_cint;
5723 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memn;
5725 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
5726 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP) {
5727 if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED)
5728 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_int;
5730 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_cint;
5731 } else if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEDUP) {
5732 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memnr;
5734 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memn;
5737 txn->mt_dbxs[dbi].md_dcmp = NULL;
5741 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
5746 int rc, dbflag, exact;
5749 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
5750 mdb_default_cmp(txn, FREE_DBI);
5756 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
5757 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
5758 mdb_default_cmp(txn, MAIN_DBI);
5762 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
5763 mdb_default_cmp(txn, MAIN_DBI);
5766 /* Is the DB already open? */
5768 for (i=2; i<txn->mt_numdbs; i++) {
5769 if (len == txn->mt_dbxs[i].md_name.mv_size &&
5770 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
5776 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
5779 /* Find the DB info */
5783 key.mv_data = (void *)name;
5784 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
5785 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
5786 if (rc == MDB_SUCCESS) {
5787 /* make sure this is actually a DB */
5788 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
5789 if (!(node->mn_flags & F_SUBDATA))
5791 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
5792 /* Create if requested */
5794 data.mv_size = sizeof(MDB_db);
5795 data.mv_data = &dummy;
5796 memset(&dummy, 0, sizeof(dummy));
5797 dummy.md_root = P_INVALID;
5798 dummy.md_flags = flags & 0xffff;
5799 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
5803 /* OK, got info, add to table */
5804 if (rc == MDB_SUCCESS) {
5805 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
5806 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
5807 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
5808 txn->mt_dbflags[txn->mt_numdbs] = dbflag;
5809 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
5810 *dbi = txn->mt_numdbs;
5811 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
5812 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
5813 mdb_default_cmp(txn, txn->mt_numdbs);
5820 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
5822 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
5825 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
5828 void mdb_close(MDB_env *env, MDB_dbi dbi)
5831 if (dbi <= MAIN_DBI || dbi >= env->me_numdbs)
5833 ptr = env->me_dbxs[dbi].md_name.mv_data;
5834 env->me_dbxs[dbi].md_name.mv_data = NULL;
5835 env->me_dbxs[dbi].md_name.mv_size = 0;
5839 /** Add all the DB's pages to the free list.
5840 * @param[in] mc Cursor on the DB to free.
5841 * @param[in] subs non-Zero to check for sub-DBs in this DB.
5842 * @return 0 on success, non-zero on failure.
5845 mdb_drop0(MDB_cursor *mc, int subs)
5849 rc = mdb_page_search(mc, NULL, 0);
5850 if (rc == MDB_SUCCESS) {
5855 /* LEAF2 pages have no nodes, cannot have sub-DBs */
5856 if (!subs || IS_LEAF2(mc->mc_pg[mc->mc_top]))
5859 mdb_cursor_copy(mc, &mx);
5860 while (mc->mc_snum > 0) {
5861 if (IS_LEAF(mc->mc_pg[mc->mc_top])) {
5862 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
5863 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
5864 if (ni->mn_flags & F_SUBDATA) {
5865 mdb_xcursor_init1(mc, ni);
5866 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
5872 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
5874 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
5877 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
5882 rc = mdb_cursor_sibling(mc, 1);
5884 /* no more siblings, go back to beginning
5885 * of previous level. (stack was already popped
5886 * by mdb_cursor_sibling)
5888 for (i=1; i<mc->mc_top; i++)
5889 mc->mc_pg[i] = mx.mc_pg[i];
5893 mdb_midl_append(&mc->mc_txn->mt_free_pgs,
5894 mc->mc_db->md_root);
5899 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
5904 if (!txn || !dbi || dbi >= txn->mt_numdbs)
5907 rc = mdb_cursor_open(txn, dbi, &mc);
5911 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
5915 /* Can't delete the main DB */
5916 if (del && dbi > MAIN_DBI) {
5917 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
5919 mdb_close(txn->mt_env, dbi);
5921 txn->mt_dbflags[dbi] |= DB_DIRTY;
5922 txn->mt_dbs[dbi].md_depth = 0;
5923 txn->mt_dbs[dbi].md_branch_pages = 0;
5924 txn->mt_dbs[dbi].md_leaf_pages = 0;
5925 txn->mt_dbs[dbi].md_overflow_pages = 0;
5926 txn->mt_dbs[dbi].md_entries = 0;
5927 txn->mt_dbs[dbi].md_root = P_INVALID;
5930 mdb_cursor_close(mc);
5934 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
5936 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5939 txn->mt_dbxs[dbi].md_cmp = cmp;
5943 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
5945 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5948 txn->mt_dbxs[dbi].md_dcmp = cmp;
5952 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
5954 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5957 txn->mt_dbxs[dbi].md_rel = rel;
5961 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
5963 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5966 txn->mt_dbxs[dbi].md_relctx = ctx;