2 * @brief memory-mapped database library
4 * A Btree-based database management library modeled loosely on the
5 * BerkeleyDB API, but much simplified.
8 * Copyright 2011 Howard Chu, Symas Corp.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted only as authorized by the OpenLDAP
15 * A copy of this license is available in the file LICENSE in the
16 * top-level directory of the distribution or, alternatively, at
17 * <http://www.OpenLDAP.org/license.html>.
19 * This code is derived from btree.c written by Martin Hedenfalk.
21 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
23 * Permission to use, copy, modify, and distribute this software for any
24 * purpose with or without fee is hereby granted, provided that the above
25 * copyright notice and this permission notice appear in all copies.
27 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
28 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
29 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
30 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
31 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
32 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
33 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
35 #include <sys/types.h>
37 #include <sys/param.h>
43 #ifdef HAVE_SYS_FILE_H
63 #include <semaphore.h>
68 #define BYTE_ORDER __BYTE_ORDER
71 #define LITTLE_ENDIAN __LITTLE_ENDIAN
74 #define BIG_ENDIAN __BIG_ENDIAN
80 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
81 # error "Unknown or unsupported endianness (BYTE_ORDER)"
82 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
83 # error "Two's complement, reasonably sized integer types, please"
86 /** @defgroup internal MDB Internals
89 /** @defgroup compat Windows Compatibility Macros
90 * A bunch of macros to minimize the amount of platform-specific ifdefs
91 * needed throughout the rest of the code. When the features this library
92 * needs are similar enough to POSIX to be hidden in a one-or-two line
93 * replacement, this macro approach is used.
97 #define pthread_t DWORD
98 #define pthread_mutex_t HANDLE
99 #define pthread_key_t DWORD
100 #define pthread_self() GetCurrentThreadId()
101 #define pthread_key_create(x,y) (*(x) = TlsAlloc())
102 #define pthread_key_delete(x) TlsFree(x)
103 #define pthread_getspecific(x) TlsGetValue(x)
104 #define pthread_setspecific(x,y) TlsSetValue(x,y)
105 #define pthread_mutex_unlock(x) ReleaseMutex(x)
106 #define pthread_mutex_lock(x) WaitForSingleObject(x, INFINITE)
107 #define LOCK_MUTEX_R(env) pthread_mutex_lock((env)->me_rmutex)
108 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock((env)->me_rmutex)
109 #define LOCK_MUTEX_W(env) pthread_mutex_lock((env)->me_wmutex)
110 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock((env)->me_wmutex)
111 #define getpid() GetCurrentProcessId()
112 #define fdatasync(fd) (!FlushFileBuffers(fd))
113 #define ErrCode() GetLastError()
114 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
115 #define close(fd) CloseHandle(fd)
116 #define munmap(ptr,len) UnmapViewOfFile(ptr)
119 #define LOCK_MUTEX_R(env) sem_wait((env)->me_rmutex)
120 #define UNLOCK_MUTEX_R(env) sem_post((env)->me_rmutex)
121 #define LOCK_MUTEX_W(env) sem_wait((env)->me_wmutex)
122 #define UNLOCK_MUTEX_W(env) sem_post((env)->me_wmutex)
123 #define fdatasync(fd) fsync(fd)
125 /** Lock the reader mutex.
127 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
128 /** Unlock the reader mutex.
130 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
132 /** Lock the writer mutex.
133 * Only a single write transaction is allowed at a time. Other writers
134 * will block waiting for this mutex.
136 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
137 /** Unlock the writer mutex.
139 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
140 #endif /* __APPLE__ */
142 /** Get the error code for the last failed system function.
144 #define ErrCode() errno
146 /** An abstraction for a file handle.
147 * On POSIX systems file handles are small integers. On Windows
148 * they're opaque pointers.
152 /** A value for an invalid file handle.
153 * Mainly used to initialize file variables and signify that they are
156 #define INVALID_HANDLE_VALUE (-1)
158 /** Get the size of a memory page for the system.
159 * This is the basic size that the platform's memory manager uses, and is
160 * fundamental to the use of memory-mapped files.
162 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
165 #if defined(_WIN32) || defined(__APPLE__)
172 /** A flag for opening a file and requesting synchronous data writes.
173 * This is only used when writing a meta page. It's not strictly needed;
174 * we could just do a normal write and then immediately perform a flush.
175 * But if this flag is available it saves us an extra system call.
177 * @note If O_DSYNC is undefined but exists in /usr/include,
178 * preferably set some compiler flag to get the definition.
179 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
182 # define MDB_DSYNC O_DSYNC
186 /** A page number in the database.
187 * Note that 64 bit page numbers are overkill, since pages themselves
188 * already represent 12-13 bits of addressable memory, and the OS will
189 * always limit applications to a maximum of 63 bits of address space.
191 * @note In the #MDB_node structure, we only store 48 bits of this value,
192 * which thus limits us to only 60 bits of addressable data.
196 /** A transaction ID.
197 * See struct MDB_txn.mt_txnid for details.
201 /** @defgroup debug Debug Macros
205 /** Enable debug output.
206 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
207 * read from and written to the database (used for free space management).
212 #if !(__STDC_VERSION__ >= 199901L || defined(__GNUC__))
213 # define DPRINTF (void) /* Vararg macros may be unsupported */
215 /** Print a debug message with printf formatting. */
216 # define DPRINTF(fmt, ...) /**< Requires 2 or more args */ \
217 fprintf(stderr, "%s:%d " fmt "\n", __func__, __LINE__, __VA_ARGS__)
219 # define DPRINTF(fmt, ...) ((void) 0)
221 /** Print a debug string.
222 * The string is printed literally, with no format processing.
224 #define DPUTS(arg) DPRINTF("%s", arg)
227 /** A default memory page size.
228 * The actual size is platform-dependent, but we use this for
229 * boot-strapping. We probably should not be using this any more.
230 * The #GET_PAGESIZE() macro is used to get the actual size.
232 * Note that we don't currently support Huge pages. On Linux,
233 * regular data files cannot use Huge pages, and in general
234 * Huge pages aren't actually pageable. We rely on the OS
235 * demand-pager to read our data and page it out when memory
236 * pressure from other processes is high. So until OSs have
237 * actual paging support for Huge pages, they're not viable.
239 #define PAGESIZE 4096
241 /** The minimum number of keys required in a database page.
242 * Setting this to a larger value will place a smaller bound on the
243 * maximum size of a data item. Data items larger than this size will
244 * be pushed into overflow pages instead of being stored directly in
245 * the B-tree node. This value used to default to 4. With a page size
246 * of 4096 bytes that meant that any item larger than 1024 bytes would
247 * go into an overflow page. That also meant that on average 2-3KB of
248 * each overflow page was wasted space. The value cannot be lower than
249 * 2 because then there would no longer be a tree structure. With this
250 * value, items larger than 2KB will go into overflow pages, and on
251 * average only 1KB will be wasted.
253 #define MDB_MINKEYS 2
255 /** A stamp that identifies a file as an MDB file.
256 * There's nothing special about this value other than that it is easily
257 * recognizable, and it will reflect any byte order mismatches.
259 #define MDB_MAGIC 0xBEEFC0DE
261 /** The version number for a database's file format. */
262 #define MDB_VERSION 1
264 /** The maximum size of a key in the database.
265 * While data items have essentially unbounded size, we require that
266 * keys all fit onto a regular page. This limit could be raised a bit
267 * further if needed; to something just under #PAGESIZE / #MDB_MINKEYS.
269 #define MAXKEYSIZE 511
274 * This is used for printing a hex dump of a key's contents.
276 #define DKBUF char kbuf[(MAXKEYSIZE*2+1)]
277 /** Display a key in hex.
279 * Invoke a function to display a key in hex.
281 #define DKEY(x) mdb_dkey(x, kbuf)
283 #define DKBUF typedef int dummy_kbuf /* so we can put ';' after */
287 /** @defgroup lazylock Lazy Locking
288 * Macros for locks that are't actually needed.
289 * The DB view is always consistent because all writes are wrapped in
290 * the wmutex. Finer-grained locks aren't necessary.
294 /** Use lazy locking. I.e., don't lock these accesses at all. */
298 /** Grab the reader lock */
299 #define LAZY_MUTEX_LOCK(x)
300 /** Release the reader lock */
301 #define LAZY_MUTEX_UNLOCK(x)
302 /** Release the DB table reader/writer lock */
303 #define LAZY_RWLOCK_UNLOCK(x)
304 /** Grab the DB table write lock */
305 #define LAZY_RWLOCK_WRLOCK(x)
306 /** Grab the DB table read lock */
307 #define LAZY_RWLOCK_RDLOCK(x)
308 /** Declare the DB table rwlock. Should not be followed by ';'. */
309 #define LAZY_RWLOCK_DEF(x)
310 /** Initialize the DB table rwlock */
311 #define LAZY_RWLOCK_INIT(x,y)
312 /** Destroy the DB table rwlock */
313 #define LAZY_RWLOCK_DESTROY(x)
315 #define LAZY_MUTEX_LOCK(x) pthread_mutex_lock(x)
316 #define LAZY_MUTEX_UNLOCK(x) pthread_mutex_unlock(x)
317 #define LAZY_RWLOCK_UNLOCK(x) pthread_rwlock_unlock(x)
318 #define LAZY_RWLOCK_WRLOCK(x) pthread_rwlock_wrlock(x)
319 #define LAZY_RWLOCK_RDLOCK(x) pthread_rwlock_rdlock(x)
320 #define LAZY_RWLOCK_DEF(x) pthread_rwlock_t x;
321 #define LAZY_RWLOCK_INIT(x,y) pthread_rwlock_init(x,y)
322 #define LAZY_RWLOCK_DESTROY(x) pthread_rwlock_destroy(x)
326 /** An invalid page number.
327 * Mainly used to denote an empty tree.
329 #define P_INVALID (~0UL)
331 /** Test if a flag \b f is set in a flag word \b w. */
332 #define F_ISSET(w, f) (((w) & (f)) == (f))
334 /** Used for offsets within a single page.
335 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
338 typedef uint16_t indx_t;
340 /** Default size of memory map.
341 * This is certainly too small for any actual applications. Apps should always set
342 * the size explicitly using #mdb_env_set_mapsize().
344 #define DEFAULT_MAPSIZE 1048576
346 /** @defgroup readers Reader Lock Table
347 * Readers don't acquire any locks for their data access. Instead, they
348 * simply record their transaction ID in the reader table. The reader
349 * mutex is needed just to find an empty slot in the reader table. The
350 * slot's address is saved in thread-specific data so that subsequent read
351 * transactions started by the same thread need no further locking to proceed.
353 * Since the database uses multi-version concurrency control, readers don't
354 * actually need any locking. This table is used to keep track of which
355 * readers are using data from which old transactions, so that we'll know
356 * when a particular old transaction is no longer in use. Old transactions
357 * that have discarded any data pages can then have those pages reclaimed
358 * for use by a later write transaction.
360 * The lock table is constructed such that reader slots are aligned with the
361 * processor's cache line size. Any slot is only ever used by one thread.
362 * This alignment guarantees that there will be no contention or cache
363 * thrashing as threads update their own slot info, and also eliminates
364 * any need for locking when accessing a slot.
366 * A writer thread will scan every slot in the table to determine the oldest
367 * outstanding reader transaction. Any freed pages older than this will be
368 * reclaimed by the writer. The writer doesn't use any locks when scanning
369 * this table. This means that there's no guarantee that the writer will
370 * see the most up-to-date reader info, but that's not required for correct
371 * operation - all we need is to know the upper bound on the oldest reader,
372 * we don't care at all about the newest reader. So the only consequence of
373 * reading stale information here is that old pages might hang around a
374 * while longer before being reclaimed. That's actually good anyway, because
375 * the longer we delay reclaiming old pages, the more likely it is that a
376 * string of contiguous pages can be found after coalescing old pages from
377 * many old transactions together.
379 * @todo We don't actually do such coalescing yet, we grab pages from one
380 * old transaction at a time.
383 /** Number of slots in the reader table.
384 * This value was chosen somewhat arbitrarily. 126 readers plus a
385 * couple mutexes fit exactly into 8KB on my development machine.
386 * Applications should set the table size using #mdb_env_set_maxreaders().
388 #define DEFAULT_READERS 126
390 /** The size of a CPU cache line in bytes. We want our lock structures
391 * aligned to this size to avoid false cache line sharing in the
393 * This value works for most CPUs. For Itanium this should be 128.
399 /** The information we store in a single slot of the reader table.
400 * In addition to a transaction ID, we also record the process and
401 * thread ID that owns a slot, so that we can detect stale information,
402 * e.g. threads or processes that went away without cleaning up.
403 * @note We currently don't check for stale records. We simply re-init
404 * the table when we know that we're the only process opening the
407 typedef struct MDB_rxbody {
408 /** The current Transaction ID when this transaction began.
409 * Multiple readers that start at the same time will probably have the
410 * same ID here. Again, it's not important to exclude them from
411 * anything; all we need to know is which version of the DB they
412 * started from so we can avoid overwriting any data used in that
413 * particular version.
416 /** The process ID of the process owning this reader txn. */
418 /** The thread ID of the thread owning this txn. */
422 /** The actual reader record, with cacheline padding. */
423 typedef struct MDB_reader {
426 /** shorthand for mrb_txnid */
427 #define mr_txnid mru.mrx.mrb_txnid
428 #define mr_pid mru.mrx.mrb_pid
429 #define mr_tid mru.mrx.mrb_tid
430 /** cache line alignment */
431 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
435 /** The header for the reader table.
436 * The table resides in a memory-mapped file. (This is a different file
437 * than is used for the main database.)
439 * For POSIX the actual mutexes reside in the shared memory of this
440 * mapped file. On Windows, mutexes are named objects allocated by the
441 * kernel; we store the mutex names in this mapped file so that other
442 * processes can grab them. This same approach will also be used on
443 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
444 * process-shared POSIX mutexes.
446 typedef struct MDB_txbody {
447 /** Stamp identifying this as an MDB lock file. It must be set
450 /** Version number of this lock file. Must be set to #MDB_VERSION. */
451 uint32_t mtb_version;
452 #if defined(_WIN32) || defined(__APPLE__)
453 char mtb_rmname[MNAME_LEN];
455 /** Mutex protecting access to this table.
456 * This is the reader lock that #LOCK_MUTEX_R acquires.
458 pthread_mutex_t mtb_mutex;
460 /** The ID of the last transaction committed to the database.
461 * This is recorded here only for convenience; the value can always
462 * be determined by reading the main database meta pages.
465 /** The number of slots that have been used in the reader table.
466 * This always records the maximum count, it is not decremented
467 * when readers release their slots.
469 unsigned mtb_numreaders;
470 /** The ID of the most recent meta page in the database.
471 * This is recorded here only for convenience; the value can always
472 * be determined by reading the main database meta pages.
474 uint32_t mtb_me_toggle;
477 /** The actual reader table definition. */
478 typedef struct MDB_txninfo {
481 #define mti_magic mt1.mtb.mtb_magic
482 #define mti_version mt1.mtb.mtb_version
483 #define mti_mutex mt1.mtb.mtb_mutex
484 #define mti_rmname mt1.mtb.mtb_rmname
485 #define mti_txnid mt1.mtb.mtb_txnid
486 #define mti_numreaders mt1.mtb.mtb_numreaders
487 #define mti_me_toggle mt1.mtb.mtb_me_toggle
488 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
491 #if defined(_WIN32) || defined(__APPLE__)
492 char mt2_wmname[MNAME_LEN];
493 #define mti_wmname mt2.mt2_wmname
495 pthread_mutex_t mt2_wmutex;
496 #define mti_wmutex mt2.mt2_wmutex
498 char pad[(sizeof(pthread_mutex_t)+CACHELINE-1) & ~(CACHELINE-1)];
500 MDB_reader mti_readers[1];
504 /** Common header for all page types.
505 * Overflow records occupy a number of contiguous pages with no
506 * headers on any page after the first.
508 typedef struct MDB_page {
509 #define mp_pgno mp_p.p_pgno
510 #define mp_next mp_p.p_next
512 pgno_t p_pgno; /**< page number */
513 void * p_next; /**< for in-memory list of freed structs */
516 /** @defgroup mdb_page Page Flags
518 * Flags for the page headers.
521 #define P_BRANCH 0x01 /**< branch page */
522 #define P_LEAF 0x02 /**< leaf page */
523 #define P_OVERFLOW 0x04 /**< overflow page */
524 #define P_META 0x08 /**< meta page */
525 #define P_DIRTY 0x10 /**< dirty page */
526 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
527 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
529 uint16_t mp_flags; /**< @ref mdb_page */
530 #define mp_lower mp_pb.pb.pb_lower
531 #define mp_upper mp_pb.pb.pb_upper
532 #define mp_pages mp_pb.pb_pages
535 indx_t pb_lower; /**< lower bound of free space */
536 indx_t pb_upper; /**< upper bound of free space */
538 uint32_t pb_pages; /**< number of overflow pages */
540 indx_t mp_ptrs[1]; /**< dynamic size */
543 /** Size of the page header, excluding dynamic data at the end */
544 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
546 /** Address of first usable data byte in a page, after the header */
547 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
549 /** Number of nodes on a page */
550 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
552 /** The amount of space remaining in the page */
553 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
555 /** The percentage of space used in the page, in tenths of a percent. */
556 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
557 ((env)->me_psize - PAGEHDRSZ))
558 /** The minimum page fill factor, in tenths of a percent.
559 * Pages emptier than this are candidates for merging.
561 #define FILL_THRESHOLD 250
563 /** Test if a page is a leaf page */
564 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
565 /** Test if a page is a LEAF2 page */
566 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
567 /** Test if a page is a branch page */
568 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
569 /** Test if a page is an overflow page */
570 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
571 /** Test if a page is a sub page */
572 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
574 /** The number of overflow pages needed to store the given size. */
575 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
577 /** Header for a single key/data pair within a page.
578 * We guarantee 2-byte alignment for nodes.
580 typedef struct MDB_node {
581 /** lo and hi are used for data size on leaf nodes and for
582 * child pgno on branch nodes. On 64 bit platforms, flags
583 * is also used for pgno. (Branch nodes have no flags).
584 * They are in host byte order in case that lets some
585 * accesses be optimized into a 32-bit word access.
587 #define mn_lo mn_offset[BYTE_ORDER!=LITTLE_ENDIAN]
588 #define mn_hi mn_offset[BYTE_ORDER==LITTLE_ENDIAN] /**< part of dsize or pgno */
589 unsigned short mn_offset[2]; /**< storage for #mn_lo and #mn_hi */
590 /** @defgroup mdb_node Node Flags
592 * Flags for node headers.
595 #define F_BIGDATA 0x01 /**< data put on overflow page */
596 #define F_SUBDATA 0x02 /**< data is a sub-database */
597 #define F_DUPDATA 0x04 /**< data has duplicates */
599 unsigned short mn_flags; /**< @ref mdb_node */
600 unsigned short mn_ksize; /**< key size */
601 char mn_data[1]; /**< key and data are appended here */
604 /** Size of the node header, excluding dynamic data at the end */
605 #define NODESIZE offsetof(MDB_node, mn_data)
607 /** Bit position of top word in page number, for shifting mn_flags */
608 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
610 /** Size of a node in a branch page with a given key.
611 * This is just the node header plus the key, there is no data.
613 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
615 /** Size of a node in a leaf page with a given key and data.
616 * This is node header plus key plus data size.
618 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
620 /** Address of node \b i in page \b p */
621 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
623 /** Address of the key for the node */
624 #define NODEKEY(node) (void *)((node)->mn_data)
626 /** Address of the data for a node */
627 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
629 /** Get the page number pointed to by a branch node */
630 #define NODEPGNO(node) \
631 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
632 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
633 /** Set the page number in a branch node */
634 #define SETPGNO(node,pgno) do { \
635 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
636 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
638 /** Get the size of the data in a leaf node */
639 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
640 /** Set the size of the data for a leaf node */
641 #define SETDSZ(node,size) do { \
642 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
643 /** The size of a key in a node */
644 #define NODEKSZ(node) ((node)->mn_ksize)
646 /** The address of a key in a LEAF2 page.
647 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
648 * There are no node headers, keys are stored contiguously.
650 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
652 /** Set the \b node's key into \b key, if requested. */
653 #define MDB_SET_KEY(node, key) { if ((key) != NULL) { \
654 (key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node); } }
656 /** Information about a single database in the environment. */
657 typedef struct MDB_db {
658 uint32_t md_pad; /**< also ksize for LEAF2 pages */
659 uint16_t md_flags; /**< @ref mdb_open */
660 uint16_t md_depth; /**< depth of this tree */
661 pgno_t md_branch_pages; /**< number of internal pages */
662 pgno_t md_leaf_pages; /**< number of leaf pages */
663 pgno_t md_overflow_pages; /**< number of overflow pages */
664 size_t md_entries; /**< number of data items */
665 pgno_t md_root; /**< the root page of this tree */
668 /** Handle for the DB used to track free pages. */
670 /** Handle for the default DB. */
673 /** Meta page content. */
674 typedef struct MDB_meta {
675 /** Stamp identifying this as an MDB data file. It must be set
678 /** Version number of this lock file. Must be set to #MDB_VERSION. */
680 void *mm_address; /**< address for fixed mapping */
681 size_t mm_mapsize; /**< size of mmap region */
682 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
683 /** The size of pages used in this DB */
684 #define mm_psize mm_dbs[0].md_pad
685 /** Any persistent environment flags. @ref mdb_env */
686 #define mm_flags mm_dbs[0].md_flags
687 pgno_t mm_last_pg; /**< last used page in file */
688 txnid_t mm_txnid; /**< txnid that committed this page */
691 /** Auxiliary DB info.
692 * The information here is mostly static/read-only. There is
693 * only a single copy of this record in the environment.
695 typedef struct MDB_dbx {
696 MDB_val md_name; /**< name of the database */
697 MDB_cmp_func *md_cmp; /**< function for comparing keys */
698 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
699 MDB_rel_func *md_rel; /**< user relocate function */
700 void *md_relctx; /**< user-provided context for md_rel */
703 /** A database transaction.
704 * Every operation requires a transaction handle.
707 MDB_txn *mt_parent; /**< parent of a nested txn */
708 MDB_txn *mt_child; /**< nested txn under this txn */
709 pgno_t mt_next_pgno; /**< next unallocated page */
710 /** The ID of this transaction. IDs are integers incrementing from 1.
711 * Only committed write transactions increment the ID. If a transaction
712 * aborts, the ID may be re-used by the next writer.
715 MDB_env *mt_env; /**< the DB environment */
716 /** The list of pages that became unused during this transaction.
720 ID2L dirty_list; /**< modified pages */
721 MDB_reader *reader; /**< this thread's slot in the reader table */
723 /** Array of records for each DB known in the environment. */
725 /** Array of MDB_db records for each known DB */
727 /** @defgroup mt_dbflag Transaction DB Flags
731 #define DB_DIRTY 0x01 /**< DB was written in this txn */
732 #define DB_STALE 0x02 /**< DB record is older than txnID */
734 /** Array of cursors for each DB */
735 MDB_cursor **mt_cursors;
736 /** Array of flags for each DB */
737 unsigned char *mt_dbflags;
738 /** Number of DB records in use. This number only ever increments;
739 * we don't decrement it when individual DB handles are closed.
743 /** @defgroup mdb_txn Transaction Flags
747 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
748 #define MDB_TXN_ERROR 0x02 /**< an error has occurred */
750 unsigned int mt_flags; /**< @ref mdb_txn */
751 /** Tracks which of the two meta pages was used at the start
752 * of this transaction.
754 unsigned int mt_toggle;
757 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
758 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
759 * raise this on a 64 bit machine.
761 #define CURSOR_STACK 32
765 /** Cursors are used for all DB operations */
767 /** Next cursor on this DB in this txn */
769 /** Original cursor if this is a shadow */
771 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
772 struct MDB_xcursor *mc_xcursor;
773 /** The transaction that owns this cursor */
775 /** The database handle this cursor operates on */
777 /** The database record for this cursor */
779 /** The database auxiliary record for this cursor */
781 /** The @ref mt_dbflag for this database */
782 unsigned char *mc_dbflag;
783 unsigned short mc_snum; /**< number of pushed pages */
784 unsigned short mc_top; /**< index of top page, mc_snum-1 */
785 /** @defgroup mdb_cursor Cursor Flags
787 * Cursor state flags.
790 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
791 #define C_EOF 0x02 /**< No more data */
792 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
793 #define C_SHADOW 0x08 /**< Cursor is a dup from a parent txn */
795 unsigned int mc_flags; /**< @ref mdb_cursor */
796 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
797 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
800 /** Context for sorted-dup records.
801 * We could have gone to a fully recursive design, with arbitrarily
802 * deep nesting of sub-databases. But for now we only handle these
803 * levels - main DB, optional sub-DB, sorted-duplicate DB.
805 typedef struct MDB_xcursor {
806 /** A sub-cursor for traversing the Dup DB */
807 MDB_cursor mx_cursor;
808 /** The database record for this Dup DB */
810 /** The auxiliary DB record for this Dup DB */
812 /** The @ref mt_dbflag for this Dup DB */
813 unsigned char mx_dbflag;
816 /** A set of pages freed by an earlier transaction. */
817 typedef struct MDB_oldpages {
818 /** Usually we only read one record from the FREEDB at a time, but
819 * in case we read more, this will chain them together.
821 struct MDB_oldpages *mo_next;
822 /** The ID of the transaction in which these pages were freed. */
824 /** An #IDL of the pages */
825 pgno_t mo_pages[1]; /* dynamic */
828 /** The database environment. */
830 HANDLE me_fd; /**< The main data file */
831 HANDLE me_lfd; /**< The lock file */
832 HANDLE me_mfd; /**< just for writing the meta pages */
833 /** Failed to update the meta page. Probably an I/O error. */
834 #define MDB_FATAL_ERROR 0x80000000U
835 uint32_t me_flags; /**< @ref mdb_env */
836 uint32_t me_extrapad; /**< unused for now */
837 unsigned int me_maxreaders; /**< size of the reader table */
838 MDB_dbi me_numdbs; /**< number of DBs opened */
839 MDB_dbi me_maxdbs; /**< size of the DB table */
840 char *me_path; /**< path to the DB files */
841 char *me_map; /**< the memory map of the data file */
842 MDB_txninfo *me_txns; /**< the memory map of the lock file */
843 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
844 MDB_txn *me_txn; /**< current write transaction */
845 size_t me_mapsize; /**< size of the data memory map */
846 off_t me_size; /**< current file size */
847 pgno_t me_maxpg; /**< me_mapsize / me_psize */
848 unsigned int me_psize; /**< size of a page, from #GET_PAGESIZE */
849 unsigned int me_db_toggle; /**< which DB table is current */
850 txnid_t me_wtxnid; /**< ID of last txn we committed */
851 MDB_dbx *me_dbxs; /**< array of static DB info */
852 MDB_db *me_dbs[2]; /**< two arrays of MDB_db info */
853 MDB_oldpages *me_pghead; /**< list of old page records */
854 pthread_key_t me_txkey; /**< thread-key for readers */
855 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
856 /** IDL of pages that became unused in a write txn */
858 /** ID2L of pages that were written during a write txn */
859 ID2 me_dirty_list[MDB_IDL_UM_SIZE];
860 /** rwlock for the DB tables, if #LAZY_LOCKS is false */
861 LAZY_RWLOCK_DEF(me_dblock)
863 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
867 sem_t *me_rmutex; /* Apple doesn't support shared mutexes */
871 /** max number of pages to commit in one writev() call */
872 #define MDB_COMMIT_PAGES 64
874 static MDB_page *mdb_page_alloc(MDB_cursor *mc, int num);
875 static MDB_page *mdb_page_new(MDB_cursor *mc, uint32_t flags, int num);
876 static int mdb_page_touch(MDB_cursor *mc);
878 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
879 static int mdb_page_search_root(MDB_cursor *mc,
880 MDB_val *key, int modify);
881 static int mdb_page_search(MDB_cursor *mc,
882 MDB_val *key, int modify);
883 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
884 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
887 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
888 static int mdb_env_read_meta(MDB_env *env, int *which);
889 static int mdb_env_write_meta(MDB_txn *txn);
891 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
892 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
893 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags);
894 static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
895 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
896 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
897 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
898 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
899 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
901 static int mdb_rebalance(MDB_cursor *mc);
902 static int mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
904 static void mdb_cursor_pop(MDB_cursor *mc);
905 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
907 static int mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
908 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
909 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
910 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
911 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
913 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
914 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
916 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
917 static void mdb_xcursor_init0(MDB_cursor *mc);
918 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
920 static int mdb_drop0(MDB_cursor *mc, int subs);
921 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
924 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
928 static SECURITY_DESCRIPTOR mdb_null_sd;
929 static SECURITY_ATTRIBUTES mdb_all_sa;
930 static int mdb_sec_inited;
933 /** Return the library version info. */
935 mdb_version(int *major, int *minor, int *patch)
937 if (major) *major = MDB_VERSION_MAJOR;
938 if (minor) *minor = MDB_VERSION_MINOR;
939 if (patch) *patch = MDB_VERSION_PATCH;
940 return MDB_VERSION_STRING;
943 /** Table of descriptions for MDB @ref errors */
944 static char *const mdb_errstr[] = {
945 "MDB_KEYEXIST: Key/data pair already exists",
946 "MDB_NOTFOUND: No matching key/data pair found",
947 "MDB_PAGE_NOTFOUND: Requested page not found",
948 "MDB_CORRUPTED: Located page was wrong type",
949 "MDB_PANIC: Update of meta page failed",
950 "MDB_VERSION_MISMATCH: Database environment version mismatch"
954 mdb_strerror(int err)
957 return ("Successful return: 0");
959 if (err >= MDB_KEYEXIST && err <= MDB_VERSION_MISMATCH)
960 return mdb_errstr[err - MDB_KEYEXIST];
962 return strerror(err);
966 /** Display a key in hexadecimal and return the address of the result.
967 * @param[in] key the key to display
968 * @param[in] buf the buffer to write into. Should always be #DKBUF.
969 * @return The key in hexadecimal form.
972 mdb_dkey(MDB_val *key, char *buf)
975 unsigned char *c = key->mv_data;
977 if (key->mv_size > MAXKEYSIZE)
979 /* may want to make this a dynamic check: if the key is mostly
980 * printable characters, print it as-is instead of converting to hex.
983 for (i=0; i<key->mv_size; i++)
984 ptr += sprintf(ptr, "%02x", *c++);
986 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
993 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
995 return txn->mt_dbxs[dbi].md_cmp(a, b);
999 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1001 if (txn->mt_dbxs[dbi].md_dcmp)
1002 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1004 return EINVAL; /* too bad you can't distinguish this from a valid result */
1007 /** Allocate a single page.
1008 * Re-use old malloc'd pages first, otherwise just malloc.
1011 mdb_page_malloc(MDB_cursor *mc) {
1013 if (mc->mc_txn->mt_env->me_dpages) {
1014 ret = mc->mc_txn->mt_env->me_dpages;
1015 mc->mc_txn->mt_env->me_dpages = ret->mp_next;
1017 ret = malloc(mc->mc_txn->mt_env->me_psize);
1022 /** Allocate pages for writing.
1023 * If there are free pages available from older transactions, they
1024 * will be re-used first. Otherwise a new page will be allocated.
1025 * @param[in] mc cursor A cursor handle identifying the transaction and
1026 * database for which we are allocating.
1027 * @param[in] num the number of pages to allocate.
1028 * @return Address of the allocated page(s). Requests for multiple pages
1029 * will always be satisfied by a single contiguous chunk of memory.
1032 mdb_page_alloc(MDB_cursor *mc, int num)
1034 MDB_txn *txn = mc->mc_txn;
1036 pgno_t pgno = P_INVALID;
1039 if (txn->mt_txnid > 2) {
1041 if (!txn->mt_env->me_pghead && mc->mc_dbi != FREE_DBI &&
1042 txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
1043 /* See if there's anything in the free DB */
1046 txnid_t *kptr, oldest;
1048 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1049 mdb_page_search(&m2, NULL, 0);
1050 leaf = NODEPTR(m2.mc_pg[m2.mc_top], 0);
1051 kptr = (txnid_t *)NODEKEY(leaf);
1055 oldest = txn->mt_txnid - 1;
1056 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
1057 txnid_t mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
1058 if (mr && mr < oldest)
1063 if (oldest > *kptr) {
1064 /* It's usable, grab it.
1070 mdb_node_read(txn, leaf, &data);
1071 idl = (ID *) data.mv_data;
1072 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
1073 mop->mo_next = txn->mt_env->me_pghead;
1074 mop->mo_txnid = *kptr;
1075 txn->mt_env->me_pghead = mop;
1076 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
1081 DPRINTF("IDL read txn %zu root %zu num %zu",
1082 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1083 for (i=0; i<idl[0]; i++) {
1084 DPRINTF("IDL %zu", idl[i+1]);
1088 /* drop this IDL from the DB */
1089 m2.mc_ki[m2.mc_top] = 0;
1090 m2.mc_flags = C_INITIALIZED;
1091 mdb_cursor_del(&m2, 0);
1094 if (txn->mt_env->me_pghead) {
1095 MDB_oldpages *mop = txn->mt_env->me_pghead;
1097 /* FIXME: For now, always use fresh pages. We
1098 * really ought to search the free list for a
1103 /* peel pages off tail, so we only have to truncate the list */
1104 pgno = MDB_IDL_LAST(mop->mo_pages);
1105 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
1107 if (mop->mo_pages[2] > mop->mo_pages[1])
1108 mop->mo_pages[0] = 0;
1112 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
1113 txn->mt_env->me_pghead = mop->mo_next;
1120 if (pgno == P_INVALID) {
1121 /* DB size is maxed out */
1122 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg) {
1123 assert(txn->mt_next_pgno + num < txn->mt_env->me_maxpg);
1127 if (txn->mt_env->me_dpages && num == 1) {
1128 np = txn->mt_env->me_dpages;
1129 txn->mt_env->me_dpages = np->mp_next;
1131 if ((np = malloc(txn->mt_env->me_psize * num )) == NULL)
1134 if (pgno == P_INVALID) {
1135 np->mp_pgno = txn->mt_next_pgno;
1136 txn->mt_next_pgno += num;
1140 mid.mid = np->mp_pgno;
1142 mdb_mid2l_insert(txn->mt_u.dirty_list, &mid);
1147 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1148 * @param[in] mc cursor pointing to the page to be touched
1149 * @return 0 on success, non-zero on failure.
1152 mdb_page_touch(MDB_cursor *mc)
1154 MDB_page *mp = mc->mc_pg[mc->mc_top];
1157 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1159 if ((np = mdb_page_alloc(mc, 1)) == NULL)
1161 DPRINTF("touched db %u page %zu -> %zu", mc->mc_dbi, mp->mp_pgno, np->mp_pgno);
1162 assert(mp->mp_pgno != np->mp_pgno);
1163 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
1165 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1168 mp->mp_flags |= P_DIRTY;
1171 /* Adjust other cursors pointing to mp */
1172 if (mc->mc_flags & C_SUB) {
1173 MDB_cursor *m2, *m3;
1174 MDB_dbi dbi = mc->mc_dbi-1;
1176 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
1177 m3 = &m2->mc_xcursor->mx_cursor;
1178 if (m3->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1179 m3->mc_pg[mc->mc_top] = mp;
1185 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
1186 if (m2->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1187 m2->mc_pg[mc->mc_top] = mp;
1191 mc->mc_pg[mc->mc_top] = mp;
1192 /** If this page has a parent, update the parent to point to
1196 SETPGNO(NODEPTR(mc->mc_pg[mc->mc_top-1], mc->mc_ki[mc->mc_top-1]), mp->mp_pgno);
1198 mc->mc_db->md_root = mp->mp_pgno;
1199 } else if (mc->mc_txn->mt_parent) {
1202 /* If txn has a parent, make sure the page is in our
1205 if (mc->mc_txn->mt_u.dirty_list[0].mid) {
1206 unsigned x = mdb_mid2l_search(mc->mc_txn->mt_u.dirty_list, mp->mp_pgno);
1207 if (x <= mc->mc_txn->mt_u.dirty_list[0].mid &&
1208 mc->mc_txn->mt_u.dirty_list[x].mid == mp->mp_pgno) {
1209 if (mc->mc_txn->mt_u.dirty_list[x].mptr != mp) {
1210 mp = mc->mc_txn->mt_u.dirty_list[x].mptr;
1211 mc->mc_pg[mc->mc_top] = mp;
1217 np = mdb_page_malloc(mc);
1218 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1219 mid.mid = np->mp_pgno;
1221 mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &mid);
1229 mdb_env_sync(MDB_env *env, int force)
1232 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1233 if (fdatasync(env->me_fd))
1239 /** Make shadow copies of all of parent txn's cursors */
1241 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
1243 MDB_cursor *mc, *m2;
1244 unsigned int i, j, size;
1246 for (i=0;i<src->mt_numdbs; i++) {
1247 if (src->mt_cursors[i]) {
1248 size = sizeof(MDB_cursor);
1249 if (src->mt_cursors[i]->mc_xcursor)
1250 size += sizeof(MDB_xcursor);
1251 for (m2 = src->mt_cursors[i]; m2; m2=m2->mc_next) {
1258 mc->mc_db = &dst->mt_dbs[i];
1259 mc->mc_dbx = m2->mc_dbx;
1260 mc->mc_dbflag = &dst->mt_dbflags[i];
1261 mc->mc_snum = m2->mc_snum;
1262 mc->mc_top = m2->mc_top;
1263 mc->mc_flags = m2->mc_flags | C_SHADOW;
1264 for (j=0; j<mc->mc_snum; j++) {
1265 mc->mc_pg[j] = m2->mc_pg[j];
1266 mc->mc_ki[j] = m2->mc_ki[j];
1268 if (m2->mc_xcursor) {
1269 MDB_xcursor *mx, *mx2;
1270 mx = (MDB_xcursor *)(mc+1);
1271 mc->mc_xcursor = mx;
1272 mx2 = m2->mc_xcursor;
1273 mx->mx_db = mx2->mx_db;
1274 mx->mx_dbx = mx2->mx_dbx;
1275 mx->mx_dbflag = mx2->mx_dbflag;
1276 mx->mx_cursor.mc_txn = dst;
1277 mx->mx_cursor.mc_dbi = mx2->mx_cursor.mc_dbi;
1278 mx->mx_cursor.mc_db = &mx->mx_db;
1279 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
1280 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
1281 mx->mx_cursor.mc_snum = mx2->mx_cursor.mc_snum;
1282 mx->mx_cursor.mc_top = mx2->mx_cursor.mc_top;
1283 mx->mx_cursor.mc_flags = mx2->mx_cursor.mc_flags | C_SHADOW;
1284 for (j=0; j<mx2->mx_cursor.mc_snum; j++) {
1285 mx->mx_cursor.mc_pg[j] = mx2->mx_cursor.mc_pg[j];
1286 mx->mx_cursor.mc_ki[j] = mx2->mx_cursor.mc_ki[j];
1289 mc->mc_xcursor = NULL;
1291 mc->mc_next = dst->mt_cursors[i];
1292 dst->mt_cursors[i] = mc;
1299 /** Merge shadow cursors back into parent's */
1301 mdb_cursor_merge(MDB_txn *txn)
1304 for (i=0; i<txn->mt_numdbs; i++) {
1305 if (txn->mt_cursors[i]) {
1307 while ((mc = txn->mt_cursors[i])) {
1308 txn->mt_cursors[i] = mc->mc_next;
1309 if (mc->mc_flags & C_SHADOW) {
1310 MDB_cursor *m2 = mc->mc_orig;
1312 m2->mc_snum = mc->mc_snum;
1313 m2->mc_top = mc->mc_top;
1314 for (j=0; j<mc->mc_snum; j++) {
1315 m2->mc_pg[j] = mc->mc_pg[j];
1316 m2->mc_ki[j] = mc->mc_ki[j];
1326 mdb_txn_reset0(MDB_txn *txn);
1328 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
1329 * @param[in] txn the transaction handle to initialize
1330 * @return 0 on success, non-zero on failure. This can only
1331 * fail for read-only transactions, and then only if the
1332 * reader table is full.
1335 mdb_txn_renew0(MDB_txn *txn)
1337 MDB_env *env = txn->mt_env;
1340 if (txn->mt_flags & MDB_TXN_RDONLY) {
1341 MDB_reader *r = pthread_getspecific(env->me_txkey);
1344 pid_t pid = getpid();
1345 pthread_t tid = pthread_self();
1348 for (i=0; i<env->me_txns->mti_numreaders; i++)
1349 if (env->me_txns->mti_readers[i].mr_pid == 0)
1351 if (i == env->me_maxreaders) {
1352 UNLOCK_MUTEX_R(env);
1355 env->me_txns->mti_readers[i].mr_pid = pid;
1356 env->me_txns->mti_readers[i].mr_tid = tid;
1357 if (i >= env->me_txns->mti_numreaders)
1358 env->me_txns->mti_numreaders = i+1;
1359 UNLOCK_MUTEX_R(env);
1360 r = &env->me_txns->mti_readers[i];
1361 pthread_setspecific(env->me_txkey, r);
1363 txn->mt_toggle = env->me_txns->mti_me_toggle;
1364 txn->mt_txnid = env->me_txns->mti_txnid;
1365 /* This happens if a different process was the
1366 * last writer to the DB.
1368 if (env->me_wtxnid < txn->mt_txnid)
1369 mt_dbflag = DB_STALE;
1370 r->mr_txnid = txn->mt_txnid;
1371 txn->mt_u.reader = r;
1375 txn->mt_txnid = env->me_txns->mti_txnid;
1376 if (env->me_wtxnid < txn->mt_txnid)
1377 mt_dbflag = DB_STALE;
1379 txn->mt_toggle = env->me_txns->mti_me_toggle;
1380 txn->mt_u.dirty_list = env->me_dirty_list;
1381 txn->mt_u.dirty_list[0].mid = 0;
1382 txn->mt_free_pgs = env->me_free_pgs;
1383 txn->mt_free_pgs[0] = 0;
1384 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1388 /* Copy the DB arrays */
1389 LAZY_RWLOCK_RDLOCK(&env->me_dblock);
1390 txn->mt_numdbs = env->me_numdbs;
1391 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
1392 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
1393 if (txn->mt_numdbs > 2)
1394 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
1395 (txn->mt_numdbs - 2) * sizeof(MDB_db));
1396 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1398 memset(txn->mt_dbflags, mt_dbflag, env->me_numdbs);
1404 mdb_txn_renew(MDB_txn *txn)
1411 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
1412 DPUTS("environment had fatal error, must shutdown!");
1416 rc = mdb_txn_renew0(txn);
1417 if (rc == MDB_SUCCESS) {
1418 DPRINTF("renew txn %zu%c %p on mdbenv %p, root page %zu",
1419 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1420 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1426 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
1431 if (env->me_flags & MDB_FATAL_ERROR) {
1432 DPUTS("environment had fatal error, must shutdown!");
1436 /* parent already has an active child txn */
1437 if (parent->mt_child) {
1441 size = sizeof(MDB_txn) + env->me_maxdbs * (sizeof(MDB_db)+1);
1442 if (!(flags & MDB_RDONLY))
1443 size += env->me_maxdbs * sizeof(MDB_cursor *);
1445 if ((txn = calloc(1, size)) == NULL) {
1446 DPRINTF("calloc: %s", strerror(ErrCode()));
1449 txn->mt_dbs = (MDB_db *)(txn+1);
1450 if (flags & MDB_RDONLY) {
1451 txn->mt_flags |= MDB_TXN_RDONLY;
1452 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
1454 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
1455 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
1460 txn->mt_free_pgs = mdb_midl_alloc();
1461 if (!txn->mt_free_pgs) {
1465 txn->mt_u.dirty_list = malloc(sizeof(ID2)*MDB_IDL_UM_SIZE);
1466 if (!txn->mt_u.dirty_list) {
1467 free(txn->mt_free_pgs);
1471 txn->mt_txnid = parent->mt_txnid;
1472 txn->mt_toggle = parent->mt_toggle;
1473 txn->mt_u.dirty_list[0].mid = 0;
1474 txn->mt_free_pgs[0] = 0;
1475 txn->mt_next_pgno = parent->mt_next_pgno;
1476 parent->mt_child = txn;
1477 txn->mt_parent = parent;
1478 txn->mt_numdbs = parent->mt_numdbs;
1479 txn->mt_dbxs = parent->mt_dbxs;
1480 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
1481 memcpy(txn->mt_dbflags, parent->mt_dbflags, txn->mt_numdbs);
1482 mdb_cursor_shadow(parent, txn);
1485 rc = mdb_txn_renew0(txn);
1491 DPRINTF("begin txn %zu%c %p on mdbenv %p, root page %zu",
1492 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1493 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
1499 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
1500 * @param[in] txn the transaction handle to reset
1503 mdb_txn_reset0(MDB_txn *txn)
1505 MDB_env *env = txn->mt_env;
1507 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1508 txn->mt_u.reader->mr_txnid = 0;
1514 /* close(free) all cursors */
1515 for (i=0; i<txn->mt_numdbs; i++) {
1516 if (txn->mt_cursors[i]) {
1518 while ((mc = txn->mt_cursors[i])) {
1519 txn->mt_cursors[i] = mc->mc_next;
1525 /* return all dirty pages to dpage list */
1526 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1527 dp = txn->mt_u.dirty_list[i].mptr;
1528 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1529 dp->mp_next = txn->mt_env->me_dpages;
1530 txn->mt_env->me_dpages = dp;
1532 /* large pages just get freed directly */
1537 if (txn->mt_parent) {
1538 txn->mt_parent->mt_child = NULL;
1539 free(txn->mt_free_pgs);
1540 free(txn->mt_u.dirty_list);
1543 if (mdb_midl_shrink(&txn->mt_free_pgs))
1544 env->me_free_pgs = txn->mt_free_pgs;
1547 while ((mop = txn->mt_env->me_pghead)) {
1548 txn->mt_env->me_pghead = mop->mo_next;
1553 /* The writer mutex was locked in mdb_txn_begin. */
1554 UNLOCK_MUTEX_W(env);
1559 mdb_txn_reset(MDB_txn *txn)
1564 DPRINTF("reset txn %zu%c %p on mdbenv %p, root page %zu",
1565 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1566 (void *) txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1568 mdb_txn_reset0(txn);
1572 mdb_txn_abort(MDB_txn *txn)
1577 DPRINTF("abort txn %zu%c %p on mdbenv %p, root page %zu",
1578 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1579 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1582 mdb_txn_abort(txn->mt_child);
1584 mdb_txn_reset0(txn);
1589 mdb_txn_commit(MDB_txn *txn)
1600 assert(txn != NULL);
1601 assert(txn->mt_env != NULL);
1603 if (txn->mt_child) {
1604 mdb_txn_commit(txn->mt_child);
1605 txn->mt_child = NULL;
1610 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1611 if (txn->mt_numdbs > env->me_numdbs) {
1612 /* update the DB tables */
1613 int toggle = !env->me_db_toggle;
1617 ip = &env->me_dbs[toggle][env->me_numdbs];
1618 jp = &txn->mt_dbs[env->me_numdbs];
1619 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1620 for (i = env->me_numdbs; i < txn->mt_numdbs; i++) {
1624 env->me_db_toggle = toggle;
1625 env->me_numdbs = txn->mt_numdbs;
1626 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1632 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1633 DPUTS("error flag is set, can't commit");
1635 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
1640 /* Merge (and close) our cursors with parent's */
1641 mdb_cursor_merge(txn);
1643 if (txn->mt_parent) {
1649 /* Update parent's DB table */
1650 ip = &txn->mt_parent->mt_dbs[2];
1651 jp = &txn->mt_dbs[2];
1652 for (i = 2; i < txn->mt_numdbs; i++) {
1653 if (ip->md_root != jp->md_root)
1657 txn->mt_parent->mt_numdbs = txn->mt_numdbs;
1659 /* Append our free list to parent's */
1660 mdb_midl_append_list(&txn->mt_parent->mt_free_pgs,
1662 mdb_midl_free(txn->mt_free_pgs);
1664 /* Merge our dirty list with parent's */
1665 dst = txn->mt_parent->mt_u.dirty_list;
1666 src = txn->mt_u.dirty_list;
1667 x = mdb_mid2l_search(dst, src[1].mid);
1668 for (y=1; y<=src[0].mid; y++) {
1669 while (x <= dst[0].mid && dst[x].mid != src[y].mid) x++;
1673 dst[x].mptr = src[y].mptr;
1676 for (; y<=src[0].mid; y++) {
1677 if (++x >= MDB_IDL_UM_MAX)
1682 free(txn->mt_u.dirty_list);
1683 txn->mt_parent->mt_child = NULL;
1688 if (txn != env->me_txn) {
1689 DPUTS("attempt to commit unknown transaction");
1694 if (!txn->mt_u.dirty_list[0].mid)
1697 DPRINTF("committing txn %zu %p on mdbenv %p, root page %zu",
1698 txn->mt_txnid, (void *)txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
1700 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1702 /* should only be one record now */
1703 if (env->me_pghead) {
1704 /* make sure first page of freeDB is touched and on freelist */
1705 mdb_page_search(&mc, NULL, 1);
1707 /* save to free list */
1708 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
1712 /* make sure last page of freeDB is touched and on freelist */
1713 key.mv_size = MAXKEYSIZE+1;
1715 mdb_page_search(&mc, &key, 1);
1717 mdb_midl_sort(txn->mt_free_pgs);
1721 ID *idl = txn->mt_free_pgs;
1722 DPRINTF("IDL write txn %zu root %zu num %zu",
1723 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1724 for (i=0; i<idl[0]; i++) {
1725 DPRINTF("IDL %zu", idl[i+1]);
1729 /* write to last page of freeDB */
1730 key.mv_size = sizeof(pgno_t);
1731 key.mv_data = &txn->mt_txnid;
1732 data.mv_data = txn->mt_free_pgs;
1733 /* The free list can still grow during this call,
1734 * despite the pre-emptive touches above. So check
1735 * and make sure the entire thing got written.
1738 i = txn->mt_free_pgs[0];
1739 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
1740 rc = mdb_cursor_put(&mc, &key, &data, 0);
1745 } while (i != txn->mt_free_pgs[0]);
1746 if (mdb_midl_shrink(&txn->mt_free_pgs))
1747 env->me_free_pgs = txn->mt_free_pgs;
1749 /* should only be one record now */
1750 if (env->me_pghead) {
1754 mop = env->me_pghead;
1755 key.mv_size = sizeof(pgno_t);
1756 key.mv_data = &mop->mo_txnid;
1757 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
1758 data.mv_data = mop->mo_pages;
1759 mdb_cursor_put(&mc, &key, &data, 0);
1760 free(env->me_pghead);
1761 env->me_pghead = NULL;
1764 /* Update DB root pointers. Their pages have already been
1765 * touched so this is all in-place and cannot fail.
1770 data.mv_size = sizeof(MDB_db);
1772 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
1773 for (i = 2; i < txn->mt_numdbs; i++) {
1774 if (txn->mt_dbflags[i] & DB_DIRTY) {
1775 data.mv_data = &txn->mt_dbs[i];
1776 mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
1781 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
1787 /* Windows actually supports scatter/gather I/O, but only on
1788 * unbuffered file handles. Since we're relying on the OS page
1789 * cache for all our data, that's self-defeating. So we just
1790 * write pages one at a time. We use the ov structure to set
1791 * the write offset, to at least save the overhead of a Seek
1795 memset(&ov, 0, sizeof(ov));
1796 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1798 dp = txn->mt_u.dirty_list[i].mptr;
1799 DPRINTF("committing page %zu", dp->mp_pgno);
1800 size = dp->mp_pgno * env->me_psize;
1801 ov.Offset = size & 0xffffffff;
1802 ov.OffsetHigh = size >> 16;
1803 ov.OffsetHigh >>= 16;
1804 /* clear dirty flag */
1805 dp->mp_flags &= ~P_DIRTY;
1806 wsize = env->me_psize;
1807 if (IS_OVERFLOW(dp)) wsize *= dp->mp_pages;
1808 rc = WriteFile(env->me_fd, dp, wsize, NULL, &ov);
1811 DPRINTF("WriteFile: %d", n);
1818 struct iovec iov[MDB_COMMIT_PAGES];
1822 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1823 dp = txn->mt_u.dirty_list[i].mptr;
1824 if (dp->mp_pgno != next) {
1826 DPRINTF("committing %u dirty pages", n);
1827 rc = writev(env->me_fd, iov, n);
1831 DPUTS("short write, filesystem full?");
1833 DPRINTF("writev: %s", strerror(n));
1840 lseek(env->me_fd, dp->mp_pgno * env->me_psize, SEEK_SET);
1843 DPRINTF("committing page %zu", dp->mp_pgno);
1844 iov[n].iov_len = env->me_psize;
1845 if (IS_OVERFLOW(dp)) iov[n].iov_len *= dp->mp_pages;
1846 iov[n].iov_base = dp;
1847 size += iov[n].iov_len;
1848 next = dp->mp_pgno + (IS_OVERFLOW(dp) ? dp->mp_pages : 1);
1849 /* clear dirty flag */
1850 dp->mp_flags &= ~P_DIRTY;
1851 if (++n >= MDB_COMMIT_PAGES) {
1861 DPRINTF("committing %u dirty pages", n);
1862 rc = writev(env->me_fd, iov, n);
1866 DPUTS("short write, filesystem full?");
1868 DPRINTF("writev: %s", strerror(n));
1875 /* Drop the dirty pages.
1877 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1878 dp = txn->mt_u.dirty_list[i].mptr;
1879 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1880 dp->mp_next = txn->mt_env->me_dpages;
1881 txn->mt_env->me_dpages = dp;
1885 txn->mt_u.dirty_list[i].mid = 0;
1887 txn->mt_u.dirty_list[0].mid = 0;
1889 if ((n = mdb_env_sync(env, 0)) != 0 ||
1890 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
1894 env->me_wtxnid = txn->mt_txnid;
1898 /* update the DB tables */
1900 int toggle = !env->me_db_toggle;
1904 ip = &env->me_dbs[toggle][2];
1905 jp = &txn->mt_dbs[2];
1906 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1907 for (i = 2; i < txn->mt_numdbs; i++) {
1908 if (ip->md_root != jp->md_root)
1913 env->me_db_toggle = toggle;
1914 env->me_numdbs = txn->mt_numdbs;
1915 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1918 UNLOCK_MUTEX_W(env);
1924 /** Read the environment parameters of a DB environment before
1925 * mapping it into memory.
1926 * @param[in] env the environment handle
1927 * @param[out] meta address of where to store the meta information
1928 * @return 0 on success, non-zero on failure.
1931 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
1933 char page[PAGESIZE];
1938 /* We don't know the page size yet, so use a minimum value.
1942 if (!ReadFile(env->me_fd, page, PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
1944 if ((rc = read(env->me_fd, page, PAGESIZE)) == 0)
1949 else if (rc != PAGESIZE) {
1953 DPRINTF("read: %s", strerror(err));
1957 p = (MDB_page *)page;
1959 if (!F_ISSET(p->mp_flags, P_META)) {
1960 DPRINTF("page %zu not a meta page", p->mp_pgno);
1965 if (m->mm_magic != MDB_MAGIC) {
1966 DPUTS("meta has invalid magic");
1970 if (m->mm_version != MDB_VERSION) {
1971 DPRINTF("database is version %u, expected version %u",
1972 m->mm_version, MDB_VERSION);
1973 return MDB_VERSION_MISMATCH;
1976 memcpy(meta, m, sizeof(*m));
1980 /** Write the environment parameters of a freshly created DB environment.
1981 * @param[in] env the environment handle
1982 * @param[out] meta address of where to store the meta information
1983 * @return 0 on success, non-zero on failure.
1986 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
1993 DPUTS("writing new meta page");
1995 GET_PAGESIZE(psize);
1997 meta->mm_magic = MDB_MAGIC;
1998 meta->mm_version = MDB_VERSION;
1999 meta->mm_psize = psize;
2000 meta->mm_last_pg = 1;
2001 meta->mm_flags = env->me_flags & 0xffff;
2002 meta->mm_flags |= MDB_INTEGERKEY;
2003 meta->mm_dbs[0].md_root = P_INVALID;
2004 meta->mm_dbs[1].md_root = P_INVALID;
2006 p = calloc(2, psize);
2008 p->mp_flags = P_META;
2011 memcpy(m, meta, sizeof(*meta));
2013 q = (MDB_page *)((char *)p + psize);
2016 q->mp_flags = P_META;
2019 memcpy(m, meta, sizeof(*meta));
2024 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
2025 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
2028 rc = write(env->me_fd, p, psize * 2);
2029 rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
2035 /** Update the environment info to commit a transaction.
2036 * @param[in] txn the transaction that's being committed
2037 * @return 0 on success, non-zero on failure.
2040 mdb_env_write_meta(MDB_txn *txn)
2043 MDB_meta meta, metab;
2045 int rc, len, toggle;
2051 assert(txn != NULL);
2052 assert(txn->mt_env != NULL);
2054 toggle = !txn->mt_toggle;
2055 DPRINTF("writing meta page %d for root page %zu",
2056 toggle, txn->mt_dbs[MAIN_DBI].md_root);
2060 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
2061 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
2063 ptr = (char *)&meta;
2064 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
2065 len = sizeof(MDB_meta) - off;
2068 meta.mm_dbs[0] = txn->mt_dbs[0];
2069 meta.mm_dbs[1] = txn->mt_dbs[1];
2070 meta.mm_last_pg = txn->mt_next_pgno - 1;
2071 meta.mm_txnid = txn->mt_txnid;
2074 off += env->me_psize;
2077 /* Write to the SYNC fd */
2080 memset(&ov, 0, sizeof(ov));
2082 WriteFile(env->me_mfd, ptr, len, (DWORD *)&rc, &ov);
2085 rc = pwrite(env->me_mfd, ptr, len, off);
2090 DPUTS("write failed, disk error?");
2091 /* On a failure, the pagecache still contains the new data.
2092 * Write some old data back, to prevent it from being used.
2093 * Use the non-SYNC fd; we know it will fail anyway.
2095 meta.mm_last_pg = metab.mm_last_pg;
2096 meta.mm_txnid = metab.mm_txnid;
2098 WriteFile(env->me_fd, ptr, len, NULL, &ov);
2100 r2 = pwrite(env->me_fd, ptr, len, off);
2102 env->me_flags |= MDB_FATAL_ERROR;
2105 /* Memory ordering issues are irrelevant; since the entire writer
2106 * is wrapped by wmutex, all of these changes will become visible
2107 * after the wmutex is unlocked. Since the DB is multi-version,
2108 * readers will get consistent data regardless of how fresh or
2109 * how stale their view of these values is.
2111 LAZY_MUTEX_LOCK(&env->me_txns->mti_mutex);
2112 txn->mt_env->me_txns->mti_me_toggle = toggle;
2113 txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
2114 LAZY_MUTEX_UNLOCK(&env->me_txns->mti_mutex);
2119 /** Check both meta pages to see which one is newer.
2120 * @param[in] env the environment handle
2121 * @param[out] which address of where to store the meta toggle ID
2122 * @return 0 on success, non-zero on failure.
2125 mdb_env_read_meta(MDB_env *env, int *which)
2129 assert(env != NULL);
2131 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
2134 DPRINTF("Using meta page %d", toggle);
2141 mdb_env_create(MDB_env **env)
2145 e = calloc(1, sizeof(MDB_env));
2149 e->me_free_pgs = mdb_midl_alloc();
2150 if (!e->me_free_pgs) {
2154 e->me_maxreaders = DEFAULT_READERS;
2156 e->me_fd = INVALID_HANDLE_VALUE;
2157 e->me_lfd = INVALID_HANDLE_VALUE;
2158 e->me_mfd = INVALID_HANDLE_VALUE;
2164 mdb_env_set_mapsize(MDB_env *env, size_t size)
2168 env->me_mapsize = size;
2170 env->me_maxpg = env->me_mapsize / env->me_psize;
2175 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
2179 env->me_maxdbs = dbs;
2184 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
2186 if (env->me_map || readers < 1)
2188 env->me_maxreaders = readers;
2193 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
2195 if (!env || !readers)
2197 *readers = env->me_maxreaders;
2201 /** Further setup required for opening an MDB environment
2204 mdb_env_open2(MDB_env *env, unsigned int flags)
2206 int i, newenv = 0, toggle;
2210 env->me_flags = flags;
2212 memset(&meta, 0, sizeof(meta));
2214 if ((i = mdb_env_read_header(env, &meta)) != 0) {
2217 DPUTS("new mdbenv");
2221 if (!env->me_mapsize) {
2222 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
2228 LONG sizelo, sizehi;
2229 sizelo = env->me_mapsize & 0xffffffff;
2230 sizehi = env->me_mapsize >> 16; /* pointless on WIN32, only needed on W64 */
2232 /* Windows won't create mappings for zero length files.
2233 * Just allocate the maxsize right now.
2236 SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
2237 if (!SetEndOfFile(env->me_fd))
2239 SetFilePointer(env->me_fd, 0, NULL, 0);
2241 mh = CreateFileMapping(env->me_fd, NULL, PAGE_READONLY,
2242 sizehi, sizelo, NULL);
2245 env->me_map = MapViewOfFileEx(mh, FILE_MAP_READ, 0, 0, env->me_mapsize,
2253 if (meta.mm_address && (flags & MDB_FIXEDMAP))
2255 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
2257 if (env->me_map == MAP_FAILED)
2262 meta.mm_mapsize = env->me_mapsize;
2263 if (flags & MDB_FIXEDMAP)
2264 meta.mm_address = env->me_map;
2265 i = mdb_env_init_meta(env, &meta);
2266 if (i != MDB_SUCCESS) {
2267 munmap(env->me_map, env->me_mapsize);
2271 env->me_psize = meta.mm_psize;
2273 env->me_maxpg = env->me_mapsize / env->me_psize;
2275 p = (MDB_page *)env->me_map;
2276 env->me_metas[0] = METADATA(p);
2277 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
2279 if ((i = mdb_env_read_meta(env, &toggle)) != 0)
2282 DPRINTF("opened database version %u, pagesize %u",
2283 env->me_metas[toggle]->mm_version, env->me_psize);
2284 DPRINTF("depth: %u", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_depth);
2285 DPRINTF("entries: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_entries);
2286 DPRINTF("branch pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_branch_pages);
2287 DPRINTF("leaf pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_leaf_pages);
2288 DPRINTF("overflow pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_overflow_pages);
2289 DPRINTF("root: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_root);
2295 /** Release a reader thread's slot in the reader lock table.
2296 * This function is called automatically when a thread exits.
2297 * Windows doesn't support destructor callbacks for thread-specific storage,
2298 * so this function is not compiled there.
2299 * @param[in] ptr This points to the slot in the reader lock table.
2302 mdb_env_reader_dest(void *ptr)
2304 MDB_reader *reader = ptr;
2306 reader->mr_txnid = 0;
2312 /** Downgrade the exclusive lock on the region back to shared */
2314 mdb_env_share_locks(MDB_env *env)
2318 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
2320 env->me_txns->mti_me_toggle = toggle;
2321 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
2326 /* First acquire a shared lock. The Unlock will
2327 * then release the existing exclusive lock.
2329 memset(&ov, 0, sizeof(ov));
2330 LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov);
2331 UnlockFile(env->me_lfd, 0, 0, 1, 0);
2335 struct flock lock_info;
2336 /* The shared lock replaces the existing lock */
2337 memset((void *)&lock_info, 0, sizeof(lock_info));
2338 lock_info.l_type = F_RDLCK;
2339 lock_info.l_whence = SEEK_SET;
2340 lock_info.l_start = 0;
2341 lock_info.l_len = 1;
2342 fcntl(env->me_lfd, F_SETLK, &lock_info);
2346 #if defined(_WIN32) || defined(__APPLE__)
2348 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
2350 * @(#) $Revision: 5.1 $
2351 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
2352 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
2354 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
2358 * Please do not copyright this code. This code is in the public domain.
2360 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
2361 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
2362 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
2363 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
2364 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
2365 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
2366 * PERFORMANCE OF THIS SOFTWARE.
2369 * chongo <Landon Curt Noll> /\oo/\
2370 * http://www.isthe.com/chongo/
2372 * Share and Enjoy! :-)
2375 typedef unsigned long long mdb_hash_t;
2376 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
2378 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
2379 * @param[in] str string to hash
2380 * @param[in] hval initial value for hash
2381 * @return 64 bit hash
2383 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
2384 * hval arg on the first call.
2387 mdb_hash_str(char *str, mdb_hash_t hval)
2389 unsigned char *s = (unsigned char *)str; /* unsigned string */
2391 * FNV-1a hash each octet of the string
2394 /* xor the bottom with the current octet */
2395 hval ^= (mdb_hash_t)*s++;
2397 /* multiply by the 64 bit FNV magic prime mod 2^64 */
2398 hval += (hval << 1) + (hval << 4) + (hval << 5) +
2399 (hval << 7) + (hval << 8) + (hval << 40);
2401 /* return our new hash value */
2405 /** Hash the string and output the hash in hex.
2406 * @param[in] str string to hash
2407 * @param[out] hexbuf an array of 17 chars to hold the hash
2410 mdb_hash_hex(char *str, char *hexbuf)
2413 mdb_hash_t h = mdb_hash_str(str, MDB_HASH_INIT);
2414 for (i=0; i<8; i++) {
2415 hexbuf += sprintf(hexbuf, "%02x", (unsigned int)h & 0xff);
2421 /** Open and/or initialize the lock region for the environment.
2422 * @param[in] env The MDB environment.
2423 * @param[in] lpath The pathname of the file used for the lock region.
2424 * @param[in] mode The Unix permissions for the file, if we create it.
2425 * @param[out] excl Set to true if we got an exclusive lock on the region.
2426 * @return 0 on success, non-zero on failure.
2429 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
2437 if ((env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
2438 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
2439 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
2443 /* Try to get exclusive lock. If we succeed, then
2444 * nobody is using the lock region and we should initialize it.
2447 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
2451 memset(&ov, 0, sizeof(ov));
2452 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
2458 size = GetFileSize(env->me_lfd, NULL);
2460 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
2464 /* Try to get exclusive lock. If we succeed, then
2465 * nobody is using the lock region and we should initialize it.
2468 struct flock lock_info;
2469 memset((void *)&lock_info, 0, sizeof(lock_info));
2470 lock_info.l_type = F_WRLCK;
2471 lock_info.l_whence = SEEK_SET;
2472 lock_info.l_start = 0;
2473 lock_info.l_len = 1;
2474 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
2478 lock_info.l_type = F_RDLCK;
2479 rc = fcntl(env->me_lfd, F_SETLKW, &lock_info);
2486 size = lseek(env->me_lfd, 0, SEEK_END);
2488 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
2489 if (size < rsize && *excl) {
2491 SetFilePointer(env->me_lfd, rsize, NULL, 0);
2492 if (!SetEndOfFile(env->me_lfd)) {
2497 if (ftruncate(env->me_lfd, rsize) != 0) {
2504 size = rsize - sizeof(MDB_txninfo);
2505 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
2510 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
2516 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
2518 if (!env->me_txns) {
2524 env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
2526 if (env->me_txns == MAP_FAILED) {
2534 if (!mdb_sec_inited) {
2535 InitializeSecurityDescriptor(&mdb_null_sd,
2536 SECURITY_DESCRIPTOR_REVISION);
2537 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
2538 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2539 mdb_all_sa.bInheritHandle = FALSE;
2540 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
2543 mdb_hash_hex(lpath, hexbuf);
2544 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", hexbuf);
2545 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
2546 if (!env->me_rmutex) {
2550 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", hexbuf);
2551 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
2552 if (!env->me_wmutex) {
2559 mdb_hash_hex(lpath, hexbuf);
2560 sprintf(env->me_txns->mti_rmname, "MDBr%s", hexbuf);
2561 if (sem_unlink(env->me_txns->mti_rmname)) {
2563 if (rc != ENOENT && rc != EINVAL)
2566 env->me_rmutex = sem_open(env->me_txns->mti_rmname, O_CREAT, mode, 1);
2567 if (!env->me_rmutex) {
2571 sprintf(env->me_txns->mti_wmname, "MDBw%s", hexbuf);
2572 if (sem_unlink(env->me_txns->mti_wmname)) {
2574 if (rc != ENOENT && rc != EINVAL)
2577 env->me_wmutex = sem_open(env->me_txns->mti_wmname, O_CREAT, mode, 1);
2578 if (!env->me_wmutex) {
2582 #else /* __APPLE__ */
2583 pthread_mutexattr_t mattr;
2585 pthread_mutexattr_init(&mattr);
2586 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
2590 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
2591 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
2592 #endif /* __APPLE__ */
2594 env->me_txns->mti_version = MDB_VERSION;
2595 env->me_txns->mti_magic = MDB_MAGIC;
2596 env->me_txns->mti_txnid = 0;
2597 env->me_txns->mti_numreaders = 0;
2598 env->me_txns->mti_me_toggle = 0;
2601 if (env->me_txns->mti_magic != MDB_MAGIC) {
2602 DPUTS("lock region has invalid magic");
2606 if (env->me_txns->mti_version != MDB_VERSION) {
2607 DPRINTF("lock region is version %u, expected version %u",
2608 env->me_txns->mti_version, MDB_VERSION);
2609 rc = MDB_VERSION_MISMATCH;
2613 if (rc != EACCES && rc != EAGAIN) {
2617 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
2618 if (!env->me_rmutex) {
2622 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
2623 if (!env->me_wmutex) {
2629 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
2630 if (!env->me_rmutex) {
2634 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
2635 if (!env->me_wmutex) {
2645 env->me_lfd = INVALID_HANDLE_VALUE;
2650 /** The name of the lock file in the DB environment */
2651 #define LOCKNAME "/lock.mdb"
2652 /** The name of the data file in the DB environment */
2653 #define DATANAME "/data.mdb"
2655 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
2657 int oflags, rc, len, excl;
2658 char *lpath, *dpath;
2661 lpath = malloc(len + sizeof(LOCKNAME) + len + sizeof(DATANAME));
2664 dpath = lpath + len + sizeof(LOCKNAME);
2665 sprintf(lpath, "%s" LOCKNAME, path);
2666 sprintf(dpath, "%s" DATANAME, path);
2668 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
2673 if (F_ISSET(flags, MDB_RDONLY)) {
2674 oflags = GENERIC_READ;
2675 len = OPEN_EXISTING;
2677 oflags = GENERIC_READ|GENERIC_WRITE;
2680 mode = FILE_ATTRIBUTE_NORMAL;
2681 if ((env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2682 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2687 if (F_ISSET(flags, MDB_RDONLY))
2690 oflags = O_RDWR | O_CREAT;
2692 if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
2698 if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
2699 /* synchronous fd for meta writes */
2701 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2702 mode |= FILE_FLAG_WRITE_THROUGH;
2703 if ((env->me_mfd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2704 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2709 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2710 oflags |= MDB_DSYNC;
2711 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
2716 env->me_path = strdup(path);
2717 DPRINTF("opened dbenv %p", (void *) env);
2718 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
2719 LAZY_RWLOCK_INIT(&env->me_dblock, NULL);
2721 mdb_env_share_locks(env);
2722 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
2723 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
2724 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
2730 if (env->me_fd != INVALID_HANDLE_VALUE) {
2732 env->me_fd = INVALID_HANDLE_VALUE;
2734 if (env->me_lfd != INVALID_HANDLE_VALUE) {
2736 env->me_lfd = INVALID_HANDLE_VALUE;
2744 mdb_env_close(MDB_env *env)
2751 while (env->me_dpages) {
2752 dp = env->me_dpages;
2753 env->me_dpages = dp->mp_next;
2757 free(env->me_dbs[1]);
2758 free(env->me_dbs[0]);
2762 LAZY_RWLOCK_DESTROY(&env->me_dblock);
2763 pthread_key_delete(env->me_txkey);
2766 munmap(env->me_map, env->me_mapsize);
2771 pid_t pid = getpid();
2773 for (i=0; i<env->me_txns->mti_numreaders; i++)
2774 if (env->me_txns->mti_readers[i].mr_pid == pid)
2775 env->me_txns->mti_readers[i].mr_pid = 0;
2776 munmap(env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
2779 mdb_midl_free(env->me_free_pgs);
2783 /** Compare two items pointing at aligned size_t's */
2785 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
2787 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
2788 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
2791 /** Compare two items pointing at aligned int's */
2793 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
2795 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
2796 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
2799 /** Compare two items pointing at ints of unknown alignment.
2800 * Nodes and keys are guaranteed to be 2-byte aligned.
2803 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
2805 #if BYTE_ORDER == LITTLE_ENDIAN
2806 unsigned short *u, *c;
2809 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
2810 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
2813 } while(!x && u > (unsigned short *)a->mv_data);
2816 return memcmp(a->mv_data, b->mv_data, a->mv_size);
2820 /** Compare two items lexically */
2822 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
2829 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
2835 diff = memcmp(a->mv_data, b->mv_data, len);
2836 return diff ? diff : len_diff<0 ? -1 : len_diff;
2839 /** Compare two items in reverse byte order */
2841 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
2843 const unsigned char *p1, *p2, *p1_lim;
2847 p1_lim = (const unsigned char *)a->mv_data;
2848 p1 = (const unsigned char *)a->mv_data + a->mv_size;
2849 p2 = (const unsigned char *)b->mv_data + b->mv_size;
2851 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
2857 while (p1 > p1_lim) {
2858 diff = *--p1 - *--p2;
2862 return len_diff<0 ? -1 : len_diff;
2865 /** Search for key within a page, using binary search.
2866 * Returns the smallest entry larger or equal to the key.
2867 * If exactp is non-null, stores whether the found entry was an exact match
2868 * in *exactp (1 or 0).
2869 * Updates the cursor index with the index of the found entry.
2870 * If no entry larger or equal to the key is found, returns NULL.
2873 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
2875 unsigned int i = 0, nkeys;
2878 MDB_page *mp = mc->mc_pg[mc->mc_top];
2879 MDB_node *node = NULL;
2884 nkeys = NUMKEYS(mp);
2886 DPRINTF("searching %u keys in %s %spage %zu",
2887 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
2892 low = IS_LEAF(mp) ? 0 : 1;
2894 cmp = mc->mc_dbx->md_cmp;
2896 /* Branch pages have no data, so if using integer keys,
2897 * alignment is guaranteed. Use faster mdb_cmp_int.
2899 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
2900 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
2907 nodekey.mv_size = mc->mc_db->md_pad;
2908 node = NODEPTR(mp, 0); /* fake */
2909 while (low <= high) {
2910 i = (low + high) >> 1;
2911 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
2912 rc = cmp(key, &nodekey);
2913 DPRINTF("found leaf index %u [%s], rc = %i",
2914 i, DKEY(&nodekey), rc);
2923 while (low <= high) {
2924 i = (low + high) >> 1;
2926 node = NODEPTR(mp, i);
2927 nodekey.mv_size = NODEKSZ(node);
2928 nodekey.mv_data = NODEKEY(node);
2930 rc = cmp(key, &nodekey);
2933 DPRINTF("found leaf index %u [%s], rc = %i",
2934 i, DKEY(&nodekey), rc);
2936 DPRINTF("found branch index %u [%s -> %zu], rc = %i",
2937 i, DKEY(&nodekey), NODEPGNO(node), rc);
2948 if (rc > 0) { /* Found entry is less than the key. */
2949 i++; /* Skip to get the smallest entry larger than key. */
2951 node = NODEPTR(mp, i);
2954 *exactp = (rc == 0);
2955 /* store the key index */
2956 mc->mc_ki[mc->mc_top] = i;
2958 /* There is no entry larger or equal to the key. */
2961 /* nodeptr is fake for LEAF2 */
2967 mdb_cursor_adjust(MDB_cursor *mc, func)
2971 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
2972 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
2979 /** Pop a page off the top of the cursor's stack. */
2981 mdb_cursor_pop(MDB_cursor *mc)
2986 top = mc->mc_pg[mc->mc_top];
2991 DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
2992 mc->mc_dbi, (void *) mc);
2996 /** Push a page onto the top of the cursor's stack. */
2998 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
3000 DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
3001 mc->mc_dbi, (void *) mc);
3003 if (mc->mc_snum >= CURSOR_STACK) {
3004 assert(mc->mc_snum < CURSOR_STACK);
3008 mc->mc_top = mc->mc_snum++;
3009 mc->mc_pg[mc->mc_top] = mp;
3010 mc->mc_ki[mc->mc_top] = 0;
3015 /** Find the address of the page corresponding to a given page number.
3016 * @param[in] txn the transaction for this access.
3017 * @param[in] pgno the page number for the page to retrieve.
3018 * @param[out] ret address of a pointer where the page's address will be stored.
3019 * @return 0 on success, non-zero on failure.
3022 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
3026 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
3028 x = mdb_mid2l_search(txn->mt_u.dirty_list, pgno);
3029 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
3030 p = txn->mt_u.dirty_list[x].mptr;
3034 if (pgno <= txn->mt_env->me_metas[txn->mt_toggle]->mm_last_pg)
3035 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
3039 DPRINTF("page %zu not found", pgno);
3042 return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
3045 /** Search for the page a given key should be in.
3046 * Pushes parent pages on the cursor stack. This function continues a
3047 * search on a cursor that has already been initialized. (Usually by
3048 * #mdb_page_search() but also by #mdb_node_move().)
3049 * @param[in,out] mc the cursor for this operation.
3050 * @param[in] key the key to search for. If NULL, search for the lowest
3051 * page. (This is used by #mdb_cursor_first().)
3052 * @param[in] modify If true, visited pages are updated with new page numbers.
3053 * @return 0 on success, non-zero on failure.
3056 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
3058 MDB_page *mp = mc->mc_pg[mc->mc_top];
3063 while (IS_BRANCH(mp)) {
3067 DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
3068 assert(NUMKEYS(mp) > 1);
3069 DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
3071 if (key == NULL) /* Initialize cursor to first page. */
3073 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
3074 /* cursor to last page */
3078 node = mdb_node_search(mc, key, &exact);
3080 i = NUMKEYS(mp) - 1;
3082 i = mc->mc_ki[mc->mc_top];
3091 DPRINTF("following index %u for key [%s]",
3093 assert(i < NUMKEYS(mp));
3094 node = NODEPTR(mp, i);
3096 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp)))
3099 mc->mc_ki[mc->mc_top] = i;
3100 if ((rc = mdb_cursor_push(mc, mp)))
3104 if ((rc = mdb_page_touch(mc)) != 0)
3106 mp = mc->mc_pg[mc->mc_top];
3111 DPRINTF("internal error, index points to a %02X page!?",
3113 return MDB_CORRUPTED;
3116 DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
3117 key ? DKEY(key) : NULL);
3122 /** Search for the page a given key should be in.
3123 * Pushes parent pages on the cursor stack. This function just sets up
3124 * the search; it finds the root page for \b mc's database and sets this
3125 * as the root of the cursor's stack. Then #mdb_page_search_root() is
3126 * called to complete the search.
3127 * @param[in,out] mc the cursor for this operation.
3128 * @param[in] key the key to search for. If NULL, search for the lowest
3129 * page. (This is used by #mdb_cursor_first().)
3130 * @param[in] modify If true, visited pages are updated with new page numbers.
3131 * @return 0 on success, non-zero on failure.
3134 mdb_page_search(MDB_cursor *mc, MDB_val *key, int modify)
3139 /* Make sure the txn is still viable, then find the root from
3140 * the txn's db table.
3142 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
3143 DPUTS("transaction has failed, must abort");
3146 /* Make sure we're using an up-to-date root */
3147 if (mc->mc_dbi > MAIN_DBI) {
3148 if ((*mc->mc_dbflag & DB_STALE) ||
3149 (modify && !(*mc->mc_dbflag & DB_DIRTY))) {
3151 unsigned char dbflag = 0;
3152 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
3153 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, modify);
3156 if (*mc->mc_dbflag & DB_STALE) {
3159 MDB_node *leaf = mdb_node_search(&mc2,
3160 &mc->mc_dbx->md_name, &exact);
3162 return MDB_NOTFOUND;
3163 mdb_node_read(mc->mc_txn, leaf, &data);
3164 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
3168 *mc->mc_dbflag = dbflag;
3171 root = mc->mc_db->md_root;
3173 if (root == P_INVALID) { /* Tree is empty. */
3174 DPUTS("tree is empty");
3175 return MDB_NOTFOUND;
3179 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0])))
3185 DPRINTF("db %u root page %zu has flags 0x%X",
3186 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
3189 if ((rc = mdb_page_touch(mc)))
3193 return mdb_page_search_root(mc, key, modify);
3196 /** Return the data associated with a given node.
3197 * @param[in] txn The transaction for this operation.
3198 * @param[in] leaf The node being read.
3199 * @param[out] data Updated to point to the node's data.
3200 * @return 0 on success, non-zero on failure.
3203 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
3205 MDB_page *omp; /* overflow page */
3209 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
3210 data->mv_size = NODEDSZ(leaf);
3211 data->mv_data = NODEDATA(leaf);
3215 /* Read overflow data.
3217 data->mv_size = NODEDSZ(leaf);
3218 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
3219 if ((rc = mdb_page_get(txn, pgno, &omp))) {
3220 DPRINTF("read overflow page %zu failed", pgno);
3223 data->mv_data = METADATA(omp);
3229 mdb_get(MDB_txn *txn, MDB_dbi dbi,
3230 MDB_val *key, MDB_val *data)
3239 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
3241 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3244 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3248 mdb_cursor_init(&mc, txn, dbi, &mx);
3249 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
3252 /** Find a sibling for a page.
3253 * Replaces the page at the top of the cursor's stack with the
3254 * specified sibling, if one exists.
3255 * @param[in] mc The cursor for this operation.
3256 * @param[in] move_right Non-zero if the right sibling is requested,
3257 * otherwise the left sibling.
3258 * @return 0 on success, non-zero on failure.
3261 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
3267 if (mc->mc_snum < 2) {
3268 return MDB_NOTFOUND; /* root has no siblings */
3272 DPRINTF("parent page is page %zu, index %u",
3273 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]);
3275 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
3276 : (mc->mc_ki[mc->mc_top] == 0)) {
3277 DPRINTF("no more keys left, moving to %s sibling",
3278 move_right ? "right" : "left");
3279 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS)
3283 mc->mc_ki[mc->mc_top]++;
3285 mc->mc_ki[mc->mc_top]--;
3286 DPRINTF("just moving to %s index key %u",
3287 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]);
3289 assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
3291 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3292 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp)))
3295 mdb_cursor_push(mc, mp);
3300 /** Move the cursor to the next data item. */
3302 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3308 if (mc->mc_flags & C_EOF) {
3309 return MDB_NOTFOUND;
3312 assert(mc->mc_flags & C_INITIALIZED);
3314 mp = mc->mc_pg[mc->mc_top];
3316 if (mc->mc_db->md_flags & MDB_DUPSORT) {
3317 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3318 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3319 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
3320 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
3321 if (op != MDB_NEXT || rc == MDB_SUCCESS)
3325 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3326 if (op == MDB_NEXT_DUP)
3327 return MDB_NOTFOUND;
3331 DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3333 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
3334 DPUTS("=====> move to next sibling page");
3335 if (mdb_cursor_sibling(mc, 1) != MDB_SUCCESS) {
3336 mc->mc_flags |= C_EOF;
3337 mc->mc_flags &= ~C_INITIALIZED;
3338 return MDB_NOTFOUND;
3340 mp = mc->mc_pg[mc->mc_top];
3341 DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3343 mc->mc_ki[mc->mc_top]++;
3345 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3346 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3349 key->mv_size = mc->mc_db->md_pad;
3350 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3354 assert(IS_LEAF(mp));
3355 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3357 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3358 mdb_xcursor_init1(mc, leaf);
3361 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3364 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3365 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3366 if (rc != MDB_SUCCESS)
3371 MDB_SET_KEY(leaf, key);
3375 /** Move the cursor to the previous data item. */
3377 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3383 assert(mc->mc_flags & C_INITIALIZED);
3385 mp = mc->mc_pg[mc->mc_top];
3387 if (mc->mc_db->md_flags & MDB_DUPSORT) {
3388 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3389 if (op == MDB_PREV || op == MDB_PREV_DUP) {
3390 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3391 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
3392 if (op != MDB_PREV || rc == MDB_SUCCESS)
3395 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3396 if (op == MDB_PREV_DUP)
3397 return MDB_NOTFOUND;
3402 DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3404 if (mc->mc_ki[mc->mc_top] == 0) {
3405 DPUTS("=====> move to prev sibling page");
3406 if (mdb_cursor_sibling(mc, 0) != MDB_SUCCESS) {
3407 mc->mc_flags &= ~C_INITIALIZED;
3408 return MDB_NOTFOUND;
3410 mp = mc->mc_pg[mc->mc_top];
3411 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
3412 DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3414 mc->mc_ki[mc->mc_top]--;
3416 mc->mc_flags &= ~C_EOF;
3418 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3419 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3422 key->mv_size = mc->mc_db->md_pad;
3423 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3427 assert(IS_LEAF(mp));
3428 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3430 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3431 mdb_xcursor_init1(mc, leaf);
3434 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3437 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3438 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3439 if (rc != MDB_SUCCESS)
3444 MDB_SET_KEY(leaf, key);
3448 /** Set the cursor on a specific data item. */
3450 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3451 MDB_cursor_op op, int *exactp)
3460 assert(key->mv_size > 0);
3462 /* See if we're already on the right page */
3463 if (mc->mc_flags & C_INITIALIZED) {
3466 mp = mc->mc_pg[mc->mc_top];
3468 mc->mc_ki[mc->mc_top] = 0;
3469 return MDB_NOTFOUND;
3471 if (mp->mp_flags & P_LEAF2) {
3472 nodekey.mv_size = mc->mc_db->md_pad;
3473 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
3475 leaf = NODEPTR(mp, 0);
3476 MDB_SET_KEY(leaf, &nodekey);
3478 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3480 /* Probably happens rarely, but first node on the page
3481 * was the one we wanted.
3483 mc->mc_ki[mc->mc_top] = 0;
3484 leaf = NODEPTR(mp, 0);
3491 unsigned int nkeys = NUMKEYS(mp);
3493 if (mp->mp_flags & P_LEAF2) {
3494 nodekey.mv_data = LEAF2KEY(mp,
3495 nkeys-1, nodekey.mv_size);
3497 leaf = NODEPTR(mp, nkeys-1);
3498 MDB_SET_KEY(leaf, &nodekey);
3500 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3502 /* last node was the one we wanted */
3503 mc->mc_ki[mc->mc_top] = nkeys-1;
3504 leaf = NODEPTR(mp, nkeys-1);
3510 /* This is definitely the right page, skip search_page */
3515 /* If any parents have right-sibs, search.
3516 * Otherwise, there's nothing further.
3518 for (i=0; i<mc->mc_top; i++)
3520 NUMKEYS(mc->mc_pg[i])-1)
3522 if (i == mc->mc_top) {
3523 /* There are no other pages */
3524 mc->mc_ki[mc->mc_top] = nkeys;
3525 return MDB_NOTFOUND;
3529 /* There are no other pages */
3530 mc->mc_ki[mc->mc_top] = 0;
3531 return MDB_NOTFOUND;
3535 rc = mdb_page_search(mc, key, 0);
3536 if (rc != MDB_SUCCESS)
3539 mp = mc->mc_pg[mc->mc_top];
3540 assert(IS_LEAF(mp));
3543 leaf = mdb_node_search(mc, key, exactp);
3544 if (exactp != NULL && !*exactp) {
3545 /* MDB_SET specified and not an exact match. */
3546 return MDB_NOTFOUND;
3550 DPUTS("===> inexact leaf not found, goto sibling");
3551 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
3552 return rc; /* no entries matched */
3553 mp = mc->mc_pg[mc->mc_top];
3554 assert(IS_LEAF(mp));
3555 leaf = NODEPTR(mp, 0);
3559 mc->mc_flags |= C_INITIALIZED;
3560 mc->mc_flags &= ~C_EOF;
3563 key->mv_size = mc->mc_db->md_pad;
3564 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3568 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3569 mdb_xcursor_init1(mc, leaf);
3572 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3573 if (op == MDB_SET || op == MDB_SET_RANGE) {
3574 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3577 if (op == MDB_GET_BOTH) {
3583 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
3584 if (rc != MDB_SUCCESS)
3587 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
3589 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
3591 rc = mc->mc_dbx->md_dcmp(data, &d2);
3593 if (op == MDB_GET_BOTH || rc > 0)
3594 return MDB_NOTFOUND;
3599 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3600 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3605 /* The key already matches in all other cases */
3606 if (op == MDB_SET_RANGE)
3607 MDB_SET_KEY(leaf, key);
3608 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
3613 /** Move the cursor to the first item in the database. */
3615 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3620 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3621 rc = mdb_page_search(mc, NULL, 0);
3622 if (rc != MDB_SUCCESS)
3625 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3627 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
3628 mc->mc_flags |= C_INITIALIZED;
3629 mc->mc_flags &= ~C_EOF;
3631 mc->mc_ki[mc->mc_top] = 0;
3633 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3634 key->mv_size = mc->mc_db->md_pad;
3635 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
3640 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3641 mdb_xcursor_init1(mc, leaf);
3642 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3647 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3648 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3652 MDB_SET_KEY(leaf, key);
3656 /** Move the cursor to the last item in the database. */
3658 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3664 lkey.mv_size = MAXKEYSIZE+1;
3665 lkey.mv_data = NULL;
3667 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3668 rc = mdb_page_search(mc, &lkey, 0);
3669 if (rc != MDB_SUCCESS)
3672 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3674 leaf = NODEPTR(mc->mc_pg[mc->mc_top], NUMKEYS(mc->mc_pg[mc->mc_top])-1);
3675 mc->mc_flags |= C_INITIALIZED;
3676 mc->mc_flags &= ~C_EOF;
3678 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
3680 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3681 key->mv_size = mc->mc_db->md_pad;
3682 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
3687 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3688 mdb_xcursor_init1(mc, leaf);
3689 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3694 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3695 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3700 MDB_SET_KEY(leaf, key);
3705 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3715 case MDB_GET_BOTH_RANGE:
3716 if (data == NULL || mc->mc_xcursor == NULL) {
3723 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3725 } else if (op == MDB_SET_RANGE)
3726 rc = mdb_cursor_set(mc, key, data, op, NULL);
3728 rc = mdb_cursor_set(mc, key, data, op, &exact);
3730 case MDB_GET_MULTIPLE:
3732 !(mc->mc_db->md_flags & MDB_DUPFIXED) ||
3733 !(mc->mc_flags & C_INITIALIZED)) {
3738 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
3739 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
3742 case MDB_NEXT_MULTIPLE:
3744 !(mc->mc_db->md_flags & MDB_DUPFIXED)) {
3748 if (!(mc->mc_flags & C_INITIALIZED))
3749 rc = mdb_cursor_first(mc, key, data);
3751 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
3752 if (rc == MDB_SUCCESS) {
3753 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
3756 mx = &mc->mc_xcursor->mx_cursor;
3757 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
3759 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
3760 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
3768 case MDB_NEXT_NODUP:
3769 if (!(mc->mc_flags & C_INITIALIZED))
3770 rc = mdb_cursor_first(mc, key, data);
3772 rc = mdb_cursor_next(mc, key, data, op);
3776 case MDB_PREV_NODUP:
3777 if (!(mc->mc_flags & C_INITIALIZED) || (mc->mc_flags & C_EOF))
3778 rc = mdb_cursor_last(mc, key, data);
3780 rc = mdb_cursor_prev(mc, key, data, op);
3783 rc = mdb_cursor_first(mc, key, data);
3787 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
3788 !(mc->mc_flags & C_INITIALIZED) ||
3789 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3793 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3796 rc = mdb_cursor_last(mc, key, data);
3800 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
3801 !(mc->mc_flags & C_INITIALIZED) ||
3802 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3806 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3809 DPRINTF("unhandled/unimplemented cursor operation %u", op);
3817 /** Touch all the pages in the cursor stack.
3818 * Makes sure all the pages are writable, before attempting a write operation.
3819 * @param[in] mc The cursor to operate on.
3822 mdb_cursor_touch(MDB_cursor *mc)
3826 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
3828 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
3829 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 1);
3832 *mc->mc_dbflag = DB_DIRTY;
3834 for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
3835 rc = mdb_page_touch(mc);
3839 mc->mc_top = mc->mc_snum-1;
3844 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3847 MDB_node *leaf = NULL;
3848 MDB_val xdata, *rdata, dkey;
3854 char pbuf[PAGESIZE];
3855 char dbuf[MAXKEYSIZE+1];
3858 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
3861 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
3862 mc->mc_dbi, DKEY(key), key ? key->mv_size:0, data->mv_size);
3866 if (flags == MDB_CURRENT) {
3867 if (!(mc->mc_flags & C_INITIALIZED))
3870 } else if (mc->mc_db->md_root == P_INVALID) {
3872 /* new database, write a root leaf page */
3873 DPUTS("allocating new root leaf page");
3874 if ((np = mdb_page_new(mc, P_LEAF, 1)) == NULL) {
3878 mdb_cursor_push(mc, np);
3879 mc->mc_db->md_root = np->mp_pgno;
3880 mc->mc_db->md_depth++;
3881 *mc->mc_dbflag = DB_DIRTY;
3882 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
3884 np->mp_flags |= P_LEAF2;
3885 mc->mc_flags |= C_INITIALIZED;
3891 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
3892 if (flags == MDB_NOOVERWRITE && rc == 0) {
3893 DPRINTF("duplicate key [%s]", DKEY(key));
3895 return MDB_KEYEXIST;
3897 if (rc && rc != MDB_NOTFOUND)
3901 /* Cursor is positioned, now make sure all pages are writable */
3902 rc2 = mdb_cursor_touch(mc);
3907 /* The key already exists */
3908 if (rc == MDB_SUCCESS) {
3909 /* there's only a key anyway, so this is a no-op */
3910 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3911 unsigned int ksize = mc->mc_db->md_pad;
3912 if (key->mv_size != ksize)
3914 if (flags == MDB_CURRENT) {
3915 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
3916 memcpy(ptr, key->mv_data, ksize);
3921 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3924 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
3925 /* Was a single item before, must convert now */
3926 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3927 /* Just overwrite the current item */
3928 if (flags == MDB_CURRENT)
3931 dkey.mv_size = NODEDSZ(leaf);
3932 dkey.mv_data = NODEDATA(leaf);
3933 /* data matches, ignore it */
3934 if (!mc->mc_dbx->md_dcmp(data, &dkey))
3935 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
3937 /* create a fake page for the dup items */
3938 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
3939 dkey.mv_data = dbuf;
3940 fp = (MDB_page *)pbuf;
3941 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
3942 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
3943 fp->mp_lower = PAGEHDRSZ;
3944 fp->mp_upper = PAGEHDRSZ + dkey.mv_size + data->mv_size;
3945 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
3946 fp->mp_flags |= P_LEAF2;
3947 fp->mp_pad = data->mv_size;
3949 fp->mp_upper += 2 * sizeof(indx_t) + 2 * NODESIZE +
3950 (dkey.mv_size & 1) + (data->mv_size & 1);
3952 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
3955 xdata.mv_size = fp->mp_upper;
3956 xdata.mv_data = pbuf;
3960 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
3961 /* See if we need to convert from fake page to subDB */
3963 unsigned int offset;
3966 fp = NODEDATA(leaf);
3967 if (flags == MDB_CURRENT) {
3968 fp->mp_flags |= P_DIRTY;
3969 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
3970 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
3974 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
3975 offset = fp->mp_pad;
3977 offset = NODESIZE + sizeof(indx_t) + data->mv_size;
3979 offset += offset & 1;
3980 if (NODESIZE + sizeof(indx_t) + NODEKSZ(leaf) + NODEDSZ(leaf) +
3981 offset >= (mc->mc_txn->mt_env->me_psize - PAGEHDRSZ) /
3983 /* yes, convert it */
3985 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
3986 dummy.md_pad = fp->mp_pad;
3987 dummy.md_flags = MDB_DUPFIXED;
3988 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
3989 dummy.md_flags |= MDB_INTEGERKEY;
3992 dummy.md_branch_pages = 0;
3993 dummy.md_leaf_pages = 1;
3994 dummy.md_overflow_pages = 0;
3995 dummy.md_entries = NUMKEYS(fp);
3997 xdata.mv_size = sizeof(MDB_db);
3998 xdata.mv_data = &dummy;
3999 mp = mdb_page_alloc(mc, 1);
4002 offset = mc->mc_txn->mt_env->me_psize - NODEDSZ(leaf);
4003 flags |= F_DUPDATA|F_SUBDATA;
4004 dummy.md_root = mp->mp_pgno;
4006 /* no, just grow it */
4008 xdata.mv_size = NODEDSZ(leaf) + offset;
4009 xdata.mv_data = pbuf;
4010 mp = (MDB_page *)pbuf;
4011 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4014 mp->mp_flags = fp->mp_flags | P_DIRTY;
4015 mp->mp_pad = fp->mp_pad;
4016 mp->mp_lower = fp->mp_lower;
4017 mp->mp_upper = fp->mp_upper + offset;
4019 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
4021 nsize = NODEDSZ(leaf) - fp->mp_upper;
4022 memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper, nsize);
4023 for (i=0; i<NUMKEYS(fp); i++)
4024 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
4026 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4030 /* data is on sub-DB, just store it */
4031 flags |= F_DUPDATA|F_SUBDATA;
4035 /* same size, just replace it */
4036 if (!F_ISSET(leaf->mn_flags, F_BIGDATA) &&
4037 NODEDSZ(leaf) == data->mv_size) {
4038 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
4041 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4043 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
4049 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
4050 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
4051 rc = mdb_page_split(mc, key, rdata, P_INVALID);
4053 /* There is room already in this leaf page. */
4054 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, 0);
4055 if (rc == 0 && !do_sub) {
4056 /* Adjust other cursors pointing to mp */
4057 MDB_cursor *m2, *m3;
4058 MDB_dbi dbi = mc->mc_dbi;
4059 unsigned i = mc->mc_top;
4060 MDB_page *mp = mc->mc_pg[i];
4062 if (mc->mc_flags & C_SUB)
4065 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
4066 if (mc->mc_flags & C_SUB)
4067 m3 = &m2->mc_xcursor->mx_cursor;
4070 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
4077 if (rc != MDB_SUCCESS)
4078 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4080 /* Remember if we just added a subdatabase */
4081 if (flags & (F_SUBDATA|F_DUPDATA)) {
4082 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4083 leaf->mn_flags |= (flags & (F_SUBDATA|F_DUPDATA));
4086 /* Now store the actual data in the child DB. Note that we're
4087 * storing the user data in the keys field, so there are strict
4088 * size limits on dupdata. The actual data fields of the child
4089 * DB are all zero size.
4097 if (flags & MDB_CURRENT) {
4098 xflags = MDB_CURRENT;
4100 mdb_xcursor_init1(mc, leaf);
4101 xflags = (flags & MDB_NODUPDATA) ? MDB_NOOVERWRITE : 0;
4103 /* converted, write the original data first */
4105 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
4109 /* Adjust other cursors pointing to mp */
4111 unsigned i = mc->mc_top;
4112 MDB_page *mp = mc->mc_pg[i];
4114 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4115 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
4116 mdb_xcursor_init1(m2, leaf);
4121 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
4122 if (flags & F_SUBDATA) {
4123 db = NODEDATA(leaf);
4124 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4127 /* sub-writes might have failed so check rc again.
4128 * Don't increment count if we just replaced an existing item.
4130 if (!rc && !(flags & MDB_CURRENT))
4131 mc->mc_db->md_entries++;
4138 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
4143 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
4146 if (!mc->mc_flags & C_INITIALIZED)
4149 rc = mdb_cursor_touch(mc);
4153 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4155 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4156 if (flags != MDB_NODUPDATA) {
4157 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
4158 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
4160 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
4161 /* If sub-DB still has entries, we're done */
4162 if (mc->mc_xcursor->mx_db.md_entries) {
4163 if (leaf->mn_flags & F_SUBDATA) {
4164 /* update subDB info */
4165 MDB_db *db = NODEDATA(leaf);
4166 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4168 /* shrink fake page */
4169 mdb_node_shrink(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4171 mc->mc_db->md_entries--;
4174 /* otherwise fall thru and delete the sub-DB */
4177 if (leaf->mn_flags & F_SUBDATA) {
4178 /* add all the child DB's pages to the free list */
4179 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
4180 if (rc == MDB_SUCCESS) {
4181 mc->mc_db->md_entries -=
4182 mc->mc_xcursor->mx_db.md_entries;
4187 return mdb_cursor_del0(mc, leaf);
4190 /** Allocate and initialize new pages for a database.
4191 * @param[in] mc a cursor on the database being added to.
4192 * @param[in] flags flags defining what type of page is being allocated.
4193 * @param[in] num the number of pages to allocate. This is usually 1,
4194 * unless allocating overflow pages for a large record.
4195 * @return Address of a page, or NULL on failure.
4198 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num)
4202 if ((np = mdb_page_alloc(mc, num)) == NULL)
4204 DPRINTF("allocated new mpage %zu, page size %u",
4205 np->mp_pgno, mc->mc_txn->mt_env->me_psize);
4206 np->mp_flags = flags | P_DIRTY;
4207 np->mp_lower = PAGEHDRSZ;
4208 np->mp_upper = mc->mc_txn->mt_env->me_psize;
4211 mc->mc_db->md_branch_pages++;
4212 else if (IS_LEAF(np))
4213 mc->mc_db->md_leaf_pages++;
4214 else if (IS_OVERFLOW(np)) {
4215 mc->mc_db->md_overflow_pages += num;
4222 /** Calculate the size of a leaf node.
4223 * The size depends on the environment's page size; if a data item
4224 * is too large it will be put onto an overflow page and the node
4225 * size will only include the key and not the data. Sizes are always
4226 * rounded up to an even number of bytes, to guarantee 2-byte alignment
4227 * of the #MDB_node headers.
4228 * @param[in] env The environment handle.
4229 * @param[in] key The key for the node.
4230 * @param[in] data The data for the node.
4231 * @return The number of bytes needed to store the node.
4234 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
4238 sz = LEAFSIZE(key, data);
4239 if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
4240 /* put on overflow page */
4241 sz -= data->mv_size - sizeof(pgno_t);
4245 return sz + sizeof(indx_t);
4248 /** Calculate the size of a branch node.
4249 * The size should depend on the environment's page size but since
4250 * we currently don't support spilling large keys onto overflow
4251 * pages, it's simply the size of the #MDB_node header plus the
4252 * size of the key. Sizes are always rounded up to an even number
4253 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
4254 * @param[in] env The environment handle.
4255 * @param[in] key The key for the node.
4256 * @return The number of bytes needed to store the node.
4259 mdb_branch_size(MDB_env *env, MDB_val *key)
4264 if (sz >= env->me_psize / MDB_MINKEYS) {
4265 /* put on overflow page */
4266 /* not implemented */
4267 /* sz -= key->size - sizeof(pgno_t); */
4270 return sz + sizeof(indx_t);
4273 /** Add a node to the page pointed to by the cursor.
4274 * @param[in] mc The cursor for this operation.
4275 * @param[in] indx The index on the page where the new node should be added.
4276 * @param[in] key The key for the new node.
4277 * @param[in] data The data for the new node, if any.
4278 * @param[in] pgno The page number, if adding a branch node.
4279 * @param[in] flags Flags for the node.
4280 * @return 0 on success, non-zero on failure. Possible errors are:
4282 * <li>ENOMEM - failed to allocate overflow pages for the node.
4283 * <li>ENOSPC - there is insufficient room in the page. This error
4284 * should never happen since all callers already calculate the
4285 * page's free space before calling this function.
4289 mdb_node_add(MDB_cursor *mc, indx_t indx,
4290 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags)
4293 size_t node_size = NODESIZE;
4296 MDB_page *mp = mc->mc_pg[mc->mc_top];
4297 MDB_page *ofp = NULL; /* overflow page */
4300 assert(mp->mp_upper >= mp->mp_lower);
4302 DPRINTF("add to %s %spage %zu index %i, data size %zu key size %zu [%s]",
4303 IS_LEAF(mp) ? "leaf" : "branch",
4304 IS_SUBP(mp) ? "sub-" : "",
4305 mp->mp_pgno, indx, data ? data->mv_size : 0,
4306 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
4309 /* Move higher keys up one slot. */
4310 int ksize = mc->mc_db->md_pad, dif;
4311 char *ptr = LEAF2KEY(mp, indx, ksize);
4312 dif = NUMKEYS(mp) - indx;
4314 memmove(ptr+ksize, ptr, dif*ksize);
4315 /* insert new key */
4316 memcpy(ptr, key->mv_data, ksize);
4318 /* Just using these for counting */
4319 mp->mp_lower += sizeof(indx_t);
4320 mp->mp_upper -= ksize - sizeof(indx_t);
4325 node_size += key->mv_size;
4329 if (F_ISSET(flags, F_BIGDATA)) {
4330 /* Data already on overflow page. */
4331 node_size += sizeof(pgno_t);
4332 } else if (data->mv_size >= mc->mc_txn->mt_env->me_psize / MDB_MINKEYS) {
4333 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
4334 /* Put data on overflow page. */
4335 DPRINTF("data size is %zu, put on overflow page",
4337 node_size += sizeof(pgno_t);
4338 if ((ofp = mdb_page_new(mc, P_OVERFLOW, ovpages)) == NULL)
4340 DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
4343 node_size += data->mv_size;
4346 node_size += node_size & 1;
4348 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
4349 DPRINTF("not enough room in page %zu, got %u ptrs",
4350 mp->mp_pgno, NUMKEYS(mp));
4351 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
4352 mp->mp_upper - mp->mp_lower);
4353 DPRINTF("node size = %zu", node_size);
4357 /* Move higher pointers up one slot. */
4358 for (i = NUMKEYS(mp); i > indx; i--)
4359 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
4361 /* Adjust free space offsets. */
4362 ofs = mp->mp_upper - node_size;
4363 assert(ofs >= mp->mp_lower + sizeof(indx_t));
4364 mp->mp_ptrs[indx] = ofs;
4366 mp->mp_lower += sizeof(indx_t);
4368 /* Write the node data. */
4369 node = NODEPTR(mp, indx);
4370 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
4371 node->mn_flags = flags;
4373 SETDSZ(node,data->mv_size);
4378 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
4383 if (F_ISSET(flags, F_BIGDATA))
4384 memcpy(node->mn_data + key->mv_size, data->mv_data,
4387 memcpy(node->mn_data + key->mv_size, data->mv_data,
4390 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
4392 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
4399 /** Delete the specified node from a page.
4400 * @param[in] mp The page to operate on.
4401 * @param[in] indx The index of the node to delete.
4402 * @param[in] ksize The size of a node. Only used if the page is
4403 * part of a #MDB_DUPFIXED database.
4406 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
4409 indx_t i, j, numkeys, ptr;
4413 DPRINTF("delete node %u on %s page %zu", indx,
4414 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
4415 assert(indx < NUMKEYS(mp));
4418 int x = NUMKEYS(mp) - 1 - indx;
4419 base = LEAF2KEY(mp, indx, ksize);
4421 memmove(base, base + ksize, x * ksize);
4422 mp->mp_lower -= sizeof(indx_t);
4423 mp->mp_upper += ksize - sizeof(indx_t);
4427 node = NODEPTR(mp, indx);
4428 sz = NODESIZE + node->mn_ksize;
4430 if (F_ISSET(node->mn_flags, F_BIGDATA))
4431 sz += sizeof(pgno_t);
4433 sz += NODEDSZ(node);
4437 ptr = mp->mp_ptrs[indx];
4438 numkeys = NUMKEYS(mp);
4439 for (i = j = 0; i < numkeys; i++) {
4441 mp->mp_ptrs[j] = mp->mp_ptrs[i];
4442 if (mp->mp_ptrs[i] < ptr)
4443 mp->mp_ptrs[j] += sz;
4448 base = (char *)mp + mp->mp_upper;
4449 memmove(base + sz, base, ptr - mp->mp_upper);
4451 mp->mp_lower -= sizeof(indx_t);
4455 /** Compact the main page after deleting a node on a subpage.
4456 * @param[in] mp The main page to operate on.
4457 * @param[in] indx The index of the subpage on the main page.
4460 mdb_node_shrink(MDB_page *mp, indx_t indx)
4467 indx_t i, numkeys, ptr;
4469 node = NODEPTR(mp, indx);
4470 sp = (MDB_page *)NODEDATA(node);
4471 osize = NODEDSZ(node);
4473 delta = sp->mp_upper - sp->mp_lower;
4474 SETDSZ(node, osize - delta);
4475 xp = (MDB_page *)((char *)sp + delta);
4477 /* shift subpage upward */
4479 nsize = NUMKEYS(sp) * sp->mp_pad;
4480 memmove(METADATA(xp), METADATA(sp), nsize);
4483 nsize = osize - sp->mp_upper;
4484 numkeys = NUMKEYS(sp);
4485 for (i=numkeys-1; i>=0; i--)
4486 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
4488 xp->mp_upper = sp->mp_lower;
4489 xp->mp_lower = sp->mp_lower;
4490 xp->mp_flags = sp->mp_flags;
4491 xp->mp_pad = sp->mp_pad;
4492 xp->mp_pgno = mp->mp_pgno;
4494 /* shift lower nodes upward */
4495 ptr = mp->mp_ptrs[indx];
4496 numkeys = NUMKEYS(mp);
4497 for (i = 0; i < numkeys; i++) {
4498 if (mp->mp_ptrs[i] <= ptr)
4499 mp->mp_ptrs[i] += delta;
4502 base = (char *)mp + mp->mp_upper;
4503 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
4504 mp->mp_upper += delta;
4507 /** Initial setup of a sorted-dups cursor.
4508 * Sorted duplicates are implemented as a sub-database for the given key.
4509 * The duplicate data items are actually keys of the sub-database.
4510 * Operations on the duplicate data items are performed using a sub-cursor
4511 * initialized when the sub-database is first accessed. This function does
4512 * the preliminary setup of the sub-cursor, filling in the fields that
4513 * depend only on the parent DB.
4514 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4517 mdb_xcursor_init0(MDB_cursor *mc)
4519 MDB_xcursor *mx = mc->mc_xcursor;
4521 mx->mx_cursor.mc_xcursor = NULL;
4522 mx->mx_cursor.mc_txn = mc->mc_txn;
4523 mx->mx_cursor.mc_db = &mx->mx_db;
4524 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
4525 mx->mx_cursor.mc_dbi = mc->mc_dbi+1;
4526 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
4527 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
4528 mx->mx_dbx.md_dcmp = NULL;
4529 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
4532 /** Final setup of a sorted-dups cursor.
4533 * Sets up the fields that depend on the data from the main cursor.
4534 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4535 * @param[in] node The data containing the #MDB_db record for the
4536 * sorted-dup database.
4539 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
4541 MDB_xcursor *mx = mc->mc_xcursor;
4543 if (node->mn_flags & F_SUBDATA) {
4544 MDB_db *db = NODEDATA(node);
4546 mx->mx_cursor.mc_snum = 0;
4547 mx->mx_cursor.mc_flags = C_SUB;
4549 MDB_page *fp = NODEDATA(node);
4550 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
4551 mx->mx_db.md_flags = 0;
4552 mx->mx_db.md_depth = 1;
4553 mx->mx_db.md_branch_pages = 0;
4554 mx->mx_db.md_leaf_pages = 1;
4555 mx->mx_db.md_overflow_pages = 0;
4556 mx->mx_db.md_entries = NUMKEYS(fp);
4557 mx->mx_db.md_root = fp->mp_pgno;
4558 mx->mx_cursor.mc_snum = 1;
4559 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
4560 mx->mx_cursor.mc_top = 0;
4561 mx->mx_cursor.mc_pg[0] = fp;
4562 mx->mx_cursor.mc_ki[0] = 0;
4563 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4564 mx->mx_db.md_flags = MDB_DUPFIXED;
4565 mx->mx_db.md_pad = fp->mp_pad;
4566 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
4567 mx->mx_db.md_flags |= MDB_INTEGERKEY;
4570 DPRINTF("Sub-db %u for db %u root page %zu", mx->mx_cursor.mc_dbi, mc->mc_dbi,
4572 mx->mx_dbflag = (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY)) ?
4574 mx->mx_dbx.md_name.mv_data = NODEKEY(node);
4575 mx->mx_dbx.md_name.mv_size = node->mn_ksize;
4576 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
4577 mx->mx_dbx.md_cmp = mdb_cmp_long;
4580 /** Initialize a cursor for a given transaction and database. */
4582 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
4587 mc->mc_db = &txn->mt_dbs[dbi];
4588 mc->mc_dbx = &txn->mt_dbxs[dbi];
4589 mc->mc_dbflag = &txn->mt_dbflags[dbi];
4592 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4594 mc->mc_xcursor = mx;
4595 mdb_xcursor_init0(mc);
4597 mc->mc_xcursor = NULL;
4602 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
4605 MDB_xcursor *mx = NULL;
4606 size_t size = sizeof(MDB_cursor);
4608 if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
4611 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
4612 size += sizeof(MDB_xcursor);
4614 if ((mc = malloc(size)) != NULL) {
4615 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4616 mx = (MDB_xcursor *)(mc + 1);
4618 mdb_cursor_init(mc, txn, dbi, mx);
4619 if (txn->mt_cursors) {
4620 mc->mc_next = txn->mt_cursors[dbi];
4621 txn->mt_cursors[dbi] = mc;
4632 /* Return the count of duplicate data items for the current key */
4634 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
4638 if (mc == NULL || countp == NULL)
4641 if (!(mc->mc_db->md_flags & MDB_DUPSORT))
4644 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4645 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4648 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
4651 *countp = mc->mc_xcursor->mx_db.md_entries;
4657 mdb_cursor_close(MDB_cursor *mc)
4660 /* remove from txn, if tracked */
4661 if (mc->mc_txn->mt_cursors) {
4662 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
4663 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
4665 *prev = mc->mc_next;
4671 /** Replace the key for a node with a new key.
4672 * @param[in] mp The page containing the node to operate on.
4673 * @param[in] indx The index of the node to operate on.
4674 * @param[in] key The new key to use.
4675 * @return 0 on success, non-zero on failure.
4678 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
4680 indx_t ptr, i, numkeys;
4687 node = NODEPTR(mp, indx);
4688 ptr = mp->mp_ptrs[indx];
4689 DPRINTF("update key %u (ofs %u) [%.*s] to [%s] on page %zu",
4691 (int)node->mn_ksize, (char *)NODEKEY(node),
4695 delta = key->mv_size - node->mn_ksize;
4697 if (delta > 0 && SIZELEFT(mp) < delta) {
4698 DPRINTF("OUCH! Not enough room, delta = %d", delta);
4702 numkeys = NUMKEYS(mp);
4703 for (i = 0; i < numkeys; i++) {
4704 if (mp->mp_ptrs[i] <= ptr)
4705 mp->mp_ptrs[i] -= delta;
4708 base = (char *)mp + mp->mp_upper;
4709 len = ptr - mp->mp_upper + NODESIZE;
4710 memmove(base - delta, base, len);
4711 mp->mp_upper -= delta;
4713 node = NODEPTR(mp, indx);
4714 node->mn_ksize = key->mv_size;
4717 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
4722 /** Move a node from csrc to cdst.
4725 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
4732 /* Mark src and dst as dirty. */
4733 if ((rc = mdb_page_touch(csrc)) ||
4734 (rc = mdb_page_touch(cdst)))
4737 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4738 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
4739 key.mv_size = csrc->mc_db->md_pad;
4740 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
4742 data.mv_data = NULL;
4744 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
4745 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
4746 unsigned int snum = csrc->mc_snum;
4748 /* must find the lowest key below src */
4749 mdb_page_search_root(csrc, NULL, 0);
4750 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
4751 key.mv_size = NODEKSZ(s2);
4752 key.mv_data = NODEKEY(s2);
4753 csrc->mc_snum = snum--;
4754 csrc->mc_top = snum;
4756 key.mv_size = NODEKSZ(srcnode);
4757 key.mv_data = NODEKEY(srcnode);
4759 data.mv_size = NODEDSZ(srcnode);
4760 data.mv_data = NODEDATA(srcnode);
4762 DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
4763 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
4764 csrc->mc_ki[csrc->mc_top],
4766 csrc->mc_pg[csrc->mc_top]->mp_pgno,
4767 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
4769 /* Add the node to the destination page.
4771 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, NODEPGNO(srcnode),
4773 if (rc != MDB_SUCCESS)
4776 /* Delete the node from the source page.
4778 mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
4781 /* Adjust other cursors pointing to mp */
4782 MDB_cursor *m2, *m3;
4783 MDB_dbi dbi = csrc->mc_dbi;
4784 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
4786 if (csrc->mc_flags & C_SUB)
4789 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
4790 if (csrc->mc_flags & C_SUB)
4791 m3 = &m2->mc_xcursor->mx_cursor;
4794 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
4795 csrc->mc_ki[csrc->mc_top]) {
4796 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
4797 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
4802 /* Update the parent separators.
4804 if (csrc->mc_ki[csrc->mc_top] == 0) {
4805 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
4806 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4807 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
4809 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
4810 key.mv_size = NODEKSZ(srcnode);
4811 key.mv_data = NODEKEY(srcnode);
4813 DPRINTF("update separator for source page %zu to [%s]",
4814 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
4815 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1],
4816 &key)) != MDB_SUCCESS)
4819 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
4821 nullkey.mv_size = 0;
4822 assert(mdb_update_key(csrc->mc_pg[csrc->mc_top], 0, &nullkey) == MDB_SUCCESS);
4826 if (cdst->mc_ki[cdst->mc_top] == 0) {
4827 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
4828 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4829 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
4831 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
4832 key.mv_size = NODEKSZ(srcnode);
4833 key.mv_data = NODEKEY(srcnode);
4835 DPRINTF("update separator for destination page %zu to [%s]",
4836 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
4837 if ((rc = mdb_update_key(cdst->mc_pg[cdst->mc_top-1], cdst->mc_ki[cdst->mc_top-1],
4838 &key)) != MDB_SUCCESS)
4841 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
4843 nullkey.mv_size = 0;
4844 assert(mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &nullkey) == MDB_SUCCESS);
4851 /** Merge one page into another.
4852 * The nodes from the page pointed to by \b csrc will
4853 * be copied to the page pointed to by \b cdst and then
4854 * the \b csrc page will be freed.
4855 * @param[in] csrc Cursor pointing to the source page.
4856 * @param[in] cdst Cursor pointing to the destination page.
4859 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
4867 DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
4868 cdst->mc_pg[cdst->mc_top]->mp_pgno);
4870 assert(csrc->mc_snum > 1); /* can't merge root page */
4871 assert(cdst->mc_snum > 1);
4873 /* Mark dst as dirty. */
4874 if ((rc = mdb_page_touch(cdst)))
4877 /* Move all nodes from src to dst.
4879 j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
4880 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4881 key.mv_size = csrc->mc_db->md_pad;
4882 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
4883 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
4884 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
4885 if (rc != MDB_SUCCESS)
4887 key.mv_data = (char *)key.mv_data + key.mv_size;
4890 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
4891 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
4893 key.mv_size = srcnode->mn_ksize;
4894 key.mv_data = NODEKEY(srcnode);
4895 data.mv_size = NODEDSZ(srcnode);
4896 data.mv_data = NODEDATA(srcnode);
4897 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
4898 if (rc != MDB_SUCCESS)
4903 DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
4904 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);
4906 /* Unlink the src page from parent and add to free list.
4908 mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
4909 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
4911 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], 0, &key)) != MDB_SUCCESS)
4915 mdb_midl_append(&csrc->mc_txn->mt_free_pgs, csrc->mc_pg[csrc->mc_top]->mp_pgno);
4916 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
4917 csrc->mc_db->md_leaf_pages--;
4919 csrc->mc_db->md_branch_pages--;
4921 /* Adjust other cursors pointing to mp */
4922 MDB_cursor *m2, *m3;
4923 MDB_dbi dbi = csrc->mc_dbi;
4924 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
4926 if (csrc->mc_flags & C_SUB)
4929 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
4930 if (csrc->mc_flags & C_SUB)
4931 m3 = &m2->mc_xcursor->mx_cursor;
4934 if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
4935 m3->mc_pg[csrc->mc_top] = mp;
4936 m3->mc_ki[csrc->mc_top] += nkeys;
4940 mdb_cursor_pop(csrc);
4942 return mdb_rebalance(csrc);
4945 /** Copy the contents of a cursor.
4946 * @param[in] csrc The cursor to copy from.
4947 * @param[out] cdst The cursor to copy to.
4950 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
4954 cdst->mc_txn = csrc->mc_txn;
4955 cdst->mc_dbi = csrc->mc_dbi;
4956 cdst->mc_db = csrc->mc_db;
4957 cdst->mc_dbx = csrc->mc_dbx;
4958 cdst->mc_snum = csrc->mc_snum;
4959 cdst->mc_top = csrc->mc_top;
4960 cdst->mc_flags = csrc->mc_flags;
4962 for (i=0; i<csrc->mc_snum; i++) {
4963 cdst->mc_pg[i] = csrc->mc_pg[i];
4964 cdst->mc_ki[i] = csrc->mc_ki[i];
4968 /** Rebalance the tree after a delete operation.
4969 * @param[in] mc Cursor pointing to the page where rebalancing
4971 * @return 0 on success, non-zero on failure.
4974 mdb_rebalance(MDB_cursor *mc)
4981 DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
4982 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
4983 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);
4985 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD) {
4986 DPRINTF("no need to rebalance page %zu, above fill threshold",
4987 mc->mc_pg[mc->mc_top]->mp_pgno);
4991 if (mc->mc_snum < 2) {
4992 MDB_page *mp = mc->mc_pg[0];
4993 if (NUMKEYS(mp) == 0) {
4994 DPUTS("tree is completely empty");
4995 mc->mc_db->md_root = P_INVALID;
4996 mc->mc_db->md_depth = 0;
4997 mc->mc_db->md_leaf_pages = 0;
4998 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5002 /* Adjust other cursors pointing to mp */
5003 MDB_cursor *m2, *m3;
5004 MDB_dbi dbi = mc->mc_dbi;
5006 if (mc->mc_flags & C_SUB)
5009 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5010 if (mc->mc_flags & C_SUB)
5011 m3 = &m2->mc_xcursor->mx_cursor;
5014 if (m3->mc_pg[0] == mp) {
5020 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
5021 DPUTS("collapsing root page!");
5022 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5023 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
5024 if ((rc = mdb_page_get(mc->mc_txn, mc->mc_db->md_root,
5027 mc->mc_db->md_depth--;
5028 mc->mc_db->md_branch_pages--;
5030 /* Adjust other cursors pointing to mp */
5031 MDB_cursor *m2, *m3;
5032 MDB_dbi dbi = mc->mc_dbi;
5034 if (mc->mc_flags & C_SUB)
5037 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5038 if (mc->mc_flags & C_SUB)
5039 m3 = &m2->mc_xcursor->mx_cursor;
5042 if (m3->mc_pg[0] == mp) {
5043 m3->mc_pg[0] = mc->mc_pg[0];
5048 DPUTS("root page doesn't need rebalancing");
5052 /* The parent (branch page) must have at least 2 pointers,
5053 * otherwise the tree is invalid.
5055 ptop = mc->mc_top-1;
5056 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
5058 /* Leaf page fill factor is below the threshold.
5059 * Try to move keys from left or right neighbor, or
5060 * merge with a neighbor page.
5065 mdb_cursor_copy(mc, &mn);
5066 mn.mc_xcursor = NULL;
5068 if (mc->mc_ki[ptop] == 0) {
5069 /* We're the leftmost leaf in our parent.
5071 DPUTS("reading right neighbor");
5073 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5074 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5076 mn.mc_ki[mn.mc_top] = 0;
5077 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
5079 /* There is at least one neighbor to the left.
5081 DPUTS("reading left neighbor");
5083 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5084 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5086 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
5087 mc->mc_ki[mc->mc_top] = 0;
5090 DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
5091 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);
5093 /* If the neighbor page is above threshold and has at least two
5094 * keys, move one key from it.
5096 * Otherwise we should try to merge them.
5098 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) >= 2)
5099 return mdb_node_move(&mn, mc);
5100 else { /* FIXME: if (has_enough_room()) */
5101 mc->mc_flags &= ~C_INITIALIZED;
5102 if (mc->mc_ki[ptop] == 0)
5103 return mdb_page_merge(&mn, mc);
5105 return mdb_page_merge(mc, &mn);
5109 /** Complete a delete operation started by #mdb_cursor_del(). */
5111 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
5115 /* add overflow pages to free list */
5116 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5120 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
5121 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
5122 for (i=0; i<ovpages; i++) {
5123 DPRINTF("freed ov page %zu", pg);
5124 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
5128 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], mc->mc_db->md_pad);
5129 mc->mc_db->md_entries--;
5130 rc = mdb_rebalance(mc);
5131 if (rc != MDB_SUCCESS)
5132 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5138 mdb_del(MDB_txn *txn, MDB_dbi dbi,
5139 MDB_val *key, MDB_val *data)
5144 MDB_val rdata, *xdata;
5148 assert(key != NULL);
5150 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
5152 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5155 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
5159 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
5163 mdb_cursor_init(&mc, txn, dbi, &mx);
5174 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
5176 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
5180 /** Split a page and insert a new node.
5181 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
5182 * The cursor will be updated to point to the actual page and index where
5183 * the node got inserted after the split.
5184 * @param[in] newkey The key for the newly inserted node.
5185 * @param[in] newdata The data for the newly inserted node.
5186 * @param[in] newpgno The page number, if the new node is a branch node.
5187 * @return 0 on success, non-zero on failure.
5190 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno)
5193 int rc = MDB_SUCCESS, ins_new = 0, new_root = 0;
5196 unsigned int i, j, split_indx, nkeys, pmax;
5198 MDB_val sepkey, rkey, rdata;
5200 MDB_page *mp, *rp, *pp;
5205 mp = mc->mc_pg[mc->mc_top];
5206 newindx = mc->mc_ki[mc->mc_top];
5208 DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
5209 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
5210 DKEY(newkey), mc->mc_ki[mc->mc_top]);
5212 if (mc->mc_snum < 2) {
5213 if ((pp = mdb_page_new(mc, P_BRANCH, 1)) == NULL)
5215 /* shift current top to make room for new parent */
5216 mc->mc_pg[1] = mc->mc_pg[0];
5217 mc->mc_ki[1] = mc->mc_ki[0];
5220 mc->mc_db->md_root = pp->mp_pgno;
5221 DPRINTF("root split! new root = %zu", pp->mp_pgno);
5222 mc->mc_db->md_depth++;
5225 /* Add left (implicit) pointer. */
5226 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
5227 /* undo the pre-push */
5228 mc->mc_pg[0] = mc->mc_pg[1];
5229 mc->mc_ki[0] = mc->mc_ki[1];
5230 mc->mc_db->md_root = mp->mp_pgno;
5231 mc->mc_db->md_depth--;
5238 ptop = mc->mc_top-1;
5239 DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
5242 /* Create a right sibling. */
5243 if ((rp = mdb_page_new(mc, mp->mp_flags, 1)) == NULL)
5245 mdb_cursor_copy(mc, &mn);
5246 mn.mc_pg[mn.mc_top] = rp;
5247 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
5248 DPRINTF("new right sibling: page %zu", rp->mp_pgno);
5250 nkeys = NUMKEYS(mp);
5251 split_indx = nkeys / 2 + 1;
5256 unsigned int lsize, rsize, ksize;
5257 /* Move half of the keys to the right sibling */
5259 x = mc->mc_ki[mc->mc_top] - split_indx;
5260 ksize = mc->mc_db->md_pad;
5261 split = LEAF2KEY(mp, split_indx, ksize);
5262 rsize = (nkeys - split_indx) * ksize;
5263 lsize = (nkeys - split_indx) * sizeof(indx_t);
5264 mp->mp_lower -= lsize;
5265 rp->mp_lower += lsize;
5266 mp->mp_upper += rsize - lsize;
5267 rp->mp_upper -= rsize - lsize;
5268 sepkey.mv_size = ksize;
5269 if (newindx == split_indx) {
5270 sepkey.mv_data = newkey->mv_data;
5272 sepkey.mv_data = split;
5275 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
5276 memcpy(rp->mp_ptrs, split, rsize);
5277 sepkey.mv_data = rp->mp_ptrs;
5278 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
5279 memcpy(ins, newkey->mv_data, ksize);
5280 mp->mp_lower += sizeof(indx_t);
5281 mp->mp_upper -= ksize - sizeof(indx_t);
5284 memcpy(rp->mp_ptrs, split, x * ksize);
5285 ins = LEAF2KEY(rp, x, ksize);
5286 memcpy(ins, newkey->mv_data, ksize);
5287 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
5288 rp->mp_lower += sizeof(indx_t);
5289 rp->mp_upper -= ksize - sizeof(indx_t);
5290 mc->mc_ki[mc->mc_top] = x;
5291 mc->mc_pg[mc->mc_top] = rp;
5296 /* For leaf pages, check the split point based on what
5297 * fits where, since otherwise add_node can fail.
5300 unsigned int psize, nsize;
5301 /* Maximum free space in an empty page */
5302 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
5303 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
5304 if (newindx < split_indx) {
5306 for (i=0; i<split_indx; i++) {
5307 node = NODEPTR(mp, i);
5308 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
5309 if (F_ISSET(node->mn_flags, F_BIGDATA))
5310 psize += sizeof(pgno_t);
5312 psize += NODEDSZ(node);
5321 for (i=nkeys-1; i>=split_indx; i--) {
5322 node = NODEPTR(mp, i);
5323 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
5324 if (F_ISSET(node->mn_flags, F_BIGDATA))
5325 psize += sizeof(pgno_t);
5327 psize += NODEDSZ(node);
5337 /* First find the separating key between the split pages.
5339 if (newindx == split_indx) {
5340 sepkey.mv_size = newkey->mv_size;
5341 sepkey.mv_data = newkey->mv_data;
5343 node = NODEPTR(mp, split_indx);
5344 sepkey.mv_size = node->mn_ksize;
5345 sepkey.mv_data = NODEKEY(node);
5349 DPRINTF("separator is [%s]", DKEY(&sepkey));
5351 /* Copy separator key to the parent.
5353 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
5356 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno);
5358 /* Right page might now have changed parent.
5359 * Check if left page also changed parent.
5361 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
5362 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
5363 mc->mc_pg[ptop] = mn.mc_pg[ptop];
5364 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
5368 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
5371 if (rc != MDB_SUCCESS) {
5378 /* Move half of the keys to the right sibling. */
5380 /* grab a page to hold a temporary copy */
5381 copy = mdb_page_malloc(mc);
5385 copy->mp_pgno = mp->mp_pgno;
5386 copy->mp_flags = mp->mp_flags;
5387 copy->mp_lower = PAGEHDRSZ;
5388 copy->mp_upper = mc->mc_txn->mt_env->me_psize;
5389 mc->mc_pg[mc->mc_top] = copy;
5390 for (i = j = 0; i <= nkeys; j++) {
5391 if (i == split_indx) {
5392 /* Insert in right sibling. */
5393 /* Reset insert index for right sibling. */
5394 j = (i == newindx && ins_new);
5395 mc->mc_pg[mc->mc_top] = rp;
5398 if (i == newindx && !ins_new) {
5399 /* Insert the original entry that caused the split. */
5400 rkey.mv_data = newkey->mv_data;
5401 rkey.mv_size = newkey->mv_size;
5403 rdata.mv_data = newdata->mv_data;
5404 rdata.mv_size = newdata->mv_size;
5411 /* Update page and index for the new key. */
5412 mc->mc_ki[mc->mc_top] = j;
5413 } else if (i == nkeys) {
5416 node = NODEPTR(mp, i);
5417 rkey.mv_data = NODEKEY(node);
5418 rkey.mv_size = node->mn_ksize;
5420 rdata.mv_data = NODEDATA(node);
5421 rdata.mv_size = NODEDSZ(node);
5423 pgno = NODEPGNO(node);
5424 flags = node->mn_flags;
5429 if (!IS_LEAF(mp) && j == 0) {
5430 /* First branch index doesn't need key data. */
5434 rc = mdb_node_add(mc, j, &rkey, &rdata, pgno, flags);
5437 /* reset back to original page */
5438 if (newindx < split_indx)
5439 mc->mc_pg[mc->mc_top] = mp;
5441 nkeys = NUMKEYS(copy);
5442 for (i=0; i<nkeys; i++)
5443 mp->mp_ptrs[i] = copy->mp_ptrs[i];
5444 mp->mp_lower = copy->mp_lower;
5445 mp->mp_upper = copy->mp_upper;
5446 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
5447 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
5449 /* return tmp page to freelist */
5450 copy->mp_next = mc->mc_txn->mt_env->me_dpages;
5451 mc->mc_txn->mt_env->me_dpages = copy;
5454 /* Adjust other cursors pointing to mp */
5455 MDB_cursor *m2, *m3;
5456 MDB_dbi dbi = mc->mc_dbi;
5458 if (mc->mc_flags & C_SUB)
5461 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5462 if (mc->mc_flags & C_SUB)
5463 m3 = &m2->mc_xcursor->mx_cursor;
5468 for (i=m3->mc_top; i>0; i--) {
5469 m3->mc_ki[i+1] = m3->mc_ki[i];
5470 m3->mc_pg[i+1] = m3->mc_pg[i];
5472 m3->mc_ki[0] = mc->mc_ki[0];
5473 m3->mc_pg[0] = mc->mc_pg[0];
5477 if (m3->mc_pg[mc->mc_top] == mp) {
5478 if (m3->mc_ki[m3->mc_top] >= split_indx) {
5479 m3->mc_pg[m3->mc_top] = rp;
5480 m3->mc_ki[m3->mc_top] -= split_indx;
5489 mdb_put(MDB_txn *txn, MDB_dbi dbi,
5490 MDB_val *key, MDB_val *data, unsigned int flags)
5495 assert(key != NULL);
5496 assert(data != NULL);
5498 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5501 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
5505 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
5509 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA)) != flags)
5512 mdb_cursor_init(&mc, txn, dbi, &mx);
5513 return mdb_cursor_put(&mc, key, data, flags);
5516 /** Only a subset of the @ref mdb_env flags can be changed
5517 * at runtime. Changing other flags requires closing the environment
5518 * and re-opening it with the new flags.
5520 #define CHANGEABLE (MDB_NOSYNC)
5522 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
5524 if ((flag & CHANGEABLE) != flag)
5527 env->me_flags |= flag;
5529 env->me_flags &= ~flag;
5534 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
5539 *arg = env->me_flags;
5544 mdb_env_get_path(MDB_env *env, const char **arg)
5549 *arg = env->me_path;
5553 /** Common code for #mdb_stat() and #mdb_env_stat().
5554 * @param[in] env the environment to operate in.
5555 * @param[in] db the #MDB_db record containing the stats to return.
5556 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
5557 * @return 0, this function always succeeds.
5560 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
5562 arg->ms_psize = env->me_psize;
5563 arg->ms_depth = db->md_depth;
5564 arg->ms_branch_pages = db->md_branch_pages;
5565 arg->ms_leaf_pages = db->md_leaf_pages;
5566 arg->ms_overflow_pages = db->md_overflow_pages;
5567 arg->ms_entries = db->md_entries;
5572 mdb_env_stat(MDB_env *env, MDB_stat *arg)
5576 if (env == NULL || arg == NULL)
5579 mdb_env_read_meta(env, &toggle);
5581 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
5584 /** Set the default comparison functions for a database.
5585 * Called immediately after a database is opened to set the defaults.
5586 * The user can then override them with #mdb_set_compare() or
5587 * #mdb_set_dupsort().
5588 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
5589 * @param[in] dbi A database handle returned by #mdb_open()
5592 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
5594 if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEKEY)
5595 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memnr;
5596 else if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERKEY)
5597 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_cint;
5599 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memn;
5601 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
5602 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP) {
5603 if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED)
5604 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_int;
5606 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_cint;
5607 } else if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEDUP) {
5608 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memnr;
5610 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memn;
5613 txn->mt_dbxs[dbi].md_dcmp = NULL;
5617 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
5624 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
5625 mdb_default_cmp(txn, FREE_DBI);
5631 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
5632 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
5633 mdb_default_cmp(txn, MAIN_DBI);
5637 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
5638 mdb_default_cmp(txn, MAIN_DBI);
5641 /* Is the DB already open? */
5643 for (i=2; i<txn->mt_numdbs; i++) {
5644 if (len == txn->mt_dbxs[i].md_name.mv_size &&
5645 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
5651 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
5654 /* Find the DB info */
5656 key.mv_data = (void *)name;
5657 rc = mdb_get(txn, MAIN_DBI, &key, &data);
5659 /* Create if requested */
5660 if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
5663 data.mv_size = sizeof(MDB_db);
5664 data.mv_data = &dummy;
5665 memset(&dummy, 0, sizeof(dummy));
5666 dummy.md_root = P_INVALID;
5667 dummy.md_flags = flags & 0xffff;
5668 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
5669 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
5673 /* OK, got info, add to table */
5674 if (rc == MDB_SUCCESS) {
5675 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
5676 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
5677 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
5678 txn->mt_dbflags[txn->mt_numdbs] = dbflag;
5679 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
5680 *dbi = txn->mt_numdbs;
5681 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
5682 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
5683 mdb_default_cmp(txn, txn->mt_numdbs);
5690 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
5692 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
5695 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
5698 void mdb_close(MDB_env *env, MDB_dbi dbi)
5701 if (dbi <= MAIN_DBI || dbi >= env->me_numdbs)
5703 ptr = env->me_dbxs[dbi].md_name.mv_data;
5704 env->me_dbxs[dbi].md_name.mv_data = NULL;
5705 env->me_dbxs[dbi].md_name.mv_size = 0;
5709 /** Add all the DB's pages to the free list.
5710 * @param[in] mc Cursor on the DB to free.
5711 * @param[in] subs non-Zero to check for sub-DBs in this DB.
5712 * @return 0 on success, non-zero on failure.
5715 mdb_drop0(MDB_cursor *mc, int subs)
5719 rc = mdb_page_search(mc, NULL, 0);
5720 if (rc == MDB_SUCCESS) {
5725 /* LEAF2 pages have no nodes, cannot have sub-DBs */
5726 if (!subs || IS_LEAF2(mc->mc_pg[mc->mc_top]))
5729 mdb_cursor_copy(mc, &mx);
5730 while (mc->mc_snum > 0) {
5731 if (IS_LEAF(mc->mc_pg[mc->mc_top])) {
5732 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
5733 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
5734 if (ni->mn_flags & F_SUBDATA) {
5735 mdb_xcursor_init1(mc, ni);
5736 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
5742 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
5744 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
5747 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
5752 rc = mdb_cursor_sibling(mc, 1);
5754 /* no more siblings, go back to beginning
5755 * of previous level. (stack was already popped
5756 * by mdb_cursor_sibling)
5758 for (i=1; i<mc->mc_top; i++)
5759 mc->mc_pg[i] = mx.mc_pg[i];
5763 mdb_midl_append(&mc->mc_txn->mt_free_pgs,
5764 mc->mc_db->md_root);
5769 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
5774 if (!txn || !dbi || dbi >= txn->mt_numdbs)
5777 rc = mdb_cursor_open(txn, dbi, &mc);
5781 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
5783 mdb_cursor_close(mc);
5786 /* Can't delete the main DB */
5787 if (del && dbi > MAIN_DBI) {
5788 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
5790 mdb_close(txn->mt_env, dbi);
5792 txn->mt_dbflags[dbi] |= DB_DIRTY;
5793 txn->mt_dbs[dbi].md_depth = 0;
5794 txn->mt_dbs[dbi].md_branch_pages = 0;
5795 txn->mt_dbs[dbi].md_leaf_pages = 0;
5796 txn->mt_dbs[dbi].md_overflow_pages = 0;
5797 txn->mt_dbs[dbi].md_entries = 0;
5798 txn->mt_dbs[dbi].md_root = P_INVALID;
5800 mdb_cursor_close(mc);
5804 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
5806 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5809 txn->mt_dbxs[dbi].md_cmp = cmp;
5813 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
5815 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5818 txn->mt_dbxs[dbi].md_dcmp = cmp;
5822 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
5824 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5827 txn->mt_dbxs[dbi].md_rel = rel;
5831 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
5833 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5836 txn->mt_dbxs[dbi].md_relctx = ctx;