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 */
515 /** @defgroup mdb_page Page Flags
517 * Flags for the page headers.
520 #define P_BRANCH 0x01 /**< branch page */
521 #define P_LEAF 0x02 /**< leaf page */
522 #define P_OVERFLOW 0x04 /**< overflow page */
523 #define P_META 0x08 /**< meta page */
524 #define P_DIRTY 0x10 /**< dirty page */
525 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
527 uint32_t mp_flags; /**< @ref mdb_page */
528 #define mp_lower mp_pb.pb.pb_lower
529 #define mp_upper mp_pb.pb.pb_upper
530 #define mp_pages mp_pb.pb_pages
533 indx_t pb_lower; /**< lower bound of free space */
534 indx_t pb_upper; /**< upper bound of free space */
536 uint32_t pb_pages; /**< number of overflow pages */
538 indx_t mp_ptrs[1]; /**< dynamic size */
541 /** Size of the page header, excluding dynamic data at the end */
542 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
544 /** Address of first usable data byte in a page, after the header */
545 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
547 /** Number of nodes on a page */
548 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
550 /** The amount of space remaining in the page */
551 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
553 /** The percentage of space used in the page, in tenths of a percent. */
554 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
555 ((env)->me_psize - PAGEHDRSZ))
556 /** The minimum page fill factor, in tenths of a percent.
557 * Pages emptier than this are candidates for merging.
559 #define FILL_THRESHOLD 250
561 /** Test if a page is a leaf page */
562 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
563 /** Test if a page is a LEAF2 page */
564 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
565 /** Test if a page is a branch page */
566 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
567 /** Test if a page is an overflow page */
568 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
570 /** The number of overflow pages needed to store the given size. */
571 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
573 /** Header for a single key/data pair within a page.
574 * We guarantee 2-byte alignment for nodes.
576 typedef struct MDB_node {
577 /** lo and hi are used for data size on leaf nodes and for
578 * child pgno on branch nodes. On 64 bit platforms, flags
579 * is also used for pgno. (Branch nodes have no flags).
580 * They are in host byte order in case that lets some
581 * accesses be optimized into a 32-bit word access.
583 #define mn_lo mn_offset[BYTE_ORDER!=LITTLE_ENDIAN]
584 #define mn_hi mn_offset[BYTE_ORDER==LITTLE_ENDIAN] /**< part of dsize or pgno */
585 unsigned short mn_offset[2]; /**< storage for #mn_lo and #mn_hi */
586 /** @defgroup mdb_node Node Flags
588 * Flags for node headers.
591 #define F_BIGDATA 0x01 /**< data put on overflow page */
592 #define F_SUBDATA 0x02 /**< data is a sub-database */
593 #define F_DUPDATA 0x04 /**< data has duplicates */
595 unsigned short mn_flags; /**< @ref mdb_node */
596 unsigned short mn_ksize; /**< key size */
597 char mn_data[1]; /**< key and data are appended here */
600 /** Size of the node header, excluding dynamic data at the end */
601 #define NODESIZE offsetof(MDB_node, mn_data)
603 /** Bit position of top word in page number, for shifting mn_flags */
604 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
606 /** Size of a node in a branch page with a given key.
607 * This is just the node header plus the key, there is no data.
609 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
611 /** Size of a node in a leaf page with a given key and data.
612 * This is node header plus key plus data size.
614 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
616 /** Address of node \b i in page \b p */
617 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
619 /** Address of the key for the node */
620 #define NODEKEY(node) (void *)((node)->mn_data)
622 /** Address of the data for a node */
623 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
625 /** Get the page number pointed to by a branch node */
626 #define NODEPGNO(node) \
627 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
628 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
629 /** Set the page number in a branch node */
630 #define SETPGNO(node,pgno) do { \
631 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
632 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
634 /** Get the size of the data in a leaf node */
635 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
636 /** Set the size of the data for a leaf node */
637 #define SETDSZ(node,size) do { \
638 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
639 /** The size of a key in a node */
640 #define NODEKSZ(node) ((node)->mn_ksize)
642 /** The address of a key in a LEAF2 page.
643 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
644 * There are no node headers, keys are stored contiguously.
646 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
648 /** Set the \b node's key into \b key, if requested. */
649 #define MDB_SET_KEY(node, key) { if ((key) != NULL) { \
650 (key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node); } }
652 /** Information about a single database in the environment. */
653 typedef struct MDB_db {
654 uint32_t md_pad; /**< also ksize for LEAF2 pages */
655 uint16_t md_flags; /**< @ref mdb_open */
656 uint16_t md_depth; /**< depth of this tree */
657 pgno_t md_branch_pages; /**< number of internal pages */
658 pgno_t md_leaf_pages; /**< number of leaf pages */
659 pgno_t md_overflow_pages; /**< number of overflow pages */
660 size_t md_entries; /**< number of data items */
661 pgno_t md_root; /**< the root page of this tree */
664 /** Handle for the DB used to track free pages. */
666 /** Handle for the default DB. */
669 /** Identify a data item as a valid sub-DB record */
670 #define MDB_SUBDATA 0x8200
672 /** Meta page content. */
673 typedef struct MDB_meta {
674 /** Stamp identifying this as an MDB data file. It must be set
677 /** Version number of this lock file. Must be set to #MDB_VERSION. */
679 void *mm_address; /**< address for fixed mapping */
680 size_t mm_mapsize; /**< size of mmap region */
681 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
682 /** The size of pages used in this DB */
683 #define mm_psize mm_dbs[0].md_pad
684 /** Any persistent environment flags. @ref mdb_env */
685 #define mm_flags mm_dbs[0].md_flags
686 pgno_t mm_last_pg; /**< last used page in file */
687 txnid_t mm_txnid; /**< txnid that committed this page */
690 /** Auxiliary DB info.
691 * The information here is mostly static/read-only. There is
692 * only a single copy of this record in the environment.
693 * The \b md_dirty flag is not read-only, but only a write
694 * transaction can ever update it, and only write transactions
695 * need to worry about it.
697 typedef struct MDB_dbx {
698 MDB_val md_name; /**< name of the database */
699 MDB_cmp_func *md_cmp; /**< function for comparing keys */
700 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
701 MDB_rel_func *md_rel; /**< user relocate function */
702 void *md_relctx; /**< user-provided context for md_rel */
703 MDB_dbi md_parent; /**< parent DB of a sub-DB */
704 unsigned int md_dirty; /**< TRUE if DB was written in this txn */
707 /** A database transaction.
708 * Every operation requires a transaction handle.
711 pgno_t mt_next_pgno; /**< next unallocated page */
712 /** The ID of this transaction. IDs are integers incrementing from 1.
713 * Only committed write transactions increment the ID. If a transaction
714 * aborts, the ID may be re-used by the next writer.
717 MDB_env *mt_env; /**< the DB environment */
718 /** The list of pages that became unused during this transaction.
723 ID2L dirty_list; /**< modified pages */
724 MDB_reader *reader; /**< this thread's slot in the reader table */
726 /** Array of records for each DB known in the environment. */
728 /** Array of MDB_db records for each known DB */
730 /** Number of DB records in use. This number only ever increments;
731 * we don't decrement it when individual DB handles are closed.
735 /** @defgroup mdb_txn Transaction Flags
739 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
740 #define MDB_TXN_ERROR 0x02 /**< an error has occurred */
742 unsigned int mt_flags; /**< @ref mdb_txn */
743 /** Tracks which of the two meta pages was used at the start
744 * of this transaction.
746 unsigned int mt_toggle;
749 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
750 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
751 * raise this on a 64 bit machine.
753 #define CURSOR_STACK 32
757 /** Cursors are used for all DB operations */
759 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
760 struct MDB_xcursor *mc_xcursor;
761 /** The transaction that owns this cursor */
763 /** The database handle this cursor operates on */
765 /** The database record for this cursor */
767 /** The database auxiliary record for this cursor */
769 unsigned short mc_snum; /**< number of pushed pages */
770 unsigned short mc_top; /**< index of top page, mc_snum-1 */
771 /** @defgroup mdb_cursor Cursor Flags
773 * Cursor state flags.
776 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
777 #define C_EOF 0x02 /**< No more data */
779 unsigned int mc_flags; /**< @ref mdb_cursor */
780 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
781 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
784 /** Context for sorted-dup records.
785 * We could have gone to a fully recursive design, with arbitrarily
786 * deep nesting of sub-databases. But for now we only handle these
787 * levels - main DB, optional sub-DB, sorted-duplicate DB.
789 typedef struct MDB_xcursor {
790 /** A sub-cursor for traversing the Dup DB */
791 MDB_cursor mx_cursor;
792 /** The database record for this Dup DB */
794 /** The auxiliary DB record for this Dup DB */
798 /** A set of pages freed by an earlier transaction. */
799 typedef struct MDB_oldpages {
800 /** Usually we only read one record from the FREEDB at a time, but
801 * in case we read more, this will chain them together.
803 struct MDB_oldpages *mo_next;
804 /** The ID of the transaction in which these pages were freed. */
806 /** An #IDL of the pages */
807 pgno_t mo_pages[1]; /* dynamic */
810 /** The database environment. */
812 HANDLE me_fd; /**< The main data file */
813 HANDLE me_lfd; /**< The lock file */
814 HANDLE me_mfd; /**< just for writing the meta pages */
815 /** Failed to update the meta page. Probably an I/O error. */
816 #define MDB_FATAL_ERROR 0x80000000U
817 uint32_t me_flags; /**< @ref mdb_env */
818 uint32_t me_extrapad; /**< unused for now */
819 unsigned int me_maxreaders; /**< size of the reader table */
820 MDB_dbi me_numdbs; /**< number of DBs opened */
821 MDB_dbi me_maxdbs; /**< size of the DB table */
822 char *me_path; /**< path to the DB files */
823 char *me_map; /**< the memory map of the data file */
824 MDB_txninfo *me_txns; /**< the memory map of the lock file */
825 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
826 MDB_txn *me_txn; /**< current write transaction */
827 size_t me_mapsize; /**< size of the data memory map */
828 off_t me_size; /**< current file size */
829 pgno_t me_maxpg; /**< me_mapsize / me_psize */
830 unsigned int me_psize; /**< size of a page, from #GET_PAGESIZE */
831 unsigned int me_db_toggle; /**< which DB table is current */
832 MDB_dbx *me_dbxs; /**< array of static DB info */
833 MDB_db *me_dbs[2]; /**< two arrays of MDB_db info */
834 MDB_oldpages *me_pghead; /**< list of old page records */
835 pthread_key_t me_txkey; /**< thread-key for readers */
836 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
837 /** IDL of pages that became unused in a write txn */
838 pgno_t me_free_pgs[MDB_IDL_UM_SIZE];
839 /** ID2L of pages that were written during a write txn */
840 ID2 me_dirty_list[MDB_IDL_UM_SIZE];
841 /** rwlock for the DB tables, if #LAZY_LOCKS is false */
842 LAZY_RWLOCK_DEF(me_dblock)
844 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
848 sem_t *me_rmutex; /* Apple doesn't support shared mutexes */
852 /** max number of pages to commit in one writev() call */
853 #define MDB_COMMIT_PAGES 64
855 static MDB_page *mdb_page_alloc(MDB_cursor *mc, int num);
856 static MDB_page *mdb_page_new(MDB_cursor *mc, uint32_t flags, int num);
857 static int mdb_page_touch(MDB_cursor *mc);
859 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
860 static int mdb_page_search_root(MDB_cursor *mc,
861 MDB_val *key, int modify);
862 static int mdb_page_search(MDB_cursor *mc,
863 MDB_val *key, int modify);
864 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
865 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
868 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
869 static int mdb_env_read_meta(MDB_env *env, int *which);
870 static int mdb_env_write_meta(MDB_txn *txn);
872 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
873 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
874 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags);
875 static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
876 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
877 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
878 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
879 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
881 static int mdb_rebalance(MDB_cursor *mc);
882 static int mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
884 static void mdb_cursor_pop(MDB_cursor *mc);
885 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
887 static int mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
888 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
889 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
890 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
891 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
893 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
894 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
896 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
897 static void mdb_xcursor_init0(MDB_cursor *mc);
898 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
900 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
903 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
907 static SECURITY_DESCRIPTOR mdb_null_sd;
908 static SECURITY_ATTRIBUTES mdb_all_sa;
909 static int mdb_sec_inited;
912 /** Return the library version info. */
914 mdb_version(int *major, int *minor, int *patch)
916 if (major) *major = MDB_VERSION_MAJOR;
917 if (minor) *minor = MDB_VERSION_MINOR;
918 if (patch) *patch = MDB_VERSION_PATCH;
919 return MDB_VERSION_STRING;
922 /** Table of descriptions for MDB @ref errors */
923 static char *const mdb_errstr[] = {
924 "MDB_KEYEXIST: Key/data pair already exists",
925 "MDB_NOTFOUND: No matching key/data pair found",
926 "MDB_PAGE_NOTFOUND: Requested page not found",
927 "MDB_CORRUPTED: Located page was wrong type",
928 "MDB_PANIC: Update of meta page failed",
929 "MDB_VERSION_MISMATCH: Database environment version mismatch"
933 mdb_strerror(int err)
936 return ("Successful return: 0");
938 if (err >= MDB_KEYEXIST && err <= MDB_VERSION_MISMATCH)
939 return mdb_errstr[err - MDB_KEYEXIST];
941 return strerror(err);
945 /** Display a key in hexadecimal and return the address of the result.
946 * @param[in] key the key to display
947 * @param[in] buf the buffer to write into. Should always be #DKBUF.
948 * @return The key in hexadecimal form.
951 mdb_dkey(MDB_val *key, char *buf)
954 unsigned char *c = key->mv_data;
956 if (key->mv_size > MAXKEYSIZE)
958 /* may want to make this a dynamic check: if the key is mostly
959 * printable characters, print it as-is instead of converting to hex.
962 for (i=0; i<key->mv_size; i++)
963 ptr += sprintf(ptr, "%02x", *c++);
965 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
972 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
974 return txn->mt_dbxs[dbi].md_cmp(a, b);
978 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
980 if (txn->mt_dbxs[dbi].md_dcmp)
981 return txn->mt_dbxs[dbi].md_dcmp(a, b);
983 return EINVAL; /* too bad you can't distinguish this from a valid result */
986 /** Allocate pages for writing.
987 * If there are free pages available from older transactions, they
988 * will be re-used first. Otherwise a new page will be allocated.
989 * @param[in] mc cursor A cursor handle identifying the transaction and
990 * database for which we are allocating.
991 * @param[in] num the number of pages to allocate.
992 * @return Address of the allocated page(s). Requests for multiple pages
993 * will always be satisfied by a single contiguous chunk of memory.
996 mdb_page_alloc(MDB_cursor *mc, int num)
998 MDB_txn *txn = mc->mc_txn;
1000 pgno_t pgno = P_INVALID;
1003 if (txn->mt_txnid > 2) {
1005 if (!txn->mt_env->me_pghead && mc->mc_dbi != FREE_DBI &&
1006 txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
1007 /* See if there's anything in the free DB */
1010 txnid_t *kptr, oldest;
1012 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1013 mdb_page_search(&m2, NULL, 0);
1014 leaf = NODEPTR(m2.mc_pg[m2.mc_top], 0);
1015 kptr = (txnid_t *)NODEKEY(leaf);
1019 oldest = txn->mt_txnid - 1;
1020 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
1021 txnid_t mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
1022 if (mr && mr < oldest)
1027 if (oldest > *kptr) {
1028 /* It's usable, grab it.
1034 mdb_node_read(txn, leaf, &data);
1035 idl = (ID *) data.mv_data;
1036 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
1037 mop->mo_next = txn->mt_env->me_pghead;
1038 mop->mo_txnid = *kptr;
1039 txn->mt_env->me_pghead = mop;
1040 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
1045 DPRINTF("IDL read txn %zu root %zu num %zu",
1046 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1047 for (i=0; i<idl[0]; i++) {
1048 DPRINTF("IDL %zu", idl[i+1]);
1052 /* drop this IDL from the DB */
1053 m2.mc_ki[m2.mc_top] = 0;
1054 m2.mc_flags = C_INITIALIZED;
1055 mdb_cursor_del(&m2, 0);
1058 if (txn->mt_env->me_pghead) {
1059 MDB_oldpages *mop = txn->mt_env->me_pghead;
1061 /* FIXME: For now, always use fresh pages. We
1062 * really ought to search the free list for a
1067 /* peel pages off tail, so we only have to truncate the list */
1068 pgno = MDB_IDL_LAST(mop->mo_pages);
1069 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
1071 if (mop->mo_pages[2] > mop->mo_pages[1])
1072 mop->mo_pages[0] = 0;
1076 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
1077 txn->mt_env->me_pghead = mop->mo_next;
1084 if (pgno == P_INVALID) {
1085 /* DB size is maxed out */
1086 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg) {
1087 assert(txn->mt_next_pgno + num < txn->mt_env->me_maxpg);
1091 if (txn->mt_env->me_dpages && num == 1) {
1092 np = txn->mt_env->me_dpages;
1093 txn->mt_env->me_dpages = np->mp_next;
1095 if ((np = malloc(txn->mt_env->me_psize * num )) == NULL)
1098 if (pgno == P_INVALID) {
1099 np->mp_pgno = txn->mt_next_pgno;
1100 txn->mt_next_pgno += num;
1104 mid.mid = np->mp_pgno;
1106 mdb_mid2l_insert(txn->mt_u.dirty_list, &mid);
1111 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1112 * @param[in] mc cursor pointing to the page to be touched
1113 * @return 0 on success, non-zero on failure.
1116 mdb_page_touch(MDB_cursor *mc)
1118 MDB_page *mp = mc->mc_pg[mc->mc_top];
1121 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1123 if ((np = mdb_page_alloc(mc, 1)) == NULL)
1125 DPRINTF("touched db %u page %zu -> %zu", mc->mc_dbi, mp->mp_pgno, np->mp_pgno);
1126 assert(mp->mp_pgno != np->mp_pgno);
1127 mdb_midl_append(mc->mc_txn->mt_free_pgs, mp->mp_pgno);
1129 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1132 mp->mp_flags |= P_DIRTY;
1134 mc->mc_pg[mc->mc_top] = mp;
1135 /** If this page has a parent, update the parent to point to
1139 SETPGNO(NODEPTR(mc->mc_pg[mc->mc_top-1], mc->mc_ki[mc->mc_top-1]), mp->mp_pgno);
1145 mdb_env_sync(MDB_env *env, int force)
1148 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1149 if (fdatasync(env->me_fd))
1156 mdb_txn_reset0(MDB_txn *txn);
1158 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
1159 * @param[in] txn the transaction handle to initialize
1160 * @return 0 on success, non-zero on failure. This can only
1161 * fail for read-only transactions, and then only if the
1162 * reader table is full.
1165 mdb_txn_renew0(MDB_txn *txn)
1167 MDB_env *env = txn->mt_env;
1169 if (txn->mt_flags & MDB_TXN_RDONLY) {
1170 MDB_reader *r = pthread_getspecific(env->me_txkey);
1173 pid_t pid = getpid();
1174 pthread_t tid = pthread_self();
1177 for (i=0; i<env->me_txns->mti_numreaders; i++)
1178 if (env->me_txns->mti_readers[i].mr_pid == 0)
1180 if (i == env->me_maxreaders) {
1181 UNLOCK_MUTEX_R(env);
1184 env->me_txns->mti_readers[i].mr_pid = pid;
1185 env->me_txns->mti_readers[i].mr_tid = tid;
1186 if (i >= env->me_txns->mti_numreaders)
1187 env->me_txns->mti_numreaders = i+1;
1188 UNLOCK_MUTEX_R(env);
1189 r = &env->me_txns->mti_readers[i];
1190 pthread_setspecific(env->me_txkey, r);
1192 txn->mt_txnid = env->me_txns->mti_txnid;
1193 txn->mt_toggle = env->me_txns->mti_me_toggle;
1194 r->mr_txnid = txn->mt_txnid;
1195 txn->mt_u.reader = r;
1199 txn->mt_txnid = env->me_txns->mti_txnid+1;
1200 txn->mt_toggle = env->me_txns->mti_me_toggle;
1201 txn->mt_u.dirty_list = env->me_dirty_list;
1202 txn->mt_u.dirty_list[0].mid = 0;
1203 txn->mt_free_pgs = env->me_free_pgs;
1204 txn->mt_free_pgs[0] = 0;
1205 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1209 /* Copy the DB arrays */
1210 LAZY_RWLOCK_RDLOCK(&env->me_dblock);
1211 txn->mt_numdbs = env->me_numdbs;
1212 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
1213 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
1214 if (txn->mt_numdbs > 2)
1215 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
1216 (txn->mt_numdbs - 2) * sizeof(MDB_db));
1217 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1223 mdb_txn_renew(MDB_txn *txn)
1230 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
1231 DPUTS("environment had fatal error, must shutdown!");
1235 rc = mdb_txn_renew0(txn);
1236 if (rc == MDB_SUCCESS) {
1237 DPRINTF("renew txn %zu%c %p on mdbenv %p, root page %zu",
1238 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1239 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1245 mdb_txn_begin(MDB_env *env, unsigned int flags, MDB_txn **ret)
1250 if (env->me_flags & MDB_FATAL_ERROR) {
1251 DPUTS("environment had fatal error, must shutdown!");
1254 if ((txn = calloc(1, sizeof(MDB_txn) + env->me_maxdbs * sizeof(MDB_db))) == NULL) {
1255 DPRINTF("calloc: %s", strerror(ErrCode()));
1258 txn->mt_dbs = (MDB_db *)(txn+1);
1259 if (flags & MDB_RDONLY) {
1260 txn->mt_flags |= MDB_TXN_RDONLY;
1264 rc = mdb_txn_renew0(txn);
1269 DPRINTF("begin txn %zu%c %p on mdbenv %p, root page %zu",
1270 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1271 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
1277 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
1278 * @param[in] txn the transaction handle to reset
1281 mdb_txn_reset0(MDB_txn *txn)
1283 MDB_env *env = txn->mt_env;
1285 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1286 txn->mt_u.reader->mr_txnid = 0;
1293 /* return all dirty pages to dpage list */
1294 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1295 dp = txn->mt_u.dirty_list[i].mptr;
1296 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1297 dp->mp_next = txn->mt_env->me_dpages;
1298 txn->mt_env->me_dpages = dp;
1300 /* large pages just get freed directly */
1305 while ((mop = txn->mt_env->me_pghead)) {
1306 txn->mt_env->me_pghead = mop->mo_next;
1311 for (dbi=2; dbi<env->me_numdbs; dbi++)
1312 env->me_dbxs[dbi].md_dirty = 0;
1313 /* The writer mutex was locked in mdb_txn_begin. */
1314 UNLOCK_MUTEX_W(env);
1319 mdb_txn_reset(MDB_txn *txn)
1324 DPRINTF("reset txn %zu%c %p on mdbenv %p, root page %zu",
1325 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1326 (void *) txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1328 mdb_txn_reset0(txn);
1332 mdb_txn_abort(MDB_txn *txn)
1337 DPRINTF("abort txn %zu%c %p on mdbenv %p, root page %zu",
1338 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1339 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1341 mdb_txn_reset0(txn);
1346 mdb_txn_commit(MDB_txn *txn)
1357 assert(txn != NULL);
1358 assert(txn->mt_env != NULL);
1362 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1367 if (txn != env->me_txn) {
1368 DPUTS("attempt to commit unknown transaction");
1373 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1374 DPUTS("error flag is set, can't commit");
1379 if (!txn->mt_u.dirty_list[0].mid)
1382 DPRINTF("committing txn %zu %p on mdbenv %p, root page %zu",
1383 txn->mt_txnid, (void *)txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
1385 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1387 /* should only be one record now */
1388 if (env->me_pghead) {
1389 /* make sure first page of freeDB is touched and on freelist */
1390 mdb_page_search(&mc, NULL, 1);
1392 /* save to free list */
1393 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
1397 /* make sure last page of freeDB is touched and on freelist */
1398 key.mv_size = MAXKEYSIZE+1;
1400 mdb_page_search(&mc, &key, 1);
1402 mdb_midl_sort(txn->mt_free_pgs);
1406 ID *idl = txn->mt_free_pgs;
1407 DPRINTF("IDL write txn %zu root %zu num %zu",
1408 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1409 for (i=0; i<idl[0]; i++) {
1410 DPRINTF("IDL %zu", idl[i+1]);
1414 /* write to last page of freeDB */
1415 key.mv_size = sizeof(pgno_t);
1416 key.mv_data = &txn->mt_txnid;
1417 data.mv_data = txn->mt_free_pgs;
1418 /* The free list can still grow during this call,
1419 * despite the pre-emptive touches above. So check
1420 * and make sure the entire thing got written.
1423 i = txn->mt_free_pgs[0];
1424 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
1425 rc = mdb_cursor_put(&mc, &key, &data, 0);
1430 } while (i != txn->mt_free_pgs[0]);
1432 /* should only be one record now */
1433 if (env->me_pghead) {
1437 mop = env->me_pghead;
1438 key.mv_size = sizeof(pgno_t);
1439 key.mv_data = &mop->mo_txnid;
1440 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
1441 data.mv_data = mop->mo_pages;
1442 mdb_cursor_put(&mc, &key, &data, 0);
1443 free(env->me_pghead);
1444 env->me_pghead = NULL;
1447 /* Update DB root pointers. Their pages have already been
1448 * touched so this is all in-place and cannot fail.
1453 data.mv_size = sizeof(MDB_db);
1455 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
1456 for (i = 2; i < txn->mt_numdbs; i++) {
1457 if (txn->mt_dbxs[i].md_dirty) {
1458 data.mv_data = &txn->mt_dbs[i];
1459 mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
1464 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
1470 /* Windows actually supports scatter/gather I/O, but only on
1471 * unbuffered file handles. Since we're relying on the OS page
1472 * cache for all our data, that's self-defeating. So we just
1473 * write pages one at a time. We use the ov structure to set
1474 * the write offset, to at least save the overhead of a Seek
1478 memset(&ov, 0, sizeof(ov));
1479 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1481 dp = txn->mt_u.dirty_list[i].mptr;
1482 DPRINTF("committing page %zu", dp->mp_pgno);
1483 size = dp->mp_pgno * env->me_psize;
1484 ov.Offset = size & 0xffffffff;
1485 ov.OffsetHigh = size >> 16;
1486 ov.OffsetHigh >>= 16;
1487 /* clear dirty flag */
1488 dp->mp_flags &= ~P_DIRTY;
1489 wsize = env->me_psize;
1490 if (IS_OVERFLOW(dp)) wsize *= dp->mp_pages;
1491 rc = WriteFile(env->me_fd, dp, wsize, NULL, &ov);
1494 DPRINTF("WriteFile: %d", n);
1501 struct iovec iov[MDB_COMMIT_PAGES];
1505 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1506 dp = txn->mt_u.dirty_list[i].mptr;
1507 if (dp->mp_pgno != next) {
1509 DPRINTF("committing %u dirty pages", n);
1510 rc = writev(env->me_fd, iov, n);
1514 DPUTS("short write, filesystem full?");
1516 DPRINTF("writev: %s", strerror(n));
1523 lseek(env->me_fd, dp->mp_pgno * env->me_psize, SEEK_SET);
1526 DPRINTF("committing page %zu", dp->mp_pgno);
1527 iov[n].iov_len = env->me_psize;
1528 if (IS_OVERFLOW(dp)) iov[n].iov_len *= dp->mp_pages;
1529 iov[n].iov_base = dp;
1530 size += iov[n].iov_len;
1531 next = dp->mp_pgno + (IS_OVERFLOW(dp) ? dp->mp_pages : 1);
1532 /* clear dirty flag */
1533 dp->mp_flags &= ~P_DIRTY;
1534 if (++n >= MDB_COMMIT_PAGES) {
1544 DPRINTF("committing %u dirty pages", n);
1545 rc = writev(env->me_fd, iov, n);
1549 DPUTS("short write, filesystem full?");
1551 DPRINTF("writev: %s", strerror(n));
1558 /* Drop the dirty pages.
1560 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1561 dp = txn->mt_u.dirty_list[i].mptr;
1562 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1563 dp->mp_next = txn->mt_env->me_dpages;
1564 txn->mt_env->me_dpages = dp;
1568 txn->mt_u.dirty_list[i].mid = 0;
1570 txn->mt_u.dirty_list[0].mid = 0;
1572 if ((n = mdb_env_sync(env, 0)) != 0 ||
1573 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
1580 /* update the DB tables */
1582 int toggle = !env->me_db_toggle;
1586 ip = &env->me_dbs[toggle][2];
1587 jp = &txn->mt_dbs[2];
1588 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1589 for (i = 2; i < txn->mt_numdbs; i++) {
1590 if (ip->md_root != jp->md_root)
1595 for (i = 2; i < txn->mt_numdbs; i++) {
1596 if (txn->mt_dbxs[i].md_dirty)
1597 txn->mt_dbxs[i].md_dirty = 0;
1599 env->me_db_toggle = toggle;
1600 env->me_numdbs = txn->mt_numdbs;
1601 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1604 UNLOCK_MUTEX_W(env);
1610 /** Read the environment parameters of a DB environment before
1611 * mapping it into memory.
1612 * @param[in] env the environment handle
1613 * @param[out] meta address of where to store the meta information
1614 * @return 0 on success, non-zero on failure.
1617 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
1619 char page[PAGESIZE];
1624 /* We don't know the page size yet, so use a minimum value.
1628 if (!ReadFile(env->me_fd, page, PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
1630 if ((rc = read(env->me_fd, page, PAGESIZE)) == 0)
1635 else if (rc != PAGESIZE) {
1639 DPRINTF("read: %s", strerror(err));
1643 p = (MDB_page *)page;
1645 if (!F_ISSET(p->mp_flags, P_META)) {
1646 DPRINTF("page %zu not a meta page", p->mp_pgno);
1651 if (m->mm_magic != MDB_MAGIC) {
1652 DPUTS("meta has invalid magic");
1656 if (m->mm_version != MDB_VERSION) {
1657 DPRINTF("database is version %u, expected version %u",
1658 m->mm_version, MDB_VERSION);
1659 return MDB_VERSION_MISMATCH;
1662 memcpy(meta, m, sizeof(*m));
1666 /** Write the environment parameters of a freshly created DB environment.
1667 * @param[in] env the environment handle
1668 * @param[out] meta address of where to store the meta information
1669 * @return 0 on success, non-zero on failure.
1672 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
1679 DPUTS("writing new meta page");
1681 GET_PAGESIZE(psize);
1683 meta->mm_magic = MDB_MAGIC;
1684 meta->mm_version = MDB_VERSION;
1685 meta->mm_psize = psize;
1686 meta->mm_last_pg = 1;
1687 meta->mm_flags = env->me_flags & 0xffff;
1688 meta->mm_flags |= MDB_INTEGERKEY;
1689 meta->mm_dbs[0].md_root = P_INVALID;
1690 meta->mm_dbs[1].md_root = P_INVALID;
1692 p = calloc(2, psize);
1694 p->mp_flags = P_META;
1697 memcpy(m, meta, sizeof(*meta));
1699 q = (MDB_page *)((char *)p + psize);
1702 q->mp_flags = P_META;
1705 memcpy(m, meta, sizeof(*meta));
1710 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
1711 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
1714 rc = write(env->me_fd, p, psize * 2);
1715 rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
1721 /** Update the environment info to commit a transaction.
1722 * @param[in] txn the transaction that's being committed
1723 * @return 0 on success, non-zero on failure.
1726 mdb_env_write_meta(MDB_txn *txn)
1729 MDB_meta meta, metab;
1731 int rc, len, toggle;
1737 assert(txn != NULL);
1738 assert(txn->mt_env != NULL);
1740 toggle = !txn->mt_toggle;
1741 DPRINTF("writing meta page %d for root page %zu",
1742 toggle, txn->mt_dbs[MAIN_DBI].md_root);
1746 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
1747 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
1749 ptr = (char *)&meta;
1750 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
1751 len = sizeof(MDB_meta) - off;
1754 meta.mm_dbs[0] = txn->mt_dbs[0];
1755 meta.mm_dbs[1] = txn->mt_dbs[1];
1756 meta.mm_last_pg = txn->mt_next_pgno - 1;
1757 meta.mm_txnid = txn->mt_txnid;
1760 off += env->me_psize;
1763 /* Write to the SYNC fd */
1766 memset(&ov, 0, sizeof(ov));
1768 WriteFile(env->me_mfd, ptr, len, (DWORD *)&rc, &ov);
1771 rc = pwrite(env->me_mfd, ptr, len, off);
1776 DPUTS("write failed, disk error?");
1777 /* On a failure, the pagecache still contains the new data.
1778 * Write some old data back, to prevent it from being used.
1779 * Use the non-SYNC fd; we know it will fail anyway.
1781 meta.mm_last_pg = metab.mm_last_pg;
1782 meta.mm_txnid = metab.mm_txnid;
1784 WriteFile(env->me_fd, ptr, len, NULL, &ov);
1786 r2 = pwrite(env->me_fd, ptr, len, off);
1788 env->me_flags |= MDB_FATAL_ERROR;
1791 /* Memory ordering issues are irrelevant; since the entire writer
1792 * is wrapped by wmutex, all of these changes will become visible
1793 * after the wmutex is unlocked. Since the DB is multi-version,
1794 * readers will get consistent data regardless of how fresh or
1795 * how stale their view of these values is.
1797 LAZY_MUTEX_LOCK(&env->me_txns->mti_mutex);
1798 txn->mt_env->me_txns->mti_me_toggle = toggle;
1799 txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
1800 LAZY_MUTEX_UNLOCK(&env->me_txns->mti_mutex);
1805 /** Check both meta pages to see which one is newer.
1806 * @param[in] env the environment handle
1807 * @param[out] which address of where to store the meta toggle ID
1808 * @return 0 on success, non-zero on failure.
1811 mdb_env_read_meta(MDB_env *env, int *which)
1815 assert(env != NULL);
1817 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1820 DPRINTF("Using meta page %d", toggle);
1827 mdb_env_create(MDB_env **env)
1831 e = calloc(1, sizeof(MDB_env));
1835 e->me_maxreaders = DEFAULT_READERS;
1837 e->me_fd = INVALID_HANDLE_VALUE;
1838 e->me_lfd = INVALID_HANDLE_VALUE;
1839 e->me_mfd = INVALID_HANDLE_VALUE;
1845 mdb_env_set_mapsize(MDB_env *env, size_t size)
1849 env->me_mapsize = size;
1854 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
1858 env->me_maxdbs = dbs;
1863 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
1865 if (env->me_map || readers < 1)
1867 env->me_maxreaders = readers;
1872 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
1874 if (!env || !readers)
1876 *readers = env->me_maxreaders;
1880 /** Further setup required for opening an MDB environment
1883 mdb_env_open2(MDB_env *env, unsigned int flags)
1885 int i, newenv = 0, toggle;
1889 env->me_flags = flags;
1891 memset(&meta, 0, sizeof(meta));
1893 if ((i = mdb_env_read_header(env, &meta)) != 0) {
1896 DPUTS("new mdbenv");
1900 if (!env->me_mapsize) {
1901 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
1907 LONG sizelo, sizehi;
1908 sizelo = env->me_mapsize & 0xffffffff;
1909 sizehi = env->me_mapsize >> 16; /* pointless on WIN32, only needed on W64 */
1911 /* Windows won't create mappings for zero length files.
1912 * Just allocate the maxsize right now.
1915 SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
1916 if (!SetEndOfFile(env->me_fd))
1918 SetFilePointer(env->me_fd, 0, NULL, 0);
1920 mh = CreateFileMapping(env->me_fd, NULL, PAGE_READONLY,
1921 sizehi, sizelo, NULL);
1924 env->me_map = MapViewOfFileEx(mh, FILE_MAP_READ, 0, 0, env->me_mapsize,
1932 if (meta.mm_address && (flags & MDB_FIXEDMAP))
1934 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
1936 if (env->me_map == MAP_FAILED)
1941 meta.mm_mapsize = env->me_mapsize;
1942 if (flags & MDB_FIXEDMAP)
1943 meta.mm_address = env->me_map;
1944 i = mdb_env_init_meta(env, &meta);
1945 if (i != MDB_SUCCESS) {
1946 munmap(env->me_map, env->me_mapsize);
1950 env->me_psize = meta.mm_psize;
1952 env->me_maxpg = env->me_mapsize / env->me_psize;
1954 p = (MDB_page *)env->me_map;
1955 env->me_metas[0] = METADATA(p);
1956 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
1958 if ((i = mdb_env_read_meta(env, &toggle)) != 0)
1961 DPRINTF("opened database version %u, pagesize %u",
1962 env->me_metas[toggle]->mm_version, env->me_psize);
1963 DPRINTF("depth: %u", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_depth);
1964 DPRINTF("entries: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_entries);
1965 DPRINTF("branch pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_branch_pages);
1966 DPRINTF("leaf pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_leaf_pages);
1967 DPRINTF("overflow pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_overflow_pages);
1968 DPRINTF("root: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_root);
1974 /** Release a reader thread's slot in the reader lock table.
1975 * This function is called automatically when a thread exits.
1976 * Windows doesn't support destructor callbacks for thread-specific storage,
1977 * so this function is not compiled there.
1978 * @param[in] ptr This points to the slot in the reader lock table.
1981 mdb_env_reader_dest(void *ptr)
1983 MDB_reader *reader = ptr;
1985 reader->mr_txnid = 0;
1991 /** Downgrade the exclusive lock on the region back to shared */
1993 mdb_env_share_locks(MDB_env *env)
1997 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1999 env->me_txns->mti_me_toggle = toggle;
2000 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
2005 /* First acquire a shared lock. The Unlock will
2006 * then release the existing exclusive lock.
2008 memset(&ov, 0, sizeof(ov));
2009 LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov);
2010 UnlockFile(env->me_lfd, 0, 0, 1, 0);
2014 struct flock lock_info;
2015 /* The shared lock replaces the existing lock */
2016 memset((void *)&lock_info, 0, sizeof(lock_info));
2017 lock_info.l_type = F_RDLCK;
2018 lock_info.l_whence = SEEK_SET;
2019 lock_info.l_start = 0;
2020 lock_info.l_len = 1;
2021 fcntl(env->me_lfd, F_SETLK, &lock_info);
2025 #if defined(_WIN32) || defined(__APPLE__)
2027 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
2029 * @(#) $Revision: 5.1 $
2030 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
2031 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
2033 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
2037 * Please do not copyright this code. This code is in the public domain.
2039 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
2040 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
2041 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
2042 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
2043 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
2044 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
2045 * PERFORMANCE OF THIS SOFTWARE.
2048 * chongo <Landon Curt Noll> /\oo/\
2049 * http://www.isthe.com/chongo/
2051 * Share and Enjoy! :-)
2054 typedef unsigned long long mdb_hash_t;
2055 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
2057 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
2058 * @param[in] str string to hash
2059 * @param[in] hval initial value for hash
2060 * @return 64 bit hash
2062 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
2063 * hval arg on the first call.
2065 static inline mdb_hash_t
2066 mdb_hash_str(char *str, mdb_hash_t hval)
2068 unsigned char *s = (unsigned char *)str; /* unsigned string */
2070 * FNV-1a hash each octet of the string
2073 /* xor the bottom with the current octet */
2074 hval ^= (mdb_hash_t)*s++;
2076 /* multiply by the 64 bit FNV magic prime mod 2^64 */
2077 hval += (hval << 1) + (hval << 4) + (hval << 5) +
2078 (hval << 7) + (hval << 8) + (hval << 40);
2080 /* return our new hash value */
2084 /** Hash the string and output the hash in hex.
2085 * @param[in] str string to hash
2086 * @param[out] hexbuf an array of 17 chars to hold the hash
2089 mdb_hash_hex(char *str, char *hexbuf)
2092 mdb_hash_t h = mdb_hash_str(str, MDB_HASH_INIT);
2093 for (i=0; i<8; i++) {
2094 hexbuf += sprintf(hexbuf, "%02x", (unsigned int)h & 0xff);
2100 /** Open and/or initialize the lock region for the environment.
2101 * @param[in] env The MDB environment.
2102 * @param[in] lpath The pathname of the file used for the lock region.
2103 * @param[in] mode The Unix permissions for the file, if we create it.
2104 * @param[out] excl Set to true if we got an exclusive lock on the region.
2105 * @return 0 on success, non-zero on failure.
2108 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
2116 if ((env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
2117 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
2118 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
2122 /* Try to get exclusive lock. If we succeed, then
2123 * nobody is using the lock region and we should initialize it.
2126 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
2130 memset(&ov, 0, sizeof(ov));
2131 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
2137 size = GetFileSize(env->me_lfd, NULL);
2139 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
2143 /* Try to get exclusive lock. If we succeed, then
2144 * nobody is using the lock region and we should initialize it.
2147 struct flock lock_info;
2148 memset((void *)&lock_info, 0, sizeof(lock_info));
2149 lock_info.l_type = F_WRLCK;
2150 lock_info.l_whence = SEEK_SET;
2151 lock_info.l_start = 0;
2152 lock_info.l_len = 1;
2153 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
2157 lock_info.l_type = F_RDLCK;
2158 rc = fcntl(env->me_lfd, F_SETLKW, &lock_info);
2165 size = lseek(env->me_lfd, 0, SEEK_END);
2167 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
2168 if (size < rsize && *excl) {
2170 SetFilePointer(env->me_lfd, rsize, NULL, 0);
2171 if (!SetEndOfFile(env->me_lfd)) {
2176 if (ftruncate(env->me_lfd, rsize) != 0) {
2183 size = rsize - sizeof(MDB_txninfo);
2184 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
2189 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
2195 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
2197 if (!env->me_txns) {
2203 env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
2205 if (env->me_txns == MAP_FAILED) {
2213 if (!mdb_sec_inited) {
2214 InitializeSecurityDescriptor(&mdb_null_sd,
2215 SECURITY_DESCRIPTOR_REVISION);
2216 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
2217 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2218 mdb_all_sa.bInheritHandle = FALSE;
2219 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
2222 mdb_hash_hex(lpath, hexbuf);
2223 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", hexbuf);
2224 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
2225 if (!env->me_rmutex) {
2229 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", hexbuf);
2230 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
2231 if (!env->me_wmutex) {
2238 mdb_hash_hex(lpath, hexbuf);
2239 sprintf(env->me_txns->mti_rmname, "MDBr%s", hexbuf);
2240 if (sem_unlink(env->me_txns->mti_rmname)) {
2242 if (rc != ENOENT && rc != EINVAL)
2245 env->me_rmutex = sem_open(env->me_txns->mti_rmname, O_CREAT, mode, 1);
2246 if (!env->me_rmutex) {
2250 sprintf(env->me_txns->mti_wmname, "MDBw%s", hexbuf);
2251 if (sem_unlink(env->me_txns->mti_wmname)) {
2253 if (rc != ENOENT && rc != EINVAL)
2256 env->me_wmutex = sem_open(env->me_txns->mti_wmname, O_CREAT, mode, 1);
2257 if (!env->me_wmutex) {
2261 #else /* __APPLE__ */
2262 pthread_mutexattr_t mattr;
2264 pthread_mutexattr_init(&mattr);
2265 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
2269 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
2270 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
2271 #endif /* __APPLE__ */
2273 env->me_txns->mti_version = MDB_VERSION;
2274 env->me_txns->mti_magic = MDB_MAGIC;
2275 env->me_txns->mti_txnid = 0;
2276 env->me_txns->mti_numreaders = 0;
2277 env->me_txns->mti_me_toggle = 0;
2280 if (env->me_txns->mti_magic != MDB_MAGIC) {
2281 DPUTS("lock region has invalid magic");
2285 if (env->me_txns->mti_version != MDB_VERSION) {
2286 DPRINTF("lock region is version %u, expected version %u",
2287 env->me_txns->mti_version, MDB_VERSION);
2288 rc = MDB_VERSION_MISMATCH;
2292 if (rc != EACCES && rc != EAGAIN) {
2296 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
2297 if (!env->me_rmutex) {
2301 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
2302 if (!env->me_wmutex) {
2308 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
2309 if (!env->me_rmutex) {
2313 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
2314 if (!env->me_wmutex) {
2324 env->me_lfd = INVALID_HANDLE_VALUE;
2329 /** The name of the lock file in the DB environment */
2330 #define LOCKNAME "/lock.mdb"
2331 /** The name of the data file in the DB environment */
2332 #define DATANAME "/data.mdb"
2334 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
2336 int oflags, rc, len, excl;
2337 char *lpath, *dpath;
2340 lpath = malloc(len + sizeof(LOCKNAME) + len + sizeof(DATANAME));
2343 dpath = lpath + len + sizeof(LOCKNAME);
2344 sprintf(lpath, "%s" LOCKNAME, path);
2345 sprintf(dpath, "%s" DATANAME, path);
2347 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
2352 if (F_ISSET(flags, MDB_RDONLY)) {
2353 oflags = GENERIC_READ;
2354 len = OPEN_EXISTING;
2356 oflags = GENERIC_READ|GENERIC_WRITE;
2359 mode = FILE_ATTRIBUTE_NORMAL;
2360 if ((env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2361 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2366 if (F_ISSET(flags, MDB_RDONLY))
2369 oflags = O_RDWR | O_CREAT;
2371 if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
2377 if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
2378 /* synchronous fd for meta writes */
2380 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2381 mode |= FILE_FLAG_WRITE_THROUGH;
2382 if ((env->me_mfd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2383 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2388 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2389 oflags |= MDB_DSYNC;
2390 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
2395 env->me_path = strdup(path);
2396 DPRINTF("opened dbenv %p", (void *) env);
2397 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
2398 LAZY_RWLOCK_INIT(&env->me_dblock, NULL);
2400 mdb_env_share_locks(env);
2401 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
2402 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
2403 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
2409 if (env->me_fd != INVALID_HANDLE_VALUE) {
2411 env->me_fd = INVALID_HANDLE_VALUE;
2413 if (env->me_lfd != INVALID_HANDLE_VALUE) {
2415 env->me_lfd = INVALID_HANDLE_VALUE;
2423 mdb_env_close(MDB_env *env)
2430 while (env->me_dpages) {
2431 dp = env->me_dpages;
2432 env->me_dpages = dp->mp_next;
2436 free(env->me_dbs[1]);
2437 free(env->me_dbs[0]);
2441 LAZY_RWLOCK_DESTROY(&env->me_dblock);
2442 pthread_key_delete(env->me_txkey);
2445 munmap(env->me_map, env->me_mapsize);
2450 pid_t pid = getpid();
2452 for (i=0; i<env->me_txns->mti_numreaders; i++)
2453 if (env->me_txns->mti_readers[i].mr_pid == pid)
2454 env->me_txns->mti_readers[i].mr_pid = 0;
2455 munmap(env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
2461 /** Compare two items pointing at aligned size_t's */
2463 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
2465 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
2466 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
2469 /** Compare two items pointing at aligned int's */
2471 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
2473 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
2474 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
2477 /** Compare two items pointing at ints of unknown alignment.
2478 * Nodes and keys are guaranteed to be 2-byte aligned.
2481 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
2483 #if BYTE_ORDER == LITTLE_ENDIAN
2484 unsigned short *u, *c;
2487 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
2488 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
2491 } while(!x && u > (unsigned short *)a->mv_data);
2494 return memcmp(a->mv_data, b->mv_data, a->mv_size);
2498 /** Compare two items lexically */
2500 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
2507 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
2513 diff = memcmp(a->mv_data, b->mv_data, len);
2514 return diff ? diff : len_diff<0 ? -1 : len_diff;
2517 /** Compare two items in reverse byte order */
2519 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
2521 const unsigned char *p1, *p2, *p1_lim;
2525 p1_lim = (const unsigned char *)a->mv_data;
2526 p1 = (const unsigned char *)a->mv_data + a->mv_size;
2527 p2 = (const unsigned char *)b->mv_data + b->mv_size;
2529 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
2535 while (p1 > p1_lim) {
2536 diff = *--p1 - *--p2;
2540 return len_diff<0 ? -1 : len_diff;
2543 /** Search for key within a page, using binary search.
2544 * Returns the smallest entry larger or equal to the key.
2545 * If exactp is non-null, stores whether the found entry was an exact match
2546 * in *exactp (1 or 0).
2547 * Updates the cursor index with the index of the found entry.
2548 * If no entry larger or equal to the key is found, returns NULL.
2551 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
2553 unsigned int i = 0, nkeys;
2556 MDB_page *mp = mc->mc_pg[mc->mc_top];
2557 MDB_node *node = NULL;
2562 nkeys = NUMKEYS(mp);
2564 DPRINTF("searching %u keys in %s page %zu",
2565 nkeys, IS_LEAF(mp) ? "leaf" : "branch",
2570 low = IS_LEAF(mp) ? 0 : 1;
2572 cmp = mc->mc_dbx->md_cmp;
2574 /* Branch pages have no data, so if using integer keys,
2575 * alignment is guaranteed. Use faster mdb_cmp_int.
2577 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
2578 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
2585 nodekey.mv_size = mc->mc_db->md_pad;
2586 node = NODEPTR(mp, 0); /* fake */
2587 while (low <= high) {
2588 i = (low + high) >> 1;
2589 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
2590 rc = cmp(key, &nodekey);
2591 DPRINTF("found leaf index %u [%s], rc = %i",
2592 i, DKEY(&nodekey), rc);
2601 while (low <= high) {
2602 i = (low + high) >> 1;
2604 node = NODEPTR(mp, i);
2605 nodekey.mv_size = NODEKSZ(node);
2606 nodekey.mv_data = NODEKEY(node);
2608 rc = cmp(key, &nodekey);
2611 DPRINTF("found leaf index %u [%s], rc = %i",
2612 i, DKEY(&nodekey), rc);
2614 DPRINTF("found branch index %u [%s -> %zu], rc = %i",
2615 i, DKEY(&nodekey), NODEPGNO(node), rc);
2626 if (rc > 0) { /* Found entry is less than the key. */
2627 i++; /* Skip to get the smallest entry larger than key. */
2629 node = NODEPTR(mp, i);
2632 *exactp = (rc == 0);
2633 /* store the key index */
2634 mc->mc_ki[mc->mc_top] = i;
2636 /* There is no entry larger or equal to the key. */
2639 /* nodeptr is fake for LEAF2 */
2643 /** Pop a page off the top of the cursor's stack. */
2645 mdb_cursor_pop(MDB_cursor *mc)
2650 top = mc->mc_pg[mc->mc_top];
2655 DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
2656 mc->mc_dbi, (void *) mc);
2660 /** Push a page onto the top of the cursor's stack. */
2662 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
2664 DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
2665 mc->mc_dbi, (void *) mc);
2667 if (mc->mc_snum >= CURSOR_STACK) {
2668 assert(mc->mc_snum < CURSOR_STACK);
2672 mc->mc_top = mc->mc_snum++;
2673 mc->mc_pg[mc->mc_top] = mp;
2674 mc->mc_ki[mc->mc_top] = 0;
2679 /** Find the address of the page corresponding to a given page number.
2680 * @param[in] txn the transaction for this access.
2681 * @param[in] pgno the page number for the page to retrieve.
2682 * @param[out] ret address of a pointer where the page's address will be stored.
2683 * @return 0 on success, non-zero on failure.
2686 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
2690 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
2692 x = mdb_mid2l_search(txn->mt_u.dirty_list, pgno);
2693 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
2694 p = txn->mt_u.dirty_list[x].mptr;
2698 if (pgno <= txn->mt_env->me_metas[txn->mt_toggle]->mm_last_pg)
2699 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
2703 DPRINTF("page %zu not found", pgno);
2706 return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
2709 /** Search for the page a given key should be in.
2710 * Pushes parent pages on the cursor stack. This function continues a
2711 * search on a cursor that has already been initialized. (Usually by
2712 * #mdb_page_search() but also by #mdb_node_move().)
2713 * @param[in,out] mc the cursor for this operation.
2714 * @param[in] key the key to search for. If NULL, search for the lowest
2715 * page. (This is used by #mdb_cursor_first().)
2716 * @param[in] modify If true, visited pages are updated with new page numbers.
2717 * @return 0 on success, non-zero on failure.
2720 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
2722 MDB_page *mp = mc->mc_pg[mc->mc_top];
2727 while (IS_BRANCH(mp)) {
2731 DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
2732 assert(NUMKEYS(mp) > 1);
2733 DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
2735 if (key == NULL) /* Initialize cursor to first page. */
2737 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
2738 /* cursor to last page */
2742 node = mdb_node_search(mc, key, &exact);
2744 i = NUMKEYS(mp) - 1;
2746 i = mc->mc_ki[mc->mc_top];
2755 DPRINTF("following index %u for key [%s]",
2757 assert(i < NUMKEYS(mp));
2758 node = NODEPTR(mp, i);
2760 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp)))
2763 mc->mc_ki[mc->mc_top] = i;
2764 if ((rc = mdb_cursor_push(mc, mp)))
2768 if ((rc = mdb_page_touch(mc)) != 0)
2770 mp = mc->mc_pg[mc->mc_top];
2775 DPRINTF("internal error, index points to a %02X page!?",
2777 return MDB_CORRUPTED;
2780 DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
2781 key ? DKEY(key) : NULL);
2786 /** Search for the page a given key should be in.
2787 * Pushes parent pages on the cursor stack. This function just sets up
2788 * the search; it finds the root page for \b mc's database and sets this
2789 * as the root of the cursor's stack. Then #mdb_page_search_root() is
2790 * called to complete the search.
2791 * @param[in,out] mc the cursor for this operation.
2792 * @param[in] key the key to search for. If NULL, search for the lowest
2793 * page. (This is used by #mdb_cursor_first().)
2794 * @param[in] modify If true, visited pages are updated with new page numbers.
2795 * @return 0 on success, non-zero on failure.
2798 mdb_page_search(MDB_cursor *mc, MDB_val *key, int modify)
2803 /* Make sure the txn is still viable, then find the root from
2804 * the txn's db table.
2806 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
2807 DPUTS("transaction has failed, must abort");
2810 root = mc->mc_db->md_root;
2812 if (root == P_INVALID) { /* Tree is empty. */
2813 DPUTS("tree is empty");
2814 return MDB_NOTFOUND;
2817 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0])))
2823 DPRINTF("db %u root page %zu has flags 0x%X",
2824 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
2827 /* For sub-databases, update main root first */
2828 if (mc->mc_dbi > MAIN_DBI && !mc->mc_dbx->md_dirty) {
2830 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
2831 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 1);
2834 mc->mc_dbx->md_dirty = 1;
2836 if (!F_ISSET(mc->mc_pg[0]->mp_flags, P_DIRTY)) {
2837 if ((rc = mdb_page_touch(mc)))
2839 mc->mc_db->md_root = mc->mc_pg[0]->mp_pgno;
2843 return mdb_page_search_root(mc, key, modify);
2846 /** Return the data associated with a given node.
2847 * @param[in] txn The transaction for this operation.
2848 * @param[in] leaf The node being read.
2849 * @param[out] data Updated to point to the node's data.
2850 * @return 0 on success, non-zero on failure.
2853 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
2855 MDB_page *omp; /* overflow page */
2859 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
2860 data->mv_size = NODEDSZ(leaf);
2861 data->mv_data = NODEDATA(leaf);
2865 /* Read overflow data.
2867 data->mv_size = NODEDSZ(leaf);
2868 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
2869 if ((rc = mdb_page_get(txn, pgno, &omp))) {
2870 DPRINTF("read overflow page %zu failed", pgno);
2873 data->mv_data = METADATA(omp);
2879 mdb_get(MDB_txn *txn, MDB_dbi dbi,
2880 MDB_val *key, MDB_val *data)
2889 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
2891 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
2894 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2898 mdb_cursor_init(&mc, txn, dbi, &mx);
2899 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
2902 /** Find a sibling for a page.
2903 * Replaces the page at the top of the cursor's stack with the
2904 * specified sibling, if one exists.
2905 * @param[in] mc The cursor for this operation.
2906 * @param[in] move_right Non-zero if the right sibling is requested,
2907 * otherwise the left sibling.
2908 * @return 0 on success, non-zero on failure.
2911 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
2917 if (mc->mc_snum < 2) {
2918 return MDB_NOTFOUND; /* root has no siblings */
2922 DPRINTF("parent page is page %zu, index %u",
2923 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]);
2925 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
2926 : (mc->mc_ki[mc->mc_top] == 0)) {
2927 DPRINTF("no more keys left, moving to %s sibling",
2928 move_right ? "right" : "left");
2929 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS)
2933 mc->mc_ki[mc->mc_top]++;
2935 mc->mc_ki[mc->mc_top]--;
2936 DPRINTF("just moving to %s index key %u",
2937 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]);
2939 assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
2941 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
2942 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp)))
2945 mdb_cursor_push(mc, mp);
2950 /** Move the cursor to the next data item. */
2952 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
2958 if (mc->mc_flags & C_EOF) {
2959 return MDB_NOTFOUND;
2962 assert(mc->mc_flags & C_INITIALIZED);
2964 mp = mc->mc_pg[mc->mc_top];
2966 if (mc->mc_db->md_flags & MDB_DUPSORT) {
2967 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
2968 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2969 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
2970 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
2971 if (op != MDB_NEXT || rc == MDB_SUCCESS)
2975 mc->mc_xcursor->mx_cursor.mc_flags = 0;
2976 if (op == MDB_NEXT_DUP)
2977 return MDB_NOTFOUND;
2981 DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
2983 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
2984 DPUTS("=====> move to next sibling page");
2985 if (mdb_cursor_sibling(mc, 1) != MDB_SUCCESS) {
2986 mc->mc_flags |= C_EOF;
2987 return MDB_NOTFOUND;
2989 mp = mc->mc_pg[mc->mc_top];
2990 DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
2992 mc->mc_ki[mc->mc_top]++;
2994 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
2995 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
2998 key->mv_size = mc->mc_db->md_pad;
2999 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3003 assert(IS_LEAF(mp));
3004 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3006 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3007 mdb_xcursor_init1(mc, leaf);
3010 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3013 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3014 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3015 if (rc != MDB_SUCCESS)
3020 MDB_SET_KEY(leaf, key);
3024 /** Move the cursor to the previous data item. */
3026 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3032 assert(mc->mc_flags & C_INITIALIZED);
3034 mp = mc->mc_pg[mc->mc_top];
3036 if (mc->mc_db->md_flags & MDB_DUPSORT) {
3037 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3038 if (op == MDB_PREV || op == MDB_PREV_DUP) {
3039 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3040 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
3041 if (op != MDB_PREV || rc == MDB_SUCCESS)
3044 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3045 if (op == MDB_PREV_DUP)
3046 return MDB_NOTFOUND;
3051 DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3053 if (mc->mc_ki[mc->mc_top] == 0) {
3054 DPUTS("=====> move to prev sibling page");
3055 if (mdb_cursor_sibling(mc, 0) != MDB_SUCCESS) {
3056 mc->mc_flags &= ~C_INITIALIZED;
3057 return MDB_NOTFOUND;
3059 mp = mc->mc_pg[mc->mc_top];
3060 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
3061 DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3063 mc->mc_ki[mc->mc_top]--;
3065 mc->mc_flags &= ~C_EOF;
3067 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3068 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3071 key->mv_size = mc->mc_db->md_pad;
3072 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3076 assert(IS_LEAF(mp));
3077 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3079 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3080 mdb_xcursor_init1(mc, leaf);
3083 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3086 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3087 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3088 if (rc != MDB_SUCCESS)
3093 MDB_SET_KEY(leaf, key);
3097 /** Set the cursor on a specific data item. */
3099 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3100 MDB_cursor_op op, int *exactp)
3109 assert(key->mv_size > 0);
3111 /* See if we're already on the right page */
3112 if (mc->mc_flags & C_INITIALIZED) {
3115 mp = mc->mc_pg[mc->mc_top];
3116 if (mp->mp_flags & P_LEAF2) {
3117 nodekey.mv_size = mc->mc_db->md_pad;
3118 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
3120 leaf = NODEPTR(mp, 0);
3121 MDB_SET_KEY(leaf, &nodekey);
3123 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3125 /* Probably happens rarely, but first node on the page
3126 * was the one we wanted.
3128 mc->mc_ki[mc->mc_top] = 0;
3129 leaf = NODEPTR(mp, 0);
3136 unsigned int nkeys = NUMKEYS(mp);
3138 if (mp->mp_flags & P_LEAF2) {
3139 nodekey.mv_data = LEAF2KEY(mp,
3140 nkeys-1, nodekey.mv_size);
3142 leaf = NODEPTR(mp, nkeys-1);
3143 MDB_SET_KEY(leaf, &nodekey);
3145 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3147 /* last node was the one we wanted */
3148 mc->mc_ki[mc->mc_top] = nkeys-1;
3149 leaf = NODEPTR(mp, nkeys-1);
3155 /* This is definitely the right page, skip search_page */
3160 /* If any parents have right-sibs, search.
3161 * Otherwise, there's nothing further.
3163 for (i=0; i<mc->mc_top; i++)
3165 NUMKEYS(mc->mc_pg[i])-1)
3167 if (i == mc->mc_top) {
3168 /* There are no other pages */
3169 mc->mc_ki[mc->mc_top] = nkeys;
3170 return MDB_NOTFOUND;
3175 rc = mdb_page_search(mc, key, 0);
3176 if (rc != MDB_SUCCESS)
3179 mp = mc->mc_pg[mc->mc_top];
3180 assert(IS_LEAF(mp));
3183 leaf = mdb_node_search(mc, key, exactp);
3184 if (exactp != NULL && !*exactp) {
3185 /* MDB_SET specified and not an exact match. */
3186 return MDB_NOTFOUND;
3190 DPUTS("===> inexact leaf not found, goto sibling");
3191 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
3192 return rc; /* no entries matched */
3193 mp = mc->mc_pg[mc->mc_top];
3194 assert(IS_LEAF(mp));
3195 leaf = NODEPTR(mp, 0);
3199 mc->mc_flags |= C_INITIALIZED;
3200 mc->mc_flags &= ~C_EOF;
3203 key->mv_size = mc->mc_db->md_pad;
3204 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3208 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3209 mdb_xcursor_init1(mc, leaf);
3212 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3213 if (op == MDB_SET || op == MDB_SET_RANGE) {
3214 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3217 if (op == MDB_GET_BOTH) {
3223 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
3224 if (rc != MDB_SUCCESS)
3227 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
3229 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
3231 rc = mc->mc_dbx->md_dcmp(data, &d2);
3233 if (op == MDB_GET_BOTH || rc > 0)
3234 return MDB_NOTFOUND;
3239 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3240 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3245 /* The key already matches in all other cases */
3246 if (op == MDB_SET_RANGE)
3247 MDB_SET_KEY(leaf, key);
3248 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
3253 /** Move the cursor to the first item in the database. */
3255 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3260 rc = mdb_page_search(mc, NULL, 0);
3261 if (rc != MDB_SUCCESS)
3263 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3265 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
3266 mc->mc_flags |= C_INITIALIZED;
3267 mc->mc_flags &= ~C_EOF;
3269 mc->mc_ki[mc->mc_top] = 0;
3271 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3272 key->mv_size = mc->mc_db->md_pad;
3273 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
3278 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3279 mdb_xcursor_init1(mc, leaf);
3280 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3285 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3286 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3290 MDB_SET_KEY(leaf, key);
3294 /** Move the cursor to the last item in the database. */
3296 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3302 lkey.mv_size = MAXKEYSIZE+1;
3303 lkey.mv_data = NULL;
3305 rc = mdb_page_search(mc, &lkey, 0);
3306 if (rc != MDB_SUCCESS)
3308 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3310 leaf = NODEPTR(mc->mc_pg[mc->mc_top], NUMKEYS(mc->mc_pg[mc->mc_top])-1);
3311 mc->mc_flags |= C_INITIALIZED;
3312 mc->mc_flags &= ~C_EOF;
3314 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
3316 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3317 key->mv_size = mc->mc_db->md_pad;
3318 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
3323 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3324 mdb_xcursor_init1(mc, leaf);
3325 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3330 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3331 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3336 MDB_SET_KEY(leaf, key);
3341 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3351 case MDB_GET_BOTH_RANGE:
3352 if (data == NULL || mc->mc_xcursor == NULL) {
3359 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3361 } else if (op == MDB_SET_RANGE)
3362 rc = mdb_cursor_set(mc, key, data, op, NULL);
3364 rc = mdb_cursor_set(mc, key, data, op, &exact);
3366 case MDB_GET_MULTIPLE:
3368 !(mc->mc_db->md_flags & MDB_DUPFIXED) ||
3369 !(mc->mc_flags & C_INITIALIZED)) {
3374 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
3375 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
3378 case MDB_NEXT_MULTIPLE:
3380 !(mc->mc_db->md_flags & MDB_DUPFIXED)) {
3384 if (!(mc->mc_flags & C_INITIALIZED))
3385 rc = mdb_cursor_first(mc, key, data);
3387 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
3388 if (rc == MDB_SUCCESS) {
3389 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
3392 mx = &mc->mc_xcursor->mx_cursor;
3393 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
3395 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
3396 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
3404 case MDB_NEXT_NODUP:
3405 if (!(mc->mc_flags & C_INITIALIZED))
3406 rc = mdb_cursor_first(mc, key, data);
3408 rc = mdb_cursor_next(mc, key, data, op);
3412 case MDB_PREV_NODUP:
3413 if (!(mc->mc_flags & C_INITIALIZED) || (mc->mc_flags & C_EOF))
3414 rc = mdb_cursor_last(mc, key, data);
3416 rc = mdb_cursor_prev(mc, key, data, op);
3419 rc = mdb_cursor_first(mc, key, data);
3423 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
3424 !(mc->mc_flags & C_INITIALIZED) ||
3425 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3429 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3432 rc = mdb_cursor_last(mc, key, data);
3436 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
3437 !(mc->mc_flags & C_INITIALIZED) ||
3438 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3442 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3445 DPRINTF("unhandled/unimplemented cursor operation %u", op);
3453 /** Touch all the pages in the cursor stack.
3454 * Makes sure all the pages are writable, before attempting a write operation.
3455 * @param[in] mc The cursor to operate on.
3458 mdb_cursor_touch(MDB_cursor *mc)
3462 if (mc->mc_dbi > MAIN_DBI && !mc->mc_dbx->md_dirty) {
3464 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
3465 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 1);
3468 mc->mc_dbx->md_dirty = 1;
3470 for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
3471 if (!F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY)) {
3472 rc = mdb_page_touch(mc);
3476 mc->mc_db->md_root =
3477 mc->mc_pg[mc->mc_top]->mp_pgno;
3481 mc->mc_top = mc->mc_snum-1;
3486 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3490 MDB_val xdata, *rdata, dkey;
3492 char dbuf[PAGESIZE];
3498 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
3501 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
3502 mc->mc_dbi, DKEY(key), key->mv_size, data->mv_size);
3506 if (flags == MDB_CURRENT) {
3507 if (!(mc->mc_flags & C_INITIALIZED))
3510 } else if (mc->mc_db->md_root == P_INVALID) {
3512 /* new database, write a root leaf page */
3513 DPUTS("allocating new root leaf page");
3514 if ((np = mdb_page_new(mc, P_LEAF, 1)) == NULL) {
3518 mdb_cursor_push(mc, np);
3519 mc->mc_db->md_root = np->mp_pgno;
3520 mc->mc_db->md_depth++;
3521 mc->mc_dbx->md_dirty = 1;
3522 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
3524 np->mp_flags |= P_LEAF2;
3525 mc->mc_flags |= C_INITIALIZED;
3531 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
3532 if (flags == MDB_NOOVERWRITE && rc == 0) {
3533 DPRINTF("duplicate key [%s]", DKEY(key));
3535 return MDB_KEYEXIST;
3537 if (rc && rc != MDB_NOTFOUND)
3541 /* Cursor is positioned, now make sure all pages are writable */
3542 rc2 = mdb_cursor_touch(mc);
3547 /* The key already exists */
3548 if (rc == MDB_SUCCESS) {
3549 /* there's only a key anyway, so this is a no-op */
3550 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3551 unsigned int ksize = mc->mc_db->md_pad;
3552 if (key->mv_size != ksize)
3554 if (flags == MDB_CURRENT) {
3555 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
3556 memcpy(ptr, key->mv_data, ksize);
3561 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3564 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
3565 /* Was a single item before, must convert now */
3566 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3567 dkey.mv_size = NODEDSZ(leaf);
3568 dkey.mv_data = dbuf;
3569 memcpy(dbuf, NODEDATA(leaf), dkey.mv_size);
3570 /* data matches, ignore it */
3571 if (!mc->mc_dbx->md_dcmp(data, &dkey))
3572 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
3573 memset(&dummy, 0, sizeof(dummy));
3574 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
3575 dummy.md_pad = data->mv_size;
3576 dummy.md_flags = MDB_DUPFIXED;
3577 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
3578 dummy.md_flags |= MDB_INTEGERKEY;
3580 dummy.md_flags |= MDB_SUBDATA;
3581 dummy.md_root = P_INVALID;
3582 if (dkey.mv_size == sizeof(MDB_db)) {
3583 memcpy(NODEDATA(leaf), &dummy, sizeof(dummy));
3586 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
3589 xdata.mv_size = sizeof(MDB_db);
3590 xdata.mv_data = &dummy;
3591 /* new sub-DB, must fully init xcursor */
3592 if (flags == MDB_CURRENT)
3598 /* same size, just replace it */
3599 if (!F_ISSET(leaf->mn_flags, F_BIGDATA) &&
3600 NODEDSZ(leaf) == data->mv_size) {
3601 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
3604 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
3606 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
3612 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
3613 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
3614 rc = mdb_page_split(mc, key, rdata, P_INVALID);
3616 /* There is room already in this leaf page. */
3617 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, 0);
3620 if (rc != MDB_SUCCESS)
3621 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
3623 /* Remember if we just added a subdatabase */
3624 if (flags & F_SUBDATA) {
3625 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3626 leaf->mn_flags |= F_SUBDATA;
3629 /* Now store the actual data in the child DB. Note that we're
3630 * storing the user data in the keys field, so there are strict
3631 * size limits on dupdata. The actual data fields of the child
3632 * DB are all zero size.
3636 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3638 if (flags != MDB_CURRENT)
3639 mdb_xcursor_init1(mc, leaf);
3642 if (flags == MDB_NODUPDATA)
3643 flags = MDB_NOOVERWRITE;
3644 /* converted, write the original data first */
3646 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, flags);
3649 leaf->mn_flags |= F_DUPDATA;
3651 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, flags);
3652 db = NODEDATA(leaf);
3653 assert((db->md_flags & MDB_SUBDATA) == MDB_SUBDATA);
3654 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
3656 mc->mc_db->md_entries++;
3663 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
3668 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
3671 if (!mc->mc_flags & C_INITIALIZED)
3674 rc = mdb_cursor_touch(mc);
3678 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3680 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3681 if (flags != MDB_NODUPDATA) {
3682 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
3683 /* If sub-DB still has entries, we're done */
3684 if (mc->mc_xcursor->mx_db.md_root != P_INVALID) {
3685 MDB_db *db = NODEDATA(leaf);
3686 assert((db->md_flags & MDB_SUBDATA) == MDB_SUBDATA);
3687 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
3688 mc->mc_db->md_entries--;
3691 /* otherwise fall thru and delete the sub-DB */
3694 /* add all the child DB's pages to the free list */
3695 rc = mdb_page_search(&mc->mc_xcursor->mx_cursor, NULL, 0);
3696 if (rc == MDB_SUCCESS) {
3701 mx = &mc->mc_xcursor->mx_cursor;
3702 mc->mc_db->md_entries -=
3703 mx->mc_db->md_entries;
3706 while (mx->mc_snum > 1) {
3707 for (i=0; i<NUMKEYS(mx->mc_pg[mx->mc_top]); i++) {
3710 ni = NODEPTR(mx->mc_pg[mx->mc_top], i);
3712 if ((rc = mdb_page_get(mc->mc_txn, pg, &mp)))
3715 mdb_midl_append(mc->mc_txn->mt_free_pgs, pg);
3717 rc = mdb_cursor_sibling(mx, 1);
3722 mdb_midl_append(mc->mc_txn->mt_free_pgs,
3723 mx->mc_db->md_root);
3727 return mdb_cursor_del0(mc, leaf);
3730 /** Allocate and initialize new pages for a database.
3731 * @param[in] mc a cursor on the database being added to.
3732 * @param[in] flags flags defining what type of page is being allocated.
3733 * @param[in] num the number of pages to allocate. This is usually 1,
3734 * unless allocating overflow pages for a large record.
3735 * @return Address of a page, or NULL on failure.
3738 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num)
3742 if ((np = mdb_page_alloc(mc, num)) == NULL)
3744 DPRINTF("allocated new mpage %zu, page size %u",
3745 np->mp_pgno, mc->mc_txn->mt_env->me_psize);
3746 np->mp_flags = flags | P_DIRTY;
3747 np->mp_lower = PAGEHDRSZ;
3748 np->mp_upper = mc->mc_txn->mt_env->me_psize;
3751 mc->mc_db->md_branch_pages++;
3752 else if (IS_LEAF(np))
3753 mc->mc_db->md_leaf_pages++;
3754 else if (IS_OVERFLOW(np)) {
3755 mc->mc_db->md_overflow_pages += num;
3762 /** Calculate the size of a leaf node.
3763 * The size depends on the environment's page size; if a data item
3764 * is too large it will be put onto an overflow page and the node
3765 * size will only include the key and not the data. Sizes are always
3766 * rounded up to an even number of bytes, to guarantee 2-byte alignment
3767 * of the #MDB_node headers.
3768 * @param[in] env The environment handle.
3769 * @param[in] key The key for the node.
3770 * @param[in] data The data for the node.
3771 * @return The number of bytes needed to store the node.
3774 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
3778 sz = LEAFSIZE(key, data);
3779 if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
3780 /* put on overflow page */
3781 sz -= data->mv_size - sizeof(pgno_t);
3785 return sz + sizeof(indx_t);
3788 /** Calculate the size of a branch node.
3789 * The size should depend on the environment's page size but since
3790 * we currently don't support spilling large keys onto overflow
3791 * pages, it's simply the size of the #MDB_node header plus the
3792 * size of the key. Sizes are always rounded up to an even number
3793 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
3794 * @param[in] env The environment handle.
3795 * @param[in] key The key for the node.
3796 * @return The number of bytes needed to store the node.
3799 mdb_branch_size(MDB_env *env, MDB_val *key)
3804 if (sz >= env->me_psize / MDB_MINKEYS) {
3805 /* put on overflow page */
3806 /* not implemented */
3807 /* sz -= key->size - sizeof(pgno_t); */
3810 return sz + sizeof(indx_t);
3813 /** Add a node to the page pointed to by the cursor.
3814 * @param[in] mc The cursor for this operation.
3815 * @param[in] indx The index on the page where the new node should be added.
3816 * @param[in] key The key for the new node.
3817 * @param[in] data The data for the new node, if any.
3818 * @param[in] pgno The page number, if adding a branch node.
3819 * @param[in] flags Flags for the node.
3820 * @return 0 on success, non-zero on failure. Possible errors are:
3822 * <li>ENOMEM - failed to allocate overflow pages for the node.
3823 * <li>ENOSPC - there is insufficient room in the page. This error
3824 * should never happen since all callers already calculate the
3825 * page's free space before calling this function.
3829 mdb_node_add(MDB_cursor *mc, indx_t indx,
3830 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags)
3833 size_t node_size = NODESIZE;
3836 MDB_page *mp = mc->mc_pg[mc->mc_top];
3837 MDB_page *ofp = NULL; /* overflow page */
3840 assert(mp->mp_upper >= mp->mp_lower);
3842 DPRINTF("add to %s page %zu index %i, data size %zu key size %zu [%s]",
3843 IS_LEAF(mp) ? "leaf" : "branch",
3844 mp->mp_pgno, indx, data ? data->mv_size : 0,
3845 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
3848 /* Move higher keys up one slot. */
3849 int ksize = mc->mc_db->md_pad, dif;
3850 char *ptr = LEAF2KEY(mp, indx, ksize);
3851 dif = NUMKEYS(mp) - indx;
3853 memmove(ptr+ksize, ptr, dif*ksize);
3854 /* insert new key */
3855 memcpy(ptr, key->mv_data, ksize);
3857 /* Just using these for counting */
3858 mp->mp_lower += sizeof(indx_t);
3859 mp->mp_upper -= ksize - sizeof(indx_t);
3864 node_size += key->mv_size;
3868 if (F_ISSET(flags, F_BIGDATA)) {
3869 /* Data already on overflow page. */
3870 node_size += sizeof(pgno_t);
3871 } else if (data->mv_size >= mc->mc_txn->mt_env->me_psize / MDB_MINKEYS) {
3872 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
3873 /* Put data on overflow page. */
3874 DPRINTF("data size is %zu, put on overflow page",
3876 node_size += sizeof(pgno_t);
3877 if ((ofp = mdb_page_new(mc, P_OVERFLOW, ovpages)) == NULL)
3879 DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
3882 node_size += data->mv_size;
3885 node_size += node_size & 1;
3887 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
3888 DPRINTF("not enough room in page %zu, got %u ptrs",
3889 mp->mp_pgno, NUMKEYS(mp));
3890 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
3891 mp->mp_upper - mp->mp_lower);
3892 DPRINTF("node size = %zu", node_size);
3896 /* Move higher pointers up one slot. */
3897 for (i = NUMKEYS(mp); i > indx; i--)
3898 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
3900 /* Adjust free space offsets. */
3901 ofs = mp->mp_upper - node_size;
3902 assert(ofs >= mp->mp_lower + sizeof(indx_t));
3903 mp->mp_ptrs[indx] = ofs;
3905 mp->mp_lower += sizeof(indx_t);
3907 /* Write the node data. */
3908 node = NODEPTR(mp, indx);
3909 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
3910 node->mn_flags = flags;
3912 SETDSZ(node,data->mv_size);
3917 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
3922 if (F_ISSET(flags, F_BIGDATA))
3923 memcpy(node->mn_data + key->mv_size, data->mv_data,
3926 memcpy(node->mn_data + key->mv_size, data->mv_data,
3929 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
3931 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
3938 /** Delete the specified node from a page.
3939 * @param[in] mp The page to operate on.
3940 * @param[in] indx The index of the node to delete.
3941 * @param[in] ksize The size of a node. Only used if the page is
3942 * part of a #MDB_DUPFIXED database.
3945 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
3948 indx_t i, j, numkeys, ptr;
3952 DPRINTF("delete node %u on %s page %zu", indx,
3953 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
3954 assert(indx < NUMKEYS(mp));
3957 int x = NUMKEYS(mp) - 1 - indx;
3958 base = LEAF2KEY(mp, indx, ksize);
3960 memmove(base, base + ksize, x * ksize);
3961 mp->mp_lower -= sizeof(indx_t);
3962 mp->mp_upper += ksize - sizeof(indx_t);
3966 node = NODEPTR(mp, indx);
3967 sz = NODESIZE + node->mn_ksize;
3969 if (F_ISSET(node->mn_flags, F_BIGDATA))
3970 sz += sizeof(pgno_t);
3972 sz += NODEDSZ(node);
3976 ptr = mp->mp_ptrs[indx];
3977 numkeys = NUMKEYS(mp);
3978 for (i = j = 0; i < numkeys; i++) {
3980 mp->mp_ptrs[j] = mp->mp_ptrs[i];
3981 if (mp->mp_ptrs[i] < ptr)
3982 mp->mp_ptrs[j] += sz;
3987 base = (char *)mp + mp->mp_upper;
3988 memmove(base + sz, base, ptr - mp->mp_upper);
3990 mp->mp_lower -= sizeof(indx_t);
3994 /** Initial setup of a sorted-dups cursor.
3995 * Sorted duplicates are implemented as a sub-database for the given key.
3996 * The duplicate data items are actually keys of the sub-database.
3997 * Operations on the duplicate data items are performed using a sub-cursor
3998 * initialized when the sub-database is first accessed. This function does
3999 * the preliminary setup of the sub-cursor, filling in the fields that
4000 * depend only on the parent DB.
4001 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4004 mdb_xcursor_init0(MDB_cursor *mc)
4006 MDB_xcursor *mx = mc->mc_xcursor;
4008 mx->mx_cursor.mc_xcursor = NULL;
4009 mx->mx_cursor.mc_txn = mc->mc_txn;
4010 mx->mx_cursor.mc_db = &mx->mx_db;
4011 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
4012 mx->mx_cursor.mc_dbi = mc->mc_dbi+1;
4013 mx->mx_dbx.md_parent = mc->mc_dbi;
4014 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
4015 mx->mx_dbx.md_dcmp = NULL;
4016 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
4017 mx->mx_dbx.md_dirty = 0;
4020 /** Final setup of a sorted-dups cursor.
4021 * Sets up the fields that depend on the data from the main cursor.
4022 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4023 * @param[in] node The data containing the #MDB_db record for the
4024 * sorted-dup database.
4027 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
4029 MDB_db *db = NODEDATA(node);
4030 MDB_xcursor *mx = mc->mc_xcursor;
4031 assert((db->md_flags & MDB_SUBDATA) == MDB_SUBDATA);
4033 DPRINTF("Sub-db %u for db %u root page %zu", mx->mx_cursor.mc_dbi, mc->mc_dbi,
4035 if (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY))
4036 mx->mx_dbx.md_dirty = 1;
4037 mx->mx_dbx.md_name.mv_data = NODEKEY(node);
4038 mx->mx_dbx.md_name.mv_size = node->mn_ksize;
4039 mx->mx_cursor.mc_snum = 0;
4040 mx->mx_cursor.mc_flags = 0;
4041 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
4042 mx->mx_dbx.md_cmp = mdb_cmp_long;
4045 /** Initialize a cursor for a given transaction and database. */
4047 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
4051 mc->mc_db = &txn->mt_dbs[dbi];
4052 mc->mc_dbx = &txn->mt_dbxs[dbi];
4055 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4057 mc->mc_xcursor = mx;
4058 mdb_xcursor_init0(mc);
4060 mc->mc_xcursor = NULL;
4065 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
4068 MDB_xcursor *mx = NULL;
4069 size_t size = sizeof(MDB_cursor);
4071 if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
4074 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
4075 size += sizeof(MDB_xcursor);
4077 if ((mc = malloc(size)) != NULL) {
4078 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4079 mx = (MDB_xcursor *)(mc + 1);
4081 mdb_cursor_init(mc, txn, dbi, mx);
4091 /* Return the count of duplicate data items for the current key */
4093 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
4097 if (mc == NULL || countp == NULL)
4100 if (!(mc->mc_db->md_flags & MDB_DUPSORT))
4103 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4104 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4107 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
4110 *countp = mc->mc_xcursor->mx_db.md_entries;
4116 mdb_cursor_close(MDB_cursor *mc)
4123 /** Replace the key for a node with a new key.
4124 * @param[in] mp The page containing the node to operate on.
4125 * @param[in] indx The index of the node to operate on.
4126 * @param[in] key The new key to use.
4127 * @return 0 on success, non-zero on failure.
4130 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
4132 indx_t ptr, i, numkeys;
4139 node = NODEPTR(mp, indx);
4140 ptr = mp->mp_ptrs[indx];
4141 DPRINTF("update key %u (ofs %u) [%.*s] to [%s] on page %zu",
4143 (int)node->mn_ksize, (char *)NODEKEY(node),
4147 delta = key->mv_size - node->mn_ksize;
4149 if (delta > 0 && SIZELEFT(mp) < delta) {
4150 DPRINTF("OUCH! Not enough room, delta = %d", delta);
4154 numkeys = NUMKEYS(mp);
4155 for (i = 0; i < numkeys; i++) {
4156 if (mp->mp_ptrs[i] <= ptr)
4157 mp->mp_ptrs[i] -= delta;
4160 base = (char *)mp + mp->mp_upper;
4161 len = ptr - mp->mp_upper + NODESIZE;
4162 memmove(base - delta, base, len);
4163 mp->mp_upper -= delta;
4165 node = NODEPTR(mp, indx);
4166 node->mn_ksize = key->mv_size;
4169 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
4174 /** Move a node from csrc to cdst.
4177 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
4184 /* Mark src and dst as dirty. */
4185 if ((rc = mdb_page_touch(csrc)) ||
4186 (rc = mdb_page_touch(cdst)))
4189 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4190 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
4191 key.mv_size = csrc->mc_db->md_pad;
4192 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
4194 data.mv_data = NULL;
4196 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
4197 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
4198 unsigned int snum = csrc->mc_snum;
4200 /* must find the lowest key below src */
4201 mdb_page_search_root(csrc, NULL, 0);
4202 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
4203 key.mv_size = NODEKSZ(s2);
4204 key.mv_data = NODEKEY(s2);
4205 csrc->mc_snum = snum--;
4206 csrc->mc_top = snum;
4208 key.mv_size = NODEKSZ(srcnode);
4209 key.mv_data = NODEKEY(srcnode);
4211 data.mv_size = NODEDSZ(srcnode);
4212 data.mv_data = NODEDATA(srcnode);
4214 DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
4215 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
4216 csrc->mc_ki[csrc->mc_top],
4218 csrc->mc_pg[csrc->mc_top]->mp_pgno,
4219 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
4221 /* Add the node to the destination page.
4223 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, NODEPGNO(srcnode),
4225 if (rc != MDB_SUCCESS)
4228 /* Delete the node from the source page.
4230 mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
4232 /* Update the parent separators.
4234 if (csrc->mc_ki[csrc->mc_top] == 0) {
4235 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
4236 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4237 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
4239 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
4240 key.mv_size = NODEKSZ(srcnode);
4241 key.mv_data = NODEKEY(srcnode);
4243 DPRINTF("update separator for source page %zu to [%s]",
4244 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
4245 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1],
4246 &key)) != MDB_SUCCESS)
4249 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
4251 nullkey.mv_size = 0;
4252 assert(mdb_update_key(csrc->mc_pg[csrc->mc_top], 0, &nullkey) == MDB_SUCCESS);
4256 if (cdst->mc_ki[cdst->mc_top] == 0) {
4257 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
4258 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4259 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
4261 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
4262 key.mv_size = NODEKSZ(srcnode);
4263 key.mv_data = NODEKEY(srcnode);
4265 DPRINTF("update separator for destination page %zu to [%s]",
4266 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
4267 if ((rc = mdb_update_key(cdst->mc_pg[cdst->mc_top-1], cdst->mc_ki[cdst->mc_top-1],
4268 &key)) != MDB_SUCCESS)
4271 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
4273 nullkey.mv_size = 0;
4274 assert(mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &nullkey) == MDB_SUCCESS);
4281 /** Merge one page into another.
4282 * The nodes from the page pointed to by \b csrc will
4283 * be copied to the page pointed to by \b cdst and then
4284 * the \b csrc page will be freed.
4285 * @param[in] csrc Cursor pointing to the source page.
4286 * @param[in] cdst Cursor pointing to the destination page.
4289 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
4296 DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
4297 cdst->mc_pg[cdst->mc_top]->mp_pgno);
4299 assert(csrc->mc_snum > 1); /* can't merge root page */
4300 assert(cdst->mc_snum > 1);
4302 /* Mark dst as dirty. */
4303 if ((rc = mdb_page_touch(cdst)))
4306 /* Move all nodes from src to dst.
4308 j = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
4309 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4310 key.mv_size = csrc->mc_db->md_pad;
4311 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
4312 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
4313 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
4314 if (rc != MDB_SUCCESS)
4316 key.mv_data = (char *)key.mv_data + key.mv_size;
4319 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
4320 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
4322 key.mv_size = srcnode->mn_ksize;
4323 key.mv_data = NODEKEY(srcnode);
4324 data.mv_size = NODEDSZ(srcnode);
4325 data.mv_data = NODEDATA(srcnode);
4326 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
4327 if (rc != MDB_SUCCESS)
4332 DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
4333 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);
4335 /* Unlink the src page from parent and add to free list.
4337 mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
4338 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
4340 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], 0, &key)) != MDB_SUCCESS)
4344 mdb_midl_append(csrc->mc_txn->mt_free_pgs, csrc->mc_pg[csrc->mc_top]->mp_pgno);
4345 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
4346 csrc->mc_db->md_leaf_pages--;
4348 csrc->mc_db->md_branch_pages--;
4349 mdb_cursor_pop(csrc);
4351 return mdb_rebalance(csrc);
4354 /** Copy the contents of a cursor.
4355 * @param[in] csrc The cursor to copy from.
4356 * @param[out] cdst The cursor to copy to.
4359 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
4363 cdst->mc_txn = csrc->mc_txn;
4364 cdst->mc_dbi = csrc->mc_dbi;
4365 cdst->mc_db = csrc->mc_db;
4366 cdst->mc_dbx = csrc->mc_dbx;
4367 cdst->mc_snum = csrc->mc_snum;
4368 cdst->mc_top = csrc->mc_top;
4369 cdst->mc_flags = csrc->mc_flags;
4371 for (i=0; i<csrc->mc_snum; i++) {
4372 cdst->mc_pg[i] = csrc->mc_pg[i];
4373 cdst->mc_ki[i] = csrc->mc_ki[i];
4377 /** Rebalance the tree after a delete operation.
4378 * @param[in] mc Cursor pointing to the page where rebalancing
4380 * @return 0 on success, non-zero on failure.
4383 mdb_rebalance(MDB_cursor *mc)
4390 DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
4391 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
4392 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);
4394 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD) {
4395 DPRINTF("no need to rebalance page %zu, above fill threshold",
4396 mc->mc_pg[mc->mc_top]->mp_pgno);
4400 if (mc->mc_snum < 2) {
4401 if (NUMKEYS(mc->mc_pg[mc->mc_top]) == 0) {
4402 DPUTS("tree is completely empty");
4403 mc->mc_db->md_root = P_INVALID;
4404 mc->mc_db->md_depth = 0;
4405 mc->mc_db->md_leaf_pages = 0;
4406 mdb_midl_append(mc->mc_txn->mt_free_pgs, mc->mc_pg[mc->mc_top]->mp_pgno);
4408 } else if (IS_BRANCH(mc->mc_pg[mc->mc_top]) && NUMKEYS(mc->mc_pg[mc->mc_top]) == 1) {
4409 DPUTS("collapsing root page!");
4410 mdb_midl_append(mc->mc_txn->mt_free_pgs, mc->mc_pg[mc->mc_top]->mp_pgno);
4411 mc->mc_db->md_root = NODEPGNO(NODEPTR(mc->mc_pg[mc->mc_top], 0));
4412 if ((rc = mdb_page_get(mc->mc_txn, mc->mc_db->md_root,
4413 &mc->mc_pg[mc->mc_top])))
4415 mc->mc_db->md_depth--;
4416 mc->mc_db->md_branch_pages--;
4418 DPUTS("root page doesn't need rebalancing");
4422 /* The parent (branch page) must have at least 2 pointers,
4423 * otherwise the tree is invalid.
4425 ptop = mc->mc_top-1;
4426 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
4428 /* Leaf page fill factor is below the threshold.
4429 * Try to move keys from left or right neighbor, or
4430 * merge with a neighbor page.
4435 mdb_cursor_copy(mc, &mn);
4436 mn.mc_xcursor = NULL;
4438 if (mc->mc_ki[ptop] == 0) {
4439 /* We're the leftmost leaf in our parent.
4441 DPUTS("reading right neighbor");
4443 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
4444 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
4446 mn.mc_ki[mn.mc_top] = 0;
4447 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
4449 /* There is at least one neighbor to the left.
4451 DPUTS("reading left neighbor");
4453 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
4454 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
4456 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
4457 mc->mc_ki[mc->mc_top] = 0;
4460 DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
4461 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);
4463 /* If the neighbor page is above threshold and has at least two
4464 * keys, move one key from it.
4466 * Otherwise we should try to merge them.
4468 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) >= 2)
4469 return mdb_node_move(&mn, mc);
4470 else { /* FIXME: if (has_enough_room()) */
4471 if (mc->mc_ki[ptop] == 0)
4472 return mdb_page_merge(&mn, mc);
4474 return mdb_page_merge(mc, &mn);
4478 /** Complete a delete operation started by #mdb_cursor_del(). */
4480 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
4484 /* add overflow pages to free list */
4485 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
4489 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
4490 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
4491 for (i=0; i<ovpages; i++) {
4492 DPRINTF("freed ov page %zu", pg);
4493 mdb_midl_append(mc->mc_txn->mt_free_pgs, pg);
4497 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], mc->mc_db->md_pad);
4498 mc->mc_db->md_entries--;
4499 rc = mdb_rebalance(mc);
4500 if (rc != MDB_SUCCESS)
4501 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4507 mdb_del(MDB_txn *txn, MDB_dbi dbi,
4508 MDB_val *key, MDB_val *data)
4513 MDB_val rdata, *xdata;
4517 assert(key != NULL);
4519 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
4521 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4524 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
4528 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
4532 mdb_cursor_init(&mc, txn, dbi, &mx);
4543 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
4545 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
4549 /** Split a page and insert a new node.
4550 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
4551 * The cursor will be updated to point to the actual page and index where
4552 * the node got inserted after the split.
4553 * @param[in] newkey The key for the newly inserted node.
4554 * @param[in] newdata The data for the newly inserted node.
4555 * @param[in] newpgno The page number, if the new node is a branch node.
4556 * @return 0 on success, non-zero on failure.
4559 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno)
4562 int rc = MDB_SUCCESS, ins_new = 0;
4565 unsigned int i, j, split_indx, nkeys, pmax;
4567 MDB_val sepkey, rkey, rdata;
4569 MDB_page *mp, *rp, *pp;
4574 mp = mc->mc_pg[mc->mc_top];
4575 newindx = mc->mc_ki[mc->mc_top];
4577 DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
4578 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
4579 DKEY(newkey), mc->mc_ki[mc->mc_top]);
4581 if (mc->mc_snum < 2) {
4582 if ((pp = mdb_page_new(mc, P_BRANCH, 1)) == NULL)
4584 /* shift current top to make room for new parent */
4585 mc->mc_pg[1] = mc->mc_pg[0];
4586 mc->mc_ki[1] = mc->mc_ki[0];
4589 mc->mc_db->md_root = pp->mp_pgno;
4590 DPRINTF("root split! new root = %zu", pp->mp_pgno);
4591 mc->mc_db->md_depth++;
4593 /* Add left (implicit) pointer. */
4594 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
4595 /* undo the pre-push */
4596 mc->mc_pg[0] = mc->mc_pg[1];
4597 mc->mc_ki[0] = mc->mc_ki[1];
4598 mc->mc_db->md_root = mp->mp_pgno;
4599 mc->mc_db->md_depth--;
4606 ptop = mc->mc_top-1;
4607 DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
4610 /* Create a right sibling. */
4611 if ((rp = mdb_page_new(mc, mp->mp_flags, 1)) == NULL)
4613 mdb_cursor_copy(mc, &mn);
4614 mn.mc_pg[mn.mc_top] = rp;
4615 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
4616 DPRINTF("new right sibling: page %zu", rp->mp_pgno);
4618 nkeys = NUMKEYS(mp);
4619 split_indx = nkeys / 2 + 1;
4624 unsigned int lsize, rsize, ksize;
4625 /* Move half of the keys to the right sibling */
4627 x = mc->mc_ki[mc->mc_top] - split_indx;
4628 ksize = mc->mc_db->md_pad;
4629 split = LEAF2KEY(mp, split_indx, ksize);
4630 rsize = (nkeys - split_indx) * ksize;
4631 lsize = (nkeys - split_indx) * sizeof(indx_t);
4632 mp->mp_lower -= lsize;
4633 rp->mp_lower += lsize;
4634 mp->mp_upper += rsize - lsize;
4635 rp->mp_upper -= rsize - lsize;
4636 sepkey.mv_size = ksize;
4637 if (newindx == split_indx) {
4638 sepkey.mv_data = newkey->mv_data;
4640 sepkey.mv_data = split;
4643 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
4644 memcpy(rp->mp_ptrs, split, rsize);
4645 sepkey.mv_data = rp->mp_ptrs;
4646 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
4647 memcpy(ins, newkey->mv_data, ksize);
4648 mp->mp_lower += sizeof(indx_t);
4649 mp->mp_upper -= ksize - sizeof(indx_t);
4652 memcpy(rp->mp_ptrs, split, x * ksize);
4653 ins = LEAF2KEY(rp, x, ksize);
4654 memcpy(ins, newkey->mv_data, ksize);
4655 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
4656 rp->mp_lower += sizeof(indx_t);
4657 rp->mp_upper -= ksize - sizeof(indx_t);
4658 mc->mc_ki[mc->mc_top] = x;
4659 mc->mc_pg[mc->mc_top] = rp;
4664 /* For leaf pages, check the split point based on what
4665 * fits where, since otherwise add_node can fail.
4668 unsigned int psize, nsize;
4669 /* Maximum free space in an empty page */
4670 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
4671 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
4672 if (newindx < split_indx) {
4674 for (i=0; i<split_indx; i++) {
4675 node = NODEPTR(mp, i);
4676 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
4677 if (F_ISSET(node->mn_flags, F_BIGDATA))
4678 psize += sizeof(pgno_t);
4680 psize += NODEDSZ(node);
4689 for (i=nkeys-1; i>=split_indx; i--) {
4690 node = NODEPTR(mp, i);
4691 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
4692 if (F_ISSET(node->mn_flags, F_BIGDATA))
4693 psize += sizeof(pgno_t);
4695 psize += NODEDSZ(node);
4705 /* First find the separating key between the split pages.
4707 if (newindx == split_indx) {
4708 sepkey.mv_size = newkey->mv_size;
4709 sepkey.mv_data = newkey->mv_data;
4711 node = NODEPTR(mp, split_indx);
4712 sepkey.mv_size = node->mn_ksize;
4713 sepkey.mv_data = NODEKEY(node);
4717 DPRINTF("separator is [%s]", DKEY(&sepkey));
4719 /* Copy separator key to the parent.
4721 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
4724 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno);
4726 /* Right page might now have changed parent.
4727 * Check if left page also changed parent.
4729 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
4730 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
4731 mc->mc_pg[ptop] = mn.mc_pg[ptop];
4732 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
4736 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
4742 if (rc != MDB_SUCCESS) {
4746 /* Move half of the keys to the right sibling. */
4748 /* grab a page to hold a temporary copy */
4749 if (mc->mc_txn->mt_env->me_dpages) {
4750 copy = mc->mc_txn->mt_env->me_dpages;
4751 mc->mc_txn->mt_env->me_dpages = copy->mp_next;
4753 if ((copy = malloc(mc->mc_txn->mt_env->me_psize)) == NULL)
4757 copy->mp_pgno = mp->mp_pgno;
4758 copy->mp_flags = mp->mp_flags;
4759 copy->mp_lower = PAGEHDRSZ;
4760 copy->mp_upper = mc->mc_txn->mt_env->me_psize;
4761 mc->mc_pg[mc->mc_top] = copy;
4762 for (i = j = 0; i <= nkeys; j++) {
4763 if (i == split_indx) {
4764 /* Insert in right sibling. */
4765 /* Reset insert index for right sibling. */
4766 j = (i == newindx && ins_new);
4767 mc->mc_pg[mc->mc_top] = rp;
4770 if (i == newindx && !ins_new) {
4771 /* Insert the original entry that caused the split. */
4772 rkey.mv_data = newkey->mv_data;
4773 rkey.mv_size = newkey->mv_size;
4775 rdata.mv_data = newdata->mv_data;
4776 rdata.mv_size = newdata->mv_size;
4783 /* Update page and index for the new key. */
4784 mc->mc_ki[mc->mc_top] = j;
4785 } else if (i == nkeys) {
4788 node = NODEPTR(mp, i);
4789 rkey.mv_data = NODEKEY(node);
4790 rkey.mv_size = node->mn_ksize;
4792 rdata.mv_data = NODEDATA(node);
4793 rdata.mv_size = NODEDSZ(node);
4795 pgno = NODEPGNO(node);
4796 flags = node->mn_flags;
4801 if (!IS_LEAF(mp) && j == 0) {
4802 /* First branch index doesn't need key data. */
4806 rc = mdb_node_add(mc, j, &rkey, &rdata, pgno, flags);
4809 /* reset back to original page */
4810 if (newindx < split_indx)
4811 mc->mc_pg[mc->mc_top] = mp;
4813 nkeys = NUMKEYS(copy);
4814 for (i=0; i<nkeys; i++)
4815 mp->mp_ptrs[i] = copy->mp_ptrs[i];
4816 mp->mp_lower = copy->mp_lower;
4817 mp->mp_upper = copy->mp_upper;
4818 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
4819 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
4821 /* return tmp page to freelist */
4822 copy->mp_next = mc->mc_txn->mt_env->me_dpages;
4823 mc->mc_txn->mt_env->me_dpages = copy;
4828 mdb_put(MDB_txn *txn, MDB_dbi dbi,
4829 MDB_val *key, MDB_val *data, unsigned int flags)
4834 assert(key != NULL);
4835 assert(data != NULL);
4837 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4840 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
4844 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
4848 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA)) != flags)
4851 mdb_cursor_init(&mc, txn, dbi, &mx);
4852 return mdb_cursor_put(&mc, key, data, flags);
4856 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
4858 /** Only a subset of the @ref mdb_env flags can be changed
4859 * at runtime. Changing other flags requires closing the environment
4860 * and re-opening it with the new flags.
4862 #define CHANGEABLE (MDB_NOSYNC)
4863 if ((flag & CHANGEABLE) != flag)
4866 env->me_flags |= flag;
4868 env->me_flags &= ~flag;
4873 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
4878 *arg = env->me_flags;
4883 mdb_env_get_path(MDB_env *env, const char **arg)
4888 *arg = env->me_path;
4892 /** Common code for #mdb_stat() and #mdb_env_stat().
4893 * @param[in] env the environment to operate in.
4894 * @param[in] db the #MDB_db record containing the stats to return.
4895 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
4896 * @return 0, this function always succeeds.
4899 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
4901 arg->ms_psize = env->me_psize;
4902 arg->ms_depth = db->md_depth;
4903 arg->ms_branch_pages = db->md_branch_pages;
4904 arg->ms_leaf_pages = db->md_leaf_pages;
4905 arg->ms_overflow_pages = db->md_overflow_pages;
4906 arg->ms_entries = db->md_entries;
4911 mdb_env_stat(MDB_env *env, MDB_stat *arg)
4915 if (env == NULL || arg == NULL)
4918 mdb_env_read_meta(env, &toggle);
4920 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
4923 /** Set the default comparison functions for a database.
4924 * Called immediately after a database is opened to set the defaults.
4925 * The user can then override them with #mdb_set_compare() or
4926 * #mdb_set_dupsort().
4927 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
4928 * @param[in] dbi A database handle returned by #mdb_open()
4931 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
4933 if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEKEY)
4934 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memnr;
4935 else if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERKEY)
4936 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_cint;
4938 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memn;
4940 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4941 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP) {
4942 if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED)
4943 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_int;
4945 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_cint;
4946 } else if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEDUP) {
4947 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memnr;
4949 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memn;
4952 txn->mt_dbxs[dbi].md_dcmp = NULL;
4956 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
4963 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
4964 mdb_default_cmp(txn, FREE_DBI);
4970 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
4971 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
4972 mdb_default_cmp(txn, MAIN_DBI);
4976 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
4977 mdb_default_cmp(txn, MAIN_DBI);
4980 /* Is the DB already open? */
4982 for (i=2; i<txn->mt_numdbs; i++) {
4983 if (len == txn->mt_dbxs[i].md_name.mv_size &&
4984 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
4990 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
4993 /* Find the DB info */
4995 key.mv_data = (void *)name;
4996 rc = mdb_get(txn, MAIN_DBI, &key, &data);
4998 /* Create if requested */
4999 if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
5002 data.mv_size = sizeof(MDB_db);
5003 data.mv_data = &dummy;
5004 memset(&dummy, 0, sizeof(dummy));
5005 dummy.md_root = P_INVALID;
5006 dummy.md_flags = flags & 0xffff;
5007 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
5008 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
5012 /* OK, got info, add to table */
5013 if (rc == MDB_SUCCESS) {
5014 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
5015 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
5016 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
5017 txn->mt_dbxs[txn->mt_numdbs].md_parent = MAIN_DBI;
5018 txn->mt_dbxs[txn->mt_numdbs].md_dirty = dirty;
5019 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
5020 *dbi = txn->mt_numdbs;
5021 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
5022 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
5023 mdb_default_cmp(txn, txn->mt_numdbs);
5030 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
5032 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
5035 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
5038 void mdb_close(MDB_txn *txn, MDB_dbi dbi)
5041 if (dbi <= MAIN_DBI || dbi >= txn->mt_numdbs)
5043 ptr = txn->mt_dbxs[dbi].md_name.mv_data;
5044 txn->mt_dbxs[dbi].md_name.mv_data = NULL;
5045 txn->mt_dbxs[dbi].md_name.mv_size = 0;
5049 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
5051 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5054 txn->mt_dbxs[dbi].md_cmp = cmp;
5058 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
5060 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5063 txn->mt_dbxs[dbi].md_dcmp = cmp;
5067 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
5069 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5072 txn->mt_dbxs[dbi].md_rel = rel;
5076 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
5078 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5081 txn->mt_dbxs[dbi].md_relctx = ctx;