2 * @brief memory-mapped database library
4 * A Btree-based database management library modeled loosely on the
5 * BerkeleyDB API, but much simplified.
8 * Copyright 2011-2013 Howard Chu, Symas Corp.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted only as authorized by the OpenLDAP
15 * A copy of this license is available in the file LICENSE in the
16 * top-level directory of the distribution or, alternatively, at
17 * <http://www.OpenLDAP.org/license.html>.
19 * This code is derived from btree.c written by Martin Hedenfalk.
21 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
23 * Permission to use, copy, modify, and distribute this software for any
24 * purpose with or without fee is hereby granted, provided that the above
25 * copyright notice and this permission notice appear in all copies.
27 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
28 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
29 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
30 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
31 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
32 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
33 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
38 #include <sys/types.h>
40 #include <sys/param.h>
46 #ifdef HAVE_SYS_FILE_H
63 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
64 #include <netinet/in.h>
65 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
68 #if defined(__APPLE__) || defined (BSD)
69 # define MDB_USE_POSIX_SEM 1
70 # define MDB_FDATASYNC fsync
71 #elif defined(ANDROID)
72 # define MDB_FDATASYNC fsync
77 #ifdef MDB_USE_POSIX_SEM
78 #include <semaphore.h>
83 #include <valgrind/memcheck.h>
84 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
85 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
86 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
87 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
88 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
90 #define VGMEMP_CREATE(h,r,z)
91 #define VGMEMP_ALLOC(h,a,s)
92 #define VGMEMP_FREE(h,a)
93 #define VGMEMP_DESTROY(h)
94 #define VGMEMP_DEFINED(a,s)
98 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
99 /* Solaris just defines one or the other */
100 # define LITTLE_ENDIAN 1234
101 # define BIG_ENDIAN 4321
102 # ifdef _LITTLE_ENDIAN
103 # define BYTE_ORDER LITTLE_ENDIAN
105 # define BYTE_ORDER BIG_ENDIAN
108 # define BYTE_ORDER __BYTE_ORDER
112 #ifndef LITTLE_ENDIAN
113 #define LITTLE_ENDIAN __LITTLE_ENDIAN
116 #define BIG_ENDIAN __BIG_ENDIAN
119 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
120 #define MISALIGNED_OK 1
126 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
127 # error "Unknown or unsupported endianness (BYTE_ORDER)"
128 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
129 # error "Two's complement, reasonably sized integer types, please"
132 /** @defgroup internal MDB Internals
135 /** @defgroup compat Windows Compatibility Macros
136 * A bunch of macros to minimize the amount of platform-specific ifdefs
137 * needed throughout the rest of the code. When the features this library
138 * needs are similar enough to POSIX to be hidden in a one-or-two line
139 * replacement, this macro approach is used.
143 #define pthread_t DWORD
144 #define pthread_mutex_t HANDLE
145 #define pthread_key_t DWORD
146 #define pthread_self() GetCurrentThreadId()
147 #define pthread_key_create(x,y) \
148 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
149 #define pthread_key_delete(x) TlsFree(x)
150 #define pthread_getspecific(x) TlsGetValue(x)
151 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
152 #define pthread_mutex_unlock(x) ReleaseMutex(x)
153 #define pthread_mutex_lock(x) WaitForSingleObject(x, INFINITE)
154 #define LOCK_MUTEX_R(env) pthread_mutex_lock((env)->me_rmutex)
155 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock((env)->me_rmutex)
156 #define LOCK_MUTEX_W(env) pthread_mutex_lock((env)->me_wmutex)
157 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock((env)->me_wmutex)
158 #define getpid() GetCurrentProcessId()
159 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
160 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
161 #define ErrCode() GetLastError()
162 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
163 #define close(fd) (CloseHandle(fd) ? 0 : -1)
164 #define munmap(ptr,len) UnmapViewOfFile(ptr)
167 #ifdef MDB_USE_POSIX_SEM
169 #define LOCK_MUTEX_R(env) mdb_sem_wait((env)->me_rmutex)
170 #define UNLOCK_MUTEX_R(env) sem_post((env)->me_rmutex)
171 #define LOCK_MUTEX_W(env) mdb_sem_wait((env)->me_wmutex)
172 #define UNLOCK_MUTEX_W(env) sem_post((env)->me_wmutex)
175 mdb_sem_wait(sem_t *sem)
178 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
183 /** Lock the reader mutex.
185 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
186 /** Unlock the reader mutex.
188 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
190 /** Lock the writer mutex.
191 * Only a single write transaction is allowed at a time. Other writers
192 * will block waiting for this mutex.
194 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
195 /** Unlock the writer mutex.
197 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
198 #endif /* MDB_USE_POSIX_SEM */
200 /** Get the error code for the last failed system function.
202 #define ErrCode() errno
204 /** An abstraction for a file handle.
205 * On POSIX systems file handles are small integers. On Windows
206 * they're opaque pointers.
210 /** A value for an invalid file handle.
211 * Mainly used to initialize file variables and signify that they are
214 #define INVALID_HANDLE_VALUE (-1)
216 /** Get the size of a memory page for the system.
217 * This is the basic size that the platform's memory manager uses, and is
218 * fundamental to the use of memory-mapped files.
220 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
223 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
226 #define MNAME_LEN (sizeof(pthread_mutex_t))
232 /** A flag for opening a file and requesting synchronous data writes.
233 * This is only used when writing a meta page. It's not strictly needed;
234 * we could just do a normal write and then immediately perform a flush.
235 * But if this flag is available it saves us an extra system call.
237 * @note If O_DSYNC is undefined but exists in /usr/include,
238 * preferably set some compiler flag to get the definition.
239 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
242 # define MDB_DSYNC O_DSYNC
246 /** Function for flushing the data of a file. Define this to fsync
247 * if fdatasync() is not supported.
249 #ifndef MDB_FDATASYNC
250 # define MDB_FDATASYNC fdatasync
254 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
265 /** A page number in the database.
266 * Note that 64 bit page numbers are overkill, since pages themselves
267 * already represent 12-13 bits of addressable memory, and the OS will
268 * always limit applications to a maximum of 63 bits of address space.
270 * @note In the #MDB_node structure, we only store 48 bits of this value,
271 * which thus limits us to only 60 bits of addressable data.
273 typedef MDB_ID pgno_t;
275 /** A transaction ID.
276 * See struct MDB_txn.mt_txnid for details.
278 typedef MDB_ID txnid_t;
280 /** @defgroup debug Debug Macros
284 /** Enable debug output.
285 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
286 * read from and written to the database (used for free space management).
291 #if !(__STDC_VERSION__ >= 199901L || defined(__GNUC__))
294 # define DPRINTF (void) /* Vararg macros may be unsupported */
296 static int mdb_debug;
297 static txnid_t mdb_debug_start;
299 /** Print a debug message with printf formatting. */
300 # define DPRINTF(fmt, ...) /**< Requires 2 or more args */ \
301 ((void) ((mdb_debug) && \
302 fprintf(stderr, "%s:%d " fmt "\n", __func__, __LINE__, __VA_ARGS__)))
304 # define DPRINTF(fmt, ...) ((void) 0)
305 # define MDB_DEBUG_SKIP
307 /** Print a debug string.
308 * The string is printed literally, with no format processing.
310 #define DPUTS(arg) DPRINTF("%s", arg)
313 /** A default memory page size.
314 * The actual size is platform-dependent, but we use this for
315 * boot-strapping. We probably should not be using this any more.
316 * The #GET_PAGESIZE() macro is used to get the actual size.
318 * Note that we don't currently support Huge pages. On Linux,
319 * regular data files cannot use Huge pages, and in general
320 * Huge pages aren't actually pageable. We rely on the OS
321 * demand-pager to read our data and page it out when memory
322 * pressure from other processes is high. So until OSs have
323 * actual paging support for Huge pages, they're not viable.
325 #define MDB_PAGESIZE 4096
327 /** The minimum number of keys required in a database page.
328 * Setting this to a larger value will place a smaller bound on the
329 * maximum size of a data item. Data items larger than this size will
330 * be pushed into overflow pages instead of being stored directly in
331 * the B-tree node. This value used to default to 4. With a page size
332 * of 4096 bytes that meant that any item larger than 1024 bytes would
333 * go into an overflow page. That also meant that on average 2-3KB of
334 * each overflow page was wasted space. The value cannot be lower than
335 * 2 because then there would no longer be a tree structure. With this
336 * value, items larger than 2KB will go into overflow pages, and on
337 * average only 1KB will be wasted.
339 #define MDB_MINKEYS 2
341 /** A stamp that identifies a file as an MDB file.
342 * There's nothing special about this value other than that it is easily
343 * recognizable, and it will reflect any byte order mismatches.
345 #define MDB_MAGIC 0xBEEFC0DE
347 /** The version number for a database's file format. */
348 #define MDB_VERSION 1
350 /** @brief The maximum size of a key in the database.
352 * The library rejects bigger keys, and cannot deal with records
353 * with bigger keys stored by a library with bigger max keysize.
355 * We require that keys all fit onto a regular page. This limit
356 * could be raised a bit further if needed; to something just
357 * under #MDB_PAGESIZE / #MDB_MINKEYS.
359 * Note that data items in an #MDB_DUPSORT database are actually keys
360 * of a subDB, so they're also limited to this size.
362 #ifndef MDB_MAXKEYSIZE
363 #define MDB_MAXKEYSIZE 511
366 /** @brief The maximum size of a data item.
368 * We only store a 32 bit value for node sizes.
370 #define MAXDATASIZE 0xffffffffUL
375 * This is used for printing a hex dump of a key's contents.
377 #define DKBUF char kbuf[(MDB_MAXKEYSIZE*2+1)]
378 /** Display a key in hex.
380 * Invoke a function to display a key in hex.
382 #define DKEY(x) mdb_dkey(x, kbuf)
384 #define DKBUF typedef int dummy_kbuf /* so we can put ';' after */
388 /** An invalid page number.
389 * Mainly used to denote an empty tree.
391 #define P_INVALID (~(pgno_t)0)
393 /** Test if the flags \b f are set in a flag word \b w. */
394 #define F_ISSET(w, f) (((w) & (f)) == (f))
396 /** Used for offsets within a single page.
397 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
400 typedef uint16_t indx_t;
402 /** Default size of memory map.
403 * This is certainly too small for any actual applications. Apps should always set
404 * the size explicitly using #mdb_env_set_mapsize().
406 #define DEFAULT_MAPSIZE 1048576
408 /** @defgroup readers Reader Lock Table
409 * Readers don't acquire any locks for their data access. Instead, they
410 * simply record their transaction ID in the reader table. The reader
411 * mutex is needed just to find an empty slot in the reader table. The
412 * slot's address is saved in thread-specific data so that subsequent read
413 * transactions started by the same thread need no further locking to proceed.
415 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
417 * No reader table is used if the database is on a read-only filesystem.
419 * Since the database uses multi-version concurrency control, readers don't
420 * actually need any locking. This table is used to keep track of which
421 * readers are using data from which old transactions, so that we'll know
422 * when a particular old transaction is no longer in use. Old transactions
423 * that have discarded any data pages can then have those pages reclaimed
424 * for use by a later write transaction.
426 * The lock table is constructed such that reader slots are aligned with the
427 * processor's cache line size. Any slot is only ever used by one thread.
428 * This alignment guarantees that there will be no contention or cache
429 * thrashing as threads update their own slot info, and also eliminates
430 * any need for locking when accessing a slot.
432 * A writer thread will scan every slot in the table to determine the oldest
433 * outstanding reader transaction. Any freed pages older than this will be
434 * reclaimed by the writer. The writer doesn't use any locks when scanning
435 * this table. This means that there's no guarantee that the writer will
436 * see the most up-to-date reader info, but that's not required for correct
437 * operation - all we need is to know the upper bound on the oldest reader,
438 * we don't care at all about the newest reader. So the only consequence of
439 * reading stale information here is that old pages might hang around a
440 * while longer before being reclaimed. That's actually good anyway, because
441 * the longer we delay reclaiming old pages, the more likely it is that a
442 * string of contiguous pages can be found after coalescing old pages from
443 * many old transactions together.
446 /** Number of slots in the reader table.
447 * This value was chosen somewhat arbitrarily. 126 readers plus a
448 * couple mutexes fit exactly into 8KB on my development machine.
449 * Applications should set the table size using #mdb_env_set_maxreaders().
451 #define DEFAULT_READERS 126
453 /** The size of a CPU cache line in bytes. We want our lock structures
454 * aligned to this size to avoid false cache line sharing in the
456 * This value works for most CPUs. For Itanium this should be 128.
462 /** The information we store in a single slot of the reader table.
463 * In addition to a transaction ID, we also record the process and
464 * thread ID that owns a slot, so that we can detect stale information,
465 * e.g. threads or processes that went away without cleaning up.
466 * @note We currently don't check for stale records. We simply re-init
467 * the table when we know that we're the only process opening the
470 typedef struct MDB_rxbody {
471 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
472 * Multiple readers that start at the same time will probably have the
473 * same ID here. Again, it's not important to exclude them from
474 * anything; all we need to know is which version of the DB they
475 * started from so we can avoid overwriting any data used in that
476 * particular version.
479 /** The process ID of the process owning this reader txn. */
481 /** The thread ID of the thread owning this txn. */
485 /** The actual reader record, with cacheline padding. */
486 typedef struct MDB_reader {
489 /** shorthand for mrb_txnid */
490 #define mr_txnid mru.mrx.mrb_txnid
491 #define mr_pid mru.mrx.mrb_pid
492 #define mr_tid mru.mrx.mrb_tid
493 /** cache line alignment */
494 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
498 /** The header for the reader table.
499 * The table resides in a memory-mapped file. (This is a different file
500 * than is used for the main database.)
502 * For POSIX the actual mutexes reside in the shared memory of this
503 * mapped file. On Windows, mutexes are named objects allocated by the
504 * kernel; we store the mutex names in this mapped file so that other
505 * processes can grab them. This same approach is also used on
506 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
507 * process-shared POSIX mutexes. For these cases where a named object
508 * is used, the object name is derived from a 64 bit FNV hash of the
509 * environment pathname. As such, naming collisions are extremely
510 * unlikely. If a collision occurs, the results are unpredictable.
512 typedef struct MDB_txbody {
513 /** Stamp identifying this as an MDB file. It must be set
516 /** Version number of this lock file. Must be set to #MDB_VERSION. */
517 uint32_t mtb_version;
518 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
519 char mtb_rmname[MNAME_LEN];
521 /** Mutex protecting access to this table.
522 * This is the reader lock that #LOCK_MUTEX_R acquires.
524 pthread_mutex_t mtb_mutex;
526 /** The ID of the last transaction committed to the database.
527 * This is recorded here only for convenience; the value can always
528 * be determined by reading the main database meta pages.
531 /** The number of slots that have been used in the reader table.
532 * This always records the maximum count, it is not decremented
533 * when readers release their slots.
535 unsigned mtb_numreaders;
538 /** The actual reader table definition. */
539 typedef struct MDB_txninfo {
542 #define mti_magic mt1.mtb.mtb_magic
543 #define mti_version mt1.mtb.mtb_version
544 #define mti_mutex mt1.mtb.mtb_mutex
545 #define mti_rmname mt1.mtb.mtb_rmname
546 #define mti_txnid mt1.mtb.mtb_txnid
547 #define mti_numreaders mt1.mtb.mtb_numreaders
548 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
551 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
552 char mt2_wmname[MNAME_LEN];
553 #define mti_wmname mt2.mt2_wmname
555 pthread_mutex_t mt2_wmutex;
556 #define mti_wmutex mt2.mt2_wmutex
558 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
560 MDB_reader mti_readers[1];
564 /** Common header for all page types.
565 * Overflow records occupy a number of contiguous pages with no
566 * headers on any page after the first.
568 typedef struct MDB_page {
569 #define mp_pgno mp_p.p_pgno
570 #define mp_next mp_p.p_next
572 pgno_t p_pgno; /**< page number */
573 void * p_next; /**< for in-memory list of freed structs */
576 /** @defgroup mdb_page Page Flags
578 * Flags for the page headers.
581 #define P_BRANCH 0x01 /**< branch page */
582 #define P_LEAF 0x02 /**< leaf page */
583 #define P_OVERFLOW 0x04 /**< overflow page */
584 #define P_META 0x08 /**< meta page */
585 #define P_DIRTY 0x10 /**< dirty page */
586 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
587 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
588 #define P_KEEP 0x8000 /**< leave this page alone during spill */
590 uint16_t mp_flags; /**< @ref mdb_page */
591 #define mp_lower mp_pb.pb.pb_lower
592 #define mp_upper mp_pb.pb.pb_upper
593 #define mp_pages mp_pb.pb_pages
596 indx_t pb_lower; /**< lower bound of free space */
597 indx_t pb_upper; /**< upper bound of free space */
599 uint32_t pb_pages; /**< number of overflow pages */
601 indx_t mp_ptrs[1]; /**< dynamic size */
604 /** Size of the page header, excluding dynamic data at the end */
605 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
607 /** Address of first usable data byte in a page, after the header */
608 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
610 /** Number of nodes on a page */
611 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
613 /** The amount of space remaining in the page */
614 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
616 /** The percentage of space used in the page, in tenths of a percent. */
617 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
618 ((env)->me_psize - PAGEHDRSZ))
619 /** The minimum page fill factor, in tenths of a percent.
620 * Pages emptier than this are candidates for merging.
622 #define FILL_THRESHOLD 250
624 /** Test if a page is a leaf page */
625 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
626 /** Test if a page is a LEAF2 page */
627 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
628 /** Test if a page is a branch page */
629 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
630 /** Test if a page is an overflow page */
631 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
632 /** Test if a page is a sub page */
633 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
635 /** The number of overflow pages needed to store the given size. */
636 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
638 /** Header for a single key/data pair within a page.
639 * We guarantee 2-byte alignment for nodes.
641 typedef struct MDB_node {
642 /** lo and hi are used for data size on leaf nodes and for
643 * child pgno on branch nodes. On 64 bit platforms, flags
644 * is also used for pgno. (Branch nodes have no flags).
645 * They are in host byte order in case that lets some
646 * accesses be optimized into a 32-bit word access.
648 #define mn_lo mn_offset[BYTE_ORDER!=LITTLE_ENDIAN]
649 #define mn_hi mn_offset[BYTE_ORDER==LITTLE_ENDIAN] /**< part of dsize or pgno */
650 unsigned short mn_offset[2]; /**< storage for #mn_lo and #mn_hi */
651 /** @defgroup mdb_node Node Flags
653 * Flags for node headers.
656 #define F_BIGDATA 0x01 /**< data put on overflow page */
657 #define F_SUBDATA 0x02 /**< data is a sub-database */
658 #define F_DUPDATA 0x04 /**< data has duplicates */
660 /** valid flags for #mdb_node_add() */
661 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
664 unsigned short mn_flags; /**< @ref mdb_node */
665 unsigned short mn_ksize; /**< key size */
666 char mn_data[1]; /**< key and data are appended here */
669 /** Size of the node header, excluding dynamic data at the end */
670 #define NODESIZE offsetof(MDB_node, mn_data)
672 /** Bit position of top word in page number, for shifting mn_flags */
673 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
675 /** Size of a node in a branch page with a given key.
676 * This is just the node header plus the key, there is no data.
678 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
680 /** Size of a node in a leaf page with a given key and data.
681 * This is node header plus key plus data size.
683 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
685 /** Address of node \b i in page \b p */
686 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
688 /** Address of the key for the node */
689 #define NODEKEY(node) (void *)((node)->mn_data)
691 /** Address of the data for a node */
692 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
694 /** Get the page number pointed to by a branch node */
695 #define NODEPGNO(node) \
696 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
697 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
698 /** Set the page number in a branch node */
699 #define SETPGNO(node,pgno) do { \
700 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
701 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
703 /** Get the size of the data in a leaf node */
704 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
705 /** Set the size of the data for a leaf node */
706 #define SETDSZ(node,size) do { \
707 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
708 /** The size of a key in a node */
709 #define NODEKSZ(node) ((node)->mn_ksize)
711 /** Copy a page number from src to dst */
713 #define COPY_PGNO(dst,src) dst = src
715 #if SIZE_MAX > 4294967295UL
716 #define COPY_PGNO(dst,src) do { \
717 unsigned short *s, *d; \
718 s = (unsigned short *)&(src); \
719 d = (unsigned short *)&(dst); \
726 #define COPY_PGNO(dst,src) do { \
727 unsigned short *s, *d; \
728 s = (unsigned short *)&(src); \
729 d = (unsigned short *)&(dst); \
735 /** The address of a key in a LEAF2 page.
736 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
737 * There are no node headers, keys are stored contiguously.
739 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
741 /** Set the \b node's key into \b key, if requested. */
742 #define MDB_GET_KEY(node, key) { if ((key) != NULL) { \
743 (key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node); } }
745 /** Information about a single database in the environment. */
746 typedef struct MDB_db {
747 uint32_t md_pad; /**< also ksize for LEAF2 pages */
748 uint16_t md_flags; /**< @ref mdb_dbi_open */
749 uint16_t md_depth; /**< depth of this tree */
750 pgno_t md_branch_pages; /**< number of internal pages */
751 pgno_t md_leaf_pages; /**< number of leaf pages */
752 pgno_t md_overflow_pages; /**< number of overflow pages */
753 size_t md_entries; /**< number of data items */
754 pgno_t md_root; /**< the root page of this tree */
757 /** mdb_dbi_open flags */
758 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
759 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
760 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
761 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
763 /** Handle for the DB used to track free pages. */
765 /** Handle for the default DB. */
768 /** Meta page content. */
769 typedef struct MDB_meta {
770 /** Stamp identifying this as an MDB file. It must be set
773 /** Version number of this lock file. Must be set to #MDB_VERSION. */
775 void *mm_address; /**< address for fixed mapping */
776 size_t mm_mapsize; /**< size of mmap region */
777 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
778 /** The size of pages used in this DB */
779 #define mm_psize mm_dbs[0].md_pad
780 /** Any persistent environment flags. @ref mdb_env */
781 #define mm_flags mm_dbs[0].md_flags
782 pgno_t mm_last_pg; /**< last used page in file */
783 txnid_t mm_txnid; /**< txnid that committed this page */
786 /** Buffer for a stack-allocated dirty page.
787 * The members define size and alignment, and silence type
788 * aliasing warnings. They are not used directly; that could
789 * mean incorrectly using several union members in parallel.
791 typedef union MDB_pagebuf {
792 char mb_raw[MDB_PAGESIZE];
795 char mm_pad[PAGEHDRSZ];
800 /** Auxiliary DB info.
801 * The information here is mostly static/read-only. There is
802 * only a single copy of this record in the environment.
804 typedef struct MDB_dbx {
805 MDB_val md_name; /**< name of the database */
806 MDB_cmp_func *md_cmp; /**< function for comparing keys */
807 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
808 MDB_rel_func *md_rel; /**< user relocate function */
809 void *md_relctx; /**< user-provided context for md_rel */
812 /** A database transaction.
813 * Every operation requires a transaction handle.
816 MDB_txn *mt_parent; /**< parent of a nested txn */
817 MDB_txn *mt_child; /**< nested txn under this txn */
818 pgno_t mt_next_pgno; /**< next unallocated page */
819 /** The ID of this transaction. IDs are integers incrementing from 1.
820 * Only committed write transactions increment the ID. If a transaction
821 * aborts, the ID may be re-used by the next writer.
824 MDB_env *mt_env; /**< the DB environment */
825 /** The list of pages that became unused during this transaction.
828 /** The list of dirty pages we temporarily wrote to disk
829 * because the dirty list was full.
831 MDB_IDL mt_spill_pgs;
833 MDB_ID2L dirty_list; /**< for write txns: modified pages */
834 MDB_reader *reader; /**< this thread's reader table slot or NULL */
836 /** Array of records for each DB known in the environment. */
838 /** Array of MDB_db records for each known DB */
840 /** @defgroup mt_dbflag Transaction DB Flags
844 #define DB_DIRTY 0x01 /**< DB was written in this txn */
845 #define DB_STALE 0x02 /**< DB record is older than txnID */
846 #define DB_NEW 0x04 /**< DB handle opened in this txn */
847 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
849 /** In write txns, array of cursors for each DB */
850 MDB_cursor **mt_cursors;
851 /** Array of flags for each DB */
852 unsigned char *mt_dbflags;
853 /** Number of DB records in use. This number only ever increments;
854 * we don't decrement it when individual DB handles are closed.
858 /** @defgroup mdb_txn Transaction Flags
862 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
863 #define MDB_TXN_ERROR 0x02 /**< an error has occurred */
864 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
865 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
867 unsigned int mt_flags; /**< @ref mdb_txn */
868 /** dirty_list maxsize - # of allocated pages allowed, including in parent txns */
869 unsigned int mt_dirty_room;
870 /** Tracks which of the two meta pages was used at the start
871 * of this transaction.
873 unsigned int mt_toggle;
876 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
877 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
878 * raise this on a 64 bit machine.
880 #define CURSOR_STACK 32
884 /** Cursors are used for all DB operations */
886 /** Next cursor on this DB in this txn */
888 /** Backup of the original cursor if this cursor is a shadow */
889 MDB_cursor *mc_backup;
890 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
891 struct MDB_xcursor *mc_xcursor;
892 /** The transaction that owns this cursor */
894 /** The database handle this cursor operates on */
896 /** The database record for this cursor */
898 /** The database auxiliary record for this cursor */
900 /** The @ref mt_dbflag for this database */
901 unsigned char *mc_dbflag;
902 unsigned short mc_snum; /**< number of pushed pages */
903 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
904 /** @defgroup mdb_cursor Cursor Flags
906 * Cursor state flags.
909 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
910 #define C_EOF 0x02 /**< No more data */
911 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
912 #define C_SPLITTING 0x20 /**< Cursor is in page_split */
913 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
915 unsigned int mc_flags; /**< @ref mdb_cursor */
916 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
917 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
920 /** Context for sorted-dup records.
921 * We could have gone to a fully recursive design, with arbitrarily
922 * deep nesting of sub-databases. But for now we only handle these
923 * levels - main DB, optional sub-DB, sorted-duplicate DB.
925 typedef struct MDB_xcursor {
926 /** A sub-cursor for traversing the Dup DB */
927 MDB_cursor mx_cursor;
928 /** The database record for this Dup DB */
930 /** The auxiliary DB record for this Dup DB */
932 /** The @ref mt_dbflag for this Dup DB */
933 unsigned char mx_dbflag;
936 /** State of FreeDB old pages, stored in the MDB_env */
937 typedef struct MDB_pgstate {
938 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
939 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
942 /** The database environment. */
944 HANDLE me_fd; /**< The main data file */
945 HANDLE me_lfd; /**< The lock file */
946 HANDLE me_mfd; /**< just for writing the meta pages */
947 /** Failed to update the meta page. Probably an I/O error. */
948 #define MDB_FATAL_ERROR 0x80000000U
949 /** Some fields are initialized. */
950 #define MDB_ENV_ACTIVE 0x20000000U
951 /** me_txkey is set */
952 #define MDB_ENV_TXKEY 0x10000000U
953 uint32_t me_flags; /**< @ref mdb_env */
954 unsigned int me_psize; /**< size of a page, from #GET_PAGESIZE */
955 unsigned int me_maxreaders; /**< size of the reader table */
956 unsigned int me_numreaders; /**< max numreaders set by this env */
957 MDB_dbi me_numdbs; /**< number of DBs opened */
958 MDB_dbi me_maxdbs; /**< size of the DB table */
959 pid_t me_pid; /**< process ID of this env */
960 char *me_path; /**< path to the DB files */
961 char *me_map; /**< the memory map of the data file */
962 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
963 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
964 MDB_txn *me_txn; /**< current write transaction */
965 size_t me_mapsize; /**< size of the data memory map */
966 off_t me_size; /**< current file size */
967 pgno_t me_maxpg; /**< me_mapsize / me_psize */
968 MDB_dbx *me_dbxs; /**< array of static DB info */
969 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
970 pthread_key_t me_txkey; /**< thread-key for readers */
971 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
972 # define me_pglast me_pgstate.mf_pglast
973 # define me_pghead me_pgstate.mf_pghead
974 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
975 /** IDL of pages that became unused in a write txn */
977 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
978 MDB_ID2L me_dirty_list;
979 /** Max number of freelist items that can fit in a single overflow page */
981 /** Max size of a node on a page */
982 unsigned int me_nodemax;
984 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
986 #elif defined(MDB_USE_POSIX_SEM)
987 sem_t *me_rmutex; /* Shared mutexes are not supported */
992 /** Nested transaction */
993 typedef struct MDB_ntxn {
994 MDB_txn mnt_txn; /* the transaction */
995 MDB_pgstate mnt_pgstate; /* parent transaction's saved freestate */
998 /** max number of pages to commit in one writev() call */
999 #define MDB_COMMIT_PAGES 64
1000 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1001 #undef MDB_COMMIT_PAGES
1002 #define MDB_COMMIT_PAGES IOV_MAX
1005 /* max bytes to write in one call */
1006 #define MAX_WRITE (0x80000000U >> (sizeof(ssize_t) == 4))
1008 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1009 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1010 static int mdb_page_touch(MDB_cursor *mc);
1012 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp, int *lvl);
1013 static int mdb_page_search_root(MDB_cursor *mc,
1014 MDB_val *key, int modify);
1015 #define MDB_PS_MODIFY 1
1016 #define MDB_PS_ROOTONLY 2
1017 static int mdb_page_search(MDB_cursor *mc,
1018 MDB_val *key, int flags);
1019 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1021 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1022 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1023 pgno_t newpgno, unsigned int nflags);
1025 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1026 static int mdb_env_pick_meta(const MDB_env *env);
1027 static int mdb_env_write_meta(MDB_txn *txn);
1028 #if !(defined(_WIN32) || defined(MDB_USE_POSIX_SEM)) /* Drop unused excl arg */
1029 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1031 static void mdb_env_close0(MDB_env *env, int excl);
1033 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1034 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1035 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1036 static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
1037 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1038 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
1039 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1040 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1041 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1043 static int mdb_rebalance(MDB_cursor *mc);
1044 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1046 static void mdb_cursor_pop(MDB_cursor *mc);
1047 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1049 static int mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
1050 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1051 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1052 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1053 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1055 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1056 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1058 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1059 static void mdb_xcursor_init0(MDB_cursor *mc);
1060 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1062 static int mdb_drop0(MDB_cursor *mc, int subs);
1063 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1066 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1070 static SECURITY_DESCRIPTOR mdb_null_sd;
1071 static SECURITY_ATTRIBUTES mdb_all_sa;
1072 static int mdb_sec_inited;
1075 /** Return the library version info. */
1077 mdb_version(int *major, int *minor, int *patch)
1079 if (major) *major = MDB_VERSION_MAJOR;
1080 if (minor) *minor = MDB_VERSION_MINOR;
1081 if (patch) *patch = MDB_VERSION_PATCH;
1082 return MDB_VERSION_STRING;
1085 /** Table of descriptions for MDB @ref errors */
1086 static char *const mdb_errstr[] = {
1087 "MDB_KEYEXIST: Key/data pair already exists",
1088 "MDB_NOTFOUND: No matching key/data pair found",
1089 "MDB_PAGE_NOTFOUND: Requested page not found",
1090 "MDB_CORRUPTED: Located page was wrong type",
1091 "MDB_PANIC: Update of meta page failed",
1092 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1093 "MDB_INVALID: File is not an MDB file",
1094 "MDB_MAP_FULL: Environment mapsize limit reached",
1095 "MDB_DBS_FULL: Environment maxdbs limit reached",
1096 "MDB_READERS_FULL: Environment maxreaders limit reached",
1097 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1098 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1099 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1100 "MDB_PAGE_FULL: Internal error - page has no more space",
1101 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1102 "MDB_INCOMPATIBLE: Database flags changed or would change",
1103 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1107 mdb_strerror(int err)
1111 return ("Successful return: 0");
1113 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1114 i = err - MDB_KEYEXIST;
1115 return mdb_errstr[i];
1118 return strerror(err);
1122 /** Display a key in hexadecimal and return the address of the result.
1123 * @param[in] key the key to display
1124 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1125 * @return The key in hexadecimal form.
1128 mdb_dkey(MDB_val *key, char *buf)
1131 unsigned char *c = key->mv_data;
1137 if (key->mv_size > MDB_MAXKEYSIZE)
1138 return "MDB_MAXKEYSIZE";
1139 /* may want to make this a dynamic check: if the key is mostly
1140 * printable characters, print it as-is instead of converting to hex.
1144 for (i=0; i<key->mv_size; i++)
1145 ptr += sprintf(ptr, "%02x", *c++);
1147 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1152 /** Display all the keys in the page. */
1154 mdb_page_list(MDB_page *mp)
1157 unsigned int i, nkeys, nsize;
1161 nkeys = NUMKEYS(mp);
1162 fprintf(stderr, "Page %zu numkeys %d\n", mp->mp_pgno, nkeys);
1163 for (i=0; i<nkeys; i++) {
1164 node = NODEPTR(mp, i);
1165 key.mv_size = node->mn_ksize;
1166 key.mv_data = node->mn_data;
1167 nsize = NODESIZE + NODEKSZ(node) + sizeof(indx_t);
1168 if (IS_BRANCH(mp)) {
1169 fprintf(stderr, "key %d: page %zu, %s\n", i, NODEPGNO(node),
1172 if (F_ISSET(node->mn_flags, F_BIGDATA))
1173 nsize += sizeof(pgno_t);
1175 nsize += NODEDSZ(node);
1176 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1182 mdb_cursor_chk(MDB_cursor *mc)
1188 if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1189 for (i=0; i<mc->mc_top; i++) {
1191 node = NODEPTR(mp, mc->mc_ki[i]);
1192 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1195 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1201 /** Count all the pages in each DB and in the freelist
1202 * and make sure it matches the actual number of pages
1205 static void mdb_audit(MDB_txn *txn)
1209 MDB_ID freecount, count;
1214 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1215 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1216 freecount += *(MDB_ID *)data.mv_data;
1219 for (i = 0; i<txn->mt_numdbs; i++) {
1221 mdb_cursor_init(&mc, txn, i, &mx);
1222 if (txn->mt_dbs[i].md_root == P_INVALID)
1224 count += txn->mt_dbs[i].md_branch_pages +
1225 txn->mt_dbs[i].md_leaf_pages +
1226 txn->mt_dbs[i].md_overflow_pages;
1227 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1228 mdb_page_search(&mc, NULL, 0);
1232 mp = mc.mc_pg[mc.mc_top];
1233 for (j=0; j<NUMKEYS(mp); j++) {
1234 MDB_node *leaf = NODEPTR(mp, j);
1235 if (leaf->mn_flags & F_SUBDATA) {
1237 memcpy(&db, NODEDATA(leaf), sizeof(db));
1238 count += db.md_branch_pages + db.md_leaf_pages +
1239 db.md_overflow_pages;
1243 while (mdb_cursor_sibling(&mc, 1) == 0);
1246 if (freecount + count + 2 /* metapages */ != txn->mt_next_pgno) {
1247 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1248 txn->mt_txnid, freecount, count+2, freecount+count+2, txn->mt_next_pgno);
1254 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1256 return txn->mt_dbxs[dbi].md_cmp(a, b);
1260 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1262 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1265 /** Allocate a page.
1266 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1269 mdb_page_malloc(MDB_txn *txn, unsigned num)
1271 MDB_env *env = txn->mt_env;
1272 MDB_page *ret = env->me_dpages;
1273 size_t sz = env->me_psize;
1276 VGMEMP_ALLOC(env, ret, sz);
1277 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1278 env->me_dpages = ret->mp_next;
1284 if ((ret = malloc(sz)) != NULL) {
1285 VGMEMP_ALLOC(env, ret, sz);
1290 /** Free a single page.
1291 * Saves single pages to a list, for future reuse.
1292 * (This is not used for multi-page overflow pages.)
1295 mdb_page_free(MDB_env *env, MDB_page *mp)
1297 mp->mp_next = env->me_dpages;
1298 VGMEMP_FREE(env, mp);
1299 env->me_dpages = mp;
1302 /* Free a dirty page */
1304 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1306 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1307 mdb_page_free(env, dp);
1309 /* large pages just get freed directly */
1310 VGMEMP_FREE(env, dp);
1315 /** Return all dirty pages to dpage list */
1317 mdb_dlist_free(MDB_txn *txn)
1319 MDB_env *env = txn->mt_env;
1320 MDB_ID2L dl = txn->mt_u.dirty_list;
1321 unsigned i, n = dl[0].mid;
1323 for (i = 1; i <= n; i++) {
1324 mdb_dpage_free(env, dl[i].mptr);
1329 static int mdb_page_flush(MDB_txn *txn);
1331 /** Spill pages from the dirty list back to disk.
1332 * This is intended to prevent running into #MDB_TXN_FULL situations,
1333 * but note that they may still occur in a few cases:
1334 * 1) pages in #MDB_DUPSORT sub-DBs are never spilled, so if there
1335 * are too many of these dirtied in one txn, the txn may still get
1337 * 2) child txns may run out of space if their parents dirtied a
1338 * lot of pages and never spilled them. TODO: we probably should do
1339 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1340 * the parent's dirty_room is below a given threshold.
1341 * 3) our estimate of the txn size could be too small. At the
1342 * moment this seems unlikely.
1344 * Otherwise, if not using nested txns, it is expected that apps will
1345 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1346 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1347 * If the txn never references them again, they can be left alone.
1348 * If the txn only reads them, they can be used without any fuss.
1349 * If the txn writes them again, they can be dirtied immediately without
1350 * going thru all of the work of #mdb_page_touch(). Such references are
1351 * handled by #mdb_page_unspill().
1353 * Also note, we never spill DB root pages, nor pages of active cursors,
1354 * because we'll need these back again soon anyway. And in nested txns,
1355 * we can't spill a page in a child txn if it was already spilled in a
1356 * parent txn. That would alter the parent txns' data even though
1357 * the child hasn't committed yet, and we'd have no way to undo it if
1358 * the child aborted.
1360 * @param[in] m0 cursor A cursor handle identifying the transaction and
1361 * database for which we are checking space.
1362 * @param[in] key For a put operation, the key being stored.
1363 * @param[in] data For a put operation, the data being stored.
1364 * @return 0 on success, non-zero on failure.
1367 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1369 MDB_txn *txn = m0->mc_txn;
1371 MDB_ID2L dl = txn->mt_u.dirty_list;
1375 if (m0->mc_flags & C_SUB)
1378 /* Estimate how much space this op will take */
1379 i = m0->mc_db->md_depth;
1380 /* Named DBs also dirty the main DB */
1381 if (m0->mc_dbi > MAIN_DBI)
1382 i += txn->mt_dbs[MAIN_DBI].md_depth;
1383 /* For puts, roughly factor in the key+data size */
1385 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
1386 i += i; /* double it for good measure */
1388 if (txn->mt_dirty_room > i)
1391 if (!txn->mt_spill_pgs) {
1392 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
1393 if (!txn->mt_spill_pgs)
1397 /* Mark all the dirty root pages we want to preserve */
1398 for (i=0; i<txn->mt_numdbs; i++) {
1399 if (txn->mt_dbflags[i] & DB_DIRTY) {
1400 j = mdb_mid2l_search(dl, txn->mt_dbs[i].md_root);
1401 if (j <= dl[0].mid) {
1403 dp->mp_flags |= P_KEEP;
1407 /* Mark all the pages of active cursors we want to preserve */
1408 for (i=0; i<txn->mt_numdbs; i++) {
1409 MDB_cursor *mc = txn->mt_cursors[i];
1410 /* See if m0 is tracked or not */
1411 if (i == m0->mc_dbi && !(m0->mc_flags & C_UNTRACK)) {
1412 /* nope. tack it on in front */
1416 for (; mc; mc=mc->mc_next) {
1417 if (mc->mc_flags & C_INITIALIZED) {
1418 for (j=0; j<mc->mc_snum; j++) {
1419 if (mc->mc_pg[j]->mp_flags & P_DIRTY)
1420 mc->mc_pg[j]->mp_flags |= P_KEEP;
1422 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1423 MDB_cursor *mx = &mc->mc_xcursor->mx_cursor;
1424 if (mx->mc_flags & C_INITIALIZED) {
1425 for (j=0; j<mx->mc_snum; j++) {
1426 if ((mx->mc_pg[j]->mp_flags & (P_SUBP|P_DIRTY))
1428 mx->mc_pg[j]->mp_flags |= P_KEEP;
1436 /* Save the page IDs of all the pages we're flushing */
1437 for (i=1; i<=dl[0].mid; i++) {
1439 if (dp->mp_flags & P_KEEP)
1441 /* Can't spill twice, make sure it's not already in a parent's
1444 if (txn->mt_parent) {
1446 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1447 if (tx2->mt_spill_pgs) {
1448 j = mdb_midl_search(tx2->mt_spill_pgs, dl[i].mid);
1449 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == dl[i].mid) {
1450 dp->mp_flags |= P_KEEP;
1458 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, dl[i].mid)))
1461 mdb_midl_sort(txn->mt_spill_pgs);
1463 rc = mdb_page_flush(txn);
1465 txn->mt_dirty_room = MDB_IDL_UM_MAX - dl[0].mid;
1466 txn->mt_flags |= MDB_TXN_SPILLS;
1471 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
1473 mdb_find_oldest(MDB_txn *txn)
1476 txnid_t mr, oldest = txn->mt_txnid - 1;
1477 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
1478 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
1488 /** Add a page to the txn's dirty list */
1490 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
1493 int (*insert)(MDB_ID2L, MDB_ID2 *);
1495 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1496 insert = mdb_mid2l_append;
1498 insert = mdb_mid2l_insert;
1500 mid.mid = mp->mp_pgno;
1502 insert(txn->mt_u.dirty_list, &mid);
1503 txn->mt_dirty_room--;
1506 /** Allocate pages for writing.
1507 * If there are free pages available from older transactions, they
1508 * will be re-used first. Otherwise a new page will be allocated.
1509 * @param[in] mc cursor A cursor handle identifying the transaction and
1510 * database for which we are allocating.
1511 * @param[in] num the number of pages to allocate.
1512 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
1513 * will always be satisfied by a single contiguous chunk of memory.
1514 * @return 0 on success, non-zero on failure.
1517 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
1519 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
1520 /* Get at most <Max_retries> more freeDB records once me_pghead
1521 * has enough pages. If not enough, use new pages from the map.
1522 * If <Paranoid> and mc is updating the freeDB, only get new
1523 * records if me_pghead is empty. Then the freelist cannot play
1524 * catch-up with itself by growing while trying to save it.
1526 enum { Paranoid = 1, Max_retries = 500 };
1528 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
1530 int rc, n2 = num-1, retry = Max_retries;
1531 MDB_txn *txn = mc->mc_txn;
1532 MDB_env *env = txn->mt_env;
1533 pgno_t pgno, *mop = env->me_pghead;
1534 unsigned i, j, k, mop_len = mop ? mop[0] : 0;
1536 txnid_t oldest = 0, last;
1542 /* If our dirty list is already full, we can't do anything */
1543 if (txn->mt_dirty_room == 0)
1544 return MDB_TXN_FULL;
1546 for (op = MDB_FIRST;; op = MDB_NEXT) {
1549 pgno_t *idl, old_id, new_id;
1551 /* Seek a big enough contiguous page range. Prefer
1552 * pages at the tail, just truncating the list.
1554 if (mop_len >= (unsigned)num) {
1558 if (mop[i-n2] == pgno+n2)
1560 } while (--i >= (unsigned)num);
1561 if (Max_retries < INT_MAX && --retry < 0)
1565 if (op == MDB_FIRST) { /* 1st iteration */
1566 /* Prepare to fetch more and coalesce */
1567 oldest = mdb_find_oldest(txn);
1568 last = env->me_pglast;
1569 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1572 key.mv_data = &last; /* will loop up last+1 */
1573 key.mv_size = sizeof(last);
1575 if (Paranoid && mc->mc_dbi == FREE_DBI)
1578 if (Paranoid && retry < 0 && mop_len)
1582 /* Do not fetch more if the record will be too recent */
1585 rc = mdb_cursor_get(&m2, &key, NULL, op);
1587 if (rc == MDB_NOTFOUND)
1591 last = *(txnid_t*)key.mv_data;
1594 np = m2.mc_pg[m2.mc_top];
1595 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
1596 if ((rc = mdb_node_read(txn, leaf, &data)) != MDB_SUCCESS)
1599 idl = (MDB_ID *) data.mv_data;
1602 if (!(env->me_pghead = mop = mdb_midl_alloc(i)))
1605 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
1607 mop = env->me_pghead;
1609 env->me_pglast = last;
1611 DPRINTF("IDL read txn %zu root %zu num %u",
1612 last, txn->mt_dbs[FREE_DBI].md_root, i);
1614 DPRINTF("IDL %zu", idl[k]);
1616 /* Merge in descending sorted order */
1619 mop[0] = (pgno_t)-1;
1623 for (; old_id < new_id; old_id = mop[--j])
1630 /* Use new pages from the map when nothing suitable in the freeDB */
1632 pgno = txn->mt_next_pgno;
1633 if (pgno + num >= env->me_maxpg) {
1634 DPUTS("DB size maxed out");
1635 return MDB_MAP_FULL;
1639 if (env->me_flags & MDB_WRITEMAP) {
1640 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
1642 if (!(np = mdb_page_malloc(txn, num)))
1646 mop[0] = mop_len -= num;
1647 /* Move any stragglers down */
1648 for (j = i-num; j < mop_len; )
1649 mop[++j] = mop[++i];
1651 txn->mt_next_pgno = pgno + num;
1654 mdb_page_dirty(txn, np);
1660 /** Copy the used portions of a non-overflow page.
1661 * @param[in] dst page to copy into
1662 * @param[in] src page to copy from
1663 * @param[in] psize size of a page
1666 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
1668 enum { Align = sizeof(pgno_t) };
1669 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
1671 /* If page isn't full, just copy the used portion. Adjust
1672 * alignment so memcpy may copy words instead of bytes.
1674 if ((unused &= -Align) && !IS_LEAF2(src)) {
1676 memcpy(dst, src, (lower + (Align-1)) & -Align);
1677 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
1680 memcpy(dst, src, psize - unused);
1684 /** Pull a page off the txn's spill list, if present.
1685 * If a page being referenced was spilled to disk in this txn, bring
1686 * it back and make it dirty/writable again.
1687 * @param[in] tx0 the transaction handle.
1688 * @param[in] mp the page being referenced.
1689 * @param[out] ret the writable page, if any. ret is unchanged if
1690 * mp wasn't spilled.
1693 mdb_page_unspill(MDB_txn *tx0, MDB_page *mp, MDB_page **ret)
1695 MDB_env *env = tx0->mt_env;
1698 pgno_t pgno = mp->mp_pgno;
1700 for (txn = tx0; txn; txn=txn->mt_parent) {
1701 if (!txn->mt_spill_pgs)
1703 x = mdb_midl_search(txn->mt_spill_pgs, pgno);
1704 if (x <= txn->mt_spill_pgs[0] && txn->mt_spill_pgs[x] == pgno) {
1707 if (IS_OVERFLOW(mp))
1711 if (env->me_flags & MDB_WRITEMAP) {
1714 np = mdb_page_malloc(txn, num);
1718 memcpy(np, mp, num * env->me_psize);
1720 mdb_page_copy(np, mp, env->me_psize);
1723 /* If in current txn, this page is no longer spilled */
1724 for (; x < txn->mt_spill_pgs[0]; x++)
1725 txn->mt_spill_pgs[x] = txn->mt_spill_pgs[x+1];
1726 txn->mt_spill_pgs[0]--;
1727 } /* otherwise, if belonging to a parent txn, the
1728 * page remains spilled until child commits
1730 mdb_page_dirty(tx0, np);
1731 np->mp_flags |= P_DIRTY;
1739 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1740 * @param[in] mc cursor pointing to the page to be touched
1741 * @return 0 on success, non-zero on failure.
1744 mdb_page_touch(MDB_cursor *mc)
1746 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
1747 MDB_txn *txn = mc->mc_txn;
1748 MDB_cursor *m2, *m3;
1753 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1754 if (txn->mt_flags & MDB_TXN_SPILLS) {
1756 rc = mdb_page_unspill(txn, mp, &np);
1762 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
1763 (rc = mdb_page_alloc(mc, 1, &np)))
1766 DPRINTF("touched db %u page %zu -> %zu", mc->mc_dbi,mp->mp_pgno,pgno);
1767 assert(mp->mp_pgno != pgno);
1768 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
1769 /* Update the parent page, if any, to point to the new page */
1771 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
1772 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
1773 SETPGNO(node, pgno);
1775 mc->mc_db->md_root = pgno;
1777 } else if (txn->mt_parent && !IS_SUBP(mp)) {
1778 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
1780 /* If txn has a parent, make sure the page is in our
1784 unsigned x = mdb_mid2l_search(dl, pgno);
1785 if (x <= dl[0].mid && dl[x].mid == pgno) {
1786 if (mp != dl[x].mptr) { /* bad cursor? */
1787 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1788 return MDB_CORRUPTED;
1793 assert(dl[0].mid < MDB_IDL_UM_MAX);
1795 np = mdb_page_malloc(txn, 1);
1800 mdb_mid2l_insert(dl, &mid);
1805 mdb_page_copy(np, mp, txn->mt_env->me_psize);
1807 np->mp_flags |= P_DIRTY;
1810 /* Adjust cursors pointing to mp */
1811 mc->mc_pg[mc->mc_top] = np;
1813 if (mc->mc_flags & C_SUB) {
1815 for (m2 = txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
1816 m3 = &m2->mc_xcursor->mx_cursor;
1817 if (m3->mc_snum < mc->mc_snum) continue;
1818 if (m3->mc_pg[mc->mc_top] == mp)
1819 m3->mc_pg[mc->mc_top] = np;
1822 for (m2 = txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
1823 if (m2->mc_snum < mc->mc_snum) continue;
1824 if (m2->mc_pg[mc->mc_top] == mp) {
1825 m2->mc_pg[mc->mc_top] = np;
1826 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
1827 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
1829 MDB_node *leaf = NODEPTR(np, mc->mc_ki[mc->mc_top]);
1830 if (!(leaf->mn_flags & F_SUBDATA))
1831 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
1840 mdb_env_sync(MDB_env *env, int force)
1843 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1844 if (env->me_flags & MDB_WRITEMAP) {
1845 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
1846 ? MS_ASYNC : MS_SYNC;
1847 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
1850 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
1854 if (MDB_FDATASYNC(env->me_fd))
1861 /** Back up parent txn's cursors, then grab the originals for tracking */
1863 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
1865 MDB_cursor *mc, *bk;
1870 for (i = src->mt_numdbs; --i >= 0; ) {
1871 if ((mc = src->mt_cursors[i]) != NULL) {
1872 size = sizeof(MDB_cursor);
1874 size += sizeof(MDB_xcursor);
1875 for (; mc; mc = bk->mc_next) {
1881 mc->mc_db = &dst->mt_dbs[i];
1882 /* Kill pointers into src - and dst to reduce abuse: The
1883 * user may not use mc until dst ends. Otherwise we'd...
1885 mc->mc_txn = NULL; /* ...set this to dst */
1886 mc->mc_dbflag = NULL; /* ...and &dst->mt_dbflags[i] */
1887 if ((mx = mc->mc_xcursor) != NULL) {
1888 *(MDB_xcursor *)(bk+1) = *mx;
1889 mx->mx_cursor.mc_txn = NULL; /* ...and dst. */
1891 mc->mc_next = dst->mt_cursors[i];
1892 dst->mt_cursors[i] = mc;
1899 /** Close this write txn's cursors, give parent txn's cursors back to parent.
1900 * @param[in] txn the transaction handle.
1901 * @param[in] merge true to keep changes to parent cursors, false to revert.
1902 * @return 0 on success, non-zero on failure.
1905 mdb_cursors_close(MDB_txn *txn, unsigned merge)
1907 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
1911 for (i = txn->mt_numdbs; --i >= 0; ) {
1912 for (mc = cursors[i]; mc; mc = next) {
1914 if ((bk = mc->mc_backup) != NULL) {
1916 /* Commit changes to parent txn */
1917 mc->mc_next = bk->mc_next;
1918 mc->mc_backup = bk->mc_backup;
1919 mc->mc_txn = bk->mc_txn;
1920 mc->mc_db = bk->mc_db;
1921 mc->mc_dbflag = bk->mc_dbflag;
1922 if ((mx = mc->mc_xcursor) != NULL)
1923 mx->mx_cursor.mc_txn = bk->mc_txn;
1925 /* Abort nested txn */
1927 if ((mx = mc->mc_xcursor) != NULL)
1928 *mx = *(MDB_xcursor *)(bk+1);
1938 #ifdef MDB_DEBUG_SKIP
1939 #define mdb_txn_reset0(txn, act) mdb_txn_reset0(txn)
1942 mdb_txn_reset0(MDB_txn *txn, const char *act);
1944 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
1945 * @param[in] txn the transaction handle to initialize
1946 * @return 0 on success, non-zero on failure.
1949 mdb_txn_renew0(MDB_txn *txn)
1951 MDB_env *env = txn->mt_env;
1954 int rc, new_notls = 0;
1957 txn->mt_numdbs = env->me_numdbs;
1958 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
1960 if (txn->mt_flags & MDB_TXN_RDONLY) {
1961 if (!env->me_txns) {
1962 i = mdb_env_pick_meta(env);
1963 txn->mt_txnid = env->me_metas[i]->mm_txnid;
1964 txn->mt_u.reader = NULL;
1966 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
1967 pthread_getspecific(env->me_txkey);
1969 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
1970 return MDB_BAD_RSLOT;
1972 pid_t pid = env->me_pid;
1973 pthread_t tid = pthread_self();
1976 for (i=0; i<env->me_txns->mti_numreaders; i++)
1977 if (env->me_txns->mti_readers[i].mr_pid == 0)
1979 if (i == env->me_maxreaders) {
1980 UNLOCK_MUTEX_R(env);
1981 return MDB_READERS_FULL;
1983 env->me_txns->mti_readers[i].mr_pid = pid;
1984 env->me_txns->mti_readers[i].mr_tid = tid;
1985 if (i >= env->me_txns->mti_numreaders)
1986 env->me_txns->mti_numreaders = i+1;
1987 /* Save numreaders for un-mutexed mdb_env_close() */
1988 env->me_numreaders = env->me_txns->mti_numreaders;
1989 UNLOCK_MUTEX_R(env);
1990 r = &env->me_txns->mti_readers[i];
1991 new_notls = (env->me_flags & MDB_NOTLS);
1992 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
1997 txn->mt_txnid = r->mr_txnid = env->me_txns->mti_txnid;
1998 txn->mt_u.reader = r;
2000 txn->mt_toggle = txn->mt_txnid & 1;
2004 txn->mt_txnid = env->me_txns->mti_txnid;
2005 txn->mt_toggle = txn->mt_txnid & 1;
2008 if (txn->mt_txnid == mdb_debug_start)
2011 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2012 txn->mt_u.dirty_list = env->me_dirty_list;
2013 txn->mt_u.dirty_list[0].mid = 0;
2014 txn->mt_free_pgs = env->me_free_pgs;
2015 txn->mt_free_pgs[0] = 0;
2016 txn->mt_spill_pgs = NULL;
2020 /* Copy the DB info and flags */
2021 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
2023 /* Moved to here to avoid a data race in read TXNs */
2024 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
2026 for (i=2; i<txn->mt_numdbs; i++) {
2027 x = env->me_dbflags[i];
2028 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2029 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_STALE : 0;
2031 txn->mt_dbflags[0] = txn->mt_dbflags[1] = DB_VALID;
2033 if (env->me_maxpg < txn->mt_next_pgno) {
2034 mdb_txn_reset0(txn, "renew0-mapfail");
2036 txn->mt_u.reader->mr_pid = 0;
2037 txn->mt_u.reader = NULL;
2039 return MDB_MAP_RESIZED;
2046 mdb_txn_renew(MDB_txn *txn)
2050 if (!txn || txn->mt_dbxs) /* A reset txn has mt_dbxs==NULL */
2053 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
2054 DPUTS("environment had fatal error, must shutdown!");
2058 rc = mdb_txn_renew0(txn);
2059 if (rc == MDB_SUCCESS) {
2060 DPRINTF("renew txn %zu%c %p on mdbenv %p, root page %zu",
2061 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2062 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
2068 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2072 int rc, size, tsize = sizeof(MDB_txn);
2074 if (env->me_flags & MDB_FATAL_ERROR) {
2075 DPUTS("environment had fatal error, must shutdown!");
2078 if ((env->me_flags & MDB_RDONLY) && !(flags & MDB_RDONLY))
2081 /* Nested transactions: Max 1 child, write txns only, no writemap */
2082 if (parent->mt_child ||
2083 (flags & MDB_RDONLY) || (parent->mt_flags & MDB_TXN_RDONLY) ||
2084 (env->me_flags & MDB_WRITEMAP))
2088 tsize = sizeof(MDB_ntxn);
2090 size = tsize + env->me_maxdbs * (sizeof(MDB_db)+1);
2091 if (!(flags & MDB_RDONLY))
2092 size += env->me_maxdbs * sizeof(MDB_cursor *);
2094 if ((txn = calloc(1, size)) == NULL) {
2095 DPRINTF("calloc: %s", strerror(ErrCode()));
2098 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2099 if (flags & MDB_RDONLY) {
2100 txn->mt_flags |= MDB_TXN_RDONLY;
2101 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
2103 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2104 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
2110 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2111 if (!txn->mt_u.dirty_list ||
2112 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2114 free(txn->mt_u.dirty_list);
2118 txn->mt_txnid = parent->mt_txnid;
2119 txn->mt_toggle = parent->mt_toggle;
2120 txn->mt_dirty_room = parent->mt_dirty_room;
2121 txn->mt_u.dirty_list[0].mid = 0;
2122 txn->mt_spill_pgs = NULL;
2123 txn->mt_next_pgno = parent->mt_next_pgno;
2124 parent->mt_child = txn;
2125 txn->mt_parent = parent;
2126 txn->mt_numdbs = parent->mt_numdbs;
2127 txn->mt_flags = parent->mt_flags;
2128 txn->mt_dbxs = parent->mt_dbxs;
2129 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2130 /* Copy parent's mt_dbflags, but clear DB_NEW */
2131 for (i=0; i<txn->mt_numdbs; i++)
2132 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2134 ntxn = (MDB_ntxn *)txn;
2135 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2136 if (env->me_pghead) {
2137 size = MDB_IDL_SIZEOF(env->me_pghead);
2138 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2140 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2145 rc = mdb_cursor_shadow(parent, txn);
2147 mdb_txn_reset0(txn, "beginchild-fail");
2149 rc = mdb_txn_renew0(txn);
2155 DPRINTF("begin txn %zu%c %p on mdbenv %p, root page %zu",
2156 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2157 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
2163 /** Export or close DBI handles opened in this txn. */
2165 mdb_dbis_update(MDB_txn *txn, int keep)
2168 MDB_dbi n = txn->mt_numdbs;
2169 MDB_env *env = txn->mt_env;
2170 unsigned char *tdbflags = txn->mt_dbflags;
2172 for (i = n; --i >= 2;) {
2173 if (tdbflags[i] & DB_NEW) {
2175 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2177 char *ptr = env->me_dbxs[i].md_name.mv_data;
2178 env->me_dbxs[i].md_name.mv_data = NULL;
2179 env->me_dbxs[i].md_name.mv_size = 0;
2180 env->me_dbflags[i] = 0;
2185 if (keep && env->me_numdbs < n)
2189 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
2190 * May be called twice for readonly txns: First reset it, then abort.
2191 * @param[in] txn the transaction handle to reset
2194 mdb_txn_reset0(MDB_txn *txn, const char *act)
2196 MDB_env *env = txn->mt_env;
2198 /* Close any DBI handles opened in this txn */
2199 mdb_dbis_update(txn, 0);
2201 DPRINTF("%s txn %zu%c %p on mdbenv %p, root page %zu",
2202 act, txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2203 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
2205 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2206 if (txn->mt_u.reader) {
2207 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2208 if (!(env->me_flags & MDB_NOTLS))
2209 txn->mt_u.reader = NULL; /* txn does not own reader */
2211 txn->mt_numdbs = 0; /* close nothing if called again */
2212 txn->mt_dbxs = NULL; /* mark txn as reset */
2214 mdb_cursors_close(txn, 0);
2216 if (!(env->me_flags & MDB_WRITEMAP)) {
2217 mdb_dlist_free(txn);
2219 mdb_midl_free(env->me_pghead);
2221 if (txn->mt_parent) {
2222 txn->mt_parent->mt_child = NULL;
2223 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2224 mdb_midl_free(txn->mt_free_pgs);
2225 mdb_midl_free(txn->mt_spill_pgs);
2226 free(txn->mt_u.dirty_list);
2230 if (mdb_midl_shrink(&txn->mt_free_pgs))
2231 env->me_free_pgs = txn->mt_free_pgs;
2232 env->me_pghead = NULL;
2236 /* The writer mutex was locked in mdb_txn_begin. */
2237 UNLOCK_MUTEX_W(env);
2242 mdb_txn_reset(MDB_txn *txn)
2247 /* This call is only valid for read-only txns */
2248 if (!(txn->mt_flags & MDB_TXN_RDONLY))
2251 mdb_txn_reset0(txn, "reset");
2255 mdb_txn_abort(MDB_txn *txn)
2261 mdb_txn_abort(txn->mt_child);
2263 mdb_txn_reset0(txn, "abort");
2264 /* Free reader slot tied to this txn (if MDB_NOTLS && writable FS) */
2265 if ((txn->mt_flags & MDB_TXN_RDONLY) && txn->mt_u.reader)
2266 txn->mt_u.reader->mr_pid = 0;
2271 /** Save the freelist as of this transaction to the freeDB.
2272 * This changes the freelist. Keep trying until it stabilizes.
2275 mdb_freelist_save(MDB_txn *txn)
2277 /* env->me_pghead[] can grow and shrink during this call.
2278 * env->me_pglast and txn->mt_free_pgs[] can only grow.
2279 * Page numbers cannot disappear from txn->mt_free_pgs[].
2282 MDB_env *env = txn->mt_env;
2283 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
2284 txnid_t pglast = 0, head_id = 0;
2285 pgno_t freecnt = 0, *free_pgs, *mop;
2286 ssize_t head_room = 0, total_room = 0, mop_len;
2288 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
2290 if (env->me_pghead) {
2291 /* Make sure first page of freeDB is touched and on freelist */
2292 rc = mdb_page_search(&mc, NULL, MDB_PS_MODIFY);
2293 if (rc && rc != MDB_NOTFOUND)
2298 /* Come back here after each Put() in case freelist changed */
2301 /* If using records from freeDB which we have not yet
2302 * deleted, delete them and any we reserved for me_pghead.
2304 while (pglast < env->me_pglast) {
2305 rc = mdb_cursor_first(&mc, &key, NULL);
2308 pglast = head_id = *(txnid_t *)key.mv_data;
2309 total_room = head_room = 0;
2310 assert(pglast <= env->me_pglast);
2311 rc = mdb_cursor_del(&mc, 0);
2316 /* Save the IDL of pages freed by this txn, to a single record */
2317 if (freecnt < txn->mt_free_pgs[0]) {
2319 /* Make sure last page of freeDB is touched and on freelist */
2320 key.mv_size = MDB_MAXKEYSIZE+1;
2322 rc = mdb_page_search(&mc, &key, MDB_PS_MODIFY);
2323 if (rc && rc != MDB_NOTFOUND)
2326 free_pgs = txn->mt_free_pgs;
2327 /* Write to last page of freeDB */
2328 key.mv_size = sizeof(txn->mt_txnid);
2329 key.mv_data = &txn->mt_txnid;
2331 freecnt = free_pgs[0];
2332 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
2333 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2336 /* Retry if mt_free_pgs[] grew during the Put() */
2337 free_pgs = txn->mt_free_pgs;
2338 } while (freecnt < free_pgs[0]);
2339 mdb_midl_sort(free_pgs);
2340 memcpy(data.mv_data, free_pgs, data.mv_size);
2343 unsigned int i = free_pgs[0];
2344 DPRINTF("IDL write txn %zu root %zu num %u",
2345 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i);
2347 DPRINTF("IDL %zu", free_pgs[i]);
2353 mop = env->me_pghead;
2354 mop_len = mop ? mop[0] : 0;
2356 /* Reserve records for me_pghead[]. Split it if multi-page,
2357 * to avoid searching freeDB for a page range. Use keys in
2358 * range [1,me_pglast]: Smaller than txnid of oldest reader.
2360 if (total_room >= mop_len) {
2361 if (total_room == mop_len || --more < 0)
2363 } else if (head_room >= maxfree_1pg && head_id > 1) {
2364 /* Keep current record (overflow page), add a new one */
2368 /* (Re)write {key = head_id, IDL length = head_room} */
2369 total_room -= head_room;
2370 head_room = mop_len - total_room;
2371 if (head_room > maxfree_1pg && head_id > 1) {
2372 /* Overflow multi-page for part of me_pghead */
2373 head_room /= head_id; /* amortize page sizes */
2374 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
2375 } else if (head_room < 0) {
2376 /* Rare case, not bothering to delete this record */
2379 key.mv_size = sizeof(head_id);
2380 key.mv_data = &head_id;
2381 data.mv_size = (head_room + 1) * sizeof(pgno_t);
2382 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2385 *(MDB_ID *)data.mv_data = 0; /* IDL is initially empty */
2386 total_room += head_room;
2389 /* Fill in the reserved, touched me_pghead records */
2395 rc = mdb_cursor_first(&mc, &key, &data);
2396 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
2397 unsigned flags = MDB_CURRENT;
2398 txnid_t id = *(txnid_t *)key.mv_data;
2399 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
2402 assert(len >= 0 && id <= env->me_pglast);
2404 if (len > mop_len) {
2406 data.mv_size = (len + 1) * sizeof(MDB_ID);
2409 data.mv_data = mop -= len;
2412 rc = mdb_cursor_put(&mc, &key, &data, flags);
2414 if (rc || !(mop_len -= len))
2421 /** Flush dirty pages to the map, after clearing their dirty flag.
2424 mdb_page_flush(MDB_txn *txn)
2426 MDB_env *env = txn->mt_env;
2427 MDB_ID2L dl = txn->mt_u.dirty_list;
2428 unsigned psize = env->me_psize, j;
2429 int i, pagecount = dl[0].mid, rc;
2430 size_t size = 0, pos = 0;
2432 MDB_page *dp = NULL;
2436 struct iovec iov[MDB_COMMIT_PAGES];
2437 ssize_t wpos = 0, wsize = 0, wres;
2438 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
2443 if (env->me_flags & MDB_WRITEMAP) {
2444 /* Clear dirty flags */
2445 for (i = pagecount; i; i--) {
2447 /* Don't flush this page yet */
2448 if (dp->mp_flags & P_KEEP) {
2449 dp->mp_flags ^= P_KEEP;
2453 dp->mp_flags &= ~P_DIRTY;
2459 /* Write the pages */
2461 if (i <= pagecount) {
2463 /* Don't flush this page yet */
2464 if (dp->mp_flags & P_KEEP) {
2465 dp->mp_flags ^= P_KEEP;
2470 /* clear dirty flag */
2471 dp->mp_flags &= ~P_DIRTY;
2474 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
2479 /* Windows actually supports scatter/gather I/O, but only on
2480 * unbuffered file handles. Since we're relying on the OS page
2481 * cache for all our data, that's self-defeating. So we just
2482 * write pages one at a time. We use the ov structure to set
2483 * the write offset, to at least save the overhead of a Seek
2486 DPRINTF("committing page %zu", pgno);
2487 memset(&ov, 0, sizeof(ov));
2488 ov.Offset = pos & 0xffffffff;
2489 ov.OffsetHigh = pos >> 16 >> 16;
2490 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
2492 DPRINTF("WriteFile: %d", rc);
2496 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
2497 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
2499 /* Write previous page(s) */
2500 #ifdef MDB_USE_PWRITEV
2501 wres = pwritev(env->me_fd, iov, n, wpos);
2504 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
2506 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
2508 DPRINTF("lseek: %s", strerror(rc));
2511 wres = writev(env->me_fd, iov, n);
2514 if (wres != wsize) {
2517 DPRINTF("Write error: %s", strerror(rc));
2519 rc = EIO; /* TODO: Use which error code? */
2520 DPUTS("short write, filesystem full?");
2531 DPRINTF("committing page %zu", pgno);
2532 next_pos = pos + size;
2533 iov[n].iov_len = size;
2534 iov[n].iov_base = (char *)dp;
2541 for (i=1; i<=pagecount; i++) {
2543 /* This is a page we skipped above */
2546 dl[j].mid = dp->mp_pgno;
2549 mdb_dpage_free(env, dp);
2557 mdb_txn_commit(MDB_txn *txn)
2563 assert(txn != NULL);
2564 assert(txn->mt_env != NULL);
2566 if (txn->mt_child) {
2567 rc = mdb_txn_commit(txn->mt_child);
2568 txn->mt_child = NULL;
2575 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2576 mdb_dbis_update(txn, 1);
2577 txn->mt_numdbs = 2; /* so txn_abort() doesn't close any new handles */
2582 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
2583 DPUTS("error flag is set, can't commit");
2585 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
2590 if (txn->mt_parent) {
2591 MDB_txn *parent = txn->mt_parent;
2595 /* Append our free list to parent's */
2596 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
2599 mdb_midl_free(txn->mt_free_pgs);
2601 parent->mt_next_pgno = txn->mt_next_pgno;
2602 parent->mt_flags = txn->mt_flags;
2604 /* Merge our cursors into parent's and close them */
2605 mdb_cursors_close(txn, 1);
2607 /* Update parent's DB table. */
2608 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2609 parent->mt_numdbs = txn->mt_numdbs;
2610 parent->mt_dbflags[0] = txn->mt_dbflags[0];
2611 parent->mt_dbflags[1] = txn->mt_dbflags[1];
2612 for (i=2; i<txn->mt_numdbs; i++) {
2613 /* preserve parent's DB_NEW status */
2614 x = parent->mt_dbflags[i] & DB_NEW;
2615 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
2618 dst = parent->mt_u.dirty_list;
2619 src = txn->mt_u.dirty_list;
2620 /* Remove anything in our dirty list from parent's spill list */
2621 if (parent->mt_spill_pgs) {
2622 x = parent->mt_spill_pgs[0];
2624 /* zero out our dirty pages in parent spill list */
2625 for (i=1; i<=src[0].mid; i++) {
2626 if (src[i].mid < parent->mt_spill_pgs[x])
2628 if (src[i].mid > parent->mt_spill_pgs[x]) {
2634 parent->mt_spill_pgs[x] = 0;
2637 /* OK, we had a few hits, squash zeros from the spill list */
2638 if (len < parent->mt_spill_pgs[0]) {
2640 for (y=1; y<=parent->mt_spill_pgs[0]; y++) {
2641 if (parent->mt_spill_pgs[y]) {
2643 parent->mt_spill_pgs[x] = parent->mt_spill_pgs[y];
2648 parent->mt_spill_pgs[0] = len;
2651 /* Find len = length of merging our dirty list with parent's */
2653 dst[0].mid = 0; /* simplify loops */
2654 if (parent->mt_parent) {
2655 len = x + src[0].mid;
2656 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
2657 for (i = x; y && i; y--) {
2658 pgno_t yp = src[y].mid;
2659 while (yp < dst[i].mid)
2661 if (yp == dst[i].mid) {
2666 } else { /* Simplify the above for single-ancestor case */
2667 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
2669 /* Merge our dirty list with parent's */
2671 for (i = len; y; dst[i--] = src[y--]) {
2672 pgno_t yp = src[y].mid;
2673 while (yp < dst[x].mid)
2674 dst[i--] = dst[x--];
2675 if (yp == dst[x].mid)
2676 free(dst[x--].mptr);
2680 free(txn->mt_u.dirty_list);
2681 parent->mt_dirty_room = txn->mt_dirty_room;
2682 if (txn->mt_spill_pgs) {
2683 if (parent->mt_spill_pgs) {
2684 mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
2685 mdb_midl_free(txn->mt_spill_pgs);
2686 mdb_midl_sort(parent->mt_spill_pgs);
2688 parent->mt_spill_pgs = txn->mt_spill_pgs;
2692 parent->mt_child = NULL;
2693 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
2698 if (txn != env->me_txn) {
2699 DPUTS("attempt to commit unknown transaction");
2704 mdb_cursors_close(txn, 0);
2706 if (!txn->mt_u.dirty_list[0].mid && !(txn->mt_flags & MDB_TXN_DIRTY))
2709 DPRINTF("committing txn %zu %p on mdbenv %p, root page %zu",
2710 txn->mt_txnid, (void *)txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
2712 /* Update DB root pointers */
2713 if (txn->mt_numdbs > 2) {
2717 data.mv_size = sizeof(MDB_db);
2719 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
2720 for (i = 2; i < txn->mt_numdbs; i++) {
2721 if (txn->mt_dbflags[i] & DB_DIRTY) {
2722 data.mv_data = &txn->mt_dbs[i];
2723 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
2730 rc = mdb_freelist_save(txn);
2734 mdb_midl_free(env->me_pghead);
2735 env->me_pghead = NULL;
2736 if (mdb_midl_shrink(&txn->mt_free_pgs))
2737 env->me_free_pgs = txn->mt_free_pgs;
2743 if ((rc = mdb_page_flush(txn)) ||
2744 (rc = mdb_env_sync(env, 0)) ||
2745 (rc = mdb_env_write_meta(txn)))
2751 mdb_dbis_update(txn, 1);
2753 UNLOCK_MUTEX_W(env);
2763 /** Read the environment parameters of a DB environment before
2764 * mapping it into memory.
2765 * @param[in] env the environment handle
2766 * @param[out] meta address of where to store the meta information
2767 * @return 0 on success, non-zero on failure.
2770 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
2777 /* We don't know the page size yet, so use a minimum value.
2778 * Read both meta pages so we can use the latest one.
2781 for (i=off=0; i<2; i++, off = meta->mm_psize) {
2785 memset(&ov, 0, sizeof(ov));
2787 rc = ReadFile(env->me_fd,&pbuf,MDB_PAGESIZE,&len,&ov) ? (int)len : -1;
2788 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
2791 rc = pread(env->me_fd, &pbuf, MDB_PAGESIZE, off);
2793 if (rc != MDB_PAGESIZE) {
2794 if (rc == 0 && off == 0)
2796 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
2797 DPRINTF("read: %s", mdb_strerror(rc));
2801 p = (MDB_page *)&pbuf;
2803 if (!F_ISSET(p->mp_flags, P_META)) {
2804 DPRINTF("page %zu not a meta page", p->mp_pgno);
2809 if (m->mm_magic != MDB_MAGIC) {
2810 DPUTS("meta has invalid magic");
2814 if (m->mm_version != MDB_VERSION) {
2815 DPRINTF("database is version %u, expected version %u",
2816 m->mm_version, MDB_VERSION);
2817 return MDB_VERSION_MISMATCH;
2820 if (off == 0 || m->mm_txnid > meta->mm_txnid)
2826 /** Write the environment parameters of a freshly created DB environment.
2827 * @param[in] env the environment handle
2828 * @param[out] meta address of where to store the meta information
2829 * @return 0 on success, non-zero on failure.
2832 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
2838 DPUTS("writing new meta page");
2840 GET_PAGESIZE(psize);
2842 meta->mm_magic = MDB_MAGIC;
2843 meta->mm_version = MDB_VERSION;
2844 meta->mm_mapsize = env->me_mapsize;
2845 meta->mm_psize = psize;
2846 meta->mm_last_pg = 1;
2847 meta->mm_flags = env->me_flags & 0xffff;
2848 meta->mm_flags |= MDB_INTEGERKEY;
2849 meta->mm_dbs[0].md_root = P_INVALID;
2850 meta->mm_dbs[1].md_root = P_INVALID;
2852 p = calloc(2, psize);
2854 p->mp_flags = P_META;
2855 *(MDB_meta *)METADATA(p) = *meta;
2857 q = (MDB_page *)((char *)p + psize);
2859 q->mp_flags = P_META;
2860 *(MDB_meta *)METADATA(q) = *meta;
2866 memset(&ov, 0, sizeof(ov));
2867 rc = WriteFile(env->me_fd, p, psize * 2, &len, &ov);
2868 rc = rc ? (len == psize * 2 ? MDB_SUCCESS : EIO) : ErrCode();
2871 rc = pwrite(env->me_fd, p, psize * 2, 0);
2872 rc = (rc == (int)psize * 2) ? MDB_SUCCESS : rc < 0 ? ErrCode() : EIO;
2878 /** Update the environment info to commit a transaction.
2879 * @param[in] txn the transaction that's being committed
2880 * @return 0 on success, non-zero on failure.
2883 mdb_env_write_meta(MDB_txn *txn)
2886 MDB_meta meta, metab, *mp;
2888 int rc, len, toggle;
2897 assert(txn != NULL);
2898 assert(txn->mt_env != NULL);
2900 toggle = !txn->mt_toggle;
2901 DPRINTF("writing meta page %d for root page %zu",
2902 toggle, txn->mt_dbs[MAIN_DBI].md_root);
2905 mp = env->me_metas[toggle];
2907 if (env->me_flags & MDB_WRITEMAP) {
2908 /* Persist any increases of mapsize config */
2909 if (env->me_mapsize > mp->mm_mapsize)
2910 mp->mm_mapsize = env->me_mapsize;
2911 mp->mm_dbs[0] = txn->mt_dbs[0];
2912 mp->mm_dbs[1] = txn->mt_dbs[1];
2913 mp->mm_last_pg = txn->mt_next_pgno - 1;
2914 mp->mm_txnid = txn->mt_txnid;
2915 if (!(env->me_flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
2916 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
2919 ptr += env->me_psize;
2920 if (MDB_MSYNC(ptr, env->me_psize, rc)) {
2927 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
2928 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
2930 ptr = (char *)&meta;
2931 if (env->me_mapsize > mp->mm_mapsize) {
2932 /* Persist any increases of mapsize config */
2933 meta.mm_mapsize = env->me_mapsize;
2934 off = offsetof(MDB_meta, mm_mapsize);
2936 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
2938 len = sizeof(MDB_meta) - off;
2941 meta.mm_dbs[0] = txn->mt_dbs[0];
2942 meta.mm_dbs[1] = txn->mt_dbs[1];
2943 meta.mm_last_pg = txn->mt_next_pgno - 1;
2944 meta.mm_txnid = txn->mt_txnid;
2947 off += env->me_psize;
2950 /* Write to the SYNC fd */
2951 mfd = env->me_flags & (MDB_NOSYNC|MDB_NOMETASYNC) ?
2952 env->me_fd : env->me_mfd;
2955 memset(&ov, 0, sizeof(ov));
2957 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
2961 rc = pwrite(mfd, ptr, len, off);
2964 rc = rc < 0 ? ErrCode() : EIO;
2965 DPUTS("write failed, disk error?");
2966 /* On a failure, the pagecache still contains the new data.
2967 * Write some old data back, to prevent it from being used.
2968 * Use the non-SYNC fd; we know it will fail anyway.
2970 meta.mm_last_pg = metab.mm_last_pg;
2971 meta.mm_txnid = metab.mm_txnid;
2973 memset(&ov, 0, sizeof(ov));
2975 WriteFile(env->me_fd, ptr, len, NULL, &ov);
2977 r2 = pwrite(env->me_fd, ptr, len, off);
2980 env->me_flags |= MDB_FATAL_ERROR;
2984 /* Memory ordering issues are irrelevant; since the entire writer
2985 * is wrapped by wmutex, all of these changes will become visible
2986 * after the wmutex is unlocked. Since the DB is multi-version,
2987 * readers will get consistent data regardless of how fresh or
2988 * how stale their view of these values is.
2990 env->me_txns->mti_txnid = txn->mt_txnid;
2995 /** Check both meta pages to see which one is newer.
2996 * @param[in] env the environment handle
2997 * @return meta toggle (0 or 1).
3000 mdb_env_pick_meta(const MDB_env *env)
3002 return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
3006 mdb_env_create(MDB_env **env)
3010 e = calloc(1, sizeof(MDB_env));
3014 e->me_maxreaders = DEFAULT_READERS;
3015 e->me_maxdbs = e->me_numdbs = 2;
3016 e->me_fd = INVALID_HANDLE_VALUE;
3017 e->me_lfd = INVALID_HANDLE_VALUE;
3018 e->me_mfd = INVALID_HANDLE_VALUE;
3019 #ifdef MDB_USE_POSIX_SEM
3020 e->me_rmutex = SEM_FAILED;
3021 e->me_wmutex = SEM_FAILED;
3023 e->me_pid = getpid();
3024 VGMEMP_CREATE(e,0,0);
3030 mdb_env_set_mapsize(MDB_env *env, size_t size)
3034 env->me_mapsize = size;
3036 env->me_maxpg = env->me_mapsize / env->me_psize;
3041 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
3045 env->me_maxdbs = dbs + 2; /* Named databases + main and free DB */
3050 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
3052 if (env->me_map || readers < 1)
3054 env->me_maxreaders = readers;
3059 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
3061 if (!env || !readers)
3063 *readers = env->me_maxreaders;
3067 /** Further setup required for opening an MDB environment
3070 mdb_env_open2(MDB_env *env)
3072 unsigned int flags = env->me_flags;
3080 memset(&meta, 0, sizeof(meta));
3082 if ((i = mdb_env_read_header(env, &meta)) != 0) {
3085 DPUTS("new mdbenv");
3089 /* Was a mapsize configured? */
3090 if (!env->me_mapsize) {
3091 /* If this is a new environment, take the default,
3092 * else use the size recorded in the existing env.
3094 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
3095 } else if (env->me_mapsize < meta.mm_mapsize) {
3096 /* If the configured size is smaller, make sure it's
3097 * still big enough. Silently round up to minimum if not.
3099 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
3100 if (env->me_mapsize < minsize)
3101 env->me_mapsize = minsize;
3108 LONG sizelo, sizehi;
3109 sizelo = env->me_mapsize & 0xffffffff;
3110 sizehi = env->me_mapsize >> 16 >> 16; /* only needed on Win64 */
3111 /* Windows won't create mappings for zero length files.
3112 * Just allocate the maxsize right now.
3115 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3116 || !SetEndOfFile(env->me_fd)
3117 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3120 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3121 PAGE_READWRITE : PAGE_READONLY,
3122 sizehi, sizelo, NULL);
3125 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3126 FILE_MAP_WRITE : FILE_MAP_READ,
3127 0, 0, env->me_mapsize, meta.mm_address);
3128 rc = env->me_map ? 0 : ErrCode();
3136 if (flags & MDB_WRITEMAP) {
3138 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3141 env->me_map = mmap(meta.mm_address, env->me_mapsize, prot, i,
3143 if (env->me_map == MAP_FAILED) {
3147 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3149 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3151 #ifdef POSIX_MADV_RANDOM
3152 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3153 #endif /* POSIX_MADV_RANDOM */
3154 #endif /* MADV_RANDOM */
3158 if (flags & MDB_FIXEDMAP)
3159 meta.mm_address = env->me_map;
3160 i = mdb_env_init_meta(env, &meta);
3161 if (i != MDB_SUCCESS) {
3164 } else if (meta.mm_address && env->me_map != meta.mm_address) {
3165 /* Can happen because the address argument to mmap() is just a
3166 * hint. mmap() can pick another, e.g. if the range is in use.
3167 * The MAP_FIXED flag would prevent that, but then mmap could
3168 * instead unmap existing pages to make room for the new map.
3170 return EBUSY; /* TODO: Make a new MDB_* error code? */
3172 env->me_psize = meta.mm_psize;
3173 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
3174 env->me_nodemax = (env->me_psize - PAGEHDRSZ) / MDB_MINKEYS;
3176 env->me_maxpg = env->me_mapsize / env->me_psize;
3178 p = (MDB_page *)env->me_map;
3179 env->me_metas[0] = METADATA(p);
3180 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
3184 int toggle = mdb_env_pick_meta(env);
3185 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
3187 DPRINTF("opened database version %u, pagesize %u",
3188 env->me_metas[0]->mm_version, env->me_psize);
3189 DPRINTF("using meta page %d", toggle);
3190 DPRINTF("depth: %u", db->md_depth);
3191 DPRINTF("entries: %zu", db->md_entries);
3192 DPRINTF("branch pages: %zu", db->md_branch_pages);
3193 DPRINTF("leaf pages: %zu", db->md_leaf_pages);
3194 DPRINTF("overflow pages: %zu", db->md_overflow_pages);
3195 DPRINTF("root: %zu", db->md_root);
3203 /** Release a reader thread's slot in the reader lock table.
3204 * This function is called automatically when a thread exits.
3205 * @param[in] ptr This points to the slot in the reader lock table.
3208 mdb_env_reader_dest(void *ptr)
3210 MDB_reader *reader = ptr;
3216 /** Junk for arranging thread-specific callbacks on Windows. This is
3217 * necessarily platform and compiler-specific. Windows supports up
3218 * to 1088 keys. Let's assume nobody opens more than 64 environments
3219 * in a single process, for now. They can override this if needed.
3221 #ifndef MAX_TLS_KEYS
3222 #define MAX_TLS_KEYS 64
3224 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
3225 static int mdb_tls_nkeys;
3227 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
3231 case DLL_PROCESS_ATTACH: break;
3232 case DLL_THREAD_ATTACH: break;
3233 case DLL_THREAD_DETACH:
3234 for (i=0; i<mdb_tls_nkeys; i++) {
3235 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
3236 mdb_env_reader_dest(r);
3239 case DLL_PROCESS_DETACH: break;
3244 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3246 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3250 /* Force some symbol references.
3251 * _tls_used forces the linker to create the TLS directory if not already done
3252 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
3254 #pragma comment(linker, "/INCLUDE:_tls_used")
3255 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
3256 #pragma const_seg(".CRT$XLB")
3257 extern const PIMAGE_TLS_CALLBACK mdb_tls_callback;
3258 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3261 #pragma comment(linker, "/INCLUDE:__tls_used")
3262 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
3263 #pragma data_seg(".CRT$XLB")
3264 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3266 #endif /* WIN 32/64 */
3267 #endif /* !__GNUC__ */
3270 /** Downgrade the exclusive lock on the region back to shared */
3272 mdb_env_share_locks(MDB_env *env, int *excl)
3274 int rc = 0, toggle = mdb_env_pick_meta(env);
3276 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
3281 /* First acquire a shared lock. The Unlock will
3282 * then release the existing exclusive lock.
3284 memset(&ov, 0, sizeof(ov));
3285 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3288 UnlockFile(env->me_lfd, 0, 0, 1, 0);
3294 struct flock lock_info;
3295 /* The shared lock replaces the existing lock */
3296 memset((void *)&lock_info, 0, sizeof(lock_info));
3297 lock_info.l_type = F_RDLCK;
3298 lock_info.l_whence = SEEK_SET;
3299 lock_info.l_start = 0;
3300 lock_info.l_len = 1;
3301 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3302 (rc = ErrCode()) == EINTR) ;
3303 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
3310 /** Try to get exlusive lock, otherwise shared.
3311 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
3314 mdb_env_excl_lock(MDB_env *env, int *excl)
3318 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
3322 memset(&ov, 0, sizeof(ov));
3323 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3330 struct flock lock_info;
3331 memset((void *)&lock_info, 0, sizeof(lock_info));
3332 lock_info.l_type = F_WRLCK;
3333 lock_info.l_whence = SEEK_SET;
3334 lock_info.l_start = 0;
3335 lock_info.l_len = 1;
3336 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3337 (rc = ErrCode()) == EINTR) ;
3341 # ifdef MDB_USE_POSIX_SEM
3342 if (*excl < 0) /* always true when !MDB_USE_POSIX_SEM */
3345 lock_info.l_type = F_RDLCK;
3346 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
3347 (rc = ErrCode()) == EINTR) ;
3355 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
3357 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
3359 * @(#) $Revision: 5.1 $
3360 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
3361 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
3363 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
3367 * Please do not copyright this code. This code is in the public domain.
3369 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
3370 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
3371 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
3372 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
3373 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
3374 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
3375 * PERFORMANCE OF THIS SOFTWARE.
3378 * chongo <Landon Curt Noll> /\oo/\
3379 * http://www.isthe.com/chongo/
3381 * Share and Enjoy! :-)
3384 typedef unsigned long long mdb_hash_t;
3385 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
3387 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
3388 * @param[in] str string to hash
3389 * @param[in] hval initial value for hash
3390 * @return 64 bit hash
3392 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
3393 * hval arg on the first call.
3396 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
3398 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
3399 unsigned char *end = s + val->mv_size;
3401 * FNV-1a hash each octet of the string
3404 /* xor the bottom with the current octet */
3405 hval ^= (mdb_hash_t)*s++;
3407 /* multiply by the 64 bit FNV magic prime mod 2^64 */
3408 hval += (hval << 1) + (hval << 4) + (hval << 5) +
3409 (hval << 7) + (hval << 8) + (hval << 40);
3411 /* return our new hash value */
3415 /** Hash the string and output the hash in hex.
3416 * @param[in] str string to hash
3417 * @param[out] hexbuf an array of 17 chars to hold the hash
3420 mdb_hash_hex(MDB_val *val, char *hexbuf)
3423 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
3424 for (i=0; i<8; i++) {
3425 hexbuf += sprintf(hexbuf, "%02x", (unsigned int)h & 0xff);
3431 /** Open and/or initialize the lock region for the environment.
3432 * @param[in] env The MDB environment.
3433 * @param[in] lpath The pathname of the file used for the lock region.
3434 * @param[in] mode The Unix permissions for the file, if we create it.
3435 * @param[out] excl Resulting file lock type: -1 none, 0 shared, 1 exclusive
3436 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
3437 * @return 0 on success, non-zero on failure.
3440 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
3443 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
3445 # define MDB_ERRCODE_ROFS EROFS
3446 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
3447 # define MDB_CLOEXEC O_CLOEXEC
3450 # define MDB_CLOEXEC 0
3457 env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
3458 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
3459 FILE_ATTRIBUTE_NORMAL, NULL);
3461 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
3463 if (env->me_lfd == INVALID_HANDLE_VALUE) {
3465 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
3470 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
3471 /* Lose record locks when exec*() */
3472 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
3473 fcntl(env->me_lfd, F_SETFD, fdflags);
3476 if (!(env->me_flags & MDB_NOTLS)) {
3477 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
3480 env->me_flags |= MDB_ENV_TXKEY;
3482 /* Windows TLS callbacks need help finding their TLS info. */
3483 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
3487 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
3491 /* Try to get exclusive lock. If we succeed, then
3492 * nobody is using the lock region and we should initialize it.
3494 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
3497 size = GetFileSize(env->me_lfd, NULL);
3499 size = lseek(env->me_lfd, 0, SEEK_END);
3500 if (size == -1) goto fail_errno;
3502 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
3503 if (size < rsize && *excl > 0) {
3505 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != rsize
3506 || !SetEndOfFile(env->me_lfd))
3509 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
3513 size = rsize - sizeof(MDB_txninfo);
3514 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
3519 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
3521 if (!mh) goto fail_errno;
3522 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
3524 if (!env->me_txns) goto fail_errno;
3526 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
3528 if (m == MAP_FAILED) goto fail_errno;
3534 BY_HANDLE_FILE_INFORMATION stbuf;
3543 if (!mdb_sec_inited) {
3544 InitializeSecurityDescriptor(&mdb_null_sd,
3545 SECURITY_DESCRIPTOR_REVISION);
3546 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
3547 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
3548 mdb_all_sa.bInheritHandle = FALSE;
3549 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
3552 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
3553 idbuf.volume = stbuf.dwVolumeSerialNumber;
3554 idbuf.nhigh = stbuf.nFileIndexHigh;
3555 idbuf.nlow = stbuf.nFileIndexLow;
3556 val.mv_data = &idbuf;
3557 val.mv_size = sizeof(idbuf);
3558 mdb_hash_hex(&val, hexbuf);
3559 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", hexbuf);
3560 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", hexbuf);
3561 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
3562 if (!env->me_rmutex) goto fail_errno;
3563 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
3564 if (!env->me_wmutex) goto fail_errno;
3565 #elif defined(MDB_USE_POSIX_SEM)
3574 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
3575 idbuf.dev = stbuf.st_dev;
3576 idbuf.ino = stbuf.st_ino;
3577 val.mv_data = &idbuf;
3578 val.mv_size = sizeof(idbuf);
3579 mdb_hash_hex(&val, hexbuf);
3580 sprintf(env->me_txns->mti_rmname, "/MDBr%s", hexbuf);
3581 sprintf(env->me_txns->mti_wmname, "/MDBw%s", hexbuf);
3582 /* Clean up after a previous run, if needed: Try to
3583 * remove both semaphores before doing anything else.
3585 sem_unlink(env->me_txns->mti_rmname);
3586 sem_unlink(env->me_txns->mti_wmname);
3587 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
3588 O_CREAT|O_EXCL, mode, 1);
3589 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3590 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
3591 O_CREAT|O_EXCL, mode, 1);
3592 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3593 #else /* MDB_USE_POSIX_SEM */
3594 pthread_mutexattr_t mattr;
3596 if ((rc = pthread_mutexattr_init(&mattr))
3597 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
3598 || (rc = pthread_mutex_init(&env->me_txns->mti_mutex, &mattr))
3599 || (rc = pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr)))
3601 pthread_mutexattr_destroy(&mattr);
3602 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
3604 env->me_txns->mti_version = MDB_VERSION;
3605 env->me_txns->mti_magic = MDB_MAGIC;
3606 env->me_txns->mti_txnid = 0;
3607 env->me_txns->mti_numreaders = 0;
3610 if (env->me_txns->mti_magic != MDB_MAGIC) {
3611 DPUTS("lock region has invalid magic");
3615 if (env->me_txns->mti_version != MDB_VERSION) {
3616 DPRINTF("lock region is version %u, expected version %u",
3617 env->me_txns->mti_version, MDB_VERSION);
3618 rc = MDB_VERSION_MISMATCH;
3622 if (rc && rc != EACCES && rc != EAGAIN) {
3626 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
3627 if (!env->me_rmutex) goto fail_errno;
3628 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
3629 if (!env->me_wmutex) goto fail_errno;
3630 #elif defined(MDB_USE_POSIX_SEM)
3631 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
3632 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3633 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
3634 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3645 /** The name of the lock file in the DB environment */
3646 #define LOCKNAME "/lock.mdb"
3647 /** The name of the data file in the DB environment */
3648 #define DATANAME "/data.mdb"
3649 /** The suffix of the lock file when no subdir is used */
3650 #define LOCKSUFF "-lock"
3651 /** Only a subset of the @ref mdb_env flags can be changed
3652 * at runtime. Changing other flags requires closing the
3653 * environment and re-opening it with the new flags.
3655 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC)
3656 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY|MDB_WRITEMAP|MDB_NOTLS)
3659 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
3661 int oflags, rc, len, excl = -1;
3662 char *lpath, *dpath;
3664 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
3668 if (flags & MDB_NOSUBDIR) {
3669 rc = len + sizeof(LOCKSUFF) + len + 1;
3671 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
3676 if (flags & MDB_NOSUBDIR) {
3677 dpath = lpath + len + sizeof(LOCKSUFF);
3678 sprintf(lpath, "%s" LOCKSUFF, path);
3679 strcpy(dpath, path);
3681 dpath = lpath + len + sizeof(LOCKNAME);
3682 sprintf(lpath, "%s" LOCKNAME, path);
3683 sprintf(dpath, "%s" DATANAME, path);
3687 flags |= env->me_flags;
3688 if (flags & MDB_RDONLY) {
3689 /* silently ignore WRITEMAP when we're only getting read access */
3690 flags &= ~MDB_WRITEMAP;
3692 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
3693 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
3696 env->me_flags = flags |= MDB_ENV_ACTIVE;
3700 env->me_path = strdup(path);
3701 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
3702 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
3703 if (!(env->me_dbxs && env->me_path && env->me_dbflags)) {
3708 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
3713 if (F_ISSET(flags, MDB_RDONLY)) {
3714 oflags = GENERIC_READ;
3715 len = OPEN_EXISTING;
3717 oflags = GENERIC_READ|GENERIC_WRITE;
3720 mode = FILE_ATTRIBUTE_NORMAL;
3721 env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
3722 NULL, len, mode, NULL);
3724 if (F_ISSET(flags, MDB_RDONLY))
3727 oflags = O_RDWR | O_CREAT;
3729 env->me_fd = open(dpath, oflags, mode);
3731 if (env->me_fd == INVALID_HANDLE_VALUE) {
3736 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
3737 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
3738 env->me_mfd = env->me_fd;
3740 /* Synchronous fd for meta writes. Needed even with
3741 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
3744 env->me_mfd = CreateFile(dpath, oflags,
3745 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
3746 mode | FILE_FLAG_WRITE_THROUGH, NULL);
3748 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
3750 if (env->me_mfd == INVALID_HANDLE_VALUE) {
3755 DPRINTF("opened dbenv %p", (void *) env);
3757 rc = mdb_env_share_locks(env, &excl);
3763 mdb_env_close0(env, excl);
3769 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
3771 mdb_env_close0(MDB_env *env, int excl)
3775 if (!(env->me_flags & MDB_ENV_ACTIVE))
3778 /* Doing this here since me_dbxs may not exist during mdb_env_close */
3779 for (i = env->me_maxdbs; --i > MAIN_DBI; )
3780 free(env->me_dbxs[i].md_name.mv_data);
3782 free(env->me_dbflags);
3785 free(env->me_dirty_list);
3786 mdb_midl_free(env->me_free_pgs);
3788 if (env->me_flags & MDB_ENV_TXKEY) {
3789 pthread_key_delete(env->me_txkey);
3791 /* Delete our key from the global list */
3792 for (i=0; i<mdb_tls_nkeys; i++)
3793 if (mdb_tls_keys[i] == env->me_txkey) {
3794 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
3802 munmap(env->me_map, env->me_mapsize);
3804 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
3805 (void) close(env->me_mfd);
3806 if (env->me_fd != INVALID_HANDLE_VALUE)
3807 (void) close(env->me_fd);
3809 pid_t pid = env->me_pid;
3810 /* Clearing readers is done in this function because
3811 * me_txkey with its destructor must be disabled first.
3813 for (i = env->me_numreaders; --i >= 0; )
3814 if (env->me_txns->mti_readers[i].mr_pid == pid)
3815 env->me_txns->mti_readers[i].mr_pid = 0;
3817 if (env->me_rmutex) {
3818 CloseHandle(env->me_rmutex);
3819 if (env->me_wmutex) CloseHandle(env->me_wmutex);
3821 /* Windows automatically destroys the mutexes when
3822 * the last handle closes.
3824 #elif defined(MDB_USE_POSIX_SEM)
3825 if (env->me_rmutex != SEM_FAILED) {
3826 sem_close(env->me_rmutex);
3827 if (env->me_wmutex != SEM_FAILED)
3828 sem_close(env->me_wmutex);
3829 /* If we have the filelock: If we are the
3830 * only remaining user, clean up semaphores.
3833 mdb_env_excl_lock(env, &excl);
3835 sem_unlink(env->me_txns->mti_rmname);
3836 sem_unlink(env->me_txns->mti_wmname);
3840 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
3842 if (env->me_lfd != INVALID_HANDLE_VALUE) {
3845 /* Unlock the lockfile. Windows would have unlocked it
3846 * after closing anyway, but not necessarily at once.
3848 UnlockFile(env->me_lfd, 0, 0, 1, 0);
3851 (void) close(env->me_lfd);
3854 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
3858 mdb_env_copyfd(MDB_env *env, HANDLE fd)
3860 MDB_txn *txn = NULL;
3865 /* Do the lock/unlock of the reader mutex before starting the
3866 * write txn. Otherwise other read txns could block writers.
3868 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
3873 /* We must start the actual read txn after blocking writers */
3874 mdb_txn_reset0(txn, "reset-stage1");
3876 /* Temporarily block writers until we snapshot the meta pages */
3879 rc = mdb_txn_renew0(txn);
3881 UNLOCK_MUTEX_W(env);
3886 wsize = env->me_psize * 2;
3890 rc = WriteFile(fd, env->me_map, wsize, &len, NULL);
3891 rc = rc ? (len == wsize ? MDB_SUCCESS : EIO) : ErrCode();
3894 rc = write(fd, env->me_map, wsize);
3895 rc = rc == (int)wsize ? MDB_SUCCESS : rc < 0 ? ErrCode() : EIO;
3898 UNLOCK_MUTEX_W(env);
3903 ptr = env->me_map + wsize;
3904 wsize = txn->mt_next_pgno * env->me_psize - wsize;
3908 if (wsize > MAX_WRITE)
3912 rc = WriteFile(fd, ptr, w2, &len, NULL);
3913 rc = rc ? (len == w2 ? MDB_SUCCESS : EIO) : ErrCode();
3922 if (wsize > MAX_WRITE)
3926 wres = write(fd, ptr, w2);
3927 rc = wres == (ssize_t)w2 ? MDB_SUCCESS : wres < 0 ? ErrCode() : EIO;
3940 mdb_env_copy(MDB_env *env, const char *path)
3944 HANDLE newfd = INVALID_HANDLE_VALUE;
3946 if (env->me_flags & MDB_NOSUBDIR) {
3947 lpath = (char *)path;
3950 len += sizeof(DATANAME);
3951 lpath = malloc(len);
3954 sprintf(lpath, "%s" DATANAME, path);
3957 /* The destination path must exist, but the destination file must not.
3958 * We don't want the OS to cache the writes, since the source data is
3959 * already in the OS cache.
3962 newfd = CreateFile(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
3963 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
3965 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL
3971 if (newfd == INVALID_HANDLE_VALUE) {
3976 #ifdef F_NOCACHE /* __APPLE__ */
3977 rc = fcntl(newfd, F_NOCACHE, 1);
3984 rc = mdb_env_copyfd(env, newfd);
3987 if (!(env->me_flags & MDB_NOSUBDIR))
3989 if (newfd != INVALID_HANDLE_VALUE)
3990 if (close(newfd) < 0 && rc == MDB_SUCCESS)
3997 mdb_env_close(MDB_env *env)
4004 VGMEMP_DESTROY(env);
4005 while ((dp = env->me_dpages) != NULL) {
4006 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
4007 env->me_dpages = dp->mp_next;
4011 mdb_env_close0(env, 0);
4015 /** Compare two items pointing at aligned size_t's */
4017 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
4019 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
4020 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
4023 /** Compare two items pointing at aligned int's */
4025 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
4027 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
4028 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
4031 /** Compare two items pointing at ints of unknown alignment.
4032 * Nodes and keys are guaranteed to be 2-byte aligned.
4035 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
4037 #if BYTE_ORDER == LITTLE_ENDIAN
4038 unsigned short *u, *c;
4041 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4042 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
4045 } while(!x && u > (unsigned short *)a->mv_data);
4048 return memcmp(a->mv_data, b->mv_data, a->mv_size);
4052 /** Compare two items lexically */
4054 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
4061 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4067 diff = memcmp(a->mv_data, b->mv_data, len);
4068 return diff ? diff : len_diff<0 ? -1 : len_diff;
4071 /** Compare two items in reverse byte order */
4073 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
4075 const unsigned char *p1, *p2, *p1_lim;
4079 p1_lim = (const unsigned char *)a->mv_data;
4080 p1 = (const unsigned char *)a->mv_data + a->mv_size;
4081 p2 = (const unsigned char *)b->mv_data + b->mv_size;
4083 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4089 while (p1 > p1_lim) {
4090 diff = *--p1 - *--p2;
4094 return len_diff<0 ? -1 : len_diff;
4097 /** Search for key within a page, using binary search.
4098 * Returns the smallest entry larger or equal to the key.
4099 * If exactp is non-null, stores whether the found entry was an exact match
4100 * in *exactp (1 or 0).
4101 * Updates the cursor index with the index of the found entry.
4102 * If no entry larger or equal to the key is found, returns NULL.
4105 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
4107 unsigned int i = 0, nkeys;
4110 MDB_page *mp = mc->mc_pg[mc->mc_top];
4111 MDB_node *node = NULL;
4116 nkeys = NUMKEYS(mp);
4121 COPY_PGNO(pgno, mp->mp_pgno);
4122 DPRINTF("searching %u keys in %s %spage %zu",
4123 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
4130 low = IS_LEAF(mp) ? 0 : 1;
4132 cmp = mc->mc_dbx->md_cmp;
4134 /* Branch pages have no data, so if using integer keys,
4135 * alignment is guaranteed. Use faster mdb_cmp_int.
4137 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
4138 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
4145 nodekey.mv_size = mc->mc_db->md_pad;
4146 node = NODEPTR(mp, 0); /* fake */
4147 while (low <= high) {
4148 i = (low + high) >> 1;
4149 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
4150 rc = cmp(key, &nodekey);
4151 DPRINTF("found leaf index %u [%s], rc = %i",
4152 i, DKEY(&nodekey), rc);
4161 while (low <= high) {
4162 i = (low + high) >> 1;
4164 node = NODEPTR(mp, i);
4165 nodekey.mv_size = NODEKSZ(node);
4166 nodekey.mv_data = NODEKEY(node);
4168 rc = cmp(key, &nodekey);
4171 DPRINTF("found leaf index %u [%s], rc = %i",
4172 i, DKEY(&nodekey), rc);
4174 DPRINTF("found branch index %u [%s -> %zu], rc = %i",
4175 i, DKEY(&nodekey), NODEPGNO(node), rc);
4186 if (rc > 0) { /* Found entry is less than the key. */
4187 i++; /* Skip to get the smallest entry larger than key. */
4189 node = NODEPTR(mp, i);
4192 *exactp = (rc == 0);
4193 /* store the key index */
4194 mc->mc_ki[mc->mc_top] = i;
4196 /* There is no entry larger or equal to the key. */
4199 /* nodeptr is fake for LEAF2 */
4205 mdb_cursor_adjust(MDB_cursor *mc, func)
4209 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4210 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
4217 /** Pop a page off the top of the cursor's stack. */
4219 mdb_cursor_pop(MDB_cursor *mc)
4222 #ifndef MDB_DEBUG_SKIP
4223 MDB_page *top = mc->mc_pg[mc->mc_top];
4229 DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
4230 mc->mc_dbi, (void *) mc);
4234 /** Push a page onto the top of the cursor's stack. */
4236 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
4238 DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
4239 mc->mc_dbi, (void *) mc);
4241 if (mc->mc_snum >= CURSOR_STACK) {
4242 assert(mc->mc_snum < CURSOR_STACK);
4243 return MDB_CURSOR_FULL;
4246 mc->mc_top = mc->mc_snum++;
4247 mc->mc_pg[mc->mc_top] = mp;
4248 mc->mc_ki[mc->mc_top] = 0;
4253 /** Find the address of the page corresponding to a given page number.
4254 * @param[in] txn the transaction for this access.
4255 * @param[in] pgno the page number for the page to retrieve.
4256 * @param[out] ret address of a pointer where the page's address will be stored.
4257 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
4258 * @return 0 on success, non-zero on failure.
4261 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
4266 if (!((txn->mt_flags & MDB_TXN_RDONLY) |
4267 (txn->mt_env->me_flags & MDB_WRITEMAP)))
4272 MDB_ID2L dl = tx2->mt_u.dirty_list;
4274 /* Spilled pages were dirtied in this txn and flushed
4275 * because the dirty list got full. Bring this page
4276 * back in from the map (but don't unspill it here,
4277 * leave that unless page_touch happens again).
4279 if (tx2->mt_spill_pgs) {
4280 x = mdb_midl_search(tx2->mt_spill_pgs, pgno);
4281 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pgno) {
4282 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
4287 unsigned x = mdb_mid2l_search(dl, pgno);
4288 if (x <= dl[0].mid && dl[x].mid == pgno) {
4294 } while ((tx2 = tx2->mt_parent) != NULL);
4297 if (pgno < txn->mt_next_pgno) {
4299 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
4301 DPRINTF("page %zu not found", pgno);
4303 return MDB_PAGE_NOTFOUND;
4313 /** Search for the page a given key should be in.
4314 * Pushes parent pages on the cursor stack. This function continues a
4315 * search on a cursor that has already been initialized. (Usually by
4316 * #mdb_page_search() but also by #mdb_node_move().)
4317 * @param[in,out] mc the cursor for this operation.
4318 * @param[in] key the key to search for. If NULL, search for the lowest
4319 * page. (This is used by #mdb_cursor_first().)
4320 * @param[in] modify If true, visited pages are updated with new page numbers.
4321 * @return 0 on success, non-zero on failure.
4324 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
4326 MDB_page *mp = mc->mc_pg[mc->mc_top];
4331 while (IS_BRANCH(mp)) {
4335 DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
4336 assert(NUMKEYS(mp) > 1);
4337 DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
4339 if (key == NULL) /* Initialize cursor to first page. */
4341 else if (key->mv_size > MDB_MAXKEYSIZE && key->mv_data == NULL) {
4342 /* cursor to last page */
4346 node = mdb_node_search(mc, key, &exact);
4348 i = NUMKEYS(mp) - 1;
4350 i = mc->mc_ki[mc->mc_top];
4359 DPRINTF("following index %u for key [%s]",
4361 assert(i < NUMKEYS(mp));
4362 node = NODEPTR(mp, i);
4364 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4367 mc->mc_ki[mc->mc_top] = i;
4368 if ((rc = mdb_cursor_push(mc, mp)))
4372 if ((rc = mdb_page_touch(mc)) != 0)
4374 mp = mc->mc_pg[mc->mc_top];
4379 DPRINTF("internal error, index points to a %02X page!?",
4381 return MDB_CORRUPTED;
4384 DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
4385 key ? DKEY(key) : NULL);
4386 mc->mc_flags |= C_INITIALIZED;
4387 mc->mc_flags &= ~C_EOF;
4392 /** Search for the lowest key under the current branch page.
4393 * This just bypasses a NUMKEYS check in the current page
4394 * before calling mdb_page_search_root(), because the callers
4395 * are all in situations where the current page is known to
4399 mdb_page_search_lowest(MDB_cursor *mc)
4401 MDB_page *mp = mc->mc_pg[mc->mc_top];
4402 MDB_node *node = NODEPTR(mp, 0);
4405 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4408 mc->mc_ki[mc->mc_top] = 0;
4409 if ((rc = mdb_cursor_push(mc, mp)))
4411 return mdb_page_search_root(mc, NULL, 0);
4414 /** Search for the page a given key should be in.
4415 * Pushes parent pages on the cursor stack. This function just sets up
4416 * the search; it finds the root page for \b mc's database and sets this
4417 * as the root of the cursor's stack. Then #mdb_page_search_root() is
4418 * called to complete the search.
4419 * @param[in,out] mc the cursor for this operation.
4420 * @param[in] key the key to search for. If NULL, search for the lowest
4421 * page. (This is used by #mdb_cursor_first().)
4422 * @param[in] flags If MDB_PS_MODIFY set, visited pages are updated with new page numbers.
4423 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
4424 * @return 0 on success, non-zero on failure.
4427 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
4432 /* Make sure the txn is still viable, then find the root from
4433 * the txn's db table.
4435 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
4436 DPUTS("transaction has failed, must abort");
4439 /* Make sure we're using an up-to-date root */
4440 if (mc->mc_dbi > MAIN_DBI) {
4441 if ((*mc->mc_dbflag & DB_STALE) ||
4442 ((flags & MDB_PS_MODIFY) && !(*mc->mc_dbflag & DB_DIRTY))) {
4444 unsigned char dbflag = 0;
4445 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
4446 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, flags & MDB_PS_MODIFY);
4449 if (*mc->mc_dbflag & DB_STALE) {
4453 MDB_node *leaf = mdb_node_search(&mc2,
4454 &mc->mc_dbx->md_name, &exact);
4456 return MDB_NOTFOUND;
4457 rc = mdb_node_read(mc->mc_txn, leaf, &data);
4460 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
4462 /* The txn may not know this DBI, or another process may
4463 * have dropped and recreated the DB with other flags.
4465 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
4466 return MDB_INCOMPATIBLE;
4467 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
4469 if (flags & MDB_PS_MODIFY)
4471 *mc->mc_dbflag &= ~DB_STALE;
4472 *mc->mc_dbflag |= dbflag;
4475 root = mc->mc_db->md_root;
4477 if (root == P_INVALID) { /* Tree is empty. */
4478 DPUTS("tree is empty");
4479 return MDB_NOTFOUND;
4484 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
4485 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0], NULL)) != 0)
4491 DPRINTF("db %u root page %zu has flags 0x%X",
4492 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
4494 if (flags & MDB_PS_MODIFY) {
4495 if ((rc = mdb_page_touch(mc)))
4499 if (flags & MDB_PS_ROOTONLY)
4502 return mdb_page_search_root(mc, key, flags);
4506 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
4508 MDB_txn *txn = mc->mc_txn;
4509 pgno_t pg = mp->mp_pgno;
4510 unsigned i, ovpages = mp->mp_pages;
4511 MDB_env *env = txn->mt_env;
4514 DPRINTF("free ov page %zu (%d)", pg, ovpages);
4515 /* If the page is dirty or on the spill list we just acquired it,
4516 * so we should give it back to our current free list, if any.
4517 * Not currently supported in nested txns.
4518 * Otherwise put it onto the list of pages we freed in this txn.
4520 if (!(mp->mp_flags & P_DIRTY) && txn->mt_spill_pgs) {
4521 unsigned x = mdb_midl_search(txn->mt_spill_pgs, pg);
4522 if (x <= txn->mt_spill_pgs[0] && txn->mt_spill_pgs[x] == pg) {
4523 /* This page is no longer spilled */
4524 for (; x < txn->mt_spill_pgs[0]; x++)
4525 txn->mt_spill_pgs[x] = txn->mt_spill_pgs[x+1];
4526 txn->mt_spill_pgs[0]--;
4530 if ((mp->mp_flags & P_DIRTY) && !txn->mt_parent && env->me_pghead) {
4533 MDB_ID2 *dl, ix, iy;
4534 rc = mdb_midl_need(&env->me_pghead, ovpages);
4537 /* Remove from dirty list */
4538 dl = txn->mt_u.dirty_list;
4540 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
4548 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
4549 txn->mt_flags |= MDB_TXN_ERROR;
4550 return MDB_CORRUPTED;
4553 if (!(env->me_flags & MDB_WRITEMAP))
4554 mdb_dpage_free(env, mp);
4556 /* Insert in me_pghead */
4557 mop = env->me_pghead;
4558 j = mop[0] + ovpages;
4559 for (i = mop[0]; i && mop[i] < pg; i--)
4565 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
4569 mc->mc_db->md_overflow_pages -= ovpages;
4573 /** Return the data associated with a given node.
4574 * @param[in] txn The transaction for this operation.
4575 * @param[in] leaf The node being read.
4576 * @param[out] data Updated to point to the node's data.
4577 * @return 0 on success, non-zero on failure.
4580 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
4582 MDB_page *omp; /* overflow page */
4586 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
4587 data->mv_size = NODEDSZ(leaf);
4588 data->mv_data = NODEDATA(leaf);
4592 /* Read overflow data.
4594 data->mv_size = NODEDSZ(leaf);
4595 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
4596 if ((rc = mdb_page_get(txn, pgno, &omp, NULL)) != 0) {
4597 DPRINTF("read overflow page %zu failed", pgno);
4600 data->mv_data = METADATA(omp);
4606 mdb_get(MDB_txn *txn, MDB_dbi dbi,
4607 MDB_val *key, MDB_val *data)
4616 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
4618 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
4621 if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
4625 mdb_cursor_init(&mc, txn, dbi, &mx);
4626 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
4629 /** Find a sibling for a page.
4630 * Replaces the page at the top of the cursor's stack with the
4631 * specified sibling, if one exists.
4632 * @param[in] mc The cursor for this operation.
4633 * @param[in] move_right Non-zero if the right sibling is requested,
4634 * otherwise the left sibling.
4635 * @return 0 on success, non-zero on failure.
4638 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
4644 if (mc->mc_snum < 2) {
4645 return MDB_NOTFOUND; /* root has no siblings */
4649 DPRINTF("parent page is page %zu, index %u",
4650 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]);
4652 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
4653 : (mc->mc_ki[mc->mc_top] == 0)) {
4654 DPRINTF("no more keys left, moving to %s sibling",
4655 move_right ? "right" : "left");
4656 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
4657 /* undo cursor_pop before returning */
4664 mc->mc_ki[mc->mc_top]++;
4666 mc->mc_ki[mc->mc_top]--;
4667 DPRINTF("just moving to %s index key %u",
4668 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]);
4670 assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
4672 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4673 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL) != 0))
4676 mdb_cursor_push(mc, mp);
4678 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
4683 /** Move the cursor to the next data item. */
4685 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
4691 if (mc->mc_flags & C_EOF) {
4692 return MDB_NOTFOUND;
4695 assert(mc->mc_flags & C_INITIALIZED);
4697 mp = mc->mc_pg[mc->mc_top];
4699 if (mc->mc_db->md_flags & MDB_DUPSORT) {
4700 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4701 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4702 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
4703 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
4704 if (op != MDB_NEXT || rc != MDB_NOTFOUND)
4708 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
4709 if (op == MDB_NEXT_DUP)
4710 return MDB_NOTFOUND;
4714 DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
4716 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
4717 DPUTS("=====> move to next sibling page");
4718 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
4719 mc->mc_flags |= C_EOF;
4722 mp = mc->mc_pg[mc->mc_top];
4723 DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
4725 mc->mc_ki[mc->mc_top]++;
4727 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
4728 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
4731 key->mv_size = mc->mc_db->md_pad;
4732 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
4736 assert(IS_LEAF(mp));
4737 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4739 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4740 mdb_xcursor_init1(mc, leaf);
4743 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4746 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4747 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4748 if (rc != MDB_SUCCESS)
4753 MDB_GET_KEY(leaf, key);
4757 /** Move the cursor to the previous data item. */
4759 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
4765 assert(mc->mc_flags & C_INITIALIZED);
4767 mp = mc->mc_pg[mc->mc_top];
4769 if (mc->mc_db->md_flags & MDB_DUPSORT) {
4770 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4771 if (op == MDB_PREV || op == MDB_PREV_DUP) {
4772 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4773 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
4774 if (op != MDB_PREV || rc != MDB_NOTFOUND)
4777 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
4778 if (op == MDB_PREV_DUP)
4779 return MDB_NOTFOUND;
4784 DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
4786 if (mc->mc_ki[mc->mc_top] == 0) {
4787 DPUTS("=====> move to prev sibling page");
4788 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
4791 mp = mc->mc_pg[mc->mc_top];
4792 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
4793 DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
4795 mc->mc_ki[mc->mc_top]--;
4797 mc->mc_flags &= ~C_EOF;
4799 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
4800 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
4803 key->mv_size = mc->mc_db->md_pad;
4804 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
4808 assert(IS_LEAF(mp));
4809 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4811 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4812 mdb_xcursor_init1(mc, leaf);
4815 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4818 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4819 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
4820 if (rc != MDB_SUCCESS)
4825 MDB_GET_KEY(leaf, key);
4829 /** Set the cursor on a specific data item. */
4831 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
4832 MDB_cursor_op op, int *exactp)
4836 MDB_node *leaf = NULL;
4841 assert(key->mv_size > 0);
4843 /* See if we're already on the right page */
4844 if (mc->mc_flags & C_INITIALIZED) {
4847 mp = mc->mc_pg[mc->mc_top];
4849 mc->mc_ki[mc->mc_top] = 0;
4850 return MDB_NOTFOUND;
4852 if (mp->mp_flags & P_LEAF2) {
4853 nodekey.mv_size = mc->mc_db->md_pad;
4854 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
4856 leaf = NODEPTR(mp, 0);
4857 MDB_GET_KEY(leaf, &nodekey);
4859 rc = mc->mc_dbx->md_cmp(key, &nodekey);
4861 /* Probably happens rarely, but first node on the page
4862 * was the one we wanted.
4864 mc->mc_ki[mc->mc_top] = 0;
4871 unsigned int nkeys = NUMKEYS(mp);
4873 if (mp->mp_flags & P_LEAF2) {
4874 nodekey.mv_data = LEAF2KEY(mp,
4875 nkeys-1, nodekey.mv_size);
4877 leaf = NODEPTR(mp, nkeys-1);
4878 MDB_GET_KEY(leaf, &nodekey);
4880 rc = mc->mc_dbx->md_cmp(key, &nodekey);
4882 /* last node was the one we wanted */
4883 mc->mc_ki[mc->mc_top] = nkeys-1;
4889 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
4890 /* This is definitely the right page, skip search_page */
4891 if (mp->mp_flags & P_LEAF2) {
4892 nodekey.mv_data = LEAF2KEY(mp,
4893 mc->mc_ki[mc->mc_top], nodekey.mv_size);
4895 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4896 MDB_GET_KEY(leaf, &nodekey);
4898 rc = mc->mc_dbx->md_cmp(key, &nodekey);
4900 /* current node was the one we wanted */
4910 /* If any parents have right-sibs, search.
4911 * Otherwise, there's nothing further.
4913 for (i=0; i<mc->mc_top; i++)
4915 NUMKEYS(mc->mc_pg[i])-1)
4917 if (i == mc->mc_top) {
4918 /* There are no other pages */
4919 mc->mc_ki[mc->mc_top] = nkeys;
4920 return MDB_NOTFOUND;
4924 /* There are no other pages */
4925 mc->mc_ki[mc->mc_top] = 0;
4926 return MDB_NOTFOUND;
4930 rc = mdb_page_search(mc, key, 0);
4931 if (rc != MDB_SUCCESS)
4934 mp = mc->mc_pg[mc->mc_top];
4935 assert(IS_LEAF(mp));
4938 leaf = mdb_node_search(mc, key, exactp);
4939 if (exactp != NULL && !*exactp) {
4940 /* MDB_SET specified and not an exact match. */
4941 return MDB_NOTFOUND;
4945 DPUTS("===> inexact leaf not found, goto sibling");
4946 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
4947 return rc; /* no entries matched */
4948 mp = mc->mc_pg[mc->mc_top];
4949 assert(IS_LEAF(mp));
4950 leaf = NODEPTR(mp, 0);
4954 mc->mc_flags |= C_INITIALIZED;
4955 mc->mc_flags &= ~C_EOF;
4958 key->mv_size = mc->mc_db->md_pad;
4959 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
4963 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4964 mdb_xcursor_init1(mc, leaf);
4967 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4968 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
4969 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4972 if (op == MDB_GET_BOTH) {
4978 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
4979 if (rc != MDB_SUCCESS)
4982 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
4984 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
4986 rc = mc->mc_dbx->md_dcmp(data, &d2);
4988 if (op == MDB_GET_BOTH || rc > 0)
4989 return MDB_NOTFOUND;
4994 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
4995 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5000 /* The key already matches in all other cases */
5001 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
5002 MDB_GET_KEY(leaf, key);
5003 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
5008 /** Move the cursor to the first item in the database. */
5010 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5015 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5016 rc = mdb_page_search(mc, NULL, 0);
5017 if (rc != MDB_SUCCESS)
5020 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
5022 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
5023 mc->mc_flags |= C_INITIALIZED;
5024 mc->mc_flags &= ~C_EOF;
5026 mc->mc_ki[mc->mc_top] = 0;
5028 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5029 key->mv_size = mc->mc_db->md_pad;
5030 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
5035 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5036 mdb_xcursor_init1(mc, leaf);
5037 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5042 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5043 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5047 MDB_GET_KEY(leaf, key);
5051 /** Move the cursor to the last item in the database. */
5053 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5058 if (!(mc->mc_flags & C_EOF)) {
5060 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5063 lkey.mv_size = MDB_MAXKEYSIZE+1;
5064 lkey.mv_data = NULL;
5065 rc = mdb_page_search(mc, &lkey, 0);
5066 if (rc != MDB_SUCCESS)
5069 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
5072 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
5073 mc->mc_flags |= C_INITIALIZED|C_EOF;
5074 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5076 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5077 key->mv_size = mc->mc_db->md_pad;
5078 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
5083 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5084 mdb_xcursor_init1(mc, leaf);
5085 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5090 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5091 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5096 MDB_GET_KEY(leaf, key);
5101 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5110 case MDB_GET_CURRENT:
5111 if (!(mc->mc_flags & C_INITIALIZED)) {
5114 MDB_page *mp = mc->mc_pg[mc->mc_top];
5116 mc->mc_ki[mc->mc_top] = 0;
5122 key->mv_size = mc->mc_db->md_pad;
5123 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5125 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5126 MDB_GET_KEY(leaf, key);
5128 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5129 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
5131 rc = mdb_node_read(mc->mc_txn, leaf, data);
5138 case MDB_GET_BOTH_RANGE:
5139 if (data == NULL || mc->mc_xcursor == NULL) {
5147 if (key == NULL || key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
5149 } else if (op == MDB_SET_RANGE)
5150 rc = mdb_cursor_set(mc, key, data, op, NULL);
5152 rc = mdb_cursor_set(mc, key, data, op, &exact);
5154 case MDB_GET_MULTIPLE:
5156 !(mc->mc_db->md_flags & MDB_DUPFIXED) ||
5157 !(mc->mc_flags & C_INITIALIZED)) {
5162 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
5163 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
5166 case MDB_NEXT_MULTIPLE:
5168 !(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5172 if (!(mc->mc_flags & C_INITIALIZED))
5173 rc = mdb_cursor_first(mc, key, data);
5175 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
5176 if (rc == MDB_SUCCESS) {
5177 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
5180 mx = &mc->mc_xcursor->mx_cursor;
5181 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
5183 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
5184 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
5192 case MDB_NEXT_NODUP:
5193 if (!(mc->mc_flags & C_INITIALIZED))
5194 rc = mdb_cursor_first(mc, key, data);
5196 rc = mdb_cursor_next(mc, key, data, op);
5200 case MDB_PREV_NODUP:
5201 if (!(mc->mc_flags & C_INITIALIZED)) {
5202 rc = mdb_cursor_last(mc, key, data);
5205 mc->mc_flags |= C_INITIALIZED;
5206 mc->mc_ki[mc->mc_top]++;
5208 rc = mdb_cursor_prev(mc, key, data, op);
5211 rc = mdb_cursor_first(mc, key, data);
5215 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
5216 !(mc->mc_flags & C_INITIALIZED) ||
5217 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
5221 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5224 rc = mdb_cursor_last(mc, key, data);
5228 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
5229 !(mc->mc_flags & C_INITIALIZED) ||
5230 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
5234 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5237 DPRINTF("unhandled/unimplemented cursor operation %u", op);
5245 /** Touch all the pages in the cursor stack.
5246 * Makes sure all the pages are writable, before attempting a write operation.
5247 * @param[in] mc The cursor to operate on.
5250 mdb_cursor_touch(MDB_cursor *mc)
5254 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
5257 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
5258 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
5261 *mc->mc_dbflag |= DB_DIRTY;
5263 for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
5264 rc = mdb_page_touch(mc);
5268 mc->mc_top = mc->mc_snum-1;
5272 /** Do not spill pages to disk if txn is getting full, may fail instead */
5273 #define MDB_NOSPILL 0x8000
5276 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5279 enum { MDB_NO_ROOT = MDB_LAST_ERRCODE+10 }; /* internal code */
5280 MDB_node *leaf = NULL;
5281 MDB_val xdata, *rdata, dkey;
5284 int do_sub = 0, insert = 0;
5285 unsigned int mcount = 0, dcount = 0, nospill;
5289 char dbuf[MDB_MAXKEYSIZE+1];
5290 unsigned int nflags;
5293 /* Check this first so counter will always be zero on any
5296 if (flags & MDB_MULTIPLE) {
5297 dcount = data[1].mv_size;
5298 data[1].mv_size = 0;
5299 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
5303 nospill = flags & MDB_NOSPILL;
5304 flags &= ~MDB_NOSPILL;
5306 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
5309 if (flags != MDB_CURRENT && (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE))
5312 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT) && data->mv_size > MDB_MAXKEYSIZE)
5315 #if SIZE_MAX > MAXDATASIZE
5316 if (data->mv_size > MAXDATASIZE)
5320 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
5321 mc->mc_dbi, DKEY(key), key ? key->mv_size:0, data->mv_size);
5325 if (flags == MDB_CURRENT) {
5326 if (!(mc->mc_flags & C_INITIALIZED))
5329 } else if (mc->mc_db->md_root == P_INVALID) {
5330 /* new database, cursor has nothing to point to */
5332 mc->mc_flags &= ~C_INITIALIZED;
5337 if (flags & MDB_APPEND) {
5339 rc = mdb_cursor_last(mc, &k2, &d2);
5341 rc = mc->mc_dbx->md_cmp(key, &k2);
5344 mc->mc_ki[mc->mc_top]++;
5346 /* new key is <= last key */
5351 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
5353 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
5354 DPRINTF("duplicate key [%s]", DKEY(key));
5356 return MDB_KEYEXIST;
5358 if (rc && rc != MDB_NOTFOUND)
5362 /* Cursor is positioned, check for room in the dirty list */
5364 if (flags & MDB_MULTIPLE) {
5366 xdata.mv_size = data->mv_size * dcount;
5370 if ((rc2 = mdb_page_spill(mc, key, rdata)))
5374 if (rc == MDB_NO_ROOT) {
5376 /* new database, write a root leaf page */
5377 DPUTS("allocating new root leaf page");
5378 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
5381 mdb_cursor_push(mc, np);
5382 mc->mc_db->md_root = np->mp_pgno;
5383 mc->mc_db->md_depth++;
5384 *mc->mc_dbflag |= DB_DIRTY;
5385 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
5387 np->mp_flags |= P_LEAF2;
5388 mc->mc_flags |= C_INITIALIZED;
5390 /* make sure all cursor pages are writable */
5391 rc2 = mdb_cursor_touch(mc);
5396 /* The key already exists */
5397 if (rc == MDB_SUCCESS) {
5398 /* there's only a key anyway, so this is a no-op */
5399 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5400 unsigned int ksize = mc->mc_db->md_pad;
5401 if (key->mv_size != ksize)
5403 if (flags == MDB_CURRENT) {
5404 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
5405 memcpy(ptr, key->mv_data, ksize);
5410 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5413 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
5414 /* Was a single item before, must convert now */
5416 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5417 /* Just overwrite the current item */
5418 if (flags == MDB_CURRENT)
5421 dkey.mv_size = NODEDSZ(leaf);
5422 dkey.mv_data = NODEDATA(leaf);
5423 #if UINT_MAX < SIZE_MAX
5424 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && dkey.mv_size == sizeof(size_t))
5425 #ifdef MISALIGNED_OK
5426 mc->mc_dbx->md_dcmp = mdb_cmp_long;
5428 mc->mc_dbx->md_dcmp = mdb_cmp_cint;
5431 /* if data matches, ignore it */
5432 if (!mc->mc_dbx->md_dcmp(data, &dkey))
5433 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
5435 /* create a fake page for the dup items */
5436 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
5437 dkey.mv_data = dbuf;
5438 fp = (MDB_page *)&pbuf;
5439 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
5440 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
5441 fp->mp_lower = PAGEHDRSZ;
5442 fp->mp_upper = PAGEHDRSZ + dkey.mv_size + data->mv_size;
5443 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5444 fp->mp_flags |= P_LEAF2;
5445 fp->mp_pad = data->mv_size;
5446 fp->mp_upper += 2 * data->mv_size; /* leave space for 2 more */
5448 fp->mp_upper += 2 * sizeof(indx_t) + 2 * NODESIZE +
5449 (dkey.mv_size & 1) + (data->mv_size & 1);
5451 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5454 xdata.mv_size = fp->mp_upper;
5459 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
5460 /* See if we need to convert from fake page to subDB */
5462 unsigned int offset;
5466 fp = NODEDATA(leaf);
5467 if (flags == MDB_CURRENT) {
5469 fp->mp_flags |= P_DIRTY;
5470 COPY_PGNO(fp->mp_pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
5471 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
5475 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5476 offset = fp->mp_pad;
5477 if (SIZELEFT(fp) >= offset)
5479 offset *= 4; /* space for 4 more */
5481 offset = NODESIZE + sizeof(indx_t) + data->mv_size;
5483 offset += offset & 1;
5484 fp_flags = fp->mp_flags;
5485 if (NODESIZE + sizeof(indx_t) + NODEKSZ(leaf) + NODEDSZ(leaf) +
5486 offset >= mc->mc_txn->mt_env->me_nodemax) {
5487 /* yes, convert it */
5489 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5490 dummy.md_pad = fp->mp_pad;
5491 dummy.md_flags = MDB_DUPFIXED;
5492 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
5493 dummy.md_flags |= MDB_INTEGERKEY;
5496 dummy.md_branch_pages = 0;
5497 dummy.md_leaf_pages = 1;
5498 dummy.md_overflow_pages = 0;
5499 dummy.md_entries = NUMKEYS(fp);
5501 xdata.mv_size = sizeof(MDB_db);
5502 xdata.mv_data = &dummy;
5503 if ((rc = mdb_page_alloc(mc, 1, &mp)))
5505 offset = mc->mc_txn->mt_env->me_psize - NODEDSZ(leaf);
5506 flags |= F_DUPDATA|F_SUBDATA;
5507 dummy.md_root = mp->mp_pgno;
5508 fp_flags &= ~P_SUBP;
5510 /* no, just grow it */
5512 xdata.mv_size = NODEDSZ(leaf) + offset;
5513 xdata.mv_data = &pbuf;
5514 mp = (MDB_page *)&pbuf;
5515 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
5518 mp->mp_flags = fp_flags | P_DIRTY;
5519 mp->mp_pad = fp->mp_pad;
5520 mp->mp_lower = fp->mp_lower;
5521 mp->mp_upper = fp->mp_upper + offset;
5523 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
5525 nsize = NODEDSZ(leaf) - fp->mp_upper;
5526 memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper, nsize);
5527 for (i=0; i<NUMKEYS(fp); i++)
5528 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
5530 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5534 /* data is on sub-DB, just store it */
5535 flags |= F_DUPDATA|F_SUBDATA;
5539 /* overflow page overwrites need special handling */
5540 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5543 unsigned psize = mc->mc_txn->mt_env->me_psize;
5544 int level, ovpages, dpages = OVPAGES(data->mv_size, psize);
5546 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
5547 if ((rc2 = mdb_page_get(mc->mc_txn, pg, &omp, &level)) != 0)
5549 ovpages = omp->mp_pages;
5551 /* Is the ov page large enough? */
5552 if (ovpages >= dpages) {
5553 if (!(omp->mp_flags & P_DIRTY) &&
5554 (level || (mc->mc_txn->mt_env->me_flags & MDB_WRITEMAP)))
5556 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
5559 level = 0; /* dirty in this txn or clean */
5562 if (omp->mp_flags & P_DIRTY) {
5563 /* yes, overwrite it. Note in this case we don't
5564 * bother to try shrinking the page if the new data
5565 * is smaller than the overflow threshold.
5568 /* It is writable only in a parent txn */
5569 size_t sz = (size_t) psize * ovpages, off;
5570 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
5576 mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
5577 if (!(flags & MDB_RESERVE)) {
5578 /* Copy end of page, adjusting alignment so
5579 * compiler may copy words instead of bytes.
5581 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
5582 memcpy((size_t *)((char *)np + off),
5583 (size_t *)((char *)omp + off), sz - off);
5586 memcpy(np, omp, sz); /* Copy beginning of page */
5589 SETDSZ(leaf, data->mv_size);
5590 if (F_ISSET(flags, MDB_RESERVE))
5591 data->mv_data = METADATA(omp);
5593 memcpy(METADATA(omp), data->mv_data, data->mv_size);
5597 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
5599 } else if (NODEDSZ(leaf) == data->mv_size) {
5600 /* same size, just replace it. Note that we could
5601 * also reuse this node if the new data is smaller,
5602 * but instead we opt to shrink the node in that case.
5604 if (F_ISSET(flags, MDB_RESERVE))
5605 data->mv_data = NODEDATA(leaf);
5606 else if (data->mv_size)
5607 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
5609 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
5612 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5613 mc->mc_db->md_entries--;
5615 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
5622 nflags = flags & NODE_ADD_FLAGS;
5623 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
5624 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
5625 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
5626 nflags &= ~MDB_APPEND;
5628 nflags |= MDB_SPLIT_REPLACE;
5629 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
5631 /* There is room already in this leaf page. */
5632 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
5633 if (rc == 0 && !do_sub && insert) {
5634 /* Adjust other cursors pointing to mp */
5635 MDB_cursor *m2, *m3;
5636 MDB_dbi dbi = mc->mc_dbi;
5637 unsigned i = mc->mc_top;
5638 MDB_page *mp = mc->mc_pg[i];
5640 if (mc->mc_flags & C_SUB)
5643 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5644 if (mc->mc_flags & C_SUB)
5645 m3 = &m2->mc_xcursor->mx_cursor;
5648 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
5649 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
5656 if (rc != MDB_SUCCESS)
5657 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5659 /* Now store the actual data in the child DB. Note that we're
5660 * storing the user data in the keys field, so there are strict
5661 * size limits on dupdata. The actual data fields of the child
5662 * DB are all zero size.
5669 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5670 if (flags & MDB_CURRENT) {
5671 xflags = MDB_CURRENT|MDB_NOSPILL;
5673 mdb_xcursor_init1(mc, leaf);
5674 xflags = (flags & MDB_NODUPDATA) ?
5675 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
5677 /* converted, write the original data first */
5679 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
5683 /* Adjust other cursors pointing to mp */
5685 unsigned i = mc->mc_top;
5686 MDB_page *mp = mc->mc_pg[i];
5688 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5689 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
5690 if (!(m2->mc_flags & C_INITIALIZED)) continue;
5691 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
5692 mdb_xcursor_init1(m2, leaf);
5696 /* we've done our job */
5699 if (flags & MDB_APPENDDUP)
5700 xflags |= MDB_APPEND;
5701 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
5702 if (flags & F_SUBDATA) {
5703 void *db = NODEDATA(leaf);
5704 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
5707 /* sub-writes might have failed so check rc again.
5708 * Don't increment count if we just replaced an existing item.
5710 if (!rc && !(flags & MDB_CURRENT))
5711 mc->mc_db->md_entries++;
5712 if (flags & MDB_MULTIPLE) {
5715 if (mcount < dcount) {
5716 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
5717 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5721 /* let caller know how many succeeded, if any */
5722 data[1].mv_size = mcount;
5726 /* If we succeeded and the key didn't exist before, make sure
5727 * the cursor is marked valid.
5730 mc->mc_flags |= C_INITIALIZED;
5735 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
5740 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
5743 if (!(mc->mc_flags & C_INITIALIZED))
5746 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
5748 flags &= ~MDB_NOSPILL; /* TODO: Or change (flags != MDB_NODUPDATA) to ~(flags & MDB_NODUPDATA), not looking at the logic of that code just now */
5750 rc = mdb_cursor_touch(mc);
5754 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5756 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5757 if (flags != MDB_NODUPDATA) {
5758 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
5759 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
5761 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
5762 /* If sub-DB still has entries, we're done */
5763 if (mc->mc_xcursor->mx_db.md_entries) {
5764 if (leaf->mn_flags & F_SUBDATA) {
5765 /* update subDB info */
5766 void *db = NODEDATA(leaf);
5767 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
5770 /* shrink fake page */
5771 mdb_node_shrink(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5772 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5773 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
5774 /* fix other sub-DB cursors pointed at this fake page */
5775 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5776 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
5777 if (m2->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top] &&
5778 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
5779 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
5782 mc->mc_db->md_entries--;
5785 /* otherwise fall thru and delete the sub-DB */
5788 if (leaf->mn_flags & F_SUBDATA) {
5789 /* add all the child DB's pages to the free list */
5790 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
5791 if (rc == MDB_SUCCESS) {
5792 mc->mc_db->md_entries -=
5793 mc->mc_xcursor->mx_db.md_entries;
5798 return mdb_cursor_del0(mc, leaf);
5801 /** Allocate and initialize new pages for a database.
5802 * @param[in] mc a cursor on the database being added to.
5803 * @param[in] flags flags defining what type of page is being allocated.
5804 * @param[in] num the number of pages to allocate. This is usually 1,
5805 * unless allocating overflow pages for a large record.
5806 * @param[out] mp Address of a page, or NULL on failure.
5807 * @return 0 on success, non-zero on failure.
5810 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
5815 if ((rc = mdb_page_alloc(mc, num, &np)))
5817 DPRINTF("allocated new mpage %zu, page size %u",
5818 np->mp_pgno, mc->mc_txn->mt_env->me_psize);
5819 np->mp_flags = flags | P_DIRTY;
5820 np->mp_lower = PAGEHDRSZ;
5821 np->mp_upper = mc->mc_txn->mt_env->me_psize;
5824 mc->mc_db->md_branch_pages++;
5825 else if (IS_LEAF(np))
5826 mc->mc_db->md_leaf_pages++;
5827 else if (IS_OVERFLOW(np)) {
5828 mc->mc_db->md_overflow_pages += num;
5836 /** Calculate the size of a leaf node.
5837 * The size depends on the environment's page size; if a data item
5838 * is too large it will be put onto an overflow page and the node
5839 * size will only include the key and not the data. Sizes are always
5840 * rounded up to an even number of bytes, to guarantee 2-byte alignment
5841 * of the #MDB_node headers.
5842 * @param[in] env The environment handle.
5843 * @param[in] key The key for the node.
5844 * @param[in] data The data for the node.
5845 * @return The number of bytes needed to store the node.
5848 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
5852 sz = LEAFSIZE(key, data);
5853 if (sz >= env->me_nodemax) {
5854 /* put on overflow page */
5855 sz -= data->mv_size - sizeof(pgno_t);
5859 return sz + sizeof(indx_t);
5862 /** Calculate the size of a branch node.
5863 * The size should depend on the environment's page size but since
5864 * we currently don't support spilling large keys onto overflow
5865 * pages, it's simply the size of the #MDB_node header plus the
5866 * size of the key. Sizes are always rounded up to an even number
5867 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
5868 * @param[in] env The environment handle.
5869 * @param[in] key The key for the node.
5870 * @return The number of bytes needed to store the node.
5873 mdb_branch_size(MDB_env *env, MDB_val *key)
5878 if (sz >= env->me_nodemax) {
5879 /* put on overflow page */
5880 /* not implemented */
5881 /* sz -= key->size - sizeof(pgno_t); */
5884 return sz + sizeof(indx_t);
5887 /** Add a node to the page pointed to by the cursor.
5888 * @param[in] mc The cursor for this operation.
5889 * @param[in] indx The index on the page where the new node should be added.
5890 * @param[in] key The key for the new node.
5891 * @param[in] data The data for the new node, if any.
5892 * @param[in] pgno The page number, if adding a branch node.
5893 * @param[in] flags Flags for the node.
5894 * @return 0 on success, non-zero on failure. Possible errors are:
5896 * <li>ENOMEM - failed to allocate overflow pages for the node.
5897 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
5898 * should never happen since all callers already calculate the
5899 * page's free space before calling this function.
5903 mdb_node_add(MDB_cursor *mc, indx_t indx,
5904 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
5907 size_t node_size = NODESIZE;
5910 MDB_page *mp = mc->mc_pg[mc->mc_top];
5911 MDB_page *ofp = NULL; /* overflow page */
5914 assert(mp->mp_upper >= mp->mp_lower);
5916 DPRINTF("add to %s %spage %zu index %i, data size %zu key size %zu [%s]",
5917 IS_LEAF(mp) ? "leaf" : "branch",
5918 IS_SUBP(mp) ? "sub-" : "",
5919 mp->mp_pgno, indx, data ? data->mv_size : 0,
5920 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
5923 /* Move higher keys up one slot. */
5924 int ksize = mc->mc_db->md_pad, dif;
5925 char *ptr = LEAF2KEY(mp, indx, ksize);
5926 dif = NUMKEYS(mp) - indx;
5928 memmove(ptr+ksize, ptr, dif*ksize);
5929 /* insert new key */
5930 memcpy(ptr, key->mv_data, ksize);
5932 /* Just using these for counting */
5933 mp->mp_lower += sizeof(indx_t);
5934 mp->mp_upper -= ksize - sizeof(indx_t);
5939 node_size += key->mv_size;
5943 if (F_ISSET(flags, F_BIGDATA)) {
5944 /* Data already on overflow page. */
5945 node_size += sizeof(pgno_t);
5946 } else if (node_size + data->mv_size >= mc->mc_txn->mt_env->me_nodemax) {
5947 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
5949 /* Put data on overflow page. */
5950 DPRINTF("data size is %zu, node would be %zu, put data on overflow page",
5951 data->mv_size, node_size+data->mv_size);
5952 node_size += sizeof(pgno_t);
5953 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
5955 DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
5958 node_size += data->mv_size;
5961 node_size += node_size & 1;
5963 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
5964 DPRINTF("not enough room in page %zu, got %u ptrs",
5965 mp->mp_pgno, NUMKEYS(mp));
5966 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
5967 mp->mp_upper - mp->mp_lower);
5968 DPRINTF("node size = %zu", node_size);
5969 return MDB_PAGE_FULL;
5972 /* Move higher pointers up one slot. */
5973 for (i = NUMKEYS(mp); i > indx; i--)
5974 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
5976 /* Adjust free space offsets. */
5977 ofs = mp->mp_upper - node_size;
5978 assert(ofs >= mp->mp_lower + sizeof(indx_t));
5979 mp->mp_ptrs[indx] = ofs;
5981 mp->mp_lower += sizeof(indx_t);
5983 /* Write the node data. */
5984 node = NODEPTR(mp, indx);
5985 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
5986 node->mn_flags = flags;
5988 SETDSZ(node,data->mv_size);
5993 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
5998 if (F_ISSET(flags, F_BIGDATA))
5999 memcpy(node->mn_data + key->mv_size, data->mv_data,
6001 else if (F_ISSET(flags, MDB_RESERVE))
6002 data->mv_data = node->mn_data + key->mv_size;
6004 memcpy(node->mn_data + key->mv_size, data->mv_data,
6007 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
6009 if (F_ISSET(flags, MDB_RESERVE))
6010 data->mv_data = METADATA(ofp);
6012 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
6019 /** Delete the specified node from a page.
6020 * @param[in] mp The page to operate on.
6021 * @param[in] indx The index of the node to delete.
6022 * @param[in] ksize The size of a node. Only used if the page is
6023 * part of a #MDB_DUPFIXED database.
6026 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
6029 indx_t i, j, numkeys, ptr;
6036 COPY_PGNO(pgno, mp->mp_pgno);
6037 DPRINTF("delete node %u on %s page %zu", indx,
6038 IS_LEAF(mp) ? "leaf" : "branch", pgno);
6041 assert(indx < NUMKEYS(mp));
6044 int x = NUMKEYS(mp) - 1 - indx;
6045 base = LEAF2KEY(mp, indx, ksize);
6047 memmove(base, base + ksize, x * ksize);
6048 mp->mp_lower -= sizeof(indx_t);
6049 mp->mp_upper += ksize - sizeof(indx_t);
6053 node = NODEPTR(mp, indx);
6054 sz = NODESIZE + node->mn_ksize;
6056 if (F_ISSET(node->mn_flags, F_BIGDATA))
6057 sz += sizeof(pgno_t);
6059 sz += NODEDSZ(node);
6063 ptr = mp->mp_ptrs[indx];
6064 numkeys = NUMKEYS(mp);
6065 for (i = j = 0; i < numkeys; i++) {
6067 mp->mp_ptrs[j] = mp->mp_ptrs[i];
6068 if (mp->mp_ptrs[i] < ptr)
6069 mp->mp_ptrs[j] += sz;
6074 base = (char *)mp + mp->mp_upper;
6075 memmove(base + sz, base, ptr - mp->mp_upper);
6077 mp->mp_lower -= sizeof(indx_t);
6081 /** Compact the main page after deleting a node on a subpage.
6082 * @param[in] mp The main page to operate on.
6083 * @param[in] indx The index of the subpage on the main page.
6086 mdb_node_shrink(MDB_page *mp, indx_t indx)
6093 indx_t i, numkeys, ptr;
6095 node = NODEPTR(mp, indx);
6096 sp = (MDB_page *)NODEDATA(node);
6097 osize = NODEDSZ(node);
6099 delta = sp->mp_upper - sp->mp_lower;
6100 SETDSZ(node, osize - delta);
6101 xp = (MDB_page *)((char *)sp + delta);
6103 /* shift subpage upward */
6105 nsize = NUMKEYS(sp) * sp->mp_pad;
6106 memmove(METADATA(xp), METADATA(sp), nsize);
6109 nsize = osize - sp->mp_upper;
6110 numkeys = NUMKEYS(sp);
6111 for (i=numkeys-1; i>=0; i--)
6112 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
6114 xp->mp_upper = sp->mp_lower;
6115 xp->mp_lower = sp->mp_lower;
6116 xp->mp_flags = sp->mp_flags;
6117 xp->mp_pad = sp->mp_pad;
6118 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
6120 /* shift lower nodes upward */
6121 ptr = mp->mp_ptrs[indx];
6122 numkeys = NUMKEYS(mp);
6123 for (i = 0; i < numkeys; i++) {
6124 if (mp->mp_ptrs[i] <= ptr)
6125 mp->mp_ptrs[i] += delta;
6128 base = (char *)mp + mp->mp_upper;
6129 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
6130 mp->mp_upper += delta;
6133 /** Initial setup of a sorted-dups cursor.
6134 * Sorted duplicates are implemented as a sub-database for the given key.
6135 * The duplicate data items are actually keys of the sub-database.
6136 * Operations on the duplicate data items are performed using a sub-cursor
6137 * initialized when the sub-database is first accessed. This function does
6138 * the preliminary setup of the sub-cursor, filling in the fields that
6139 * depend only on the parent DB.
6140 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6143 mdb_xcursor_init0(MDB_cursor *mc)
6145 MDB_xcursor *mx = mc->mc_xcursor;
6147 mx->mx_cursor.mc_xcursor = NULL;
6148 mx->mx_cursor.mc_txn = mc->mc_txn;
6149 mx->mx_cursor.mc_db = &mx->mx_db;
6150 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
6151 mx->mx_cursor.mc_dbi = mc->mc_dbi+1;
6152 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
6153 mx->mx_cursor.mc_snum = 0;
6154 mx->mx_cursor.mc_top = 0;
6155 mx->mx_cursor.mc_flags = C_SUB;
6156 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
6157 mx->mx_dbx.md_dcmp = NULL;
6158 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
6161 /** Final setup of a sorted-dups cursor.
6162 * Sets up the fields that depend on the data from the main cursor.
6163 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6164 * @param[in] node The data containing the #MDB_db record for the
6165 * sorted-dup database.
6168 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
6170 MDB_xcursor *mx = mc->mc_xcursor;
6172 if (node->mn_flags & F_SUBDATA) {
6173 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
6174 mx->mx_cursor.mc_pg[0] = 0;
6175 mx->mx_cursor.mc_snum = 0;
6176 mx->mx_cursor.mc_flags = C_SUB;
6178 MDB_page *fp = NODEDATA(node);
6179 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
6180 mx->mx_db.md_flags = 0;
6181 mx->mx_db.md_depth = 1;
6182 mx->mx_db.md_branch_pages = 0;
6183 mx->mx_db.md_leaf_pages = 1;
6184 mx->mx_db.md_overflow_pages = 0;
6185 mx->mx_db.md_entries = NUMKEYS(fp);
6186 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
6187 mx->mx_cursor.mc_snum = 1;
6188 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
6189 mx->mx_cursor.mc_top = 0;
6190 mx->mx_cursor.mc_pg[0] = fp;
6191 mx->mx_cursor.mc_ki[0] = 0;
6192 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6193 mx->mx_db.md_flags = MDB_DUPFIXED;
6194 mx->mx_db.md_pad = fp->mp_pad;
6195 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6196 mx->mx_db.md_flags |= MDB_INTEGERKEY;
6199 DPRINTF("Sub-db %u for db %u root page %zu", mx->mx_cursor.mc_dbi, mc->mc_dbi,
6201 mx->mx_dbflag = DB_VALID | (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY) ?
6203 mx->mx_dbx.md_name.mv_data = NODEKEY(node);
6204 mx->mx_dbx.md_name.mv_size = node->mn_ksize;
6205 #if UINT_MAX < SIZE_MAX
6206 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
6207 #ifdef MISALIGNED_OK
6208 mx->mx_dbx.md_cmp = mdb_cmp_long;
6210 mx->mx_dbx.md_cmp = mdb_cmp_cint;
6215 /** Initialize a cursor for a given transaction and database. */
6217 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
6219 mc->mc_backup = NULL;
6222 mc->mc_db = &txn->mt_dbs[dbi];
6223 mc->mc_dbx = &txn->mt_dbxs[dbi];
6224 mc->mc_dbflag = &txn->mt_dbflags[dbi];
6229 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
6231 mc->mc_xcursor = mx;
6232 mdb_xcursor_init0(mc);
6234 mc->mc_xcursor = NULL;
6236 if (*mc->mc_dbflag & DB_STALE) {
6237 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
6242 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
6245 size_t size = sizeof(MDB_cursor);
6247 if (txn == NULL || ret == NULL || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
6250 /* Allow read access to the freelist */
6251 if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
6254 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
6255 size += sizeof(MDB_xcursor);
6257 if ((mc = malloc(size)) != NULL) {
6258 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
6259 if (txn->mt_cursors) {
6260 mc->mc_next = txn->mt_cursors[dbi];
6261 txn->mt_cursors[dbi] = mc;
6262 mc->mc_flags |= C_UNTRACK;
6274 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
6276 if (txn == NULL || mc == NULL || mc->mc_dbi >= txn->mt_numdbs)
6279 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
6282 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
6286 /* Return the count of duplicate data items for the current key */
6288 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
6292 if (mc == NULL || countp == NULL)
6295 if (!(mc->mc_db->md_flags & MDB_DUPSORT))
6298 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6299 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6302 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
6305 *countp = mc->mc_xcursor->mx_db.md_entries;
6311 mdb_cursor_close(MDB_cursor *mc)
6313 if (mc && !mc->mc_backup) {
6314 /* remove from txn, if tracked */
6315 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
6316 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
6317 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
6319 *prev = mc->mc_next;
6326 mdb_cursor_txn(MDB_cursor *mc)
6328 if (!mc) return NULL;
6333 mdb_cursor_dbi(MDB_cursor *mc)
6339 /** Replace the key for a node with a new key.
6340 * @param[in] mc Cursor pointing to the node to operate on.
6341 * @param[in] key The new key to use.
6342 * @return 0 on success, non-zero on failure.
6345 mdb_update_key(MDB_cursor *mc, MDB_val *key)
6352 indx_t ptr, i, numkeys, indx;
6355 indx = mc->mc_ki[mc->mc_top];
6356 mp = mc->mc_pg[mc->mc_top];
6357 node = NODEPTR(mp, indx);
6358 ptr = mp->mp_ptrs[indx];
6362 char kbuf2[(MDB_MAXKEYSIZE*2+1)];
6363 k2.mv_data = NODEKEY(node);
6364 k2.mv_size = node->mn_ksize;
6365 DPRINTF("update key %u (ofs %u) [%s] to [%s] on page %zu",
6367 mdb_dkey(&k2, kbuf2),
6373 delta0 = delta = key->mv_size - node->mn_ksize;
6375 /* Must be 2-byte aligned. If new key is
6376 * shorter by 1, the shift will be skipped.
6378 delta += (delta & 1);
6380 if (delta > 0 && SIZELEFT(mp) < delta) {
6382 /* not enough space left, do a delete and split */
6383 DPRINTF("Not enough room, delta = %d, splitting...", delta);
6384 pgno = NODEPGNO(node);
6385 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
6386 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
6389 numkeys = NUMKEYS(mp);
6390 for (i = 0; i < numkeys; i++) {
6391 if (mp->mp_ptrs[i] <= ptr)
6392 mp->mp_ptrs[i] -= delta;
6395 base = (char *)mp + mp->mp_upper;
6396 len = ptr - mp->mp_upper + NODESIZE;
6397 memmove(base - delta, base, len);
6398 mp->mp_upper -= delta;
6400 node = NODEPTR(mp, indx);
6403 /* But even if no shift was needed, update ksize */
6405 node->mn_ksize = key->mv_size;
6408 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6414 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
6416 /** Move a node from csrc to cdst.
6419 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
6426 unsigned short flags;
6430 /* Mark src and dst as dirty. */
6431 if ((rc = mdb_page_touch(csrc)) ||
6432 (rc = mdb_page_touch(cdst)))
6435 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6436 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
6437 key.mv_size = csrc->mc_db->md_pad;
6438 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
6440 data.mv_data = NULL;
6444 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
6445 assert(!((long)srcnode&1));
6446 srcpg = NODEPGNO(srcnode);
6447 flags = srcnode->mn_flags;
6448 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6449 unsigned int snum = csrc->mc_snum;
6451 /* must find the lowest key below src */
6452 mdb_page_search_lowest(csrc);
6453 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6454 key.mv_size = csrc->mc_db->md_pad;
6455 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6457 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6458 key.mv_size = NODEKSZ(s2);
6459 key.mv_data = NODEKEY(s2);
6461 csrc->mc_snum = snum--;
6462 csrc->mc_top = snum;
6464 key.mv_size = NODEKSZ(srcnode);
6465 key.mv_data = NODEKEY(srcnode);
6467 data.mv_size = NODEDSZ(srcnode);
6468 data.mv_data = NODEDATA(srcnode);
6470 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
6471 unsigned int snum = cdst->mc_snum;
6474 /* must find the lowest key below dst */
6475 mdb_page_search_lowest(cdst);
6476 if (IS_LEAF2(cdst->mc_pg[cdst->mc_top])) {
6477 bkey.mv_size = cdst->mc_db->md_pad;
6478 bkey.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, bkey.mv_size);
6480 s2 = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
6481 bkey.mv_size = NODEKSZ(s2);
6482 bkey.mv_data = NODEKEY(s2);
6484 cdst->mc_snum = snum--;
6485 cdst->mc_top = snum;
6486 mdb_cursor_copy(cdst, &mn);
6488 rc = mdb_update_key(&mn, &bkey);
6493 DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
6494 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
6495 csrc->mc_ki[csrc->mc_top],
6497 csrc->mc_pg[csrc->mc_top]->mp_pgno,
6498 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
6500 /* Add the node to the destination page.
6502 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
6503 if (rc != MDB_SUCCESS)
6506 /* Delete the node from the source page.
6508 mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
6511 /* Adjust other cursors pointing to mp */
6512 MDB_cursor *m2, *m3;
6513 MDB_dbi dbi = csrc->mc_dbi;
6514 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
6516 if (csrc->mc_flags & C_SUB)
6519 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6520 if (csrc->mc_flags & C_SUB)
6521 m3 = &m2->mc_xcursor->mx_cursor;
6524 if (m3 == csrc) continue;
6525 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
6526 csrc->mc_ki[csrc->mc_top]) {
6527 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
6528 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
6533 /* Update the parent separators.
6535 if (csrc->mc_ki[csrc->mc_top] == 0) {
6536 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
6537 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6538 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6540 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6541 key.mv_size = NODEKSZ(srcnode);
6542 key.mv_data = NODEKEY(srcnode);
6544 DPRINTF("update separator for source page %zu to [%s]",
6545 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
6546 mdb_cursor_copy(csrc, &mn);
6549 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
6552 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6554 indx_t ix = csrc->mc_ki[csrc->mc_top];
6555 nullkey.mv_size = 0;
6556 csrc->mc_ki[csrc->mc_top] = 0;
6557 rc = mdb_update_key(csrc, &nullkey);
6558 csrc->mc_ki[csrc->mc_top] = ix;
6559 assert(rc == MDB_SUCCESS);
6563 if (cdst->mc_ki[cdst->mc_top] == 0) {
6564 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
6565 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6566 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
6568 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
6569 key.mv_size = NODEKSZ(srcnode);
6570 key.mv_data = NODEKEY(srcnode);
6572 DPRINTF("update separator for destination page %zu to [%s]",
6573 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
6574 mdb_cursor_copy(cdst, &mn);
6577 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
6580 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
6582 indx_t ix = cdst->mc_ki[cdst->mc_top];
6583 nullkey.mv_size = 0;
6584 cdst->mc_ki[cdst->mc_top] = 0;
6585 rc = mdb_update_key(cdst, &nullkey);
6586 cdst->mc_ki[cdst->mc_top] = ix;
6587 assert(rc == MDB_SUCCESS);
6594 /** Merge one page into another.
6595 * The nodes from the page pointed to by \b csrc will
6596 * be copied to the page pointed to by \b cdst and then
6597 * the \b csrc page will be freed.
6598 * @param[in] csrc Cursor pointing to the source page.
6599 * @param[in] cdst Cursor pointing to the destination page.
6602 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
6610 DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
6611 cdst->mc_pg[cdst->mc_top]->mp_pgno);
6613 assert(csrc->mc_snum > 1); /* can't merge root page */
6614 assert(cdst->mc_snum > 1);
6616 /* Mark dst as dirty. */
6617 if ((rc = mdb_page_touch(cdst)))
6620 /* Move all nodes from src to dst.
6622 j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
6623 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6624 key.mv_size = csrc->mc_db->md_pad;
6625 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
6626 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
6627 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
6628 if (rc != MDB_SUCCESS)
6630 key.mv_data = (char *)key.mv_data + key.mv_size;
6633 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
6634 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
6635 if (i == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6636 unsigned int snum = csrc->mc_snum;
6638 /* must find the lowest key below src */
6639 mdb_page_search_lowest(csrc);
6640 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6641 key.mv_size = csrc->mc_db->md_pad;
6642 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6644 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6645 key.mv_size = NODEKSZ(s2);
6646 key.mv_data = NODEKEY(s2);
6648 csrc->mc_snum = snum--;
6649 csrc->mc_top = snum;
6651 key.mv_size = srcnode->mn_ksize;
6652 key.mv_data = NODEKEY(srcnode);
6655 data.mv_size = NODEDSZ(srcnode);
6656 data.mv_data = NODEDATA(srcnode);
6657 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
6658 if (rc != MDB_SUCCESS)
6663 DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
6664 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);
6666 /* Unlink the src page from parent and add to free list.
6668 mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
6669 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
6672 rc = mdb_update_key(csrc, &key);
6678 rc = mdb_midl_append(&csrc->mc_txn->mt_free_pgs,
6679 csrc->mc_pg[csrc->mc_top]->mp_pgno);
6682 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
6683 csrc->mc_db->md_leaf_pages--;
6685 csrc->mc_db->md_branch_pages--;
6687 /* Adjust other cursors pointing to mp */
6688 MDB_cursor *m2, *m3;
6689 MDB_dbi dbi = csrc->mc_dbi;
6690 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
6692 if (csrc->mc_flags & C_SUB)
6695 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6696 if (csrc->mc_flags & C_SUB)
6697 m3 = &m2->mc_xcursor->mx_cursor;
6700 if (m3 == csrc) continue;
6701 if (m3->mc_snum < csrc->mc_snum) continue;
6702 if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
6703 m3->mc_pg[csrc->mc_top] = mp;
6704 m3->mc_ki[csrc->mc_top] += nkeys;
6708 mdb_cursor_pop(csrc);
6710 return mdb_rebalance(csrc);
6713 /** Copy the contents of a cursor.
6714 * @param[in] csrc The cursor to copy from.
6715 * @param[out] cdst The cursor to copy to.
6718 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
6722 cdst->mc_txn = csrc->mc_txn;
6723 cdst->mc_dbi = csrc->mc_dbi;
6724 cdst->mc_db = csrc->mc_db;
6725 cdst->mc_dbx = csrc->mc_dbx;
6726 cdst->mc_snum = csrc->mc_snum;
6727 cdst->mc_top = csrc->mc_top;
6728 cdst->mc_flags = csrc->mc_flags;
6730 for (i=0; i<csrc->mc_snum; i++) {
6731 cdst->mc_pg[i] = csrc->mc_pg[i];
6732 cdst->mc_ki[i] = csrc->mc_ki[i];
6736 /** Rebalance the tree after a delete operation.
6737 * @param[in] mc Cursor pointing to the page where rebalancing
6739 * @return 0 on success, non-zero on failure.
6742 mdb_rebalance(MDB_cursor *mc)
6746 unsigned int ptop, minkeys;
6749 minkeys = 1 + (IS_BRANCH(mc->mc_pg[mc->mc_top]));
6753 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
6754 DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
6755 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
6756 pgno, NUMKEYS(mc->mc_pg[mc->mc_top]), (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10);
6760 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD &&
6761 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
6764 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
6765 DPRINTF("no need to rebalance page %zu, above fill threshold",
6771 if (mc->mc_snum < 2) {
6772 MDB_page *mp = mc->mc_pg[0];
6774 DPUTS("Can't rebalance a subpage, ignoring");
6777 if (NUMKEYS(mp) == 0) {
6778 DPUTS("tree is completely empty");
6779 mc->mc_db->md_root = P_INVALID;
6780 mc->mc_db->md_depth = 0;
6781 mc->mc_db->md_leaf_pages = 0;
6782 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
6785 /* Adjust cursors pointing to mp */
6789 MDB_cursor *m2, *m3;
6790 MDB_dbi dbi = mc->mc_dbi;
6792 if (mc->mc_flags & C_SUB)
6795 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6796 if (mc->mc_flags & C_SUB)
6797 m3 = &m2->mc_xcursor->mx_cursor;
6800 if (m3->mc_snum < mc->mc_snum) continue;
6801 if (m3->mc_pg[0] == mp) {
6807 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
6808 DPUTS("collapsing root page!");
6809 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
6812 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
6813 rc = mdb_page_get(mc->mc_txn,mc->mc_db->md_root,&mc->mc_pg[0],NULL);
6816 mc->mc_db->md_depth--;
6817 mc->mc_db->md_branch_pages--;
6818 mc->mc_ki[0] = mc->mc_ki[1];
6820 /* Adjust other cursors pointing to mp */
6821 MDB_cursor *m2, *m3;
6822 MDB_dbi dbi = mc->mc_dbi;
6824 if (mc->mc_flags & C_SUB)
6827 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6828 if (mc->mc_flags & C_SUB)
6829 m3 = &m2->mc_xcursor->mx_cursor;
6832 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
6833 if (m3->mc_pg[0] == mp) {
6834 m3->mc_pg[0] = mc->mc_pg[0];
6837 m3->mc_ki[0] = m3->mc_ki[1];
6842 DPUTS("root page doesn't need rebalancing");
6846 /* The parent (branch page) must have at least 2 pointers,
6847 * otherwise the tree is invalid.
6849 ptop = mc->mc_top-1;
6850 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
6852 /* Leaf page fill factor is below the threshold.
6853 * Try to move keys from left or right neighbor, or
6854 * merge with a neighbor page.
6859 mdb_cursor_copy(mc, &mn);
6860 mn.mc_xcursor = NULL;
6862 if (mc->mc_ki[ptop] == 0) {
6863 /* We're the leftmost leaf in our parent.
6865 DPUTS("reading right neighbor");
6867 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
6868 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
6871 mn.mc_ki[mn.mc_top] = 0;
6872 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
6874 /* There is at least one neighbor to the left.
6876 DPUTS("reading left neighbor");
6878 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
6879 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
6882 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
6883 mc->mc_ki[mc->mc_top] = 0;
6886 DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
6887 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);
6889 /* If the neighbor page is above threshold and has enough keys,
6890 * move one key from it. Otherwise we should try to merge them.
6891 * (A branch page must never have less than 2 keys.)
6893 minkeys = 1 + (IS_BRANCH(mn.mc_pg[mn.mc_top]));
6894 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys)
6895 return mdb_node_move(&mn, mc);
6897 if (mc->mc_ki[ptop] == 0)
6898 rc = mdb_page_merge(&mn, mc);
6900 rc = mdb_page_merge(mc, &mn);
6901 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
6906 /** Complete a delete operation started by #mdb_cursor_del(). */
6908 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
6914 mp = mc->mc_pg[mc->mc_top];
6915 ki = mc->mc_ki[mc->mc_top];
6917 /* add overflow pages to free list */
6918 if (!IS_LEAF2(mp) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6922 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
6923 if ((rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL)) ||
6924 (rc = mdb_ovpage_free(mc, omp)))
6927 mdb_node_del(mp, ki, mc->mc_db->md_pad);
6928 mc->mc_db->md_entries--;
6929 rc = mdb_rebalance(mc);
6930 if (rc != MDB_SUCCESS)
6931 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6932 /* if mc points past last node in page, invalidate */
6933 else if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6934 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
6937 /* Adjust other cursors pointing to mp */
6940 MDB_dbi dbi = mc->mc_dbi;
6942 mp = mc->mc_pg[mc->mc_top];
6943 nkeys = NUMKEYS(mp);
6944 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6947 if (!(m2->mc_flags & C_INITIALIZED))
6949 if (m2->mc_pg[mc->mc_top] == mp) {
6950 if (m2->mc_ki[mc->mc_top] > ki)
6951 m2->mc_ki[mc->mc_top]--;
6952 if (m2->mc_ki[mc->mc_top] >= nkeys)
6953 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
6962 mdb_del(MDB_txn *txn, MDB_dbi dbi,
6963 MDB_val *key, MDB_val *data)
6968 MDB_val rdata, *xdata;
6972 assert(key != NULL);
6974 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
6976 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
6979 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
6983 if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
6987 mdb_cursor_init(&mc, txn, dbi, &mx);
6998 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
7000 /* let mdb_page_split know about this cursor if needed:
7001 * delete will trigger a rebalance; if it needs to move
7002 * a node from one page to another, it will have to
7003 * update the parent's separator key(s). If the new sepkey
7004 * is larger than the current one, the parent page may
7005 * run out of space, triggering a split. We need this
7006 * cursor to be consistent until the end of the rebalance.
7008 mc.mc_flags |= C_UNTRACK;
7009 mc.mc_next = txn->mt_cursors[dbi];
7010 txn->mt_cursors[dbi] = &mc;
7011 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
7012 txn->mt_cursors[dbi] = mc.mc_next;
7017 /** Split a page and insert a new node.
7018 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
7019 * The cursor will be updated to point to the actual page and index where
7020 * the node got inserted after the split.
7021 * @param[in] newkey The key for the newly inserted node.
7022 * @param[in] newdata The data for the newly inserted node.
7023 * @param[in] newpgno The page number, if the new node is a branch node.
7024 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
7025 * @return 0 on success, non-zero on failure.
7028 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
7029 unsigned int nflags)
7032 int rc = MDB_SUCCESS, ins_new = 0, new_root = 0, newpos = 1, did_split = 0;
7035 unsigned int i, j, split_indx, nkeys, pmax;
7037 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
7039 MDB_page *mp, *rp, *pp;
7044 mp = mc->mc_pg[mc->mc_top];
7045 newindx = mc->mc_ki[mc->mc_top];
7047 DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
7048 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
7049 DKEY(newkey), mc->mc_ki[mc->mc_top]);
7051 /* Create a right sibling. */
7052 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
7054 DPRINTF("new right sibling: page %zu", rp->mp_pgno);
7056 if (mc->mc_snum < 2) {
7057 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
7059 /* shift current top to make room for new parent */
7060 mc->mc_pg[1] = mc->mc_pg[0];
7061 mc->mc_ki[1] = mc->mc_ki[0];
7064 mc->mc_db->md_root = pp->mp_pgno;
7065 DPRINTF("root split! new root = %zu", pp->mp_pgno);
7066 mc->mc_db->md_depth++;
7069 /* Add left (implicit) pointer. */
7070 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
7071 /* undo the pre-push */
7072 mc->mc_pg[0] = mc->mc_pg[1];
7073 mc->mc_ki[0] = mc->mc_ki[1];
7074 mc->mc_db->md_root = mp->mp_pgno;
7075 mc->mc_db->md_depth--;
7082 ptop = mc->mc_top-1;
7083 DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
7086 mc->mc_flags |= C_SPLITTING;
7087 mdb_cursor_copy(mc, &mn);
7088 mn.mc_pg[mn.mc_top] = rp;
7089 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
7091 if (nflags & MDB_APPEND) {
7092 mn.mc_ki[mn.mc_top] = 0;
7094 split_indx = newindx;
7099 nkeys = NUMKEYS(mp);
7100 split_indx = nkeys / 2;
7101 if (newindx < split_indx)
7107 unsigned int lsize, rsize, ksize;
7108 /* Move half of the keys to the right sibling */
7110 x = mc->mc_ki[mc->mc_top] - split_indx;
7111 ksize = mc->mc_db->md_pad;
7112 split = LEAF2KEY(mp, split_indx, ksize);
7113 rsize = (nkeys - split_indx) * ksize;
7114 lsize = (nkeys - split_indx) * sizeof(indx_t);
7115 mp->mp_lower -= lsize;
7116 rp->mp_lower += lsize;
7117 mp->mp_upper += rsize - lsize;
7118 rp->mp_upper -= rsize - lsize;
7119 sepkey.mv_size = ksize;
7120 if (newindx == split_indx) {
7121 sepkey.mv_data = newkey->mv_data;
7123 sepkey.mv_data = split;
7126 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
7127 memcpy(rp->mp_ptrs, split, rsize);
7128 sepkey.mv_data = rp->mp_ptrs;
7129 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
7130 memcpy(ins, newkey->mv_data, ksize);
7131 mp->mp_lower += sizeof(indx_t);
7132 mp->mp_upper -= ksize - sizeof(indx_t);
7135 memcpy(rp->mp_ptrs, split, x * ksize);
7136 ins = LEAF2KEY(rp, x, ksize);
7137 memcpy(ins, newkey->mv_data, ksize);
7138 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
7139 rp->mp_lower += sizeof(indx_t);
7140 rp->mp_upper -= ksize - sizeof(indx_t);
7141 mc->mc_ki[mc->mc_top] = x;
7142 mc->mc_pg[mc->mc_top] = rp;
7147 /* For leaf pages, check the split point based on what
7148 * fits where, since otherwise mdb_node_add can fail.
7150 * This check is only needed when the data items are
7151 * relatively large, such that being off by one will
7152 * make the difference between success or failure.
7154 * It's also relevant if a page happens to be laid out
7155 * such that one half of its nodes are all "small" and
7156 * the other half of its nodes are "large." If the new
7157 * item is also "large" and falls on the half with
7158 * "large" nodes, it also may not fit.
7161 unsigned int psize, nsize;
7162 /* Maximum free space in an empty page */
7163 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
7164 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
7165 if ((nkeys < 20) || (nsize > pmax/16)) {
7166 if (newindx <= split_indx) {
7169 for (i=0; i<split_indx; i++) {
7170 node = NODEPTR(mp, i);
7171 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
7172 if (F_ISSET(node->mn_flags, F_BIGDATA))
7173 psize += sizeof(pgno_t);
7175 psize += NODEDSZ(node);
7179 split_indx = newindx;
7190 for (i=nkeys-1; i>=split_indx; i--) {
7191 node = NODEPTR(mp, i);
7192 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
7193 if (F_ISSET(node->mn_flags, F_BIGDATA))
7194 psize += sizeof(pgno_t);
7196 psize += NODEDSZ(node);
7200 split_indx = newindx;
7211 /* First find the separating key between the split pages.
7212 * The case where newindx == split_indx is ambiguous; the
7213 * new item could go to the new page or stay on the original
7214 * page. If newpos == 1 it goes to the new page.
7216 if (newindx == split_indx && newpos) {
7217 sepkey.mv_size = newkey->mv_size;
7218 sepkey.mv_data = newkey->mv_data;
7220 node = NODEPTR(mp, split_indx);
7221 sepkey.mv_size = node->mn_ksize;
7222 sepkey.mv_data = NODEKEY(node);
7226 DPRINTF("separator is [%s]", DKEY(&sepkey));
7228 /* Copy separator key to the parent.
7230 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
7234 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
7237 if (mn.mc_snum == mc->mc_snum) {
7238 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
7239 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
7240 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
7241 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
7246 /* Right page might now have changed parent.
7247 * Check if left page also changed parent.
7249 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7250 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7251 for (i=0; i<ptop; i++) {
7252 mc->mc_pg[i] = mn.mc_pg[i];
7253 mc->mc_ki[i] = mn.mc_ki[i];
7255 mc->mc_pg[ptop] = mn.mc_pg[ptop];
7256 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
7260 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
7263 mc->mc_flags ^= C_SPLITTING;
7264 if (rc != MDB_SUCCESS) {
7267 if (nflags & MDB_APPEND) {
7268 mc->mc_pg[mc->mc_top] = rp;
7269 mc->mc_ki[mc->mc_top] = 0;
7270 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
7273 for (i=0; i<mc->mc_top; i++)
7274 mc->mc_ki[i] = mn.mc_ki[i];
7281 /* Move half of the keys to the right sibling. */
7283 /* grab a page to hold a temporary copy */
7284 copy = mdb_page_malloc(mc->mc_txn, 1);
7288 copy->mp_pgno = mp->mp_pgno;
7289 copy->mp_flags = mp->mp_flags;
7290 copy->mp_lower = PAGEHDRSZ;
7291 copy->mp_upper = mc->mc_txn->mt_env->me_psize;
7292 mc->mc_pg[mc->mc_top] = copy;
7293 for (i = j = 0; i <= nkeys; j++) {
7294 if (i == split_indx) {
7295 /* Insert in right sibling. */
7296 /* Reset insert index for right sibling. */
7297 if (i != newindx || (newpos ^ ins_new)) {
7299 mc->mc_pg[mc->mc_top] = rp;
7303 if (i == newindx && !ins_new) {
7304 /* Insert the original entry that caused the split. */
7305 rkey.mv_data = newkey->mv_data;
7306 rkey.mv_size = newkey->mv_size;
7315 /* Update index for the new key. */
7316 mc->mc_ki[mc->mc_top] = j;
7317 } else if (i == nkeys) {
7320 node = NODEPTR(mp, i);
7321 rkey.mv_data = NODEKEY(node);
7322 rkey.mv_size = node->mn_ksize;
7324 xdata.mv_data = NODEDATA(node);
7325 xdata.mv_size = NODEDSZ(node);
7328 pgno = NODEPGNO(node);
7329 flags = node->mn_flags;
7334 if (!IS_LEAF(mp) && j == 0) {
7335 /* First branch index doesn't need key data. */
7339 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
7343 nkeys = NUMKEYS(copy);
7344 for (i=0; i<nkeys; i++)
7345 mp->mp_ptrs[i] = copy->mp_ptrs[i];
7346 mp->mp_lower = copy->mp_lower;
7347 mp->mp_upper = copy->mp_upper;
7348 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
7349 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
7351 /* reset back to original page */
7352 if (newindx < split_indx || (!newpos && newindx == split_indx)) {
7353 mc->mc_pg[mc->mc_top] = mp;
7354 if (nflags & MDB_RESERVE) {
7355 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7356 if (!(node->mn_flags & F_BIGDATA))
7357 newdata->mv_data = NODEDATA(node);
7361 /* Make sure mc_ki is still valid.
7363 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7364 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7365 for (i=0; i<ptop; i++) {
7366 mc->mc_pg[i] = mn.mc_pg[i];
7367 mc->mc_ki[i] = mn.mc_ki[i];
7369 mc->mc_pg[ptop] = mn.mc_pg[ptop];
7370 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
7374 /* return tmp page to freelist */
7375 mdb_page_free(mc->mc_txn->mt_env, copy);
7378 /* Adjust other cursors pointing to mp */
7379 MDB_cursor *m2, *m3;
7380 MDB_dbi dbi = mc->mc_dbi;
7381 int fixup = NUMKEYS(mp);
7383 if (mc->mc_flags & C_SUB)
7386 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7387 if (mc->mc_flags & C_SUB)
7388 m3 = &m2->mc_xcursor->mx_cursor;
7393 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
7395 if (m3->mc_flags & C_SPLITTING)
7400 for (k=m3->mc_top; k>=0; k--) {
7401 m3->mc_ki[k+1] = m3->mc_ki[k];
7402 m3->mc_pg[k+1] = m3->mc_pg[k];
7404 if (m3->mc_ki[0] >= split_indx) {
7409 m3->mc_pg[0] = mc->mc_pg[0];
7413 if (m3->mc_pg[mc->mc_top] == mp) {
7414 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
7415 m3->mc_ki[mc->mc_top]++;
7416 if (m3->mc_ki[mc->mc_top] >= fixup) {
7417 m3->mc_pg[mc->mc_top] = rp;
7418 m3->mc_ki[mc->mc_top] -= fixup;
7419 m3->mc_ki[ptop] = mn.mc_ki[ptop];
7421 } else if (!did_split && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
7422 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
7431 mdb_put(MDB_txn *txn, MDB_dbi dbi,
7432 MDB_val *key, MDB_val *data, unsigned int flags)
7437 assert(key != NULL);
7438 assert(data != NULL);
7440 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7443 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
7447 if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
7451 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP)) != flags)
7454 mdb_cursor_init(&mc, txn, dbi, &mx);
7455 return mdb_cursor_put(&mc, key, data, flags);
7459 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
7461 if ((flag & CHANGEABLE) != flag)
7464 env->me_flags |= flag;
7466 env->me_flags &= ~flag;
7471 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
7476 *arg = env->me_flags;
7481 mdb_env_get_path(MDB_env *env, const char **arg)
7486 *arg = env->me_path;
7490 /** Common code for #mdb_stat() and #mdb_env_stat().
7491 * @param[in] env the environment to operate in.
7492 * @param[in] db the #MDB_db record containing the stats to return.
7493 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
7494 * @return 0, this function always succeeds.
7497 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
7499 arg->ms_psize = env->me_psize;
7500 arg->ms_depth = db->md_depth;
7501 arg->ms_branch_pages = db->md_branch_pages;
7502 arg->ms_leaf_pages = db->md_leaf_pages;
7503 arg->ms_overflow_pages = db->md_overflow_pages;
7504 arg->ms_entries = db->md_entries;
7509 mdb_env_stat(MDB_env *env, MDB_stat *arg)
7513 if (env == NULL || arg == NULL)
7516 toggle = mdb_env_pick_meta(env);
7518 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
7522 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
7526 if (env == NULL || arg == NULL)
7529 toggle = mdb_env_pick_meta(env);
7530 arg->me_mapaddr = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : 0;
7531 arg->me_mapsize = env->me_mapsize;
7532 arg->me_maxreaders = env->me_maxreaders;
7533 arg->me_numreaders = env->me_numreaders;
7534 arg->me_last_pgno = env->me_metas[toggle]->mm_last_pg;
7535 arg->me_last_txnid = env->me_metas[toggle]->mm_txnid;
7539 /** Set the default comparison functions for a database.
7540 * Called immediately after a database is opened to set the defaults.
7541 * The user can then override them with #mdb_set_compare() or
7542 * #mdb_set_dupsort().
7543 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
7544 * @param[in] dbi A database handle returned by #mdb_dbi_open()
7547 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
7549 uint16_t f = txn->mt_dbs[dbi].md_flags;
7551 txn->mt_dbxs[dbi].md_cmp =
7552 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
7553 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
7555 txn->mt_dbxs[dbi].md_dcmp =
7556 !(f & MDB_DUPSORT) ? 0 :
7557 ((f & MDB_INTEGERDUP)
7558 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
7559 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
7562 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
7567 int rc, dbflag, exact;
7568 unsigned int unused = 0;
7571 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
7572 mdb_default_cmp(txn, FREE_DBI);
7575 if ((flags & VALID_FLAGS) != flags)
7581 if (flags & PERSISTENT_FLAGS) {
7582 uint16_t f2 = flags & PERSISTENT_FLAGS;
7583 /* make sure flag changes get committed */
7584 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
7585 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
7586 txn->mt_flags |= MDB_TXN_DIRTY;
7589 mdb_default_cmp(txn, MAIN_DBI);
7593 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
7594 mdb_default_cmp(txn, MAIN_DBI);
7597 /* Is the DB already open? */
7599 for (i=2; i<txn->mt_numdbs; i++) {
7600 if (!txn->mt_dbxs[i].md_name.mv_size) {
7601 /* Remember this free slot */
7602 if (!unused) unused = i;
7605 if (len == txn->mt_dbxs[i].md_name.mv_size &&
7606 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
7612 /* If no free slot and max hit, fail */
7613 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
7614 return MDB_DBS_FULL;
7616 /* Cannot mix named databases with some mainDB flags */
7617 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
7618 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
7620 /* Find the DB info */
7621 dbflag = DB_NEW|DB_VALID;
7624 key.mv_data = (void *)name;
7625 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
7626 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
7627 if (rc == MDB_SUCCESS) {
7628 /* make sure this is actually a DB */
7629 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
7630 if (!(node->mn_flags & F_SUBDATA))
7632 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
7633 /* Create if requested */
7635 data.mv_size = sizeof(MDB_db);
7636 data.mv_data = &dummy;
7637 memset(&dummy, 0, sizeof(dummy));
7638 dummy.md_root = P_INVALID;
7639 dummy.md_flags = flags & PERSISTENT_FLAGS;
7640 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
7644 /* OK, got info, add to table */
7645 if (rc == MDB_SUCCESS) {
7646 unsigned int slot = unused ? unused : txn->mt_numdbs;
7647 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
7648 txn->mt_dbxs[slot].md_name.mv_size = len;
7649 txn->mt_dbxs[slot].md_rel = NULL;
7650 txn->mt_dbflags[slot] = dbflag;
7651 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
7653 txn->mt_env->me_dbflags[slot] = txn->mt_dbs[slot].md_flags;
7654 mdb_default_cmp(txn, slot);
7663 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
7665 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
7668 if (txn->mt_dbflags[dbi] & DB_STALE) {
7671 /* Stale, must read the DB's root. cursor_init does it for us. */
7672 mdb_cursor_init(&mc, txn, dbi, &mx);
7674 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
7677 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
7680 if (dbi <= MAIN_DBI || dbi >= env->me_maxdbs)
7682 ptr = env->me_dbxs[dbi].md_name.mv_data;
7683 env->me_dbxs[dbi].md_name.mv_data = NULL;
7684 env->me_dbxs[dbi].md_name.mv_size = 0;
7685 env->me_dbflags[dbi] = 0;
7689 /** Add all the DB's pages to the free list.
7690 * @param[in] mc Cursor on the DB to free.
7691 * @param[in] subs non-Zero to check for sub-DBs in this DB.
7692 * @return 0 on success, non-zero on failure.
7695 mdb_drop0(MDB_cursor *mc, int subs)
7699 rc = mdb_page_search(mc, NULL, 0);
7700 if (rc == MDB_SUCCESS) {
7701 MDB_txn *txn = mc->mc_txn;
7706 /* LEAF2 pages have no nodes, cannot have sub-DBs */
7707 if (IS_LEAF2(mc->mc_pg[mc->mc_top]))
7710 mdb_cursor_copy(mc, &mx);
7711 while (mc->mc_snum > 0) {
7712 MDB_page *mp = mc->mc_pg[mc->mc_top];
7713 unsigned n = NUMKEYS(mp);
7715 for (i=0; i<n; i++) {
7716 ni = NODEPTR(mp, i);
7717 if (ni->mn_flags & F_BIGDATA) {
7720 memcpy(&pg, NODEDATA(ni), sizeof(pg));
7721 rc = mdb_page_get(txn, pg, &omp, NULL);
7724 assert(IS_OVERFLOW(omp));
7725 rc = mdb_midl_append_range(&txn->mt_free_pgs,
7729 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
7730 mdb_xcursor_init1(mc, ni);
7731 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
7737 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
7739 for (i=0; i<n; i++) {
7741 ni = NODEPTR(mp, i);
7744 mdb_midl_xappend(txn->mt_free_pgs, pg);
7749 mc->mc_ki[mc->mc_top] = i;
7750 rc = mdb_cursor_sibling(mc, 1);
7752 /* no more siblings, go back to beginning
7753 * of previous level.
7757 for (i=1; i<mc->mc_snum; i++) {
7759 mc->mc_pg[i] = mx.mc_pg[i];
7764 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
7765 } else if (rc == MDB_NOTFOUND) {
7771 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
7773 MDB_cursor *mc, *m2;
7776 if (!txn || !dbi || dbi >= txn->mt_numdbs || (unsigned)del > 1 || !(txn->mt_dbflags[dbi] & DB_VALID))
7779 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
7782 rc = mdb_cursor_open(txn, dbi, &mc);
7786 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
7787 /* Invalidate the dropped DB's cursors */
7788 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
7789 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
7793 /* Can't delete the main DB */
7794 if (del && dbi > MAIN_DBI) {
7795 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
7797 txn->mt_dbflags[dbi] = DB_STALE;
7798 mdb_dbi_close(txn->mt_env, dbi);
7801 /* reset the DB record, mark it dirty */
7802 txn->mt_dbflags[dbi] |= DB_DIRTY;
7803 txn->mt_dbs[dbi].md_depth = 0;
7804 txn->mt_dbs[dbi].md_branch_pages = 0;
7805 txn->mt_dbs[dbi].md_leaf_pages = 0;
7806 txn->mt_dbs[dbi].md_overflow_pages = 0;
7807 txn->mt_dbs[dbi].md_entries = 0;
7808 txn->mt_dbs[dbi].md_root = P_INVALID;
7810 txn->mt_flags |= MDB_TXN_DIRTY;
7813 mdb_cursor_close(mc);
7817 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
7819 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7822 txn->mt_dbxs[dbi].md_cmp = cmp;
7826 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
7828 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7831 txn->mt_dbxs[dbi].md_dcmp = cmp;
7835 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
7837 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7840 txn->mt_dbxs[dbi].md_rel = rel;
7844 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
7846 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7849 txn->mt_dbxs[dbi].md_relctx = ctx;