2 * @brief memory-mapped database library
4 * A Btree-based database management library modeled loosely on the
5 * BerkeleyDB API, but much simplified.
8 * Copyright 2011-2013 Howard Chu, Symas Corp.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted only as authorized by the OpenLDAP
15 * A copy of this license is available in the file LICENSE in the
16 * top-level directory of the distribution or, alternatively, at
17 * <http://www.OpenLDAP.org/license.html>.
19 * This code is derived from btree.c written by Martin Hedenfalk.
21 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
23 * Permission to use, copy, modify, and distribute this software for any
24 * purpose with or without fee is hereby granted, provided that the above
25 * copyright notice and this permission notice appear in all copies.
27 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
28 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
29 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
30 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
31 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
32 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
33 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
38 #include <sys/types.h>
42 /** getpid() returns int; MinGW defines pid_t but MinGW64 typedefs it
43 * as int64 which is wrong. MSVC doesn't define it at all, so just
48 # include <sys/param.h>
50 # define LITTLE_ENDIAN 1234
51 # define BIG_ENDIAN 4321
52 # define BYTE_ORDER LITTLE_ENDIAN
54 # define SSIZE_MAX INT_MAX
58 #define MDB_PID_T pid_t
59 #include <sys/param.h>
62 #ifdef HAVE_SYS_FILE_H
79 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
80 #include <netinet/in.h>
81 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
84 #if defined(__APPLE__) || defined (BSD)
85 # define MDB_USE_POSIX_SEM 1
86 # define MDB_FDATASYNC fsync
87 #elif defined(ANDROID)
88 # define MDB_FDATASYNC fsync
93 #ifdef MDB_USE_POSIX_SEM
94 # define MDB_USE_HASH 1
95 #include <semaphore.h>
100 #include <valgrind/memcheck.h>
101 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
102 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
103 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
104 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
105 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
107 #define VGMEMP_CREATE(h,r,z)
108 #define VGMEMP_ALLOC(h,a,s)
109 #define VGMEMP_FREE(h,a)
110 #define VGMEMP_DESTROY(h)
111 #define VGMEMP_DEFINED(a,s)
115 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
116 /* Solaris just defines one or the other */
117 # define LITTLE_ENDIAN 1234
118 # define BIG_ENDIAN 4321
119 # ifdef _LITTLE_ENDIAN
120 # define BYTE_ORDER LITTLE_ENDIAN
122 # define BYTE_ORDER BIG_ENDIAN
125 # define BYTE_ORDER __BYTE_ORDER
129 #ifndef LITTLE_ENDIAN
130 #define LITTLE_ENDIAN __LITTLE_ENDIAN
133 #define BIG_ENDIAN __BIG_ENDIAN
136 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
137 #define MISALIGNED_OK 1
143 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
144 # error "Unknown or unsupported endianness (BYTE_ORDER)"
145 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
146 # error "Two's complement, reasonably sized integer types, please"
149 /** @defgroup internal MDB Internals
152 /** @defgroup compat Compatibility Macros
153 * A bunch of macros to minimize the amount of platform-specific ifdefs
154 * needed throughout the rest of the code. When the features this library
155 * needs are similar enough to POSIX to be hidden in a one-or-two line
156 * replacement, this macro approach is used.
160 /** Wrapper around __func__, which is a C99 feature */
161 #if __STDC_VERSION__ >= 199901L
162 # define mdb_func_ __func__
163 #elif __GNUC__ >= 2 || _MSC_VER >= 1300
164 # define mdb_func_ __FUNCTION__
166 /* If a debug message says <mdb_unknown>(), update the #if statements above */
167 # define mdb_func_ "<mdb_unknown>"
171 #define MDB_USE_HASH 1
172 #define MDB_PIDLOCK 0
173 #define pthread_t DWORD
174 #define pthread_mutex_t HANDLE
175 #define pthread_key_t DWORD
176 #define pthread_self() GetCurrentThreadId()
177 #define pthread_key_create(x,y) \
178 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
179 #define pthread_key_delete(x) TlsFree(x)
180 #define pthread_getspecific(x) TlsGetValue(x)
181 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
182 #define pthread_mutex_unlock(x) ReleaseMutex(x)
183 #define pthread_mutex_lock(x) WaitForSingleObject(x, INFINITE)
184 #define LOCK_MUTEX_R(env) pthread_mutex_lock((env)->me_rmutex)
185 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock((env)->me_rmutex)
186 #define LOCK_MUTEX_W(env) pthread_mutex_lock((env)->me_wmutex)
187 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock((env)->me_wmutex)
188 #define getpid() GetCurrentProcessId()
189 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
190 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
191 #define ErrCode() GetLastError()
192 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
193 #define close(fd) (CloseHandle(fd) ? 0 : -1)
194 #define munmap(ptr,len) UnmapViewOfFile(ptr)
195 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
196 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
198 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
203 #define Z "z" /**< printf format modifier for size_t */
205 /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
206 #define MDB_PIDLOCK 1
208 #ifdef MDB_USE_POSIX_SEM
210 #define LOCK_MUTEX_R(env) mdb_sem_wait((env)->me_rmutex)
211 #define UNLOCK_MUTEX_R(env) sem_post((env)->me_rmutex)
212 #define LOCK_MUTEX_W(env) mdb_sem_wait((env)->me_wmutex)
213 #define UNLOCK_MUTEX_W(env) sem_post((env)->me_wmutex)
216 mdb_sem_wait(sem_t *sem)
219 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
224 /** Lock the reader mutex.
226 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
227 /** Unlock the reader mutex.
229 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
231 /** Lock the writer mutex.
232 * Only a single write transaction is allowed at a time. Other writers
233 * will block waiting for this mutex.
235 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
236 /** Unlock the writer mutex.
238 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
239 #endif /* MDB_USE_POSIX_SEM */
241 /** Get the error code for the last failed system function.
243 #define ErrCode() errno
245 /** An abstraction for a file handle.
246 * On POSIX systems file handles are small integers. On Windows
247 * they're opaque pointers.
251 /** A value for an invalid file handle.
252 * Mainly used to initialize file variables and signify that they are
255 #define INVALID_HANDLE_VALUE (-1)
257 /** Get the size of a memory page for the system.
258 * This is the basic size that the platform's memory manager uses, and is
259 * fundamental to the use of memory-mapped files.
261 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
264 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
267 #define MNAME_LEN (sizeof(pthread_mutex_t))
273 /** A flag for opening a file and requesting synchronous data writes.
274 * This is only used when writing a meta page. It's not strictly needed;
275 * we could just do a normal write and then immediately perform a flush.
276 * But if this flag is available it saves us an extra system call.
278 * @note If O_DSYNC is undefined but exists in /usr/include,
279 * preferably set some compiler flag to get the definition.
280 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
283 # define MDB_DSYNC O_DSYNC
287 /** Function for flushing the data of a file. Define this to fsync
288 * if fdatasync() is not supported.
290 #ifndef MDB_FDATASYNC
291 # define MDB_FDATASYNC fdatasync
295 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
306 /** A page number in the database.
307 * Note that 64 bit page numbers are overkill, since pages themselves
308 * already represent 12-13 bits of addressable memory, and the OS will
309 * always limit applications to a maximum of 63 bits of address space.
311 * @note In the #MDB_node structure, we only store 48 bits of this value,
312 * which thus limits us to only 60 bits of addressable data.
314 typedef MDB_ID pgno_t;
316 /** A transaction ID.
317 * See struct MDB_txn.mt_txnid for details.
319 typedef MDB_ID txnid_t;
321 /** @defgroup debug Debug Macros
325 /** Enable debug output. Needs variable argument macros (a C99 feature).
326 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
327 * read from and written to the database (used for free space management).
333 static int mdb_debug;
334 static txnid_t mdb_debug_start;
336 /** Print a debug message with printf formatting.
337 * Requires double parenthesis around 2 or more args.
339 # define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
340 # define DPRINTF0(fmt, ...) \
341 fprintf(stderr, "%s:%d " fmt "\n", mdb_func_, __LINE__, __VA_ARGS__)
343 # define DPRINTF(args) ((void) 0)
345 /** Print a debug string.
346 * The string is printed literally, with no format processing.
348 #define DPUTS(arg) DPRINTF(("%s", arg))
349 /** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
351 (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
354 /** @brief The maximum size of a database page.
356 * This is 32k, since it must fit in #MDB_page.#mp_upper.
358 * LMDB will use database pages < OS pages if needed.
359 * That causes more I/O in write transactions: The OS must
360 * know (read) the whole page before writing a partial page.
362 * Note that we don't currently support Huge pages. On Linux,
363 * regular data files cannot use Huge pages, and in general
364 * Huge pages aren't actually pageable. We rely on the OS
365 * demand-pager to read our data and page it out when memory
366 * pressure from other processes is high. So until OSs have
367 * actual paging support for Huge pages, they're not viable.
369 #define MAX_PAGESIZE 0x8000
371 /** The minimum number of keys required in a database page.
372 * Setting this to a larger value will place a smaller bound on the
373 * maximum size of a data item. Data items larger than this size will
374 * be pushed into overflow pages instead of being stored directly in
375 * the B-tree node. This value used to default to 4. With a page size
376 * of 4096 bytes that meant that any item larger than 1024 bytes would
377 * go into an overflow page. That also meant that on average 2-3KB of
378 * each overflow page was wasted space. The value cannot be lower than
379 * 2 because then there would no longer be a tree structure. With this
380 * value, items larger than 2KB will go into overflow pages, and on
381 * average only 1KB will be wasted.
383 #define MDB_MINKEYS 2
385 /** A stamp that identifies a file as an MDB file.
386 * There's nothing special about this value other than that it is easily
387 * recognizable, and it will reflect any byte order mismatches.
389 #define MDB_MAGIC 0xBEEFC0DE
391 /** The version number for a database's datafile format. */
392 #define MDB_DATA_VERSION 1
393 /** The version number for a database's lockfile format. */
394 #define MDB_LOCK_VERSION 1
396 /** @brief The max size of a key we can write, or 0 for dynamic max.
398 * Define this as 0 to compute the max from the page size. 511
399 * is default for backwards compat: liblmdb <= 0.9.10 can break
400 * when modifying a DB with keys/dupsort data bigger than its max.
402 * Data items in an #MDB_DUPSORT database are also limited to
403 * this size, since they're actually keys of a sub-DB. Keys and
404 * #MDB_DUPSORT data items must fit on a node in a regular page.
406 #ifndef MDB_MAXKEYSIZE
407 #define MDB_MAXKEYSIZE 511
410 /** The maximum size of a key we can write to the environment. */
412 #define ENV_MAXKEY(env) (MDB_MAXKEYSIZE)
414 #define ENV_MAXKEY(env) ((env)->me_maxkey)
417 /** @brief The maximum size of a data item.
419 * We only store a 32 bit value for node sizes.
421 #define MAXDATASIZE 0xffffffffUL
424 /** Key size which fits in a #DKBUF.
427 #define DKBUF_MAXKEYSIZE ((MDB_MAXKEYSIZE) > 0 ? (MDB_MAXKEYSIZE) : 511)
430 * This is used for printing a hex dump of a key's contents.
432 #define DKBUF char kbuf[DKBUF_MAXKEYSIZE*2+1]
433 /** Display a key in hex.
435 * Invoke a function to display a key in hex.
437 #define DKEY(x) mdb_dkey(x, kbuf)
443 /** An invalid page number.
444 * Mainly used to denote an empty tree.
446 #define P_INVALID (~(pgno_t)0)
448 /** Test if the flags \b f are set in a flag word \b w. */
449 #define F_ISSET(w, f) (((w) & (f)) == (f))
451 /** Round \b n up to an even number. */
452 #define EVEN(n) (((n) + 1U) & -2) /* sign-extending -2 to match n+1U */
454 /** Used for offsets within a single page.
455 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
458 typedef uint16_t indx_t;
460 /** Default size of memory map.
461 * This is certainly too small for any actual applications. Apps should always set
462 * the size explicitly using #mdb_env_set_mapsize().
464 #define DEFAULT_MAPSIZE 1048576
466 /** @defgroup readers Reader Lock Table
467 * Readers don't acquire any locks for their data access. Instead, they
468 * simply record their transaction ID in the reader table. The reader
469 * mutex is needed just to find an empty slot in the reader table. The
470 * slot's address is saved in thread-specific data so that subsequent read
471 * transactions started by the same thread need no further locking to proceed.
473 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
475 * No reader table is used if the database is on a read-only filesystem, or
476 * if #MDB_NOLOCK is set.
478 * Since the database uses multi-version concurrency control, readers don't
479 * actually need any locking. This table is used to keep track of which
480 * readers are using data from which old transactions, so that we'll know
481 * when a particular old transaction is no longer in use. Old transactions
482 * that have discarded any data pages can then have those pages reclaimed
483 * for use by a later write transaction.
485 * The lock table is constructed such that reader slots are aligned with the
486 * processor's cache line size. Any slot is only ever used by one thread.
487 * This alignment guarantees that there will be no contention or cache
488 * thrashing as threads update their own slot info, and also eliminates
489 * any need for locking when accessing a slot.
491 * A writer thread will scan every slot in the table to determine the oldest
492 * outstanding reader transaction. Any freed pages older than this will be
493 * reclaimed by the writer. The writer doesn't use any locks when scanning
494 * this table. This means that there's no guarantee that the writer will
495 * see the most up-to-date reader info, but that's not required for correct
496 * operation - all we need is to know the upper bound on the oldest reader,
497 * we don't care at all about the newest reader. So the only consequence of
498 * reading stale information here is that old pages might hang around a
499 * while longer before being reclaimed. That's actually good anyway, because
500 * the longer we delay reclaiming old pages, the more likely it is that a
501 * string of contiguous pages can be found after coalescing old pages from
502 * many old transactions together.
505 /** Number of slots in the reader table.
506 * This value was chosen somewhat arbitrarily. 126 readers plus a
507 * couple mutexes fit exactly into 8KB on my development machine.
508 * Applications should set the table size using #mdb_env_set_maxreaders().
510 #define DEFAULT_READERS 126
512 /** The size of a CPU cache line in bytes. We want our lock structures
513 * aligned to this size to avoid false cache line sharing in the
515 * This value works for most CPUs. For Itanium this should be 128.
521 /** The information we store in a single slot of the reader table.
522 * In addition to a transaction ID, we also record the process and
523 * thread ID that owns a slot, so that we can detect stale information,
524 * e.g. threads or processes that went away without cleaning up.
525 * @note We currently don't check for stale records. We simply re-init
526 * the table when we know that we're the only process opening the
529 typedef struct MDB_rxbody {
530 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
531 * Multiple readers that start at the same time will probably have the
532 * same ID here. Again, it's not important to exclude them from
533 * anything; all we need to know is which version of the DB they
534 * started from so we can avoid overwriting any data used in that
535 * particular version.
538 /** The process ID of the process owning this reader txn. */
540 /** The thread ID of the thread owning this txn. */
544 /** The actual reader record, with cacheline padding. */
545 typedef struct MDB_reader {
548 /** shorthand for mrb_txnid */
549 #define mr_txnid mru.mrx.mrb_txnid
550 #define mr_pid mru.mrx.mrb_pid
551 #define mr_tid mru.mrx.mrb_tid
552 /** cache line alignment */
553 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
557 /** The header for the reader table.
558 * The table resides in a memory-mapped file. (This is a different file
559 * than is used for the main database.)
561 * For POSIX the actual mutexes reside in the shared memory of this
562 * mapped file. On Windows, mutexes are named objects allocated by the
563 * kernel; we store the mutex names in this mapped file so that other
564 * processes can grab them. This same approach is also used on
565 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
566 * process-shared POSIX mutexes. For these cases where a named object
567 * is used, the object name is derived from a 64 bit FNV hash of the
568 * environment pathname. As such, naming collisions are extremely
569 * unlikely. If a collision occurs, the results are unpredictable.
571 typedef struct MDB_txbody {
572 /** Stamp identifying this as an MDB file. It must be set
575 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
577 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
578 char mtb_rmname[MNAME_LEN];
580 /** Mutex protecting access to this table.
581 * This is the reader lock that #LOCK_MUTEX_R acquires.
583 pthread_mutex_t mtb_mutex;
585 /** The ID of the last transaction committed to the database.
586 * This is recorded here only for convenience; the value can always
587 * be determined by reading the main database meta pages.
590 /** The number of slots that have been used in the reader table.
591 * This always records the maximum count, it is not decremented
592 * when readers release their slots.
594 unsigned mtb_numreaders;
597 /** The actual reader table definition. */
598 typedef struct MDB_txninfo {
601 #define mti_magic mt1.mtb.mtb_magic
602 #define mti_format mt1.mtb.mtb_format
603 #define mti_mutex mt1.mtb.mtb_mutex
604 #define mti_rmname mt1.mtb.mtb_rmname
605 #define mti_txnid mt1.mtb.mtb_txnid
606 #define mti_numreaders mt1.mtb.mtb_numreaders
607 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
610 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
611 char mt2_wmname[MNAME_LEN];
612 #define mti_wmname mt2.mt2_wmname
614 pthread_mutex_t mt2_wmutex;
615 #define mti_wmutex mt2.mt2_wmutex
617 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
619 MDB_reader mti_readers[1];
622 /** Lockfile format signature: version, features and field layout */
623 #define MDB_LOCK_FORMAT \
625 ((MDB_LOCK_VERSION) \
626 /* Flags which describe functionality */ \
627 + (((MDB_PIDLOCK) != 0) << 16)))
630 /** Common header for all page types.
631 * Overflow records occupy a number of contiguous pages with no
632 * headers on any page after the first.
634 typedef struct MDB_page {
635 #define mp_pgno mp_p.p_pgno
636 #define mp_next mp_p.p_next
638 pgno_t p_pgno; /**< page number */
639 void * p_next; /**< for in-memory list of freed structs */
642 /** @defgroup mdb_page Page Flags
644 * Flags for the page headers.
647 #define P_BRANCH 0x01 /**< branch page */
648 #define P_LEAF 0x02 /**< leaf page */
649 #define P_OVERFLOW 0x04 /**< overflow page */
650 #define P_META 0x08 /**< meta page */
651 #define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
652 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
653 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
654 #define P_KEEP 0x8000 /**< leave this page alone during spill */
656 uint16_t mp_flags; /**< @ref mdb_page */
657 #define mp_lower mp_pb.pb.pb_lower
658 #define mp_upper mp_pb.pb.pb_upper
659 #define mp_pages mp_pb.pb_pages
662 indx_t pb_lower; /**< lower bound of free space */
663 indx_t pb_upper; /**< upper bound of free space */
665 uint32_t pb_pages; /**< number of overflow pages */
667 indx_t mp_ptrs[1]; /**< dynamic size */
670 /** Size of the page header, excluding dynamic data at the end */
671 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
673 /** Address of first usable data byte in a page, after the header */
674 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
676 /** Number of nodes on a page */
677 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
679 /** The amount of space remaining in the page */
680 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
682 /** The percentage of space used in the page, in tenths of a percent. */
683 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
684 ((env)->me_psize - PAGEHDRSZ))
685 /** The minimum page fill factor, in tenths of a percent.
686 * Pages emptier than this are candidates for merging.
688 #define FILL_THRESHOLD 250
690 /** Test if a page is a leaf page */
691 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
692 /** Test if a page is a LEAF2 page */
693 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
694 /** Test if a page is a branch page */
695 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
696 /** Test if a page is an overflow page */
697 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
698 /** Test if a page is a sub page */
699 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
701 /** The number of overflow pages needed to store the given size. */
702 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
704 /** Header for a single key/data pair within a page.
705 * Used in pages of type #P_BRANCH and #P_LEAF without #P_LEAF2.
706 * We guarantee 2-byte alignment for 'MDB_node's.
708 typedef struct MDB_node {
709 /** lo and hi are used for data size on leaf nodes and for
710 * child pgno on branch nodes. On 64 bit platforms, flags
711 * is also used for pgno. (Branch nodes have no flags).
712 * They are in host byte order in case that lets some
713 * accesses be optimized into a 32-bit word access.
715 #if BYTE_ORDER == LITTLE_ENDIAN
716 unsigned short mn_lo, mn_hi; /**< part of data size or pgno */
718 unsigned short mn_hi, mn_lo;
720 /** @defgroup mdb_node Node Flags
722 * Flags for node headers.
725 #define F_BIGDATA 0x01 /**< data put on overflow page */
726 #define F_SUBDATA 0x02 /**< data is a sub-database */
727 #define F_DUPDATA 0x04 /**< data has duplicates */
729 /** valid flags for #mdb_node_add() */
730 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
733 unsigned short mn_flags; /**< @ref mdb_node */
734 unsigned short mn_ksize; /**< key size */
735 char mn_data[1]; /**< key and data are appended here */
738 /** Size of the node header, excluding dynamic data at the end */
739 #define NODESIZE offsetof(MDB_node, mn_data)
741 /** Bit position of top word in page number, for shifting mn_flags */
742 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
744 /** Size of a node in a branch page with a given key.
745 * This is just the node header plus the key, there is no data.
747 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
749 /** Size of a node in a leaf page with a given key and data.
750 * This is node header plus key plus data size.
752 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
754 /** Address of node \b i in page \b p */
755 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
757 /** Address of the key for the node */
758 #define NODEKEY(node) (void *)((node)->mn_data)
760 /** Address of the data for a node */
761 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
763 /** Get the page number pointed to by a branch node */
764 #define NODEPGNO(node) \
765 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
766 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
767 /** Set the page number in a branch node */
768 #define SETPGNO(node,pgno) do { \
769 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
770 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
772 /** Get the size of the data in a leaf node */
773 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
774 /** Set the size of the data for a leaf node */
775 #define SETDSZ(node,size) do { \
776 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
777 /** The size of a key in a node */
778 #define NODEKSZ(node) ((node)->mn_ksize)
780 /** Copy a page number from src to dst */
782 #define COPY_PGNO(dst,src) dst = src
784 #if SIZE_MAX > 4294967295UL
785 #define COPY_PGNO(dst,src) do { \
786 unsigned short *s, *d; \
787 s = (unsigned short *)&(src); \
788 d = (unsigned short *)&(dst); \
795 #define COPY_PGNO(dst,src) do { \
796 unsigned short *s, *d; \
797 s = (unsigned short *)&(src); \
798 d = (unsigned short *)&(dst); \
804 /** The address of a key in a LEAF2 page.
805 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
806 * There are no node headers, keys are stored contiguously.
808 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
810 /** Set the \b node's key into \b keyptr, if requested. */
811 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
812 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
814 /** Set the \b node's key into \b key. */
815 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
817 /** Information about a single database in the environment. */
818 typedef struct MDB_db {
819 uint32_t md_pad; /**< also ksize for LEAF2 pages */
820 uint16_t md_flags; /**< @ref mdb_dbi_open */
821 uint16_t md_depth; /**< depth of this tree */
822 pgno_t md_branch_pages; /**< number of internal pages */
823 pgno_t md_leaf_pages; /**< number of leaf pages */
824 pgno_t md_overflow_pages; /**< number of overflow pages */
825 size_t md_entries; /**< number of data items */
826 pgno_t md_root; /**< the root page of this tree */
829 /** mdb_dbi_open flags */
830 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
831 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
832 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
833 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
835 /** Handle for the DB used to track free pages. */
837 /** Handle for the default DB. */
840 /** Meta page content.
841 * A meta page is the start point for accessing a database snapshot.
842 * Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
844 typedef struct MDB_meta {
845 /** Stamp identifying this as an MDB file. It must be set
848 /** Version number of this lock file. Must be set to #MDB_DATA_VERSION. */
850 void *mm_address; /**< address for fixed mapping */
851 size_t mm_mapsize; /**< size of mmap region */
852 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
853 /** The size of pages used in this DB */
854 #define mm_psize mm_dbs[0].md_pad
855 /** Any persistent environment flags. @ref mdb_env */
856 #define mm_flags mm_dbs[0].md_flags
857 pgno_t mm_last_pg; /**< last used page in file */
858 txnid_t mm_txnid; /**< txnid that committed this page */
861 /** Buffer for a stack-allocated meta page.
862 * The members define size and alignment, and silence type
863 * aliasing warnings. They are not used directly; that could
864 * mean incorrectly using several union members in parallel.
866 typedef union MDB_metabuf {
869 char mm_pad[PAGEHDRSZ];
874 /** Auxiliary DB info.
875 * The information here is mostly static/read-only. There is
876 * only a single copy of this record in the environment.
878 typedef struct MDB_dbx {
879 MDB_val md_name; /**< name of the database */
880 MDB_cmp_func *md_cmp; /**< function for comparing keys */
881 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
882 MDB_rel_func *md_rel; /**< user relocate function */
883 void *md_relctx; /**< user-provided context for md_rel */
886 /** A database transaction.
887 * Every operation requires a transaction handle.
890 MDB_txn *mt_parent; /**< parent of a nested txn */
891 MDB_txn *mt_child; /**< nested txn under this txn */
892 pgno_t mt_next_pgno; /**< next unallocated page */
893 /** The ID of this transaction. IDs are integers incrementing from 1.
894 * Only committed write transactions increment the ID. If a transaction
895 * aborts, the ID may be re-used by the next writer.
898 MDB_env *mt_env; /**< the DB environment */
899 /** The list of pages that became unused during this transaction.
902 /** The sorted list of dirty pages we temporarily wrote to disk
903 * because the dirty list was full. page numbers in here are
904 * shifted left by 1, deleted slots have the LSB set.
906 MDB_IDL mt_spill_pgs;
908 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
910 /** For read txns: This thread/txn's reader table slot, or NULL. */
913 /** Array of records for each DB known in the environment. */
915 /** Array of MDB_db records for each known DB */
917 /** @defgroup mt_dbflag Transaction DB Flags
921 #define DB_DIRTY 0x01 /**< DB was modified or is DUPSORT data */
922 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
923 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
924 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
926 /** In write txns, array of cursors for each DB */
927 MDB_cursor **mt_cursors;
928 /** Array of flags for each DB */
929 unsigned char *mt_dbflags;
930 /** Number of DB records in use. This number only ever increments;
931 * we don't decrement it when individual DB handles are closed.
935 /** @defgroup mdb_txn Transaction Flags
939 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
940 #define MDB_TXN_ERROR 0x02 /**< an error has occurred */
941 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
942 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
944 unsigned int mt_flags; /**< @ref mdb_txn */
945 /** dirty_list room: Array size - #dirty pages visible to this txn.
946 * Includes ancestor txns' dirty pages not hidden by other txns'
947 * dirty/spilled pages. Thus commit(nested txn) has room to merge
948 * dirty_list into mt_parent after freeing hidden mt_parent pages.
950 unsigned int mt_dirty_room;
953 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
954 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
955 * raise this on a 64 bit machine.
957 #define CURSOR_STACK 32
961 /** Cursors are used for all DB operations.
962 * A cursor holds a path of (page pointer, key index) from the DB
963 * root to a position in the DB, plus other state. #MDB_DUPSORT
964 * cursors include an xcursor to the current data item. Write txns
965 * track their cursors and keep them up to date when data moves.
966 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
967 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
970 /** Next cursor on this DB in this txn */
972 /** Backup of the original cursor if this cursor is a shadow */
973 MDB_cursor *mc_backup;
974 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
975 struct MDB_xcursor *mc_xcursor;
976 /** The transaction that owns this cursor */
978 /** The database handle this cursor operates on */
980 /** The database record for this cursor */
982 /** The database auxiliary record for this cursor */
984 /** The @ref mt_dbflag for this database */
985 unsigned char *mc_dbflag;
986 unsigned short mc_snum; /**< number of pushed pages */
987 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
988 /** @defgroup mdb_cursor Cursor Flags
990 * Cursor state flags.
993 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
994 #define C_EOF 0x02 /**< No more data */
995 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
996 #define C_DEL 0x08 /**< last op was a cursor_del */
997 #define C_SPLITTING 0x20 /**< Cursor is in page_split */
998 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
1000 unsigned int mc_flags; /**< @ref mdb_cursor */
1001 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
1002 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
1005 /** Context for sorted-dup records.
1006 * We could have gone to a fully recursive design, with arbitrarily
1007 * deep nesting of sub-databases. But for now we only handle these
1008 * levels - main DB, optional sub-DB, sorted-duplicate DB.
1010 typedef struct MDB_xcursor {
1011 /** A sub-cursor for traversing the Dup DB */
1012 MDB_cursor mx_cursor;
1013 /** The database record for this Dup DB */
1015 /** The auxiliary DB record for this Dup DB */
1017 /** The @ref mt_dbflag for this Dup DB */
1018 unsigned char mx_dbflag;
1021 /** State of FreeDB old pages, stored in the MDB_env */
1022 typedef struct MDB_pgstate {
1023 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1024 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1027 /** The database environment. */
1029 HANDLE me_fd; /**< The main data file */
1030 HANDLE me_lfd; /**< The lock file */
1031 HANDLE me_mfd; /**< just for writing the meta pages */
1032 /** Failed to update the meta page. Probably an I/O error. */
1033 #define MDB_FATAL_ERROR 0x80000000U
1034 /** Some fields are initialized. */
1035 #define MDB_ENV_ACTIVE 0x20000000U
1036 /** me_txkey is set */
1037 #define MDB_ENV_TXKEY 0x10000000U
1038 /** Have liveness lock in reader table */
1039 #define MDB_LIVE_READER 0x08000000U
1040 uint32_t me_flags; /**< @ref mdb_env */
1041 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1042 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1043 unsigned int me_maxreaders; /**< size of the reader table */
1044 unsigned int me_numreaders; /**< max numreaders set by this env */
1045 MDB_dbi me_numdbs; /**< number of DBs opened */
1046 MDB_dbi me_maxdbs; /**< size of the DB table */
1047 MDB_PID_T me_pid; /**< process ID of this env */
1048 char *me_path; /**< path to the DB files */
1049 char *me_map; /**< the memory map of the data file */
1050 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1051 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
1052 void *me_pbuf; /**< scratch area for DUPSORT put() */
1053 MDB_txn *me_txn; /**< current write transaction */
1054 size_t me_mapsize; /**< size of the data memory map */
1055 off_t me_size; /**< current file size */
1056 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1057 MDB_dbx *me_dbxs; /**< array of static DB info */
1058 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1059 pthread_key_t me_txkey; /**< thread-key for readers */
1060 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1061 # define me_pglast me_pgstate.mf_pglast
1062 # define me_pghead me_pgstate.mf_pghead
1063 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1064 /** IDL of pages that became unused in a write txn */
1065 MDB_IDL me_free_pgs;
1066 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1067 MDB_ID2L me_dirty_list;
1068 /** Max number of freelist items that can fit in a single overflow page */
1070 /** Max size of a node on a page */
1071 unsigned int me_nodemax;
1072 #if !(MDB_MAXKEYSIZE)
1073 unsigned int me_maxkey; /**< max size of a key */
1076 int me_pidquery; /**< Used in OpenProcess */
1077 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
1079 #elif defined(MDB_USE_POSIX_SEM)
1080 sem_t *me_rmutex; /* Shared mutexes are not supported */
1083 void *me_userctx; /**< User-settable context */
1086 /** Nested transaction */
1087 typedef struct MDB_ntxn {
1088 MDB_txn mnt_txn; /**< the transaction */
1089 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1092 /** max number of pages to commit in one writev() call */
1093 #define MDB_COMMIT_PAGES 64
1094 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1095 #undef MDB_COMMIT_PAGES
1096 #define MDB_COMMIT_PAGES IOV_MAX
1099 /* max bytes to write in one call */
1100 #define MAX_WRITE (0x80000000U >> (sizeof(ssize_t) == 4))
1102 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1103 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1104 static int mdb_page_touch(MDB_cursor *mc);
1106 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp, int *lvl);
1107 static int mdb_page_search_root(MDB_cursor *mc,
1108 MDB_val *key, int modify);
1109 #define MDB_PS_MODIFY 1
1110 #define MDB_PS_ROOTONLY 2
1111 #define MDB_PS_FIRST 4
1112 #define MDB_PS_LAST 8
1113 static int mdb_page_search(MDB_cursor *mc,
1114 MDB_val *key, int flags);
1115 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1117 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1118 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1119 pgno_t newpgno, unsigned int nflags);
1121 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1122 static int mdb_env_pick_meta(const MDB_env *env);
1123 static int mdb_env_write_meta(MDB_txn *txn);
1124 #if !(defined(_WIN32) || defined(MDB_USE_POSIX_SEM)) /* Drop unused excl arg */
1125 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1127 static void mdb_env_close0(MDB_env *env, int excl);
1129 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1130 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1131 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1132 static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
1133 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1134 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
1135 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1136 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1137 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1139 static int mdb_rebalance(MDB_cursor *mc);
1140 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1142 static void mdb_cursor_pop(MDB_cursor *mc);
1143 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1145 static int mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
1146 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1147 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1148 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1149 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1151 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1152 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1154 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1155 static void mdb_xcursor_init0(MDB_cursor *mc);
1156 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1158 static int mdb_drop0(MDB_cursor *mc, int subs);
1159 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1162 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1166 static SECURITY_DESCRIPTOR mdb_null_sd;
1167 static SECURITY_ATTRIBUTES mdb_all_sa;
1168 static int mdb_sec_inited;
1171 /** Return the library version info. */
1173 mdb_version(int *major, int *minor, int *patch)
1175 if (major) *major = MDB_VERSION_MAJOR;
1176 if (minor) *minor = MDB_VERSION_MINOR;
1177 if (patch) *patch = MDB_VERSION_PATCH;
1178 return MDB_VERSION_STRING;
1181 /** Table of descriptions for MDB @ref errors */
1182 static char *const mdb_errstr[] = {
1183 "MDB_KEYEXIST: Key/data pair already exists",
1184 "MDB_NOTFOUND: No matching key/data pair found",
1185 "MDB_PAGE_NOTFOUND: Requested page not found",
1186 "MDB_CORRUPTED: Located page was wrong type",
1187 "MDB_PANIC: Update of meta page failed",
1188 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1189 "MDB_INVALID: File is not an MDB file",
1190 "MDB_MAP_FULL: Environment mapsize limit reached",
1191 "MDB_DBS_FULL: Environment maxdbs limit reached",
1192 "MDB_READERS_FULL: Environment maxreaders limit reached",
1193 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1194 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1195 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1196 "MDB_PAGE_FULL: Internal error - page has no more space",
1197 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1198 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1199 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1200 "MDB_BAD_TXN: Transaction cannot recover - it must be aborted",
1201 "MDB_BAD_VALSIZE: Too big key/data, key is empty, or wrong DUPFIXED size",
1205 mdb_strerror(int err)
1209 return ("Successful return: 0");
1211 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1212 i = err - MDB_KEYEXIST;
1213 return mdb_errstr[i];
1216 return strerror(err);
1220 /** Return the page number of \b mp which may be sub-page, for debug output */
1222 mdb_dbg_pgno(MDB_page *mp)
1225 COPY_PGNO(ret, mp->mp_pgno);
1229 /** Display a key in hexadecimal and return the address of the result.
1230 * @param[in] key the key to display
1231 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1232 * @return The key in hexadecimal form.
1235 mdb_dkey(MDB_val *key, char *buf)
1238 unsigned char *c = key->mv_data;
1244 if (key->mv_size > DKBUF_MAXKEYSIZE)
1245 return "MDB_MAXKEYSIZE";
1246 /* may want to make this a dynamic check: if the key is mostly
1247 * printable characters, print it as-is instead of converting to hex.
1251 for (i=0; i<key->mv_size; i++)
1252 ptr += sprintf(ptr, "%02x", *c++);
1254 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1259 /** Display all the keys in the page. */
1261 mdb_page_list(MDB_page *mp)
1264 unsigned int i, nkeys, nsize, total = 0;
1268 nkeys = NUMKEYS(mp);
1269 fprintf(stderr, "Page %"Z"u numkeys %d\n", mdb_dbg_pgno(mp), nkeys);
1270 for (i=0; i<nkeys; i++) {
1271 node = NODEPTR(mp, i);
1272 key.mv_size = node->mn_ksize;
1273 key.mv_data = node->mn_data;
1274 nsize = NODESIZE + key.mv_size;
1275 if (IS_BRANCH(mp)) {
1276 fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
1280 if (F_ISSET(node->mn_flags, F_BIGDATA))
1281 nsize += sizeof(pgno_t);
1283 nsize += NODEDSZ(node);
1285 nsize += sizeof(indx_t);
1286 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1288 total = EVEN(total);
1290 fprintf(stderr, "Total: %d\n", total);
1294 mdb_cursor_chk(MDB_cursor *mc)
1300 if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1301 for (i=0; i<mc->mc_top; i++) {
1303 node = NODEPTR(mp, mc->mc_ki[i]);
1304 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1307 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1313 /** Count all the pages in each DB and in the freelist
1314 * and make sure it matches the actual number of pages
1317 static void mdb_audit(MDB_txn *txn)
1321 MDB_ID freecount, count;
1326 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1327 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1328 freecount += *(MDB_ID *)data.mv_data;
1331 for (i = 0; i<txn->mt_numdbs; i++) {
1333 mdb_cursor_init(&mc, txn, i, &mx);
1334 if (txn->mt_dbs[i].md_root == P_INVALID)
1336 count += txn->mt_dbs[i].md_branch_pages +
1337 txn->mt_dbs[i].md_leaf_pages +
1338 txn->mt_dbs[i].md_overflow_pages;
1339 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1340 mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1344 mp = mc.mc_pg[mc.mc_top];
1345 for (j=0; j<NUMKEYS(mp); j++) {
1346 MDB_node *leaf = NODEPTR(mp, j);
1347 if (leaf->mn_flags & F_SUBDATA) {
1349 memcpy(&db, NODEDATA(leaf), sizeof(db));
1350 count += db.md_branch_pages + db.md_leaf_pages +
1351 db.md_overflow_pages;
1355 while (mdb_cursor_sibling(&mc, 1) == 0);
1358 if (freecount + count + 2 /* metapages */ != txn->mt_next_pgno) {
1359 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1360 txn->mt_txnid, freecount, count+2, freecount+count+2, txn->mt_next_pgno);
1366 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1368 return txn->mt_dbxs[dbi].md_cmp(a, b);
1372 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1374 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1377 /** Allocate memory for a page.
1378 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1381 mdb_page_malloc(MDB_txn *txn, unsigned num)
1383 MDB_env *env = txn->mt_env;
1384 MDB_page *ret = env->me_dpages;
1385 size_t psize = env->me_psize, sz = psize, off;
1386 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1387 * For a single page alloc, we init everything after the page header.
1388 * For multi-page, we init the final page; if the caller needed that
1389 * many pages they will be filling in at least up to the last page.
1393 VGMEMP_ALLOC(env, ret, sz);
1394 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1395 env->me_dpages = ret->mp_next;
1398 psize -= off = PAGEHDRSZ;
1403 if ((ret = malloc(sz)) != NULL) {
1404 VGMEMP_ALLOC(env, ret, sz);
1405 if (!(env->me_flags & MDB_NOMEMINIT)) {
1406 memset((char *)ret + off, 0, psize);
1410 txn->mt_flags |= MDB_TXN_ERROR;
1415 /** Free a single page.
1416 * Saves single pages to a list, for future reuse.
1417 * (This is not used for multi-page overflow pages.)
1420 mdb_page_free(MDB_env *env, MDB_page *mp)
1422 mp->mp_next = env->me_dpages;
1423 VGMEMP_FREE(env, mp);
1424 env->me_dpages = mp;
1427 /** Free a dirty page */
1429 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1431 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1432 mdb_page_free(env, dp);
1434 /* large pages just get freed directly */
1435 VGMEMP_FREE(env, dp);
1440 /** Return all dirty pages to dpage list */
1442 mdb_dlist_free(MDB_txn *txn)
1444 MDB_env *env = txn->mt_env;
1445 MDB_ID2L dl = txn->mt_u.dirty_list;
1446 unsigned i, n = dl[0].mid;
1448 for (i = 1; i <= n; i++) {
1449 mdb_dpage_free(env, dl[i].mptr);
1454 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
1455 * @param[in] mc A cursor handle for the current operation.
1456 * @param[in] pflags Flags of the pages to update:
1457 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1458 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
1459 * @return 0 on success, non-zero on failure.
1462 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
1464 enum { Mask = P_SUBP|P_DIRTY|P_KEEP };
1465 MDB_txn *txn = mc->mc_txn;
1471 int rc = MDB_SUCCESS, level;
1473 /* Mark pages seen by cursors */
1474 if (mc->mc_flags & C_UNTRACK)
1475 mc = NULL; /* will find mc in mt_cursors */
1476 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1477 for (; mc; mc=mc->mc_next) {
1478 if (!(mc->mc_flags & C_INITIALIZED))
1480 for (m3 = mc;; m3 = &mx->mx_cursor) {
1482 for (j=0; j<m3->mc_snum; j++) {
1484 if ((mp->mp_flags & Mask) == pflags)
1485 mp->mp_flags ^= P_KEEP;
1487 mx = m3->mc_xcursor;
1488 /* Proceed to mx if it is at a sub-database */
1489 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
1491 if (! (mp && (mp->mp_flags & P_LEAF)))
1493 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
1494 if (!(leaf->mn_flags & F_SUBDATA))
1503 /* Mark dirty root pages */
1504 for (i=0; i<txn->mt_numdbs; i++) {
1505 if (txn->mt_dbflags[i] & DB_DIRTY) {
1506 pgno_t pgno = txn->mt_dbs[i].md_root;
1507 if (pgno == P_INVALID)
1509 if ((rc = mdb_page_get(txn, pgno, &dp, &level)) != MDB_SUCCESS)
1511 if ((dp->mp_flags & Mask) == pflags && level <= 1)
1512 dp->mp_flags ^= P_KEEP;
1520 static int mdb_page_flush(MDB_txn *txn, int keep);
1522 /** Spill pages from the dirty list back to disk.
1523 * This is intended to prevent running into #MDB_TXN_FULL situations,
1524 * but note that they may still occur in a few cases:
1525 * 1) our estimate of the txn size could be too small. Currently this
1526 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
1527 * 2) child txns may run out of space if their parents dirtied a
1528 * lot of pages and never spilled them. TODO: we probably should do
1529 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1530 * the parent's dirty_room is below a given threshold.
1532 * Otherwise, if not using nested txns, it is expected that apps will
1533 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1534 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1535 * If the txn never references them again, they can be left alone.
1536 * If the txn only reads them, they can be used without any fuss.
1537 * If the txn writes them again, they can be dirtied immediately without
1538 * going thru all of the work of #mdb_page_touch(). Such references are
1539 * handled by #mdb_page_unspill().
1541 * Also note, we never spill DB root pages, nor pages of active cursors,
1542 * because we'll need these back again soon anyway. And in nested txns,
1543 * we can't spill a page in a child txn if it was already spilled in a
1544 * parent txn. That would alter the parent txns' data even though
1545 * the child hasn't committed yet, and we'd have no way to undo it if
1546 * the child aborted.
1548 * @param[in] m0 cursor A cursor handle identifying the transaction and
1549 * database for which we are checking space.
1550 * @param[in] key For a put operation, the key being stored.
1551 * @param[in] data For a put operation, the data being stored.
1552 * @return 0 on success, non-zero on failure.
1555 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1557 MDB_txn *txn = m0->mc_txn;
1559 MDB_ID2L dl = txn->mt_u.dirty_list;
1560 unsigned int i, j, need;
1563 if (m0->mc_flags & C_SUB)
1566 /* Estimate how much space this op will take */
1567 i = m0->mc_db->md_depth;
1568 /* Named DBs also dirty the main DB */
1569 if (m0->mc_dbi > MAIN_DBI)
1570 i += txn->mt_dbs[MAIN_DBI].md_depth;
1571 /* For puts, roughly factor in the key+data size */
1573 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
1574 i += i; /* double it for good measure */
1577 if (txn->mt_dirty_room > i)
1580 if (!txn->mt_spill_pgs) {
1581 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
1582 if (!txn->mt_spill_pgs)
1585 /* purge deleted slots */
1586 MDB_IDL sl = txn->mt_spill_pgs;
1587 unsigned int num = sl[0];
1589 for (i=1; i<=num; i++) {
1596 /* Preserve pages which may soon be dirtied again */
1597 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
1600 /* Less aggressive spill - we originally spilled the entire dirty list,
1601 * with a few exceptions for cursor pages and DB root pages. But this
1602 * turns out to be a lot of wasted effort because in a large txn many
1603 * of those pages will need to be used again. So now we spill only 1/8th
1604 * of the dirty pages. Testing revealed this to be a good tradeoff,
1605 * better than 1/2, 1/4, or 1/10.
1607 if (need < MDB_IDL_UM_MAX / 8)
1608 need = MDB_IDL_UM_MAX / 8;
1610 /* Save the page IDs of all the pages we're flushing */
1611 /* flush from the tail forward, this saves a lot of shifting later on. */
1612 for (i=dl[0].mid; i && need; i--) {
1613 MDB_ID pn = dl[i].mid << 1;
1615 if (dp->mp_flags & P_KEEP)
1617 /* Can't spill twice, make sure it's not already in a parent's
1620 if (txn->mt_parent) {
1622 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1623 if (tx2->mt_spill_pgs) {
1624 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
1625 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
1626 dp->mp_flags |= P_KEEP;
1634 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
1638 mdb_midl_sort(txn->mt_spill_pgs);
1640 /* Flush the spilled part of dirty list */
1641 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
1644 /* Reset any dirty pages we kept that page_flush didn't see */
1645 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
1648 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
1652 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
1654 mdb_find_oldest(MDB_txn *txn)
1657 txnid_t mr, oldest = txn->mt_txnid - 1;
1658 if (txn->mt_env->me_txns) {
1659 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
1660 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
1671 /** Add a page to the txn's dirty list */
1673 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
1676 int (*insert)(MDB_ID2L, MDB_ID2 *);
1678 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1679 insert = mdb_mid2l_append;
1681 insert = mdb_mid2l_insert;
1683 mid.mid = mp->mp_pgno;
1685 insert(txn->mt_u.dirty_list, &mid);
1686 txn->mt_dirty_room--;
1689 /** Allocate page numbers and memory for writing. Maintain me_pglast,
1690 * me_pghead and mt_next_pgno.
1692 * If there are free pages available from older transactions, they
1693 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
1694 * Do not modify the freedB, just merge freeDB records into me_pghead[]
1695 * and move me_pglast to say which records were consumed. Only this
1696 * function can create me_pghead and move me_pglast/mt_next_pgno.
1697 * @param[in] mc cursor A cursor handle identifying the transaction and
1698 * database for which we are allocating.
1699 * @param[in] num the number of pages to allocate.
1700 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
1701 * will always be satisfied by a single contiguous chunk of memory.
1702 * @return 0 on success, non-zero on failure.
1705 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
1707 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
1708 /* Get at most <Max_retries> more freeDB records once me_pghead
1709 * has enough pages. If not enough, use new pages from the map.
1710 * If <Paranoid> and mc is updating the freeDB, only get new
1711 * records if me_pghead is empty. Then the freelist cannot play
1712 * catch-up with itself by growing while trying to save it.
1714 enum { Paranoid = 1, Max_retries = 500 };
1716 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
1718 int rc, retry = Max_retries;
1719 MDB_txn *txn = mc->mc_txn;
1720 MDB_env *env = txn->mt_env;
1721 pgno_t pgno, *mop = env->me_pghead;
1722 unsigned i, j, k, mop_len = mop ? mop[0] : 0, n2 = num-1;
1724 txnid_t oldest = 0, last;
1730 /* If our dirty list is already full, we can't do anything */
1731 if (txn->mt_dirty_room == 0) {
1736 for (op = MDB_FIRST;; op = MDB_NEXT) {
1739 pgno_t *idl, old_id, new_id;
1741 /* Seek a big enough contiguous page range. Prefer
1742 * pages at the tail, just truncating the list.
1748 if (mop[i-n2] == pgno+n2)
1751 if (Max_retries < INT_MAX && --retry < 0)
1755 if (op == MDB_FIRST) { /* 1st iteration */
1756 /* Prepare to fetch more and coalesce */
1757 oldest = mdb_find_oldest(txn);
1758 last = env->me_pglast;
1759 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1762 key.mv_data = &last; /* will look up last+1 */
1763 key.mv_size = sizeof(last);
1765 if (Paranoid && mc->mc_dbi == FREE_DBI)
1768 if (Paranoid && retry < 0 && mop_len)
1772 /* Do not fetch more if the record will be too recent */
1775 rc = mdb_cursor_get(&m2, &key, NULL, op);
1777 if (rc == MDB_NOTFOUND)
1781 last = *(txnid_t*)key.mv_data;
1784 np = m2.mc_pg[m2.mc_top];
1785 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
1786 if ((rc = mdb_node_read(txn, leaf, &data)) != MDB_SUCCESS)
1789 idl = (MDB_ID *) data.mv_data;
1792 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
1797 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
1799 mop = env->me_pghead;
1801 env->me_pglast = last;
1803 DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
1804 last, txn->mt_dbs[FREE_DBI].md_root, i));
1806 DPRINTF(("IDL %"Z"u", idl[k]));
1808 /* Merge in descending sorted order */
1811 mop[0] = (pgno_t)-1;
1815 for (; old_id < new_id; old_id = mop[--j])
1822 /* Use new pages from the map when nothing suitable in the freeDB */
1824 pgno = txn->mt_next_pgno;
1825 if (pgno + num >= env->me_maxpg) {
1826 DPUTS("DB size maxed out");
1832 if (env->me_flags & MDB_WRITEMAP) {
1833 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
1835 if (!(np = mdb_page_malloc(txn, num))) {
1841 mop[0] = mop_len -= num;
1842 /* Move any stragglers down */
1843 for (j = i-num; j < mop_len; )
1844 mop[++j] = mop[++i];
1846 txn->mt_next_pgno = pgno + num;
1849 mdb_page_dirty(txn, np);
1855 txn->mt_flags |= MDB_TXN_ERROR;
1859 /** Copy the used portions of a non-overflow page.
1860 * @param[in] dst page to copy into
1861 * @param[in] src page to copy from
1862 * @param[in] psize size of a page
1865 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
1867 enum { Align = sizeof(pgno_t) };
1868 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
1870 /* If page isn't full, just copy the used portion. Adjust
1871 * alignment so memcpy may copy words instead of bytes.
1873 if ((unused &= -Align) && !IS_LEAF2(src)) {
1875 memcpy(dst, src, (lower + (Align-1)) & -Align);
1876 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
1879 memcpy(dst, src, psize - unused);
1883 /** Pull a page off the txn's spill list, if present.
1884 * If a page being referenced was spilled to disk in this txn, bring
1885 * it back and make it dirty/writable again.
1886 * @param[in] txn the transaction handle.
1887 * @param[in] mp the page being referenced. It must not be dirty.
1888 * @param[out] ret the writable page, if any. ret is unchanged if
1889 * mp wasn't spilled.
1892 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
1894 MDB_env *env = txn->mt_env;
1897 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
1899 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
1900 if (!tx2->mt_spill_pgs)
1902 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
1903 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
1906 if (txn->mt_dirty_room == 0)
1907 return MDB_TXN_FULL;
1908 if (IS_OVERFLOW(mp))
1912 if (env->me_flags & MDB_WRITEMAP) {
1915 np = mdb_page_malloc(txn, num);
1919 memcpy(np, mp, num * env->me_psize);
1921 mdb_page_copy(np, mp, env->me_psize);
1924 /* If in current txn, this page is no longer spilled.
1925 * If it happens to be the last page, truncate the spill list.
1926 * Otherwise mark it as deleted by setting the LSB.
1928 if (x == txn->mt_spill_pgs[0])
1929 txn->mt_spill_pgs[0]--;
1931 txn->mt_spill_pgs[x] |= 1;
1932 } /* otherwise, if belonging to a parent txn, the
1933 * page remains spilled until child commits
1936 mdb_page_dirty(txn, np);
1937 np->mp_flags |= P_DIRTY;
1945 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1946 * @param[in] mc cursor pointing to the page to be touched
1947 * @return 0 on success, non-zero on failure.
1950 mdb_page_touch(MDB_cursor *mc)
1952 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
1953 MDB_txn *txn = mc->mc_txn;
1954 MDB_cursor *m2, *m3;
1958 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1959 if (txn->mt_flags & MDB_TXN_SPILLS) {
1961 rc = mdb_page_unspill(txn, mp, &np);
1967 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
1968 (rc = mdb_page_alloc(mc, 1, &np)))
1971 DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
1972 mp->mp_pgno, pgno));
1973 assert(mp->mp_pgno != pgno);
1974 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
1975 /* Update the parent page, if any, to point to the new page */
1977 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
1978 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
1979 SETPGNO(node, pgno);
1981 mc->mc_db->md_root = pgno;
1983 } else if (txn->mt_parent && !IS_SUBP(mp)) {
1984 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
1986 /* If txn has a parent, make sure the page is in our
1990 unsigned x = mdb_mid2l_search(dl, pgno);
1991 if (x <= dl[0].mid && dl[x].mid == pgno) {
1992 if (mp != dl[x].mptr) { /* bad cursor? */
1993 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1994 txn->mt_flags |= MDB_TXN_ERROR;
1995 return MDB_CORRUPTED;
2000 assert(dl[0].mid < MDB_IDL_UM_MAX);
2002 np = mdb_page_malloc(txn, 1);
2007 mdb_mid2l_insert(dl, &mid);
2012 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2014 np->mp_flags |= P_DIRTY;
2017 /* Adjust cursors pointing to mp */
2018 mc->mc_pg[mc->mc_top] = np;
2019 m2 = txn->mt_cursors[mc->mc_dbi];
2020 if (mc->mc_flags & C_SUB) {
2021 for (; m2; m2=m2->mc_next) {
2022 m3 = &m2->mc_xcursor->mx_cursor;
2023 if (m3->mc_snum < mc->mc_snum) continue;
2024 if (m3->mc_pg[mc->mc_top] == mp)
2025 m3->mc_pg[mc->mc_top] = np;
2028 for (; m2; m2=m2->mc_next) {
2029 if (m2->mc_snum < mc->mc_snum) continue;
2030 if (m2->mc_pg[mc->mc_top] == mp) {
2031 m2->mc_pg[mc->mc_top] = np;
2032 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
2033 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
2035 MDB_node *leaf = NODEPTR(np, mc->mc_ki[mc->mc_top]);
2036 if (!(leaf->mn_flags & F_SUBDATA))
2037 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
2045 txn->mt_flags |= MDB_TXN_ERROR;
2050 mdb_env_sync(MDB_env *env, int force)
2053 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2054 if (env->me_flags & MDB_WRITEMAP) {
2055 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2056 ? MS_ASYNC : MS_SYNC;
2057 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
2060 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2064 if (MDB_FDATASYNC(env->me_fd))
2071 /** Back up parent txn's cursors, then grab the originals for tracking */
2073 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2075 MDB_cursor *mc, *bk;
2080 for (i = src->mt_numdbs; --i >= 0; ) {
2081 if ((mc = src->mt_cursors[i]) != NULL) {
2082 size = sizeof(MDB_cursor);
2084 size += sizeof(MDB_xcursor);
2085 for (; mc; mc = bk->mc_next) {
2091 mc->mc_db = &dst->mt_dbs[i];
2092 /* Kill pointers into src - and dst to reduce abuse: The
2093 * user may not use mc until dst ends. Otherwise we'd...
2095 mc->mc_txn = NULL; /* ...set this to dst */
2096 mc->mc_dbflag = NULL; /* ...and &dst->mt_dbflags[i] */
2097 if ((mx = mc->mc_xcursor) != NULL) {
2098 *(MDB_xcursor *)(bk+1) = *mx;
2099 mx->mx_cursor.mc_txn = NULL; /* ...and dst. */
2101 mc->mc_next = dst->mt_cursors[i];
2102 dst->mt_cursors[i] = mc;
2109 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2110 * @param[in] txn the transaction handle.
2111 * @param[in] merge true to keep changes to parent cursors, false to revert.
2112 * @return 0 on success, non-zero on failure.
2115 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2117 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2121 for (i = txn->mt_numdbs; --i >= 0; ) {
2122 for (mc = cursors[i]; mc; mc = next) {
2124 if ((bk = mc->mc_backup) != NULL) {
2126 /* Commit changes to parent txn */
2127 mc->mc_next = bk->mc_next;
2128 mc->mc_backup = bk->mc_backup;
2129 mc->mc_txn = bk->mc_txn;
2130 mc->mc_db = bk->mc_db;
2131 mc->mc_dbflag = bk->mc_dbflag;
2132 if ((mx = mc->mc_xcursor) != NULL)
2133 mx->mx_cursor.mc_txn = bk->mc_txn;
2135 /* Abort nested txn */
2137 if ((mx = mc->mc_xcursor) != NULL)
2138 *mx = *(MDB_xcursor *)(bk+1);
2142 /* Only malloced cursors are permanently tracked. */
2150 #define mdb_txn_reset0(txn, act) mdb_txn_reset0(txn)
2153 mdb_txn_reset0(MDB_txn *txn, const char *act);
2155 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2161 Pidset = F_SETLK, Pidcheck = F_GETLK
2165 /** Set or check a pid lock. Set returns 0 on success.
2166 * Check returns 0 if the process is certainly dead, nonzero if it may
2167 * be alive (the lock exists or an error happened so we do not know).
2169 * On Windows Pidset is a no-op, we merely check for the existence
2170 * of the process with the given pid. On POSIX we use a single byte
2171 * lock on the lockfile, set at an offset equal to the pid.
2174 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2176 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2179 if (op == Pidcheck) {
2180 h = OpenProcess(env->me_pidquery, FALSE, pid);
2181 /* No documented "no such process" code, but other program use this: */
2183 return ErrCode() != ERROR_INVALID_PARAMETER;
2184 /* A process exists until all handles to it close. Has it exited? */
2185 ret = WaitForSingleObject(h, 0) != 0;
2192 struct flock lock_info;
2193 memset(&lock_info, 0, sizeof(lock_info));
2194 lock_info.l_type = F_WRLCK;
2195 lock_info.l_whence = SEEK_SET;
2196 lock_info.l_start = pid;
2197 lock_info.l_len = 1;
2198 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2199 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2201 } else if ((rc = ErrCode()) == EINTR) {
2209 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2210 * @param[in] txn the transaction handle to initialize
2211 * @return 0 on success, non-zero on failure.
2214 mdb_txn_renew0(MDB_txn *txn)
2216 MDB_env *env = txn->mt_env;
2217 MDB_txninfo *ti = env->me_txns;
2221 int rc, new_notls = 0;
2224 txn->mt_numdbs = env->me_numdbs;
2225 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
2227 if (txn->mt_flags & MDB_TXN_RDONLY) {
2229 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2230 txn->mt_txnid = meta->mm_txnid;
2231 txn->mt_u.reader = NULL;
2233 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2234 pthread_getspecific(env->me_txkey);
2236 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2237 return MDB_BAD_RSLOT;
2239 MDB_PID_T pid = env->me_pid;
2240 pthread_t tid = pthread_self();
2242 if (!(env->me_flags & MDB_LIVE_READER)) {
2243 rc = mdb_reader_pid(env, Pidset, pid);
2246 env->me_flags |= MDB_LIVE_READER;
2250 nr = ti->mti_numreaders;
2251 for (i=0; i<nr; i++)
2252 if (ti->mti_readers[i].mr_pid == 0)
2254 if (i == env->me_maxreaders) {
2255 UNLOCK_MUTEX_R(env);
2256 return MDB_READERS_FULL;
2258 ti->mti_readers[i].mr_pid = pid;
2259 ti->mti_readers[i].mr_tid = tid;
2261 ti->mti_numreaders = ++nr;
2262 /* Save numreaders for un-mutexed mdb_env_close() */
2263 env->me_numreaders = nr;
2264 UNLOCK_MUTEX_R(env);
2266 r = &ti->mti_readers[i];
2267 new_notls = (env->me_flags & MDB_NOTLS);
2268 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2273 txn->mt_txnid = r->mr_txnid = ti->mti_txnid;
2274 txn->mt_u.reader = r;
2275 meta = env->me_metas[txn->mt_txnid & 1];
2281 txn->mt_txnid = ti->mti_txnid;
2282 meta = env->me_metas[txn->mt_txnid & 1];
2284 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2285 txn->mt_txnid = meta->mm_txnid;
2289 if (txn->mt_txnid == mdb_debug_start)
2292 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2293 txn->mt_u.dirty_list = env->me_dirty_list;
2294 txn->mt_u.dirty_list[0].mid = 0;
2295 txn->mt_free_pgs = env->me_free_pgs;
2296 txn->mt_free_pgs[0] = 0;
2297 txn->mt_spill_pgs = NULL;
2301 /* Copy the DB info and flags */
2302 memcpy(txn->mt_dbs, meta->mm_dbs, 2 * sizeof(MDB_db));
2304 /* Moved to here to avoid a data race in read TXNs */
2305 txn->mt_next_pgno = meta->mm_last_pg+1;
2307 for (i=2; i<txn->mt_numdbs; i++) {
2308 x = env->me_dbflags[i];
2309 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2310 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_STALE : 0;
2312 txn->mt_dbflags[0] = txn->mt_dbflags[1] = DB_VALID;
2314 if (env->me_maxpg < txn->mt_next_pgno) {
2315 mdb_txn_reset0(txn, "renew0-mapfail");
2317 txn->mt_u.reader->mr_pid = 0;
2318 txn->mt_u.reader = NULL;
2320 return MDB_MAP_RESIZED;
2327 mdb_txn_renew(MDB_txn *txn)
2331 if (!txn || txn->mt_dbxs) /* A reset txn has mt_dbxs==NULL */
2334 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
2335 DPUTS("environment had fatal error, must shutdown!");
2339 rc = mdb_txn_renew0(txn);
2340 if (rc == MDB_SUCCESS) {
2341 DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2342 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2343 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2349 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2353 int rc, size, tsize = sizeof(MDB_txn);
2355 if (env->me_flags & MDB_FATAL_ERROR) {
2356 DPUTS("environment had fatal error, must shutdown!");
2359 if ((env->me_flags & MDB_RDONLY) && !(flags & MDB_RDONLY))
2362 /* Nested transactions: Max 1 child, write txns only, no writemap */
2363 if (parent->mt_child ||
2364 (flags & MDB_RDONLY) ||
2365 (parent->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR)) ||
2366 (env->me_flags & MDB_WRITEMAP))
2368 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
2370 tsize = sizeof(MDB_ntxn);
2372 size = tsize + env->me_maxdbs * (sizeof(MDB_db)+1);
2373 if (!(flags & MDB_RDONLY))
2374 size += env->me_maxdbs * sizeof(MDB_cursor *);
2376 if ((txn = calloc(1, size)) == NULL) {
2377 DPRINTF(("calloc: %s", strerror(ErrCode())));
2380 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2381 if (flags & MDB_RDONLY) {
2382 txn->mt_flags |= MDB_TXN_RDONLY;
2383 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
2385 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2386 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
2392 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2393 if (!txn->mt_u.dirty_list ||
2394 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2396 free(txn->mt_u.dirty_list);
2400 txn->mt_txnid = parent->mt_txnid;
2401 txn->mt_dirty_room = parent->mt_dirty_room;
2402 txn->mt_u.dirty_list[0].mid = 0;
2403 txn->mt_spill_pgs = NULL;
2404 txn->mt_next_pgno = parent->mt_next_pgno;
2405 parent->mt_child = txn;
2406 txn->mt_parent = parent;
2407 txn->mt_numdbs = parent->mt_numdbs;
2408 txn->mt_flags = parent->mt_flags;
2409 txn->mt_dbxs = parent->mt_dbxs;
2410 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2411 /* Copy parent's mt_dbflags, but clear DB_NEW */
2412 for (i=0; i<txn->mt_numdbs; i++)
2413 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2415 ntxn = (MDB_ntxn *)txn;
2416 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2417 if (env->me_pghead) {
2418 size = MDB_IDL_SIZEOF(env->me_pghead);
2419 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2421 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2426 rc = mdb_cursor_shadow(parent, txn);
2428 mdb_txn_reset0(txn, "beginchild-fail");
2430 rc = mdb_txn_renew0(txn);
2436 DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2437 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2438 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
2445 mdb_txn_env(MDB_txn *txn)
2447 if(!txn) return NULL;
2451 /** Export or close DBI handles opened in this txn. */
2453 mdb_dbis_update(MDB_txn *txn, int keep)
2456 MDB_dbi n = txn->mt_numdbs;
2457 MDB_env *env = txn->mt_env;
2458 unsigned char *tdbflags = txn->mt_dbflags;
2460 for (i = n; --i >= 2;) {
2461 if (tdbflags[i] & DB_NEW) {
2463 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2465 char *ptr = env->me_dbxs[i].md_name.mv_data;
2466 env->me_dbxs[i].md_name.mv_data = NULL;
2467 env->me_dbxs[i].md_name.mv_size = 0;
2468 env->me_dbflags[i] = 0;
2473 if (keep && env->me_numdbs < n)
2477 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
2478 * May be called twice for readonly txns: First reset it, then abort.
2479 * @param[in] txn the transaction handle to reset
2480 * @param[in] act why the transaction is being reset
2483 mdb_txn_reset0(MDB_txn *txn, const char *act)
2485 MDB_env *env = txn->mt_env;
2487 /* Close any DBI handles opened in this txn */
2488 mdb_dbis_update(txn, 0);
2490 DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2491 act, txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2492 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
2494 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2495 if (txn->mt_u.reader) {
2496 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2497 if (!(env->me_flags & MDB_NOTLS))
2498 txn->mt_u.reader = NULL; /* txn does not own reader */
2500 txn->mt_numdbs = 0; /* close nothing if called again */
2501 txn->mt_dbxs = NULL; /* mark txn as reset */
2503 mdb_cursors_close(txn, 0);
2505 if (!(env->me_flags & MDB_WRITEMAP)) {
2506 mdb_dlist_free(txn);
2508 mdb_midl_free(env->me_pghead);
2510 if (txn->mt_parent) {
2511 txn->mt_parent->mt_child = NULL;
2512 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2513 mdb_midl_free(txn->mt_free_pgs);
2514 mdb_midl_free(txn->mt_spill_pgs);
2515 free(txn->mt_u.dirty_list);
2519 if (mdb_midl_shrink(&txn->mt_free_pgs))
2520 env->me_free_pgs = txn->mt_free_pgs;
2521 env->me_pghead = NULL;
2525 /* The writer mutex was locked in mdb_txn_begin. */
2527 UNLOCK_MUTEX_W(env);
2532 mdb_txn_reset(MDB_txn *txn)
2537 /* This call is only valid for read-only txns */
2538 if (!(txn->mt_flags & MDB_TXN_RDONLY))
2541 mdb_txn_reset0(txn, "reset");
2545 mdb_txn_abort(MDB_txn *txn)
2551 mdb_txn_abort(txn->mt_child);
2553 mdb_txn_reset0(txn, "abort");
2554 /* Free reader slot tied to this txn (if MDB_NOTLS && writable FS) */
2555 if ((txn->mt_flags & MDB_TXN_RDONLY) && txn->mt_u.reader)
2556 txn->mt_u.reader->mr_pid = 0;
2561 /** Save the freelist as of this transaction to the freeDB.
2562 * This changes the freelist. Keep trying until it stabilizes.
2565 mdb_freelist_save(MDB_txn *txn)
2567 /* env->me_pghead[] can grow and shrink during this call.
2568 * env->me_pglast and txn->mt_free_pgs[] can only grow.
2569 * Page numbers cannot disappear from txn->mt_free_pgs[].
2572 MDB_env *env = txn->mt_env;
2573 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
2574 txnid_t pglast = 0, head_id = 0;
2575 pgno_t freecnt = 0, *free_pgs, *mop;
2576 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
2578 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
2580 if (env->me_pghead) {
2581 /* Make sure first page of freeDB is touched and on freelist */
2582 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
2583 if (rc && rc != MDB_NOTFOUND)
2587 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
2588 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
2589 ? SSIZE_MAX : maxfree_1pg;
2592 /* Come back here after each Put() in case freelist changed */
2597 /* If using records from freeDB which we have not yet
2598 * deleted, delete them and any we reserved for me_pghead.
2600 while (pglast < env->me_pglast) {
2601 rc = mdb_cursor_first(&mc, &key, NULL);
2604 pglast = head_id = *(txnid_t *)key.mv_data;
2605 total_room = head_room = 0;
2606 assert(pglast <= env->me_pglast);
2607 rc = mdb_cursor_del(&mc, 0);
2612 /* Save the IDL of pages freed by this txn, to a single record */
2613 if (freecnt < txn->mt_free_pgs[0]) {
2615 /* Make sure last page of freeDB is touched and on freelist */
2616 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
2617 if (rc && rc != MDB_NOTFOUND)
2620 free_pgs = txn->mt_free_pgs;
2621 /* Write to last page of freeDB */
2622 key.mv_size = sizeof(txn->mt_txnid);
2623 key.mv_data = &txn->mt_txnid;
2625 freecnt = free_pgs[0];
2626 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
2627 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2630 /* Retry if mt_free_pgs[] grew during the Put() */
2631 free_pgs = txn->mt_free_pgs;
2632 } while (freecnt < free_pgs[0]);
2633 mdb_midl_sort(free_pgs);
2634 memcpy(data.mv_data, free_pgs, data.mv_size);
2637 unsigned int i = free_pgs[0];
2638 DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
2639 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
2641 DPRINTF(("IDL %"Z"u", free_pgs[i]));
2647 mop = env->me_pghead;
2648 mop_len = mop ? mop[0] : 0;
2650 /* Reserve records for me_pghead[]. Split it if multi-page,
2651 * to avoid searching freeDB for a page range. Use keys in
2652 * range [1,me_pglast]: Smaller than txnid of oldest reader.
2654 if (total_room >= mop_len) {
2655 if (total_room == mop_len || --more < 0)
2657 } else if (head_room >= maxfree_1pg && head_id > 1) {
2658 /* Keep current record (overflow page), add a new one */
2662 /* (Re)write {key = head_id, IDL length = head_room} */
2663 total_room -= head_room;
2664 head_room = mop_len - total_room;
2665 if (head_room > maxfree_1pg && head_id > 1) {
2666 /* Overflow multi-page for part of me_pghead */
2667 head_room /= head_id; /* amortize page sizes */
2668 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
2669 } else if (head_room < 0) {
2670 /* Rare case, not bothering to delete this record */
2673 key.mv_size = sizeof(head_id);
2674 key.mv_data = &head_id;
2675 data.mv_size = (head_room + 1) * sizeof(pgno_t);
2676 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2679 /* IDL is initially empty, zero out at least the length */
2680 pgs = (pgno_t *)data.mv_data;
2681 j = head_room > clean_limit ? head_room : 0;
2685 total_room += head_room;
2688 /* Fill in the reserved me_pghead records */
2694 rc = mdb_cursor_first(&mc, &key, &data);
2695 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
2696 unsigned flags = MDB_CURRENT;
2697 txnid_t id = *(txnid_t *)key.mv_data;
2698 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
2701 assert(len >= 0 && id <= env->me_pglast);
2703 if (len > mop_len) {
2705 data.mv_size = (len + 1) * sizeof(MDB_ID);
2708 data.mv_data = mop -= len;
2711 rc = mdb_cursor_put(&mc, &key, &data, flags);
2713 if (rc || !(mop_len -= len))
2720 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
2721 * @param[in] txn the transaction that's being committed
2722 * @param[in] keep number of initial pages in dirty_list to keep dirty.
2723 * @return 0 on success, non-zero on failure.
2726 mdb_page_flush(MDB_txn *txn, int keep)
2728 MDB_env *env = txn->mt_env;
2729 MDB_ID2L dl = txn->mt_u.dirty_list;
2730 unsigned psize = env->me_psize, j;
2731 int i, pagecount = dl[0].mid, rc;
2732 size_t size = 0, pos = 0;
2734 MDB_page *dp = NULL;
2738 struct iovec iov[MDB_COMMIT_PAGES];
2739 ssize_t wpos = 0, wsize = 0, wres;
2740 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
2746 if (env->me_flags & MDB_WRITEMAP) {
2747 /* Clear dirty flags */
2748 while (++i <= pagecount) {
2750 /* Don't flush this page yet */
2751 if (dp->mp_flags & P_KEEP) {
2752 dp->mp_flags ^= P_KEEP;
2756 dp->mp_flags &= ~P_DIRTY;
2761 /* Write the pages */
2763 if (++i <= pagecount) {
2765 /* Don't flush this page yet */
2766 if (dp->mp_flags & P_KEEP) {
2767 dp->mp_flags ^= P_KEEP;
2772 /* clear dirty flag */
2773 dp->mp_flags &= ~P_DIRTY;
2776 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
2781 /* Windows actually supports scatter/gather I/O, but only on
2782 * unbuffered file handles. Since we're relying on the OS page
2783 * cache for all our data, that's self-defeating. So we just
2784 * write pages one at a time. We use the ov structure to set
2785 * the write offset, to at least save the overhead of a Seek
2788 DPRINTF(("committing page %"Z"u", pgno));
2789 memset(&ov, 0, sizeof(ov));
2790 ov.Offset = pos & 0xffffffff;
2791 ov.OffsetHigh = pos >> 16 >> 16;
2792 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
2794 DPRINTF(("WriteFile: %d", rc));
2798 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
2799 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
2801 /* Write previous page(s) */
2802 #ifdef MDB_USE_PWRITEV
2803 wres = pwritev(env->me_fd, iov, n, wpos);
2806 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
2808 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
2810 DPRINTF(("lseek: %s", strerror(rc)));
2813 wres = writev(env->me_fd, iov, n);
2816 if (wres != wsize) {
2819 DPRINTF(("Write error: %s", strerror(rc)));
2821 rc = EIO; /* TODO: Use which error code? */
2822 DPUTS("short write, filesystem full?");
2833 DPRINTF(("committing page %"Z"u", pgno));
2834 next_pos = pos + size;
2835 iov[n].iov_len = size;
2836 iov[n].iov_base = (char *)dp;
2842 for (i = keep; ++i <= pagecount; ) {
2844 /* This is a page we skipped above */
2847 dl[j].mid = dp->mp_pgno;
2850 mdb_dpage_free(env, dp);
2855 txn->mt_dirty_room += i - j;
2861 mdb_txn_commit(MDB_txn *txn)
2867 if (txn == NULL || txn->mt_env == NULL)
2870 if (txn->mt_child) {
2871 rc = mdb_txn_commit(txn->mt_child);
2872 txn->mt_child = NULL;
2879 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2880 mdb_dbis_update(txn, 1);
2881 txn->mt_numdbs = 2; /* so txn_abort() doesn't close any new handles */
2886 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
2887 DPUTS("error flag is set, can't commit");
2889 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
2894 if (txn->mt_parent) {
2895 MDB_txn *parent = txn->mt_parent;
2898 unsigned x, y, len, ps_len;
2900 /* Append our free list to parent's */
2901 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
2904 mdb_midl_free(txn->mt_free_pgs);
2905 /* Failures after this must either undo the changes
2906 * to the parent or set MDB_TXN_ERROR in the parent.
2909 parent->mt_next_pgno = txn->mt_next_pgno;
2910 parent->mt_flags = txn->mt_flags;
2912 /* Merge our cursors into parent's and close them */
2913 mdb_cursors_close(txn, 1);
2915 /* Update parent's DB table. */
2916 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2917 parent->mt_numdbs = txn->mt_numdbs;
2918 parent->mt_dbflags[0] = txn->mt_dbflags[0];
2919 parent->mt_dbflags[1] = txn->mt_dbflags[1];
2920 for (i=2; i<txn->mt_numdbs; i++) {
2921 /* preserve parent's DB_NEW status */
2922 x = parent->mt_dbflags[i] & DB_NEW;
2923 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
2926 dst = parent->mt_u.dirty_list;
2927 src = txn->mt_u.dirty_list;
2928 /* Remove anything in our dirty list from parent's spill list */
2929 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
2931 pspill[0] = (pgno_t)-1;
2932 /* Mark our dirty pages as deleted in parent spill list */
2933 for (i=0, len=src[0].mid; ++i <= len; ) {
2934 MDB_ID pn = src[i].mid << 1;
2935 while (pn > pspill[x])
2937 if (pn == pspill[x]) {
2942 /* Squash deleted pagenums if we deleted any */
2943 for (x=y; ++x <= ps_len; )
2944 if (!(pspill[x] & 1))
2945 pspill[++y] = pspill[x];
2949 /* Find len = length of merging our dirty list with parent's */
2951 dst[0].mid = 0; /* simplify loops */
2952 if (parent->mt_parent) {
2953 len = x + src[0].mid;
2954 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
2955 for (i = x; y && i; y--) {
2956 pgno_t yp = src[y].mid;
2957 while (yp < dst[i].mid)
2959 if (yp == dst[i].mid) {
2964 } else { /* Simplify the above for single-ancestor case */
2965 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
2967 /* Merge our dirty list with parent's */
2969 for (i = len; y; dst[i--] = src[y--]) {
2970 pgno_t yp = src[y].mid;
2971 while (yp < dst[x].mid)
2972 dst[i--] = dst[x--];
2973 if (yp == dst[x].mid)
2974 free(dst[x--].mptr);
2978 free(txn->mt_u.dirty_list);
2979 parent->mt_dirty_room = txn->mt_dirty_room;
2980 if (txn->mt_spill_pgs) {
2981 if (parent->mt_spill_pgs) {
2982 /* TODO: Prevent failure here, so parent does not fail */
2983 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
2985 parent->mt_flags |= MDB_TXN_ERROR;
2986 mdb_midl_free(txn->mt_spill_pgs);
2987 mdb_midl_sort(parent->mt_spill_pgs);
2989 parent->mt_spill_pgs = txn->mt_spill_pgs;
2993 parent->mt_child = NULL;
2994 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
2999 if (txn != env->me_txn) {
3000 DPUTS("attempt to commit unknown transaction");
3005 mdb_cursors_close(txn, 0);
3007 if (!txn->mt_u.dirty_list[0].mid &&
3008 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
3011 DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
3012 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3014 /* Update DB root pointers */
3015 if (txn->mt_numdbs > 2) {
3019 data.mv_size = sizeof(MDB_db);
3021 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3022 for (i = 2; i < txn->mt_numdbs; i++) {
3023 if (txn->mt_dbflags[i] & DB_DIRTY) {
3024 data.mv_data = &txn->mt_dbs[i];
3025 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
3032 rc = mdb_freelist_save(txn);
3036 mdb_midl_free(env->me_pghead);
3037 env->me_pghead = NULL;
3038 if (mdb_midl_shrink(&txn->mt_free_pgs))
3039 env->me_free_pgs = txn->mt_free_pgs;
3045 if ((rc = mdb_page_flush(txn, 0)) ||
3046 (rc = mdb_env_sync(env, 0)) ||
3047 (rc = mdb_env_write_meta(txn)))
3053 mdb_dbis_update(txn, 1);
3056 UNLOCK_MUTEX_W(env);
3066 /** Read the environment parameters of a DB environment before
3067 * mapping it into memory.
3068 * @param[in] env the environment handle
3069 * @param[out] meta address of where to store the meta information
3070 * @return 0 on success, non-zero on failure.
3073 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3079 enum { Size = sizeof(pbuf) };
3081 /* We don't know the page size yet, so use a minimum value.
3082 * Read both meta pages so we can use the latest one.
3085 for (i=off=0; i<2; i++, off = meta->mm_psize) {
3089 memset(&ov, 0, sizeof(ov));
3091 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3092 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3095 rc = pread(env->me_fd, &pbuf, Size, off);
3098 if (rc == 0 && off == 0)
3100 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3101 DPRINTF(("read: %s", mdb_strerror(rc)));
3105 p = (MDB_page *)&pbuf;
3107 if (!F_ISSET(p->mp_flags, P_META)) {
3108 DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
3113 if (m->mm_magic != MDB_MAGIC) {
3114 DPUTS("meta has invalid magic");
3118 if (m->mm_version != MDB_DATA_VERSION) {
3119 DPRINTF(("database is version %u, expected version %u",
3120 m->mm_version, MDB_DATA_VERSION));
3121 return MDB_VERSION_MISMATCH;
3124 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3130 /** Write the environment parameters of a freshly created DB environment.
3131 * @param[in] env the environment handle
3132 * @param[out] meta address of where to store the meta information
3133 * @return 0 on success, non-zero on failure.
3136 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3144 memset(&ov, 0, sizeof(ov));
3145 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3147 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3150 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3151 len = pwrite(fd, ptr, size, pos); \
3152 rc = (len >= 0); } while(0)
3155 DPUTS("writing new meta page");
3157 psize = env->me_psize;
3159 meta->mm_magic = MDB_MAGIC;
3160 meta->mm_version = MDB_DATA_VERSION;
3161 meta->mm_mapsize = env->me_mapsize;
3162 meta->mm_psize = psize;
3163 meta->mm_last_pg = 1;
3164 meta->mm_flags = env->me_flags & 0xffff;
3165 meta->mm_flags |= MDB_INTEGERKEY;
3166 meta->mm_dbs[0].md_root = P_INVALID;
3167 meta->mm_dbs[1].md_root = P_INVALID;
3169 p = calloc(2, psize);
3171 p->mp_flags = P_META;
3172 *(MDB_meta *)METADATA(p) = *meta;
3174 q = (MDB_page *)((char *)p + psize);
3176 q->mp_flags = P_META;
3177 *(MDB_meta *)METADATA(q) = *meta;
3179 DO_PWRITE(rc, env->me_fd, p, psize * 2, len, 0);
3182 else if ((unsigned) len == psize * 2)
3190 /** Update the environment info to commit a transaction.
3191 * @param[in] txn the transaction that's being committed
3192 * @return 0 on success, non-zero on failure.
3195 mdb_env_write_meta(MDB_txn *txn)
3198 MDB_meta meta, metab, *mp;
3200 int rc, len, toggle;
3209 toggle = txn->mt_txnid & 1;
3210 DPRINTF(("writing meta page %d for root page %"Z"u",
3211 toggle, txn->mt_dbs[MAIN_DBI].md_root));
3214 mp = env->me_metas[toggle];
3216 if (env->me_flags & MDB_WRITEMAP) {
3217 /* Persist any increases of mapsize config */
3218 if (env->me_mapsize > mp->mm_mapsize)
3219 mp->mm_mapsize = env->me_mapsize;
3220 mp->mm_dbs[0] = txn->mt_dbs[0];
3221 mp->mm_dbs[1] = txn->mt_dbs[1];
3222 mp->mm_last_pg = txn->mt_next_pgno - 1;
3223 mp->mm_txnid = txn->mt_txnid;
3224 if (!(env->me_flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3225 unsigned meta_size = env->me_psize;
3226 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3229 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
3230 if (meta_size < env->me_os_psize)
3231 meta_size += meta_size;
3236 if (MDB_MSYNC(ptr, meta_size, rc)) {
3243 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
3244 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
3246 ptr = (char *)&meta;
3247 if (env->me_mapsize > mp->mm_mapsize) {
3248 /* Persist any increases of mapsize config */
3249 meta.mm_mapsize = env->me_mapsize;
3250 off = offsetof(MDB_meta, mm_mapsize);
3252 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
3254 len = sizeof(MDB_meta) - off;
3257 meta.mm_dbs[0] = txn->mt_dbs[0];
3258 meta.mm_dbs[1] = txn->mt_dbs[1];
3259 meta.mm_last_pg = txn->mt_next_pgno - 1;
3260 meta.mm_txnid = txn->mt_txnid;
3263 off += env->me_psize;
3266 /* Write to the SYNC fd */
3267 mfd = env->me_flags & (MDB_NOSYNC|MDB_NOMETASYNC) ?
3268 env->me_fd : env->me_mfd;
3271 memset(&ov, 0, sizeof(ov));
3273 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3277 rc = pwrite(mfd, ptr, len, off);
3280 rc = rc < 0 ? ErrCode() : EIO;
3281 DPUTS("write failed, disk error?");
3282 /* On a failure, the pagecache still contains the new data.
3283 * Write some old data back, to prevent it from being used.
3284 * Use the non-SYNC fd; we know it will fail anyway.
3286 meta.mm_last_pg = metab.mm_last_pg;
3287 meta.mm_txnid = metab.mm_txnid;
3289 memset(&ov, 0, sizeof(ov));
3291 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3293 r2 = pwrite(env->me_fd, ptr, len, off);
3294 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
3297 env->me_flags |= MDB_FATAL_ERROR;
3301 /* Memory ordering issues are irrelevant; since the entire writer
3302 * is wrapped by wmutex, all of these changes will become visible
3303 * after the wmutex is unlocked. Since the DB is multi-version,
3304 * readers will get consistent data regardless of how fresh or
3305 * how stale their view of these values is.
3308 env->me_txns->mti_txnid = txn->mt_txnid;
3313 /** Check both meta pages to see which one is newer.
3314 * @param[in] env the environment handle
3315 * @return meta toggle (0 or 1).
3318 mdb_env_pick_meta(const MDB_env *env)
3320 return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
3324 mdb_env_create(MDB_env **env)
3328 e = calloc(1, sizeof(MDB_env));
3332 e->me_maxreaders = DEFAULT_READERS;
3333 e->me_maxdbs = e->me_numdbs = 2;
3334 e->me_fd = INVALID_HANDLE_VALUE;
3335 e->me_lfd = INVALID_HANDLE_VALUE;
3336 e->me_mfd = INVALID_HANDLE_VALUE;
3337 #ifdef MDB_USE_POSIX_SEM
3338 e->me_rmutex = SEM_FAILED;
3339 e->me_wmutex = SEM_FAILED;
3341 e->me_pid = getpid();
3342 GET_PAGESIZE(e->me_os_psize);
3343 VGMEMP_CREATE(e,0,0);
3349 mdb_env_map(MDB_env *env, void *addr, int newsize)
3352 unsigned int flags = env->me_flags;
3356 LONG sizelo, sizehi;
3357 sizelo = env->me_mapsize & 0xffffffff;
3358 sizehi = env->me_mapsize >> 16 >> 16; /* only needed on Win64 */
3360 /* Windows won't create mappings for zero length files.
3361 * Just allocate the maxsize right now.
3364 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3365 || !SetEndOfFile(env->me_fd)
3366 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3369 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3370 PAGE_READWRITE : PAGE_READONLY,
3371 sizehi, sizelo, NULL);
3374 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3375 FILE_MAP_WRITE : FILE_MAP_READ,
3376 0, 0, env->me_mapsize, addr);
3377 rc = env->me_map ? 0 : ErrCode();
3382 int prot = PROT_READ;
3383 if (flags & MDB_WRITEMAP) {
3385 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3388 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
3390 if (env->me_map == MAP_FAILED) {
3395 if (flags & MDB_NORDAHEAD) {
3396 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3398 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3400 #ifdef POSIX_MADV_RANDOM
3401 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3402 #endif /* POSIX_MADV_RANDOM */
3403 #endif /* MADV_RANDOM */
3407 /* Can happen because the address argument to mmap() is just a
3408 * hint. mmap() can pick another, e.g. if the range is in use.
3409 * The MAP_FIXED flag would prevent that, but then mmap could
3410 * instead unmap existing pages to make room for the new map.
3412 if (addr && env->me_map != addr)
3413 return EBUSY; /* TODO: Make a new MDB_* error code? */
3415 p = (MDB_page *)env->me_map;
3416 env->me_metas[0] = METADATA(p);
3417 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
3423 mdb_env_set_mapsize(MDB_env *env, size_t size)
3425 /* If env is already open, caller is responsible for making
3426 * sure there are no active txns.
3434 size = env->me_metas[mdb_env_pick_meta(env)]->mm_mapsize;
3435 else if (size < env->me_mapsize) {
3436 /* If the configured size is smaller, make sure it's
3437 * still big enough. Silently round up to minimum if not.
3439 size_t minsize = (env->me_metas[mdb_env_pick_meta(env)]->mm_last_pg + 1) * env->me_psize;
3443 munmap(env->me_map, env->me_mapsize);
3444 env->me_mapsize = size;
3445 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
3446 rc = mdb_env_map(env, old, 1);
3450 env->me_mapsize = size;
3452 env->me_maxpg = env->me_mapsize / env->me_psize;
3457 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
3461 env->me_maxdbs = dbs + 2; /* Named databases + main and free DB */
3466 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
3468 if (env->me_map || readers < 1)
3470 env->me_maxreaders = readers;
3475 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
3477 if (!env || !readers)
3479 *readers = env->me_maxreaders;
3483 /** Further setup required for opening an MDB environment
3486 mdb_env_open2(MDB_env *env)
3488 unsigned int flags = env->me_flags;
3489 int i, newenv = 0, rc;
3493 /* See if we should use QueryLimited */
3495 if ((rc & 0xff) > 5)
3496 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
3498 env->me_pidquery = PROCESS_QUERY_INFORMATION;
3501 memset(&meta, 0, sizeof(meta));
3503 if ((i = mdb_env_read_header(env, &meta)) != 0) {
3506 DPUTS("new mdbenv");
3508 env->me_psize = env->me_os_psize;
3509 if (env->me_psize > MAX_PAGESIZE)
3510 env->me_psize = MAX_PAGESIZE;
3512 env->me_psize = meta.mm_psize;
3515 /* Was a mapsize configured? */
3516 if (!env->me_mapsize) {
3517 /* If this is a new environment, take the default,
3518 * else use the size recorded in the existing env.
3520 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
3521 } else if (env->me_mapsize < meta.mm_mapsize) {
3522 /* If the configured size is smaller, make sure it's
3523 * still big enough. Silently round up to minimum if not.
3525 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
3526 if (env->me_mapsize < minsize)
3527 env->me_mapsize = minsize;
3530 rc = mdb_env_map(env, meta.mm_address, newenv);
3535 if (flags & MDB_FIXEDMAP)
3536 meta.mm_address = env->me_map;
3537 i = mdb_env_init_meta(env, &meta);
3538 if (i != MDB_SUCCESS) {
3543 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
3544 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
3546 #if !(MDB_MAXKEYSIZE)
3547 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
3549 env->me_maxpg = env->me_mapsize / env->me_psize;
3553 int toggle = mdb_env_pick_meta(env);
3554 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
3556 DPRINTF(("opened database version %u, pagesize %u",
3557 env->me_metas[0]->mm_version, env->me_psize));
3558 DPRINTF(("using meta page %d", toggle));
3559 DPRINTF(("depth: %u", db->md_depth));
3560 DPRINTF(("entries: %"Z"u", db->md_entries));
3561 DPRINTF(("branch pages: %"Z"u", db->md_branch_pages));
3562 DPRINTF(("leaf pages: %"Z"u", db->md_leaf_pages));
3563 DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
3564 DPRINTF(("root: %"Z"u", db->md_root));
3572 /** Release a reader thread's slot in the reader lock table.
3573 * This function is called automatically when a thread exits.
3574 * @param[in] ptr This points to the slot in the reader lock table.
3577 mdb_env_reader_dest(void *ptr)
3579 MDB_reader *reader = ptr;
3585 /** Junk for arranging thread-specific callbacks on Windows. This is
3586 * necessarily platform and compiler-specific. Windows supports up
3587 * to 1088 keys. Let's assume nobody opens more than 64 environments
3588 * in a single process, for now. They can override this if needed.
3590 #ifndef MAX_TLS_KEYS
3591 #define MAX_TLS_KEYS 64
3593 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
3594 static int mdb_tls_nkeys;
3596 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
3600 case DLL_PROCESS_ATTACH: break;
3601 case DLL_THREAD_ATTACH: break;
3602 case DLL_THREAD_DETACH:
3603 for (i=0; i<mdb_tls_nkeys; i++) {
3604 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
3605 mdb_env_reader_dest(r);
3608 case DLL_PROCESS_DETACH: break;
3613 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3615 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3619 /* Force some symbol references.
3620 * _tls_used forces the linker to create the TLS directory if not already done
3621 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
3623 #pragma comment(linker, "/INCLUDE:_tls_used")
3624 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
3625 #pragma const_seg(".CRT$XLB")
3626 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
3627 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3630 #pragma comment(linker, "/INCLUDE:__tls_used")
3631 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
3632 #pragma data_seg(".CRT$XLB")
3633 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3635 #endif /* WIN 32/64 */
3636 #endif /* !__GNUC__ */
3639 /** Downgrade the exclusive lock on the region back to shared */
3641 mdb_env_share_locks(MDB_env *env, int *excl)
3643 int rc = 0, toggle = mdb_env_pick_meta(env);
3645 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
3650 /* First acquire a shared lock. The Unlock will
3651 * then release the existing exclusive lock.
3653 memset(&ov, 0, sizeof(ov));
3654 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3657 UnlockFile(env->me_lfd, 0, 0, 1, 0);
3663 struct flock lock_info;
3664 /* The shared lock replaces the existing lock */
3665 memset((void *)&lock_info, 0, sizeof(lock_info));
3666 lock_info.l_type = F_RDLCK;
3667 lock_info.l_whence = SEEK_SET;
3668 lock_info.l_start = 0;
3669 lock_info.l_len = 1;
3670 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3671 (rc = ErrCode()) == EINTR) ;
3672 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
3679 /** Try to get exlusive lock, otherwise shared.
3680 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
3683 mdb_env_excl_lock(MDB_env *env, int *excl)
3687 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
3691 memset(&ov, 0, sizeof(ov));
3692 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3699 struct flock lock_info;
3700 memset((void *)&lock_info, 0, sizeof(lock_info));
3701 lock_info.l_type = F_WRLCK;
3702 lock_info.l_whence = SEEK_SET;
3703 lock_info.l_start = 0;
3704 lock_info.l_len = 1;
3705 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3706 (rc = ErrCode()) == EINTR) ;
3710 # ifdef MDB_USE_POSIX_SEM
3711 if (*excl < 0) /* always true when !MDB_USE_POSIX_SEM */
3714 lock_info.l_type = F_RDLCK;
3715 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
3716 (rc = ErrCode()) == EINTR) ;
3726 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
3728 * @(#) $Revision: 5.1 $
3729 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
3730 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
3732 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
3736 * Please do not copyright this code. This code is in the public domain.
3738 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
3739 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
3740 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
3741 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
3742 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
3743 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
3744 * PERFORMANCE OF THIS SOFTWARE.
3747 * chongo <Landon Curt Noll> /\oo/\
3748 * http://www.isthe.com/chongo/
3750 * Share and Enjoy! :-)
3753 typedef unsigned long long mdb_hash_t;
3754 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
3756 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
3757 * @param[in] val value to hash
3758 * @param[in] hval initial value for hash
3759 * @return 64 bit hash
3761 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
3762 * hval arg on the first call.
3765 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
3767 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
3768 unsigned char *end = s + val->mv_size;
3770 * FNV-1a hash each octet of the string
3773 /* xor the bottom with the current octet */
3774 hval ^= (mdb_hash_t)*s++;
3776 /* multiply by the 64 bit FNV magic prime mod 2^64 */
3777 hval += (hval << 1) + (hval << 4) + (hval << 5) +
3778 (hval << 7) + (hval << 8) + (hval << 40);
3780 /* return our new hash value */
3784 /** Hash the string and output the encoded hash.
3785 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
3786 * very short name limits. We don't care about the encoding being reversible,
3787 * we just want to preserve as many bits of the input as possible in a
3788 * small printable string.
3789 * @param[in] str string to hash
3790 * @param[out] encbuf an array of 11 chars to hold the hash
3792 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
3795 mdb_pack85(unsigned long l, char *out)
3799 for (i=0; i<5; i++) {
3800 *out++ = mdb_a85[l % 85];
3806 mdb_hash_enc(MDB_val *val, char *encbuf)
3808 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
3810 mdb_pack85(h, encbuf);
3811 mdb_pack85(h>>32, encbuf+5);
3816 /** Open and/or initialize the lock region for the environment.
3817 * @param[in] env The MDB environment.
3818 * @param[in] lpath The pathname of the file used for the lock region.
3819 * @param[in] mode The Unix permissions for the file, if we create it.
3820 * @param[out] excl Resulting file lock type: -1 none, 0 shared, 1 exclusive
3821 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
3822 * @return 0 on success, non-zero on failure.
3825 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
3828 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
3830 # define MDB_ERRCODE_ROFS EROFS
3831 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
3832 # define MDB_CLOEXEC O_CLOEXEC
3835 # define MDB_CLOEXEC 0
3842 env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
3843 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
3844 FILE_ATTRIBUTE_NORMAL, NULL);
3846 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
3848 if (env->me_lfd == INVALID_HANDLE_VALUE) {
3850 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
3855 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
3856 /* Lose record locks when exec*() */
3857 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
3858 fcntl(env->me_lfd, F_SETFD, fdflags);
3861 if (!(env->me_flags & MDB_NOTLS)) {
3862 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
3865 env->me_flags |= MDB_ENV_TXKEY;
3867 /* Windows TLS callbacks need help finding their TLS info. */
3868 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
3872 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
3876 /* Try to get exclusive lock. If we succeed, then
3877 * nobody is using the lock region and we should initialize it.
3879 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
3882 size = GetFileSize(env->me_lfd, NULL);
3884 size = lseek(env->me_lfd, 0, SEEK_END);
3885 if (size == -1) goto fail_errno;
3887 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
3888 if (size < rsize && *excl > 0) {
3890 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
3891 || !SetEndOfFile(env->me_lfd))
3894 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
3898 size = rsize - sizeof(MDB_txninfo);
3899 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
3904 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
3906 if (!mh) goto fail_errno;
3907 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
3909 if (!env->me_txns) goto fail_errno;
3911 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
3913 if (m == MAP_FAILED) goto fail_errno;
3919 BY_HANDLE_FILE_INFORMATION stbuf;
3928 if (!mdb_sec_inited) {
3929 InitializeSecurityDescriptor(&mdb_null_sd,
3930 SECURITY_DESCRIPTOR_REVISION);
3931 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
3932 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
3933 mdb_all_sa.bInheritHandle = FALSE;
3934 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
3937 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
3938 idbuf.volume = stbuf.dwVolumeSerialNumber;
3939 idbuf.nhigh = stbuf.nFileIndexHigh;
3940 idbuf.nlow = stbuf.nFileIndexLow;
3941 val.mv_data = &idbuf;
3942 val.mv_size = sizeof(idbuf);
3943 mdb_hash_enc(&val, encbuf);
3944 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
3945 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
3946 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
3947 if (!env->me_rmutex) goto fail_errno;
3948 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
3949 if (!env->me_wmutex) goto fail_errno;
3950 #elif defined(MDB_USE_POSIX_SEM)
3959 #if defined(__NetBSD__)
3960 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
3962 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
3963 idbuf.dev = stbuf.st_dev;
3964 idbuf.ino = stbuf.st_ino;
3965 val.mv_data = &idbuf;
3966 val.mv_size = sizeof(idbuf);
3967 mdb_hash_enc(&val, encbuf);
3968 #ifdef MDB_SHORT_SEMNAMES
3969 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
3971 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
3972 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
3973 /* Clean up after a previous run, if needed: Try to
3974 * remove both semaphores before doing anything else.
3976 sem_unlink(env->me_txns->mti_rmname);
3977 sem_unlink(env->me_txns->mti_wmname);
3978 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
3979 O_CREAT|O_EXCL, mode, 1);
3980 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3981 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
3982 O_CREAT|O_EXCL, mode, 1);
3983 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3984 #else /* MDB_USE_POSIX_SEM */
3985 pthread_mutexattr_t mattr;
3987 if ((rc = pthread_mutexattr_init(&mattr))
3988 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
3989 || (rc = pthread_mutex_init(&env->me_txns->mti_mutex, &mattr))
3990 || (rc = pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr)))
3992 pthread_mutexattr_destroy(&mattr);
3993 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
3995 env->me_txns->mti_magic = MDB_MAGIC;
3996 env->me_txns->mti_format = MDB_LOCK_FORMAT;
3997 env->me_txns->mti_txnid = 0;
3998 env->me_txns->mti_numreaders = 0;
4001 if (env->me_txns->mti_magic != MDB_MAGIC) {
4002 DPUTS("lock region has invalid magic");
4006 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
4007 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
4008 env->me_txns->mti_format, MDB_LOCK_FORMAT));
4009 rc = MDB_VERSION_MISMATCH;
4013 if (rc && rc != EACCES && rc != EAGAIN) {
4017 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
4018 if (!env->me_rmutex) goto fail_errno;
4019 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
4020 if (!env->me_wmutex) goto fail_errno;
4021 #elif defined(MDB_USE_POSIX_SEM)
4022 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
4023 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4024 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
4025 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4036 /** The name of the lock file in the DB environment */
4037 #define LOCKNAME "/lock.mdb"
4038 /** The name of the data file in the DB environment */
4039 #define DATANAME "/data.mdb"
4040 /** The suffix of the lock file when no subdir is used */
4041 #define LOCKSUFF "-lock"
4042 /** Only a subset of the @ref mdb_env flags can be changed
4043 * at runtime. Changing other flags requires closing the
4044 * environment and re-opening it with the new flags.
4046 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
4047 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY|MDB_WRITEMAP| \
4048 MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
4050 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
4051 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
4055 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
4057 int oflags, rc, len, excl = -1;
4058 char *lpath, *dpath;
4060 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
4064 if (flags & MDB_NOSUBDIR) {
4065 rc = len + sizeof(LOCKSUFF) + len + 1;
4067 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
4072 if (flags & MDB_NOSUBDIR) {
4073 dpath = lpath + len + sizeof(LOCKSUFF);
4074 sprintf(lpath, "%s" LOCKSUFF, path);
4075 strcpy(dpath, path);
4077 dpath = lpath + len + sizeof(LOCKNAME);
4078 sprintf(lpath, "%s" LOCKNAME, path);
4079 sprintf(dpath, "%s" DATANAME, path);
4083 flags |= env->me_flags;
4084 if (flags & MDB_RDONLY) {
4085 /* silently ignore WRITEMAP when we're only getting read access */
4086 flags &= ~MDB_WRITEMAP;
4088 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
4089 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
4092 env->me_flags = flags |= MDB_ENV_ACTIVE;
4096 env->me_path = strdup(path);
4097 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
4098 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
4099 if (!(env->me_dbxs && env->me_path && env->me_dbflags)) {
4104 /* For RDONLY, get lockfile after we know datafile exists */
4105 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
4106 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4112 if (F_ISSET(flags, MDB_RDONLY)) {
4113 oflags = GENERIC_READ;
4114 len = OPEN_EXISTING;
4116 oflags = GENERIC_READ|GENERIC_WRITE;
4119 mode = FILE_ATTRIBUTE_NORMAL;
4120 env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
4121 NULL, len, mode, NULL);
4123 if (F_ISSET(flags, MDB_RDONLY))
4126 oflags = O_RDWR | O_CREAT;
4128 env->me_fd = open(dpath, oflags, mode);
4130 if (env->me_fd == INVALID_HANDLE_VALUE) {
4135 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
4136 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4141 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
4142 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
4143 env->me_mfd = env->me_fd;
4145 /* Synchronous fd for meta writes. Needed even with
4146 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
4149 len = OPEN_EXISTING;
4150 env->me_mfd = CreateFile(dpath, oflags,
4151 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
4152 mode | FILE_FLAG_WRITE_THROUGH, NULL);
4155 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
4157 if (env->me_mfd == INVALID_HANDLE_VALUE) {
4162 DPRINTF(("opened dbenv %p", (void *) env));
4164 rc = mdb_env_share_locks(env, &excl);
4168 if (!((flags & MDB_RDONLY) ||
4169 (env->me_pbuf = calloc(1, env->me_psize))))
4175 mdb_env_close0(env, excl);
4181 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
4183 mdb_env_close0(MDB_env *env, int excl)
4187 if (!(env->me_flags & MDB_ENV_ACTIVE))
4190 /* Doing this here since me_dbxs may not exist during mdb_env_close */
4191 for (i = env->me_maxdbs; --i > MAIN_DBI; )
4192 free(env->me_dbxs[i].md_name.mv_data);
4195 free(env->me_dbflags);
4198 free(env->me_dirty_list);
4199 mdb_midl_free(env->me_free_pgs);
4201 if (env->me_flags & MDB_ENV_TXKEY) {
4202 pthread_key_delete(env->me_txkey);
4204 /* Delete our key from the global list */
4205 for (i=0; i<mdb_tls_nkeys; i++)
4206 if (mdb_tls_keys[i] == env->me_txkey) {
4207 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
4215 munmap(env->me_map, env->me_mapsize);
4217 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
4218 (void) close(env->me_mfd);
4219 if (env->me_fd != INVALID_HANDLE_VALUE)
4220 (void) close(env->me_fd);
4222 MDB_PID_T pid = env->me_pid;
4223 /* Clearing readers is done in this function because
4224 * me_txkey with its destructor must be disabled first.
4226 for (i = env->me_numreaders; --i >= 0; )
4227 if (env->me_txns->mti_readers[i].mr_pid == pid)
4228 env->me_txns->mti_readers[i].mr_pid = 0;
4230 if (env->me_rmutex) {
4231 CloseHandle(env->me_rmutex);
4232 if (env->me_wmutex) CloseHandle(env->me_wmutex);
4234 /* Windows automatically destroys the mutexes when
4235 * the last handle closes.
4237 #elif defined(MDB_USE_POSIX_SEM)
4238 if (env->me_rmutex != SEM_FAILED) {
4239 sem_close(env->me_rmutex);
4240 if (env->me_wmutex != SEM_FAILED)
4241 sem_close(env->me_wmutex);
4242 /* If we have the filelock: If we are the
4243 * only remaining user, clean up semaphores.
4246 mdb_env_excl_lock(env, &excl);
4248 sem_unlink(env->me_txns->mti_rmname);
4249 sem_unlink(env->me_txns->mti_wmname);
4253 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
4255 if (env->me_lfd != INVALID_HANDLE_VALUE) {
4258 /* Unlock the lockfile. Windows would have unlocked it
4259 * after closing anyway, but not necessarily at once.
4261 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4264 (void) close(env->me_lfd);
4267 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
4271 mdb_env_copyfd(MDB_env *env, HANDLE fd)
4273 MDB_txn *txn = NULL;
4279 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
4283 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
4286 /* Do the lock/unlock of the reader mutex before starting the
4287 * write txn. Otherwise other read txns could block writers.
4289 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
4294 /* We must start the actual read txn after blocking writers */
4295 mdb_txn_reset0(txn, "reset-stage1");
4297 /* Temporarily block writers until we snapshot the meta pages */
4300 rc = mdb_txn_renew0(txn);
4302 UNLOCK_MUTEX_W(env);
4307 wsize = env->me_psize * 2;
4311 DO_WRITE(rc, fd, ptr, w2, len);
4315 } else if (len > 0) {
4321 /* Non-blocking or async handles are not supported */
4327 UNLOCK_MUTEX_W(env);
4332 wsize = txn->mt_next_pgno * env->me_psize - wsize;
4334 if (wsize > MAX_WRITE)
4338 DO_WRITE(rc, fd, ptr, w2, len);
4342 } else if (len > 0) {
4359 mdb_env_copy(MDB_env *env, const char *path)
4363 HANDLE newfd = INVALID_HANDLE_VALUE;
4365 if (env->me_flags & MDB_NOSUBDIR) {
4366 lpath = (char *)path;
4369 len += sizeof(DATANAME);
4370 lpath = malloc(len);
4373 sprintf(lpath, "%s" DATANAME, path);
4376 /* The destination path must exist, but the destination file must not.
4377 * We don't want the OS to cache the writes, since the source data is
4378 * already in the OS cache.
4381 newfd = CreateFile(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
4382 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
4384 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
4386 if (newfd == INVALID_HANDLE_VALUE) {
4392 /* Set O_DIRECT if the file system supports it */
4393 if ((rc = fcntl(newfd, F_GETFL)) != -1)
4394 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
4396 #ifdef F_NOCACHE /* __APPLE__ */
4397 rc = fcntl(newfd, F_NOCACHE, 1);
4404 rc = mdb_env_copyfd(env, newfd);
4407 if (!(env->me_flags & MDB_NOSUBDIR))
4409 if (newfd != INVALID_HANDLE_VALUE)
4410 if (close(newfd) < 0 && rc == MDB_SUCCESS)
4417 mdb_env_close(MDB_env *env)
4424 VGMEMP_DESTROY(env);
4425 while ((dp = env->me_dpages) != NULL) {
4426 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
4427 env->me_dpages = dp->mp_next;
4431 mdb_env_close0(env, 0);
4435 /** Compare two items pointing at aligned size_t's */
4437 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
4439 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
4440 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
4443 /** Compare two items pointing at aligned unsigned int's */
4445 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
4447 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
4448 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
4451 /** Compare two items pointing at unsigned ints of unknown alignment.
4452 * Nodes and keys are guaranteed to be 2-byte aligned.
4455 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
4457 #if BYTE_ORDER == LITTLE_ENDIAN
4458 unsigned short *u, *c;
4461 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4462 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
4465 } while(!x && u > (unsigned short *)a->mv_data);
4468 return memcmp(a->mv_data, b->mv_data, a->mv_size);
4472 /** Compare two items lexically */
4474 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
4481 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4487 diff = memcmp(a->mv_data, b->mv_data, len);
4488 return diff ? diff : len_diff<0 ? -1 : len_diff;
4491 /** Compare two items in reverse byte order */
4493 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
4495 const unsigned char *p1, *p2, *p1_lim;
4499 p1_lim = (const unsigned char *)a->mv_data;
4500 p1 = (const unsigned char *)a->mv_data + a->mv_size;
4501 p2 = (const unsigned char *)b->mv_data + b->mv_size;
4503 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4509 while (p1 > p1_lim) {
4510 diff = *--p1 - *--p2;
4514 return len_diff<0 ? -1 : len_diff;
4517 /** Search for key within a page, using binary search.
4518 * Returns the smallest entry larger or equal to the key.
4519 * If exactp is non-null, stores whether the found entry was an exact match
4520 * in *exactp (1 or 0).
4521 * Updates the cursor index with the index of the found entry.
4522 * If no entry larger or equal to the key is found, returns NULL.
4525 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
4527 unsigned int i = 0, nkeys;
4530 MDB_page *mp = mc->mc_pg[mc->mc_top];
4531 MDB_node *node = NULL;
4536 nkeys = NUMKEYS(mp);
4538 DPRINTF(("searching %u keys in %s %spage %"Z"u",
4539 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
4542 low = IS_LEAF(mp) ? 0 : 1;
4544 cmp = mc->mc_dbx->md_cmp;
4546 /* Branch pages have no data, so if using integer keys,
4547 * alignment is guaranteed. Use faster mdb_cmp_int.
4549 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
4550 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
4557 nodekey.mv_size = mc->mc_db->md_pad;
4558 node = NODEPTR(mp, 0); /* fake */
4559 while (low <= high) {
4560 i = (low + high) >> 1;
4561 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
4562 rc = cmp(key, &nodekey);
4563 DPRINTF(("found leaf index %u [%s], rc = %i",
4564 i, DKEY(&nodekey), rc));
4573 while (low <= high) {
4574 i = (low + high) >> 1;
4576 node = NODEPTR(mp, i);
4577 nodekey.mv_size = NODEKSZ(node);
4578 nodekey.mv_data = NODEKEY(node);
4580 rc = cmp(key, &nodekey);
4583 DPRINTF(("found leaf index %u [%s], rc = %i",
4584 i, DKEY(&nodekey), rc));
4586 DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
4587 i, DKEY(&nodekey), NODEPGNO(node), rc));
4598 if (rc > 0) { /* Found entry is less than the key. */
4599 i++; /* Skip to get the smallest entry larger than key. */
4601 node = NODEPTR(mp, i);
4604 *exactp = (rc == 0 && nkeys > 0);
4605 /* store the key index */
4606 mc->mc_ki[mc->mc_top] = i;
4608 /* There is no entry larger or equal to the key. */
4611 /* nodeptr is fake for LEAF2 */
4617 mdb_cursor_adjust(MDB_cursor *mc, func)
4621 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4622 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
4629 /** Pop a page off the top of the cursor's stack. */
4631 mdb_cursor_pop(MDB_cursor *mc)
4635 MDB_page *top = mc->mc_pg[mc->mc_top];
4641 DPRINTF(("popped page %"Z"u off db %d cursor %p", top->mp_pgno,
4642 DDBI(mc), (void *) mc));
4646 /** Push a page onto the top of the cursor's stack. */
4648 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
4650 DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
4651 DDBI(mc), (void *) mc));
4653 if (mc->mc_snum >= CURSOR_STACK) {
4654 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4655 return MDB_CURSOR_FULL;
4658 mc->mc_top = mc->mc_snum++;
4659 mc->mc_pg[mc->mc_top] = mp;
4660 mc->mc_ki[mc->mc_top] = 0;
4665 /** Find the address of the page corresponding to a given page number.
4666 * @param[in] txn the transaction for this access.
4667 * @param[in] pgno the page number for the page to retrieve.
4668 * @param[out] ret address of a pointer where the page's address will be stored.
4669 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
4670 * @return 0 on success, non-zero on failure.
4673 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
4675 MDB_env *env = txn->mt_env;
4679 if (!((txn->mt_flags & MDB_TXN_RDONLY) | (env->me_flags & MDB_WRITEMAP))) {
4683 MDB_ID2L dl = tx2->mt_u.dirty_list;
4685 /* Spilled pages were dirtied in this txn and flushed
4686 * because the dirty list got full. Bring this page
4687 * back in from the map (but don't unspill it here,
4688 * leave that unless page_touch happens again).
4690 if (tx2->mt_spill_pgs) {
4691 MDB_ID pn = pgno << 1;
4692 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
4693 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
4694 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
4699 unsigned x = mdb_mid2l_search(dl, pgno);
4700 if (x <= dl[0].mid && dl[x].mid == pgno) {
4706 } while ((tx2 = tx2->mt_parent) != NULL);
4709 if (pgno < txn->mt_next_pgno) {
4711 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
4713 DPRINTF(("page %"Z"u not found", pgno));
4714 txn->mt_flags |= MDB_TXN_ERROR;
4715 return MDB_PAGE_NOTFOUND;
4725 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
4726 * The cursor is at the root page, set up the rest of it.
4729 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
4731 MDB_page *mp = mc->mc_pg[mc->mc_top];
4735 while (IS_BRANCH(mp)) {
4739 DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
4740 assert(NUMKEYS(mp) > 1);
4741 DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
4743 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
4745 if (flags & MDB_PS_LAST)
4746 i = NUMKEYS(mp) - 1;
4749 node = mdb_node_search(mc, key, &exact);
4751 i = NUMKEYS(mp) - 1;
4753 i = mc->mc_ki[mc->mc_top];
4759 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
4762 assert(i < NUMKEYS(mp));
4763 node = NODEPTR(mp, i);
4765 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4768 mc->mc_ki[mc->mc_top] = i;
4769 if ((rc = mdb_cursor_push(mc, mp)))
4772 if (flags & MDB_PS_MODIFY) {
4773 if ((rc = mdb_page_touch(mc)) != 0)
4775 mp = mc->mc_pg[mc->mc_top];
4780 DPRINTF(("internal error, index points to a %02X page!?",
4782 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4783 return MDB_CORRUPTED;
4786 DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
4787 key ? DKEY(key) : "null"));
4788 mc->mc_flags |= C_INITIALIZED;
4789 mc->mc_flags &= ~C_EOF;
4794 /** Search for the lowest key under the current branch page.
4795 * This just bypasses a NUMKEYS check in the current page
4796 * before calling mdb_page_search_root(), because the callers
4797 * are all in situations where the current page is known to
4801 mdb_page_search_lowest(MDB_cursor *mc)
4803 MDB_page *mp = mc->mc_pg[mc->mc_top];
4804 MDB_node *node = NODEPTR(mp, 0);
4807 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4810 mc->mc_ki[mc->mc_top] = 0;
4811 if ((rc = mdb_cursor_push(mc, mp)))
4813 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
4816 /** Search for the page a given key should be in.
4817 * Push it and its parent pages on the cursor stack.
4818 * @param[in,out] mc the cursor for this operation.
4819 * @param[in] key the key to search for, or NULL for first/last page.
4820 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
4821 * are touched (updated with new page numbers).
4822 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
4823 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
4824 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
4825 * @return 0 on success, non-zero on failure.
4828 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
4833 /* Make sure the txn is still viable, then find the root from
4834 * the txn's db table and set it as the root of the cursor's stack.
4836 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
4837 DPUTS("transaction has failed, must abort");
4840 /* Make sure we're using an up-to-date root */
4841 if (*mc->mc_dbflag & DB_STALE) {
4843 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
4844 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
4851 MDB_node *leaf = mdb_node_search(&mc2,
4852 &mc->mc_dbx->md_name, &exact);
4854 return MDB_NOTFOUND;
4855 rc = mdb_node_read(mc->mc_txn, leaf, &data);
4858 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
4860 /* The txn may not know this DBI, or another process may
4861 * have dropped and recreated the DB with other flags.
4863 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
4864 return MDB_INCOMPATIBLE;
4865 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
4867 *mc->mc_dbflag &= ~DB_STALE;
4869 root = mc->mc_db->md_root;
4871 if (root == P_INVALID) { /* Tree is empty. */
4872 DPUTS("tree is empty");
4873 return MDB_NOTFOUND;
4878 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
4879 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0], NULL)) != 0)
4885 DPRINTF(("db %d root page %"Z"u has flags 0x%X",
4886 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
4888 if (flags & MDB_PS_MODIFY) {
4889 if ((rc = mdb_page_touch(mc)))
4893 if (flags & MDB_PS_ROOTONLY)
4896 return mdb_page_search_root(mc, key, flags);
4900 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
4902 MDB_txn *txn = mc->mc_txn;
4903 pgno_t pg = mp->mp_pgno;
4904 unsigned x = 0, ovpages = mp->mp_pages;
4905 MDB_env *env = txn->mt_env;
4906 MDB_IDL sl = txn->mt_spill_pgs;
4907 MDB_ID pn = pg << 1;
4910 DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
4911 /* If the page is dirty or on the spill list we just acquired it,
4912 * so we should give it back to our current free list, if any.
4913 * Otherwise put it onto the list of pages we freed in this txn.
4915 * Won't create me_pghead: me_pglast must be inited along with it.
4916 * Unsupported in nested txns: They would need to hide the page
4917 * range in ancestor txns' dirty and spilled lists.
4919 if (env->me_pghead &&
4921 ((mp->mp_flags & P_DIRTY) ||
4922 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
4926 MDB_ID2 *dl, ix, iy;
4927 rc = mdb_midl_need(&env->me_pghead, ovpages);
4930 if (!(mp->mp_flags & P_DIRTY)) {
4931 /* This page is no longer spilled */
4938 /* Remove from dirty list */
4939 dl = txn->mt_u.dirty_list;
4941 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
4949 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
4950 txn->mt_flags |= MDB_TXN_ERROR;
4951 return MDB_CORRUPTED;
4954 if (!(env->me_flags & MDB_WRITEMAP))
4955 mdb_dpage_free(env, mp);
4957 /* Insert in me_pghead */
4958 mop = env->me_pghead;
4959 j = mop[0] + ovpages;
4960 for (i = mop[0]; i && mop[i] < pg; i--)
4966 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
4970 mc->mc_db->md_overflow_pages -= ovpages;
4974 /** Return the data associated with a given node.
4975 * @param[in] txn The transaction for this operation.
4976 * @param[in] leaf The node being read.
4977 * @param[out] data Updated to point to the node's data.
4978 * @return 0 on success, non-zero on failure.
4981 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
4983 MDB_page *omp; /* overflow page */
4987 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
4988 data->mv_size = NODEDSZ(leaf);
4989 data->mv_data = NODEDATA(leaf);
4993 /* Read overflow data.
4995 data->mv_size = NODEDSZ(leaf);
4996 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
4997 if ((rc = mdb_page_get(txn, pgno, &omp, NULL)) != 0) {
4998 DPRINTF(("read overflow page %"Z"u failed", pgno));
5001 data->mv_data = METADATA(omp);
5007 mdb_get(MDB_txn *txn, MDB_dbi dbi,
5008 MDB_val *key, MDB_val *data)
5015 if (key == NULL || data == NULL)
5018 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
5020 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
5023 if (txn->mt_flags & MDB_TXN_ERROR)
5026 mdb_cursor_init(&mc, txn, dbi, &mx);
5027 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
5030 /** Find a sibling for a page.
5031 * Replaces the page at the top of the cursor's stack with the
5032 * specified sibling, if one exists.
5033 * @param[in] mc The cursor for this operation.
5034 * @param[in] move_right Non-zero if the right sibling is requested,
5035 * otherwise the left sibling.
5036 * @return 0 on success, non-zero on failure.
5039 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
5045 if (mc->mc_snum < 2) {
5046 return MDB_NOTFOUND; /* root has no siblings */
5050 DPRINTF(("parent page is page %"Z"u, index %u",
5051 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
5053 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
5054 : (mc->mc_ki[mc->mc_top] == 0)) {
5055 DPRINTF(("no more keys left, moving to %s sibling",
5056 move_right ? "right" : "left"));
5057 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
5058 /* undo cursor_pop before returning */
5065 mc->mc_ki[mc->mc_top]++;
5067 mc->mc_ki[mc->mc_top]--;
5068 DPRINTF(("just moving to %s index key %u",
5069 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
5071 assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
5073 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5074 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL)) != 0) {
5075 /* mc will be inconsistent if caller does mc_snum++ as above */
5076 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
5080 mdb_cursor_push(mc, mp);
5082 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
5087 /** Move the cursor to the next data item. */
5089 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5095 if (mc->mc_flags & C_EOF) {
5096 return MDB_NOTFOUND;
5099 assert(mc->mc_flags & C_INITIALIZED);
5101 mp = mc->mc_pg[mc->mc_top];
5103 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5104 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5105 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5106 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
5107 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
5108 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
5109 if (rc == MDB_SUCCESS)
5110 MDB_GET_KEY(leaf, key);
5115 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5116 if (op == MDB_NEXT_DUP)
5117 return MDB_NOTFOUND;
5121 DPRINTF(("cursor_next: top page is %"Z"u in cursor %p",
5122 mdb_dbg_pgno(mp), (void *) mc));
5123 if (mc->mc_flags & C_DEL)
5126 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
5127 DPUTS("=====> move to next sibling page");
5128 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5129 mc->mc_flags |= C_EOF;
5132 mp = mc->mc_pg[mc->mc_top];
5133 DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5135 mc->mc_ki[mc->mc_top]++;
5138 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5139 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5142 key->mv_size = mc->mc_db->md_pad;
5143 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5147 assert(IS_LEAF(mp));
5148 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5150 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5151 mdb_xcursor_init1(mc, leaf);
5154 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5157 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5158 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5159 if (rc != MDB_SUCCESS)
5164 MDB_GET_KEY(leaf, key);
5168 /** Move the cursor to the previous data item. */
5170 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5176 assert(mc->mc_flags & C_INITIALIZED);
5178 mp = mc->mc_pg[mc->mc_top];
5180 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5181 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5182 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5183 if (op == MDB_PREV || op == MDB_PREV_DUP) {
5184 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
5185 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
5186 if (rc == MDB_SUCCESS)
5187 MDB_GET_KEY(leaf, key);
5191 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5192 if (op == MDB_PREV_DUP)
5193 return MDB_NOTFOUND;
5198 DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p",
5199 mdb_dbg_pgno(mp), (void *) mc));
5201 if (mc->mc_ki[mc->mc_top] == 0) {
5202 DPUTS("=====> move to prev sibling page");
5203 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
5206 mp = mc->mc_pg[mc->mc_top];
5207 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
5208 DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5210 mc->mc_ki[mc->mc_top]--;
5212 mc->mc_flags &= ~C_EOF;
5214 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5215 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5218 key->mv_size = mc->mc_db->md_pad;
5219 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5223 assert(IS_LEAF(mp));
5224 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5226 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5227 mdb_xcursor_init1(mc, leaf);
5230 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5233 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5234 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5235 if (rc != MDB_SUCCESS)
5240 MDB_GET_KEY(leaf, key);
5244 /** Set the cursor on a specific data item. */
5246 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5247 MDB_cursor_op op, int *exactp)
5251 MDB_node *leaf = NULL;
5256 if (key->mv_size == 0)
5257 return MDB_BAD_VALSIZE;
5260 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5262 /* See if we're already on the right page */
5263 if (mc->mc_flags & C_INITIALIZED) {
5266 mp = mc->mc_pg[mc->mc_top];
5268 mc->mc_ki[mc->mc_top] = 0;
5269 return MDB_NOTFOUND;
5271 if (mp->mp_flags & P_LEAF2) {
5272 nodekey.mv_size = mc->mc_db->md_pad;
5273 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
5275 leaf = NODEPTR(mp, 0);
5276 MDB_GET_KEY2(leaf, nodekey);
5278 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5280 /* Probably happens rarely, but first node on the page
5281 * was the one we wanted.
5283 mc->mc_ki[mc->mc_top] = 0;
5290 unsigned int nkeys = NUMKEYS(mp);
5292 if (mp->mp_flags & P_LEAF2) {
5293 nodekey.mv_data = LEAF2KEY(mp,
5294 nkeys-1, nodekey.mv_size);
5296 leaf = NODEPTR(mp, nkeys-1);
5297 MDB_GET_KEY2(leaf, nodekey);
5299 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5301 /* last node was the one we wanted */
5302 mc->mc_ki[mc->mc_top] = nkeys-1;
5308 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
5309 /* This is definitely the right page, skip search_page */
5310 if (mp->mp_flags & P_LEAF2) {
5311 nodekey.mv_data = LEAF2KEY(mp,
5312 mc->mc_ki[mc->mc_top], nodekey.mv_size);
5314 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5315 MDB_GET_KEY2(leaf, nodekey);
5317 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5319 /* current node was the one we wanted */
5329 /* If any parents have right-sibs, search.
5330 * Otherwise, there's nothing further.
5332 for (i=0; i<mc->mc_top; i++)
5334 NUMKEYS(mc->mc_pg[i])-1)
5336 if (i == mc->mc_top) {
5337 /* There are no other pages */
5338 mc->mc_ki[mc->mc_top] = nkeys;
5339 return MDB_NOTFOUND;
5343 /* There are no other pages */
5344 mc->mc_ki[mc->mc_top] = 0;
5345 if (op == MDB_SET_RANGE) {
5349 return MDB_NOTFOUND;
5353 rc = mdb_page_search(mc, key, 0);
5354 if (rc != MDB_SUCCESS)
5357 mp = mc->mc_pg[mc->mc_top];
5358 assert(IS_LEAF(mp));
5361 leaf = mdb_node_search(mc, key, exactp);
5362 if (exactp != NULL && !*exactp) {
5363 /* MDB_SET specified and not an exact match. */
5364 return MDB_NOTFOUND;
5368 DPUTS("===> inexact leaf not found, goto sibling");
5369 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
5370 return rc; /* no entries matched */
5371 mp = mc->mc_pg[mc->mc_top];
5372 assert(IS_LEAF(mp));
5373 leaf = NODEPTR(mp, 0);
5377 mc->mc_flags |= C_INITIALIZED;
5378 mc->mc_flags &= ~C_EOF;
5381 key->mv_size = mc->mc_db->md_pad;
5382 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5386 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5387 mdb_xcursor_init1(mc, leaf);
5390 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5391 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
5392 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5395 if (op == MDB_GET_BOTH) {
5401 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
5402 if (rc != MDB_SUCCESS)
5405 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
5407 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
5409 rc = mc->mc_dbx->md_dcmp(data, &d2);
5411 if (op == MDB_GET_BOTH || rc > 0)
5412 return MDB_NOTFOUND;
5419 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5420 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5425 /* The key already matches in all other cases */
5426 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
5427 MDB_GET_KEY(leaf, key);
5428 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
5433 /** Move the cursor to the first item in the database. */
5435 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5441 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5443 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5444 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
5445 if (rc != MDB_SUCCESS)
5448 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
5450 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
5451 mc->mc_flags |= C_INITIALIZED;
5452 mc->mc_flags &= ~C_EOF;
5454 mc->mc_ki[mc->mc_top] = 0;
5456 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5457 key->mv_size = mc->mc_db->md_pad;
5458 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
5463 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5464 mdb_xcursor_init1(mc, leaf);
5465 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5469 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5473 MDB_GET_KEY(leaf, key);
5477 /** Move the cursor to the last item in the database. */
5479 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5485 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5487 if (!(mc->mc_flags & C_EOF)) {
5489 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5490 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
5491 if (rc != MDB_SUCCESS)
5494 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
5497 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
5498 mc->mc_flags |= C_INITIALIZED|C_EOF;
5499 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5501 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5502 key->mv_size = mc->mc_db->md_pad;
5503 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
5508 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5509 mdb_xcursor_init1(mc, leaf);
5510 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5514 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5519 MDB_GET_KEY(leaf, key);
5524 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5529 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
5534 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
5538 case MDB_GET_CURRENT:
5539 if (!(mc->mc_flags & C_INITIALIZED)) {
5542 MDB_page *mp = mc->mc_pg[mc->mc_top];
5543 int nkeys = NUMKEYS(mp);
5544 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
5545 mc->mc_ki[mc->mc_top] = nkeys;
5551 key->mv_size = mc->mc_db->md_pad;
5552 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5554 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5555 MDB_GET_KEY(leaf, key);
5557 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5558 if (mc->mc_flags & C_DEL)
5559 mdb_xcursor_init1(mc, leaf);
5560 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
5562 rc = mdb_node_read(mc->mc_txn, leaf, data);
5569 case MDB_GET_BOTH_RANGE:
5574 if (mc->mc_xcursor == NULL) {
5575 rc = MDB_INCOMPATIBLE;
5585 rc = mdb_cursor_set(mc, key, data, op,
5586 op == MDB_SET_RANGE ? NULL : &exact);
5589 case MDB_GET_MULTIPLE:
5590 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5594 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5595 rc = MDB_INCOMPATIBLE;
5599 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
5600 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
5603 case MDB_NEXT_MULTIPLE:
5608 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5609 rc = MDB_INCOMPATIBLE;
5612 if (!(mc->mc_flags & C_INITIALIZED))
5613 rc = mdb_cursor_first(mc, key, data);
5615 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
5616 if (rc == MDB_SUCCESS) {
5617 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
5620 mx = &mc->mc_xcursor->mx_cursor;
5621 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
5623 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
5624 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
5632 case MDB_NEXT_NODUP:
5633 if (!(mc->mc_flags & C_INITIALIZED))
5634 rc = mdb_cursor_first(mc, key, data);
5636 rc = mdb_cursor_next(mc, key, data, op);
5640 case MDB_PREV_NODUP:
5641 if (!(mc->mc_flags & C_INITIALIZED)) {
5642 rc = mdb_cursor_last(mc, key, data);
5645 mc->mc_flags |= C_INITIALIZED;
5646 mc->mc_ki[mc->mc_top]++;
5648 rc = mdb_cursor_prev(mc, key, data, op);
5651 rc = mdb_cursor_first(mc, key, data);
5654 mfunc = mdb_cursor_first;
5656 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5660 if (mc->mc_xcursor == NULL) {
5661 rc = MDB_INCOMPATIBLE;
5664 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
5668 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
5671 rc = mdb_cursor_last(mc, key, data);
5674 mfunc = mdb_cursor_last;
5677 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
5682 if (mc->mc_flags & C_DEL)
5683 mc->mc_flags ^= C_DEL;
5688 /** Touch all the pages in the cursor stack. Set mc_top.
5689 * Makes sure all the pages are writable, before attempting a write operation.
5690 * @param[in] mc The cursor to operate on.
5693 mdb_cursor_touch(MDB_cursor *mc)
5695 int rc = MDB_SUCCESS;
5697 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
5700 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
5701 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
5704 *mc->mc_dbflag |= DB_DIRTY;
5709 rc = mdb_page_touch(mc);
5710 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
5711 mc->mc_top = mc->mc_snum-1;
5716 /** Do not spill pages to disk if txn is getting full, may fail instead */
5717 #define MDB_NOSPILL 0x8000
5720 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5723 enum { MDB_NO_ROOT = MDB_LAST_ERRCODE+10 }; /* internal code */
5724 MDB_env *env = mc->mc_txn->mt_env;
5725 MDB_node *leaf = NULL;
5728 MDB_val xdata, *rdata, dkey, olddata;
5730 int do_sub = 0, insert;
5731 unsigned int mcount = 0, dcount = 0, nospill;
5734 unsigned int nflags;
5737 /* Check this first so counter will always be zero on any
5740 if (flags & MDB_MULTIPLE) {
5741 dcount = data[1].mv_size;
5742 data[1].mv_size = 0;
5743 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
5744 return MDB_INCOMPATIBLE;
5747 nospill = flags & MDB_NOSPILL;
5748 flags &= ~MDB_NOSPILL;
5750 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
5751 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
5753 if (flags != MDB_CURRENT && key->mv_size-1 >= ENV_MAXKEY(env))
5754 return MDB_BAD_VALSIZE;
5756 #if SIZE_MAX > MAXDATASIZE
5757 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
5758 return MDB_BAD_VALSIZE;
5760 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
5761 return MDB_BAD_VALSIZE;
5764 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
5765 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
5769 if (flags == MDB_CURRENT) {
5770 if (!(mc->mc_flags & C_INITIALIZED))
5773 } else if (mc->mc_db->md_root == P_INVALID) {
5774 /* new database, cursor has nothing to point to */
5777 mc->mc_flags &= ~C_INITIALIZED;
5782 if (flags & MDB_APPEND) {
5784 rc = mdb_cursor_last(mc, &k2, &d2);
5786 rc = mc->mc_dbx->md_cmp(key, &k2);
5789 mc->mc_ki[mc->mc_top]++;
5791 /* new key is <= last key */
5796 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
5798 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
5799 DPRINTF(("duplicate key [%s]", DKEY(key)));
5801 return MDB_KEYEXIST;
5803 if (rc && rc != MDB_NOTFOUND)
5807 if (mc->mc_flags & C_DEL)
5808 mc->mc_flags ^= C_DEL;
5810 /* Cursor is positioned, check for room in the dirty list */
5812 if (flags & MDB_MULTIPLE) {
5814 xdata.mv_size = data->mv_size * dcount;
5818 if ((rc2 = mdb_page_spill(mc, key, rdata)))
5822 if (rc == MDB_NO_ROOT) {
5824 /* new database, write a root leaf page */
5825 DPUTS("allocating new root leaf page");
5826 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
5829 mdb_cursor_push(mc, np);
5830 mc->mc_db->md_root = np->mp_pgno;
5831 mc->mc_db->md_depth++;
5832 *mc->mc_dbflag |= DB_DIRTY;
5833 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
5835 np->mp_flags |= P_LEAF2;
5836 mc->mc_flags |= C_INITIALIZED;
5838 /* make sure all cursor pages are writable */
5839 rc2 = mdb_cursor_touch(mc);
5846 /* The key does not exist */
5847 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
5848 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
5849 LEAFSIZE(key, data) > env->me_nodemax)
5851 /* Too big for a node, insert in sub-DB */
5852 fp_flags = P_LEAF|P_DIRTY;
5854 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
5855 fp->mp_lower = fp->mp_upper = olddata.mv_size = PAGEHDRSZ;
5859 /* there's only a key anyway, so this is a no-op */
5860 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5861 unsigned int ksize = mc->mc_db->md_pad;
5862 if (key->mv_size != ksize)
5863 return MDB_BAD_VALSIZE;
5864 if (flags == MDB_CURRENT) {
5865 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
5866 memcpy(ptr, key->mv_data, ksize);
5872 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5873 olddata.mv_size = NODEDSZ(leaf);
5874 olddata.mv_data = NODEDATA(leaf);
5877 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
5878 /* Prepare (sub-)page/sub-DB to accept the new item,
5879 * if needed. fp: old sub-page or a header faking
5880 * it. mp: new (sub-)page. offset: growth in page
5881 * size. xdata: node data with new page or DB.
5883 ssize_t i, offset = 0;
5884 mp = fp = xdata.mv_data = env->me_pbuf;
5885 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
5887 /* Was a single item before, must convert now */
5888 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5889 /* Just overwrite the current item */
5890 if (flags == MDB_CURRENT)
5893 #if UINT_MAX < SIZE_MAX
5894 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
5895 #ifdef MISALIGNED_OK
5896 mc->mc_dbx->md_dcmp = mdb_cmp_long;
5898 mc->mc_dbx->md_dcmp = mdb_cmp_cint;
5901 /* if data matches, skip it */
5902 if (!mc->mc_dbx->md_dcmp(data, &olddata)) {
5903 if (flags & MDB_NODUPDATA)
5905 else if (flags & MDB_MULTIPLE)
5912 /* Back up original data item */
5913 dkey.mv_size = olddata.mv_size;
5914 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
5916 /* Make sub-page header for the dup items, with dummy body */
5917 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
5918 fp->mp_lower = PAGEHDRSZ;
5919 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
5920 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5921 fp->mp_flags |= P_LEAF2;
5922 fp->mp_pad = data->mv_size;
5923 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
5925 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
5926 (dkey.mv_size & 1) + (data->mv_size & 1);
5928 fp->mp_upper = xdata.mv_size;
5929 olddata.mv_size = fp->mp_upper; /* pretend olddata is fp */
5930 } else if (leaf->mn_flags & F_SUBDATA) {
5931 /* Data is on sub-DB, just store it */
5932 flags |= F_DUPDATA|F_SUBDATA;
5935 /* Data is on sub-page */
5936 fp = olddata.mv_data;
5939 i = -(ssize_t)SIZELEFT(fp);
5940 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5941 offset = i += (ssize_t) EVEN(
5942 sizeof(indx_t) + NODESIZE + data->mv_size);
5944 i += offset = fp->mp_pad;
5945 offset *= 4; /* space for 4 more */
5949 /* FALLTHRU: Sub-page is big enough */
5951 fp->mp_flags |= P_DIRTY;
5952 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
5953 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
5957 xdata.mv_size = olddata.mv_size + offset;
5960 fp_flags = fp->mp_flags;
5961 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
5962 /* Too big for a sub-page, convert to sub-DB */
5963 fp_flags &= ~P_SUBP;
5965 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5966 fp_flags |= P_LEAF2;
5967 dummy.md_pad = fp->mp_pad;
5968 dummy.md_flags = MDB_DUPFIXED;
5969 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
5970 dummy.md_flags |= MDB_INTEGERKEY;
5976 dummy.md_branch_pages = 0;
5977 dummy.md_leaf_pages = 1;
5978 dummy.md_overflow_pages = 0;
5979 dummy.md_entries = NUMKEYS(fp);
5980 xdata.mv_size = sizeof(MDB_db);
5981 xdata.mv_data = &dummy;
5982 if ((rc = mdb_page_alloc(mc, 1, &mp)))
5984 offset = env->me_psize - olddata.mv_size;
5985 flags |= F_DUPDATA|F_SUBDATA;
5986 dummy.md_root = mp->mp_pgno;
5989 mp->mp_flags = fp_flags | P_DIRTY;
5990 mp->mp_pad = fp->mp_pad;
5991 mp->mp_lower = fp->mp_lower;
5992 mp->mp_upper = fp->mp_upper + offset;
5993 if (fp_flags & P_LEAF2) {
5994 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
5996 memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper,
5997 olddata.mv_size - fp->mp_upper);
5998 for (i = NUMKEYS(fp); --i >= 0; )
5999 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
6007 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
6011 /* overflow page overwrites need special handling */
6012 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6015 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
6017 memcpy(&pg, olddata.mv_data, sizeof(pg));
6018 if ((rc2 = mdb_page_get(mc->mc_txn, pg, &omp, &level)) != 0)
6020 ovpages = omp->mp_pages;
6022 /* Is the ov page large enough? */
6023 if (ovpages >= dpages) {
6024 if (!(omp->mp_flags & P_DIRTY) &&
6025 (level || (env->me_flags & MDB_WRITEMAP)))
6027 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
6030 level = 0; /* dirty in this txn or clean */
6033 if (omp->mp_flags & P_DIRTY) {
6034 /* yes, overwrite it. Note in this case we don't
6035 * bother to try shrinking the page if the new data
6036 * is smaller than the overflow threshold.
6039 /* It is writable only in a parent txn */
6040 size_t sz = (size_t) env->me_psize * ovpages, off;
6041 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
6047 mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
6048 if (!(flags & MDB_RESERVE)) {
6049 /* Copy end of page, adjusting alignment so
6050 * compiler may copy words instead of bytes.
6052 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
6053 memcpy((size_t *)((char *)np + off),
6054 (size_t *)((char *)omp + off), sz - off);
6057 memcpy(np, omp, sz); /* Copy beginning of page */
6060 SETDSZ(leaf, data->mv_size);
6061 if (F_ISSET(flags, MDB_RESERVE))
6062 data->mv_data = METADATA(omp);
6064 memcpy(METADATA(omp), data->mv_data, data->mv_size);
6068 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
6070 } else if (data->mv_size == olddata.mv_size) {
6071 /* same size, just replace it. Note that we could
6072 * also reuse this node if the new data is smaller,
6073 * but instead we opt to shrink the node in that case.
6075 if (F_ISSET(flags, MDB_RESERVE))
6076 data->mv_data = olddata.mv_data;
6077 else if (data->mv_size)
6078 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
6080 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
6083 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
6084 mc->mc_db->md_entries--;
6090 nflags = flags & NODE_ADD_FLAGS;
6091 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
6092 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
6093 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
6094 nflags &= ~MDB_APPEND;
6096 nflags |= MDB_SPLIT_REPLACE;
6097 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
6099 /* There is room already in this leaf page. */
6100 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
6101 if (rc == 0 && !do_sub && insert) {
6102 /* Adjust other cursors pointing to mp */
6103 MDB_cursor *m2, *m3;
6104 MDB_dbi dbi = mc->mc_dbi;
6105 unsigned i = mc->mc_top;
6106 MDB_page *mp = mc->mc_pg[i];
6108 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6109 if (mc->mc_flags & C_SUB)
6110 m3 = &m2->mc_xcursor->mx_cursor;
6113 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
6114 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
6121 if (rc != MDB_SUCCESS)
6122 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6124 /* Now store the actual data in the child DB. Note that we're
6125 * storing the user data in the keys field, so there are strict
6126 * size limits on dupdata. The actual data fields of the child
6127 * DB are all zero size.
6134 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6135 if (flags & MDB_CURRENT) {
6136 xflags = MDB_CURRENT|MDB_NOSPILL;
6138 mdb_xcursor_init1(mc, leaf);
6139 xflags = (flags & MDB_NODUPDATA) ?
6140 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
6142 /* converted, write the original data first */
6144 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
6148 /* Adjust other cursors pointing to mp */
6150 unsigned i = mc->mc_top;
6151 MDB_page *mp = mc->mc_pg[i];
6153 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6154 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6155 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6156 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
6157 mdb_xcursor_init1(m2, leaf);
6161 /* we've done our job */
6164 if (flags & MDB_APPENDDUP)
6165 xflags |= MDB_APPEND;
6166 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
6167 if (flags & F_SUBDATA) {
6168 void *db = NODEDATA(leaf);
6169 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6172 /* sub-writes might have failed so check rc again.
6173 * Don't increment count if we just replaced an existing item.
6175 if (!rc && !(flags & MDB_CURRENT))
6176 mc->mc_db->md_entries++;
6177 if (flags & MDB_MULTIPLE) {
6181 /* let caller know how many succeeded, if any */
6182 data[1].mv_size = mcount;
6183 if (mcount < dcount) {
6184 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
6191 /* If we succeeded and the key didn't exist before, make sure
6192 * the cursor is marked valid.
6195 mc->mc_flags |= C_INITIALIZED;
6200 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
6206 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
6207 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6209 if (!(mc->mc_flags & C_INITIALIZED))
6212 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6213 return MDB_NOTFOUND;
6215 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
6218 rc = mdb_cursor_touch(mc);
6222 mp = mc->mc_pg[mc->mc_top];
6223 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6225 if (!IS_LEAF2(mp) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6226 if (!(flags & MDB_NODUPDATA)) {
6227 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
6228 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6230 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
6231 /* If sub-DB still has entries, we're done */
6232 if (mc->mc_xcursor->mx_db.md_entries) {
6233 if (leaf->mn_flags & F_SUBDATA) {
6234 /* update subDB info */
6235 void *db = NODEDATA(leaf);
6236 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6239 /* shrink fake page */
6240 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
6241 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6242 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6243 /* fix other sub-DB cursors pointed at this fake page */
6244 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6245 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6246 if (m2->mc_pg[mc->mc_top] == mp &&
6247 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
6248 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6251 mc->mc_db->md_entries--;
6252 mc->mc_flags |= C_DEL;
6255 /* otherwise fall thru and delete the sub-DB */
6258 if (leaf->mn_flags & F_SUBDATA) {
6259 /* add all the child DB's pages to the free list */
6260 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6261 if (rc == MDB_SUCCESS) {
6262 mc->mc_db->md_entries -=
6263 mc->mc_xcursor->mx_db.md_entries;
6268 return mdb_cursor_del0(mc, leaf);
6271 /** Allocate and initialize new pages for a database.
6272 * @param[in] mc a cursor on the database being added to.
6273 * @param[in] flags flags defining what type of page is being allocated.
6274 * @param[in] num the number of pages to allocate. This is usually 1,
6275 * unless allocating overflow pages for a large record.
6276 * @param[out] mp Address of a page, or NULL on failure.
6277 * @return 0 on success, non-zero on failure.
6280 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
6285 if ((rc = mdb_page_alloc(mc, num, &np)))
6287 DPRINTF(("allocated new mpage %"Z"u, page size %u",
6288 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
6289 np->mp_flags = flags | P_DIRTY;
6290 np->mp_lower = PAGEHDRSZ;
6291 np->mp_upper = mc->mc_txn->mt_env->me_psize;
6294 mc->mc_db->md_branch_pages++;
6295 else if (IS_LEAF(np))
6296 mc->mc_db->md_leaf_pages++;
6297 else if (IS_OVERFLOW(np)) {
6298 mc->mc_db->md_overflow_pages += num;
6306 /** Calculate the size of a leaf node.
6307 * The size depends on the environment's page size; if a data item
6308 * is too large it will be put onto an overflow page and the node
6309 * size will only include the key and not the data. Sizes are always
6310 * rounded up to an even number of bytes, to guarantee 2-byte alignment
6311 * of the #MDB_node headers.
6312 * @param[in] env The environment handle.
6313 * @param[in] key The key for the node.
6314 * @param[in] data The data for the node.
6315 * @return The number of bytes needed to store the node.
6318 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
6322 sz = LEAFSIZE(key, data);
6323 if (sz > env->me_nodemax) {
6324 /* put on overflow page */
6325 sz -= data->mv_size - sizeof(pgno_t);
6328 return EVEN(sz + sizeof(indx_t));
6331 /** Calculate the size of a branch node.
6332 * The size should depend on the environment's page size but since
6333 * we currently don't support spilling large keys onto overflow
6334 * pages, it's simply the size of the #MDB_node header plus the
6335 * size of the key. Sizes are always rounded up to an even number
6336 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
6337 * @param[in] env The environment handle.
6338 * @param[in] key The key for the node.
6339 * @return The number of bytes needed to store the node.
6342 mdb_branch_size(MDB_env *env, MDB_val *key)
6347 if (sz > env->me_nodemax) {
6348 /* put on overflow page */
6349 /* not implemented */
6350 /* sz -= key->size - sizeof(pgno_t); */
6353 return sz + sizeof(indx_t);
6356 /** Add a node to the page pointed to by the cursor.
6357 * @param[in] mc The cursor for this operation.
6358 * @param[in] indx The index on the page where the new node should be added.
6359 * @param[in] key The key for the new node.
6360 * @param[in] data The data for the new node, if any.
6361 * @param[in] pgno The page number, if adding a branch node.
6362 * @param[in] flags Flags for the node.
6363 * @return 0 on success, non-zero on failure. Possible errors are:
6365 * <li>ENOMEM - failed to allocate overflow pages for the node.
6366 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
6367 * should never happen since all callers already calculate the
6368 * page's free space before calling this function.
6372 mdb_node_add(MDB_cursor *mc, indx_t indx,
6373 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
6376 size_t node_size = NODESIZE;
6380 MDB_page *mp = mc->mc_pg[mc->mc_top];
6381 MDB_page *ofp = NULL; /* overflow page */
6384 assert(mp->mp_upper >= mp->mp_lower);
6386 DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
6387 IS_LEAF(mp) ? "leaf" : "branch",
6388 IS_SUBP(mp) ? "sub-" : "",
6389 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
6390 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
6393 /* Move higher keys up one slot. */
6394 int ksize = mc->mc_db->md_pad, dif;
6395 char *ptr = LEAF2KEY(mp, indx, ksize);
6396 dif = NUMKEYS(mp) - indx;
6398 memmove(ptr+ksize, ptr, dif*ksize);
6399 /* insert new key */
6400 memcpy(ptr, key->mv_data, ksize);
6402 /* Just using these for counting */
6403 mp->mp_lower += sizeof(indx_t);
6404 mp->mp_upper -= ksize - sizeof(indx_t);
6408 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
6410 node_size += key->mv_size;
6413 if (F_ISSET(flags, F_BIGDATA)) {
6414 /* Data already on overflow page. */
6415 node_size += sizeof(pgno_t);
6416 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
6417 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
6419 /* Put data on overflow page. */
6420 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
6421 data->mv_size, node_size+data->mv_size));
6422 node_size = EVEN(node_size + sizeof(pgno_t));
6423 if ((ssize_t)node_size > room)
6425 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
6427 DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
6431 node_size += data->mv_size;
6434 node_size = EVEN(node_size);
6435 if ((ssize_t)node_size > room)
6439 /* Move higher pointers up one slot. */
6440 for (i = NUMKEYS(mp); i > indx; i--)
6441 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
6443 /* Adjust free space offsets. */
6444 ofs = mp->mp_upper - node_size;
6445 assert(ofs >= mp->mp_lower + sizeof(indx_t));
6446 mp->mp_ptrs[indx] = ofs;
6448 mp->mp_lower += sizeof(indx_t);
6450 /* Write the node data. */
6451 node = NODEPTR(mp, indx);
6452 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
6453 node->mn_flags = flags;
6455 SETDSZ(node,data->mv_size);
6460 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6465 if (F_ISSET(flags, F_BIGDATA))
6466 memcpy(node->mn_data + key->mv_size, data->mv_data,
6468 else if (F_ISSET(flags, MDB_RESERVE))
6469 data->mv_data = node->mn_data + key->mv_size;
6471 memcpy(node->mn_data + key->mv_size, data->mv_data,
6474 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
6476 if (F_ISSET(flags, MDB_RESERVE))
6477 data->mv_data = METADATA(ofp);
6479 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
6486 DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
6487 mdb_dbg_pgno(mp), NUMKEYS(mp)));
6488 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
6489 DPRINTF(("node size = %"Z"u", node_size));
6490 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6491 return MDB_PAGE_FULL;
6494 /** Delete the specified node from a page.
6495 * @param[in] mp The page to operate on.
6496 * @param[in] indx The index of the node to delete.
6497 * @param[in] ksize The size of a node. Only used if the page is
6498 * part of a #MDB_DUPFIXED database.
6501 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
6504 indx_t i, j, numkeys, ptr;
6508 DPRINTF(("delete node %u on %s page %"Z"u", indx,
6509 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
6510 assert(indx < NUMKEYS(mp));
6513 int x = NUMKEYS(mp) - 1 - indx;
6514 base = LEAF2KEY(mp, indx, ksize);
6516 memmove(base, base + ksize, x * ksize);
6517 mp->mp_lower -= sizeof(indx_t);
6518 mp->mp_upper += ksize - sizeof(indx_t);
6522 node = NODEPTR(mp, indx);
6523 sz = NODESIZE + node->mn_ksize;
6525 if (F_ISSET(node->mn_flags, F_BIGDATA))
6526 sz += sizeof(pgno_t);
6528 sz += NODEDSZ(node);
6532 ptr = mp->mp_ptrs[indx];
6533 numkeys = NUMKEYS(mp);
6534 for (i = j = 0; i < numkeys; i++) {
6536 mp->mp_ptrs[j] = mp->mp_ptrs[i];
6537 if (mp->mp_ptrs[i] < ptr)
6538 mp->mp_ptrs[j] += sz;
6543 base = (char *)mp + mp->mp_upper;
6544 memmove(base + sz, base, ptr - mp->mp_upper);
6546 mp->mp_lower -= sizeof(indx_t);
6550 /** Compact the main page after deleting a node on a subpage.
6551 * @param[in] mp The main page to operate on.
6552 * @param[in] indx The index of the subpage on the main page.
6555 mdb_node_shrink(MDB_page *mp, indx_t indx)
6561 indx_t i, numkeys, ptr;
6563 node = NODEPTR(mp, indx);
6564 sp = (MDB_page *)NODEDATA(node);
6565 delta = SIZELEFT(sp);
6566 xp = (MDB_page *)((char *)sp + delta);
6568 /* shift subpage upward */
6570 nsize = NUMKEYS(sp) * sp->mp_pad;
6572 return; /* do not make the node uneven-sized */
6573 memmove(METADATA(xp), METADATA(sp), nsize);
6576 numkeys = NUMKEYS(sp);
6577 for (i=numkeys-1; i>=0; i--)
6578 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
6580 xp->mp_upper = sp->mp_lower;
6581 xp->mp_lower = sp->mp_lower;
6582 xp->mp_flags = sp->mp_flags;
6583 xp->mp_pad = sp->mp_pad;
6584 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
6586 nsize = NODEDSZ(node) - delta;
6587 SETDSZ(node, nsize);
6589 /* shift lower nodes upward */
6590 ptr = mp->mp_ptrs[indx];
6591 numkeys = NUMKEYS(mp);
6592 for (i = 0; i < numkeys; i++) {
6593 if (mp->mp_ptrs[i] <= ptr)
6594 mp->mp_ptrs[i] += delta;
6597 base = (char *)mp + mp->mp_upper;
6598 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
6599 mp->mp_upper += delta;
6602 /** Initial setup of a sorted-dups cursor.
6603 * Sorted duplicates are implemented as a sub-database for the given key.
6604 * The duplicate data items are actually keys of the sub-database.
6605 * Operations on the duplicate data items are performed using a sub-cursor
6606 * initialized when the sub-database is first accessed. This function does
6607 * the preliminary setup of the sub-cursor, filling in the fields that
6608 * depend only on the parent DB.
6609 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6612 mdb_xcursor_init0(MDB_cursor *mc)
6614 MDB_xcursor *mx = mc->mc_xcursor;
6616 mx->mx_cursor.mc_xcursor = NULL;
6617 mx->mx_cursor.mc_txn = mc->mc_txn;
6618 mx->mx_cursor.mc_db = &mx->mx_db;
6619 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
6620 mx->mx_cursor.mc_dbi = mc->mc_dbi;
6621 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
6622 mx->mx_cursor.mc_snum = 0;
6623 mx->mx_cursor.mc_top = 0;
6624 mx->mx_cursor.mc_flags = C_SUB;
6625 mx->mx_dbx.md_name.mv_size = 0;
6626 mx->mx_dbx.md_name.mv_data = NULL;
6627 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
6628 mx->mx_dbx.md_dcmp = NULL;
6629 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
6632 /** Final setup of a sorted-dups cursor.
6633 * Sets up the fields that depend on the data from the main cursor.
6634 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6635 * @param[in] node The data containing the #MDB_db record for the
6636 * sorted-dup database.
6639 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
6641 MDB_xcursor *mx = mc->mc_xcursor;
6643 if (node->mn_flags & F_SUBDATA) {
6644 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
6645 mx->mx_cursor.mc_pg[0] = 0;
6646 mx->mx_cursor.mc_snum = 0;
6647 mx->mx_cursor.mc_top = 0;
6648 mx->mx_cursor.mc_flags = C_SUB;
6650 MDB_page *fp = NODEDATA(node);
6651 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
6652 mx->mx_db.md_flags = 0;
6653 mx->mx_db.md_depth = 1;
6654 mx->mx_db.md_branch_pages = 0;
6655 mx->mx_db.md_leaf_pages = 1;
6656 mx->mx_db.md_overflow_pages = 0;
6657 mx->mx_db.md_entries = NUMKEYS(fp);
6658 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
6659 mx->mx_cursor.mc_snum = 1;
6660 mx->mx_cursor.mc_top = 0;
6661 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
6662 mx->mx_cursor.mc_pg[0] = fp;
6663 mx->mx_cursor.mc_ki[0] = 0;
6664 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6665 mx->mx_db.md_flags = MDB_DUPFIXED;
6666 mx->mx_db.md_pad = fp->mp_pad;
6667 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6668 mx->mx_db.md_flags |= MDB_INTEGERKEY;
6671 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
6672 mx->mx_db.md_root));
6673 mx->mx_dbflag = DB_VALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
6674 #if UINT_MAX < SIZE_MAX
6675 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
6676 #ifdef MISALIGNED_OK
6677 mx->mx_dbx.md_cmp = mdb_cmp_long;
6679 mx->mx_dbx.md_cmp = mdb_cmp_cint;
6684 /** Initialize a cursor for a given transaction and database. */
6686 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
6689 mc->mc_backup = NULL;
6692 mc->mc_db = &txn->mt_dbs[dbi];
6693 mc->mc_dbx = &txn->mt_dbxs[dbi];
6694 mc->mc_dbflag = &txn->mt_dbflags[dbi];
6699 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
6701 mc->mc_xcursor = mx;
6702 mdb_xcursor_init0(mc);
6704 mc->mc_xcursor = NULL;
6706 if (*mc->mc_dbflag & DB_STALE) {
6707 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
6712 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
6715 size_t size = sizeof(MDB_cursor);
6717 if (txn == NULL || ret == NULL || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
6720 if (txn->mt_flags & MDB_TXN_ERROR)
6723 /* Allow read access to the freelist */
6724 if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
6727 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
6728 size += sizeof(MDB_xcursor);
6730 if ((mc = malloc(size)) != NULL) {
6731 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
6732 if (txn->mt_cursors) {
6733 mc->mc_next = txn->mt_cursors[dbi];
6734 txn->mt_cursors[dbi] = mc;
6735 mc->mc_flags |= C_UNTRACK;
6747 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
6749 if (txn == NULL || mc == NULL || mc->mc_dbi >= txn->mt_numdbs)
6752 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
6755 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
6759 /* Return the count of duplicate data items for the current key */
6761 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
6765 if (mc == NULL || countp == NULL)
6768 if (mc->mc_xcursor == NULL)
6769 return MDB_INCOMPATIBLE;
6771 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6772 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6775 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
6778 *countp = mc->mc_xcursor->mx_db.md_entries;
6784 mdb_cursor_close(MDB_cursor *mc)
6786 if (mc && !mc->mc_backup) {
6787 /* remove from txn, if tracked */
6788 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
6789 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
6790 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
6792 *prev = mc->mc_next;
6799 mdb_cursor_txn(MDB_cursor *mc)
6801 if (!mc) return NULL;
6806 mdb_cursor_dbi(MDB_cursor *mc)
6812 /** Replace the key for a branch node with a new key.
6813 * @param[in] mc Cursor pointing to the node to operate on.
6814 * @param[in] key The new key to use.
6815 * @return 0 on success, non-zero on failure.
6818 mdb_update_key(MDB_cursor *mc, MDB_val *key)
6824 int delta, ksize, oksize;
6825 indx_t ptr, i, numkeys, indx;
6828 indx = mc->mc_ki[mc->mc_top];
6829 mp = mc->mc_pg[mc->mc_top];
6830 node = NODEPTR(mp, indx);
6831 ptr = mp->mp_ptrs[indx];
6835 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
6836 k2.mv_data = NODEKEY(node);
6837 k2.mv_size = node->mn_ksize;
6838 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
6840 mdb_dkey(&k2, kbuf2),
6846 /* Sizes must be 2-byte aligned. */
6847 ksize = EVEN(key->mv_size);
6848 oksize = EVEN(node->mn_ksize);
6849 delta = ksize - oksize;
6851 /* Shift node contents if EVEN(key length) changed. */
6853 if (delta > 0 && SIZELEFT(mp) < delta) {
6855 /* not enough space left, do a delete and split */
6856 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
6857 pgno = NODEPGNO(node);
6858 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
6859 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
6862 numkeys = NUMKEYS(mp);
6863 for (i = 0; i < numkeys; i++) {
6864 if (mp->mp_ptrs[i] <= ptr)
6865 mp->mp_ptrs[i] -= delta;
6868 base = (char *)mp + mp->mp_upper;
6869 len = ptr - mp->mp_upper + NODESIZE;
6870 memmove(base - delta, base, len);
6871 mp->mp_upper -= delta;
6873 node = NODEPTR(mp, indx);
6876 /* But even if no shift was needed, update ksize */
6877 if (node->mn_ksize != key->mv_size)
6878 node->mn_ksize = key->mv_size;
6881 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6887 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
6889 /** Move a node from csrc to cdst.
6892 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
6899 unsigned short flags;
6903 /* Mark src and dst as dirty. */
6904 if ((rc = mdb_page_touch(csrc)) ||
6905 (rc = mdb_page_touch(cdst)))
6908 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6909 key.mv_size = csrc->mc_db->md_pad;
6910 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
6912 data.mv_data = NULL;
6916 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
6917 assert(!((size_t)srcnode&1));
6918 srcpg = NODEPGNO(srcnode);
6919 flags = srcnode->mn_flags;
6920 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6921 unsigned int snum = csrc->mc_snum;
6923 /* must find the lowest key below src */
6924 mdb_page_search_lowest(csrc);
6925 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6926 key.mv_size = csrc->mc_db->md_pad;
6927 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6929 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6930 key.mv_size = NODEKSZ(s2);
6931 key.mv_data = NODEKEY(s2);
6933 csrc->mc_snum = snum--;
6934 csrc->mc_top = snum;
6936 key.mv_size = NODEKSZ(srcnode);
6937 key.mv_data = NODEKEY(srcnode);
6939 data.mv_size = NODEDSZ(srcnode);
6940 data.mv_data = NODEDATA(srcnode);
6942 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
6943 unsigned int snum = cdst->mc_snum;
6946 /* must find the lowest key below dst */
6947 mdb_page_search_lowest(cdst);
6948 if (IS_LEAF2(cdst->mc_pg[cdst->mc_top])) {
6949 bkey.mv_size = cdst->mc_db->md_pad;
6950 bkey.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, bkey.mv_size);
6952 s2 = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
6953 bkey.mv_size = NODEKSZ(s2);
6954 bkey.mv_data = NODEKEY(s2);
6956 cdst->mc_snum = snum--;
6957 cdst->mc_top = snum;
6958 mdb_cursor_copy(cdst, &mn);
6960 rc = mdb_update_key(&mn, &bkey);
6965 DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
6966 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
6967 csrc->mc_ki[csrc->mc_top],
6969 csrc->mc_pg[csrc->mc_top]->mp_pgno,
6970 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
6972 /* Add the node to the destination page.
6974 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
6975 if (rc != MDB_SUCCESS)
6978 /* Delete the node from the source page.
6980 mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
6983 /* Adjust other cursors pointing to mp */
6984 MDB_cursor *m2, *m3;
6985 MDB_dbi dbi = csrc->mc_dbi;
6986 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
6988 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6989 if (csrc->mc_flags & C_SUB)
6990 m3 = &m2->mc_xcursor->mx_cursor;
6993 if (m3 == csrc) continue;
6994 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
6995 csrc->mc_ki[csrc->mc_top]) {
6996 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
6997 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7002 /* Update the parent separators.
7004 if (csrc->mc_ki[csrc->mc_top] == 0) {
7005 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
7006 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7007 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7009 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7010 key.mv_size = NODEKSZ(srcnode);
7011 key.mv_data = NODEKEY(srcnode);
7013 DPRINTF(("update separator for source page %"Z"u to [%s]",
7014 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
7015 mdb_cursor_copy(csrc, &mn);
7018 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7021 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7023 indx_t ix = csrc->mc_ki[csrc->mc_top];
7024 nullkey.mv_size = 0;
7025 csrc->mc_ki[csrc->mc_top] = 0;
7026 rc = mdb_update_key(csrc, &nullkey);
7027 csrc->mc_ki[csrc->mc_top] = ix;
7028 assert(rc == MDB_SUCCESS);
7032 if (cdst->mc_ki[cdst->mc_top] == 0) {
7033 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
7034 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7035 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
7037 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
7038 key.mv_size = NODEKSZ(srcnode);
7039 key.mv_data = NODEKEY(srcnode);
7041 DPRINTF(("update separator for destination page %"Z"u to [%s]",
7042 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
7043 mdb_cursor_copy(cdst, &mn);
7046 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7049 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
7051 indx_t ix = cdst->mc_ki[cdst->mc_top];
7052 nullkey.mv_size = 0;
7053 cdst->mc_ki[cdst->mc_top] = 0;
7054 rc = mdb_update_key(cdst, &nullkey);
7055 cdst->mc_ki[cdst->mc_top] = ix;
7056 assert(rc == MDB_SUCCESS);
7063 /** Merge one page into another.
7064 * The nodes from the page pointed to by \b csrc will
7065 * be copied to the page pointed to by \b cdst and then
7066 * the \b csrc page will be freed.
7067 * @param[in] csrc Cursor pointing to the source page.
7068 * @param[in] cdst Cursor pointing to the destination page.
7071 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
7079 DPRINTF(("merging page %"Z"u into %"Z"u", csrc->mc_pg[csrc->mc_top]->mp_pgno,
7080 cdst->mc_pg[cdst->mc_top]->mp_pgno));
7082 assert(csrc->mc_snum > 1); /* can't merge root page */
7083 assert(cdst->mc_snum > 1);
7085 /* Mark dst as dirty. */
7086 if ((rc = mdb_page_touch(cdst)))
7089 /* Move all nodes from src to dst.
7091 j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
7092 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7093 key.mv_size = csrc->mc_db->md_pad;
7094 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
7095 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
7096 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
7097 if (rc != MDB_SUCCESS)
7099 key.mv_data = (char *)key.mv_data + key.mv_size;
7102 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
7103 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
7104 if (i == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7105 unsigned int snum = csrc->mc_snum;
7107 /* must find the lowest key below src */
7108 mdb_page_search_lowest(csrc);
7109 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7110 key.mv_size = csrc->mc_db->md_pad;
7111 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7113 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7114 key.mv_size = NODEKSZ(s2);
7115 key.mv_data = NODEKEY(s2);
7117 csrc->mc_snum = snum--;
7118 csrc->mc_top = snum;
7120 key.mv_size = srcnode->mn_ksize;
7121 key.mv_data = NODEKEY(srcnode);
7124 data.mv_size = NODEDSZ(srcnode);
7125 data.mv_data = NODEDATA(srcnode);
7126 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
7127 if (rc != MDB_SUCCESS)
7132 DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
7133 cdst->mc_pg[cdst->mc_top]->mp_pgno, NUMKEYS(cdst->mc_pg[cdst->mc_top]),
7134 (float)PAGEFILL(cdst->mc_txn->mt_env, cdst->mc_pg[cdst->mc_top]) / 10));
7136 /* Unlink the src page from parent and add to free list.
7138 mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
7139 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
7142 rc = mdb_update_key(csrc, &key);
7148 rc = mdb_midl_append(&csrc->mc_txn->mt_free_pgs,
7149 csrc->mc_pg[csrc->mc_top]->mp_pgno);
7152 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
7153 csrc->mc_db->md_leaf_pages--;
7155 csrc->mc_db->md_branch_pages--;
7157 /* Adjust other cursors pointing to mp */
7158 MDB_cursor *m2, *m3;
7159 MDB_dbi dbi = csrc->mc_dbi;
7160 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
7162 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7163 if (csrc->mc_flags & C_SUB)
7164 m3 = &m2->mc_xcursor->mx_cursor;
7167 if (m3 == csrc) continue;
7168 if (m3->mc_snum < csrc->mc_snum) continue;
7169 if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
7170 m3->mc_pg[csrc->mc_top] = mp;
7171 m3->mc_ki[csrc->mc_top] += nkeys;
7175 mdb_cursor_pop(csrc);
7177 return mdb_rebalance(csrc);
7180 /** Copy the contents of a cursor.
7181 * @param[in] csrc The cursor to copy from.
7182 * @param[out] cdst The cursor to copy to.
7185 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
7189 cdst->mc_txn = csrc->mc_txn;
7190 cdst->mc_dbi = csrc->mc_dbi;
7191 cdst->mc_db = csrc->mc_db;
7192 cdst->mc_dbx = csrc->mc_dbx;
7193 cdst->mc_snum = csrc->mc_snum;
7194 cdst->mc_top = csrc->mc_top;
7195 cdst->mc_flags = csrc->mc_flags;
7197 for (i=0; i<csrc->mc_snum; i++) {
7198 cdst->mc_pg[i] = csrc->mc_pg[i];
7199 cdst->mc_ki[i] = csrc->mc_ki[i];
7203 /** Rebalance the tree after a delete operation.
7204 * @param[in] mc Cursor pointing to the page where rebalancing
7206 * @return 0 on success, non-zero on failure.
7209 mdb_rebalance(MDB_cursor *mc)
7213 unsigned int ptop, minkeys;
7216 minkeys = 1 + (IS_BRANCH(mc->mc_pg[mc->mc_top]));
7217 DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
7218 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
7219 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
7220 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
7222 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD &&
7223 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
7224 DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
7225 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
7229 if (mc->mc_snum < 2) {
7230 MDB_page *mp = mc->mc_pg[0];
7232 DPUTS("Can't rebalance a subpage, ignoring");
7235 if (NUMKEYS(mp) == 0) {
7236 DPUTS("tree is completely empty");
7237 mc->mc_db->md_root = P_INVALID;
7238 mc->mc_db->md_depth = 0;
7239 mc->mc_db->md_leaf_pages = 0;
7240 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7243 /* Adjust cursors pointing to mp */
7246 mc->mc_flags &= ~C_INITIALIZED;
7248 MDB_cursor *m2, *m3;
7249 MDB_dbi dbi = mc->mc_dbi;
7251 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7252 if (mc->mc_flags & C_SUB)
7253 m3 = &m2->mc_xcursor->mx_cursor;
7256 if (m3->mc_snum < mc->mc_snum) continue;
7257 if (m3->mc_pg[0] == mp) {
7260 m3->mc_flags &= ~C_INITIALIZED;
7264 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
7265 DPUTS("collapsing root page!");
7266 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7269 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
7270 rc = mdb_page_get(mc->mc_txn,mc->mc_db->md_root,&mc->mc_pg[0],NULL);
7273 mc->mc_db->md_depth--;
7274 mc->mc_db->md_branch_pages--;
7275 mc->mc_ki[0] = mc->mc_ki[1];
7277 /* Adjust other cursors pointing to mp */
7278 MDB_cursor *m2, *m3;
7279 MDB_dbi dbi = mc->mc_dbi;
7281 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7282 if (mc->mc_flags & C_SUB)
7283 m3 = &m2->mc_xcursor->mx_cursor;
7286 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
7287 if (m3->mc_pg[0] == mp) {
7291 for (i=0; i<m3->mc_snum; i++) {
7292 m3->mc_pg[i] = m3->mc_pg[i+1];
7293 m3->mc_ki[i] = m3->mc_ki[i+1];
7299 DPUTS("root page doesn't need rebalancing");
7303 /* The parent (branch page) must have at least 2 pointers,
7304 * otherwise the tree is invalid.
7306 ptop = mc->mc_top-1;
7307 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
7309 /* Leaf page fill factor is below the threshold.
7310 * Try to move keys from left or right neighbor, or
7311 * merge with a neighbor page.
7316 mdb_cursor_copy(mc, &mn);
7317 mn.mc_xcursor = NULL;
7319 if (mc->mc_ki[ptop] == 0) {
7320 /* We're the leftmost leaf in our parent.
7322 DPUTS("reading right neighbor");
7324 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7325 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7328 mn.mc_ki[mn.mc_top] = 0;
7329 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
7331 /* There is at least one neighbor to the left.
7333 DPUTS("reading left neighbor");
7335 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7336 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7339 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
7340 mc->mc_ki[mc->mc_top] = 0;
7343 DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
7344 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
7345 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
7347 /* If the neighbor page is above threshold and has enough keys,
7348 * move one key from it. Otherwise we should try to merge them.
7349 * (A branch page must never have less than 2 keys.)
7351 minkeys = 1 + (IS_BRANCH(mn.mc_pg[mn.mc_top]));
7352 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys)
7353 return mdb_node_move(&mn, mc);
7355 if (mc->mc_ki[ptop] == 0)
7356 rc = mdb_page_merge(&mn, mc);
7358 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
7359 rc = mdb_page_merge(mc, &mn);
7360 mdb_cursor_copy(&mn, mc);
7362 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
7367 /** Complete a delete operation started by #mdb_cursor_del(). */
7369 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
7376 mp = mc->mc_pg[mc->mc_top];
7377 ki = mc->mc_ki[mc->mc_top];
7379 /* add overflow pages to free list */
7380 if (!IS_LEAF2(mp) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7384 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
7385 if ((rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL)) ||
7386 (rc = mdb_ovpage_free(mc, omp)))
7389 mdb_node_del(mp, ki, mc->mc_db->md_pad);
7390 mc->mc_db->md_entries--;
7391 rc = mdb_rebalance(mc);
7392 if (rc != MDB_SUCCESS)
7393 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7395 MDB_cursor *m2, *m3;
7396 MDB_dbi dbi = mc->mc_dbi;
7398 mp = mc->mc_pg[mc->mc_top];
7399 nkeys = NUMKEYS(mp);
7401 /* if mc points past last node in page, find next sibling */
7402 if (mc->mc_ki[mc->mc_top] >= nkeys)
7403 mdb_cursor_sibling(mc, 1);
7405 /* Adjust other cursors pointing to mp */
7406 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7407 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
7408 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
7410 if (m3 == mc || m3->mc_snum < mc->mc_snum)
7412 if (m3->mc_pg[mc->mc_top] == mp) {
7413 if (m3->mc_ki[mc->mc_top] >= ki) {
7414 m3->mc_flags |= C_DEL;
7415 if (m3->mc_ki[mc->mc_top] > ki)
7416 m3->mc_ki[mc->mc_top]--;
7418 if (m3->mc_ki[mc->mc_top] >= nkeys)
7419 mdb_cursor_sibling(m3, 1);
7422 mc->mc_flags |= C_DEL;
7429 mdb_del(MDB_txn *txn, MDB_dbi dbi,
7430 MDB_val *key, MDB_val *data)
7435 MDB_val rdata, *xdata;
7442 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
7444 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7447 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
7448 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7450 mdb_cursor_init(&mc, txn, dbi, &mx);
7453 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
7454 /* must ignore any data */
7465 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
7467 /* let mdb_page_split know about this cursor if needed:
7468 * delete will trigger a rebalance; if it needs to move
7469 * a node from one page to another, it will have to
7470 * update the parent's separator key(s). If the new sepkey
7471 * is larger than the current one, the parent page may
7472 * run out of space, triggering a split. We need this
7473 * cursor to be consistent until the end of the rebalance.
7475 mc.mc_flags |= C_UNTRACK;
7476 mc.mc_next = txn->mt_cursors[dbi];
7477 txn->mt_cursors[dbi] = &mc;
7478 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
7479 txn->mt_cursors[dbi] = mc.mc_next;
7484 /** Split a page and insert a new node.
7485 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
7486 * The cursor will be updated to point to the actual page and index where
7487 * the node got inserted after the split.
7488 * @param[in] newkey The key for the newly inserted node.
7489 * @param[in] newdata The data for the newly inserted node.
7490 * @param[in] newpgno The page number, if the new node is a branch node.
7491 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
7492 * @return 0 on success, non-zero on failure.
7495 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
7496 unsigned int nflags)
7499 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
7502 int i, j, split_indx, nkeys, pmax;
7503 MDB_env *env = mc->mc_txn->mt_env;
7505 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
7506 MDB_page *copy = NULL;
7507 MDB_page *mp, *rp, *pp;
7512 mp = mc->mc_pg[mc->mc_top];
7513 newindx = mc->mc_ki[mc->mc_top];
7514 nkeys = NUMKEYS(mp);
7516 DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i/%i",
7517 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
7518 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
7520 /* Create a right sibling. */
7521 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
7523 DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
7525 if (mc->mc_snum < 2) {
7526 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
7528 /* shift current top to make room for new parent */
7529 mc->mc_pg[1] = mc->mc_pg[0];
7530 mc->mc_ki[1] = mc->mc_ki[0];
7533 mc->mc_db->md_root = pp->mp_pgno;
7534 DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
7535 mc->mc_db->md_depth++;
7538 /* Add left (implicit) pointer. */
7539 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
7540 /* undo the pre-push */
7541 mc->mc_pg[0] = mc->mc_pg[1];
7542 mc->mc_ki[0] = mc->mc_ki[1];
7543 mc->mc_db->md_root = mp->mp_pgno;
7544 mc->mc_db->md_depth--;
7551 ptop = mc->mc_top-1;
7552 DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
7555 mc->mc_flags |= C_SPLITTING;
7556 mdb_cursor_copy(mc, &mn);
7557 mn.mc_pg[mn.mc_top] = rp;
7558 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
7560 if (nflags & MDB_APPEND) {
7561 mn.mc_ki[mn.mc_top] = 0;
7563 split_indx = newindx;
7567 split_indx = (nkeys+1) / 2;
7572 unsigned int lsize, rsize, ksize;
7573 /* Move half of the keys to the right sibling */
7575 x = mc->mc_ki[mc->mc_top] - split_indx;
7576 ksize = mc->mc_db->md_pad;
7577 split = LEAF2KEY(mp, split_indx, ksize);
7578 rsize = (nkeys - split_indx) * ksize;
7579 lsize = (nkeys - split_indx) * sizeof(indx_t);
7580 mp->mp_lower -= lsize;
7581 rp->mp_lower += lsize;
7582 mp->mp_upper += rsize - lsize;
7583 rp->mp_upper -= rsize - lsize;
7584 sepkey.mv_size = ksize;
7585 if (newindx == split_indx) {
7586 sepkey.mv_data = newkey->mv_data;
7588 sepkey.mv_data = split;
7591 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
7592 memcpy(rp->mp_ptrs, split, rsize);
7593 sepkey.mv_data = rp->mp_ptrs;
7594 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
7595 memcpy(ins, newkey->mv_data, ksize);
7596 mp->mp_lower += sizeof(indx_t);
7597 mp->mp_upper -= ksize - sizeof(indx_t);
7600 memcpy(rp->mp_ptrs, split, x * ksize);
7601 ins = LEAF2KEY(rp, x, ksize);
7602 memcpy(ins, newkey->mv_data, ksize);
7603 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
7604 rp->mp_lower += sizeof(indx_t);
7605 rp->mp_upper -= ksize - sizeof(indx_t);
7606 mc->mc_ki[mc->mc_top] = x;
7607 mc->mc_pg[mc->mc_top] = rp;
7610 int psize, nsize, k;
7611 /* Maximum free space in an empty page */
7612 pmax = env->me_psize - PAGEHDRSZ;
7614 nsize = mdb_leaf_size(env, newkey, newdata);
7616 nsize = mdb_branch_size(env, newkey);
7617 nsize = EVEN(nsize);
7619 /* grab a page to hold a temporary copy */
7620 copy = mdb_page_malloc(mc->mc_txn, 1);
7623 copy->mp_pgno = mp->mp_pgno;
7624 copy->mp_flags = mp->mp_flags;
7625 copy->mp_lower = PAGEHDRSZ;
7626 copy->mp_upper = env->me_psize;
7628 /* prepare to insert */
7629 for (i=0, j=0; i<nkeys; i++) {
7631 copy->mp_ptrs[j++] = 0;
7633 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
7636 /* When items are relatively large the split point needs
7637 * to be checked, because being off-by-one will make the
7638 * difference between success or failure in mdb_node_add.
7640 * It's also relevant if a page happens to be laid out
7641 * such that one half of its nodes are all "small" and
7642 * the other half of its nodes are "large." If the new
7643 * item is also "large" and falls on the half with
7644 * "large" nodes, it also may not fit.
7646 * As a final tweak, if the new item goes on the last
7647 * spot on the page (and thus, onto the new page), bias
7648 * the split so the new page is emptier than the old page.
7649 * This yields better packing during sequential inserts.
7651 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
7652 /* Find split point */
7654 if (newindx <= split_indx || newindx >= nkeys) {
7656 k = newindx >= nkeys ? nkeys : split_indx+2;
7661 for (; i!=k; i+=j) {
7666 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i]);
7667 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
7669 if (F_ISSET(node->mn_flags, F_BIGDATA))
7670 psize += sizeof(pgno_t);
7672 psize += NODEDSZ(node);
7674 psize = EVEN(psize);
7676 if (psize > pmax || i == k-j) {
7677 split_indx = i + (j<0);
7682 if (split_indx == newindx) {
7683 sepkey.mv_size = newkey->mv_size;
7684 sepkey.mv_data = newkey->mv_data;
7686 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx]);
7687 sepkey.mv_size = node->mn_ksize;
7688 sepkey.mv_data = NODEKEY(node);
7693 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
7695 /* Copy separator key to the parent.
7697 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
7701 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
7704 if (mn.mc_snum == mc->mc_snum) {
7705 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
7706 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
7707 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
7708 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
7713 /* Right page might now have changed parent.
7714 * Check if left page also changed parent.
7716 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7717 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7718 for (i=0; i<ptop; i++) {
7719 mc->mc_pg[i] = mn.mc_pg[i];
7720 mc->mc_ki[i] = mn.mc_ki[i];
7722 mc->mc_pg[ptop] = mn.mc_pg[ptop];
7723 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
7727 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
7730 mc->mc_flags ^= C_SPLITTING;
7731 if (rc != MDB_SUCCESS) {
7734 if (nflags & MDB_APPEND) {
7735 mc->mc_pg[mc->mc_top] = rp;
7736 mc->mc_ki[mc->mc_top] = 0;
7737 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
7740 for (i=0; i<mc->mc_top; i++)
7741 mc->mc_ki[i] = mn.mc_ki[i];
7742 } else if (!IS_LEAF2(mp)) {
7744 mc->mc_pg[mc->mc_top] = rp;
7749 rkey.mv_data = newkey->mv_data;
7750 rkey.mv_size = newkey->mv_size;
7756 /* Update index for the new key. */
7757 mc->mc_ki[mc->mc_top] = j;
7759 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i]);
7760 rkey.mv_data = NODEKEY(node);
7761 rkey.mv_size = node->mn_ksize;
7763 xdata.mv_data = NODEDATA(node);
7764 xdata.mv_size = NODEDSZ(node);
7767 pgno = NODEPGNO(node);
7768 flags = node->mn_flags;
7771 if (!IS_LEAF(mp) && j == 0) {
7772 /* First branch index doesn't need key data. */
7776 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
7778 /* return tmp page to freelist */
7779 mdb_page_free(env, copy);
7785 mc->mc_pg[mc->mc_top] = copy;
7790 } while (i != split_indx);
7792 nkeys = NUMKEYS(copy);
7793 for (i=0; i<nkeys; i++)
7794 mp->mp_ptrs[i] = copy->mp_ptrs[i];
7795 mp->mp_lower = copy->mp_lower;
7796 mp->mp_upper = copy->mp_upper;
7797 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
7798 env->me_psize - copy->mp_upper);
7800 /* reset back to original page */
7801 if (newindx < split_indx) {
7802 mc->mc_pg[mc->mc_top] = mp;
7803 if (nflags & MDB_RESERVE) {
7804 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7805 if (!(node->mn_flags & F_BIGDATA))
7806 newdata->mv_data = NODEDATA(node);
7809 mc->mc_pg[mc->mc_top] = rp;
7811 /* Make sure mc_ki is still valid.
7813 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7814 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7815 for (i=0; i<ptop; i++) {
7816 mc->mc_pg[i] = mn.mc_pg[i];
7817 mc->mc_ki[i] = mn.mc_ki[i];
7819 mc->mc_pg[ptop] = mn.mc_pg[ptop];
7820 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
7823 /* return tmp page to freelist */
7824 mdb_page_free(env, copy);
7828 /* Adjust other cursors pointing to mp */
7829 MDB_cursor *m2, *m3;
7830 MDB_dbi dbi = mc->mc_dbi;
7831 int fixup = NUMKEYS(mp);
7833 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7834 if (mc->mc_flags & C_SUB)
7835 m3 = &m2->mc_xcursor->mx_cursor;
7840 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
7842 if (m3->mc_flags & C_SPLITTING)
7847 for (k=m3->mc_top; k>=0; k--) {
7848 m3->mc_ki[k+1] = m3->mc_ki[k];
7849 m3->mc_pg[k+1] = m3->mc_pg[k];
7851 if (m3->mc_ki[0] >= split_indx) {
7856 m3->mc_pg[0] = mc->mc_pg[0];
7860 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
7861 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
7862 m3->mc_ki[mc->mc_top]++;
7863 if (m3->mc_ki[mc->mc_top] >= fixup) {
7864 m3->mc_pg[mc->mc_top] = rp;
7865 m3->mc_ki[mc->mc_top] -= fixup;
7866 m3->mc_ki[ptop] = mn.mc_ki[ptop];
7868 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
7869 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
7874 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
7879 mdb_put(MDB_txn *txn, MDB_dbi dbi,
7880 MDB_val *key, MDB_val *data, unsigned int flags)
7885 if (key == NULL || data == NULL)
7888 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7891 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP)) != flags)
7894 mdb_cursor_init(&mc, txn, dbi, &mx);
7895 return mdb_cursor_put(&mc, key, data, flags);
7899 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
7901 if ((flag & CHANGEABLE) != flag)
7904 env->me_flags |= flag;
7906 env->me_flags &= ~flag;
7911 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
7916 *arg = env->me_flags;
7921 mdb_env_set_userctx(MDB_env *env, void *ctx)
7925 env->me_userctx = ctx;
7930 mdb_env_get_userctx(MDB_env *env)
7932 return env ? env->me_userctx : NULL;
7936 mdb_env_get_path(MDB_env *env, const char **arg)
7941 *arg = env->me_path;
7946 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
7955 /** Common code for #mdb_stat() and #mdb_env_stat().
7956 * @param[in] env the environment to operate in.
7957 * @param[in] db the #MDB_db record containing the stats to return.
7958 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
7959 * @return 0, this function always succeeds.
7962 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
7964 arg->ms_psize = env->me_psize;
7965 arg->ms_depth = db->md_depth;
7966 arg->ms_branch_pages = db->md_branch_pages;
7967 arg->ms_leaf_pages = db->md_leaf_pages;
7968 arg->ms_overflow_pages = db->md_overflow_pages;
7969 arg->ms_entries = db->md_entries;
7974 mdb_env_stat(MDB_env *env, MDB_stat *arg)
7978 if (env == NULL || arg == NULL)
7981 toggle = mdb_env_pick_meta(env);
7983 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
7987 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
7991 if (env == NULL || arg == NULL)
7994 toggle = mdb_env_pick_meta(env);
7995 arg->me_mapaddr = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : 0;
7996 arg->me_mapsize = env->me_mapsize;
7997 arg->me_maxreaders = env->me_maxreaders;
7999 /* me_numreaders may be zero if this process never used any readers. Use
8000 * the shared numreader count if it exists.
8002 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : env->me_numreaders;
8004 arg->me_last_pgno = env->me_metas[toggle]->mm_last_pg;
8005 arg->me_last_txnid = env->me_metas[toggle]->mm_txnid;
8009 /** Set the default comparison functions for a database.
8010 * Called immediately after a database is opened to set the defaults.
8011 * The user can then override them with #mdb_set_compare() or
8012 * #mdb_set_dupsort().
8013 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
8014 * @param[in] dbi A database handle returned by #mdb_dbi_open()
8017 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
8019 uint16_t f = txn->mt_dbs[dbi].md_flags;
8021 txn->mt_dbxs[dbi].md_cmp =
8022 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
8023 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
8025 txn->mt_dbxs[dbi].md_dcmp =
8026 !(f & MDB_DUPSORT) ? 0 :
8027 ((f & MDB_INTEGERDUP)
8028 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
8029 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
8032 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
8037 int rc, dbflag, exact;
8038 unsigned int unused = 0;
8041 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
8042 mdb_default_cmp(txn, FREE_DBI);
8045 if ((flags & VALID_FLAGS) != flags)
8047 if (txn->mt_flags & MDB_TXN_ERROR)
8053 if (flags & PERSISTENT_FLAGS) {
8054 uint16_t f2 = flags & PERSISTENT_FLAGS;
8055 /* make sure flag changes get committed */
8056 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
8057 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
8058 txn->mt_flags |= MDB_TXN_DIRTY;
8061 mdb_default_cmp(txn, MAIN_DBI);
8065 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
8066 mdb_default_cmp(txn, MAIN_DBI);
8069 /* Is the DB already open? */
8071 for (i=2; i<txn->mt_numdbs; i++) {
8072 if (!txn->mt_dbxs[i].md_name.mv_size) {
8073 /* Remember this free slot */
8074 if (!unused) unused = i;
8077 if (len == txn->mt_dbxs[i].md_name.mv_size &&
8078 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
8084 /* If no free slot and max hit, fail */
8085 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
8086 return MDB_DBS_FULL;
8088 /* Cannot mix named databases with some mainDB flags */
8089 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
8090 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
8092 /* Find the DB info */
8093 dbflag = DB_NEW|DB_VALID;
8096 key.mv_data = (void *)name;
8097 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
8098 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
8099 if (rc == MDB_SUCCESS) {
8100 /* make sure this is actually a DB */
8101 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
8102 if (!(node->mn_flags & F_SUBDATA))
8103 return MDB_INCOMPATIBLE;
8104 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
8105 /* Create if requested */
8107 data.mv_size = sizeof(MDB_db);
8108 data.mv_data = &dummy;
8109 memset(&dummy, 0, sizeof(dummy));
8110 dummy.md_root = P_INVALID;
8111 dummy.md_flags = flags & PERSISTENT_FLAGS;
8112 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
8116 /* OK, got info, add to table */
8117 if (rc == MDB_SUCCESS) {
8118 unsigned int slot = unused ? unused : txn->mt_numdbs;
8119 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
8120 txn->mt_dbxs[slot].md_name.mv_size = len;
8121 txn->mt_dbxs[slot].md_rel = NULL;
8122 txn->mt_dbflags[slot] = dbflag;
8123 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
8125 mdb_default_cmp(txn, slot);
8134 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
8136 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
8139 if (txn->mt_dbflags[dbi] & DB_STALE) {
8142 /* Stale, must read the DB's root. cursor_init does it for us. */
8143 mdb_cursor_init(&mc, txn, dbi, &mx);
8145 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
8148 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
8151 if (dbi <= MAIN_DBI || dbi >= env->me_maxdbs)
8153 ptr = env->me_dbxs[dbi].md_name.mv_data;
8154 env->me_dbxs[dbi].md_name.mv_data = NULL;
8155 env->me_dbxs[dbi].md_name.mv_size = 0;
8156 env->me_dbflags[dbi] = 0;
8160 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
8162 /* We could return the flags for the FREE_DBI too but what's the point? */
8163 if (txn == NULL || dbi < MAIN_DBI || dbi >= txn->mt_numdbs)
8165 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
8169 /** Add all the DB's pages to the free list.
8170 * @param[in] mc Cursor on the DB to free.
8171 * @param[in] subs non-Zero to check for sub-DBs in this DB.
8172 * @return 0 on success, non-zero on failure.
8175 mdb_drop0(MDB_cursor *mc, int subs)
8179 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
8180 if (rc == MDB_SUCCESS) {
8181 MDB_txn *txn = mc->mc_txn;
8186 /* LEAF2 pages have no nodes, cannot have sub-DBs */
8187 if (IS_LEAF2(mc->mc_pg[mc->mc_top]))
8190 mdb_cursor_copy(mc, &mx);
8191 while (mc->mc_snum > 0) {
8192 MDB_page *mp = mc->mc_pg[mc->mc_top];
8193 unsigned n = NUMKEYS(mp);
8195 for (i=0; i<n; i++) {
8196 ni = NODEPTR(mp, i);
8197 if (ni->mn_flags & F_BIGDATA) {
8200 memcpy(&pg, NODEDATA(ni), sizeof(pg));
8201 rc = mdb_page_get(txn, pg, &omp, NULL);
8204 assert(IS_OVERFLOW(omp));
8205 rc = mdb_midl_append_range(&txn->mt_free_pgs,
8209 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
8210 mdb_xcursor_init1(mc, ni);
8211 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
8217 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
8219 for (i=0; i<n; i++) {
8221 ni = NODEPTR(mp, i);
8224 mdb_midl_xappend(txn->mt_free_pgs, pg);
8229 mc->mc_ki[mc->mc_top] = i;
8230 rc = mdb_cursor_sibling(mc, 1);
8232 /* no more siblings, go back to beginning
8233 * of previous level.
8237 for (i=1; i<mc->mc_snum; i++) {
8239 mc->mc_pg[i] = mx.mc_pg[i];
8244 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
8245 } else if (rc == MDB_NOTFOUND) {
8251 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
8253 MDB_cursor *mc, *m2;
8256 if (!txn || !dbi || dbi >= txn->mt_numdbs || (unsigned)del > 1 || !(txn->mt_dbflags[dbi] & DB_VALID))
8259 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
8262 rc = mdb_cursor_open(txn, dbi, &mc);
8266 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
8267 /* Invalidate the dropped DB's cursors */
8268 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
8269 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
8273 /* Can't delete the main DB */
8274 if (del && dbi > MAIN_DBI) {
8275 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
8277 txn->mt_dbflags[dbi] = DB_STALE;
8278 mdb_dbi_close(txn->mt_env, dbi);
8281 /* reset the DB record, mark it dirty */
8282 txn->mt_dbflags[dbi] |= DB_DIRTY;
8283 txn->mt_dbs[dbi].md_depth = 0;
8284 txn->mt_dbs[dbi].md_branch_pages = 0;
8285 txn->mt_dbs[dbi].md_leaf_pages = 0;
8286 txn->mt_dbs[dbi].md_overflow_pages = 0;
8287 txn->mt_dbs[dbi].md_entries = 0;
8288 txn->mt_dbs[dbi].md_root = P_INVALID;
8290 txn->mt_flags |= MDB_TXN_DIRTY;
8293 mdb_cursor_close(mc);
8297 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
8299 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8302 txn->mt_dbxs[dbi].md_cmp = cmp;
8306 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
8308 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8311 txn->mt_dbxs[dbi].md_dcmp = cmp;
8315 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
8317 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8320 txn->mt_dbxs[dbi].md_rel = rel;
8324 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
8326 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8329 txn->mt_dbxs[dbi].md_relctx = ctx;
8333 int mdb_env_get_maxkeysize(MDB_env *env)
8335 return ENV_MAXKEY(env);
8338 int mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
8340 unsigned int i, rdrs;
8343 int rc = 0, first = 1;
8347 if (!env->me_txns) {
8348 return func("(no reader locks)\n", ctx);
8350 rdrs = env->me_txns->mti_numreaders;
8351 mr = env->me_txns->mti_readers;
8352 for (i=0; i<rdrs; i++) {
8354 txnid_t txnid = mr[i].mr_txnid;
8355 sprintf(buf, txnid == (txnid_t)-1 ?
8356 "%10d %"Z"x -\n" : "%10d %"Z"x %"Z"u\n",
8357 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
8360 rc = func(" pid thread txnid\n", ctx);
8364 rc = func(buf, ctx);
8370 rc = func("(no active readers)\n", ctx);
8375 /** Insert pid into list if not already present.
8376 * return -1 if already present.
8378 static int mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
8380 /* binary search of pid in list */
8382 unsigned cursor = 1;
8384 unsigned n = ids[0];
8387 unsigned pivot = n >> 1;
8388 cursor = base + pivot + 1;
8389 val = pid - ids[cursor];
8394 } else if ( val > 0 ) {
8399 /* found, so it's a duplicate */
8408 for (n = ids[0]; n > cursor; n--)
8414 int mdb_reader_check(MDB_env *env, int *dead)
8416 unsigned int i, j, rdrs;
8418 MDB_PID_T *pids, pid;
8427 rdrs = env->me_txns->mti_numreaders;
8428 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
8432 mr = env->me_txns->mti_readers;
8433 for (i=0; i<rdrs; i++) {
8434 if (mr[i].mr_pid && mr[i].mr_pid != env->me_pid) {
8436 if (mdb_pid_insert(pids, pid) == 0) {
8437 if (!mdb_reader_pid(env, Pidcheck, pid)) {
8439 /* Recheck, a new process may have reused pid */
8440 if (!mdb_reader_pid(env, Pidcheck, pid)) {
8441 for (j=i; j<rdrs; j++)
8442 if (mr[j].mr_pid == pid) {
8443 DPRINTF(("clear stale reader pid %u txn %"Z"d",
8444 (unsigned) pid, mr[j].mr_txnid));
8449 UNLOCK_MUTEX_R(env);