2 * @brief memory-mapped database library
4 * A Btree-based database management library modeled loosely on the
5 * BerkeleyDB API, but much simplified.
8 * Copyright 2011-2013 Howard Chu, Symas Corp.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted only as authorized by the OpenLDAP
15 * A copy of this license is available in the file LICENSE in the
16 * top-level directory of the distribution or, alternatively, at
17 * <http://www.OpenLDAP.org/license.html>.
19 * This code is derived from btree.c written by Martin Hedenfalk.
21 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
23 * Permission to use, copy, modify, and distribute this software for any
24 * purpose with or without fee is hereby granted, provided that the above
25 * copyright notice and this permission notice appear in all copies.
27 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
28 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
29 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
30 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
31 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
32 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
33 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
38 #include <sys/types.h>
40 #include <sys/param.h>
46 #ifdef HAVE_SYS_FILE_H
63 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
64 #include <netinet/in.h>
65 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
68 #if defined(__APPLE__) || defined (BSD)
69 # define MDB_USE_POSIX_SEM 1
70 # define MDB_FDATASYNC fsync
71 #elif defined(ANDROID)
72 # define MDB_FDATASYNC fsync
77 #ifdef MDB_USE_POSIX_SEM
78 #include <semaphore.h>
83 #include <valgrind/memcheck.h>
84 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
85 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
86 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
87 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
88 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
90 #define VGMEMP_CREATE(h,r,z)
91 #define VGMEMP_ALLOC(h,a,s)
92 #define VGMEMP_FREE(h,a)
93 #define VGMEMP_DESTROY(h)
94 #define VGMEMP_DEFINED(a,s)
98 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
99 /* Solaris just defines one or the other */
100 # define LITTLE_ENDIAN 1234
101 # define BIG_ENDIAN 4321
102 # ifdef _LITTLE_ENDIAN
103 # define BYTE_ORDER LITTLE_ENDIAN
105 # define BYTE_ORDER BIG_ENDIAN
108 # define BYTE_ORDER __BYTE_ORDER
112 #ifndef LITTLE_ENDIAN
113 #define LITTLE_ENDIAN __LITTLE_ENDIAN
116 #define BIG_ENDIAN __BIG_ENDIAN
119 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
120 #define MISALIGNED_OK 1
126 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
127 # error "Unknown or unsupported endianness (BYTE_ORDER)"
128 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
129 # error "Two's complement, reasonably sized integer types, please"
132 /** @defgroup internal MDB Internals
135 /** @defgroup compat Windows Compatibility Macros
136 * A bunch of macros to minimize the amount of platform-specific ifdefs
137 * needed throughout the rest of the code. When the features this library
138 * needs are similar enough to POSIX to be hidden in a one-or-two line
139 * replacement, this macro approach is used.
143 #define MDB_PIDLOCK 0
144 #define pthread_t DWORD
145 #define pthread_mutex_t HANDLE
146 #define pthread_key_t DWORD
147 #define pthread_self() GetCurrentThreadId()
148 #define pthread_key_create(x,y) \
149 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
150 #define pthread_key_delete(x) TlsFree(x)
151 #define pthread_getspecific(x) TlsGetValue(x)
152 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
153 #define pthread_mutex_unlock(x) ReleaseMutex(x)
154 #define pthread_mutex_lock(x) WaitForSingleObject(x, INFINITE)
155 #define LOCK_MUTEX_R(env) pthread_mutex_lock((env)->me_rmutex)
156 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock((env)->me_rmutex)
157 #define LOCK_MUTEX_W(env) pthread_mutex_lock((env)->me_wmutex)
158 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock((env)->me_wmutex)
159 #define getpid() GetCurrentProcessId()
160 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
161 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
162 #define ErrCode() GetLastError()
163 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
164 #define close(fd) (CloseHandle(fd) ? 0 : -1)
165 #define munmap(ptr,len) UnmapViewOfFile(ptr)
166 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
167 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
169 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
176 /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
177 #define MDB_PIDLOCK 1
179 #ifdef MDB_USE_POSIX_SEM
181 #define LOCK_MUTEX_R(env) mdb_sem_wait((env)->me_rmutex)
182 #define UNLOCK_MUTEX_R(env) sem_post((env)->me_rmutex)
183 #define LOCK_MUTEX_W(env) mdb_sem_wait((env)->me_wmutex)
184 #define UNLOCK_MUTEX_W(env) sem_post((env)->me_wmutex)
187 mdb_sem_wait(sem_t *sem)
190 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
195 /** Lock the reader mutex.
197 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
198 /** Unlock the reader mutex.
200 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
202 /** Lock the writer mutex.
203 * Only a single write transaction is allowed at a time. Other writers
204 * will block waiting for this mutex.
206 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
207 /** Unlock the writer mutex.
209 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
210 #endif /* MDB_USE_POSIX_SEM */
212 /** Get the error code for the last failed system function.
214 #define ErrCode() errno
216 /** An abstraction for a file handle.
217 * On POSIX systems file handles are small integers. On Windows
218 * they're opaque pointers.
222 /** A value for an invalid file handle.
223 * Mainly used to initialize file variables and signify that they are
226 #define INVALID_HANDLE_VALUE (-1)
228 /** Get the size of a memory page for the system.
229 * This is the basic size that the platform's memory manager uses, and is
230 * fundamental to the use of memory-mapped files.
232 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
235 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
238 #define MNAME_LEN (sizeof(pthread_mutex_t))
244 /** A flag for opening a file and requesting synchronous data writes.
245 * This is only used when writing a meta page. It's not strictly needed;
246 * we could just do a normal write and then immediately perform a flush.
247 * But if this flag is available it saves us an extra system call.
249 * @note If O_DSYNC is undefined but exists in /usr/include,
250 * preferably set some compiler flag to get the definition.
251 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
254 # define MDB_DSYNC O_DSYNC
258 /** Function for flushing the data of a file. Define this to fsync
259 * if fdatasync() is not supported.
261 #ifndef MDB_FDATASYNC
262 # define MDB_FDATASYNC fdatasync
266 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
277 /** A page number in the database.
278 * Note that 64 bit page numbers are overkill, since pages themselves
279 * already represent 12-13 bits of addressable memory, and the OS will
280 * always limit applications to a maximum of 63 bits of address space.
282 * @note In the #MDB_node structure, we only store 48 bits of this value,
283 * which thus limits us to only 60 bits of addressable data.
285 typedef MDB_ID pgno_t;
287 /** A transaction ID.
288 * See struct MDB_txn.mt_txnid for details.
290 typedef MDB_ID txnid_t;
292 /** @defgroup debug Debug Macros
296 /** Enable debug output. Needs variable argument macros (a C99 feature).
297 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
298 * read from and written to the database (used for free space management).
304 static int mdb_debug;
305 static txnid_t mdb_debug_start;
307 /** Print a debug message with printf formatting.
308 * Requires double parenthesis around 2 or more args.
310 # define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
311 # define DPRINTF0(fmt, ...) \
312 fprintf(stderr, "%s:%d " fmt "\n", __func__, __LINE__, __VA_ARGS__)
314 # define DPRINTF(args) ((void) 0)
316 /** Print a debug string.
317 * The string is printed literally, with no format processing.
319 #define DPUTS(arg) DPRINTF(("%s", arg))
322 /** A default memory page size.
323 * The actual size is platform-dependent, but we use this for
324 * boot-strapping. We probably should not be using this any more.
325 * The #GET_PAGESIZE() macro is used to get the actual size.
327 * Note that we don't currently support Huge pages. On Linux,
328 * regular data files cannot use Huge pages, and in general
329 * Huge pages aren't actually pageable. We rely on the OS
330 * demand-pager to read our data and page it out when memory
331 * pressure from other processes is high. So until OSs have
332 * actual paging support for Huge pages, they're not viable.
334 #define MDB_PAGESIZE 4096
336 /** The minimum number of keys required in a database page.
337 * Setting this to a larger value will place a smaller bound on the
338 * maximum size of a data item. Data items larger than this size will
339 * be pushed into overflow pages instead of being stored directly in
340 * the B-tree node. This value used to default to 4. With a page size
341 * of 4096 bytes that meant that any item larger than 1024 bytes would
342 * go into an overflow page. That also meant that on average 2-3KB of
343 * each overflow page was wasted space. The value cannot be lower than
344 * 2 because then there would no longer be a tree structure. With this
345 * value, items larger than 2KB will go into overflow pages, and on
346 * average only 1KB will be wasted.
348 #define MDB_MINKEYS 2
350 /** A stamp that identifies a file as an MDB file.
351 * There's nothing special about this value other than that it is easily
352 * recognizable, and it will reflect any byte order mismatches.
354 #define MDB_MAGIC 0xBEEFC0DE
356 /** The version number for a database's datafile format. */
357 #define MDB_DATA_VERSION 1
358 /** The version number for a database's lockfile format. */
359 #define MDB_LOCK_VERSION 1
361 /** @brief The maximum size of a key in the database.
363 * The library rejects bigger keys, and cannot deal with records
364 * with bigger keys stored by a library with bigger max keysize.
366 * We require that keys all fit onto a regular page. This limit
367 * could be raised a bit further if needed; to something just
368 * under #MDB_PAGESIZE / #MDB_MINKEYS.
370 * Note that data items in an #MDB_DUPSORT database are actually keys
371 * of a subDB, so they're also limited to this size.
373 #ifndef MDB_MAXKEYSIZE
374 #define MDB_MAXKEYSIZE 511
377 /** @brief The maximum size of a data item.
379 * We only store a 32 bit value for node sizes.
381 #define MAXDATASIZE 0xffffffffUL
386 * This is used for printing a hex dump of a key's contents.
388 #define DKBUF char kbuf[(MDB_MAXKEYSIZE*2+1)]
389 /** Display a key in hex.
391 * Invoke a function to display a key in hex.
393 #define DKEY(x) mdb_dkey(x, kbuf)
399 /** An invalid page number.
400 * Mainly used to denote an empty tree.
402 #define P_INVALID (~(pgno_t)0)
404 /** Test if the flags \b f are set in a flag word \b w. */
405 #define F_ISSET(w, f) (((w) & (f)) == (f))
407 /** Used for offsets within a single page.
408 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
411 typedef uint16_t indx_t;
413 /** Default size of memory map.
414 * This is certainly too small for any actual applications. Apps should always set
415 * the size explicitly using #mdb_env_set_mapsize().
417 #define DEFAULT_MAPSIZE 1048576
419 /** @defgroup readers Reader Lock Table
420 * Readers don't acquire any locks for their data access. Instead, they
421 * simply record their transaction ID in the reader table. The reader
422 * mutex is needed just to find an empty slot in the reader table. The
423 * slot's address is saved in thread-specific data so that subsequent read
424 * transactions started by the same thread need no further locking to proceed.
426 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
428 * No reader table is used if the database is on a read-only filesystem.
430 * Since the database uses multi-version concurrency control, readers don't
431 * actually need any locking. This table is used to keep track of which
432 * readers are using data from which old transactions, so that we'll know
433 * when a particular old transaction is no longer in use. Old transactions
434 * that have discarded any data pages can then have those pages reclaimed
435 * for use by a later write transaction.
437 * The lock table is constructed such that reader slots are aligned with the
438 * processor's cache line size. Any slot is only ever used by one thread.
439 * This alignment guarantees that there will be no contention or cache
440 * thrashing as threads update their own slot info, and also eliminates
441 * any need for locking when accessing a slot.
443 * A writer thread will scan every slot in the table to determine the oldest
444 * outstanding reader transaction. Any freed pages older than this will be
445 * reclaimed by the writer. The writer doesn't use any locks when scanning
446 * this table. This means that there's no guarantee that the writer will
447 * see the most up-to-date reader info, but that's not required for correct
448 * operation - all we need is to know the upper bound on the oldest reader,
449 * we don't care at all about the newest reader. So the only consequence of
450 * reading stale information here is that old pages might hang around a
451 * while longer before being reclaimed. That's actually good anyway, because
452 * the longer we delay reclaiming old pages, the more likely it is that a
453 * string of contiguous pages can be found after coalescing old pages from
454 * many old transactions together.
457 /** Number of slots in the reader table.
458 * This value was chosen somewhat arbitrarily. 126 readers plus a
459 * couple mutexes fit exactly into 8KB on my development machine.
460 * Applications should set the table size using #mdb_env_set_maxreaders().
462 #define DEFAULT_READERS 126
464 /** The size of a CPU cache line in bytes. We want our lock structures
465 * aligned to this size to avoid false cache line sharing in the
467 * This value works for most CPUs. For Itanium this should be 128.
473 /** The information we store in a single slot of the reader table.
474 * In addition to a transaction ID, we also record the process and
475 * thread ID that owns a slot, so that we can detect stale information,
476 * e.g. threads or processes that went away without cleaning up.
477 * @note We currently don't check for stale records. We simply re-init
478 * the table when we know that we're the only process opening the
481 typedef struct MDB_rxbody {
482 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
483 * Multiple readers that start at the same time will probably have the
484 * same ID here. Again, it's not important to exclude them from
485 * anything; all we need to know is which version of the DB they
486 * started from so we can avoid overwriting any data used in that
487 * particular version.
490 /** The process ID of the process owning this reader txn. */
492 /** The thread ID of the thread owning this txn. */
496 /** The actual reader record, with cacheline padding. */
497 typedef struct MDB_reader {
500 /** shorthand for mrb_txnid */
501 #define mr_txnid mru.mrx.mrb_txnid
502 #define mr_pid mru.mrx.mrb_pid
503 #define mr_tid mru.mrx.mrb_tid
504 /** cache line alignment */
505 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
509 /** The header for the reader table.
510 * The table resides in a memory-mapped file. (This is a different file
511 * than is used for the main database.)
513 * For POSIX the actual mutexes reside in the shared memory of this
514 * mapped file. On Windows, mutexes are named objects allocated by the
515 * kernel; we store the mutex names in this mapped file so that other
516 * processes can grab them. This same approach is also used on
517 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
518 * process-shared POSIX mutexes. For these cases where a named object
519 * is used, the object name is derived from a 64 bit FNV hash of the
520 * environment pathname. As such, naming collisions are extremely
521 * unlikely. If a collision occurs, the results are unpredictable.
523 typedef struct MDB_txbody {
524 /** Stamp identifying this as an MDB file. It must be set
527 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
529 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
530 char mtb_rmname[MNAME_LEN];
532 /** Mutex protecting access to this table.
533 * This is the reader lock that #LOCK_MUTEX_R acquires.
535 pthread_mutex_t mtb_mutex;
537 /** The ID of the last transaction committed to the database.
538 * This is recorded here only for convenience; the value can always
539 * be determined by reading the main database meta pages.
542 /** The number of slots that have been used in the reader table.
543 * This always records the maximum count, it is not decremented
544 * when readers release their slots.
546 unsigned mtb_numreaders;
549 /** The actual reader table definition. */
550 typedef struct MDB_txninfo {
553 #define mti_magic mt1.mtb.mtb_magic
554 #define mti_format mt1.mtb.mtb_format
555 #define mti_mutex mt1.mtb.mtb_mutex
556 #define mti_rmname mt1.mtb.mtb_rmname
557 #define mti_txnid mt1.mtb.mtb_txnid
558 #define mti_numreaders mt1.mtb.mtb_numreaders
559 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
562 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
563 char mt2_wmname[MNAME_LEN];
564 #define mti_wmname mt2.mt2_wmname
566 pthread_mutex_t mt2_wmutex;
567 #define mti_wmutex mt2.mt2_wmutex
569 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
571 MDB_reader mti_readers[1];
574 /** Lockfile format signature: version, features and field layout */
575 #define MDB_LOCK_FORMAT \
577 ((MDB_LOCK_VERSION) \
578 /* Flags which describe functionality */ \
579 + (((MDB_PIDLOCK) != 0) << 16)))
582 /** Common header for all page types.
583 * Overflow records occupy a number of contiguous pages with no
584 * headers on any page after the first.
586 typedef struct MDB_page {
587 #define mp_pgno mp_p.p_pgno
588 #define mp_next mp_p.p_next
590 pgno_t p_pgno; /**< page number */
591 void * p_next; /**< for in-memory list of freed structs */
594 /** @defgroup mdb_page Page Flags
596 * Flags for the page headers.
599 #define P_BRANCH 0x01 /**< branch page */
600 #define P_LEAF 0x02 /**< leaf page */
601 #define P_OVERFLOW 0x04 /**< overflow page */
602 #define P_META 0x08 /**< meta page */
603 #define P_DIRTY 0x10 /**< dirty page */
604 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
605 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
606 #define P_KEEP 0x8000 /**< leave this page alone during spill */
608 uint16_t mp_flags; /**< @ref mdb_page */
609 #define mp_lower mp_pb.pb.pb_lower
610 #define mp_upper mp_pb.pb.pb_upper
611 #define mp_pages mp_pb.pb_pages
614 indx_t pb_lower; /**< lower bound of free space */
615 indx_t pb_upper; /**< upper bound of free space */
617 uint32_t pb_pages; /**< number of overflow pages */
619 indx_t mp_ptrs[1]; /**< dynamic size */
622 /** Size of the page header, excluding dynamic data at the end */
623 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
625 /** Address of first usable data byte in a page, after the header */
626 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
628 /** Number of nodes on a page */
629 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
631 /** The amount of space remaining in the page */
632 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
634 /** The percentage of space used in the page, in tenths of a percent. */
635 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
636 ((env)->me_psize - PAGEHDRSZ))
637 /** The minimum page fill factor, in tenths of a percent.
638 * Pages emptier than this are candidates for merging.
640 #define FILL_THRESHOLD 250
642 /** Test if a page is a leaf page */
643 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
644 /** Test if a page is a LEAF2 page */
645 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
646 /** Test if a page is a branch page */
647 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
648 /** Test if a page is an overflow page */
649 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
650 /** Test if a page is a sub page */
651 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
653 /** The number of overflow pages needed to store the given size. */
654 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
656 /** Header for a single key/data pair within a page.
657 * We guarantee 2-byte alignment for nodes.
659 typedef struct MDB_node {
660 /** lo and hi are used for data size on leaf nodes and for
661 * child pgno on branch nodes. On 64 bit platforms, flags
662 * is also used for pgno. (Branch nodes have no flags).
663 * They are in host byte order in case that lets some
664 * accesses be optimized into a 32-bit word access.
666 #define mn_lo mn_offset[BYTE_ORDER!=LITTLE_ENDIAN]
667 #define mn_hi mn_offset[BYTE_ORDER==LITTLE_ENDIAN] /**< part of dsize or pgno */
668 unsigned short mn_offset[2]; /**< storage for #mn_lo and #mn_hi */
669 /** @defgroup mdb_node Node Flags
671 * Flags for node headers.
674 #define F_BIGDATA 0x01 /**< data put on overflow page */
675 #define F_SUBDATA 0x02 /**< data is a sub-database */
676 #define F_DUPDATA 0x04 /**< data has duplicates */
678 /** valid flags for #mdb_node_add() */
679 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
682 unsigned short mn_flags; /**< @ref mdb_node */
683 unsigned short mn_ksize; /**< key size */
684 char mn_data[1]; /**< key and data are appended here */
687 /** Size of the node header, excluding dynamic data at the end */
688 #define NODESIZE offsetof(MDB_node, mn_data)
690 /** Bit position of top word in page number, for shifting mn_flags */
691 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
693 /** Size of a node in a branch page with a given key.
694 * This is just the node header plus the key, there is no data.
696 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
698 /** Size of a node in a leaf page with a given key and data.
699 * This is node header plus key plus data size.
701 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
703 /** Address of node \b i in page \b p */
704 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
706 /** Address of the key for the node */
707 #define NODEKEY(node) (void *)((node)->mn_data)
709 /** Address of the data for a node */
710 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
712 /** Get the page number pointed to by a branch node */
713 #define NODEPGNO(node) \
714 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
715 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
716 /** Set the page number in a branch node */
717 #define SETPGNO(node,pgno) do { \
718 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
719 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
721 /** Get the size of the data in a leaf node */
722 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
723 /** Set the size of the data for a leaf node */
724 #define SETDSZ(node,size) do { \
725 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
726 /** The size of a key in a node */
727 #define NODEKSZ(node) ((node)->mn_ksize)
729 /** Copy a page number from src to dst */
731 #define COPY_PGNO(dst,src) dst = src
733 #if SIZE_MAX > 4294967295UL
734 #define COPY_PGNO(dst,src) do { \
735 unsigned short *s, *d; \
736 s = (unsigned short *)&(src); \
737 d = (unsigned short *)&(dst); \
744 #define COPY_PGNO(dst,src) do { \
745 unsigned short *s, *d; \
746 s = (unsigned short *)&(src); \
747 d = (unsigned short *)&(dst); \
753 /** The address of a key in a LEAF2 page.
754 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
755 * There are no node headers, keys are stored contiguously.
757 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
759 /** Set the \b node's key into \b keyptr, if requested. */
760 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
761 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
763 /** Set the \b node's key into \b key. */
764 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
766 /** Information about a single database in the environment. */
767 typedef struct MDB_db {
768 uint32_t md_pad; /**< also ksize for LEAF2 pages */
769 uint16_t md_flags; /**< @ref mdb_dbi_open */
770 uint16_t md_depth; /**< depth of this tree */
771 pgno_t md_branch_pages; /**< number of internal pages */
772 pgno_t md_leaf_pages; /**< number of leaf pages */
773 pgno_t md_overflow_pages; /**< number of overflow pages */
774 size_t md_entries; /**< number of data items */
775 pgno_t md_root; /**< the root page of this tree */
778 /** mdb_dbi_open flags */
779 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
780 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
781 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
782 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
784 /** Handle for the DB used to track free pages. */
786 /** Handle for the default DB. */
789 /** Meta page content. */
790 typedef struct MDB_meta {
791 /** Stamp identifying this as an MDB file. It must be set
794 /** Version number of this lock file. Must be set to #MDB_DATA_VERSION. */
796 void *mm_address; /**< address for fixed mapping */
797 size_t mm_mapsize; /**< size of mmap region */
798 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
799 /** The size of pages used in this DB */
800 #define mm_psize mm_dbs[0].md_pad
801 /** Any persistent environment flags. @ref mdb_env */
802 #define mm_flags mm_dbs[0].md_flags
803 pgno_t mm_last_pg; /**< last used page in file */
804 txnid_t mm_txnid; /**< txnid that committed this page */
807 /** Buffer for a stack-allocated dirty page.
808 * The members define size and alignment, and silence type
809 * aliasing warnings. They are not used directly; that could
810 * mean incorrectly using several union members in parallel.
812 typedef union MDB_pagebuf {
813 char mb_raw[MDB_PAGESIZE];
816 char mm_pad[PAGEHDRSZ];
821 /** Auxiliary DB info.
822 * The information here is mostly static/read-only. There is
823 * only a single copy of this record in the environment.
825 typedef struct MDB_dbx {
826 MDB_val md_name; /**< name of the database */
827 MDB_cmp_func *md_cmp; /**< function for comparing keys */
828 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
829 MDB_rel_func *md_rel; /**< user relocate function */
830 void *md_relctx; /**< user-provided context for md_rel */
833 /** A database transaction.
834 * Every operation requires a transaction handle.
837 MDB_txn *mt_parent; /**< parent of a nested txn */
838 MDB_txn *mt_child; /**< nested txn under this txn */
839 pgno_t mt_next_pgno; /**< next unallocated page */
840 /** The ID of this transaction. IDs are integers incrementing from 1.
841 * Only committed write transactions increment the ID. If a transaction
842 * aborts, the ID may be re-used by the next writer.
845 MDB_env *mt_env; /**< the DB environment */
846 /** The list of pages that became unused during this transaction.
849 /** The sorted list of dirty pages we temporarily wrote to disk
850 * because the dirty list was full.
852 MDB_IDL mt_spill_pgs;
854 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
856 /** For read txns: This thread/txn's reader table slot, or NULL. */
859 /** Array of records for each DB known in the environment. */
861 /** Array of MDB_db records for each known DB */
863 /** @defgroup mt_dbflag Transaction DB Flags
867 #define DB_DIRTY 0x01 /**< DB was written in this txn */
868 #define DB_STALE 0x02 /**< DB record is older than txnID */
869 #define DB_NEW 0x04 /**< DB handle opened in this txn */
870 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
872 /** In write txns, array of cursors for each DB */
873 MDB_cursor **mt_cursors;
874 /** Array of flags for each DB */
875 unsigned char *mt_dbflags;
876 /** Number of DB records in use. This number only ever increments;
877 * we don't decrement it when individual DB handles are closed.
881 /** @defgroup mdb_txn Transaction Flags
885 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
886 #define MDB_TXN_ERROR 0x02 /**< an error has occurred */
887 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
888 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
890 unsigned int mt_flags; /**< @ref mdb_txn */
891 /** dirty_list maxsize - # of allocated pages allowed, including in parent txns */
892 unsigned int mt_dirty_room;
893 /** Tracks which of the two meta pages was used at the start
894 * of this transaction.
896 unsigned int mt_toggle;
899 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
900 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
901 * raise this on a 64 bit machine.
903 #define CURSOR_STACK 32
907 /** Cursors are used for all DB operations */
909 /** Next cursor on this DB in this txn */
911 /** Backup of the original cursor if this cursor is a shadow */
912 MDB_cursor *mc_backup;
913 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
914 struct MDB_xcursor *mc_xcursor;
915 /** The transaction that owns this cursor */
917 /** The database handle this cursor operates on */
919 /** The database record for this cursor */
921 /** The database auxiliary record for this cursor */
923 /** The @ref mt_dbflag for this database */
924 unsigned char *mc_dbflag;
925 unsigned short mc_snum; /**< number of pushed pages */
926 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
927 /** @defgroup mdb_cursor Cursor Flags
929 * Cursor state flags.
932 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
933 #define C_EOF 0x02 /**< No more data */
934 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
935 #define C_SPLITTING 0x20 /**< Cursor is in page_split */
936 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
938 unsigned int mc_flags; /**< @ref mdb_cursor */
939 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
940 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
943 /** Context for sorted-dup records.
944 * We could have gone to a fully recursive design, with arbitrarily
945 * deep nesting of sub-databases. But for now we only handle these
946 * levels - main DB, optional sub-DB, sorted-duplicate DB.
948 typedef struct MDB_xcursor {
949 /** A sub-cursor for traversing the Dup DB */
950 MDB_cursor mx_cursor;
951 /** The database record for this Dup DB */
953 /** The auxiliary DB record for this Dup DB */
955 /** The @ref mt_dbflag for this Dup DB */
956 unsigned char mx_dbflag;
959 /** State of FreeDB old pages, stored in the MDB_env */
960 typedef struct MDB_pgstate {
961 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
962 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
965 /** The database environment. */
967 HANDLE me_fd; /**< The main data file */
968 HANDLE me_lfd; /**< The lock file */
969 HANDLE me_mfd; /**< just for writing the meta pages */
970 /** Failed to update the meta page. Probably an I/O error. */
971 #define MDB_FATAL_ERROR 0x80000000U
972 /** Some fields are initialized. */
973 #define MDB_ENV_ACTIVE 0x20000000U
974 /** me_txkey is set */
975 #define MDB_ENV_TXKEY 0x10000000U
976 /** Have liveness lock in reader table */
977 #define MDB_LIVE_READER 0x08000000U
978 uint32_t me_flags; /**< @ref mdb_env */
979 unsigned int me_psize; /**< size of a page, from #GET_PAGESIZE */
980 unsigned int me_maxreaders; /**< size of the reader table */
981 unsigned int me_numreaders; /**< max numreaders set by this env */
982 MDB_dbi me_numdbs; /**< number of DBs opened */
983 MDB_dbi me_maxdbs; /**< size of the DB table */
984 pid_t me_pid; /**< process ID of this env */
985 char *me_path; /**< path to the DB files */
986 char *me_map; /**< the memory map of the data file */
987 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
988 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
989 MDB_txn *me_txn; /**< current write transaction */
990 size_t me_mapsize; /**< size of the data memory map */
991 off_t me_size; /**< current file size */
992 pgno_t me_maxpg; /**< me_mapsize / me_psize */
993 MDB_dbx *me_dbxs; /**< array of static DB info */
994 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
995 pthread_key_t me_txkey; /**< thread-key for readers */
996 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
997 # define me_pglast me_pgstate.mf_pglast
998 # define me_pghead me_pgstate.mf_pghead
999 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1000 /** IDL of pages that became unused in a write txn */
1001 MDB_IDL me_free_pgs;
1002 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1003 MDB_ID2L me_dirty_list;
1004 /** Max number of freelist items that can fit in a single overflow page */
1006 /** Max size of a node on a page */
1007 unsigned int me_nodemax;
1009 int me_pidquery; /**< Used in OpenProcess */
1010 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
1012 #elif defined(MDB_USE_POSIX_SEM)
1013 sem_t *me_rmutex; /* Shared mutexes are not supported */
1018 /** Nested transaction */
1019 typedef struct MDB_ntxn {
1020 MDB_txn mnt_txn; /* the transaction */
1021 MDB_pgstate mnt_pgstate; /* parent transaction's saved freestate */
1024 /** max number of pages to commit in one writev() call */
1025 #define MDB_COMMIT_PAGES 64
1026 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1027 #undef MDB_COMMIT_PAGES
1028 #define MDB_COMMIT_PAGES IOV_MAX
1031 /* max bytes to write in one call */
1032 #define MAX_WRITE (0x80000000U >> (sizeof(ssize_t) == 4))
1034 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1035 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1036 static int mdb_page_touch(MDB_cursor *mc);
1038 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp, int *lvl);
1039 static int mdb_page_search_root(MDB_cursor *mc,
1040 MDB_val *key, int modify);
1041 #define MDB_PS_MODIFY 1
1042 #define MDB_PS_ROOTONLY 2
1043 static int mdb_page_search(MDB_cursor *mc,
1044 MDB_val *key, int flags);
1045 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1047 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1048 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1049 pgno_t newpgno, unsigned int nflags);
1051 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1052 static int mdb_env_pick_meta(const MDB_env *env);
1053 static int mdb_env_write_meta(MDB_txn *txn);
1054 #if !(defined(_WIN32) || defined(MDB_USE_POSIX_SEM)) /* Drop unused excl arg */
1055 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1057 static void mdb_env_close0(MDB_env *env, int excl);
1059 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1060 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1061 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1062 static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
1063 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1064 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
1065 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1066 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1067 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1069 static int mdb_rebalance(MDB_cursor *mc);
1070 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1072 static void mdb_cursor_pop(MDB_cursor *mc);
1073 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1075 static int mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
1076 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1077 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1078 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1079 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1081 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1082 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1084 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1085 static void mdb_xcursor_init0(MDB_cursor *mc);
1086 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1088 static int mdb_drop0(MDB_cursor *mc, int subs);
1089 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1092 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1096 static SECURITY_DESCRIPTOR mdb_null_sd;
1097 static SECURITY_ATTRIBUTES mdb_all_sa;
1098 static int mdb_sec_inited;
1101 /** Return the library version info. */
1103 mdb_version(int *major, int *minor, int *patch)
1105 if (major) *major = MDB_VERSION_MAJOR;
1106 if (minor) *minor = MDB_VERSION_MINOR;
1107 if (patch) *patch = MDB_VERSION_PATCH;
1108 return MDB_VERSION_STRING;
1111 /** Table of descriptions for MDB @ref errors */
1112 static char *const mdb_errstr[] = {
1113 "MDB_KEYEXIST: Key/data pair already exists",
1114 "MDB_NOTFOUND: No matching key/data pair found",
1115 "MDB_PAGE_NOTFOUND: Requested page not found",
1116 "MDB_CORRUPTED: Located page was wrong type",
1117 "MDB_PANIC: Update of meta page failed",
1118 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1119 "MDB_INVALID: File is not an MDB file",
1120 "MDB_MAP_FULL: Environment mapsize limit reached",
1121 "MDB_DBS_FULL: Environment maxdbs limit reached",
1122 "MDB_READERS_FULL: Environment maxreaders limit reached",
1123 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1124 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1125 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1126 "MDB_PAGE_FULL: Internal error - page has no more space",
1127 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1128 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1129 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1130 "MDB_BAD_TXN: Transaction cannot recover - it must be aborted",
1131 "MDB_BAD_VALSIZE: Too big key/data, key is empty, or wrong DUPFIXED size",
1135 mdb_strerror(int err)
1139 return ("Successful return: 0");
1141 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1142 i = err - MDB_KEYEXIST;
1143 return mdb_errstr[i];
1146 return strerror(err);
1150 /** Display a key in hexadecimal and return the address of the result.
1151 * @param[in] key the key to display
1152 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1153 * @return The key in hexadecimal form.
1156 mdb_dkey(MDB_val *key, char *buf)
1159 unsigned char *c = key->mv_data;
1165 if (key->mv_size > MDB_MAXKEYSIZE)
1166 return "MDB_MAXKEYSIZE";
1167 /* may want to make this a dynamic check: if the key is mostly
1168 * printable characters, print it as-is instead of converting to hex.
1172 for (i=0; i<key->mv_size; i++)
1173 ptr += sprintf(ptr, "%02x", *c++);
1175 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1180 /** Display all the keys in the page. */
1182 mdb_page_list(MDB_page *mp)
1185 unsigned int i, nkeys, nsize;
1189 nkeys = NUMKEYS(mp);
1190 fprintf(stderr, "Page %"Z"u numkeys %d\n", mp->mp_pgno, nkeys);
1191 for (i=0; i<nkeys; i++) {
1192 node = NODEPTR(mp, i);
1193 key.mv_size = node->mn_ksize;
1194 key.mv_data = node->mn_data;
1195 nsize = NODESIZE + NODEKSZ(node) + sizeof(indx_t);
1196 if (IS_BRANCH(mp)) {
1197 fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
1200 if (F_ISSET(node->mn_flags, F_BIGDATA))
1201 nsize += sizeof(pgno_t);
1203 nsize += NODEDSZ(node);
1204 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1210 mdb_cursor_chk(MDB_cursor *mc)
1216 if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1217 for (i=0; i<mc->mc_top; i++) {
1219 node = NODEPTR(mp, mc->mc_ki[i]);
1220 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1223 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1229 /** Count all the pages in each DB and in the freelist
1230 * and make sure it matches the actual number of pages
1233 static void mdb_audit(MDB_txn *txn)
1237 MDB_ID freecount, count;
1242 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1243 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1244 freecount += *(MDB_ID *)data.mv_data;
1247 for (i = 0; i<txn->mt_numdbs; i++) {
1249 mdb_cursor_init(&mc, txn, i, &mx);
1250 if (txn->mt_dbs[i].md_root == P_INVALID)
1252 count += txn->mt_dbs[i].md_branch_pages +
1253 txn->mt_dbs[i].md_leaf_pages +
1254 txn->mt_dbs[i].md_overflow_pages;
1255 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1256 mdb_page_search(&mc, NULL, 0);
1260 mp = mc.mc_pg[mc.mc_top];
1261 for (j=0; j<NUMKEYS(mp); j++) {
1262 MDB_node *leaf = NODEPTR(mp, j);
1263 if (leaf->mn_flags & F_SUBDATA) {
1265 memcpy(&db, NODEDATA(leaf), sizeof(db));
1266 count += db.md_branch_pages + db.md_leaf_pages +
1267 db.md_overflow_pages;
1271 while (mdb_cursor_sibling(&mc, 1) == 0);
1274 if (freecount + count + 2 /* metapages */ != txn->mt_next_pgno) {
1275 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1276 txn->mt_txnid, freecount, count+2, freecount+count+2, txn->mt_next_pgno);
1282 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1284 return txn->mt_dbxs[dbi].md_cmp(a, b);
1288 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1290 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1293 /** Allocate memory for a page.
1294 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1297 mdb_page_malloc(MDB_txn *txn, unsigned num)
1299 MDB_env *env = txn->mt_env;
1300 MDB_page *ret = env->me_dpages;
1301 size_t sz = env->me_psize;
1304 VGMEMP_ALLOC(env, ret, sz);
1305 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1306 env->me_dpages = ret->mp_next;
1312 if ((ret = malloc(sz)) != NULL) {
1313 VGMEMP_ALLOC(env, ret, sz);
1318 /** Free a single page.
1319 * Saves single pages to a list, for future reuse.
1320 * (This is not used for multi-page overflow pages.)
1323 mdb_page_free(MDB_env *env, MDB_page *mp)
1325 mp->mp_next = env->me_dpages;
1326 VGMEMP_FREE(env, mp);
1327 env->me_dpages = mp;
1330 /* Free a dirty page */
1332 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1334 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1335 mdb_page_free(env, dp);
1337 /* large pages just get freed directly */
1338 VGMEMP_FREE(env, dp);
1343 /** Return all dirty pages to dpage list */
1345 mdb_dlist_free(MDB_txn *txn)
1347 MDB_env *env = txn->mt_env;
1348 MDB_ID2L dl = txn->mt_u.dirty_list;
1349 unsigned i, n = dl[0].mid;
1351 for (i = 1; i <= n; i++) {
1352 mdb_dpage_free(env, dl[i].mptr);
1357 /* Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
1358 * @param[in] mc A cursor handle for the current operation.
1359 * @param[in] pflags Flags of the pages to update:
1360 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1361 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
1362 * @return 0 on success, non-zero on failure.
1365 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
1367 MDB_txn *txn = mc->mc_txn;
1372 int rc = MDB_SUCCESS, level;
1374 /* Mark pages seen by cursors */
1375 if (mc->mc_flags & C_UNTRACK)
1376 mc = NULL; /* will find mc in mt_cursors */
1377 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1378 for (; mc; mc=mc->mc_next) {
1379 for (m3 = mc; m3->mc_flags & C_INITIALIZED; m3 = &mx->mx_cursor) {
1380 for (j=0; j<m3->mc_snum; j++)
1381 if ((m3->mc_pg[j]->mp_flags & (P_SUBP|P_DIRTY|P_KEEP))
1383 m3->mc_pg[j]->mp_flags ^= P_KEEP;
1384 mx = m3->mc_xcursor;
1394 /* Mark dirty root pages */
1395 for (i=0; i<txn->mt_numdbs; i++) {
1396 if (txn->mt_dbflags[i] & DB_DIRTY) {
1397 pgno_t pgno = txn->mt_dbs[i].md_root;
1398 if (pgno == P_INVALID)
1400 if ((rc = mdb_page_get(txn, pgno, &dp, &level)) != MDB_SUCCESS)
1402 if ((dp->mp_flags & (P_DIRTY|P_KEEP)) == pflags && level <= 1)
1403 dp->mp_flags ^= P_KEEP;
1411 static int mdb_page_flush(MDB_txn *txn, int keep);
1413 /** Spill pages from the dirty list back to disk.
1414 * This is intended to prevent running into #MDB_TXN_FULL situations,
1415 * but note that they may still occur in a few cases:
1416 * 1) pages in #MDB_DUPSORT sub-DBs are never spilled, so if there
1417 * are too many of these dirtied in one txn, the txn may still get
1419 * 2) child txns may run out of space if their parents dirtied a
1420 * lot of pages and never spilled them. TODO: we probably should do
1421 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1422 * the parent's dirty_room is below a given threshold.
1423 * 3) our estimate of the txn size could be too small. At the
1424 * moment this seems unlikely.
1426 * Otherwise, if not using nested txns, it is expected that apps will
1427 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1428 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1429 * If the txn never references them again, they can be left alone.
1430 * If the txn only reads them, they can be used without any fuss.
1431 * If the txn writes them again, they can be dirtied immediately without
1432 * going thru all of the work of #mdb_page_touch(). Such references are
1433 * handled by #mdb_page_unspill().
1435 * Also note, we never spill DB root pages, nor pages of active cursors,
1436 * because we'll need these back again soon anyway. And in nested txns,
1437 * we can't spill a page in a child txn if it was already spilled in a
1438 * parent txn. That would alter the parent txns' data even though
1439 * the child hasn't committed yet, and we'd have no way to undo it if
1440 * the child aborted.
1442 * @param[in] m0 cursor A cursor handle identifying the transaction and
1443 * database for which we are checking space.
1444 * @param[in] key For a put operation, the key being stored.
1445 * @param[in] data For a put operation, the data being stored.
1446 * @return 0 on success, non-zero on failure.
1449 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1451 MDB_txn *txn = m0->mc_txn;
1453 MDB_ID2L dl = txn->mt_u.dirty_list;
1454 unsigned int i, j, need;
1457 if (m0->mc_flags & C_SUB)
1460 /* Estimate how much space this op will take */
1461 i = m0->mc_db->md_depth;
1462 /* Named DBs also dirty the main DB */
1463 if (m0->mc_dbi > MAIN_DBI)
1464 i += txn->mt_dbs[MAIN_DBI].md_depth;
1465 /* For puts, roughly factor in the key+data size */
1467 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
1468 i += i; /* double it for good measure */
1471 if (txn->mt_dirty_room > i)
1474 if (!txn->mt_spill_pgs) {
1475 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
1476 if (!txn->mt_spill_pgs)
1480 /* Preserve pages which may soon be dirtied again */
1481 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
1484 /* Less aggressive spill - we originally spilled the entire dirty list,
1485 * with a few exceptions for cursor pages and DB root pages. But this
1486 * turns out to be a lot of wasted effort because in a large txn many
1487 * of those pages will need to be used again. So now we spill only 1/8th
1488 * of the dirty pages. Testing revealed this to be a good tradeoff,
1489 * better than 1/2, 1/4, or 1/10.
1491 if (need < MDB_IDL_UM_MAX / 8)
1492 need = MDB_IDL_UM_MAX / 8;
1494 /* Save the page IDs of all the pages we're flushing */
1495 /* flush from the tail forward, this saves a lot of shifting later on. */
1496 for (i=dl[0].mid; i && need; i--) {
1498 if (dp->mp_flags & P_KEEP)
1500 /* Can't spill twice, make sure it's not already in a parent's
1503 if (txn->mt_parent) {
1505 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1506 if (tx2->mt_spill_pgs) {
1507 j = mdb_midl_search(tx2->mt_spill_pgs, dl[i].mid);
1508 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == dl[i].mid) {
1509 dp->mp_flags |= P_KEEP;
1517 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, dl[i].mid)))
1521 mdb_midl_sort(txn->mt_spill_pgs);
1523 /* Flush the spilled part of dirty list */
1524 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
1527 /* Reset any dirty pages we kept that page_flush didn't see */
1528 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
1532 if (txn->mt_parent) {
1533 txn->mt_dirty_room = txn->mt_parent->mt_dirty_room - dl[0].mid;
1534 /* dirty pages that are dirty in an ancestor don't
1535 * count against this txn's dirty_room.
1537 for (i=1; i<=dl[0].mid; i++) {
1538 pgno_t pgno = dl[i].mid;
1540 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1541 j = mdb_mid2l_search(tx2->mt_u.dirty_list, pgno);
1542 if (j <= tx2->mt_u.dirty_list[0].mid &&
1543 tx2->mt_u.dirty_list[j].mid == pgno) {
1544 txn->mt_dirty_room++;
1550 txn->mt_dirty_room = MDB_IDL_UM_MAX - dl[0].mid;
1552 txn->mt_flags |= MDB_TXN_SPILLS;
1554 txn->mt_flags |= MDB_TXN_ERROR;
1559 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
1561 mdb_find_oldest(MDB_txn *txn)
1564 txnid_t mr, oldest = txn->mt_txnid - 1;
1565 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
1566 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
1576 /** Add a page to the txn's dirty list */
1578 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
1581 int (*insert)(MDB_ID2L, MDB_ID2 *);
1583 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1584 insert = mdb_mid2l_append;
1586 insert = mdb_mid2l_insert;
1588 mid.mid = mp->mp_pgno;
1590 insert(txn->mt_u.dirty_list, &mid);
1591 txn->mt_dirty_room--;
1594 /** Allocate page numbers and memory for writing. Maintain me_pglast,
1595 * me_pghead and mt_next_pgno.
1597 * If there are free pages available from older transactions, they
1598 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
1599 * Do not modify the freedB, just merge freeDB records into me_pghead[]
1600 * and move me_pglast to say which records were consumed. Only this
1601 * function can create me_pghead and move me_pglast/mt_next_pgno.
1602 * @param[in] mc cursor A cursor handle identifying the transaction and
1603 * database for which we are allocating.
1604 * @param[in] num the number of pages to allocate.
1605 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
1606 * will always be satisfied by a single contiguous chunk of memory.
1607 * @return 0 on success, non-zero on failure.
1610 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
1612 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
1613 /* Get at most <Max_retries> more freeDB records once me_pghead
1614 * has enough pages. If not enough, use new pages from the map.
1615 * If <Paranoid> and mc is updating the freeDB, only get new
1616 * records if me_pghead is empty. Then the freelist cannot play
1617 * catch-up with itself by growing while trying to save it.
1619 enum { Paranoid = 1, Max_retries = 500 };
1621 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
1623 int rc, n2 = num-1, retry = Max_retries;
1624 MDB_txn *txn = mc->mc_txn;
1625 MDB_env *env = txn->mt_env;
1626 pgno_t pgno, *mop = env->me_pghead;
1627 unsigned i, j, k, mop_len = mop ? mop[0] : 0;
1629 txnid_t oldest = 0, last;
1635 /* If our dirty list is already full, we can't do anything */
1636 if (txn->mt_dirty_room == 0)
1637 return MDB_TXN_FULL;
1639 for (op = MDB_FIRST;; op = MDB_NEXT) {
1642 pgno_t *idl, old_id, new_id;
1644 /* Seek a big enough contiguous page range. Prefer
1645 * pages at the tail, just truncating the list.
1647 if (mop_len >= (unsigned)num) {
1651 if (mop[i-n2] == pgno+n2)
1653 } while (--i >= (unsigned)num);
1654 if (Max_retries < INT_MAX && --retry < 0)
1658 if (op == MDB_FIRST) { /* 1st iteration */
1659 /* Prepare to fetch more and coalesce */
1660 oldest = mdb_find_oldest(txn);
1661 last = env->me_pglast;
1662 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1665 key.mv_data = &last; /* will look up last+1 */
1666 key.mv_size = sizeof(last);
1668 if (Paranoid && mc->mc_dbi == FREE_DBI)
1671 if (Paranoid && retry < 0 && mop_len)
1675 /* Do not fetch more if the record will be too recent */
1678 rc = mdb_cursor_get(&m2, &key, NULL, op);
1680 if (rc == MDB_NOTFOUND)
1684 last = *(txnid_t*)key.mv_data;
1687 np = m2.mc_pg[m2.mc_top];
1688 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
1689 if ((rc = mdb_node_read(txn, leaf, &data)) != MDB_SUCCESS)
1692 idl = (MDB_ID *) data.mv_data;
1695 if (!(env->me_pghead = mop = mdb_midl_alloc(i)))
1698 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
1700 mop = env->me_pghead;
1702 env->me_pglast = last;
1704 DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
1705 last, txn->mt_dbs[FREE_DBI].md_root, i));
1707 DPRINTF(("IDL %"Z"u", idl[k]));
1709 /* Merge in descending sorted order */
1712 mop[0] = (pgno_t)-1;
1716 for (; old_id < new_id; old_id = mop[--j])
1723 /* Use new pages from the map when nothing suitable in the freeDB */
1725 pgno = txn->mt_next_pgno;
1726 if (pgno + num >= env->me_maxpg) {
1727 DPUTS("DB size maxed out");
1728 return MDB_MAP_FULL;
1732 if (env->me_flags & MDB_WRITEMAP) {
1733 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
1735 if (!(np = mdb_page_malloc(txn, num)))
1739 mop[0] = mop_len -= num;
1740 /* Move any stragglers down */
1741 for (j = i-num; j < mop_len; )
1742 mop[++j] = mop[++i];
1744 txn->mt_next_pgno = pgno + num;
1747 mdb_page_dirty(txn, np);
1753 /** Copy the used portions of a non-overflow page.
1754 * @param[in] dst page to copy into
1755 * @param[in] src page to copy from
1756 * @param[in] psize size of a page
1759 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
1761 enum { Align = sizeof(pgno_t) };
1762 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
1764 /* If page isn't full, just copy the used portion. Adjust
1765 * alignment so memcpy may copy words instead of bytes.
1767 if ((unused &= -Align) && !IS_LEAF2(src)) {
1769 memcpy(dst, src, (lower + (Align-1)) & -Align);
1770 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
1773 memcpy(dst, src, psize - unused);
1777 /** Pull a page off the txn's spill list, if present.
1778 * If a page being referenced was spilled to disk in this txn, bring
1779 * it back and make it dirty/writable again.
1780 * @param[in] tx0 the transaction handle.
1781 * @param[in] mp the page being referenced.
1782 * @param[out] ret the writable page, if any. ret is unchanged if
1783 * mp wasn't spilled.
1786 mdb_page_unspill(MDB_txn *tx0, MDB_page *mp, MDB_page **ret)
1788 MDB_env *env = tx0->mt_env;
1791 pgno_t pgno = mp->mp_pgno;
1793 for (txn = tx0; txn; txn=txn->mt_parent) {
1794 if (!txn->mt_spill_pgs)
1796 x = mdb_midl_search(txn->mt_spill_pgs, pgno);
1797 if (x <= txn->mt_spill_pgs[0] && txn->mt_spill_pgs[x] == pgno) {
1800 if (IS_OVERFLOW(mp))
1804 if (env->me_flags & MDB_WRITEMAP) {
1807 np = mdb_page_malloc(txn, num);
1811 memcpy(np, mp, num * env->me_psize);
1813 mdb_page_copy(np, mp, env->me_psize);
1816 /* If in current txn, this page is no longer spilled */
1817 for (; x < txn->mt_spill_pgs[0]; x++)
1818 txn->mt_spill_pgs[x] = txn->mt_spill_pgs[x+1];
1819 txn->mt_spill_pgs[0]--;
1820 } /* otherwise, if belonging to a parent txn, the
1821 * page remains spilled until child commits
1824 if (txn->mt_parent) {
1826 /* If this page is also in a parent's dirty list, then
1827 * it's already accounted in dirty_room, and we need to
1828 * cancel out the decrement that mdb_page_dirty does.
1830 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1831 x = mdb_mid2l_search(tx2->mt_u.dirty_list, pgno);
1832 if (x <= tx2->mt_u.dirty_list[0].mid &&
1833 tx2->mt_u.dirty_list[x].mid == pgno) {
1834 txn->mt_dirty_room++;
1839 mdb_page_dirty(tx0, np);
1840 np->mp_flags |= P_DIRTY;
1848 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1849 * @param[in] mc cursor pointing to the page to be touched
1850 * @return 0 on success, non-zero on failure.
1853 mdb_page_touch(MDB_cursor *mc)
1855 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
1856 MDB_txn *txn = mc->mc_txn;
1857 MDB_cursor *m2, *m3;
1862 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1863 if (txn->mt_flags & MDB_TXN_SPILLS) {
1865 rc = mdb_page_unspill(txn, mp, &np);
1871 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
1872 (rc = mdb_page_alloc(mc, 1, &np)))
1875 DPRINTF(("touched db %u page %"Z"u -> %"Z"u", mc->mc_dbi,mp->mp_pgno,pgno));
1876 assert(mp->mp_pgno != pgno);
1877 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
1878 /* Update the parent page, if any, to point to the new page */
1880 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
1881 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
1882 SETPGNO(node, pgno);
1884 mc->mc_db->md_root = pgno;
1886 } else if (txn->mt_parent && !IS_SUBP(mp)) {
1887 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
1889 /* If txn has a parent, make sure the page is in our
1893 unsigned x = mdb_mid2l_search(dl, pgno);
1894 if (x <= dl[0].mid && dl[x].mid == pgno) {
1895 if (mp != dl[x].mptr) { /* bad cursor? */
1896 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1897 return MDB_CORRUPTED;
1902 assert(dl[0].mid < MDB_IDL_UM_MAX);
1904 np = mdb_page_malloc(txn, 1);
1909 mdb_mid2l_insert(dl, &mid);
1914 mdb_page_copy(np, mp, txn->mt_env->me_psize);
1916 np->mp_flags |= P_DIRTY;
1919 /* Adjust cursors pointing to mp */
1920 mc->mc_pg[mc->mc_top] = np;
1922 if (mc->mc_flags & C_SUB) {
1924 for (m2 = txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
1925 m3 = &m2->mc_xcursor->mx_cursor;
1926 if (m3->mc_snum < mc->mc_snum) continue;
1927 if (m3->mc_pg[mc->mc_top] == mp)
1928 m3->mc_pg[mc->mc_top] = np;
1931 for (m2 = txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
1932 if (m2->mc_snum < mc->mc_snum) continue;
1933 if (m2->mc_pg[mc->mc_top] == mp) {
1934 m2->mc_pg[mc->mc_top] = np;
1935 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
1936 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
1938 MDB_node *leaf = NODEPTR(np, mc->mc_ki[mc->mc_top]);
1939 if (!(leaf->mn_flags & F_SUBDATA))
1940 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
1949 mdb_env_sync(MDB_env *env, int force)
1952 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1953 if (env->me_flags & MDB_WRITEMAP) {
1954 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
1955 ? MS_ASYNC : MS_SYNC;
1956 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
1959 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
1963 if (MDB_FDATASYNC(env->me_fd))
1970 /** Back up parent txn's cursors, then grab the originals for tracking */
1972 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
1974 MDB_cursor *mc, *bk;
1979 for (i = src->mt_numdbs; --i >= 0; ) {
1980 if ((mc = src->mt_cursors[i]) != NULL) {
1981 size = sizeof(MDB_cursor);
1983 size += sizeof(MDB_xcursor);
1984 for (; mc; mc = bk->mc_next) {
1990 mc->mc_db = &dst->mt_dbs[i];
1991 /* Kill pointers into src - and dst to reduce abuse: The
1992 * user may not use mc until dst ends. Otherwise we'd...
1994 mc->mc_txn = NULL; /* ...set this to dst */
1995 mc->mc_dbflag = NULL; /* ...and &dst->mt_dbflags[i] */
1996 if ((mx = mc->mc_xcursor) != NULL) {
1997 *(MDB_xcursor *)(bk+1) = *mx;
1998 mx->mx_cursor.mc_txn = NULL; /* ...and dst. */
2000 mc->mc_next = dst->mt_cursors[i];
2001 dst->mt_cursors[i] = mc;
2008 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2009 * @param[in] txn the transaction handle.
2010 * @param[in] merge true to keep changes to parent cursors, false to revert.
2011 * @return 0 on success, non-zero on failure.
2014 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2016 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2020 for (i = txn->mt_numdbs; --i >= 0; ) {
2021 for (mc = cursors[i]; mc; mc = next) {
2023 if ((bk = mc->mc_backup) != NULL) {
2025 /* Commit changes to parent txn */
2026 mc->mc_next = bk->mc_next;
2027 mc->mc_backup = bk->mc_backup;
2028 mc->mc_txn = bk->mc_txn;
2029 mc->mc_db = bk->mc_db;
2030 mc->mc_dbflag = bk->mc_dbflag;
2031 if ((mx = mc->mc_xcursor) != NULL)
2032 mx->mx_cursor.mc_txn = bk->mc_txn;
2034 /* Abort nested txn */
2036 if ((mx = mc->mc_xcursor) != NULL)
2037 *mx = *(MDB_xcursor *)(bk+1);
2041 /* Only malloced cursors are permanently tracked. */
2049 #define mdb_txn_reset0(txn, act) mdb_txn_reset0(txn)
2052 mdb_txn_reset0(MDB_txn *txn, const char *act);
2054 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2060 Pidset = F_SETLK, Pidcheck = F_GETLK
2064 /** Set or check a pid lock. Set returns 0 on success.
2065 * Check returns 0 if the process is certainly dead, nonzero if it may
2066 * be alive (the lock exists or an error happened so we do not know).
2068 * On Windows Pidset is a no-op, we merely check for the existence
2069 * of the process with the given pid. On POSIX we use a single byte
2070 * lock on the lockfile, set at an offset equal to the pid.
2073 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, pid_t pid)
2075 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2078 if (op == Pidcheck) {
2079 h = OpenProcess(env->me_pidquery, FALSE, pid);
2080 /* No documented "no such process" code, but other program use this: */
2082 return ErrCode() != ERROR_INVALID_PARAMETER;
2083 /* A process exists until all handles to it close. Has it exited? */
2084 ret = WaitForSingleObject(h, 0) != 0;
2091 struct flock lock_info;
2092 memset(&lock_info, 0, sizeof(lock_info));
2093 lock_info.l_type = F_WRLCK;
2094 lock_info.l_whence = SEEK_SET;
2095 lock_info.l_start = pid;
2096 lock_info.l_len = 1;
2097 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2098 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2100 } else if ((rc = ErrCode()) == EINTR) {
2108 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2109 * @param[in] txn the transaction handle to initialize
2110 * @return 0 on success, non-zero on failure.
2113 mdb_txn_renew0(MDB_txn *txn)
2115 MDB_env *env = txn->mt_env;
2118 int rc, new_notls = 0;
2121 txn->mt_numdbs = env->me_numdbs;
2122 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
2124 if (txn->mt_flags & MDB_TXN_RDONLY) {
2125 if (!env->me_txns) {
2126 i = mdb_env_pick_meta(env);
2127 txn->mt_txnid = env->me_metas[i]->mm_txnid;
2128 txn->mt_u.reader = NULL;
2130 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2131 pthread_getspecific(env->me_txkey);
2133 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2134 return MDB_BAD_RSLOT;
2136 pid_t pid = env->me_pid;
2137 pthread_t tid = pthread_self();
2139 if (!(env->me_flags & MDB_LIVE_READER)) {
2140 rc = mdb_reader_pid(env, Pidset, pid);
2142 UNLOCK_MUTEX_R(env);
2145 env->me_flags |= MDB_LIVE_READER;
2149 for (i=0; i<env->me_txns->mti_numreaders; i++)
2150 if (env->me_txns->mti_readers[i].mr_pid == 0)
2152 if (i == env->me_maxreaders) {
2153 UNLOCK_MUTEX_R(env);
2154 return MDB_READERS_FULL;
2156 env->me_txns->mti_readers[i].mr_pid = pid;
2157 env->me_txns->mti_readers[i].mr_tid = tid;
2158 if (i >= env->me_txns->mti_numreaders)
2159 env->me_txns->mti_numreaders = i+1;
2160 /* Save numreaders for un-mutexed mdb_env_close() */
2161 env->me_numreaders = env->me_txns->mti_numreaders;
2162 UNLOCK_MUTEX_R(env);
2163 r = &env->me_txns->mti_readers[i];
2164 new_notls = (env->me_flags & MDB_NOTLS);
2165 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2170 txn->mt_txnid = r->mr_txnid = env->me_txns->mti_txnid;
2171 txn->mt_u.reader = r;
2173 txn->mt_toggle = txn->mt_txnid & 1;
2177 txn->mt_txnid = env->me_txns->mti_txnid;
2178 txn->mt_toggle = txn->mt_txnid & 1;
2181 if (txn->mt_txnid == mdb_debug_start)
2184 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2185 txn->mt_u.dirty_list = env->me_dirty_list;
2186 txn->mt_u.dirty_list[0].mid = 0;
2187 txn->mt_free_pgs = env->me_free_pgs;
2188 txn->mt_free_pgs[0] = 0;
2189 txn->mt_spill_pgs = NULL;
2193 /* Copy the DB info and flags */
2194 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
2196 /* Moved to here to avoid a data race in read TXNs */
2197 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
2199 for (i=2; i<txn->mt_numdbs; i++) {
2200 x = env->me_dbflags[i];
2201 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2202 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_STALE : 0;
2204 txn->mt_dbflags[0] = txn->mt_dbflags[1] = DB_VALID;
2206 if (env->me_maxpg < txn->mt_next_pgno) {
2207 mdb_txn_reset0(txn, "renew0-mapfail");
2209 txn->mt_u.reader->mr_pid = 0;
2210 txn->mt_u.reader = NULL;
2212 return MDB_MAP_RESIZED;
2219 mdb_txn_renew(MDB_txn *txn)
2223 if (!txn || txn->mt_dbxs) /* A reset txn has mt_dbxs==NULL */
2226 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
2227 DPUTS("environment had fatal error, must shutdown!");
2231 rc = mdb_txn_renew0(txn);
2232 if (rc == MDB_SUCCESS) {
2233 DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2234 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2235 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2241 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2245 int rc, size, tsize = sizeof(MDB_txn);
2247 if (env->me_flags & MDB_FATAL_ERROR) {
2248 DPUTS("environment had fatal error, must shutdown!");
2251 if ((env->me_flags & MDB_RDONLY) && !(flags & MDB_RDONLY))
2254 /* Nested transactions: Max 1 child, write txns only, no writemap */
2255 if (parent->mt_child ||
2256 (flags & MDB_RDONLY) ||
2257 (parent->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR)) ||
2258 (env->me_flags & MDB_WRITEMAP))
2260 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
2262 tsize = sizeof(MDB_ntxn);
2264 size = tsize + env->me_maxdbs * (sizeof(MDB_db)+1);
2265 if (!(flags & MDB_RDONLY))
2266 size += env->me_maxdbs * sizeof(MDB_cursor *);
2268 if ((txn = calloc(1, size)) == NULL) {
2269 DPRINTF(("calloc: %s", strerror(ErrCode())));
2272 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2273 if (flags & MDB_RDONLY) {
2274 txn->mt_flags |= MDB_TXN_RDONLY;
2275 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
2277 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2278 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
2284 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2285 if (!txn->mt_u.dirty_list ||
2286 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2288 free(txn->mt_u.dirty_list);
2292 txn->mt_txnid = parent->mt_txnid;
2293 txn->mt_toggle = parent->mt_toggle;
2294 txn->mt_dirty_room = parent->mt_dirty_room;
2295 txn->mt_u.dirty_list[0].mid = 0;
2296 txn->mt_spill_pgs = NULL;
2297 txn->mt_next_pgno = parent->mt_next_pgno;
2298 parent->mt_child = txn;
2299 txn->mt_parent = parent;
2300 txn->mt_numdbs = parent->mt_numdbs;
2301 txn->mt_flags = parent->mt_flags;
2302 txn->mt_dbxs = parent->mt_dbxs;
2303 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2304 /* Copy parent's mt_dbflags, but clear DB_NEW */
2305 for (i=0; i<txn->mt_numdbs; i++)
2306 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2308 ntxn = (MDB_ntxn *)txn;
2309 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2310 if (env->me_pghead) {
2311 size = MDB_IDL_SIZEOF(env->me_pghead);
2312 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2314 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2319 rc = mdb_cursor_shadow(parent, txn);
2321 mdb_txn_reset0(txn, "beginchild-fail");
2323 rc = mdb_txn_renew0(txn);
2329 DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2330 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2331 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
2338 mdb_txn_env(MDB_txn *txn)
2340 if(!txn) return NULL;
2344 /** Export or close DBI handles opened in this txn. */
2346 mdb_dbis_update(MDB_txn *txn, int keep)
2349 MDB_dbi n = txn->mt_numdbs;
2350 MDB_env *env = txn->mt_env;
2351 unsigned char *tdbflags = txn->mt_dbflags;
2353 for (i = n; --i >= 2;) {
2354 if (tdbflags[i] & DB_NEW) {
2356 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2358 char *ptr = env->me_dbxs[i].md_name.mv_data;
2359 env->me_dbxs[i].md_name.mv_data = NULL;
2360 env->me_dbxs[i].md_name.mv_size = 0;
2361 env->me_dbflags[i] = 0;
2366 if (keep && env->me_numdbs < n)
2370 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
2371 * May be called twice for readonly txns: First reset it, then abort.
2372 * @param[in] txn the transaction handle to reset
2373 * @param[in] act why the transaction is being reset
2376 mdb_txn_reset0(MDB_txn *txn, const char *act)
2378 MDB_env *env = txn->mt_env;
2380 /* Close any DBI handles opened in this txn */
2381 mdb_dbis_update(txn, 0);
2383 DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2384 act, txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2385 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
2387 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2388 if (txn->mt_u.reader) {
2389 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2390 if (!(env->me_flags & MDB_NOTLS))
2391 txn->mt_u.reader = NULL; /* txn does not own reader */
2393 txn->mt_numdbs = 0; /* close nothing if called again */
2394 txn->mt_dbxs = NULL; /* mark txn as reset */
2396 mdb_cursors_close(txn, 0);
2398 if (!(env->me_flags & MDB_WRITEMAP)) {
2399 mdb_dlist_free(txn);
2401 mdb_midl_free(env->me_pghead);
2403 if (txn->mt_parent) {
2404 txn->mt_parent->mt_child = NULL;
2405 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2406 mdb_midl_free(txn->mt_free_pgs);
2407 mdb_midl_free(txn->mt_spill_pgs);
2408 free(txn->mt_u.dirty_list);
2412 if (mdb_midl_shrink(&txn->mt_free_pgs))
2413 env->me_free_pgs = txn->mt_free_pgs;
2414 env->me_pghead = NULL;
2418 /* The writer mutex was locked in mdb_txn_begin. */
2419 UNLOCK_MUTEX_W(env);
2424 mdb_txn_reset(MDB_txn *txn)
2429 /* This call is only valid for read-only txns */
2430 if (!(txn->mt_flags & MDB_TXN_RDONLY))
2433 mdb_txn_reset0(txn, "reset");
2437 mdb_txn_abort(MDB_txn *txn)
2443 mdb_txn_abort(txn->mt_child);
2445 mdb_txn_reset0(txn, "abort");
2446 /* Free reader slot tied to this txn (if MDB_NOTLS && writable FS) */
2447 if ((txn->mt_flags & MDB_TXN_RDONLY) && txn->mt_u.reader)
2448 txn->mt_u.reader->mr_pid = 0;
2453 /** Save the freelist as of this transaction to the freeDB.
2454 * This changes the freelist. Keep trying until it stabilizes.
2457 mdb_freelist_save(MDB_txn *txn)
2459 /* env->me_pghead[] can grow and shrink during this call.
2460 * env->me_pglast and txn->mt_free_pgs[] can only grow.
2461 * Page numbers cannot disappear from txn->mt_free_pgs[].
2464 MDB_env *env = txn->mt_env;
2465 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
2466 txnid_t pglast = 0, head_id = 0;
2467 pgno_t freecnt = 0, *free_pgs, *mop;
2468 ssize_t head_room = 0, total_room = 0, mop_len;
2470 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
2472 if (env->me_pghead) {
2473 /* Make sure first page of freeDB is touched and on freelist */
2474 rc = mdb_page_search(&mc, NULL, MDB_PS_MODIFY);
2475 if (rc && rc != MDB_NOTFOUND)
2480 /* Come back here after each Put() in case freelist changed */
2483 /* If using records from freeDB which we have not yet
2484 * deleted, delete them and any we reserved for me_pghead.
2486 while (pglast < env->me_pglast) {
2487 rc = mdb_cursor_first(&mc, &key, NULL);
2490 pglast = head_id = *(txnid_t *)key.mv_data;
2491 total_room = head_room = 0;
2492 assert(pglast <= env->me_pglast);
2493 rc = mdb_cursor_del(&mc, 0);
2498 /* Save the IDL of pages freed by this txn, to a single record */
2499 if (freecnt < txn->mt_free_pgs[0]) {
2501 /* Make sure last page of freeDB is touched and on freelist */
2502 key.mv_size = MDB_MAXKEYSIZE+1;
2504 rc = mdb_page_search(&mc, &key, MDB_PS_MODIFY);
2505 if (rc && rc != MDB_NOTFOUND)
2508 free_pgs = txn->mt_free_pgs;
2509 /* Write to last page of freeDB */
2510 key.mv_size = sizeof(txn->mt_txnid);
2511 key.mv_data = &txn->mt_txnid;
2513 freecnt = free_pgs[0];
2514 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
2515 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2518 /* Retry if mt_free_pgs[] grew during the Put() */
2519 free_pgs = txn->mt_free_pgs;
2520 } while (freecnt < free_pgs[0]);
2521 mdb_midl_sort(free_pgs);
2522 memcpy(data.mv_data, free_pgs, data.mv_size);
2525 unsigned int i = free_pgs[0];
2526 DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
2527 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
2529 DPRINTF(("IDL %"Z"u", free_pgs[i]));
2535 mop = env->me_pghead;
2536 mop_len = mop ? mop[0] : 0;
2538 /* Reserve records for me_pghead[]. Split it if multi-page,
2539 * to avoid searching freeDB for a page range. Use keys in
2540 * range [1,me_pglast]: Smaller than txnid of oldest reader.
2542 if (total_room >= mop_len) {
2543 if (total_room == mop_len || --more < 0)
2545 } else if (head_room >= maxfree_1pg && head_id > 1) {
2546 /* Keep current record (overflow page), add a new one */
2550 /* (Re)write {key = head_id, IDL length = head_room} */
2551 total_room -= head_room;
2552 head_room = mop_len - total_room;
2553 if (head_room > maxfree_1pg && head_id > 1) {
2554 /* Overflow multi-page for part of me_pghead */
2555 head_room /= head_id; /* amortize page sizes */
2556 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
2557 } else if (head_room < 0) {
2558 /* Rare case, not bothering to delete this record */
2561 key.mv_size = sizeof(head_id);
2562 key.mv_data = &head_id;
2563 data.mv_size = (head_room + 1) * sizeof(pgno_t);
2564 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2567 *(MDB_ID *)data.mv_data = 0; /* IDL is initially empty */
2568 total_room += head_room;
2571 /* Fill in the reserved, touched me_pghead records */
2577 rc = mdb_cursor_first(&mc, &key, &data);
2578 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
2579 unsigned flags = MDB_CURRENT;
2580 txnid_t id = *(txnid_t *)key.mv_data;
2581 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
2584 assert(len >= 0 && id <= env->me_pglast);
2586 if (len > mop_len) {
2588 data.mv_size = (len + 1) * sizeof(MDB_ID);
2591 data.mv_data = mop -= len;
2594 rc = mdb_cursor_put(&mc, &key, &data, flags);
2596 if (rc || !(mop_len -= len))
2603 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
2604 * @param[in] txn the transaction that's being committed
2605 * @param[in] keep number of initial pages in dirty_list to keep dirty.
2606 * @return 0 on success, non-zero on failure.
2609 mdb_page_flush(MDB_txn *txn, int keep)
2611 MDB_env *env = txn->mt_env;
2612 MDB_ID2L dl = txn->mt_u.dirty_list;
2613 unsigned psize = env->me_psize, j;
2614 int i, pagecount = dl[0].mid, rc;
2615 size_t size = 0, pos = 0;
2617 MDB_page *dp = NULL;
2621 struct iovec iov[MDB_COMMIT_PAGES];
2622 ssize_t wpos = 0, wsize = 0, wres;
2623 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
2629 if (env->me_flags & MDB_WRITEMAP) {
2630 /* Clear dirty flags */
2631 while (++i <= pagecount) {
2633 /* Don't flush this page yet */
2634 if (dp->mp_flags & P_KEEP) {
2635 dp->mp_flags ^= P_KEEP;
2639 dp->mp_flags &= ~P_DIRTY;
2645 /* Write the pages */
2647 if (++i <= pagecount) {
2649 /* Don't flush this page yet */
2650 if (dp->mp_flags & P_KEEP) {
2651 dp->mp_flags ^= P_KEEP;
2656 /* clear dirty flag */
2657 dp->mp_flags &= ~P_DIRTY;
2660 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
2665 /* Windows actually supports scatter/gather I/O, but only on
2666 * unbuffered file handles. Since we're relying on the OS page
2667 * cache for all our data, that's self-defeating. So we just
2668 * write pages one at a time. We use the ov structure to set
2669 * the write offset, to at least save the overhead of a Seek
2672 DPRINTF(("committing page %"Z"u", pgno));
2673 memset(&ov, 0, sizeof(ov));
2674 ov.Offset = pos & 0xffffffff;
2675 ov.OffsetHigh = pos >> 16 >> 16;
2676 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
2678 DPRINTF(("WriteFile: %d", rc));
2682 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
2683 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
2685 /* Write previous page(s) */
2686 #ifdef MDB_USE_PWRITEV
2687 wres = pwritev(env->me_fd, iov, n, wpos);
2690 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
2692 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
2694 DPRINTF(("lseek: %s", strerror(rc)));
2697 wres = writev(env->me_fd, iov, n);
2700 if (wres != wsize) {
2703 DPRINTF(("Write error: %s", strerror(rc)));
2705 rc = EIO; /* TODO: Use which error code? */
2706 DPUTS("short write, filesystem full?");
2717 DPRINTF(("committing page %"Z"u", pgno));
2718 next_pos = pos + size;
2719 iov[n].iov_len = size;
2720 iov[n].iov_base = (char *)dp;
2726 for (i = keep; ++i <= pagecount; ) {
2728 /* This is a page we skipped above */
2731 dl[j].mid = dp->mp_pgno;
2734 mdb_dpage_free(env, dp);
2742 mdb_txn_commit(MDB_txn *txn)
2748 assert(txn != NULL);
2749 assert(txn->mt_env != NULL);
2751 if (txn->mt_child) {
2752 rc = mdb_txn_commit(txn->mt_child);
2753 txn->mt_child = NULL;
2760 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2761 mdb_dbis_update(txn, 1);
2762 txn->mt_numdbs = 2; /* so txn_abort() doesn't close any new handles */
2767 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
2768 DPUTS("error flag is set, can't commit");
2770 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
2775 if (txn->mt_parent) {
2776 MDB_txn *parent = txn->mt_parent;
2780 /* Append our free list to parent's */
2781 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
2784 mdb_midl_free(txn->mt_free_pgs);
2786 parent->mt_next_pgno = txn->mt_next_pgno;
2787 parent->mt_flags = txn->mt_flags;
2789 /* Merge our cursors into parent's and close them */
2790 mdb_cursors_close(txn, 1);
2792 /* Update parent's DB table. */
2793 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2794 parent->mt_numdbs = txn->mt_numdbs;
2795 parent->mt_dbflags[0] = txn->mt_dbflags[0];
2796 parent->mt_dbflags[1] = txn->mt_dbflags[1];
2797 for (i=2; i<txn->mt_numdbs; i++) {
2798 /* preserve parent's DB_NEW status */
2799 x = parent->mt_dbflags[i] & DB_NEW;
2800 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
2803 dst = parent->mt_u.dirty_list;
2804 src = txn->mt_u.dirty_list;
2805 /* Remove anything in our dirty list from parent's spill list */
2806 if (parent->mt_spill_pgs) {
2807 x = parent->mt_spill_pgs[0];
2809 /* zero out our dirty pages in parent spill list */
2810 for (i=1; i<=src[0].mid; i++) {
2811 if (src[i].mid < parent->mt_spill_pgs[x])
2813 if (src[i].mid > parent->mt_spill_pgs[x]) {
2819 parent->mt_spill_pgs[x] = 0;
2822 /* OK, we had a few hits, squash zeros from the spill list */
2823 if (len < parent->mt_spill_pgs[0]) {
2825 for (y=1; y<=parent->mt_spill_pgs[0]; y++) {
2826 if (parent->mt_spill_pgs[y]) {
2828 parent->mt_spill_pgs[x] = parent->mt_spill_pgs[y];
2833 parent->mt_spill_pgs[0] = len;
2836 /* Find len = length of merging our dirty list with parent's */
2838 dst[0].mid = 0; /* simplify loops */
2839 if (parent->mt_parent) {
2840 len = x + src[0].mid;
2841 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
2842 for (i = x; y && i; y--) {
2843 pgno_t yp = src[y].mid;
2844 while (yp < dst[i].mid)
2846 if (yp == dst[i].mid) {
2851 } else { /* Simplify the above for single-ancestor case */
2852 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
2854 /* Merge our dirty list with parent's */
2856 for (i = len; y; dst[i--] = src[y--]) {
2857 pgno_t yp = src[y].mid;
2858 while (yp < dst[x].mid)
2859 dst[i--] = dst[x--];
2860 if (yp == dst[x].mid)
2861 free(dst[x--].mptr);
2865 free(txn->mt_u.dirty_list);
2866 parent->mt_dirty_room = txn->mt_dirty_room;
2867 if (txn->mt_spill_pgs) {
2868 if (parent->mt_spill_pgs) {
2869 mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
2870 mdb_midl_free(txn->mt_spill_pgs);
2871 mdb_midl_sort(parent->mt_spill_pgs);
2873 parent->mt_spill_pgs = txn->mt_spill_pgs;
2877 parent->mt_child = NULL;
2878 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
2883 if (txn != env->me_txn) {
2884 DPUTS("attempt to commit unknown transaction");
2889 mdb_cursors_close(txn, 0);
2891 if (!txn->mt_u.dirty_list[0].mid &&
2892 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
2895 DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
2896 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
2898 /* Update DB root pointers */
2899 if (txn->mt_numdbs > 2) {
2903 data.mv_size = sizeof(MDB_db);
2905 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
2906 for (i = 2; i < txn->mt_numdbs; i++) {
2907 if (txn->mt_dbflags[i] & DB_DIRTY) {
2908 data.mv_data = &txn->mt_dbs[i];
2909 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
2916 rc = mdb_freelist_save(txn);
2920 mdb_midl_free(env->me_pghead);
2921 env->me_pghead = NULL;
2922 if (mdb_midl_shrink(&txn->mt_free_pgs))
2923 env->me_free_pgs = txn->mt_free_pgs;
2929 if ((rc = mdb_page_flush(txn, 0)) ||
2930 (rc = mdb_env_sync(env, 0)) ||
2931 (rc = mdb_env_write_meta(txn)))
2937 mdb_dbis_update(txn, 1);
2939 UNLOCK_MUTEX_W(env);
2949 /** Read the environment parameters of a DB environment before
2950 * mapping it into memory.
2951 * @param[in] env the environment handle
2952 * @param[out] meta address of where to store the meta information
2953 * @return 0 on success, non-zero on failure.
2956 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
2963 /* We don't know the page size yet, so use a minimum value.
2964 * Read both meta pages so we can use the latest one.
2967 for (i=off=0; i<2; i++, off = meta->mm_psize) {
2971 memset(&ov, 0, sizeof(ov));
2973 rc = ReadFile(env->me_fd,&pbuf,MDB_PAGESIZE,&len,&ov) ? (int)len : -1;
2974 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
2977 rc = pread(env->me_fd, &pbuf, MDB_PAGESIZE, off);
2979 if (rc != MDB_PAGESIZE) {
2980 if (rc == 0 && off == 0)
2982 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
2983 DPRINTF(("read: %s", mdb_strerror(rc)));
2987 p = (MDB_page *)&pbuf;
2989 if (!F_ISSET(p->mp_flags, P_META)) {
2990 DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
2995 if (m->mm_magic != MDB_MAGIC) {
2996 DPUTS("meta has invalid magic");
3000 if (m->mm_version != MDB_DATA_VERSION) {
3001 DPRINTF(("database is version %u, expected version %u",
3002 m->mm_version, MDB_DATA_VERSION));
3003 return MDB_VERSION_MISMATCH;
3006 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3012 /** Write the environment parameters of a freshly created DB environment.
3013 * @param[in] env the environment handle
3014 * @param[out] meta address of where to store the meta information
3015 * @return 0 on success, non-zero on failure.
3018 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3026 memset(&ov, 0, sizeof(ov));
3027 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3029 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3032 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3033 len = pwrite(fd, ptr, size, pos); \
3034 rc = (len >= 0); } while(0)
3037 DPUTS("writing new meta page");
3039 GET_PAGESIZE(psize);
3041 meta->mm_magic = MDB_MAGIC;
3042 meta->mm_version = MDB_DATA_VERSION;
3043 meta->mm_mapsize = env->me_mapsize;
3044 meta->mm_psize = psize;
3045 meta->mm_last_pg = 1;
3046 meta->mm_flags = env->me_flags & 0xffff;
3047 meta->mm_flags |= MDB_INTEGERKEY;
3048 meta->mm_dbs[0].md_root = P_INVALID;
3049 meta->mm_dbs[1].md_root = P_INVALID;
3051 p = calloc(2, psize);
3053 p->mp_flags = P_META;
3054 *(MDB_meta *)METADATA(p) = *meta;
3056 q = (MDB_page *)((char *)p + psize);
3058 q->mp_flags = P_META;
3059 *(MDB_meta *)METADATA(q) = *meta;
3061 DO_PWRITE(rc, env->me_fd, p, psize * 2, len, 0);
3064 else if ((unsigned) len == psize * 2)
3072 /** Update the environment info to commit a transaction.
3073 * @param[in] txn the transaction that's being committed
3074 * @return 0 on success, non-zero on failure.
3077 mdb_env_write_meta(MDB_txn *txn)
3080 MDB_meta meta, metab, *mp;
3082 int rc, len, toggle;
3091 assert(txn != NULL);
3092 assert(txn->mt_env != NULL);
3094 toggle = !txn->mt_toggle;
3095 DPRINTF(("writing meta page %d for root page %"Z"u",
3096 toggle, txn->mt_dbs[MAIN_DBI].md_root));
3099 mp = env->me_metas[toggle];
3101 if (env->me_flags & MDB_WRITEMAP) {
3102 /* Persist any increases of mapsize config */
3103 if (env->me_mapsize > mp->mm_mapsize)
3104 mp->mm_mapsize = env->me_mapsize;
3105 mp->mm_dbs[0] = txn->mt_dbs[0];
3106 mp->mm_dbs[1] = txn->mt_dbs[1];
3107 mp->mm_last_pg = txn->mt_next_pgno - 1;
3108 mp->mm_txnid = txn->mt_txnid;
3109 if (!(env->me_flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3110 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3113 ptr += env->me_psize;
3114 if (MDB_MSYNC(ptr, env->me_psize, rc)) {
3121 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
3122 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
3124 ptr = (char *)&meta;
3125 if (env->me_mapsize > mp->mm_mapsize) {
3126 /* Persist any increases of mapsize config */
3127 meta.mm_mapsize = env->me_mapsize;
3128 off = offsetof(MDB_meta, mm_mapsize);
3130 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
3132 len = sizeof(MDB_meta) - off;
3135 meta.mm_dbs[0] = txn->mt_dbs[0];
3136 meta.mm_dbs[1] = txn->mt_dbs[1];
3137 meta.mm_last_pg = txn->mt_next_pgno - 1;
3138 meta.mm_txnid = txn->mt_txnid;
3141 off += env->me_psize;
3144 /* Write to the SYNC fd */
3145 mfd = env->me_flags & (MDB_NOSYNC|MDB_NOMETASYNC) ?
3146 env->me_fd : env->me_mfd;
3149 memset(&ov, 0, sizeof(ov));
3151 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3155 rc = pwrite(mfd, ptr, len, off);
3158 rc = rc < 0 ? ErrCode() : EIO;
3159 DPUTS("write failed, disk error?");
3160 /* On a failure, the pagecache still contains the new data.
3161 * Write some old data back, to prevent it from being used.
3162 * Use the non-SYNC fd; we know it will fail anyway.
3164 meta.mm_last_pg = metab.mm_last_pg;
3165 meta.mm_txnid = metab.mm_txnid;
3167 memset(&ov, 0, sizeof(ov));
3169 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3171 r2 = pwrite(env->me_fd, ptr, len, off);
3172 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
3175 env->me_flags |= MDB_FATAL_ERROR;
3179 /* Memory ordering issues are irrelevant; since the entire writer
3180 * is wrapped by wmutex, all of these changes will become visible
3181 * after the wmutex is unlocked. Since the DB is multi-version,
3182 * readers will get consistent data regardless of how fresh or
3183 * how stale their view of these values is.
3185 env->me_txns->mti_txnid = txn->mt_txnid;
3190 /** Check both meta pages to see which one is newer.
3191 * @param[in] env the environment handle
3192 * @return meta toggle (0 or 1).
3195 mdb_env_pick_meta(const MDB_env *env)
3197 return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
3201 mdb_env_create(MDB_env **env)
3205 e = calloc(1, sizeof(MDB_env));
3209 e->me_maxreaders = DEFAULT_READERS;
3210 e->me_maxdbs = e->me_numdbs = 2;
3211 e->me_fd = INVALID_HANDLE_VALUE;
3212 e->me_lfd = INVALID_HANDLE_VALUE;
3213 e->me_mfd = INVALID_HANDLE_VALUE;
3214 #ifdef MDB_USE_POSIX_SEM
3215 e->me_rmutex = SEM_FAILED;
3216 e->me_wmutex = SEM_FAILED;
3218 e->me_pid = getpid();
3219 VGMEMP_CREATE(e,0,0);
3225 mdb_env_set_mapsize(MDB_env *env, size_t size)
3229 env->me_mapsize = size;
3231 env->me_maxpg = env->me_mapsize / env->me_psize;
3236 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
3240 env->me_maxdbs = dbs + 2; /* Named databases + main and free DB */
3245 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
3247 if (env->me_map || readers < 1)
3249 env->me_maxreaders = readers;
3254 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
3256 if (!env || !readers)
3258 *readers = env->me_maxreaders;
3262 /** Further setup required for opening an MDB environment
3265 mdb_env_open2(MDB_env *env)
3267 unsigned int flags = env->me_flags;
3275 memset(&meta, 0, sizeof(meta));
3277 if ((i = mdb_env_read_header(env, &meta)) != 0) {
3280 DPUTS("new mdbenv");
3284 /* Was a mapsize configured? */
3285 if (!env->me_mapsize) {
3286 /* If this is a new environment, take the default,
3287 * else use the size recorded in the existing env.
3289 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
3290 } else if (env->me_mapsize < meta.mm_mapsize) {
3291 /* If the configured size is smaller, make sure it's
3292 * still big enough. Silently round up to minimum if not.
3294 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
3295 if (env->me_mapsize < minsize)
3296 env->me_mapsize = minsize;
3303 LONG sizelo, sizehi;
3304 sizelo = env->me_mapsize & 0xffffffff;
3305 sizehi = env->me_mapsize >> 16 >> 16; /* only needed on Win64 */
3307 /* See if we should use QueryLimited */
3309 if ((rc & 0xff) > 5)
3310 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
3312 env->me_pidquery = PROCESS_QUERY_INFORMATION;
3314 /* Windows won't create mappings for zero length files.
3315 * Just allocate the maxsize right now.
3318 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3319 || !SetEndOfFile(env->me_fd)
3320 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3323 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3324 PAGE_READWRITE : PAGE_READONLY,
3325 sizehi, sizelo, NULL);
3328 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3329 FILE_MAP_WRITE : FILE_MAP_READ,
3330 0, 0, env->me_mapsize, meta.mm_address);
3331 rc = env->me_map ? 0 : ErrCode();
3339 if (flags & MDB_WRITEMAP) {
3341 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3344 env->me_map = mmap(meta.mm_address, env->me_mapsize, prot, i,
3346 if (env->me_map == MAP_FAILED) {
3350 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3352 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3354 #ifdef POSIX_MADV_RANDOM
3355 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3356 #endif /* POSIX_MADV_RANDOM */
3357 #endif /* MADV_RANDOM */
3361 if (flags & MDB_FIXEDMAP)
3362 meta.mm_address = env->me_map;
3363 i = mdb_env_init_meta(env, &meta);
3364 if (i != MDB_SUCCESS) {
3367 } else if (meta.mm_address && env->me_map != meta.mm_address) {
3368 /* Can happen because the address argument to mmap() is just a
3369 * hint. mmap() can pick another, e.g. if the range is in use.
3370 * The MAP_FIXED flag would prevent that, but then mmap could
3371 * instead unmap existing pages to make room for the new map.
3373 return EBUSY; /* TODO: Make a new MDB_* error code? */
3375 env->me_psize = meta.mm_psize;
3376 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
3377 env->me_nodemax = (env->me_psize - PAGEHDRSZ) / MDB_MINKEYS;
3379 env->me_maxpg = env->me_mapsize / env->me_psize;
3381 p = (MDB_page *)env->me_map;
3382 env->me_metas[0] = METADATA(p);
3383 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
3387 int toggle = mdb_env_pick_meta(env);
3388 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
3390 DPRINTF(("opened database version %u, pagesize %u",
3391 env->me_metas[0]->mm_version, env->me_psize));
3392 DPRINTF(("using meta page %d", toggle));
3393 DPRINTF(("depth: %u", db->md_depth));
3394 DPRINTF(("entries: %"Z"u", db->md_entries));
3395 DPRINTF(("branch pages: %"Z"u", db->md_branch_pages));
3396 DPRINTF(("leaf pages: %"Z"u", db->md_leaf_pages));
3397 DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
3398 DPRINTF(("root: %"Z"u", db->md_root));
3406 /** Release a reader thread's slot in the reader lock table.
3407 * This function is called automatically when a thread exits.
3408 * @param[in] ptr This points to the slot in the reader lock table.
3411 mdb_env_reader_dest(void *ptr)
3413 MDB_reader *reader = ptr;
3419 /** Junk for arranging thread-specific callbacks on Windows. This is
3420 * necessarily platform and compiler-specific. Windows supports up
3421 * to 1088 keys. Let's assume nobody opens more than 64 environments
3422 * in a single process, for now. They can override this if needed.
3424 #ifndef MAX_TLS_KEYS
3425 #define MAX_TLS_KEYS 64
3427 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
3428 static int mdb_tls_nkeys;
3430 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
3434 case DLL_PROCESS_ATTACH: break;
3435 case DLL_THREAD_ATTACH: break;
3436 case DLL_THREAD_DETACH:
3437 for (i=0; i<mdb_tls_nkeys; i++) {
3438 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
3439 mdb_env_reader_dest(r);
3442 case DLL_PROCESS_DETACH: break;
3447 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3449 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3453 /* Force some symbol references.
3454 * _tls_used forces the linker to create the TLS directory if not already done
3455 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
3457 #pragma comment(linker, "/INCLUDE:_tls_used")
3458 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
3459 #pragma const_seg(".CRT$XLB")
3460 extern const PIMAGE_TLS_CALLBACK mdb_tls_callback;
3461 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3464 #pragma comment(linker, "/INCLUDE:__tls_used")
3465 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
3466 #pragma data_seg(".CRT$XLB")
3467 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3469 #endif /* WIN 32/64 */
3470 #endif /* !__GNUC__ */
3473 /** Downgrade the exclusive lock on the region back to shared */
3475 mdb_env_share_locks(MDB_env *env, int *excl)
3477 int rc = 0, toggle = mdb_env_pick_meta(env);
3479 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
3484 /* First acquire a shared lock. The Unlock will
3485 * then release the existing exclusive lock.
3487 memset(&ov, 0, sizeof(ov));
3488 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3491 UnlockFile(env->me_lfd, 0, 0, 1, 0);
3497 struct flock lock_info;
3498 /* The shared lock replaces the existing lock */
3499 memset((void *)&lock_info, 0, sizeof(lock_info));
3500 lock_info.l_type = F_RDLCK;
3501 lock_info.l_whence = SEEK_SET;
3502 lock_info.l_start = 0;
3503 lock_info.l_len = 1;
3504 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3505 (rc = ErrCode()) == EINTR) ;
3506 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
3513 /** Try to get exlusive lock, otherwise shared.
3514 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
3517 mdb_env_excl_lock(MDB_env *env, int *excl)
3521 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
3525 memset(&ov, 0, sizeof(ov));
3526 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3533 struct flock lock_info;
3534 memset((void *)&lock_info, 0, sizeof(lock_info));
3535 lock_info.l_type = F_WRLCK;
3536 lock_info.l_whence = SEEK_SET;
3537 lock_info.l_start = 0;
3538 lock_info.l_len = 1;
3539 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3540 (rc = ErrCode()) == EINTR) ;
3544 # ifdef MDB_USE_POSIX_SEM
3545 if (*excl < 0) /* always true when !MDB_USE_POSIX_SEM */
3548 lock_info.l_type = F_RDLCK;
3549 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
3550 (rc = ErrCode()) == EINTR) ;
3558 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
3560 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
3562 * @(#) $Revision: 5.1 $
3563 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
3564 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
3566 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
3570 * Please do not copyright this code. This code is in the public domain.
3572 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
3573 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
3574 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
3575 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
3576 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
3577 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
3578 * PERFORMANCE OF THIS SOFTWARE.
3581 * chongo <Landon Curt Noll> /\oo/\
3582 * http://www.isthe.com/chongo/
3584 * Share and Enjoy! :-)
3587 typedef unsigned long long mdb_hash_t;
3588 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
3590 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
3591 * @param[in] val value to hash
3592 * @param[in] hval initial value for hash
3593 * @return 64 bit hash
3595 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
3596 * hval arg on the first call.
3599 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
3601 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
3602 unsigned char *end = s + val->mv_size;
3604 * FNV-1a hash each octet of the string
3607 /* xor the bottom with the current octet */
3608 hval ^= (mdb_hash_t)*s++;
3610 /* multiply by the 64 bit FNV magic prime mod 2^64 */
3611 hval += (hval << 1) + (hval << 4) + (hval << 5) +
3612 (hval << 7) + (hval << 8) + (hval << 40);
3614 /* return our new hash value */
3618 /** Hash the string and output the encoded hash.
3619 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
3620 * very short name limits. We don't care about the encoding being reversible,
3621 * we just want to preserve as many bits of the input as possible in a
3622 * small printable string.
3623 * @param[in] str string to hash
3624 * @param[out] encbuf an array of 11 chars to hold the hash
3626 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
3629 mdb_pack85(unsigned long l, char *out)
3633 for (i=0; i<5; i++) {
3634 *out++ = mdb_a85[l % 85];
3640 mdb_hash_enc(MDB_val *val, char *encbuf)
3642 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
3644 mdb_pack85(h, encbuf);
3645 mdb_pack85(h>>32, encbuf+5);
3650 /** Open and/or initialize the lock region for the environment.
3651 * @param[in] env The MDB environment.
3652 * @param[in] lpath The pathname of the file used for the lock region.
3653 * @param[in] mode The Unix permissions for the file, if we create it.
3654 * @param[out] excl Resulting file lock type: -1 none, 0 shared, 1 exclusive
3655 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
3656 * @return 0 on success, non-zero on failure.
3659 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
3662 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
3664 # define MDB_ERRCODE_ROFS EROFS
3665 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
3666 # define MDB_CLOEXEC O_CLOEXEC
3669 # define MDB_CLOEXEC 0
3676 env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
3677 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
3678 FILE_ATTRIBUTE_NORMAL, NULL);
3680 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
3682 if (env->me_lfd == INVALID_HANDLE_VALUE) {
3684 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
3689 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
3690 /* Lose record locks when exec*() */
3691 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
3692 fcntl(env->me_lfd, F_SETFD, fdflags);
3695 if (!(env->me_flags & MDB_NOTLS)) {
3696 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
3699 env->me_flags |= MDB_ENV_TXKEY;
3701 /* Windows TLS callbacks need help finding their TLS info. */
3702 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
3706 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
3710 /* Try to get exclusive lock. If we succeed, then
3711 * nobody is using the lock region and we should initialize it.
3713 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
3716 size = GetFileSize(env->me_lfd, NULL);
3718 size = lseek(env->me_lfd, 0, SEEK_END);
3719 if (size == -1) goto fail_errno;
3721 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
3722 if (size < rsize && *excl > 0) {
3724 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != rsize
3725 || !SetEndOfFile(env->me_lfd))
3728 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
3732 size = rsize - sizeof(MDB_txninfo);
3733 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
3738 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
3740 if (!mh) goto fail_errno;
3741 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
3743 if (!env->me_txns) goto fail_errno;
3745 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
3747 if (m == MAP_FAILED) goto fail_errno;
3753 BY_HANDLE_FILE_INFORMATION stbuf;
3762 if (!mdb_sec_inited) {
3763 InitializeSecurityDescriptor(&mdb_null_sd,
3764 SECURITY_DESCRIPTOR_REVISION);
3765 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
3766 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
3767 mdb_all_sa.bInheritHandle = FALSE;
3768 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
3771 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
3772 idbuf.volume = stbuf.dwVolumeSerialNumber;
3773 idbuf.nhigh = stbuf.nFileIndexHigh;
3774 idbuf.nlow = stbuf.nFileIndexLow;
3775 val.mv_data = &idbuf;
3776 val.mv_size = sizeof(idbuf);
3777 mdb_hash_enc(&val, encbuf);
3778 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
3779 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
3780 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
3781 if (!env->me_rmutex) goto fail_errno;
3782 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
3783 if (!env->me_wmutex) goto fail_errno;
3784 #elif defined(MDB_USE_POSIX_SEM)
3793 #if defined(__NetBSD__)
3794 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
3796 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
3797 idbuf.dev = stbuf.st_dev;
3798 idbuf.ino = stbuf.st_ino;
3799 val.mv_data = &idbuf;
3800 val.mv_size = sizeof(idbuf);
3801 mdb_hash_enc(&val, encbuf);
3802 #ifdef MDB_SHORT_SEMNAMES
3803 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
3805 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
3806 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
3807 /* Clean up after a previous run, if needed: Try to
3808 * remove both semaphores before doing anything else.
3810 sem_unlink(env->me_txns->mti_rmname);
3811 sem_unlink(env->me_txns->mti_wmname);
3812 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
3813 O_CREAT|O_EXCL, mode, 1);
3814 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3815 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
3816 O_CREAT|O_EXCL, mode, 1);
3817 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3818 #else /* MDB_USE_POSIX_SEM */
3819 pthread_mutexattr_t mattr;
3821 if ((rc = pthread_mutexattr_init(&mattr))
3822 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
3823 || (rc = pthread_mutex_init(&env->me_txns->mti_mutex, &mattr))
3824 || (rc = pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr)))
3826 pthread_mutexattr_destroy(&mattr);
3827 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
3829 env->me_txns->mti_magic = MDB_MAGIC;
3830 env->me_txns->mti_format = MDB_LOCK_FORMAT;
3831 env->me_txns->mti_txnid = 0;
3832 env->me_txns->mti_numreaders = 0;
3835 if (env->me_txns->mti_magic != MDB_MAGIC) {
3836 DPUTS("lock region has invalid magic");
3840 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
3841 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
3842 env->me_txns->mti_format, MDB_LOCK_FORMAT));
3843 rc = MDB_VERSION_MISMATCH;
3847 if (rc && rc != EACCES && rc != EAGAIN) {
3851 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
3852 if (!env->me_rmutex) goto fail_errno;
3853 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
3854 if (!env->me_wmutex) goto fail_errno;
3855 #elif defined(MDB_USE_POSIX_SEM)
3856 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
3857 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3858 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
3859 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3870 /** The name of the lock file in the DB environment */
3871 #define LOCKNAME "/lock.mdb"
3872 /** The name of the data file in the DB environment */
3873 #define DATANAME "/data.mdb"
3874 /** The suffix of the lock file when no subdir is used */
3875 #define LOCKSUFF "-lock"
3876 /** Only a subset of the @ref mdb_env flags can be changed
3877 * at runtime. Changing other flags requires closing the
3878 * environment and re-opening it with the new flags.
3880 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC)
3881 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY|MDB_WRITEMAP|MDB_NOTLS)
3884 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
3886 int oflags, rc, len, excl = -1;
3887 char *lpath, *dpath;
3889 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
3893 if (flags & MDB_NOSUBDIR) {
3894 rc = len + sizeof(LOCKSUFF) + len + 1;
3896 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
3901 if (flags & MDB_NOSUBDIR) {
3902 dpath = lpath + len + sizeof(LOCKSUFF);
3903 sprintf(lpath, "%s" LOCKSUFF, path);
3904 strcpy(dpath, path);
3906 dpath = lpath + len + sizeof(LOCKNAME);
3907 sprintf(lpath, "%s" LOCKNAME, path);
3908 sprintf(dpath, "%s" DATANAME, path);
3912 flags |= env->me_flags;
3913 if (flags & MDB_RDONLY) {
3914 /* silently ignore WRITEMAP when we're only getting read access */
3915 flags &= ~MDB_WRITEMAP;
3917 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
3918 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
3921 env->me_flags = flags |= MDB_ENV_ACTIVE;
3925 env->me_path = strdup(path);
3926 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
3927 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
3928 if (!(env->me_dbxs && env->me_path && env->me_dbflags)) {
3933 /* For RDONLY, get lockfile after we know datafile exists */
3934 if (!F_ISSET(flags, MDB_RDONLY)) {
3935 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
3941 if (F_ISSET(flags, MDB_RDONLY)) {
3942 oflags = GENERIC_READ;
3943 len = OPEN_EXISTING;
3945 oflags = GENERIC_READ|GENERIC_WRITE;
3948 mode = FILE_ATTRIBUTE_NORMAL;
3949 env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
3950 NULL, len, mode, NULL);
3952 if (F_ISSET(flags, MDB_RDONLY))
3955 oflags = O_RDWR | O_CREAT;
3957 env->me_fd = open(dpath, oflags, mode);
3959 if (env->me_fd == INVALID_HANDLE_VALUE) {
3964 if (F_ISSET(flags, MDB_RDONLY)) {
3965 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
3970 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
3971 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
3972 env->me_mfd = env->me_fd;
3974 /* Synchronous fd for meta writes. Needed even with
3975 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
3978 len = OPEN_EXISTING;
3979 env->me_mfd = CreateFile(dpath, oflags,
3980 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
3981 mode | FILE_FLAG_WRITE_THROUGH, NULL);
3984 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
3986 if (env->me_mfd == INVALID_HANDLE_VALUE) {
3991 DPRINTF(("opened dbenv %p", (void *) env));
3993 rc = mdb_env_share_locks(env, &excl);
3999 mdb_env_close0(env, excl);
4005 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
4007 mdb_env_close0(MDB_env *env, int excl)
4011 if (!(env->me_flags & MDB_ENV_ACTIVE))
4014 /* Doing this here since me_dbxs may not exist during mdb_env_close */
4015 for (i = env->me_maxdbs; --i > MAIN_DBI; )
4016 free(env->me_dbxs[i].md_name.mv_data);
4018 free(env->me_dbflags);
4021 free(env->me_dirty_list);
4022 mdb_midl_free(env->me_free_pgs);
4024 if (env->me_flags & MDB_ENV_TXKEY) {
4025 pthread_key_delete(env->me_txkey);
4027 /* Delete our key from the global list */
4028 for (i=0; i<mdb_tls_nkeys; i++)
4029 if (mdb_tls_keys[i] == env->me_txkey) {
4030 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
4038 munmap(env->me_map, env->me_mapsize);
4040 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
4041 (void) close(env->me_mfd);
4042 if (env->me_fd != INVALID_HANDLE_VALUE)
4043 (void) close(env->me_fd);
4045 pid_t pid = env->me_pid;
4046 /* Clearing readers is done in this function because
4047 * me_txkey with its destructor must be disabled first.
4049 for (i = env->me_numreaders; --i >= 0; )
4050 if (env->me_txns->mti_readers[i].mr_pid == pid)
4051 env->me_txns->mti_readers[i].mr_pid = 0;
4053 if (env->me_rmutex) {
4054 CloseHandle(env->me_rmutex);
4055 if (env->me_wmutex) CloseHandle(env->me_wmutex);
4057 /* Windows automatically destroys the mutexes when
4058 * the last handle closes.
4060 #elif defined(MDB_USE_POSIX_SEM)
4061 if (env->me_rmutex != SEM_FAILED) {
4062 sem_close(env->me_rmutex);
4063 if (env->me_wmutex != SEM_FAILED)
4064 sem_close(env->me_wmutex);
4065 /* If we have the filelock: If we are the
4066 * only remaining user, clean up semaphores.
4069 mdb_env_excl_lock(env, &excl);
4071 sem_unlink(env->me_txns->mti_rmname);
4072 sem_unlink(env->me_txns->mti_wmname);
4076 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
4078 if (env->me_lfd != INVALID_HANDLE_VALUE) {
4081 /* Unlock the lockfile. Windows would have unlocked it
4082 * after closing anyway, but not necessarily at once.
4084 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4087 (void) close(env->me_lfd);
4090 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
4094 mdb_env_copyfd(MDB_env *env, HANDLE fd)
4096 MDB_txn *txn = NULL;
4102 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
4106 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
4109 /* Do the lock/unlock of the reader mutex before starting the
4110 * write txn. Otherwise other read txns could block writers.
4112 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
4117 /* We must start the actual read txn after blocking writers */
4118 mdb_txn_reset0(txn, "reset-stage1");
4120 /* Temporarily block writers until we snapshot the meta pages */
4123 rc = mdb_txn_renew0(txn);
4125 UNLOCK_MUTEX_W(env);
4130 wsize = env->me_psize * 2;
4134 DO_WRITE(rc, fd, ptr, w2, len);
4138 } else if (len > 0) {
4144 /* Non-blocking or async handles are not supported */
4150 UNLOCK_MUTEX_W(env);
4155 wsize = txn->mt_next_pgno * env->me_psize - wsize;
4157 if (wsize > MAX_WRITE)
4161 DO_WRITE(rc, fd, ptr, w2, len);
4165 } else if (len > 0) {
4182 mdb_env_copy(MDB_env *env, const char *path)
4186 HANDLE newfd = INVALID_HANDLE_VALUE;
4188 if (env->me_flags & MDB_NOSUBDIR) {
4189 lpath = (char *)path;
4192 len += sizeof(DATANAME);
4193 lpath = malloc(len);
4196 sprintf(lpath, "%s" DATANAME, path);
4199 /* The destination path must exist, but the destination file must not.
4200 * We don't want the OS to cache the writes, since the source data is
4201 * already in the OS cache.
4204 newfd = CreateFile(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
4205 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
4207 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL
4213 if (newfd == INVALID_HANDLE_VALUE) {
4218 #ifdef F_NOCACHE /* __APPLE__ */
4219 rc = fcntl(newfd, F_NOCACHE, 1);
4226 rc = mdb_env_copyfd(env, newfd);
4229 if (!(env->me_flags & MDB_NOSUBDIR))
4231 if (newfd != INVALID_HANDLE_VALUE)
4232 if (close(newfd) < 0 && rc == MDB_SUCCESS)
4239 mdb_env_close(MDB_env *env)
4246 VGMEMP_DESTROY(env);
4247 while ((dp = env->me_dpages) != NULL) {
4248 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
4249 env->me_dpages = dp->mp_next;
4253 mdb_env_close0(env, 0);
4257 /** Compare two items pointing at aligned size_t's */
4259 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
4261 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
4262 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
4265 /** Compare two items pointing at aligned int's */
4267 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
4269 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
4270 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
4273 /** Compare two items pointing at ints of unknown alignment.
4274 * Nodes and keys are guaranteed to be 2-byte aligned.
4277 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
4279 #if BYTE_ORDER == LITTLE_ENDIAN
4280 unsigned short *u, *c;
4283 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4284 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
4287 } while(!x && u > (unsigned short *)a->mv_data);
4290 return memcmp(a->mv_data, b->mv_data, a->mv_size);
4294 /** Compare two items lexically */
4296 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
4303 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4309 diff = memcmp(a->mv_data, b->mv_data, len);
4310 return diff ? diff : len_diff<0 ? -1 : len_diff;
4313 /** Compare two items in reverse byte order */
4315 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
4317 const unsigned char *p1, *p2, *p1_lim;
4321 p1_lim = (const unsigned char *)a->mv_data;
4322 p1 = (const unsigned char *)a->mv_data + a->mv_size;
4323 p2 = (const unsigned char *)b->mv_data + b->mv_size;
4325 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4331 while (p1 > p1_lim) {
4332 diff = *--p1 - *--p2;
4336 return len_diff<0 ? -1 : len_diff;
4339 /** Search for key within a page, using binary search.
4340 * Returns the smallest entry larger or equal to the key.
4341 * If exactp is non-null, stores whether the found entry was an exact match
4342 * in *exactp (1 or 0).
4343 * Updates the cursor index with the index of the found entry.
4344 * If no entry larger or equal to the key is found, returns NULL.
4347 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
4349 unsigned int i = 0, nkeys;
4352 MDB_page *mp = mc->mc_pg[mc->mc_top];
4353 MDB_node *node = NULL;
4358 nkeys = NUMKEYS(mp);
4363 COPY_PGNO(pgno, mp->mp_pgno);
4364 DPRINTF(("searching %u keys in %s %spage %"Z"u",
4365 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
4372 low = IS_LEAF(mp) ? 0 : 1;
4374 cmp = mc->mc_dbx->md_cmp;
4376 /* Branch pages have no data, so if using integer keys,
4377 * alignment is guaranteed. Use faster mdb_cmp_int.
4379 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
4380 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
4387 nodekey.mv_size = mc->mc_db->md_pad;
4388 node = NODEPTR(mp, 0); /* fake */
4389 while (low <= high) {
4390 i = (low + high) >> 1;
4391 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
4392 rc = cmp(key, &nodekey);
4393 DPRINTF(("found leaf index %u [%s], rc = %i",
4394 i, DKEY(&nodekey), rc));
4403 while (low <= high) {
4404 i = (low + high) >> 1;
4406 node = NODEPTR(mp, i);
4407 nodekey.mv_size = NODEKSZ(node);
4408 nodekey.mv_data = NODEKEY(node);
4410 rc = cmp(key, &nodekey);
4413 DPRINTF(("found leaf index %u [%s], rc = %i",
4414 i, DKEY(&nodekey), rc));
4416 DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
4417 i, DKEY(&nodekey), NODEPGNO(node), rc));
4428 if (rc > 0) { /* Found entry is less than the key. */
4429 i++; /* Skip to get the smallest entry larger than key. */
4431 node = NODEPTR(mp, i);
4434 *exactp = (rc == 0);
4435 /* store the key index */
4436 mc->mc_ki[mc->mc_top] = i;
4438 /* There is no entry larger or equal to the key. */
4441 /* nodeptr is fake for LEAF2 */
4447 mdb_cursor_adjust(MDB_cursor *mc, func)
4451 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4452 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
4459 /** Pop a page off the top of the cursor's stack. */
4461 mdb_cursor_pop(MDB_cursor *mc)
4465 MDB_page *top = mc->mc_pg[mc->mc_top];
4471 DPRINTF(("popped page %"Z"u off db %u cursor %p", top->mp_pgno,
4472 mc->mc_dbi, (void *) mc));
4476 /** Push a page onto the top of the cursor's stack. */
4478 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
4480 DPRINTF(("pushing page %"Z"u on db %u cursor %p", mp->mp_pgno,
4481 mc->mc_dbi, (void *) mc));
4483 if (mc->mc_snum >= CURSOR_STACK) {
4484 assert(mc->mc_snum < CURSOR_STACK);
4485 return MDB_CURSOR_FULL;
4488 mc->mc_top = mc->mc_snum++;
4489 mc->mc_pg[mc->mc_top] = mp;
4490 mc->mc_ki[mc->mc_top] = 0;
4495 /** Find the address of the page corresponding to a given page number.
4496 * @param[in] txn the transaction for this access.
4497 * @param[in] pgno the page number for the page to retrieve.
4498 * @param[out] ret address of a pointer where the page's address will be stored.
4499 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
4500 * @return 0 on success, non-zero on failure.
4503 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
4505 MDB_env *env = txn->mt_env;
4509 if (!((txn->mt_flags & MDB_TXN_RDONLY) | (env->me_flags & MDB_WRITEMAP))) {
4513 MDB_ID2L dl = tx2->mt_u.dirty_list;
4515 /* Spilled pages were dirtied in this txn and flushed
4516 * because the dirty list got full. Bring this page
4517 * back in from the map (but don't unspill it here,
4518 * leave that unless page_touch happens again).
4520 if (tx2->mt_spill_pgs) {
4521 x = mdb_midl_search(tx2->mt_spill_pgs, pgno);
4522 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pgno) {
4523 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
4528 unsigned x = mdb_mid2l_search(dl, pgno);
4529 if (x <= dl[0].mid && dl[x].mid == pgno) {
4535 } while ((tx2 = tx2->mt_parent) != NULL);
4538 if (pgno < txn->mt_next_pgno) {
4540 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
4542 DPRINTF(("page %"Z"u not found", pgno));
4544 return MDB_PAGE_NOTFOUND;
4554 /** Search for the page a given key should be in.
4555 * Pushes parent pages on the cursor stack. This function continues a
4556 * search on a cursor that has already been initialized. (Usually by
4557 * #mdb_page_search() but also by #mdb_node_move().)
4558 * @param[in,out] mc the cursor for this operation.
4559 * @param[in] key the key to search for. If NULL, search for the lowest
4560 * page. (This is used by #mdb_cursor_first().)
4561 * @param[in] modify If true, visited pages are updated with new page numbers.
4562 * @return 0 on success, non-zero on failure.
4565 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
4567 MDB_page *mp = mc->mc_pg[mc->mc_top];
4571 while (IS_BRANCH(mp)) {
4575 DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
4576 assert(NUMKEYS(mp) > 1);
4577 DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
4579 if (key == NULL) /* Initialize cursor to first page. */
4581 else if (key->mv_size > MDB_MAXKEYSIZE && key->mv_data == NULL) {
4582 /* cursor to last page */
4586 node = mdb_node_search(mc, key, &exact);
4588 i = NUMKEYS(mp) - 1;
4590 i = mc->mc_ki[mc->mc_top];
4599 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
4600 assert(i < NUMKEYS(mp));
4601 node = NODEPTR(mp, i);
4603 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4606 mc->mc_ki[mc->mc_top] = i;
4607 if ((rc = mdb_cursor_push(mc, mp)))
4611 if ((rc = mdb_page_touch(mc)) != 0)
4613 mp = mc->mc_pg[mc->mc_top];
4618 DPRINTF(("internal error, index points to a %02X page!?",
4620 return MDB_CORRUPTED;
4623 DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
4624 key ? DKEY(key) : NULL));
4625 mc->mc_flags |= C_INITIALIZED;
4626 mc->mc_flags &= ~C_EOF;
4631 /** Search for the lowest key under the current branch page.
4632 * This just bypasses a NUMKEYS check in the current page
4633 * before calling mdb_page_search_root(), because the callers
4634 * are all in situations where the current page is known to
4638 mdb_page_search_lowest(MDB_cursor *mc)
4640 MDB_page *mp = mc->mc_pg[mc->mc_top];
4641 MDB_node *node = NODEPTR(mp, 0);
4644 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4647 mc->mc_ki[mc->mc_top] = 0;
4648 if ((rc = mdb_cursor_push(mc, mp)))
4650 return mdb_page_search_root(mc, NULL, 0);
4653 /** Search for the page a given key should be in.
4654 * Pushes parent pages on the cursor stack. This function just sets up
4655 * the search; it finds the root page for \b mc's database and sets this
4656 * as the root of the cursor's stack. Then #mdb_page_search_root() is
4657 * called to complete the search.
4658 * @param[in,out] mc the cursor for this operation.
4659 * @param[in] key the key to search for. If NULL, search for the lowest
4660 * page. (This is used by #mdb_cursor_first().)
4661 * @param[in] flags If MDB_PS_MODIFY set, visited pages are updated with new page numbers.
4662 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
4663 * @return 0 on success, non-zero on failure.
4666 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
4671 /* Make sure the txn is still viable, then find the root from
4672 * the txn's db table.
4674 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
4675 DPUTS("transaction has failed, must abort");
4678 /* Make sure we're using an up-to-date root */
4679 if (mc->mc_dbi > MAIN_DBI) {
4680 if ((*mc->mc_dbflag & DB_STALE) ||
4681 ((flags & MDB_PS_MODIFY) && !(*mc->mc_dbflag & DB_DIRTY))) {
4683 unsigned char dbflag = 0;
4684 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
4685 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, flags & MDB_PS_MODIFY);
4688 if (*mc->mc_dbflag & DB_STALE) {
4692 MDB_node *leaf = mdb_node_search(&mc2,
4693 &mc->mc_dbx->md_name, &exact);
4695 return MDB_NOTFOUND;
4696 rc = mdb_node_read(mc->mc_txn, leaf, &data);
4699 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
4701 /* The txn may not know this DBI, or another process may
4702 * have dropped and recreated the DB with other flags.
4704 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
4705 return MDB_INCOMPATIBLE;
4706 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
4708 if (flags & MDB_PS_MODIFY)
4710 *mc->mc_dbflag &= ~DB_STALE;
4711 *mc->mc_dbflag |= dbflag;
4714 root = mc->mc_db->md_root;
4716 if (root == P_INVALID) { /* Tree is empty. */
4717 DPUTS("tree is empty");
4718 return MDB_NOTFOUND;
4723 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
4724 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0], NULL)) != 0)
4730 DPRINTF(("db %u root page %"Z"u has flags 0x%X",
4731 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags));
4733 if (flags & MDB_PS_MODIFY) {
4734 if ((rc = mdb_page_touch(mc)))
4738 if (flags & MDB_PS_ROOTONLY)
4741 return mdb_page_search_root(mc, key, flags);
4745 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
4747 MDB_txn *txn = mc->mc_txn;
4748 pgno_t pg = mp->mp_pgno;
4749 unsigned x = 0, ovpages = mp->mp_pages;
4750 MDB_env *env = txn->mt_env;
4751 MDB_IDL sl = txn->mt_spill_pgs;
4754 DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
4755 /* If the page is dirty or on the spill list we just acquired it,
4756 * so we should give it back to our current free list, if any.
4757 * Otherwise put it onto the list of pages we freed in this txn.
4759 * Won't create me_pghead: me_pglast must be inited along with it.
4760 * Unsupported in nested txns: They would need to hide the page
4761 * range in ancestor txns' dirty and spilled lists.
4763 if (env->me_pghead &&
4765 ((mp->mp_flags & P_DIRTY) ||
4766 (sl && (x = mdb_midl_search(sl, pg)) <= sl[0] && sl[x] == pg)))
4770 MDB_ID2 *dl, ix, iy;
4771 rc = mdb_midl_need(&env->me_pghead, ovpages);
4774 if (!(mp->mp_flags & P_DIRTY)) {
4775 /* This page is no longer spilled */
4776 for (; x < sl[0]; x++)
4781 /* Remove from dirty list */
4782 dl = txn->mt_u.dirty_list;
4784 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
4792 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
4793 txn->mt_flags |= MDB_TXN_ERROR;
4794 return MDB_CORRUPTED;
4797 if (!(env->me_flags & MDB_WRITEMAP))
4798 mdb_dpage_free(env, mp);
4800 /* Insert in me_pghead */
4801 mop = env->me_pghead;
4802 j = mop[0] + ovpages;
4803 for (i = mop[0]; i && mop[i] < pg; i--)
4809 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
4813 mc->mc_db->md_overflow_pages -= ovpages;
4817 /** Return the data associated with a given node.
4818 * @param[in] txn The transaction for this operation.
4819 * @param[in] leaf The node being read.
4820 * @param[out] data Updated to point to the node's data.
4821 * @return 0 on success, non-zero on failure.
4824 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
4826 MDB_page *omp; /* overflow page */
4830 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
4831 data->mv_size = NODEDSZ(leaf);
4832 data->mv_data = NODEDATA(leaf);
4836 /* Read overflow data.
4838 data->mv_size = NODEDSZ(leaf);
4839 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
4840 if ((rc = mdb_page_get(txn, pgno, &omp, NULL)) != 0) {
4841 DPRINTF(("read overflow page %"Z"u failed", pgno));
4844 data->mv_data = METADATA(omp);
4850 mdb_get(MDB_txn *txn, MDB_dbi dbi,
4851 MDB_val *key, MDB_val *data)
4860 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
4862 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
4865 if (txn->mt_flags & MDB_TXN_ERROR)
4868 if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
4869 return MDB_BAD_VALSIZE;
4872 mdb_cursor_init(&mc, txn, dbi, &mx);
4873 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
4876 /** Find a sibling for a page.
4877 * Replaces the page at the top of the cursor's stack with the
4878 * specified sibling, if one exists.
4879 * @param[in] mc The cursor for this operation.
4880 * @param[in] move_right Non-zero if the right sibling is requested,
4881 * otherwise the left sibling.
4882 * @return 0 on success, non-zero on failure.
4885 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
4891 if (mc->mc_snum < 2) {
4892 return MDB_NOTFOUND; /* root has no siblings */
4896 DPRINTF(("parent page is page %"Z"u, index %u",
4897 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
4899 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
4900 : (mc->mc_ki[mc->mc_top] == 0)) {
4901 DPRINTF(("no more keys left, moving to %s sibling",
4902 move_right ? "right" : "left"));
4903 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
4904 /* undo cursor_pop before returning */
4911 mc->mc_ki[mc->mc_top]++;
4913 mc->mc_ki[mc->mc_top]--;
4914 DPRINTF(("just moving to %s index key %u",
4915 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
4917 assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
4919 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4920 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL) != 0))
4923 mdb_cursor_push(mc, mp);
4925 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
4930 /** Move the cursor to the next data item. */
4932 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
4938 if (mc->mc_flags & C_EOF) {
4939 return MDB_NOTFOUND;
4942 assert(mc->mc_flags & C_INITIALIZED);
4944 mp = mc->mc_pg[mc->mc_top];
4946 if (mc->mc_db->md_flags & MDB_DUPSORT) {
4947 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4948 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4949 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
4950 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
4951 if (op != MDB_NEXT || rc != MDB_NOTFOUND)
4955 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
4956 if (op == MDB_NEXT_DUP)
4957 return MDB_NOTFOUND;
4961 DPRINTF(("cursor_next: top page is %"Z"u in cursor %p", mp->mp_pgno, (void *) mc));
4963 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
4964 DPUTS("=====> move to next sibling page");
4965 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
4966 mc->mc_flags |= C_EOF;
4969 mp = mc->mc_pg[mc->mc_top];
4970 DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
4972 mc->mc_ki[mc->mc_top]++;
4974 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
4975 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
4978 key->mv_size = mc->mc_db->md_pad;
4979 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
4983 assert(IS_LEAF(mp));
4984 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4986 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4987 mdb_xcursor_init1(mc, leaf);
4990 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4993 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4994 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4995 if (rc != MDB_SUCCESS)
5000 MDB_GET_KEY(leaf, key);
5004 /** Move the cursor to the previous data item. */
5006 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5012 assert(mc->mc_flags & C_INITIALIZED);
5014 mp = mc->mc_pg[mc->mc_top];
5016 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5017 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5018 if (op == MDB_PREV || op == MDB_PREV_DUP) {
5019 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5020 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
5021 if (op != MDB_PREV || rc != MDB_NOTFOUND)
5024 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5025 if (op == MDB_PREV_DUP)
5026 return MDB_NOTFOUND;
5031 DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p", mp->mp_pgno, (void *) mc));
5033 if (mc->mc_ki[mc->mc_top] == 0) {
5034 DPUTS("=====> move to prev sibling page");
5035 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
5038 mp = mc->mc_pg[mc->mc_top];
5039 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
5040 DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5042 mc->mc_ki[mc->mc_top]--;
5044 mc->mc_flags &= ~C_EOF;
5046 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5047 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5050 key->mv_size = mc->mc_db->md_pad;
5051 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5055 assert(IS_LEAF(mp));
5056 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5058 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5059 mdb_xcursor_init1(mc, leaf);
5062 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5065 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5066 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5067 if (rc != MDB_SUCCESS)
5072 MDB_GET_KEY(leaf, key);
5076 /** Set the cursor on a specific data item. */
5078 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5079 MDB_cursor_op op, int *exactp)
5083 MDB_node *leaf = NULL;
5088 assert(key->mv_size > 0);
5091 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5093 /* See if we're already on the right page */
5094 if (mc->mc_flags & C_INITIALIZED) {
5097 mp = mc->mc_pg[mc->mc_top];
5099 mc->mc_ki[mc->mc_top] = 0;
5100 return MDB_NOTFOUND;
5102 if (mp->mp_flags & P_LEAF2) {
5103 nodekey.mv_size = mc->mc_db->md_pad;
5104 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
5106 leaf = NODEPTR(mp, 0);
5107 MDB_GET_KEY2(leaf, nodekey);
5109 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5111 /* Probably happens rarely, but first node on the page
5112 * was the one we wanted.
5114 mc->mc_ki[mc->mc_top] = 0;
5121 unsigned int nkeys = NUMKEYS(mp);
5123 if (mp->mp_flags & P_LEAF2) {
5124 nodekey.mv_data = LEAF2KEY(mp,
5125 nkeys-1, nodekey.mv_size);
5127 leaf = NODEPTR(mp, nkeys-1);
5128 MDB_GET_KEY2(leaf, nodekey);
5130 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5132 /* last node was the one we wanted */
5133 mc->mc_ki[mc->mc_top] = nkeys-1;
5139 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
5140 /* This is definitely the right page, skip search_page */
5141 if (mp->mp_flags & P_LEAF2) {
5142 nodekey.mv_data = LEAF2KEY(mp,
5143 mc->mc_ki[mc->mc_top], nodekey.mv_size);
5145 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5146 MDB_GET_KEY2(leaf, nodekey);
5148 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5150 /* current node was the one we wanted */
5160 /* If any parents have right-sibs, search.
5161 * Otherwise, there's nothing further.
5163 for (i=0; i<mc->mc_top; i++)
5165 NUMKEYS(mc->mc_pg[i])-1)
5167 if (i == mc->mc_top) {
5168 /* There are no other pages */
5169 mc->mc_ki[mc->mc_top] = nkeys;
5170 return MDB_NOTFOUND;
5174 /* There are no other pages */
5175 mc->mc_ki[mc->mc_top] = 0;
5176 return MDB_NOTFOUND;
5180 rc = mdb_page_search(mc, key, 0);
5181 if (rc != MDB_SUCCESS)
5184 mp = mc->mc_pg[mc->mc_top];
5185 assert(IS_LEAF(mp));
5188 leaf = mdb_node_search(mc, key, exactp);
5189 if (exactp != NULL && !*exactp) {
5190 /* MDB_SET specified and not an exact match. */
5191 return MDB_NOTFOUND;
5195 DPUTS("===> inexact leaf not found, goto sibling");
5196 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
5197 return rc; /* no entries matched */
5198 mp = mc->mc_pg[mc->mc_top];
5199 assert(IS_LEAF(mp));
5200 leaf = NODEPTR(mp, 0);
5204 mc->mc_flags |= C_INITIALIZED;
5205 mc->mc_flags &= ~C_EOF;
5208 key->mv_size = mc->mc_db->md_pad;
5209 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5213 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5214 mdb_xcursor_init1(mc, leaf);
5217 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5218 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
5219 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5222 if (op == MDB_GET_BOTH) {
5228 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
5229 if (rc != MDB_SUCCESS)
5232 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
5234 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
5236 rc = mc->mc_dbx->md_dcmp(data, &d2);
5238 if (op == MDB_GET_BOTH || rc > 0)
5239 return MDB_NOTFOUND;
5244 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5245 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5250 /* The key already matches in all other cases */
5251 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
5252 MDB_GET_KEY(leaf, key);
5253 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
5258 /** Move the cursor to the first item in the database. */
5260 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5266 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5268 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5269 rc = mdb_page_search(mc, NULL, 0);
5270 if (rc != MDB_SUCCESS)
5273 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
5275 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
5276 mc->mc_flags |= C_INITIALIZED;
5277 mc->mc_flags &= ~C_EOF;
5279 mc->mc_ki[mc->mc_top] = 0;
5281 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5282 key->mv_size = mc->mc_db->md_pad;
5283 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
5288 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5289 mdb_xcursor_init1(mc, leaf);
5290 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5294 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5298 MDB_GET_KEY(leaf, key);
5302 /** Move the cursor to the last item in the database. */
5304 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5310 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5312 if (!(mc->mc_flags & C_EOF)) {
5314 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5317 lkey.mv_size = MDB_MAXKEYSIZE+1;
5318 lkey.mv_data = NULL;
5319 rc = mdb_page_search(mc, &lkey, 0);
5320 if (rc != MDB_SUCCESS)
5323 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
5326 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
5327 mc->mc_flags |= C_INITIALIZED|C_EOF;
5328 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5330 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5331 key->mv_size = mc->mc_db->md_pad;
5332 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
5337 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5338 mdb_xcursor_init1(mc, leaf);
5339 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5343 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5348 MDB_GET_KEY(leaf, key);
5353 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5358 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
5362 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
5366 case MDB_GET_CURRENT:
5367 if (!(mc->mc_flags & C_INITIALIZED)) {
5370 MDB_page *mp = mc->mc_pg[mc->mc_top];
5372 mc->mc_ki[mc->mc_top] = 0;
5378 key->mv_size = mc->mc_db->md_pad;
5379 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5381 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5382 MDB_GET_KEY(leaf, key);
5384 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5385 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
5387 rc = mdb_node_read(mc->mc_txn, leaf, data);
5394 case MDB_GET_BOTH_RANGE:
5399 if (mc->mc_xcursor == NULL) {
5400 rc = MDB_INCOMPATIBLE;
5409 } else if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
5410 rc = MDB_BAD_VALSIZE;
5411 } else if (op == MDB_SET_RANGE)
5412 rc = mdb_cursor_set(mc, key, data, op, NULL);
5414 rc = mdb_cursor_set(mc, key, data, op, &exact);
5416 case MDB_GET_MULTIPLE:
5417 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5421 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5422 rc = MDB_INCOMPATIBLE;
5426 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
5427 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
5430 case MDB_NEXT_MULTIPLE:
5435 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5436 rc = MDB_INCOMPATIBLE;
5439 if (!(mc->mc_flags & C_INITIALIZED))
5440 rc = mdb_cursor_first(mc, key, data);
5442 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
5443 if (rc == MDB_SUCCESS) {
5444 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
5447 mx = &mc->mc_xcursor->mx_cursor;
5448 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
5450 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
5451 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
5459 case MDB_NEXT_NODUP:
5460 if (!(mc->mc_flags & C_INITIALIZED))
5461 rc = mdb_cursor_first(mc, key, data);
5463 rc = mdb_cursor_next(mc, key, data, op);
5467 case MDB_PREV_NODUP:
5468 if (!(mc->mc_flags & C_INITIALIZED)) {
5469 rc = mdb_cursor_last(mc, key, data);
5472 mc->mc_flags |= C_INITIALIZED;
5473 mc->mc_ki[mc->mc_top]++;
5475 rc = mdb_cursor_prev(mc, key, data, op);
5478 rc = mdb_cursor_first(mc, key, data);
5481 mfunc = mdb_cursor_first;
5483 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5487 if (mc->mc_xcursor == NULL) {
5488 rc = MDB_INCOMPATIBLE;
5491 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
5495 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
5498 rc = mdb_cursor_last(mc, key, data);
5501 mfunc = mdb_cursor_last;
5504 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
5512 /** Touch all the pages in the cursor stack.
5513 * Makes sure all the pages are writable, before attempting a write operation.
5514 * @param[in] mc The cursor to operate on.
5517 mdb_cursor_touch(MDB_cursor *mc)
5521 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
5524 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
5525 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
5528 *mc->mc_dbflag |= DB_DIRTY;
5530 for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
5531 rc = mdb_page_touch(mc);
5535 mc->mc_top = mc->mc_snum-1;
5539 /** Do not spill pages to disk if txn is getting full, may fail instead */
5540 #define MDB_NOSPILL 0x8000
5543 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5546 enum { MDB_NO_ROOT = MDB_LAST_ERRCODE+10 }; /* internal code */
5547 MDB_node *leaf = NULL;
5548 MDB_val xdata, *rdata, dkey;
5551 int do_sub = 0, insert = 0;
5552 unsigned int mcount = 0, dcount = 0, nospill;
5556 char dbuf[MDB_MAXKEYSIZE+1];
5557 unsigned int nflags;
5560 /* Check this first so counter will always be zero on any
5563 if (flags & MDB_MULTIPLE) {
5564 dcount = data[1].mv_size;
5565 data[1].mv_size = 0;
5566 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
5567 return MDB_INCOMPATIBLE;
5570 nospill = flags & MDB_NOSPILL;
5571 flags &= ~MDB_NOSPILL;
5573 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
5574 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
5576 if (flags != MDB_CURRENT && (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE))
5577 return MDB_BAD_VALSIZE;
5579 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT) && data->mv_size > MDB_MAXKEYSIZE)
5580 return MDB_BAD_VALSIZE;
5582 #if SIZE_MAX > MAXDATASIZE
5583 if (data->mv_size > MAXDATASIZE)
5584 return MDB_BAD_VALSIZE;
5587 DPRINTF(("==> put db %u key [%s], size %"Z"u, data size %"Z"u",
5588 mc->mc_dbi, DKEY(key), key ? key->mv_size:0, data->mv_size));
5592 if (flags == MDB_CURRENT) {
5593 if (!(mc->mc_flags & C_INITIALIZED))
5596 } else if (mc->mc_db->md_root == P_INVALID) {
5597 /* new database, cursor has nothing to point to */
5599 mc->mc_flags &= ~C_INITIALIZED;
5604 if (flags & MDB_APPEND) {
5606 rc = mdb_cursor_last(mc, &k2, &d2);
5608 rc = mc->mc_dbx->md_cmp(key, &k2);
5611 mc->mc_ki[mc->mc_top]++;
5613 /* new key is <= last key */
5618 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
5620 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
5621 DPRINTF(("duplicate key [%s]", DKEY(key)));
5623 return MDB_KEYEXIST;
5625 if (rc && rc != MDB_NOTFOUND)
5629 /* Cursor is positioned, check for room in the dirty list */
5631 if (flags & MDB_MULTIPLE) {
5633 xdata.mv_size = data->mv_size * dcount;
5637 if ((rc2 = mdb_page_spill(mc, key, rdata)))
5641 if (rc == MDB_NO_ROOT) {
5643 /* new database, write a root leaf page */
5644 DPUTS("allocating new root leaf page");
5645 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
5648 mdb_cursor_push(mc, np);
5649 mc->mc_db->md_root = np->mp_pgno;
5650 mc->mc_db->md_depth++;
5651 *mc->mc_dbflag |= DB_DIRTY;
5652 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
5654 np->mp_flags |= P_LEAF2;
5655 mc->mc_flags |= C_INITIALIZED;
5657 /* make sure all cursor pages are writable */
5658 rc2 = mdb_cursor_touch(mc);
5663 /* The key already exists */
5664 if (rc == MDB_SUCCESS) {
5665 /* there's only a key anyway, so this is a no-op */
5666 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5667 unsigned int ksize = mc->mc_db->md_pad;
5668 if (key->mv_size != ksize)
5669 return MDB_BAD_VALSIZE;
5670 if (flags == MDB_CURRENT) {
5671 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
5672 memcpy(ptr, key->mv_data, ksize);
5677 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5680 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
5681 /* Was a single item before, must convert now */
5683 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5684 /* Just overwrite the current item */
5685 if (flags == MDB_CURRENT)
5688 dkey.mv_size = NODEDSZ(leaf);
5689 dkey.mv_data = NODEDATA(leaf);
5690 #if UINT_MAX < SIZE_MAX
5691 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && dkey.mv_size == sizeof(size_t))
5692 #ifdef MISALIGNED_OK
5693 mc->mc_dbx->md_dcmp = mdb_cmp_long;
5695 mc->mc_dbx->md_dcmp = mdb_cmp_cint;
5698 /* if data matches, skip it */
5699 if (!mc->mc_dbx->md_dcmp(data, &dkey)) {
5700 if (flags & MDB_NODUPDATA)
5702 else if (flags & MDB_MULTIPLE)
5709 /* create a fake page for the dup items */
5710 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
5711 dkey.mv_data = dbuf;
5712 fp = (MDB_page *)&pbuf;
5713 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
5714 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
5715 fp->mp_lower = PAGEHDRSZ;
5716 fp->mp_upper = PAGEHDRSZ + dkey.mv_size + data->mv_size;
5717 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5718 fp->mp_flags |= P_LEAF2;
5719 fp->mp_pad = data->mv_size;
5720 fp->mp_upper += 2 * data->mv_size; /* leave space for 2 more */
5722 fp->mp_upper += 2 * sizeof(indx_t) + 2 * NODESIZE +
5723 (dkey.mv_size & 1) + (data->mv_size & 1);
5725 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5728 xdata.mv_size = fp->mp_upper;
5733 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
5734 /* See if we need to convert from fake page to subDB */
5736 unsigned int offset;
5740 fp = NODEDATA(leaf);
5741 if (flags == MDB_CURRENT) {
5743 fp->mp_flags |= P_DIRTY;
5744 COPY_PGNO(fp->mp_pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
5745 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
5749 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5750 offset = fp->mp_pad;
5751 if (SIZELEFT(fp) >= offset)
5753 offset *= 4; /* space for 4 more */
5755 offset = NODESIZE + sizeof(indx_t) + data->mv_size;
5757 offset += offset & 1;
5758 fp_flags = fp->mp_flags;
5759 if (NODESIZE + sizeof(indx_t) + NODEKSZ(leaf) + NODEDSZ(leaf) +
5760 offset >= mc->mc_txn->mt_env->me_nodemax) {
5761 /* yes, convert it */
5763 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5764 dummy.md_pad = fp->mp_pad;
5765 dummy.md_flags = MDB_DUPFIXED;
5766 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
5767 dummy.md_flags |= MDB_INTEGERKEY;
5770 dummy.md_branch_pages = 0;
5771 dummy.md_leaf_pages = 1;
5772 dummy.md_overflow_pages = 0;
5773 dummy.md_entries = NUMKEYS(fp);
5775 xdata.mv_size = sizeof(MDB_db);
5776 xdata.mv_data = &dummy;
5777 if ((rc = mdb_page_alloc(mc, 1, &mp)))
5779 offset = mc->mc_txn->mt_env->me_psize - NODEDSZ(leaf);
5780 flags |= F_DUPDATA|F_SUBDATA;
5781 dummy.md_root = mp->mp_pgno;
5782 fp_flags &= ~P_SUBP;
5784 /* no, just grow it */
5786 xdata.mv_size = NODEDSZ(leaf) + offset;
5787 xdata.mv_data = &pbuf;
5788 mp = (MDB_page *)&pbuf;
5789 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
5792 mp->mp_flags = fp_flags | P_DIRTY;
5793 mp->mp_pad = fp->mp_pad;
5794 mp->mp_lower = fp->mp_lower;
5795 mp->mp_upper = fp->mp_upper + offset;
5797 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
5799 nsize = NODEDSZ(leaf) - fp->mp_upper;
5800 memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper, nsize);
5801 for (i=0; i<NUMKEYS(fp); i++)
5802 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
5804 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5808 /* data is on sub-DB, just store it */
5809 flags |= F_DUPDATA|F_SUBDATA;
5813 /* overflow page overwrites need special handling */
5814 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5817 unsigned psize = mc->mc_txn->mt_env->me_psize;
5818 int level, ovpages, dpages = OVPAGES(data->mv_size, psize);
5820 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
5821 if ((rc2 = mdb_page_get(mc->mc_txn, pg, &omp, &level)) != 0)
5823 ovpages = omp->mp_pages;
5825 /* Is the ov page large enough? */
5826 if (ovpages >= dpages) {
5827 if (!(omp->mp_flags & P_DIRTY) &&
5828 (level || (mc->mc_txn->mt_env->me_flags & MDB_WRITEMAP)))
5830 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
5833 level = 0; /* dirty in this txn or clean */
5836 if (omp->mp_flags & P_DIRTY) {
5837 /* yes, overwrite it. Note in this case we don't
5838 * bother to try shrinking the page if the new data
5839 * is smaller than the overflow threshold.
5842 /* It is writable only in a parent txn */
5843 size_t sz = (size_t) psize * ovpages, off;
5844 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
5850 mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
5851 if (!(flags & MDB_RESERVE)) {
5852 /* Copy end of page, adjusting alignment so
5853 * compiler may copy words instead of bytes.
5855 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
5856 memcpy((size_t *)((char *)np + off),
5857 (size_t *)((char *)omp + off), sz - off);
5860 memcpy(np, omp, sz); /* Copy beginning of page */
5863 SETDSZ(leaf, data->mv_size);
5864 if (F_ISSET(flags, MDB_RESERVE))
5865 data->mv_data = METADATA(omp);
5867 memcpy(METADATA(omp), data->mv_data, data->mv_size);
5871 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
5873 } else if (NODEDSZ(leaf) == data->mv_size) {
5874 /* same size, just replace it. Note that we could
5875 * also reuse this node if the new data is smaller,
5876 * but instead we opt to shrink the node in that case.
5878 if (F_ISSET(flags, MDB_RESERVE))
5879 data->mv_data = NODEDATA(leaf);
5880 else if (data->mv_size)
5881 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
5883 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
5886 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5887 mc->mc_db->md_entries--;
5889 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
5896 nflags = flags & NODE_ADD_FLAGS;
5897 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
5898 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
5899 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
5900 nflags &= ~MDB_APPEND;
5902 nflags |= MDB_SPLIT_REPLACE;
5903 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
5905 /* There is room already in this leaf page. */
5906 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
5907 if (rc == 0 && !do_sub && insert) {
5908 /* Adjust other cursors pointing to mp */
5909 MDB_cursor *m2, *m3;
5910 MDB_dbi dbi = mc->mc_dbi;
5911 unsigned i = mc->mc_top;
5912 MDB_page *mp = mc->mc_pg[i];
5914 if (mc->mc_flags & C_SUB)
5917 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5918 if (mc->mc_flags & C_SUB)
5919 m3 = &m2->mc_xcursor->mx_cursor;
5922 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
5923 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
5930 if (rc != MDB_SUCCESS)
5931 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5933 /* Now store the actual data in the child DB. Note that we're
5934 * storing the user data in the keys field, so there are strict
5935 * size limits on dupdata. The actual data fields of the child
5936 * DB are all zero size.
5943 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5944 if (flags & MDB_CURRENT) {
5945 xflags = MDB_CURRENT|MDB_NOSPILL;
5947 mdb_xcursor_init1(mc, leaf);
5948 xflags = (flags & MDB_NODUPDATA) ?
5949 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
5951 /* converted, write the original data first */
5953 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
5957 /* Adjust other cursors pointing to mp */
5959 unsigned i = mc->mc_top;
5960 MDB_page *mp = mc->mc_pg[i];
5962 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5963 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
5964 if (!(m2->mc_flags & C_INITIALIZED)) continue;
5965 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
5966 mdb_xcursor_init1(m2, leaf);
5970 /* we've done our job */
5973 if (flags & MDB_APPENDDUP)
5974 xflags |= MDB_APPEND;
5975 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
5976 if (flags & F_SUBDATA) {
5977 void *db = NODEDATA(leaf);
5978 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
5981 /* sub-writes might have failed so check rc again.
5982 * Don't increment count if we just replaced an existing item.
5984 if (!rc && !(flags & MDB_CURRENT))
5985 mc->mc_db->md_entries++;
5986 if (flags & MDB_MULTIPLE) {
5990 /* let caller know how many succeeded, if any */
5991 data[1].mv_size = mcount;
5992 if (mcount < dcount) {
5993 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
5994 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6001 /* If we succeeded and the key didn't exist before, make sure
6002 * the cursor is marked valid.
6005 mc->mc_flags |= C_INITIALIZED;
6010 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
6015 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
6016 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6018 if (!(mc->mc_flags & C_INITIALIZED))
6021 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
6023 flags &= ~MDB_NOSPILL; /* TODO: Or change (flags != MDB_NODUPDATA) to ~(flags & MDB_NODUPDATA), not looking at the logic of that code just now */
6025 rc = mdb_cursor_touch(mc);
6029 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6031 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6032 if (!(flags & MDB_NODUPDATA)) {
6033 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
6034 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6036 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
6037 /* If sub-DB still has entries, we're done */
6038 if (mc->mc_xcursor->mx_db.md_entries) {
6039 if (leaf->mn_flags & F_SUBDATA) {
6040 /* update subDB info */
6041 void *db = NODEDATA(leaf);
6042 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6045 /* shrink fake page */
6046 mdb_node_shrink(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6047 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6048 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6049 /* fix other sub-DB cursors pointed at this fake page */
6050 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6051 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6052 if (m2->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top] &&
6053 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
6054 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6057 mc->mc_db->md_entries--;
6060 /* otherwise fall thru and delete the sub-DB */
6063 if (leaf->mn_flags & F_SUBDATA) {
6064 /* add all the child DB's pages to the free list */
6065 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6066 if (rc == MDB_SUCCESS) {
6067 mc->mc_db->md_entries -=
6068 mc->mc_xcursor->mx_db.md_entries;
6073 return mdb_cursor_del0(mc, leaf);
6076 /** Allocate and initialize new pages for a database.
6077 * @param[in] mc a cursor on the database being added to.
6078 * @param[in] flags flags defining what type of page is being allocated.
6079 * @param[in] num the number of pages to allocate. This is usually 1,
6080 * unless allocating overflow pages for a large record.
6081 * @param[out] mp Address of a page, or NULL on failure.
6082 * @return 0 on success, non-zero on failure.
6085 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
6090 if ((rc = mdb_page_alloc(mc, num, &np)))
6092 DPRINTF(("allocated new mpage %"Z"u, page size %u",
6093 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
6094 np->mp_flags = flags | P_DIRTY;
6095 np->mp_lower = PAGEHDRSZ;
6096 np->mp_upper = mc->mc_txn->mt_env->me_psize;
6099 mc->mc_db->md_branch_pages++;
6100 else if (IS_LEAF(np))
6101 mc->mc_db->md_leaf_pages++;
6102 else if (IS_OVERFLOW(np)) {
6103 mc->mc_db->md_overflow_pages += num;
6111 /** Calculate the size of a leaf node.
6112 * The size depends on the environment's page size; if a data item
6113 * is too large it will be put onto an overflow page and the node
6114 * size will only include the key and not the data. Sizes are always
6115 * rounded up to an even number of bytes, to guarantee 2-byte alignment
6116 * of the #MDB_node headers.
6117 * @param[in] env The environment handle.
6118 * @param[in] key The key for the node.
6119 * @param[in] data The data for the node.
6120 * @return The number of bytes needed to store the node.
6123 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
6127 sz = LEAFSIZE(key, data);
6128 if (sz >= env->me_nodemax) {
6129 /* put on overflow page */
6130 sz -= data->mv_size - sizeof(pgno_t);
6134 return sz + sizeof(indx_t);
6137 /** Calculate the size of a branch node.
6138 * The size should depend on the environment's page size but since
6139 * we currently don't support spilling large keys onto overflow
6140 * pages, it's simply the size of the #MDB_node header plus the
6141 * size of the key. Sizes are always rounded up to an even number
6142 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
6143 * @param[in] env The environment handle.
6144 * @param[in] key The key for the node.
6145 * @return The number of bytes needed to store the node.
6148 mdb_branch_size(MDB_env *env, MDB_val *key)
6153 if (sz >= env->me_nodemax) {
6154 /* put on overflow page */
6155 /* not implemented */
6156 /* sz -= key->size - sizeof(pgno_t); */
6159 return sz + sizeof(indx_t);
6162 /** Add a node to the page pointed to by the cursor.
6163 * @param[in] mc The cursor for this operation.
6164 * @param[in] indx The index on the page where the new node should be added.
6165 * @param[in] key The key for the new node.
6166 * @param[in] data The data for the new node, if any.
6167 * @param[in] pgno The page number, if adding a branch node.
6168 * @param[in] flags Flags for the node.
6169 * @return 0 on success, non-zero on failure. Possible errors are:
6171 * <li>ENOMEM - failed to allocate overflow pages for the node.
6172 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
6173 * should never happen since all callers already calculate the
6174 * page's free space before calling this function.
6178 mdb_node_add(MDB_cursor *mc, indx_t indx,
6179 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
6182 size_t node_size = NODESIZE;
6185 MDB_page *mp = mc->mc_pg[mc->mc_top];
6186 MDB_page *ofp = NULL; /* overflow page */
6189 assert(mp->mp_upper >= mp->mp_lower);
6191 DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
6192 IS_LEAF(mp) ? "leaf" : "branch",
6193 IS_SUBP(mp) ? "sub-" : "",
6194 mp->mp_pgno, indx, data ? data->mv_size : 0,
6195 key ? key->mv_size : 0, key ? DKEY(key) : NULL));
6198 /* Move higher keys up one slot. */
6199 int ksize = mc->mc_db->md_pad, dif;
6200 char *ptr = LEAF2KEY(mp, indx, ksize);
6201 dif = NUMKEYS(mp) - indx;
6203 memmove(ptr+ksize, ptr, dif*ksize);
6204 /* insert new key */
6205 memcpy(ptr, key->mv_data, ksize);
6207 /* Just using these for counting */
6208 mp->mp_lower += sizeof(indx_t);
6209 mp->mp_upper -= ksize - sizeof(indx_t);
6214 node_size += key->mv_size;
6218 if (F_ISSET(flags, F_BIGDATA)) {
6219 /* Data already on overflow page. */
6220 node_size += sizeof(pgno_t);
6221 } else if (node_size + data->mv_size >= mc->mc_txn->mt_env->me_nodemax) {
6222 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
6224 /* Put data on overflow page. */
6225 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
6226 data->mv_size, node_size+data->mv_size));
6227 node_size += sizeof(pgno_t);
6228 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
6230 DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
6233 node_size += data->mv_size;
6236 node_size += node_size & 1;
6238 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
6239 DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
6240 mp->mp_pgno, NUMKEYS(mp)));
6241 DPRINTF(("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
6242 mp->mp_upper - mp->mp_lower));
6243 DPRINTF(("node size = %"Z"u", node_size));
6244 return MDB_PAGE_FULL;
6247 /* Move higher pointers up one slot. */
6248 for (i = NUMKEYS(mp); i > indx; i--)
6249 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
6251 /* Adjust free space offsets. */
6252 ofs = mp->mp_upper - node_size;
6253 assert(ofs >= mp->mp_lower + sizeof(indx_t));
6254 mp->mp_ptrs[indx] = ofs;
6256 mp->mp_lower += sizeof(indx_t);
6258 /* Write the node data. */
6259 node = NODEPTR(mp, indx);
6260 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
6261 node->mn_flags = flags;
6263 SETDSZ(node,data->mv_size);
6268 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6273 if (F_ISSET(flags, F_BIGDATA))
6274 memcpy(node->mn_data + key->mv_size, data->mv_data,
6276 else if (F_ISSET(flags, MDB_RESERVE))
6277 data->mv_data = node->mn_data + key->mv_size;
6279 memcpy(node->mn_data + key->mv_size, data->mv_data,
6282 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
6284 if (F_ISSET(flags, MDB_RESERVE))
6285 data->mv_data = METADATA(ofp);
6287 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
6294 /** Delete the specified node from a page.
6295 * @param[in] mp The page to operate on.
6296 * @param[in] indx The index of the node to delete.
6297 * @param[in] ksize The size of a node. Only used if the page is
6298 * part of a #MDB_DUPFIXED database.
6301 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
6304 indx_t i, j, numkeys, ptr;
6311 COPY_PGNO(pgno, mp->mp_pgno);
6312 DPRINTF(("delete node %u on %s page %"Z"u", indx,
6313 IS_LEAF(mp) ? "leaf" : "branch", pgno));
6316 assert(indx < NUMKEYS(mp));
6319 int x = NUMKEYS(mp) - 1 - indx;
6320 base = LEAF2KEY(mp, indx, ksize);
6322 memmove(base, base + ksize, x * ksize);
6323 mp->mp_lower -= sizeof(indx_t);
6324 mp->mp_upper += ksize - sizeof(indx_t);
6328 node = NODEPTR(mp, indx);
6329 sz = NODESIZE + node->mn_ksize;
6331 if (F_ISSET(node->mn_flags, F_BIGDATA))
6332 sz += sizeof(pgno_t);
6334 sz += NODEDSZ(node);
6338 ptr = mp->mp_ptrs[indx];
6339 numkeys = NUMKEYS(mp);
6340 for (i = j = 0; i < numkeys; i++) {
6342 mp->mp_ptrs[j] = mp->mp_ptrs[i];
6343 if (mp->mp_ptrs[i] < ptr)
6344 mp->mp_ptrs[j] += sz;
6349 base = (char *)mp + mp->mp_upper;
6350 memmove(base + sz, base, ptr - mp->mp_upper);
6352 mp->mp_lower -= sizeof(indx_t);
6356 /** Compact the main page after deleting a node on a subpage.
6357 * @param[in] mp The main page to operate on.
6358 * @param[in] indx The index of the subpage on the main page.
6361 mdb_node_shrink(MDB_page *mp, indx_t indx)
6368 indx_t i, numkeys, ptr;
6370 node = NODEPTR(mp, indx);
6371 sp = (MDB_page *)NODEDATA(node);
6372 osize = NODEDSZ(node);
6374 delta = sp->mp_upper - sp->mp_lower;
6375 SETDSZ(node, osize - delta);
6376 xp = (MDB_page *)((char *)sp + delta);
6378 /* shift subpage upward */
6380 nsize = NUMKEYS(sp) * sp->mp_pad;
6381 memmove(METADATA(xp), METADATA(sp), nsize);
6384 nsize = osize - sp->mp_upper;
6385 numkeys = NUMKEYS(sp);
6386 for (i=numkeys-1; i>=0; i--)
6387 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
6389 xp->mp_upper = sp->mp_lower;
6390 xp->mp_lower = sp->mp_lower;
6391 xp->mp_flags = sp->mp_flags;
6392 xp->mp_pad = sp->mp_pad;
6393 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
6395 /* shift lower nodes upward */
6396 ptr = mp->mp_ptrs[indx];
6397 numkeys = NUMKEYS(mp);
6398 for (i = 0; i < numkeys; i++) {
6399 if (mp->mp_ptrs[i] <= ptr)
6400 mp->mp_ptrs[i] += delta;
6403 base = (char *)mp + mp->mp_upper;
6404 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
6405 mp->mp_upper += delta;
6408 /** Initial setup of a sorted-dups cursor.
6409 * Sorted duplicates are implemented as a sub-database for the given key.
6410 * The duplicate data items are actually keys of the sub-database.
6411 * Operations on the duplicate data items are performed using a sub-cursor
6412 * initialized when the sub-database is first accessed. This function does
6413 * the preliminary setup of the sub-cursor, filling in the fields that
6414 * depend only on the parent DB.
6415 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6418 mdb_xcursor_init0(MDB_cursor *mc)
6420 MDB_xcursor *mx = mc->mc_xcursor;
6422 mx->mx_cursor.mc_xcursor = NULL;
6423 mx->mx_cursor.mc_txn = mc->mc_txn;
6424 mx->mx_cursor.mc_db = &mx->mx_db;
6425 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
6426 mx->mx_cursor.mc_dbi = mc->mc_dbi+1;
6427 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
6428 mx->mx_cursor.mc_snum = 0;
6429 mx->mx_cursor.mc_top = 0;
6430 mx->mx_cursor.mc_flags = C_SUB;
6431 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
6432 mx->mx_dbx.md_dcmp = NULL;
6433 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
6436 /** Final setup of a sorted-dups cursor.
6437 * Sets up the fields that depend on the data from the main cursor.
6438 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6439 * @param[in] node The data containing the #MDB_db record for the
6440 * sorted-dup database.
6443 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
6445 MDB_xcursor *mx = mc->mc_xcursor;
6447 if (node->mn_flags & F_SUBDATA) {
6448 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
6449 mx->mx_cursor.mc_pg[0] = 0;
6450 mx->mx_cursor.mc_snum = 0;
6451 mx->mx_cursor.mc_flags = C_SUB;
6453 MDB_page *fp = NODEDATA(node);
6454 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
6455 mx->mx_db.md_flags = 0;
6456 mx->mx_db.md_depth = 1;
6457 mx->mx_db.md_branch_pages = 0;
6458 mx->mx_db.md_leaf_pages = 1;
6459 mx->mx_db.md_overflow_pages = 0;
6460 mx->mx_db.md_entries = NUMKEYS(fp);
6461 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
6462 mx->mx_cursor.mc_snum = 1;
6463 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
6464 mx->mx_cursor.mc_top = 0;
6465 mx->mx_cursor.mc_pg[0] = fp;
6466 mx->mx_cursor.mc_ki[0] = 0;
6467 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6468 mx->mx_db.md_flags = MDB_DUPFIXED;
6469 mx->mx_db.md_pad = fp->mp_pad;
6470 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6471 mx->mx_db.md_flags |= MDB_INTEGERKEY;
6474 DPRINTF(("Sub-db %u for db %u root page %"Z"u", mx->mx_cursor.mc_dbi, mc->mc_dbi,
6475 mx->mx_db.md_root));
6476 mx->mx_dbflag = DB_VALID | (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY) ?
6478 mx->mx_dbx.md_name.mv_data = NODEKEY(node);
6479 mx->mx_dbx.md_name.mv_size = node->mn_ksize;
6480 #if UINT_MAX < SIZE_MAX
6481 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
6482 #ifdef MISALIGNED_OK
6483 mx->mx_dbx.md_cmp = mdb_cmp_long;
6485 mx->mx_dbx.md_cmp = mdb_cmp_cint;
6490 /** Initialize a cursor for a given transaction and database. */
6492 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
6495 mc->mc_backup = NULL;
6498 mc->mc_db = &txn->mt_dbs[dbi];
6499 mc->mc_dbx = &txn->mt_dbxs[dbi];
6500 mc->mc_dbflag = &txn->mt_dbflags[dbi];
6505 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
6507 mc->mc_xcursor = mx;
6508 mdb_xcursor_init0(mc);
6510 mc->mc_xcursor = NULL;
6512 if (*mc->mc_dbflag & DB_STALE) {
6513 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
6518 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
6521 size_t size = sizeof(MDB_cursor);
6523 if (txn == NULL || ret == NULL || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
6526 if (txn->mt_flags & MDB_TXN_ERROR)
6529 /* Allow read access to the freelist */
6530 if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
6533 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
6534 size += sizeof(MDB_xcursor);
6536 if ((mc = malloc(size)) != NULL) {
6537 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
6538 if (txn->mt_cursors) {
6539 mc->mc_next = txn->mt_cursors[dbi];
6540 txn->mt_cursors[dbi] = mc;
6541 mc->mc_flags |= C_UNTRACK;
6553 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
6555 if (txn == NULL || mc == NULL || mc->mc_dbi >= txn->mt_numdbs)
6558 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
6561 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
6565 /* Return the count of duplicate data items for the current key */
6567 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
6571 if (mc == NULL || countp == NULL)
6574 if (mc->mc_xcursor == NULL)
6575 return MDB_INCOMPATIBLE;
6577 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6578 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6581 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
6584 *countp = mc->mc_xcursor->mx_db.md_entries;
6590 mdb_cursor_close(MDB_cursor *mc)
6592 if (mc && !mc->mc_backup) {
6593 /* remove from txn, if tracked */
6594 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
6595 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
6596 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
6598 *prev = mc->mc_next;
6605 mdb_cursor_txn(MDB_cursor *mc)
6607 if (!mc) return NULL;
6612 mdb_cursor_dbi(MDB_cursor *mc)
6618 /** Replace the key for a node with a new key.
6619 * @param[in] mc Cursor pointing to the node to operate on.
6620 * @param[in] key The new key to use.
6621 * @return 0 on success, non-zero on failure.
6624 mdb_update_key(MDB_cursor *mc, MDB_val *key)
6631 indx_t ptr, i, numkeys, indx;
6634 indx = mc->mc_ki[mc->mc_top];
6635 mp = mc->mc_pg[mc->mc_top];
6636 node = NODEPTR(mp, indx);
6637 ptr = mp->mp_ptrs[indx];
6641 char kbuf2[(MDB_MAXKEYSIZE*2+1)];
6642 k2.mv_data = NODEKEY(node);
6643 k2.mv_size = node->mn_ksize;
6644 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
6646 mdb_dkey(&k2, kbuf2),
6652 delta0 = delta = key->mv_size - node->mn_ksize;
6654 /* Must be 2-byte aligned. If new key is
6655 * shorter by 1, the shift will be skipped.
6657 delta += (delta & 1);
6659 if (delta > 0 && SIZELEFT(mp) < delta) {
6661 /* not enough space left, do a delete and split */
6662 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
6663 pgno = NODEPGNO(node);
6664 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
6665 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
6668 numkeys = NUMKEYS(mp);
6669 for (i = 0; i < numkeys; i++) {
6670 if (mp->mp_ptrs[i] <= ptr)
6671 mp->mp_ptrs[i] -= delta;
6674 base = (char *)mp + mp->mp_upper;
6675 len = ptr - mp->mp_upper + NODESIZE;
6676 memmove(base - delta, base, len);
6677 mp->mp_upper -= delta;
6679 node = NODEPTR(mp, indx);
6682 /* But even if no shift was needed, update ksize */
6684 node->mn_ksize = key->mv_size;
6687 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6693 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
6695 /** Move a node from csrc to cdst.
6698 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
6705 unsigned short flags;
6709 /* Mark src and dst as dirty. */
6710 if ((rc = mdb_page_touch(csrc)) ||
6711 (rc = mdb_page_touch(cdst)))
6714 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6715 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
6716 key.mv_size = csrc->mc_db->md_pad;
6717 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
6719 data.mv_data = NULL;
6723 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
6724 assert(!((long)srcnode&1));
6725 srcpg = NODEPGNO(srcnode);
6726 flags = srcnode->mn_flags;
6727 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6728 unsigned int snum = csrc->mc_snum;
6730 /* must find the lowest key below src */
6731 mdb_page_search_lowest(csrc);
6732 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6733 key.mv_size = csrc->mc_db->md_pad;
6734 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6736 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6737 key.mv_size = NODEKSZ(s2);
6738 key.mv_data = NODEKEY(s2);
6740 csrc->mc_snum = snum--;
6741 csrc->mc_top = snum;
6743 key.mv_size = NODEKSZ(srcnode);
6744 key.mv_data = NODEKEY(srcnode);
6746 data.mv_size = NODEDSZ(srcnode);
6747 data.mv_data = NODEDATA(srcnode);
6749 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
6750 unsigned int snum = cdst->mc_snum;
6753 /* must find the lowest key below dst */
6754 mdb_page_search_lowest(cdst);
6755 if (IS_LEAF2(cdst->mc_pg[cdst->mc_top])) {
6756 bkey.mv_size = cdst->mc_db->md_pad;
6757 bkey.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, bkey.mv_size);
6759 s2 = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
6760 bkey.mv_size = NODEKSZ(s2);
6761 bkey.mv_data = NODEKEY(s2);
6763 cdst->mc_snum = snum--;
6764 cdst->mc_top = snum;
6765 mdb_cursor_copy(cdst, &mn);
6767 rc = mdb_update_key(&mn, &bkey);
6772 DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
6773 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
6774 csrc->mc_ki[csrc->mc_top],
6776 csrc->mc_pg[csrc->mc_top]->mp_pgno,
6777 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
6779 /* Add the node to the destination page.
6781 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
6782 if (rc != MDB_SUCCESS)
6785 /* Delete the node from the source page.
6787 mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
6790 /* Adjust other cursors pointing to mp */
6791 MDB_cursor *m2, *m3;
6792 MDB_dbi dbi = csrc->mc_dbi;
6793 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
6795 if (csrc->mc_flags & C_SUB)
6798 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6799 if (csrc->mc_flags & C_SUB)
6800 m3 = &m2->mc_xcursor->mx_cursor;
6803 if (m3 == csrc) continue;
6804 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
6805 csrc->mc_ki[csrc->mc_top]) {
6806 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
6807 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
6812 /* Update the parent separators.
6814 if (csrc->mc_ki[csrc->mc_top] == 0) {
6815 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
6816 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6817 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6819 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6820 key.mv_size = NODEKSZ(srcnode);
6821 key.mv_data = NODEKEY(srcnode);
6823 DPRINTF(("update separator for source page %"Z"u to [%s]",
6824 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
6825 mdb_cursor_copy(csrc, &mn);
6828 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
6831 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6833 indx_t ix = csrc->mc_ki[csrc->mc_top];
6834 nullkey.mv_size = 0;
6835 csrc->mc_ki[csrc->mc_top] = 0;
6836 rc = mdb_update_key(csrc, &nullkey);
6837 csrc->mc_ki[csrc->mc_top] = ix;
6838 assert(rc == MDB_SUCCESS);
6842 if (cdst->mc_ki[cdst->mc_top] == 0) {
6843 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
6844 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6845 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
6847 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
6848 key.mv_size = NODEKSZ(srcnode);
6849 key.mv_data = NODEKEY(srcnode);
6851 DPRINTF(("update separator for destination page %"Z"u to [%s]",
6852 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
6853 mdb_cursor_copy(cdst, &mn);
6856 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
6859 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
6861 indx_t ix = cdst->mc_ki[cdst->mc_top];
6862 nullkey.mv_size = 0;
6863 cdst->mc_ki[cdst->mc_top] = 0;
6864 rc = mdb_update_key(cdst, &nullkey);
6865 cdst->mc_ki[cdst->mc_top] = ix;
6866 assert(rc == MDB_SUCCESS);
6873 /** Merge one page into another.
6874 * The nodes from the page pointed to by \b csrc will
6875 * be copied to the page pointed to by \b cdst and then
6876 * the \b csrc page will be freed.
6877 * @param[in] csrc Cursor pointing to the source page.
6878 * @param[in] cdst Cursor pointing to the destination page.
6881 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
6889 DPRINTF(("merging page %"Z"u into %"Z"u", csrc->mc_pg[csrc->mc_top]->mp_pgno,
6890 cdst->mc_pg[cdst->mc_top]->mp_pgno));
6892 assert(csrc->mc_snum > 1); /* can't merge root page */
6893 assert(cdst->mc_snum > 1);
6895 /* Mark dst as dirty. */
6896 if ((rc = mdb_page_touch(cdst)))
6899 /* Move all nodes from src to dst.
6901 j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
6902 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6903 key.mv_size = csrc->mc_db->md_pad;
6904 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
6905 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
6906 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
6907 if (rc != MDB_SUCCESS)
6909 key.mv_data = (char *)key.mv_data + key.mv_size;
6912 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
6913 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
6914 if (i == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6915 unsigned int snum = csrc->mc_snum;
6917 /* must find the lowest key below src */
6918 mdb_page_search_lowest(csrc);
6919 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6920 key.mv_size = csrc->mc_db->md_pad;
6921 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6923 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6924 key.mv_size = NODEKSZ(s2);
6925 key.mv_data = NODEKEY(s2);
6927 csrc->mc_snum = snum--;
6928 csrc->mc_top = snum;
6930 key.mv_size = srcnode->mn_ksize;
6931 key.mv_data = NODEKEY(srcnode);
6934 data.mv_size = NODEDSZ(srcnode);
6935 data.mv_data = NODEDATA(srcnode);
6936 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
6937 if (rc != MDB_SUCCESS)
6942 DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
6943 cdst->mc_pg[cdst->mc_top]->mp_pgno, NUMKEYS(cdst->mc_pg[cdst->mc_top]),
6944 (float)PAGEFILL(cdst->mc_txn->mt_env, cdst->mc_pg[cdst->mc_top]) / 10));
6946 /* Unlink the src page from parent and add to free list.
6948 mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
6949 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
6952 rc = mdb_update_key(csrc, &key);
6958 rc = mdb_midl_append(&csrc->mc_txn->mt_free_pgs,
6959 csrc->mc_pg[csrc->mc_top]->mp_pgno);
6962 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
6963 csrc->mc_db->md_leaf_pages--;
6965 csrc->mc_db->md_branch_pages--;
6967 /* Adjust other cursors pointing to mp */
6968 MDB_cursor *m2, *m3;
6969 MDB_dbi dbi = csrc->mc_dbi;
6970 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
6972 if (csrc->mc_flags & C_SUB)
6975 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6976 if (csrc->mc_flags & C_SUB)
6977 m3 = &m2->mc_xcursor->mx_cursor;
6980 if (m3 == csrc) continue;
6981 if (m3->mc_snum < csrc->mc_snum) continue;
6982 if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
6983 m3->mc_pg[csrc->mc_top] = mp;
6984 m3->mc_ki[csrc->mc_top] += nkeys;
6988 mdb_cursor_pop(csrc);
6990 return mdb_rebalance(csrc);
6993 /** Copy the contents of a cursor.
6994 * @param[in] csrc The cursor to copy from.
6995 * @param[out] cdst The cursor to copy to.
6998 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
7002 cdst->mc_txn = csrc->mc_txn;
7003 cdst->mc_dbi = csrc->mc_dbi;
7004 cdst->mc_db = csrc->mc_db;
7005 cdst->mc_dbx = csrc->mc_dbx;
7006 cdst->mc_snum = csrc->mc_snum;
7007 cdst->mc_top = csrc->mc_top;
7008 cdst->mc_flags = csrc->mc_flags;
7010 for (i=0; i<csrc->mc_snum; i++) {
7011 cdst->mc_pg[i] = csrc->mc_pg[i];
7012 cdst->mc_ki[i] = csrc->mc_ki[i];
7016 /** Rebalance the tree after a delete operation.
7017 * @param[in] mc Cursor pointing to the page where rebalancing
7019 * @return 0 on success, non-zero on failure.
7022 mdb_rebalance(MDB_cursor *mc)
7026 unsigned int ptop, minkeys;
7029 minkeys = 1 + (IS_BRANCH(mc->mc_pg[mc->mc_top]));
7033 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
7034 DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
7035 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
7036 pgno, NUMKEYS(mc->mc_pg[mc->mc_top]),
7037 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
7041 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD &&
7042 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
7045 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
7046 DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
7052 if (mc->mc_snum < 2) {
7053 MDB_page *mp = mc->mc_pg[0];
7055 DPUTS("Can't rebalance a subpage, ignoring");
7058 if (NUMKEYS(mp) == 0) {
7059 DPUTS("tree is completely empty");
7060 mc->mc_db->md_root = P_INVALID;
7061 mc->mc_db->md_depth = 0;
7062 mc->mc_db->md_leaf_pages = 0;
7063 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7066 /* Adjust cursors pointing to mp */
7070 MDB_cursor *m2, *m3;
7071 MDB_dbi dbi = mc->mc_dbi;
7073 if (mc->mc_flags & C_SUB)
7076 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7077 if (mc->mc_flags & C_SUB)
7078 m3 = &m2->mc_xcursor->mx_cursor;
7081 if (m3->mc_snum < mc->mc_snum) continue;
7082 if (m3->mc_pg[0] == mp) {
7088 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
7089 DPUTS("collapsing root page!");
7090 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7093 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
7094 rc = mdb_page_get(mc->mc_txn,mc->mc_db->md_root,&mc->mc_pg[0],NULL);
7097 mc->mc_db->md_depth--;
7098 mc->mc_db->md_branch_pages--;
7099 mc->mc_ki[0] = mc->mc_ki[1];
7101 /* Adjust other cursors pointing to mp */
7102 MDB_cursor *m2, *m3;
7103 MDB_dbi dbi = mc->mc_dbi;
7105 if (mc->mc_flags & C_SUB)
7108 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7109 if (mc->mc_flags & C_SUB)
7110 m3 = &m2->mc_xcursor->mx_cursor;
7113 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
7114 if (m3->mc_pg[0] == mp) {
7115 m3->mc_pg[0] = mc->mc_pg[0];
7118 m3->mc_ki[0] = m3->mc_ki[1];
7123 DPUTS("root page doesn't need rebalancing");
7127 /* The parent (branch page) must have at least 2 pointers,
7128 * otherwise the tree is invalid.
7130 ptop = mc->mc_top-1;
7131 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
7133 /* Leaf page fill factor is below the threshold.
7134 * Try to move keys from left or right neighbor, or
7135 * merge with a neighbor page.
7140 mdb_cursor_copy(mc, &mn);
7141 mn.mc_xcursor = NULL;
7143 if (mc->mc_ki[ptop] == 0) {
7144 /* We're the leftmost leaf in our parent.
7146 DPUTS("reading right neighbor");
7148 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7149 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7152 mn.mc_ki[mn.mc_top] = 0;
7153 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
7155 /* There is at least one neighbor to the left.
7157 DPUTS("reading left neighbor");
7159 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7160 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7163 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
7164 mc->mc_ki[mc->mc_top] = 0;
7167 DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
7168 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
7169 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
7171 /* If the neighbor page is above threshold and has enough keys,
7172 * move one key from it. Otherwise we should try to merge them.
7173 * (A branch page must never have less than 2 keys.)
7175 minkeys = 1 + (IS_BRANCH(mn.mc_pg[mn.mc_top]));
7176 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys)
7177 return mdb_node_move(&mn, mc);
7179 if (mc->mc_ki[ptop] == 0)
7180 rc = mdb_page_merge(&mn, mc);
7182 rc = mdb_page_merge(mc, &mn);
7183 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
7188 /** Complete a delete operation started by #mdb_cursor_del(). */
7190 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
7197 mp = mc->mc_pg[mc->mc_top];
7198 ki = mc->mc_ki[mc->mc_top];
7200 /* add overflow pages to free list */
7201 if (!IS_LEAF2(mp) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7205 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
7206 if ((rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL)) ||
7207 (rc = mdb_ovpage_free(mc, omp)))
7210 mdb_node_del(mp, ki, mc->mc_db->md_pad);
7211 mc->mc_db->md_entries--;
7212 rc = mdb_rebalance(mc);
7213 if (rc != MDB_SUCCESS)
7214 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7217 MDB_dbi dbi = mc->mc_dbi;
7219 mp = mc->mc_pg[mc->mc_top];
7220 nkeys = NUMKEYS(mp);
7222 /* if mc points past last node in page, find next sibling */
7223 if (mc->mc_ki[mc->mc_top] >= nkeys)
7224 mdb_cursor_sibling(mc, 1);
7226 /* Adjust other cursors pointing to mp */
7227 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7230 if (!(m2->mc_flags & C_INITIALIZED))
7232 if (m2->mc_pg[mc->mc_top] == mp) {
7233 if (m2->mc_ki[mc->mc_top] > ki)
7234 m2->mc_ki[mc->mc_top]--;
7235 if (m2->mc_ki[mc->mc_top] >= nkeys)
7236 mdb_cursor_sibling(m2, 1);
7245 mdb_del(MDB_txn *txn, MDB_dbi dbi,
7246 MDB_val *key, MDB_val *data)
7251 MDB_val rdata, *xdata;
7255 assert(key != NULL);
7257 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
7259 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7262 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
7263 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7265 if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
7266 return MDB_BAD_VALSIZE;
7269 mdb_cursor_init(&mc, txn, dbi, &mx);
7272 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
7273 /* must ignore any data */
7284 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
7286 /* let mdb_page_split know about this cursor if needed:
7287 * delete will trigger a rebalance; if it needs to move
7288 * a node from one page to another, it will have to
7289 * update the parent's separator key(s). If the new sepkey
7290 * is larger than the current one, the parent page may
7291 * run out of space, triggering a split. We need this
7292 * cursor to be consistent until the end of the rebalance.
7294 mc.mc_flags |= C_UNTRACK;
7295 mc.mc_next = txn->mt_cursors[dbi];
7296 txn->mt_cursors[dbi] = &mc;
7297 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
7298 txn->mt_cursors[dbi] = mc.mc_next;
7303 /** Split a page and insert a new node.
7304 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
7305 * The cursor will be updated to point to the actual page and index where
7306 * the node got inserted after the split.
7307 * @param[in] newkey The key for the newly inserted node.
7308 * @param[in] newdata The data for the newly inserted node.
7309 * @param[in] newpgno The page number, if the new node is a branch node.
7310 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
7311 * @return 0 on success, non-zero on failure.
7314 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
7315 unsigned int nflags)
7318 int rc = MDB_SUCCESS, ins_new = 0, new_root = 0, newpos = 1, did_split = 0;
7321 unsigned int i, j, split_indx, nkeys, pmax;
7323 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
7325 MDB_page *mp, *rp, *pp;
7330 mp = mc->mc_pg[mc->mc_top];
7331 newindx = mc->mc_ki[mc->mc_top];
7333 DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i",
7334 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
7335 DKEY(newkey), mc->mc_ki[mc->mc_top]));
7337 /* Create a right sibling. */
7338 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
7340 DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
7342 if (mc->mc_snum < 2) {
7343 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
7345 /* shift current top to make room for new parent */
7346 mc->mc_pg[1] = mc->mc_pg[0];
7347 mc->mc_ki[1] = mc->mc_ki[0];
7350 mc->mc_db->md_root = pp->mp_pgno;
7351 DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
7352 mc->mc_db->md_depth++;
7355 /* Add left (implicit) pointer. */
7356 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
7357 /* undo the pre-push */
7358 mc->mc_pg[0] = mc->mc_pg[1];
7359 mc->mc_ki[0] = mc->mc_ki[1];
7360 mc->mc_db->md_root = mp->mp_pgno;
7361 mc->mc_db->md_depth--;
7368 ptop = mc->mc_top-1;
7369 DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
7372 mc->mc_flags |= C_SPLITTING;
7373 mdb_cursor_copy(mc, &mn);
7374 mn.mc_pg[mn.mc_top] = rp;
7375 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
7377 if (nflags & MDB_APPEND) {
7378 mn.mc_ki[mn.mc_top] = 0;
7380 split_indx = newindx;
7385 nkeys = NUMKEYS(mp);
7386 split_indx = nkeys / 2;
7387 if (newindx < split_indx)
7393 unsigned int lsize, rsize, ksize;
7394 /* Move half of the keys to the right sibling */
7396 x = mc->mc_ki[mc->mc_top] - split_indx;
7397 ksize = mc->mc_db->md_pad;
7398 split = LEAF2KEY(mp, split_indx, ksize);
7399 rsize = (nkeys - split_indx) * ksize;
7400 lsize = (nkeys - split_indx) * sizeof(indx_t);
7401 mp->mp_lower -= lsize;
7402 rp->mp_lower += lsize;
7403 mp->mp_upper += rsize - lsize;
7404 rp->mp_upper -= rsize - lsize;
7405 sepkey.mv_size = ksize;
7406 if (newindx == split_indx) {
7407 sepkey.mv_data = newkey->mv_data;
7409 sepkey.mv_data = split;
7412 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
7413 memcpy(rp->mp_ptrs, split, rsize);
7414 sepkey.mv_data = rp->mp_ptrs;
7415 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
7416 memcpy(ins, newkey->mv_data, ksize);
7417 mp->mp_lower += sizeof(indx_t);
7418 mp->mp_upper -= ksize - sizeof(indx_t);
7421 memcpy(rp->mp_ptrs, split, x * ksize);
7422 ins = LEAF2KEY(rp, x, ksize);
7423 memcpy(ins, newkey->mv_data, ksize);
7424 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
7425 rp->mp_lower += sizeof(indx_t);
7426 rp->mp_upper -= ksize - sizeof(indx_t);
7427 mc->mc_ki[mc->mc_top] = x;
7428 mc->mc_pg[mc->mc_top] = rp;
7433 /* For leaf pages, check the split point based on what
7434 * fits where, since otherwise mdb_node_add can fail.
7436 * This check is only needed when the data items are
7437 * relatively large, such that being off by one will
7438 * make the difference between success or failure.
7440 * It's also relevant if a page happens to be laid out
7441 * such that one half of its nodes are all "small" and
7442 * the other half of its nodes are "large." If the new
7443 * item is also "large" and falls on the half with
7444 * "large" nodes, it also may not fit.
7447 unsigned int psize, nsize;
7448 /* Maximum free space in an empty page */
7449 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
7450 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
7451 if ((nkeys < 20) || (nsize > pmax/16)) {
7452 if (newindx <= split_indx) {
7455 for (i=0; i<split_indx; i++) {
7456 node = NODEPTR(mp, i);
7457 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
7458 if (F_ISSET(node->mn_flags, F_BIGDATA))
7459 psize += sizeof(pgno_t);
7461 psize += NODEDSZ(node);
7465 split_indx = newindx;
7476 for (i=nkeys-1; i>=split_indx; i--) {
7477 node = NODEPTR(mp, i);
7478 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
7479 if (F_ISSET(node->mn_flags, F_BIGDATA))
7480 psize += sizeof(pgno_t);
7482 psize += NODEDSZ(node);
7486 split_indx = newindx;
7497 /* First find the separating key between the split pages.
7498 * The case where newindx == split_indx is ambiguous; the
7499 * new item could go to the new page or stay on the original
7500 * page. If newpos == 1 it goes to the new page.
7502 if (newindx == split_indx && newpos) {
7503 sepkey.mv_size = newkey->mv_size;
7504 sepkey.mv_data = newkey->mv_data;
7506 node = NODEPTR(mp, split_indx);
7507 sepkey.mv_size = node->mn_ksize;
7508 sepkey.mv_data = NODEKEY(node);
7512 DPRINTF(("separator is [%s]", DKEY(&sepkey)));
7514 /* Copy separator key to the parent.
7516 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
7520 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
7523 if (mn.mc_snum == mc->mc_snum) {
7524 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
7525 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
7526 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
7527 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
7532 /* Right page might now have changed parent.
7533 * Check if left page also changed parent.
7535 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7536 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7537 for (i=0; i<ptop; i++) {
7538 mc->mc_pg[i] = mn.mc_pg[i];
7539 mc->mc_ki[i] = mn.mc_ki[i];
7541 mc->mc_pg[ptop] = mn.mc_pg[ptop];
7542 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
7546 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
7549 mc->mc_flags ^= C_SPLITTING;
7550 if (rc != MDB_SUCCESS) {
7553 if (nflags & MDB_APPEND) {
7554 mc->mc_pg[mc->mc_top] = rp;
7555 mc->mc_ki[mc->mc_top] = 0;
7556 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
7559 for (i=0; i<mc->mc_top; i++)
7560 mc->mc_ki[i] = mn.mc_ki[i];
7567 /* Move half of the keys to the right sibling. */
7569 /* grab a page to hold a temporary copy */
7570 copy = mdb_page_malloc(mc->mc_txn, 1);
7574 copy->mp_pgno = mp->mp_pgno;
7575 copy->mp_flags = mp->mp_flags;
7576 copy->mp_lower = PAGEHDRSZ;
7577 copy->mp_upper = mc->mc_txn->mt_env->me_psize;
7578 mc->mc_pg[mc->mc_top] = copy;
7579 for (i = j = 0; i <= nkeys; j++) {
7580 if (i == split_indx) {
7581 /* Insert in right sibling. */
7582 /* Reset insert index for right sibling. */
7583 if (i != newindx || (newpos ^ ins_new)) {
7585 mc->mc_pg[mc->mc_top] = rp;
7589 if (i == newindx && !ins_new) {
7590 /* Insert the original entry that caused the split. */
7591 rkey.mv_data = newkey->mv_data;
7592 rkey.mv_size = newkey->mv_size;
7601 /* Update index for the new key. */
7602 mc->mc_ki[mc->mc_top] = j;
7603 } else if (i == nkeys) {
7606 node = NODEPTR(mp, i);
7607 rkey.mv_data = NODEKEY(node);
7608 rkey.mv_size = node->mn_ksize;
7610 xdata.mv_data = NODEDATA(node);
7611 xdata.mv_size = NODEDSZ(node);
7614 pgno = NODEPGNO(node);
7615 flags = node->mn_flags;
7620 if (!IS_LEAF(mp) && j == 0) {
7621 /* First branch index doesn't need key data. */
7625 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
7629 nkeys = NUMKEYS(copy);
7630 for (i=0; i<nkeys; i++)
7631 mp->mp_ptrs[i] = copy->mp_ptrs[i];
7632 mp->mp_lower = copy->mp_lower;
7633 mp->mp_upper = copy->mp_upper;
7634 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
7635 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
7637 /* reset back to original page */
7638 if (newindx < split_indx || (!newpos && newindx == split_indx)) {
7639 mc->mc_pg[mc->mc_top] = mp;
7640 if (nflags & MDB_RESERVE) {
7641 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7642 if (!(node->mn_flags & F_BIGDATA))
7643 newdata->mv_data = NODEDATA(node);
7647 /* Make sure mc_ki is still valid.
7649 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7650 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7651 for (i=0; i<ptop; i++) {
7652 mc->mc_pg[i] = mn.mc_pg[i];
7653 mc->mc_ki[i] = mn.mc_ki[i];
7655 mc->mc_pg[ptop] = mn.mc_pg[ptop];
7656 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
7660 /* return tmp page to freelist */
7661 mdb_page_free(mc->mc_txn->mt_env, copy);
7664 /* Adjust other cursors pointing to mp */
7665 MDB_cursor *m2, *m3;
7666 MDB_dbi dbi = mc->mc_dbi;
7667 int fixup = NUMKEYS(mp);
7669 if (mc->mc_flags & C_SUB)
7672 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7673 if (mc->mc_flags & C_SUB)
7674 m3 = &m2->mc_xcursor->mx_cursor;
7679 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
7681 if (m3->mc_flags & C_SPLITTING)
7686 for (k=m3->mc_top; k>=0; k--) {
7687 m3->mc_ki[k+1] = m3->mc_ki[k];
7688 m3->mc_pg[k+1] = m3->mc_pg[k];
7690 if (m3->mc_ki[0] >= split_indx) {
7695 m3->mc_pg[0] = mc->mc_pg[0];
7699 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
7700 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
7701 m3->mc_ki[mc->mc_top]++;
7702 if (m3->mc_ki[mc->mc_top] >= fixup) {
7703 m3->mc_pg[mc->mc_top] = rp;
7704 m3->mc_ki[mc->mc_top] -= fixup;
7705 m3->mc_ki[ptop] = mn.mc_ki[ptop];
7707 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
7708 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
7717 mdb_put(MDB_txn *txn, MDB_dbi dbi,
7718 MDB_val *key, MDB_val *data, unsigned int flags)
7723 assert(key != NULL);
7724 assert(data != NULL);
7726 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7729 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
7730 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7732 if (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE) {
7733 return MDB_BAD_VALSIZE;
7736 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP)) != flags)
7739 mdb_cursor_init(&mc, txn, dbi, &mx);
7740 return mdb_cursor_put(&mc, key, data, flags);
7744 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
7746 if ((flag & CHANGEABLE) != flag)
7749 env->me_flags |= flag;
7751 env->me_flags &= ~flag;
7756 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
7761 *arg = env->me_flags;
7766 mdb_env_get_path(MDB_env *env, const char **arg)
7771 *arg = env->me_path;
7775 /** Common code for #mdb_stat() and #mdb_env_stat().
7776 * @param[in] env the environment to operate in.
7777 * @param[in] db the #MDB_db record containing the stats to return.
7778 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
7779 * @return 0, this function always succeeds.
7782 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
7784 arg->ms_psize = env->me_psize;
7785 arg->ms_depth = db->md_depth;
7786 arg->ms_branch_pages = db->md_branch_pages;
7787 arg->ms_leaf_pages = db->md_leaf_pages;
7788 arg->ms_overflow_pages = db->md_overflow_pages;
7789 arg->ms_entries = db->md_entries;
7794 mdb_env_stat(MDB_env *env, MDB_stat *arg)
7798 if (env == NULL || arg == NULL)
7801 toggle = mdb_env_pick_meta(env);
7803 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
7807 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
7811 if (env == NULL || arg == NULL)
7814 toggle = mdb_env_pick_meta(env);
7815 arg->me_mapaddr = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : 0;
7816 arg->me_mapsize = env->me_mapsize;
7817 arg->me_maxreaders = env->me_maxreaders;
7819 /* me_numreaders may be zero if this process never used any readers. Use
7820 * the shared numreader count if it exists.
7822 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : env->me_numreaders;
7824 arg->me_last_pgno = env->me_metas[toggle]->mm_last_pg;
7825 arg->me_last_txnid = env->me_metas[toggle]->mm_txnid;
7829 /** Set the default comparison functions for a database.
7830 * Called immediately after a database is opened to set the defaults.
7831 * The user can then override them with #mdb_set_compare() or
7832 * #mdb_set_dupsort().
7833 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
7834 * @param[in] dbi A database handle returned by #mdb_dbi_open()
7837 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
7839 uint16_t f = txn->mt_dbs[dbi].md_flags;
7841 txn->mt_dbxs[dbi].md_cmp =
7842 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
7843 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
7845 txn->mt_dbxs[dbi].md_dcmp =
7846 !(f & MDB_DUPSORT) ? 0 :
7847 ((f & MDB_INTEGERDUP)
7848 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
7849 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
7852 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
7857 int rc, dbflag, exact;
7858 unsigned int unused = 0;
7861 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
7862 mdb_default_cmp(txn, FREE_DBI);
7865 if ((flags & VALID_FLAGS) != flags)
7867 if (txn->mt_flags & MDB_TXN_ERROR)
7873 if (flags & PERSISTENT_FLAGS) {
7874 uint16_t f2 = flags & PERSISTENT_FLAGS;
7875 /* make sure flag changes get committed */
7876 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
7877 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
7878 txn->mt_flags |= MDB_TXN_DIRTY;
7881 mdb_default_cmp(txn, MAIN_DBI);
7885 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
7886 mdb_default_cmp(txn, MAIN_DBI);
7889 /* Is the DB already open? */
7891 for (i=2; i<txn->mt_numdbs; i++) {
7892 if (!txn->mt_dbxs[i].md_name.mv_size) {
7893 /* Remember this free slot */
7894 if (!unused) unused = i;
7897 if (len == txn->mt_dbxs[i].md_name.mv_size &&
7898 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
7904 /* If no free slot and max hit, fail */
7905 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
7906 return MDB_DBS_FULL;
7908 /* Cannot mix named databases with some mainDB flags */
7909 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
7910 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
7912 /* Find the DB info */
7913 dbflag = DB_NEW|DB_VALID;
7916 key.mv_data = (void *)name;
7917 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
7918 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
7919 if (rc == MDB_SUCCESS) {
7920 /* make sure this is actually a DB */
7921 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
7922 if (!(node->mn_flags & F_SUBDATA))
7923 return MDB_INCOMPATIBLE;
7924 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
7925 /* Create if requested */
7927 data.mv_size = sizeof(MDB_db);
7928 data.mv_data = &dummy;
7929 memset(&dummy, 0, sizeof(dummy));
7930 dummy.md_root = P_INVALID;
7931 dummy.md_flags = flags & PERSISTENT_FLAGS;
7932 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
7936 /* OK, got info, add to table */
7937 if (rc == MDB_SUCCESS) {
7938 unsigned int slot = unused ? unused : txn->mt_numdbs;
7939 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
7940 txn->mt_dbxs[slot].md_name.mv_size = len;
7941 txn->mt_dbxs[slot].md_rel = NULL;
7942 txn->mt_dbflags[slot] = dbflag;
7943 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
7945 txn->mt_env->me_dbflags[slot] = txn->mt_dbs[slot].md_flags;
7946 mdb_default_cmp(txn, slot);
7955 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
7957 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
7960 if (txn->mt_dbflags[dbi] & DB_STALE) {
7963 /* Stale, must read the DB's root. cursor_init does it for us. */
7964 mdb_cursor_init(&mc, txn, dbi, &mx);
7966 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
7969 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
7972 if (dbi <= MAIN_DBI || dbi >= env->me_maxdbs)
7974 ptr = env->me_dbxs[dbi].md_name.mv_data;
7975 env->me_dbxs[dbi].md_name.mv_data = NULL;
7976 env->me_dbxs[dbi].md_name.mv_size = 0;
7977 env->me_dbflags[dbi] = 0;
7981 int mdb_dbi_flags(MDB_env *env, MDB_dbi dbi, unsigned int *flags)
7983 /* We could return the flags for the FREE_DBI too but what's the point? */
7984 if (dbi < MAIN_DBI || dbi >= env->me_numdbs)
7986 *flags = env->me_dbflags[dbi];
7990 /** Add all the DB's pages to the free list.
7991 * @param[in] mc Cursor on the DB to free.
7992 * @param[in] subs non-Zero to check for sub-DBs in this DB.
7993 * @return 0 on success, non-zero on failure.
7996 mdb_drop0(MDB_cursor *mc, int subs)
8000 rc = mdb_page_search(mc, NULL, 0);
8001 if (rc == MDB_SUCCESS) {
8002 MDB_txn *txn = mc->mc_txn;
8007 /* LEAF2 pages have no nodes, cannot have sub-DBs */
8008 if (IS_LEAF2(mc->mc_pg[mc->mc_top]))
8011 mdb_cursor_copy(mc, &mx);
8012 while (mc->mc_snum > 0) {
8013 MDB_page *mp = mc->mc_pg[mc->mc_top];
8014 unsigned n = NUMKEYS(mp);
8016 for (i=0; i<n; i++) {
8017 ni = NODEPTR(mp, i);
8018 if (ni->mn_flags & F_BIGDATA) {
8021 memcpy(&pg, NODEDATA(ni), sizeof(pg));
8022 rc = mdb_page_get(txn, pg, &omp, NULL);
8025 assert(IS_OVERFLOW(omp));
8026 rc = mdb_midl_append_range(&txn->mt_free_pgs,
8030 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
8031 mdb_xcursor_init1(mc, ni);
8032 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
8038 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
8040 for (i=0; i<n; i++) {
8042 ni = NODEPTR(mp, i);
8045 mdb_midl_xappend(txn->mt_free_pgs, pg);
8050 mc->mc_ki[mc->mc_top] = i;
8051 rc = mdb_cursor_sibling(mc, 1);
8053 /* no more siblings, go back to beginning
8054 * of previous level.
8058 for (i=1; i<mc->mc_snum; i++) {
8060 mc->mc_pg[i] = mx.mc_pg[i];
8065 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
8066 } else if (rc == MDB_NOTFOUND) {
8072 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
8074 MDB_cursor *mc, *m2;
8077 if (!txn || !dbi || dbi >= txn->mt_numdbs || (unsigned)del > 1 || !(txn->mt_dbflags[dbi] & DB_VALID))
8080 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
8083 rc = mdb_cursor_open(txn, dbi, &mc);
8087 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
8088 /* Invalidate the dropped DB's cursors */
8089 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
8090 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
8094 /* Can't delete the main DB */
8095 if (del && dbi > MAIN_DBI) {
8096 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
8098 txn->mt_dbflags[dbi] = DB_STALE;
8099 mdb_dbi_close(txn->mt_env, dbi);
8102 /* reset the DB record, mark it dirty */
8103 txn->mt_dbflags[dbi] |= DB_DIRTY;
8104 txn->mt_dbs[dbi].md_depth = 0;
8105 txn->mt_dbs[dbi].md_branch_pages = 0;
8106 txn->mt_dbs[dbi].md_leaf_pages = 0;
8107 txn->mt_dbs[dbi].md_overflow_pages = 0;
8108 txn->mt_dbs[dbi].md_entries = 0;
8109 txn->mt_dbs[dbi].md_root = P_INVALID;
8111 txn->mt_flags |= MDB_TXN_DIRTY;
8114 mdb_cursor_close(mc);
8118 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
8120 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8123 txn->mt_dbxs[dbi].md_cmp = cmp;
8127 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
8129 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8132 txn->mt_dbxs[dbi].md_dcmp = cmp;
8136 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
8138 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8141 txn->mt_dbxs[dbi].md_rel = rel;
8145 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
8147 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8150 txn->mt_dbxs[dbi].md_relctx = ctx;
8154 int mdb_env_get_maxkeysize(MDB_env *env)
8156 return MDB_MAXKEYSIZE;
8159 int mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
8161 unsigned int i, rdrs;
8168 if (!env->me_txns) {
8169 return func("(no reader locks)\n", ctx);
8171 rdrs = env->me_txns->mti_numreaders;
8172 mr = env->me_txns->mti_readers;
8173 for (i=0; i<rdrs; i++) {
8178 if (mr[i].mr_txnid == (txnid_t)-1) {
8179 sprintf(buf, "%10d %"Z"x -\n", mr[i].mr_pid, tid);
8181 sprintf(buf, "%10d %"Z"x %"Z"u\n", mr[i].mr_pid, tid, mr[i].mr_txnid);
8185 func(" pid thread txnid\n", ctx);
8187 rc = func(buf, ctx);
8193 func("(no active readers)\n", ctx);
8198 /* insert pid into list if not already present.
8199 * return -1 if already present.
8201 static int mdb_pid_insert(pid_t *ids, pid_t pid)
8203 /* binary search of pid in list */
8205 unsigned cursor = 1;
8207 unsigned n = ids[0];
8210 unsigned pivot = n >> 1;
8211 cursor = base + pivot + 1;
8212 val = pid - ids[cursor];
8217 } else if ( val > 0 ) {
8222 /* found, so it's a duplicate */
8231 for (n = ids[0]; n > cursor; n--)
8237 int mdb_reader_check(MDB_env *env, int *dead)
8239 unsigned int i, j, rdrs;
8250 rdrs = env->me_txns->mti_numreaders;
8251 pids = malloc((rdrs+1) * sizeof(pid_t));
8255 mr = env->me_txns->mti_readers;
8257 for (i=0; i<rdrs; i++) {
8258 if (mr[i].mr_pid && mr[i].mr_pid != env->me_pid) {
8260 if (mdb_pid_insert(pids, pid) == 0) {
8261 if (!mdb_reader_pid(env, Pidcheck, pid)) {
8263 /* Recheck, a new process may have reused pid */
8264 if (!mdb_reader_pid(env, Pidcheck, pid)) {
8265 for (j=i; j<rdrs; j++)
8266 if (mr[j].mr_pid == pid) {
8271 UNLOCK_MUTEX_R(env);