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);
2965 COPY_PGNO(pgno, mp->mp_pgno);
2966 DPRINTF("searching %u keys in %s %spage %zu",
2967 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
2974 low = IS_LEAF(mp) ? 0 : 1;
2976 cmp = mc->mc_dbx->md_cmp;
2978 /* Branch pages have no data, so if using integer keys,
2979 * alignment is guaranteed. Use faster mdb_cmp_int.
2981 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
2982 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
2989 nodekey.mv_size = mc->mc_db->md_pad;
2990 node = NODEPTR(mp, 0); /* fake */
2991 while (low <= high) {
2992 i = (low + high) >> 1;
2993 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
2994 rc = cmp(key, &nodekey);
2995 DPRINTF("found leaf index %u [%s], rc = %i",
2996 i, DKEY(&nodekey), rc);
3005 while (low <= high) {
3006 i = (low + high) >> 1;
3008 node = NODEPTR(mp, i);
3009 nodekey.mv_size = NODEKSZ(node);
3010 nodekey.mv_data = NODEKEY(node);
3012 rc = cmp(key, &nodekey);
3015 DPRINTF("found leaf index %u [%s], rc = %i",
3016 i, DKEY(&nodekey), rc);
3018 DPRINTF("found branch index %u [%s -> %zu], rc = %i",
3019 i, DKEY(&nodekey), NODEPGNO(node), rc);
3030 if (rc > 0) { /* Found entry is less than the key. */
3031 i++; /* Skip to get the smallest entry larger than key. */
3033 node = NODEPTR(mp, i);
3036 *exactp = (rc == 0);
3037 /* store the key index */
3038 mc->mc_ki[mc->mc_top] = i;
3040 /* There is no entry larger or equal to the key. */
3043 /* nodeptr is fake for LEAF2 */
3049 mdb_cursor_adjust(MDB_cursor *mc, func)
3053 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
3054 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
3061 /** Pop a page off the top of the cursor's stack. */
3063 mdb_cursor_pop(MDB_cursor *mc)
3068 top = mc->mc_pg[mc->mc_top];
3073 DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
3074 mc->mc_dbi, (void *) mc);
3078 /** Push a page onto the top of the cursor's stack. */
3080 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
3082 DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
3083 mc->mc_dbi, (void *) mc);
3085 if (mc->mc_snum >= CURSOR_STACK) {
3086 assert(mc->mc_snum < CURSOR_STACK);
3090 mc->mc_top = mc->mc_snum++;
3091 mc->mc_pg[mc->mc_top] = mp;
3092 mc->mc_ki[mc->mc_top] = 0;
3097 /** Find the address of the page corresponding to a given page number.
3098 * @param[in] txn the transaction for this access.
3099 * @param[in] pgno the page number for the page to retrieve.
3100 * @param[out] ret address of a pointer where the page's address will be stored.
3101 * @return 0 on success, non-zero on failure.
3104 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
3108 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
3110 x = mdb_mid2l_search(txn->mt_u.dirty_list, pgno);
3111 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
3112 p = txn->mt_u.dirty_list[x].mptr;
3116 if (pgno <= txn->mt_env->me_metas[txn->mt_toggle]->mm_last_pg)
3117 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
3121 DPRINTF("page %zu not found", pgno);
3124 return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
3127 /** Search for the page a given key should be in.
3128 * Pushes parent pages on the cursor stack. This function continues a
3129 * search on a cursor that has already been initialized. (Usually by
3130 * #mdb_page_search() but also by #mdb_node_move().)
3131 * @param[in,out] mc the cursor for this operation.
3132 * @param[in] key the key to search for. If NULL, search for the lowest
3133 * page. (This is used by #mdb_cursor_first().)
3134 * @param[in] modify If true, visited pages are updated with new page numbers.
3135 * @return 0 on success, non-zero on failure.
3138 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
3140 MDB_page *mp = mc->mc_pg[mc->mc_top];
3145 while (IS_BRANCH(mp)) {
3149 DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
3150 assert(NUMKEYS(mp) > 1);
3151 DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
3153 if (key == NULL) /* Initialize cursor to first page. */
3155 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
3156 /* cursor to last page */
3160 node = mdb_node_search(mc, key, &exact);
3162 i = NUMKEYS(mp) - 1;
3164 i = mc->mc_ki[mc->mc_top];
3173 DPRINTF("following index %u for key [%s]",
3175 assert(i < NUMKEYS(mp));
3176 node = NODEPTR(mp, i);
3178 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp)))
3181 mc->mc_ki[mc->mc_top] = i;
3182 if ((rc = mdb_cursor_push(mc, mp)))
3186 if ((rc = mdb_page_touch(mc)) != 0)
3188 mp = mc->mc_pg[mc->mc_top];
3193 DPRINTF("internal error, index points to a %02X page!?",
3195 return MDB_CORRUPTED;
3198 DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
3199 key ? DKEY(key) : NULL);
3204 /** Search for the page a given key should be in.
3205 * Pushes parent pages on the cursor stack. This function just sets up
3206 * the search; it finds the root page for \b mc's database and sets this
3207 * as the root of the cursor's stack. Then #mdb_page_search_root() is
3208 * called to complete the search.
3209 * @param[in,out] mc the cursor for this operation.
3210 * @param[in] key the key to search for. If NULL, search for the lowest
3211 * page. (This is used by #mdb_cursor_first().)
3212 * @param[in] modify If true, visited pages are updated with new page numbers.
3213 * @return 0 on success, non-zero on failure.
3216 mdb_page_search(MDB_cursor *mc, MDB_val *key, int modify)
3221 /* Make sure the txn is still viable, then find the root from
3222 * the txn's db table.
3224 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
3225 DPUTS("transaction has failed, must abort");
3228 /* Make sure we're using an up-to-date root */
3229 if (mc->mc_dbi > MAIN_DBI) {
3230 if ((*mc->mc_dbflag & DB_STALE) ||
3231 (modify && !(*mc->mc_dbflag & DB_DIRTY))) {
3233 unsigned char dbflag = 0;
3234 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
3235 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, modify);
3238 if (*mc->mc_dbflag & DB_STALE) {
3241 MDB_node *leaf = mdb_node_search(&mc2,
3242 &mc->mc_dbx->md_name, &exact);
3244 return MDB_NOTFOUND;
3245 mdb_node_read(mc->mc_txn, leaf, &data);
3246 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
3250 *mc->mc_dbflag = dbflag;
3253 root = mc->mc_db->md_root;
3255 if (root == P_INVALID) { /* Tree is empty. */
3256 DPUTS("tree is empty");
3257 return MDB_NOTFOUND;
3262 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0])))
3268 DPRINTF("db %u root page %zu has flags 0x%X",
3269 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
3272 if ((rc = mdb_page_touch(mc)))
3276 return mdb_page_search_root(mc, key, modify);
3279 /** Return the data associated with a given node.
3280 * @param[in] txn The transaction for this operation.
3281 * @param[in] leaf The node being read.
3282 * @param[out] data Updated to point to the node's data.
3283 * @return 0 on success, non-zero on failure.
3286 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
3288 MDB_page *omp; /* overflow page */
3292 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
3293 data->mv_size = NODEDSZ(leaf);
3294 data->mv_data = NODEDATA(leaf);
3298 /* Read overflow data.
3300 data->mv_size = NODEDSZ(leaf);
3301 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
3302 if ((rc = mdb_page_get(txn, pgno, &omp))) {
3303 DPRINTF("read overflow page %zu failed", pgno);
3306 data->mv_data = METADATA(omp);
3312 mdb_get(MDB_txn *txn, MDB_dbi dbi,
3313 MDB_val *key, MDB_val *data)
3322 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
3324 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3327 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3331 mdb_cursor_init(&mc, txn, dbi, &mx);
3332 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
3335 /** Find a sibling for a page.
3336 * Replaces the page at the top of the cursor's stack with the
3337 * specified sibling, if one exists.
3338 * @param[in] mc The cursor for this operation.
3339 * @param[in] move_right Non-zero if the right sibling is requested,
3340 * otherwise the left sibling.
3341 * @return 0 on success, non-zero on failure.
3344 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
3350 if (mc->mc_snum < 2) {
3351 return MDB_NOTFOUND; /* root has no siblings */
3355 DPRINTF("parent page is page %zu, index %u",
3356 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]);
3358 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
3359 : (mc->mc_ki[mc->mc_top] == 0)) {
3360 DPRINTF("no more keys left, moving to %s sibling",
3361 move_right ? "right" : "left");
3362 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS)
3366 mc->mc_ki[mc->mc_top]++;
3368 mc->mc_ki[mc->mc_top]--;
3369 DPRINTF("just moving to %s index key %u",
3370 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]);
3372 assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
3374 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3375 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp)))
3378 mdb_cursor_push(mc, mp);
3383 /** Move the cursor to the next data item. */
3385 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3391 if (mc->mc_flags & C_EOF) {
3392 return MDB_NOTFOUND;
3395 assert(mc->mc_flags & C_INITIALIZED);
3397 mp = mc->mc_pg[mc->mc_top];
3399 if (mc->mc_db->md_flags & MDB_DUPSORT) {
3400 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3401 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3402 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
3403 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
3404 if (op != MDB_NEXT || rc == MDB_SUCCESS)
3408 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3409 if (op == MDB_NEXT_DUP)
3410 return MDB_NOTFOUND;
3414 DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3416 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
3417 DPUTS("=====> move to next sibling page");
3418 if (mdb_cursor_sibling(mc, 1) != MDB_SUCCESS) {
3419 mc->mc_flags |= C_EOF;
3420 mc->mc_flags &= ~C_INITIALIZED;
3421 return MDB_NOTFOUND;
3423 mp = mc->mc_pg[mc->mc_top];
3424 DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3426 mc->mc_ki[mc->mc_top]++;
3428 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3429 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3432 key->mv_size = mc->mc_db->md_pad;
3433 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3437 assert(IS_LEAF(mp));
3438 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3440 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3441 mdb_xcursor_init1(mc, leaf);
3444 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3447 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3448 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3449 if (rc != MDB_SUCCESS)
3454 MDB_SET_KEY(leaf, key);
3458 /** Move the cursor to the previous data item. */
3460 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3466 assert(mc->mc_flags & C_INITIALIZED);
3468 mp = mc->mc_pg[mc->mc_top];
3470 if (mc->mc_db->md_flags & MDB_DUPSORT) {
3471 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3472 if (op == MDB_PREV || op == MDB_PREV_DUP) {
3473 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3474 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
3475 if (op != MDB_PREV || rc == MDB_SUCCESS)
3478 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3479 if (op == MDB_PREV_DUP)
3480 return MDB_NOTFOUND;
3485 DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3487 if (mc->mc_ki[mc->mc_top] == 0) {
3488 DPUTS("=====> move to prev sibling page");
3489 if (mdb_cursor_sibling(mc, 0) != MDB_SUCCESS) {
3490 mc->mc_flags &= ~C_INITIALIZED;
3491 return MDB_NOTFOUND;
3493 mp = mc->mc_pg[mc->mc_top];
3494 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
3495 DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3497 mc->mc_ki[mc->mc_top]--;
3499 mc->mc_flags &= ~C_EOF;
3501 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3502 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3505 key->mv_size = mc->mc_db->md_pad;
3506 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3510 assert(IS_LEAF(mp));
3511 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3513 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3514 mdb_xcursor_init1(mc, leaf);
3517 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3520 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3521 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3522 if (rc != MDB_SUCCESS)
3527 MDB_SET_KEY(leaf, key);
3531 /** Set the cursor on a specific data item. */
3533 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3534 MDB_cursor_op op, int *exactp)
3543 assert(key->mv_size > 0);
3545 /* See if we're already on the right page */
3546 if (mc->mc_flags & C_INITIALIZED) {
3549 mp = mc->mc_pg[mc->mc_top];
3551 mc->mc_ki[mc->mc_top] = 0;
3552 return MDB_NOTFOUND;
3554 if (mp->mp_flags & P_LEAF2) {
3555 nodekey.mv_size = mc->mc_db->md_pad;
3556 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
3558 leaf = NODEPTR(mp, 0);
3559 MDB_SET_KEY(leaf, &nodekey);
3561 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3563 /* Probably happens rarely, but first node on the page
3564 * was the one we wanted.
3566 mc->mc_ki[mc->mc_top] = 0;
3567 leaf = NODEPTR(mp, 0);
3574 unsigned int nkeys = NUMKEYS(mp);
3576 if (mp->mp_flags & P_LEAF2) {
3577 nodekey.mv_data = LEAF2KEY(mp,
3578 nkeys-1, nodekey.mv_size);
3580 leaf = NODEPTR(mp, nkeys-1);
3581 MDB_SET_KEY(leaf, &nodekey);
3583 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3585 /* last node was the one we wanted */
3586 mc->mc_ki[mc->mc_top] = nkeys-1;
3587 leaf = NODEPTR(mp, nkeys-1);
3593 /* This is definitely the right page, skip search_page */
3598 /* If any parents have right-sibs, search.
3599 * Otherwise, there's nothing further.
3601 for (i=0; i<mc->mc_top; i++)
3603 NUMKEYS(mc->mc_pg[i])-1)
3605 if (i == mc->mc_top) {
3606 /* There are no other pages */
3607 mc->mc_ki[mc->mc_top] = nkeys;
3608 return MDB_NOTFOUND;
3612 /* There are no other pages */
3613 mc->mc_ki[mc->mc_top] = 0;
3614 return MDB_NOTFOUND;
3618 rc = mdb_page_search(mc, key, 0);
3619 if (rc != MDB_SUCCESS)
3622 mp = mc->mc_pg[mc->mc_top];
3623 assert(IS_LEAF(mp));
3626 leaf = mdb_node_search(mc, key, exactp);
3627 if (exactp != NULL && !*exactp) {
3628 /* MDB_SET specified and not an exact match. */
3629 return MDB_NOTFOUND;
3633 DPUTS("===> inexact leaf not found, goto sibling");
3634 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
3635 return rc; /* no entries matched */
3636 mp = mc->mc_pg[mc->mc_top];
3637 assert(IS_LEAF(mp));
3638 leaf = NODEPTR(mp, 0);
3642 mc->mc_flags |= C_INITIALIZED;
3643 mc->mc_flags &= ~C_EOF;
3646 key->mv_size = mc->mc_db->md_pad;
3647 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3651 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3652 mdb_xcursor_init1(mc, leaf);
3655 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3656 if (op == MDB_SET || op == MDB_SET_RANGE) {
3657 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3660 if (op == MDB_GET_BOTH) {
3666 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
3667 if (rc != MDB_SUCCESS)
3670 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
3672 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
3674 rc = mc->mc_dbx->md_dcmp(data, &d2);
3676 if (op == MDB_GET_BOTH || rc > 0)
3677 return MDB_NOTFOUND;
3682 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3683 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3688 /* The key already matches in all other cases */
3689 if (op == MDB_SET_RANGE)
3690 MDB_SET_KEY(leaf, key);
3691 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
3696 /** Move the cursor to the first item in the database. */
3698 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3703 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3704 rc = mdb_page_search(mc, NULL, 0);
3705 if (rc != MDB_SUCCESS)
3708 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3710 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
3711 mc->mc_flags |= C_INITIALIZED;
3712 mc->mc_flags &= ~C_EOF;
3714 mc->mc_ki[mc->mc_top] = 0;
3716 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3717 key->mv_size = mc->mc_db->md_pad;
3718 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
3723 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3724 mdb_xcursor_init1(mc, leaf);
3725 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3730 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3731 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3735 MDB_SET_KEY(leaf, key);
3739 /** Move the cursor to the last item in the database. */
3741 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3747 lkey.mv_size = MAXKEYSIZE+1;
3748 lkey.mv_data = NULL;
3750 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3751 rc = mdb_page_search(mc, &lkey, 0);
3752 if (rc != MDB_SUCCESS)
3755 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3757 leaf = NODEPTR(mc->mc_pg[mc->mc_top], NUMKEYS(mc->mc_pg[mc->mc_top])-1);
3758 mc->mc_flags |= C_INITIALIZED;
3759 mc->mc_flags &= ~C_EOF;
3761 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
3763 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3764 key->mv_size = mc->mc_db->md_pad;
3765 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
3770 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3771 mdb_xcursor_init1(mc, leaf);
3772 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3777 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3778 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3783 MDB_SET_KEY(leaf, key);
3788 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3798 case MDB_GET_BOTH_RANGE:
3799 if (data == NULL || mc->mc_xcursor == NULL) {
3806 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3808 } else if (op == MDB_SET_RANGE)
3809 rc = mdb_cursor_set(mc, key, data, op, NULL);
3811 rc = mdb_cursor_set(mc, key, data, op, &exact);
3813 case MDB_GET_MULTIPLE:
3815 !(mc->mc_db->md_flags & MDB_DUPFIXED) ||
3816 !(mc->mc_flags & C_INITIALIZED)) {
3821 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
3822 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
3825 case MDB_NEXT_MULTIPLE:
3827 !(mc->mc_db->md_flags & MDB_DUPFIXED)) {
3831 if (!(mc->mc_flags & C_INITIALIZED))
3832 rc = mdb_cursor_first(mc, key, data);
3834 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
3835 if (rc == MDB_SUCCESS) {
3836 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
3839 mx = &mc->mc_xcursor->mx_cursor;
3840 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
3842 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
3843 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
3851 case MDB_NEXT_NODUP:
3852 if (!(mc->mc_flags & C_INITIALIZED))
3853 rc = mdb_cursor_first(mc, key, data);
3855 rc = mdb_cursor_next(mc, key, data, op);
3859 case MDB_PREV_NODUP:
3860 if (!(mc->mc_flags & C_INITIALIZED) || (mc->mc_flags & C_EOF))
3861 rc = mdb_cursor_last(mc, key, data);
3863 rc = mdb_cursor_prev(mc, key, data, op);
3866 rc = mdb_cursor_first(mc, key, data);
3870 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
3871 !(mc->mc_flags & C_INITIALIZED) ||
3872 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3876 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3879 rc = mdb_cursor_last(mc, key, data);
3883 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
3884 !(mc->mc_flags & C_INITIALIZED) ||
3885 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3889 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3892 DPRINTF("unhandled/unimplemented cursor operation %u", op);
3900 /** Touch all the pages in the cursor stack.
3901 * Makes sure all the pages are writable, before attempting a write operation.
3902 * @param[in] mc The cursor to operate on.
3905 mdb_cursor_touch(MDB_cursor *mc)
3909 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
3911 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
3912 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 1);
3915 *mc->mc_dbflag = DB_DIRTY;
3917 for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
3918 rc = mdb_page_touch(mc);
3922 mc->mc_top = mc->mc_snum-1;
3927 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3930 MDB_node *leaf = NULL;
3931 MDB_val xdata, *rdata, dkey;
3935 unsigned int mcount = 0;
3938 char pbuf[MDB_PAGESIZE];
3939 char dbuf[MAXKEYSIZE+1];
3940 unsigned int nflags;
3943 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
3946 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
3947 mc->mc_dbi, DKEY(key), key ? key->mv_size:0, data->mv_size);
3951 if (flags == MDB_CURRENT) {
3952 if (!(mc->mc_flags & C_INITIALIZED))
3955 } else if (mc->mc_db->md_root == P_INVALID) {
3957 /* new database, write a root leaf page */
3958 DPUTS("allocating new root leaf page");
3959 if ((np = mdb_page_new(mc, P_LEAF, 1)) == NULL) {
3963 mdb_cursor_push(mc, np);
3964 mc->mc_db->md_root = np->mp_pgno;
3965 mc->mc_db->md_depth++;
3966 *mc->mc_dbflag = DB_DIRTY;
3967 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
3969 np->mp_flags |= P_LEAF2;
3970 mc->mc_flags |= C_INITIALIZED;
3976 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
3977 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
3978 DPRINTF("duplicate key [%s]", DKEY(key));
3980 return MDB_KEYEXIST;
3982 if (rc && rc != MDB_NOTFOUND)
3986 /* Cursor is positioned, now make sure all pages are writable */
3987 rc2 = mdb_cursor_touch(mc);
3992 /* The key already exists */
3993 if (rc == MDB_SUCCESS) {
3994 /* there's only a key anyway, so this is a no-op */
3995 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3996 unsigned int ksize = mc->mc_db->md_pad;
3997 if (key->mv_size != ksize)
3999 if (flags == MDB_CURRENT) {
4000 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
4001 memcpy(ptr, key->mv_data, ksize);
4006 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4009 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
4010 /* Was a single item before, must convert now */
4012 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4013 /* Just overwrite the current item */
4014 if (flags == MDB_CURRENT)
4017 dkey.mv_size = NODEDSZ(leaf);
4018 dkey.mv_data = NODEDATA(leaf);
4019 #if UINT_MAX < SIZE_MAX
4020 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && dkey.mv_size == sizeof(size_t))
4021 #ifdef MISALIGNED_OK
4022 mc->mc_dbx->md_dcmp = mdb_cmp_long;
4024 mc->mc_dbx->md_dcmp = mdb_cmp_cint;
4027 /* if data matches, ignore it */
4028 if (!mc->mc_dbx->md_dcmp(data, &dkey))
4029 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
4031 /* create a fake page for the dup items */
4032 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
4033 dkey.mv_data = dbuf;
4034 fp = (MDB_page *)pbuf;
4035 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4036 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
4037 fp->mp_lower = PAGEHDRSZ;
4038 fp->mp_upper = PAGEHDRSZ + dkey.mv_size + data->mv_size;
4039 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4040 fp->mp_flags |= P_LEAF2;
4041 fp->mp_pad = data->mv_size;
4043 fp->mp_upper += 2 * sizeof(indx_t) + 2 * NODESIZE +
4044 (dkey.mv_size & 1) + (data->mv_size & 1);
4046 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4049 xdata.mv_size = fp->mp_upper;
4050 xdata.mv_data = pbuf;
4054 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
4055 /* See if we need to convert from fake page to subDB */
4057 unsigned int offset;
4060 fp = NODEDATA(leaf);
4061 if (flags == MDB_CURRENT) {
4062 fp->mp_flags |= P_DIRTY;
4063 COPY_PGNO(fp->mp_pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
4064 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
4068 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4069 offset = fp->mp_pad;
4071 offset = NODESIZE + sizeof(indx_t) + data->mv_size;
4073 offset += offset & 1;
4074 if (NODESIZE + sizeof(indx_t) + NODEKSZ(leaf) + NODEDSZ(leaf) +
4075 offset >= (mc->mc_txn->mt_env->me_psize - PAGEHDRSZ) /
4077 /* yes, convert it */
4079 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4080 dummy.md_pad = fp->mp_pad;
4081 dummy.md_flags = MDB_DUPFIXED;
4082 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
4083 dummy.md_flags |= MDB_INTEGERKEY;
4086 dummy.md_branch_pages = 0;
4087 dummy.md_leaf_pages = 1;
4088 dummy.md_overflow_pages = 0;
4089 dummy.md_entries = NUMKEYS(fp);
4091 xdata.mv_size = sizeof(MDB_db);
4092 xdata.mv_data = &dummy;
4093 mp = mdb_page_alloc(mc, 1);
4096 offset = mc->mc_txn->mt_env->me_psize - NODEDSZ(leaf);
4097 flags |= F_DUPDATA|F_SUBDATA;
4098 dummy.md_root = mp->mp_pgno;
4100 /* no, just grow it */
4102 xdata.mv_size = NODEDSZ(leaf) + offset;
4103 xdata.mv_data = pbuf;
4104 mp = (MDB_page *)pbuf;
4105 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4108 mp->mp_flags = fp->mp_flags | P_DIRTY;
4109 mp->mp_pad = fp->mp_pad;
4110 mp->mp_lower = fp->mp_lower;
4111 mp->mp_upper = fp->mp_upper + offset;
4113 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
4115 nsize = NODEDSZ(leaf) - fp->mp_upper;
4116 memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper, nsize);
4117 for (i=0; i<NUMKEYS(fp); i++)
4118 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
4120 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4124 /* data is on sub-DB, just store it */
4125 flags |= F_DUPDATA|F_SUBDATA;
4129 /* same size, just replace it */
4130 if (!F_ISSET(leaf->mn_flags, F_BIGDATA) &&
4131 NODEDSZ(leaf) == data->mv_size) {
4132 if (F_ISSET(flags, MDB_RESERVE))
4133 data->mv_data = NODEDATA(leaf);
4135 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
4138 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4140 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
4146 nflags = flags & NODE_ADD_FLAGS;
4147 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
4148 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
4149 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
4150 nflags &= ~MDB_APPEND;
4151 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
4153 /* There is room already in this leaf page. */
4154 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
4155 if (rc == 0 && !do_sub) {
4156 /* Adjust other cursors pointing to mp */
4157 MDB_cursor *m2, *m3;
4158 MDB_dbi dbi = mc->mc_dbi;
4159 unsigned i = mc->mc_top;
4160 MDB_page *mp = mc->mc_pg[i];
4162 if (mc->mc_flags & C_SUB)
4165 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
4166 if (mc->mc_flags & C_SUB)
4167 m3 = &m2->mc_xcursor->mx_cursor;
4170 if (m3 == mc) continue;
4171 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
4178 if (rc != MDB_SUCCESS)
4179 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4181 /* Now store the actual data in the child DB. Note that we're
4182 * storing the user data in the keys field, so there are strict
4183 * size limits on dupdata. The actual data fields of the child
4184 * DB are all zero size.
4192 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4193 if (flags & MDB_CURRENT) {
4194 xflags = MDB_CURRENT;
4196 mdb_xcursor_init1(mc, leaf);
4197 xflags = (flags & MDB_NODUPDATA) ? MDB_NOOVERWRITE : 0;
4199 /* converted, write the original data first */
4201 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
4205 /* Adjust other cursors pointing to mp */
4207 unsigned i = mc->mc_top;
4208 MDB_page *mp = mc->mc_pg[i];
4210 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4211 if (m2 == mc) continue;
4212 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
4213 mdb_xcursor_init1(m2, leaf);
4218 xflags |= (flags & MDB_APPEND);
4219 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
4220 if (flags & F_SUBDATA) {
4221 db = NODEDATA(leaf);
4222 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4225 /* sub-writes might have failed so check rc again.
4226 * Don't increment count if we just replaced an existing item.
4228 if (!rc && !(flags & MDB_CURRENT))
4229 mc->mc_db->md_entries++;
4230 if (flags & MDB_MULTIPLE) {
4232 if (mcount < data[1].mv_size) {
4233 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
4234 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4244 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
4249 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
4252 if (!mc->mc_flags & C_INITIALIZED)
4255 rc = mdb_cursor_touch(mc);
4259 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4261 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4262 if (flags != MDB_NODUPDATA) {
4263 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
4264 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
4266 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
4267 /* If sub-DB still has entries, we're done */
4268 if (mc->mc_xcursor->mx_db.md_entries) {
4269 if (leaf->mn_flags & F_SUBDATA) {
4270 /* update subDB info */
4271 MDB_db *db = NODEDATA(leaf);
4272 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4274 /* shrink fake page */
4275 mdb_node_shrink(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4277 mc->mc_db->md_entries--;
4280 /* otherwise fall thru and delete the sub-DB */
4283 if (leaf->mn_flags & F_SUBDATA) {
4284 /* add all the child DB's pages to the free list */
4285 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
4286 if (rc == MDB_SUCCESS) {
4287 mc->mc_db->md_entries -=
4288 mc->mc_xcursor->mx_db.md_entries;
4293 return mdb_cursor_del0(mc, leaf);
4296 /** Allocate and initialize new pages for a database.
4297 * @param[in] mc a cursor on the database being added to.
4298 * @param[in] flags flags defining what type of page is being allocated.
4299 * @param[in] num the number of pages to allocate. This is usually 1,
4300 * unless allocating overflow pages for a large record.
4301 * @return Address of a page, or NULL on failure.
4304 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num)
4308 if ((np = mdb_page_alloc(mc, num)) == NULL)
4310 DPRINTF("allocated new mpage %zu, page size %u",
4311 np->mp_pgno, mc->mc_txn->mt_env->me_psize);
4312 np->mp_flags = flags | P_DIRTY;
4313 np->mp_lower = PAGEHDRSZ;
4314 np->mp_upper = mc->mc_txn->mt_env->me_psize;
4317 mc->mc_db->md_branch_pages++;
4318 else if (IS_LEAF(np))
4319 mc->mc_db->md_leaf_pages++;
4320 else if (IS_OVERFLOW(np)) {
4321 mc->mc_db->md_overflow_pages += num;
4328 /** Calculate the size of a leaf node.
4329 * The size depends on the environment's page size; if a data item
4330 * is too large it will be put onto an overflow page and the node
4331 * size will only include the key and not the data. Sizes are always
4332 * rounded up to an even number of bytes, to guarantee 2-byte alignment
4333 * of the #MDB_node headers.
4334 * @param[in] env The environment handle.
4335 * @param[in] key The key for the node.
4336 * @param[in] data The data for the node.
4337 * @return The number of bytes needed to store the node.
4340 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
4344 sz = LEAFSIZE(key, data);
4345 if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
4346 /* put on overflow page */
4347 sz -= data->mv_size - sizeof(pgno_t);
4351 return sz + sizeof(indx_t);
4354 /** Calculate the size of a branch node.
4355 * The size should depend on the environment's page size but since
4356 * we currently don't support spilling large keys onto overflow
4357 * pages, it's simply the size of the #MDB_node header plus the
4358 * size of the key. Sizes are always rounded up to an even number
4359 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
4360 * @param[in] env The environment handle.
4361 * @param[in] key The key for the node.
4362 * @return The number of bytes needed to store the node.
4365 mdb_branch_size(MDB_env *env, MDB_val *key)
4370 if (sz >= env->me_psize / MDB_MINKEYS) {
4371 /* put on overflow page */
4372 /* not implemented */
4373 /* sz -= key->size - sizeof(pgno_t); */
4376 return sz + sizeof(indx_t);
4379 /** Add a node to the page pointed to by the cursor.
4380 * @param[in] mc The cursor for this operation.
4381 * @param[in] indx The index on the page where the new node should be added.
4382 * @param[in] key The key for the new node.
4383 * @param[in] data The data for the new node, if any.
4384 * @param[in] pgno The page number, if adding a branch node.
4385 * @param[in] flags Flags for the node.
4386 * @return 0 on success, non-zero on failure. Possible errors are:
4388 * <li>ENOMEM - failed to allocate overflow pages for the node.
4389 * <li>ENOSPC - there is insufficient room in the page. This error
4390 * should never happen since all callers already calculate the
4391 * page's free space before calling this function.
4395 mdb_node_add(MDB_cursor *mc, indx_t indx,
4396 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
4399 size_t node_size = NODESIZE;
4402 MDB_page *mp = mc->mc_pg[mc->mc_top];
4403 MDB_page *ofp = NULL; /* overflow page */
4406 assert(mp->mp_upper >= mp->mp_lower);
4408 DPRINTF("add to %s %spage %zu index %i, data size %zu key size %zu [%s]",
4409 IS_LEAF(mp) ? "leaf" : "branch",
4410 IS_SUBP(mp) ? "sub-" : "",
4411 mp->mp_pgno, indx, data ? data->mv_size : 0,
4412 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
4415 /* Move higher keys up one slot. */
4416 int ksize = mc->mc_db->md_pad, dif;
4417 char *ptr = LEAF2KEY(mp, indx, ksize);
4418 dif = NUMKEYS(mp) - indx;
4420 memmove(ptr+ksize, ptr, dif*ksize);
4421 /* insert new key */
4422 memcpy(ptr, key->mv_data, ksize);
4424 /* Just using these for counting */
4425 mp->mp_lower += sizeof(indx_t);
4426 mp->mp_upper -= ksize - sizeof(indx_t);
4431 node_size += key->mv_size;
4435 if (F_ISSET(flags, F_BIGDATA)) {
4436 /* Data already on overflow page. */
4437 node_size += sizeof(pgno_t);
4438 } else if (data->mv_size >= mc->mc_txn->mt_env->me_psize / MDB_MINKEYS) {
4439 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
4440 /* Put data on overflow page. */
4441 DPRINTF("data size is %zu, put on overflow page",
4443 node_size += sizeof(pgno_t);
4444 if ((ofp = mdb_page_new(mc, P_OVERFLOW, ovpages)) == NULL)
4446 DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
4449 node_size += data->mv_size;
4452 node_size += node_size & 1;
4454 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
4455 DPRINTF("not enough room in page %zu, got %u ptrs",
4456 mp->mp_pgno, NUMKEYS(mp));
4457 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
4458 mp->mp_upper - mp->mp_lower);
4459 DPRINTF("node size = %zu", node_size);
4463 /* Move higher pointers up one slot. */
4464 for (i = NUMKEYS(mp); i > indx; i--)
4465 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
4467 /* Adjust free space offsets. */
4468 ofs = mp->mp_upper - node_size;
4469 assert(ofs >= mp->mp_lower + sizeof(indx_t));
4470 mp->mp_ptrs[indx] = ofs;
4472 mp->mp_lower += sizeof(indx_t);
4474 /* Write the node data. */
4475 node = NODEPTR(mp, indx);
4476 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
4477 node->mn_flags = flags;
4479 SETDSZ(node,data->mv_size);
4484 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
4489 if (F_ISSET(flags, F_BIGDATA))
4490 memcpy(node->mn_data + key->mv_size, data->mv_data,
4492 else if (F_ISSET(flags, MDB_RESERVE))
4493 data->mv_data = node->mn_data + key->mv_size;
4495 memcpy(node->mn_data + key->mv_size, data->mv_data,
4498 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
4500 if (F_ISSET(flags, MDB_RESERVE))
4501 data->mv_data = METADATA(ofp);
4503 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
4510 /** Delete the specified node from a page.
4511 * @param[in] mp The page to operate on.
4512 * @param[in] indx The index of the node to delete.
4513 * @param[in] ksize The size of a node. Only used if the page is
4514 * part of a #MDB_DUPFIXED database.
4517 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
4520 indx_t i, j, numkeys, ptr;
4527 COPY_PGNO(pgno, mp->mp_pgno);
4528 DPRINTF("delete node %u on %s page %zu", indx,
4529 IS_LEAF(mp) ? "leaf" : "branch", pgno);
4532 assert(indx < NUMKEYS(mp));
4535 int x = NUMKEYS(mp) - 1 - indx;
4536 base = LEAF2KEY(mp, indx, ksize);
4538 memmove(base, base + ksize, x * ksize);
4539 mp->mp_lower -= sizeof(indx_t);
4540 mp->mp_upper += ksize - sizeof(indx_t);
4544 node = NODEPTR(mp, indx);
4545 sz = NODESIZE + node->mn_ksize;
4547 if (F_ISSET(node->mn_flags, F_BIGDATA))
4548 sz += sizeof(pgno_t);
4550 sz += NODEDSZ(node);
4554 ptr = mp->mp_ptrs[indx];
4555 numkeys = NUMKEYS(mp);
4556 for (i = j = 0; i < numkeys; i++) {
4558 mp->mp_ptrs[j] = mp->mp_ptrs[i];
4559 if (mp->mp_ptrs[i] < ptr)
4560 mp->mp_ptrs[j] += sz;
4565 base = (char *)mp + mp->mp_upper;
4566 memmove(base + sz, base, ptr - mp->mp_upper);
4568 mp->mp_lower -= sizeof(indx_t);
4572 /** Compact the main page after deleting a node on a subpage.
4573 * @param[in] mp The main page to operate on.
4574 * @param[in] indx The index of the subpage on the main page.
4577 mdb_node_shrink(MDB_page *mp, indx_t indx)
4584 indx_t i, numkeys, ptr;
4586 node = NODEPTR(mp, indx);
4587 sp = (MDB_page *)NODEDATA(node);
4588 osize = NODEDSZ(node);
4590 delta = sp->mp_upper - sp->mp_lower;
4591 SETDSZ(node, osize - delta);
4592 xp = (MDB_page *)((char *)sp + delta);
4594 /* shift subpage upward */
4596 nsize = NUMKEYS(sp) * sp->mp_pad;
4597 memmove(METADATA(xp), METADATA(sp), nsize);
4600 nsize = osize - sp->mp_upper;
4601 numkeys = NUMKEYS(sp);
4602 for (i=numkeys-1; i>=0; i--)
4603 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
4605 xp->mp_upper = sp->mp_lower;
4606 xp->mp_lower = sp->mp_lower;
4607 xp->mp_flags = sp->mp_flags;
4608 xp->mp_pad = sp->mp_pad;
4609 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
4611 /* shift lower nodes upward */
4612 ptr = mp->mp_ptrs[indx];
4613 numkeys = NUMKEYS(mp);
4614 for (i = 0; i < numkeys; i++) {
4615 if (mp->mp_ptrs[i] <= ptr)
4616 mp->mp_ptrs[i] += delta;
4619 base = (char *)mp + mp->mp_upper;
4620 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
4621 mp->mp_upper += delta;
4624 /** Initial setup of a sorted-dups cursor.
4625 * Sorted duplicates are implemented as a sub-database for the given key.
4626 * The duplicate data items are actually keys of the sub-database.
4627 * Operations on the duplicate data items are performed using a sub-cursor
4628 * initialized when the sub-database is first accessed. This function does
4629 * the preliminary setup of the sub-cursor, filling in the fields that
4630 * depend only on the parent DB.
4631 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4634 mdb_xcursor_init0(MDB_cursor *mc)
4636 MDB_xcursor *mx = mc->mc_xcursor;
4638 mx->mx_cursor.mc_xcursor = NULL;
4639 mx->mx_cursor.mc_txn = mc->mc_txn;
4640 mx->mx_cursor.mc_db = &mx->mx_db;
4641 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
4642 mx->mx_cursor.mc_dbi = mc->mc_dbi+1;
4643 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
4644 mx->mx_cursor.mc_snum = 0;
4645 mx->mx_cursor.mc_flags = C_SUB;
4646 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
4647 mx->mx_dbx.md_dcmp = NULL;
4648 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
4651 /** Final setup of a sorted-dups cursor.
4652 * Sets up the fields that depend on the data from the main cursor.
4653 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4654 * @param[in] node The data containing the #MDB_db record for the
4655 * sorted-dup database.
4658 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
4660 MDB_xcursor *mx = mc->mc_xcursor;
4662 if (node->mn_flags & F_SUBDATA) {
4663 MDB_db *db = NODEDATA(node);
4665 mx->mx_cursor.mc_snum = 0;
4666 mx->mx_cursor.mc_flags = C_SUB;
4668 MDB_page *fp = NODEDATA(node);
4669 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
4670 mx->mx_db.md_flags = 0;
4671 mx->mx_db.md_depth = 1;
4672 mx->mx_db.md_branch_pages = 0;
4673 mx->mx_db.md_leaf_pages = 1;
4674 mx->mx_db.md_overflow_pages = 0;
4675 mx->mx_db.md_entries = NUMKEYS(fp);
4676 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
4677 mx->mx_cursor.mc_snum = 1;
4678 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
4679 mx->mx_cursor.mc_top = 0;
4680 mx->mx_cursor.mc_pg[0] = fp;
4681 mx->mx_cursor.mc_ki[0] = 0;
4682 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4683 mx->mx_db.md_flags = MDB_DUPFIXED;
4684 mx->mx_db.md_pad = fp->mp_pad;
4685 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
4686 mx->mx_db.md_flags |= MDB_INTEGERKEY;
4689 DPRINTF("Sub-db %u for db %u root page %zu", mx->mx_cursor.mc_dbi, mc->mc_dbi,
4691 mx->mx_dbflag = (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY)) ?
4693 mx->mx_dbx.md_name.mv_data = NODEKEY(node);
4694 mx->mx_dbx.md_name.mv_size = node->mn_ksize;
4695 #if UINT_MAX < SIZE_MAX
4696 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
4697 #ifdef MISALIGNED_OK
4698 mx->mx_dbx.md_cmp = mdb_cmp_long;
4700 mx->mx_dbx.md_cmp = mdb_cmp_cint;
4705 /** Initialize a cursor for a given transaction and database. */
4707 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
4712 mc->mc_db = &txn->mt_dbs[dbi];
4713 mc->mc_dbx = &txn->mt_dbxs[dbi];
4714 mc->mc_dbflag = &txn->mt_dbflags[dbi];
4717 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4719 mc->mc_xcursor = mx;
4720 mdb_xcursor_init0(mc);
4722 mc->mc_xcursor = NULL;
4727 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
4730 MDB_xcursor *mx = NULL;
4731 size_t size = sizeof(MDB_cursor);
4733 if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
4736 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
4737 size += sizeof(MDB_xcursor);
4739 if ((mc = malloc(size)) != NULL) {
4740 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4741 mx = (MDB_xcursor *)(mc + 1);
4743 mdb_cursor_init(mc, txn, dbi, mx);
4744 if (txn->mt_cursors) {
4745 mc->mc_next = txn->mt_cursors[dbi];
4746 txn->mt_cursors[dbi] = mc;
4748 mc->mc_flags |= C_ALLOCD;
4758 /* Return the count of duplicate data items for the current key */
4760 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
4764 if (mc == NULL || countp == NULL)
4767 if (!(mc->mc_db->md_flags & MDB_DUPSORT))
4770 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4771 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4774 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
4777 *countp = mc->mc_xcursor->mx_db.md_entries;
4783 mdb_cursor_close(MDB_cursor *mc)
4786 /* remove from txn, if tracked */
4787 if (mc->mc_txn->mt_cursors) {
4788 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
4789 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
4791 *prev = mc->mc_next;
4793 if (mc->mc_flags & C_ALLOCD)
4799 mdb_cursor_txn(MDB_cursor *mc)
4801 if (!mc) return NULL;
4806 mdb_cursor_dbi(MDB_cursor *mc)
4812 /** Replace the key for a node with a new key.
4813 * @param[in] mp The page containing the node to operate on.
4814 * @param[in] indx The index of the node to operate on.
4815 * @param[in] key The new key to use.
4816 * @return 0 on success, non-zero on failure.
4819 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
4821 indx_t ptr, i, numkeys;
4828 node = NODEPTR(mp, indx);
4829 ptr = mp->mp_ptrs[indx];
4830 DPRINTF("update key %u (ofs %u) [%.*s] to [%s] on page %zu",
4832 (int)node->mn_ksize, (char *)NODEKEY(node),
4836 delta = key->mv_size - node->mn_ksize;
4838 if (delta > 0 && SIZELEFT(mp) < delta) {
4839 DPRINTF("OUCH! Not enough room, delta = %d", delta);
4843 numkeys = NUMKEYS(mp);
4844 for (i = 0; i < numkeys; i++) {
4845 if (mp->mp_ptrs[i] <= ptr)
4846 mp->mp_ptrs[i] -= delta;
4849 base = (char *)mp + mp->mp_upper;
4850 len = ptr - mp->mp_upper + NODESIZE;
4851 memmove(base - delta, base, len);
4852 mp->mp_upper -= delta;
4854 node = NODEPTR(mp, indx);
4855 node->mn_ksize = key->mv_size;
4858 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
4863 /** Move a node from csrc to cdst.
4866 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
4873 /* Mark src and dst as dirty. */
4874 if ((rc = mdb_page_touch(csrc)) ||
4875 (rc = mdb_page_touch(cdst)))
4878 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4879 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
4880 key.mv_size = csrc->mc_db->md_pad;
4881 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
4883 data.mv_data = NULL;
4885 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
4886 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
4887 unsigned int snum = csrc->mc_snum;
4889 /* must find the lowest key below src */
4890 mdb_page_search_root(csrc, NULL, 0);
4891 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
4892 key.mv_size = NODEKSZ(s2);
4893 key.mv_data = NODEKEY(s2);
4894 csrc->mc_snum = snum--;
4895 csrc->mc_top = snum;
4897 key.mv_size = NODEKSZ(srcnode);
4898 key.mv_data = NODEKEY(srcnode);
4900 data.mv_size = NODEDSZ(srcnode);
4901 data.mv_data = NODEDATA(srcnode);
4903 DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
4904 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
4905 csrc->mc_ki[csrc->mc_top],
4907 csrc->mc_pg[csrc->mc_top]->mp_pgno,
4908 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
4910 /* Add the node to the destination page.
4912 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, NODEPGNO(srcnode),
4914 if (rc != MDB_SUCCESS)
4917 /* Delete the node from the source page.
4919 mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
4922 /* Adjust other cursors pointing to mp */
4923 MDB_cursor *m2, *m3;
4924 MDB_dbi dbi = csrc->mc_dbi;
4925 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
4927 if (csrc->mc_flags & C_SUB)
4930 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
4931 if (m2 == csrc) continue;
4932 if (csrc->mc_flags & C_SUB)
4933 m3 = &m2->mc_xcursor->mx_cursor;
4936 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
4937 csrc->mc_ki[csrc->mc_top]) {
4938 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
4939 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
4944 /* Update the parent separators.
4946 if (csrc->mc_ki[csrc->mc_top] == 0) {
4947 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
4948 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4949 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
4951 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
4952 key.mv_size = NODEKSZ(srcnode);
4953 key.mv_data = NODEKEY(srcnode);
4955 DPRINTF("update separator for source page %zu to [%s]",
4956 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
4957 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1],
4958 &key)) != MDB_SUCCESS)
4961 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
4963 nullkey.mv_size = 0;
4964 rc = mdb_update_key(csrc->mc_pg[csrc->mc_top], 0, &nullkey);
4965 assert(rc == MDB_SUCCESS);
4969 if (cdst->mc_ki[cdst->mc_top] == 0) {
4970 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
4971 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4972 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
4974 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
4975 key.mv_size = NODEKSZ(srcnode);
4976 key.mv_data = NODEKEY(srcnode);
4978 DPRINTF("update separator for destination page %zu to [%s]",
4979 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
4980 if ((rc = mdb_update_key(cdst->mc_pg[cdst->mc_top-1], cdst->mc_ki[cdst->mc_top-1],
4981 &key)) != MDB_SUCCESS)
4984 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
4986 nullkey.mv_size = 0;
4987 rc = mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &nullkey);
4988 assert(rc == MDB_SUCCESS);
4995 /** Merge one page into another.
4996 * The nodes from the page pointed to by \b csrc will
4997 * be copied to the page pointed to by \b cdst and then
4998 * the \b csrc page will be freed.
4999 * @param[in] csrc Cursor pointing to the source page.
5000 * @param[in] cdst Cursor pointing to the destination page.
5003 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
5011 DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
5012 cdst->mc_pg[cdst->mc_top]->mp_pgno);
5014 assert(csrc->mc_snum > 1); /* can't merge root page */
5015 assert(cdst->mc_snum > 1);
5017 /* Mark dst as dirty. */
5018 if ((rc = mdb_page_touch(cdst)))
5021 /* Move all nodes from src to dst.
5023 j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
5024 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5025 key.mv_size = csrc->mc_db->md_pad;
5026 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
5027 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
5028 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
5029 if (rc != MDB_SUCCESS)
5031 key.mv_data = (char *)key.mv_data + key.mv_size;
5034 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
5035 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
5037 key.mv_size = srcnode->mn_ksize;
5038 key.mv_data = NODEKEY(srcnode);
5039 data.mv_size = NODEDSZ(srcnode);
5040 data.mv_data = NODEDATA(srcnode);
5041 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
5042 if (rc != MDB_SUCCESS)
5047 DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
5048 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);
5050 /* Unlink the src page from parent and add to free list.
5052 mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
5053 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
5055 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], 0, &key)) != MDB_SUCCESS)
5059 mdb_midl_append(&csrc->mc_txn->mt_free_pgs, csrc->mc_pg[csrc->mc_top]->mp_pgno);
5060 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
5061 csrc->mc_db->md_leaf_pages--;
5063 csrc->mc_db->md_branch_pages--;
5065 /* Adjust other cursors pointing to mp */
5066 MDB_cursor *m2, *m3;
5067 MDB_dbi dbi = csrc->mc_dbi;
5068 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
5070 if (csrc->mc_flags & C_SUB)
5073 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5074 if (m2 == csrc) continue;
5075 if (csrc->mc_flags & C_SUB)
5076 m3 = &m2->mc_xcursor->mx_cursor;
5079 if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
5080 m3->mc_pg[csrc->mc_top] = mp;
5081 m3->mc_ki[csrc->mc_top] += nkeys;
5085 mdb_cursor_pop(csrc);
5087 return mdb_rebalance(csrc);
5090 /** Copy the contents of a cursor.
5091 * @param[in] csrc The cursor to copy from.
5092 * @param[out] cdst The cursor to copy to.
5095 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
5099 cdst->mc_txn = csrc->mc_txn;
5100 cdst->mc_dbi = csrc->mc_dbi;
5101 cdst->mc_db = csrc->mc_db;
5102 cdst->mc_dbx = csrc->mc_dbx;
5103 cdst->mc_snum = csrc->mc_snum;
5104 cdst->mc_top = csrc->mc_top;
5105 cdst->mc_flags = csrc->mc_flags;
5107 for (i=0; i<csrc->mc_snum; i++) {
5108 cdst->mc_pg[i] = csrc->mc_pg[i];
5109 cdst->mc_ki[i] = csrc->mc_ki[i];
5113 /** Rebalance the tree after a delete operation.
5114 * @param[in] mc Cursor pointing to the page where rebalancing
5116 * @return 0 on success, non-zero on failure.
5119 mdb_rebalance(MDB_cursor *mc)
5129 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
5130 DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
5131 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
5132 pgno, NUMKEYS(mc->mc_pg[mc->mc_top]), (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10);
5136 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD) {
5139 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
5140 DPRINTF("no need to rebalance page %zu, above fill threshold",
5146 if (mc->mc_snum < 2) {
5147 MDB_page *mp = mc->mc_pg[0];
5148 if (NUMKEYS(mp) == 0) {
5149 DPUTS("tree is completely empty");
5150 mc->mc_db->md_root = P_INVALID;
5151 mc->mc_db->md_depth = 0;
5152 mc->mc_db->md_leaf_pages = 0;
5153 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5157 /* Adjust other cursors pointing to mp */
5158 MDB_cursor *m2, *m3;
5159 MDB_dbi dbi = mc->mc_dbi;
5161 if (mc->mc_flags & C_SUB)
5164 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5165 if (m2 == mc) continue;
5166 if (mc->mc_flags & C_SUB)
5167 m3 = &m2->mc_xcursor->mx_cursor;
5170 if (m3->mc_pg[0] == mp) {
5176 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
5177 DPUTS("collapsing root page!");
5178 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5179 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
5180 if ((rc = mdb_page_get(mc->mc_txn, mc->mc_db->md_root,
5183 mc->mc_db->md_depth--;
5184 mc->mc_db->md_branch_pages--;
5186 /* Adjust other cursors pointing to mp */
5187 MDB_cursor *m2, *m3;
5188 MDB_dbi dbi = mc->mc_dbi;
5190 if (mc->mc_flags & C_SUB)
5193 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5194 if (m2 == mc) continue;
5195 if (mc->mc_flags & C_SUB)
5196 m3 = &m2->mc_xcursor->mx_cursor;
5199 if (m3->mc_pg[0] == mp) {
5200 m3->mc_pg[0] = mc->mc_pg[0];
5205 DPUTS("root page doesn't need rebalancing");
5209 /* The parent (branch page) must have at least 2 pointers,
5210 * otherwise the tree is invalid.
5212 ptop = mc->mc_top-1;
5213 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
5215 /* Leaf page fill factor is below the threshold.
5216 * Try to move keys from left or right neighbor, or
5217 * merge with a neighbor page.
5222 mdb_cursor_copy(mc, &mn);
5223 mn.mc_xcursor = NULL;
5225 if (mc->mc_ki[ptop] == 0) {
5226 /* We're the leftmost leaf in our parent.
5228 DPUTS("reading right neighbor");
5230 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5231 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5233 mn.mc_ki[mn.mc_top] = 0;
5234 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
5236 /* There is at least one neighbor to the left.
5238 DPUTS("reading left neighbor");
5240 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5241 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5243 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
5244 mc->mc_ki[mc->mc_top] = 0;
5247 DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
5248 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);
5250 /* If the neighbor page is above threshold and has at least two
5251 * keys, move one key from it.
5253 * Otherwise we should try to merge them.
5255 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) >= 2)
5256 return mdb_node_move(&mn, mc);
5257 else { /* FIXME: if (has_enough_room()) */
5258 mc->mc_flags &= ~C_INITIALIZED;
5259 if (mc->mc_ki[ptop] == 0)
5260 return mdb_page_merge(&mn, mc);
5262 return mdb_page_merge(mc, &mn);
5266 /** Complete a delete operation started by #mdb_cursor_del(). */
5268 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
5272 /* add overflow pages to free list */
5273 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5277 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
5278 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
5279 for (i=0; i<ovpages; i++) {
5280 DPRINTF("freed ov page %zu", pg);
5281 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
5285 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], mc->mc_db->md_pad);
5286 mc->mc_db->md_entries--;
5287 rc = mdb_rebalance(mc);
5288 if (rc != MDB_SUCCESS)
5289 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5295 mdb_del(MDB_txn *txn, MDB_dbi dbi,
5296 MDB_val *key, MDB_val *data)
5301 MDB_val rdata, *xdata;
5305 assert(key != NULL);
5307 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
5309 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5312 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
5316 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
5320 mdb_cursor_init(&mc, txn, dbi, &mx);
5331 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
5333 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
5337 /** Split a page and insert a new node.
5338 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
5339 * The cursor will be updated to point to the actual page and index where
5340 * the node got inserted after the split.
5341 * @param[in] newkey The key for the newly inserted node.
5342 * @param[in] newdata The data for the newly inserted node.
5343 * @param[in] newpgno The page number, if the new node is a branch node.
5344 * @return 0 on success, non-zero on failure.
5347 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
5348 unsigned int nflags)
5351 int rc = MDB_SUCCESS, ins_new = 0, new_root = 0;
5354 unsigned int i, j, split_indx, nkeys, pmax;
5356 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
5358 MDB_page *mp, *rp, *pp;
5363 mp = mc->mc_pg[mc->mc_top];
5364 newindx = mc->mc_ki[mc->mc_top];
5366 DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
5367 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
5368 DKEY(newkey), mc->mc_ki[mc->mc_top]);
5370 if (mc->mc_snum < 2) {
5371 if ((pp = mdb_page_new(mc, P_BRANCH, 1)) == NULL)
5373 /* shift current top to make room for new parent */
5374 mc->mc_pg[1] = mc->mc_pg[0];
5375 mc->mc_ki[1] = mc->mc_ki[0];
5378 mc->mc_db->md_root = pp->mp_pgno;
5379 DPRINTF("root split! new root = %zu", pp->mp_pgno);
5380 mc->mc_db->md_depth++;
5383 /* Add left (implicit) pointer. */
5384 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
5385 /* undo the pre-push */
5386 mc->mc_pg[0] = mc->mc_pg[1];
5387 mc->mc_ki[0] = mc->mc_ki[1];
5388 mc->mc_db->md_root = mp->mp_pgno;
5389 mc->mc_db->md_depth--;
5396 ptop = mc->mc_top-1;
5397 DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
5400 /* Create a right sibling. */
5401 if ((rp = mdb_page_new(mc, mp->mp_flags, 1)) == NULL)
5403 DPRINTF("new right sibling: page %zu", rp->mp_pgno);
5405 mdb_cursor_copy(mc, &mn);
5406 mn.mc_pg[mn.mc_top] = rp;
5407 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
5409 if (nflags & MDB_APPEND) {
5410 mn.mc_ki[mn.mc_top] = 0;
5417 nkeys = NUMKEYS(mp);
5418 split_indx = nkeys / 2 + 1;
5423 unsigned int lsize, rsize, ksize;
5424 /* Move half of the keys to the right sibling */
5426 x = mc->mc_ki[mc->mc_top] - split_indx;
5427 ksize = mc->mc_db->md_pad;
5428 split = LEAF2KEY(mp, split_indx, ksize);
5429 rsize = (nkeys - split_indx) * ksize;
5430 lsize = (nkeys - split_indx) * sizeof(indx_t);
5431 mp->mp_lower -= lsize;
5432 rp->mp_lower += lsize;
5433 mp->mp_upper += rsize - lsize;
5434 rp->mp_upper -= rsize - lsize;
5435 sepkey.mv_size = ksize;
5436 if (newindx == split_indx) {
5437 sepkey.mv_data = newkey->mv_data;
5439 sepkey.mv_data = split;
5442 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
5443 memcpy(rp->mp_ptrs, split, rsize);
5444 sepkey.mv_data = rp->mp_ptrs;
5445 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
5446 memcpy(ins, newkey->mv_data, ksize);
5447 mp->mp_lower += sizeof(indx_t);
5448 mp->mp_upper -= ksize - sizeof(indx_t);
5451 memcpy(rp->mp_ptrs, split, x * ksize);
5452 ins = LEAF2KEY(rp, x, ksize);
5453 memcpy(ins, newkey->mv_data, ksize);
5454 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
5455 rp->mp_lower += sizeof(indx_t);
5456 rp->mp_upper -= ksize - sizeof(indx_t);
5457 mc->mc_ki[mc->mc_top] = x;
5458 mc->mc_pg[mc->mc_top] = rp;
5463 /* For leaf pages, check the split point based on what
5464 * fits where, since otherwise add_node can fail.
5467 unsigned int psize, nsize;
5468 /* Maximum free space in an empty page */
5469 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
5470 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
5471 if (newindx < split_indx) {
5473 for (i=0; i<split_indx; i++) {
5474 node = NODEPTR(mp, i);
5475 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
5476 if (F_ISSET(node->mn_flags, F_BIGDATA))
5477 psize += sizeof(pgno_t);
5479 psize += NODEDSZ(node);
5488 for (i=nkeys-1; i>=split_indx; i--) {
5489 node = NODEPTR(mp, i);
5490 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
5491 if (F_ISSET(node->mn_flags, F_BIGDATA))
5492 psize += sizeof(pgno_t);
5494 psize += NODEDSZ(node);
5504 /* First find the separating key between the split pages.
5506 if (newindx == split_indx) {
5507 sepkey.mv_size = newkey->mv_size;
5508 sepkey.mv_data = newkey->mv_data;
5510 node = NODEPTR(mp, split_indx);
5511 sepkey.mv_size = node->mn_ksize;
5512 sepkey.mv_data = NODEKEY(node);
5516 DPRINTF("separator is [%s]", DKEY(&sepkey));
5518 /* Copy separator key to the parent.
5520 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
5523 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
5525 /* Right page might now have changed parent.
5526 * Check if left page also changed parent.
5528 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
5529 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
5530 mc->mc_pg[ptop] = mn.mc_pg[ptop];
5531 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
5535 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
5538 if (rc != MDB_SUCCESS) {
5541 if (nflags & MDB_APPEND) {
5542 mc->mc_pg[mc->mc_top] = rp;
5543 mc->mc_ki[mc->mc_top] = 0;
5544 return mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
5550 /* Move half of the keys to the right sibling. */
5552 /* grab a page to hold a temporary copy */
5553 copy = mdb_page_malloc(mc);
5557 copy->mp_pgno = mp->mp_pgno;
5558 copy->mp_flags = mp->mp_flags;
5559 copy->mp_lower = PAGEHDRSZ;
5560 copy->mp_upper = mc->mc_txn->mt_env->me_psize;
5561 mc->mc_pg[mc->mc_top] = copy;
5562 for (i = j = 0; i <= nkeys; j++) {
5563 if (i == split_indx) {
5564 /* Insert in right sibling. */
5565 /* Reset insert index for right sibling. */
5566 j = (i == newindx && ins_new);
5567 mc->mc_pg[mc->mc_top] = rp;
5570 if (i == newindx && !ins_new) {
5571 /* Insert the original entry that caused the split. */
5572 rkey.mv_data = newkey->mv_data;
5573 rkey.mv_size = newkey->mv_size;
5582 /* Update page and index for the new key. */
5583 mc->mc_ki[mc->mc_top] = j;
5584 } else if (i == nkeys) {
5587 node = NODEPTR(mp, i);
5588 rkey.mv_data = NODEKEY(node);
5589 rkey.mv_size = node->mn_ksize;
5591 xdata.mv_data = NODEDATA(node);
5592 xdata.mv_size = NODEDSZ(node);
5595 pgno = NODEPGNO(node);
5596 flags = node->mn_flags;
5601 if (!IS_LEAF(mp) && j == 0) {
5602 /* First branch index doesn't need key data. */
5606 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
5609 nkeys = NUMKEYS(copy);
5610 for (i=0; i<nkeys; i++)
5611 mp->mp_ptrs[i] = copy->mp_ptrs[i];
5612 mp->mp_lower = copy->mp_lower;
5613 mp->mp_upper = copy->mp_upper;
5614 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
5615 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
5617 /* reset back to original page */
5618 if (newindx < split_indx) {
5619 mc->mc_pg[mc->mc_top] = mp;
5620 if (nflags & MDB_RESERVE) {
5621 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5622 if (!(node->mn_flags & F_BIGDATA))
5623 newdata->mv_data = NODEDATA(node);
5627 /* return tmp page to freelist */
5628 copy->mp_next = mc->mc_txn->mt_env->me_dpages;
5629 mc->mc_txn->mt_env->me_dpages = copy;
5632 /* Adjust other cursors pointing to mp */
5633 MDB_cursor *m2, *m3;
5634 MDB_dbi dbi = mc->mc_dbi;
5636 if (mc->mc_flags & C_SUB)
5639 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5640 if (m2 == mc) continue;
5641 if (mc->mc_flags & C_SUB)
5642 m3 = &m2->mc_xcursor->mx_cursor;
5645 if (!(m3->mc_flags & C_INITIALIZED))
5649 for (i=m3->mc_top; i>0; i--) {
5650 m3->mc_ki[i+1] = m3->mc_ki[i];
5651 m3->mc_pg[i+1] = m3->mc_pg[i];
5653 m3->mc_ki[0] = mc->mc_ki[0];
5654 m3->mc_pg[0] = mc->mc_pg[0];
5658 if (m3->mc_pg[mc->mc_top] == mp) {
5659 if (m3->mc_ki[m3->mc_top] >= split_indx) {
5660 m3->mc_pg[m3->mc_top] = rp;
5661 m3->mc_ki[m3->mc_top] -= split_indx;
5670 mdb_put(MDB_txn *txn, MDB_dbi dbi,
5671 MDB_val *key, MDB_val *data, unsigned int flags)
5676 assert(key != NULL);
5677 assert(data != NULL);
5679 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5682 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
5686 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
5690 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND)) != flags)
5693 mdb_cursor_init(&mc, txn, dbi, &mx);
5694 return mdb_cursor_put(&mc, key, data, flags);
5697 /** Only a subset of the @ref mdb_env flags can be changed
5698 * at runtime. Changing other flags requires closing the environment
5699 * and re-opening it with the new flags.
5701 #define CHANGEABLE (MDB_NOSYNC)
5703 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
5705 if ((flag & CHANGEABLE) != flag)
5708 env->me_flags |= flag;
5710 env->me_flags &= ~flag;
5715 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
5720 *arg = env->me_flags;
5725 mdb_env_get_path(MDB_env *env, const char **arg)
5730 *arg = env->me_path;
5734 /** Common code for #mdb_stat() and #mdb_env_stat().
5735 * @param[in] env the environment to operate in.
5736 * @param[in] db the #MDB_db record containing the stats to return.
5737 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
5738 * @return 0, this function always succeeds.
5741 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
5743 arg->ms_psize = env->me_psize;
5744 arg->ms_depth = db->md_depth;
5745 arg->ms_branch_pages = db->md_branch_pages;
5746 arg->ms_leaf_pages = db->md_leaf_pages;
5747 arg->ms_overflow_pages = db->md_overflow_pages;
5748 arg->ms_entries = db->md_entries;
5753 mdb_env_stat(MDB_env *env, MDB_stat *arg)
5757 if (env == NULL || arg == NULL)
5760 mdb_env_read_meta(env, &toggle);
5762 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
5765 /** Set the default comparison functions for a database.
5766 * Called immediately after a database is opened to set the defaults.
5767 * The user can then override them with #mdb_set_compare() or
5768 * #mdb_set_dupsort().
5769 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
5770 * @param[in] dbi A database handle returned by #mdb_open()
5773 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
5775 if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEKEY)
5776 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memnr;
5777 else if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERKEY)
5778 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_cint;
5780 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memn;
5782 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
5783 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP) {
5784 if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED)
5785 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_int;
5787 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_cint;
5788 } else if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEDUP) {
5789 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memnr;
5791 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memn;
5794 txn->mt_dbxs[dbi].md_dcmp = NULL;
5798 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
5803 int rc, dbflag, exact;
5806 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
5807 mdb_default_cmp(txn, FREE_DBI);
5813 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
5814 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
5815 mdb_default_cmp(txn, MAIN_DBI);
5819 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
5820 mdb_default_cmp(txn, MAIN_DBI);
5823 /* Is the DB already open? */
5825 for (i=2; i<txn->mt_numdbs; i++) {
5826 if (len == txn->mt_dbxs[i].md_name.mv_size &&
5827 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
5833 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
5836 /* Find the DB info */
5840 key.mv_data = (void *)name;
5841 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
5842 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
5843 if (rc == MDB_SUCCESS) {
5844 /* make sure this is actually a DB */
5845 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
5846 if (!(node->mn_flags & F_SUBDATA))
5848 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
5849 /* Create if requested */
5851 data.mv_size = sizeof(MDB_db);
5852 data.mv_data = &dummy;
5853 memset(&dummy, 0, sizeof(dummy));
5854 dummy.md_root = P_INVALID;
5855 dummy.md_flags = flags & 0xffff;
5856 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
5860 /* OK, got info, add to table */
5861 if (rc == MDB_SUCCESS) {
5862 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
5863 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
5864 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
5865 txn->mt_dbflags[txn->mt_numdbs] = dbflag;
5866 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
5867 *dbi = txn->mt_numdbs;
5868 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
5869 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
5870 mdb_default_cmp(txn, txn->mt_numdbs);
5877 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
5879 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
5882 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
5885 void mdb_close(MDB_env *env, MDB_dbi dbi)
5888 if (dbi <= MAIN_DBI || dbi >= env->me_numdbs)
5890 ptr = env->me_dbxs[dbi].md_name.mv_data;
5891 env->me_dbxs[dbi].md_name.mv_data = NULL;
5892 env->me_dbxs[dbi].md_name.mv_size = 0;
5896 /** Add all the DB's pages to the free list.
5897 * @param[in] mc Cursor on the DB to free.
5898 * @param[in] subs non-Zero to check for sub-DBs in this DB.
5899 * @return 0 on success, non-zero on failure.
5902 mdb_drop0(MDB_cursor *mc, int subs)
5906 rc = mdb_page_search(mc, NULL, 0);
5907 if (rc == MDB_SUCCESS) {
5912 /* LEAF2 pages have no nodes, cannot have sub-DBs */
5913 if (!subs || IS_LEAF2(mc->mc_pg[mc->mc_top]))
5916 mdb_cursor_copy(mc, &mx);
5917 while (mc->mc_snum > 0) {
5918 if (IS_LEAF(mc->mc_pg[mc->mc_top])) {
5919 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
5920 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
5921 if (ni->mn_flags & F_SUBDATA) {
5922 mdb_xcursor_init1(mc, ni);
5923 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
5929 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
5931 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
5934 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
5939 rc = mdb_cursor_sibling(mc, 1);
5941 /* no more siblings, go back to beginning
5942 * of previous level. (stack was already popped
5943 * by mdb_cursor_sibling)
5945 for (i=1; i<mc->mc_top; i++)
5946 mc->mc_pg[i] = mx.mc_pg[i];
5950 mdb_midl_append(&mc->mc_txn->mt_free_pgs,
5951 mc->mc_db->md_root);
5956 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
5961 if (!txn || !dbi || dbi >= txn->mt_numdbs)
5964 rc = mdb_cursor_open(txn, dbi, &mc);
5968 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
5972 /* Can't delete the main DB */
5973 if (del && dbi > MAIN_DBI) {
5974 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
5976 mdb_close(txn->mt_env, dbi);
5978 txn->mt_dbflags[dbi] |= DB_DIRTY;
5979 txn->mt_dbs[dbi].md_depth = 0;
5980 txn->mt_dbs[dbi].md_branch_pages = 0;
5981 txn->mt_dbs[dbi].md_leaf_pages = 0;
5982 txn->mt_dbs[dbi].md_overflow_pages = 0;
5983 txn->mt_dbs[dbi].md_entries = 0;
5984 txn->mt_dbs[dbi].md_root = P_INVALID;
5987 mdb_cursor_close(mc);
5991 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
5993 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5996 txn->mt_dbxs[dbi].md_cmp = cmp;
6000 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
6002 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6005 txn->mt_dbxs[dbi].md_dcmp = cmp;
6009 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
6011 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6014 txn->mt_dbxs[dbi].md_rel = rel;
6018 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
6020 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6023 txn->mt_dbxs[dbi].md_relctx = ctx;