2 * @brief memory-mapped database library
4 * A Btree-based database management library modeled loosely on the
5 * BerkeleyDB API, but much simplified.
8 * Copyright 2011 Howard Chu, Symas Corp.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted only as authorized by the OpenLDAP
15 * A copy of this license is available in the file LICENSE in the
16 * top-level directory of the distribution or, alternatively, at
17 * <http://www.OpenLDAP.org/license.html>.
19 * This code is derived from btree.c written by Martin Hedenfalk.
21 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
23 * Permission to use, copy, modify, and distribute this software for any
24 * purpose with or without fee is hereby granted, provided that the above
25 * copyright notice and this permission notice appear in all copies.
27 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
28 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
29 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
30 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
31 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
32 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
33 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
35 #include <sys/types.h>
37 #include <sys/param.h>
43 #ifdef HAVE_SYS_FILE_H
63 #include <semaphore.h>
68 #define BYTE_ORDER __BYTE_ORDER
71 #define LITTLE_ENDIAN __LITTLE_ENDIAN
74 #define BIG_ENDIAN __BIG_ENDIAN
80 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
81 # error "Unknown or unsupported endianness (BYTE_ORDER)"
82 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
83 # error "Two's complement, reasonably sized integer types, please"
86 /** @defgroup internal MDB Internals
89 /** @defgroup compat Windows Compatibility Macros
90 * A bunch of macros to minimize the amount of platform-specific ifdefs
91 * needed throughout the rest of the code. When the features this library
92 * needs are similar enough to POSIX to be hidden in a one-or-two line
93 * replacement, this macro approach is used.
97 #define pthread_t DWORD
98 #define pthread_mutex_t HANDLE
99 #define pthread_key_t DWORD
100 #define pthread_self() GetCurrentThreadId()
101 #define pthread_key_create(x,y) (*(x) = TlsAlloc())
102 #define pthread_key_delete(x) TlsFree(x)
103 #define pthread_getspecific(x) TlsGetValue(x)
104 #define pthread_setspecific(x,y) TlsSetValue(x,y)
105 #define pthread_mutex_unlock(x) ReleaseMutex(x)
106 #define pthread_mutex_lock(x) WaitForSingleObject(x, INFINITE)
107 #define LOCK_MUTEX_R(env) pthread_mutex_lock((env)->me_rmutex)
108 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock((env)->me_rmutex)
109 #define LOCK_MUTEX_W(env) pthread_mutex_lock((env)->me_wmutex)
110 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock((env)->me_wmutex)
111 #define getpid() GetCurrentProcessId()
112 #define fdatasync(fd) (!FlushFileBuffers(fd))
113 #define ErrCode() GetLastError()
114 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
115 #define close(fd) CloseHandle(fd)
116 #define munmap(ptr,len) UnmapViewOfFile(ptr)
119 #define LOCK_MUTEX_R(env) sem_wait((env)->me_rmutex)
120 #define UNLOCK_MUTEX_R(env) sem_post((env)->me_rmutex)
121 #define LOCK_MUTEX_W(env) sem_wait((env)->me_wmutex)
122 #define UNLOCK_MUTEX_W(env) sem_post((env)->me_wmutex)
123 #define fdatasync(fd) fsync(fd)
125 /** Lock the reader mutex.
127 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
128 /** Unlock the reader mutex.
130 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
132 /** Lock the writer mutex.
133 * Only a single write transaction is allowed at a time. Other writers
134 * will block waiting for this mutex.
136 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
137 /** Unlock the writer mutex.
139 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
140 #endif /* __APPLE__ */
142 /** Get the error code for the last failed system function.
144 #define ErrCode() errno
146 /** An abstraction for a file handle.
147 * On POSIX systems file handles are small integers. On Windows
148 * they're opaque pointers.
152 /** A value for an invalid file handle.
153 * Mainly used to initialize file variables and signify that they are
156 #define INVALID_HANDLE_VALUE (-1)
158 /** Get the size of a memory page for the system.
159 * This is the basic size that the platform's memory manager uses, and is
160 * fundamental to the use of memory-mapped files.
162 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
165 #if defined(_WIN32) || defined(__APPLE__)
172 /** A flag for opening a file and requesting synchronous data writes.
173 * This is only used when writing a meta page. It's not strictly needed;
174 * we could just do a normal write and then immediately perform a flush.
175 * But if this flag is available it saves us an extra system call.
177 * @note If O_DSYNC is undefined but exists in /usr/include,
178 * preferably set some compiler flag to get the definition.
179 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
182 # define MDB_DSYNC O_DSYNC
186 /** A page number in the database.
187 * Note that 64 bit page numbers are overkill, since pages themselves
188 * already represent 12-13 bits of addressable memory, and the OS will
189 * always limit applications to a maximum of 63 bits of address space.
191 * @note In the #MDB_node structure, we only store 48 bits of this value,
192 * which thus limits us to only 60 bits of addressable data.
196 /** A transaction ID.
197 * See struct MDB_txn.mt_txnid for details.
201 /** @defgroup debug Debug Macros
205 /** Enable debug output.
206 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
207 * read from and written to the database (used for free space management).
212 #if !(__STDC_VERSION__ >= 199901L || defined(__GNUC__))
213 # define DPRINTF (void) /* Vararg macros may be unsupported */
215 /** Print a debug message with printf formatting. */
216 # define DPRINTF(fmt, ...) /**< Requires 2 or more args */ \
217 fprintf(stderr, "%s:%d " fmt "\n", __func__, __LINE__, __VA_ARGS__)
219 # define DPRINTF(fmt, ...) ((void) 0)
221 /** Print a debug string.
222 * The string is printed literally, with no format processing.
224 #define DPUTS(arg) DPRINTF("%s", arg)
227 /** A default memory page size.
228 * The actual size is platform-dependent, but we use this for
229 * boot-strapping. We probably should not be using this any more.
230 * The #GET_PAGESIZE() macro is used to get the actual size.
232 * Note that we don't currently support Huge pages. On Linux,
233 * regular data files cannot use Huge pages, and in general
234 * Huge pages aren't actually pageable. We rely on the OS
235 * demand-pager to read our data and page it out when memory
236 * pressure from other processes is high. So until OSs have
237 * actual paging support for Huge pages, they're not viable.
239 #define PAGESIZE 4096
241 /** The minimum number of keys required in a database page.
242 * Setting this to a larger value will place a smaller bound on the
243 * maximum size of a data item. Data items larger than this size will
244 * be pushed into overflow pages instead of being stored directly in
245 * the B-tree node. This value used to default to 4. With a page size
246 * of 4096 bytes that meant that any item larger than 1024 bytes would
247 * go into an overflow page. That also meant that on average 2-3KB of
248 * each overflow page was wasted space. The value cannot be lower than
249 * 2 because then there would no longer be a tree structure. With this
250 * value, items larger than 2KB will go into overflow pages, and on
251 * average only 1KB will be wasted.
253 #define MDB_MINKEYS 2
255 /** A stamp that identifies a file as an MDB file.
256 * There's nothing special about this value other than that it is easily
257 * recognizable, and it will reflect any byte order mismatches.
259 #define MDB_MAGIC 0xBEEFC0DE
261 /** The version number for a database's file format. */
262 #define MDB_VERSION 1
264 /** The maximum size of a key in the database.
265 * While data items have essentially unbounded size, we require that
266 * keys all fit onto a regular page. This limit could be raised a bit
267 * further if needed; to something just under #PAGESIZE / #MDB_MINKEYS.
269 #define MAXKEYSIZE 511
274 * This is used for printing a hex dump of a key's contents.
276 #define DKBUF char kbuf[(MAXKEYSIZE*2+1)]
277 /** Display a key in hex.
279 * Invoke a function to display a key in hex.
281 #define DKEY(x) mdb_dkey(x, kbuf)
283 #define DKBUF typedef int dummy_kbuf /* so we can put ';' after */
287 /** @defgroup lazylock Lazy Locking
288 * Macros for locks that are't actually needed.
289 * The DB view is always consistent because all writes are wrapped in
290 * the wmutex. Finer-grained locks aren't necessary.
294 /** Use lazy locking. I.e., don't lock these accesses at all. */
298 /** Grab the reader lock */
299 #define LAZY_MUTEX_LOCK(x)
300 /** Release the reader lock */
301 #define LAZY_MUTEX_UNLOCK(x)
302 /** Release the DB table reader/writer lock */
303 #define LAZY_RWLOCK_UNLOCK(x)
304 /** Grab the DB table write lock */
305 #define LAZY_RWLOCK_WRLOCK(x)
306 /** Grab the DB table read lock */
307 #define LAZY_RWLOCK_RDLOCK(x)
308 /** Declare the DB table rwlock. Should not be followed by ';'. */
309 #define LAZY_RWLOCK_DEF(x)
310 /** Initialize the DB table rwlock */
311 #define LAZY_RWLOCK_INIT(x,y)
312 /** Destroy the DB table rwlock */
313 #define LAZY_RWLOCK_DESTROY(x)
315 #define LAZY_MUTEX_LOCK(x) pthread_mutex_lock(x)
316 #define LAZY_MUTEX_UNLOCK(x) pthread_mutex_unlock(x)
317 #define LAZY_RWLOCK_UNLOCK(x) pthread_rwlock_unlock(x)
318 #define LAZY_RWLOCK_WRLOCK(x) pthread_rwlock_wrlock(x)
319 #define LAZY_RWLOCK_RDLOCK(x) pthread_rwlock_rdlock(x)
320 #define LAZY_RWLOCK_DEF(x) pthread_rwlock_t x;
321 #define LAZY_RWLOCK_INIT(x,y) pthread_rwlock_init(x,y)
322 #define LAZY_RWLOCK_DESTROY(x) pthread_rwlock_destroy(x)
326 /** An invalid page number.
327 * Mainly used to denote an empty tree.
329 #define P_INVALID (~0UL)
331 /** Test if a flag \b f is set in a flag word \b w. */
332 #define F_ISSET(w, f) (((w) & (f)) == (f))
334 /** Used for offsets within a single page.
335 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
338 typedef uint16_t indx_t;
340 /** Default size of memory map.
341 * This is certainly too small for any actual applications. Apps should always set
342 * the size explicitly using #mdb_env_set_mapsize().
344 #define DEFAULT_MAPSIZE 1048576
346 /** @defgroup readers Reader Lock Table
347 * Readers don't acquire any locks for their data access. Instead, they
348 * simply record their transaction ID in the reader table. The reader
349 * mutex is needed just to find an empty slot in the reader table. The
350 * slot's address is saved in thread-specific data so that subsequent read
351 * transactions started by the same thread need no further locking to proceed.
353 * Since the database uses multi-version concurrency control, readers don't
354 * actually need any locking. This table is used to keep track of which
355 * readers are using data from which old transactions, so that we'll know
356 * when a particular old transaction is no longer in use. Old transactions
357 * that have discarded any data pages can then have those pages reclaimed
358 * for use by a later write transaction.
360 * The lock table is constructed such that reader slots are aligned with the
361 * processor's cache line size. Any slot is only ever used by one thread.
362 * This alignment guarantees that there will be no contention or cache
363 * thrashing as threads update their own slot info, and also eliminates
364 * any need for locking when accessing a slot.
366 * A writer thread will scan every slot in the table to determine the oldest
367 * outstanding reader transaction. Any freed pages older than this will be
368 * reclaimed by the writer. The writer doesn't use any locks when scanning
369 * this table. This means that there's no guarantee that the writer will
370 * see the most up-to-date reader info, but that's not required for correct
371 * operation - all we need is to know the upper bound on the oldest reader,
372 * we don't care at all about the newest reader. So the only consequence of
373 * reading stale information here is that old pages might hang around a
374 * while longer before being reclaimed. That's actually good anyway, because
375 * the longer we delay reclaiming old pages, the more likely it is that a
376 * string of contiguous pages can be found after coalescing old pages from
377 * many old transactions together.
379 * @todo We don't actually do such coalescing yet, we grab pages from one
380 * old transaction at a time.
383 /** Number of slots in the reader table.
384 * This value was chosen somewhat arbitrarily. 126 readers plus a
385 * couple mutexes fit exactly into 8KB on my development machine.
386 * Applications should set the table size using #mdb_env_set_maxreaders().
388 #define DEFAULT_READERS 126
390 /** The size of a CPU cache line in bytes. We want our lock structures
391 * aligned to this size to avoid false cache line sharing in the
393 * This value works for most CPUs. For Itanium this should be 128.
399 /** The information we store in a single slot of the reader table.
400 * In addition to a transaction ID, we also record the process and
401 * thread ID that owns a slot, so that we can detect stale information,
402 * e.g. threads or processes that went away without cleaning up.
403 * @note We currently don't check for stale records. We simply re-init
404 * the table when we know that we're the only process opening the
407 typedef struct MDB_rxbody {
408 /** The current Transaction ID when this transaction began.
409 * Multiple readers that start at the same time will probably have the
410 * same ID here. Again, it's not important to exclude them from
411 * anything; all we need to know is which version of the DB they
412 * started from so we can avoid overwriting any data used in that
413 * particular version.
416 /** The process ID of the process owning this reader txn. */
418 /** The thread ID of the thread owning this txn. */
422 /** The actual reader record, with cacheline padding. */
423 typedef struct MDB_reader {
426 /** shorthand for mrb_txnid */
427 #define mr_txnid mru.mrx.mrb_txnid
428 #define mr_pid mru.mrx.mrb_pid
429 #define mr_tid mru.mrx.mrb_tid
430 /** cache line alignment */
431 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
435 /** The header for the reader table.
436 * The table resides in a memory-mapped file. (This is a different file
437 * than is used for the main database.)
439 * For POSIX the actual mutexes reside in the shared memory of this
440 * mapped file. On Windows, mutexes are named objects allocated by the
441 * kernel; we store the mutex names in this mapped file so that other
442 * processes can grab them. This same approach will also be used on
443 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
444 * process-shared POSIX mutexes.
446 typedef struct MDB_txbody {
447 /** Stamp identifying this as an MDB lock file. It must be set
450 /** Version number of this lock file. Must be set to #MDB_VERSION. */
451 uint32_t mtb_version;
452 #if defined(_WIN32) || defined(__APPLE__)
453 char mtb_rmname[MNAME_LEN];
455 /** Mutex protecting access to this table.
456 * This is the reader lock that #LOCK_MUTEX_R acquires.
458 pthread_mutex_t mtb_mutex;
460 /** The ID of the last transaction committed to the database.
461 * This is recorded here only for convenience; the value can always
462 * be determined by reading the main database meta pages.
465 /** The number of slots that have been used in the reader table.
466 * This always records the maximum count, it is not decremented
467 * when readers release their slots.
469 unsigned mtb_numreaders;
470 /** The ID of the most recent meta page in the database.
471 * This is recorded here only for convenience; the value can always
472 * be determined by reading the main database meta pages.
474 uint32_t mtb_me_toggle;
477 /** The actual reader table definition. */
478 typedef struct MDB_txninfo {
481 #define mti_magic mt1.mtb.mtb_magic
482 #define mti_version mt1.mtb.mtb_version
483 #define mti_mutex mt1.mtb.mtb_mutex
484 #define mti_rmname mt1.mtb.mtb_rmname
485 #define mti_txnid mt1.mtb.mtb_txnid
486 #define mti_numreaders mt1.mtb.mtb_numreaders
487 #define mti_me_toggle mt1.mtb.mtb_me_toggle
488 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
491 #if defined(_WIN32) || defined(__APPLE__)
492 char mt2_wmname[MNAME_LEN];
493 #define mti_wmname mt2.mt2_wmname
495 pthread_mutex_t mt2_wmutex;
496 #define mti_wmutex mt2.mt2_wmutex
498 char pad[(sizeof(pthread_mutex_t)+CACHELINE-1) & ~(CACHELINE-1)];
500 MDB_reader mti_readers[1];
504 /** Common header for all page types.
505 * Overflow records occupy a number of contiguous pages with no
506 * headers on any page after the first.
508 typedef struct MDB_page {
509 #define mp_pgno mp_p.p_pgno
510 #define mp_next mp_p.p_next
512 pgno_t p_pgno; /**< page number */
513 void * p_next; /**< for in-memory list of freed structs */
516 /** @defgroup mdb_page Page Flags
518 * Flags for the page headers.
521 #define P_BRANCH 0x01 /**< branch page */
522 #define P_LEAF 0x02 /**< leaf page */
523 #define P_OVERFLOW 0x04 /**< overflow page */
524 #define P_META 0x08 /**< meta page */
525 #define P_DIRTY 0x10 /**< dirty page */
526 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
527 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
529 uint16_t mp_flags; /**< @ref mdb_page */
530 #define mp_lower mp_pb.pb.pb_lower
531 #define mp_upper mp_pb.pb.pb_upper
532 #define mp_pages mp_pb.pb_pages
535 indx_t pb_lower; /**< lower bound of free space */
536 indx_t pb_upper; /**< upper bound of free space */
538 uint32_t pb_pages; /**< number of overflow pages */
540 indx_t mp_ptrs[1]; /**< dynamic size */
543 /** Size of the page header, excluding dynamic data at the end */
544 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
546 /** Address of first usable data byte in a page, after the header */
547 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
549 /** Number of nodes on a page */
550 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
552 /** The amount of space remaining in the page */
553 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
555 /** The percentage of space used in the page, in tenths of a percent. */
556 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
557 ((env)->me_psize - PAGEHDRSZ))
558 /** The minimum page fill factor, in tenths of a percent.
559 * Pages emptier than this are candidates for merging.
561 #define FILL_THRESHOLD 250
563 /** Test if a page is a leaf page */
564 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
565 /** Test if a page is a LEAF2 page */
566 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
567 /** Test if a page is a branch page */
568 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
569 /** Test if a page is an overflow page */
570 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
571 /** Test if a page is a sub page */
572 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
574 /** The number of overflow pages needed to store the given size. */
575 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
577 /** Header for a single key/data pair within a page.
578 * We guarantee 2-byte alignment for nodes.
580 typedef struct MDB_node {
581 /** lo and hi are used for data size on leaf nodes and for
582 * child pgno on branch nodes. On 64 bit platforms, flags
583 * is also used for pgno. (Branch nodes have no flags).
584 * They are in host byte order in case that lets some
585 * accesses be optimized into a 32-bit word access.
587 #define mn_lo mn_offset[BYTE_ORDER!=LITTLE_ENDIAN]
588 #define mn_hi mn_offset[BYTE_ORDER==LITTLE_ENDIAN] /**< part of dsize or pgno */
589 unsigned short mn_offset[2]; /**< storage for #mn_lo and #mn_hi */
590 /** @defgroup mdb_node Node Flags
592 * Flags for node headers.
595 #define F_BIGDATA 0x01 /**< data put on overflow page */
596 #define F_SUBDATA 0x02 /**< data is a sub-database */
597 #define F_DUPDATA 0x04 /**< data has duplicates */
599 unsigned short mn_flags; /**< @ref mdb_node */
600 unsigned short mn_ksize; /**< key size */
601 char mn_data[1]; /**< key and data are appended here */
604 /** Size of the node header, excluding dynamic data at the end */
605 #define NODESIZE offsetof(MDB_node, mn_data)
607 /** Bit position of top word in page number, for shifting mn_flags */
608 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
610 /** Size of a node in a branch page with a given key.
611 * This is just the node header plus the key, there is no data.
613 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
615 /** Size of a node in a leaf page with a given key and data.
616 * This is node header plus key plus data size.
618 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
620 /** Address of node \b i in page \b p */
621 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
623 /** Address of the key for the node */
624 #define NODEKEY(node) (void *)((node)->mn_data)
626 /** Address of the data for a node */
627 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
629 /** Get the page number pointed to by a branch node */
630 #define NODEPGNO(node) \
631 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
632 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
633 /** Set the page number in a branch node */
634 #define SETPGNO(node,pgno) do { \
635 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
636 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
638 /** Get the size of the data in a leaf node */
639 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
640 /** Set the size of the data for a leaf node */
641 #define SETDSZ(node,size) do { \
642 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
643 /** The size of a key in a node */
644 #define NODEKSZ(node) ((node)->mn_ksize)
646 /** The address of a key in a LEAF2 page.
647 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
648 * There are no node headers, keys are stored contiguously.
650 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
652 /** Set the \b node's key into \b key, if requested. */
653 #define MDB_SET_KEY(node, key) { if ((key) != NULL) { \
654 (key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node); } }
656 /** Information about a single database in the environment. */
657 typedef struct MDB_db {
658 uint32_t md_pad; /**< also ksize for LEAF2 pages */
659 uint16_t md_flags; /**< @ref mdb_open */
660 uint16_t md_depth; /**< depth of this tree */
661 pgno_t md_branch_pages; /**< number of internal pages */
662 pgno_t md_leaf_pages; /**< number of leaf pages */
663 pgno_t md_overflow_pages; /**< number of overflow pages */
664 size_t md_entries; /**< number of data items */
665 pgno_t md_root; /**< the root page of this tree */
668 /** Handle for the DB used to track free pages. */
670 /** Handle for the default DB. */
673 /** Meta page content. */
674 typedef struct MDB_meta {
675 /** Stamp identifying this as an MDB data file. It must be set
678 /** Version number of this lock file. Must be set to #MDB_VERSION. */
680 void *mm_address; /**< address for fixed mapping */
681 size_t mm_mapsize; /**< size of mmap region */
682 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
683 /** The size of pages used in this DB */
684 #define mm_psize mm_dbs[0].md_pad
685 /** Any persistent environment flags. @ref mdb_env */
686 #define mm_flags mm_dbs[0].md_flags
687 pgno_t mm_last_pg; /**< last used page in file */
688 txnid_t mm_txnid; /**< txnid that committed this page */
691 /** Auxiliary DB info.
692 * The information here is mostly static/read-only. There is
693 * only a single copy of this record in the environment.
695 typedef struct MDB_dbx {
696 MDB_val md_name; /**< name of the database */
697 MDB_cmp_func *md_cmp; /**< function for comparing keys */
698 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
699 MDB_rel_func *md_rel; /**< user relocate function */
700 void *md_relctx; /**< user-provided context for md_rel */
703 /** A database transaction.
704 * Every operation requires a transaction handle.
707 pgno_t mt_next_pgno; /**< next unallocated page */
708 /** The ID of this transaction. IDs are integers incrementing from 1.
709 * Only committed write transactions increment the ID. If a transaction
710 * aborts, the ID may be re-used by the next writer.
713 MDB_env *mt_env; /**< the DB environment */
714 /** The list of pages that became unused during this transaction.
718 ID2L dirty_list; /**< modified pages */
719 MDB_reader *reader; /**< this thread's slot in the reader table */
721 /** Array of records for each DB known in the environment. */
723 /** Array of MDB_db records for each known DB */
725 /** @defgroup mt_dbflag Transaction DB Flags
729 #define DB_DIRTY 0x01 /**< DB was written in this txn */
730 #define DB_STALE 0x02 /**< DB record is older than txnID */
732 /** Array of flags for each DB */
733 unsigned char *mt_dbflags;
734 /** Number of DB records in use. This number only ever increments;
735 * we don't decrement it when individual DB handles are closed.
739 /** @defgroup mdb_txn Transaction Flags
743 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
744 #define MDB_TXN_ERROR 0x02 /**< an error has occurred */
746 unsigned int mt_flags; /**< @ref mdb_txn */
747 /** Tracks which of the two meta pages was used at the start
748 * of this transaction.
750 unsigned int mt_toggle;
753 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
754 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
755 * raise this on a 64 bit machine.
757 #define CURSOR_STACK 32
761 /** Cursors are used for all DB operations */
763 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
764 struct MDB_xcursor *mc_xcursor;
765 /** The transaction that owns this cursor */
767 /** The database handle this cursor operates on */
769 /** The database record for this cursor */
771 /** The database auxiliary record for this cursor */
773 /** The @ref mt_dbflag for this database */
774 unsigned char *mc_dbflag;
775 unsigned short mc_snum; /**< number of pushed pages */
776 unsigned short mc_top; /**< index of top page, mc_snum-1 */
777 /** @defgroup mdb_cursor Cursor Flags
779 * Cursor state flags.
782 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
783 #define C_EOF 0x02 /**< No more data */
785 unsigned int mc_flags; /**< @ref mdb_cursor */
786 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
787 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
790 /** Context for sorted-dup records.
791 * We could have gone to a fully recursive design, with arbitrarily
792 * deep nesting of sub-databases. But for now we only handle these
793 * levels - main DB, optional sub-DB, sorted-duplicate DB.
795 typedef struct MDB_xcursor {
796 /** A sub-cursor for traversing the Dup DB */
797 MDB_cursor mx_cursor;
798 /** The database record for this Dup DB */
800 /** The auxiliary DB record for this Dup DB */
802 /** The @ref mt_dbflag for this Dup DB */
803 unsigned char mx_dbflag;
806 /** A set of pages freed by an earlier transaction. */
807 typedef struct MDB_oldpages {
808 /** Usually we only read one record from the FREEDB at a time, but
809 * in case we read more, this will chain them together.
811 struct MDB_oldpages *mo_next;
812 /** The ID of the transaction in which these pages were freed. */
814 /** An #IDL of the pages */
815 pgno_t mo_pages[1]; /* dynamic */
818 /** The database environment. */
820 HANDLE me_fd; /**< The main data file */
821 HANDLE me_lfd; /**< The lock file */
822 HANDLE me_mfd; /**< just for writing the meta pages */
823 /** Failed to update the meta page. Probably an I/O error. */
824 #define MDB_FATAL_ERROR 0x80000000U
825 uint32_t me_flags; /**< @ref mdb_env */
826 uint32_t me_extrapad; /**< unused for now */
827 unsigned int me_maxreaders; /**< size of the reader table */
828 MDB_dbi me_numdbs; /**< number of DBs opened */
829 MDB_dbi me_maxdbs; /**< size of the DB table */
830 char *me_path; /**< path to the DB files */
831 char *me_map; /**< the memory map of the data file */
832 MDB_txninfo *me_txns; /**< the memory map of the lock file */
833 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
834 MDB_txn *me_txn; /**< current write transaction */
835 size_t me_mapsize; /**< size of the data memory map */
836 off_t me_size; /**< current file size */
837 pgno_t me_maxpg; /**< me_mapsize / me_psize */
838 unsigned int me_psize; /**< size of a page, from #GET_PAGESIZE */
839 unsigned int me_db_toggle; /**< which DB table is current */
840 txnid_t me_wtxnid; /**< ID of last txn we committed */
841 MDB_dbx *me_dbxs; /**< array of static DB info */
842 MDB_db *me_dbs[2]; /**< two arrays of MDB_db info */
843 MDB_oldpages *me_pghead; /**< list of old page records */
844 pthread_key_t me_txkey; /**< thread-key for readers */
845 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
846 /** IDL of pages that became unused in a write txn */
848 /** ID2L of pages that were written during a write txn */
849 ID2 me_dirty_list[MDB_IDL_UM_SIZE];
850 /** rwlock for the DB tables, if #LAZY_LOCKS is false */
851 LAZY_RWLOCK_DEF(me_dblock)
853 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
857 sem_t *me_rmutex; /* Apple doesn't support shared mutexes */
861 /** max number of pages to commit in one writev() call */
862 #define MDB_COMMIT_PAGES 64
864 static MDB_page *mdb_page_alloc(MDB_cursor *mc, int num);
865 static MDB_page *mdb_page_new(MDB_cursor *mc, uint32_t flags, int num);
866 static int mdb_page_touch(MDB_cursor *mc);
868 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
869 static int mdb_page_search_root(MDB_cursor *mc,
870 MDB_val *key, int modify);
871 static int mdb_page_search(MDB_cursor *mc,
872 MDB_val *key, int modify);
873 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
874 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
877 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
878 static int mdb_env_read_meta(MDB_env *env, int *which);
879 static int mdb_env_write_meta(MDB_txn *txn);
881 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
882 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
883 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags);
884 static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
885 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
886 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
887 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
888 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
889 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
891 static int mdb_rebalance(MDB_cursor *mc);
892 static int mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
894 static void mdb_cursor_pop(MDB_cursor *mc);
895 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
897 static int mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
898 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
899 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
900 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
901 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
903 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
904 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
906 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
907 static void mdb_xcursor_init0(MDB_cursor *mc);
908 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
910 static int mdb_drop0(MDB_cursor *mc, int subs);
911 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
914 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
918 static SECURITY_DESCRIPTOR mdb_null_sd;
919 static SECURITY_ATTRIBUTES mdb_all_sa;
920 static int mdb_sec_inited;
923 /** Return the library version info. */
925 mdb_version(int *major, int *minor, int *patch)
927 if (major) *major = MDB_VERSION_MAJOR;
928 if (minor) *minor = MDB_VERSION_MINOR;
929 if (patch) *patch = MDB_VERSION_PATCH;
930 return MDB_VERSION_STRING;
933 /** Table of descriptions for MDB @ref errors */
934 static char *const mdb_errstr[] = {
935 "MDB_KEYEXIST: Key/data pair already exists",
936 "MDB_NOTFOUND: No matching key/data pair found",
937 "MDB_PAGE_NOTFOUND: Requested page not found",
938 "MDB_CORRUPTED: Located page was wrong type",
939 "MDB_PANIC: Update of meta page failed",
940 "MDB_VERSION_MISMATCH: Database environment version mismatch"
944 mdb_strerror(int err)
947 return ("Successful return: 0");
949 if (err >= MDB_KEYEXIST && err <= MDB_VERSION_MISMATCH)
950 return mdb_errstr[err - MDB_KEYEXIST];
952 return strerror(err);
956 /** Display a key in hexadecimal and return the address of the result.
957 * @param[in] key the key to display
958 * @param[in] buf the buffer to write into. Should always be #DKBUF.
959 * @return The key in hexadecimal form.
962 mdb_dkey(MDB_val *key, char *buf)
965 unsigned char *c = key->mv_data;
967 if (key->mv_size > MAXKEYSIZE)
969 /* may want to make this a dynamic check: if the key is mostly
970 * printable characters, print it as-is instead of converting to hex.
973 for (i=0; i<key->mv_size; i++)
974 ptr += sprintf(ptr, "%02x", *c++);
976 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
983 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
985 return txn->mt_dbxs[dbi].md_cmp(a, b);
989 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
991 if (txn->mt_dbxs[dbi].md_dcmp)
992 return txn->mt_dbxs[dbi].md_dcmp(a, b);
994 return EINVAL; /* too bad you can't distinguish this from a valid result */
997 /** Allocate pages for writing.
998 * If there are free pages available from older transactions, they
999 * will be re-used first. Otherwise a new page will be allocated.
1000 * @param[in] mc cursor A cursor handle identifying the transaction and
1001 * database for which we are allocating.
1002 * @param[in] num the number of pages to allocate.
1003 * @return Address of the allocated page(s). Requests for multiple pages
1004 * will always be satisfied by a single contiguous chunk of memory.
1007 mdb_page_alloc(MDB_cursor *mc, int num)
1009 MDB_txn *txn = mc->mc_txn;
1011 pgno_t pgno = P_INVALID;
1014 if (txn->mt_txnid > 2) {
1016 if (!txn->mt_env->me_pghead && mc->mc_dbi != FREE_DBI &&
1017 txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
1018 /* See if there's anything in the free DB */
1021 txnid_t *kptr, oldest;
1023 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1024 mdb_page_search(&m2, NULL, 0);
1025 leaf = NODEPTR(m2.mc_pg[m2.mc_top], 0);
1026 kptr = (txnid_t *)NODEKEY(leaf);
1030 oldest = txn->mt_txnid - 1;
1031 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
1032 txnid_t mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
1033 if (mr && mr < oldest)
1038 if (oldest > *kptr) {
1039 /* It's usable, grab it.
1045 mdb_node_read(txn, leaf, &data);
1046 idl = (ID *) data.mv_data;
1047 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
1048 mop->mo_next = txn->mt_env->me_pghead;
1049 mop->mo_txnid = *kptr;
1050 txn->mt_env->me_pghead = mop;
1051 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
1056 DPRINTF("IDL read txn %zu root %zu num %zu",
1057 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1058 for (i=0; i<idl[0]; i++) {
1059 DPRINTF("IDL %zu", idl[i+1]);
1063 /* drop this IDL from the DB */
1064 m2.mc_ki[m2.mc_top] = 0;
1065 m2.mc_flags = C_INITIALIZED;
1066 mdb_cursor_del(&m2, 0);
1069 if (txn->mt_env->me_pghead) {
1070 MDB_oldpages *mop = txn->mt_env->me_pghead;
1072 /* FIXME: For now, always use fresh pages. We
1073 * really ought to search the free list for a
1078 /* peel pages off tail, so we only have to truncate the list */
1079 pgno = MDB_IDL_LAST(mop->mo_pages);
1080 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
1082 if (mop->mo_pages[2] > mop->mo_pages[1])
1083 mop->mo_pages[0] = 0;
1087 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
1088 txn->mt_env->me_pghead = mop->mo_next;
1095 if (pgno == P_INVALID) {
1096 /* DB size is maxed out */
1097 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg) {
1098 assert(txn->mt_next_pgno + num < txn->mt_env->me_maxpg);
1102 if (txn->mt_env->me_dpages && num == 1) {
1103 np = txn->mt_env->me_dpages;
1104 txn->mt_env->me_dpages = np->mp_next;
1106 if ((np = malloc(txn->mt_env->me_psize * num )) == NULL)
1109 if (pgno == P_INVALID) {
1110 np->mp_pgno = txn->mt_next_pgno;
1111 txn->mt_next_pgno += num;
1115 mid.mid = np->mp_pgno;
1117 mdb_mid2l_insert(txn->mt_u.dirty_list, &mid);
1122 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1123 * @param[in] mc cursor pointing to the page to be touched
1124 * @return 0 on success, non-zero on failure.
1127 mdb_page_touch(MDB_cursor *mc)
1129 MDB_page *mp = mc->mc_pg[mc->mc_top];
1132 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1134 if ((np = mdb_page_alloc(mc, 1)) == NULL)
1136 DPRINTF("touched db %u page %zu -> %zu", mc->mc_dbi, mp->mp_pgno, np->mp_pgno);
1137 assert(mp->mp_pgno != np->mp_pgno);
1138 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
1140 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1143 mp->mp_flags |= P_DIRTY;
1145 mc->mc_pg[mc->mc_top] = mp;
1146 /** If this page has a parent, update the parent to point to
1150 SETPGNO(NODEPTR(mc->mc_pg[mc->mc_top-1], mc->mc_ki[mc->mc_top-1]), mp->mp_pgno);
1156 mdb_env_sync(MDB_env *env, int force)
1159 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1160 if (fdatasync(env->me_fd))
1167 mdb_txn_reset0(MDB_txn *txn);
1169 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
1170 * @param[in] txn the transaction handle to initialize
1171 * @return 0 on success, non-zero on failure. This can only
1172 * fail for read-only transactions, and then only if the
1173 * reader table is full.
1176 mdb_txn_renew0(MDB_txn *txn)
1178 MDB_env *env = txn->mt_env;
1181 if (txn->mt_flags & MDB_TXN_RDONLY) {
1182 MDB_reader *r = pthread_getspecific(env->me_txkey);
1185 pid_t pid = getpid();
1186 pthread_t tid = pthread_self();
1189 for (i=0; i<env->me_txns->mti_numreaders; i++)
1190 if (env->me_txns->mti_readers[i].mr_pid == 0)
1192 if (i == env->me_maxreaders) {
1193 UNLOCK_MUTEX_R(env);
1196 env->me_txns->mti_readers[i].mr_pid = pid;
1197 env->me_txns->mti_readers[i].mr_tid = tid;
1198 if (i >= env->me_txns->mti_numreaders)
1199 env->me_txns->mti_numreaders = i+1;
1200 UNLOCK_MUTEX_R(env);
1201 r = &env->me_txns->mti_readers[i];
1202 pthread_setspecific(env->me_txkey, r);
1204 txn->mt_toggle = env->me_txns->mti_me_toggle;
1205 txn->mt_txnid = env->me_txns->mti_txnid;
1206 /* This happens if a different process was the
1207 * last writer to the DB.
1209 if (env->me_wtxnid < txn->mt_txnid)
1210 mt_dbflag = DB_STALE;
1211 r->mr_txnid = txn->mt_txnid;
1212 txn->mt_u.reader = r;
1216 txn->mt_txnid = env->me_txns->mti_txnid;
1217 if (env->me_wtxnid < txn->mt_txnid)
1218 mt_dbflag = DB_STALE;
1220 txn->mt_toggle = env->me_txns->mti_me_toggle;
1221 txn->mt_u.dirty_list = env->me_dirty_list;
1222 txn->mt_u.dirty_list[0].mid = 0;
1223 txn->mt_free_pgs = env->me_free_pgs;
1224 txn->mt_free_pgs[0] = 0;
1225 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1229 /* Copy the DB arrays */
1230 LAZY_RWLOCK_RDLOCK(&env->me_dblock);
1231 txn->mt_numdbs = env->me_numdbs;
1232 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
1233 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
1234 if (txn->mt_numdbs > 2)
1235 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
1236 (txn->mt_numdbs - 2) * sizeof(MDB_db));
1237 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1239 memset(txn->mt_dbflags, mt_dbflag, env->me_numdbs);
1245 mdb_txn_renew(MDB_txn *txn)
1252 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
1253 DPUTS("environment had fatal error, must shutdown!");
1257 rc = mdb_txn_renew0(txn);
1258 if (rc == MDB_SUCCESS) {
1259 DPRINTF("renew txn %zu%c %p on mdbenv %p, root page %zu",
1260 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1261 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1267 mdb_txn_begin(MDB_env *env, unsigned int flags, MDB_txn **ret)
1272 if (env->me_flags & MDB_FATAL_ERROR) {
1273 DPUTS("environment had fatal error, must shutdown!");
1276 if ((txn = calloc(1, sizeof(MDB_txn) +
1277 env->me_maxdbs * (sizeof(MDB_db)+1))) == NULL) {
1278 DPRINTF("calloc: %s", strerror(ErrCode()));
1281 txn->mt_dbs = (MDB_db *)(txn+1);
1282 if (flags & MDB_RDONLY) {
1283 txn->mt_flags |= MDB_TXN_RDONLY;
1285 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
1288 rc = mdb_txn_renew0(txn);
1293 DPRINTF("begin txn %zu%c %p on mdbenv %p, root page %zu",
1294 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1295 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
1301 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
1302 * @param[in] txn the transaction handle to reset
1305 mdb_txn_reset0(MDB_txn *txn)
1307 MDB_env *env = txn->mt_env;
1309 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1310 txn->mt_u.reader->mr_txnid = 0;
1316 if (mdb_midl_shrink(&txn->mt_free_pgs))
1317 env->me_free_pgs = txn->mt_free_pgs;
1319 /* return all dirty pages to dpage list */
1320 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1321 dp = txn->mt_u.dirty_list[i].mptr;
1322 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1323 dp->mp_next = txn->mt_env->me_dpages;
1324 txn->mt_env->me_dpages = dp;
1326 /* large pages just get freed directly */
1331 while ((mop = txn->mt_env->me_pghead)) {
1332 txn->mt_env->me_pghead = mop->mo_next;
1337 /* The writer mutex was locked in mdb_txn_begin. */
1338 UNLOCK_MUTEX_W(env);
1343 mdb_txn_reset(MDB_txn *txn)
1348 DPRINTF("reset txn %zu%c %p on mdbenv %p, root page %zu",
1349 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1350 (void *) txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1352 mdb_txn_reset0(txn);
1356 mdb_txn_abort(MDB_txn *txn)
1361 DPRINTF("abort txn %zu%c %p on mdbenv %p, root page %zu",
1362 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1363 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1365 mdb_txn_reset0(txn);
1370 mdb_txn_commit(MDB_txn *txn)
1381 assert(txn != NULL);
1382 assert(txn->mt_env != NULL);
1386 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1387 if (txn->mt_numdbs > env->me_numdbs) {
1388 /* update the DB tables */
1389 int toggle = !env->me_db_toggle;
1393 ip = &env->me_dbs[toggle][env->me_numdbs];
1394 jp = &txn->mt_dbs[env->me_numdbs];
1395 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1396 for (i = env->me_numdbs; i < txn->mt_numdbs; i++) {
1400 env->me_db_toggle = toggle;
1401 env->me_numdbs = txn->mt_numdbs;
1402 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1408 if (txn != env->me_txn) {
1409 DPUTS("attempt to commit unknown transaction");
1414 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1415 DPUTS("error flag is set, can't commit");
1420 if (!txn->mt_u.dirty_list[0].mid)
1423 DPRINTF("committing txn %zu %p on mdbenv %p, root page %zu",
1424 txn->mt_txnid, (void *)txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
1426 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1428 /* should only be one record now */
1429 if (env->me_pghead) {
1430 /* make sure first page of freeDB is touched and on freelist */
1431 mdb_page_search(&mc, NULL, 1);
1433 /* save to free list */
1434 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
1438 /* make sure last page of freeDB is touched and on freelist */
1439 key.mv_size = MAXKEYSIZE+1;
1441 mdb_page_search(&mc, &key, 1);
1443 mdb_midl_sort(txn->mt_free_pgs);
1447 ID *idl = txn->mt_free_pgs;
1448 DPRINTF("IDL write txn %zu root %zu num %zu",
1449 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1450 for (i=0; i<idl[0]; i++) {
1451 DPRINTF("IDL %zu", idl[i+1]);
1455 /* write to last page of freeDB */
1456 key.mv_size = sizeof(pgno_t);
1457 key.mv_data = &txn->mt_txnid;
1458 data.mv_data = txn->mt_free_pgs;
1459 /* The free list can still grow during this call,
1460 * despite the pre-emptive touches above. So check
1461 * and make sure the entire thing got written.
1464 i = txn->mt_free_pgs[0];
1465 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
1466 rc = mdb_cursor_put(&mc, &key, &data, 0);
1471 } while (i != txn->mt_free_pgs[0]);
1472 if (mdb_midl_shrink(&txn->mt_free_pgs))
1473 env->me_free_pgs = txn->mt_free_pgs;
1475 /* should only be one record now */
1476 if (env->me_pghead) {
1480 mop = env->me_pghead;
1481 key.mv_size = sizeof(pgno_t);
1482 key.mv_data = &mop->mo_txnid;
1483 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
1484 data.mv_data = mop->mo_pages;
1485 mdb_cursor_put(&mc, &key, &data, 0);
1486 free(env->me_pghead);
1487 env->me_pghead = NULL;
1490 /* Update DB root pointers. Their pages have already been
1491 * touched so this is all in-place and cannot fail.
1496 data.mv_size = sizeof(MDB_db);
1498 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
1499 for (i = 2; i < txn->mt_numdbs; i++) {
1500 if (txn->mt_dbflags[i] & DB_DIRTY) {
1501 data.mv_data = &txn->mt_dbs[i];
1502 mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
1507 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
1513 /* Windows actually supports scatter/gather I/O, but only on
1514 * unbuffered file handles. Since we're relying on the OS page
1515 * cache for all our data, that's self-defeating. So we just
1516 * write pages one at a time. We use the ov structure to set
1517 * the write offset, to at least save the overhead of a Seek
1521 memset(&ov, 0, sizeof(ov));
1522 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1524 dp = txn->mt_u.dirty_list[i].mptr;
1525 DPRINTF("committing page %zu", dp->mp_pgno);
1526 size = dp->mp_pgno * env->me_psize;
1527 ov.Offset = size & 0xffffffff;
1528 ov.OffsetHigh = size >> 16;
1529 ov.OffsetHigh >>= 16;
1530 /* clear dirty flag */
1531 dp->mp_flags &= ~P_DIRTY;
1532 wsize = env->me_psize;
1533 if (IS_OVERFLOW(dp)) wsize *= dp->mp_pages;
1534 rc = WriteFile(env->me_fd, dp, wsize, NULL, &ov);
1537 DPRINTF("WriteFile: %d", n);
1544 struct iovec iov[MDB_COMMIT_PAGES];
1548 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1549 dp = txn->mt_u.dirty_list[i].mptr;
1550 if (dp->mp_pgno != next) {
1552 DPRINTF("committing %u dirty pages", n);
1553 rc = writev(env->me_fd, iov, n);
1557 DPUTS("short write, filesystem full?");
1559 DPRINTF("writev: %s", strerror(n));
1566 lseek(env->me_fd, dp->mp_pgno * env->me_psize, SEEK_SET);
1569 DPRINTF("committing page %zu", dp->mp_pgno);
1570 iov[n].iov_len = env->me_psize;
1571 if (IS_OVERFLOW(dp)) iov[n].iov_len *= dp->mp_pages;
1572 iov[n].iov_base = dp;
1573 size += iov[n].iov_len;
1574 next = dp->mp_pgno + (IS_OVERFLOW(dp) ? dp->mp_pages : 1);
1575 /* clear dirty flag */
1576 dp->mp_flags &= ~P_DIRTY;
1577 if (++n >= MDB_COMMIT_PAGES) {
1587 DPRINTF("committing %u dirty pages", n);
1588 rc = writev(env->me_fd, iov, n);
1592 DPUTS("short write, filesystem full?");
1594 DPRINTF("writev: %s", strerror(n));
1601 /* Drop the dirty pages.
1603 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1604 dp = txn->mt_u.dirty_list[i].mptr;
1605 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1606 dp->mp_next = txn->mt_env->me_dpages;
1607 txn->mt_env->me_dpages = dp;
1611 txn->mt_u.dirty_list[i].mid = 0;
1613 txn->mt_u.dirty_list[0].mid = 0;
1615 if ((n = mdb_env_sync(env, 0)) != 0 ||
1616 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
1622 env->me_wtxnid = txn->mt_txnid;
1624 /* update the DB tables */
1626 int toggle = !env->me_db_toggle;
1630 ip = &env->me_dbs[toggle][2];
1631 jp = &txn->mt_dbs[2];
1632 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1633 for (i = 2; i < txn->mt_numdbs; i++) {
1634 if (ip->md_root != jp->md_root)
1639 env->me_db_toggle = toggle;
1640 env->me_numdbs = txn->mt_numdbs;
1641 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1644 UNLOCK_MUTEX_W(env);
1650 /** Read the environment parameters of a DB environment before
1651 * mapping it into memory.
1652 * @param[in] env the environment handle
1653 * @param[out] meta address of where to store the meta information
1654 * @return 0 on success, non-zero on failure.
1657 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
1659 char page[PAGESIZE];
1664 /* We don't know the page size yet, so use a minimum value.
1668 if (!ReadFile(env->me_fd, page, PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
1670 if ((rc = read(env->me_fd, page, PAGESIZE)) == 0)
1675 else if (rc != PAGESIZE) {
1679 DPRINTF("read: %s", strerror(err));
1683 p = (MDB_page *)page;
1685 if (!F_ISSET(p->mp_flags, P_META)) {
1686 DPRINTF("page %zu not a meta page", p->mp_pgno);
1691 if (m->mm_magic != MDB_MAGIC) {
1692 DPUTS("meta has invalid magic");
1696 if (m->mm_version != MDB_VERSION) {
1697 DPRINTF("database is version %u, expected version %u",
1698 m->mm_version, MDB_VERSION);
1699 return MDB_VERSION_MISMATCH;
1702 memcpy(meta, m, sizeof(*m));
1706 /** Write the environment parameters of a freshly created DB environment.
1707 * @param[in] env the environment handle
1708 * @param[out] meta address of where to store the meta information
1709 * @return 0 on success, non-zero on failure.
1712 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
1719 DPUTS("writing new meta page");
1721 GET_PAGESIZE(psize);
1723 meta->mm_magic = MDB_MAGIC;
1724 meta->mm_version = MDB_VERSION;
1725 meta->mm_psize = psize;
1726 meta->mm_last_pg = 1;
1727 meta->mm_flags = env->me_flags & 0xffff;
1728 meta->mm_flags |= MDB_INTEGERKEY;
1729 meta->mm_dbs[0].md_root = P_INVALID;
1730 meta->mm_dbs[1].md_root = P_INVALID;
1732 p = calloc(2, psize);
1734 p->mp_flags = P_META;
1737 memcpy(m, meta, sizeof(*meta));
1739 q = (MDB_page *)((char *)p + psize);
1742 q->mp_flags = P_META;
1745 memcpy(m, meta, sizeof(*meta));
1750 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
1751 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
1754 rc = write(env->me_fd, p, psize * 2);
1755 rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
1761 /** Update the environment info to commit a transaction.
1762 * @param[in] txn the transaction that's being committed
1763 * @return 0 on success, non-zero on failure.
1766 mdb_env_write_meta(MDB_txn *txn)
1769 MDB_meta meta, metab;
1771 int rc, len, toggle;
1777 assert(txn != NULL);
1778 assert(txn->mt_env != NULL);
1780 toggle = !txn->mt_toggle;
1781 DPRINTF("writing meta page %d for root page %zu",
1782 toggle, txn->mt_dbs[MAIN_DBI].md_root);
1786 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
1787 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
1789 ptr = (char *)&meta;
1790 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
1791 len = sizeof(MDB_meta) - off;
1794 meta.mm_dbs[0] = txn->mt_dbs[0];
1795 meta.mm_dbs[1] = txn->mt_dbs[1];
1796 meta.mm_last_pg = txn->mt_next_pgno - 1;
1797 meta.mm_txnid = txn->mt_txnid;
1800 off += env->me_psize;
1803 /* Write to the SYNC fd */
1806 memset(&ov, 0, sizeof(ov));
1808 WriteFile(env->me_mfd, ptr, len, (DWORD *)&rc, &ov);
1811 rc = pwrite(env->me_mfd, ptr, len, off);
1816 DPUTS("write failed, disk error?");
1817 /* On a failure, the pagecache still contains the new data.
1818 * Write some old data back, to prevent it from being used.
1819 * Use the non-SYNC fd; we know it will fail anyway.
1821 meta.mm_last_pg = metab.mm_last_pg;
1822 meta.mm_txnid = metab.mm_txnid;
1824 WriteFile(env->me_fd, ptr, len, NULL, &ov);
1826 r2 = pwrite(env->me_fd, ptr, len, off);
1828 env->me_flags |= MDB_FATAL_ERROR;
1831 /* Memory ordering issues are irrelevant; since the entire writer
1832 * is wrapped by wmutex, all of these changes will become visible
1833 * after the wmutex is unlocked. Since the DB is multi-version,
1834 * readers will get consistent data regardless of how fresh or
1835 * how stale their view of these values is.
1837 LAZY_MUTEX_LOCK(&env->me_txns->mti_mutex);
1838 txn->mt_env->me_txns->mti_me_toggle = toggle;
1839 txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
1840 LAZY_MUTEX_UNLOCK(&env->me_txns->mti_mutex);
1845 /** Check both meta pages to see which one is newer.
1846 * @param[in] env the environment handle
1847 * @param[out] which address of where to store the meta toggle ID
1848 * @return 0 on success, non-zero on failure.
1851 mdb_env_read_meta(MDB_env *env, int *which)
1855 assert(env != NULL);
1857 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1860 DPRINTF("Using meta page %d", toggle);
1867 mdb_env_create(MDB_env **env)
1871 e = calloc(1, sizeof(MDB_env));
1875 e->me_free_pgs = mdb_midl_alloc();
1876 if (!e->me_free_pgs) {
1880 e->me_maxreaders = DEFAULT_READERS;
1882 e->me_fd = INVALID_HANDLE_VALUE;
1883 e->me_lfd = INVALID_HANDLE_VALUE;
1884 e->me_mfd = INVALID_HANDLE_VALUE;
1890 mdb_env_set_mapsize(MDB_env *env, size_t size)
1894 env->me_mapsize = size;
1899 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
1903 env->me_maxdbs = dbs;
1908 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
1910 if (env->me_map || readers < 1)
1912 env->me_maxreaders = readers;
1917 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
1919 if (!env || !readers)
1921 *readers = env->me_maxreaders;
1925 /** Further setup required for opening an MDB environment
1928 mdb_env_open2(MDB_env *env, unsigned int flags)
1930 int i, newenv = 0, toggle;
1934 env->me_flags = flags;
1936 memset(&meta, 0, sizeof(meta));
1938 if ((i = mdb_env_read_header(env, &meta)) != 0) {
1941 DPUTS("new mdbenv");
1945 if (!env->me_mapsize) {
1946 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
1952 LONG sizelo, sizehi;
1953 sizelo = env->me_mapsize & 0xffffffff;
1954 sizehi = env->me_mapsize >> 16; /* pointless on WIN32, only needed on W64 */
1956 /* Windows won't create mappings for zero length files.
1957 * Just allocate the maxsize right now.
1960 SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
1961 if (!SetEndOfFile(env->me_fd))
1963 SetFilePointer(env->me_fd, 0, NULL, 0);
1965 mh = CreateFileMapping(env->me_fd, NULL, PAGE_READONLY,
1966 sizehi, sizelo, NULL);
1969 env->me_map = MapViewOfFileEx(mh, FILE_MAP_READ, 0, 0, env->me_mapsize,
1977 if (meta.mm_address && (flags & MDB_FIXEDMAP))
1979 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
1981 if (env->me_map == MAP_FAILED)
1986 meta.mm_mapsize = env->me_mapsize;
1987 if (flags & MDB_FIXEDMAP)
1988 meta.mm_address = env->me_map;
1989 i = mdb_env_init_meta(env, &meta);
1990 if (i != MDB_SUCCESS) {
1991 munmap(env->me_map, env->me_mapsize);
1995 env->me_psize = meta.mm_psize;
1997 env->me_maxpg = env->me_mapsize / env->me_psize;
1999 p = (MDB_page *)env->me_map;
2000 env->me_metas[0] = METADATA(p);
2001 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
2003 if ((i = mdb_env_read_meta(env, &toggle)) != 0)
2006 DPRINTF("opened database version %u, pagesize %u",
2007 env->me_metas[toggle]->mm_version, env->me_psize);
2008 DPRINTF("depth: %u", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_depth);
2009 DPRINTF("entries: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_entries);
2010 DPRINTF("branch pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_branch_pages);
2011 DPRINTF("leaf pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_leaf_pages);
2012 DPRINTF("overflow pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_overflow_pages);
2013 DPRINTF("root: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_root);
2019 /** Release a reader thread's slot in the reader lock table.
2020 * This function is called automatically when a thread exits.
2021 * Windows doesn't support destructor callbacks for thread-specific storage,
2022 * so this function is not compiled there.
2023 * @param[in] ptr This points to the slot in the reader lock table.
2026 mdb_env_reader_dest(void *ptr)
2028 MDB_reader *reader = ptr;
2030 reader->mr_txnid = 0;
2036 /** Downgrade the exclusive lock on the region back to shared */
2038 mdb_env_share_locks(MDB_env *env)
2042 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
2044 env->me_txns->mti_me_toggle = toggle;
2045 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
2050 /* First acquire a shared lock. The Unlock will
2051 * then release the existing exclusive lock.
2053 memset(&ov, 0, sizeof(ov));
2054 LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov);
2055 UnlockFile(env->me_lfd, 0, 0, 1, 0);
2059 struct flock lock_info;
2060 /* The shared lock replaces the existing lock */
2061 memset((void *)&lock_info, 0, sizeof(lock_info));
2062 lock_info.l_type = F_RDLCK;
2063 lock_info.l_whence = SEEK_SET;
2064 lock_info.l_start = 0;
2065 lock_info.l_len = 1;
2066 fcntl(env->me_lfd, F_SETLK, &lock_info);
2070 #if defined(_WIN32) || defined(__APPLE__)
2072 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
2074 * @(#) $Revision: 5.1 $
2075 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
2076 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
2078 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
2082 * Please do not copyright this code. This code is in the public domain.
2084 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
2085 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
2086 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
2087 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
2088 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
2089 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
2090 * PERFORMANCE OF THIS SOFTWARE.
2093 * chongo <Landon Curt Noll> /\oo/\
2094 * http://www.isthe.com/chongo/
2096 * Share and Enjoy! :-)
2099 typedef unsigned long long mdb_hash_t;
2100 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
2102 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
2103 * @param[in] str string to hash
2104 * @param[in] hval initial value for hash
2105 * @return 64 bit hash
2107 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
2108 * hval arg on the first call.
2111 mdb_hash_str(char *str, mdb_hash_t hval)
2113 unsigned char *s = (unsigned char *)str; /* unsigned string */
2115 * FNV-1a hash each octet of the string
2118 /* xor the bottom with the current octet */
2119 hval ^= (mdb_hash_t)*s++;
2121 /* multiply by the 64 bit FNV magic prime mod 2^64 */
2122 hval += (hval << 1) + (hval << 4) + (hval << 5) +
2123 (hval << 7) + (hval << 8) + (hval << 40);
2125 /* return our new hash value */
2129 /** Hash the string and output the hash in hex.
2130 * @param[in] str string to hash
2131 * @param[out] hexbuf an array of 17 chars to hold the hash
2134 mdb_hash_hex(char *str, char *hexbuf)
2137 mdb_hash_t h = mdb_hash_str(str, MDB_HASH_INIT);
2138 for (i=0; i<8; i++) {
2139 hexbuf += sprintf(hexbuf, "%02x", (unsigned int)h & 0xff);
2145 /** Open and/or initialize the lock region for the environment.
2146 * @param[in] env The MDB environment.
2147 * @param[in] lpath The pathname of the file used for the lock region.
2148 * @param[in] mode The Unix permissions for the file, if we create it.
2149 * @param[out] excl Set to true if we got an exclusive lock on the region.
2150 * @return 0 on success, non-zero on failure.
2153 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
2161 if ((env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
2162 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
2163 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
2167 /* Try to get exclusive lock. If we succeed, then
2168 * nobody is using the lock region and we should initialize it.
2171 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
2175 memset(&ov, 0, sizeof(ov));
2176 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
2182 size = GetFileSize(env->me_lfd, NULL);
2184 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
2188 /* Try to get exclusive lock. If we succeed, then
2189 * nobody is using the lock region and we should initialize it.
2192 struct flock lock_info;
2193 memset((void *)&lock_info, 0, sizeof(lock_info));
2194 lock_info.l_type = F_WRLCK;
2195 lock_info.l_whence = SEEK_SET;
2196 lock_info.l_start = 0;
2197 lock_info.l_len = 1;
2198 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
2202 lock_info.l_type = F_RDLCK;
2203 rc = fcntl(env->me_lfd, F_SETLKW, &lock_info);
2210 size = lseek(env->me_lfd, 0, SEEK_END);
2212 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
2213 if (size < rsize && *excl) {
2215 SetFilePointer(env->me_lfd, rsize, NULL, 0);
2216 if (!SetEndOfFile(env->me_lfd)) {
2221 if (ftruncate(env->me_lfd, rsize) != 0) {
2228 size = rsize - sizeof(MDB_txninfo);
2229 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
2234 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
2240 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
2242 if (!env->me_txns) {
2248 env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
2250 if (env->me_txns == MAP_FAILED) {
2258 if (!mdb_sec_inited) {
2259 InitializeSecurityDescriptor(&mdb_null_sd,
2260 SECURITY_DESCRIPTOR_REVISION);
2261 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
2262 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2263 mdb_all_sa.bInheritHandle = FALSE;
2264 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
2267 mdb_hash_hex(lpath, hexbuf);
2268 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", hexbuf);
2269 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
2270 if (!env->me_rmutex) {
2274 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", hexbuf);
2275 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
2276 if (!env->me_wmutex) {
2283 mdb_hash_hex(lpath, hexbuf);
2284 sprintf(env->me_txns->mti_rmname, "MDBr%s", hexbuf);
2285 if (sem_unlink(env->me_txns->mti_rmname)) {
2287 if (rc != ENOENT && rc != EINVAL)
2290 env->me_rmutex = sem_open(env->me_txns->mti_rmname, O_CREAT, mode, 1);
2291 if (!env->me_rmutex) {
2295 sprintf(env->me_txns->mti_wmname, "MDBw%s", hexbuf);
2296 if (sem_unlink(env->me_txns->mti_wmname)) {
2298 if (rc != ENOENT && rc != EINVAL)
2301 env->me_wmutex = sem_open(env->me_txns->mti_wmname, O_CREAT, mode, 1);
2302 if (!env->me_wmutex) {
2306 #else /* __APPLE__ */
2307 pthread_mutexattr_t mattr;
2309 pthread_mutexattr_init(&mattr);
2310 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
2314 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
2315 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
2316 #endif /* __APPLE__ */
2318 env->me_txns->mti_version = MDB_VERSION;
2319 env->me_txns->mti_magic = MDB_MAGIC;
2320 env->me_txns->mti_txnid = 0;
2321 env->me_txns->mti_numreaders = 0;
2322 env->me_txns->mti_me_toggle = 0;
2325 if (env->me_txns->mti_magic != MDB_MAGIC) {
2326 DPUTS("lock region has invalid magic");
2330 if (env->me_txns->mti_version != MDB_VERSION) {
2331 DPRINTF("lock region is version %u, expected version %u",
2332 env->me_txns->mti_version, MDB_VERSION);
2333 rc = MDB_VERSION_MISMATCH;
2337 if (rc != EACCES && rc != EAGAIN) {
2341 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
2342 if (!env->me_rmutex) {
2346 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
2347 if (!env->me_wmutex) {
2353 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
2354 if (!env->me_rmutex) {
2358 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
2359 if (!env->me_wmutex) {
2369 env->me_lfd = INVALID_HANDLE_VALUE;
2374 /** The name of the lock file in the DB environment */
2375 #define LOCKNAME "/lock.mdb"
2376 /** The name of the data file in the DB environment */
2377 #define DATANAME "/data.mdb"
2379 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
2381 int oflags, rc, len, excl;
2382 char *lpath, *dpath;
2385 lpath = malloc(len + sizeof(LOCKNAME) + len + sizeof(DATANAME));
2388 dpath = lpath + len + sizeof(LOCKNAME);
2389 sprintf(lpath, "%s" LOCKNAME, path);
2390 sprintf(dpath, "%s" DATANAME, path);
2392 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
2397 if (F_ISSET(flags, MDB_RDONLY)) {
2398 oflags = GENERIC_READ;
2399 len = OPEN_EXISTING;
2401 oflags = GENERIC_READ|GENERIC_WRITE;
2404 mode = FILE_ATTRIBUTE_NORMAL;
2405 if ((env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2406 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2411 if (F_ISSET(flags, MDB_RDONLY))
2414 oflags = O_RDWR | O_CREAT;
2416 if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
2422 if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
2423 /* synchronous fd for meta writes */
2425 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2426 mode |= FILE_FLAG_WRITE_THROUGH;
2427 if ((env->me_mfd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2428 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2433 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2434 oflags |= MDB_DSYNC;
2435 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
2440 env->me_path = strdup(path);
2441 DPRINTF("opened dbenv %p", (void *) env);
2442 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
2443 LAZY_RWLOCK_INIT(&env->me_dblock, NULL);
2445 mdb_env_share_locks(env);
2446 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
2447 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
2448 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
2454 if (env->me_fd != INVALID_HANDLE_VALUE) {
2456 env->me_fd = INVALID_HANDLE_VALUE;
2458 if (env->me_lfd != INVALID_HANDLE_VALUE) {
2460 env->me_lfd = INVALID_HANDLE_VALUE;
2468 mdb_env_close(MDB_env *env)
2475 while (env->me_dpages) {
2476 dp = env->me_dpages;
2477 env->me_dpages = dp->mp_next;
2481 free(env->me_dbs[1]);
2482 free(env->me_dbs[0]);
2486 LAZY_RWLOCK_DESTROY(&env->me_dblock);
2487 pthread_key_delete(env->me_txkey);
2490 munmap(env->me_map, env->me_mapsize);
2495 pid_t pid = getpid();
2497 for (i=0; i<env->me_txns->mti_numreaders; i++)
2498 if (env->me_txns->mti_readers[i].mr_pid == pid)
2499 env->me_txns->mti_readers[i].mr_pid = 0;
2500 munmap(env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
2503 mdb_midl_free(env->me_free_pgs);
2507 /** Compare two items pointing at aligned size_t's */
2509 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
2511 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
2512 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
2515 /** Compare two items pointing at aligned int's */
2517 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
2519 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
2520 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
2523 /** Compare two items pointing at ints of unknown alignment.
2524 * Nodes and keys are guaranteed to be 2-byte aligned.
2527 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
2529 #if BYTE_ORDER == LITTLE_ENDIAN
2530 unsigned short *u, *c;
2533 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
2534 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
2537 } while(!x && u > (unsigned short *)a->mv_data);
2540 return memcmp(a->mv_data, b->mv_data, a->mv_size);
2544 /** Compare two items lexically */
2546 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
2553 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
2559 diff = memcmp(a->mv_data, b->mv_data, len);
2560 return diff ? diff : len_diff<0 ? -1 : len_diff;
2563 /** Compare two items in reverse byte order */
2565 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
2567 const unsigned char *p1, *p2, *p1_lim;
2571 p1_lim = (const unsigned char *)a->mv_data;
2572 p1 = (const unsigned char *)a->mv_data + a->mv_size;
2573 p2 = (const unsigned char *)b->mv_data + b->mv_size;
2575 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
2581 while (p1 > p1_lim) {
2582 diff = *--p1 - *--p2;
2586 return len_diff<0 ? -1 : len_diff;
2589 /** Search for key within a page, using binary search.
2590 * Returns the smallest entry larger or equal to the key.
2591 * If exactp is non-null, stores whether the found entry was an exact match
2592 * in *exactp (1 or 0).
2593 * Updates the cursor index with the index of the found entry.
2594 * If no entry larger or equal to the key is found, returns NULL.
2597 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
2599 unsigned int i = 0, nkeys;
2602 MDB_page *mp = mc->mc_pg[mc->mc_top];
2603 MDB_node *node = NULL;
2608 nkeys = NUMKEYS(mp);
2610 DPRINTF("searching %u keys in %s %spage %zu",
2611 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
2616 low = IS_LEAF(mp) ? 0 : 1;
2618 cmp = mc->mc_dbx->md_cmp;
2620 /* Branch pages have no data, so if using integer keys,
2621 * alignment is guaranteed. Use faster mdb_cmp_int.
2623 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
2624 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
2631 nodekey.mv_size = mc->mc_db->md_pad;
2632 node = NODEPTR(mp, 0); /* fake */
2633 while (low <= high) {
2634 i = (low + high) >> 1;
2635 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
2636 rc = cmp(key, &nodekey);
2637 DPRINTF("found leaf index %u [%s], rc = %i",
2638 i, DKEY(&nodekey), rc);
2647 while (low <= high) {
2648 i = (low + high) >> 1;
2650 node = NODEPTR(mp, i);
2651 nodekey.mv_size = NODEKSZ(node);
2652 nodekey.mv_data = NODEKEY(node);
2654 rc = cmp(key, &nodekey);
2657 DPRINTF("found leaf index %u [%s], rc = %i",
2658 i, DKEY(&nodekey), rc);
2660 DPRINTF("found branch index %u [%s -> %zu], rc = %i",
2661 i, DKEY(&nodekey), NODEPGNO(node), rc);
2672 if (rc > 0) { /* Found entry is less than the key. */
2673 i++; /* Skip to get the smallest entry larger than key. */
2675 node = NODEPTR(mp, i);
2678 *exactp = (rc == 0);
2679 /* store the key index */
2680 mc->mc_ki[mc->mc_top] = i;
2682 /* There is no entry larger or equal to the key. */
2685 /* nodeptr is fake for LEAF2 */
2689 /** Pop a page off the top of the cursor's stack. */
2691 mdb_cursor_pop(MDB_cursor *mc)
2696 top = mc->mc_pg[mc->mc_top];
2701 DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
2702 mc->mc_dbi, (void *) mc);
2706 /** Push a page onto the top of the cursor's stack. */
2708 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
2710 DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
2711 mc->mc_dbi, (void *) mc);
2713 if (mc->mc_snum >= CURSOR_STACK) {
2714 assert(mc->mc_snum < CURSOR_STACK);
2718 mc->mc_top = mc->mc_snum++;
2719 mc->mc_pg[mc->mc_top] = mp;
2720 mc->mc_ki[mc->mc_top] = 0;
2725 /** Find the address of the page corresponding to a given page number.
2726 * @param[in] txn the transaction for this access.
2727 * @param[in] pgno the page number for the page to retrieve.
2728 * @param[out] ret address of a pointer where the page's address will be stored.
2729 * @return 0 on success, non-zero on failure.
2732 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
2736 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
2738 x = mdb_mid2l_search(txn->mt_u.dirty_list, pgno);
2739 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
2740 p = txn->mt_u.dirty_list[x].mptr;
2744 if (pgno <= txn->mt_env->me_metas[txn->mt_toggle]->mm_last_pg)
2745 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
2749 DPRINTF("page %zu not found", pgno);
2752 return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
2755 /** Search for the page a given key should be in.
2756 * Pushes parent pages on the cursor stack. This function continues a
2757 * search on a cursor that has already been initialized. (Usually by
2758 * #mdb_page_search() but also by #mdb_node_move().)
2759 * @param[in,out] mc the cursor for this operation.
2760 * @param[in] key the key to search for. If NULL, search for the lowest
2761 * page. (This is used by #mdb_cursor_first().)
2762 * @param[in] modify If true, visited pages are updated with new page numbers.
2763 * @return 0 on success, non-zero on failure.
2766 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
2768 MDB_page *mp = mc->mc_pg[mc->mc_top];
2773 while (IS_BRANCH(mp)) {
2777 DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
2778 assert(NUMKEYS(mp) > 1);
2779 DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
2781 if (key == NULL) /* Initialize cursor to first page. */
2783 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
2784 /* cursor to last page */
2788 node = mdb_node_search(mc, key, &exact);
2790 i = NUMKEYS(mp) - 1;
2792 i = mc->mc_ki[mc->mc_top];
2801 DPRINTF("following index %u for key [%s]",
2803 assert(i < NUMKEYS(mp));
2804 node = NODEPTR(mp, i);
2806 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp)))
2809 mc->mc_ki[mc->mc_top] = i;
2810 if ((rc = mdb_cursor_push(mc, mp)))
2814 if ((rc = mdb_page_touch(mc)) != 0)
2816 mp = mc->mc_pg[mc->mc_top];
2821 DPRINTF("internal error, index points to a %02X page!?",
2823 return MDB_CORRUPTED;
2826 DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
2827 key ? DKEY(key) : NULL);
2832 /** Search for the page a given key should be in.
2833 * Pushes parent pages on the cursor stack. This function just sets up
2834 * the search; it finds the root page for \b mc's database and sets this
2835 * as the root of the cursor's stack. Then #mdb_page_search_root() is
2836 * called to complete the search.
2837 * @param[in,out] mc the cursor for this operation.
2838 * @param[in] key the key to search for. If NULL, search for the lowest
2839 * page. (This is used by #mdb_cursor_first().)
2840 * @param[in] modify If true, visited pages are updated with new page numbers.
2841 * @return 0 on success, non-zero on failure.
2844 mdb_page_search(MDB_cursor *mc, MDB_val *key, int modify)
2849 /* Make sure the txn is still viable, then find the root from
2850 * the txn's db table.
2852 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
2853 DPUTS("transaction has failed, must abort");
2856 root = mc->mc_db->md_root;
2858 if (root == P_INVALID) { /* Tree is empty. */
2859 DPUTS("tree is empty");
2860 return MDB_NOTFOUND;
2863 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0])))
2869 DPRINTF("db %u root page %zu has flags 0x%X",
2870 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
2872 /* For sub-databases, update main root first */
2873 if (mc->mc_dbi > MAIN_DBI) {
2874 if ((*mc->mc_dbflag & DB_STALE) ||
2875 (modify && !(*mc->mc_dbflag & DB_DIRTY))) {
2877 unsigned char dbflag = 0;
2878 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
2879 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, modify);
2882 if (*mc->mc_dbflag & DB_STALE) {
2885 MDB_node *leaf = mdb_node_search(&mc2,
2886 &mc->mc_dbx->md_name, &exact);
2888 return MDB_NOTFOUND;
2889 mdb_node_read(mc->mc_txn, leaf, &data);
2890 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
2894 *mc->mc_dbflag = dbflag;
2898 if (!F_ISSET(mc->mc_pg[0]->mp_flags, P_DIRTY)) {
2899 if ((rc = mdb_page_touch(mc)))
2901 mc->mc_db->md_root = mc->mc_pg[0]->mp_pgno;
2905 return mdb_page_search_root(mc, key, modify);
2908 /** Return the data associated with a given node.
2909 * @param[in] txn The transaction for this operation.
2910 * @param[in] leaf The node being read.
2911 * @param[out] data Updated to point to the node's data.
2912 * @return 0 on success, non-zero on failure.
2915 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
2917 MDB_page *omp; /* overflow page */
2921 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
2922 data->mv_size = NODEDSZ(leaf);
2923 data->mv_data = NODEDATA(leaf);
2927 /* Read overflow data.
2929 data->mv_size = NODEDSZ(leaf);
2930 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
2931 if ((rc = mdb_page_get(txn, pgno, &omp))) {
2932 DPRINTF("read overflow page %zu failed", pgno);
2935 data->mv_data = METADATA(omp);
2941 mdb_get(MDB_txn *txn, MDB_dbi dbi,
2942 MDB_val *key, MDB_val *data)
2951 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
2953 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
2956 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2960 mdb_cursor_init(&mc, txn, dbi, &mx);
2961 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
2964 /** Find a sibling for a page.
2965 * Replaces the page at the top of the cursor's stack with the
2966 * specified sibling, if one exists.
2967 * @param[in] mc The cursor for this operation.
2968 * @param[in] move_right Non-zero if the right sibling is requested,
2969 * otherwise the left sibling.
2970 * @return 0 on success, non-zero on failure.
2973 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
2979 if (mc->mc_snum < 2) {
2980 return MDB_NOTFOUND; /* root has no siblings */
2984 DPRINTF("parent page is page %zu, index %u",
2985 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]);
2987 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
2988 : (mc->mc_ki[mc->mc_top] == 0)) {
2989 DPRINTF("no more keys left, moving to %s sibling",
2990 move_right ? "right" : "left");
2991 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS)
2995 mc->mc_ki[mc->mc_top]++;
2997 mc->mc_ki[mc->mc_top]--;
2998 DPRINTF("just moving to %s index key %u",
2999 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]);
3001 assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
3003 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3004 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp)))
3007 mdb_cursor_push(mc, mp);
3012 /** Move the cursor to the next data item. */
3014 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3020 if (mc->mc_flags & C_EOF) {
3021 return MDB_NOTFOUND;
3024 assert(mc->mc_flags & C_INITIALIZED);
3026 mp = mc->mc_pg[mc->mc_top];
3028 if (mc->mc_db->md_flags & MDB_DUPSORT) {
3029 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3030 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3031 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
3032 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
3033 if (op != MDB_NEXT || rc == MDB_SUCCESS)
3037 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3038 if (op == MDB_NEXT_DUP)
3039 return MDB_NOTFOUND;
3043 DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3045 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
3046 DPUTS("=====> move to next sibling page");
3047 if (mdb_cursor_sibling(mc, 1) != MDB_SUCCESS) {
3048 mc->mc_flags |= C_EOF;
3049 mc->mc_flags &= ~C_INITIALIZED;
3050 return MDB_NOTFOUND;
3052 mp = mc->mc_pg[mc->mc_top];
3053 DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3055 mc->mc_ki[mc->mc_top]++;
3057 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3058 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3061 key->mv_size = mc->mc_db->md_pad;
3062 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3066 assert(IS_LEAF(mp));
3067 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3069 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3070 mdb_xcursor_init1(mc, leaf);
3073 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3076 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3077 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3078 if (rc != MDB_SUCCESS)
3083 MDB_SET_KEY(leaf, key);
3087 /** Move the cursor to the previous data item. */
3089 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3095 assert(mc->mc_flags & C_INITIALIZED);
3097 mp = mc->mc_pg[mc->mc_top];
3099 if (mc->mc_db->md_flags & MDB_DUPSORT) {
3100 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3101 if (op == MDB_PREV || op == MDB_PREV_DUP) {
3102 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3103 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
3104 if (op != MDB_PREV || rc == MDB_SUCCESS)
3107 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3108 if (op == MDB_PREV_DUP)
3109 return MDB_NOTFOUND;
3114 DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3116 if (mc->mc_ki[mc->mc_top] == 0) {
3117 DPUTS("=====> move to prev sibling page");
3118 if (mdb_cursor_sibling(mc, 0) != MDB_SUCCESS) {
3119 mc->mc_flags &= ~C_INITIALIZED;
3120 return MDB_NOTFOUND;
3122 mp = mc->mc_pg[mc->mc_top];
3123 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
3124 DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3126 mc->mc_ki[mc->mc_top]--;
3128 mc->mc_flags &= ~C_EOF;
3130 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3131 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3134 key->mv_size = mc->mc_db->md_pad;
3135 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3139 assert(IS_LEAF(mp));
3140 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3142 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3143 mdb_xcursor_init1(mc, leaf);
3146 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3149 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3150 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3151 if (rc != MDB_SUCCESS)
3156 MDB_SET_KEY(leaf, key);
3160 /** Set the cursor on a specific data item. */
3162 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3163 MDB_cursor_op op, int *exactp)
3172 assert(key->mv_size > 0);
3174 /* See if we're already on the right page */
3175 if (mc->mc_flags & C_INITIALIZED) {
3178 mp = mc->mc_pg[mc->mc_top];
3180 mc->mc_ki[mc->mc_top] = 0;
3181 return MDB_NOTFOUND;
3183 if (mp->mp_flags & P_LEAF2) {
3184 nodekey.mv_size = mc->mc_db->md_pad;
3185 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
3187 leaf = NODEPTR(mp, 0);
3188 MDB_SET_KEY(leaf, &nodekey);
3190 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3192 /* Probably happens rarely, but first node on the page
3193 * was the one we wanted.
3195 mc->mc_ki[mc->mc_top] = 0;
3196 leaf = NODEPTR(mp, 0);
3203 unsigned int nkeys = NUMKEYS(mp);
3205 if (mp->mp_flags & P_LEAF2) {
3206 nodekey.mv_data = LEAF2KEY(mp,
3207 nkeys-1, nodekey.mv_size);
3209 leaf = NODEPTR(mp, nkeys-1);
3210 MDB_SET_KEY(leaf, &nodekey);
3212 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3214 /* last node was the one we wanted */
3215 mc->mc_ki[mc->mc_top] = nkeys-1;
3216 leaf = NODEPTR(mp, nkeys-1);
3222 /* This is definitely the right page, skip search_page */
3227 /* If any parents have right-sibs, search.
3228 * Otherwise, there's nothing further.
3230 for (i=0; i<mc->mc_top; i++)
3232 NUMKEYS(mc->mc_pg[i])-1)
3234 if (i == mc->mc_top) {
3235 /* There are no other pages */
3236 mc->mc_ki[mc->mc_top] = nkeys;
3237 return MDB_NOTFOUND;
3241 /* There are no other pages */
3242 mc->mc_ki[mc->mc_top] = 0;
3243 return MDB_NOTFOUND;
3247 rc = mdb_page_search(mc, key, 0);
3248 if (rc != MDB_SUCCESS)
3251 mp = mc->mc_pg[mc->mc_top];
3252 assert(IS_LEAF(mp));
3255 leaf = mdb_node_search(mc, key, exactp);
3256 if (exactp != NULL && !*exactp) {
3257 /* MDB_SET specified and not an exact match. */
3258 return MDB_NOTFOUND;
3262 DPUTS("===> inexact leaf not found, goto sibling");
3263 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
3264 return rc; /* no entries matched */
3265 mp = mc->mc_pg[mc->mc_top];
3266 assert(IS_LEAF(mp));
3267 leaf = NODEPTR(mp, 0);
3271 mc->mc_flags |= C_INITIALIZED;
3272 mc->mc_flags &= ~C_EOF;
3275 key->mv_size = mc->mc_db->md_pad;
3276 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3280 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3281 mdb_xcursor_init1(mc, leaf);
3284 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3285 if (op == MDB_SET || op == MDB_SET_RANGE) {
3286 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3289 if (op == MDB_GET_BOTH) {
3295 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
3296 if (rc != MDB_SUCCESS)
3299 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
3301 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
3303 rc = mc->mc_dbx->md_dcmp(data, &d2);
3305 if (op == MDB_GET_BOTH || rc > 0)
3306 return MDB_NOTFOUND;
3311 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3312 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3317 /* The key already matches in all other cases */
3318 if (op == MDB_SET_RANGE)
3319 MDB_SET_KEY(leaf, key);
3320 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
3325 /** Move the cursor to the first item in the database. */
3327 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3332 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3333 rc = mdb_page_search(mc, NULL, 0);
3334 if (rc != MDB_SUCCESS)
3337 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3339 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
3340 mc->mc_flags |= C_INITIALIZED;
3341 mc->mc_flags &= ~C_EOF;
3343 mc->mc_ki[mc->mc_top] = 0;
3345 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3346 key->mv_size = mc->mc_db->md_pad;
3347 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
3352 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3353 mdb_xcursor_init1(mc, leaf);
3354 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3359 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3360 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3364 MDB_SET_KEY(leaf, key);
3368 /** Move the cursor to the last item in the database. */
3370 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3376 lkey.mv_size = MAXKEYSIZE+1;
3377 lkey.mv_data = NULL;
3379 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3380 rc = mdb_page_search(mc, &lkey, 0);
3381 if (rc != MDB_SUCCESS)
3384 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3386 leaf = NODEPTR(mc->mc_pg[mc->mc_top], NUMKEYS(mc->mc_pg[mc->mc_top])-1);
3387 mc->mc_flags |= C_INITIALIZED;
3388 mc->mc_flags &= ~C_EOF;
3390 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
3392 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3393 key->mv_size = mc->mc_db->md_pad;
3394 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
3399 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3400 mdb_xcursor_init1(mc, leaf);
3401 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3406 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3407 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3412 MDB_SET_KEY(leaf, key);
3417 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3427 case MDB_GET_BOTH_RANGE:
3428 if (data == NULL || mc->mc_xcursor == NULL) {
3435 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3437 } else if (op == MDB_SET_RANGE)
3438 rc = mdb_cursor_set(mc, key, data, op, NULL);
3440 rc = mdb_cursor_set(mc, key, data, op, &exact);
3442 case MDB_GET_MULTIPLE:
3444 !(mc->mc_db->md_flags & MDB_DUPFIXED) ||
3445 !(mc->mc_flags & C_INITIALIZED)) {
3450 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
3451 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
3454 case MDB_NEXT_MULTIPLE:
3456 !(mc->mc_db->md_flags & MDB_DUPFIXED)) {
3460 if (!(mc->mc_flags & C_INITIALIZED))
3461 rc = mdb_cursor_first(mc, key, data);
3463 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
3464 if (rc == MDB_SUCCESS) {
3465 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
3468 mx = &mc->mc_xcursor->mx_cursor;
3469 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
3471 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
3472 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
3480 case MDB_NEXT_NODUP:
3481 if (!(mc->mc_flags & C_INITIALIZED))
3482 rc = mdb_cursor_first(mc, key, data);
3484 rc = mdb_cursor_next(mc, key, data, op);
3488 case MDB_PREV_NODUP:
3489 if (!(mc->mc_flags & C_INITIALIZED) || (mc->mc_flags & C_EOF))
3490 rc = mdb_cursor_last(mc, key, data);
3492 rc = mdb_cursor_prev(mc, key, data, op);
3495 rc = mdb_cursor_first(mc, key, data);
3499 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
3500 !(mc->mc_flags & C_INITIALIZED) ||
3501 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3505 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3508 rc = mdb_cursor_last(mc, key, data);
3512 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
3513 !(mc->mc_flags & C_INITIALIZED) ||
3514 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3518 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3521 DPRINTF("unhandled/unimplemented cursor operation %u", op);
3529 /** Touch all the pages in the cursor stack.
3530 * Makes sure all the pages are writable, before attempting a write operation.
3531 * @param[in] mc The cursor to operate on.
3534 mdb_cursor_touch(MDB_cursor *mc)
3538 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
3540 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
3541 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 1);
3544 *mc->mc_dbflag = DB_DIRTY;
3546 for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
3547 if (!F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY)) {
3548 rc = mdb_page_touch(mc);
3552 mc->mc_db->md_root =
3553 mc->mc_pg[mc->mc_top]->mp_pgno;
3557 mc->mc_top = mc->mc_snum-1;
3562 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3565 MDB_node *leaf = NULL;
3566 MDB_val xdata, *rdata, dkey;
3572 char pbuf[PAGESIZE];
3573 char dbuf[MAXKEYSIZE+1];
3576 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
3579 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
3580 mc->mc_dbi, DKEY(key), key->mv_size, data->mv_size);
3584 if (flags == MDB_CURRENT) {
3585 if (!(mc->mc_flags & C_INITIALIZED))
3588 } else if (mc->mc_db->md_root == P_INVALID) {
3590 /* new database, write a root leaf page */
3591 DPUTS("allocating new root leaf page");
3592 if ((np = mdb_page_new(mc, P_LEAF, 1)) == NULL) {
3596 mdb_cursor_push(mc, np);
3597 mc->mc_db->md_root = np->mp_pgno;
3598 mc->mc_db->md_depth++;
3599 *mc->mc_dbflag = DB_DIRTY;
3600 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
3602 np->mp_flags |= P_LEAF2;
3603 mc->mc_flags |= C_INITIALIZED;
3609 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
3610 if (flags == MDB_NOOVERWRITE && rc == 0) {
3611 DPRINTF("duplicate key [%s]", DKEY(key));
3613 return MDB_KEYEXIST;
3615 if (rc && rc != MDB_NOTFOUND)
3619 /* Cursor is positioned, now make sure all pages are writable */
3620 rc2 = mdb_cursor_touch(mc);
3625 /* The key already exists */
3626 if (rc == MDB_SUCCESS) {
3627 /* there's only a key anyway, so this is a no-op */
3628 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3629 unsigned int ksize = mc->mc_db->md_pad;
3630 if (key->mv_size != ksize)
3632 if (flags == MDB_CURRENT) {
3633 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
3634 memcpy(ptr, key->mv_data, ksize);
3639 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3642 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
3643 /* Was a single item before, must convert now */
3644 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3645 /* Just overwrite the current item */
3646 if (flags == MDB_CURRENT)
3649 /* create a fake page for the dup items */
3650 dkey.mv_size = NODEDSZ(leaf);
3651 dkey.mv_data = NODEDATA(leaf);
3652 /* data matches, ignore it */
3653 if (!mc->mc_dbx->md_dcmp(data, &dkey))
3654 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
3655 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
3656 dkey.mv_data = dbuf;
3657 fp = (MDB_page *)pbuf;
3658 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
3659 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
3660 fp->mp_lower = PAGEHDRSZ;
3661 fp->mp_upper = PAGEHDRSZ + dkey.mv_size + data->mv_size;
3662 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
3663 fp->mp_flags |= P_LEAF2;
3664 fp->mp_pad = data->mv_size;
3666 fp->mp_upper += 2 * sizeof(indx_t) + 2 * NODESIZE +
3667 (dkey.mv_size & 1) + (data->mv_size & 1);
3669 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
3672 xdata.mv_size = fp->mp_upper;
3673 xdata.mv_data = pbuf;
3677 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
3678 /* See if we need to convert from fake page to subDB */
3680 unsigned int offset;
3683 fp = NODEDATA(leaf);
3684 if (flags == MDB_CURRENT) {
3685 fp->mp_flags |= P_DIRTY;
3686 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
3687 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
3691 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
3692 offset = fp->mp_pad;
3694 offset = NODESIZE + sizeof(indx_t) + data->mv_size;
3696 offset += offset & 1;
3697 if (NODEDSZ(leaf) + offset >= mc->mc_txn->mt_env->me_psize / MDB_MINKEYS) {
3698 /* yes, convert it */
3700 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
3701 dummy.md_pad = fp->mp_pad;
3702 dummy.md_flags = MDB_DUPFIXED;
3703 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
3704 dummy.md_flags |= MDB_INTEGERKEY;
3707 dummy.md_branch_pages = 0;
3708 dummy.md_leaf_pages = 1;
3709 dummy.md_overflow_pages = 0;
3710 dummy.md_entries = NUMKEYS(fp);
3712 xdata.mv_size = sizeof(MDB_db);
3713 xdata.mv_data = &dummy;
3714 mp = mdb_page_alloc(mc, 1);
3717 offset = mc->mc_txn->mt_env->me_psize - NODEDSZ(leaf);
3718 flags |= F_DUPDATA|F_SUBDATA;
3719 dummy.md_root = mp->mp_pgno;
3721 /* no, just grow it */
3723 xdata.mv_size = NODEDSZ(leaf) + offset;
3724 xdata.mv_data = pbuf;
3725 mp = (MDB_page *)pbuf;
3726 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
3729 mp->mp_flags = fp->mp_flags | P_DIRTY;
3730 mp->mp_pad = fp->mp_pad;
3731 mp->mp_lower = fp->mp_lower;
3732 mp->mp_upper = fp->mp_upper + offset;
3734 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
3736 nsize = NODEDSZ(leaf) - fp->mp_upper;
3737 memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper, nsize);
3738 for (i=0; i<NUMKEYS(fp); i++)
3739 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
3741 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
3745 /* data is on sub-DB, just store it */
3746 flags |= F_DUPDATA|F_SUBDATA;
3750 /* same size, just replace it */
3751 if (!F_ISSET(leaf->mn_flags, F_BIGDATA) &&
3752 NODEDSZ(leaf) == data->mv_size) {
3753 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
3756 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
3758 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
3764 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
3765 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
3766 rc = mdb_page_split(mc, key, rdata, P_INVALID);
3768 /* There is room already in this leaf page. */
3769 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, 0);
3772 if (rc != MDB_SUCCESS)
3773 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
3775 /* Remember if we just added a subdatabase */
3776 if (flags & (F_SUBDATA|F_DUPDATA)) {
3777 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3778 leaf->mn_flags |= (flags & (F_SUBDATA|F_DUPDATA));
3781 /* Now store the actual data in the child DB. Note that we're
3782 * storing the user data in the keys field, so there are strict
3783 * size limits on dupdata. The actual data fields of the child
3784 * DB are all zero size.
3792 if (flags & MDB_CURRENT) {
3793 xflags = MDB_CURRENT;
3795 mdb_xcursor_init1(mc, leaf);
3796 xflags = (flags & MDB_NODUPDATA) ? MDB_NOOVERWRITE : 0;
3798 /* converted, write the original data first */
3800 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
3804 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
3805 if (flags & F_SUBDATA) {
3806 db = NODEDATA(leaf);
3807 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
3810 /* sub-writes might have failed so check rc again.
3811 * Don't increment count if we just replaced an existing item.
3813 if (!rc && !(flags & MDB_CURRENT))
3814 mc->mc_db->md_entries++;
3821 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
3826 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
3829 if (!mc->mc_flags & C_INITIALIZED)
3832 rc = mdb_cursor_touch(mc);
3836 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3838 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3839 if (flags != MDB_NODUPDATA) {
3840 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
3841 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
3843 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
3844 /* If sub-DB still has entries, we're done */
3845 if (mc->mc_xcursor->mx_db.md_root != P_INVALID) {
3846 if (leaf->mn_flags & F_SUBDATA) {
3847 /* update subDB info */
3848 MDB_db *db = NODEDATA(leaf);
3849 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
3851 /* shrink fake page */
3852 mdb_node_shrink(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3854 mc->mc_db->md_entries--;
3857 /* otherwise fall thru and delete the sub-DB */
3860 if (leaf->mn_flags & F_SUBDATA) {
3861 /* add all the child DB's pages to the free list */
3862 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
3863 if (rc == MDB_SUCCESS) {
3864 mc->mc_db->md_entries -=
3865 mc->mc_xcursor->mx_db.md_entries;
3870 return mdb_cursor_del0(mc, leaf);
3873 /** Allocate and initialize new pages for a database.
3874 * @param[in] mc a cursor on the database being added to.
3875 * @param[in] flags flags defining what type of page is being allocated.
3876 * @param[in] num the number of pages to allocate. This is usually 1,
3877 * unless allocating overflow pages for a large record.
3878 * @return Address of a page, or NULL on failure.
3881 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num)
3885 if ((np = mdb_page_alloc(mc, num)) == NULL)
3887 DPRINTF("allocated new mpage %zu, page size %u",
3888 np->mp_pgno, mc->mc_txn->mt_env->me_psize);
3889 np->mp_flags = flags | P_DIRTY;
3890 np->mp_lower = PAGEHDRSZ;
3891 np->mp_upper = mc->mc_txn->mt_env->me_psize;
3894 mc->mc_db->md_branch_pages++;
3895 else if (IS_LEAF(np))
3896 mc->mc_db->md_leaf_pages++;
3897 else if (IS_OVERFLOW(np)) {
3898 mc->mc_db->md_overflow_pages += num;
3905 /** Calculate the size of a leaf node.
3906 * The size depends on the environment's page size; if a data item
3907 * is too large it will be put onto an overflow page and the node
3908 * size will only include the key and not the data. Sizes are always
3909 * rounded up to an even number of bytes, to guarantee 2-byte alignment
3910 * of the #MDB_node headers.
3911 * @param[in] env The environment handle.
3912 * @param[in] key The key for the node.
3913 * @param[in] data The data for the node.
3914 * @return The number of bytes needed to store the node.
3917 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
3921 sz = LEAFSIZE(key, data);
3922 if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
3923 /* put on overflow page */
3924 sz -= data->mv_size - sizeof(pgno_t);
3928 return sz + sizeof(indx_t);
3931 /** Calculate the size of a branch node.
3932 * The size should depend on the environment's page size but since
3933 * we currently don't support spilling large keys onto overflow
3934 * pages, it's simply the size of the #MDB_node header plus the
3935 * size of the key. Sizes are always rounded up to an even number
3936 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
3937 * @param[in] env The environment handle.
3938 * @param[in] key The key for the node.
3939 * @return The number of bytes needed to store the node.
3942 mdb_branch_size(MDB_env *env, MDB_val *key)
3947 if (sz >= env->me_psize / MDB_MINKEYS) {
3948 /* put on overflow page */
3949 /* not implemented */
3950 /* sz -= key->size - sizeof(pgno_t); */
3953 return sz + sizeof(indx_t);
3956 /** Add a node to the page pointed to by the cursor.
3957 * @param[in] mc The cursor for this operation.
3958 * @param[in] indx The index on the page where the new node should be added.
3959 * @param[in] key The key for the new node.
3960 * @param[in] data The data for the new node, if any.
3961 * @param[in] pgno The page number, if adding a branch node.
3962 * @param[in] flags Flags for the node.
3963 * @return 0 on success, non-zero on failure. Possible errors are:
3965 * <li>ENOMEM - failed to allocate overflow pages for the node.
3966 * <li>ENOSPC - there is insufficient room in the page. This error
3967 * should never happen since all callers already calculate the
3968 * page's free space before calling this function.
3972 mdb_node_add(MDB_cursor *mc, indx_t indx,
3973 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags)
3976 size_t node_size = NODESIZE;
3979 MDB_page *mp = mc->mc_pg[mc->mc_top];
3980 MDB_page *ofp = NULL; /* overflow page */
3983 assert(mp->mp_upper >= mp->mp_lower);
3985 DPRINTF("add to %s %spage %zu index %i, data size %zu key size %zu [%s]",
3986 IS_LEAF(mp) ? "leaf" : "branch",
3987 IS_SUBP(mp) ? "sub-" : "",
3988 mp->mp_pgno, indx, data ? data->mv_size : 0,
3989 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
3992 /* Move higher keys up one slot. */
3993 int ksize = mc->mc_db->md_pad, dif;
3994 char *ptr = LEAF2KEY(mp, indx, ksize);
3995 dif = NUMKEYS(mp) - indx;
3997 memmove(ptr+ksize, ptr, dif*ksize);
3998 /* insert new key */
3999 memcpy(ptr, key->mv_data, ksize);
4001 /* Just using these for counting */
4002 mp->mp_lower += sizeof(indx_t);
4003 mp->mp_upper -= ksize - sizeof(indx_t);
4008 node_size += key->mv_size;
4012 if (F_ISSET(flags, F_BIGDATA)) {
4013 /* Data already on overflow page. */
4014 node_size += sizeof(pgno_t);
4015 } else if (data->mv_size >= mc->mc_txn->mt_env->me_psize / MDB_MINKEYS) {
4016 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
4017 /* Put data on overflow page. */
4018 DPRINTF("data size is %zu, put on overflow page",
4020 node_size += sizeof(pgno_t);
4021 if ((ofp = mdb_page_new(mc, P_OVERFLOW, ovpages)) == NULL)
4023 DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
4026 node_size += data->mv_size;
4029 node_size += node_size & 1;
4031 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
4032 DPRINTF("not enough room in page %zu, got %u ptrs",
4033 mp->mp_pgno, NUMKEYS(mp));
4034 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
4035 mp->mp_upper - mp->mp_lower);
4036 DPRINTF("node size = %zu", node_size);
4040 /* Move higher pointers up one slot. */
4041 for (i = NUMKEYS(mp); i > indx; i--)
4042 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
4044 /* Adjust free space offsets. */
4045 ofs = mp->mp_upper - node_size;
4046 assert(ofs >= mp->mp_lower + sizeof(indx_t));
4047 mp->mp_ptrs[indx] = ofs;
4049 mp->mp_lower += sizeof(indx_t);
4051 /* Write the node data. */
4052 node = NODEPTR(mp, indx);
4053 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
4054 node->mn_flags = flags;
4056 SETDSZ(node,data->mv_size);
4061 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
4066 if (F_ISSET(flags, F_BIGDATA))
4067 memcpy(node->mn_data + key->mv_size, data->mv_data,
4070 memcpy(node->mn_data + key->mv_size, data->mv_data,
4073 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
4075 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
4082 /** Delete the specified node from a page.
4083 * @param[in] mp The page to operate on.
4084 * @param[in] indx The index of the node to delete.
4085 * @param[in] ksize The size of a node. Only used if the page is
4086 * part of a #MDB_DUPFIXED database.
4089 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
4092 indx_t i, j, numkeys, ptr;
4096 DPRINTF("delete node %u on %s page %zu", indx,
4097 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
4098 assert(indx < NUMKEYS(mp));
4101 int x = NUMKEYS(mp) - 1 - indx;
4102 base = LEAF2KEY(mp, indx, ksize);
4104 memmove(base, base + ksize, x * ksize);
4105 mp->mp_lower -= sizeof(indx_t);
4106 mp->mp_upper += ksize - sizeof(indx_t);
4110 node = NODEPTR(mp, indx);
4111 sz = NODESIZE + node->mn_ksize;
4113 if (F_ISSET(node->mn_flags, F_BIGDATA))
4114 sz += sizeof(pgno_t);
4116 sz += NODEDSZ(node);
4120 ptr = mp->mp_ptrs[indx];
4121 numkeys = NUMKEYS(mp);
4122 for (i = j = 0; i < numkeys; i++) {
4124 mp->mp_ptrs[j] = mp->mp_ptrs[i];
4125 if (mp->mp_ptrs[i] < ptr)
4126 mp->mp_ptrs[j] += sz;
4131 base = (char *)mp + mp->mp_upper;
4132 memmove(base + sz, base, ptr - mp->mp_upper);
4134 mp->mp_lower -= sizeof(indx_t);
4138 /** Compact the main page after deleting a node on a subpage.
4139 * @param[in] mp The main page to operate on.
4140 * @param[in] indx The index of the subpage on the main page.
4143 mdb_node_shrink(MDB_page *mp, indx_t indx)
4150 indx_t i, numkeys, ptr;
4152 node = NODEPTR(mp, indx);
4153 sp = (MDB_page *)NODEDATA(node);
4154 osize = NODEDSZ(node);
4156 delta = sp->mp_upper - sp->mp_lower;
4157 SETDSZ(node, osize - delta);
4158 xp = (MDB_page *)((char *)sp + delta);
4160 /* shift subpage upward */
4162 nsize = NUMKEYS(sp) * sp->mp_pad;
4163 memmove(METADATA(xp), METADATA(sp), nsize);
4166 nsize = osize - sp->mp_upper;
4167 numkeys = NUMKEYS(sp);
4168 for (i=numkeys-1; i>=0; i--)
4169 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
4171 xp->mp_upper = sp->mp_lower;
4172 xp->mp_lower = sp->mp_lower;
4173 xp->mp_flags = sp->mp_flags;
4174 xp->mp_pad = sp->mp_pad;
4175 xp->mp_pgno = mp->mp_pgno;
4177 /* shift lower nodes upward */
4178 ptr = mp->mp_ptrs[indx];
4179 numkeys = NUMKEYS(mp);
4180 for (i = 0; i < numkeys; i++) {
4181 if (mp->mp_ptrs[i] <= ptr)
4182 mp->mp_ptrs[i] += delta;
4185 base = (char *)mp + mp->mp_upper;
4186 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
4187 mp->mp_upper += delta;
4190 /** Initial setup of a sorted-dups cursor.
4191 * Sorted duplicates are implemented as a sub-database for the given key.
4192 * The duplicate data items are actually keys of the sub-database.
4193 * Operations on the duplicate data items are performed using a sub-cursor
4194 * initialized when the sub-database is first accessed. This function does
4195 * the preliminary setup of the sub-cursor, filling in the fields that
4196 * depend only on the parent DB.
4197 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4200 mdb_xcursor_init0(MDB_cursor *mc)
4202 MDB_xcursor *mx = mc->mc_xcursor;
4204 mx->mx_cursor.mc_xcursor = NULL;
4205 mx->mx_cursor.mc_txn = mc->mc_txn;
4206 mx->mx_cursor.mc_db = &mx->mx_db;
4207 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
4208 mx->mx_cursor.mc_dbi = mc->mc_dbi+1;
4209 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
4210 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
4211 mx->mx_dbx.md_dcmp = NULL;
4212 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
4215 /** Final setup of a sorted-dups cursor.
4216 * Sets up the fields that depend on the data from the main cursor.
4217 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4218 * @param[in] node The data containing the #MDB_db record for the
4219 * sorted-dup database.
4222 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
4224 MDB_xcursor *mx = mc->mc_xcursor;
4226 if (node->mn_flags & F_SUBDATA) {
4227 MDB_db *db = NODEDATA(node);
4229 mx->mx_cursor.mc_snum = 0;
4230 mx->mx_cursor.mc_flags = 0;
4232 MDB_page *fp = NODEDATA(node);
4233 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
4234 mx->mx_db.md_flags = 0;
4235 mx->mx_db.md_depth = 1;
4236 mx->mx_db.md_branch_pages = 0;
4237 mx->mx_db.md_leaf_pages = 1;
4238 mx->mx_db.md_overflow_pages = 0;
4239 mx->mx_db.md_entries = NUMKEYS(fp);
4240 mx->mx_db.md_root = fp->mp_pgno;
4241 mx->mx_cursor.mc_snum = 1;
4242 mx->mx_cursor.mc_flags = C_INITIALIZED;
4243 mx->mx_cursor.mc_top = 0;
4244 mx->mx_cursor.mc_pg[0] = fp;
4245 mx->mx_cursor.mc_ki[0] = 0;
4246 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4247 mx->mx_db.md_flags = MDB_DUPFIXED;
4248 mx->mx_db.md_pad = fp->mp_pad;
4249 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
4250 mx->mx_db.md_flags |= MDB_INTEGERKEY;
4253 DPRINTF("Sub-db %u for db %u root page %zu", mx->mx_cursor.mc_dbi, mc->mc_dbi,
4255 mx->mx_dbflag = (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY)) ?
4257 mx->mx_dbx.md_name.mv_data = NODEKEY(node);
4258 mx->mx_dbx.md_name.mv_size = node->mn_ksize;
4259 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
4260 mx->mx_dbx.md_cmp = mdb_cmp_long;
4263 /** Initialize a cursor for a given transaction and database. */
4265 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
4269 mc->mc_db = &txn->mt_dbs[dbi];
4270 mc->mc_dbx = &txn->mt_dbxs[dbi];
4271 mc->mc_dbflag = &txn->mt_dbflags[dbi];
4274 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4276 mc->mc_xcursor = mx;
4277 mdb_xcursor_init0(mc);
4279 mc->mc_xcursor = NULL;
4284 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
4287 MDB_xcursor *mx = NULL;
4288 size_t size = sizeof(MDB_cursor);
4290 if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
4293 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
4294 size += sizeof(MDB_xcursor);
4296 if ((mc = malloc(size)) != NULL) {
4297 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4298 mx = (MDB_xcursor *)(mc + 1);
4300 mdb_cursor_init(mc, txn, dbi, mx);
4310 /* Return the count of duplicate data items for the current key */
4312 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
4316 if (mc == NULL || countp == NULL)
4319 if (!(mc->mc_db->md_flags & MDB_DUPSORT))
4322 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4323 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4326 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
4329 *countp = mc->mc_xcursor->mx_db.md_entries;
4335 mdb_cursor_close(MDB_cursor *mc)
4342 /** Replace the key for a node with a new key.
4343 * @param[in] mp The page containing the node to operate on.
4344 * @param[in] indx The index of the node to operate on.
4345 * @param[in] key The new key to use.
4346 * @return 0 on success, non-zero on failure.
4349 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
4351 indx_t ptr, i, numkeys;
4358 node = NODEPTR(mp, indx);
4359 ptr = mp->mp_ptrs[indx];
4360 DPRINTF("update key %u (ofs %u) [%.*s] to [%s] on page %zu",
4362 (int)node->mn_ksize, (char *)NODEKEY(node),
4366 delta = key->mv_size - node->mn_ksize;
4368 if (delta > 0 && SIZELEFT(mp) < delta) {
4369 DPRINTF("OUCH! Not enough room, delta = %d", delta);
4373 numkeys = NUMKEYS(mp);
4374 for (i = 0; i < numkeys; i++) {
4375 if (mp->mp_ptrs[i] <= ptr)
4376 mp->mp_ptrs[i] -= delta;
4379 base = (char *)mp + mp->mp_upper;
4380 len = ptr - mp->mp_upper + NODESIZE;
4381 memmove(base - delta, base, len);
4382 mp->mp_upper -= delta;
4384 node = NODEPTR(mp, indx);
4385 node->mn_ksize = key->mv_size;
4388 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
4393 /** Move a node from csrc to cdst.
4396 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
4403 /* Mark src and dst as dirty. */
4404 if ((rc = mdb_page_touch(csrc)) ||
4405 (rc = mdb_page_touch(cdst)))
4408 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4409 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
4410 key.mv_size = csrc->mc_db->md_pad;
4411 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
4413 data.mv_data = NULL;
4415 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
4416 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
4417 unsigned int snum = csrc->mc_snum;
4419 /* must find the lowest key below src */
4420 mdb_page_search_root(csrc, NULL, 0);
4421 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
4422 key.mv_size = NODEKSZ(s2);
4423 key.mv_data = NODEKEY(s2);
4424 csrc->mc_snum = snum--;
4425 csrc->mc_top = snum;
4427 key.mv_size = NODEKSZ(srcnode);
4428 key.mv_data = NODEKEY(srcnode);
4430 data.mv_size = NODEDSZ(srcnode);
4431 data.mv_data = NODEDATA(srcnode);
4433 DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
4434 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
4435 csrc->mc_ki[csrc->mc_top],
4437 csrc->mc_pg[csrc->mc_top]->mp_pgno,
4438 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
4440 /* Add the node to the destination page.
4442 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, NODEPGNO(srcnode),
4444 if (rc != MDB_SUCCESS)
4447 /* Delete the node from the source page.
4449 mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
4451 /* Update the parent separators.
4453 if (csrc->mc_ki[csrc->mc_top] == 0) {
4454 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
4455 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4456 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
4458 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
4459 key.mv_size = NODEKSZ(srcnode);
4460 key.mv_data = NODEKEY(srcnode);
4462 DPRINTF("update separator for source page %zu to [%s]",
4463 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
4464 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1],
4465 &key)) != MDB_SUCCESS)
4468 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
4470 nullkey.mv_size = 0;
4471 assert(mdb_update_key(csrc->mc_pg[csrc->mc_top], 0, &nullkey) == MDB_SUCCESS);
4475 if (cdst->mc_ki[cdst->mc_top] == 0) {
4476 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
4477 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4478 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
4480 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
4481 key.mv_size = NODEKSZ(srcnode);
4482 key.mv_data = NODEKEY(srcnode);
4484 DPRINTF("update separator for destination page %zu to [%s]",
4485 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
4486 if ((rc = mdb_update_key(cdst->mc_pg[cdst->mc_top-1], cdst->mc_ki[cdst->mc_top-1],
4487 &key)) != MDB_SUCCESS)
4490 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
4492 nullkey.mv_size = 0;
4493 assert(mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &nullkey) == MDB_SUCCESS);
4500 /** Merge one page into another.
4501 * The nodes from the page pointed to by \b csrc will
4502 * be copied to the page pointed to by \b cdst and then
4503 * the \b csrc page will be freed.
4504 * @param[in] csrc Cursor pointing to the source page.
4505 * @param[in] cdst Cursor pointing to the destination page.
4508 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
4515 DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
4516 cdst->mc_pg[cdst->mc_top]->mp_pgno);
4518 assert(csrc->mc_snum > 1); /* can't merge root page */
4519 assert(cdst->mc_snum > 1);
4521 /* Mark dst as dirty. */
4522 if ((rc = mdb_page_touch(cdst)))
4525 /* Move all nodes from src to dst.
4527 j = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
4528 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4529 key.mv_size = csrc->mc_db->md_pad;
4530 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
4531 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
4532 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
4533 if (rc != MDB_SUCCESS)
4535 key.mv_data = (char *)key.mv_data + key.mv_size;
4538 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
4539 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
4541 key.mv_size = srcnode->mn_ksize;
4542 key.mv_data = NODEKEY(srcnode);
4543 data.mv_size = NODEDSZ(srcnode);
4544 data.mv_data = NODEDATA(srcnode);
4545 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
4546 if (rc != MDB_SUCCESS)
4551 DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
4552 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);
4554 /* Unlink the src page from parent and add to free list.
4556 mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
4557 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
4559 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], 0, &key)) != MDB_SUCCESS)
4563 mdb_midl_append(&csrc->mc_txn->mt_free_pgs, csrc->mc_pg[csrc->mc_top]->mp_pgno);
4564 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
4565 csrc->mc_db->md_leaf_pages--;
4567 csrc->mc_db->md_branch_pages--;
4568 mdb_cursor_pop(csrc);
4570 return mdb_rebalance(csrc);
4573 /** Copy the contents of a cursor.
4574 * @param[in] csrc The cursor to copy from.
4575 * @param[out] cdst The cursor to copy to.
4578 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
4582 cdst->mc_txn = csrc->mc_txn;
4583 cdst->mc_dbi = csrc->mc_dbi;
4584 cdst->mc_db = csrc->mc_db;
4585 cdst->mc_dbx = csrc->mc_dbx;
4586 cdst->mc_snum = csrc->mc_snum;
4587 cdst->mc_top = csrc->mc_top;
4588 cdst->mc_flags = csrc->mc_flags;
4590 for (i=0; i<csrc->mc_snum; i++) {
4591 cdst->mc_pg[i] = csrc->mc_pg[i];
4592 cdst->mc_ki[i] = csrc->mc_ki[i];
4596 /** Rebalance the tree after a delete operation.
4597 * @param[in] mc Cursor pointing to the page where rebalancing
4599 * @return 0 on success, non-zero on failure.
4602 mdb_rebalance(MDB_cursor *mc)
4609 DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
4610 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
4611 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);
4613 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD) {
4614 DPRINTF("no need to rebalance page %zu, above fill threshold",
4615 mc->mc_pg[mc->mc_top]->mp_pgno);
4619 if (mc->mc_snum < 2) {
4620 if (NUMKEYS(mc->mc_pg[mc->mc_top]) == 0) {
4621 DPUTS("tree is completely empty");
4622 mc->mc_db->md_root = P_INVALID;
4623 mc->mc_db->md_depth = 0;
4624 mc->mc_db->md_leaf_pages = 0;
4625 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mc->mc_pg[mc->mc_top]->mp_pgno);
4627 } else if (IS_BRANCH(mc->mc_pg[mc->mc_top]) && NUMKEYS(mc->mc_pg[mc->mc_top]) == 1) {
4628 DPUTS("collapsing root page!");
4629 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mc->mc_pg[mc->mc_top]->mp_pgno);
4630 mc->mc_db->md_root = NODEPGNO(NODEPTR(mc->mc_pg[mc->mc_top], 0));
4631 if ((rc = mdb_page_get(mc->mc_txn, mc->mc_db->md_root,
4632 &mc->mc_pg[mc->mc_top])))
4634 mc->mc_db->md_depth--;
4635 mc->mc_db->md_branch_pages--;
4637 DPUTS("root page doesn't need rebalancing");
4641 /* The parent (branch page) must have at least 2 pointers,
4642 * otherwise the tree is invalid.
4644 ptop = mc->mc_top-1;
4645 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
4647 /* Leaf page fill factor is below the threshold.
4648 * Try to move keys from left or right neighbor, or
4649 * merge with a neighbor page.
4654 mdb_cursor_copy(mc, &mn);
4655 mn.mc_xcursor = NULL;
4657 if (mc->mc_ki[ptop] == 0) {
4658 /* We're the leftmost leaf in our parent.
4660 DPUTS("reading right neighbor");
4662 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
4663 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
4665 mn.mc_ki[mn.mc_top] = 0;
4666 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
4668 /* There is at least one neighbor to the left.
4670 DPUTS("reading left neighbor");
4672 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
4673 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
4675 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
4676 mc->mc_ki[mc->mc_top] = 0;
4679 DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
4680 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);
4682 /* If the neighbor page is above threshold and has at least two
4683 * keys, move one key from it.
4685 * Otherwise we should try to merge them.
4687 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) >= 2)
4688 return mdb_node_move(&mn, mc);
4689 else { /* FIXME: if (has_enough_room()) */
4690 mc->mc_flags &= ~C_INITIALIZED;
4691 if (mc->mc_ki[ptop] == 0)
4692 return mdb_page_merge(&mn, mc);
4694 return mdb_page_merge(mc, &mn);
4698 /** Complete a delete operation started by #mdb_cursor_del(). */
4700 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
4704 /* add overflow pages to free list */
4705 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
4709 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
4710 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
4711 for (i=0; i<ovpages; i++) {
4712 DPRINTF("freed ov page %zu", pg);
4713 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
4717 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], mc->mc_db->md_pad);
4718 mc->mc_db->md_entries--;
4719 rc = mdb_rebalance(mc);
4720 if (rc != MDB_SUCCESS)
4721 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4727 mdb_del(MDB_txn *txn, MDB_dbi dbi,
4728 MDB_val *key, MDB_val *data)
4733 MDB_val rdata, *xdata;
4737 assert(key != NULL);
4739 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
4741 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4744 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
4748 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
4752 mdb_cursor_init(&mc, txn, dbi, &mx);
4763 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
4765 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
4769 /** Split a page and insert a new node.
4770 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
4771 * The cursor will be updated to point to the actual page and index where
4772 * the node got inserted after the split.
4773 * @param[in] newkey The key for the newly inserted node.
4774 * @param[in] newdata The data for the newly inserted node.
4775 * @param[in] newpgno The page number, if the new node is a branch node.
4776 * @return 0 on success, non-zero on failure.
4779 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno)
4782 int rc = MDB_SUCCESS, ins_new = 0;
4785 unsigned int i, j, split_indx, nkeys, pmax;
4787 MDB_val sepkey, rkey, rdata;
4789 MDB_page *mp, *rp, *pp;
4794 mp = mc->mc_pg[mc->mc_top];
4795 newindx = mc->mc_ki[mc->mc_top];
4797 DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
4798 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
4799 DKEY(newkey), mc->mc_ki[mc->mc_top]);
4801 if (mc->mc_snum < 2) {
4802 if ((pp = mdb_page_new(mc, P_BRANCH, 1)) == NULL)
4804 /* shift current top to make room for new parent */
4805 mc->mc_pg[1] = mc->mc_pg[0];
4806 mc->mc_ki[1] = mc->mc_ki[0];
4809 mc->mc_db->md_root = pp->mp_pgno;
4810 DPRINTF("root split! new root = %zu", pp->mp_pgno);
4811 mc->mc_db->md_depth++;
4813 /* Add left (implicit) pointer. */
4814 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
4815 /* undo the pre-push */
4816 mc->mc_pg[0] = mc->mc_pg[1];
4817 mc->mc_ki[0] = mc->mc_ki[1];
4818 mc->mc_db->md_root = mp->mp_pgno;
4819 mc->mc_db->md_depth--;
4826 ptop = mc->mc_top-1;
4827 DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
4830 /* Create a right sibling. */
4831 if ((rp = mdb_page_new(mc, mp->mp_flags, 1)) == NULL)
4833 mdb_cursor_copy(mc, &mn);
4834 mn.mc_pg[mn.mc_top] = rp;
4835 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
4836 DPRINTF("new right sibling: page %zu", rp->mp_pgno);
4838 nkeys = NUMKEYS(mp);
4839 split_indx = nkeys / 2 + 1;
4844 unsigned int lsize, rsize, ksize;
4845 /* Move half of the keys to the right sibling */
4847 x = mc->mc_ki[mc->mc_top] - split_indx;
4848 ksize = mc->mc_db->md_pad;
4849 split = LEAF2KEY(mp, split_indx, ksize);
4850 rsize = (nkeys - split_indx) * ksize;
4851 lsize = (nkeys - split_indx) * sizeof(indx_t);
4852 mp->mp_lower -= lsize;
4853 rp->mp_lower += lsize;
4854 mp->mp_upper += rsize - lsize;
4855 rp->mp_upper -= rsize - lsize;
4856 sepkey.mv_size = ksize;
4857 if (newindx == split_indx) {
4858 sepkey.mv_data = newkey->mv_data;
4860 sepkey.mv_data = split;
4863 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
4864 memcpy(rp->mp_ptrs, split, rsize);
4865 sepkey.mv_data = rp->mp_ptrs;
4866 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
4867 memcpy(ins, newkey->mv_data, ksize);
4868 mp->mp_lower += sizeof(indx_t);
4869 mp->mp_upper -= ksize - sizeof(indx_t);
4872 memcpy(rp->mp_ptrs, split, x * ksize);
4873 ins = LEAF2KEY(rp, x, ksize);
4874 memcpy(ins, newkey->mv_data, ksize);
4875 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
4876 rp->mp_lower += sizeof(indx_t);
4877 rp->mp_upper -= ksize - sizeof(indx_t);
4878 mc->mc_ki[mc->mc_top] = x;
4879 mc->mc_pg[mc->mc_top] = rp;
4884 /* For leaf pages, check the split point based on what
4885 * fits where, since otherwise add_node can fail.
4888 unsigned int psize, nsize;
4889 /* Maximum free space in an empty page */
4890 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
4891 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
4892 if (newindx < split_indx) {
4894 for (i=0; i<split_indx; i++) {
4895 node = NODEPTR(mp, i);
4896 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
4897 if (F_ISSET(node->mn_flags, F_BIGDATA))
4898 psize += sizeof(pgno_t);
4900 psize += NODEDSZ(node);
4909 for (i=nkeys-1; i>=split_indx; i--) {
4910 node = NODEPTR(mp, i);
4911 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
4912 if (F_ISSET(node->mn_flags, F_BIGDATA))
4913 psize += sizeof(pgno_t);
4915 psize += NODEDSZ(node);
4925 /* First find the separating key between the split pages.
4927 if (newindx == split_indx) {
4928 sepkey.mv_size = newkey->mv_size;
4929 sepkey.mv_data = newkey->mv_data;
4931 node = NODEPTR(mp, split_indx);
4932 sepkey.mv_size = node->mn_ksize;
4933 sepkey.mv_data = NODEKEY(node);
4937 DPRINTF("separator is [%s]", DKEY(&sepkey));
4939 /* Copy separator key to the parent.
4941 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
4944 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno);
4946 /* Right page might now have changed parent.
4947 * Check if left page also changed parent.
4949 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
4950 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
4951 mc->mc_pg[ptop] = mn.mc_pg[ptop];
4952 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
4956 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
4962 if (rc != MDB_SUCCESS) {
4966 /* Move half of the keys to the right sibling. */
4968 /* grab a page to hold a temporary copy */
4969 if (mc->mc_txn->mt_env->me_dpages) {
4970 copy = mc->mc_txn->mt_env->me_dpages;
4971 mc->mc_txn->mt_env->me_dpages = copy->mp_next;
4973 if ((copy = malloc(mc->mc_txn->mt_env->me_psize)) == NULL)
4977 copy->mp_pgno = mp->mp_pgno;
4978 copy->mp_flags = mp->mp_flags;
4979 copy->mp_lower = PAGEHDRSZ;
4980 copy->mp_upper = mc->mc_txn->mt_env->me_psize;
4981 mc->mc_pg[mc->mc_top] = copy;
4982 for (i = j = 0; i <= nkeys; j++) {
4983 if (i == split_indx) {
4984 /* Insert in right sibling. */
4985 /* Reset insert index for right sibling. */
4986 j = (i == newindx && ins_new);
4987 mc->mc_pg[mc->mc_top] = rp;
4990 if (i == newindx && !ins_new) {
4991 /* Insert the original entry that caused the split. */
4992 rkey.mv_data = newkey->mv_data;
4993 rkey.mv_size = newkey->mv_size;
4995 rdata.mv_data = newdata->mv_data;
4996 rdata.mv_size = newdata->mv_size;
5003 /* Update page and index for the new key. */
5004 mc->mc_ki[mc->mc_top] = j;
5005 } else if (i == nkeys) {
5008 node = NODEPTR(mp, i);
5009 rkey.mv_data = NODEKEY(node);
5010 rkey.mv_size = node->mn_ksize;
5012 rdata.mv_data = NODEDATA(node);
5013 rdata.mv_size = NODEDSZ(node);
5015 pgno = NODEPGNO(node);
5016 flags = node->mn_flags;
5021 if (!IS_LEAF(mp) && j == 0) {
5022 /* First branch index doesn't need key data. */
5026 rc = mdb_node_add(mc, j, &rkey, &rdata, pgno, flags);
5029 /* reset back to original page */
5030 if (newindx < split_indx)
5031 mc->mc_pg[mc->mc_top] = mp;
5033 nkeys = NUMKEYS(copy);
5034 for (i=0; i<nkeys; i++)
5035 mp->mp_ptrs[i] = copy->mp_ptrs[i];
5036 mp->mp_lower = copy->mp_lower;
5037 mp->mp_upper = copy->mp_upper;
5038 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
5039 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
5041 /* return tmp page to freelist */
5042 copy->mp_next = mc->mc_txn->mt_env->me_dpages;
5043 mc->mc_txn->mt_env->me_dpages = copy;
5048 mdb_put(MDB_txn *txn, MDB_dbi dbi,
5049 MDB_val *key, MDB_val *data, unsigned int flags)
5054 assert(key != NULL);
5055 assert(data != NULL);
5057 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5060 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
5064 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
5068 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA)) != flags)
5071 mdb_cursor_init(&mc, txn, dbi, &mx);
5072 return mdb_cursor_put(&mc, key, data, flags);
5076 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
5078 /** Only a subset of the @ref mdb_env flags can be changed
5079 * at runtime. Changing other flags requires closing the environment
5080 * and re-opening it with the new flags.
5082 #define CHANGEABLE (MDB_NOSYNC)
5083 if ((flag & CHANGEABLE) != flag)
5086 env->me_flags |= flag;
5088 env->me_flags &= ~flag;
5093 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
5098 *arg = env->me_flags;
5103 mdb_env_get_path(MDB_env *env, const char **arg)
5108 *arg = env->me_path;
5112 /** Common code for #mdb_stat() and #mdb_env_stat().
5113 * @param[in] env the environment to operate in.
5114 * @param[in] db the #MDB_db record containing the stats to return.
5115 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
5116 * @return 0, this function always succeeds.
5119 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
5121 arg->ms_psize = env->me_psize;
5122 arg->ms_depth = db->md_depth;
5123 arg->ms_branch_pages = db->md_branch_pages;
5124 arg->ms_leaf_pages = db->md_leaf_pages;
5125 arg->ms_overflow_pages = db->md_overflow_pages;
5126 arg->ms_entries = db->md_entries;
5131 mdb_env_stat(MDB_env *env, MDB_stat *arg)
5135 if (env == NULL || arg == NULL)
5138 mdb_env_read_meta(env, &toggle);
5140 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
5143 /** Set the default comparison functions for a database.
5144 * Called immediately after a database is opened to set the defaults.
5145 * The user can then override them with #mdb_set_compare() or
5146 * #mdb_set_dupsort().
5147 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
5148 * @param[in] dbi A database handle returned by #mdb_open()
5151 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
5153 if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEKEY)
5154 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memnr;
5155 else if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERKEY)
5156 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_cint;
5158 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memn;
5160 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
5161 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP) {
5162 if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED)
5163 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_int;
5165 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_cint;
5166 } else if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEDUP) {
5167 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memnr;
5169 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memn;
5172 txn->mt_dbxs[dbi].md_dcmp = NULL;
5176 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
5183 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
5184 mdb_default_cmp(txn, FREE_DBI);
5190 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
5191 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
5192 mdb_default_cmp(txn, MAIN_DBI);
5196 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
5197 mdb_default_cmp(txn, MAIN_DBI);
5200 /* Is the DB already open? */
5202 for (i=2; i<txn->mt_numdbs; i++) {
5203 if (len == txn->mt_dbxs[i].md_name.mv_size &&
5204 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
5210 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
5213 /* Find the DB info */
5215 key.mv_data = (void *)name;
5216 rc = mdb_get(txn, MAIN_DBI, &key, &data);
5218 /* Create if requested */
5219 if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
5222 data.mv_size = sizeof(MDB_db);
5223 data.mv_data = &dummy;
5224 memset(&dummy, 0, sizeof(dummy));
5225 dummy.md_root = P_INVALID;
5226 dummy.md_flags = flags & 0xffff;
5227 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
5228 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
5232 /* OK, got info, add to table */
5233 if (rc == MDB_SUCCESS) {
5234 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
5235 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
5236 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
5237 txn->mt_dbflags[txn->mt_numdbs] = dbflag;
5238 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
5239 *dbi = txn->mt_numdbs;
5240 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
5241 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
5242 mdb_default_cmp(txn, txn->mt_numdbs);
5249 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
5251 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
5254 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
5257 void mdb_close(MDB_env *env, MDB_dbi dbi)
5260 if (dbi <= MAIN_DBI || dbi >= env->me_numdbs)
5262 ptr = env->me_dbxs[dbi].md_name.mv_data;
5263 env->me_dbxs[dbi].md_name.mv_data = NULL;
5264 env->me_dbxs[dbi].md_name.mv_size = 0;
5268 /** Add all the DB's pages to the free list.
5269 * @param[in] mc Cursor on the DB to free.
5270 * @param[in] subs non-Zero to check for sub-DBs in this DB.
5271 * @return 0 on success, non-zero on failure.
5274 mdb_drop0(MDB_cursor *mc, int subs)
5278 rc = mdb_page_search(mc, NULL, 0);
5279 if (rc == MDB_SUCCESS) {
5284 /* LEAF2 pages have no nodes, cannot have sub-DBs */
5285 if (!subs || IS_LEAF2(mc->mc_pg[mc->mc_top]))
5288 mdb_cursor_copy(mc, &mx);
5289 while (mc->mc_snum > 0) {
5290 if (IS_LEAF(mc->mc_pg[mc->mc_top])) {
5291 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
5292 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
5293 if (ni->mn_flags & F_SUBDATA) {
5294 mdb_xcursor_init1(mc, ni);
5295 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
5301 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
5303 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
5306 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
5311 rc = mdb_cursor_sibling(mc, 1);
5313 /* no more siblings, go back to beginning
5314 * of previous level. (stack was already popped
5315 * by mdb_cursor_sibling)
5317 for (i=1; i<mc->mc_top; i++)
5318 mc->mc_pg[i] = mx.mc_pg[i];
5322 mdb_midl_append(&mc->mc_txn->mt_free_pgs,
5323 mc->mc_db->md_root);
5328 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
5333 if (!txn || !dbi || dbi >= txn->mt_numdbs)
5336 rc = mdb_cursor_open(txn, dbi, &mc);
5340 rc = mdb_drop0(mc, 1);
5342 mdb_cursor_close(mc);
5346 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
5348 mdb_close(txn->mt_env, dbi);
5350 mdb_cursor_close(mc);
5354 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
5356 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5359 txn->mt_dbxs[dbi].md_cmp = cmp;
5363 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
5365 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5368 txn->mt_dbxs[dbi].md_dcmp = cmp;
5372 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
5374 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5377 txn->mt_dbxs[dbi].md_rel = rel;
5381 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
5383 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5386 txn->mt_dbxs[dbi].md_relctx = ctx;