2 * @brief memory-mapped database library
4 * A Btree-based database management library modeled loosely on the
5 * BerkeleyDB API, but much simplified.
8 * Copyright 2011-2013 Howard Chu, Symas Corp.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted only as authorized by the OpenLDAP
15 * A copy of this license is available in the file LICENSE in the
16 * top-level directory of the distribution or, alternatively, at
17 * <http://www.OpenLDAP.org/license.html>.
19 * This code is derived from btree.c written by Martin Hedenfalk.
21 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
23 * Permission to use, copy, modify, and distribute this software for any
24 * purpose with or without fee is hereby granted, provided that the above
25 * copyright notice and this permission notice appear in all copies.
27 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
28 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
29 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
30 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
31 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
32 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
33 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
38 #include <sys/types.h>
40 #include <sys/param.h>
46 #ifdef HAVE_SYS_FILE_H
63 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
64 #include <netinet/in.h>
65 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
68 #if defined(__APPLE__) || defined (BSD)
69 # define MDB_USE_POSIX_SEM 1
70 # define MDB_FDATASYNC fsync
71 #elif defined(ANDROID)
72 # define MDB_FDATASYNC fsync
77 #ifdef MDB_USE_POSIX_SEM
78 #include <semaphore.h>
83 #include <valgrind/memcheck.h>
84 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
85 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
86 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
87 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
88 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
90 #define VGMEMP_CREATE(h,r,z)
91 #define VGMEMP_ALLOC(h,a,s)
92 #define VGMEMP_FREE(h,a)
93 #define VGMEMP_DESTROY(h)
94 #define VGMEMP_DEFINED(a,s)
98 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
99 /* Solaris just defines one or the other */
100 # define LITTLE_ENDIAN 1234
101 # define BIG_ENDIAN 4321
102 # ifdef _LITTLE_ENDIAN
103 # define BYTE_ORDER LITTLE_ENDIAN
105 # define BYTE_ORDER BIG_ENDIAN
108 # define BYTE_ORDER __BYTE_ORDER
112 #ifndef LITTLE_ENDIAN
113 #define LITTLE_ENDIAN __LITTLE_ENDIAN
116 #define BIG_ENDIAN __BIG_ENDIAN
119 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
120 #define MISALIGNED_OK 1
126 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
127 # error "Unknown or unsupported endianness (BYTE_ORDER)"
128 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
129 # error "Two's complement, reasonably sized integer types, please"
132 /** @defgroup internal MDB Internals
135 /** @defgroup compat Windows Compatibility Macros
136 * A bunch of macros to minimize the amount of platform-specific ifdefs
137 * needed throughout the rest of the code. When the features this library
138 * needs are similar enough to POSIX to be hidden in a one-or-two line
139 * replacement, this macro approach is used.
143 #define pthread_t DWORD
144 #define pthread_mutex_t HANDLE
145 #define pthread_key_t DWORD
146 #define pthread_self() GetCurrentThreadId()
147 #define pthread_key_create(x,y) \
148 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
149 #define pthread_key_delete(x) TlsFree(x)
150 #define pthread_getspecific(x) TlsGetValue(x)
151 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
152 #define pthread_mutex_unlock(x) ReleaseMutex(x)
153 #define pthread_mutex_lock(x) WaitForSingleObject(x, INFINITE)
154 #define LOCK_MUTEX_R(env) pthread_mutex_lock((env)->me_rmutex)
155 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock((env)->me_rmutex)
156 #define LOCK_MUTEX_W(env) pthread_mutex_lock((env)->me_wmutex)
157 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock((env)->me_wmutex)
158 #define getpid() GetCurrentProcessId()
159 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
160 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
161 #define ErrCode() GetLastError()
162 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
163 #define close(fd) (CloseHandle(fd) ? 0 : -1)
164 #define munmap(ptr,len) UnmapViewOfFile(ptr)
167 #ifdef MDB_USE_POSIX_SEM
169 #define LOCK_MUTEX_R(env) mdb_sem_wait((env)->me_rmutex)
170 #define UNLOCK_MUTEX_R(env) sem_post((env)->me_rmutex)
171 #define LOCK_MUTEX_W(env) mdb_sem_wait((env)->me_wmutex)
172 #define UNLOCK_MUTEX_W(env) sem_post((env)->me_wmutex)
175 mdb_sem_wait(sem_t *sem)
178 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
183 /** Lock the reader mutex.
185 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
186 /** Unlock the reader mutex.
188 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
190 /** Lock the writer mutex.
191 * Only a single write transaction is allowed at a time. Other writers
192 * will block waiting for this mutex.
194 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
195 /** Unlock the writer mutex.
197 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
198 #endif /* MDB_USE_POSIX_SEM */
200 /** Get the error code for the last failed system function.
202 #define ErrCode() errno
204 /** An abstraction for a file handle.
205 * On POSIX systems file handles are small integers. On Windows
206 * they're opaque pointers.
210 /** A value for an invalid file handle.
211 * Mainly used to initialize file variables and signify that they are
214 #define INVALID_HANDLE_VALUE (-1)
216 /** Get the size of a memory page for the system.
217 * This is the basic size that the platform's memory manager uses, and is
218 * fundamental to the use of memory-mapped files.
220 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
223 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
226 #define MNAME_LEN (sizeof(pthread_mutex_t))
232 /** A flag for opening a file and requesting synchronous data writes.
233 * This is only used when writing a meta page. It's not strictly needed;
234 * we could just do a normal write and then immediately perform a flush.
235 * But if this flag is available it saves us an extra system call.
237 * @note If O_DSYNC is undefined but exists in /usr/include,
238 * preferably set some compiler flag to get the definition.
239 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
242 # define MDB_DSYNC O_DSYNC
246 /** Function for flushing the data of a file. Define this to fsync
247 * if fdatasync() is not supported.
249 #ifndef MDB_FDATASYNC
250 # define MDB_FDATASYNC fdatasync
254 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
265 /** A page number in the database.
266 * Note that 64 bit page numbers are overkill, since pages themselves
267 * already represent 12-13 bits of addressable memory, and the OS will
268 * always limit applications to a maximum of 63 bits of address space.
270 * @note In the #MDB_node structure, we only store 48 bits of this value,
271 * which thus limits us to only 60 bits of addressable data.
273 typedef MDB_ID pgno_t;
275 /** A transaction ID.
276 * See struct MDB_txn.mt_txnid for details.
278 typedef MDB_ID txnid_t;
280 /** @defgroup debug Debug Macros
284 /** Enable debug output.
285 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
286 * read from and written to the database (used for free space management).
291 #if !(__STDC_VERSION__ >= 199901L || defined(__GNUC__))
294 # define DPRINTF (void) /* Vararg macros may be unsupported */
296 static int mdb_debug;
297 static txnid_t mdb_debug_start;
299 /** Print a debug message with printf formatting. */
300 # define DPRINTF(fmt, ...) /**< Requires 2 or more args */ \
301 ((void) ((mdb_debug) && \
302 fprintf(stderr, "%s:%d " fmt "\n", __func__, __LINE__, __VA_ARGS__)))
304 # define DPRINTF(fmt, ...) ((void) 0)
305 # define MDB_DEBUG_SKIP
307 /** Print a debug string.
308 * The string is printed literally, with no format processing.
310 #define DPUTS(arg) DPRINTF("%s", arg)
313 /** A default memory page size.
314 * The actual size is platform-dependent, but we use this for
315 * boot-strapping. We probably should not be using this any more.
316 * The #GET_PAGESIZE() macro is used to get the actual size.
318 * Note that we don't currently support Huge pages. On Linux,
319 * regular data files cannot use Huge pages, and in general
320 * Huge pages aren't actually pageable. We rely on the OS
321 * demand-pager to read our data and page it out when memory
322 * pressure from other processes is high. So until OSs have
323 * actual paging support for Huge pages, they're not viable.
325 #define MDB_PAGESIZE 4096
327 /** The minimum number of keys required in a database page.
328 * Setting this to a larger value will place a smaller bound on the
329 * maximum size of a data item. Data items larger than this size will
330 * be pushed into overflow pages instead of being stored directly in
331 * the B-tree node. This value used to default to 4. With a page size
332 * of 4096 bytes that meant that any item larger than 1024 bytes would
333 * go into an overflow page. That also meant that on average 2-3KB of
334 * each overflow page was wasted space. The value cannot be lower than
335 * 2 because then there would no longer be a tree structure. With this
336 * value, items larger than 2KB will go into overflow pages, and on
337 * average only 1KB will be wasted.
339 #define MDB_MINKEYS 2
341 /** A stamp that identifies a file as an MDB file.
342 * There's nothing special about this value other than that it is easily
343 * recognizable, and it will reflect any byte order mismatches.
345 #define MDB_MAGIC 0xBEEFC0DE
347 /** The version number for a database's datafile format. */
348 #define MDB_DATA_VERSION 1
349 /** The version number for a database's lockfile format. */
350 #define MDB_LOCK_VERSION 1
352 /** @brief The maximum size of a key in the database.
354 * The library rejects bigger keys, and cannot deal with records
355 * with bigger keys stored by a library with bigger max keysize.
357 * We require that keys all fit onto a regular page. This limit
358 * could be raised a bit further if needed; to something just
359 * under #MDB_PAGESIZE / #MDB_MINKEYS.
361 * Note that data items in an #MDB_DUPSORT database are actually keys
362 * of a subDB, so they're also limited to this size.
364 #ifndef MDB_MAXKEYSIZE
365 #define MDB_MAXKEYSIZE 511
368 /** @brief The maximum size of a data item.
370 * We only store a 32 bit value for node sizes.
372 #define MAXDATASIZE 0xffffffffUL
377 * This is used for printing a hex dump of a key's contents.
379 #define DKBUF char kbuf[(MDB_MAXKEYSIZE*2+1)]
380 /** Display a key in hex.
382 * Invoke a function to display a key in hex.
384 #define DKEY(x) mdb_dkey(x, kbuf)
386 #define DKBUF typedef int dummy_kbuf /* so we can put ';' after */
390 /** An invalid page number.
391 * Mainly used to denote an empty tree.
393 #define P_INVALID (~(pgno_t)0)
395 /** Test if the flags \b f are set in a flag word \b w. */
396 #define F_ISSET(w, f) (((w) & (f)) == (f))
398 /** Used for offsets within a single page.
399 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
402 typedef uint16_t indx_t;
404 /** Default size of memory map.
405 * This is certainly too small for any actual applications. Apps should always set
406 * the size explicitly using #mdb_env_set_mapsize().
408 #define DEFAULT_MAPSIZE 1048576
410 /** @defgroup readers Reader Lock Table
411 * Readers don't acquire any locks for their data access. Instead, they
412 * simply record their transaction ID in the reader table. The reader
413 * mutex is needed just to find an empty slot in the reader table. The
414 * slot's address is saved in thread-specific data so that subsequent read
415 * transactions started by the same thread need no further locking to proceed.
417 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
419 * No reader table is used if the database is on a read-only filesystem.
421 * Since the database uses multi-version concurrency control, readers don't
422 * actually need any locking. This table is used to keep track of which
423 * readers are using data from which old transactions, so that we'll know
424 * when a particular old transaction is no longer in use. Old transactions
425 * that have discarded any data pages can then have those pages reclaimed
426 * for use by a later write transaction.
428 * The lock table is constructed such that reader slots are aligned with the
429 * processor's cache line size. Any slot is only ever used by one thread.
430 * This alignment guarantees that there will be no contention or cache
431 * thrashing as threads update their own slot info, and also eliminates
432 * any need for locking when accessing a slot.
434 * A writer thread will scan every slot in the table to determine the oldest
435 * outstanding reader transaction. Any freed pages older than this will be
436 * reclaimed by the writer. The writer doesn't use any locks when scanning
437 * this table. This means that there's no guarantee that the writer will
438 * see the most up-to-date reader info, but that's not required for correct
439 * operation - all we need is to know the upper bound on the oldest reader,
440 * we don't care at all about the newest reader. So the only consequence of
441 * reading stale information here is that old pages might hang around a
442 * while longer before being reclaimed. That's actually good anyway, because
443 * the longer we delay reclaiming old pages, the more likely it is that a
444 * string of contiguous pages can be found after coalescing old pages from
445 * many old transactions together.
448 /** Number of slots in the reader table.
449 * This value was chosen somewhat arbitrarily. 126 readers plus a
450 * couple mutexes fit exactly into 8KB on my development machine.
451 * Applications should set the table size using #mdb_env_set_maxreaders().
453 #define DEFAULT_READERS 126
455 /** The size of a CPU cache line in bytes. We want our lock structures
456 * aligned to this size to avoid false cache line sharing in the
458 * This value works for most CPUs. For Itanium this should be 128.
464 /** The information we store in a single slot of the reader table.
465 * In addition to a transaction ID, we also record the process and
466 * thread ID that owns a slot, so that we can detect stale information,
467 * e.g. threads or processes that went away without cleaning up.
468 * @note We currently don't check for stale records. We simply re-init
469 * the table when we know that we're the only process opening the
472 typedef struct MDB_rxbody {
473 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
474 * Multiple readers that start at the same time will probably have the
475 * same ID here. Again, it's not important to exclude them from
476 * anything; all we need to know is which version of the DB they
477 * started from so we can avoid overwriting any data used in that
478 * particular version.
481 /** The process ID of the process owning this reader txn. */
483 /** The thread ID of the thread owning this txn. */
487 /** The actual reader record, with cacheline padding. */
488 typedef struct MDB_reader {
491 /** shorthand for mrb_txnid */
492 #define mr_txnid mru.mrx.mrb_txnid
493 #define mr_pid mru.mrx.mrb_pid
494 #define mr_tid mru.mrx.mrb_tid
495 /** cache line alignment */
496 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
500 /** The header for the reader table.
501 * The table resides in a memory-mapped file. (This is a different file
502 * than is used for the main database.)
504 * For POSIX the actual mutexes reside in the shared memory of this
505 * mapped file. On Windows, mutexes are named objects allocated by the
506 * kernel; we store the mutex names in this mapped file so that other
507 * processes can grab them. This same approach is also used on
508 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
509 * process-shared POSIX mutexes. For these cases where a named object
510 * is used, the object name is derived from a 64 bit FNV hash of the
511 * environment pathname. As such, naming collisions are extremely
512 * unlikely. If a collision occurs, the results are unpredictable.
514 typedef struct MDB_txbody {
515 /** Stamp identifying this as an MDB file. It must be set
518 /** Version number of this lock file. Must be set to #MDB_LOCK_VERSION. */
519 uint32_t mtb_version;
520 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
521 char mtb_rmname[MNAME_LEN];
523 /** Mutex protecting access to this table.
524 * This is the reader lock that #LOCK_MUTEX_R acquires.
526 pthread_mutex_t mtb_mutex;
528 /** The ID of the last transaction committed to the database.
529 * This is recorded here only for convenience; the value can always
530 * be determined by reading the main database meta pages.
533 /** The number of slots that have been used in the reader table.
534 * This always records the maximum count, it is not decremented
535 * when readers release their slots.
537 unsigned mtb_numreaders;
540 /** The actual reader table definition. */
541 typedef struct MDB_txninfo {
544 #define mti_magic mt1.mtb.mtb_magic
545 #define mti_version mt1.mtb.mtb_version
546 #define mti_mutex mt1.mtb.mtb_mutex
547 #define mti_rmname mt1.mtb.mtb_rmname
548 #define mti_txnid mt1.mtb.mtb_txnid
549 #define mti_numreaders mt1.mtb.mtb_numreaders
550 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
553 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
554 char mt2_wmname[MNAME_LEN];
555 #define mti_wmname mt2.mt2_wmname
557 pthread_mutex_t mt2_wmutex;
558 #define mti_wmutex mt2.mt2_wmutex
560 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
562 MDB_reader mti_readers[1];
566 /** Common header for all page types.
567 * Overflow records occupy a number of contiguous pages with no
568 * headers on any page after the first.
570 typedef struct MDB_page {
571 #define mp_pgno mp_p.p_pgno
572 #define mp_next mp_p.p_next
574 pgno_t p_pgno; /**< page number */
575 void * p_next; /**< for in-memory list of freed structs */
578 /** @defgroup mdb_page Page Flags
580 * Flags for the page headers.
583 #define P_BRANCH 0x01 /**< branch page */
584 #define P_LEAF 0x02 /**< leaf page */
585 #define P_OVERFLOW 0x04 /**< overflow page */
586 #define P_META 0x08 /**< meta page */
587 #define P_DIRTY 0x10 /**< dirty page */
588 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
589 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
590 #define P_KEEP 0x8000 /**< leave this page alone during spill */
592 uint16_t mp_flags; /**< @ref mdb_page */
593 #define mp_lower mp_pb.pb.pb_lower
594 #define mp_upper mp_pb.pb.pb_upper
595 #define mp_pages mp_pb.pb_pages
598 indx_t pb_lower; /**< lower bound of free space */
599 indx_t pb_upper; /**< upper bound of free space */
601 uint32_t pb_pages; /**< number of overflow pages */
603 indx_t mp_ptrs[1]; /**< dynamic size */
606 /** Size of the page header, excluding dynamic data at the end */
607 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
609 /** Address of first usable data byte in a page, after the header */
610 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
612 /** Number of nodes on a page */
613 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
615 /** The amount of space remaining in the page */
616 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
618 /** The percentage of space used in the page, in tenths of a percent. */
619 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
620 ((env)->me_psize - PAGEHDRSZ))
621 /** The minimum page fill factor, in tenths of a percent.
622 * Pages emptier than this are candidates for merging.
624 #define FILL_THRESHOLD 250
626 /** Test if a page is a leaf page */
627 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
628 /** Test if a page is a LEAF2 page */
629 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
630 /** Test if a page is a branch page */
631 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
632 /** Test if a page is an overflow page */
633 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
634 /** Test if a page is a sub page */
635 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
637 /** The number of overflow pages needed to store the given size. */
638 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
640 /** Header for a single key/data pair within a page.
641 * We guarantee 2-byte alignment for nodes.
643 typedef struct MDB_node {
644 /** lo and hi are used for data size on leaf nodes and for
645 * child pgno on branch nodes. On 64 bit platforms, flags
646 * is also used for pgno. (Branch nodes have no flags).
647 * They are in host byte order in case that lets some
648 * accesses be optimized into a 32-bit word access.
650 #define mn_lo mn_offset[BYTE_ORDER!=LITTLE_ENDIAN]
651 #define mn_hi mn_offset[BYTE_ORDER==LITTLE_ENDIAN] /**< part of dsize or pgno */
652 unsigned short mn_offset[2]; /**< storage for #mn_lo and #mn_hi */
653 /** @defgroup mdb_node Node Flags
655 * Flags for node headers.
658 #define F_BIGDATA 0x01 /**< data put on overflow page */
659 #define F_SUBDATA 0x02 /**< data is a sub-database */
660 #define F_DUPDATA 0x04 /**< data has duplicates */
662 /** valid flags for #mdb_node_add() */
663 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
666 unsigned short mn_flags; /**< @ref mdb_node */
667 unsigned short mn_ksize; /**< key size */
668 char mn_data[1]; /**< key and data are appended here */
671 /** Size of the node header, excluding dynamic data at the end */
672 #define NODESIZE offsetof(MDB_node, mn_data)
674 /** Bit position of top word in page number, for shifting mn_flags */
675 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
677 /** Size of a node in a branch page with a given key.
678 * This is just the node header plus the key, there is no data.
680 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
682 /** Size of a node in a leaf page with a given key and data.
683 * This is node header plus key plus data size.
685 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
687 /** Address of node \b i in page \b p */
688 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
690 /** Address of the key for the node */
691 #define NODEKEY(node) (void *)((node)->mn_data)
693 /** Address of the data for a node */
694 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
696 /** Get the page number pointed to by a branch node */
697 #define NODEPGNO(node) \
698 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
699 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
700 /** Set the page number in a branch node */
701 #define SETPGNO(node,pgno) do { \
702 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
703 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
705 /** Get the size of the data in a leaf node */
706 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
707 /** Set the size of the data for a leaf node */
708 #define SETDSZ(node,size) do { \
709 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
710 /** The size of a key in a node */
711 #define NODEKSZ(node) ((node)->mn_ksize)
713 /** Copy a page number from src to dst */
715 #define COPY_PGNO(dst,src) dst = src
717 #if SIZE_MAX > 4294967295UL
718 #define COPY_PGNO(dst,src) do { \
719 unsigned short *s, *d; \
720 s = (unsigned short *)&(src); \
721 d = (unsigned short *)&(dst); \
728 #define COPY_PGNO(dst,src) do { \
729 unsigned short *s, *d; \
730 s = (unsigned short *)&(src); \
731 d = (unsigned short *)&(dst); \
737 /** The address of a key in a LEAF2 page.
738 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
739 * There are no node headers, keys are stored contiguously.
741 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
743 /** Set the \b node's key into \b key, if requested. */
744 #define MDB_GET_KEY(node, key) { if ((key) != NULL) { \
745 (key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node); } }
747 /** Information about a single database in the environment. */
748 typedef struct MDB_db {
749 uint32_t md_pad; /**< also ksize for LEAF2 pages */
750 uint16_t md_flags; /**< @ref mdb_dbi_open */
751 uint16_t md_depth; /**< depth of this tree */
752 pgno_t md_branch_pages; /**< number of internal pages */
753 pgno_t md_leaf_pages; /**< number of leaf pages */
754 pgno_t md_overflow_pages; /**< number of overflow pages */
755 size_t md_entries; /**< number of data items */
756 pgno_t md_root; /**< the root page of this tree */
759 /** mdb_dbi_open flags */
760 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
761 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
762 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
763 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
765 /** Handle for the DB used to track free pages. */
767 /** Handle for the default DB. */
770 /** Meta page content. */
771 typedef struct MDB_meta {
772 /** Stamp identifying this as an MDB file. It must be set
775 /** Version number of this lock file. Must be set to #MDB_DATA_VERSION. */
777 void *mm_address; /**< address for fixed mapping */
778 size_t mm_mapsize; /**< size of mmap region */
779 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
780 /** The size of pages used in this DB */
781 #define mm_psize mm_dbs[0].md_pad
782 /** Any persistent environment flags. @ref mdb_env */
783 #define mm_flags mm_dbs[0].md_flags
784 pgno_t mm_last_pg; /**< last used page in file */
785 txnid_t mm_txnid; /**< txnid that committed this page */
788 /** Buffer for a stack-allocated dirty page.
789 * The members define size and alignment, and silence type
790 * aliasing warnings. They are not used directly; that could
791 * mean incorrectly using several union members in parallel.
793 typedef union MDB_pagebuf {
794 char mb_raw[MDB_PAGESIZE];
797 char mm_pad[PAGEHDRSZ];
802 /** Auxiliary DB info.
803 * The information here is mostly static/read-only. There is
804 * only a single copy of this record in the environment.
806 typedef struct MDB_dbx {
807 MDB_val md_name; /**< name of the database */
808 MDB_cmp_func *md_cmp; /**< function for comparing keys */
809 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
810 MDB_rel_func *md_rel; /**< user relocate function */
811 void *md_relctx; /**< user-provided context for md_rel */
814 /** A database transaction.
815 * Every operation requires a transaction handle.
818 MDB_txn *mt_parent; /**< parent of a nested txn */
819 MDB_txn *mt_child; /**< nested txn under this txn */
820 pgno_t mt_next_pgno; /**< next unallocated page */
821 /** The ID of this transaction. IDs are integers incrementing from 1.
822 * Only committed write transactions increment the ID. If a transaction
823 * aborts, the ID may be re-used by the next writer.
826 MDB_env *mt_env; /**< the DB environment */
827 /** The list of pages that became unused during this transaction.
830 /** The list of dirty pages we temporarily wrote to disk
831 * because the dirty list was full.
833 MDB_IDL mt_spill_pgs;
835 MDB_ID2L dirty_list; /**< for write txns: modified pages */
836 MDB_reader *reader; /**< this thread's reader table slot or NULL */
838 /** Array of records for each DB known in the environment. */
840 /** Array of MDB_db records for each known DB */
842 /** @defgroup mt_dbflag Transaction DB Flags
846 #define DB_DIRTY 0x01 /**< DB was written in this txn */
847 #define DB_STALE 0x02 /**< DB record is older than txnID */
848 #define DB_NEW 0x04 /**< DB handle opened in this txn */
849 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
851 /** In write txns, array of cursors for each DB */
852 MDB_cursor **mt_cursors;
853 /** Array of flags for each DB */
854 unsigned char *mt_dbflags;
855 /** Number of DB records in use. This number only ever increments;
856 * we don't decrement it when individual DB handles are closed.
860 /** @defgroup mdb_txn Transaction Flags
864 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
865 #define MDB_TXN_ERROR 0x02 /**< an error has occurred */
866 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
867 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
869 unsigned int mt_flags; /**< @ref mdb_txn */
870 /** dirty_list maxsize - # of allocated pages allowed, including in parent txns */
871 unsigned int mt_dirty_room;
872 /** Tracks which of the two meta pages was used at the start
873 * of this transaction.
875 unsigned int mt_toggle;
878 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
879 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
880 * raise this on a 64 bit machine.
882 #define CURSOR_STACK 32
886 /** Cursors are used for all DB operations */
888 /** Next cursor on this DB in this txn */
890 /** Backup of the original cursor if this cursor is a shadow */
891 MDB_cursor *mc_backup;
892 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
893 struct MDB_xcursor *mc_xcursor;
894 /** The transaction that owns this cursor */
896 /** The database handle this cursor operates on */
898 /** The database record for this cursor */
900 /** The database auxiliary record for this cursor */
902 /** The @ref mt_dbflag for this database */
903 unsigned char *mc_dbflag;
904 unsigned short mc_snum; /**< number of pushed pages */
905 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
906 /** @defgroup mdb_cursor Cursor Flags
908 * Cursor state flags.
911 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
912 #define C_EOF 0x02 /**< No more data */
913 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
914 #define C_SPLITTING 0x20 /**< Cursor is in page_split */
915 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
917 unsigned int mc_flags; /**< @ref mdb_cursor */
918 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
919 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
922 /** Context for sorted-dup records.
923 * We could have gone to a fully recursive design, with arbitrarily
924 * deep nesting of sub-databases. But for now we only handle these
925 * levels - main DB, optional sub-DB, sorted-duplicate DB.
927 typedef struct MDB_xcursor {
928 /** A sub-cursor for traversing the Dup DB */
929 MDB_cursor mx_cursor;
930 /** The database record for this Dup DB */
932 /** The auxiliary DB record for this Dup DB */
934 /** The @ref mt_dbflag for this Dup DB */
935 unsigned char mx_dbflag;
938 /** State of FreeDB old pages, stored in the MDB_env */
939 typedef struct MDB_pgstate {
940 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
941 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
944 /** The database environment. */
946 HANDLE me_fd; /**< The main data file */
947 HANDLE me_lfd; /**< The lock file */
948 HANDLE me_mfd; /**< just for writing the meta pages */
949 /** Failed to update the meta page. Probably an I/O error. */
950 #define MDB_FATAL_ERROR 0x80000000U
951 /** Some fields are initialized. */
952 #define MDB_ENV_ACTIVE 0x20000000U
953 /** me_txkey is set */
954 #define MDB_ENV_TXKEY 0x10000000U
955 uint32_t me_flags; /**< @ref mdb_env */
956 unsigned int me_psize; /**< size of a page, from #GET_PAGESIZE */
957 unsigned int me_maxreaders; /**< size of the reader table */
958 unsigned int me_numreaders; /**< max numreaders set by this env */
959 MDB_dbi me_numdbs; /**< number of DBs opened */
960 MDB_dbi me_maxdbs; /**< size of the DB table */
961 pid_t me_pid; /**< process ID of this env */
962 char *me_path; /**< path to the DB files */
963 char *me_map; /**< the memory map of the data file */
964 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
965 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
966 MDB_txn *me_txn; /**< current write transaction */
967 size_t me_mapsize; /**< size of the data memory map */
968 off_t me_size; /**< current file size */
969 pgno_t me_maxpg; /**< me_mapsize / me_psize */
970 MDB_dbx *me_dbxs; /**< array of static DB info */
971 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
972 pthread_key_t me_txkey; /**< thread-key for readers */
973 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
974 # define me_pglast me_pgstate.mf_pglast
975 # define me_pghead me_pgstate.mf_pghead
976 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
977 /** IDL of pages that became unused in a write txn */
979 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
980 MDB_ID2L me_dirty_list;
981 /** Max number of freelist items that can fit in a single overflow page */
983 /** Max size of a node on a page */
984 unsigned int me_nodemax;
986 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
988 #elif defined(MDB_USE_POSIX_SEM)
989 sem_t *me_rmutex; /* Shared mutexes are not supported */
994 /** Nested transaction */
995 typedef struct MDB_ntxn {
996 MDB_txn mnt_txn; /* the transaction */
997 MDB_pgstate mnt_pgstate; /* parent transaction's saved freestate */
1000 /** max number of pages to commit in one writev() call */
1001 #define MDB_COMMIT_PAGES 64
1002 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1003 #undef MDB_COMMIT_PAGES
1004 #define MDB_COMMIT_PAGES IOV_MAX
1007 /* max bytes to write in one call */
1008 #define MAX_WRITE (0x80000000U >> (sizeof(ssize_t) == 4))
1010 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1011 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1012 static int mdb_page_touch(MDB_cursor *mc);
1014 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp, int *lvl);
1015 static int mdb_page_search_root(MDB_cursor *mc,
1016 MDB_val *key, int modify);
1017 #define MDB_PS_MODIFY 1
1018 #define MDB_PS_ROOTONLY 2
1019 static int mdb_page_search(MDB_cursor *mc,
1020 MDB_val *key, int flags);
1021 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1023 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1024 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1025 pgno_t newpgno, unsigned int nflags);
1027 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1028 static int mdb_env_pick_meta(const MDB_env *env);
1029 static int mdb_env_write_meta(MDB_txn *txn);
1030 #if !(defined(_WIN32) || defined(MDB_USE_POSIX_SEM)) /* Drop unused excl arg */
1031 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1033 static void mdb_env_close0(MDB_env *env, int excl);
1035 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1036 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1037 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1038 static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
1039 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1040 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
1041 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1042 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1043 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1045 static int mdb_rebalance(MDB_cursor *mc);
1046 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1048 static void mdb_cursor_pop(MDB_cursor *mc);
1049 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1051 static int mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
1052 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1053 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1054 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1055 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1057 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1058 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1060 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1061 static void mdb_xcursor_init0(MDB_cursor *mc);
1062 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1064 static int mdb_drop0(MDB_cursor *mc, int subs);
1065 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1068 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1072 static SECURITY_DESCRIPTOR mdb_null_sd;
1073 static SECURITY_ATTRIBUTES mdb_all_sa;
1074 static int mdb_sec_inited;
1077 /** Return the library version info. */
1079 mdb_version(int *major, int *minor, int *patch)
1081 if (major) *major = MDB_VERSION_MAJOR;
1082 if (minor) *minor = MDB_VERSION_MINOR;
1083 if (patch) *patch = MDB_VERSION_PATCH;
1084 return MDB_VERSION_STRING;
1087 /** Table of descriptions for MDB @ref errors */
1088 static char *const mdb_errstr[] = {
1089 "MDB_KEYEXIST: Key/data pair already exists",
1090 "MDB_NOTFOUND: No matching key/data pair found",
1091 "MDB_PAGE_NOTFOUND: Requested page not found",
1092 "MDB_CORRUPTED: Located page was wrong type",
1093 "MDB_PANIC: Update of meta page failed",
1094 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1095 "MDB_INVALID: File is not an MDB file",
1096 "MDB_MAP_FULL: Environment mapsize limit reached",
1097 "MDB_DBS_FULL: Environment maxdbs limit reached",
1098 "MDB_READERS_FULL: Environment maxreaders limit reached",
1099 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1100 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1101 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1102 "MDB_PAGE_FULL: Internal error - page has no more space",
1103 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1104 "MDB_INCOMPATIBLE: Database flags changed or would change",
1105 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1109 mdb_strerror(int err)
1113 return ("Successful return: 0");
1115 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1116 i = err - MDB_KEYEXIST;
1117 return mdb_errstr[i];
1120 return strerror(err);
1124 /** Display a key in hexadecimal and return the address of the result.
1125 * @param[in] key the key to display
1126 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1127 * @return The key in hexadecimal form.
1130 mdb_dkey(MDB_val *key, char *buf)
1133 unsigned char *c = key->mv_data;
1139 if (key->mv_size > MDB_MAXKEYSIZE)
1140 return "MDB_MAXKEYSIZE";
1141 /* may want to make this a dynamic check: if the key is mostly
1142 * printable characters, print it as-is instead of converting to hex.
1146 for (i=0; i<key->mv_size; i++)
1147 ptr += sprintf(ptr, "%02x", *c++);
1149 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1154 /** Display all the keys in the page. */
1156 mdb_page_list(MDB_page *mp)
1159 unsigned int i, nkeys, nsize;
1163 nkeys = NUMKEYS(mp);
1164 fprintf(stderr, "Page %zu numkeys %d\n", mp->mp_pgno, nkeys);
1165 for (i=0; i<nkeys; i++) {
1166 node = NODEPTR(mp, i);
1167 key.mv_size = node->mn_ksize;
1168 key.mv_data = node->mn_data;
1169 nsize = NODESIZE + NODEKSZ(node) + sizeof(indx_t);
1170 if (IS_BRANCH(mp)) {
1171 fprintf(stderr, "key %d: page %zu, %s\n", i, NODEPGNO(node),
1174 if (F_ISSET(node->mn_flags, F_BIGDATA))
1175 nsize += sizeof(pgno_t);
1177 nsize += NODEDSZ(node);
1178 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1184 mdb_cursor_chk(MDB_cursor *mc)
1190 if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1191 for (i=0; i<mc->mc_top; i++) {
1193 node = NODEPTR(mp, mc->mc_ki[i]);
1194 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1197 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1203 /** Count all the pages in each DB and in the freelist
1204 * and make sure it matches the actual number of pages
1207 static void mdb_audit(MDB_txn *txn)
1211 MDB_ID freecount, count;
1216 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1217 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1218 freecount += *(MDB_ID *)data.mv_data;
1221 for (i = 0; i<txn->mt_numdbs; i++) {
1223 mdb_cursor_init(&mc, txn, i, &mx);
1224 if (txn->mt_dbs[i].md_root == P_INVALID)
1226 count += txn->mt_dbs[i].md_branch_pages +
1227 txn->mt_dbs[i].md_leaf_pages +
1228 txn->mt_dbs[i].md_overflow_pages;
1229 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1230 mdb_page_search(&mc, NULL, 0);
1234 mp = mc.mc_pg[mc.mc_top];
1235 for (j=0; j<NUMKEYS(mp); j++) {
1236 MDB_node *leaf = NODEPTR(mp, j);
1237 if (leaf->mn_flags & F_SUBDATA) {
1239 memcpy(&db, NODEDATA(leaf), sizeof(db));
1240 count += db.md_branch_pages + db.md_leaf_pages +
1241 db.md_overflow_pages;
1245 while (mdb_cursor_sibling(&mc, 1) == 0);
1248 if (freecount + count + 2 /* metapages */ != txn->mt_next_pgno) {
1249 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1250 txn->mt_txnid, freecount, count+2, freecount+count+2, txn->mt_next_pgno);
1256 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1258 return txn->mt_dbxs[dbi].md_cmp(a, b);
1262 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1264 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1267 /** Allocate a page.
1268 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1271 mdb_page_malloc(MDB_txn *txn, unsigned num)
1273 MDB_env *env = txn->mt_env;
1274 MDB_page *ret = env->me_dpages;
1275 size_t sz = env->me_psize;
1278 VGMEMP_ALLOC(env, ret, sz);
1279 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1280 env->me_dpages = ret->mp_next;
1286 if ((ret = malloc(sz)) != NULL) {
1287 VGMEMP_ALLOC(env, ret, sz);
1292 /** Free a single page.
1293 * Saves single pages to a list, for future reuse.
1294 * (This is not used for multi-page overflow pages.)
1297 mdb_page_free(MDB_env *env, MDB_page *mp)
1299 mp->mp_next = env->me_dpages;
1300 VGMEMP_FREE(env, mp);
1301 env->me_dpages = mp;
1304 /* Free a dirty page */
1306 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1308 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1309 mdb_page_free(env, dp);
1311 /* large pages just get freed directly */
1312 VGMEMP_FREE(env, dp);
1317 /** Return all dirty pages to dpage list */
1319 mdb_dlist_free(MDB_txn *txn)
1321 MDB_env *env = txn->mt_env;
1322 MDB_ID2L dl = txn->mt_u.dirty_list;
1323 unsigned i, n = dl[0].mid;
1325 for (i = 1; i <= n; i++) {
1326 mdb_dpage_free(env, dl[i].mptr);
1331 /* Set or clear P_KEEP in non-overflow, non-sub pages in known cursors.
1332 * When clearing, only consider backup cursors (from parent txns) since
1333 * other P_KEEP flags have already been cleared.
1334 * @param[in] mc A cursor handle for the current operation.
1335 * @param[in] pflags Flags of the pages to update:
1336 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1339 mdb_cursorpages_mark(MDB_cursor *mc, unsigned pflags)
1341 MDB_txn *txn = mc->mc_txn;
1342 MDB_cursor *m2, *m3;
1346 if (mc->mc_flags & C_UNTRACK)
1347 mc = NULL; /* will find mc in mt_cursors */
1348 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1349 for (; mc; mc=mc->mc_next) {
1350 m2 = pflags == P_DIRTY ? mc : mc->mc_backup;
1351 for (; m2; m2 = m2->mc_backup) {
1352 for (m3=m2; m3->mc_flags & C_INITIALIZED; m3=&mx->mx_cursor) {
1353 for (j=0; j<m3->mc_snum; j++)
1354 if ((m3->mc_pg[j]->mp_flags & (P_SUBP|P_DIRTY|P_KEEP))
1356 m3->mc_pg[j]->mp_flags ^= P_KEEP;
1357 if (!(m3->mc_db->md_flags & MDB_DUPSORT))
1359 /* Cursor backups have mx malloced at the end of m2 */
1360 mx = (m3 == mc ? m3->mc_xcursor : (MDB_xcursor *)(m3+1));
1369 static int mdb_page_flush(MDB_txn *txn);
1371 /** Spill pages from the dirty list back to disk.
1372 * This is intended to prevent running into #MDB_TXN_FULL situations,
1373 * but note that they may still occur in a few cases:
1374 * 1) pages in #MDB_DUPSORT sub-DBs are never spilled, so if there
1375 * are too many of these dirtied in one txn, the txn may still get
1377 * 2) child txns may run out of space if their parents dirtied a
1378 * lot of pages and never spilled them. TODO: we probably should do
1379 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1380 * the parent's dirty_room is below a given threshold.
1381 * 3) our estimate of the txn size could be too small. At the
1382 * moment this seems unlikely.
1384 * Otherwise, if not using nested txns, it is expected that apps will
1385 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1386 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1387 * If the txn never references them again, they can be left alone.
1388 * If the txn only reads them, they can be used without any fuss.
1389 * If the txn writes them again, they can be dirtied immediately without
1390 * going thru all of the work of #mdb_page_touch(). Such references are
1391 * handled by #mdb_page_unspill().
1393 * Also note, we never spill DB root pages, nor pages of active cursors,
1394 * because we'll need these back again soon anyway. And in nested txns,
1395 * we can't spill a page in a child txn if it was already spilled in a
1396 * parent txn. That would alter the parent txns' data even though
1397 * the child hasn't committed yet, and we'd have no way to undo it if
1398 * the child aborted.
1400 * @param[in] m0 cursor A cursor handle identifying the transaction and
1401 * database for which we are checking space.
1402 * @param[in] key For a put operation, the key being stored.
1403 * @param[in] data For a put operation, the data being stored.
1404 * @return 0 on success, non-zero on failure.
1407 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1409 MDB_txn *txn = m0->mc_txn;
1411 MDB_ID2L dl = txn->mt_u.dirty_list;
1415 if (m0->mc_flags & C_SUB)
1418 /* Estimate how much space this op will take */
1419 i = m0->mc_db->md_depth;
1420 /* Named DBs also dirty the main DB */
1421 if (m0->mc_dbi > MAIN_DBI)
1422 i += txn->mt_dbs[MAIN_DBI].md_depth;
1423 /* For puts, roughly factor in the key+data size */
1425 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
1426 i += i; /* double it for good measure */
1428 if (txn->mt_dirty_room > i)
1431 if (!txn->mt_spill_pgs) {
1432 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
1433 if (!txn->mt_spill_pgs)
1437 /* Mark all the dirty root pages we want to preserve */
1438 for (i=0; i<txn->mt_numdbs; i++) {
1439 if (txn->mt_dbflags[i] & DB_DIRTY) {
1440 j = mdb_mid2l_search(dl, txn->mt_dbs[i].md_root);
1441 if (j <= dl[0].mid) {
1443 dp->mp_flags |= P_KEEP;
1448 /* Preserve pages used by cursors */
1449 mdb_cursorpages_mark(m0, P_DIRTY);
1451 /* Save the page IDs of all the pages we're flushing */
1452 for (i=1; i<=dl[0].mid; i++) {
1454 if (dp->mp_flags & P_KEEP)
1456 /* Can't spill twice, make sure it's not already in a parent's
1459 if (txn->mt_parent) {
1461 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1462 if (tx2->mt_spill_pgs) {
1463 j = mdb_midl_search(tx2->mt_spill_pgs, dl[i].mid);
1464 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == dl[i].mid) {
1465 dp->mp_flags |= P_KEEP;
1473 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, dl[i].mid)))
1476 mdb_midl_sort(txn->mt_spill_pgs);
1478 rc = mdb_page_flush(txn);
1480 mdb_cursorpages_mark(m0, P_DIRTY|P_KEEP);
1483 if (txn->mt_parent) {
1485 pgno_t pgno = dl[i].mid;
1486 txn->mt_dirty_room = txn->mt_parent->mt_dirty_room - dl[0].mid;
1487 /* dirty pages that are dirty in an ancestor don't
1488 * count against this txn's dirty_room.
1490 for (i=1; i<=dl[0].mid; i++) {
1491 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1492 j = mdb_mid2l_search(tx2->mt_u.dirty_list, pgno);
1493 if (j <= tx2->mt_u.dirty_list[0].mid &&
1494 tx2->mt_u.dirty_list[j].mid == pgno) {
1495 txn->mt_dirty_room++;
1501 txn->mt_dirty_room = MDB_IDL_UM_MAX - dl[0].mid;
1503 txn->mt_flags |= MDB_TXN_SPILLS;
1508 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
1510 mdb_find_oldest(MDB_txn *txn)
1513 txnid_t mr, oldest = txn->mt_txnid - 1;
1514 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
1515 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
1525 /** Add a page to the txn's dirty list */
1527 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
1530 int (*insert)(MDB_ID2L, MDB_ID2 *);
1532 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1533 insert = mdb_mid2l_append;
1535 insert = mdb_mid2l_insert;
1537 mid.mid = mp->mp_pgno;
1539 insert(txn->mt_u.dirty_list, &mid);
1540 txn->mt_dirty_room--;
1543 /** Allocate pages for writing.
1544 * If there are free pages available from older transactions, they
1545 * will be re-used first. Otherwise a new page will be allocated.
1546 * @param[in] mc cursor A cursor handle identifying the transaction and
1547 * database for which we are allocating.
1548 * @param[in] num the number of pages to allocate.
1549 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
1550 * will always be satisfied by a single contiguous chunk of memory.
1551 * @return 0 on success, non-zero on failure.
1554 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
1556 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
1557 /* Get at most <Max_retries> more freeDB records once me_pghead
1558 * has enough pages. If not enough, use new pages from the map.
1559 * If <Paranoid> and mc is updating the freeDB, only get new
1560 * records if me_pghead is empty. Then the freelist cannot play
1561 * catch-up with itself by growing while trying to save it.
1563 enum { Paranoid = 1, Max_retries = 500 };
1565 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
1567 int rc, n2 = num-1, retry = Max_retries;
1568 MDB_txn *txn = mc->mc_txn;
1569 MDB_env *env = txn->mt_env;
1570 pgno_t pgno, *mop = env->me_pghead;
1571 unsigned i, j, k, mop_len = mop ? mop[0] : 0;
1573 txnid_t oldest = 0, last;
1579 /* If our dirty list is already full, we can't do anything */
1580 if (txn->mt_dirty_room == 0)
1581 return MDB_TXN_FULL;
1583 for (op = MDB_FIRST;; op = MDB_NEXT) {
1586 pgno_t *idl, old_id, new_id;
1588 /* Seek a big enough contiguous page range. Prefer
1589 * pages at the tail, just truncating the list.
1591 if (mop_len >= (unsigned)num) {
1595 if (mop[i-n2] == pgno+n2)
1597 } while (--i >= (unsigned)num);
1598 if (Max_retries < INT_MAX && --retry < 0)
1602 if (op == MDB_FIRST) { /* 1st iteration */
1603 /* Prepare to fetch more and coalesce */
1604 oldest = mdb_find_oldest(txn);
1605 last = env->me_pglast;
1606 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1609 key.mv_data = &last; /* will loop up last+1 */
1610 key.mv_size = sizeof(last);
1612 if (Paranoid && mc->mc_dbi == FREE_DBI)
1615 if (Paranoid && retry < 0 && mop_len)
1619 /* Do not fetch more if the record will be too recent */
1622 rc = mdb_cursor_get(&m2, &key, NULL, op);
1624 if (rc == MDB_NOTFOUND)
1628 last = *(txnid_t*)key.mv_data;
1631 np = m2.mc_pg[m2.mc_top];
1632 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
1633 if ((rc = mdb_node_read(txn, leaf, &data)) != MDB_SUCCESS)
1636 idl = (MDB_ID *) data.mv_data;
1639 if (!(env->me_pghead = mop = mdb_midl_alloc(i)))
1642 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
1644 mop = env->me_pghead;
1646 env->me_pglast = last;
1648 DPRINTF("IDL read txn %zu root %zu num %u",
1649 last, txn->mt_dbs[FREE_DBI].md_root, i);
1651 DPRINTF("IDL %zu", idl[k]);
1653 /* Merge in descending sorted order */
1656 mop[0] = (pgno_t)-1;
1660 for (; old_id < new_id; old_id = mop[--j])
1667 /* Use new pages from the map when nothing suitable in the freeDB */
1669 pgno = txn->mt_next_pgno;
1670 if (pgno + num >= env->me_maxpg) {
1671 DPUTS("DB size maxed out");
1672 return MDB_MAP_FULL;
1676 if (env->me_flags & MDB_WRITEMAP) {
1677 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
1679 if (!(np = mdb_page_malloc(txn, num)))
1683 mop[0] = mop_len -= num;
1684 /* Move any stragglers down */
1685 for (j = i-num; j < mop_len; )
1686 mop[++j] = mop[++i];
1688 txn->mt_next_pgno = pgno + num;
1691 mdb_page_dirty(txn, np);
1697 /** Copy the used portions of a non-overflow page.
1698 * @param[in] dst page to copy into
1699 * @param[in] src page to copy from
1700 * @param[in] psize size of a page
1703 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
1705 enum { Align = sizeof(pgno_t) };
1706 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
1708 /* If page isn't full, just copy the used portion. Adjust
1709 * alignment so memcpy may copy words instead of bytes.
1711 if ((unused &= -Align) && !IS_LEAF2(src)) {
1713 memcpy(dst, src, (lower + (Align-1)) & -Align);
1714 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
1717 memcpy(dst, src, psize - unused);
1721 /** Pull a page off the txn's spill list, if present.
1722 * If a page being referenced was spilled to disk in this txn, bring
1723 * it back and make it dirty/writable again.
1724 * @param[in] tx0 the transaction handle.
1725 * @param[in] mp the page being referenced.
1726 * @param[out] ret the writable page, if any. ret is unchanged if
1727 * mp wasn't spilled.
1730 mdb_page_unspill(MDB_txn *tx0, MDB_page *mp, MDB_page **ret)
1732 MDB_env *env = tx0->mt_env;
1735 pgno_t pgno = mp->mp_pgno;
1737 for (txn = tx0; txn; txn=txn->mt_parent) {
1738 if (!txn->mt_spill_pgs)
1740 x = mdb_midl_search(txn->mt_spill_pgs, pgno);
1741 if (x <= txn->mt_spill_pgs[0] && txn->mt_spill_pgs[x] == pgno) {
1744 if (IS_OVERFLOW(mp))
1748 if (env->me_flags & MDB_WRITEMAP) {
1751 np = mdb_page_malloc(txn, num);
1755 memcpy(np, mp, num * env->me_psize);
1757 mdb_page_copy(np, mp, env->me_psize);
1760 /* If in current txn, this page is no longer spilled */
1761 for (; x < txn->mt_spill_pgs[0]; x++)
1762 txn->mt_spill_pgs[x] = txn->mt_spill_pgs[x+1];
1763 txn->mt_spill_pgs[0]--;
1764 } /* otherwise, if belonging to a parent txn, the
1765 * page remains spilled until child commits
1768 if (txn->mt_parent) {
1770 /* If this page is also in a parent's dirty list, then
1771 * it's already accounted in dirty_room, and we need to
1772 * cancel out the decrement that mdb_page_dirty does.
1774 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1775 x = mdb_mid2l_search(tx2->mt_u.dirty_list, pgno);
1776 if (x <= tx2->mt_u.dirty_list[0].mid &&
1777 tx2->mt_u.dirty_list[x].mid == pgno) {
1778 txn->mt_dirty_room++;
1783 mdb_page_dirty(tx0, np);
1784 np->mp_flags |= P_DIRTY;
1792 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1793 * @param[in] mc cursor pointing to the page to be touched
1794 * @return 0 on success, non-zero on failure.
1797 mdb_page_touch(MDB_cursor *mc)
1799 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
1800 MDB_txn *txn = mc->mc_txn;
1801 MDB_cursor *m2, *m3;
1806 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1807 if (txn->mt_flags & MDB_TXN_SPILLS) {
1809 rc = mdb_page_unspill(txn, mp, &np);
1815 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
1816 (rc = mdb_page_alloc(mc, 1, &np)))
1819 DPRINTF("touched db %u page %zu -> %zu", mc->mc_dbi,mp->mp_pgno,pgno);
1820 assert(mp->mp_pgno != pgno);
1821 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
1822 /* Update the parent page, if any, to point to the new page */
1824 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
1825 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
1826 SETPGNO(node, pgno);
1828 mc->mc_db->md_root = pgno;
1830 } else if (txn->mt_parent && !IS_SUBP(mp)) {
1831 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
1833 /* If txn has a parent, make sure the page is in our
1837 unsigned x = mdb_mid2l_search(dl, pgno);
1838 if (x <= dl[0].mid && dl[x].mid == pgno) {
1839 if (mp != dl[x].mptr) { /* bad cursor? */
1840 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1841 return MDB_CORRUPTED;
1846 assert(dl[0].mid < MDB_IDL_UM_MAX);
1848 np = mdb_page_malloc(txn, 1);
1853 mdb_mid2l_insert(dl, &mid);
1858 mdb_page_copy(np, mp, txn->mt_env->me_psize);
1860 np->mp_flags |= P_DIRTY;
1863 /* Adjust cursors pointing to mp */
1864 mc->mc_pg[mc->mc_top] = np;
1866 if (mc->mc_flags & C_SUB) {
1868 for (m2 = txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
1869 m3 = &m2->mc_xcursor->mx_cursor;
1870 if (m3->mc_snum < mc->mc_snum) continue;
1871 if (m3->mc_pg[mc->mc_top] == mp)
1872 m3->mc_pg[mc->mc_top] = np;
1875 for (m2 = txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
1876 if (m2->mc_snum < mc->mc_snum) continue;
1877 if (m2->mc_pg[mc->mc_top] == mp) {
1878 m2->mc_pg[mc->mc_top] = np;
1879 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
1880 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
1882 MDB_node *leaf = NODEPTR(np, mc->mc_ki[mc->mc_top]);
1883 if (!(leaf->mn_flags & F_SUBDATA))
1884 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
1893 mdb_env_sync(MDB_env *env, int force)
1896 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1897 if (env->me_flags & MDB_WRITEMAP) {
1898 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
1899 ? MS_ASYNC : MS_SYNC;
1900 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
1903 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
1907 if (MDB_FDATASYNC(env->me_fd))
1914 /** Back up parent txn's cursors, then grab the originals for tracking */
1916 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
1918 MDB_cursor *mc, *bk;
1923 for (i = src->mt_numdbs; --i >= 0; ) {
1924 if ((mc = src->mt_cursors[i]) != NULL) {
1925 size = sizeof(MDB_cursor);
1927 size += sizeof(MDB_xcursor);
1928 for (; mc; mc = bk->mc_next) {
1934 mc->mc_db = &dst->mt_dbs[i];
1935 /* Kill pointers into src - and dst to reduce abuse: The
1936 * user may not use mc until dst ends. Otherwise we'd...
1938 mc->mc_txn = NULL; /* ...set this to dst */
1939 mc->mc_dbflag = NULL; /* ...and &dst->mt_dbflags[i] */
1940 if ((mx = mc->mc_xcursor) != NULL) {
1941 *(MDB_xcursor *)(bk+1) = *mx;
1942 mx->mx_cursor.mc_txn = NULL; /* ...and dst. */
1944 mc->mc_next = dst->mt_cursors[i];
1945 dst->mt_cursors[i] = mc;
1952 /** Close this write txn's cursors, give parent txn's cursors back to parent.
1953 * @param[in] txn the transaction handle.
1954 * @param[in] merge true to keep changes to parent cursors, false to revert.
1955 * @return 0 on success, non-zero on failure.
1958 mdb_cursors_close(MDB_txn *txn, unsigned merge)
1960 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
1964 for (i = txn->mt_numdbs; --i >= 0; ) {
1965 for (mc = cursors[i]; mc; mc = next) {
1967 if ((bk = mc->mc_backup) != NULL) {
1969 /* Commit changes to parent txn */
1970 mc->mc_next = bk->mc_next;
1971 mc->mc_backup = bk->mc_backup;
1972 mc->mc_txn = bk->mc_txn;
1973 mc->mc_db = bk->mc_db;
1974 mc->mc_dbflag = bk->mc_dbflag;
1975 if ((mx = mc->mc_xcursor) != NULL)
1976 mx->mx_cursor.mc_txn = bk->mc_txn;
1978 /* Abort nested txn */
1980 if ((mx = mc->mc_xcursor) != NULL)
1981 *mx = *(MDB_xcursor *)(bk+1);
1991 #ifdef MDB_DEBUG_SKIP
1992 #define mdb_txn_reset0(txn, act) mdb_txn_reset0(txn)
1995 mdb_txn_reset0(MDB_txn *txn, const char *act);
1997 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
1998 * @param[in] txn the transaction handle to initialize
1999 * @return 0 on success, non-zero on failure.
2002 mdb_txn_renew0(MDB_txn *txn)
2004 MDB_env *env = txn->mt_env;
2007 int rc, new_notls = 0;
2010 txn->mt_numdbs = env->me_numdbs;
2011 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
2013 if (txn->mt_flags & MDB_TXN_RDONLY) {
2014 if (!env->me_txns) {
2015 i = mdb_env_pick_meta(env);
2016 txn->mt_txnid = env->me_metas[i]->mm_txnid;
2017 txn->mt_u.reader = NULL;
2019 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2020 pthread_getspecific(env->me_txkey);
2022 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2023 return MDB_BAD_RSLOT;
2025 pid_t pid = env->me_pid;
2026 pthread_t tid = pthread_self();
2029 for (i=0; i<env->me_txns->mti_numreaders; i++)
2030 if (env->me_txns->mti_readers[i].mr_pid == 0)
2032 if (i == env->me_maxreaders) {
2033 UNLOCK_MUTEX_R(env);
2034 return MDB_READERS_FULL;
2036 env->me_txns->mti_readers[i].mr_pid = pid;
2037 env->me_txns->mti_readers[i].mr_tid = tid;
2038 if (i >= env->me_txns->mti_numreaders)
2039 env->me_txns->mti_numreaders = i+1;
2040 /* Save numreaders for un-mutexed mdb_env_close() */
2041 env->me_numreaders = env->me_txns->mti_numreaders;
2042 UNLOCK_MUTEX_R(env);
2043 r = &env->me_txns->mti_readers[i];
2044 new_notls = (env->me_flags & MDB_NOTLS);
2045 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2050 txn->mt_txnid = r->mr_txnid = env->me_txns->mti_txnid;
2051 txn->mt_u.reader = r;
2053 txn->mt_toggle = txn->mt_txnid & 1;
2057 txn->mt_txnid = env->me_txns->mti_txnid;
2058 txn->mt_toggle = txn->mt_txnid & 1;
2061 if (txn->mt_txnid == mdb_debug_start)
2064 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2065 txn->mt_u.dirty_list = env->me_dirty_list;
2066 txn->mt_u.dirty_list[0].mid = 0;
2067 txn->mt_free_pgs = env->me_free_pgs;
2068 txn->mt_free_pgs[0] = 0;
2069 txn->mt_spill_pgs = NULL;
2073 /* Copy the DB info and flags */
2074 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
2076 /* Moved to here to avoid a data race in read TXNs */
2077 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
2079 for (i=2; i<txn->mt_numdbs; i++) {
2080 x = env->me_dbflags[i];
2081 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2082 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_STALE : 0;
2084 txn->mt_dbflags[0] = txn->mt_dbflags[1] = DB_VALID;
2086 if (env->me_maxpg < txn->mt_next_pgno) {
2087 mdb_txn_reset0(txn, "renew0-mapfail");
2089 txn->mt_u.reader->mr_pid = 0;
2090 txn->mt_u.reader = NULL;
2092 return MDB_MAP_RESIZED;
2099 mdb_txn_renew(MDB_txn *txn)
2103 if (!txn || txn->mt_dbxs) /* A reset txn has mt_dbxs==NULL */
2106 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
2107 DPUTS("environment had fatal error, must shutdown!");
2111 rc = mdb_txn_renew0(txn);
2112 if (rc == MDB_SUCCESS) {
2113 DPRINTF("renew txn %zu%c %p on mdbenv %p, root page %zu",
2114 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2115 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
2121 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2125 int rc, size, tsize = sizeof(MDB_txn);
2127 if (env->me_flags & MDB_FATAL_ERROR) {
2128 DPUTS("environment had fatal error, must shutdown!");
2131 if ((env->me_flags & MDB_RDONLY) && !(flags & MDB_RDONLY))
2134 /* Nested transactions: Max 1 child, write txns only, no writemap */
2135 if (parent->mt_child ||
2136 (flags & MDB_RDONLY) || (parent->mt_flags & MDB_TXN_RDONLY) ||
2137 (env->me_flags & MDB_WRITEMAP))
2141 tsize = sizeof(MDB_ntxn);
2143 size = tsize + env->me_maxdbs * (sizeof(MDB_db)+1);
2144 if (!(flags & MDB_RDONLY))
2145 size += env->me_maxdbs * sizeof(MDB_cursor *);
2147 if ((txn = calloc(1, size)) == NULL) {
2148 DPRINTF("calloc: %s", strerror(ErrCode()));
2151 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2152 if (flags & MDB_RDONLY) {
2153 txn->mt_flags |= MDB_TXN_RDONLY;
2154 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
2156 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2157 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
2163 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2164 if (!txn->mt_u.dirty_list ||
2165 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2167 free(txn->mt_u.dirty_list);
2171 txn->mt_txnid = parent->mt_txnid;
2172 txn->mt_toggle = parent->mt_toggle;
2173 txn->mt_dirty_room = parent->mt_dirty_room;
2174 txn->mt_u.dirty_list[0].mid = 0;
2175 txn->mt_spill_pgs = NULL;
2176 txn->mt_next_pgno = parent->mt_next_pgno;
2177 parent->mt_child = txn;
2178 txn->mt_parent = parent;
2179 txn->mt_numdbs = parent->mt_numdbs;
2180 txn->mt_flags = parent->mt_flags;
2181 txn->mt_dbxs = parent->mt_dbxs;
2182 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2183 /* Copy parent's mt_dbflags, but clear DB_NEW */
2184 for (i=0; i<txn->mt_numdbs; i++)
2185 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2187 ntxn = (MDB_ntxn *)txn;
2188 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2189 if (env->me_pghead) {
2190 size = MDB_IDL_SIZEOF(env->me_pghead);
2191 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2193 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2198 rc = mdb_cursor_shadow(parent, txn);
2200 mdb_txn_reset0(txn, "beginchild-fail");
2202 rc = mdb_txn_renew0(txn);
2208 DPRINTF("begin txn %zu%c %p on mdbenv %p, root page %zu",
2209 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2210 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
2216 /** Export or close DBI handles opened in this txn. */
2218 mdb_dbis_update(MDB_txn *txn, int keep)
2221 MDB_dbi n = txn->mt_numdbs;
2222 MDB_env *env = txn->mt_env;
2223 unsigned char *tdbflags = txn->mt_dbflags;
2225 for (i = n; --i >= 2;) {
2226 if (tdbflags[i] & DB_NEW) {
2228 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2230 char *ptr = env->me_dbxs[i].md_name.mv_data;
2231 env->me_dbxs[i].md_name.mv_data = NULL;
2232 env->me_dbxs[i].md_name.mv_size = 0;
2233 env->me_dbflags[i] = 0;
2238 if (keep && env->me_numdbs < n)
2242 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
2243 * May be called twice for readonly txns: First reset it, then abort.
2244 * @param[in] txn the transaction handle to reset
2247 mdb_txn_reset0(MDB_txn *txn, const char *act)
2249 MDB_env *env = txn->mt_env;
2251 /* Close any DBI handles opened in this txn */
2252 mdb_dbis_update(txn, 0);
2254 DPRINTF("%s txn %zu%c %p on mdbenv %p, root page %zu",
2255 act, txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2256 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
2258 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2259 if (txn->mt_u.reader) {
2260 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2261 if (!(env->me_flags & MDB_NOTLS))
2262 txn->mt_u.reader = NULL; /* txn does not own reader */
2264 txn->mt_numdbs = 0; /* close nothing if called again */
2265 txn->mt_dbxs = NULL; /* mark txn as reset */
2267 mdb_cursors_close(txn, 0);
2269 if (!(env->me_flags & MDB_WRITEMAP)) {
2270 mdb_dlist_free(txn);
2272 mdb_midl_free(env->me_pghead);
2274 if (txn->mt_parent) {
2275 txn->mt_parent->mt_child = NULL;
2276 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2277 mdb_midl_free(txn->mt_free_pgs);
2278 mdb_midl_free(txn->mt_spill_pgs);
2279 free(txn->mt_u.dirty_list);
2283 if (mdb_midl_shrink(&txn->mt_free_pgs))
2284 env->me_free_pgs = txn->mt_free_pgs;
2285 env->me_pghead = NULL;
2289 /* The writer mutex was locked in mdb_txn_begin. */
2290 UNLOCK_MUTEX_W(env);
2295 mdb_txn_reset(MDB_txn *txn)
2300 /* This call is only valid for read-only txns */
2301 if (!(txn->mt_flags & MDB_TXN_RDONLY))
2304 mdb_txn_reset0(txn, "reset");
2308 mdb_txn_abort(MDB_txn *txn)
2314 mdb_txn_abort(txn->mt_child);
2316 mdb_txn_reset0(txn, "abort");
2317 /* Free reader slot tied to this txn (if MDB_NOTLS && writable FS) */
2318 if ((txn->mt_flags & MDB_TXN_RDONLY) && txn->mt_u.reader)
2319 txn->mt_u.reader->mr_pid = 0;
2324 /** Save the freelist as of this transaction to the freeDB.
2325 * This changes the freelist. Keep trying until it stabilizes.
2328 mdb_freelist_save(MDB_txn *txn)
2330 /* env->me_pghead[] can grow and shrink during this call.
2331 * env->me_pglast and txn->mt_free_pgs[] can only grow.
2332 * Page numbers cannot disappear from txn->mt_free_pgs[].
2335 MDB_env *env = txn->mt_env;
2336 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
2337 txnid_t pglast = 0, head_id = 0;
2338 pgno_t freecnt = 0, *free_pgs, *mop;
2339 ssize_t head_room = 0, total_room = 0, mop_len;
2341 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
2343 if (env->me_pghead) {
2344 /* Make sure first page of freeDB is touched and on freelist */
2345 rc = mdb_page_search(&mc, NULL, MDB_PS_MODIFY);
2346 if (rc && rc != MDB_NOTFOUND)
2351 /* Come back here after each Put() in case freelist changed */
2354 /* If using records from freeDB which we have not yet
2355 * deleted, delete them and any we reserved for me_pghead.
2357 while (pglast < env->me_pglast) {
2358 rc = mdb_cursor_first(&mc, &key, NULL);
2361 pglast = head_id = *(txnid_t *)key.mv_data;
2362 total_room = head_room = 0;
2363 assert(pglast <= env->me_pglast);
2364 rc = mdb_cursor_del(&mc, 0);
2369 /* Save the IDL of pages freed by this txn, to a single record */
2370 if (freecnt < txn->mt_free_pgs[0]) {
2372 /* Make sure last page of freeDB is touched and on freelist */
2373 key.mv_size = MDB_MAXKEYSIZE+1;
2375 rc = mdb_page_search(&mc, &key, MDB_PS_MODIFY);
2376 if (rc && rc != MDB_NOTFOUND)
2379 free_pgs = txn->mt_free_pgs;
2380 /* Write to last page of freeDB */
2381 key.mv_size = sizeof(txn->mt_txnid);
2382 key.mv_data = &txn->mt_txnid;
2384 freecnt = free_pgs[0];
2385 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
2386 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2389 /* Retry if mt_free_pgs[] grew during the Put() */
2390 free_pgs = txn->mt_free_pgs;
2391 } while (freecnt < free_pgs[0]);
2392 mdb_midl_sort(free_pgs);
2393 memcpy(data.mv_data, free_pgs, data.mv_size);
2396 unsigned int i = free_pgs[0];
2397 DPRINTF("IDL write txn %zu root %zu num %u",
2398 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i);
2400 DPRINTF("IDL %zu", free_pgs[i]);
2406 mop = env->me_pghead;
2407 mop_len = mop ? mop[0] : 0;
2409 /* Reserve records for me_pghead[]. Split it if multi-page,
2410 * to avoid searching freeDB for a page range. Use keys in
2411 * range [1,me_pglast]: Smaller than txnid of oldest reader.
2413 if (total_room >= mop_len) {
2414 if (total_room == mop_len || --more < 0)
2416 } else if (head_room >= maxfree_1pg && head_id > 1) {
2417 /* Keep current record (overflow page), add a new one */
2421 /* (Re)write {key = head_id, IDL length = head_room} */
2422 total_room -= head_room;
2423 head_room = mop_len - total_room;
2424 if (head_room > maxfree_1pg && head_id > 1) {
2425 /* Overflow multi-page for part of me_pghead */
2426 head_room /= head_id; /* amortize page sizes */
2427 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
2428 } else if (head_room < 0) {
2429 /* Rare case, not bothering to delete this record */
2432 key.mv_size = sizeof(head_id);
2433 key.mv_data = &head_id;
2434 data.mv_size = (head_room + 1) * sizeof(pgno_t);
2435 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2438 *(MDB_ID *)data.mv_data = 0; /* IDL is initially empty */
2439 total_room += head_room;
2442 /* Fill in the reserved, touched me_pghead records */
2448 rc = mdb_cursor_first(&mc, &key, &data);
2449 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
2450 unsigned flags = MDB_CURRENT;
2451 txnid_t id = *(txnid_t *)key.mv_data;
2452 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
2455 assert(len >= 0 && id <= env->me_pglast);
2457 if (len > mop_len) {
2459 data.mv_size = (len + 1) * sizeof(MDB_ID);
2462 data.mv_data = mop -= len;
2465 rc = mdb_cursor_put(&mc, &key, &data, flags);
2467 if (rc || !(mop_len -= len))
2474 /** Flush dirty pages to the map, after clearing their dirty flag.
2477 mdb_page_flush(MDB_txn *txn)
2479 MDB_env *env = txn->mt_env;
2480 MDB_ID2L dl = txn->mt_u.dirty_list;
2481 unsigned psize = env->me_psize, j;
2482 int i, pagecount = dl[0].mid, rc;
2483 size_t size = 0, pos = 0;
2485 MDB_page *dp = NULL;
2489 struct iovec iov[MDB_COMMIT_PAGES];
2490 ssize_t wpos = 0, wsize = 0, wres;
2491 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
2496 if (env->me_flags & MDB_WRITEMAP) {
2497 /* Clear dirty flags */
2498 for (i = pagecount; i; i--) {
2500 /* Don't flush this page yet */
2501 if (dp->mp_flags & P_KEEP) {
2502 dp->mp_flags ^= P_KEEP;
2506 dp->mp_flags &= ~P_DIRTY;
2512 /* Write the pages */
2514 if (i <= pagecount) {
2516 /* Don't flush this page yet */
2517 if (dp->mp_flags & P_KEEP) {
2518 dp->mp_flags ^= P_KEEP;
2523 /* clear dirty flag */
2524 dp->mp_flags &= ~P_DIRTY;
2527 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
2532 /* Windows actually supports scatter/gather I/O, but only on
2533 * unbuffered file handles. Since we're relying on the OS page
2534 * cache for all our data, that's self-defeating. So we just
2535 * write pages one at a time. We use the ov structure to set
2536 * the write offset, to at least save the overhead of a Seek
2539 DPRINTF("committing page %zu", pgno);
2540 memset(&ov, 0, sizeof(ov));
2541 ov.Offset = pos & 0xffffffff;
2542 ov.OffsetHigh = pos >> 16 >> 16;
2543 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
2545 DPRINTF("WriteFile: %d", rc);
2549 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
2550 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
2552 /* Write previous page(s) */
2553 #ifdef MDB_USE_PWRITEV
2554 wres = pwritev(env->me_fd, iov, n, wpos);
2557 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
2559 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
2561 DPRINTF("lseek: %s", strerror(rc));
2564 wres = writev(env->me_fd, iov, n);
2567 if (wres != wsize) {
2570 DPRINTF("Write error: %s", strerror(rc));
2572 rc = EIO; /* TODO: Use which error code? */
2573 DPUTS("short write, filesystem full?");
2584 DPRINTF("committing page %zu", pgno);
2585 next_pos = pos + size;
2586 iov[n].iov_len = size;
2587 iov[n].iov_base = (char *)dp;
2594 for (i=1; i<=pagecount; i++) {
2596 /* This is a page we skipped above */
2599 dl[j].mid = dp->mp_pgno;
2602 mdb_dpage_free(env, dp);
2610 mdb_txn_commit(MDB_txn *txn)
2616 assert(txn != NULL);
2617 assert(txn->mt_env != NULL);
2619 if (txn->mt_child) {
2620 rc = mdb_txn_commit(txn->mt_child);
2621 txn->mt_child = NULL;
2628 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2629 mdb_dbis_update(txn, 1);
2630 txn->mt_numdbs = 2; /* so txn_abort() doesn't close any new handles */
2635 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
2636 DPUTS("error flag is set, can't commit");
2638 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
2643 if (txn->mt_parent) {
2644 MDB_txn *parent = txn->mt_parent;
2648 /* Append our free list to parent's */
2649 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
2652 mdb_midl_free(txn->mt_free_pgs);
2654 parent->mt_next_pgno = txn->mt_next_pgno;
2655 parent->mt_flags = txn->mt_flags;
2657 /* Merge our cursors into parent's and close them */
2658 mdb_cursors_close(txn, 1);
2660 /* Update parent's DB table. */
2661 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2662 parent->mt_numdbs = txn->mt_numdbs;
2663 parent->mt_dbflags[0] = txn->mt_dbflags[0];
2664 parent->mt_dbflags[1] = txn->mt_dbflags[1];
2665 for (i=2; i<txn->mt_numdbs; i++) {
2666 /* preserve parent's DB_NEW status */
2667 x = parent->mt_dbflags[i] & DB_NEW;
2668 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
2671 dst = parent->mt_u.dirty_list;
2672 src = txn->mt_u.dirty_list;
2673 /* Remove anything in our dirty list from parent's spill list */
2674 if (parent->mt_spill_pgs) {
2675 x = parent->mt_spill_pgs[0];
2677 /* zero out our dirty pages in parent spill list */
2678 for (i=1; i<=src[0].mid; i++) {
2679 if (src[i].mid < parent->mt_spill_pgs[x])
2681 if (src[i].mid > parent->mt_spill_pgs[x]) {
2687 parent->mt_spill_pgs[x] = 0;
2690 /* OK, we had a few hits, squash zeros from the spill list */
2691 if (len < parent->mt_spill_pgs[0]) {
2693 for (y=1; y<=parent->mt_spill_pgs[0]; y++) {
2694 if (parent->mt_spill_pgs[y]) {
2696 parent->mt_spill_pgs[x] = parent->mt_spill_pgs[y];
2701 parent->mt_spill_pgs[0] = len;
2704 /* Find len = length of merging our dirty list with parent's */
2706 dst[0].mid = 0; /* simplify loops */
2707 if (parent->mt_parent) {
2708 len = x + src[0].mid;
2709 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
2710 for (i = x; y && i; y--) {
2711 pgno_t yp = src[y].mid;
2712 while (yp < dst[i].mid)
2714 if (yp == dst[i].mid) {
2719 } else { /* Simplify the above for single-ancestor case */
2720 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
2722 /* Merge our dirty list with parent's */
2724 for (i = len; y; dst[i--] = src[y--]) {
2725 pgno_t yp = src[y].mid;
2726 while (yp < dst[x].mid)
2727 dst[i--] = dst[x--];
2728 if (yp == dst[x].mid)
2729 free(dst[x--].mptr);
2733 free(txn->mt_u.dirty_list);
2734 parent->mt_dirty_room = txn->mt_dirty_room;
2735 if (txn->mt_spill_pgs) {
2736 if (parent->mt_spill_pgs) {
2737 mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
2738 mdb_midl_free(txn->mt_spill_pgs);
2739 mdb_midl_sort(parent->mt_spill_pgs);
2741 parent->mt_spill_pgs = txn->mt_spill_pgs;
2745 parent->mt_child = NULL;
2746 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
2751 if (txn != env->me_txn) {
2752 DPUTS("attempt to commit unknown transaction");
2757 mdb_cursors_close(txn, 0);
2759 if (!txn->mt_u.dirty_list[0].mid && !(txn->mt_flags & MDB_TXN_DIRTY))
2762 DPRINTF("committing txn %zu %p on mdbenv %p, root page %zu",
2763 txn->mt_txnid, (void *)txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
2765 /* Update DB root pointers */
2766 if (txn->mt_numdbs > 2) {
2770 data.mv_size = sizeof(MDB_db);
2772 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
2773 for (i = 2; i < txn->mt_numdbs; i++) {
2774 if (txn->mt_dbflags[i] & DB_DIRTY) {
2775 data.mv_data = &txn->mt_dbs[i];
2776 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
2783 rc = mdb_freelist_save(txn);
2787 mdb_midl_free(env->me_pghead);
2788 env->me_pghead = NULL;
2789 if (mdb_midl_shrink(&txn->mt_free_pgs))
2790 env->me_free_pgs = txn->mt_free_pgs;
2796 if ((rc = mdb_page_flush(txn)) ||
2797 (rc = mdb_env_sync(env, 0)) ||
2798 (rc = mdb_env_write_meta(txn)))
2804 mdb_dbis_update(txn, 1);
2806 UNLOCK_MUTEX_W(env);
2816 /** Read the environment parameters of a DB environment before
2817 * mapping it into memory.
2818 * @param[in] env the environment handle
2819 * @param[out] meta address of where to store the meta information
2820 * @return 0 on success, non-zero on failure.
2823 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
2830 /* We don't know the page size yet, so use a minimum value.
2831 * Read both meta pages so we can use the latest one.
2834 for (i=off=0; i<2; i++, off = meta->mm_psize) {
2838 memset(&ov, 0, sizeof(ov));
2840 rc = ReadFile(env->me_fd,&pbuf,MDB_PAGESIZE,&len,&ov) ? (int)len : -1;
2841 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
2844 rc = pread(env->me_fd, &pbuf, MDB_PAGESIZE, off);
2846 if (rc != MDB_PAGESIZE) {
2847 if (rc == 0 && off == 0)
2849 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
2850 DPRINTF("read: %s", mdb_strerror(rc));
2854 p = (MDB_page *)&pbuf;
2856 if (!F_ISSET(p->mp_flags, P_META)) {
2857 DPRINTF("page %zu not a meta page", p->mp_pgno);
2862 if (m->mm_magic != MDB_MAGIC) {
2863 DPUTS("meta has invalid magic");
2867 if (m->mm_version != MDB_DATA_VERSION) {
2868 DPRINTF("database is version %u, expected version %u",
2869 m->mm_version, MDB_DATA_VERSION);
2870 return MDB_VERSION_MISMATCH;
2873 if (off == 0 || m->mm_txnid > meta->mm_txnid)
2879 /** Write the environment parameters of a freshly created DB environment.
2880 * @param[in] env the environment handle
2881 * @param[out] meta address of where to store the meta information
2882 * @return 0 on success, non-zero on failure.
2885 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
2891 DPUTS("writing new meta page");
2893 GET_PAGESIZE(psize);
2895 meta->mm_magic = MDB_MAGIC;
2896 meta->mm_version = MDB_DATA_VERSION;
2897 meta->mm_mapsize = env->me_mapsize;
2898 meta->mm_psize = psize;
2899 meta->mm_last_pg = 1;
2900 meta->mm_flags = env->me_flags & 0xffff;
2901 meta->mm_flags |= MDB_INTEGERKEY;
2902 meta->mm_dbs[0].md_root = P_INVALID;
2903 meta->mm_dbs[1].md_root = P_INVALID;
2905 p = calloc(2, psize);
2907 p->mp_flags = P_META;
2908 *(MDB_meta *)METADATA(p) = *meta;
2910 q = (MDB_page *)((char *)p + psize);
2912 q->mp_flags = P_META;
2913 *(MDB_meta *)METADATA(q) = *meta;
2919 memset(&ov, 0, sizeof(ov));
2920 rc = WriteFile(env->me_fd, p, psize * 2, &len, &ov);
2921 rc = rc ? (len == psize * 2 ? MDB_SUCCESS : EIO) : ErrCode();
2924 rc = pwrite(env->me_fd, p, psize * 2, 0);
2925 rc = (rc == (int)psize * 2) ? MDB_SUCCESS : rc < 0 ? ErrCode() : EIO;
2931 /** Update the environment info to commit a transaction.
2932 * @param[in] txn the transaction that's being committed
2933 * @return 0 on success, non-zero on failure.
2936 mdb_env_write_meta(MDB_txn *txn)
2939 MDB_meta meta, metab, *mp;
2941 int rc, len, toggle;
2950 assert(txn != NULL);
2951 assert(txn->mt_env != NULL);
2953 toggle = !txn->mt_toggle;
2954 DPRINTF("writing meta page %d for root page %zu",
2955 toggle, txn->mt_dbs[MAIN_DBI].md_root);
2958 mp = env->me_metas[toggle];
2960 if (env->me_flags & MDB_WRITEMAP) {
2961 /* Persist any increases of mapsize config */
2962 if (env->me_mapsize > mp->mm_mapsize)
2963 mp->mm_mapsize = env->me_mapsize;
2964 mp->mm_dbs[0] = txn->mt_dbs[0];
2965 mp->mm_dbs[1] = txn->mt_dbs[1];
2966 mp->mm_last_pg = txn->mt_next_pgno - 1;
2967 mp->mm_txnid = txn->mt_txnid;
2968 if (!(env->me_flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
2969 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
2972 ptr += env->me_psize;
2973 if (MDB_MSYNC(ptr, env->me_psize, rc)) {
2980 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
2981 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
2983 ptr = (char *)&meta;
2984 if (env->me_mapsize > mp->mm_mapsize) {
2985 /* Persist any increases of mapsize config */
2986 meta.mm_mapsize = env->me_mapsize;
2987 off = offsetof(MDB_meta, mm_mapsize);
2989 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
2991 len = sizeof(MDB_meta) - off;
2994 meta.mm_dbs[0] = txn->mt_dbs[0];
2995 meta.mm_dbs[1] = txn->mt_dbs[1];
2996 meta.mm_last_pg = txn->mt_next_pgno - 1;
2997 meta.mm_txnid = txn->mt_txnid;
3000 off += env->me_psize;
3003 /* Write to the SYNC fd */
3004 mfd = env->me_flags & (MDB_NOSYNC|MDB_NOMETASYNC) ?
3005 env->me_fd : env->me_mfd;
3008 memset(&ov, 0, sizeof(ov));
3010 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3014 rc = pwrite(mfd, ptr, len, off);
3017 rc = rc < 0 ? ErrCode() : EIO;
3018 DPUTS("write failed, disk error?");
3019 /* On a failure, the pagecache still contains the new data.
3020 * Write some old data back, to prevent it from being used.
3021 * Use the non-SYNC fd; we know it will fail anyway.
3023 meta.mm_last_pg = metab.mm_last_pg;
3024 meta.mm_txnid = metab.mm_txnid;
3026 memset(&ov, 0, sizeof(ov));
3028 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3030 r2 = pwrite(env->me_fd, ptr, len, off);
3033 env->me_flags |= MDB_FATAL_ERROR;
3037 /* Memory ordering issues are irrelevant; since the entire writer
3038 * is wrapped by wmutex, all of these changes will become visible
3039 * after the wmutex is unlocked. Since the DB is multi-version,
3040 * readers will get consistent data regardless of how fresh or
3041 * how stale their view of these values is.
3043 env->me_txns->mti_txnid = txn->mt_txnid;
3048 /** Check both meta pages to see which one is newer.
3049 * @param[in] env the environment handle
3050 * @return meta toggle (0 or 1).
3053 mdb_env_pick_meta(const MDB_env *env)
3055 return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
3059 mdb_env_create(MDB_env **env)
3063 e = calloc(1, sizeof(MDB_env));
3067 e->me_maxreaders = DEFAULT_READERS;
3068 e->me_maxdbs = e->me_numdbs = 2;
3069 e->me_fd = INVALID_HANDLE_VALUE;
3070 e->me_lfd = INVALID_HANDLE_VALUE;
3071 e->me_mfd = INVALID_HANDLE_VALUE;
3072 #ifdef MDB_USE_POSIX_SEM
3073 e->me_rmutex = SEM_FAILED;
3074 e->me_wmutex = SEM_FAILED;
3076 e->me_pid = getpid();
3077 VGMEMP_CREATE(e,0,0);
3083 mdb_env_set_mapsize(MDB_env *env, size_t size)
3087 env->me_mapsize = size;
3089 env->me_maxpg = env->me_mapsize / env->me_psize;
3094 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
3098 env->me_maxdbs = dbs + 2; /* Named databases + main and free DB */
3103 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
3105 if (env->me_map || readers < 1)
3107 env->me_maxreaders = readers;
3112 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
3114 if (!env || !readers)
3116 *readers = env->me_maxreaders;
3120 /** Further setup required for opening an MDB environment
3123 mdb_env_open2(MDB_env *env)
3125 unsigned int flags = env->me_flags;
3133 memset(&meta, 0, sizeof(meta));
3135 if ((i = mdb_env_read_header(env, &meta)) != 0) {
3138 DPUTS("new mdbenv");
3142 /* Was a mapsize configured? */
3143 if (!env->me_mapsize) {
3144 /* If this is a new environment, take the default,
3145 * else use the size recorded in the existing env.
3147 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
3148 } else if (env->me_mapsize < meta.mm_mapsize) {
3149 /* If the configured size is smaller, make sure it's
3150 * still big enough. Silently round up to minimum if not.
3152 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
3153 if (env->me_mapsize < minsize)
3154 env->me_mapsize = minsize;
3161 LONG sizelo, sizehi;
3162 sizelo = env->me_mapsize & 0xffffffff;
3163 sizehi = env->me_mapsize >> 16 >> 16; /* only needed on Win64 */
3164 /* Windows won't create mappings for zero length files.
3165 * Just allocate the maxsize right now.
3168 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3169 || !SetEndOfFile(env->me_fd)
3170 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3173 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3174 PAGE_READWRITE : PAGE_READONLY,
3175 sizehi, sizelo, NULL);
3178 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3179 FILE_MAP_WRITE : FILE_MAP_READ,
3180 0, 0, env->me_mapsize, meta.mm_address);
3181 rc = env->me_map ? 0 : ErrCode();
3189 if (flags & MDB_WRITEMAP) {
3191 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3194 env->me_map = mmap(meta.mm_address, env->me_mapsize, prot, i,
3196 if (env->me_map == MAP_FAILED) {
3200 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3202 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3204 #ifdef POSIX_MADV_RANDOM
3205 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3206 #endif /* POSIX_MADV_RANDOM */
3207 #endif /* MADV_RANDOM */
3211 if (flags & MDB_FIXEDMAP)
3212 meta.mm_address = env->me_map;
3213 i = mdb_env_init_meta(env, &meta);
3214 if (i != MDB_SUCCESS) {
3217 } else if (meta.mm_address && env->me_map != meta.mm_address) {
3218 /* Can happen because the address argument to mmap() is just a
3219 * hint. mmap() can pick another, e.g. if the range is in use.
3220 * The MAP_FIXED flag would prevent that, but then mmap could
3221 * instead unmap existing pages to make room for the new map.
3223 return EBUSY; /* TODO: Make a new MDB_* error code? */
3225 env->me_psize = meta.mm_psize;
3226 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
3227 env->me_nodemax = (env->me_psize - PAGEHDRSZ) / MDB_MINKEYS;
3229 env->me_maxpg = env->me_mapsize / env->me_psize;
3231 p = (MDB_page *)env->me_map;
3232 env->me_metas[0] = METADATA(p);
3233 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
3237 int toggle = mdb_env_pick_meta(env);
3238 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
3240 DPRINTF("opened database version %u, pagesize %u",
3241 env->me_metas[0]->mm_version, env->me_psize);
3242 DPRINTF("using meta page %d", toggle);
3243 DPRINTF("depth: %u", db->md_depth);
3244 DPRINTF("entries: %zu", db->md_entries);
3245 DPRINTF("branch pages: %zu", db->md_branch_pages);
3246 DPRINTF("leaf pages: %zu", db->md_leaf_pages);
3247 DPRINTF("overflow pages: %zu", db->md_overflow_pages);
3248 DPRINTF("root: %zu", db->md_root);
3256 /** Release a reader thread's slot in the reader lock table.
3257 * This function is called automatically when a thread exits.
3258 * @param[in] ptr This points to the slot in the reader lock table.
3261 mdb_env_reader_dest(void *ptr)
3263 MDB_reader *reader = ptr;
3269 /** Junk for arranging thread-specific callbacks on Windows. This is
3270 * necessarily platform and compiler-specific. Windows supports up
3271 * to 1088 keys. Let's assume nobody opens more than 64 environments
3272 * in a single process, for now. They can override this if needed.
3274 #ifndef MAX_TLS_KEYS
3275 #define MAX_TLS_KEYS 64
3277 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
3278 static int mdb_tls_nkeys;
3280 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
3284 case DLL_PROCESS_ATTACH: break;
3285 case DLL_THREAD_ATTACH: break;
3286 case DLL_THREAD_DETACH:
3287 for (i=0; i<mdb_tls_nkeys; i++) {
3288 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
3289 mdb_env_reader_dest(r);
3292 case DLL_PROCESS_DETACH: break;
3297 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3299 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3303 /* Force some symbol references.
3304 * _tls_used forces the linker to create the TLS directory if not already done
3305 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
3307 #pragma comment(linker, "/INCLUDE:_tls_used")
3308 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
3309 #pragma const_seg(".CRT$XLB")
3310 extern const PIMAGE_TLS_CALLBACK mdb_tls_callback;
3311 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3314 #pragma comment(linker, "/INCLUDE:__tls_used")
3315 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
3316 #pragma data_seg(".CRT$XLB")
3317 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3319 #endif /* WIN 32/64 */
3320 #endif /* !__GNUC__ */
3323 /** Downgrade the exclusive lock on the region back to shared */
3325 mdb_env_share_locks(MDB_env *env, int *excl)
3327 int rc = 0, toggle = mdb_env_pick_meta(env);
3329 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
3334 /* First acquire a shared lock. The Unlock will
3335 * then release the existing exclusive lock.
3337 memset(&ov, 0, sizeof(ov));
3338 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3341 UnlockFile(env->me_lfd, 0, 0, 1, 0);
3347 struct flock lock_info;
3348 /* The shared lock replaces the existing lock */
3349 memset((void *)&lock_info, 0, sizeof(lock_info));
3350 lock_info.l_type = F_RDLCK;
3351 lock_info.l_whence = SEEK_SET;
3352 lock_info.l_start = 0;
3353 lock_info.l_len = 1;
3354 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3355 (rc = ErrCode()) == EINTR) ;
3356 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
3363 /** Try to get exlusive lock, otherwise shared.
3364 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
3367 mdb_env_excl_lock(MDB_env *env, int *excl)
3371 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
3375 memset(&ov, 0, sizeof(ov));
3376 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3383 struct flock lock_info;
3384 memset((void *)&lock_info, 0, sizeof(lock_info));
3385 lock_info.l_type = F_WRLCK;
3386 lock_info.l_whence = SEEK_SET;
3387 lock_info.l_start = 0;
3388 lock_info.l_len = 1;
3389 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3390 (rc = ErrCode()) == EINTR) ;
3394 # ifdef MDB_USE_POSIX_SEM
3395 if (*excl < 0) /* always true when !MDB_USE_POSIX_SEM */
3398 lock_info.l_type = F_RDLCK;
3399 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
3400 (rc = ErrCode()) == EINTR) ;
3408 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
3410 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
3412 * @(#) $Revision: 5.1 $
3413 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
3414 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
3416 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
3420 * Please do not copyright this code. This code is in the public domain.
3422 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
3423 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
3424 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
3425 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
3426 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
3427 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
3428 * PERFORMANCE OF THIS SOFTWARE.
3431 * chongo <Landon Curt Noll> /\oo/\
3432 * http://www.isthe.com/chongo/
3434 * Share and Enjoy! :-)
3437 typedef unsigned long long mdb_hash_t;
3438 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
3440 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
3441 * @param[in] str string to hash
3442 * @param[in] hval initial value for hash
3443 * @return 64 bit hash
3445 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
3446 * hval arg on the first call.
3449 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
3451 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
3452 unsigned char *end = s + val->mv_size;
3454 * FNV-1a hash each octet of the string
3457 /* xor the bottom with the current octet */
3458 hval ^= (mdb_hash_t)*s++;
3460 /* multiply by the 64 bit FNV magic prime mod 2^64 */
3461 hval += (hval << 1) + (hval << 4) + (hval << 5) +
3462 (hval << 7) + (hval << 8) + (hval << 40);
3464 /* return our new hash value */
3468 /** Hash the string and output the hash in hex.
3469 * @param[in] str string to hash
3470 * @param[out] hexbuf an array of 17 chars to hold the hash
3473 mdb_hash_hex(MDB_val *val, char *hexbuf)
3476 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
3477 for (i=0; i<8; i++) {
3478 hexbuf += sprintf(hexbuf, "%02x", (unsigned int)h & 0xff);
3484 /** Open and/or initialize the lock region for the environment.
3485 * @param[in] env The MDB environment.
3486 * @param[in] lpath The pathname of the file used for the lock region.
3487 * @param[in] mode The Unix permissions for the file, if we create it.
3488 * @param[out] excl Resulting file lock type: -1 none, 0 shared, 1 exclusive
3489 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
3490 * @return 0 on success, non-zero on failure.
3493 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
3496 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
3498 # define MDB_ERRCODE_ROFS EROFS
3499 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
3500 # define MDB_CLOEXEC O_CLOEXEC
3503 # define MDB_CLOEXEC 0
3510 env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
3511 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
3512 FILE_ATTRIBUTE_NORMAL, NULL);
3514 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
3516 if (env->me_lfd == INVALID_HANDLE_VALUE) {
3518 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
3523 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
3524 /* Lose record locks when exec*() */
3525 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
3526 fcntl(env->me_lfd, F_SETFD, fdflags);
3529 if (!(env->me_flags & MDB_NOTLS)) {
3530 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
3533 env->me_flags |= MDB_ENV_TXKEY;
3535 /* Windows TLS callbacks need help finding their TLS info. */
3536 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
3540 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
3544 /* Try to get exclusive lock. If we succeed, then
3545 * nobody is using the lock region and we should initialize it.
3547 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
3550 size = GetFileSize(env->me_lfd, NULL);
3552 size = lseek(env->me_lfd, 0, SEEK_END);
3553 if (size == -1) goto fail_errno;
3555 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
3556 if (size < rsize && *excl > 0) {
3558 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != rsize
3559 || !SetEndOfFile(env->me_lfd))
3562 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
3566 size = rsize - sizeof(MDB_txninfo);
3567 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
3572 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
3574 if (!mh) goto fail_errno;
3575 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
3577 if (!env->me_txns) goto fail_errno;
3579 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
3581 if (m == MAP_FAILED) goto fail_errno;
3587 BY_HANDLE_FILE_INFORMATION stbuf;
3596 if (!mdb_sec_inited) {
3597 InitializeSecurityDescriptor(&mdb_null_sd,
3598 SECURITY_DESCRIPTOR_REVISION);
3599 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
3600 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
3601 mdb_all_sa.bInheritHandle = FALSE;
3602 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
3605 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
3606 idbuf.volume = stbuf.dwVolumeSerialNumber;
3607 idbuf.nhigh = stbuf.nFileIndexHigh;
3608 idbuf.nlow = stbuf.nFileIndexLow;
3609 val.mv_data = &idbuf;
3610 val.mv_size = sizeof(idbuf);
3611 mdb_hash_hex(&val, hexbuf);
3612 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", hexbuf);
3613 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", hexbuf);
3614 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
3615 if (!env->me_rmutex) goto fail_errno;
3616 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
3617 if (!env->me_wmutex) goto fail_errno;
3618 #elif defined(MDB_USE_POSIX_SEM)
3627 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
3628 idbuf.dev = stbuf.st_dev;
3629 idbuf.ino = stbuf.st_ino;
3630 val.mv_data = &idbuf;
3631 val.mv_size = sizeof(idbuf);
3632 mdb_hash_hex(&val, hexbuf);
3633 sprintf(env->me_txns->mti_rmname, "/MDBr%s", hexbuf);
3634 sprintf(env->me_txns->mti_wmname, "/MDBw%s", hexbuf);
3635 /* Clean up after a previous run, if needed: Try to
3636 * remove both semaphores before doing anything else.
3638 sem_unlink(env->me_txns->mti_rmname);
3639 sem_unlink(env->me_txns->mti_wmname);
3640 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
3641 O_CREAT|O_EXCL, mode, 1);
3642 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3643 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
3644 O_CREAT|O_EXCL, mode, 1);
3645 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3646 #else /* MDB_USE_POSIX_SEM */
3647 pthread_mutexattr_t mattr;
3649 if ((rc = pthread_mutexattr_init(&mattr))
3650 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
3651 || (rc = pthread_mutex_init(&env->me_txns->mti_mutex, &mattr))
3652 || (rc = pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr)))
3654 pthread_mutexattr_destroy(&mattr);
3655 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
3657 env->me_txns->mti_version = MDB_LOCK_VERSION;
3658 env->me_txns->mti_magic = MDB_MAGIC;
3659 env->me_txns->mti_txnid = 0;
3660 env->me_txns->mti_numreaders = 0;
3663 if (env->me_txns->mti_magic != MDB_MAGIC) {
3664 DPUTS("lock region has invalid magic");
3668 if (env->me_txns->mti_version != MDB_LOCK_VERSION) {
3669 DPRINTF("lock region is version %u, expected version %u",
3670 env->me_txns->mti_version, MDB_LOCK_VERSION);
3671 rc = MDB_VERSION_MISMATCH;
3675 if (rc && rc != EACCES && rc != EAGAIN) {
3679 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
3680 if (!env->me_rmutex) goto fail_errno;
3681 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
3682 if (!env->me_wmutex) goto fail_errno;
3683 #elif defined(MDB_USE_POSIX_SEM)
3684 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
3685 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3686 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
3687 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3698 /** The name of the lock file in the DB environment */
3699 #define LOCKNAME "/lock.mdb"
3700 /** The name of the data file in the DB environment */
3701 #define DATANAME "/data.mdb"
3702 /** The suffix of the lock file when no subdir is used */
3703 #define LOCKSUFF "-lock"
3704 /** Only a subset of the @ref mdb_env flags can be changed
3705 * at runtime. Changing other flags requires closing the
3706 * environment and re-opening it with the new flags.
3708 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC)
3709 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY|MDB_WRITEMAP|MDB_NOTLS)
3712 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
3714 int oflags, rc, len, excl = -1;
3715 char *lpath, *dpath;
3717 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
3721 if (flags & MDB_NOSUBDIR) {
3722 rc = len + sizeof(LOCKSUFF) + len + 1;
3724 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
3729 if (flags & MDB_NOSUBDIR) {
3730 dpath = lpath + len + sizeof(LOCKSUFF);
3731 sprintf(lpath, "%s" LOCKSUFF, path);
3732 strcpy(dpath, path);
3734 dpath = lpath + len + sizeof(LOCKNAME);
3735 sprintf(lpath, "%s" LOCKNAME, path);
3736 sprintf(dpath, "%s" DATANAME, path);
3740 flags |= env->me_flags;
3741 if (flags & MDB_RDONLY) {
3742 /* silently ignore WRITEMAP when we're only getting read access */
3743 flags &= ~MDB_WRITEMAP;
3745 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
3746 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
3749 env->me_flags = flags |= MDB_ENV_ACTIVE;
3753 env->me_path = strdup(path);
3754 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
3755 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
3756 if (!(env->me_dbxs && env->me_path && env->me_dbflags)) {
3761 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
3766 if (F_ISSET(flags, MDB_RDONLY)) {
3767 oflags = GENERIC_READ;
3768 len = OPEN_EXISTING;
3770 oflags = GENERIC_READ|GENERIC_WRITE;
3773 mode = FILE_ATTRIBUTE_NORMAL;
3774 env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
3775 NULL, len, mode, NULL);
3777 if (F_ISSET(flags, MDB_RDONLY))
3780 oflags = O_RDWR | O_CREAT;
3782 env->me_fd = open(dpath, oflags, mode);
3784 if (env->me_fd == INVALID_HANDLE_VALUE) {
3789 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
3790 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
3791 env->me_mfd = env->me_fd;
3793 /* Synchronous fd for meta writes. Needed even with
3794 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
3797 env->me_mfd = CreateFile(dpath, oflags,
3798 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
3799 mode | FILE_FLAG_WRITE_THROUGH, NULL);
3801 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
3803 if (env->me_mfd == INVALID_HANDLE_VALUE) {
3808 DPRINTF("opened dbenv %p", (void *) env);
3810 rc = mdb_env_share_locks(env, &excl);
3816 mdb_env_close0(env, excl);
3822 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
3824 mdb_env_close0(MDB_env *env, int excl)
3828 if (!(env->me_flags & MDB_ENV_ACTIVE))
3831 /* Doing this here since me_dbxs may not exist during mdb_env_close */
3832 for (i = env->me_maxdbs; --i > MAIN_DBI; )
3833 free(env->me_dbxs[i].md_name.mv_data);
3835 free(env->me_dbflags);
3838 free(env->me_dirty_list);
3839 mdb_midl_free(env->me_free_pgs);
3841 if (env->me_flags & MDB_ENV_TXKEY) {
3842 pthread_key_delete(env->me_txkey);
3844 /* Delete our key from the global list */
3845 for (i=0; i<mdb_tls_nkeys; i++)
3846 if (mdb_tls_keys[i] == env->me_txkey) {
3847 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
3855 munmap(env->me_map, env->me_mapsize);
3857 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
3858 (void) close(env->me_mfd);
3859 if (env->me_fd != INVALID_HANDLE_VALUE)
3860 (void) close(env->me_fd);
3862 pid_t pid = env->me_pid;
3863 /* Clearing readers is done in this function because
3864 * me_txkey with its destructor must be disabled first.
3866 for (i = env->me_numreaders; --i >= 0; )
3867 if (env->me_txns->mti_readers[i].mr_pid == pid)
3868 env->me_txns->mti_readers[i].mr_pid = 0;
3870 if (env->me_rmutex) {
3871 CloseHandle(env->me_rmutex);
3872 if (env->me_wmutex) CloseHandle(env->me_wmutex);
3874 /* Windows automatically destroys the mutexes when
3875 * the last handle closes.
3877 #elif defined(MDB_USE_POSIX_SEM)
3878 if (env->me_rmutex != SEM_FAILED) {
3879 sem_close(env->me_rmutex);
3880 if (env->me_wmutex != SEM_FAILED)
3881 sem_close(env->me_wmutex);
3882 /* If we have the filelock: If we are the
3883 * only remaining user, clean up semaphores.
3886 mdb_env_excl_lock(env, &excl);
3888 sem_unlink(env->me_txns->mti_rmname);
3889 sem_unlink(env->me_txns->mti_wmname);
3893 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
3895 if (env->me_lfd != INVALID_HANDLE_VALUE) {
3898 /* Unlock the lockfile. Windows would have unlocked it
3899 * after closing anyway, but not necessarily at once.
3901 UnlockFile(env->me_lfd, 0, 0, 1, 0);
3904 (void) close(env->me_lfd);
3907 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
3911 mdb_env_copyfd(MDB_env *env, HANDLE fd)
3913 MDB_txn *txn = NULL;
3918 /* Do the lock/unlock of the reader mutex before starting the
3919 * write txn. Otherwise other read txns could block writers.
3921 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
3926 /* We must start the actual read txn after blocking writers */
3927 mdb_txn_reset0(txn, "reset-stage1");
3929 /* Temporarily block writers until we snapshot the meta pages */
3932 rc = mdb_txn_renew0(txn);
3934 UNLOCK_MUTEX_W(env);
3939 wsize = env->me_psize * 2;
3943 rc = WriteFile(fd, env->me_map, wsize, &len, NULL);
3944 rc = rc ? (len == wsize ? MDB_SUCCESS : EIO) : ErrCode();
3947 rc = write(fd, env->me_map, wsize);
3948 rc = rc == (int)wsize ? MDB_SUCCESS : rc < 0 ? ErrCode() : EIO;
3951 UNLOCK_MUTEX_W(env);
3956 ptr = env->me_map + wsize;
3957 wsize = txn->mt_next_pgno * env->me_psize - wsize;
3961 if (wsize > MAX_WRITE)
3965 rc = WriteFile(fd, ptr, w2, &len, NULL);
3966 rc = rc ? (len == w2 ? MDB_SUCCESS : EIO) : ErrCode();
3975 if (wsize > MAX_WRITE)
3979 wres = write(fd, ptr, w2);
3980 rc = wres == (ssize_t)w2 ? MDB_SUCCESS : wres < 0 ? ErrCode() : EIO;
3993 mdb_env_copy(MDB_env *env, const char *path)
3997 HANDLE newfd = INVALID_HANDLE_VALUE;
3999 if (env->me_flags & MDB_NOSUBDIR) {
4000 lpath = (char *)path;
4003 len += sizeof(DATANAME);
4004 lpath = malloc(len);
4007 sprintf(lpath, "%s" DATANAME, path);
4010 /* The destination path must exist, but the destination file must not.
4011 * We don't want the OS to cache the writes, since the source data is
4012 * already in the OS cache.
4015 newfd = CreateFile(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
4016 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
4018 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL
4024 if (newfd == INVALID_HANDLE_VALUE) {
4029 #ifdef F_NOCACHE /* __APPLE__ */
4030 rc = fcntl(newfd, F_NOCACHE, 1);
4037 rc = mdb_env_copyfd(env, newfd);
4040 if (!(env->me_flags & MDB_NOSUBDIR))
4042 if (newfd != INVALID_HANDLE_VALUE)
4043 if (close(newfd) < 0 && rc == MDB_SUCCESS)
4050 mdb_env_close(MDB_env *env)
4057 VGMEMP_DESTROY(env);
4058 while ((dp = env->me_dpages) != NULL) {
4059 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
4060 env->me_dpages = dp->mp_next;
4064 mdb_env_close0(env, 0);
4068 /** Compare two items pointing at aligned size_t's */
4070 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
4072 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
4073 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
4076 /** Compare two items pointing at aligned int's */
4078 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
4080 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
4081 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
4084 /** Compare two items pointing at ints of unknown alignment.
4085 * Nodes and keys are guaranteed to be 2-byte aligned.
4088 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
4090 #if BYTE_ORDER == LITTLE_ENDIAN
4091 unsigned short *u, *c;
4094 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4095 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
4098 } while(!x && u > (unsigned short *)a->mv_data);
4101 return memcmp(a->mv_data, b->mv_data, a->mv_size);
4105 /** Compare two items lexically */
4107 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
4114 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4120 diff = memcmp(a->mv_data, b->mv_data, len);
4121 return diff ? diff : len_diff<0 ? -1 : len_diff;
4124 /** Compare two items in reverse byte order */
4126 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
4128 const unsigned char *p1, *p2, *p1_lim;
4132 p1_lim = (const unsigned char *)a->mv_data;
4133 p1 = (const unsigned char *)a->mv_data + a->mv_size;
4134 p2 = (const unsigned char *)b->mv_data + b->mv_size;
4136 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4142 while (p1 > p1_lim) {
4143 diff = *--p1 - *--p2;
4147 return len_diff<0 ? -1 : len_diff;
4150 /** Search for key within a page, using binary search.
4151 * Returns the smallest entry larger or equal to the key.
4152 * If exactp is non-null, stores whether the found entry was an exact match
4153 * in *exactp (1 or 0).
4154 * Updates the cursor index with the index of the found entry.
4155 * If no entry larger or equal to the key is found, returns NULL.
4158 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
4160 unsigned int i = 0, nkeys;
4163 MDB_page *mp = mc->mc_pg[mc->mc_top];
4164 MDB_node *node = NULL;
4169 nkeys = NUMKEYS(mp);
4174 COPY_PGNO(pgno, mp->mp_pgno);
4175 DPRINTF("searching %u keys in %s %spage %zu",
4176 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
4183 low = IS_LEAF(mp) ? 0 : 1;
4185 cmp = mc->mc_dbx->md_cmp;
4187 /* Branch pages have no data, so if using integer keys,
4188 * alignment is guaranteed. Use faster mdb_cmp_int.
4190 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
4191 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
4198 nodekey.mv_size = mc->mc_db->md_pad;
4199 node = NODEPTR(mp, 0); /* fake */
4200 while (low <= high) {
4201 i = (low + high) >> 1;
4202 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
4203 rc = cmp(key, &nodekey);
4204 DPRINTF("found leaf index %u [%s], rc = %i",
4205 i, DKEY(&nodekey), rc);
4214 while (low <= high) {
4215 i = (low + high) >> 1;
4217 node = NODEPTR(mp, i);
4218 nodekey.mv_size = NODEKSZ(node);
4219 nodekey.mv_data = NODEKEY(node);
4221 rc = cmp(key, &nodekey);
4224 DPRINTF("found leaf index %u [%s], rc = %i",
4225 i, DKEY(&nodekey), rc);
4227 DPRINTF("found branch index %u [%s -> %zu], rc = %i",
4228 i, DKEY(&nodekey), NODEPGNO(node), rc);
4239 if (rc > 0) { /* Found entry is less than the key. */
4240 i++; /* Skip to get the smallest entry larger than key. */
4242 node = NODEPTR(mp, i);
4245 *exactp = (rc == 0);
4246 /* store the key index */
4247 mc->mc_ki[mc->mc_top] = i;
4249 /* There is no entry larger or equal to the key. */
4252 /* nodeptr is fake for LEAF2 */
4258 mdb_cursor_adjust(MDB_cursor *mc, func)
4262 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4263 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
4270 /** Pop a page off the top of the cursor's stack. */
4272 mdb_cursor_pop(MDB_cursor *mc)
4275 #ifndef MDB_DEBUG_SKIP
4276 MDB_page *top = mc->mc_pg[mc->mc_top];
4282 DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
4283 mc->mc_dbi, (void *) mc);
4287 /** Push a page onto the top of the cursor's stack. */
4289 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
4291 DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
4292 mc->mc_dbi, (void *) mc);
4294 if (mc->mc_snum >= CURSOR_STACK) {
4295 assert(mc->mc_snum < CURSOR_STACK);
4296 return MDB_CURSOR_FULL;
4299 mc->mc_top = mc->mc_snum++;
4300 mc->mc_pg[mc->mc_top] = mp;
4301 mc->mc_ki[mc->mc_top] = 0;
4306 /** Find the address of the page corresponding to a given page number.
4307 * @param[in] txn the transaction for this access.
4308 * @param[in] pgno the page number for the page to retrieve.
4309 * @param[out] ret address of a pointer where the page's address will be stored.
4310 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
4311 * @return 0 on success, non-zero on failure.
4314 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
4319 if (!((txn->mt_flags & MDB_TXN_RDONLY) |
4320 (txn->mt_env->me_flags & MDB_WRITEMAP)))
4325 MDB_ID2L dl = tx2->mt_u.dirty_list;
4327 /* Spilled pages were dirtied in this txn and flushed
4328 * because the dirty list got full. Bring this page
4329 * back in from the map (but don't unspill it here,
4330 * leave that unless page_touch happens again).
4332 if (tx2->mt_spill_pgs) {
4333 x = mdb_midl_search(tx2->mt_spill_pgs, pgno);
4334 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pgno) {
4335 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
4340 unsigned x = mdb_mid2l_search(dl, pgno);
4341 if (x <= dl[0].mid && dl[x].mid == pgno) {
4347 } while ((tx2 = tx2->mt_parent) != NULL);
4350 if (pgno < txn->mt_next_pgno) {
4352 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
4354 DPRINTF("page %zu not found", pgno);
4356 return MDB_PAGE_NOTFOUND;
4366 /** Search for the page a given key should be in.
4367 * Pushes parent pages on the cursor stack. This function continues a
4368 * search on a cursor that has already been initialized. (Usually by
4369 * #mdb_page_search() but also by #mdb_node_move().)
4370 * @param[in,out] mc the cursor for this operation.
4371 * @param[in] key the key to search for. If NULL, search for the lowest
4372 * page. (This is used by #mdb_cursor_first().)
4373 * @param[in] modify If true, visited pages are updated with new page numbers.
4374 * @return 0 on success, non-zero on failure.
4377 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
4379 MDB_page *mp = mc->mc_pg[mc->mc_top];
4384 while (IS_BRANCH(mp)) {
4388 DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
4389 assert(NUMKEYS(mp) > 1);
4390 DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
4392 if (key == NULL) /* Initialize cursor to first page. */
4394 else if (key->mv_size > MDB_MAXKEYSIZE && key->mv_data == NULL) {
4395 /* cursor to last page */
4399 node = mdb_node_search(mc, key, &exact);
4401 i = NUMKEYS(mp) - 1;
4403 i = mc->mc_ki[mc->mc_top];
4412 DPRINTF("following index %u for key [%s]",
4414 assert(i < NUMKEYS(mp));
4415 node = NODEPTR(mp, i);
4417 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4420 mc->mc_ki[mc->mc_top] = i;
4421 if ((rc = mdb_cursor_push(mc, mp)))
4425 if ((rc = mdb_page_touch(mc)) != 0)
4427 mp = mc->mc_pg[mc->mc_top];
4432 DPRINTF("internal error, index points to a %02X page!?",
4434 return MDB_CORRUPTED;
4437 DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
4438 key ? DKEY(key) : NULL);
4439 mc->mc_flags |= C_INITIALIZED;
4440 mc->mc_flags &= ~C_EOF;
4445 /** Search for the lowest key under the current branch page.
4446 * This just bypasses a NUMKEYS check in the current page
4447 * before calling mdb_page_search_root(), because the callers
4448 * are all in situations where the current page is known to
4452 mdb_page_search_lowest(MDB_cursor *mc)
4454 MDB_page *mp = mc->mc_pg[mc->mc_top];
4455 MDB_node *node = NODEPTR(mp, 0);
4458 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4461 mc->mc_ki[mc->mc_top] = 0;
4462 if ((rc = mdb_cursor_push(mc, mp)))
4464 return mdb_page_search_root(mc, NULL, 0);
4467 /** Search for the page a given key should be in.
4468 * Pushes parent pages on the cursor stack. This function just sets up
4469 * the search; it finds the root page for \b mc's database and sets this
4470 * as the root of the cursor's stack. Then #mdb_page_search_root() is
4471 * called to complete the search.
4472 * @param[in,out] mc the cursor for this operation.
4473 * @param[in] key the key to search for. If NULL, search for the lowest
4474 * page. (This is used by #mdb_cursor_first().)
4475 * @param[in] flags If MDB_PS_MODIFY set, visited pages are updated with new page numbers.
4476 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
4477 * @return 0 on success, non-zero on failure.
4480 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
4485 /* Make sure the txn is still viable, then find the root from
4486 * the txn's db table.
4488 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
4489 DPUTS("transaction has failed, must abort");
4492 /* Make sure we're using an up-to-date root */
4493 if (mc->mc_dbi > MAIN_DBI) {
4494 if ((*mc->mc_dbflag & DB_STALE) ||
4495 ((flags & MDB_PS_MODIFY) && !(*mc->mc_dbflag & DB_DIRTY))) {
4497 unsigned char dbflag = 0;
4498 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
4499 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, flags & MDB_PS_MODIFY);
4502 if (*mc->mc_dbflag & DB_STALE) {
4506 MDB_node *leaf = mdb_node_search(&mc2,
4507 &mc->mc_dbx->md_name, &exact);
4509 return MDB_NOTFOUND;
4510 rc = mdb_node_read(mc->mc_txn, leaf, &data);
4513 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
4515 /* The txn may not know this DBI, or another process may
4516 * have dropped and recreated the DB with other flags.
4518 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
4519 return MDB_INCOMPATIBLE;
4520 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
4522 if (flags & MDB_PS_MODIFY)
4524 *mc->mc_dbflag &= ~DB_STALE;
4525 *mc->mc_dbflag |= dbflag;
4528 root = mc->mc_db->md_root;
4530 if (root == P_INVALID) { /* Tree is empty. */
4531 DPUTS("tree is empty");
4532 return MDB_NOTFOUND;
4537 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
4538 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0], NULL)) != 0)
4544 DPRINTF("db %u root page %zu has flags 0x%X",
4545 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
4547 if (flags & MDB_PS_MODIFY) {
4548 if ((rc = mdb_page_touch(mc)))
4552 if (flags & MDB_PS_ROOTONLY)
4555 return mdb_page_search_root(mc, key, flags);
4559 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
4561 MDB_txn *txn = mc->mc_txn;
4562 pgno_t pg = mp->mp_pgno;
4563 unsigned i, ovpages = mp->mp_pages;
4564 MDB_env *env = txn->mt_env;
4567 DPRINTF("free ov page %zu (%d)", pg, ovpages);
4568 /* If the page is dirty or on the spill list we just acquired it,
4569 * so we should give it back to our current free list, if any.
4570 * Not currently supported in nested txns.
4571 * Otherwise put it onto the list of pages we freed in this txn.
4573 if (!(mp->mp_flags & P_DIRTY) && txn->mt_spill_pgs) {
4574 unsigned x = mdb_midl_search(txn->mt_spill_pgs, pg);
4575 if (x <= txn->mt_spill_pgs[0] && txn->mt_spill_pgs[x] == pg) {
4576 /* This page is no longer spilled */
4577 for (; x < txn->mt_spill_pgs[0]; x++)
4578 txn->mt_spill_pgs[x] = txn->mt_spill_pgs[x+1];
4579 txn->mt_spill_pgs[0]--;
4583 if ((mp->mp_flags & P_DIRTY) && !txn->mt_parent && env->me_pghead) {
4586 MDB_ID2 *dl, ix, iy;
4587 rc = mdb_midl_need(&env->me_pghead, ovpages);
4590 /* Remove from dirty list */
4591 dl = txn->mt_u.dirty_list;
4593 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
4601 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
4602 txn->mt_flags |= MDB_TXN_ERROR;
4603 return MDB_CORRUPTED;
4606 if (!(env->me_flags & MDB_WRITEMAP))
4607 mdb_dpage_free(env, mp);
4609 /* Insert in me_pghead */
4610 mop = env->me_pghead;
4611 j = mop[0] + ovpages;
4612 for (i = mop[0]; i && mop[i] < pg; i--)
4618 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
4622 mc->mc_db->md_overflow_pages -= ovpages;
4626 /** Return the data associated with a given node.
4627 * @param[in] txn The transaction for this operation.
4628 * @param[in] leaf The node being read.
4629 * @param[out] data Updated to point to the node's data.
4630 * @return 0 on success, non-zero on failure.
4633 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
4635 MDB_page *omp; /* overflow page */
4639 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
4640 data->mv_size = NODEDSZ(leaf);
4641 data->mv_data = NODEDATA(leaf);
4645 /* Read overflow data.
4647 data->mv_size = NODEDSZ(leaf);
4648 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
4649 if ((rc = mdb_page_get(txn, pgno, &omp, NULL)) != 0) {
4650 DPRINTF("read overflow page %zu failed", pgno);
4653 data->mv_data = METADATA(omp);
4659 mdb_get(MDB_txn *txn, MDB_dbi dbi,
4660 MDB_val *key, MDB_val *data)
4669 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
4671 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
4674 if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
4678 mdb_cursor_init(&mc, txn, dbi, &mx);
4679 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
4682 /** Find a sibling for a page.
4683 * Replaces the page at the top of the cursor's stack with the
4684 * specified sibling, if one exists.
4685 * @param[in] mc The cursor for this operation.
4686 * @param[in] move_right Non-zero if the right sibling is requested,
4687 * otherwise the left sibling.
4688 * @return 0 on success, non-zero on failure.
4691 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
4697 if (mc->mc_snum < 2) {
4698 return MDB_NOTFOUND; /* root has no siblings */
4702 DPRINTF("parent page is page %zu, index %u",
4703 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]);
4705 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
4706 : (mc->mc_ki[mc->mc_top] == 0)) {
4707 DPRINTF("no more keys left, moving to %s sibling",
4708 move_right ? "right" : "left");
4709 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
4710 /* undo cursor_pop before returning */
4717 mc->mc_ki[mc->mc_top]++;
4719 mc->mc_ki[mc->mc_top]--;
4720 DPRINTF("just moving to %s index key %u",
4721 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]);
4723 assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
4725 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4726 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL) != 0))
4729 mdb_cursor_push(mc, mp);
4731 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
4736 /** Move the cursor to the next data item. */
4738 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
4744 if (mc->mc_flags & C_EOF) {
4745 return MDB_NOTFOUND;
4748 assert(mc->mc_flags & C_INITIALIZED);
4750 mp = mc->mc_pg[mc->mc_top];
4752 if (mc->mc_db->md_flags & MDB_DUPSORT) {
4753 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4754 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4755 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
4756 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
4757 if (op != MDB_NEXT || rc != MDB_NOTFOUND)
4761 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
4762 if (op == MDB_NEXT_DUP)
4763 return MDB_NOTFOUND;
4767 DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
4769 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
4770 DPUTS("=====> move to next sibling page");
4771 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
4772 mc->mc_flags |= C_EOF;
4775 mp = mc->mc_pg[mc->mc_top];
4776 DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
4778 mc->mc_ki[mc->mc_top]++;
4780 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
4781 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
4784 key->mv_size = mc->mc_db->md_pad;
4785 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
4789 assert(IS_LEAF(mp));
4790 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4792 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4793 mdb_xcursor_init1(mc, leaf);
4796 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4799 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4800 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4801 if (rc != MDB_SUCCESS)
4806 MDB_GET_KEY(leaf, key);
4810 /** Move the cursor to the previous data item. */
4812 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
4818 assert(mc->mc_flags & C_INITIALIZED);
4820 mp = mc->mc_pg[mc->mc_top];
4822 if (mc->mc_db->md_flags & MDB_DUPSORT) {
4823 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4824 if (op == MDB_PREV || op == MDB_PREV_DUP) {
4825 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4826 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
4827 if (op != MDB_PREV || rc != MDB_NOTFOUND)
4830 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
4831 if (op == MDB_PREV_DUP)
4832 return MDB_NOTFOUND;
4837 DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
4839 if (mc->mc_ki[mc->mc_top] == 0) {
4840 DPUTS("=====> move to prev sibling page");
4841 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
4844 mp = mc->mc_pg[mc->mc_top];
4845 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
4846 DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
4848 mc->mc_ki[mc->mc_top]--;
4850 mc->mc_flags &= ~C_EOF;
4852 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
4853 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
4856 key->mv_size = mc->mc_db->md_pad;
4857 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
4861 assert(IS_LEAF(mp));
4862 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4864 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4865 mdb_xcursor_init1(mc, leaf);
4868 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4871 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4872 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
4873 if (rc != MDB_SUCCESS)
4878 MDB_GET_KEY(leaf, key);
4882 /** Set the cursor on a specific data item. */
4884 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
4885 MDB_cursor_op op, int *exactp)
4889 MDB_node *leaf = NULL;
4894 assert(key->mv_size > 0);
4897 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
4899 /* See if we're already on the right page */
4900 if (mc->mc_flags & C_INITIALIZED) {
4903 mp = mc->mc_pg[mc->mc_top];
4905 mc->mc_ki[mc->mc_top] = 0;
4906 return MDB_NOTFOUND;
4908 if (mp->mp_flags & P_LEAF2) {
4909 nodekey.mv_size = mc->mc_db->md_pad;
4910 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
4912 leaf = NODEPTR(mp, 0);
4913 MDB_GET_KEY(leaf, &nodekey);
4915 rc = mc->mc_dbx->md_cmp(key, &nodekey);
4917 /* Probably happens rarely, but first node on the page
4918 * was the one we wanted.
4920 mc->mc_ki[mc->mc_top] = 0;
4927 unsigned int nkeys = NUMKEYS(mp);
4929 if (mp->mp_flags & P_LEAF2) {
4930 nodekey.mv_data = LEAF2KEY(mp,
4931 nkeys-1, nodekey.mv_size);
4933 leaf = NODEPTR(mp, nkeys-1);
4934 MDB_GET_KEY(leaf, &nodekey);
4936 rc = mc->mc_dbx->md_cmp(key, &nodekey);
4938 /* last node was the one we wanted */
4939 mc->mc_ki[mc->mc_top] = nkeys-1;
4945 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
4946 /* This is definitely the right page, skip search_page */
4947 if (mp->mp_flags & P_LEAF2) {
4948 nodekey.mv_data = LEAF2KEY(mp,
4949 mc->mc_ki[mc->mc_top], nodekey.mv_size);
4951 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4952 MDB_GET_KEY(leaf, &nodekey);
4954 rc = mc->mc_dbx->md_cmp(key, &nodekey);
4956 /* current node was the one we wanted */
4966 /* If any parents have right-sibs, search.
4967 * Otherwise, there's nothing further.
4969 for (i=0; i<mc->mc_top; i++)
4971 NUMKEYS(mc->mc_pg[i])-1)
4973 if (i == mc->mc_top) {
4974 /* There are no other pages */
4975 mc->mc_ki[mc->mc_top] = nkeys;
4976 return MDB_NOTFOUND;
4980 /* There are no other pages */
4981 mc->mc_ki[mc->mc_top] = 0;
4982 return MDB_NOTFOUND;
4986 rc = mdb_page_search(mc, key, 0);
4987 if (rc != MDB_SUCCESS)
4990 mp = mc->mc_pg[mc->mc_top];
4991 assert(IS_LEAF(mp));
4994 leaf = mdb_node_search(mc, key, exactp);
4995 if (exactp != NULL && !*exactp) {
4996 /* MDB_SET specified and not an exact match. */
4997 return MDB_NOTFOUND;
5001 DPUTS("===> inexact leaf not found, goto sibling");
5002 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
5003 return rc; /* no entries matched */
5004 mp = mc->mc_pg[mc->mc_top];
5005 assert(IS_LEAF(mp));
5006 leaf = NODEPTR(mp, 0);
5010 mc->mc_flags |= C_INITIALIZED;
5011 mc->mc_flags &= ~C_EOF;
5014 key->mv_size = mc->mc_db->md_pad;
5015 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5019 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5020 mdb_xcursor_init1(mc, leaf);
5023 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5024 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
5025 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5028 if (op == MDB_GET_BOTH) {
5034 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
5035 if (rc != MDB_SUCCESS)
5038 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
5040 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
5042 rc = mc->mc_dbx->md_dcmp(data, &d2);
5044 if (op == MDB_GET_BOTH || rc > 0)
5045 return MDB_NOTFOUND;
5050 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5051 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5056 /* The key already matches in all other cases */
5057 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
5058 MDB_GET_KEY(leaf, key);
5059 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
5064 /** Move the cursor to the first item in the database. */
5066 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5072 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5074 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5075 rc = mdb_page_search(mc, NULL, 0);
5076 if (rc != MDB_SUCCESS)
5079 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
5081 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
5082 mc->mc_flags |= C_INITIALIZED;
5083 mc->mc_flags &= ~C_EOF;
5085 mc->mc_ki[mc->mc_top] = 0;
5087 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5088 key->mv_size = mc->mc_db->md_pad;
5089 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
5094 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5095 mdb_xcursor_init1(mc, leaf);
5096 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5100 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5104 MDB_GET_KEY(leaf, key);
5108 /** Move the cursor to the last item in the database. */
5110 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5116 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5118 if (!(mc->mc_flags & C_EOF)) {
5120 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5123 lkey.mv_size = MDB_MAXKEYSIZE+1;
5124 lkey.mv_data = NULL;
5125 rc = mdb_page_search(mc, &lkey, 0);
5126 if (rc != MDB_SUCCESS)
5129 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
5132 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
5133 mc->mc_flags |= C_INITIALIZED|C_EOF;
5134 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5136 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5137 key->mv_size = mc->mc_db->md_pad;
5138 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
5143 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5144 mdb_xcursor_init1(mc, leaf);
5145 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5149 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5154 MDB_GET_KEY(leaf, key);
5159 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5168 case MDB_GET_CURRENT:
5169 if (!(mc->mc_flags & C_INITIALIZED)) {
5172 MDB_page *mp = mc->mc_pg[mc->mc_top];
5174 mc->mc_ki[mc->mc_top] = 0;
5180 key->mv_size = mc->mc_db->md_pad;
5181 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5183 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5184 MDB_GET_KEY(leaf, key);
5186 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5187 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
5189 rc = mdb_node_read(mc->mc_txn, leaf, data);
5196 case MDB_GET_BOTH_RANGE:
5197 if (data == NULL || mc->mc_xcursor == NULL) {
5205 if (key == NULL || key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
5207 } else if (op == MDB_SET_RANGE)
5208 rc = mdb_cursor_set(mc, key, data, op, NULL);
5210 rc = mdb_cursor_set(mc, key, data, op, &exact);
5212 case MDB_GET_MULTIPLE:
5214 !(mc->mc_db->md_flags & MDB_DUPFIXED) ||
5215 !(mc->mc_flags & C_INITIALIZED)) {
5220 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
5221 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
5224 case MDB_NEXT_MULTIPLE:
5226 !(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5230 if (!(mc->mc_flags & C_INITIALIZED))
5231 rc = mdb_cursor_first(mc, key, data);
5233 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
5234 if (rc == MDB_SUCCESS) {
5235 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
5238 mx = &mc->mc_xcursor->mx_cursor;
5239 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
5241 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
5242 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
5250 case MDB_NEXT_NODUP:
5251 if (!(mc->mc_flags & C_INITIALIZED))
5252 rc = mdb_cursor_first(mc, key, data);
5254 rc = mdb_cursor_next(mc, key, data, op);
5258 case MDB_PREV_NODUP:
5259 if (!(mc->mc_flags & C_INITIALIZED)) {
5260 rc = mdb_cursor_last(mc, key, data);
5263 mc->mc_flags |= C_INITIALIZED;
5264 mc->mc_ki[mc->mc_top]++;
5266 rc = mdb_cursor_prev(mc, key, data, op);
5269 rc = mdb_cursor_first(mc, key, data);
5273 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
5274 !(mc->mc_flags & C_INITIALIZED) ||
5275 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
5279 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5282 rc = mdb_cursor_last(mc, key, data);
5286 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
5287 !(mc->mc_flags & C_INITIALIZED) ||
5288 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
5292 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5295 DPRINTF("unhandled/unimplemented cursor operation %u", op);
5303 /** Touch all the pages in the cursor stack.
5304 * Makes sure all the pages are writable, before attempting a write operation.
5305 * @param[in] mc The cursor to operate on.
5308 mdb_cursor_touch(MDB_cursor *mc)
5312 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
5315 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
5316 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
5319 *mc->mc_dbflag |= DB_DIRTY;
5321 for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
5322 rc = mdb_page_touch(mc);
5326 mc->mc_top = mc->mc_snum-1;
5330 /** Do not spill pages to disk if txn is getting full, may fail instead */
5331 #define MDB_NOSPILL 0x8000
5334 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5337 enum { MDB_NO_ROOT = MDB_LAST_ERRCODE+10 }; /* internal code */
5338 MDB_node *leaf = NULL;
5339 MDB_val xdata, *rdata, dkey;
5342 int do_sub = 0, insert = 0;
5343 unsigned int mcount = 0, dcount = 0, nospill;
5347 char dbuf[MDB_MAXKEYSIZE+1];
5348 unsigned int nflags;
5351 /* Check this first so counter will always be zero on any
5354 if (flags & MDB_MULTIPLE) {
5355 dcount = data[1].mv_size;
5356 data[1].mv_size = 0;
5357 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
5361 nospill = flags & MDB_NOSPILL;
5362 flags &= ~MDB_NOSPILL;
5364 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
5367 if (flags != MDB_CURRENT && (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE))
5370 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT) && data->mv_size > MDB_MAXKEYSIZE)
5373 #if SIZE_MAX > MAXDATASIZE
5374 if (data->mv_size > MAXDATASIZE)
5378 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
5379 mc->mc_dbi, DKEY(key), key ? key->mv_size:0, data->mv_size);
5383 if (flags == MDB_CURRENT) {
5384 if (!(mc->mc_flags & C_INITIALIZED))
5387 } else if (mc->mc_db->md_root == P_INVALID) {
5388 /* new database, cursor has nothing to point to */
5390 mc->mc_flags &= ~C_INITIALIZED;
5395 if (flags & MDB_APPEND) {
5397 rc = mdb_cursor_last(mc, &k2, &d2);
5399 rc = mc->mc_dbx->md_cmp(key, &k2);
5402 mc->mc_ki[mc->mc_top]++;
5404 /* new key is <= last key */
5409 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
5411 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
5412 DPRINTF("duplicate key [%s]", DKEY(key));
5414 return MDB_KEYEXIST;
5416 if (rc && rc != MDB_NOTFOUND)
5420 /* Cursor is positioned, check for room in the dirty list */
5422 if (flags & MDB_MULTIPLE) {
5424 xdata.mv_size = data->mv_size * dcount;
5428 if ((rc2 = mdb_page_spill(mc, key, rdata)))
5432 if (rc == MDB_NO_ROOT) {
5434 /* new database, write a root leaf page */
5435 DPUTS("allocating new root leaf page");
5436 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
5439 mdb_cursor_push(mc, np);
5440 mc->mc_db->md_root = np->mp_pgno;
5441 mc->mc_db->md_depth++;
5442 *mc->mc_dbflag |= DB_DIRTY;
5443 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
5445 np->mp_flags |= P_LEAF2;
5446 mc->mc_flags |= C_INITIALIZED;
5448 /* make sure all cursor pages are writable */
5449 rc2 = mdb_cursor_touch(mc);
5454 /* The key already exists */
5455 if (rc == MDB_SUCCESS) {
5456 /* there's only a key anyway, so this is a no-op */
5457 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5458 unsigned int ksize = mc->mc_db->md_pad;
5459 if (key->mv_size != ksize)
5461 if (flags == MDB_CURRENT) {
5462 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
5463 memcpy(ptr, key->mv_data, ksize);
5468 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5471 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
5472 /* Was a single item before, must convert now */
5474 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5475 /* Just overwrite the current item */
5476 if (flags == MDB_CURRENT)
5479 dkey.mv_size = NODEDSZ(leaf);
5480 dkey.mv_data = NODEDATA(leaf);
5481 #if UINT_MAX < SIZE_MAX
5482 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && dkey.mv_size == sizeof(size_t))
5483 #ifdef MISALIGNED_OK
5484 mc->mc_dbx->md_dcmp = mdb_cmp_long;
5486 mc->mc_dbx->md_dcmp = mdb_cmp_cint;
5489 /* if data matches, ignore it */
5490 if (!mc->mc_dbx->md_dcmp(data, &dkey))
5491 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
5493 /* create a fake page for the dup items */
5494 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
5495 dkey.mv_data = dbuf;
5496 fp = (MDB_page *)&pbuf;
5497 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
5498 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
5499 fp->mp_lower = PAGEHDRSZ;
5500 fp->mp_upper = PAGEHDRSZ + dkey.mv_size + data->mv_size;
5501 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5502 fp->mp_flags |= P_LEAF2;
5503 fp->mp_pad = data->mv_size;
5504 fp->mp_upper += 2 * data->mv_size; /* leave space for 2 more */
5506 fp->mp_upper += 2 * sizeof(indx_t) + 2 * NODESIZE +
5507 (dkey.mv_size & 1) + (data->mv_size & 1);
5509 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5512 xdata.mv_size = fp->mp_upper;
5517 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
5518 /* See if we need to convert from fake page to subDB */
5520 unsigned int offset;
5524 fp = NODEDATA(leaf);
5525 if (flags == MDB_CURRENT) {
5527 fp->mp_flags |= P_DIRTY;
5528 COPY_PGNO(fp->mp_pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
5529 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
5533 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5534 offset = fp->mp_pad;
5535 if (SIZELEFT(fp) >= offset)
5537 offset *= 4; /* space for 4 more */
5539 offset = NODESIZE + sizeof(indx_t) + data->mv_size;
5541 offset += offset & 1;
5542 fp_flags = fp->mp_flags;
5543 if (NODESIZE + sizeof(indx_t) + NODEKSZ(leaf) + NODEDSZ(leaf) +
5544 offset >= mc->mc_txn->mt_env->me_nodemax) {
5545 /* yes, convert it */
5547 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5548 dummy.md_pad = fp->mp_pad;
5549 dummy.md_flags = MDB_DUPFIXED;
5550 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
5551 dummy.md_flags |= MDB_INTEGERKEY;
5554 dummy.md_branch_pages = 0;
5555 dummy.md_leaf_pages = 1;
5556 dummy.md_overflow_pages = 0;
5557 dummy.md_entries = NUMKEYS(fp);
5559 xdata.mv_size = sizeof(MDB_db);
5560 xdata.mv_data = &dummy;
5561 if ((rc = mdb_page_alloc(mc, 1, &mp)))
5563 offset = mc->mc_txn->mt_env->me_psize - NODEDSZ(leaf);
5564 flags |= F_DUPDATA|F_SUBDATA;
5565 dummy.md_root = mp->mp_pgno;
5566 fp_flags &= ~P_SUBP;
5568 /* no, just grow it */
5570 xdata.mv_size = NODEDSZ(leaf) + offset;
5571 xdata.mv_data = &pbuf;
5572 mp = (MDB_page *)&pbuf;
5573 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
5576 mp->mp_flags = fp_flags | P_DIRTY;
5577 mp->mp_pad = fp->mp_pad;
5578 mp->mp_lower = fp->mp_lower;
5579 mp->mp_upper = fp->mp_upper + offset;
5581 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
5583 nsize = NODEDSZ(leaf) - fp->mp_upper;
5584 memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper, nsize);
5585 for (i=0; i<NUMKEYS(fp); i++)
5586 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
5588 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5592 /* data is on sub-DB, just store it */
5593 flags |= F_DUPDATA|F_SUBDATA;
5597 /* overflow page overwrites need special handling */
5598 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5601 unsigned psize = mc->mc_txn->mt_env->me_psize;
5602 int level, ovpages, dpages = OVPAGES(data->mv_size, psize);
5604 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
5605 if ((rc2 = mdb_page_get(mc->mc_txn, pg, &omp, &level)) != 0)
5607 ovpages = omp->mp_pages;
5609 /* Is the ov page large enough? */
5610 if (ovpages >= dpages) {
5611 if (!(omp->mp_flags & P_DIRTY) &&
5612 (level || (mc->mc_txn->mt_env->me_flags & MDB_WRITEMAP)))
5614 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
5617 level = 0; /* dirty in this txn or clean */
5620 if (omp->mp_flags & P_DIRTY) {
5621 /* yes, overwrite it. Note in this case we don't
5622 * bother to try shrinking the page if the new data
5623 * is smaller than the overflow threshold.
5626 /* It is writable only in a parent txn */
5627 size_t sz = (size_t) psize * ovpages, off;
5628 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
5634 mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
5635 if (!(flags & MDB_RESERVE)) {
5636 /* Copy end of page, adjusting alignment so
5637 * compiler may copy words instead of bytes.
5639 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
5640 memcpy((size_t *)((char *)np + off),
5641 (size_t *)((char *)omp + off), sz - off);
5644 memcpy(np, omp, sz); /* Copy beginning of page */
5647 SETDSZ(leaf, data->mv_size);
5648 if (F_ISSET(flags, MDB_RESERVE))
5649 data->mv_data = METADATA(omp);
5651 memcpy(METADATA(omp), data->mv_data, data->mv_size);
5655 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
5657 } else if (NODEDSZ(leaf) == data->mv_size) {
5658 /* same size, just replace it. Note that we could
5659 * also reuse this node if the new data is smaller,
5660 * but instead we opt to shrink the node in that case.
5662 if (F_ISSET(flags, MDB_RESERVE))
5663 data->mv_data = NODEDATA(leaf);
5664 else if (data->mv_size)
5665 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
5667 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
5670 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5671 mc->mc_db->md_entries--;
5673 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
5680 nflags = flags & NODE_ADD_FLAGS;
5681 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
5682 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
5683 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
5684 nflags &= ~MDB_APPEND;
5686 nflags |= MDB_SPLIT_REPLACE;
5687 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
5689 /* There is room already in this leaf page. */
5690 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
5691 if (rc == 0 && !do_sub && insert) {
5692 /* Adjust other cursors pointing to mp */
5693 MDB_cursor *m2, *m3;
5694 MDB_dbi dbi = mc->mc_dbi;
5695 unsigned i = mc->mc_top;
5696 MDB_page *mp = mc->mc_pg[i];
5698 if (mc->mc_flags & C_SUB)
5701 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5702 if (mc->mc_flags & C_SUB)
5703 m3 = &m2->mc_xcursor->mx_cursor;
5706 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
5707 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
5714 if (rc != MDB_SUCCESS)
5715 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5717 /* Now store the actual data in the child DB. Note that we're
5718 * storing the user data in the keys field, so there are strict
5719 * size limits on dupdata. The actual data fields of the child
5720 * DB are all zero size.
5727 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5728 if (flags & MDB_CURRENT) {
5729 xflags = MDB_CURRENT|MDB_NOSPILL;
5731 mdb_xcursor_init1(mc, leaf);
5732 xflags = (flags & MDB_NODUPDATA) ?
5733 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
5735 /* converted, write the original data first */
5737 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
5741 /* Adjust other cursors pointing to mp */
5743 unsigned i = mc->mc_top;
5744 MDB_page *mp = mc->mc_pg[i];
5746 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5747 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
5748 if (!(m2->mc_flags & C_INITIALIZED)) continue;
5749 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
5750 mdb_xcursor_init1(m2, leaf);
5754 /* we've done our job */
5757 if (flags & MDB_APPENDDUP)
5758 xflags |= MDB_APPEND;
5759 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
5760 if (flags & F_SUBDATA) {
5761 void *db = NODEDATA(leaf);
5762 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
5765 /* sub-writes might have failed so check rc again.
5766 * Don't increment count if we just replaced an existing item.
5768 if (!rc && !(flags & MDB_CURRENT))
5769 mc->mc_db->md_entries++;
5770 if (flags & MDB_MULTIPLE) {
5773 if (mcount < dcount) {
5774 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
5775 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5779 /* let caller know how many succeeded, if any */
5780 data[1].mv_size = mcount;
5784 /* If we succeeded and the key didn't exist before, make sure
5785 * the cursor is marked valid.
5788 mc->mc_flags |= C_INITIALIZED;
5793 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
5798 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
5801 if (!(mc->mc_flags & C_INITIALIZED))
5804 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
5806 flags &= ~MDB_NOSPILL; /* TODO: Or change (flags != MDB_NODUPDATA) to ~(flags & MDB_NODUPDATA), not looking at the logic of that code just now */
5808 rc = mdb_cursor_touch(mc);
5812 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5814 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5815 if (flags != MDB_NODUPDATA) {
5816 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
5817 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
5819 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
5820 /* If sub-DB still has entries, we're done */
5821 if (mc->mc_xcursor->mx_db.md_entries) {
5822 if (leaf->mn_flags & F_SUBDATA) {
5823 /* update subDB info */
5824 void *db = NODEDATA(leaf);
5825 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
5828 /* shrink fake page */
5829 mdb_node_shrink(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5830 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5831 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
5832 /* fix other sub-DB cursors pointed at this fake page */
5833 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5834 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
5835 if (m2->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top] &&
5836 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
5837 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
5840 mc->mc_db->md_entries--;
5843 /* otherwise fall thru and delete the sub-DB */
5846 if (leaf->mn_flags & F_SUBDATA) {
5847 /* add all the child DB's pages to the free list */
5848 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
5849 if (rc == MDB_SUCCESS) {
5850 mc->mc_db->md_entries -=
5851 mc->mc_xcursor->mx_db.md_entries;
5856 return mdb_cursor_del0(mc, leaf);
5859 /** Allocate and initialize new pages for a database.
5860 * @param[in] mc a cursor on the database being added to.
5861 * @param[in] flags flags defining what type of page is being allocated.
5862 * @param[in] num the number of pages to allocate. This is usually 1,
5863 * unless allocating overflow pages for a large record.
5864 * @param[out] mp Address of a page, or NULL on failure.
5865 * @return 0 on success, non-zero on failure.
5868 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
5873 if ((rc = mdb_page_alloc(mc, num, &np)))
5875 DPRINTF("allocated new mpage %zu, page size %u",
5876 np->mp_pgno, mc->mc_txn->mt_env->me_psize);
5877 np->mp_flags = flags | P_DIRTY;
5878 np->mp_lower = PAGEHDRSZ;
5879 np->mp_upper = mc->mc_txn->mt_env->me_psize;
5882 mc->mc_db->md_branch_pages++;
5883 else if (IS_LEAF(np))
5884 mc->mc_db->md_leaf_pages++;
5885 else if (IS_OVERFLOW(np)) {
5886 mc->mc_db->md_overflow_pages += num;
5894 /** Calculate the size of a leaf node.
5895 * The size depends on the environment's page size; if a data item
5896 * is too large it will be put onto an overflow page and the node
5897 * size will only include the key and not the data. Sizes are always
5898 * rounded up to an even number of bytes, to guarantee 2-byte alignment
5899 * of the #MDB_node headers.
5900 * @param[in] env The environment handle.
5901 * @param[in] key The key for the node.
5902 * @param[in] data The data for the node.
5903 * @return The number of bytes needed to store the node.
5906 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
5910 sz = LEAFSIZE(key, data);
5911 if (sz >= env->me_nodemax) {
5912 /* put on overflow page */
5913 sz -= data->mv_size - sizeof(pgno_t);
5917 return sz + sizeof(indx_t);
5920 /** Calculate the size of a branch node.
5921 * The size should depend on the environment's page size but since
5922 * we currently don't support spilling large keys onto overflow
5923 * pages, it's simply the size of the #MDB_node header plus the
5924 * size of the key. Sizes are always rounded up to an even number
5925 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
5926 * @param[in] env The environment handle.
5927 * @param[in] key The key for the node.
5928 * @return The number of bytes needed to store the node.
5931 mdb_branch_size(MDB_env *env, MDB_val *key)
5936 if (sz >= env->me_nodemax) {
5937 /* put on overflow page */
5938 /* not implemented */
5939 /* sz -= key->size - sizeof(pgno_t); */
5942 return sz + sizeof(indx_t);
5945 /** Add a node to the page pointed to by the cursor.
5946 * @param[in] mc The cursor for this operation.
5947 * @param[in] indx The index on the page where the new node should be added.
5948 * @param[in] key The key for the new node.
5949 * @param[in] data The data for the new node, if any.
5950 * @param[in] pgno The page number, if adding a branch node.
5951 * @param[in] flags Flags for the node.
5952 * @return 0 on success, non-zero on failure. Possible errors are:
5954 * <li>ENOMEM - failed to allocate overflow pages for the node.
5955 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
5956 * should never happen since all callers already calculate the
5957 * page's free space before calling this function.
5961 mdb_node_add(MDB_cursor *mc, indx_t indx,
5962 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
5965 size_t node_size = NODESIZE;
5968 MDB_page *mp = mc->mc_pg[mc->mc_top];
5969 MDB_page *ofp = NULL; /* overflow page */
5972 assert(mp->mp_upper >= mp->mp_lower);
5974 DPRINTF("add to %s %spage %zu index %i, data size %zu key size %zu [%s]",
5975 IS_LEAF(mp) ? "leaf" : "branch",
5976 IS_SUBP(mp) ? "sub-" : "",
5977 mp->mp_pgno, indx, data ? data->mv_size : 0,
5978 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
5981 /* Move higher keys up one slot. */
5982 int ksize = mc->mc_db->md_pad, dif;
5983 char *ptr = LEAF2KEY(mp, indx, ksize);
5984 dif = NUMKEYS(mp) - indx;
5986 memmove(ptr+ksize, ptr, dif*ksize);
5987 /* insert new key */
5988 memcpy(ptr, key->mv_data, ksize);
5990 /* Just using these for counting */
5991 mp->mp_lower += sizeof(indx_t);
5992 mp->mp_upper -= ksize - sizeof(indx_t);
5997 node_size += key->mv_size;
6001 if (F_ISSET(flags, F_BIGDATA)) {
6002 /* Data already on overflow page. */
6003 node_size += sizeof(pgno_t);
6004 } else if (node_size + data->mv_size >= mc->mc_txn->mt_env->me_nodemax) {
6005 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
6007 /* Put data on overflow page. */
6008 DPRINTF("data size is %zu, node would be %zu, put data on overflow page",
6009 data->mv_size, node_size+data->mv_size);
6010 node_size += sizeof(pgno_t);
6011 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
6013 DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
6016 node_size += data->mv_size;
6019 node_size += node_size & 1;
6021 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
6022 DPRINTF("not enough room in page %zu, got %u ptrs",
6023 mp->mp_pgno, NUMKEYS(mp));
6024 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
6025 mp->mp_upper - mp->mp_lower);
6026 DPRINTF("node size = %zu", node_size);
6027 return MDB_PAGE_FULL;
6030 /* Move higher pointers up one slot. */
6031 for (i = NUMKEYS(mp); i > indx; i--)
6032 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
6034 /* Adjust free space offsets. */
6035 ofs = mp->mp_upper - node_size;
6036 assert(ofs >= mp->mp_lower + sizeof(indx_t));
6037 mp->mp_ptrs[indx] = ofs;
6039 mp->mp_lower += sizeof(indx_t);
6041 /* Write the node data. */
6042 node = NODEPTR(mp, indx);
6043 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
6044 node->mn_flags = flags;
6046 SETDSZ(node,data->mv_size);
6051 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6056 if (F_ISSET(flags, F_BIGDATA))
6057 memcpy(node->mn_data + key->mv_size, data->mv_data,
6059 else if (F_ISSET(flags, MDB_RESERVE))
6060 data->mv_data = node->mn_data + key->mv_size;
6062 memcpy(node->mn_data + key->mv_size, data->mv_data,
6065 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
6067 if (F_ISSET(flags, MDB_RESERVE))
6068 data->mv_data = METADATA(ofp);
6070 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
6077 /** Delete the specified node from a page.
6078 * @param[in] mp The page to operate on.
6079 * @param[in] indx The index of the node to delete.
6080 * @param[in] ksize The size of a node. Only used if the page is
6081 * part of a #MDB_DUPFIXED database.
6084 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
6087 indx_t i, j, numkeys, ptr;
6094 COPY_PGNO(pgno, mp->mp_pgno);
6095 DPRINTF("delete node %u on %s page %zu", indx,
6096 IS_LEAF(mp) ? "leaf" : "branch", pgno);
6099 assert(indx < NUMKEYS(mp));
6102 int x = NUMKEYS(mp) - 1 - indx;
6103 base = LEAF2KEY(mp, indx, ksize);
6105 memmove(base, base + ksize, x * ksize);
6106 mp->mp_lower -= sizeof(indx_t);
6107 mp->mp_upper += ksize - sizeof(indx_t);
6111 node = NODEPTR(mp, indx);
6112 sz = NODESIZE + node->mn_ksize;
6114 if (F_ISSET(node->mn_flags, F_BIGDATA))
6115 sz += sizeof(pgno_t);
6117 sz += NODEDSZ(node);
6121 ptr = mp->mp_ptrs[indx];
6122 numkeys = NUMKEYS(mp);
6123 for (i = j = 0; i < numkeys; i++) {
6125 mp->mp_ptrs[j] = mp->mp_ptrs[i];
6126 if (mp->mp_ptrs[i] < ptr)
6127 mp->mp_ptrs[j] += sz;
6132 base = (char *)mp + mp->mp_upper;
6133 memmove(base + sz, base, ptr - mp->mp_upper);
6135 mp->mp_lower -= sizeof(indx_t);
6139 /** Compact the main page after deleting a node on a subpage.
6140 * @param[in] mp The main page to operate on.
6141 * @param[in] indx The index of the subpage on the main page.
6144 mdb_node_shrink(MDB_page *mp, indx_t indx)
6151 indx_t i, numkeys, ptr;
6153 node = NODEPTR(mp, indx);
6154 sp = (MDB_page *)NODEDATA(node);
6155 osize = NODEDSZ(node);
6157 delta = sp->mp_upper - sp->mp_lower;
6158 SETDSZ(node, osize - delta);
6159 xp = (MDB_page *)((char *)sp + delta);
6161 /* shift subpage upward */
6163 nsize = NUMKEYS(sp) * sp->mp_pad;
6164 memmove(METADATA(xp), METADATA(sp), nsize);
6167 nsize = osize - sp->mp_upper;
6168 numkeys = NUMKEYS(sp);
6169 for (i=numkeys-1; i>=0; i--)
6170 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
6172 xp->mp_upper = sp->mp_lower;
6173 xp->mp_lower = sp->mp_lower;
6174 xp->mp_flags = sp->mp_flags;
6175 xp->mp_pad = sp->mp_pad;
6176 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
6178 /* shift lower nodes upward */
6179 ptr = mp->mp_ptrs[indx];
6180 numkeys = NUMKEYS(mp);
6181 for (i = 0; i < numkeys; i++) {
6182 if (mp->mp_ptrs[i] <= ptr)
6183 mp->mp_ptrs[i] += delta;
6186 base = (char *)mp + mp->mp_upper;
6187 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
6188 mp->mp_upper += delta;
6191 /** Initial setup of a sorted-dups cursor.
6192 * Sorted duplicates are implemented as a sub-database for the given key.
6193 * The duplicate data items are actually keys of the sub-database.
6194 * Operations on the duplicate data items are performed using a sub-cursor
6195 * initialized when the sub-database is first accessed. This function does
6196 * the preliminary setup of the sub-cursor, filling in the fields that
6197 * depend only on the parent DB.
6198 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6201 mdb_xcursor_init0(MDB_cursor *mc)
6203 MDB_xcursor *mx = mc->mc_xcursor;
6205 mx->mx_cursor.mc_xcursor = NULL;
6206 mx->mx_cursor.mc_txn = mc->mc_txn;
6207 mx->mx_cursor.mc_db = &mx->mx_db;
6208 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
6209 mx->mx_cursor.mc_dbi = mc->mc_dbi+1;
6210 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
6211 mx->mx_cursor.mc_snum = 0;
6212 mx->mx_cursor.mc_top = 0;
6213 mx->mx_cursor.mc_flags = C_SUB;
6214 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
6215 mx->mx_dbx.md_dcmp = NULL;
6216 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
6219 /** Final setup of a sorted-dups cursor.
6220 * Sets up the fields that depend on the data from the main cursor.
6221 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6222 * @param[in] node The data containing the #MDB_db record for the
6223 * sorted-dup database.
6226 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
6228 MDB_xcursor *mx = mc->mc_xcursor;
6230 if (node->mn_flags & F_SUBDATA) {
6231 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
6232 mx->mx_cursor.mc_pg[0] = 0;
6233 mx->mx_cursor.mc_snum = 0;
6234 mx->mx_cursor.mc_flags = C_SUB;
6236 MDB_page *fp = NODEDATA(node);
6237 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
6238 mx->mx_db.md_flags = 0;
6239 mx->mx_db.md_depth = 1;
6240 mx->mx_db.md_branch_pages = 0;
6241 mx->mx_db.md_leaf_pages = 1;
6242 mx->mx_db.md_overflow_pages = 0;
6243 mx->mx_db.md_entries = NUMKEYS(fp);
6244 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
6245 mx->mx_cursor.mc_snum = 1;
6246 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
6247 mx->mx_cursor.mc_top = 0;
6248 mx->mx_cursor.mc_pg[0] = fp;
6249 mx->mx_cursor.mc_ki[0] = 0;
6250 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6251 mx->mx_db.md_flags = MDB_DUPFIXED;
6252 mx->mx_db.md_pad = fp->mp_pad;
6253 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6254 mx->mx_db.md_flags |= MDB_INTEGERKEY;
6257 DPRINTF("Sub-db %u for db %u root page %zu", mx->mx_cursor.mc_dbi, mc->mc_dbi,
6259 mx->mx_dbflag = DB_VALID | (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY) ?
6261 mx->mx_dbx.md_name.mv_data = NODEKEY(node);
6262 mx->mx_dbx.md_name.mv_size = node->mn_ksize;
6263 #if UINT_MAX < SIZE_MAX
6264 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
6265 #ifdef MISALIGNED_OK
6266 mx->mx_dbx.md_cmp = mdb_cmp_long;
6268 mx->mx_dbx.md_cmp = mdb_cmp_cint;
6273 /** Initialize a cursor for a given transaction and database. */
6275 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
6278 mc->mc_backup = NULL;
6281 mc->mc_db = &txn->mt_dbs[dbi];
6282 mc->mc_dbx = &txn->mt_dbxs[dbi];
6283 mc->mc_dbflag = &txn->mt_dbflags[dbi];
6288 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
6290 mc->mc_xcursor = mx;
6291 mdb_xcursor_init0(mc);
6293 mc->mc_xcursor = NULL;
6295 if (*mc->mc_dbflag & DB_STALE) {
6296 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
6301 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
6304 size_t size = sizeof(MDB_cursor);
6306 if (txn == NULL || ret == NULL || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
6309 /* Allow read access to the freelist */
6310 if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
6313 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
6314 size += sizeof(MDB_xcursor);
6316 if ((mc = malloc(size)) != NULL) {
6317 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
6318 if (txn->mt_cursors) {
6319 mc->mc_next = txn->mt_cursors[dbi];
6320 txn->mt_cursors[dbi] = mc;
6321 mc->mc_flags |= C_UNTRACK;
6333 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
6335 if (txn == NULL || mc == NULL || mc->mc_dbi >= txn->mt_numdbs)
6338 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
6341 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
6345 /* Return the count of duplicate data items for the current key */
6347 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
6351 if (mc == NULL || countp == NULL)
6354 if (!(mc->mc_db->md_flags & MDB_DUPSORT))
6357 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6358 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6361 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
6364 *countp = mc->mc_xcursor->mx_db.md_entries;
6370 mdb_cursor_close(MDB_cursor *mc)
6372 if (mc && !mc->mc_backup) {
6373 /* remove from txn, if tracked */
6374 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
6375 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
6376 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
6378 *prev = mc->mc_next;
6385 mdb_cursor_txn(MDB_cursor *mc)
6387 if (!mc) return NULL;
6392 mdb_cursor_dbi(MDB_cursor *mc)
6398 /** Replace the key for a node with a new key.
6399 * @param[in] mc Cursor pointing to the node to operate on.
6400 * @param[in] key The new key to use.
6401 * @return 0 on success, non-zero on failure.
6404 mdb_update_key(MDB_cursor *mc, MDB_val *key)
6411 indx_t ptr, i, numkeys, indx;
6414 indx = mc->mc_ki[mc->mc_top];
6415 mp = mc->mc_pg[mc->mc_top];
6416 node = NODEPTR(mp, indx);
6417 ptr = mp->mp_ptrs[indx];
6421 char kbuf2[(MDB_MAXKEYSIZE*2+1)];
6422 k2.mv_data = NODEKEY(node);
6423 k2.mv_size = node->mn_ksize;
6424 DPRINTF("update key %u (ofs %u) [%s] to [%s] on page %zu",
6426 mdb_dkey(&k2, kbuf2),
6432 delta0 = delta = key->mv_size - node->mn_ksize;
6434 /* Must be 2-byte aligned. If new key is
6435 * shorter by 1, the shift will be skipped.
6437 delta += (delta & 1);
6439 if (delta > 0 && SIZELEFT(mp) < delta) {
6441 /* not enough space left, do a delete and split */
6442 DPRINTF("Not enough room, delta = %d, splitting...", delta);
6443 pgno = NODEPGNO(node);
6444 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
6445 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
6448 numkeys = NUMKEYS(mp);
6449 for (i = 0; i < numkeys; i++) {
6450 if (mp->mp_ptrs[i] <= ptr)
6451 mp->mp_ptrs[i] -= delta;
6454 base = (char *)mp + mp->mp_upper;
6455 len = ptr - mp->mp_upper + NODESIZE;
6456 memmove(base - delta, base, len);
6457 mp->mp_upper -= delta;
6459 node = NODEPTR(mp, indx);
6462 /* But even if no shift was needed, update ksize */
6464 node->mn_ksize = key->mv_size;
6467 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6473 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
6475 /** Move a node from csrc to cdst.
6478 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
6485 unsigned short flags;
6489 /* Mark src and dst as dirty. */
6490 if ((rc = mdb_page_touch(csrc)) ||
6491 (rc = mdb_page_touch(cdst)))
6494 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6495 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
6496 key.mv_size = csrc->mc_db->md_pad;
6497 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
6499 data.mv_data = NULL;
6503 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
6504 assert(!((long)srcnode&1));
6505 srcpg = NODEPGNO(srcnode);
6506 flags = srcnode->mn_flags;
6507 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6508 unsigned int snum = csrc->mc_snum;
6510 /* must find the lowest key below src */
6511 mdb_page_search_lowest(csrc);
6512 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6513 key.mv_size = csrc->mc_db->md_pad;
6514 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6516 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6517 key.mv_size = NODEKSZ(s2);
6518 key.mv_data = NODEKEY(s2);
6520 csrc->mc_snum = snum--;
6521 csrc->mc_top = snum;
6523 key.mv_size = NODEKSZ(srcnode);
6524 key.mv_data = NODEKEY(srcnode);
6526 data.mv_size = NODEDSZ(srcnode);
6527 data.mv_data = NODEDATA(srcnode);
6529 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
6530 unsigned int snum = cdst->mc_snum;
6533 /* must find the lowest key below dst */
6534 mdb_page_search_lowest(cdst);
6535 if (IS_LEAF2(cdst->mc_pg[cdst->mc_top])) {
6536 bkey.mv_size = cdst->mc_db->md_pad;
6537 bkey.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, bkey.mv_size);
6539 s2 = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
6540 bkey.mv_size = NODEKSZ(s2);
6541 bkey.mv_data = NODEKEY(s2);
6543 cdst->mc_snum = snum--;
6544 cdst->mc_top = snum;
6545 mdb_cursor_copy(cdst, &mn);
6547 rc = mdb_update_key(&mn, &bkey);
6552 DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
6553 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
6554 csrc->mc_ki[csrc->mc_top],
6556 csrc->mc_pg[csrc->mc_top]->mp_pgno,
6557 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
6559 /* Add the node to the destination page.
6561 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
6562 if (rc != MDB_SUCCESS)
6565 /* Delete the node from the source page.
6567 mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
6570 /* Adjust other cursors pointing to mp */
6571 MDB_cursor *m2, *m3;
6572 MDB_dbi dbi = csrc->mc_dbi;
6573 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
6575 if (csrc->mc_flags & C_SUB)
6578 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6579 if (csrc->mc_flags & C_SUB)
6580 m3 = &m2->mc_xcursor->mx_cursor;
6583 if (m3 == csrc) continue;
6584 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
6585 csrc->mc_ki[csrc->mc_top]) {
6586 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
6587 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
6592 /* Update the parent separators.
6594 if (csrc->mc_ki[csrc->mc_top] == 0) {
6595 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
6596 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6597 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6599 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6600 key.mv_size = NODEKSZ(srcnode);
6601 key.mv_data = NODEKEY(srcnode);
6603 DPRINTF("update separator for source page %zu to [%s]",
6604 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
6605 mdb_cursor_copy(csrc, &mn);
6608 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
6611 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6613 indx_t ix = csrc->mc_ki[csrc->mc_top];
6614 nullkey.mv_size = 0;
6615 csrc->mc_ki[csrc->mc_top] = 0;
6616 rc = mdb_update_key(csrc, &nullkey);
6617 csrc->mc_ki[csrc->mc_top] = ix;
6618 assert(rc == MDB_SUCCESS);
6622 if (cdst->mc_ki[cdst->mc_top] == 0) {
6623 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
6624 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6625 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
6627 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
6628 key.mv_size = NODEKSZ(srcnode);
6629 key.mv_data = NODEKEY(srcnode);
6631 DPRINTF("update separator for destination page %zu to [%s]",
6632 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
6633 mdb_cursor_copy(cdst, &mn);
6636 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
6639 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
6641 indx_t ix = cdst->mc_ki[cdst->mc_top];
6642 nullkey.mv_size = 0;
6643 cdst->mc_ki[cdst->mc_top] = 0;
6644 rc = mdb_update_key(cdst, &nullkey);
6645 cdst->mc_ki[cdst->mc_top] = ix;
6646 assert(rc == MDB_SUCCESS);
6653 /** Merge one page into another.
6654 * The nodes from the page pointed to by \b csrc will
6655 * be copied to the page pointed to by \b cdst and then
6656 * the \b csrc page will be freed.
6657 * @param[in] csrc Cursor pointing to the source page.
6658 * @param[in] cdst Cursor pointing to the destination page.
6661 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
6669 DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
6670 cdst->mc_pg[cdst->mc_top]->mp_pgno);
6672 assert(csrc->mc_snum > 1); /* can't merge root page */
6673 assert(cdst->mc_snum > 1);
6675 /* Mark dst as dirty. */
6676 if ((rc = mdb_page_touch(cdst)))
6679 /* Move all nodes from src to dst.
6681 j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
6682 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6683 key.mv_size = csrc->mc_db->md_pad;
6684 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
6685 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
6686 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
6687 if (rc != MDB_SUCCESS)
6689 key.mv_data = (char *)key.mv_data + key.mv_size;
6692 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
6693 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
6694 if (i == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6695 unsigned int snum = csrc->mc_snum;
6697 /* must find the lowest key below src */
6698 mdb_page_search_lowest(csrc);
6699 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6700 key.mv_size = csrc->mc_db->md_pad;
6701 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6703 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6704 key.mv_size = NODEKSZ(s2);
6705 key.mv_data = NODEKEY(s2);
6707 csrc->mc_snum = snum--;
6708 csrc->mc_top = snum;
6710 key.mv_size = srcnode->mn_ksize;
6711 key.mv_data = NODEKEY(srcnode);
6714 data.mv_size = NODEDSZ(srcnode);
6715 data.mv_data = NODEDATA(srcnode);
6716 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
6717 if (rc != MDB_SUCCESS)
6722 DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
6723 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);
6725 /* Unlink the src page from parent and add to free list.
6727 mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
6728 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
6731 rc = mdb_update_key(csrc, &key);
6737 rc = mdb_midl_append(&csrc->mc_txn->mt_free_pgs,
6738 csrc->mc_pg[csrc->mc_top]->mp_pgno);
6741 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
6742 csrc->mc_db->md_leaf_pages--;
6744 csrc->mc_db->md_branch_pages--;
6746 /* Adjust other cursors pointing to mp */
6747 MDB_cursor *m2, *m3;
6748 MDB_dbi dbi = csrc->mc_dbi;
6749 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
6751 if (csrc->mc_flags & C_SUB)
6754 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6755 if (csrc->mc_flags & C_SUB)
6756 m3 = &m2->mc_xcursor->mx_cursor;
6759 if (m3 == csrc) continue;
6760 if (m3->mc_snum < csrc->mc_snum) continue;
6761 if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
6762 m3->mc_pg[csrc->mc_top] = mp;
6763 m3->mc_ki[csrc->mc_top] += nkeys;
6767 mdb_cursor_pop(csrc);
6769 return mdb_rebalance(csrc);
6772 /** Copy the contents of a cursor.
6773 * @param[in] csrc The cursor to copy from.
6774 * @param[out] cdst The cursor to copy to.
6777 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
6781 cdst->mc_txn = csrc->mc_txn;
6782 cdst->mc_dbi = csrc->mc_dbi;
6783 cdst->mc_db = csrc->mc_db;
6784 cdst->mc_dbx = csrc->mc_dbx;
6785 cdst->mc_snum = csrc->mc_snum;
6786 cdst->mc_top = csrc->mc_top;
6787 cdst->mc_flags = csrc->mc_flags;
6789 for (i=0; i<csrc->mc_snum; i++) {
6790 cdst->mc_pg[i] = csrc->mc_pg[i];
6791 cdst->mc_ki[i] = csrc->mc_ki[i];
6795 /** Rebalance the tree after a delete operation.
6796 * @param[in] mc Cursor pointing to the page where rebalancing
6798 * @return 0 on success, non-zero on failure.
6801 mdb_rebalance(MDB_cursor *mc)
6805 unsigned int ptop, minkeys;
6808 minkeys = 1 + (IS_BRANCH(mc->mc_pg[mc->mc_top]));
6812 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
6813 DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
6814 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
6815 pgno, NUMKEYS(mc->mc_pg[mc->mc_top]), (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10);
6819 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD &&
6820 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
6823 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
6824 DPRINTF("no need to rebalance page %zu, above fill threshold",
6830 if (mc->mc_snum < 2) {
6831 MDB_page *mp = mc->mc_pg[0];
6833 DPUTS("Can't rebalance a subpage, ignoring");
6836 if (NUMKEYS(mp) == 0) {
6837 DPUTS("tree is completely empty");
6838 mc->mc_db->md_root = P_INVALID;
6839 mc->mc_db->md_depth = 0;
6840 mc->mc_db->md_leaf_pages = 0;
6841 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
6844 /* Adjust cursors pointing to mp */
6848 MDB_cursor *m2, *m3;
6849 MDB_dbi dbi = mc->mc_dbi;
6851 if (mc->mc_flags & C_SUB)
6854 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6855 if (mc->mc_flags & C_SUB)
6856 m3 = &m2->mc_xcursor->mx_cursor;
6859 if (m3->mc_snum < mc->mc_snum) continue;
6860 if (m3->mc_pg[0] == mp) {
6866 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
6867 DPUTS("collapsing root page!");
6868 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
6871 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
6872 rc = mdb_page_get(mc->mc_txn,mc->mc_db->md_root,&mc->mc_pg[0],NULL);
6875 mc->mc_db->md_depth--;
6876 mc->mc_db->md_branch_pages--;
6877 mc->mc_ki[0] = mc->mc_ki[1];
6879 /* Adjust other cursors pointing to mp */
6880 MDB_cursor *m2, *m3;
6881 MDB_dbi dbi = mc->mc_dbi;
6883 if (mc->mc_flags & C_SUB)
6886 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6887 if (mc->mc_flags & C_SUB)
6888 m3 = &m2->mc_xcursor->mx_cursor;
6891 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
6892 if (m3->mc_pg[0] == mp) {
6893 m3->mc_pg[0] = mc->mc_pg[0];
6896 m3->mc_ki[0] = m3->mc_ki[1];
6901 DPUTS("root page doesn't need rebalancing");
6905 /* The parent (branch page) must have at least 2 pointers,
6906 * otherwise the tree is invalid.
6908 ptop = mc->mc_top-1;
6909 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
6911 /* Leaf page fill factor is below the threshold.
6912 * Try to move keys from left or right neighbor, or
6913 * merge with a neighbor page.
6918 mdb_cursor_copy(mc, &mn);
6919 mn.mc_xcursor = NULL;
6921 if (mc->mc_ki[ptop] == 0) {
6922 /* We're the leftmost leaf in our parent.
6924 DPUTS("reading right neighbor");
6926 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
6927 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
6930 mn.mc_ki[mn.mc_top] = 0;
6931 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
6933 /* There is at least one neighbor to the left.
6935 DPUTS("reading left neighbor");
6937 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
6938 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
6941 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
6942 mc->mc_ki[mc->mc_top] = 0;
6945 DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
6946 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);
6948 /* If the neighbor page is above threshold and has enough keys,
6949 * move one key from it. Otherwise we should try to merge them.
6950 * (A branch page must never have less than 2 keys.)
6952 minkeys = 1 + (IS_BRANCH(mn.mc_pg[mn.mc_top]));
6953 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys)
6954 return mdb_node_move(&mn, mc);
6956 if (mc->mc_ki[ptop] == 0)
6957 rc = mdb_page_merge(&mn, mc);
6959 rc = mdb_page_merge(mc, &mn);
6960 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
6965 /** Complete a delete operation started by #mdb_cursor_del(). */
6967 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
6973 mp = mc->mc_pg[mc->mc_top];
6974 ki = mc->mc_ki[mc->mc_top];
6976 /* add overflow pages to free list */
6977 if (!IS_LEAF2(mp) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6981 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
6982 if ((rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL)) ||
6983 (rc = mdb_ovpage_free(mc, omp)))
6986 mdb_node_del(mp, ki, mc->mc_db->md_pad);
6987 mc->mc_db->md_entries--;
6988 rc = mdb_rebalance(mc);
6989 if (rc != MDB_SUCCESS)
6990 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6991 /* if mc points past last node in page, invalidate */
6992 else if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6993 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
6996 /* Adjust other cursors pointing to mp */
6999 MDB_dbi dbi = mc->mc_dbi;
7001 mp = mc->mc_pg[mc->mc_top];
7002 nkeys = NUMKEYS(mp);
7003 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7006 if (!(m2->mc_flags & C_INITIALIZED))
7008 if (m2->mc_pg[mc->mc_top] == mp) {
7009 if (m2->mc_ki[mc->mc_top] > ki)
7010 m2->mc_ki[mc->mc_top]--;
7011 if (m2->mc_ki[mc->mc_top] >= nkeys)
7012 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
7021 mdb_del(MDB_txn *txn, MDB_dbi dbi,
7022 MDB_val *key, MDB_val *data)
7027 MDB_val rdata, *xdata;
7031 assert(key != NULL);
7033 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
7035 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7038 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
7042 if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
7046 mdb_cursor_init(&mc, txn, dbi, &mx);
7057 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
7059 /* let mdb_page_split know about this cursor if needed:
7060 * delete will trigger a rebalance; if it needs to move
7061 * a node from one page to another, it will have to
7062 * update the parent's separator key(s). If the new sepkey
7063 * is larger than the current one, the parent page may
7064 * run out of space, triggering a split. We need this
7065 * cursor to be consistent until the end of the rebalance.
7067 mc.mc_flags |= C_UNTRACK;
7068 mc.mc_next = txn->mt_cursors[dbi];
7069 txn->mt_cursors[dbi] = &mc;
7070 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
7071 txn->mt_cursors[dbi] = mc.mc_next;
7076 /** Split a page and insert a new node.
7077 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
7078 * The cursor will be updated to point to the actual page and index where
7079 * the node got inserted after the split.
7080 * @param[in] newkey The key for the newly inserted node.
7081 * @param[in] newdata The data for the newly inserted node.
7082 * @param[in] newpgno The page number, if the new node is a branch node.
7083 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
7084 * @return 0 on success, non-zero on failure.
7087 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
7088 unsigned int nflags)
7091 int rc = MDB_SUCCESS, ins_new = 0, new_root = 0, newpos = 1, did_split = 0;
7094 unsigned int i, j, split_indx, nkeys, pmax;
7096 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
7098 MDB_page *mp, *rp, *pp;
7103 mp = mc->mc_pg[mc->mc_top];
7104 newindx = mc->mc_ki[mc->mc_top];
7106 DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
7107 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
7108 DKEY(newkey), mc->mc_ki[mc->mc_top]);
7110 /* Create a right sibling. */
7111 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
7113 DPRINTF("new right sibling: page %zu", rp->mp_pgno);
7115 if (mc->mc_snum < 2) {
7116 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
7118 /* shift current top to make room for new parent */
7119 mc->mc_pg[1] = mc->mc_pg[0];
7120 mc->mc_ki[1] = mc->mc_ki[0];
7123 mc->mc_db->md_root = pp->mp_pgno;
7124 DPRINTF("root split! new root = %zu", pp->mp_pgno);
7125 mc->mc_db->md_depth++;
7128 /* Add left (implicit) pointer. */
7129 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
7130 /* undo the pre-push */
7131 mc->mc_pg[0] = mc->mc_pg[1];
7132 mc->mc_ki[0] = mc->mc_ki[1];
7133 mc->mc_db->md_root = mp->mp_pgno;
7134 mc->mc_db->md_depth--;
7141 ptop = mc->mc_top-1;
7142 DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
7145 mc->mc_flags |= C_SPLITTING;
7146 mdb_cursor_copy(mc, &mn);
7147 mn.mc_pg[mn.mc_top] = rp;
7148 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
7150 if (nflags & MDB_APPEND) {
7151 mn.mc_ki[mn.mc_top] = 0;
7153 split_indx = newindx;
7158 nkeys = NUMKEYS(mp);
7159 split_indx = nkeys / 2;
7160 if (newindx < split_indx)
7166 unsigned int lsize, rsize, ksize;
7167 /* Move half of the keys to the right sibling */
7169 x = mc->mc_ki[mc->mc_top] - split_indx;
7170 ksize = mc->mc_db->md_pad;
7171 split = LEAF2KEY(mp, split_indx, ksize);
7172 rsize = (nkeys - split_indx) * ksize;
7173 lsize = (nkeys - split_indx) * sizeof(indx_t);
7174 mp->mp_lower -= lsize;
7175 rp->mp_lower += lsize;
7176 mp->mp_upper += rsize - lsize;
7177 rp->mp_upper -= rsize - lsize;
7178 sepkey.mv_size = ksize;
7179 if (newindx == split_indx) {
7180 sepkey.mv_data = newkey->mv_data;
7182 sepkey.mv_data = split;
7185 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
7186 memcpy(rp->mp_ptrs, split, rsize);
7187 sepkey.mv_data = rp->mp_ptrs;
7188 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
7189 memcpy(ins, newkey->mv_data, ksize);
7190 mp->mp_lower += sizeof(indx_t);
7191 mp->mp_upper -= ksize - sizeof(indx_t);
7194 memcpy(rp->mp_ptrs, split, x * ksize);
7195 ins = LEAF2KEY(rp, x, ksize);
7196 memcpy(ins, newkey->mv_data, ksize);
7197 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
7198 rp->mp_lower += sizeof(indx_t);
7199 rp->mp_upper -= ksize - sizeof(indx_t);
7200 mc->mc_ki[mc->mc_top] = x;
7201 mc->mc_pg[mc->mc_top] = rp;
7206 /* For leaf pages, check the split point based on what
7207 * fits where, since otherwise mdb_node_add can fail.
7209 * This check is only needed when the data items are
7210 * relatively large, such that being off by one will
7211 * make the difference between success or failure.
7213 * It's also relevant if a page happens to be laid out
7214 * such that one half of its nodes are all "small" and
7215 * the other half of its nodes are "large." If the new
7216 * item is also "large" and falls on the half with
7217 * "large" nodes, it also may not fit.
7220 unsigned int psize, nsize;
7221 /* Maximum free space in an empty page */
7222 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
7223 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
7224 if ((nkeys < 20) || (nsize > pmax/16)) {
7225 if (newindx <= split_indx) {
7228 for (i=0; i<split_indx; i++) {
7229 node = NODEPTR(mp, i);
7230 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
7231 if (F_ISSET(node->mn_flags, F_BIGDATA))
7232 psize += sizeof(pgno_t);
7234 psize += NODEDSZ(node);
7238 split_indx = newindx;
7249 for (i=nkeys-1; i>=split_indx; i--) {
7250 node = NODEPTR(mp, i);
7251 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
7252 if (F_ISSET(node->mn_flags, F_BIGDATA))
7253 psize += sizeof(pgno_t);
7255 psize += NODEDSZ(node);
7259 split_indx = newindx;
7270 /* First find the separating key between the split pages.
7271 * The case where newindx == split_indx is ambiguous; the
7272 * new item could go to the new page or stay on the original
7273 * page. If newpos == 1 it goes to the new page.
7275 if (newindx == split_indx && newpos) {
7276 sepkey.mv_size = newkey->mv_size;
7277 sepkey.mv_data = newkey->mv_data;
7279 node = NODEPTR(mp, split_indx);
7280 sepkey.mv_size = node->mn_ksize;
7281 sepkey.mv_data = NODEKEY(node);
7285 DPRINTF("separator is [%s]", DKEY(&sepkey));
7287 /* Copy separator key to the parent.
7289 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
7293 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
7296 if (mn.mc_snum == mc->mc_snum) {
7297 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
7298 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
7299 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
7300 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
7305 /* Right page might now have changed parent.
7306 * Check if left page also changed parent.
7308 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7309 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7310 for (i=0; i<ptop; i++) {
7311 mc->mc_pg[i] = mn.mc_pg[i];
7312 mc->mc_ki[i] = mn.mc_ki[i];
7314 mc->mc_pg[ptop] = mn.mc_pg[ptop];
7315 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
7319 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
7322 mc->mc_flags ^= C_SPLITTING;
7323 if (rc != MDB_SUCCESS) {
7326 if (nflags & MDB_APPEND) {
7327 mc->mc_pg[mc->mc_top] = rp;
7328 mc->mc_ki[mc->mc_top] = 0;
7329 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
7332 for (i=0; i<mc->mc_top; i++)
7333 mc->mc_ki[i] = mn.mc_ki[i];
7340 /* Move half of the keys to the right sibling. */
7342 /* grab a page to hold a temporary copy */
7343 copy = mdb_page_malloc(mc->mc_txn, 1);
7347 copy->mp_pgno = mp->mp_pgno;
7348 copy->mp_flags = mp->mp_flags;
7349 copy->mp_lower = PAGEHDRSZ;
7350 copy->mp_upper = mc->mc_txn->mt_env->me_psize;
7351 mc->mc_pg[mc->mc_top] = copy;
7352 for (i = j = 0; i <= nkeys; j++) {
7353 if (i == split_indx) {
7354 /* Insert in right sibling. */
7355 /* Reset insert index for right sibling. */
7356 if (i != newindx || (newpos ^ ins_new)) {
7358 mc->mc_pg[mc->mc_top] = rp;
7362 if (i == newindx && !ins_new) {
7363 /* Insert the original entry that caused the split. */
7364 rkey.mv_data = newkey->mv_data;
7365 rkey.mv_size = newkey->mv_size;
7374 /* Update index for the new key. */
7375 mc->mc_ki[mc->mc_top] = j;
7376 } else if (i == nkeys) {
7379 node = NODEPTR(mp, i);
7380 rkey.mv_data = NODEKEY(node);
7381 rkey.mv_size = node->mn_ksize;
7383 xdata.mv_data = NODEDATA(node);
7384 xdata.mv_size = NODEDSZ(node);
7387 pgno = NODEPGNO(node);
7388 flags = node->mn_flags;
7393 if (!IS_LEAF(mp) && j == 0) {
7394 /* First branch index doesn't need key data. */
7398 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
7402 nkeys = NUMKEYS(copy);
7403 for (i=0; i<nkeys; i++)
7404 mp->mp_ptrs[i] = copy->mp_ptrs[i];
7405 mp->mp_lower = copy->mp_lower;
7406 mp->mp_upper = copy->mp_upper;
7407 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
7408 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
7410 /* reset back to original page */
7411 if (newindx < split_indx || (!newpos && newindx == split_indx)) {
7412 mc->mc_pg[mc->mc_top] = mp;
7413 if (nflags & MDB_RESERVE) {
7414 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7415 if (!(node->mn_flags & F_BIGDATA))
7416 newdata->mv_data = NODEDATA(node);
7420 /* Make sure mc_ki is still valid.
7422 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7423 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7424 for (i=0; i<ptop; i++) {
7425 mc->mc_pg[i] = mn.mc_pg[i];
7426 mc->mc_ki[i] = mn.mc_ki[i];
7428 mc->mc_pg[ptop] = mn.mc_pg[ptop];
7429 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
7433 /* return tmp page to freelist */
7434 mdb_page_free(mc->mc_txn->mt_env, copy);
7437 /* Adjust other cursors pointing to mp */
7438 MDB_cursor *m2, *m3;
7439 MDB_dbi dbi = mc->mc_dbi;
7440 int fixup = NUMKEYS(mp);
7442 if (mc->mc_flags & C_SUB)
7445 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7446 if (mc->mc_flags & C_SUB)
7447 m3 = &m2->mc_xcursor->mx_cursor;
7452 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
7454 if (m3->mc_flags & C_SPLITTING)
7459 for (k=m3->mc_top; k>=0; k--) {
7460 m3->mc_ki[k+1] = m3->mc_ki[k];
7461 m3->mc_pg[k+1] = m3->mc_pg[k];
7463 if (m3->mc_ki[0] >= split_indx) {
7468 m3->mc_pg[0] = mc->mc_pg[0];
7472 if (m3->mc_pg[mc->mc_top] == mp) {
7473 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
7474 m3->mc_ki[mc->mc_top]++;
7475 if (m3->mc_ki[mc->mc_top] >= fixup) {
7476 m3->mc_pg[mc->mc_top] = rp;
7477 m3->mc_ki[mc->mc_top] -= fixup;
7478 m3->mc_ki[ptop] = mn.mc_ki[ptop];
7480 } else if (!did_split && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
7481 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
7490 mdb_put(MDB_txn *txn, MDB_dbi dbi,
7491 MDB_val *key, MDB_val *data, unsigned int flags)
7496 assert(key != NULL);
7497 assert(data != NULL);
7499 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7502 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
7506 if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
7510 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP)) != flags)
7513 mdb_cursor_init(&mc, txn, dbi, &mx);
7514 return mdb_cursor_put(&mc, key, data, flags);
7518 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
7520 if ((flag & CHANGEABLE) != flag)
7523 env->me_flags |= flag;
7525 env->me_flags &= ~flag;
7530 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
7535 *arg = env->me_flags;
7540 mdb_env_get_path(MDB_env *env, const char **arg)
7545 *arg = env->me_path;
7549 /** Common code for #mdb_stat() and #mdb_env_stat().
7550 * @param[in] env the environment to operate in.
7551 * @param[in] db the #MDB_db record containing the stats to return.
7552 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
7553 * @return 0, this function always succeeds.
7556 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
7558 arg->ms_psize = env->me_psize;
7559 arg->ms_depth = db->md_depth;
7560 arg->ms_branch_pages = db->md_branch_pages;
7561 arg->ms_leaf_pages = db->md_leaf_pages;
7562 arg->ms_overflow_pages = db->md_overflow_pages;
7563 arg->ms_entries = db->md_entries;
7568 mdb_env_stat(MDB_env *env, MDB_stat *arg)
7572 if (env == NULL || arg == NULL)
7575 toggle = mdb_env_pick_meta(env);
7577 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
7581 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
7585 if (env == NULL || arg == NULL)
7588 toggle = mdb_env_pick_meta(env);
7589 arg->me_mapaddr = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : 0;
7590 arg->me_mapsize = env->me_mapsize;
7591 arg->me_maxreaders = env->me_maxreaders;
7592 arg->me_numreaders = env->me_numreaders;
7593 arg->me_last_pgno = env->me_metas[toggle]->mm_last_pg;
7594 arg->me_last_txnid = env->me_metas[toggle]->mm_txnid;
7598 /** Set the default comparison functions for a database.
7599 * Called immediately after a database is opened to set the defaults.
7600 * The user can then override them with #mdb_set_compare() or
7601 * #mdb_set_dupsort().
7602 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
7603 * @param[in] dbi A database handle returned by #mdb_dbi_open()
7606 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
7608 uint16_t f = txn->mt_dbs[dbi].md_flags;
7610 txn->mt_dbxs[dbi].md_cmp =
7611 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
7612 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
7614 txn->mt_dbxs[dbi].md_dcmp =
7615 !(f & MDB_DUPSORT) ? 0 :
7616 ((f & MDB_INTEGERDUP)
7617 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
7618 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
7621 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
7626 int rc, dbflag, exact;
7627 unsigned int unused = 0;
7630 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
7631 mdb_default_cmp(txn, FREE_DBI);
7634 if ((flags & VALID_FLAGS) != flags)
7640 if (flags & PERSISTENT_FLAGS) {
7641 uint16_t f2 = flags & PERSISTENT_FLAGS;
7642 /* make sure flag changes get committed */
7643 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
7644 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
7645 txn->mt_flags |= MDB_TXN_DIRTY;
7648 mdb_default_cmp(txn, MAIN_DBI);
7652 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
7653 mdb_default_cmp(txn, MAIN_DBI);
7656 /* Is the DB already open? */
7658 for (i=2; i<txn->mt_numdbs; i++) {
7659 if (!txn->mt_dbxs[i].md_name.mv_size) {
7660 /* Remember this free slot */
7661 if (!unused) unused = i;
7664 if (len == txn->mt_dbxs[i].md_name.mv_size &&
7665 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
7671 /* If no free slot and max hit, fail */
7672 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
7673 return MDB_DBS_FULL;
7675 /* Cannot mix named databases with some mainDB flags */
7676 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
7677 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
7679 /* Find the DB info */
7680 dbflag = DB_NEW|DB_VALID;
7683 key.mv_data = (void *)name;
7684 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
7685 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
7686 if (rc == MDB_SUCCESS) {
7687 /* make sure this is actually a DB */
7688 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
7689 if (!(node->mn_flags & F_SUBDATA))
7691 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
7692 /* Create if requested */
7694 data.mv_size = sizeof(MDB_db);
7695 data.mv_data = &dummy;
7696 memset(&dummy, 0, sizeof(dummy));
7697 dummy.md_root = P_INVALID;
7698 dummy.md_flags = flags & PERSISTENT_FLAGS;
7699 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
7703 /* OK, got info, add to table */
7704 if (rc == MDB_SUCCESS) {
7705 unsigned int slot = unused ? unused : txn->mt_numdbs;
7706 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
7707 txn->mt_dbxs[slot].md_name.mv_size = len;
7708 txn->mt_dbxs[slot].md_rel = NULL;
7709 txn->mt_dbflags[slot] = dbflag;
7710 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
7712 txn->mt_env->me_dbflags[slot] = txn->mt_dbs[slot].md_flags;
7713 mdb_default_cmp(txn, slot);
7722 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
7724 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
7727 if (txn->mt_dbflags[dbi] & DB_STALE) {
7730 /* Stale, must read the DB's root. cursor_init does it for us. */
7731 mdb_cursor_init(&mc, txn, dbi, &mx);
7733 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
7736 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
7739 if (dbi <= MAIN_DBI || dbi >= env->me_maxdbs)
7741 ptr = env->me_dbxs[dbi].md_name.mv_data;
7742 env->me_dbxs[dbi].md_name.mv_data = NULL;
7743 env->me_dbxs[dbi].md_name.mv_size = 0;
7744 env->me_dbflags[dbi] = 0;
7748 int mdb_dbi_flags(MDB_env *env, MDB_dbi dbi, unsigned int *flags)
7750 /* We could return the flags for the FREE_DBI too but what's the point? */
7751 if (dbi <= MAIN_DBI || dbi >= env->me_numdbs)
7753 *flags = env->me_dbflags[dbi];
7757 /** Add all the DB's pages to the free list.
7758 * @param[in] mc Cursor on the DB to free.
7759 * @param[in] subs non-Zero to check for sub-DBs in this DB.
7760 * @return 0 on success, non-zero on failure.
7763 mdb_drop0(MDB_cursor *mc, int subs)
7767 rc = mdb_page_search(mc, NULL, 0);
7768 if (rc == MDB_SUCCESS) {
7769 MDB_txn *txn = mc->mc_txn;
7774 /* LEAF2 pages have no nodes, cannot have sub-DBs */
7775 if (IS_LEAF2(mc->mc_pg[mc->mc_top]))
7778 mdb_cursor_copy(mc, &mx);
7779 while (mc->mc_snum > 0) {
7780 MDB_page *mp = mc->mc_pg[mc->mc_top];
7781 unsigned n = NUMKEYS(mp);
7783 for (i=0; i<n; i++) {
7784 ni = NODEPTR(mp, i);
7785 if (ni->mn_flags & F_BIGDATA) {
7788 memcpy(&pg, NODEDATA(ni), sizeof(pg));
7789 rc = mdb_page_get(txn, pg, &omp, NULL);
7792 assert(IS_OVERFLOW(omp));
7793 rc = mdb_midl_append_range(&txn->mt_free_pgs,
7797 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
7798 mdb_xcursor_init1(mc, ni);
7799 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
7805 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
7807 for (i=0; i<n; i++) {
7809 ni = NODEPTR(mp, i);
7812 mdb_midl_xappend(txn->mt_free_pgs, pg);
7817 mc->mc_ki[mc->mc_top] = i;
7818 rc = mdb_cursor_sibling(mc, 1);
7820 /* no more siblings, go back to beginning
7821 * of previous level.
7825 for (i=1; i<mc->mc_snum; i++) {
7827 mc->mc_pg[i] = mx.mc_pg[i];
7832 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
7833 } else if (rc == MDB_NOTFOUND) {
7839 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
7841 MDB_cursor *mc, *m2;
7844 if (!txn || !dbi || dbi >= txn->mt_numdbs || (unsigned)del > 1 || !(txn->mt_dbflags[dbi] & DB_VALID))
7847 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
7850 rc = mdb_cursor_open(txn, dbi, &mc);
7854 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
7855 /* Invalidate the dropped DB's cursors */
7856 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
7857 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
7861 /* Can't delete the main DB */
7862 if (del && dbi > MAIN_DBI) {
7863 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
7865 txn->mt_dbflags[dbi] = DB_STALE;
7866 mdb_dbi_close(txn->mt_env, dbi);
7869 /* reset the DB record, mark it dirty */
7870 txn->mt_dbflags[dbi] |= DB_DIRTY;
7871 txn->mt_dbs[dbi].md_depth = 0;
7872 txn->mt_dbs[dbi].md_branch_pages = 0;
7873 txn->mt_dbs[dbi].md_leaf_pages = 0;
7874 txn->mt_dbs[dbi].md_overflow_pages = 0;
7875 txn->mt_dbs[dbi].md_entries = 0;
7876 txn->mt_dbs[dbi].md_root = P_INVALID;
7878 txn->mt_flags |= MDB_TXN_DIRTY;
7881 mdb_cursor_close(mc);
7885 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
7887 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7890 txn->mt_dbxs[dbi].md_cmp = cmp;
7894 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
7896 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7899 txn->mt_dbxs[dbi].md_dcmp = cmp;
7903 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
7905 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7908 txn->mt_dbxs[dbi].md_rel = rel;
7912 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
7914 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7917 txn->mt_dbxs[dbi].md_relctx = ctx;
7921 int mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
7923 unsigned int i, rdrs;
7930 if (!env->me_txns) {
7931 return func("(no reader locks)\n", ctx);
7933 rdrs = env->me_numreaders;
7934 mr = env->me_txns->mti_readers;
7935 for (i=0; i<rdrs; i++) {
7940 if (mr[i].mr_txnid == (txnid_t)-1) {
7941 sprintf(buf, "%10d %zx -\n", mr[i].mr_pid, tid);
7943 sprintf(buf, "%10d %zx %zu\n", mr[i].mr_pid, tid, mr[i].mr_txnid);
7947 func(" pid thread txnid\n", ctx);
7949 rc = func(buf, ctx);
7955 func("(no active readers)\n", ctx);