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>
42 /** getpid() returns int; MinGW defines pid_t but MinGW64 typedefs it
43 * as int64 which is wrong. MSVC doesn't define it at all, so just
48 # include <sys/param.h>
50 # define LITTLE_ENDIAN 1234
51 # define BIG_ENDIAN 4321
52 # define BYTE_ORDER LITTLE_ENDIAN
54 # define SSIZE_MAX INT_MAX
58 #define MDB_PID_T pid_t
59 #include <sys/param.h>
62 #ifdef HAVE_SYS_FILE_H
79 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
80 #include <netinet/in.h>
81 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
84 #if defined(__APPLE__) || defined (BSD)
85 # define MDB_USE_POSIX_SEM 1
86 # define MDB_FDATASYNC fsync
87 #elif defined(ANDROID)
88 # define MDB_FDATASYNC fsync
93 #ifdef MDB_USE_POSIX_SEM
94 # define MDB_USE_HASH 1
95 #include <semaphore.h>
100 #include <valgrind/memcheck.h>
101 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
102 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
103 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
104 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
105 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
107 #define VGMEMP_CREATE(h,r,z)
108 #define VGMEMP_ALLOC(h,a,s)
109 #define VGMEMP_FREE(h,a)
110 #define VGMEMP_DESTROY(h)
111 #define VGMEMP_DEFINED(a,s)
115 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
116 /* Solaris just defines one or the other */
117 # define LITTLE_ENDIAN 1234
118 # define BIG_ENDIAN 4321
119 # ifdef _LITTLE_ENDIAN
120 # define BYTE_ORDER LITTLE_ENDIAN
122 # define BYTE_ORDER BIG_ENDIAN
125 # define BYTE_ORDER __BYTE_ORDER
129 #ifndef LITTLE_ENDIAN
130 #define LITTLE_ENDIAN __LITTLE_ENDIAN
133 #define BIG_ENDIAN __BIG_ENDIAN
136 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
137 #define MISALIGNED_OK 1
143 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
144 # error "Unknown or unsupported endianness (BYTE_ORDER)"
145 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
146 # error "Two's complement, reasonably sized integer types, please"
149 /** @defgroup internal MDB Internals
152 /** @defgroup compat Windows Compatibility Macros
153 * A bunch of macros to minimize the amount of platform-specific ifdefs
154 * needed throughout the rest of the code. When the features this library
155 * needs are similar enough to POSIX to be hidden in a one-or-two line
156 * replacement, this macro approach is used.
160 #define MDB_USE_HASH 1
161 #define MDB_PIDLOCK 0
162 #define pthread_t DWORD
163 #define pthread_mutex_t HANDLE
164 #define pthread_key_t DWORD
165 #define pthread_self() GetCurrentThreadId()
166 #define pthread_key_create(x,y) \
167 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
168 #define pthread_key_delete(x) TlsFree(x)
169 #define pthread_getspecific(x) TlsGetValue(x)
170 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
171 #define pthread_mutex_unlock(x) ReleaseMutex(x)
172 #define pthread_mutex_lock(x) WaitForSingleObject(x, INFINITE)
173 #define LOCK_MUTEX_R(env) pthread_mutex_lock((env)->me_rmutex)
174 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock((env)->me_rmutex)
175 #define LOCK_MUTEX_W(env) pthread_mutex_lock((env)->me_wmutex)
176 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock((env)->me_wmutex)
177 #define getpid() GetCurrentProcessId()
178 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
179 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
180 #define ErrCode() GetLastError()
181 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
182 #define close(fd) (CloseHandle(fd) ? 0 : -1)
183 #define munmap(ptr,len) UnmapViewOfFile(ptr)
184 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
185 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
187 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
192 #define Z "z" /**< printf format modifier for size_t */
194 /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
195 #define MDB_PIDLOCK 1
197 #ifdef MDB_USE_POSIX_SEM
199 #define LOCK_MUTEX_R(env) mdb_sem_wait((env)->me_rmutex)
200 #define UNLOCK_MUTEX_R(env) sem_post((env)->me_rmutex)
201 #define LOCK_MUTEX_W(env) mdb_sem_wait((env)->me_wmutex)
202 #define UNLOCK_MUTEX_W(env) sem_post((env)->me_wmutex)
205 mdb_sem_wait(sem_t *sem)
208 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
213 /** Lock the reader mutex.
215 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
216 /** Unlock the reader mutex.
218 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
220 /** Lock the writer mutex.
221 * Only a single write transaction is allowed at a time. Other writers
222 * will block waiting for this mutex.
224 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
225 /** Unlock the writer mutex.
227 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
228 #endif /* MDB_USE_POSIX_SEM */
230 /** Get the error code for the last failed system function.
232 #define ErrCode() errno
234 /** An abstraction for a file handle.
235 * On POSIX systems file handles are small integers. On Windows
236 * they're opaque pointers.
240 /** A value for an invalid file handle.
241 * Mainly used to initialize file variables and signify that they are
244 #define INVALID_HANDLE_VALUE (-1)
246 /** Get the size of a memory page for the system.
247 * This is the basic size that the platform's memory manager uses, and is
248 * fundamental to the use of memory-mapped files.
250 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
253 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
256 #define MNAME_LEN (sizeof(pthread_mutex_t))
262 /** A flag for opening a file and requesting synchronous data writes.
263 * This is only used when writing a meta page. It's not strictly needed;
264 * we could just do a normal write and then immediately perform a flush.
265 * But if this flag is available it saves us an extra system call.
267 * @note If O_DSYNC is undefined but exists in /usr/include,
268 * preferably set some compiler flag to get the definition.
269 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
272 # define MDB_DSYNC O_DSYNC
276 /** Function for flushing the data of a file. Define this to fsync
277 * if fdatasync() is not supported.
279 #ifndef MDB_FDATASYNC
280 # define MDB_FDATASYNC fdatasync
284 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
295 /** A page number in the database.
296 * Note that 64 bit page numbers are overkill, since pages themselves
297 * already represent 12-13 bits of addressable memory, and the OS will
298 * always limit applications to a maximum of 63 bits of address space.
300 * @note In the #MDB_node structure, we only store 48 bits of this value,
301 * which thus limits us to only 60 bits of addressable data.
303 typedef MDB_ID pgno_t;
305 /** A transaction ID.
306 * See struct MDB_txn.mt_txnid for details.
308 typedef MDB_ID txnid_t;
310 /** @defgroup debug Debug Macros
314 /** Enable debug output. Needs variable argument macros (a C99 feature).
315 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
316 * read from and written to the database (used for free space management).
322 static int mdb_debug;
323 static txnid_t mdb_debug_start;
325 /** Print a debug message with printf formatting.
326 * Requires double parenthesis around 2 or more args.
328 # define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
329 # define DPRINTF0(fmt, ...) \
330 fprintf(stderr, "%s:%d " fmt "\n", __func__, __LINE__, __VA_ARGS__)
332 # define DPRINTF(args) ((void) 0)
334 /** Print a debug string.
335 * The string is printed literally, with no format processing.
337 #define DPUTS(arg) DPRINTF(("%s", arg))
338 /** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
340 (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
343 /** @brief The maximum size of a database page.
345 * This is 32k, since it must fit in #MDB_page.#mp_upper.
347 * LMDB will use database pages < OS pages if needed.
348 * That causes more I/O in write transactions: The OS must
349 * know (read) the whole page before writing a partial page.
351 * Note that we don't currently support Huge pages. On Linux,
352 * regular data files cannot use Huge pages, and in general
353 * Huge pages aren't actually pageable. We rely on the OS
354 * demand-pager to read our data and page it out when memory
355 * pressure from other processes is high. So until OSs have
356 * actual paging support for Huge pages, they're not viable.
358 #define MAX_PAGESIZE 0x8000
360 /** The minimum number of keys required in a database page.
361 * Setting this to a larger value will place a smaller bound on the
362 * maximum size of a data item. Data items larger than this size will
363 * be pushed into overflow pages instead of being stored directly in
364 * the B-tree node. This value used to default to 4. With a page size
365 * of 4096 bytes that meant that any item larger than 1024 bytes would
366 * go into an overflow page. That also meant that on average 2-3KB of
367 * each overflow page was wasted space. The value cannot be lower than
368 * 2 because then there would no longer be a tree structure. With this
369 * value, items larger than 2KB will go into overflow pages, and on
370 * average only 1KB will be wasted.
372 #define MDB_MINKEYS 2
374 /** A stamp that identifies a file as an MDB file.
375 * There's nothing special about this value other than that it is easily
376 * recognizable, and it will reflect any byte order mismatches.
378 #define MDB_MAGIC 0xBEEFC0DE
380 /** The version number for a database's datafile format. */
381 #define MDB_DATA_VERSION 1
382 /** The version number for a database's lockfile format. */
383 #define MDB_LOCK_VERSION 1
385 /** @brief The maximum size of a key in the database.
387 * The library rejects bigger keys, and cannot deal with records
388 * with bigger keys stored by a library with bigger max keysize.
390 * We require that keys all fit onto a regular page. This limit
391 * could be raised a bit further if needed; to something just
392 * under (page size / #MDB_MINKEYS / 3).
394 * Note that data items in an #MDB_DUPSORT database are actually keys
395 * of a subDB, so they're also limited to this size.
397 #ifndef MDB_MAXKEYSIZE
398 #define MDB_MAXKEYSIZE 511
401 /** @brief The maximum size of a data item.
403 * We only store a 32 bit value for node sizes.
405 #define MAXDATASIZE 0xffffffffUL
410 * This is used for printing a hex dump of a key's contents.
412 #define DKBUF char kbuf[(MDB_MAXKEYSIZE*2+1)]
413 /** Display a key in hex.
415 * Invoke a function to display a key in hex.
417 #define DKEY(x) mdb_dkey(x, kbuf)
423 /** An invalid page number.
424 * Mainly used to denote an empty tree.
426 #define P_INVALID (~(pgno_t)0)
428 /** Test if the flags \b f are set in a flag word \b w. */
429 #define F_ISSET(w, f) (((w) & (f)) == (f))
431 /** Round \b n up to an even number. */
432 #define EVEN(n) (((n) + 1U) & -2) /* sign-extending -2 to match n+1U */
434 /** Used for offsets within a single page.
435 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
438 typedef uint16_t indx_t;
440 /** Default size of memory map.
441 * This is certainly too small for any actual applications. Apps should always set
442 * the size explicitly using #mdb_env_set_mapsize().
444 #define DEFAULT_MAPSIZE 1048576
446 /** @defgroup readers Reader Lock Table
447 * Readers don't acquire any locks for their data access. Instead, they
448 * simply record their transaction ID in the reader table. The reader
449 * mutex is needed just to find an empty slot in the reader table. The
450 * slot's address is saved in thread-specific data so that subsequent read
451 * transactions started by the same thread need no further locking to proceed.
453 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
455 * No reader table is used if the database is on a read-only filesystem, or
456 * if #MDB_NOLOCK is set.
458 * Since the database uses multi-version concurrency control, readers don't
459 * actually need any locking. This table is used to keep track of which
460 * readers are using data from which old transactions, so that we'll know
461 * when a particular old transaction is no longer in use. Old transactions
462 * that have discarded any data pages can then have those pages reclaimed
463 * for use by a later write transaction.
465 * The lock table is constructed such that reader slots are aligned with the
466 * processor's cache line size. Any slot is only ever used by one thread.
467 * This alignment guarantees that there will be no contention or cache
468 * thrashing as threads update their own slot info, and also eliminates
469 * any need for locking when accessing a slot.
471 * A writer thread will scan every slot in the table to determine the oldest
472 * outstanding reader transaction. Any freed pages older than this will be
473 * reclaimed by the writer. The writer doesn't use any locks when scanning
474 * this table. This means that there's no guarantee that the writer will
475 * see the most up-to-date reader info, but that's not required for correct
476 * operation - all we need is to know the upper bound on the oldest reader,
477 * we don't care at all about the newest reader. So the only consequence of
478 * reading stale information here is that old pages might hang around a
479 * while longer before being reclaimed. That's actually good anyway, because
480 * the longer we delay reclaiming old pages, the more likely it is that a
481 * string of contiguous pages can be found after coalescing old pages from
482 * many old transactions together.
485 /** Number of slots in the reader table.
486 * This value was chosen somewhat arbitrarily. 126 readers plus a
487 * couple mutexes fit exactly into 8KB on my development machine.
488 * Applications should set the table size using #mdb_env_set_maxreaders().
490 #define DEFAULT_READERS 126
492 /** The size of a CPU cache line in bytes. We want our lock structures
493 * aligned to this size to avoid false cache line sharing in the
495 * This value works for most CPUs. For Itanium this should be 128.
501 /** The information we store in a single slot of the reader table.
502 * In addition to a transaction ID, we also record the process and
503 * thread ID that owns a slot, so that we can detect stale information,
504 * e.g. threads or processes that went away without cleaning up.
505 * @note We currently don't check for stale records. We simply re-init
506 * the table when we know that we're the only process opening the
509 typedef struct MDB_rxbody {
510 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
511 * Multiple readers that start at the same time will probably have the
512 * same ID here. Again, it's not important to exclude them from
513 * anything; all we need to know is which version of the DB they
514 * started from so we can avoid overwriting any data used in that
515 * particular version.
518 /** The process ID of the process owning this reader txn. */
520 /** The thread ID of the thread owning this txn. */
524 /** The actual reader record, with cacheline padding. */
525 typedef struct MDB_reader {
528 /** shorthand for mrb_txnid */
529 #define mr_txnid mru.mrx.mrb_txnid
530 #define mr_pid mru.mrx.mrb_pid
531 #define mr_tid mru.mrx.mrb_tid
532 /** cache line alignment */
533 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
537 /** The header for the reader table.
538 * The table resides in a memory-mapped file. (This is a different file
539 * than is used for the main database.)
541 * For POSIX the actual mutexes reside in the shared memory of this
542 * mapped file. On Windows, mutexes are named objects allocated by the
543 * kernel; we store the mutex names in this mapped file so that other
544 * processes can grab them. This same approach is also used on
545 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
546 * process-shared POSIX mutexes. For these cases where a named object
547 * is used, the object name is derived from a 64 bit FNV hash of the
548 * environment pathname. As such, naming collisions are extremely
549 * unlikely. If a collision occurs, the results are unpredictable.
551 typedef struct MDB_txbody {
552 /** Stamp identifying this as an MDB file. It must be set
555 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
557 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
558 char mtb_rmname[MNAME_LEN];
560 /** Mutex protecting access to this table.
561 * This is the reader lock that #LOCK_MUTEX_R acquires.
563 pthread_mutex_t mtb_mutex;
565 /** The ID of the last transaction committed to the database.
566 * This is recorded here only for convenience; the value can always
567 * be determined by reading the main database meta pages.
570 /** The number of slots that have been used in the reader table.
571 * This always records the maximum count, it is not decremented
572 * when readers release their slots.
574 unsigned mtb_numreaders;
577 /** The actual reader table definition. */
578 typedef struct MDB_txninfo {
581 #define mti_magic mt1.mtb.mtb_magic
582 #define mti_format mt1.mtb.mtb_format
583 #define mti_mutex mt1.mtb.mtb_mutex
584 #define mti_rmname mt1.mtb.mtb_rmname
585 #define mti_txnid mt1.mtb.mtb_txnid
586 #define mti_numreaders mt1.mtb.mtb_numreaders
587 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
590 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
591 char mt2_wmname[MNAME_LEN];
592 #define mti_wmname mt2.mt2_wmname
594 pthread_mutex_t mt2_wmutex;
595 #define mti_wmutex mt2.mt2_wmutex
597 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
599 MDB_reader mti_readers[1];
602 /** Lockfile format signature: version, features and field layout */
603 #define MDB_LOCK_FORMAT \
605 ((MDB_LOCK_VERSION) \
606 /* Flags which describe functionality */ \
607 + (((MDB_PIDLOCK) != 0) << 16)))
610 /** Common header for all page types.
611 * Overflow records occupy a number of contiguous pages with no
612 * headers on any page after the first.
614 typedef struct MDB_page {
615 #define mp_pgno mp_p.p_pgno
616 #define mp_next mp_p.p_next
618 pgno_t p_pgno; /**< page number */
619 void * p_next; /**< for in-memory list of freed structs */
622 /** @defgroup mdb_page Page Flags
624 * Flags for the page headers.
627 #define P_BRANCH 0x01 /**< branch page */
628 #define P_LEAF 0x02 /**< leaf page */
629 #define P_OVERFLOW 0x04 /**< overflow page */
630 #define P_META 0x08 /**< meta page */
631 #define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
632 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
633 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
634 #define P_KEEP 0x8000 /**< leave this page alone during spill */
636 uint16_t mp_flags; /**< @ref mdb_page */
637 #define mp_lower mp_pb.pb.pb_lower
638 #define mp_upper mp_pb.pb.pb_upper
639 #define mp_pages mp_pb.pb_pages
642 indx_t pb_lower; /**< lower bound of free space */
643 indx_t pb_upper; /**< upper bound of free space */
645 uint32_t pb_pages; /**< number of overflow pages */
647 indx_t mp_ptrs[1]; /**< dynamic size */
650 /** Size of the page header, excluding dynamic data at the end */
651 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
653 /** Address of first usable data byte in a page, after the header */
654 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
656 /** Number of nodes on a page */
657 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
659 /** The amount of space remaining in the page */
660 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
662 /** The percentage of space used in the page, in tenths of a percent. */
663 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
664 ((env)->me_psize - PAGEHDRSZ))
665 /** The minimum page fill factor, in tenths of a percent.
666 * Pages emptier than this are candidates for merging.
668 #define FILL_THRESHOLD 250
670 /** Test if a page is a leaf page */
671 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
672 /** Test if a page is a LEAF2 page */
673 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
674 /** Test if a page is a branch page */
675 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
676 /** Test if a page is an overflow page */
677 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
678 /** Test if a page is a sub page */
679 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
681 /** The number of overflow pages needed to store the given size. */
682 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
684 /** Header for a single key/data pair within a page.
685 * We guarantee 2-byte alignment for nodes.
687 typedef struct MDB_node {
688 /** lo and hi are used for data size on leaf nodes and for
689 * child pgno on branch nodes. On 64 bit platforms, flags
690 * is also used for pgno. (Branch nodes have no flags).
691 * They are in host byte order in case that lets some
692 * accesses be optimized into a 32-bit word access.
694 #define mn_lo mn_offset[BYTE_ORDER!=LITTLE_ENDIAN]
695 #define mn_hi mn_offset[BYTE_ORDER==LITTLE_ENDIAN] /**< part of dsize or pgno */
696 unsigned short mn_offset[2]; /**< storage for #mn_lo and #mn_hi */
697 /** @defgroup mdb_node Node Flags
699 * Flags for node headers.
702 #define F_BIGDATA 0x01 /**< data put on overflow page */
703 #define F_SUBDATA 0x02 /**< data is a sub-database */
704 #define F_DUPDATA 0x04 /**< data has duplicates */
706 /** valid flags for #mdb_node_add() */
707 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
710 unsigned short mn_flags; /**< @ref mdb_node */
711 unsigned short mn_ksize; /**< key size */
712 char mn_data[1]; /**< key and data are appended here */
715 /** Size of the node header, excluding dynamic data at the end */
716 #define NODESIZE offsetof(MDB_node, mn_data)
718 /** Bit position of top word in page number, for shifting mn_flags */
719 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
721 /** Size of a node in a branch page with a given key.
722 * This is just the node header plus the key, there is no data.
724 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
726 /** Size of a node in a leaf page with a given key and data.
727 * This is node header plus key plus data size.
729 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
731 /** Address of node \b i in page \b p */
732 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
734 /** Address of the key for the node */
735 #define NODEKEY(node) (void *)((node)->mn_data)
737 /** Address of the data for a node */
738 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
740 /** Get the page number pointed to by a branch node */
741 #define NODEPGNO(node) \
742 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
743 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
744 /** Set the page number in a branch node */
745 #define SETPGNO(node,pgno) do { \
746 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
747 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
749 /** Get the size of the data in a leaf node */
750 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
751 /** Set the size of the data for a leaf node */
752 #define SETDSZ(node,size) do { \
753 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
754 /** The size of a key in a node */
755 #define NODEKSZ(node) ((node)->mn_ksize)
757 /** Copy a page number from src to dst */
759 #define COPY_PGNO(dst,src) dst = src
761 #if SIZE_MAX > 4294967295UL
762 #define COPY_PGNO(dst,src) do { \
763 unsigned short *s, *d; \
764 s = (unsigned short *)&(src); \
765 d = (unsigned short *)&(dst); \
772 #define COPY_PGNO(dst,src) do { \
773 unsigned short *s, *d; \
774 s = (unsigned short *)&(src); \
775 d = (unsigned short *)&(dst); \
781 /** The address of a key in a LEAF2 page.
782 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
783 * There are no node headers, keys are stored contiguously.
785 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
787 /** Set the \b node's key into \b keyptr, if requested. */
788 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
789 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
791 /** Set the \b node's key into \b key. */
792 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
794 /** Information about a single database in the environment. */
795 typedef struct MDB_db {
796 uint32_t md_pad; /**< also ksize for LEAF2 pages */
797 uint16_t md_flags; /**< @ref mdb_dbi_open */
798 uint16_t md_depth; /**< depth of this tree */
799 pgno_t md_branch_pages; /**< number of internal pages */
800 pgno_t md_leaf_pages; /**< number of leaf pages */
801 pgno_t md_overflow_pages; /**< number of overflow pages */
802 size_t md_entries; /**< number of data items */
803 pgno_t md_root; /**< the root page of this tree */
806 /** mdb_dbi_open flags */
807 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
808 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
809 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
810 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
812 /** Handle for the DB used to track free pages. */
814 /** Handle for the default DB. */
817 /** Meta page content.
818 * A meta page is the start point for accessing a database snapshot.
819 * Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
821 typedef struct MDB_meta {
822 /** Stamp identifying this as an MDB file. It must be set
825 /** Version number of this lock file. Must be set to #MDB_DATA_VERSION. */
827 void *mm_address; /**< address for fixed mapping */
828 size_t mm_mapsize; /**< size of mmap region */
829 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
830 /** The size of pages used in this DB */
831 #define mm_psize mm_dbs[0].md_pad
832 /** Any persistent environment flags. @ref mdb_env */
833 #define mm_flags mm_dbs[0].md_flags
834 pgno_t mm_last_pg; /**< last used page in file */
835 txnid_t mm_txnid; /**< txnid that committed this page */
838 /** Buffer for a stack-allocated meta page.
839 * The members define size and alignment, and silence type
840 * aliasing warnings. They are not used directly; that could
841 * mean incorrectly using several union members in parallel.
843 typedef union MDB_metabuf {
846 char mm_pad[PAGEHDRSZ];
851 /** Auxiliary DB info.
852 * The information here is mostly static/read-only. There is
853 * only a single copy of this record in the environment.
855 typedef struct MDB_dbx {
856 MDB_val md_name; /**< name of the database */
857 MDB_cmp_func *md_cmp; /**< function for comparing keys */
858 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
859 MDB_rel_func *md_rel; /**< user relocate function */
860 void *md_relctx; /**< user-provided context for md_rel */
863 /** A database transaction.
864 * Every operation requires a transaction handle.
867 MDB_txn *mt_parent; /**< parent of a nested txn */
868 MDB_txn *mt_child; /**< nested txn under this txn */
869 pgno_t mt_next_pgno; /**< next unallocated page */
870 /** The ID of this transaction. IDs are integers incrementing from 1.
871 * Only committed write transactions increment the ID. If a transaction
872 * aborts, the ID may be re-used by the next writer.
875 MDB_env *mt_env; /**< the DB environment */
876 /** The list of pages that became unused during this transaction.
879 /** The sorted list of dirty pages we temporarily wrote to disk
880 * because the dirty list was full. page numbers in here are
881 * shifted left by 1, deleted slots have the LSB set.
883 MDB_IDL mt_spill_pgs;
885 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
887 /** For read txns: This thread/txn's reader table slot, or NULL. */
890 /** Array of records for each DB known in the environment. */
892 /** Array of MDB_db records for each known DB */
894 /** @defgroup mt_dbflag Transaction DB Flags
898 #define DB_DIRTY 0x01 /**< DB was modified or is DUPSORT data */
899 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
900 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
901 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
903 /** In write txns, array of cursors for each DB */
904 MDB_cursor **mt_cursors;
905 /** Array of flags for each DB */
906 unsigned char *mt_dbflags;
907 /** Number of DB records in use. This number only ever increments;
908 * we don't decrement it when individual DB handles are closed.
912 /** @defgroup mdb_txn Transaction Flags
916 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
917 #define MDB_TXN_ERROR 0x02 /**< an error has occurred */
918 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
919 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
921 unsigned int mt_flags; /**< @ref mdb_txn */
922 /** dirty_list room: Array size - #dirty pages visible to this txn.
923 * Includes ancestor txns' dirty pages not hidden by other txns'
924 * dirty/spilled pages. Thus commit(nested txn) has room to merge
925 * dirty_list into mt_parent after freeing hidden mt_parent pages.
927 unsigned int mt_dirty_room;
930 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
931 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
932 * raise this on a 64 bit machine.
934 #define CURSOR_STACK 32
938 /** Cursors are used for all DB operations.
939 * A cursor holds a path of (page pointer, key index) from the DB
940 * root to a position in the DB, plus other state. #MDB_DUPSORT
941 * cursors include an xcursor to the current data item. Write txns
942 * track their cursors and keep them up to date when data moves.
943 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
944 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
947 /** Next cursor on this DB in this txn */
949 /** Backup of the original cursor if this cursor is a shadow */
950 MDB_cursor *mc_backup;
951 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
952 struct MDB_xcursor *mc_xcursor;
953 /** The transaction that owns this cursor */
955 /** The database handle this cursor operates on */
957 /** The database record for this cursor */
959 /** The database auxiliary record for this cursor */
961 /** The @ref mt_dbflag for this database */
962 unsigned char *mc_dbflag;
963 unsigned short mc_snum; /**< number of pushed pages */
964 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
965 /** @defgroup mdb_cursor Cursor Flags
967 * Cursor state flags.
970 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
971 #define C_EOF 0x02 /**< No more data */
972 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
973 #define C_DEL 0x08 /**< last op was a cursor_del */
974 #define C_SPLITTING 0x20 /**< Cursor is in page_split */
975 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
977 unsigned int mc_flags; /**< @ref mdb_cursor */
978 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
979 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
982 /** Context for sorted-dup records.
983 * We could have gone to a fully recursive design, with arbitrarily
984 * deep nesting of sub-databases. But for now we only handle these
985 * levels - main DB, optional sub-DB, sorted-duplicate DB.
987 typedef struct MDB_xcursor {
988 /** A sub-cursor for traversing the Dup DB */
989 MDB_cursor mx_cursor;
990 /** The database record for this Dup DB */
992 /** The auxiliary DB record for this Dup DB */
994 /** The @ref mt_dbflag for this Dup DB */
995 unsigned char mx_dbflag;
998 /** State of FreeDB old pages, stored in the MDB_env */
999 typedef struct MDB_pgstate {
1000 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1001 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1004 /** The database environment. */
1006 HANDLE me_fd; /**< The main data file */
1007 HANDLE me_lfd; /**< The lock file */
1008 HANDLE me_mfd; /**< just for writing the meta pages */
1009 /** Failed to update the meta page. Probably an I/O error. */
1010 #define MDB_FATAL_ERROR 0x80000000U
1011 /** Some fields are initialized. */
1012 #define MDB_ENV_ACTIVE 0x20000000U
1013 /** me_txkey is set */
1014 #define MDB_ENV_TXKEY 0x10000000U
1015 /** Have liveness lock in reader table */
1016 #define MDB_LIVE_READER 0x08000000U
1017 uint32_t me_flags; /**< @ref mdb_env */
1018 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1019 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1020 unsigned int me_maxreaders; /**< size of the reader table */
1021 unsigned int me_numreaders; /**< max numreaders set by this env */
1022 MDB_dbi me_numdbs; /**< number of DBs opened */
1023 MDB_dbi me_maxdbs; /**< size of the DB table */
1024 MDB_PID_T me_pid; /**< process ID of this env */
1025 char *me_path; /**< path to the DB files */
1026 char *me_map; /**< the memory map of the data file */
1027 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1028 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
1029 void *me_pbuf; /**< scratch area for DUPSORT put() */
1030 MDB_txn *me_txn; /**< current write transaction */
1031 size_t me_mapsize; /**< size of the data memory map */
1032 off_t me_size; /**< current file size */
1033 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1034 MDB_dbx *me_dbxs; /**< array of static DB info */
1035 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1036 pthread_key_t me_txkey; /**< thread-key for readers */
1037 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1038 # define me_pglast me_pgstate.mf_pglast
1039 # define me_pghead me_pgstate.mf_pghead
1040 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1041 /** IDL of pages that became unused in a write txn */
1042 MDB_IDL me_free_pgs;
1043 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1044 MDB_ID2L me_dirty_list;
1045 /** Max number of freelist items that can fit in a single overflow page */
1047 /** Max size of a node on a page */
1048 unsigned int me_nodemax;
1050 int me_pidquery; /**< Used in OpenProcess */
1051 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
1053 #elif defined(MDB_USE_POSIX_SEM)
1054 sem_t *me_rmutex; /* Shared mutexes are not supported */
1059 /** Nested transaction */
1060 typedef struct MDB_ntxn {
1061 MDB_txn mnt_txn; /**< the transaction */
1062 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1065 /** max number of pages to commit in one writev() call */
1066 #define MDB_COMMIT_PAGES 64
1067 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1068 #undef MDB_COMMIT_PAGES
1069 #define MDB_COMMIT_PAGES IOV_MAX
1072 /* max bytes to write in one call */
1073 #define MAX_WRITE (0x80000000U >> (sizeof(ssize_t) == 4))
1075 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1076 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1077 static int mdb_page_touch(MDB_cursor *mc);
1079 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp, int *lvl);
1080 static int mdb_page_search_root(MDB_cursor *mc,
1081 MDB_val *key, int modify);
1082 #define MDB_PS_MODIFY 1
1083 #define MDB_PS_ROOTONLY 2
1084 #define MDB_PS_FIRST 4
1085 #define MDB_PS_LAST 8
1086 static int mdb_page_search(MDB_cursor *mc,
1087 MDB_val *key, int flags);
1088 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1090 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1091 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1092 pgno_t newpgno, unsigned int nflags);
1094 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1095 static int mdb_env_pick_meta(const MDB_env *env);
1096 static int mdb_env_write_meta(MDB_txn *txn);
1097 #if !(defined(_WIN32) || defined(MDB_USE_POSIX_SEM)) /* Drop unused excl arg */
1098 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1100 static void mdb_env_close0(MDB_env *env, int excl);
1102 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1103 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1104 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1105 static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
1106 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1107 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
1108 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1109 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1110 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1112 static int mdb_rebalance(MDB_cursor *mc);
1113 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1115 static void mdb_cursor_pop(MDB_cursor *mc);
1116 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1118 static int mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
1119 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1120 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1121 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1122 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1124 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1125 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1127 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1128 static void mdb_xcursor_init0(MDB_cursor *mc);
1129 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1131 static int mdb_drop0(MDB_cursor *mc, int subs);
1132 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1135 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1139 static SECURITY_DESCRIPTOR mdb_null_sd;
1140 static SECURITY_ATTRIBUTES mdb_all_sa;
1141 static int mdb_sec_inited;
1144 /** Return the library version info. */
1146 mdb_version(int *major, int *minor, int *patch)
1148 if (major) *major = MDB_VERSION_MAJOR;
1149 if (minor) *minor = MDB_VERSION_MINOR;
1150 if (patch) *patch = MDB_VERSION_PATCH;
1151 return MDB_VERSION_STRING;
1154 /** Table of descriptions for MDB @ref errors */
1155 static char *const mdb_errstr[] = {
1156 "MDB_KEYEXIST: Key/data pair already exists",
1157 "MDB_NOTFOUND: No matching key/data pair found",
1158 "MDB_PAGE_NOTFOUND: Requested page not found",
1159 "MDB_CORRUPTED: Located page was wrong type",
1160 "MDB_PANIC: Update of meta page failed",
1161 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1162 "MDB_INVALID: File is not an MDB file",
1163 "MDB_MAP_FULL: Environment mapsize limit reached",
1164 "MDB_DBS_FULL: Environment maxdbs limit reached",
1165 "MDB_READERS_FULL: Environment maxreaders limit reached",
1166 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1167 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1168 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1169 "MDB_PAGE_FULL: Internal error - page has no more space",
1170 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1171 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1172 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1173 "MDB_BAD_TXN: Transaction cannot recover - it must be aborted",
1174 "MDB_BAD_VALSIZE: Too big key/data, key is empty, or wrong DUPFIXED size",
1178 mdb_strerror(int err)
1182 return ("Successful return: 0");
1184 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1185 i = err - MDB_KEYEXIST;
1186 return mdb_errstr[i];
1189 return strerror(err);
1193 /** Display a key in hexadecimal and return the address of the result.
1194 * @param[in] key the key to display
1195 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1196 * @return The key in hexadecimal form.
1199 mdb_dkey(MDB_val *key, char *buf)
1202 unsigned char *c = key->mv_data;
1208 if (key->mv_size > MDB_MAXKEYSIZE)
1209 return "MDB_MAXKEYSIZE";
1210 /* may want to make this a dynamic check: if the key is mostly
1211 * printable characters, print it as-is instead of converting to hex.
1215 for (i=0; i<key->mv_size; i++)
1216 ptr += sprintf(ptr, "%02x", *c++);
1218 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1223 /** Display all the keys in the page. */
1225 mdb_page_list(MDB_page *mp)
1228 unsigned int i, nkeys, nsize, total = 0;
1232 nkeys = NUMKEYS(mp);
1233 fprintf(stderr, "Page %"Z"u numkeys %d\n", mp->mp_pgno, nkeys);
1234 for (i=0; i<nkeys; i++) {
1235 node = NODEPTR(mp, i);
1236 key.mv_size = node->mn_ksize;
1237 key.mv_data = node->mn_data;
1238 nsize = NODESIZE + key.mv_size;
1239 if (IS_BRANCH(mp)) {
1240 fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
1244 if (F_ISSET(node->mn_flags, F_BIGDATA))
1245 nsize += sizeof(pgno_t);
1247 nsize += NODEDSZ(node);
1249 nsize += sizeof(indx_t);
1250 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1252 total = EVEN(total);
1254 fprintf(stderr, "Total: %d\n", total);
1258 mdb_cursor_chk(MDB_cursor *mc)
1264 if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1265 for (i=0; i<mc->mc_top; i++) {
1267 node = NODEPTR(mp, mc->mc_ki[i]);
1268 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1271 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1277 /** Count all the pages in each DB and in the freelist
1278 * and make sure it matches the actual number of pages
1281 static void mdb_audit(MDB_txn *txn)
1285 MDB_ID freecount, count;
1290 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1291 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1292 freecount += *(MDB_ID *)data.mv_data;
1295 for (i = 0; i<txn->mt_numdbs; i++) {
1297 mdb_cursor_init(&mc, txn, i, &mx);
1298 if (txn->mt_dbs[i].md_root == P_INVALID)
1300 count += txn->mt_dbs[i].md_branch_pages +
1301 txn->mt_dbs[i].md_leaf_pages +
1302 txn->mt_dbs[i].md_overflow_pages;
1303 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1304 mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1308 mp = mc.mc_pg[mc.mc_top];
1309 for (j=0; j<NUMKEYS(mp); j++) {
1310 MDB_node *leaf = NODEPTR(mp, j);
1311 if (leaf->mn_flags & F_SUBDATA) {
1313 memcpy(&db, NODEDATA(leaf), sizeof(db));
1314 count += db.md_branch_pages + db.md_leaf_pages +
1315 db.md_overflow_pages;
1319 while (mdb_cursor_sibling(&mc, 1) == 0);
1322 if (freecount + count + 2 /* metapages */ != txn->mt_next_pgno) {
1323 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1324 txn->mt_txnid, freecount, count+2, freecount+count+2, txn->mt_next_pgno);
1330 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1332 return txn->mt_dbxs[dbi].md_cmp(a, b);
1336 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1338 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1341 /** Allocate memory for a page.
1342 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1345 mdb_page_malloc(MDB_txn *txn, unsigned num)
1347 MDB_env *env = txn->mt_env;
1348 MDB_page *ret = env->me_dpages;
1349 size_t psize = env->me_psize, sz = psize, off;
1350 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1351 * For a single page alloc, we init everything after the page header.
1352 * For multi-page, we init the final page; if the caller needed that
1353 * many pages they will be filling in at least up to the last page.
1357 VGMEMP_ALLOC(env, ret, sz);
1358 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1359 env->me_dpages = ret->mp_next;
1362 psize -= off = PAGEHDRSZ;
1367 if ((ret = malloc(sz)) != NULL) {
1368 if (!(env->me_flags & MDB_NOMEMINIT)) {
1369 memset((char *)ret + off, 0, psize);
1372 VGMEMP_ALLOC(env, ret, sz);
1377 /** Free a single page.
1378 * Saves single pages to a list, for future reuse.
1379 * (This is not used for multi-page overflow pages.)
1382 mdb_page_free(MDB_env *env, MDB_page *mp)
1384 mp->mp_next = env->me_dpages;
1385 VGMEMP_FREE(env, mp);
1386 env->me_dpages = mp;
1389 /** Free a dirty page */
1391 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1393 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1394 mdb_page_free(env, dp);
1396 /* large pages just get freed directly */
1397 VGMEMP_FREE(env, dp);
1402 /** Return all dirty pages to dpage list */
1404 mdb_dlist_free(MDB_txn *txn)
1406 MDB_env *env = txn->mt_env;
1407 MDB_ID2L dl = txn->mt_u.dirty_list;
1408 unsigned i, n = dl[0].mid;
1410 for (i = 1; i <= n; i++) {
1411 mdb_dpage_free(env, dl[i].mptr);
1416 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
1417 * @param[in] mc A cursor handle for the current operation.
1418 * @param[in] pflags Flags of the pages to update:
1419 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1420 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
1421 * @return 0 on success, non-zero on failure.
1424 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
1426 enum { Mask = P_SUBP|P_DIRTY|P_KEEP };
1427 MDB_txn *txn = mc->mc_txn;
1433 int rc = MDB_SUCCESS, level;
1435 /* Mark pages seen by cursors */
1436 if (mc->mc_flags & C_UNTRACK)
1437 mc = NULL; /* will find mc in mt_cursors */
1438 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1439 for (; mc; mc=mc->mc_next) {
1440 if (!(mc->mc_flags & C_INITIALIZED))
1442 for (m3 = mc;; m3 = &mx->mx_cursor) {
1444 for (j=0; j<m3->mc_snum; j++) {
1446 if ((mp->mp_flags & Mask) == pflags)
1447 mp->mp_flags ^= P_KEEP;
1449 mx = m3->mc_xcursor;
1450 /* Proceed to mx if it is at a sub-database */
1451 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
1453 if (! (mp && (mp->mp_flags & P_LEAF)))
1455 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
1456 if (!(leaf->mn_flags & F_SUBDATA))
1465 /* Mark dirty root pages */
1466 for (i=0; i<txn->mt_numdbs; i++) {
1467 if (txn->mt_dbflags[i] & DB_DIRTY) {
1468 pgno_t pgno = txn->mt_dbs[i].md_root;
1469 if (pgno == P_INVALID)
1471 if ((rc = mdb_page_get(txn, pgno, &dp, &level)) != MDB_SUCCESS)
1473 if ((dp->mp_flags & Mask) == pflags && level <= 1)
1474 dp->mp_flags ^= P_KEEP;
1482 static int mdb_page_flush(MDB_txn *txn, int keep);
1484 /** Spill pages from the dirty list back to disk.
1485 * This is intended to prevent running into #MDB_TXN_FULL situations,
1486 * but note that they may still occur in a few cases:
1487 * 1) our estimate of the txn size could be too small. Currently this
1488 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
1489 * 2) child txns may run out of space if their parents dirtied a
1490 * lot of pages and never spilled them. TODO: we probably should do
1491 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1492 * the parent's dirty_room is below a given threshold.
1494 * Otherwise, if not using nested txns, it is expected that apps will
1495 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1496 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1497 * If the txn never references them again, they can be left alone.
1498 * If the txn only reads them, they can be used without any fuss.
1499 * If the txn writes them again, they can be dirtied immediately without
1500 * going thru all of the work of #mdb_page_touch(). Such references are
1501 * handled by #mdb_page_unspill().
1503 * Also note, we never spill DB root pages, nor pages of active cursors,
1504 * because we'll need these back again soon anyway. And in nested txns,
1505 * we can't spill a page in a child txn if it was already spilled in a
1506 * parent txn. That would alter the parent txns' data even though
1507 * the child hasn't committed yet, and we'd have no way to undo it if
1508 * the child aborted.
1510 * @param[in] m0 cursor A cursor handle identifying the transaction and
1511 * database for which we are checking space.
1512 * @param[in] key For a put operation, the key being stored.
1513 * @param[in] data For a put operation, the data being stored.
1514 * @return 0 on success, non-zero on failure.
1517 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1519 MDB_txn *txn = m0->mc_txn;
1521 MDB_ID2L dl = txn->mt_u.dirty_list;
1522 unsigned int i, j, need;
1525 if (m0->mc_flags & C_SUB)
1528 /* Estimate how much space this op will take */
1529 i = m0->mc_db->md_depth;
1530 /* Named DBs also dirty the main DB */
1531 if (m0->mc_dbi > MAIN_DBI)
1532 i += txn->mt_dbs[MAIN_DBI].md_depth;
1533 /* For puts, roughly factor in the key+data size */
1535 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
1536 i += i; /* double it for good measure */
1539 if (txn->mt_dirty_room > i)
1542 if (!txn->mt_spill_pgs) {
1543 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
1544 if (!txn->mt_spill_pgs)
1547 /* purge deleted slots */
1548 MDB_IDL sl = txn->mt_spill_pgs;
1549 unsigned int num = sl[0];
1551 for (i=1; i<=num; i++) {
1558 /* Preserve pages which may soon be dirtied again */
1559 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
1562 /* Less aggressive spill - we originally spilled the entire dirty list,
1563 * with a few exceptions for cursor pages and DB root pages. But this
1564 * turns out to be a lot of wasted effort because in a large txn many
1565 * of those pages will need to be used again. So now we spill only 1/8th
1566 * of the dirty pages. Testing revealed this to be a good tradeoff,
1567 * better than 1/2, 1/4, or 1/10.
1569 if (need < MDB_IDL_UM_MAX / 8)
1570 need = MDB_IDL_UM_MAX / 8;
1572 /* Save the page IDs of all the pages we're flushing */
1573 /* flush from the tail forward, this saves a lot of shifting later on. */
1574 for (i=dl[0].mid; i && need; i--) {
1575 MDB_ID pn = dl[i].mid << 1;
1577 if (dp->mp_flags & P_KEEP)
1579 /* Can't spill twice, make sure it's not already in a parent's
1582 if (txn->mt_parent) {
1584 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1585 if (tx2->mt_spill_pgs) {
1586 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
1587 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
1588 dp->mp_flags |= P_KEEP;
1596 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
1600 mdb_midl_sort(txn->mt_spill_pgs);
1602 /* Flush the spilled part of dirty list */
1603 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
1606 /* Reset any dirty pages we kept that page_flush didn't see */
1607 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
1610 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
1614 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
1616 mdb_find_oldest(MDB_txn *txn)
1619 txnid_t mr, oldest = txn->mt_txnid - 1;
1620 if (txn->mt_env->me_txns) {
1621 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
1622 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
1633 /** Add a page to the txn's dirty list */
1635 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
1638 int (*insert)(MDB_ID2L, MDB_ID2 *);
1640 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1641 insert = mdb_mid2l_append;
1643 insert = mdb_mid2l_insert;
1645 mid.mid = mp->mp_pgno;
1647 insert(txn->mt_u.dirty_list, &mid);
1648 txn->mt_dirty_room--;
1651 /** Allocate page numbers and memory for writing. Maintain me_pglast,
1652 * me_pghead and mt_next_pgno.
1654 * If there are free pages available from older transactions, they
1655 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
1656 * Do not modify the freedB, just merge freeDB records into me_pghead[]
1657 * and move me_pglast to say which records were consumed. Only this
1658 * function can create me_pghead and move me_pglast/mt_next_pgno.
1659 * @param[in] mc cursor A cursor handle identifying the transaction and
1660 * database for which we are allocating.
1661 * @param[in] num the number of pages to allocate.
1662 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
1663 * will always be satisfied by a single contiguous chunk of memory.
1664 * @return 0 on success, non-zero on failure.
1667 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
1669 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
1670 /* Get at most <Max_retries> more freeDB records once me_pghead
1671 * has enough pages. If not enough, use new pages from the map.
1672 * If <Paranoid> and mc is updating the freeDB, only get new
1673 * records if me_pghead is empty. Then the freelist cannot play
1674 * catch-up with itself by growing while trying to save it.
1676 enum { Paranoid = 1, Max_retries = 500 };
1678 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
1680 int rc, retry = Max_retries;
1681 MDB_txn *txn = mc->mc_txn;
1682 MDB_env *env = txn->mt_env;
1683 pgno_t pgno, *mop = env->me_pghead;
1684 unsigned i, j, k, mop_len = mop ? mop[0] : 0, n2 = num-1;
1686 txnid_t oldest = 0, last;
1692 /* If our dirty list is already full, we can't do anything */
1693 if (txn->mt_dirty_room == 0)
1694 return MDB_TXN_FULL;
1696 for (op = MDB_FIRST;; op = MDB_NEXT) {
1699 pgno_t *idl, old_id, new_id;
1701 /* Seek a big enough contiguous page range. Prefer
1702 * pages at the tail, just truncating the list.
1708 if (mop[i-n2] == pgno+n2)
1711 if (Max_retries < INT_MAX && --retry < 0)
1715 if (op == MDB_FIRST) { /* 1st iteration */
1716 /* Prepare to fetch more and coalesce */
1717 oldest = mdb_find_oldest(txn);
1718 last = env->me_pglast;
1719 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1722 key.mv_data = &last; /* will look up last+1 */
1723 key.mv_size = sizeof(last);
1725 if (Paranoid && mc->mc_dbi == FREE_DBI)
1728 if (Paranoid && retry < 0 && mop_len)
1732 /* Do not fetch more if the record will be too recent */
1735 rc = mdb_cursor_get(&m2, &key, NULL, op);
1737 if (rc == MDB_NOTFOUND)
1741 last = *(txnid_t*)key.mv_data;
1744 np = m2.mc_pg[m2.mc_top];
1745 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
1746 if ((rc = mdb_node_read(txn, leaf, &data)) != MDB_SUCCESS)
1749 idl = (MDB_ID *) data.mv_data;
1752 if (!(env->me_pghead = mop = mdb_midl_alloc(i)))
1755 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
1757 mop = env->me_pghead;
1759 env->me_pglast = last;
1761 DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
1762 last, txn->mt_dbs[FREE_DBI].md_root, i));
1764 DPRINTF(("IDL %"Z"u", idl[k]));
1766 /* Merge in descending sorted order */
1769 mop[0] = (pgno_t)-1;
1773 for (; old_id < new_id; old_id = mop[--j])
1780 /* Use new pages from the map when nothing suitable in the freeDB */
1782 pgno = txn->mt_next_pgno;
1783 if (pgno + num >= env->me_maxpg) {
1784 DPUTS("DB size maxed out");
1785 return MDB_MAP_FULL;
1789 if (env->me_flags & MDB_WRITEMAP) {
1790 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
1792 if (!(np = mdb_page_malloc(txn, num)))
1796 mop[0] = mop_len -= num;
1797 /* Move any stragglers down */
1798 for (j = i-num; j < mop_len; )
1799 mop[++j] = mop[++i];
1801 txn->mt_next_pgno = pgno + num;
1804 mdb_page_dirty(txn, np);
1810 /** Copy the used portions of a non-overflow page.
1811 * @param[in] dst page to copy into
1812 * @param[in] src page to copy from
1813 * @param[in] psize size of a page
1816 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
1818 enum { Align = sizeof(pgno_t) };
1819 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
1821 /* If page isn't full, just copy the used portion. Adjust
1822 * alignment so memcpy may copy words instead of bytes.
1824 if ((unused &= -Align) && !IS_LEAF2(src)) {
1826 memcpy(dst, src, (lower + (Align-1)) & -Align);
1827 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
1830 memcpy(dst, src, psize - unused);
1834 /** Pull a page off the txn's spill list, if present.
1835 * If a page being referenced was spilled to disk in this txn, bring
1836 * it back and make it dirty/writable again.
1837 * @param[in] txn the transaction handle.
1838 * @param[in] mp the page being referenced.
1839 * @param[out] ret the writable page, if any. ret is unchanged if
1840 * mp wasn't spilled.
1843 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
1845 MDB_env *env = txn->mt_env;
1848 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
1850 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
1851 if (!tx2->mt_spill_pgs)
1853 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
1854 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
1857 if (txn->mt_dirty_room == 0)
1858 return MDB_TXN_FULL;
1859 if (IS_OVERFLOW(mp))
1863 if (env->me_flags & MDB_WRITEMAP) {
1866 np = mdb_page_malloc(txn, num);
1870 memcpy(np, mp, num * env->me_psize);
1872 mdb_page_copy(np, mp, env->me_psize);
1875 /* If in current txn, this page is no longer spilled.
1876 * If it happens to be the last page, truncate the spill list.
1877 * Otherwise mark it as deleted by setting the LSB.
1879 if (x == txn->mt_spill_pgs[0])
1880 txn->mt_spill_pgs[0]--;
1882 txn->mt_spill_pgs[x] |= 1;
1883 } /* otherwise, if belonging to a parent txn, the
1884 * page remains spilled until child commits
1887 mdb_page_dirty(txn, np);
1888 np->mp_flags |= P_DIRTY;
1896 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1897 * @param[in] mc cursor pointing to the page to be touched
1898 * @return 0 on success, non-zero on failure.
1901 mdb_page_touch(MDB_cursor *mc)
1903 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
1904 MDB_txn *txn = mc->mc_txn;
1905 MDB_cursor *m2, *m3;
1909 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1910 if (txn->mt_flags & MDB_TXN_SPILLS) {
1912 rc = mdb_page_unspill(txn, mp, &np);
1918 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
1919 (rc = mdb_page_alloc(mc, 1, &np)))
1922 DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
1923 mp->mp_pgno, pgno));
1924 assert(mp->mp_pgno != pgno);
1925 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
1926 /* Update the parent page, if any, to point to the new page */
1928 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
1929 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
1930 SETPGNO(node, pgno);
1932 mc->mc_db->md_root = pgno;
1934 } else if (txn->mt_parent && !IS_SUBP(mp)) {
1935 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
1937 /* If txn has a parent, make sure the page is in our
1941 unsigned x = mdb_mid2l_search(dl, pgno);
1942 if (x <= dl[0].mid && dl[x].mid == pgno) {
1943 if (mp != dl[x].mptr) { /* bad cursor? */
1944 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1945 return MDB_CORRUPTED;
1950 assert(dl[0].mid < MDB_IDL_UM_MAX);
1952 np = mdb_page_malloc(txn, 1);
1957 mdb_mid2l_insert(dl, &mid);
1962 mdb_page_copy(np, mp, txn->mt_env->me_psize);
1964 np->mp_flags |= P_DIRTY;
1967 /* Adjust cursors pointing to mp */
1968 mc->mc_pg[mc->mc_top] = np;
1969 m2 = txn->mt_cursors[mc->mc_dbi];
1970 if (mc->mc_flags & C_SUB) {
1971 for (; m2; m2=m2->mc_next) {
1972 m3 = &m2->mc_xcursor->mx_cursor;
1973 if (m3->mc_snum < mc->mc_snum) continue;
1974 if (m3->mc_pg[mc->mc_top] == mp)
1975 m3->mc_pg[mc->mc_top] = np;
1978 for (; m2; m2=m2->mc_next) {
1979 if (m2->mc_snum < mc->mc_snum) continue;
1980 if (m2->mc_pg[mc->mc_top] == mp) {
1981 m2->mc_pg[mc->mc_top] = np;
1982 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
1983 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
1985 MDB_node *leaf = NODEPTR(np, mc->mc_ki[mc->mc_top]);
1986 if (!(leaf->mn_flags & F_SUBDATA))
1987 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
1996 mdb_env_sync(MDB_env *env, int force)
1999 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2000 if (env->me_flags & MDB_WRITEMAP) {
2001 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2002 ? MS_ASYNC : MS_SYNC;
2003 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
2006 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2010 if (MDB_FDATASYNC(env->me_fd))
2017 /** Back up parent txn's cursors, then grab the originals for tracking */
2019 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2021 MDB_cursor *mc, *bk;
2026 for (i = src->mt_numdbs; --i >= 0; ) {
2027 if ((mc = src->mt_cursors[i]) != NULL) {
2028 size = sizeof(MDB_cursor);
2030 size += sizeof(MDB_xcursor);
2031 for (; mc; mc = bk->mc_next) {
2037 mc->mc_db = &dst->mt_dbs[i];
2038 /* Kill pointers into src - and dst to reduce abuse: The
2039 * user may not use mc until dst ends. Otherwise we'd...
2041 mc->mc_txn = NULL; /* ...set this to dst */
2042 mc->mc_dbflag = NULL; /* ...and &dst->mt_dbflags[i] */
2043 if ((mx = mc->mc_xcursor) != NULL) {
2044 *(MDB_xcursor *)(bk+1) = *mx;
2045 mx->mx_cursor.mc_txn = NULL; /* ...and dst. */
2047 mc->mc_next = dst->mt_cursors[i];
2048 dst->mt_cursors[i] = mc;
2055 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2056 * @param[in] txn the transaction handle.
2057 * @param[in] merge true to keep changes to parent cursors, false to revert.
2058 * @return 0 on success, non-zero on failure.
2061 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2063 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2067 for (i = txn->mt_numdbs; --i >= 0; ) {
2068 for (mc = cursors[i]; mc; mc = next) {
2070 if ((bk = mc->mc_backup) != NULL) {
2072 /* Commit changes to parent txn */
2073 mc->mc_next = bk->mc_next;
2074 mc->mc_backup = bk->mc_backup;
2075 mc->mc_txn = bk->mc_txn;
2076 mc->mc_db = bk->mc_db;
2077 mc->mc_dbflag = bk->mc_dbflag;
2078 if ((mx = mc->mc_xcursor) != NULL)
2079 mx->mx_cursor.mc_txn = bk->mc_txn;
2081 /* Abort nested txn */
2083 if ((mx = mc->mc_xcursor) != NULL)
2084 *mx = *(MDB_xcursor *)(bk+1);
2088 /* Only malloced cursors are permanently tracked. */
2096 #define mdb_txn_reset0(txn, act) mdb_txn_reset0(txn)
2099 mdb_txn_reset0(MDB_txn *txn, const char *act);
2101 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2107 Pidset = F_SETLK, Pidcheck = F_GETLK
2111 /** Set or check a pid lock. Set returns 0 on success.
2112 * Check returns 0 if the process is certainly dead, nonzero if it may
2113 * be alive (the lock exists or an error happened so we do not know).
2115 * On Windows Pidset is a no-op, we merely check for the existence
2116 * of the process with the given pid. On POSIX we use a single byte
2117 * lock on the lockfile, set at an offset equal to the pid.
2120 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2122 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2125 if (op == Pidcheck) {
2126 h = OpenProcess(env->me_pidquery, FALSE, pid);
2127 /* No documented "no such process" code, but other program use this: */
2129 return ErrCode() != ERROR_INVALID_PARAMETER;
2130 /* A process exists until all handles to it close. Has it exited? */
2131 ret = WaitForSingleObject(h, 0) != 0;
2138 struct flock lock_info;
2139 memset(&lock_info, 0, sizeof(lock_info));
2140 lock_info.l_type = F_WRLCK;
2141 lock_info.l_whence = SEEK_SET;
2142 lock_info.l_start = pid;
2143 lock_info.l_len = 1;
2144 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2145 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2147 } else if ((rc = ErrCode()) == EINTR) {
2155 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2156 * @param[in] txn the transaction handle to initialize
2157 * @return 0 on success, non-zero on failure.
2160 mdb_txn_renew0(MDB_txn *txn)
2162 MDB_env *env = txn->mt_env;
2163 MDB_txninfo *ti = env->me_txns;
2167 int rc, new_notls = 0;
2170 txn->mt_numdbs = env->me_numdbs;
2171 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
2173 if (txn->mt_flags & MDB_TXN_RDONLY) {
2175 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2176 txn->mt_txnid = meta->mm_txnid;
2177 txn->mt_u.reader = NULL;
2179 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2180 pthread_getspecific(env->me_txkey);
2182 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2183 return MDB_BAD_RSLOT;
2185 MDB_PID_T pid = env->me_pid;
2186 pthread_t tid = pthread_self();
2188 if (!(env->me_flags & MDB_LIVE_READER)) {
2189 rc = mdb_reader_pid(env, Pidset, pid);
2191 UNLOCK_MUTEX_R(env);
2194 env->me_flags |= MDB_LIVE_READER;
2198 nr = ti->mti_numreaders;
2199 for (i=0; i<nr; i++)
2200 if (ti->mti_readers[i].mr_pid == 0)
2202 if (i == env->me_maxreaders) {
2203 UNLOCK_MUTEX_R(env);
2204 return MDB_READERS_FULL;
2206 ti->mti_readers[i].mr_pid = pid;
2207 ti->mti_readers[i].mr_tid = tid;
2209 ti->mti_numreaders = ++nr;
2210 /* Save numreaders for un-mutexed mdb_env_close() */
2211 env->me_numreaders = nr;
2212 UNLOCK_MUTEX_R(env);
2214 r = &ti->mti_readers[i];
2215 new_notls = (env->me_flags & MDB_NOTLS);
2216 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2221 txn->mt_txnid = r->mr_txnid = ti->mti_txnid;
2222 txn->mt_u.reader = r;
2223 meta = env->me_metas[txn->mt_txnid & 1];
2229 txn->mt_txnid = ti->mti_txnid;
2230 meta = env->me_metas[txn->mt_txnid & 1];
2232 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2233 txn->mt_txnid = meta->mm_txnid;
2237 if (txn->mt_txnid == mdb_debug_start)
2240 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2241 txn->mt_u.dirty_list = env->me_dirty_list;
2242 txn->mt_u.dirty_list[0].mid = 0;
2243 txn->mt_free_pgs = env->me_free_pgs;
2244 txn->mt_free_pgs[0] = 0;
2245 txn->mt_spill_pgs = NULL;
2249 /* Copy the DB info and flags */
2250 memcpy(txn->mt_dbs, meta->mm_dbs, 2 * sizeof(MDB_db));
2252 /* Moved to here to avoid a data race in read TXNs */
2253 txn->mt_next_pgno = meta->mm_last_pg+1;
2255 for (i=2; i<txn->mt_numdbs; i++) {
2256 x = env->me_dbflags[i];
2257 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2258 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_STALE : 0;
2260 txn->mt_dbflags[0] = txn->mt_dbflags[1] = DB_VALID;
2262 if (env->me_maxpg < txn->mt_next_pgno) {
2263 mdb_txn_reset0(txn, "renew0-mapfail");
2265 txn->mt_u.reader->mr_pid = 0;
2266 txn->mt_u.reader = NULL;
2268 return MDB_MAP_RESIZED;
2275 mdb_txn_renew(MDB_txn *txn)
2279 if (!txn || txn->mt_dbxs) /* A reset txn has mt_dbxs==NULL */
2282 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
2283 DPUTS("environment had fatal error, must shutdown!");
2287 rc = mdb_txn_renew0(txn);
2288 if (rc == MDB_SUCCESS) {
2289 DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2290 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2291 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2297 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2301 int rc, size, tsize = sizeof(MDB_txn);
2303 if (env->me_flags & MDB_FATAL_ERROR) {
2304 DPUTS("environment had fatal error, must shutdown!");
2307 if ((env->me_flags & MDB_RDONLY) && !(flags & MDB_RDONLY))
2310 /* Nested transactions: Max 1 child, write txns only, no writemap */
2311 if (parent->mt_child ||
2312 (flags & MDB_RDONLY) ||
2313 (parent->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR)) ||
2314 (env->me_flags & MDB_WRITEMAP))
2316 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
2318 tsize = sizeof(MDB_ntxn);
2320 size = tsize + env->me_maxdbs * (sizeof(MDB_db)+1);
2321 if (!(flags & MDB_RDONLY))
2322 size += env->me_maxdbs * sizeof(MDB_cursor *);
2324 if ((txn = calloc(1, size)) == NULL) {
2325 DPRINTF(("calloc: %s", strerror(ErrCode())));
2328 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2329 if (flags & MDB_RDONLY) {
2330 txn->mt_flags |= MDB_TXN_RDONLY;
2331 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
2333 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2334 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
2340 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2341 if (!txn->mt_u.dirty_list ||
2342 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2344 free(txn->mt_u.dirty_list);
2348 txn->mt_txnid = parent->mt_txnid;
2349 txn->mt_dirty_room = parent->mt_dirty_room;
2350 txn->mt_u.dirty_list[0].mid = 0;
2351 txn->mt_spill_pgs = NULL;
2352 txn->mt_next_pgno = parent->mt_next_pgno;
2353 parent->mt_child = txn;
2354 txn->mt_parent = parent;
2355 txn->mt_numdbs = parent->mt_numdbs;
2356 txn->mt_flags = parent->mt_flags;
2357 txn->mt_dbxs = parent->mt_dbxs;
2358 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2359 /* Copy parent's mt_dbflags, but clear DB_NEW */
2360 for (i=0; i<txn->mt_numdbs; i++)
2361 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2363 ntxn = (MDB_ntxn *)txn;
2364 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2365 if (env->me_pghead) {
2366 size = MDB_IDL_SIZEOF(env->me_pghead);
2367 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2369 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2374 rc = mdb_cursor_shadow(parent, txn);
2376 mdb_txn_reset0(txn, "beginchild-fail");
2378 rc = mdb_txn_renew0(txn);
2384 DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2385 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2386 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
2393 mdb_txn_env(MDB_txn *txn)
2395 if(!txn) return NULL;
2399 /** Export or close DBI handles opened in this txn. */
2401 mdb_dbis_update(MDB_txn *txn, int keep)
2404 MDB_dbi n = txn->mt_numdbs;
2405 MDB_env *env = txn->mt_env;
2406 unsigned char *tdbflags = txn->mt_dbflags;
2408 for (i = n; --i >= 2;) {
2409 if (tdbflags[i] & DB_NEW) {
2411 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2413 char *ptr = env->me_dbxs[i].md_name.mv_data;
2414 env->me_dbxs[i].md_name.mv_data = NULL;
2415 env->me_dbxs[i].md_name.mv_size = 0;
2416 env->me_dbflags[i] = 0;
2421 if (keep && env->me_numdbs < n)
2425 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
2426 * May be called twice for readonly txns: First reset it, then abort.
2427 * @param[in] txn the transaction handle to reset
2428 * @param[in] act why the transaction is being reset
2431 mdb_txn_reset0(MDB_txn *txn, const char *act)
2433 MDB_env *env = txn->mt_env;
2435 /* Close any DBI handles opened in this txn */
2436 mdb_dbis_update(txn, 0);
2438 DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2439 act, txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2440 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
2442 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2443 if (txn->mt_u.reader) {
2444 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2445 if (!(env->me_flags & MDB_NOTLS))
2446 txn->mt_u.reader = NULL; /* txn does not own reader */
2448 txn->mt_numdbs = 0; /* close nothing if called again */
2449 txn->mt_dbxs = NULL; /* mark txn as reset */
2451 mdb_cursors_close(txn, 0);
2453 if (!(env->me_flags & MDB_WRITEMAP)) {
2454 mdb_dlist_free(txn);
2456 mdb_midl_free(env->me_pghead);
2458 if (txn->mt_parent) {
2459 txn->mt_parent->mt_child = NULL;
2460 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2461 mdb_midl_free(txn->mt_free_pgs);
2462 mdb_midl_free(txn->mt_spill_pgs);
2463 free(txn->mt_u.dirty_list);
2467 if (mdb_midl_shrink(&txn->mt_free_pgs))
2468 env->me_free_pgs = txn->mt_free_pgs;
2469 env->me_pghead = NULL;
2473 /* The writer mutex was locked in mdb_txn_begin. */
2475 UNLOCK_MUTEX_W(env);
2480 mdb_txn_reset(MDB_txn *txn)
2485 /* This call is only valid for read-only txns */
2486 if (!(txn->mt_flags & MDB_TXN_RDONLY))
2489 mdb_txn_reset0(txn, "reset");
2493 mdb_txn_abort(MDB_txn *txn)
2499 mdb_txn_abort(txn->mt_child);
2501 mdb_txn_reset0(txn, "abort");
2502 /* Free reader slot tied to this txn (if MDB_NOTLS && writable FS) */
2503 if ((txn->mt_flags & MDB_TXN_RDONLY) && txn->mt_u.reader)
2504 txn->mt_u.reader->mr_pid = 0;
2509 /** Save the freelist as of this transaction to the freeDB.
2510 * This changes the freelist. Keep trying until it stabilizes.
2513 mdb_freelist_save(MDB_txn *txn)
2515 /* env->me_pghead[] can grow and shrink during this call.
2516 * env->me_pglast and txn->mt_free_pgs[] can only grow.
2517 * Page numbers cannot disappear from txn->mt_free_pgs[].
2520 MDB_env *env = txn->mt_env;
2521 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
2522 txnid_t pglast = 0, head_id = 0;
2523 pgno_t freecnt = 0, *free_pgs, *mop;
2524 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
2526 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
2528 if (env->me_pghead) {
2529 /* Make sure first page of freeDB is touched and on freelist */
2530 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
2531 if (rc && rc != MDB_NOTFOUND)
2535 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
2536 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
2537 ? SSIZE_MAX : maxfree_1pg;
2540 /* Come back here after each Put() in case freelist changed */
2545 /* If using records from freeDB which we have not yet
2546 * deleted, delete them and any we reserved for me_pghead.
2548 while (pglast < env->me_pglast) {
2549 rc = mdb_cursor_first(&mc, &key, NULL);
2552 pglast = head_id = *(txnid_t *)key.mv_data;
2553 total_room = head_room = 0;
2554 assert(pglast <= env->me_pglast);
2555 rc = mdb_cursor_del(&mc, 0);
2560 /* Save the IDL of pages freed by this txn, to a single record */
2561 if (freecnt < txn->mt_free_pgs[0]) {
2563 /* Make sure last page of freeDB is touched and on freelist */
2564 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
2565 if (rc && rc != MDB_NOTFOUND)
2568 free_pgs = txn->mt_free_pgs;
2569 /* Write to last page of freeDB */
2570 key.mv_size = sizeof(txn->mt_txnid);
2571 key.mv_data = &txn->mt_txnid;
2573 freecnt = free_pgs[0];
2574 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
2575 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2578 /* Retry if mt_free_pgs[] grew during the Put() */
2579 free_pgs = txn->mt_free_pgs;
2580 } while (freecnt < free_pgs[0]);
2581 mdb_midl_sort(free_pgs);
2582 memcpy(data.mv_data, free_pgs, data.mv_size);
2585 unsigned int i = free_pgs[0];
2586 DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
2587 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
2589 DPRINTF(("IDL %"Z"u", free_pgs[i]));
2595 mop = env->me_pghead;
2596 mop_len = mop ? mop[0] : 0;
2598 /* Reserve records for me_pghead[]. Split it if multi-page,
2599 * to avoid searching freeDB for a page range. Use keys in
2600 * range [1,me_pglast]: Smaller than txnid of oldest reader.
2602 if (total_room >= mop_len) {
2603 if (total_room == mop_len || --more < 0)
2605 } else if (head_room >= maxfree_1pg && head_id > 1) {
2606 /* Keep current record (overflow page), add a new one */
2610 /* (Re)write {key = head_id, IDL length = head_room} */
2611 total_room -= head_room;
2612 head_room = mop_len - total_room;
2613 if (head_room > maxfree_1pg && head_id > 1) {
2614 /* Overflow multi-page for part of me_pghead */
2615 head_room /= head_id; /* amortize page sizes */
2616 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
2617 } else if (head_room < 0) {
2618 /* Rare case, not bothering to delete this record */
2621 key.mv_size = sizeof(head_id);
2622 key.mv_data = &head_id;
2623 data.mv_size = (head_room + 1) * sizeof(pgno_t);
2624 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2627 /* IDL is initially empty, zero out at least the length */
2628 pgs = (pgno_t *)data.mv_data;
2629 j = head_room > clean_limit ? head_room : 0;
2633 total_room += head_room;
2636 /* Fill in the reserved me_pghead records */
2642 rc = mdb_cursor_first(&mc, &key, &data);
2643 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
2644 unsigned flags = MDB_CURRENT;
2645 txnid_t id = *(txnid_t *)key.mv_data;
2646 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
2649 assert(len >= 0 && id <= env->me_pglast);
2651 if (len > mop_len) {
2653 data.mv_size = (len + 1) * sizeof(MDB_ID);
2656 data.mv_data = mop -= len;
2659 rc = mdb_cursor_put(&mc, &key, &data, flags);
2661 if (rc || !(mop_len -= len))
2668 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
2669 * @param[in] txn the transaction that's being committed
2670 * @param[in] keep number of initial pages in dirty_list to keep dirty.
2671 * @return 0 on success, non-zero on failure.
2674 mdb_page_flush(MDB_txn *txn, int keep)
2676 MDB_env *env = txn->mt_env;
2677 MDB_ID2L dl = txn->mt_u.dirty_list;
2678 unsigned psize = env->me_psize, j;
2679 int i, pagecount = dl[0].mid, rc;
2680 size_t size = 0, pos = 0;
2682 MDB_page *dp = NULL;
2686 struct iovec iov[MDB_COMMIT_PAGES];
2687 ssize_t wpos = 0, wsize = 0, wres;
2688 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
2694 if (env->me_flags & MDB_WRITEMAP) {
2695 /* Clear dirty flags */
2696 while (++i <= pagecount) {
2698 /* Don't flush this page yet */
2699 if (dp->mp_flags & P_KEEP) {
2700 dp->mp_flags ^= P_KEEP;
2704 dp->mp_flags &= ~P_DIRTY;
2709 /* Write the pages */
2711 if (++i <= pagecount) {
2713 /* Don't flush this page yet */
2714 if (dp->mp_flags & P_KEEP) {
2715 dp->mp_flags ^= P_KEEP;
2720 /* clear dirty flag */
2721 dp->mp_flags &= ~P_DIRTY;
2724 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
2729 /* Windows actually supports scatter/gather I/O, but only on
2730 * unbuffered file handles. Since we're relying on the OS page
2731 * cache for all our data, that's self-defeating. So we just
2732 * write pages one at a time. We use the ov structure to set
2733 * the write offset, to at least save the overhead of a Seek
2736 DPRINTF(("committing page %"Z"u", pgno));
2737 memset(&ov, 0, sizeof(ov));
2738 ov.Offset = pos & 0xffffffff;
2739 ov.OffsetHigh = pos >> 16 >> 16;
2740 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
2742 DPRINTF(("WriteFile: %d", rc));
2746 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
2747 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
2749 /* Write previous page(s) */
2750 #ifdef MDB_USE_PWRITEV
2751 wres = pwritev(env->me_fd, iov, n, wpos);
2754 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
2756 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
2758 DPRINTF(("lseek: %s", strerror(rc)));
2761 wres = writev(env->me_fd, iov, n);
2764 if (wres != wsize) {
2767 DPRINTF(("Write error: %s", strerror(rc)));
2769 rc = EIO; /* TODO: Use which error code? */
2770 DPUTS("short write, filesystem full?");
2781 DPRINTF(("committing page %"Z"u", pgno));
2782 next_pos = pos + size;
2783 iov[n].iov_len = size;
2784 iov[n].iov_base = (char *)dp;
2790 for (i = keep; ++i <= pagecount; ) {
2792 /* This is a page we skipped above */
2795 dl[j].mid = dp->mp_pgno;
2798 mdb_dpage_free(env, dp);
2803 txn->mt_dirty_room += i - j;
2809 mdb_txn_commit(MDB_txn *txn)
2815 assert(txn != NULL);
2816 assert(txn->mt_env != NULL);
2818 if (txn->mt_child) {
2819 rc = mdb_txn_commit(txn->mt_child);
2820 txn->mt_child = NULL;
2827 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2828 mdb_dbis_update(txn, 1);
2829 txn->mt_numdbs = 2; /* so txn_abort() doesn't close any new handles */
2834 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
2835 DPUTS("error flag is set, can't commit");
2837 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
2842 if (txn->mt_parent) {
2843 MDB_txn *parent = txn->mt_parent;
2846 unsigned x, y, len, ps_len;
2848 /* Append our free list to parent's */
2849 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
2852 mdb_midl_free(txn->mt_free_pgs);
2853 /* Failures after this must either undo the changes
2854 * to the parent or set MDB_TXN_ERROR in the parent.
2857 parent->mt_next_pgno = txn->mt_next_pgno;
2858 parent->mt_flags = txn->mt_flags;
2860 /* Merge our cursors into parent's and close them */
2861 mdb_cursors_close(txn, 1);
2863 /* Update parent's DB table. */
2864 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2865 parent->mt_numdbs = txn->mt_numdbs;
2866 parent->mt_dbflags[0] = txn->mt_dbflags[0];
2867 parent->mt_dbflags[1] = txn->mt_dbflags[1];
2868 for (i=2; i<txn->mt_numdbs; i++) {
2869 /* preserve parent's DB_NEW status */
2870 x = parent->mt_dbflags[i] & DB_NEW;
2871 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
2874 dst = parent->mt_u.dirty_list;
2875 src = txn->mt_u.dirty_list;
2876 /* Remove anything in our dirty list from parent's spill list */
2877 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
2879 pspill[0] = (pgno_t)-1;
2880 /* Mark our dirty pages as deleted in parent spill list */
2881 for (i=0, len=src[0].mid; ++i <= len; ) {
2882 MDB_ID pn = src[i].mid << 1;
2883 while (pn > pspill[x])
2885 if (pn == pspill[x]) {
2890 /* Squash deleted pagenums if we deleted any */
2891 for (x=y; ++x <= ps_len; )
2892 if (!(pspill[x] & 1))
2893 pspill[++y] = pspill[x];
2897 /* Find len = length of merging our dirty list with parent's */
2899 dst[0].mid = 0; /* simplify loops */
2900 if (parent->mt_parent) {
2901 len = x + src[0].mid;
2902 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
2903 for (i = x; y && i; y--) {
2904 pgno_t yp = src[y].mid;
2905 while (yp < dst[i].mid)
2907 if (yp == dst[i].mid) {
2912 } else { /* Simplify the above for single-ancestor case */
2913 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
2915 /* Merge our dirty list with parent's */
2917 for (i = len; y; dst[i--] = src[y--]) {
2918 pgno_t yp = src[y].mid;
2919 while (yp < dst[x].mid)
2920 dst[i--] = dst[x--];
2921 if (yp == dst[x].mid)
2922 free(dst[x--].mptr);
2926 free(txn->mt_u.dirty_list);
2927 parent->mt_dirty_room = txn->mt_dirty_room;
2928 if (txn->mt_spill_pgs) {
2929 if (parent->mt_spill_pgs) {
2930 /* TODO: Prevent failure here, so parent does not fail */
2931 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
2933 parent->mt_flags |= MDB_TXN_ERROR;
2934 mdb_midl_free(txn->mt_spill_pgs);
2935 mdb_midl_sort(parent->mt_spill_pgs);
2937 parent->mt_spill_pgs = txn->mt_spill_pgs;
2941 parent->mt_child = NULL;
2942 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
2947 if (txn != env->me_txn) {
2948 DPUTS("attempt to commit unknown transaction");
2953 mdb_cursors_close(txn, 0);
2955 if (!txn->mt_u.dirty_list[0].mid &&
2956 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
2959 DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
2960 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
2962 /* Update DB root pointers */
2963 if (txn->mt_numdbs > 2) {
2967 data.mv_size = sizeof(MDB_db);
2969 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
2970 for (i = 2; i < txn->mt_numdbs; i++) {
2971 if (txn->mt_dbflags[i] & DB_DIRTY) {
2972 data.mv_data = &txn->mt_dbs[i];
2973 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
2980 rc = mdb_freelist_save(txn);
2984 mdb_midl_free(env->me_pghead);
2985 env->me_pghead = NULL;
2986 if (mdb_midl_shrink(&txn->mt_free_pgs))
2987 env->me_free_pgs = txn->mt_free_pgs;
2993 if ((rc = mdb_page_flush(txn, 0)) ||
2994 (rc = mdb_env_sync(env, 0)) ||
2995 (rc = mdb_env_write_meta(txn)))
3001 mdb_dbis_update(txn, 1);
3004 UNLOCK_MUTEX_W(env);
3014 /** Read the environment parameters of a DB environment before
3015 * mapping it into memory.
3016 * @param[in] env the environment handle
3017 * @param[out] meta address of where to store the meta information
3018 * @return 0 on success, non-zero on failure.
3021 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3027 enum { Size = sizeof(pbuf) };
3029 /* We don't know the page size yet, so use a minimum value.
3030 * Read both meta pages so we can use the latest one.
3033 for (i=off=0; i<2; i++, off = meta->mm_psize) {
3037 memset(&ov, 0, sizeof(ov));
3039 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3040 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3043 rc = pread(env->me_fd, &pbuf, Size, off);
3046 if (rc == 0 && off == 0)
3048 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3049 DPRINTF(("read: %s", mdb_strerror(rc)));
3053 p = (MDB_page *)&pbuf;
3055 if (!F_ISSET(p->mp_flags, P_META)) {
3056 DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
3061 if (m->mm_magic != MDB_MAGIC) {
3062 DPUTS("meta has invalid magic");
3066 if (m->mm_version != MDB_DATA_VERSION) {
3067 DPRINTF(("database is version %u, expected version %u",
3068 m->mm_version, MDB_DATA_VERSION));
3069 return MDB_VERSION_MISMATCH;
3072 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3078 /** Write the environment parameters of a freshly created DB environment.
3079 * @param[in] env the environment handle
3080 * @param[out] meta address of where to store the meta information
3081 * @return 0 on success, non-zero on failure.
3084 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3092 memset(&ov, 0, sizeof(ov));
3093 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3095 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3098 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3099 len = pwrite(fd, ptr, size, pos); \
3100 rc = (len >= 0); } while(0)
3103 DPUTS("writing new meta page");
3105 psize = env->me_psize;
3107 meta->mm_magic = MDB_MAGIC;
3108 meta->mm_version = MDB_DATA_VERSION;
3109 meta->mm_mapsize = env->me_mapsize;
3110 meta->mm_psize = psize;
3111 meta->mm_last_pg = 1;
3112 meta->mm_flags = env->me_flags & 0xffff;
3113 meta->mm_flags |= MDB_INTEGERKEY;
3114 meta->mm_dbs[0].md_root = P_INVALID;
3115 meta->mm_dbs[1].md_root = P_INVALID;
3117 p = calloc(2, psize);
3119 p->mp_flags = P_META;
3120 *(MDB_meta *)METADATA(p) = *meta;
3122 q = (MDB_page *)((char *)p + psize);
3124 q->mp_flags = P_META;
3125 *(MDB_meta *)METADATA(q) = *meta;
3127 DO_PWRITE(rc, env->me_fd, p, psize * 2, len, 0);
3130 else if ((unsigned) len == psize * 2)
3138 /** Update the environment info to commit a transaction.
3139 * @param[in] txn the transaction that's being committed
3140 * @return 0 on success, non-zero on failure.
3143 mdb_env_write_meta(MDB_txn *txn)
3146 MDB_meta meta, metab, *mp;
3148 int rc, len, toggle;
3157 assert(txn != NULL);
3158 assert(txn->mt_env != NULL);
3160 toggle = txn->mt_txnid & 1;
3161 DPRINTF(("writing meta page %d for root page %"Z"u",
3162 toggle, txn->mt_dbs[MAIN_DBI].md_root));
3165 mp = env->me_metas[toggle];
3167 if (env->me_flags & MDB_WRITEMAP) {
3168 /* Persist any increases of mapsize config */
3169 if (env->me_mapsize > mp->mm_mapsize)
3170 mp->mm_mapsize = env->me_mapsize;
3171 mp->mm_dbs[0] = txn->mt_dbs[0];
3172 mp->mm_dbs[1] = txn->mt_dbs[1];
3173 mp->mm_last_pg = txn->mt_next_pgno - 1;
3174 mp->mm_txnid = txn->mt_txnid;
3175 if (!(env->me_flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3176 unsigned meta_size = env->me_psize;
3177 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3180 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
3181 if (meta_size < env->me_os_psize)
3182 meta_size += meta_size;
3187 if (MDB_MSYNC(ptr, meta_size, rc)) {
3194 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
3195 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
3197 ptr = (char *)&meta;
3198 if (env->me_mapsize > mp->mm_mapsize) {
3199 /* Persist any increases of mapsize config */
3200 meta.mm_mapsize = env->me_mapsize;
3201 off = offsetof(MDB_meta, mm_mapsize);
3203 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
3205 len = sizeof(MDB_meta) - off;
3208 meta.mm_dbs[0] = txn->mt_dbs[0];
3209 meta.mm_dbs[1] = txn->mt_dbs[1];
3210 meta.mm_last_pg = txn->mt_next_pgno - 1;
3211 meta.mm_txnid = txn->mt_txnid;
3214 off += env->me_psize;
3217 /* Write to the SYNC fd */
3218 mfd = env->me_flags & (MDB_NOSYNC|MDB_NOMETASYNC) ?
3219 env->me_fd : env->me_mfd;
3222 memset(&ov, 0, sizeof(ov));
3224 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3228 rc = pwrite(mfd, ptr, len, off);
3231 rc = rc < 0 ? ErrCode() : EIO;
3232 DPUTS("write failed, disk error?");
3233 /* On a failure, the pagecache still contains the new data.
3234 * Write some old data back, to prevent it from being used.
3235 * Use the non-SYNC fd; we know it will fail anyway.
3237 meta.mm_last_pg = metab.mm_last_pg;
3238 meta.mm_txnid = metab.mm_txnid;
3240 memset(&ov, 0, sizeof(ov));
3242 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3244 r2 = pwrite(env->me_fd, ptr, len, off);
3245 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
3248 env->me_flags |= MDB_FATAL_ERROR;
3252 /* Memory ordering issues are irrelevant; since the entire writer
3253 * is wrapped by wmutex, all of these changes will become visible
3254 * after the wmutex is unlocked. Since the DB is multi-version,
3255 * readers will get consistent data regardless of how fresh or
3256 * how stale their view of these values is.
3259 env->me_txns->mti_txnid = txn->mt_txnid;
3264 /** Check both meta pages to see which one is newer.
3265 * @param[in] env the environment handle
3266 * @return meta toggle (0 or 1).
3269 mdb_env_pick_meta(const MDB_env *env)
3271 return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
3275 mdb_env_create(MDB_env **env)
3279 e = calloc(1, sizeof(MDB_env));
3283 e->me_maxreaders = DEFAULT_READERS;
3284 e->me_maxdbs = e->me_numdbs = 2;
3285 e->me_fd = INVALID_HANDLE_VALUE;
3286 e->me_lfd = INVALID_HANDLE_VALUE;
3287 e->me_mfd = INVALID_HANDLE_VALUE;
3288 #ifdef MDB_USE_POSIX_SEM
3289 e->me_rmutex = SEM_FAILED;
3290 e->me_wmutex = SEM_FAILED;
3292 e->me_pid = getpid();
3293 GET_PAGESIZE(e->me_os_psize);
3294 VGMEMP_CREATE(e,0,0);
3300 mdb_env_map(MDB_env *env, void *addr, int newsize)
3303 unsigned int flags = env->me_flags;
3307 LONG sizelo, sizehi;
3308 sizelo = env->me_mapsize & 0xffffffff;
3309 sizehi = env->me_mapsize >> 16 >> 16; /* only needed on Win64 */
3311 /* Windows won't create mappings for zero length files.
3312 * Just allocate the maxsize right now.
3315 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3316 || !SetEndOfFile(env->me_fd)
3317 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3320 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3321 PAGE_READWRITE : PAGE_READONLY,
3322 sizehi, sizelo, NULL);
3325 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3326 FILE_MAP_WRITE : FILE_MAP_READ,
3327 0, 0, env->me_mapsize, addr);
3328 rc = env->me_map ? 0 : ErrCode();
3333 int prot = PROT_READ;
3334 if (flags & MDB_WRITEMAP) {
3336 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3339 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
3341 if (env->me_map == MAP_FAILED) {
3346 if (flags & MDB_NORDAHEAD) {
3347 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3349 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3351 #ifdef POSIX_MADV_RANDOM
3352 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3353 #endif /* POSIX_MADV_RANDOM */
3354 #endif /* MADV_RANDOM */
3358 /* Can happen because the address argument to mmap() is just a
3359 * hint. mmap() can pick another, e.g. if the range is in use.
3360 * The MAP_FIXED flag would prevent that, but then mmap could
3361 * instead unmap existing pages to make room for the new map.
3363 if (addr && env->me_map != addr)
3364 return EBUSY; /* TODO: Make a new MDB_* error code? */
3366 p = (MDB_page *)env->me_map;
3367 env->me_metas[0] = METADATA(p);
3368 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
3374 mdb_env_set_mapsize(MDB_env *env, size_t size)
3376 /* If env is already open, caller is responsible for making
3377 * sure there are no active txns.
3385 size = env->me_metas[mdb_env_pick_meta(env)]->mm_mapsize;
3386 else if (size < env->me_mapsize) {
3387 /* If the configured size is smaller, make sure it's
3388 * still big enough. Silently round up to minimum if not.
3390 size_t minsize = (env->me_metas[mdb_env_pick_meta(env)]->mm_last_pg + 1) * env->me_psize;
3394 munmap(env->me_map, env->me_mapsize);
3395 env->me_mapsize = size;
3396 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
3397 rc = mdb_env_map(env, old, 1);
3401 env->me_mapsize = size;
3403 env->me_maxpg = env->me_mapsize / env->me_psize;
3408 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
3412 env->me_maxdbs = dbs + 2; /* Named databases + main and free DB */
3417 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
3419 if (env->me_map || readers < 1)
3421 env->me_maxreaders = readers;
3426 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
3428 if (!env || !readers)
3430 *readers = env->me_maxreaders;
3434 /** Further setup required for opening an MDB environment
3437 mdb_env_open2(MDB_env *env)
3439 unsigned int flags = env->me_flags;
3440 int i, newenv = 0, rc;
3444 /* See if we should use QueryLimited */
3446 if ((rc & 0xff) > 5)
3447 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
3449 env->me_pidquery = PROCESS_QUERY_INFORMATION;
3452 memset(&meta, 0, sizeof(meta));
3454 if ((i = mdb_env_read_header(env, &meta)) != 0) {
3457 DPUTS("new mdbenv");
3459 env->me_psize = env->me_os_psize;
3460 if (env->me_psize > MAX_PAGESIZE)
3461 env->me_psize = MAX_PAGESIZE;
3463 env->me_psize = meta.mm_psize;
3466 /* Was a mapsize configured? */
3467 if (!env->me_mapsize) {
3468 /* If this is a new environment, take the default,
3469 * else use the size recorded in the existing env.
3471 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
3472 } else if (env->me_mapsize < meta.mm_mapsize) {
3473 /* If the configured size is smaller, make sure it's
3474 * still big enough. Silently round up to minimum if not.
3476 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
3477 if (env->me_mapsize < minsize)
3478 env->me_mapsize = minsize;
3481 rc = mdb_env_map(env, meta.mm_address, newenv);
3486 if (flags & MDB_FIXEDMAP)
3487 meta.mm_address = env->me_map;
3488 i = mdb_env_init_meta(env, &meta);
3489 if (i != MDB_SUCCESS) {
3493 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
3494 env->me_nodemax = (env->me_psize - PAGEHDRSZ) / MDB_MINKEYS;
3496 env->me_maxpg = env->me_mapsize / env->me_psize;
3499 int toggle = mdb_env_pick_meta(env);
3500 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
3502 DPRINTF(("opened database version %u, pagesize %u",
3503 env->me_metas[0]->mm_version, env->me_psize));
3504 DPRINTF(("using meta page %d", toggle));
3505 DPRINTF(("depth: %u", db->md_depth));
3506 DPRINTF(("entries: %"Z"u", db->md_entries));
3507 DPRINTF(("branch pages: %"Z"u", db->md_branch_pages));
3508 DPRINTF(("leaf pages: %"Z"u", db->md_leaf_pages));
3509 DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
3510 DPRINTF(("root: %"Z"u", db->md_root));
3518 /** Release a reader thread's slot in the reader lock table.
3519 * This function is called automatically when a thread exits.
3520 * @param[in] ptr This points to the slot in the reader lock table.
3523 mdb_env_reader_dest(void *ptr)
3525 MDB_reader *reader = ptr;
3531 /** Junk for arranging thread-specific callbacks on Windows. This is
3532 * necessarily platform and compiler-specific. Windows supports up
3533 * to 1088 keys. Let's assume nobody opens more than 64 environments
3534 * in a single process, for now. They can override this if needed.
3536 #ifndef MAX_TLS_KEYS
3537 #define MAX_TLS_KEYS 64
3539 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
3540 static int mdb_tls_nkeys;
3542 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
3546 case DLL_PROCESS_ATTACH: break;
3547 case DLL_THREAD_ATTACH: break;
3548 case DLL_THREAD_DETACH:
3549 for (i=0; i<mdb_tls_nkeys; i++) {
3550 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
3551 mdb_env_reader_dest(r);
3554 case DLL_PROCESS_DETACH: break;
3559 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3561 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3565 /* Force some symbol references.
3566 * _tls_used forces the linker to create the TLS directory if not already done
3567 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
3569 #pragma comment(linker, "/INCLUDE:_tls_used")
3570 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
3571 #pragma const_seg(".CRT$XLB")
3572 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
3573 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3576 #pragma comment(linker, "/INCLUDE:__tls_used")
3577 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
3578 #pragma data_seg(".CRT$XLB")
3579 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3581 #endif /* WIN 32/64 */
3582 #endif /* !__GNUC__ */
3585 /** Downgrade the exclusive lock on the region back to shared */
3587 mdb_env_share_locks(MDB_env *env, int *excl)
3589 int rc = 0, toggle = mdb_env_pick_meta(env);
3591 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
3596 /* First acquire a shared lock. The Unlock will
3597 * then release the existing exclusive lock.
3599 memset(&ov, 0, sizeof(ov));
3600 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3603 UnlockFile(env->me_lfd, 0, 0, 1, 0);
3609 struct flock lock_info;
3610 /* The shared lock replaces the existing lock */
3611 memset((void *)&lock_info, 0, sizeof(lock_info));
3612 lock_info.l_type = F_RDLCK;
3613 lock_info.l_whence = SEEK_SET;
3614 lock_info.l_start = 0;
3615 lock_info.l_len = 1;
3616 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3617 (rc = ErrCode()) == EINTR) ;
3618 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
3625 /** Try to get exlusive lock, otherwise shared.
3626 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
3629 mdb_env_excl_lock(MDB_env *env, int *excl)
3633 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
3637 memset(&ov, 0, sizeof(ov));
3638 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3645 struct flock lock_info;
3646 memset((void *)&lock_info, 0, sizeof(lock_info));
3647 lock_info.l_type = F_WRLCK;
3648 lock_info.l_whence = SEEK_SET;
3649 lock_info.l_start = 0;
3650 lock_info.l_len = 1;
3651 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3652 (rc = ErrCode()) == EINTR) ;
3656 # ifdef MDB_USE_POSIX_SEM
3657 if (*excl < 0) /* always true when !MDB_USE_POSIX_SEM */
3660 lock_info.l_type = F_RDLCK;
3661 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
3662 (rc = ErrCode()) == EINTR) ;
3672 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
3674 * @(#) $Revision: 5.1 $
3675 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
3676 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
3678 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
3682 * Please do not copyright this code. This code is in the public domain.
3684 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
3685 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
3686 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
3687 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
3688 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
3689 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
3690 * PERFORMANCE OF THIS SOFTWARE.
3693 * chongo <Landon Curt Noll> /\oo/\
3694 * http://www.isthe.com/chongo/
3696 * Share and Enjoy! :-)
3699 typedef unsigned long long mdb_hash_t;
3700 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
3702 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
3703 * @param[in] val value to hash
3704 * @param[in] hval initial value for hash
3705 * @return 64 bit hash
3707 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
3708 * hval arg on the first call.
3711 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
3713 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
3714 unsigned char *end = s + val->mv_size;
3716 * FNV-1a hash each octet of the string
3719 /* xor the bottom with the current octet */
3720 hval ^= (mdb_hash_t)*s++;
3722 /* multiply by the 64 bit FNV magic prime mod 2^64 */
3723 hval += (hval << 1) + (hval << 4) + (hval << 5) +
3724 (hval << 7) + (hval << 8) + (hval << 40);
3726 /* return our new hash value */
3730 /** Hash the string and output the encoded hash.
3731 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
3732 * very short name limits. We don't care about the encoding being reversible,
3733 * we just want to preserve as many bits of the input as possible in a
3734 * small printable string.
3735 * @param[in] str string to hash
3736 * @param[out] encbuf an array of 11 chars to hold the hash
3738 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
3741 mdb_pack85(unsigned long l, char *out)
3745 for (i=0; i<5; i++) {
3746 *out++ = mdb_a85[l % 85];
3752 mdb_hash_enc(MDB_val *val, char *encbuf)
3754 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
3756 mdb_pack85(h, encbuf);
3757 mdb_pack85(h>>32, encbuf+5);
3762 /** Open and/or initialize the lock region for the environment.
3763 * @param[in] env The MDB environment.
3764 * @param[in] lpath The pathname of the file used for the lock region.
3765 * @param[in] mode The Unix permissions for the file, if we create it.
3766 * @param[out] excl Resulting file lock type: -1 none, 0 shared, 1 exclusive
3767 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
3768 * @return 0 on success, non-zero on failure.
3771 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
3774 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
3776 # define MDB_ERRCODE_ROFS EROFS
3777 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
3778 # define MDB_CLOEXEC O_CLOEXEC
3781 # define MDB_CLOEXEC 0
3788 env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
3789 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
3790 FILE_ATTRIBUTE_NORMAL, NULL);
3792 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
3794 if (env->me_lfd == INVALID_HANDLE_VALUE) {
3796 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
3801 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
3802 /* Lose record locks when exec*() */
3803 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
3804 fcntl(env->me_lfd, F_SETFD, fdflags);
3807 if (!(env->me_flags & MDB_NOTLS)) {
3808 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
3811 env->me_flags |= MDB_ENV_TXKEY;
3813 /* Windows TLS callbacks need help finding their TLS info. */
3814 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
3818 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
3822 /* Try to get exclusive lock. If we succeed, then
3823 * nobody is using the lock region and we should initialize it.
3825 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
3828 size = GetFileSize(env->me_lfd, NULL);
3830 size = lseek(env->me_lfd, 0, SEEK_END);
3831 if (size == -1) goto fail_errno;
3833 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
3834 if (size < rsize && *excl > 0) {
3836 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
3837 || !SetEndOfFile(env->me_lfd))
3840 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
3844 size = rsize - sizeof(MDB_txninfo);
3845 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
3850 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
3852 if (!mh) goto fail_errno;
3853 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
3855 if (!env->me_txns) goto fail_errno;
3857 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
3859 if (m == MAP_FAILED) goto fail_errno;
3865 BY_HANDLE_FILE_INFORMATION stbuf;
3874 if (!mdb_sec_inited) {
3875 InitializeSecurityDescriptor(&mdb_null_sd,
3876 SECURITY_DESCRIPTOR_REVISION);
3877 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
3878 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
3879 mdb_all_sa.bInheritHandle = FALSE;
3880 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
3883 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
3884 idbuf.volume = stbuf.dwVolumeSerialNumber;
3885 idbuf.nhigh = stbuf.nFileIndexHigh;
3886 idbuf.nlow = stbuf.nFileIndexLow;
3887 val.mv_data = &idbuf;
3888 val.mv_size = sizeof(idbuf);
3889 mdb_hash_enc(&val, encbuf);
3890 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
3891 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
3892 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
3893 if (!env->me_rmutex) goto fail_errno;
3894 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
3895 if (!env->me_wmutex) goto fail_errno;
3896 #elif defined(MDB_USE_POSIX_SEM)
3905 #if defined(__NetBSD__)
3906 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
3908 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
3909 idbuf.dev = stbuf.st_dev;
3910 idbuf.ino = stbuf.st_ino;
3911 val.mv_data = &idbuf;
3912 val.mv_size = sizeof(idbuf);
3913 mdb_hash_enc(&val, encbuf);
3914 #ifdef MDB_SHORT_SEMNAMES
3915 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
3917 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
3918 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
3919 /* Clean up after a previous run, if needed: Try to
3920 * remove both semaphores before doing anything else.
3922 sem_unlink(env->me_txns->mti_rmname);
3923 sem_unlink(env->me_txns->mti_wmname);
3924 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
3925 O_CREAT|O_EXCL, mode, 1);
3926 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3927 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
3928 O_CREAT|O_EXCL, mode, 1);
3929 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3930 #else /* MDB_USE_POSIX_SEM */
3931 pthread_mutexattr_t mattr;
3933 if ((rc = pthread_mutexattr_init(&mattr))
3934 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
3935 || (rc = pthread_mutex_init(&env->me_txns->mti_mutex, &mattr))
3936 || (rc = pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr)))
3938 pthread_mutexattr_destroy(&mattr);
3939 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
3941 env->me_txns->mti_magic = MDB_MAGIC;
3942 env->me_txns->mti_format = MDB_LOCK_FORMAT;
3943 env->me_txns->mti_txnid = 0;
3944 env->me_txns->mti_numreaders = 0;
3947 if (env->me_txns->mti_magic != MDB_MAGIC) {
3948 DPUTS("lock region has invalid magic");
3952 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
3953 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
3954 env->me_txns->mti_format, MDB_LOCK_FORMAT));
3955 rc = MDB_VERSION_MISMATCH;
3959 if (rc && rc != EACCES && rc != EAGAIN) {
3963 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
3964 if (!env->me_rmutex) goto fail_errno;
3965 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
3966 if (!env->me_wmutex) goto fail_errno;
3967 #elif defined(MDB_USE_POSIX_SEM)
3968 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
3969 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3970 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
3971 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3982 /** The name of the lock file in the DB environment */
3983 #define LOCKNAME "/lock.mdb"
3984 /** The name of the data file in the DB environment */
3985 #define DATANAME "/data.mdb"
3986 /** The suffix of the lock file when no subdir is used */
3987 #define LOCKSUFF "-lock"
3988 /** Only a subset of the @ref mdb_env flags can be changed
3989 * at runtime. Changing other flags requires closing the
3990 * environment and re-opening it with the new flags.
3992 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
3993 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY|MDB_WRITEMAP| \
3994 MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
3997 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
3999 int oflags, rc, len, excl = -1;
4000 char *lpath, *dpath;
4002 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
4006 if (flags & MDB_NOSUBDIR) {
4007 rc = len + sizeof(LOCKSUFF) + len + 1;
4009 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
4014 if (flags & MDB_NOSUBDIR) {
4015 dpath = lpath + len + sizeof(LOCKSUFF);
4016 sprintf(lpath, "%s" LOCKSUFF, path);
4017 strcpy(dpath, path);
4019 dpath = lpath + len + sizeof(LOCKNAME);
4020 sprintf(lpath, "%s" LOCKNAME, path);
4021 sprintf(dpath, "%s" DATANAME, path);
4025 flags |= env->me_flags;
4026 if (flags & MDB_RDONLY) {
4027 /* silently ignore WRITEMAP when we're only getting read access */
4028 flags &= ~MDB_WRITEMAP;
4030 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
4031 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
4034 env->me_flags = flags |= MDB_ENV_ACTIVE;
4038 env->me_path = strdup(path);
4039 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
4040 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
4041 if (!(env->me_dbxs && env->me_path && env->me_dbflags)) {
4046 /* For RDONLY, get lockfile after we know datafile exists */
4047 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
4048 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4054 if (F_ISSET(flags, MDB_RDONLY)) {
4055 oflags = GENERIC_READ;
4056 len = OPEN_EXISTING;
4058 oflags = GENERIC_READ|GENERIC_WRITE;
4061 mode = FILE_ATTRIBUTE_NORMAL;
4062 env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
4063 NULL, len, mode, NULL);
4065 if (F_ISSET(flags, MDB_RDONLY))
4068 oflags = O_RDWR | O_CREAT;
4070 env->me_fd = open(dpath, oflags, mode);
4072 if (env->me_fd == INVALID_HANDLE_VALUE) {
4077 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
4078 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4083 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
4084 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
4085 env->me_mfd = env->me_fd;
4087 /* Synchronous fd for meta writes. Needed even with
4088 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
4091 len = OPEN_EXISTING;
4092 env->me_mfd = CreateFile(dpath, oflags,
4093 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
4094 mode | FILE_FLAG_WRITE_THROUGH, NULL);
4097 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
4099 if (env->me_mfd == INVALID_HANDLE_VALUE) {
4104 DPRINTF(("opened dbenv %p", (void *) env));
4106 rc = mdb_env_share_locks(env, &excl);
4110 if (!((flags & MDB_RDONLY) ||
4111 (env->me_pbuf = calloc(1, env->me_psize))))
4117 mdb_env_close0(env, excl);
4123 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
4125 mdb_env_close0(MDB_env *env, int excl)
4129 if (!(env->me_flags & MDB_ENV_ACTIVE))
4132 /* Doing this here since me_dbxs may not exist during mdb_env_close */
4133 for (i = env->me_maxdbs; --i > MAIN_DBI; )
4134 free(env->me_dbxs[i].md_name.mv_data);
4137 free(env->me_dbflags);
4140 free(env->me_dirty_list);
4141 mdb_midl_free(env->me_free_pgs);
4143 if (env->me_flags & MDB_ENV_TXKEY) {
4144 pthread_key_delete(env->me_txkey);
4146 /* Delete our key from the global list */
4147 for (i=0; i<mdb_tls_nkeys; i++)
4148 if (mdb_tls_keys[i] == env->me_txkey) {
4149 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
4157 munmap(env->me_map, env->me_mapsize);
4159 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
4160 (void) close(env->me_mfd);
4161 if (env->me_fd != INVALID_HANDLE_VALUE)
4162 (void) close(env->me_fd);
4164 MDB_PID_T pid = env->me_pid;
4165 /* Clearing readers is done in this function because
4166 * me_txkey with its destructor must be disabled first.
4168 for (i = env->me_numreaders; --i >= 0; )
4169 if (env->me_txns->mti_readers[i].mr_pid == pid)
4170 env->me_txns->mti_readers[i].mr_pid = 0;
4172 if (env->me_rmutex) {
4173 CloseHandle(env->me_rmutex);
4174 if (env->me_wmutex) CloseHandle(env->me_wmutex);
4176 /* Windows automatically destroys the mutexes when
4177 * the last handle closes.
4179 #elif defined(MDB_USE_POSIX_SEM)
4180 if (env->me_rmutex != SEM_FAILED) {
4181 sem_close(env->me_rmutex);
4182 if (env->me_wmutex != SEM_FAILED)
4183 sem_close(env->me_wmutex);
4184 /* If we have the filelock: If we are the
4185 * only remaining user, clean up semaphores.
4188 mdb_env_excl_lock(env, &excl);
4190 sem_unlink(env->me_txns->mti_rmname);
4191 sem_unlink(env->me_txns->mti_wmname);
4195 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
4197 if (env->me_lfd != INVALID_HANDLE_VALUE) {
4200 /* Unlock the lockfile. Windows would have unlocked it
4201 * after closing anyway, but not necessarily at once.
4203 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4206 (void) close(env->me_lfd);
4209 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
4213 mdb_env_copyfd(MDB_env *env, HANDLE fd)
4215 MDB_txn *txn = NULL;
4221 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
4225 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
4228 /* Do the lock/unlock of the reader mutex before starting the
4229 * write txn. Otherwise other read txns could block writers.
4231 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
4236 /* We must start the actual read txn after blocking writers */
4237 mdb_txn_reset0(txn, "reset-stage1");
4239 /* Temporarily block writers until we snapshot the meta pages */
4242 rc = mdb_txn_renew0(txn);
4244 UNLOCK_MUTEX_W(env);
4249 wsize = env->me_psize * 2;
4253 DO_WRITE(rc, fd, ptr, w2, len);
4257 } else if (len > 0) {
4263 /* Non-blocking or async handles are not supported */
4269 UNLOCK_MUTEX_W(env);
4274 wsize = txn->mt_next_pgno * env->me_psize - wsize;
4276 if (wsize > MAX_WRITE)
4280 DO_WRITE(rc, fd, ptr, w2, len);
4284 } else if (len > 0) {
4301 mdb_env_copy(MDB_env *env, const char *path)
4305 HANDLE newfd = INVALID_HANDLE_VALUE;
4307 if (env->me_flags & MDB_NOSUBDIR) {
4308 lpath = (char *)path;
4311 len += sizeof(DATANAME);
4312 lpath = malloc(len);
4315 sprintf(lpath, "%s" DATANAME, path);
4318 /* The destination path must exist, but the destination file must not.
4319 * We don't want the OS to cache the writes, since the source data is
4320 * already in the OS cache.
4323 newfd = CreateFile(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
4324 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
4326 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
4328 if (newfd == INVALID_HANDLE_VALUE) {
4334 /* Set O_DIRECT if the file system supports it */
4335 if ((rc = fcntl(newfd, F_GETFL)) != -1)
4336 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
4338 #ifdef F_NOCACHE /* __APPLE__ */
4339 rc = fcntl(newfd, F_NOCACHE, 1);
4346 rc = mdb_env_copyfd(env, newfd);
4349 if (!(env->me_flags & MDB_NOSUBDIR))
4351 if (newfd != INVALID_HANDLE_VALUE)
4352 if (close(newfd) < 0 && rc == MDB_SUCCESS)
4359 mdb_env_close(MDB_env *env)
4366 VGMEMP_DESTROY(env);
4367 while ((dp = env->me_dpages) != NULL) {
4368 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
4369 env->me_dpages = dp->mp_next;
4373 mdb_env_close0(env, 0);
4377 /** Compare two items pointing at aligned size_t's */
4379 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
4381 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
4382 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
4385 /** Compare two items pointing at aligned unsigned int's */
4387 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
4389 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
4390 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
4393 /** Compare two items pointing at unsigned ints of unknown alignment.
4394 * Nodes and keys are guaranteed to be 2-byte aligned.
4397 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
4399 #if BYTE_ORDER == LITTLE_ENDIAN
4400 unsigned short *u, *c;
4403 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4404 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
4407 } while(!x && u > (unsigned short *)a->mv_data);
4410 return memcmp(a->mv_data, b->mv_data, a->mv_size);
4414 /** Compare two items lexically */
4416 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
4423 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4429 diff = memcmp(a->mv_data, b->mv_data, len);
4430 return diff ? diff : len_diff<0 ? -1 : len_diff;
4433 /** Compare two items in reverse byte order */
4435 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
4437 const unsigned char *p1, *p2, *p1_lim;
4441 p1_lim = (const unsigned char *)a->mv_data;
4442 p1 = (const unsigned char *)a->mv_data + a->mv_size;
4443 p2 = (const unsigned char *)b->mv_data + b->mv_size;
4445 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4451 while (p1 > p1_lim) {
4452 diff = *--p1 - *--p2;
4456 return len_diff<0 ? -1 : len_diff;
4459 /** Search for key within a page, using binary search.
4460 * Returns the smallest entry larger or equal to the key.
4461 * If exactp is non-null, stores whether the found entry was an exact match
4462 * in *exactp (1 or 0).
4463 * Updates the cursor index with the index of the found entry.
4464 * If no entry larger or equal to the key is found, returns NULL.
4467 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
4469 unsigned int i = 0, nkeys;
4472 MDB_page *mp = mc->mc_pg[mc->mc_top];
4473 MDB_node *node = NULL;
4478 nkeys = NUMKEYS(mp);
4483 COPY_PGNO(pgno, mp->mp_pgno);
4484 DPRINTF(("searching %u keys in %s %spage %"Z"u",
4485 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
4492 low = IS_LEAF(mp) ? 0 : 1;
4494 cmp = mc->mc_dbx->md_cmp;
4496 /* Branch pages have no data, so if using integer keys,
4497 * alignment is guaranteed. Use faster mdb_cmp_int.
4499 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
4500 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
4507 nodekey.mv_size = mc->mc_db->md_pad;
4508 node = NODEPTR(mp, 0); /* fake */
4509 while (low <= high) {
4510 i = (low + high) >> 1;
4511 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
4512 rc = cmp(key, &nodekey);
4513 DPRINTF(("found leaf index %u [%s], rc = %i",
4514 i, DKEY(&nodekey), rc));
4523 while (low <= high) {
4524 i = (low + high) >> 1;
4526 node = NODEPTR(mp, i);
4527 nodekey.mv_size = NODEKSZ(node);
4528 nodekey.mv_data = NODEKEY(node);
4530 rc = cmp(key, &nodekey);
4533 DPRINTF(("found leaf index %u [%s], rc = %i",
4534 i, DKEY(&nodekey), rc));
4536 DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
4537 i, DKEY(&nodekey), NODEPGNO(node), rc));
4548 if (rc > 0) { /* Found entry is less than the key. */
4549 i++; /* Skip to get the smallest entry larger than key. */
4551 node = NODEPTR(mp, i);
4554 *exactp = (rc == 0);
4555 /* store the key index */
4556 mc->mc_ki[mc->mc_top] = i;
4558 /* There is no entry larger or equal to the key. */
4561 /* nodeptr is fake for LEAF2 */
4567 mdb_cursor_adjust(MDB_cursor *mc, func)
4571 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4572 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
4579 /** Pop a page off the top of the cursor's stack. */
4581 mdb_cursor_pop(MDB_cursor *mc)
4585 MDB_page *top = mc->mc_pg[mc->mc_top];
4591 DPRINTF(("popped page %"Z"u off db %d cursor %p", top->mp_pgno,
4592 DDBI(mc), (void *) mc));
4596 /** Push a page onto the top of the cursor's stack. */
4598 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
4600 DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
4601 DDBI(mc), (void *) mc));
4603 if (mc->mc_snum >= CURSOR_STACK) {
4604 assert(mc->mc_snum < CURSOR_STACK);
4605 return MDB_CURSOR_FULL;
4608 mc->mc_top = mc->mc_snum++;
4609 mc->mc_pg[mc->mc_top] = mp;
4610 mc->mc_ki[mc->mc_top] = 0;
4615 /** Find the address of the page corresponding to a given page number.
4616 * @param[in] txn the transaction for this access.
4617 * @param[in] pgno the page number for the page to retrieve.
4618 * @param[out] ret address of a pointer where the page's address will be stored.
4619 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
4620 * @return 0 on success, non-zero on failure.
4623 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
4625 MDB_env *env = txn->mt_env;
4629 if (!((txn->mt_flags & MDB_TXN_RDONLY) | (env->me_flags & MDB_WRITEMAP))) {
4633 MDB_ID2L dl = tx2->mt_u.dirty_list;
4635 /* Spilled pages were dirtied in this txn and flushed
4636 * because the dirty list got full. Bring this page
4637 * back in from the map (but don't unspill it here,
4638 * leave that unless page_touch happens again).
4640 if (tx2->mt_spill_pgs) {
4641 MDB_ID pn = pgno << 1;
4642 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
4643 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
4644 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
4649 unsigned x = mdb_mid2l_search(dl, pgno);
4650 if (x <= dl[0].mid && dl[x].mid == pgno) {
4656 } while ((tx2 = tx2->mt_parent) != NULL);
4659 if (pgno < txn->mt_next_pgno) {
4661 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
4663 DPRINTF(("page %"Z"u not found", pgno));
4665 return MDB_PAGE_NOTFOUND;
4675 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
4676 * The cursor is at the root page, set up the rest of it.
4679 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
4681 MDB_page *mp = mc->mc_pg[mc->mc_top];
4685 while (IS_BRANCH(mp)) {
4689 DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
4690 assert(NUMKEYS(mp) > 1);
4691 DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
4693 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
4695 if (flags & MDB_PS_LAST)
4696 i = NUMKEYS(mp) - 1;
4699 node = mdb_node_search(mc, key, &exact);
4701 i = NUMKEYS(mp) - 1;
4703 i = mc->mc_ki[mc->mc_top];
4709 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
4712 assert(i < NUMKEYS(mp));
4713 node = NODEPTR(mp, i);
4715 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4718 mc->mc_ki[mc->mc_top] = i;
4719 if ((rc = mdb_cursor_push(mc, mp)))
4722 if (flags & MDB_PS_MODIFY) {
4723 if ((rc = mdb_page_touch(mc)) != 0)
4725 mp = mc->mc_pg[mc->mc_top];
4730 DPRINTF(("internal error, index points to a %02X page!?",
4732 return MDB_CORRUPTED;
4735 DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
4736 key ? DKEY(key) : "null"));
4737 mc->mc_flags |= C_INITIALIZED;
4738 mc->mc_flags &= ~C_EOF;
4743 /** Search for the lowest key under the current branch page.
4744 * This just bypasses a NUMKEYS check in the current page
4745 * before calling mdb_page_search_root(), because the callers
4746 * are all in situations where the current page is known to
4750 mdb_page_search_lowest(MDB_cursor *mc)
4752 MDB_page *mp = mc->mc_pg[mc->mc_top];
4753 MDB_node *node = NODEPTR(mp, 0);
4756 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4759 mc->mc_ki[mc->mc_top] = 0;
4760 if ((rc = mdb_cursor_push(mc, mp)))
4762 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
4765 /** Search for the page a given key should be in.
4766 * Push it and its parent pages on the cursor stack.
4767 * @param[in,out] mc the cursor for this operation.
4768 * @param[in] key the key to search for, or NULL for first/last page.
4769 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
4770 * are touched (updated with new page numbers).
4771 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
4772 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
4773 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
4774 * @return 0 on success, non-zero on failure.
4777 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
4782 /* Make sure the txn is still viable, then find the root from
4783 * the txn's db table and set it as the root of the cursor's stack.
4785 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
4786 DPUTS("transaction has failed, must abort");
4789 /* Make sure we're using an up-to-date root */
4790 if (*mc->mc_dbflag & DB_STALE) {
4792 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
4793 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
4800 MDB_node *leaf = mdb_node_search(&mc2,
4801 &mc->mc_dbx->md_name, &exact);
4803 return MDB_NOTFOUND;
4804 rc = mdb_node_read(mc->mc_txn, leaf, &data);
4807 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
4809 /* The txn may not know this DBI, or another process may
4810 * have dropped and recreated the DB with other flags.
4812 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
4813 return MDB_INCOMPATIBLE;
4814 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
4816 *mc->mc_dbflag &= ~DB_STALE;
4818 root = mc->mc_db->md_root;
4820 if (root == P_INVALID) { /* Tree is empty. */
4821 DPUTS("tree is empty");
4822 return MDB_NOTFOUND;
4827 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
4828 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0], NULL)) != 0)
4834 DPRINTF(("db %d root page %"Z"u has flags 0x%X",
4835 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
4837 if (flags & MDB_PS_MODIFY) {
4838 if ((rc = mdb_page_touch(mc)))
4842 if (flags & MDB_PS_ROOTONLY)
4845 return mdb_page_search_root(mc, key, flags);
4849 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
4851 MDB_txn *txn = mc->mc_txn;
4852 pgno_t pg = mp->mp_pgno;
4853 unsigned x = 0, ovpages = mp->mp_pages;
4854 MDB_env *env = txn->mt_env;
4855 MDB_IDL sl = txn->mt_spill_pgs;
4856 MDB_ID pn = pg << 1;
4859 DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
4860 /* If the page is dirty or on the spill list we just acquired it,
4861 * so we should give it back to our current free list, if any.
4862 * Otherwise put it onto the list of pages we freed in this txn.
4864 * Won't create me_pghead: me_pglast must be inited along with it.
4865 * Unsupported in nested txns: They would need to hide the page
4866 * range in ancestor txns' dirty and spilled lists.
4868 if (env->me_pghead &&
4870 ((mp->mp_flags & P_DIRTY) ||
4871 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
4875 MDB_ID2 *dl, ix, iy;
4876 rc = mdb_midl_need(&env->me_pghead, ovpages);
4879 if (!(mp->mp_flags & P_DIRTY)) {
4880 /* This page is no longer spilled */
4887 /* Remove from dirty list */
4888 dl = txn->mt_u.dirty_list;
4890 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
4898 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
4899 txn->mt_flags |= MDB_TXN_ERROR;
4900 return MDB_CORRUPTED;
4903 if (!(env->me_flags & MDB_WRITEMAP))
4904 mdb_dpage_free(env, mp);
4906 /* Insert in me_pghead */
4907 mop = env->me_pghead;
4908 j = mop[0] + ovpages;
4909 for (i = mop[0]; i && mop[i] < pg; i--)
4915 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
4919 mc->mc_db->md_overflow_pages -= ovpages;
4923 /** Return the data associated with a given node.
4924 * @param[in] txn The transaction for this operation.
4925 * @param[in] leaf The node being read.
4926 * @param[out] data Updated to point to the node's data.
4927 * @return 0 on success, non-zero on failure.
4930 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
4932 MDB_page *omp; /* overflow page */
4936 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
4937 data->mv_size = NODEDSZ(leaf);
4938 data->mv_data = NODEDATA(leaf);
4942 /* Read overflow data.
4944 data->mv_size = NODEDSZ(leaf);
4945 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
4946 if ((rc = mdb_page_get(txn, pgno, &omp, NULL)) != 0) {
4947 DPRINTF(("read overflow page %"Z"u failed", pgno));
4950 data->mv_data = METADATA(omp);
4956 mdb_get(MDB_txn *txn, MDB_dbi dbi,
4957 MDB_val *key, MDB_val *data)
4966 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
4968 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
4971 if (txn->mt_flags & MDB_TXN_ERROR)
4974 if (key->mv_size > MDB_MAXKEYSIZE) {
4975 return MDB_BAD_VALSIZE;
4978 mdb_cursor_init(&mc, txn, dbi, &mx);
4979 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
4982 /** Find a sibling for a page.
4983 * Replaces the page at the top of the cursor's stack with the
4984 * specified sibling, if one exists.
4985 * @param[in] mc The cursor for this operation.
4986 * @param[in] move_right Non-zero if the right sibling is requested,
4987 * otherwise the left sibling.
4988 * @return 0 on success, non-zero on failure.
4991 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
4997 if (mc->mc_snum < 2) {
4998 return MDB_NOTFOUND; /* root has no siblings */
5002 DPRINTF(("parent page is page %"Z"u, index %u",
5003 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
5005 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
5006 : (mc->mc_ki[mc->mc_top] == 0)) {
5007 DPRINTF(("no more keys left, moving to %s sibling",
5008 move_right ? "right" : "left"));
5009 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
5010 /* undo cursor_pop before returning */
5017 mc->mc_ki[mc->mc_top]++;
5019 mc->mc_ki[mc->mc_top]--;
5020 DPRINTF(("just moving to %s index key %u",
5021 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
5023 assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
5025 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5026 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL)) != 0) {
5027 /* mc will be inconsistent if caller does mc_snum++ as above */
5028 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
5032 mdb_cursor_push(mc, mp);
5034 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
5039 /** Move the cursor to the next data item. */
5041 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5047 if (mc->mc_flags & C_EOF) {
5048 return MDB_NOTFOUND;
5051 assert(mc->mc_flags & C_INITIALIZED);
5053 mp = mc->mc_pg[mc->mc_top];
5055 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5056 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5057 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5058 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
5059 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
5060 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
5061 if (rc == MDB_SUCCESS)
5062 MDB_GET_KEY(leaf, key);
5067 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5068 if (op == MDB_NEXT_DUP)
5069 return MDB_NOTFOUND;
5073 DPRINTF(("cursor_next: top page is %"Z"u in cursor %p", mp->mp_pgno, (void *) mc));
5074 if (mc->mc_flags & C_DEL)
5077 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
5078 DPUTS("=====> move to next sibling page");
5079 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5080 mc->mc_flags |= C_EOF;
5083 mp = mc->mc_pg[mc->mc_top];
5084 DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5086 mc->mc_ki[mc->mc_top]++;
5089 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5090 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5093 key->mv_size = mc->mc_db->md_pad;
5094 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5098 assert(IS_LEAF(mp));
5099 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5101 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5102 mdb_xcursor_init1(mc, leaf);
5105 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5108 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5109 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5110 if (rc != MDB_SUCCESS)
5115 MDB_GET_KEY(leaf, key);
5119 /** Move the cursor to the previous data item. */
5121 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5127 assert(mc->mc_flags & C_INITIALIZED);
5129 mp = mc->mc_pg[mc->mc_top];
5131 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5132 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5133 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5134 if (op == MDB_PREV || op == MDB_PREV_DUP) {
5135 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
5136 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
5137 if (rc == MDB_SUCCESS)
5138 MDB_GET_KEY(leaf, key);
5142 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5143 if (op == MDB_PREV_DUP)
5144 return MDB_NOTFOUND;
5149 DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p", mp->mp_pgno, (void *) mc));
5151 if (mc->mc_ki[mc->mc_top] == 0) {
5152 DPUTS("=====> move to prev sibling page");
5153 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
5156 mp = mc->mc_pg[mc->mc_top];
5157 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
5158 DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5160 mc->mc_ki[mc->mc_top]--;
5162 mc->mc_flags &= ~C_EOF;
5164 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5165 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5168 key->mv_size = mc->mc_db->md_pad;
5169 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5173 assert(IS_LEAF(mp));
5174 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5176 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5177 mdb_xcursor_init1(mc, leaf);
5180 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5183 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5184 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5185 if (rc != MDB_SUCCESS)
5190 MDB_GET_KEY(leaf, key);
5194 /** Set the cursor on a specific data item. */
5196 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5197 MDB_cursor_op op, int *exactp)
5201 MDB_node *leaf = NULL;
5206 if (key->mv_size == 0)
5207 return MDB_BAD_VALSIZE;
5210 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5212 /* See if we're already on the right page */
5213 if (mc->mc_flags & C_INITIALIZED) {
5216 mp = mc->mc_pg[mc->mc_top];
5218 mc->mc_ki[mc->mc_top] = 0;
5219 return MDB_NOTFOUND;
5221 if (mp->mp_flags & P_LEAF2) {
5222 nodekey.mv_size = mc->mc_db->md_pad;
5223 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
5225 leaf = NODEPTR(mp, 0);
5226 MDB_GET_KEY2(leaf, nodekey);
5228 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5230 /* Probably happens rarely, but first node on the page
5231 * was the one we wanted.
5233 mc->mc_ki[mc->mc_top] = 0;
5240 unsigned int nkeys = NUMKEYS(mp);
5242 if (mp->mp_flags & P_LEAF2) {
5243 nodekey.mv_data = LEAF2KEY(mp,
5244 nkeys-1, nodekey.mv_size);
5246 leaf = NODEPTR(mp, nkeys-1);
5247 MDB_GET_KEY2(leaf, nodekey);
5249 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5251 /* last node was the one we wanted */
5252 mc->mc_ki[mc->mc_top] = nkeys-1;
5258 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
5259 /* This is definitely the right page, skip search_page */
5260 if (mp->mp_flags & P_LEAF2) {
5261 nodekey.mv_data = LEAF2KEY(mp,
5262 mc->mc_ki[mc->mc_top], nodekey.mv_size);
5264 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5265 MDB_GET_KEY2(leaf, nodekey);
5267 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5269 /* current node was the one we wanted */
5279 /* If any parents have right-sibs, search.
5280 * Otherwise, there's nothing further.
5282 for (i=0; i<mc->mc_top; i++)
5284 NUMKEYS(mc->mc_pg[i])-1)
5286 if (i == mc->mc_top) {
5287 /* There are no other pages */
5288 mc->mc_ki[mc->mc_top] = nkeys;
5289 return MDB_NOTFOUND;
5293 /* There are no other pages */
5294 mc->mc_ki[mc->mc_top] = 0;
5295 if (op == MDB_SET_RANGE) {
5299 return MDB_NOTFOUND;
5303 rc = mdb_page_search(mc, key, 0);
5304 if (rc != MDB_SUCCESS)
5307 mp = mc->mc_pg[mc->mc_top];
5308 assert(IS_LEAF(mp));
5311 leaf = mdb_node_search(mc, key, exactp);
5312 if (exactp != NULL && !*exactp) {
5313 /* MDB_SET specified and not an exact match. */
5314 return MDB_NOTFOUND;
5318 DPUTS("===> inexact leaf not found, goto sibling");
5319 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
5320 return rc; /* no entries matched */
5321 mp = mc->mc_pg[mc->mc_top];
5322 assert(IS_LEAF(mp));
5323 leaf = NODEPTR(mp, 0);
5327 mc->mc_flags |= C_INITIALIZED;
5328 mc->mc_flags &= ~C_EOF;
5331 key->mv_size = mc->mc_db->md_pad;
5332 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5336 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5337 mdb_xcursor_init1(mc, leaf);
5340 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5341 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
5342 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5345 if (op == MDB_GET_BOTH) {
5351 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
5352 if (rc != MDB_SUCCESS)
5355 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
5357 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
5359 rc = mc->mc_dbx->md_dcmp(data, &d2);
5361 if (op == MDB_GET_BOTH || rc > 0)
5362 return MDB_NOTFOUND;
5369 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5370 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5375 /* The key already matches in all other cases */
5376 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
5377 MDB_GET_KEY(leaf, key);
5378 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
5383 /** Move the cursor to the first item in the database. */
5385 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5391 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5393 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5394 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
5395 if (rc != MDB_SUCCESS)
5398 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
5400 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
5401 mc->mc_flags |= C_INITIALIZED;
5402 mc->mc_flags &= ~C_EOF;
5404 mc->mc_ki[mc->mc_top] = 0;
5406 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5407 key->mv_size = mc->mc_db->md_pad;
5408 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
5413 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5414 mdb_xcursor_init1(mc, leaf);
5415 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5419 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5423 MDB_GET_KEY(leaf, key);
5427 /** Move the cursor to the last item in the database. */
5429 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5435 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5437 if (!(mc->mc_flags & C_EOF)) {
5439 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5440 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
5441 if (rc != MDB_SUCCESS)
5444 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
5447 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
5448 mc->mc_flags |= C_INITIALIZED|C_EOF;
5449 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5451 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5452 key->mv_size = mc->mc_db->md_pad;
5453 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
5458 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5459 mdb_xcursor_init1(mc, leaf);
5460 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5464 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5469 MDB_GET_KEY(leaf, key);
5474 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5479 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
5483 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
5487 case MDB_GET_CURRENT:
5488 if (!(mc->mc_flags & C_INITIALIZED)) {
5491 MDB_page *mp = mc->mc_pg[mc->mc_top];
5492 int nkeys = NUMKEYS(mp);
5493 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
5494 mc->mc_ki[mc->mc_top] = nkeys;
5500 key->mv_size = mc->mc_db->md_pad;
5501 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5503 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5504 MDB_GET_KEY(leaf, key);
5506 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5507 if (mc->mc_flags & C_DEL)
5508 mdb_xcursor_init1(mc, leaf);
5509 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
5511 rc = mdb_node_read(mc->mc_txn, leaf, data);
5518 case MDB_GET_BOTH_RANGE:
5523 if (mc->mc_xcursor == NULL) {
5524 rc = MDB_INCOMPATIBLE;
5533 } else if (key->mv_size > MDB_MAXKEYSIZE) {
5534 rc = MDB_BAD_VALSIZE;
5535 } else if (op == MDB_SET_RANGE)
5536 rc = mdb_cursor_set(mc, key, data, op, NULL);
5538 rc = mdb_cursor_set(mc, key, data, op, &exact);
5540 case MDB_GET_MULTIPLE:
5541 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5545 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5546 rc = MDB_INCOMPATIBLE;
5550 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
5551 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
5554 case MDB_NEXT_MULTIPLE:
5559 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5560 rc = MDB_INCOMPATIBLE;
5563 if (!(mc->mc_flags & C_INITIALIZED))
5564 rc = mdb_cursor_first(mc, key, data);
5566 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
5567 if (rc == MDB_SUCCESS) {
5568 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
5571 mx = &mc->mc_xcursor->mx_cursor;
5572 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
5574 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
5575 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
5583 case MDB_NEXT_NODUP:
5584 if (!(mc->mc_flags & C_INITIALIZED))
5585 rc = mdb_cursor_first(mc, key, data);
5587 rc = mdb_cursor_next(mc, key, data, op);
5591 case MDB_PREV_NODUP:
5592 if (!(mc->mc_flags & C_INITIALIZED)) {
5593 rc = mdb_cursor_last(mc, key, data);
5596 mc->mc_flags |= C_INITIALIZED;
5597 mc->mc_ki[mc->mc_top]++;
5599 rc = mdb_cursor_prev(mc, key, data, op);
5602 rc = mdb_cursor_first(mc, key, data);
5605 mfunc = mdb_cursor_first;
5607 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5611 if (mc->mc_xcursor == NULL) {
5612 rc = MDB_INCOMPATIBLE;
5615 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
5619 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
5622 rc = mdb_cursor_last(mc, key, data);
5625 mfunc = mdb_cursor_last;
5628 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
5633 if (mc->mc_flags & C_DEL)
5634 mc->mc_flags ^= C_DEL;
5639 /** Touch all the pages in the cursor stack. Set mc_top.
5640 * Makes sure all the pages are writable, before attempting a write operation.
5641 * @param[in] mc The cursor to operate on.
5644 mdb_cursor_touch(MDB_cursor *mc)
5646 int rc = MDB_SUCCESS;
5648 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
5651 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
5652 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
5655 *mc->mc_dbflag |= DB_DIRTY;
5660 rc = mdb_page_touch(mc);
5661 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
5662 mc->mc_top = mc->mc_snum-1;
5667 /** Do not spill pages to disk if txn is getting full, may fail instead */
5668 #define MDB_NOSPILL 0x8000
5671 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5674 enum { MDB_NO_ROOT = MDB_LAST_ERRCODE+10 }; /* internal code */
5675 MDB_env *env = mc->mc_txn->mt_env;
5676 MDB_node *leaf = NULL;
5677 MDB_val xdata, *rdata, dkey;
5679 int do_sub = 0, insert = 0;
5680 unsigned int mcount = 0, dcount = 0, nospill;
5683 char dbuf[MDB_MAXKEYSIZE+1];
5684 unsigned int nflags;
5687 /* Check this first so counter will always be zero on any
5690 if (flags & MDB_MULTIPLE) {
5691 dcount = data[1].mv_size;
5692 data[1].mv_size = 0;
5693 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
5694 return MDB_INCOMPATIBLE;
5697 nospill = flags & MDB_NOSPILL;
5698 flags &= ~MDB_NOSPILL;
5700 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
5701 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
5703 if (flags != MDB_CURRENT && (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE))
5704 return MDB_BAD_VALSIZE;
5706 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT) && data->mv_size > MDB_MAXKEYSIZE)
5707 return MDB_BAD_VALSIZE;
5709 #if SIZE_MAX > MAXDATASIZE
5710 if (data->mv_size > MAXDATASIZE)
5711 return MDB_BAD_VALSIZE;
5714 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
5715 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
5719 if (flags == MDB_CURRENT) {
5720 if (!(mc->mc_flags & C_INITIALIZED))
5723 } else if (mc->mc_db->md_root == P_INVALID) {
5724 /* new database, cursor has nothing to point to */
5727 mc->mc_flags &= ~C_INITIALIZED;
5732 if (flags & MDB_APPEND) {
5734 rc = mdb_cursor_last(mc, &k2, &d2);
5736 rc = mc->mc_dbx->md_cmp(key, &k2);
5739 mc->mc_ki[mc->mc_top]++;
5741 /* new key is <= last key */
5746 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
5748 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
5749 DPRINTF(("duplicate key [%s]", DKEY(key)));
5751 return MDB_KEYEXIST;
5753 if (rc && rc != MDB_NOTFOUND)
5757 if (mc->mc_flags & C_DEL)
5758 mc->mc_flags ^= C_DEL;
5760 /* Cursor is positioned, check for room in the dirty list */
5762 if (flags & MDB_MULTIPLE) {
5764 xdata.mv_size = data->mv_size * dcount;
5768 if ((rc2 = mdb_page_spill(mc, key, rdata)))
5772 if (rc == MDB_NO_ROOT) {
5774 /* new database, write a root leaf page */
5775 DPUTS("allocating new root leaf page");
5776 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
5779 mdb_cursor_push(mc, np);
5780 mc->mc_db->md_root = np->mp_pgno;
5781 mc->mc_db->md_depth++;
5782 *mc->mc_dbflag |= DB_DIRTY;
5783 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
5785 np->mp_flags |= P_LEAF2;
5786 mc->mc_flags |= C_INITIALIZED;
5788 /* make sure all cursor pages are writable */
5789 rc2 = mdb_cursor_touch(mc);
5794 /* The key already exists */
5795 if (rc == MDB_SUCCESS) {
5799 /* there's only a key anyway, so this is a no-op */
5800 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5801 unsigned int ksize = mc->mc_db->md_pad;
5802 if (key->mv_size != ksize)
5803 return MDB_BAD_VALSIZE;
5804 if (flags == MDB_CURRENT) {
5805 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
5806 memcpy(ptr, key->mv_data, ksize);
5812 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5813 olddata.mv_size = NODEDSZ(leaf);
5814 olddata.mv_data = NODEDATA(leaf);
5817 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
5818 mp = fp = xdata.mv_data = env->me_pbuf;
5819 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
5821 /* Was a single item before, must convert now */
5822 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5823 /* Just overwrite the current item */
5824 if (flags == MDB_CURRENT)
5828 #if UINT_MAX < SIZE_MAX
5829 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && dkey.mv_size == sizeof(size_t))
5830 #ifdef MISALIGNED_OK
5831 mc->mc_dbx->md_dcmp = mdb_cmp_long;
5833 mc->mc_dbx->md_dcmp = mdb_cmp_cint;
5836 /* if data matches, skip it */
5837 if (!mc->mc_dbx->md_dcmp(data, &dkey)) {
5838 if (flags & MDB_NODUPDATA)
5840 else if (flags & MDB_MULTIPLE)
5847 /* create a fake page for the dup items */
5848 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
5849 dkey.mv_data = dbuf;
5850 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
5851 fp->mp_lower = PAGEHDRSZ;
5852 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
5853 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5854 fp->mp_flags |= P_LEAF2;
5855 fp->mp_pad = data->mv_size;
5856 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
5858 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
5859 (dkey.mv_size & 1) + (data->mv_size & 1);
5861 fp->mp_upper = xdata.mv_size;
5862 } else if (leaf->mn_flags & F_SUBDATA) {
5863 /* Data is on sub-DB, just store it */
5864 flags |= F_DUPDATA|F_SUBDATA;
5867 /* See if we need to convert from fake page to subDB */
5868 unsigned int offset;
5872 fp = olddata.mv_data;
5875 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5876 offset = EVEN(NODESIZE + sizeof(indx_t) +
5880 offset = fp->mp_pad;
5881 if (SIZELEFT(fp) < offset) {
5882 offset *= 4; /* space for 4 more */
5885 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
5887 fp->mp_flags |= P_DIRTY;
5888 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
5889 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
5893 fp_flags = fp->mp_flags;
5894 xdata.mv_size = olddata.mv_size + offset;
5895 if (NODESIZE + sizeof(indx_t) + NODEKSZ(leaf) + xdata.mv_size
5896 >= env->me_nodemax) {
5897 /* yes, convert it */
5898 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5899 dummy.md_pad = fp->mp_pad;
5900 dummy.md_flags = MDB_DUPFIXED;
5901 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
5902 dummy.md_flags |= MDB_INTEGERKEY;
5908 dummy.md_branch_pages = 0;
5909 dummy.md_leaf_pages = 1;
5910 dummy.md_overflow_pages = 0;
5911 dummy.md_entries = NUMKEYS(fp);
5912 xdata.mv_size = sizeof(MDB_db);
5913 xdata.mv_data = &dummy;
5914 if ((rc = mdb_page_alloc(mc, 1, &mp)))
5916 offset = env->me_psize - olddata.mv_size;
5917 flags |= F_DUPDATA|F_SUBDATA;
5918 dummy.md_root = mp->mp_pgno;
5919 fp_flags &= ~P_SUBP;
5921 mp->mp_flags = fp_flags | P_DIRTY;
5922 mp->mp_pad = fp->mp_pad;
5923 mp->mp_lower = fp->mp_lower;
5924 mp->mp_upper = fp->mp_upper + offset;
5926 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
5928 memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper,
5929 olddata.mv_size - fp->mp_upper);
5930 for (i=0; i<NUMKEYS(fp); i++)
5931 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
5938 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5942 /* overflow page overwrites need special handling */
5943 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5946 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
5948 memcpy(&pg, olddata.mv_data, sizeof(pg));
5949 if ((rc2 = mdb_page_get(mc->mc_txn, pg, &omp, &level)) != 0)
5951 ovpages = omp->mp_pages;
5953 /* Is the ov page large enough? */
5954 if (ovpages >= dpages) {
5955 if (!(omp->mp_flags & P_DIRTY) &&
5956 (level || (env->me_flags & MDB_WRITEMAP)))
5958 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
5961 level = 0; /* dirty in this txn or clean */
5964 if (omp->mp_flags & P_DIRTY) {
5965 /* yes, overwrite it. Note in this case we don't
5966 * bother to try shrinking the page if the new data
5967 * is smaller than the overflow threshold.
5970 /* It is writable only in a parent txn */
5971 size_t sz = (size_t) env->me_psize * ovpages, off;
5972 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
5978 mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
5979 if (!(flags & MDB_RESERVE)) {
5980 /* Copy end of page, adjusting alignment so
5981 * compiler may copy words instead of bytes.
5983 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
5984 memcpy((size_t *)((char *)np + off),
5985 (size_t *)((char *)omp + off), sz - off);
5988 memcpy(np, omp, sz); /* Copy beginning of page */
5991 SETDSZ(leaf, data->mv_size);
5992 if (F_ISSET(flags, MDB_RESERVE))
5993 data->mv_data = METADATA(omp);
5995 memcpy(METADATA(omp), data->mv_data, data->mv_size);
5999 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
6001 } else if (data->mv_size == olddata.mv_size) {
6002 /* same size, just replace it. Note that we could
6003 * also reuse this node if the new data is smaller,
6004 * but instead we opt to shrink the node in that case.
6006 if (F_ISSET(flags, MDB_RESERVE))
6007 data->mv_data = olddata.mv_data;
6008 else if (data->mv_size)
6009 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
6011 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
6014 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
6015 mc->mc_db->md_entries--;
6017 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
6024 nflags = flags & NODE_ADD_FLAGS;
6025 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
6026 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
6027 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
6028 nflags &= ~MDB_APPEND;
6030 nflags |= MDB_SPLIT_REPLACE;
6031 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
6033 /* There is room already in this leaf page. */
6034 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
6035 if (rc == 0 && !do_sub && insert) {
6036 /* Adjust other cursors pointing to mp */
6037 MDB_cursor *m2, *m3;
6038 MDB_dbi dbi = mc->mc_dbi;
6039 unsigned i = mc->mc_top;
6040 MDB_page *mp = mc->mc_pg[i];
6042 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6043 if (mc->mc_flags & C_SUB)
6044 m3 = &m2->mc_xcursor->mx_cursor;
6047 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
6048 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
6055 if (rc != MDB_SUCCESS)
6056 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6058 /* Now store the actual data in the child DB. Note that we're
6059 * storing the user data in the keys field, so there are strict
6060 * size limits on dupdata. The actual data fields of the child
6061 * DB are all zero size.
6068 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6069 if (flags & MDB_CURRENT) {
6070 xflags = MDB_CURRENT|MDB_NOSPILL;
6072 mdb_xcursor_init1(mc, leaf);
6073 xflags = (flags & MDB_NODUPDATA) ?
6074 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
6076 /* converted, write the original data first */
6078 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
6082 /* Adjust other cursors pointing to mp */
6084 unsigned i = mc->mc_top;
6085 MDB_page *mp = mc->mc_pg[i];
6087 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6088 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6089 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6090 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
6091 mdb_xcursor_init1(m2, leaf);
6095 /* we've done our job */
6098 if (flags & MDB_APPENDDUP)
6099 xflags |= MDB_APPEND;
6100 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
6101 if (flags & F_SUBDATA) {
6102 void *db = NODEDATA(leaf);
6103 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6106 /* sub-writes might have failed so check rc again.
6107 * Don't increment count if we just replaced an existing item.
6109 if (!rc && !(flags & MDB_CURRENT))
6110 mc->mc_db->md_entries++;
6111 if (flags & MDB_MULTIPLE) {
6115 /* let caller know how many succeeded, if any */
6116 data[1].mv_size = mcount;
6117 if (mcount < dcount) {
6118 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
6125 /* If we succeeded and the key didn't exist before, make sure
6126 * the cursor is marked valid.
6129 mc->mc_flags |= C_INITIALIZED;
6134 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
6140 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
6141 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6143 if (!(mc->mc_flags & C_INITIALIZED))
6146 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6147 return MDB_NOTFOUND;
6149 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
6152 rc = mdb_cursor_touch(mc);
6156 mp = mc->mc_pg[mc->mc_top];
6157 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6159 if (!IS_LEAF2(mp) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6160 if (!(flags & MDB_NODUPDATA)) {
6161 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
6162 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6164 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
6165 /* If sub-DB still has entries, we're done */
6166 if (mc->mc_xcursor->mx_db.md_entries) {
6167 if (leaf->mn_flags & F_SUBDATA) {
6168 /* update subDB info */
6169 void *db = NODEDATA(leaf);
6170 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6173 /* shrink fake page */
6174 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
6175 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6176 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6177 /* fix other sub-DB cursors pointed at this fake page */
6178 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6179 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6180 if (m2->mc_pg[mc->mc_top] == mp &&
6181 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
6182 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6185 mc->mc_db->md_entries--;
6186 mc->mc_flags |= C_DEL;
6189 /* otherwise fall thru and delete the sub-DB */
6192 if (leaf->mn_flags & F_SUBDATA) {
6193 /* add all the child DB's pages to the free list */
6194 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6195 if (rc == MDB_SUCCESS) {
6196 mc->mc_db->md_entries -=
6197 mc->mc_xcursor->mx_db.md_entries;
6202 return mdb_cursor_del0(mc, leaf);
6205 /** Allocate and initialize new pages for a database.
6206 * @param[in] mc a cursor on the database being added to.
6207 * @param[in] flags flags defining what type of page is being allocated.
6208 * @param[in] num the number of pages to allocate. This is usually 1,
6209 * unless allocating overflow pages for a large record.
6210 * @param[out] mp Address of a page, or NULL on failure.
6211 * @return 0 on success, non-zero on failure.
6214 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
6219 if ((rc = mdb_page_alloc(mc, num, &np)))
6221 DPRINTF(("allocated new mpage %"Z"u, page size %u",
6222 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
6223 np->mp_flags = flags | P_DIRTY;
6224 np->mp_lower = PAGEHDRSZ;
6225 np->mp_upper = mc->mc_txn->mt_env->me_psize;
6228 mc->mc_db->md_branch_pages++;
6229 else if (IS_LEAF(np))
6230 mc->mc_db->md_leaf_pages++;
6231 else if (IS_OVERFLOW(np)) {
6232 mc->mc_db->md_overflow_pages += num;
6240 /** Calculate the size of a leaf node.
6241 * The size depends on the environment's page size; if a data item
6242 * is too large it will be put onto an overflow page and the node
6243 * size will only include the key and not the data. Sizes are always
6244 * rounded up to an even number of bytes, to guarantee 2-byte alignment
6245 * of the #MDB_node headers.
6246 * @param[in] env The environment handle.
6247 * @param[in] key The key for the node.
6248 * @param[in] data The data for the node.
6249 * @return The number of bytes needed to store the node.
6252 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
6256 sz = LEAFSIZE(key, data);
6257 if (sz >= env->me_nodemax) {
6258 /* put on overflow page */
6259 sz -= data->mv_size - sizeof(pgno_t);
6262 return EVEN(sz + sizeof(indx_t));
6265 /** Calculate the size of a branch node.
6266 * The size should depend on the environment's page size but since
6267 * we currently don't support spilling large keys onto overflow
6268 * pages, it's simply the size of the #MDB_node header plus the
6269 * size of the key. Sizes are always rounded up to an even number
6270 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
6271 * @param[in] env The environment handle.
6272 * @param[in] key The key for the node.
6273 * @return The number of bytes needed to store the node.
6276 mdb_branch_size(MDB_env *env, MDB_val *key)
6281 if (sz >= env->me_nodemax) {
6282 /* put on overflow page */
6283 /* not implemented */
6284 /* sz -= key->size - sizeof(pgno_t); */
6287 return sz + sizeof(indx_t);
6290 /** Add a node to the page pointed to by the cursor.
6291 * @param[in] mc The cursor for this operation.
6292 * @param[in] indx The index on the page where the new node should be added.
6293 * @param[in] key The key for the new node.
6294 * @param[in] data The data for the new node, if any.
6295 * @param[in] pgno The page number, if adding a branch node.
6296 * @param[in] flags Flags for the node.
6297 * @return 0 on success, non-zero on failure. Possible errors are:
6299 * <li>ENOMEM - failed to allocate overflow pages for the node.
6300 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
6301 * should never happen since all callers already calculate the
6302 * page's free space before calling this function.
6306 mdb_node_add(MDB_cursor *mc, indx_t indx,
6307 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
6310 size_t node_size = NODESIZE;
6314 MDB_page *mp = mc->mc_pg[mc->mc_top];
6315 MDB_page *ofp = NULL; /* overflow page */
6318 assert(mp->mp_upper >= mp->mp_lower);
6320 DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
6321 IS_LEAF(mp) ? "leaf" : "branch",
6322 IS_SUBP(mp) ? "sub-" : "",
6323 mp->mp_pgno, indx, data ? data->mv_size : 0,
6324 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
6327 /* Move higher keys up one slot. */
6328 int ksize = mc->mc_db->md_pad, dif;
6329 char *ptr = LEAF2KEY(mp, indx, ksize);
6330 dif = NUMKEYS(mp) - indx;
6332 memmove(ptr+ksize, ptr, dif*ksize);
6333 /* insert new key */
6334 memcpy(ptr, key->mv_data, ksize);
6336 /* Just using these for counting */
6337 mp->mp_lower += sizeof(indx_t);
6338 mp->mp_upper -= ksize - sizeof(indx_t);
6342 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
6344 node_size += key->mv_size;
6347 if (F_ISSET(flags, F_BIGDATA)) {
6348 /* Data already on overflow page. */
6349 node_size += sizeof(pgno_t);
6350 } else if (node_size + data->mv_size >= mc->mc_txn->mt_env->me_nodemax) {
6351 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
6353 /* Put data on overflow page. */
6354 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
6355 data->mv_size, node_size+data->mv_size));
6356 node_size = EVEN(node_size + sizeof(pgno_t));
6357 if ((ssize_t)node_size > room)
6359 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
6361 DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
6365 node_size += data->mv_size;
6368 node_size = EVEN(node_size);
6369 if ((ssize_t)node_size > room)
6373 /* Move higher pointers up one slot. */
6374 for (i = NUMKEYS(mp); i > indx; i--)
6375 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
6377 /* Adjust free space offsets. */
6378 ofs = mp->mp_upper - node_size;
6379 assert(ofs >= mp->mp_lower + sizeof(indx_t));
6380 mp->mp_ptrs[indx] = ofs;
6382 mp->mp_lower += sizeof(indx_t);
6384 /* Write the node data. */
6385 node = NODEPTR(mp, indx);
6386 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
6387 node->mn_flags = flags;
6389 SETDSZ(node,data->mv_size);
6394 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6399 if (F_ISSET(flags, F_BIGDATA))
6400 memcpy(node->mn_data + key->mv_size, data->mv_data,
6402 else if (F_ISSET(flags, MDB_RESERVE))
6403 data->mv_data = node->mn_data + key->mv_size;
6405 memcpy(node->mn_data + key->mv_size, data->mv_data,
6408 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
6410 if (F_ISSET(flags, MDB_RESERVE))
6411 data->mv_data = METADATA(ofp);
6413 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
6420 DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
6421 mp->mp_pgno, NUMKEYS(mp)));
6422 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
6423 DPRINTF(("node size = %"Z"u", node_size));
6424 return MDB_PAGE_FULL;
6427 /** Delete the specified node from a page.
6428 * @param[in] mp The page to operate on.
6429 * @param[in] indx The index of the node to delete.
6430 * @param[in] ksize The size of a node. Only used if the page is
6431 * part of a #MDB_DUPFIXED database.
6434 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
6437 indx_t i, j, numkeys, ptr;
6444 COPY_PGNO(pgno, mp->mp_pgno);
6445 DPRINTF(("delete node %u on %s page %"Z"u", indx,
6446 IS_LEAF(mp) ? "leaf" : "branch", pgno));
6449 assert(indx < NUMKEYS(mp));
6452 int x = NUMKEYS(mp) - 1 - indx;
6453 base = LEAF2KEY(mp, indx, ksize);
6455 memmove(base, base + ksize, x * ksize);
6456 mp->mp_lower -= sizeof(indx_t);
6457 mp->mp_upper += ksize - sizeof(indx_t);
6461 node = NODEPTR(mp, indx);
6462 sz = NODESIZE + node->mn_ksize;
6464 if (F_ISSET(node->mn_flags, F_BIGDATA))
6465 sz += sizeof(pgno_t);
6467 sz += NODEDSZ(node);
6471 ptr = mp->mp_ptrs[indx];
6472 numkeys = NUMKEYS(mp);
6473 for (i = j = 0; i < numkeys; i++) {
6475 mp->mp_ptrs[j] = mp->mp_ptrs[i];
6476 if (mp->mp_ptrs[i] < ptr)
6477 mp->mp_ptrs[j] += sz;
6482 base = (char *)mp + mp->mp_upper;
6483 memmove(base + sz, base, ptr - mp->mp_upper);
6485 mp->mp_lower -= sizeof(indx_t);
6489 /** Compact the main page after deleting a node on a subpage.
6490 * @param[in] mp The main page to operate on.
6491 * @param[in] indx The index of the subpage on the main page.
6494 mdb_node_shrink(MDB_page *mp, indx_t indx)
6501 indx_t i, numkeys, ptr;
6503 node = NODEPTR(mp, indx);
6504 sp = (MDB_page *)NODEDATA(node);
6505 osize = NODEDSZ(node);
6507 delta = sp->mp_upper - sp->mp_lower;
6508 SETDSZ(node, osize - delta);
6509 xp = (MDB_page *)((char *)sp + delta);
6511 /* shift subpage upward */
6513 nsize = NUMKEYS(sp) * sp->mp_pad;
6514 memmove(METADATA(xp), METADATA(sp), nsize);
6517 numkeys = NUMKEYS(sp);
6518 for (i=numkeys-1; i>=0; i--)
6519 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
6521 xp->mp_upper = sp->mp_lower;
6522 xp->mp_lower = sp->mp_lower;
6523 xp->mp_flags = sp->mp_flags;
6524 xp->mp_pad = sp->mp_pad;
6525 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
6527 /* shift lower nodes upward */
6528 ptr = mp->mp_ptrs[indx];
6529 numkeys = NUMKEYS(mp);
6530 for (i = 0; i < numkeys; i++) {
6531 if (mp->mp_ptrs[i] <= ptr)
6532 mp->mp_ptrs[i] += delta;
6535 base = (char *)mp + mp->mp_upper;
6536 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
6537 mp->mp_upper += delta;
6540 /** Initial setup of a sorted-dups cursor.
6541 * Sorted duplicates are implemented as a sub-database for the given key.
6542 * The duplicate data items are actually keys of the sub-database.
6543 * Operations on the duplicate data items are performed using a sub-cursor
6544 * initialized when the sub-database is first accessed. This function does
6545 * the preliminary setup of the sub-cursor, filling in the fields that
6546 * depend only on the parent DB.
6547 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6550 mdb_xcursor_init0(MDB_cursor *mc)
6552 MDB_xcursor *mx = mc->mc_xcursor;
6554 mx->mx_cursor.mc_xcursor = NULL;
6555 mx->mx_cursor.mc_txn = mc->mc_txn;
6556 mx->mx_cursor.mc_db = &mx->mx_db;
6557 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
6558 mx->mx_cursor.mc_dbi = mc->mc_dbi;
6559 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
6560 mx->mx_cursor.mc_snum = 0;
6561 mx->mx_cursor.mc_top = 0;
6562 mx->mx_cursor.mc_flags = C_SUB;
6563 mx->mx_dbx.md_name.mv_size = 0;
6564 mx->mx_dbx.md_name.mv_data = NULL;
6565 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
6566 mx->mx_dbx.md_dcmp = NULL;
6567 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
6570 /** Final setup of a sorted-dups cursor.
6571 * Sets up the fields that depend on the data from the main cursor.
6572 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6573 * @param[in] node The data containing the #MDB_db record for the
6574 * sorted-dup database.
6577 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
6579 MDB_xcursor *mx = mc->mc_xcursor;
6581 if (node->mn_flags & F_SUBDATA) {
6582 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
6583 mx->mx_cursor.mc_pg[0] = 0;
6584 mx->mx_cursor.mc_snum = 0;
6585 mx->mx_cursor.mc_top = 0;
6586 mx->mx_cursor.mc_flags = C_SUB;
6588 MDB_page *fp = NODEDATA(node);
6589 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
6590 mx->mx_db.md_flags = 0;
6591 mx->mx_db.md_depth = 1;
6592 mx->mx_db.md_branch_pages = 0;
6593 mx->mx_db.md_leaf_pages = 1;
6594 mx->mx_db.md_overflow_pages = 0;
6595 mx->mx_db.md_entries = NUMKEYS(fp);
6596 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
6597 mx->mx_cursor.mc_snum = 1;
6598 mx->mx_cursor.mc_top = 0;
6599 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
6600 mx->mx_cursor.mc_pg[0] = fp;
6601 mx->mx_cursor.mc_ki[0] = 0;
6602 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6603 mx->mx_db.md_flags = MDB_DUPFIXED;
6604 mx->mx_db.md_pad = fp->mp_pad;
6605 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6606 mx->mx_db.md_flags |= MDB_INTEGERKEY;
6609 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
6610 mx->mx_db.md_root));
6611 mx->mx_dbflag = DB_VALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
6612 #if UINT_MAX < SIZE_MAX
6613 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
6614 #ifdef MISALIGNED_OK
6615 mx->mx_dbx.md_cmp = mdb_cmp_long;
6617 mx->mx_dbx.md_cmp = mdb_cmp_cint;
6622 /** Initialize a cursor for a given transaction and database. */
6624 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
6627 mc->mc_backup = NULL;
6630 mc->mc_db = &txn->mt_dbs[dbi];
6631 mc->mc_dbx = &txn->mt_dbxs[dbi];
6632 mc->mc_dbflag = &txn->mt_dbflags[dbi];
6637 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
6639 mc->mc_xcursor = mx;
6640 mdb_xcursor_init0(mc);
6642 mc->mc_xcursor = NULL;
6644 if (*mc->mc_dbflag & DB_STALE) {
6645 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
6650 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
6653 size_t size = sizeof(MDB_cursor);
6655 if (txn == NULL || ret == NULL || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
6658 if (txn->mt_flags & MDB_TXN_ERROR)
6661 /* Allow read access to the freelist */
6662 if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
6665 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
6666 size += sizeof(MDB_xcursor);
6668 if ((mc = malloc(size)) != NULL) {
6669 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
6670 if (txn->mt_cursors) {
6671 mc->mc_next = txn->mt_cursors[dbi];
6672 txn->mt_cursors[dbi] = mc;
6673 mc->mc_flags |= C_UNTRACK;
6685 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
6687 if (txn == NULL || mc == NULL || mc->mc_dbi >= txn->mt_numdbs)
6690 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
6693 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
6697 /* Return the count of duplicate data items for the current key */
6699 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
6703 if (mc == NULL || countp == NULL)
6706 if (mc->mc_xcursor == NULL)
6707 return MDB_INCOMPATIBLE;
6709 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6710 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6713 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
6716 *countp = mc->mc_xcursor->mx_db.md_entries;
6722 mdb_cursor_close(MDB_cursor *mc)
6724 if (mc && !mc->mc_backup) {
6725 /* remove from txn, if tracked */
6726 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
6727 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
6728 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
6730 *prev = mc->mc_next;
6737 mdb_cursor_txn(MDB_cursor *mc)
6739 if (!mc) return NULL;
6744 mdb_cursor_dbi(MDB_cursor *mc)
6750 /** Replace the key for a node with a new key.
6751 * @param[in] mc Cursor pointing to the node to operate on.
6752 * @param[in] key The new key to use.
6753 * @return 0 on success, non-zero on failure.
6756 mdb_update_key(MDB_cursor *mc, MDB_val *key)
6762 int delta, ksize, oksize;
6763 indx_t ptr, i, numkeys, indx;
6766 indx = mc->mc_ki[mc->mc_top];
6767 mp = mc->mc_pg[mc->mc_top];
6768 node = NODEPTR(mp, indx);
6769 ptr = mp->mp_ptrs[indx];
6773 char kbuf2[(MDB_MAXKEYSIZE*2+1)];
6774 k2.mv_data = NODEKEY(node);
6775 k2.mv_size = node->mn_ksize;
6776 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
6778 mdb_dkey(&k2, kbuf2),
6784 /* Sizes must be 2-byte aligned. */
6785 ksize = EVEN(key->mv_size);
6786 oksize = EVEN(node->mn_ksize);
6787 delta = ksize - oksize;
6789 /* Shift node contents if EVEN(key length) changed. */
6791 if (delta > 0 && SIZELEFT(mp) < delta) {
6793 /* not enough space left, do a delete and split */
6794 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
6795 pgno = NODEPGNO(node);
6796 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
6797 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
6800 numkeys = NUMKEYS(mp);
6801 for (i = 0; i < numkeys; i++) {
6802 if (mp->mp_ptrs[i] <= ptr)
6803 mp->mp_ptrs[i] -= delta;
6806 base = (char *)mp + mp->mp_upper;
6807 len = ptr - mp->mp_upper + NODESIZE;
6808 memmove(base - delta, base, len);
6809 mp->mp_upper -= delta;
6811 node = NODEPTR(mp, indx);
6814 /* But even if no shift was needed, update ksize */
6815 if (node->mn_ksize != key->mv_size)
6816 node->mn_ksize = key->mv_size;
6819 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6825 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
6827 /** Move a node from csrc to cdst.
6830 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
6837 unsigned short flags;
6841 /* Mark src and dst as dirty. */
6842 if ((rc = mdb_page_touch(csrc)) ||
6843 (rc = mdb_page_touch(cdst)))
6846 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6847 key.mv_size = csrc->mc_db->md_pad;
6848 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
6850 data.mv_data = NULL;
6854 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
6855 assert(!((size_t)srcnode&1));
6856 srcpg = NODEPGNO(srcnode);
6857 flags = srcnode->mn_flags;
6858 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6859 unsigned int snum = csrc->mc_snum;
6861 /* must find the lowest key below src */
6862 mdb_page_search_lowest(csrc);
6863 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6864 key.mv_size = csrc->mc_db->md_pad;
6865 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6867 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6868 key.mv_size = NODEKSZ(s2);
6869 key.mv_data = NODEKEY(s2);
6871 csrc->mc_snum = snum--;
6872 csrc->mc_top = snum;
6874 key.mv_size = NODEKSZ(srcnode);
6875 key.mv_data = NODEKEY(srcnode);
6877 data.mv_size = NODEDSZ(srcnode);
6878 data.mv_data = NODEDATA(srcnode);
6880 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
6881 unsigned int snum = cdst->mc_snum;
6884 /* must find the lowest key below dst */
6885 mdb_page_search_lowest(cdst);
6886 if (IS_LEAF2(cdst->mc_pg[cdst->mc_top])) {
6887 bkey.mv_size = cdst->mc_db->md_pad;
6888 bkey.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, bkey.mv_size);
6890 s2 = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
6891 bkey.mv_size = NODEKSZ(s2);
6892 bkey.mv_data = NODEKEY(s2);
6894 cdst->mc_snum = snum--;
6895 cdst->mc_top = snum;
6896 mdb_cursor_copy(cdst, &mn);
6898 rc = mdb_update_key(&mn, &bkey);
6903 DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
6904 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
6905 csrc->mc_ki[csrc->mc_top],
6907 csrc->mc_pg[csrc->mc_top]->mp_pgno,
6908 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
6910 /* Add the node to the destination page.
6912 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
6913 if (rc != MDB_SUCCESS)
6916 /* Delete the node from the source page.
6918 mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
6921 /* Adjust other cursors pointing to mp */
6922 MDB_cursor *m2, *m3;
6923 MDB_dbi dbi = csrc->mc_dbi;
6924 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
6926 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6927 if (csrc->mc_flags & C_SUB)
6928 m3 = &m2->mc_xcursor->mx_cursor;
6931 if (m3 == csrc) continue;
6932 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
6933 csrc->mc_ki[csrc->mc_top]) {
6934 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
6935 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
6940 /* Update the parent separators.
6942 if (csrc->mc_ki[csrc->mc_top] == 0) {
6943 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
6944 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6945 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6947 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6948 key.mv_size = NODEKSZ(srcnode);
6949 key.mv_data = NODEKEY(srcnode);
6951 DPRINTF(("update separator for source page %"Z"u to [%s]",
6952 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
6953 mdb_cursor_copy(csrc, &mn);
6956 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
6959 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6961 indx_t ix = csrc->mc_ki[csrc->mc_top];
6962 nullkey.mv_size = 0;
6963 csrc->mc_ki[csrc->mc_top] = 0;
6964 rc = mdb_update_key(csrc, &nullkey);
6965 csrc->mc_ki[csrc->mc_top] = ix;
6966 assert(rc == MDB_SUCCESS);
6970 if (cdst->mc_ki[cdst->mc_top] == 0) {
6971 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
6972 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6973 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
6975 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
6976 key.mv_size = NODEKSZ(srcnode);
6977 key.mv_data = NODEKEY(srcnode);
6979 DPRINTF(("update separator for destination page %"Z"u to [%s]",
6980 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
6981 mdb_cursor_copy(cdst, &mn);
6984 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
6987 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
6989 indx_t ix = cdst->mc_ki[cdst->mc_top];
6990 nullkey.mv_size = 0;
6991 cdst->mc_ki[cdst->mc_top] = 0;
6992 rc = mdb_update_key(cdst, &nullkey);
6993 cdst->mc_ki[cdst->mc_top] = ix;
6994 assert(rc == MDB_SUCCESS);
7001 /** Merge one page into another.
7002 * The nodes from the page pointed to by \b csrc will
7003 * be copied to the page pointed to by \b cdst and then
7004 * the \b csrc page will be freed.
7005 * @param[in] csrc Cursor pointing to the source page.
7006 * @param[in] cdst Cursor pointing to the destination page.
7009 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
7017 DPRINTF(("merging page %"Z"u into %"Z"u", csrc->mc_pg[csrc->mc_top]->mp_pgno,
7018 cdst->mc_pg[cdst->mc_top]->mp_pgno));
7020 assert(csrc->mc_snum > 1); /* can't merge root page */
7021 assert(cdst->mc_snum > 1);
7023 /* Mark dst as dirty. */
7024 if ((rc = mdb_page_touch(cdst)))
7027 /* Move all nodes from src to dst.
7029 j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
7030 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7031 key.mv_size = csrc->mc_db->md_pad;
7032 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
7033 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
7034 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
7035 if (rc != MDB_SUCCESS)
7037 key.mv_data = (char *)key.mv_data + key.mv_size;
7040 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
7041 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
7042 if (i == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7043 unsigned int snum = csrc->mc_snum;
7045 /* must find the lowest key below src */
7046 mdb_page_search_lowest(csrc);
7047 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7048 key.mv_size = csrc->mc_db->md_pad;
7049 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7051 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7052 key.mv_size = NODEKSZ(s2);
7053 key.mv_data = NODEKEY(s2);
7055 csrc->mc_snum = snum--;
7056 csrc->mc_top = snum;
7058 key.mv_size = srcnode->mn_ksize;
7059 key.mv_data = NODEKEY(srcnode);
7062 data.mv_size = NODEDSZ(srcnode);
7063 data.mv_data = NODEDATA(srcnode);
7064 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
7065 if (rc != MDB_SUCCESS)
7070 DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
7071 cdst->mc_pg[cdst->mc_top]->mp_pgno, NUMKEYS(cdst->mc_pg[cdst->mc_top]),
7072 (float)PAGEFILL(cdst->mc_txn->mt_env, cdst->mc_pg[cdst->mc_top]) / 10));
7074 /* Unlink the src page from parent and add to free list.
7076 mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
7077 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
7080 rc = mdb_update_key(csrc, &key);
7086 rc = mdb_midl_append(&csrc->mc_txn->mt_free_pgs,
7087 csrc->mc_pg[csrc->mc_top]->mp_pgno);
7090 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
7091 csrc->mc_db->md_leaf_pages--;
7093 csrc->mc_db->md_branch_pages--;
7095 /* Adjust other cursors pointing to mp */
7096 MDB_cursor *m2, *m3;
7097 MDB_dbi dbi = csrc->mc_dbi;
7098 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
7100 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7101 if (csrc->mc_flags & C_SUB)
7102 m3 = &m2->mc_xcursor->mx_cursor;
7105 if (m3 == csrc) continue;
7106 if (m3->mc_snum < csrc->mc_snum) continue;
7107 if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
7108 m3->mc_pg[csrc->mc_top] = mp;
7109 m3->mc_ki[csrc->mc_top] += nkeys;
7113 mdb_cursor_pop(csrc);
7115 return mdb_rebalance(csrc);
7118 /** Copy the contents of a cursor.
7119 * @param[in] csrc The cursor to copy from.
7120 * @param[out] cdst The cursor to copy to.
7123 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
7127 cdst->mc_txn = csrc->mc_txn;
7128 cdst->mc_dbi = csrc->mc_dbi;
7129 cdst->mc_db = csrc->mc_db;
7130 cdst->mc_dbx = csrc->mc_dbx;
7131 cdst->mc_snum = csrc->mc_snum;
7132 cdst->mc_top = csrc->mc_top;
7133 cdst->mc_flags = csrc->mc_flags;
7135 for (i=0; i<csrc->mc_snum; i++) {
7136 cdst->mc_pg[i] = csrc->mc_pg[i];
7137 cdst->mc_ki[i] = csrc->mc_ki[i];
7141 /** Rebalance the tree after a delete operation.
7142 * @param[in] mc Cursor pointing to the page where rebalancing
7144 * @return 0 on success, non-zero on failure.
7147 mdb_rebalance(MDB_cursor *mc)
7151 unsigned int ptop, minkeys;
7154 minkeys = 1 + (IS_BRANCH(mc->mc_pg[mc->mc_top]));
7158 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
7159 DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
7160 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
7161 pgno, NUMKEYS(mc->mc_pg[mc->mc_top]),
7162 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
7166 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD &&
7167 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
7170 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
7171 DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
7177 if (mc->mc_snum < 2) {
7178 MDB_page *mp = mc->mc_pg[0];
7180 DPUTS("Can't rebalance a subpage, ignoring");
7183 if (NUMKEYS(mp) == 0) {
7184 DPUTS("tree is completely empty");
7185 mc->mc_db->md_root = P_INVALID;
7186 mc->mc_db->md_depth = 0;
7187 mc->mc_db->md_leaf_pages = 0;
7188 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7191 /* Adjust cursors pointing to mp */
7194 mc->mc_flags &= ~C_INITIALIZED;
7196 MDB_cursor *m2, *m3;
7197 MDB_dbi dbi = mc->mc_dbi;
7199 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7200 if (mc->mc_flags & C_SUB)
7201 m3 = &m2->mc_xcursor->mx_cursor;
7204 if (m3->mc_snum < mc->mc_snum) continue;
7205 if (m3->mc_pg[0] == mp) {
7208 m3->mc_flags &= ~C_INITIALIZED;
7212 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
7213 DPUTS("collapsing root page!");
7214 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7217 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
7218 rc = mdb_page_get(mc->mc_txn,mc->mc_db->md_root,&mc->mc_pg[0],NULL);
7221 mc->mc_db->md_depth--;
7222 mc->mc_db->md_branch_pages--;
7223 mc->mc_ki[0] = mc->mc_ki[1];
7225 /* Adjust other cursors pointing to mp */
7226 MDB_cursor *m2, *m3;
7227 MDB_dbi dbi = mc->mc_dbi;
7229 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7230 if (mc->mc_flags & C_SUB)
7231 m3 = &m2->mc_xcursor->mx_cursor;
7234 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
7235 if (m3->mc_pg[0] == mp) {
7239 for (i=0; i<m3->mc_snum; i++) {
7240 m3->mc_pg[i] = m3->mc_pg[i+1];
7241 m3->mc_ki[i] = m3->mc_ki[i+1];
7247 DPUTS("root page doesn't need rebalancing");
7251 /* The parent (branch page) must have at least 2 pointers,
7252 * otherwise the tree is invalid.
7254 ptop = mc->mc_top-1;
7255 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
7257 /* Leaf page fill factor is below the threshold.
7258 * Try to move keys from left or right neighbor, or
7259 * merge with a neighbor page.
7264 mdb_cursor_copy(mc, &mn);
7265 mn.mc_xcursor = NULL;
7267 if (mc->mc_ki[ptop] == 0) {
7268 /* We're the leftmost leaf in our parent.
7270 DPUTS("reading right neighbor");
7272 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7273 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7276 mn.mc_ki[mn.mc_top] = 0;
7277 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
7279 /* There is at least one neighbor to the left.
7281 DPUTS("reading left neighbor");
7283 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7284 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7287 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
7288 mc->mc_ki[mc->mc_top] = 0;
7291 DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
7292 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
7293 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
7295 /* If the neighbor page is above threshold and has enough keys,
7296 * move one key from it. Otherwise we should try to merge them.
7297 * (A branch page must never have less than 2 keys.)
7299 minkeys = 1 + (IS_BRANCH(mn.mc_pg[mn.mc_top]));
7300 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys)
7301 return mdb_node_move(&mn, mc);
7303 if (mc->mc_ki[ptop] == 0)
7304 rc = mdb_page_merge(&mn, mc);
7306 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
7307 rc = mdb_page_merge(mc, &mn);
7308 mdb_cursor_copy(&mn, mc);
7310 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
7315 /** Complete a delete operation started by #mdb_cursor_del(). */
7317 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
7324 mp = mc->mc_pg[mc->mc_top];
7325 ki = mc->mc_ki[mc->mc_top];
7327 /* add overflow pages to free list */
7328 if (!IS_LEAF2(mp) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7332 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
7333 if ((rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL)) ||
7334 (rc = mdb_ovpage_free(mc, omp)))
7337 mdb_node_del(mp, ki, mc->mc_db->md_pad);
7338 mc->mc_db->md_entries--;
7339 rc = mdb_rebalance(mc);
7340 if (rc != MDB_SUCCESS)
7341 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7344 MDB_dbi dbi = mc->mc_dbi;
7346 mp = mc->mc_pg[mc->mc_top];
7347 nkeys = NUMKEYS(mp);
7349 /* if mc points past last node in page, find next sibling */
7350 if (mc->mc_ki[mc->mc_top] >= nkeys)
7351 mdb_cursor_sibling(mc, 1);
7353 /* Adjust other cursors pointing to mp */
7354 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7355 if (m2 == mc || m2->mc_snum < mc->mc_snum)
7357 if (!(m2->mc_flags & C_INITIALIZED))
7359 if (m2->mc_pg[mc->mc_top] == mp) {
7360 if (m2->mc_ki[mc->mc_top] >= ki) {
7361 m2->mc_flags |= C_DEL;
7362 if (m2->mc_ki[mc->mc_top] > ki)
7363 m2->mc_ki[mc->mc_top]--;
7365 if (m2->mc_ki[mc->mc_top] >= nkeys)
7366 mdb_cursor_sibling(m2, 1);
7369 mc->mc_flags |= C_DEL;
7376 mdb_del(MDB_txn *txn, MDB_dbi dbi,
7377 MDB_val *key, MDB_val *data)
7382 MDB_val rdata, *xdata;
7386 assert(key != NULL);
7388 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
7390 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7393 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
7394 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7396 if (key->mv_size > MDB_MAXKEYSIZE) {
7397 return MDB_BAD_VALSIZE;
7400 mdb_cursor_init(&mc, txn, dbi, &mx);
7403 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
7404 /* must ignore any data */
7415 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
7417 /* let mdb_page_split know about this cursor if needed:
7418 * delete will trigger a rebalance; if it needs to move
7419 * a node from one page to another, it will have to
7420 * update the parent's separator key(s). If the new sepkey
7421 * is larger than the current one, the parent page may
7422 * run out of space, triggering a split. We need this
7423 * cursor to be consistent until the end of the rebalance.
7425 mc.mc_flags |= C_UNTRACK;
7426 mc.mc_next = txn->mt_cursors[dbi];
7427 txn->mt_cursors[dbi] = &mc;
7428 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
7429 txn->mt_cursors[dbi] = mc.mc_next;
7434 /** Split a page and insert a new node.
7435 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
7436 * The cursor will be updated to point to the actual page and index where
7437 * the node got inserted after the split.
7438 * @param[in] newkey The key for the newly inserted node.
7439 * @param[in] newdata The data for the newly inserted node.
7440 * @param[in] newpgno The page number, if the new node is a branch node.
7441 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
7442 * @return 0 on success, non-zero on failure.
7445 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
7446 unsigned int nflags)
7449 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
7452 int i, j, split_indx, nkeys, pmax;
7453 MDB_env *env = mc->mc_txn->mt_env;
7455 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
7456 MDB_page *copy = NULL;
7457 MDB_page *mp, *rp, *pp;
7462 mp = mc->mc_pg[mc->mc_top];
7463 newindx = mc->mc_ki[mc->mc_top];
7464 nkeys = NUMKEYS(mp);
7466 DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i/%i",
7467 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
7468 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
7470 /* Create a right sibling. */
7471 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
7473 DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
7475 if (mc->mc_snum < 2) {
7476 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
7478 /* shift current top to make room for new parent */
7479 mc->mc_pg[1] = mc->mc_pg[0];
7480 mc->mc_ki[1] = mc->mc_ki[0];
7483 mc->mc_db->md_root = pp->mp_pgno;
7484 DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
7485 mc->mc_db->md_depth++;
7488 /* Add left (implicit) pointer. */
7489 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
7490 /* undo the pre-push */
7491 mc->mc_pg[0] = mc->mc_pg[1];
7492 mc->mc_ki[0] = mc->mc_ki[1];
7493 mc->mc_db->md_root = mp->mp_pgno;
7494 mc->mc_db->md_depth--;
7501 ptop = mc->mc_top-1;
7502 DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
7505 mc->mc_flags |= C_SPLITTING;
7506 mdb_cursor_copy(mc, &mn);
7507 mn.mc_pg[mn.mc_top] = rp;
7508 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
7510 if (nflags & MDB_APPEND) {
7511 mn.mc_ki[mn.mc_top] = 0;
7513 split_indx = newindx;
7517 split_indx = (nkeys+1) / 2;
7522 unsigned int lsize, rsize, ksize;
7523 /* Move half of the keys to the right sibling */
7525 x = mc->mc_ki[mc->mc_top] - split_indx;
7526 ksize = mc->mc_db->md_pad;
7527 split = LEAF2KEY(mp, split_indx, ksize);
7528 rsize = (nkeys - split_indx) * ksize;
7529 lsize = (nkeys - split_indx) * sizeof(indx_t);
7530 mp->mp_lower -= lsize;
7531 rp->mp_lower += lsize;
7532 mp->mp_upper += rsize - lsize;
7533 rp->mp_upper -= rsize - lsize;
7534 sepkey.mv_size = ksize;
7535 if (newindx == split_indx) {
7536 sepkey.mv_data = newkey->mv_data;
7538 sepkey.mv_data = split;
7541 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
7542 memcpy(rp->mp_ptrs, split, rsize);
7543 sepkey.mv_data = rp->mp_ptrs;
7544 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
7545 memcpy(ins, newkey->mv_data, ksize);
7546 mp->mp_lower += sizeof(indx_t);
7547 mp->mp_upper -= ksize - sizeof(indx_t);
7550 memcpy(rp->mp_ptrs, split, x * ksize);
7551 ins = LEAF2KEY(rp, x, ksize);
7552 memcpy(ins, newkey->mv_data, ksize);
7553 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
7554 rp->mp_lower += sizeof(indx_t);
7555 rp->mp_upper -= ksize - sizeof(indx_t);
7556 mc->mc_ki[mc->mc_top] = x;
7557 mc->mc_pg[mc->mc_top] = rp;
7560 int psize, nsize, k;
7561 /* Maximum free space in an empty page */
7562 pmax = env->me_psize - PAGEHDRSZ;
7564 nsize = mdb_leaf_size(env, newkey, newdata);
7566 nsize = mdb_branch_size(env, newkey);
7567 nsize = EVEN(nsize);
7569 /* grab a page to hold a temporary copy */
7570 copy = mdb_page_malloc(mc->mc_txn, 1);
7573 copy->mp_pgno = mp->mp_pgno;
7574 copy->mp_flags = mp->mp_flags;
7575 copy->mp_lower = PAGEHDRSZ;
7576 copy->mp_upper = env->me_psize;
7578 /* prepare to insert */
7579 for (i=0, j=0; i<nkeys; i++) {
7581 copy->mp_ptrs[j++] = 0;
7583 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
7586 /* When items are relatively large the split point needs
7587 * to be checked, because being off-by-one will make the
7588 * difference between success or failure in mdb_node_add.
7590 * It's also relevant if a page happens to be laid out
7591 * such that one half of its nodes are all "small" and
7592 * the other half of its nodes are "large." If the new
7593 * item is also "large" and falls on the half with
7594 * "large" nodes, it also may not fit.
7596 * As a final tweak, if the new item goes on the last
7597 * spot on the page (and thus, onto the new page), bias
7598 * the split so the new page is emptier than the old page.
7599 * This yields better packing during sequential inserts.
7601 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
7602 /* Find split point */
7604 if (newindx <= split_indx || newindx >= nkeys) {
7606 k = newindx >= nkeys ? nkeys : split_indx+2;
7611 for (; i!=k; i+=j) {
7616 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i]);
7617 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
7619 if (F_ISSET(node->mn_flags, F_BIGDATA))
7620 psize += sizeof(pgno_t);
7622 psize += NODEDSZ(node);
7624 psize = EVEN(psize);
7626 if (psize > pmax || i == k-j) {
7627 split_indx = i + (j<0);
7632 if (split_indx == newindx) {
7633 sepkey.mv_size = newkey->mv_size;
7634 sepkey.mv_data = newkey->mv_data;
7636 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx]);
7637 sepkey.mv_size = node->mn_ksize;
7638 sepkey.mv_data = NODEKEY(node);
7643 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
7645 /* Copy separator key to the parent.
7647 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
7651 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
7654 if (mn.mc_snum == mc->mc_snum) {
7655 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
7656 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
7657 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
7658 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
7663 /* Right page might now have changed parent.
7664 * Check if left page also changed parent.
7666 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7667 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7668 for (i=0; i<ptop; i++) {
7669 mc->mc_pg[i] = mn.mc_pg[i];
7670 mc->mc_ki[i] = mn.mc_ki[i];
7672 mc->mc_pg[ptop] = mn.mc_pg[ptop];
7673 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
7677 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
7680 mc->mc_flags ^= C_SPLITTING;
7681 if (rc != MDB_SUCCESS) {
7684 if (nflags & MDB_APPEND) {
7685 mc->mc_pg[mc->mc_top] = rp;
7686 mc->mc_ki[mc->mc_top] = 0;
7687 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
7690 for (i=0; i<mc->mc_top; i++)
7691 mc->mc_ki[i] = mn.mc_ki[i];
7692 } else if (!IS_LEAF2(mp)) {
7694 mc->mc_pg[mc->mc_top] = rp;
7699 rkey.mv_data = newkey->mv_data;
7700 rkey.mv_size = newkey->mv_size;
7706 /* Update index for the new key. */
7707 mc->mc_ki[mc->mc_top] = j;
7709 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i]);
7710 rkey.mv_data = NODEKEY(node);
7711 rkey.mv_size = node->mn_ksize;
7713 xdata.mv_data = NODEDATA(node);
7714 xdata.mv_size = NODEDSZ(node);
7717 pgno = NODEPGNO(node);
7718 flags = node->mn_flags;
7721 if (!IS_LEAF(mp) && j == 0) {
7722 /* First branch index doesn't need key data. */
7726 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
7728 /* return tmp page to freelist */
7729 mdb_page_free(env, copy);
7735 mc->mc_pg[mc->mc_top] = copy;
7740 } while (i != split_indx);
7742 nkeys = NUMKEYS(copy);
7743 for (i=0; i<nkeys; i++)
7744 mp->mp_ptrs[i] = copy->mp_ptrs[i];
7745 mp->mp_lower = copy->mp_lower;
7746 mp->mp_upper = copy->mp_upper;
7747 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
7748 env->me_psize - copy->mp_upper);
7750 /* reset back to original page */
7751 if (newindx < split_indx) {
7752 mc->mc_pg[mc->mc_top] = mp;
7753 if (nflags & MDB_RESERVE) {
7754 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7755 if (!(node->mn_flags & F_BIGDATA))
7756 newdata->mv_data = NODEDATA(node);
7759 mc->mc_pg[mc->mc_top] = rp;
7761 /* Make sure mc_ki is still valid.
7763 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7764 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7765 for (i=0; i<ptop; i++) {
7766 mc->mc_pg[i] = mn.mc_pg[i];
7767 mc->mc_ki[i] = mn.mc_ki[i];
7769 mc->mc_pg[ptop] = mn.mc_pg[ptop];
7770 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
7773 /* return tmp page to freelist */
7774 mdb_page_free(env, copy);
7778 /* Adjust other cursors pointing to mp */
7779 MDB_cursor *m2, *m3;
7780 MDB_dbi dbi = mc->mc_dbi;
7781 int fixup = NUMKEYS(mp);
7783 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7784 if (mc->mc_flags & C_SUB)
7785 m3 = &m2->mc_xcursor->mx_cursor;
7790 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
7792 if (m3->mc_flags & C_SPLITTING)
7797 for (k=m3->mc_top; k>=0; k--) {
7798 m3->mc_ki[k+1] = m3->mc_ki[k];
7799 m3->mc_pg[k+1] = m3->mc_pg[k];
7801 if (m3->mc_ki[0] >= split_indx) {
7806 m3->mc_pg[0] = mc->mc_pg[0];
7810 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
7811 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
7812 m3->mc_ki[mc->mc_top]++;
7813 if (m3->mc_ki[mc->mc_top] >= fixup) {
7814 m3->mc_pg[mc->mc_top] = rp;
7815 m3->mc_ki[mc->mc_top] -= fixup;
7816 m3->mc_ki[ptop] = mn.mc_ki[ptop];
7818 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
7819 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
7824 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
7829 mdb_put(MDB_txn *txn, MDB_dbi dbi,
7830 MDB_val *key, MDB_val *data, unsigned int flags)
7835 assert(key != NULL);
7836 assert(data != NULL);
7838 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7841 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP)) != flags)
7844 mdb_cursor_init(&mc, txn, dbi, &mx);
7845 return mdb_cursor_put(&mc, key, data, flags);
7849 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
7851 if ((flag & CHANGEABLE) != flag)
7854 env->me_flags |= flag;
7856 env->me_flags &= ~flag;
7861 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
7866 *arg = env->me_flags;
7871 mdb_env_get_path(MDB_env *env, const char **arg)
7876 *arg = env->me_path;
7881 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
7890 /** Common code for #mdb_stat() and #mdb_env_stat().
7891 * @param[in] env the environment to operate in.
7892 * @param[in] db the #MDB_db record containing the stats to return.
7893 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
7894 * @return 0, this function always succeeds.
7897 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
7899 arg->ms_psize = env->me_psize;
7900 arg->ms_depth = db->md_depth;
7901 arg->ms_branch_pages = db->md_branch_pages;
7902 arg->ms_leaf_pages = db->md_leaf_pages;
7903 arg->ms_overflow_pages = db->md_overflow_pages;
7904 arg->ms_entries = db->md_entries;
7909 mdb_env_stat(MDB_env *env, MDB_stat *arg)
7913 if (env == NULL || arg == NULL)
7916 toggle = mdb_env_pick_meta(env);
7918 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
7922 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
7926 if (env == NULL || arg == NULL)
7929 toggle = mdb_env_pick_meta(env);
7930 arg->me_mapaddr = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : 0;
7931 arg->me_mapsize = env->me_mapsize;
7932 arg->me_maxreaders = env->me_maxreaders;
7934 /* me_numreaders may be zero if this process never used any readers. Use
7935 * the shared numreader count if it exists.
7937 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : env->me_numreaders;
7939 arg->me_last_pgno = env->me_metas[toggle]->mm_last_pg;
7940 arg->me_last_txnid = env->me_metas[toggle]->mm_txnid;
7944 /** Set the default comparison functions for a database.
7945 * Called immediately after a database is opened to set the defaults.
7946 * The user can then override them with #mdb_set_compare() or
7947 * #mdb_set_dupsort().
7948 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
7949 * @param[in] dbi A database handle returned by #mdb_dbi_open()
7952 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
7954 uint16_t f = txn->mt_dbs[dbi].md_flags;
7956 txn->mt_dbxs[dbi].md_cmp =
7957 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
7958 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
7960 txn->mt_dbxs[dbi].md_dcmp =
7961 !(f & MDB_DUPSORT) ? 0 :
7962 ((f & MDB_INTEGERDUP)
7963 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
7964 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
7967 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
7972 int rc, dbflag, exact;
7973 unsigned int unused = 0;
7976 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
7977 mdb_default_cmp(txn, FREE_DBI);
7980 if ((flags & VALID_FLAGS) != flags)
7982 if (txn->mt_flags & MDB_TXN_ERROR)
7988 if (flags & PERSISTENT_FLAGS) {
7989 uint16_t f2 = flags & PERSISTENT_FLAGS;
7990 /* make sure flag changes get committed */
7991 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
7992 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
7993 txn->mt_flags |= MDB_TXN_DIRTY;
7996 mdb_default_cmp(txn, MAIN_DBI);
8000 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
8001 mdb_default_cmp(txn, MAIN_DBI);
8004 /* Is the DB already open? */
8006 for (i=2; i<txn->mt_numdbs; i++) {
8007 if (!txn->mt_dbxs[i].md_name.mv_size) {
8008 /* Remember this free slot */
8009 if (!unused) unused = i;
8012 if (len == txn->mt_dbxs[i].md_name.mv_size &&
8013 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
8019 /* If no free slot and max hit, fail */
8020 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
8021 return MDB_DBS_FULL;
8023 /* Cannot mix named databases with some mainDB flags */
8024 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
8025 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
8027 /* Find the DB info */
8028 dbflag = DB_NEW|DB_VALID;
8031 key.mv_data = (void *)name;
8032 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
8033 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
8034 if (rc == MDB_SUCCESS) {
8035 /* make sure this is actually a DB */
8036 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
8037 if (!(node->mn_flags & F_SUBDATA))
8038 return MDB_INCOMPATIBLE;
8039 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
8040 /* Create if requested */
8042 data.mv_size = sizeof(MDB_db);
8043 data.mv_data = &dummy;
8044 memset(&dummy, 0, sizeof(dummy));
8045 dummy.md_root = P_INVALID;
8046 dummy.md_flags = flags & PERSISTENT_FLAGS;
8047 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
8051 /* OK, got info, add to table */
8052 if (rc == MDB_SUCCESS) {
8053 unsigned int slot = unused ? unused : txn->mt_numdbs;
8054 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
8055 txn->mt_dbxs[slot].md_name.mv_size = len;
8056 txn->mt_dbxs[slot].md_rel = NULL;
8057 txn->mt_dbflags[slot] = dbflag;
8058 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
8060 mdb_default_cmp(txn, slot);
8069 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
8071 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
8074 if (txn->mt_dbflags[dbi] & DB_STALE) {
8077 /* Stale, must read the DB's root. cursor_init does it for us. */
8078 mdb_cursor_init(&mc, txn, dbi, &mx);
8080 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
8083 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
8086 if (dbi <= MAIN_DBI || dbi >= env->me_maxdbs)
8088 ptr = env->me_dbxs[dbi].md_name.mv_data;
8089 env->me_dbxs[dbi].md_name.mv_data = NULL;
8090 env->me_dbxs[dbi].md_name.mv_size = 0;
8091 env->me_dbflags[dbi] = 0;
8095 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
8097 /* We could return the flags for the FREE_DBI too but what's the point? */
8098 if (txn == NULL || dbi < MAIN_DBI || dbi >= txn->mt_numdbs)
8100 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
8104 /** Add all the DB's pages to the free list.
8105 * @param[in] mc Cursor on the DB to free.
8106 * @param[in] subs non-Zero to check for sub-DBs in this DB.
8107 * @return 0 on success, non-zero on failure.
8110 mdb_drop0(MDB_cursor *mc, int subs)
8114 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
8115 if (rc == MDB_SUCCESS) {
8116 MDB_txn *txn = mc->mc_txn;
8121 /* LEAF2 pages have no nodes, cannot have sub-DBs */
8122 if (IS_LEAF2(mc->mc_pg[mc->mc_top]))
8125 mdb_cursor_copy(mc, &mx);
8126 while (mc->mc_snum > 0) {
8127 MDB_page *mp = mc->mc_pg[mc->mc_top];
8128 unsigned n = NUMKEYS(mp);
8130 for (i=0; i<n; i++) {
8131 ni = NODEPTR(mp, i);
8132 if (ni->mn_flags & F_BIGDATA) {
8135 memcpy(&pg, NODEDATA(ni), sizeof(pg));
8136 rc = mdb_page_get(txn, pg, &omp, NULL);
8139 assert(IS_OVERFLOW(omp));
8140 rc = mdb_midl_append_range(&txn->mt_free_pgs,
8144 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
8145 mdb_xcursor_init1(mc, ni);
8146 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
8152 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
8154 for (i=0; i<n; i++) {
8156 ni = NODEPTR(mp, i);
8159 mdb_midl_xappend(txn->mt_free_pgs, pg);
8164 mc->mc_ki[mc->mc_top] = i;
8165 rc = mdb_cursor_sibling(mc, 1);
8167 /* no more siblings, go back to beginning
8168 * of previous level.
8172 for (i=1; i<mc->mc_snum; i++) {
8174 mc->mc_pg[i] = mx.mc_pg[i];
8179 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
8180 } else if (rc == MDB_NOTFOUND) {
8186 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
8188 MDB_cursor *mc, *m2;
8191 if (!txn || !dbi || dbi >= txn->mt_numdbs || (unsigned)del > 1 || !(txn->mt_dbflags[dbi] & DB_VALID))
8194 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
8197 rc = mdb_cursor_open(txn, dbi, &mc);
8201 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
8202 /* Invalidate the dropped DB's cursors */
8203 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
8204 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
8208 /* Can't delete the main DB */
8209 if (del && dbi > MAIN_DBI) {
8210 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
8212 txn->mt_dbflags[dbi] = DB_STALE;
8213 mdb_dbi_close(txn->mt_env, dbi);
8216 /* reset the DB record, mark it dirty */
8217 txn->mt_dbflags[dbi] |= DB_DIRTY;
8218 txn->mt_dbs[dbi].md_depth = 0;
8219 txn->mt_dbs[dbi].md_branch_pages = 0;
8220 txn->mt_dbs[dbi].md_leaf_pages = 0;
8221 txn->mt_dbs[dbi].md_overflow_pages = 0;
8222 txn->mt_dbs[dbi].md_entries = 0;
8223 txn->mt_dbs[dbi].md_root = P_INVALID;
8225 txn->mt_flags |= MDB_TXN_DIRTY;
8228 mdb_cursor_close(mc);
8232 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
8234 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8237 txn->mt_dbxs[dbi].md_cmp = cmp;
8241 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
8243 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8246 txn->mt_dbxs[dbi].md_dcmp = cmp;
8250 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
8252 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8255 txn->mt_dbxs[dbi].md_rel = rel;
8259 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
8261 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8264 txn->mt_dbxs[dbi].md_relctx = ctx;
8268 int mdb_env_get_maxkeysize(MDB_env *env)
8270 return MDB_MAXKEYSIZE;
8273 int mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
8275 unsigned int i, rdrs;
8282 if (!env->me_txns) {
8283 return func("(no reader locks)\n", ctx);
8285 rdrs = env->me_txns->mti_numreaders;
8286 mr = env->me_txns->mti_readers;
8287 for (i=0; i<rdrs; i++) {
8292 if (mr[i].mr_txnid == (txnid_t)-1) {
8293 sprintf(buf, "%10d %"Z"x -\n", mr[i].mr_pid, tid);
8295 sprintf(buf, "%10d %"Z"x %"Z"u\n", mr[i].mr_pid, tid, mr[i].mr_txnid);
8299 func(" pid thread txnid\n", ctx);
8301 rc = func(buf, ctx);
8307 func("(no active readers)\n", ctx);
8312 /** Insert pid into list if not already present.
8313 * return -1 if already present.
8315 static int mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
8317 /* binary search of pid in list */
8319 unsigned cursor = 1;
8321 unsigned n = ids[0];
8324 unsigned pivot = n >> 1;
8325 cursor = base + pivot + 1;
8326 val = pid - ids[cursor];
8331 } else if ( val > 0 ) {
8336 /* found, so it's a duplicate */
8345 for (n = ids[0]; n > cursor; n--)
8351 int mdb_reader_check(MDB_env *env, int *dead)
8353 unsigned int i, j, rdrs;
8355 MDB_PID_T *pids, pid;
8364 rdrs = env->me_txns->mti_numreaders;
8365 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
8369 mr = env->me_txns->mti_readers;
8370 for (i=0; i<rdrs; i++) {
8371 if (mr[i].mr_pid && mr[i].mr_pid != env->me_pid) {
8373 if (mdb_pid_insert(pids, pid) == 0) {
8374 if (!mdb_reader_pid(env, Pidcheck, pid)) {
8376 /* Recheck, a new process may have reused pid */
8377 if (!mdb_reader_pid(env, Pidcheck, pid)) {
8378 for (j=i; j<rdrs; j++)
8379 if (mr[j].mr_pid == pid) {
8380 DPRINTF(("clear stale reader pid %u txn %"Z"d",
8381 (unsigned) pid, mr[j].mr_txnid));
8386 UNLOCK_MUTEX_R(env);