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 /* Set or clear P_KEEP in non-overflow, non-sub pages in known cursors.
1330 * When clearing, only consider backup cursors (from parent txns) since
1331 * other P_KEEP flags have already been cleared.
1332 * @param[in] mc A cursor handle for the current operation.
1333 * @param[in] pflags Flags of the pages to update:
1334 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1337 mdb_cursorpages_mark(MDB_cursor *mc, unsigned pflags)
1339 MDB_txn *txn = mc->mc_txn;
1340 MDB_cursor *m2, *m3;
1344 if (mc->mc_flags & C_UNTRACK)
1345 mc = NULL; /* will find mc in mt_cursors */
1346 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1347 for (; mc; mc=mc->mc_next) {
1348 m2 = pflags == P_DIRTY ? mc : mc->mc_backup;
1349 for (; m2; m2 = m2->mc_backup) {
1350 for (m3=m2; m3->mc_flags & C_INITIALIZED; m3=&mx->mx_cursor) {
1351 for (j=0; j<m3->mc_snum; j++)
1352 if ((m3->mc_pg[j]->mp_flags & (P_SUBP|P_DIRTY|P_KEEP))
1354 m3->mc_pg[j]->mp_flags ^= P_KEEP;
1355 if (!(m3->mc_db->md_flags & MDB_DUPSORT))
1357 /* Cursor backups have mx malloced at the end of m2 */
1358 mx = (m3 == mc ? m3->mc_xcursor : (MDB_xcursor *)(m3+1));
1367 static int mdb_page_flush(MDB_txn *txn);
1369 /** Spill pages from the dirty list back to disk.
1370 * This is intended to prevent running into #MDB_TXN_FULL situations,
1371 * but note that they may still occur in a few cases:
1372 * 1) pages in #MDB_DUPSORT sub-DBs are never spilled, so if there
1373 * are too many of these dirtied in one txn, the txn may still get
1375 * 2) child txns may run out of space if their parents dirtied a
1376 * lot of pages and never spilled them. TODO: we probably should do
1377 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1378 * the parent's dirty_room is below a given threshold.
1379 * 3) our estimate of the txn size could be too small. At the
1380 * moment this seems unlikely.
1382 * Otherwise, if not using nested txns, it is expected that apps will
1383 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1384 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1385 * If the txn never references them again, they can be left alone.
1386 * If the txn only reads them, they can be used without any fuss.
1387 * If the txn writes them again, they can be dirtied immediately without
1388 * going thru all of the work of #mdb_page_touch(). Such references are
1389 * handled by #mdb_page_unspill().
1391 * Also note, we never spill DB root pages, nor pages of active cursors,
1392 * because we'll need these back again soon anyway. And in nested txns,
1393 * we can't spill a page in a child txn if it was already spilled in a
1394 * parent txn. That would alter the parent txns' data even though
1395 * the child hasn't committed yet, and we'd have no way to undo it if
1396 * the child aborted.
1398 * @param[in] m0 cursor A cursor handle identifying the transaction and
1399 * database for which we are checking space.
1400 * @param[in] key For a put operation, the key being stored.
1401 * @param[in] data For a put operation, the data being stored.
1402 * @return 0 on success, non-zero on failure.
1405 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1407 MDB_txn *txn = m0->mc_txn;
1409 MDB_ID2L dl = txn->mt_u.dirty_list;
1413 if (m0->mc_flags & C_SUB)
1416 /* Estimate how much space this op will take */
1417 i = m0->mc_db->md_depth;
1418 /* Named DBs also dirty the main DB */
1419 if (m0->mc_dbi > MAIN_DBI)
1420 i += txn->mt_dbs[MAIN_DBI].md_depth;
1421 /* For puts, roughly factor in the key+data size */
1423 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
1424 i += i; /* double it for good measure */
1426 if (txn->mt_dirty_room > i)
1429 if (!txn->mt_spill_pgs) {
1430 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
1431 if (!txn->mt_spill_pgs)
1435 /* Mark all the dirty root pages we want to preserve */
1436 for (i=0; i<txn->mt_numdbs; i++) {
1437 if (txn->mt_dbflags[i] & DB_DIRTY) {
1438 j = mdb_mid2l_search(dl, txn->mt_dbs[i].md_root);
1439 if (j <= dl[0].mid) {
1441 dp->mp_flags |= P_KEEP;
1446 /* Preserve pages used by cursors */
1447 mdb_cursorpages_mark(m0, P_DIRTY);
1449 /* Save the page IDs of all the pages we're flushing */
1450 for (i=1; i<=dl[0].mid; i++) {
1452 if (dp->mp_flags & P_KEEP)
1454 /* Can't spill twice, make sure it's not already in a parent's
1457 if (txn->mt_parent) {
1459 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1460 if (tx2->mt_spill_pgs) {
1461 j = mdb_midl_search(tx2->mt_spill_pgs, dl[i].mid);
1462 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == dl[i].mid) {
1463 dp->mp_flags |= P_KEEP;
1471 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, dl[i].mid)))
1474 mdb_midl_sort(txn->mt_spill_pgs);
1476 rc = mdb_page_flush(txn);
1478 mdb_cursorpages_mark(m0, P_DIRTY|P_KEEP);
1481 if (txn->mt_parent) {
1483 pgno_t pgno = dl[i].mid;
1484 txn->mt_dirty_room = txn->mt_parent->mt_dirty_room - dl[0].mid;
1485 /* dirty pages that are dirty in an ancestor don't
1486 * count against this txn's dirty_room.
1488 for (i=1; i<=dl[0].mid; i++) {
1489 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1490 j = mdb_mid2l_search(tx2->mt_u.dirty_list, pgno);
1491 if (j <= tx2->mt_u.dirty_list[0].mid &&
1492 tx2->mt_u.dirty_list[j].mid == pgno) {
1493 txn->mt_dirty_room++;
1499 txn->mt_dirty_room = MDB_IDL_UM_MAX - dl[0].mid;
1501 txn->mt_flags |= MDB_TXN_SPILLS;
1506 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
1508 mdb_find_oldest(MDB_txn *txn)
1511 txnid_t mr, oldest = txn->mt_txnid - 1;
1512 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
1513 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
1523 /** Add a page to the txn's dirty list */
1525 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
1528 int (*insert)(MDB_ID2L, MDB_ID2 *);
1530 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1531 insert = mdb_mid2l_append;
1533 insert = mdb_mid2l_insert;
1535 mid.mid = mp->mp_pgno;
1537 insert(txn->mt_u.dirty_list, &mid);
1538 txn->mt_dirty_room--;
1541 /** Allocate pages for writing.
1542 * If there are free pages available from older transactions, they
1543 * will be re-used first. Otherwise a new page will be allocated.
1544 * @param[in] mc cursor A cursor handle identifying the transaction and
1545 * database for which we are allocating.
1546 * @param[in] num the number of pages to allocate.
1547 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
1548 * will always be satisfied by a single contiguous chunk of memory.
1549 * @return 0 on success, non-zero on failure.
1552 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
1554 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
1555 /* Get at most <Max_retries> more freeDB records once me_pghead
1556 * has enough pages. If not enough, use new pages from the map.
1557 * If <Paranoid> and mc is updating the freeDB, only get new
1558 * records if me_pghead is empty. Then the freelist cannot play
1559 * catch-up with itself by growing while trying to save it.
1561 enum { Paranoid = 1, Max_retries = 500 };
1563 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
1565 int rc, n2 = num-1, retry = Max_retries;
1566 MDB_txn *txn = mc->mc_txn;
1567 MDB_env *env = txn->mt_env;
1568 pgno_t pgno, *mop = env->me_pghead;
1569 unsigned i, j, k, mop_len = mop ? mop[0] : 0;
1571 txnid_t oldest = 0, last;
1577 /* If our dirty list is already full, we can't do anything */
1578 if (txn->mt_dirty_room == 0)
1579 return MDB_TXN_FULL;
1581 for (op = MDB_FIRST;; op = MDB_NEXT) {
1584 pgno_t *idl, old_id, new_id;
1586 /* Seek a big enough contiguous page range. Prefer
1587 * pages at the tail, just truncating the list.
1589 if (mop_len >= (unsigned)num) {
1593 if (mop[i-n2] == pgno+n2)
1595 } while (--i >= (unsigned)num);
1596 if (Max_retries < INT_MAX && --retry < 0)
1600 if (op == MDB_FIRST) { /* 1st iteration */
1601 /* Prepare to fetch more and coalesce */
1602 oldest = mdb_find_oldest(txn);
1603 last = env->me_pglast;
1604 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1607 key.mv_data = &last; /* will loop up last+1 */
1608 key.mv_size = sizeof(last);
1610 if (Paranoid && mc->mc_dbi == FREE_DBI)
1613 if (Paranoid && retry < 0 && mop_len)
1617 /* Do not fetch more if the record will be too recent */
1620 rc = mdb_cursor_get(&m2, &key, NULL, op);
1622 if (rc == MDB_NOTFOUND)
1626 last = *(txnid_t*)key.mv_data;
1629 np = m2.mc_pg[m2.mc_top];
1630 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
1631 if ((rc = mdb_node_read(txn, leaf, &data)) != MDB_SUCCESS)
1634 idl = (MDB_ID *) data.mv_data;
1637 if (!(env->me_pghead = mop = mdb_midl_alloc(i)))
1640 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
1642 mop = env->me_pghead;
1644 env->me_pglast = last;
1646 DPRINTF("IDL read txn %zu root %zu num %u",
1647 last, txn->mt_dbs[FREE_DBI].md_root, i);
1649 DPRINTF("IDL %zu", idl[k]);
1651 /* Merge in descending sorted order */
1654 mop[0] = (pgno_t)-1;
1658 for (; old_id < new_id; old_id = mop[--j])
1665 /* Use new pages from the map when nothing suitable in the freeDB */
1667 pgno = txn->mt_next_pgno;
1668 if (pgno + num >= env->me_maxpg) {
1669 DPUTS("DB size maxed out");
1670 return MDB_MAP_FULL;
1674 if (env->me_flags & MDB_WRITEMAP) {
1675 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
1677 if (!(np = mdb_page_malloc(txn, num)))
1681 mop[0] = mop_len -= num;
1682 /* Move any stragglers down */
1683 for (j = i-num; j < mop_len; )
1684 mop[++j] = mop[++i];
1686 txn->mt_next_pgno = pgno + num;
1689 mdb_page_dirty(txn, np);
1695 /** Copy the used portions of a non-overflow page.
1696 * @param[in] dst page to copy into
1697 * @param[in] src page to copy from
1698 * @param[in] psize size of a page
1701 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
1703 enum { Align = sizeof(pgno_t) };
1704 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
1706 /* If page isn't full, just copy the used portion. Adjust
1707 * alignment so memcpy may copy words instead of bytes.
1709 if ((unused &= -Align) && !IS_LEAF2(src)) {
1711 memcpy(dst, src, (lower + (Align-1)) & -Align);
1712 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
1715 memcpy(dst, src, psize - unused);
1719 /** Pull a page off the txn's spill list, if present.
1720 * If a page being referenced was spilled to disk in this txn, bring
1721 * it back and make it dirty/writable again.
1722 * @param[in] tx0 the transaction handle.
1723 * @param[in] mp the page being referenced.
1724 * @param[out] ret the writable page, if any. ret is unchanged if
1725 * mp wasn't spilled.
1728 mdb_page_unspill(MDB_txn *tx0, MDB_page *mp, MDB_page **ret)
1730 MDB_env *env = tx0->mt_env;
1733 pgno_t pgno = mp->mp_pgno;
1735 for (txn = tx0; txn; txn=txn->mt_parent) {
1736 if (!txn->mt_spill_pgs)
1738 x = mdb_midl_search(txn->mt_spill_pgs, pgno);
1739 if (x <= txn->mt_spill_pgs[0] && txn->mt_spill_pgs[x] == pgno) {
1742 if (IS_OVERFLOW(mp))
1746 if (env->me_flags & MDB_WRITEMAP) {
1749 np = mdb_page_malloc(txn, num);
1753 memcpy(np, mp, num * env->me_psize);
1755 mdb_page_copy(np, mp, env->me_psize);
1758 /* If in current txn, this page is no longer spilled */
1759 for (; x < txn->mt_spill_pgs[0]; x++)
1760 txn->mt_spill_pgs[x] = txn->mt_spill_pgs[x+1];
1761 txn->mt_spill_pgs[0]--;
1762 } /* otherwise, if belonging to a parent txn, the
1763 * page remains spilled until child commits
1766 if (txn->mt_parent) {
1768 /* If this page is also in a parent's dirty list, then
1769 * it's already accounted in dirty_room, and we need to
1770 * cancel out the decrement that mdb_page_dirty does.
1772 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1773 x = mdb_mid2l_search(tx2->mt_u.dirty_list, pgno);
1774 if (x <= tx2->mt_u.dirty_list[0].mid &&
1775 tx2->mt_u.dirty_list[x].mid == pgno) {
1776 txn->mt_dirty_room++;
1781 mdb_page_dirty(tx0, np);
1782 np->mp_flags |= P_DIRTY;
1790 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1791 * @param[in] mc cursor pointing to the page to be touched
1792 * @return 0 on success, non-zero on failure.
1795 mdb_page_touch(MDB_cursor *mc)
1797 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
1798 MDB_txn *txn = mc->mc_txn;
1799 MDB_cursor *m2, *m3;
1804 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1805 if (txn->mt_flags & MDB_TXN_SPILLS) {
1807 rc = mdb_page_unspill(txn, mp, &np);
1813 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
1814 (rc = mdb_page_alloc(mc, 1, &np)))
1817 DPRINTF("touched db %u page %zu -> %zu", mc->mc_dbi,mp->mp_pgno,pgno);
1818 assert(mp->mp_pgno != pgno);
1819 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
1820 /* Update the parent page, if any, to point to the new page */
1822 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
1823 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
1824 SETPGNO(node, pgno);
1826 mc->mc_db->md_root = pgno;
1828 } else if (txn->mt_parent && !IS_SUBP(mp)) {
1829 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
1831 /* If txn has a parent, make sure the page is in our
1835 unsigned x = mdb_mid2l_search(dl, pgno);
1836 if (x <= dl[0].mid && dl[x].mid == pgno) {
1837 if (mp != dl[x].mptr) { /* bad cursor? */
1838 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1839 return MDB_CORRUPTED;
1844 assert(dl[0].mid < MDB_IDL_UM_MAX);
1846 np = mdb_page_malloc(txn, 1);
1851 mdb_mid2l_insert(dl, &mid);
1856 mdb_page_copy(np, mp, txn->mt_env->me_psize);
1858 np->mp_flags |= P_DIRTY;
1861 /* Adjust cursors pointing to mp */
1862 mc->mc_pg[mc->mc_top] = np;
1864 if (mc->mc_flags & C_SUB) {
1866 for (m2 = txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
1867 m3 = &m2->mc_xcursor->mx_cursor;
1868 if (m3->mc_snum < mc->mc_snum) continue;
1869 if (m3->mc_pg[mc->mc_top] == mp)
1870 m3->mc_pg[mc->mc_top] = np;
1873 for (m2 = txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
1874 if (m2->mc_snum < mc->mc_snum) continue;
1875 if (m2->mc_pg[mc->mc_top] == mp) {
1876 m2->mc_pg[mc->mc_top] = np;
1877 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
1878 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
1880 MDB_node *leaf = NODEPTR(np, mc->mc_ki[mc->mc_top]);
1881 if (!(leaf->mn_flags & F_SUBDATA))
1882 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
1891 mdb_env_sync(MDB_env *env, int force)
1894 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1895 if (env->me_flags & MDB_WRITEMAP) {
1896 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
1897 ? MS_ASYNC : MS_SYNC;
1898 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
1901 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
1905 if (MDB_FDATASYNC(env->me_fd))
1912 /** Back up parent txn's cursors, then grab the originals for tracking */
1914 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
1916 MDB_cursor *mc, *bk;
1921 for (i = src->mt_numdbs; --i >= 0; ) {
1922 if ((mc = src->mt_cursors[i]) != NULL) {
1923 size = sizeof(MDB_cursor);
1925 size += sizeof(MDB_xcursor);
1926 for (; mc; mc = bk->mc_next) {
1932 mc->mc_db = &dst->mt_dbs[i];
1933 /* Kill pointers into src - and dst to reduce abuse: The
1934 * user may not use mc until dst ends. Otherwise we'd...
1936 mc->mc_txn = NULL; /* ...set this to dst */
1937 mc->mc_dbflag = NULL; /* ...and &dst->mt_dbflags[i] */
1938 if ((mx = mc->mc_xcursor) != NULL) {
1939 *(MDB_xcursor *)(bk+1) = *mx;
1940 mx->mx_cursor.mc_txn = NULL; /* ...and dst. */
1942 mc->mc_next = dst->mt_cursors[i];
1943 dst->mt_cursors[i] = mc;
1950 /** Close this write txn's cursors, give parent txn's cursors back to parent.
1951 * @param[in] txn the transaction handle.
1952 * @param[in] merge true to keep changes to parent cursors, false to revert.
1953 * @return 0 on success, non-zero on failure.
1956 mdb_cursors_close(MDB_txn *txn, unsigned merge)
1958 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
1962 for (i = txn->mt_numdbs; --i >= 0; ) {
1963 for (mc = cursors[i]; mc; mc = next) {
1965 if ((bk = mc->mc_backup) != NULL) {
1967 /* Commit changes to parent txn */
1968 mc->mc_next = bk->mc_next;
1969 mc->mc_backup = bk->mc_backup;
1970 mc->mc_txn = bk->mc_txn;
1971 mc->mc_db = bk->mc_db;
1972 mc->mc_dbflag = bk->mc_dbflag;
1973 if ((mx = mc->mc_xcursor) != NULL)
1974 mx->mx_cursor.mc_txn = bk->mc_txn;
1976 /* Abort nested txn */
1978 if ((mx = mc->mc_xcursor) != NULL)
1979 *mx = *(MDB_xcursor *)(bk+1);
1989 #ifdef MDB_DEBUG_SKIP
1990 #define mdb_txn_reset0(txn, act) mdb_txn_reset0(txn)
1993 mdb_txn_reset0(MDB_txn *txn, const char *act);
1995 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
1996 * @param[in] txn the transaction handle to initialize
1997 * @return 0 on success, non-zero on failure.
2000 mdb_txn_renew0(MDB_txn *txn)
2002 MDB_env *env = txn->mt_env;
2005 int rc, new_notls = 0;
2008 txn->mt_numdbs = env->me_numdbs;
2009 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
2011 if (txn->mt_flags & MDB_TXN_RDONLY) {
2012 if (!env->me_txns) {
2013 i = mdb_env_pick_meta(env);
2014 txn->mt_txnid = env->me_metas[i]->mm_txnid;
2015 txn->mt_u.reader = NULL;
2017 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2018 pthread_getspecific(env->me_txkey);
2020 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2021 return MDB_BAD_RSLOT;
2023 pid_t pid = env->me_pid;
2024 pthread_t tid = pthread_self();
2027 for (i=0; i<env->me_txns->mti_numreaders; i++)
2028 if (env->me_txns->mti_readers[i].mr_pid == 0)
2030 if (i == env->me_maxreaders) {
2031 UNLOCK_MUTEX_R(env);
2032 return MDB_READERS_FULL;
2034 env->me_txns->mti_readers[i].mr_pid = pid;
2035 env->me_txns->mti_readers[i].mr_tid = tid;
2036 if (i >= env->me_txns->mti_numreaders)
2037 env->me_txns->mti_numreaders = i+1;
2038 /* Save numreaders for un-mutexed mdb_env_close() */
2039 env->me_numreaders = env->me_txns->mti_numreaders;
2040 UNLOCK_MUTEX_R(env);
2041 r = &env->me_txns->mti_readers[i];
2042 new_notls = (env->me_flags & MDB_NOTLS);
2043 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2048 txn->mt_txnid = r->mr_txnid = env->me_txns->mti_txnid;
2049 txn->mt_u.reader = r;
2051 txn->mt_toggle = txn->mt_txnid & 1;
2055 txn->mt_txnid = env->me_txns->mti_txnid;
2056 txn->mt_toggle = txn->mt_txnid & 1;
2059 if (txn->mt_txnid == mdb_debug_start)
2062 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2063 txn->mt_u.dirty_list = env->me_dirty_list;
2064 txn->mt_u.dirty_list[0].mid = 0;
2065 txn->mt_free_pgs = env->me_free_pgs;
2066 txn->mt_free_pgs[0] = 0;
2067 txn->mt_spill_pgs = NULL;
2071 /* Copy the DB info and flags */
2072 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
2074 /* Moved to here to avoid a data race in read TXNs */
2075 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
2077 for (i=2; i<txn->mt_numdbs; i++) {
2078 x = env->me_dbflags[i];
2079 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2080 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_STALE : 0;
2082 txn->mt_dbflags[0] = txn->mt_dbflags[1] = DB_VALID;
2084 if (env->me_maxpg < txn->mt_next_pgno) {
2085 mdb_txn_reset0(txn, "renew0-mapfail");
2087 txn->mt_u.reader->mr_pid = 0;
2088 txn->mt_u.reader = NULL;
2090 return MDB_MAP_RESIZED;
2097 mdb_txn_renew(MDB_txn *txn)
2101 if (!txn || txn->mt_dbxs) /* A reset txn has mt_dbxs==NULL */
2104 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
2105 DPUTS("environment had fatal error, must shutdown!");
2109 rc = mdb_txn_renew0(txn);
2110 if (rc == MDB_SUCCESS) {
2111 DPRINTF("renew txn %zu%c %p on mdbenv %p, root page %zu",
2112 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2113 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
2119 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2123 int rc, size, tsize = sizeof(MDB_txn);
2125 if (env->me_flags & MDB_FATAL_ERROR) {
2126 DPUTS("environment had fatal error, must shutdown!");
2129 if ((env->me_flags & MDB_RDONLY) && !(flags & MDB_RDONLY))
2132 /* Nested transactions: Max 1 child, write txns only, no writemap */
2133 if (parent->mt_child ||
2134 (flags & MDB_RDONLY) || (parent->mt_flags & MDB_TXN_RDONLY) ||
2135 (env->me_flags & MDB_WRITEMAP))
2139 tsize = sizeof(MDB_ntxn);
2141 size = tsize + env->me_maxdbs * (sizeof(MDB_db)+1);
2142 if (!(flags & MDB_RDONLY))
2143 size += env->me_maxdbs * sizeof(MDB_cursor *);
2145 if ((txn = calloc(1, size)) == NULL) {
2146 DPRINTF("calloc: %s", strerror(ErrCode()));
2149 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2150 if (flags & MDB_RDONLY) {
2151 txn->mt_flags |= MDB_TXN_RDONLY;
2152 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
2154 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2155 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
2161 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2162 if (!txn->mt_u.dirty_list ||
2163 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2165 free(txn->mt_u.dirty_list);
2169 txn->mt_txnid = parent->mt_txnid;
2170 txn->mt_toggle = parent->mt_toggle;
2171 txn->mt_dirty_room = parent->mt_dirty_room;
2172 txn->mt_u.dirty_list[0].mid = 0;
2173 txn->mt_spill_pgs = NULL;
2174 txn->mt_next_pgno = parent->mt_next_pgno;
2175 parent->mt_child = txn;
2176 txn->mt_parent = parent;
2177 txn->mt_numdbs = parent->mt_numdbs;
2178 txn->mt_flags = parent->mt_flags;
2179 txn->mt_dbxs = parent->mt_dbxs;
2180 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2181 /* Copy parent's mt_dbflags, but clear DB_NEW */
2182 for (i=0; i<txn->mt_numdbs; i++)
2183 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2185 ntxn = (MDB_ntxn *)txn;
2186 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2187 if (env->me_pghead) {
2188 size = MDB_IDL_SIZEOF(env->me_pghead);
2189 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2191 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2196 rc = mdb_cursor_shadow(parent, txn);
2198 mdb_txn_reset0(txn, "beginchild-fail");
2200 rc = mdb_txn_renew0(txn);
2206 DPRINTF("begin txn %zu%c %p on mdbenv %p, root page %zu",
2207 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2208 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
2214 /** Export or close DBI handles opened in this txn. */
2216 mdb_dbis_update(MDB_txn *txn, int keep)
2219 MDB_dbi n = txn->mt_numdbs;
2220 MDB_env *env = txn->mt_env;
2221 unsigned char *tdbflags = txn->mt_dbflags;
2223 for (i = n; --i >= 2;) {
2224 if (tdbflags[i] & DB_NEW) {
2226 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2228 char *ptr = env->me_dbxs[i].md_name.mv_data;
2229 env->me_dbxs[i].md_name.mv_data = NULL;
2230 env->me_dbxs[i].md_name.mv_size = 0;
2231 env->me_dbflags[i] = 0;
2236 if (keep && env->me_numdbs < n)
2240 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
2241 * May be called twice for readonly txns: First reset it, then abort.
2242 * @param[in] txn the transaction handle to reset
2245 mdb_txn_reset0(MDB_txn *txn, const char *act)
2247 MDB_env *env = txn->mt_env;
2249 /* Close any DBI handles opened in this txn */
2250 mdb_dbis_update(txn, 0);
2252 DPRINTF("%s txn %zu%c %p on mdbenv %p, root page %zu",
2253 act, txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2254 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
2256 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2257 if (txn->mt_u.reader) {
2258 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2259 if (!(env->me_flags & MDB_NOTLS))
2260 txn->mt_u.reader = NULL; /* txn does not own reader */
2262 txn->mt_numdbs = 0; /* close nothing if called again */
2263 txn->mt_dbxs = NULL; /* mark txn as reset */
2265 mdb_cursors_close(txn, 0);
2267 if (!(env->me_flags & MDB_WRITEMAP)) {
2268 mdb_dlist_free(txn);
2270 mdb_midl_free(env->me_pghead);
2272 if (txn->mt_parent) {
2273 txn->mt_parent->mt_child = NULL;
2274 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2275 mdb_midl_free(txn->mt_free_pgs);
2276 mdb_midl_free(txn->mt_spill_pgs);
2277 free(txn->mt_u.dirty_list);
2281 if (mdb_midl_shrink(&txn->mt_free_pgs))
2282 env->me_free_pgs = txn->mt_free_pgs;
2283 env->me_pghead = NULL;
2287 /* The writer mutex was locked in mdb_txn_begin. */
2288 UNLOCK_MUTEX_W(env);
2293 mdb_txn_reset(MDB_txn *txn)
2298 /* This call is only valid for read-only txns */
2299 if (!(txn->mt_flags & MDB_TXN_RDONLY))
2302 mdb_txn_reset0(txn, "reset");
2306 mdb_txn_abort(MDB_txn *txn)
2312 mdb_txn_abort(txn->mt_child);
2314 mdb_txn_reset0(txn, "abort");
2315 /* Free reader slot tied to this txn (if MDB_NOTLS && writable FS) */
2316 if ((txn->mt_flags & MDB_TXN_RDONLY) && txn->mt_u.reader)
2317 txn->mt_u.reader->mr_pid = 0;
2322 /** Save the freelist as of this transaction to the freeDB.
2323 * This changes the freelist. Keep trying until it stabilizes.
2326 mdb_freelist_save(MDB_txn *txn)
2328 /* env->me_pghead[] can grow and shrink during this call.
2329 * env->me_pglast and txn->mt_free_pgs[] can only grow.
2330 * Page numbers cannot disappear from txn->mt_free_pgs[].
2333 MDB_env *env = txn->mt_env;
2334 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
2335 txnid_t pglast = 0, head_id = 0;
2336 pgno_t freecnt = 0, *free_pgs, *mop;
2337 ssize_t head_room = 0, total_room = 0, mop_len;
2339 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
2341 if (env->me_pghead) {
2342 /* Make sure first page of freeDB is touched and on freelist */
2343 rc = mdb_page_search(&mc, NULL, MDB_PS_MODIFY);
2344 if (rc && rc != MDB_NOTFOUND)
2349 /* Come back here after each Put() in case freelist changed */
2352 /* If using records from freeDB which we have not yet
2353 * deleted, delete them and any we reserved for me_pghead.
2355 while (pglast < env->me_pglast) {
2356 rc = mdb_cursor_first(&mc, &key, NULL);
2359 pglast = head_id = *(txnid_t *)key.mv_data;
2360 total_room = head_room = 0;
2361 assert(pglast <= env->me_pglast);
2362 rc = mdb_cursor_del(&mc, 0);
2367 /* Save the IDL of pages freed by this txn, to a single record */
2368 if (freecnt < txn->mt_free_pgs[0]) {
2370 /* Make sure last page of freeDB is touched and on freelist */
2371 key.mv_size = MDB_MAXKEYSIZE+1;
2373 rc = mdb_page_search(&mc, &key, MDB_PS_MODIFY);
2374 if (rc && rc != MDB_NOTFOUND)
2377 free_pgs = txn->mt_free_pgs;
2378 /* Write to last page of freeDB */
2379 key.mv_size = sizeof(txn->mt_txnid);
2380 key.mv_data = &txn->mt_txnid;
2382 freecnt = free_pgs[0];
2383 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
2384 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2387 /* Retry if mt_free_pgs[] grew during the Put() */
2388 free_pgs = txn->mt_free_pgs;
2389 } while (freecnt < free_pgs[0]);
2390 mdb_midl_sort(free_pgs);
2391 memcpy(data.mv_data, free_pgs, data.mv_size);
2394 unsigned int i = free_pgs[0];
2395 DPRINTF("IDL write txn %zu root %zu num %u",
2396 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i);
2398 DPRINTF("IDL %zu", free_pgs[i]);
2404 mop = env->me_pghead;
2405 mop_len = mop ? mop[0] : 0;
2407 /* Reserve records for me_pghead[]. Split it if multi-page,
2408 * to avoid searching freeDB for a page range. Use keys in
2409 * range [1,me_pglast]: Smaller than txnid of oldest reader.
2411 if (total_room >= mop_len) {
2412 if (total_room == mop_len || --more < 0)
2414 } else if (head_room >= maxfree_1pg && head_id > 1) {
2415 /* Keep current record (overflow page), add a new one */
2419 /* (Re)write {key = head_id, IDL length = head_room} */
2420 total_room -= head_room;
2421 head_room = mop_len - total_room;
2422 if (head_room > maxfree_1pg && head_id > 1) {
2423 /* Overflow multi-page for part of me_pghead */
2424 head_room /= head_id; /* amortize page sizes */
2425 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
2426 } else if (head_room < 0) {
2427 /* Rare case, not bothering to delete this record */
2430 key.mv_size = sizeof(head_id);
2431 key.mv_data = &head_id;
2432 data.mv_size = (head_room + 1) * sizeof(pgno_t);
2433 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2436 *(MDB_ID *)data.mv_data = 0; /* IDL is initially empty */
2437 total_room += head_room;
2440 /* Fill in the reserved, touched me_pghead records */
2446 rc = mdb_cursor_first(&mc, &key, &data);
2447 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
2448 unsigned flags = MDB_CURRENT;
2449 txnid_t id = *(txnid_t *)key.mv_data;
2450 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
2453 assert(len >= 0 && id <= env->me_pglast);
2455 if (len > mop_len) {
2457 data.mv_size = (len + 1) * sizeof(MDB_ID);
2460 data.mv_data = mop -= len;
2463 rc = mdb_cursor_put(&mc, &key, &data, flags);
2465 if (rc || !(mop_len -= len))
2472 /** Flush dirty pages to the map, after clearing their dirty flag.
2475 mdb_page_flush(MDB_txn *txn)
2477 MDB_env *env = txn->mt_env;
2478 MDB_ID2L dl = txn->mt_u.dirty_list;
2479 unsigned psize = env->me_psize, j;
2480 int i, pagecount = dl[0].mid, rc;
2481 size_t size = 0, pos = 0;
2483 MDB_page *dp = NULL;
2487 struct iovec iov[MDB_COMMIT_PAGES];
2488 ssize_t wpos = 0, wsize = 0, wres;
2489 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
2494 if (env->me_flags & MDB_WRITEMAP) {
2495 /* Clear dirty flags */
2496 for (i = pagecount; i; i--) {
2498 /* Don't flush this page yet */
2499 if (dp->mp_flags & P_KEEP) {
2500 dp->mp_flags ^= P_KEEP;
2504 dp->mp_flags &= ~P_DIRTY;
2510 /* Write the pages */
2512 if (i <= pagecount) {
2514 /* Don't flush this page yet */
2515 if (dp->mp_flags & P_KEEP) {
2516 dp->mp_flags ^= P_KEEP;
2521 /* clear dirty flag */
2522 dp->mp_flags &= ~P_DIRTY;
2525 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
2530 /* Windows actually supports scatter/gather I/O, but only on
2531 * unbuffered file handles. Since we're relying on the OS page
2532 * cache for all our data, that's self-defeating. So we just
2533 * write pages one at a time. We use the ov structure to set
2534 * the write offset, to at least save the overhead of a Seek
2537 DPRINTF("committing page %zu", pgno);
2538 memset(&ov, 0, sizeof(ov));
2539 ov.Offset = pos & 0xffffffff;
2540 ov.OffsetHigh = pos >> 16 >> 16;
2541 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
2543 DPRINTF("WriteFile: %d", rc);
2547 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
2548 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
2550 /* Write previous page(s) */
2551 #ifdef MDB_USE_PWRITEV
2552 wres = pwritev(env->me_fd, iov, n, wpos);
2555 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
2557 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
2559 DPRINTF("lseek: %s", strerror(rc));
2562 wres = writev(env->me_fd, iov, n);
2565 if (wres != wsize) {
2568 DPRINTF("Write error: %s", strerror(rc));
2570 rc = EIO; /* TODO: Use which error code? */
2571 DPUTS("short write, filesystem full?");
2582 DPRINTF("committing page %zu", pgno);
2583 next_pos = pos + size;
2584 iov[n].iov_len = size;
2585 iov[n].iov_base = (char *)dp;
2592 for (i=1; i<=pagecount; i++) {
2594 /* This is a page we skipped above */
2597 dl[j].mid = dp->mp_pgno;
2600 mdb_dpage_free(env, dp);
2608 mdb_txn_commit(MDB_txn *txn)
2614 assert(txn != NULL);
2615 assert(txn->mt_env != NULL);
2617 if (txn->mt_child) {
2618 rc = mdb_txn_commit(txn->mt_child);
2619 txn->mt_child = NULL;
2626 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2627 mdb_dbis_update(txn, 1);
2628 txn->mt_numdbs = 2; /* so txn_abort() doesn't close any new handles */
2633 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
2634 DPUTS("error flag is set, can't commit");
2636 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
2641 if (txn->mt_parent) {
2642 MDB_txn *parent = txn->mt_parent;
2646 /* Append our free list to parent's */
2647 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
2650 mdb_midl_free(txn->mt_free_pgs);
2652 parent->mt_next_pgno = txn->mt_next_pgno;
2653 parent->mt_flags = txn->mt_flags;
2655 /* Merge our cursors into parent's and close them */
2656 mdb_cursors_close(txn, 1);
2658 /* Update parent's DB table. */
2659 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2660 parent->mt_numdbs = txn->mt_numdbs;
2661 parent->mt_dbflags[0] = txn->mt_dbflags[0];
2662 parent->mt_dbflags[1] = txn->mt_dbflags[1];
2663 for (i=2; i<txn->mt_numdbs; i++) {
2664 /* preserve parent's DB_NEW status */
2665 x = parent->mt_dbflags[i] & DB_NEW;
2666 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
2669 dst = parent->mt_u.dirty_list;
2670 src = txn->mt_u.dirty_list;
2671 /* Remove anything in our dirty list from parent's spill list */
2672 if (parent->mt_spill_pgs) {
2673 x = parent->mt_spill_pgs[0];
2675 /* zero out our dirty pages in parent spill list */
2676 for (i=1; i<=src[0].mid; i++) {
2677 if (src[i].mid < parent->mt_spill_pgs[x])
2679 if (src[i].mid > parent->mt_spill_pgs[x]) {
2685 parent->mt_spill_pgs[x] = 0;
2688 /* OK, we had a few hits, squash zeros from the spill list */
2689 if (len < parent->mt_spill_pgs[0]) {
2691 for (y=1; y<=parent->mt_spill_pgs[0]; y++) {
2692 if (parent->mt_spill_pgs[y]) {
2694 parent->mt_spill_pgs[x] = parent->mt_spill_pgs[y];
2699 parent->mt_spill_pgs[0] = len;
2702 /* Find len = length of merging our dirty list with parent's */
2704 dst[0].mid = 0; /* simplify loops */
2705 if (parent->mt_parent) {
2706 len = x + src[0].mid;
2707 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
2708 for (i = x; y && i; y--) {
2709 pgno_t yp = src[y].mid;
2710 while (yp < dst[i].mid)
2712 if (yp == dst[i].mid) {
2717 } else { /* Simplify the above for single-ancestor case */
2718 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
2720 /* Merge our dirty list with parent's */
2722 for (i = len; y; dst[i--] = src[y--]) {
2723 pgno_t yp = src[y].mid;
2724 while (yp < dst[x].mid)
2725 dst[i--] = dst[x--];
2726 if (yp == dst[x].mid)
2727 free(dst[x--].mptr);
2731 free(txn->mt_u.dirty_list);
2732 parent->mt_dirty_room = txn->mt_dirty_room;
2733 if (txn->mt_spill_pgs) {
2734 if (parent->mt_spill_pgs) {
2735 mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
2736 mdb_midl_free(txn->mt_spill_pgs);
2737 mdb_midl_sort(parent->mt_spill_pgs);
2739 parent->mt_spill_pgs = txn->mt_spill_pgs;
2743 parent->mt_child = NULL;
2744 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
2749 if (txn != env->me_txn) {
2750 DPUTS("attempt to commit unknown transaction");
2755 mdb_cursors_close(txn, 0);
2757 if (!txn->mt_u.dirty_list[0].mid && !(txn->mt_flags & MDB_TXN_DIRTY))
2760 DPRINTF("committing txn %zu %p on mdbenv %p, root page %zu",
2761 txn->mt_txnid, (void *)txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
2763 /* Update DB root pointers */
2764 if (txn->mt_numdbs > 2) {
2768 data.mv_size = sizeof(MDB_db);
2770 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
2771 for (i = 2; i < txn->mt_numdbs; i++) {
2772 if (txn->mt_dbflags[i] & DB_DIRTY) {
2773 data.mv_data = &txn->mt_dbs[i];
2774 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
2781 rc = mdb_freelist_save(txn);
2785 mdb_midl_free(env->me_pghead);
2786 env->me_pghead = NULL;
2787 if (mdb_midl_shrink(&txn->mt_free_pgs))
2788 env->me_free_pgs = txn->mt_free_pgs;
2794 if ((rc = mdb_page_flush(txn)) ||
2795 (rc = mdb_env_sync(env, 0)) ||
2796 (rc = mdb_env_write_meta(txn)))
2802 mdb_dbis_update(txn, 1);
2804 UNLOCK_MUTEX_W(env);
2814 /** Read the environment parameters of a DB environment before
2815 * mapping it into memory.
2816 * @param[in] env the environment handle
2817 * @param[out] meta address of where to store the meta information
2818 * @return 0 on success, non-zero on failure.
2821 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
2828 /* We don't know the page size yet, so use a minimum value.
2829 * Read both meta pages so we can use the latest one.
2832 for (i=off=0; i<2; i++, off = meta->mm_psize) {
2836 memset(&ov, 0, sizeof(ov));
2838 rc = ReadFile(env->me_fd,&pbuf,MDB_PAGESIZE,&len,&ov) ? (int)len : -1;
2839 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
2842 rc = pread(env->me_fd, &pbuf, MDB_PAGESIZE, off);
2844 if (rc != MDB_PAGESIZE) {
2845 if (rc == 0 && off == 0)
2847 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
2848 DPRINTF("read: %s", mdb_strerror(rc));
2852 p = (MDB_page *)&pbuf;
2854 if (!F_ISSET(p->mp_flags, P_META)) {
2855 DPRINTF("page %zu not a meta page", p->mp_pgno);
2860 if (m->mm_magic != MDB_MAGIC) {
2861 DPUTS("meta has invalid magic");
2865 if (m->mm_version != MDB_VERSION) {
2866 DPRINTF("database is version %u, expected version %u",
2867 m->mm_version, MDB_VERSION);
2868 return MDB_VERSION_MISMATCH;
2871 if (off == 0 || m->mm_txnid > meta->mm_txnid)
2877 /** Write the environment parameters of a freshly created DB environment.
2878 * @param[in] env the environment handle
2879 * @param[out] meta address of where to store the meta information
2880 * @return 0 on success, non-zero on failure.
2883 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
2889 DPUTS("writing new meta page");
2891 GET_PAGESIZE(psize);
2893 meta->mm_magic = MDB_MAGIC;
2894 meta->mm_version = MDB_VERSION;
2895 meta->mm_mapsize = env->me_mapsize;
2896 meta->mm_psize = psize;
2897 meta->mm_last_pg = 1;
2898 meta->mm_flags = env->me_flags & 0xffff;
2899 meta->mm_flags |= MDB_INTEGERKEY;
2900 meta->mm_dbs[0].md_root = P_INVALID;
2901 meta->mm_dbs[1].md_root = P_INVALID;
2903 p = calloc(2, psize);
2905 p->mp_flags = P_META;
2906 *(MDB_meta *)METADATA(p) = *meta;
2908 q = (MDB_page *)((char *)p + psize);
2910 q->mp_flags = P_META;
2911 *(MDB_meta *)METADATA(q) = *meta;
2917 memset(&ov, 0, sizeof(ov));
2918 rc = WriteFile(env->me_fd, p, psize * 2, &len, &ov);
2919 rc = rc ? (len == psize * 2 ? MDB_SUCCESS : EIO) : ErrCode();
2922 rc = pwrite(env->me_fd, p, psize * 2, 0);
2923 rc = (rc == (int)psize * 2) ? MDB_SUCCESS : rc < 0 ? ErrCode() : EIO;
2929 /** Update the environment info to commit a transaction.
2930 * @param[in] txn the transaction that's being committed
2931 * @return 0 on success, non-zero on failure.
2934 mdb_env_write_meta(MDB_txn *txn)
2937 MDB_meta meta, metab, *mp;
2939 int rc, len, toggle;
2948 assert(txn != NULL);
2949 assert(txn->mt_env != NULL);
2951 toggle = !txn->mt_toggle;
2952 DPRINTF("writing meta page %d for root page %zu",
2953 toggle, txn->mt_dbs[MAIN_DBI].md_root);
2956 mp = env->me_metas[toggle];
2958 if (env->me_flags & MDB_WRITEMAP) {
2959 /* Persist any increases of mapsize config */
2960 if (env->me_mapsize > mp->mm_mapsize)
2961 mp->mm_mapsize = env->me_mapsize;
2962 mp->mm_dbs[0] = txn->mt_dbs[0];
2963 mp->mm_dbs[1] = txn->mt_dbs[1];
2964 mp->mm_last_pg = txn->mt_next_pgno - 1;
2965 mp->mm_txnid = txn->mt_txnid;
2966 if (!(env->me_flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
2967 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
2970 ptr += env->me_psize;
2971 if (MDB_MSYNC(ptr, env->me_psize, rc)) {
2978 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
2979 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
2981 ptr = (char *)&meta;
2982 if (env->me_mapsize > mp->mm_mapsize) {
2983 /* Persist any increases of mapsize config */
2984 meta.mm_mapsize = env->me_mapsize;
2985 off = offsetof(MDB_meta, mm_mapsize);
2987 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
2989 len = sizeof(MDB_meta) - off;
2992 meta.mm_dbs[0] = txn->mt_dbs[0];
2993 meta.mm_dbs[1] = txn->mt_dbs[1];
2994 meta.mm_last_pg = txn->mt_next_pgno - 1;
2995 meta.mm_txnid = txn->mt_txnid;
2998 off += env->me_psize;
3001 /* Write to the SYNC fd */
3002 mfd = env->me_flags & (MDB_NOSYNC|MDB_NOMETASYNC) ?
3003 env->me_fd : env->me_mfd;
3006 memset(&ov, 0, sizeof(ov));
3008 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3012 rc = pwrite(mfd, ptr, len, off);
3015 rc = rc < 0 ? ErrCode() : EIO;
3016 DPUTS("write failed, disk error?");
3017 /* On a failure, the pagecache still contains the new data.
3018 * Write some old data back, to prevent it from being used.
3019 * Use the non-SYNC fd; we know it will fail anyway.
3021 meta.mm_last_pg = metab.mm_last_pg;
3022 meta.mm_txnid = metab.mm_txnid;
3024 memset(&ov, 0, sizeof(ov));
3026 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3028 r2 = pwrite(env->me_fd, ptr, len, off);
3031 env->me_flags |= MDB_FATAL_ERROR;
3035 /* Memory ordering issues are irrelevant; since the entire writer
3036 * is wrapped by wmutex, all of these changes will become visible
3037 * after the wmutex is unlocked. Since the DB is multi-version,
3038 * readers will get consistent data regardless of how fresh or
3039 * how stale their view of these values is.
3041 env->me_txns->mti_txnid = txn->mt_txnid;
3046 /** Check both meta pages to see which one is newer.
3047 * @param[in] env the environment handle
3048 * @return meta toggle (0 or 1).
3051 mdb_env_pick_meta(const MDB_env *env)
3053 return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
3057 mdb_env_create(MDB_env **env)
3061 e = calloc(1, sizeof(MDB_env));
3065 e->me_maxreaders = DEFAULT_READERS;
3066 e->me_maxdbs = e->me_numdbs = 2;
3067 e->me_fd = INVALID_HANDLE_VALUE;
3068 e->me_lfd = INVALID_HANDLE_VALUE;
3069 e->me_mfd = INVALID_HANDLE_VALUE;
3070 #ifdef MDB_USE_POSIX_SEM
3071 e->me_rmutex = SEM_FAILED;
3072 e->me_wmutex = SEM_FAILED;
3074 e->me_pid = getpid();
3075 VGMEMP_CREATE(e,0,0);
3081 mdb_env_set_mapsize(MDB_env *env, size_t size)
3085 env->me_mapsize = size;
3087 env->me_maxpg = env->me_mapsize / env->me_psize;
3092 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
3096 env->me_maxdbs = dbs + 2; /* Named databases + main and free DB */
3101 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
3103 if (env->me_map || readers < 1)
3105 env->me_maxreaders = readers;
3110 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
3112 if (!env || !readers)
3114 *readers = env->me_maxreaders;
3118 /** Further setup required for opening an MDB environment
3121 mdb_env_open2(MDB_env *env)
3123 unsigned int flags = env->me_flags;
3131 memset(&meta, 0, sizeof(meta));
3133 if ((i = mdb_env_read_header(env, &meta)) != 0) {
3136 DPUTS("new mdbenv");
3140 /* Was a mapsize configured? */
3141 if (!env->me_mapsize) {
3142 /* If this is a new environment, take the default,
3143 * else use the size recorded in the existing env.
3145 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
3146 } else if (env->me_mapsize < meta.mm_mapsize) {
3147 /* If the configured size is smaller, make sure it's
3148 * still big enough. Silently round up to minimum if not.
3150 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
3151 if (env->me_mapsize < minsize)
3152 env->me_mapsize = minsize;
3159 LONG sizelo, sizehi;
3160 sizelo = env->me_mapsize & 0xffffffff;
3161 sizehi = env->me_mapsize >> 16 >> 16; /* only needed on Win64 */
3162 /* Windows won't create mappings for zero length files.
3163 * Just allocate the maxsize right now.
3166 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3167 || !SetEndOfFile(env->me_fd)
3168 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3171 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3172 PAGE_READWRITE : PAGE_READONLY,
3173 sizehi, sizelo, NULL);
3176 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3177 FILE_MAP_WRITE : FILE_MAP_READ,
3178 0, 0, env->me_mapsize, meta.mm_address);
3179 rc = env->me_map ? 0 : ErrCode();
3187 if (flags & MDB_WRITEMAP) {
3189 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3192 env->me_map = mmap(meta.mm_address, env->me_mapsize, prot, i,
3194 if (env->me_map == MAP_FAILED) {
3198 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3200 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3202 #ifdef POSIX_MADV_RANDOM
3203 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3204 #endif /* POSIX_MADV_RANDOM */
3205 #endif /* MADV_RANDOM */
3209 if (flags & MDB_FIXEDMAP)
3210 meta.mm_address = env->me_map;
3211 i = mdb_env_init_meta(env, &meta);
3212 if (i != MDB_SUCCESS) {
3215 } else if (meta.mm_address && env->me_map != meta.mm_address) {
3216 /* Can happen because the address argument to mmap() is just a
3217 * hint. mmap() can pick another, e.g. if the range is in use.
3218 * The MAP_FIXED flag would prevent that, but then mmap could
3219 * instead unmap existing pages to make room for the new map.
3221 return EBUSY; /* TODO: Make a new MDB_* error code? */
3223 env->me_psize = meta.mm_psize;
3224 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
3225 env->me_nodemax = (env->me_psize - PAGEHDRSZ) / MDB_MINKEYS;
3227 env->me_maxpg = env->me_mapsize / env->me_psize;
3229 p = (MDB_page *)env->me_map;
3230 env->me_metas[0] = METADATA(p);
3231 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
3235 int toggle = mdb_env_pick_meta(env);
3236 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
3238 DPRINTF("opened database version %u, pagesize %u",
3239 env->me_metas[0]->mm_version, env->me_psize);
3240 DPRINTF("using meta page %d", toggle);
3241 DPRINTF("depth: %u", db->md_depth);
3242 DPRINTF("entries: %zu", db->md_entries);
3243 DPRINTF("branch pages: %zu", db->md_branch_pages);
3244 DPRINTF("leaf pages: %zu", db->md_leaf_pages);
3245 DPRINTF("overflow pages: %zu", db->md_overflow_pages);
3246 DPRINTF("root: %zu", db->md_root);
3254 /** Release a reader thread's slot in the reader lock table.
3255 * This function is called automatically when a thread exits.
3256 * @param[in] ptr This points to the slot in the reader lock table.
3259 mdb_env_reader_dest(void *ptr)
3261 MDB_reader *reader = ptr;
3267 /** Junk for arranging thread-specific callbacks on Windows. This is
3268 * necessarily platform and compiler-specific. Windows supports up
3269 * to 1088 keys. Let's assume nobody opens more than 64 environments
3270 * in a single process, for now. They can override this if needed.
3272 #ifndef MAX_TLS_KEYS
3273 #define MAX_TLS_KEYS 64
3275 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
3276 static int mdb_tls_nkeys;
3278 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
3282 case DLL_PROCESS_ATTACH: break;
3283 case DLL_THREAD_ATTACH: break;
3284 case DLL_THREAD_DETACH:
3285 for (i=0; i<mdb_tls_nkeys; i++) {
3286 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
3287 mdb_env_reader_dest(r);
3290 case DLL_PROCESS_DETACH: break;
3295 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3297 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3301 /* Force some symbol references.
3302 * _tls_used forces the linker to create the TLS directory if not already done
3303 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
3305 #pragma comment(linker, "/INCLUDE:_tls_used")
3306 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
3307 #pragma const_seg(".CRT$XLB")
3308 extern const PIMAGE_TLS_CALLBACK mdb_tls_callback;
3309 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3312 #pragma comment(linker, "/INCLUDE:__tls_used")
3313 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
3314 #pragma data_seg(".CRT$XLB")
3315 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3317 #endif /* WIN 32/64 */
3318 #endif /* !__GNUC__ */
3321 /** Downgrade the exclusive lock on the region back to shared */
3323 mdb_env_share_locks(MDB_env *env, int *excl)
3325 int rc = 0, toggle = mdb_env_pick_meta(env);
3327 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
3332 /* First acquire a shared lock. The Unlock will
3333 * then release the existing exclusive lock.
3335 memset(&ov, 0, sizeof(ov));
3336 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3339 UnlockFile(env->me_lfd, 0, 0, 1, 0);
3345 struct flock lock_info;
3346 /* The shared lock replaces the existing lock */
3347 memset((void *)&lock_info, 0, sizeof(lock_info));
3348 lock_info.l_type = F_RDLCK;
3349 lock_info.l_whence = SEEK_SET;
3350 lock_info.l_start = 0;
3351 lock_info.l_len = 1;
3352 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3353 (rc = ErrCode()) == EINTR) ;
3354 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
3361 /** Try to get exlusive lock, otherwise shared.
3362 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
3365 mdb_env_excl_lock(MDB_env *env, int *excl)
3369 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
3373 memset(&ov, 0, sizeof(ov));
3374 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3381 struct flock lock_info;
3382 memset((void *)&lock_info, 0, sizeof(lock_info));
3383 lock_info.l_type = F_WRLCK;
3384 lock_info.l_whence = SEEK_SET;
3385 lock_info.l_start = 0;
3386 lock_info.l_len = 1;
3387 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3388 (rc = ErrCode()) == EINTR) ;
3392 # ifdef MDB_USE_POSIX_SEM
3393 if (*excl < 0) /* always true when !MDB_USE_POSIX_SEM */
3396 lock_info.l_type = F_RDLCK;
3397 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
3398 (rc = ErrCode()) == EINTR) ;
3406 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
3408 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
3410 * @(#) $Revision: 5.1 $
3411 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
3412 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
3414 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
3418 * Please do not copyright this code. This code is in the public domain.
3420 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
3421 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
3422 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
3423 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
3424 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
3425 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
3426 * PERFORMANCE OF THIS SOFTWARE.
3429 * chongo <Landon Curt Noll> /\oo/\
3430 * http://www.isthe.com/chongo/
3432 * Share and Enjoy! :-)
3435 typedef unsigned long long mdb_hash_t;
3436 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
3438 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
3439 * @param[in] str string to hash
3440 * @param[in] hval initial value for hash
3441 * @return 64 bit hash
3443 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
3444 * hval arg on the first call.
3447 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
3449 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
3450 unsigned char *end = s + val->mv_size;
3452 * FNV-1a hash each octet of the string
3455 /* xor the bottom with the current octet */
3456 hval ^= (mdb_hash_t)*s++;
3458 /* multiply by the 64 bit FNV magic prime mod 2^64 */
3459 hval += (hval << 1) + (hval << 4) + (hval << 5) +
3460 (hval << 7) + (hval << 8) + (hval << 40);
3462 /* return our new hash value */
3466 /** Hash the string and output the hash in hex.
3467 * @param[in] str string to hash
3468 * @param[out] hexbuf an array of 17 chars to hold the hash
3471 mdb_hash_hex(MDB_val *val, char *hexbuf)
3474 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
3475 for (i=0; i<8; i++) {
3476 hexbuf += sprintf(hexbuf, "%02x", (unsigned int)h & 0xff);
3482 /** Open and/or initialize the lock region for the environment.
3483 * @param[in] env The MDB environment.
3484 * @param[in] lpath The pathname of the file used for the lock region.
3485 * @param[in] mode The Unix permissions for the file, if we create it.
3486 * @param[out] excl Resulting file lock type: -1 none, 0 shared, 1 exclusive
3487 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
3488 * @return 0 on success, non-zero on failure.
3491 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
3494 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
3496 # define MDB_ERRCODE_ROFS EROFS
3497 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
3498 # define MDB_CLOEXEC O_CLOEXEC
3501 # define MDB_CLOEXEC 0
3508 env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
3509 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
3510 FILE_ATTRIBUTE_NORMAL, NULL);
3512 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
3514 if (env->me_lfd == INVALID_HANDLE_VALUE) {
3516 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
3521 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
3522 /* Lose record locks when exec*() */
3523 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
3524 fcntl(env->me_lfd, F_SETFD, fdflags);
3527 if (!(env->me_flags & MDB_NOTLS)) {
3528 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
3531 env->me_flags |= MDB_ENV_TXKEY;
3533 /* Windows TLS callbacks need help finding their TLS info. */
3534 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
3538 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
3542 /* Try to get exclusive lock. If we succeed, then
3543 * nobody is using the lock region and we should initialize it.
3545 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
3548 size = GetFileSize(env->me_lfd, NULL);
3550 size = lseek(env->me_lfd, 0, SEEK_END);
3551 if (size == -1) goto fail_errno;
3553 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
3554 if (size < rsize && *excl > 0) {
3556 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != rsize
3557 || !SetEndOfFile(env->me_lfd))
3560 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
3564 size = rsize - sizeof(MDB_txninfo);
3565 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
3570 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
3572 if (!mh) goto fail_errno;
3573 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
3575 if (!env->me_txns) goto fail_errno;
3577 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
3579 if (m == MAP_FAILED) goto fail_errno;
3585 BY_HANDLE_FILE_INFORMATION stbuf;
3594 if (!mdb_sec_inited) {
3595 InitializeSecurityDescriptor(&mdb_null_sd,
3596 SECURITY_DESCRIPTOR_REVISION);
3597 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
3598 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
3599 mdb_all_sa.bInheritHandle = FALSE;
3600 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
3603 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
3604 idbuf.volume = stbuf.dwVolumeSerialNumber;
3605 idbuf.nhigh = stbuf.nFileIndexHigh;
3606 idbuf.nlow = stbuf.nFileIndexLow;
3607 val.mv_data = &idbuf;
3608 val.mv_size = sizeof(idbuf);
3609 mdb_hash_hex(&val, hexbuf);
3610 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", hexbuf);
3611 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", hexbuf);
3612 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
3613 if (!env->me_rmutex) goto fail_errno;
3614 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
3615 if (!env->me_wmutex) goto fail_errno;
3616 #elif defined(MDB_USE_POSIX_SEM)
3625 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
3626 idbuf.dev = stbuf.st_dev;
3627 idbuf.ino = stbuf.st_ino;
3628 val.mv_data = &idbuf;
3629 val.mv_size = sizeof(idbuf);
3630 mdb_hash_hex(&val, hexbuf);
3631 sprintf(env->me_txns->mti_rmname, "/MDBr%s", hexbuf);
3632 sprintf(env->me_txns->mti_wmname, "/MDBw%s", hexbuf);
3633 /* Clean up after a previous run, if needed: Try to
3634 * remove both semaphores before doing anything else.
3636 sem_unlink(env->me_txns->mti_rmname);
3637 sem_unlink(env->me_txns->mti_wmname);
3638 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
3639 O_CREAT|O_EXCL, mode, 1);
3640 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3641 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
3642 O_CREAT|O_EXCL, mode, 1);
3643 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3644 #else /* MDB_USE_POSIX_SEM */
3645 pthread_mutexattr_t mattr;
3647 if ((rc = pthread_mutexattr_init(&mattr))
3648 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
3649 || (rc = pthread_mutex_init(&env->me_txns->mti_mutex, &mattr))
3650 || (rc = pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr)))
3652 pthread_mutexattr_destroy(&mattr);
3653 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
3655 env->me_txns->mti_version = MDB_VERSION;
3656 env->me_txns->mti_magic = MDB_MAGIC;
3657 env->me_txns->mti_txnid = 0;
3658 env->me_txns->mti_numreaders = 0;
3661 if (env->me_txns->mti_magic != MDB_MAGIC) {
3662 DPUTS("lock region has invalid magic");
3666 if (env->me_txns->mti_version != MDB_VERSION) {
3667 DPRINTF("lock region is version %u, expected version %u",
3668 env->me_txns->mti_version, MDB_VERSION);
3669 rc = MDB_VERSION_MISMATCH;
3673 if (rc && rc != EACCES && rc != EAGAIN) {
3677 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
3678 if (!env->me_rmutex) goto fail_errno;
3679 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
3680 if (!env->me_wmutex) goto fail_errno;
3681 #elif defined(MDB_USE_POSIX_SEM)
3682 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
3683 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3684 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
3685 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3696 /** The name of the lock file in the DB environment */
3697 #define LOCKNAME "/lock.mdb"
3698 /** The name of the data file in the DB environment */
3699 #define DATANAME "/data.mdb"
3700 /** The suffix of the lock file when no subdir is used */
3701 #define LOCKSUFF "-lock"
3702 /** Only a subset of the @ref mdb_env flags can be changed
3703 * at runtime. Changing other flags requires closing the
3704 * environment and re-opening it with the new flags.
3706 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC)
3707 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY|MDB_WRITEMAP|MDB_NOTLS)
3710 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
3712 int oflags, rc, len, excl = -1;
3713 char *lpath, *dpath;
3715 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
3719 if (flags & MDB_NOSUBDIR) {
3720 rc = len + sizeof(LOCKSUFF) + len + 1;
3722 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
3727 if (flags & MDB_NOSUBDIR) {
3728 dpath = lpath + len + sizeof(LOCKSUFF);
3729 sprintf(lpath, "%s" LOCKSUFF, path);
3730 strcpy(dpath, path);
3732 dpath = lpath + len + sizeof(LOCKNAME);
3733 sprintf(lpath, "%s" LOCKNAME, path);
3734 sprintf(dpath, "%s" DATANAME, path);
3738 flags |= env->me_flags;
3739 if (flags & MDB_RDONLY) {
3740 /* silently ignore WRITEMAP when we're only getting read access */
3741 flags &= ~MDB_WRITEMAP;
3743 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
3744 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
3747 env->me_flags = flags |= MDB_ENV_ACTIVE;
3751 env->me_path = strdup(path);
3752 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
3753 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
3754 if (!(env->me_dbxs && env->me_path && env->me_dbflags)) {
3759 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
3764 if (F_ISSET(flags, MDB_RDONLY)) {
3765 oflags = GENERIC_READ;
3766 len = OPEN_EXISTING;
3768 oflags = GENERIC_READ|GENERIC_WRITE;
3771 mode = FILE_ATTRIBUTE_NORMAL;
3772 env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
3773 NULL, len, mode, NULL);
3775 if (F_ISSET(flags, MDB_RDONLY))
3778 oflags = O_RDWR | O_CREAT;
3780 env->me_fd = open(dpath, oflags, mode);
3782 if (env->me_fd == INVALID_HANDLE_VALUE) {
3787 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
3788 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
3789 env->me_mfd = env->me_fd;
3791 /* Synchronous fd for meta writes. Needed even with
3792 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
3795 env->me_mfd = CreateFile(dpath, oflags,
3796 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
3797 mode | FILE_FLAG_WRITE_THROUGH, NULL);
3799 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
3801 if (env->me_mfd == INVALID_HANDLE_VALUE) {
3806 DPRINTF("opened dbenv %p", (void *) env);
3808 rc = mdb_env_share_locks(env, &excl);
3814 mdb_env_close0(env, excl);
3820 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
3822 mdb_env_close0(MDB_env *env, int excl)
3826 if (!(env->me_flags & MDB_ENV_ACTIVE))
3829 /* Doing this here since me_dbxs may not exist during mdb_env_close */
3830 for (i = env->me_maxdbs; --i > MAIN_DBI; )
3831 free(env->me_dbxs[i].md_name.mv_data);
3833 free(env->me_dbflags);
3836 free(env->me_dirty_list);
3837 mdb_midl_free(env->me_free_pgs);
3839 if (env->me_flags & MDB_ENV_TXKEY) {
3840 pthread_key_delete(env->me_txkey);
3842 /* Delete our key from the global list */
3843 for (i=0; i<mdb_tls_nkeys; i++)
3844 if (mdb_tls_keys[i] == env->me_txkey) {
3845 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
3853 munmap(env->me_map, env->me_mapsize);
3855 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
3856 (void) close(env->me_mfd);
3857 if (env->me_fd != INVALID_HANDLE_VALUE)
3858 (void) close(env->me_fd);
3860 pid_t pid = env->me_pid;
3861 /* Clearing readers is done in this function because
3862 * me_txkey with its destructor must be disabled first.
3864 for (i = env->me_numreaders; --i >= 0; )
3865 if (env->me_txns->mti_readers[i].mr_pid == pid)
3866 env->me_txns->mti_readers[i].mr_pid = 0;
3868 if (env->me_rmutex) {
3869 CloseHandle(env->me_rmutex);
3870 if (env->me_wmutex) CloseHandle(env->me_wmutex);
3872 /* Windows automatically destroys the mutexes when
3873 * the last handle closes.
3875 #elif defined(MDB_USE_POSIX_SEM)
3876 if (env->me_rmutex != SEM_FAILED) {
3877 sem_close(env->me_rmutex);
3878 if (env->me_wmutex != SEM_FAILED)
3879 sem_close(env->me_wmutex);
3880 /* If we have the filelock: If we are the
3881 * only remaining user, clean up semaphores.
3884 mdb_env_excl_lock(env, &excl);
3886 sem_unlink(env->me_txns->mti_rmname);
3887 sem_unlink(env->me_txns->mti_wmname);
3891 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
3893 if (env->me_lfd != INVALID_HANDLE_VALUE) {
3896 /* Unlock the lockfile. Windows would have unlocked it
3897 * after closing anyway, but not necessarily at once.
3899 UnlockFile(env->me_lfd, 0, 0, 1, 0);
3902 (void) close(env->me_lfd);
3905 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
3909 mdb_env_copyfd(MDB_env *env, HANDLE fd)
3911 MDB_txn *txn = NULL;
3916 /* Do the lock/unlock of the reader mutex before starting the
3917 * write txn. Otherwise other read txns could block writers.
3919 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
3924 /* We must start the actual read txn after blocking writers */
3925 mdb_txn_reset0(txn, "reset-stage1");
3927 /* Temporarily block writers until we snapshot the meta pages */
3930 rc = mdb_txn_renew0(txn);
3932 UNLOCK_MUTEX_W(env);
3937 wsize = env->me_psize * 2;
3941 rc = WriteFile(fd, env->me_map, wsize, &len, NULL);
3942 rc = rc ? (len == wsize ? MDB_SUCCESS : EIO) : ErrCode();
3945 rc = write(fd, env->me_map, wsize);
3946 rc = rc == (int)wsize ? MDB_SUCCESS : rc < 0 ? ErrCode() : EIO;
3949 UNLOCK_MUTEX_W(env);
3954 ptr = env->me_map + wsize;
3955 wsize = txn->mt_next_pgno * env->me_psize - wsize;
3959 if (wsize > MAX_WRITE)
3963 rc = WriteFile(fd, ptr, w2, &len, NULL);
3964 rc = rc ? (len == w2 ? MDB_SUCCESS : EIO) : ErrCode();
3973 if (wsize > MAX_WRITE)
3977 wres = write(fd, ptr, w2);
3978 rc = wres == (ssize_t)w2 ? MDB_SUCCESS : wres < 0 ? ErrCode() : EIO;
3991 mdb_env_copy(MDB_env *env, const char *path)
3995 HANDLE newfd = INVALID_HANDLE_VALUE;
3997 if (env->me_flags & MDB_NOSUBDIR) {
3998 lpath = (char *)path;
4001 len += sizeof(DATANAME);
4002 lpath = malloc(len);
4005 sprintf(lpath, "%s" DATANAME, path);
4008 /* The destination path must exist, but the destination file must not.
4009 * We don't want the OS to cache the writes, since the source data is
4010 * already in the OS cache.
4013 newfd = CreateFile(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
4014 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
4016 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL
4022 if (newfd == INVALID_HANDLE_VALUE) {
4027 #ifdef F_NOCACHE /* __APPLE__ */
4028 rc = fcntl(newfd, F_NOCACHE, 1);
4035 rc = mdb_env_copyfd(env, newfd);
4038 if (!(env->me_flags & MDB_NOSUBDIR))
4040 if (newfd != INVALID_HANDLE_VALUE)
4041 if (close(newfd) < 0 && rc == MDB_SUCCESS)
4048 mdb_env_close(MDB_env *env)
4055 VGMEMP_DESTROY(env);
4056 while ((dp = env->me_dpages) != NULL) {
4057 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
4058 env->me_dpages = dp->mp_next;
4062 mdb_env_close0(env, 0);
4066 /** Compare two items pointing at aligned size_t's */
4068 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
4070 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
4071 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
4074 /** Compare two items pointing at aligned int's */
4076 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
4078 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
4079 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
4082 /** Compare two items pointing at ints of unknown alignment.
4083 * Nodes and keys are guaranteed to be 2-byte aligned.
4086 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
4088 #if BYTE_ORDER == LITTLE_ENDIAN
4089 unsigned short *u, *c;
4092 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4093 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
4096 } while(!x && u > (unsigned short *)a->mv_data);
4099 return memcmp(a->mv_data, b->mv_data, a->mv_size);
4103 /** Compare two items lexically */
4105 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
4112 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4118 diff = memcmp(a->mv_data, b->mv_data, len);
4119 return diff ? diff : len_diff<0 ? -1 : len_diff;
4122 /** Compare two items in reverse byte order */
4124 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
4126 const unsigned char *p1, *p2, *p1_lim;
4130 p1_lim = (const unsigned char *)a->mv_data;
4131 p1 = (const unsigned char *)a->mv_data + a->mv_size;
4132 p2 = (const unsigned char *)b->mv_data + b->mv_size;
4134 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4140 while (p1 > p1_lim) {
4141 diff = *--p1 - *--p2;
4145 return len_diff<0 ? -1 : len_diff;
4148 /** Search for key within a page, using binary search.
4149 * Returns the smallest entry larger or equal to the key.
4150 * If exactp is non-null, stores whether the found entry was an exact match
4151 * in *exactp (1 or 0).
4152 * Updates the cursor index with the index of the found entry.
4153 * If no entry larger or equal to the key is found, returns NULL.
4156 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
4158 unsigned int i = 0, nkeys;
4161 MDB_page *mp = mc->mc_pg[mc->mc_top];
4162 MDB_node *node = NULL;
4167 nkeys = NUMKEYS(mp);
4172 COPY_PGNO(pgno, mp->mp_pgno);
4173 DPRINTF("searching %u keys in %s %spage %zu",
4174 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
4181 low = IS_LEAF(mp) ? 0 : 1;
4183 cmp = mc->mc_dbx->md_cmp;
4185 /* Branch pages have no data, so if using integer keys,
4186 * alignment is guaranteed. Use faster mdb_cmp_int.
4188 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
4189 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
4196 nodekey.mv_size = mc->mc_db->md_pad;
4197 node = NODEPTR(mp, 0); /* fake */
4198 while (low <= high) {
4199 i = (low + high) >> 1;
4200 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
4201 rc = cmp(key, &nodekey);
4202 DPRINTF("found leaf index %u [%s], rc = %i",
4203 i, DKEY(&nodekey), rc);
4212 while (low <= high) {
4213 i = (low + high) >> 1;
4215 node = NODEPTR(mp, i);
4216 nodekey.mv_size = NODEKSZ(node);
4217 nodekey.mv_data = NODEKEY(node);
4219 rc = cmp(key, &nodekey);
4222 DPRINTF("found leaf index %u [%s], rc = %i",
4223 i, DKEY(&nodekey), rc);
4225 DPRINTF("found branch index %u [%s -> %zu], rc = %i",
4226 i, DKEY(&nodekey), NODEPGNO(node), rc);
4237 if (rc > 0) { /* Found entry is less than the key. */
4238 i++; /* Skip to get the smallest entry larger than key. */
4240 node = NODEPTR(mp, i);
4243 *exactp = (rc == 0);
4244 /* store the key index */
4245 mc->mc_ki[mc->mc_top] = i;
4247 /* There is no entry larger or equal to the key. */
4250 /* nodeptr is fake for LEAF2 */
4256 mdb_cursor_adjust(MDB_cursor *mc, func)
4260 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4261 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
4268 /** Pop a page off the top of the cursor's stack. */
4270 mdb_cursor_pop(MDB_cursor *mc)
4273 #ifndef MDB_DEBUG_SKIP
4274 MDB_page *top = mc->mc_pg[mc->mc_top];
4280 DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
4281 mc->mc_dbi, (void *) mc);
4285 /** Push a page onto the top of the cursor's stack. */
4287 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
4289 DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
4290 mc->mc_dbi, (void *) mc);
4292 if (mc->mc_snum >= CURSOR_STACK) {
4293 assert(mc->mc_snum < CURSOR_STACK);
4294 return MDB_CURSOR_FULL;
4297 mc->mc_top = mc->mc_snum++;
4298 mc->mc_pg[mc->mc_top] = mp;
4299 mc->mc_ki[mc->mc_top] = 0;
4304 /** Find the address of the page corresponding to a given page number.
4305 * @param[in] txn the transaction for this access.
4306 * @param[in] pgno the page number for the page to retrieve.
4307 * @param[out] ret address of a pointer where the page's address will be stored.
4308 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
4309 * @return 0 on success, non-zero on failure.
4312 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
4317 if (!((txn->mt_flags & MDB_TXN_RDONLY) |
4318 (txn->mt_env->me_flags & MDB_WRITEMAP)))
4323 MDB_ID2L dl = tx2->mt_u.dirty_list;
4325 /* Spilled pages were dirtied in this txn and flushed
4326 * because the dirty list got full. Bring this page
4327 * back in from the map (but don't unspill it here,
4328 * leave that unless page_touch happens again).
4330 if (tx2->mt_spill_pgs) {
4331 x = mdb_midl_search(tx2->mt_spill_pgs, pgno);
4332 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pgno) {
4333 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
4338 unsigned x = mdb_mid2l_search(dl, pgno);
4339 if (x <= dl[0].mid && dl[x].mid == pgno) {
4345 } while ((tx2 = tx2->mt_parent) != NULL);
4348 if (pgno < txn->mt_next_pgno) {
4350 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
4352 DPRINTF("page %zu not found", pgno);
4354 return MDB_PAGE_NOTFOUND;
4364 /** Search for the page a given key should be in.
4365 * Pushes parent pages on the cursor stack. This function continues a
4366 * search on a cursor that has already been initialized. (Usually by
4367 * #mdb_page_search() but also by #mdb_node_move().)
4368 * @param[in,out] mc the cursor for this operation.
4369 * @param[in] key the key to search for. If NULL, search for the lowest
4370 * page. (This is used by #mdb_cursor_first().)
4371 * @param[in] modify If true, visited pages are updated with new page numbers.
4372 * @return 0 on success, non-zero on failure.
4375 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
4377 MDB_page *mp = mc->mc_pg[mc->mc_top];
4382 while (IS_BRANCH(mp)) {
4386 DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
4387 assert(NUMKEYS(mp) > 1);
4388 DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
4390 if (key == NULL) /* Initialize cursor to first page. */
4392 else if (key->mv_size > MDB_MAXKEYSIZE && key->mv_data == NULL) {
4393 /* cursor to last page */
4397 node = mdb_node_search(mc, key, &exact);
4399 i = NUMKEYS(mp) - 1;
4401 i = mc->mc_ki[mc->mc_top];
4410 DPRINTF("following index %u for key [%s]",
4412 assert(i < NUMKEYS(mp));
4413 node = NODEPTR(mp, i);
4415 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4418 mc->mc_ki[mc->mc_top] = i;
4419 if ((rc = mdb_cursor_push(mc, mp)))
4423 if ((rc = mdb_page_touch(mc)) != 0)
4425 mp = mc->mc_pg[mc->mc_top];
4430 DPRINTF("internal error, index points to a %02X page!?",
4432 return MDB_CORRUPTED;
4435 DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
4436 key ? DKEY(key) : NULL);
4437 mc->mc_flags |= C_INITIALIZED;
4438 mc->mc_flags &= ~C_EOF;
4443 /** Search for the lowest key under the current branch page.
4444 * This just bypasses a NUMKEYS check in the current page
4445 * before calling mdb_page_search_root(), because the callers
4446 * are all in situations where the current page is known to
4450 mdb_page_search_lowest(MDB_cursor *mc)
4452 MDB_page *mp = mc->mc_pg[mc->mc_top];
4453 MDB_node *node = NODEPTR(mp, 0);
4456 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4459 mc->mc_ki[mc->mc_top] = 0;
4460 if ((rc = mdb_cursor_push(mc, mp)))
4462 return mdb_page_search_root(mc, NULL, 0);
4465 /** Search for the page a given key should be in.
4466 * Pushes parent pages on the cursor stack. This function just sets up
4467 * the search; it finds the root page for \b mc's database and sets this
4468 * as the root of the cursor's stack. Then #mdb_page_search_root() is
4469 * called to complete the search.
4470 * @param[in,out] mc the cursor for this operation.
4471 * @param[in] key the key to search for. If NULL, search for the lowest
4472 * page. (This is used by #mdb_cursor_first().)
4473 * @param[in] flags If MDB_PS_MODIFY set, visited pages are updated with new page numbers.
4474 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
4475 * @return 0 on success, non-zero on failure.
4478 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
4483 /* Make sure the txn is still viable, then find the root from
4484 * the txn's db table.
4486 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
4487 DPUTS("transaction has failed, must abort");
4490 /* Make sure we're using an up-to-date root */
4491 if (mc->mc_dbi > MAIN_DBI) {
4492 if ((*mc->mc_dbflag & DB_STALE) ||
4493 ((flags & MDB_PS_MODIFY) && !(*mc->mc_dbflag & DB_DIRTY))) {
4495 unsigned char dbflag = 0;
4496 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
4497 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, flags & MDB_PS_MODIFY);
4500 if (*mc->mc_dbflag & DB_STALE) {
4504 MDB_node *leaf = mdb_node_search(&mc2,
4505 &mc->mc_dbx->md_name, &exact);
4507 return MDB_NOTFOUND;
4508 rc = mdb_node_read(mc->mc_txn, leaf, &data);
4511 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
4513 /* The txn may not know this DBI, or another process may
4514 * have dropped and recreated the DB with other flags.
4516 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
4517 return MDB_INCOMPATIBLE;
4518 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
4520 if (flags & MDB_PS_MODIFY)
4522 *mc->mc_dbflag &= ~DB_STALE;
4523 *mc->mc_dbflag |= dbflag;
4526 root = mc->mc_db->md_root;
4528 if (root == P_INVALID) { /* Tree is empty. */
4529 DPUTS("tree is empty");
4530 return MDB_NOTFOUND;
4535 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
4536 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0], NULL)) != 0)
4542 DPRINTF("db %u root page %zu has flags 0x%X",
4543 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
4545 if (flags & MDB_PS_MODIFY) {
4546 if ((rc = mdb_page_touch(mc)))
4550 if (flags & MDB_PS_ROOTONLY)
4553 return mdb_page_search_root(mc, key, flags);
4557 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
4559 MDB_txn *txn = mc->mc_txn;
4560 pgno_t pg = mp->mp_pgno;
4561 unsigned i, ovpages = mp->mp_pages;
4562 MDB_env *env = txn->mt_env;
4565 DPRINTF("free ov page %zu (%d)", pg, ovpages);
4566 /* If the page is dirty or on the spill list we just acquired it,
4567 * so we should give it back to our current free list, if any.
4568 * Not currently supported in nested txns.
4569 * Otherwise put it onto the list of pages we freed in this txn.
4571 if (!(mp->mp_flags & P_DIRTY) && txn->mt_spill_pgs) {
4572 unsigned x = mdb_midl_search(txn->mt_spill_pgs, pg);
4573 if (x <= txn->mt_spill_pgs[0] && txn->mt_spill_pgs[x] == pg) {
4574 /* This page is no longer spilled */
4575 for (; x < txn->mt_spill_pgs[0]; x++)
4576 txn->mt_spill_pgs[x] = txn->mt_spill_pgs[x+1];
4577 txn->mt_spill_pgs[0]--;
4581 if ((mp->mp_flags & P_DIRTY) && !txn->mt_parent && env->me_pghead) {
4584 MDB_ID2 *dl, ix, iy;
4585 rc = mdb_midl_need(&env->me_pghead, ovpages);
4588 /* Remove from dirty list */
4589 dl = txn->mt_u.dirty_list;
4591 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
4599 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
4600 txn->mt_flags |= MDB_TXN_ERROR;
4601 return MDB_CORRUPTED;
4604 if (!(env->me_flags & MDB_WRITEMAP))
4605 mdb_dpage_free(env, mp);
4607 /* Insert in me_pghead */
4608 mop = env->me_pghead;
4609 j = mop[0] + ovpages;
4610 for (i = mop[0]; i && mop[i] < pg; i--)
4616 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
4620 mc->mc_db->md_overflow_pages -= ovpages;
4624 /** Return the data associated with a given node.
4625 * @param[in] txn The transaction for this operation.
4626 * @param[in] leaf The node being read.
4627 * @param[out] data Updated to point to the node's data.
4628 * @return 0 on success, non-zero on failure.
4631 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
4633 MDB_page *omp; /* overflow page */
4637 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
4638 data->mv_size = NODEDSZ(leaf);
4639 data->mv_data = NODEDATA(leaf);
4643 /* Read overflow data.
4645 data->mv_size = NODEDSZ(leaf);
4646 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
4647 if ((rc = mdb_page_get(txn, pgno, &omp, NULL)) != 0) {
4648 DPRINTF("read overflow page %zu failed", pgno);
4651 data->mv_data = METADATA(omp);
4657 mdb_get(MDB_txn *txn, MDB_dbi dbi,
4658 MDB_val *key, MDB_val *data)
4667 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
4669 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
4672 if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
4676 mdb_cursor_init(&mc, txn, dbi, &mx);
4677 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
4680 /** Find a sibling for a page.
4681 * Replaces the page at the top of the cursor's stack with the
4682 * specified sibling, if one exists.
4683 * @param[in] mc The cursor for this operation.
4684 * @param[in] move_right Non-zero if the right sibling is requested,
4685 * otherwise the left sibling.
4686 * @return 0 on success, non-zero on failure.
4689 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
4695 if (mc->mc_snum < 2) {
4696 return MDB_NOTFOUND; /* root has no siblings */
4700 DPRINTF("parent page is page %zu, index %u",
4701 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]);
4703 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
4704 : (mc->mc_ki[mc->mc_top] == 0)) {
4705 DPRINTF("no more keys left, moving to %s sibling",
4706 move_right ? "right" : "left");
4707 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
4708 /* undo cursor_pop before returning */
4715 mc->mc_ki[mc->mc_top]++;
4717 mc->mc_ki[mc->mc_top]--;
4718 DPRINTF("just moving to %s index key %u",
4719 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]);
4721 assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
4723 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4724 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL) != 0))
4727 mdb_cursor_push(mc, mp);
4729 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
4734 /** Move the cursor to the next data item. */
4736 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
4742 if (mc->mc_flags & C_EOF) {
4743 return MDB_NOTFOUND;
4746 assert(mc->mc_flags & C_INITIALIZED);
4748 mp = mc->mc_pg[mc->mc_top];
4750 if (mc->mc_db->md_flags & MDB_DUPSORT) {
4751 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4752 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4753 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
4754 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
4755 if (op != MDB_NEXT || rc != MDB_NOTFOUND)
4759 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
4760 if (op == MDB_NEXT_DUP)
4761 return MDB_NOTFOUND;
4765 DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
4767 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
4768 DPUTS("=====> move to next sibling page");
4769 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
4770 mc->mc_flags |= C_EOF;
4773 mp = mc->mc_pg[mc->mc_top];
4774 DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
4776 mc->mc_ki[mc->mc_top]++;
4778 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
4779 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
4782 key->mv_size = mc->mc_db->md_pad;
4783 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
4787 assert(IS_LEAF(mp));
4788 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4790 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4791 mdb_xcursor_init1(mc, leaf);
4794 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4797 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4798 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4799 if (rc != MDB_SUCCESS)
4804 MDB_GET_KEY(leaf, key);
4808 /** Move the cursor to the previous data item. */
4810 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
4816 assert(mc->mc_flags & C_INITIALIZED);
4818 mp = mc->mc_pg[mc->mc_top];
4820 if (mc->mc_db->md_flags & MDB_DUPSORT) {
4821 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4822 if (op == MDB_PREV || op == MDB_PREV_DUP) {
4823 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4824 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
4825 if (op != MDB_PREV || rc != MDB_NOTFOUND)
4828 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
4829 if (op == MDB_PREV_DUP)
4830 return MDB_NOTFOUND;
4835 DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
4837 if (mc->mc_ki[mc->mc_top] == 0) {
4838 DPUTS("=====> move to prev sibling page");
4839 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
4842 mp = mc->mc_pg[mc->mc_top];
4843 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
4844 DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
4846 mc->mc_ki[mc->mc_top]--;
4848 mc->mc_flags &= ~C_EOF;
4850 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
4851 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
4854 key->mv_size = mc->mc_db->md_pad;
4855 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
4859 assert(IS_LEAF(mp));
4860 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4862 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4863 mdb_xcursor_init1(mc, leaf);
4866 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4869 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4870 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
4871 if (rc != MDB_SUCCESS)
4876 MDB_GET_KEY(leaf, key);
4880 /** Set the cursor on a specific data item. */
4882 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
4883 MDB_cursor_op op, int *exactp)
4887 MDB_node *leaf = NULL;
4892 assert(key->mv_size > 0);
4895 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
4897 /* See if we're already on the right page */
4898 if (mc->mc_flags & C_INITIALIZED) {
4901 mp = mc->mc_pg[mc->mc_top];
4903 mc->mc_ki[mc->mc_top] = 0;
4904 return MDB_NOTFOUND;
4906 if (mp->mp_flags & P_LEAF2) {
4907 nodekey.mv_size = mc->mc_db->md_pad;
4908 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
4910 leaf = NODEPTR(mp, 0);
4911 MDB_GET_KEY(leaf, &nodekey);
4913 rc = mc->mc_dbx->md_cmp(key, &nodekey);
4915 /* Probably happens rarely, but first node on the page
4916 * was the one we wanted.
4918 mc->mc_ki[mc->mc_top] = 0;
4925 unsigned int nkeys = NUMKEYS(mp);
4927 if (mp->mp_flags & P_LEAF2) {
4928 nodekey.mv_data = LEAF2KEY(mp,
4929 nkeys-1, nodekey.mv_size);
4931 leaf = NODEPTR(mp, nkeys-1);
4932 MDB_GET_KEY(leaf, &nodekey);
4934 rc = mc->mc_dbx->md_cmp(key, &nodekey);
4936 /* last node was the one we wanted */
4937 mc->mc_ki[mc->mc_top] = nkeys-1;
4943 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
4944 /* This is definitely the right page, skip search_page */
4945 if (mp->mp_flags & P_LEAF2) {
4946 nodekey.mv_data = LEAF2KEY(mp,
4947 mc->mc_ki[mc->mc_top], nodekey.mv_size);
4949 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4950 MDB_GET_KEY(leaf, &nodekey);
4952 rc = mc->mc_dbx->md_cmp(key, &nodekey);
4954 /* current node was the one we wanted */
4964 /* If any parents have right-sibs, search.
4965 * Otherwise, there's nothing further.
4967 for (i=0; i<mc->mc_top; i++)
4969 NUMKEYS(mc->mc_pg[i])-1)
4971 if (i == mc->mc_top) {
4972 /* There are no other pages */
4973 mc->mc_ki[mc->mc_top] = nkeys;
4974 return MDB_NOTFOUND;
4978 /* There are no other pages */
4979 mc->mc_ki[mc->mc_top] = 0;
4980 return MDB_NOTFOUND;
4984 rc = mdb_page_search(mc, key, 0);
4985 if (rc != MDB_SUCCESS)
4988 mp = mc->mc_pg[mc->mc_top];
4989 assert(IS_LEAF(mp));
4992 leaf = mdb_node_search(mc, key, exactp);
4993 if (exactp != NULL && !*exactp) {
4994 /* MDB_SET specified and not an exact match. */
4995 return MDB_NOTFOUND;
4999 DPUTS("===> inexact leaf not found, goto sibling");
5000 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
5001 return rc; /* no entries matched */
5002 mp = mc->mc_pg[mc->mc_top];
5003 assert(IS_LEAF(mp));
5004 leaf = NODEPTR(mp, 0);
5008 mc->mc_flags |= C_INITIALIZED;
5009 mc->mc_flags &= ~C_EOF;
5012 key->mv_size = mc->mc_db->md_pad;
5013 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5017 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5018 mdb_xcursor_init1(mc, leaf);
5021 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5022 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
5023 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5026 if (op == MDB_GET_BOTH) {
5032 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
5033 if (rc != MDB_SUCCESS)
5036 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
5038 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
5040 rc = mc->mc_dbx->md_dcmp(data, &d2);
5042 if (op == MDB_GET_BOTH || rc > 0)
5043 return MDB_NOTFOUND;
5048 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5049 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5054 /* The key already matches in all other cases */
5055 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
5056 MDB_GET_KEY(leaf, key);
5057 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
5062 /** Move the cursor to the first item in the database. */
5064 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5070 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5072 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5073 rc = mdb_page_search(mc, NULL, 0);
5074 if (rc != MDB_SUCCESS)
5077 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
5079 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
5080 mc->mc_flags |= C_INITIALIZED;
5081 mc->mc_flags &= ~C_EOF;
5083 mc->mc_ki[mc->mc_top] = 0;
5085 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5086 key->mv_size = mc->mc_db->md_pad;
5087 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
5092 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5093 mdb_xcursor_init1(mc, leaf);
5094 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5098 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5102 MDB_GET_KEY(leaf, key);
5106 /** Move the cursor to the last item in the database. */
5108 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5114 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5116 if (!(mc->mc_flags & C_EOF)) {
5118 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5121 lkey.mv_size = MDB_MAXKEYSIZE+1;
5122 lkey.mv_data = NULL;
5123 rc = mdb_page_search(mc, &lkey, 0);
5124 if (rc != MDB_SUCCESS)
5127 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
5130 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
5131 mc->mc_flags |= C_INITIALIZED|C_EOF;
5132 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5134 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5135 key->mv_size = mc->mc_db->md_pad;
5136 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
5141 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5142 mdb_xcursor_init1(mc, leaf);
5143 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5147 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5152 MDB_GET_KEY(leaf, key);
5157 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5166 case MDB_GET_CURRENT:
5167 if (!(mc->mc_flags & C_INITIALIZED)) {
5170 MDB_page *mp = mc->mc_pg[mc->mc_top];
5172 mc->mc_ki[mc->mc_top] = 0;
5178 key->mv_size = mc->mc_db->md_pad;
5179 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5181 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5182 MDB_GET_KEY(leaf, key);
5184 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5185 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
5187 rc = mdb_node_read(mc->mc_txn, leaf, data);
5194 case MDB_GET_BOTH_RANGE:
5195 if (data == NULL || mc->mc_xcursor == NULL) {
5203 if (key == NULL || key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
5205 } else if (op == MDB_SET_RANGE)
5206 rc = mdb_cursor_set(mc, key, data, op, NULL);
5208 rc = mdb_cursor_set(mc, key, data, op, &exact);
5210 case MDB_GET_MULTIPLE:
5212 !(mc->mc_db->md_flags & MDB_DUPFIXED) ||
5213 !(mc->mc_flags & C_INITIALIZED)) {
5218 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
5219 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
5222 case MDB_NEXT_MULTIPLE:
5224 !(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5228 if (!(mc->mc_flags & C_INITIALIZED))
5229 rc = mdb_cursor_first(mc, key, data);
5231 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
5232 if (rc == MDB_SUCCESS) {
5233 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
5236 mx = &mc->mc_xcursor->mx_cursor;
5237 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
5239 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
5240 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
5248 case MDB_NEXT_NODUP:
5249 if (!(mc->mc_flags & C_INITIALIZED))
5250 rc = mdb_cursor_first(mc, key, data);
5252 rc = mdb_cursor_next(mc, key, data, op);
5256 case MDB_PREV_NODUP:
5257 if (!(mc->mc_flags & C_INITIALIZED)) {
5258 rc = mdb_cursor_last(mc, key, data);
5261 mc->mc_flags |= C_INITIALIZED;
5262 mc->mc_ki[mc->mc_top]++;
5264 rc = mdb_cursor_prev(mc, key, data, op);
5267 rc = mdb_cursor_first(mc, key, data);
5271 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
5272 !(mc->mc_flags & C_INITIALIZED) ||
5273 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
5277 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5280 rc = mdb_cursor_last(mc, key, data);
5284 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
5285 !(mc->mc_flags & C_INITIALIZED) ||
5286 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
5290 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5293 DPRINTF("unhandled/unimplemented cursor operation %u", op);
5301 /** Touch all the pages in the cursor stack.
5302 * Makes sure all the pages are writable, before attempting a write operation.
5303 * @param[in] mc The cursor to operate on.
5306 mdb_cursor_touch(MDB_cursor *mc)
5310 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
5313 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
5314 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
5317 *mc->mc_dbflag |= DB_DIRTY;
5319 for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
5320 rc = mdb_page_touch(mc);
5324 mc->mc_top = mc->mc_snum-1;
5328 /** Do not spill pages to disk if txn is getting full, may fail instead */
5329 #define MDB_NOSPILL 0x8000
5332 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5335 enum { MDB_NO_ROOT = MDB_LAST_ERRCODE+10 }; /* internal code */
5336 MDB_node *leaf = NULL;
5337 MDB_val xdata, *rdata, dkey;
5340 int do_sub = 0, insert = 0;
5341 unsigned int mcount = 0, dcount = 0, nospill;
5345 char dbuf[MDB_MAXKEYSIZE+1];
5346 unsigned int nflags;
5349 /* Check this first so counter will always be zero on any
5352 if (flags & MDB_MULTIPLE) {
5353 dcount = data[1].mv_size;
5354 data[1].mv_size = 0;
5355 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
5359 nospill = flags & MDB_NOSPILL;
5360 flags &= ~MDB_NOSPILL;
5362 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
5365 if (flags != MDB_CURRENT && (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE))
5368 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT) && data->mv_size > MDB_MAXKEYSIZE)
5371 #if SIZE_MAX > MAXDATASIZE
5372 if (data->mv_size > MAXDATASIZE)
5376 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
5377 mc->mc_dbi, DKEY(key), key ? key->mv_size:0, data->mv_size);
5381 if (flags == MDB_CURRENT) {
5382 if (!(mc->mc_flags & C_INITIALIZED))
5385 } else if (mc->mc_db->md_root == P_INVALID) {
5386 /* new database, cursor has nothing to point to */
5388 mc->mc_flags &= ~C_INITIALIZED;
5393 if (flags & MDB_APPEND) {
5395 rc = mdb_cursor_last(mc, &k2, &d2);
5397 rc = mc->mc_dbx->md_cmp(key, &k2);
5400 mc->mc_ki[mc->mc_top]++;
5402 /* new key is <= last key */
5407 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
5409 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
5410 DPRINTF("duplicate key [%s]", DKEY(key));
5412 return MDB_KEYEXIST;
5414 if (rc && rc != MDB_NOTFOUND)
5418 /* Cursor is positioned, check for room in the dirty list */
5420 if (flags & MDB_MULTIPLE) {
5422 xdata.mv_size = data->mv_size * dcount;
5426 if ((rc2 = mdb_page_spill(mc, key, rdata)))
5430 if (rc == MDB_NO_ROOT) {
5432 /* new database, write a root leaf page */
5433 DPUTS("allocating new root leaf page");
5434 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
5437 mdb_cursor_push(mc, np);
5438 mc->mc_db->md_root = np->mp_pgno;
5439 mc->mc_db->md_depth++;
5440 *mc->mc_dbflag |= DB_DIRTY;
5441 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
5443 np->mp_flags |= P_LEAF2;
5444 mc->mc_flags |= C_INITIALIZED;
5446 /* make sure all cursor pages are writable */
5447 rc2 = mdb_cursor_touch(mc);
5452 /* The key already exists */
5453 if (rc == MDB_SUCCESS) {
5454 /* there's only a key anyway, so this is a no-op */
5455 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5456 unsigned int ksize = mc->mc_db->md_pad;
5457 if (key->mv_size != ksize)
5459 if (flags == MDB_CURRENT) {
5460 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
5461 memcpy(ptr, key->mv_data, ksize);
5466 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5469 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
5470 /* Was a single item before, must convert now */
5472 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5473 /* Just overwrite the current item */
5474 if (flags == MDB_CURRENT)
5477 dkey.mv_size = NODEDSZ(leaf);
5478 dkey.mv_data = NODEDATA(leaf);
5479 #if UINT_MAX < SIZE_MAX
5480 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && dkey.mv_size == sizeof(size_t))
5481 #ifdef MISALIGNED_OK
5482 mc->mc_dbx->md_dcmp = mdb_cmp_long;
5484 mc->mc_dbx->md_dcmp = mdb_cmp_cint;
5487 /* if data matches, ignore it */
5488 if (!mc->mc_dbx->md_dcmp(data, &dkey))
5489 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
5491 /* create a fake page for the dup items */
5492 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
5493 dkey.mv_data = dbuf;
5494 fp = (MDB_page *)&pbuf;
5495 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
5496 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
5497 fp->mp_lower = PAGEHDRSZ;
5498 fp->mp_upper = PAGEHDRSZ + dkey.mv_size + data->mv_size;
5499 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5500 fp->mp_flags |= P_LEAF2;
5501 fp->mp_pad = data->mv_size;
5502 fp->mp_upper += 2 * data->mv_size; /* leave space for 2 more */
5504 fp->mp_upper += 2 * sizeof(indx_t) + 2 * NODESIZE +
5505 (dkey.mv_size & 1) + (data->mv_size & 1);
5507 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5510 xdata.mv_size = fp->mp_upper;
5515 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
5516 /* See if we need to convert from fake page to subDB */
5518 unsigned int offset;
5522 fp = NODEDATA(leaf);
5523 if (flags == MDB_CURRENT) {
5525 fp->mp_flags |= P_DIRTY;
5526 COPY_PGNO(fp->mp_pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
5527 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
5531 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5532 offset = fp->mp_pad;
5533 if (SIZELEFT(fp) >= offset)
5535 offset *= 4; /* space for 4 more */
5537 offset = NODESIZE + sizeof(indx_t) + data->mv_size;
5539 offset += offset & 1;
5540 fp_flags = fp->mp_flags;
5541 if (NODESIZE + sizeof(indx_t) + NODEKSZ(leaf) + NODEDSZ(leaf) +
5542 offset >= mc->mc_txn->mt_env->me_nodemax) {
5543 /* yes, convert it */
5545 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5546 dummy.md_pad = fp->mp_pad;
5547 dummy.md_flags = MDB_DUPFIXED;
5548 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
5549 dummy.md_flags |= MDB_INTEGERKEY;
5552 dummy.md_branch_pages = 0;
5553 dummy.md_leaf_pages = 1;
5554 dummy.md_overflow_pages = 0;
5555 dummy.md_entries = NUMKEYS(fp);
5557 xdata.mv_size = sizeof(MDB_db);
5558 xdata.mv_data = &dummy;
5559 if ((rc = mdb_page_alloc(mc, 1, &mp)))
5561 offset = mc->mc_txn->mt_env->me_psize - NODEDSZ(leaf);
5562 flags |= F_DUPDATA|F_SUBDATA;
5563 dummy.md_root = mp->mp_pgno;
5564 fp_flags &= ~P_SUBP;
5566 /* no, just grow it */
5568 xdata.mv_size = NODEDSZ(leaf) + offset;
5569 xdata.mv_data = &pbuf;
5570 mp = (MDB_page *)&pbuf;
5571 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
5574 mp->mp_flags = fp_flags | P_DIRTY;
5575 mp->mp_pad = fp->mp_pad;
5576 mp->mp_lower = fp->mp_lower;
5577 mp->mp_upper = fp->mp_upper + offset;
5579 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
5581 nsize = NODEDSZ(leaf) - fp->mp_upper;
5582 memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper, nsize);
5583 for (i=0; i<NUMKEYS(fp); i++)
5584 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
5586 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5590 /* data is on sub-DB, just store it */
5591 flags |= F_DUPDATA|F_SUBDATA;
5595 /* overflow page overwrites need special handling */
5596 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5599 unsigned psize = mc->mc_txn->mt_env->me_psize;
5600 int level, ovpages, dpages = OVPAGES(data->mv_size, psize);
5602 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
5603 if ((rc2 = mdb_page_get(mc->mc_txn, pg, &omp, &level)) != 0)
5605 ovpages = omp->mp_pages;
5607 /* Is the ov page large enough? */
5608 if (ovpages >= dpages) {
5609 if (!(omp->mp_flags & P_DIRTY) &&
5610 (level || (mc->mc_txn->mt_env->me_flags & MDB_WRITEMAP)))
5612 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
5615 level = 0; /* dirty in this txn or clean */
5618 if (omp->mp_flags & P_DIRTY) {
5619 /* yes, overwrite it. Note in this case we don't
5620 * bother to try shrinking the page if the new data
5621 * is smaller than the overflow threshold.
5624 /* It is writable only in a parent txn */
5625 size_t sz = (size_t) psize * ovpages, off;
5626 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
5632 mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
5633 if (!(flags & MDB_RESERVE)) {
5634 /* Copy end of page, adjusting alignment so
5635 * compiler may copy words instead of bytes.
5637 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
5638 memcpy((size_t *)((char *)np + off),
5639 (size_t *)((char *)omp + off), sz - off);
5642 memcpy(np, omp, sz); /* Copy beginning of page */
5645 SETDSZ(leaf, data->mv_size);
5646 if (F_ISSET(flags, MDB_RESERVE))
5647 data->mv_data = METADATA(omp);
5649 memcpy(METADATA(omp), data->mv_data, data->mv_size);
5653 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
5655 } else if (NODEDSZ(leaf) == data->mv_size) {
5656 /* same size, just replace it. Note that we could
5657 * also reuse this node if the new data is smaller,
5658 * but instead we opt to shrink the node in that case.
5660 if (F_ISSET(flags, MDB_RESERVE))
5661 data->mv_data = NODEDATA(leaf);
5662 else if (data->mv_size)
5663 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
5665 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
5668 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5669 mc->mc_db->md_entries--;
5671 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
5678 nflags = flags & NODE_ADD_FLAGS;
5679 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
5680 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
5681 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
5682 nflags &= ~MDB_APPEND;
5684 nflags |= MDB_SPLIT_REPLACE;
5685 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
5687 /* There is room already in this leaf page. */
5688 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
5689 if (rc == 0 && !do_sub && insert) {
5690 /* Adjust other cursors pointing to mp */
5691 MDB_cursor *m2, *m3;
5692 MDB_dbi dbi = mc->mc_dbi;
5693 unsigned i = mc->mc_top;
5694 MDB_page *mp = mc->mc_pg[i];
5696 if (mc->mc_flags & C_SUB)
5699 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5700 if (mc->mc_flags & C_SUB)
5701 m3 = &m2->mc_xcursor->mx_cursor;
5704 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
5705 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
5712 if (rc != MDB_SUCCESS)
5713 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5715 /* Now store the actual data in the child DB. Note that we're
5716 * storing the user data in the keys field, so there are strict
5717 * size limits on dupdata. The actual data fields of the child
5718 * DB are all zero size.
5725 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5726 if (flags & MDB_CURRENT) {
5727 xflags = MDB_CURRENT|MDB_NOSPILL;
5729 mdb_xcursor_init1(mc, leaf);
5730 xflags = (flags & MDB_NODUPDATA) ?
5731 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
5733 /* converted, write the original data first */
5735 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
5739 /* Adjust other cursors pointing to mp */
5741 unsigned i = mc->mc_top;
5742 MDB_page *mp = mc->mc_pg[i];
5744 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5745 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
5746 if (!(m2->mc_flags & C_INITIALIZED)) continue;
5747 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
5748 mdb_xcursor_init1(m2, leaf);
5752 /* we've done our job */
5755 if (flags & MDB_APPENDDUP)
5756 xflags |= MDB_APPEND;
5757 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
5758 if (flags & F_SUBDATA) {
5759 void *db = NODEDATA(leaf);
5760 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
5763 /* sub-writes might have failed so check rc again.
5764 * Don't increment count if we just replaced an existing item.
5766 if (!rc && !(flags & MDB_CURRENT))
5767 mc->mc_db->md_entries++;
5768 if (flags & MDB_MULTIPLE) {
5771 if (mcount < dcount) {
5772 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
5773 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5777 /* let caller know how many succeeded, if any */
5778 data[1].mv_size = mcount;
5782 /* If we succeeded and the key didn't exist before, make sure
5783 * the cursor is marked valid.
5786 mc->mc_flags |= C_INITIALIZED;
5791 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
5796 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
5799 if (!(mc->mc_flags & C_INITIALIZED))
5802 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
5804 flags &= ~MDB_NOSPILL; /* TODO: Or change (flags != MDB_NODUPDATA) to ~(flags & MDB_NODUPDATA), not looking at the logic of that code just now */
5806 rc = mdb_cursor_touch(mc);
5810 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5812 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5813 if (flags != MDB_NODUPDATA) {
5814 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
5815 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
5817 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
5818 /* If sub-DB still has entries, we're done */
5819 if (mc->mc_xcursor->mx_db.md_entries) {
5820 if (leaf->mn_flags & F_SUBDATA) {
5821 /* update subDB info */
5822 void *db = NODEDATA(leaf);
5823 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
5826 /* shrink fake page */
5827 mdb_node_shrink(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5828 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5829 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
5830 /* fix other sub-DB cursors pointed at this fake page */
5831 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5832 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
5833 if (m2->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top] &&
5834 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
5835 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
5838 mc->mc_db->md_entries--;
5841 /* otherwise fall thru and delete the sub-DB */
5844 if (leaf->mn_flags & F_SUBDATA) {
5845 /* add all the child DB's pages to the free list */
5846 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
5847 if (rc == MDB_SUCCESS) {
5848 mc->mc_db->md_entries -=
5849 mc->mc_xcursor->mx_db.md_entries;
5854 return mdb_cursor_del0(mc, leaf);
5857 /** Allocate and initialize new pages for a database.
5858 * @param[in] mc a cursor on the database being added to.
5859 * @param[in] flags flags defining what type of page is being allocated.
5860 * @param[in] num the number of pages to allocate. This is usually 1,
5861 * unless allocating overflow pages for a large record.
5862 * @param[out] mp Address of a page, or NULL on failure.
5863 * @return 0 on success, non-zero on failure.
5866 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
5871 if ((rc = mdb_page_alloc(mc, num, &np)))
5873 DPRINTF("allocated new mpage %zu, page size %u",
5874 np->mp_pgno, mc->mc_txn->mt_env->me_psize);
5875 np->mp_flags = flags | P_DIRTY;
5876 np->mp_lower = PAGEHDRSZ;
5877 np->mp_upper = mc->mc_txn->mt_env->me_psize;
5880 mc->mc_db->md_branch_pages++;
5881 else if (IS_LEAF(np))
5882 mc->mc_db->md_leaf_pages++;
5883 else if (IS_OVERFLOW(np)) {
5884 mc->mc_db->md_overflow_pages += num;
5892 /** Calculate the size of a leaf node.
5893 * The size depends on the environment's page size; if a data item
5894 * is too large it will be put onto an overflow page and the node
5895 * size will only include the key and not the data. Sizes are always
5896 * rounded up to an even number of bytes, to guarantee 2-byte alignment
5897 * of the #MDB_node headers.
5898 * @param[in] env The environment handle.
5899 * @param[in] key The key for the node.
5900 * @param[in] data The data for the node.
5901 * @return The number of bytes needed to store the node.
5904 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
5908 sz = LEAFSIZE(key, data);
5909 if (sz >= env->me_nodemax) {
5910 /* put on overflow page */
5911 sz -= data->mv_size - sizeof(pgno_t);
5915 return sz + sizeof(indx_t);
5918 /** Calculate the size of a branch node.
5919 * The size should depend on the environment's page size but since
5920 * we currently don't support spilling large keys onto overflow
5921 * pages, it's simply the size of the #MDB_node header plus the
5922 * size of the key. Sizes are always rounded up to an even number
5923 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
5924 * @param[in] env The environment handle.
5925 * @param[in] key The key for the node.
5926 * @return The number of bytes needed to store the node.
5929 mdb_branch_size(MDB_env *env, MDB_val *key)
5934 if (sz >= env->me_nodemax) {
5935 /* put on overflow page */
5936 /* not implemented */
5937 /* sz -= key->size - sizeof(pgno_t); */
5940 return sz + sizeof(indx_t);
5943 /** Add a node to the page pointed to by the cursor.
5944 * @param[in] mc The cursor for this operation.
5945 * @param[in] indx The index on the page where the new node should be added.
5946 * @param[in] key The key for the new node.
5947 * @param[in] data The data for the new node, if any.
5948 * @param[in] pgno The page number, if adding a branch node.
5949 * @param[in] flags Flags for the node.
5950 * @return 0 on success, non-zero on failure. Possible errors are:
5952 * <li>ENOMEM - failed to allocate overflow pages for the node.
5953 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
5954 * should never happen since all callers already calculate the
5955 * page's free space before calling this function.
5959 mdb_node_add(MDB_cursor *mc, indx_t indx,
5960 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
5963 size_t node_size = NODESIZE;
5966 MDB_page *mp = mc->mc_pg[mc->mc_top];
5967 MDB_page *ofp = NULL; /* overflow page */
5970 assert(mp->mp_upper >= mp->mp_lower);
5972 DPRINTF("add to %s %spage %zu index %i, data size %zu key size %zu [%s]",
5973 IS_LEAF(mp) ? "leaf" : "branch",
5974 IS_SUBP(mp) ? "sub-" : "",
5975 mp->mp_pgno, indx, data ? data->mv_size : 0,
5976 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
5979 /* Move higher keys up one slot. */
5980 int ksize = mc->mc_db->md_pad, dif;
5981 char *ptr = LEAF2KEY(mp, indx, ksize);
5982 dif = NUMKEYS(mp) - indx;
5984 memmove(ptr+ksize, ptr, dif*ksize);
5985 /* insert new key */
5986 memcpy(ptr, key->mv_data, ksize);
5988 /* Just using these for counting */
5989 mp->mp_lower += sizeof(indx_t);
5990 mp->mp_upper -= ksize - sizeof(indx_t);
5995 node_size += key->mv_size;
5999 if (F_ISSET(flags, F_BIGDATA)) {
6000 /* Data already on overflow page. */
6001 node_size += sizeof(pgno_t);
6002 } else if (node_size + data->mv_size >= mc->mc_txn->mt_env->me_nodemax) {
6003 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
6005 /* Put data on overflow page. */
6006 DPRINTF("data size is %zu, node would be %zu, put data on overflow page",
6007 data->mv_size, node_size+data->mv_size);
6008 node_size += sizeof(pgno_t);
6009 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
6011 DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
6014 node_size += data->mv_size;
6017 node_size += node_size & 1;
6019 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
6020 DPRINTF("not enough room in page %zu, got %u ptrs",
6021 mp->mp_pgno, NUMKEYS(mp));
6022 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
6023 mp->mp_upper - mp->mp_lower);
6024 DPRINTF("node size = %zu", node_size);
6025 return MDB_PAGE_FULL;
6028 /* Move higher pointers up one slot. */
6029 for (i = NUMKEYS(mp); i > indx; i--)
6030 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
6032 /* Adjust free space offsets. */
6033 ofs = mp->mp_upper - node_size;
6034 assert(ofs >= mp->mp_lower + sizeof(indx_t));
6035 mp->mp_ptrs[indx] = ofs;
6037 mp->mp_lower += sizeof(indx_t);
6039 /* Write the node data. */
6040 node = NODEPTR(mp, indx);
6041 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
6042 node->mn_flags = flags;
6044 SETDSZ(node,data->mv_size);
6049 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6054 if (F_ISSET(flags, F_BIGDATA))
6055 memcpy(node->mn_data + key->mv_size, data->mv_data,
6057 else if (F_ISSET(flags, MDB_RESERVE))
6058 data->mv_data = node->mn_data + key->mv_size;
6060 memcpy(node->mn_data + key->mv_size, data->mv_data,
6063 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
6065 if (F_ISSET(flags, MDB_RESERVE))
6066 data->mv_data = METADATA(ofp);
6068 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
6075 /** Delete the specified node from a page.
6076 * @param[in] mp The page to operate on.
6077 * @param[in] indx The index of the node to delete.
6078 * @param[in] ksize The size of a node. Only used if the page is
6079 * part of a #MDB_DUPFIXED database.
6082 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
6085 indx_t i, j, numkeys, ptr;
6092 COPY_PGNO(pgno, mp->mp_pgno);
6093 DPRINTF("delete node %u on %s page %zu", indx,
6094 IS_LEAF(mp) ? "leaf" : "branch", pgno);
6097 assert(indx < NUMKEYS(mp));
6100 int x = NUMKEYS(mp) - 1 - indx;
6101 base = LEAF2KEY(mp, indx, ksize);
6103 memmove(base, base + ksize, x * ksize);
6104 mp->mp_lower -= sizeof(indx_t);
6105 mp->mp_upper += ksize - sizeof(indx_t);
6109 node = NODEPTR(mp, indx);
6110 sz = NODESIZE + node->mn_ksize;
6112 if (F_ISSET(node->mn_flags, F_BIGDATA))
6113 sz += sizeof(pgno_t);
6115 sz += NODEDSZ(node);
6119 ptr = mp->mp_ptrs[indx];
6120 numkeys = NUMKEYS(mp);
6121 for (i = j = 0; i < numkeys; i++) {
6123 mp->mp_ptrs[j] = mp->mp_ptrs[i];
6124 if (mp->mp_ptrs[i] < ptr)
6125 mp->mp_ptrs[j] += sz;
6130 base = (char *)mp + mp->mp_upper;
6131 memmove(base + sz, base, ptr - mp->mp_upper);
6133 mp->mp_lower -= sizeof(indx_t);
6137 /** Compact the main page after deleting a node on a subpage.
6138 * @param[in] mp The main page to operate on.
6139 * @param[in] indx The index of the subpage on the main page.
6142 mdb_node_shrink(MDB_page *mp, indx_t indx)
6149 indx_t i, numkeys, ptr;
6151 node = NODEPTR(mp, indx);
6152 sp = (MDB_page *)NODEDATA(node);
6153 osize = NODEDSZ(node);
6155 delta = sp->mp_upper - sp->mp_lower;
6156 SETDSZ(node, osize - delta);
6157 xp = (MDB_page *)((char *)sp + delta);
6159 /* shift subpage upward */
6161 nsize = NUMKEYS(sp) * sp->mp_pad;
6162 memmove(METADATA(xp), METADATA(sp), nsize);
6165 nsize = osize - sp->mp_upper;
6166 numkeys = NUMKEYS(sp);
6167 for (i=numkeys-1; i>=0; i--)
6168 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
6170 xp->mp_upper = sp->mp_lower;
6171 xp->mp_lower = sp->mp_lower;
6172 xp->mp_flags = sp->mp_flags;
6173 xp->mp_pad = sp->mp_pad;
6174 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
6176 /* shift lower nodes upward */
6177 ptr = mp->mp_ptrs[indx];
6178 numkeys = NUMKEYS(mp);
6179 for (i = 0; i < numkeys; i++) {
6180 if (mp->mp_ptrs[i] <= ptr)
6181 mp->mp_ptrs[i] += delta;
6184 base = (char *)mp + mp->mp_upper;
6185 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
6186 mp->mp_upper += delta;
6189 /** Initial setup of a sorted-dups cursor.
6190 * Sorted duplicates are implemented as a sub-database for the given key.
6191 * The duplicate data items are actually keys of the sub-database.
6192 * Operations on the duplicate data items are performed using a sub-cursor
6193 * initialized when the sub-database is first accessed. This function does
6194 * the preliminary setup of the sub-cursor, filling in the fields that
6195 * depend only on the parent DB.
6196 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6199 mdb_xcursor_init0(MDB_cursor *mc)
6201 MDB_xcursor *mx = mc->mc_xcursor;
6203 mx->mx_cursor.mc_xcursor = NULL;
6204 mx->mx_cursor.mc_txn = mc->mc_txn;
6205 mx->mx_cursor.mc_db = &mx->mx_db;
6206 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
6207 mx->mx_cursor.mc_dbi = mc->mc_dbi+1;
6208 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
6209 mx->mx_cursor.mc_snum = 0;
6210 mx->mx_cursor.mc_top = 0;
6211 mx->mx_cursor.mc_flags = C_SUB;
6212 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
6213 mx->mx_dbx.md_dcmp = NULL;
6214 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
6217 /** Final setup of a sorted-dups cursor.
6218 * Sets up the fields that depend on the data from the main cursor.
6219 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6220 * @param[in] node The data containing the #MDB_db record for the
6221 * sorted-dup database.
6224 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
6226 MDB_xcursor *mx = mc->mc_xcursor;
6228 if (node->mn_flags & F_SUBDATA) {
6229 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
6230 mx->mx_cursor.mc_pg[0] = 0;
6231 mx->mx_cursor.mc_snum = 0;
6232 mx->mx_cursor.mc_flags = C_SUB;
6234 MDB_page *fp = NODEDATA(node);
6235 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
6236 mx->mx_db.md_flags = 0;
6237 mx->mx_db.md_depth = 1;
6238 mx->mx_db.md_branch_pages = 0;
6239 mx->mx_db.md_leaf_pages = 1;
6240 mx->mx_db.md_overflow_pages = 0;
6241 mx->mx_db.md_entries = NUMKEYS(fp);
6242 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
6243 mx->mx_cursor.mc_snum = 1;
6244 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
6245 mx->mx_cursor.mc_top = 0;
6246 mx->mx_cursor.mc_pg[0] = fp;
6247 mx->mx_cursor.mc_ki[0] = 0;
6248 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6249 mx->mx_db.md_flags = MDB_DUPFIXED;
6250 mx->mx_db.md_pad = fp->mp_pad;
6251 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6252 mx->mx_db.md_flags |= MDB_INTEGERKEY;
6255 DPRINTF("Sub-db %u for db %u root page %zu", mx->mx_cursor.mc_dbi, mc->mc_dbi,
6257 mx->mx_dbflag = DB_VALID | (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY) ?
6259 mx->mx_dbx.md_name.mv_data = NODEKEY(node);
6260 mx->mx_dbx.md_name.mv_size = node->mn_ksize;
6261 #if UINT_MAX < SIZE_MAX
6262 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
6263 #ifdef MISALIGNED_OK
6264 mx->mx_dbx.md_cmp = mdb_cmp_long;
6266 mx->mx_dbx.md_cmp = mdb_cmp_cint;
6271 /** Initialize a cursor for a given transaction and database. */
6273 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
6276 mc->mc_backup = NULL;
6279 mc->mc_db = &txn->mt_dbs[dbi];
6280 mc->mc_dbx = &txn->mt_dbxs[dbi];
6281 mc->mc_dbflag = &txn->mt_dbflags[dbi];
6286 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
6288 mc->mc_xcursor = mx;
6289 mdb_xcursor_init0(mc);
6291 mc->mc_xcursor = NULL;
6293 if (*mc->mc_dbflag & DB_STALE) {
6294 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
6299 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
6302 size_t size = sizeof(MDB_cursor);
6304 if (txn == NULL || ret == NULL || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
6307 /* Allow read access to the freelist */
6308 if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
6311 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
6312 size += sizeof(MDB_xcursor);
6314 if ((mc = malloc(size)) != NULL) {
6315 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
6316 if (txn->mt_cursors) {
6317 mc->mc_next = txn->mt_cursors[dbi];
6318 txn->mt_cursors[dbi] = mc;
6319 mc->mc_flags |= C_UNTRACK;
6331 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
6333 if (txn == NULL || mc == NULL || mc->mc_dbi >= txn->mt_numdbs)
6336 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
6339 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
6343 /* Return the count of duplicate data items for the current key */
6345 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
6349 if (mc == NULL || countp == NULL)
6352 if (!(mc->mc_db->md_flags & MDB_DUPSORT))
6355 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6356 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6359 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
6362 *countp = mc->mc_xcursor->mx_db.md_entries;
6368 mdb_cursor_close(MDB_cursor *mc)
6370 if (mc && !mc->mc_backup) {
6371 /* remove from txn, if tracked */
6372 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
6373 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
6374 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
6376 *prev = mc->mc_next;
6383 mdb_cursor_txn(MDB_cursor *mc)
6385 if (!mc) return NULL;
6390 mdb_cursor_dbi(MDB_cursor *mc)
6396 /** Replace the key for a node with a new key.
6397 * @param[in] mc Cursor pointing to the node to operate on.
6398 * @param[in] key The new key to use.
6399 * @return 0 on success, non-zero on failure.
6402 mdb_update_key(MDB_cursor *mc, MDB_val *key)
6409 indx_t ptr, i, numkeys, indx;
6412 indx = mc->mc_ki[mc->mc_top];
6413 mp = mc->mc_pg[mc->mc_top];
6414 node = NODEPTR(mp, indx);
6415 ptr = mp->mp_ptrs[indx];
6419 char kbuf2[(MDB_MAXKEYSIZE*2+1)];
6420 k2.mv_data = NODEKEY(node);
6421 k2.mv_size = node->mn_ksize;
6422 DPRINTF("update key %u (ofs %u) [%s] to [%s] on page %zu",
6424 mdb_dkey(&k2, kbuf2),
6430 delta0 = delta = key->mv_size - node->mn_ksize;
6432 /* Must be 2-byte aligned. If new key is
6433 * shorter by 1, the shift will be skipped.
6435 delta += (delta & 1);
6437 if (delta > 0 && SIZELEFT(mp) < delta) {
6439 /* not enough space left, do a delete and split */
6440 DPRINTF("Not enough room, delta = %d, splitting...", delta);
6441 pgno = NODEPGNO(node);
6442 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
6443 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
6446 numkeys = NUMKEYS(mp);
6447 for (i = 0; i < numkeys; i++) {
6448 if (mp->mp_ptrs[i] <= ptr)
6449 mp->mp_ptrs[i] -= delta;
6452 base = (char *)mp + mp->mp_upper;
6453 len = ptr - mp->mp_upper + NODESIZE;
6454 memmove(base - delta, base, len);
6455 mp->mp_upper -= delta;
6457 node = NODEPTR(mp, indx);
6460 /* But even if no shift was needed, update ksize */
6462 node->mn_ksize = key->mv_size;
6465 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6471 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
6473 /** Move a node from csrc to cdst.
6476 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
6483 unsigned short flags;
6487 /* Mark src and dst as dirty. */
6488 if ((rc = mdb_page_touch(csrc)) ||
6489 (rc = mdb_page_touch(cdst)))
6492 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6493 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
6494 key.mv_size = csrc->mc_db->md_pad;
6495 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
6497 data.mv_data = NULL;
6501 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
6502 assert(!((long)srcnode&1));
6503 srcpg = NODEPGNO(srcnode);
6504 flags = srcnode->mn_flags;
6505 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6506 unsigned int snum = csrc->mc_snum;
6508 /* must find the lowest key below src */
6509 mdb_page_search_lowest(csrc);
6510 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6511 key.mv_size = csrc->mc_db->md_pad;
6512 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6514 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6515 key.mv_size = NODEKSZ(s2);
6516 key.mv_data = NODEKEY(s2);
6518 csrc->mc_snum = snum--;
6519 csrc->mc_top = snum;
6521 key.mv_size = NODEKSZ(srcnode);
6522 key.mv_data = NODEKEY(srcnode);
6524 data.mv_size = NODEDSZ(srcnode);
6525 data.mv_data = NODEDATA(srcnode);
6527 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
6528 unsigned int snum = cdst->mc_snum;
6531 /* must find the lowest key below dst */
6532 mdb_page_search_lowest(cdst);
6533 if (IS_LEAF2(cdst->mc_pg[cdst->mc_top])) {
6534 bkey.mv_size = cdst->mc_db->md_pad;
6535 bkey.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, bkey.mv_size);
6537 s2 = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
6538 bkey.mv_size = NODEKSZ(s2);
6539 bkey.mv_data = NODEKEY(s2);
6541 cdst->mc_snum = snum--;
6542 cdst->mc_top = snum;
6543 mdb_cursor_copy(cdst, &mn);
6545 rc = mdb_update_key(&mn, &bkey);
6550 DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
6551 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
6552 csrc->mc_ki[csrc->mc_top],
6554 csrc->mc_pg[csrc->mc_top]->mp_pgno,
6555 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
6557 /* Add the node to the destination page.
6559 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
6560 if (rc != MDB_SUCCESS)
6563 /* Delete the node from the source page.
6565 mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
6568 /* Adjust other cursors pointing to mp */
6569 MDB_cursor *m2, *m3;
6570 MDB_dbi dbi = csrc->mc_dbi;
6571 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
6573 if (csrc->mc_flags & C_SUB)
6576 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6577 if (csrc->mc_flags & C_SUB)
6578 m3 = &m2->mc_xcursor->mx_cursor;
6581 if (m3 == csrc) continue;
6582 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
6583 csrc->mc_ki[csrc->mc_top]) {
6584 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
6585 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
6590 /* Update the parent separators.
6592 if (csrc->mc_ki[csrc->mc_top] == 0) {
6593 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
6594 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6595 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6597 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6598 key.mv_size = NODEKSZ(srcnode);
6599 key.mv_data = NODEKEY(srcnode);
6601 DPRINTF("update separator for source page %zu to [%s]",
6602 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
6603 mdb_cursor_copy(csrc, &mn);
6606 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
6609 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6611 indx_t ix = csrc->mc_ki[csrc->mc_top];
6612 nullkey.mv_size = 0;
6613 csrc->mc_ki[csrc->mc_top] = 0;
6614 rc = mdb_update_key(csrc, &nullkey);
6615 csrc->mc_ki[csrc->mc_top] = ix;
6616 assert(rc == MDB_SUCCESS);
6620 if (cdst->mc_ki[cdst->mc_top] == 0) {
6621 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
6622 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6623 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
6625 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
6626 key.mv_size = NODEKSZ(srcnode);
6627 key.mv_data = NODEKEY(srcnode);
6629 DPRINTF("update separator for destination page %zu to [%s]",
6630 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
6631 mdb_cursor_copy(cdst, &mn);
6634 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
6637 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
6639 indx_t ix = cdst->mc_ki[cdst->mc_top];
6640 nullkey.mv_size = 0;
6641 cdst->mc_ki[cdst->mc_top] = 0;
6642 rc = mdb_update_key(cdst, &nullkey);
6643 cdst->mc_ki[cdst->mc_top] = ix;
6644 assert(rc == MDB_SUCCESS);
6651 /** Merge one page into another.
6652 * The nodes from the page pointed to by \b csrc will
6653 * be copied to the page pointed to by \b cdst and then
6654 * the \b csrc page will be freed.
6655 * @param[in] csrc Cursor pointing to the source page.
6656 * @param[in] cdst Cursor pointing to the destination page.
6659 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
6667 DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
6668 cdst->mc_pg[cdst->mc_top]->mp_pgno);
6670 assert(csrc->mc_snum > 1); /* can't merge root page */
6671 assert(cdst->mc_snum > 1);
6673 /* Mark dst as dirty. */
6674 if ((rc = mdb_page_touch(cdst)))
6677 /* Move all nodes from src to dst.
6679 j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
6680 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6681 key.mv_size = csrc->mc_db->md_pad;
6682 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
6683 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
6684 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
6685 if (rc != MDB_SUCCESS)
6687 key.mv_data = (char *)key.mv_data + key.mv_size;
6690 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
6691 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
6692 if (i == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6693 unsigned int snum = csrc->mc_snum;
6695 /* must find the lowest key below src */
6696 mdb_page_search_lowest(csrc);
6697 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6698 key.mv_size = csrc->mc_db->md_pad;
6699 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6701 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6702 key.mv_size = NODEKSZ(s2);
6703 key.mv_data = NODEKEY(s2);
6705 csrc->mc_snum = snum--;
6706 csrc->mc_top = snum;
6708 key.mv_size = srcnode->mn_ksize;
6709 key.mv_data = NODEKEY(srcnode);
6712 data.mv_size = NODEDSZ(srcnode);
6713 data.mv_data = NODEDATA(srcnode);
6714 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
6715 if (rc != MDB_SUCCESS)
6720 DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
6721 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);
6723 /* Unlink the src page from parent and add to free list.
6725 mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
6726 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
6729 rc = mdb_update_key(csrc, &key);
6735 rc = mdb_midl_append(&csrc->mc_txn->mt_free_pgs,
6736 csrc->mc_pg[csrc->mc_top]->mp_pgno);
6739 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
6740 csrc->mc_db->md_leaf_pages--;
6742 csrc->mc_db->md_branch_pages--;
6744 /* Adjust other cursors pointing to mp */
6745 MDB_cursor *m2, *m3;
6746 MDB_dbi dbi = csrc->mc_dbi;
6747 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
6749 if (csrc->mc_flags & C_SUB)
6752 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6753 if (csrc->mc_flags & C_SUB)
6754 m3 = &m2->mc_xcursor->mx_cursor;
6757 if (m3 == csrc) continue;
6758 if (m3->mc_snum < csrc->mc_snum) continue;
6759 if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
6760 m3->mc_pg[csrc->mc_top] = mp;
6761 m3->mc_ki[csrc->mc_top] += nkeys;
6765 mdb_cursor_pop(csrc);
6767 return mdb_rebalance(csrc);
6770 /** Copy the contents of a cursor.
6771 * @param[in] csrc The cursor to copy from.
6772 * @param[out] cdst The cursor to copy to.
6775 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
6779 cdst->mc_txn = csrc->mc_txn;
6780 cdst->mc_dbi = csrc->mc_dbi;
6781 cdst->mc_db = csrc->mc_db;
6782 cdst->mc_dbx = csrc->mc_dbx;
6783 cdst->mc_snum = csrc->mc_snum;
6784 cdst->mc_top = csrc->mc_top;
6785 cdst->mc_flags = csrc->mc_flags;
6787 for (i=0; i<csrc->mc_snum; i++) {
6788 cdst->mc_pg[i] = csrc->mc_pg[i];
6789 cdst->mc_ki[i] = csrc->mc_ki[i];
6793 /** Rebalance the tree after a delete operation.
6794 * @param[in] mc Cursor pointing to the page where rebalancing
6796 * @return 0 on success, non-zero on failure.
6799 mdb_rebalance(MDB_cursor *mc)
6803 unsigned int ptop, minkeys;
6806 minkeys = 1 + (IS_BRANCH(mc->mc_pg[mc->mc_top]));
6810 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
6811 DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
6812 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
6813 pgno, NUMKEYS(mc->mc_pg[mc->mc_top]), (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10);
6817 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD &&
6818 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
6821 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
6822 DPRINTF("no need to rebalance page %zu, above fill threshold",
6828 if (mc->mc_snum < 2) {
6829 MDB_page *mp = mc->mc_pg[0];
6831 DPUTS("Can't rebalance a subpage, ignoring");
6834 if (NUMKEYS(mp) == 0) {
6835 DPUTS("tree is completely empty");
6836 mc->mc_db->md_root = P_INVALID;
6837 mc->mc_db->md_depth = 0;
6838 mc->mc_db->md_leaf_pages = 0;
6839 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
6842 /* Adjust cursors pointing to mp */
6846 MDB_cursor *m2, *m3;
6847 MDB_dbi dbi = mc->mc_dbi;
6849 if (mc->mc_flags & C_SUB)
6852 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6853 if (mc->mc_flags & C_SUB)
6854 m3 = &m2->mc_xcursor->mx_cursor;
6857 if (m3->mc_snum < mc->mc_snum) continue;
6858 if (m3->mc_pg[0] == mp) {
6864 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
6865 DPUTS("collapsing root page!");
6866 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
6869 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
6870 rc = mdb_page_get(mc->mc_txn,mc->mc_db->md_root,&mc->mc_pg[0],NULL);
6873 mc->mc_db->md_depth--;
6874 mc->mc_db->md_branch_pages--;
6875 mc->mc_ki[0] = mc->mc_ki[1];
6877 /* Adjust other cursors pointing to mp */
6878 MDB_cursor *m2, *m3;
6879 MDB_dbi dbi = mc->mc_dbi;
6881 if (mc->mc_flags & C_SUB)
6884 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6885 if (mc->mc_flags & C_SUB)
6886 m3 = &m2->mc_xcursor->mx_cursor;
6889 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
6890 if (m3->mc_pg[0] == mp) {
6891 m3->mc_pg[0] = mc->mc_pg[0];
6894 m3->mc_ki[0] = m3->mc_ki[1];
6899 DPUTS("root page doesn't need rebalancing");
6903 /* The parent (branch page) must have at least 2 pointers,
6904 * otherwise the tree is invalid.
6906 ptop = mc->mc_top-1;
6907 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
6909 /* Leaf page fill factor is below the threshold.
6910 * Try to move keys from left or right neighbor, or
6911 * merge with a neighbor page.
6916 mdb_cursor_copy(mc, &mn);
6917 mn.mc_xcursor = NULL;
6919 if (mc->mc_ki[ptop] == 0) {
6920 /* We're the leftmost leaf in our parent.
6922 DPUTS("reading right neighbor");
6924 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
6925 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
6928 mn.mc_ki[mn.mc_top] = 0;
6929 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
6931 /* There is at least one neighbor to the left.
6933 DPUTS("reading left neighbor");
6935 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
6936 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
6939 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
6940 mc->mc_ki[mc->mc_top] = 0;
6943 DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
6944 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);
6946 /* If the neighbor page is above threshold and has enough keys,
6947 * move one key from it. Otherwise we should try to merge them.
6948 * (A branch page must never have less than 2 keys.)
6950 minkeys = 1 + (IS_BRANCH(mn.mc_pg[mn.mc_top]));
6951 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys)
6952 return mdb_node_move(&mn, mc);
6954 if (mc->mc_ki[ptop] == 0)
6955 rc = mdb_page_merge(&mn, mc);
6957 rc = mdb_page_merge(mc, &mn);
6958 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
6963 /** Complete a delete operation started by #mdb_cursor_del(). */
6965 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
6971 mp = mc->mc_pg[mc->mc_top];
6972 ki = mc->mc_ki[mc->mc_top];
6974 /* add overflow pages to free list */
6975 if (!IS_LEAF2(mp) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6979 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
6980 if ((rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL)) ||
6981 (rc = mdb_ovpage_free(mc, omp)))
6984 mdb_node_del(mp, ki, mc->mc_db->md_pad);
6985 mc->mc_db->md_entries--;
6986 rc = mdb_rebalance(mc);
6987 if (rc != MDB_SUCCESS)
6988 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6989 /* if mc points past last node in page, invalidate */
6990 else if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6991 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
6994 /* Adjust other cursors pointing to mp */
6997 MDB_dbi dbi = mc->mc_dbi;
6999 mp = mc->mc_pg[mc->mc_top];
7000 nkeys = NUMKEYS(mp);
7001 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7004 if (!(m2->mc_flags & C_INITIALIZED))
7006 if (m2->mc_pg[mc->mc_top] == mp) {
7007 if (m2->mc_ki[mc->mc_top] > ki)
7008 m2->mc_ki[mc->mc_top]--;
7009 if (m2->mc_ki[mc->mc_top] >= nkeys)
7010 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
7019 mdb_del(MDB_txn *txn, MDB_dbi dbi,
7020 MDB_val *key, MDB_val *data)
7025 MDB_val rdata, *xdata;
7029 assert(key != NULL);
7031 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
7033 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7036 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
7040 if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
7044 mdb_cursor_init(&mc, txn, dbi, &mx);
7055 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
7057 /* let mdb_page_split know about this cursor if needed:
7058 * delete will trigger a rebalance; if it needs to move
7059 * a node from one page to another, it will have to
7060 * update the parent's separator key(s). If the new sepkey
7061 * is larger than the current one, the parent page may
7062 * run out of space, triggering a split. We need this
7063 * cursor to be consistent until the end of the rebalance.
7065 mc.mc_flags |= C_UNTRACK;
7066 mc.mc_next = txn->mt_cursors[dbi];
7067 txn->mt_cursors[dbi] = &mc;
7068 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
7069 txn->mt_cursors[dbi] = mc.mc_next;
7074 /** Split a page and insert a new node.
7075 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
7076 * The cursor will be updated to point to the actual page and index where
7077 * the node got inserted after the split.
7078 * @param[in] newkey The key for the newly inserted node.
7079 * @param[in] newdata The data for the newly inserted node.
7080 * @param[in] newpgno The page number, if the new node is a branch node.
7081 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
7082 * @return 0 on success, non-zero on failure.
7085 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
7086 unsigned int nflags)
7089 int rc = MDB_SUCCESS, ins_new = 0, new_root = 0, newpos = 1, did_split = 0;
7092 unsigned int i, j, split_indx, nkeys, pmax;
7094 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
7096 MDB_page *mp, *rp, *pp;
7101 mp = mc->mc_pg[mc->mc_top];
7102 newindx = mc->mc_ki[mc->mc_top];
7104 DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
7105 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
7106 DKEY(newkey), mc->mc_ki[mc->mc_top]);
7108 /* Create a right sibling. */
7109 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
7111 DPRINTF("new right sibling: page %zu", rp->mp_pgno);
7113 if (mc->mc_snum < 2) {
7114 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
7116 /* shift current top to make room for new parent */
7117 mc->mc_pg[1] = mc->mc_pg[0];
7118 mc->mc_ki[1] = mc->mc_ki[0];
7121 mc->mc_db->md_root = pp->mp_pgno;
7122 DPRINTF("root split! new root = %zu", pp->mp_pgno);
7123 mc->mc_db->md_depth++;
7126 /* Add left (implicit) pointer. */
7127 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
7128 /* undo the pre-push */
7129 mc->mc_pg[0] = mc->mc_pg[1];
7130 mc->mc_ki[0] = mc->mc_ki[1];
7131 mc->mc_db->md_root = mp->mp_pgno;
7132 mc->mc_db->md_depth--;
7139 ptop = mc->mc_top-1;
7140 DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
7143 mc->mc_flags |= C_SPLITTING;
7144 mdb_cursor_copy(mc, &mn);
7145 mn.mc_pg[mn.mc_top] = rp;
7146 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
7148 if (nflags & MDB_APPEND) {
7149 mn.mc_ki[mn.mc_top] = 0;
7151 split_indx = newindx;
7156 nkeys = NUMKEYS(mp);
7157 split_indx = nkeys / 2;
7158 if (newindx < split_indx)
7164 unsigned int lsize, rsize, ksize;
7165 /* Move half of the keys to the right sibling */
7167 x = mc->mc_ki[mc->mc_top] - split_indx;
7168 ksize = mc->mc_db->md_pad;
7169 split = LEAF2KEY(mp, split_indx, ksize);
7170 rsize = (nkeys - split_indx) * ksize;
7171 lsize = (nkeys - split_indx) * sizeof(indx_t);
7172 mp->mp_lower -= lsize;
7173 rp->mp_lower += lsize;
7174 mp->mp_upper += rsize - lsize;
7175 rp->mp_upper -= rsize - lsize;
7176 sepkey.mv_size = ksize;
7177 if (newindx == split_indx) {
7178 sepkey.mv_data = newkey->mv_data;
7180 sepkey.mv_data = split;
7183 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
7184 memcpy(rp->mp_ptrs, split, rsize);
7185 sepkey.mv_data = rp->mp_ptrs;
7186 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
7187 memcpy(ins, newkey->mv_data, ksize);
7188 mp->mp_lower += sizeof(indx_t);
7189 mp->mp_upper -= ksize - sizeof(indx_t);
7192 memcpy(rp->mp_ptrs, split, x * ksize);
7193 ins = LEAF2KEY(rp, x, ksize);
7194 memcpy(ins, newkey->mv_data, ksize);
7195 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
7196 rp->mp_lower += sizeof(indx_t);
7197 rp->mp_upper -= ksize - sizeof(indx_t);
7198 mc->mc_ki[mc->mc_top] = x;
7199 mc->mc_pg[mc->mc_top] = rp;
7204 /* For leaf pages, check the split point based on what
7205 * fits where, since otherwise mdb_node_add can fail.
7207 * This check is only needed when the data items are
7208 * relatively large, such that being off by one will
7209 * make the difference between success or failure.
7211 * It's also relevant if a page happens to be laid out
7212 * such that one half of its nodes are all "small" and
7213 * the other half of its nodes are "large." If the new
7214 * item is also "large" and falls on the half with
7215 * "large" nodes, it also may not fit.
7218 unsigned int psize, nsize;
7219 /* Maximum free space in an empty page */
7220 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
7221 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
7222 if ((nkeys < 20) || (nsize > pmax/16)) {
7223 if (newindx <= split_indx) {
7226 for (i=0; i<split_indx; i++) {
7227 node = NODEPTR(mp, i);
7228 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
7229 if (F_ISSET(node->mn_flags, F_BIGDATA))
7230 psize += sizeof(pgno_t);
7232 psize += NODEDSZ(node);
7236 split_indx = newindx;
7247 for (i=nkeys-1; i>=split_indx; i--) {
7248 node = NODEPTR(mp, i);
7249 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
7250 if (F_ISSET(node->mn_flags, F_BIGDATA))
7251 psize += sizeof(pgno_t);
7253 psize += NODEDSZ(node);
7257 split_indx = newindx;
7268 /* First find the separating key between the split pages.
7269 * The case where newindx == split_indx is ambiguous; the
7270 * new item could go to the new page or stay on the original
7271 * page. If newpos == 1 it goes to the new page.
7273 if (newindx == split_indx && newpos) {
7274 sepkey.mv_size = newkey->mv_size;
7275 sepkey.mv_data = newkey->mv_data;
7277 node = NODEPTR(mp, split_indx);
7278 sepkey.mv_size = node->mn_ksize;
7279 sepkey.mv_data = NODEKEY(node);
7283 DPRINTF("separator is [%s]", DKEY(&sepkey));
7285 /* Copy separator key to the parent.
7287 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
7291 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
7294 if (mn.mc_snum == mc->mc_snum) {
7295 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
7296 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
7297 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
7298 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
7303 /* Right page might now have changed parent.
7304 * Check if left page also changed parent.
7306 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7307 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7308 for (i=0; i<ptop; i++) {
7309 mc->mc_pg[i] = mn.mc_pg[i];
7310 mc->mc_ki[i] = mn.mc_ki[i];
7312 mc->mc_pg[ptop] = mn.mc_pg[ptop];
7313 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
7317 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
7320 mc->mc_flags ^= C_SPLITTING;
7321 if (rc != MDB_SUCCESS) {
7324 if (nflags & MDB_APPEND) {
7325 mc->mc_pg[mc->mc_top] = rp;
7326 mc->mc_ki[mc->mc_top] = 0;
7327 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
7330 for (i=0; i<mc->mc_top; i++)
7331 mc->mc_ki[i] = mn.mc_ki[i];
7338 /* Move half of the keys to the right sibling. */
7340 /* grab a page to hold a temporary copy */
7341 copy = mdb_page_malloc(mc->mc_txn, 1);
7345 copy->mp_pgno = mp->mp_pgno;
7346 copy->mp_flags = mp->mp_flags;
7347 copy->mp_lower = PAGEHDRSZ;
7348 copy->mp_upper = mc->mc_txn->mt_env->me_psize;
7349 mc->mc_pg[mc->mc_top] = copy;
7350 for (i = j = 0; i <= nkeys; j++) {
7351 if (i == split_indx) {
7352 /* Insert in right sibling. */
7353 /* Reset insert index for right sibling. */
7354 if (i != newindx || (newpos ^ ins_new)) {
7356 mc->mc_pg[mc->mc_top] = rp;
7360 if (i == newindx && !ins_new) {
7361 /* Insert the original entry that caused the split. */
7362 rkey.mv_data = newkey->mv_data;
7363 rkey.mv_size = newkey->mv_size;
7372 /* Update index for the new key. */
7373 mc->mc_ki[mc->mc_top] = j;
7374 } else if (i == nkeys) {
7377 node = NODEPTR(mp, i);
7378 rkey.mv_data = NODEKEY(node);
7379 rkey.mv_size = node->mn_ksize;
7381 xdata.mv_data = NODEDATA(node);
7382 xdata.mv_size = NODEDSZ(node);
7385 pgno = NODEPGNO(node);
7386 flags = node->mn_flags;
7391 if (!IS_LEAF(mp) && j == 0) {
7392 /* First branch index doesn't need key data. */
7396 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
7400 nkeys = NUMKEYS(copy);
7401 for (i=0; i<nkeys; i++)
7402 mp->mp_ptrs[i] = copy->mp_ptrs[i];
7403 mp->mp_lower = copy->mp_lower;
7404 mp->mp_upper = copy->mp_upper;
7405 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
7406 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
7408 /* reset back to original page */
7409 if (newindx < split_indx || (!newpos && newindx == split_indx)) {
7410 mc->mc_pg[mc->mc_top] = mp;
7411 if (nflags & MDB_RESERVE) {
7412 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7413 if (!(node->mn_flags & F_BIGDATA))
7414 newdata->mv_data = NODEDATA(node);
7418 /* Make sure mc_ki is still valid.
7420 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7421 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7422 for (i=0; i<ptop; i++) {
7423 mc->mc_pg[i] = mn.mc_pg[i];
7424 mc->mc_ki[i] = mn.mc_ki[i];
7426 mc->mc_pg[ptop] = mn.mc_pg[ptop];
7427 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
7431 /* return tmp page to freelist */
7432 mdb_page_free(mc->mc_txn->mt_env, copy);
7435 /* Adjust other cursors pointing to mp */
7436 MDB_cursor *m2, *m3;
7437 MDB_dbi dbi = mc->mc_dbi;
7438 int fixup = NUMKEYS(mp);
7440 if (mc->mc_flags & C_SUB)
7443 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7444 if (mc->mc_flags & C_SUB)
7445 m3 = &m2->mc_xcursor->mx_cursor;
7450 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
7452 if (m3->mc_flags & C_SPLITTING)
7457 for (k=m3->mc_top; k>=0; k--) {
7458 m3->mc_ki[k+1] = m3->mc_ki[k];
7459 m3->mc_pg[k+1] = m3->mc_pg[k];
7461 if (m3->mc_ki[0] >= split_indx) {
7466 m3->mc_pg[0] = mc->mc_pg[0];
7470 if (m3->mc_pg[mc->mc_top] == mp) {
7471 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
7472 m3->mc_ki[mc->mc_top]++;
7473 if (m3->mc_ki[mc->mc_top] >= fixup) {
7474 m3->mc_pg[mc->mc_top] = rp;
7475 m3->mc_ki[mc->mc_top] -= fixup;
7476 m3->mc_ki[ptop] = mn.mc_ki[ptop];
7478 } else if (!did_split && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
7479 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
7488 mdb_put(MDB_txn *txn, MDB_dbi dbi,
7489 MDB_val *key, MDB_val *data, unsigned int flags)
7494 assert(key != NULL);
7495 assert(data != NULL);
7497 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7500 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
7504 if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
7508 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP)) != flags)
7511 mdb_cursor_init(&mc, txn, dbi, &mx);
7512 return mdb_cursor_put(&mc, key, data, flags);
7516 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
7518 if ((flag & CHANGEABLE) != flag)
7521 env->me_flags |= flag;
7523 env->me_flags &= ~flag;
7528 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
7533 *arg = env->me_flags;
7538 mdb_env_get_path(MDB_env *env, const char **arg)
7543 *arg = env->me_path;
7547 /** Common code for #mdb_stat() and #mdb_env_stat().
7548 * @param[in] env the environment to operate in.
7549 * @param[in] db the #MDB_db record containing the stats to return.
7550 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
7551 * @return 0, this function always succeeds.
7554 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
7556 arg->ms_psize = env->me_psize;
7557 arg->ms_depth = db->md_depth;
7558 arg->ms_branch_pages = db->md_branch_pages;
7559 arg->ms_leaf_pages = db->md_leaf_pages;
7560 arg->ms_overflow_pages = db->md_overflow_pages;
7561 arg->ms_entries = db->md_entries;
7566 mdb_env_stat(MDB_env *env, MDB_stat *arg)
7570 if (env == NULL || arg == NULL)
7573 toggle = mdb_env_pick_meta(env);
7575 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
7579 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
7583 if (env == NULL || arg == NULL)
7586 toggle = mdb_env_pick_meta(env);
7587 arg->me_mapaddr = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : 0;
7588 arg->me_mapsize = env->me_mapsize;
7589 arg->me_maxreaders = env->me_maxreaders;
7590 arg->me_numreaders = env->me_numreaders;
7591 arg->me_last_pgno = env->me_metas[toggle]->mm_last_pg;
7592 arg->me_last_txnid = env->me_metas[toggle]->mm_txnid;
7596 /** Set the default comparison functions for a database.
7597 * Called immediately after a database is opened to set the defaults.
7598 * The user can then override them with #mdb_set_compare() or
7599 * #mdb_set_dupsort().
7600 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
7601 * @param[in] dbi A database handle returned by #mdb_dbi_open()
7604 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
7606 uint16_t f = txn->mt_dbs[dbi].md_flags;
7608 txn->mt_dbxs[dbi].md_cmp =
7609 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
7610 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
7612 txn->mt_dbxs[dbi].md_dcmp =
7613 !(f & MDB_DUPSORT) ? 0 :
7614 ((f & MDB_INTEGERDUP)
7615 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
7616 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
7619 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
7624 int rc, dbflag, exact;
7625 unsigned int unused = 0;
7628 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
7629 mdb_default_cmp(txn, FREE_DBI);
7632 if ((flags & VALID_FLAGS) != flags)
7638 if (flags & PERSISTENT_FLAGS) {
7639 uint16_t f2 = flags & PERSISTENT_FLAGS;
7640 /* make sure flag changes get committed */
7641 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
7642 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
7643 txn->mt_flags |= MDB_TXN_DIRTY;
7646 mdb_default_cmp(txn, MAIN_DBI);
7650 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
7651 mdb_default_cmp(txn, MAIN_DBI);
7654 /* Is the DB already open? */
7656 for (i=2; i<txn->mt_numdbs; i++) {
7657 if (!txn->mt_dbxs[i].md_name.mv_size) {
7658 /* Remember this free slot */
7659 if (!unused) unused = i;
7662 if (len == txn->mt_dbxs[i].md_name.mv_size &&
7663 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
7669 /* If no free slot and max hit, fail */
7670 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
7671 return MDB_DBS_FULL;
7673 /* Cannot mix named databases with some mainDB flags */
7674 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
7675 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
7677 /* Find the DB info */
7678 dbflag = DB_NEW|DB_VALID;
7681 key.mv_data = (void *)name;
7682 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
7683 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
7684 if (rc == MDB_SUCCESS) {
7685 /* make sure this is actually a DB */
7686 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
7687 if (!(node->mn_flags & F_SUBDATA))
7689 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
7690 /* Create if requested */
7692 data.mv_size = sizeof(MDB_db);
7693 data.mv_data = &dummy;
7694 memset(&dummy, 0, sizeof(dummy));
7695 dummy.md_root = P_INVALID;
7696 dummy.md_flags = flags & PERSISTENT_FLAGS;
7697 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
7701 /* OK, got info, add to table */
7702 if (rc == MDB_SUCCESS) {
7703 unsigned int slot = unused ? unused : txn->mt_numdbs;
7704 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
7705 txn->mt_dbxs[slot].md_name.mv_size = len;
7706 txn->mt_dbxs[slot].md_rel = NULL;
7707 txn->mt_dbflags[slot] = dbflag;
7708 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
7710 txn->mt_env->me_dbflags[slot] = txn->mt_dbs[slot].md_flags;
7711 mdb_default_cmp(txn, slot);
7720 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
7722 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
7725 if (txn->mt_dbflags[dbi] & DB_STALE) {
7728 /* Stale, must read the DB's root. cursor_init does it for us. */
7729 mdb_cursor_init(&mc, txn, dbi, &mx);
7731 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
7734 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
7737 if (dbi <= MAIN_DBI || dbi >= env->me_maxdbs)
7739 ptr = env->me_dbxs[dbi].md_name.mv_data;
7740 env->me_dbxs[dbi].md_name.mv_data = NULL;
7741 env->me_dbxs[dbi].md_name.mv_size = 0;
7742 env->me_dbflags[dbi] = 0;
7746 int mdb_dbi_flags(MDB_env *env, MDB_dbi dbi, unsigned int *flags)
7748 /* We could return the flags for the FREE_DBI too but what's the point? */
7749 if (dbi <= MAIN_DBI || dbi >= env->me_numdbs)
7751 *flags = env->me_dbflags[dbi];
7755 /** Add all the DB's pages to the free list.
7756 * @param[in] mc Cursor on the DB to free.
7757 * @param[in] subs non-Zero to check for sub-DBs in this DB.
7758 * @return 0 on success, non-zero on failure.
7761 mdb_drop0(MDB_cursor *mc, int subs)
7765 rc = mdb_page_search(mc, NULL, 0);
7766 if (rc == MDB_SUCCESS) {
7767 MDB_txn *txn = mc->mc_txn;
7772 /* LEAF2 pages have no nodes, cannot have sub-DBs */
7773 if (IS_LEAF2(mc->mc_pg[mc->mc_top]))
7776 mdb_cursor_copy(mc, &mx);
7777 while (mc->mc_snum > 0) {
7778 MDB_page *mp = mc->mc_pg[mc->mc_top];
7779 unsigned n = NUMKEYS(mp);
7781 for (i=0; i<n; i++) {
7782 ni = NODEPTR(mp, i);
7783 if (ni->mn_flags & F_BIGDATA) {
7786 memcpy(&pg, NODEDATA(ni), sizeof(pg));
7787 rc = mdb_page_get(txn, pg, &omp, NULL);
7790 assert(IS_OVERFLOW(omp));
7791 rc = mdb_midl_append_range(&txn->mt_free_pgs,
7795 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
7796 mdb_xcursor_init1(mc, ni);
7797 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
7803 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
7805 for (i=0; i<n; i++) {
7807 ni = NODEPTR(mp, i);
7810 mdb_midl_xappend(txn->mt_free_pgs, pg);
7815 mc->mc_ki[mc->mc_top] = i;
7816 rc = mdb_cursor_sibling(mc, 1);
7818 /* no more siblings, go back to beginning
7819 * of previous level.
7823 for (i=1; i<mc->mc_snum; i++) {
7825 mc->mc_pg[i] = mx.mc_pg[i];
7830 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
7831 } else if (rc == MDB_NOTFOUND) {
7837 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
7839 MDB_cursor *mc, *m2;
7842 if (!txn || !dbi || dbi >= txn->mt_numdbs || (unsigned)del > 1 || !(txn->mt_dbflags[dbi] & DB_VALID))
7845 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
7848 rc = mdb_cursor_open(txn, dbi, &mc);
7852 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
7853 /* Invalidate the dropped DB's cursors */
7854 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
7855 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
7859 /* Can't delete the main DB */
7860 if (del && dbi > MAIN_DBI) {
7861 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
7863 txn->mt_dbflags[dbi] = DB_STALE;
7864 mdb_dbi_close(txn->mt_env, dbi);
7867 /* reset the DB record, mark it dirty */
7868 txn->mt_dbflags[dbi] |= DB_DIRTY;
7869 txn->mt_dbs[dbi].md_depth = 0;
7870 txn->mt_dbs[dbi].md_branch_pages = 0;
7871 txn->mt_dbs[dbi].md_leaf_pages = 0;
7872 txn->mt_dbs[dbi].md_overflow_pages = 0;
7873 txn->mt_dbs[dbi].md_entries = 0;
7874 txn->mt_dbs[dbi].md_root = P_INVALID;
7876 txn->mt_flags |= MDB_TXN_DIRTY;
7879 mdb_cursor_close(mc);
7883 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
7885 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7888 txn->mt_dbxs[dbi].md_cmp = cmp;
7892 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
7894 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7897 txn->mt_dbxs[dbi].md_dcmp = cmp;
7901 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
7903 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7906 txn->mt_dbxs[dbi].md_rel = rel;
7910 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
7912 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7915 txn->mt_dbxs[dbi].md_relctx = ctx;