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 /** A page number in the database.
206 * Note that 64 bit page numbers are overkill, since pages themselves
207 * already represent 12-13 bits of addressable memory, and the OS will
208 * always limit applications to a maximum of 63 bits of address space.
210 * @note In the #MDB_node structure, we only store 48 bits of this value,
211 * which thus limits us to only 60 bits of addressable data.
215 /** A transaction ID.
216 * See struct MDB_txn.mt_txnid for details.
220 /** @defgroup debug Debug Macros
224 /** Enable debug output.
225 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
226 * read from and written to the database (used for free space management).
231 #if !(__STDC_VERSION__ >= 199901L || defined(__GNUC__))
232 # define DPRINTF (void) /* Vararg macros may be unsupported */
234 /** Print a debug message with printf formatting. */
235 # define DPRINTF(fmt, ...) /**< Requires 2 or more args */ \
236 fprintf(stderr, "%s:%d " fmt "\n", __func__, __LINE__, __VA_ARGS__)
238 # define DPRINTF(fmt, ...) ((void) 0)
240 /** Print a debug string.
241 * The string is printed literally, with no format processing.
243 #define DPUTS(arg) DPRINTF("%s", arg)
246 /** A default memory page size.
247 * The actual size is platform-dependent, but we use this for
248 * boot-strapping. We probably should not be using this any more.
249 * The #GET_PAGESIZE() macro is used to get the actual size.
251 * Note that we don't currently support Huge pages. On Linux,
252 * regular data files cannot use Huge pages, and in general
253 * Huge pages aren't actually pageable. We rely on the OS
254 * demand-pager to read our data and page it out when memory
255 * pressure from other processes is high. So until OSs have
256 * actual paging support for Huge pages, they're not viable.
258 #define MDB_PAGESIZE 4096
260 /** The minimum number of keys required in a database page.
261 * Setting this to a larger value will place a smaller bound on the
262 * maximum size of a data item. Data items larger than this size will
263 * be pushed into overflow pages instead of being stored directly in
264 * the B-tree node. This value used to default to 4. With a page size
265 * of 4096 bytes that meant that any item larger than 1024 bytes would
266 * go into an overflow page. That also meant that on average 2-3KB of
267 * each overflow page was wasted space. The value cannot be lower than
268 * 2 because then there would no longer be a tree structure. With this
269 * value, items larger than 2KB will go into overflow pages, and on
270 * average only 1KB will be wasted.
272 #define MDB_MINKEYS 2
274 /** A stamp that identifies a file as an MDB file.
275 * There's nothing special about this value other than that it is easily
276 * recognizable, and it will reflect any byte order mismatches.
278 #define MDB_MAGIC 0xBEEFC0DE
280 /** The version number for a database's file format. */
281 #define MDB_VERSION 1
283 /** The maximum size of a key in the database.
284 * While data items have essentially unbounded size, we require that
285 * keys all fit onto a regular page. This limit could be raised a bit
286 * further if needed; to something just under #MDB_PAGESIZE / #MDB_MINKEYS.
288 #define MAXKEYSIZE 511
293 * This is used for printing a hex dump of a key's contents.
295 #define DKBUF char kbuf[(MAXKEYSIZE*2+1)]
296 /** Display a key in hex.
298 * Invoke a function to display a key in hex.
300 #define DKEY(x) mdb_dkey(x, kbuf)
302 #define DKBUF typedef int dummy_kbuf /* so we can put ';' after */
306 /** @defgroup lazylock Lazy Locking
307 * Macros for locks that are't actually needed.
308 * The DB view is always consistent because all writes are wrapped in
309 * the wmutex. Finer-grained locks aren't necessary.
313 /** Use lazy locking. I.e., don't lock these accesses at all. */
317 /** Grab the reader lock */
318 #define LAZY_MUTEX_LOCK(x)
319 /** Release the reader lock */
320 #define LAZY_MUTEX_UNLOCK(x)
321 /** Release the DB table reader/writer lock */
322 #define LAZY_RWLOCK_UNLOCK(x)
323 /** Grab the DB table write lock */
324 #define LAZY_RWLOCK_WRLOCK(x)
325 /** Grab the DB table read lock */
326 #define LAZY_RWLOCK_RDLOCK(x)
327 /** Declare the DB table rwlock. Should not be followed by ';'. */
328 #define LAZY_RWLOCK_DEF(x)
329 /** Initialize the DB table rwlock */
330 #define LAZY_RWLOCK_INIT(x,y)
331 /** Destroy the DB table rwlock */
332 #define LAZY_RWLOCK_DESTROY(x)
334 #define LAZY_MUTEX_LOCK(x) pthread_mutex_lock(x)
335 #define LAZY_MUTEX_UNLOCK(x) pthread_mutex_unlock(x)
336 #define LAZY_RWLOCK_UNLOCK(x) pthread_rwlock_unlock(x)
337 #define LAZY_RWLOCK_WRLOCK(x) pthread_rwlock_wrlock(x)
338 #define LAZY_RWLOCK_RDLOCK(x) pthread_rwlock_rdlock(x)
339 #define LAZY_RWLOCK_DEF(x) pthread_rwlock_t x;
340 #define LAZY_RWLOCK_INIT(x,y) pthread_rwlock_init(x,y)
341 #define LAZY_RWLOCK_DESTROY(x) pthread_rwlock_destroy(x)
345 /** An invalid page number.
346 * Mainly used to denote an empty tree.
348 #define P_INVALID (~0UL)
350 /** Test if a flag \b f is set in a flag word \b w. */
351 #define F_ISSET(w, f) (((w) & (f)) == (f))
353 /** Used for offsets within a single page.
354 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
357 typedef uint16_t indx_t;
359 /** Default size of memory map.
360 * This is certainly too small for any actual applications. Apps should always set
361 * the size explicitly using #mdb_env_set_mapsize().
363 #define DEFAULT_MAPSIZE 1048576
365 /** @defgroup readers Reader Lock Table
366 * Readers don't acquire any locks for their data access. Instead, they
367 * simply record their transaction ID in the reader table. The reader
368 * mutex is needed just to find an empty slot in the reader table. The
369 * slot's address is saved in thread-specific data so that subsequent read
370 * transactions started by the same thread need no further locking to proceed.
372 * Since the database uses multi-version concurrency control, readers don't
373 * actually need any locking. This table is used to keep track of which
374 * readers are using data from which old transactions, so that we'll know
375 * when a particular old transaction is no longer in use. Old transactions
376 * that have discarded any data pages can then have those pages reclaimed
377 * for use by a later write transaction.
379 * The lock table is constructed such that reader slots are aligned with the
380 * processor's cache line size. Any slot is only ever used by one thread.
381 * This alignment guarantees that there will be no contention or cache
382 * thrashing as threads update their own slot info, and also eliminates
383 * any need for locking when accessing a slot.
385 * A writer thread will scan every slot in the table to determine the oldest
386 * outstanding reader transaction. Any freed pages older than this will be
387 * reclaimed by the writer. The writer doesn't use any locks when scanning
388 * this table. This means that there's no guarantee that the writer will
389 * see the most up-to-date reader info, but that's not required for correct
390 * operation - all we need is to know the upper bound on the oldest reader,
391 * we don't care at all about the newest reader. So the only consequence of
392 * reading stale information here is that old pages might hang around a
393 * while longer before being reclaimed. That's actually good anyway, because
394 * the longer we delay reclaiming old pages, the more likely it is that a
395 * string of contiguous pages can be found after coalescing old pages from
396 * many old transactions together.
398 * @todo We don't actually do such coalescing yet, we grab pages from one
399 * old transaction at a time.
402 /** Number of slots in the reader table.
403 * This value was chosen somewhat arbitrarily. 126 readers plus a
404 * couple mutexes fit exactly into 8KB on my development machine.
405 * Applications should set the table size using #mdb_env_set_maxreaders().
407 #define DEFAULT_READERS 126
409 /** The size of a CPU cache line in bytes. We want our lock structures
410 * aligned to this size to avoid false cache line sharing in the
412 * This value works for most CPUs. For Itanium this should be 128.
418 /** The information we store in a single slot of the reader table.
419 * In addition to a transaction ID, we also record the process and
420 * thread ID that owns a slot, so that we can detect stale information,
421 * e.g. threads or processes that went away without cleaning up.
422 * @note We currently don't check for stale records. We simply re-init
423 * the table when we know that we're the only process opening the
426 typedef struct MDB_rxbody {
427 /** The current Transaction ID when this transaction began.
428 * Multiple readers that start at the same time will probably have the
429 * same ID here. Again, it's not important to exclude them from
430 * anything; all we need to know is which version of the DB they
431 * started from so we can avoid overwriting any data used in that
432 * particular version.
435 /** The process ID of the process owning this reader txn. */
437 /** The thread ID of the thread owning this txn. */
441 /** The actual reader record, with cacheline padding. */
442 typedef struct MDB_reader {
445 /** shorthand for mrb_txnid */
446 #define mr_txnid mru.mrx.mrb_txnid
447 #define mr_pid mru.mrx.mrb_pid
448 #define mr_tid mru.mrx.mrb_tid
449 /** cache line alignment */
450 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
454 /** The header for the reader table.
455 * The table resides in a memory-mapped file. (This is a different file
456 * than is used for the main database.)
458 * For POSIX the actual mutexes reside in the shared memory of this
459 * mapped file. On Windows, mutexes are named objects allocated by the
460 * kernel; we store the mutex names in this mapped file so that other
461 * processes can grab them. This same approach is also used on
462 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
463 * process-shared POSIX mutexes. For these cases where a named object
464 * is used, the object name is derived from a 64 bit FNV hash of the
465 * environment pathname. As such, naming collisions are extremely
466 * unlikely. If a collision occurs, the results are unpredictable.
468 typedef struct MDB_txbody {
469 /** Stamp identifying this as an MDB lock file. It must be set
472 /** Version number of this lock file. Must be set to #MDB_VERSION. */
473 uint32_t mtb_version;
474 #if defined(_WIN32) || defined(__APPLE__)
475 char mtb_rmname[MNAME_LEN];
477 /** Mutex protecting access to this table.
478 * This is the reader lock that #LOCK_MUTEX_R acquires.
480 pthread_mutex_t mtb_mutex;
482 /** The ID of the last transaction committed to the database.
483 * This is recorded here only for convenience; the value can always
484 * be determined by reading the main database meta pages.
487 /** The number of slots that have been used in the reader table.
488 * This always records the maximum count, it is not decremented
489 * when readers release their slots.
491 unsigned mtb_numreaders;
492 /** The ID of the most recent meta page in the database.
493 * This is recorded here only for convenience; the value can always
494 * be determined by reading the main database meta pages.
496 uint32_t mtb_me_toggle;
499 /** The actual reader table definition. */
500 typedef struct MDB_txninfo {
503 #define mti_magic mt1.mtb.mtb_magic
504 #define mti_version mt1.mtb.mtb_version
505 #define mti_mutex mt1.mtb.mtb_mutex
506 #define mti_rmname mt1.mtb.mtb_rmname
507 #define mti_txnid mt1.mtb.mtb_txnid
508 #define mti_numreaders mt1.mtb.mtb_numreaders
509 #define mti_me_toggle mt1.mtb.mtb_me_toggle
510 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
513 #if defined(_WIN32) || defined(__APPLE__)
514 char mt2_wmname[MNAME_LEN];
515 #define mti_wmname mt2.mt2_wmname
517 pthread_mutex_t mt2_wmutex;
518 #define mti_wmutex mt2.mt2_wmutex
520 char pad[(sizeof(pthread_mutex_t)+CACHELINE-1) & ~(CACHELINE-1)];
522 MDB_reader mti_readers[1];
526 /** Common header for all page types.
527 * Overflow records occupy a number of contiguous pages with no
528 * headers on any page after the first.
530 typedef struct MDB_page {
531 #define mp_pgno mp_p.p_pgno
532 #define mp_next mp_p.p_next
534 pgno_t p_pgno; /**< page number */
535 void * p_next; /**< for in-memory list of freed structs */
538 /** @defgroup mdb_page Page Flags
540 * Flags for the page headers.
543 #define P_BRANCH 0x01 /**< branch page */
544 #define P_LEAF 0x02 /**< leaf page */
545 #define P_OVERFLOW 0x04 /**< overflow page */
546 #define P_META 0x08 /**< meta page */
547 #define P_DIRTY 0x10 /**< dirty page */
548 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
549 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
551 uint16_t mp_flags; /**< @ref mdb_page */
552 #define mp_lower mp_pb.pb.pb_lower
553 #define mp_upper mp_pb.pb.pb_upper
554 #define mp_pages mp_pb.pb_pages
557 indx_t pb_lower; /**< lower bound of free space */
558 indx_t pb_upper; /**< upper bound of free space */
560 uint32_t pb_pages; /**< number of overflow pages */
562 indx_t mp_ptrs[1]; /**< dynamic size */
565 /** Size of the page header, excluding dynamic data at the end */
566 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
568 /** Address of first usable data byte in a page, after the header */
569 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
571 /** Number of nodes on a page */
572 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
574 /** The amount of space remaining in the page */
575 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
577 /** The percentage of space used in the page, in tenths of a percent. */
578 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
579 ((env)->me_psize - PAGEHDRSZ))
580 /** The minimum page fill factor, in tenths of a percent.
581 * Pages emptier than this are candidates for merging.
583 #define FILL_THRESHOLD 250
585 /** Test if a page is a leaf page */
586 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
587 /** Test if a page is a LEAF2 page */
588 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
589 /** Test if a page is a branch page */
590 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
591 /** Test if a page is an overflow page */
592 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
593 /** Test if a page is a sub page */
594 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
596 /** The number of overflow pages needed to store the given size. */
597 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
599 /** Header for a single key/data pair within a page.
600 * We guarantee 2-byte alignment for nodes.
602 typedef struct MDB_node {
603 /** lo and hi are used for data size on leaf nodes and for
604 * child pgno on branch nodes. On 64 bit platforms, flags
605 * is also used for pgno. (Branch nodes have no flags).
606 * They are in host byte order in case that lets some
607 * accesses be optimized into a 32-bit word access.
609 #define mn_lo mn_offset[BYTE_ORDER!=LITTLE_ENDIAN]
610 #define mn_hi mn_offset[BYTE_ORDER==LITTLE_ENDIAN] /**< part of dsize or pgno */
611 unsigned short mn_offset[2]; /**< storage for #mn_lo and #mn_hi */
612 /** @defgroup mdb_node Node Flags
614 * Flags for node headers.
617 #define F_BIGDATA 0x01 /**< data put on overflow page */
618 #define F_SUBDATA 0x02 /**< data is a sub-database */
619 #define F_DUPDATA 0x04 /**< data has duplicates */
621 /** valid flags for #mdb_node_add() */
622 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
625 unsigned short mn_flags; /**< @ref mdb_node */
626 unsigned short mn_ksize; /**< key size */
627 char mn_data[1]; /**< key and data are appended here */
630 /** Size of the node header, excluding dynamic data at the end */
631 #define NODESIZE offsetof(MDB_node, mn_data)
633 /** Bit position of top word in page number, for shifting mn_flags */
634 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
636 /** Size of a node in a branch page with a given key.
637 * This is just the node header plus the key, there is no data.
639 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
641 /** Size of a node in a leaf page with a given key and data.
642 * This is node header plus key plus data size.
644 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
646 /** Address of node \b i in page \b p */
647 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
649 /** Address of the key for the node */
650 #define NODEKEY(node) (void *)((node)->mn_data)
652 /** Address of the data for a node */
653 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
655 /** Get the page number pointed to by a branch node */
656 #define NODEPGNO(node) \
657 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
658 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
659 /** Set the page number in a branch node */
660 #define SETPGNO(node,pgno) do { \
661 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
662 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
664 /** Get the size of the data in a leaf node */
665 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
666 /** Set the size of the data for a leaf node */
667 #define SETDSZ(node,size) do { \
668 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
669 /** The size of a key in a node */
670 #define NODEKSZ(node) ((node)->mn_ksize)
672 /** Copy a page number from src to dst */
674 #define COPY_PGNO(dst,src) dst = src
676 #if SIZE_MAX > 4294967295UL
677 #define COPY_PGNO(dst,src) do { \
678 unsigned short *s, *d; \
679 s = (unsigned short *)&(src); \
680 d = (unsigned short *)&(dst); \
687 #define COPY_PGNO(dst,src) do { \
688 unsigned short *s, *d; \
689 s = (unsigned short *)&(src); \
690 d = (unsigned short *)&(dst); \
696 /** The address of a key in a LEAF2 page.
697 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
698 * There are no node headers, keys are stored contiguously.
700 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
702 /** Set the \b node's key into \b key, if requested. */
703 #define MDB_SET_KEY(node, key) { if ((key) != NULL) { \
704 (key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node); } }
706 /** Information about a single database in the environment. */
707 typedef struct MDB_db {
708 uint32_t md_pad; /**< also ksize for LEAF2 pages */
709 uint16_t md_flags; /**< @ref mdb_open */
710 uint16_t md_depth; /**< depth of this tree */
711 pgno_t md_branch_pages; /**< number of internal pages */
712 pgno_t md_leaf_pages; /**< number of leaf pages */
713 pgno_t md_overflow_pages; /**< number of overflow pages */
714 size_t md_entries; /**< number of data items */
715 pgno_t md_root; /**< the root page of this tree */
718 /** Handle for the DB used to track free pages. */
720 /** Handle for the default DB. */
723 /** Meta page content. */
724 typedef struct MDB_meta {
725 /** Stamp identifying this as an MDB data file. It must be set
728 /** Version number of this lock file. Must be set to #MDB_VERSION. */
730 void *mm_address; /**< address for fixed mapping */
731 size_t mm_mapsize; /**< size of mmap region */
732 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
733 /** The size of pages used in this DB */
734 #define mm_psize mm_dbs[0].md_pad
735 /** Any persistent environment flags. @ref mdb_env */
736 #define mm_flags mm_dbs[0].md_flags
737 pgno_t mm_last_pg; /**< last used page in file */
738 txnid_t mm_txnid; /**< txnid that committed this page */
741 /** Auxiliary DB info.
742 * The information here is mostly static/read-only. There is
743 * only a single copy of this record in the environment.
745 typedef struct MDB_dbx {
746 MDB_val md_name; /**< name of the database */
747 MDB_cmp_func *md_cmp; /**< function for comparing keys */
748 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
749 MDB_rel_func *md_rel; /**< user relocate function */
750 void *md_relctx; /**< user-provided context for md_rel */
753 /** A database transaction.
754 * Every operation requires a transaction handle.
757 MDB_txn *mt_parent; /**< parent of a nested txn */
758 MDB_txn *mt_child; /**< nested txn under this txn */
759 pgno_t mt_next_pgno; /**< next unallocated page */
760 /** The ID of this transaction. IDs are integers incrementing from 1.
761 * Only committed write transactions increment the ID. If a transaction
762 * aborts, the ID may be re-used by the next writer.
765 MDB_env *mt_env; /**< the DB environment */
766 /** The list of pages that became unused during this transaction.
770 ID2L dirty_list; /**< modified pages */
771 MDB_reader *reader; /**< this thread's slot in the reader table */
773 /** Array of records for each DB known in the environment. */
775 /** Array of MDB_db records for each known DB */
777 /** @defgroup mt_dbflag Transaction DB Flags
781 #define DB_DIRTY 0x01 /**< DB was written in this txn */
782 #define DB_STALE 0x02 /**< DB record is older than txnID */
784 /** Array of cursors for each DB */
785 MDB_cursor **mt_cursors;
786 /** Array of flags for each DB */
787 unsigned char *mt_dbflags;
788 /** Number of DB records in use. This number only ever increments;
789 * we don't decrement it when individual DB handles are closed.
793 /** @defgroup mdb_txn Transaction Flags
797 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
798 #define MDB_TXN_ERROR 0x02 /**< an error has occurred */
800 unsigned int mt_flags; /**< @ref mdb_txn */
801 /** Tracks which of the two meta pages was used at the start
802 * of this transaction.
804 unsigned int mt_toggle;
807 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
808 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
809 * raise this on a 64 bit machine.
811 #define CURSOR_STACK 32
815 /** Cursors are used for all DB operations */
817 /** Next cursor on this DB in this txn */
819 /** Original cursor if this is a shadow */
821 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
822 struct MDB_xcursor *mc_xcursor;
823 /** The transaction that owns this cursor */
825 /** The database handle this cursor operates on */
827 /** The database record for this cursor */
829 /** The database auxiliary record for this cursor */
831 /** The @ref mt_dbflag for this database */
832 unsigned char *mc_dbflag;
833 unsigned short mc_snum; /**< number of pushed pages */
834 unsigned short mc_top; /**< index of top page, mc_snum-1 */
835 /** @defgroup mdb_cursor Cursor Flags
837 * Cursor state flags.
840 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
841 #define C_EOF 0x02 /**< No more data */
842 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
843 #define C_SHADOW 0x08 /**< Cursor is a dup from a parent txn */
844 #define C_ALLOCD 0x10 /**< Cursor was malloc'd */
846 unsigned int mc_flags; /**< @ref mdb_cursor */
847 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
848 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
851 /** Context for sorted-dup records.
852 * We could have gone to a fully recursive design, with arbitrarily
853 * deep nesting of sub-databases. But for now we only handle these
854 * levels - main DB, optional sub-DB, sorted-duplicate DB.
856 typedef struct MDB_xcursor {
857 /** A sub-cursor for traversing the Dup DB */
858 MDB_cursor mx_cursor;
859 /** The database record for this Dup DB */
861 /** The auxiliary DB record for this Dup DB */
863 /** The @ref mt_dbflag for this Dup DB */
864 unsigned char mx_dbflag;
867 /** A set of pages freed by an earlier transaction. */
868 typedef struct MDB_oldpages {
869 /** Usually we only read one record from the FREEDB at a time, but
870 * in case we read more, this will chain them together.
872 struct MDB_oldpages *mo_next;
873 /** The ID of the transaction in which these pages were freed. */
875 /** An #IDL of the pages */
876 pgno_t mo_pages[1]; /* dynamic */
879 /** The database environment. */
881 HANDLE me_fd; /**< The main data file */
882 HANDLE me_lfd; /**< The lock file */
883 HANDLE me_mfd; /**< just for writing the meta pages */
884 /** Failed to update the meta page. Probably an I/O error. */
885 #define MDB_FATAL_ERROR 0x80000000U
886 uint32_t me_flags; /**< @ref mdb_env */
887 uint32_t me_extrapad; /**< unused for now */
888 unsigned int me_maxreaders; /**< size of the reader table */
889 MDB_dbi me_numdbs; /**< number of DBs opened */
890 MDB_dbi me_maxdbs; /**< size of the DB table */
891 char *me_path; /**< path to the DB files */
892 char *me_map; /**< the memory map of the data file */
893 MDB_txninfo *me_txns; /**< the memory map of the lock file */
894 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
895 MDB_txn *me_txn; /**< current write transaction */
896 size_t me_mapsize; /**< size of the data memory map */
897 off_t me_size; /**< current file size */
898 pgno_t me_maxpg; /**< me_mapsize / me_psize */
899 unsigned int me_psize; /**< size of a page, from #GET_PAGESIZE */
900 unsigned int me_db_toggle; /**< which DB table is current */
901 txnid_t me_wtxnid; /**< ID of last txn we committed */
902 MDB_dbx *me_dbxs; /**< array of static DB info */
903 MDB_db *me_dbs[2]; /**< two arrays of MDB_db info */
904 MDB_oldpages *me_pghead; /**< list of old page records */
905 pthread_key_t me_txkey; /**< thread-key for readers */
906 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
907 /** IDL of pages that became unused in a write txn */
909 /** ID2L of pages that were written during a write txn */
910 ID2 me_dirty_list[MDB_IDL_UM_SIZE];
911 /** rwlock for the DB tables, if #LAZY_LOCKS is false */
912 LAZY_RWLOCK_DEF(me_dblock)
914 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
918 sem_t *me_rmutex; /* Apple doesn't support shared mutexes */
922 /** max number of pages to commit in one writev() call */
923 #define MDB_COMMIT_PAGES 64
925 static MDB_page *mdb_page_alloc(MDB_cursor *mc, int num);
926 static MDB_page *mdb_page_new(MDB_cursor *mc, uint32_t flags, int num);
927 static int mdb_page_touch(MDB_cursor *mc);
929 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
930 static int mdb_page_search_root(MDB_cursor *mc,
931 MDB_val *key, int modify);
932 static int mdb_page_search(MDB_cursor *mc,
933 MDB_val *key, int modify);
934 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
935 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
936 pgno_t newpgno, unsigned int nflags);
938 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
939 static int mdb_env_read_meta(MDB_env *env, int *which);
940 static int mdb_env_write_meta(MDB_txn *txn);
942 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
943 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
944 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
945 static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
946 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
947 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
948 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
949 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
950 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
952 static int mdb_rebalance(MDB_cursor *mc);
953 static int mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
955 static void mdb_cursor_pop(MDB_cursor *mc);
956 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
958 static int mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
959 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
960 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
961 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
962 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
964 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
965 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
967 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
968 static void mdb_xcursor_init0(MDB_cursor *mc);
969 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
971 static int mdb_drop0(MDB_cursor *mc, int subs);
972 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
975 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
979 static SECURITY_DESCRIPTOR mdb_null_sd;
980 static SECURITY_ATTRIBUTES mdb_all_sa;
981 static int mdb_sec_inited;
984 /** Return the library version info. */
986 mdb_version(int *major, int *minor, int *patch)
988 if (major) *major = MDB_VERSION_MAJOR;
989 if (minor) *minor = MDB_VERSION_MINOR;
990 if (patch) *patch = MDB_VERSION_PATCH;
991 return MDB_VERSION_STRING;
994 /** Table of descriptions for MDB @ref errors */
995 static char *const mdb_errstr[] = {
996 "MDB_KEYEXIST: Key/data pair already exists",
997 "MDB_NOTFOUND: No matching key/data pair found",
998 "MDB_PAGE_NOTFOUND: Requested page not found",
999 "MDB_CORRUPTED: Located page was wrong type",
1000 "MDB_PANIC: Update of meta page failed",
1001 "MDB_VERSION_MISMATCH: Database environment version mismatch"
1005 mdb_strerror(int err)
1008 return ("Successful return: 0");
1010 if (err >= MDB_KEYEXIST && err <= MDB_VERSION_MISMATCH)
1011 return mdb_errstr[err - MDB_KEYEXIST];
1013 return strerror(err);
1017 /** Display a key in hexadecimal and return the address of the result.
1018 * @param[in] key the key to display
1019 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1020 * @return The key in hexadecimal form.
1023 mdb_dkey(MDB_val *key, char *buf)
1026 unsigned char *c = key->mv_data;
1028 if (key->mv_size > MAXKEYSIZE)
1029 return "MAXKEYSIZE";
1030 /* may want to make this a dynamic check: if the key is mostly
1031 * printable characters, print it as-is instead of converting to hex.
1034 for (i=0; i<key->mv_size; i++)
1035 ptr += sprintf(ptr, "%02x", *c++);
1037 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1044 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1046 return txn->mt_dbxs[dbi].md_cmp(a, b);
1050 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1052 if (txn->mt_dbxs[dbi].md_dcmp)
1053 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1055 return EINVAL; /* too bad you can't distinguish this from a valid result */
1058 /** Allocate a single page.
1059 * Re-use old malloc'd pages first, otherwise just malloc.
1062 mdb_page_malloc(MDB_cursor *mc) {
1064 if (mc->mc_txn->mt_env->me_dpages) {
1065 ret = mc->mc_txn->mt_env->me_dpages;
1066 mc->mc_txn->mt_env->me_dpages = ret->mp_next;
1068 ret = malloc(mc->mc_txn->mt_env->me_psize);
1073 /** Allocate pages for writing.
1074 * If there are free pages available from older transactions, they
1075 * will be re-used first. Otherwise a new page will be allocated.
1076 * @param[in] mc cursor A cursor handle identifying the transaction and
1077 * database for which we are allocating.
1078 * @param[in] num the number of pages to allocate.
1079 * @return Address of the allocated page(s). Requests for multiple pages
1080 * will always be satisfied by a single contiguous chunk of memory.
1083 mdb_page_alloc(MDB_cursor *mc, int num)
1085 MDB_txn *txn = mc->mc_txn;
1087 pgno_t pgno = P_INVALID;
1090 if (txn->mt_txnid > 2) {
1092 if (!txn->mt_env->me_pghead && mc->mc_dbi != FREE_DBI &&
1093 txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
1094 /* See if there's anything in the free DB */
1097 txnid_t *kptr, oldest;
1099 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1100 mdb_page_search(&m2, NULL, 0);
1101 leaf = NODEPTR(m2.mc_pg[m2.mc_top], 0);
1102 kptr = (txnid_t *)NODEKEY(leaf);
1106 oldest = txn->mt_txnid - 1;
1107 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
1108 txnid_t mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
1109 if (mr && mr < oldest)
1114 if (oldest > *kptr) {
1115 /* It's usable, grab it.
1121 mdb_node_read(txn, leaf, &data);
1122 idl = (ID *) data.mv_data;
1123 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
1124 mop->mo_next = txn->mt_env->me_pghead;
1125 mop->mo_txnid = *kptr;
1126 txn->mt_env->me_pghead = mop;
1127 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
1132 DPRINTF("IDL read txn %zu root %zu num %zu",
1133 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1134 for (i=0; i<idl[0]; i++) {
1135 DPRINTF("IDL %zu", idl[i+1]);
1139 /* drop this IDL from the DB */
1140 m2.mc_ki[m2.mc_top] = 0;
1141 m2.mc_flags = C_INITIALIZED;
1142 mdb_cursor_del(&m2, 0);
1145 if (txn->mt_env->me_pghead) {
1146 MDB_oldpages *mop = txn->mt_env->me_pghead;
1148 /* FIXME: For now, always use fresh pages. We
1149 * really ought to search the free list for a
1154 /* peel pages off tail, so we only have to truncate the list */
1155 pgno = MDB_IDL_LAST(mop->mo_pages);
1156 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
1158 if (mop->mo_pages[2] > mop->mo_pages[1])
1159 mop->mo_pages[0] = 0;
1163 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
1164 txn->mt_env->me_pghead = mop->mo_next;
1171 if (pgno == P_INVALID) {
1172 /* DB size is maxed out */
1173 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg) {
1174 DPUTS("DB size maxed out");
1178 if (txn->mt_env->me_dpages && num == 1) {
1179 np = txn->mt_env->me_dpages;
1180 txn->mt_env->me_dpages = np->mp_next;
1182 if ((np = malloc(txn->mt_env->me_psize * num )) == NULL)
1185 if (pgno == P_INVALID) {
1186 np->mp_pgno = txn->mt_next_pgno;
1187 txn->mt_next_pgno += num;
1191 mid.mid = np->mp_pgno;
1193 mdb_mid2l_insert(txn->mt_u.dirty_list, &mid);
1198 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1199 * @param[in] mc cursor pointing to the page to be touched
1200 * @return 0 on success, non-zero on failure.
1203 mdb_page_touch(MDB_cursor *mc)
1205 MDB_page *mp = mc->mc_pg[mc->mc_top];
1208 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1210 if ((np = mdb_page_alloc(mc, 1)) == NULL)
1212 DPRINTF("touched db %u page %zu -> %zu", mc->mc_dbi, mp->mp_pgno, np->mp_pgno);
1213 assert(mp->mp_pgno != np->mp_pgno);
1214 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
1216 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1219 mp->mp_flags |= P_DIRTY;
1222 /* Adjust other cursors pointing to mp */
1223 if (mc->mc_flags & C_SUB) {
1224 MDB_cursor *m2, *m3;
1225 MDB_dbi dbi = mc->mc_dbi-1;
1227 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
1228 if (m2 == mc) continue;
1229 m3 = &m2->mc_xcursor->mx_cursor;
1230 if (m3->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1231 m3->mc_pg[mc->mc_top] = mp;
1237 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
1238 if (m2 == mc) continue;
1239 if (m2->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1240 m2->mc_pg[mc->mc_top] = mp;
1244 mc->mc_pg[mc->mc_top] = mp;
1245 /** If this page has a parent, update the parent to point to
1249 SETPGNO(NODEPTR(mc->mc_pg[mc->mc_top-1], mc->mc_ki[mc->mc_top-1]), mp->mp_pgno);
1251 mc->mc_db->md_root = mp->mp_pgno;
1252 } else if (mc->mc_txn->mt_parent) {
1255 /* If txn has a parent, make sure the page is in our
1258 if (mc->mc_txn->mt_u.dirty_list[0].mid) {
1259 unsigned x = mdb_mid2l_search(mc->mc_txn->mt_u.dirty_list, mp->mp_pgno);
1260 if (x <= mc->mc_txn->mt_u.dirty_list[0].mid &&
1261 mc->mc_txn->mt_u.dirty_list[x].mid == mp->mp_pgno) {
1262 if (mc->mc_txn->mt_u.dirty_list[x].mptr != mp) {
1263 mp = mc->mc_txn->mt_u.dirty_list[x].mptr;
1264 mc->mc_pg[mc->mc_top] = mp;
1270 np = mdb_page_malloc(mc);
1271 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1272 mid.mid = np->mp_pgno;
1274 mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &mid);
1282 mdb_env_sync(MDB_env *env, int force)
1285 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1286 if (fdatasync(env->me_fd))
1292 /** Make shadow copies of all of parent txn's cursors */
1294 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
1296 MDB_cursor *mc, *m2;
1297 unsigned int i, j, size;
1299 for (i=0;i<src->mt_numdbs; i++) {
1300 if (src->mt_cursors[i]) {
1301 size = sizeof(MDB_cursor);
1302 if (src->mt_cursors[i]->mc_xcursor)
1303 size += sizeof(MDB_xcursor);
1304 for (m2 = src->mt_cursors[i]; m2; m2=m2->mc_next) {
1311 mc->mc_db = &dst->mt_dbs[i];
1312 mc->mc_dbx = m2->mc_dbx;
1313 mc->mc_dbflag = &dst->mt_dbflags[i];
1314 mc->mc_snum = m2->mc_snum;
1315 mc->mc_top = m2->mc_top;
1316 mc->mc_flags = m2->mc_flags | C_SHADOW;
1317 for (j=0; j<mc->mc_snum; j++) {
1318 mc->mc_pg[j] = m2->mc_pg[j];
1319 mc->mc_ki[j] = m2->mc_ki[j];
1321 if (m2->mc_xcursor) {
1322 MDB_xcursor *mx, *mx2;
1323 mx = (MDB_xcursor *)(mc+1);
1324 mc->mc_xcursor = mx;
1325 mx2 = m2->mc_xcursor;
1326 mx->mx_db = mx2->mx_db;
1327 mx->mx_dbx = mx2->mx_dbx;
1328 mx->mx_dbflag = mx2->mx_dbflag;
1329 mx->mx_cursor.mc_txn = dst;
1330 mx->mx_cursor.mc_dbi = mx2->mx_cursor.mc_dbi;
1331 mx->mx_cursor.mc_db = &mx->mx_db;
1332 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
1333 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
1334 mx->mx_cursor.mc_snum = mx2->mx_cursor.mc_snum;
1335 mx->mx_cursor.mc_top = mx2->mx_cursor.mc_top;
1336 mx->mx_cursor.mc_flags = mx2->mx_cursor.mc_flags | C_SHADOW;
1337 for (j=0; j<mx2->mx_cursor.mc_snum; j++) {
1338 mx->mx_cursor.mc_pg[j] = mx2->mx_cursor.mc_pg[j];
1339 mx->mx_cursor.mc_ki[j] = mx2->mx_cursor.mc_ki[j];
1342 mc->mc_xcursor = NULL;
1344 mc->mc_next = dst->mt_cursors[i];
1345 dst->mt_cursors[i] = mc;
1352 /** Merge shadow cursors back into parent's */
1354 mdb_cursor_merge(MDB_txn *txn)
1357 for (i=0; i<txn->mt_numdbs; i++) {
1358 if (txn->mt_cursors[i]) {
1360 while ((mc = txn->mt_cursors[i])) {
1361 txn->mt_cursors[i] = mc->mc_next;
1362 if (mc->mc_flags & C_SHADOW) {
1363 MDB_cursor *m2 = mc->mc_orig;
1365 m2->mc_snum = mc->mc_snum;
1366 m2->mc_top = mc->mc_top;
1367 for (j=0; j<mc->mc_snum; j++) {
1368 m2->mc_pg[j] = mc->mc_pg[j];
1369 m2->mc_ki[j] = mc->mc_ki[j];
1372 if (mc->mc_flags & C_ALLOCD)
1380 mdb_txn_reset0(MDB_txn *txn);
1382 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
1383 * @param[in] txn the transaction handle to initialize
1384 * @return 0 on success, non-zero on failure. This can only
1385 * fail for read-only transactions, and then only if the
1386 * reader table is full.
1389 mdb_txn_renew0(MDB_txn *txn)
1391 MDB_env *env = txn->mt_env;
1394 if (txn->mt_flags & MDB_TXN_RDONLY) {
1395 MDB_reader *r = pthread_getspecific(env->me_txkey);
1398 pid_t pid = getpid();
1399 pthread_t tid = pthread_self();
1402 for (i=0; i<env->me_txns->mti_numreaders; i++)
1403 if (env->me_txns->mti_readers[i].mr_pid == 0)
1405 if (i == env->me_maxreaders) {
1406 UNLOCK_MUTEX_R(env);
1409 env->me_txns->mti_readers[i].mr_pid = pid;
1410 env->me_txns->mti_readers[i].mr_tid = tid;
1411 if (i >= env->me_txns->mti_numreaders)
1412 env->me_txns->mti_numreaders = i+1;
1413 UNLOCK_MUTEX_R(env);
1414 r = &env->me_txns->mti_readers[i];
1415 pthread_setspecific(env->me_txkey, r);
1417 txn->mt_toggle = env->me_txns->mti_me_toggle;
1418 txn->mt_txnid = env->me_txns->mti_txnid;
1419 /* This happens if a different process was the
1420 * last writer to the DB.
1422 if (env->me_wtxnid < txn->mt_txnid)
1423 mt_dbflag = DB_STALE;
1424 r->mr_txnid = txn->mt_txnid;
1425 txn->mt_u.reader = r;
1429 txn->mt_txnid = env->me_txns->mti_txnid;
1430 if (env->me_wtxnid < txn->mt_txnid)
1431 mt_dbflag = DB_STALE;
1433 txn->mt_toggle = env->me_txns->mti_me_toggle;
1434 txn->mt_u.dirty_list = env->me_dirty_list;
1435 txn->mt_u.dirty_list[0].mid = 0;
1436 txn->mt_free_pgs = env->me_free_pgs;
1437 txn->mt_free_pgs[0] = 0;
1438 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1442 /* Copy the DB arrays */
1443 LAZY_RWLOCK_RDLOCK(&env->me_dblock);
1444 txn->mt_numdbs = env->me_numdbs;
1445 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
1446 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
1447 if (txn->mt_numdbs > 2)
1448 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
1449 (txn->mt_numdbs - 2) * sizeof(MDB_db));
1450 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1452 memset(txn->mt_dbflags, mt_dbflag, env->me_numdbs);
1458 mdb_txn_renew(MDB_txn *txn)
1465 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
1466 DPUTS("environment had fatal error, must shutdown!");
1470 rc = mdb_txn_renew0(txn);
1471 if (rc == MDB_SUCCESS) {
1472 DPRINTF("renew txn %zu%c %p on mdbenv %p, root page %zu",
1473 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1474 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1480 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
1485 if (env->me_flags & MDB_FATAL_ERROR) {
1486 DPUTS("environment had fatal error, must shutdown!");
1490 /* parent already has an active child txn */
1491 if (parent->mt_child) {
1495 size = sizeof(MDB_txn) + env->me_maxdbs * (sizeof(MDB_db)+1);
1496 if (!(flags & MDB_RDONLY))
1497 size += env->me_maxdbs * sizeof(MDB_cursor *);
1499 if ((txn = calloc(1, size)) == NULL) {
1500 DPRINTF("calloc: %s", strerror(ErrCode()));
1503 txn->mt_dbs = (MDB_db *)(txn+1);
1504 if (flags & MDB_RDONLY) {
1505 txn->mt_flags |= MDB_TXN_RDONLY;
1506 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
1508 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
1509 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
1514 txn->mt_free_pgs = mdb_midl_alloc();
1515 if (!txn->mt_free_pgs) {
1519 txn->mt_u.dirty_list = malloc(sizeof(ID2)*MDB_IDL_UM_SIZE);
1520 if (!txn->mt_u.dirty_list) {
1521 free(txn->mt_free_pgs);
1525 txn->mt_txnid = parent->mt_txnid;
1526 txn->mt_toggle = parent->mt_toggle;
1527 txn->mt_u.dirty_list[0].mid = 0;
1528 txn->mt_free_pgs[0] = 0;
1529 txn->mt_next_pgno = parent->mt_next_pgno;
1530 parent->mt_child = txn;
1531 txn->mt_parent = parent;
1532 txn->mt_numdbs = parent->mt_numdbs;
1533 txn->mt_dbxs = parent->mt_dbxs;
1534 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
1535 memcpy(txn->mt_dbflags, parent->mt_dbflags, txn->mt_numdbs);
1536 mdb_cursor_shadow(parent, txn);
1539 rc = mdb_txn_renew0(txn);
1545 DPRINTF("begin txn %zu%c %p on mdbenv %p, root page %zu",
1546 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1547 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
1553 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
1554 * @param[in] txn the transaction handle to reset
1557 mdb_txn_reset0(MDB_txn *txn)
1559 MDB_env *env = txn->mt_env;
1561 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1562 txn->mt_u.reader->mr_txnid = 0;
1568 /* close(free) all cursors */
1569 for (i=0; i<txn->mt_numdbs; i++) {
1570 if (txn->mt_cursors[i]) {
1572 while ((mc = txn->mt_cursors[i])) {
1573 txn->mt_cursors[i] = mc->mc_next;
1574 if (mc->mc_flags & C_ALLOCD)
1580 /* return all dirty pages to dpage list */
1581 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1582 dp = txn->mt_u.dirty_list[i].mptr;
1583 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1584 dp->mp_next = txn->mt_env->me_dpages;
1585 txn->mt_env->me_dpages = dp;
1587 /* large pages just get freed directly */
1592 if (txn->mt_parent) {
1593 txn->mt_parent->mt_child = NULL;
1594 free(txn->mt_free_pgs);
1595 free(txn->mt_u.dirty_list);
1598 if (mdb_midl_shrink(&txn->mt_free_pgs))
1599 env->me_free_pgs = txn->mt_free_pgs;
1602 while ((mop = txn->mt_env->me_pghead)) {
1603 txn->mt_env->me_pghead = mop->mo_next;
1608 /* The writer mutex was locked in mdb_txn_begin. */
1609 UNLOCK_MUTEX_W(env);
1614 mdb_txn_reset(MDB_txn *txn)
1619 DPRINTF("reset txn %zu%c %p on mdbenv %p, root page %zu",
1620 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1621 (void *) txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1623 mdb_txn_reset0(txn);
1627 mdb_txn_abort(MDB_txn *txn)
1632 DPRINTF("abort txn %zu%c %p on mdbenv %p, root page %zu",
1633 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1634 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1637 mdb_txn_abort(txn->mt_child);
1639 mdb_txn_reset0(txn);
1644 mdb_txn_commit(MDB_txn *txn)
1655 assert(txn != NULL);
1656 assert(txn->mt_env != NULL);
1658 if (txn->mt_child) {
1659 mdb_txn_commit(txn->mt_child);
1660 txn->mt_child = NULL;
1665 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1666 if (txn->mt_numdbs > env->me_numdbs) {
1667 /* update the DB tables */
1668 int toggle = !env->me_db_toggle;
1672 ip = &env->me_dbs[toggle][env->me_numdbs];
1673 jp = &txn->mt_dbs[env->me_numdbs];
1674 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1675 for (i = env->me_numdbs; i < txn->mt_numdbs; i++) {
1679 env->me_db_toggle = toggle;
1680 env->me_numdbs = txn->mt_numdbs;
1681 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1687 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1688 DPUTS("error flag is set, can't commit");
1690 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
1695 /* Merge (and close) our cursors with parent's */
1696 mdb_cursor_merge(txn);
1698 if (txn->mt_parent) {
1704 /* Update parent's DB table */
1705 ip = &txn->mt_parent->mt_dbs[2];
1706 jp = &txn->mt_dbs[2];
1707 for (i = 2; i < txn->mt_numdbs; i++) {
1708 if (ip->md_root != jp->md_root)
1712 txn->mt_parent->mt_numdbs = txn->mt_numdbs;
1714 /* Append our free list to parent's */
1715 mdb_midl_append_list(&txn->mt_parent->mt_free_pgs,
1717 mdb_midl_free(txn->mt_free_pgs);
1719 /* Merge our dirty list with parent's */
1720 dst = txn->mt_parent->mt_u.dirty_list;
1721 src = txn->mt_u.dirty_list;
1722 x = mdb_mid2l_search(dst, src[1].mid);
1723 for (y=1; y<=src[0].mid; y++) {
1724 while (x <= dst[0].mid && dst[x].mid != src[y].mid) x++;
1728 dst[x].mptr = src[y].mptr;
1731 for (; y<=src[0].mid; y++) {
1732 if (++x >= MDB_IDL_UM_MAX)
1737 free(txn->mt_u.dirty_list);
1738 txn->mt_parent->mt_child = NULL;
1743 if (txn != env->me_txn) {
1744 DPUTS("attempt to commit unknown transaction");
1749 if (!txn->mt_u.dirty_list[0].mid)
1752 DPRINTF("committing txn %zu %p on mdbenv %p, root page %zu",
1753 txn->mt_txnid, (void *)txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
1755 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1757 /* should only be one record now */
1758 if (env->me_pghead) {
1759 /* make sure first page of freeDB is touched and on freelist */
1760 mdb_page_search(&mc, NULL, 1);
1762 /* save to free list */
1763 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
1767 /* make sure last page of freeDB is touched and on freelist */
1768 key.mv_size = MAXKEYSIZE+1;
1770 mdb_page_search(&mc, &key, 1);
1772 mdb_midl_sort(txn->mt_free_pgs);
1776 ID *idl = txn->mt_free_pgs;
1777 DPRINTF("IDL write txn %zu root %zu num %zu",
1778 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1779 for (i=0; i<idl[0]; i++) {
1780 DPRINTF("IDL %zu", idl[i+1]);
1784 /* write to last page of freeDB */
1785 key.mv_size = sizeof(pgno_t);
1786 key.mv_data = &txn->mt_txnid;
1787 data.mv_data = txn->mt_free_pgs;
1788 /* The free list can still grow during this call,
1789 * despite the pre-emptive touches above. So check
1790 * and make sure the entire thing got written.
1793 i = txn->mt_free_pgs[0];
1794 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
1795 rc = mdb_cursor_put(&mc, &key, &data, 0);
1800 } while (i != txn->mt_free_pgs[0]);
1801 if (mdb_midl_shrink(&txn->mt_free_pgs))
1802 env->me_free_pgs = txn->mt_free_pgs;
1804 /* should only be one record now */
1805 if (env->me_pghead) {
1809 mop = env->me_pghead;
1810 env->me_pghead = NULL;
1811 key.mv_size = sizeof(pgno_t);
1812 key.mv_data = &mop->mo_txnid;
1813 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
1814 data.mv_data = mop->mo_pages;
1815 mdb_cursor_put(&mc, &key, &data, 0);
1819 /* Update DB root pointers. Their pages have already been
1820 * touched so this is all in-place and cannot fail.
1825 data.mv_size = sizeof(MDB_db);
1827 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
1828 for (i = 2; i < txn->mt_numdbs; i++) {
1829 if (txn->mt_dbflags[i] & DB_DIRTY) {
1830 data.mv_data = &txn->mt_dbs[i];
1831 mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
1836 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
1842 /* Windows actually supports scatter/gather I/O, but only on
1843 * unbuffered file handles. Since we're relying on the OS page
1844 * cache for all our data, that's self-defeating. So we just
1845 * write pages one at a time. We use the ov structure to set
1846 * the write offset, to at least save the overhead of a Seek
1850 memset(&ov, 0, sizeof(ov));
1851 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1853 dp = txn->mt_u.dirty_list[i].mptr;
1854 DPRINTF("committing page %zu", dp->mp_pgno);
1855 size = dp->mp_pgno * env->me_psize;
1856 ov.Offset = size & 0xffffffff;
1857 ov.OffsetHigh = size >> 16;
1858 ov.OffsetHigh >>= 16;
1859 /* clear dirty flag */
1860 dp->mp_flags &= ~P_DIRTY;
1861 wsize = env->me_psize;
1862 if (IS_OVERFLOW(dp)) wsize *= dp->mp_pages;
1863 rc = WriteFile(env->me_fd, dp, wsize, NULL, &ov);
1866 DPRINTF("WriteFile: %d", n);
1873 struct iovec iov[MDB_COMMIT_PAGES];
1877 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1878 dp = txn->mt_u.dirty_list[i].mptr;
1879 if (dp->mp_pgno != next) {
1881 DPRINTF("committing %u dirty pages", n);
1882 rc = writev(env->me_fd, iov, n);
1886 DPUTS("short write, filesystem full?");
1888 DPRINTF("writev: %s", strerror(n));
1895 lseek(env->me_fd, dp->mp_pgno * env->me_psize, SEEK_SET);
1898 DPRINTF("committing page %zu", dp->mp_pgno);
1899 iov[n].iov_len = env->me_psize;
1900 if (IS_OVERFLOW(dp)) iov[n].iov_len *= dp->mp_pages;
1901 iov[n].iov_base = (char *)dp;
1902 size += iov[n].iov_len;
1903 next = dp->mp_pgno + (IS_OVERFLOW(dp) ? dp->mp_pages : 1);
1904 /* clear dirty flag */
1905 dp->mp_flags &= ~P_DIRTY;
1906 if (++n >= MDB_COMMIT_PAGES) {
1916 DPRINTF("committing %u dirty pages", n);
1917 rc = writev(env->me_fd, iov, n);
1921 DPUTS("short write, filesystem full?");
1923 DPRINTF("writev: %s", strerror(n));
1930 /* Drop the dirty pages.
1932 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1933 dp = txn->mt_u.dirty_list[i].mptr;
1934 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1935 dp->mp_next = txn->mt_env->me_dpages;
1936 txn->mt_env->me_dpages = dp;
1940 txn->mt_u.dirty_list[i].mid = 0;
1942 txn->mt_u.dirty_list[0].mid = 0;
1944 if ((n = mdb_env_sync(env, 0)) != 0 ||
1945 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
1949 env->me_wtxnid = txn->mt_txnid;
1953 /* update the DB tables */
1955 int toggle = !env->me_db_toggle;
1959 ip = &env->me_dbs[toggle][2];
1960 jp = &txn->mt_dbs[2];
1961 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1962 for (i = 2; i < txn->mt_numdbs; i++) {
1963 if (ip->md_root != jp->md_root)
1968 env->me_db_toggle = toggle;
1969 env->me_numdbs = txn->mt_numdbs;
1970 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1973 UNLOCK_MUTEX_W(env);
1979 /** Read the environment parameters of a DB environment before
1980 * mapping it into memory.
1981 * @param[in] env the environment handle
1982 * @param[out] meta address of where to store the meta information
1983 * @return 0 on success, non-zero on failure.
1986 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
1988 char page[MDB_PAGESIZE];
1993 /* We don't know the page size yet, so use a minimum value.
1997 if (!ReadFile(env->me_fd, page, MDB_PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
1999 if ((rc = read(env->me_fd, page, MDB_PAGESIZE)) == 0)
2004 else if (rc != MDB_PAGESIZE) {
2008 DPRINTF("read: %s", strerror(err));
2012 p = (MDB_page *)page;
2014 if (!F_ISSET(p->mp_flags, P_META)) {
2015 DPRINTF("page %zu not a meta page", p->mp_pgno);
2020 if (m->mm_magic != MDB_MAGIC) {
2021 DPUTS("meta has invalid magic");
2025 if (m->mm_version != MDB_VERSION) {
2026 DPRINTF("database is version %u, expected version %u",
2027 m->mm_version, MDB_VERSION);
2028 return MDB_VERSION_MISMATCH;
2031 memcpy(meta, m, sizeof(*m));
2035 /** Write the environment parameters of a freshly created DB environment.
2036 * @param[in] env the environment handle
2037 * @param[out] meta address of where to store the meta information
2038 * @return 0 on success, non-zero on failure.
2041 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
2048 DPUTS("writing new meta page");
2050 GET_PAGESIZE(psize);
2052 meta->mm_magic = MDB_MAGIC;
2053 meta->mm_version = MDB_VERSION;
2054 meta->mm_psize = psize;
2055 meta->mm_last_pg = 1;
2056 meta->mm_flags = env->me_flags & 0xffff;
2057 meta->mm_flags |= MDB_INTEGERKEY;
2058 meta->mm_dbs[0].md_root = P_INVALID;
2059 meta->mm_dbs[1].md_root = P_INVALID;
2061 p = calloc(2, psize);
2063 p->mp_flags = P_META;
2066 memcpy(m, meta, sizeof(*meta));
2068 q = (MDB_page *)((char *)p + psize);
2071 q->mp_flags = P_META;
2074 memcpy(m, meta, sizeof(*meta));
2079 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
2080 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
2083 rc = write(env->me_fd, p, psize * 2);
2084 rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
2090 /** Update the environment info to commit a transaction.
2091 * @param[in] txn the transaction that's being committed
2092 * @return 0 on success, non-zero on failure.
2095 mdb_env_write_meta(MDB_txn *txn)
2098 MDB_meta meta, metab;
2100 int rc, len, toggle;
2106 assert(txn != NULL);
2107 assert(txn->mt_env != NULL);
2109 toggle = !txn->mt_toggle;
2110 DPRINTF("writing meta page %d for root page %zu",
2111 toggle, txn->mt_dbs[MAIN_DBI].md_root);
2115 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
2116 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
2118 ptr = (char *)&meta;
2119 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
2120 len = sizeof(MDB_meta) - off;
2123 meta.mm_dbs[0] = txn->mt_dbs[0];
2124 meta.mm_dbs[1] = txn->mt_dbs[1];
2125 meta.mm_last_pg = txn->mt_next_pgno - 1;
2126 meta.mm_txnid = txn->mt_txnid;
2129 off += env->me_psize;
2132 /* Write to the SYNC fd */
2135 memset(&ov, 0, sizeof(ov));
2137 WriteFile(env->me_mfd, ptr, len, (DWORD *)&rc, &ov);
2140 rc = pwrite(env->me_mfd, ptr, len, off);
2145 DPUTS("write failed, disk error?");
2146 /* On a failure, the pagecache still contains the new data.
2147 * Write some old data back, to prevent it from being used.
2148 * Use the non-SYNC fd; we know it will fail anyway.
2150 meta.mm_last_pg = metab.mm_last_pg;
2151 meta.mm_txnid = metab.mm_txnid;
2153 WriteFile(env->me_fd, ptr, len, NULL, &ov);
2155 r2 = pwrite(env->me_fd, ptr, len, off);
2157 env->me_flags |= MDB_FATAL_ERROR;
2160 /* Memory ordering issues are irrelevant; since the entire writer
2161 * is wrapped by wmutex, all of these changes will become visible
2162 * after the wmutex is unlocked. Since the DB is multi-version,
2163 * readers will get consistent data regardless of how fresh or
2164 * how stale their view of these values is.
2166 LAZY_MUTEX_LOCK(&env->me_txns->mti_mutex);
2167 txn->mt_env->me_txns->mti_me_toggle = toggle;
2168 txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
2169 LAZY_MUTEX_UNLOCK(&env->me_txns->mti_mutex);
2174 /** Check both meta pages to see which one is newer.
2175 * @param[in] env the environment handle
2176 * @param[out] which address of where to store the meta toggle ID
2177 * @return 0 on success, non-zero on failure.
2180 mdb_env_read_meta(MDB_env *env, int *which)
2184 assert(env != NULL);
2186 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
2189 DPRINTF("Using meta page %d", toggle);
2196 mdb_env_create(MDB_env **env)
2200 e = calloc(1, sizeof(MDB_env));
2204 e->me_free_pgs = mdb_midl_alloc();
2205 if (!e->me_free_pgs) {
2209 e->me_maxreaders = DEFAULT_READERS;
2211 e->me_fd = INVALID_HANDLE_VALUE;
2212 e->me_lfd = INVALID_HANDLE_VALUE;
2213 e->me_mfd = INVALID_HANDLE_VALUE;
2219 mdb_env_set_mapsize(MDB_env *env, size_t size)
2223 env->me_mapsize = size;
2225 env->me_maxpg = env->me_mapsize / env->me_psize;
2230 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
2234 env->me_maxdbs = dbs;
2239 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
2241 if (env->me_map || readers < 1)
2243 env->me_maxreaders = readers;
2248 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
2250 if (!env || !readers)
2252 *readers = env->me_maxreaders;
2256 /** Further setup required for opening an MDB environment
2259 mdb_env_open2(MDB_env *env, unsigned int flags)
2261 int i, newenv = 0, toggle;
2265 env->me_flags = flags;
2267 memset(&meta, 0, sizeof(meta));
2269 if ((i = mdb_env_read_header(env, &meta)) != 0) {
2272 DPUTS("new mdbenv");
2276 if (!env->me_mapsize) {
2277 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
2283 LONG sizelo, sizehi;
2284 sizelo = env->me_mapsize & 0xffffffff;
2285 sizehi = env->me_mapsize >> 16; /* pointless on WIN32, only needed on W64 */
2287 /* Windows won't create mappings for zero length files.
2288 * Just allocate the maxsize right now.
2291 SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
2292 if (!SetEndOfFile(env->me_fd))
2294 SetFilePointer(env->me_fd, 0, NULL, 0);
2296 mh = CreateFileMapping(env->me_fd, NULL, PAGE_READONLY,
2297 sizehi, sizelo, NULL);
2300 env->me_map = MapViewOfFileEx(mh, FILE_MAP_READ, 0, 0, env->me_mapsize,
2308 if (meta.mm_address && (flags & MDB_FIXEDMAP))
2310 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
2312 if (env->me_map == MAP_FAILED)
2317 meta.mm_mapsize = env->me_mapsize;
2318 if (flags & MDB_FIXEDMAP)
2319 meta.mm_address = env->me_map;
2320 i = mdb_env_init_meta(env, &meta);
2321 if (i != MDB_SUCCESS) {
2322 munmap(env->me_map, env->me_mapsize);
2326 env->me_psize = meta.mm_psize;
2328 env->me_maxpg = env->me_mapsize / env->me_psize;
2330 p = (MDB_page *)env->me_map;
2331 env->me_metas[0] = METADATA(p);
2332 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
2334 if ((i = mdb_env_read_meta(env, &toggle)) != 0)
2337 DPRINTF("opened database version %u, pagesize %u",
2338 env->me_metas[toggle]->mm_version, env->me_psize);
2339 DPRINTF("depth: %u", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_depth);
2340 DPRINTF("entries: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_entries);
2341 DPRINTF("branch pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_branch_pages);
2342 DPRINTF("leaf pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_leaf_pages);
2343 DPRINTF("overflow pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_overflow_pages);
2344 DPRINTF("root: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_root);
2350 /** Release a reader thread's slot in the reader lock table.
2351 * This function is called automatically when a thread exits.
2352 * Windows doesn't support destructor callbacks for thread-specific storage,
2353 * so this function is not compiled there.
2354 * @param[in] ptr This points to the slot in the reader lock table.
2357 mdb_env_reader_dest(void *ptr)
2359 MDB_reader *reader = ptr;
2361 reader->mr_txnid = 0;
2367 /** Downgrade the exclusive lock on the region back to shared */
2369 mdb_env_share_locks(MDB_env *env)
2373 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
2375 env->me_txns->mti_me_toggle = toggle;
2376 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
2381 /* First acquire a shared lock. The Unlock will
2382 * then release the existing exclusive lock.
2384 memset(&ov, 0, sizeof(ov));
2385 LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov);
2386 UnlockFile(env->me_lfd, 0, 0, 1, 0);
2390 struct flock lock_info;
2391 /* The shared lock replaces the existing lock */
2392 memset((void *)&lock_info, 0, sizeof(lock_info));
2393 lock_info.l_type = F_RDLCK;
2394 lock_info.l_whence = SEEK_SET;
2395 lock_info.l_start = 0;
2396 lock_info.l_len = 1;
2397 fcntl(env->me_lfd, F_SETLK, &lock_info);
2401 #if defined(_WIN32) || defined(__APPLE__)
2403 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
2405 * @(#) $Revision: 5.1 $
2406 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
2407 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
2409 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
2413 * Please do not copyright this code. This code is in the public domain.
2415 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
2416 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
2417 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
2418 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
2419 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
2420 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
2421 * PERFORMANCE OF THIS SOFTWARE.
2424 * chongo <Landon Curt Noll> /\oo/\
2425 * http://www.isthe.com/chongo/
2427 * Share and Enjoy! :-)
2430 typedef unsigned long long mdb_hash_t;
2431 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
2433 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
2434 * @param[in] str string to hash
2435 * @param[in] hval initial value for hash
2436 * @return 64 bit hash
2438 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
2439 * hval arg on the first call.
2442 mdb_hash_str(char *str, mdb_hash_t hval)
2444 unsigned char *s = (unsigned char *)str; /* unsigned string */
2446 * FNV-1a hash each octet of the string
2449 /* xor the bottom with the current octet */
2450 hval ^= (mdb_hash_t)*s++;
2452 /* multiply by the 64 bit FNV magic prime mod 2^64 */
2453 hval += (hval << 1) + (hval << 4) + (hval << 5) +
2454 (hval << 7) + (hval << 8) + (hval << 40);
2456 /* return our new hash value */
2460 /** Hash the string and output the hash in hex.
2461 * @param[in] str string to hash
2462 * @param[out] hexbuf an array of 17 chars to hold the hash
2465 mdb_hash_hex(char *str, char *hexbuf)
2468 mdb_hash_t h = mdb_hash_str(str, MDB_HASH_INIT);
2469 for (i=0; i<8; i++) {
2470 hexbuf += sprintf(hexbuf, "%02x", (unsigned int)h & 0xff);
2476 /** Open and/or initialize the lock region for the environment.
2477 * @param[in] env The MDB environment.
2478 * @param[in] lpath The pathname of the file used for the lock region.
2479 * @param[in] mode The Unix permissions for the file, if we create it.
2480 * @param[out] excl Set to true if we got an exclusive lock on the region.
2481 * @return 0 on success, non-zero on failure.
2484 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
2492 if ((env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
2493 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
2494 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
2498 /* Try to get exclusive lock. If we succeed, then
2499 * nobody is using the lock region and we should initialize it.
2502 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
2506 memset(&ov, 0, sizeof(ov));
2507 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
2513 size = GetFileSize(env->me_lfd, NULL);
2515 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
2519 /* Try to get exclusive lock. If we succeed, then
2520 * nobody is using the lock region and we should initialize it.
2523 struct flock lock_info;
2524 memset((void *)&lock_info, 0, sizeof(lock_info));
2525 lock_info.l_type = F_WRLCK;
2526 lock_info.l_whence = SEEK_SET;
2527 lock_info.l_start = 0;
2528 lock_info.l_len = 1;
2529 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
2533 lock_info.l_type = F_RDLCK;
2534 rc = fcntl(env->me_lfd, F_SETLKW, &lock_info);
2541 size = lseek(env->me_lfd, 0, SEEK_END);
2543 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
2544 if (size < rsize && *excl) {
2546 SetFilePointer(env->me_lfd, rsize, NULL, 0);
2547 if (!SetEndOfFile(env->me_lfd)) {
2552 if (ftruncate(env->me_lfd, rsize) != 0) {
2559 size = rsize - sizeof(MDB_txninfo);
2560 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
2565 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
2571 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
2573 if (!env->me_txns) {
2579 env->me_txns = (MDB_txninfo *)mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
2581 if (env->me_txns == MAP_FAILED) {
2589 if (!mdb_sec_inited) {
2590 InitializeSecurityDescriptor(&mdb_null_sd,
2591 SECURITY_DESCRIPTOR_REVISION);
2592 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
2593 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2594 mdb_all_sa.bInheritHandle = FALSE;
2595 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
2598 mdb_hash_hex(lpath, hexbuf);
2599 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", hexbuf);
2600 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
2601 if (!env->me_rmutex) {
2605 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", hexbuf);
2606 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
2607 if (!env->me_wmutex) {
2614 mdb_hash_hex(lpath, hexbuf);
2615 sprintf(env->me_txns->mti_rmname, "MDBr%s", hexbuf);
2616 if (sem_unlink(env->me_txns->mti_rmname)) {
2618 if (rc != ENOENT && rc != EINVAL)
2621 env->me_rmutex = sem_open(env->me_txns->mti_rmname, O_CREAT, mode, 1);
2622 if (!env->me_rmutex) {
2626 sprintf(env->me_txns->mti_wmname, "MDBw%s", hexbuf);
2627 if (sem_unlink(env->me_txns->mti_wmname)) {
2629 if (rc != ENOENT && rc != EINVAL)
2632 env->me_wmutex = sem_open(env->me_txns->mti_wmname, O_CREAT, mode, 1);
2633 if (!env->me_wmutex) {
2637 #else /* __APPLE__ */
2638 pthread_mutexattr_t mattr;
2640 pthread_mutexattr_init(&mattr);
2641 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
2645 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
2646 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
2647 #endif /* __APPLE__ */
2649 env->me_txns->mti_version = MDB_VERSION;
2650 env->me_txns->mti_magic = MDB_MAGIC;
2651 env->me_txns->mti_txnid = 0;
2652 env->me_txns->mti_numreaders = 0;
2653 env->me_txns->mti_me_toggle = 0;
2656 if (env->me_txns->mti_magic != MDB_MAGIC) {
2657 DPUTS("lock region has invalid magic");
2661 if (env->me_txns->mti_version != MDB_VERSION) {
2662 DPRINTF("lock region is version %u, expected version %u",
2663 env->me_txns->mti_version, MDB_VERSION);
2664 rc = MDB_VERSION_MISMATCH;
2668 if (rc != EACCES && rc != EAGAIN) {
2672 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
2673 if (!env->me_rmutex) {
2677 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
2678 if (!env->me_wmutex) {
2684 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
2685 if (!env->me_rmutex) {
2689 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
2690 if (!env->me_wmutex) {
2700 env->me_lfd = INVALID_HANDLE_VALUE;
2705 /** The name of the lock file in the DB environment */
2706 #define LOCKNAME "/lock.mdb"
2707 /** The name of the data file in the DB environment */
2708 #define DATANAME "/data.mdb"
2709 /** The suffix of the lock file when no subdir is used */
2710 #define LOCKSUFF "-lock"
2713 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
2715 int oflags, rc, len, excl;
2716 char *lpath, *dpath;
2719 if (flags & MDB_NOSUBDIR) {
2720 rc = len + sizeof(LOCKSUFF) + len + 1;
2722 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
2727 if (flags & MDB_NOSUBDIR) {
2728 dpath = lpath + len + sizeof(LOCKSUFF);
2729 sprintf(lpath, "%s" LOCKSUFF, path);
2730 strcpy(dpath, path);
2732 dpath = lpath + len + sizeof(LOCKNAME);
2733 sprintf(lpath, "%s" LOCKNAME, path);
2734 sprintf(dpath, "%s" DATANAME, path);
2737 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
2742 if (F_ISSET(flags, MDB_RDONLY)) {
2743 oflags = GENERIC_READ;
2744 len = OPEN_EXISTING;
2746 oflags = GENERIC_READ|GENERIC_WRITE;
2749 mode = FILE_ATTRIBUTE_NORMAL;
2750 if ((env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2751 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2756 if (F_ISSET(flags, MDB_RDONLY))
2759 oflags = O_RDWR | O_CREAT;
2761 if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
2767 if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
2768 /* synchronous fd for meta writes */
2770 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2771 mode |= FILE_FLAG_WRITE_THROUGH;
2772 if ((env->me_mfd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2773 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2778 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2779 oflags |= MDB_DSYNC;
2780 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
2785 env->me_path = strdup(path);
2786 DPRINTF("opened dbenv %p", (void *) env);
2787 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
2788 LAZY_RWLOCK_INIT(&env->me_dblock, NULL);
2790 mdb_env_share_locks(env);
2791 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
2792 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
2793 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
2799 if (env->me_fd != INVALID_HANDLE_VALUE) {
2801 env->me_fd = INVALID_HANDLE_VALUE;
2803 if (env->me_lfd != INVALID_HANDLE_VALUE) {
2805 env->me_lfd = INVALID_HANDLE_VALUE;
2813 mdb_env_close(MDB_env *env)
2820 while (env->me_dpages) {
2821 dp = env->me_dpages;
2822 env->me_dpages = dp->mp_next;
2826 free(env->me_dbs[1]);
2827 free(env->me_dbs[0]);
2831 LAZY_RWLOCK_DESTROY(&env->me_dblock);
2832 pthread_key_delete(env->me_txkey);
2835 munmap(env->me_map, env->me_mapsize);
2840 pid_t pid = getpid();
2842 for (i=0; i<env->me_txns->mti_numreaders; i++)
2843 if (env->me_txns->mti_readers[i].mr_pid == pid)
2844 env->me_txns->mti_readers[i].mr_pid = 0;
2845 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
2848 mdb_midl_free(env->me_free_pgs);
2852 /** Compare two items pointing at aligned size_t's */
2854 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
2856 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
2857 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
2860 /** Compare two items pointing at aligned int's */
2862 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
2864 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
2865 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
2868 /** Compare two items pointing at ints of unknown alignment.
2869 * Nodes and keys are guaranteed to be 2-byte aligned.
2872 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
2874 #if BYTE_ORDER == LITTLE_ENDIAN
2875 unsigned short *u, *c;
2878 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
2879 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
2882 } while(!x && u > (unsigned short *)a->mv_data);
2885 return memcmp(a->mv_data, b->mv_data, a->mv_size);
2889 /** Compare two items lexically */
2891 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
2898 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
2904 diff = memcmp(a->mv_data, b->mv_data, len);
2905 return diff ? diff : len_diff<0 ? -1 : len_diff;
2908 /** Compare two items in reverse byte order */
2910 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
2912 const unsigned char *p1, *p2, *p1_lim;
2916 p1_lim = (const unsigned char *)a->mv_data;
2917 p1 = (const unsigned char *)a->mv_data + a->mv_size;
2918 p2 = (const unsigned char *)b->mv_data + b->mv_size;
2920 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
2926 while (p1 > p1_lim) {
2927 diff = *--p1 - *--p2;
2931 return len_diff<0 ? -1 : len_diff;
2934 /** Search for key within a page, using binary search.
2935 * Returns the smallest entry larger or equal to the key.
2936 * If exactp is non-null, stores whether the found entry was an exact match
2937 * in *exactp (1 or 0).
2938 * Updates the cursor index with the index of the found entry.
2939 * If no entry larger or equal to the key is found, returns NULL.
2942 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
2944 unsigned int i = 0, nkeys;
2947 MDB_page *mp = mc->mc_pg[mc->mc_top];
2948 MDB_node *node = NULL;
2953 nkeys = NUMKEYS(mp);
2955 DPRINTF("searching %u keys in %s %spage %zu",
2956 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
2961 low = IS_LEAF(mp) ? 0 : 1;
2963 cmp = mc->mc_dbx->md_cmp;
2965 /* Branch pages have no data, so if using integer keys,
2966 * alignment is guaranteed. Use faster mdb_cmp_int.
2968 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
2969 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
2976 nodekey.mv_size = mc->mc_db->md_pad;
2977 node = NODEPTR(mp, 0); /* fake */
2978 while (low <= high) {
2979 i = (low + high) >> 1;
2980 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
2981 rc = cmp(key, &nodekey);
2982 DPRINTF("found leaf index %u [%s], rc = %i",
2983 i, DKEY(&nodekey), rc);
2992 while (low <= high) {
2993 i = (low + high) >> 1;
2995 node = NODEPTR(mp, i);
2996 nodekey.mv_size = NODEKSZ(node);
2997 nodekey.mv_data = NODEKEY(node);
2999 rc = cmp(key, &nodekey);
3002 DPRINTF("found leaf index %u [%s], rc = %i",
3003 i, DKEY(&nodekey), rc);
3005 DPRINTF("found branch index %u [%s -> %zu], rc = %i",
3006 i, DKEY(&nodekey), NODEPGNO(node), rc);
3017 if (rc > 0) { /* Found entry is less than the key. */
3018 i++; /* Skip to get the smallest entry larger than key. */
3020 node = NODEPTR(mp, i);
3023 *exactp = (rc == 0);
3024 /* store the key index */
3025 mc->mc_ki[mc->mc_top] = i;
3027 /* There is no entry larger or equal to the key. */
3030 /* nodeptr is fake for LEAF2 */
3036 mdb_cursor_adjust(MDB_cursor *mc, func)
3040 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
3041 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
3048 /** Pop a page off the top of the cursor's stack. */
3050 mdb_cursor_pop(MDB_cursor *mc)
3055 top = mc->mc_pg[mc->mc_top];
3060 DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
3061 mc->mc_dbi, (void *) mc);
3065 /** Push a page onto the top of the cursor's stack. */
3067 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
3069 DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
3070 mc->mc_dbi, (void *) mc);
3072 if (mc->mc_snum >= CURSOR_STACK) {
3073 assert(mc->mc_snum < CURSOR_STACK);
3077 mc->mc_top = mc->mc_snum++;
3078 mc->mc_pg[mc->mc_top] = mp;
3079 mc->mc_ki[mc->mc_top] = 0;
3084 /** Find the address of the page corresponding to a given page number.
3085 * @param[in] txn the transaction for this access.
3086 * @param[in] pgno the page number for the page to retrieve.
3087 * @param[out] ret address of a pointer where the page's address will be stored.
3088 * @return 0 on success, non-zero on failure.
3091 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
3095 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
3097 x = mdb_mid2l_search(txn->mt_u.dirty_list, pgno);
3098 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
3099 p = txn->mt_u.dirty_list[x].mptr;
3103 if (pgno <= txn->mt_env->me_metas[txn->mt_toggle]->mm_last_pg)
3104 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
3108 DPRINTF("page %zu not found", pgno);
3111 return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
3114 /** Search for the page a given key should be in.
3115 * Pushes parent pages on the cursor stack. This function continues a
3116 * search on a cursor that has already been initialized. (Usually by
3117 * #mdb_page_search() but also by #mdb_node_move().)
3118 * @param[in,out] mc the cursor for this operation.
3119 * @param[in] key the key to search for. If NULL, search for the lowest
3120 * page. (This is used by #mdb_cursor_first().)
3121 * @param[in] modify If true, visited pages are updated with new page numbers.
3122 * @return 0 on success, non-zero on failure.
3125 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
3127 MDB_page *mp = mc->mc_pg[mc->mc_top];
3132 while (IS_BRANCH(mp)) {
3136 DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
3137 assert(NUMKEYS(mp) > 1);
3138 DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
3140 if (key == NULL) /* Initialize cursor to first page. */
3142 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
3143 /* cursor to last page */
3147 node = mdb_node_search(mc, key, &exact);
3149 i = NUMKEYS(mp) - 1;
3151 i = mc->mc_ki[mc->mc_top];
3160 DPRINTF("following index %u for key [%s]",
3162 assert(i < NUMKEYS(mp));
3163 node = NODEPTR(mp, i);
3165 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp)))
3168 mc->mc_ki[mc->mc_top] = i;
3169 if ((rc = mdb_cursor_push(mc, mp)))
3173 if ((rc = mdb_page_touch(mc)) != 0)
3175 mp = mc->mc_pg[mc->mc_top];
3180 DPRINTF("internal error, index points to a %02X page!?",
3182 return MDB_CORRUPTED;
3185 DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
3186 key ? DKEY(key) : NULL);
3191 /** Search for the page a given key should be in.
3192 * Pushes parent pages on the cursor stack. This function just sets up
3193 * the search; it finds the root page for \b mc's database and sets this
3194 * as the root of the cursor's stack. Then #mdb_page_search_root() is
3195 * called to complete the search.
3196 * @param[in,out] mc the cursor for this operation.
3197 * @param[in] key the key to search for. If NULL, search for the lowest
3198 * page. (This is used by #mdb_cursor_first().)
3199 * @param[in] modify If true, visited pages are updated with new page numbers.
3200 * @return 0 on success, non-zero on failure.
3203 mdb_page_search(MDB_cursor *mc, MDB_val *key, int modify)
3208 /* Make sure the txn is still viable, then find the root from
3209 * the txn's db table.
3211 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
3212 DPUTS("transaction has failed, must abort");
3215 /* Make sure we're using an up-to-date root */
3216 if (mc->mc_dbi > MAIN_DBI) {
3217 if ((*mc->mc_dbflag & DB_STALE) ||
3218 (modify && !(*mc->mc_dbflag & DB_DIRTY))) {
3220 unsigned char dbflag = 0;
3221 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
3222 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, modify);
3225 if (*mc->mc_dbflag & DB_STALE) {
3228 MDB_node *leaf = mdb_node_search(&mc2,
3229 &mc->mc_dbx->md_name, &exact);
3231 return MDB_NOTFOUND;
3232 mdb_node_read(mc->mc_txn, leaf, &data);
3233 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
3237 *mc->mc_dbflag = dbflag;
3240 root = mc->mc_db->md_root;
3242 if (root == P_INVALID) { /* Tree is empty. */
3243 DPUTS("tree is empty");
3244 return MDB_NOTFOUND;
3249 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0])))
3255 DPRINTF("db %u root page %zu has flags 0x%X",
3256 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
3259 if ((rc = mdb_page_touch(mc)))
3263 return mdb_page_search_root(mc, key, modify);
3266 /** Return the data associated with a given node.
3267 * @param[in] txn The transaction for this operation.
3268 * @param[in] leaf The node being read.
3269 * @param[out] data Updated to point to the node's data.
3270 * @return 0 on success, non-zero on failure.
3273 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
3275 MDB_page *omp; /* overflow page */
3279 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
3280 data->mv_size = NODEDSZ(leaf);
3281 data->mv_data = NODEDATA(leaf);
3285 /* Read overflow data.
3287 data->mv_size = NODEDSZ(leaf);
3288 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
3289 if ((rc = mdb_page_get(txn, pgno, &omp))) {
3290 DPRINTF("read overflow page %zu failed", pgno);
3293 data->mv_data = METADATA(omp);
3299 mdb_get(MDB_txn *txn, MDB_dbi dbi,
3300 MDB_val *key, MDB_val *data)
3309 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
3311 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3314 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3318 mdb_cursor_init(&mc, txn, dbi, &mx);
3319 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
3322 /** Find a sibling for a page.
3323 * Replaces the page at the top of the cursor's stack with the
3324 * specified sibling, if one exists.
3325 * @param[in] mc The cursor for this operation.
3326 * @param[in] move_right Non-zero if the right sibling is requested,
3327 * otherwise the left sibling.
3328 * @return 0 on success, non-zero on failure.
3331 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
3337 if (mc->mc_snum < 2) {
3338 return MDB_NOTFOUND; /* root has no siblings */
3342 DPRINTF("parent page is page %zu, index %u",
3343 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]);
3345 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
3346 : (mc->mc_ki[mc->mc_top] == 0)) {
3347 DPRINTF("no more keys left, moving to %s sibling",
3348 move_right ? "right" : "left");
3349 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS)
3353 mc->mc_ki[mc->mc_top]++;
3355 mc->mc_ki[mc->mc_top]--;
3356 DPRINTF("just moving to %s index key %u",
3357 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]);
3359 assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
3361 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3362 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp)))
3365 mdb_cursor_push(mc, mp);
3370 /** Move the cursor to the next data item. */
3372 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3378 if (mc->mc_flags & C_EOF) {
3379 return MDB_NOTFOUND;
3382 assert(mc->mc_flags & C_INITIALIZED);
3384 mp = mc->mc_pg[mc->mc_top];
3386 if (mc->mc_db->md_flags & MDB_DUPSORT) {
3387 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3388 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3389 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
3390 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
3391 if (op != MDB_NEXT || rc == MDB_SUCCESS)
3395 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3396 if (op == MDB_NEXT_DUP)
3397 return MDB_NOTFOUND;
3401 DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3403 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
3404 DPUTS("=====> move to next sibling page");
3405 if (mdb_cursor_sibling(mc, 1) != MDB_SUCCESS) {
3406 mc->mc_flags |= C_EOF;
3407 mc->mc_flags &= ~C_INITIALIZED;
3408 return MDB_NOTFOUND;
3410 mp = mc->mc_pg[mc->mc_top];
3411 DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3413 mc->mc_ki[mc->mc_top]++;
3415 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3416 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3419 key->mv_size = mc->mc_db->md_pad;
3420 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3424 assert(IS_LEAF(mp));
3425 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3427 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3428 mdb_xcursor_init1(mc, leaf);
3431 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3434 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3435 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3436 if (rc != MDB_SUCCESS)
3441 MDB_SET_KEY(leaf, key);
3445 /** Move the cursor to the previous data item. */
3447 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3453 assert(mc->mc_flags & C_INITIALIZED);
3455 mp = mc->mc_pg[mc->mc_top];
3457 if (mc->mc_db->md_flags & MDB_DUPSORT) {
3458 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3459 if (op == MDB_PREV || op == MDB_PREV_DUP) {
3460 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3461 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
3462 if (op != MDB_PREV || rc == MDB_SUCCESS)
3465 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3466 if (op == MDB_PREV_DUP)
3467 return MDB_NOTFOUND;
3472 DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3474 if (mc->mc_ki[mc->mc_top] == 0) {
3475 DPUTS("=====> move to prev sibling page");
3476 if (mdb_cursor_sibling(mc, 0) != MDB_SUCCESS) {
3477 mc->mc_flags &= ~C_INITIALIZED;
3478 return MDB_NOTFOUND;
3480 mp = mc->mc_pg[mc->mc_top];
3481 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
3482 DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3484 mc->mc_ki[mc->mc_top]--;
3486 mc->mc_flags &= ~C_EOF;
3488 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3489 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3492 key->mv_size = mc->mc_db->md_pad;
3493 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3497 assert(IS_LEAF(mp));
3498 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3500 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3501 mdb_xcursor_init1(mc, leaf);
3504 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3507 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3508 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3509 if (rc != MDB_SUCCESS)
3514 MDB_SET_KEY(leaf, key);
3518 /** Set the cursor on a specific data item. */
3520 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3521 MDB_cursor_op op, int *exactp)
3530 assert(key->mv_size > 0);
3532 /* See if we're already on the right page */
3533 if (mc->mc_flags & C_INITIALIZED) {
3536 mp = mc->mc_pg[mc->mc_top];
3538 mc->mc_ki[mc->mc_top] = 0;
3539 return MDB_NOTFOUND;
3541 if (mp->mp_flags & P_LEAF2) {
3542 nodekey.mv_size = mc->mc_db->md_pad;
3543 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
3545 leaf = NODEPTR(mp, 0);
3546 MDB_SET_KEY(leaf, &nodekey);
3548 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3550 /* Probably happens rarely, but first node on the page
3551 * was the one we wanted.
3553 mc->mc_ki[mc->mc_top] = 0;
3554 leaf = NODEPTR(mp, 0);
3561 unsigned int nkeys = NUMKEYS(mp);
3563 if (mp->mp_flags & P_LEAF2) {
3564 nodekey.mv_data = LEAF2KEY(mp,
3565 nkeys-1, nodekey.mv_size);
3567 leaf = NODEPTR(mp, nkeys-1);
3568 MDB_SET_KEY(leaf, &nodekey);
3570 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3572 /* last node was the one we wanted */
3573 mc->mc_ki[mc->mc_top] = nkeys-1;
3574 leaf = NODEPTR(mp, nkeys-1);
3580 /* This is definitely the right page, skip search_page */
3585 /* If any parents have right-sibs, search.
3586 * Otherwise, there's nothing further.
3588 for (i=0; i<mc->mc_top; i++)
3590 NUMKEYS(mc->mc_pg[i])-1)
3592 if (i == mc->mc_top) {
3593 /* There are no other pages */
3594 mc->mc_ki[mc->mc_top] = nkeys;
3595 return MDB_NOTFOUND;
3599 /* There are no other pages */
3600 mc->mc_ki[mc->mc_top] = 0;
3601 return MDB_NOTFOUND;
3605 rc = mdb_page_search(mc, key, 0);
3606 if (rc != MDB_SUCCESS)
3609 mp = mc->mc_pg[mc->mc_top];
3610 assert(IS_LEAF(mp));
3613 leaf = mdb_node_search(mc, key, exactp);
3614 if (exactp != NULL && !*exactp) {
3615 /* MDB_SET specified and not an exact match. */
3616 return MDB_NOTFOUND;
3620 DPUTS("===> inexact leaf not found, goto sibling");
3621 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
3622 return rc; /* no entries matched */
3623 mp = mc->mc_pg[mc->mc_top];
3624 assert(IS_LEAF(mp));
3625 leaf = NODEPTR(mp, 0);
3629 mc->mc_flags |= C_INITIALIZED;
3630 mc->mc_flags &= ~C_EOF;
3633 key->mv_size = mc->mc_db->md_pad;
3634 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3638 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3639 mdb_xcursor_init1(mc, leaf);
3642 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3643 if (op == MDB_SET || op == MDB_SET_RANGE) {
3644 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3647 if (op == MDB_GET_BOTH) {
3653 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
3654 if (rc != MDB_SUCCESS)
3657 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
3659 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
3661 rc = mc->mc_dbx->md_dcmp(data, &d2);
3663 if (op == MDB_GET_BOTH || rc > 0)
3664 return MDB_NOTFOUND;
3669 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3670 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3675 /* The key already matches in all other cases */
3676 if (op == MDB_SET_RANGE)
3677 MDB_SET_KEY(leaf, key);
3678 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
3683 /** Move the cursor to the first item in the database. */
3685 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3690 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3691 rc = mdb_page_search(mc, NULL, 0);
3692 if (rc != MDB_SUCCESS)
3695 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3697 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
3698 mc->mc_flags |= C_INITIALIZED;
3699 mc->mc_flags &= ~C_EOF;
3701 mc->mc_ki[mc->mc_top] = 0;
3703 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3704 key->mv_size = mc->mc_db->md_pad;
3705 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
3710 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3711 mdb_xcursor_init1(mc, leaf);
3712 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3717 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3718 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3722 MDB_SET_KEY(leaf, key);
3726 /** Move the cursor to the last item in the database. */
3728 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3734 lkey.mv_size = MAXKEYSIZE+1;
3735 lkey.mv_data = NULL;
3737 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
3738 rc = mdb_page_search(mc, &lkey, 0);
3739 if (rc != MDB_SUCCESS)
3742 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3744 leaf = NODEPTR(mc->mc_pg[mc->mc_top], NUMKEYS(mc->mc_pg[mc->mc_top])-1);
3745 mc->mc_flags |= C_INITIALIZED;
3746 mc->mc_flags &= ~C_EOF;
3748 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
3750 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3751 key->mv_size = mc->mc_db->md_pad;
3752 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
3757 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3758 mdb_xcursor_init1(mc, leaf);
3759 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3764 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3765 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3770 MDB_SET_KEY(leaf, key);
3775 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3785 case MDB_GET_BOTH_RANGE:
3786 if (data == NULL || mc->mc_xcursor == NULL) {
3793 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3795 } else if (op == MDB_SET_RANGE)
3796 rc = mdb_cursor_set(mc, key, data, op, NULL);
3798 rc = mdb_cursor_set(mc, key, data, op, &exact);
3800 case MDB_GET_MULTIPLE:
3802 !(mc->mc_db->md_flags & MDB_DUPFIXED) ||
3803 !(mc->mc_flags & C_INITIALIZED)) {
3808 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
3809 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
3812 case MDB_NEXT_MULTIPLE:
3814 !(mc->mc_db->md_flags & MDB_DUPFIXED)) {
3818 if (!(mc->mc_flags & C_INITIALIZED))
3819 rc = mdb_cursor_first(mc, key, data);
3821 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
3822 if (rc == MDB_SUCCESS) {
3823 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
3826 mx = &mc->mc_xcursor->mx_cursor;
3827 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
3829 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
3830 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
3838 case MDB_NEXT_NODUP:
3839 if (!(mc->mc_flags & C_INITIALIZED))
3840 rc = mdb_cursor_first(mc, key, data);
3842 rc = mdb_cursor_next(mc, key, data, op);
3846 case MDB_PREV_NODUP:
3847 if (!(mc->mc_flags & C_INITIALIZED) || (mc->mc_flags & C_EOF))
3848 rc = mdb_cursor_last(mc, key, data);
3850 rc = mdb_cursor_prev(mc, key, data, op);
3853 rc = mdb_cursor_first(mc, key, data);
3857 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
3858 !(mc->mc_flags & C_INITIALIZED) ||
3859 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3863 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3866 rc = mdb_cursor_last(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_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3879 DPRINTF("unhandled/unimplemented cursor operation %u", op);
3887 /** Touch all the pages in the cursor stack.
3888 * Makes sure all the pages are writable, before attempting a write operation.
3889 * @param[in] mc The cursor to operate on.
3892 mdb_cursor_touch(MDB_cursor *mc)
3896 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
3898 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
3899 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 1);
3902 *mc->mc_dbflag = DB_DIRTY;
3904 for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
3905 rc = mdb_page_touch(mc);
3909 mc->mc_top = mc->mc_snum-1;
3914 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3917 MDB_node *leaf = NULL;
3918 MDB_val xdata, *rdata, dkey;
3922 unsigned int mcount = 0;
3925 char pbuf[MDB_PAGESIZE];
3926 char dbuf[MAXKEYSIZE+1];
3927 unsigned int nflags;
3930 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
3933 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
3934 mc->mc_dbi, DKEY(key), key ? key->mv_size:0, data->mv_size);
3938 if (flags == MDB_CURRENT) {
3939 if (!(mc->mc_flags & C_INITIALIZED))
3942 } else if (mc->mc_db->md_root == P_INVALID) {
3944 /* new database, write a root leaf page */
3945 DPUTS("allocating new root leaf page");
3946 if ((np = mdb_page_new(mc, P_LEAF, 1)) == NULL) {
3950 mdb_cursor_push(mc, np);
3951 mc->mc_db->md_root = np->mp_pgno;
3952 mc->mc_db->md_depth++;
3953 *mc->mc_dbflag = DB_DIRTY;
3954 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
3956 np->mp_flags |= P_LEAF2;
3957 mc->mc_flags |= C_INITIALIZED;
3963 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
3964 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
3965 DPRINTF("duplicate key [%s]", DKEY(key));
3967 return MDB_KEYEXIST;
3969 if (rc && rc != MDB_NOTFOUND)
3973 /* Cursor is positioned, now make sure all pages are writable */
3974 rc2 = mdb_cursor_touch(mc);
3979 /* The key already exists */
3980 if (rc == MDB_SUCCESS) {
3981 /* there's only a key anyway, so this is a no-op */
3982 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3983 unsigned int ksize = mc->mc_db->md_pad;
3984 if (key->mv_size != ksize)
3986 if (flags == MDB_CURRENT) {
3987 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
3988 memcpy(ptr, key->mv_data, ksize);
3993 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3996 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
3997 /* Was a single item before, must convert now */
3999 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4000 /* Just overwrite the current item */
4001 if (flags == MDB_CURRENT)
4004 dkey.mv_size = NODEDSZ(leaf);
4005 dkey.mv_data = NODEDATA(leaf);
4006 #if UINT_MAX > SIZE_MAX
4007 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && dkey.mv_size == sizeof(size_t))
4008 #ifdef MISALIGNED_OK
4009 mc->mc_dbx->md_dcmp = mdb_cmp_long;
4011 mc->mc_dbx->md_dcmp = mdb_cmp_cint;
4014 /* if data matches, ignore it */
4015 if (!mc->mc_dbx->md_dcmp(data, &dkey))
4016 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
4018 /* create a fake page for the dup items */
4019 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
4020 dkey.mv_data = dbuf;
4021 fp = (MDB_page *)pbuf;
4022 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4023 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
4024 fp->mp_lower = PAGEHDRSZ;
4025 fp->mp_upper = PAGEHDRSZ + dkey.mv_size + data->mv_size;
4026 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4027 fp->mp_flags |= P_LEAF2;
4028 fp->mp_pad = data->mv_size;
4030 fp->mp_upper += 2 * sizeof(indx_t) + 2 * NODESIZE +
4031 (dkey.mv_size & 1) + (data->mv_size & 1);
4033 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4036 xdata.mv_size = fp->mp_upper;
4037 xdata.mv_data = pbuf;
4041 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
4042 /* See if we need to convert from fake page to subDB */
4044 unsigned int offset;
4047 fp = NODEDATA(leaf);
4048 if (flags == MDB_CURRENT) {
4049 fp->mp_flags |= P_DIRTY;
4050 COPY_PGNO(fp->mp_pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
4051 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
4055 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4056 offset = fp->mp_pad;
4058 offset = NODESIZE + sizeof(indx_t) + data->mv_size;
4060 offset += offset & 1;
4061 if (NODESIZE + sizeof(indx_t) + NODEKSZ(leaf) + NODEDSZ(leaf) +
4062 offset >= (mc->mc_txn->mt_env->me_psize - PAGEHDRSZ) /
4064 /* yes, convert it */
4066 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4067 dummy.md_pad = fp->mp_pad;
4068 dummy.md_flags = MDB_DUPFIXED;
4069 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
4070 dummy.md_flags |= MDB_INTEGERKEY;
4073 dummy.md_branch_pages = 0;
4074 dummy.md_leaf_pages = 1;
4075 dummy.md_overflow_pages = 0;
4076 dummy.md_entries = NUMKEYS(fp);
4078 xdata.mv_size = sizeof(MDB_db);
4079 xdata.mv_data = &dummy;
4080 mp = mdb_page_alloc(mc, 1);
4083 offset = mc->mc_txn->mt_env->me_psize - NODEDSZ(leaf);
4084 flags |= F_DUPDATA|F_SUBDATA;
4085 dummy.md_root = mp->mp_pgno;
4087 /* no, just grow it */
4089 xdata.mv_size = NODEDSZ(leaf) + offset;
4090 xdata.mv_data = pbuf;
4091 mp = (MDB_page *)pbuf;
4092 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4095 mp->mp_flags = fp->mp_flags | P_DIRTY;
4096 mp->mp_pad = fp->mp_pad;
4097 mp->mp_lower = fp->mp_lower;
4098 mp->mp_upper = fp->mp_upper + offset;
4100 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
4102 nsize = NODEDSZ(leaf) - fp->mp_upper;
4103 memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper, nsize);
4104 for (i=0; i<NUMKEYS(fp); i++)
4105 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
4107 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4111 /* data is on sub-DB, just store it */
4112 flags |= F_DUPDATA|F_SUBDATA;
4116 /* same size, just replace it */
4117 if (!F_ISSET(leaf->mn_flags, F_BIGDATA) &&
4118 NODEDSZ(leaf) == data->mv_size) {
4119 if (F_ISSET(flags, MDB_RESERVE))
4120 data->mv_data = NODEDATA(leaf);
4122 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
4125 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4127 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
4133 nflags = flags & NODE_ADD_FLAGS;
4134 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
4135 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
4136 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
4137 nflags &= ~MDB_APPEND;
4138 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
4140 /* There is room already in this leaf page. */
4141 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
4142 if (rc == 0 && !do_sub) {
4143 /* Adjust other cursors pointing to mp */
4144 MDB_cursor *m2, *m3;
4145 MDB_dbi dbi = mc->mc_dbi;
4146 unsigned i = mc->mc_top;
4147 MDB_page *mp = mc->mc_pg[i];
4149 if (mc->mc_flags & C_SUB)
4152 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
4153 if (mc->mc_flags & C_SUB)
4154 m3 = &m2->mc_xcursor->mx_cursor;
4157 if (m3 == mc) continue;
4158 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
4165 if (rc != MDB_SUCCESS)
4166 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4168 /* Now store the actual data in the child DB. Note that we're
4169 * storing the user data in the keys field, so there are strict
4170 * size limits on dupdata. The actual data fields of the child
4171 * DB are all zero size.
4179 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4180 if (flags & MDB_CURRENT) {
4181 xflags = MDB_CURRENT;
4183 mdb_xcursor_init1(mc, leaf);
4184 xflags = (flags & MDB_NODUPDATA) ? MDB_NOOVERWRITE : 0;
4186 /* converted, write the original data first */
4188 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
4192 /* Adjust other cursors pointing to mp */
4194 unsigned i = mc->mc_top;
4195 MDB_page *mp = mc->mc_pg[i];
4197 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4198 if (m2 == mc) continue;
4199 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
4200 mdb_xcursor_init1(m2, leaf);
4205 xflags |= (flags & MDB_APPEND);
4206 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
4207 if (flags & F_SUBDATA) {
4208 db = NODEDATA(leaf);
4209 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4212 /* sub-writes might have failed so check rc again.
4213 * Don't increment count if we just replaced an existing item.
4215 if (!rc && !(flags & MDB_CURRENT))
4216 mc->mc_db->md_entries++;
4217 if (flags & MDB_MULTIPLE) {
4219 if (mcount < data[1].mv_size) {
4220 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
4221 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4231 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
4236 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
4239 if (!mc->mc_flags & C_INITIALIZED)
4242 rc = mdb_cursor_touch(mc);
4246 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4248 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4249 if (flags != MDB_NODUPDATA) {
4250 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
4251 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
4253 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
4254 /* If sub-DB still has entries, we're done */
4255 if (mc->mc_xcursor->mx_db.md_entries) {
4256 if (leaf->mn_flags & F_SUBDATA) {
4257 /* update subDB info */
4258 MDB_db *db = NODEDATA(leaf);
4259 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4261 /* shrink fake page */
4262 mdb_node_shrink(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4264 mc->mc_db->md_entries--;
4267 /* otherwise fall thru and delete the sub-DB */
4270 if (leaf->mn_flags & F_SUBDATA) {
4271 /* add all the child DB's pages to the free list */
4272 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
4273 if (rc == MDB_SUCCESS) {
4274 mc->mc_db->md_entries -=
4275 mc->mc_xcursor->mx_db.md_entries;
4280 return mdb_cursor_del0(mc, leaf);
4283 /** Allocate and initialize new pages for a database.
4284 * @param[in] mc a cursor on the database being added to.
4285 * @param[in] flags flags defining what type of page is being allocated.
4286 * @param[in] num the number of pages to allocate. This is usually 1,
4287 * unless allocating overflow pages for a large record.
4288 * @return Address of a page, or NULL on failure.
4291 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num)
4295 if ((np = mdb_page_alloc(mc, num)) == NULL)
4297 DPRINTF("allocated new mpage %zu, page size %u",
4298 np->mp_pgno, mc->mc_txn->mt_env->me_psize);
4299 np->mp_flags = flags | P_DIRTY;
4300 np->mp_lower = PAGEHDRSZ;
4301 np->mp_upper = mc->mc_txn->mt_env->me_psize;
4304 mc->mc_db->md_branch_pages++;
4305 else if (IS_LEAF(np))
4306 mc->mc_db->md_leaf_pages++;
4307 else if (IS_OVERFLOW(np)) {
4308 mc->mc_db->md_overflow_pages += num;
4315 /** Calculate the size of a leaf node.
4316 * The size depends on the environment's page size; if a data item
4317 * is too large it will be put onto an overflow page and the node
4318 * size will only include the key and not the data. Sizes are always
4319 * rounded up to an even number of bytes, to guarantee 2-byte alignment
4320 * of the #MDB_node headers.
4321 * @param[in] env The environment handle.
4322 * @param[in] key The key for the node.
4323 * @param[in] data The data for the node.
4324 * @return The number of bytes needed to store the node.
4327 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
4331 sz = LEAFSIZE(key, data);
4332 if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
4333 /* put on overflow page */
4334 sz -= data->mv_size - sizeof(pgno_t);
4338 return sz + sizeof(indx_t);
4341 /** Calculate the size of a branch node.
4342 * The size should depend on the environment's page size but since
4343 * we currently don't support spilling large keys onto overflow
4344 * pages, it's simply the size of the #MDB_node header plus the
4345 * size of the key. Sizes are always rounded up to an even number
4346 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
4347 * @param[in] env The environment handle.
4348 * @param[in] key The key for the node.
4349 * @return The number of bytes needed to store the node.
4352 mdb_branch_size(MDB_env *env, MDB_val *key)
4357 if (sz >= env->me_psize / MDB_MINKEYS) {
4358 /* put on overflow page */
4359 /* not implemented */
4360 /* sz -= key->size - sizeof(pgno_t); */
4363 return sz + sizeof(indx_t);
4366 /** Add a node to the page pointed to by the cursor.
4367 * @param[in] mc The cursor for this operation.
4368 * @param[in] indx The index on the page where the new node should be added.
4369 * @param[in] key The key for the new node.
4370 * @param[in] data The data for the new node, if any.
4371 * @param[in] pgno The page number, if adding a branch node.
4372 * @param[in] flags Flags for the node.
4373 * @return 0 on success, non-zero on failure. Possible errors are:
4375 * <li>ENOMEM - failed to allocate overflow pages for the node.
4376 * <li>ENOSPC - there is insufficient room in the page. This error
4377 * should never happen since all callers already calculate the
4378 * page's free space before calling this function.
4382 mdb_node_add(MDB_cursor *mc, indx_t indx,
4383 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
4386 size_t node_size = NODESIZE;
4389 MDB_page *mp = mc->mc_pg[mc->mc_top];
4390 MDB_page *ofp = NULL; /* overflow page */
4393 assert(mp->mp_upper >= mp->mp_lower);
4395 DPRINTF("add to %s %spage %zu index %i, data size %zu key size %zu [%s]",
4396 IS_LEAF(mp) ? "leaf" : "branch",
4397 IS_SUBP(mp) ? "sub-" : "",
4398 mp->mp_pgno, indx, data ? data->mv_size : 0,
4399 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
4402 /* Move higher keys up one slot. */
4403 int ksize = mc->mc_db->md_pad, dif;
4404 char *ptr = LEAF2KEY(mp, indx, ksize);
4405 dif = NUMKEYS(mp) - indx;
4407 memmove(ptr+ksize, ptr, dif*ksize);
4408 /* insert new key */
4409 memcpy(ptr, key->mv_data, ksize);
4411 /* Just using these for counting */
4412 mp->mp_lower += sizeof(indx_t);
4413 mp->mp_upper -= ksize - sizeof(indx_t);
4418 node_size += key->mv_size;
4422 if (F_ISSET(flags, F_BIGDATA)) {
4423 /* Data already on overflow page. */
4424 node_size += sizeof(pgno_t);
4425 } else if (data->mv_size >= mc->mc_txn->mt_env->me_psize / MDB_MINKEYS) {
4426 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
4427 /* Put data on overflow page. */
4428 DPRINTF("data size is %zu, put on overflow page",
4430 node_size += sizeof(pgno_t);
4431 if ((ofp = mdb_page_new(mc, P_OVERFLOW, ovpages)) == NULL)
4433 DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
4436 node_size += data->mv_size;
4439 node_size += node_size & 1;
4441 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
4442 DPRINTF("not enough room in page %zu, got %u ptrs",
4443 mp->mp_pgno, NUMKEYS(mp));
4444 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
4445 mp->mp_upper - mp->mp_lower);
4446 DPRINTF("node size = %zu", node_size);
4450 /* Move higher pointers up one slot. */
4451 for (i = NUMKEYS(mp); i > indx; i--)
4452 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
4454 /* Adjust free space offsets. */
4455 ofs = mp->mp_upper - node_size;
4456 assert(ofs >= mp->mp_lower + sizeof(indx_t));
4457 mp->mp_ptrs[indx] = ofs;
4459 mp->mp_lower += sizeof(indx_t);
4461 /* Write the node data. */
4462 node = NODEPTR(mp, indx);
4463 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
4464 node->mn_flags = flags;
4466 SETDSZ(node,data->mv_size);
4471 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
4476 if (F_ISSET(flags, F_BIGDATA))
4477 memcpy(node->mn_data + key->mv_size, data->mv_data,
4479 else if (F_ISSET(flags, MDB_RESERVE))
4480 data->mv_data = node->mn_data + key->mv_size;
4482 memcpy(node->mn_data + key->mv_size, data->mv_data,
4485 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
4487 if (F_ISSET(flags, MDB_RESERVE))
4488 data->mv_data = METADATA(ofp);
4490 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
4497 /** Delete the specified node from a page.
4498 * @param[in] mp The page to operate on.
4499 * @param[in] indx The index of the node to delete.
4500 * @param[in] ksize The size of a node. Only used if the page is
4501 * part of a #MDB_DUPFIXED database.
4504 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
4507 indx_t i, j, numkeys, ptr;
4511 DPRINTF("delete node %u on %s page %zu", indx,
4512 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
4513 assert(indx < NUMKEYS(mp));
4516 int x = NUMKEYS(mp) - 1 - indx;
4517 base = LEAF2KEY(mp, indx, ksize);
4519 memmove(base, base + ksize, x * ksize);
4520 mp->mp_lower -= sizeof(indx_t);
4521 mp->mp_upper += ksize - sizeof(indx_t);
4525 node = NODEPTR(mp, indx);
4526 sz = NODESIZE + node->mn_ksize;
4528 if (F_ISSET(node->mn_flags, F_BIGDATA))
4529 sz += sizeof(pgno_t);
4531 sz += NODEDSZ(node);
4535 ptr = mp->mp_ptrs[indx];
4536 numkeys = NUMKEYS(mp);
4537 for (i = j = 0; i < numkeys; i++) {
4539 mp->mp_ptrs[j] = mp->mp_ptrs[i];
4540 if (mp->mp_ptrs[i] < ptr)
4541 mp->mp_ptrs[j] += sz;
4546 base = (char *)mp + mp->mp_upper;
4547 memmove(base + sz, base, ptr - mp->mp_upper);
4549 mp->mp_lower -= sizeof(indx_t);
4553 /** Compact the main page after deleting a node on a subpage.
4554 * @param[in] mp The main page to operate on.
4555 * @param[in] indx The index of the subpage on the main page.
4558 mdb_node_shrink(MDB_page *mp, indx_t indx)
4565 indx_t i, numkeys, ptr;
4567 node = NODEPTR(mp, indx);
4568 sp = (MDB_page *)NODEDATA(node);
4569 osize = NODEDSZ(node);
4571 delta = sp->mp_upper - sp->mp_lower;
4572 SETDSZ(node, osize - delta);
4573 xp = (MDB_page *)((char *)sp + delta);
4575 /* shift subpage upward */
4577 nsize = NUMKEYS(sp) * sp->mp_pad;
4578 memmove(METADATA(xp), METADATA(sp), nsize);
4581 nsize = osize - sp->mp_upper;
4582 numkeys = NUMKEYS(sp);
4583 for (i=numkeys-1; i>=0; i--)
4584 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
4586 xp->mp_upper = sp->mp_lower;
4587 xp->mp_lower = sp->mp_lower;
4588 xp->mp_flags = sp->mp_flags;
4589 xp->mp_pad = sp->mp_pad;
4590 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
4592 /* shift lower nodes upward */
4593 ptr = mp->mp_ptrs[indx];
4594 numkeys = NUMKEYS(mp);
4595 for (i = 0; i < numkeys; i++) {
4596 if (mp->mp_ptrs[i] <= ptr)
4597 mp->mp_ptrs[i] += delta;
4600 base = (char *)mp + mp->mp_upper;
4601 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
4602 mp->mp_upper += delta;
4605 /** Initial setup of a sorted-dups cursor.
4606 * Sorted duplicates are implemented as a sub-database for the given key.
4607 * The duplicate data items are actually keys of the sub-database.
4608 * Operations on the duplicate data items are performed using a sub-cursor
4609 * initialized when the sub-database is first accessed. This function does
4610 * the preliminary setup of the sub-cursor, filling in the fields that
4611 * depend only on the parent DB.
4612 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4615 mdb_xcursor_init0(MDB_cursor *mc)
4617 MDB_xcursor *mx = mc->mc_xcursor;
4619 mx->mx_cursor.mc_xcursor = NULL;
4620 mx->mx_cursor.mc_txn = mc->mc_txn;
4621 mx->mx_cursor.mc_db = &mx->mx_db;
4622 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
4623 mx->mx_cursor.mc_dbi = mc->mc_dbi+1;
4624 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
4625 mx->mx_cursor.mc_snum = 0;
4626 mx->mx_cursor.mc_flags = C_SUB;
4627 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
4628 mx->mx_dbx.md_dcmp = NULL;
4629 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
4632 /** Final setup of a sorted-dups cursor.
4633 * Sets up the fields that depend on the data from the main cursor.
4634 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
4635 * @param[in] node The data containing the #MDB_db record for the
4636 * sorted-dup database.
4639 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
4641 MDB_xcursor *mx = mc->mc_xcursor;
4643 if (node->mn_flags & F_SUBDATA) {
4644 MDB_db *db = NODEDATA(node);
4646 mx->mx_cursor.mc_snum = 0;
4647 mx->mx_cursor.mc_flags = C_SUB;
4649 MDB_page *fp = NODEDATA(node);
4650 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
4651 mx->mx_db.md_flags = 0;
4652 mx->mx_db.md_depth = 1;
4653 mx->mx_db.md_branch_pages = 0;
4654 mx->mx_db.md_leaf_pages = 1;
4655 mx->mx_db.md_overflow_pages = 0;
4656 mx->mx_db.md_entries = NUMKEYS(fp);
4657 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
4658 mx->mx_cursor.mc_snum = 1;
4659 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
4660 mx->mx_cursor.mc_top = 0;
4661 mx->mx_cursor.mc_pg[0] = fp;
4662 mx->mx_cursor.mc_ki[0] = 0;
4663 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4664 mx->mx_db.md_flags = MDB_DUPFIXED;
4665 mx->mx_db.md_pad = fp->mp_pad;
4666 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
4667 mx->mx_db.md_flags |= MDB_INTEGERKEY;
4670 DPRINTF("Sub-db %u for db %u root page %zu", mx->mx_cursor.mc_dbi, mc->mc_dbi,
4672 mx->mx_dbflag = (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY)) ?
4674 mx->mx_dbx.md_name.mv_data = NODEKEY(node);
4675 mx->mx_dbx.md_name.mv_size = node->mn_ksize;
4676 #if UINT_MAX > SIZE_MAX
4677 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
4678 #ifdef MISALIGNED_OK
4679 mx->mx_dbx.md_cmp = mdb_cmp_long;
4681 mx->mx_dbx.md_cmp = mdb_cmp_cint;
4686 /** Initialize a cursor for a given transaction and database. */
4688 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
4693 mc->mc_db = &txn->mt_dbs[dbi];
4694 mc->mc_dbx = &txn->mt_dbxs[dbi];
4695 mc->mc_dbflag = &txn->mt_dbflags[dbi];
4698 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4700 mc->mc_xcursor = mx;
4701 mdb_xcursor_init0(mc);
4703 mc->mc_xcursor = NULL;
4708 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
4711 MDB_xcursor *mx = NULL;
4712 size_t size = sizeof(MDB_cursor);
4714 if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
4717 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
4718 size += sizeof(MDB_xcursor);
4720 if ((mc = malloc(size)) != NULL) {
4721 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4722 mx = (MDB_xcursor *)(mc + 1);
4724 mdb_cursor_init(mc, txn, dbi, mx);
4725 if (txn->mt_cursors) {
4726 mc->mc_next = txn->mt_cursors[dbi];
4727 txn->mt_cursors[dbi] = mc;
4729 mc->mc_flags |= C_ALLOCD;
4739 /* Return the count of duplicate data items for the current key */
4741 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
4745 if (mc == NULL || countp == NULL)
4748 if (!(mc->mc_db->md_flags & MDB_DUPSORT))
4751 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4752 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4755 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
4758 *countp = mc->mc_xcursor->mx_db.md_entries;
4764 mdb_cursor_close(MDB_cursor *mc)
4767 /* remove from txn, if tracked */
4768 if (mc->mc_txn->mt_cursors) {
4769 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
4770 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
4772 *prev = mc->mc_next;
4774 if (mc->mc_flags & C_ALLOCD)
4780 mdb_cursor_txn(MDB_cursor *mc)
4782 if (!mc) return NULL;
4787 mdb_cursor_dbi(MDB_cursor *mc)
4793 /** Replace the key for a node with a new key.
4794 * @param[in] mp The page containing the node to operate on.
4795 * @param[in] indx The index of the node to operate on.
4796 * @param[in] key The new key to use.
4797 * @return 0 on success, non-zero on failure.
4800 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
4802 indx_t ptr, i, numkeys;
4809 node = NODEPTR(mp, indx);
4810 ptr = mp->mp_ptrs[indx];
4811 DPRINTF("update key %u (ofs %u) [%.*s] to [%s] on page %zu",
4813 (int)node->mn_ksize, (char *)NODEKEY(node),
4817 delta = key->mv_size - node->mn_ksize;
4819 if (delta > 0 && SIZELEFT(mp) < delta) {
4820 DPRINTF("OUCH! Not enough room, delta = %d", delta);
4824 numkeys = NUMKEYS(mp);
4825 for (i = 0; i < numkeys; i++) {
4826 if (mp->mp_ptrs[i] <= ptr)
4827 mp->mp_ptrs[i] -= delta;
4830 base = (char *)mp + mp->mp_upper;
4831 len = ptr - mp->mp_upper + NODESIZE;
4832 memmove(base - delta, base, len);
4833 mp->mp_upper -= delta;
4835 node = NODEPTR(mp, indx);
4836 node->mn_ksize = key->mv_size;
4839 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
4844 /** Move a node from csrc to cdst.
4847 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
4854 /* Mark src and dst as dirty. */
4855 if ((rc = mdb_page_touch(csrc)) ||
4856 (rc = mdb_page_touch(cdst)))
4859 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4860 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
4861 key.mv_size = csrc->mc_db->md_pad;
4862 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
4864 data.mv_data = NULL;
4866 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
4867 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
4868 unsigned int snum = csrc->mc_snum;
4870 /* must find the lowest key below src */
4871 mdb_page_search_root(csrc, NULL, 0);
4872 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
4873 key.mv_size = NODEKSZ(s2);
4874 key.mv_data = NODEKEY(s2);
4875 csrc->mc_snum = snum--;
4876 csrc->mc_top = snum;
4878 key.mv_size = NODEKSZ(srcnode);
4879 key.mv_data = NODEKEY(srcnode);
4881 data.mv_size = NODEDSZ(srcnode);
4882 data.mv_data = NODEDATA(srcnode);
4884 DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
4885 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
4886 csrc->mc_ki[csrc->mc_top],
4888 csrc->mc_pg[csrc->mc_top]->mp_pgno,
4889 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
4891 /* Add the node to the destination page.
4893 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, NODEPGNO(srcnode),
4895 if (rc != MDB_SUCCESS)
4898 /* Delete the node from the source page.
4900 mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
4903 /* Adjust other cursors pointing to mp */
4904 MDB_cursor *m2, *m3;
4905 MDB_dbi dbi = csrc->mc_dbi;
4906 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
4908 if (csrc->mc_flags & C_SUB)
4911 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
4912 if (m2 == csrc) continue;
4913 if (csrc->mc_flags & C_SUB)
4914 m3 = &m2->mc_xcursor->mx_cursor;
4917 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
4918 csrc->mc_ki[csrc->mc_top]) {
4919 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
4920 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
4925 /* Update the parent separators.
4927 if (csrc->mc_ki[csrc->mc_top] == 0) {
4928 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
4929 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4930 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
4932 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
4933 key.mv_size = NODEKSZ(srcnode);
4934 key.mv_data = NODEKEY(srcnode);
4936 DPRINTF("update separator for source page %zu to [%s]",
4937 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
4938 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1],
4939 &key)) != MDB_SUCCESS)
4942 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
4944 nullkey.mv_size = 0;
4945 rc = mdb_update_key(csrc->mc_pg[csrc->mc_top], 0, &nullkey);
4946 assert(rc == MDB_SUCCESS);
4950 if (cdst->mc_ki[cdst->mc_top] == 0) {
4951 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
4952 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4953 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
4955 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
4956 key.mv_size = NODEKSZ(srcnode);
4957 key.mv_data = NODEKEY(srcnode);
4959 DPRINTF("update separator for destination page %zu to [%s]",
4960 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
4961 if ((rc = mdb_update_key(cdst->mc_pg[cdst->mc_top-1], cdst->mc_ki[cdst->mc_top-1],
4962 &key)) != MDB_SUCCESS)
4965 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
4967 nullkey.mv_size = 0;
4968 rc = mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &nullkey);
4969 assert(rc == MDB_SUCCESS);
4976 /** Merge one page into another.
4977 * The nodes from the page pointed to by \b csrc will
4978 * be copied to the page pointed to by \b cdst and then
4979 * the \b csrc page will be freed.
4980 * @param[in] csrc Cursor pointing to the source page.
4981 * @param[in] cdst Cursor pointing to the destination page.
4984 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
4992 DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
4993 cdst->mc_pg[cdst->mc_top]->mp_pgno);
4995 assert(csrc->mc_snum > 1); /* can't merge root page */
4996 assert(cdst->mc_snum > 1);
4998 /* Mark dst as dirty. */
4999 if ((rc = mdb_page_touch(cdst)))
5002 /* Move all nodes from src to dst.
5004 j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
5005 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5006 key.mv_size = csrc->mc_db->md_pad;
5007 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
5008 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
5009 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
5010 if (rc != MDB_SUCCESS)
5012 key.mv_data = (char *)key.mv_data + key.mv_size;
5015 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
5016 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
5018 key.mv_size = srcnode->mn_ksize;
5019 key.mv_data = NODEKEY(srcnode);
5020 data.mv_size = NODEDSZ(srcnode);
5021 data.mv_data = NODEDATA(srcnode);
5022 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
5023 if (rc != MDB_SUCCESS)
5028 DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
5029 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);
5031 /* Unlink the src page from parent and add to free list.
5033 mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
5034 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
5036 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], 0, &key)) != MDB_SUCCESS)
5040 mdb_midl_append(&csrc->mc_txn->mt_free_pgs, csrc->mc_pg[csrc->mc_top]->mp_pgno);
5041 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
5042 csrc->mc_db->md_leaf_pages--;
5044 csrc->mc_db->md_branch_pages--;
5046 /* Adjust other cursors pointing to mp */
5047 MDB_cursor *m2, *m3;
5048 MDB_dbi dbi = csrc->mc_dbi;
5049 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
5051 if (csrc->mc_flags & C_SUB)
5054 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5055 if (m2 == csrc) continue;
5056 if (csrc->mc_flags & C_SUB)
5057 m3 = &m2->mc_xcursor->mx_cursor;
5060 if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
5061 m3->mc_pg[csrc->mc_top] = mp;
5062 m3->mc_ki[csrc->mc_top] += nkeys;
5066 mdb_cursor_pop(csrc);
5068 return mdb_rebalance(csrc);
5071 /** Copy the contents of a cursor.
5072 * @param[in] csrc The cursor to copy from.
5073 * @param[out] cdst The cursor to copy to.
5076 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
5080 cdst->mc_txn = csrc->mc_txn;
5081 cdst->mc_dbi = csrc->mc_dbi;
5082 cdst->mc_db = csrc->mc_db;
5083 cdst->mc_dbx = csrc->mc_dbx;
5084 cdst->mc_snum = csrc->mc_snum;
5085 cdst->mc_top = csrc->mc_top;
5086 cdst->mc_flags = csrc->mc_flags;
5088 for (i=0; i<csrc->mc_snum; i++) {
5089 cdst->mc_pg[i] = csrc->mc_pg[i];
5090 cdst->mc_ki[i] = csrc->mc_ki[i];
5094 /** Rebalance the tree after a delete operation.
5095 * @param[in] mc Cursor pointing to the page where rebalancing
5097 * @return 0 on success, non-zero on failure.
5100 mdb_rebalance(MDB_cursor *mc)
5107 DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
5108 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
5109 mc->mc_pg[mc->mc_top]->mp_pgno, NUMKEYS(mc->mc_pg[mc->mc_top]), (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10);
5111 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD) {
5112 DPRINTF("no need to rebalance page %zu, above fill threshold",
5113 mc->mc_pg[mc->mc_top]->mp_pgno);
5117 if (mc->mc_snum < 2) {
5118 MDB_page *mp = mc->mc_pg[0];
5119 if (NUMKEYS(mp) == 0) {
5120 DPUTS("tree is completely empty");
5121 mc->mc_db->md_root = P_INVALID;
5122 mc->mc_db->md_depth = 0;
5123 mc->mc_db->md_leaf_pages = 0;
5124 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5128 /* Adjust other cursors pointing to mp */
5129 MDB_cursor *m2, *m3;
5130 MDB_dbi dbi = mc->mc_dbi;
5132 if (mc->mc_flags & C_SUB)
5135 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5136 if (m2 == mc) continue;
5137 if (mc->mc_flags & C_SUB)
5138 m3 = &m2->mc_xcursor->mx_cursor;
5141 if (m3->mc_pg[0] == mp) {
5147 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
5148 DPUTS("collapsing root page!");
5149 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5150 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
5151 if ((rc = mdb_page_get(mc->mc_txn, mc->mc_db->md_root,
5154 mc->mc_db->md_depth--;
5155 mc->mc_db->md_branch_pages--;
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) {
5171 m3->mc_pg[0] = mc->mc_pg[0];
5176 DPUTS("root page doesn't need rebalancing");
5180 /* The parent (branch page) must have at least 2 pointers,
5181 * otherwise the tree is invalid.
5183 ptop = mc->mc_top-1;
5184 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
5186 /* Leaf page fill factor is below the threshold.
5187 * Try to move keys from left or right neighbor, or
5188 * merge with a neighbor page.
5193 mdb_cursor_copy(mc, &mn);
5194 mn.mc_xcursor = NULL;
5196 if (mc->mc_ki[ptop] == 0) {
5197 /* We're the leftmost leaf in our parent.
5199 DPUTS("reading right neighbor");
5201 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5202 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5204 mn.mc_ki[mn.mc_top] = 0;
5205 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
5207 /* There is at least one neighbor to the left.
5209 DPUTS("reading left neighbor");
5211 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5212 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5214 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
5215 mc->mc_ki[mc->mc_top] = 0;
5218 DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
5219 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);
5221 /* If the neighbor page is above threshold and has at least two
5222 * keys, move one key from it.
5224 * Otherwise we should try to merge them.
5226 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) >= 2)
5227 return mdb_node_move(&mn, mc);
5228 else { /* FIXME: if (has_enough_room()) */
5229 mc->mc_flags &= ~C_INITIALIZED;
5230 if (mc->mc_ki[ptop] == 0)
5231 return mdb_page_merge(&mn, mc);
5233 return mdb_page_merge(mc, &mn);
5237 /** Complete a delete operation started by #mdb_cursor_del(). */
5239 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
5243 /* add overflow pages to free list */
5244 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5248 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
5249 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
5250 for (i=0; i<ovpages; i++) {
5251 DPRINTF("freed ov page %zu", pg);
5252 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
5256 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], mc->mc_db->md_pad);
5257 mc->mc_db->md_entries--;
5258 rc = mdb_rebalance(mc);
5259 if (rc != MDB_SUCCESS)
5260 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5266 mdb_del(MDB_txn *txn, MDB_dbi dbi,
5267 MDB_val *key, MDB_val *data)
5272 MDB_val rdata, *xdata;
5276 assert(key != NULL);
5278 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
5280 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5283 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
5287 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
5291 mdb_cursor_init(&mc, txn, dbi, &mx);
5302 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
5304 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
5308 /** Split a page and insert a new node.
5309 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
5310 * The cursor will be updated to point to the actual page and index where
5311 * the node got inserted after the split.
5312 * @param[in] newkey The key for the newly inserted node.
5313 * @param[in] newdata The data for the newly inserted node.
5314 * @param[in] newpgno The page number, if the new node is a branch node.
5315 * @return 0 on success, non-zero on failure.
5318 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
5319 unsigned int nflags)
5322 int rc = MDB_SUCCESS, ins_new = 0, new_root = 0;
5325 unsigned int i, j, split_indx, nkeys, pmax;
5327 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
5329 MDB_page *mp, *rp, *pp;
5334 mp = mc->mc_pg[mc->mc_top];
5335 newindx = mc->mc_ki[mc->mc_top];
5337 DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
5338 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
5339 DKEY(newkey), mc->mc_ki[mc->mc_top]);
5341 if (mc->mc_snum < 2) {
5342 if ((pp = mdb_page_new(mc, P_BRANCH, 1)) == NULL)
5344 /* shift current top to make room for new parent */
5345 mc->mc_pg[1] = mc->mc_pg[0];
5346 mc->mc_ki[1] = mc->mc_ki[0];
5349 mc->mc_db->md_root = pp->mp_pgno;
5350 DPRINTF("root split! new root = %zu", pp->mp_pgno);
5351 mc->mc_db->md_depth++;
5354 /* Add left (implicit) pointer. */
5355 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
5356 /* undo the pre-push */
5357 mc->mc_pg[0] = mc->mc_pg[1];
5358 mc->mc_ki[0] = mc->mc_ki[1];
5359 mc->mc_db->md_root = mp->mp_pgno;
5360 mc->mc_db->md_depth--;
5367 ptop = mc->mc_top-1;
5368 DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
5371 /* Create a right sibling. */
5372 if ((rp = mdb_page_new(mc, mp->mp_flags, 1)) == NULL)
5374 DPRINTF("new right sibling: page %zu", rp->mp_pgno);
5376 mdb_cursor_copy(mc, &mn);
5377 mn.mc_pg[mn.mc_top] = rp;
5378 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
5380 if (nflags & MDB_APPEND) {
5381 mn.mc_ki[mn.mc_top] = 0;
5388 nkeys = NUMKEYS(mp);
5389 split_indx = nkeys / 2 + 1;
5394 unsigned int lsize, rsize, ksize;
5395 /* Move half of the keys to the right sibling */
5397 x = mc->mc_ki[mc->mc_top] - split_indx;
5398 ksize = mc->mc_db->md_pad;
5399 split = LEAF2KEY(mp, split_indx, ksize);
5400 rsize = (nkeys - split_indx) * ksize;
5401 lsize = (nkeys - split_indx) * sizeof(indx_t);
5402 mp->mp_lower -= lsize;
5403 rp->mp_lower += lsize;
5404 mp->mp_upper += rsize - lsize;
5405 rp->mp_upper -= rsize - lsize;
5406 sepkey.mv_size = ksize;
5407 if (newindx == split_indx) {
5408 sepkey.mv_data = newkey->mv_data;
5410 sepkey.mv_data = split;
5413 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
5414 memcpy(rp->mp_ptrs, split, rsize);
5415 sepkey.mv_data = rp->mp_ptrs;
5416 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
5417 memcpy(ins, newkey->mv_data, ksize);
5418 mp->mp_lower += sizeof(indx_t);
5419 mp->mp_upper -= ksize - sizeof(indx_t);
5422 memcpy(rp->mp_ptrs, split, x * ksize);
5423 ins = LEAF2KEY(rp, x, ksize);
5424 memcpy(ins, newkey->mv_data, ksize);
5425 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
5426 rp->mp_lower += sizeof(indx_t);
5427 rp->mp_upper -= ksize - sizeof(indx_t);
5428 mc->mc_ki[mc->mc_top] = x;
5429 mc->mc_pg[mc->mc_top] = rp;
5434 /* For leaf pages, check the split point based on what
5435 * fits where, since otherwise add_node can fail.
5438 unsigned int psize, nsize;
5439 /* Maximum free space in an empty page */
5440 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
5441 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
5442 if (newindx < split_indx) {
5444 for (i=0; i<split_indx; i++) {
5445 node = NODEPTR(mp, i);
5446 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
5447 if (F_ISSET(node->mn_flags, F_BIGDATA))
5448 psize += sizeof(pgno_t);
5450 psize += NODEDSZ(node);
5459 for (i=nkeys-1; i>=split_indx; i--) {
5460 node = NODEPTR(mp, i);
5461 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
5462 if (F_ISSET(node->mn_flags, F_BIGDATA))
5463 psize += sizeof(pgno_t);
5465 psize += NODEDSZ(node);
5475 /* First find the separating key between the split pages.
5477 if (newindx == split_indx) {
5478 sepkey.mv_size = newkey->mv_size;
5479 sepkey.mv_data = newkey->mv_data;
5481 node = NODEPTR(mp, split_indx);
5482 sepkey.mv_size = node->mn_ksize;
5483 sepkey.mv_data = NODEKEY(node);
5487 DPRINTF("separator is [%s]", DKEY(&sepkey));
5489 /* Copy separator key to the parent.
5491 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
5494 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
5496 /* Right page might now have changed parent.
5497 * Check if left page also changed parent.
5499 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
5500 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
5501 mc->mc_pg[ptop] = mn.mc_pg[ptop];
5502 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
5506 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
5509 if (rc != MDB_SUCCESS) {
5512 if (nflags & MDB_APPEND) {
5513 mc->mc_pg[mc->mc_top] = rp;
5514 mc->mc_ki[mc->mc_top] = 0;
5515 return mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
5521 /* Move half of the keys to the right sibling. */
5523 /* grab a page to hold a temporary copy */
5524 copy = mdb_page_malloc(mc);
5528 copy->mp_pgno = mp->mp_pgno;
5529 copy->mp_flags = mp->mp_flags;
5530 copy->mp_lower = PAGEHDRSZ;
5531 copy->mp_upper = mc->mc_txn->mt_env->me_psize;
5532 mc->mc_pg[mc->mc_top] = copy;
5533 for (i = j = 0; i <= nkeys; j++) {
5534 if (i == split_indx) {
5535 /* Insert in right sibling. */
5536 /* Reset insert index for right sibling. */
5537 j = (i == newindx && ins_new);
5538 mc->mc_pg[mc->mc_top] = rp;
5541 if (i == newindx && !ins_new) {
5542 /* Insert the original entry that caused the split. */
5543 rkey.mv_data = newkey->mv_data;
5544 rkey.mv_size = newkey->mv_size;
5553 /* Update page and index for the new key. */
5554 mc->mc_ki[mc->mc_top] = j;
5555 } else if (i == nkeys) {
5558 node = NODEPTR(mp, i);
5559 rkey.mv_data = NODEKEY(node);
5560 rkey.mv_size = node->mn_ksize;
5562 xdata.mv_data = NODEDATA(node);
5563 xdata.mv_size = NODEDSZ(node);
5566 pgno = NODEPGNO(node);
5567 flags = node->mn_flags;
5572 if (!IS_LEAF(mp) && j == 0) {
5573 /* First branch index doesn't need key data. */
5577 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
5580 nkeys = NUMKEYS(copy);
5581 for (i=0; i<nkeys; i++)
5582 mp->mp_ptrs[i] = copy->mp_ptrs[i];
5583 mp->mp_lower = copy->mp_lower;
5584 mp->mp_upper = copy->mp_upper;
5585 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
5586 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
5588 /* reset back to original page */
5589 if (newindx < split_indx) {
5590 mc->mc_pg[mc->mc_top] = mp;
5591 if (nflags & MDB_RESERVE) {
5592 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5593 if (!(node->mn_flags & F_BIGDATA))
5594 newdata->mv_data = NODEDATA(node);
5598 /* return tmp page to freelist */
5599 copy->mp_next = mc->mc_txn->mt_env->me_dpages;
5600 mc->mc_txn->mt_env->me_dpages = copy;
5603 /* Adjust other cursors pointing to mp */
5604 MDB_cursor *m2, *m3;
5605 MDB_dbi dbi = mc->mc_dbi;
5607 if (mc->mc_flags & C_SUB)
5610 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5611 if (m2 == mc) continue;
5612 if (mc->mc_flags & C_SUB)
5613 m3 = &m2->mc_xcursor->mx_cursor;
5616 if (!(m3->mc_flags & C_INITIALIZED))
5620 for (i=m3->mc_top; i>0; i--) {
5621 m3->mc_ki[i+1] = m3->mc_ki[i];
5622 m3->mc_pg[i+1] = m3->mc_pg[i];
5624 m3->mc_ki[0] = mc->mc_ki[0];
5625 m3->mc_pg[0] = mc->mc_pg[0];
5629 if (m3->mc_pg[mc->mc_top] == mp) {
5630 if (m3->mc_ki[m3->mc_top] >= split_indx) {
5631 m3->mc_pg[m3->mc_top] = rp;
5632 m3->mc_ki[m3->mc_top] -= split_indx;
5641 mdb_put(MDB_txn *txn, MDB_dbi dbi,
5642 MDB_val *key, MDB_val *data, unsigned int flags)
5647 assert(key != NULL);
5648 assert(data != NULL);
5650 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5653 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
5657 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
5661 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND)) != flags)
5664 mdb_cursor_init(&mc, txn, dbi, &mx);
5665 return mdb_cursor_put(&mc, key, data, flags);
5668 /** Only a subset of the @ref mdb_env flags can be changed
5669 * at runtime. Changing other flags requires closing the environment
5670 * and re-opening it with the new flags.
5672 #define CHANGEABLE (MDB_NOSYNC)
5674 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
5676 if ((flag & CHANGEABLE) != flag)
5679 env->me_flags |= flag;
5681 env->me_flags &= ~flag;
5686 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
5691 *arg = env->me_flags;
5696 mdb_env_get_path(MDB_env *env, const char **arg)
5701 *arg = env->me_path;
5705 /** Common code for #mdb_stat() and #mdb_env_stat().
5706 * @param[in] env the environment to operate in.
5707 * @param[in] db the #MDB_db record containing the stats to return.
5708 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
5709 * @return 0, this function always succeeds.
5712 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
5714 arg->ms_psize = env->me_psize;
5715 arg->ms_depth = db->md_depth;
5716 arg->ms_branch_pages = db->md_branch_pages;
5717 arg->ms_leaf_pages = db->md_leaf_pages;
5718 arg->ms_overflow_pages = db->md_overflow_pages;
5719 arg->ms_entries = db->md_entries;
5724 mdb_env_stat(MDB_env *env, MDB_stat *arg)
5728 if (env == NULL || arg == NULL)
5731 mdb_env_read_meta(env, &toggle);
5733 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
5736 /** Set the default comparison functions for a database.
5737 * Called immediately after a database is opened to set the defaults.
5738 * The user can then override them with #mdb_set_compare() or
5739 * #mdb_set_dupsort().
5740 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
5741 * @param[in] dbi A database handle returned by #mdb_open()
5744 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
5746 if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEKEY)
5747 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memnr;
5748 else if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERKEY)
5749 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_cint;
5751 txn->mt_dbxs[dbi].md_cmp = mdb_cmp_memn;
5753 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
5754 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP) {
5755 if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED)
5756 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_int;
5758 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_cint;
5759 } else if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEDUP) {
5760 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memnr;
5762 txn->mt_dbxs[dbi].md_dcmp = mdb_cmp_memn;
5765 txn->mt_dbxs[dbi].md_dcmp = NULL;
5769 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
5774 int rc, dbflag, exact;
5777 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
5778 mdb_default_cmp(txn, FREE_DBI);
5784 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
5785 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
5786 mdb_default_cmp(txn, MAIN_DBI);
5790 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
5791 mdb_default_cmp(txn, MAIN_DBI);
5794 /* Is the DB already open? */
5796 for (i=2; i<txn->mt_numdbs; i++) {
5797 if (len == txn->mt_dbxs[i].md_name.mv_size &&
5798 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
5804 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
5807 /* Find the DB info */
5811 key.mv_data = (void *)name;
5812 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
5813 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
5814 if (rc == MDB_SUCCESS) {
5815 /* make sure this is actually a DB */
5816 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
5817 if (!(node->mn_flags & F_SUBDATA))
5819 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
5820 /* Create if requested */
5822 data.mv_size = sizeof(MDB_db);
5823 data.mv_data = &dummy;
5824 memset(&dummy, 0, sizeof(dummy));
5825 dummy.md_root = P_INVALID;
5826 dummy.md_flags = flags & 0xffff;
5827 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
5831 /* OK, got info, add to table */
5832 if (rc == MDB_SUCCESS) {
5833 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
5834 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
5835 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
5836 txn->mt_dbflags[txn->mt_numdbs] = dbflag;
5837 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
5838 *dbi = txn->mt_numdbs;
5839 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
5840 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
5841 mdb_default_cmp(txn, txn->mt_numdbs);
5848 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
5850 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
5853 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
5856 void mdb_close(MDB_env *env, MDB_dbi dbi)
5859 if (dbi <= MAIN_DBI || dbi >= env->me_numdbs)
5861 ptr = env->me_dbxs[dbi].md_name.mv_data;
5862 env->me_dbxs[dbi].md_name.mv_data = NULL;
5863 env->me_dbxs[dbi].md_name.mv_size = 0;
5867 /** Add all the DB's pages to the free list.
5868 * @param[in] mc Cursor on the DB to free.
5869 * @param[in] subs non-Zero to check for sub-DBs in this DB.
5870 * @return 0 on success, non-zero on failure.
5873 mdb_drop0(MDB_cursor *mc, int subs)
5877 rc = mdb_page_search(mc, NULL, 0);
5878 if (rc == MDB_SUCCESS) {
5883 /* LEAF2 pages have no nodes, cannot have sub-DBs */
5884 if (!subs || IS_LEAF2(mc->mc_pg[mc->mc_top]))
5887 mdb_cursor_copy(mc, &mx);
5888 while (mc->mc_snum > 0) {
5889 if (IS_LEAF(mc->mc_pg[mc->mc_top])) {
5890 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
5891 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
5892 if (ni->mn_flags & F_SUBDATA) {
5893 mdb_xcursor_init1(mc, ni);
5894 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
5900 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
5902 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
5905 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
5910 rc = mdb_cursor_sibling(mc, 1);
5912 /* no more siblings, go back to beginning
5913 * of previous level. (stack was already popped
5914 * by mdb_cursor_sibling)
5916 for (i=1; i<mc->mc_top; i++)
5917 mc->mc_pg[i] = mx.mc_pg[i];
5921 mdb_midl_append(&mc->mc_txn->mt_free_pgs,
5922 mc->mc_db->md_root);
5927 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
5932 if (!txn || !dbi || dbi >= txn->mt_numdbs)
5935 rc = mdb_cursor_open(txn, dbi, &mc);
5939 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
5943 /* Can't delete the main DB */
5944 if (del && dbi > MAIN_DBI) {
5945 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
5947 mdb_close(txn->mt_env, dbi);
5949 txn->mt_dbflags[dbi] |= DB_DIRTY;
5950 txn->mt_dbs[dbi].md_depth = 0;
5951 txn->mt_dbs[dbi].md_branch_pages = 0;
5952 txn->mt_dbs[dbi].md_leaf_pages = 0;
5953 txn->mt_dbs[dbi].md_overflow_pages = 0;
5954 txn->mt_dbs[dbi].md_entries = 0;
5955 txn->mt_dbs[dbi].md_root = P_INVALID;
5958 mdb_cursor_close(mc);
5962 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
5964 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5967 txn->mt_dbxs[dbi].md_cmp = cmp;
5971 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
5973 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5976 txn->mt_dbxs[dbi].md_dcmp = cmp;
5980 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
5982 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5985 txn->mt_dbxs[dbi].md_rel = rel;
5989 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
5991 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5994 txn->mt_dbxs[dbi].md_relctx = ctx;