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 /** Handle for the DB used to track free pages. */
750 /** Handle for the default DB. */
753 /** Meta page content. */
754 typedef struct MDB_meta {
755 /** Stamp identifying this as an MDB file. It must be set
758 /** Version number of this lock file. Must be set to #MDB_VERSION. */
760 void *mm_address; /**< address for fixed mapping */
761 size_t mm_mapsize; /**< size of mmap region */
762 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
763 /** The size of pages used in this DB */
764 #define mm_psize mm_dbs[0].md_pad
765 /** Any persistent environment flags. @ref mdb_env */
766 #define mm_flags mm_dbs[0].md_flags
767 pgno_t mm_last_pg; /**< last used page in file */
768 txnid_t mm_txnid; /**< txnid that committed this page */
771 /** Buffer for a stack-allocated dirty page.
772 * The members define size and alignment, and silence type
773 * aliasing warnings. They are not used directly; that could
774 * mean incorrectly using several union members in parallel.
776 typedef union MDB_pagebuf {
777 char mb_raw[MDB_PAGESIZE];
780 char mm_pad[PAGEHDRSZ];
785 /** Auxiliary DB info.
786 * The information here is mostly static/read-only. There is
787 * only a single copy of this record in the environment.
789 typedef struct MDB_dbx {
790 MDB_val md_name; /**< name of the database */
791 MDB_cmp_func *md_cmp; /**< function for comparing keys */
792 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
793 MDB_rel_func *md_rel; /**< user relocate function */
794 void *md_relctx; /**< user-provided context for md_rel */
797 /** A database transaction.
798 * Every operation requires a transaction handle.
801 MDB_txn *mt_parent; /**< parent of a nested txn */
802 MDB_txn *mt_child; /**< nested txn under this txn */
803 pgno_t mt_next_pgno; /**< next unallocated page */
804 /** The ID of this transaction. IDs are integers incrementing from 1.
805 * Only committed write transactions increment the ID. If a transaction
806 * aborts, the ID may be re-used by the next writer.
809 MDB_env *mt_env; /**< the DB environment */
810 /** The list of pages that became unused during this transaction.
814 MDB_ID2L dirty_list; /**< for write txns: modified pages */
815 MDB_reader *reader; /**< this thread's reader table slot or NULL */
817 /** Array of records for each DB known in the environment. */
819 /** Array of MDB_db records for each known DB */
821 /** @defgroup mt_dbflag Transaction DB Flags
825 #define DB_DIRTY 0x01 /**< DB was written in this txn */
826 #define DB_STALE 0x02 /**< DB record is older than txnID */
828 /** In write txns, array of cursors for each DB */
829 MDB_cursor **mt_cursors;
830 /** Array of flags for each DB */
831 unsigned char *mt_dbflags;
832 /** Number of DB records in use. This number only ever increments;
833 * we don't decrement it when individual DB handles are closed.
837 /** @defgroup mdb_txn Transaction Flags
841 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
842 #define MDB_TXN_ERROR 0x02 /**< an error has occurred */
843 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
845 unsigned int mt_flags; /**< @ref mdb_txn */
846 /** dirty_list maxsize - #allocated pages including in parent txns */
847 unsigned int mt_dirty_room;
848 /** Tracks which of the two meta pages was used at the start
849 * of this transaction.
851 unsigned int mt_toggle;
854 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
855 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
856 * raise this on a 64 bit machine.
858 #define CURSOR_STACK 32
862 /** Cursors are used for all DB operations */
864 /** Next cursor on this DB in this txn */
866 /** Original cursor if this is a shadow */
868 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
869 struct MDB_xcursor *mc_xcursor;
870 /** The transaction that owns this cursor */
872 /** The database handle this cursor operates on */
874 /** The database record for this cursor */
876 /** The database auxiliary record for this cursor */
878 /** The @ref mt_dbflag for this database */
879 unsigned char *mc_dbflag;
880 unsigned short mc_snum; /**< number of pushed pages */
881 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
882 /** @defgroup mdb_cursor Cursor Flags
884 * Cursor state flags.
887 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
888 #define C_EOF 0x02 /**< No more data */
889 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
890 #define C_SHADOW 0x08 /**< Cursor is a dup from a parent txn */
891 #define C_ALLOCD 0x10 /**< Cursor was malloc'd */
892 #define C_SPLITTING 0x20 /**< Cursor is in page_split */
894 unsigned int mc_flags; /**< @ref mdb_cursor */
895 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
896 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
899 /** Context for sorted-dup records.
900 * We could have gone to a fully recursive design, with arbitrarily
901 * deep nesting of sub-databases. But for now we only handle these
902 * levels - main DB, optional sub-DB, sorted-duplicate DB.
904 typedef struct MDB_xcursor {
905 /** A sub-cursor for traversing the Dup DB */
906 MDB_cursor mx_cursor;
907 /** The database record for this Dup DB */
909 /** The auxiliary DB record for this Dup DB */
911 /** The @ref mt_dbflag for this Dup DB */
912 unsigned char mx_dbflag;
915 /** State of FreeDB old pages, stored in the MDB_env */
916 typedef struct MDB_pgstate {
917 txnid_t mf_pglast; /**< ID of last old page record we used */
918 pgno_t *mf_pghead; /**< old pages reclaimed from freelist */
919 pgno_t *mf_pgfree; /**< memory to free when dropping me_pghead */
922 /** The database environment. */
924 HANDLE me_fd; /**< The main data file */
925 HANDLE me_lfd; /**< The lock file */
926 HANDLE me_mfd; /**< just for writing the meta pages */
927 /** Failed to update the meta page. Probably an I/O error. */
928 #define MDB_FATAL_ERROR 0x80000000U
929 /** Read-only Filesystem. Allow read access, no locking. */
930 #define MDB_ROFS 0x40000000U
931 /** Some fields are initialized. */
932 #define MDB_ENV_ACTIVE 0x20000000U
933 uint32_t me_flags; /**< @ref mdb_env */
934 unsigned int me_psize; /**< size of a page, from #GET_PAGESIZE */
935 unsigned int me_maxreaders; /**< size of the reader table */
936 unsigned int me_numreaders; /**< max numreaders set by this env */
937 MDB_dbi me_numdbs; /**< number of DBs opened */
938 MDB_dbi me_maxdbs; /**< size of the DB table */
939 pid_t me_pid; /**< process ID of this env */
940 char *me_path; /**< path to the DB files */
941 char *me_map; /**< the memory map of the data file */
942 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
943 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
944 MDB_txn *me_txn; /**< current write transaction */
945 size_t me_mapsize; /**< size of the data memory map */
946 off_t me_size; /**< current file size */
947 pgno_t me_maxpg; /**< me_mapsize / me_psize */
948 MDB_dbx *me_dbxs; /**< array of static DB info */
949 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
950 pthread_key_t me_txkey; /**< thread-key for readers */
951 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
952 # define me_pglast me_pgstate.mf_pglast
953 # define me_pghead me_pgstate.mf_pghead
954 # define me_pgfree me_pgstate.mf_pgfree
955 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
956 /** IDL of pages that became unused in a write txn */
958 /** ID2L of pages that were written during a write txn */
959 MDB_ID2 me_dirty_list[MDB_IDL_UM_SIZE];
960 /** Max number of freelist items that can fit in a single overflow page */
961 unsigned int me_maxfree_1pg;
962 /** Max size of a node on a page */
963 unsigned int me_nodemax;
965 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
967 #elif defined(MDB_USE_POSIX_SEM)
968 sem_t *me_rmutex; /* Shared mutexes are not supported */
973 /** Nested transaction */
974 typedef struct MDB_ntxn {
975 MDB_txn mnt_txn; /* the transaction */
976 MDB_pgstate mnt_pgstate; /* parent transaction's saved freestate */
979 /** max number of pages to commit in one writev() call */
980 #define MDB_COMMIT_PAGES 64
981 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
982 #undef MDB_COMMIT_PAGES
983 #define MDB_COMMIT_PAGES IOV_MAX
986 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
987 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
988 static int mdb_page_touch(MDB_cursor *mc);
990 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
991 static int mdb_page_search_root(MDB_cursor *mc,
992 MDB_val *key, int modify);
993 #define MDB_PS_MODIFY 1
994 #define MDB_PS_ROOTONLY 2
995 static int mdb_page_search(MDB_cursor *mc,
996 MDB_val *key, int flags);
997 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
999 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1000 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1001 pgno_t newpgno, unsigned int nflags);
1003 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1004 static int mdb_env_pick_meta(const MDB_env *env);
1005 static int mdb_env_write_meta(MDB_txn *txn);
1006 static void mdb_env_close0(MDB_env *env, int excl);
1008 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1009 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1010 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1011 static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
1012 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1013 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
1014 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1015 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1016 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1018 static int mdb_rebalance(MDB_cursor *mc);
1019 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1021 static void mdb_cursor_pop(MDB_cursor *mc);
1022 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1024 static int mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
1025 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1026 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1027 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1028 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1030 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1031 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1033 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1034 static void mdb_xcursor_init0(MDB_cursor *mc);
1035 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1037 static int mdb_drop0(MDB_cursor *mc, int subs);
1038 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1041 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1045 static SECURITY_DESCRIPTOR mdb_null_sd;
1046 static SECURITY_ATTRIBUTES mdb_all_sa;
1047 static int mdb_sec_inited;
1050 /** Return the library version info. */
1052 mdb_version(int *major, int *minor, int *patch)
1054 if (major) *major = MDB_VERSION_MAJOR;
1055 if (minor) *minor = MDB_VERSION_MINOR;
1056 if (patch) *patch = MDB_VERSION_PATCH;
1057 return MDB_VERSION_STRING;
1060 /** Table of descriptions for MDB @ref errors */
1061 static char *const mdb_errstr[] = {
1062 "MDB_KEYEXIST: Key/data pair already exists",
1063 "MDB_NOTFOUND: No matching key/data pair found",
1064 "MDB_PAGE_NOTFOUND: Requested page not found",
1065 "MDB_CORRUPTED: Located page was wrong type",
1066 "MDB_PANIC: Update of meta page failed",
1067 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1068 "MDB_INVALID: File is not an MDB file",
1069 "MDB_MAP_FULL: Environment mapsize limit reached",
1070 "MDB_DBS_FULL: Environment maxdbs limit reached",
1071 "MDB_READERS_FULL: Environment maxreaders limit reached",
1072 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1073 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1074 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1075 "MDB_PAGE_FULL: Internal error - page has no more space",
1076 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1077 "MDB_INCOMPATIBLE: Database flags changed or would change",
1081 mdb_strerror(int err)
1085 return ("Successful return: 0");
1087 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1088 i = err - MDB_KEYEXIST;
1089 return mdb_errstr[i];
1092 return strerror(err);
1096 /** Display a key in hexadecimal and return the address of the result.
1097 * @param[in] key the key to display
1098 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1099 * @return The key in hexadecimal form.
1102 mdb_dkey(MDB_val *key, char *buf)
1105 unsigned char *c = key->mv_data;
1111 if (key->mv_size > MDB_MAXKEYSIZE)
1112 return "MDB_MAXKEYSIZE";
1113 /* may want to make this a dynamic check: if the key is mostly
1114 * printable characters, print it as-is instead of converting to hex.
1118 for (i=0; i<key->mv_size; i++)
1119 ptr += sprintf(ptr, "%02x", *c++);
1121 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1126 /** Display all the keys in the page. */
1128 mdb_page_list(MDB_page *mp)
1131 unsigned int i, nkeys, nsize;
1135 nkeys = NUMKEYS(mp);
1136 fprintf(stderr, "Page %zu numkeys %d\n", mp->mp_pgno, nkeys);
1137 for (i=0; i<nkeys; i++) {
1138 node = NODEPTR(mp, i);
1139 key.mv_size = node->mn_ksize;
1140 key.mv_data = node->mn_data;
1141 nsize = NODESIZE + NODEKSZ(node) + sizeof(indx_t);
1142 if (IS_BRANCH(mp)) {
1143 fprintf(stderr, "key %d: page %zu, %s\n", i, NODEPGNO(node),
1146 if (F_ISSET(node->mn_flags, F_BIGDATA))
1147 nsize += sizeof(pgno_t);
1149 nsize += NODEDSZ(node);
1150 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1156 mdb_cursor_chk(MDB_cursor *mc)
1162 if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1163 for (i=0; i<mc->mc_top; i++) {
1165 node = NODEPTR(mp, mc->mc_ki[i]);
1166 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1169 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1175 /** Count all the pages in each DB and in the freelist
1176 * and make sure it matches the actual number of pages
1179 static void mdb_audit(MDB_txn *txn)
1183 MDB_ID freecount, count;
1188 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1189 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1190 freecount += *(MDB_ID *)data.mv_data;
1193 for (i = 0; i<txn->mt_numdbs; i++) {
1194 MDB_xcursor mx, *mxp;
1195 mxp = (txn->mt_dbs[i].md_flags & MDB_DUPSORT) ? &mx : NULL;
1196 mdb_cursor_init(&mc, txn, i, mxp);
1197 if (txn->mt_dbs[i].md_root == P_INVALID)
1199 count += txn->mt_dbs[i].md_branch_pages +
1200 txn->mt_dbs[i].md_leaf_pages +
1201 txn->mt_dbs[i].md_overflow_pages;
1202 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1203 mdb_page_search(&mc, NULL, 0);
1207 mp = mc.mc_pg[mc.mc_top];
1208 for (j=0; j<NUMKEYS(mp); j++) {
1209 MDB_node *leaf = NODEPTR(mp, j);
1210 if (leaf->mn_flags & F_SUBDATA) {
1212 memcpy(&db, NODEDATA(leaf), sizeof(db));
1213 count += db.md_branch_pages + db.md_leaf_pages +
1214 db.md_overflow_pages;
1218 while (mdb_cursor_sibling(&mc, 1) == 0);
1221 if (freecount + count + 2 /* metapages */ != txn->mt_next_pgno) {
1222 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1223 txn->mt_txnid, freecount, count+2, freecount+count+2, txn->mt_next_pgno);
1229 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1231 return txn->mt_dbxs[dbi].md_cmp(a, b);
1235 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1237 if (txn->mt_dbxs[dbi].md_dcmp)
1238 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1240 return EINVAL; /* too bad you can't distinguish this from a valid result */
1243 /** Allocate a single page.
1244 * Re-use old malloc'd pages first, otherwise just malloc.
1247 mdb_page_malloc(MDB_cursor *mc) {
1249 size_t sz = mc->mc_txn->mt_env->me_psize;
1250 if ((ret = mc->mc_txn->mt_env->me_dpages) != NULL) {
1251 VGMEMP_ALLOC(mc->mc_txn->mt_env, ret, sz);
1252 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1253 mc->mc_txn->mt_env->me_dpages = ret->mp_next;
1254 } else if ((ret = malloc(sz)) != NULL) {
1255 VGMEMP_ALLOC(mc->mc_txn->mt_env, ret, sz);
1261 mdb_page_free(MDB_env *env, MDB_page *mp)
1263 mp->mp_next = env->me_dpages;
1264 VGMEMP_FREE(env, mp);
1265 env->me_dpages = mp;
1268 /** Allocate pages for writing.
1269 * If there are free pages available from older transactions, they
1270 * will be re-used first. Otherwise a new page will be allocated.
1271 * @param[in] mc cursor A cursor handle identifying the transaction and
1272 * database for which we are allocating.
1273 * @param[in] num the number of pages to allocate.
1274 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
1275 * will always be satisfied by a single contiguous chunk of memory.
1276 * @return 0 on success, non-zero on failure.
1279 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
1281 MDB_txn *txn = mc->mc_txn;
1283 pgno_t pgno = P_INVALID;
1285 txnid_t oldest = 0, last;
1290 /* If our dirty list is already full, we can't do anything */
1291 if (txn->mt_dirty_room == 0)
1292 return MDB_TXN_FULL;
1294 /* The free list won't have any content at all until txn 2 has
1295 * committed. The pages freed by txn 2 will be unreferenced
1296 * after txn 3 commits, and so will be safe to re-use in txn 4.
1298 if (txn->mt_txnid > 3) {
1299 if (!txn->mt_env->me_pghead &&
1300 txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
1301 /* See if there's anything in the free DB */
1308 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1309 if (!txn->mt_env->me_pglast) {
1310 mdb_page_search(&m2, NULL, 0);
1311 leaf = NODEPTR(m2.mc_pg[m2.mc_top], 0);
1312 kptr = (txnid_t *)NODEKEY(leaf);
1317 last = txn->mt_env->me_pglast + 1;
1319 key.mv_data = &last;
1320 key.mv_size = sizeof(last);
1321 rc = mdb_cursor_set(&m2, &key, &data, MDB_SET_RANGE, NULL);
1324 last = *(txnid_t *)key.mv_data;
1330 oldest = txn->mt_txnid - 1;
1331 nr = txn->mt_env->me_txns->mti_numreaders;
1332 r = txn->mt_env->me_txns->mti_readers;
1333 for (i=0; i<nr; i++) {
1334 if (!r[i].mr_pid) continue;
1341 if (oldest > last) {
1342 /* It's usable, grab it.
1346 if (!txn->mt_env->me_pglast) {
1347 mdb_node_read(txn, leaf, &data);
1349 idl = (MDB_ID *) data.mv_data;
1350 /* We might have a zero-length IDL due to freelist growth
1351 * during a prior commit
1354 txn->mt_env->me_pglast = last;
1357 mop = malloc(MDB_IDL_SIZEOF(idl));
1360 txn->mt_env->me_pglast = last;
1361 txn->mt_env->me_pghead = txn->mt_env->me_pgfree = mop;
1362 memcpy(mop, idl, MDB_IDL_SIZEOF(idl));
1367 DPRINTF("IDL read txn %zu root %zu num %zu",
1368 last, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1369 for (i=0; i<idl[0]; i++) {
1370 DPRINTF("IDL %zu", idl[i+1]);
1377 if (txn->mt_env->me_pghead) {
1378 pgno_t *mop = txn->mt_env->me_pghead;
1381 int retry = 1, readit = 0, n2 = num-1;
1382 unsigned int i, j, k;
1384 /* If current list is too short, must fetch more and coalesce */
1385 if (mop[0] < (unsigned)num)
1388 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1390 /* If on freelist, don't try to read more. If what we have
1391 * right now isn't enough just use new pages.
1392 * TODO: get all of this working. Many circular dependencies...
1394 if (mc->mc_dbi == FREE_DBI) {
1402 last = txn->mt_env->me_pglast + 1;
1404 /* We haven't hit the readers list yet? */
1410 oldest = txn->mt_txnid - 1;
1411 nr = txn->mt_env->me_txns->mti_numreaders;
1412 r = txn->mt_env->me_txns->mti_readers;
1413 for (i=0; i<nr; i++) {
1414 if (!r[i].mr_pid) continue;
1421 /* There's nothing we can use on the freelist */
1422 if (oldest - last < 1)
1425 key.mv_data = &last;
1426 key.mv_size = sizeof(last);
1427 rc = mdb_cursor_set(&m2,&key,&data,MDB_SET_RANGE,NULL);
1429 if (rc == MDB_NOTFOUND)
1433 last = *(txnid_t*)key.mv_data;
1436 idl = (MDB_ID *) data.mv_data;
1437 mop2 = malloc(MDB_IDL_SIZEOF(idl) + MDB_IDL_SIZEOF(mop));
1440 /* merge in sorted order */
1441 i = idl[0]; j = mop[0]; mop2[0] = k = i+j;
1443 while (i>0 || j>0) {
1444 if (i && idl[i] < mop[j])
1445 mop2[k--] = idl[i--];
1447 mop2[k--] = mop[j--];
1449 txn->mt_env->me_pglast = last;
1450 free(txn->mt_env->me_pgfree);
1451 txn->mt_env->me_pghead = txn->mt_env->me_pgfree = mop2;
1453 /* Keep trying to read until we have enough */
1454 if (mop[0] < (unsigned)num) {
1459 /* current list has enough pages, but are they contiguous? */
1460 for (i=mop[0]; i>=(unsigned)num; i--) {
1461 if (mop[i-n2] == mop[i] + n2) {
1464 /* move any stragglers down */
1465 for (j=i+num; j<=mop[0]; j++)
1472 /* Stop if we succeeded, or no retries */
1473 if (!retry || pgno != P_INVALID)
1479 /* peel pages off tail, so we only have to truncate the list */
1480 pgno = MDB_IDL_LAST(mop);
1483 if (MDB_IDL_IS_ZERO(mop)) {
1484 free(txn->mt_env->me_pgfree);
1485 txn->mt_env->me_pghead = txn->mt_env->me_pgfree = NULL;
1490 if (pgno == P_INVALID) {
1491 /* DB size is maxed out */
1492 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg) {
1493 DPUTS("DB size maxed out");
1494 return MDB_MAP_FULL;
1497 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1498 if (pgno == P_INVALID) {
1499 pgno = txn->mt_next_pgno;
1500 txn->mt_next_pgno += num;
1502 np = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
1505 if (txn->mt_env->me_dpages && num == 1) {
1506 np = txn->mt_env->me_dpages;
1507 VGMEMP_ALLOC(txn->mt_env, np, txn->mt_env->me_psize);
1508 VGMEMP_DEFINED(np, sizeof(np->mp_next));
1509 txn->mt_env->me_dpages = np->mp_next;
1511 size_t sz = txn->mt_env->me_psize * num;
1512 if ((np = malloc(sz)) == NULL)
1514 VGMEMP_ALLOC(txn->mt_env, np, sz);
1516 if (pgno == P_INVALID) {
1517 np->mp_pgno = txn->mt_next_pgno;
1518 txn->mt_next_pgno += num;
1523 mid.mid = np->mp_pgno;
1525 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1526 mdb_mid2l_append(txn->mt_u.dirty_list, &mid);
1528 mdb_mid2l_insert(txn->mt_u.dirty_list, &mid);
1530 txn->mt_dirty_room--;
1536 /** Copy a page: avoid copying unused portions of the page.
1537 * @param[in] dst page to copy into
1538 * @param[in] src page to copy from
1541 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
1543 dst->mp_flags = src->mp_flags | P_DIRTY;
1544 dst->mp_pages = src->mp_pages;
1546 if (IS_LEAF2(src)) {
1547 memcpy(dst->mp_ptrs, src->mp_ptrs, psize - PAGEHDRSZ - SIZELEFT(src));
1549 unsigned int i, nkeys = NUMKEYS(src);
1550 for (i=0; i<nkeys; i++)
1551 dst->mp_ptrs[i] = src->mp_ptrs[i];
1552 memcpy((char *)dst+src->mp_upper, (char *)src+src->mp_upper,
1553 psize - src->mp_upper);
1557 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1558 * @param[in] mc cursor pointing to the page to be touched
1559 * @return 0 on success, non-zero on failure.
1562 mdb_page_touch(MDB_cursor *mc)
1564 MDB_page *mp = mc->mc_pg[mc->mc_top];
1568 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1570 if ((rc = mdb_page_alloc(mc, 1, &np)))
1572 DPRINTF("touched db %u page %zu -> %zu", mc->mc_dbi, mp->mp_pgno, np->mp_pgno);
1573 assert(mp->mp_pgno != np->mp_pgno);
1574 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
1576 /* If page isn't full, just copy the used portion */
1577 mdb_page_copy(np, mp, mc->mc_txn->mt_env->me_psize);
1580 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1582 np->mp_flags |= P_DIRTY;
1587 /* Adjust other cursors pointing to mp */
1588 if (mc->mc_flags & C_SUB) {
1589 MDB_cursor *m2, *m3;
1590 MDB_dbi dbi = mc->mc_dbi-1;
1592 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
1593 if (m2 == mc) continue;
1594 m3 = &m2->mc_xcursor->mx_cursor;
1595 if (m3->mc_snum < mc->mc_snum) continue;
1596 if (m3->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1597 m3->mc_pg[mc->mc_top] = mp;
1603 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
1604 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
1605 if (m2->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1606 m2->mc_pg[mc->mc_top] = mp;
1610 mc->mc_pg[mc->mc_top] = mp;
1611 /** If this page has a parent, update the parent to point to
1615 SETPGNO(NODEPTR(mc->mc_pg[mc->mc_top-1], mc->mc_ki[mc->mc_top-1]), mp->mp_pgno);
1617 mc->mc_db->md_root = mp->mp_pgno;
1618 } else if (mc->mc_txn->mt_parent) {
1621 /* If txn has a parent, make sure the page is in our
1624 if (mc->mc_txn->mt_u.dirty_list[0].mid) {
1625 unsigned x = mdb_mid2l_search(mc->mc_txn->mt_u.dirty_list, mp->mp_pgno);
1626 if (x <= mc->mc_txn->mt_u.dirty_list[0].mid &&
1627 mc->mc_txn->mt_u.dirty_list[x].mid == mp->mp_pgno) {
1628 if (mc->mc_txn->mt_u.dirty_list[x].mptr != mp) {
1629 mp = mc->mc_txn->mt_u.dirty_list[x].mptr;
1630 mc->mc_pg[mc->mc_top] = mp;
1635 assert(mc->mc_txn->mt_u.dirty_list[0].mid < MDB_IDL_UM_MAX);
1637 np = mdb_page_malloc(mc);
1640 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1641 mid.mid = np->mp_pgno;
1643 mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &mid);
1651 mdb_env_sync(MDB_env *env, int force)
1654 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1655 if (env->me_flags & MDB_WRITEMAP) {
1656 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
1657 ? MS_ASYNC : MS_SYNC;
1658 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
1661 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
1665 if (MDB_FDATASYNC(env->me_fd))
1672 /** Make shadow copies of all of parent txn's cursors */
1674 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
1676 MDB_cursor *mc, *m2;
1677 unsigned int i, j, size;
1679 for (i=0;i<src->mt_numdbs; i++) {
1680 if (src->mt_cursors[i]) {
1681 size = sizeof(MDB_cursor);
1682 if (src->mt_cursors[i]->mc_xcursor)
1683 size += sizeof(MDB_xcursor);
1684 for (m2 = src->mt_cursors[i]; m2; m2=m2->mc_next) {
1691 mc->mc_db = &dst->mt_dbs[i];
1692 mc->mc_dbx = m2->mc_dbx;
1693 mc->mc_dbflag = &dst->mt_dbflags[i];
1694 mc->mc_snum = m2->mc_snum;
1695 mc->mc_top = m2->mc_top;
1696 mc->mc_flags = m2->mc_flags | C_SHADOW;
1697 for (j=0; j<mc->mc_snum; j++) {
1698 mc->mc_pg[j] = m2->mc_pg[j];
1699 mc->mc_ki[j] = m2->mc_ki[j];
1701 if (m2->mc_xcursor) {
1702 MDB_xcursor *mx, *mx2;
1703 mx = (MDB_xcursor *)(mc+1);
1704 mc->mc_xcursor = mx;
1705 mx2 = m2->mc_xcursor;
1706 mx->mx_db = mx2->mx_db;
1707 mx->mx_dbx = mx2->mx_dbx;
1708 mx->mx_dbflag = mx2->mx_dbflag;
1709 mx->mx_cursor.mc_txn = dst;
1710 mx->mx_cursor.mc_dbi = mx2->mx_cursor.mc_dbi;
1711 mx->mx_cursor.mc_db = &mx->mx_db;
1712 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
1713 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
1714 mx->mx_cursor.mc_snum = mx2->mx_cursor.mc_snum;
1715 mx->mx_cursor.mc_top = mx2->mx_cursor.mc_top;
1716 mx->mx_cursor.mc_flags = mx2->mx_cursor.mc_flags | C_SHADOW;
1717 for (j=0; j<mx2->mx_cursor.mc_snum; j++) {
1718 mx->mx_cursor.mc_pg[j] = mx2->mx_cursor.mc_pg[j];
1719 mx->mx_cursor.mc_ki[j] = mx2->mx_cursor.mc_ki[j];
1722 mc->mc_xcursor = NULL;
1724 mc->mc_next = dst->mt_cursors[i];
1725 dst->mt_cursors[i] = mc;
1732 /** Merge shadow cursors back into parent's */
1734 mdb_cursor_merge(MDB_txn *txn)
1737 for (i=0; i<txn->mt_numdbs; i++) {
1738 if (txn->mt_cursors[i]) {
1740 while ((mc = txn->mt_cursors[i])) {
1741 txn->mt_cursors[i] = mc->mc_next;
1742 if (mc->mc_flags & C_SHADOW) {
1743 MDB_cursor *m2 = mc->mc_orig;
1745 m2->mc_snum = mc->mc_snum;
1746 m2->mc_top = mc->mc_top;
1747 for (j=0; j<mc->mc_snum; j++) {
1748 m2->mc_pg[j] = mc->mc_pg[j];
1749 m2->mc_ki[j] = mc->mc_ki[j];
1752 if (mc->mc_flags & C_ALLOCD)
1760 mdb_txn_reset0(MDB_txn *txn);
1762 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
1763 * @param[in] txn the transaction handle to initialize
1764 * @return 0 on success, non-zero on failure. This can only
1765 * fail for read-only transactions, and then only if the
1766 * reader table is full.
1769 mdb_txn_renew0(MDB_txn *txn)
1771 MDB_env *env = txn->mt_env;
1776 txn->mt_numdbs = env->me_numdbs;
1777 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
1779 if (txn->mt_flags & MDB_TXN_RDONLY) {
1780 if (env->me_flags & MDB_ROFS) {
1781 i = mdb_env_pick_meta(env);
1782 txn->mt_txnid = env->me_metas[i]->mm_txnid;
1783 txn->mt_u.reader = NULL;
1785 MDB_reader *r = pthread_getspecific(env->me_txkey);
1787 pid_t pid = env->me_pid;
1788 pthread_t tid = pthread_self();
1791 for (i=0; i<env->me_txns->mti_numreaders; i++)
1792 if (env->me_txns->mti_readers[i].mr_pid == 0)
1794 if (i == env->me_maxreaders) {
1795 UNLOCK_MUTEX_R(env);
1796 return MDB_READERS_FULL;
1798 env->me_txns->mti_readers[i].mr_pid = pid;
1799 env->me_txns->mti_readers[i].mr_tid = tid;
1800 if (i >= env->me_txns->mti_numreaders)
1801 env->me_txns->mti_numreaders = i+1;
1802 /* Save numreaders for un-mutexed mdb_env_close() */
1803 env->me_numreaders = env->me_txns->mti_numreaders;
1804 UNLOCK_MUTEX_R(env);
1805 r = &env->me_txns->mti_readers[i];
1806 if ((rc = pthread_setspecific(env->me_txkey, r)) != 0) {
1807 env->me_txns->mti_readers[i].mr_pid = 0;
1811 txn->mt_txnid = r->mr_txnid = env->me_txns->mti_txnid;
1812 txn->mt_u.reader = r;
1814 txn->mt_toggle = txn->mt_txnid & 1;
1815 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1819 txn->mt_txnid = env->me_txns->mti_txnid;
1820 txn->mt_toggle = txn->mt_txnid & 1;
1821 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1824 if (txn->mt_txnid == mdb_debug_start)
1827 txn->mt_dirty_room = MDB_IDL_UM_MAX;
1828 txn->mt_u.dirty_list = env->me_dirty_list;
1829 txn->mt_u.dirty_list[0].mid = 0;
1830 txn->mt_free_pgs = env->me_free_pgs;
1831 txn->mt_free_pgs[0] = 0;
1835 /* Copy the DB info and flags */
1836 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
1837 for (i=2; i<txn->mt_numdbs; i++)
1838 txn->mt_dbs[i].md_flags = env->me_dbflags[i];
1839 txn->mt_dbflags[0] = txn->mt_dbflags[1] = 0;
1840 if (txn->mt_numdbs > 2)
1841 memset(txn->mt_dbflags+2, DB_STALE, txn->mt_numdbs-2);
1843 if (env->me_maxpg < txn->mt_next_pgno) {
1844 mdb_txn_reset0(txn);
1845 return MDB_MAP_RESIZED;
1852 mdb_txn_renew(MDB_txn *txn)
1856 if (! (txn && (txn->mt_flags & MDB_TXN_RDONLY)))
1859 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
1860 DPUTS("environment had fatal error, must shutdown!");
1864 rc = mdb_txn_renew0(txn);
1865 if (rc == MDB_SUCCESS) {
1866 DPRINTF("renew txn %zu%c %p on mdbenv %p, root page %zu",
1867 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1868 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1874 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
1878 int rc, size, tsize = sizeof(MDB_txn);
1880 if (env->me_flags & MDB_FATAL_ERROR) {
1881 DPUTS("environment had fatal error, must shutdown!");
1884 if ((env->me_flags & MDB_RDONLY) && !(flags & MDB_RDONLY))
1887 /* Nested transactions: Max 1 child, write txns only, no writemap */
1888 if (parent->mt_child ||
1889 (flags & MDB_RDONLY) || (parent->mt_flags & MDB_TXN_RDONLY) ||
1890 (env->me_flags & MDB_WRITEMAP))
1894 tsize = sizeof(MDB_ntxn);
1896 size = tsize + env->me_maxdbs * (sizeof(MDB_db)+1);
1897 if (!(flags & MDB_RDONLY))
1898 size += env->me_maxdbs * sizeof(MDB_cursor *);
1900 if ((txn = calloc(1, size)) == NULL) {
1901 DPRINTF("calloc: %s", strerror(ErrCode()));
1904 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
1905 if (flags & MDB_RDONLY) {
1906 txn->mt_flags |= MDB_TXN_RDONLY;
1907 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
1909 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
1910 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
1915 txn->mt_free_pgs = mdb_midl_alloc();
1916 if (!txn->mt_free_pgs) {
1920 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
1921 if (!txn->mt_u.dirty_list) {
1922 free(txn->mt_free_pgs);
1926 txn->mt_txnid = parent->mt_txnid;
1927 txn->mt_toggle = parent->mt_toggle;
1928 txn->mt_dirty_room = parent->mt_dirty_room;
1929 txn->mt_u.dirty_list[0].mid = 0;
1930 txn->mt_free_pgs[0] = 0;
1931 txn->mt_next_pgno = parent->mt_next_pgno;
1932 parent->mt_child = txn;
1933 txn->mt_parent = parent;
1934 txn->mt_numdbs = parent->mt_numdbs;
1935 txn->mt_dbxs = parent->mt_dbxs;
1936 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
1937 memcpy(txn->mt_dbflags, parent->mt_dbflags, txn->mt_numdbs);
1939 ntxn = (MDB_ntxn *)txn;
1940 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
1941 if (env->me_pghead) {
1942 size = MDB_IDL_SIZEOF(env->me_pghead);
1943 env->me_pghead = malloc(size);
1945 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
1949 env->me_pgfree = env->me_pghead;
1951 rc = mdb_cursor_shadow(parent, txn);
1953 mdb_txn_reset0(txn);
1955 rc = mdb_txn_renew0(txn);
1961 DPRINTF("begin txn %zu%c %p on mdbenv %p, root page %zu",
1962 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1963 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
1969 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
1970 * @param[in] txn the transaction handle to reset
1973 mdb_txn_reset0(MDB_txn *txn)
1975 MDB_env *env = txn->mt_env;
1977 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1978 if (!(env->me_flags & MDB_ROFS))
1979 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
1984 /* close(free) all cursors */
1985 for (i=0; i<txn->mt_numdbs; i++) {
1986 if (txn->mt_cursors[i]) {
1988 while ((mc = txn->mt_cursors[i])) {
1989 txn->mt_cursors[i] = mc->mc_next;
1990 if (mc->mc_flags & C_ALLOCD)
1996 if (!(env->me_flags & MDB_WRITEMAP)) {
1997 /* return all dirty pages to dpage list */
1998 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1999 dp = txn->mt_u.dirty_list[i].mptr;
2000 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
2001 mdb_page_free(txn->mt_env, dp);
2003 /* large pages just get freed directly */
2004 VGMEMP_FREE(txn->mt_env, dp);
2010 free(env->me_pgfree);
2012 if (txn->mt_parent) {
2013 txn->mt_parent->mt_child = NULL;
2014 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2015 mdb_midl_free(txn->mt_free_pgs);
2016 free(txn->mt_u.dirty_list);
2019 if (mdb_midl_shrink(&txn->mt_free_pgs))
2020 env->me_free_pgs = txn->mt_free_pgs;
2023 txn->mt_env->me_pghead = txn->mt_env->me_pgfree = NULL;
2024 txn->mt_env->me_pglast = 0;
2027 /* The writer mutex was locked in mdb_txn_begin. */
2028 UNLOCK_MUTEX_W(env);
2033 mdb_txn_reset(MDB_txn *txn)
2038 DPRINTF("reset txn %zu%c %p on mdbenv %p, root page %zu",
2039 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2040 (void *) txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
2042 mdb_txn_reset0(txn);
2046 mdb_txn_abort(MDB_txn *txn)
2051 DPRINTF("abort txn %zu%c %p on mdbenv %p, root page %zu",
2052 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2053 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
2056 mdb_txn_abort(txn->mt_child);
2058 mdb_txn_reset0(txn);
2063 mdb_txn_commit(MDB_txn *txn)
2071 pgno_t next, freecnt;
2072 txnid_t oldpg_txnid, id;
2075 assert(txn != NULL);
2076 assert(txn->mt_env != NULL);
2078 if (txn->mt_child) {
2079 mdb_txn_commit(txn->mt_child);
2080 txn->mt_child = NULL;
2085 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2086 if (txn->mt_numdbs > env->me_numdbs) {
2087 /* update the DB flags */
2089 for (i = env->me_numdbs; i<txn->mt_numdbs; i++)
2090 env->me_dbflags[i] = txn->mt_dbs[i].md_flags;
2097 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
2098 DPUTS("error flag is set, can't commit");
2100 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
2105 if (txn->mt_parent) {
2106 MDB_txn *parent = txn->mt_parent;
2110 /* Append our free list to parent's */
2111 if (mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs)) {
2115 mdb_midl_free(txn->mt_free_pgs);
2117 parent->mt_next_pgno = txn->mt_next_pgno;
2118 parent->mt_flags = txn->mt_flags;
2120 /* Merge (and close) our cursors with parent's */
2121 mdb_cursor_merge(txn);
2123 /* Update parent's DB table. */
2124 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2125 memcpy(parent->mt_dbflags, txn->mt_dbflags, txn->mt_numdbs);
2126 txn->mt_parent->mt_numdbs = txn->mt_numdbs;
2128 dst = txn->mt_parent->mt_u.dirty_list;
2129 src = txn->mt_u.dirty_list;
2130 /* Find len = length of merging our dirty list with parent's */
2132 dst[0].mid = 0; /* simplify loops */
2133 if (parent->mt_parent) {
2134 len = x + src[0].mid;
2135 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
2136 for (i = x; y && i; y--) {
2137 pgno_t yp = src[y].mid;
2138 while (yp < dst[i].mid)
2140 if (yp == dst[i].mid) {
2145 } else { /* Simplify the above for single-ancestor case */
2146 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
2148 /* Merge our dirty list with parent's */
2150 for (i = len; y; dst[i--] = src[y--]) {
2151 pgno_t yp = src[y].mid;
2152 while (yp < dst[x].mid)
2153 dst[i--] = dst[x--];
2154 if (yp == dst[x].mid)
2155 free(dst[x--].mptr);
2159 free(txn->mt_u.dirty_list);
2160 parent->mt_dirty_room = txn->mt_dirty_room;
2162 txn->mt_parent->mt_child = NULL;
2163 free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pgfree);
2168 if (txn != env->me_txn) {
2169 DPUTS("attempt to commit unknown transaction");
2174 if (!txn->mt_u.dirty_list[0].mid && !(txn->mt_flags & MDB_TXN_DIRTY))
2177 DPRINTF("committing txn %zu %p on mdbenv %p, root page %zu",
2178 txn->mt_txnid, (void *)txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
2180 /* Update DB root pointers */
2181 if (txn->mt_numdbs > 2) {
2184 data.mv_size = sizeof(MDB_db);
2186 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
2187 for (i = 2; i < txn->mt_numdbs; i++) {
2188 if (txn->mt_dbflags[i] & DB_DIRTY) {
2189 data.mv_data = &txn->mt_dbs[i];
2190 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
2197 /* Save the freelist as of this transaction to the freeDB. This
2198 * can change the freelist, so keep trying until it stabilizes.
2200 * env->me_pglast and the length of txn->mt_free_pgs cannot decrease,
2201 * except the code below can decrease env->me_pglast to split pghead.
2202 * Page numbers cannot disappear from txn->mt_free_pgs. New pages
2203 * can only appear in env->me_pghead when env->me_pglast increases.
2204 * Until then, the me_pghead pointer won't move but can become NULL.
2207 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
2208 oldpg_txnid = id = 0;
2211 /* should only be one record now */
2212 if (env->me_pghead || env->me_pglast) {
2213 /* make sure first page of freeDB is touched and on freelist */
2214 rc = mdb_page_search(&mc, NULL, MDB_PS_MODIFY);
2215 if (rc && rc != MDB_NOTFOUND) {
2222 /* Delete IDLs we used from the free list */
2223 if (env->me_pglast) {
2228 rc = mdb_cursor_first(&mc, &key, NULL);
2231 oldpg_txnid = *(txnid_t *)key.mv_data;
2233 assert(oldpg_txnid <= env->me_pglast);
2235 rc = mdb_cursor_del(&mc, 0);
2238 } while (oldpg_txnid < env->me_pglast);
2241 /* Save IDL of pages freed by this txn, to freeDB */
2243 if (freecnt != txn->mt_free_pgs[0]) {
2246 /* make sure last page of freeDB is touched and on freelist */
2247 key.mv_size = MDB_MAXKEYSIZE+1;
2249 rc = mdb_page_search(&mc, &key, MDB_PS_MODIFY);
2250 if (rc && rc != MDB_NOTFOUND)
2256 MDB_IDL idl = txn->mt_free_pgs;
2257 mdb_midl_sort(txn->mt_free_pgs);
2258 DPRINTF("IDL write txn %zu root %zu num %zu",
2259 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
2260 for (i=1; i<=idl[0]; i++) {
2261 DPRINTF("IDL %zu", idl[i]);
2265 /* write to last page of freeDB */
2266 key.mv_size = sizeof(pgno_t);
2267 key.mv_data = &txn->mt_txnid;
2268 /* The free list can still grow during this call,
2269 * despite the pre-emptive touches above. So retry
2270 * until the reserved space remains big enough.
2273 assert(freecnt < txn->mt_free_pgs[0]);
2274 freecnt = txn->mt_free_pgs[0];
2275 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
2276 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2279 } while (freecnt != txn->mt_free_pgs[0]);
2280 mdb_midl_sort(txn->mt_free_pgs);
2281 memcpy(data.mv_data, txn->mt_free_pgs, data.mv_size);
2282 if (oldpg_txnid < env->me_pglast || (!env->me_pghead && id))
2283 goto free_pgfirst; /* used up freeDB[oldpg_txnid] */
2286 /* Put back page numbers we took from freeDB but did not use */
2287 if (env->me_pghead) {
2292 mop = env->me_pghead;
2293 id = env->me_pglast;
2294 key.mv_size = sizeof(id);
2296 /* These steps may grow the freelist again
2297 * due to freed overflow pages...
2302 if (orig > env->me_maxfree_1pg && id > 4)
2303 orig = env->me_maxfree_1pg; /* Do not use more than 1 page */
2304 data.mv_size = (orig + 1) * sizeof(pgno_t);
2305 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2308 assert(!env->me_pghead || env->me_pglast);
2309 /* mop could have been used again here */
2310 if (id != env->me_pglast || env->me_pghead == NULL)
2311 goto again; /* was completely used up */
2312 assert(mop == env->me_pghead);
2313 } while (mop[0] < orig && --i);
2314 memcpy(data.mv_data, mop, data.mv_size);
2317 *(pgno_t *)data.mv_data = orig;
2318 mop[orig] = mop[0] - orig;
2319 env->me_pghead = mop += orig;
2320 /* Save more oldpages at the previous txnid. */
2321 assert(env->me_pglast == id && id == oldpg_txnid);
2322 env->me_pglast = --oldpg_txnid;
2326 /* Check for growth of freelist again */
2327 if (freecnt != txn->mt_free_pgs[0])
2330 free(env->me_pgfree);
2331 env->me_pghead = env->me_pgfree = NULL;
2333 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
2334 if (mdb_midl_shrink(&txn->mt_free_pgs))
2335 env->me_free_pgs = txn->mt_free_pgs;
2342 if (env->me_flags & MDB_WRITEMAP) {
2343 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
2344 dp = txn->mt_u.dirty_list[i].mptr;
2345 /* clear dirty flag */
2346 dp->mp_flags &= ~P_DIRTY;
2347 txn->mt_u.dirty_list[i].mid = 0;
2349 txn->mt_u.dirty_list[0].mid = 0;
2353 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
2359 /* Windows actually supports scatter/gather I/O, but only on
2360 * unbuffered file handles. Since we're relying on the OS page
2361 * cache for all our data, that's self-defeating. So we just
2362 * write pages one at a time. We use the ov structure to set
2363 * the write offset, to at least save the overhead of a Seek
2367 memset(&ov, 0, sizeof(ov));
2368 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
2370 dp = txn->mt_u.dirty_list[i].mptr;
2371 DPRINTF("committing page %zu", dp->mp_pgno);
2372 size = dp->mp_pgno * env->me_psize;
2373 ov.Offset = size & 0xffffffff;
2374 ov.OffsetHigh = size >> 16;
2375 ov.OffsetHigh >>= 16;
2376 /* clear dirty flag */
2377 dp->mp_flags &= ~P_DIRTY;
2378 wsize = env->me_psize;
2379 if (IS_OVERFLOW(dp)) wsize *= dp->mp_pages;
2380 rc = WriteFile(env->me_fd, dp, wsize, NULL, &ov);
2383 DPRINTF("WriteFile: %d", n);
2390 struct iovec iov[MDB_COMMIT_PAGES];
2394 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
2395 dp = txn->mt_u.dirty_list[i].mptr;
2396 if (dp->mp_pgno != next) {
2398 rc = writev(env->me_fd, iov, n);
2402 DPUTS("short write, filesystem full?");
2404 DPRINTF("writev: %s", strerror(n));
2411 lseek(env->me_fd, dp->mp_pgno * env->me_psize, SEEK_SET);
2414 DPRINTF("committing page %zu", dp->mp_pgno);
2415 iov[n].iov_len = env->me_psize;
2416 if (IS_OVERFLOW(dp)) iov[n].iov_len *= dp->mp_pages;
2417 iov[n].iov_base = (char *)dp;
2418 size += iov[n].iov_len;
2419 next = dp->mp_pgno + (IS_OVERFLOW(dp) ? dp->mp_pages : 1);
2420 /* clear dirty flag */
2421 dp->mp_flags &= ~P_DIRTY;
2422 if (++n >= MDB_COMMIT_PAGES) {
2432 rc = writev(env->me_fd, iov, n);
2436 DPUTS("short write, filesystem full?");
2438 DPRINTF("writev: %s", strerror(n));
2445 /* Drop the dirty pages.
2447 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
2448 dp = txn->mt_u.dirty_list[i].mptr;
2449 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
2450 mdb_page_free(txn->mt_env, dp);
2452 VGMEMP_FREE(txn->mt_env, dp);
2455 txn->mt_u.dirty_list[i].mid = 0;
2457 txn->mt_u.dirty_list[0].mid = 0;
2460 if ((n = mdb_env_sync(env, 0)) != 0 ||
2461 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
2469 if (txn->mt_numdbs > env->me_numdbs) {
2470 /* update the DB flags */
2472 for (i = env->me_numdbs; i<txn->mt_numdbs; i++)
2473 env->me_dbflags[i] = txn->mt_dbs[i].md_flags;
2477 UNLOCK_MUTEX_W(env);
2483 /** Read the environment parameters of a DB environment before
2484 * mapping it into memory.
2485 * @param[in] env the environment handle
2486 * @param[out] meta address of where to store the meta information
2487 * @return 0 on success, non-zero on failure.
2490 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
2497 /* We don't know the page size yet, so use a minimum value.
2498 * Read both meta pages so we can use the latest one.
2501 for (i=0; i<2; i++) {
2503 if (!ReadFile(env->me_fd, &pbuf, MDB_PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
2505 if ((rc = read(env->me_fd, &pbuf, MDB_PAGESIZE)) == 0)
2510 else if (rc != MDB_PAGESIZE) {
2514 DPRINTF("read: %s", strerror(err));
2518 p = (MDB_page *)&pbuf;
2520 if (!F_ISSET(p->mp_flags, P_META)) {
2521 DPRINTF("page %zu not a meta page", p->mp_pgno);
2526 if (m->mm_magic != MDB_MAGIC) {
2527 DPUTS("meta has invalid magic");
2531 if (m->mm_version != MDB_VERSION) {
2532 DPRINTF("database is version %u, expected version %u",
2533 m->mm_version, MDB_VERSION);
2534 return MDB_VERSION_MISMATCH;
2538 if (m->mm_txnid > meta->mm_txnid)
2539 memcpy(meta, m, sizeof(*m));
2541 memcpy(meta, m, sizeof(*m));
2543 if (SetFilePointer(env->me_fd, meta->mm_psize, NULL, FILE_BEGIN) != meta->mm_psize)
2545 if (lseek(env->me_fd, meta->mm_psize, SEEK_SET) != meta->mm_psize)
2553 /** Write the environment parameters of a freshly created DB environment.
2554 * @param[in] env the environment handle
2555 * @param[out] meta address of where to store the meta information
2556 * @return 0 on success, non-zero on failure.
2559 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
2566 DPUTS("writing new meta page");
2568 GET_PAGESIZE(psize);
2570 meta->mm_magic = MDB_MAGIC;
2571 meta->mm_version = MDB_VERSION;
2572 meta->mm_mapsize = env->me_mapsize;
2573 meta->mm_psize = psize;
2574 meta->mm_last_pg = 1;
2575 meta->mm_flags = env->me_flags & 0xffff;
2576 meta->mm_flags |= MDB_INTEGERKEY;
2577 meta->mm_dbs[0].md_root = P_INVALID;
2578 meta->mm_dbs[1].md_root = P_INVALID;
2580 p = calloc(2, psize);
2582 p->mp_flags = P_META;
2585 memcpy(m, meta, sizeof(*meta));
2587 q = (MDB_page *)((char *)p + psize);
2590 q->mp_flags = P_META;
2593 memcpy(m, meta, sizeof(*meta));
2598 SetFilePointer(env->me_fd, 0, NULL, FILE_BEGIN);
2599 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
2600 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
2603 lseek(env->me_fd, 0, SEEK_SET);
2604 rc = write(env->me_fd, p, psize * 2);
2605 rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
2611 /** Update the environment info to commit a transaction.
2612 * @param[in] txn the transaction that's being committed
2613 * @return 0 on success, non-zero on failure.
2616 mdb_env_write_meta(MDB_txn *txn)
2619 MDB_meta meta, metab, *mp;
2621 int rc, len, toggle;
2628 assert(txn != NULL);
2629 assert(txn->mt_env != NULL);
2631 toggle = !txn->mt_toggle;
2632 DPRINTF("writing meta page %d for root page %zu",
2633 toggle, txn->mt_dbs[MAIN_DBI].md_root);
2636 mp = env->me_metas[toggle];
2638 if (env->me_flags & MDB_WRITEMAP) {
2639 /* Persist any increases of mapsize config */
2640 if (env->me_mapsize > mp->mm_mapsize)
2641 mp->mm_mapsize = env->me_mapsize;
2642 mp->mm_dbs[0] = txn->mt_dbs[0];
2643 mp->mm_dbs[1] = txn->mt_dbs[1];
2644 mp->mm_last_pg = txn->mt_next_pgno - 1;
2645 mp->mm_txnid = txn->mt_txnid;
2646 if (!(env->me_flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
2647 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
2650 ptr += env->me_psize;
2651 if (MDB_MSYNC(ptr, env->me_psize, rc)) {
2658 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
2659 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
2661 ptr = (char *)&meta;
2662 if (env->me_mapsize > mp->mm_mapsize) {
2663 /* Persist any increases of mapsize config */
2664 meta.mm_mapsize = env->me_mapsize;
2665 off = offsetof(MDB_meta, mm_mapsize);
2667 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
2669 len = sizeof(MDB_meta) - off;
2672 meta.mm_dbs[0] = txn->mt_dbs[0];
2673 meta.mm_dbs[1] = txn->mt_dbs[1];
2674 meta.mm_last_pg = txn->mt_next_pgno - 1;
2675 meta.mm_txnid = txn->mt_txnid;
2678 off += env->me_psize;
2681 /* Write to the SYNC fd */
2682 mfd = env->me_flags & (MDB_NOSYNC|MDB_NOMETASYNC) ?
2683 env->me_fd : env->me_mfd;
2686 memset(&ov, 0, sizeof(ov));
2688 WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov);
2691 rc = pwrite(mfd, ptr, len, off);
2696 DPUTS("write failed, disk error?");
2697 /* On a failure, the pagecache still contains the new data.
2698 * Write some old data back, to prevent it from being used.
2699 * Use the non-SYNC fd; we know it will fail anyway.
2701 meta.mm_last_pg = metab.mm_last_pg;
2702 meta.mm_txnid = metab.mm_txnid;
2704 WriteFile(env->me_fd, ptr, len, NULL, &ov);
2706 r2 = pwrite(env->me_fd, ptr, len, off);
2709 env->me_flags |= MDB_FATAL_ERROR;
2713 /* Memory ordering issues are irrelevant; since the entire writer
2714 * is wrapped by wmutex, all of these changes will become visible
2715 * after the wmutex is unlocked. Since the DB is multi-version,
2716 * readers will get consistent data regardless of how fresh or
2717 * how stale their view of these values is.
2719 txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
2724 /** Check both meta pages to see which one is newer.
2725 * @param[in] env the environment handle
2726 * @return meta toggle (0 or 1).
2729 mdb_env_pick_meta(const MDB_env *env)
2731 return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
2735 mdb_env_create(MDB_env **env)
2739 e = calloc(1, sizeof(MDB_env));
2743 e->me_free_pgs = mdb_midl_alloc();
2744 if (!e->me_free_pgs) {
2748 e->me_maxreaders = DEFAULT_READERS;
2750 e->me_fd = INVALID_HANDLE_VALUE;
2751 e->me_lfd = INVALID_HANDLE_VALUE;
2752 e->me_mfd = INVALID_HANDLE_VALUE;
2753 #ifdef MDB_USE_POSIX_SEM
2754 e->me_rmutex = SEM_FAILED;
2755 e->me_wmutex = SEM_FAILED;
2757 e->me_pid = getpid();
2758 VGMEMP_CREATE(e,0,0);
2764 mdb_env_set_mapsize(MDB_env *env, size_t size)
2768 env->me_mapsize = size;
2770 env->me_maxpg = env->me_mapsize / env->me_psize;
2775 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
2779 env->me_maxdbs = dbs + 2; /* Named databases + main and free DB */
2784 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
2786 if (env->me_map || readers < 1)
2788 env->me_maxreaders = readers;
2793 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
2795 if (!env || !readers)
2797 *readers = env->me_maxreaders;
2801 /** Further setup required for opening an MDB environment
2804 mdb_env_open2(MDB_env *env)
2806 unsigned int flags = env->me_flags;
2807 int i, newenv = 0, prot;
2811 memset(&meta, 0, sizeof(meta));
2813 if ((i = mdb_env_read_header(env, &meta)) != 0) {
2816 DPUTS("new mdbenv");
2820 /* Was a mapsize configured? */
2821 if (!env->me_mapsize) {
2822 /* If this is a new environment, take the default,
2823 * else use the size recorded in the existing env.
2825 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
2826 } else if (env->me_mapsize < meta.mm_mapsize) {
2827 /* If the configured size is smaller, make sure it's
2828 * still big enough. Silently round up to minimum if not.
2830 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
2831 if (env->me_mapsize < minsize)
2832 env->me_mapsize = minsize;
2838 LONG sizelo, sizehi;
2839 sizelo = env->me_mapsize & 0xffffffff;
2840 sizehi = env->me_mapsize >> 16; /* pointless on WIN32, only needed on W64 */
2842 /* Windows won't create mappings for zero length files.
2843 * Just allocate the maxsize right now.
2846 SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
2847 if (!SetEndOfFile(env->me_fd))
2849 SetFilePointer(env->me_fd, 0, NULL, 0);
2851 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
2852 PAGE_READWRITE : PAGE_READONLY,
2853 sizehi, sizelo, NULL);
2856 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
2857 FILE_MAP_WRITE : FILE_MAP_READ,
2858 0, 0, env->me_mapsize, meta.mm_address);
2866 if (flags & MDB_WRITEMAP) {
2868 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
2871 env->me_map = mmap(meta.mm_address, env->me_mapsize, prot, i,
2873 if (env->me_map == MAP_FAILED) {
2877 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
2879 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
2881 #ifdef POSIX_MADV_RANDOM
2882 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
2883 #endif /* POSIX_MADV_RANDOM */
2884 #endif /* MADV_RANDOM */
2888 if (flags & MDB_FIXEDMAP)
2889 meta.mm_address = env->me_map;
2890 i = mdb_env_init_meta(env, &meta);
2891 if (i != MDB_SUCCESS) {
2894 } else if (meta.mm_address && env->me_map != meta.mm_address) {
2895 /* Can happen because the address argument to mmap() is just a
2896 * hint. mmap() can pick another, e.g. if the range is in use.
2897 * The MAP_FIXED flag would prevent that, but then mmap could
2898 * instead unmap existing pages to make room for the new map.
2900 return EBUSY; /* TODO: Make a new MDB_* error code? */
2902 env->me_psize = meta.mm_psize;
2903 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
2904 env->me_nodemax = (env->me_psize - PAGEHDRSZ) / MDB_MINKEYS;
2906 env->me_maxpg = env->me_mapsize / env->me_psize;
2908 p = (MDB_page *)env->me_map;
2909 env->me_metas[0] = METADATA(p);
2910 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
2914 int toggle = mdb_env_pick_meta(env);
2915 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
2917 DPRINTF("opened database version %u, pagesize %u",
2918 env->me_metas[0]->mm_version, env->me_psize);
2919 DPRINTF("using meta page %d", toggle);
2920 DPRINTF("depth: %u", db->md_depth);
2921 DPRINTF("entries: %zu", db->md_entries);
2922 DPRINTF("branch pages: %zu", db->md_branch_pages);
2923 DPRINTF("leaf pages: %zu", db->md_leaf_pages);
2924 DPRINTF("overflow pages: %zu", db->md_overflow_pages);
2925 DPRINTF("root: %zu", db->md_root);
2933 /** Release a reader thread's slot in the reader lock table.
2934 * This function is called automatically when a thread exits.
2935 * @param[in] ptr This points to the slot in the reader lock table.
2938 mdb_env_reader_dest(void *ptr)
2940 MDB_reader *reader = ptr;
2946 /** Junk for arranging thread-specific callbacks on Windows. This is
2947 * necessarily platform and compiler-specific. Windows supports up
2948 * to 1088 keys. Let's assume nobody opens more than 64 environments
2949 * in a single process, for now. They can override this if needed.
2951 #ifndef MAX_TLS_KEYS
2952 #define MAX_TLS_KEYS 64
2954 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
2955 static int mdb_tls_nkeys;
2957 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
2961 case DLL_PROCESS_ATTACH: break;
2962 case DLL_THREAD_ATTACH: break;
2963 case DLL_THREAD_DETACH:
2964 for (i=0; i<mdb_tls_nkeys; i++) {
2965 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
2966 mdb_env_reader_dest(r);
2969 case DLL_PROCESS_DETACH: break;
2974 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
2976 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
2980 /* Force some symbol references.
2981 * _tls_used forces the linker to create the TLS directory if not already done
2982 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
2984 #pragma comment(linker, "/INCLUDE:_tls_used")
2985 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
2986 #pragma const_seg(".CRT$XLB")
2987 extern const PIMAGE_TLS_CALLBACK mdb_tls_callback;
2988 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
2991 #pragma comment(linker, "/INCLUDE:__tls_used")
2992 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
2993 #pragma data_seg(".CRT$XLB")
2994 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
2996 #endif /* WIN 32/64 */
2997 #endif /* !__GNUC__ */
3000 /** Downgrade the exclusive lock on the region back to shared */
3002 mdb_env_share_locks(MDB_env *env, int *excl)
3004 int rc = 0, toggle = mdb_env_pick_meta(env);
3006 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
3011 /* First acquire a shared lock. The Unlock will
3012 * then release the existing exclusive lock.
3014 memset(&ov, 0, sizeof(ov));
3015 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3018 UnlockFile(env->me_lfd, 0, 0, 1, 0);
3024 struct flock lock_info;
3025 /* The shared lock replaces the existing lock */
3026 memset((void *)&lock_info, 0, sizeof(lock_info));
3027 lock_info.l_type = F_RDLCK;
3028 lock_info.l_whence = SEEK_SET;
3029 lock_info.l_start = 0;
3030 lock_info.l_len = 1;
3031 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3032 (rc = ErrCode()) == EINTR) ;
3033 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
3040 /** Try to get exlusive lock, otherwise shared.
3041 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
3044 mdb_env_excl_lock(MDB_env *env, int *excl)
3048 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
3052 memset(&ov, 0, sizeof(ov));
3053 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3060 struct flock lock_info;
3061 memset((void *)&lock_info, 0, sizeof(lock_info));
3062 lock_info.l_type = F_WRLCK;
3063 lock_info.l_whence = SEEK_SET;
3064 lock_info.l_start = 0;
3065 lock_info.l_len = 1;
3066 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3067 (rc = ErrCode()) == EINTR) ;
3071 # ifdef MDB_USE_POSIX_SEM
3072 if (*excl < 0) /* always true when !MDB_USE_POSIX_SEM */
3075 lock_info.l_type = F_RDLCK;
3076 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
3077 (rc = ErrCode()) == EINTR) ;
3085 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
3087 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
3089 * @(#) $Revision: 5.1 $
3090 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
3091 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
3093 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
3097 * Please do not copyright this code. This code is in the public domain.
3099 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
3100 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
3101 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
3102 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
3103 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
3104 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
3105 * PERFORMANCE OF THIS SOFTWARE.
3108 * chongo <Landon Curt Noll> /\oo/\
3109 * http://www.isthe.com/chongo/
3111 * Share and Enjoy! :-)
3114 typedef unsigned long long mdb_hash_t;
3115 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
3117 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
3118 * @param[in] str string to hash
3119 * @param[in] hval initial value for hash
3120 * @return 64 bit hash
3122 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
3123 * hval arg on the first call.
3126 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
3128 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
3129 unsigned char *end = s + val->mv_size;
3131 * FNV-1a hash each octet of the string
3134 /* xor the bottom with the current octet */
3135 hval ^= (mdb_hash_t)*s++;
3137 /* multiply by the 64 bit FNV magic prime mod 2^64 */
3138 hval += (hval << 1) + (hval << 4) + (hval << 5) +
3139 (hval << 7) + (hval << 8) + (hval << 40);
3141 /* return our new hash value */
3145 /** Hash the string and output the hash in hex.
3146 * @param[in] str string to hash
3147 * @param[out] hexbuf an array of 17 chars to hold the hash
3150 mdb_hash_hex(MDB_val *val, char *hexbuf)
3153 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
3154 for (i=0; i<8; i++) {
3155 hexbuf += sprintf(hexbuf, "%02x", (unsigned int)h & 0xff);
3161 /** Open and/or initialize the lock region for the environment.
3162 * @param[in] env The MDB environment.
3163 * @param[in] lpath The pathname of the file used for the lock region.
3164 * @param[in] mode The Unix permissions for the file, if we create it.
3165 * @param[out] excl Resulting file lock type: -1 none, 0 shared, 1 exclusive
3166 * @return 0 on success, non-zero on failure.
3169 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
3177 if ((env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
3178 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
3179 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
3181 if (rc == ERROR_WRITE_PROTECT && (env->me_flags & MDB_RDONLY)) {
3182 env->me_flags |= MDB_ROFS;
3187 /* Try to get exclusive lock. If we succeed, then
3188 * nobody is using the lock region and we should initialize it.
3190 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
3191 size = GetFileSize(env->me_lfd, NULL);
3197 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
3199 if (rc == EROFS && (env->me_flags & MDB_RDONLY)) {
3200 env->me_flags |= MDB_ROFS;
3205 /* Lose record locks when exec*() */
3206 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
3207 fcntl(env->me_lfd, F_SETFD, fdflags);
3209 #else /* O_CLOEXEC on Linux: Open file and set FD_CLOEXEC atomically */
3210 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT|O_CLOEXEC, mode)) == -1) {
3212 if (rc == EROFS && (env->me_flags & MDB_RDONLY)) {
3213 env->me_flags |= MDB_ROFS;
3220 /* Try to get exclusive lock. If we succeed, then
3221 * nobody is using the lock region and we should initialize it.
3223 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
3225 size = lseek(env->me_lfd, 0, SEEK_END);
3227 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
3228 if (size < rsize && *excl > 0) {
3230 SetFilePointer(env->me_lfd, rsize, NULL, 0);
3231 if (!SetEndOfFile(env->me_lfd)) goto fail_errno;
3233 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
3237 size = rsize - sizeof(MDB_txninfo);
3238 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
3243 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
3245 if (!mh) goto fail_errno;
3246 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
3248 if (!env->me_txns) goto fail_errno;
3250 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
3252 if (m == MAP_FAILED) goto fail_errno;
3258 BY_HANDLE_FILE_INFORMATION stbuf;
3267 if (!mdb_sec_inited) {
3268 InitializeSecurityDescriptor(&mdb_null_sd,
3269 SECURITY_DESCRIPTOR_REVISION);
3270 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
3271 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
3272 mdb_all_sa.bInheritHandle = FALSE;
3273 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
3276 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
3277 idbuf.volume = stbuf.dwVolumeSerialNumber;
3278 idbuf.nhigh = stbuf.nFileIndexHigh;
3279 idbuf.nlow = stbuf.nFileIndexLow;
3280 val.mv_data = &idbuf;
3281 val.mv_size = sizeof(idbuf);
3282 mdb_hash_hex(&val, hexbuf);
3283 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", hexbuf);
3284 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", hexbuf);
3285 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
3286 if (!env->me_rmutex) goto fail_errno;
3287 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
3288 if (!env->me_wmutex) goto fail_errno;
3289 #elif defined(MDB_USE_POSIX_SEM)
3298 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
3299 idbuf.dev = stbuf.st_dev;
3300 idbuf.ino = stbuf.st_ino;
3301 val.mv_data = &idbuf;
3302 val.mv_size = sizeof(idbuf);
3303 mdb_hash_hex(&val, hexbuf);
3304 sprintf(env->me_txns->mti_rmname, "/MDBr%s", hexbuf);
3305 sprintf(env->me_txns->mti_wmname, "/MDBw%s", hexbuf);
3306 /* Clean up after a previous run, if needed: Try to
3307 * remove both semaphores before doing anything else.
3309 sem_unlink(env->me_txns->mti_rmname);
3310 sem_unlink(env->me_txns->mti_wmname);
3311 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
3312 O_CREAT|O_EXCL, mode, 1);
3313 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3314 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
3315 O_CREAT|O_EXCL, mode, 1);
3316 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3317 #else /* MDB_USE_POSIX_SEM */
3318 pthread_mutexattr_t mattr;
3320 if ((rc = pthread_mutexattr_init(&mattr))
3321 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
3322 || (rc = pthread_mutex_init(&env->me_txns->mti_mutex, &mattr))
3323 || (rc = pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr)))
3325 pthread_mutexattr_destroy(&mattr);
3326 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
3328 env->me_txns->mti_version = MDB_VERSION;
3329 env->me_txns->mti_magic = MDB_MAGIC;
3330 env->me_txns->mti_txnid = 0;
3331 env->me_txns->mti_numreaders = 0;
3334 if (env->me_txns->mti_magic != MDB_MAGIC) {
3335 DPUTS("lock region has invalid magic");
3339 if (env->me_txns->mti_version != MDB_VERSION) {
3340 DPRINTF("lock region is version %u, expected version %u",
3341 env->me_txns->mti_version, MDB_VERSION);
3342 rc = MDB_VERSION_MISMATCH;
3346 if (rc != EACCES && rc != EAGAIN) {
3350 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
3351 if (!env->me_rmutex) goto fail_errno;
3352 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
3353 if (!env->me_wmutex) goto fail_errno;
3354 #elif defined(MDB_USE_POSIX_SEM)
3355 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
3356 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3357 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
3358 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3369 /** The name of the lock file in the DB environment */
3370 #define LOCKNAME "/lock.mdb"
3371 /** The name of the data file in the DB environment */
3372 #define DATANAME "/data.mdb"
3373 /** The suffix of the lock file when no subdir is used */
3374 #define LOCKSUFF "-lock"
3375 /** Only a subset of the @ref mdb_env flags can be changed
3376 * at runtime. Changing other flags requires closing the
3377 * environment and re-opening it with the new flags.
3379 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC)
3380 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY|MDB_WRITEMAP)
3383 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
3385 int oflags, rc, len, excl;
3386 char *lpath, *dpath;
3388 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
3392 if (flags & MDB_NOSUBDIR) {
3393 rc = len + sizeof(LOCKSUFF) + len + 1;
3395 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
3400 if (flags & MDB_NOSUBDIR) {
3401 dpath = lpath + len + sizeof(LOCKSUFF);
3402 sprintf(lpath, "%s" LOCKSUFF, path);
3403 strcpy(dpath, path);
3405 dpath = lpath + len + sizeof(LOCKNAME);
3406 sprintf(lpath, "%s" LOCKNAME, path);
3407 sprintf(dpath, "%s" DATANAME, path);
3410 flags |= env->me_flags;
3411 /* silently ignore WRITEMAP if we're only getting read access */
3412 if (F_ISSET(flags, MDB_RDONLY|MDB_WRITEMAP))
3413 flags ^= MDB_WRITEMAP;
3414 env->me_flags = flags |= MDB_ENV_ACTIVE;
3416 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
3421 if (F_ISSET(flags, MDB_RDONLY)) {
3422 oflags = GENERIC_READ;
3423 len = OPEN_EXISTING;
3425 oflags = GENERIC_READ|GENERIC_WRITE;
3428 mode = FILE_ATTRIBUTE_NORMAL;
3429 env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
3430 NULL, len, mode, NULL);
3432 if (F_ISSET(flags, MDB_RDONLY))
3435 oflags = O_RDWR | O_CREAT;
3437 env->me_fd = open(dpath, oflags, mode);
3439 if (env->me_fd == INVALID_HANDLE_VALUE) {
3444 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
3445 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
3446 env->me_mfd = env->me_fd;
3448 /* Synchronous fd for meta writes. Needed even with
3449 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
3452 env->me_mfd = CreateFile(dpath, oflags,
3453 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
3454 mode | FILE_FLAG_WRITE_THROUGH, NULL);
3456 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
3458 if (env->me_mfd == INVALID_HANDLE_VALUE) {
3463 DPRINTF("opened dbenv %p", (void *) env);
3464 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
3467 env->me_numdbs = 2; /* this notes that me_txkey was set */
3469 /* Windows TLS callbacks need help finding their TLS info. */
3470 if (mdb_tls_nkeys < MAX_TLS_KEYS)
3471 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
3478 rc = mdb_env_share_locks(env, &excl);
3482 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
3483 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
3484 env->me_path = strdup(path);
3485 if (!env->me_dbxs || !env->me_dbflags || !env->me_path)
3491 mdb_env_close0(env, excl);
3497 /** Destroy resources from mdb_env_open() and clear our readers */
3499 mdb_env_close0(MDB_env *env, int excl)
3503 if (!(env->me_flags & MDB_ENV_ACTIVE))
3506 free(env->me_dbflags);
3510 if (env->me_numdbs) {
3511 pthread_key_delete(env->me_txkey);
3513 /* Delete our key from the global list */
3514 for (i=0; i<mdb_tls_nkeys; i++)
3515 if (mdb_tls_keys[i] == env->me_txkey) {
3516 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
3524 munmap(env->me_map, env->me_mapsize);
3526 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
3528 if (env->me_fd != INVALID_HANDLE_VALUE)
3531 pid_t pid = env->me_pid;
3532 /* Clearing readers is done in this function because
3533 * me_txkey with its destructor must be disabled first.
3535 for (i = env->me_numreaders; --i >= 0; )
3536 if (env->me_txns->mti_readers[i].mr_pid == pid)
3537 env->me_txns->mti_readers[i].mr_pid = 0;
3539 if (env->me_rmutex) {
3540 CloseHandle(env->me_rmutex);
3541 if (env->me_wmutex) CloseHandle(env->me_wmutex);
3543 /* Windows automatically destroys the mutexes when
3544 * the last handle closes.
3546 #elif defined(MDB_USE_POSIX_SEM)
3547 if (env->me_rmutex != SEM_FAILED) {
3548 sem_close(env->me_rmutex);
3549 if (env->me_wmutex != SEM_FAILED)
3550 sem_close(env->me_wmutex);
3551 /* If we have the filelock: If we are the
3552 * only remaining user, clean up semaphores.
3555 mdb_env_excl_lock(env, &excl);
3557 sem_unlink(env->me_txns->mti_rmname);
3558 sem_unlink(env->me_txns->mti_wmname);
3562 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
3564 if (env->me_lfd != INVALID_HANDLE_VALUE) {
3567 /* Unlock the lockfile. Windows would have unlocked it
3568 * after closing anyway, but not necessarily at once.
3570 UnlockFile(env->me_lfd, 0, 0, 1, 0);
3576 env->me_flags &= ~MDB_ENV_ACTIVE;
3580 mdb_env_copy(MDB_env *env, const char *path)
3582 MDB_txn *txn = NULL;
3586 HANDLE newfd = INVALID_HANDLE_VALUE;
3588 if (env->me_flags & MDB_NOSUBDIR) {
3589 lpath = (char *)path;
3592 len += sizeof(DATANAME);
3593 lpath = malloc(len);
3596 sprintf(lpath, "%s" DATANAME, path);
3599 /* The destination path must exist, but the destination file must not.
3600 * We don't want the OS to cache the writes, since the source data is
3601 * already in the OS cache.
3604 newfd = CreateFile(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
3605 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
3607 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL
3613 if (!(env->me_flags & MDB_NOSUBDIR))
3615 if (newfd == INVALID_HANDLE_VALUE) {
3620 #ifdef F_NOCACHE /* __APPLE__ */
3621 rc = fcntl(newfd, F_NOCACHE, 1);
3628 /* Do the lock/unlock of the reader mutex before starting the
3629 * write txn. Otherwise other read txns could block writers.
3631 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
3635 if (!(env->me_flags & MDB_ROFS)) {
3636 /* We must start the actual read txn after blocking writers */
3637 mdb_txn_reset0(txn);
3639 /* Temporarily block writers until we snapshot the meta pages */
3642 rc = mdb_txn_renew0(txn);
3644 UNLOCK_MUTEX_W(env);
3649 wsize = env->me_psize * 2;
3653 rc = WriteFile(newfd, env->me_map, wsize, &len, NULL);
3654 rc = (len == wsize) ? MDB_SUCCESS : ErrCode();
3657 rc = write(newfd, env->me_map, wsize);
3658 rc = (rc == (int)wsize) ? MDB_SUCCESS : ErrCode();
3660 if (! (env->me_flags & MDB_ROFS))
3661 UNLOCK_MUTEX_W(env);
3666 ptr = env->me_map + wsize;
3667 wsize = txn->mt_next_pgno * env->me_psize - wsize;
3668 #define MAX_WRITE 2147483648U
3672 if (wsize > MAX_WRITE)
3676 rc = WriteFile(newfd, ptr, w2, &len, NULL);
3677 rc = (len == w2) ? MDB_SUCCESS : ErrCode();
3686 if (wsize > MAX_WRITE)
3690 wres = write(newfd, ptr, w2);
3691 rc = (wres > 0) ? MDB_SUCCESS : ErrCode();
3700 if (newfd != INVALID_HANDLE_VALUE)
3707 mdb_env_close(MDB_env *env)
3714 VGMEMP_DESTROY(env);
3715 while ((dp = env->me_dpages) != NULL) {
3716 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
3717 env->me_dpages = dp->mp_next;
3721 mdb_env_close0(env, 0);
3722 mdb_midl_free(env->me_free_pgs);
3726 /** Compare two items pointing at aligned size_t's */
3728 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
3730 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
3731 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
3734 /** Compare two items pointing at aligned int's */
3736 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
3738 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
3739 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
3742 /** Compare two items pointing at ints of unknown alignment.
3743 * Nodes and keys are guaranteed to be 2-byte aligned.
3746 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
3748 #if BYTE_ORDER == LITTLE_ENDIAN
3749 unsigned short *u, *c;
3752 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
3753 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
3756 } while(!x && u > (unsigned short *)a->mv_data);
3759 return memcmp(a->mv_data, b->mv_data, a->mv_size);
3763 /** Compare two items lexically */
3765 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
3772 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
3778 diff = memcmp(a->mv_data, b->mv_data, len);
3779 return diff ? diff : len_diff<0 ? -1 : len_diff;
3782 /** Compare two items in reverse byte order */
3784 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
3786 const unsigned char *p1, *p2, *p1_lim;
3790 p1_lim = (const unsigned char *)a->mv_data;
3791 p1 = (const unsigned char *)a->mv_data + a->mv_size;
3792 p2 = (const unsigned char *)b->mv_data + b->mv_size;
3794 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
3800 while (p1 > p1_lim) {
3801 diff = *--p1 - *--p2;
3805 return len_diff<0 ? -1 : len_diff;
3808 /** Search for key within a page, using binary search.
3809 * Returns the smallest entry larger or equal to the key.
3810 * If exactp is non-null, stores whether the found entry was an exact match
3811 * in *exactp (1 or 0).
3812 * Updates the cursor index with the index of the found entry.
3813 * If no entry larger or equal to the key is found, returns NULL.
3816 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
3818 unsigned int i = 0, nkeys;
3821 MDB_page *mp = mc->mc_pg[mc->mc_top];
3822 MDB_node *node = NULL;
3827 nkeys = NUMKEYS(mp);
3832 COPY_PGNO(pgno, mp->mp_pgno);
3833 DPRINTF("searching %u keys in %s %spage %zu",
3834 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
3841 low = IS_LEAF(mp) ? 0 : 1;
3843 cmp = mc->mc_dbx->md_cmp;
3845 /* Branch pages have no data, so if using integer keys,
3846 * alignment is guaranteed. Use faster mdb_cmp_int.
3848 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
3849 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
3856 nodekey.mv_size = mc->mc_db->md_pad;
3857 node = NODEPTR(mp, 0); /* fake */
3858 while (low <= high) {
3859 i = (low + high) >> 1;
3860 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
3861 rc = cmp(key, &nodekey);
3862 DPRINTF("found leaf index %u [%s], rc = %i",
3863 i, DKEY(&nodekey), rc);
3872 while (low <= high) {
3873 i = (low + high) >> 1;
3875 node = NODEPTR(mp, i);
3876 nodekey.mv_size = NODEKSZ(node);
3877 nodekey.mv_data = NODEKEY(node);
3879 rc = cmp(key, &nodekey);
3882 DPRINTF("found leaf index %u [%s], rc = %i",
3883 i, DKEY(&nodekey), rc);
3885 DPRINTF("found branch index %u [%s -> %zu], rc = %i",
3886 i, DKEY(&nodekey), NODEPGNO(node), rc);
3897 if (rc > 0) { /* Found entry is less than the key. */
3898 i++; /* Skip to get the smallest entry larger than key. */
3900 node = NODEPTR(mp, i);
3903 *exactp = (rc == 0);
3904 /* store the key index */
3905 mc->mc_ki[mc->mc_top] = i;
3907 /* There is no entry larger or equal to the key. */
3910 /* nodeptr is fake for LEAF2 */
3916 mdb_cursor_adjust(MDB_cursor *mc, func)
3920 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
3921 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
3928 /** Pop a page off the top of the cursor's stack. */
3930 mdb_cursor_pop(MDB_cursor *mc)
3933 #ifndef MDB_DEBUG_SKIP
3934 MDB_page *top = mc->mc_pg[mc->mc_top];
3940 DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
3941 mc->mc_dbi, (void *) mc);
3945 /** Push a page onto the top of the cursor's stack. */
3947 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
3949 DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
3950 mc->mc_dbi, (void *) mc);
3952 if (mc->mc_snum >= CURSOR_STACK) {
3953 assert(mc->mc_snum < CURSOR_STACK);
3954 return MDB_CURSOR_FULL;
3957 mc->mc_top = mc->mc_snum++;
3958 mc->mc_pg[mc->mc_top] = mp;
3959 mc->mc_ki[mc->mc_top] = 0;
3964 /** Find the address of the page corresponding to a given page number.
3965 * @param[in] txn the transaction for this access.
3966 * @param[in] pgno the page number for the page to retrieve.
3967 * @param[out] ret address of a pointer where the page's address will be stored.
3968 * @return 0 on success, non-zero on failure.
3971 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
3975 if (!((txn->mt_flags & MDB_TXN_RDONLY) |
3976 (txn->mt_env->me_flags & MDB_WRITEMAP)))
3980 MDB_ID2L dl = tx2->mt_u.dirty_list;
3982 unsigned x = mdb_mid2l_search(dl, pgno);
3983 if (x <= dl[0].mid && dl[x].mid == pgno) {
3988 } while ((tx2 = tx2->mt_parent) != NULL);
3991 if (pgno < txn->mt_next_pgno) {
3992 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
3994 DPRINTF("page %zu not found", pgno);
4000 return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
4003 /** Search for the page a given key should be in.
4004 * Pushes parent pages on the cursor stack. This function continues a
4005 * search on a cursor that has already been initialized. (Usually by
4006 * #mdb_page_search() but also by #mdb_node_move().)
4007 * @param[in,out] mc the cursor for this operation.
4008 * @param[in] key the key to search for. If NULL, search for the lowest
4009 * page. (This is used by #mdb_cursor_first().)
4010 * @param[in] flags If MDB_PS_MODIFY set, visited pages are updated with new page numbers.
4011 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
4012 * @return 0 on success, non-zero on failure.
4015 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
4017 MDB_page *mp = mc->mc_pg[mc->mc_top];
4022 while (IS_BRANCH(mp)) {
4026 DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
4027 assert(NUMKEYS(mp) > 1);
4028 DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
4030 if (key == NULL) /* Initialize cursor to first page. */
4032 else if (key->mv_size > MDB_MAXKEYSIZE && key->mv_data == NULL) {
4033 /* cursor to last page */
4037 node = mdb_node_search(mc, key, &exact);
4039 i = NUMKEYS(mp) - 1;
4041 i = mc->mc_ki[mc->mc_top];
4050 DPRINTF("following index %u for key [%s]",
4052 assert(i < NUMKEYS(mp));
4053 node = NODEPTR(mp, i);
4055 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp)))
4058 mc->mc_ki[mc->mc_top] = i;
4059 if ((rc = mdb_cursor_push(mc, mp)))
4063 if ((rc = mdb_page_touch(mc)) != 0)
4065 mp = mc->mc_pg[mc->mc_top];
4070 DPRINTF("internal error, index points to a %02X page!?",
4072 return MDB_CORRUPTED;
4075 DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
4076 key ? DKEY(key) : NULL);
4081 /** Search for the page a given key should be in.
4082 * Pushes parent pages on the cursor stack. This function just sets up
4083 * the search; it finds the root page for \b mc's database and sets this
4084 * as the root of the cursor's stack. Then #mdb_page_search_root() is
4085 * called to complete the search.
4086 * @param[in,out] mc the cursor for this operation.
4087 * @param[in] key the key to search for. If NULL, search for the lowest
4088 * page. (This is used by #mdb_cursor_first().)
4089 * @param[in] modify If true, visited pages are updated with new page numbers.
4090 * @return 0 on success, non-zero on failure.
4093 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
4098 /* Make sure the txn is still viable, then find the root from
4099 * the txn's db table.
4101 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
4102 DPUTS("transaction has failed, must abort");
4105 /* Make sure we're using an up-to-date root */
4106 if (mc->mc_dbi > MAIN_DBI) {
4107 if ((*mc->mc_dbflag & DB_STALE) ||
4108 ((flags & MDB_PS_MODIFY) && !(*mc->mc_dbflag & DB_DIRTY))) {
4110 unsigned char dbflag = 0;
4111 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
4112 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, flags & MDB_PS_MODIFY);
4115 if (*mc->mc_dbflag & DB_STALE) {
4119 MDB_node *leaf = mdb_node_search(&mc2,
4120 &mc->mc_dbx->md_name, &exact);
4122 return MDB_NOTFOUND;
4123 mdb_node_read(mc->mc_txn, leaf, &data);
4124 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
4126 /* The txn may not know this DBI, or another process may
4127 * have dropped and recreated the DB with other flags.
4129 if (mc->mc_db->md_flags != flags)
4130 return MDB_INCOMPATIBLE;
4131 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
4133 if (flags & MDB_PS_MODIFY)
4135 *mc->mc_dbflag = dbflag;
4138 root = mc->mc_db->md_root;
4140 if (root == P_INVALID) { /* Tree is empty. */
4141 DPUTS("tree is empty");
4142 return MDB_NOTFOUND;
4147 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
4148 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0])))
4154 DPRINTF("db %u root page %zu has flags 0x%X",
4155 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
4157 if (flags & MDB_PS_MODIFY) {
4158 if ((rc = mdb_page_touch(mc)))
4162 if (flags & MDB_PS_ROOTONLY)
4165 return mdb_page_search_root(mc, key, flags);
4168 /** Return the data associated with a given node.
4169 * @param[in] txn The transaction for this operation.
4170 * @param[in] leaf The node being read.
4171 * @param[out] data Updated to point to the node's data.
4172 * @return 0 on success, non-zero on failure.
4175 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
4177 MDB_page *omp; /* overflow page */
4181 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
4182 data->mv_size = NODEDSZ(leaf);
4183 data->mv_data = NODEDATA(leaf);
4187 /* Read overflow data.
4189 data->mv_size = NODEDSZ(leaf);
4190 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
4191 if ((rc = mdb_page_get(txn, pgno, &omp))) {
4192 DPRINTF("read overflow page %zu failed", pgno);
4195 data->mv_data = METADATA(omp);
4201 mdb_get(MDB_txn *txn, MDB_dbi dbi,
4202 MDB_val *key, MDB_val *data)
4211 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
4213 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4216 if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
4220 mdb_cursor_init(&mc, txn, dbi, &mx);
4221 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
4224 /** Find a sibling for a page.
4225 * Replaces the page at the top of the cursor's stack with the
4226 * specified sibling, if one exists.
4227 * @param[in] mc The cursor for this operation.
4228 * @param[in] move_right Non-zero if the right sibling is requested,
4229 * otherwise the left sibling.
4230 * @return 0 on success, non-zero on failure.
4233 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
4239 if (mc->mc_snum < 2) {
4240 return MDB_NOTFOUND; /* root has no siblings */
4244 DPRINTF("parent page is page %zu, index %u",
4245 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]);
4247 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
4248 : (mc->mc_ki[mc->mc_top] == 0)) {
4249 DPRINTF("no more keys left, moving to %s sibling",
4250 move_right ? "right" : "left");
4251 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
4252 /* undo cursor_pop before returning */
4259 mc->mc_ki[mc->mc_top]++;
4261 mc->mc_ki[mc->mc_top]--;
4262 DPRINTF("just moving to %s index key %u",
4263 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]);
4265 assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
4267 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4268 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp)))
4271 mdb_cursor_push(mc, mp);
4276 /** Move the cursor to the next data item. */
4278 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
4284 if (mc->mc_flags & C_EOF) {
4285 return MDB_NOTFOUND;
4288 assert(mc->mc_flags & C_INITIALIZED);
4290 mp = mc->mc_pg[mc->mc_top];
4292 if (mc->mc_db->md_flags & MDB_DUPSORT) {
4293 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4294 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4295 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
4296 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
4297 if (op != MDB_NEXT || rc == MDB_SUCCESS)
4301 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
4302 if (op == MDB_NEXT_DUP)
4303 return MDB_NOTFOUND;
4307 DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
4309 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
4310 DPUTS("=====> move to next sibling page");
4311 if (mdb_cursor_sibling(mc, 1) != MDB_SUCCESS) {
4312 mc->mc_flags |= C_EOF;
4313 mc->mc_flags &= ~C_INITIALIZED;
4314 return MDB_NOTFOUND;
4316 mp = mc->mc_pg[mc->mc_top];
4317 DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
4319 mc->mc_ki[mc->mc_top]++;
4321 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
4322 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
4325 key->mv_size = mc->mc_db->md_pad;
4326 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
4330 assert(IS_LEAF(mp));
4331 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4333 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4334 mdb_xcursor_init1(mc, leaf);
4337 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4340 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4341 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4342 if (rc != MDB_SUCCESS)
4347 MDB_GET_KEY(leaf, key);
4351 /** Move the cursor to the previous data item. */
4353 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
4359 assert(mc->mc_flags & C_INITIALIZED);
4361 mp = mc->mc_pg[mc->mc_top];
4363 if (mc->mc_db->md_flags & MDB_DUPSORT) {
4364 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4365 if (op == MDB_PREV || op == MDB_PREV_DUP) {
4366 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4367 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
4368 if (op != MDB_PREV || rc == MDB_SUCCESS)
4371 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
4372 if (op == MDB_PREV_DUP)
4373 return MDB_NOTFOUND;
4378 DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
4380 if (mc->mc_ki[mc->mc_top] == 0) {
4381 DPUTS("=====> move to prev sibling page");
4382 if (mdb_cursor_sibling(mc, 0) != MDB_SUCCESS) {
4383 mc->mc_flags &= ~C_INITIALIZED;
4384 return MDB_NOTFOUND;
4386 mp = mc->mc_pg[mc->mc_top];
4387 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
4388 DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
4390 mc->mc_ki[mc->mc_top]--;
4392 mc->mc_flags &= ~C_EOF;
4394 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
4395 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
4398 key->mv_size = mc->mc_db->md_pad;
4399 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
4403 assert(IS_LEAF(mp));
4404 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4406 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4407 mdb_xcursor_init1(mc, leaf);
4410 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4413 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4414 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
4415 if (rc != MDB_SUCCESS)
4420 MDB_GET_KEY(leaf, key);
4424 /** Set the cursor on a specific data item. */
4426 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
4427 MDB_cursor_op op, int *exactp)
4431 MDB_node *leaf = NULL;
4436 assert(key->mv_size > 0);
4438 /* See if we're already on the right page */
4439 if (mc->mc_flags & C_INITIALIZED) {
4442 mp = mc->mc_pg[mc->mc_top];
4444 mc->mc_ki[mc->mc_top] = 0;
4445 return MDB_NOTFOUND;
4447 if (mp->mp_flags & P_LEAF2) {
4448 nodekey.mv_size = mc->mc_db->md_pad;
4449 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
4451 leaf = NODEPTR(mp, 0);
4452 MDB_GET_KEY(leaf, &nodekey);
4454 rc = mc->mc_dbx->md_cmp(key, &nodekey);
4456 /* Probably happens rarely, but first node on the page
4457 * was the one we wanted.
4459 mc->mc_ki[mc->mc_top] = 0;
4466 unsigned int nkeys = NUMKEYS(mp);
4468 if (mp->mp_flags & P_LEAF2) {
4469 nodekey.mv_data = LEAF2KEY(mp,
4470 nkeys-1, nodekey.mv_size);
4472 leaf = NODEPTR(mp, nkeys-1);
4473 MDB_GET_KEY(leaf, &nodekey);
4475 rc = mc->mc_dbx->md_cmp(key, &nodekey);
4477 /* last node was the one we wanted */
4478 mc->mc_ki[mc->mc_top] = nkeys-1;
4484 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
4485 /* This is definitely the right page, skip search_page */
4486 if (mp->mp_flags & P_LEAF2) {
4487 nodekey.mv_data = LEAF2KEY(mp,
4488 mc->mc_ki[mc->mc_top], nodekey.mv_size);
4490 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4491 MDB_GET_KEY(leaf, &nodekey);
4493 rc = mc->mc_dbx->md_cmp(key, &nodekey);
4495 /* current node was the one we wanted */
4505 /* If any parents have right-sibs, search.
4506 * Otherwise, there's nothing further.
4508 for (i=0; i<mc->mc_top; i++)
4510 NUMKEYS(mc->mc_pg[i])-1)
4512 if (i == mc->mc_top) {
4513 /* There are no other pages */
4514 mc->mc_ki[mc->mc_top] = nkeys;
4515 return MDB_NOTFOUND;
4519 /* There are no other pages */
4520 mc->mc_ki[mc->mc_top] = 0;
4521 return MDB_NOTFOUND;
4525 rc = mdb_page_search(mc, key, 0);
4526 if (rc != MDB_SUCCESS)
4529 mp = mc->mc_pg[mc->mc_top];
4530 assert(IS_LEAF(mp));
4533 leaf = mdb_node_search(mc, key, exactp);
4534 if (exactp != NULL && !*exactp) {
4535 /* MDB_SET specified and not an exact match. */
4536 return MDB_NOTFOUND;
4540 DPUTS("===> inexact leaf not found, goto sibling");
4541 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
4542 return rc; /* no entries matched */
4543 mp = mc->mc_pg[mc->mc_top];
4544 assert(IS_LEAF(mp));
4545 leaf = NODEPTR(mp, 0);
4549 mc->mc_flags |= C_INITIALIZED;
4550 mc->mc_flags &= ~C_EOF;
4553 key->mv_size = mc->mc_db->md_pad;
4554 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
4558 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4559 mdb_xcursor_init1(mc, leaf);
4562 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4563 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
4564 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4567 if (op == MDB_GET_BOTH) {
4573 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
4574 if (rc != MDB_SUCCESS)
4577 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
4579 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
4581 rc = mc->mc_dbx->md_dcmp(data, &d2);
4583 if (op == MDB_GET_BOTH || rc > 0)
4584 return MDB_NOTFOUND;
4589 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
4590 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4595 /* The key already matches in all other cases */
4596 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
4597 MDB_GET_KEY(leaf, key);
4598 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
4603 /** Move the cursor to the first item in the database. */
4605 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
4610 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
4611 rc = mdb_page_search(mc, NULL, 0);
4612 if (rc != MDB_SUCCESS)
4615 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
4617 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
4618 mc->mc_flags |= C_INITIALIZED;
4619 mc->mc_flags &= ~C_EOF;
4621 mc->mc_ki[mc->mc_top] = 0;
4623 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
4624 key->mv_size = mc->mc_db->md_pad;
4625 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
4630 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4631 mdb_xcursor_init1(mc, leaf);
4632 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4637 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
4638 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4642 MDB_GET_KEY(leaf, key);
4646 /** Move the cursor to the last item in the database. */
4648 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
4653 if (!(mc->mc_flags & C_EOF)) {
4655 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
4658 lkey.mv_size = MDB_MAXKEYSIZE+1;
4659 lkey.mv_data = NULL;
4660 rc = mdb_page_search(mc, &lkey, 0);
4661 if (rc != MDB_SUCCESS)
4664 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
4666 mc->mc_flags |= C_INITIALIZED|C_EOF;
4667 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
4669 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4671 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
4672 key->mv_size = mc->mc_db->md_pad;
4673 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
4678 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4679 mdb_xcursor_init1(mc, leaf);
4680 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
4685 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
4686 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4691 MDB_GET_KEY(leaf, key);
4696 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
4705 case MDB_GET_CURRENT:
4706 if (!(mc->mc_flags & C_INITIALIZED)) {
4709 MDB_page *mp = mc->mc_pg[mc->mc_top];
4711 mc->mc_ki[mc->mc_top] = 0;
4717 key->mv_size = mc->mc_db->md_pad;
4718 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
4720 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4721 MDB_GET_KEY(leaf, key);
4723 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4724 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
4726 rc = mdb_node_read(mc->mc_txn, leaf, data);
4733 case MDB_GET_BOTH_RANGE:
4734 if (data == NULL || mc->mc_xcursor == NULL) {
4742 if (key == NULL || key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
4744 } else if (op == MDB_SET_RANGE)
4745 rc = mdb_cursor_set(mc, key, data, op, NULL);
4747 rc = mdb_cursor_set(mc, key, data, op, &exact);
4749 case MDB_GET_MULTIPLE:
4751 !(mc->mc_db->md_flags & MDB_DUPFIXED) ||
4752 !(mc->mc_flags & C_INITIALIZED)) {
4757 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
4758 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
4761 case MDB_NEXT_MULTIPLE:
4763 !(mc->mc_db->md_flags & MDB_DUPFIXED)) {
4767 if (!(mc->mc_flags & C_INITIALIZED))
4768 rc = mdb_cursor_first(mc, key, data);
4770 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
4771 if (rc == MDB_SUCCESS) {
4772 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
4775 mx = &mc->mc_xcursor->mx_cursor;
4776 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
4778 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
4779 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
4787 case MDB_NEXT_NODUP:
4788 if (!(mc->mc_flags & C_INITIALIZED))
4789 rc = mdb_cursor_first(mc, key, data);
4791 rc = mdb_cursor_next(mc, key, data, op);
4795 case MDB_PREV_NODUP:
4796 if (!(mc->mc_flags & C_INITIALIZED)) {
4797 rc = mdb_cursor_last(mc, key, data);
4798 mc->mc_flags |= C_INITIALIZED;
4799 mc->mc_ki[mc->mc_top]++;
4801 rc = mdb_cursor_prev(mc, key, data, op);
4804 rc = mdb_cursor_first(mc, key, data);
4808 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
4809 !(mc->mc_flags & C_INITIALIZED) ||
4810 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
4814 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4817 rc = mdb_cursor_last(mc, key, data);
4821 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
4822 !(mc->mc_flags & C_INITIALIZED) ||
4823 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
4827 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
4830 DPRINTF("unhandled/unimplemented cursor operation %u", op);
4838 /** Touch all the pages in the cursor stack.
4839 * Makes sure all the pages are writable, before attempting a write operation.
4840 * @param[in] mc The cursor to operate on.
4843 mdb_cursor_touch(MDB_cursor *mc)
4847 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
4850 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI,
4851 mc->mc_txn->mt_dbs[MAIN_DBI].md_flags & MDB_DUPSORT ? &mcx : NULL);
4852 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
4855 *mc->mc_dbflag = DB_DIRTY;
4857 for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
4858 rc = mdb_page_touch(mc);
4862 mc->mc_top = mc->mc_snum-1;
4867 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
4870 MDB_node *leaf = NULL;
4871 MDB_val xdata, *rdata, dkey;
4874 int do_sub = 0, insert = 0;
4875 unsigned int mcount = 0;
4879 char dbuf[MDB_MAXKEYSIZE+1];
4880 unsigned int nflags;
4883 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
4886 if (flags != MDB_CURRENT && (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE))
4889 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT) && data->mv_size > MDB_MAXKEYSIZE)
4892 #if SIZE_MAX > MAXDATASIZE
4893 if (data->mv_size > MAXDATASIZE)
4897 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
4898 mc->mc_dbi, DKEY(key), key ? key->mv_size:0, data->mv_size);
4902 if (flags == MDB_CURRENT) {
4903 if (!(mc->mc_flags & C_INITIALIZED))
4906 } else if (mc->mc_db->md_root == P_INVALID) {
4908 /* new database, write a root leaf page */
4909 DPUTS("allocating new root leaf page");
4910 if ((rc = mdb_page_new(mc, P_LEAF, 1, &np))) {
4914 mdb_cursor_push(mc, np);
4915 mc->mc_db->md_root = np->mp_pgno;
4916 mc->mc_db->md_depth++;
4917 *mc->mc_dbflag = DB_DIRTY;
4918 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
4920 np->mp_flags |= P_LEAF2;
4921 mc->mc_flags |= C_INITIALIZED;
4927 if (flags & MDB_APPEND) {
4929 rc = mdb_cursor_last(mc, &k2, &d2);
4931 rc = mc->mc_dbx->md_cmp(key, &k2);
4934 mc->mc_ki[mc->mc_top]++;
4940 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
4942 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
4943 DPRINTF("duplicate key [%s]", DKEY(key));
4945 return MDB_KEYEXIST;
4947 if (rc && rc != MDB_NOTFOUND)
4951 /* Cursor is positioned, now make sure all pages are writable */
4952 rc2 = mdb_cursor_touch(mc);
4957 /* The key already exists */
4958 if (rc == MDB_SUCCESS) {
4959 /* there's only a key anyway, so this is a no-op */
4960 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
4961 unsigned int ksize = mc->mc_db->md_pad;
4962 if (key->mv_size != ksize)
4964 if (flags == MDB_CURRENT) {
4965 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
4966 memcpy(ptr, key->mv_data, ksize);
4971 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4974 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
4975 /* Was a single item before, must convert now */
4977 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4978 /* Just overwrite the current item */
4979 if (flags == MDB_CURRENT)
4982 dkey.mv_size = NODEDSZ(leaf);
4983 dkey.mv_data = NODEDATA(leaf);
4984 #if UINT_MAX < SIZE_MAX
4985 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && dkey.mv_size == sizeof(size_t))
4986 #ifdef MISALIGNED_OK
4987 mc->mc_dbx->md_dcmp = mdb_cmp_long;
4989 mc->mc_dbx->md_dcmp = mdb_cmp_cint;
4992 /* if data matches, ignore it */
4993 if (!mc->mc_dbx->md_dcmp(data, &dkey))
4994 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
4996 /* create a fake page for the dup items */
4997 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
4998 dkey.mv_data = dbuf;
4999 fp = (MDB_page *)&pbuf;
5000 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
5001 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
5002 fp->mp_lower = PAGEHDRSZ;
5003 fp->mp_upper = PAGEHDRSZ + dkey.mv_size + data->mv_size;
5004 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5005 fp->mp_flags |= P_LEAF2;
5006 fp->mp_pad = data->mv_size;
5007 fp->mp_upper += 2 * data->mv_size; /* leave space for 2 more */
5009 fp->mp_upper += 2 * sizeof(indx_t) + 2 * NODESIZE +
5010 (dkey.mv_size & 1) + (data->mv_size & 1);
5012 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5015 xdata.mv_size = fp->mp_upper;
5020 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
5021 /* See if we need to convert from fake page to subDB */
5023 unsigned int offset;
5026 fp = NODEDATA(leaf);
5027 if (flags == MDB_CURRENT) {
5029 fp->mp_flags |= P_DIRTY;
5030 COPY_PGNO(fp->mp_pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
5031 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
5035 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5036 offset = fp->mp_pad;
5037 if (SIZELEFT(fp) >= offset)
5039 offset *= 4; /* space for 4 more */
5041 offset = NODESIZE + sizeof(indx_t) + data->mv_size;
5043 offset += offset & 1;
5044 if (NODESIZE + sizeof(indx_t) + NODEKSZ(leaf) + NODEDSZ(leaf) +
5045 offset >= mc->mc_txn->mt_env->me_nodemax) {
5046 /* yes, convert it */
5048 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5049 dummy.md_pad = fp->mp_pad;
5050 dummy.md_flags = MDB_DUPFIXED;
5051 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
5052 dummy.md_flags |= MDB_INTEGERKEY;
5055 dummy.md_branch_pages = 0;
5056 dummy.md_leaf_pages = 1;
5057 dummy.md_overflow_pages = 0;
5058 dummy.md_entries = NUMKEYS(fp);
5060 xdata.mv_size = sizeof(MDB_db);
5061 xdata.mv_data = &dummy;
5062 if ((rc = mdb_page_alloc(mc, 1, &mp)))
5064 offset = mc->mc_txn->mt_env->me_psize - NODEDSZ(leaf);
5065 flags |= F_DUPDATA|F_SUBDATA;
5066 dummy.md_root = mp->mp_pgno;
5068 /* no, just grow it */
5070 xdata.mv_size = NODEDSZ(leaf) + offset;
5071 xdata.mv_data = &pbuf;
5072 mp = (MDB_page *)&pbuf;
5073 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
5076 mp->mp_flags = fp->mp_flags | P_DIRTY;
5077 mp->mp_pad = fp->mp_pad;
5078 mp->mp_lower = fp->mp_lower;
5079 mp->mp_upper = fp->mp_upper + offset;
5081 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
5083 nsize = NODEDSZ(leaf) - fp->mp_upper;
5084 memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper, nsize);
5085 for (i=0; i<NUMKEYS(fp); i++)
5086 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
5088 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5092 /* data is on sub-DB, just store it */
5093 flags |= F_DUPDATA|F_SUBDATA;
5097 /* overflow page overwrites need special handling */
5098 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5101 int ovpages, dpages;
5103 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
5104 dpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
5105 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
5106 mdb_page_get(mc->mc_txn, pg, &omp);
5107 /* Is the ov page writable and large enough? */
5108 if ((omp->mp_flags & P_DIRTY) && ovpages >= dpages) {
5109 /* yes, overwrite it. Note in this case we don't
5110 * bother to try shrinking the node if the new data
5111 * is smaller than the overflow threshold.
5113 if (F_ISSET(flags, MDB_RESERVE))
5114 data->mv_data = METADATA(omp);
5116 memcpy(METADATA(omp), data->mv_data, data->mv_size);
5119 /* no, free ovpages */
5121 mc->mc_db->md_overflow_pages -= ovpages;
5122 for (i=0; i<ovpages; i++) {
5123 DPRINTF("freed ov page %zu", pg);
5124 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
5128 } else if (NODEDSZ(leaf) == data->mv_size) {
5129 /* same size, just replace it. Note that we could
5130 * also reuse this node if the new data is smaller,
5131 * but instead we opt to shrink the node in that case.
5133 if (F_ISSET(flags, MDB_RESERVE))
5134 data->mv_data = NODEDATA(leaf);
5135 else if (data->mv_size)
5136 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
5138 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
5141 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5142 mc->mc_db->md_entries--;
5144 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
5151 nflags = flags & NODE_ADD_FLAGS;
5152 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
5153 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
5154 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
5155 nflags &= ~MDB_APPEND;
5157 nflags |= MDB_SPLIT_REPLACE;
5158 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
5160 /* There is room already in this leaf page. */
5161 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
5162 if (rc == 0 && !do_sub && insert) {
5163 /* Adjust other cursors pointing to mp */
5164 MDB_cursor *m2, *m3;
5165 MDB_dbi dbi = mc->mc_dbi;
5166 unsigned i = mc->mc_top;
5167 MDB_page *mp = mc->mc_pg[i];
5169 if (mc->mc_flags & C_SUB)
5172 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5173 if (mc->mc_flags & C_SUB)
5174 m3 = &m2->mc_xcursor->mx_cursor;
5177 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
5178 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
5185 if (rc != MDB_SUCCESS)
5186 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5188 /* Now store the actual data in the child DB. Note that we're
5189 * storing the user data in the keys field, so there are strict
5190 * size limits on dupdata. The actual data fields of the child
5191 * DB are all zero size.
5198 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5199 if (flags & MDB_CURRENT) {
5200 xflags = MDB_CURRENT;
5202 mdb_xcursor_init1(mc, leaf);
5203 xflags = (flags & MDB_NODUPDATA) ? MDB_NOOVERWRITE : 0;
5205 /* converted, write the original data first */
5207 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
5211 /* Adjust other cursors pointing to mp */
5213 unsigned i = mc->mc_top;
5214 MDB_page *mp = mc->mc_pg[i];
5216 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5217 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
5218 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
5219 mdb_xcursor_init1(m2, leaf);
5223 /* we've done our job */
5226 if (flags & MDB_APPENDDUP)
5227 xflags |= MDB_APPEND;
5228 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
5229 if (flags & F_SUBDATA) {
5230 void *db = NODEDATA(leaf);
5231 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
5234 /* sub-writes might have failed so check rc again.
5235 * Don't increment count if we just replaced an existing item.
5237 if (!rc && !(flags & MDB_CURRENT))
5238 mc->mc_db->md_entries++;
5239 if (flags & MDB_MULTIPLE) {
5241 if (mcount < data[1].mv_size) {
5242 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
5243 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5249 /* If we succeeded and the key didn't exist before, make sure
5250 * the cursor is marked valid.
5253 mc->mc_flags |= C_INITIALIZED;
5258 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
5263 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
5266 if (!(mc->mc_flags & C_INITIALIZED))
5269 rc = mdb_cursor_touch(mc);
5273 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5275 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5276 if (flags != MDB_NODUPDATA) {
5277 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
5278 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
5280 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
5281 /* If sub-DB still has entries, we're done */
5282 if (mc->mc_xcursor->mx_db.md_entries) {
5283 if (leaf->mn_flags & F_SUBDATA) {
5284 /* update subDB info */
5285 void *db = NODEDATA(leaf);
5286 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
5288 /* shrink fake page */
5289 mdb_node_shrink(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5291 mc->mc_db->md_entries--;
5294 /* otherwise fall thru and delete the sub-DB */
5297 if (leaf->mn_flags & F_SUBDATA) {
5298 /* add all the child DB's pages to the free list */
5299 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
5300 if (rc == MDB_SUCCESS) {
5301 mc->mc_db->md_entries -=
5302 mc->mc_xcursor->mx_db.md_entries;
5307 return mdb_cursor_del0(mc, leaf);
5310 /** Allocate and initialize new pages for a database.
5311 * @param[in] mc a cursor on the database being added to.
5312 * @param[in] flags flags defining what type of page is being allocated.
5313 * @param[in] num the number of pages to allocate. This is usually 1,
5314 * unless allocating overflow pages for a large record.
5315 * @param[out] mp Address of a page, or NULL on failure.
5316 * @return 0 on success, non-zero on failure.
5319 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
5324 if ((rc = mdb_page_alloc(mc, num, &np)))
5326 DPRINTF("allocated new mpage %zu, page size %u",
5327 np->mp_pgno, mc->mc_txn->mt_env->me_psize);
5328 np->mp_flags = flags | P_DIRTY;
5329 np->mp_lower = PAGEHDRSZ;
5330 np->mp_upper = mc->mc_txn->mt_env->me_psize;
5333 mc->mc_db->md_branch_pages++;
5334 else if (IS_LEAF(np))
5335 mc->mc_db->md_leaf_pages++;
5336 else if (IS_OVERFLOW(np)) {
5337 mc->mc_db->md_overflow_pages += num;
5345 /** Calculate the size of a leaf node.
5346 * The size depends on the environment's page size; if a data item
5347 * is too large it will be put onto an overflow page and the node
5348 * size will only include the key and not the data. Sizes are always
5349 * rounded up to an even number of bytes, to guarantee 2-byte alignment
5350 * of the #MDB_node headers.
5351 * @param[in] env The environment handle.
5352 * @param[in] key The key for the node.
5353 * @param[in] data The data for the node.
5354 * @return The number of bytes needed to store the node.
5357 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
5361 sz = LEAFSIZE(key, data);
5362 if (sz >= env->me_nodemax) {
5363 /* put on overflow page */
5364 sz -= data->mv_size - sizeof(pgno_t);
5368 return sz + sizeof(indx_t);
5371 /** Calculate the size of a branch node.
5372 * The size should depend on the environment's page size but since
5373 * we currently don't support spilling large keys onto overflow
5374 * pages, it's simply the size of the #MDB_node header plus the
5375 * size of the key. Sizes are always rounded up to an even number
5376 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
5377 * @param[in] env The environment handle.
5378 * @param[in] key The key for the node.
5379 * @return The number of bytes needed to store the node.
5382 mdb_branch_size(MDB_env *env, MDB_val *key)
5387 if (sz >= env->me_nodemax) {
5388 /* put on overflow page */
5389 /* not implemented */
5390 /* sz -= key->size - sizeof(pgno_t); */
5393 return sz + sizeof(indx_t);
5396 /** Add a node to the page pointed to by the cursor.
5397 * @param[in] mc The cursor for this operation.
5398 * @param[in] indx The index on the page where the new node should be added.
5399 * @param[in] key The key for the new node.
5400 * @param[in] data The data for the new node, if any.
5401 * @param[in] pgno The page number, if adding a branch node.
5402 * @param[in] flags Flags for the node.
5403 * @return 0 on success, non-zero on failure. Possible errors are:
5405 * <li>ENOMEM - failed to allocate overflow pages for the node.
5406 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
5407 * should never happen since all callers already calculate the
5408 * page's free space before calling this function.
5412 mdb_node_add(MDB_cursor *mc, indx_t indx,
5413 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
5416 size_t node_size = NODESIZE;
5419 MDB_page *mp = mc->mc_pg[mc->mc_top];
5420 MDB_page *ofp = NULL; /* overflow page */
5423 assert(mp->mp_upper >= mp->mp_lower);
5425 DPRINTF("add to %s %spage %zu index %i, data size %zu key size %zu [%s]",
5426 IS_LEAF(mp) ? "leaf" : "branch",
5427 IS_SUBP(mp) ? "sub-" : "",
5428 mp->mp_pgno, indx, data ? data->mv_size : 0,
5429 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
5432 /* Move higher keys up one slot. */
5433 int ksize = mc->mc_db->md_pad, dif;
5434 char *ptr = LEAF2KEY(mp, indx, ksize);
5435 dif = NUMKEYS(mp) - indx;
5437 memmove(ptr+ksize, ptr, dif*ksize);
5438 /* insert new key */
5439 memcpy(ptr, key->mv_data, ksize);
5441 /* Just using these for counting */
5442 mp->mp_lower += sizeof(indx_t);
5443 mp->mp_upper -= ksize - sizeof(indx_t);
5448 node_size += key->mv_size;
5452 if (F_ISSET(flags, F_BIGDATA)) {
5453 /* Data already on overflow page. */
5454 node_size += sizeof(pgno_t);
5455 } else if (node_size + data->mv_size >= mc->mc_txn->mt_env->me_nodemax) {
5456 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
5458 /* Put data on overflow page. */
5459 DPRINTF("data size is %zu, node would be %zu, put data on overflow page",
5460 data->mv_size, node_size+data->mv_size);
5461 node_size += sizeof(pgno_t);
5462 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
5464 DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
5467 node_size += data->mv_size;
5470 node_size += node_size & 1;
5472 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
5473 DPRINTF("not enough room in page %zu, got %u ptrs",
5474 mp->mp_pgno, NUMKEYS(mp));
5475 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
5476 mp->mp_upper - mp->mp_lower);
5477 DPRINTF("node size = %zu", node_size);
5478 return MDB_PAGE_FULL;
5481 /* Move higher pointers up one slot. */
5482 for (i = NUMKEYS(mp); i > indx; i--)
5483 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
5485 /* Adjust free space offsets. */
5486 ofs = mp->mp_upper - node_size;
5487 assert(ofs >= mp->mp_lower + sizeof(indx_t));
5488 mp->mp_ptrs[indx] = ofs;
5490 mp->mp_lower += sizeof(indx_t);
5492 /* Write the node data. */
5493 node = NODEPTR(mp, indx);
5494 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
5495 node->mn_flags = flags;
5497 SETDSZ(node,data->mv_size);
5502 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
5507 if (F_ISSET(flags, F_BIGDATA))
5508 memcpy(node->mn_data + key->mv_size, data->mv_data,
5510 else if (F_ISSET(flags, MDB_RESERVE))
5511 data->mv_data = node->mn_data + key->mv_size;
5513 memcpy(node->mn_data + key->mv_size, data->mv_data,
5516 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
5518 if (F_ISSET(flags, MDB_RESERVE))
5519 data->mv_data = METADATA(ofp);
5521 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
5528 /** Delete the specified node from a page.
5529 * @param[in] mp The page to operate on.
5530 * @param[in] indx The index of the node to delete.
5531 * @param[in] ksize The size of a node. Only used if the page is
5532 * part of a #MDB_DUPFIXED database.
5535 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
5538 indx_t i, j, numkeys, ptr;
5545 COPY_PGNO(pgno, mp->mp_pgno);
5546 DPRINTF("delete node %u on %s page %zu", indx,
5547 IS_LEAF(mp) ? "leaf" : "branch", pgno);
5550 assert(indx < NUMKEYS(mp));
5553 int x = NUMKEYS(mp) - 1 - indx;
5554 base = LEAF2KEY(mp, indx, ksize);
5556 memmove(base, base + ksize, x * ksize);
5557 mp->mp_lower -= sizeof(indx_t);
5558 mp->mp_upper += ksize - sizeof(indx_t);
5562 node = NODEPTR(mp, indx);
5563 sz = NODESIZE + node->mn_ksize;
5565 if (F_ISSET(node->mn_flags, F_BIGDATA))
5566 sz += sizeof(pgno_t);
5568 sz += NODEDSZ(node);
5572 ptr = mp->mp_ptrs[indx];
5573 numkeys = NUMKEYS(mp);
5574 for (i = j = 0; i < numkeys; i++) {
5576 mp->mp_ptrs[j] = mp->mp_ptrs[i];
5577 if (mp->mp_ptrs[i] < ptr)
5578 mp->mp_ptrs[j] += sz;
5583 base = (char *)mp + mp->mp_upper;
5584 memmove(base + sz, base, ptr - mp->mp_upper);
5586 mp->mp_lower -= sizeof(indx_t);
5590 /** Compact the main page after deleting a node on a subpage.
5591 * @param[in] mp The main page to operate on.
5592 * @param[in] indx The index of the subpage on the main page.
5595 mdb_node_shrink(MDB_page *mp, indx_t indx)
5602 indx_t i, numkeys, ptr;
5604 node = NODEPTR(mp, indx);
5605 sp = (MDB_page *)NODEDATA(node);
5606 osize = NODEDSZ(node);
5608 delta = sp->mp_upper - sp->mp_lower;
5609 SETDSZ(node, osize - delta);
5610 xp = (MDB_page *)((char *)sp + delta);
5612 /* shift subpage upward */
5614 nsize = NUMKEYS(sp) * sp->mp_pad;
5615 memmove(METADATA(xp), METADATA(sp), nsize);
5618 nsize = osize - sp->mp_upper;
5619 numkeys = NUMKEYS(sp);
5620 for (i=numkeys-1; i>=0; i--)
5621 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
5623 xp->mp_upper = sp->mp_lower;
5624 xp->mp_lower = sp->mp_lower;
5625 xp->mp_flags = sp->mp_flags;
5626 xp->mp_pad = sp->mp_pad;
5627 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
5629 /* shift lower nodes upward */
5630 ptr = mp->mp_ptrs[indx];
5631 numkeys = NUMKEYS(mp);
5632 for (i = 0; i < numkeys; i++) {
5633 if (mp->mp_ptrs[i] <= ptr)
5634 mp->mp_ptrs[i] += delta;
5637 base = (char *)mp + mp->mp_upper;
5638 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
5639 mp->mp_upper += delta;
5642 /** Initial setup of a sorted-dups cursor.
5643 * Sorted duplicates are implemented as a sub-database for the given key.
5644 * The duplicate data items are actually keys of the sub-database.
5645 * Operations on the duplicate data items are performed using a sub-cursor
5646 * initialized when the sub-database is first accessed. This function does
5647 * the preliminary setup of the sub-cursor, filling in the fields that
5648 * depend only on the parent DB.
5649 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
5652 mdb_xcursor_init0(MDB_cursor *mc)
5654 MDB_xcursor *mx = mc->mc_xcursor;
5656 mx->mx_cursor.mc_xcursor = NULL;
5657 mx->mx_cursor.mc_txn = mc->mc_txn;
5658 mx->mx_cursor.mc_db = &mx->mx_db;
5659 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
5660 mx->mx_cursor.mc_dbi = mc->mc_dbi+1;
5661 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
5662 mx->mx_cursor.mc_snum = 0;
5663 mx->mx_cursor.mc_top = 0;
5664 mx->mx_cursor.mc_flags = C_SUB;
5665 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
5666 mx->mx_dbx.md_dcmp = NULL;
5667 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
5670 /** Final setup of a sorted-dups cursor.
5671 * Sets up the fields that depend on the data from the main cursor.
5672 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
5673 * @param[in] node The data containing the #MDB_db record for the
5674 * sorted-dup database.
5677 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
5679 MDB_xcursor *mx = mc->mc_xcursor;
5681 if (node->mn_flags & F_SUBDATA) {
5682 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
5683 mx->mx_cursor.mc_pg[0] = 0;
5684 mx->mx_cursor.mc_snum = 0;
5685 mx->mx_cursor.mc_flags = C_SUB;
5687 MDB_page *fp = NODEDATA(node);
5688 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
5689 mx->mx_db.md_flags = 0;
5690 mx->mx_db.md_depth = 1;
5691 mx->mx_db.md_branch_pages = 0;
5692 mx->mx_db.md_leaf_pages = 1;
5693 mx->mx_db.md_overflow_pages = 0;
5694 mx->mx_db.md_entries = NUMKEYS(fp);
5695 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
5696 mx->mx_cursor.mc_snum = 1;
5697 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
5698 mx->mx_cursor.mc_top = 0;
5699 mx->mx_cursor.mc_pg[0] = fp;
5700 mx->mx_cursor.mc_ki[0] = 0;
5701 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5702 mx->mx_db.md_flags = MDB_DUPFIXED;
5703 mx->mx_db.md_pad = fp->mp_pad;
5704 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
5705 mx->mx_db.md_flags |= MDB_INTEGERKEY;
5708 DPRINTF("Sub-db %u for db %u root page %zu", mx->mx_cursor.mc_dbi, mc->mc_dbi,
5710 mx->mx_dbflag = (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY)) ?
5712 mx->mx_dbx.md_name.mv_data = NODEKEY(node);
5713 mx->mx_dbx.md_name.mv_size = node->mn_ksize;
5714 #if UINT_MAX < SIZE_MAX
5715 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
5716 #ifdef MISALIGNED_OK
5717 mx->mx_dbx.md_cmp = mdb_cmp_long;
5719 mx->mx_dbx.md_cmp = mdb_cmp_cint;
5724 /** Initialize a cursor for a given transaction and database. */
5726 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
5731 mc->mc_db = &txn->mt_dbs[dbi];
5732 mc->mc_dbx = &txn->mt_dbxs[dbi];
5733 mc->mc_dbflag = &txn->mt_dbflags[dbi];
5738 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
5740 mc->mc_xcursor = mx;
5741 mdb_xcursor_init0(mc);
5743 mc->mc_xcursor = NULL;
5745 if (*mc->mc_dbflag & DB_STALE) {
5746 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
5751 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
5754 MDB_xcursor *mx = NULL;
5755 size_t size = sizeof(MDB_cursor);
5757 if (txn == NULL || ret == NULL || dbi >= txn->mt_numdbs)
5760 /* Allow read access to the freelist */
5761 if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
5764 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
5765 size += sizeof(MDB_xcursor);
5767 if ((mc = malloc(size)) != NULL) {
5768 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
5769 mx = (MDB_xcursor *)(mc + 1);
5771 mdb_cursor_init(mc, txn, dbi, mx);
5772 if (txn->mt_cursors) {
5773 mc->mc_next = txn->mt_cursors[dbi];
5774 txn->mt_cursors[dbi] = mc;
5776 mc->mc_flags |= C_ALLOCD;
5787 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
5789 if (txn == NULL || mc == NULL || mc->mc_dbi >= txn->mt_numdbs)
5792 if (txn->mt_cursors)
5795 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
5799 /* Return the count of duplicate data items for the current key */
5801 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
5805 if (mc == NULL || countp == NULL)
5808 if (!(mc->mc_db->md_flags & MDB_DUPSORT))
5811 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5812 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5815 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
5818 *countp = mc->mc_xcursor->mx_db.md_entries;
5824 mdb_cursor_close(MDB_cursor *mc)
5827 /* remove from txn, if tracked */
5828 if (mc->mc_txn->mt_cursors) {
5829 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
5830 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
5832 *prev = mc->mc_next;
5834 if (mc->mc_flags & C_ALLOCD)
5840 mdb_cursor_txn(MDB_cursor *mc)
5842 if (!mc) return NULL;
5847 mdb_cursor_dbi(MDB_cursor *mc)
5853 /** Replace the key for a node with a new key.
5854 * @param[in] mp The page containing the node to operate on.
5855 * @param[in] indx The index of the node to operate on.
5856 * @param[in] key The new key to use.
5857 * @return 0 on success, non-zero on failure.
5860 mdb_update_key(MDB_cursor *mc, MDB_val *key)
5867 indx_t ptr, i, numkeys, indx;
5870 indx = mc->mc_ki[mc->mc_top];
5871 mp = mc->mc_pg[mc->mc_top];
5872 node = NODEPTR(mp, indx);
5873 ptr = mp->mp_ptrs[indx];
5877 char kbuf2[(MDB_MAXKEYSIZE*2+1)];
5878 k2.mv_data = NODEKEY(node);
5879 k2.mv_size = node->mn_ksize;
5880 DPRINTF("update key %u (ofs %u) [%s] to [%s] on page %zu",
5882 mdb_dkey(&k2, kbuf2),
5888 delta0 = delta = key->mv_size - node->mn_ksize;
5890 /* Must be 2-byte aligned. If new key is
5891 * shorter by 1, the shift will be skipped.
5893 delta += (delta & 1);
5895 if (delta > 0 && SIZELEFT(mp) < delta) {
5897 /* not enough space left, do a delete and split */
5898 DPRINTF("Not enough room, delta = %d, splitting...", delta);
5899 pgno = NODEPGNO(node);
5900 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5901 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
5904 numkeys = NUMKEYS(mp);
5905 for (i = 0; i < numkeys; i++) {
5906 if (mp->mp_ptrs[i] <= ptr)
5907 mp->mp_ptrs[i] -= delta;
5910 base = (char *)mp + mp->mp_upper;
5911 len = ptr - mp->mp_upper + NODESIZE;
5912 memmove(base - delta, base, len);
5913 mp->mp_upper -= delta;
5915 node = NODEPTR(mp, indx);
5918 /* But even if no shift was needed, update ksize */
5920 node->mn_ksize = key->mv_size;
5923 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
5929 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
5931 /** Move a node from csrc to cdst.
5934 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
5941 unsigned short flags;
5945 /* Mark src and dst as dirty. */
5946 if ((rc = mdb_page_touch(csrc)) ||
5947 (rc = mdb_page_touch(cdst)))
5950 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5951 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
5952 key.mv_size = csrc->mc_db->md_pad;
5953 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
5955 data.mv_data = NULL;
5959 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
5960 assert(!((long)srcnode&1));
5961 srcpg = NODEPGNO(srcnode);
5962 flags = srcnode->mn_flags;
5963 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
5964 unsigned int snum = csrc->mc_snum;
5966 /* must find the lowest key below src */
5967 mdb_page_search_root(csrc, NULL, 0);
5968 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5969 key.mv_size = csrc->mc_db->md_pad;
5970 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
5972 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
5973 key.mv_size = NODEKSZ(s2);
5974 key.mv_data = NODEKEY(s2);
5976 csrc->mc_snum = snum--;
5977 csrc->mc_top = snum;
5979 key.mv_size = NODEKSZ(srcnode);
5980 key.mv_data = NODEKEY(srcnode);
5982 data.mv_size = NODEDSZ(srcnode);
5983 data.mv_data = NODEDATA(srcnode);
5985 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
5986 unsigned int snum = cdst->mc_snum;
5989 /* must find the lowest key below dst */
5990 mdb_page_search_root(cdst, NULL, 0);
5991 if (IS_LEAF2(cdst->mc_pg[cdst->mc_top])) {
5992 bkey.mv_size = cdst->mc_db->md_pad;
5993 bkey.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, bkey.mv_size);
5995 s2 = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
5996 bkey.mv_size = NODEKSZ(s2);
5997 bkey.mv_data = NODEKEY(s2);
5999 cdst->mc_snum = snum--;
6000 cdst->mc_top = snum;
6001 mdb_cursor_copy(cdst, &mn);
6003 rc = mdb_update_key(&mn, &bkey);
6008 DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
6009 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
6010 csrc->mc_ki[csrc->mc_top],
6012 csrc->mc_pg[csrc->mc_top]->mp_pgno,
6013 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
6015 /* Add the node to the destination page.
6017 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
6018 if (rc != MDB_SUCCESS)
6021 /* Delete the node from the source page.
6023 mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
6026 /* Adjust other cursors pointing to mp */
6027 MDB_cursor *m2, *m3;
6028 MDB_dbi dbi = csrc->mc_dbi;
6029 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
6031 if (csrc->mc_flags & C_SUB)
6034 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6035 if (m2 == csrc) continue;
6036 if (csrc->mc_flags & C_SUB)
6037 m3 = &m2->mc_xcursor->mx_cursor;
6040 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
6041 csrc->mc_ki[csrc->mc_top]) {
6042 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
6043 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
6048 /* Update the parent separators.
6050 if (csrc->mc_ki[csrc->mc_top] == 0) {
6051 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
6052 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6053 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6055 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6056 key.mv_size = NODEKSZ(srcnode);
6057 key.mv_data = NODEKEY(srcnode);
6059 DPRINTF("update separator for source page %zu to [%s]",
6060 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
6061 mdb_cursor_copy(csrc, &mn);
6064 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
6067 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6069 indx_t ix = csrc->mc_ki[csrc->mc_top];
6070 nullkey.mv_size = 0;
6071 csrc->mc_ki[csrc->mc_top] = 0;
6072 rc = mdb_update_key(csrc, &nullkey);
6073 csrc->mc_ki[csrc->mc_top] = ix;
6074 assert(rc == MDB_SUCCESS);
6078 if (cdst->mc_ki[cdst->mc_top] == 0) {
6079 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
6080 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6081 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
6083 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
6084 key.mv_size = NODEKSZ(srcnode);
6085 key.mv_data = NODEKEY(srcnode);
6087 DPRINTF("update separator for destination page %zu to [%s]",
6088 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
6089 mdb_cursor_copy(cdst, &mn);
6092 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
6095 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
6097 indx_t ix = cdst->mc_ki[cdst->mc_top];
6098 nullkey.mv_size = 0;
6099 cdst->mc_ki[cdst->mc_top] = 0;
6100 rc = mdb_update_key(cdst, &nullkey);
6101 cdst->mc_ki[cdst->mc_top] = ix;
6102 assert(rc == MDB_SUCCESS);
6109 /** Merge one page into another.
6110 * The nodes from the page pointed to by \b csrc will
6111 * be copied to the page pointed to by \b cdst and then
6112 * the \b csrc page will be freed.
6113 * @param[in] csrc Cursor pointing to the source page.
6114 * @param[in] cdst Cursor pointing to the destination page.
6117 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
6125 DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
6126 cdst->mc_pg[cdst->mc_top]->mp_pgno);
6128 assert(csrc->mc_snum > 1); /* can't merge root page */
6129 assert(cdst->mc_snum > 1);
6131 /* Mark dst as dirty. */
6132 if ((rc = mdb_page_touch(cdst)))
6135 /* Move all nodes from src to dst.
6137 j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
6138 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6139 key.mv_size = csrc->mc_db->md_pad;
6140 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
6141 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
6142 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
6143 if (rc != MDB_SUCCESS)
6145 key.mv_data = (char *)key.mv_data + key.mv_size;
6148 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
6149 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
6150 if (i == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6151 unsigned int snum = csrc->mc_snum;
6153 /* must find the lowest key below src */
6154 mdb_page_search_root(csrc, NULL, 0);
6155 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6156 key.mv_size = csrc->mc_db->md_pad;
6157 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6159 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6160 key.mv_size = NODEKSZ(s2);
6161 key.mv_data = NODEKEY(s2);
6163 csrc->mc_snum = snum--;
6164 csrc->mc_top = snum;
6166 key.mv_size = srcnode->mn_ksize;
6167 key.mv_data = NODEKEY(srcnode);
6170 data.mv_size = NODEDSZ(srcnode);
6171 data.mv_data = NODEDATA(srcnode);
6172 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
6173 if (rc != MDB_SUCCESS)
6178 DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
6179 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);
6181 /* Unlink the src page from parent and add to free list.
6183 mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
6184 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
6187 rc = mdb_update_key(csrc, &key);
6193 mdb_midl_append(&csrc->mc_txn->mt_free_pgs, csrc->mc_pg[csrc->mc_top]->mp_pgno);
6194 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
6195 csrc->mc_db->md_leaf_pages--;
6197 csrc->mc_db->md_branch_pages--;
6199 /* Adjust other cursors pointing to mp */
6200 MDB_cursor *m2, *m3;
6201 MDB_dbi dbi = csrc->mc_dbi;
6202 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
6204 if (csrc->mc_flags & C_SUB)
6207 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6208 if (csrc->mc_flags & C_SUB)
6209 m3 = &m2->mc_xcursor->mx_cursor;
6212 if (m3 == csrc) continue;
6213 if (m3->mc_snum < csrc->mc_snum) continue;
6214 if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
6215 m3->mc_pg[csrc->mc_top] = mp;
6216 m3->mc_ki[csrc->mc_top] += nkeys;
6220 mdb_cursor_pop(csrc);
6222 return mdb_rebalance(csrc);
6225 /** Copy the contents of a cursor.
6226 * @param[in] csrc The cursor to copy from.
6227 * @param[out] cdst The cursor to copy to.
6230 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
6234 cdst->mc_txn = csrc->mc_txn;
6235 cdst->mc_dbi = csrc->mc_dbi;
6236 cdst->mc_db = csrc->mc_db;
6237 cdst->mc_dbx = csrc->mc_dbx;
6238 cdst->mc_snum = csrc->mc_snum;
6239 cdst->mc_top = csrc->mc_top;
6240 cdst->mc_flags = csrc->mc_flags;
6242 for (i=0; i<csrc->mc_snum; i++) {
6243 cdst->mc_pg[i] = csrc->mc_pg[i];
6244 cdst->mc_ki[i] = csrc->mc_ki[i];
6248 /** Rebalance the tree after a delete operation.
6249 * @param[in] mc Cursor pointing to the page where rebalancing
6251 * @return 0 on success, non-zero on failure.
6254 mdb_rebalance(MDB_cursor *mc)
6264 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
6265 DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
6266 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
6267 pgno, NUMKEYS(mc->mc_pg[mc->mc_top]), (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10);
6271 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD) {
6274 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
6275 DPRINTF("no need to rebalance page %zu, above fill threshold",
6281 if (mc->mc_snum < 2) {
6282 MDB_page *mp = mc->mc_pg[0];
6283 if (NUMKEYS(mp) == 0) {
6284 DPUTS("tree is completely empty");
6285 mc->mc_db->md_root = P_INVALID;
6286 mc->mc_db->md_depth = 0;
6287 mc->mc_db->md_leaf_pages = 0;
6288 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
6292 /* Adjust other cursors pointing to mp */
6293 MDB_cursor *m2, *m3;
6294 MDB_dbi dbi = mc->mc_dbi;
6296 if (mc->mc_flags & C_SUB)
6299 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6300 if (m2 == mc) continue;
6301 if (mc->mc_flags & C_SUB)
6302 m3 = &m2->mc_xcursor->mx_cursor;
6305 if (m3->mc_snum < mc->mc_snum) continue;
6306 if (m3->mc_pg[0] == mp) {
6312 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
6313 DPUTS("collapsing root page!");
6314 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
6315 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
6316 if ((rc = mdb_page_get(mc->mc_txn, mc->mc_db->md_root,
6319 mc->mc_db->md_depth--;
6320 mc->mc_db->md_branch_pages--;
6322 /* Adjust other cursors pointing to mp */
6323 MDB_cursor *m2, *m3;
6324 MDB_dbi dbi = mc->mc_dbi;
6326 if (mc->mc_flags & C_SUB)
6329 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6330 if (m2 == mc) continue;
6331 if (mc->mc_flags & C_SUB)
6332 m3 = &m2->mc_xcursor->mx_cursor;
6335 if (m3->mc_snum < mc->mc_snum) continue;
6336 if (m3->mc_pg[0] == mp) {
6337 m3->mc_pg[0] = mc->mc_pg[0];
6342 DPUTS("root page doesn't need rebalancing");
6346 /* The parent (branch page) must have at least 2 pointers,
6347 * otherwise the tree is invalid.
6349 ptop = mc->mc_top-1;
6350 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
6352 /* Leaf page fill factor is below the threshold.
6353 * Try to move keys from left or right neighbor, or
6354 * merge with a neighbor page.
6359 mdb_cursor_copy(mc, &mn);
6360 mn.mc_xcursor = NULL;
6362 if (mc->mc_ki[ptop] == 0) {
6363 /* We're the leftmost leaf in our parent.
6365 DPUTS("reading right neighbor");
6367 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
6368 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
6370 mn.mc_ki[mn.mc_top] = 0;
6371 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
6373 /* There is at least one neighbor to the left.
6375 DPUTS("reading left neighbor");
6377 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
6378 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
6380 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
6381 mc->mc_ki[mc->mc_top] = 0;
6384 DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
6385 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);
6387 /* If the neighbor page is above threshold and has enough keys,
6388 * move one key from it. Otherwise we should try to merge them.
6389 * (A branch page must never have less than 2 keys.)
6391 minkeys = 1 + (IS_BRANCH(mn.mc_pg[mn.mc_top]));
6392 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys)
6393 return mdb_node_move(&mn, mc);
6395 if (mc->mc_ki[ptop] == 0)
6396 rc = mdb_page_merge(&mn, mc);
6398 rc = mdb_page_merge(mc, &mn);
6399 mc->mc_flags &= ~C_INITIALIZED;
6404 /** Complete a delete operation started by #mdb_cursor_del(). */
6406 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
6410 /* add overflow pages to free list */
6411 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6415 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
6416 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
6417 mc->mc_db->md_overflow_pages -= ovpages;
6418 for (i=0; i<ovpages; i++) {
6419 DPRINTF("freed ov page %zu", pg);
6420 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
6424 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], mc->mc_db->md_pad);
6425 mc->mc_db->md_entries--;
6426 rc = mdb_rebalance(mc);
6427 if (rc != MDB_SUCCESS)
6428 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6429 /* if mc points past last node in page, invalidate */
6430 else if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6431 mc->mc_flags &= ~C_INITIALIZED;
6437 mdb_del(MDB_txn *txn, MDB_dbi dbi,
6438 MDB_val *key, MDB_val *data)
6443 MDB_val rdata, *xdata;
6447 assert(key != NULL);
6449 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
6451 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6454 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
6458 if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
6462 mdb_cursor_init(&mc, txn, dbi, &mx);
6473 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
6475 /* let mdb_page_split know about this cursor if needed:
6476 * delete will trigger a rebalance; if it needs to move
6477 * a node from one page to another, it will have to
6478 * update the parent's separator key(s). If the new sepkey
6479 * is larger than the current one, the parent page may
6480 * run out of space, triggering a split. We need this
6481 * cursor to be consistent until the end of the rebalance.
6483 mc.mc_next = txn->mt_cursors[dbi];
6484 txn->mt_cursors[dbi] = &mc;
6485 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
6486 txn->mt_cursors[dbi] = mc.mc_next;
6491 /** Split a page and insert a new node.
6492 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
6493 * The cursor will be updated to point to the actual page and index where
6494 * the node got inserted after the split.
6495 * @param[in] newkey The key for the newly inserted node.
6496 * @param[in] newdata The data for the newly inserted node.
6497 * @param[in] newpgno The page number, if the new node is a branch node.
6498 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
6499 * @return 0 on success, non-zero on failure.
6502 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
6503 unsigned int nflags)
6506 int rc = MDB_SUCCESS, ins_new = 0, new_root = 0, newpos = 1, did_split = 0;
6509 unsigned int i, j, split_indx, nkeys, pmax;
6511 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
6513 MDB_page *mp, *rp, *pp;
6518 mp = mc->mc_pg[mc->mc_top];
6519 newindx = mc->mc_ki[mc->mc_top];
6521 DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
6522 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
6523 DKEY(newkey), mc->mc_ki[mc->mc_top]);
6525 /* Create a right sibling. */
6526 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
6528 DPRINTF("new right sibling: page %zu", rp->mp_pgno);
6530 if (mc->mc_snum < 2) {
6531 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
6533 /* shift current top to make room for new parent */
6534 mc->mc_pg[1] = mc->mc_pg[0];
6535 mc->mc_ki[1] = mc->mc_ki[0];
6538 mc->mc_db->md_root = pp->mp_pgno;
6539 DPRINTF("root split! new root = %zu", pp->mp_pgno);
6540 mc->mc_db->md_depth++;
6543 /* Add left (implicit) pointer. */
6544 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
6545 /* undo the pre-push */
6546 mc->mc_pg[0] = mc->mc_pg[1];
6547 mc->mc_ki[0] = mc->mc_ki[1];
6548 mc->mc_db->md_root = mp->mp_pgno;
6549 mc->mc_db->md_depth--;
6556 ptop = mc->mc_top-1;
6557 DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
6560 mc->mc_flags |= C_SPLITTING;
6561 mdb_cursor_copy(mc, &mn);
6562 mn.mc_pg[mn.mc_top] = rp;
6563 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
6565 if (nflags & MDB_APPEND) {
6566 mn.mc_ki[mn.mc_top] = 0;
6568 split_indx = newindx;
6573 nkeys = NUMKEYS(mp);
6574 split_indx = nkeys / 2;
6575 if (newindx < split_indx)
6581 unsigned int lsize, rsize, ksize;
6582 /* Move half of the keys to the right sibling */
6584 x = mc->mc_ki[mc->mc_top] - split_indx;
6585 ksize = mc->mc_db->md_pad;
6586 split = LEAF2KEY(mp, split_indx, ksize);
6587 rsize = (nkeys - split_indx) * ksize;
6588 lsize = (nkeys - split_indx) * sizeof(indx_t);
6589 mp->mp_lower -= lsize;
6590 rp->mp_lower += lsize;
6591 mp->mp_upper += rsize - lsize;
6592 rp->mp_upper -= rsize - lsize;
6593 sepkey.mv_size = ksize;
6594 if (newindx == split_indx) {
6595 sepkey.mv_data = newkey->mv_data;
6597 sepkey.mv_data = split;
6600 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
6601 memcpy(rp->mp_ptrs, split, rsize);
6602 sepkey.mv_data = rp->mp_ptrs;
6603 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
6604 memcpy(ins, newkey->mv_data, ksize);
6605 mp->mp_lower += sizeof(indx_t);
6606 mp->mp_upper -= ksize - sizeof(indx_t);
6609 memcpy(rp->mp_ptrs, split, x * ksize);
6610 ins = LEAF2KEY(rp, x, ksize);
6611 memcpy(ins, newkey->mv_data, ksize);
6612 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
6613 rp->mp_lower += sizeof(indx_t);
6614 rp->mp_upper -= ksize - sizeof(indx_t);
6615 mc->mc_ki[mc->mc_top] = x;
6616 mc->mc_pg[mc->mc_top] = rp;
6621 /* For leaf pages, check the split point based on what
6622 * fits where, since otherwise mdb_node_add can fail.
6624 * This check is only needed when the data items are
6625 * relatively large, such that being off by one will
6626 * make the difference between success or failure.
6628 * It's also relevant if a page happens to be laid out
6629 * such that one half of its nodes are all "small" and
6630 * the other half of its nodes are "large." If the new
6631 * item is also "large" and falls on the half with
6632 * "large" nodes, it also may not fit.
6635 unsigned int psize, nsize;
6636 /* Maximum free space in an empty page */
6637 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
6638 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
6639 if ((nkeys < 20) || (nsize > pmax/16)) {
6640 if (newindx <= split_indx) {
6643 for (i=0; i<split_indx; i++) {
6644 node = NODEPTR(mp, i);
6645 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
6646 if (F_ISSET(node->mn_flags, F_BIGDATA))
6647 psize += sizeof(pgno_t);
6649 psize += NODEDSZ(node);
6653 split_indx = newindx;
6664 for (i=nkeys-1; i>=split_indx; i--) {
6665 node = NODEPTR(mp, i);
6666 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
6667 if (F_ISSET(node->mn_flags, F_BIGDATA))
6668 psize += sizeof(pgno_t);
6670 psize += NODEDSZ(node);
6674 split_indx = newindx;
6685 /* First find the separating key between the split pages.
6686 * The case where newindx == split_indx is ambiguous; the
6687 * new item could go to the new page or stay on the original
6688 * page. If newpos == 1 it goes to the new page.
6690 if (newindx == split_indx && newpos) {
6691 sepkey.mv_size = newkey->mv_size;
6692 sepkey.mv_data = newkey->mv_data;
6694 node = NODEPTR(mp, split_indx);
6695 sepkey.mv_size = node->mn_ksize;
6696 sepkey.mv_data = NODEKEY(node);
6700 DPRINTF("separator is [%s]", DKEY(&sepkey));
6702 /* Copy separator key to the parent.
6704 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
6708 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
6711 if (mn.mc_snum == mc->mc_snum) {
6712 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
6713 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
6714 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
6715 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
6720 /* Right page might now have changed parent.
6721 * Check if left page also changed parent.
6723 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
6724 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
6725 for (i=0; i<ptop; i++) {
6726 mc->mc_pg[i] = mn.mc_pg[i];
6727 mc->mc_ki[i] = mn.mc_ki[i];
6729 mc->mc_pg[ptop] = mn.mc_pg[ptop];
6730 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
6734 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
6737 mc->mc_flags ^= C_SPLITTING;
6738 if (rc != MDB_SUCCESS) {
6741 if (nflags & MDB_APPEND) {
6742 mc->mc_pg[mc->mc_top] = rp;
6743 mc->mc_ki[mc->mc_top] = 0;
6744 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
6747 for (i=0; i<mc->mc_top; i++)
6748 mc->mc_ki[i] = mn.mc_ki[i];
6755 /* Move half of the keys to the right sibling. */
6757 /* grab a page to hold a temporary copy */
6758 copy = mdb_page_malloc(mc);
6762 copy->mp_pgno = mp->mp_pgno;
6763 copy->mp_flags = mp->mp_flags;
6764 copy->mp_lower = PAGEHDRSZ;
6765 copy->mp_upper = mc->mc_txn->mt_env->me_psize;
6766 mc->mc_pg[mc->mc_top] = copy;
6767 for (i = j = 0; i <= nkeys; j++) {
6768 if (i == split_indx) {
6769 /* Insert in right sibling. */
6770 /* Reset insert index for right sibling. */
6771 if (i != newindx || (newpos ^ ins_new)) {
6773 mc->mc_pg[mc->mc_top] = rp;
6777 if (i == newindx && !ins_new) {
6778 /* Insert the original entry that caused the split. */
6779 rkey.mv_data = newkey->mv_data;
6780 rkey.mv_size = newkey->mv_size;
6789 /* Update index for the new key. */
6790 mc->mc_ki[mc->mc_top] = j;
6791 } else if (i == nkeys) {
6794 node = NODEPTR(mp, i);
6795 rkey.mv_data = NODEKEY(node);
6796 rkey.mv_size = node->mn_ksize;
6798 xdata.mv_data = NODEDATA(node);
6799 xdata.mv_size = NODEDSZ(node);
6802 pgno = NODEPGNO(node);
6803 flags = node->mn_flags;
6808 if (!IS_LEAF(mp) && j == 0) {
6809 /* First branch index doesn't need key data. */
6813 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
6817 nkeys = NUMKEYS(copy);
6818 for (i=0; i<nkeys; i++)
6819 mp->mp_ptrs[i] = copy->mp_ptrs[i];
6820 mp->mp_lower = copy->mp_lower;
6821 mp->mp_upper = copy->mp_upper;
6822 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
6823 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
6825 /* reset back to original page */
6826 if (newindx < split_indx || (!newpos && newindx == split_indx)) {
6827 mc->mc_pg[mc->mc_top] = mp;
6828 if (nflags & MDB_RESERVE) {
6829 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6830 if (!(node->mn_flags & F_BIGDATA))
6831 newdata->mv_data = NODEDATA(node);
6837 /* return tmp page to freelist */
6838 mdb_page_free(mc->mc_txn->mt_env, copy);
6841 /* Adjust other cursors pointing to mp */
6842 MDB_cursor *m2, *m3;
6843 MDB_dbi dbi = mc->mc_dbi;
6844 int fixup = NUMKEYS(mp);
6846 if (mc->mc_flags & C_SUB)
6849 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6850 if (m2 == mc) continue;
6851 if (mc->mc_flags & C_SUB)
6852 m3 = &m2->mc_xcursor->mx_cursor;
6855 if (!(m3->mc_flags & C_INITIALIZED))
6857 if (m3->mc_flags & C_SPLITTING)
6862 for (k=m3->mc_top; k>=0; k--) {
6863 m3->mc_ki[k+1] = m3->mc_ki[k];
6864 m3->mc_pg[k+1] = m3->mc_pg[k];
6866 if (m3->mc_ki[0] >= split_indx) {
6871 m3->mc_pg[0] = mc->mc_pg[0];
6875 if (m3->mc_pg[mc->mc_top] == mp) {
6876 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
6877 m3->mc_ki[mc->mc_top]++;
6878 if (m3->mc_ki[mc->mc_top] >= fixup) {
6879 m3->mc_pg[mc->mc_top] = rp;
6880 m3->mc_ki[mc->mc_top] -= fixup;
6881 m3->mc_ki[ptop] = mn.mc_ki[ptop];
6883 } else if (!did_split && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
6884 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
6893 mdb_put(MDB_txn *txn, MDB_dbi dbi,
6894 MDB_val *key, MDB_val *data, unsigned int flags)
6899 assert(key != NULL);
6900 assert(data != NULL);
6902 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6905 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
6909 if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
6913 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND)) != flags)
6916 mdb_cursor_init(&mc, txn, dbi, &mx);
6917 return mdb_cursor_put(&mc, key, data, flags);
6921 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
6923 if ((flag & CHANGEABLE) != flag)
6926 env->me_flags |= flag;
6928 env->me_flags &= ~flag;
6933 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
6938 *arg = env->me_flags;
6943 mdb_env_get_path(MDB_env *env, const char **arg)
6948 *arg = env->me_path;
6952 /** Common code for #mdb_stat() and #mdb_env_stat().
6953 * @param[in] env the environment to operate in.
6954 * @param[in] db the #MDB_db record containing the stats to return.
6955 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
6956 * @return 0, this function always succeeds.
6959 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
6961 arg->ms_psize = env->me_psize;
6962 arg->ms_depth = db->md_depth;
6963 arg->ms_branch_pages = db->md_branch_pages;
6964 arg->ms_leaf_pages = db->md_leaf_pages;
6965 arg->ms_overflow_pages = db->md_overflow_pages;
6966 arg->ms_entries = db->md_entries;
6971 mdb_env_stat(MDB_env *env, MDB_stat *arg)
6975 if (env == NULL || arg == NULL)
6978 toggle = mdb_env_pick_meta(env);
6980 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
6984 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
6988 if (env == NULL || arg == NULL)
6991 toggle = mdb_env_pick_meta(env);
6992 arg->me_mapaddr = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : 0;
6993 arg->me_mapsize = env->me_mapsize;
6994 arg->me_maxreaders = env->me_maxreaders;
6995 arg->me_numreaders = env->me_numreaders;
6996 arg->me_last_pgno = env->me_metas[toggle]->mm_last_pg;
6997 arg->me_last_txnid = env->me_metas[toggle]->mm_txnid;
7001 /** Set the default comparison functions for a database.
7002 * Called immediately after a database is opened to set the defaults.
7003 * The user can then override them with #mdb_set_compare() or
7004 * #mdb_set_dupsort().
7005 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
7006 * @param[in] dbi A database handle returned by #mdb_dbi_open()
7009 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
7011 uint16_t f = txn->mt_dbs[dbi].md_flags;
7013 txn->mt_dbxs[dbi].md_cmp =
7014 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
7015 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
7017 txn->mt_dbxs[dbi].md_dcmp =
7018 !(f & MDB_DUPSORT) ? 0 :
7019 ((f & MDB_INTEGERDUP)
7020 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
7021 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
7024 #define PERSISTENT_FLAGS 0xffff
7025 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
7026 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
7027 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
7033 int rc, dbflag, exact;
7034 unsigned int unused = 0;
7037 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
7038 mdb_default_cmp(txn, FREE_DBI);
7041 if ((flags & VALID_FLAGS) != flags)
7047 if (flags & PERSISTENT_FLAGS) {
7048 uint16_t f2 = flags & PERSISTENT_FLAGS;
7049 /* make sure flag changes get committed */
7050 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
7051 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
7052 txn->mt_flags |= MDB_TXN_DIRTY;
7055 mdb_default_cmp(txn, MAIN_DBI);
7059 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
7060 mdb_default_cmp(txn, MAIN_DBI);
7063 /* Is the DB already open? */
7065 for (i=2; i<txn->mt_numdbs; i++) {
7066 if (!txn->mt_dbxs[i].md_name.mv_size) {
7067 /* Remember this free slot */
7068 if (!unused) unused = i;
7071 if (len == txn->mt_dbxs[i].md_name.mv_size &&
7072 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
7078 /* If no free slot and max hit, fail */
7079 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
7080 return MDB_DBS_FULL;
7082 /* Find the DB info */
7086 key.mv_data = (void *)name;
7087 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
7088 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
7089 if (rc == MDB_SUCCESS) {
7090 /* make sure this is actually a DB */
7091 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
7092 if (!(node->mn_flags & F_SUBDATA))
7094 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
7095 /* Create if requested */
7097 data.mv_size = sizeof(MDB_db);
7098 data.mv_data = &dummy;
7099 memset(&dummy, 0, sizeof(dummy));
7100 dummy.md_root = P_INVALID;
7101 dummy.md_flags = flags & PERSISTENT_FLAGS;
7102 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
7106 /* OK, got info, add to table */
7107 if (rc == MDB_SUCCESS) {
7108 unsigned int slot = unused ? unused : txn->mt_numdbs;
7109 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
7110 txn->mt_dbxs[slot].md_name.mv_size = len;
7111 txn->mt_dbxs[slot].md_rel = NULL;
7112 txn->mt_dbflags[slot] = dbflag;
7113 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
7115 txn->mt_env->me_dbflags[slot] = mdflags = txn->mt_dbs[slot].md_flags;
7116 mdb_default_cmp(txn, slot);
7119 txn->mt_env->me_numdbs++;
7121 /* Open the DB in parent txns as well */
7122 while ((txn = txn->mt_parent) != NULL) {
7123 txn->mt_dbflags[slot] = DB_STALE;
7124 txn->mt_dbs[slot].md_flags = mdflags;
7133 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
7135 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
7138 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
7141 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
7144 if (dbi <= MAIN_DBI || dbi >= env->me_numdbs)
7146 ptr = env->me_dbxs[dbi].md_name.mv_data;
7147 env->me_dbxs[dbi].md_name.mv_data = NULL;
7148 env->me_dbxs[dbi].md_name.mv_size = 0;
7152 /** Add all the DB's pages to the free list.
7153 * @param[in] mc Cursor on the DB to free.
7154 * @param[in] subs non-Zero to check for sub-DBs in this DB.
7155 * @return 0 on success, non-zero on failure.
7158 mdb_drop0(MDB_cursor *mc, int subs)
7162 rc = mdb_page_search(mc, NULL, 0);
7163 if (rc == MDB_SUCCESS) {
7168 /* LEAF2 pages have no nodes, cannot have sub-DBs */
7169 if (!subs || IS_LEAF2(mc->mc_pg[mc->mc_top]))
7172 mdb_cursor_copy(mc, &mx);
7173 while (mc->mc_snum > 0) {
7174 if (IS_LEAF(mc->mc_pg[mc->mc_top])) {
7175 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
7176 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
7177 if (ni->mn_flags & F_SUBDATA) {
7178 mdb_xcursor_init1(mc, ni);
7179 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
7185 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
7187 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
7190 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
7195 rc = mdb_cursor_sibling(mc, 1);
7197 /* no more siblings, go back to beginning
7198 * of previous level.
7201 for (i=1; i<mc->mc_top; i++)
7202 mc->mc_pg[i] = mx.mc_pg[i];
7206 mdb_midl_append(&mc->mc_txn->mt_free_pgs,
7207 mc->mc_db->md_root);
7212 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
7217 if (!txn || !dbi || dbi >= txn->mt_numdbs || (unsigned)del > 1)
7220 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
7223 rc = mdb_cursor_open(txn, dbi, &mc);
7227 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
7231 /* Can't delete the main DB */
7232 if (del && dbi > MAIN_DBI) {
7233 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
7235 txn->mt_dbflags[dbi] = DB_STALE;
7236 mdb_dbi_close(txn->mt_env, dbi);
7239 /* reset the DB record, mark it dirty */
7240 txn->mt_dbflags[dbi] |= DB_DIRTY;
7241 txn->mt_dbs[dbi].md_depth = 0;
7242 txn->mt_dbs[dbi].md_branch_pages = 0;
7243 txn->mt_dbs[dbi].md_leaf_pages = 0;
7244 txn->mt_dbs[dbi].md_overflow_pages = 0;
7245 txn->mt_dbs[dbi].md_entries = 0;
7246 txn->mt_dbs[dbi].md_root = P_INVALID;
7248 if (!txn->mt_u.dirty_list[0].mid) {
7251 /* make sure we have at least one dirty page in this txn
7252 * otherwise these changes will be ignored.
7254 key.mv_size = sizeof(txnid_t);
7255 key.mv_data = &txn->mt_txnid;
7256 data.mv_size = sizeof(MDB_ID);
7257 data.mv_data = txn->mt_free_pgs;
7258 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
7259 rc = mdb_cursor_put(&m2, &key, &data, 0);
7263 mdb_cursor_close(mc);
7267 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
7269 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
7272 txn->mt_dbxs[dbi].md_cmp = cmp;
7276 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
7278 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
7281 txn->mt_dbxs[dbi].md_dcmp = cmp;
7285 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
7287 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
7290 txn->mt_dbxs[dbi].md_rel = rel;
7294 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
7296 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
7299 txn->mt_dbxs[dbi].md_relctx = ctx;