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 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
69 /* Solaris just defines one or the other */
70 # define LITTLE_ENDIAN 1234
71 # define BIG_ENDIAN 4321
72 # ifdef _LITTLE_ENDIAN
73 # define BYTE_ORDER LITTLE_ENDIAN
75 # define BYTE_ORDER BIG_ENDIAN
78 # define BYTE_ORDER __BYTE_ORDER
83 #define LITTLE_ENDIAN __LITTLE_ENDIAN
86 #define BIG_ENDIAN __BIG_ENDIAN
89 #if defined(__i386) || defined(__x86_64)
90 #define MISALIGNED_OK 1
96 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
97 # error "Unknown or unsupported endianness (BYTE_ORDER)"
98 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
99 # error "Two's complement, reasonably sized integer types, please"
102 /** @defgroup internal MDB Internals
105 /** @defgroup compat Windows Compatibility Macros
106 * A bunch of macros to minimize the amount of platform-specific ifdefs
107 * needed throughout the rest of the code. When the features this library
108 * needs are similar enough to POSIX to be hidden in a one-or-two line
109 * replacement, this macro approach is used.
113 #define pthread_t DWORD
114 #define pthread_mutex_t HANDLE
115 #define pthread_key_t DWORD
116 #define pthread_self() GetCurrentThreadId()
117 #define pthread_key_create(x,y) (*(x) = TlsAlloc())
118 #define pthread_key_delete(x) TlsFree(x)
119 #define pthread_getspecific(x) TlsGetValue(x)
120 #define pthread_setspecific(x,y) TlsSetValue(x,y)
121 #define pthread_mutex_unlock(x) ReleaseMutex(x)
122 #define pthread_mutex_lock(x) WaitForSingleObject(x, INFINITE)
123 #define LOCK_MUTEX_R(env) pthread_mutex_lock((env)->me_rmutex)
124 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock((env)->me_rmutex)
125 #define LOCK_MUTEX_W(env) pthread_mutex_lock((env)->me_wmutex)
126 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock((env)->me_wmutex)
127 #define getpid() GetCurrentProcessId()
128 #define fdatasync(fd) (!FlushFileBuffers(fd))
129 #define ErrCode() GetLastError()
130 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
131 #define close(fd) CloseHandle(fd)
132 #define munmap(ptr,len) UnmapViewOfFile(ptr)
135 #define LOCK_MUTEX_R(env) sem_wait((env)->me_rmutex)
136 #define UNLOCK_MUTEX_R(env) sem_post((env)->me_rmutex)
137 #define LOCK_MUTEX_W(env) sem_wait((env)->me_wmutex)
138 #define UNLOCK_MUTEX_W(env) sem_post((env)->me_wmutex)
139 #define fdatasync(fd) fsync(fd)
142 #define fdatasync(fd) fsync(fd)
144 /** Lock the reader mutex.
146 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
147 /** Unlock the reader mutex.
149 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
151 /** Lock the writer mutex.
152 * Only a single write transaction is allowed at a time. Other writers
153 * will block waiting for this mutex.
155 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
156 /** Unlock the writer mutex.
158 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
159 #endif /* __APPLE__ */
161 /** Get the error code for the last failed system function.
163 #define ErrCode() errno
165 /** An abstraction for a file handle.
166 * On POSIX systems file handles are small integers. On Windows
167 * they're opaque pointers.
171 /** A value for an invalid file handle.
172 * Mainly used to initialize file variables and signify that they are
175 #define INVALID_HANDLE_VALUE (-1)
177 /** Get the size of a memory page for the system.
178 * This is the basic size that the platform's memory manager uses, and is
179 * fundamental to the use of memory-mapped files.
181 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
184 #if defined(_WIN32) || defined(__APPLE__)
191 /** A flag for opening a file and requesting synchronous data writes.
192 * This is only used when writing a meta page. It's not strictly needed;
193 * we could just do a normal write and then immediately perform a flush.
194 * But if this flag is available it saves us an extra system call.
196 * @note If O_DSYNC is undefined but exists in /usr/include,
197 * preferably set some compiler flag to get the definition.
198 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
201 # define MDB_DSYNC O_DSYNC
205 /** Function for flushing the data of a file. Define this to fsync
206 * if fdatasync() is not supported.
208 #ifndef MDB_FDATASYNC
209 # define MDB_FDATASYNC fdatasync
212 /** A page number in the database.
213 * Note that 64 bit page numbers are overkill, since pages themselves
214 * already represent 12-13 bits of addressable memory, and the OS will
215 * always limit applications to a maximum of 63 bits of address space.
217 * @note In the #MDB_node structure, we only store 48 bits of this value,
218 * which thus limits us to only 60 bits of addressable data.
222 /** A transaction ID.
223 * See struct MDB_txn.mt_txnid for details.
227 /** @defgroup debug Debug Macros
231 /** Enable debug output.
232 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
233 * read from and written to the database (used for free space management).
238 #if !(__STDC_VERSION__ >= 199901L || defined(__GNUC__))
239 # define DPRINTF (void) /* Vararg macros may be unsupported */
241 /** Print a debug message with printf formatting. */
242 # define DPRINTF(fmt, ...) /**< Requires 2 or more args */ \
243 fprintf(stderr, "%s:%d " fmt "\n", __func__, __LINE__, __VA_ARGS__)
245 # define DPRINTF(fmt, ...) ((void) 0)
247 /** Print a debug string.
248 * The string is printed literally, with no format processing.
250 #define DPUTS(arg) DPRINTF("%s", arg)
253 /** A default memory page size.
254 * The actual size is platform-dependent, but we use this for
255 * boot-strapping. We probably should not be using this any more.
256 * The #GET_PAGESIZE() macro is used to get the actual size.
258 * Note that we don't currently support Huge pages. On Linux,
259 * regular data files cannot use Huge pages, and in general
260 * Huge pages aren't actually pageable. We rely on the OS
261 * demand-pager to read our data and page it out when memory
262 * pressure from other processes is high. So until OSs have
263 * actual paging support for Huge pages, they're not viable.
265 #define MDB_PAGESIZE 4096
267 /** The minimum number of keys required in a database page.
268 * Setting this to a larger value will place a smaller bound on the
269 * maximum size of a data item. Data items larger than this size will
270 * be pushed into overflow pages instead of being stored directly in
271 * the B-tree node. This value used to default to 4. With a page size
272 * of 4096 bytes that meant that any item larger than 1024 bytes would
273 * go into an overflow page. That also meant that on average 2-3KB of
274 * each overflow page was wasted space. The value cannot be lower than
275 * 2 because then there would no longer be a tree structure. With this
276 * value, items larger than 2KB will go into overflow pages, and on
277 * average only 1KB will be wasted.
279 #define MDB_MINKEYS 2
281 /** A stamp that identifies a file as an MDB file.
282 * There's nothing special about this value other than that it is easily
283 * recognizable, and it will reflect any byte order mismatches.
285 #define MDB_MAGIC 0xBEEFC0DE
287 /** The version number for a database's file format. */
288 #define MDB_VERSION 1
290 /** The maximum size of a key in the database.
291 * While data items have essentially unbounded size, we require that
292 * keys all fit onto a regular page. This limit could be raised a bit
293 * further if needed; to something just under #MDB_PAGESIZE / #MDB_MINKEYS.
295 #define MAXKEYSIZE 511
300 * This is used for printing a hex dump of a key's contents.
302 #define DKBUF char kbuf[(MAXKEYSIZE*2+1)]
303 /** Display a key in hex.
305 * Invoke a function to display a key in hex.
307 #define DKEY(x) mdb_dkey(x, kbuf)
309 #define DKBUF typedef int dummy_kbuf /* so we can put ';' after */
313 /** @defgroup lazylock Lazy Locking
314 * Macros for locks that are't actually needed.
315 * The DB view is always consistent because all writes are wrapped in
316 * the wmutex. Finer-grained locks aren't necessary.
320 /** Use lazy locking. I.e., don't lock these accesses at all. */
324 /** Grab the reader lock */
325 #define LAZY_MUTEX_LOCK(x)
326 /** Release the reader lock */
327 #define LAZY_MUTEX_UNLOCK(x)
328 /** Release the DB table reader/writer lock */
329 #define LAZY_RWLOCK_UNLOCK(x)
330 /** Grab the DB table write lock */
331 #define LAZY_RWLOCK_WRLOCK(x)
332 /** Grab the DB table read lock */
333 #define LAZY_RWLOCK_RDLOCK(x)
334 /** Declare the DB table rwlock. Should not be followed by ';'. */
335 #define LAZY_RWLOCK_DEF(x)
336 /** Initialize the DB table rwlock */
337 #define LAZY_RWLOCK_INIT(x,y)
338 /** Destroy the DB table rwlock */
339 #define LAZY_RWLOCK_DESTROY(x)
341 #define LAZY_MUTEX_LOCK(x) pthread_mutex_lock(x)
342 #define LAZY_MUTEX_UNLOCK(x) pthread_mutex_unlock(x)
343 #define LAZY_RWLOCK_UNLOCK(x) pthread_rwlock_unlock(x)
344 #define LAZY_RWLOCK_WRLOCK(x) pthread_rwlock_wrlock(x)
345 #define LAZY_RWLOCK_RDLOCK(x) pthread_rwlock_rdlock(x)
346 #define LAZY_RWLOCK_DEF(x) pthread_rwlock_t x;
347 #define LAZY_RWLOCK_INIT(x,y) pthread_rwlock_init(x,y)
348 #define LAZY_RWLOCK_DESTROY(x) pthread_rwlock_destroy(x)
352 /** An invalid page number.
353 * Mainly used to denote an empty tree.
355 #define P_INVALID (~0UL)
357 /** Test if a flag \b f is set in a flag word \b w. */
358 #define F_ISSET(w, f) (((w) & (f)) == (f))
360 /** Used for offsets within a single page.
361 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
364 typedef uint16_t indx_t;
366 /** Default size of memory map.
367 * This is certainly too small for any actual applications. Apps should always set
368 * the size explicitly using #mdb_env_set_mapsize().
370 #define DEFAULT_MAPSIZE 1048576
372 /** @defgroup readers Reader Lock Table
373 * Readers don't acquire any locks for their data access. Instead, they
374 * simply record their transaction ID in the reader table. The reader
375 * mutex is needed just to find an empty slot in the reader table. The
376 * slot's address is saved in thread-specific data so that subsequent read
377 * transactions started by the same thread need no further locking to proceed.
379 * Since the database uses multi-version concurrency control, readers don't
380 * actually need any locking. This table is used to keep track of which
381 * readers are using data from which old transactions, so that we'll know
382 * when a particular old transaction is no longer in use. Old transactions
383 * that have discarded any data pages can then have those pages reclaimed
384 * for use by a later write transaction.
386 * The lock table is constructed such that reader slots are aligned with the
387 * processor's cache line size. Any slot is only ever used by one thread.
388 * This alignment guarantees that there will be no contention or cache
389 * thrashing as threads update their own slot info, and also eliminates
390 * any need for locking when accessing a slot.
392 * A writer thread will scan every slot in the table to determine the oldest
393 * outstanding reader transaction. Any freed pages older than this will be
394 * reclaimed by the writer. The writer doesn't use any locks when scanning
395 * this table. This means that there's no guarantee that the writer will
396 * see the most up-to-date reader info, but that's not required for correct
397 * operation - all we need is to know the upper bound on the oldest reader,
398 * we don't care at all about the newest reader. So the only consequence of
399 * reading stale information here is that old pages might hang around a
400 * while longer before being reclaimed. That's actually good anyway, because
401 * the longer we delay reclaiming old pages, the more likely it is that a
402 * string of contiguous pages can be found after coalescing old pages from
403 * many old transactions together.
405 * @todo We don't actually do such coalescing yet, we grab pages from one
406 * old transaction at a time.
409 /** Number of slots in the reader table.
410 * This value was chosen somewhat arbitrarily. 126 readers plus a
411 * couple mutexes fit exactly into 8KB on my development machine.
412 * Applications should set the table size using #mdb_env_set_maxreaders().
414 #define DEFAULT_READERS 126
416 /** The size of a CPU cache line in bytes. We want our lock structures
417 * aligned to this size to avoid false cache line sharing in the
419 * This value works for most CPUs. For Itanium this should be 128.
425 /** The information we store in a single slot of the reader table.
426 * In addition to a transaction ID, we also record the process and
427 * thread ID that owns a slot, so that we can detect stale information,
428 * e.g. threads or processes that went away without cleaning up.
429 * @note We currently don't check for stale records. We simply re-init
430 * the table when we know that we're the only process opening the
433 typedef struct MDB_rxbody {
434 /** The current Transaction ID when this transaction began.
435 * Multiple readers that start at the same time will probably have the
436 * same ID here. Again, it's not important to exclude them from
437 * anything; all we need to know is which version of the DB they
438 * started from so we can avoid overwriting any data used in that
439 * particular version.
442 /** The process ID of the process owning this reader txn. */
444 /** The thread ID of the thread owning this txn. */
448 /** The actual reader record, with cacheline padding. */
449 typedef struct MDB_reader {
452 /** shorthand for mrb_txnid */
453 #define mr_txnid mru.mrx.mrb_txnid
454 #define mr_pid mru.mrx.mrb_pid
455 #define mr_tid mru.mrx.mrb_tid
456 /** cache line alignment */
457 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
461 /** The header for the reader table.
462 * The table resides in a memory-mapped file. (This is a different file
463 * than is used for the main database.)
465 * For POSIX the actual mutexes reside in the shared memory of this
466 * mapped file. On Windows, mutexes are named objects allocated by the
467 * kernel; we store the mutex names in this mapped file so that other
468 * processes can grab them. This same approach is also used on
469 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
470 * process-shared POSIX mutexes. For these cases where a named object
471 * is used, the object name is derived from a 64 bit FNV hash of the
472 * environment pathname. As such, naming collisions are extremely
473 * unlikely. If a collision occurs, the results are unpredictable.
475 typedef struct MDB_txbody {
476 /** Stamp identifying this as an MDB lock file. It must be set
479 /** Version number of this lock file. Must be set to #MDB_VERSION. */
480 uint32_t mtb_version;
481 #if defined(_WIN32) || defined(__APPLE__)
482 char mtb_rmname[MNAME_LEN];
484 /** Mutex protecting access to this table.
485 * This is the reader lock that #LOCK_MUTEX_R acquires.
487 pthread_mutex_t mtb_mutex;
489 /** The ID of the last transaction committed to the database.
490 * This is recorded here only for convenience; the value can always
491 * be determined by reading the main database meta pages.
494 /** The number of slots that have been used in the reader table.
495 * This always records the maximum count, it is not decremented
496 * when readers release their slots.
498 unsigned mtb_numreaders;
499 /** The ID of the most recent meta page in the database.
500 * This is recorded here only for convenience; the value can always
501 * be determined by reading the main database meta pages.
503 uint32_t mtb_me_toggle;
506 /** The actual reader table definition. */
507 typedef struct MDB_txninfo {
510 #define mti_magic mt1.mtb.mtb_magic
511 #define mti_version mt1.mtb.mtb_version
512 #define mti_mutex mt1.mtb.mtb_mutex
513 #define mti_rmname mt1.mtb.mtb_rmname
514 #define mti_txnid mt1.mtb.mtb_txnid
515 #define mti_numreaders mt1.mtb.mtb_numreaders
516 #define mti_me_toggle mt1.mtb.mtb_me_toggle
517 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
520 #if defined(_WIN32) || defined(__APPLE__)
521 char mt2_wmname[MNAME_LEN];
522 #define mti_wmname mt2.mt2_wmname
524 pthread_mutex_t mt2_wmutex;
525 #define mti_wmutex mt2.mt2_wmutex
527 char pad[(sizeof(pthread_mutex_t)+CACHELINE-1) & ~(CACHELINE-1)];
529 MDB_reader mti_readers[1];
533 /** Common header for all page types.
534 * Overflow records occupy a number of contiguous pages with no
535 * headers on any page after the first.
537 typedef struct MDB_page {
538 #define mp_pgno mp_p.p_pgno
539 #define mp_next mp_p.p_next
541 pgno_t p_pgno; /**< page number */
542 void * p_next; /**< for in-memory list of freed structs */
545 /** @defgroup mdb_page Page Flags
547 * Flags for the page headers.
550 #define P_BRANCH 0x01 /**< branch page */
551 #define P_LEAF 0x02 /**< leaf page */
552 #define P_OVERFLOW 0x04 /**< overflow page */
553 #define P_META 0x08 /**< meta page */
554 #define P_DIRTY 0x10 /**< dirty page */
555 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
556 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
558 uint16_t mp_flags; /**< @ref mdb_page */
559 #define mp_lower mp_pb.pb.pb_lower
560 #define mp_upper mp_pb.pb.pb_upper
561 #define mp_pages mp_pb.pb_pages
564 indx_t pb_lower; /**< lower bound of free space */
565 indx_t pb_upper; /**< upper bound of free space */
567 uint32_t pb_pages; /**< number of overflow pages */
569 indx_t mp_ptrs[1]; /**< dynamic size */
572 /** Size of the page header, excluding dynamic data at the end */
573 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
575 /** Address of first usable data byte in a page, after the header */
576 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
578 /** Number of nodes on a page */
579 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
581 /** The amount of space remaining in the page */
582 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
584 /** The percentage of space used in the page, in tenths of a percent. */
585 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
586 ((env)->me_psize - PAGEHDRSZ))
587 /** The minimum page fill factor, in tenths of a percent.
588 * Pages emptier than this are candidates for merging.
590 #define FILL_THRESHOLD 250
592 /** Test if a page is a leaf page */
593 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
594 /** Test if a page is a LEAF2 page */
595 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
596 /** Test if a page is a branch page */
597 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
598 /** Test if a page is an overflow page */
599 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
600 /** Test if a page is a sub page */
601 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
603 /** The number of overflow pages needed to store the given size. */
604 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
606 /** Header for a single key/data pair within a page.
607 * We guarantee 2-byte alignment for nodes.
609 typedef struct MDB_node {
610 /** lo and hi are used for data size on leaf nodes and for
611 * child pgno on branch nodes. On 64 bit platforms, flags
612 * is also used for pgno. (Branch nodes have no flags).
613 * They are in host byte order in case that lets some
614 * accesses be optimized into a 32-bit word access.
616 #define mn_lo mn_offset[BYTE_ORDER!=LITTLE_ENDIAN]
617 #define mn_hi mn_offset[BYTE_ORDER==LITTLE_ENDIAN] /**< part of dsize or pgno */
618 unsigned short mn_offset[2]; /**< storage for #mn_lo and #mn_hi */
619 /** @defgroup mdb_node Node Flags
621 * Flags for node headers.
624 #define F_BIGDATA 0x01 /**< data put on overflow page */
625 #define F_SUBDATA 0x02 /**< data is a sub-database */
626 #define F_DUPDATA 0x04 /**< data has duplicates */
628 /** valid flags for #mdb_node_add() */
629 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
632 unsigned short mn_flags; /**< @ref mdb_node */
633 unsigned short mn_ksize; /**< key size */
634 char mn_data[1]; /**< key and data are appended here */
637 /** Size of the node header, excluding dynamic data at the end */
638 #define NODESIZE offsetof(MDB_node, mn_data)
640 /** Bit position of top word in page number, for shifting mn_flags */
641 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
643 /** Size of a node in a branch page with a given key.
644 * This is just the node header plus the key, there is no data.
646 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
648 /** Size of a node in a leaf page with a given key and data.
649 * This is node header plus key plus data size.
651 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
653 /** Address of node \b i in page \b p */
654 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
656 /** Address of the key for the node */
657 #define NODEKEY(node) (void *)((node)->mn_data)
659 /** Address of the data for a node */
660 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
662 /** Get the page number pointed to by a branch node */
663 #define NODEPGNO(node) \
664 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
665 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
666 /** Set the page number in a branch node */
667 #define SETPGNO(node,pgno) do { \
668 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
669 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
671 /** Get the size of the data in a leaf node */
672 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
673 /** Set the size of the data for a leaf node */
674 #define SETDSZ(node,size) do { \
675 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
676 /** The size of a key in a node */
677 #define NODEKSZ(node) ((node)->mn_ksize)
679 /** Copy a page number from src to dst */
681 #define COPY_PGNO(dst,src) dst = src
683 #if SIZE_MAX > 4294967295UL
684 #define COPY_PGNO(dst,src) do { \
685 unsigned short *s, *d; \
686 s = (unsigned short *)&(src); \
687 d = (unsigned short *)&(dst); \
694 #define COPY_PGNO(dst,src) do { \
695 unsigned short *s, *d; \
696 s = (unsigned short *)&(src); \
697 d = (unsigned short *)&(dst); \
703 /** The address of a key in a LEAF2 page.
704 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
705 * There are no node headers, keys are stored contiguously.
707 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
709 /** Set the \b node's key into \b key, if requested. */
710 #define MDB_SET_KEY(node, key) { if ((key) != NULL) { \
711 (key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node); } }
713 /** Information about a single database in the environment. */
714 typedef struct MDB_db {
715 uint32_t md_pad; /**< also ksize for LEAF2 pages */
716 uint16_t md_flags; /**< @ref mdb_open */
717 uint16_t md_depth; /**< depth of this tree */
718 pgno_t md_branch_pages; /**< number of internal pages */
719 pgno_t md_leaf_pages; /**< number of leaf pages */
720 pgno_t md_overflow_pages; /**< number of overflow pages */
721 size_t md_entries; /**< number of data items */
722 pgno_t md_root; /**< the root page of this tree */
725 /** Handle for the DB used to track free pages. */
727 /** Handle for the default DB. */
730 /** Meta page content. */
731 typedef struct MDB_meta {
732 /** Stamp identifying this as an MDB data file. It must be set
735 /** Version number of this lock file. Must be set to #MDB_VERSION. */
737 void *mm_address; /**< address for fixed mapping */
738 size_t mm_mapsize; /**< size of mmap region */
739 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
740 /** The size of pages used in this DB */
741 #define mm_psize mm_dbs[0].md_pad
742 /** Any persistent environment flags. @ref mdb_env */
743 #define mm_flags mm_dbs[0].md_flags
744 pgno_t mm_last_pg; /**< last used page in file */
745 txnid_t mm_txnid; /**< txnid that committed this page */
748 /** Auxiliary DB info.
749 * The information here is mostly static/read-only. There is
750 * only a single copy of this record in the environment.
752 typedef struct MDB_dbx {
753 MDB_val md_name; /**< name of the database */
754 MDB_cmp_func *md_cmp; /**< function for comparing keys */
755 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
756 MDB_rel_func *md_rel; /**< user relocate function */
757 void *md_relctx; /**< user-provided context for md_rel */
760 /** A database transaction.
761 * Every operation requires a transaction handle.
764 MDB_txn *mt_parent; /**< parent of a nested txn */
765 MDB_txn *mt_child; /**< nested txn under this txn */
766 pgno_t mt_next_pgno; /**< next unallocated page */
767 /** The ID of this transaction. IDs are integers incrementing from 1.
768 * Only committed write transactions increment the ID. If a transaction
769 * aborts, the ID may be re-used by the next writer.
772 MDB_env *mt_env; /**< the DB environment */
773 /** The list of pages that became unused during this transaction.
777 ID2L dirty_list; /**< modified pages */
778 MDB_reader *reader; /**< this thread's slot in the reader table */
780 /** Array of records for each DB known in the environment. */
782 /** Array of MDB_db records for each known DB */
784 /** @defgroup mt_dbflag Transaction DB Flags
788 #define DB_DIRTY 0x01 /**< DB was written in this txn */
789 #define DB_STALE 0x02 /**< DB record is older than txnID */
791 /** Array of cursors for each DB */
792 MDB_cursor **mt_cursors;
793 /** Array of flags for each DB */
794 unsigned char *mt_dbflags;
795 /** Number of DB records in use. This number only ever increments;
796 * we don't decrement it when individual DB handles are closed.
800 /** @defgroup mdb_txn Transaction Flags
804 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
805 #define MDB_TXN_ERROR 0x02 /**< an error has occurred */
807 unsigned int mt_flags; /**< @ref mdb_txn */
808 /** Tracks which of the two meta pages was used at the start
809 * of this transaction.
811 unsigned int mt_toggle;
814 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
815 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
816 * raise this on a 64 bit machine.
818 #define CURSOR_STACK 32
822 /** Cursors are used for all DB operations */
824 /** Next cursor on this DB in this txn */
826 /** Original cursor if this is a shadow */
828 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
829 struct MDB_xcursor *mc_xcursor;
830 /** The transaction that owns this cursor */
832 /** The database handle this cursor operates on */
834 /** The database record for this cursor */
836 /** The database auxiliary record for this cursor */
838 /** The @ref mt_dbflag for this database */
839 unsigned char *mc_dbflag;
840 unsigned short mc_snum; /**< number of pushed pages */
841 unsigned short mc_top; /**< index of top page, mc_snum-1 */
842 /** @defgroup mdb_cursor Cursor Flags
844 * Cursor state flags.
847 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
848 #define C_EOF 0x02 /**< No more data */
849 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
850 #define C_SHADOW 0x08 /**< Cursor is a dup from a parent txn */
851 #define C_ALLOCD 0x10 /**< Cursor was malloc'd */
853 unsigned int mc_flags; /**< @ref mdb_cursor */
854 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
855 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
858 /** Context for sorted-dup records.
859 * We could have gone to a fully recursive design, with arbitrarily
860 * deep nesting of sub-databases. But for now we only handle these
861 * levels - main DB, optional sub-DB, sorted-duplicate DB.
863 typedef struct MDB_xcursor {
864 /** A sub-cursor for traversing the Dup DB */
865 MDB_cursor mx_cursor;
866 /** The database record for this Dup DB */
868 /** The auxiliary DB record for this Dup DB */
870 /** The @ref mt_dbflag for this Dup DB */
871 unsigned char mx_dbflag;
874 /** A set of pages freed by an earlier transaction. */
875 typedef struct MDB_oldpages {
876 /** Usually we only read one record from the FREEDB at a time, but
877 * in case we read more, this will chain them together.
879 struct MDB_oldpages *mo_next;
880 /** The ID of the transaction in which these pages were freed. */
882 /** An #IDL of the pages */
883 pgno_t mo_pages[1]; /* dynamic */
886 /** The database environment. */
888 HANDLE me_fd; /**< The main data file */
889 HANDLE me_lfd; /**< The lock file */
890 HANDLE me_mfd; /**< just for writing the meta pages */
891 /** Failed to update the meta page. Probably an I/O error. */
892 #define MDB_FATAL_ERROR 0x80000000U
893 uint32_t me_flags; /**< @ref mdb_env */
894 uint32_t me_extrapad; /**< unused for now */
895 unsigned int me_maxreaders; /**< size of the reader table */
896 MDB_dbi me_numdbs; /**< number of DBs opened */
897 MDB_dbi me_maxdbs; /**< size of the DB table */
898 char *me_path; /**< path to the DB files */
899 char *me_map; /**< the memory map of the data file */
900 MDB_txninfo *me_txns; /**< the memory map of the lock file */
901 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
902 MDB_txn *me_txn; /**< current write transaction */
903 size_t me_mapsize; /**< size of the data memory map */
904 off_t me_size; /**< current file size */
905 pgno_t me_maxpg; /**< me_mapsize / me_psize */
906 unsigned int me_psize; /**< size of a page, from #GET_PAGESIZE */
907 unsigned int me_db_toggle; /**< which DB table is current */
908 txnid_t me_wtxnid; /**< ID of last txn we committed */
909 MDB_dbx *me_dbxs; /**< array of static DB info */
910 MDB_db *me_dbs[2]; /**< two arrays of MDB_db info */
911 MDB_oldpages *me_pghead; /**< list of old page records */
912 pthread_key_t me_txkey; /**< thread-key for readers */
913 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
914 /** IDL of pages that became unused in a write txn */
916 /** ID2L of pages that were written during a write txn */
917 ID2 me_dirty_list[MDB_IDL_UM_SIZE];
918 /** rwlock for the DB tables, if #LAZY_LOCKS is false */
919 LAZY_RWLOCK_DEF(me_dblock)
921 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
925 sem_t *me_rmutex; /* Apple doesn't support shared mutexes */
929 /** max number of pages to commit in one writev() call */
930 #define MDB_COMMIT_PAGES 64
932 static MDB_page *mdb_page_alloc(MDB_cursor *mc, int num);
933 static MDB_page *mdb_page_new(MDB_cursor *mc, uint32_t flags, int num);
934 static int mdb_page_touch(MDB_cursor *mc);
936 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
937 static int mdb_page_search_root(MDB_cursor *mc,
938 MDB_val *key, int modify);
939 static int mdb_page_search(MDB_cursor *mc,
940 MDB_val *key, int modify);
941 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
942 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
943 pgno_t newpgno, unsigned int nflags);
945 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
946 static int mdb_env_read_meta(MDB_env *env, int *which);
947 static int mdb_env_write_meta(MDB_txn *txn);
949 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
950 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
951 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
952 static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
953 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
954 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
955 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
956 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
957 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
959 static int mdb_rebalance(MDB_cursor *mc);
960 static int mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
962 static void mdb_cursor_pop(MDB_cursor *mc);
963 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
965 static int mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
966 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
967 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
968 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
969 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
971 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
972 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
974 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
975 static void mdb_xcursor_init0(MDB_cursor *mc);
976 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
978 static int mdb_drop0(MDB_cursor *mc, int subs);
979 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
982 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
986 static SECURITY_DESCRIPTOR mdb_null_sd;
987 static SECURITY_ATTRIBUTES mdb_all_sa;
988 static int mdb_sec_inited;
991 /** Return the library version info. */
993 mdb_version(int *major, int *minor, int *patch)
995 if (major) *major = MDB_VERSION_MAJOR;
996 if (minor) *minor = MDB_VERSION_MINOR;
997 if (patch) *patch = MDB_VERSION_PATCH;
998 return MDB_VERSION_STRING;
1001 /** Table of descriptions for MDB @ref errors */
1002 static char *const mdb_errstr[] = {
1003 "MDB_KEYEXIST: Key/data pair already exists",
1004 "MDB_NOTFOUND: No matching key/data pair found",
1005 "MDB_PAGE_NOTFOUND: Requested page not found",
1006 "MDB_CORRUPTED: Located page was wrong type",
1007 "MDB_PANIC: Update of meta page failed",
1008 "MDB_VERSION_MISMATCH: Database environment version mismatch"
1012 mdb_strerror(int err)
1015 return ("Successful return: 0");
1017 if (err >= MDB_KEYEXIST && err <= MDB_VERSION_MISMATCH)
1018 return mdb_errstr[err - MDB_KEYEXIST];
1020 return strerror(err);
1024 /** Display a key in hexadecimal and return the address of the result.
1025 * @param[in] key the key to display
1026 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1027 * @return The key in hexadecimal form.
1030 mdb_dkey(MDB_val *key, char *buf)
1033 unsigned char *c = key->mv_data;
1035 if (key->mv_size > MAXKEYSIZE)
1036 return "MAXKEYSIZE";
1037 /* may want to make this a dynamic check: if the key is mostly
1038 * printable characters, print it as-is instead of converting to hex.
1041 for (i=0; i<key->mv_size; i++)
1042 ptr += sprintf(ptr, "%02x", *c++);
1044 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1051 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1053 return txn->mt_dbxs[dbi].md_cmp(a, b);
1057 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1059 if (txn->mt_dbxs[dbi].md_dcmp)
1060 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1062 return EINVAL; /* too bad you can't distinguish this from a valid result */
1065 /** Allocate a single page.
1066 * Re-use old malloc'd pages first, otherwise just malloc.
1069 mdb_page_malloc(MDB_cursor *mc) {
1071 if (mc->mc_txn->mt_env->me_dpages) {
1072 ret = mc->mc_txn->mt_env->me_dpages;
1073 mc->mc_txn->mt_env->me_dpages = ret->mp_next;
1075 ret = malloc(mc->mc_txn->mt_env->me_psize);
1080 /** Allocate pages for writing.
1081 * If there are free pages available from older transactions, they
1082 * will be re-used first. Otherwise a new page will be allocated.
1083 * @param[in] mc cursor A cursor handle identifying the transaction and
1084 * database for which we are allocating.
1085 * @param[in] num the number of pages to allocate.
1086 * @return Address of the allocated page(s). Requests for multiple pages
1087 * will always be satisfied by a single contiguous chunk of memory.
1090 mdb_page_alloc(MDB_cursor *mc, int num)
1092 MDB_txn *txn = mc->mc_txn;
1094 pgno_t pgno = P_INVALID;
1097 if (txn->mt_txnid > 2) {
1099 if (!txn->mt_env->me_pghead && mc->mc_dbi != FREE_DBI &&
1100 txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
1101 /* See if there's anything in the free DB */
1104 txnid_t *kptr, oldest;
1106 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1107 mdb_page_search(&m2, NULL, 0);
1108 leaf = NODEPTR(m2.mc_pg[m2.mc_top], 0);
1109 kptr = (txnid_t *)NODEKEY(leaf);
1113 oldest = txn->mt_txnid - 1;
1114 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
1115 txnid_t mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
1116 if (mr && mr < oldest)
1121 if (oldest > *kptr) {
1122 /* It's usable, grab it.
1128 mdb_node_read(txn, leaf, &data);
1129 idl = (ID *) data.mv_data;
1130 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
1131 mop->mo_next = txn->mt_env->me_pghead;
1132 mop->mo_txnid = *kptr;
1133 txn->mt_env->me_pghead = mop;
1134 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
1139 DPRINTF("IDL read txn %zu root %zu num %zu",
1140 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1141 for (i=0; i<idl[0]; i++) {
1142 DPRINTF("IDL %zu", idl[i+1]);
1146 /* drop this IDL from the DB */
1147 m2.mc_ki[m2.mc_top] = 0;
1148 m2.mc_flags = C_INITIALIZED;
1149 mdb_cursor_del(&m2, 0);
1152 if (txn->mt_env->me_pghead) {
1153 MDB_oldpages *mop = txn->mt_env->me_pghead;
1155 /* FIXME: For now, always use fresh pages. We
1156 * really ought to search the free list for a
1161 /* peel pages off tail, so we only have to truncate the list */
1162 pgno = MDB_IDL_LAST(mop->mo_pages);
1163 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
1165 if (mop->mo_pages[2] > mop->mo_pages[1])
1166 mop->mo_pages[0] = 0;
1170 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
1171 txn->mt_env->me_pghead = mop->mo_next;
1178 if (pgno == P_INVALID) {
1179 /* DB size is maxed out */
1180 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg) {
1181 DPUTS("DB size maxed out");
1185 if (txn->mt_env->me_dpages && num == 1) {
1186 np = txn->mt_env->me_dpages;
1187 txn->mt_env->me_dpages = np->mp_next;
1189 if ((np = malloc(txn->mt_env->me_psize * num )) == NULL)
1192 if (pgno == P_INVALID) {
1193 np->mp_pgno = txn->mt_next_pgno;
1194 txn->mt_next_pgno += num;
1198 mid.mid = np->mp_pgno;
1200 mdb_mid2l_insert(txn->mt_u.dirty_list, &mid);
1205 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1206 * @param[in] mc cursor pointing to the page to be touched
1207 * @return 0 on success, non-zero on failure.
1210 mdb_page_touch(MDB_cursor *mc)
1212 MDB_page *mp = mc->mc_pg[mc->mc_top];
1215 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1217 if ((np = mdb_page_alloc(mc, 1)) == NULL)
1219 DPRINTF("touched db %u page %zu -> %zu", mc->mc_dbi, mp->mp_pgno, np->mp_pgno);
1220 assert(mp->mp_pgno != np->mp_pgno);
1221 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
1223 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1226 mp->mp_flags |= P_DIRTY;
1229 /* Adjust other cursors pointing to mp */
1230 if (mc->mc_flags & C_SUB) {
1231 MDB_cursor *m2, *m3;
1232 MDB_dbi dbi = mc->mc_dbi-1;
1234 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
1235 if (m2 == mc) continue;
1236 m3 = &m2->mc_xcursor->mx_cursor;
1237 if (m3->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1238 m3->mc_pg[mc->mc_top] = mp;
1244 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
1245 if (m2 == mc) continue;
1246 if (m2->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1247 m2->mc_pg[mc->mc_top] = mp;
1251 mc->mc_pg[mc->mc_top] = mp;
1252 /** If this page has a parent, update the parent to point to
1256 SETPGNO(NODEPTR(mc->mc_pg[mc->mc_top-1], mc->mc_ki[mc->mc_top-1]), mp->mp_pgno);
1258 mc->mc_db->md_root = mp->mp_pgno;
1259 } else if (mc->mc_txn->mt_parent) {
1262 /* If txn has a parent, make sure the page is in our
1265 if (mc->mc_txn->mt_u.dirty_list[0].mid) {
1266 unsigned x = mdb_mid2l_search(mc->mc_txn->mt_u.dirty_list, mp->mp_pgno);
1267 if (x <= mc->mc_txn->mt_u.dirty_list[0].mid &&
1268 mc->mc_txn->mt_u.dirty_list[x].mid == mp->mp_pgno) {
1269 if (mc->mc_txn->mt_u.dirty_list[x].mptr != mp) {
1270 mp = mc->mc_txn->mt_u.dirty_list[x].mptr;
1271 mc->mc_pg[mc->mc_top] = mp;
1277 np = mdb_page_malloc(mc);
1278 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1279 mid.mid = np->mp_pgno;
1281 mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &mid);
1289 mdb_env_sync(MDB_env *env, int force)
1292 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1293 if (MDB_FDATASYNC(env->me_fd))
1299 /** Make shadow copies of all of parent txn's cursors */
1301 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
1303 MDB_cursor *mc, *m2;
1304 unsigned int i, j, size;
1306 for (i=0;i<src->mt_numdbs; i++) {
1307 if (src->mt_cursors[i]) {
1308 size = sizeof(MDB_cursor);
1309 if (src->mt_cursors[i]->mc_xcursor)
1310 size += sizeof(MDB_xcursor);
1311 for (m2 = src->mt_cursors[i]; m2; m2=m2->mc_next) {
1318 mc->mc_db = &dst->mt_dbs[i];
1319 mc->mc_dbx = m2->mc_dbx;
1320 mc->mc_dbflag = &dst->mt_dbflags[i];
1321 mc->mc_snum = m2->mc_snum;
1322 mc->mc_top = m2->mc_top;
1323 mc->mc_flags = m2->mc_flags | C_SHADOW;
1324 for (j=0; j<mc->mc_snum; j++) {
1325 mc->mc_pg[j] = m2->mc_pg[j];
1326 mc->mc_ki[j] = m2->mc_ki[j];
1328 if (m2->mc_xcursor) {
1329 MDB_xcursor *mx, *mx2;
1330 mx = (MDB_xcursor *)(mc+1);
1331 mc->mc_xcursor = mx;
1332 mx2 = m2->mc_xcursor;
1333 mx->mx_db = mx2->mx_db;
1334 mx->mx_dbx = mx2->mx_dbx;
1335 mx->mx_dbflag = mx2->mx_dbflag;
1336 mx->mx_cursor.mc_txn = dst;
1337 mx->mx_cursor.mc_dbi = mx2->mx_cursor.mc_dbi;
1338 mx->mx_cursor.mc_db = &mx->mx_db;
1339 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
1340 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
1341 mx->mx_cursor.mc_snum = mx2->mx_cursor.mc_snum;
1342 mx->mx_cursor.mc_top = mx2->mx_cursor.mc_top;
1343 mx->mx_cursor.mc_flags = mx2->mx_cursor.mc_flags | C_SHADOW;
1344 for (j=0; j<mx2->mx_cursor.mc_snum; j++) {
1345 mx->mx_cursor.mc_pg[j] = mx2->mx_cursor.mc_pg[j];
1346 mx->mx_cursor.mc_ki[j] = mx2->mx_cursor.mc_ki[j];
1349 mc->mc_xcursor = NULL;
1351 mc->mc_next = dst->mt_cursors[i];
1352 dst->mt_cursors[i] = mc;
1359 /** Merge shadow cursors back into parent's */
1361 mdb_cursor_merge(MDB_txn *txn)
1364 for (i=0; i<txn->mt_numdbs; i++) {
1365 if (txn->mt_cursors[i]) {
1367 while ((mc = txn->mt_cursors[i])) {
1368 txn->mt_cursors[i] = mc->mc_next;
1369 if (mc->mc_flags & C_SHADOW) {
1370 MDB_cursor *m2 = mc->mc_orig;
1372 m2->mc_snum = mc->mc_snum;
1373 m2->mc_top = mc->mc_top;
1374 for (j=0; j<mc->mc_snum; j++) {
1375 m2->mc_pg[j] = mc->mc_pg[j];
1376 m2->mc_ki[j] = mc->mc_ki[j];
1379 if (mc->mc_flags & C_ALLOCD)
1387 mdb_txn_reset0(MDB_txn *txn);
1389 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
1390 * @param[in] txn the transaction handle to initialize
1391 * @return 0 on success, non-zero on failure. This can only
1392 * fail for read-only transactions, and then only if the
1393 * reader table is full.
1396 mdb_txn_renew0(MDB_txn *txn)
1398 MDB_env *env = txn->mt_env;
1401 if (txn->mt_flags & MDB_TXN_RDONLY) {
1402 MDB_reader *r = pthread_getspecific(env->me_txkey);
1405 pid_t pid = getpid();
1406 pthread_t tid = pthread_self();
1409 for (i=0; i<env->me_txns->mti_numreaders; i++)
1410 if (env->me_txns->mti_readers[i].mr_pid == 0)
1412 if (i == env->me_maxreaders) {
1413 UNLOCK_MUTEX_R(env);
1416 env->me_txns->mti_readers[i].mr_pid = pid;
1417 env->me_txns->mti_readers[i].mr_tid = tid;
1418 if (i >= env->me_txns->mti_numreaders)
1419 env->me_txns->mti_numreaders = i+1;
1420 UNLOCK_MUTEX_R(env);
1421 r = &env->me_txns->mti_readers[i];
1422 pthread_setspecific(env->me_txkey, r);
1424 txn->mt_toggle = env->me_txns->mti_me_toggle;
1425 txn->mt_txnid = env->me_txns->mti_txnid;
1426 /* This happens if a different process was the
1427 * last writer to the DB.
1429 if (env->me_wtxnid < txn->mt_txnid)
1430 mt_dbflag = DB_STALE;
1431 r->mr_txnid = txn->mt_txnid;
1432 txn->mt_u.reader = r;
1436 txn->mt_txnid = env->me_txns->mti_txnid;
1437 if (env->me_wtxnid < txn->mt_txnid)
1438 mt_dbflag = DB_STALE;
1440 txn->mt_toggle = env->me_txns->mti_me_toggle;
1441 txn->mt_u.dirty_list = env->me_dirty_list;
1442 txn->mt_u.dirty_list[0].mid = 0;
1443 txn->mt_free_pgs = env->me_free_pgs;
1444 txn->mt_free_pgs[0] = 0;
1445 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1449 /* Copy the DB arrays */
1450 LAZY_RWLOCK_RDLOCK(&env->me_dblock);
1451 txn->mt_numdbs = env->me_numdbs;
1452 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
1453 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
1454 if (txn->mt_numdbs > 2)
1455 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
1456 (txn->mt_numdbs - 2) * sizeof(MDB_db));
1457 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1459 memset(txn->mt_dbflags, mt_dbflag, env->me_numdbs);
1465 mdb_txn_renew(MDB_txn *txn)
1472 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
1473 DPUTS("environment had fatal error, must shutdown!");
1477 rc = mdb_txn_renew0(txn);
1478 if (rc == MDB_SUCCESS) {
1479 DPRINTF("renew txn %zu%c %p on mdbenv %p, root page %zu",
1480 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1481 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1487 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
1492 if (env->me_flags & MDB_FATAL_ERROR) {
1493 DPUTS("environment had fatal error, must shutdown!");
1497 /* parent already has an active child txn */
1498 if (parent->mt_child) {
1502 size = sizeof(MDB_txn) + env->me_maxdbs * (sizeof(MDB_db)+1);
1503 if (!(flags & MDB_RDONLY))
1504 size += env->me_maxdbs * sizeof(MDB_cursor *);
1506 if ((txn = calloc(1, size)) == NULL) {
1507 DPRINTF("calloc: %s", strerror(ErrCode()));
1510 txn->mt_dbs = (MDB_db *)(txn+1);
1511 if (flags & MDB_RDONLY) {
1512 txn->mt_flags |= MDB_TXN_RDONLY;
1513 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
1515 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
1516 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
1521 txn->mt_free_pgs = mdb_midl_alloc();
1522 if (!txn->mt_free_pgs) {
1526 txn->mt_u.dirty_list = malloc(sizeof(ID2)*MDB_IDL_UM_SIZE);
1527 if (!txn->mt_u.dirty_list) {
1528 free(txn->mt_free_pgs);
1532 txn->mt_txnid = parent->mt_txnid;
1533 txn->mt_toggle = parent->mt_toggle;
1534 txn->mt_u.dirty_list[0].mid = 0;
1535 txn->mt_free_pgs[0] = 0;
1536 txn->mt_next_pgno = parent->mt_next_pgno;
1537 parent->mt_child = txn;
1538 txn->mt_parent = parent;
1539 txn->mt_numdbs = parent->mt_numdbs;
1540 txn->mt_dbxs = parent->mt_dbxs;
1541 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
1542 memcpy(txn->mt_dbflags, parent->mt_dbflags, txn->mt_numdbs);
1543 mdb_cursor_shadow(parent, txn);
1546 rc = mdb_txn_renew0(txn);
1552 DPRINTF("begin txn %zu%c %p on mdbenv %p, root page %zu",
1553 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1554 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
1560 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
1561 * @param[in] txn the transaction handle to reset
1564 mdb_txn_reset0(MDB_txn *txn)
1566 MDB_env *env = txn->mt_env;
1568 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1569 txn->mt_u.reader->mr_txnid = 0;
1575 /* close(free) all cursors */
1576 for (i=0; i<txn->mt_numdbs; i++) {
1577 if (txn->mt_cursors[i]) {
1579 while ((mc = txn->mt_cursors[i])) {
1580 txn->mt_cursors[i] = mc->mc_next;
1581 if (mc->mc_flags & C_ALLOCD)
1587 /* return all dirty pages to dpage list */
1588 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1589 dp = txn->mt_u.dirty_list[i].mptr;
1590 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1591 dp->mp_next = txn->mt_env->me_dpages;
1592 txn->mt_env->me_dpages = dp;
1594 /* large pages just get freed directly */
1599 if (txn->mt_parent) {
1600 txn->mt_parent->mt_child = NULL;
1601 free(txn->mt_free_pgs);
1602 free(txn->mt_u.dirty_list);
1605 if (mdb_midl_shrink(&txn->mt_free_pgs))
1606 env->me_free_pgs = txn->mt_free_pgs;
1609 while ((mop = txn->mt_env->me_pghead)) {
1610 txn->mt_env->me_pghead = mop->mo_next;
1615 /* The writer mutex was locked in mdb_txn_begin. */
1616 UNLOCK_MUTEX_W(env);
1621 mdb_txn_reset(MDB_txn *txn)
1626 DPRINTF("reset txn %zu%c %p on mdbenv %p, root page %zu",
1627 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1628 (void *) txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1630 mdb_txn_reset0(txn);
1634 mdb_txn_abort(MDB_txn *txn)
1639 DPRINTF("abort txn %zu%c %p on mdbenv %p, root page %zu",
1640 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1641 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1644 mdb_txn_abort(txn->mt_child);
1646 mdb_txn_reset0(txn);
1651 mdb_txn_commit(MDB_txn *txn)
1662 assert(txn != NULL);
1663 assert(txn->mt_env != NULL);
1665 if (txn->mt_child) {
1666 mdb_txn_commit(txn->mt_child);
1667 txn->mt_child = NULL;
1672 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1673 if (txn->mt_numdbs > env->me_numdbs) {
1674 /* update the DB tables */
1675 int toggle = !env->me_db_toggle;
1679 ip = &env->me_dbs[toggle][env->me_numdbs];
1680 jp = &txn->mt_dbs[env->me_numdbs];
1681 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1682 for (i = env->me_numdbs; i < txn->mt_numdbs; i++) {
1686 env->me_db_toggle = toggle;
1687 env->me_numdbs = txn->mt_numdbs;
1688 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1694 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1695 DPUTS("error flag is set, can't commit");
1697 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
1702 /* Merge (and close) our cursors with parent's */
1703 mdb_cursor_merge(txn);
1705 if (txn->mt_parent) {
1711 /* Update parent's DB table */
1712 ip = &txn->mt_parent->mt_dbs[2];
1713 jp = &txn->mt_dbs[2];
1714 for (i = 2; i < txn->mt_numdbs; i++) {
1715 if (ip->md_root != jp->md_root)
1719 txn->mt_parent->mt_numdbs = txn->mt_numdbs;
1721 /* Append our free list to parent's */
1722 mdb_midl_append_list(&txn->mt_parent->mt_free_pgs,
1724 mdb_midl_free(txn->mt_free_pgs);
1726 /* Merge our dirty list with parent's */
1727 dst = txn->mt_parent->mt_u.dirty_list;
1728 src = txn->mt_u.dirty_list;
1729 x = mdb_mid2l_search(dst, src[1].mid);
1730 for (y=1; y<=src[0].mid; y++) {
1731 while (x <= dst[0].mid && dst[x].mid != src[y].mid) x++;
1735 dst[x].mptr = src[y].mptr;
1738 for (; y<=src[0].mid; y++) {
1739 if (++x >= MDB_IDL_UM_MAX)
1744 free(txn->mt_u.dirty_list);
1745 txn->mt_parent->mt_child = NULL;
1750 if (txn != env->me_txn) {
1751 DPUTS("attempt to commit unknown transaction");
1756 if (!txn->mt_u.dirty_list[0].mid)
1759 DPRINTF("committing txn %zu %p on mdbenv %p, root page %zu",
1760 txn->mt_txnid, (void *)txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
1762 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1764 /* should only be one record now */
1765 if (env->me_pghead) {
1766 /* make sure first page of freeDB is touched and on freelist */
1767 mdb_page_search(&mc, NULL, 1);
1769 /* save to free list */
1770 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
1774 /* make sure last page of freeDB is touched and on freelist */
1775 key.mv_size = MAXKEYSIZE+1;
1777 mdb_page_search(&mc, &key, 1);
1779 mdb_midl_sort(txn->mt_free_pgs);
1783 ID *idl = txn->mt_free_pgs;
1784 DPRINTF("IDL write txn %zu root %zu num %zu",
1785 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1786 for (i=0; i<idl[0]; i++) {
1787 DPRINTF("IDL %zu", idl[i+1]);
1791 /* write to last page of freeDB */
1792 key.mv_size = sizeof(pgno_t);
1793 key.mv_data = &txn->mt_txnid;
1794 data.mv_data = txn->mt_free_pgs;
1795 /* The free list can still grow during this call,
1796 * despite the pre-emptive touches above. So check
1797 * and make sure the entire thing got written.
1800 i = txn->mt_free_pgs[0];
1801 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
1802 rc = mdb_cursor_put(&mc, &key, &data, 0);
1807 } while (i != txn->mt_free_pgs[0]);
1808 if (mdb_midl_shrink(&txn->mt_free_pgs))
1809 env->me_free_pgs = txn->mt_free_pgs;
1811 /* should only be one record now */
1812 if (env->me_pghead) {
1816 mop = env->me_pghead;
1817 env->me_pghead = NULL;
1818 key.mv_size = sizeof(pgno_t);
1819 key.mv_data = &mop->mo_txnid;
1820 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
1821 data.mv_data = mop->mo_pages;
1822 mdb_cursor_put(&mc, &key, &data, 0);
1826 /* Update DB root pointers. Their pages have already been
1827 * touched so this is all in-place and cannot fail.
1832 data.mv_size = sizeof(MDB_db);
1834 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
1835 for (i = 2; i < txn->mt_numdbs; i++) {
1836 if (txn->mt_dbflags[i] & DB_DIRTY) {
1837 data.mv_data = &txn->mt_dbs[i];
1838 mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
1843 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
1849 /* Windows actually supports scatter/gather I/O, but only on
1850 * unbuffered file handles. Since we're relying on the OS page
1851 * cache for all our data, that's self-defeating. So we just
1852 * write pages one at a time. We use the ov structure to set
1853 * the write offset, to at least save the overhead of a Seek
1857 memset(&ov, 0, sizeof(ov));
1858 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1860 dp = txn->mt_u.dirty_list[i].mptr;
1861 DPRINTF("committing page %zu", dp->mp_pgno);
1862 size = dp->mp_pgno * env->me_psize;
1863 ov.Offset = size & 0xffffffff;
1864 ov.OffsetHigh = size >> 16;
1865 ov.OffsetHigh >>= 16;
1866 /* clear dirty flag */
1867 dp->mp_flags &= ~P_DIRTY;
1868 wsize = env->me_psize;
1869 if (IS_OVERFLOW(dp)) wsize *= dp->mp_pages;
1870 rc = WriteFile(env->me_fd, dp, wsize, NULL, &ov);
1873 DPRINTF("WriteFile: %d", n);
1880 struct iovec iov[MDB_COMMIT_PAGES];
1884 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1885 dp = txn->mt_u.dirty_list[i].mptr;
1886 if (dp->mp_pgno != next) {
1888 DPRINTF("committing %u dirty pages", n);
1889 rc = writev(env->me_fd, iov, n);
1893 DPUTS("short write, filesystem full?");
1895 DPRINTF("writev: %s", strerror(n));
1902 lseek(env->me_fd, dp->mp_pgno * env->me_psize, SEEK_SET);
1905 DPRINTF("committing page %zu", dp->mp_pgno);
1906 iov[n].iov_len = env->me_psize;
1907 if (IS_OVERFLOW(dp)) iov[n].iov_len *= dp->mp_pages;
1908 iov[n].iov_base = (char *)dp;
1909 size += iov[n].iov_len;
1910 next = dp->mp_pgno + (IS_OVERFLOW(dp) ? dp->mp_pages : 1);
1911 /* clear dirty flag */
1912 dp->mp_flags &= ~P_DIRTY;
1913 if (++n >= MDB_COMMIT_PAGES) {
1923 DPRINTF("committing %u dirty pages", n);
1924 rc = writev(env->me_fd, iov, n);
1928 DPUTS("short write, filesystem full?");
1930 DPRINTF("writev: %s", strerror(n));
1937 /* Drop the dirty pages.
1939 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1940 dp = txn->mt_u.dirty_list[i].mptr;
1941 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1942 dp->mp_next = txn->mt_env->me_dpages;
1943 txn->mt_env->me_dpages = dp;
1947 txn->mt_u.dirty_list[i].mid = 0;
1949 txn->mt_u.dirty_list[0].mid = 0;
1951 if ((n = mdb_env_sync(env, 0)) != 0 ||
1952 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
1956 env->me_wtxnid = txn->mt_txnid;
1960 /* update the DB tables */
1962 int toggle = !env->me_db_toggle;
1966 ip = &env->me_dbs[toggle][2];
1967 jp = &txn->mt_dbs[2];
1968 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1969 for (i = 2; i < txn->mt_numdbs; i++) {
1970 if (ip->md_root != jp->md_root)
1975 env->me_db_toggle = toggle;
1976 env->me_numdbs = txn->mt_numdbs;
1977 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1980 UNLOCK_MUTEX_W(env);
1986 /** Read the environment parameters of a DB environment before
1987 * mapping it into memory.
1988 * @param[in] env the environment handle
1989 * @param[out] meta address of where to store the meta information
1990 * @return 0 on success, non-zero on failure.
1993 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
1995 char page[MDB_PAGESIZE];
2000 /* We don't know the page size yet, so use a minimum value.
2004 if (!ReadFile(env->me_fd, page, MDB_PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
2006 if ((rc = read(env->me_fd, page, MDB_PAGESIZE)) == 0)
2011 else if (rc != MDB_PAGESIZE) {
2015 DPRINTF("read: %s", strerror(err));
2019 p = (MDB_page *)page;
2021 if (!F_ISSET(p->mp_flags, P_META)) {
2022 DPRINTF("page %zu not a meta page", p->mp_pgno);
2027 if (m->mm_magic != MDB_MAGIC) {
2028 DPUTS("meta has invalid magic");
2032 if (m->mm_version != MDB_VERSION) {
2033 DPRINTF("database is version %u, expected version %u",
2034 m->mm_version, MDB_VERSION);
2035 return MDB_VERSION_MISMATCH;
2038 memcpy(meta, m, sizeof(*m));
2042 /** Write the environment parameters of a freshly created DB environment.
2043 * @param[in] env the environment handle
2044 * @param[out] meta address of where to store the meta information
2045 * @return 0 on success, non-zero on failure.
2048 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
2055 DPUTS("writing new meta page");
2057 GET_PAGESIZE(psize);
2059 meta->mm_magic = MDB_MAGIC;
2060 meta->mm_version = MDB_VERSION;
2061 meta->mm_psize = psize;
2062 meta->mm_last_pg = 1;
2063 meta->mm_flags = env->me_flags & 0xffff;
2064 meta->mm_flags |= MDB_INTEGERKEY;
2065 meta->mm_dbs[0].md_root = P_INVALID;
2066 meta->mm_dbs[1].md_root = P_INVALID;
2068 p = calloc(2, psize);
2070 p->mp_flags = P_META;
2073 memcpy(m, meta, sizeof(*meta));
2075 q = (MDB_page *)((char *)p + psize);
2078 q->mp_flags = P_META;
2081 memcpy(m, meta, sizeof(*meta));
2086 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
2087 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
2090 rc = write(env->me_fd, p, psize * 2);
2091 rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
2097 /** Update the environment info to commit a transaction.
2098 * @param[in] txn the transaction that's being committed
2099 * @return 0 on success, non-zero on failure.
2102 mdb_env_write_meta(MDB_txn *txn)
2105 MDB_meta meta, metab;
2107 int rc, len, toggle;
2113 assert(txn != NULL);
2114 assert(txn->mt_env != NULL);
2116 toggle = !txn->mt_toggle;
2117 DPRINTF("writing meta page %d for root page %zu",
2118 toggle, txn->mt_dbs[MAIN_DBI].md_root);
2122 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
2123 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
2125 ptr = (char *)&meta;
2126 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
2127 len = sizeof(MDB_meta) - off;
2130 meta.mm_dbs[0] = txn->mt_dbs[0];
2131 meta.mm_dbs[1] = txn->mt_dbs[1];
2132 meta.mm_last_pg = txn->mt_next_pgno - 1;
2133 meta.mm_txnid = txn->mt_txnid;
2136 off += env->me_psize;
2139 /* Write to the SYNC fd */
2142 memset(&ov, 0, sizeof(ov));
2144 WriteFile(env->me_mfd, ptr, len, (DWORD *)&rc, &ov);
2147 rc = pwrite(env->me_mfd, ptr, len, off);
2152 DPUTS("write failed, disk error?");
2153 /* On a failure, the pagecache still contains the new data.
2154 * Write some old data back, to prevent it from being used.
2155 * Use the non-SYNC fd; we know it will fail anyway.
2157 meta.mm_last_pg = metab.mm_last_pg;
2158 meta.mm_txnid = metab.mm_txnid;
2160 WriteFile(env->me_fd, ptr, len, NULL, &ov);
2162 r2 = pwrite(env->me_fd, ptr, len, off);
2164 env->me_flags |= MDB_FATAL_ERROR;
2167 /* Memory ordering issues are irrelevant; since the entire writer
2168 * is wrapped by wmutex, all of these changes will become visible
2169 * after the wmutex is unlocked. Since the DB is multi-version,
2170 * readers will get consistent data regardless of how fresh or
2171 * how stale their view of these values is.
2173 LAZY_MUTEX_LOCK(&env->me_txns->mti_mutex);
2174 txn->mt_env->me_txns->mti_me_toggle = toggle;
2175 txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
2176 LAZY_MUTEX_UNLOCK(&env->me_txns->mti_mutex);
2181 /** Check both meta pages to see which one is newer.
2182 * @param[in] env the environment handle
2183 * @param[out] which address of where to store the meta toggle ID
2184 * @return 0 on success, non-zero on failure.
2187 mdb_env_read_meta(MDB_env *env, int *which)
2191 assert(env != NULL);
2193 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
2196 DPRINTF("Using meta page %d", toggle);
2203 mdb_env_create(MDB_env **env)
2207 e = calloc(1, sizeof(MDB_env));
2211 e->me_free_pgs = mdb_midl_alloc();
2212 if (!e->me_free_pgs) {
2216 e->me_maxreaders = DEFAULT_READERS;
2218 e->me_fd = INVALID_HANDLE_VALUE;
2219 e->me_lfd = INVALID_HANDLE_VALUE;
2220 e->me_mfd = INVALID_HANDLE_VALUE;
2226 mdb_env_set_mapsize(MDB_env *env, size_t size)
2230 env->me_mapsize = size;
2232 env->me_maxpg = env->me_mapsize / env->me_psize;
2237 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
2241 env->me_maxdbs = dbs;
2246 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
2248 if (env->me_map || readers < 1)
2250 env->me_maxreaders = readers;
2255 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
2257 if (!env || !readers)
2259 *readers = env->me_maxreaders;
2263 /** Further setup required for opening an MDB environment
2266 mdb_env_open2(MDB_env *env, unsigned int flags)
2268 int i, newenv = 0, toggle;
2272 env->me_flags = flags;
2274 memset(&meta, 0, sizeof(meta));
2276 if ((i = mdb_env_read_header(env, &meta)) != 0) {
2279 DPUTS("new mdbenv");
2283 if (!env->me_mapsize) {
2284 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
2290 LONG sizelo, sizehi;
2291 sizelo = env->me_mapsize & 0xffffffff;
2292 sizehi = env->me_mapsize >> 16; /* pointless on WIN32, only needed on W64 */
2294 /* Windows won't create mappings for zero length files.
2295 * Just allocate the maxsize right now.
2298 SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
2299 if (!SetEndOfFile(env->me_fd))
2301 SetFilePointer(env->me_fd, 0, NULL, 0);
2303 mh = CreateFileMapping(env->me_fd, NULL, PAGE_READONLY,
2304 sizehi, sizelo, NULL);
2307 env->me_map = MapViewOfFileEx(mh, FILE_MAP_READ, 0, 0, env->me_mapsize,
2315 if (meta.mm_address && (flags & MDB_FIXEDMAP))
2317 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
2319 if (env->me_map == MAP_FAILED)
2324 meta.mm_mapsize = env->me_mapsize;
2325 if (flags & MDB_FIXEDMAP)
2326 meta.mm_address = env->me_map;
2327 i = mdb_env_init_meta(env, &meta);
2328 if (i != MDB_SUCCESS) {
2329 munmap(env->me_map, env->me_mapsize);
2333 env->me_psize = meta.mm_psize;
2335 env->me_maxpg = env->me_mapsize / env->me_psize;
2337 p = (MDB_page *)env->me_map;
2338 env->me_metas[0] = METADATA(p);
2339 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
2341 if ((i = mdb_env_read_meta(env, &toggle)) != 0)
2344 DPRINTF("opened database version %u, pagesize %u",
2345 env->me_metas[toggle]->mm_version, env->me_psize);
2346 DPRINTF("depth: %u", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_depth);
2347 DPRINTF("entries: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_entries);
2348 DPRINTF("branch pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_branch_pages);
2349 DPRINTF("leaf pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_leaf_pages);
2350 DPRINTF("overflow pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_overflow_pages);
2351 DPRINTF("root: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_root);
2357 /** Release a reader thread's slot in the reader lock table.
2358 * This function is called automatically when a thread exits.
2359 * Windows doesn't support destructor callbacks for thread-specific storage,
2360 * so this function is not compiled there.
2361 * @param[in] ptr This points to the slot in the reader lock table.
2364 mdb_env_reader_dest(void *ptr)
2366 MDB_reader *reader = ptr;
2368 reader->mr_txnid = 0;
2374 /** Downgrade the exclusive lock on the region back to shared */
2376 mdb_env_share_locks(MDB_env *env)
2380 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
2382 env->me_txns->mti_me_toggle = toggle;
2383 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
2388 /* First acquire a shared lock. The Unlock will
2389 * then release the existing exclusive lock.
2391 memset(&ov, 0, sizeof(ov));
2392 LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov);
2393 UnlockFile(env->me_lfd, 0, 0, 1, 0);
2397 struct flock lock_info;
2398 /* The shared lock replaces the existing lock */
2399 memset((void *)&lock_info, 0, sizeof(lock_info));
2400 lock_info.l_type = F_RDLCK;
2401 lock_info.l_whence = SEEK_SET;
2402 lock_info.l_start = 0;
2403 lock_info.l_len = 1;
2404 fcntl(env->me_lfd, F_SETLK, &lock_info);
2408 #if defined(_WIN32) || defined(__APPLE__)
2410 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
2412 * @(#) $Revision: 5.1 $
2413 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
2414 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
2416 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
2420 * Please do not copyright this code. This code is in the public domain.
2422 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
2423 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
2424 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
2425 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
2426 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
2427 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
2428 * PERFORMANCE OF THIS SOFTWARE.
2431 * chongo <Landon Curt Noll> /\oo/\
2432 * http://www.isthe.com/chongo/
2434 * Share and Enjoy! :-)
2437 typedef unsigned long long mdb_hash_t;
2438 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
2440 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
2441 * @param[in] str string to hash
2442 * @param[in] hval initial value for hash
2443 * @return 64 bit hash
2445 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
2446 * hval arg on the first call.
2449 mdb_hash_str(char *str, mdb_hash_t hval)
2451 unsigned char *s = (unsigned char *)str; /* unsigned string */
2453 * FNV-1a hash each octet of the string
2456 /* xor the bottom with the current octet */
2457 hval ^= (mdb_hash_t)*s++;
2459 /* multiply by the 64 bit FNV magic prime mod 2^64 */
2460 hval += (hval << 1) + (hval << 4) + (hval << 5) +
2461 (hval << 7) + (hval << 8) + (hval << 40);
2463 /* return our new hash value */
2467 /** Hash the string and output the hash in hex.
2468 * @param[in] str string to hash
2469 * @param[out] hexbuf an array of 17 chars to hold the hash
2472 mdb_hash_hex(char *str, char *hexbuf)
2475 mdb_hash_t h = mdb_hash_str(str, MDB_HASH_INIT);
2476 for (i=0; i<8; i++) {
2477 hexbuf += sprintf(hexbuf, "%02x", (unsigned int)h & 0xff);
2483 /** Open and/or initialize the lock region for the environment.
2484 * @param[in] env The MDB environment.
2485 * @param[in] lpath The pathname of the file used for the lock region.
2486 * @param[in] mode The Unix permissions for the file, if we create it.
2487 * @param[out] excl Set to true if we got an exclusive lock on the region.
2488 * @return 0 on success, non-zero on failure.
2491 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
2499 if ((env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
2500 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
2501 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
2505 /* Try to get exclusive lock. If we succeed, then
2506 * nobody is using the lock region and we should initialize it.
2509 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
2513 memset(&ov, 0, sizeof(ov));
2514 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
2520 size = GetFileSize(env->me_lfd, NULL);
2522 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
2526 /* Try to get exclusive lock. If we succeed, then
2527 * nobody is using the lock region and we should initialize it.
2530 struct flock lock_info;
2531 memset((void *)&lock_info, 0, sizeof(lock_info));
2532 lock_info.l_type = F_WRLCK;
2533 lock_info.l_whence = SEEK_SET;
2534 lock_info.l_start = 0;
2535 lock_info.l_len = 1;
2536 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
2540 lock_info.l_type = F_RDLCK;
2541 rc = fcntl(env->me_lfd, F_SETLKW, &lock_info);
2548 size = lseek(env->me_lfd, 0, SEEK_END);
2550 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
2551 if (size < rsize && *excl) {
2553 SetFilePointer(env->me_lfd, rsize, NULL, 0);
2554 if (!SetEndOfFile(env->me_lfd)) {
2559 if (ftruncate(env->me_lfd, rsize) != 0) {
2566 size = rsize - sizeof(MDB_txninfo);
2567 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
2572 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
2578 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
2580 if (!env->me_txns) {
2586 env->me_txns = (MDB_txninfo *)mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
2588 if (env->me_txns == MAP_FAILED) {
2596 if (!mdb_sec_inited) {
2597 InitializeSecurityDescriptor(&mdb_null_sd,
2598 SECURITY_DESCRIPTOR_REVISION);
2599 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
2600 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2601 mdb_all_sa.bInheritHandle = FALSE;
2602 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
2605 mdb_hash_hex(lpath, hexbuf);
2606 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", hexbuf);
2607 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
2608 if (!env->me_rmutex) {
2612 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", hexbuf);
2613 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
2614 if (!env->me_wmutex) {
2621 mdb_hash_hex(lpath, hexbuf);
2622 sprintf(env->me_txns->mti_rmname, "MDBr%s", hexbuf);
2623 if (sem_unlink(env->me_txns->mti_rmname)) {
2625 if (rc != ENOENT && rc != EINVAL)
2628 env->me_rmutex = sem_open(env->me_txns->mti_rmname, O_CREAT, mode, 1);
2629 if (!env->me_rmutex) {
2633 sprintf(env->me_txns->mti_wmname, "MDBw%s", hexbuf);
2634 if (sem_unlink(env->me_txns->mti_wmname)) {
2636 if (rc != ENOENT && rc != EINVAL)
2639 env->me_wmutex = sem_open(env->me_txns->mti_wmname, O_CREAT, mode, 1);
2640 if (!env->me_wmutex) {
2644 #else /* __APPLE__ */
2645 pthread_mutexattr_t mattr;
2647 pthread_mutexattr_init(&mattr);
2648 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
2652 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
2653 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
2654 #endif /* __APPLE__ */
2656 env->me_txns->mti_version = MDB_VERSION;
2657 env->me_txns->mti_magic = MDB_MAGIC;
2658 env->me_txns->mti_txnid = 0;
2659 env->me_txns->mti_numreaders = 0;
2660 env->me_txns->mti_me_toggle = 0;
2663 if (env->me_txns->mti_magic != MDB_MAGIC) {
2664 DPUTS("lock region has invalid magic");
2668 if (env->me_txns->mti_version != MDB_VERSION) {
2669 DPRINTF("lock region is version %u, expected version %u",
2670 env->me_txns->mti_version, MDB_VERSION);
2671 rc = MDB_VERSION_MISMATCH;
2675 if (rc != EACCES && rc != EAGAIN) {
2679 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
2680 if (!env->me_rmutex) {
2684 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
2685 if (!env->me_wmutex) {
2691 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
2692 if (!env->me_rmutex) {
2696 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
2697 if (!env->me_wmutex) {
2707 env->me_lfd = INVALID_HANDLE_VALUE;
2712 /** The name of the lock file in the DB environment */
2713 #define LOCKNAME "/lock.mdb"
2714 /** The name of the data file in the DB environment */
2715 #define DATANAME "/data.mdb"
2716 /** The suffix of the lock file when no subdir is used */
2717 #define LOCKSUFF "-lock"
2720 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
2722 int oflags, rc, len, excl;
2723 char *lpath, *dpath;
2726 if (flags & MDB_NOSUBDIR) {
2727 rc = len + sizeof(LOCKSUFF) + len + 1;
2729 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
2734 if (flags & MDB_NOSUBDIR) {
2735 dpath = lpath + len + sizeof(LOCKSUFF);
2736 sprintf(lpath, "%s" LOCKSUFF, path);
2737 strcpy(dpath, path);
2739 dpath = lpath + len + sizeof(LOCKNAME);
2740 sprintf(lpath, "%s" LOCKNAME, path);
2741 sprintf(dpath, "%s" DATANAME, path);
2744 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
2749 if (F_ISSET(flags, MDB_RDONLY)) {
2750 oflags = GENERIC_READ;
2751 len = OPEN_EXISTING;
2753 oflags = GENERIC_READ|GENERIC_WRITE;
2756 mode = FILE_ATTRIBUTE_NORMAL;
2757 if ((env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2758 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2763 if (F_ISSET(flags, MDB_RDONLY))
2766 oflags = O_RDWR | O_CREAT;
2768 if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
2774 if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
2775 /* synchronous fd for meta writes */
2777 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2778 mode |= FILE_FLAG_WRITE_THROUGH;
2779 if ((env->me_mfd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2780 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2785 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2786 oflags |= MDB_DSYNC;
2787 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
2792 env->me_path = strdup(path);
2793 DPRINTF("opened dbenv %p", (void *) env);
2794 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
2795 LAZY_RWLOCK_INIT(&env->me_dblock, NULL);
2797 mdb_env_share_locks(env);
2798 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
2799 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
2800 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
2806 if (env->me_fd != INVALID_HANDLE_VALUE) {
2808 env->me_fd = INVALID_HANDLE_VALUE;
2810 if (env->me_lfd != INVALID_HANDLE_VALUE) {
2812 env->me_lfd = INVALID_HANDLE_VALUE;
2820 mdb_env_close(MDB_env *env)
2827 while (env->me_dpages) {
2828 dp = env->me_dpages;
2829 env->me_dpages = dp->mp_next;
2833 free(env->me_dbs[1]);
2834 free(env->me_dbs[0]);
2838 LAZY_RWLOCK_DESTROY(&env->me_dblock);
2839 pthread_key_delete(env->me_txkey);
2842 munmap(env->me_map, env->me_mapsize);
2847 pid_t pid = getpid();
2849 for (i=0; i<env->me_txns->mti_numreaders; i++)
2850 if (env->me_txns->mti_readers[i].mr_pid == pid)
2851 env->me_txns->mti_readers[i].mr_pid = 0;
2852 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
2855 mdb_midl_free(env->me_free_pgs);
2859 /** Compare two items pointing at aligned size_t's */
2861 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
2863 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
2864 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
2867 /** Compare two items pointing at aligned int's */
2869 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
2871 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
2872 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
2875 /** Compare two items pointing at ints of unknown alignment.
2876 * Nodes and keys are guaranteed to be 2-byte aligned.
2879 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
2881 #if BYTE_ORDER == LITTLE_ENDIAN
2882 unsigned short *u, *c;
2885 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
2886 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
2889 } while(!x && u > (unsigned short *)a->mv_data);
2892 return memcmp(a->mv_data, b->mv_data, a->mv_size);
2896 /** Compare two items lexically */
2898 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
2905 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
2911 diff = memcmp(a->mv_data, b->mv_data, len);
2912 return diff ? diff : len_diff<0 ? -1 : len_diff;
2915 /** Compare two items in reverse byte order */
2917 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
2919 const unsigned char *p1, *p2, *p1_lim;
2923 p1_lim = (const unsigned char *)a->mv_data;
2924 p1 = (const unsigned char *)a->mv_data + a->mv_size;
2925 p2 = (const unsigned char *)b->mv_data + b->mv_size;
2927 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
2933 while (p1 > p1_lim) {
2934 diff = *--p1 - *--p2;
2938 return len_diff<0 ? -1 : len_diff;
2941 /** Search for key within a page, using binary search.
2942 * Returns the smallest entry larger or equal to the key.
2943 * If exactp is non-null, stores whether the found entry was an exact match
2944 * in *exactp (1 or 0).
2945 * Updates the cursor index with the index of the found entry.
2946 * If no entry larger or equal to the key is found, returns NULL.
2949 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
2951 unsigned int i = 0, nkeys;
2954 MDB_page *mp = mc->mc_pg[mc->mc_top];
2955 MDB_node *node = NULL;
2960 nkeys = NUMKEYS(mp);
2962 DPRINTF("searching %u keys in %s %spage %zu",
2963 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
2968 low = IS_LEAF(mp) ? 0 : 1;
2970 cmp = mc->mc_dbx->md_cmp;
2972 /* Branch pages have no data, so if using integer keys,
2973 * alignment is guaranteed. Use faster mdb_cmp_int.
2975 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
2976 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
2983 nodekey.mv_size = mc->mc_db->md_pad;
2984 node = NODEPTR(mp, 0); /* fake */
2985 while (low <= high) {
2986 i = (low + high) >> 1;
2987 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
2988 rc = cmp(key, &nodekey);
2989 DPRINTF("found leaf index %u [%s], rc = %i",
2990 i, DKEY(&nodekey), rc);
2999 while (low <= high) {
3000 i = (low + high) >> 1;
3002 node = NODEPTR(mp, i);
3003 nodekey.mv_size = NODEKSZ(node);
3004 nodekey.mv_data = NODEKEY(node);
3006 rc = cmp(key, &nodekey);
3009 DPRINTF("found leaf index %u [%s], rc = %i",
3010 i, DKEY(&nodekey), rc);
3012 DPRINTF("found branch index %u [%s -> %zu], rc = %i",
3013 i, DKEY(&nodekey), NODEPGNO(node), rc);
3024 if (rc > 0) { /* Found entry is less than the key. */
3025 i++; /* Skip to get the smallest entry larger than key. */
3027 node = NODEPTR(mp, i);
3030 *exactp = (rc == 0);
3031 /* store the key index */
3032 mc->mc_ki[mc->mc_top] = i;
3034 /* There is no entry larger or equal to the key. */
3037 /* nodeptr is fake for LEAF2 */
3043 mdb_cursor_adjust(MDB_cursor *mc, func)
3047 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
3048 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
3055 /** Pop a page off the top of the cursor's stack. */
3057 mdb_cursor_pop(MDB_cursor *mc)
3062 top = mc->mc_pg[mc->mc_top];
3067 DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
3068 mc->mc_dbi, (void *) mc);
3072 /** Push a page onto the top of the cursor's stack. */
3074 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
3076 DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
3077 mc->mc_dbi, (void *) mc);
3079 if (mc->mc_snum >= CURSOR_STACK) {
3080 assert(mc->mc_snum < CURSOR_STACK);
3084 mc->mc_top = mc->mc_snum++;
3085 mc->mc_pg[mc->mc_top] = mp;
3086 mc->mc_ki[mc->mc_top] = 0;
3091 /** Find the address of the page corresponding to a given page number.
3092 * @param[in] txn the transaction for this access.
3093 * @param[in] pgno the page number for the page to retrieve.
3094 * @param[out] ret address of a pointer where the page's address will be stored.
3095 * @return 0 on success, non-zero on failure.
3098 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
3102 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
3104 x = mdb_mid2l_search(txn->mt_u.dirty_list, pgno);
3105 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
3106 p = txn->mt_u.dirty_list[x].mptr;
3110 if (pgno <= txn->mt_env->me_metas[txn->mt_toggle]->mm_last_pg)
3111 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
3115 DPRINTF("page %zu not found", pgno);
3118 return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
3121 /** Search for the page a given key should be in.
3122 * Pushes parent pages on the cursor stack. This function continues a
3123 * search on a cursor that has already been initialized. (Usually by
3124 * #mdb_page_search() but also by #mdb_node_move().)
3125 * @param[in,out] mc the cursor for this operation.
3126 * @param[in] key the key to search for. If NULL, search for the lowest
3127 * page. (This is used by #mdb_cursor_first().)
3128 * @param[in] modify If true, visited pages are updated with new page numbers.
3129 * @return 0 on success, non-zero on failure.
3132 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
3134 MDB_page *mp = mc->mc_pg[mc->mc_top];
3139 while (IS_BRANCH(mp)) {
3143 DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
3144 assert(NUMKEYS(mp) > 1);
3145 DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
3147 if (key == NULL) /* Initialize cursor to first page. */
3149 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
3150 /* cursor to last page */
3154 node = mdb_node_search(mc, key, &exact);
3156 i = NUMKEYS(mp) - 1;
3158 i = mc->mc_ki[mc->mc_top];
3167 DPRINTF("following index %u for key [%s]",
3169 assert(i < NUMKEYS(mp));
3170 node = NODEPTR(mp, i);
3172 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp)))
3175 mc->mc_ki[mc->mc_top] = i;
3176 if ((rc = mdb_cursor_push(mc, mp)))
3180 if ((rc = mdb_page_touch(mc)) != 0)
3182 mp = mc->mc_pg[mc->mc_top];
3187 DPRINTF("internal error, index points to a %02X page!?",
3189 return MDB_CORRUPTED;
3192 DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
3193 key ? DKEY(key) : NULL);
3198 /** Search for the page a given key should be in.
3199 * Pushes parent pages on the cursor stack. This function just sets up
3200 * the search; it finds the root page for \b mc's database and sets this
3201 * as the root of the cursor's stack. Then #mdb_page_search_root() is
3202 * called to complete the search.
3203 * @param[in,out] mc the cursor for this operation.
3204 * @param[in] key the key to search for. If NULL, search for the lowest
3205 * page. (This is used by #mdb_cursor_first().)
3206 * @param[in] modify If true, visited pages are updated with new page numbers.
3207 * @return 0 on success, non-zero on failure.
3210 mdb_page_search(MDB_cursor *mc, MDB_val *key, int modify)
3215 /* Make sure the txn is still viable, then find the root from
3216 * the txn's db table.
3218 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
3219 DPUTS("transaction has failed, must abort");
3222 /* Make sure we're using an up-to-date root */
3223 if (mc->mc_dbi > MAIN_DBI) {
3224 if ((*mc->mc_dbflag & DB_STALE) ||
3225 (modify && !(*mc->mc_dbflag & DB_DIRTY))) {
3227 unsigned char dbflag = 0;
3228 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
3229 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, modify);
3232 if (*mc->mc_dbflag & DB_STALE) {
3235 MDB_node *leaf = mdb_node_search(&mc2,
3236 &mc->mc_dbx->md_name, &exact);
3238 return MDB_NOTFOUND;
3239 mdb_node_read(mc->mc_txn, leaf, &data);
3240 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
3244 *mc->mc_dbflag = dbflag;
3247 root = mc->mc_db->md_root;
3249 if (root == P_INVALID) { /* Tree is empty. */
3250 DPUTS("tree is empty");
3251 return MDB_NOTFOUND;
3256 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0])))
3262 DPRINTF("db %u root page %zu has flags 0x%X",
3263 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
3266 if ((rc = mdb_page_touch(mc)))
3270 return mdb_page_search_root(mc, key, modify);
3273 /** Return the data associated with a given node.
3274 * @param[in] txn The transaction for this operation.
3275 * @param[in] leaf The node being read.
3276 * @param[out] data Updated to point to the node's data.
3277 * @return 0 on success, non-zero on failure.
3280 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
3282 MDB_page *omp; /* overflow page */
3286 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
3287 data->mv_size = NODEDSZ(leaf);
3288 data->mv_data = NODEDATA(leaf);
3292 /* Read overflow data.
3294 data->mv_size = NODEDSZ(leaf);
3295 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
3296 if ((rc = mdb_page_get(txn, pgno, &omp))) {
3297 DPRINTF("read overflow page %zu failed", pgno);
3300 data->mv_data = METADATA(omp);
3306 mdb_get(MDB_txn *txn, MDB_dbi dbi,
3307 MDB_val *key, MDB_val *data)
3316 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
3318 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3321 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3325 mdb_cursor_init(&mc, txn, dbi, &mx);
3326 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
3329 /** Find a sibling for a page.
3330 * Replaces the page at the top of the cursor's stack with the
3331 * specified sibling, if one exists.
3332 * @param[in] mc The cursor for this operation.
3333 * @param[in] move_right Non-zero if the right sibling is requested,
3334 * otherwise the left sibling.
3335 * @return 0 on success, non-zero on failure.
3338 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
3344 if (mc->mc_snum < 2) {
3345 return MDB_NOTFOUND; /* root has no siblings */
3349 DPRINTF("parent page is page %zu, index %u",
3350 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]);
3352 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
3353 : (mc->mc_ki[mc->mc_top] == 0)) {
3354 DPRINTF("no more keys left, moving to %s sibling",
3355 move_right ? "right" : "left");
3356 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS)
3360 mc->mc_ki[mc->mc_top]++;
3362 mc->mc_ki[mc->mc_top]--;
3363 DPRINTF("just moving to %s index key %u",
3364 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]);
3366 assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
3368 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3369 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp)))
3372 mdb_cursor_push(mc, mp);
3377 /** Move the cursor to the next data item. */
3379 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3385 if (mc->mc_flags & C_EOF) {
3386 return MDB_NOTFOUND;
3389 assert(mc->mc_flags & C_INITIALIZED);
3391 mp = mc->mc_pg[mc->mc_top];
3393 if (mc->mc_db->md_flags & MDB_DUPSORT) {
3394 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3395 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3396 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
3397 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
3398 if (op != MDB_NEXT || rc == MDB_SUCCESS)
3402 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3403 if (op == MDB_NEXT_DUP)
3404 return MDB_NOTFOUND;
3408 DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3410 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
3411 DPUTS("=====> move to next sibling page");
3412 if (mdb_cursor_sibling(mc, 1) != MDB_SUCCESS) {
3413 mc->mc_flags |= C_EOF;
3414 mc->mc_flags &= ~C_INITIALIZED;
3415 return MDB_NOTFOUND;
3417 mp = mc->mc_pg[mc->mc_top];
3418 DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3420 mc->mc_ki[mc->mc_top]++;
3422 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3423 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3426 key->mv_size = mc->mc_db->md_pad;
3427 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3431 assert(IS_LEAF(mp));
3432 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3434 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3435 mdb_xcursor_init1(mc, leaf);
3438 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3441 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3442 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3443 if (rc != MDB_SUCCESS)
3448 MDB_SET_KEY(leaf, key);
3452 /** Move the cursor to the previous data item. */
3454 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3460 assert(mc->mc_flags & C_INITIALIZED);
3462 mp = mc->mc_pg[mc->mc_top];
3464 if (mc->mc_db->md_flags & MDB_DUPSORT) {
3465 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3466 if (op == MDB_PREV || op == MDB_PREV_DUP) {
3467 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3468 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
3469 if (op != MDB_PREV || rc == MDB_SUCCESS)
3472 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3473 if (op == MDB_PREV_DUP)
3474 return MDB_NOTFOUND;
3479 DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3481 if (mc->mc_ki[mc->mc_top] == 0) {
3482 DPUTS("=====> move to prev sibling page");
3483 if (mdb_cursor_sibling(mc, 0) != MDB_SUCCESS) {
3484 mc->mc_flags &= ~C_INITIALIZED;
3485 return MDB_NOTFOUND;
3487 mp = mc->mc_pg[mc->mc_top];
3488 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
3489 DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3491 mc->mc_ki[mc->mc_top]--;
3493 mc->mc_flags &= ~C_EOF;
3495 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3496 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3499 key->mv_size = mc->mc_db->md_pad;
3500 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3504 assert(IS_LEAF(mp));
3505 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3507 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3508 mdb_xcursor_init1(mc, leaf);
3511 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3514 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3515 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3516 if (rc != MDB_SUCCESS)
3521 MDB_SET_KEY(leaf, key);
3525 /** Set the cursor on a specific data item. */
3527 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3528 MDB_cursor_op op, int *exactp)
3537 assert(key->mv_size > 0);
3539 /* See if we're already on the right page */
3540 if (mc->mc_flags & C_INITIALIZED) {
3543 mp = mc->mc_pg[mc->mc_top];
3545 mc->mc_ki[mc->mc_top] = 0;
3546 return MDB_NOTFOUND;
3548 if (mp->mp_flags & P_LEAF2) {
3549 nodekey.mv_size = mc->mc_db->md_pad;
3550 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
3552 leaf = NODEPTR(mp, 0);
3553 MDB_SET_KEY(leaf, &nodekey);
3555 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3557 /* Probably happens rarely, but first node on the page
3558 * was the one we wanted.
3560 mc->mc_ki[mc->mc_top] = 0;
3561 leaf = NODEPTR(mp, 0);
3568 unsigned int nkeys = NUMKEYS(mp);
3570 if (mp->mp_flags & P_LEAF2) {
3571 nodekey.mv_data = LEAF2KEY(mp,
3572 nkeys-1, nodekey.mv_size);
3574 leaf = NODEPTR(mp, nkeys-1);
3575 MDB_SET_KEY(leaf, &nodekey);
3577 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3579 /* last node was the one we wanted */
3580 mc->mc_ki[mc->mc_top] = nkeys-1;
3581 leaf = NODEPTR(mp, nkeys-1);
3587 /* This is definitely the right page, skip search_page */
3592 /* If any parents have right-sibs, search.
3593 * Otherwise, there's nothing further.
3595 for (i=0; i<mc->mc_top; i++)
3597 NUMKEYS(mc->mc_pg[i])-1)
3599 if (i == mc->mc_top) {
3600 /* There are no other pages */
3601 mc->mc_ki[mc->mc_top] = nkeys;
3602 return MDB_NOTFOUND;
3606 /* There are no other pages */
3607 mc->mc_ki[mc->mc_top] = 0;
3608 return MDB_NOTFOUND;
3612 rc = mdb_page_search(mc, key, 0);
3613 if (rc != MDB_SUCCESS)
3616 mp = mc->mc_pg[mc->mc_top];
3617 assert(IS_LEAF(mp));
3620 leaf = mdb_node_search(mc, key, exactp);
3621 if (exactp != NULL && !*exactp) {
3622 /* MDB_SET specified and not an exact match. */
3623 return MDB_NOTFOUND;
3627 DPUTS("===> inexact leaf not found, goto sibling");
3628 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
3629 return rc; /* no entries matched */
3630 mp = mc->mc_pg[mc->mc_top];
3631 assert(IS_LEAF(mp));
3632 leaf = NODEPTR(mp, 0);
3636 mc->mc_flags |= C_INITIALIZED;
3637 mc->mc_flags &= ~C_EOF;
3640 key->mv_size = mc->mc_db->md_pad;
3641 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3645 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3646 mdb_xcursor_init1(mc, leaf);
3649 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3650 if (op == MDB_SET || op == MDB_SET_RANGE) {
3651 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3654 if (op == MDB_GET_BOTH) {
3660 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
3661 if (rc != MDB_SUCCESS)
3664 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
3666 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
3668 rc = mc->mc_dbx->md_dcmp(data, &d2);
3670 if (op == MDB_GET_BOTH || rc > 0)
3671 return MDB_NOTFOUND;
3676 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3677 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3682 /* The key already matches in all other cases */
3683 if (op == MDB_SET_RANGE)
3684 MDB_SET_KEY(leaf, key);
3685 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
3690 /** Move the cursor to the first item in the database. */
3692 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3697 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3698 rc = mdb_page_search(mc, NULL, 0);
3699 if (rc != MDB_SUCCESS)
3702 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3704 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
3705 mc->mc_flags |= C_INITIALIZED;
3706 mc->mc_flags &= ~C_EOF;
3708 mc->mc_ki[mc->mc_top] = 0;
3710 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3711 key->mv_size = mc->mc_db->md_pad;
3712 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
3717 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3718 mdb_xcursor_init1(mc, leaf);
3719 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3724 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3725 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3729 MDB_SET_KEY(leaf, key);
3733 /** Move the cursor to the last item in the database. */
3735 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3741 lkey.mv_size = MAXKEYSIZE+1;
3742 lkey.mv_data = NULL;
3744 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3745 rc = mdb_page_search(mc, &lkey, 0);
3746 if (rc != MDB_SUCCESS)
3749 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3751 leaf = NODEPTR(mc->mc_pg[mc->mc_top], NUMKEYS(mc->mc_pg[mc->mc_top])-1);
3752 mc->mc_flags |= C_INITIALIZED;
3753 mc->mc_flags &= ~C_EOF;
3755 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
3757 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3758 key->mv_size = mc->mc_db->md_pad;
3759 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
3764 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3765 mdb_xcursor_init1(mc, leaf);
3766 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3771 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3772 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3777 MDB_SET_KEY(leaf, key);
3782 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3792 case MDB_GET_BOTH_RANGE:
3793 if (data == NULL || mc->mc_xcursor == NULL) {
3800 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3802 } else if (op == MDB_SET_RANGE)
3803 rc = mdb_cursor_set(mc, key, data, op, NULL);
3805 rc = mdb_cursor_set(mc, key, data, op, &exact);
3807 case MDB_GET_MULTIPLE:
3809 !(mc->mc_db->md_flags & MDB_DUPFIXED) ||
3810 !(mc->mc_flags & C_INITIALIZED)) {
3815 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
3816 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
3819 case MDB_NEXT_MULTIPLE:
3821 !(mc->mc_db->md_flags & MDB_DUPFIXED)) {
3825 if (!(mc->mc_flags & C_INITIALIZED))
3826 rc = mdb_cursor_first(mc, key, data);
3828 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
3829 if (rc == MDB_SUCCESS) {
3830 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
3833 mx = &mc->mc_xcursor->mx_cursor;
3834 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
3836 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
3837 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
3845 case MDB_NEXT_NODUP:
3846 if (!(mc->mc_flags & C_INITIALIZED))
3847 rc = mdb_cursor_first(mc, key, data);
3849 rc = mdb_cursor_next(mc, key, data, op);
3853 case MDB_PREV_NODUP:
3854 if (!(mc->mc_flags & C_INITIALIZED) || (mc->mc_flags & C_EOF))
3855 rc = mdb_cursor_last(mc, key, data);
3857 rc = mdb_cursor_prev(mc, key, data, op);
3860 rc = mdb_cursor_first(mc, key, data);
3864 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
3865 !(mc->mc_flags & C_INITIALIZED) ||
3866 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3870 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3873 rc = mdb_cursor_last(mc, key, data);
3877 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
3878 !(mc->mc_flags & C_INITIALIZED) ||
3879 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3883 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3886 DPRINTF("unhandled/unimplemented cursor operation %u", op);
3894 /** Touch all the pages in the cursor stack.
3895 * Makes sure all the pages are writable, before attempting a write operation.
3896 * @param[in] mc The cursor to operate on.
3899 mdb_cursor_touch(MDB_cursor *mc)
3903 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
3905 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
3906 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 1);
3909 *mc->mc_dbflag = DB_DIRTY;
3911 for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
3912 rc = mdb_page_touch(mc);
3916 mc->mc_top = mc->mc_snum-1;
3921 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3924 MDB_node *leaf = NULL;
3925 MDB_val xdata, *rdata, dkey;
3929 unsigned int mcount = 0;
3932 char pbuf[MDB_PAGESIZE];
3933 char dbuf[MAXKEYSIZE+1];
3934 unsigned int nflags;
3937 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
3940 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
3941 mc->mc_dbi, DKEY(key), key ? key->mv_size:0, data->mv_size);
3945 if (flags == MDB_CURRENT) {
3946 if (!(mc->mc_flags & C_INITIALIZED))
3949 } else if (mc->mc_db->md_root == P_INVALID) {
3951 /* new database, write a root leaf page */
3952 DPUTS("allocating new root leaf page");
3953 if ((np = mdb_page_new(mc, P_LEAF, 1)) == NULL) {
3957 mdb_cursor_push(mc, np);
3958 mc->mc_db->md_root = np->mp_pgno;
3959 mc->mc_db->md_depth++;
3960 *mc->mc_dbflag = DB_DIRTY;
3961 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
3963 np->mp_flags |= P_LEAF2;
3964 mc->mc_flags |= C_INITIALIZED;
3970 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
3971 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
3972 DPRINTF("duplicate key [%s]", DKEY(key));
3974 return MDB_KEYEXIST;
3976 if (rc && rc != MDB_NOTFOUND)
3980 /* Cursor is positioned, now make sure all pages are writable */
3981 rc2 = mdb_cursor_touch(mc);
3986 /* The key already exists */
3987 if (rc == MDB_SUCCESS) {
3988 /* there's only a key anyway, so this is a no-op */
3989 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3990 unsigned int ksize = mc->mc_db->md_pad;
3991 if (key->mv_size != ksize)
3993 if (flags == MDB_CURRENT) {
3994 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
3995 memcpy(ptr, key->mv_data, ksize);
4000 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4003 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
4004 /* Was a single item before, must convert now */
4006 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4007 /* Just overwrite the current item */
4008 if (flags == MDB_CURRENT)
4011 dkey.mv_size = NODEDSZ(leaf);
4012 dkey.mv_data = NODEDATA(leaf);
4013 #if UINT_MAX < SIZE_MAX
4014 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && dkey.mv_size == sizeof(size_t))
4015 #ifdef MISALIGNED_OK
4016 mc->mc_dbx->md_dcmp = mdb_cmp_long;
4018 mc->mc_dbx->md_dcmp = mdb_cmp_cint;
4021 /* if data matches, ignore it */
4022 if (!mc->mc_dbx->md_dcmp(data, &dkey))
4023 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
4025 /* create a fake page for the dup items */
4026 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
4027 dkey.mv_data = dbuf;
4028 fp = (MDB_page *)pbuf;
4029 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4030 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
4031 fp->mp_lower = PAGEHDRSZ;
4032 fp->mp_upper = PAGEHDRSZ + dkey.mv_size + data->mv_size;
4033 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4034 fp->mp_flags |= P_LEAF2;
4035 fp->mp_pad = data->mv_size;
4037 fp->mp_upper += 2 * sizeof(indx_t) + 2 * NODESIZE +
4038 (dkey.mv_size & 1) + (data->mv_size & 1);
4040 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4043 xdata.mv_size = fp->mp_upper;
4044 xdata.mv_data = pbuf;
4048 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
4049 /* See if we need to convert from fake page to subDB */
4051 unsigned int offset;
4054 fp = NODEDATA(leaf);
4055 if (flags == MDB_CURRENT) {
4056 fp->mp_flags |= P_DIRTY;
4057 COPY_PGNO(fp->mp_pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
4058 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
4062 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4063 offset = fp->mp_pad;
4065 offset = NODESIZE + sizeof(indx_t) + data->mv_size;
4067 offset += offset & 1;
4068 if (NODESIZE + sizeof(indx_t) + NODEKSZ(leaf) + NODEDSZ(leaf) +
4069 offset >= (mc->mc_txn->mt_env->me_psize - PAGEHDRSZ) /
4071 /* yes, convert it */
4073 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4074 dummy.md_pad = fp->mp_pad;
4075 dummy.md_flags = MDB_DUPFIXED;
4076 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
4077 dummy.md_flags |= MDB_INTEGERKEY;
4080 dummy.md_branch_pages = 0;
4081 dummy.md_leaf_pages = 1;
4082 dummy.md_overflow_pages = 0;
4083 dummy.md_entries = NUMKEYS(fp);
4085 xdata.mv_size = sizeof(MDB_db);
4086 xdata.mv_data = &dummy;
4087 mp = mdb_page_alloc(mc, 1);
4090 offset = mc->mc_txn->mt_env->me_psize - NODEDSZ(leaf);
4091 flags |= F_DUPDATA|F_SUBDATA;
4092 dummy.md_root = mp->mp_pgno;
4094 /* no, just grow it */
4096 xdata.mv_size = NODEDSZ(leaf) + offset;
4097 xdata.mv_data = pbuf;
4098 mp = (MDB_page *)pbuf;
4099 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4102 mp->mp_flags = fp->mp_flags | P_DIRTY;
4103 mp->mp_pad = fp->mp_pad;
4104 mp->mp_lower = fp->mp_lower;
4105 mp->mp_upper = fp->mp_upper + offset;
4107 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
4109 nsize = NODEDSZ(leaf) - fp->mp_upper;
4110 memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper, nsize);
4111 for (i=0; i<NUMKEYS(fp); i++)
4112 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
4114 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4118 /* data is on sub-DB, just store it */
4119 flags |= F_DUPDATA|F_SUBDATA;
4123 /* same size, just replace it */
4124 if (!F_ISSET(leaf->mn_flags, F_BIGDATA) &&
4125 NODEDSZ(leaf) == data->mv_size) {
4126 if (F_ISSET(flags, MDB_RESERVE))
4127 data->mv_data = NODEDATA(leaf);
4129 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
4132 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4134 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
4140 nflags = flags & NODE_ADD_FLAGS;
4141 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
4142 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
4143 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
4144 nflags &= ~MDB_APPEND;
4145 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
4147 /* There is room already in this leaf page. */
4148 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
4149 if (rc == 0 && !do_sub) {
4150 /* Adjust other cursors pointing to mp */
4151 MDB_cursor *m2, *m3;
4152 MDB_dbi dbi = mc->mc_dbi;
4153 unsigned i = mc->mc_top;
4154 MDB_page *mp = mc->mc_pg[i];
4156 if (mc->mc_flags & C_SUB)
4159 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
4160 if (mc->mc_flags & C_SUB)
4161 m3 = &m2->mc_xcursor->mx_cursor;
4164 if (m3 == mc) continue;
4165 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
4172 if (rc != MDB_SUCCESS)
4173 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4175 /* Now store the actual data in the child DB. Note that we're
4176 * storing the user data in the keys field, so there are strict
4177 * size limits on dupdata. The actual data fields of the child
4178 * DB are all zero size.
4186 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4187 if (flags & MDB_CURRENT) {
4188 xflags = MDB_CURRENT;
4190 mdb_xcursor_init1(mc, leaf);
4191 xflags = (flags & MDB_NODUPDATA) ? MDB_NOOVERWRITE : 0;
4193 /* converted, write the original data first */
4195 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
4199 /* Adjust other cursors pointing to mp */
4201 unsigned i = mc->mc_top;
4202 MDB_page *mp = mc->mc_pg[i];
4204 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4205 if (m2 == mc) continue;
4206 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
4207 mdb_xcursor_init1(m2, leaf);
4212 xflags |= (flags & MDB_APPEND);
4213 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
4214 if (flags & F_SUBDATA) {
4215 db = NODEDATA(leaf);
4216 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4219 /* sub-writes might have failed so check rc again.
4220 * Don't increment count if we just replaced an existing item.
4222 if (!rc && !(flags & MDB_CURRENT))
4223 mc->mc_db->md_entries++;
4224 if (flags & MDB_MULTIPLE) {
4226 if (mcount < data[1].mv_size) {
4227 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
4228 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4238 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
4243 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
4246 if (!mc->mc_flags & C_INITIALIZED)
4249 rc = mdb_cursor_touch(mc);
4253 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4255 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4256 if (flags != MDB_NODUPDATA) {
4257 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
4258 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
4260 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
4261 /* If sub-DB still has entries, we're done */
4262 if (mc->mc_xcursor->mx_db.md_entries) {
4263 if (leaf->mn_flags & F_SUBDATA) {
4264 /* update subDB info */
4265 MDB_db *db = NODEDATA(leaf);
4266 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4268 /* shrink fake page */
4269 mdb_node_shrink(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4271 mc->mc_db->md_entries--;
4274 /* otherwise fall thru and delete the sub-DB */
4277 if (leaf->mn_flags & F_SUBDATA) {
4278 /* add all the child DB's pages to the free list */
4279 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
4280 if (rc == MDB_SUCCESS) {
4281 mc->mc_db->md_entries -=
4282 mc->mc_xcursor->mx_db.md_entries;
4287 return mdb_cursor_del0(mc, leaf);
4290 /** Allocate and initialize new pages for a database.
4291 * @param[in] mc a cursor on the database being added to.
4292 * @param[in] flags flags defining what type of page is being allocated.
4293 * @param[in] num the number of pages to allocate. This is usually 1,
4294 * unless allocating overflow pages for a large record.
4295 * @return Address of a page, or NULL on failure.
4298 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num)
4302 if ((np = mdb_page_alloc(mc, num)) == NULL)
4304 DPRINTF("allocated new mpage %zu, page size %u",
4305 np->mp_pgno, mc->mc_txn->mt_env->me_psize);
4306 np->mp_flags = flags | P_DIRTY;
4307 np->mp_lower = PAGEHDRSZ;
4308 np->mp_upper = mc->mc_txn->mt_env->me_psize;
4311 mc->mc_db->md_branch_pages++;
4312 else if (IS_LEAF(np))
4313 mc->mc_db->md_leaf_pages++;
4314 else if (IS_OVERFLOW(np)) {
4315 mc->mc_db->md_overflow_pages += num;
4322 /** Calculate the size of a leaf node.
4323 * The size depends on the environment's page size; if a data item
4324 * is too large it will be put onto an overflow page and the node
4325 * size will only include the key and not the data. Sizes are always
4326 * rounded up to an even number of bytes, to guarantee 2-byte alignment
4327 * of the #MDB_node headers.
4328 * @param[in] env The environment handle.
4329 * @param[in] key The key for the node.
4330 * @param[in] data The data for the node.
4331 * @return The number of bytes needed to store the node.
4334 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
4338 sz = LEAFSIZE(key, data);
4339 if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
4340 /* put on overflow page */
4341 sz -= data->mv_size - sizeof(pgno_t);
4345 return sz + sizeof(indx_t);
4348 /** Calculate the size of a branch node.
4349 * The size should depend on the environment's page size but since
4350 * we currently don't support spilling large keys onto overflow
4351 * pages, it's simply the size of the #MDB_node header plus the
4352 * size of the key. Sizes are always rounded up to an even number
4353 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
4354 * @param[in] env The environment handle.
4355 * @param[in] key The key for the node.
4356 * @return The number of bytes needed to store the node.
4359 mdb_branch_size(MDB_env *env, MDB_val *key)
4364 if (sz >= env->me_psize / MDB_MINKEYS) {
4365 /* put on overflow page */
4366 /* not implemented */
4367 /* sz -= key->size - sizeof(pgno_t); */
4370 return sz + sizeof(indx_t);
4373 /** Add a node to the page pointed to by the cursor.
4374 * @param[in] mc The cursor for this operation.
4375 * @param[in] indx The index on the page where the new node should be added.
4376 * @param[in] key The key for the new node.
4377 * @param[in] data The data for the new node, if any.
4378 * @param[in] pgno The page number, if adding a branch node.
4379 * @param[in] flags Flags for the node.
4380 * @return 0 on success, non-zero on failure. Possible errors are:
4382 * <li>ENOMEM - failed to allocate overflow pages for the node.
4383 * <li>ENOSPC - there is insufficient room in the page. This error
4384 * should never happen since all callers already calculate the
4385 * page's free space before calling this function.
4389 mdb_node_add(MDB_cursor *mc, indx_t indx,
4390 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
4393 size_t node_size = NODESIZE;
4396 MDB_page *mp = mc->mc_pg[mc->mc_top];
4397 MDB_page *ofp = NULL; /* overflow page */
4400 assert(mp->mp_upper >= mp->mp_lower);
4402 DPRINTF("add to %s %spage %zu index %i, data size %zu key size %zu [%s]",
4403 IS_LEAF(mp) ? "leaf" : "branch",
4404 IS_SUBP(mp) ? "sub-" : "",
4405 mp->mp_pgno, indx, data ? data->mv_size : 0,
4406 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
4409 /* Move higher keys up one slot. */
4410 int ksize = mc->mc_db->md_pad, dif;
4411 char *ptr = LEAF2KEY(mp, indx, ksize);
4412 dif = NUMKEYS(mp) - indx;
4414 memmove(ptr+ksize, ptr, dif*ksize);
4415 /* insert new key */
4416 memcpy(ptr, key->mv_data, ksize);
4418 /* Just using these for counting */
4419 mp->mp_lower += sizeof(indx_t);
4420 mp->mp_upper -= ksize - sizeof(indx_t);
4425 node_size += key->mv_size;
4429 if (F_ISSET(flags, F_BIGDATA)) {
4430 /* Data already on overflow page. */
4431 node_size += sizeof(pgno_t);
4432 } else if (data->mv_size >= mc->mc_txn->mt_env->me_psize / MDB_MINKEYS) {
4433 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
4434 /* Put data on overflow page. */
4435 DPRINTF("data size is %zu, put on overflow page",
4437 node_size += sizeof(pgno_t);
4438 if ((ofp = mdb_page_new(mc, P_OVERFLOW, ovpages)) == NULL)
4440 DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
4443 node_size += data->mv_size;
4446 node_size += node_size & 1;
4448 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
4449 DPRINTF("not enough room in page %zu, got %u ptrs",
4450 mp->mp_pgno, NUMKEYS(mp));
4451 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
4452 mp->mp_upper - mp->mp_lower);
4453 DPRINTF("node size = %zu", node_size);
4457 /* Move higher pointers up one slot. */
4458 for (i = NUMKEYS(mp); i > indx; i--)
4459 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
4461 /* Adjust free space offsets. */
4462 ofs = mp->mp_upper - node_size;
4463 assert(ofs >= mp->mp_lower + sizeof(indx_t));
4464 mp->mp_ptrs[indx] = ofs;
4466 mp->mp_lower += sizeof(indx_t);
4468 /* Write the node data. */
4469 node = NODEPTR(mp, indx);
4470 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
4471 node->mn_flags = flags;
4473 SETDSZ(node,data->mv_size);
4478 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
4483 if (F_ISSET(flags, F_BIGDATA))
4484 memcpy(node->mn_data + key->mv_size, data->mv_data,
4486 else if (F_ISSET(flags, MDB_RESERVE))
4487 data->mv_data = node->mn_data + key->mv_size;
4489 memcpy(node->mn_data + key->mv_size, data->mv_data,
4492 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
4494 if (F_ISSET(flags, MDB_RESERVE))
4495 data->mv_data = METADATA(ofp);
4497 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
4504 /** Delete the specified node from a page.
4505 * @param[in] mp The page to operate on.
4506 * @param[in] indx The index of the node to delete.
4507 * @param[in] ksize The size of a node. Only used if the page is
4508 * part of a #MDB_DUPFIXED database.
4511 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
4514 indx_t i, j, numkeys, ptr;
4518 DPRINTF("delete node %u on %s page %zu", indx,
4519 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
4520 assert(indx < NUMKEYS(mp));
4523 int x = NUMKEYS(mp) - 1 - indx;
4524 base = LEAF2KEY(mp, indx, ksize);
4526 memmove(base, base + ksize, x * ksize);
4527 mp->mp_lower -= sizeof(indx_t);
4528 mp->mp_upper += ksize - sizeof(indx_t);
4532 node = NODEPTR(mp, indx);
4533 sz = NODESIZE + node->mn_ksize;
4535 if (F_ISSET(node->mn_flags, F_BIGDATA))
4536 sz += sizeof(pgno_t);
4538 sz += NODEDSZ(node);
4542 ptr = mp->mp_ptrs[indx];
4543 numkeys = NUMKEYS(mp);
4544 for (i = j = 0; i < numkeys; i++) {
4546 mp->mp_ptrs[j] = mp->mp_ptrs[i];
4547 if (mp->mp_ptrs[i] < ptr)
4548 mp->mp_ptrs[j] += sz;
4553 base = (char *)mp + mp->mp_upper;
4554 memmove(base + sz, base, ptr - mp->mp_upper);
4556 mp->mp_lower -= sizeof(indx_t);
4560 /** Compact the main page after deleting a node on a subpage.
4561 * @param[in] mp The main page to operate on.
4562 * @param[in] indx The index of the subpage on the main page.
4565 mdb_node_shrink(MDB_page *mp, indx_t indx)
4572 indx_t i, numkeys, ptr;
4574 node = NODEPTR(mp, indx);
4575 sp = (MDB_page *)NODEDATA(node);
4576 osize = NODEDSZ(node);
4578 delta = sp->mp_upper - sp->mp_lower;
4579 SETDSZ(node, osize - delta);
4580 xp = (MDB_page *)((char *)sp + delta);
4582 /* shift subpage upward */
4584 nsize = NUMKEYS(sp) * sp->mp_pad;
4585 memmove(METADATA(xp), METADATA(sp), nsize);
4588 nsize = osize - sp->mp_upper;
4589 numkeys = NUMKEYS(sp);
4590 for (i=numkeys-1; i>=0; i--)
4591 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
4593 xp->mp_upper = sp->mp_lower;
4594 xp->mp_lower = sp->mp_lower;
4595 xp->mp_flags = sp->mp_flags;
4596 xp->mp_pad = sp->mp_pad;
4597 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
4599 /* shift lower nodes upward */
4600 ptr = mp->mp_ptrs[indx];
4601 numkeys = NUMKEYS(mp);
4602 for (i = 0; i < numkeys; i++) {
4603 if (mp->mp_ptrs[i] <= ptr)
4604 mp->mp_ptrs[i] += delta;
4607 base = (char *)mp + mp->mp_upper;
4608 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
4609 mp->mp_upper += delta;
4612 /** Initial setup of a sorted-dups cursor.
4613 * Sorted duplicates are implemented as a sub-database for the given key.
4614 * The duplicate data items are actually keys of the sub-database.
4615 * Operations on the duplicate data items are performed using a sub-cursor
4616 * initialized when the sub-database is first accessed. This function does
4617 * the preliminary setup of the sub-cursor, filling in the fields that
4618 * depend only on the parent DB.
4619 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4622 mdb_xcursor_init0(MDB_cursor *mc)
4624 MDB_xcursor *mx = mc->mc_xcursor;
4626 mx->mx_cursor.mc_xcursor = NULL;
4627 mx->mx_cursor.mc_txn = mc->mc_txn;
4628 mx->mx_cursor.mc_db = &mx->mx_db;
4629 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
4630 mx->mx_cursor.mc_dbi = mc->mc_dbi+1;
4631 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
4632 mx->mx_cursor.mc_snum = 0;
4633 mx->mx_cursor.mc_flags = C_SUB;
4634 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
4635 mx->mx_dbx.md_dcmp = NULL;
4636 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
4639 /** Final setup of a sorted-dups cursor.
4640 * Sets up the fields that depend on the data from the main cursor.
4641 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4642 * @param[in] node The data containing the #MDB_db record for the
4643 * sorted-dup database.
4646 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
4648 MDB_xcursor *mx = mc->mc_xcursor;
4650 if (node->mn_flags & F_SUBDATA) {
4651 MDB_db *db = NODEDATA(node);
4653 mx->mx_cursor.mc_snum = 0;
4654 mx->mx_cursor.mc_flags = C_SUB;
4656 MDB_page *fp = NODEDATA(node);
4657 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
4658 mx->mx_db.md_flags = 0;
4659 mx->mx_db.md_depth = 1;
4660 mx->mx_db.md_branch_pages = 0;
4661 mx->mx_db.md_leaf_pages = 1;
4662 mx->mx_db.md_overflow_pages = 0;
4663 mx->mx_db.md_entries = NUMKEYS(fp);
4664 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
4665 mx->mx_cursor.mc_snum = 1;
4666 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
4667 mx->mx_cursor.mc_top = 0;
4668 mx->mx_cursor.mc_pg[0] = fp;
4669 mx->mx_cursor.mc_ki[0] = 0;
4670 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4671 mx->mx_db.md_flags = MDB_DUPFIXED;
4672 mx->mx_db.md_pad = fp->mp_pad;
4673 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
4674 mx->mx_db.md_flags |= MDB_INTEGERKEY;
4677 DPRINTF("Sub-db %u for db %u root page %zu", mx->mx_cursor.mc_dbi, mc->mc_dbi,
4679 mx->mx_dbflag = (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY)) ?
4681 mx->mx_dbx.md_name.mv_data = NODEKEY(node);
4682 mx->mx_dbx.md_name.mv_size = node->mn_ksize;
4683 #if UINT_MAX < SIZE_MAX
4684 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
4685 #ifdef MISALIGNED_OK
4686 mx->mx_dbx.md_cmp = mdb_cmp_long;
4688 mx->mx_dbx.md_cmp = mdb_cmp_cint;
4693 /** Initialize a cursor for a given transaction and database. */
4695 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
4700 mc->mc_db = &txn->mt_dbs[dbi];
4701 mc->mc_dbx = &txn->mt_dbxs[dbi];
4702 mc->mc_dbflag = &txn->mt_dbflags[dbi];
4705 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4707 mc->mc_xcursor = mx;
4708 mdb_xcursor_init0(mc);
4710 mc->mc_xcursor = NULL;
4715 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
4718 MDB_xcursor *mx = NULL;
4719 size_t size = sizeof(MDB_cursor);
4721 if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
4724 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
4725 size += sizeof(MDB_xcursor);
4727 if ((mc = malloc(size)) != NULL) {
4728 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4729 mx = (MDB_xcursor *)(mc + 1);
4731 mdb_cursor_init(mc, txn, dbi, mx);
4732 if (txn->mt_cursors) {
4733 mc->mc_next = txn->mt_cursors[dbi];
4734 txn->mt_cursors[dbi] = mc;
4736 mc->mc_flags |= C_ALLOCD;
4746 /* Return the count of duplicate data items for the current key */
4748 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
4752 if (mc == NULL || countp == NULL)
4755 if (!(mc->mc_db->md_flags & MDB_DUPSORT))
4758 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4759 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4762 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
4765 *countp = mc->mc_xcursor->mx_db.md_entries;
4771 mdb_cursor_close(MDB_cursor *mc)
4774 /* remove from txn, if tracked */
4775 if (mc->mc_txn->mt_cursors) {
4776 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
4777 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
4779 *prev = mc->mc_next;
4781 if (mc->mc_flags & C_ALLOCD)
4787 mdb_cursor_txn(MDB_cursor *mc)
4789 if (!mc) return NULL;
4794 mdb_cursor_dbi(MDB_cursor *mc)
4800 /** Replace the key for a node with a new key.
4801 * @param[in] mp The page containing the node to operate on.
4802 * @param[in] indx The index of the node to operate on.
4803 * @param[in] key The new key to use.
4804 * @return 0 on success, non-zero on failure.
4807 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
4809 indx_t ptr, i, numkeys;
4816 node = NODEPTR(mp, indx);
4817 ptr = mp->mp_ptrs[indx];
4818 DPRINTF("update key %u (ofs %u) [%.*s] to [%s] on page %zu",
4820 (int)node->mn_ksize, (char *)NODEKEY(node),
4824 delta = key->mv_size - node->mn_ksize;
4826 if (delta > 0 && SIZELEFT(mp) < delta) {
4827 DPRINTF("OUCH! Not enough room, delta = %d", delta);
4831 numkeys = NUMKEYS(mp);
4832 for (i = 0; i < numkeys; i++) {
4833 if (mp->mp_ptrs[i] <= ptr)
4834 mp->mp_ptrs[i] -= delta;
4837 base = (char *)mp + mp->mp_upper;
4838 len = ptr - mp->mp_upper + NODESIZE;
4839 memmove(base - delta, base, len);
4840 mp->mp_upper -= delta;
4842 node = NODEPTR(mp, indx);
4843 node->mn_ksize = key->mv_size;
4846 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
4851 /** Move a node from csrc to cdst.
4854 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
4861 /* Mark src and dst as dirty. */
4862 if ((rc = mdb_page_touch(csrc)) ||
4863 (rc = mdb_page_touch(cdst)))
4866 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4867 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
4868 key.mv_size = csrc->mc_db->md_pad;
4869 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
4871 data.mv_data = NULL;
4873 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
4874 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
4875 unsigned int snum = csrc->mc_snum;
4877 /* must find the lowest key below src */
4878 mdb_page_search_root(csrc, NULL, 0);
4879 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
4880 key.mv_size = NODEKSZ(s2);
4881 key.mv_data = NODEKEY(s2);
4882 csrc->mc_snum = snum--;
4883 csrc->mc_top = snum;
4885 key.mv_size = NODEKSZ(srcnode);
4886 key.mv_data = NODEKEY(srcnode);
4888 data.mv_size = NODEDSZ(srcnode);
4889 data.mv_data = NODEDATA(srcnode);
4891 DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
4892 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
4893 csrc->mc_ki[csrc->mc_top],
4895 csrc->mc_pg[csrc->mc_top]->mp_pgno,
4896 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
4898 /* Add the node to the destination page.
4900 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, NODEPGNO(srcnode),
4902 if (rc != MDB_SUCCESS)
4905 /* Delete the node from the source page.
4907 mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
4910 /* Adjust other cursors pointing to mp */
4911 MDB_cursor *m2, *m3;
4912 MDB_dbi dbi = csrc->mc_dbi;
4913 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
4915 if (csrc->mc_flags & C_SUB)
4918 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
4919 if (m2 == csrc) continue;
4920 if (csrc->mc_flags & C_SUB)
4921 m3 = &m2->mc_xcursor->mx_cursor;
4924 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
4925 csrc->mc_ki[csrc->mc_top]) {
4926 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
4927 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
4932 /* Update the parent separators.
4934 if (csrc->mc_ki[csrc->mc_top] == 0) {
4935 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
4936 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4937 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
4939 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
4940 key.mv_size = NODEKSZ(srcnode);
4941 key.mv_data = NODEKEY(srcnode);
4943 DPRINTF("update separator for source page %zu to [%s]",
4944 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
4945 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1],
4946 &key)) != MDB_SUCCESS)
4949 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
4951 nullkey.mv_size = 0;
4952 rc = mdb_update_key(csrc->mc_pg[csrc->mc_top], 0, &nullkey);
4953 assert(rc == MDB_SUCCESS);
4957 if (cdst->mc_ki[cdst->mc_top] == 0) {
4958 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
4959 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4960 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
4962 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
4963 key.mv_size = NODEKSZ(srcnode);
4964 key.mv_data = NODEKEY(srcnode);
4966 DPRINTF("update separator for destination page %zu to [%s]",
4967 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
4968 if ((rc = mdb_update_key(cdst->mc_pg[cdst->mc_top-1], cdst->mc_ki[cdst->mc_top-1],
4969 &key)) != MDB_SUCCESS)
4972 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
4974 nullkey.mv_size = 0;
4975 rc = mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &nullkey);
4976 assert(rc == MDB_SUCCESS);
4983 /** Merge one page into another.
4984 * The nodes from the page pointed to by \b csrc will
4985 * be copied to the page pointed to by \b cdst and then
4986 * the \b csrc page will be freed.
4987 * @param[in] csrc Cursor pointing to the source page.
4988 * @param[in] cdst Cursor pointing to the destination page.
4991 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
4999 DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
5000 cdst->mc_pg[cdst->mc_top]->mp_pgno);
5002 assert(csrc->mc_snum > 1); /* can't merge root page */
5003 assert(cdst->mc_snum > 1);
5005 /* Mark dst as dirty. */
5006 if ((rc = mdb_page_touch(cdst)))
5009 /* Move all nodes from src to dst.
5011 j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
5012 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5013 key.mv_size = csrc->mc_db->md_pad;
5014 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
5015 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
5016 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
5017 if (rc != MDB_SUCCESS)
5019 key.mv_data = (char *)key.mv_data + key.mv_size;
5022 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
5023 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
5025 key.mv_size = srcnode->mn_ksize;
5026 key.mv_data = NODEKEY(srcnode);
5027 data.mv_size = NODEDSZ(srcnode);
5028 data.mv_data = NODEDATA(srcnode);
5029 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
5030 if (rc != MDB_SUCCESS)
5035 DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
5036 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);
5038 /* Unlink the src page from parent and add to free list.
5040 mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
5041 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
5043 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], 0, &key)) != MDB_SUCCESS)
5047 mdb_midl_append(&csrc->mc_txn->mt_free_pgs, csrc->mc_pg[csrc->mc_top]->mp_pgno);
5048 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
5049 csrc->mc_db->md_leaf_pages--;
5051 csrc->mc_db->md_branch_pages--;
5053 /* Adjust other cursors pointing to mp */
5054 MDB_cursor *m2, *m3;
5055 MDB_dbi dbi = csrc->mc_dbi;
5056 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
5058 if (csrc->mc_flags & C_SUB)
5061 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5062 if (m2 == csrc) continue;
5063 if (csrc->mc_flags & C_SUB)
5064 m3 = &m2->mc_xcursor->mx_cursor;
5067 if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
5068 m3->mc_pg[csrc->mc_top] = mp;
5069 m3->mc_ki[csrc->mc_top] += nkeys;
5073 mdb_cursor_pop(csrc);
5075 return mdb_rebalance(csrc);
5078 /** Copy the contents of a cursor.
5079 * @param[in] csrc The cursor to copy from.
5080 * @param[out] cdst The cursor to copy to.
5083 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
5087 cdst->mc_txn = csrc->mc_txn;
5088 cdst->mc_dbi = csrc->mc_dbi;
5089 cdst->mc_db = csrc->mc_db;
5090 cdst->mc_dbx = csrc->mc_dbx;
5091 cdst->mc_snum = csrc->mc_snum;
5092 cdst->mc_top = csrc->mc_top;
5093 cdst->mc_flags = csrc->mc_flags;
5095 for (i=0; i<csrc->mc_snum; i++) {
5096 cdst->mc_pg[i] = csrc->mc_pg[i];
5097 cdst->mc_ki[i] = csrc->mc_ki[i];
5101 /** Rebalance the tree after a delete operation.
5102 * @param[in] mc Cursor pointing to the page where rebalancing
5104 * @return 0 on success, non-zero on failure.
5107 mdb_rebalance(MDB_cursor *mc)
5114 DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
5115 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
5116 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);
5118 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD) {
5119 DPRINTF("no need to rebalance page %zu, above fill threshold",
5120 mc->mc_pg[mc->mc_top]->mp_pgno);
5124 if (mc->mc_snum < 2) {
5125 MDB_page *mp = mc->mc_pg[0];
5126 if (NUMKEYS(mp) == 0) {
5127 DPUTS("tree is completely empty");
5128 mc->mc_db->md_root = P_INVALID;
5129 mc->mc_db->md_depth = 0;
5130 mc->mc_db->md_leaf_pages = 0;
5131 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5135 /* Adjust other cursors pointing to mp */
5136 MDB_cursor *m2, *m3;
5137 MDB_dbi dbi = mc->mc_dbi;
5139 if (mc->mc_flags & C_SUB)
5142 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5143 if (m2 == mc) continue;
5144 if (mc->mc_flags & C_SUB)
5145 m3 = &m2->mc_xcursor->mx_cursor;
5148 if (m3->mc_pg[0] == mp) {
5154 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
5155 DPUTS("collapsing root page!");
5156 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5157 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
5158 if ((rc = mdb_page_get(mc->mc_txn, mc->mc_db->md_root,
5161 mc->mc_db->md_depth--;
5162 mc->mc_db->md_branch_pages--;
5164 /* Adjust other cursors pointing to mp */
5165 MDB_cursor *m2, *m3;
5166 MDB_dbi dbi = mc->mc_dbi;
5168 if (mc->mc_flags & C_SUB)
5171 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5172 if (m2 == mc) continue;
5173 if (mc->mc_flags & C_SUB)
5174 m3 = &m2->mc_xcursor->mx_cursor;
5177 if (m3->mc_pg[0] == mp) {
5178 m3->mc_pg[0] = mc->mc_pg[0];
5183 DPUTS("root page doesn't need rebalancing");
5187 /* The parent (branch page) must have at least 2 pointers,
5188 * otherwise the tree is invalid.
5190 ptop = mc->mc_top-1;
5191 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
5193 /* Leaf page fill factor is below the threshold.
5194 * Try to move keys from left or right neighbor, or
5195 * merge with a neighbor page.
5200 mdb_cursor_copy(mc, &mn);
5201 mn.mc_xcursor = NULL;
5203 if (mc->mc_ki[ptop] == 0) {
5204 /* We're the leftmost leaf in our parent.
5206 DPUTS("reading right neighbor");
5208 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5209 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5211 mn.mc_ki[mn.mc_top] = 0;
5212 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
5214 /* There is at least one neighbor to the left.
5216 DPUTS("reading left neighbor");
5218 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5219 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5221 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
5222 mc->mc_ki[mc->mc_top] = 0;
5225 DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
5226 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);
5228 /* If the neighbor page is above threshold and has at least two
5229 * keys, move one key from it.
5231 * Otherwise we should try to merge them.
5233 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) >= 2)
5234 return mdb_node_move(&mn, mc);
5235 else { /* FIXME: if (has_enough_room()) */
5236 mc->mc_flags &= ~C_INITIALIZED;
5237 if (mc->mc_ki[ptop] == 0)
5238 return mdb_page_merge(&mn, mc);
5240 return mdb_page_merge(mc, &mn);
5244 /** Complete a delete operation started by #mdb_cursor_del(). */
5246 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
5250 /* add overflow pages to free list */
5251 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5255 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
5256 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
5257 for (i=0; i<ovpages; i++) {
5258 DPRINTF("freed ov page %zu", pg);
5259 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
5263 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], mc->mc_db->md_pad);
5264 mc->mc_db->md_entries--;
5265 rc = mdb_rebalance(mc);
5266 if (rc != MDB_SUCCESS)
5267 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5273 mdb_del(MDB_txn *txn, MDB_dbi dbi,
5274 MDB_val *key, MDB_val *data)
5279 MDB_val rdata, *xdata;
5283 assert(key != NULL);
5285 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
5287 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5290 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
5294 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
5298 mdb_cursor_init(&mc, txn, dbi, &mx);
5309 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
5311 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
5315 /** Split a page and insert a new node.
5316 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
5317 * The cursor will be updated to point to the actual page and index where
5318 * the node got inserted after the split.
5319 * @param[in] newkey The key for the newly inserted node.
5320 * @param[in] newdata The data for the newly inserted node.
5321 * @param[in] newpgno The page number, if the new node is a branch node.
5322 * @return 0 on success, non-zero on failure.
5325 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
5326 unsigned int nflags)
5329 int rc = MDB_SUCCESS, ins_new = 0, new_root = 0;
5332 unsigned int i, j, split_indx, nkeys, pmax;
5334 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
5336 MDB_page *mp, *rp, *pp;
5341 mp = mc->mc_pg[mc->mc_top];
5342 newindx = mc->mc_ki[mc->mc_top];
5344 DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
5345 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
5346 DKEY(newkey), mc->mc_ki[mc->mc_top]);
5348 if (mc->mc_snum < 2) {
5349 if ((pp = mdb_page_new(mc, P_BRANCH, 1)) == NULL)
5351 /* shift current top to make room for new parent */
5352 mc->mc_pg[1] = mc->mc_pg[0];
5353 mc->mc_ki[1] = mc->mc_ki[0];
5356 mc->mc_db->md_root = pp->mp_pgno;
5357 DPRINTF("root split! new root = %zu", pp->mp_pgno);
5358 mc->mc_db->md_depth++;
5361 /* Add left (implicit) pointer. */
5362 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
5363 /* undo the pre-push */
5364 mc->mc_pg[0] = mc->mc_pg[1];
5365 mc->mc_ki[0] = mc->mc_ki[1];
5366 mc->mc_db->md_root = mp->mp_pgno;
5367 mc->mc_db->md_depth--;
5374 ptop = mc->mc_top-1;
5375 DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
5378 /* Create a right sibling. */
5379 if ((rp = mdb_page_new(mc, mp->mp_flags, 1)) == NULL)
5381 DPRINTF("new right sibling: page %zu", rp->mp_pgno);
5383 mdb_cursor_copy(mc, &mn);
5384 mn.mc_pg[mn.mc_top] = rp;
5385 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
5387 if (nflags & MDB_APPEND) {
5388 mn.mc_ki[mn.mc_top] = 0;
5395 nkeys = NUMKEYS(mp);
5396 split_indx = nkeys / 2 + 1;
5401 unsigned int lsize, rsize, ksize;
5402 /* Move half of the keys to the right sibling */
5404 x = mc->mc_ki[mc->mc_top] - split_indx;
5405 ksize = mc->mc_db->md_pad;
5406 split = LEAF2KEY(mp, split_indx, ksize);
5407 rsize = (nkeys - split_indx) * ksize;
5408 lsize = (nkeys - split_indx) * sizeof(indx_t);
5409 mp->mp_lower -= lsize;
5410 rp->mp_lower += lsize;
5411 mp->mp_upper += rsize - lsize;
5412 rp->mp_upper -= rsize - lsize;
5413 sepkey.mv_size = ksize;
5414 if (newindx == split_indx) {
5415 sepkey.mv_data = newkey->mv_data;
5417 sepkey.mv_data = split;
5420 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
5421 memcpy(rp->mp_ptrs, split, rsize);
5422 sepkey.mv_data = rp->mp_ptrs;
5423 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
5424 memcpy(ins, newkey->mv_data, ksize);
5425 mp->mp_lower += sizeof(indx_t);
5426 mp->mp_upper -= ksize - sizeof(indx_t);
5429 memcpy(rp->mp_ptrs, split, x * ksize);
5430 ins = LEAF2KEY(rp, x, ksize);
5431 memcpy(ins, newkey->mv_data, ksize);
5432 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
5433 rp->mp_lower += sizeof(indx_t);
5434 rp->mp_upper -= ksize - sizeof(indx_t);
5435 mc->mc_ki[mc->mc_top] = x;
5436 mc->mc_pg[mc->mc_top] = rp;
5441 /* For leaf pages, check the split point based on what
5442 * fits where, since otherwise add_node can fail.
5445 unsigned int psize, nsize;
5446 /* Maximum free space in an empty page */
5447 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
5448 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
5449 if (newindx < split_indx) {
5451 for (i=0; i<split_indx; i++) {
5452 node = NODEPTR(mp, i);
5453 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
5454 if (F_ISSET(node->mn_flags, F_BIGDATA))
5455 psize += sizeof(pgno_t);
5457 psize += NODEDSZ(node);
5466 for (i=nkeys-1; i>=split_indx; i--) {
5467 node = NODEPTR(mp, i);
5468 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
5469 if (F_ISSET(node->mn_flags, F_BIGDATA))
5470 psize += sizeof(pgno_t);
5472 psize += NODEDSZ(node);
5482 /* First find the separating key between the split pages.
5484 if (newindx == split_indx) {
5485 sepkey.mv_size = newkey->mv_size;
5486 sepkey.mv_data = newkey->mv_data;
5488 node = NODEPTR(mp, split_indx);
5489 sepkey.mv_size = node->mn_ksize;
5490 sepkey.mv_data = NODEKEY(node);
5494 DPRINTF("separator is [%s]", DKEY(&sepkey));
5496 /* Copy separator key to the parent.
5498 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
5501 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
5503 /* Right page might now have changed parent.
5504 * Check if left page also changed parent.
5506 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
5507 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
5508 mc->mc_pg[ptop] = mn.mc_pg[ptop];
5509 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
5513 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
5516 if (rc != MDB_SUCCESS) {
5519 if (nflags & MDB_APPEND) {
5520 mc->mc_pg[mc->mc_top] = rp;
5521 mc->mc_ki[mc->mc_top] = 0;
5522 return mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
5528 /* Move half of the keys to the right sibling. */
5530 /* grab a page to hold a temporary copy */
5531 copy = mdb_page_malloc(mc);
5535 copy->mp_pgno = mp->mp_pgno;
5536 copy->mp_flags = mp->mp_flags;
5537 copy->mp_lower = PAGEHDRSZ;
5538 copy->mp_upper = mc->mc_txn->mt_env->me_psize;
5539 mc->mc_pg[mc->mc_top] = copy;
5540 for (i = j = 0; i <= nkeys; j++) {
5541 if (i == split_indx) {
5542 /* Insert in right sibling. */
5543 /* Reset insert index for right sibling. */
5544 j = (i == newindx && ins_new);
5545 mc->mc_pg[mc->mc_top] = rp;
5548 if (i == newindx && !ins_new) {
5549 /* Insert the original entry that caused the split. */
5550 rkey.mv_data = newkey->mv_data;
5551 rkey.mv_size = newkey->mv_size;
5560 /* Update page and index for the new key. */
5561 mc->mc_ki[mc->mc_top] = j;
5562 } else if (i == nkeys) {
5565 node = NODEPTR(mp, i);
5566 rkey.mv_data = NODEKEY(node);
5567 rkey.mv_size = node->mn_ksize;
5569 xdata.mv_data = NODEDATA(node);
5570 xdata.mv_size = NODEDSZ(node);
5573 pgno = NODEPGNO(node);
5574 flags = node->mn_flags;
5579 if (!IS_LEAF(mp) && j == 0) {
5580 /* First branch index doesn't need key data. */
5584 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
5587 nkeys = NUMKEYS(copy);
5588 for (i=0; i<nkeys; i++)
5589 mp->mp_ptrs[i] = copy->mp_ptrs[i];
5590 mp->mp_lower = copy->mp_lower;
5591 mp->mp_upper = copy->mp_upper;
5592 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
5593 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
5595 /* reset back to original page */
5596 if (newindx < split_indx) {
5597 mc->mc_pg[mc->mc_top] = mp;
5598 if (nflags & MDB_RESERVE) {
5599 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5600 if (!(node->mn_flags & F_BIGDATA))
5601 newdata->mv_data = NODEDATA(node);
5605 /* return tmp page to freelist */
5606 copy->mp_next = mc->mc_txn->mt_env->me_dpages;
5607 mc->mc_txn->mt_env->me_dpages = copy;
5610 /* Adjust other cursors pointing to mp */
5611 MDB_cursor *m2, *m3;
5612 MDB_dbi dbi = mc->mc_dbi;
5614 if (mc->mc_flags & C_SUB)
5617 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5618 if (m2 == mc) continue;
5619 if (mc->mc_flags & C_SUB)
5620 m3 = &m2->mc_xcursor->mx_cursor;
5623 if (!(m3->mc_flags & C_INITIALIZED))
5627 for (i=m3->mc_top; i>0; i--) {
5628 m3->mc_ki[i+1] = m3->mc_ki[i];
5629 m3->mc_pg[i+1] = m3->mc_pg[i];
5631 m3->mc_ki[0] = mc->mc_ki[0];
5632 m3->mc_pg[0] = mc->mc_pg[0];
5636 if (m3->mc_pg[mc->mc_top] == mp) {
5637 if (m3->mc_ki[m3->mc_top] >= split_indx) {
5638 m3->mc_pg[m3->mc_top] = rp;
5639 m3->mc_ki[m3->mc_top] -= split_indx;
5648 mdb_put(MDB_txn *txn, MDB_dbi dbi,
5649 MDB_val *key, MDB_val *data, unsigned int flags)
5654 assert(key != NULL);
5655 assert(data != NULL);
5657 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5660 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
5664 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
5668 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND)) != flags)
5671 mdb_cursor_init(&mc, txn, dbi, &mx);
5672 return mdb_cursor_put(&mc, key, data, flags);
5675 /** Only a subset of the @ref mdb_env flags can be changed
5676 * at runtime. Changing other flags requires closing the environment
5677 * and re-opening it with the new flags.
5679 #define CHANGEABLE (MDB_NOSYNC)
5681 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
5683 if ((flag & CHANGEABLE) != flag)
5686 env->me_flags |= flag;
5688 env->me_flags &= ~flag;
5693 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
5698 *arg = env->me_flags;
5703 mdb_env_get_path(MDB_env *env, const char **arg)
5708 *arg = env->me_path;
5712 /** Common code for #mdb_stat() and #mdb_env_stat().
5713 * @param[in] env the environment to operate in.
5714 * @param[in] db the #MDB_db record containing the stats to return.
5715 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
5716 * @return 0, this function always succeeds.
5719 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
5721 arg->ms_psize = env->me_psize;
5722 arg->ms_depth = db->md_depth;
5723 arg->ms_branch_pages = db->md_branch_pages;
5724 arg->ms_leaf_pages = db->md_leaf_pages;
5725 arg->ms_overflow_pages = db->md_overflow_pages;
5726 arg->ms_entries = db->md_entries;
5731 mdb_env_stat(MDB_env *env, MDB_stat *arg)
5735 if (env == NULL || arg == NULL)
5738 mdb_env_read_meta(env, &toggle);
5740 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
5743 /** Set the default comparison functions for a database.
5744 * Called immediately after a database is opened to set the defaults.
5745 * The user can then override them with #mdb_set_compare() or
5746 * #mdb_set_dupsort().
5747 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
5748 * @param[in] dbi A database handle returned by #mdb_open()
5751 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
5753 if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEKEY)
5754 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memnr;
5755 else if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERKEY)
5756 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_cint;
5758 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memn;
5760 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
5761 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP) {
5762 if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED)
5763 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_int;
5765 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_cint;
5766 } else if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEDUP) {
5767 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memnr;
5769 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memn;
5772 txn->mt_dbxs[dbi].md_dcmp = NULL;
5776 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
5781 int rc, dbflag, exact;
5784 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
5785 mdb_default_cmp(txn, FREE_DBI);
5791 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
5792 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
5793 mdb_default_cmp(txn, MAIN_DBI);
5797 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
5798 mdb_default_cmp(txn, MAIN_DBI);
5801 /* Is the DB already open? */
5803 for (i=2; i<txn->mt_numdbs; i++) {
5804 if (len == txn->mt_dbxs[i].md_name.mv_size &&
5805 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
5811 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
5814 /* Find the DB info */
5818 key.mv_data = (void *)name;
5819 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
5820 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
5821 if (rc == MDB_SUCCESS) {
5822 /* make sure this is actually a DB */
5823 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
5824 if (!(node->mn_flags & F_SUBDATA))
5826 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
5827 /* Create if requested */
5829 data.mv_size = sizeof(MDB_db);
5830 data.mv_data = &dummy;
5831 memset(&dummy, 0, sizeof(dummy));
5832 dummy.md_root = P_INVALID;
5833 dummy.md_flags = flags & 0xffff;
5834 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
5838 /* OK, got info, add to table */
5839 if (rc == MDB_SUCCESS) {
5840 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
5841 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
5842 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
5843 txn->mt_dbflags[txn->mt_numdbs] = dbflag;
5844 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
5845 *dbi = txn->mt_numdbs;
5846 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
5847 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
5848 mdb_default_cmp(txn, txn->mt_numdbs);
5855 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
5857 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
5860 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
5863 void mdb_close(MDB_env *env, MDB_dbi dbi)
5866 if (dbi <= MAIN_DBI || dbi >= env->me_numdbs)
5868 ptr = env->me_dbxs[dbi].md_name.mv_data;
5869 env->me_dbxs[dbi].md_name.mv_data = NULL;
5870 env->me_dbxs[dbi].md_name.mv_size = 0;
5874 /** Add all the DB's pages to the free list.
5875 * @param[in] mc Cursor on the DB to free.
5876 * @param[in] subs non-Zero to check for sub-DBs in this DB.
5877 * @return 0 on success, non-zero on failure.
5880 mdb_drop0(MDB_cursor *mc, int subs)
5884 rc = mdb_page_search(mc, NULL, 0);
5885 if (rc == MDB_SUCCESS) {
5890 /* LEAF2 pages have no nodes, cannot have sub-DBs */
5891 if (!subs || IS_LEAF2(mc->mc_pg[mc->mc_top]))
5894 mdb_cursor_copy(mc, &mx);
5895 while (mc->mc_snum > 0) {
5896 if (IS_LEAF(mc->mc_pg[mc->mc_top])) {
5897 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
5898 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
5899 if (ni->mn_flags & F_SUBDATA) {
5900 mdb_xcursor_init1(mc, ni);
5901 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
5907 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
5909 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
5912 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
5917 rc = mdb_cursor_sibling(mc, 1);
5919 /* no more siblings, go back to beginning
5920 * of previous level. (stack was already popped
5921 * by mdb_cursor_sibling)
5923 for (i=1; i<mc->mc_top; i++)
5924 mc->mc_pg[i] = mx.mc_pg[i];
5928 mdb_midl_append(&mc->mc_txn->mt_free_pgs,
5929 mc->mc_db->md_root);
5934 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
5939 if (!txn || !dbi || dbi >= txn->mt_numdbs)
5942 rc = mdb_cursor_open(txn, dbi, &mc);
5946 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
5950 /* Can't delete the main DB */
5951 if (del && dbi > MAIN_DBI) {
5952 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
5954 mdb_close(txn->mt_env, dbi);
5956 txn->mt_dbflags[dbi] |= DB_DIRTY;
5957 txn->mt_dbs[dbi].md_depth = 0;
5958 txn->mt_dbs[dbi].md_branch_pages = 0;
5959 txn->mt_dbs[dbi].md_leaf_pages = 0;
5960 txn->mt_dbs[dbi].md_overflow_pages = 0;
5961 txn->mt_dbs[dbi].md_entries = 0;
5962 txn->mt_dbs[dbi].md_root = P_INVALID;
5965 mdb_cursor_close(mc);
5969 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
5971 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5974 txn->mt_dbxs[dbi].md_cmp = cmp;
5978 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
5980 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5983 txn->mt_dbxs[dbi].md_dcmp = cmp;
5987 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
5989 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5992 txn->mt_dbxs[dbi].md_rel = rel;
5996 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
5998 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6001 txn->mt_dbxs[dbi].md_relctx = ctx;