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
67 #if (__BYTE_ORDER == __LITTLE_ENDIAN) == (__BYTE_ORDER == __BIG_ENDIAN)
68 # error "Unknown or unsupported endianness (__BYTE_ORDER)"
69 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
70 # error "Two's complement, reasonably sized integer types, please"
73 /** @defgroup internal MDB Internals
76 /** @defgroup compat Windows Compatibility Macros
77 * A bunch of macros to minimize the amount of platform-specific ifdefs
78 * needed throughout the rest of the code. When the features this library
79 * needs are similar enough to POSIX to be hidden in a one-or-two line
80 * replacement, this macro approach is used.
84 #define pthread_t DWORD
85 #define pthread_mutex_t HANDLE
86 #define pthread_key_t DWORD
87 #define pthread_self() GetCurrentThreadId()
88 #define pthread_key_create(x,y) (*(x) = TlsAlloc())
89 #define pthread_key_delete(x) TlsFree(x)
90 #define pthread_getspecific(x) TlsGetValue(x)
91 #define pthread_setspecific(x,y) TlsSetValue(x,y)
92 #define pthread_mutex_unlock(x) ReleaseMutex(x)
93 #define pthread_mutex_lock(x) WaitForSingleObject(x, INFINITE)
94 #define LOCK_MUTEX_R(env) pthread_mutex_lock((env)->me_rmutex)
95 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock((env)->me_rmutex)
96 #define LOCK_MUTEX_W(env) pthread_mutex_lock((env)->me_wmutex)
97 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock((env)->me_wmutex)
98 #define getpid() GetCurrentProcessId()
99 #define fdatasync(fd) (!FlushFileBuffers(fd))
100 #define ErrCode() GetLastError()
101 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
102 #define close(fd) CloseHandle(fd)
103 #define munmap(ptr,len) UnmapViewOfFile(ptr)
105 /** Lock the reader mutex.
107 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
108 /** Unlock the reader mutex.
110 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
112 /** Lock the writer mutex.
113 * Only a single write transaction is allowed at a time. Other writers
114 * will block waiting for this mutex.
116 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
117 /** Unlock the writer mutex.
119 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
121 /** Get the error code for the last failed system function.
123 #define ErrCode() errno
125 /** An abstraction for a file handle.
126 * On POSIX systems file handles are small integers. On Windows
127 * they're opaque pointers.
131 /** A value for an invalid file handle.
132 * Mainly used to initialize file variables and signify that they are
135 #define INVALID_HANDLE_VALUE (-1)
137 /** Get the size of a memory page for the system.
138 * This is the basic size that the platform's memory manager uses, and is
139 * fundamental to the use of memory-mapped files.
141 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
147 /** A flag for opening a file and requesting synchronous data writes.
148 * This is only used when writing a meta page. It's not strictly needed;
149 * we could just do a normal write and then immediately perform a flush.
150 * But if this flag is available it saves us an extra system call.
152 * @note If O_DSYNC is undefined but exists in /usr/include,
153 * preferably set some compiler flag to get the definition.
154 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
157 # define MDB_DSYNC O_DSYNC
161 /** A page number in the database.
162 * Note that 64 bit page numbers are overkill, since pages themselves
163 * already represent 12-13 bits of addressable memory, and the OS will
164 * always limit applications to a maximum of 63 bits of address space.
166 * @note In the #MDB_node structure, we only store 48 bits of this value,
167 * which thus limits us to only 60 bits of addressable data.
171 /** A transaction ID.
172 * See struct MDB_txn.mt_txnid for details.
176 /** @defgroup debug Debug Macros
180 /** Enable debug output.
181 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
182 * read from and written to the database (used for free space management).
187 #if !(__STDC_VERSION__ >= 199901L || defined(__GNUC__))
188 # define DPRINTF (void) /* Vararg macros may be unsupported */
190 /** Print a debug message with printf formatting. */
191 # define DPRINTF(fmt, ...) /**< Requires 2 or more args */ \
192 fprintf(stderr, "%s:%d " fmt "\n", __func__, __LINE__, __VA_ARGS__)
194 # define DPRINTF(fmt, ...) ((void) 0)
196 /** Print a debug string.
197 * The string is printed literally, with no format processing.
199 #define DPUTS(arg) DPRINTF("%s", arg)
202 /** A default memory page size.
203 * The actual size is platform-dependent, but we use this for
204 * boot-strapping. We probably should not be using this any more.
205 * The #GET_PAGESIZE() macro is used to get the actual size.
207 * Note that we don't currently support Huge pages. On Linux,
208 * regular data files cannot use Huge pages, and in general
209 * Huge pages aren't actually pageable. We rely on the OS
210 * demand-pager to read our data and page it out when memory
211 * pressure from other processes is high. So until OSs have
212 * actual paging support for Huge pages, they're not viable.
214 #define PAGESIZE 4096
216 /** The minimum number of keys required in a database page.
217 * Setting this to a larger value will place a smaller bound on the
218 * maximum size of a data item. Data items larger than this size will
219 * be pushed into overflow pages instead of being stored directly in
220 * the B-tree node. This value used to default to 4. With a page size
221 * of 4096 bytes that meant that any item larger than 1024 bytes would
222 * go into an overflow page. That also meant that on average 2-3KB of
223 * each overflow page was wasted space. The value cannot be lower than
224 * 2 because then there would no longer be a tree structure. With this
225 * value, items larger than 2KB will go into overflow pages, and on
226 * average only 1KB will be wasted.
228 #define MDB_MINKEYS 2
230 /** A stamp that identifies a file as an MDB file.
231 * There's nothing special about this value other than that it is easily
232 * recognizable, and it will reflect any byte order mismatches.
234 #define MDB_MAGIC 0xBEEFC0DE
236 /** The version number for a database's file format. */
237 #define MDB_VERSION 1
239 /** The maximum size of a key in the database.
240 * While data items have essentially unbounded size, we require that
241 * keys all fit onto a regular page. This limit could be raised a bit
242 * further if needed; to something just under #PAGESIZE / #MDB_MINKEYS.
244 #define MAXKEYSIZE 511
249 * This is used for printing a hex dump of a key's contents.
251 #define DKBUF char kbuf[(MAXKEYSIZE*2+1)]
252 /** Display a key in hex.
254 * Invoke a function to display a key in hex.
256 #define DKEY(x) mdb_dkey(x, kbuf)
258 #define DKBUF typedef int dummy_kbuf /* so we can put ';' after */
262 /** @defgroup lazylock Lazy Locking
263 * Macros for locks that are't actually needed.
264 * The DB view is always consistent because all writes are wrapped in
265 * the wmutex. Finer-grained locks aren't necessary.
269 /** Use lazy locking. I.e., don't lock these accesses at all. */
273 /** Grab the reader lock */
274 #define LAZY_MUTEX_LOCK(x)
275 /** Release the reader lock */
276 #define LAZY_MUTEX_UNLOCK(x)
277 /** Release the DB table reader/writer lock */
278 #define LAZY_RWLOCK_UNLOCK(x)
279 /** Grab the DB table write lock */
280 #define LAZY_RWLOCK_WRLOCK(x)
281 /** Grab the DB table read lock */
282 #define LAZY_RWLOCK_RDLOCK(x)
283 /** Declare the DB table rwlock. Should not be followed by ';'. */
284 #define LAZY_RWLOCK_DEF(x)
285 /** Initialize the DB table rwlock */
286 #define LAZY_RWLOCK_INIT(x,y)
287 /** Destroy the DB table rwlock */
288 #define LAZY_RWLOCK_DESTROY(x)
290 #define LAZY_MUTEX_LOCK(x) pthread_mutex_lock(x)
291 #define LAZY_MUTEX_UNLOCK(x) pthread_mutex_unlock(x)
292 #define LAZY_RWLOCK_UNLOCK(x) pthread_rwlock_unlock(x)
293 #define LAZY_RWLOCK_WRLOCK(x) pthread_rwlock_wrlock(x)
294 #define LAZY_RWLOCK_RDLOCK(x) pthread_rwlock_rdlock(x)
295 #define LAZY_RWLOCK_DEF(x) pthread_rwlock_t x;
296 #define LAZY_RWLOCK_INIT(x,y) pthread_rwlock_init(x,y)
297 #define LAZY_RWLOCK_DESTROY(x) pthread_rwlock_destroy(x)
301 /** An invalid page number.
302 * Mainly used to denote an empty tree.
304 #define P_INVALID (~0UL)
306 /** Test if a flag \b f is set in a flag word \b w. */
307 #define F_ISSET(w, f) (((w) & (f)) == (f))
309 /** Used for offsets within a single page.
310 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
313 typedef uint16_t indx_t;
315 /** Default size of memory map.
316 * This is certainly too small for any actual applications. Apps should always set
317 * the size explicitly using #mdb_env_set_mapsize().
319 #define DEFAULT_MAPSIZE 1048576
321 /** @defgroup readers Reader Lock Table
322 * Readers don't acquire any locks for their data access. Instead, they
323 * simply record their transaction ID in the reader table. The reader
324 * mutex is needed just to find an empty slot in the reader table. The
325 * slot's address is saved in thread-specific data so that subsequent read
326 * transactions started by the same thread need no further locking to proceed.
328 * Since the database uses multi-version concurrency control, readers don't
329 * actually need any locking. This table is used to keep track of which
330 * readers are using data from which old transactions, so that we'll know
331 * when a particular old transaction is no longer in use. Old transactions
332 * that have discarded any data pages can then have those pages reclaimed
333 * for use by a later write transaction.
335 * The lock table is constructed such that reader slots are aligned with the
336 * processor's cache line size. Any slot is only ever used by one thread.
337 * This alignment guarantees that there will be no contention or cache
338 * thrashing as threads update their own slot info, and also eliminates
339 * any need for locking when accessing a slot.
341 * A writer thread will scan every slot in the table to determine the oldest
342 * outstanding reader transaction. Any freed pages older than this will be
343 * reclaimed by the writer. The writer doesn't use any locks when scanning
344 * this table. This means that there's no guarantee that the writer will
345 * see the most up-to-date reader info, but that's not required for correct
346 * operation - all we need is to know the upper bound on the oldest reader,
347 * we don't care at all about the newest reader. So the only consequence of
348 * reading stale information here is that old pages might hang around a
349 * while longer before being reclaimed. That's actually good anyway, because
350 * the longer we delay reclaiming old pages, the more likely it is that a
351 * string of contiguous pages can be found after coalescing old pages from
352 * many old transactions together.
354 * @todo We don't actually do such coalescing yet, we grab pages from one
355 * old transaction at a time.
358 /** Number of slots in the reader table.
359 * This value was chosen somewhat arbitrarily. 126 readers plus a
360 * couple mutexes fit exactly into 8KB on my development machine.
361 * Applications should set the table size using #mdb_env_set_maxreaders().
363 #define DEFAULT_READERS 126
365 /** The size of a CPU cache line in bytes. We want our lock structures
366 * aligned to this size to avoid false cache line sharing in the
368 * This value works for most CPUs. For Itanium this should be 128.
374 /** The information we store in a single slot of the reader table.
375 * In addition to a transaction ID, we also record the process and
376 * thread ID that owns a slot, so that we can detect stale information,
377 * e.g. threads or processes that went away without cleaning up.
378 * @note We currently don't check for stale records. We simply re-init
379 * the table when we know that we're the only process opening the
382 typedef struct MDB_rxbody {
383 /** The current Transaction ID when this transaction began.
384 * Multiple readers that start at the same time will probably have the
385 * same ID here. Again, it's not important to exclude them from
386 * anything; all we need to know is which version of the DB they
387 * started from so we can avoid overwriting any data used in that
388 * particular version.
391 /** The process ID of the process owning this reader txn. */
393 /** The thread ID of the thread owning this txn. */
397 /** The actual reader record, with cacheline padding. */
398 typedef struct MDB_reader {
401 /** shorthand for mrb_txnid */
402 #define mr_txnid mru.mrx.mrb_txnid
403 #define mr_pid mru.mrx.mrb_pid
404 #define mr_tid mru.mrx.mrb_tid
405 /** cache line alignment */
406 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
410 /** The header for the reader table.
411 * The table resides in a memory-mapped file. (This is a different file
412 * than is used for the main database.)
414 * For POSIX the actual mutexes reside in the shared memory of this
415 * mapped file. On Windows, mutexes are named objects allocated by the
416 * kernel; we store the mutex names in this mapped file so that other
417 * processes can grab them. This same approach will also be used on
418 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
419 * process-shared POSIX mutexes.
421 typedef struct MDB_txbody {
422 /** Stamp identifying this as an MDB lock file. It must be set
425 /** Version number of this lock file. Must be set to #MDB_VERSION. */
426 uint32_t mtb_version;
430 /** Mutex protecting access to this table.
431 * This is the reader lock that #LOCK_MUTEX_R acquires.
433 pthread_mutex_t mtb_mutex;
435 /** The ID of the last transaction committed to the database.
436 * This is recorded here only for convenience; the value can always
437 * be determined by reading the main database meta pages.
440 /** The number of slots that have been used in the reader table.
441 * This always records the maximum count, it is not decremented
442 * when readers release their slots.
444 unsigned mtb_numreaders;
445 /** The ID of the most recent meta page in the database.
446 * This is recorded here only for convenience; the value can always
447 * be determined by reading the main database meta pages.
449 uint32_t mtb_me_toggle;
452 /** The actual reader table definition. */
453 typedef struct MDB_txninfo {
456 #define mti_magic mt1.mtb.mtb_magic
457 #define mti_version mt1.mtb.mtb_version
458 #define mti_mutex mt1.mtb.mtb_mutex
459 #define mti_rmname mt1.mtb.mtb_rmname
460 #define mti_txnid mt1.mtb.mtb_txnid
461 #define mti_numreaders mt1.mtb.mtb_numreaders
462 #define mti_me_toggle mt1.mtb.mtb_me_toggle
463 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
468 #define mti_wmname mt2.mt2_wmname
470 pthread_mutex_t mt2_wmutex;
471 #define mti_wmutex mt2.mt2_wmutex
473 char pad[(sizeof(pthread_mutex_t)+CACHELINE-1) & ~(CACHELINE-1)];
475 MDB_reader mti_readers[1];
479 /** Common header for all page types.
480 * Overflow records occupy a number of contiguous pages with no
481 * headers on any page after the first.
483 typedef struct MDB_page {
484 #define mp_pgno mp_p.p_pgno
485 #define mp_next mp_p.p_next
487 pgno_t p_pgno; /**< page number */
488 void * p_next; /**< for in-memory list of freed structs */
490 /** @defgroup mdb_page Page Flags
492 * Flags for the page headers.
495 #define P_BRANCH 0x01 /**< branch page */
496 #define P_LEAF 0x02 /**< leaf page */
497 #define P_OVERFLOW 0x04 /**< overflow page */
498 #define P_META 0x08 /**< meta page */
499 #define P_DIRTY 0x10 /**< dirty page */
500 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
502 uint32_t mp_flags; /**< @ref mdb_page */
503 #define mp_lower mp_pb.pb.pb_lower
504 #define mp_upper mp_pb.pb.pb_upper
505 #define mp_pages mp_pb.pb_pages
508 indx_t pb_lower; /**< lower bound of free space */
509 indx_t pb_upper; /**< upper bound of free space */
511 uint32_t pb_pages; /**< number of overflow pages */
513 indx_t mp_ptrs[1]; /**< dynamic size */
516 /** Size of the page header, excluding dynamic data at the end */
517 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
519 /** Address of first usable data byte in a page, after the header */
520 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
522 /** Number of nodes on a page */
523 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
525 /** The amount of space remaining in the page */
526 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
528 /** The percentage of space used in the page, in tenths of a percent. */
529 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
530 ((env)->me_psize - PAGEHDRSZ))
531 /** The minimum page fill factor, in tenths of a percent.
532 * Pages emptier than this are candidates for merging.
534 #define FILL_THRESHOLD 250
536 /** Test if a page is a leaf page */
537 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
538 /** Test if a page is a LEAF2 page */
539 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
540 /** Test if a page is a branch page */
541 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
542 /** Test if a page is an overflow page */
543 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
545 /** The number of overflow pages needed to store the given size. */
546 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
548 /** Header for a single key/data pair within a page.
549 * We guarantee 2-byte alignment for nodes.
551 typedef struct MDB_node {
552 /** lo and hi are used for data size on leaf nodes and for
553 * child pgno on branch nodes. On 64 bit platforms, flags
554 * is also used for pgno. (Branch nodes have no flags).
555 * They are in host byte order in case that lets some
556 * accesses be optimized into a 32-bit word access.
558 #define mn_lo mn_offset[__BYTE_ORDER!=__LITTLE_ENDIAN]
559 #define mn_hi mn_offset[__BYTE_ORDER==__LITTLE_ENDIAN] /**< part of dsize or pgno */
560 unsigned short mn_offset[2]; /**< storage for #mn_lo and #mn_hi */
561 /** @defgroup mdb_node Node Flags
563 * Flags for node headers.
566 #define F_BIGDATA 0x01 /**< data put on overflow page */
567 #define F_SUBDATA 0x02 /**< data is a sub-database */
568 #define F_DUPDATA 0x04 /**< data has duplicates */
570 unsigned short mn_flags; /**< @ref mdb_node */
571 unsigned short mn_ksize; /**< key size */
572 char mn_data[1]; /**< key and data are appended here */
575 /** Size of the node header, excluding dynamic data at the end */
576 #define NODESIZE offsetof(MDB_node, mn_data)
578 /** Bit position of top word in page number, for shifting mn_flags */
579 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
581 /** Size of a node in a branch page with a given key.
582 * This is just the node header plus the key, there is no data.
584 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
586 /** Size of a node in a leaf page with a given key and data.
587 * This is node header plus key plus data size.
589 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
591 /** Address of node \b i in page \b p */
592 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
594 /** Address of the key for the node */
595 #define NODEKEY(node) (void *)((node)->mn_data)
597 /** Address of the data for a node */
598 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
600 /** Get the page number pointed to by a branch node */
601 #define NODEPGNO(node) \
602 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
603 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
604 /** Set the page number in a branch node */
605 #define SETPGNO(node,pgno) do { \
606 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
607 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
609 /** Get the size of the data in a leaf node */
610 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
611 /** Set the size of the data for a leaf node */
612 #define SETDSZ(node,size) do { \
613 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
614 /** The size of a key in a node */
615 #define NODEKSZ(node) ((node)->mn_ksize)
617 /** The address of a key in a LEAF2 page.
618 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
619 * There are no node headers, keys are stored contiguously.
621 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
623 /** Set the \b node's key into \b key, if requested. */
624 #define MDB_SET_KEY(node, key) { if ((key) != NULL) { \
625 (key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node); } }
627 /** Information about a single database in the environment. */
628 typedef struct MDB_db {
629 uint32_t md_pad; /**< also ksize for LEAF2 pages */
630 uint16_t md_flags; /**< @ref mdb_open */
631 uint16_t md_depth; /**< depth of this tree */
632 pgno_t md_branch_pages; /**< number of internal pages */
633 pgno_t md_leaf_pages; /**< number of leaf pages */
634 pgno_t md_overflow_pages; /**< number of overflow pages */
635 size_t md_entries; /**< number of data items */
636 pgno_t md_root; /**< the root page of this tree */
639 /** Handle for the DB used to track free pages. */
641 /** Handle for the default DB. */
644 /** Identify a data item as a valid sub-DB record */
645 #define MDB_SUBDATA 0x8200
647 /** Meta page content. */
648 typedef struct MDB_meta {
649 /** Stamp identifying this as an MDB data file. It must be set
652 /** Version number of this lock file. Must be set to #MDB_VERSION. */
654 void *mm_address; /**< address for fixed mapping */
655 size_t mm_mapsize; /**< size of mmap region */
656 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
657 /** The size of pages used in this DB */
658 #define mm_psize mm_dbs[0].md_pad
659 /** Any persistent environment flags. @ref mdb_env */
660 #define mm_flags mm_dbs[0].md_flags
661 pgno_t mm_last_pg; /**< last used page in file */
662 txnid_t mm_txnid; /**< txnid that committed this page */
665 /** Auxiliary DB info.
666 * The information here is mostly static/read-only. There is
667 * only a single copy of this record in the environment.
668 * The \b md_dirty flag is not read-only, but only a write
669 * transaction can ever update it, and only write transactions
670 * need to worry about it.
672 typedef struct MDB_dbx {
673 MDB_val md_name; /**< name of the database */
674 MDB_cmp_func *md_cmp; /**< function for comparing keys */
675 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
676 MDB_rel_func *md_rel; /**< user relocate function */
677 void *md_relctx; /**< user-provided context for md_rel */
678 MDB_dbi md_parent; /**< parent DB of a sub-DB */
679 unsigned int md_dirty; /**< TRUE if DB was written in this txn */
682 /** A database transaction.
683 * Every operation requires a transaction handle.
686 pgno_t mt_next_pgno; /**< next unallocated page */
687 /** The ID of this transaction. IDs are integers incrementing from 1.
688 * Only committed write transactions increment the ID. If a transaction
689 * aborts, the ID may be re-used by the next writer.
692 MDB_env *mt_env; /**< the DB environment */
693 /** The list of pages that became unused during this transaction.
698 ID2L dirty_list; /**< modified pages */
699 MDB_reader *reader; /**< this thread's slot in the reader table */
701 /** Array of records for each DB known in the environment. */
703 /** Array of MDB_db records for each known DB */
705 /** Number of DB records in use. This number only ever increments;
706 * we don't decrement it when individual DB handles are closed.
710 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
711 #define MDB_TXN_ERROR 0x02 /**< an error has occurred */
712 unsigned int mt_flags;
713 /** Tracks which of the two meta pages was used at the start
714 * of this transaction.
716 unsigned int mt_toggle;
719 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
720 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
721 * raise this on a 64 bit machine.
723 #define CURSOR_STACK 32
727 /** Cursors are used for all DB operations */
729 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
730 struct MDB_xcursor *mc_xcursor;
731 /** The transaction that owns this cursor */
733 /** The database handle this cursor operates on */
735 /** The database record for this cursor */
737 /** The database auxiliary record for this cursor */
739 unsigned short mc_snum; /**< number of pushed pages */
740 unsigned short mc_top; /**< index of top page, mc_snum-1 */
741 /** @defgroup mdb_cursor Cursor Flags
743 * Cursor state flags.
746 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
747 #define C_EOF 0x02 /**< No more data */
749 unsigned int mc_flags; /**< @ref mdb_cursor */
750 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
751 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
754 /** Context for sorted-dup records.
755 * We could have gone to a fully recursive design, with arbitrarily
756 * deep nesting of sub-databases. But for now we only handle these
757 * levels - main DB, optional sub-DB, sorted-duplicate DB.
759 typedef struct MDB_xcursor {
760 /** A sub-cursor for traversing the Dup DB */
761 MDB_cursor mx_cursor;
762 /** The database record for this Dup DB */
764 /** The auxiliary DB record for this Dup DB */
768 /** A set of pages freed by an earlier transaction. */
769 typedef struct MDB_oldpages {
770 /** Usually we only read one record from the FREEDB at a time, but
771 * in case we read more, this will chain them together.
773 struct MDB_oldpages *mo_next;
774 /** The ID of the transaction in which these pages were freed. */
776 /** An #IDL of the pages */
777 pgno_t mo_pages[1]; /* dynamic */
780 /** The database environment. */
782 HANDLE me_fd; /**< The main data file */
783 HANDLE me_lfd; /**< The lock file */
784 HANDLE me_mfd; /**< just for writing the meta pages */
785 /** Failed to update the meta page. Probably an I/O error. */
786 #define MDB_FATAL_ERROR 0x80000000U
787 uint32_t me_flags; /**< @ref mdb_env */
788 uint32_t me_extrapad; /**< unused for now */
789 unsigned int me_maxreaders; /**< size of the reader table */
790 MDB_dbi me_numdbs; /**< number of DBs opened */
791 MDB_dbi me_maxdbs; /**< size of the DB table */
792 char *me_path; /**< path to the DB files */
793 char *me_map; /**< the memory map of the data file */
794 MDB_txninfo *me_txns; /**< the memory map of the lock file */
795 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
796 MDB_txn *me_txn; /**< current write transaction */
797 size_t me_mapsize; /**< size of the data memory map */
798 off_t me_size; /**< current file size */
799 pgno_t me_maxpg; /**< me_mapsize / me_psize */
800 unsigned int me_psize; /**< size of a page, from #GET_PAGESIZE */
801 unsigned int me_db_toggle; /**< which DB table is current */
802 MDB_dbx *me_dbxs; /**< array of static DB info */
803 MDB_db *me_dbs[2]; /**< two arrays of MDB_db info */
804 MDB_oldpages *me_pghead; /**< list of old page records */
805 pthread_key_t me_txkey; /**< thread-key for readers */
806 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
807 /** IDL of pages that became unused in a write txn */
808 pgno_t me_free_pgs[MDB_IDL_UM_SIZE];
809 /** ID2L of pages that were written during a write txn */
810 ID2 me_dirty_list[MDB_IDL_UM_SIZE];
811 /** rwlock for the DB tables, if #LAZY_LOCKS is false */
812 LAZY_RWLOCK_DEF(me_dblock)
814 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
818 /** max number of pages to commit in one writev() call */
819 #define MDB_COMMIT_PAGES 64
821 static MDB_page *mdb_page_alloc(MDB_cursor *mc, int num);
822 static MDB_page *mdb_page_new(MDB_cursor *mc, uint32_t flags, int num);
823 static int mdb_page_touch(MDB_cursor *mc);
825 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
826 static int mdb_page_search_root(MDB_cursor *mc,
827 MDB_val *key, int modify);
828 static int mdb_page_search(MDB_cursor *mc,
829 MDB_val *key, int modify);
830 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
831 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
834 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
835 static int mdb_env_read_meta(MDB_env *env, int *which);
836 static int mdb_env_write_meta(MDB_txn *txn);
838 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
839 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
840 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags);
841 static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
842 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
843 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
844 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
845 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
847 static int mdb_rebalance(MDB_cursor *mc);
848 static int mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
850 static void mdb_cursor_pop(MDB_cursor *mc);
851 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
853 static int mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
854 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
855 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
856 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
857 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
859 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
860 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
862 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
863 static void mdb_xcursor_init0(MDB_cursor *mc);
864 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
866 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
869 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
873 static SECURITY_DESCRIPTOR mdb_null_sd;
874 static SECURITY_ATTRIBUTES mdb_all_sa;
875 static int mdb_sec_inited;
878 /** Return the library version info. */
880 mdb_version(int *major, int *minor, int *patch)
882 if (major) *major = MDB_VERSION_MAJOR;
883 if (minor) *minor = MDB_VERSION_MINOR;
884 if (patch) *patch = MDB_VERSION_PATCH;
885 return MDB_VERSION_STRING;
888 /** Table of descriptions for MDB @ref errors */
889 static char *const mdb_errstr[] = {
890 "MDB_KEYEXIST: Key/data pair already exists",
891 "MDB_NOTFOUND: No matching key/data pair found",
892 "MDB_PAGE_NOTFOUND: Requested page not found",
893 "MDB_CORRUPTED: Located page was wrong type",
894 "MDB_PANIC: Update of meta page failed",
895 "MDB_VERSION_MISMATCH: Database environment version mismatch"
899 mdb_strerror(int err)
902 return ("Successful return: 0");
904 if (err >= MDB_KEYEXIST && err <= MDB_VERSION_MISMATCH)
905 return mdb_errstr[err - MDB_KEYEXIST];
907 return strerror(err);
911 /** Display a key in hexadecimal and return the address of the result.
912 * @param[in] key the key to display
913 * @param[in] buf the buffer to write into. Should always be #DKBUF.
914 * @return The key in hexadecimal form.
917 mdb_dkey(MDB_val *key, char *buf)
920 unsigned char *c = key->mv_data;
922 if (key->mv_size > MAXKEYSIZE)
924 /* may want to make this a dynamic check: if the key is mostly
925 * printable characters, print it as-is instead of converting to hex.
928 for (i=0; i<key->mv_size; i++)
929 ptr += sprintf(ptr, "%02x", *c++);
931 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
938 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
940 return txn->mt_dbxs[dbi].md_cmp(a, b);
944 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
946 if (txn->mt_dbxs[dbi].md_dcmp)
947 return txn->mt_dbxs[dbi].md_dcmp(a, b);
949 return EINVAL; /* too bad you can't distinguish this from a valid result */
952 /** Allocate pages for writing.
953 * If there are free pages available from older transactions, they
954 * will be re-used first. Otherwise a new page will be allocated.
955 * @param[in] mc cursor A cursor handle identifying the transaction and
956 * database for which we are allocating.
957 * @param[in] num the number of pages to allocate.
958 * @return Address of the allocated page(s). Requests for multiple pages
959 * will always be satisfied by a single contiguous chunk of memory.
962 mdb_page_alloc(MDB_cursor *mc, int num)
964 MDB_txn *txn = mc->mc_txn;
966 pgno_t pgno = P_INVALID;
969 if (txn->mt_txnid > 2) {
971 if (!txn->mt_env->me_pghead && mc->mc_dbi != FREE_DBI &&
972 txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
973 /* See if there's anything in the free DB */
976 txnid_t *kptr, oldest;
978 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
979 mdb_page_search(&m2, NULL, 0);
980 leaf = NODEPTR(m2.mc_pg[m2.mc_top], 0);
981 kptr = (txnid_t *)NODEKEY(leaf);
985 oldest = txn->mt_txnid - 1;
986 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
987 txnid_t mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
988 if (mr && mr < oldest)
993 if (oldest > *kptr) {
994 /* It's usable, grab it.
1000 mdb_node_read(txn, leaf, &data);
1001 idl = (ID *) data.mv_data;
1002 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
1003 mop->mo_next = txn->mt_env->me_pghead;
1004 mop->mo_txnid = *kptr;
1005 txn->mt_env->me_pghead = mop;
1006 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
1011 DPRINTF("IDL read txn %zu root %zu num %zu",
1012 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1013 for (i=0; i<idl[0]; i++) {
1014 DPRINTF("IDL %zu", idl[i+1]);
1018 /* drop this IDL from the DB */
1019 m2.mc_ki[m2.mc_top] = 0;
1020 m2.mc_flags = C_INITIALIZED;
1021 mdb_cursor_del(&m2, 0);
1024 if (txn->mt_env->me_pghead) {
1025 MDB_oldpages *mop = txn->mt_env->me_pghead;
1027 /* FIXME: For now, always use fresh pages. We
1028 * really ought to search the free list for a
1033 /* peel pages off tail, so we only have to truncate the list */
1034 pgno = MDB_IDL_LAST(mop->mo_pages);
1035 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
1037 if (mop->mo_pages[2] > mop->mo_pages[1])
1038 mop->mo_pages[0] = 0;
1042 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
1043 txn->mt_env->me_pghead = mop->mo_next;
1050 if (pgno == P_INVALID) {
1051 /* DB size is maxed out */
1052 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg) {
1053 assert(txn->mt_next_pgno + num < txn->mt_env->me_maxpg);
1057 if (txn->mt_env->me_dpages && num == 1) {
1058 np = txn->mt_env->me_dpages;
1059 txn->mt_env->me_dpages = np->mp_next;
1061 if ((np = malloc(txn->mt_env->me_psize * num )) == NULL)
1064 if (pgno == P_INVALID) {
1065 np->mp_pgno = txn->mt_next_pgno;
1066 txn->mt_next_pgno += num;
1070 mid.mid = np->mp_pgno;
1072 mdb_mid2l_insert(txn->mt_u.dirty_list, &mid);
1077 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1078 * @param[in] mc cursor pointing to the page to be touched
1079 * @return 0 on success, non-zero on failure.
1082 mdb_page_touch(MDB_cursor *mc)
1084 MDB_page *mp = mc->mc_pg[mc->mc_top];
1087 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1089 if ((np = mdb_page_alloc(mc, 1)) == NULL)
1091 DPRINTF("touched db %u page %zu -> %zu", mc->mc_dbi, mp->mp_pgno, np->mp_pgno);
1092 assert(mp->mp_pgno != np->mp_pgno);
1093 mdb_midl_append(mc->mc_txn->mt_free_pgs, mp->mp_pgno);
1095 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1098 mp->mp_flags |= P_DIRTY;
1100 mc->mc_pg[mc->mc_top] = mp;
1101 /** If this page has a parent, update the parent to point to
1105 SETPGNO(NODEPTR(mc->mc_pg[mc->mc_top-1], mc->mc_ki[mc->mc_top-1]), mp->mp_pgno);
1111 mdb_env_sync(MDB_env *env, int force)
1114 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1115 if (fdatasync(env->me_fd))
1122 mdb_txn_reset0(MDB_txn *txn);
1124 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
1125 * @param[in] txn the transaction handle to initialize
1126 * @return 0 on success, non-zero on failure. This can only
1127 * fail for read-only transactions, and then only if the
1128 * reader table is full.
1131 mdb_txn_renew0(MDB_txn *txn)
1133 MDB_env *env = txn->mt_env;
1135 if (txn->mt_flags & MDB_TXN_RDONLY) {
1136 MDB_reader *r = pthread_getspecific(env->me_txkey);
1139 pid_t pid = getpid();
1140 pthread_t tid = pthread_self();
1143 for (i=0; i<env->me_txns->mti_numreaders; i++)
1144 if (env->me_txns->mti_readers[i].mr_pid == 0)
1146 if (i == env->me_maxreaders) {
1147 UNLOCK_MUTEX_R(env);
1150 env->me_txns->mti_readers[i].mr_pid = pid;
1151 env->me_txns->mti_readers[i].mr_tid = tid;
1152 if (i >= env->me_txns->mti_numreaders)
1153 env->me_txns->mti_numreaders = i+1;
1154 UNLOCK_MUTEX_R(env);
1155 r = &env->me_txns->mti_readers[i];
1156 pthread_setspecific(env->me_txkey, r);
1158 txn->mt_txnid = env->me_txns->mti_txnid;
1159 txn->mt_toggle = env->me_txns->mti_me_toggle;
1160 r->mr_txnid = txn->mt_txnid;
1161 txn->mt_u.reader = r;
1165 txn->mt_txnid = env->me_txns->mti_txnid+1;
1166 txn->mt_toggle = env->me_txns->mti_me_toggle;
1167 txn->mt_u.dirty_list = env->me_dirty_list;
1168 txn->mt_u.dirty_list[0].mid = 0;
1169 txn->mt_free_pgs = env->me_free_pgs;
1170 txn->mt_free_pgs[0] = 0;
1171 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1175 /* Copy the DB arrays */
1176 LAZY_RWLOCK_RDLOCK(&env->me_dblock);
1177 txn->mt_numdbs = env->me_numdbs;
1178 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
1179 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
1180 if (txn->mt_numdbs > 2)
1181 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
1182 (txn->mt_numdbs - 2) * sizeof(MDB_db));
1183 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1189 mdb_txn_renew(MDB_txn *txn)
1196 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
1197 DPUTS("environment had fatal error, must shutdown!");
1201 rc = mdb_txn_renew0(txn);
1202 if (rc == MDB_SUCCESS) {
1203 DPRINTF("renew txn %zu%c %p on mdbenv %p, root page %zu",
1204 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1205 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1211 mdb_txn_begin(MDB_env *env, unsigned int flags, MDB_txn **ret)
1216 if (env->me_flags & MDB_FATAL_ERROR) {
1217 DPUTS("environment had fatal error, must shutdown!");
1220 if ((txn = calloc(1, sizeof(MDB_txn) + env->me_maxdbs * sizeof(MDB_db))) == NULL) {
1221 DPRINTF("calloc: %s", strerror(ErrCode()));
1224 txn->mt_dbs = (MDB_db *)(txn+1);
1225 if (flags & MDB_RDONLY) {
1226 txn->mt_flags |= MDB_TXN_RDONLY;
1230 rc = mdb_txn_renew0(txn);
1235 DPRINTF("begin txn %zu%c %p on mdbenv %p, root page %zu",
1236 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1237 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
1243 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
1244 * @param[in] txn the transaction handle to reset
1247 mdb_txn_reset0(MDB_txn *txn)
1249 MDB_env *env = txn->mt_env;
1251 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1252 txn->mt_u.reader->mr_txnid = 0;
1259 /* return all dirty pages to dpage list */
1260 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1261 dp = txn->mt_u.dirty_list[i].mptr;
1262 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1263 dp->mp_next = txn->mt_env->me_dpages;
1264 txn->mt_env->me_dpages = dp;
1266 /* large pages just get freed directly */
1271 while ((mop = txn->mt_env->me_pghead)) {
1272 txn->mt_env->me_pghead = mop->mo_next;
1277 for (dbi=2; dbi<env->me_numdbs; dbi++)
1278 env->me_dbxs[dbi].md_dirty = 0;
1279 /* The writer mutex was locked in mdb_txn_begin. */
1280 UNLOCK_MUTEX_W(env);
1285 mdb_txn_reset(MDB_txn *txn)
1290 DPRINTF("reset txn %zu%c %p on mdbenv %p, root page %zu",
1291 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1292 (void *) txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1294 mdb_txn_reset0(txn);
1298 mdb_txn_abort(MDB_txn *txn)
1303 DPRINTF("abort txn %zu%c %p on mdbenv %p, root page %zu",
1304 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1305 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1307 mdb_txn_reset0(txn);
1312 mdb_txn_commit(MDB_txn *txn)
1323 assert(txn != NULL);
1324 assert(txn->mt_env != NULL);
1328 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1333 if (txn != env->me_txn) {
1334 DPUTS("attempt to commit unknown transaction");
1339 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1340 DPUTS("error flag is set, can't commit");
1345 if (!txn->mt_u.dirty_list[0].mid)
1348 DPRINTF("committing txn %zu %p on mdbenv %p, root page %zu",
1349 txn->mt_txnid, (void *)txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
1351 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1353 /* should only be one record now */
1354 if (env->me_pghead) {
1355 /* make sure first page of freeDB is touched and on freelist */
1356 mdb_page_search(&mc, NULL, 1);
1358 /* save to free list */
1359 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
1363 /* make sure last page of freeDB is touched and on freelist */
1364 key.mv_size = MAXKEYSIZE+1;
1366 mdb_page_search(&mc, &key, 1);
1368 mdb_midl_sort(txn->mt_free_pgs);
1372 ID *idl = txn->mt_free_pgs;
1373 DPRINTF("IDL write txn %zu root %zu num %zu",
1374 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1375 for (i=0; i<idl[0]; i++) {
1376 DPRINTF("IDL %zu", idl[i+1]);
1380 /* write to last page of freeDB */
1381 key.mv_size = sizeof(pgno_t);
1382 key.mv_data = &txn->mt_txnid;
1383 data.mv_data = txn->mt_free_pgs;
1384 /* The free list can still grow during this call,
1385 * despite the pre-emptive touches above. So check
1386 * and make sure the entire thing got written.
1389 i = txn->mt_free_pgs[0];
1390 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
1391 rc = mdb_cursor_put(&mc, &key, &data, 0);
1396 } while (i != txn->mt_free_pgs[0]);
1398 /* should only be one record now */
1399 if (env->me_pghead) {
1403 mop = env->me_pghead;
1404 key.mv_size = sizeof(pgno_t);
1405 key.mv_data = &mop->mo_txnid;
1406 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
1407 data.mv_data = mop->mo_pages;
1408 mdb_cursor_put(&mc, &key, &data, 0);
1409 free(env->me_pghead);
1410 env->me_pghead = NULL;
1413 /* Update DB root pointers. Their pages have already been
1414 * touched so this is all in-place and cannot fail.
1419 data.mv_size = sizeof(MDB_db);
1421 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
1422 for (i = 2; i < txn->mt_numdbs; i++) {
1423 if (txn->mt_dbxs[i].md_dirty) {
1424 data.mv_data = &txn->mt_dbs[i];
1425 mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
1430 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
1436 /* Windows actually supports scatter/gather I/O, but only on
1437 * unbuffered file handles. Since we're relying on the OS page
1438 * cache for all our data, that's self-defeating. So we just
1439 * write pages one at a time. We use the ov structure to set
1440 * the write offset, to at least save the overhead of a Seek
1444 memset(&ov, 0, sizeof(ov));
1445 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1447 dp = txn->mt_u.dirty_list[i].mptr;
1448 DPRINTF("committing page %zu", dp->mp_pgno);
1449 size = dp->mp_pgno * env->me_psize;
1450 ov.Offset = size & 0xffffffff;
1451 ov.OffsetHigh = size >> 16;
1452 ov.OffsetHigh >>= 16;
1453 /* clear dirty flag */
1454 dp->mp_flags &= ~P_DIRTY;
1455 wsize = env->me_psize;
1456 if (IS_OVERFLOW(dp)) wsize *= dp->mp_pages;
1457 rc = WriteFile(env->me_fd, dp, wsize, NULL, &ov);
1460 DPRINTF("WriteFile: %d", n);
1467 struct iovec iov[MDB_COMMIT_PAGES];
1471 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1472 dp = txn->mt_u.dirty_list[i].mptr;
1473 if (dp->mp_pgno != next) {
1475 DPRINTF("committing %u dirty pages", n);
1476 rc = writev(env->me_fd, iov, n);
1480 DPUTS("short write, filesystem full?");
1482 DPRINTF("writev: %s", strerror(n));
1489 lseek(env->me_fd, dp->mp_pgno * env->me_psize, SEEK_SET);
1492 DPRINTF("committing page %zu", dp->mp_pgno);
1493 iov[n].iov_len = env->me_psize;
1494 if (IS_OVERFLOW(dp)) iov[n].iov_len *= dp->mp_pages;
1495 iov[n].iov_base = dp;
1496 size += iov[n].iov_len;
1497 next = dp->mp_pgno + (IS_OVERFLOW(dp) ? dp->mp_pages : 1);
1498 /* clear dirty flag */
1499 dp->mp_flags &= ~P_DIRTY;
1500 if (++n >= MDB_COMMIT_PAGES) {
1510 DPRINTF("committing %u dirty pages", n);
1511 rc = writev(env->me_fd, iov, n);
1515 DPUTS("short write, filesystem full?");
1517 DPRINTF("writev: %s", strerror(n));
1524 /* Drop the dirty pages.
1526 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1527 dp = txn->mt_u.dirty_list[i].mptr;
1528 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1529 dp->mp_next = txn->mt_env->me_dpages;
1530 txn->mt_env->me_dpages = dp;
1534 txn->mt_u.dirty_list[i].mid = 0;
1536 txn->mt_u.dirty_list[0].mid = 0;
1538 if ((n = mdb_env_sync(env, 0)) != 0 ||
1539 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
1546 /* update the DB tables */
1548 int toggle = !env->me_db_toggle;
1552 ip = &env->me_dbs[toggle][2];
1553 jp = &txn->mt_dbs[2];
1554 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1555 for (i = 2; i < txn->mt_numdbs; i++) {
1556 if (ip->md_root != jp->md_root)
1561 for (i = 2; i < txn->mt_numdbs; i++) {
1562 if (txn->mt_dbxs[i].md_dirty)
1563 txn->mt_dbxs[i].md_dirty = 0;
1565 env->me_db_toggle = toggle;
1566 env->me_numdbs = txn->mt_numdbs;
1567 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1570 UNLOCK_MUTEX_W(env);
1576 /** Read the environment parameters of a DB environment before
1577 * mapping it into memory.
1578 * @param[in] env the environment handle
1579 * @param[out] meta address of where to store the meta information
1580 * @return 0 on success, non-zero on failure.
1583 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
1585 char page[PAGESIZE];
1590 /* We don't know the page size yet, so use a minimum value.
1594 if (!ReadFile(env->me_fd, page, PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
1596 if ((rc = read(env->me_fd, page, PAGESIZE)) == 0)
1601 else if (rc != PAGESIZE) {
1605 DPRINTF("read: %s", strerror(err));
1609 p = (MDB_page *)page;
1611 if (!F_ISSET(p->mp_flags, P_META)) {
1612 DPRINTF("page %zu not a meta page", p->mp_pgno);
1617 if (m->mm_magic != MDB_MAGIC) {
1618 DPUTS("meta has invalid magic");
1622 if (m->mm_version != MDB_VERSION) {
1623 DPRINTF("database is version %u, expected version %u",
1624 m->mm_version, MDB_VERSION);
1625 return MDB_VERSION_MISMATCH;
1628 memcpy(meta, m, sizeof(*m));
1632 /** Write the environment parameters of a freshly created DB environment.
1633 * @param[in] env the environment handle
1634 * @param[out] meta address of where to store the meta information
1635 * @return 0 on success, non-zero on failure.
1638 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
1645 DPUTS("writing new meta page");
1647 GET_PAGESIZE(psize);
1649 meta->mm_magic = MDB_MAGIC;
1650 meta->mm_version = MDB_VERSION;
1651 meta->mm_psize = psize;
1652 meta->mm_last_pg = 1;
1653 meta->mm_flags = env->me_flags & 0xffff;
1654 meta->mm_flags |= MDB_INTEGERKEY;
1655 meta->mm_dbs[0].md_root = P_INVALID;
1656 meta->mm_dbs[1].md_root = P_INVALID;
1658 p = calloc(2, psize);
1660 p->mp_flags = P_META;
1663 memcpy(m, meta, sizeof(*meta));
1665 q = (MDB_page *)((char *)p + psize);
1668 q->mp_flags = P_META;
1671 memcpy(m, meta, sizeof(*meta));
1676 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
1677 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
1680 rc = write(env->me_fd, p, psize * 2);
1681 rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
1687 /** Update the environment info to commit a transaction.
1688 * @param[in] txn the transaction that's being committed
1689 * @return 0 on success, non-zero on failure.
1692 mdb_env_write_meta(MDB_txn *txn)
1695 MDB_meta meta, metab;
1697 int rc, len, toggle;
1703 assert(txn != NULL);
1704 assert(txn->mt_env != NULL);
1706 toggle = !txn->mt_toggle;
1707 DPRINTF("writing meta page %d for root page %zu",
1708 toggle, txn->mt_dbs[MAIN_DBI].md_root);
1712 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
1713 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
1715 ptr = (char *)&meta;
1716 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
1717 len = sizeof(MDB_meta) - off;
1720 meta.mm_dbs[0] = txn->mt_dbs[0];
1721 meta.mm_dbs[1] = txn->mt_dbs[1];
1722 meta.mm_last_pg = txn->mt_next_pgno - 1;
1723 meta.mm_txnid = txn->mt_txnid;
1726 off += env->me_psize;
1729 /* Write to the SYNC fd */
1732 memset(&ov, 0, sizeof(ov));
1734 WriteFile(env->me_mfd, ptr, len, (DWORD *)&rc, &ov);
1737 rc = pwrite(env->me_mfd, ptr, len, off);
1742 DPUTS("write failed, disk error?");
1743 /* On a failure, the pagecache still contains the new data.
1744 * Write some old data back, to prevent it from being used.
1745 * Use the non-SYNC fd; we know it will fail anyway.
1747 meta.mm_last_pg = metab.mm_last_pg;
1748 meta.mm_txnid = metab.mm_txnid;
1750 WriteFile(env->me_fd, ptr, len, NULL, &ov);
1752 r2 = pwrite(env->me_fd, ptr, len, off);
1754 env->me_flags |= MDB_FATAL_ERROR;
1757 /* Memory ordering issues are irrelevant; since the entire writer
1758 * is wrapped by wmutex, all of these changes will become visible
1759 * after the wmutex is unlocked. Since the DB is multi-version,
1760 * readers will get consistent data regardless of how fresh or
1761 * how stale their view of these values is.
1763 LAZY_MUTEX_LOCK(&env->me_txns->mti_mutex);
1764 txn->mt_env->me_txns->mti_me_toggle = toggle;
1765 txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
1766 LAZY_MUTEX_UNLOCK(&env->me_txns->mti_mutex);
1771 /** Check both meta pages to see which one is newer.
1772 * @param[in] env the environment handle
1773 * @param[out] which address of where to store the meta toggle ID
1774 * @return 0 on success, non-zero on failure.
1777 mdb_env_read_meta(MDB_env *env, int *which)
1781 assert(env != NULL);
1783 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1786 DPRINTF("Using meta page %d", toggle);
1793 mdb_env_create(MDB_env **env)
1797 e = calloc(1, sizeof(MDB_env));
1801 e->me_maxreaders = DEFAULT_READERS;
1803 e->me_fd = INVALID_HANDLE_VALUE;
1804 e->me_lfd = INVALID_HANDLE_VALUE;
1805 e->me_mfd = INVALID_HANDLE_VALUE;
1811 mdb_env_set_mapsize(MDB_env *env, size_t size)
1815 env->me_mapsize = size;
1820 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
1824 env->me_maxdbs = dbs;
1829 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
1831 if (env->me_map || readers < 1)
1833 env->me_maxreaders = readers;
1838 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
1840 if (!env || !readers)
1842 *readers = env->me_maxreaders;
1846 /** Further setup required for opening an MDB environment
1849 mdb_env_open2(MDB_env *env, unsigned int flags)
1851 int i, newenv = 0, toggle;
1855 env->me_flags = flags;
1857 memset(&meta, 0, sizeof(meta));
1859 if ((i = mdb_env_read_header(env, &meta)) != 0) {
1862 DPUTS("new mdbenv");
1866 if (!env->me_mapsize) {
1867 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
1873 LONG sizelo, sizehi;
1874 sizelo = env->me_mapsize & 0xffffffff;
1875 sizehi = env->me_mapsize >> 16; /* pointless on WIN32, only needed on W64 */
1877 /* Windows won't create mappings for zero length files.
1878 * Just allocate the maxsize right now.
1881 SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
1882 if (!SetEndOfFile(env->me_fd))
1884 SetFilePointer(env->me_fd, 0, NULL, 0);
1886 mh = CreateFileMapping(env->me_fd, NULL, PAGE_READONLY,
1887 sizehi, sizelo, NULL);
1890 env->me_map = MapViewOfFileEx(mh, FILE_MAP_READ, 0, 0, env->me_mapsize,
1898 if (meta.mm_address && (flags & MDB_FIXEDMAP))
1900 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
1902 if (env->me_map == MAP_FAILED)
1907 meta.mm_mapsize = env->me_mapsize;
1908 if (flags & MDB_FIXEDMAP)
1909 meta.mm_address = env->me_map;
1910 i = mdb_env_init_meta(env, &meta);
1911 if (i != MDB_SUCCESS) {
1912 munmap(env->me_map, env->me_mapsize);
1916 env->me_psize = meta.mm_psize;
1918 env->me_maxpg = env->me_mapsize / env->me_psize;
1920 p = (MDB_page *)env->me_map;
1921 env->me_metas[0] = METADATA(p);
1922 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
1924 if ((i = mdb_env_read_meta(env, &toggle)) != 0)
1927 DPRINTF("opened database version %u, pagesize %u",
1928 env->me_metas[toggle]->mm_version, env->me_psize);
1929 DPRINTF("depth: %u", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_depth);
1930 DPRINTF("entries: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_entries);
1931 DPRINTF("branch pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_branch_pages);
1932 DPRINTF("leaf pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_leaf_pages);
1933 DPRINTF("overflow pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_overflow_pages);
1934 DPRINTF("root: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_root);
1940 /** Release a reader thread's slot in the reader lock table.
1941 * This function is called automatically when a thread exits.
1942 * Windows doesn't support destructor callbacks for thread-specific storage,
1943 * so this function is not compiled there.
1944 * @param[in] ptr This points to the slot in the reader lock table.
1947 mdb_env_reader_dest(void *ptr)
1949 MDB_reader *reader = ptr;
1951 reader->mr_txnid = 0;
1957 /** Downgrade the exclusive lock on the region back to shared */
1959 mdb_env_share_locks(MDB_env *env)
1963 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1965 env->me_txns->mti_me_toggle = toggle;
1966 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
1971 /* First acquire a shared lock. The Unlock will
1972 * then release the existing exclusive lock.
1974 memset(&ov, 0, sizeof(ov));
1975 LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov);
1976 UnlockFile(env->me_lfd, 0, 0, 1, 0);
1980 struct flock lock_info;
1981 /* The shared lock replaces the existing lock */
1982 memset((void *)&lock_info, 0, sizeof(lock_info));
1983 lock_info.l_type = F_RDLCK;
1984 lock_info.l_whence = SEEK_SET;
1985 lock_info.l_start = 0;
1986 lock_info.l_len = 1;
1987 fcntl(env->me_lfd, F_SETLK, &lock_info);
1992 /** Open and/or initialize the lock region for the environment.
1993 * @param[in] env The MDB environment.
1994 * @param[in] lpath The pathname of the file used for the lock region.
1995 * @param[in] mode The Unix permissions for the file, if we create it.
1996 * @param[out] excl Set to true if we got an exclusive lock on the region.
1997 * @return 0 on success, non-zero on failure.
2000 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
2008 if ((env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
2009 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
2010 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
2014 /* Try to get exclusive lock. If we succeed, then
2015 * nobody is using the lock region and we should initialize it.
2018 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
2022 memset(&ov, 0, sizeof(ov));
2023 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
2029 size = GetFileSize(env->me_lfd, NULL);
2031 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
2035 /* Try to get exclusive lock. If we succeed, then
2036 * nobody is using the lock region and we should initialize it.
2039 struct flock lock_info;
2040 memset((void *)&lock_info, 0, sizeof(lock_info));
2041 lock_info.l_type = F_WRLCK;
2042 lock_info.l_whence = SEEK_SET;
2043 lock_info.l_start = 0;
2044 lock_info.l_len = 1;
2045 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
2049 lock_info.l_type = F_RDLCK;
2050 rc = fcntl(env->me_lfd, F_SETLKW, &lock_info);
2057 size = lseek(env->me_lfd, 0, SEEK_END);
2059 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
2060 if (size < rsize && *excl) {
2062 SetFilePointer(env->me_lfd, rsize, NULL, 0);
2063 if (!SetEndOfFile(env->me_lfd)) {
2068 if (ftruncate(env->me_lfd, rsize) != 0) {
2075 size = rsize - sizeof(MDB_txninfo);
2076 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
2081 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
2087 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
2089 if (!env->me_txns) {
2095 env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
2097 if (env->me_txns == MAP_FAILED) {
2105 if (!mdb_sec_inited) {
2106 InitializeSecurityDescriptor(&mdb_null_sd,
2107 SECURITY_DESCRIPTOR_REVISION);
2108 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
2109 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2110 mdb_all_sa.bInheritHandle = FALSE;
2111 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
2114 /* FIXME: only using up to 20 characters of the env path here,
2115 * probably not enough to assure uniqueness...
2117 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%.20s", lpath);
2118 ptr = env->me_txns->mti_rmname + sizeof("Global\\MDBr");
2119 while ((ptr = strchr(ptr, '\\')))
2121 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
2122 if (!env->me_rmutex) {
2126 sprintf(env->me_txns->mti_rmname, "Global\\MDBw%.20s", lpath);
2127 ptr = env->me_txns->mti_rmname + sizeof("Global\\MDBw");
2128 while ((ptr = strchr(ptr, '\\')))
2130 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
2131 if (!env->me_wmutex) {
2136 pthread_mutexattr_t mattr;
2138 pthread_mutexattr_init(&mattr);
2139 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
2143 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
2144 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
2146 env->me_txns->mti_version = MDB_VERSION;
2147 env->me_txns->mti_magic = MDB_MAGIC;
2148 env->me_txns->mti_txnid = 0;
2149 env->me_txns->mti_numreaders = 0;
2150 env->me_txns->mti_me_toggle = 0;
2153 if (env->me_txns->mti_magic != MDB_MAGIC) {
2154 DPUTS("lock region has invalid magic");
2158 if (env->me_txns->mti_version != MDB_VERSION) {
2159 DPRINTF("lock region is version %u, expected version %u",
2160 env->me_txns->mti_version, MDB_VERSION);
2161 rc = MDB_VERSION_MISMATCH;
2165 if (rc != EACCES && rc != EAGAIN) {
2169 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
2170 if (!env->me_rmutex) {
2174 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
2175 if (!env->me_wmutex) {
2185 env->me_lfd = INVALID_HANDLE_VALUE;
2190 /** The name of the lock file in the DB environment */
2191 #define LOCKNAME "/lock.mdb"
2192 /** The name of the data file in the DB environment */
2193 #define DATANAME "/data.mdb"
2195 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
2197 int oflags, rc, len, excl;
2198 char *lpath, *dpath;
2201 lpath = malloc(len + sizeof(LOCKNAME) + len + sizeof(DATANAME));
2204 dpath = lpath + len + sizeof(LOCKNAME);
2205 sprintf(lpath, "%s" LOCKNAME, path);
2206 sprintf(dpath, "%s" DATANAME, path);
2208 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
2213 if (F_ISSET(flags, MDB_RDONLY)) {
2214 oflags = GENERIC_READ;
2215 len = OPEN_EXISTING;
2217 oflags = GENERIC_READ|GENERIC_WRITE;
2220 mode = FILE_ATTRIBUTE_NORMAL;
2221 if ((env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2222 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2227 if (F_ISSET(flags, MDB_RDONLY))
2230 oflags = O_RDWR | O_CREAT;
2232 if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
2238 if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
2239 /* synchronous fd for meta writes */
2241 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2242 mode |= FILE_FLAG_WRITE_THROUGH;
2243 if ((env->me_mfd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2244 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2249 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2250 oflags |= MDB_DSYNC;
2251 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
2256 env->me_path = strdup(path);
2257 DPRINTF("opened dbenv %p", (void *) env);
2258 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
2259 LAZY_RWLOCK_INIT(&env->me_dblock, NULL);
2261 mdb_env_share_locks(env);
2262 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
2263 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
2264 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
2270 if (env->me_fd != INVALID_HANDLE_VALUE) {
2272 env->me_fd = INVALID_HANDLE_VALUE;
2274 if (env->me_lfd != INVALID_HANDLE_VALUE) {
2276 env->me_lfd = INVALID_HANDLE_VALUE;
2284 mdb_env_close(MDB_env *env)
2291 while (env->me_dpages) {
2292 dp = env->me_dpages;
2293 env->me_dpages = dp->mp_next;
2297 free(env->me_dbs[1]);
2298 free(env->me_dbs[0]);
2302 LAZY_RWLOCK_DESTROY(&env->me_dblock);
2303 pthread_key_delete(env->me_txkey);
2306 munmap(env->me_map, env->me_mapsize);
2311 pid_t pid = getpid();
2313 for (i=0; i<env->me_txns->mti_numreaders; i++)
2314 if (env->me_txns->mti_readers[i].mr_pid == pid)
2315 env->me_txns->mti_readers[i].mr_pid = 0;
2316 munmap(env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
2322 /** Compare two items pointing at aligned size_t's */
2324 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
2326 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
2327 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
2330 /** Compare two items pointing at aligned int's */
2332 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
2334 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
2335 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
2338 /** Compare two items pointing at ints of unknown alignment.
2339 * Nodes and keys are guaranteed to be 2-byte aligned.
2342 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
2344 #if __BYTE_ORDER == __LITTLE_ENDIAN
2345 unsigned short *u, *c;
2348 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
2349 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
2352 } while(!x && u > (unsigned short *)a->mv_data);
2355 return memcmp(a->mv_data, b->mv_data, a->mv_size);
2359 /** Compare two items lexically */
2361 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
2368 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
2374 diff = memcmp(a->mv_data, b->mv_data, len);
2375 return diff ? diff : len_diff<0 ? -1 : len_diff;
2378 /** Compare two items in reverse byte order */
2380 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
2382 const unsigned char *p1, *p2, *p1_lim;
2386 p1_lim = (const unsigned char *)a->mv_data;
2387 p1 = (const unsigned char *)a->mv_data + a->mv_size;
2388 p2 = (const unsigned char *)b->mv_data + b->mv_size;
2390 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
2396 while (p1 > p1_lim) {
2397 diff = *--p1 - *--p2;
2401 return len_diff<0 ? -1 : len_diff;
2404 /** Search for key within a page, using binary search.
2405 * Returns the smallest entry larger or equal to the key.
2406 * If exactp is non-null, stores whether the found entry was an exact match
2407 * in *exactp (1 or 0).
2408 * Updates the cursor index with the index of the found entry.
2409 * If no entry larger or equal to the key is found, returns NULL.
2412 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
2414 unsigned int i = 0, nkeys;
2417 MDB_page *mp = mc->mc_pg[mc->mc_top];
2418 MDB_node *node = NULL;
2423 nkeys = NUMKEYS(mp);
2425 DPRINTF("searching %u keys in %s page %zu",
2426 nkeys, IS_LEAF(mp) ? "leaf" : "branch",
2431 low = IS_LEAF(mp) ? 0 : 1;
2433 cmp = mc->mc_dbx->md_cmp;
2435 /* Branch pages have no data, so if using integer keys,
2436 * alignment is guaranteed. Use faster mdb_cmp_int.
2438 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
2439 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
2446 nodekey.mv_size = mc->mc_db->md_pad;
2447 node = NODEPTR(mp, 0); /* fake */
2448 while (low <= high) {
2449 i = (low + high) >> 1;
2450 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
2451 rc = cmp(key, &nodekey);
2452 DPRINTF("found leaf index %u [%s], rc = %i",
2453 i, DKEY(&nodekey), rc);
2462 while (low <= high) {
2463 i = (low + high) >> 1;
2465 node = NODEPTR(mp, i);
2466 nodekey.mv_size = NODEKSZ(node);
2467 nodekey.mv_data = NODEKEY(node);
2469 rc = cmp(key, &nodekey);
2472 DPRINTF("found leaf index %u [%s], rc = %i",
2473 i, DKEY(&nodekey), rc);
2475 DPRINTF("found branch index %u [%s -> %zu], rc = %i",
2476 i, DKEY(&nodekey), NODEPGNO(node), rc);
2487 if (rc > 0) { /* Found entry is less than the key. */
2488 i++; /* Skip to get the smallest entry larger than key. */
2490 node = NODEPTR(mp, i);
2493 *exactp = (rc == 0);
2494 /* store the key index */
2495 mc->mc_ki[mc->mc_top] = i;
2497 /* There is no entry larger or equal to the key. */
2500 /* nodeptr is fake for LEAF2 */
2504 /** Pop a page off the top of the cursor's stack. */
2506 mdb_cursor_pop(MDB_cursor *mc)
2511 top = mc->mc_pg[mc->mc_top];
2516 DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
2517 mc->mc_dbi, (void *) mc);
2521 /** Push a page onto the top of the cursor's stack. */
2523 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
2525 DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
2526 mc->mc_dbi, (void *) mc);
2528 if (mc->mc_snum >= CURSOR_STACK) {
2529 assert(mc->mc_snum < CURSOR_STACK);
2533 mc->mc_top = mc->mc_snum++;
2534 mc->mc_pg[mc->mc_top] = mp;
2535 mc->mc_ki[mc->mc_top] = 0;
2540 /** Find the address of the page corresponding to a given page number.
2541 * @param[in] txn the transaction for this access.
2542 * @param[in] pgno the page number for the page to retrieve.
2543 * @param[out] ret address of a pointer where the page's address will be stored.
2544 * @return 0 on success, non-zero on failure.
2547 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
2551 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
2553 x = mdb_mid2l_search(txn->mt_u.dirty_list, pgno);
2554 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
2555 p = txn->mt_u.dirty_list[x].mptr;
2559 if (pgno <= txn->mt_env->me_metas[txn->mt_toggle]->mm_last_pg)
2560 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
2564 DPRINTF("page %zu not found", pgno);
2567 return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
2570 /** Search for the page a given key should be in.
2571 * Pushes parent pages on the cursor stack. This function continues a
2572 * search on a cursor that has already been initialized. (Usually by
2573 * #mdb_page_search() but also by #mdb_node_move().)
2574 * @param[in,out] mc the cursor for this operation.
2575 * @param[in] key the key to search for. If NULL, search for the lowest
2576 * page. (This is used by #mdb_cursor_first().)
2577 * @param[in] modify If true, visited pages are updated with new page numbers.
2578 * @return 0 on success, non-zero on failure.
2581 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
2583 MDB_page *mp = mc->mc_pg[mc->mc_top];
2588 while (IS_BRANCH(mp)) {
2592 DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
2593 assert(NUMKEYS(mp) > 1);
2594 DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
2596 if (key == NULL) /* Initialize cursor to first page. */
2598 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
2599 /* cursor to last page */
2603 node = mdb_node_search(mc, key, &exact);
2605 i = NUMKEYS(mp) - 1;
2607 i = mc->mc_ki[mc->mc_top];
2616 DPRINTF("following index %u for key [%s]",
2618 assert(i < NUMKEYS(mp));
2619 node = NODEPTR(mp, i);
2621 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp)))
2624 mc->mc_ki[mc->mc_top] = i;
2625 if ((rc = mdb_cursor_push(mc, mp)))
2629 if ((rc = mdb_page_touch(mc)) != 0)
2631 mp = mc->mc_pg[mc->mc_top];
2636 DPRINTF("internal error, index points to a %02X page!?",
2638 return MDB_CORRUPTED;
2641 DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
2642 key ? DKEY(key) : NULL);
2647 /** Search for the page a given key should be in.
2648 * Pushes parent pages on the cursor stack. This function just sets up
2649 * the search; it finds the root page for \b mc's database and sets this
2650 * as the root of the cursor's stack. Then #mdb_page_search_root() is
2651 * called to complete the search.
2652 * @param[in,out] mc the cursor for this operation.
2653 * @param[in] key the key to search for. If NULL, search for the lowest
2654 * page. (This is used by #mdb_cursor_first().)
2655 * @param[in] modify If true, visited pages are updated with new page numbers.
2656 * @return 0 on success, non-zero on failure.
2659 mdb_page_search(MDB_cursor *mc, MDB_val *key, int modify)
2664 /* Make sure the txn is still viable, then find the root from
2665 * the txn's db table.
2667 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
2668 DPUTS("transaction has failed, must abort");
2671 root = mc->mc_db->md_root;
2673 if (root == P_INVALID) { /* Tree is empty. */
2674 DPUTS("tree is empty");
2675 return MDB_NOTFOUND;
2678 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0])))
2684 DPRINTF("db %u root page %zu has flags 0x%X",
2685 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
2688 /* For sub-databases, update main root first */
2689 if (mc->mc_dbi > MAIN_DBI && !mc->mc_dbx->md_dirty) {
2691 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
2692 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 1);
2695 mc->mc_dbx->md_dirty = 1;
2697 if (!F_ISSET(mc->mc_pg[0]->mp_flags, P_DIRTY)) {
2698 if ((rc = mdb_page_touch(mc)))
2700 mc->mc_db->md_root = mc->mc_pg[0]->mp_pgno;
2704 return mdb_page_search_root(mc, key, modify);
2707 /** Return the data associated with a given node.
2708 * @param[in] txn The transaction for this operation.
2709 * @param[in] leaf The node being read.
2710 * @param[out] data Updated to point to the node's data.
2711 * @return 0 on success, non-zero on failure.
2714 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
2716 MDB_page *omp; /* overflow page */
2720 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
2721 data->mv_size = NODEDSZ(leaf);
2722 data->mv_data = NODEDATA(leaf);
2726 /* Read overflow data.
2728 data->mv_size = NODEDSZ(leaf);
2729 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
2730 if ((rc = mdb_page_get(txn, pgno, &omp))) {
2731 DPRINTF("read overflow page %zu failed", pgno);
2734 data->mv_data = METADATA(omp);
2740 mdb_get(MDB_txn *txn, MDB_dbi dbi,
2741 MDB_val *key, MDB_val *data)
2750 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
2752 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
2755 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2759 mdb_cursor_init(&mc, txn, dbi, &mx);
2760 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
2763 /** Find a sibling for a page.
2764 * Replaces the page at the top of the cursor's stack with the
2765 * specified sibling, if one exists.
2766 * @param[in] mc The cursor for this operation.
2767 * @param[in] move_right Non-zero if the right sibling is requested,
2768 * otherwise the left sibling.
2769 * @return 0 on success, non-zero on failure.
2772 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
2778 if (mc->mc_snum < 2) {
2779 return MDB_NOTFOUND; /* root has no siblings */
2783 DPRINTF("parent page is page %zu, index %u",
2784 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]);
2786 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
2787 : (mc->mc_ki[mc->mc_top] == 0)) {
2788 DPRINTF("no more keys left, moving to %s sibling",
2789 move_right ? "right" : "left");
2790 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS)
2794 mc->mc_ki[mc->mc_top]++;
2796 mc->mc_ki[mc->mc_top]--;
2797 DPRINTF("just moving to %s index key %u",
2798 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]);
2800 assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
2802 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
2803 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp)))
2806 mdb_cursor_push(mc, mp);
2811 /** Move the cursor to the next data item. */
2813 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
2819 if (mc->mc_flags & C_EOF) {
2820 return MDB_NOTFOUND;
2823 assert(mc->mc_flags & C_INITIALIZED);
2825 mp = mc->mc_pg[mc->mc_top];
2827 if (mc->mc_db->md_flags & MDB_DUPSORT) {
2828 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
2829 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2830 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
2831 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
2832 if (op != MDB_NEXT || rc == MDB_SUCCESS)
2836 mc->mc_xcursor->mx_cursor.mc_flags = 0;
2837 if (op == MDB_NEXT_DUP)
2838 return MDB_NOTFOUND;
2842 DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
2844 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
2845 DPUTS("=====> move to next sibling page");
2846 if (mdb_cursor_sibling(mc, 1) != MDB_SUCCESS) {
2847 mc->mc_flags |= C_EOF;
2848 return MDB_NOTFOUND;
2850 mp = mc->mc_pg[mc->mc_top];
2851 DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
2853 mc->mc_ki[mc->mc_top]++;
2855 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
2856 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
2859 key->mv_size = mc->mc_db->md_pad;
2860 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
2864 assert(IS_LEAF(mp));
2865 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
2867 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2868 mdb_xcursor_init1(mc, leaf);
2871 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
2874 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2875 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
2876 if (rc != MDB_SUCCESS)
2881 MDB_SET_KEY(leaf, key);
2885 /** Move the cursor to the previous data item. */
2887 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
2893 assert(mc->mc_flags & C_INITIALIZED);
2895 mp = mc->mc_pg[mc->mc_top];
2897 if (mc->mc_db->md_flags & MDB_DUPSORT) {
2898 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
2899 if (op == MDB_PREV || op == MDB_PREV_DUP) {
2900 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2901 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
2902 if (op != MDB_PREV || rc == MDB_SUCCESS)
2905 mc->mc_xcursor->mx_cursor.mc_flags = 0;
2906 if (op == MDB_PREV_DUP)
2907 return MDB_NOTFOUND;
2912 DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
2914 if (mc->mc_ki[mc->mc_top] == 0) {
2915 DPUTS("=====> move to prev sibling page");
2916 if (mdb_cursor_sibling(mc, 0) != MDB_SUCCESS) {
2917 mc->mc_flags &= ~C_INITIALIZED;
2918 return MDB_NOTFOUND;
2920 mp = mc->mc_pg[mc->mc_top];
2921 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
2922 DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
2924 mc->mc_ki[mc->mc_top]--;
2926 mc->mc_flags &= ~C_EOF;
2928 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
2929 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
2932 key->mv_size = mc->mc_db->md_pad;
2933 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
2937 assert(IS_LEAF(mp));
2938 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
2940 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2941 mdb_xcursor_init1(mc, leaf);
2944 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
2947 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2948 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
2949 if (rc != MDB_SUCCESS)
2954 MDB_SET_KEY(leaf, key);
2958 /** Set the cursor on a specific data item. */
2960 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
2961 MDB_cursor_op op, int *exactp)
2970 assert(key->mv_size > 0);
2972 /* See if we're already on the right page */
2973 if (mc->mc_flags & C_INITIALIZED) {
2976 mp = mc->mc_pg[mc->mc_top];
2977 if (mp->mp_flags & P_LEAF2) {
2978 nodekey.mv_size = mc->mc_db->md_pad;
2979 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
2981 leaf = NODEPTR(mp, 0);
2982 MDB_SET_KEY(leaf, &nodekey);
2984 rc = mc->mc_dbx->md_cmp(key, &nodekey);
2986 /* Probably happens rarely, but first node on the page
2987 * was the one we wanted.
2989 mc->mc_ki[mc->mc_top] = 0;
2990 leaf = NODEPTR(mp, 0);
2997 unsigned int nkeys = NUMKEYS(mp);
2999 if (mp->mp_flags & P_LEAF2) {
3000 nodekey.mv_data = LEAF2KEY(mp,
3001 nkeys-1, nodekey.mv_size);
3003 leaf = NODEPTR(mp, nkeys-1);
3004 MDB_SET_KEY(leaf, &nodekey);
3006 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3008 /* last node was the one we wanted */
3009 mc->mc_ki[mc->mc_top] = nkeys-1;
3010 leaf = NODEPTR(mp, nkeys-1);
3016 /* This is definitely the right page, skip search_page */
3021 /* If any parents have right-sibs, search.
3022 * Otherwise, there's nothing further.
3024 for (i=0; i<mc->mc_top; i++)
3026 NUMKEYS(mc->mc_pg[i])-1)
3028 if (i == mc->mc_top) {
3029 /* There are no other pages */
3030 mc->mc_ki[mc->mc_top] = nkeys;
3031 return MDB_NOTFOUND;
3036 rc = mdb_page_search(mc, key, 0);
3037 if (rc != MDB_SUCCESS)
3040 mp = mc->mc_pg[mc->mc_top];
3041 assert(IS_LEAF(mp));
3044 leaf = mdb_node_search(mc, key, exactp);
3045 if (exactp != NULL && !*exactp) {
3046 /* MDB_SET specified and not an exact match. */
3047 return MDB_NOTFOUND;
3051 DPUTS("===> inexact leaf not found, goto sibling");
3052 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
3053 return rc; /* no entries matched */
3054 mp = mc->mc_pg[mc->mc_top];
3055 assert(IS_LEAF(mp));
3056 leaf = NODEPTR(mp, 0);
3060 mc->mc_flags |= C_INITIALIZED;
3061 mc->mc_flags &= ~C_EOF;
3064 key->mv_size = mc->mc_db->md_pad;
3065 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3069 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3070 mdb_xcursor_init1(mc, leaf);
3073 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3074 if (op == MDB_SET || op == MDB_SET_RANGE) {
3075 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3078 if (op == MDB_GET_BOTH) {
3084 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
3085 if (rc != MDB_SUCCESS)
3088 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
3090 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
3092 rc = mc->mc_dbx->md_dcmp(data, &d2);
3094 if (op == MDB_GET_BOTH || rc > 0)
3095 return MDB_NOTFOUND;
3100 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3101 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3106 /* The key already matches in all other cases */
3107 if (op == MDB_SET_RANGE)
3108 MDB_SET_KEY(leaf, key);
3109 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
3114 /** Move the cursor to the first item in the database. */
3116 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3121 rc = mdb_page_search(mc, NULL, 0);
3122 if (rc != MDB_SUCCESS)
3124 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3126 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
3127 mc->mc_flags |= C_INITIALIZED;
3128 mc->mc_flags &= ~C_EOF;
3130 mc->mc_ki[mc->mc_top] = 0;
3132 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3133 key->mv_size = mc->mc_db->md_pad;
3134 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
3139 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3140 mdb_xcursor_init1(mc, leaf);
3141 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3146 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3147 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3151 MDB_SET_KEY(leaf, key);
3155 /** Move the cursor to the last item in the database. */
3157 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3163 lkey.mv_size = MAXKEYSIZE+1;
3164 lkey.mv_data = NULL;
3166 rc = mdb_page_search(mc, &lkey, 0);
3167 if (rc != MDB_SUCCESS)
3169 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3171 leaf = NODEPTR(mc->mc_pg[mc->mc_top], NUMKEYS(mc->mc_pg[mc->mc_top])-1);
3172 mc->mc_flags |= C_INITIALIZED;
3173 mc->mc_flags &= ~C_EOF;
3175 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
3177 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3178 key->mv_size = mc->mc_db->md_pad;
3179 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
3184 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3185 mdb_xcursor_init1(mc, leaf);
3186 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3191 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3192 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3197 MDB_SET_KEY(leaf, key);
3202 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3212 case MDB_GET_BOTH_RANGE:
3213 if (data == NULL || mc->mc_xcursor == NULL) {
3220 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3222 } else if (op == MDB_SET_RANGE)
3223 rc = mdb_cursor_set(mc, key, data, op, NULL);
3225 rc = mdb_cursor_set(mc, key, data, op, &exact);
3227 case MDB_GET_MULTIPLE:
3229 !(mc->mc_db->md_flags & MDB_DUPFIXED) ||
3230 !(mc->mc_flags & C_INITIALIZED)) {
3235 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
3236 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
3239 case MDB_NEXT_MULTIPLE:
3241 !(mc->mc_db->md_flags & MDB_DUPFIXED)) {
3245 if (!(mc->mc_flags & C_INITIALIZED))
3246 rc = mdb_cursor_first(mc, key, data);
3248 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
3249 if (rc == MDB_SUCCESS) {
3250 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
3253 mx = &mc->mc_xcursor->mx_cursor;
3254 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
3256 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
3257 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
3265 case MDB_NEXT_NODUP:
3266 if (!(mc->mc_flags & C_INITIALIZED))
3267 rc = mdb_cursor_first(mc, key, data);
3269 rc = mdb_cursor_next(mc, key, data, op);
3273 case MDB_PREV_NODUP:
3274 if (!(mc->mc_flags & C_INITIALIZED) || (mc->mc_flags & C_EOF))
3275 rc = mdb_cursor_last(mc, key, data);
3277 rc = mdb_cursor_prev(mc, key, data, op);
3280 rc = mdb_cursor_first(mc, key, data);
3284 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
3285 !(mc->mc_flags & C_INITIALIZED) ||
3286 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3290 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3293 rc = mdb_cursor_last(mc, key, data);
3297 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
3298 !(mc->mc_flags & C_INITIALIZED) ||
3299 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3303 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3306 DPRINTF("unhandled/unimplemented cursor operation %u", op);
3314 /** Touch all the pages in the cursor stack.
3315 * Makes sure all the pages are writable, before attempting a write operation.
3316 * @param[in] mc The cursor to operate on.
3319 mdb_cursor_touch(MDB_cursor *mc)
3323 if (mc->mc_dbi > MAIN_DBI && !mc->mc_dbx->md_dirty) {
3325 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
3326 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 1);
3329 mc->mc_dbx->md_dirty = 1;
3331 for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
3332 if (!F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY)) {
3333 rc = mdb_page_touch(mc);
3337 mc->mc_db->md_root =
3338 mc->mc_pg[mc->mc_top]->mp_pgno;
3342 mc->mc_top = mc->mc_snum-1;
3347 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3351 MDB_val xdata, *rdata, dkey;
3353 char dbuf[PAGESIZE];
3359 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
3362 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
3363 mc->mc_dbi, DKEY(key), key->mv_size, data->mv_size);
3367 if (flags == MDB_CURRENT) {
3368 if (!(mc->mc_flags & C_INITIALIZED))
3371 } else if (mc->mc_db->md_root == P_INVALID) {
3373 /* new database, write a root leaf page */
3374 DPUTS("allocating new root leaf page");
3375 if ((np = mdb_page_new(mc, P_LEAF, 1)) == NULL) {
3379 mdb_cursor_push(mc, np);
3380 mc->mc_db->md_root = np->mp_pgno;
3381 mc->mc_db->md_depth++;
3382 mc->mc_dbx->md_dirty = 1;
3383 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
3385 np->mp_flags |= P_LEAF2;
3386 mc->mc_flags |= C_INITIALIZED;
3392 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
3393 if (flags == MDB_NOOVERWRITE && rc == 0) {
3394 DPRINTF("duplicate key [%s]", DKEY(key));
3396 return MDB_KEYEXIST;
3398 if (rc && rc != MDB_NOTFOUND)
3402 /* Cursor is positioned, now make sure all pages are writable */
3403 rc2 = mdb_cursor_touch(mc);
3408 /* The key already exists */
3409 if (rc == MDB_SUCCESS) {
3410 /* there's only a key anyway, so this is a no-op */
3411 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3412 unsigned int ksize = mc->mc_db->md_pad;
3413 if (key->mv_size != ksize)
3415 if (flags == MDB_CURRENT) {
3416 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
3417 memcpy(ptr, key->mv_data, ksize);
3422 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3425 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
3426 /* Was a single item before, must convert now */
3427 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3428 dkey.mv_size = NODEDSZ(leaf);
3429 dkey.mv_data = dbuf;
3430 memcpy(dbuf, NODEDATA(leaf), dkey.mv_size);
3431 /* data matches, ignore it */
3432 if (!mc->mc_dbx->md_dcmp(data, &dkey))
3433 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
3434 memset(&dummy, 0, sizeof(dummy));
3435 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
3436 dummy.md_pad = data->mv_size;
3437 dummy.md_flags = MDB_DUPFIXED;
3438 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
3439 dummy.md_flags |= MDB_INTEGERKEY;
3441 dummy.md_flags |= MDB_SUBDATA;
3442 dummy.md_root = P_INVALID;
3443 if (dkey.mv_size == sizeof(MDB_db)) {
3444 memcpy(NODEDATA(leaf), &dummy, sizeof(dummy));
3447 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
3450 xdata.mv_size = sizeof(MDB_db);
3451 xdata.mv_data = &dummy;
3452 /* new sub-DB, must fully init xcursor */
3453 if (flags == MDB_CURRENT)
3459 /* same size, just replace it */
3460 if (!F_ISSET(leaf->mn_flags, F_BIGDATA) &&
3461 NODEDSZ(leaf) == data->mv_size) {
3462 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
3465 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
3467 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
3473 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
3474 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
3475 rc = mdb_page_split(mc, key, rdata, P_INVALID);
3477 /* There is room already in this leaf page. */
3478 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, 0);
3481 if (rc != MDB_SUCCESS)
3482 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
3484 /* Remember if we just added a subdatabase */
3485 if (flags & F_SUBDATA) {
3486 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3487 leaf->mn_flags |= F_SUBDATA;
3490 /* Now store the actual data in the child DB. Note that we're
3491 * storing the user data in the keys field, so there are strict
3492 * size limits on dupdata. The actual data fields of the child
3493 * DB are all zero size.
3497 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3499 if (flags != MDB_CURRENT)
3500 mdb_xcursor_init1(mc, leaf);
3503 if (flags == MDB_NODUPDATA)
3504 flags = MDB_NOOVERWRITE;
3505 /* converted, write the original data first */
3507 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, flags);
3510 leaf->mn_flags |= F_DUPDATA;
3512 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, flags);
3513 db = NODEDATA(leaf);
3514 assert((db->md_flags & MDB_SUBDATA) == MDB_SUBDATA);
3515 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
3517 mc->mc_db->md_entries++;
3524 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
3529 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
3532 if (!mc->mc_flags & C_INITIALIZED)
3535 rc = mdb_cursor_touch(mc);
3539 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3541 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3542 if (flags != MDB_NODUPDATA) {
3543 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
3544 /* If sub-DB still has entries, we're done */
3545 if (mc->mc_xcursor->mx_db.md_root != P_INVALID) {
3546 MDB_db *db = NODEDATA(leaf);
3547 assert((db->md_flags & MDB_SUBDATA) == MDB_SUBDATA);
3548 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
3549 mc->mc_db->md_entries--;
3552 /* otherwise fall thru and delete the sub-DB */
3555 /* add all the child DB's pages to the free list */
3556 rc = mdb_page_search(&mc->mc_xcursor->mx_cursor, NULL, 0);
3557 if (rc == MDB_SUCCESS) {
3562 mx = &mc->mc_xcursor->mx_cursor;
3563 mc->mc_db->md_entries -=
3564 mx->mc_db->md_entries;
3567 while (mx->mc_snum > 1) {
3568 for (i=0; i<NUMKEYS(mx->mc_pg[mx->mc_top]); i++) {
3571 ni = NODEPTR(mx->mc_pg[mx->mc_top], i);
3573 if ((rc = mdb_page_get(mc->mc_txn, pg, &mp)))
3576 mdb_midl_append(mc->mc_txn->mt_free_pgs, pg);
3578 rc = mdb_cursor_sibling(mx, 1);
3583 mdb_midl_append(mc->mc_txn->mt_free_pgs,
3584 mx->mc_db->md_root);
3588 return mdb_cursor_del0(mc, leaf);
3591 /** Allocate and initialize new pages for a database.
3592 * @param[in] mc a cursor on the database being added to.
3593 * @param[in] flags flags defining what type of page is being allocated.
3594 * @param[in] num the number of pages to allocate. This is usually 1,
3595 * unless allocating overflow pages for a large record.
3596 * @return Address of a page, or NULL on failure.
3599 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num)
3603 if ((np = mdb_page_alloc(mc, num)) == NULL)
3605 DPRINTF("allocated new mpage %zu, page size %u",
3606 np->mp_pgno, mc->mc_txn->mt_env->me_psize);
3607 np->mp_flags = flags | P_DIRTY;
3608 np->mp_lower = PAGEHDRSZ;
3609 np->mp_upper = mc->mc_txn->mt_env->me_psize;
3612 mc->mc_db->md_branch_pages++;
3613 else if (IS_LEAF(np))
3614 mc->mc_db->md_leaf_pages++;
3615 else if (IS_OVERFLOW(np)) {
3616 mc->mc_db->md_overflow_pages += num;
3623 /** Calculate the size of a leaf node.
3624 * The size depends on the environment's page size; if a data item
3625 * is too large it will be put onto an overflow page and the node
3626 * size will only include the key and not the data. Sizes are always
3627 * rounded up to an even number of bytes, to guarantee 2-byte alignment
3628 * of the #MDB_node headers.
3629 * @param[in] env The environment handle.
3630 * @param[in] key The key for the node.
3631 * @param[in] data The data for the node.
3632 * @return The number of bytes needed to store the node.
3635 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
3639 sz = LEAFSIZE(key, data);
3640 if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
3641 /* put on overflow page */
3642 sz -= data->mv_size - sizeof(pgno_t);
3646 return sz + sizeof(indx_t);
3649 /** Calculate the size of a branch node.
3650 * The size should depend on the environment's page size but since
3651 * we currently don't support spilling large keys onto overflow
3652 * pages, it's simply the size of the #MDB_node header plus the
3653 * size of the key. Sizes are always rounded up to an even number
3654 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
3655 * @param[in] env The environment handle.
3656 * @param[in] key The key for the node.
3657 * @return The number of bytes needed to store the node.
3660 mdb_branch_size(MDB_env *env, MDB_val *key)
3665 if (sz >= env->me_psize / MDB_MINKEYS) {
3666 /* put on overflow page */
3667 /* not implemented */
3668 /* sz -= key->size - sizeof(pgno_t); */
3671 return sz + sizeof(indx_t);
3674 /** Add a node to the page pointed to by the cursor.
3675 * @param[in] mc The cursor for this operation.
3676 * @param[in] indx The index on the page where the new node should be added.
3677 * @param[in] key The key for the new node.
3678 * @param[in] data The data for the new node, if any.
3679 * @param[in] pgno The page number, if adding a branch node.
3680 * @param[in] flags Flags for the node.
3681 * @return 0 on success, non-zero on failure. Possible errors are:
3683 * <li>ENOMEM - failed to allocate overflow pages for the node.
3684 * <li>ENOSPC - there is insufficient room in the page. This error
3685 * should never happen since all callers already calculate the
3686 * page's free space before calling this function.
3690 mdb_node_add(MDB_cursor *mc, indx_t indx,
3691 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags)
3694 size_t node_size = NODESIZE;
3697 MDB_page *mp = mc->mc_pg[mc->mc_top];
3698 MDB_page *ofp = NULL; /* overflow page */
3701 assert(mp->mp_upper >= mp->mp_lower);
3703 DPRINTF("add to %s page %zu index %i, data size %zu key size %zu [%s]",
3704 IS_LEAF(mp) ? "leaf" : "branch",
3705 mp->mp_pgno, indx, data ? data->mv_size : 0,
3706 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
3709 /* Move higher keys up one slot. */
3710 int ksize = mc->mc_db->md_pad, dif;
3711 char *ptr = LEAF2KEY(mp, indx, ksize);
3712 dif = NUMKEYS(mp) - indx;
3714 memmove(ptr+ksize, ptr, dif*ksize);
3715 /* insert new key */
3716 memcpy(ptr, key->mv_data, ksize);
3718 /* Just using these for counting */
3719 mp->mp_lower += sizeof(indx_t);
3720 mp->mp_upper -= ksize - sizeof(indx_t);
3725 node_size += key->mv_size;
3729 if (F_ISSET(flags, F_BIGDATA)) {
3730 /* Data already on overflow page. */
3731 node_size += sizeof(pgno_t);
3732 } else if (data->mv_size >= mc->mc_txn->mt_env->me_psize / MDB_MINKEYS) {
3733 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
3734 /* Put data on overflow page. */
3735 DPRINTF("data size is %zu, put on overflow page",
3737 node_size += sizeof(pgno_t);
3738 if ((ofp = mdb_page_new(mc, P_OVERFLOW, ovpages)) == NULL)
3740 DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
3743 node_size += data->mv_size;
3746 node_size += node_size & 1;
3748 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
3749 DPRINTF("not enough room in page %zu, got %u ptrs",
3750 mp->mp_pgno, NUMKEYS(mp));
3751 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
3752 mp->mp_upper - mp->mp_lower);
3753 DPRINTF("node size = %zu", node_size);
3757 /* Move higher pointers up one slot. */
3758 for (i = NUMKEYS(mp); i > indx; i--)
3759 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
3761 /* Adjust free space offsets. */
3762 ofs = mp->mp_upper - node_size;
3763 assert(ofs >= mp->mp_lower + sizeof(indx_t));
3764 mp->mp_ptrs[indx] = ofs;
3766 mp->mp_lower += sizeof(indx_t);
3768 /* Write the node data. */
3769 node = NODEPTR(mp, indx);
3770 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
3771 node->mn_flags = flags;
3773 SETDSZ(node,data->mv_size);
3778 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
3783 if (F_ISSET(flags, F_BIGDATA))
3784 memcpy(node->mn_data + key->mv_size, data->mv_data,
3787 memcpy(node->mn_data + key->mv_size, data->mv_data,
3790 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
3792 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
3799 /** Delete the specified node from a page.
3800 * @param[in] mp The page to operate on.
3801 * @param[in] indx The index of the node to delete.
3802 * @param[in] ksize The size of a node. Only used if the page is
3803 * part of a #MDB_DUPFIXED database.
3806 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
3809 indx_t i, j, numkeys, ptr;
3813 DPRINTF("delete node %u on %s page %zu", indx,
3814 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
3815 assert(indx < NUMKEYS(mp));
3818 int x = NUMKEYS(mp) - 1 - indx;
3819 base = LEAF2KEY(mp, indx, ksize);
3821 memmove(base, base + ksize, x * ksize);
3822 mp->mp_lower -= sizeof(indx_t);
3823 mp->mp_upper += ksize - sizeof(indx_t);
3827 node = NODEPTR(mp, indx);
3828 sz = NODESIZE + node->mn_ksize;
3830 if (F_ISSET(node->mn_flags, F_BIGDATA))
3831 sz += sizeof(pgno_t);
3833 sz += NODEDSZ(node);
3837 ptr = mp->mp_ptrs[indx];
3838 numkeys = NUMKEYS(mp);
3839 for (i = j = 0; i < numkeys; i++) {
3841 mp->mp_ptrs[j] = mp->mp_ptrs[i];
3842 if (mp->mp_ptrs[i] < ptr)
3843 mp->mp_ptrs[j] += sz;
3848 base = (char *)mp + mp->mp_upper;
3849 memmove(base + sz, base, ptr - mp->mp_upper);
3851 mp->mp_lower -= sizeof(indx_t);
3855 /** Initial setup of a sorted-dups cursor.
3856 * Sorted duplicates are implemented as a sub-database for the given key.
3857 * The duplicate data items are actually keys of the sub-database.
3858 * Operations on the duplicate data items are performed using a sub-cursor
3859 * initialized when the sub-database is first accessed. This function does
3860 * the preliminary setup of the sub-cursor, filling in the fields that
3861 * depend only on the parent DB.
3862 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
3865 mdb_xcursor_init0(MDB_cursor *mc)
3867 MDB_xcursor *mx = mc->mc_xcursor;
3869 mx->mx_cursor.mc_xcursor = NULL;
3870 mx->mx_cursor.mc_txn = mc->mc_txn;
3871 mx->mx_cursor.mc_db = &mx->mx_db;
3872 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
3873 mx->mx_cursor.mc_dbi = mc->mc_dbi+1;
3874 mx->mx_dbx.md_parent = mc->mc_dbi;
3875 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
3876 mx->mx_dbx.md_dcmp = NULL;
3877 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
3878 mx->mx_dbx.md_dirty = 0;
3881 /** Final setup of a sorted-dups cursor.
3882 * Sets up the fields that depend on the data from the main cursor.
3883 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
3884 * @param[in] node The data containing the #MDB_db record for the
3885 * sorted-dup database.
3888 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
3890 MDB_db *db = NODEDATA(node);
3891 MDB_xcursor *mx = mc->mc_xcursor;
3892 assert((db->md_flags & MDB_SUBDATA) == MDB_SUBDATA);
3894 DPRINTF("Sub-db %u for db %u root page %zu", mx->mx_cursor.mc_dbi, mc->mc_dbi,
3896 if (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY))
3897 mx->mx_dbx.md_dirty = 1;
3898 mx->mx_dbx.md_name.mv_data = NODEKEY(node);
3899 mx->mx_dbx.md_name.mv_size = node->mn_ksize;
3900 mx->mx_cursor.mc_snum = 0;
3901 mx->mx_cursor.mc_flags = 0;
3902 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
3903 mx->mx_dbx.md_cmp = mdb_cmp_long;
3906 /** Initialize a cursor for a given transaction and database. */
3908 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
3912 mc->mc_db = &txn->mt_dbs[dbi];
3913 mc->mc_dbx = &txn->mt_dbxs[dbi];
3916 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
3918 mc->mc_xcursor = mx;
3919 mdb_xcursor_init0(mc);
3921 mc->mc_xcursor = NULL;
3926 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
3929 MDB_xcursor *mx = NULL;
3930 size_t size = sizeof(MDB_cursor);
3932 if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
3935 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
3936 size += sizeof(MDB_xcursor);
3938 if ((mc = malloc(size)) != NULL) {
3939 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
3940 mx = (MDB_xcursor *)(mc + 1);
3942 mdb_cursor_init(mc, txn, dbi, mx);
3952 /* Return the count of duplicate data items for the current key */
3954 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
3958 if (mc == NULL || countp == NULL)
3961 if (!(mc->mc_db->md_flags & MDB_DUPSORT))
3964 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3965 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3968 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
3971 *countp = mc->mc_xcursor->mx_db.md_entries;
3977 mdb_cursor_close(MDB_cursor *mc)
3984 /** Replace the key for a node with a new key.
3985 * @param[in] mp The page containing the node to operate on.
3986 * @param[in] indx The index of the node to operate on.
3987 * @param[in] key The new key to use.
3988 * @return 0 on success, non-zero on failure.
3991 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
3993 indx_t ptr, i, numkeys;
4000 node = NODEPTR(mp, indx);
4001 ptr = mp->mp_ptrs[indx];
4002 DPRINTF("update key %u (ofs %u) [%.*s] to [%s] on page %zu",
4004 (int)node->mn_ksize, (char *)NODEKEY(node),
4008 delta = key->mv_size - node->mn_ksize;
4010 if (delta > 0 && SIZELEFT(mp) < delta) {
4011 DPRINTF("OUCH! Not enough room, delta = %d", delta);
4015 numkeys = NUMKEYS(mp);
4016 for (i = 0; i < numkeys; i++) {
4017 if (mp->mp_ptrs[i] <= ptr)
4018 mp->mp_ptrs[i] -= delta;
4021 base = (char *)mp + mp->mp_upper;
4022 len = ptr - mp->mp_upper + NODESIZE;
4023 memmove(base - delta, base, len);
4024 mp->mp_upper -= delta;
4026 node = NODEPTR(mp, indx);
4027 node->mn_ksize = key->mv_size;
4030 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
4035 /** Move a node from csrc to cdst.
4038 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
4045 /* Mark src and dst as dirty. */
4046 if ((rc = mdb_page_touch(csrc)) ||
4047 (rc = mdb_page_touch(cdst)))
4050 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4051 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
4052 key.mv_size = csrc->mc_db->md_pad;
4053 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
4055 data.mv_data = NULL;
4057 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
4058 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
4059 unsigned int snum = csrc->mc_snum;
4061 /* must find the lowest key below src */
4062 mdb_page_search_root(csrc, NULL, 0);
4063 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
4064 key.mv_size = NODEKSZ(s2);
4065 key.mv_data = NODEKEY(s2);
4066 csrc->mc_snum = snum--;
4067 csrc->mc_top = snum;
4069 key.mv_size = NODEKSZ(srcnode);
4070 key.mv_data = NODEKEY(srcnode);
4072 data.mv_size = NODEDSZ(srcnode);
4073 data.mv_data = NODEDATA(srcnode);
4075 DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
4076 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
4077 csrc->mc_ki[csrc->mc_top],
4079 csrc->mc_pg[csrc->mc_top]->mp_pgno,
4080 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
4082 /* Add the node to the destination page.
4084 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, NODEPGNO(srcnode),
4086 if (rc != MDB_SUCCESS)
4089 /* Delete the node from the source page.
4091 mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
4093 /* Update the parent separators.
4095 if (csrc->mc_ki[csrc->mc_top] == 0) {
4096 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
4097 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4098 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
4100 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
4101 key.mv_size = NODEKSZ(srcnode);
4102 key.mv_data = NODEKEY(srcnode);
4104 DPRINTF("update separator for source page %zu to [%s]",
4105 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
4106 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1],
4107 &key)) != MDB_SUCCESS)
4110 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
4112 nullkey.mv_size = 0;
4113 assert(mdb_update_key(csrc->mc_pg[csrc->mc_top], 0, &nullkey) == MDB_SUCCESS);
4117 if (cdst->mc_ki[cdst->mc_top] == 0) {
4118 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
4119 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4120 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
4122 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
4123 key.mv_size = NODEKSZ(srcnode);
4124 key.mv_data = NODEKEY(srcnode);
4126 DPRINTF("update separator for destination page %zu to [%s]",
4127 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
4128 if ((rc = mdb_update_key(cdst->mc_pg[cdst->mc_top-1], cdst->mc_ki[cdst->mc_top-1],
4129 &key)) != MDB_SUCCESS)
4132 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
4134 nullkey.mv_size = 0;
4135 assert(mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &nullkey) == MDB_SUCCESS);
4142 /** Merge one page into another.
4143 * The nodes from the page pointed to by \b csrc will
4144 * be copied to the page pointed to by \b cdst and then
4145 * the \b csrc page will be freed.
4146 * @param[in] csrc Cursor pointing to the source page.
4147 * @param[in] cdst Cursor pointing to the destination page.
4150 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
4157 DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
4158 cdst->mc_pg[cdst->mc_top]->mp_pgno);
4160 assert(csrc->mc_snum > 1); /* can't merge root page */
4161 assert(cdst->mc_snum > 1);
4163 /* Mark dst as dirty. */
4164 if ((rc = mdb_page_touch(cdst)))
4167 /* Move all nodes from src to dst.
4169 j = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
4170 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4171 key.mv_size = csrc->mc_db->md_pad;
4172 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
4173 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
4174 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
4175 if (rc != MDB_SUCCESS)
4177 key.mv_data = (char *)key.mv_data + key.mv_size;
4180 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
4181 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
4183 key.mv_size = srcnode->mn_ksize;
4184 key.mv_data = NODEKEY(srcnode);
4185 data.mv_size = NODEDSZ(srcnode);
4186 data.mv_data = NODEDATA(srcnode);
4187 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
4188 if (rc != MDB_SUCCESS)
4193 DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
4194 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);
4196 /* Unlink the src page from parent and add to free list.
4198 mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
4199 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
4201 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], 0, &key)) != MDB_SUCCESS)
4205 mdb_midl_append(csrc->mc_txn->mt_free_pgs, csrc->mc_pg[csrc->mc_top]->mp_pgno);
4206 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
4207 csrc->mc_db->md_leaf_pages--;
4209 csrc->mc_db->md_branch_pages--;
4210 mdb_cursor_pop(csrc);
4212 return mdb_rebalance(csrc);
4215 /** Copy the contents of a cursor.
4216 * @param[in] csrc The cursor to copy from.
4217 * @param[out] cdst The cursor to copy to.
4220 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
4224 cdst->mc_txn = csrc->mc_txn;
4225 cdst->mc_dbi = csrc->mc_dbi;
4226 cdst->mc_db = csrc->mc_db;
4227 cdst->mc_dbx = csrc->mc_dbx;
4228 cdst->mc_snum = csrc->mc_snum;
4229 cdst->mc_top = csrc->mc_top;
4230 cdst->mc_flags = csrc->mc_flags;
4232 for (i=0; i<csrc->mc_snum; i++) {
4233 cdst->mc_pg[i] = csrc->mc_pg[i];
4234 cdst->mc_ki[i] = csrc->mc_ki[i];
4238 /** Rebalance the tree after a delete operation.
4239 * @param[in] mc Cursor pointing to the page where rebalancing
4241 * @return 0 on success, non-zero on failure.
4244 mdb_rebalance(MDB_cursor *mc)
4251 DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
4252 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
4253 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);
4255 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD) {
4256 DPRINTF("no need to rebalance page %zu, above fill threshold",
4257 mc->mc_pg[mc->mc_top]->mp_pgno);
4261 if (mc->mc_snum < 2) {
4262 if (NUMKEYS(mc->mc_pg[mc->mc_top]) == 0) {
4263 DPUTS("tree is completely empty");
4264 mc->mc_db->md_root = P_INVALID;
4265 mc->mc_db->md_depth = 0;
4266 mc->mc_db->md_leaf_pages = 0;
4267 mdb_midl_append(mc->mc_txn->mt_free_pgs, mc->mc_pg[mc->mc_top]->mp_pgno);
4269 } else if (IS_BRANCH(mc->mc_pg[mc->mc_top]) && NUMKEYS(mc->mc_pg[mc->mc_top]) == 1) {
4270 DPUTS("collapsing root page!");
4271 mdb_midl_append(mc->mc_txn->mt_free_pgs, mc->mc_pg[mc->mc_top]->mp_pgno);
4272 mc->mc_db->md_root = NODEPGNO(NODEPTR(mc->mc_pg[mc->mc_top], 0));
4273 if ((rc = mdb_page_get(mc->mc_txn, mc->mc_db->md_root,
4274 &mc->mc_pg[mc->mc_top])))
4276 mc->mc_db->md_depth--;
4277 mc->mc_db->md_branch_pages--;
4279 DPUTS("root page doesn't need rebalancing");
4283 /* The parent (branch page) must have at least 2 pointers,
4284 * otherwise the tree is invalid.
4286 ptop = mc->mc_top-1;
4287 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
4289 /* Leaf page fill factor is below the threshold.
4290 * Try to move keys from left or right neighbor, or
4291 * merge with a neighbor page.
4296 mdb_cursor_copy(mc, &mn);
4297 mn.mc_xcursor = NULL;
4299 if (mc->mc_ki[ptop] == 0) {
4300 /* We're the leftmost leaf in our parent.
4302 DPUTS("reading right neighbor");
4304 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
4305 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
4307 mn.mc_ki[mn.mc_top] = 0;
4308 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
4310 /* There is at least one neighbor to the left.
4312 DPUTS("reading left neighbor");
4314 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
4315 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
4317 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
4318 mc->mc_ki[mc->mc_top] = 0;
4321 DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
4322 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);
4324 /* If the neighbor page is above threshold and has at least two
4325 * keys, move one key from it.
4327 * Otherwise we should try to merge them.
4329 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) >= 2)
4330 return mdb_node_move(&mn, mc);
4331 else { /* FIXME: if (has_enough_room()) */
4332 if (mc->mc_ki[ptop] == 0)
4333 return mdb_page_merge(&mn, mc);
4335 return mdb_page_merge(mc, &mn);
4339 /** Complete a delete operation started by #mdb_cursor_del(). */
4341 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
4345 /* add overflow pages to free list */
4346 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
4350 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
4351 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
4352 for (i=0; i<ovpages; i++) {
4353 DPRINTF("freed ov page %zu", pg);
4354 mdb_midl_append(mc->mc_txn->mt_free_pgs, pg);
4358 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], mc->mc_db->md_pad);
4359 mc->mc_db->md_entries--;
4360 rc = mdb_rebalance(mc);
4361 if (rc != MDB_SUCCESS)
4362 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4368 mdb_del(MDB_txn *txn, MDB_dbi dbi,
4369 MDB_val *key, MDB_val *data)
4374 MDB_val rdata, *xdata;
4378 assert(key != NULL);
4380 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
4382 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4385 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
4389 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
4393 mdb_cursor_init(&mc, txn, dbi, &mx);
4404 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
4406 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
4410 /** Split a page and insert a new node.
4411 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
4412 * The cursor will be updated to point to the actual page and index where
4413 * the node got inserted after the split.
4414 * @param[in] newkey The key for the newly inserted node.
4415 * @param[in] newdata The data for the newly inserted node.
4416 * @param[in] newpgno The page number, if the new node is a branch node.
4417 * @return 0 on success, non-zero on failure.
4420 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno)
4423 int rc = MDB_SUCCESS, ins_new = 0;
4426 unsigned int i, j, split_indx, nkeys, pmax;
4428 MDB_val sepkey, rkey, rdata;
4430 MDB_page *mp, *rp, *pp;
4435 mp = mc->mc_pg[mc->mc_top];
4436 newindx = mc->mc_ki[mc->mc_top];
4438 DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
4439 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
4440 DKEY(newkey), mc->mc_ki[mc->mc_top]);
4442 if (mc->mc_snum < 2) {
4443 if ((pp = mdb_page_new(mc, P_BRANCH, 1)) == NULL)
4445 /* shift current top to make room for new parent */
4446 mc->mc_pg[1] = mc->mc_pg[0];
4447 mc->mc_ki[1] = mc->mc_ki[0];
4450 mc->mc_db->md_root = pp->mp_pgno;
4451 DPRINTF("root split! new root = %zu", pp->mp_pgno);
4452 mc->mc_db->md_depth++;
4454 /* Add left (implicit) pointer. */
4455 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
4456 /* undo the pre-push */
4457 mc->mc_pg[0] = mc->mc_pg[1];
4458 mc->mc_ki[0] = mc->mc_ki[1];
4459 mc->mc_db->md_root = mp->mp_pgno;
4460 mc->mc_db->md_depth--;
4467 ptop = mc->mc_top-1;
4468 DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
4471 /* Create a right sibling. */
4472 if ((rp = mdb_page_new(mc, mp->mp_flags, 1)) == NULL)
4474 mdb_cursor_copy(mc, &mn);
4475 mn.mc_pg[mn.mc_top] = rp;
4476 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
4477 DPRINTF("new right sibling: page %zu", rp->mp_pgno);
4479 nkeys = NUMKEYS(mp);
4480 split_indx = nkeys / 2 + 1;
4485 unsigned int lsize, rsize, ksize;
4486 /* Move half of the keys to the right sibling */
4488 x = mc->mc_ki[mc->mc_top] - split_indx;
4489 ksize = mc->mc_db->md_pad;
4490 split = LEAF2KEY(mp, split_indx, ksize);
4491 rsize = (nkeys - split_indx) * ksize;
4492 lsize = (nkeys - split_indx) * sizeof(indx_t);
4493 mp->mp_lower -= lsize;
4494 rp->mp_lower += lsize;
4495 mp->mp_upper += rsize - lsize;
4496 rp->mp_upper -= rsize - lsize;
4497 sepkey.mv_size = ksize;
4498 if (newindx == split_indx) {
4499 sepkey.mv_data = newkey->mv_data;
4501 sepkey.mv_data = split;
4504 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
4505 memcpy(rp->mp_ptrs, split, rsize);
4506 sepkey.mv_data = rp->mp_ptrs;
4507 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
4508 memcpy(ins, newkey->mv_data, ksize);
4509 mp->mp_lower += sizeof(indx_t);
4510 mp->mp_upper -= ksize - sizeof(indx_t);
4513 memcpy(rp->mp_ptrs, split, x * ksize);
4514 ins = LEAF2KEY(rp, x, ksize);
4515 memcpy(ins, newkey->mv_data, ksize);
4516 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
4517 rp->mp_lower += sizeof(indx_t);
4518 rp->mp_upper -= ksize - sizeof(indx_t);
4519 mc->mc_ki[mc->mc_top] = x;
4520 mc->mc_pg[mc->mc_top] = rp;
4525 /* For leaf pages, check the split point based on what
4526 * fits where, since otherwise add_node can fail.
4529 unsigned int psize, nsize;
4530 /* Maximum free space in an empty page */
4531 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
4532 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
4533 if (newindx < split_indx) {
4535 for (i=0; i<split_indx; i++) {
4536 node = NODEPTR(mp, i);
4537 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
4538 if (F_ISSET(node->mn_flags, F_BIGDATA))
4539 psize += sizeof(pgno_t);
4541 psize += NODEDSZ(node);
4550 for (i=nkeys-1; i>=split_indx; i--) {
4551 node = NODEPTR(mp, i);
4552 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
4553 if (F_ISSET(node->mn_flags, F_BIGDATA))
4554 psize += sizeof(pgno_t);
4556 psize += NODEDSZ(node);
4566 /* First find the separating key between the split pages.
4568 if (newindx == split_indx) {
4569 sepkey.mv_size = newkey->mv_size;
4570 sepkey.mv_data = newkey->mv_data;
4572 node = NODEPTR(mp, split_indx);
4573 sepkey.mv_size = node->mn_ksize;
4574 sepkey.mv_data = NODEKEY(node);
4578 DPRINTF("separator is [%s]", DKEY(&sepkey));
4580 /* Copy separator key to the parent.
4582 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
4585 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno);
4587 /* Right page might now have changed parent.
4588 * Check if left page also changed parent.
4590 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
4591 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
4592 mc->mc_pg[ptop] = mn.mc_pg[ptop];
4593 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
4597 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
4603 if (rc != MDB_SUCCESS) {
4607 /* Move half of the keys to the right sibling. */
4609 /* grab a page to hold a temporary copy */
4610 if (mc->mc_txn->mt_env->me_dpages) {
4611 copy = mc->mc_txn->mt_env->me_dpages;
4612 mc->mc_txn->mt_env->me_dpages = copy->mp_next;
4614 if ((copy = malloc(mc->mc_txn->mt_env->me_psize)) == NULL)
4618 copy->mp_pgno = mp->mp_pgno;
4619 copy->mp_flags = mp->mp_flags;
4620 copy->mp_lower = PAGEHDRSZ;
4621 copy->mp_upper = mc->mc_txn->mt_env->me_psize;
4622 mc->mc_pg[mc->mc_top] = copy;
4623 for (i = j = 0; i <= nkeys; j++) {
4624 if (i == split_indx) {
4625 /* Insert in right sibling. */
4626 /* Reset insert index for right sibling. */
4627 j = (i == newindx && ins_new);
4628 mc->mc_pg[mc->mc_top] = rp;
4631 if (i == newindx && !ins_new) {
4632 /* Insert the original entry that caused the split. */
4633 rkey.mv_data = newkey->mv_data;
4634 rkey.mv_size = newkey->mv_size;
4636 rdata.mv_data = newdata->mv_data;
4637 rdata.mv_size = newdata->mv_size;
4644 /* Update page and index for the new key. */
4645 mc->mc_ki[mc->mc_top] = j;
4646 } else if (i == nkeys) {
4649 node = NODEPTR(mp, i);
4650 rkey.mv_data = NODEKEY(node);
4651 rkey.mv_size = node->mn_ksize;
4653 rdata.mv_data = NODEDATA(node);
4654 rdata.mv_size = NODEDSZ(node);
4656 pgno = NODEPGNO(node);
4657 flags = node->mn_flags;
4662 if (!IS_LEAF(mp) && j == 0) {
4663 /* First branch index doesn't need key data. */
4667 rc = mdb_node_add(mc, j, &rkey, &rdata, pgno, flags);
4670 /* reset back to original page */
4671 if (newindx < split_indx)
4672 mc->mc_pg[mc->mc_top] = mp;
4674 nkeys = NUMKEYS(copy);
4675 for (i=0; i<nkeys; i++)
4676 mp->mp_ptrs[i] = copy->mp_ptrs[i];
4677 mp->mp_lower = copy->mp_lower;
4678 mp->mp_upper = copy->mp_upper;
4679 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
4680 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
4682 /* return tmp page to freelist */
4683 copy->mp_next = mc->mc_txn->mt_env->me_dpages;
4684 mc->mc_txn->mt_env->me_dpages = copy;
4689 mdb_put(MDB_txn *txn, MDB_dbi dbi,
4690 MDB_val *key, MDB_val *data, unsigned int flags)
4695 assert(key != NULL);
4696 assert(data != NULL);
4698 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4701 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
4705 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
4709 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA)) != flags)
4712 mdb_cursor_init(&mc, txn, dbi, &mx);
4713 return mdb_cursor_put(&mc, key, data, flags);
4717 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
4719 /** Only a subset of the @ref mdb_env flags can be changed
4720 * at runtime. Changing other flags requires closing the environment
4721 * and re-opening it with the new flags.
4723 #define CHANGEABLE (MDB_NOSYNC)
4724 if ((flag & CHANGEABLE) != flag)
4727 env->me_flags |= flag;
4729 env->me_flags &= ~flag;
4734 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
4739 *arg = env->me_flags;
4744 mdb_env_get_path(MDB_env *env, const char **arg)
4749 *arg = env->me_path;
4753 /** Common code for #mdb_stat() and #mdb_env_stat().
4754 * @param[in] env the environment to operate in.
4755 * @param[in] db the #MDB_db record containing the stats to return.
4756 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
4757 * @return 0, this function always succeeds.
4760 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
4762 arg->ms_psize = env->me_psize;
4763 arg->ms_depth = db->md_depth;
4764 arg->ms_branch_pages = db->md_branch_pages;
4765 arg->ms_leaf_pages = db->md_leaf_pages;
4766 arg->ms_overflow_pages = db->md_overflow_pages;
4767 arg->ms_entries = db->md_entries;
4772 mdb_env_stat(MDB_env *env, MDB_stat *arg)
4776 if (env == NULL || arg == NULL)
4779 mdb_env_read_meta(env, &toggle);
4781 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
4784 /** Set the default comparison functions for a database.
4785 * Called immediately after a database is opened to set the defaults.
4786 * The user can then override them with #mdb_set_compare() or
4787 * #mdb_set_dupsort().
4788 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
4789 * @param[in] dbi A database handle returned by #mdb_open()
4792 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
4794 if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEKEY)
4795 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memnr;
4796 else if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERKEY)
4797 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_cint;
4799 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memn;
4801 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4802 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP) {
4803 if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED)
4804 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_int;
4806 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_cint;
4807 } else if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEDUP) {
4808 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memnr;
4810 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memn;
4813 txn->mt_dbxs[dbi].md_dcmp = NULL;
4817 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
4824 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
4825 mdb_default_cmp(txn, FREE_DBI);
4831 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
4832 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
4833 mdb_default_cmp(txn, MAIN_DBI);
4837 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
4838 mdb_default_cmp(txn, MAIN_DBI);
4841 /* Is the DB already open? */
4843 for (i=2; i<txn->mt_numdbs; i++) {
4844 if (len == txn->mt_dbxs[i].md_name.mv_size &&
4845 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
4851 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
4854 /* Find the DB info */
4856 key.mv_data = (void *)name;
4857 rc = mdb_get(txn, MAIN_DBI, &key, &data);
4859 /* Create if requested */
4860 if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
4863 data.mv_size = sizeof(MDB_db);
4864 data.mv_data = &dummy;
4865 memset(&dummy, 0, sizeof(dummy));
4866 dummy.md_root = P_INVALID;
4867 dummy.md_flags = flags & 0xffff;
4868 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
4869 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
4873 /* OK, got info, add to table */
4874 if (rc == MDB_SUCCESS) {
4875 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
4876 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
4877 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
4878 txn->mt_dbxs[txn->mt_numdbs].md_parent = MAIN_DBI;
4879 txn->mt_dbxs[txn->mt_numdbs].md_dirty = dirty;
4880 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
4881 *dbi = txn->mt_numdbs;
4882 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
4883 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
4884 mdb_default_cmp(txn, txn->mt_numdbs);
4891 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
4893 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
4896 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
4899 void mdb_close(MDB_txn *txn, MDB_dbi dbi)
4902 if (dbi <= MAIN_DBI || dbi >= txn->mt_numdbs)
4904 ptr = txn->mt_dbxs[dbi].md_name.mv_data;
4905 txn->mt_dbxs[dbi].md_name.mv_data = NULL;
4906 txn->mt_dbxs[dbi].md_name.mv_size = 0;
4910 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
4912 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4915 txn->mt_dbxs[dbi].md_cmp = cmp;
4919 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
4921 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4924 txn->mt_dbxs[dbi].md_dcmp = cmp;
4928 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
4930 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4933 txn->mt_dbxs[dbi].md_rel = rel;
4937 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
4939 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4942 txn->mt_dbxs[dbi].md_relctx = ctx;