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.
694 * The \b md_dirty flag is not read-only, but only a write
695 * transaction can ever update it, and only write transactions
696 * need to worry about it.
698 typedef struct MDB_dbx {
699 MDB_val md_name; /**< name of the database */
700 MDB_cmp_func *md_cmp; /**< function for comparing keys */
701 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
702 MDB_rel_func *md_rel; /**< user relocate function */
703 void *md_relctx; /**< user-provided context for md_rel */
704 MDB_dbi md_parent; /**< parent DB of a sub-DB */
705 unsigned int md_dirty; /**< TRUE if DB was written in this txn */
708 /** A database transaction.
709 * Every operation requires a transaction handle.
712 pgno_t mt_next_pgno; /**< next unallocated page */
713 /** The ID of this transaction. IDs are integers incrementing from 1.
714 * Only committed write transactions increment the ID. If a transaction
715 * aborts, the ID may be re-used by the next writer.
718 MDB_env *mt_env; /**< the DB environment */
719 /** The list of pages that became unused during this transaction.
724 ID2L dirty_list; /**< modified pages */
725 MDB_reader *reader; /**< this thread's slot in the reader table */
727 /** Array of records for each DB known in the environment. */
729 /** Array of MDB_db records for each known DB */
731 /** Number of DB records in use. This number only ever increments;
732 * we don't decrement it when individual DB handles are closed.
736 /** @defgroup mdb_txn Transaction Flags
740 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
741 #define MDB_TXN_ERROR 0x02 /**< an error has occurred */
743 unsigned int mt_flags; /**< @ref mdb_txn */
744 /** Tracks which of the two meta pages was used at the start
745 * of this transaction.
747 unsigned int mt_toggle;
750 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
751 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
752 * raise this on a 64 bit machine.
754 #define CURSOR_STACK 32
758 /** Cursors are used for all DB operations */
760 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
761 struct MDB_xcursor *mc_xcursor;
762 /** The transaction that owns this cursor */
764 /** The database handle this cursor operates on */
766 /** The database record for this cursor */
768 /** The database auxiliary record for this cursor */
770 unsigned short mc_snum; /**< number of pushed pages */
771 unsigned short mc_top; /**< index of top page, mc_snum-1 */
772 /** @defgroup mdb_cursor Cursor Flags
774 * Cursor state flags.
777 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
778 #define C_EOF 0x02 /**< No more data */
780 unsigned int mc_flags; /**< @ref mdb_cursor */
781 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
782 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
785 /** Context for sorted-dup records.
786 * We could have gone to a fully recursive design, with arbitrarily
787 * deep nesting of sub-databases. But for now we only handle these
788 * levels - main DB, optional sub-DB, sorted-duplicate DB.
790 typedef struct MDB_xcursor {
791 /** A sub-cursor for traversing the Dup DB */
792 MDB_cursor mx_cursor;
793 /** The database record for this Dup DB */
795 /** The auxiliary DB record for this Dup DB */
799 /** A set of pages freed by an earlier transaction. */
800 typedef struct MDB_oldpages {
801 /** Usually we only read one record from the FREEDB at a time, but
802 * in case we read more, this will chain them together.
804 struct MDB_oldpages *mo_next;
805 /** The ID of the transaction in which these pages were freed. */
807 /** An #IDL of the pages */
808 pgno_t mo_pages[1]; /* dynamic */
811 /** The database environment. */
813 HANDLE me_fd; /**< The main data file */
814 HANDLE me_lfd; /**< The lock file */
815 HANDLE me_mfd; /**< just for writing the meta pages */
816 /** Failed to update the meta page. Probably an I/O error. */
817 #define MDB_FATAL_ERROR 0x80000000U
818 uint32_t me_flags; /**< @ref mdb_env */
819 uint32_t me_extrapad; /**< unused for now */
820 unsigned int me_maxreaders; /**< size of the reader table */
821 MDB_dbi me_numdbs; /**< number of DBs opened */
822 MDB_dbi me_maxdbs; /**< size of the DB table */
823 char *me_path; /**< path to the DB files */
824 char *me_map; /**< the memory map of the data file */
825 MDB_txninfo *me_txns; /**< the memory map of the lock file */
826 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
827 MDB_txn *me_txn; /**< current write transaction */
828 size_t me_mapsize; /**< size of the data memory map */
829 off_t me_size; /**< current file size */
830 pgno_t me_maxpg; /**< me_mapsize / me_psize */
831 unsigned int me_psize; /**< size of a page, from #GET_PAGESIZE */
832 unsigned int me_db_toggle; /**< which DB table is current */
833 MDB_dbx *me_dbxs; /**< array of static DB info */
834 MDB_db *me_dbs[2]; /**< two arrays of MDB_db info */
835 MDB_oldpages *me_pghead; /**< list of old page records */
836 pthread_key_t me_txkey; /**< thread-key for readers */
837 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
838 /** IDL of pages that became unused in a write txn */
839 pgno_t me_free_pgs[MDB_IDL_UM_SIZE];
840 /** ID2L of pages that were written during a write txn */
841 ID2 me_dirty_list[MDB_IDL_UM_SIZE];
842 /** rwlock for the DB tables, if #LAZY_LOCKS is false */
843 LAZY_RWLOCK_DEF(me_dblock)
845 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
849 sem_t *me_rmutex; /* Apple doesn't support shared mutexes */
853 /** max number of pages to commit in one writev() call */
854 #define MDB_COMMIT_PAGES 64
856 static MDB_page *mdb_page_alloc(MDB_cursor *mc, int num);
857 static MDB_page *mdb_page_new(MDB_cursor *mc, uint32_t flags, int num);
858 static int mdb_page_touch(MDB_cursor *mc);
860 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
861 static int mdb_page_search_root(MDB_cursor *mc,
862 MDB_val *key, int modify);
863 static int mdb_page_search(MDB_cursor *mc,
864 MDB_val *key, int modify);
865 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
866 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
869 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
870 static int mdb_env_read_meta(MDB_env *env, int *which);
871 static int mdb_env_write_meta(MDB_txn *txn);
873 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
874 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
875 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags);
876 static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
877 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
878 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
879 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
880 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
881 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
883 static int mdb_rebalance(MDB_cursor *mc);
884 static int mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
886 static void mdb_cursor_pop(MDB_cursor *mc);
887 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
889 static int mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
890 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
891 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
892 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
893 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
895 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
896 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
898 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
899 static void mdb_xcursor_init0(MDB_cursor *mc);
900 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
902 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
905 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
909 static SECURITY_DESCRIPTOR mdb_null_sd;
910 static SECURITY_ATTRIBUTES mdb_all_sa;
911 static int mdb_sec_inited;
914 /** Return the library version info. */
916 mdb_version(int *major, int *minor, int *patch)
918 if (major) *major = MDB_VERSION_MAJOR;
919 if (minor) *minor = MDB_VERSION_MINOR;
920 if (patch) *patch = MDB_VERSION_PATCH;
921 return MDB_VERSION_STRING;
924 /** Table of descriptions for MDB @ref errors */
925 static char *const mdb_errstr[] = {
926 "MDB_KEYEXIST: Key/data pair already exists",
927 "MDB_NOTFOUND: No matching key/data pair found",
928 "MDB_PAGE_NOTFOUND: Requested page not found",
929 "MDB_CORRUPTED: Located page was wrong type",
930 "MDB_PANIC: Update of meta page failed",
931 "MDB_VERSION_MISMATCH: Database environment version mismatch"
935 mdb_strerror(int err)
938 return ("Successful return: 0");
940 if (err >= MDB_KEYEXIST && err <= MDB_VERSION_MISMATCH)
941 return mdb_errstr[err - MDB_KEYEXIST];
943 return strerror(err);
947 /** Display a key in hexadecimal and return the address of the result.
948 * @param[in] key the key to display
949 * @param[in] buf the buffer to write into. Should always be #DKBUF.
950 * @return The key in hexadecimal form.
953 mdb_dkey(MDB_val *key, char *buf)
956 unsigned char *c = key->mv_data;
958 if (key->mv_size > MAXKEYSIZE)
960 /* may want to make this a dynamic check: if the key is mostly
961 * printable characters, print it as-is instead of converting to hex.
964 for (i=0; i<key->mv_size; i++)
965 ptr += sprintf(ptr, "%02x", *c++);
967 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
974 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
976 return txn->mt_dbxs[dbi].md_cmp(a, b);
980 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
982 if (txn->mt_dbxs[dbi].md_dcmp)
983 return txn->mt_dbxs[dbi].md_dcmp(a, b);
985 return EINVAL; /* too bad you can't distinguish this from a valid result */
988 /** Allocate pages for writing.
989 * If there are free pages available from older transactions, they
990 * will be re-used first. Otherwise a new page will be allocated.
991 * @param[in] mc cursor A cursor handle identifying the transaction and
992 * database for which we are allocating.
993 * @param[in] num the number of pages to allocate.
994 * @return Address of the allocated page(s). Requests for multiple pages
995 * will always be satisfied by a single contiguous chunk of memory.
998 mdb_page_alloc(MDB_cursor *mc, int num)
1000 MDB_txn *txn = mc->mc_txn;
1002 pgno_t pgno = P_INVALID;
1005 if (txn->mt_txnid > 2) {
1007 if (!txn->mt_env->me_pghead && mc->mc_dbi != FREE_DBI &&
1008 txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
1009 /* See if there's anything in the free DB */
1012 txnid_t *kptr, oldest;
1014 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1015 mdb_page_search(&m2, NULL, 0);
1016 leaf = NODEPTR(m2.mc_pg[m2.mc_top], 0);
1017 kptr = (txnid_t *)NODEKEY(leaf);
1021 oldest = txn->mt_txnid - 1;
1022 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
1023 txnid_t mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
1024 if (mr && mr < oldest)
1029 if (oldest > *kptr) {
1030 /* It's usable, grab it.
1036 mdb_node_read(txn, leaf, &data);
1037 idl = (ID *) data.mv_data;
1038 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
1039 mop->mo_next = txn->mt_env->me_pghead;
1040 mop->mo_txnid = *kptr;
1041 txn->mt_env->me_pghead = mop;
1042 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
1047 DPRINTF("IDL read txn %zu root %zu num %zu",
1048 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1049 for (i=0; i<idl[0]; i++) {
1050 DPRINTF("IDL %zu", idl[i+1]);
1054 /* drop this IDL from the DB */
1055 m2.mc_ki[m2.mc_top] = 0;
1056 m2.mc_flags = C_INITIALIZED;
1057 mdb_cursor_del(&m2, 0);
1060 if (txn->mt_env->me_pghead) {
1061 MDB_oldpages *mop = txn->mt_env->me_pghead;
1063 /* FIXME: For now, always use fresh pages. We
1064 * really ought to search the free list for a
1069 /* peel pages off tail, so we only have to truncate the list */
1070 pgno = MDB_IDL_LAST(mop->mo_pages);
1071 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
1073 if (mop->mo_pages[2] > mop->mo_pages[1])
1074 mop->mo_pages[0] = 0;
1078 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
1079 txn->mt_env->me_pghead = mop->mo_next;
1086 if (pgno == P_INVALID) {
1087 /* DB size is maxed out */
1088 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg) {
1089 assert(txn->mt_next_pgno + num < txn->mt_env->me_maxpg);
1093 if (txn->mt_env->me_dpages && num == 1) {
1094 np = txn->mt_env->me_dpages;
1095 txn->mt_env->me_dpages = np->mp_next;
1097 if ((np = malloc(txn->mt_env->me_psize * num )) == NULL)
1100 if (pgno == P_INVALID) {
1101 np->mp_pgno = txn->mt_next_pgno;
1102 txn->mt_next_pgno += num;
1106 mid.mid = np->mp_pgno;
1108 mdb_mid2l_insert(txn->mt_u.dirty_list, &mid);
1113 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1114 * @param[in] mc cursor pointing to the page to be touched
1115 * @return 0 on success, non-zero on failure.
1118 mdb_page_touch(MDB_cursor *mc)
1120 MDB_page *mp = mc->mc_pg[mc->mc_top];
1123 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1125 if ((np = mdb_page_alloc(mc, 1)) == NULL)
1127 DPRINTF("touched db %u page %zu -> %zu", mc->mc_dbi, mp->mp_pgno, np->mp_pgno);
1128 assert(mp->mp_pgno != np->mp_pgno);
1129 mdb_midl_append(mc->mc_txn->mt_free_pgs, mp->mp_pgno);
1131 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1134 mp->mp_flags |= P_DIRTY;
1136 mc->mc_pg[mc->mc_top] = mp;
1137 /** If this page has a parent, update the parent to point to
1141 SETPGNO(NODEPTR(mc->mc_pg[mc->mc_top-1], mc->mc_ki[mc->mc_top-1]), mp->mp_pgno);
1147 mdb_env_sync(MDB_env *env, int force)
1150 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1151 if (fdatasync(env->me_fd))
1158 mdb_txn_reset0(MDB_txn *txn);
1160 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
1161 * @param[in] txn the transaction handle to initialize
1162 * @return 0 on success, non-zero on failure. This can only
1163 * fail for read-only transactions, and then only if the
1164 * reader table is full.
1167 mdb_txn_renew0(MDB_txn *txn)
1169 MDB_env *env = txn->mt_env;
1171 if (txn->mt_flags & MDB_TXN_RDONLY) {
1172 MDB_reader *r = pthread_getspecific(env->me_txkey);
1175 pid_t pid = getpid();
1176 pthread_t tid = pthread_self();
1179 for (i=0; i<env->me_txns->mti_numreaders; i++)
1180 if (env->me_txns->mti_readers[i].mr_pid == 0)
1182 if (i == env->me_maxreaders) {
1183 UNLOCK_MUTEX_R(env);
1186 env->me_txns->mti_readers[i].mr_pid = pid;
1187 env->me_txns->mti_readers[i].mr_tid = tid;
1188 if (i >= env->me_txns->mti_numreaders)
1189 env->me_txns->mti_numreaders = i+1;
1190 UNLOCK_MUTEX_R(env);
1191 r = &env->me_txns->mti_readers[i];
1192 pthread_setspecific(env->me_txkey, r);
1194 txn->mt_txnid = env->me_txns->mti_txnid;
1195 txn->mt_toggle = env->me_txns->mti_me_toggle;
1196 r->mr_txnid = txn->mt_txnid;
1197 txn->mt_u.reader = r;
1201 txn->mt_txnid = env->me_txns->mti_txnid+1;
1202 txn->mt_toggle = env->me_txns->mti_me_toggle;
1203 txn->mt_u.dirty_list = env->me_dirty_list;
1204 txn->mt_u.dirty_list[0].mid = 0;
1205 txn->mt_free_pgs = env->me_free_pgs;
1206 txn->mt_free_pgs[0] = 0;
1207 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1211 /* Copy the DB arrays */
1212 LAZY_RWLOCK_RDLOCK(&env->me_dblock);
1213 txn->mt_numdbs = env->me_numdbs;
1214 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
1215 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
1216 if (txn->mt_numdbs > 2)
1217 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
1218 (txn->mt_numdbs - 2) * sizeof(MDB_db));
1219 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1225 mdb_txn_renew(MDB_txn *txn)
1232 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
1233 DPUTS("environment had fatal error, must shutdown!");
1237 rc = mdb_txn_renew0(txn);
1238 if (rc == MDB_SUCCESS) {
1239 DPRINTF("renew txn %zu%c %p on mdbenv %p, root page %zu",
1240 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1241 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1247 mdb_txn_begin(MDB_env *env, unsigned int flags, MDB_txn **ret)
1252 if (env->me_flags & MDB_FATAL_ERROR) {
1253 DPUTS("environment had fatal error, must shutdown!");
1256 if ((txn = calloc(1, sizeof(MDB_txn) + env->me_maxdbs * sizeof(MDB_db))) == NULL) {
1257 DPRINTF("calloc: %s", strerror(ErrCode()));
1260 txn->mt_dbs = (MDB_db *)(txn+1);
1261 if (flags & MDB_RDONLY) {
1262 txn->mt_flags |= MDB_TXN_RDONLY;
1266 rc = mdb_txn_renew0(txn);
1271 DPRINTF("begin txn %zu%c %p on mdbenv %p, root page %zu",
1272 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1273 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
1279 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
1280 * @param[in] txn the transaction handle to reset
1283 mdb_txn_reset0(MDB_txn *txn)
1285 MDB_env *env = txn->mt_env;
1287 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1288 txn->mt_u.reader->mr_txnid = 0;
1295 /* return all dirty pages to dpage list */
1296 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1297 dp = txn->mt_u.dirty_list[i].mptr;
1298 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1299 dp->mp_next = txn->mt_env->me_dpages;
1300 txn->mt_env->me_dpages = dp;
1302 /* large pages just get freed directly */
1307 while ((mop = txn->mt_env->me_pghead)) {
1308 txn->mt_env->me_pghead = mop->mo_next;
1313 for (dbi=2; dbi<env->me_numdbs; dbi++)
1314 env->me_dbxs[dbi].md_dirty = 0;
1315 /* The writer mutex was locked in mdb_txn_begin. */
1316 UNLOCK_MUTEX_W(env);
1321 mdb_txn_reset(MDB_txn *txn)
1326 DPRINTF("reset txn %zu%c %p on mdbenv %p, root page %zu",
1327 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1328 (void *) txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1330 mdb_txn_reset0(txn);
1334 mdb_txn_abort(MDB_txn *txn)
1339 DPRINTF("abort txn %zu%c %p on mdbenv %p, root page %zu",
1340 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1341 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1343 mdb_txn_reset0(txn);
1348 mdb_txn_commit(MDB_txn *txn)
1359 assert(txn != NULL);
1360 assert(txn->mt_env != NULL);
1364 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1369 if (txn != env->me_txn) {
1370 DPUTS("attempt to commit unknown transaction");
1375 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1376 DPUTS("error flag is set, can't commit");
1381 if (!txn->mt_u.dirty_list[0].mid)
1384 DPRINTF("committing txn %zu %p on mdbenv %p, root page %zu",
1385 txn->mt_txnid, (void *)txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
1387 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1389 /* should only be one record now */
1390 if (env->me_pghead) {
1391 /* make sure first page of freeDB is touched and on freelist */
1392 mdb_page_search(&mc, NULL, 1);
1394 /* save to free list */
1395 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
1399 /* make sure last page of freeDB is touched and on freelist */
1400 key.mv_size = MAXKEYSIZE+1;
1402 mdb_page_search(&mc, &key, 1);
1404 mdb_midl_sort(txn->mt_free_pgs);
1408 ID *idl = txn->mt_free_pgs;
1409 DPRINTF("IDL write txn %zu root %zu num %zu",
1410 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1411 for (i=0; i<idl[0]; i++) {
1412 DPRINTF("IDL %zu", idl[i+1]);
1416 /* write to last page of freeDB */
1417 key.mv_size = sizeof(pgno_t);
1418 key.mv_data = &txn->mt_txnid;
1419 data.mv_data = txn->mt_free_pgs;
1420 /* The free list can still grow during this call,
1421 * despite the pre-emptive touches above. So check
1422 * and make sure the entire thing got written.
1425 i = txn->mt_free_pgs[0];
1426 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
1427 rc = mdb_cursor_put(&mc, &key, &data, 0);
1432 } while (i != txn->mt_free_pgs[0]);
1434 /* should only be one record now */
1435 if (env->me_pghead) {
1439 mop = env->me_pghead;
1440 key.mv_size = sizeof(pgno_t);
1441 key.mv_data = &mop->mo_txnid;
1442 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
1443 data.mv_data = mop->mo_pages;
1444 mdb_cursor_put(&mc, &key, &data, 0);
1445 free(env->me_pghead);
1446 env->me_pghead = NULL;
1449 /* Update DB root pointers. Their pages have already been
1450 * touched so this is all in-place and cannot fail.
1455 data.mv_size = sizeof(MDB_db);
1457 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
1458 for (i = 2; i < txn->mt_numdbs; i++) {
1459 if (txn->mt_dbxs[i].md_dirty) {
1460 data.mv_data = &txn->mt_dbs[i];
1461 mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
1466 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
1472 /* Windows actually supports scatter/gather I/O, but only on
1473 * unbuffered file handles. Since we're relying on the OS page
1474 * cache for all our data, that's self-defeating. So we just
1475 * write pages one at a time. We use the ov structure to set
1476 * the write offset, to at least save the overhead of a Seek
1480 memset(&ov, 0, sizeof(ov));
1481 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1483 dp = txn->mt_u.dirty_list[i].mptr;
1484 DPRINTF("committing page %zu", dp->mp_pgno);
1485 size = dp->mp_pgno * env->me_psize;
1486 ov.Offset = size & 0xffffffff;
1487 ov.OffsetHigh = size >> 16;
1488 ov.OffsetHigh >>= 16;
1489 /* clear dirty flag */
1490 dp->mp_flags &= ~P_DIRTY;
1491 wsize = env->me_psize;
1492 if (IS_OVERFLOW(dp)) wsize *= dp->mp_pages;
1493 rc = WriteFile(env->me_fd, dp, wsize, NULL, &ov);
1496 DPRINTF("WriteFile: %d", n);
1503 struct iovec iov[MDB_COMMIT_PAGES];
1507 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1508 dp = txn->mt_u.dirty_list[i].mptr;
1509 if (dp->mp_pgno != next) {
1511 DPRINTF("committing %u dirty pages", n);
1512 rc = writev(env->me_fd, iov, n);
1516 DPUTS("short write, filesystem full?");
1518 DPRINTF("writev: %s", strerror(n));
1525 lseek(env->me_fd, dp->mp_pgno * env->me_psize, SEEK_SET);
1528 DPRINTF("committing page %zu", dp->mp_pgno);
1529 iov[n].iov_len = env->me_psize;
1530 if (IS_OVERFLOW(dp)) iov[n].iov_len *= dp->mp_pages;
1531 iov[n].iov_base = dp;
1532 size += iov[n].iov_len;
1533 next = dp->mp_pgno + (IS_OVERFLOW(dp) ? dp->mp_pages : 1);
1534 /* clear dirty flag */
1535 dp->mp_flags &= ~P_DIRTY;
1536 if (++n >= MDB_COMMIT_PAGES) {
1546 DPRINTF("committing %u dirty pages", n);
1547 rc = writev(env->me_fd, iov, n);
1551 DPUTS("short write, filesystem full?");
1553 DPRINTF("writev: %s", strerror(n));
1560 /* Drop the dirty pages.
1562 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1563 dp = txn->mt_u.dirty_list[i].mptr;
1564 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1565 dp->mp_next = txn->mt_env->me_dpages;
1566 txn->mt_env->me_dpages = dp;
1570 txn->mt_u.dirty_list[i].mid = 0;
1572 txn->mt_u.dirty_list[0].mid = 0;
1574 if ((n = mdb_env_sync(env, 0)) != 0 ||
1575 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
1582 /* update the DB tables */
1584 int toggle = !env->me_db_toggle;
1588 ip = &env->me_dbs[toggle][2];
1589 jp = &txn->mt_dbs[2];
1590 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1591 for (i = 2; i < txn->mt_numdbs; i++) {
1592 if (ip->md_root != jp->md_root)
1597 for (i = 2; i < txn->mt_numdbs; i++) {
1598 if (txn->mt_dbxs[i].md_dirty)
1599 txn->mt_dbxs[i].md_dirty = 0;
1601 env->me_db_toggle = toggle;
1602 env->me_numdbs = txn->mt_numdbs;
1603 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1606 UNLOCK_MUTEX_W(env);
1612 /** Read the environment parameters of a DB environment before
1613 * mapping it into memory.
1614 * @param[in] env the environment handle
1615 * @param[out] meta address of where to store the meta information
1616 * @return 0 on success, non-zero on failure.
1619 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
1621 char page[PAGESIZE];
1626 /* We don't know the page size yet, so use a minimum value.
1630 if (!ReadFile(env->me_fd, page, PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
1632 if ((rc = read(env->me_fd, page, PAGESIZE)) == 0)
1637 else if (rc != PAGESIZE) {
1641 DPRINTF("read: %s", strerror(err));
1645 p = (MDB_page *)page;
1647 if (!F_ISSET(p->mp_flags, P_META)) {
1648 DPRINTF("page %zu not a meta page", p->mp_pgno);
1653 if (m->mm_magic != MDB_MAGIC) {
1654 DPUTS("meta has invalid magic");
1658 if (m->mm_version != MDB_VERSION) {
1659 DPRINTF("database is version %u, expected version %u",
1660 m->mm_version, MDB_VERSION);
1661 return MDB_VERSION_MISMATCH;
1664 memcpy(meta, m, sizeof(*m));
1668 /** Write the environment parameters of a freshly created DB environment.
1669 * @param[in] env the environment handle
1670 * @param[out] meta address of where to store the meta information
1671 * @return 0 on success, non-zero on failure.
1674 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
1681 DPUTS("writing new meta page");
1683 GET_PAGESIZE(psize);
1685 meta->mm_magic = MDB_MAGIC;
1686 meta->mm_version = MDB_VERSION;
1687 meta->mm_psize = psize;
1688 meta->mm_last_pg = 1;
1689 meta->mm_flags = env->me_flags & 0xffff;
1690 meta->mm_flags |= MDB_INTEGERKEY;
1691 meta->mm_dbs[0].md_root = P_INVALID;
1692 meta->mm_dbs[1].md_root = P_INVALID;
1694 p = calloc(2, psize);
1696 p->mp_flags = P_META;
1699 memcpy(m, meta, sizeof(*meta));
1701 q = (MDB_page *)((char *)p + psize);
1704 q->mp_flags = P_META;
1707 memcpy(m, meta, sizeof(*meta));
1712 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
1713 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
1716 rc = write(env->me_fd, p, psize * 2);
1717 rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
1723 /** Update the environment info to commit a transaction.
1724 * @param[in] txn the transaction that's being committed
1725 * @return 0 on success, non-zero on failure.
1728 mdb_env_write_meta(MDB_txn *txn)
1731 MDB_meta meta, metab;
1733 int rc, len, toggle;
1739 assert(txn != NULL);
1740 assert(txn->mt_env != NULL);
1742 toggle = !txn->mt_toggle;
1743 DPRINTF("writing meta page %d for root page %zu",
1744 toggle, txn->mt_dbs[MAIN_DBI].md_root);
1748 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
1749 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
1751 ptr = (char *)&meta;
1752 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
1753 len = sizeof(MDB_meta) - off;
1756 meta.mm_dbs[0] = txn->mt_dbs[0];
1757 meta.mm_dbs[1] = txn->mt_dbs[1];
1758 meta.mm_last_pg = txn->mt_next_pgno - 1;
1759 meta.mm_txnid = txn->mt_txnid;
1762 off += env->me_psize;
1765 /* Write to the SYNC fd */
1768 memset(&ov, 0, sizeof(ov));
1770 WriteFile(env->me_mfd, ptr, len, (DWORD *)&rc, &ov);
1773 rc = pwrite(env->me_mfd, ptr, len, off);
1778 DPUTS("write failed, disk error?");
1779 /* On a failure, the pagecache still contains the new data.
1780 * Write some old data back, to prevent it from being used.
1781 * Use the non-SYNC fd; we know it will fail anyway.
1783 meta.mm_last_pg = metab.mm_last_pg;
1784 meta.mm_txnid = metab.mm_txnid;
1786 WriteFile(env->me_fd, ptr, len, NULL, &ov);
1788 r2 = pwrite(env->me_fd, ptr, len, off);
1790 env->me_flags |= MDB_FATAL_ERROR;
1793 /* Memory ordering issues are irrelevant; since the entire writer
1794 * is wrapped by wmutex, all of these changes will become visible
1795 * after the wmutex is unlocked. Since the DB is multi-version,
1796 * readers will get consistent data regardless of how fresh or
1797 * how stale their view of these values is.
1799 LAZY_MUTEX_LOCK(&env->me_txns->mti_mutex);
1800 txn->mt_env->me_txns->mti_me_toggle = toggle;
1801 txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
1802 LAZY_MUTEX_UNLOCK(&env->me_txns->mti_mutex);
1807 /** Check both meta pages to see which one is newer.
1808 * @param[in] env the environment handle
1809 * @param[out] which address of where to store the meta toggle ID
1810 * @return 0 on success, non-zero on failure.
1813 mdb_env_read_meta(MDB_env *env, int *which)
1817 assert(env != NULL);
1819 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1822 DPRINTF("Using meta page %d", toggle);
1829 mdb_env_create(MDB_env **env)
1833 e = calloc(1, sizeof(MDB_env));
1837 e->me_maxreaders = DEFAULT_READERS;
1839 e->me_fd = INVALID_HANDLE_VALUE;
1840 e->me_lfd = INVALID_HANDLE_VALUE;
1841 e->me_mfd = INVALID_HANDLE_VALUE;
1847 mdb_env_set_mapsize(MDB_env *env, size_t size)
1851 env->me_mapsize = size;
1856 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
1860 env->me_maxdbs = dbs;
1865 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
1867 if (env->me_map || readers < 1)
1869 env->me_maxreaders = readers;
1874 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
1876 if (!env || !readers)
1878 *readers = env->me_maxreaders;
1882 /** Further setup required for opening an MDB environment
1885 mdb_env_open2(MDB_env *env, unsigned int flags)
1887 int i, newenv = 0, toggle;
1891 env->me_flags = flags;
1893 memset(&meta, 0, sizeof(meta));
1895 if ((i = mdb_env_read_header(env, &meta)) != 0) {
1898 DPUTS("new mdbenv");
1902 if (!env->me_mapsize) {
1903 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
1909 LONG sizelo, sizehi;
1910 sizelo = env->me_mapsize & 0xffffffff;
1911 sizehi = env->me_mapsize >> 16; /* pointless on WIN32, only needed on W64 */
1913 /* Windows won't create mappings for zero length files.
1914 * Just allocate the maxsize right now.
1917 SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
1918 if (!SetEndOfFile(env->me_fd))
1920 SetFilePointer(env->me_fd, 0, NULL, 0);
1922 mh = CreateFileMapping(env->me_fd, NULL, PAGE_READONLY,
1923 sizehi, sizelo, NULL);
1926 env->me_map = MapViewOfFileEx(mh, FILE_MAP_READ, 0, 0, env->me_mapsize,
1934 if (meta.mm_address && (flags & MDB_FIXEDMAP))
1936 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
1938 if (env->me_map == MAP_FAILED)
1943 meta.mm_mapsize = env->me_mapsize;
1944 if (flags & MDB_FIXEDMAP)
1945 meta.mm_address = env->me_map;
1946 i = mdb_env_init_meta(env, &meta);
1947 if (i != MDB_SUCCESS) {
1948 munmap(env->me_map, env->me_mapsize);
1952 env->me_psize = meta.mm_psize;
1954 env->me_maxpg = env->me_mapsize / env->me_psize;
1956 p = (MDB_page *)env->me_map;
1957 env->me_metas[0] = METADATA(p);
1958 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
1960 if ((i = mdb_env_read_meta(env, &toggle)) != 0)
1963 DPRINTF("opened database version %u, pagesize %u",
1964 env->me_metas[toggle]->mm_version, env->me_psize);
1965 DPRINTF("depth: %u", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_depth);
1966 DPRINTF("entries: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_entries);
1967 DPRINTF("branch pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_branch_pages);
1968 DPRINTF("leaf pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_leaf_pages);
1969 DPRINTF("overflow pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_overflow_pages);
1970 DPRINTF("root: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_root);
1976 /** Release a reader thread's slot in the reader lock table.
1977 * This function is called automatically when a thread exits.
1978 * Windows doesn't support destructor callbacks for thread-specific storage,
1979 * so this function is not compiled there.
1980 * @param[in] ptr This points to the slot in the reader lock table.
1983 mdb_env_reader_dest(void *ptr)
1985 MDB_reader *reader = ptr;
1987 reader->mr_txnid = 0;
1993 /** Downgrade the exclusive lock on the region back to shared */
1995 mdb_env_share_locks(MDB_env *env)
1999 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
2001 env->me_txns->mti_me_toggle = toggle;
2002 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
2007 /* First acquire a shared lock. The Unlock will
2008 * then release the existing exclusive lock.
2010 memset(&ov, 0, sizeof(ov));
2011 LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov);
2012 UnlockFile(env->me_lfd, 0, 0, 1, 0);
2016 struct flock lock_info;
2017 /* The shared lock replaces the existing lock */
2018 memset((void *)&lock_info, 0, sizeof(lock_info));
2019 lock_info.l_type = F_RDLCK;
2020 lock_info.l_whence = SEEK_SET;
2021 lock_info.l_start = 0;
2022 lock_info.l_len = 1;
2023 fcntl(env->me_lfd, F_SETLK, &lock_info);
2027 #if defined(_WIN32) || defined(__APPLE__)
2029 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
2031 * @(#) $Revision: 5.1 $
2032 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
2033 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
2035 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
2039 * Please do not copyright this code. This code is in the public domain.
2041 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
2042 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
2043 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
2044 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
2045 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
2046 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
2047 * PERFORMANCE OF THIS SOFTWARE.
2050 * chongo <Landon Curt Noll> /\oo/\
2051 * http://www.isthe.com/chongo/
2053 * Share and Enjoy! :-)
2056 typedef unsigned long long mdb_hash_t;
2057 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
2059 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
2060 * @param[in] str string to hash
2061 * @param[in] hval initial value for hash
2062 * @return 64 bit hash
2064 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
2065 * hval arg on the first call.
2067 static inline mdb_hash_t
2068 mdb_hash_str(char *str, mdb_hash_t hval)
2070 unsigned char *s = (unsigned char *)str; /* unsigned string */
2072 * FNV-1a hash each octet of the string
2075 /* xor the bottom with the current octet */
2076 hval ^= (mdb_hash_t)*s++;
2078 /* multiply by the 64 bit FNV magic prime mod 2^64 */
2079 hval += (hval << 1) + (hval << 4) + (hval << 5) +
2080 (hval << 7) + (hval << 8) + (hval << 40);
2082 /* return our new hash value */
2086 /** Hash the string and output the hash in hex.
2087 * @param[in] str string to hash
2088 * @param[out] hexbuf an array of 17 chars to hold the hash
2091 mdb_hash_hex(char *str, char *hexbuf)
2094 mdb_hash_t h = mdb_hash_str(str, MDB_HASH_INIT);
2095 for (i=0; i<8; i++) {
2096 hexbuf += sprintf(hexbuf, "%02x", (unsigned int)h & 0xff);
2102 /** Open and/or initialize the lock region for the environment.
2103 * @param[in] env The MDB environment.
2104 * @param[in] lpath The pathname of the file used for the lock region.
2105 * @param[in] mode The Unix permissions for the file, if we create it.
2106 * @param[out] excl Set to true if we got an exclusive lock on the region.
2107 * @return 0 on success, non-zero on failure.
2110 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
2118 if ((env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
2119 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
2120 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
2124 /* Try to get exclusive lock. If we succeed, then
2125 * nobody is using the lock region and we should initialize it.
2128 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
2132 memset(&ov, 0, sizeof(ov));
2133 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
2139 size = GetFileSize(env->me_lfd, NULL);
2141 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
2145 /* Try to get exclusive lock. If we succeed, then
2146 * nobody is using the lock region and we should initialize it.
2149 struct flock lock_info;
2150 memset((void *)&lock_info, 0, sizeof(lock_info));
2151 lock_info.l_type = F_WRLCK;
2152 lock_info.l_whence = SEEK_SET;
2153 lock_info.l_start = 0;
2154 lock_info.l_len = 1;
2155 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
2159 lock_info.l_type = F_RDLCK;
2160 rc = fcntl(env->me_lfd, F_SETLKW, &lock_info);
2167 size = lseek(env->me_lfd, 0, SEEK_END);
2169 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
2170 if (size < rsize && *excl) {
2172 SetFilePointer(env->me_lfd, rsize, NULL, 0);
2173 if (!SetEndOfFile(env->me_lfd)) {
2178 if (ftruncate(env->me_lfd, rsize) != 0) {
2185 size = rsize - sizeof(MDB_txninfo);
2186 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
2191 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
2197 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
2199 if (!env->me_txns) {
2205 env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
2207 if (env->me_txns == MAP_FAILED) {
2215 if (!mdb_sec_inited) {
2216 InitializeSecurityDescriptor(&mdb_null_sd,
2217 SECURITY_DESCRIPTOR_REVISION);
2218 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
2219 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2220 mdb_all_sa.bInheritHandle = FALSE;
2221 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
2224 mdb_hash_hex(lpath, hexbuf);
2225 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", hexbuf);
2226 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
2227 if (!env->me_rmutex) {
2231 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", hexbuf);
2232 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
2233 if (!env->me_wmutex) {
2240 mdb_hash_hex(lpath, hexbuf);
2241 sprintf(env->me_txns->mti_rmname, "MDBr%s", hexbuf);
2242 if (sem_unlink(env->me_txns->mti_rmname)) {
2244 if (rc != ENOENT && rc != EINVAL)
2247 env->me_rmutex = sem_open(env->me_txns->mti_rmname, O_CREAT, mode, 1);
2248 if (!env->me_rmutex) {
2252 sprintf(env->me_txns->mti_wmname, "MDBw%s", hexbuf);
2253 if (sem_unlink(env->me_txns->mti_wmname)) {
2255 if (rc != ENOENT && rc != EINVAL)
2258 env->me_wmutex = sem_open(env->me_txns->mti_wmname, O_CREAT, mode, 1);
2259 if (!env->me_wmutex) {
2263 #else /* __APPLE__ */
2264 pthread_mutexattr_t mattr;
2266 pthread_mutexattr_init(&mattr);
2267 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
2271 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
2272 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
2273 #endif /* __APPLE__ */
2275 env->me_txns->mti_version = MDB_VERSION;
2276 env->me_txns->mti_magic = MDB_MAGIC;
2277 env->me_txns->mti_txnid = 0;
2278 env->me_txns->mti_numreaders = 0;
2279 env->me_txns->mti_me_toggle = 0;
2282 if (env->me_txns->mti_magic != MDB_MAGIC) {
2283 DPUTS("lock region has invalid magic");
2287 if (env->me_txns->mti_version != MDB_VERSION) {
2288 DPRINTF("lock region is version %u, expected version %u",
2289 env->me_txns->mti_version, MDB_VERSION);
2290 rc = MDB_VERSION_MISMATCH;
2294 if (rc != EACCES && rc != EAGAIN) {
2298 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
2299 if (!env->me_rmutex) {
2303 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
2304 if (!env->me_wmutex) {
2310 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
2311 if (!env->me_rmutex) {
2315 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
2316 if (!env->me_wmutex) {
2326 env->me_lfd = INVALID_HANDLE_VALUE;
2331 /** The name of the lock file in the DB environment */
2332 #define LOCKNAME "/lock.mdb"
2333 /** The name of the data file in the DB environment */
2334 #define DATANAME "/data.mdb"
2336 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
2338 int oflags, rc, len, excl;
2339 char *lpath, *dpath;
2342 lpath = malloc(len + sizeof(LOCKNAME) + len + sizeof(DATANAME));
2345 dpath = lpath + len + sizeof(LOCKNAME);
2346 sprintf(lpath, "%s" LOCKNAME, path);
2347 sprintf(dpath, "%s" DATANAME, path);
2349 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
2354 if (F_ISSET(flags, MDB_RDONLY)) {
2355 oflags = GENERIC_READ;
2356 len = OPEN_EXISTING;
2358 oflags = GENERIC_READ|GENERIC_WRITE;
2361 mode = FILE_ATTRIBUTE_NORMAL;
2362 if ((env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2363 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2368 if (F_ISSET(flags, MDB_RDONLY))
2371 oflags = O_RDWR | O_CREAT;
2373 if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
2379 if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
2380 /* synchronous fd for meta writes */
2382 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2383 mode |= FILE_FLAG_WRITE_THROUGH;
2384 if ((env->me_mfd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2385 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2390 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2391 oflags |= MDB_DSYNC;
2392 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
2397 env->me_path = strdup(path);
2398 DPRINTF("opened dbenv %p", (void *) env);
2399 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
2400 LAZY_RWLOCK_INIT(&env->me_dblock, NULL);
2402 mdb_env_share_locks(env);
2403 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
2404 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
2405 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
2411 if (env->me_fd != INVALID_HANDLE_VALUE) {
2413 env->me_fd = INVALID_HANDLE_VALUE;
2415 if (env->me_lfd != INVALID_HANDLE_VALUE) {
2417 env->me_lfd = INVALID_HANDLE_VALUE;
2425 mdb_env_close(MDB_env *env)
2432 while (env->me_dpages) {
2433 dp = env->me_dpages;
2434 env->me_dpages = dp->mp_next;
2438 free(env->me_dbs[1]);
2439 free(env->me_dbs[0]);
2443 LAZY_RWLOCK_DESTROY(&env->me_dblock);
2444 pthread_key_delete(env->me_txkey);
2447 munmap(env->me_map, env->me_mapsize);
2452 pid_t pid = getpid();
2454 for (i=0; i<env->me_txns->mti_numreaders; i++)
2455 if (env->me_txns->mti_readers[i].mr_pid == pid)
2456 env->me_txns->mti_readers[i].mr_pid = 0;
2457 munmap(env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
2463 /** Compare two items pointing at aligned size_t's */
2465 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
2467 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
2468 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
2471 /** Compare two items pointing at aligned int's */
2473 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
2475 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
2476 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
2479 /** Compare two items pointing at ints of unknown alignment.
2480 * Nodes and keys are guaranteed to be 2-byte aligned.
2483 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
2485 #if BYTE_ORDER == LITTLE_ENDIAN
2486 unsigned short *u, *c;
2489 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
2490 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
2493 } while(!x && u > (unsigned short *)a->mv_data);
2496 return memcmp(a->mv_data, b->mv_data, a->mv_size);
2500 /** Compare two items lexically */
2502 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
2509 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
2515 diff = memcmp(a->mv_data, b->mv_data, len);
2516 return diff ? diff : len_diff<0 ? -1 : len_diff;
2519 /** Compare two items in reverse byte order */
2521 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
2523 const unsigned char *p1, *p2, *p1_lim;
2527 p1_lim = (const unsigned char *)a->mv_data;
2528 p1 = (const unsigned char *)a->mv_data + a->mv_size;
2529 p2 = (const unsigned char *)b->mv_data + b->mv_size;
2531 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
2537 while (p1 > p1_lim) {
2538 diff = *--p1 - *--p2;
2542 return len_diff<0 ? -1 : len_diff;
2545 /** Search for key within a page, using binary search.
2546 * Returns the smallest entry larger or equal to the key.
2547 * If exactp is non-null, stores whether the found entry was an exact match
2548 * in *exactp (1 or 0).
2549 * Updates the cursor index with the index of the found entry.
2550 * If no entry larger or equal to the key is found, returns NULL.
2553 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
2555 unsigned int i = 0, nkeys;
2558 MDB_page *mp = mc->mc_pg[mc->mc_top];
2559 MDB_node *node = NULL;
2564 nkeys = NUMKEYS(mp);
2566 DPRINTF("searching %u keys in %s %spage %zu",
2567 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
2572 low = IS_LEAF(mp) ? 0 : 1;
2574 cmp = mc->mc_dbx->md_cmp;
2576 /* Branch pages have no data, so if using integer keys,
2577 * alignment is guaranteed. Use faster mdb_cmp_int.
2579 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
2580 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
2587 nodekey.mv_size = mc->mc_db->md_pad;
2588 node = NODEPTR(mp, 0); /* fake */
2589 while (low <= high) {
2590 i = (low + high) >> 1;
2591 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
2592 rc = cmp(key, &nodekey);
2593 DPRINTF("found leaf index %u [%s], rc = %i",
2594 i, DKEY(&nodekey), rc);
2603 while (low <= high) {
2604 i = (low + high) >> 1;
2606 node = NODEPTR(mp, i);
2607 nodekey.mv_size = NODEKSZ(node);
2608 nodekey.mv_data = NODEKEY(node);
2610 rc = cmp(key, &nodekey);
2613 DPRINTF("found leaf index %u [%s], rc = %i",
2614 i, DKEY(&nodekey), rc);
2616 DPRINTF("found branch index %u [%s -> %zu], rc = %i",
2617 i, DKEY(&nodekey), NODEPGNO(node), rc);
2628 if (rc > 0) { /* Found entry is less than the key. */
2629 i++; /* Skip to get the smallest entry larger than key. */
2631 node = NODEPTR(mp, i);
2634 *exactp = (rc == 0);
2635 /* store the key index */
2636 mc->mc_ki[mc->mc_top] = i;
2638 /* There is no entry larger or equal to the key. */
2641 /* nodeptr is fake for LEAF2 */
2645 /** Pop a page off the top of the cursor's stack. */
2647 mdb_cursor_pop(MDB_cursor *mc)
2652 top = mc->mc_pg[mc->mc_top];
2657 DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
2658 mc->mc_dbi, (void *) mc);
2662 /** Push a page onto the top of the cursor's stack. */
2664 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
2666 DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
2667 mc->mc_dbi, (void *) mc);
2669 if (mc->mc_snum >= CURSOR_STACK) {
2670 assert(mc->mc_snum < CURSOR_STACK);
2674 mc->mc_top = mc->mc_snum++;
2675 mc->mc_pg[mc->mc_top] = mp;
2676 mc->mc_ki[mc->mc_top] = 0;
2681 /** Find the address of the page corresponding to a given page number.
2682 * @param[in] txn the transaction for this access.
2683 * @param[in] pgno the page number for the page to retrieve.
2684 * @param[out] ret address of a pointer where the page's address will be stored.
2685 * @return 0 on success, non-zero on failure.
2688 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
2692 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
2694 x = mdb_mid2l_search(txn->mt_u.dirty_list, pgno);
2695 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
2696 p = txn->mt_u.dirty_list[x].mptr;
2700 if (pgno <= txn->mt_env->me_metas[txn->mt_toggle]->mm_last_pg)
2701 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
2705 DPRINTF("page %zu not found", pgno);
2708 return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
2711 /** Search for the page a given key should be in.
2712 * Pushes parent pages on the cursor stack. This function continues a
2713 * search on a cursor that has already been initialized. (Usually by
2714 * #mdb_page_search() but also by #mdb_node_move().)
2715 * @param[in,out] mc the cursor for this operation.
2716 * @param[in] key the key to search for. If NULL, search for the lowest
2717 * page. (This is used by #mdb_cursor_first().)
2718 * @param[in] modify If true, visited pages are updated with new page numbers.
2719 * @return 0 on success, non-zero on failure.
2722 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
2724 MDB_page *mp = mc->mc_pg[mc->mc_top];
2729 while (IS_BRANCH(mp)) {
2733 DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
2734 assert(NUMKEYS(mp) > 1);
2735 DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
2737 if (key == NULL) /* Initialize cursor to first page. */
2739 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
2740 /* cursor to last page */
2744 node = mdb_node_search(mc, key, &exact);
2746 i = NUMKEYS(mp) - 1;
2748 i = mc->mc_ki[mc->mc_top];
2757 DPRINTF("following index %u for key [%s]",
2759 assert(i < NUMKEYS(mp));
2760 node = NODEPTR(mp, i);
2762 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp)))
2765 mc->mc_ki[mc->mc_top] = i;
2766 if ((rc = mdb_cursor_push(mc, mp)))
2770 if ((rc = mdb_page_touch(mc)) != 0)
2772 mp = mc->mc_pg[mc->mc_top];
2777 DPRINTF("internal error, index points to a %02X page!?",
2779 return MDB_CORRUPTED;
2782 DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
2783 key ? DKEY(key) : NULL);
2788 /** Search for the page a given key should be in.
2789 * Pushes parent pages on the cursor stack. This function just sets up
2790 * the search; it finds the root page for \b mc's database and sets this
2791 * as the root of the cursor's stack. Then #mdb_page_search_root() is
2792 * called to complete the search.
2793 * @param[in,out] mc the cursor for this operation.
2794 * @param[in] key the key to search for. If NULL, search for the lowest
2795 * page. (This is used by #mdb_cursor_first().)
2796 * @param[in] modify If true, visited pages are updated with new page numbers.
2797 * @return 0 on success, non-zero on failure.
2800 mdb_page_search(MDB_cursor *mc, MDB_val *key, int modify)
2805 /* Make sure the txn is still viable, then find the root from
2806 * the txn's db table.
2808 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
2809 DPUTS("transaction has failed, must abort");
2812 root = mc->mc_db->md_root;
2814 if (root == P_INVALID) { /* Tree is empty. */
2815 DPUTS("tree is empty");
2816 return MDB_NOTFOUND;
2819 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0])))
2825 DPRINTF("db %u root page %zu has flags 0x%X",
2826 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
2829 /* For sub-databases, update main root first */
2830 if (mc->mc_dbi > MAIN_DBI && !mc->mc_dbx->md_dirty) {
2832 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
2833 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 1);
2836 mc->mc_dbx->md_dirty = 1;
2838 if (!F_ISSET(mc->mc_pg[0]->mp_flags, P_DIRTY)) {
2839 if ((rc = mdb_page_touch(mc)))
2841 mc->mc_db->md_root = mc->mc_pg[0]->mp_pgno;
2845 return mdb_page_search_root(mc, key, modify);
2848 /** Return the data associated with a given node.
2849 * @param[in] txn The transaction for this operation.
2850 * @param[in] leaf The node being read.
2851 * @param[out] data Updated to point to the node's data.
2852 * @return 0 on success, non-zero on failure.
2855 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
2857 MDB_page *omp; /* overflow page */
2861 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
2862 data->mv_size = NODEDSZ(leaf);
2863 data->mv_data = NODEDATA(leaf);
2867 /* Read overflow data.
2869 data->mv_size = NODEDSZ(leaf);
2870 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
2871 if ((rc = mdb_page_get(txn, pgno, &omp))) {
2872 DPRINTF("read overflow page %zu failed", pgno);
2875 data->mv_data = METADATA(omp);
2881 mdb_get(MDB_txn *txn, MDB_dbi dbi,
2882 MDB_val *key, MDB_val *data)
2891 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
2893 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
2896 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2900 mdb_cursor_init(&mc, txn, dbi, &mx);
2901 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
2904 /** Find a sibling for a page.
2905 * Replaces the page at the top of the cursor's stack with the
2906 * specified sibling, if one exists.
2907 * @param[in] mc The cursor for this operation.
2908 * @param[in] move_right Non-zero if the right sibling is requested,
2909 * otherwise the left sibling.
2910 * @return 0 on success, non-zero on failure.
2913 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
2919 if (mc->mc_snum < 2) {
2920 return MDB_NOTFOUND; /* root has no siblings */
2924 DPRINTF("parent page is page %zu, index %u",
2925 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]);
2927 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
2928 : (mc->mc_ki[mc->mc_top] == 0)) {
2929 DPRINTF("no more keys left, moving to %s sibling",
2930 move_right ? "right" : "left");
2931 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS)
2935 mc->mc_ki[mc->mc_top]++;
2937 mc->mc_ki[mc->mc_top]--;
2938 DPRINTF("just moving to %s index key %u",
2939 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]);
2941 assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
2943 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
2944 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp)))
2947 mdb_cursor_push(mc, mp);
2952 /** Move the cursor to the next data item. */
2954 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
2960 if (mc->mc_flags & C_EOF) {
2961 return MDB_NOTFOUND;
2964 assert(mc->mc_flags & C_INITIALIZED);
2966 mp = mc->mc_pg[mc->mc_top];
2968 if (mc->mc_db->md_flags & MDB_DUPSORT) {
2969 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
2970 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2971 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
2972 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
2973 if (op != MDB_NEXT || rc == MDB_SUCCESS)
2977 mc->mc_xcursor->mx_cursor.mc_flags = 0;
2978 if (op == MDB_NEXT_DUP)
2979 return MDB_NOTFOUND;
2983 DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
2985 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
2986 DPUTS("=====> move to next sibling page");
2987 if (mdb_cursor_sibling(mc, 1) != MDB_SUCCESS) {
2988 mc->mc_flags |= C_EOF;
2989 mc->mc_flags &= ~C_INITIALIZED;
2990 return MDB_NOTFOUND;
2992 mp = mc->mc_pg[mc->mc_top];
2993 DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
2995 mc->mc_ki[mc->mc_top]++;
2997 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
2998 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3001 key->mv_size = mc->mc_db->md_pad;
3002 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3006 assert(IS_LEAF(mp));
3007 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3009 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3010 mdb_xcursor_init1(mc, leaf);
3013 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3016 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3017 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3018 if (rc != MDB_SUCCESS)
3023 MDB_SET_KEY(leaf, key);
3027 /** Move the cursor to the previous data item. */
3029 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3035 assert(mc->mc_flags & C_INITIALIZED);
3037 mp = mc->mc_pg[mc->mc_top];
3039 if (mc->mc_db->md_flags & MDB_DUPSORT) {
3040 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3041 if (op == MDB_PREV || op == MDB_PREV_DUP) {
3042 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3043 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
3044 if (op != MDB_PREV || rc == MDB_SUCCESS)
3047 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3048 if (op == MDB_PREV_DUP)
3049 return MDB_NOTFOUND;
3054 DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3056 if (mc->mc_ki[mc->mc_top] == 0) {
3057 DPUTS("=====> move to prev sibling page");
3058 if (mdb_cursor_sibling(mc, 0) != MDB_SUCCESS) {
3059 mc->mc_flags &= ~C_INITIALIZED;
3060 return MDB_NOTFOUND;
3062 mp = mc->mc_pg[mc->mc_top];
3063 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
3064 DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3066 mc->mc_ki[mc->mc_top]--;
3068 mc->mc_flags &= ~C_EOF;
3070 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3071 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3074 key->mv_size = mc->mc_db->md_pad;
3075 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3079 assert(IS_LEAF(mp));
3080 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3082 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3083 mdb_xcursor_init1(mc, leaf);
3086 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3089 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3090 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3091 if (rc != MDB_SUCCESS)
3096 MDB_SET_KEY(leaf, key);
3100 /** Set the cursor on a specific data item. */
3102 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3103 MDB_cursor_op op, int *exactp)
3112 assert(key->mv_size > 0);
3114 /* See if we're already on the right page */
3115 if (mc->mc_flags & C_INITIALIZED) {
3118 mp = mc->mc_pg[mc->mc_top];
3120 mc->mc_ki[mc->mc_top] = 0;
3121 return MDB_NOTFOUND;
3123 if (mp->mp_flags & P_LEAF2) {
3124 nodekey.mv_size = mc->mc_db->md_pad;
3125 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
3127 leaf = NODEPTR(mp, 0);
3128 MDB_SET_KEY(leaf, &nodekey);
3130 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3132 /* Probably happens rarely, but first node on the page
3133 * was the one we wanted.
3135 mc->mc_ki[mc->mc_top] = 0;
3136 leaf = NODEPTR(mp, 0);
3143 unsigned int nkeys = NUMKEYS(mp);
3145 if (mp->mp_flags & P_LEAF2) {
3146 nodekey.mv_data = LEAF2KEY(mp,
3147 nkeys-1, nodekey.mv_size);
3149 leaf = NODEPTR(mp, nkeys-1);
3150 MDB_SET_KEY(leaf, &nodekey);
3152 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3154 /* last node was the one we wanted */
3155 mc->mc_ki[mc->mc_top] = nkeys-1;
3156 leaf = NODEPTR(mp, nkeys-1);
3162 /* This is definitely the right page, skip search_page */
3167 /* If any parents have right-sibs, search.
3168 * Otherwise, there's nothing further.
3170 for (i=0; i<mc->mc_top; i++)
3172 NUMKEYS(mc->mc_pg[i])-1)
3174 if (i == mc->mc_top) {
3175 /* There are no other pages */
3176 mc->mc_ki[mc->mc_top] = nkeys;
3177 return MDB_NOTFOUND;
3181 /* There are no other pages */
3182 mc->mc_ki[mc->mc_top] = 0;
3183 return MDB_NOTFOUND;
3187 rc = mdb_page_search(mc, key, 0);
3188 if (rc != MDB_SUCCESS)
3191 mp = mc->mc_pg[mc->mc_top];
3192 assert(IS_LEAF(mp));
3195 leaf = mdb_node_search(mc, key, exactp);
3196 if (exactp != NULL && !*exactp) {
3197 /* MDB_SET specified and not an exact match. */
3198 return MDB_NOTFOUND;
3202 DPUTS("===> inexact leaf not found, goto sibling");
3203 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
3204 return rc; /* no entries matched */
3205 mp = mc->mc_pg[mc->mc_top];
3206 assert(IS_LEAF(mp));
3207 leaf = NODEPTR(mp, 0);
3211 mc->mc_flags |= C_INITIALIZED;
3212 mc->mc_flags &= ~C_EOF;
3215 key->mv_size = mc->mc_db->md_pad;
3216 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3220 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3221 mdb_xcursor_init1(mc, leaf);
3224 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3225 if (op == MDB_SET || op == MDB_SET_RANGE) {
3226 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3229 if (op == MDB_GET_BOTH) {
3235 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
3236 if (rc != MDB_SUCCESS)
3239 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
3241 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
3243 rc = mc->mc_dbx->md_dcmp(data, &d2);
3245 if (op == MDB_GET_BOTH || rc > 0)
3246 return MDB_NOTFOUND;
3251 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3252 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3257 /* The key already matches in all other cases */
3258 if (op == MDB_SET_RANGE)
3259 MDB_SET_KEY(leaf, key);
3260 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
3265 /** Move the cursor to the first item in the database. */
3267 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3272 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3273 rc = mdb_page_search(mc, NULL, 0);
3274 if (rc != MDB_SUCCESS)
3277 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3279 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
3280 mc->mc_flags |= C_INITIALIZED;
3281 mc->mc_flags &= ~C_EOF;
3283 mc->mc_ki[mc->mc_top] = 0;
3285 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3286 key->mv_size = mc->mc_db->md_pad;
3287 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
3292 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3293 mdb_xcursor_init1(mc, leaf);
3294 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3299 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3300 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3304 MDB_SET_KEY(leaf, key);
3308 /** Move the cursor to the last item in the database. */
3310 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3316 lkey.mv_size = MAXKEYSIZE+1;
3317 lkey.mv_data = NULL;
3319 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3320 rc = mdb_page_search(mc, &lkey, 0);
3321 if (rc != MDB_SUCCESS)
3324 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3326 leaf = NODEPTR(mc->mc_pg[mc->mc_top], NUMKEYS(mc->mc_pg[mc->mc_top])-1);
3327 mc->mc_flags |= C_INITIALIZED;
3328 mc->mc_flags &= ~C_EOF;
3330 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
3332 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3333 key->mv_size = mc->mc_db->md_pad;
3334 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
3339 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3340 mdb_xcursor_init1(mc, leaf);
3341 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3346 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3347 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3352 MDB_SET_KEY(leaf, key);
3357 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3367 case MDB_GET_BOTH_RANGE:
3368 if (data == NULL || mc->mc_xcursor == NULL) {
3375 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3377 } else if (op == MDB_SET_RANGE)
3378 rc = mdb_cursor_set(mc, key, data, op, NULL);
3380 rc = mdb_cursor_set(mc, key, data, op, &exact);
3382 case MDB_GET_MULTIPLE:
3384 !(mc->mc_db->md_flags & MDB_DUPFIXED) ||
3385 !(mc->mc_flags & C_INITIALIZED)) {
3390 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
3391 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
3394 case MDB_NEXT_MULTIPLE:
3396 !(mc->mc_db->md_flags & MDB_DUPFIXED)) {
3400 if (!(mc->mc_flags & C_INITIALIZED))
3401 rc = mdb_cursor_first(mc, key, data);
3403 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
3404 if (rc == MDB_SUCCESS) {
3405 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
3408 mx = &mc->mc_xcursor->mx_cursor;
3409 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
3411 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
3412 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
3420 case MDB_NEXT_NODUP:
3421 if (!(mc->mc_flags & C_INITIALIZED))
3422 rc = mdb_cursor_first(mc, key, data);
3424 rc = mdb_cursor_next(mc, key, data, op);
3428 case MDB_PREV_NODUP:
3429 if (!(mc->mc_flags & C_INITIALIZED) || (mc->mc_flags & C_EOF))
3430 rc = mdb_cursor_last(mc, key, data);
3432 rc = mdb_cursor_prev(mc, key, data, op);
3435 rc = mdb_cursor_first(mc, key, data);
3439 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
3440 !(mc->mc_flags & C_INITIALIZED) ||
3441 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3445 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3448 rc = mdb_cursor_last(mc, key, data);
3452 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
3453 !(mc->mc_flags & C_INITIALIZED) ||
3454 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3458 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3461 DPRINTF("unhandled/unimplemented cursor operation %u", op);
3469 /** Touch all the pages in the cursor stack.
3470 * Makes sure all the pages are writable, before attempting a write operation.
3471 * @param[in] mc The cursor to operate on.
3474 mdb_cursor_touch(MDB_cursor *mc)
3478 if (mc->mc_dbi > MAIN_DBI && !mc->mc_dbx->md_dirty) {
3480 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
3481 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 1);
3484 mc->mc_dbx->md_dirty = 1;
3486 for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
3487 if (!F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY)) {
3488 rc = mdb_page_touch(mc);
3492 mc->mc_db->md_root =
3493 mc->mc_pg[mc->mc_top]->mp_pgno;
3497 mc->mc_top = mc->mc_snum-1;
3502 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3506 MDB_val xdata, *rdata, dkey;
3512 char pbuf[PAGESIZE];
3513 char dbuf[MAXKEYSIZE+1];
3516 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
3519 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
3520 mc->mc_dbi, DKEY(key), key->mv_size, data->mv_size);
3524 if (flags == MDB_CURRENT) {
3525 if (!(mc->mc_flags & C_INITIALIZED))
3528 } else if (mc->mc_db->md_root == P_INVALID) {
3530 /* new database, write a root leaf page */
3531 DPUTS("allocating new root leaf page");
3532 if ((np = mdb_page_new(mc, P_LEAF, 1)) == NULL) {
3536 mdb_cursor_push(mc, np);
3537 mc->mc_db->md_root = np->mp_pgno;
3538 mc->mc_db->md_depth++;
3539 mc->mc_dbx->md_dirty = 1;
3540 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
3542 np->mp_flags |= P_LEAF2;
3543 mc->mc_flags |= C_INITIALIZED;
3549 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
3550 if (flags == MDB_NOOVERWRITE && rc == 0) {
3551 DPRINTF("duplicate key [%s]", DKEY(key));
3553 return MDB_KEYEXIST;
3555 if (rc && rc != MDB_NOTFOUND)
3559 /* Cursor is positioned, now make sure all pages are writable */
3560 rc2 = mdb_cursor_touch(mc);
3565 /* The key already exists */
3566 if (rc == MDB_SUCCESS) {
3567 /* there's only a key anyway, so this is a no-op */
3568 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3569 unsigned int ksize = mc->mc_db->md_pad;
3570 if (key->mv_size != ksize)
3572 if (flags == MDB_CURRENT) {
3573 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
3574 memcpy(ptr, key->mv_data, ksize);
3579 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3582 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
3583 /* Was a single item before, must convert now */
3584 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3585 /* Just overwrite the current item */
3586 if (flags == MDB_CURRENT)
3589 /* create a fake page for the dup items */
3590 dkey.mv_size = NODEDSZ(leaf);
3591 dkey.mv_data = NODEDATA(leaf);
3592 /* data matches, ignore it */
3593 if (!mc->mc_dbx->md_dcmp(data, &dkey))
3594 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
3595 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
3596 dkey.mv_data = dbuf;
3597 fp = (MDB_page *)pbuf;
3598 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
3599 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
3600 fp->mp_lower = PAGEHDRSZ;
3601 fp->mp_upper = PAGEHDRSZ + dkey.mv_size + data->mv_size;
3602 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
3603 fp->mp_flags |= P_LEAF2;
3604 fp->mp_pad = data->mv_size;
3606 fp->mp_upper += 2 * sizeof(indx_t) + 2 * NODESIZE +
3607 (dkey.mv_size & 1) + (data->mv_size & 1);
3609 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
3612 xdata.mv_size = fp->mp_upper;
3613 xdata.mv_data = pbuf;
3617 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
3618 /* See if we need to convert from fake page to subDB */
3620 unsigned int offset;
3623 fp = NODEDATA(leaf);
3624 if (flags == MDB_CURRENT) {
3625 fp->mp_flags |= P_DIRTY;
3626 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
3627 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
3631 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
3632 offset = fp->mp_pad;
3634 offset = NODESIZE + sizeof(indx_t) + data->mv_size;
3636 offset += offset & 1;
3637 if (NODEDSZ(leaf) + offset >= mc->mc_txn->mt_env->me_psize / MDB_MINKEYS) {
3638 /* yes, convert it */
3640 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
3641 dummy.md_pad = fp->mp_pad;
3642 dummy.md_flags = MDB_DUPFIXED;
3643 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
3644 dummy.md_flags |= MDB_INTEGERKEY;
3647 dummy.md_branch_pages = 0;
3648 dummy.md_leaf_pages = 1;
3649 dummy.md_overflow_pages = 0;
3650 dummy.md_entries = NUMKEYS(fp);
3652 xdata.mv_size = sizeof(MDB_db);
3653 xdata.mv_data = &dummy;
3654 mp = mdb_page_alloc(mc, 1);
3657 offset = mc->mc_txn->mt_env->me_psize - NODEDSZ(leaf);
3658 flags |= F_DUPDATA|F_SUBDATA;
3659 dummy.md_root = mp->mp_pgno;
3661 /* no, just grow it */
3663 xdata.mv_size = NODEDSZ(leaf) + offset;
3664 xdata.mv_data = pbuf;
3665 mp = (MDB_page *)pbuf;
3666 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
3669 mp->mp_flags = fp->mp_flags | P_DIRTY;
3670 mp->mp_pad = fp->mp_pad;
3671 mp->mp_lower = fp->mp_lower;
3672 mp->mp_upper = fp->mp_upper + offset;
3674 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
3676 nsize = NODEDSZ(leaf) - fp->mp_upper;
3677 memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper, nsize);
3678 for (i=0; i<NUMKEYS(fp); i++)
3679 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
3681 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
3685 /* data is on sub-DB, just store it */
3686 flags |= F_DUPDATA|F_SUBDATA;
3690 /* same size, just replace it */
3691 if (!F_ISSET(leaf->mn_flags, F_BIGDATA) &&
3692 NODEDSZ(leaf) == data->mv_size) {
3693 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
3696 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
3698 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
3704 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
3705 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
3706 rc = mdb_page_split(mc, key, rdata, P_INVALID);
3708 /* There is room already in this leaf page. */
3709 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, 0);
3712 if (rc != MDB_SUCCESS)
3713 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
3715 /* Remember if we just added a subdatabase */
3716 if (flags & (F_SUBDATA|F_DUPDATA)) {
3717 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3718 leaf->mn_flags |= (flags & (F_SUBDATA|F_DUPDATA));
3721 /* Now store the actual data in the child DB. Note that we're
3722 * storing the user data in the keys field, so there are strict
3723 * size limits on dupdata. The actual data fields of the child
3724 * DB are all zero size.
3732 if (flags & MDB_CURRENT) {
3733 xflags = MDB_CURRENT;
3735 mdb_xcursor_init1(mc, leaf);
3736 xflags = (flags & MDB_NODUPDATA) ? MDB_NOOVERWRITE : 0;
3738 /* converted, write the original data first */
3740 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
3744 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
3745 if (flags & F_SUBDATA) {
3746 db = NODEDATA(leaf);
3747 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
3750 /* sub-writes might have failed so check rc again.
3751 * Don't increment count if we just replaced an existing item.
3753 if (!rc && !(flags & MDB_CURRENT))
3754 mc->mc_db->md_entries++;
3761 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
3766 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
3769 if (!mc->mc_flags & C_INITIALIZED)
3772 rc = mdb_cursor_touch(mc);
3776 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3778 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3779 if (flags != MDB_NODUPDATA) {
3780 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
3781 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
3783 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
3784 /* If sub-DB still has entries, we're done */
3785 if (mc->mc_xcursor->mx_db.md_root != P_INVALID) {
3786 if (leaf->mn_flags & F_SUBDATA) {
3787 /* update subDB info */
3788 MDB_db *db = NODEDATA(leaf);
3789 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
3791 /* shrink fake page */
3792 mdb_node_shrink(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3794 mc->mc_db->md_entries--;
3797 /* otherwise fall thru and delete the sub-DB */
3800 if (leaf->mn_flags & F_SUBDATA) {
3801 /* add all the child DB's pages to the free list */
3802 rc = mdb_page_search(&mc->mc_xcursor->mx_cursor, NULL, 0);
3803 if (rc == MDB_SUCCESS) {
3808 mx = &mc->mc_xcursor->mx_cursor;
3809 mc->mc_db->md_entries -=
3810 mx->mc_db->md_entries;
3813 while (mx->mc_snum > 0) {
3814 for (i=0; i<NUMKEYS(mx->mc_pg[mx->mc_top]); i++) {
3816 ni = NODEPTR(mx->mc_pg[mx->mc_top], i);
3819 mdb_midl_append(mc->mc_txn->mt_free_pgs, pg);
3823 rc = mdb_cursor_sibling(mx, 1);
3825 /* no more siblings, go back to beginning
3826 * of previous level. (stack was already popped
3827 * by mdb_cursor_sibling)
3829 for (i=1; i<mx->mc_top; i++) {
3831 ni = NODEPTR(mx->mc_pg[i-1],0);
3833 if ((rc = mdb_page_get(mc->mc_txn, pg, &mx->mc_pg[i])))
3839 mdb_midl_append(mc->mc_txn->mt_free_pgs,
3840 mx->mc_db->md_root);
3845 return mdb_cursor_del0(mc, leaf);
3848 /** Allocate and initialize new pages for a database.
3849 * @param[in] mc a cursor on the database being added to.
3850 * @param[in] flags flags defining what type of page is being allocated.
3851 * @param[in] num the number of pages to allocate. This is usually 1,
3852 * unless allocating overflow pages for a large record.
3853 * @return Address of a page, or NULL on failure.
3856 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num)
3860 if ((np = mdb_page_alloc(mc, num)) == NULL)
3862 DPRINTF("allocated new mpage %zu, page size %u",
3863 np->mp_pgno, mc->mc_txn->mt_env->me_psize);
3864 np->mp_flags = flags | P_DIRTY;
3865 np->mp_lower = PAGEHDRSZ;
3866 np->mp_upper = mc->mc_txn->mt_env->me_psize;
3869 mc->mc_db->md_branch_pages++;
3870 else if (IS_LEAF(np))
3871 mc->mc_db->md_leaf_pages++;
3872 else if (IS_OVERFLOW(np)) {
3873 mc->mc_db->md_overflow_pages += num;
3880 /** Calculate the size of a leaf node.
3881 * The size depends on the environment's page size; if a data item
3882 * is too large it will be put onto an overflow page and the node
3883 * size will only include the key and not the data. Sizes are always
3884 * rounded up to an even number of bytes, to guarantee 2-byte alignment
3885 * of the #MDB_node headers.
3886 * @param[in] env The environment handle.
3887 * @param[in] key The key for the node.
3888 * @param[in] data The data for the node.
3889 * @return The number of bytes needed to store the node.
3892 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
3896 sz = LEAFSIZE(key, data);
3897 if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
3898 /* put on overflow page */
3899 sz -= data->mv_size - sizeof(pgno_t);
3903 return sz + sizeof(indx_t);
3906 /** Calculate the size of a branch node.
3907 * The size should depend on the environment's page size but since
3908 * we currently don't support spilling large keys onto overflow
3909 * pages, it's simply the size of the #MDB_node header plus the
3910 * size of the key. Sizes are always rounded up to an even number
3911 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
3912 * @param[in] env The environment handle.
3913 * @param[in] key The key for the node.
3914 * @return The number of bytes needed to store the node.
3917 mdb_branch_size(MDB_env *env, MDB_val *key)
3922 if (sz >= env->me_psize / MDB_MINKEYS) {
3923 /* put on overflow page */
3924 /* not implemented */
3925 /* sz -= key->size - sizeof(pgno_t); */
3928 return sz + sizeof(indx_t);
3931 /** Add a node to the page pointed to by the cursor.
3932 * @param[in] mc The cursor for this operation.
3933 * @param[in] indx The index on the page where the new node should be added.
3934 * @param[in] key The key for the new node.
3935 * @param[in] data The data for the new node, if any.
3936 * @param[in] pgno The page number, if adding a branch node.
3937 * @param[in] flags Flags for the node.
3938 * @return 0 on success, non-zero on failure. Possible errors are:
3940 * <li>ENOMEM - failed to allocate overflow pages for the node.
3941 * <li>ENOSPC - there is insufficient room in the page. This error
3942 * should never happen since all callers already calculate the
3943 * page's free space before calling this function.
3947 mdb_node_add(MDB_cursor *mc, indx_t indx,
3948 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags)
3951 size_t node_size = NODESIZE;
3954 MDB_page *mp = mc->mc_pg[mc->mc_top];
3955 MDB_page *ofp = NULL; /* overflow page */
3958 assert(mp->mp_upper >= mp->mp_lower);
3960 DPRINTF("add to %s %spage %zu index %i, data size %zu key size %zu [%s]",
3961 IS_LEAF(mp) ? "leaf" : "branch",
3962 IS_SUBP(mp) ? "sub-" : "",
3963 mp->mp_pgno, indx, data ? data->mv_size : 0,
3964 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
3967 /* Move higher keys up one slot. */
3968 int ksize = mc->mc_db->md_pad, dif;
3969 char *ptr = LEAF2KEY(mp, indx, ksize);
3970 dif = NUMKEYS(mp) - indx;
3972 memmove(ptr+ksize, ptr, dif*ksize);
3973 /* insert new key */
3974 memcpy(ptr, key->mv_data, ksize);
3976 /* Just using these for counting */
3977 mp->mp_lower += sizeof(indx_t);
3978 mp->mp_upper -= ksize - sizeof(indx_t);
3983 node_size += key->mv_size;
3987 if (F_ISSET(flags, F_BIGDATA)) {
3988 /* Data already on overflow page. */
3989 node_size += sizeof(pgno_t);
3990 } else if (data->mv_size >= mc->mc_txn->mt_env->me_psize / MDB_MINKEYS) {
3991 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
3992 /* Put data on overflow page. */
3993 DPRINTF("data size is %zu, put on overflow page",
3995 node_size += sizeof(pgno_t);
3996 if ((ofp = mdb_page_new(mc, P_OVERFLOW, ovpages)) == NULL)
3998 DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
4001 node_size += data->mv_size;
4004 node_size += node_size & 1;
4006 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
4007 DPRINTF("not enough room in page %zu, got %u ptrs",
4008 mp->mp_pgno, NUMKEYS(mp));
4009 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
4010 mp->mp_upper - mp->mp_lower);
4011 DPRINTF("node size = %zu", node_size);
4015 /* Move higher pointers up one slot. */
4016 for (i = NUMKEYS(mp); i > indx; i--)
4017 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
4019 /* Adjust free space offsets. */
4020 ofs = mp->mp_upper - node_size;
4021 assert(ofs >= mp->mp_lower + sizeof(indx_t));
4022 mp->mp_ptrs[indx] = ofs;
4024 mp->mp_lower += sizeof(indx_t);
4026 /* Write the node data. */
4027 node = NODEPTR(mp, indx);
4028 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
4029 node->mn_flags = flags;
4031 SETDSZ(node,data->mv_size);
4036 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
4041 if (F_ISSET(flags, F_BIGDATA))
4042 memcpy(node->mn_data + key->mv_size, data->mv_data,
4045 memcpy(node->mn_data + key->mv_size, data->mv_data,
4048 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
4050 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
4057 /** Delete the specified node from a page.
4058 * @param[in] mp The page to operate on.
4059 * @param[in] indx The index of the node to delete.
4060 * @param[in] ksize The size of a node. Only used if the page is
4061 * part of a #MDB_DUPFIXED database.
4064 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
4067 indx_t i, j, numkeys, ptr;
4071 DPRINTF("delete node %u on %s page %zu", indx,
4072 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
4073 assert(indx < NUMKEYS(mp));
4076 int x = NUMKEYS(mp) - 1 - indx;
4077 base = LEAF2KEY(mp, indx, ksize);
4079 memmove(base, base + ksize, x * ksize);
4080 mp->mp_lower -= sizeof(indx_t);
4081 mp->mp_upper += ksize - sizeof(indx_t);
4085 node = NODEPTR(mp, indx);
4086 sz = NODESIZE + node->mn_ksize;
4088 if (F_ISSET(node->mn_flags, F_BIGDATA))
4089 sz += sizeof(pgno_t);
4091 sz += NODEDSZ(node);
4095 ptr = mp->mp_ptrs[indx];
4096 numkeys = NUMKEYS(mp);
4097 for (i = j = 0; i < numkeys; i++) {
4099 mp->mp_ptrs[j] = mp->mp_ptrs[i];
4100 if (mp->mp_ptrs[i] < ptr)
4101 mp->mp_ptrs[j] += sz;
4106 base = (char *)mp + mp->mp_upper;
4107 memmove(base + sz, base, ptr - mp->mp_upper);
4109 mp->mp_lower -= sizeof(indx_t);
4113 /** Compact the main page after deleting a node on a subpage.
4114 * @param[in] mp The main page to operate on.
4115 * @param[in] indx The index of the subpage on the main page.
4118 mdb_node_shrink(MDB_page *mp, indx_t indx)
4125 indx_t i, numkeys, ptr;
4127 node = NODEPTR(mp, indx);
4128 sp = (MDB_page *)NODEDATA(node);
4129 osize = NODEDSZ(node);
4131 delta = sp->mp_upper - sp->mp_lower;
4132 SETDSZ(node, osize - delta);
4133 xp = (MDB_page *)((char *)sp + delta);
4135 /* shift subpage upward */
4137 nsize = NUMKEYS(sp) * sp->mp_pad;
4138 memmove(METADATA(xp), METADATA(sp), nsize);
4141 nsize = osize - sp->mp_upper;
4142 numkeys = NUMKEYS(sp);
4143 for (i=numkeys-1; i>=0; i--)
4144 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
4146 xp->mp_upper = sp->mp_lower;
4147 xp->mp_lower = sp->mp_lower;
4148 xp->mp_flags = sp->mp_flags;
4149 xp->mp_pad = sp->mp_pad;
4150 xp->mp_pgno = mp->mp_pgno;
4152 /* shift lower nodes upward */
4153 ptr = mp->mp_ptrs[indx];
4154 numkeys = NUMKEYS(mp);
4155 for (i = 0; i < numkeys; i++) {
4156 if (mp->mp_ptrs[i] <= ptr)
4157 mp->mp_ptrs[i] += delta;
4160 base = (char *)mp + mp->mp_upper;
4161 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
4162 mp->mp_upper += delta;
4165 /** Initial setup of a sorted-dups cursor.
4166 * Sorted duplicates are implemented as a sub-database for the given key.
4167 * The duplicate data items are actually keys of the sub-database.
4168 * Operations on the duplicate data items are performed using a sub-cursor
4169 * initialized when the sub-database is first accessed. This function does
4170 * the preliminary setup of the sub-cursor, filling in the fields that
4171 * depend only on the parent DB.
4172 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4175 mdb_xcursor_init0(MDB_cursor *mc)
4177 MDB_xcursor *mx = mc->mc_xcursor;
4179 mx->mx_cursor.mc_xcursor = NULL;
4180 mx->mx_cursor.mc_txn = mc->mc_txn;
4181 mx->mx_cursor.mc_db = &mx->mx_db;
4182 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
4183 mx->mx_cursor.mc_dbi = mc->mc_dbi+1;
4184 mx->mx_dbx.md_parent = mc->mc_dbi;
4185 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
4186 mx->mx_dbx.md_dcmp = NULL;
4187 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
4188 mx->mx_dbx.md_dirty = 0;
4191 /** Final setup of a sorted-dups cursor.
4192 * Sets up the fields that depend on the data from the main cursor.
4193 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4194 * @param[in] node The data containing the #MDB_db record for the
4195 * sorted-dup database.
4198 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
4200 MDB_xcursor *mx = mc->mc_xcursor;
4202 if (node->mn_flags & F_SUBDATA) {
4203 MDB_db *db = NODEDATA(node);
4205 mx->mx_cursor.mc_snum = 0;
4206 mx->mx_cursor.mc_flags = 0;
4208 MDB_page *fp = NODEDATA(node);
4209 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
4210 mx->mx_db.md_flags = 0;
4211 mx->mx_db.md_depth = 1;
4212 mx->mx_db.md_branch_pages = 0;
4213 mx->mx_db.md_leaf_pages = 1;
4214 mx->mx_db.md_overflow_pages = 0;
4215 mx->mx_db.md_entries = NUMKEYS(fp);
4216 mx->mx_db.md_root = fp->mp_pgno;
4217 mx->mx_cursor.mc_snum = 1;
4218 mx->mx_cursor.mc_flags = C_INITIALIZED;
4219 mx->mx_cursor.mc_top = 0;
4220 mx->mx_cursor.mc_pg[0] = fp;
4221 mx->mx_cursor.mc_ki[0] = 0;
4222 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4223 mx->mx_db.md_flags = MDB_DUPFIXED;
4224 mx->mx_db.md_pad = fp->mp_pad;
4225 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
4226 mx->mx_db.md_flags |= MDB_INTEGERKEY;
4229 DPRINTF("Sub-db %u for db %u root page %zu", mx->mx_cursor.mc_dbi, mc->mc_dbi,
4231 if (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY))
4232 mx->mx_dbx.md_dirty = 1;
4233 mx->mx_dbx.md_name.mv_data = NODEKEY(node);
4234 mx->mx_dbx.md_name.mv_size = node->mn_ksize;
4235 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
4236 mx->mx_dbx.md_cmp = mdb_cmp_long;
4239 /** Initialize a cursor for a given transaction and database. */
4241 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
4245 mc->mc_db = &txn->mt_dbs[dbi];
4246 mc->mc_dbx = &txn->mt_dbxs[dbi];
4249 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4251 mc->mc_xcursor = mx;
4252 mdb_xcursor_init0(mc);
4254 mc->mc_xcursor = NULL;
4259 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
4262 MDB_xcursor *mx = NULL;
4263 size_t size = sizeof(MDB_cursor);
4265 if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
4268 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
4269 size += sizeof(MDB_xcursor);
4271 if ((mc = malloc(size)) != NULL) {
4272 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4273 mx = (MDB_xcursor *)(mc + 1);
4275 mdb_cursor_init(mc, txn, dbi, mx);
4285 /* Return the count of duplicate data items for the current key */
4287 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
4291 if (mc == NULL || countp == NULL)
4294 if (!(mc->mc_db->md_flags & MDB_DUPSORT))
4297 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4298 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4301 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
4304 *countp = mc->mc_xcursor->mx_db.md_entries;
4310 mdb_cursor_close(MDB_cursor *mc)
4317 /** Replace the key for a node with a new key.
4318 * @param[in] mp The page containing the node to operate on.
4319 * @param[in] indx The index of the node to operate on.
4320 * @param[in] key The new key to use.
4321 * @return 0 on success, non-zero on failure.
4324 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
4326 indx_t ptr, i, numkeys;
4333 node = NODEPTR(mp, indx);
4334 ptr = mp->mp_ptrs[indx];
4335 DPRINTF("update key %u (ofs %u) [%.*s] to [%s] on page %zu",
4337 (int)node->mn_ksize, (char *)NODEKEY(node),
4341 delta = key->mv_size - node->mn_ksize;
4343 if (delta > 0 && SIZELEFT(mp) < delta) {
4344 DPRINTF("OUCH! Not enough room, delta = %d", delta);
4348 numkeys = NUMKEYS(mp);
4349 for (i = 0; i < numkeys; i++) {
4350 if (mp->mp_ptrs[i] <= ptr)
4351 mp->mp_ptrs[i] -= delta;
4354 base = (char *)mp + mp->mp_upper;
4355 len = ptr - mp->mp_upper + NODESIZE;
4356 memmove(base - delta, base, len);
4357 mp->mp_upper -= delta;
4359 node = NODEPTR(mp, indx);
4360 node->mn_ksize = key->mv_size;
4363 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
4368 /** Move a node from csrc to cdst.
4371 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
4378 /* Mark src and dst as dirty. */
4379 if ((rc = mdb_page_touch(csrc)) ||
4380 (rc = mdb_page_touch(cdst)))
4383 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4384 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
4385 key.mv_size = csrc->mc_db->md_pad;
4386 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
4388 data.mv_data = NULL;
4390 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
4391 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
4392 unsigned int snum = csrc->mc_snum;
4394 /* must find the lowest key below src */
4395 mdb_page_search_root(csrc, NULL, 0);
4396 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
4397 key.mv_size = NODEKSZ(s2);
4398 key.mv_data = NODEKEY(s2);
4399 csrc->mc_snum = snum--;
4400 csrc->mc_top = snum;
4402 key.mv_size = NODEKSZ(srcnode);
4403 key.mv_data = NODEKEY(srcnode);
4405 data.mv_size = NODEDSZ(srcnode);
4406 data.mv_data = NODEDATA(srcnode);
4408 DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
4409 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
4410 csrc->mc_ki[csrc->mc_top],
4412 csrc->mc_pg[csrc->mc_top]->mp_pgno,
4413 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
4415 /* Add the node to the destination page.
4417 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, NODEPGNO(srcnode),
4419 if (rc != MDB_SUCCESS)
4422 /* Delete the node from the source page.
4424 mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
4426 /* Update the parent separators.
4428 if (csrc->mc_ki[csrc->mc_top] == 0) {
4429 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
4430 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4431 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
4433 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
4434 key.mv_size = NODEKSZ(srcnode);
4435 key.mv_data = NODEKEY(srcnode);
4437 DPRINTF("update separator for source page %zu to [%s]",
4438 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
4439 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1],
4440 &key)) != MDB_SUCCESS)
4443 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
4445 nullkey.mv_size = 0;
4446 assert(mdb_update_key(csrc->mc_pg[csrc->mc_top], 0, &nullkey) == MDB_SUCCESS);
4450 if (cdst->mc_ki[cdst->mc_top] == 0) {
4451 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
4452 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4453 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
4455 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
4456 key.mv_size = NODEKSZ(srcnode);
4457 key.mv_data = NODEKEY(srcnode);
4459 DPRINTF("update separator for destination page %zu to [%s]",
4460 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
4461 if ((rc = mdb_update_key(cdst->mc_pg[cdst->mc_top-1], cdst->mc_ki[cdst->mc_top-1],
4462 &key)) != MDB_SUCCESS)
4465 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
4467 nullkey.mv_size = 0;
4468 assert(mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &nullkey) == MDB_SUCCESS);
4475 /** Merge one page into another.
4476 * The nodes from the page pointed to by \b csrc will
4477 * be copied to the page pointed to by \b cdst and then
4478 * the \b csrc page will be freed.
4479 * @param[in] csrc Cursor pointing to the source page.
4480 * @param[in] cdst Cursor pointing to the destination page.
4483 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
4490 DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
4491 cdst->mc_pg[cdst->mc_top]->mp_pgno);
4493 assert(csrc->mc_snum > 1); /* can't merge root page */
4494 assert(cdst->mc_snum > 1);
4496 /* Mark dst as dirty. */
4497 if ((rc = mdb_page_touch(cdst)))
4500 /* Move all nodes from src to dst.
4502 j = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
4503 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4504 key.mv_size = csrc->mc_db->md_pad;
4505 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
4506 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
4507 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
4508 if (rc != MDB_SUCCESS)
4510 key.mv_data = (char *)key.mv_data + key.mv_size;
4513 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
4514 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
4516 key.mv_size = srcnode->mn_ksize;
4517 key.mv_data = NODEKEY(srcnode);
4518 data.mv_size = NODEDSZ(srcnode);
4519 data.mv_data = NODEDATA(srcnode);
4520 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
4521 if (rc != MDB_SUCCESS)
4526 DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
4527 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);
4529 /* Unlink the src page from parent and add to free list.
4531 mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
4532 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
4534 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], 0, &key)) != MDB_SUCCESS)
4538 mdb_midl_append(csrc->mc_txn->mt_free_pgs, csrc->mc_pg[csrc->mc_top]->mp_pgno);
4539 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
4540 csrc->mc_db->md_leaf_pages--;
4542 csrc->mc_db->md_branch_pages--;
4543 mdb_cursor_pop(csrc);
4545 return mdb_rebalance(csrc);
4548 /** Copy the contents of a cursor.
4549 * @param[in] csrc The cursor to copy from.
4550 * @param[out] cdst The cursor to copy to.
4553 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
4557 cdst->mc_txn = csrc->mc_txn;
4558 cdst->mc_dbi = csrc->mc_dbi;
4559 cdst->mc_db = csrc->mc_db;
4560 cdst->mc_dbx = csrc->mc_dbx;
4561 cdst->mc_snum = csrc->mc_snum;
4562 cdst->mc_top = csrc->mc_top;
4563 cdst->mc_flags = csrc->mc_flags;
4565 for (i=0; i<csrc->mc_snum; i++) {
4566 cdst->mc_pg[i] = csrc->mc_pg[i];
4567 cdst->mc_ki[i] = csrc->mc_ki[i];
4571 /** Rebalance the tree after a delete operation.
4572 * @param[in] mc Cursor pointing to the page where rebalancing
4574 * @return 0 on success, non-zero on failure.
4577 mdb_rebalance(MDB_cursor *mc)
4584 DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
4585 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
4586 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);
4588 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD) {
4589 DPRINTF("no need to rebalance page %zu, above fill threshold",
4590 mc->mc_pg[mc->mc_top]->mp_pgno);
4594 if (mc->mc_snum < 2) {
4595 if (NUMKEYS(mc->mc_pg[mc->mc_top]) == 0) {
4596 DPUTS("tree is completely empty");
4597 mc->mc_db->md_root = P_INVALID;
4598 mc->mc_db->md_depth = 0;
4599 mc->mc_db->md_leaf_pages = 0;
4600 mdb_midl_append(mc->mc_txn->mt_free_pgs, mc->mc_pg[mc->mc_top]->mp_pgno);
4602 } else if (IS_BRANCH(mc->mc_pg[mc->mc_top]) && NUMKEYS(mc->mc_pg[mc->mc_top]) == 1) {
4603 DPUTS("collapsing root page!");
4604 mdb_midl_append(mc->mc_txn->mt_free_pgs, mc->mc_pg[mc->mc_top]->mp_pgno);
4605 mc->mc_db->md_root = NODEPGNO(NODEPTR(mc->mc_pg[mc->mc_top], 0));
4606 if ((rc = mdb_page_get(mc->mc_txn, mc->mc_db->md_root,
4607 &mc->mc_pg[mc->mc_top])))
4609 mc->mc_db->md_depth--;
4610 mc->mc_db->md_branch_pages--;
4612 DPUTS("root page doesn't need rebalancing");
4616 /* The parent (branch page) must have at least 2 pointers,
4617 * otherwise the tree is invalid.
4619 ptop = mc->mc_top-1;
4620 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
4622 /* Leaf page fill factor is below the threshold.
4623 * Try to move keys from left or right neighbor, or
4624 * merge with a neighbor page.
4629 mdb_cursor_copy(mc, &mn);
4630 mn.mc_xcursor = NULL;
4632 if (mc->mc_ki[ptop] == 0) {
4633 /* We're the leftmost leaf in our parent.
4635 DPUTS("reading right neighbor");
4637 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
4638 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
4640 mn.mc_ki[mn.mc_top] = 0;
4641 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
4643 /* There is at least one neighbor to the left.
4645 DPUTS("reading left neighbor");
4647 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
4648 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
4650 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
4651 mc->mc_ki[mc->mc_top] = 0;
4654 DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
4655 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);
4657 /* If the neighbor page is above threshold and has at least two
4658 * keys, move one key from it.
4660 * Otherwise we should try to merge them.
4662 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) >= 2)
4663 return mdb_node_move(&mn, mc);
4664 else { /* FIXME: if (has_enough_room()) */
4665 mc->mc_flags &= ~C_INITIALIZED;
4666 if (mc->mc_ki[ptop] == 0)
4667 return mdb_page_merge(&mn, mc);
4669 return mdb_page_merge(mc, &mn);
4673 /** Complete a delete operation started by #mdb_cursor_del(). */
4675 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
4679 /* add overflow pages to free list */
4680 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
4684 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
4685 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
4686 for (i=0; i<ovpages; i++) {
4687 DPRINTF("freed ov page %zu", pg);
4688 mdb_midl_append(mc->mc_txn->mt_free_pgs, pg);
4692 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], mc->mc_db->md_pad);
4693 mc->mc_db->md_entries--;
4694 rc = mdb_rebalance(mc);
4695 if (rc != MDB_SUCCESS)
4696 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4702 mdb_del(MDB_txn *txn, MDB_dbi dbi,
4703 MDB_val *key, MDB_val *data)
4708 MDB_val rdata, *xdata;
4712 assert(key != NULL);
4714 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
4716 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4719 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
4723 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
4727 mdb_cursor_init(&mc, txn, dbi, &mx);
4738 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
4740 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
4744 /** Split a page and insert a new node.
4745 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
4746 * The cursor will be updated to point to the actual page and index where
4747 * the node got inserted after the split.
4748 * @param[in] newkey The key for the newly inserted node.
4749 * @param[in] newdata The data for the newly inserted node.
4750 * @param[in] newpgno The page number, if the new node is a branch node.
4751 * @return 0 on success, non-zero on failure.
4754 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno)
4757 int rc = MDB_SUCCESS, ins_new = 0;
4760 unsigned int i, j, split_indx, nkeys, pmax;
4762 MDB_val sepkey, rkey, rdata;
4764 MDB_page *mp, *rp, *pp;
4769 mp = mc->mc_pg[mc->mc_top];
4770 newindx = mc->mc_ki[mc->mc_top];
4772 DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
4773 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
4774 DKEY(newkey), mc->mc_ki[mc->mc_top]);
4776 if (mc->mc_snum < 2) {
4777 if ((pp = mdb_page_new(mc, P_BRANCH, 1)) == NULL)
4779 /* shift current top to make room for new parent */
4780 mc->mc_pg[1] = mc->mc_pg[0];
4781 mc->mc_ki[1] = mc->mc_ki[0];
4784 mc->mc_db->md_root = pp->mp_pgno;
4785 DPRINTF("root split! new root = %zu", pp->mp_pgno);
4786 mc->mc_db->md_depth++;
4788 /* Add left (implicit) pointer. */
4789 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
4790 /* undo the pre-push */
4791 mc->mc_pg[0] = mc->mc_pg[1];
4792 mc->mc_ki[0] = mc->mc_ki[1];
4793 mc->mc_db->md_root = mp->mp_pgno;
4794 mc->mc_db->md_depth--;
4801 ptop = mc->mc_top-1;
4802 DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
4805 /* Create a right sibling. */
4806 if ((rp = mdb_page_new(mc, mp->mp_flags, 1)) == NULL)
4808 mdb_cursor_copy(mc, &mn);
4809 mn.mc_pg[mn.mc_top] = rp;
4810 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
4811 DPRINTF("new right sibling: page %zu", rp->mp_pgno);
4813 nkeys = NUMKEYS(mp);
4814 split_indx = nkeys / 2 + 1;
4819 unsigned int lsize, rsize, ksize;
4820 /* Move half of the keys to the right sibling */
4822 x = mc->mc_ki[mc->mc_top] - split_indx;
4823 ksize = mc->mc_db->md_pad;
4824 split = LEAF2KEY(mp, split_indx, ksize);
4825 rsize = (nkeys - split_indx) * ksize;
4826 lsize = (nkeys - split_indx) * sizeof(indx_t);
4827 mp->mp_lower -= lsize;
4828 rp->mp_lower += lsize;
4829 mp->mp_upper += rsize - lsize;
4830 rp->mp_upper -= rsize - lsize;
4831 sepkey.mv_size = ksize;
4832 if (newindx == split_indx) {
4833 sepkey.mv_data = newkey->mv_data;
4835 sepkey.mv_data = split;
4838 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
4839 memcpy(rp->mp_ptrs, split, rsize);
4840 sepkey.mv_data = rp->mp_ptrs;
4841 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
4842 memcpy(ins, newkey->mv_data, ksize);
4843 mp->mp_lower += sizeof(indx_t);
4844 mp->mp_upper -= ksize - sizeof(indx_t);
4847 memcpy(rp->mp_ptrs, split, x * ksize);
4848 ins = LEAF2KEY(rp, x, ksize);
4849 memcpy(ins, newkey->mv_data, ksize);
4850 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
4851 rp->mp_lower += sizeof(indx_t);
4852 rp->mp_upper -= ksize - sizeof(indx_t);
4853 mc->mc_ki[mc->mc_top] = x;
4854 mc->mc_pg[mc->mc_top] = rp;
4859 /* For leaf pages, check the split point based on what
4860 * fits where, since otherwise add_node can fail.
4863 unsigned int psize, nsize;
4864 /* Maximum free space in an empty page */
4865 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
4866 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
4867 if (newindx < split_indx) {
4869 for (i=0; i<split_indx; i++) {
4870 node = NODEPTR(mp, i);
4871 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
4872 if (F_ISSET(node->mn_flags, F_BIGDATA))
4873 psize += sizeof(pgno_t);
4875 psize += NODEDSZ(node);
4884 for (i=nkeys-1; i>=split_indx; i--) {
4885 node = NODEPTR(mp, i);
4886 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
4887 if (F_ISSET(node->mn_flags, F_BIGDATA))
4888 psize += sizeof(pgno_t);
4890 psize += NODEDSZ(node);
4900 /* First find the separating key between the split pages.
4902 if (newindx == split_indx) {
4903 sepkey.mv_size = newkey->mv_size;
4904 sepkey.mv_data = newkey->mv_data;
4906 node = NODEPTR(mp, split_indx);
4907 sepkey.mv_size = node->mn_ksize;
4908 sepkey.mv_data = NODEKEY(node);
4912 DPRINTF("separator is [%s]", DKEY(&sepkey));
4914 /* Copy separator key to the parent.
4916 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
4919 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno);
4921 /* Right page might now have changed parent.
4922 * Check if left page also changed parent.
4924 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
4925 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
4926 mc->mc_pg[ptop] = mn.mc_pg[ptop];
4927 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
4931 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
4937 if (rc != MDB_SUCCESS) {
4941 /* Move half of the keys to the right sibling. */
4943 /* grab a page to hold a temporary copy */
4944 if (mc->mc_txn->mt_env->me_dpages) {
4945 copy = mc->mc_txn->mt_env->me_dpages;
4946 mc->mc_txn->mt_env->me_dpages = copy->mp_next;
4948 if ((copy = malloc(mc->mc_txn->mt_env->me_psize)) == NULL)
4952 copy->mp_pgno = mp->mp_pgno;
4953 copy->mp_flags = mp->mp_flags;
4954 copy->mp_lower = PAGEHDRSZ;
4955 copy->mp_upper = mc->mc_txn->mt_env->me_psize;
4956 mc->mc_pg[mc->mc_top] = copy;
4957 for (i = j = 0; i <= nkeys; j++) {
4958 if (i == split_indx) {
4959 /* Insert in right sibling. */
4960 /* Reset insert index for right sibling. */
4961 j = (i == newindx && ins_new);
4962 mc->mc_pg[mc->mc_top] = rp;
4965 if (i == newindx && !ins_new) {
4966 /* Insert the original entry that caused the split. */
4967 rkey.mv_data = newkey->mv_data;
4968 rkey.mv_size = newkey->mv_size;
4970 rdata.mv_data = newdata->mv_data;
4971 rdata.mv_size = newdata->mv_size;
4978 /* Update page and index for the new key. */
4979 mc->mc_ki[mc->mc_top] = j;
4980 } else if (i == nkeys) {
4983 node = NODEPTR(mp, i);
4984 rkey.mv_data = NODEKEY(node);
4985 rkey.mv_size = node->mn_ksize;
4987 rdata.mv_data = NODEDATA(node);
4988 rdata.mv_size = NODEDSZ(node);
4990 pgno = NODEPGNO(node);
4991 flags = node->mn_flags;
4996 if (!IS_LEAF(mp) && j == 0) {
4997 /* First branch index doesn't need key data. */
5001 rc = mdb_node_add(mc, j, &rkey, &rdata, pgno, flags);
5004 /* reset back to original page */
5005 if (newindx < split_indx)
5006 mc->mc_pg[mc->mc_top] = mp;
5008 nkeys = NUMKEYS(copy);
5009 for (i=0; i<nkeys; i++)
5010 mp->mp_ptrs[i] = copy->mp_ptrs[i];
5011 mp->mp_lower = copy->mp_lower;
5012 mp->mp_upper = copy->mp_upper;
5013 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
5014 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
5016 /* return tmp page to freelist */
5017 copy->mp_next = mc->mc_txn->mt_env->me_dpages;
5018 mc->mc_txn->mt_env->me_dpages = copy;
5023 mdb_put(MDB_txn *txn, MDB_dbi dbi,
5024 MDB_val *key, MDB_val *data, unsigned int flags)
5029 assert(key != NULL);
5030 assert(data != NULL);
5032 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5035 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
5039 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
5043 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA)) != flags)
5046 mdb_cursor_init(&mc, txn, dbi, &mx);
5047 return mdb_cursor_put(&mc, key, data, flags);
5051 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
5053 /** Only a subset of the @ref mdb_env flags can be changed
5054 * at runtime. Changing other flags requires closing the environment
5055 * and re-opening it with the new flags.
5057 #define CHANGEABLE (MDB_NOSYNC)
5058 if ((flag & CHANGEABLE) != flag)
5061 env->me_flags |= flag;
5063 env->me_flags &= ~flag;
5068 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
5073 *arg = env->me_flags;
5078 mdb_env_get_path(MDB_env *env, const char **arg)
5083 *arg = env->me_path;
5087 /** Common code for #mdb_stat() and #mdb_env_stat().
5088 * @param[in] env the environment to operate in.
5089 * @param[in] db the #MDB_db record containing the stats to return.
5090 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
5091 * @return 0, this function always succeeds.
5094 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
5096 arg->ms_psize = env->me_psize;
5097 arg->ms_depth = db->md_depth;
5098 arg->ms_branch_pages = db->md_branch_pages;
5099 arg->ms_leaf_pages = db->md_leaf_pages;
5100 arg->ms_overflow_pages = db->md_overflow_pages;
5101 arg->ms_entries = db->md_entries;
5106 mdb_env_stat(MDB_env *env, MDB_stat *arg)
5110 if (env == NULL || arg == NULL)
5113 mdb_env_read_meta(env, &toggle);
5115 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
5118 /** Set the default comparison functions for a database.
5119 * Called immediately after a database is opened to set the defaults.
5120 * The user can then override them with #mdb_set_compare() or
5121 * #mdb_set_dupsort().
5122 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
5123 * @param[in] dbi A database handle returned by #mdb_open()
5126 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
5128 if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEKEY)
5129 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memnr;
5130 else if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERKEY)
5131 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_cint;
5133 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memn;
5135 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
5136 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP) {
5137 if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED)
5138 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_int;
5140 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_cint;
5141 } else if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEDUP) {
5142 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memnr;
5144 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memn;
5147 txn->mt_dbxs[dbi].md_dcmp = NULL;
5151 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
5158 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
5159 mdb_default_cmp(txn, FREE_DBI);
5165 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
5166 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
5167 mdb_default_cmp(txn, MAIN_DBI);
5171 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
5172 mdb_default_cmp(txn, MAIN_DBI);
5175 /* Is the DB already open? */
5177 for (i=2; i<txn->mt_numdbs; i++) {
5178 if (len == txn->mt_dbxs[i].md_name.mv_size &&
5179 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
5185 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
5188 /* Find the DB info */
5190 key.mv_data = (void *)name;
5191 rc = mdb_get(txn, MAIN_DBI, &key, &data);
5193 /* Create if requested */
5194 if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
5197 data.mv_size = sizeof(MDB_db);
5198 data.mv_data = &dummy;
5199 memset(&dummy, 0, sizeof(dummy));
5200 dummy.md_root = P_INVALID;
5201 dummy.md_flags = flags & 0xffff;
5202 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
5203 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
5207 /* OK, got info, add to table */
5208 if (rc == MDB_SUCCESS) {
5209 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
5210 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
5211 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
5212 txn->mt_dbxs[txn->mt_numdbs].md_parent = MAIN_DBI;
5213 txn->mt_dbxs[txn->mt_numdbs].md_dirty = dirty;
5214 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
5215 *dbi = txn->mt_numdbs;
5216 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
5217 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
5218 mdb_default_cmp(txn, txn->mt_numdbs);
5225 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
5227 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
5230 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
5233 void mdb_close(MDB_txn *txn, MDB_dbi dbi)
5236 if (dbi <= MAIN_DBI || dbi >= txn->mt_numdbs)
5238 ptr = txn->mt_dbxs[dbi].md_name.mv_data;
5239 txn->mt_dbxs[dbi].md_name.mv_data = NULL;
5240 txn->mt_dbxs[dbi].md_name.mv_size = 0;
5244 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
5246 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5249 txn->mt_dbxs[dbi].md_cmp = cmp;
5253 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
5255 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5258 txn->mt_dbxs[dbi].md_dcmp = cmp;
5262 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
5264 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5267 txn->mt_dbxs[dbi].md_rel = rel;
5271 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
5273 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5276 txn->mt_dbxs[dbi].md_relctx = ctx;