2 * @brief memory-mapped database library
4 * A Btree-based database management library modeled loosely on the
5 * BerkeleyDB API, but much simplified.
8 * Copyright 2011-2013 Howard Chu, Symas Corp.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted only as authorized by the OpenLDAP
15 * A copy of this license is available in the file LICENSE in the
16 * top-level directory of the distribution or, alternatively, at
17 * <http://www.OpenLDAP.org/license.html>.
19 * This code is derived from btree.c written by Martin Hedenfalk.
21 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
23 * Permission to use, copy, modify, and distribute this software for any
24 * purpose with or without fee is hereby granted, provided that the above
25 * copyright notice and this permission notice appear in all copies.
27 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
28 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
29 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
30 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
31 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
32 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
33 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
38 #include <sys/types.h>
40 #include <sys/param.h>
46 #ifdef HAVE_SYS_FILE_H
63 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
64 #include <netinet/in.h>
65 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
68 #if defined(__APPLE__) || defined (BSD)
69 # define MDB_USE_POSIX_SEM 1
70 # define MDB_FDATASYNC fsync
71 #elif defined(ANDROID)
72 # define MDB_FDATASYNC fsync
77 #ifdef MDB_USE_POSIX_SEM
78 #include <semaphore.h>
83 #include <valgrind/memcheck.h>
84 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
85 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
86 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
87 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
88 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
90 #define VGMEMP_CREATE(h,r,z)
91 #define VGMEMP_ALLOC(h,a,s)
92 #define VGMEMP_FREE(h,a)
93 #define VGMEMP_DESTROY(h)
94 #define VGMEMP_DEFINED(a,s)
98 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
99 /* Solaris just defines one or the other */
100 # define LITTLE_ENDIAN 1234
101 # define BIG_ENDIAN 4321
102 # ifdef _LITTLE_ENDIAN
103 # define BYTE_ORDER LITTLE_ENDIAN
105 # define BYTE_ORDER BIG_ENDIAN
108 # define BYTE_ORDER __BYTE_ORDER
112 #ifndef LITTLE_ENDIAN
113 #define LITTLE_ENDIAN __LITTLE_ENDIAN
116 #define BIG_ENDIAN __BIG_ENDIAN
119 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
120 #define MISALIGNED_OK 1
126 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
127 # error "Unknown or unsupported endianness (BYTE_ORDER)"
128 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
129 # error "Two's complement, reasonably sized integer types, please"
132 /** @defgroup internal MDB Internals
135 /** @defgroup compat Windows Compatibility Macros
136 * A bunch of macros to minimize the amount of platform-specific ifdefs
137 * needed throughout the rest of the code. When the features this library
138 * needs are similar enough to POSIX to be hidden in a one-or-two line
139 * replacement, this macro approach is used.
143 #define pthread_t DWORD
144 #define pthread_mutex_t HANDLE
145 #define pthread_key_t DWORD
146 #define pthread_self() GetCurrentThreadId()
147 #define pthread_key_create(x,y) \
148 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
149 #define pthread_key_delete(x) TlsFree(x)
150 #define pthread_getspecific(x) TlsGetValue(x)
151 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
152 #define pthread_mutex_unlock(x) ReleaseMutex(x)
153 #define pthread_mutex_lock(x) WaitForSingleObject(x, INFINITE)
154 #define LOCK_MUTEX_R(env) pthread_mutex_lock((env)->me_rmutex)
155 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock((env)->me_rmutex)
156 #define LOCK_MUTEX_W(env) pthread_mutex_lock((env)->me_wmutex)
157 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock((env)->me_wmutex)
158 #define getpid() GetCurrentProcessId()
159 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
160 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
161 #define ErrCode() GetLastError()
162 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
163 #define close(fd) (CloseHandle(fd) ? 0 : -1)
164 #define munmap(ptr,len) UnmapViewOfFile(ptr)
167 #ifdef MDB_USE_POSIX_SEM
169 #define LOCK_MUTEX_R(env) mdb_sem_wait((env)->me_rmutex)
170 #define UNLOCK_MUTEX_R(env) sem_post((env)->me_rmutex)
171 #define LOCK_MUTEX_W(env) mdb_sem_wait((env)->me_wmutex)
172 #define UNLOCK_MUTEX_W(env) sem_post((env)->me_wmutex)
175 mdb_sem_wait(sem_t *sem)
178 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
183 /** Lock the reader mutex.
185 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
186 /** Unlock the reader mutex.
188 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
190 /** Lock the writer mutex.
191 * Only a single write transaction is allowed at a time. Other writers
192 * will block waiting for this mutex.
194 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
195 /** Unlock the writer mutex.
197 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
198 #endif /* MDB_USE_POSIX_SEM */
200 /** Get the error code for the last failed system function.
202 #define ErrCode() errno
204 /** An abstraction for a file handle.
205 * On POSIX systems file handles are small integers. On Windows
206 * they're opaque pointers.
210 /** A value for an invalid file handle.
211 * Mainly used to initialize file variables and signify that they are
214 #define INVALID_HANDLE_VALUE (-1)
216 /** Get the size of a memory page for the system.
217 * This is the basic size that the platform's memory manager uses, and is
218 * fundamental to the use of memory-mapped files.
220 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
223 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
226 #define MNAME_LEN (sizeof(pthread_mutex_t))
232 /** A flag for opening a file and requesting synchronous data writes.
233 * This is only used when writing a meta page. It's not strictly needed;
234 * we could just do a normal write and then immediately perform a flush.
235 * But if this flag is available it saves us an extra system call.
237 * @note If O_DSYNC is undefined but exists in /usr/include,
238 * preferably set some compiler flag to get the definition.
239 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
242 # define MDB_DSYNC O_DSYNC
246 /** Function for flushing the data of a file. Define this to fsync
247 * if fdatasync() is not supported.
249 #ifndef MDB_FDATASYNC
250 # define MDB_FDATASYNC fdatasync
254 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
265 /** A page number in the database.
266 * Note that 64 bit page numbers are overkill, since pages themselves
267 * already represent 12-13 bits of addressable memory, and the OS will
268 * always limit applications to a maximum of 63 bits of address space.
270 * @note In the #MDB_node structure, we only store 48 bits of this value,
271 * which thus limits us to only 60 bits of addressable data.
273 typedef MDB_ID pgno_t;
275 /** A transaction ID.
276 * See struct MDB_txn.mt_txnid for details.
278 typedef MDB_ID txnid_t;
280 /** @defgroup debug Debug Macros
284 /** Enable debug output.
285 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
286 * read from and written to the database (used for free space management).
291 #if !(__STDC_VERSION__ >= 199901L || defined(__GNUC__))
294 # define DPRINTF (void) /* Vararg macros may be unsupported */
296 static int mdb_debug;
297 static txnid_t mdb_debug_start;
299 /** Print a debug message with printf formatting. */
300 # define DPRINTF(fmt, ...) /**< Requires 2 or more args */ \
301 ((void) ((mdb_debug) && \
302 fprintf(stderr, "%s:%d " fmt "\n", __func__, __LINE__, __VA_ARGS__)))
304 # define DPRINTF(fmt, ...) ((void) 0)
305 # define MDB_DEBUG_SKIP
307 /** Print a debug string.
308 * The string is printed literally, with no format processing.
310 #define DPUTS(arg) DPRINTF("%s", arg)
313 /** A default memory page size.
314 * The actual size is platform-dependent, but we use this for
315 * boot-strapping. We probably should not be using this any more.
316 * The #GET_PAGESIZE() macro is used to get the actual size.
318 * Note that we don't currently support Huge pages. On Linux,
319 * regular data files cannot use Huge pages, and in general
320 * Huge pages aren't actually pageable. We rely on the OS
321 * demand-pager to read our data and page it out when memory
322 * pressure from other processes is high. So until OSs have
323 * actual paging support for Huge pages, they're not viable.
325 #define MDB_PAGESIZE 4096
327 /** The minimum number of keys required in a database page.
328 * Setting this to a larger value will place a smaller bound on the
329 * maximum size of a data item. Data items larger than this size will
330 * be pushed into overflow pages instead of being stored directly in
331 * the B-tree node. This value used to default to 4. With a page size
332 * of 4096 bytes that meant that any item larger than 1024 bytes would
333 * go into an overflow page. That also meant that on average 2-3KB of
334 * each overflow page was wasted space. The value cannot be lower than
335 * 2 because then there would no longer be a tree structure. With this
336 * value, items larger than 2KB will go into overflow pages, and on
337 * average only 1KB will be wasted.
339 #define MDB_MINKEYS 2
341 /** A stamp that identifies a file as an MDB file.
342 * There's nothing special about this value other than that it is easily
343 * recognizable, and it will reflect any byte order mismatches.
345 #define MDB_MAGIC 0xBEEFC0DE
347 /** The version number for a database's datafile format. */
348 #define MDB_DATA_VERSION 1
349 /** The version number for a database's lockfile format. */
350 #define MDB_LOCK_VERSION 1
352 /** @brief The maximum size of a key in the database.
354 * The library rejects bigger keys, and cannot deal with records
355 * with bigger keys stored by a library with bigger max keysize.
357 * We require that keys all fit onto a regular page. This limit
358 * could be raised a bit further if needed; to something just
359 * under #MDB_PAGESIZE / #MDB_MINKEYS.
361 * Note that data items in an #MDB_DUPSORT database are actually keys
362 * of a subDB, so they're also limited to this size.
364 #ifndef MDB_MAXKEYSIZE
365 #define MDB_MAXKEYSIZE 511
368 /** @brief The maximum size of a data item.
370 * We only store a 32 bit value for node sizes.
372 #define MAXDATASIZE 0xffffffffUL
377 * This is used for printing a hex dump of a key's contents.
379 #define DKBUF char kbuf[(MDB_MAXKEYSIZE*2+1)]
380 /** Display a key in hex.
382 * Invoke a function to display a key in hex.
384 #define DKEY(x) mdb_dkey(x, kbuf)
386 #define DKBUF typedef int dummy_kbuf /* so we can put ';' after */
390 /** An invalid page number.
391 * Mainly used to denote an empty tree.
393 #define P_INVALID (~(pgno_t)0)
395 /** Test if the flags \b f are set in a flag word \b w. */
396 #define F_ISSET(w, f) (((w) & (f)) == (f))
398 /** Used for offsets within a single page.
399 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
402 typedef uint16_t indx_t;
404 /** Default size of memory map.
405 * This is certainly too small for any actual applications. Apps should always set
406 * the size explicitly using #mdb_env_set_mapsize().
408 #define DEFAULT_MAPSIZE 1048576
410 /** @defgroup readers Reader Lock Table
411 * Readers don't acquire any locks for their data access. Instead, they
412 * simply record their transaction ID in the reader table. The reader
413 * mutex is needed just to find an empty slot in the reader table. The
414 * slot's address is saved in thread-specific data so that subsequent read
415 * transactions started by the same thread need no further locking to proceed.
417 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
419 * No reader table is used if the database is on a read-only filesystem.
421 * Since the database uses multi-version concurrency control, readers don't
422 * actually need any locking. This table is used to keep track of which
423 * readers are using data from which old transactions, so that we'll know
424 * when a particular old transaction is no longer in use. Old transactions
425 * that have discarded any data pages can then have those pages reclaimed
426 * for use by a later write transaction.
428 * The lock table is constructed such that reader slots are aligned with the
429 * processor's cache line size. Any slot is only ever used by one thread.
430 * This alignment guarantees that there will be no contention or cache
431 * thrashing as threads update their own slot info, and also eliminates
432 * any need for locking when accessing a slot.
434 * A writer thread will scan every slot in the table to determine the oldest
435 * outstanding reader transaction. Any freed pages older than this will be
436 * reclaimed by the writer. The writer doesn't use any locks when scanning
437 * this table. This means that there's no guarantee that the writer will
438 * see the most up-to-date reader info, but that's not required for correct
439 * operation - all we need is to know the upper bound on the oldest reader,
440 * we don't care at all about the newest reader. So the only consequence of
441 * reading stale information here is that old pages might hang around a
442 * while longer before being reclaimed. That's actually good anyway, because
443 * the longer we delay reclaiming old pages, the more likely it is that a
444 * string of contiguous pages can be found after coalescing old pages from
445 * many old transactions together.
448 /** Number of slots in the reader table.
449 * This value was chosen somewhat arbitrarily. 126 readers plus a
450 * couple mutexes fit exactly into 8KB on my development machine.
451 * Applications should set the table size using #mdb_env_set_maxreaders().
453 #define DEFAULT_READERS 126
455 /** The size of a CPU cache line in bytes. We want our lock structures
456 * aligned to this size to avoid false cache line sharing in the
458 * This value works for most CPUs. For Itanium this should be 128.
464 /** The information we store in a single slot of the reader table.
465 * In addition to a transaction ID, we also record the process and
466 * thread ID that owns a slot, so that we can detect stale information,
467 * e.g. threads or processes that went away without cleaning up.
468 * @note We currently don't check for stale records. We simply re-init
469 * the table when we know that we're the only process opening the
472 typedef struct MDB_rxbody {
473 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
474 * Multiple readers that start at the same time will probably have the
475 * same ID here. Again, it's not important to exclude them from
476 * anything; all we need to know is which version of the DB they
477 * started from so we can avoid overwriting any data used in that
478 * particular version.
481 /** The process ID of the process owning this reader txn. */
483 /** The thread ID of the thread owning this txn. */
487 /** The actual reader record, with cacheline padding. */
488 typedef struct MDB_reader {
491 /** shorthand for mrb_txnid */
492 #define mr_txnid mru.mrx.mrb_txnid
493 #define mr_pid mru.mrx.mrb_pid
494 #define mr_tid mru.mrx.mrb_tid
495 /** cache line alignment */
496 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
500 /** The header for the reader table.
501 * The table resides in a memory-mapped file. (This is a different file
502 * than is used for the main database.)
504 * For POSIX the actual mutexes reside in the shared memory of this
505 * mapped file. On Windows, mutexes are named objects allocated by the
506 * kernel; we store the mutex names in this mapped file so that other
507 * processes can grab them. This same approach is also used on
508 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
509 * process-shared POSIX mutexes. For these cases where a named object
510 * is used, the object name is derived from a 64 bit FNV hash of the
511 * environment pathname. As such, naming collisions are extremely
512 * unlikely. If a collision occurs, the results are unpredictable.
514 typedef struct MDB_txbody {
515 /** Stamp identifying this as an MDB file. It must be set
518 /** Version number of this lock file. Must be set to #MDB_LOCK_VERSION. */
519 uint32_t mtb_version;
520 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
521 char mtb_rmname[MNAME_LEN];
523 /** Mutex protecting access to this table.
524 * This is the reader lock that #LOCK_MUTEX_R acquires.
526 pthread_mutex_t mtb_mutex;
528 /** The ID of the last transaction committed to the database.
529 * This is recorded here only for convenience; the value can always
530 * be determined by reading the main database meta pages.
533 /** The number of slots that have been used in the reader table.
534 * This always records the maximum count, it is not decremented
535 * when readers release their slots.
537 unsigned mtb_numreaders;
540 /** The actual reader table definition. */
541 typedef struct MDB_txninfo {
544 #define mti_magic mt1.mtb.mtb_magic
545 #define mti_version mt1.mtb.mtb_version
546 #define mti_mutex mt1.mtb.mtb_mutex
547 #define mti_rmname mt1.mtb.mtb_rmname
548 #define mti_txnid mt1.mtb.mtb_txnid
549 #define mti_numreaders mt1.mtb.mtb_numreaders
550 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
553 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
554 char mt2_wmname[MNAME_LEN];
555 #define mti_wmname mt2.mt2_wmname
557 pthread_mutex_t mt2_wmutex;
558 #define mti_wmutex mt2.mt2_wmutex
560 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
562 MDB_reader mti_readers[1];
566 /** Common header for all page types.
567 * Overflow records occupy a number of contiguous pages with no
568 * headers on any page after the first.
570 typedef struct MDB_page {
571 #define mp_pgno mp_p.p_pgno
572 #define mp_next mp_p.p_next
574 pgno_t p_pgno; /**< page number */
575 void * p_next; /**< for in-memory list of freed structs */
578 /** @defgroup mdb_page Page Flags
580 * Flags for the page headers.
583 #define P_BRANCH 0x01 /**< branch page */
584 #define P_LEAF 0x02 /**< leaf page */
585 #define P_OVERFLOW 0x04 /**< overflow page */
586 #define P_META 0x08 /**< meta page */
587 #define P_DIRTY 0x10 /**< dirty page */
588 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
589 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
590 #define P_KEEP 0x8000 /**< leave this page alone during spill */
592 uint16_t mp_flags; /**< @ref mdb_page */
593 #define mp_lower mp_pb.pb.pb_lower
594 #define mp_upper mp_pb.pb.pb_upper
595 #define mp_pages mp_pb.pb_pages
598 indx_t pb_lower; /**< lower bound of free space */
599 indx_t pb_upper; /**< upper bound of free space */
601 uint32_t pb_pages; /**< number of overflow pages */
603 indx_t mp_ptrs[1]; /**< dynamic size */
606 /** Size of the page header, excluding dynamic data at the end */
607 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
609 /** Address of first usable data byte in a page, after the header */
610 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
612 /** Number of nodes on a page */
613 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
615 /** The amount of space remaining in the page */
616 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
618 /** The percentage of space used in the page, in tenths of a percent. */
619 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
620 ((env)->me_psize - PAGEHDRSZ))
621 /** The minimum page fill factor, in tenths of a percent.
622 * Pages emptier than this are candidates for merging.
624 #define FILL_THRESHOLD 250
626 /** Test if a page is a leaf page */
627 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
628 /** Test if a page is a LEAF2 page */
629 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
630 /** Test if a page is a branch page */
631 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
632 /** Test if a page is an overflow page */
633 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
634 /** Test if a page is a sub page */
635 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
637 /** The number of overflow pages needed to store the given size. */
638 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
640 /** Header for a single key/data pair within a page.
641 * We guarantee 2-byte alignment for nodes.
643 typedef struct MDB_node {
644 /** lo and hi are used for data size on leaf nodes and for
645 * child pgno on branch nodes. On 64 bit platforms, flags
646 * is also used for pgno. (Branch nodes have no flags).
647 * They are in host byte order in case that lets some
648 * accesses be optimized into a 32-bit word access.
650 #define mn_lo mn_offset[BYTE_ORDER!=LITTLE_ENDIAN]
651 #define mn_hi mn_offset[BYTE_ORDER==LITTLE_ENDIAN] /**< part of dsize or pgno */
652 unsigned short mn_offset[2]; /**< storage for #mn_lo and #mn_hi */
653 /** @defgroup mdb_node Node Flags
655 * Flags for node headers.
658 #define F_BIGDATA 0x01 /**< data put on overflow page */
659 #define F_SUBDATA 0x02 /**< data is a sub-database */
660 #define F_DUPDATA 0x04 /**< data has duplicates */
662 /** valid flags for #mdb_node_add() */
663 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
666 unsigned short mn_flags; /**< @ref mdb_node */
667 unsigned short mn_ksize; /**< key size */
668 char mn_data[1]; /**< key and data are appended here */
671 /** Size of the node header, excluding dynamic data at the end */
672 #define NODESIZE offsetof(MDB_node, mn_data)
674 /** Bit position of top word in page number, for shifting mn_flags */
675 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
677 /** Size of a node in a branch page with a given key.
678 * This is just the node header plus the key, there is no data.
680 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
682 /** Size of a node in a leaf page with a given key and data.
683 * This is node header plus key plus data size.
685 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
687 /** Address of node \b i in page \b p */
688 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
690 /** Address of the key for the node */
691 #define NODEKEY(node) (void *)((node)->mn_data)
693 /** Address of the data for a node */
694 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
696 /** Get the page number pointed to by a branch node */
697 #define NODEPGNO(node) \
698 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
699 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
700 /** Set the page number in a branch node */
701 #define SETPGNO(node,pgno) do { \
702 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
703 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
705 /** Get the size of the data in a leaf node */
706 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
707 /** Set the size of the data for a leaf node */
708 #define SETDSZ(node,size) do { \
709 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
710 /** The size of a key in a node */
711 #define NODEKSZ(node) ((node)->mn_ksize)
713 /** Copy a page number from src to dst */
715 #define COPY_PGNO(dst,src) dst = src
717 #if SIZE_MAX > 4294967295UL
718 #define COPY_PGNO(dst,src) do { \
719 unsigned short *s, *d; \
720 s = (unsigned short *)&(src); \
721 d = (unsigned short *)&(dst); \
728 #define COPY_PGNO(dst,src) do { \
729 unsigned short *s, *d; \
730 s = (unsigned short *)&(src); \
731 d = (unsigned short *)&(dst); \
737 /** The address of a key in a LEAF2 page.
738 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
739 * There are no node headers, keys are stored contiguously.
741 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
743 /** Set the \b node's key into \b key, if requested. */
744 #define MDB_GET_KEY(node, key) { if ((key) != NULL) { \
745 (key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node); } }
747 /** Information about a single database in the environment. */
748 typedef struct MDB_db {
749 uint32_t md_pad; /**< also ksize for LEAF2 pages */
750 uint16_t md_flags; /**< @ref mdb_dbi_open */
751 uint16_t md_depth; /**< depth of this tree */
752 pgno_t md_branch_pages; /**< number of internal pages */
753 pgno_t md_leaf_pages; /**< number of leaf pages */
754 pgno_t md_overflow_pages; /**< number of overflow pages */
755 size_t md_entries; /**< number of data items */
756 pgno_t md_root; /**< the root page of this tree */
759 /** mdb_dbi_open flags */
760 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
761 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
762 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
763 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
765 /** Handle for the DB used to track free pages. */
767 /** Handle for the default DB. */
770 /** Meta page content. */
771 typedef struct MDB_meta {
772 /** Stamp identifying this as an MDB file. It must be set
775 /** Version number of this lock file. Must be set to #MDB_DATA_VERSION. */
777 void *mm_address; /**< address for fixed mapping */
778 size_t mm_mapsize; /**< size of mmap region */
779 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
780 /** The size of pages used in this DB */
781 #define mm_psize mm_dbs[0].md_pad
782 /** Any persistent environment flags. @ref mdb_env */
783 #define mm_flags mm_dbs[0].md_flags
784 pgno_t mm_last_pg; /**< last used page in file */
785 txnid_t mm_txnid; /**< txnid that committed this page */
788 /** Buffer for a stack-allocated dirty page.
789 * The members define size and alignment, and silence type
790 * aliasing warnings. They are not used directly; that could
791 * mean incorrectly using several union members in parallel.
793 typedef union MDB_pagebuf {
794 char mb_raw[MDB_PAGESIZE];
797 char mm_pad[PAGEHDRSZ];
802 /** Auxiliary DB info.
803 * The information here is mostly static/read-only. There is
804 * only a single copy of this record in the environment.
806 typedef struct MDB_dbx {
807 MDB_val md_name; /**< name of the database */
808 MDB_cmp_func *md_cmp; /**< function for comparing keys */
809 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
810 MDB_rel_func *md_rel; /**< user relocate function */
811 void *md_relctx; /**< user-provided context for md_rel */
814 /** A database transaction.
815 * Every operation requires a transaction handle.
818 MDB_txn *mt_parent; /**< parent of a nested txn */
819 MDB_txn *mt_child; /**< nested txn under this txn */
820 pgno_t mt_next_pgno; /**< next unallocated page */
821 /** The ID of this transaction. IDs are integers incrementing from 1.
822 * Only committed write transactions increment the ID. If a transaction
823 * aborts, the ID may be re-used by the next writer.
826 MDB_env *mt_env; /**< the DB environment */
827 /** The list of pages that became unused during this transaction.
830 /** The sorted list of dirty pages we temporarily wrote to disk
831 * because the dirty list was full.
833 MDB_IDL mt_spill_pgs;
835 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
837 /** For read txns: This thread/txn's reader table slot, or NULL. */
840 /** Array of records for each DB known in the environment. */
842 /** Array of MDB_db records for each known DB */
844 /** @defgroup mt_dbflag Transaction DB Flags
848 #define DB_DIRTY 0x01 /**< DB was written in this txn */
849 #define DB_STALE 0x02 /**< DB record is older than txnID */
850 #define DB_NEW 0x04 /**< DB handle opened in this txn */
851 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
853 /** In write txns, array of cursors for each DB */
854 MDB_cursor **mt_cursors;
855 /** Array of flags for each DB */
856 unsigned char *mt_dbflags;
857 /** Number of DB records in use. This number only ever increments;
858 * we don't decrement it when individual DB handles are closed.
862 /** @defgroup mdb_txn Transaction Flags
866 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
867 #define MDB_TXN_ERROR 0x02 /**< an error has occurred */
868 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
869 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
871 unsigned int mt_flags; /**< @ref mdb_txn */
872 /** dirty_list maxsize - # of allocated pages allowed, including in parent txns */
873 unsigned int mt_dirty_room;
874 /** Tracks which of the two meta pages was used at the start
875 * of this transaction.
877 unsigned int mt_toggle;
880 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
881 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
882 * raise this on a 64 bit machine.
884 #define CURSOR_STACK 32
888 /** Cursors are used for all DB operations */
890 /** Next cursor on this DB in this txn */
892 /** Backup of the original cursor if this cursor is a shadow */
893 MDB_cursor *mc_backup;
894 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
895 struct MDB_xcursor *mc_xcursor;
896 /** The transaction that owns this cursor */
898 /** The database handle this cursor operates on */
900 /** The database record for this cursor */
902 /** The database auxiliary record for this cursor */
904 /** The @ref mt_dbflag for this database */
905 unsigned char *mc_dbflag;
906 unsigned short mc_snum; /**< number of pushed pages */
907 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
908 /** @defgroup mdb_cursor Cursor Flags
910 * Cursor state flags.
913 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
914 #define C_EOF 0x02 /**< No more data */
915 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
916 #define C_SPLITTING 0x20 /**< Cursor is in page_split */
917 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
919 unsigned int mc_flags; /**< @ref mdb_cursor */
920 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
921 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
924 /** Context for sorted-dup records.
925 * We could have gone to a fully recursive design, with arbitrarily
926 * deep nesting of sub-databases. But for now we only handle these
927 * levels - main DB, optional sub-DB, sorted-duplicate DB.
929 typedef struct MDB_xcursor {
930 /** A sub-cursor for traversing the Dup DB */
931 MDB_cursor mx_cursor;
932 /** The database record for this Dup DB */
934 /** The auxiliary DB record for this Dup DB */
936 /** The @ref mt_dbflag for this Dup DB */
937 unsigned char mx_dbflag;
940 /** State of FreeDB old pages, stored in the MDB_env */
941 typedef struct MDB_pgstate {
942 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
943 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
946 /** The database environment. */
948 HANDLE me_fd; /**< The main data file */
949 HANDLE me_lfd; /**< The lock file */
950 HANDLE me_mfd; /**< just for writing the meta pages */
951 /** Failed to update the meta page. Probably an I/O error. */
952 #define MDB_FATAL_ERROR 0x80000000U
953 /** Some fields are initialized. */
954 #define MDB_ENV_ACTIVE 0x20000000U
955 /** me_txkey is set */
956 #define MDB_ENV_TXKEY 0x10000000U
957 /** Have liveness lock in reader table */
958 #define MDB_LIVE_READER 0x08000000U
959 uint32_t me_flags; /**< @ref mdb_env */
960 unsigned int me_psize; /**< size of a page, from #GET_PAGESIZE */
961 unsigned int me_maxreaders; /**< size of the reader table */
962 unsigned int me_numreaders; /**< max numreaders set by this env */
963 MDB_dbi me_numdbs; /**< number of DBs opened */
964 MDB_dbi me_maxdbs; /**< size of the DB table */
965 pid_t me_pid; /**< process ID of this env */
966 char *me_path; /**< path to the DB files */
967 char *me_map; /**< the memory map of the data file */
968 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
969 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
970 MDB_txn *me_txn; /**< current write transaction */
971 size_t me_mapsize; /**< size of the data memory map */
972 off_t me_size; /**< current file size */
973 pgno_t me_maxpg; /**< me_mapsize / me_psize */
974 MDB_dbx *me_dbxs; /**< array of static DB info */
975 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
976 pthread_key_t me_txkey; /**< thread-key for readers */
977 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
978 # define me_pglast me_pgstate.mf_pglast
979 # define me_pghead me_pgstate.mf_pghead
980 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
981 /** IDL of pages that became unused in a write txn */
983 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
984 MDB_ID2L me_dirty_list;
985 /** Max number of freelist items that can fit in a single overflow page */
987 /** Max size of a node on a page */
988 unsigned int me_nodemax;
990 int me_pidquery; /**< Used in OpenProcess */
991 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
993 #elif defined(MDB_USE_POSIX_SEM)
994 sem_t *me_rmutex; /* Shared mutexes are not supported */
999 /** Nested transaction */
1000 typedef struct MDB_ntxn {
1001 MDB_txn mnt_txn; /* the transaction */
1002 MDB_pgstate mnt_pgstate; /* parent transaction's saved freestate */
1005 /** max number of pages to commit in one writev() call */
1006 #define MDB_COMMIT_PAGES 64
1007 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1008 #undef MDB_COMMIT_PAGES
1009 #define MDB_COMMIT_PAGES IOV_MAX
1012 /* max bytes to write in one call */
1013 #define MAX_WRITE (0x80000000U >> (sizeof(ssize_t) == 4))
1015 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1016 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1017 static int mdb_page_touch(MDB_cursor *mc);
1019 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp, int *lvl);
1020 static int mdb_page_search_root(MDB_cursor *mc,
1021 MDB_val *key, int modify);
1022 #define MDB_PS_MODIFY 1
1023 #define MDB_PS_ROOTONLY 2
1024 static int mdb_page_search(MDB_cursor *mc,
1025 MDB_val *key, int flags);
1026 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1028 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1029 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1030 pgno_t newpgno, unsigned int nflags);
1032 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1033 static int mdb_env_pick_meta(const MDB_env *env);
1034 static int mdb_env_write_meta(MDB_txn *txn);
1035 #if !(defined(_WIN32) || defined(MDB_USE_POSIX_SEM)) /* Drop unused excl arg */
1036 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1038 static void mdb_env_close0(MDB_env *env, int excl);
1040 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1041 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1042 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1043 static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
1044 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1045 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
1046 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1047 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1048 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1050 static int mdb_rebalance(MDB_cursor *mc);
1051 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1053 static void mdb_cursor_pop(MDB_cursor *mc);
1054 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1056 static int mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
1057 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1058 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1059 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1060 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1062 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1063 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1065 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1066 static void mdb_xcursor_init0(MDB_cursor *mc);
1067 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1069 static int mdb_drop0(MDB_cursor *mc, int subs);
1070 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1073 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1077 static SECURITY_DESCRIPTOR mdb_null_sd;
1078 static SECURITY_ATTRIBUTES mdb_all_sa;
1079 static int mdb_sec_inited;
1082 /** Return the library version info. */
1084 mdb_version(int *major, int *minor, int *patch)
1086 if (major) *major = MDB_VERSION_MAJOR;
1087 if (minor) *minor = MDB_VERSION_MINOR;
1088 if (patch) *patch = MDB_VERSION_PATCH;
1089 return MDB_VERSION_STRING;
1092 /** Table of descriptions for MDB @ref errors */
1093 static char *const mdb_errstr[] = {
1094 "MDB_KEYEXIST: Key/data pair already exists",
1095 "MDB_NOTFOUND: No matching key/data pair found",
1096 "MDB_PAGE_NOTFOUND: Requested page not found",
1097 "MDB_CORRUPTED: Located page was wrong type",
1098 "MDB_PANIC: Update of meta page failed",
1099 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1100 "MDB_INVALID: File is not an MDB file",
1101 "MDB_MAP_FULL: Environment mapsize limit reached",
1102 "MDB_DBS_FULL: Environment maxdbs limit reached",
1103 "MDB_READERS_FULL: Environment maxreaders limit reached",
1104 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1105 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1106 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1107 "MDB_PAGE_FULL: Internal error - page has no more space",
1108 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1109 "MDB_INCOMPATIBLE: Database flags changed or would change",
1110 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1114 mdb_strerror(int err)
1118 return ("Successful return: 0");
1120 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1121 i = err - MDB_KEYEXIST;
1122 return mdb_errstr[i];
1125 return strerror(err);
1129 /** Display a key in hexadecimal and return the address of the result.
1130 * @param[in] key the key to display
1131 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1132 * @return The key in hexadecimal form.
1135 mdb_dkey(MDB_val *key, char *buf)
1138 unsigned char *c = key->mv_data;
1144 if (key->mv_size > MDB_MAXKEYSIZE)
1145 return "MDB_MAXKEYSIZE";
1146 /* may want to make this a dynamic check: if the key is mostly
1147 * printable characters, print it as-is instead of converting to hex.
1151 for (i=0; i<key->mv_size; i++)
1152 ptr += sprintf(ptr, "%02x", *c++);
1154 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1159 /** Display all the keys in the page. */
1161 mdb_page_list(MDB_page *mp)
1164 unsigned int i, nkeys, nsize;
1168 nkeys = NUMKEYS(mp);
1169 fprintf(stderr, "Page %zu numkeys %d\n", mp->mp_pgno, nkeys);
1170 for (i=0; i<nkeys; i++) {
1171 node = NODEPTR(mp, i);
1172 key.mv_size = node->mn_ksize;
1173 key.mv_data = node->mn_data;
1174 nsize = NODESIZE + NODEKSZ(node) + sizeof(indx_t);
1175 if (IS_BRANCH(mp)) {
1176 fprintf(stderr, "key %d: page %zu, %s\n", i, NODEPGNO(node),
1179 if (F_ISSET(node->mn_flags, F_BIGDATA))
1180 nsize += sizeof(pgno_t);
1182 nsize += NODEDSZ(node);
1183 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1189 mdb_cursor_chk(MDB_cursor *mc)
1195 if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1196 for (i=0; i<mc->mc_top; i++) {
1198 node = NODEPTR(mp, mc->mc_ki[i]);
1199 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1202 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1208 /** Count all the pages in each DB and in the freelist
1209 * and make sure it matches the actual number of pages
1212 static void mdb_audit(MDB_txn *txn)
1216 MDB_ID freecount, count;
1221 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1222 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1223 freecount += *(MDB_ID *)data.mv_data;
1226 for (i = 0; i<txn->mt_numdbs; i++) {
1228 mdb_cursor_init(&mc, txn, i, &mx);
1229 if (txn->mt_dbs[i].md_root == P_INVALID)
1231 count += txn->mt_dbs[i].md_branch_pages +
1232 txn->mt_dbs[i].md_leaf_pages +
1233 txn->mt_dbs[i].md_overflow_pages;
1234 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1235 mdb_page_search(&mc, NULL, 0);
1239 mp = mc.mc_pg[mc.mc_top];
1240 for (j=0; j<NUMKEYS(mp); j++) {
1241 MDB_node *leaf = NODEPTR(mp, j);
1242 if (leaf->mn_flags & F_SUBDATA) {
1244 memcpy(&db, NODEDATA(leaf), sizeof(db));
1245 count += db.md_branch_pages + db.md_leaf_pages +
1246 db.md_overflow_pages;
1250 while (mdb_cursor_sibling(&mc, 1) == 0);
1253 if (freecount + count + 2 /* metapages */ != txn->mt_next_pgno) {
1254 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1255 txn->mt_txnid, freecount, count+2, freecount+count+2, txn->mt_next_pgno);
1261 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1263 return txn->mt_dbxs[dbi].md_cmp(a, b);
1267 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1269 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1272 /** Allocate memory for a page.
1273 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1276 mdb_page_malloc(MDB_txn *txn, unsigned num)
1278 MDB_env *env = txn->mt_env;
1279 MDB_page *ret = env->me_dpages;
1280 size_t sz = env->me_psize;
1283 VGMEMP_ALLOC(env, ret, sz);
1284 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1285 env->me_dpages = ret->mp_next;
1291 if ((ret = malloc(sz)) != NULL) {
1292 VGMEMP_ALLOC(env, ret, sz);
1297 /** Free a single page.
1298 * Saves single pages to a list, for future reuse.
1299 * (This is not used for multi-page overflow pages.)
1302 mdb_page_free(MDB_env *env, MDB_page *mp)
1304 mp->mp_next = env->me_dpages;
1305 VGMEMP_FREE(env, mp);
1306 env->me_dpages = mp;
1309 /* Free a dirty page */
1311 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1313 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1314 mdb_page_free(env, dp);
1316 /* large pages just get freed directly */
1317 VGMEMP_FREE(env, dp);
1322 /** Return all dirty pages to dpage list */
1324 mdb_dlist_free(MDB_txn *txn)
1326 MDB_env *env = txn->mt_env;
1327 MDB_ID2L dl = txn->mt_u.dirty_list;
1328 unsigned i, n = dl[0].mid;
1330 for (i = 1; i <= n; i++) {
1331 mdb_dpage_free(env, dl[i].mptr);
1336 /* Set or clear P_KEEP in non-overflow, non-sub pages in known cursors.
1337 * When clearing, only consider backup cursors (from parent txns) since
1338 * other P_KEEP flags have already been cleared.
1339 * @param[in] mc A cursor handle for the current operation.
1340 * @param[in] pflags Flags of the pages to update:
1341 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1344 mdb_cursorpages_mark(MDB_cursor *mc, unsigned pflags)
1346 MDB_txn *txn = mc->mc_txn;
1347 MDB_cursor *m2, *m3;
1351 if (mc->mc_flags & C_UNTRACK)
1352 mc = NULL; /* will find mc in mt_cursors */
1353 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1354 for (; mc; mc=mc->mc_next) {
1355 m2 = pflags == P_DIRTY ? mc : mc->mc_backup;
1356 for (; m2; m2 = m2->mc_backup) {
1357 for (m3=m2; m3->mc_flags & C_INITIALIZED; m3=&mx->mx_cursor) {
1358 for (j=0; j<m3->mc_snum; j++)
1359 if ((m3->mc_pg[j]->mp_flags & (P_SUBP|P_DIRTY|P_KEEP))
1361 m3->mc_pg[j]->mp_flags ^= P_KEEP;
1362 if (!(m3->mc_db->md_flags & MDB_DUPSORT))
1364 /* Cursor backups have mx malloced at the end of m2 */
1365 mx = (m3 == mc ? m3->mc_xcursor : (MDB_xcursor *)(m3+1));
1374 static int mdb_page_flush(MDB_txn *txn);
1376 /** Spill pages from the dirty list back to disk.
1377 * This is intended to prevent running into #MDB_TXN_FULL situations,
1378 * but note that they may still occur in a few cases:
1379 * 1) pages in #MDB_DUPSORT sub-DBs are never spilled, so if there
1380 * are too many of these dirtied in one txn, the txn may still get
1382 * 2) child txns may run out of space if their parents dirtied a
1383 * lot of pages and never spilled them. TODO: we probably should do
1384 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1385 * the parent's dirty_room is below a given threshold.
1386 * 3) our estimate of the txn size could be too small. At the
1387 * moment this seems unlikely.
1389 * Otherwise, if not using nested txns, it is expected that apps will
1390 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1391 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1392 * If the txn never references them again, they can be left alone.
1393 * If the txn only reads them, they can be used without any fuss.
1394 * If the txn writes them again, they can be dirtied immediately without
1395 * going thru all of the work of #mdb_page_touch(). Such references are
1396 * handled by #mdb_page_unspill().
1398 * Also note, we never spill DB root pages, nor pages of active cursors,
1399 * because we'll need these back again soon anyway. And in nested txns,
1400 * we can't spill a page in a child txn if it was already spilled in a
1401 * parent txn. That would alter the parent txns' data even though
1402 * the child hasn't committed yet, and we'd have no way to undo it if
1403 * the child aborted.
1405 * @param[in] m0 cursor A cursor handle identifying the transaction and
1406 * database for which we are checking space.
1407 * @param[in] key For a put operation, the key being stored.
1408 * @param[in] data For a put operation, the data being stored.
1409 * @return 0 on success, non-zero on failure.
1412 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1414 MDB_txn *txn = m0->mc_txn;
1416 MDB_ID2L dl = txn->mt_u.dirty_list;
1420 if (m0->mc_flags & C_SUB)
1423 /* Estimate how much space this op will take */
1424 i = m0->mc_db->md_depth;
1425 /* Named DBs also dirty the main DB */
1426 if (m0->mc_dbi > MAIN_DBI)
1427 i += txn->mt_dbs[MAIN_DBI].md_depth;
1428 /* For puts, roughly factor in the key+data size */
1430 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
1431 i += i; /* double it for good measure */
1433 if (txn->mt_dirty_room > i)
1436 if (!txn->mt_spill_pgs) {
1437 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
1438 if (!txn->mt_spill_pgs)
1442 /* Mark all the dirty root pages we want to preserve */
1443 for (i=0; i<txn->mt_numdbs; i++) {
1444 if (txn->mt_dbflags[i] & DB_DIRTY) {
1445 j = mdb_mid2l_search(dl, txn->mt_dbs[i].md_root);
1446 if (j <= dl[0].mid) {
1448 dp->mp_flags |= P_KEEP;
1453 /* Preserve pages used by cursors */
1454 mdb_cursorpages_mark(m0, P_DIRTY);
1456 /* Save the page IDs of all the pages we're flushing */
1457 for (i=1; i<=dl[0].mid; i++) {
1459 if (dp->mp_flags & P_KEEP)
1461 /* Can't spill twice, make sure it's not already in a parent's
1464 if (txn->mt_parent) {
1466 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1467 if (tx2->mt_spill_pgs) {
1468 j = mdb_midl_search(tx2->mt_spill_pgs, dl[i].mid);
1469 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == dl[i].mid) {
1470 dp->mp_flags |= P_KEEP;
1478 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, dl[i].mid)))
1481 mdb_midl_sort(txn->mt_spill_pgs);
1483 rc = mdb_page_flush(txn);
1485 mdb_cursorpages_mark(m0, P_DIRTY|P_KEEP);
1488 if (txn->mt_parent) {
1490 pgno_t pgno = dl[i].mid;
1491 txn->mt_dirty_room = txn->mt_parent->mt_dirty_room - dl[0].mid;
1492 /* dirty pages that are dirty in an ancestor don't
1493 * count against this txn's dirty_room.
1495 for (i=1; i<=dl[0].mid; i++) {
1496 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1497 j = mdb_mid2l_search(tx2->mt_u.dirty_list, pgno);
1498 if (j <= tx2->mt_u.dirty_list[0].mid &&
1499 tx2->mt_u.dirty_list[j].mid == pgno) {
1500 txn->mt_dirty_room++;
1506 txn->mt_dirty_room = MDB_IDL_UM_MAX - dl[0].mid;
1508 txn->mt_flags |= MDB_TXN_SPILLS;
1513 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
1515 mdb_find_oldest(MDB_txn *txn)
1518 txnid_t mr, oldest = txn->mt_txnid - 1;
1519 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
1520 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
1530 /** Add a page to the txn's dirty list */
1532 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
1535 int (*insert)(MDB_ID2L, MDB_ID2 *);
1537 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1538 insert = mdb_mid2l_append;
1540 insert = mdb_mid2l_insert;
1542 mid.mid = mp->mp_pgno;
1544 insert(txn->mt_u.dirty_list, &mid);
1545 txn->mt_dirty_room--;
1548 /** Allocate page numbers and memory for writing. Maintain me_pglast,
1549 * me_pghead and mt_next_pgno.
1551 * If there are free pages available from older transactions, they
1552 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
1553 * Do not modify the freedB, just merge freeDB records into me_pghead[]
1554 * and move me_pglast to say which records were consumed. Only this
1555 * function can create me_pghead and move me_pglast/mt_next_pgno.
1556 * @param[in] mc cursor A cursor handle identifying the transaction and
1557 * database for which we are allocating.
1558 * @param[in] num the number of pages to allocate.
1559 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
1560 * will always be satisfied by a single contiguous chunk of memory.
1561 * @return 0 on success, non-zero on failure.
1564 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
1566 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
1567 /* Get at most <Max_retries> more freeDB records once me_pghead
1568 * has enough pages. If not enough, use new pages from the map.
1569 * If <Paranoid> and mc is updating the freeDB, only get new
1570 * records if me_pghead is empty. Then the freelist cannot play
1571 * catch-up with itself by growing while trying to save it.
1573 enum { Paranoid = 1, Max_retries = 500 };
1575 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
1577 int rc, n2 = num-1, retry = Max_retries;
1578 MDB_txn *txn = mc->mc_txn;
1579 MDB_env *env = txn->mt_env;
1580 pgno_t pgno, *mop = env->me_pghead;
1581 unsigned i, j, k, mop_len = mop ? mop[0] : 0;
1583 txnid_t oldest = 0, last;
1589 /* If our dirty list is already full, we can't do anything */
1590 if (txn->mt_dirty_room == 0)
1591 return MDB_TXN_FULL;
1593 for (op = MDB_FIRST;; op = MDB_NEXT) {
1596 pgno_t *idl, old_id, new_id;
1598 /* Seek a big enough contiguous page range. Prefer
1599 * pages at the tail, just truncating the list.
1601 if (mop_len >= (unsigned)num) {
1605 if (mop[i-n2] == pgno+n2)
1607 } while (--i >= (unsigned)num);
1608 if (Max_retries < INT_MAX && --retry < 0)
1612 if (op == MDB_FIRST) { /* 1st iteration */
1613 /* Prepare to fetch more and coalesce */
1614 oldest = mdb_find_oldest(txn);
1615 last = env->me_pglast;
1616 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1619 key.mv_data = &last; /* will look up last+1 */
1620 key.mv_size = sizeof(last);
1622 if (Paranoid && mc->mc_dbi == FREE_DBI)
1625 if (Paranoid && retry < 0 && mop_len)
1629 /* Do not fetch more if the record will be too recent */
1632 rc = mdb_cursor_get(&m2, &key, NULL, op);
1634 if (rc == MDB_NOTFOUND)
1638 last = *(txnid_t*)key.mv_data;
1641 np = m2.mc_pg[m2.mc_top];
1642 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
1643 if ((rc = mdb_node_read(txn, leaf, &data)) != MDB_SUCCESS)
1646 idl = (MDB_ID *) data.mv_data;
1649 if (!(env->me_pghead = mop = mdb_midl_alloc(i)))
1652 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
1654 mop = env->me_pghead;
1656 env->me_pglast = last;
1658 DPRINTF("IDL read txn %zu root %zu num %u",
1659 last, txn->mt_dbs[FREE_DBI].md_root, i);
1661 DPRINTF("IDL %zu", idl[k]);
1663 /* Merge in descending sorted order */
1666 mop[0] = (pgno_t)-1;
1670 for (; old_id < new_id; old_id = mop[--j])
1677 /* Use new pages from the map when nothing suitable in the freeDB */
1679 pgno = txn->mt_next_pgno;
1680 if (pgno + num >= env->me_maxpg) {
1681 DPUTS("DB size maxed out");
1682 return MDB_MAP_FULL;
1686 if (env->me_flags & MDB_WRITEMAP) {
1687 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
1689 if (!(np = mdb_page_malloc(txn, num)))
1693 mop[0] = mop_len -= num;
1694 /* Move any stragglers down */
1695 for (j = i-num; j < mop_len; )
1696 mop[++j] = mop[++i];
1698 txn->mt_next_pgno = pgno + num;
1701 mdb_page_dirty(txn, np);
1707 /** Copy the used portions of a non-overflow page.
1708 * @param[in] dst page to copy into
1709 * @param[in] src page to copy from
1710 * @param[in] psize size of a page
1713 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
1715 enum { Align = sizeof(pgno_t) };
1716 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
1718 /* If page isn't full, just copy the used portion. Adjust
1719 * alignment so memcpy may copy words instead of bytes.
1721 if ((unused &= -Align) && !IS_LEAF2(src)) {
1723 memcpy(dst, src, (lower + (Align-1)) & -Align);
1724 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
1727 memcpy(dst, src, psize - unused);
1731 /** Pull a page off the txn's spill list, if present.
1732 * If a page being referenced was spilled to disk in this txn, bring
1733 * it back and make it dirty/writable again.
1734 * @param[in] tx0 the transaction handle.
1735 * @param[in] mp the page being referenced.
1736 * @param[out] ret the writable page, if any. ret is unchanged if
1737 * mp wasn't spilled.
1740 mdb_page_unspill(MDB_txn *tx0, MDB_page *mp, MDB_page **ret)
1742 MDB_env *env = tx0->mt_env;
1745 pgno_t pgno = mp->mp_pgno;
1747 for (txn = tx0; txn; txn=txn->mt_parent) {
1748 if (!txn->mt_spill_pgs)
1750 x = mdb_midl_search(txn->mt_spill_pgs, pgno);
1751 if (x <= txn->mt_spill_pgs[0] && txn->mt_spill_pgs[x] == pgno) {
1754 if (IS_OVERFLOW(mp))
1758 if (env->me_flags & MDB_WRITEMAP) {
1761 np = mdb_page_malloc(txn, num);
1765 memcpy(np, mp, num * env->me_psize);
1767 mdb_page_copy(np, mp, env->me_psize);
1770 /* If in current txn, this page is no longer spilled */
1771 for (; x < txn->mt_spill_pgs[0]; x++)
1772 txn->mt_spill_pgs[x] = txn->mt_spill_pgs[x+1];
1773 txn->mt_spill_pgs[0]--;
1774 } /* otherwise, if belonging to a parent txn, the
1775 * page remains spilled until child commits
1778 if (txn->mt_parent) {
1780 /* If this page is also in a parent's dirty list, then
1781 * it's already accounted in dirty_room, and we need to
1782 * cancel out the decrement that mdb_page_dirty does.
1784 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1785 x = mdb_mid2l_search(tx2->mt_u.dirty_list, pgno);
1786 if (x <= tx2->mt_u.dirty_list[0].mid &&
1787 tx2->mt_u.dirty_list[x].mid == pgno) {
1788 txn->mt_dirty_room++;
1793 mdb_page_dirty(tx0, np);
1794 np->mp_flags |= P_DIRTY;
1802 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1803 * @param[in] mc cursor pointing to the page to be touched
1804 * @return 0 on success, non-zero on failure.
1807 mdb_page_touch(MDB_cursor *mc)
1809 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
1810 MDB_txn *txn = mc->mc_txn;
1811 MDB_cursor *m2, *m3;
1816 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1817 if (txn->mt_flags & MDB_TXN_SPILLS) {
1819 rc = mdb_page_unspill(txn, mp, &np);
1825 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
1826 (rc = mdb_page_alloc(mc, 1, &np)))
1829 DPRINTF("touched db %u page %zu -> %zu", mc->mc_dbi,mp->mp_pgno,pgno);
1830 assert(mp->mp_pgno != pgno);
1831 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
1832 /* Update the parent page, if any, to point to the new page */
1834 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
1835 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
1836 SETPGNO(node, pgno);
1838 mc->mc_db->md_root = pgno;
1840 } else if (txn->mt_parent && !IS_SUBP(mp)) {
1841 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
1843 /* If txn has a parent, make sure the page is in our
1847 unsigned x = mdb_mid2l_search(dl, pgno);
1848 if (x <= dl[0].mid && dl[x].mid == pgno) {
1849 if (mp != dl[x].mptr) { /* bad cursor? */
1850 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1851 return MDB_CORRUPTED;
1856 assert(dl[0].mid < MDB_IDL_UM_MAX);
1858 np = mdb_page_malloc(txn, 1);
1863 mdb_mid2l_insert(dl, &mid);
1868 mdb_page_copy(np, mp, txn->mt_env->me_psize);
1870 np->mp_flags |= P_DIRTY;
1873 /* Adjust cursors pointing to mp */
1874 mc->mc_pg[mc->mc_top] = np;
1876 if (mc->mc_flags & C_SUB) {
1878 for (m2 = txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
1879 m3 = &m2->mc_xcursor->mx_cursor;
1880 if (m3->mc_snum < mc->mc_snum) continue;
1881 if (m3->mc_pg[mc->mc_top] == mp)
1882 m3->mc_pg[mc->mc_top] = np;
1885 for (m2 = txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
1886 if (m2->mc_snum < mc->mc_snum) continue;
1887 if (m2->mc_pg[mc->mc_top] == mp) {
1888 m2->mc_pg[mc->mc_top] = np;
1889 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
1890 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
1892 MDB_node *leaf = NODEPTR(np, mc->mc_ki[mc->mc_top]);
1893 if (!(leaf->mn_flags & F_SUBDATA))
1894 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
1903 mdb_env_sync(MDB_env *env, int force)
1906 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1907 if (env->me_flags & MDB_WRITEMAP) {
1908 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
1909 ? MS_ASYNC : MS_SYNC;
1910 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
1913 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
1917 if (MDB_FDATASYNC(env->me_fd))
1924 /** Back up parent txn's cursors, then grab the originals for tracking */
1926 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
1928 MDB_cursor *mc, *bk;
1933 for (i = src->mt_numdbs; --i >= 0; ) {
1934 if ((mc = src->mt_cursors[i]) != NULL) {
1935 size = sizeof(MDB_cursor);
1937 size += sizeof(MDB_xcursor);
1938 for (; mc; mc = bk->mc_next) {
1944 mc->mc_db = &dst->mt_dbs[i];
1945 /* Kill pointers into src - and dst to reduce abuse: The
1946 * user may not use mc until dst ends. Otherwise we'd...
1948 mc->mc_txn = NULL; /* ...set this to dst */
1949 mc->mc_dbflag = NULL; /* ...and &dst->mt_dbflags[i] */
1950 if ((mx = mc->mc_xcursor) != NULL) {
1951 *(MDB_xcursor *)(bk+1) = *mx;
1952 mx->mx_cursor.mc_txn = NULL; /* ...and dst. */
1954 mc->mc_next = dst->mt_cursors[i];
1955 dst->mt_cursors[i] = mc;
1962 /** Close this write txn's cursors, give parent txn's cursors back to parent.
1963 * @param[in] txn the transaction handle.
1964 * @param[in] merge true to keep changes to parent cursors, false to revert.
1965 * @return 0 on success, non-zero on failure.
1968 mdb_cursors_close(MDB_txn *txn, unsigned merge)
1970 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
1974 for (i = txn->mt_numdbs; --i >= 0; ) {
1975 for (mc = cursors[i]; mc; mc = next) {
1977 if ((bk = mc->mc_backup) != NULL) {
1979 /* Commit changes to parent txn */
1980 mc->mc_next = bk->mc_next;
1981 mc->mc_backup = bk->mc_backup;
1982 mc->mc_txn = bk->mc_txn;
1983 mc->mc_db = bk->mc_db;
1984 mc->mc_dbflag = bk->mc_dbflag;
1985 if ((mx = mc->mc_xcursor) != NULL)
1986 mx->mx_cursor.mc_txn = bk->mc_txn;
1988 /* Abort nested txn */
1990 if ((mx = mc->mc_xcursor) != NULL)
1991 *mx = *(MDB_xcursor *)(bk+1);
1995 /* Only malloced cursors are permanently tracked. */
2002 #ifdef MDB_DEBUG_SKIP
2003 #define mdb_txn_reset0(txn, act) mdb_txn_reset0(txn)
2006 mdb_txn_reset0(MDB_txn *txn, const char *act);
2014 Pidset = F_SETLK, Pidcheck = F_GETLK
2018 /** Set or check a pid lock. Set returns 0 on success.
2019 * Check returns 0 if lock exists (meaning the process is alive).
2021 * On Windows Pidset is a no-op, we merely check for the existence
2022 * of the process with the given pid. On POSIX we use a single byte
2023 * lock on the lockfile, set at an offset equal to the pid.
2026 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, pid_t pid)
2035 h = OpenProcess(env->me_pidquery, FALSE, pid);
2037 return GetLastError();
2044 struct flock lock_info;
2045 memset((void *)&lock_info, 0, sizeof(lock_info));
2046 lock_info.l_type = F_WRLCK;
2047 lock_info.l_whence = SEEK_SET;
2048 lock_info.l_start = pid;
2049 lock_info.l_len = 1;
2050 while ((rc = fcntl(env->me_lfd, op, &lock_info)) &&
2051 (rc = ErrCode()) == EINTR) ;
2052 if (op == F_GETLK && rc == 0 && lock_info.l_type == F_UNLCK)
2058 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2059 * @param[in] txn the transaction handle to initialize
2060 * @return 0 on success, non-zero on failure.
2063 mdb_txn_renew0(MDB_txn *txn)
2065 MDB_env *env = txn->mt_env;
2068 int rc, new_notls = 0;
2071 txn->mt_numdbs = env->me_numdbs;
2072 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
2074 if (txn->mt_flags & MDB_TXN_RDONLY) {
2075 if (!env->me_txns) {
2076 i = mdb_env_pick_meta(env);
2077 txn->mt_txnid = env->me_metas[i]->mm_txnid;
2078 txn->mt_u.reader = NULL;
2080 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2081 pthread_getspecific(env->me_txkey);
2083 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2084 return MDB_BAD_RSLOT;
2086 pid_t pid = env->me_pid;
2087 pthread_t tid = pthread_self();
2089 if (!(env->me_flags & MDB_LIVE_READER)) {
2090 rc = mdb_reader_pid(env, Pidset, pid);
2092 UNLOCK_MUTEX_R(env);
2095 env->me_flags |= MDB_LIVE_READER;
2099 for (i=0; i<env->me_txns->mti_numreaders; i++)
2100 if (env->me_txns->mti_readers[i].mr_pid == 0)
2102 if (i == env->me_maxreaders) {
2103 UNLOCK_MUTEX_R(env);
2104 return MDB_READERS_FULL;
2106 env->me_txns->mti_readers[i].mr_pid = pid;
2107 env->me_txns->mti_readers[i].mr_tid = tid;
2108 if (i >= env->me_txns->mti_numreaders)
2109 env->me_txns->mti_numreaders = i+1;
2110 /* Save numreaders for un-mutexed mdb_env_close() */
2111 env->me_numreaders = env->me_txns->mti_numreaders;
2112 UNLOCK_MUTEX_R(env);
2113 r = &env->me_txns->mti_readers[i];
2114 new_notls = (env->me_flags & MDB_NOTLS);
2115 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2120 txn->mt_txnid = r->mr_txnid = env->me_txns->mti_txnid;
2121 txn->mt_u.reader = r;
2123 txn->mt_toggle = txn->mt_txnid & 1;
2127 txn->mt_txnid = env->me_txns->mti_txnid;
2128 txn->mt_toggle = txn->mt_txnid & 1;
2131 if (txn->mt_txnid == mdb_debug_start)
2134 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2135 txn->mt_u.dirty_list = env->me_dirty_list;
2136 txn->mt_u.dirty_list[0].mid = 0;
2137 txn->mt_free_pgs = env->me_free_pgs;
2138 txn->mt_free_pgs[0] = 0;
2139 txn->mt_spill_pgs = NULL;
2143 /* Copy the DB info and flags */
2144 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
2146 /* Moved to here to avoid a data race in read TXNs */
2147 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
2149 for (i=2; i<txn->mt_numdbs; i++) {
2150 x = env->me_dbflags[i];
2151 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2152 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_STALE : 0;
2154 txn->mt_dbflags[0] = txn->mt_dbflags[1] = DB_VALID;
2156 if (env->me_maxpg < txn->mt_next_pgno) {
2157 mdb_txn_reset0(txn, "renew0-mapfail");
2159 txn->mt_u.reader->mr_pid = 0;
2160 txn->mt_u.reader = NULL;
2162 return MDB_MAP_RESIZED;
2169 mdb_txn_renew(MDB_txn *txn)
2173 if (!txn || txn->mt_dbxs) /* A reset txn has mt_dbxs==NULL */
2176 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
2177 DPUTS("environment had fatal error, must shutdown!");
2181 rc = mdb_txn_renew0(txn);
2182 if (rc == MDB_SUCCESS) {
2183 DPRINTF("renew txn %zu%c %p on mdbenv %p, root page %zu",
2184 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2185 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
2191 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2195 int rc, size, tsize = sizeof(MDB_txn);
2197 if (env->me_flags & MDB_FATAL_ERROR) {
2198 DPUTS("environment had fatal error, must shutdown!");
2201 if ((env->me_flags & MDB_RDONLY) && !(flags & MDB_RDONLY))
2204 /* Nested transactions: Max 1 child, write txns only, no writemap */
2205 if (parent->mt_child ||
2206 (flags & MDB_RDONLY) || (parent->mt_flags & MDB_TXN_RDONLY) ||
2207 (env->me_flags & MDB_WRITEMAP))
2211 tsize = sizeof(MDB_ntxn);
2213 size = tsize + env->me_maxdbs * (sizeof(MDB_db)+1);
2214 if (!(flags & MDB_RDONLY))
2215 size += env->me_maxdbs * sizeof(MDB_cursor *);
2217 if ((txn = calloc(1, size)) == NULL) {
2218 DPRINTF("calloc: %s", strerror(ErrCode()));
2221 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2222 if (flags & MDB_RDONLY) {
2223 txn->mt_flags |= MDB_TXN_RDONLY;
2224 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
2226 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2227 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
2233 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2234 if (!txn->mt_u.dirty_list ||
2235 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2237 free(txn->mt_u.dirty_list);
2241 txn->mt_txnid = parent->mt_txnid;
2242 txn->mt_toggle = parent->mt_toggle;
2243 txn->mt_dirty_room = parent->mt_dirty_room;
2244 txn->mt_u.dirty_list[0].mid = 0;
2245 txn->mt_spill_pgs = NULL;
2246 txn->mt_next_pgno = parent->mt_next_pgno;
2247 parent->mt_child = txn;
2248 txn->mt_parent = parent;
2249 txn->mt_numdbs = parent->mt_numdbs;
2250 txn->mt_flags = parent->mt_flags;
2251 txn->mt_dbxs = parent->mt_dbxs;
2252 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2253 /* Copy parent's mt_dbflags, but clear DB_NEW */
2254 for (i=0; i<txn->mt_numdbs; i++)
2255 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2257 ntxn = (MDB_ntxn *)txn;
2258 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2259 if (env->me_pghead) {
2260 size = MDB_IDL_SIZEOF(env->me_pghead);
2261 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2263 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2268 rc = mdb_cursor_shadow(parent, txn);
2270 mdb_txn_reset0(txn, "beginchild-fail");
2272 rc = mdb_txn_renew0(txn);
2278 DPRINTF("begin txn %zu%c %p on mdbenv %p, root page %zu",
2279 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2280 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
2286 /** Export or close DBI handles opened in this txn. */
2288 mdb_dbis_update(MDB_txn *txn, int keep)
2291 MDB_dbi n = txn->mt_numdbs;
2292 MDB_env *env = txn->mt_env;
2293 unsigned char *tdbflags = txn->mt_dbflags;
2295 for (i = n; --i >= 2;) {
2296 if (tdbflags[i] & DB_NEW) {
2298 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2300 char *ptr = env->me_dbxs[i].md_name.mv_data;
2301 env->me_dbxs[i].md_name.mv_data = NULL;
2302 env->me_dbxs[i].md_name.mv_size = 0;
2303 env->me_dbflags[i] = 0;
2308 if (keep && env->me_numdbs < n)
2312 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
2313 * May be called twice for readonly txns: First reset it, then abort.
2314 * @param[in] txn the transaction handle to reset
2315 * @param[in] act why the transaction is being reset
2318 mdb_txn_reset0(MDB_txn *txn, const char *act)
2320 MDB_env *env = txn->mt_env;
2322 /* Close any DBI handles opened in this txn */
2323 mdb_dbis_update(txn, 0);
2325 DPRINTF("%s txn %zu%c %p on mdbenv %p, root page %zu",
2326 act, txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2327 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
2329 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2330 if (txn->mt_u.reader) {
2331 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2332 if (!(env->me_flags & MDB_NOTLS))
2333 txn->mt_u.reader = NULL; /* txn does not own reader */
2335 txn->mt_numdbs = 0; /* close nothing if called again */
2336 txn->mt_dbxs = NULL; /* mark txn as reset */
2338 mdb_cursors_close(txn, 0);
2340 if (!(env->me_flags & MDB_WRITEMAP)) {
2341 mdb_dlist_free(txn);
2343 mdb_midl_free(env->me_pghead);
2345 if (txn->mt_parent) {
2346 txn->mt_parent->mt_child = NULL;
2347 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2348 mdb_midl_free(txn->mt_free_pgs);
2349 mdb_midl_free(txn->mt_spill_pgs);
2350 free(txn->mt_u.dirty_list);
2354 if (mdb_midl_shrink(&txn->mt_free_pgs))
2355 env->me_free_pgs = txn->mt_free_pgs;
2356 env->me_pghead = NULL;
2360 /* The writer mutex was locked in mdb_txn_begin. */
2361 UNLOCK_MUTEX_W(env);
2366 mdb_txn_reset(MDB_txn *txn)
2371 /* This call is only valid for read-only txns */
2372 if (!(txn->mt_flags & MDB_TXN_RDONLY))
2375 mdb_txn_reset0(txn, "reset");
2379 mdb_txn_abort(MDB_txn *txn)
2385 mdb_txn_abort(txn->mt_child);
2387 mdb_txn_reset0(txn, "abort");
2388 /* Free reader slot tied to this txn (if MDB_NOTLS && writable FS) */
2389 if ((txn->mt_flags & MDB_TXN_RDONLY) && txn->mt_u.reader)
2390 txn->mt_u.reader->mr_pid = 0;
2395 /** Save the freelist as of this transaction to the freeDB.
2396 * This changes the freelist. Keep trying until it stabilizes.
2399 mdb_freelist_save(MDB_txn *txn)
2401 /* env->me_pghead[] can grow and shrink during this call.
2402 * env->me_pglast and txn->mt_free_pgs[] can only grow.
2403 * Page numbers cannot disappear from txn->mt_free_pgs[].
2406 MDB_env *env = txn->mt_env;
2407 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
2408 txnid_t pglast = 0, head_id = 0;
2409 pgno_t freecnt = 0, *free_pgs, *mop;
2410 ssize_t head_room = 0, total_room = 0, mop_len;
2412 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
2414 if (env->me_pghead) {
2415 /* Make sure first page of freeDB is touched and on freelist */
2416 rc = mdb_page_search(&mc, NULL, MDB_PS_MODIFY);
2417 if (rc && rc != MDB_NOTFOUND)
2422 /* Come back here after each Put() in case freelist changed */
2425 /* If using records from freeDB which we have not yet
2426 * deleted, delete them and any we reserved for me_pghead.
2428 while (pglast < env->me_pglast) {
2429 rc = mdb_cursor_first(&mc, &key, NULL);
2432 pglast = head_id = *(txnid_t *)key.mv_data;
2433 total_room = head_room = 0;
2434 assert(pglast <= env->me_pglast);
2435 rc = mdb_cursor_del(&mc, 0);
2440 /* Save the IDL of pages freed by this txn, to a single record */
2441 if (freecnt < txn->mt_free_pgs[0]) {
2443 /* Make sure last page of freeDB is touched and on freelist */
2444 key.mv_size = MDB_MAXKEYSIZE+1;
2446 rc = mdb_page_search(&mc, &key, MDB_PS_MODIFY);
2447 if (rc && rc != MDB_NOTFOUND)
2450 free_pgs = txn->mt_free_pgs;
2451 /* Write to last page of freeDB */
2452 key.mv_size = sizeof(txn->mt_txnid);
2453 key.mv_data = &txn->mt_txnid;
2455 freecnt = free_pgs[0];
2456 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
2457 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2460 /* Retry if mt_free_pgs[] grew during the Put() */
2461 free_pgs = txn->mt_free_pgs;
2462 } while (freecnt < free_pgs[0]);
2463 mdb_midl_sort(free_pgs);
2464 memcpy(data.mv_data, free_pgs, data.mv_size);
2467 unsigned int i = free_pgs[0];
2468 DPRINTF("IDL write txn %zu root %zu num %u",
2469 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i);
2471 DPRINTF("IDL %zu", free_pgs[i]);
2477 mop = env->me_pghead;
2478 mop_len = mop ? mop[0] : 0;
2480 /* Reserve records for me_pghead[]. Split it if multi-page,
2481 * to avoid searching freeDB for a page range. Use keys in
2482 * range [1,me_pglast]: Smaller than txnid of oldest reader.
2484 if (total_room >= mop_len) {
2485 if (total_room == mop_len || --more < 0)
2487 } else if (head_room >= maxfree_1pg && head_id > 1) {
2488 /* Keep current record (overflow page), add a new one */
2492 /* (Re)write {key = head_id, IDL length = head_room} */
2493 total_room -= head_room;
2494 head_room = mop_len - total_room;
2495 if (head_room > maxfree_1pg && head_id > 1) {
2496 /* Overflow multi-page for part of me_pghead */
2497 head_room /= head_id; /* amortize page sizes */
2498 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
2499 } else if (head_room < 0) {
2500 /* Rare case, not bothering to delete this record */
2503 key.mv_size = sizeof(head_id);
2504 key.mv_data = &head_id;
2505 data.mv_size = (head_room + 1) * sizeof(pgno_t);
2506 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2509 *(MDB_ID *)data.mv_data = 0; /* IDL is initially empty */
2510 total_room += head_room;
2513 /* Fill in the reserved, touched me_pghead records */
2519 rc = mdb_cursor_first(&mc, &key, &data);
2520 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
2521 unsigned flags = MDB_CURRENT;
2522 txnid_t id = *(txnid_t *)key.mv_data;
2523 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
2526 assert(len >= 0 && id <= env->me_pglast);
2528 if (len > mop_len) {
2530 data.mv_size = (len + 1) * sizeof(MDB_ID);
2533 data.mv_data = mop -= len;
2536 rc = mdb_cursor_put(&mc, &key, &data, flags);
2538 if (rc || !(mop_len -= len))
2545 /** Flush dirty pages to the map, after clearing their dirty flag.
2548 mdb_page_flush(MDB_txn *txn)
2550 MDB_env *env = txn->mt_env;
2551 MDB_ID2L dl = txn->mt_u.dirty_list;
2552 unsigned psize = env->me_psize, j;
2553 int i, pagecount = dl[0].mid, rc;
2554 size_t size = 0, pos = 0;
2556 MDB_page *dp = NULL;
2560 struct iovec iov[MDB_COMMIT_PAGES];
2561 ssize_t wpos = 0, wsize = 0, wres;
2562 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
2567 if (env->me_flags & MDB_WRITEMAP) {
2568 /* Clear dirty flags */
2569 for (i = pagecount; i; i--) {
2571 /* Don't flush this page yet */
2572 if (dp->mp_flags & P_KEEP) {
2573 dp->mp_flags ^= P_KEEP;
2577 dp->mp_flags &= ~P_DIRTY;
2583 /* Write the pages */
2585 if (i <= pagecount) {
2587 /* Don't flush this page yet */
2588 if (dp->mp_flags & P_KEEP) {
2589 dp->mp_flags ^= P_KEEP;
2594 /* clear dirty flag */
2595 dp->mp_flags &= ~P_DIRTY;
2598 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
2603 /* Windows actually supports scatter/gather I/O, but only on
2604 * unbuffered file handles. Since we're relying on the OS page
2605 * cache for all our data, that's self-defeating. So we just
2606 * write pages one at a time. We use the ov structure to set
2607 * the write offset, to at least save the overhead of a Seek
2610 DPRINTF("committing page %zu", pgno);
2611 memset(&ov, 0, sizeof(ov));
2612 ov.Offset = pos & 0xffffffff;
2613 ov.OffsetHigh = pos >> 16 >> 16;
2614 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
2616 DPRINTF("WriteFile: %d", rc);
2620 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
2621 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
2623 /* Write previous page(s) */
2624 #ifdef MDB_USE_PWRITEV
2625 wres = pwritev(env->me_fd, iov, n, wpos);
2628 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
2630 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
2632 DPRINTF("lseek: %s", strerror(rc));
2635 wres = writev(env->me_fd, iov, n);
2638 if (wres != wsize) {
2641 DPRINTF("Write error: %s", strerror(rc));
2643 rc = EIO; /* TODO: Use which error code? */
2644 DPUTS("short write, filesystem full?");
2655 DPRINTF("committing page %zu", pgno);
2656 next_pos = pos + size;
2657 iov[n].iov_len = size;
2658 iov[n].iov_base = (char *)dp;
2665 for (i=1; i<=pagecount; i++) {
2667 /* This is a page we skipped above */
2670 dl[j].mid = dp->mp_pgno;
2673 mdb_dpage_free(env, dp);
2681 mdb_txn_commit(MDB_txn *txn)
2687 assert(txn != NULL);
2688 assert(txn->mt_env != NULL);
2690 if (txn->mt_child) {
2691 rc = mdb_txn_commit(txn->mt_child);
2692 txn->mt_child = NULL;
2699 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2700 mdb_dbis_update(txn, 1);
2701 txn->mt_numdbs = 2; /* so txn_abort() doesn't close any new handles */
2706 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
2707 DPUTS("error flag is set, can't commit");
2709 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
2714 if (txn->mt_parent) {
2715 MDB_txn *parent = txn->mt_parent;
2719 /* Append our free list to parent's */
2720 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
2723 mdb_midl_free(txn->mt_free_pgs);
2725 parent->mt_next_pgno = txn->mt_next_pgno;
2726 parent->mt_flags = txn->mt_flags;
2728 /* Merge our cursors into parent's and close them */
2729 mdb_cursors_close(txn, 1);
2731 /* Update parent's DB table. */
2732 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2733 parent->mt_numdbs = txn->mt_numdbs;
2734 parent->mt_dbflags[0] = txn->mt_dbflags[0];
2735 parent->mt_dbflags[1] = txn->mt_dbflags[1];
2736 for (i=2; i<txn->mt_numdbs; i++) {
2737 /* preserve parent's DB_NEW status */
2738 x = parent->mt_dbflags[i] & DB_NEW;
2739 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
2742 dst = parent->mt_u.dirty_list;
2743 src = txn->mt_u.dirty_list;
2744 /* Remove anything in our dirty list from parent's spill list */
2745 if (parent->mt_spill_pgs) {
2746 x = parent->mt_spill_pgs[0];
2748 /* zero out our dirty pages in parent spill list */
2749 for (i=1; i<=src[0].mid; i++) {
2750 if (src[i].mid < parent->mt_spill_pgs[x])
2752 if (src[i].mid > parent->mt_spill_pgs[x]) {
2758 parent->mt_spill_pgs[x] = 0;
2761 /* OK, we had a few hits, squash zeros from the spill list */
2762 if (len < parent->mt_spill_pgs[0]) {
2764 for (y=1; y<=parent->mt_spill_pgs[0]; y++) {
2765 if (parent->mt_spill_pgs[y]) {
2767 parent->mt_spill_pgs[x] = parent->mt_spill_pgs[y];
2772 parent->mt_spill_pgs[0] = len;
2775 /* Find len = length of merging our dirty list with parent's */
2777 dst[0].mid = 0; /* simplify loops */
2778 if (parent->mt_parent) {
2779 len = x + src[0].mid;
2780 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
2781 for (i = x; y && i; y--) {
2782 pgno_t yp = src[y].mid;
2783 while (yp < dst[i].mid)
2785 if (yp == dst[i].mid) {
2790 } else { /* Simplify the above for single-ancestor case */
2791 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
2793 /* Merge our dirty list with parent's */
2795 for (i = len; y; dst[i--] = src[y--]) {
2796 pgno_t yp = src[y].mid;
2797 while (yp < dst[x].mid)
2798 dst[i--] = dst[x--];
2799 if (yp == dst[x].mid)
2800 free(dst[x--].mptr);
2804 free(txn->mt_u.dirty_list);
2805 parent->mt_dirty_room = txn->mt_dirty_room;
2806 if (txn->mt_spill_pgs) {
2807 if (parent->mt_spill_pgs) {
2808 mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
2809 mdb_midl_free(txn->mt_spill_pgs);
2810 mdb_midl_sort(parent->mt_spill_pgs);
2812 parent->mt_spill_pgs = txn->mt_spill_pgs;
2816 parent->mt_child = NULL;
2817 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
2822 if (txn != env->me_txn) {
2823 DPUTS("attempt to commit unknown transaction");
2828 mdb_cursors_close(txn, 0);
2830 if (!txn->mt_u.dirty_list[0].mid && !(txn->mt_flags & MDB_TXN_DIRTY))
2833 DPRINTF("committing txn %zu %p on mdbenv %p, root page %zu",
2834 txn->mt_txnid, (void *)txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
2836 /* Update DB root pointers */
2837 if (txn->mt_numdbs > 2) {
2841 data.mv_size = sizeof(MDB_db);
2843 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
2844 for (i = 2; i < txn->mt_numdbs; i++) {
2845 if (txn->mt_dbflags[i] & DB_DIRTY) {
2846 data.mv_data = &txn->mt_dbs[i];
2847 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
2854 rc = mdb_freelist_save(txn);
2858 mdb_midl_free(env->me_pghead);
2859 env->me_pghead = NULL;
2860 if (mdb_midl_shrink(&txn->mt_free_pgs))
2861 env->me_free_pgs = txn->mt_free_pgs;
2867 if ((rc = mdb_page_flush(txn)) ||
2868 (rc = mdb_env_sync(env, 0)) ||
2869 (rc = mdb_env_write_meta(txn)))
2875 mdb_dbis_update(txn, 1);
2877 UNLOCK_MUTEX_W(env);
2887 /** Read the environment parameters of a DB environment before
2888 * mapping it into memory.
2889 * @param[in] env the environment handle
2890 * @param[out] meta address of where to store the meta information
2891 * @return 0 on success, non-zero on failure.
2894 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
2901 /* We don't know the page size yet, so use a minimum value.
2902 * Read both meta pages so we can use the latest one.
2905 for (i=off=0; i<2; i++, off = meta->mm_psize) {
2909 memset(&ov, 0, sizeof(ov));
2911 rc = ReadFile(env->me_fd,&pbuf,MDB_PAGESIZE,&len,&ov) ? (int)len : -1;
2912 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
2915 rc = pread(env->me_fd, &pbuf, MDB_PAGESIZE, off);
2917 if (rc != MDB_PAGESIZE) {
2918 if (rc == 0 && off == 0)
2920 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
2921 DPRINTF("read: %s", mdb_strerror(rc));
2925 p = (MDB_page *)&pbuf;
2927 if (!F_ISSET(p->mp_flags, P_META)) {
2928 DPRINTF("page %zu not a meta page", p->mp_pgno);
2933 if (m->mm_magic != MDB_MAGIC) {
2934 DPUTS("meta has invalid magic");
2938 if (m->mm_version != MDB_DATA_VERSION) {
2939 DPRINTF("database is version %u, expected version %u",
2940 m->mm_version, MDB_DATA_VERSION);
2941 return MDB_VERSION_MISMATCH;
2944 if (off == 0 || m->mm_txnid > meta->mm_txnid)
2950 /** Write the environment parameters of a freshly created DB environment.
2951 * @param[in] env the environment handle
2952 * @param[out] meta address of where to store the meta information
2953 * @return 0 on success, non-zero on failure.
2956 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
2964 memset(&ov, 0, sizeof(ov));
2965 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
2967 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
2970 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
2971 len = pwrite(fd, ptr, size, pos); \
2972 rc = (len >= 0); } while(0)
2975 DPUTS("writing new meta page");
2977 GET_PAGESIZE(psize);
2979 meta->mm_magic = MDB_MAGIC;
2980 meta->mm_version = MDB_DATA_VERSION;
2981 meta->mm_mapsize = env->me_mapsize;
2982 meta->mm_psize = psize;
2983 meta->mm_last_pg = 1;
2984 meta->mm_flags = env->me_flags & 0xffff;
2985 meta->mm_flags |= MDB_INTEGERKEY;
2986 meta->mm_dbs[0].md_root = P_INVALID;
2987 meta->mm_dbs[1].md_root = P_INVALID;
2989 p = calloc(2, psize);
2991 p->mp_flags = P_META;
2992 *(MDB_meta *)METADATA(p) = *meta;
2994 q = (MDB_page *)((char *)p + psize);
2996 q->mp_flags = P_META;
2997 *(MDB_meta *)METADATA(q) = *meta;
2999 DO_PWRITE(rc, env->me_fd, p, psize * 2, len, 0);
3002 else if ((unsigned) len == psize * 2)
3010 /** Update the environment info to commit a transaction.
3011 * @param[in] txn the transaction that's being committed
3012 * @return 0 on success, non-zero on failure.
3015 mdb_env_write_meta(MDB_txn *txn)
3018 MDB_meta meta, metab, *mp;
3020 int rc, len, toggle;
3029 assert(txn != NULL);
3030 assert(txn->mt_env != NULL);
3032 toggle = !txn->mt_toggle;
3033 DPRINTF("writing meta page %d for root page %zu",
3034 toggle, txn->mt_dbs[MAIN_DBI].md_root);
3037 mp = env->me_metas[toggle];
3039 if (env->me_flags & MDB_WRITEMAP) {
3040 /* Persist any increases of mapsize config */
3041 if (env->me_mapsize > mp->mm_mapsize)
3042 mp->mm_mapsize = env->me_mapsize;
3043 mp->mm_dbs[0] = txn->mt_dbs[0];
3044 mp->mm_dbs[1] = txn->mt_dbs[1];
3045 mp->mm_last_pg = txn->mt_next_pgno - 1;
3046 mp->mm_txnid = txn->mt_txnid;
3047 if (!(env->me_flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3048 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3051 ptr += env->me_psize;
3052 if (MDB_MSYNC(ptr, env->me_psize, rc)) {
3059 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
3060 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
3062 ptr = (char *)&meta;
3063 if (env->me_mapsize > mp->mm_mapsize) {
3064 /* Persist any increases of mapsize config */
3065 meta.mm_mapsize = env->me_mapsize;
3066 off = offsetof(MDB_meta, mm_mapsize);
3068 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
3070 len = sizeof(MDB_meta) - off;
3073 meta.mm_dbs[0] = txn->mt_dbs[0];
3074 meta.mm_dbs[1] = txn->mt_dbs[1];
3075 meta.mm_last_pg = txn->mt_next_pgno - 1;
3076 meta.mm_txnid = txn->mt_txnid;
3079 off += env->me_psize;
3082 /* Write to the SYNC fd */
3083 mfd = env->me_flags & (MDB_NOSYNC|MDB_NOMETASYNC) ?
3084 env->me_fd : env->me_mfd;
3087 memset(&ov, 0, sizeof(ov));
3089 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3093 rc = pwrite(mfd, ptr, len, off);
3096 rc = rc < 0 ? ErrCode() : EIO;
3097 DPUTS("write failed, disk error?");
3098 /* On a failure, the pagecache still contains the new data.
3099 * Write some old data back, to prevent it from being used.
3100 * Use the non-SYNC fd; we know it will fail anyway.
3102 meta.mm_last_pg = metab.mm_last_pg;
3103 meta.mm_txnid = metab.mm_txnid;
3105 memset(&ov, 0, sizeof(ov));
3107 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3109 r2 = pwrite(env->me_fd, ptr, len, off);
3112 env->me_flags |= MDB_FATAL_ERROR;
3116 /* Memory ordering issues are irrelevant; since the entire writer
3117 * is wrapped by wmutex, all of these changes will become visible
3118 * after the wmutex is unlocked. Since the DB is multi-version,
3119 * readers will get consistent data regardless of how fresh or
3120 * how stale their view of these values is.
3122 env->me_txns->mti_txnid = txn->mt_txnid;
3127 /** Check both meta pages to see which one is newer.
3128 * @param[in] env the environment handle
3129 * @return meta toggle (0 or 1).
3132 mdb_env_pick_meta(const MDB_env *env)
3134 return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
3138 mdb_env_create(MDB_env **env)
3142 e = calloc(1, sizeof(MDB_env));
3146 e->me_maxreaders = DEFAULT_READERS;
3147 e->me_maxdbs = e->me_numdbs = 2;
3148 e->me_fd = INVALID_HANDLE_VALUE;
3149 e->me_lfd = INVALID_HANDLE_VALUE;
3150 e->me_mfd = INVALID_HANDLE_VALUE;
3151 #ifdef MDB_USE_POSIX_SEM
3152 e->me_rmutex = SEM_FAILED;
3153 e->me_wmutex = SEM_FAILED;
3155 e->me_pid = getpid();
3156 VGMEMP_CREATE(e,0,0);
3162 mdb_env_set_mapsize(MDB_env *env, size_t size)
3166 env->me_mapsize = size;
3168 env->me_maxpg = env->me_mapsize / env->me_psize;
3173 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
3177 env->me_maxdbs = dbs + 2; /* Named databases + main and free DB */
3182 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
3184 if (env->me_map || readers < 1)
3186 env->me_maxreaders = readers;
3191 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
3193 if (!env || !readers)
3195 *readers = env->me_maxreaders;
3199 /** Further setup required for opening an MDB environment
3202 mdb_env_open2(MDB_env *env)
3204 unsigned int flags = env->me_flags;
3212 memset(&meta, 0, sizeof(meta));
3214 if ((i = mdb_env_read_header(env, &meta)) != 0) {
3217 DPUTS("new mdbenv");
3221 /* Was a mapsize configured? */
3222 if (!env->me_mapsize) {
3223 /* If this is a new environment, take the default,
3224 * else use the size recorded in the existing env.
3226 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
3227 } else if (env->me_mapsize < meta.mm_mapsize) {
3228 /* If the configured size is smaller, make sure it's
3229 * still big enough. Silently round up to minimum if not.
3231 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
3232 if (env->me_mapsize < minsize)
3233 env->me_mapsize = minsize;
3240 LONG sizelo, sizehi;
3241 sizelo = env->me_mapsize & 0xffffffff;
3242 sizehi = env->me_mapsize >> 16 >> 16; /* only needed on Win64 */
3244 /* See if we should use QueryLimited */
3246 if ((rc & 0xff) > 5)
3247 env->me_pidquery = PROCESS_QUERY_LIMITED_INFORMATION;
3249 env->me_pidquery = PROCESS_QUERY_INFORMATION;
3251 /* Windows won't create mappings for zero length files.
3252 * Just allocate the maxsize right now.
3255 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3256 || !SetEndOfFile(env->me_fd)
3257 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3260 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3261 PAGE_READWRITE : PAGE_READONLY,
3262 sizehi, sizelo, NULL);
3265 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3266 FILE_MAP_WRITE : FILE_MAP_READ,
3267 0, 0, env->me_mapsize, meta.mm_address);
3268 rc = env->me_map ? 0 : ErrCode();
3276 if (flags & MDB_WRITEMAP) {
3278 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3281 env->me_map = mmap(meta.mm_address, env->me_mapsize, prot, i,
3283 if (env->me_map == MAP_FAILED) {
3287 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3289 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3291 #ifdef POSIX_MADV_RANDOM
3292 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3293 #endif /* POSIX_MADV_RANDOM */
3294 #endif /* MADV_RANDOM */
3298 if (flags & MDB_FIXEDMAP)
3299 meta.mm_address = env->me_map;
3300 i = mdb_env_init_meta(env, &meta);
3301 if (i != MDB_SUCCESS) {
3304 } else if (meta.mm_address && env->me_map != meta.mm_address) {
3305 /* Can happen because the address argument to mmap() is just a
3306 * hint. mmap() can pick another, e.g. if the range is in use.
3307 * The MAP_FIXED flag would prevent that, but then mmap could
3308 * instead unmap existing pages to make room for the new map.
3310 return EBUSY; /* TODO: Make a new MDB_* error code? */
3312 env->me_psize = meta.mm_psize;
3313 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
3314 env->me_nodemax = (env->me_psize - PAGEHDRSZ) / MDB_MINKEYS;
3316 env->me_maxpg = env->me_mapsize / env->me_psize;
3318 p = (MDB_page *)env->me_map;
3319 env->me_metas[0] = METADATA(p);
3320 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
3324 int toggle = mdb_env_pick_meta(env);
3325 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
3327 DPRINTF("opened database version %u, pagesize %u",
3328 env->me_metas[0]->mm_version, env->me_psize);
3329 DPRINTF("using meta page %d", toggle);
3330 DPRINTF("depth: %u", db->md_depth);
3331 DPRINTF("entries: %zu", db->md_entries);
3332 DPRINTF("branch pages: %zu", db->md_branch_pages);
3333 DPRINTF("leaf pages: %zu", db->md_leaf_pages);
3334 DPRINTF("overflow pages: %zu", db->md_overflow_pages);
3335 DPRINTF("root: %zu", db->md_root);
3343 /** Release a reader thread's slot in the reader lock table.
3344 * This function is called automatically when a thread exits.
3345 * @param[in] ptr This points to the slot in the reader lock table.
3348 mdb_env_reader_dest(void *ptr)
3350 MDB_reader *reader = ptr;
3356 /** Junk for arranging thread-specific callbacks on Windows. This is
3357 * necessarily platform and compiler-specific. Windows supports up
3358 * to 1088 keys. Let's assume nobody opens more than 64 environments
3359 * in a single process, for now. They can override this if needed.
3361 #ifndef MAX_TLS_KEYS
3362 #define MAX_TLS_KEYS 64
3364 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
3365 static int mdb_tls_nkeys;
3367 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
3371 case DLL_PROCESS_ATTACH: break;
3372 case DLL_THREAD_ATTACH: break;
3373 case DLL_THREAD_DETACH:
3374 for (i=0; i<mdb_tls_nkeys; i++) {
3375 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
3376 mdb_env_reader_dest(r);
3379 case DLL_PROCESS_DETACH: break;
3384 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3386 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3390 /* Force some symbol references.
3391 * _tls_used forces the linker to create the TLS directory if not already done
3392 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
3394 #pragma comment(linker, "/INCLUDE:_tls_used")
3395 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
3396 #pragma const_seg(".CRT$XLB")
3397 extern const PIMAGE_TLS_CALLBACK mdb_tls_callback;
3398 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3401 #pragma comment(linker, "/INCLUDE:__tls_used")
3402 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
3403 #pragma data_seg(".CRT$XLB")
3404 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3406 #endif /* WIN 32/64 */
3407 #endif /* !__GNUC__ */
3410 /** Downgrade the exclusive lock on the region back to shared */
3412 mdb_env_share_locks(MDB_env *env, int *excl)
3414 int rc = 0, toggle = mdb_env_pick_meta(env);
3416 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
3421 /* First acquire a shared lock. The Unlock will
3422 * then release the existing exclusive lock.
3424 memset(&ov, 0, sizeof(ov));
3425 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3428 UnlockFile(env->me_lfd, 0, 0, 1, 0);
3434 struct flock lock_info;
3435 /* The shared lock replaces the existing lock */
3436 memset((void *)&lock_info, 0, sizeof(lock_info));
3437 lock_info.l_type = F_RDLCK;
3438 lock_info.l_whence = SEEK_SET;
3439 lock_info.l_start = 0;
3440 lock_info.l_len = 1;
3441 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3442 (rc = ErrCode()) == EINTR) ;
3443 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
3450 /** Try to get exlusive lock, otherwise shared.
3451 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
3454 mdb_env_excl_lock(MDB_env *env, int *excl)
3458 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
3462 memset(&ov, 0, sizeof(ov));
3463 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3470 struct flock lock_info;
3471 memset((void *)&lock_info, 0, sizeof(lock_info));
3472 lock_info.l_type = F_WRLCK;
3473 lock_info.l_whence = SEEK_SET;
3474 lock_info.l_start = 0;
3475 lock_info.l_len = 1;
3476 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3477 (rc = ErrCode()) == EINTR) ;
3481 # ifdef MDB_USE_POSIX_SEM
3482 if (*excl < 0) /* always true when !MDB_USE_POSIX_SEM */
3485 lock_info.l_type = F_RDLCK;
3486 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
3487 (rc = ErrCode()) == EINTR) ;
3495 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
3497 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
3499 * @(#) $Revision: 5.1 $
3500 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
3501 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
3503 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
3507 * Please do not copyright this code. This code is in the public domain.
3509 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
3510 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
3511 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
3512 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
3513 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
3514 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
3515 * PERFORMANCE OF THIS SOFTWARE.
3518 * chongo <Landon Curt Noll> /\oo/\
3519 * http://www.isthe.com/chongo/
3521 * Share and Enjoy! :-)
3524 typedef unsigned long long mdb_hash_t;
3525 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
3527 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
3528 * @param[in] val value to hash
3529 * @param[in] hval initial value for hash
3530 * @return 64 bit hash
3532 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
3533 * hval arg on the first call.
3536 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
3538 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
3539 unsigned char *end = s + val->mv_size;
3541 * FNV-1a hash each octet of the string
3544 /* xor the bottom with the current octet */
3545 hval ^= (mdb_hash_t)*s++;
3547 /* multiply by the 64 bit FNV magic prime mod 2^64 */
3548 hval += (hval << 1) + (hval << 4) + (hval << 5) +
3549 (hval << 7) + (hval << 8) + (hval << 40);
3551 /* return our new hash value */
3555 /** Hash the string and output the encoded hash.
3556 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
3557 * very short name limits. We don't care about the encoding being reversible,
3558 * we just want to preserve as many bits of the input as possible in a
3559 * small printable string.
3560 * @param[in] str string to hash
3561 * @param[out] encbuf an array of 11 chars to hold the hash
3563 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
3566 mdb_pack85(unsigned long l, char *out)
3570 for (i=0; i<5; i++) {
3571 *out++ = mdb_a85[l % 85];
3577 mdb_hash_enc(MDB_val *val, char *encbuf)
3579 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
3580 unsigned long *l = (unsigned long *)&h;
3582 mdb_pack85(l[0], encbuf);
3583 mdb_pack85(l[1], encbuf+5);
3588 /** Open and/or initialize the lock region for the environment.
3589 * @param[in] env The MDB environment.
3590 * @param[in] lpath The pathname of the file used for the lock region.
3591 * @param[in] mode The Unix permissions for the file, if we create it.
3592 * @param[out] excl Resulting file lock type: -1 none, 0 shared, 1 exclusive
3593 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
3594 * @return 0 on success, non-zero on failure.
3597 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
3600 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
3602 # define MDB_ERRCODE_ROFS EROFS
3603 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
3604 # define MDB_CLOEXEC O_CLOEXEC
3607 # define MDB_CLOEXEC 0
3614 env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
3615 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
3616 FILE_ATTRIBUTE_NORMAL, NULL);
3618 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
3620 if (env->me_lfd == INVALID_HANDLE_VALUE) {
3622 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
3627 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
3628 /* Lose record locks when exec*() */
3629 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
3630 fcntl(env->me_lfd, F_SETFD, fdflags);
3633 if (!(env->me_flags & MDB_NOTLS)) {
3634 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
3637 env->me_flags |= MDB_ENV_TXKEY;
3639 /* Windows TLS callbacks need help finding their TLS info. */
3640 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
3644 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
3648 /* Try to get exclusive lock. If we succeed, then
3649 * nobody is using the lock region and we should initialize it.
3651 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
3654 size = GetFileSize(env->me_lfd, NULL);
3656 size = lseek(env->me_lfd, 0, SEEK_END);
3657 if (size == -1) goto fail_errno;
3659 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
3660 if (size < rsize && *excl > 0) {
3662 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != rsize
3663 || !SetEndOfFile(env->me_lfd))
3666 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
3670 size = rsize - sizeof(MDB_txninfo);
3671 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
3676 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
3678 if (!mh) goto fail_errno;
3679 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
3681 if (!env->me_txns) goto fail_errno;
3683 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
3685 if (m == MAP_FAILED) goto fail_errno;
3691 BY_HANDLE_FILE_INFORMATION stbuf;
3700 if (!mdb_sec_inited) {
3701 InitializeSecurityDescriptor(&mdb_null_sd,
3702 SECURITY_DESCRIPTOR_REVISION);
3703 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
3704 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
3705 mdb_all_sa.bInheritHandle = FALSE;
3706 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
3709 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
3710 idbuf.volume = stbuf.dwVolumeSerialNumber;
3711 idbuf.nhigh = stbuf.nFileIndexHigh;
3712 idbuf.nlow = stbuf.nFileIndexLow;
3713 val.mv_data = &idbuf;
3714 val.mv_size = sizeof(idbuf);
3715 mdb_hash_enc(&val, encbuf);
3716 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
3717 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
3718 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
3719 if (!env->me_rmutex) goto fail_errno;
3720 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
3721 if (!env->me_wmutex) goto fail_errno;
3722 #elif defined(MDB_USE_POSIX_SEM)
3731 #if defined(__NetBSD__)
3732 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
3734 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
3735 idbuf.dev = stbuf.st_dev;
3736 idbuf.ino = stbuf.st_ino;
3737 val.mv_data = &idbuf;
3738 val.mv_size = sizeof(idbuf);
3739 mdb_hash_enc(&val, encbuf);
3740 #ifdef MDB_SHORT_SEMNAMES
3741 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
3743 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
3744 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
3745 /* Clean up after a previous run, if needed: Try to
3746 * remove both semaphores before doing anything else.
3748 sem_unlink(env->me_txns->mti_rmname);
3749 sem_unlink(env->me_txns->mti_wmname);
3750 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
3751 O_CREAT|O_EXCL, mode, 1);
3752 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3753 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
3754 O_CREAT|O_EXCL, mode, 1);
3755 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3756 #else /* MDB_USE_POSIX_SEM */
3757 pthread_mutexattr_t mattr;
3759 if ((rc = pthread_mutexattr_init(&mattr))
3760 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
3761 || (rc = pthread_mutex_init(&env->me_txns->mti_mutex, &mattr))
3762 || (rc = pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr)))
3764 pthread_mutexattr_destroy(&mattr);
3765 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
3767 env->me_txns->mti_version = MDB_LOCK_VERSION;
3768 env->me_txns->mti_magic = MDB_MAGIC;
3769 env->me_txns->mti_txnid = 0;
3770 env->me_txns->mti_numreaders = 0;
3773 if (env->me_txns->mti_magic != MDB_MAGIC) {
3774 DPUTS("lock region has invalid magic");
3778 if (env->me_txns->mti_version != MDB_LOCK_VERSION) {
3779 DPRINTF("lock region is version %u, expected version %u",
3780 env->me_txns->mti_version, MDB_LOCK_VERSION);
3781 rc = MDB_VERSION_MISMATCH;
3785 if (rc && rc != EACCES && rc != EAGAIN) {
3789 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
3790 if (!env->me_rmutex) goto fail_errno;
3791 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
3792 if (!env->me_wmutex) goto fail_errno;
3793 #elif defined(MDB_USE_POSIX_SEM)
3794 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
3795 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3796 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
3797 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3808 /** The name of the lock file in the DB environment */
3809 #define LOCKNAME "/lock.mdb"
3810 /** The name of the data file in the DB environment */
3811 #define DATANAME "/data.mdb"
3812 /** The suffix of the lock file when no subdir is used */
3813 #define LOCKSUFF "-lock"
3814 /** Only a subset of the @ref mdb_env flags can be changed
3815 * at runtime. Changing other flags requires closing the
3816 * environment and re-opening it with the new flags.
3818 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC)
3819 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY|MDB_WRITEMAP|MDB_NOTLS)
3822 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
3824 int oflags, rc, len, excl = -1;
3825 char *lpath, *dpath;
3827 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
3831 if (flags & MDB_NOSUBDIR) {
3832 rc = len + sizeof(LOCKSUFF) + len + 1;
3834 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
3839 if (flags & MDB_NOSUBDIR) {
3840 dpath = lpath + len + sizeof(LOCKSUFF);
3841 sprintf(lpath, "%s" LOCKSUFF, path);
3842 strcpy(dpath, path);
3844 dpath = lpath + len + sizeof(LOCKNAME);
3845 sprintf(lpath, "%s" LOCKNAME, path);
3846 sprintf(dpath, "%s" DATANAME, path);
3850 flags |= env->me_flags;
3851 if (flags & MDB_RDONLY) {
3852 /* silently ignore WRITEMAP when we're only getting read access */
3853 flags &= ~MDB_WRITEMAP;
3855 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
3856 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
3859 env->me_flags = flags |= MDB_ENV_ACTIVE;
3863 env->me_path = strdup(path);
3864 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
3865 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
3866 if (!(env->me_dbxs && env->me_path && env->me_dbflags)) {
3871 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
3876 if (F_ISSET(flags, MDB_RDONLY)) {
3877 oflags = GENERIC_READ;
3878 len = OPEN_EXISTING;
3880 oflags = GENERIC_READ|GENERIC_WRITE;
3883 mode = FILE_ATTRIBUTE_NORMAL;
3884 env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
3885 NULL, len, mode, NULL);
3887 if (F_ISSET(flags, MDB_RDONLY))
3890 oflags = O_RDWR | O_CREAT;
3892 env->me_fd = open(dpath, oflags, mode);
3894 if (env->me_fd == INVALID_HANDLE_VALUE) {
3899 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
3900 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
3901 env->me_mfd = env->me_fd;
3903 /* Synchronous fd for meta writes. Needed even with
3904 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
3907 env->me_mfd = CreateFile(dpath, oflags,
3908 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
3909 mode | FILE_FLAG_WRITE_THROUGH, NULL);
3911 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
3913 if (env->me_mfd == INVALID_HANDLE_VALUE) {
3918 DPRINTF("opened dbenv %p", (void *) env);
3920 rc = mdb_env_share_locks(env, &excl);
3926 mdb_env_close0(env, excl);
3932 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
3934 mdb_env_close0(MDB_env *env, int excl)
3938 if (!(env->me_flags & MDB_ENV_ACTIVE))
3941 /* Doing this here since me_dbxs may not exist during mdb_env_close */
3942 for (i = env->me_maxdbs; --i > MAIN_DBI; )
3943 free(env->me_dbxs[i].md_name.mv_data);
3945 free(env->me_dbflags);
3948 free(env->me_dirty_list);
3949 mdb_midl_free(env->me_free_pgs);
3951 if (env->me_flags & MDB_ENV_TXKEY) {
3952 pthread_key_delete(env->me_txkey);
3954 /* Delete our key from the global list */
3955 for (i=0; i<mdb_tls_nkeys; i++)
3956 if (mdb_tls_keys[i] == env->me_txkey) {
3957 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
3965 munmap(env->me_map, env->me_mapsize);
3967 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
3968 (void) close(env->me_mfd);
3969 if (env->me_fd != INVALID_HANDLE_VALUE)
3970 (void) close(env->me_fd);
3972 pid_t pid = env->me_pid;
3973 /* Clearing readers is done in this function because
3974 * me_txkey with its destructor must be disabled first.
3976 for (i = env->me_numreaders; --i >= 0; )
3977 if (env->me_txns->mti_readers[i].mr_pid == pid)
3978 env->me_txns->mti_readers[i].mr_pid = 0;
3980 if (env->me_rmutex) {
3981 CloseHandle(env->me_rmutex);
3982 if (env->me_wmutex) CloseHandle(env->me_wmutex);
3984 /* Windows automatically destroys the mutexes when
3985 * the last handle closes.
3987 #elif defined(MDB_USE_POSIX_SEM)
3988 if (env->me_rmutex != SEM_FAILED) {
3989 sem_close(env->me_rmutex);
3990 if (env->me_wmutex != SEM_FAILED)
3991 sem_close(env->me_wmutex);
3992 /* If we have the filelock: If we are the
3993 * only remaining user, clean up semaphores.
3996 mdb_env_excl_lock(env, &excl);
3998 sem_unlink(env->me_txns->mti_rmname);
3999 sem_unlink(env->me_txns->mti_wmname);
4003 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
4005 if (env->me_lfd != INVALID_HANDLE_VALUE) {
4008 /* Unlock the lockfile. Windows would have unlocked it
4009 * after closing anyway, but not necessarily at once.
4011 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4014 (void) close(env->me_lfd);
4017 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
4021 mdb_env_copyfd(MDB_env *env, HANDLE fd)
4023 MDB_txn *txn = NULL;
4029 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
4033 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
4036 /* Do the lock/unlock of the reader mutex before starting the
4037 * write txn. Otherwise other read txns could block writers.
4039 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
4044 /* We must start the actual read txn after blocking writers */
4045 mdb_txn_reset0(txn, "reset-stage1");
4047 /* Temporarily block writers until we snapshot the meta pages */
4050 rc = mdb_txn_renew0(txn);
4052 UNLOCK_MUTEX_W(env);
4057 wsize = env->me_psize * 2;
4061 DO_WRITE(rc, fd, ptr, w2, len);
4065 } else if (len > 0) {
4071 /* Non-blocking or async handles are not supported */
4077 UNLOCK_MUTEX_W(env);
4082 wsize = txn->mt_next_pgno * env->me_psize - wsize;
4084 if (wsize > MAX_WRITE)
4088 DO_WRITE(rc, fd, ptr, w2, len);
4092 } else if (len > 0) {
4109 mdb_env_copy(MDB_env *env, const char *path)
4113 HANDLE newfd = INVALID_HANDLE_VALUE;
4115 if (env->me_flags & MDB_NOSUBDIR) {
4116 lpath = (char *)path;
4119 len += sizeof(DATANAME);
4120 lpath = malloc(len);
4123 sprintf(lpath, "%s" DATANAME, path);
4126 /* The destination path must exist, but the destination file must not.
4127 * We don't want the OS to cache the writes, since the source data is
4128 * already in the OS cache.
4131 newfd = CreateFile(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
4132 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
4134 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL
4140 if (newfd == INVALID_HANDLE_VALUE) {
4145 #ifdef F_NOCACHE /* __APPLE__ */
4146 rc = fcntl(newfd, F_NOCACHE, 1);
4153 rc = mdb_env_copyfd(env, newfd);
4156 if (!(env->me_flags & MDB_NOSUBDIR))
4158 if (newfd != INVALID_HANDLE_VALUE)
4159 if (close(newfd) < 0 && rc == MDB_SUCCESS)
4166 mdb_env_close(MDB_env *env)
4173 VGMEMP_DESTROY(env);
4174 while ((dp = env->me_dpages) != NULL) {
4175 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
4176 env->me_dpages = dp->mp_next;
4180 mdb_env_close0(env, 0);
4184 /** Compare two items pointing at aligned size_t's */
4186 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
4188 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
4189 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
4192 /** Compare two items pointing at aligned int's */
4194 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
4196 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
4197 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
4200 /** Compare two items pointing at ints of unknown alignment.
4201 * Nodes and keys are guaranteed to be 2-byte aligned.
4204 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
4206 #if BYTE_ORDER == LITTLE_ENDIAN
4207 unsigned short *u, *c;
4210 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4211 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
4214 } while(!x && u > (unsigned short *)a->mv_data);
4217 return memcmp(a->mv_data, b->mv_data, a->mv_size);
4221 /** Compare two items lexically */
4223 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
4230 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4236 diff = memcmp(a->mv_data, b->mv_data, len);
4237 return diff ? diff : len_diff<0 ? -1 : len_diff;
4240 /** Compare two items in reverse byte order */
4242 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
4244 const unsigned char *p1, *p2, *p1_lim;
4248 p1_lim = (const unsigned char *)a->mv_data;
4249 p1 = (const unsigned char *)a->mv_data + a->mv_size;
4250 p2 = (const unsigned char *)b->mv_data + b->mv_size;
4252 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4258 while (p1 > p1_lim) {
4259 diff = *--p1 - *--p2;
4263 return len_diff<0 ? -1 : len_diff;
4266 /** Search for key within a page, using binary search.
4267 * Returns the smallest entry larger or equal to the key.
4268 * If exactp is non-null, stores whether the found entry was an exact match
4269 * in *exactp (1 or 0).
4270 * Updates the cursor index with the index of the found entry.
4271 * If no entry larger or equal to the key is found, returns NULL.
4274 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
4276 unsigned int i = 0, nkeys;
4279 MDB_page *mp = mc->mc_pg[mc->mc_top];
4280 MDB_node *node = NULL;
4285 nkeys = NUMKEYS(mp);
4290 COPY_PGNO(pgno, mp->mp_pgno);
4291 DPRINTF("searching %u keys in %s %spage %zu",
4292 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
4299 low = IS_LEAF(mp) ? 0 : 1;
4301 cmp = mc->mc_dbx->md_cmp;
4303 /* Branch pages have no data, so if using integer keys,
4304 * alignment is guaranteed. Use faster mdb_cmp_int.
4306 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
4307 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
4314 nodekey.mv_size = mc->mc_db->md_pad;
4315 node = NODEPTR(mp, 0); /* fake */
4316 while (low <= high) {
4317 i = (low + high) >> 1;
4318 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
4319 rc = cmp(key, &nodekey);
4320 DPRINTF("found leaf index %u [%s], rc = %i",
4321 i, DKEY(&nodekey), rc);
4330 while (low <= high) {
4331 i = (low + high) >> 1;
4333 node = NODEPTR(mp, i);
4334 nodekey.mv_size = NODEKSZ(node);
4335 nodekey.mv_data = NODEKEY(node);
4337 rc = cmp(key, &nodekey);
4340 DPRINTF("found leaf index %u [%s], rc = %i",
4341 i, DKEY(&nodekey), rc);
4343 DPRINTF("found branch index %u [%s -> %zu], rc = %i",
4344 i, DKEY(&nodekey), NODEPGNO(node), rc);
4355 if (rc > 0) { /* Found entry is less than the key. */
4356 i++; /* Skip to get the smallest entry larger than key. */
4358 node = NODEPTR(mp, i);
4361 *exactp = (rc == 0);
4362 /* store the key index */
4363 mc->mc_ki[mc->mc_top] = i;
4365 /* There is no entry larger or equal to the key. */
4368 /* nodeptr is fake for LEAF2 */
4374 mdb_cursor_adjust(MDB_cursor *mc, func)
4378 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4379 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
4386 /** Pop a page off the top of the cursor's stack. */
4388 mdb_cursor_pop(MDB_cursor *mc)
4391 #ifndef MDB_DEBUG_SKIP
4392 MDB_page *top = mc->mc_pg[mc->mc_top];
4398 DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
4399 mc->mc_dbi, (void *) mc);
4403 /** Push a page onto the top of the cursor's stack. */
4405 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
4407 DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
4408 mc->mc_dbi, (void *) mc);
4410 if (mc->mc_snum >= CURSOR_STACK) {
4411 assert(mc->mc_snum < CURSOR_STACK);
4412 return MDB_CURSOR_FULL;
4415 mc->mc_top = mc->mc_snum++;
4416 mc->mc_pg[mc->mc_top] = mp;
4417 mc->mc_ki[mc->mc_top] = 0;
4422 /** Find the address of the page corresponding to a given page number.
4423 * @param[in] txn the transaction for this access.
4424 * @param[in] pgno the page number for the page to retrieve.
4425 * @param[out] ret address of a pointer where the page's address will be stored.
4426 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
4427 * @return 0 on success, non-zero on failure.
4430 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
4435 if (!((txn->mt_flags & MDB_TXN_RDONLY) |
4436 (txn->mt_env->me_flags & MDB_WRITEMAP)))
4441 MDB_ID2L dl = tx2->mt_u.dirty_list;
4443 /* Spilled pages were dirtied in this txn and flushed
4444 * because the dirty list got full. Bring this page
4445 * back in from the map (but don't unspill it here,
4446 * leave that unless page_touch happens again).
4448 if (tx2->mt_spill_pgs) {
4449 x = mdb_midl_search(tx2->mt_spill_pgs, pgno);
4450 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pgno) {
4451 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
4456 unsigned x = mdb_mid2l_search(dl, pgno);
4457 if (x <= dl[0].mid && dl[x].mid == pgno) {
4463 } while ((tx2 = tx2->mt_parent) != NULL);
4466 if (pgno < txn->mt_next_pgno) {
4468 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
4470 DPRINTF("page %zu not found", pgno);
4472 return MDB_PAGE_NOTFOUND;
4482 /** Search for the page a given key should be in.
4483 * Pushes parent pages on the cursor stack. This function continues a
4484 * search on a cursor that has already been initialized. (Usually by
4485 * #mdb_page_search() but also by #mdb_node_move().)
4486 * @param[in,out] mc the cursor for this operation.
4487 * @param[in] key the key to search for. If NULL, search for the lowest
4488 * page. (This is used by #mdb_cursor_first().)
4489 * @param[in] modify If true, visited pages are updated with new page numbers.
4490 * @return 0 on success, non-zero on failure.
4493 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
4495 MDB_page *mp = mc->mc_pg[mc->mc_top];
4500 while (IS_BRANCH(mp)) {
4504 DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
4505 assert(NUMKEYS(mp) > 1);
4506 DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
4508 if (key == NULL) /* Initialize cursor to first page. */
4510 else if (key->mv_size > MDB_MAXKEYSIZE && key->mv_data == NULL) {
4511 /* cursor to last page */
4515 node = mdb_node_search(mc, key, &exact);
4517 i = NUMKEYS(mp) - 1;
4519 i = mc->mc_ki[mc->mc_top];
4528 DPRINTF("following index %u for key [%s]",
4530 assert(i < NUMKEYS(mp));
4531 node = NODEPTR(mp, i);
4533 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4536 mc->mc_ki[mc->mc_top] = i;
4537 if ((rc = mdb_cursor_push(mc, mp)))
4541 if ((rc = mdb_page_touch(mc)) != 0)
4543 mp = mc->mc_pg[mc->mc_top];
4548 DPRINTF("internal error, index points to a %02X page!?",
4550 return MDB_CORRUPTED;
4553 DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
4554 key ? DKEY(key) : NULL);
4555 mc->mc_flags |= C_INITIALIZED;
4556 mc->mc_flags &= ~C_EOF;
4561 /** Search for the lowest key under the current branch page.
4562 * This just bypasses a NUMKEYS check in the current page
4563 * before calling mdb_page_search_root(), because the callers
4564 * are all in situations where the current page is known to
4568 mdb_page_search_lowest(MDB_cursor *mc)
4570 MDB_page *mp = mc->mc_pg[mc->mc_top];
4571 MDB_node *node = NODEPTR(mp, 0);
4574 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4577 mc->mc_ki[mc->mc_top] = 0;
4578 if ((rc = mdb_cursor_push(mc, mp)))
4580 return mdb_page_search_root(mc, NULL, 0);
4583 /** Search for the page a given key should be in.
4584 * Pushes parent pages on the cursor stack. This function just sets up
4585 * the search; it finds the root page for \b mc's database and sets this
4586 * as the root of the cursor's stack. Then #mdb_page_search_root() is
4587 * called to complete the search.
4588 * @param[in,out] mc the cursor for this operation.
4589 * @param[in] key the key to search for. If NULL, search for the lowest
4590 * page. (This is used by #mdb_cursor_first().)
4591 * @param[in] flags If MDB_PS_MODIFY set, visited pages are updated with new page numbers.
4592 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
4593 * @return 0 on success, non-zero on failure.
4596 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
4601 /* Make sure the txn is still viable, then find the root from
4602 * the txn's db table.
4604 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
4605 DPUTS("transaction has failed, must abort");
4608 /* Make sure we're using an up-to-date root */
4609 if (mc->mc_dbi > MAIN_DBI) {
4610 if ((*mc->mc_dbflag & DB_STALE) ||
4611 ((flags & MDB_PS_MODIFY) && !(*mc->mc_dbflag & DB_DIRTY))) {
4613 unsigned char dbflag = 0;
4614 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
4615 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, flags & MDB_PS_MODIFY);
4618 if (*mc->mc_dbflag & DB_STALE) {
4622 MDB_node *leaf = mdb_node_search(&mc2,
4623 &mc->mc_dbx->md_name, &exact);
4625 return MDB_NOTFOUND;
4626 rc = mdb_node_read(mc->mc_txn, leaf, &data);
4629 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
4631 /* The txn may not know this DBI, or another process may
4632 * have dropped and recreated the DB with other flags.
4634 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
4635 return MDB_INCOMPATIBLE;
4636 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
4638 if (flags & MDB_PS_MODIFY)
4640 *mc->mc_dbflag &= ~DB_STALE;
4641 *mc->mc_dbflag |= dbflag;
4644 root = mc->mc_db->md_root;
4646 if (root == P_INVALID) { /* Tree is empty. */
4647 DPUTS("tree is empty");
4648 return MDB_NOTFOUND;
4653 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
4654 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0], NULL)) != 0)
4660 DPRINTF("db %u root page %zu has flags 0x%X",
4661 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
4663 if (flags & MDB_PS_MODIFY) {
4664 if ((rc = mdb_page_touch(mc)))
4668 if (flags & MDB_PS_ROOTONLY)
4671 return mdb_page_search_root(mc, key, flags);
4675 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
4677 MDB_txn *txn = mc->mc_txn;
4678 pgno_t pg = mp->mp_pgno;
4679 unsigned i, ovpages = mp->mp_pages;
4680 MDB_env *env = txn->mt_env;
4683 DPRINTF("free ov page %zu (%d)", pg, ovpages);
4684 /* If the page is dirty or on the spill list we just acquired it,
4685 * so we should give it back to our current free list, if any.
4686 * Not currently supported in nested txns.
4687 * Otherwise put it onto the list of pages we freed in this txn.
4689 if (!(mp->mp_flags & P_DIRTY) && txn->mt_spill_pgs) {
4690 unsigned x = mdb_midl_search(txn->mt_spill_pgs, pg);
4691 if (x <= txn->mt_spill_pgs[0] && txn->mt_spill_pgs[x] == pg) {
4692 /* This page is no longer spilled */
4693 for (; x < txn->mt_spill_pgs[0]; x++)
4694 txn->mt_spill_pgs[x] = txn->mt_spill_pgs[x+1];
4695 txn->mt_spill_pgs[0]--;
4699 if ((mp->mp_flags & P_DIRTY) && !txn->mt_parent && env->me_pghead) {
4702 MDB_ID2 *dl, ix, iy;
4703 rc = mdb_midl_need(&env->me_pghead, ovpages);
4706 /* Remove from dirty list */
4707 dl = txn->mt_u.dirty_list;
4709 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
4717 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
4718 txn->mt_flags |= MDB_TXN_ERROR;
4719 return MDB_CORRUPTED;
4722 if (!(env->me_flags & MDB_WRITEMAP))
4723 mdb_dpage_free(env, mp);
4725 /* Insert in me_pghead */
4726 mop = env->me_pghead;
4727 j = mop[0] + ovpages;
4728 for (i = mop[0]; i && mop[i] < pg; i--)
4734 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
4738 mc->mc_db->md_overflow_pages -= ovpages;
4742 /** Return the data associated with a given node.
4743 * @param[in] txn The transaction for this operation.
4744 * @param[in] leaf The node being read.
4745 * @param[out] data Updated to point to the node's data.
4746 * @return 0 on success, non-zero on failure.
4749 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
4751 MDB_page *omp; /* overflow page */
4755 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
4756 data->mv_size = NODEDSZ(leaf);
4757 data->mv_data = NODEDATA(leaf);
4761 /* Read overflow data.
4763 data->mv_size = NODEDSZ(leaf);
4764 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
4765 if ((rc = mdb_page_get(txn, pgno, &omp, NULL)) != 0) {
4766 DPRINTF("read overflow page %zu failed", pgno);
4769 data->mv_data = METADATA(omp);
4775 mdb_get(MDB_txn *txn, MDB_dbi dbi,
4776 MDB_val *key, MDB_val *data)
4785 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
4787 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
4790 if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
4794 mdb_cursor_init(&mc, txn, dbi, &mx);
4795 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
4798 /** Find a sibling for a page.
4799 * Replaces the page at the top of the cursor's stack with the
4800 * specified sibling, if one exists.
4801 * @param[in] mc The cursor for this operation.
4802 * @param[in] move_right Non-zero if the right sibling is requested,
4803 * otherwise the left sibling.
4804 * @return 0 on success, non-zero on failure.
4807 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
4813 if (mc->mc_snum < 2) {
4814 return MDB_NOTFOUND; /* root has no siblings */
4818 DPRINTF("parent page is page %zu, index %u",
4819 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]);
4821 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
4822 : (mc->mc_ki[mc->mc_top] == 0)) {
4823 DPRINTF("no more keys left, moving to %s sibling",
4824 move_right ? "right" : "left");
4825 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
4826 /* undo cursor_pop before returning */
4833 mc->mc_ki[mc->mc_top]++;
4835 mc->mc_ki[mc->mc_top]--;
4836 DPRINTF("just moving to %s index key %u",
4837 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]);
4839 assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
4841 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4842 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL) != 0))
4845 mdb_cursor_push(mc, mp);
4847 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
4852 /** Move the cursor to the next data item. */
4854 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
4860 if (mc->mc_flags & C_EOF) {
4861 return MDB_NOTFOUND;
4864 assert(mc->mc_flags & C_INITIALIZED);
4866 mp = mc->mc_pg[mc->mc_top];
4868 if (mc->mc_db->md_flags & MDB_DUPSORT) {
4869 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4870 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4871 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
4872 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
4873 if (op != MDB_NEXT || rc != MDB_NOTFOUND)
4877 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
4878 if (op == MDB_NEXT_DUP)
4879 return MDB_NOTFOUND;
4883 DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
4885 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
4886 DPUTS("=====> move to next sibling page");
4887 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
4888 mc->mc_flags |= C_EOF;
4891 mp = mc->mc_pg[mc->mc_top];
4892 DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
4894 mc->mc_ki[mc->mc_top]++;
4896 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
4897 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
4900 key->mv_size = mc->mc_db->md_pad;
4901 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
4905 assert(IS_LEAF(mp));
4906 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4908 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4909 mdb_xcursor_init1(mc, leaf);
4912 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4915 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4916 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4917 if (rc != MDB_SUCCESS)
4922 MDB_GET_KEY(leaf, key);
4926 /** Move the cursor to the previous data item. */
4928 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
4934 assert(mc->mc_flags & C_INITIALIZED);
4936 mp = mc->mc_pg[mc->mc_top];
4938 if (mc->mc_db->md_flags & MDB_DUPSORT) {
4939 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4940 if (op == MDB_PREV || op == MDB_PREV_DUP) {
4941 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4942 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
4943 if (op != MDB_PREV || rc != MDB_NOTFOUND)
4946 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
4947 if (op == MDB_PREV_DUP)
4948 return MDB_NOTFOUND;
4953 DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
4955 if (mc->mc_ki[mc->mc_top] == 0) {
4956 DPUTS("=====> move to prev sibling page");
4957 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
4960 mp = mc->mc_pg[mc->mc_top];
4961 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
4962 DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
4964 mc->mc_ki[mc->mc_top]--;
4966 mc->mc_flags &= ~C_EOF;
4968 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
4969 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
4972 key->mv_size = mc->mc_db->md_pad;
4973 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
4977 assert(IS_LEAF(mp));
4978 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4980 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4981 mdb_xcursor_init1(mc, leaf);
4984 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4987 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4988 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
4989 if (rc != MDB_SUCCESS)
4994 MDB_GET_KEY(leaf, key);
4998 /** Set the cursor on a specific data item. */
5000 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5001 MDB_cursor_op op, int *exactp)
5005 MDB_node *leaf = NULL;
5010 assert(key->mv_size > 0);
5013 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5015 /* See if we're already on the right page */
5016 if (mc->mc_flags & C_INITIALIZED) {
5019 mp = mc->mc_pg[mc->mc_top];
5021 mc->mc_ki[mc->mc_top] = 0;
5022 return MDB_NOTFOUND;
5024 if (mp->mp_flags & P_LEAF2) {
5025 nodekey.mv_size = mc->mc_db->md_pad;
5026 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
5028 leaf = NODEPTR(mp, 0);
5029 MDB_GET_KEY(leaf, &nodekey);
5031 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5033 /* Probably happens rarely, but first node on the page
5034 * was the one we wanted.
5036 mc->mc_ki[mc->mc_top] = 0;
5043 unsigned int nkeys = NUMKEYS(mp);
5045 if (mp->mp_flags & P_LEAF2) {
5046 nodekey.mv_data = LEAF2KEY(mp,
5047 nkeys-1, nodekey.mv_size);
5049 leaf = NODEPTR(mp, nkeys-1);
5050 MDB_GET_KEY(leaf, &nodekey);
5052 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5054 /* last node was the one we wanted */
5055 mc->mc_ki[mc->mc_top] = nkeys-1;
5061 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
5062 /* This is definitely the right page, skip search_page */
5063 if (mp->mp_flags & P_LEAF2) {
5064 nodekey.mv_data = LEAF2KEY(mp,
5065 mc->mc_ki[mc->mc_top], nodekey.mv_size);
5067 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5068 MDB_GET_KEY(leaf, &nodekey);
5070 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5072 /* current node was the one we wanted */
5082 /* If any parents have right-sibs, search.
5083 * Otherwise, there's nothing further.
5085 for (i=0; i<mc->mc_top; i++)
5087 NUMKEYS(mc->mc_pg[i])-1)
5089 if (i == mc->mc_top) {
5090 /* There are no other pages */
5091 mc->mc_ki[mc->mc_top] = nkeys;
5092 return MDB_NOTFOUND;
5096 /* There are no other pages */
5097 mc->mc_ki[mc->mc_top] = 0;
5098 return MDB_NOTFOUND;
5102 rc = mdb_page_search(mc, key, 0);
5103 if (rc != MDB_SUCCESS)
5106 mp = mc->mc_pg[mc->mc_top];
5107 assert(IS_LEAF(mp));
5110 leaf = mdb_node_search(mc, key, exactp);
5111 if (exactp != NULL && !*exactp) {
5112 /* MDB_SET specified and not an exact match. */
5113 return MDB_NOTFOUND;
5117 DPUTS("===> inexact leaf not found, goto sibling");
5118 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
5119 return rc; /* no entries matched */
5120 mp = mc->mc_pg[mc->mc_top];
5121 assert(IS_LEAF(mp));
5122 leaf = NODEPTR(mp, 0);
5126 mc->mc_flags |= C_INITIALIZED;
5127 mc->mc_flags &= ~C_EOF;
5130 key->mv_size = mc->mc_db->md_pad;
5131 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5135 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5136 mdb_xcursor_init1(mc, leaf);
5139 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5140 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
5141 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5144 if (op == MDB_GET_BOTH) {
5150 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
5151 if (rc != MDB_SUCCESS)
5154 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
5156 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
5158 rc = mc->mc_dbx->md_dcmp(data, &d2);
5160 if (op == MDB_GET_BOTH || rc > 0)
5161 return MDB_NOTFOUND;
5166 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5167 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5172 /* The key already matches in all other cases */
5173 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
5174 MDB_GET_KEY(leaf, key);
5175 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
5180 /** Move the cursor to the first item in the database. */
5182 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5188 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5190 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5191 rc = mdb_page_search(mc, NULL, 0);
5192 if (rc != MDB_SUCCESS)
5195 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
5197 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
5198 mc->mc_flags |= C_INITIALIZED;
5199 mc->mc_flags &= ~C_EOF;
5201 mc->mc_ki[mc->mc_top] = 0;
5203 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5204 key->mv_size = mc->mc_db->md_pad;
5205 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
5210 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5211 mdb_xcursor_init1(mc, leaf);
5212 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5216 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5220 MDB_GET_KEY(leaf, key);
5224 /** Move the cursor to the last item in the database. */
5226 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5232 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5234 if (!(mc->mc_flags & C_EOF)) {
5236 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5239 lkey.mv_size = MDB_MAXKEYSIZE+1;
5240 lkey.mv_data = NULL;
5241 rc = mdb_page_search(mc, &lkey, 0);
5242 if (rc != MDB_SUCCESS)
5245 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
5248 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
5249 mc->mc_flags |= C_INITIALIZED|C_EOF;
5250 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5252 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5253 key->mv_size = mc->mc_db->md_pad;
5254 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
5259 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5260 mdb_xcursor_init1(mc, leaf);
5261 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5265 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5270 MDB_GET_KEY(leaf, key);
5275 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5284 case MDB_GET_CURRENT:
5285 if (!(mc->mc_flags & C_INITIALIZED)) {
5288 MDB_page *mp = mc->mc_pg[mc->mc_top];
5290 mc->mc_ki[mc->mc_top] = 0;
5296 key->mv_size = mc->mc_db->md_pad;
5297 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5299 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5300 MDB_GET_KEY(leaf, key);
5302 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5303 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
5305 rc = mdb_node_read(mc->mc_txn, leaf, data);
5312 case MDB_GET_BOTH_RANGE:
5313 if (data == NULL || mc->mc_xcursor == NULL) {
5321 if (key == NULL || key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
5323 } else if (op == MDB_SET_RANGE)
5324 rc = mdb_cursor_set(mc, key, data, op, NULL);
5326 rc = mdb_cursor_set(mc, key, data, op, &exact);
5328 case MDB_GET_MULTIPLE:
5330 !(mc->mc_db->md_flags & MDB_DUPFIXED) ||
5331 !(mc->mc_flags & C_INITIALIZED)) {
5336 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
5337 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
5340 case MDB_NEXT_MULTIPLE:
5342 !(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5346 if (!(mc->mc_flags & C_INITIALIZED))
5347 rc = mdb_cursor_first(mc, key, data);
5349 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
5350 if (rc == MDB_SUCCESS) {
5351 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
5354 mx = &mc->mc_xcursor->mx_cursor;
5355 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
5357 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
5358 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
5366 case MDB_NEXT_NODUP:
5367 if (!(mc->mc_flags & C_INITIALIZED))
5368 rc = mdb_cursor_first(mc, key, data);
5370 rc = mdb_cursor_next(mc, key, data, op);
5374 case MDB_PREV_NODUP:
5375 if (!(mc->mc_flags & C_INITIALIZED)) {
5376 rc = mdb_cursor_last(mc, key, data);
5379 mc->mc_flags |= C_INITIALIZED;
5380 mc->mc_ki[mc->mc_top]++;
5382 rc = mdb_cursor_prev(mc, key, data, op);
5385 rc = mdb_cursor_first(mc, key, data);
5389 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
5390 !(mc->mc_flags & C_INITIALIZED) ||
5391 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
5395 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5398 rc = mdb_cursor_last(mc, key, data);
5402 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
5403 !(mc->mc_flags & C_INITIALIZED) ||
5404 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
5408 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5411 DPRINTF("unhandled/unimplemented cursor operation %u", op);
5419 /** Touch all the pages in the cursor stack.
5420 * Makes sure all the pages are writable, before attempting a write operation.
5421 * @param[in] mc The cursor to operate on.
5424 mdb_cursor_touch(MDB_cursor *mc)
5428 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
5431 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
5432 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
5435 *mc->mc_dbflag |= DB_DIRTY;
5437 for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
5438 rc = mdb_page_touch(mc);
5442 mc->mc_top = mc->mc_snum-1;
5446 /** Do not spill pages to disk if txn is getting full, may fail instead */
5447 #define MDB_NOSPILL 0x8000
5450 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5453 enum { MDB_NO_ROOT = MDB_LAST_ERRCODE+10 }; /* internal code */
5454 MDB_node *leaf = NULL;
5455 MDB_val xdata, *rdata, dkey;
5458 int do_sub = 0, insert = 0;
5459 unsigned int mcount = 0, dcount = 0, nospill;
5463 char dbuf[MDB_MAXKEYSIZE+1];
5464 unsigned int nflags;
5467 /* Check this first so counter will always be zero on any
5470 if (flags & MDB_MULTIPLE) {
5471 dcount = data[1].mv_size;
5472 data[1].mv_size = 0;
5473 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
5477 nospill = flags & MDB_NOSPILL;
5478 flags &= ~MDB_NOSPILL;
5480 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
5483 if (flags != MDB_CURRENT && (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE))
5486 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT) && data->mv_size > MDB_MAXKEYSIZE)
5489 #if SIZE_MAX > MAXDATASIZE
5490 if (data->mv_size > MAXDATASIZE)
5494 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
5495 mc->mc_dbi, DKEY(key), key ? key->mv_size:0, data->mv_size);
5499 if (flags == MDB_CURRENT) {
5500 if (!(mc->mc_flags & C_INITIALIZED))
5503 } else if (mc->mc_db->md_root == P_INVALID) {
5504 /* new database, cursor has nothing to point to */
5506 mc->mc_flags &= ~C_INITIALIZED;
5511 if (flags & MDB_APPEND) {
5513 rc = mdb_cursor_last(mc, &k2, &d2);
5515 rc = mc->mc_dbx->md_cmp(key, &k2);
5518 mc->mc_ki[mc->mc_top]++;
5520 /* new key is <= last key */
5525 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
5527 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
5528 DPRINTF("duplicate key [%s]", DKEY(key));
5530 return MDB_KEYEXIST;
5532 if (rc && rc != MDB_NOTFOUND)
5536 /* Cursor is positioned, check for room in the dirty list */
5538 if (flags & MDB_MULTIPLE) {
5540 xdata.mv_size = data->mv_size * dcount;
5544 if ((rc2 = mdb_page_spill(mc, key, rdata)))
5548 if (rc == MDB_NO_ROOT) {
5550 /* new database, write a root leaf page */
5551 DPUTS("allocating new root leaf page");
5552 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
5555 mdb_cursor_push(mc, np);
5556 mc->mc_db->md_root = np->mp_pgno;
5557 mc->mc_db->md_depth++;
5558 *mc->mc_dbflag |= DB_DIRTY;
5559 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
5561 np->mp_flags |= P_LEAF2;
5562 mc->mc_flags |= C_INITIALIZED;
5564 /* make sure all cursor pages are writable */
5565 rc2 = mdb_cursor_touch(mc);
5570 /* The key already exists */
5571 if (rc == MDB_SUCCESS) {
5572 /* there's only a key anyway, so this is a no-op */
5573 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5574 unsigned int ksize = mc->mc_db->md_pad;
5575 if (key->mv_size != ksize)
5577 if (flags == MDB_CURRENT) {
5578 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
5579 memcpy(ptr, key->mv_data, ksize);
5584 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5587 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
5588 /* Was a single item before, must convert now */
5590 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5591 /* Just overwrite the current item */
5592 if (flags == MDB_CURRENT)
5595 dkey.mv_size = NODEDSZ(leaf);
5596 dkey.mv_data = NODEDATA(leaf);
5597 #if UINT_MAX < SIZE_MAX
5598 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && dkey.mv_size == sizeof(size_t))
5599 #ifdef MISALIGNED_OK
5600 mc->mc_dbx->md_dcmp = mdb_cmp_long;
5602 mc->mc_dbx->md_dcmp = mdb_cmp_cint;
5605 /* if data matches, ignore it */
5606 if (!mc->mc_dbx->md_dcmp(data, &dkey))
5607 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
5609 /* create a fake page for the dup items */
5610 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
5611 dkey.mv_data = dbuf;
5612 fp = (MDB_page *)&pbuf;
5613 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
5614 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
5615 fp->mp_lower = PAGEHDRSZ;
5616 fp->mp_upper = PAGEHDRSZ + dkey.mv_size + data->mv_size;
5617 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5618 fp->mp_flags |= P_LEAF2;
5619 fp->mp_pad = data->mv_size;
5620 fp->mp_upper += 2 * data->mv_size; /* leave space for 2 more */
5622 fp->mp_upper += 2 * sizeof(indx_t) + 2 * NODESIZE +
5623 (dkey.mv_size & 1) + (data->mv_size & 1);
5625 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5628 xdata.mv_size = fp->mp_upper;
5633 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
5634 /* See if we need to convert from fake page to subDB */
5636 unsigned int offset;
5640 fp = NODEDATA(leaf);
5641 if (flags == MDB_CURRENT) {
5643 fp->mp_flags |= P_DIRTY;
5644 COPY_PGNO(fp->mp_pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
5645 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
5649 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5650 offset = fp->mp_pad;
5651 if (SIZELEFT(fp) >= offset)
5653 offset *= 4; /* space for 4 more */
5655 offset = NODESIZE + sizeof(indx_t) + data->mv_size;
5657 offset += offset & 1;
5658 fp_flags = fp->mp_flags;
5659 if (NODESIZE + sizeof(indx_t) + NODEKSZ(leaf) + NODEDSZ(leaf) +
5660 offset >= mc->mc_txn->mt_env->me_nodemax) {
5661 /* yes, convert it */
5663 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5664 dummy.md_pad = fp->mp_pad;
5665 dummy.md_flags = MDB_DUPFIXED;
5666 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
5667 dummy.md_flags |= MDB_INTEGERKEY;
5670 dummy.md_branch_pages = 0;
5671 dummy.md_leaf_pages = 1;
5672 dummy.md_overflow_pages = 0;
5673 dummy.md_entries = NUMKEYS(fp);
5675 xdata.mv_size = sizeof(MDB_db);
5676 xdata.mv_data = &dummy;
5677 if ((rc = mdb_page_alloc(mc, 1, &mp)))
5679 offset = mc->mc_txn->mt_env->me_psize - NODEDSZ(leaf);
5680 flags |= F_DUPDATA|F_SUBDATA;
5681 dummy.md_root = mp->mp_pgno;
5682 fp_flags &= ~P_SUBP;
5684 /* no, just grow it */
5686 xdata.mv_size = NODEDSZ(leaf) + offset;
5687 xdata.mv_data = &pbuf;
5688 mp = (MDB_page *)&pbuf;
5689 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
5692 mp->mp_flags = fp_flags | P_DIRTY;
5693 mp->mp_pad = fp->mp_pad;
5694 mp->mp_lower = fp->mp_lower;
5695 mp->mp_upper = fp->mp_upper + offset;
5697 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
5699 nsize = NODEDSZ(leaf) - fp->mp_upper;
5700 memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper, nsize);
5701 for (i=0; i<NUMKEYS(fp); i++)
5702 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
5704 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5708 /* data is on sub-DB, just store it */
5709 flags |= F_DUPDATA|F_SUBDATA;
5713 /* overflow page overwrites need special handling */
5714 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5717 unsigned psize = mc->mc_txn->mt_env->me_psize;
5718 int level, ovpages, dpages = OVPAGES(data->mv_size, psize);
5720 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
5721 if ((rc2 = mdb_page_get(mc->mc_txn, pg, &omp, &level)) != 0)
5723 ovpages = omp->mp_pages;
5725 /* Is the ov page large enough? */
5726 if (ovpages >= dpages) {
5727 if (!(omp->mp_flags & P_DIRTY) &&
5728 (level || (mc->mc_txn->mt_env->me_flags & MDB_WRITEMAP)))
5730 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
5733 level = 0; /* dirty in this txn or clean */
5736 if (omp->mp_flags & P_DIRTY) {
5737 /* yes, overwrite it. Note in this case we don't
5738 * bother to try shrinking the page if the new data
5739 * is smaller than the overflow threshold.
5742 /* It is writable only in a parent txn */
5743 size_t sz = (size_t) psize * ovpages, off;
5744 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
5750 mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
5751 if (!(flags & MDB_RESERVE)) {
5752 /* Copy end of page, adjusting alignment so
5753 * compiler may copy words instead of bytes.
5755 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
5756 memcpy((size_t *)((char *)np + off),
5757 (size_t *)((char *)omp + off), sz - off);
5760 memcpy(np, omp, sz); /* Copy beginning of page */
5763 SETDSZ(leaf, data->mv_size);
5764 if (F_ISSET(flags, MDB_RESERVE))
5765 data->mv_data = METADATA(omp);
5767 memcpy(METADATA(omp), data->mv_data, data->mv_size);
5771 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
5773 } else if (NODEDSZ(leaf) == data->mv_size) {
5774 /* same size, just replace it. Note that we could
5775 * also reuse this node if the new data is smaller,
5776 * but instead we opt to shrink the node in that case.
5778 if (F_ISSET(flags, MDB_RESERVE))
5779 data->mv_data = NODEDATA(leaf);
5780 else if (data->mv_size)
5781 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
5783 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
5786 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5787 mc->mc_db->md_entries--;
5789 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
5796 nflags = flags & NODE_ADD_FLAGS;
5797 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
5798 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
5799 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
5800 nflags &= ~MDB_APPEND;
5802 nflags |= MDB_SPLIT_REPLACE;
5803 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
5805 /* There is room already in this leaf page. */
5806 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
5807 if (rc == 0 && !do_sub && insert) {
5808 /* Adjust other cursors pointing to mp */
5809 MDB_cursor *m2, *m3;
5810 MDB_dbi dbi = mc->mc_dbi;
5811 unsigned i = mc->mc_top;
5812 MDB_page *mp = mc->mc_pg[i];
5814 if (mc->mc_flags & C_SUB)
5817 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5818 if (mc->mc_flags & C_SUB)
5819 m3 = &m2->mc_xcursor->mx_cursor;
5822 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
5823 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
5830 if (rc != MDB_SUCCESS)
5831 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5833 /* Now store the actual data in the child DB. Note that we're
5834 * storing the user data in the keys field, so there are strict
5835 * size limits on dupdata. The actual data fields of the child
5836 * DB are all zero size.
5843 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5844 if (flags & MDB_CURRENT) {
5845 xflags = MDB_CURRENT|MDB_NOSPILL;
5847 mdb_xcursor_init1(mc, leaf);
5848 xflags = (flags & MDB_NODUPDATA) ?
5849 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
5851 /* converted, write the original data first */
5853 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
5857 /* Adjust other cursors pointing to mp */
5859 unsigned i = mc->mc_top;
5860 MDB_page *mp = mc->mc_pg[i];
5862 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5863 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
5864 if (!(m2->mc_flags & C_INITIALIZED)) continue;
5865 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
5866 mdb_xcursor_init1(m2, leaf);
5870 /* we've done our job */
5873 if (flags & MDB_APPENDDUP)
5874 xflags |= MDB_APPEND;
5875 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
5876 if (flags & F_SUBDATA) {
5877 void *db = NODEDATA(leaf);
5878 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
5881 /* sub-writes might have failed so check rc again.
5882 * Don't increment count if we just replaced an existing item.
5884 if (!rc && !(flags & MDB_CURRENT))
5885 mc->mc_db->md_entries++;
5886 if (flags & MDB_MULTIPLE) {
5889 if (mcount < dcount) {
5890 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
5891 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5895 /* let caller know how many succeeded, if any */
5896 data[1].mv_size = mcount;
5900 /* If we succeeded and the key didn't exist before, make sure
5901 * the cursor is marked valid.
5904 mc->mc_flags |= C_INITIALIZED;
5909 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
5914 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
5917 if (!(mc->mc_flags & C_INITIALIZED))
5920 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
5922 flags &= ~MDB_NOSPILL; /* TODO: Or change (flags != MDB_NODUPDATA) to ~(flags & MDB_NODUPDATA), not looking at the logic of that code just now */
5924 rc = mdb_cursor_touch(mc);
5928 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5930 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5931 if (flags != MDB_NODUPDATA) {
5932 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
5933 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
5935 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
5936 /* If sub-DB still has entries, we're done */
5937 if (mc->mc_xcursor->mx_db.md_entries) {
5938 if (leaf->mn_flags & F_SUBDATA) {
5939 /* update subDB info */
5940 void *db = NODEDATA(leaf);
5941 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
5944 /* shrink fake page */
5945 mdb_node_shrink(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5946 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5947 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
5948 /* fix other sub-DB cursors pointed at this fake page */
5949 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5950 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
5951 if (m2->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top] &&
5952 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
5953 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
5956 mc->mc_db->md_entries--;
5959 /* otherwise fall thru and delete the sub-DB */
5962 if (leaf->mn_flags & F_SUBDATA) {
5963 /* add all the child DB's pages to the free list */
5964 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
5965 if (rc == MDB_SUCCESS) {
5966 mc->mc_db->md_entries -=
5967 mc->mc_xcursor->mx_db.md_entries;
5972 return mdb_cursor_del0(mc, leaf);
5975 /** Allocate and initialize new pages for a database.
5976 * @param[in] mc a cursor on the database being added to.
5977 * @param[in] flags flags defining what type of page is being allocated.
5978 * @param[in] num the number of pages to allocate. This is usually 1,
5979 * unless allocating overflow pages for a large record.
5980 * @param[out] mp Address of a page, or NULL on failure.
5981 * @return 0 on success, non-zero on failure.
5984 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
5989 if ((rc = mdb_page_alloc(mc, num, &np)))
5991 DPRINTF("allocated new mpage %zu, page size %u",
5992 np->mp_pgno, mc->mc_txn->mt_env->me_psize);
5993 np->mp_flags = flags | P_DIRTY;
5994 np->mp_lower = PAGEHDRSZ;
5995 np->mp_upper = mc->mc_txn->mt_env->me_psize;
5998 mc->mc_db->md_branch_pages++;
5999 else if (IS_LEAF(np))
6000 mc->mc_db->md_leaf_pages++;
6001 else if (IS_OVERFLOW(np)) {
6002 mc->mc_db->md_overflow_pages += num;
6010 /** Calculate the size of a leaf node.
6011 * The size depends on the environment's page size; if a data item
6012 * is too large it will be put onto an overflow page and the node
6013 * size will only include the key and not the data. Sizes are always
6014 * rounded up to an even number of bytes, to guarantee 2-byte alignment
6015 * of the #MDB_node headers.
6016 * @param[in] env The environment handle.
6017 * @param[in] key The key for the node.
6018 * @param[in] data The data for the node.
6019 * @return The number of bytes needed to store the node.
6022 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
6026 sz = LEAFSIZE(key, data);
6027 if (sz >= env->me_nodemax) {
6028 /* put on overflow page */
6029 sz -= data->mv_size - sizeof(pgno_t);
6033 return sz + sizeof(indx_t);
6036 /** Calculate the size of a branch node.
6037 * The size should depend on the environment's page size but since
6038 * we currently don't support spilling large keys onto overflow
6039 * pages, it's simply the size of the #MDB_node header plus the
6040 * size of the key. Sizes are always rounded up to an even number
6041 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
6042 * @param[in] env The environment handle.
6043 * @param[in] key The key for the node.
6044 * @return The number of bytes needed to store the node.
6047 mdb_branch_size(MDB_env *env, MDB_val *key)
6052 if (sz >= env->me_nodemax) {
6053 /* put on overflow page */
6054 /* not implemented */
6055 /* sz -= key->size - sizeof(pgno_t); */
6058 return sz + sizeof(indx_t);
6061 /** Add a node to the page pointed to by the cursor.
6062 * @param[in] mc The cursor for this operation.
6063 * @param[in] indx The index on the page where the new node should be added.
6064 * @param[in] key The key for the new node.
6065 * @param[in] data The data for the new node, if any.
6066 * @param[in] pgno The page number, if adding a branch node.
6067 * @param[in] flags Flags for the node.
6068 * @return 0 on success, non-zero on failure. Possible errors are:
6070 * <li>ENOMEM - failed to allocate overflow pages for the node.
6071 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
6072 * should never happen since all callers already calculate the
6073 * page's free space before calling this function.
6077 mdb_node_add(MDB_cursor *mc, indx_t indx,
6078 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
6081 size_t node_size = NODESIZE;
6084 MDB_page *mp = mc->mc_pg[mc->mc_top];
6085 MDB_page *ofp = NULL; /* overflow page */
6088 assert(mp->mp_upper >= mp->mp_lower);
6090 DPRINTF("add to %s %spage %zu index %i, data size %zu key size %zu [%s]",
6091 IS_LEAF(mp) ? "leaf" : "branch",
6092 IS_SUBP(mp) ? "sub-" : "",
6093 mp->mp_pgno, indx, data ? data->mv_size : 0,
6094 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
6097 /* Move higher keys up one slot. */
6098 int ksize = mc->mc_db->md_pad, dif;
6099 char *ptr = LEAF2KEY(mp, indx, ksize);
6100 dif = NUMKEYS(mp) - indx;
6102 memmove(ptr+ksize, ptr, dif*ksize);
6103 /* insert new key */
6104 memcpy(ptr, key->mv_data, ksize);
6106 /* Just using these for counting */
6107 mp->mp_lower += sizeof(indx_t);
6108 mp->mp_upper -= ksize - sizeof(indx_t);
6113 node_size += key->mv_size;
6117 if (F_ISSET(flags, F_BIGDATA)) {
6118 /* Data already on overflow page. */
6119 node_size += sizeof(pgno_t);
6120 } else if (node_size + data->mv_size >= mc->mc_txn->mt_env->me_nodemax) {
6121 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
6123 /* Put data on overflow page. */
6124 DPRINTF("data size is %zu, node would be %zu, put data on overflow page",
6125 data->mv_size, node_size+data->mv_size);
6126 node_size += sizeof(pgno_t);
6127 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
6129 DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
6132 node_size += data->mv_size;
6135 node_size += node_size & 1;
6137 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
6138 DPRINTF("not enough room in page %zu, got %u ptrs",
6139 mp->mp_pgno, NUMKEYS(mp));
6140 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
6141 mp->mp_upper - mp->mp_lower);
6142 DPRINTF("node size = %zu", node_size);
6143 return MDB_PAGE_FULL;
6146 /* Move higher pointers up one slot. */
6147 for (i = NUMKEYS(mp); i > indx; i--)
6148 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
6150 /* Adjust free space offsets. */
6151 ofs = mp->mp_upper - node_size;
6152 assert(ofs >= mp->mp_lower + sizeof(indx_t));
6153 mp->mp_ptrs[indx] = ofs;
6155 mp->mp_lower += sizeof(indx_t);
6157 /* Write the node data. */
6158 node = NODEPTR(mp, indx);
6159 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
6160 node->mn_flags = flags;
6162 SETDSZ(node,data->mv_size);
6167 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6172 if (F_ISSET(flags, F_BIGDATA))
6173 memcpy(node->mn_data + key->mv_size, data->mv_data,
6175 else if (F_ISSET(flags, MDB_RESERVE))
6176 data->mv_data = node->mn_data + key->mv_size;
6178 memcpy(node->mn_data + key->mv_size, data->mv_data,
6181 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
6183 if (F_ISSET(flags, MDB_RESERVE))
6184 data->mv_data = METADATA(ofp);
6186 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
6193 /** Delete the specified node from a page.
6194 * @param[in] mp The page to operate on.
6195 * @param[in] indx The index of the node to delete.
6196 * @param[in] ksize The size of a node. Only used if the page is
6197 * part of a #MDB_DUPFIXED database.
6200 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
6203 indx_t i, j, numkeys, ptr;
6210 COPY_PGNO(pgno, mp->mp_pgno);
6211 DPRINTF("delete node %u on %s page %zu", indx,
6212 IS_LEAF(mp) ? "leaf" : "branch", pgno);
6215 assert(indx < NUMKEYS(mp));
6218 int x = NUMKEYS(mp) - 1 - indx;
6219 base = LEAF2KEY(mp, indx, ksize);
6221 memmove(base, base + ksize, x * ksize);
6222 mp->mp_lower -= sizeof(indx_t);
6223 mp->mp_upper += ksize - sizeof(indx_t);
6227 node = NODEPTR(mp, indx);
6228 sz = NODESIZE + node->mn_ksize;
6230 if (F_ISSET(node->mn_flags, F_BIGDATA))
6231 sz += sizeof(pgno_t);
6233 sz += NODEDSZ(node);
6237 ptr = mp->mp_ptrs[indx];
6238 numkeys = NUMKEYS(mp);
6239 for (i = j = 0; i < numkeys; i++) {
6241 mp->mp_ptrs[j] = mp->mp_ptrs[i];
6242 if (mp->mp_ptrs[i] < ptr)
6243 mp->mp_ptrs[j] += sz;
6248 base = (char *)mp + mp->mp_upper;
6249 memmove(base + sz, base, ptr - mp->mp_upper);
6251 mp->mp_lower -= sizeof(indx_t);
6255 /** Compact the main page after deleting a node on a subpage.
6256 * @param[in] mp The main page to operate on.
6257 * @param[in] indx The index of the subpage on the main page.
6260 mdb_node_shrink(MDB_page *mp, indx_t indx)
6267 indx_t i, numkeys, ptr;
6269 node = NODEPTR(mp, indx);
6270 sp = (MDB_page *)NODEDATA(node);
6271 osize = NODEDSZ(node);
6273 delta = sp->mp_upper - sp->mp_lower;
6274 SETDSZ(node, osize - delta);
6275 xp = (MDB_page *)((char *)sp + delta);
6277 /* shift subpage upward */
6279 nsize = NUMKEYS(sp) * sp->mp_pad;
6280 memmove(METADATA(xp), METADATA(sp), nsize);
6283 nsize = osize - sp->mp_upper;
6284 numkeys = NUMKEYS(sp);
6285 for (i=numkeys-1; i>=0; i--)
6286 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
6288 xp->mp_upper = sp->mp_lower;
6289 xp->mp_lower = sp->mp_lower;
6290 xp->mp_flags = sp->mp_flags;
6291 xp->mp_pad = sp->mp_pad;
6292 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
6294 /* shift lower nodes upward */
6295 ptr = mp->mp_ptrs[indx];
6296 numkeys = NUMKEYS(mp);
6297 for (i = 0; i < numkeys; i++) {
6298 if (mp->mp_ptrs[i] <= ptr)
6299 mp->mp_ptrs[i] += delta;
6302 base = (char *)mp + mp->mp_upper;
6303 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
6304 mp->mp_upper += delta;
6307 /** Initial setup of a sorted-dups cursor.
6308 * Sorted duplicates are implemented as a sub-database for the given key.
6309 * The duplicate data items are actually keys of the sub-database.
6310 * Operations on the duplicate data items are performed using a sub-cursor
6311 * initialized when the sub-database is first accessed. This function does
6312 * the preliminary setup of the sub-cursor, filling in the fields that
6313 * depend only on the parent DB.
6314 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6317 mdb_xcursor_init0(MDB_cursor *mc)
6319 MDB_xcursor *mx = mc->mc_xcursor;
6321 mx->mx_cursor.mc_xcursor = NULL;
6322 mx->mx_cursor.mc_txn = mc->mc_txn;
6323 mx->mx_cursor.mc_db = &mx->mx_db;
6324 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
6325 mx->mx_cursor.mc_dbi = mc->mc_dbi+1;
6326 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
6327 mx->mx_cursor.mc_snum = 0;
6328 mx->mx_cursor.mc_top = 0;
6329 mx->mx_cursor.mc_flags = C_SUB;
6330 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
6331 mx->mx_dbx.md_dcmp = NULL;
6332 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
6335 /** Final setup of a sorted-dups cursor.
6336 * Sets up the fields that depend on the data from the main cursor.
6337 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6338 * @param[in] node The data containing the #MDB_db record for the
6339 * sorted-dup database.
6342 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
6344 MDB_xcursor *mx = mc->mc_xcursor;
6346 if (node->mn_flags & F_SUBDATA) {
6347 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
6348 mx->mx_cursor.mc_pg[0] = 0;
6349 mx->mx_cursor.mc_snum = 0;
6350 mx->mx_cursor.mc_flags = C_SUB;
6352 MDB_page *fp = NODEDATA(node);
6353 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
6354 mx->mx_db.md_flags = 0;
6355 mx->mx_db.md_depth = 1;
6356 mx->mx_db.md_branch_pages = 0;
6357 mx->mx_db.md_leaf_pages = 1;
6358 mx->mx_db.md_overflow_pages = 0;
6359 mx->mx_db.md_entries = NUMKEYS(fp);
6360 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
6361 mx->mx_cursor.mc_snum = 1;
6362 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
6363 mx->mx_cursor.mc_top = 0;
6364 mx->mx_cursor.mc_pg[0] = fp;
6365 mx->mx_cursor.mc_ki[0] = 0;
6366 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6367 mx->mx_db.md_flags = MDB_DUPFIXED;
6368 mx->mx_db.md_pad = fp->mp_pad;
6369 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6370 mx->mx_db.md_flags |= MDB_INTEGERKEY;
6373 DPRINTF("Sub-db %u for db %u root page %zu", mx->mx_cursor.mc_dbi, mc->mc_dbi,
6375 mx->mx_dbflag = DB_VALID | (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY) ?
6377 mx->mx_dbx.md_name.mv_data = NODEKEY(node);
6378 mx->mx_dbx.md_name.mv_size = node->mn_ksize;
6379 #if UINT_MAX < SIZE_MAX
6380 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
6381 #ifdef MISALIGNED_OK
6382 mx->mx_dbx.md_cmp = mdb_cmp_long;
6384 mx->mx_dbx.md_cmp = mdb_cmp_cint;
6389 /** Initialize a cursor for a given transaction and database. */
6391 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
6394 mc->mc_backup = NULL;
6397 mc->mc_db = &txn->mt_dbs[dbi];
6398 mc->mc_dbx = &txn->mt_dbxs[dbi];
6399 mc->mc_dbflag = &txn->mt_dbflags[dbi];
6404 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
6406 mc->mc_xcursor = mx;
6407 mdb_xcursor_init0(mc);
6409 mc->mc_xcursor = NULL;
6411 if (*mc->mc_dbflag & DB_STALE) {
6412 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
6417 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
6420 size_t size = sizeof(MDB_cursor);
6422 if (txn == NULL || ret == NULL || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
6425 /* Allow read access to the freelist */
6426 if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
6429 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
6430 size += sizeof(MDB_xcursor);
6432 if ((mc = malloc(size)) != NULL) {
6433 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
6434 if (txn->mt_cursors) {
6435 mc->mc_next = txn->mt_cursors[dbi];
6436 txn->mt_cursors[dbi] = mc;
6437 mc->mc_flags |= C_UNTRACK;
6449 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
6451 if (txn == NULL || mc == NULL || mc->mc_dbi >= txn->mt_numdbs)
6454 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
6457 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
6461 /* Return the count of duplicate data items for the current key */
6463 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
6467 if (mc == NULL || countp == NULL)
6470 if (!(mc->mc_db->md_flags & MDB_DUPSORT))
6473 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6474 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6477 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
6480 *countp = mc->mc_xcursor->mx_db.md_entries;
6486 mdb_cursor_close(MDB_cursor *mc)
6488 if (mc && !mc->mc_backup) {
6489 /* remove from txn, if tracked */
6490 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
6491 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
6492 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
6494 *prev = mc->mc_next;
6501 mdb_cursor_txn(MDB_cursor *mc)
6503 if (!mc) return NULL;
6508 mdb_cursor_dbi(MDB_cursor *mc)
6514 /** Replace the key for a node with a new key.
6515 * @param[in] mc Cursor pointing to the node to operate on.
6516 * @param[in] key The new key to use.
6517 * @return 0 on success, non-zero on failure.
6520 mdb_update_key(MDB_cursor *mc, MDB_val *key)
6527 indx_t ptr, i, numkeys, indx;
6530 indx = mc->mc_ki[mc->mc_top];
6531 mp = mc->mc_pg[mc->mc_top];
6532 node = NODEPTR(mp, indx);
6533 ptr = mp->mp_ptrs[indx];
6537 char kbuf2[(MDB_MAXKEYSIZE*2+1)];
6538 k2.mv_data = NODEKEY(node);
6539 k2.mv_size = node->mn_ksize;
6540 DPRINTF("update key %u (ofs %u) [%s] to [%s] on page %zu",
6542 mdb_dkey(&k2, kbuf2),
6548 delta0 = delta = key->mv_size - node->mn_ksize;
6550 /* Must be 2-byte aligned. If new key is
6551 * shorter by 1, the shift will be skipped.
6553 delta += (delta & 1);
6555 if (delta > 0 && SIZELEFT(mp) < delta) {
6557 /* not enough space left, do a delete and split */
6558 DPRINTF("Not enough room, delta = %d, splitting...", delta);
6559 pgno = NODEPGNO(node);
6560 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
6561 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
6564 numkeys = NUMKEYS(mp);
6565 for (i = 0; i < numkeys; i++) {
6566 if (mp->mp_ptrs[i] <= ptr)
6567 mp->mp_ptrs[i] -= delta;
6570 base = (char *)mp + mp->mp_upper;
6571 len = ptr - mp->mp_upper + NODESIZE;
6572 memmove(base - delta, base, len);
6573 mp->mp_upper -= delta;
6575 node = NODEPTR(mp, indx);
6578 /* But even if no shift was needed, update ksize */
6580 node->mn_ksize = key->mv_size;
6583 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6589 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
6591 /** Move a node from csrc to cdst.
6594 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
6601 unsigned short flags;
6605 /* Mark src and dst as dirty. */
6606 if ((rc = mdb_page_touch(csrc)) ||
6607 (rc = mdb_page_touch(cdst)))
6610 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6611 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
6612 key.mv_size = csrc->mc_db->md_pad;
6613 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
6615 data.mv_data = NULL;
6619 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
6620 assert(!((long)srcnode&1));
6621 srcpg = NODEPGNO(srcnode);
6622 flags = srcnode->mn_flags;
6623 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6624 unsigned int snum = csrc->mc_snum;
6626 /* must find the lowest key below src */
6627 mdb_page_search_lowest(csrc);
6628 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6629 key.mv_size = csrc->mc_db->md_pad;
6630 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6632 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6633 key.mv_size = NODEKSZ(s2);
6634 key.mv_data = NODEKEY(s2);
6636 csrc->mc_snum = snum--;
6637 csrc->mc_top = snum;
6639 key.mv_size = NODEKSZ(srcnode);
6640 key.mv_data = NODEKEY(srcnode);
6642 data.mv_size = NODEDSZ(srcnode);
6643 data.mv_data = NODEDATA(srcnode);
6645 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
6646 unsigned int snum = cdst->mc_snum;
6649 /* must find the lowest key below dst */
6650 mdb_page_search_lowest(cdst);
6651 if (IS_LEAF2(cdst->mc_pg[cdst->mc_top])) {
6652 bkey.mv_size = cdst->mc_db->md_pad;
6653 bkey.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, bkey.mv_size);
6655 s2 = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
6656 bkey.mv_size = NODEKSZ(s2);
6657 bkey.mv_data = NODEKEY(s2);
6659 cdst->mc_snum = snum--;
6660 cdst->mc_top = snum;
6661 mdb_cursor_copy(cdst, &mn);
6663 rc = mdb_update_key(&mn, &bkey);
6668 DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
6669 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
6670 csrc->mc_ki[csrc->mc_top],
6672 csrc->mc_pg[csrc->mc_top]->mp_pgno,
6673 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
6675 /* Add the node to the destination page.
6677 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
6678 if (rc != MDB_SUCCESS)
6681 /* Delete the node from the source page.
6683 mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
6686 /* Adjust other cursors pointing to mp */
6687 MDB_cursor *m2, *m3;
6688 MDB_dbi dbi = csrc->mc_dbi;
6689 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
6691 if (csrc->mc_flags & C_SUB)
6694 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6695 if (csrc->mc_flags & C_SUB)
6696 m3 = &m2->mc_xcursor->mx_cursor;
6699 if (m3 == csrc) continue;
6700 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
6701 csrc->mc_ki[csrc->mc_top]) {
6702 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
6703 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
6708 /* Update the parent separators.
6710 if (csrc->mc_ki[csrc->mc_top] == 0) {
6711 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
6712 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6713 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6715 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6716 key.mv_size = NODEKSZ(srcnode);
6717 key.mv_data = NODEKEY(srcnode);
6719 DPRINTF("update separator for source page %zu to [%s]",
6720 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
6721 mdb_cursor_copy(csrc, &mn);
6724 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
6727 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6729 indx_t ix = csrc->mc_ki[csrc->mc_top];
6730 nullkey.mv_size = 0;
6731 csrc->mc_ki[csrc->mc_top] = 0;
6732 rc = mdb_update_key(csrc, &nullkey);
6733 csrc->mc_ki[csrc->mc_top] = ix;
6734 assert(rc == MDB_SUCCESS);
6738 if (cdst->mc_ki[cdst->mc_top] == 0) {
6739 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
6740 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6741 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
6743 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
6744 key.mv_size = NODEKSZ(srcnode);
6745 key.mv_data = NODEKEY(srcnode);
6747 DPRINTF("update separator for destination page %zu to [%s]",
6748 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
6749 mdb_cursor_copy(cdst, &mn);
6752 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
6755 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
6757 indx_t ix = cdst->mc_ki[cdst->mc_top];
6758 nullkey.mv_size = 0;
6759 cdst->mc_ki[cdst->mc_top] = 0;
6760 rc = mdb_update_key(cdst, &nullkey);
6761 cdst->mc_ki[cdst->mc_top] = ix;
6762 assert(rc == MDB_SUCCESS);
6769 /** Merge one page into another.
6770 * The nodes from the page pointed to by \b csrc will
6771 * be copied to the page pointed to by \b cdst and then
6772 * the \b csrc page will be freed.
6773 * @param[in] csrc Cursor pointing to the source page.
6774 * @param[in] cdst Cursor pointing to the destination page.
6777 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
6785 DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
6786 cdst->mc_pg[cdst->mc_top]->mp_pgno);
6788 assert(csrc->mc_snum > 1); /* can't merge root page */
6789 assert(cdst->mc_snum > 1);
6791 /* Mark dst as dirty. */
6792 if ((rc = mdb_page_touch(cdst)))
6795 /* Move all nodes from src to dst.
6797 j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
6798 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6799 key.mv_size = csrc->mc_db->md_pad;
6800 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
6801 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
6802 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
6803 if (rc != MDB_SUCCESS)
6805 key.mv_data = (char *)key.mv_data + key.mv_size;
6808 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
6809 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
6810 if (i == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6811 unsigned int snum = csrc->mc_snum;
6813 /* must find the lowest key below src */
6814 mdb_page_search_lowest(csrc);
6815 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6816 key.mv_size = csrc->mc_db->md_pad;
6817 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6819 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6820 key.mv_size = NODEKSZ(s2);
6821 key.mv_data = NODEKEY(s2);
6823 csrc->mc_snum = snum--;
6824 csrc->mc_top = snum;
6826 key.mv_size = srcnode->mn_ksize;
6827 key.mv_data = NODEKEY(srcnode);
6830 data.mv_size = NODEDSZ(srcnode);
6831 data.mv_data = NODEDATA(srcnode);
6832 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
6833 if (rc != MDB_SUCCESS)
6838 DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
6839 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);
6841 /* Unlink the src page from parent and add to free list.
6843 mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
6844 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
6847 rc = mdb_update_key(csrc, &key);
6853 rc = mdb_midl_append(&csrc->mc_txn->mt_free_pgs,
6854 csrc->mc_pg[csrc->mc_top]->mp_pgno);
6857 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
6858 csrc->mc_db->md_leaf_pages--;
6860 csrc->mc_db->md_branch_pages--;
6862 /* Adjust other cursors pointing to mp */
6863 MDB_cursor *m2, *m3;
6864 MDB_dbi dbi = csrc->mc_dbi;
6865 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
6867 if (csrc->mc_flags & C_SUB)
6870 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6871 if (csrc->mc_flags & C_SUB)
6872 m3 = &m2->mc_xcursor->mx_cursor;
6875 if (m3 == csrc) continue;
6876 if (m3->mc_snum < csrc->mc_snum) continue;
6877 if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
6878 m3->mc_pg[csrc->mc_top] = mp;
6879 m3->mc_ki[csrc->mc_top] += nkeys;
6883 mdb_cursor_pop(csrc);
6885 return mdb_rebalance(csrc);
6888 /** Copy the contents of a cursor.
6889 * @param[in] csrc The cursor to copy from.
6890 * @param[out] cdst The cursor to copy to.
6893 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
6897 cdst->mc_txn = csrc->mc_txn;
6898 cdst->mc_dbi = csrc->mc_dbi;
6899 cdst->mc_db = csrc->mc_db;
6900 cdst->mc_dbx = csrc->mc_dbx;
6901 cdst->mc_snum = csrc->mc_snum;
6902 cdst->mc_top = csrc->mc_top;
6903 cdst->mc_flags = csrc->mc_flags;
6905 for (i=0; i<csrc->mc_snum; i++) {
6906 cdst->mc_pg[i] = csrc->mc_pg[i];
6907 cdst->mc_ki[i] = csrc->mc_ki[i];
6911 /** Rebalance the tree after a delete operation.
6912 * @param[in] mc Cursor pointing to the page where rebalancing
6914 * @return 0 on success, non-zero on failure.
6917 mdb_rebalance(MDB_cursor *mc)
6921 unsigned int ptop, minkeys;
6924 minkeys = 1 + (IS_BRANCH(mc->mc_pg[mc->mc_top]));
6928 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
6929 DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
6930 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
6931 pgno, NUMKEYS(mc->mc_pg[mc->mc_top]), (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10);
6935 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD &&
6936 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
6939 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
6940 DPRINTF("no need to rebalance page %zu, above fill threshold",
6946 if (mc->mc_snum < 2) {
6947 MDB_page *mp = mc->mc_pg[0];
6949 DPUTS("Can't rebalance a subpage, ignoring");
6952 if (NUMKEYS(mp) == 0) {
6953 DPUTS("tree is completely empty");
6954 mc->mc_db->md_root = P_INVALID;
6955 mc->mc_db->md_depth = 0;
6956 mc->mc_db->md_leaf_pages = 0;
6957 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
6960 /* Adjust cursors pointing to mp */
6964 MDB_cursor *m2, *m3;
6965 MDB_dbi dbi = mc->mc_dbi;
6967 if (mc->mc_flags & C_SUB)
6970 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6971 if (mc->mc_flags & C_SUB)
6972 m3 = &m2->mc_xcursor->mx_cursor;
6975 if (m3->mc_snum < mc->mc_snum) continue;
6976 if (m3->mc_pg[0] == mp) {
6982 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
6983 DPUTS("collapsing root page!");
6984 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
6987 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
6988 rc = mdb_page_get(mc->mc_txn,mc->mc_db->md_root,&mc->mc_pg[0],NULL);
6991 mc->mc_db->md_depth--;
6992 mc->mc_db->md_branch_pages--;
6993 mc->mc_ki[0] = mc->mc_ki[1];
6995 /* Adjust other cursors pointing to mp */
6996 MDB_cursor *m2, *m3;
6997 MDB_dbi dbi = mc->mc_dbi;
6999 if (mc->mc_flags & C_SUB)
7002 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7003 if (mc->mc_flags & C_SUB)
7004 m3 = &m2->mc_xcursor->mx_cursor;
7007 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
7008 if (m3->mc_pg[0] == mp) {
7009 m3->mc_pg[0] = mc->mc_pg[0];
7012 m3->mc_ki[0] = m3->mc_ki[1];
7017 DPUTS("root page doesn't need rebalancing");
7021 /* The parent (branch page) must have at least 2 pointers,
7022 * otherwise the tree is invalid.
7024 ptop = mc->mc_top-1;
7025 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
7027 /* Leaf page fill factor is below the threshold.
7028 * Try to move keys from left or right neighbor, or
7029 * merge with a neighbor page.
7034 mdb_cursor_copy(mc, &mn);
7035 mn.mc_xcursor = NULL;
7037 if (mc->mc_ki[ptop] == 0) {
7038 /* We're the leftmost leaf in our parent.
7040 DPUTS("reading right neighbor");
7042 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7043 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7046 mn.mc_ki[mn.mc_top] = 0;
7047 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
7049 /* There is at least one neighbor to the left.
7051 DPUTS("reading left neighbor");
7053 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7054 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7057 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
7058 mc->mc_ki[mc->mc_top] = 0;
7061 DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
7062 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);
7064 /* If the neighbor page is above threshold and has enough keys,
7065 * move one key from it. Otherwise we should try to merge them.
7066 * (A branch page must never have less than 2 keys.)
7068 minkeys = 1 + (IS_BRANCH(mn.mc_pg[mn.mc_top]));
7069 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys)
7070 return mdb_node_move(&mn, mc);
7072 if (mc->mc_ki[ptop] == 0)
7073 rc = mdb_page_merge(&mn, mc);
7075 rc = mdb_page_merge(mc, &mn);
7076 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
7081 /** Complete a delete operation started by #mdb_cursor_del(). */
7083 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
7089 mp = mc->mc_pg[mc->mc_top];
7090 ki = mc->mc_ki[mc->mc_top];
7092 /* add overflow pages to free list */
7093 if (!IS_LEAF2(mp) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7097 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
7098 if ((rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL)) ||
7099 (rc = mdb_ovpage_free(mc, omp)))
7102 mdb_node_del(mp, ki, mc->mc_db->md_pad);
7103 mc->mc_db->md_entries--;
7104 rc = mdb_rebalance(mc);
7105 if (rc != MDB_SUCCESS)
7106 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7107 /* if mc points past last node in page, invalidate */
7108 else if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
7109 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
7112 /* Adjust other cursors pointing to mp */
7115 MDB_dbi dbi = mc->mc_dbi;
7117 mp = mc->mc_pg[mc->mc_top];
7118 nkeys = NUMKEYS(mp);
7119 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7122 if (!(m2->mc_flags & C_INITIALIZED))
7124 if (m2->mc_pg[mc->mc_top] == mp) {
7125 if (m2->mc_ki[mc->mc_top] > ki)
7126 m2->mc_ki[mc->mc_top]--;
7127 if (m2->mc_ki[mc->mc_top] >= nkeys)
7128 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
7137 mdb_del(MDB_txn *txn, MDB_dbi dbi,
7138 MDB_val *key, MDB_val *data)
7143 MDB_val rdata, *xdata;
7147 assert(key != NULL);
7149 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
7151 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7154 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
7158 if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
7162 mdb_cursor_init(&mc, txn, dbi, &mx);
7173 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
7175 /* let mdb_page_split know about this cursor if needed:
7176 * delete will trigger a rebalance; if it needs to move
7177 * a node from one page to another, it will have to
7178 * update the parent's separator key(s). If the new sepkey
7179 * is larger than the current one, the parent page may
7180 * run out of space, triggering a split. We need this
7181 * cursor to be consistent until the end of the rebalance.
7183 mc.mc_flags |= C_UNTRACK;
7184 mc.mc_next = txn->mt_cursors[dbi];
7185 txn->mt_cursors[dbi] = &mc;
7186 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
7187 txn->mt_cursors[dbi] = mc.mc_next;
7192 /** Split a page and insert a new node.
7193 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
7194 * The cursor will be updated to point to the actual page and index where
7195 * the node got inserted after the split.
7196 * @param[in] newkey The key for the newly inserted node.
7197 * @param[in] newdata The data for the newly inserted node.
7198 * @param[in] newpgno The page number, if the new node is a branch node.
7199 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
7200 * @return 0 on success, non-zero on failure.
7203 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
7204 unsigned int nflags)
7207 int rc = MDB_SUCCESS, ins_new = 0, new_root = 0, newpos = 1, did_split = 0;
7210 unsigned int i, j, split_indx, nkeys, pmax;
7212 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
7214 MDB_page *mp, *rp, *pp;
7219 mp = mc->mc_pg[mc->mc_top];
7220 newindx = mc->mc_ki[mc->mc_top];
7222 DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
7223 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
7224 DKEY(newkey), mc->mc_ki[mc->mc_top]);
7226 /* Create a right sibling. */
7227 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
7229 DPRINTF("new right sibling: page %zu", rp->mp_pgno);
7231 if (mc->mc_snum < 2) {
7232 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
7234 /* shift current top to make room for new parent */
7235 mc->mc_pg[1] = mc->mc_pg[0];
7236 mc->mc_ki[1] = mc->mc_ki[0];
7239 mc->mc_db->md_root = pp->mp_pgno;
7240 DPRINTF("root split! new root = %zu", pp->mp_pgno);
7241 mc->mc_db->md_depth++;
7244 /* Add left (implicit) pointer. */
7245 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
7246 /* undo the pre-push */
7247 mc->mc_pg[0] = mc->mc_pg[1];
7248 mc->mc_ki[0] = mc->mc_ki[1];
7249 mc->mc_db->md_root = mp->mp_pgno;
7250 mc->mc_db->md_depth--;
7257 ptop = mc->mc_top-1;
7258 DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
7261 mc->mc_flags |= C_SPLITTING;
7262 mdb_cursor_copy(mc, &mn);
7263 mn.mc_pg[mn.mc_top] = rp;
7264 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
7266 if (nflags & MDB_APPEND) {
7267 mn.mc_ki[mn.mc_top] = 0;
7269 split_indx = newindx;
7274 nkeys = NUMKEYS(mp);
7275 split_indx = nkeys / 2;
7276 if (newindx < split_indx)
7282 unsigned int lsize, rsize, ksize;
7283 /* Move half of the keys to the right sibling */
7285 x = mc->mc_ki[mc->mc_top] - split_indx;
7286 ksize = mc->mc_db->md_pad;
7287 split = LEAF2KEY(mp, split_indx, ksize);
7288 rsize = (nkeys - split_indx) * ksize;
7289 lsize = (nkeys - split_indx) * sizeof(indx_t);
7290 mp->mp_lower -= lsize;
7291 rp->mp_lower += lsize;
7292 mp->mp_upper += rsize - lsize;
7293 rp->mp_upper -= rsize - lsize;
7294 sepkey.mv_size = ksize;
7295 if (newindx == split_indx) {
7296 sepkey.mv_data = newkey->mv_data;
7298 sepkey.mv_data = split;
7301 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
7302 memcpy(rp->mp_ptrs, split, rsize);
7303 sepkey.mv_data = rp->mp_ptrs;
7304 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
7305 memcpy(ins, newkey->mv_data, ksize);
7306 mp->mp_lower += sizeof(indx_t);
7307 mp->mp_upper -= ksize - sizeof(indx_t);
7310 memcpy(rp->mp_ptrs, split, x * ksize);
7311 ins = LEAF2KEY(rp, x, ksize);
7312 memcpy(ins, newkey->mv_data, ksize);
7313 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
7314 rp->mp_lower += sizeof(indx_t);
7315 rp->mp_upper -= ksize - sizeof(indx_t);
7316 mc->mc_ki[mc->mc_top] = x;
7317 mc->mc_pg[mc->mc_top] = rp;
7322 /* For leaf pages, check the split point based on what
7323 * fits where, since otherwise mdb_node_add can fail.
7325 * This check is only needed when the data items are
7326 * relatively large, such that being off by one will
7327 * make the difference between success or failure.
7329 * It's also relevant if a page happens to be laid out
7330 * such that one half of its nodes are all "small" and
7331 * the other half of its nodes are "large." If the new
7332 * item is also "large" and falls on the half with
7333 * "large" nodes, it also may not fit.
7336 unsigned int psize, nsize;
7337 /* Maximum free space in an empty page */
7338 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
7339 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
7340 if ((nkeys < 20) || (nsize > pmax/16)) {
7341 if (newindx <= split_indx) {
7344 for (i=0; i<split_indx; i++) {
7345 node = NODEPTR(mp, i);
7346 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
7347 if (F_ISSET(node->mn_flags, F_BIGDATA))
7348 psize += sizeof(pgno_t);
7350 psize += NODEDSZ(node);
7354 split_indx = newindx;
7365 for (i=nkeys-1; i>=split_indx; i--) {
7366 node = NODEPTR(mp, i);
7367 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
7368 if (F_ISSET(node->mn_flags, F_BIGDATA))
7369 psize += sizeof(pgno_t);
7371 psize += NODEDSZ(node);
7375 split_indx = newindx;
7386 /* First find the separating key between the split pages.
7387 * The case where newindx == split_indx is ambiguous; the
7388 * new item could go to the new page or stay on the original
7389 * page. If newpos == 1 it goes to the new page.
7391 if (newindx == split_indx && newpos) {
7392 sepkey.mv_size = newkey->mv_size;
7393 sepkey.mv_data = newkey->mv_data;
7395 node = NODEPTR(mp, split_indx);
7396 sepkey.mv_size = node->mn_ksize;
7397 sepkey.mv_data = NODEKEY(node);
7401 DPRINTF("separator is [%s]", DKEY(&sepkey));
7403 /* Copy separator key to the parent.
7405 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
7409 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
7412 if (mn.mc_snum == mc->mc_snum) {
7413 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
7414 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
7415 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
7416 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
7421 /* Right page might now have changed parent.
7422 * Check if left page also changed parent.
7424 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7425 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7426 for (i=0; i<ptop; i++) {
7427 mc->mc_pg[i] = mn.mc_pg[i];
7428 mc->mc_ki[i] = mn.mc_ki[i];
7430 mc->mc_pg[ptop] = mn.mc_pg[ptop];
7431 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
7435 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
7438 mc->mc_flags ^= C_SPLITTING;
7439 if (rc != MDB_SUCCESS) {
7442 if (nflags & MDB_APPEND) {
7443 mc->mc_pg[mc->mc_top] = rp;
7444 mc->mc_ki[mc->mc_top] = 0;
7445 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
7448 for (i=0; i<mc->mc_top; i++)
7449 mc->mc_ki[i] = mn.mc_ki[i];
7456 /* Move half of the keys to the right sibling. */
7458 /* grab a page to hold a temporary copy */
7459 copy = mdb_page_malloc(mc->mc_txn, 1);
7463 copy->mp_pgno = mp->mp_pgno;
7464 copy->mp_flags = mp->mp_flags;
7465 copy->mp_lower = PAGEHDRSZ;
7466 copy->mp_upper = mc->mc_txn->mt_env->me_psize;
7467 mc->mc_pg[mc->mc_top] = copy;
7468 for (i = j = 0; i <= nkeys; j++) {
7469 if (i == split_indx) {
7470 /* Insert in right sibling. */
7471 /* Reset insert index for right sibling. */
7472 if (i != newindx || (newpos ^ ins_new)) {
7474 mc->mc_pg[mc->mc_top] = rp;
7478 if (i == newindx && !ins_new) {
7479 /* Insert the original entry that caused the split. */
7480 rkey.mv_data = newkey->mv_data;
7481 rkey.mv_size = newkey->mv_size;
7490 /* Update index for the new key. */
7491 mc->mc_ki[mc->mc_top] = j;
7492 } else if (i == nkeys) {
7495 node = NODEPTR(mp, i);
7496 rkey.mv_data = NODEKEY(node);
7497 rkey.mv_size = node->mn_ksize;
7499 xdata.mv_data = NODEDATA(node);
7500 xdata.mv_size = NODEDSZ(node);
7503 pgno = NODEPGNO(node);
7504 flags = node->mn_flags;
7509 if (!IS_LEAF(mp) && j == 0) {
7510 /* First branch index doesn't need key data. */
7514 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
7518 nkeys = NUMKEYS(copy);
7519 for (i=0; i<nkeys; i++)
7520 mp->mp_ptrs[i] = copy->mp_ptrs[i];
7521 mp->mp_lower = copy->mp_lower;
7522 mp->mp_upper = copy->mp_upper;
7523 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
7524 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
7526 /* reset back to original page */
7527 if (newindx < split_indx || (!newpos && newindx == split_indx)) {
7528 mc->mc_pg[mc->mc_top] = mp;
7529 if (nflags & MDB_RESERVE) {
7530 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7531 if (!(node->mn_flags & F_BIGDATA))
7532 newdata->mv_data = NODEDATA(node);
7536 /* Make sure mc_ki is still valid.
7538 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7539 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7540 for (i=0; i<ptop; i++) {
7541 mc->mc_pg[i] = mn.mc_pg[i];
7542 mc->mc_ki[i] = mn.mc_ki[i];
7544 mc->mc_pg[ptop] = mn.mc_pg[ptop];
7545 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
7549 /* return tmp page to freelist */
7550 mdb_page_free(mc->mc_txn->mt_env, copy);
7553 /* Adjust other cursors pointing to mp */
7554 MDB_cursor *m2, *m3;
7555 MDB_dbi dbi = mc->mc_dbi;
7556 int fixup = NUMKEYS(mp);
7558 if (mc->mc_flags & C_SUB)
7561 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7562 if (mc->mc_flags & C_SUB)
7563 m3 = &m2->mc_xcursor->mx_cursor;
7568 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
7570 if (m3->mc_flags & C_SPLITTING)
7575 for (k=m3->mc_top; k>=0; k--) {
7576 m3->mc_ki[k+1] = m3->mc_ki[k];
7577 m3->mc_pg[k+1] = m3->mc_pg[k];
7579 if (m3->mc_ki[0] >= split_indx) {
7584 m3->mc_pg[0] = mc->mc_pg[0];
7588 if (m3->mc_pg[mc->mc_top] == mp) {
7589 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
7590 m3->mc_ki[mc->mc_top]++;
7591 if (m3->mc_ki[mc->mc_top] >= fixup) {
7592 m3->mc_pg[mc->mc_top] = rp;
7593 m3->mc_ki[mc->mc_top] -= fixup;
7594 m3->mc_ki[ptop] = mn.mc_ki[ptop];
7596 } else if (!did_split && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
7597 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
7606 mdb_put(MDB_txn *txn, MDB_dbi dbi,
7607 MDB_val *key, MDB_val *data, unsigned int flags)
7612 assert(key != NULL);
7613 assert(data != NULL);
7615 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7618 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
7622 if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
7626 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP)) != flags)
7629 mdb_cursor_init(&mc, txn, dbi, &mx);
7630 return mdb_cursor_put(&mc, key, data, flags);
7634 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
7636 if ((flag & CHANGEABLE) != flag)
7639 env->me_flags |= flag;
7641 env->me_flags &= ~flag;
7646 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
7651 *arg = env->me_flags;
7656 mdb_env_get_path(MDB_env *env, const char **arg)
7661 *arg = env->me_path;
7665 /** Common code for #mdb_stat() and #mdb_env_stat().
7666 * @param[in] env the environment to operate in.
7667 * @param[in] db the #MDB_db record containing the stats to return.
7668 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
7669 * @return 0, this function always succeeds.
7672 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
7674 arg->ms_psize = env->me_psize;
7675 arg->ms_depth = db->md_depth;
7676 arg->ms_branch_pages = db->md_branch_pages;
7677 arg->ms_leaf_pages = db->md_leaf_pages;
7678 arg->ms_overflow_pages = db->md_overflow_pages;
7679 arg->ms_entries = db->md_entries;
7684 mdb_env_stat(MDB_env *env, MDB_stat *arg)
7688 if (env == NULL || arg == NULL)
7691 toggle = mdb_env_pick_meta(env);
7693 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
7697 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
7701 if (env == NULL || arg == NULL)
7704 toggle = mdb_env_pick_meta(env);
7705 arg->me_mapaddr = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : 0;
7706 arg->me_mapsize = env->me_mapsize;
7707 arg->me_maxreaders = env->me_maxreaders;
7709 /* me_numreaders may be zero if this process never used any readers. Use
7710 * the shared numreader count if it exists.
7712 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : env->me_numreaders;
7714 arg->me_last_pgno = env->me_metas[toggle]->mm_last_pg;
7715 arg->me_last_txnid = env->me_metas[toggle]->mm_txnid;
7719 /** Set the default comparison functions for a database.
7720 * Called immediately after a database is opened to set the defaults.
7721 * The user can then override them with #mdb_set_compare() or
7722 * #mdb_set_dupsort().
7723 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
7724 * @param[in] dbi A database handle returned by #mdb_dbi_open()
7727 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
7729 uint16_t f = txn->mt_dbs[dbi].md_flags;
7731 txn->mt_dbxs[dbi].md_cmp =
7732 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
7733 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
7735 txn->mt_dbxs[dbi].md_dcmp =
7736 !(f & MDB_DUPSORT) ? 0 :
7737 ((f & MDB_INTEGERDUP)
7738 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
7739 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
7742 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
7747 int rc, dbflag, exact;
7748 unsigned int unused = 0;
7751 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
7752 mdb_default_cmp(txn, FREE_DBI);
7755 if ((flags & VALID_FLAGS) != flags)
7761 if (flags & PERSISTENT_FLAGS) {
7762 uint16_t f2 = flags & PERSISTENT_FLAGS;
7763 /* make sure flag changes get committed */
7764 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
7765 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
7766 txn->mt_flags |= MDB_TXN_DIRTY;
7769 mdb_default_cmp(txn, MAIN_DBI);
7773 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
7774 mdb_default_cmp(txn, MAIN_DBI);
7777 /* Is the DB already open? */
7779 for (i=2; i<txn->mt_numdbs; i++) {
7780 if (!txn->mt_dbxs[i].md_name.mv_size) {
7781 /* Remember this free slot */
7782 if (!unused) unused = i;
7785 if (len == txn->mt_dbxs[i].md_name.mv_size &&
7786 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
7792 /* If no free slot and max hit, fail */
7793 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
7794 return MDB_DBS_FULL;
7796 /* Cannot mix named databases with some mainDB flags */
7797 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
7798 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
7800 /* Find the DB info */
7801 dbflag = DB_NEW|DB_VALID;
7804 key.mv_data = (void *)name;
7805 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
7806 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
7807 if (rc == MDB_SUCCESS) {
7808 /* make sure this is actually a DB */
7809 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
7810 if (!(node->mn_flags & F_SUBDATA))
7812 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
7813 /* Create if requested */
7815 data.mv_size = sizeof(MDB_db);
7816 data.mv_data = &dummy;
7817 memset(&dummy, 0, sizeof(dummy));
7818 dummy.md_root = P_INVALID;
7819 dummy.md_flags = flags & PERSISTENT_FLAGS;
7820 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
7824 /* OK, got info, add to table */
7825 if (rc == MDB_SUCCESS) {
7826 unsigned int slot = unused ? unused : txn->mt_numdbs;
7827 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
7828 txn->mt_dbxs[slot].md_name.mv_size = len;
7829 txn->mt_dbxs[slot].md_rel = NULL;
7830 txn->mt_dbflags[slot] = dbflag;
7831 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
7833 txn->mt_env->me_dbflags[slot] = txn->mt_dbs[slot].md_flags;
7834 mdb_default_cmp(txn, slot);
7843 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
7845 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
7848 if (txn->mt_dbflags[dbi] & DB_STALE) {
7851 /* Stale, must read the DB's root. cursor_init does it for us. */
7852 mdb_cursor_init(&mc, txn, dbi, &mx);
7854 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
7857 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
7860 if (dbi <= MAIN_DBI || dbi >= env->me_maxdbs)
7862 ptr = env->me_dbxs[dbi].md_name.mv_data;
7863 env->me_dbxs[dbi].md_name.mv_data = NULL;
7864 env->me_dbxs[dbi].md_name.mv_size = 0;
7865 env->me_dbflags[dbi] = 0;
7869 int mdb_dbi_flags(MDB_env *env, MDB_dbi dbi, unsigned int *flags)
7871 /* We could return the flags for the FREE_DBI too but what's the point? */
7872 if (dbi <= MAIN_DBI || dbi >= env->me_numdbs)
7874 *flags = env->me_dbflags[dbi];
7878 /** Add all the DB's pages to the free list.
7879 * @param[in] mc Cursor on the DB to free.
7880 * @param[in] subs non-Zero to check for sub-DBs in this DB.
7881 * @return 0 on success, non-zero on failure.
7884 mdb_drop0(MDB_cursor *mc, int subs)
7888 rc = mdb_page_search(mc, NULL, 0);
7889 if (rc == MDB_SUCCESS) {
7890 MDB_txn *txn = mc->mc_txn;
7895 /* LEAF2 pages have no nodes, cannot have sub-DBs */
7896 if (IS_LEAF2(mc->mc_pg[mc->mc_top]))
7899 mdb_cursor_copy(mc, &mx);
7900 while (mc->mc_snum > 0) {
7901 MDB_page *mp = mc->mc_pg[mc->mc_top];
7902 unsigned n = NUMKEYS(mp);
7904 for (i=0; i<n; i++) {
7905 ni = NODEPTR(mp, i);
7906 if (ni->mn_flags & F_BIGDATA) {
7909 memcpy(&pg, NODEDATA(ni), sizeof(pg));
7910 rc = mdb_page_get(txn, pg, &omp, NULL);
7913 assert(IS_OVERFLOW(omp));
7914 rc = mdb_midl_append_range(&txn->mt_free_pgs,
7918 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
7919 mdb_xcursor_init1(mc, ni);
7920 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
7926 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
7928 for (i=0; i<n; i++) {
7930 ni = NODEPTR(mp, i);
7933 mdb_midl_xappend(txn->mt_free_pgs, pg);
7938 mc->mc_ki[mc->mc_top] = i;
7939 rc = mdb_cursor_sibling(mc, 1);
7941 /* no more siblings, go back to beginning
7942 * of previous level.
7946 for (i=1; i<mc->mc_snum; i++) {
7948 mc->mc_pg[i] = mx.mc_pg[i];
7953 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
7954 } else if (rc == MDB_NOTFOUND) {
7960 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
7962 MDB_cursor *mc, *m2;
7965 if (!txn || !dbi || dbi >= txn->mt_numdbs || (unsigned)del > 1 || !(txn->mt_dbflags[dbi] & DB_VALID))
7968 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
7971 rc = mdb_cursor_open(txn, dbi, &mc);
7975 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
7976 /* Invalidate the dropped DB's cursors */
7977 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
7978 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
7982 /* Can't delete the main DB */
7983 if (del && dbi > MAIN_DBI) {
7984 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
7986 txn->mt_dbflags[dbi] = DB_STALE;
7987 mdb_dbi_close(txn->mt_env, dbi);
7990 /* reset the DB record, mark it dirty */
7991 txn->mt_dbflags[dbi] |= DB_DIRTY;
7992 txn->mt_dbs[dbi].md_depth = 0;
7993 txn->mt_dbs[dbi].md_branch_pages = 0;
7994 txn->mt_dbs[dbi].md_leaf_pages = 0;
7995 txn->mt_dbs[dbi].md_overflow_pages = 0;
7996 txn->mt_dbs[dbi].md_entries = 0;
7997 txn->mt_dbs[dbi].md_root = P_INVALID;
7999 txn->mt_flags |= MDB_TXN_DIRTY;
8002 mdb_cursor_close(mc);
8006 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
8008 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8011 txn->mt_dbxs[dbi].md_cmp = cmp;
8015 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
8017 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8020 txn->mt_dbxs[dbi].md_dcmp = cmp;
8024 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
8026 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8029 txn->mt_dbxs[dbi].md_rel = rel;
8033 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
8035 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8038 txn->mt_dbxs[dbi].md_relctx = ctx;
8042 int mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
8044 unsigned int i, rdrs;
8051 if (!env->me_txns) {
8052 return func("(no reader locks)\n", ctx);
8054 rdrs = env->me_txns->mti_numreaders;
8055 mr = env->me_txns->mti_readers;
8056 for (i=0; i<rdrs; i++) {
8061 if (mr[i].mr_txnid == (txnid_t)-1) {
8062 sprintf(buf, "%10d %zx -\n", mr[i].mr_pid, tid);
8064 sprintf(buf, "%10d %zx %zu\n", mr[i].mr_pid, tid, mr[i].mr_txnid);
8068 func(" pid thread txnid\n", ctx);
8070 rc = func(buf, ctx);
8076 func("(no active readers)\n", ctx);
8081 /* insert pid into list if not already present.
8082 * return -1 if already present.
8084 static int mdb_pid_insert(pid_t *ids, pid_t pid)
8086 /* binary search of pid in list */
8088 unsigned cursor = 1;
8090 unsigned n = ids[0];
8093 unsigned pivot = n >> 1;
8094 cursor = base + pivot + 1;
8095 val = pid - ids[cursor];
8100 } else if ( val > 0 ) {
8105 /* found, so it's a duplicate */
8114 for (n = ids[0]; n > cursor; n--)
8120 int mdb_reader_check(MDB_env *env, int *dead)
8122 unsigned int i, j, rdrs;
8133 rdrs = env->me_txns->mti_numreaders;
8134 pids = malloc((rdrs+1) * sizeof(pid_t));
8138 mr = env->me_txns->mti_readers;
8140 for (i=0; i<rdrs; i++) {
8141 if (mr[i].mr_pid && mr[i].mr_pid != env->me_pid) {
8143 if (mdb_pid_insert(pids, pid) == 0) {
8144 if (mdb_reader_pid(env, Pidcheck, pid)) {
8146 if (mdb_reader_pid(env, Pidcheck, pid)) {
8147 for (j=i; j<rdrs; j++)
8148 if (mr[j].mr_pid == pid) {
8153 UNLOCK_MUTEX_R(env);