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.
36 #include <sys/types.h>
38 #include <sys/param.h>
44 #ifdef HAVE_SYS_FILE_H
61 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
62 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
65 #if defined(__APPLE__) || defined (BSD)
66 # define MDB_USE_POSIX_SEM 1
67 # define MDB_FDATASYNC fsync
68 #elif defined(ANDROID)
69 # define MDB_FDATASYNC fsync
74 #ifdef MDB_USE_POSIX_SEM
75 #include <semaphore.h>
80 #include <valgrind/memcheck.h>
81 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
82 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
83 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
84 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
85 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
87 #define VGMEMP_CREATE(h,r,z)
88 #define VGMEMP_ALLOC(h,a,s)
89 #define VGMEMP_FREE(h,a)
90 #define VGMEMP_DESTROY(h)
91 #define VGMEMP_DEFINED(a,s)
95 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
96 /* Solaris just defines one or the other */
97 # define LITTLE_ENDIAN 1234
98 # define BIG_ENDIAN 4321
99 # ifdef _LITTLE_ENDIAN
100 # define BYTE_ORDER LITTLE_ENDIAN
102 # define BYTE_ORDER BIG_ENDIAN
105 # define BYTE_ORDER __BYTE_ORDER
109 #ifndef LITTLE_ENDIAN
110 #define LITTLE_ENDIAN __LITTLE_ENDIAN
113 #define BIG_ENDIAN __BIG_ENDIAN
116 #if defined(__i386) || defined(__x86_64)
117 #define MISALIGNED_OK 1
123 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
124 # error "Unknown or unsupported endianness (BYTE_ORDER)"
125 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
126 # error "Two's complement, reasonably sized integer types, please"
129 /** @defgroup internal MDB Internals
132 /** @defgroup compat Windows Compatibility Macros
133 * A bunch of macros to minimize the amount of platform-specific ifdefs
134 * needed throughout the rest of the code. When the features this library
135 * needs are similar enough to POSIX to be hidden in a one-or-two line
136 * replacement, this macro approach is used.
140 #define pthread_t DWORD
141 #define pthread_mutex_t HANDLE
142 #define pthread_key_t DWORD
143 #define pthread_self() GetCurrentThreadId()
144 #define pthread_key_create(x,y) \
145 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
146 #define pthread_key_delete(x) TlsFree(x)
147 #define pthread_getspecific(x) TlsGetValue(x)
148 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
149 #define pthread_mutex_unlock(x) ReleaseMutex(x)
150 #define pthread_mutex_lock(x) WaitForSingleObject(x, INFINITE)
151 #define LOCK_MUTEX_R(env) pthread_mutex_lock((env)->me_rmutex)
152 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock((env)->me_rmutex)
153 #define LOCK_MUTEX_W(env) pthread_mutex_lock((env)->me_wmutex)
154 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock((env)->me_wmutex)
155 #define getpid() GetCurrentProcessId()
156 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
157 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
158 #define ErrCode() GetLastError()
159 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
160 #define close(fd) CloseHandle(fd)
161 #define munmap(ptr,len) UnmapViewOfFile(ptr)
164 #ifdef MDB_USE_POSIX_SEM
166 #define LOCK_MUTEX_R(env) mdb_sem_wait((env)->me_rmutex)
167 #define UNLOCK_MUTEX_R(env) sem_post((env)->me_rmutex)
168 #define LOCK_MUTEX_W(env) mdb_sem_wait((env)->me_wmutex)
169 #define UNLOCK_MUTEX_W(env) sem_post((env)->me_wmutex)
172 mdb_sem_wait(sem_t *sem)
175 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
180 /** Lock the reader mutex.
182 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
183 /** Unlock the reader mutex.
185 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
187 /** Lock the writer mutex.
188 * Only a single write transaction is allowed at a time. Other writers
189 * will block waiting for this mutex.
191 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
192 /** Unlock the writer mutex.
194 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
195 #endif /* MDB_USE_POSIX_SEM */
197 /** Get the error code for the last failed system function.
199 #define ErrCode() errno
201 /** An abstraction for a file handle.
202 * On POSIX systems file handles are small integers. On Windows
203 * they're opaque pointers.
207 /** A value for an invalid file handle.
208 * Mainly used to initialize file variables and signify that they are
211 #define INVALID_HANDLE_VALUE (-1)
213 /** Get the size of a memory page for the system.
214 * This is the basic size that the platform's memory manager uses, and is
215 * fundamental to the use of memory-mapped files.
217 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
220 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
223 #define MNAME_LEN (sizeof(pthread_mutex_t))
229 /** A flag for opening a file and requesting synchronous data writes.
230 * This is only used when writing a meta page. It's not strictly needed;
231 * we could just do a normal write and then immediately perform a flush.
232 * But if this flag is available it saves us an extra system call.
234 * @note If O_DSYNC is undefined but exists in /usr/include,
235 * preferably set some compiler flag to get the definition.
236 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
239 # define MDB_DSYNC O_DSYNC
243 /** Function for flushing the data of a file. Define this to fsync
244 * if fdatasync() is not supported.
246 #ifndef MDB_FDATASYNC
247 # define MDB_FDATASYNC fdatasync
251 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
262 /** A page number in the database.
263 * Note that 64 bit page numbers are overkill, since pages themselves
264 * already represent 12-13 bits of addressable memory, and the OS will
265 * always limit applications to a maximum of 63 bits of address space.
267 * @note In the #MDB_node structure, we only store 48 bits of this value,
268 * which thus limits us to only 60 bits of addressable data.
270 typedef MDB_ID pgno_t;
272 /** A transaction ID.
273 * See struct MDB_txn.mt_txnid for details.
275 typedef MDB_ID txnid_t;
277 /** @defgroup debug Debug Macros
281 /** Enable debug output.
282 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
283 * read from and written to the database (used for free space management).
288 #if !(__STDC_VERSION__ >= 199901L || defined(__GNUC__))
291 # define DPRINTF (void) /* Vararg macros may be unsupported */
293 static int mdb_debug;
294 static txnid_t mdb_debug_start;
296 /** Print a debug message with printf formatting. */
297 # define DPRINTF(fmt, ...) /**< Requires 2 or more args */ \
298 ((void) ((mdb_debug) && \
299 fprintf(stderr, "%s:%d " fmt "\n", __func__, __LINE__, __VA_ARGS__)))
301 # define DPRINTF(fmt, ...) ((void) 0)
302 # define MDB_DEBUG_SKIP
304 /** Print a debug string.
305 * The string is printed literally, with no format processing.
307 #define DPUTS(arg) DPRINTF("%s", arg)
310 /** A default memory page size.
311 * The actual size is platform-dependent, but we use this for
312 * boot-strapping. We probably should not be using this any more.
313 * The #GET_PAGESIZE() macro is used to get the actual size.
315 * Note that we don't currently support Huge pages. On Linux,
316 * regular data files cannot use Huge pages, and in general
317 * Huge pages aren't actually pageable. We rely on the OS
318 * demand-pager to read our data and page it out when memory
319 * pressure from other processes is high. So until OSs have
320 * actual paging support for Huge pages, they're not viable.
322 #define MDB_PAGESIZE 4096
324 /** The minimum number of keys required in a database page.
325 * Setting this to a larger value will place a smaller bound on the
326 * maximum size of a data item. Data items larger than this size will
327 * be pushed into overflow pages instead of being stored directly in
328 * the B-tree node. This value used to default to 4. With a page size
329 * of 4096 bytes that meant that any item larger than 1024 bytes would
330 * go into an overflow page. That also meant that on average 2-3KB of
331 * each overflow page was wasted space. The value cannot be lower than
332 * 2 because then there would no longer be a tree structure. With this
333 * value, items larger than 2KB will go into overflow pages, and on
334 * average only 1KB will be wasted.
336 #define MDB_MINKEYS 2
338 /** A stamp that identifies a file as an MDB file.
339 * There's nothing special about this value other than that it is easily
340 * recognizable, and it will reflect any byte order mismatches.
342 #define MDB_MAGIC 0xBEEFC0DE
344 /** The version number for a database's file format. */
345 #define MDB_VERSION 1
347 /** @brief The maximum size of a key in the database.
349 * We require that keys all fit onto a regular page. This limit
350 * could be raised a bit further if needed; to something just
351 * under #MDB_PAGESIZE / #MDB_MINKEYS.
353 * Note that data items in an #MDB_DUPSORT database are actually keys
354 * of a subDB, so they're also limited to this size.
356 #ifndef MDB_MAXKEYSIZE
357 #define MDB_MAXKEYSIZE 511
360 /** @brief The maximum size of a data item.
362 * We only store a 32 bit value for node sizes.
364 #define MAXDATASIZE 0xffffffffUL
369 * This is used for printing a hex dump of a key's contents.
371 #define DKBUF char kbuf[(MDB_MAXKEYSIZE*2+1)]
372 /** Display a key in hex.
374 * Invoke a function to display a key in hex.
376 #define DKEY(x) mdb_dkey(x, kbuf)
378 #define DKBUF typedef int dummy_kbuf /* so we can put ';' after */
382 /** An invalid page number.
383 * Mainly used to denote an empty tree.
385 #define P_INVALID (~(pgno_t)0)
387 /** Test if the flags \b f are set in a flag word \b w. */
388 #define F_ISSET(w, f) (((w) & (f)) == (f))
390 /** Used for offsets within a single page.
391 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
394 typedef uint16_t indx_t;
396 /** Default size of memory map.
397 * This is certainly too small for any actual applications. Apps should always set
398 * the size explicitly using #mdb_env_set_mapsize().
400 #define DEFAULT_MAPSIZE 1048576
402 /** @defgroup readers Reader Lock Table
403 * Readers don't acquire any locks for their data access. Instead, they
404 * simply record their transaction ID in the reader table. The reader
405 * mutex is needed just to find an empty slot in the reader table. The
406 * slot's address is saved in thread-specific data so that subsequent read
407 * transactions started by the same thread need no further locking to proceed.
409 * No reader table is used if the database is on a read-only filesystem.
411 * Since the database uses multi-version concurrency control, readers don't
412 * actually need any locking. This table is used to keep track of which
413 * readers are using data from which old transactions, so that we'll know
414 * when a particular old transaction is no longer in use. Old transactions
415 * that have discarded any data pages can then have those pages reclaimed
416 * for use by a later write transaction.
418 * The lock table is constructed such that reader slots are aligned with the
419 * processor's cache line size. Any slot is only ever used by one thread.
420 * This alignment guarantees that there will be no contention or cache
421 * thrashing as threads update their own slot info, and also eliminates
422 * any need for locking when accessing a slot.
424 * A writer thread will scan every slot in the table to determine the oldest
425 * outstanding reader transaction. Any freed pages older than this will be
426 * reclaimed by the writer. The writer doesn't use any locks when scanning
427 * this table. This means that there's no guarantee that the writer will
428 * see the most up-to-date reader info, but that's not required for correct
429 * operation - all we need is to know the upper bound on the oldest reader,
430 * we don't care at all about the newest reader. So the only consequence of
431 * reading stale information here is that old pages might hang around a
432 * while longer before being reclaimed. That's actually good anyway, because
433 * the longer we delay reclaiming old pages, the more likely it is that a
434 * string of contiguous pages can be found after coalescing old pages from
435 * many old transactions together.
438 /** Number of slots in the reader table.
439 * This value was chosen somewhat arbitrarily. 126 readers plus a
440 * couple mutexes fit exactly into 8KB on my development machine.
441 * Applications should set the table size using #mdb_env_set_maxreaders().
443 #define DEFAULT_READERS 126
445 /** The size of a CPU cache line in bytes. We want our lock structures
446 * aligned to this size to avoid false cache line sharing in the
448 * This value works for most CPUs. For Itanium this should be 128.
454 /** The information we store in a single slot of the reader table.
455 * In addition to a transaction ID, we also record the process and
456 * thread ID that owns a slot, so that we can detect stale information,
457 * e.g. threads or processes that went away without cleaning up.
458 * @note We currently don't check for stale records. We simply re-init
459 * the table when we know that we're the only process opening the
462 typedef struct MDB_rxbody {
463 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
464 * Multiple readers that start at the same time will probably have the
465 * same ID here. Again, it's not important to exclude them from
466 * anything; all we need to know is which version of the DB they
467 * started from so we can avoid overwriting any data used in that
468 * particular version.
471 /** The process ID of the process owning this reader txn. */
473 /** The thread ID of the thread owning this txn. */
477 /** The actual reader record, with cacheline padding. */
478 typedef struct MDB_reader {
481 /** shorthand for mrb_txnid */
482 #define mr_txnid mru.mrx.mrb_txnid
483 #define mr_pid mru.mrx.mrb_pid
484 #define mr_tid mru.mrx.mrb_tid
485 /** cache line alignment */
486 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
490 /** The header for the reader table.
491 * The table resides in a memory-mapped file. (This is a different file
492 * than is used for the main database.)
494 * For POSIX the actual mutexes reside in the shared memory of this
495 * mapped file. On Windows, mutexes are named objects allocated by the
496 * kernel; we store the mutex names in this mapped file so that other
497 * processes can grab them. This same approach is also used on
498 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
499 * process-shared POSIX mutexes. For these cases where a named object
500 * is used, the object name is derived from a 64 bit FNV hash of the
501 * environment pathname. As such, naming collisions are extremely
502 * unlikely. If a collision occurs, the results are unpredictable.
504 typedef struct MDB_txbody {
505 /** Stamp identifying this as an MDB file. It must be set
508 /** Version number of this lock file. Must be set to #MDB_VERSION. */
509 uint32_t mtb_version;
510 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
511 char mtb_rmname[MNAME_LEN];
513 /** Mutex protecting access to this table.
514 * This is the reader lock that #LOCK_MUTEX_R acquires.
516 pthread_mutex_t mtb_mutex;
518 /** The ID of the last transaction committed to the database.
519 * This is recorded here only for convenience; the value can always
520 * be determined by reading the main database meta pages.
523 /** The number of slots that have been used in the reader table.
524 * This always records the maximum count, it is not decremented
525 * when readers release their slots.
527 unsigned mtb_numreaders;
530 /** The actual reader table definition. */
531 typedef struct MDB_txninfo {
534 #define mti_magic mt1.mtb.mtb_magic
535 #define mti_version mt1.mtb.mtb_version
536 #define mti_mutex mt1.mtb.mtb_mutex
537 #define mti_rmname mt1.mtb.mtb_rmname
538 #define mti_txnid mt1.mtb.mtb_txnid
539 #define mti_numreaders mt1.mtb.mtb_numreaders
540 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
543 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
544 char mt2_wmname[MNAME_LEN];
545 #define mti_wmname mt2.mt2_wmname
547 pthread_mutex_t mt2_wmutex;
548 #define mti_wmutex mt2.mt2_wmutex
550 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
552 MDB_reader mti_readers[1];
556 /** Common header for all page types.
557 * Overflow records occupy a number of contiguous pages with no
558 * headers on any page after the first.
560 typedef struct MDB_page {
561 #define mp_pgno mp_p.p_pgno
562 #define mp_next mp_p.p_next
564 pgno_t p_pgno; /**< page number */
565 void * p_next; /**< for in-memory list of freed structs */
568 /** @defgroup mdb_page Page Flags
570 * Flags for the page headers.
573 #define P_BRANCH 0x01 /**< branch page */
574 #define P_LEAF 0x02 /**< leaf page */
575 #define P_OVERFLOW 0x04 /**< overflow page */
576 #define P_META 0x08 /**< meta page */
577 #define P_DIRTY 0x10 /**< dirty page */
578 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
579 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
581 uint16_t mp_flags; /**< @ref mdb_page */
582 #define mp_lower mp_pb.pb.pb_lower
583 #define mp_upper mp_pb.pb.pb_upper
584 #define mp_pages mp_pb.pb_pages
587 indx_t pb_lower; /**< lower bound of free space */
588 indx_t pb_upper; /**< upper bound of free space */
590 uint32_t pb_pages; /**< number of overflow pages */
592 indx_t mp_ptrs[1]; /**< dynamic size */
595 /** Size of the page header, excluding dynamic data at the end */
596 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
598 /** Address of first usable data byte in a page, after the header */
599 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
601 /** Number of nodes on a page */
602 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
604 /** The amount of space remaining in the page */
605 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
607 /** The percentage of space used in the page, in tenths of a percent. */
608 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
609 ((env)->me_psize - PAGEHDRSZ))
610 /** The minimum page fill factor, in tenths of a percent.
611 * Pages emptier than this are candidates for merging.
613 #define FILL_THRESHOLD 250
615 /** Test if a page is a leaf page */
616 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
617 /** Test if a page is a LEAF2 page */
618 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
619 /** Test if a page is a branch page */
620 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
621 /** Test if a page is an overflow page */
622 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
623 /** Test if a page is a sub page */
624 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
626 /** The number of overflow pages needed to store the given size. */
627 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
629 /** Header for a single key/data pair within a page.
630 * We guarantee 2-byte alignment for nodes.
632 typedef struct MDB_node {
633 /** lo and hi are used for data size on leaf nodes and for
634 * child pgno on branch nodes. On 64 bit platforms, flags
635 * is also used for pgno. (Branch nodes have no flags).
636 * They are in host byte order in case that lets some
637 * accesses be optimized into a 32-bit word access.
639 #define mn_lo mn_offset[BYTE_ORDER!=LITTLE_ENDIAN]
640 #define mn_hi mn_offset[BYTE_ORDER==LITTLE_ENDIAN] /**< part of dsize or pgno */
641 unsigned short mn_offset[2]; /**< storage for #mn_lo and #mn_hi */
642 /** @defgroup mdb_node Node Flags
644 * Flags for node headers.
647 #define F_BIGDATA 0x01 /**< data put on overflow page */
648 #define F_SUBDATA 0x02 /**< data is a sub-database */
649 #define F_DUPDATA 0x04 /**< data has duplicates */
651 /** valid flags for #mdb_node_add() */
652 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
655 unsigned short mn_flags; /**< @ref mdb_node */
656 unsigned short mn_ksize; /**< key size */
657 char mn_data[1]; /**< key and data are appended here */
660 /** Size of the node header, excluding dynamic data at the end */
661 #define NODESIZE offsetof(MDB_node, mn_data)
663 /** Bit position of top word in page number, for shifting mn_flags */
664 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
666 /** Size of a node in a branch page with a given key.
667 * This is just the node header plus the key, there is no data.
669 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
671 /** Size of a node in a leaf page with a given key and data.
672 * This is node header plus key plus data size.
674 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
676 /** Address of node \b i in page \b p */
677 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
679 /** Address of the key for the node */
680 #define NODEKEY(node) (void *)((node)->mn_data)
682 /** Address of the data for a node */
683 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
685 /** Get the page number pointed to by a branch node */
686 #define NODEPGNO(node) \
687 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
688 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
689 /** Set the page number in a branch node */
690 #define SETPGNO(node,pgno) do { \
691 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
692 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
694 /** Get the size of the data in a leaf node */
695 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
696 /** Set the size of the data for a leaf node */
697 #define SETDSZ(node,size) do { \
698 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
699 /** The size of a key in a node */
700 #define NODEKSZ(node) ((node)->mn_ksize)
702 /** Copy a page number from src to dst */
704 #define COPY_PGNO(dst,src) dst = src
706 #if SIZE_MAX > 4294967295UL
707 #define COPY_PGNO(dst,src) do { \
708 unsigned short *s, *d; \
709 s = (unsigned short *)&(src); \
710 d = (unsigned short *)&(dst); \
717 #define COPY_PGNO(dst,src) do { \
718 unsigned short *s, *d; \
719 s = (unsigned short *)&(src); \
720 d = (unsigned short *)&(dst); \
726 /** The address of a key in a LEAF2 page.
727 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
728 * There are no node headers, keys are stored contiguously.
730 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
732 /** Set the \b node's key into \b key, if requested. */
733 #define MDB_GET_KEY(node, key) { if ((key) != NULL) { \
734 (key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node); } }
736 /** Information about a single database in the environment. */
737 typedef struct MDB_db {
738 uint32_t md_pad; /**< also ksize for LEAF2 pages */
739 uint16_t md_flags; /**< @ref mdb_dbi_open */
740 uint16_t md_depth; /**< depth of this tree */
741 pgno_t md_branch_pages; /**< number of internal pages */
742 pgno_t md_leaf_pages; /**< number of leaf pages */
743 pgno_t md_overflow_pages; /**< number of overflow pages */
744 size_t md_entries; /**< number of data items */
745 pgno_t md_root; /**< the root page of this tree */
748 /** mdb_dbi_open flags */
749 #define PERSISTENT_FLAGS 0x7fff
750 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
751 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
753 /** Handle for the DB used to track free pages. */
755 /** Handle for the default DB. */
758 /** Meta page content. */
759 typedef struct MDB_meta {
760 /** Stamp identifying this as an MDB file. It must be set
763 /** Version number of this lock file. Must be set to #MDB_VERSION. */
765 void *mm_address; /**< address for fixed mapping */
766 size_t mm_mapsize; /**< size of mmap region */
767 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
768 /** The size of pages used in this DB */
769 #define mm_psize mm_dbs[0].md_pad
770 /** Any persistent environment flags. @ref mdb_env */
771 #define mm_flags mm_dbs[0].md_flags
772 pgno_t mm_last_pg; /**< last used page in file */
773 txnid_t mm_txnid; /**< txnid that committed this page */
776 /** Buffer for a stack-allocated dirty page.
777 * The members define size and alignment, and silence type
778 * aliasing warnings. They are not used directly; that could
779 * mean incorrectly using several union members in parallel.
781 typedef union MDB_pagebuf {
782 char mb_raw[MDB_PAGESIZE];
785 char mm_pad[PAGEHDRSZ];
790 /** Auxiliary DB info.
791 * The information here is mostly static/read-only. There is
792 * only a single copy of this record in the environment.
794 typedef struct MDB_dbx {
795 MDB_val md_name; /**< name of the database */
796 MDB_cmp_func *md_cmp; /**< function for comparing keys */
797 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
798 MDB_rel_func *md_rel; /**< user relocate function */
799 void *md_relctx; /**< user-provided context for md_rel */
802 /** A database transaction.
803 * Every operation requires a transaction handle.
806 MDB_txn *mt_parent; /**< parent of a nested txn */
807 MDB_txn *mt_child; /**< nested txn under this txn */
808 pgno_t mt_next_pgno; /**< next unallocated page */
809 /** The ID of this transaction. IDs are integers incrementing from 1.
810 * Only committed write transactions increment the ID. If a transaction
811 * aborts, the ID may be re-used by the next writer.
814 MDB_env *mt_env; /**< the DB environment */
815 /** The list of pages that became unused during this transaction.
819 MDB_ID2L dirty_list; /**< for write txns: modified pages */
820 MDB_reader *reader; /**< this thread's reader table slot or NULL */
822 /** Array of records for each DB known in the environment. */
824 /** Array of MDB_db records for each known DB */
826 /** @defgroup mt_dbflag Transaction DB Flags
830 #define DB_DIRTY 0x01 /**< DB was written in this txn */
831 #define DB_STALE 0x02 /**< DB record is older than txnID */
832 #define DB_NEW 0x04 /**< DB handle opened in this txn */
833 #define DB_VALID 0x08 /**< DB handle is valid */
834 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
836 /** In write txns, array of cursors for each DB */
837 MDB_cursor **mt_cursors;
838 /** Array of flags for each DB */
839 unsigned char *mt_dbflags;
840 /** Number of DB records in use. This number only ever increments;
841 * we don't decrement it when individual DB handles are closed.
845 /** @defgroup mdb_txn Transaction Flags
849 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
850 #define MDB_TXN_ERROR 0x02 /**< an error has occurred */
851 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
853 unsigned int mt_flags; /**< @ref mdb_txn */
854 /** dirty_list maxsize - #allocated pages including in parent txns */
855 unsigned int mt_dirty_room;
856 /** Tracks which of the two meta pages was used at the start
857 * of this transaction.
859 unsigned int mt_toggle;
862 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
863 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
864 * raise this on a 64 bit machine.
866 #define CURSOR_STACK 32
870 /** Cursors are used for all DB operations */
872 /** Next cursor on this DB in this txn */
874 /** Original cursor if this is a shadow */
876 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
877 struct MDB_xcursor *mc_xcursor;
878 /** The transaction that owns this cursor */
880 /** The database handle this cursor operates on */
882 /** The database record for this cursor */
884 /** The database auxiliary record for this cursor */
886 /** The @ref mt_dbflag for this database */
887 unsigned char *mc_dbflag;
888 unsigned short mc_snum; /**< number of pushed pages */
889 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
890 /** @defgroup mdb_cursor Cursor Flags
892 * Cursor state flags.
895 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
896 #define C_EOF 0x02 /**< No more data */
897 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
898 #define C_SHADOW 0x08 /**< Cursor is a dup from a parent txn */
899 #define C_ALLOCD 0x10 /**< Cursor was malloc'd */
900 #define C_SPLITTING 0x20 /**< Cursor is in page_split */
902 unsigned int mc_flags; /**< @ref mdb_cursor */
903 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
904 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
907 /** Context for sorted-dup records.
908 * We could have gone to a fully recursive design, with arbitrarily
909 * deep nesting of sub-databases. But for now we only handle these
910 * levels - main DB, optional sub-DB, sorted-duplicate DB.
912 typedef struct MDB_xcursor {
913 /** A sub-cursor for traversing the Dup DB */
914 MDB_cursor mx_cursor;
915 /** The database record for this Dup DB */
917 /** The auxiliary DB record for this Dup DB */
919 /** The @ref mt_dbflag for this Dup DB */
920 unsigned char mx_dbflag;
923 /** State of FreeDB old pages, stored in the MDB_env */
924 typedef struct MDB_pgstate {
925 txnid_t mf_pglast; /**< ID of last old page record we used */
926 pgno_t *mf_pghead; /**< old pages reclaimed from freelist */
927 pgno_t *mf_pgfree; /**< memory to free when dropping me_pghead */
930 /** The database environment. */
932 HANDLE me_fd; /**< The main data file */
933 HANDLE me_lfd; /**< The lock file */
934 HANDLE me_mfd; /**< just for writing the meta pages */
935 /** Failed to update the meta page. Probably an I/O error. */
936 #define MDB_FATAL_ERROR 0x80000000U
937 /** Some fields are initialized. */
938 #define MDB_ENV_ACTIVE 0x20000000U
939 /** me_txkey is set */
940 #define MDB_ENV_TXKEY 0x10000000U
941 uint32_t me_flags; /**< @ref mdb_env */
942 unsigned int me_psize; /**< size of a page, from #GET_PAGESIZE */
943 unsigned int me_maxreaders; /**< size of the reader table */
944 unsigned int me_numreaders; /**< max numreaders set by this env */
945 MDB_dbi me_numdbs; /**< number of DBs opened */
946 MDB_dbi me_maxdbs; /**< size of the DB table */
947 pid_t me_pid; /**< process ID of this env */
948 char *me_path; /**< path to the DB files */
949 char *me_map; /**< the memory map of the data file */
950 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
951 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
952 MDB_txn *me_txn; /**< current write transaction */
953 size_t me_mapsize; /**< size of the data memory map */
954 off_t me_size; /**< current file size */
955 pgno_t me_maxpg; /**< me_mapsize / me_psize */
956 MDB_dbx *me_dbxs; /**< array of static DB info */
957 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
958 pthread_key_t me_txkey; /**< thread-key for readers */
959 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
960 # define me_pglast me_pgstate.mf_pglast
961 # define me_pghead me_pgstate.mf_pghead
962 # define me_pgfree me_pgstate.mf_pgfree
963 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
964 /** IDL of pages that became unused in a write txn */
966 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
967 MDB_ID2L me_dirty_list;
968 /** Max number of freelist items that can fit in a single overflow page */
969 unsigned int me_maxfree_1pg;
970 /** Max size of a node on a page */
971 unsigned int me_nodemax;
973 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
975 #elif defined(MDB_USE_POSIX_SEM)
976 sem_t *me_rmutex; /* Shared mutexes are not supported */
981 /** Nested transaction */
982 typedef struct MDB_ntxn {
983 MDB_txn mnt_txn; /* the transaction */
984 MDB_pgstate mnt_pgstate; /* parent transaction's saved freestate */
987 /** max number of pages to commit in one writev() call */
988 #define MDB_COMMIT_PAGES 64
989 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
990 #undef MDB_COMMIT_PAGES
991 #define MDB_COMMIT_PAGES IOV_MAX
994 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
995 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
996 static int mdb_page_touch(MDB_cursor *mc);
998 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
999 static int mdb_page_search_root(MDB_cursor *mc,
1000 MDB_val *key, int modify);
1001 #define MDB_PS_MODIFY 1
1002 #define MDB_PS_ROOTONLY 2
1003 static int mdb_page_search(MDB_cursor *mc,
1004 MDB_val *key, int flags);
1005 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1007 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1008 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1009 pgno_t newpgno, unsigned int nflags);
1011 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1012 static int mdb_env_pick_meta(const MDB_env *env);
1013 static int mdb_env_write_meta(MDB_txn *txn);
1014 static void mdb_env_close0(MDB_env *env, int excl);
1016 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1017 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1018 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1019 static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
1020 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1021 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
1022 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1023 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1024 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1026 static int mdb_rebalance(MDB_cursor *mc);
1027 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1029 static void mdb_cursor_pop(MDB_cursor *mc);
1030 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1032 static int mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
1033 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1034 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1035 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1036 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1038 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1039 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1041 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1042 static void mdb_xcursor_init0(MDB_cursor *mc);
1043 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1045 static int mdb_drop0(MDB_cursor *mc, int subs);
1046 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1049 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1053 static SECURITY_DESCRIPTOR mdb_null_sd;
1054 static SECURITY_ATTRIBUTES mdb_all_sa;
1055 static int mdb_sec_inited;
1058 /** Return the library version info. */
1060 mdb_version(int *major, int *minor, int *patch)
1062 if (major) *major = MDB_VERSION_MAJOR;
1063 if (minor) *minor = MDB_VERSION_MINOR;
1064 if (patch) *patch = MDB_VERSION_PATCH;
1065 return MDB_VERSION_STRING;
1068 /** Table of descriptions for MDB @ref errors */
1069 static char *const mdb_errstr[] = {
1070 "MDB_KEYEXIST: Key/data pair already exists",
1071 "MDB_NOTFOUND: No matching key/data pair found",
1072 "MDB_PAGE_NOTFOUND: Requested page not found",
1073 "MDB_CORRUPTED: Located page was wrong type",
1074 "MDB_PANIC: Update of meta page failed",
1075 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1076 "MDB_INVALID: File is not an MDB file",
1077 "MDB_MAP_FULL: Environment mapsize limit reached",
1078 "MDB_DBS_FULL: Environment maxdbs limit reached",
1079 "MDB_READERS_FULL: Environment maxreaders limit reached",
1080 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1081 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1082 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1083 "MDB_PAGE_FULL: Internal error - page has no more space",
1084 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1085 "MDB_INCOMPATIBLE: Database flags changed or would change",
1086 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1090 mdb_strerror(int err)
1094 return ("Successful return: 0");
1096 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1097 i = err - MDB_KEYEXIST;
1098 return mdb_errstr[i];
1101 return strerror(err);
1105 /** Display a key in hexadecimal and return the address of the result.
1106 * @param[in] key the key to display
1107 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1108 * @return The key in hexadecimal form.
1111 mdb_dkey(MDB_val *key, char *buf)
1114 unsigned char *c = key->mv_data;
1120 if (key->mv_size > MDB_MAXKEYSIZE)
1121 return "MDB_MAXKEYSIZE";
1122 /* may want to make this a dynamic check: if the key is mostly
1123 * printable characters, print it as-is instead of converting to hex.
1127 for (i=0; i<key->mv_size; i++)
1128 ptr += sprintf(ptr, "%02x", *c++);
1130 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1135 /** Display all the keys in the page. */
1137 mdb_page_list(MDB_page *mp)
1140 unsigned int i, nkeys, nsize;
1144 nkeys = NUMKEYS(mp);
1145 fprintf(stderr, "Page %zu numkeys %d\n", mp->mp_pgno, nkeys);
1146 for (i=0; i<nkeys; i++) {
1147 node = NODEPTR(mp, i);
1148 key.mv_size = node->mn_ksize;
1149 key.mv_data = node->mn_data;
1150 nsize = NODESIZE + NODEKSZ(node) + sizeof(indx_t);
1151 if (IS_BRANCH(mp)) {
1152 fprintf(stderr, "key %d: page %zu, %s\n", i, NODEPGNO(node),
1155 if (F_ISSET(node->mn_flags, F_BIGDATA))
1156 nsize += sizeof(pgno_t);
1158 nsize += NODEDSZ(node);
1159 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1165 mdb_cursor_chk(MDB_cursor *mc)
1171 if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1172 for (i=0; i<mc->mc_top; i++) {
1174 node = NODEPTR(mp, mc->mc_ki[i]);
1175 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1178 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1184 /** Count all the pages in each DB and in the freelist
1185 * and make sure it matches the actual number of pages
1188 static void mdb_audit(MDB_txn *txn)
1192 MDB_ID freecount, count;
1197 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1198 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1199 freecount += *(MDB_ID *)data.mv_data;
1202 for (i = 0; i<txn->mt_numdbs; i++) {
1203 MDB_xcursor mx, *mxp;
1204 mxp = (txn->mt_dbs[i].md_flags & MDB_DUPSORT) ? &mx : NULL;
1205 mdb_cursor_init(&mc, txn, i, mxp);
1206 if (txn->mt_dbs[i].md_root == P_INVALID)
1208 count += txn->mt_dbs[i].md_branch_pages +
1209 txn->mt_dbs[i].md_leaf_pages +
1210 txn->mt_dbs[i].md_overflow_pages;
1211 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1212 mdb_page_search(&mc, NULL, 0);
1216 mp = mc.mc_pg[mc.mc_top];
1217 for (j=0; j<NUMKEYS(mp); j++) {
1218 MDB_node *leaf = NODEPTR(mp, j);
1219 if (leaf->mn_flags & F_SUBDATA) {
1221 memcpy(&db, NODEDATA(leaf), sizeof(db));
1222 count += db.md_branch_pages + db.md_leaf_pages +
1223 db.md_overflow_pages;
1227 while (mdb_cursor_sibling(&mc, 1) == 0);
1230 if (freecount + count + 2 /* metapages */ != txn->mt_next_pgno) {
1231 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1232 txn->mt_txnid, freecount, count+2, freecount+count+2, txn->mt_next_pgno);
1238 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1240 return txn->mt_dbxs[dbi].md_cmp(a, b);
1244 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1246 if (txn->mt_dbxs[dbi].md_dcmp)
1247 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1249 return EINVAL; /* too bad you can't distinguish this from a valid result */
1252 /** Allocate a single page.
1253 * Re-use old malloc'd pages first, otherwise just malloc.
1256 mdb_page_malloc(MDB_cursor *mc) {
1258 size_t sz = mc->mc_txn->mt_env->me_psize;
1259 if ((ret = mc->mc_txn->mt_env->me_dpages) != NULL) {
1260 VGMEMP_ALLOC(mc->mc_txn->mt_env, ret, sz);
1261 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1262 mc->mc_txn->mt_env->me_dpages = ret->mp_next;
1263 } else if ((ret = malloc(sz)) != NULL) {
1264 VGMEMP_ALLOC(mc->mc_txn->mt_env, ret, sz);
1270 mdb_page_free(MDB_env *env, MDB_page *mp)
1272 mp->mp_next = env->me_dpages;
1273 VGMEMP_FREE(env, mp);
1274 env->me_dpages = mp;
1277 /** Allocate pages for writing.
1278 * If there are free pages available from older transactions, they
1279 * will be re-used first. Otherwise a new page will be allocated.
1280 * @param[in] mc cursor A cursor handle identifying the transaction and
1281 * database for which we are allocating.
1282 * @param[in] num the number of pages to allocate.
1283 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
1284 * will always be satisfied by a single contiguous chunk of memory.
1285 * @return 0 on success, non-zero on failure.
1288 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
1290 MDB_txn *txn = mc->mc_txn;
1292 pgno_t pgno = P_INVALID;
1294 txnid_t oldest = 0, last;
1299 /* If our dirty list is already full, we can't do anything */
1300 if (txn->mt_dirty_room == 0)
1301 return MDB_TXN_FULL;
1303 /* The free list won't have any content at all until txn 2 has
1304 * committed. The pages freed by txn 2 will be unreferenced
1305 * after txn 3 commits, and so will be safe to re-use in txn 4.
1307 if (txn->mt_txnid > 3) {
1308 if (!txn->mt_env->me_pghead &&
1309 txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
1310 /* See if there's anything in the free DB */
1317 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1318 if (!txn->mt_env->me_pglast) {
1319 mdb_page_search(&m2, NULL, 0);
1320 leaf = NODEPTR(m2.mc_pg[m2.mc_top], 0);
1321 kptr = (txnid_t *)NODEKEY(leaf);
1326 last = txn->mt_env->me_pglast + 1;
1328 key.mv_data = &last;
1329 key.mv_size = sizeof(last);
1330 rc = mdb_cursor_set(&m2, &key, &data, MDB_SET_RANGE, NULL);
1333 last = *(txnid_t *)key.mv_data;
1339 oldest = txn->mt_txnid - 1;
1340 nr = txn->mt_env->me_txns->mti_numreaders;
1341 r = txn->mt_env->me_txns->mti_readers;
1342 for (i=0; i<nr; i++) {
1343 if (!r[i].mr_pid) continue;
1350 if (oldest > last) {
1351 /* It's usable, grab it.
1355 if (!txn->mt_env->me_pglast) {
1356 mdb_node_read(txn, leaf, &data);
1358 idl = (MDB_ID *) data.mv_data;
1359 /* We might have a zero-length IDL due to freelist growth
1360 * during a prior commit
1363 txn->mt_env->me_pglast = last;
1366 mop = malloc(MDB_IDL_SIZEOF(idl));
1369 txn->mt_env->me_pglast = last;
1370 txn->mt_env->me_pghead = txn->mt_env->me_pgfree = mop;
1371 memcpy(mop, idl, MDB_IDL_SIZEOF(idl));
1376 DPRINTF("IDL read txn %zu root %zu num %zu",
1377 last, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1378 for (i=0; i<idl[0]; i++) {
1379 DPRINTF("IDL %zu", idl[i+1]);
1386 if (txn->mt_env->me_pghead) {
1387 pgno_t *mop = txn->mt_env->me_pghead;
1390 int retry = 1, readit = 0, n2 = num-1;
1391 unsigned int i, j, k;
1393 /* If current list is too short, must fetch more and coalesce */
1394 if (mop[0] < (unsigned)num)
1397 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1399 /* If on freelist, don't try to read more. If what we have
1400 * right now isn't enough just use new pages.
1401 * TODO: get all of this working. Many circular dependencies...
1403 if (mc->mc_dbi == FREE_DBI) {
1411 last = txn->mt_env->me_pglast + 1;
1413 /* We haven't hit the readers list yet? */
1419 oldest = txn->mt_txnid - 1;
1420 nr = txn->mt_env->me_txns->mti_numreaders;
1421 r = txn->mt_env->me_txns->mti_readers;
1422 for (i=0; i<nr; i++) {
1423 if (!r[i].mr_pid) continue;
1430 /* There's nothing we can use on the freelist */
1431 if (oldest - last < 1)
1434 key.mv_data = &last;
1435 key.mv_size = sizeof(last);
1436 rc = mdb_cursor_set(&m2,&key,&data,MDB_SET_RANGE,NULL);
1438 if (rc == MDB_NOTFOUND)
1442 last = *(txnid_t*)key.mv_data;
1445 idl = (MDB_ID *) data.mv_data;
1446 mop2 = malloc(MDB_IDL_SIZEOF(idl) + MDB_IDL_SIZEOF(mop));
1449 /* merge in sorted order */
1450 i = idl[0]; j = mop[0]; mop2[0] = k = i+j;
1452 while (i>0 || j>0) {
1453 if (i && idl[i] < mop[j])
1454 mop2[k--] = idl[i--];
1456 mop2[k--] = mop[j--];
1458 txn->mt_env->me_pglast = last;
1459 free(txn->mt_env->me_pgfree);
1460 txn->mt_env->me_pghead = txn->mt_env->me_pgfree = mop2;
1462 /* Keep trying to read until we have enough */
1463 if (mop[0] < (unsigned)num) {
1468 /* current list has enough pages, but are they contiguous? */
1469 for (i=mop[0]; i>=(unsigned)num; i--) {
1470 if (mop[i-n2] == mop[i] + n2) {
1473 /* move any stragglers down */
1474 for (j=i+num; j<=mop[0]; j++)
1481 /* Stop if we succeeded, or no retries */
1482 if (!retry || pgno != P_INVALID)
1488 /* peel pages off tail, so we only have to truncate the list */
1489 pgno = MDB_IDL_LAST(mop);
1492 if (MDB_IDL_IS_ZERO(mop)) {
1493 free(txn->mt_env->me_pgfree);
1494 txn->mt_env->me_pghead = txn->mt_env->me_pgfree = NULL;
1499 if (pgno == P_INVALID) {
1500 /* DB size is maxed out */
1501 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg) {
1502 DPUTS("DB size maxed out");
1503 return MDB_MAP_FULL;
1506 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1507 if (pgno == P_INVALID) {
1508 pgno = txn->mt_next_pgno;
1509 txn->mt_next_pgno += num;
1511 np = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
1514 if (txn->mt_env->me_dpages && num == 1) {
1515 np = txn->mt_env->me_dpages;
1516 VGMEMP_ALLOC(txn->mt_env, np, txn->mt_env->me_psize);
1517 VGMEMP_DEFINED(np, sizeof(np->mp_next));
1518 txn->mt_env->me_dpages = np->mp_next;
1520 size_t sz = txn->mt_env->me_psize * num;
1521 if ((np = malloc(sz)) == NULL)
1523 VGMEMP_ALLOC(txn->mt_env, np, sz);
1525 if (pgno == P_INVALID) {
1526 np->mp_pgno = txn->mt_next_pgno;
1527 txn->mt_next_pgno += num;
1532 mid.mid = np->mp_pgno;
1534 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1535 mdb_mid2l_append(txn->mt_u.dirty_list, &mid);
1537 mdb_mid2l_insert(txn->mt_u.dirty_list, &mid);
1539 txn->mt_dirty_room--;
1545 /** Copy a page: avoid copying unused portions of the page.
1546 * @param[in] dst page to copy into
1547 * @param[in] src page to copy from
1550 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
1552 dst->mp_flags = src->mp_flags | P_DIRTY;
1553 dst->mp_pages = src->mp_pages;
1555 if (IS_LEAF2(src)) {
1556 memcpy(dst->mp_ptrs, src->mp_ptrs, psize - PAGEHDRSZ - SIZELEFT(src));
1558 unsigned int i, nkeys = NUMKEYS(src);
1559 for (i=0; i<nkeys; i++)
1560 dst->mp_ptrs[i] = src->mp_ptrs[i];
1561 memcpy((char *)dst+src->mp_upper, (char *)src+src->mp_upper,
1562 psize - src->mp_upper);
1566 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1567 * @param[in] mc cursor pointing to the page to be touched
1568 * @return 0 on success, non-zero on failure.
1571 mdb_page_touch(MDB_cursor *mc)
1573 MDB_page *mp = mc->mc_pg[mc->mc_top];
1577 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1579 if ((rc = mdb_page_alloc(mc, 1, &np)))
1581 DPRINTF("touched db %u page %zu -> %zu", mc->mc_dbi, mp->mp_pgno, np->mp_pgno);
1582 assert(mp->mp_pgno != np->mp_pgno);
1583 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
1585 /* If page isn't full, just copy the used portion */
1586 mdb_page_copy(np, mp, mc->mc_txn->mt_env->me_psize);
1589 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1591 np->mp_flags |= P_DIRTY;
1596 /* Adjust other cursors pointing to mp */
1597 if (mc->mc_flags & C_SUB) {
1598 MDB_cursor *m2, *m3;
1599 MDB_dbi dbi = mc->mc_dbi-1;
1601 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
1602 if (m2 == mc) continue;
1603 m3 = &m2->mc_xcursor->mx_cursor;
1604 if (m3->mc_snum < mc->mc_snum) continue;
1605 if (m3->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1606 m3->mc_pg[mc->mc_top] = mp;
1612 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
1613 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
1614 if (m2->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1615 m2->mc_pg[mc->mc_top] = mp;
1619 mc->mc_pg[mc->mc_top] = mp;
1620 /** If this page has a parent, update the parent to point to
1624 SETPGNO(NODEPTR(mc->mc_pg[mc->mc_top-1], mc->mc_ki[mc->mc_top-1]), mp->mp_pgno);
1626 mc->mc_db->md_root = mp->mp_pgno;
1627 } else if (mc->mc_txn->mt_parent) {
1630 /* If txn has a parent, make sure the page is in our
1633 if (mc->mc_txn->mt_u.dirty_list[0].mid) {
1634 unsigned x = mdb_mid2l_search(mc->mc_txn->mt_u.dirty_list, mp->mp_pgno);
1635 if (x <= mc->mc_txn->mt_u.dirty_list[0].mid &&
1636 mc->mc_txn->mt_u.dirty_list[x].mid == mp->mp_pgno) {
1637 if (mc->mc_txn->mt_u.dirty_list[x].mptr != mp) {
1638 mp = mc->mc_txn->mt_u.dirty_list[x].mptr;
1639 mc->mc_pg[mc->mc_top] = mp;
1644 assert(mc->mc_txn->mt_u.dirty_list[0].mid < MDB_IDL_UM_MAX);
1646 np = mdb_page_malloc(mc);
1649 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1650 mid.mid = np->mp_pgno;
1652 mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &mid);
1660 mdb_env_sync(MDB_env *env, int force)
1663 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1664 if (env->me_flags & MDB_WRITEMAP) {
1665 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
1666 ? MS_ASYNC : MS_SYNC;
1667 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
1670 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
1674 if (MDB_FDATASYNC(env->me_fd))
1681 /** Make shadow copies of all of parent txn's cursors */
1683 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
1685 MDB_cursor *mc, *m2;
1686 unsigned int i, j, size;
1688 for (i=0;i<src->mt_numdbs; i++) {
1689 if (src->mt_cursors[i]) {
1690 size = sizeof(MDB_cursor);
1691 if (src->mt_cursors[i]->mc_xcursor)
1692 size += sizeof(MDB_xcursor);
1693 for (m2 = src->mt_cursors[i]; m2; m2=m2->mc_next) {
1700 mc->mc_db = &dst->mt_dbs[i];
1701 mc->mc_dbx = m2->mc_dbx;
1702 mc->mc_dbflag = &dst->mt_dbflags[i];
1703 mc->mc_snum = m2->mc_snum;
1704 mc->mc_top = m2->mc_top;
1705 mc->mc_flags = m2->mc_flags | C_SHADOW;
1706 for (j=0; j<mc->mc_snum; j++) {
1707 mc->mc_pg[j] = m2->mc_pg[j];
1708 mc->mc_ki[j] = m2->mc_ki[j];
1710 if (m2->mc_xcursor) {
1711 MDB_xcursor *mx, *mx2;
1712 mx = (MDB_xcursor *)(mc+1);
1713 mc->mc_xcursor = mx;
1714 mx2 = m2->mc_xcursor;
1715 mx->mx_db = mx2->mx_db;
1716 mx->mx_dbx = mx2->mx_dbx;
1717 mx->mx_dbflag = mx2->mx_dbflag;
1718 mx->mx_cursor.mc_txn = dst;
1719 mx->mx_cursor.mc_dbi = mx2->mx_cursor.mc_dbi;
1720 mx->mx_cursor.mc_db = &mx->mx_db;
1721 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
1722 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
1723 mx->mx_cursor.mc_snum = mx2->mx_cursor.mc_snum;
1724 mx->mx_cursor.mc_top = mx2->mx_cursor.mc_top;
1725 mx->mx_cursor.mc_flags = mx2->mx_cursor.mc_flags | C_SHADOW;
1726 for (j=0; j<mx2->mx_cursor.mc_snum; j++) {
1727 mx->mx_cursor.mc_pg[j] = mx2->mx_cursor.mc_pg[j];
1728 mx->mx_cursor.mc_ki[j] = mx2->mx_cursor.mc_ki[j];
1731 mc->mc_xcursor = NULL;
1733 mc->mc_next = dst->mt_cursors[i];
1734 dst->mt_cursors[i] = mc;
1741 /** Merge shadow cursors back into parent's */
1743 mdb_cursor_merge(MDB_txn *txn)
1746 for (i=0; i<txn->mt_numdbs; i++) {
1747 if (txn->mt_cursors[i]) {
1749 while ((mc = txn->mt_cursors[i])) {
1750 txn->mt_cursors[i] = mc->mc_next;
1751 if (mc->mc_flags & C_SHADOW) {
1752 MDB_cursor *m2 = mc->mc_orig;
1754 m2->mc_snum = mc->mc_snum;
1755 m2->mc_top = mc->mc_top;
1756 for (j=0; j<mc->mc_snum; j++) {
1757 m2->mc_pg[j] = mc->mc_pg[j];
1758 m2->mc_ki[j] = mc->mc_ki[j];
1761 if (mc->mc_flags & C_ALLOCD)
1769 mdb_txn_reset0(MDB_txn *txn);
1771 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
1772 * @param[in] txn the transaction handle to initialize
1773 * @return 0 on success, non-zero on failure. This can only
1774 * fail for read-only transactions, and then only if the
1775 * reader table is full.
1778 mdb_txn_renew0(MDB_txn *txn)
1780 MDB_env *env = txn->mt_env;
1786 txn->mt_numdbs = env->me_numdbs;
1787 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
1789 if (txn->mt_flags & MDB_TXN_RDONLY) {
1790 if (!env->me_txns) {
1791 i = mdb_env_pick_meta(env);
1792 txn->mt_txnid = env->me_metas[i]->mm_txnid;
1793 txn->mt_u.reader = NULL;
1795 MDB_reader *r = pthread_getspecific(env->me_txkey);
1797 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
1798 return MDB_BAD_RSLOT;
1800 pid_t pid = env->me_pid;
1801 pthread_t tid = pthread_self();
1804 for (i=0; i<env->me_txns->mti_numreaders; i++)
1805 if (env->me_txns->mti_readers[i].mr_pid == 0)
1807 if (i == env->me_maxreaders) {
1808 UNLOCK_MUTEX_R(env);
1809 return MDB_READERS_FULL;
1811 env->me_txns->mti_readers[i].mr_pid = pid;
1812 env->me_txns->mti_readers[i].mr_tid = tid;
1813 if (i >= env->me_txns->mti_numreaders)
1814 env->me_txns->mti_numreaders = i+1;
1815 /* Save numreaders for un-mutexed mdb_env_close() */
1816 env->me_numreaders = env->me_txns->mti_numreaders;
1817 UNLOCK_MUTEX_R(env);
1818 r = &env->me_txns->mti_readers[i];
1819 if ((rc = pthread_setspecific(env->me_txkey, r)) != 0) {
1820 env->me_txns->mti_readers[i].mr_pid = 0;
1824 txn->mt_txnid = r->mr_txnid = env->me_txns->mti_txnid;
1825 txn->mt_u.reader = r;
1827 txn->mt_toggle = txn->mt_txnid & 1;
1828 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1832 txn->mt_txnid = env->me_txns->mti_txnid;
1833 txn->mt_toggle = txn->mt_txnid & 1;
1834 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1837 if (txn->mt_txnid == mdb_debug_start)
1840 txn->mt_dirty_room = MDB_IDL_UM_MAX;
1841 txn->mt_u.dirty_list = env->me_dirty_list;
1842 txn->mt_u.dirty_list[0].mid = 0;
1843 txn->mt_free_pgs = env->me_free_pgs;
1844 txn->mt_free_pgs[0] = 0;
1848 /* Copy the DB info and flags */
1849 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
1850 for (i=2; i<txn->mt_numdbs; i++) {
1851 x = env->me_dbflags[i];
1852 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
1853 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_STALE : 0;
1855 txn->mt_dbflags[0] = txn->mt_dbflags[1] = DB_VALID;
1857 if (env->me_maxpg < txn->mt_next_pgno) {
1858 mdb_txn_reset0(txn);
1859 return MDB_MAP_RESIZED;
1866 mdb_txn_renew(MDB_txn *txn)
1870 if (!txn || txn->mt_numdbs || !(txn->mt_flags & MDB_TXN_RDONLY))
1873 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
1874 DPUTS("environment had fatal error, must shutdown!");
1878 rc = mdb_txn_renew0(txn);
1879 if (rc == MDB_SUCCESS) {
1880 DPRINTF("renew txn %zu%c %p on mdbenv %p, root page %zu",
1881 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1882 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1888 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
1892 int rc, size, tsize = sizeof(MDB_txn);
1894 if (env->me_flags & MDB_FATAL_ERROR) {
1895 DPUTS("environment had fatal error, must shutdown!");
1898 if ((env->me_flags & MDB_RDONLY) && !(flags & MDB_RDONLY))
1901 /* Nested transactions: Max 1 child, write txns only, no writemap */
1902 if (parent->mt_child ||
1903 (flags & MDB_RDONLY) || (parent->mt_flags & MDB_TXN_RDONLY) ||
1904 (env->me_flags & MDB_WRITEMAP))
1908 tsize = sizeof(MDB_ntxn);
1910 size = tsize + env->me_maxdbs * (sizeof(MDB_db)+1);
1911 if (!(flags & MDB_RDONLY))
1912 size += env->me_maxdbs * sizeof(MDB_cursor *);
1914 if ((txn = calloc(1, size)) == NULL) {
1915 DPRINTF("calloc: %s", strerror(ErrCode()));
1918 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
1919 if (flags & MDB_RDONLY) {
1920 txn->mt_flags |= MDB_TXN_RDONLY;
1921 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
1923 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
1924 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
1930 txn->mt_free_pgs = mdb_midl_alloc();
1931 if (!txn->mt_free_pgs) {
1935 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
1936 if (!txn->mt_u.dirty_list) {
1937 free(txn->mt_free_pgs);
1941 txn->mt_txnid = parent->mt_txnid;
1942 txn->mt_toggle = parent->mt_toggle;
1943 txn->mt_dirty_room = parent->mt_dirty_room;
1944 txn->mt_u.dirty_list[0].mid = 0;
1945 txn->mt_free_pgs[0] = 0;
1946 txn->mt_next_pgno = parent->mt_next_pgno;
1947 parent->mt_child = txn;
1948 txn->mt_parent = parent;
1949 txn->mt_numdbs = parent->mt_numdbs;
1950 txn->mt_dbxs = parent->mt_dbxs;
1951 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
1952 /* Copy parent's mt_dbflags, but clear DB_NEW */
1953 for (i=0; i<txn->mt_numdbs; i++)
1954 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
1956 ntxn = (MDB_ntxn *)txn;
1957 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
1958 if (env->me_pghead) {
1959 size = MDB_IDL_SIZEOF(env->me_pghead);
1960 env->me_pghead = malloc(size);
1962 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
1966 env->me_pgfree = env->me_pghead;
1968 rc = mdb_cursor_shadow(parent, txn);
1970 mdb_txn_reset0(txn);
1972 rc = mdb_txn_renew0(txn);
1978 DPRINTF("begin txn %zu%c %p on mdbenv %p, root page %zu",
1979 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1980 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
1986 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
1987 * May be called twice for readonly txns: First reset it, then abort.
1988 * @param[in] txn the transaction handle to reset
1991 mdb_txn_reset0(MDB_txn *txn)
1993 MDB_env *env = txn->mt_env;
1996 /* Close any DBI handles opened in this txn */
1997 for (i=2; i<txn->mt_numdbs; i++) {
1998 if (txn->mt_dbflags[i] & DB_NEW) {
1999 char *ptr = env->me_dbxs[i].md_name.mv_data;
2000 env->me_dbxs[i].md_name.mv_data = NULL;
2001 env->me_dbxs[i].md_name.mv_size = 0;
2006 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2007 if (txn->mt_u.reader) {
2008 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2009 txn->mt_u.reader = NULL; /* do not touch mr_txnid again */
2011 txn->mt_numdbs = 0; /* mark txn as reset, do not close DBs again */
2015 /* close(free) all cursors */
2016 for (i=0; i<txn->mt_numdbs; i++) {
2017 if (txn->mt_cursors[i]) {
2019 while ((mc = txn->mt_cursors[i])) {
2020 txn->mt_cursors[i] = mc->mc_next;
2021 if (mc->mc_flags & C_ALLOCD)
2027 if (!(env->me_flags & MDB_WRITEMAP)) {
2028 /* return all dirty pages to dpage list */
2029 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
2030 dp = txn->mt_u.dirty_list[i].mptr;
2031 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
2032 mdb_page_free(txn->mt_env, dp);
2034 /* large pages just get freed directly */
2035 VGMEMP_FREE(txn->mt_env, dp);
2041 free(env->me_pgfree);
2043 if (txn->mt_parent) {
2044 txn->mt_parent->mt_child = NULL;
2045 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2046 mdb_midl_free(txn->mt_free_pgs);
2047 free(txn->mt_u.dirty_list);
2050 if (mdb_midl_shrink(&txn->mt_free_pgs))
2051 env->me_free_pgs = txn->mt_free_pgs;
2054 txn->mt_env->me_pghead = txn->mt_env->me_pgfree = NULL;
2055 txn->mt_env->me_pglast = 0;
2058 /* The writer mutex was locked in mdb_txn_begin. */
2059 UNLOCK_MUTEX_W(env);
2064 mdb_txn_reset(MDB_txn *txn)
2069 DPRINTF("reset txn %zu%c %p on mdbenv %p, root page %zu",
2070 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2071 (void *) txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
2073 /* This call is only valid for read-only txns */
2074 if (!(txn->mt_flags & MDB_TXN_RDONLY))
2077 mdb_txn_reset0(txn);
2081 mdb_txn_abort(MDB_txn *txn)
2086 DPRINTF("abort txn %zu%c %p on mdbenv %p, root page %zu",
2087 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2088 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
2091 mdb_txn_abort(txn->mt_child);
2093 mdb_txn_reset0(txn);
2098 mdb_txn_commit(MDB_txn *txn)
2106 pgno_t next, freecnt;
2107 txnid_t oldpg_txnid, id;
2110 assert(txn != NULL);
2111 assert(txn->mt_env != NULL);
2113 if (txn->mt_child) {
2114 mdb_txn_commit(txn->mt_child);
2115 txn->mt_child = NULL;
2120 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2121 /* update the DB flags */
2122 for (i = 2; i<txn->mt_numdbs; i++) {
2123 if (txn->mt_dbflags[i] & DB_NEW)
2124 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2126 if (txn->mt_numdbs > env->me_numdbs)
2127 env->me_numdbs = txn->mt_numdbs;
2128 txn->mt_numdbs = 2; /* so txn_abort() doesn't close any new handles */
2133 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
2134 DPUTS("error flag is set, can't commit");
2136 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
2141 if (txn->mt_parent) {
2142 MDB_txn *parent = txn->mt_parent;
2146 /* Append our free list to parent's */
2147 if (mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs)) {
2151 mdb_midl_free(txn->mt_free_pgs);
2153 parent->mt_next_pgno = txn->mt_next_pgno;
2154 parent->mt_flags = txn->mt_flags;
2156 /* Merge (and close) our cursors with parent's */
2157 mdb_cursor_merge(txn);
2159 /* Update parent's DB table. */
2160 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2161 txn->mt_parent->mt_numdbs = txn->mt_numdbs;
2162 txn->mt_parent->mt_dbflags[0] = txn->mt_dbflags[0];
2163 txn->mt_parent->mt_dbflags[1] = txn->mt_dbflags[1];
2164 for (i=2; i<txn->mt_numdbs; i++) {
2165 /* preserve parent's DB_NEW status */
2166 x = txn->mt_parent->mt_dbflags[i] & DB_NEW;
2167 txn->mt_parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
2170 dst = txn->mt_parent->mt_u.dirty_list;
2171 src = txn->mt_u.dirty_list;
2172 /* Find len = length of merging our dirty list with parent's */
2174 dst[0].mid = 0; /* simplify loops */
2175 if (parent->mt_parent) {
2176 len = x + src[0].mid;
2177 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
2178 for (i = x; y && i; y--) {
2179 pgno_t yp = src[y].mid;
2180 while (yp < dst[i].mid)
2182 if (yp == dst[i].mid) {
2187 } else { /* Simplify the above for single-ancestor case */
2188 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
2190 /* Merge our dirty list with parent's */
2192 for (i = len; y; dst[i--] = src[y--]) {
2193 pgno_t yp = src[y].mid;
2194 while (yp < dst[x].mid)
2195 dst[i--] = dst[x--];
2196 if (yp == dst[x].mid)
2197 free(dst[x--].mptr);
2201 free(txn->mt_u.dirty_list);
2202 parent->mt_dirty_room = txn->mt_dirty_room;
2204 txn->mt_parent->mt_child = NULL;
2205 free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pgfree);
2210 if (txn != env->me_txn) {
2211 DPUTS("attempt to commit unknown transaction");
2216 if (!txn->mt_u.dirty_list[0].mid && !(txn->mt_flags & MDB_TXN_DIRTY))
2219 DPRINTF("committing txn %zu %p on mdbenv %p, root page %zu",
2220 txn->mt_txnid, (void *)txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
2222 /* Update DB root pointers */
2223 if (txn->mt_numdbs > 2) {
2226 data.mv_size = sizeof(MDB_db);
2228 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
2229 for (i = 2; i < txn->mt_numdbs; i++) {
2230 if (txn->mt_dbflags[i] & DB_DIRTY) {
2231 data.mv_data = &txn->mt_dbs[i];
2232 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
2239 /* Save the freelist as of this transaction to the freeDB. This
2240 * can change the freelist, so keep trying until it stabilizes.
2242 * env->me_pglast and the length of txn->mt_free_pgs cannot decrease,
2243 * except the code below can decrease env->me_pglast to split pghead.
2244 * Page numbers cannot disappear from txn->mt_free_pgs. New pages
2245 * can only appear in env->me_pghead when env->me_pglast increases.
2246 * Until then, the me_pghead pointer won't move but can become NULL.
2249 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
2250 oldpg_txnid = id = 0;
2253 /* should only be one record now */
2254 if (env->me_pghead || env->me_pglast) {
2255 /* make sure first page of freeDB is touched and on freelist */
2256 rc = mdb_page_search(&mc, NULL, MDB_PS_MODIFY);
2257 if (rc && rc != MDB_NOTFOUND) {
2264 /* Delete IDLs we used from the free list */
2265 if (env->me_pglast) {
2270 rc = mdb_cursor_first(&mc, &key, NULL);
2273 oldpg_txnid = *(txnid_t *)key.mv_data;
2275 assert(oldpg_txnid <= env->me_pglast);
2277 rc = mdb_cursor_del(&mc, 0);
2280 } while (oldpg_txnid < env->me_pglast);
2283 /* Save IDL of pages freed by this txn, to freeDB */
2285 if (freecnt != txn->mt_free_pgs[0]) {
2288 /* make sure last page of freeDB is touched and on freelist */
2289 key.mv_size = MDB_MAXKEYSIZE+1;
2291 rc = mdb_page_search(&mc, &key, MDB_PS_MODIFY);
2292 if (rc && rc != MDB_NOTFOUND)
2298 MDB_IDL idl = txn->mt_free_pgs;
2299 mdb_midl_sort(txn->mt_free_pgs);
2300 DPRINTF("IDL write txn %zu root %zu num %zu",
2301 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
2302 for (i=1; i<=idl[0]; i++) {
2303 DPRINTF("IDL %zu", idl[i]);
2307 /* write to last page of freeDB */
2308 key.mv_size = sizeof(pgno_t);
2309 key.mv_data = &txn->mt_txnid;
2310 /* The free list can still grow during this call,
2311 * despite the pre-emptive touches above. So retry
2312 * until the reserved space remains big enough.
2315 assert(freecnt < txn->mt_free_pgs[0]);
2316 freecnt = txn->mt_free_pgs[0];
2317 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
2318 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2321 } while (freecnt != txn->mt_free_pgs[0]);
2322 mdb_midl_sort(txn->mt_free_pgs);
2323 memcpy(data.mv_data, txn->mt_free_pgs, data.mv_size);
2324 if (oldpg_txnid < env->me_pglast || (!env->me_pghead && id))
2325 goto free_pgfirst; /* used up freeDB[oldpg_txnid] */
2328 /* Put back page numbers we took from freeDB but did not use */
2329 if (env->me_pghead) {
2334 mop = env->me_pghead;
2335 id = env->me_pglast;
2336 key.mv_size = sizeof(id);
2338 /* These steps may grow the freelist again
2339 * due to freed overflow pages...
2344 if (orig > env->me_maxfree_1pg && id > 4)
2345 orig = env->me_maxfree_1pg; /* Do not use more than 1 page */
2346 data.mv_size = (orig + 1) * sizeof(pgno_t);
2347 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2350 assert(!env->me_pghead || env->me_pglast);
2351 /* mop could have been used again here */
2352 if (id != env->me_pglast || env->me_pghead == NULL)
2353 goto again; /* was completely used up */
2354 assert(mop == env->me_pghead);
2355 } while (mop[0] < orig && --i);
2356 memcpy(data.mv_data, mop, data.mv_size);
2359 *(pgno_t *)data.mv_data = orig;
2360 mop[orig] = mop[0] - orig;
2361 env->me_pghead = mop += orig;
2362 /* Save more oldpages at the previous txnid. */
2363 assert(env->me_pglast == id && id == oldpg_txnid);
2364 env->me_pglast = --oldpg_txnid;
2368 /* Check for growth of freelist again */
2369 if (freecnt != txn->mt_free_pgs[0])
2372 free(env->me_pgfree);
2373 env->me_pghead = env->me_pgfree = NULL;
2375 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
2376 if (mdb_midl_shrink(&txn->mt_free_pgs))
2377 env->me_free_pgs = txn->mt_free_pgs;
2384 if (env->me_flags & MDB_WRITEMAP) {
2385 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
2386 dp = txn->mt_u.dirty_list[i].mptr;
2387 /* clear dirty flag */
2388 dp->mp_flags &= ~P_DIRTY;
2389 txn->mt_u.dirty_list[i].mid = 0;
2391 txn->mt_u.dirty_list[0].mid = 0;
2395 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
2401 /* Windows actually supports scatter/gather I/O, but only on
2402 * unbuffered file handles. Since we're relying on the OS page
2403 * cache for all our data, that's self-defeating. So we just
2404 * write pages one at a time. We use the ov structure to set
2405 * the write offset, to at least save the overhead of a Seek
2409 memset(&ov, 0, sizeof(ov));
2410 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
2412 dp = txn->mt_u.dirty_list[i].mptr;
2413 DPRINTF("committing page %zu", dp->mp_pgno);
2414 size = dp->mp_pgno * env->me_psize;
2415 ov.Offset = size & 0xffffffff;
2416 ov.OffsetHigh = size >> 16;
2417 ov.OffsetHigh >>= 16;
2418 /* clear dirty flag */
2419 dp->mp_flags &= ~P_DIRTY;
2420 wsize = env->me_psize;
2421 if (IS_OVERFLOW(dp)) wsize *= dp->mp_pages;
2422 rc = WriteFile(env->me_fd, dp, wsize, NULL, &ov);
2425 DPRINTF("WriteFile: %d", n);
2432 struct iovec iov[MDB_COMMIT_PAGES];
2436 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
2437 dp = txn->mt_u.dirty_list[i].mptr;
2438 if (dp->mp_pgno != next) {
2440 rc = writev(env->me_fd, iov, n);
2444 DPUTS("short write, filesystem full?");
2446 DPRINTF("writev: %s", strerror(n));
2453 lseek(env->me_fd, dp->mp_pgno * env->me_psize, SEEK_SET);
2456 DPRINTF("committing page %zu", dp->mp_pgno);
2457 iov[n].iov_len = env->me_psize;
2458 if (IS_OVERFLOW(dp)) iov[n].iov_len *= dp->mp_pages;
2459 iov[n].iov_base = (char *)dp;
2460 size += iov[n].iov_len;
2461 next = dp->mp_pgno + (IS_OVERFLOW(dp) ? dp->mp_pages : 1);
2462 /* clear dirty flag */
2463 dp->mp_flags &= ~P_DIRTY;
2464 if (++n >= MDB_COMMIT_PAGES) {
2474 rc = writev(env->me_fd, iov, n);
2478 DPUTS("short write, filesystem full?");
2480 DPRINTF("writev: %s", strerror(n));
2487 /* Drop the dirty pages.
2489 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
2490 dp = txn->mt_u.dirty_list[i].mptr;
2491 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
2492 mdb_page_free(txn->mt_env, dp);
2494 VGMEMP_FREE(txn->mt_env, dp);
2497 txn->mt_u.dirty_list[i].mid = 0;
2499 txn->mt_u.dirty_list[0].mid = 0;
2502 if ((n = mdb_env_sync(env, 0)) != 0 ||
2503 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
2511 /* update the DB flags */
2512 for (i = 2; i<txn->mt_numdbs; i++) {
2513 if (txn->mt_dbflags[i] & DB_NEW)
2514 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2516 if (txn->mt_numdbs > env->me_numdbs)
2517 env->me_numdbs = txn->mt_numdbs;
2519 UNLOCK_MUTEX_W(env);
2525 /** Read the environment parameters of a DB environment before
2526 * mapping it into memory.
2527 * @param[in] env the environment handle
2528 * @param[out] meta address of where to store the meta information
2529 * @return 0 on success, non-zero on failure.
2532 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
2539 /* We don't know the page size yet, so use a minimum value.
2540 * Read both meta pages so we can use the latest one.
2543 for (i=0; i<2; i++) {
2545 if (!ReadFile(env->me_fd, &pbuf, MDB_PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
2547 if ((rc = read(env->me_fd, &pbuf, MDB_PAGESIZE)) == 0)
2552 else if (rc != MDB_PAGESIZE) {
2556 DPRINTF("read: %s", strerror(err));
2560 p = (MDB_page *)&pbuf;
2562 if (!F_ISSET(p->mp_flags, P_META)) {
2563 DPRINTF("page %zu not a meta page", p->mp_pgno);
2568 if (m->mm_magic != MDB_MAGIC) {
2569 DPUTS("meta has invalid magic");
2573 if (m->mm_version != MDB_VERSION) {
2574 DPRINTF("database is version %u, expected version %u",
2575 m->mm_version, MDB_VERSION);
2576 return MDB_VERSION_MISMATCH;
2580 if (m->mm_txnid > meta->mm_txnid)
2581 memcpy(meta, m, sizeof(*m));
2583 memcpy(meta, m, sizeof(*m));
2585 if (SetFilePointer(env->me_fd, meta->mm_psize, NULL, FILE_BEGIN) != meta->mm_psize)
2587 if (lseek(env->me_fd, meta->mm_psize, SEEK_SET) != meta->mm_psize)
2595 /** Write the environment parameters of a freshly created DB environment.
2596 * @param[in] env the environment handle
2597 * @param[out] meta address of where to store the meta information
2598 * @return 0 on success, non-zero on failure.
2601 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
2608 DPUTS("writing new meta page");
2610 GET_PAGESIZE(psize);
2612 meta->mm_magic = MDB_MAGIC;
2613 meta->mm_version = MDB_VERSION;
2614 meta->mm_mapsize = env->me_mapsize;
2615 meta->mm_psize = psize;
2616 meta->mm_last_pg = 1;
2617 meta->mm_flags = env->me_flags & 0xffff;
2618 meta->mm_flags |= MDB_INTEGERKEY;
2619 meta->mm_dbs[0].md_root = P_INVALID;
2620 meta->mm_dbs[1].md_root = P_INVALID;
2622 p = calloc(2, psize);
2624 p->mp_flags = P_META;
2627 memcpy(m, meta, sizeof(*meta));
2629 q = (MDB_page *)((char *)p + psize);
2632 q->mp_flags = P_META;
2635 memcpy(m, meta, sizeof(*meta));
2640 SetFilePointer(env->me_fd, 0, NULL, FILE_BEGIN);
2641 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
2642 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
2645 lseek(env->me_fd, 0, SEEK_SET);
2646 rc = write(env->me_fd, p, psize * 2);
2647 rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
2653 /** Update the environment info to commit a transaction.
2654 * @param[in] txn the transaction that's being committed
2655 * @return 0 on success, non-zero on failure.
2658 mdb_env_write_meta(MDB_txn *txn)
2661 MDB_meta meta, metab, *mp;
2663 int rc, len, toggle;
2670 assert(txn != NULL);
2671 assert(txn->mt_env != NULL);
2673 toggle = !txn->mt_toggle;
2674 DPRINTF("writing meta page %d for root page %zu",
2675 toggle, txn->mt_dbs[MAIN_DBI].md_root);
2678 mp = env->me_metas[toggle];
2680 if (env->me_flags & MDB_WRITEMAP) {
2681 /* Persist any increases of mapsize config */
2682 if (env->me_mapsize > mp->mm_mapsize)
2683 mp->mm_mapsize = env->me_mapsize;
2684 mp->mm_dbs[0] = txn->mt_dbs[0];
2685 mp->mm_dbs[1] = txn->mt_dbs[1];
2686 mp->mm_last_pg = txn->mt_next_pgno - 1;
2687 mp->mm_txnid = txn->mt_txnid;
2688 if (!(env->me_flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
2689 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
2692 ptr += env->me_psize;
2693 if (MDB_MSYNC(ptr, env->me_psize, rc)) {
2700 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
2701 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
2703 ptr = (char *)&meta;
2704 if (env->me_mapsize > mp->mm_mapsize) {
2705 /* Persist any increases of mapsize config */
2706 meta.mm_mapsize = env->me_mapsize;
2707 off = offsetof(MDB_meta, mm_mapsize);
2709 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
2711 len = sizeof(MDB_meta) - off;
2714 meta.mm_dbs[0] = txn->mt_dbs[0];
2715 meta.mm_dbs[1] = txn->mt_dbs[1];
2716 meta.mm_last_pg = txn->mt_next_pgno - 1;
2717 meta.mm_txnid = txn->mt_txnid;
2720 off += env->me_psize;
2723 /* Write to the SYNC fd */
2724 mfd = env->me_flags & (MDB_NOSYNC|MDB_NOMETASYNC) ?
2725 env->me_fd : env->me_mfd;
2728 memset(&ov, 0, sizeof(ov));
2730 WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov);
2733 rc = pwrite(mfd, ptr, len, off);
2738 DPUTS("write failed, disk error?");
2739 /* On a failure, the pagecache still contains the new data.
2740 * Write some old data back, to prevent it from being used.
2741 * Use the non-SYNC fd; we know it will fail anyway.
2743 meta.mm_last_pg = metab.mm_last_pg;
2744 meta.mm_txnid = metab.mm_txnid;
2746 WriteFile(env->me_fd, ptr, len, NULL, &ov);
2748 r2 = pwrite(env->me_fd, ptr, len, off);
2751 env->me_flags |= MDB_FATAL_ERROR;
2755 /* Memory ordering issues are irrelevant; since the entire writer
2756 * is wrapped by wmutex, all of these changes will become visible
2757 * after the wmutex is unlocked. Since the DB is multi-version,
2758 * readers will get consistent data regardless of how fresh or
2759 * how stale their view of these values is.
2761 txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
2766 /** Check both meta pages to see which one is newer.
2767 * @param[in] env the environment handle
2768 * @return meta toggle (0 or 1).
2771 mdb_env_pick_meta(const MDB_env *env)
2773 return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
2777 mdb_env_create(MDB_env **env)
2781 e = calloc(1, sizeof(MDB_env));
2785 e->me_maxreaders = DEFAULT_READERS;
2786 e->me_maxdbs = e->me_numdbs = 2;
2787 e->me_fd = INVALID_HANDLE_VALUE;
2788 e->me_lfd = INVALID_HANDLE_VALUE;
2789 e->me_mfd = INVALID_HANDLE_VALUE;
2790 #ifdef MDB_USE_POSIX_SEM
2791 e->me_rmutex = SEM_FAILED;
2792 e->me_wmutex = SEM_FAILED;
2794 e->me_pid = getpid();
2795 VGMEMP_CREATE(e,0,0);
2801 mdb_env_set_mapsize(MDB_env *env, size_t size)
2805 env->me_mapsize = size;
2807 env->me_maxpg = env->me_mapsize / env->me_psize;
2812 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
2816 env->me_maxdbs = dbs + 2; /* Named databases + main and free DB */
2821 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
2823 if (env->me_map || readers < 1)
2825 env->me_maxreaders = readers;
2830 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
2832 if (!env || !readers)
2834 *readers = env->me_maxreaders;
2838 /** Further setup required for opening an MDB environment
2841 mdb_env_open2(MDB_env *env)
2843 unsigned int flags = env->me_flags;
2844 int i, newenv = 0, prot;
2848 memset(&meta, 0, sizeof(meta));
2850 if ((i = mdb_env_read_header(env, &meta)) != 0) {
2853 DPUTS("new mdbenv");
2857 /* Was a mapsize configured? */
2858 if (!env->me_mapsize) {
2859 /* If this is a new environment, take the default,
2860 * else use the size recorded in the existing env.
2862 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
2863 } else if (env->me_mapsize < meta.mm_mapsize) {
2864 /* If the configured size is smaller, make sure it's
2865 * still big enough. Silently round up to minimum if not.
2867 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
2868 if (env->me_mapsize < minsize)
2869 env->me_mapsize = minsize;
2875 LONG sizelo, sizehi;
2876 sizelo = env->me_mapsize & 0xffffffff;
2877 sizehi = env->me_mapsize >> 16; /* pointless on WIN32, only needed on W64 */
2879 /* Windows won't create mappings for zero length files.
2880 * Just allocate the maxsize right now.
2883 SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
2884 if (!SetEndOfFile(env->me_fd))
2886 SetFilePointer(env->me_fd, 0, NULL, 0);
2888 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
2889 PAGE_READWRITE : PAGE_READONLY,
2890 sizehi, sizelo, NULL);
2893 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
2894 FILE_MAP_WRITE : FILE_MAP_READ,
2895 0, 0, env->me_mapsize, meta.mm_address);
2903 if (flags & MDB_WRITEMAP) {
2905 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
2908 env->me_map = mmap(meta.mm_address, env->me_mapsize, prot, i,
2910 if (env->me_map == MAP_FAILED) {
2914 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
2916 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
2918 #ifdef POSIX_MADV_RANDOM
2919 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
2920 #endif /* POSIX_MADV_RANDOM */
2921 #endif /* MADV_RANDOM */
2925 if (flags & MDB_FIXEDMAP)
2926 meta.mm_address = env->me_map;
2927 i = mdb_env_init_meta(env, &meta);
2928 if (i != MDB_SUCCESS) {
2931 } else if (meta.mm_address && env->me_map != meta.mm_address) {
2932 /* Can happen because the address argument to mmap() is just a
2933 * hint. mmap() can pick another, e.g. if the range is in use.
2934 * The MAP_FIXED flag would prevent that, but then mmap could
2935 * instead unmap existing pages to make room for the new map.
2937 return EBUSY; /* TODO: Make a new MDB_* error code? */
2939 env->me_psize = meta.mm_psize;
2940 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
2941 env->me_nodemax = (env->me_psize - PAGEHDRSZ) / MDB_MINKEYS;
2943 env->me_maxpg = env->me_mapsize / env->me_psize;
2945 p = (MDB_page *)env->me_map;
2946 env->me_metas[0] = METADATA(p);
2947 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
2951 int toggle = mdb_env_pick_meta(env);
2952 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
2954 DPRINTF("opened database version %u, pagesize %u",
2955 env->me_metas[0]->mm_version, env->me_psize);
2956 DPRINTF("using meta page %d", toggle);
2957 DPRINTF("depth: %u", db->md_depth);
2958 DPRINTF("entries: %zu", db->md_entries);
2959 DPRINTF("branch pages: %zu", db->md_branch_pages);
2960 DPRINTF("leaf pages: %zu", db->md_leaf_pages);
2961 DPRINTF("overflow pages: %zu", db->md_overflow_pages);
2962 DPRINTF("root: %zu", db->md_root);
2970 /** Release a reader thread's slot in the reader lock table.
2971 * This function is called automatically when a thread exits.
2972 * @param[in] ptr This points to the slot in the reader lock table.
2975 mdb_env_reader_dest(void *ptr)
2977 MDB_reader *reader = ptr;
2983 /** Junk for arranging thread-specific callbacks on Windows. This is
2984 * necessarily platform and compiler-specific. Windows supports up
2985 * to 1088 keys. Let's assume nobody opens more than 64 environments
2986 * in a single process, for now. They can override this if needed.
2988 #ifndef MAX_TLS_KEYS
2989 #define MAX_TLS_KEYS 64
2991 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
2992 static int mdb_tls_nkeys;
2994 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
2998 case DLL_PROCESS_ATTACH: break;
2999 case DLL_THREAD_ATTACH: break;
3000 case DLL_THREAD_DETACH:
3001 for (i=0; i<mdb_tls_nkeys; i++) {
3002 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
3003 mdb_env_reader_dest(r);
3006 case DLL_PROCESS_DETACH: break;
3011 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3013 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3017 /* Force some symbol references.
3018 * _tls_used forces the linker to create the TLS directory if not already done
3019 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
3021 #pragma comment(linker, "/INCLUDE:_tls_used")
3022 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
3023 #pragma const_seg(".CRT$XLB")
3024 extern const PIMAGE_TLS_CALLBACK mdb_tls_callback;
3025 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3028 #pragma comment(linker, "/INCLUDE:__tls_used")
3029 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
3030 #pragma data_seg(".CRT$XLB")
3031 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3033 #endif /* WIN 32/64 */
3034 #endif /* !__GNUC__ */
3037 /** Downgrade the exclusive lock on the region back to shared */
3039 mdb_env_share_locks(MDB_env *env, int *excl)
3041 int rc = 0, toggle = mdb_env_pick_meta(env);
3043 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
3048 /* First acquire a shared lock. The Unlock will
3049 * then release the existing exclusive lock.
3051 memset(&ov, 0, sizeof(ov));
3052 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3055 UnlockFile(env->me_lfd, 0, 0, 1, 0);
3061 struct flock lock_info;
3062 /* The shared lock replaces the existing lock */
3063 memset((void *)&lock_info, 0, sizeof(lock_info));
3064 lock_info.l_type = F_RDLCK;
3065 lock_info.l_whence = SEEK_SET;
3066 lock_info.l_start = 0;
3067 lock_info.l_len = 1;
3068 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3069 (rc = ErrCode()) == EINTR) ;
3070 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
3077 /** Try to get exlusive lock, otherwise shared.
3078 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
3081 mdb_env_excl_lock(MDB_env *env, int *excl)
3085 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
3089 memset(&ov, 0, sizeof(ov));
3090 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3097 struct flock lock_info;
3098 memset((void *)&lock_info, 0, sizeof(lock_info));
3099 lock_info.l_type = F_WRLCK;
3100 lock_info.l_whence = SEEK_SET;
3101 lock_info.l_start = 0;
3102 lock_info.l_len = 1;
3103 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3104 (rc = ErrCode()) == EINTR) ;
3108 # ifdef MDB_USE_POSIX_SEM
3109 if (*excl < 0) /* always true when !MDB_USE_POSIX_SEM */
3112 lock_info.l_type = F_RDLCK;
3113 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
3114 (rc = ErrCode()) == EINTR) ;
3122 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
3124 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
3126 * @(#) $Revision: 5.1 $
3127 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
3128 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
3130 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
3134 * Please do not copyright this code. This code is in the public domain.
3136 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
3137 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
3138 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
3139 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
3140 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
3141 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
3142 * PERFORMANCE OF THIS SOFTWARE.
3145 * chongo <Landon Curt Noll> /\oo/\
3146 * http://www.isthe.com/chongo/
3148 * Share and Enjoy! :-)
3151 typedef unsigned long long mdb_hash_t;
3152 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
3154 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
3155 * @param[in] str string to hash
3156 * @param[in] hval initial value for hash
3157 * @return 64 bit hash
3159 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
3160 * hval arg on the first call.
3163 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
3165 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
3166 unsigned char *end = s + val->mv_size;
3168 * FNV-1a hash each octet of the string
3171 /* xor the bottom with the current octet */
3172 hval ^= (mdb_hash_t)*s++;
3174 /* multiply by the 64 bit FNV magic prime mod 2^64 */
3175 hval += (hval << 1) + (hval << 4) + (hval << 5) +
3176 (hval << 7) + (hval << 8) + (hval << 40);
3178 /* return our new hash value */
3182 /** Hash the string and output the hash in hex.
3183 * @param[in] str string to hash
3184 * @param[out] hexbuf an array of 17 chars to hold the hash
3187 mdb_hash_hex(MDB_val *val, char *hexbuf)
3190 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
3191 for (i=0; i<8; i++) {
3192 hexbuf += sprintf(hexbuf, "%02x", (unsigned int)h & 0xff);
3198 /** Open and/or initialize the lock region for the environment.
3199 * @param[in] env The MDB environment.
3200 * @param[in] lpath The pathname of the file used for the lock region.
3201 * @param[in] mode The Unix permissions for the file, if we create it.
3202 * @param[out] excl Resulting file lock type: -1 none, 0 shared, 1 exclusive
3203 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
3204 * @return 0 on success, non-zero on failure.
3207 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
3210 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
3212 # define MDB_ERRCODE_ROFS EROFS
3213 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
3214 # define MDB_CLOEXEC O_CLOEXEC
3217 # define MDB_CLOEXEC 0
3224 env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
3225 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
3226 FILE_ATTRIBUTE_NORMAL, NULL);
3228 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
3230 if (env->me_lfd == INVALID_HANDLE_VALUE) {
3232 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
3237 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
3238 /* Lose record locks when exec*() */
3239 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
3240 fcntl(env->me_lfd, F_SETFD, fdflags);
3244 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
3247 env->me_flags |= MDB_ENV_TXKEY;
3249 /* Windows TLS callbacks need help finding their TLS info. */
3250 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
3254 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
3258 /* Try to get exclusive lock. If we succeed, then
3259 * nobody is using the lock region and we should initialize it.
3261 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
3264 size = GetFileSize(env->me_lfd, NULL);
3266 size = lseek(env->me_lfd, 0, SEEK_END);
3268 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
3269 if (size < rsize && *excl > 0) {
3271 SetFilePointer(env->me_lfd, rsize, NULL, 0);
3272 if (!SetEndOfFile(env->me_lfd)) goto fail_errno;
3274 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
3278 size = rsize - sizeof(MDB_txninfo);
3279 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
3284 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
3286 if (!mh) goto fail_errno;
3287 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
3289 if (!env->me_txns) goto fail_errno;
3291 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
3293 if (m == MAP_FAILED) goto fail_errno;
3299 BY_HANDLE_FILE_INFORMATION stbuf;
3308 if (!mdb_sec_inited) {
3309 InitializeSecurityDescriptor(&mdb_null_sd,
3310 SECURITY_DESCRIPTOR_REVISION);
3311 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
3312 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
3313 mdb_all_sa.bInheritHandle = FALSE;
3314 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
3317 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
3318 idbuf.volume = stbuf.dwVolumeSerialNumber;
3319 idbuf.nhigh = stbuf.nFileIndexHigh;
3320 idbuf.nlow = stbuf.nFileIndexLow;
3321 val.mv_data = &idbuf;
3322 val.mv_size = sizeof(idbuf);
3323 mdb_hash_hex(&val, hexbuf);
3324 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", hexbuf);
3325 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", hexbuf);
3326 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
3327 if (!env->me_rmutex) goto fail_errno;
3328 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
3329 if (!env->me_wmutex) goto fail_errno;
3330 #elif defined(MDB_USE_POSIX_SEM)
3339 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
3340 idbuf.dev = stbuf.st_dev;
3341 idbuf.ino = stbuf.st_ino;
3342 val.mv_data = &idbuf;
3343 val.mv_size = sizeof(idbuf);
3344 mdb_hash_hex(&val, hexbuf);
3345 sprintf(env->me_txns->mti_rmname, "/MDBr%s", hexbuf);
3346 sprintf(env->me_txns->mti_wmname, "/MDBw%s", hexbuf);
3347 /* Clean up after a previous run, if needed: Try to
3348 * remove both semaphores before doing anything else.
3350 sem_unlink(env->me_txns->mti_rmname);
3351 sem_unlink(env->me_txns->mti_wmname);
3352 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
3353 O_CREAT|O_EXCL, mode, 1);
3354 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3355 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
3356 O_CREAT|O_EXCL, mode, 1);
3357 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3358 #else /* MDB_USE_POSIX_SEM */
3359 pthread_mutexattr_t mattr;
3361 if ((rc = pthread_mutexattr_init(&mattr))
3362 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
3363 || (rc = pthread_mutex_init(&env->me_txns->mti_mutex, &mattr))
3364 || (rc = pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr)))
3366 pthread_mutexattr_destroy(&mattr);
3367 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
3369 env->me_txns->mti_version = MDB_VERSION;
3370 env->me_txns->mti_magic = MDB_MAGIC;
3371 env->me_txns->mti_txnid = 0;
3372 env->me_txns->mti_numreaders = 0;
3375 if (env->me_txns->mti_magic != MDB_MAGIC) {
3376 DPUTS("lock region has invalid magic");
3380 if (env->me_txns->mti_version != MDB_VERSION) {
3381 DPRINTF("lock region is version %u, expected version %u",
3382 env->me_txns->mti_version, MDB_VERSION);
3383 rc = MDB_VERSION_MISMATCH;
3387 if (rc != EACCES && rc != EAGAIN) {
3391 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
3392 if (!env->me_rmutex) goto fail_errno;
3393 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
3394 if (!env->me_wmutex) goto fail_errno;
3395 #elif defined(MDB_USE_POSIX_SEM)
3396 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
3397 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3398 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
3399 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3410 /** The name of the lock file in the DB environment */
3411 #define LOCKNAME "/lock.mdb"
3412 /** The name of the data file in the DB environment */
3413 #define DATANAME "/data.mdb"
3414 /** The suffix of the lock file when no subdir is used */
3415 #define LOCKSUFF "-lock"
3416 /** Only a subset of the @ref mdb_env flags can be changed
3417 * at runtime. Changing other flags requires closing the
3418 * environment and re-opening it with the new flags.
3420 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC)
3421 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY|MDB_WRITEMAP)
3424 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
3426 int oflags, rc, len, excl = -1;
3427 char *lpath, *dpath;
3429 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
3433 if (flags & MDB_NOSUBDIR) {
3434 rc = len + sizeof(LOCKSUFF) + len + 1;
3436 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
3441 if (flags & MDB_NOSUBDIR) {
3442 dpath = lpath + len + sizeof(LOCKSUFF);
3443 sprintf(lpath, "%s" LOCKSUFF, path);
3444 strcpy(dpath, path);
3446 dpath = lpath + len + sizeof(LOCKNAME);
3447 sprintf(lpath, "%s" LOCKNAME, path);
3448 sprintf(dpath, "%s" DATANAME, path);
3452 flags |= env->me_flags;
3453 if (flags & MDB_RDONLY) {
3454 /* silently ignore WRITEMAP when we're only getting read access */
3455 flags &= ~MDB_WRITEMAP;
3457 if (!((env->me_free_pgs = mdb_midl_alloc()) &&
3458 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
3461 env->me_flags = flags |= MDB_ENV_ACTIVE;
3465 env->me_path = strdup(path);
3466 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
3467 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
3468 if (!(env->me_dbxs && env->me_path && env->me_dbflags)) {
3473 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
3478 if (F_ISSET(flags, MDB_RDONLY)) {
3479 oflags = GENERIC_READ;
3480 len = OPEN_EXISTING;
3482 oflags = GENERIC_READ|GENERIC_WRITE;
3485 mode = FILE_ATTRIBUTE_NORMAL;
3486 env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
3487 NULL, len, mode, NULL);
3489 if (F_ISSET(flags, MDB_RDONLY))
3492 oflags = O_RDWR | O_CREAT;
3494 env->me_fd = open(dpath, oflags, mode);
3496 if (env->me_fd == INVALID_HANDLE_VALUE) {
3501 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
3502 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
3503 env->me_mfd = env->me_fd;
3505 /* Synchronous fd for meta writes. Needed even with
3506 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
3509 env->me_mfd = CreateFile(dpath, oflags,
3510 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
3511 mode | FILE_FLAG_WRITE_THROUGH, NULL);
3513 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
3515 if (env->me_mfd == INVALID_HANDLE_VALUE) {
3520 DPRINTF("opened dbenv %p", (void *) env);
3522 rc = mdb_env_share_locks(env, &excl);
3528 mdb_env_close0(env, excl);
3534 /** Destroy resources from mdb_env_open() and clear our readers */
3536 mdb_env_close0(MDB_env *env, int excl)
3540 if (!(env->me_flags & MDB_ENV_ACTIVE))
3543 free(env->me_dbflags);
3546 free(env->me_dirty_list);
3547 if (env->me_free_pgs)
3548 mdb_midl_free(env->me_free_pgs);
3550 if (env->me_flags & MDB_ENV_TXKEY) {
3551 pthread_key_delete(env->me_txkey);
3553 /* Delete our key from the global list */
3554 for (i=0; i<mdb_tls_nkeys; i++)
3555 if (mdb_tls_keys[i] == env->me_txkey) {
3556 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
3564 munmap(env->me_map, env->me_mapsize);
3566 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
3568 if (env->me_fd != INVALID_HANDLE_VALUE)
3571 pid_t pid = env->me_pid;
3572 /* Clearing readers is done in this function because
3573 * me_txkey with its destructor must be disabled first.
3575 for (i = env->me_numreaders; --i >= 0; )
3576 if (env->me_txns->mti_readers[i].mr_pid == pid)
3577 env->me_txns->mti_readers[i].mr_pid = 0;
3579 if (env->me_rmutex) {
3580 CloseHandle(env->me_rmutex);
3581 if (env->me_wmutex) CloseHandle(env->me_wmutex);
3583 /* Windows automatically destroys the mutexes when
3584 * the last handle closes.
3586 #elif defined(MDB_USE_POSIX_SEM)
3587 if (env->me_rmutex != SEM_FAILED) {
3588 sem_close(env->me_rmutex);
3589 if (env->me_wmutex != SEM_FAILED)
3590 sem_close(env->me_wmutex);
3591 /* If we have the filelock: If we are the
3592 * only remaining user, clean up semaphores.
3595 mdb_env_excl_lock(env, &excl);
3597 sem_unlink(env->me_txns->mti_rmname);
3598 sem_unlink(env->me_txns->mti_wmname);
3602 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
3604 if (env->me_lfd != INVALID_HANDLE_VALUE) {
3607 /* Unlock the lockfile. Windows would have unlocked it
3608 * after closing anyway, but not necessarily at once.
3610 UnlockFile(env->me_lfd, 0, 0, 1, 0);
3616 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
3620 mdb_env_copy(MDB_env *env, const char *path)
3622 MDB_txn *txn = NULL;
3626 HANDLE newfd = INVALID_HANDLE_VALUE;
3628 if (env->me_flags & MDB_NOSUBDIR) {
3629 lpath = (char *)path;
3632 len += sizeof(DATANAME);
3633 lpath = malloc(len);
3636 sprintf(lpath, "%s" DATANAME, path);
3639 /* The destination path must exist, but the destination file must not.
3640 * We don't want the OS to cache the writes, since the source data is
3641 * already in the OS cache.
3644 newfd = CreateFile(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
3645 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
3647 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL
3653 if (!(env->me_flags & MDB_NOSUBDIR))
3655 if (newfd == INVALID_HANDLE_VALUE) {
3660 #ifdef F_NOCACHE /* __APPLE__ */
3661 rc = fcntl(newfd, F_NOCACHE, 1);
3668 /* Do the lock/unlock of the reader mutex before starting the
3669 * write txn. Otherwise other read txns could block writers.
3671 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
3676 /* We must start the actual read txn after blocking writers */
3677 mdb_txn_reset0(txn);
3679 /* Temporarily block writers until we snapshot the meta pages */
3682 rc = mdb_txn_renew0(txn);
3684 UNLOCK_MUTEX_W(env);
3689 wsize = env->me_psize * 2;
3693 rc = WriteFile(newfd, env->me_map, wsize, &len, NULL);
3694 rc = (len == wsize) ? MDB_SUCCESS : ErrCode();
3697 rc = write(newfd, env->me_map, wsize);
3698 rc = (rc == (int)wsize) ? MDB_SUCCESS : ErrCode();
3701 UNLOCK_MUTEX_W(env);
3706 ptr = env->me_map + wsize;
3707 wsize = txn->mt_next_pgno * env->me_psize - wsize;
3708 #define MAX_WRITE 2147483648U
3712 if (wsize > MAX_WRITE)
3716 rc = WriteFile(newfd, ptr, w2, &len, NULL);
3717 rc = (len == w2) ? MDB_SUCCESS : ErrCode();
3726 if (wsize > MAX_WRITE)
3730 wres = write(newfd, ptr, w2);
3731 rc = (wres > 0) ? MDB_SUCCESS : ErrCode();
3740 if (newfd != INVALID_HANDLE_VALUE)
3747 mdb_env_close(MDB_env *env)
3755 for (i = env->me_numdbs; --i > MAIN_DBI; )
3756 free(env->me_dbxs[i].md_name.mv_data);
3758 VGMEMP_DESTROY(env);
3759 while ((dp = env->me_dpages) != NULL) {
3760 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
3761 env->me_dpages = dp->mp_next;
3765 mdb_env_close0(env, 0);
3769 /** Compare two items pointing at aligned size_t's */
3771 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
3773 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
3774 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
3777 /** Compare two items pointing at aligned int's */
3779 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
3781 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
3782 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
3785 /** Compare two items pointing at ints of unknown alignment.
3786 * Nodes and keys are guaranteed to be 2-byte aligned.
3789 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
3791 #if BYTE_ORDER == LITTLE_ENDIAN
3792 unsigned short *u, *c;
3795 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
3796 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
3799 } while(!x && u > (unsigned short *)a->mv_data);
3802 return memcmp(a->mv_data, b->mv_data, a->mv_size);
3806 /** Compare two items lexically */
3808 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
3815 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
3821 diff = memcmp(a->mv_data, b->mv_data, len);
3822 return diff ? diff : len_diff<0 ? -1 : len_diff;
3825 /** Compare two items in reverse byte order */
3827 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
3829 const unsigned char *p1, *p2, *p1_lim;
3833 p1_lim = (const unsigned char *)a->mv_data;
3834 p1 = (const unsigned char *)a->mv_data + a->mv_size;
3835 p2 = (const unsigned char *)b->mv_data + b->mv_size;
3837 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
3843 while (p1 > p1_lim) {
3844 diff = *--p1 - *--p2;
3848 return len_diff<0 ? -1 : len_diff;
3851 /** Search for key within a page, using binary search.
3852 * Returns the smallest entry larger or equal to the key.
3853 * If exactp is non-null, stores whether the found entry was an exact match
3854 * in *exactp (1 or 0).
3855 * Updates the cursor index with the index of the found entry.
3856 * If no entry larger or equal to the key is found, returns NULL.
3859 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
3861 unsigned int i = 0, nkeys;
3864 MDB_page *mp = mc->mc_pg[mc->mc_top];
3865 MDB_node *node = NULL;
3870 nkeys = NUMKEYS(mp);
3875 COPY_PGNO(pgno, mp->mp_pgno);
3876 DPRINTF("searching %u keys in %s %spage %zu",
3877 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
3884 low = IS_LEAF(mp) ? 0 : 1;
3886 cmp = mc->mc_dbx->md_cmp;
3888 /* Branch pages have no data, so if using integer keys,
3889 * alignment is guaranteed. Use faster mdb_cmp_int.
3891 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
3892 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
3899 nodekey.mv_size = mc->mc_db->md_pad;
3900 node = NODEPTR(mp, 0); /* fake */
3901 while (low <= high) {
3902 i = (low + high) >> 1;
3903 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
3904 rc = cmp(key, &nodekey);
3905 DPRINTF("found leaf index %u [%s], rc = %i",
3906 i, DKEY(&nodekey), rc);
3915 while (low <= high) {
3916 i = (low + high) >> 1;
3918 node = NODEPTR(mp, i);
3919 nodekey.mv_size = NODEKSZ(node);
3920 nodekey.mv_data = NODEKEY(node);
3922 rc = cmp(key, &nodekey);
3925 DPRINTF("found leaf index %u [%s], rc = %i",
3926 i, DKEY(&nodekey), rc);
3928 DPRINTF("found branch index %u [%s -> %zu], rc = %i",
3929 i, DKEY(&nodekey), NODEPGNO(node), rc);
3940 if (rc > 0) { /* Found entry is less than the key. */
3941 i++; /* Skip to get the smallest entry larger than key. */
3943 node = NODEPTR(mp, i);
3946 *exactp = (rc == 0);
3947 /* store the key index */
3948 mc->mc_ki[mc->mc_top] = i;
3950 /* There is no entry larger or equal to the key. */
3953 /* nodeptr is fake for LEAF2 */
3959 mdb_cursor_adjust(MDB_cursor *mc, func)
3963 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
3964 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
3971 /** Pop a page off the top of the cursor's stack. */
3973 mdb_cursor_pop(MDB_cursor *mc)
3976 #ifndef MDB_DEBUG_SKIP
3977 MDB_page *top = mc->mc_pg[mc->mc_top];
3983 DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
3984 mc->mc_dbi, (void *) mc);
3988 /** Push a page onto the top of the cursor's stack. */
3990 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
3992 DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
3993 mc->mc_dbi, (void *) mc);
3995 if (mc->mc_snum >= CURSOR_STACK) {
3996 assert(mc->mc_snum < CURSOR_STACK);
3997 return MDB_CURSOR_FULL;
4000 mc->mc_top = mc->mc_snum++;
4001 mc->mc_pg[mc->mc_top] = mp;
4002 mc->mc_ki[mc->mc_top] = 0;
4007 /** Find the address of the page corresponding to a given page number.
4008 * @param[in] txn the transaction for this access.
4009 * @param[in] pgno the page number for the page to retrieve.
4010 * @param[out] ret address of a pointer where the page's address will be stored.
4011 * @return 0 on success, non-zero on failure.
4014 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
4018 if (!((txn->mt_flags & MDB_TXN_RDONLY) |
4019 (txn->mt_env->me_flags & MDB_WRITEMAP)))
4023 MDB_ID2L dl = tx2->mt_u.dirty_list;
4025 unsigned x = mdb_mid2l_search(dl, pgno);
4026 if (x <= dl[0].mid && dl[x].mid == pgno) {
4031 } while ((tx2 = tx2->mt_parent) != NULL);
4034 if (pgno < txn->mt_next_pgno) {
4035 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
4037 DPRINTF("page %zu not found", pgno);
4043 return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
4046 /** Search for the page a given key should be in.
4047 * Pushes parent pages on the cursor stack. This function continues a
4048 * search on a cursor that has already been initialized. (Usually by
4049 * #mdb_page_search() but also by #mdb_node_move().)
4050 * @param[in,out] mc the cursor for this operation.
4051 * @param[in] key the key to search for. If NULL, search for the lowest
4052 * page. (This is used by #mdb_cursor_first().)
4053 * @param[in] flags If MDB_PS_MODIFY set, visited pages are updated with new page numbers.
4054 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
4055 * @return 0 on success, non-zero on failure.
4058 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
4060 MDB_page *mp = mc->mc_pg[mc->mc_top];
4065 while (IS_BRANCH(mp)) {
4069 DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
4070 assert(NUMKEYS(mp) > 1);
4071 DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
4073 if (key == NULL) /* Initialize cursor to first page. */
4075 else if (key->mv_size > MDB_MAXKEYSIZE && key->mv_data == NULL) {
4076 /* cursor to last page */
4080 node = mdb_node_search(mc, key, &exact);
4082 i = NUMKEYS(mp) - 1;
4084 i = mc->mc_ki[mc->mc_top];
4093 DPRINTF("following index %u for key [%s]",
4095 assert(i < NUMKEYS(mp));
4096 node = NODEPTR(mp, i);
4098 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp)))
4101 mc->mc_ki[mc->mc_top] = i;
4102 if ((rc = mdb_cursor_push(mc, mp)))
4106 if ((rc = mdb_page_touch(mc)) != 0)
4108 mp = mc->mc_pg[mc->mc_top];
4113 DPRINTF("internal error, index points to a %02X page!?",
4115 return MDB_CORRUPTED;
4118 DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
4119 key ? DKEY(key) : NULL);
4124 /** Search for the page a given key should be in.
4125 * Pushes parent pages on the cursor stack. This function just sets up
4126 * the search; it finds the root page for \b mc's database and sets this
4127 * as the root of the cursor's stack. Then #mdb_page_search_root() is
4128 * called to complete the search.
4129 * @param[in,out] mc the cursor for this operation.
4130 * @param[in] key the key to search for. If NULL, search for the lowest
4131 * page. (This is used by #mdb_cursor_first().)
4132 * @param[in] modify If true, visited pages are updated with new page numbers.
4133 * @return 0 on success, non-zero on failure.
4136 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
4141 /* Make sure the txn is still viable, then find the root from
4142 * the txn's db table.
4144 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
4145 DPUTS("transaction has failed, must abort");
4148 /* Make sure we're using an up-to-date root */
4149 if (mc->mc_dbi > MAIN_DBI) {
4150 if ((*mc->mc_dbflag & DB_STALE) ||
4151 ((flags & MDB_PS_MODIFY) && !(*mc->mc_dbflag & DB_DIRTY))) {
4153 unsigned char dbflag = 0;
4154 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
4155 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, flags & MDB_PS_MODIFY);
4158 if (*mc->mc_dbflag & DB_STALE) {
4162 MDB_node *leaf = mdb_node_search(&mc2,
4163 &mc->mc_dbx->md_name, &exact);
4165 return MDB_NOTFOUND;
4166 mdb_node_read(mc->mc_txn, leaf, &data);
4167 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
4169 /* The txn may not know this DBI, or another process may
4170 * have dropped and recreated the DB with other flags.
4172 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
4173 return MDB_INCOMPATIBLE;
4174 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
4176 if (flags & MDB_PS_MODIFY)
4178 *mc->mc_dbflag &= ~DB_STALE;
4179 *mc->mc_dbflag |= dbflag;
4182 root = mc->mc_db->md_root;
4184 if (root == P_INVALID) { /* Tree is empty. */
4185 DPUTS("tree is empty");
4186 return MDB_NOTFOUND;
4191 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
4192 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0])))
4198 DPRINTF("db %u root page %zu has flags 0x%X",
4199 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
4201 if (flags & MDB_PS_MODIFY) {
4202 if ((rc = mdb_page_touch(mc)))
4206 if (flags & MDB_PS_ROOTONLY)
4209 return mdb_page_search_root(mc, key, flags);
4212 /** Return the data associated with a given node.
4213 * @param[in] txn The transaction for this operation.
4214 * @param[in] leaf The node being read.
4215 * @param[out] data Updated to point to the node's data.
4216 * @return 0 on success, non-zero on failure.
4219 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
4221 MDB_page *omp; /* overflow page */
4225 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
4226 data->mv_size = NODEDSZ(leaf);
4227 data->mv_data = NODEDATA(leaf);
4231 /* Read overflow data.
4233 data->mv_size = NODEDSZ(leaf);
4234 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
4235 if ((rc = mdb_page_get(txn, pgno, &omp))) {
4236 DPRINTF("read overflow page %zu failed", pgno);
4239 data->mv_data = METADATA(omp);
4245 mdb_get(MDB_txn *txn, MDB_dbi dbi,
4246 MDB_val *key, MDB_val *data)
4255 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
4257 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
4260 if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
4264 mdb_cursor_init(&mc, txn, dbi, &mx);
4265 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
4268 /** Find a sibling for a page.
4269 * Replaces the page at the top of the cursor's stack with the
4270 * specified sibling, if one exists.
4271 * @param[in] mc The cursor for this operation.
4272 * @param[in] move_right Non-zero if the right sibling is requested,
4273 * otherwise the left sibling.
4274 * @return 0 on success, non-zero on failure.
4277 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
4283 if (mc->mc_snum < 2) {
4284 return MDB_NOTFOUND; /* root has no siblings */
4288 DPRINTF("parent page is page %zu, index %u",
4289 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]);
4291 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
4292 : (mc->mc_ki[mc->mc_top] == 0)) {
4293 DPRINTF("no more keys left, moving to %s sibling",
4294 move_right ? "right" : "left");
4295 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
4296 /* undo cursor_pop before returning */
4303 mc->mc_ki[mc->mc_top]++;
4305 mc->mc_ki[mc->mc_top]--;
4306 DPRINTF("just moving to %s index key %u",
4307 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]);
4309 assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
4311 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4312 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp)))
4315 mdb_cursor_push(mc, mp);
4317 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
4322 /** Move the cursor to the next data item. */
4324 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
4330 if (mc->mc_flags & C_EOF) {
4331 return MDB_NOTFOUND;
4334 assert(mc->mc_flags & C_INITIALIZED);
4336 mp = mc->mc_pg[mc->mc_top];
4338 if (mc->mc_db->md_flags & MDB_DUPSORT) {
4339 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4340 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4341 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
4342 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
4343 if (op != MDB_NEXT || rc == MDB_SUCCESS)
4347 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
4348 if (op == MDB_NEXT_DUP)
4349 return MDB_NOTFOUND;
4353 DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
4355 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
4356 DPUTS("=====> move to next sibling page");
4357 if (mdb_cursor_sibling(mc, 1) != MDB_SUCCESS) {
4358 mc->mc_flags |= C_EOF;
4359 mc->mc_flags &= ~C_INITIALIZED;
4360 return MDB_NOTFOUND;
4362 mp = mc->mc_pg[mc->mc_top];
4363 DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
4365 mc->mc_ki[mc->mc_top]++;
4367 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
4368 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
4371 key->mv_size = mc->mc_db->md_pad;
4372 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
4376 assert(IS_LEAF(mp));
4377 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4379 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4380 mdb_xcursor_init1(mc, leaf);
4383 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4386 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4387 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4388 if (rc != MDB_SUCCESS)
4393 MDB_GET_KEY(leaf, key);
4397 /** Move the cursor to the previous data item. */
4399 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
4405 assert(mc->mc_flags & C_INITIALIZED);
4407 mp = mc->mc_pg[mc->mc_top];
4409 if (mc->mc_db->md_flags & MDB_DUPSORT) {
4410 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4411 if (op == MDB_PREV || op == MDB_PREV_DUP) {
4412 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4413 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
4414 if (op != MDB_PREV || rc == MDB_SUCCESS)
4417 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
4418 if (op == MDB_PREV_DUP)
4419 return MDB_NOTFOUND;
4424 DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
4426 if (mc->mc_ki[mc->mc_top] == 0) {
4427 DPUTS("=====> move to prev sibling page");
4428 if (mdb_cursor_sibling(mc, 0) != MDB_SUCCESS) {
4429 mc->mc_flags &= ~C_INITIALIZED;
4430 return MDB_NOTFOUND;
4432 mp = mc->mc_pg[mc->mc_top];
4433 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
4434 DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
4436 mc->mc_ki[mc->mc_top]--;
4438 mc->mc_flags &= ~C_EOF;
4440 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
4441 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
4444 key->mv_size = mc->mc_db->md_pad;
4445 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
4449 assert(IS_LEAF(mp));
4450 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4452 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4453 mdb_xcursor_init1(mc, leaf);
4456 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4459 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4460 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
4461 if (rc != MDB_SUCCESS)
4466 MDB_GET_KEY(leaf, key);
4470 /** Set the cursor on a specific data item. */
4472 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
4473 MDB_cursor_op op, int *exactp)
4477 MDB_node *leaf = NULL;
4482 assert(key->mv_size > 0);
4484 /* See if we're already on the right page */
4485 if (mc->mc_flags & C_INITIALIZED) {
4488 mp = mc->mc_pg[mc->mc_top];
4490 mc->mc_ki[mc->mc_top] = 0;
4491 return MDB_NOTFOUND;
4493 if (mp->mp_flags & P_LEAF2) {
4494 nodekey.mv_size = mc->mc_db->md_pad;
4495 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
4497 leaf = NODEPTR(mp, 0);
4498 MDB_GET_KEY(leaf, &nodekey);
4500 rc = mc->mc_dbx->md_cmp(key, &nodekey);
4502 /* Probably happens rarely, but first node on the page
4503 * was the one we wanted.
4505 mc->mc_ki[mc->mc_top] = 0;
4512 unsigned int nkeys = NUMKEYS(mp);
4514 if (mp->mp_flags & P_LEAF2) {
4515 nodekey.mv_data = LEAF2KEY(mp,
4516 nkeys-1, nodekey.mv_size);
4518 leaf = NODEPTR(mp, nkeys-1);
4519 MDB_GET_KEY(leaf, &nodekey);
4521 rc = mc->mc_dbx->md_cmp(key, &nodekey);
4523 /* last node was the one we wanted */
4524 mc->mc_ki[mc->mc_top] = nkeys-1;
4530 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
4531 /* This is definitely the right page, skip search_page */
4532 if (mp->mp_flags & P_LEAF2) {
4533 nodekey.mv_data = LEAF2KEY(mp,
4534 mc->mc_ki[mc->mc_top], nodekey.mv_size);
4536 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4537 MDB_GET_KEY(leaf, &nodekey);
4539 rc = mc->mc_dbx->md_cmp(key, &nodekey);
4541 /* current node was the one we wanted */
4551 /* If any parents have right-sibs, search.
4552 * Otherwise, there's nothing further.
4554 for (i=0; i<mc->mc_top; i++)
4556 NUMKEYS(mc->mc_pg[i])-1)
4558 if (i == mc->mc_top) {
4559 /* There are no other pages */
4560 mc->mc_ki[mc->mc_top] = nkeys;
4561 return MDB_NOTFOUND;
4565 /* There are no other pages */
4566 mc->mc_ki[mc->mc_top] = 0;
4567 return MDB_NOTFOUND;
4571 rc = mdb_page_search(mc, key, 0);
4572 if (rc != MDB_SUCCESS)
4575 mp = mc->mc_pg[mc->mc_top];
4576 assert(IS_LEAF(mp));
4579 leaf = mdb_node_search(mc, key, exactp);
4580 if (exactp != NULL && !*exactp) {
4581 /* MDB_SET specified and not an exact match. */
4582 return MDB_NOTFOUND;
4586 DPUTS("===> inexact leaf not found, goto sibling");
4587 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
4588 return rc; /* no entries matched */
4589 mp = mc->mc_pg[mc->mc_top];
4590 assert(IS_LEAF(mp));
4591 leaf = NODEPTR(mp, 0);
4595 mc->mc_flags |= C_INITIALIZED;
4596 mc->mc_flags &= ~C_EOF;
4599 key->mv_size = mc->mc_db->md_pad;
4600 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
4604 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4605 mdb_xcursor_init1(mc, leaf);
4608 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4609 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
4610 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4613 if (op == MDB_GET_BOTH) {
4619 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
4620 if (rc != MDB_SUCCESS)
4623 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
4625 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
4627 rc = mc->mc_dbx->md_dcmp(data, &d2);
4629 if (op == MDB_GET_BOTH || rc > 0)
4630 return MDB_NOTFOUND;
4635 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
4636 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4641 /* The key already matches in all other cases */
4642 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
4643 MDB_GET_KEY(leaf, key);
4644 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
4649 /** Move the cursor to the first item in the database. */
4651 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
4656 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
4657 rc = mdb_page_search(mc, NULL, 0);
4658 if (rc != MDB_SUCCESS)
4661 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
4663 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
4664 mc->mc_flags |= C_INITIALIZED;
4665 mc->mc_flags &= ~C_EOF;
4667 mc->mc_ki[mc->mc_top] = 0;
4669 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
4670 key->mv_size = mc->mc_db->md_pad;
4671 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
4676 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4677 mdb_xcursor_init1(mc, leaf);
4678 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4683 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
4684 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4688 MDB_GET_KEY(leaf, key);
4692 /** Move the cursor to the last item in the database. */
4694 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
4699 if (!(mc->mc_flags & C_EOF)) {
4701 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
4704 lkey.mv_size = MDB_MAXKEYSIZE+1;
4705 lkey.mv_data = NULL;
4706 rc = mdb_page_search(mc, &lkey, 0);
4707 if (rc != MDB_SUCCESS)
4710 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
4712 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
4714 mc->mc_flags |= C_INITIALIZED|C_EOF;
4715 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4717 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
4718 key->mv_size = mc->mc_db->md_pad;
4719 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
4724 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4725 mdb_xcursor_init1(mc, leaf);
4726 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
4731 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
4732 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4737 MDB_GET_KEY(leaf, key);
4742 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
4751 case MDB_GET_CURRENT:
4752 if (!(mc->mc_flags & C_INITIALIZED)) {
4755 MDB_page *mp = mc->mc_pg[mc->mc_top];
4757 mc->mc_ki[mc->mc_top] = 0;
4763 key->mv_size = mc->mc_db->md_pad;
4764 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
4766 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4767 MDB_GET_KEY(leaf, key);
4769 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4770 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
4772 rc = mdb_node_read(mc->mc_txn, leaf, data);
4779 case MDB_GET_BOTH_RANGE:
4780 if (data == NULL || mc->mc_xcursor == NULL) {
4788 if (key == NULL || key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
4790 } else if (op == MDB_SET_RANGE)
4791 rc = mdb_cursor_set(mc, key, data, op, NULL);
4793 rc = mdb_cursor_set(mc, key, data, op, &exact);
4795 case MDB_GET_MULTIPLE:
4797 !(mc->mc_db->md_flags & MDB_DUPFIXED) ||
4798 !(mc->mc_flags & C_INITIALIZED)) {
4803 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
4804 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
4807 case MDB_NEXT_MULTIPLE:
4809 !(mc->mc_db->md_flags & MDB_DUPFIXED)) {
4813 if (!(mc->mc_flags & C_INITIALIZED))
4814 rc = mdb_cursor_first(mc, key, data);
4816 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
4817 if (rc == MDB_SUCCESS) {
4818 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
4821 mx = &mc->mc_xcursor->mx_cursor;
4822 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
4824 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
4825 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
4833 case MDB_NEXT_NODUP:
4834 if (!(mc->mc_flags & C_INITIALIZED))
4835 rc = mdb_cursor_first(mc, key, data);
4837 rc = mdb_cursor_next(mc, key, data, op);
4841 case MDB_PREV_NODUP:
4842 if (!(mc->mc_flags & C_INITIALIZED)) {
4843 rc = mdb_cursor_last(mc, key, data);
4844 mc->mc_flags |= C_INITIALIZED;
4845 mc->mc_ki[mc->mc_top]++;
4847 rc = mdb_cursor_prev(mc, key, data, op);
4850 rc = mdb_cursor_first(mc, key, data);
4854 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
4855 !(mc->mc_flags & C_INITIALIZED) ||
4856 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
4860 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4863 rc = mdb_cursor_last(mc, key, data);
4867 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
4868 !(mc->mc_flags & C_INITIALIZED) ||
4869 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
4873 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
4876 DPRINTF("unhandled/unimplemented cursor operation %u", op);
4884 /** Touch all the pages in the cursor stack.
4885 * Makes sure all the pages are writable, before attempting a write operation.
4886 * @param[in] mc The cursor to operate on.
4889 mdb_cursor_touch(MDB_cursor *mc)
4893 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
4896 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI,
4897 mc->mc_txn->mt_dbs[MAIN_DBI].md_flags & MDB_DUPSORT ? &mcx : NULL);
4898 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
4901 *mc->mc_dbflag |= DB_DIRTY;
4903 for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
4904 rc = mdb_page_touch(mc);
4908 mc->mc_top = mc->mc_snum-1;
4913 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
4916 MDB_node *leaf = NULL;
4917 MDB_val xdata, *rdata, dkey;
4920 int do_sub = 0, insert = 0;
4921 unsigned int mcount = 0;
4925 char dbuf[MDB_MAXKEYSIZE+1];
4926 unsigned int nflags;
4929 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
4932 if (flags != MDB_CURRENT && (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE))
4935 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT) && data->mv_size > MDB_MAXKEYSIZE)
4938 #if SIZE_MAX > MAXDATASIZE
4939 if (data->mv_size > MAXDATASIZE)
4943 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
4944 mc->mc_dbi, DKEY(key), key ? key->mv_size:0, data->mv_size);
4948 if (flags == MDB_CURRENT) {
4949 if (!(mc->mc_flags & C_INITIALIZED))
4952 } else if (mc->mc_db->md_root == P_INVALID) {
4954 /* new database, write a root leaf page */
4955 DPUTS("allocating new root leaf page");
4956 if ((rc = mdb_page_new(mc, P_LEAF, 1, &np))) {
4960 mdb_cursor_push(mc, np);
4961 mc->mc_db->md_root = np->mp_pgno;
4962 mc->mc_db->md_depth++;
4963 *mc->mc_dbflag |= DB_DIRTY;
4964 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
4966 np->mp_flags |= P_LEAF2;
4967 mc->mc_flags |= C_INITIALIZED;
4973 if (flags & MDB_APPEND) {
4975 rc = mdb_cursor_last(mc, &k2, &d2);
4977 rc = mc->mc_dbx->md_cmp(key, &k2);
4980 mc->mc_ki[mc->mc_top]++;
4982 /* new key is <= last key */
4987 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
4989 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
4990 DPRINTF("duplicate key [%s]", DKEY(key));
4992 return MDB_KEYEXIST;
4994 if (rc && rc != MDB_NOTFOUND)
4998 /* Cursor is positioned, now make sure all pages are writable */
4999 rc2 = mdb_cursor_touch(mc);
5004 /* The key already exists */
5005 if (rc == MDB_SUCCESS) {
5006 /* there's only a key anyway, so this is a no-op */
5007 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5008 unsigned int ksize = mc->mc_db->md_pad;
5009 if (key->mv_size != ksize)
5011 if (flags == MDB_CURRENT) {
5012 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
5013 memcpy(ptr, key->mv_data, ksize);
5018 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5021 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
5022 /* Was a single item before, must convert now */
5024 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5025 /* Just overwrite the current item */
5026 if (flags == MDB_CURRENT)
5029 dkey.mv_size = NODEDSZ(leaf);
5030 dkey.mv_data = NODEDATA(leaf);
5031 #if UINT_MAX < SIZE_MAX
5032 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && dkey.mv_size == sizeof(size_t))
5033 #ifdef MISALIGNED_OK
5034 mc->mc_dbx->md_dcmp = mdb_cmp_long;
5036 mc->mc_dbx->md_dcmp = mdb_cmp_cint;
5039 /* if data matches, ignore it */
5040 if (!mc->mc_dbx->md_dcmp(data, &dkey))
5041 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
5043 /* create a fake page for the dup items */
5044 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
5045 dkey.mv_data = dbuf;
5046 fp = (MDB_page *)&pbuf;
5047 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
5048 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
5049 fp->mp_lower = PAGEHDRSZ;
5050 fp->mp_upper = PAGEHDRSZ + dkey.mv_size + data->mv_size;
5051 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5052 fp->mp_flags |= P_LEAF2;
5053 fp->mp_pad = data->mv_size;
5054 fp->mp_upper += 2 * data->mv_size; /* leave space for 2 more */
5056 fp->mp_upper += 2 * sizeof(indx_t) + 2 * NODESIZE +
5057 (dkey.mv_size & 1) + (data->mv_size & 1);
5059 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5062 xdata.mv_size = fp->mp_upper;
5067 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
5068 /* See if we need to convert from fake page to subDB */
5070 unsigned int offset;
5073 fp = NODEDATA(leaf);
5074 if (flags == MDB_CURRENT) {
5076 fp->mp_flags |= P_DIRTY;
5077 COPY_PGNO(fp->mp_pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
5078 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
5082 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5083 offset = fp->mp_pad;
5084 if (SIZELEFT(fp) >= offset)
5086 offset *= 4; /* space for 4 more */
5088 offset = NODESIZE + sizeof(indx_t) + data->mv_size;
5090 offset += offset & 1;
5091 if (NODESIZE + sizeof(indx_t) + NODEKSZ(leaf) + NODEDSZ(leaf) +
5092 offset >= mc->mc_txn->mt_env->me_nodemax) {
5093 /* yes, convert it */
5095 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5096 dummy.md_pad = fp->mp_pad;
5097 dummy.md_flags = MDB_DUPFIXED;
5098 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
5099 dummy.md_flags |= MDB_INTEGERKEY;
5102 dummy.md_branch_pages = 0;
5103 dummy.md_leaf_pages = 1;
5104 dummy.md_overflow_pages = 0;
5105 dummy.md_entries = NUMKEYS(fp);
5107 xdata.mv_size = sizeof(MDB_db);
5108 xdata.mv_data = &dummy;
5109 if ((rc = mdb_page_alloc(mc, 1, &mp)))
5111 offset = mc->mc_txn->mt_env->me_psize - NODEDSZ(leaf);
5112 flags |= F_DUPDATA|F_SUBDATA;
5113 dummy.md_root = mp->mp_pgno;
5115 /* no, just grow it */
5117 xdata.mv_size = NODEDSZ(leaf) + offset;
5118 xdata.mv_data = &pbuf;
5119 mp = (MDB_page *)&pbuf;
5120 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
5123 mp->mp_flags = fp->mp_flags | P_DIRTY;
5124 mp->mp_pad = fp->mp_pad;
5125 mp->mp_lower = fp->mp_lower;
5126 mp->mp_upper = fp->mp_upper + offset;
5128 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
5130 nsize = NODEDSZ(leaf) - fp->mp_upper;
5131 memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper, nsize);
5132 for (i=0; i<NUMKEYS(fp); i++)
5133 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
5135 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5139 /* data is on sub-DB, just store it */
5140 flags |= F_DUPDATA|F_SUBDATA;
5144 /* overflow page overwrites need special handling */
5145 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5148 int ovpages, dpages;
5150 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
5151 dpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
5152 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
5153 mdb_page_get(mc->mc_txn, pg, &omp);
5154 /* Is the ov page writable and large enough? */
5155 if ((omp->mp_flags & P_DIRTY) && ovpages >= dpages) {
5156 /* yes, overwrite it. Note in this case we don't
5157 * bother to try shrinking the node if the new data
5158 * is smaller than the overflow threshold.
5160 if (F_ISSET(flags, MDB_RESERVE))
5161 data->mv_data = METADATA(omp);
5163 memcpy(METADATA(omp), data->mv_data, data->mv_size);
5166 /* no, free ovpages */
5168 mc->mc_db->md_overflow_pages -= ovpages;
5169 for (i=0; i<ovpages; i++) {
5170 DPRINTF("freed ov page %zu", pg);
5171 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
5175 } else if (NODEDSZ(leaf) == data->mv_size) {
5176 /* same size, just replace it. Note that we could
5177 * also reuse this node if the new data is smaller,
5178 * but instead we opt to shrink the node in that case.
5180 if (F_ISSET(flags, MDB_RESERVE))
5181 data->mv_data = NODEDATA(leaf);
5182 else if (data->mv_size)
5183 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
5185 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
5188 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5189 mc->mc_db->md_entries--;
5191 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
5198 nflags = flags & NODE_ADD_FLAGS;
5199 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
5200 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
5201 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
5202 nflags &= ~MDB_APPEND;
5204 nflags |= MDB_SPLIT_REPLACE;
5205 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
5207 /* There is room already in this leaf page. */
5208 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
5209 if (rc == 0 && !do_sub && insert) {
5210 /* Adjust other cursors pointing to mp */
5211 MDB_cursor *m2, *m3;
5212 MDB_dbi dbi = mc->mc_dbi;
5213 unsigned i = mc->mc_top;
5214 MDB_page *mp = mc->mc_pg[i];
5216 if (mc->mc_flags & C_SUB)
5219 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5220 if (mc->mc_flags & C_SUB)
5221 m3 = &m2->mc_xcursor->mx_cursor;
5224 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
5225 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
5232 if (rc != MDB_SUCCESS)
5233 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5235 /* Now store the actual data in the child DB. Note that we're
5236 * storing the user data in the keys field, so there are strict
5237 * size limits on dupdata. The actual data fields of the child
5238 * DB are all zero size.
5245 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5246 if (flags & MDB_CURRENT) {
5247 xflags = MDB_CURRENT;
5249 mdb_xcursor_init1(mc, leaf);
5250 xflags = (flags & MDB_NODUPDATA) ? MDB_NOOVERWRITE : 0;
5252 /* converted, write the original data first */
5254 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
5258 /* Adjust other cursors pointing to mp */
5260 unsigned i = mc->mc_top;
5261 MDB_page *mp = mc->mc_pg[i];
5263 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5264 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
5265 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
5266 mdb_xcursor_init1(m2, leaf);
5270 /* we've done our job */
5273 if (flags & MDB_APPENDDUP)
5274 xflags |= MDB_APPEND;
5275 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
5276 if (flags & F_SUBDATA) {
5277 void *db = NODEDATA(leaf);
5278 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
5281 /* sub-writes might have failed so check rc again.
5282 * Don't increment count if we just replaced an existing item.
5284 if (!rc && !(flags & MDB_CURRENT))
5285 mc->mc_db->md_entries++;
5286 if (flags & MDB_MULTIPLE) {
5288 if (mcount < data[1].mv_size) {
5289 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
5290 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5296 /* If we succeeded and the key didn't exist before, make sure
5297 * the cursor is marked valid.
5300 mc->mc_flags |= C_INITIALIZED;
5305 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
5310 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
5313 if (!(mc->mc_flags & C_INITIALIZED))
5316 rc = mdb_cursor_touch(mc);
5320 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5322 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5323 if (flags != MDB_NODUPDATA) {
5324 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
5325 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
5327 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
5328 /* If sub-DB still has entries, we're done */
5329 if (mc->mc_xcursor->mx_db.md_entries) {
5330 if (leaf->mn_flags & F_SUBDATA) {
5331 /* update subDB info */
5332 void *db = NODEDATA(leaf);
5333 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
5335 /* shrink fake page */
5336 mdb_node_shrink(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5338 mc->mc_db->md_entries--;
5341 /* otherwise fall thru and delete the sub-DB */
5344 if (leaf->mn_flags & F_SUBDATA) {
5345 /* add all the child DB's pages to the free list */
5346 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
5347 if (rc == MDB_SUCCESS) {
5348 mc->mc_db->md_entries -=
5349 mc->mc_xcursor->mx_db.md_entries;
5354 return mdb_cursor_del0(mc, leaf);
5357 /** Allocate and initialize new pages for a database.
5358 * @param[in] mc a cursor on the database being added to.
5359 * @param[in] flags flags defining what type of page is being allocated.
5360 * @param[in] num the number of pages to allocate. This is usually 1,
5361 * unless allocating overflow pages for a large record.
5362 * @param[out] mp Address of a page, or NULL on failure.
5363 * @return 0 on success, non-zero on failure.
5366 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
5371 if ((rc = mdb_page_alloc(mc, num, &np)))
5373 DPRINTF("allocated new mpage %zu, page size %u",
5374 np->mp_pgno, mc->mc_txn->mt_env->me_psize);
5375 np->mp_flags = flags | P_DIRTY;
5376 np->mp_lower = PAGEHDRSZ;
5377 np->mp_upper = mc->mc_txn->mt_env->me_psize;
5380 mc->mc_db->md_branch_pages++;
5381 else if (IS_LEAF(np))
5382 mc->mc_db->md_leaf_pages++;
5383 else if (IS_OVERFLOW(np)) {
5384 mc->mc_db->md_overflow_pages += num;
5392 /** Calculate the size of a leaf node.
5393 * The size depends on the environment's page size; if a data item
5394 * is too large it will be put onto an overflow page and the node
5395 * size will only include the key and not the data. Sizes are always
5396 * rounded up to an even number of bytes, to guarantee 2-byte alignment
5397 * of the #MDB_node headers.
5398 * @param[in] env The environment handle.
5399 * @param[in] key The key for the node.
5400 * @param[in] data The data for the node.
5401 * @return The number of bytes needed to store the node.
5404 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
5408 sz = LEAFSIZE(key, data);
5409 if (sz >= env->me_nodemax) {
5410 /* put on overflow page */
5411 sz -= data->mv_size - sizeof(pgno_t);
5415 return sz + sizeof(indx_t);
5418 /** Calculate the size of a branch node.
5419 * The size should depend on the environment's page size but since
5420 * we currently don't support spilling large keys onto overflow
5421 * pages, it's simply the size of the #MDB_node header plus the
5422 * size of the key. Sizes are always rounded up to an even number
5423 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
5424 * @param[in] env The environment handle.
5425 * @param[in] key The key for the node.
5426 * @return The number of bytes needed to store the node.
5429 mdb_branch_size(MDB_env *env, MDB_val *key)
5434 if (sz >= env->me_nodemax) {
5435 /* put on overflow page */
5436 /* not implemented */
5437 /* sz -= key->size - sizeof(pgno_t); */
5440 return sz + sizeof(indx_t);
5443 /** Add a node to the page pointed to by the cursor.
5444 * @param[in] mc The cursor for this operation.
5445 * @param[in] indx The index on the page where the new node should be added.
5446 * @param[in] key The key for the new node.
5447 * @param[in] data The data for the new node, if any.
5448 * @param[in] pgno The page number, if adding a branch node.
5449 * @param[in] flags Flags for the node.
5450 * @return 0 on success, non-zero on failure. Possible errors are:
5452 * <li>ENOMEM - failed to allocate overflow pages for the node.
5453 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
5454 * should never happen since all callers already calculate the
5455 * page's free space before calling this function.
5459 mdb_node_add(MDB_cursor *mc, indx_t indx,
5460 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
5463 size_t node_size = NODESIZE;
5466 MDB_page *mp = mc->mc_pg[mc->mc_top];
5467 MDB_page *ofp = NULL; /* overflow page */
5470 assert(mp->mp_upper >= mp->mp_lower);
5472 DPRINTF("add to %s %spage %zu index %i, data size %zu key size %zu [%s]",
5473 IS_LEAF(mp) ? "leaf" : "branch",
5474 IS_SUBP(mp) ? "sub-" : "",
5475 mp->mp_pgno, indx, data ? data->mv_size : 0,
5476 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
5479 /* Move higher keys up one slot. */
5480 int ksize = mc->mc_db->md_pad, dif;
5481 char *ptr = LEAF2KEY(mp, indx, ksize);
5482 dif = NUMKEYS(mp) - indx;
5484 memmove(ptr+ksize, ptr, dif*ksize);
5485 /* insert new key */
5486 memcpy(ptr, key->mv_data, ksize);
5488 /* Just using these for counting */
5489 mp->mp_lower += sizeof(indx_t);
5490 mp->mp_upper -= ksize - sizeof(indx_t);
5495 node_size += key->mv_size;
5499 if (F_ISSET(flags, F_BIGDATA)) {
5500 /* Data already on overflow page. */
5501 node_size += sizeof(pgno_t);
5502 } else if (node_size + data->mv_size >= mc->mc_txn->mt_env->me_nodemax) {
5503 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
5505 /* Put data on overflow page. */
5506 DPRINTF("data size is %zu, node would be %zu, put data on overflow page",
5507 data->mv_size, node_size+data->mv_size);
5508 node_size += sizeof(pgno_t);
5509 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
5511 DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
5514 node_size += data->mv_size;
5517 node_size += node_size & 1;
5519 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
5520 DPRINTF("not enough room in page %zu, got %u ptrs",
5521 mp->mp_pgno, NUMKEYS(mp));
5522 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
5523 mp->mp_upper - mp->mp_lower);
5524 DPRINTF("node size = %zu", node_size);
5525 return MDB_PAGE_FULL;
5528 /* Move higher pointers up one slot. */
5529 for (i = NUMKEYS(mp); i > indx; i--)
5530 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
5532 /* Adjust free space offsets. */
5533 ofs = mp->mp_upper - node_size;
5534 assert(ofs >= mp->mp_lower + sizeof(indx_t));
5535 mp->mp_ptrs[indx] = ofs;
5537 mp->mp_lower += sizeof(indx_t);
5539 /* Write the node data. */
5540 node = NODEPTR(mp, indx);
5541 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
5542 node->mn_flags = flags;
5544 SETDSZ(node,data->mv_size);
5549 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
5554 if (F_ISSET(flags, F_BIGDATA))
5555 memcpy(node->mn_data + key->mv_size, data->mv_data,
5557 else if (F_ISSET(flags, MDB_RESERVE))
5558 data->mv_data = node->mn_data + key->mv_size;
5560 memcpy(node->mn_data + key->mv_size, data->mv_data,
5563 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
5565 if (F_ISSET(flags, MDB_RESERVE))
5566 data->mv_data = METADATA(ofp);
5568 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
5575 /** Delete the specified node from a page.
5576 * @param[in] mp The page to operate on.
5577 * @param[in] indx The index of the node to delete.
5578 * @param[in] ksize The size of a node. Only used if the page is
5579 * part of a #MDB_DUPFIXED database.
5582 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
5585 indx_t i, j, numkeys, ptr;
5592 COPY_PGNO(pgno, mp->mp_pgno);
5593 DPRINTF("delete node %u on %s page %zu", indx,
5594 IS_LEAF(mp) ? "leaf" : "branch", pgno);
5597 assert(indx < NUMKEYS(mp));
5600 int x = NUMKEYS(mp) - 1 - indx;
5601 base = LEAF2KEY(mp, indx, ksize);
5603 memmove(base, base + ksize, x * ksize);
5604 mp->mp_lower -= sizeof(indx_t);
5605 mp->mp_upper += ksize - sizeof(indx_t);
5609 node = NODEPTR(mp, indx);
5610 sz = NODESIZE + node->mn_ksize;
5612 if (F_ISSET(node->mn_flags, F_BIGDATA))
5613 sz += sizeof(pgno_t);
5615 sz += NODEDSZ(node);
5619 ptr = mp->mp_ptrs[indx];
5620 numkeys = NUMKEYS(mp);
5621 for (i = j = 0; i < numkeys; i++) {
5623 mp->mp_ptrs[j] = mp->mp_ptrs[i];
5624 if (mp->mp_ptrs[i] < ptr)
5625 mp->mp_ptrs[j] += sz;
5630 base = (char *)mp + mp->mp_upper;
5631 memmove(base + sz, base, ptr - mp->mp_upper);
5633 mp->mp_lower -= sizeof(indx_t);
5637 /** Compact the main page after deleting a node on a subpage.
5638 * @param[in] mp The main page to operate on.
5639 * @param[in] indx The index of the subpage on the main page.
5642 mdb_node_shrink(MDB_page *mp, indx_t indx)
5649 indx_t i, numkeys, ptr;
5651 node = NODEPTR(mp, indx);
5652 sp = (MDB_page *)NODEDATA(node);
5653 osize = NODEDSZ(node);
5655 delta = sp->mp_upper - sp->mp_lower;
5656 SETDSZ(node, osize - delta);
5657 xp = (MDB_page *)((char *)sp + delta);
5659 /* shift subpage upward */
5661 nsize = NUMKEYS(sp) * sp->mp_pad;
5662 memmove(METADATA(xp), METADATA(sp), nsize);
5665 nsize = osize - sp->mp_upper;
5666 numkeys = NUMKEYS(sp);
5667 for (i=numkeys-1; i>=0; i--)
5668 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
5670 xp->mp_upper = sp->mp_lower;
5671 xp->mp_lower = sp->mp_lower;
5672 xp->mp_flags = sp->mp_flags;
5673 xp->mp_pad = sp->mp_pad;
5674 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
5676 /* shift lower nodes upward */
5677 ptr = mp->mp_ptrs[indx];
5678 numkeys = NUMKEYS(mp);
5679 for (i = 0; i < numkeys; i++) {
5680 if (mp->mp_ptrs[i] <= ptr)
5681 mp->mp_ptrs[i] += delta;
5684 base = (char *)mp + mp->mp_upper;
5685 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
5686 mp->mp_upper += delta;
5689 /** Initial setup of a sorted-dups cursor.
5690 * Sorted duplicates are implemented as a sub-database for the given key.
5691 * The duplicate data items are actually keys of the sub-database.
5692 * Operations on the duplicate data items are performed using a sub-cursor
5693 * initialized when the sub-database is first accessed. This function does
5694 * the preliminary setup of the sub-cursor, filling in the fields that
5695 * depend only on the parent DB.
5696 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
5699 mdb_xcursor_init0(MDB_cursor *mc)
5701 MDB_xcursor *mx = mc->mc_xcursor;
5703 mx->mx_cursor.mc_xcursor = NULL;
5704 mx->mx_cursor.mc_txn = mc->mc_txn;
5705 mx->mx_cursor.mc_db = &mx->mx_db;
5706 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
5707 mx->mx_cursor.mc_dbi = mc->mc_dbi+1;
5708 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
5709 mx->mx_cursor.mc_snum = 0;
5710 mx->mx_cursor.mc_top = 0;
5711 mx->mx_cursor.mc_flags = C_SUB;
5712 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
5713 mx->mx_dbx.md_dcmp = NULL;
5714 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
5717 /** Final setup of a sorted-dups cursor.
5718 * Sets up the fields that depend on the data from the main cursor.
5719 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
5720 * @param[in] node The data containing the #MDB_db record for the
5721 * sorted-dup database.
5724 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
5726 MDB_xcursor *mx = mc->mc_xcursor;
5728 if (node->mn_flags & F_SUBDATA) {
5729 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
5730 mx->mx_cursor.mc_pg[0] = 0;
5731 mx->mx_cursor.mc_snum = 0;
5732 mx->mx_cursor.mc_flags = C_SUB;
5734 MDB_page *fp = NODEDATA(node);
5735 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
5736 mx->mx_db.md_flags = 0;
5737 mx->mx_db.md_depth = 1;
5738 mx->mx_db.md_branch_pages = 0;
5739 mx->mx_db.md_leaf_pages = 1;
5740 mx->mx_db.md_overflow_pages = 0;
5741 mx->mx_db.md_entries = NUMKEYS(fp);
5742 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
5743 mx->mx_cursor.mc_snum = 1;
5744 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
5745 mx->mx_cursor.mc_top = 0;
5746 mx->mx_cursor.mc_pg[0] = fp;
5747 mx->mx_cursor.mc_ki[0] = 0;
5748 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5749 mx->mx_db.md_flags = MDB_DUPFIXED;
5750 mx->mx_db.md_pad = fp->mp_pad;
5751 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
5752 mx->mx_db.md_flags |= MDB_INTEGERKEY;
5755 DPRINTF("Sub-db %u for db %u root page %zu", mx->mx_cursor.mc_dbi, mc->mc_dbi,
5757 mx->mx_dbflag = DB_VALID | (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY) ?
5759 mx->mx_dbx.md_name.mv_data = NODEKEY(node);
5760 mx->mx_dbx.md_name.mv_size = node->mn_ksize;
5761 #if UINT_MAX < SIZE_MAX
5762 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
5763 #ifdef MISALIGNED_OK
5764 mx->mx_dbx.md_cmp = mdb_cmp_long;
5766 mx->mx_dbx.md_cmp = mdb_cmp_cint;
5771 /** Initialize a cursor for a given transaction and database. */
5773 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
5778 mc->mc_db = &txn->mt_dbs[dbi];
5779 mc->mc_dbx = &txn->mt_dbxs[dbi];
5780 mc->mc_dbflag = &txn->mt_dbflags[dbi];
5785 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
5787 mc->mc_xcursor = mx;
5788 mdb_xcursor_init0(mc);
5790 mc->mc_xcursor = NULL;
5792 if (*mc->mc_dbflag & DB_STALE) {
5793 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
5798 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
5801 MDB_xcursor *mx = NULL;
5802 size_t size = sizeof(MDB_cursor);
5804 if (txn == NULL || ret == NULL || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
5807 /* Allow read access to the freelist */
5808 if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
5811 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
5812 size += sizeof(MDB_xcursor);
5814 if ((mc = malloc(size)) != NULL) {
5815 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
5816 mx = (MDB_xcursor *)(mc + 1);
5818 mdb_cursor_init(mc, txn, dbi, mx);
5819 if (txn->mt_cursors) {
5820 mc->mc_next = txn->mt_cursors[dbi];
5821 txn->mt_cursors[dbi] = mc;
5823 mc->mc_flags |= C_ALLOCD;
5834 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
5836 if (txn == NULL || mc == NULL || mc->mc_dbi >= txn->mt_numdbs)
5839 if (txn->mt_cursors)
5842 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
5846 /* Return the count of duplicate data items for the current key */
5848 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
5852 if (mc == NULL || countp == NULL)
5855 if (!(mc->mc_db->md_flags & MDB_DUPSORT))
5858 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5859 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5862 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
5865 *countp = mc->mc_xcursor->mx_db.md_entries;
5871 mdb_cursor_close(MDB_cursor *mc)
5874 /* remove from txn, if tracked */
5875 if (mc->mc_txn->mt_cursors) {
5876 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
5877 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
5879 *prev = mc->mc_next;
5881 if (mc->mc_flags & C_ALLOCD)
5887 mdb_cursor_txn(MDB_cursor *mc)
5889 if (!mc) return NULL;
5894 mdb_cursor_dbi(MDB_cursor *mc)
5900 /** Replace the key for a node with a new key.
5901 * @param[in] mp The page containing the node to operate on.
5902 * @param[in] indx The index of the node to operate on.
5903 * @param[in] key The new key to use.
5904 * @return 0 on success, non-zero on failure.
5907 mdb_update_key(MDB_cursor *mc, MDB_val *key)
5914 indx_t ptr, i, numkeys, indx;
5917 indx = mc->mc_ki[mc->mc_top];
5918 mp = mc->mc_pg[mc->mc_top];
5919 node = NODEPTR(mp, indx);
5920 ptr = mp->mp_ptrs[indx];
5924 char kbuf2[(MDB_MAXKEYSIZE*2+1)];
5925 k2.mv_data = NODEKEY(node);
5926 k2.mv_size = node->mn_ksize;
5927 DPRINTF("update key %u (ofs %u) [%s] to [%s] on page %zu",
5929 mdb_dkey(&k2, kbuf2),
5935 delta0 = delta = key->mv_size - node->mn_ksize;
5937 /* Must be 2-byte aligned. If new key is
5938 * shorter by 1, the shift will be skipped.
5940 delta += (delta & 1);
5942 if (delta > 0 && SIZELEFT(mp) < delta) {
5944 /* not enough space left, do a delete and split */
5945 DPRINTF("Not enough room, delta = %d, splitting...", delta);
5946 pgno = NODEPGNO(node);
5947 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5948 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
5951 numkeys = NUMKEYS(mp);
5952 for (i = 0; i < numkeys; i++) {
5953 if (mp->mp_ptrs[i] <= ptr)
5954 mp->mp_ptrs[i] -= delta;
5957 base = (char *)mp + mp->mp_upper;
5958 len = ptr - mp->mp_upper + NODESIZE;
5959 memmove(base - delta, base, len);
5960 mp->mp_upper -= delta;
5962 node = NODEPTR(mp, indx);
5965 /* But even if no shift was needed, update ksize */
5967 node->mn_ksize = key->mv_size;
5970 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
5976 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
5978 /** Move a node from csrc to cdst.
5981 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
5988 unsigned short flags;
5992 /* Mark src and dst as dirty. */
5993 if ((rc = mdb_page_touch(csrc)) ||
5994 (rc = mdb_page_touch(cdst)))
5997 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5998 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
5999 key.mv_size = csrc->mc_db->md_pad;
6000 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
6002 data.mv_data = NULL;
6006 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
6007 assert(!((long)srcnode&1));
6008 srcpg = NODEPGNO(srcnode);
6009 flags = srcnode->mn_flags;
6010 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6011 unsigned int snum = csrc->mc_snum;
6013 /* must find the lowest key below src */
6014 mdb_page_search_root(csrc, NULL, 0);
6015 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6016 key.mv_size = csrc->mc_db->md_pad;
6017 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6019 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6020 key.mv_size = NODEKSZ(s2);
6021 key.mv_data = NODEKEY(s2);
6023 csrc->mc_snum = snum--;
6024 csrc->mc_top = snum;
6026 key.mv_size = NODEKSZ(srcnode);
6027 key.mv_data = NODEKEY(srcnode);
6029 data.mv_size = NODEDSZ(srcnode);
6030 data.mv_data = NODEDATA(srcnode);
6032 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
6033 unsigned int snum = cdst->mc_snum;
6036 /* must find the lowest key below dst */
6037 mdb_page_search_root(cdst, NULL, 0);
6038 if (IS_LEAF2(cdst->mc_pg[cdst->mc_top])) {
6039 bkey.mv_size = cdst->mc_db->md_pad;
6040 bkey.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, bkey.mv_size);
6042 s2 = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
6043 bkey.mv_size = NODEKSZ(s2);
6044 bkey.mv_data = NODEKEY(s2);
6046 cdst->mc_snum = snum--;
6047 cdst->mc_top = snum;
6048 mdb_cursor_copy(cdst, &mn);
6050 rc = mdb_update_key(&mn, &bkey);
6055 DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
6056 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
6057 csrc->mc_ki[csrc->mc_top],
6059 csrc->mc_pg[csrc->mc_top]->mp_pgno,
6060 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
6062 /* Add the node to the destination page.
6064 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
6065 if (rc != MDB_SUCCESS)
6068 /* Delete the node from the source page.
6070 mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
6073 /* Adjust other cursors pointing to mp */
6074 MDB_cursor *m2, *m3;
6075 MDB_dbi dbi = csrc->mc_dbi;
6076 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
6078 if (csrc->mc_flags & C_SUB)
6081 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6082 if (m2 == csrc) continue;
6083 if (csrc->mc_flags & C_SUB)
6084 m3 = &m2->mc_xcursor->mx_cursor;
6087 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
6088 csrc->mc_ki[csrc->mc_top]) {
6089 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
6090 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
6095 /* Update the parent separators.
6097 if (csrc->mc_ki[csrc->mc_top] == 0) {
6098 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
6099 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6100 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6102 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6103 key.mv_size = NODEKSZ(srcnode);
6104 key.mv_data = NODEKEY(srcnode);
6106 DPRINTF("update separator for source page %zu to [%s]",
6107 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
6108 mdb_cursor_copy(csrc, &mn);
6111 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
6114 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6116 indx_t ix = csrc->mc_ki[csrc->mc_top];
6117 nullkey.mv_size = 0;
6118 csrc->mc_ki[csrc->mc_top] = 0;
6119 rc = mdb_update_key(csrc, &nullkey);
6120 csrc->mc_ki[csrc->mc_top] = ix;
6121 assert(rc == MDB_SUCCESS);
6125 if (cdst->mc_ki[cdst->mc_top] == 0) {
6126 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
6127 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6128 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
6130 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
6131 key.mv_size = NODEKSZ(srcnode);
6132 key.mv_data = NODEKEY(srcnode);
6134 DPRINTF("update separator for destination page %zu to [%s]",
6135 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
6136 mdb_cursor_copy(cdst, &mn);
6139 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
6142 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
6144 indx_t ix = cdst->mc_ki[cdst->mc_top];
6145 nullkey.mv_size = 0;
6146 cdst->mc_ki[cdst->mc_top] = 0;
6147 rc = mdb_update_key(cdst, &nullkey);
6148 cdst->mc_ki[cdst->mc_top] = ix;
6149 assert(rc == MDB_SUCCESS);
6156 /** Merge one page into another.
6157 * The nodes from the page pointed to by \b csrc will
6158 * be copied to the page pointed to by \b cdst and then
6159 * the \b csrc page will be freed.
6160 * @param[in] csrc Cursor pointing to the source page.
6161 * @param[in] cdst Cursor pointing to the destination page.
6164 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
6172 DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
6173 cdst->mc_pg[cdst->mc_top]->mp_pgno);
6175 assert(csrc->mc_snum > 1); /* can't merge root page */
6176 assert(cdst->mc_snum > 1);
6178 /* Mark dst as dirty. */
6179 if ((rc = mdb_page_touch(cdst)))
6182 /* Move all nodes from src to dst.
6184 j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
6185 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6186 key.mv_size = csrc->mc_db->md_pad;
6187 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
6188 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
6189 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
6190 if (rc != MDB_SUCCESS)
6192 key.mv_data = (char *)key.mv_data + key.mv_size;
6195 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
6196 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
6197 if (i == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6198 unsigned int snum = csrc->mc_snum;
6200 /* must find the lowest key below src */
6201 mdb_page_search_root(csrc, NULL, 0);
6202 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6203 key.mv_size = csrc->mc_db->md_pad;
6204 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6206 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6207 key.mv_size = NODEKSZ(s2);
6208 key.mv_data = NODEKEY(s2);
6210 csrc->mc_snum = snum--;
6211 csrc->mc_top = snum;
6213 key.mv_size = srcnode->mn_ksize;
6214 key.mv_data = NODEKEY(srcnode);
6217 data.mv_size = NODEDSZ(srcnode);
6218 data.mv_data = NODEDATA(srcnode);
6219 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
6220 if (rc != MDB_SUCCESS)
6225 DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
6226 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);
6228 /* Unlink the src page from parent and add to free list.
6230 mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
6231 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
6234 rc = mdb_update_key(csrc, &key);
6240 mdb_midl_append(&csrc->mc_txn->mt_free_pgs, csrc->mc_pg[csrc->mc_top]->mp_pgno);
6241 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
6242 csrc->mc_db->md_leaf_pages--;
6244 csrc->mc_db->md_branch_pages--;
6246 /* Adjust other cursors pointing to mp */
6247 MDB_cursor *m2, *m3;
6248 MDB_dbi dbi = csrc->mc_dbi;
6249 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
6251 if (csrc->mc_flags & C_SUB)
6254 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6255 if (csrc->mc_flags & C_SUB)
6256 m3 = &m2->mc_xcursor->mx_cursor;
6259 if (m3 == csrc) continue;
6260 if (m3->mc_snum < csrc->mc_snum) continue;
6261 if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
6262 m3->mc_pg[csrc->mc_top] = mp;
6263 m3->mc_ki[csrc->mc_top] += nkeys;
6267 mdb_cursor_pop(csrc);
6269 return mdb_rebalance(csrc);
6272 /** Copy the contents of a cursor.
6273 * @param[in] csrc The cursor to copy from.
6274 * @param[out] cdst The cursor to copy to.
6277 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
6281 cdst->mc_txn = csrc->mc_txn;
6282 cdst->mc_dbi = csrc->mc_dbi;
6283 cdst->mc_db = csrc->mc_db;
6284 cdst->mc_dbx = csrc->mc_dbx;
6285 cdst->mc_snum = csrc->mc_snum;
6286 cdst->mc_top = csrc->mc_top;
6287 cdst->mc_flags = csrc->mc_flags;
6289 for (i=0; i<csrc->mc_snum; i++) {
6290 cdst->mc_pg[i] = csrc->mc_pg[i];
6291 cdst->mc_ki[i] = csrc->mc_ki[i];
6295 /** Rebalance the tree after a delete operation.
6296 * @param[in] mc Cursor pointing to the page where rebalancing
6298 * @return 0 on success, non-zero on failure.
6301 mdb_rebalance(MDB_cursor *mc)
6305 unsigned int ptop, minkeys;
6308 minkeys = 1 + (IS_BRANCH(mc->mc_pg[mc->mc_top]));
6312 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
6313 DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
6314 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
6315 pgno, NUMKEYS(mc->mc_pg[mc->mc_top]), (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10);
6319 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD &&
6320 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
6323 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
6324 DPRINTF("no need to rebalance page %zu, above fill threshold",
6330 if (mc->mc_snum < 2) {
6331 MDB_page *mp = mc->mc_pg[0];
6333 DPUTS("Can't rebalance a subpage, ignoring");
6336 if (NUMKEYS(mp) == 0) {
6337 DPUTS("tree is completely empty");
6338 mc->mc_db->md_root = P_INVALID;
6339 mc->mc_db->md_depth = 0;
6340 mc->mc_db->md_leaf_pages = 0;
6341 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
6345 /* Adjust other cursors pointing to mp */
6346 MDB_cursor *m2, *m3;
6347 MDB_dbi dbi = mc->mc_dbi;
6349 if (mc->mc_flags & C_SUB)
6352 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6353 if (m2 == mc) continue;
6354 if (mc->mc_flags & C_SUB)
6355 m3 = &m2->mc_xcursor->mx_cursor;
6358 if (m3->mc_snum < mc->mc_snum) continue;
6359 if (m3->mc_pg[0] == mp) {
6365 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
6366 DPUTS("collapsing root page!");
6367 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
6368 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
6369 if ((rc = mdb_page_get(mc->mc_txn, mc->mc_db->md_root,
6372 mc->mc_db->md_depth--;
6373 mc->mc_db->md_branch_pages--;
6375 /* Adjust other cursors pointing to mp */
6376 MDB_cursor *m2, *m3;
6377 MDB_dbi dbi = mc->mc_dbi;
6379 if (mc->mc_flags & C_SUB)
6382 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6383 if (m2 == mc) continue;
6384 if (mc->mc_flags & C_SUB)
6385 m3 = &m2->mc_xcursor->mx_cursor;
6388 if (m3->mc_snum < mc->mc_snum) continue;
6389 if (m3->mc_pg[0] == mp) {
6390 m3->mc_pg[0] = mc->mc_pg[0];
6397 DPUTS("root page doesn't need rebalancing");
6401 /* The parent (branch page) must have at least 2 pointers,
6402 * otherwise the tree is invalid.
6404 ptop = mc->mc_top-1;
6405 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
6407 /* Leaf page fill factor is below the threshold.
6408 * Try to move keys from left or right neighbor, or
6409 * merge with a neighbor page.
6414 mdb_cursor_copy(mc, &mn);
6415 mn.mc_xcursor = NULL;
6417 if (mc->mc_ki[ptop] == 0) {
6418 /* We're the leftmost leaf in our parent.
6420 DPUTS("reading right neighbor");
6422 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
6423 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
6425 mn.mc_ki[mn.mc_top] = 0;
6426 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
6428 /* There is at least one neighbor to the left.
6430 DPUTS("reading left neighbor");
6432 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
6433 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
6435 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
6436 mc->mc_ki[mc->mc_top] = 0;
6439 DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
6440 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);
6442 /* If the neighbor page is above threshold and has enough keys,
6443 * move one key from it. Otherwise we should try to merge them.
6444 * (A branch page must never have less than 2 keys.)
6446 minkeys = 1 + (IS_BRANCH(mn.mc_pg[mn.mc_top]));
6447 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys)
6448 return mdb_node_move(&mn, mc);
6450 if (mc->mc_ki[ptop] == 0)
6451 rc = mdb_page_merge(&mn, mc);
6453 rc = mdb_page_merge(mc, &mn);
6454 mc->mc_flags &= ~C_INITIALIZED;
6459 /** Complete a delete operation started by #mdb_cursor_del(). */
6461 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
6465 /* add overflow pages to free list */
6466 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6470 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
6471 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
6472 mc->mc_db->md_overflow_pages -= ovpages;
6473 for (i=0; i<ovpages; i++) {
6474 DPRINTF("freed ov page %zu", pg);
6475 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
6479 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], mc->mc_db->md_pad);
6480 mc->mc_db->md_entries--;
6481 rc = mdb_rebalance(mc);
6482 if (rc != MDB_SUCCESS)
6483 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6484 /* if mc points past last node in page, invalidate */
6485 else if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6486 mc->mc_flags &= ~C_INITIALIZED;
6492 mdb_del(MDB_txn *txn, MDB_dbi dbi,
6493 MDB_val *key, MDB_val *data)
6498 MDB_val rdata, *xdata;
6502 assert(key != NULL);
6504 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
6506 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
6509 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
6513 if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
6517 mdb_cursor_init(&mc, txn, dbi, &mx);
6528 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
6530 /* let mdb_page_split know about this cursor if needed:
6531 * delete will trigger a rebalance; if it needs to move
6532 * a node from one page to another, it will have to
6533 * update the parent's separator key(s). If the new sepkey
6534 * is larger than the current one, the parent page may
6535 * run out of space, triggering a split. We need this
6536 * cursor to be consistent until the end of the rebalance.
6538 mc.mc_next = txn->mt_cursors[dbi];
6539 txn->mt_cursors[dbi] = &mc;
6540 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
6541 txn->mt_cursors[dbi] = mc.mc_next;
6546 /** Split a page and insert a new node.
6547 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
6548 * The cursor will be updated to point to the actual page and index where
6549 * the node got inserted after the split.
6550 * @param[in] newkey The key for the newly inserted node.
6551 * @param[in] newdata The data for the newly inserted node.
6552 * @param[in] newpgno The page number, if the new node is a branch node.
6553 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
6554 * @return 0 on success, non-zero on failure.
6557 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
6558 unsigned int nflags)
6561 int rc = MDB_SUCCESS, ins_new = 0, new_root = 0, newpos = 1, did_split = 0;
6564 unsigned int i, j, split_indx, nkeys, pmax;
6566 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
6568 MDB_page *mp, *rp, *pp;
6573 mp = mc->mc_pg[mc->mc_top];
6574 newindx = mc->mc_ki[mc->mc_top];
6576 DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
6577 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
6578 DKEY(newkey), mc->mc_ki[mc->mc_top]);
6580 /* Create a right sibling. */
6581 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
6583 DPRINTF("new right sibling: page %zu", rp->mp_pgno);
6585 if (mc->mc_snum < 2) {
6586 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
6588 /* shift current top to make room for new parent */
6589 mc->mc_pg[1] = mc->mc_pg[0];
6590 mc->mc_ki[1] = mc->mc_ki[0];
6593 mc->mc_db->md_root = pp->mp_pgno;
6594 DPRINTF("root split! new root = %zu", pp->mp_pgno);
6595 mc->mc_db->md_depth++;
6598 /* Add left (implicit) pointer. */
6599 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
6600 /* undo the pre-push */
6601 mc->mc_pg[0] = mc->mc_pg[1];
6602 mc->mc_ki[0] = mc->mc_ki[1];
6603 mc->mc_db->md_root = mp->mp_pgno;
6604 mc->mc_db->md_depth--;
6611 ptop = mc->mc_top-1;
6612 DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
6615 mc->mc_flags |= C_SPLITTING;
6616 mdb_cursor_copy(mc, &mn);
6617 mn.mc_pg[mn.mc_top] = rp;
6618 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
6620 if (nflags & MDB_APPEND) {
6621 mn.mc_ki[mn.mc_top] = 0;
6623 split_indx = newindx;
6628 nkeys = NUMKEYS(mp);
6629 split_indx = nkeys / 2;
6630 if (newindx < split_indx)
6636 unsigned int lsize, rsize, ksize;
6637 /* Move half of the keys to the right sibling */
6639 x = mc->mc_ki[mc->mc_top] - split_indx;
6640 ksize = mc->mc_db->md_pad;
6641 split = LEAF2KEY(mp, split_indx, ksize);
6642 rsize = (nkeys - split_indx) * ksize;
6643 lsize = (nkeys - split_indx) * sizeof(indx_t);
6644 mp->mp_lower -= lsize;
6645 rp->mp_lower += lsize;
6646 mp->mp_upper += rsize - lsize;
6647 rp->mp_upper -= rsize - lsize;
6648 sepkey.mv_size = ksize;
6649 if (newindx == split_indx) {
6650 sepkey.mv_data = newkey->mv_data;
6652 sepkey.mv_data = split;
6655 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
6656 memcpy(rp->mp_ptrs, split, rsize);
6657 sepkey.mv_data = rp->mp_ptrs;
6658 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
6659 memcpy(ins, newkey->mv_data, ksize);
6660 mp->mp_lower += sizeof(indx_t);
6661 mp->mp_upper -= ksize - sizeof(indx_t);
6664 memcpy(rp->mp_ptrs, split, x * ksize);
6665 ins = LEAF2KEY(rp, x, ksize);
6666 memcpy(ins, newkey->mv_data, ksize);
6667 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
6668 rp->mp_lower += sizeof(indx_t);
6669 rp->mp_upper -= ksize - sizeof(indx_t);
6670 mc->mc_ki[mc->mc_top] = x;
6671 mc->mc_pg[mc->mc_top] = rp;
6676 /* For leaf pages, check the split point based on what
6677 * fits where, since otherwise mdb_node_add can fail.
6679 * This check is only needed when the data items are
6680 * relatively large, such that being off by one will
6681 * make the difference between success or failure.
6683 * It's also relevant if a page happens to be laid out
6684 * such that one half of its nodes are all "small" and
6685 * the other half of its nodes are "large." If the new
6686 * item is also "large" and falls on the half with
6687 * "large" nodes, it also may not fit.
6690 unsigned int psize, nsize;
6691 /* Maximum free space in an empty page */
6692 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
6693 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
6694 if ((nkeys < 20) || (nsize > pmax/16)) {
6695 if (newindx <= split_indx) {
6698 for (i=0; i<split_indx; i++) {
6699 node = NODEPTR(mp, i);
6700 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
6701 if (F_ISSET(node->mn_flags, F_BIGDATA))
6702 psize += sizeof(pgno_t);
6704 psize += NODEDSZ(node);
6708 split_indx = newindx;
6719 for (i=nkeys-1; i>=split_indx; i--) {
6720 node = NODEPTR(mp, i);
6721 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
6722 if (F_ISSET(node->mn_flags, F_BIGDATA))
6723 psize += sizeof(pgno_t);
6725 psize += NODEDSZ(node);
6729 split_indx = newindx;
6740 /* First find the separating key between the split pages.
6741 * The case where newindx == split_indx is ambiguous; the
6742 * new item could go to the new page or stay on the original
6743 * page. If newpos == 1 it goes to the new page.
6745 if (newindx == split_indx && newpos) {
6746 sepkey.mv_size = newkey->mv_size;
6747 sepkey.mv_data = newkey->mv_data;
6749 node = NODEPTR(mp, split_indx);
6750 sepkey.mv_size = node->mn_ksize;
6751 sepkey.mv_data = NODEKEY(node);
6755 DPRINTF("separator is [%s]", DKEY(&sepkey));
6757 /* Copy separator key to the parent.
6759 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
6763 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
6766 if (mn.mc_snum == mc->mc_snum) {
6767 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
6768 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
6769 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
6770 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
6775 /* Right page might now have changed parent.
6776 * Check if left page also changed parent.
6778 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
6779 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
6780 for (i=0; i<ptop; i++) {
6781 mc->mc_pg[i] = mn.mc_pg[i];
6782 mc->mc_ki[i] = mn.mc_ki[i];
6784 mc->mc_pg[ptop] = mn.mc_pg[ptop];
6785 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
6789 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
6792 mc->mc_flags ^= C_SPLITTING;
6793 if (rc != MDB_SUCCESS) {
6796 if (nflags & MDB_APPEND) {
6797 mc->mc_pg[mc->mc_top] = rp;
6798 mc->mc_ki[mc->mc_top] = 0;
6799 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
6802 for (i=0; i<mc->mc_top; i++)
6803 mc->mc_ki[i] = mn.mc_ki[i];
6810 /* Move half of the keys to the right sibling. */
6812 /* grab a page to hold a temporary copy */
6813 copy = mdb_page_malloc(mc);
6817 copy->mp_pgno = mp->mp_pgno;
6818 copy->mp_flags = mp->mp_flags;
6819 copy->mp_lower = PAGEHDRSZ;
6820 copy->mp_upper = mc->mc_txn->mt_env->me_psize;
6821 mc->mc_pg[mc->mc_top] = copy;
6822 for (i = j = 0; i <= nkeys; j++) {
6823 if (i == split_indx) {
6824 /* Insert in right sibling. */
6825 /* Reset insert index for right sibling. */
6826 if (i != newindx || (newpos ^ ins_new)) {
6828 mc->mc_pg[mc->mc_top] = rp;
6832 if (i == newindx && !ins_new) {
6833 /* Insert the original entry that caused the split. */
6834 rkey.mv_data = newkey->mv_data;
6835 rkey.mv_size = newkey->mv_size;
6844 /* Update index for the new key. */
6845 mc->mc_ki[mc->mc_top] = j;
6846 } else if (i == nkeys) {
6849 node = NODEPTR(mp, i);
6850 rkey.mv_data = NODEKEY(node);
6851 rkey.mv_size = node->mn_ksize;
6853 xdata.mv_data = NODEDATA(node);
6854 xdata.mv_size = NODEDSZ(node);
6857 pgno = NODEPGNO(node);
6858 flags = node->mn_flags;
6863 if (!IS_LEAF(mp) && j == 0) {
6864 /* First branch index doesn't need key data. */
6868 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
6872 nkeys = NUMKEYS(copy);
6873 for (i=0; i<nkeys; i++)
6874 mp->mp_ptrs[i] = copy->mp_ptrs[i];
6875 mp->mp_lower = copy->mp_lower;
6876 mp->mp_upper = copy->mp_upper;
6877 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
6878 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
6880 /* reset back to original page */
6881 if (newindx < split_indx || (!newpos && newindx == split_indx)) {
6882 mc->mc_pg[mc->mc_top] = mp;
6883 if (nflags & MDB_RESERVE) {
6884 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6885 if (!(node->mn_flags & F_BIGDATA))
6886 newdata->mv_data = NODEDATA(node);
6892 /* return tmp page to freelist */
6893 mdb_page_free(mc->mc_txn->mt_env, copy);
6896 /* Adjust other cursors pointing to mp */
6897 MDB_cursor *m2, *m3;
6898 MDB_dbi dbi = mc->mc_dbi;
6899 int fixup = NUMKEYS(mp);
6901 if (mc->mc_flags & C_SUB)
6904 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6905 if (m2 == mc) continue;
6906 if (mc->mc_flags & C_SUB)
6907 m3 = &m2->mc_xcursor->mx_cursor;
6910 if (!(m3->mc_flags & C_INITIALIZED))
6912 if (m3->mc_flags & C_SPLITTING)
6917 for (k=m3->mc_top; k>=0; k--) {
6918 m3->mc_ki[k+1] = m3->mc_ki[k];
6919 m3->mc_pg[k+1] = m3->mc_pg[k];
6921 if (m3->mc_ki[0] >= split_indx) {
6926 m3->mc_pg[0] = mc->mc_pg[0];
6930 if (m3->mc_pg[mc->mc_top] == mp) {
6931 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
6932 m3->mc_ki[mc->mc_top]++;
6933 if (m3->mc_ki[mc->mc_top] >= fixup) {
6934 m3->mc_pg[mc->mc_top] = rp;
6935 m3->mc_ki[mc->mc_top] -= fixup;
6936 m3->mc_ki[ptop] = mn.mc_ki[ptop];
6938 } else if (!did_split && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
6939 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
6948 mdb_put(MDB_txn *txn, MDB_dbi dbi,
6949 MDB_val *key, MDB_val *data, unsigned int flags)
6954 assert(key != NULL);
6955 assert(data != NULL);
6957 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
6960 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
6964 if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
6968 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP)) != flags)
6971 mdb_cursor_init(&mc, txn, dbi, &mx);
6972 return mdb_cursor_put(&mc, key, data, flags);
6976 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
6978 if ((flag & CHANGEABLE) != flag)
6981 env->me_flags |= flag;
6983 env->me_flags &= ~flag;
6988 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
6993 *arg = env->me_flags;
6998 mdb_env_get_path(MDB_env *env, const char **arg)
7003 *arg = env->me_path;
7007 /** Common code for #mdb_stat() and #mdb_env_stat().
7008 * @param[in] env the environment to operate in.
7009 * @param[in] db the #MDB_db record containing the stats to return.
7010 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
7011 * @return 0, this function always succeeds.
7014 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
7016 arg->ms_psize = env->me_psize;
7017 arg->ms_depth = db->md_depth;
7018 arg->ms_branch_pages = db->md_branch_pages;
7019 arg->ms_leaf_pages = db->md_leaf_pages;
7020 arg->ms_overflow_pages = db->md_overflow_pages;
7021 arg->ms_entries = db->md_entries;
7026 mdb_env_stat(MDB_env *env, MDB_stat *arg)
7030 if (env == NULL || arg == NULL)
7033 toggle = mdb_env_pick_meta(env);
7035 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
7039 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
7043 if (env == NULL || arg == NULL)
7046 toggle = mdb_env_pick_meta(env);
7047 arg->me_mapaddr = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : 0;
7048 arg->me_mapsize = env->me_mapsize;
7049 arg->me_maxreaders = env->me_maxreaders;
7050 arg->me_numreaders = env->me_numreaders;
7051 arg->me_last_pgno = env->me_metas[toggle]->mm_last_pg;
7052 arg->me_last_txnid = env->me_metas[toggle]->mm_txnid;
7056 /** Set the default comparison functions for a database.
7057 * Called immediately after a database is opened to set the defaults.
7058 * The user can then override them with #mdb_set_compare() or
7059 * #mdb_set_dupsort().
7060 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
7061 * @param[in] dbi A database handle returned by #mdb_dbi_open()
7064 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
7066 uint16_t f = txn->mt_dbs[dbi].md_flags;
7068 txn->mt_dbxs[dbi].md_cmp =
7069 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
7070 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
7072 txn->mt_dbxs[dbi].md_dcmp =
7073 !(f & MDB_DUPSORT) ? 0 :
7074 ((f & MDB_INTEGERDUP)
7075 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
7076 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
7079 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
7084 int rc, dbflag, exact;
7085 unsigned int unused = 0;
7088 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
7089 mdb_default_cmp(txn, FREE_DBI);
7092 if ((flags & VALID_FLAGS) != flags)
7098 if (flags & PERSISTENT_FLAGS) {
7099 uint16_t f2 = flags & PERSISTENT_FLAGS;
7100 /* make sure flag changes get committed */
7101 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
7102 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
7103 txn->mt_flags |= MDB_TXN_DIRTY;
7106 mdb_default_cmp(txn, MAIN_DBI);
7110 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
7111 mdb_default_cmp(txn, MAIN_DBI);
7114 /* Is the DB already open? */
7116 for (i=2; i<txn->mt_numdbs; i++) {
7117 if (!txn->mt_dbxs[i].md_name.mv_size) {
7118 /* Remember this free slot */
7119 if (!unused) unused = i;
7122 if (len == txn->mt_dbxs[i].md_name.mv_size &&
7123 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
7129 /* If no free slot and max hit, fail */
7130 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
7131 return MDB_DBS_FULL;
7133 /* Find the DB info */
7134 dbflag = DB_NEW|DB_VALID;
7137 key.mv_data = (void *)name;
7138 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
7139 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
7140 if (rc == MDB_SUCCESS) {
7141 /* make sure this is actually a DB */
7142 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
7143 if (!(node->mn_flags & F_SUBDATA))
7145 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
7146 /* Create if requested */
7148 data.mv_size = sizeof(MDB_db);
7149 data.mv_data = &dummy;
7150 memset(&dummy, 0, sizeof(dummy));
7151 dummy.md_root = P_INVALID;
7152 dummy.md_flags = flags & PERSISTENT_FLAGS;
7153 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
7157 /* OK, got info, add to table */
7158 if (rc == MDB_SUCCESS) {
7159 unsigned int slot = unused ? unused : txn->mt_numdbs;
7160 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
7161 txn->mt_dbxs[slot].md_name.mv_size = len;
7162 txn->mt_dbxs[slot].md_rel = NULL;
7163 txn->mt_dbflags[slot] = dbflag;
7164 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
7166 txn->mt_env->me_dbflags[slot] = txn->mt_dbs[slot].md_flags;
7167 mdb_default_cmp(txn, slot);
7176 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
7178 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
7181 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
7184 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
7187 if (dbi <= MAIN_DBI || dbi >= env->me_maxdbs)
7189 ptr = env->me_dbxs[dbi].md_name.mv_data;
7190 env->me_dbxs[dbi].md_name.mv_data = NULL;
7191 env->me_dbxs[dbi].md_name.mv_size = 0;
7195 /** Add all the DB's pages to the free list.
7196 * @param[in] mc Cursor on the DB to free.
7197 * @param[in] subs non-Zero to check for sub-DBs in this DB.
7198 * @return 0 on success, non-zero on failure.
7201 mdb_drop0(MDB_cursor *mc, int subs)
7205 rc = mdb_page_search(mc, NULL, 0);
7206 if (rc == MDB_SUCCESS) {
7211 /* LEAF2 pages have no nodes, cannot have sub-DBs */
7212 if (IS_LEAF2(mc->mc_pg[mc->mc_top]))
7215 mdb_cursor_copy(mc, &mx);
7216 while (mc->mc_snum > 0) {
7217 if (IS_LEAF(mc->mc_pg[mc->mc_top])) {
7218 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
7219 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
7220 if (ni->mn_flags & F_BIGDATA) {
7221 int j, ovpages = OVPAGES(NODEDSZ(ni), mc->mc_txn->mt_env->me_psize);
7223 memcpy(&pg, NODEDATA(ni), sizeof(pg));
7224 for (j=0; j<ovpages; j++) {
7225 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
7228 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
7229 mdb_xcursor_init1(mc, ni);
7230 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
7236 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
7238 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
7241 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
7246 mc->mc_ki[mc->mc_top] = i;
7247 rc = mdb_cursor_sibling(mc, 1);
7249 /* no more siblings, go back to beginning
7250 * of previous level.
7254 for (i=1; i<mc->mc_snum; i++) {
7256 mc->mc_pg[i] = mx.mc_pg[i];
7261 mdb_midl_append(&mc->mc_txn->mt_free_pgs,
7262 mc->mc_db->md_root);
7267 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
7272 if (!txn || !dbi || dbi >= txn->mt_numdbs || (unsigned)del > 1 || !(txn->mt_dbflags[dbi] & DB_VALID))
7275 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
7278 rc = mdb_cursor_open(txn, dbi, &mc);
7282 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
7286 /* Can't delete the main DB */
7287 if (del && dbi > MAIN_DBI) {
7288 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
7290 txn->mt_dbflags[dbi] = DB_STALE;
7291 mdb_dbi_close(txn->mt_env, dbi);
7294 /* reset the DB record, mark it dirty */
7295 txn->mt_dbflags[dbi] |= DB_DIRTY;
7296 txn->mt_dbs[dbi].md_depth = 0;
7297 txn->mt_dbs[dbi].md_branch_pages = 0;
7298 txn->mt_dbs[dbi].md_leaf_pages = 0;
7299 txn->mt_dbs[dbi].md_overflow_pages = 0;
7300 txn->mt_dbs[dbi].md_entries = 0;
7301 txn->mt_dbs[dbi].md_root = P_INVALID;
7303 txn->mt_flags |= MDB_TXN_DIRTY;
7306 mdb_cursor_close(mc);
7310 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
7312 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7315 txn->mt_dbxs[dbi].md_cmp = cmp;
7319 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
7321 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7324 txn->mt_dbxs[dbi].md_dcmp = cmp;
7328 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
7330 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7333 txn->mt_dbxs[dbi].md_rel = rel;
7337 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
7339 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7342 txn->mt_dbxs[dbi].md_relctx = ctx;