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-2013 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.
38 #include <sys/types.h>
40 #include <sys/param.h>
46 #ifdef HAVE_SYS_FILE_H
63 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
64 #include <netinet/in.h>
65 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
68 #if defined(__APPLE__) || defined (BSD)
69 # define MDB_USE_POSIX_SEM 1
70 # define MDB_FDATASYNC fsync
71 #elif defined(ANDROID)
72 # define MDB_FDATASYNC fsync
77 #ifdef MDB_USE_POSIX_SEM
78 #include <semaphore.h>
83 #include <valgrind/memcheck.h>
84 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
85 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
86 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
87 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
88 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
90 #define VGMEMP_CREATE(h,r,z)
91 #define VGMEMP_ALLOC(h,a,s)
92 #define VGMEMP_FREE(h,a)
93 #define VGMEMP_DESTROY(h)
94 #define VGMEMP_DEFINED(a,s)
98 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
99 /* Solaris just defines one or the other */
100 # define LITTLE_ENDIAN 1234
101 # define BIG_ENDIAN 4321
102 # ifdef _LITTLE_ENDIAN
103 # define BYTE_ORDER LITTLE_ENDIAN
105 # define BYTE_ORDER BIG_ENDIAN
108 # define BYTE_ORDER __BYTE_ORDER
112 #ifndef LITTLE_ENDIAN
113 #define LITTLE_ENDIAN __LITTLE_ENDIAN
116 #define BIG_ENDIAN __BIG_ENDIAN
119 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
120 #define MISALIGNED_OK 1
126 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
127 # error "Unknown or unsupported endianness (BYTE_ORDER)"
128 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
129 # error "Two's complement, reasonably sized integer types, please"
132 /** @defgroup internal MDB Internals
135 /** @defgroup compat Windows Compatibility Macros
136 * A bunch of macros to minimize the amount of platform-specific ifdefs
137 * needed throughout the rest of the code. When the features this library
138 * needs are similar enough to POSIX to be hidden in a one-or-two line
139 * replacement, this macro approach is used.
143 #define pthread_t DWORD
144 #define pthread_mutex_t HANDLE
145 #define pthread_key_t DWORD
146 #define pthread_self() GetCurrentThreadId()
147 #define pthread_key_create(x,y) \
148 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
149 #define pthread_key_delete(x) TlsFree(x)
150 #define pthread_getspecific(x) TlsGetValue(x)
151 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
152 #define pthread_mutex_unlock(x) ReleaseMutex(x)
153 #define pthread_mutex_lock(x) WaitForSingleObject(x, INFINITE)
154 #define LOCK_MUTEX_R(env) pthread_mutex_lock((env)->me_rmutex)
155 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock((env)->me_rmutex)
156 #define LOCK_MUTEX_W(env) pthread_mutex_lock((env)->me_wmutex)
157 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock((env)->me_wmutex)
158 #define getpid() GetCurrentProcessId()
159 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
160 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
161 #define ErrCode() GetLastError()
162 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
163 #define close(fd) (CloseHandle(fd) ? 0 : -1)
164 #define munmap(ptr,len) UnmapViewOfFile(ptr)
167 #ifdef MDB_USE_POSIX_SEM
169 #define LOCK_MUTEX_R(env) mdb_sem_wait((env)->me_rmutex)
170 #define UNLOCK_MUTEX_R(env) sem_post((env)->me_rmutex)
171 #define LOCK_MUTEX_W(env) mdb_sem_wait((env)->me_wmutex)
172 #define UNLOCK_MUTEX_W(env) sem_post((env)->me_wmutex)
175 mdb_sem_wait(sem_t *sem)
178 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
183 /** Lock the reader mutex.
185 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
186 /** Unlock the reader mutex.
188 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
190 /** Lock the writer mutex.
191 * Only a single write transaction is allowed at a time. Other writers
192 * will block waiting for this mutex.
194 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
195 /** Unlock the writer mutex.
197 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
198 #endif /* MDB_USE_POSIX_SEM */
200 /** Get the error code for the last failed system function.
202 #define ErrCode() errno
204 /** An abstraction for a file handle.
205 * On POSIX systems file handles are small integers. On Windows
206 * they're opaque pointers.
210 /** A value for an invalid file handle.
211 * Mainly used to initialize file variables and signify that they are
214 #define INVALID_HANDLE_VALUE (-1)
216 /** Get the size of a memory page for the system.
217 * This is the basic size that the platform's memory manager uses, and is
218 * fundamental to the use of memory-mapped files.
220 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
223 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
226 #define MNAME_LEN (sizeof(pthread_mutex_t))
232 /** A flag for opening a file and requesting synchronous data writes.
233 * This is only used when writing a meta page. It's not strictly needed;
234 * we could just do a normal write and then immediately perform a flush.
235 * But if this flag is available it saves us an extra system call.
237 * @note If O_DSYNC is undefined but exists in /usr/include,
238 * preferably set some compiler flag to get the definition.
239 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
242 # define MDB_DSYNC O_DSYNC
246 /** Function for flushing the data of a file. Define this to fsync
247 * if fdatasync() is not supported.
249 #ifndef MDB_FDATASYNC
250 # define MDB_FDATASYNC fdatasync
254 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
265 /** A page number in the database.
266 * Note that 64 bit page numbers are overkill, since pages themselves
267 * already represent 12-13 bits of addressable memory, and the OS will
268 * always limit applications to a maximum of 63 bits of address space.
270 * @note In the #MDB_node structure, we only store 48 bits of this value,
271 * which thus limits us to only 60 bits of addressable data.
273 typedef MDB_ID pgno_t;
275 /** A transaction ID.
276 * See struct MDB_txn.mt_txnid for details.
278 typedef MDB_ID txnid_t;
280 /** @defgroup debug Debug Macros
284 /** Enable debug output.
285 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
286 * read from and written to the database (used for free space management).
291 #if !(__STDC_VERSION__ >= 199901L || defined(__GNUC__))
294 # define DPRINTF (void) /* Vararg macros may be unsupported */
296 static int mdb_debug;
297 static txnid_t mdb_debug_start;
299 /** Print a debug message with printf formatting. */
300 # define DPRINTF(fmt, ...) /**< Requires 2 or more args */ \
301 ((void) ((mdb_debug) && \
302 fprintf(stderr, "%s:%d " fmt "\n", __func__, __LINE__, __VA_ARGS__)))
304 # define DPRINTF(fmt, ...) ((void) 0)
305 # define MDB_DEBUG_SKIP
307 /** Print a debug string.
308 * The string is printed literally, with no format processing.
310 #define DPUTS(arg) DPRINTF("%s", arg)
313 /** A default memory page size.
314 * The actual size is platform-dependent, but we use this for
315 * boot-strapping. We probably should not be using this any more.
316 * The #GET_PAGESIZE() macro is used to get the actual size.
318 * Note that we don't currently support Huge pages. On Linux,
319 * regular data files cannot use Huge pages, and in general
320 * Huge pages aren't actually pageable. We rely on the OS
321 * demand-pager to read our data and page it out when memory
322 * pressure from other processes is high. So until OSs have
323 * actual paging support for Huge pages, they're not viable.
325 #define MDB_PAGESIZE 4096
327 /** The minimum number of keys required in a database page.
328 * Setting this to a larger value will place a smaller bound on the
329 * maximum size of a data item. Data items larger than this size will
330 * be pushed into overflow pages instead of being stored directly in
331 * the B-tree node. This value used to default to 4. With a page size
332 * of 4096 bytes that meant that any item larger than 1024 bytes would
333 * go into an overflow page. That also meant that on average 2-3KB of
334 * each overflow page was wasted space. The value cannot be lower than
335 * 2 because then there would no longer be a tree structure. With this
336 * value, items larger than 2KB will go into overflow pages, and on
337 * average only 1KB will be wasted.
339 #define MDB_MINKEYS 2
341 /** A stamp that identifies a file as an MDB file.
342 * There's nothing special about this value other than that it is easily
343 * recognizable, and it will reflect any byte order mismatches.
345 #define MDB_MAGIC 0xBEEFC0DE
347 /** The version number for a database's file format. */
348 #define MDB_VERSION 1
350 /** @brief The maximum size of a key in the database.
352 * The library rejects bigger keys, and cannot deal with records
353 * with bigger keys stored by a library with bigger max keysize.
355 * We require that keys all fit onto a regular page. This limit
356 * could be raised a bit further if needed; to something just
357 * under #MDB_PAGESIZE / #MDB_MINKEYS.
359 * Note that data items in an #MDB_DUPSORT database are actually keys
360 * of a subDB, so they're also limited to this size.
362 #ifndef MDB_MAXKEYSIZE
363 #define MDB_MAXKEYSIZE 511
366 /** @brief The maximum size of a data item.
368 * We only store a 32 bit value for node sizes.
370 #define MAXDATASIZE 0xffffffffUL
375 * This is used for printing a hex dump of a key's contents.
377 #define DKBUF char kbuf[(MDB_MAXKEYSIZE*2+1)]
378 /** Display a key in hex.
380 * Invoke a function to display a key in hex.
382 #define DKEY(x) mdb_dkey(x, kbuf)
384 #define DKBUF typedef int dummy_kbuf /* so we can put ';' after */
388 /** An invalid page number.
389 * Mainly used to denote an empty tree.
391 #define P_INVALID (~(pgno_t)0)
393 /** Test if the flags \b f are set in a flag word \b w. */
394 #define F_ISSET(w, f) (((w) & (f)) == (f))
396 /** Used for offsets within a single page.
397 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
400 typedef uint16_t indx_t;
402 /** Default size of memory map.
403 * This is certainly too small for any actual applications. Apps should always set
404 * the size explicitly using #mdb_env_set_mapsize().
406 #define DEFAULT_MAPSIZE 1048576
408 /** @defgroup readers Reader Lock Table
409 * Readers don't acquire any locks for their data access. Instead, they
410 * simply record their transaction ID in the reader table. The reader
411 * mutex is needed just to find an empty slot in the reader table. The
412 * slot's address is saved in thread-specific data so that subsequent read
413 * transactions started by the same thread need no further locking to proceed.
415 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
417 * No reader table is used if the database is on a read-only filesystem.
419 * Since the database uses multi-version concurrency control, readers don't
420 * actually need any locking. This table is used to keep track of which
421 * readers are using data from which old transactions, so that we'll know
422 * when a particular old transaction is no longer in use. Old transactions
423 * that have discarded any data pages can then have those pages reclaimed
424 * for use by a later write transaction.
426 * The lock table is constructed such that reader slots are aligned with the
427 * processor's cache line size. Any slot is only ever used by one thread.
428 * This alignment guarantees that there will be no contention or cache
429 * thrashing as threads update their own slot info, and also eliminates
430 * any need for locking when accessing a slot.
432 * A writer thread will scan every slot in the table to determine the oldest
433 * outstanding reader transaction. Any freed pages older than this will be
434 * reclaimed by the writer. The writer doesn't use any locks when scanning
435 * this table. This means that there's no guarantee that the writer will
436 * see the most up-to-date reader info, but that's not required for correct
437 * operation - all we need is to know the upper bound on the oldest reader,
438 * we don't care at all about the newest reader. So the only consequence of
439 * reading stale information here is that old pages might hang around a
440 * while longer before being reclaimed. That's actually good anyway, because
441 * the longer we delay reclaiming old pages, the more likely it is that a
442 * string of contiguous pages can be found after coalescing old pages from
443 * many old transactions together.
446 /** Number of slots in the reader table.
447 * This value was chosen somewhat arbitrarily. 126 readers plus a
448 * couple mutexes fit exactly into 8KB on my development machine.
449 * Applications should set the table size using #mdb_env_set_maxreaders().
451 #define DEFAULT_READERS 126
453 /** The size of a CPU cache line in bytes. We want our lock structures
454 * aligned to this size to avoid false cache line sharing in the
456 * This value works for most CPUs. For Itanium this should be 128.
462 /** The information we store in a single slot of the reader table.
463 * In addition to a transaction ID, we also record the process and
464 * thread ID that owns a slot, so that we can detect stale information,
465 * e.g. threads or processes that went away without cleaning up.
466 * @note We currently don't check for stale records. We simply re-init
467 * the table when we know that we're the only process opening the
470 typedef struct MDB_rxbody {
471 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
472 * Multiple readers that start at the same time will probably have the
473 * same ID here. Again, it's not important to exclude them from
474 * anything; all we need to know is which version of the DB they
475 * started from so we can avoid overwriting any data used in that
476 * particular version.
479 /** The process ID of the process owning this reader txn. */
481 /** The thread ID of the thread owning this txn. */
485 /** The actual reader record, with cacheline padding. */
486 typedef struct MDB_reader {
489 /** shorthand for mrb_txnid */
490 #define mr_txnid mru.mrx.mrb_txnid
491 #define mr_pid mru.mrx.mrb_pid
492 #define mr_tid mru.mrx.mrb_tid
493 /** cache line alignment */
494 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
498 /** The header for the reader table.
499 * The table resides in a memory-mapped file. (This is a different file
500 * than is used for the main database.)
502 * For POSIX the actual mutexes reside in the shared memory of this
503 * mapped file. On Windows, mutexes are named objects allocated by the
504 * kernel; we store the mutex names in this mapped file so that other
505 * processes can grab them. This same approach is also used on
506 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
507 * process-shared POSIX mutexes. For these cases where a named object
508 * is used, the object name is derived from a 64 bit FNV hash of the
509 * environment pathname. As such, naming collisions are extremely
510 * unlikely. If a collision occurs, the results are unpredictable.
512 typedef struct MDB_txbody {
513 /** Stamp identifying this as an MDB file. It must be set
516 /** Version number of this lock file. Must be set to #MDB_VERSION. */
517 uint32_t mtb_version;
518 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
519 char mtb_rmname[MNAME_LEN];
521 /** Mutex protecting access to this table.
522 * This is the reader lock that #LOCK_MUTEX_R acquires.
524 pthread_mutex_t mtb_mutex;
526 /** The ID of the last transaction committed to the database.
527 * This is recorded here only for convenience; the value can always
528 * be determined by reading the main database meta pages.
531 /** The number of slots that have been used in the reader table.
532 * This always records the maximum count, it is not decremented
533 * when readers release their slots.
535 unsigned mtb_numreaders;
538 /** The actual reader table definition. */
539 typedef struct MDB_txninfo {
542 #define mti_magic mt1.mtb.mtb_magic
543 #define mti_version mt1.mtb.mtb_version
544 #define mti_mutex mt1.mtb.mtb_mutex
545 #define mti_rmname mt1.mtb.mtb_rmname
546 #define mti_txnid mt1.mtb.mtb_txnid
547 #define mti_numreaders mt1.mtb.mtb_numreaders
548 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
551 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
552 char mt2_wmname[MNAME_LEN];
553 #define mti_wmname mt2.mt2_wmname
555 pthread_mutex_t mt2_wmutex;
556 #define mti_wmutex mt2.mt2_wmutex
558 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
560 MDB_reader mti_readers[1];
564 /** Common header for all page types.
565 * Overflow records occupy a number of contiguous pages with no
566 * headers on any page after the first.
568 typedef struct MDB_page {
569 #define mp_pgno mp_p.p_pgno
570 #define mp_next mp_p.p_next
572 pgno_t p_pgno; /**< page number */
573 void * p_next; /**< for in-memory list of freed structs */
576 /** @defgroup mdb_page Page Flags
578 * Flags for the page headers.
581 #define P_BRANCH 0x01 /**< branch page */
582 #define P_LEAF 0x02 /**< leaf page */
583 #define P_OVERFLOW 0x04 /**< overflow page */
584 #define P_META 0x08 /**< meta page */
585 #define P_DIRTY 0x10 /**< dirty page */
586 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
587 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
589 uint16_t mp_flags; /**< @ref mdb_page */
590 #define mp_lower mp_pb.pb.pb_lower
591 #define mp_upper mp_pb.pb.pb_upper
592 #define mp_pages mp_pb.pb_pages
595 indx_t pb_lower; /**< lower bound of free space */
596 indx_t pb_upper; /**< upper bound of free space */
598 uint32_t pb_pages; /**< number of overflow pages */
600 indx_t mp_ptrs[1]; /**< dynamic size */
603 /** Size of the page header, excluding dynamic data at the end */
604 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
606 /** Address of first usable data byte in a page, after the header */
607 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
609 /** Number of nodes on a page */
610 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
612 /** The amount of space remaining in the page */
613 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
615 /** The percentage of space used in the page, in tenths of a percent. */
616 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
617 ((env)->me_psize - PAGEHDRSZ))
618 /** The minimum page fill factor, in tenths of a percent.
619 * Pages emptier than this are candidates for merging.
621 #define FILL_THRESHOLD 250
623 /** Test if a page is a leaf page */
624 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
625 /** Test if a page is a LEAF2 page */
626 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
627 /** Test if a page is a branch page */
628 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
629 /** Test if a page is an overflow page */
630 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
631 /** Test if a page is a sub page */
632 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
634 /** The number of overflow pages needed to store the given size. */
635 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
637 /** Header for a single key/data pair within a page.
638 * We guarantee 2-byte alignment for nodes.
640 typedef struct MDB_node {
641 /** lo and hi are used for data size on leaf nodes and for
642 * child pgno on branch nodes. On 64 bit platforms, flags
643 * is also used for pgno. (Branch nodes have no flags).
644 * They are in host byte order in case that lets some
645 * accesses be optimized into a 32-bit word access.
647 #define mn_lo mn_offset[BYTE_ORDER!=LITTLE_ENDIAN]
648 #define mn_hi mn_offset[BYTE_ORDER==LITTLE_ENDIAN] /**< part of dsize or pgno */
649 unsigned short mn_offset[2]; /**< storage for #mn_lo and #mn_hi */
650 /** @defgroup mdb_node Node Flags
652 * Flags for node headers.
655 #define F_BIGDATA 0x01 /**< data put on overflow page */
656 #define F_SUBDATA 0x02 /**< data is a sub-database */
657 #define F_DUPDATA 0x04 /**< data has duplicates */
659 /** valid flags for #mdb_node_add() */
660 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
663 unsigned short mn_flags; /**< @ref mdb_node */
664 unsigned short mn_ksize; /**< key size */
665 char mn_data[1]; /**< key and data are appended here */
668 /** Size of the node header, excluding dynamic data at the end */
669 #define NODESIZE offsetof(MDB_node, mn_data)
671 /** Bit position of top word in page number, for shifting mn_flags */
672 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
674 /** Size of a node in a branch page with a given key.
675 * This is just the node header plus the key, there is no data.
677 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
679 /** Size of a node in a leaf page with a given key and data.
680 * This is node header plus key plus data size.
682 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
684 /** Address of node \b i in page \b p */
685 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
687 /** Address of the key for the node */
688 #define NODEKEY(node) (void *)((node)->mn_data)
690 /** Address of the data for a node */
691 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
693 /** Get the page number pointed to by a branch node */
694 #define NODEPGNO(node) \
695 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
696 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
697 /** Set the page number in a branch node */
698 #define SETPGNO(node,pgno) do { \
699 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
700 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
702 /** Get the size of the data in a leaf node */
703 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
704 /** Set the size of the data for a leaf node */
705 #define SETDSZ(node,size) do { \
706 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
707 /** The size of a key in a node */
708 #define NODEKSZ(node) ((node)->mn_ksize)
710 /** Copy a page number from src to dst */
712 #define COPY_PGNO(dst,src) dst = src
714 #if SIZE_MAX > 4294967295UL
715 #define COPY_PGNO(dst,src) do { \
716 unsigned short *s, *d; \
717 s = (unsigned short *)&(src); \
718 d = (unsigned short *)&(dst); \
725 #define COPY_PGNO(dst,src) do { \
726 unsigned short *s, *d; \
727 s = (unsigned short *)&(src); \
728 d = (unsigned short *)&(dst); \
734 /** The address of a key in a LEAF2 page.
735 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
736 * There are no node headers, keys are stored contiguously.
738 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
740 /** Set the \b node's key into \b key, if requested. */
741 #define MDB_GET_KEY(node, key) { if ((key) != NULL) { \
742 (key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node); } }
744 /** Information about a single database in the environment. */
745 typedef struct MDB_db {
746 uint32_t md_pad; /**< also ksize for LEAF2 pages */
747 uint16_t md_flags; /**< @ref mdb_dbi_open */
748 uint16_t md_depth; /**< depth of this tree */
749 pgno_t md_branch_pages; /**< number of internal pages */
750 pgno_t md_leaf_pages; /**< number of leaf pages */
751 pgno_t md_overflow_pages; /**< number of overflow pages */
752 size_t md_entries; /**< number of data items */
753 pgno_t md_root; /**< the root page of this tree */
756 /** mdb_dbi_open flags */
757 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
758 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
759 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
760 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
762 /** Handle for the DB used to track free pages. */
764 /** Handle for the default DB. */
767 /** Meta page content. */
768 typedef struct MDB_meta {
769 /** Stamp identifying this as an MDB file. It must be set
772 /** Version number of this lock file. Must be set to #MDB_VERSION. */
774 void *mm_address; /**< address for fixed mapping */
775 size_t mm_mapsize; /**< size of mmap region */
776 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
777 /** The size of pages used in this DB */
778 #define mm_psize mm_dbs[0].md_pad
779 /** Any persistent environment flags. @ref mdb_env */
780 #define mm_flags mm_dbs[0].md_flags
781 pgno_t mm_last_pg; /**< last used page in file */
782 txnid_t mm_txnid; /**< txnid that committed this page */
785 /** Buffer for a stack-allocated dirty page.
786 * The members define size and alignment, and silence type
787 * aliasing warnings. They are not used directly; that could
788 * mean incorrectly using several union members in parallel.
790 typedef union MDB_pagebuf {
791 char mb_raw[MDB_PAGESIZE];
794 char mm_pad[PAGEHDRSZ];
799 /** Auxiliary DB info.
800 * The information here is mostly static/read-only. There is
801 * only a single copy of this record in the environment.
803 typedef struct MDB_dbx {
804 MDB_val md_name; /**< name of the database */
805 MDB_cmp_func *md_cmp; /**< function for comparing keys */
806 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
807 MDB_rel_func *md_rel; /**< user relocate function */
808 void *md_relctx; /**< user-provided context for md_rel */
811 /** A database transaction.
812 * Every operation requires a transaction handle.
815 MDB_txn *mt_parent; /**< parent of a nested txn */
816 MDB_txn *mt_child; /**< nested txn under this txn */
817 pgno_t mt_next_pgno; /**< next unallocated page */
818 /** The ID of this transaction. IDs are integers incrementing from 1.
819 * Only committed write transactions increment the ID. If a transaction
820 * aborts, the ID may be re-used by the next writer.
823 MDB_env *mt_env; /**< the DB environment */
824 /** The list of pages that became unused during this transaction.
828 MDB_ID2L dirty_list; /**< for write txns: modified pages */
829 MDB_reader *reader; /**< this thread's reader table slot or NULL */
831 /** Array of records for each DB known in the environment. */
833 /** Array of MDB_db records for each known DB */
835 /** @defgroup mt_dbflag Transaction DB Flags
839 #define DB_DIRTY 0x01 /**< DB was written in this txn */
840 #define DB_STALE 0x02 /**< DB record is older than txnID */
841 #define DB_NEW 0x04 /**< DB handle opened in this txn */
842 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
844 /** In write txns, array of cursors for each DB */
845 MDB_cursor **mt_cursors;
846 /** Array of flags for each DB */
847 unsigned char *mt_dbflags;
848 /** Number of DB records in use. This number only ever increments;
849 * we don't decrement it when individual DB handles are closed.
853 /** @defgroup mdb_txn Transaction Flags
857 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
858 #define MDB_TXN_ERROR 0x02 /**< an error has occurred */
859 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
861 unsigned int mt_flags; /**< @ref mdb_txn */
862 /** dirty_list maxsize - # of allocated pages allowed, including in parent txns */
863 unsigned int mt_dirty_room;
864 /** Tracks which of the two meta pages was used at the start
865 * of this transaction.
867 unsigned int mt_toggle;
870 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
871 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
872 * raise this on a 64 bit machine.
874 #define CURSOR_STACK 32
878 /** Cursors are used for all DB operations */
880 /** Next cursor on this DB in this txn */
882 /** Backup of the original cursor if this cursor is a shadow */
883 MDB_cursor *mc_backup;
884 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
885 struct MDB_xcursor *mc_xcursor;
886 /** The transaction that owns this cursor */
888 /** The database handle this cursor operates on */
890 /** The database record for this cursor */
892 /** The database auxiliary record for this cursor */
894 /** The @ref mt_dbflag for this database */
895 unsigned char *mc_dbflag;
896 unsigned short mc_snum; /**< number of pushed pages */
897 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
898 /** @defgroup mdb_cursor Cursor Flags
900 * Cursor state flags.
903 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
904 #define C_EOF 0x02 /**< No more data */
905 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
906 #define C_SPLITTING 0x20 /**< Cursor is in page_split */
907 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
909 unsigned int mc_flags; /**< @ref mdb_cursor */
910 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
911 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
914 /** Context for sorted-dup records.
915 * We could have gone to a fully recursive design, with arbitrarily
916 * deep nesting of sub-databases. But for now we only handle these
917 * levels - main DB, optional sub-DB, sorted-duplicate DB.
919 typedef struct MDB_xcursor {
920 /** A sub-cursor for traversing the Dup DB */
921 MDB_cursor mx_cursor;
922 /** The database record for this Dup DB */
924 /** The auxiliary DB record for this Dup DB */
926 /** The @ref mt_dbflag for this Dup DB */
927 unsigned char mx_dbflag;
930 /** State of FreeDB old pages, stored in the MDB_env */
931 typedef struct MDB_pgstate {
932 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
933 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
936 /** The database environment. */
938 HANDLE me_fd; /**< The main data file */
939 HANDLE me_lfd; /**< The lock file */
940 HANDLE me_mfd; /**< just for writing the meta pages */
941 /** Failed to update the meta page. Probably an I/O error. */
942 #define MDB_FATAL_ERROR 0x80000000U
943 /** Some fields are initialized. */
944 #define MDB_ENV_ACTIVE 0x20000000U
945 /** me_txkey is set */
946 #define MDB_ENV_TXKEY 0x10000000U
947 uint32_t me_flags; /**< @ref mdb_env */
948 unsigned int me_psize; /**< size of a page, from #GET_PAGESIZE */
949 unsigned int me_maxreaders; /**< size of the reader table */
950 unsigned int me_numreaders; /**< max numreaders set by this env */
951 MDB_dbi me_numdbs; /**< number of DBs opened */
952 MDB_dbi me_maxdbs; /**< size of the DB table */
953 pid_t me_pid; /**< process ID of this env */
954 char *me_path; /**< path to the DB files */
955 char *me_map; /**< the memory map of the data file */
956 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
957 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
958 MDB_txn *me_txn; /**< current write transaction */
959 size_t me_mapsize; /**< size of the data memory map */
960 off_t me_size; /**< current file size */
961 pgno_t me_maxpg; /**< me_mapsize / me_psize */
962 MDB_dbx *me_dbxs; /**< array of static DB info */
963 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
964 pthread_key_t me_txkey; /**< thread-key for readers */
965 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
966 # define me_pglast me_pgstate.mf_pglast
967 # define me_pghead me_pgstate.mf_pghead
968 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
969 /** IDL of pages that became unused in a write txn */
971 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
972 MDB_ID2L me_dirty_list;
973 /** Max number of freelist items that can fit in a single overflow page */
975 /** Max size of a node on a page */
976 unsigned int me_nodemax;
978 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
980 #elif defined(MDB_USE_POSIX_SEM)
981 sem_t *me_rmutex; /* Shared mutexes are not supported */
986 /** Nested transaction */
987 typedef struct MDB_ntxn {
988 MDB_txn mnt_txn; /* the transaction */
989 MDB_pgstate mnt_pgstate; /* parent transaction's saved freestate */
992 /** max number of pages to commit in one writev() call */
993 #define MDB_COMMIT_PAGES 64
994 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
995 #undef MDB_COMMIT_PAGES
996 #define MDB_COMMIT_PAGES IOV_MAX
999 /* max bytes to write in one call */
1000 #define MAX_WRITE (0x80000000U >> (sizeof(ssize_t) == 4))
1002 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1003 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1004 static int mdb_page_touch(MDB_cursor *mc);
1006 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp, int *lvl);
1007 static int mdb_page_search_root(MDB_cursor *mc,
1008 MDB_val *key, int modify);
1009 #define MDB_PS_MODIFY 1
1010 #define MDB_PS_ROOTONLY 2
1011 static int mdb_page_search(MDB_cursor *mc,
1012 MDB_val *key, int flags);
1013 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1015 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1016 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1017 pgno_t newpgno, unsigned int nflags);
1019 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1020 static int mdb_env_pick_meta(const MDB_env *env);
1021 static int mdb_env_write_meta(MDB_txn *txn);
1022 #if !(defined(_WIN32) || defined(MDB_USE_POSIX_SEM)) /* Drop unused excl arg */
1023 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1025 static void mdb_env_close0(MDB_env *env, int excl);
1027 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1028 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1029 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1030 static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
1031 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1032 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
1033 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1034 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1035 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1037 static int mdb_rebalance(MDB_cursor *mc);
1038 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1040 static void mdb_cursor_pop(MDB_cursor *mc);
1041 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1043 static int mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
1044 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1045 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1046 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1047 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1049 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1050 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1052 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1053 static void mdb_xcursor_init0(MDB_cursor *mc);
1054 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1056 static int mdb_drop0(MDB_cursor *mc, int subs);
1057 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1060 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1064 static SECURITY_DESCRIPTOR mdb_null_sd;
1065 static SECURITY_ATTRIBUTES mdb_all_sa;
1066 static int mdb_sec_inited;
1069 /** Return the library version info. */
1071 mdb_version(int *major, int *minor, int *patch)
1073 if (major) *major = MDB_VERSION_MAJOR;
1074 if (minor) *minor = MDB_VERSION_MINOR;
1075 if (patch) *patch = MDB_VERSION_PATCH;
1076 return MDB_VERSION_STRING;
1079 /** Table of descriptions for MDB @ref errors */
1080 static char *const mdb_errstr[] = {
1081 "MDB_KEYEXIST: Key/data pair already exists",
1082 "MDB_NOTFOUND: No matching key/data pair found",
1083 "MDB_PAGE_NOTFOUND: Requested page not found",
1084 "MDB_CORRUPTED: Located page was wrong type",
1085 "MDB_PANIC: Update of meta page failed",
1086 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1087 "MDB_INVALID: File is not an MDB file",
1088 "MDB_MAP_FULL: Environment mapsize limit reached",
1089 "MDB_DBS_FULL: Environment maxdbs limit reached",
1090 "MDB_READERS_FULL: Environment maxreaders limit reached",
1091 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1092 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1093 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1094 "MDB_PAGE_FULL: Internal error - page has no more space",
1095 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1096 "MDB_INCOMPATIBLE: Database flags changed or would change",
1097 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1101 mdb_strerror(int err)
1105 return ("Successful return: 0");
1107 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1108 i = err - MDB_KEYEXIST;
1109 return mdb_errstr[i];
1112 return strerror(err);
1116 /** Display a key in hexadecimal and return the address of the result.
1117 * @param[in] key the key to display
1118 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1119 * @return The key in hexadecimal form.
1122 mdb_dkey(MDB_val *key, char *buf)
1125 unsigned char *c = key->mv_data;
1131 if (key->mv_size > MDB_MAXKEYSIZE)
1132 return "MDB_MAXKEYSIZE";
1133 /* may want to make this a dynamic check: if the key is mostly
1134 * printable characters, print it as-is instead of converting to hex.
1138 for (i=0; i<key->mv_size; i++)
1139 ptr += sprintf(ptr, "%02x", *c++);
1141 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1146 /** Display all the keys in the page. */
1148 mdb_page_list(MDB_page *mp)
1151 unsigned int i, nkeys, nsize;
1155 nkeys = NUMKEYS(mp);
1156 fprintf(stderr, "Page %zu numkeys %d\n", mp->mp_pgno, nkeys);
1157 for (i=0; i<nkeys; i++) {
1158 node = NODEPTR(mp, i);
1159 key.mv_size = node->mn_ksize;
1160 key.mv_data = node->mn_data;
1161 nsize = NODESIZE + NODEKSZ(node) + sizeof(indx_t);
1162 if (IS_BRANCH(mp)) {
1163 fprintf(stderr, "key %d: page %zu, %s\n", i, NODEPGNO(node),
1166 if (F_ISSET(node->mn_flags, F_BIGDATA))
1167 nsize += sizeof(pgno_t);
1169 nsize += NODEDSZ(node);
1170 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1176 mdb_cursor_chk(MDB_cursor *mc)
1182 if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1183 for (i=0; i<mc->mc_top; i++) {
1185 node = NODEPTR(mp, mc->mc_ki[i]);
1186 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1189 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1195 /** Count all the pages in each DB and in the freelist
1196 * and make sure it matches the actual number of pages
1199 static void mdb_audit(MDB_txn *txn)
1203 MDB_ID freecount, count;
1208 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1209 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1210 freecount += *(MDB_ID *)data.mv_data;
1213 for (i = 0; i<txn->mt_numdbs; i++) {
1215 mdb_cursor_init(&mc, txn, i, &mx);
1216 if (txn->mt_dbs[i].md_root == P_INVALID)
1218 count += txn->mt_dbs[i].md_branch_pages +
1219 txn->mt_dbs[i].md_leaf_pages +
1220 txn->mt_dbs[i].md_overflow_pages;
1221 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1222 mdb_page_search(&mc, NULL, 0);
1226 mp = mc.mc_pg[mc.mc_top];
1227 for (j=0; j<NUMKEYS(mp); j++) {
1228 MDB_node *leaf = NODEPTR(mp, j);
1229 if (leaf->mn_flags & F_SUBDATA) {
1231 memcpy(&db, NODEDATA(leaf), sizeof(db));
1232 count += db.md_branch_pages + db.md_leaf_pages +
1233 db.md_overflow_pages;
1237 while (mdb_cursor_sibling(&mc, 1) == 0);
1240 if (freecount + count + 2 /* metapages */ != txn->mt_next_pgno) {
1241 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1242 txn->mt_txnid, freecount, count+2, freecount+count+2, txn->mt_next_pgno);
1248 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1250 return txn->mt_dbxs[dbi].md_cmp(a, b);
1254 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1256 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1259 /** Allocate a page.
1260 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1263 mdb_page_malloc(MDB_txn *txn, unsigned num)
1265 MDB_env *env = txn->mt_env;
1266 MDB_page *ret = env->me_dpages;
1267 size_t sz = env->me_psize;
1270 VGMEMP_ALLOC(env, ret, sz);
1271 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1272 env->me_dpages = ret->mp_next;
1278 if ((ret = malloc(sz)) != NULL) {
1279 VGMEMP_ALLOC(env, ret, sz);
1284 /** Free a single page.
1285 * Saves single pages to a list, for future reuse.
1286 * (This is not used for multi-page overflow pages.)
1289 mdb_page_free(MDB_env *env, MDB_page *mp)
1291 mp->mp_next = env->me_dpages;
1292 VGMEMP_FREE(env, mp);
1293 env->me_dpages = mp;
1296 /* Free a dirty page */
1298 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1300 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1301 mdb_page_free(env, dp);
1303 /* large pages just get freed directly */
1304 VGMEMP_FREE(env, dp);
1309 /* Return all dirty pages to dpage list */
1311 mdb_dlist_free(MDB_txn *txn)
1313 MDB_env *env = txn->mt_env;
1314 MDB_ID2L dl = txn->mt_u.dirty_list;
1315 unsigned i, n = dl[0].mid;
1317 for (i = 1; i <= n; i++) {
1318 mdb_dpage_free(env, dl[i].mptr);
1323 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
1325 mdb_find_oldest(MDB_txn *txn)
1328 txnid_t mr, oldest = txn->mt_txnid - 1;
1329 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
1330 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
1340 /** Add a page to the txn's dirty list */
1342 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
1345 int (*insert)(MDB_ID2L, MDB_ID2 *);
1347 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1348 insert = mdb_mid2l_append;
1350 insert = mdb_mid2l_insert;
1352 mid.mid = mp->mp_pgno;
1354 insert(txn->mt_u.dirty_list, &mid);
1355 txn->mt_dirty_room--;
1358 /** Allocate pages for writing.
1359 * If there are free pages available from older transactions, they
1360 * will be re-used first. Otherwise a new page will be allocated.
1361 * @param[in] mc cursor A cursor handle identifying the transaction and
1362 * database for which we are allocating.
1363 * @param[in] num the number of pages to allocate.
1364 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
1365 * will always be satisfied by a single contiguous chunk of memory.
1366 * @return 0 on success, non-zero on failure.
1369 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
1371 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
1372 /* Get at most <Max_retries> more freeDB records once me_pghead
1373 * has enough pages. If not enough, use new pages from the map.
1374 * If <Paranoid> and mc is updating the freeDB, only get new
1375 * records if me_pghead is empty. Then the freelist cannot play
1376 * catch-up with itself by growing while trying to save it.
1378 enum { Paranoid = 1, Max_retries = 500 };
1380 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
1382 int rc, n2 = num-1, retry = Max_retries;
1383 MDB_txn *txn = mc->mc_txn;
1384 MDB_env *env = txn->mt_env;
1385 pgno_t pgno, *mop = env->me_pghead;
1386 unsigned i, j, k, mop_len = mop ? mop[0] : 0;
1388 txnid_t oldest = 0, last;
1394 /* If our dirty list is already full, we can't do anything */
1395 if (txn->mt_dirty_room == 0)
1396 return MDB_TXN_FULL;
1398 for (op = MDB_FIRST;; op = MDB_NEXT) {
1401 pgno_t *idl, old_id, new_id;
1403 /* Seek a big enough contiguous page range. Prefer
1404 * pages at the tail, just truncating the list.
1406 if (mop_len >= (unsigned)num) {
1410 if (mop[i-n2] == pgno+n2)
1412 } while (--i >= (unsigned)num);
1413 if (Max_retries < INT_MAX && --retry < 0)
1417 if (op == MDB_FIRST) { /* 1st iteration */
1418 /* Prepare to fetch more and coalesce */
1419 oldest = mdb_find_oldest(txn);
1420 last = env->me_pglast;
1421 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1424 key.mv_data = &last; /* will loop up last+1 */
1425 key.mv_size = sizeof(last);
1427 if (Paranoid && mc->mc_dbi == FREE_DBI)
1430 if (Paranoid && retry < 0 && mop_len)
1434 /* Do not fetch more if the record will be too recent */
1437 rc = mdb_cursor_get(&m2, &key, NULL, op);
1439 if (rc == MDB_NOTFOUND)
1443 last = *(txnid_t*)key.mv_data;
1446 np = m2.mc_pg[m2.mc_top];
1447 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
1448 if ((rc = mdb_node_read(txn, leaf, &data)) != MDB_SUCCESS)
1451 idl = (MDB_ID *) data.mv_data;
1454 if (!(env->me_pghead = mop = mdb_midl_alloc(i)))
1457 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
1459 mop = env->me_pghead;
1461 env->me_pglast = last;
1463 DPRINTF("IDL read txn %zu root %zu num %u",
1464 last, txn->mt_dbs[FREE_DBI].md_root, i);
1466 DPRINTF("IDL %zu", idl[k]);
1468 /* Merge in descending sorted order */
1471 mop[0] = (pgno_t)-1;
1475 for (; old_id < new_id; old_id = mop[--j])
1482 /* Use new pages from the map when nothing suitable in the freeDB */
1484 pgno = txn->mt_next_pgno;
1485 if (pgno + num >= env->me_maxpg) {
1486 DPUTS("DB size maxed out");
1487 return MDB_MAP_FULL;
1491 if (env->me_flags & MDB_WRITEMAP) {
1492 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
1494 if (!(np = mdb_page_malloc(txn, num)))
1498 mop[0] = mop_len -= num;
1499 /* Move any stragglers down */
1500 for (j = i-num; j < mop_len; )
1501 mop[++j] = mop[++i];
1503 txn->mt_next_pgno = pgno + num;
1506 mdb_page_dirty(txn, np);
1512 /** Copy the used portions of a non-overflow page.
1513 * @param[in] dst page to copy into
1514 * @param[in] src page to copy from
1515 * @param[in] psize size of a page
1518 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
1520 enum { Align = sizeof(pgno_t) };
1521 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
1523 /* If page isn't full, just copy the used portion. Adjust
1524 * alignment so memcpy may copy words instead of bytes.
1526 if ((unused &= -Align) && !IS_LEAF2(src)) {
1528 memcpy(dst, src, (lower + (Align-1)) & -Align);
1529 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
1532 memcpy(dst, src, psize - unused);
1536 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1537 * @param[in] mc cursor pointing to the page to be touched
1538 * @return 0 on success, non-zero on failure.
1541 mdb_page_touch(MDB_cursor *mc)
1543 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
1544 MDB_txn *txn = mc->mc_txn;
1545 MDB_cursor *m2, *m3;
1550 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1551 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
1552 (rc = mdb_page_alloc(mc, 1, &np)))
1555 DPRINTF("touched db %u page %zu -> %zu", mc->mc_dbi,mp->mp_pgno,pgno);
1556 assert(mp->mp_pgno != pgno);
1557 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
1558 /* Update the parent page, if any, to point to the new page */
1560 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
1561 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
1562 SETPGNO(node, pgno);
1564 mc->mc_db->md_root = pgno;
1566 } else if (txn->mt_parent && !IS_SUBP(mp)) {
1567 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
1569 /* If txn has a parent, make sure the page is in our
1573 unsigned x = mdb_mid2l_search(dl, pgno);
1574 if (x <= dl[0].mid && dl[x].mid == pgno) {
1575 if (mp != dl[x].mptr) { /* bad cursor? */
1576 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1577 return MDB_CORRUPTED;
1582 assert(dl[0].mid < MDB_IDL_UM_MAX);
1584 np = mdb_page_malloc(txn, 1);
1589 mdb_mid2l_insert(dl, &mid);
1594 mdb_page_copy(np, mp, txn->mt_env->me_psize);
1596 np->mp_flags |= P_DIRTY;
1598 /* Adjust cursors pointing to mp */
1599 mc->mc_pg[mc->mc_top] = np;
1601 if (mc->mc_flags & C_SUB) {
1603 for (m2 = txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
1604 m3 = &m2->mc_xcursor->mx_cursor;
1605 if (m3->mc_snum < mc->mc_snum) continue;
1606 if (m3->mc_pg[mc->mc_top] == mp)
1607 m3->mc_pg[mc->mc_top] = np;
1610 for (m2 = txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
1611 if (m2->mc_snum < mc->mc_snum) continue;
1612 if (m2->mc_pg[mc->mc_top] == mp) {
1613 m2->mc_pg[mc->mc_top] = np;
1614 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
1615 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
1617 MDB_node *leaf = NODEPTR(np, mc->mc_ki[mc->mc_top]);
1618 if (!(leaf->mn_flags & F_SUBDATA))
1619 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
1628 mdb_env_sync(MDB_env *env, int force)
1631 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1632 if (env->me_flags & MDB_WRITEMAP) {
1633 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
1634 ? MS_ASYNC : MS_SYNC;
1635 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
1638 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
1642 if (MDB_FDATASYNC(env->me_fd))
1649 /** Back up parent txn's cursors, then grab the originals for tracking */
1651 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
1653 MDB_cursor *mc, *bk;
1658 for (i = src->mt_numdbs; --i >= 0; ) {
1659 if ((mc = src->mt_cursors[i]) != NULL) {
1660 size = sizeof(MDB_cursor);
1662 size += sizeof(MDB_xcursor);
1663 for (; mc; mc = bk->mc_next) {
1669 mc->mc_db = &dst->mt_dbs[i];
1670 /* Kill pointers into src - and dst to reduce abuse: The
1671 * user may not use mc until dst ends. Otherwise we'd...
1673 mc->mc_txn = NULL; /* ...set this to dst */
1674 mc->mc_dbflag = NULL; /* ...and &dst->mt_dbflags[i] */
1675 if ((mx = mc->mc_xcursor) != NULL) {
1676 *(MDB_xcursor *)(bk+1) = *mx;
1677 mx->mx_cursor.mc_txn = NULL; /* ...and dst. */
1679 mc->mc_next = dst->mt_cursors[i];
1680 dst->mt_cursors[i] = mc;
1687 /** Close this write txn's cursors, give parent txn's cursors back to parent.
1688 * @param[in] txn the transaction handle.
1689 * @param[in] merge true to keep changes to parent cursors, false to revert.
1690 * @return 0 on success, non-zero on failure.
1693 mdb_cursors_close(MDB_txn *txn, unsigned merge)
1695 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
1699 for (i = txn->mt_numdbs; --i >= 0; ) {
1700 for (mc = cursors[i]; mc; mc = next) {
1702 if ((bk = mc->mc_backup) != NULL) {
1704 /* Commit changes to parent txn */
1705 mc->mc_next = bk->mc_next;
1706 mc->mc_backup = bk->mc_backup;
1707 mc->mc_txn = bk->mc_txn;
1708 mc->mc_db = bk->mc_db;
1709 mc->mc_dbflag = bk->mc_dbflag;
1710 if ((mx = mc->mc_xcursor) != NULL)
1711 mx->mx_cursor.mc_txn = bk->mc_txn;
1713 /* Abort nested txn */
1715 if ((mx = mc->mc_xcursor) != NULL)
1716 *mx = *(MDB_xcursor *)(bk+1);
1726 #ifdef MDB_DEBUG_SKIP
1727 #define mdb_txn_reset0(txn, act) mdb_txn_reset0(txn)
1730 mdb_txn_reset0(MDB_txn *txn, const char *act);
1732 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
1733 * @param[in] txn the transaction handle to initialize
1734 * @return 0 on success, non-zero on failure.
1737 mdb_txn_renew0(MDB_txn *txn)
1739 MDB_env *env = txn->mt_env;
1742 int rc, new_notls = 0;
1745 txn->mt_numdbs = env->me_numdbs;
1746 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
1748 if (txn->mt_flags & MDB_TXN_RDONLY) {
1749 if (!env->me_txns) {
1750 i = mdb_env_pick_meta(env);
1751 txn->mt_txnid = env->me_metas[i]->mm_txnid;
1752 txn->mt_u.reader = NULL;
1754 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
1755 pthread_getspecific(env->me_txkey);
1757 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
1758 return MDB_BAD_RSLOT;
1760 pid_t pid = env->me_pid;
1761 pthread_t tid = pthread_self();
1764 for (i=0; i<env->me_txns->mti_numreaders; i++)
1765 if (env->me_txns->mti_readers[i].mr_pid == 0)
1767 if (i == env->me_maxreaders) {
1768 UNLOCK_MUTEX_R(env);
1769 return MDB_READERS_FULL;
1771 env->me_txns->mti_readers[i].mr_pid = pid;
1772 env->me_txns->mti_readers[i].mr_tid = tid;
1773 if (i >= env->me_txns->mti_numreaders)
1774 env->me_txns->mti_numreaders = i+1;
1775 /* Save numreaders for un-mutexed mdb_env_close() */
1776 env->me_numreaders = env->me_txns->mti_numreaders;
1777 UNLOCK_MUTEX_R(env);
1778 r = &env->me_txns->mti_readers[i];
1779 new_notls = (env->me_flags & MDB_NOTLS);
1780 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
1785 txn->mt_txnid = r->mr_txnid = env->me_txns->mti_txnid;
1786 txn->mt_u.reader = r;
1788 txn->mt_toggle = txn->mt_txnid & 1;
1792 txn->mt_txnid = env->me_txns->mti_txnid;
1793 txn->mt_toggle = txn->mt_txnid & 1;
1796 if (txn->mt_txnid == mdb_debug_start)
1799 txn->mt_dirty_room = MDB_IDL_UM_MAX;
1800 txn->mt_u.dirty_list = env->me_dirty_list;
1801 txn->mt_u.dirty_list[0].mid = 0;
1802 txn->mt_free_pgs = env->me_free_pgs;
1803 txn->mt_free_pgs[0] = 0;
1807 /* Copy the DB info and flags */
1808 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
1810 /* Moved to here to avoid a data race in read TXNs */
1811 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1813 for (i=2; i<txn->mt_numdbs; i++) {
1814 x = env->me_dbflags[i];
1815 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
1816 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_STALE : 0;
1818 txn->mt_dbflags[0] = txn->mt_dbflags[1] = DB_VALID;
1820 if (env->me_maxpg < txn->mt_next_pgno) {
1821 mdb_txn_reset0(txn, "renew0-mapfail");
1823 txn->mt_u.reader->mr_pid = 0;
1824 txn->mt_u.reader = NULL;
1826 return MDB_MAP_RESIZED;
1833 mdb_txn_renew(MDB_txn *txn)
1837 if (!txn || txn->mt_dbxs) /* A reset txn has mt_dbxs==NULL */
1840 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
1841 DPUTS("environment had fatal error, must shutdown!");
1845 rc = mdb_txn_renew0(txn);
1846 if (rc == MDB_SUCCESS) {
1847 DPRINTF("renew txn %zu%c %p on mdbenv %p, root page %zu",
1848 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1849 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1855 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
1859 int rc, size, tsize = sizeof(MDB_txn);
1861 if (env->me_flags & MDB_FATAL_ERROR) {
1862 DPUTS("environment had fatal error, must shutdown!");
1865 if ((env->me_flags & MDB_RDONLY) && !(flags & MDB_RDONLY))
1868 /* Nested transactions: Max 1 child, write txns only, no writemap */
1869 if (parent->mt_child ||
1870 (flags & MDB_RDONLY) || (parent->mt_flags & MDB_TXN_RDONLY) ||
1871 (env->me_flags & MDB_WRITEMAP))
1875 tsize = sizeof(MDB_ntxn);
1877 size = tsize + env->me_maxdbs * (sizeof(MDB_db)+1);
1878 if (!(flags & MDB_RDONLY))
1879 size += env->me_maxdbs * sizeof(MDB_cursor *);
1881 if ((txn = calloc(1, size)) == NULL) {
1882 DPRINTF("calloc: %s", strerror(ErrCode()));
1885 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
1886 if (flags & MDB_RDONLY) {
1887 txn->mt_flags |= MDB_TXN_RDONLY;
1888 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
1890 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
1891 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
1897 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
1898 if (!txn->mt_u.dirty_list ||
1899 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
1901 free(txn->mt_u.dirty_list);
1905 txn->mt_txnid = parent->mt_txnid;
1906 txn->mt_toggle = parent->mt_toggle;
1907 txn->mt_dirty_room = parent->mt_dirty_room;
1908 txn->mt_u.dirty_list[0].mid = 0;
1909 txn->mt_next_pgno = parent->mt_next_pgno;
1910 parent->mt_child = txn;
1911 txn->mt_parent = parent;
1912 txn->mt_numdbs = parent->mt_numdbs;
1913 txn->mt_flags = parent->mt_flags;
1914 txn->mt_dbxs = parent->mt_dbxs;
1915 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
1916 /* Copy parent's mt_dbflags, but clear DB_NEW */
1917 for (i=0; i<txn->mt_numdbs; i++)
1918 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
1920 ntxn = (MDB_ntxn *)txn;
1921 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
1922 if (env->me_pghead) {
1923 size = MDB_IDL_SIZEOF(env->me_pghead);
1924 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
1926 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
1931 rc = mdb_cursor_shadow(parent, txn);
1933 mdb_txn_reset0(txn, "beginchild-fail");
1935 rc = mdb_txn_renew0(txn);
1941 DPRINTF("begin txn %zu%c %p on mdbenv %p, root page %zu",
1942 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1943 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
1949 /** Export or close DBI handles opened in this txn. */
1951 mdb_dbis_update(MDB_txn *txn, int keep)
1954 MDB_dbi n = txn->mt_numdbs;
1955 MDB_env *env = txn->mt_env;
1956 unsigned char *tdbflags = txn->mt_dbflags;
1958 for (i = n; --i >= 2;) {
1959 if (tdbflags[i] & DB_NEW) {
1961 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
1963 char *ptr = env->me_dbxs[i].md_name.mv_data;
1964 env->me_dbxs[i].md_name.mv_data = NULL;
1965 env->me_dbxs[i].md_name.mv_size = 0;
1966 env->me_dbflags[i] = 0;
1971 if (keep && env->me_numdbs < n)
1975 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
1976 * May be called twice for readonly txns: First reset it, then abort.
1977 * @param[in] txn the transaction handle to reset
1980 mdb_txn_reset0(MDB_txn *txn, const char *act)
1982 MDB_env *env = txn->mt_env;
1984 /* Close any DBI handles opened in this txn */
1985 mdb_dbis_update(txn, 0);
1987 DPRINTF("%s txn %zu%c %p on mdbenv %p, root page %zu",
1988 act, txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1989 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
1991 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1992 if (txn->mt_u.reader) {
1993 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
1994 if (!(env->me_flags & MDB_NOTLS))
1995 txn->mt_u.reader = NULL; /* txn does not own reader */
1997 txn->mt_numdbs = 0; /* close nothing if called again */
1998 txn->mt_dbxs = NULL; /* mark txn as reset */
2000 mdb_cursors_close(txn, 0);
2002 if (!(env->me_flags & MDB_WRITEMAP)) {
2003 mdb_dlist_free(txn);
2005 mdb_midl_free(env->me_pghead);
2007 if (txn->mt_parent) {
2008 txn->mt_parent->mt_child = NULL;
2009 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2010 mdb_midl_free(txn->mt_free_pgs);
2011 free(txn->mt_u.dirty_list);
2015 if (mdb_midl_shrink(&txn->mt_free_pgs))
2016 env->me_free_pgs = txn->mt_free_pgs;
2017 env->me_pghead = NULL;
2021 /* The writer mutex was locked in mdb_txn_begin. */
2022 UNLOCK_MUTEX_W(env);
2027 mdb_txn_reset(MDB_txn *txn)
2032 /* This call is only valid for read-only txns */
2033 if (!(txn->mt_flags & MDB_TXN_RDONLY))
2036 mdb_txn_reset0(txn, "reset");
2040 mdb_txn_abort(MDB_txn *txn)
2046 mdb_txn_abort(txn->mt_child);
2048 mdb_txn_reset0(txn, "abort");
2049 /* Free reader slot tied to this txn (if MDB_NOTLS && writable FS) */
2050 if ((txn->mt_flags & MDB_TXN_RDONLY) && txn->mt_u.reader)
2051 txn->mt_u.reader->mr_pid = 0;
2056 /** Save the freelist as of this transaction to the freeDB.
2057 * This changes the freelist. Keep trying until it stabilizes.
2060 mdb_freelist_save(MDB_txn *txn)
2062 /* env->me_pghead[] can grow and shrink during this call.
2063 * env->me_pglast and txn->mt_free_pgs[] can only grow.
2064 * Page numbers cannot disappear from txn->mt_free_pgs[].
2067 MDB_env *env = txn->mt_env;
2068 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
2069 txnid_t pglast = 0, head_id = 0;
2070 pgno_t freecnt = 0, *free_pgs, *mop;
2071 ssize_t head_room = 0, total_room = 0, mop_len;
2073 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
2075 if (env->me_pghead) {
2076 /* Make sure first page of freeDB is touched and on freelist */
2077 rc = mdb_page_search(&mc, NULL, MDB_PS_MODIFY);
2078 if (rc && rc != MDB_NOTFOUND)
2083 /* Come back here after each Put() in case freelist changed */
2086 /* If using records from freeDB which we have not yet
2087 * deleted, delete them and any we reserved for me_pghead.
2089 while (pglast < env->me_pglast) {
2090 rc = mdb_cursor_first(&mc, &key, NULL);
2093 pglast = head_id = *(txnid_t *)key.mv_data;
2094 total_room = head_room = 0;
2095 assert(pglast <= env->me_pglast);
2096 rc = mdb_cursor_del(&mc, 0);
2101 /* Save the IDL of pages freed by this txn, to a single record */
2102 if (freecnt < txn->mt_free_pgs[0]) {
2104 /* Make sure last page of freeDB is touched and on freelist */
2105 key.mv_size = MDB_MAXKEYSIZE+1;
2107 rc = mdb_page_search(&mc, &key, MDB_PS_MODIFY);
2108 if (rc && rc != MDB_NOTFOUND)
2111 free_pgs = txn->mt_free_pgs;
2112 /* Write to last page of freeDB */
2113 key.mv_size = sizeof(txn->mt_txnid);
2114 key.mv_data = &txn->mt_txnid;
2116 freecnt = free_pgs[0];
2117 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
2118 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2121 /* Retry if mt_free_pgs[] grew during the Put() */
2122 free_pgs = txn->mt_free_pgs;
2123 } while (freecnt < free_pgs[0]);
2124 mdb_midl_sort(free_pgs);
2125 memcpy(data.mv_data, free_pgs, data.mv_size);
2128 unsigned int i = free_pgs[0];
2129 DPRINTF("IDL write txn %zu root %zu num %u",
2130 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i);
2132 DPRINTF("IDL %zu", free_pgs[i]);
2138 mop = env->me_pghead;
2139 mop_len = mop ? mop[0] : 0;
2141 /* Reserve records for me_pghead[]. Split it if multi-page,
2142 * to avoid searching freeDB for a page range. Use keys in
2143 * range [1,me_pglast]: Smaller than txnid of oldest reader.
2145 if (total_room >= mop_len) {
2146 if (total_room == mop_len || --more < 0)
2148 } else if (head_room >= maxfree_1pg && head_id > 1) {
2149 /* Keep current record (overflow page), add a new one */
2153 /* (Re)write {key = head_id, IDL length = head_room} */
2154 total_room -= head_room;
2155 head_room = mop_len - total_room;
2156 if (head_room > maxfree_1pg && head_id > 1) {
2157 /* Overflow multi-page for part of me_pghead */
2158 head_room /= head_id; /* amortize page sizes */
2159 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
2160 } else if (head_room < 0) {
2161 /* Rare case, not bothering to delete this record */
2164 key.mv_size = sizeof(head_id);
2165 key.mv_data = &head_id;
2166 data.mv_size = (head_room + 1) * sizeof(pgno_t);
2167 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2170 *(MDB_ID *)data.mv_data = 0; /* IDL is initially empty */
2171 total_room += head_room;
2174 /* Fill in the reserved, touched me_pghead records */
2180 rc = mdb_cursor_first(&mc, &key, &data);
2181 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
2182 unsigned flags = MDB_CURRENT;
2183 txnid_t id = *(txnid_t *)key.mv_data;
2184 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
2187 assert(len >= 0 && id <= env->me_pglast);
2189 if (len > mop_len) {
2191 data.mv_size = (len + 1) * sizeof(MDB_ID);
2194 data.mv_data = mop -= len;
2197 rc = mdb_cursor_put(&mc, &key, &data, flags);
2199 if (rc || !(mop_len -= len))
2206 /** Flush dirty pages to the map, after clearing their dirty flag.
2209 mdb_page_flush(MDB_txn *txn)
2211 MDB_env *env = txn->mt_env;
2212 MDB_ID2L dl = txn->mt_u.dirty_list;
2213 unsigned psize = env->me_psize;
2214 int i, pagecount = dl[0].mid, rc;
2215 size_t size = 0, pos = 0;
2217 MDB_page *dp = NULL;
2221 struct iovec iov[MDB_COMMIT_PAGES];
2222 ssize_t wpos = 0, wsize = 0, wres;
2223 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
2227 if (env->me_flags & MDB_WRITEMAP) {
2228 /* Clear dirty flags */
2229 for (i = pagecount; i; i--) {
2231 dp->mp_flags &= ~P_DIRTY;
2237 /* Write the pages */
2239 if (i <= pagecount) {
2242 /* clear dirty flag */
2243 dp->mp_flags &= ~P_DIRTY;
2246 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
2251 /* Windows actually supports scatter/gather I/O, but only on
2252 * unbuffered file handles. Since we're relying on the OS page
2253 * cache for all our data, that's self-defeating. So we just
2254 * write pages one at a time. We use the ov structure to set
2255 * the write offset, to at least save the overhead of a Seek
2258 DPRINTF("committing page %zu", pgno);
2259 memset(&ov, 0, sizeof(ov));
2260 ov.Offset = pos & 0xffffffff;
2261 ov.OffsetHigh = pos >> 16 >> 16;
2262 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
2264 DPRINTF("WriteFile: %d", rc);
2268 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
2269 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
2271 /* Write previous page(s) */
2272 #ifdef MDB_USE_PWRITEV
2273 wres = pwritev(env->me_fd, iov, n, wpos);
2276 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
2278 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
2280 DPRINTF("lseek: %s", strerror(rc));
2283 wres = writev(env->me_fd, iov, n);
2286 if (wres != wsize) {
2289 DPRINTF("Write error: %s", strerror(rc));
2291 rc = EIO; /* TODO: Use which error code? */
2292 DPUTS("short write, filesystem full?");
2303 DPRINTF("committing page %zu", pgno);
2304 next_pos = pos + size;
2305 iov[n].iov_len = size;
2306 iov[n].iov_base = (char *)dp;
2312 mdb_dlist_free(txn);
2318 mdb_txn_commit(MDB_txn *txn)
2324 assert(txn != NULL);
2325 assert(txn->mt_env != NULL);
2327 if (txn->mt_child) {
2328 rc = mdb_txn_commit(txn->mt_child);
2329 txn->mt_child = NULL;
2336 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2337 mdb_dbis_update(txn, 1);
2338 txn->mt_numdbs = 2; /* so txn_abort() doesn't close any new handles */
2343 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
2344 DPUTS("error flag is set, can't commit");
2346 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
2351 if (txn->mt_parent) {
2352 MDB_txn *parent = txn->mt_parent;
2356 /* Append our free list to parent's */
2357 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
2360 mdb_midl_free(txn->mt_free_pgs);
2362 parent->mt_next_pgno = txn->mt_next_pgno;
2363 parent->mt_flags = txn->mt_flags;
2365 /* Merge our cursors into parent's and close them */
2366 mdb_cursors_close(txn, 1);
2368 /* Update parent's DB table. */
2369 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2370 parent->mt_numdbs = txn->mt_numdbs;
2371 parent->mt_dbflags[0] = txn->mt_dbflags[0];
2372 parent->mt_dbflags[1] = txn->mt_dbflags[1];
2373 for (i=2; i<txn->mt_numdbs; i++) {
2374 /* preserve parent's DB_NEW status */
2375 x = parent->mt_dbflags[i] & DB_NEW;
2376 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
2379 dst = parent->mt_u.dirty_list;
2380 src = txn->mt_u.dirty_list;
2381 /* Find len = length of merging our dirty list with parent's */
2383 dst[0].mid = 0; /* simplify loops */
2384 if (parent->mt_parent) {
2385 len = x + src[0].mid;
2386 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
2387 for (i = x; y && i; y--) {
2388 pgno_t yp = src[y].mid;
2389 while (yp < dst[i].mid)
2391 if (yp == dst[i].mid) {
2396 } else { /* Simplify the above for single-ancestor case */
2397 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
2399 /* Merge our dirty list with parent's */
2401 for (i = len; y; dst[i--] = src[y--]) {
2402 pgno_t yp = src[y].mid;
2403 while (yp < dst[x].mid)
2404 dst[i--] = dst[x--];
2405 if (yp == dst[x].mid)
2406 free(dst[x--].mptr);
2410 free(txn->mt_u.dirty_list);
2411 parent->mt_dirty_room = txn->mt_dirty_room;
2413 parent->mt_child = NULL;
2414 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
2419 if (txn != env->me_txn) {
2420 DPUTS("attempt to commit unknown transaction");
2425 mdb_cursors_close(txn, 0);
2427 if (!txn->mt_u.dirty_list[0].mid && !(txn->mt_flags & MDB_TXN_DIRTY))
2430 DPRINTF("committing txn %zu %p on mdbenv %p, root page %zu",
2431 txn->mt_txnid, (void *)txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
2433 /* Update DB root pointers */
2434 if (txn->mt_numdbs > 2) {
2438 data.mv_size = sizeof(MDB_db);
2440 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
2441 for (i = 2; i < txn->mt_numdbs; i++) {
2442 if (txn->mt_dbflags[i] & DB_DIRTY) {
2443 data.mv_data = &txn->mt_dbs[i];
2444 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
2451 rc = mdb_freelist_save(txn);
2455 mdb_midl_free(env->me_pghead);
2456 env->me_pghead = NULL;
2457 if (mdb_midl_shrink(&txn->mt_free_pgs))
2458 env->me_free_pgs = txn->mt_free_pgs;
2464 if ((rc = mdb_page_flush(txn)) ||
2465 (rc = mdb_env_sync(env, 0)) ||
2466 (rc = mdb_env_write_meta(txn)))
2472 mdb_dbis_update(txn, 1);
2474 UNLOCK_MUTEX_W(env);
2484 /** Read the environment parameters of a DB environment before
2485 * mapping it into memory.
2486 * @param[in] env the environment handle
2487 * @param[out] meta address of where to store the meta information
2488 * @return 0 on success, non-zero on failure.
2491 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
2498 /* We don't know the page size yet, so use a minimum value.
2499 * Read both meta pages so we can use the latest one.
2502 for (i=off=0; i<2; i++, off = meta->mm_psize) {
2506 memset(&ov, 0, sizeof(ov));
2508 rc = ReadFile(env->me_fd,&pbuf,MDB_PAGESIZE,&len,&ov) ? (int)len : -1;
2509 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
2512 rc = pread(env->me_fd, &pbuf, MDB_PAGESIZE, off);
2514 if (rc != MDB_PAGESIZE) {
2515 if (rc == 0 && off == 0)
2517 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
2518 DPRINTF("read: %s", mdb_strerror(rc));
2522 p = (MDB_page *)&pbuf;
2524 if (!F_ISSET(p->mp_flags, P_META)) {
2525 DPRINTF("page %zu not a meta page", p->mp_pgno);
2530 if (m->mm_magic != MDB_MAGIC) {
2531 DPUTS("meta has invalid magic");
2535 if (m->mm_version != MDB_VERSION) {
2536 DPRINTF("database is version %u, expected version %u",
2537 m->mm_version, MDB_VERSION);
2538 return MDB_VERSION_MISMATCH;
2541 if (off == 0 || m->mm_txnid > meta->mm_txnid)
2547 /** Write the environment parameters of a freshly created DB environment.
2548 * @param[in] env the environment handle
2549 * @param[out] meta address of where to store the meta information
2550 * @return 0 on success, non-zero on failure.
2553 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
2559 DPUTS("writing new meta page");
2561 GET_PAGESIZE(psize);
2563 meta->mm_magic = MDB_MAGIC;
2564 meta->mm_version = MDB_VERSION;
2565 meta->mm_mapsize = env->me_mapsize;
2566 meta->mm_psize = psize;
2567 meta->mm_last_pg = 1;
2568 meta->mm_flags = env->me_flags & 0xffff;
2569 meta->mm_flags |= MDB_INTEGERKEY;
2570 meta->mm_dbs[0].md_root = P_INVALID;
2571 meta->mm_dbs[1].md_root = P_INVALID;
2573 p = calloc(2, psize);
2575 p->mp_flags = P_META;
2576 *(MDB_meta *)METADATA(p) = *meta;
2578 q = (MDB_page *)((char *)p + psize);
2580 q->mp_flags = P_META;
2581 *(MDB_meta *)METADATA(q) = *meta;
2587 memset(&ov, 0, sizeof(ov));
2588 rc = WriteFile(env->me_fd, p, psize * 2, &len, &ov);
2589 rc = rc ? (len == psize * 2 ? MDB_SUCCESS : EIO) : ErrCode();
2592 rc = pwrite(env->me_fd, p, psize * 2, 0);
2593 rc = (rc == (int)psize * 2) ? MDB_SUCCESS : rc < 0 ? ErrCode() : EIO;
2599 /** Update the environment info to commit a transaction.
2600 * @param[in] txn the transaction that's being committed
2601 * @return 0 on success, non-zero on failure.
2604 mdb_env_write_meta(MDB_txn *txn)
2607 MDB_meta meta, metab, *mp;
2609 int rc, len, toggle;
2618 assert(txn != NULL);
2619 assert(txn->mt_env != NULL);
2621 toggle = !txn->mt_toggle;
2622 DPRINTF("writing meta page %d for root page %zu",
2623 toggle, txn->mt_dbs[MAIN_DBI].md_root);
2626 mp = env->me_metas[toggle];
2628 if (env->me_flags & MDB_WRITEMAP) {
2629 /* Persist any increases of mapsize config */
2630 if (env->me_mapsize > mp->mm_mapsize)
2631 mp->mm_mapsize = env->me_mapsize;
2632 mp->mm_dbs[0] = txn->mt_dbs[0];
2633 mp->mm_dbs[1] = txn->mt_dbs[1];
2634 mp->mm_last_pg = txn->mt_next_pgno - 1;
2635 mp->mm_txnid = txn->mt_txnid;
2636 if (!(env->me_flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
2637 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
2640 ptr += env->me_psize;
2641 if (MDB_MSYNC(ptr, env->me_psize, rc)) {
2648 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
2649 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
2651 ptr = (char *)&meta;
2652 if (env->me_mapsize > mp->mm_mapsize) {
2653 /* Persist any increases of mapsize config */
2654 meta.mm_mapsize = env->me_mapsize;
2655 off = offsetof(MDB_meta, mm_mapsize);
2657 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
2659 len = sizeof(MDB_meta) - off;
2662 meta.mm_dbs[0] = txn->mt_dbs[0];
2663 meta.mm_dbs[1] = txn->mt_dbs[1];
2664 meta.mm_last_pg = txn->mt_next_pgno - 1;
2665 meta.mm_txnid = txn->mt_txnid;
2668 off += env->me_psize;
2671 /* Write to the SYNC fd */
2672 mfd = env->me_flags & (MDB_NOSYNC|MDB_NOMETASYNC) ?
2673 env->me_fd : env->me_mfd;
2676 memset(&ov, 0, sizeof(ov));
2678 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
2682 rc = pwrite(mfd, ptr, len, off);
2685 rc = rc < 0 ? ErrCode() : EIO;
2686 DPUTS("write failed, disk error?");
2687 /* On a failure, the pagecache still contains the new data.
2688 * Write some old data back, to prevent it from being used.
2689 * Use the non-SYNC fd; we know it will fail anyway.
2691 meta.mm_last_pg = metab.mm_last_pg;
2692 meta.mm_txnid = metab.mm_txnid;
2694 memset(&ov, 0, sizeof(ov));
2696 WriteFile(env->me_fd, ptr, len, NULL, &ov);
2698 r2 = pwrite(env->me_fd, ptr, len, off);
2701 env->me_flags |= MDB_FATAL_ERROR;
2705 /* Memory ordering issues are irrelevant; since the entire writer
2706 * is wrapped by wmutex, all of these changes will become visible
2707 * after the wmutex is unlocked. Since the DB is multi-version,
2708 * readers will get consistent data regardless of how fresh or
2709 * how stale their view of these values is.
2711 env->me_txns->mti_txnid = txn->mt_txnid;
2716 /** Check both meta pages to see which one is newer.
2717 * @param[in] env the environment handle
2718 * @return meta toggle (0 or 1).
2721 mdb_env_pick_meta(const MDB_env *env)
2723 return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
2727 mdb_env_create(MDB_env **env)
2731 e = calloc(1, sizeof(MDB_env));
2735 e->me_maxreaders = DEFAULT_READERS;
2736 e->me_maxdbs = e->me_numdbs = 2;
2737 e->me_fd = INVALID_HANDLE_VALUE;
2738 e->me_lfd = INVALID_HANDLE_VALUE;
2739 e->me_mfd = INVALID_HANDLE_VALUE;
2740 #ifdef MDB_USE_POSIX_SEM
2741 e->me_rmutex = SEM_FAILED;
2742 e->me_wmutex = SEM_FAILED;
2744 e->me_pid = getpid();
2745 VGMEMP_CREATE(e,0,0);
2751 mdb_env_set_mapsize(MDB_env *env, size_t size)
2755 env->me_mapsize = size;
2757 env->me_maxpg = env->me_mapsize / env->me_psize;
2762 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
2766 env->me_maxdbs = dbs + 2; /* Named databases + main and free DB */
2771 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
2773 if (env->me_map || readers < 1)
2775 env->me_maxreaders = readers;
2780 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
2782 if (!env || !readers)
2784 *readers = env->me_maxreaders;
2788 /** Further setup required for opening an MDB environment
2791 mdb_env_open2(MDB_env *env)
2793 unsigned int flags = env->me_flags;
2801 memset(&meta, 0, sizeof(meta));
2803 if ((i = mdb_env_read_header(env, &meta)) != 0) {
2806 DPUTS("new mdbenv");
2810 /* Was a mapsize configured? */
2811 if (!env->me_mapsize) {
2812 /* If this is a new environment, take the default,
2813 * else use the size recorded in the existing env.
2815 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
2816 } else if (env->me_mapsize < meta.mm_mapsize) {
2817 /* If the configured size is smaller, make sure it's
2818 * still big enough. Silently round up to minimum if not.
2820 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
2821 if (env->me_mapsize < minsize)
2822 env->me_mapsize = minsize;
2829 LONG sizelo, sizehi;
2830 sizelo = env->me_mapsize & 0xffffffff;
2831 sizehi = env->me_mapsize >> 16 >> 16; /* only needed on Win64 */
2832 /* Windows won't create mappings for zero length files.
2833 * Just allocate the maxsize right now.
2836 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
2837 || !SetEndOfFile(env->me_fd)
2838 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
2841 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
2842 PAGE_READWRITE : PAGE_READONLY,
2843 sizehi, sizelo, NULL);
2846 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
2847 FILE_MAP_WRITE : FILE_MAP_READ,
2848 0, 0, env->me_mapsize, meta.mm_address);
2849 rc = env->me_map ? 0 : ErrCode();
2857 if (flags & MDB_WRITEMAP) {
2859 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
2862 env->me_map = mmap(meta.mm_address, env->me_mapsize, prot, i,
2864 if (env->me_map == MAP_FAILED) {
2868 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
2870 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
2872 #ifdef POSIX_MADV_RANDOM
2873 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
2874 #endif /* POSIX_MADV_RANDOM */
2875 #endif /* MADV_RANDOM */
2879 if (flags & MDB_FIXEDMAP)
2880 meta.mm_address = env->me_map;
2881 i = mdb_env_init_meta(env, &meta);
2882 if (i != MDB_SUCCESS) {
2885 } else if (meta.mm_address && env->me_map != meta.mm_address) {
2886 /* Can happen because the address argument to mmap() is just a
2887 * hint. mmap() can pick another, e.g. if the range is in use.
2888 * The MAP_FIXED flag would prevent that, but then mmap could
2889 * instead unmap existing pages to make room for the new map.
2891 return EBUSY; /* TODO: Make a new MDB_* error code? */
2893 env->me_psize = meta.mm_psize;
2894 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
2895 env->me_nodemax = (env->me_psize - PAGEHDRSZ) / MDB_MINKEYS;
2897 env->me_maxpg = env->me_mapsize / env->me_psize;
2899 p = (MDB_page *)env->me_map;
2900 env->me_metas[0] = METADATA(p);
2901 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
2905 int toggle = mdb_env_pick_meta(env);
2906 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
2908 DPRINTF("opened database version %u, pagesize %u",
2909 env->me_metas[0]->mm_version, env->me_psize);
2910 DPRINTF("using meta page %d", toggle);
2911 DPRINTF("depth: %u", db->md_depth);
2912 DPRINTF("entries: %zu", db->md_entries);
2913 DPRINTF("branch pages: %zu", db->md_branch_pages);
2914 DPRINTF("leaf pages: %zu", db->md_leaf_pages);
2915 DPRINTF("overflow pages: %zu", db->md_overflow_pages);
2916 DPRINTF("root: %zu", db->md_root);
2924 /** Release a reader thread's slot in the reader lock table.
2925 * This function is called automatically when a thread exits.
2926 * @param[in] ptr This points to the slot in the reader lock table.
2929 mdb_env_reader_dest(void *ptr)
2931 MDB_reader *reader = ptr;
2937 /** Junk for arranging thread-specific callbacks on Windows. This is
2938 * necessarily platform and compiler-specific. Windows supports up
2939 * to 1088 keys. Let's assume nobody opens more than 64 environments
2940 * in a single process, for now. They can override this if needed.
2942 #ifndef MAX_TLS_KEYS
2943 #define MAX_TLS_KEYS 64
2945 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
2946 static int mdb_tls_nkeys;
2948 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
2952 case DLL_PROCESS_ATTACH: break;
2953 case DLL_THREAD_ATTACH: break;
2954 case DLL_THREAD_DETACH:
2955 for (i=0; i<mdb_tls_nkeys; i++) {
2956 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
2957 mdb_env_reader_dest(r);
2960 case DLL_PROCESS_DETACH: break;
2965 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
2967 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
2971 /* Force some symbol references.
2972 * _tls_used forces the linker to create the TLS directory if not already done
2973 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
2975 #pragma comment(linker, "/INCLUDE:_tls_used")
2976 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
2977 #pragma const_seg(".CRT$XLB")
2978 extern const PIMAGE_TLS_CALLBACK mdb_tls_callback;
2979 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
2982 #pragma comment(linker, "/INCLUDE:__tls_used")
2983 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
2984 #pragma data_seg(".CRT$XLB")
2985 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
2987 #endif /* WIN 32/64 */
2988 #endif /* !__GNUC__ */
2991 /** Downgrade the exclusive lock on the region back to shared */
2993 mdb_env_share_locks(MDB_env *env, int *excl)
2995 int rc = 0, toggle = mdb_env_pick_meta(env);
2997 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
3002 /* First acquire a shared lock. The Unlock will
3003 * then release the existing exclusive lock.
3005 memset(&ov, 0, sizeof(ov));
3006 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3009 UnlockFile(env->me_lfd, 0, 0, 1, 0);
3015 struct flock lock_info;
3016 /* The shared lock replaces the existing lock */
3017 memset((void *)&lock_info, 0, sizeof(lock_info));
3018 lock_info.l_type = F_RDLCK;
3019 lock_info.l_whence = SEEK_SET;
3020 lock_info.l_start = 0;
3021 lock_info.l_len = 1;
3022 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3023 (rc = ErrCode()) == EINTR) ;
3024 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
3031 /** Try to get exlusive lock, otherwise shared.
3032 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
3035 mdb_env_excl_lock(MDB_env *env, int *excl)
3039 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
3043 memset(&ov, 0, sizeof(ov));
3044 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3051 struct flock lock_info;
3052 memset((void *)&lock_info, 0, sizeof(lock_info));
3053 lock_info.l_type = F_WRLCK;
3054 lock_info.l_whence = SEEK_SET;
3055 lock_info.l_start = 0;
3056 lock_info.l_len = 1;
3057 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3058 (rc = ErrCode()) == EINTR) ;
3062 # ifdef MDB_USE_POSIX_SEM
3063 if (*excl < 0) /* always true when !MDB_USE_POSIX_SEM */
3066 lock_info.l_type = F_RDLCK;
3067 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
3068 (rc = ErrCode()) == EINTR) ;
3076 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
3078 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
3080 * @(#) $Revision: 5.1 $
3081 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
3082 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
3084 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
3088 * Please do not copyright this code. This code is in the public domain.
3090 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
3091 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
3092 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
3093 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
3094 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
3095 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
3096 * PERFORMANCE OF THIS SOFTWARE.
3099 * chongo <Landon Curt Noll> /\oo/\
3100 * http://www.isthe.com/chongo/
3102 * Share and Enjoy! :-)
3105 typedef unsigned long long mdb_hash_t;
3106 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
3108 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
3109 * @param[in] str string to hash
3110 * @param[in] hval initial value for hash
3111 * @return 64 bit hash
3113 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
3114 * hval arg on the first call.
3117 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
3119 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
3120 unsigned char *end = s + val->mv_size;
3122 * FNV-1a hash each octet of the string
3125 /* xor the bottom with the current octet */
3126 hval ^= (mdb_hash_t)*s++;
3128 /* multiply by the 64 bit FNV magic prime mod 2^64 */
3129 hval += (hval << 1) + (hval << 4) + (hval << 5) +
3130 (hval << 7) + (hval << 8) + (hval << 40);
3132 /* return our new hash value */
3136 /** Hash the string and output the hash in hex.
3137 * @param[in] str string to hash
3138 * @param[out] hexbuf an array of 17 chars to hold the hash
3141 mdb_hash_hex(MDB_val *val, char *hexbuf)
3144 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
3145 for (i=0; i<8; i++) {
3146 hexbuf += sprintf(hexbuf, "%02x", (unsigned int)h & 0xff);
3152 /** Open and/or initialize the lock region for the environment.
3153 * @param[in] env The MDB environment.
3154 * @param[in] lpath The pathname of the file used for the lock region.
3155 * @param[in] mode The Unix permissions for the file, if we create it.
3156 * @param[out] excl Resulting file lock type: -1 none, 0 shared, 1 exclusive
3157 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
3158 * @return 0 on success, non-zero on failure.
3161 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
3164 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
3166 # define MDB_ERRCODE_ROFS EROFS
3167 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
3168 # define MDB_CLOEXEC O_CLOEXEC
3171 # define MDB_CLOEXEC 0
3178 env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
3179 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
3180 FILE_ATTRIBUTE_NORMAL, NULL);
3182 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
3184 if (env->me_lfd == INVALID_HANDLE_VALUE) {
3186 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
3191 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
3192 /* Lose record locks when exec*() */
3193 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
3194 fcntl(env->me_lfd, F_SETFD, fdflags);
3197 if (!(env->me_flags & MDB_NOTLS)) {
3198 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
3201 env->me_flags |= MDB_ENV_TXKEY;
3203 /* Windows TLS callbacks need help finding their TLS info. */
3204 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
3208 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
3212 /* Try to get exclusive lock. If we succeed, then
3213 * nobody is using the lock region and we should initialize it.
3215 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
3218 size = GetFileSize(env->me_lfd, NULL);
3220 size = lseek(env->me_lfd, 0, SEEK_END);
3221 if (size == -1) goto fail_errno;
3223 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
3224 if (size < rsize && *excl > 0) {
3226 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != rsize
3227 || !SetEndOfFile(env->me_lfd))
3230 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
3234 size = rsize - sizeof(MDB_txninfo);
3235 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
3240 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
3242 if (!mh) goto fail_errno;
3243 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
3245 if (!env->me_txns) goto fail_errno;
3247 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
3249 if (m == MAP_FAILED) goto fail_errno;
3255 BY_HANDLE_FILE_INFORMATION stbuf;
3264 if (!mdb_sec_inited) {
3265 InitializeSecurityDescriptor(&mdb_null_sd,
3266 SECURITY_DESCRIPTOR_REVISION);
3267 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
3268 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
3269 mdb_all_sa.bInheritHandle = FALSE;
3270 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
3273 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
3274 idbuf.volume = stbuf.dwVolumeSerialNumber;
3275 idbuf.nhigh = stbuf.nFileIndexHigh;
3276 idbuf.nlow = stbuf.nFileIndexLow;
3277 val.mv_data = &idbuf;
3278 val.mv_size = sizeof(idbuf);
3279 mdb_hash_hex(&val, hexbuf);
3280 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", hexbuf);
3281 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", hexbuf);
3282 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
3283 if (!env->me_rmutex) goto fail_errno;
3284 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
3285 if (!env->me_wmutex) goto fail_errno;
3286 #elif defined(MDB_USE_POSIX_SEM)
3295 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
3296 idbuf.dev = stbuf.st_dev;
3297 idbuf.ino = stbuf.st_ino;
3298 val.mv_data = &idbuf;
3299 val.mv_size = sizeof(idbuf);
3300 mdb_hash_hex(&val, hexbuf);
3301 sprintf(env->me_txns->mti_rmname, "/MDBr%s", hexbuf);
3302 sprintf(env->me_txns->mti_wmname, "/MDBw%s", hexbuf);
3303 /* Clean up after a previous run, if needed: Try to
3304 * remove both semaphores before doing anything else.
3306 sem_unlink(env->me_txns->mti_rmname);
3307 sem_unlink(env->me_txns->mti_wmname);
3308 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
3309 O_CREAT|O_EXCL, mode, 1);
3310 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3311 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
3312 O_CREAT|O_EXCL, mode, 1);
3313 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3314 #else /* MDB_USE_POSIX_SEM */
3315 pthread_mutexattr_t mattr;
3317 if ((rc = pthread_mutexattr_init(&mattr))
3318 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
3319 || (rc = pthread_mutex_init(&env->me_txns->mti_mutex, &mattr))
3320 || (rc = pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr)))
3322 pthread_mutexattr_destroy(&mattr);
3323 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
3325 env->me_txns->mti_version = MDB_VERSION;
3326 env->me_txns->mti_magic = MDB_MAGIC;
3327 env->me_txns->mti_txnid = 0;
3328 env->me_txns->mti_numreaders = 0;
3331 if (env->me_txns->mti_magic != MDB_MAGIC) {
3332 DPUTS("lock region has invalid magic");
3336 if (env->me_txns->mti_version != MDB_VERSION) {
3337 DPRINTF("lock region is version %u, expected version %u",
3338 env->me_txns->mti_version, MDB_VERSION);
3339 rc = MDB_VERSION_MISMATCH;
3343 if (rc && rc != EACCES && rc != EAGAIN) {
3347 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
3348 if (!env->me_rmutex) goto fail_errno;
3349 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
3350 if (!env->me_wmutex) goto fail_errno;
3351 #elif defined(MDB_USE_POSIX_SEM)
3352 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
3353 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3354 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
3355 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3366 /** The name of the lock file in the DB environment */
3367 #define LOCKNAME "/lock.mdb"
3368 /** The name of the data file in the DB environment */
3369 #define DATANAME "/data.mdb"
3370 /** The suffix of the lock file when no subdir is used */
3371 #define LOCKSUFF "-lock"
3372 /** Only a subset of the @ref mdb_env flags can be changed
3373 * at runtime. Changing other flags requires closing the
3374 * environment and re-opening it with the new flags.
3376 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC)
3377 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY|MDB_WRITEMAP|MDB_NOTLS)
3380 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
3382 int oflags, rc, len, excl = -1;
3383 char *lpath, *dpath;
3385 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
3389 if (flags & MDB_NOSUBDIR) {
3390 rc = len + sizeof(LOCKSUFF) + len + 1;
3392 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
3397 if (flags & MDB_NOSUBDIR) {
3398 dpath = lpath + len + sizeof(LOCKSUFF);
3399 sprintf(lpath, "%s" LOCKSUFF, path);
3400 strcpy(dpath, path);
3402 dpath = lpath + len + sizeof(LOCKNAME);
3403 sprintf(lpath, "%s" LOCKNAME, path);
3404 sprintf(dpath, "%s" DATANAME, path);
3408 flags |= env->me_flags;
3409 if (flags & MDB_RDONLY) {
3410 /* silently ignore WRITEMAP when we're only getting read access */
3411 flags &= ~MDB_WRITEMAP;
3413 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
3414 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
3417 env->me_flags = flags |= MDB_ENV_ACTIVE;
3421 env->me_path = strdup(path);
3422 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
3423 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
3424 if (!(env->me_dbxs && env->me_path && env->me_dbflags)) {
3429 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
3434 if (F_ISSET(flags, MDB_RDONLY)) {
3435 oflags = GENERIC_READ;
3436 len = OPEN_EXISTING;
3438 oflags = GENERIC_READ|GENERIC_WRITE;
3441 mode = FILE_ATTRIBUTE_NORMAL;
3442 env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
3443 NULL, len, mode, NULL);
3445 if (F_ISSET(flags, MDB_RDONLY))
3448 oflags = O_RDWR | O_CREAT;
3450 env->me_fd = open(dpath, oflags, mode);
3452 if (env->me_fd == INVALID_HANDLE_VALUE) {
3457 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
3458 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
3459 env->me_mfd = env->me_fd;
3461 /* Synchronous fd for meta writes. Needed even with
3462 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
3465 env->me_mfd = CreateFile(dpath, oflags,
3466 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
3467 mode | FILE_FLAG_WRITE_THROUGH, NULL);
3469 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
3471 if (env->me_mfd == INVALID_HANDLE_VALUE) {
3476 DPRINTF("opened dbenv %p", (void *) env);
3478 rc = mdb_env_share_locks(env, &excl);
3484 mdb_env_close0(env, excl);
3490 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
3492 mdb_env_close0(MDB_env *env, int excl)
3496 if (!(env->me_flags & MDB_ENV_ACTIVE))
3499 /* Doing this here since me_dbxs may not exist during mdb_env_close */
3500 for (i = env->me_maxdbs; --i > MAIN_DBI; )
3501 free(env->me_dbxs[i].md_name.mv_data);
3503 free(env->me_dbflags);
3506 free(env->me_dirty_list);
3507 mdb_midl_free(env->me_free_pgs);
3509 if (env->me_flags & MDB_ENV_TXKEY) {
3510 pthread_key_delete(env->me_txkey);
3512 /* Delete our key from the global list */
3513 for (i=0; i<mdb_tls_nkeys; i++)
3514 if (mdb_tls_keys[i] == env->me_txkey) {
3515 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
3523 munmap(env->me_map, env->me_mapsize);
3525 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
3526 (void) close(env->me_mfd);
3527 if (env->me_fd != INVALID_HANDLE_VALUE)
3528 (void) close(env->me_fd);
3530 pid_t pid = env->me_pid;
3531 /* Clearing readers is done in this function because
3532 * me_txkey with its destructor must be disabled first.
3534 for (i = env->me_numreaders; --i >= 0; )
3535 if (env->me_txns->mti_readers[i].mr_pid == pid)
3536 env->me_txns->mti_readers[i].mr_pid = 0;
3538 if (env->me_rmutex) {
3539 CloseHandle(env->me_rmutex);
3540 if (env->me_wmutex) CloseHandle(env->me_wmutex);
3542 /* Windows automatically destroys the mutexes when
3543 * the last handle closes.
3545 #elif defined(MDB_USE_POSIX_SEM)
3546 if (env->me_rmutex != SEM_FAILED) {
3547 sem_close(env->me_rmutex);
3548 if (env->me_wmutex != SEM_FAILED)
3549 sem_close(env->me_wmutex);
3550 /* If we have the filelock: If we are the
3551 * only remaining user, clean up semaphores.
3554 mdb_env_excl_lock(env, &excl);
3556 sem_unlink(env->me_txns->mti_rmname);
3557 sem_unlink(env->me_txns->mti_wmname);
3561 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
3563 if (env->me_lfd != INVALID_HANDLE_VALUE) {
3566 /* Unlock the lockfile. Windows would have unlocked it
3567 * after closing anyway, but not necessarily at once.
3569 UnlockFile(env->me_lfd, 0, 0, 1, 0);
3572 (void) close(env->me_lfd);
3575 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
3579 mdb_env_copyfd(MDB_env *env, HANDLE fd)
3581 MDB_txn *txn = NULL;
3586 /* Do the lock/unlock of the reader mutex before starting the
3587 * write txn. Otherwise other read txns could block writers.
3589 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
3594 /* We must start the actual read txn after blocking writers */
3595 mdb_txn_reset0(txn, "reset-stage1");
3597 /* Temporarily block writers until we snapshot the meta pages */
3600 rc = mdb_txn_renew0(txn);
3602 UNLOCK_MUTEX_W(env);
3607 wsize = env->me_psize * 2;
3611 rc = WriteFile(fd, env->me_map, wsize, &len, NULL);
3612 rc = rc ? (len == wsize ? MDB_SUCCESS : EIO) : ErrCode();
3615 rc = write(fd, env->me_map, wsize);
3616 rc = rc == (int)wsize ? MDB_SUCCESS : rc < 0 ? ErrCode() : EIO;
3619 UNLOCK_MUTEX_W(env);
3624 ptr = env->me_map + wsize;
3625 wsize = txn->mt_next_pgno * env->me_psize - wsize;
3629 if (wsize > MAX_WRITE)
3633 rc = WriteFile(fd, ptr, w2, &len, NULL);
3634 rc = rc ? (len == w2 ? MDB_SUCCESS : EIO) : ErrCode();
3643 if (wsize > MAX_WRITE)
3647 wres = write(fd, ptr, w2);
3648 rc = wres == (ssize_t)w2 ? MDB_SUCCESS : wres < 0 ? ErrCode() : EIO;
3661 mdb_env_copy(MDB_env *env, const char *path)
3665 HANDLE newfd = INVALID_HANDLE_VALUE;
3667 if (env->me_flags & MDB_NOSUBDIR) {
3668 lpath = (char *)path;
3671 len += sizeof(DATANAME);
3672 lpath = malloc(len);
3675 sprintf(lpath, "%s" DATANAME, path);
3678 /* The destination path must exist, but the destination file must not.
3679 * We don't want the OS to cache the writes, since the source data is
3680 * already in the OS cache.
3683 newfd = CreateFile(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
3684 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
3686 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL
3692 if (newfd == INVALID_HANDLE_VALUE) {
3697 #ifdef F_NOCACHE /* __APPLE__ */
3698 rc = fcntl(newfd, F_NOCACHE, 1);
3705 rc = mdb_env_copyfd(env, newfd);
3708 if (!(env->me_flags & MDB_NOSUBDIR))
3710 if (newfd != INVALID_HANDLE_VALUE)
3711 if (close(newfd) < 0 && rc == MDB_SUCCESS)
3718 mdb_env_close(MDB_env *env)
3725 VGMEMP_DESTROY(env);
3726 while ((dp = env->me_dpages) != NULL) {
3727 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
3728 env->me_dpages = dp->mp_next;
3732 mdb_env_close0(env, 0);
3736 /** Compare two items pointing at aligned size_t's */
3738 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
3740 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
3741 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
3744 /** Compare two items pointing at aligned int's */
3746 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
3748 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
3749 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
3752 /** Compare two items pointing at ints of unknown alignment.
3753 * Nodes and keys are guaranteed to be 2-byte aligned.
3756 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
3758 #if BYTE_ORDER == LITTLE_ENDIAN
3759 unsigned short *u, *c;
3762 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
3763 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
3766 } while(!x && u > (unsigned short *)a->mv_data);
3769 return memcmp(a->mv_data, b->mv_data, a->mv_size);
3773 /** Compare two items lexically */
3775 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
3782 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
3788 diff = memcmp(a->mv_data, b->mv_data, len);
3789 return diff ? diff : len_diff<0 ? -1 : len_diff;
3792 /** Compare two items in reverse byte order */
3794 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
3796 const unsigned char *p1, *p2, *p1_lim;
3800 p1_lim = (const unsigned char *)a->mv_data;
3801 p1 = (const unsigned char *)a->mv_data + a->mv_size;
3802 p2 = (const unsigned char *)b->mv_data + b->mv_size;
3804 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
3810 while (p1 > p1_lim) {
3811 diff = *--p1 - *--p2;
3815 return len_diff<0 ? -1 : len_diff;
3818 /** Search for key within a page, using binary search.
3819 * Returns the smallest entry larger or equal to the key.
3820 * If exactp is non-null, stores whether the found entry was an exact match
3821 * in *exactp (1 or 0).
3822 * Updates the cursor index with the index of the found entry.
3823 * If no entry larger or equal to the key is found, returns NULL.
3826 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
3828 unsigned int i = 0, nkeys;
3831 MDB_page *mp = mc->mc_pg[mc->mc_top];
3832 MDB_node *node = NULL;
3837 nkeys = NUMKEYS(mp);
3842 COPY_PGNO(pgno, mp->mp_pgno);
3843 DPRINTF("searching %u keys in %s %spage %zu",
3844 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
3851 low = IS_LEAF(mp) ? 0 : 1;
3853 cmp = mc->mc_dbx->md_cmp;
3855 /* Branch pages have no data, so if using integer keys,
3856 * alignment is guaranteed. Use faster mdb_cmp_int.
3858 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
3859 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
3866 nodekey.mv_size = mc->mc_db->md_pad;
3867 node = NODEPTR(mp, 0); /* fake */
3868 while (low <= high) {
3869 i = (low + high) >> 1;
3870 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
3871 rc = cmp(key, &nodekey);
3872 DPRINTF("found leaf index %u [%s], rc = %i",
3873 i, DKEY(&nodekey), rc);
3882 while (low <= high) {
3883 i = (low + high) >> 1;
3885 node = NODEPTR(mp, i);
3886 nodekey.mv_size = NODEKSZ(node);
3887 nodekey.mv_data = NODEKEY(node);
3889 rc = cmp(key, &nodekey);
3892 DPRINTF("found leaf index %u [%s], rc = %i",
3893 i, DKEY(&nodekey), rc);
3895 DPRINTF("found branch index %u [%s -> %zu], rc = %i",
3896 i, DKEY(&nodekey), NODEPGNO(node), rc);
3907 if (rc > 0) { /* Found entry is less than the key. */
3908 i++; /* Skip to get the smallest entry larger than key. */
3910 node = NODEPTR(mp, i);
3913 *exactp = (rc == 0);
3914 /* store the key index */
3915 mc->mc_ki[mc->mc_top] = i;
3917 /* There is no entry larger or equal to the key. */
3920 /* nodeptr is fake for LEAF2 */
3926 mdb_cursor_adjust(MDB_cursor *mc, func)
3930 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
3931 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
3938 /** Pop a page off the top of the cursor's stack. */
3940 mdb_cursor_pop(MDB_cursor *mc)
3943 #ifndef MDB_DEBUG_SKIP
3944 MDB_page *top = mc->mc_pg[mc->mc_top];
3950 DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
3951 mc->mc_dbi, (void *) mc);
3955 /** Push a page onto the top of the cursor's stack. */
3957 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
3959 DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
3960 mc->mc_dbi, (void *) mc);
3962 if (mc->mc_snum >= CURSOR_STACK) {
3963 assert(mc->mc_snum < CURSOR_STACK);
3964 return MDB_CURSOR_FULL;
3967 mc->mc_top = mc->mc_snum++;
3968 mc->mc_pg[mc->mc_top] = mp;
3969 mc->mc_ki[mc->mc_top] = 0;
3974 /** Find the address of the page corresponding to a given page number.
3975 * @param[in] txn the transaction for this access.
3976 * @param[in] pgno the page number for the page to retrieve.
3977 * @param[out] ret address of a pointer where the page's address will be stored.
3978 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
3979 * @return 0 on success, non-zero on failure.
3982 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
3987 if (!((txn->mt_flags & MDB_TXN_RDONLY) |
3988 (txn->mt_env->me_flags & MDB_WRITEMAP)))
3993 MDB_ID2L dl = tx2->mt_u.dirty_list;
3995 unsigned x = mdb_mid2l_search(dl, pgno);
3996 if (x <= dl[0].mid && dl[x].mid == pgno) {
4002 } while ((tx2 = tx2->mt_parent) != NULL);
4005 if (pgno < txn->mt_next_pgno) {
4007 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
4009 DPRINTF("page %zu not found", pgno);
4011 return MDB_PAGE_NOTFOUND;
4021 /** Search for the page a given key should be in.
4022 * Pushes parent pages on the cursor stack. This function continues a
4023 * search on a cursor that has already been initialized. (Usually by
4024 * #mdb_page_search() but also by #mdb_node_move().)
4025 * @param[in,out] mc the cursor for this operation.
4026 * @param[in] key the key to search for. If NULL, search for the lowest
4027 * page. (This is used by #mdb_cursor_first().)
4028 * @param[in] modify If true, visited pages are updated with new page numbers.
4029 * @return 0 on success, non-zero on failure.
4032 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
4034 MDB_page *mp = mc->mc_pg[mc->mc_top];
4039 while (IS_BRANCH(mp)) {
4043 DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
4044 assert(NUMKEYS(mp) > 1);
4045 DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
4047 if (key == NULL) /* Initialize cursor to first page. */
4049 else if (key->mv_size > MDB_MAXKEYSIZE && key->mv_data == NULL) {
4050 /* cursor to last page */
4054 node = mdb_node_search(mc, key, &exact);
4056 i = NUMKEYS(mp) - 1;
4058 i = mc->mc_ki[mc->mc_top];
4067 DPRINTF("following index %u for key [%s]",
4069 assert(i < NUMKEYS(mp));
4070 node = NODEPTR(mp, i);
4072 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4075 mc->mc_ki[mc->mc_top] = i;
4076 if ((rc = mdb_cursor_push(mc, mp)))
4080 if ((rc = mdb_page_touch(mc)) != 0)
4082 mp = mc->mc_pg[mc->mc_top];
4087 DPRINTF("internal error, index points to a %02X page!?",
4089 return MDB_CORRUPTED;
4092 DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
4093 key ? DKEY(key) : NULL);
4098 /** Search for the lowest key under the current branch page.
4099 * This just bypasses a NUMKEYS check in the current page
4100 * before calling mdb_page_search_root(), because the callers
4101 * are all in situations where the current page is known to
4105 mdb_page_search_lowest(MDB_cursor *mc)
4107 MDB_page *mp = mc->mc_pg[mc->mc_top];
4108 MDB_node *node = NODEPTR(mp, 0);
4111 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4114 mc->mc_ki[mc->mc_top] = 0;
4115 if ((rc = mdb_cursor_push(mc, mp)))
4117 return mdb_page_search_root(mc, NULL, 0);
4120 /** Search for the page a given key should be in.
4121 * Pushes parent pages on the cursor stack. This function just sets up
4122 * the search; it finds the root page for \b mc's database and sets this
4123 * as the root of the cursor's stack. Then #mdb_page_search_root() is
4124 * called to complete the search.
4125 * @param[in,out] mc the cursor for this operation.
4126 * @param[in] key the key to search for. If NULL, search for the lowest
4127 * page. (This is used by #mdb_cursor_first().)
4128 * @param[in] flags If MDB_PS_MODIFY set, visited pages are updated with new page numbers.
4129 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
4130 * @return 0 on success, non-zero on failure.
4133 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
4138 /* Make sure the txn is still viable, then find the root from
4139 * the txn's db table.
4141 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
4142 DPUTS("transaction has failed, must abort");
4145 /* Make sure we're using an up-to-date root */
4146 if (mc->mc_dbi > MAIN_DBI) {
4147 if ((*mc->mc_dbflag & DB_STALE) ||
4148 ((flags & MDB_PS_MODIFY) && !(*mc->mc_dbflag & DB_DIRTY))) {
4150 unsigned char dbflag = 0;
4151 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
4152 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, flags & MDB_PS_MODIFY);
4155 if (*mc->mc_dbflag & DB_STALE) {
4159 MDB_node *leaf = mdb_node_search(&mc2,
4160 &mc->mc_dbx->md_name, &exact);
4162 return MDB_NOTFOUND;
4163 rc = mdb_node_read(mc->mc_txn, leaf, &data);
4166 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
4168 /* The txn may not know this DBI, or another process may
4169 * have dropped and recreated the DB with other flags.
4171 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
4172 return MDB_INCOMPATIBLE;
4173 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
4175 if (flags & MDB_PS_MODIFY)
4177 *mc->mc_dbflag &= ~DB_STALE;
4178 *mc->mc_dbflag |= dbflag;
4181 root = mc->mc_db->md_root;
4183 if (root == P_INVALID) { /* Tree is empty. */
4184 DPUTS("tree is empty");
4185 return MDB_NOTFOUND;
4190 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
4191 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0], NULL)) != 0)
4197 DPRINTF("db %u root page %zu has flags 0x%X",
4198 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
4200 if (flags & MDB_PS_MODIFY) {
4201 if ((rc = mdb_page_touch(mc)))
4205 if (flags & MDB_PS_ROOTONLY)
4208 return mdb_page_search_root(mc, key, flags);
4212 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
4214 MDB_txn *txn = mc->mc_txn;
4215 pgno_t pg = mp->mp_pgno;
4216 unsigned i, ovpages = mp->mp_pages;
4217 MDB_env *env = txn->mt_env;
4220 DPRINTF("free ov page %zu (%d)", pg, ovpages);
4221 /* If the page is dirty we just acquired it, so we should
4222 * give it back to our current free list, if any.
4223 * Not currently supported in nested txns.
4224 * Otherwise put it onto the list of pages we freed in this txn.
4226 if ((mp->mp_flags & P_DIRTY) && !txn->mt_parent && env->me_pghead) {
4229 MDB_ID2 *dl, ix, iy;
4230 rc = mdb_midl_need(&env->me_pghead, ovpages);
4233 /* Remove from dirty list */
4234 dl = txn->mt_u.dirty_list;
4236 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
4244 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
4245 txn->mt_flags |= MDB_TXN_ERROR;
4246 return MDB_CORRUPTED;
4249 if (!(env->me_flags & MDB_WRITEMAP))
4250 mdb_dpage_free(env, mp);
4251 /* Insert in me_pghead */
4252 mop = env->me_pghead;
4253 j = mop[0] + ovpages;
4254 for (i = mop[0]; i && mop[i] < pg; i--)
4260 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
4264 mc->mc_db->md_overflow_pages -= ovpages;
4268 /** Return the data associated with a given node.
4269 * @param[in] txn The transaction for this operation.
4270 * @param[in] leaf The node being read.
4271 * @param[out] data Updated to point to the node's data.
4272 * @return 0 on success, non-zero on failure.
4275 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
4277 MDB_page *omp; /* overflow page */
4281 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
4282 data->mv_size = NODEDSZ(leaf);
4283 data->mv_data = NODEDATA(leaf);
4287 /* Read overflow data.
4289 data->mv_size = NODEDSZ(leaf);
4290 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
4291 if ((rc = mdb_page_get(txn, pgno, &omp, NULL)) != 0) {
4292 DPRINTF("read overflow page %zu failed", pgno);
4295 data->mv_data = METADATA(omp);
4301 mdb_get(MDB_txn *txn, MDB_dbi dbi,
4302 MDB_val *key, MDB_val *data)
4311 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
4313 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
4316 if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
4320 mdb_cursor_init(&mc, txn, dbi, &mx);
4321 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
4324 /** Find a sibling for a page.
4325 * Replaces the page at the top of the cursor's stack with the
4326 * specified sibling, if one exists.
4327 * @param[in] mc The cursor for this operation.
4328 * @param[in] move_right Non-zero if the right sibling is requested,
4329 * otherwise the left sibling.
4330 * @return 0 on success, non-zero on failure.
4333 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
4339 if (mc->mc_snum < 2) {
4340 return MDB_NOTFOUND; /* root has no siblings */
4344 DPRINTF("parent page is page %zu, index %u",
4345 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]);
4347 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
4348 : (mc->mc_ki[mc->mc_top] == 0)) {
4349 DPRINTF("no more keys left, moving to %s sibling",
4350 move_right ? "right" : "left");
4351 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
4352 /* undo cursor_pop before returning */
4359 mc->mc_ki[mc->mc_top]++;
4361 mc->mc_ki[mc->mc_top]--;
4362 DPRINTF("just moving to %s index key %u",
4363 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]);
4365 assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
4367 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4368 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL) != 0))
4371 mdb_cursor_push(mc, mp);
4373 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
4378 /** Move the cursor to the next data item. */
4380 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
4386 if (mc->mc_flags & C_EOF) {
4387 return MDB_NOTFOUND;
4390 assert(mc->mc_flags & C_INITIALIZED);
4392 mp = mc->mc_pg[mc->mc_top];
4394 if (mc->mc_db->md_flags & MDB_DUPSORT) {
4395 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4396 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4397 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
4398 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
4399 if (op != MDB_NEXT || rc != MDB_NOTFOUND)
4403 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
4404 if (op == MDB_NEXT_DUP)
4405 return MDB_NOTFOUND;
4409 DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
4411 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
4412 DPUTS("=====> move to next sibling page");
4413 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
4414 mc->mc_flags |= C_EOF;
4417 mp = mc->mc_pg[mc->mc_top];
4418 DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
4420 mc->mc_ki[mc->mc_top]++;
4422 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
4423 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
4426 key->mv_size = mc->mc_db->md_pad;
4427 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
4431 assert(IS_LEAF(mp));
4432 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4434 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4435 mdb_xcursor_init1(mc, leaf);
4438 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4441 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4442 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4443 if (rc != MDB_SUCCESS)
4448 MDB_GET_KEY(leaf, key);
4452 /** Move the cursor to the previous data item. */
4454 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
4460 assert(mc->mc_flags & C_INITIALIZED);
4462 mp = mc->mc_pg[mc->mc_top];
4464 if (mc->mc_db->md_flags & MDB_DUPSORT) {
4465 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4466 if (op == MDB_PREV || op == MDB_PREV_DUP) {
4467 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4468 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
4469 if (op != MDB_PREV || rc != MDB_NOTFOUND)
4472 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
4473 if (op == MDB_PREV_DUP)
4474 return MDB_NOTFOUND;
4479 DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
4481 if (mc->mc_ki[mc->mc_top] == 0) {
4482 DPUTS("=====> move to prev sibling page");
4483 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
4486 mp = mc->mc_pg[mc->mc_top];
4487 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
4488 DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
4490 mc->mc_ki[mc->mc_top]--;
4492 mc->mc_flags &= ~C_EOF;
4494 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
4495 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
4498 key->mv_size = mc->mc_db->md_pad;
4499 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
4503 assert(IS_LEAF(mp));
4504 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4506 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4507 mdb_xcursor_init1(mc, leaf);
4510 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4513 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4514 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
4515 if (rc != MDB_SUCCESS)
4520 MDB_GET_KEY(leaf, key);
4524 /** Set the cursor on a specific data item. */
4526 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
4527 MDB_cursor_op op, int *exactp)
4531 MDB_node *leaf = NULL;
4536 assert(key->mv_size > 0);
4538 /* See if we're already on the right page */
4539 if (mc->mc_flags & C_INITIALIZED) {
4542 mp = mc->mc_pg[mc->mc_top];
4544 mc->mc_ki[mc->mc_top] = 0;
4545 return MDB_NOTFOUND;
4547 if (mp->mp_flags & P_LEAF2) {
4548 nodekey.mv_size = mc->mc_db->md_pad;
4549 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
4551 leaf = NODEPTR(mp, 0);
4552 MDB_GET_KEY(leaf, &nodekey);
4554 rc = mc->mc_dbx->md_cmp(key, &nodekey);
4556 /* Probably happens rarely, but first node on the page
4557 * was the one we wanted.
4559 mc->mc_ki[mc->mc_top] = 0;
4566 unsigned int nkeys = NUMKEYS(mp);
4568 if (mp->mp_flags & P_LEAF2) {
4569 nodekey.mv_data = LEAF2KEY(mp,
4570 nkeys-1, nodekey.mv_size);
4572 leaf = NODEPTR(mp, nkeys-1);
4573 MDB_GET_KEY(leaf, &nodekey);
4575 rc = mc->mc_dbx->md_cmp(key, &nodekey);
4577 /* last node was the one we wanted */
4578 mc->mc_ki[mc->mc_top] = nkeys-1;
4584 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
4585 /* This is definitely the right page, skip search_page */
4586 if (mp->mp_flags & P_LEAF2) {
4587 nodekey.mv_data = LEAF2KEY(mp,
4588 mc->mc_ki[mc->mc_top], nodekey.mv_size);
4590 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4591 MDB_GET_KEY(leaf, &nodekey);
4593 rc = mc->mc_dbx->md_cmp(key, &nodekey);
4595 /* current node was the one we wanted */
4605 /* If any parents have right-sibs, search.
4606 * Otherwise, there's nothing further.
4608 for (i=0; i<mc->mc_top; i++)
4610 NUMKEYS(mc->mc_pg[i])-1)
4612 if (i == mc->mc_top) {
4613 /* There are no other pages */
4614 mc->mc_ki[mc->mc_top] = nkeys;
4615 return MDB_NOTFOUND;
4619 /* There are no other pages */
4620 mc->mc_ki[mc->mc_top] = 0;
4621 return MDB_NOTFOUND;
4625 rc = mdb_page_search(mc, key, 0);
4626 if (rc != MDB_SUCCESS)
4629 mp = mc->mc_pg[mc->mc_top];
4630 assert(IS_LEAF(mp));
4633 leaf = mdb_node_search(mc, key, exactp);
4634 if (exactp != NULL && !*exactp) {
4635 /* MDB_SET specified and not an exact match. */
4636 return MDB_NOTFOUND;
4640 DPUTS("===> inexact leaf not found, goto sibling");
4641 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
4642 return rc; /* no entries matched */
4643 mp = mc->mc_pg[mc->mc_top];
4644 assert(IS_LEAF(mp));
4645 leaf = NODEPTR(mp, 0);
4649 mc->mc_flags |= C_INITIALIZED;
4650 mc->mc_flags &= ~C_EOF;
4653 key->mv_size = mc->mc_db->md_pad;
4654 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
4658 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4659 mdb_xcursor_init1(mc, leaf);
4662 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4663 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
4664 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4667 if (op == MDB_GET_BOTH) {
4673 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
4674 if (rc != MDB_SUCCESS)
4677 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
4679 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
4681 rc = mc->mc_dbx->md_dcmp(data, &d2);
4683 if (op == MDB_GET_BOTH || rc > 0)
4684 return MDB_NOTFOUND;
4689 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
4690 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4695 /* The key already matches in all other cases */
4696 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
4697 MDB_GET_KEY(leaf, key);
4698 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
4703 /** Move the cursor to the first item in the database. */
4705 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
4710 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
4711 rc = mdb_page_search(mc, NULL, 0);
4712 if (rc != MDB_SUCCESS)
4715 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
4717 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
4718 mc->mc_flags |= C_INITIALIZED;
4719 mc->mc_flags &= ~C_EOF;
4721 mc->mc_ki[mc->mc_top] = 0;
4723 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
4724 key->mv_size = mc->mc_db->md_pad;
4725 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
4730 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4731 mdb_xcursor_init1(mc, leaf);
4732 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4737 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
4738 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4742 MDB_GET_KEY(leaf, key);
4746 /** Move the cursor to the last item in the database. */
4748 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
4753 if (!(mc->mc_flags & C_EOF)) {
4755 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
4758 lkey.mv_size = MDB_MAXKEYSIZE+1;
4759 lkey.mv_data = NULL;
4760 rc = mdb_page_search(mc, &lkey, 0);
4761 if (rc != MDB_SUCCESS)
4764 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
4767 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
4768 mc->mc_flags |= C_INITIALIZED|C_EOF;
4769 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4771 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
4772 key->mv_size = mc->mc_db->md_pad;
4773 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
4778 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4779 mdb_xcursor_init1(mc, leaf);
4780 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
4785 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
4786 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4791 MDB_GET_KEY(leaf, key);
4796 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
4805 case MDB_GET_CURRENT:
4806 if (!(mc->mc_flags & C_INITIALIZED)) {
4809 MDB_page *mp = mc->mc_pg[mc->mc_top];
4811 mc->mc_ki[mc->mc_top] = 0;
4817 key->mv_size = mc->mc_db->md_pad;
4818 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
4820 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4821 MDB_GET_KEY(leaf, key);
4823 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4824 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
4826 rc = mdb_node_read(mc->mc_txn, leaf, data);
4833 case MDB_GET_BOTH_RANGE:
4834 if (data == NULL || mc->mc_xcursor == NULL) {
4842 if (key == NULL || key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
4844 } else if (op == MDB_SET_RANGE)
4845 rc = mdb_cursor_set(mc, key, data, op, NULL);
4847 rc = mdb_cursor_set(mc, key, data, op, &exact);
4849 case MDB_GET_MULTIPLE:
4851 !(mc->mc_db->md_flags & MDB_DUPFIXED) ||
4852 !(mc->mc_flags & C_INITIALIZED)) {
4857 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
4858 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
4861 case MDB_NEXT_MULTIPLE:
4863 !(mc->mc_db->md_flags & MDB_DUPFIXED)) {
4867 if (!(mc->mc_flags & C_INITIALIZED))
4868 rc = mdb_cursor_first(mc, key, data);
4870 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
4871 if (rc == MDB_SUCCESS) {
4872 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
4875 mx = &mc->mc_xcursor->mx_cursor;
4876 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
4878 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
4879 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
4887 case MDB_NEXT_NODUP:
4888 if (!(mc->mc_flags & C_INITIALIZED))
4889 rc = mdb_cursor_first(mc, key, data);
4891 rc = mdb_cursor_next(mc, key, data, op);
4895 case MDB_PREV_NODUP:
4896 if (!(mc->mc_flags & C_INITIALIZED)) {
4897 rc = mdb_cursor_last(mc, key, data);
4900 mc->mc_flags |= C_INITIALIZED;
4901 mc->mc_ki[mc->mc_top]++;
4903 rc = mdb_cursor_prev(mc, key, data, op);
4906 rc = mdb_cursor_first(mc, key, data);
4910 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
4911 !(mc->mc_flags & C_INITIALIZED) ||
4912 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
4916 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4919 rc = mdb_cursor_last(mc, key, data);
4923 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
4924 !(mc->mc_flags & C_INITIALIZED) ||
4925 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
4929 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
4932 DPRINTF("unhandled/unimplemented cursor operation %u", op);
4940 /** Touch all the pages in the cursor stack.
4941 * Makes sure all the pages are writable, before attempting a write operation.
4942 * @param[in] mc The cursor to operate on.
4945 mdb_cursor_touch(MDB_cursor *mc)
4949 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
4952 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
4953 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
4956 *mc->mc_dbflag |= DB_DIRTY;
4958 for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
4959 rc = mdb_page_touch(mc);
4963 mc->mc_top = mc->mc_snum-1;
4968 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
4971 enum { MDB_NO_ROOT = MDB_LAST_ERRCODE+10 }; /* internal code */
4972 MDB_node *leaf = NULL;
4973 MDB_val xdata, *rdata, dkey;
4976 int do_sub = 0, insert = 0;
4977 unsigned int mcount = 0, dcount = 0;
4981 char dbuf[MDB_MAXKEYSIZE+1];
4982 unsigned int nflags;
4985 /* Check this first so counter will always be zero on any
4988 if (flags & MDB_MULTIPLE) {
4989 dcount = data[1].mv_size;
4990 data[1].mv_size = 0;
4991 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
4995 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
4998 if (flags != MDB_CURRENT && (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE))
5001 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT) && data->mv_size > MDB_MAXKEYSIZE)
5004 #if SIZE_MAX > MAXDATASIZE
5005 if (data->mv_size > MAXDATASIZE)
5009 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
5010 mc->mc_dbi, DKEY(key), key ? key->mv_size:0, data->mv_size);
5014 if (flags == MDB_CURRENT) {
5015 if (!(mc->mc_flags & C_INITIALIZED))
5018 } else if (mc->mc_db->md_root == P_INVALID) {
5019 /* new database, cursor has nothing to point to */
5021 mc->mc_flags &= ~C_INITIALIZED;
5026 if (flags & MDB_APPEND) {
5028 rc = mdb_cursor_last(mc, &k2, &d2);
5030 rc = mc->mc_dbx->md_cmp(key, &k2);
5033 mc->mc_ki[mc->mc_top]++;
5035 /* new key is <= last key */
5040 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
5042 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
5043 DPRINTF("duplicate key [%s]", DKEY(key));
5045 return MDB_KEYEXIST;
5047 if (rc && rc != MDB_NOTFOUND)
5051 /* Cursor is positioned */
5053 if (rc == MDB_NO_ROOT) {
5055 /* new database, write a root leaf page */
5056 DPUTS("allocating new root leaf page");
5057 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
5060 mdb_cursor_push(mc, np);
5061 mc->mc_db->md_root = np->mp_pgno;
5062 mc->mc_db->md_depth++;
5063 *mc->mc_dbflag |= DB_DIRTY;
5064 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
5066 np->mp_flags |= P_LEAF2;
5067 mc->mc_flags |= C_INITIALIZED;
5069 /* make sure all cursor pages are writable */
5070 rc2 = mdb_cursor_touch(mc);
5075 /* The key already exists */
5076 if (rc == MDB_SUCCESS) {
5077 /* there's only a key anyway, so this is a no-op */
5078 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5079 unsigned int ksize = mc->mc_db->md_pad;
5080 if (key->mv_size != ksize)
5082 if (flags == MDB_CURRENT) {
5083 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
5084 memcpy(ptr, key->mv_data, ksize);
5089 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5092 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
5093 /* Was a single item before, must convert now */
5095 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5096 /* Just overwrite the current item */
5097 if (flags == MDB_CURRENT)
5100 dkey.mv_size = NODEDSZ(leaf);
5101 dkey.mv_data = NODEDATA(leaf);
5102 #if UINT_MAX < SIZE_MAX
5103 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && dkey.mv_size == sizeof(size_t))
5104 #ifdef MISALIGNED_OK
5105 mc->mc_dbx->md_dcmp = mdb_cmp_long;
5107 mc->mc_dbx->md_dcmp = mdb_cmp_cint;
5110 /* if data matches, ignore it */
5111 if (!mc->mc_dbx->md_dcmp(data, &dkey))
5112 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
5114 /* create a fake page for the dup items */
5115 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
5116 dkey.mv_data = dbuf;
5117 fp = (MDB_page *)&pbuf;
5118 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
5119 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
5120 fp->mp_lower = PAGEHDRSZ;
5121 fp->mp_upper = PAGEHDRSZ + dkey.mv_size + data->mv_size;
5122 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5123 fp->mp_flags |= P_LEAF2;
5124 fp->mp_pad = data->mv_size;
5125 fp->mp_upper += 2 * data->mv_size; /* leave space for 2 more */
5127 fp->mp_upper += 2 * sizeof(indx_t) + 2 * NODESIZE +
5128 (dkey.mv_size & 1) + (data->mv_size & 1);
5130 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5133 xdata.mv_size = fp->mp_upper;
5138 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
5139 /* See if we need to convert from fake page to subDB */
5141 unsigned int offset;
5145 fp = NODEDATA(leaf);
5146 if (flags == MDB_CURRENT) {
5148 fp->mp_flags |= P_DIRTY;
5149 COPY_PGNO(fp->mp_pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
5150 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
5154 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5155 offset = fp->mp_pad;
5156 if (SIZELEFT(fp) >= offset)
5158 offset *= 4; /* space for 4 more */
5160 offset = NODESIZE + sizeof(indx_t) + data->mv_size;
5162 offset += offset & 1;
5163 fp_flags = fp->mp_flags;
5164 if (NODESIZE + sizeof(indx_t) + NODEKSZ(leaf) + NODEDSZ(leaf) +
5165 offset >= mc->mc_txn->mt_env->me_nodemax) {
5166 /* yes, convert it */
5168 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5169 dummy.md_pad = fp->mp_pad;
5170 dummy.md_flags = MDB_DUPFIXED;
5171 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
5172 dummy.md_flags |= MDB_INTEGERKEY;
5175 dummy.md_branch_pages = 0;
5176 dummy.md_leaf_pages = 1;
5177 dummy.md_overflow_pages = 0;
5178 dummy.md_entries = NUMKEYS(fp);
5180 xdata.mv_size = sizeof(MDB_db);
5181 xdata.mv_data = &dummy;
5182 if ((rc = mdb_page_alloc(mc, 1, &mp)))
5184 offset = mc->mc_txn->mt_env->me_psize - NODEDSZ(leaf);
5185 flags |= F_DUPDATA|F_SUBDATA;
5186 dummy.md_root = mp->mp_pgno;
5187 fp_flags &= ~P_SUBP;
5189 /* no, just grow it */
5191 xdata.mv_size = NODEDSZ(leaf) + offset;
5192 xdata.mv_data = &pbuf;
5193 mp = (MDB_page *)&pbuf;
5194 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
5197 mp->mp_flags = fp_flags | P_DIRTY;
5198 mp->mp_pad = fp->mp_pad;
5199 mp->mp_lower = fp->mp_lower;
5200 mp->mp_upper = fp->mp_upper + offset;
5202 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
5204 nsize = NODEDSZ(leaf) - fp->mp_upper;
5205 memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper, nsize);
5206 for (i=0; i<NUMKEYS(fp); i++)
5207 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
5209 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5213 /* data is on sub-DB, just store it */
5214 flags |= F_DUPDATA|F_SUBDATA;
5218 /* overflow page overwrites need special handling */
5219 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5222 unsigned psize = mc->mc_txn->mt_env->me_psize;
5223 int level, ovpages, dpages = OVPAGES(data->mv_size, psize);
5225 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
5226 if ((rc2 = mdb_page_get(mc->mc_txn, pg, &omp, &level)) != 0)
5228 ovpages = omp->mp_pages;
5230 /* Is the ov page writable and large enough? */
5231 if ((omp->mp_flags & P_DIRTY) && ovpages >= dpages) {
5232 /* yes, overwrite it. Note in this case we don't
5233 * bother to try shrinking the page if the new data
5234 * is smaller than the overflow threshold.
5237 /* It is writable only in a parent txn */
5238 size_t sz = (size_t) psize * ovpages, off;
5239 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
5245 mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
5246 if (!(flags & MDB_RESERVE)) {
5247 /* Copy end of page, adjusting alignment so
5248 * compiler may copy words instead of bytes.
5250 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
5251 memcpy((size_t *)((char *)np + off),
5252 (size_t *)((char *)omp + off), sz - off);
5255 memcpy(np, omp, sz); /* Copy beginning of page */
5258 SETDSZ(leaf, data->mv_size);
5259 if (F_ISSET(flags, MDB_RESERVE))
5260 data->mv_data = METADATA(omp);
5262 memcpy(METADATA(omp), data->mv_data, data->mv_size);
5265 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
5268 } else if (NODEDSZ(leaf) == data->mv_size) {
5269 /* same size, just replace it. Note that we could
5270 * also reuse this node if the new data is smaller,
5271 * but instead we opt to shrink the node in that case.
5273 if (F_ISSET(flags, MDB_RESERVE))
5274 data->mv_data = NODEDATA(leaf);
5275 else if (data->mv_size)
5276 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
5278 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
5281 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5282 mc->mc_db->md_entries--;
5284 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
5291 nflags = flags & NODE_ADD_FLAGS;
5292 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
5293 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
5294 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
5295 nflags &= ~MDB_APPEND;
5297 nflags |= MDB_SPLIT_REPLACE;
5298 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
5300 /* There is room already in this leaf page. */
5301 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
5302 if (rc == 0 && !do_sub && insert) {
5303 /* Adjust other cursors pointing to mp */
5304 MDB_cursor *m2, *m3;
5305 MDB_dbi dbi = mc->mc_dbi;
5306 unsigned i = mc->mc_top;
5307 MDB_page *mp = mc->mc_pg[i];
5309 if (mc->mc_flags & C_SUB)
5312 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5313 if (mc->mc_flags & C_SUB)
5314 m3 = &m2->mc_xcursor->mx_cursor;
5317 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
5318 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
5325 if (rc != MDB_SUCCESS)
5326 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5328 /* Now store the actual data in the child DB. Note that we're
5329 * storing the user data in the keys field, so there are strict
5330 * size limits on dupdata. The actual data fields of the child
5331 * DB are all zero size.
5338 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5339 if (flags & MDB_CURRENT) {
5340 xflags = MDB_CURRENT;
5342 mdb_xcursor_init1(mc, leaf);
5343 xflags = (flags & MDB_NODUPDATA) ? MDB_NOOVERWRITE : 0;
5345 /* converted, write the original data first */
5347 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
5351 /* Adjust other cursors pointing to mp */
5353 unsigned i = mc->mc_top;
5354 MDB_page *mp = mc->mc_pg[i];
5356 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5357 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
5358 if (!(m2->mc_flags & C_INITIALIZED)) continue;
5359 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
5360 mdb_xcursor_init1(m2, leaf);
5364 /* we've done our job */
5367 if (flags & MDB_APPENDDUP)
5368 xflags |= MDB_APPEND;
5369 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
5370 if (flags & F_SUBDATA) {
5371 void *db = NODEDATA(leaf);
5372 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
5375 /* sub-writes might have failed so check rc again.
5376 * Don't increment count if we just replaced an existing item.
5378 if (!rc && !(flags & MDB_CURRENT))
5379 mc->mc_db->md_entries++;
5380 if (flags & MDB_MULTIPLE) {
5383 if (mcount < dcount) {
5384 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
5385 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5389 /* let caller know how many succeeded, if any */
5390 data[1].mv_size = mcount;
5394 /* If we succeeded and the key didn't exist before, make sure
5395 * the cursor is marked valid.
5398 mc->mc_flags |= C_INITIALIZED;
5403 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
5408 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
5411 if (!(mc->mc_flags & C_INITIALIZED))
5414 rc = mdb_cursor_touch(mc);
5418 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5420 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5421 if (flags != MDB_NODUPDATA) {
5422 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
5423 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
5425 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
5426 /* If sub-DB still has entries, we're done */
5427 if (mc->mc_xcursor->mx_db.md_entries) {
5428 if (leaf->mn_flags & F_SUBDATA) {
5429 /* update subDB info */
5430 void *db = NODEDATA(leaf);
5431 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
5434 /* shrink fake page */
5435 mdb_node_shrink(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5436 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5437 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
5438 /* fix other sub-DB cursors pointed at this fake page */
5439 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5440 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
5441 if (m2->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top] &&
5442 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
5443 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
5446 mc->mc_db->md_entries--;
5449 /* otherwise fall thru and delete the sub-DB */
5452 if (leaf->mn_flags & F_SUBDATA) {
5453 /* add all the child DB's pages to the free list */
5454 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
5455 if (rc == MDB_SUCCESS) {
5456 mc->mc_db->md_entries -=
5457 mc->mc_xcursor->mx_db.md_entries;
5462 return mdb_cursor_del0(mc, leaf);
5465 /** Allocate and initialize new pages for a database.
5466 * @param[in] mc a cursor on the database being added to.
5467 * @param[in] flags flags defining what type of page is being allocated.
5468 * @param[in] num the number of pages to allocate. This is usually 1,
5469 * unless allocating overflow pages for a large record.
5470 * @param[out] mp Address of a page, or NULL on failure.
5471 * @return 0 on success, non-zero on failure.
5474 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
5479 if ((rc = mdb_page_alloc(mc, num, &np)))
5481 DPRINTF("allocated new mpage %zu, page size %u",
5482 np->mp_pgno, mc->mc_txn->mt_env->me_psize);
5483 np->mp_flags = flags | P_DIRTY;
5484 np->mp_lower = PAGEHDRSZ;
5485 np->mp_upper = mc->mc_txn->mt_env->me_psize;
5488 mc->mc_db->md_branch_pages++;
5489 else if (IS_LEAF(np))
5490 mc->mc_db->md_leaf_pages++;
5491 else if (IS_OVERFLOW(np)) {
5492 mc->mc_db->md_overflow_pages += num;
5500 /** Calculate the size of a leaf node.
5501 * The size depends on the environment's page size; if a data item
5502 * is too large it will be put onto an overflow page and the node
5503 * size will only include the key and not the data. Sizes are always
5504 * rounded up to an even number of bytes, to guarantee 2-byte alignment
5505 * of the #MDB_node headers.
5506 * @param[in] env The environment handle.
5507 * @param[in] key The key for the node.
5508 * @param[in] data The data for the node.
5509 * @return The number of bytes needed to store the node.
5512 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
5516 sz = LEAFSIZE(key, data);
5517 if (sz >= env->me_nodemax) {
5518 /* put on overflow page */
5519 sz -= data->mv_size - sizeof(pgno_t);
5523 return sz + sizeof(indx_t);
5526 /** Calculate the size of a branch node.
5527 * The size should depend on the environment's page size but since
5528 * we currently don't support spilling large keys onto overflow
5529 * pages, it's simply the size of the #MDB_node header plus the
5530 * size of the key. Sizes are always rounded up to an even number
5531 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
5532 * @param[in] env The environment handle.
5533 * @param[in] key The key for the node.
5534 * @return The number of bytes needed to store the node.
5537 mdb_branch_size(MDB_env *env, MDB_val *key)
5542 if (sz >= env->me_nodemax) {
5543 /* put on overflow page */
5544 /* not implemented */
5545 /* sz -= key->size - sizeof(pgno_t); */
5548 return sz + sizeof(indx_t);
5551 /** Add a node to the page pointed to by the cursor.
5552 * @param[in] mc The cursor for this operation.
5553 * @param[in] indx The index on the page where the new node should be added.
5554 * @param[in] key The key for the new node.
5555 * @param[in] data The data for the new node, if any.
5556 * @param[in] pgno The page number, if adding a branch node.
5557 * @param[in] flags Flags for the node.
5558 * @return 0 on success, non-zero on failure. Possible errors are:
5560 * <li>ENOMEM - failed to allocate overflow pages for the node.
5561 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
5562 * should never happen since all callers already calculate the
5563 * page's free space before calling this function.
5567 mdb_node_add(MDB_cursor *mc, indx_t indx,
5568 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
5571 size_t node_size = NODESIZE;
5574 MDB_page *mp = mc->mc_pg[mc->mc_top];
5575 MDB_page *ofp = NULL; /* overflow page */
5578 assert(mp->mp_upper >= mp->mp_lower);
5580 DPRINTF("add to %s %spage %zu index %i, data size %zu key size %zu [%s]",
5581 IS_LEAF(mp) ? "leaf" : "branch",
5582 IS_SUBP(mp) ? "sub-" : "",
5583 mp->mp_pgno, indx, data ? data->mv_size : 0,
5584 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
5587 /* Move higher keys up one slot. */
5588 int ksize = mc->mc_db->md_pad, dif;
5589 char *ptr = LEAF2KEY(mp, indx, ksize);
5590 dif = NUMKEYS(mp) - indx;
5592 memmove(ptr+ksize, ptr, dif*ksize);
5593 /* insert new key */
5594 memcpy(ptr, key->mv_data, ksize);
5596 /* Just using these for counting */
5597 mp->mp_lower += sizeof(indx_t);
5598 mp->mp_upper -= ksize - sizeof(indx_t);
5603 node_size += key->mv_size;
5607 if (F_ISSET(flags, F_BIGDATA)) {
5608 /* Data already on overflow page. */
5609 node_size += sizeof(pgno_t);
5610 } else if (node_size + data->mv_size >= mc->mc_txn->mt_env->me_nodemax) {
5611 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
5613 /* Put data on overflow page. */
5614 DPRINTF("data size is %zu, node would be %zu, put data on overflow page",
5615 data->mv_size, node_size+data->mv_size);
5616 node_size += sizeof(pgno_t);
5617 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
5619 DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
5622 node_size += data->mv_size;
5625 node_size += node_size & 1;
5627 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
5628 DPRINTF("not enough room in page %zu, got %u ptrs",
5629 mp->mp_pgno, NUMKEYS(mp));
5630 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
5631 mp->mp_upper - mp->mp_lower);
5632 DPRINTF("node size = %zu", node_size);
5633 return MDB_PAGE_FULL;
5636 /* Move higher pointers up one slot. */
5637 for (i = NUMKEYS(mp); i > indx; i--)
5638 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
5640 /* Adjust free space offsets. */
5641 ofs = mp->mp_upper - node_size;
5642 assert(ofs >= mp->mp_lower + sizeof(indx_t));
5643 mp->mp_ptrs[indx] = ofs;
5645 mp->mp_lower += sizeof(indx_t);
5647 /* Write the node data. */
5648 node = NODEPTR(mp, indx);
5649 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
5650 node->mn_flags = flags;
5652 SETDSZ(node,data->mv_size);
5657 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
5662 if (F_ISSET(flags, F_BIGDATA))
5663 memcpy(node->mn_data + key->mv_size, data->mv_data,
5665 else if (F_ISSET(flags, MDB_RESERVE))
5666 data->mv_data = node->mn_data + key->mv_size;
5668 memcpy(node->mn_data + key->mv_size, data->mv_data,
5671 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
5673 if (F_ISSET(flags, MDB_RESERVE))
5674 data->mv_data = METADATA(ofp);
5676 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
5683 /** Delete the specified node from a page.
5684 * @param[in] mp The page to operate on.
5685 * @param[in] indx The index of the node to delete.
5686 * @param[in] ksize The size of a node. Only used if the page is
5687 * part of a #MDB_DUPFIXED database.
5690 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
5693 indx_t i, j, numkeys, ptr;
5700 COPY_PGNO(pgno, mp->mp_pgno);
5701 DPRINTF("delete node %u on %s page %zu", indx,
5702 IS_LEAF(mp) ? "leaf" : "branch", pgno);
5705 assert(indx < NUMKEYS(mp));
5708 int x = NUMKEYS(mp) - 1 - indx;
5709 base = LEAF2KEY(mp, indx, ksize);
5711 memmove(base, base + ksize, x * ksize);
5712 mp->mp_lower -= sizeof(indx_t);
5713 mp->mp_upper += ksize - sizeof(indx_t);
5717 node = NODEPTR(mp, indx);
5718 sz = NODESIZE + node->mn_ksize;
5720 if (F_ISSET(node->mn_flags, F_BIGDATA))
5721 sz += sizeof(pgno_t);
5723 sz += NODEDSZ(node);
5727 ptr = mp->mp_ptrs[indx];
5728 numkeys = NUMKEYS(mp);
5729 for (i = j = 0; i < numkeys; i++) {
5731 mp->mp_ptrs[j] = mp->mp_ptrs[i];
5732 if (mp->mp_ptrs[i] < ptr)
5733 mp->mp_ptrs[j] += sz;
5738 base = (char *)mp + mp->mp_upper;
5739 memmove(base + sz, base, ptr - mp->mp_upper);
5741 mp->mp_lower -= sizeof(indx_t);
5745 /** Compact the main page after deleting a node on a subpage.
5746 * @param[in] mp The main page to operate on.
5747 * @param[in] indx The index of the subpage on the main page.
5750 mdb_node_shrink(MDB_page *mp, indx_t indx)
5757 indx_t i, numkeys, ptr;
5759 node = NODEPTR(mp, indx);
5760 sp = (MDB_page *)NODEDATA(node);
5761 osize = NODEDSZ(node);
5763 delta = sp->mp_upper - sp->mp_lower;
5764 SETDSZ(node, osize - delta);
5765 xp = (MDB_page *)((char *)sp + delta);
5767 /* shift subpage upward */
5769 nsize = NUMKEYS(sp) * sp->mp_pad;
5770 memmove(METADATA(xp), METADATA(sp), nsize);
5773 nsize = osize - sp->mp_upper;
5774 numkeys = NUMKEYS(sp);
5775 for (i=numkeys-1; i>=0; i--)
5776 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
5778 xp->mp_upper = sp->mp_lower;
5779 xp->mp_lower = sp->mp_lower;
5780 xp->mp_flags = sp->mp_flags;
5781 xp->mp_pad = sp->mp_pad;
5782 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
5784 /* shift lower nodes upward */
5785 ptr = mp->mp_ptrs[indx];
5786 numkeys = NUMKEYS(mp);
5787 for (i = 0; i < numkeys; i++) {
5788 if (mp->mp_ptrs[i] <= ptr)
5789 mp->mp_ptrs[i] += delta;
5792 base = (char *)mp + mp->mp_upper;
5793 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
5794 mp->mp_upper += delta;
5797 /** Initial setup of a sorted-dups cursor.
5798 * Sorted duplicates are implemented as a sub-database for the given key.
5799 * The duplicate data items are actually keys of the sub-database.
5800 * Operations on the duplicate data items are performed using a sub-cursor
5801 * initialized when the sub-database is first accessed. This function does
5802 * the preliminary setup of the sub-cursor, filling in the fields that
5803 * depend only on the parent DB.
5804 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
5807 mdb_xcursor_init0(MDB_cursor *mc)
5809 MDB_xcursor *mx = mc->mc_xcursor;
5811 mx->mx_cursor.mc_xcursor = NULL;
5812 mx->mx_cursor.mc_txn = mc->mc_txn;
5813 mx->mx_cursor.mc_db = &mx->mx_db;
5814 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
5815 mx->mx_cursor.mc_dbi = mc->mc_dbi+1;
5816 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
5817 mx->mx_cursor.mc_snum = 0;
5818 mx->mx_cursor.mc_top = 0;
5819 mx->mx_cursor.mc_flags = C_SUB;
5820 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
5821 mx->mx_dbx.md_dcmp = NULL;
5822 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
5825 /** Final setup of a sorted-dups cursor.
5826 * Sets up the fields that depend on the data from the main cursor.
5827 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
5828 * @param[in] node The data containing the #MDB_db record for the
5829 * sorted-dup database.
5832 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
5834 MDB_xcursor *mx = mc->mc_xcursor;
5836 if (node->mn_flags & F_SUBDATA) {
5837 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
5838 mx->mx_cursor.mc_pg[0] = 0;
5839 mx->mx_cursor.mc_snum = 0;
5840 mx->mx_cursor.mc_flags = C_SUB;
5842 MDB_page *fp = NODEDATA(node);
5843 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
5844 mx->mx_db.md_flags = 0;
5845 mx->mx_db.md_depth = 1;
5846 mx->mx_db.md_branch_pages = 0;
5847 mx->mx_db.md_leaf_pages = 1;
5848 mx->mx_db.md_overflow_pages = 0;
5849 mx->mx_db.md_entries = NUMKEYS(fp);
5850 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
5851 mx->mx_cursor.mc_snum = 1;
5852 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
5853 mx->mx_cursor.mc_top = 0;
5854 mx->mx_cursor.mc_pg[0] = fp;
5855 mx->mx_cursor.mc_ki[0] = 0;
5856 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5857 mx->mx_db.md_flags = MDB_DUPFIXED;
5858 mx->mx_db.md_pad = fp->mp_pad;
5859 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
5860 mx->mx_db.md_flags |= MDB_INTEGERKEY;
5863 DPRINTF("Sub-db %u for db %u root page %zu", mx->mx_cursor.mc_dbi, mc->mc_dbi,
5865 mx->mx_dbflag = DB_VALID | (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY) ?
5867 mx->mx_dbx.md_name.mv_data = NODEKEY(node);
5868 mx->mx_dbx.md_name.mv_size = node->mn_ksize;
5869 #if UINT_MAX < SIZE_MAX
5870 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
5871 #ifdef MISALIGNED_OK
5872 mx->mx_dbx.md_cmp = mdb_cmp_long;
5874 mx->mx_dbx.md_cmp = mdb_cmp_cint;
5879 /** Initialize a cursor for a given transaction and database. */
5881 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
5883 mc->mc_backup = NULL;
5886 mc->mc_db = &txn->mt_dbs[dbi];
5887 mc->mc_dbx = &txn->mt_dbxs[dbi];
5888 mc->mc_dbflag = &txn->mt_dbflags[dbi];
5893 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
5895 mc->mc_xcursor = mx;
5896 mdb_xcursor_init0(mc);
5898 mc->mc_xcursor = NULL;
5900 if (*mc->mc_dbflag & DB_STALE) {
5901 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
5906 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
5909 size_t size = sizeof(MDB_cursor);
5911 if (txn == NULL || ret == NULL || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
5914 /* Allow read access to the freelist */
5915 if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
5918 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
5919 size += sizeof(MDB_xcursor);
5921 if ((mc = malloc(size)) != NULL) {
5922 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
5923 if (txn->mt_cursors) {
5924 mc->mc_next = txn->mt_cursors[dbi];
5925 txn->mt_cursors[dbi] = mc;
5926 mc->mc_flags |= C_UNTRACK;
5938 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
5940 if (txn == NULL || mc == NULL || mc->mc_dbi >= txn->mt_numdbs)
5943 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
5946 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
5950 /* Return the count of duplicate data items for the current key */
5952 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
5956 if (mc == NULL || countp == NULL)
5959 if (!(mc->mc_db->md_flags & MDB_DUPSORT))
5962 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5963 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5966 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
5969 *countp = mc->mc_xcursor->mx_db.md_entries;
5975 mdb_cursor_close(MDB_cursor *mc)
5977 if (mc && !mc->mc_backup) {
5978 /* remove from txn, if tracked */
5979 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
5980 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
5981 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
5983 *prev = mc->mc_next;
5990 mdb_cursor_txn(MDB_cursor *mc)
5992 if (!mc) return NULL;
5997 mdb_cursor_dbi(MDB_cursor *mc)
6003 /** Replace the key for a node with a new key.
6004 * @param[in] mc Cursor pointing to the node to operate on.
6005 * @param[in] key The new key to use.
6006 * @return 0 on success, non-zero on failure.
6009 mdb_update_key(MDB_cursor *mc, MDB_val *key)
6016 indx_t ptr, i, numkeys, indx;
6019 indx = mc->mc_ki[mc->mc_top];
6020 mp = mc->mc_pg[mc->mc_top];
6021 node = NODEPTR(mp, indx);
6022 ptr = mp->mp_ptrs[indx];
6026 char kbuf2[(MDB_MAXKEYSIZE*2+1)];
6027 k2.mv_data = NODEKEY(node);
6028 k2.mv_size = node->mn_ksize;
6029 DPRINTF("update key %u (ofs %u) [%s] to [%s] on page %zu",
6031 mdb_dkey(&k2, kbuf2),
6037 delta0 = delta = key->mv_size - node->mn_ksize;
6039 /* Must be 2-byte aligned. If new key is
6040 * shorter by 1, the shift will be skipped.
6042 delta += (delta & 1);
6044 if (delta > 0 && SIZELEFT(mp) < delta) {
6046 /* not enough space left, do a delete and split */
6047 DPRINTF("Not enough room, delta = %d, splitting...", delta);
6048 pgno = NODEPGNO(node);
6049 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
6050 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
6053 numkeys = NUMKEYS(mp);
6054 for (i = 0; i < numkeys; i++) {
6055 if (mp->mp_ptrs[i] <= ptr)
6056 mp->mp_ptrs[i] -= delta;
6059 base = (char *)mp + mp->mp_upper;
6060 len = ptr - mp->mp_upper + NODESIZE;
6061 memmove(base - delta, base, len);
6062 mp->mp_upper -= delta;
6064 node = NODEPTR(mp, indx);
6067 /* But even if no shift was needed, update ksize */
6069 node->mn_ksize = key->mv_size;
6072 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6078 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
6080 /** Move a node from csrc to cdst.
6083 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
6090 unsigned short flags;
6094 /* Mark src and dst as dirty. */
6095 if ((rc = mdb_page_touch(csrc)) ||
6096 (rc = mdb_page_touch(cdst)))
6099 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6100 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
6101 key.mv_size = csrc->mc_db->md_pad;
6102 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
6104 data.mv_data = NULL;
6108 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
6109 assert(!((long)srcnode&1));
6110 srcpg = NODEPGNO(srcnode);
6111 flags = srcnode->mn_flags;
6112 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6113 unsigned int snum = csrc->mc_snum;
6115 /* must find the lowest key below src */
6116 mdb_page_search_lowest(csrc);
6117 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6118 key.mv_size = csrc->mc_db->md_pad;
6119 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6121 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6122 key.mv_size = NODEKSZ(s2);
6123 key.mv_data = NODEKEY(s2);
6125 csrc->mc_snum = snum--;
6126 csrc->mc_top = snum;
6128 key.mv_size = NODEKSZ(srcnode);
6129 key.mv_data = NODEKEY(srcnode);
6131 data.mv_size = NODEDSZ(srcnode);
6132 data.mv_data = NODEDATA(srcnode);
6134 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
6135 unsigned int snum = cdst->mc_snum;
6138 /* must find the lowest key below dst */
6139 mdb_page_search_lowest(cdst);
6140 if (IS_LEAF2(cdst->mc_pg[cdst->mc_top])) {
6141 bkey.mv_size = cdst->mc_db->md_pad;
6142 bkey.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, bkey.mv_size);
6144 s2 = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
6145 bkey.mv_size = NODEKSZ(s2);
6146 bkey.mv_data = NODEKEY(s2);
6148 cdst->mc_snum = snum--;
6149 cdst->mc_top = snum;
6150 mdb_cursor_copy(cdst, &mn);
6152 rc = mdb_update_key(&mn, &bkey);
6157 DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
6158 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
6159 csrc->mc_ki[csrc->mc_top],
6161 csrc->mc_pg[csrc->mc_top]->mp_pgno,
6162 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
6164 /* Add the node to the destination page.
6166 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
6167 if (rc != MDB_SUCCESS)
6170 /* Delete the node from the source page.
6172 mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
6175 /* Adjust other cursors pointing to mp */
6176 MDB_cursor *m2, *m3;
6177 MDB_dbi dbi = csrc->mc_dbi;
6178 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
6180 if (csrc->mc_flags & C_SUB)
6183 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6184 if (csrc->mc_flags & C_SUB)
6185 m3 = &m2->mc_xcursor->mx_cursor;
6188 if (m3 == csrc) continue;
6189 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
6190 csrc->mc_ki[csrc->mc_top]) {
6191 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
6192 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
6197 /* Update the parent separators.
6199 if (csrc->mc_ki[csrc->mc_top] == 0) {
6200 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
6201 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6202 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6204 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6205 key.mv_size = NODEKSZ(srcnode);
6206 key.mv_data = NODEKEY(srcnode);
6208 DPRINTF("update separator for source page %zu to [%s]",
6209 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
6210 mdb_cursor_copy(csrc, &mn);
6213 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
6216 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6218 indx_t ix = csrc->mc_ki[csrc->mc_top];
6219 nullkey.mv_size = 0;
6220 csrc->mc_ki[csrc->mc_top] = 0;
6221 rc = mdb_update_key(csrc, &nullkey);
6222 csrc->mc_ki[csrc->mc_top] = ix;
6223 assert(rc == MDB_SUCCESS);
6227 if (cdst->mc_ki[cdst->mc_top] == 0) {
6228 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
6229 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6230 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
6232 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
6233 key.mv_size = NODEKSZ(srcnode);
6234 key.mv_data = NODEKEY(srcnode);
6236 DPRINTF("update separator for destination page %zu to [%s]",
6237 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
6238 mdb_cursor_copy(cdst, &mn);
6241 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
6244 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
6246 indx_t ix = cdst->mc_ki[cdst->mc_top];
6247 nullkey.mv_size = 0;
6248 cdst->mc_ki[cdst->mc_top] = 0;
6249 rc = mdb_update_key(cdst, &nullkey);
6250 cdst->mc_ki[cdst->mc_top] = ix;
6251 assert(rc == MDB_SUCCESS);
6258 /** Merge one page into another.
6259 * The nodes from the page pointed to by \b csrc will
6260 * be copied to the page pointed to by \b cdst and then
6261 * the \b csrc page will be freed.
6262 * @param[in] csrc Cursor pointing to the source page.
6263 * @param[in] cdst Cursor pointing to the destination page.
6266 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
6274 DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
6275 cdst->mc_pg[cdst->mc_top]->mp_pgno);
6277 assert(csrc->mc_snum > 1); /* can't merge root page */
6278 assert(cdst->mc_snum > 1);
6280 /* Mark dst as dirty. */
6281 if ((rc = mdb_page_touch(cdst)))
6284 /* Move all nodes from src to dst.
6286 j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
6287 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6288 key.mv_size = csrc->mc_db->md_pad;
6289 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
6290 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
6291 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
6292 if (rc != MDB_SUCCESS)
6294 key.mv_data = (char *)key.mv_data + key.mv_size;
6297 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
6298 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
6299 if (i == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6300 unsigned int snum = csrc->mc_snum;
6302 /* must find the lowest key below src */
6303 mdb_page_search_lowest(csrc);
6304 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6305 key.mv_size = csrc->mc_db->md_pad;
6306 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6308 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6309 key.mv_size = NODEKSZ(s2);
6310 key.mv_data = NODEKEY(s2);
6312 csrc->mc_snum = snum--;
6313 csrc->mc_top = snum;
6315 key.mv_size = srcnode->mn_ksize;
6316 key.mv_data = NODEKEY(srcnode);
6319 data.mv_size = NODEDSZ(srcnode);
6320 data.mv_data = NODEDATA(srcnode);
6321 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
6322 if (rc != MDB_SUCCESS)
6327 DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
6328 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);
6330 /* Unlink the src page from parent and add to free list.
6332 mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
6333 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
6336 rc = mdb_update_key(csrc, &key);
6342 rc = mdb_midl_append(&csrc->mc_txn->mt_free_pgs,
6343 csrc->mc_pg[csrc->mc_top]->mp_pgno);
6346 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
6347 csrc->mc_db->md_leaf_pages--;
6349 csrc->mc_db->md_branch_pages--;
6351 /* Adjust other cursors pointing to mp */
6352 MDB_cursor *m2, *m3;
6353 MDB_dbi dbi = csrc->mc_dbi;
6354 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
6356 if (csrc->mc_flags & C_SUB)
6359 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6360 if (csrc->mc_flags & C_SUB)
6361 m3 = &m2->mc_xcursor->mx_cursor;
6364 if (m3 == csrc) continue;
6365 if (m3->mc_snum < csrc->mc_snum) continue;
6366 if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
6367 m3->mc_pg[csrc->mc_top] = mp;
6368 m3->mc_ki[csrc->mc_top] += nkeys;
6372 mdb_cursor_pop(csrc);
6374 return mdb_rebalance(csrc);
6377 /** Copy the contents of a cursor.
6378 * @param[in] csrc The cursor to copy from.
6379 * @param[out] cdst The cursor to copy to.
6382 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
6386 cdst->mc_txn = csrc->mc_txn;
6387 cdst->mc_dbi = csrc->mc_dbi;
6388 cdst->mc_db = csrc->mc_db;
6389 cdst->mc_dbx = csrc->mc_dbx;
6390 cdst->mc_snum = csrc->mc_snum;
6391 cdst->mc_top = csrc->mc_top;
6392 cdst->mc_flags = csrc->mc_flags;
6394 for (i=0; i<csrc->mc_snum; i++) {
6395 cdst->mc_pg[i] = csrc->mc_pg[i];
6396 cdst->mc_ki[i] = csrc->mc_ki[i];
6400 /** Rebalance the tree after a delete operation.
6401 * @param[in] mc Cursor pointing to the page where rebalancing
6403 * @return 0 on success, non-zero on failure.
6406 mdb_rebalance(MDB_cursor *mc)
6410 unsigned int ptop, minkeys;
6413 minkeys = 1 + (IS_BRANCH(mc->mc_pg[mc->mc_top]));
6417 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
6418 DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
6419 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
6420 pgno, NUMKEYS(mc->mc_pg[mc->mc_top]), (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10);
6424 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD &&
6425 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
6428 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
6429 DPRINTF("no need to rebalance page %zu, above fill threshold",
6435 if (mc->mc_snum < 2) {
6436 MDB_page *mp = mc->mc_pg[0];
6438 DPUTS("Can't rebalance a subpage, ignoring");
6441 if (NUMKEYS(mp) == 0) {
6442 DPUTS("tree is completely empty");
6443 mc->mc_db->md_root = P_INVALID;
6444 mc->mc_db->md_depth = 0;
6445 mc->mc_db->md_leaf_pages = 0;
6446 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
6449 /* Adjust cursors pointing to mp */
6453 MDB_cursor *m2, *m3;
6454 MDB_dbi dbi = mc->mc_dbi;
6456 if (mc->mc_flags & C_SUB)
6459 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6460 if (mc->mc_flags & C_SUB)
6461 m3 = &m2->mc_xcursor->mx_cursor;
6464 if (m3->mc_snum < mc->mc_snum) continue;
6465 if (m3->mc_pg[0] == mp) {
6471 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
6472 DPUTS("collapsing root page!");
6473 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
6476 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
6477 rc = mdb_page_get(mc->mc_txn,mc->mc_db->md_root,&mc->mc_pg[0],NULL);
6480 mc->mc_db->md_depth--;
6481 mc->mc_db->md_branch_pages--;
6482 mc->mc_ki[0] = mc->mc_ki[1];
6484 /* Adjust other cursors pointing to mp */
6485 MDB_cursor *m2, *m3;
6486 MDB_dbi dbi = mc->mc_dbi;
6488 if (mc->mc_flags & C_SUB)
6491 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6492 if (mc->mc_flags & C_SUB)
6493 m3 = &m2->mc_xcursor->mx_cursor;
6496 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
6497 if (m3->mc_pg[0] == mp) {
6498 m3->mc_pg[0] = mc->mc_pg[0];
6501 m3->mc_ki[0] = m3->mc_ki[1];
6506 DPUTS("root page doesn't need rebalancing");
6510 /* The parent (branch page) must have at least 2 pointers,
6511 * otherwise the tree is invalid.
6513 ptop = mc->mc_top-1;
6514 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
6516 /* Leaf page fill factor is below the threshold.
6517 * Try to move keys from left or right neighbor, or
6518 * merge with a neighbor page.
6523 mdb_cursor_copy(mc, &mn);
6524 mn.mc_xcursor = NULL;
6526 if (mc->mc_ki[ptop] == 0) {
6527 /* We're the leftmost leaf in our parent.
6529 DPUTS("reading right neighbor");
6531 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
6532 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
6535 mn.mc_ki[mn.mc_top] = 0;
6536 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
6538 /* There is at least one neighbor to the left.
6540 DPUTS("reading left neighbor");
6542 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
6543 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
6546 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
6547 mc->mc_ki[mc->mc_top] = 0;
6550 DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
6551 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);
6553 /* If the neighbor page is above threshold and has enough keys,
6554 * move one key from it. Otherwise we should try to merge them.
6555 * (A branch page must never have less than 2 keys.)
6557 minkeys = 1 + (IS_BRANCH(mn.mc_pg[mn.mc_top]));
6558 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys)
6559 return mdb_node_move(&mn, mc);
6561 if (mc->mc_ki[ptop] == 0)
6562 rc = mdb_page_merge(&mn, mc);
6564 rc = mdb_page_merge(mc, &mn);
6565 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
6570 /** Complete a delete operation started by #mdb_cursor_del(). */
6572 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
6578 mp = mc->mc_pg[mc->mc_top];
6579 ki = mc->mc_ki[mc->mc_top];
6581 /* add overflow pages to free list */
6582 if (!IS_LEAF2(mp) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6586 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
6587 if ((rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL)) ||
6588 (rc = mdb_ovpage_free(mc, omp)))
6591 mdb_node_del(mp, ki, mc->mc_db->md_pad);
6592 mc->mc_db->md_entries--;
6593 rc = mdb_rebalance(mc);
6594 if (rc != MDB_SUCCESS)
6595 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6596 /* if mc points past last node in page, invalidate */
6597 else if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6598 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
6601 /* Adjust other cursors pointing to mp */
6604 MDB_dbi dbi = mc->mc_dbi;
6606 mp = mc->mc_pg[mc->mc_top];
6607 nkeys = NUMKEYS(mp);
6608 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6611 if (!(m2->mc_flags & C_INITIALIZED))
6613 if (m2->mc_pg[mc->mc_top] == mp) {
6614 if (m2->mc_ki[mc->mc_top] > ki)
6615 m2->mc_ki[mc->mc_top]--;
6616 if (m2->mc_ki[mc->mc_top] >= nkeys)
6617 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
6626 mdb_del(MDB_txn *txn, MDB_dbi dbi,
6627 MDB_val *key, MDB_val *data)
6632 MDB_val rdata, *xdata;
6636 assert(key != NULL);
6638 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
6640 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
6643 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
6647 if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
6651 mdb_cursor_init(&mc, txn, dbi, &mx);
6662 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
6664 /* let mdb_page_split know about this cursor if needed:
6665 * delete will trigger a rebalance; if it needs to move
6666 * a node from one page to another, it will have to
6667 * update the parent's separator key(s). If the new sepkey
6668 * is larger than the current one, the parent page may
6669 * run out of space, triggering a split. We need this
6670 * cursor to be consistent until the end of the rebalance.
6672 mc.mc_flags |= C_UNTRACK;
6673 mc.mc_next = txn->mt_cursors[dbi];
6674 txn->mt_cursors[dbi] = &mc;
6675 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
6676 txn->mt_cursors[dbi] = mc.mc_next;
6681 /** Split a page and insert a new node.
6682 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
6683 * The cursor will be updated to point to the actual page and index where
6684 * the node got inserted after the split.
6685 * @param[in] newkey The key for the newly inserted node.
6686 * @param[in] newdata The data for the newly inserted node.
6687 * @param[in] newpgno The page number, if the new node is a branch node.
6688 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
6689 * @return 0 on success, non-zero on failure.
6692 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
6693 unsigned int nflags)
6696 int rc = MDB_SUCCESS, ins_new = 0, new_root = 0, newpos = 1, did_split = 0;
6699 unsigned int i, j, split_indx, nkeys, pmax;
6701 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
6703 MDB_page *mp, *rp, *pp;
6708 mp = mc->mc_pg[mc->mc_top];
6709 newindx = mc->mc_ki[mc->mc_top];
6711 DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
6712 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
6713 DKEY(newkey), mc->mc_ki[mc->mc_top]);
6715 /* Create a right sibling. */
6716 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
6718 DPRINTF("new right sibling: page %zu", rp->mp_pgno);
6720 if (mc->mc_snum < 2) {
6721 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
6723 /* shift current top to make room for new parent */
6724 mc->mc_pg[1] = mc->mc_pg[0];
6725 mc->mc_ki[1] = mc->mc_ki[0];
6728 mc->mc_db->md_root = pp->mp_pgno;
6729 DPRINTF("root split! new root = %zu", pp->mp_pgno);
6730 mc->mc_db->md_depth++;
6733 /* Add left (implicit) pointer. */
6734 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
6735 /* undo the pre-push */
6736 mc->mc_pg[0] = mc->mc_pg[1];
6737 mc->mc_ki[0] = mc->mc_ki[1];
6738 mc->mc_db->md_root = mp->mp_pgno;
6739 mc->mc_db->md_depth--;
6746 ptop = mc->mc_top-1;
6747 DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
6750 mc->mc_flags |= C_SPLITTING;
6751 mdb_cursor_copy(mc, &mn);
6752 mn.mc_pg[mn.mc_top] = rp;
6753 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
6755 if (nflags & MDB_APPEND) {
6756 mn.mc_ki[mn.mc_top] = 0;
6758 split_indx = newindx;
6763 nkeys = NUMKEYS(mp);
6764 split_indx = nkeys / 2;
6765 if (newindx < split_indx)
6771 unsigned int lsize, rsize, ksize;
6772 /* Move half of the keys to the right sibling */
6774 x = mc->mc_ki[mc->mc_top] - split_indx;
6775 ksize = mc->mc_db->md_pad;
6776 split = LEAF2KEY(mp, split_indx, ksize);
6777 rsize = (nkeys - split_indx) * ksize;
6778 lsize = (nkeys - split_indx) * sizeof(indx_t);
6779 mp->mp_lower -= lsize;
6780 rp->mp_lower += lsize;
6781 mp->mp_upper += rsize - lsize;
6782 rp->mp_upper -= rsize - lsize;
6783 sepkey.mv_size = ksize;
6784 if (newindx == split_indx) {
6785 sepkey.mv_data = newkey->mv_data;
6787 sepkey.mv_data = split;
6790 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
6791 memcpy(rp->mp_ptrs, split, rsize);
6792 sepkey.mv_data = rp->mp_ptrs;
6793 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
6794 memcpy(ins, newkey->mv_data, ksize);
6795 mp->mp_lower += sizeof(indx_t);
6796 mp->mp_upper -= ksize - sizeof(indx_t);
6799 memcpy(rp->mp_ptrs, split, x * ksize);
6800 ins = LEAF2KEY(rp, x, ksize);
6801 memcpy(ins, newkey->mv_data, ksize);
6802 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
6803 rp->mp_lower += sizeof(indx_t);
6804 rp->mp_upper -= ksize - sizeof(indx_t);
6805 mc->mc_ki[mc->mc_top] = x;
6806 mc->mc_pg[mc->mc_top] = rp;
6811 /* For leaf pages, check the split point based on what
6812 * fits where, since otherwise mdb_node_add can fail.
6814 * This check is only needed when the data items are
6815 * relatively large, such that being off by one will
6816 * make the difference between success or failure.
6818 * It's also relevant if a page happens to be laid out
6819 * such that one half of its nodes are all "small" and
6820 * the other half of its nodes are "large." If the new
6821 * item is also "large" and falls on the half with
6822 * "large" nodes, it also may not fit.
6825 unsigned int psize, nsize;
6826 /* Maximum free space in an empty page */
6827 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
6828 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
6829 if ((nkeys < 20) || (nsize > pmax/16)) {
6830 if (newindx <= split_indx) {
6833 for (i=0; i<split_indx; i++) {
6834 node = NODEPTR(mp, i);
6835 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
6836 if (F_ISSET(node->mn_flags, F_BIGDATA))
6837 psize += sizeof(pgno_t);
6839 psize += NODEDSZ(node);
6843 split_indx = newindx;
6854 for (i=nkeys-1; i>=split_indx; i--) {
6855 node = NODEPTR(mp, i);
6856 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
6857 if (F_ISSET(node->mn_flags, F_BIGDATA))
6858 psize += sizeof(pgno_t);
6860 psize += NODEDSZ(node);
6864 split_indx = newindx;
6875 /* First find the separating key between the split pages.
6876 * The case where newindx == split_indx is ambiguous; the
6877 * new item could go to the new page or stay on the original
6878 * page. If newpos == 1 it goes to the new page.
6880 if (newindx == split_indx && newpos) {
6881 sepkey.mv_size = newkey->mv_size;
6882 sepkey.mv_data = newkey->mv_data;
6884 node = NODEPTR(mp, split_indx);
6885 sepkey.mv_size = node->mn_ksize;
6886 sepkey.mv_data = NODEKEY(node);
6890 DPRINTF("separator is [%s]", DKEY(&sepkey));
6892 /* Copy separator key to the parent.
6894 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
6898 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
6901 if (mn.mc_snum == mc->mc_snum) {
6902 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
6903 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
6904 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
6905 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
6910 /* Right page might now have changed parent.
6911 * Check if left page also changed parent.
6913 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
6914 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
6915 for (i=0; i<ptop; i++) {
6916 mc->mc_pg[i] = mn.mc_pg[i];
6917 mc->mc_ki[i] = mn.mc_ki[i];
6919 mc->mc_pg[ptop] = mn.mc_pg[ptop];
6920 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
6924 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
6927 mc->mc_flags ^= C_SPLITTING;
6928 if (rc != MDB_SUCCESS) {
6931 if (nflags & MDB_APPEND) {
6932 mc->mc_pg[mc->mc_top] = rp;
6933 mc->mc_ki[mc->mc_top] = 0;
6934 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
6937 for (i=0; i<mc->mc_top; i++)
6938 mc->mc_ki[i] = mn.mc_ki[i];
6945 /* Move half of the keys to the right sibling. */
6947 /* grab a page to hold a temporary copy */
6948 copy = mdb_page_malloc(mc->mc_txn, 1);
6952 copy->mp_pgno = mp->mp_pgno;
6953 copy->mp_flags = mp->mp_flags;
6954 copy->mp_lower = PAGEHDRSZ;
6955 copy->mp_upper = mc->mc_txn->mt_env->me_psize;
6956 mc->mc_pg[mc->mc_top] = copy;
6957 for (i = j = 0; i <= nkeys; j++) {
6958 if (i == split_indx) {
6959 /* Insert in right sibling. */
6960 /* Reset insert index for right sibling. */
6961 if (i != newindx || (newpos ^ ins_new)) {
6963 mc->mc_pg[mc->mc_top] = rp;
6967 if (i == newindx && !ins_new) {
6968 /* Insert the original entry that caused the split. */
6969 rkey.mv_data = newkey->mv_data;
6970 rkey.mv_size = newkey->mv_size;
6979 /* Update index for the new key. */
6980 mc->mc_ki[mc->mc_top] = j;
6981 } else if (i == nkeys) {
6984 node = NODEPTR(mp, i);
6985 rkey.mv_data = NODEKEY(node);
6986 rkey.mv_size = node->mn_ksize;
6988 xdata.mv_data = NODEDATA(node);
6989 xdata.mv_size = NODEDSZ(node);
6992 pgno = NODEPGNO(node);
6993 flags = node->mn_flags;
6998 if (!IS_LEAF(mp) && j == 0) {
6999 /* First branch index doesn't need key data. */
7003 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
7007 nkeys = NUMKEYS(copy);
7008 for (i=0; i<nkeys; i++)
7009 mp->mp_ptrs[i] = copy->mp_ptrs[i];
7010 mp->mp_lower = copy->mp_lower;
7011 mp->mp_upper = copy->mp_upper;
7012 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
7013 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
7015 /* reset back to original page */
7016 if (newindx < split_indx || (!newpos && newindx == split_indx)) {
7017 mc->mc_pg[mc->mc_top] = mp;
7018 if (nflags & MDB_RESERVE) {
7019 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7020 if (!(node->mn_flags & F_BIGDATA))
7021 newdata->mv_data = NODEDATA(node);
7025 /* Make sure mc_ki is still valid.
7027 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7028 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7029 for (i=0; i<ptop; i++) {
7030 mc->mc_pg[i] = mn.mc_pg[i];
7031 mc->mc_ki[i] = mn.mc_ki[i];
7033 mc->mc_pg[ptop] = mn.mc_pg[ptop];
7034 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
7038 /* return tmp page to freelist */
7039 mdb_page_free(mc->mc_txn->mt_env, copy);
7042 /* Adjust other cursors pointing to mp */
7043 MDB_cursor *m2, *m3;
7044 MDB_dbi dbi = mc->mc_dbi;
7045 int fixup = NUMKEYS(mp);
7047 if (mc->mc_flags & C_SUB)
7050 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7051 if (mc->mc_flags & C_SUB)
7052 m3 = &m2->mc_xcursor->mx_cursor;
7057 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
7059 if (m3->mc_flags & C_SPLITTING)
7064 for (k=m3->mc_top; k>=0; k--) {
7065 m3->mc_ki[k+1] = m3->mc_ki[k];
7066 m3->mc_pg[k+1] = m3->mc_pg[k];
7068 if (m3->mc_ki[0] >= split_indx) {
7073 m3->mc_pg[0] = mc->mc_pg[0];
7077 if (m3->mc_pg[mc->mc_top] == mp) {
7078 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
7079 m3->mc_ki[mc->mc_top]++;
7080 if (m3->mc_ki[mc->mc_top] >= fixup) {
7081 m3->mc_pg[mc->mc_top] = rp;
7082 m3->mc_ki[mc->mc_top] -= fixup;
7083 m3->mc_ki[ptop] = mn.mc_ki[ptop];
7085 } else if (!did_split && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
7086 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
7095 mdb_put(MDB_txn *txn, MDB_dbi dbi,
7096 MDB_val *key, MDB_val *data, unsigned int flags)
7101 assert(key != NULL);
7102 assert(data != NULL);
7104 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7107 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
7111 if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
7115 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP)) != flags)
7118 mdb_cursor_init(&mc, txn, dbi, &mx);
7119 return mdb_cursor_put(&mc, key, data, flags);
7123 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
7125 if ((flag & CHANGEABLE) != flag)
7128 env->me_flags |= flag;
7130 env->me_flags &= ~flag;
7135 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
7140 *arg = env->me_flags;
7145 mdb_env_get_path(MDB_env *env, const char **arg)
7150 *arg = env->me_path;
7154 /** Common code for #mdb_stat() and #mdb_env_stat().
7155 * @param[in] env the environment to operate in.
7156 * @param[in] db the #MDB_db record containing the stats to return.
7157 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
7158 * @return 0, this function always succeeds.
7161 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
7163 arg->ms_psize = env->me_psize;
7164 arg->ms_depth = db->md_depth;
7165 arg->ms_branch_pages = db->md_branch_pages;
7166 arg->ms_leaf_pages = db->md_leaf_pages;
7167 arg->ms_overflow_pages = db->md_overflow_pages;
7168 arg->ms_entries = db->md_entries;
7173 mdb_env_stat(MDB_env *env, MDB_stat *arg)
7177 if (env == NULL || arg == NULL)
7180 toggle = mdb_env_pick_meta(env);
7182 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
7186 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
7190 if (env == NULL || arg == NULL)
7193 toggle = mdb_env_pick_meta(env);
7194 arg->me_mapaddr = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : 0;
7195 arg->me_mapsize = env->me_mapsize;
7196 arg->me_maxreaders = env->me_maxreaders;
7197 arg->me_numreaders = env->me_numreaders;
7198 arg->me_last_pgno = env->me_metas[toggle]->mm_last_pg;
7199 arg->me_last_txnid = env->me_metas[toggle]->mm_txnid;
7203 /** Set the default comparison functions for a database.
7204 * Called immediately after a database is opened to set the defaults.
7205 * The user can then override them with #mdb_set_compare() or
7206 * #mdb_set_dupsort().
7207 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
7208 * @param[in] dbi A database handle returned by #mdb_dbi_open()
7211 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
7213 uint16_t f = txn->mt_dbs[dbi].md_flags;
7215 txn->mt_dbxs[dbi].md_cmp =
7216 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
7217 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
7219 txn->mt_dbxs[dbi].md_dcmp =
7220 !(f & MDB_DUPSORT) ? 0 :
7221 ((f & MDB_INTEGERDUP)
7222 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
7223 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
7226 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
7231 int rc, dbflag, exact;
7232 unsigned int unused = 0;
7235 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
7236 mdb_default_cmp(txn, FREE_DBI);
7239 if ((flags & VALID_FLAGS) != flags)
7245 if (flags & PERSISTENT_FLAGS) {
7246 uint16_t f2 = flags & PERSISTENT_FLAGS;
7247 /* make sure flag changes get committed */
7248 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
7249 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
7250 txn->mt_flags |= MDB_TXN_DIRTY;
7253 mdb_default_cmp(txn, MAIN_DBI);
7257 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
7258 mdb_default_cmp(txn, MAIN_DBI);
7261 /* Is the DB already open? */
7263 for (i=2; i<txn->mt_numdbs; i++) {
7264 if (!txn->mt_dbxs[i].md_name.mv_size) {
7265 /* Remember this free slot */
7266 if (!unused) unused = i;
7269 if (len == txn->mt_dbxs[i].md_name.mv_size &&
7270 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
7276 /* If no free slot and max hit, fail */
7277 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
7278 return MDB_DBS_FULL;
7280 /* Cannot mix named databases with some mainDB flags */
7281 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
7282 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
7284 /* Find the DB info */
7285 dbflag = DB_NEW|DB_VALID;
7288 key.mv_data = (void *)name;
7289 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
7290 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
7291 if (rc == MDB_SUCCESS) {
7292 /* make sure this is actually a DB */
7293 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
7294 if (!(node->mn_flags & F_SUBDATA))
7296 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
7297 /* Create if requested */
7299 data.mv_size = sizeof(MDB_db);
7300 data.mv_data = &dummy;
7301 memset(&dummy, 0, sizeof(dummy));
7302 dummy.md_root = P_INVALID;
7303 dummy.md_flags = flags & PERSISTENT_FLAGS;
7304 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
7308 /* OK, got info, add to table */
7309 if (rc == MDB_SUCCESS) {
7310 unsigned int slot = unused ? unused : txn->mt_numdbs;
7311 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
7312 txn->mt_dbxs[slot].md_name.mv_size = len;
7313 txn->mt_dbxs[slot].md_rel = NULL;
7314 txn->mt_dbflags[slot] = dbflag;
7315 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
7317 txn->mt_env->me_dbflags[slot] = txn->mt_dbs[slot].md_flags;
7318 mdb_default_cmp(txn, slot);
7327 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
7329 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
7332 if (txn->mt_dbflags[dbi] & DB_STALE) {
7335 /* Stale, must read the DB's root. cursor_init does it for us. */
7336 mdb_cursor_init(&mc, txn, dbi, &mx);
7338 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
7341 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
7344 if (dbi <= MAIN_DBI || dbi >= env->me_maxdbs)
7346 ptr = env->me_dbxs[dbi].md_name.mv_data;
7347 env->me_dbxs[dbi].md_name.mv_data = NULL;
7348 env->me_dbxs[dbi].md_name.mv_size = 0;
7349 env->me_dbflags[dbi] = 0;
7353 /** Add all the DB's pages to the free list.
7354 * @param[in] mc Cursor on the DB to free.
7355 * @param[in] subs non-Zero to check for sub-DBs in this DB.
7356 * @return 0 on success, non-zero on failure.
7359 mdb_drop0(MDB_cursor *mc, int subs)
7363 rc = mdb_page_search(mc, NULL, 0);
7364 if (rc == MDB_SUCCESS) {
7365 MDB_txn *txn = mc->mc_txn;
7370 /* LEAF2 pages have no nodes, cannot have sub-DBs */
7371 if (IS_LEAF2(mc->mc_pg[mc->mc_top]))
7374 mdb_cursor_copy(mc, &mx);
7375 while (mc->mc_snum > 0) {
7376 MDB_page *mp = mc->mc_pg[mc->mc_top];
7377 unsigned n = NUMKEYS(mp);
7379 for (i=0; i<n; i++) {
7380 ni = NODEPTR(mp, i);
7381 if (ni->mn_flags & F_BIGDATA) {
7384 memcpy(&pg, NODEDATA(ni), sizeof(pg));
7385 rc = mdb_page_get(txn, pg, &omp, NULL);
7388 assert(IS_OVERFLOW(omp));
7389 rc = mdb_midl_append_range(&txn->mt_free_pgs,
7393 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
7394 mdb_xcursor_init1(mc, ni);
7395 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
7401 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
7403 for (i=0; i<n; i++) {
7405 ni = NODEPTR(mp, i);
7408 mdb_midl_xappend(txn->mt_free_pgs, pg);
7413 mc->mc_ki[mc->mc_top] = i;
7414 rc = mdb_cursor_sibling(mc, 1);
7416 /* no more siblings, go back to beginning
7417 * of previous level.
7421 for (i=1; i<mc->mc_snum; i++) {
7423 mc->mc_pg[i] = mx.mc_pg[i];
7428 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
7429 } else if (rc == MDB_NOTFOUND) {
7435 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
7437 MDB_cursor *mc, *m2;
7440 if (!txn || !dbi || dbi >= txn->mt_numdbs || (unsigned)del > 1 || !(txn->mt_dbflags[dbi] & DB_VALID))
7443 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
7446 rc = mdb_cursor_open(txn, dbi, &mc);
7450 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
7451 /* Invalidate the dropped DB's cursors */
7452 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
7453 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
7457 /* Can't delete the main DB */
7458 if (del && dbi > MAIN_DBI) {
7459 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
7461 txn->mt_dbflags[dbi] = DB_STALE;
7462 mdb_dbi_close(txn->mt_env, dbi);
7465 /* reset the DB record, mark it dirty */
7466 txn->mt_dbflags[dbi] |= DB_DIRTY;
7467 txn->mt_dbs[dbi].md_depth = 0;
7468 txn->mt_dbs[dbi].md_branch_pages = 0;
7469 txn->mt_dbs[dbi].md_leaf_pages = 0;
7470 txn->mt_dbs[dbi].md_overflow_pages = 0;
7471 txn->mt_dbs[dbi].md_entries = 0;
7472 txn->mt_dbs[dbi].md_root = P_INVALID;
7474 txn->mt_flags |= MDB_TXN_DIRTY;
7477 mdb_cursor_close(mc);
7481 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
7483 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7486 txn->mt_dbxs[dbi].md_cmp = cmp;
7490 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
7492 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7495 txn->mt_dbxs[dbi].md_dcmp = cmp;
7499 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
7501 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7504 txn->mt_dbxs[dbi].md_rel = rel;
7508 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
7510 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7513 txn->mt_dbxs[dbi].md_relctx = ctx;