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 */
1085 /** Nested transaction */
1086 typedef struct MDB_ntxn {
1087 MDB_txn mnt_txn; /**< the transaction */
1088 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1091 /** max number of pages to commit in one writev() call */
1092 #define MDB_COMMIT_PAGES 64
1093 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1094 #undef MDB_COMMIT_PAGES
1095 #define MDB_COMMIT_PAGES IOV_MAX
1098 /* max bytes to write in one call */
1099 #define MAX_WRITE (0x80000000U >> (sizeof(ssize_t) == 4))
1101 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1102 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1103 static int mdb_page_touch(MDB_cursor *mc);
1105 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp, int *lvl);
1106 static int mdb_page_search_root(MDB_cursor *mc,
1107 MDB_val *key, int modify);
1108 #define MDB_PS_MODIFY 1
1109 #define MDB_PS_ROOTONLY 2
1110 #define MDB_PS_FIRST 4
1111 #define MDB_PS_LAST 8
1112 static int mdb_page_search(MDB_cursor *mc,
1113 MDB_val *key, int flags);
1114 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1116 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1117 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1118 pgno_t newpgno, unsigned int nflags);
1120 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1121 static int mdb_env_pick_meta(const MDB_env *env);
1122 static int mdb_env_write_meta(MDB_txn *txn);
1123 #if !(defined(_WIN32) || defined(MDB_USE_POSIX_SEM)) /* Drop unused excl arg */
1124 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1126 static void mdb_env_close0(MDB_env *env, int excl);
1128 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1129 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1130 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1131 static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
1132 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1133 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
1134 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1135 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1136 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1138 static int mdb_rebalance(MDB_cursor *mc);
1139 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1141 static void mdb_cursor_pop(MDB_cursor *mc);
1142 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1144 static int mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
1145 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1146 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1147 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1148 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1150 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1151 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1153 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1154 static void mdb_xcursor_init0(MDB_cursor *mc);
1155 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1157 static int mdb_drop0(MDB_cursor *mc, int subs);
1158 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1161 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1165 static SECURITY_DESCRIPTOR mdb_null_sd;
1166 static SECURITY_ATTRIBUTES mdb_all_sa;
1167 static int mdb_sec_inited;
1170 /** Return the library version info. */
1172 mdb_version(int *major, int *minor, int *patch)
1174 if (major) *major = MDB_VERSION_MAJOR;
1175 if (minor) *minor = MDB_VERSION_MINOR;
1176 if (patch) *patch = MDB_VERSION_PATCH;
1177 return MDB_VERSION_STRING;
1180 /** Table of descriptions for MDB @ref errors */
1181 static char *const mdb_errstr[] = {
1182 "MDB_KEYEXIST: Key/data pair already exists",
1183 "MDB_NOTFOUND: No matching key/data pair found",
1184 "MDB_PAGE_NOTFOUND: Requested page not found",
1185 "MDB_CORRUPTED: Located page was wrong type",
1186 "MDB_PANIC: Update of meta page failed",
1187 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1188 "MDB_INVALID: File is not an MDB file",
1189 "MDB_MAP_FULL: Environment mapsize limit reached",
1190 "MDB_DBS_FULL: Environment maxdbs limit reached",
1191 "MDB_READERS_FULL: Environment maxreaders limit reached",
1192 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1193 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1194 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1195 "MDB_PAGE_FULL: Internal error - page has no more space",
1196 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1197 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1198 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1199 "MDB_BAD_TXN: Transaction cannot recover - it must be aborted",
1200 "MDB_BAD_VALSIZE: Too big key/data, key is empty, or wrong DUPFIXED size",
1204 mdb_strerror(int err)
1208 return ("Successful return: 0");
1210 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1211 i = err - MDB_KEYEXIST;
1212 return mdb_errstr[i];
1215 return strerror(err);
1219 /** Return the page number of \b mp which may be sub-page, for debug output */
1221 mdb_dbg_pgno(MDB_page *mp)
1224 COPY_PGNO(ret, mp->mp_pgno);
1228 /** Display a key in hexadecimal and return the address of the result.
1229 * @param[in] key the key to display
1230 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1231 * @return The key in hexadecimal form.
1234 mdb_dkey(MDB_val *key, char *buf)
1237 unsigned char *c = key->mv_data;
1243 if (key->mv_size > DKBUF_MAXKEYSIZE)
1244 return "MDB_MAXKEYSIZE";
1245 /* may want to make this a dynamic check: if the key is mostly
1246 * printable characters, print it as-is instead of converting to hex.
1250 for (i=0; i<key->mv_size; i++)
1251 ptr += sprintf(ptr, "%02x", *c++);
1253 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1258 /** Display all the keys in the page. */
1260 mdb_page_list(MDB_page *mp)
1263 unsigned int i, nkeys, nsize, total = 0;
1267 nkeys = NUMKEYS(mp);
1268 fprintf(stderr, "Page %"Z"u numkeys %d\n", mdb_dbg_pgno(mp), nkeys);
1269 for (i=0; i<nkeys; i++) {
1270 node = NODEPTR(mp, i);
1271 key.mv_size = node->mn_ksize;
1272 key.mv_data = node->mn_data;
1273 nsize = NODESIZE + key.mv_size;
1274 if (IS_BRANCH(mp)) {
1275 fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
1279 if (F_ISSET(node->mn_flags, F_BIGDATA))
1280 nsize += sizeof(pgno_t);
1282 nsize += NODEDSZ(node);
1284 nsize += sizeof(indx_t);
1285 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1287 total = EVEN(total);
1289 fprintf(stderr, "Total: %d\n", total);
1293 mdb_cursor_chk(MDB_cursor *mc)
1299 if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1300 for (i=0; i<mc->mc_top; i++) {
1302 node = NODEPTR(mp, mc->mc_ki[i]);
1303 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1306 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1312 /** Count all the pages in each DB and in the freelist
1313 * and make sure it matches the actual number of pages
1316 static void mdb_audit(MDB_txn *txn)
1320 MDB_ID freecount, count;
1325 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1326 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1327 freecount += *(MDB_ID *)data.mv_data;
1330 for (i = 0; i<txn->mt_numdbs; i++) {
1332 mdb_cursor_init(&mc, txn, i, &mx);
1333 if (txn->mt_dbs[i].md_root == P_INVALID)
1335 count += txn->mt_dbs[i].md_branch_pages +
1336 txn->mt_dbs[i].md_leaf_pages +
1337 txn->mt_dbs[i].md_overflow_pages;
1338 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1339 mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1343 mp = mc.mc_pg[mc.mc_top];
1344 for (j=0; j<NUMKEYS(mp); j++) {
1345 MDB_node *leaf = NODEPTR(mp, j);
1346 if (leaf->mn_flags & F_SUBDATA) {
1348 memcpy(&db, NODEDATA(leaf), sizeof(db));
1349 count += db.md_branch_pages + db.md_leaf_pages +
1350 db.md_overflow_pages;
1354 while (mdb_cursor_sibling(&mc, 1) == 0);
1357 if (freecount + count + 2 /* metapages */ != txn->mt_next_pgno) {
1358 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1359 txn->mt_txnid, freecount, count+2, freecount+count+2, txn->mt_next_pgno);
1365 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1367 return txn->mt_dbxs[dbi].md_cmp(a, b);
1371 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1373 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1376 /** Allocate memory for a page.
1377 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1380 mdb_page_malloc(MDB_txn *txn, unsigned num)
1382 MDB_env *env = txn->mt_env;
1383 MDB_page *ret = env->me_dpages;
1384 size_t psize = env->me_psize, sz = psize, off;
1385 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1386 * For a single page alloc, we init everything after the page header.
1387 * For multi-page, we init the final page; if the caller needed that
1388 * many pages they will be filling in at least up to the last page.
1392 VGMEMP_ALLOC(env, ret, sz);
1393 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1394 env->me_dpages = ret->mp_next;
1397 psize -= off = PAGEHDRSZ;
1402 if ((ret = malloc(sz)) != NULL) {
1403 VGMEMP_ALLOC(env, ret, sz);
1404 if (!(env->me_flags & MDB_NOMEMINIT)) {
1405 memset((char *)ret + off, 0, psize);
1412 /** Free a single page.
1413 * Saves single pages to a list, for future reuse.
1414 * (This is not used for multi-page overflow pages.)
1417 mdb_page_free(MDB_env *env, MDB_page *mp)
1419 mp->mp_next = env->me_dpages;
1420 VGMEMP_FREE(env, mp);
1421 env->me_dpages = mp;
1424 /** Free a dirty page */
1426 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1428 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1429 mdb_page_free(env, dp);
1431 /* large pages just get freed directly */
1432 VGMEMP_FREE(env, dp);
1437 /** Return all dirty pages to dpage list */
1439 mdb_dlist_free(MDB_txn *txn)
1441 MDB_env *env = txn->mt_env;
1442 MDB_ID2L dl = txn->mt_u.dirty_list;
1443 unsigned i, n = dl[0].mid;
1445 for (i = 1; i <= n; i++) {
1446 mdb_dpage_free(env, dl[i].mptr);
1451 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
1452 * @param[in] mc A cursor handle for the current operation.
1453 * @param[in] pflags Flags of the pages to update:
1454 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1455 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
1456 * @return 0 on success, non-zero on failure.
1459 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
1461 enum { Mask = P_SUBP|P_DIRTY|P_KEEP };
1462 MDB_txn *txn = mc->mc_txn;
1468 int rc = MDB_SUCCESS, level;
1470 /* Mark pages seen by cursors */
1471 if (mc->mc_flags & C_UNTRACK)
1472 mc = NULL; /* will find mc in mt_cursors */
1473 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1474 for (; mc; mc=mc->mc_next) {
1475 if (!(mc->mc_flags & C_INITIALIZED))
1477 for (m3 = mc;; m3 = &mx->mx_cursor) {
1479 for (j=0; j<m3->mc_snum; j++) {
1481 if ((mp->mp_flags & Mask) == pflags)
1482 mp->mp_flags ^= P_KEEP;
1484 mx = m3->mc_xcursor;
1485 /* Proceed to mx if it is at a sub-database */
1486 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
1488 if (! (mp && (mp->mp_flags & P_LEAF)))
1490 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
1491 if (!(leaf->mn_flags & F_SUBDATA))
1500 /* Mark dirty root pages */
1501 for (i=0; i<txn->mt_numdbs; i++) {
1502 if (txn->mt_dbflags[i] & DB_DIRTY) {
1503 pgno_t pgno = txn->mt_dbs[i].md_root;
1504 if (pgno == P_INVALID)
1506 if ((rc = mdb_page_get(txn, pgno, &dp, &level)) != MDB_SUCCESS)
1508 if ((dp->mp_flags & Mask) == pflags && level <= 1)
1509 dp->mp_flags ^= P_KEEP;
1517 static int mdb_page_flush(MDB_txn *txn, int keep);
1519 /** Spill pages from the dirty list back to disk.
1520 * This is intended to prevent running into #MDB_TXN_FULL situations,
1521 * but note that they may still occur in a few cases:
1522 * 1) our estimate of the txn size could be too small. Currently this
1523 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
1524 * 2) child txns may run out of space if their parents dirtied a
1525 * lot of pages and never spilled them. TODO: we probably should do
1526 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1527 * the parent's dirty_room is below a given threshold.
1529 * Otherwise, if not using nested txns, it is expected that apps will
1530 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1531 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1532 * If the txn never references them again, they can be left alone.
1533 * If the txn only reads them, they can be used without any fuss.
1534 * If the txn writes them again, they can be dirtied immediately without
1535 * going thru all of the work of #mdb_page_touch(). Such references are
1536 * handled by #mdb_page_unspill().
1538 * Also note, we never spill DB root pages, nor pages of active cursors,
1539 * because we'll need these back again soon anyway. And in nested txns,
1540 * we can't spill a page in a child txn if it was already spilled in a
1541 * parent txn. That would alter the parent txns' data even though
1542 * the child hasn't committed yet, and we'd have no way to undo it if
1543 * the child aborted.
1545 * @param[in] m0 cursor A cursor handle identifying the transaction and
1546 * database for which we are checking space.
1547 * @param[in] key For a put operation, the key being stored.
1548 * @param[in] data For a put operation, the data being stored.
1549 * @return 0 on success, non-zero on failure.
1552 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1554 MDB_txn *txn = m0->mc_txn;
1556 MDB_ID2L dl = txn->mt_u.dirty_list;
1557 unsigned int i, j, need;
1560 if (m0->mc_flags & C_SUB)
1563 /* Estimate how much space this op will take */
1564 i = m0->mc_db->md_depth;
1565 /* Named DBs also dirty the main DB */
1566 if (m0->mc_dbi > MAIN_DBI)
1567 i += txn->mt_dbs[MAIN_DBI].md_depth;
1568 /* For puts, roughly factor in the key+data size */
1570 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
1571 i += i; /* double it for good measure */
1574 if (txn->mt_dirty_room > i)
1577 if (!txn->mt_spill_pgs) {
1578 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
1579 if (!txn->mt_spill_pgs)
1582 /* purge deleted slots */
1583 MDB_IDL sl = txn->mt_spill_pgs;
1584 unsigned int num = sl[0];
1586 for (i=1; i<=num; i++) {
1593 /* Preserve pages which may soon be dirtied again */
1594 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
1597 /* Less aggressive spill - we originally spilled the entire dirty list,
1598 * with a few exceptions for cursor pages and DB root pages. But this
1599 * turns out to be a lot of wasted effort because in a large txn many
1600 * of those pages will need to be used again. So now we spill only 1/8th
1601 * of the dirty pages. Testing revealed this to be a good tradeoff,
1602 * better than 1/2, 1/4, or 1/10.
1604 if (need < MDB_IDL_UM_MAX / 8)
1605 need = MDB_IDL_UM_MAX / 8;
1607 /* Save the page IDs of all the pages we're flushing */
1608 /* flush from the tail forward, this saves a lot of shifting later on. */
1609 for (i=dl[0].mid; i && need; i--) {
1610 MDB_ID pn = dl[i].mid << 1;
1612 if (dp->mp_flags & P_KEEP)
1614 /* Can't spill twice, make sure it's not already in a parent's
1617 if (txn->mt_parent) {
1619 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1620 if (tx2->mt_spill_pgs) {
1621 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
1622 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
1623 dp->mp_flags |= P_KEEP;
1631 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
1635 mdb_midl_sort(txn->mt_spill_pgs);
1637 /* Flush the spilled part of dirty list */
1638 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
1641 /* Reset any dirty pages we kept that page_flush didn't see */
1642 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
1645 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
1649 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
1651 mdb_find_oldest(MDB_txn *txn)
1654 txnid_t mr, oldest = txn->mt_txnid - 1;
1655 if (txn->mt_env->me_txns) {
1656 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
1657 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
1668 /** Add a page to the txn's dirty list */
1670 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
1673 int (*insert)(MDB_ID2L, MDB_ID2 *);
1675 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1676 insert = mdb_mid2l_append;
1678 insert = mdb_mid2l_insert;
1680 mid.mid = mp->mp_pgno;
1682 insert(txn->mt_u.dirty_list, &mid);
1683 txn->mt_dirty_room--;
1686 /** Allocate page numbers and memory for writing. Maintain me_pglast,
1687 * me_pghead and mt_next_pgno.
1689 * If there are free pages available from older transactions, they
1690 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
1691 * Do not modify the freedB, just merge freeDB records into me_pghead[]
1692 * and move me_pglast to say which records were consumed. Only this
1693 * function can create me_pghead and move me_pglast/mt_next_pgno.
1694 * @param[in] mc cursor A cursor handle identifying the transaction and
1695 * database for which we are allocating.
1696 * @param[in] num the number of pages to allocate.
1697 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
1698 * will always be satisfied by a single contiguous chunk of memory.
1699 * @return 0 on success, non-zero on failure.
1702 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
1704 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
1705 /* Get at most <Max_retries> more freeDB records once me_pghead
1706 * has enough pages. If not enough, use new pages from the map.
1707 * If <Paranoid> and mc is updating the freeDB, only get new
1708 * records if me_pghead is empty. Then the freelist cannot play
1709 * catch-up with itself by growing while trying to save it.
1711 enum { Paranoid = 1, Max_retries = 500 };
1713 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
1715 int rc, retry = Max_retries;
1716 MDB_txn *txn = mc->mc_txn;
1717 MDB_env *env = txn->mt_env;
1718 pgno_t pgno, *mop = env->me_pghead;
1719 unsigned i, j, k, mop_len = mop ? mop[0] : 0, n2 = num-1;
1721 txnid_t oldest = 0, last;
1727 /* If our dirty list is already full, we can't do anything */
1728 if (txn->mt_dirty_room == 0)
1729 return MDB_TXN_FULL;
1731 for (op = MDB_FIRST;; op = MDB_NEXT) {
1734 pgno_t *idl, old_id, new_id;
1736 /* Seek a big enough contiguous page range. Prefer
1737 * pages at the tail, just truncating the list.
1743 if (mop[i-n2] == pgno+n2)
1746 if (Max_retries < INT_MAX && --retry < 0)
1750 if (op == MDB_FIRST) { /* 1st iteration */
1751 /* Prepare to fetch more and coalesce */
1752 oldest = mdb_find_oldest(txn);
1753 last = env->me_pglast;
1754 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1757 key.mv_data = &last; /* will look up last+1 */
1758 key.mv_size = sizeof(last);
1760 if (Paranoid && mc->mc_dbi == FREE_DBI)
1763 if (Paranoid && retry < 0 && mop_len)
1767 /* Do not fetch more if the record will be too recent */
1770 rc = mdb_cursor_get(&m2, &key, NULL, op);
1772 if (rc == MDB_NOTFOUND)
1776 last = *(txnid_t*)key.mv_data;
1779 np = m2.mc_pg[m2.mc_top];
1780 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
1781 if ((rc = mdb_node_read(txn, leaf, &data)) != MDB_SUCCESS)
1784 idl = (MDB_ID *) data.mv_data;
1787 if (!(env->me_pghead = mop = mdb_midl_alloc(i)))
1790 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
1792 mop = env->me_pghead;
1794 env->me_pglast = last;
1796 DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
1797 last, txn->mt_dbs[FREE_DBI].md_root, i));
1799 DPRINTF(("IDL %"Z"u", idl[k]));
1801 /* Merge in descending sorted order */
1804 mop[0] = (pgno_t)-1;
1808 for (; old_id < new_id; old_id = mop[--j])
1815 /* Use new pages from the map when nothing suitable in the freeDB */
1817 pgno = txn->mt_next_pgno;
1818 if (pgno + num >= env->me_maxpg) {
1819 DPUTS("DB size maxed out");
1820 return MDB_MAP_FULL;
1824 if (env->me_flags & MDB_WRITEMAP) {
1825 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
1827 if (!(np = mdb_page_malloc(txn, num)))
1831 mop[0] = mop_len -= num;
1832 /* Move any stragglers down */
1833 for (j = i-num; j < mop_len; )
1834 mop[++j] = mop[++i];
1836 txn->mt_next_pgno = pgno + num;
1839 mdb_page_dirty(txn, np);
1845 /** Copy the used portions of a non-overflow page.
1846 * @param[in] dst page to copy into
1847 * @param[in] src page to copy from
1848 * @param[in] psize size of a page
1851 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
1853 enum { Align = sizeof(pgno_t) };
1854 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
1856 /* If page isn't full, just copy the used portion. Adjust
1857 * alignment so memcpy may copy words instead of bytes.
1859 if ((unused &= -Align) && !IS_LEAF2(src)) {
1861 memcpy(dst, src, (lower + (Align-1)) & -Align);
1862 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
1865 memcpy(dst, src, psize - unused);
1869 /** Pull a page off the txn's spill list, if present.
1870 * If a page being referenced was spilled to disk in this txn, bring
1871 * it back and make it dirty/writable again.
1872 * @param[in] txn the transaction handle.
1873 * @param[in] mp the page being referenced. It must not be dirty.
1874 * @param[out] ret the writable page, if any. ret is unchanged if
1875 * mp wasn't spilled.
1878 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
1880 MDB_env *env = txn->mt_env;
1883 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
1885 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
1886 if (!tx2->mt_spill_pgs)
1888 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
1889 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
1892 if (txn->mt_dirty_room == 0)
1893 return MDB_TXN_FULL;
1894 if (IS_OVERFLOW(mp))
1898 if (env->me_flags & MDB_WRITEMAP) {
1901 np = mdb_page_malloc(txn, num);
1905 memcpy(np, mp, num * env->me_psize);
1907 mdb_page_copy(np, mp, env->me_psize);
1910 /* If in current txn, this page is no longer spilled.
1911 * If it happens to be the last page, truncate the spill list.
1912 * Otherwise mark it as deleted by setting the LSB.
1914 if (x == txn->mt_spill_pgs[0])
1915 txn->mt_spill_pgs[0]--;
1917 txn->mt_spill_pgs[x] |= 1;
1918 } /* otherwise, if belonging to a parent txn, the
1919 * page remains spilled until child commits
1922 mdb_page_dirty(txn, np);
1923 np->mp_flags |= P_DIRTY;
1931 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1932 * @param[in] mc cursor pointing to the page to be touched
1933 * @return 0 on success, non-zero on failure.
1936 mdb_page_touch(MDB_cursor *mc)
1938 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
1939 MDB_txn *txn = mc->mc_txn;
1940 MDB_cursor *m2, *m3;
1944 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1945 if (txn->mt_flags & MDB_TXN_SPILLS) {
1947 rc = mdb_page_unspill(txn, mp, &np);
1953 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
1954 (rc = mdb_page_alloc(mc, 1, &np)))
1957 DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
1958 mp->mp_pgno, pgno));
1959 assert(mp->mp_pgno != pgno);
1960 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
1961 /* Update the parent page, if any, to point to the new page */
1963 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
1964 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
1965 SETPGNO(node, pgno);
1967 mc->mc_db->md_root = pgno;
1969 } else if (txn->mt_parent && !IS_SUBP(mp)) {
1970 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
1972 /* If txn has a parent, make sure the page is in our
1976 unsigned x = mdb_mid2l_search(dl, pgno);
1977 if (x <= dl[0].mid && dl[x].mid == pgno) {
1978 if (mp != dl[x].mptr) { /* bad cursor? */
1979 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1980 return MDB_CORRUPTED;
1985 assert(dl[0].mid < MDB_IDL_UM_MAX);
1987 np = mdb_page_malloc(txn, 1);
1992 mdb_mid2l_insert(dl, &mid);
1997 mdb_page_copy(np, mp, txn->mt_env->me_psize);
1999 np->mp_flags |= P_DIRTY;
2002 /* Adjust cursors pointing to mp */
2003 mc->mc_pg[mc->mc_top] = np;
2004 m2 = txn->mt_cursors[mc->mc_dbi];
2005 if (mc->mc_flags & C_SUB) {
2006 for (; m2; m2=m2->mc_next) {
2007 m3 = &m2->mc_xcursor->mx_cursor;
2008 if (m3->mc_snum < mc->mc_snum) continue;
2009 if (m3->mc_pg[mc->mc_top] == mp)
2010 m3->mc_pg[mc->mc_top] = np;
2013 for (; m2; m2=m2->mc_next) {
2014 if (m2->mc_snum < mc->mc_snum) continue;
2015 if (m2->mc_pg[mc->mc_top] == mp) {
2016 m2->mc_pg[mc->mc_top] = np;
2017 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
2018 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
2020 MDB_node *leaf = NODEPTR(np, mc->mc_ki[mc->mc_top]);
2021 if (!(leaf->mn_flags & F_SUBDATA))
2022 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
2031 mdb_env_sync(MDB_env *env, int force)
2034 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2035 if (env->me_flags & MDB_WRITEMAP) {
2036 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2037 ? MS_ASYNC : MS_SYNC;
2038 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
2041 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2045 if (MDB_FDATASYNC(env->me_fd))
2052 /** Back up parent txn's cursors, then grab the originals for tracking */
2054 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2056 MDB_cursor *mc, *bk;
2061 for (i = src->mt_numdbs; --i >= 0; ) {
2062 if ((mc = src->mt_cursors[i]) != NULL) {
2063 size = sizeof(MDB_cursor);
2065 size += sizeof(MDB_xcursor);
2066 for (; mc; mc = bk->mc_next) {
2072 mc->mc_db = &dst->mt_dbs[i];
2073 /* Kill pointers into src - and dst to reduce abuse: The
2074 * user may not use mc until dst ends. Otherwise we'd...
2076 mc->mc_txn = NULL; /* ...set this to dst */
2077 mc->mc_dbflag = NULL; /* ...and &dst->mt_dbflags[i] */
2078 if ((mx = mc->mc_xcursor) != NULL) {
2079 *(MDB_xcursor *)(bk+1) = *mx;
2080 mx->mx_cursor.mc_txn = NULL; /* ...and dst. */
2082 mc->mc_next = dst->mt_cursors[i];
2083 dst->mt_cursors[i] = mc;
2090 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2091 * @param[in] txn the transaction handle.
2092 * @param[in] merge true to keep changes to parent cursors, false to revert.
2093 * @return 0 on success, non-zero on failure.
2096 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2098 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2102 for (i = txn->mt_numdbs; --i >= 0; ) {
2103 for (mc = cursors[i]; mc; mc = next) {
2105 if ((bk = mc->mc_backup) != NULL) {
2107 /* Commit changes to parent txn */
2108 mc->mc_next = bk->mc_next;
2109 mc->mc_backup = bk->mc_backup;
2110 mc->mc_txn = bk->mc_txn;
2111 mc->mc_db = bk->mc_db;
2112 mc->mc_dbflag = bk->mc_dbflag;
2113 if ((mx = mc->mc_xcursor) != NULL)
2114 mx->mx_cursor.mc_txn = bk->mc_txn;
2116 /* Abort nested txn */
2118 if ((mx = mc->mc_xcursor) != NULL)
2119 *mx = *(MDB_xcursor *)(bk+1);
2123 /* Only malloced cursors are permanently tracked. */
2131 #define mdb_txn_reset0(txn, act) mdb_txn_reset0(txn)
2134 mdb_txn_reset0(MDB_txn *txn, const char *act);
2136 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2142 Pidset = F_SETLK, Pidcheck = F_GETLK
2146 /** Set or check a pid lock. Set returns 0 on success.
2147 * Check returns 0 if the process is certainly dead, nonzero if it may
2148 * be alive (the lock exists or an error happened so we do not know).
2150 * On Windows Pidset is a no-op, we merely check for the existence
2151 * of the process with the given pid. On POSIX we use a single byte
2152 * lock on the lockfile, set at an offset equal to the pid.
2155 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2157 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2160 if (op == Pidcheck) {
2161 h = OpenProcess(env->me_pidquery, FALSE, pid);
2162 /* No documented "no such process" code, but other program use this: */
2164 return ErrCode() != ERROR_INVALID_PARAMETER;
2165 /* A process exists until all handles to it close. Has it exited? */
2166 ret = WaitForSingleObject(h, 0) != 0;
2173 struct flock lock_info;
2174 memset(&lock_info, 0, sizeof(lock_info));
2175 lock_info.l_type = F_WRLCK;
2176 lock_info.l_whence = SEEK_SET;
2177 lock_info.l_start = pid;
2178 lock_info.l_len = 1;
2179 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2180 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2182 } else if ((rc = ErrCode()) == EINTR) {
2190 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2191 * @param[in] txn the transaction handle to initialize
2192 * @return 0 on success, non-zero on failure.
2195 mdb_txn_renew0(MDB_txn *txn)
2197 MDB_env *env = txn->mt_env;
2198 MDB_txninfo *ti = env->me_txns;
2202 int rc, new_notls = 0;
2205 txn->mt_numdbs = env->me_numdbs;
2206 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
2208 if (txn->mt_flags & MDB_TXN_RDONLY) {
2210 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2211 txn->mt_txnid = meta->mm_txnid;
2212 txn->mt_u.reader = NULL;
2214 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2215 pthread_getspecific(env->me_txkey);
2217 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2218 return MDB_BAD_RSLOT;
2220 MDB_PID_T pid = env->me_pid;
2221 pthread_t tid = pthread_self();
2223 if (!(env->me_flags & MDB_LIVE_READER)) {
2224 rc = mdb_reader_pid(env, Pidset, pid);
2227 env->me_flags |= MDB_LIVE_READER;
2231 nr = ti->mti_numreaders;
2232 for (i=0; i<nr; i++)
2233 if (ti->mti_readers[i].mr_pid == 0)
2235 if (i == env->me_maxreaders) {
2236 UNLOCK_MUTEX_R(env);
2237 return MDB_READERS_FULL;
2239 ti->mti_readers[i].mr_pid = pid;
2240 ti->mti_readers[i].mr_tid = tid;
2242 ti->mti_numreaders = ++nr;
2243 /* Save numreaders for un-mutexed mdb_env_close() */
2244 env->me_numreaders = nr;
2245 UNLOCK_MUTEX_R(env);
2247 r = &ti->mti_readers[i];
2248 new_notls = (env->me_flags & MDB_NOTLS);
2249 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2254 txn->mt_txnid = r->mr_txnid = ti->mti_txnid;
2255 txn->mt_u.reader = r;
2256 meta = env->me_metas[txn->mt_txnid & 1];
2262 txn->mt_txnid = ti->mti_txnid;
2263 meta = env->me_metas[txn->mt_txnid & 1];
2265 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2266 txn->mt_txnid = meta->mm_txnid;
2270 if (txn->mt_txnid == mdb_debug_start)
2273 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2274 txn->mt_u.dirty_list = env->me_dirty_list;
2275 txn->mt_u.dirty_list[0].mid = 0;
2276 txn->mt_free_pgs = env->me_free_pgs;
2277 txn->mt_free_pgs[0] = 0;
2278 txn->mt_spill_pgs = NULL;
2282 /* Copy the DB info and flags */
2283 memcpy(txn->mt_dbs, meta->mm_dbs, 2 * sizeof(MDB_db));
2285 /* Moved to here to avoid a data race in read TXNs */
2286 txn->mt_next_pgno = meta->mm_last_pg+1;
2288 for (i=2; i<txn->mt_numdbs; i++) {
2289 x = env->me_dbflags[i];
2290 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2291 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_STALE : 0;
2293 txn->mt_dbflags[0] = txn->mt_dbflags[1] = DB_VALID;
2295 if (env->me_maxpg < txn->mt_next_pgno) {
2296 mdb_txn_reset0(txn, "renew0-mapfail");
2298 txn->mt_u.reader->mr_pid = 0;
2299 txn->mt_u.reader = NULL;
2301 return MDB_MAP_RESIZED;
2308 mdb_txn_renew(MDB_txn *txn)
2312 if (!txn || txn->mt_dbxs) /* A reset txn has mt_dbxs==NULL */
2315 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
2316 DPUTS("environment had fatal error, must shutdown!");
2320 rc = mdb_txn_renew0(txn);
2321 if (rc == MDB_SUCCESS) {
2322 DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2323 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2324 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2330 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2334 int rc, size, tsize = sizeof(MDB_txn);
2336 if (env->me_flags & MDB_FATAL_ERROR) {
2337 DPUTS("environment had fatal error, must shutdown!");
2340 if ((env->me_flags & MDB_RDONLY) && !(flags & MDB_RDONLY))
2343 /* Nested transactions: Max 1 child, write txns only, no writemap */
2344 if (parent->mt_child ||
2345 (flags & MDB_RDONLY) ||
2346 (parent->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR)) ||
2347 (env->me_flags & MDB_WRITEMAP))
2349 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
2351 tsize = sizeof(MDB_ntxn);
2353 size = tsize + env->me_maxdbs * (sizeof(MDB_db)+1);
2354 if (!(flags & MDB_RDONLY))
2355 size += env->me_maxdbs * sizeof(MDB_cursor *);
2357 if ((txn = calloc(1, size)) == NULL) {
2358 DPRINTF(("calloc: %s", strerror(ErrCode())));
2361 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2362 if (flags & MDB_RDONLY) {
2363 txn->mt_flags |= MDB_TXN_RDONLY;
2364 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
2366 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2367 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
2373 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2374 if (!txn->mt_u.dirty_list ||
2375 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2377 free(txn->mt_u.dirty_list);
2381 txn->mt_txnid = parent->mt_txnid;
2382 txn->mt_dirty_room = parent->mt_dirty_room;
2383 txn->mt_u.dirty_list[0].mid = 0;
2384 txn->mt_spill_pgs = NULL;
2385 txn->mt_next_pgno = parent->mt_next_pgno;
2386 parent->mt_child = txn;
2387 txn->mt_parent = parent;
2388 txn->mt_numdbs = parent->mt_numdbs;
2389 txn->mt_flags = parent->mt_flags;
2390 txn->mt_dbxs = parent->mt_dbxs;
2391 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2392 /* Copy parent's mt_dbflags, but clear DB_NEW */
2393 for (i=0; i<txn->mt_numdbs; i++)
2394 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2396 ntxn = (MDB_ntxn *)txn;
2397 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2398 if (env->me_pghead) {
2399 size = MDB_IDL_SIZEOF(env->me_pghead);
2400 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2402 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2407 rc = mdb_cursor_shadow(parent, txn);
2409 mdb_txn_reset0(txn, "beginchild-fail");
2411 rc = mdb_txn_renew0(txn);
2417 DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2418 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2419 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
2426 mdb_txn_env(MDB_txn *txn)
2428 if(!txn) return NULL;
2432 /** Export or close DBI handles opened in this txn. */
2434 mdb_dbis_update(MDB_txn *txn, int keep)
2437 MDB_dbi n = txn->mt_numdbs;
2438 MDB_env *env = txn->mt_env;
2439 unsigned char *tdbflags = txn->mt_dbflags;
2441 for (i = n; --i >= 2;) {
2442 if (tdbflags[i] & DB_NEW) {
2444 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2446 char *ptr = env->me_dbxs[i].md_name.mv_data;
2447 env->me_dbxs[i].md_name.mv_data = NULL;
2448 env->me_dbxs[i].md_name.mv_size = 0;
2449 env->me_dbflags[i] = 0;
2454 if (keep && env->me_numdbs < n)
2458 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
2459 * May be called twice for readonly txns: First reset it, then abort.
2460 * @param[in] txn the transaction handle to reset
2461 * @param[in] act why the transaction is being reset
2464 mdb_txn_reset0(MDB_txn *txn, const char *act)
2466 MDB_env *env = txn->mt_env;
2468 /* Close any DBI handles opened in this txn */
2469 mdb_dbis_update(txn, 0);
2471 DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2472 act, txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2473 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
2475 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2476 if (txn->mt_u.reader) {
2477 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2478 if (!(env->me_flags & MDB_NOTLS))
2479 txn->mt_u.reader = NULL; /* txn does not own reader */
2481 txn->mt_numdbs = 0; /* close nothing if called again */
2482 txn->mt_dbxs = NULL; /* mark txn as reset */
2484 mdb_cursors_close(txn, 0);
2486 if (!(env->me_flags & MDB_WRITEMAP)) {
2487 mdb_dlist_free(txn);
2489 mdb_midl_free(env->me_pghead);
2491 if (txn->mt_parent) {
2492 txn->mt_parent->mt_child = NULL;
2493 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2494 mdb_midl_free(txn->mt_free_pgs);
2495 mdb_midl_free(txn->mt_spill_pgs);
2496 free(txn->mt_u.dirty_list);
2500 if (mdb_midl_shrink(&txn->mt_free_pgs))
2501 env->me_free_pgs = txn->mt_free_pgs;
2502 env->me_pghead = NULL;
2506 /* The writer mutex was locked in mdb_txn_begin. */
2508 UNLOCK_MUTEX_W(env);
2513 mdb_txn_reset(MDB_txn *txn)
2518 /* This call is only valid for read-only txns */
2519 if (!(txn->mt_flags & MDB_TXN_RDONLY))
2522 mdb_txn_reset0(txn, "reset");
2526 mdb_txn_abort(MDB_txn *txn)
2532 mdb_txn_abort(txn->mt_child);
2534 mdb_txn_reset0(txn, "abort");
2535 /* Free reader slot tied to this txn (if MDB_NOTLS && writable FS) */
2536 if ((txn->mt_flags & MDB_TXN_RDONLY) && txn->mt_u.reader)
2537 txn->mt_u.reader->mr_pid = 0;
2542 /** Save the freelist as of this transaction to the freeDB.
2543 * This changes the freelist. Keep trying until it stabilizes.
2546 mdb_freelist_save(MDB_txn *txn)
2548 /* env->me_pghead[] can grow and shrink during this call.
2549 * env->me_pglast and txn->mt_free_pgs[] can only grow.
2550 * Page numbers cannot disappear from txn->mt_free_pgs[].
2553 MDB_env *env = txn->mt_env;
2554 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
2555 txnid_t pglast = 0, head_id = 0;
2556 pgno_t freecnt = 0, *free_pgs, *mop;
2557 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
2559 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
2561 if (env->me_pghead) {
2562 /* Make sure first page of freeDB is touched and on freelist */
2563 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
2564 if (rc && rc != MDB_NOTFOUND)
2568 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
2569 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
2570 ? SSIZE_MAX : maxfree_1pg;
2573 /* Come back here after each Put() in case freelist changed */
2578 /* If using records from freeDB which we have not yet
2579 * deleted, delete them and any we reserved for me_pghead.
2581 while (pglast < env->me_pglast) {
2582 rc = mdb_cursor_first(&mc, &key, NULL);
2585 pglast = head_id = *(txnid_t *)key.mv_data;
2586 total_room = head_room = 0;
2587 assert(pglast <= env->me_pglast);
2588 rc = mdb_cursor_del(&mc, 0);
2593 /* Save the IDL of pages freed by this txn, to a single record */
2594 if (freecnt < txn->mt_free_pgs[0]) {
2596 /* Make sure last page of freeDB is touched and on freelist */
2597 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
2598 if (rc && rc != MDB_NOTFOUND)
2601 free_pgs = txn->mt_free_pgs;
2602 /* Write to last page of freeDB */
2603 key.mv_size = sizeof(txn->mt_txnid);
2604 key.mv_data = &txn->mt_txnid;
2606 freecnt = free_pgs[0];
2607 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
2608 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2611 /* Retry if mt_free_pgs[] grew during the Put() */
2612 free_pgs = txn->mt_free_pgs;
2613 } while (freecnt < free_pgs[0]);
2614 mdb_midl_sort(free_pgs);
2615 memcpy(data.mv_data, free_pgs, data.mv_size);
2618 unsigned int i = free_pgs[0];
2619 DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
2620 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
2622 DPRINTF(("IDL %"Z"u", free_pgs[i]));
2628 mop = env->me_pghead;
2629 mop_len = mop ? mop[0] : 0;
2631 /* Reserve records for me_pghead[]. Split it if multi-page,
2632 * to avoid searching freeDB for a page range. Use keys in
2633 * range [1,me_pglast]: Smaller than txnid of oldest reader.
2635 if (total_room >= mop_len) {
2636 if (total_room == mop_len || --more < 0)
2638 } else if (head_room >= maxfree_1pg && head_id > 1) {
2639 /* Keep current record (overflow page), add a new one */
2643 /* (Re)write {key = head_id, IDL length = head_room} */
2644 total_room -= head_room;
2645 head_room = mop_len - total_room;
2646 if (head_room > maxfree_1pg && head_id > 1) {
2647 /* Overflow multi-page for part of me_pghead */
2648 head_room /= head_id; /* amortize page sizes */
2649 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
2650 } else if (head_room < 0) {
2651 /* Rare case, not bothering to delete this record */
2654 key.mv_size = sizeof(head_id);
2655 key.mv_data = &head_id;
2656 data.mv_size = (head_room + 1) * sizeof(pgno_t);
2657 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2660 /* IDL is initially empty, zero out at least the length */
2661 pgs = (pgno_t *)data.mv_data;
2662 j = head_room > clean_limit ? head_room : 0;
2666 total_room += head_room;
2669 /* Fill in the reserved me_pghead records */
2675 rc = mdb_cursor_first(&mc, &key, &data);
2676 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
2677 unsigned flags = MDB_CURRENT;
2678 txnid_t id = *(txnid_t *)key.mv_data;
2679 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
2682 assert(len >= 0 && id <= env->me_pglast);
2684 if (len > mop_len) {
2686 data.mv_size = (len + 1) * sizeof(MDB_ID);
2689 data.mv_data = mop -= len;
2692 rc = mdb_cursor_put(&mc, &key, &data, flags);
2694 if (rc || !(mop_len -= len))
2701 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
2702 * @param[in] txn the transaction that's being committed
2703 * @param[in] keep number of initial pages in dirty_list to keep dirty.
2704 * @return 0 on success, non-zero on failure.
2707 mdb_page_flush(MDB_txn *txn, int keep)
2709 MDB_env *env = txn->mt_env;
2710 MDB_ID2L dl = txn->mt_u.dirty_list;
2711 unsigned psize = env->me_psize, j;
2712 int i, pagecount = dl[0].mid, rc;
2713 size_t size = 0, pos = 0;
2715 MDB_page *dp = NULL;
2719 struct iovec iov[MDB_COMMIT_PAGES];
2720 ssize_t wpos = 0, wsize = 0, wres;
2721 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
2727 if (env->me_flags & MDB_WRITEMAP) {
2728 /* Clear dirty flags */
2729 while (++i <= pagecount) {
2731 /* Don't flush this page yet */
2732 if (dp->mp_flags & P_KEEP) {
2733 dp->mp_flags ^= P_KEEP;
2737 dp->mp_flags &= ~P_DIRTY;
2742 /* Write the pages */
2744 if (++i <= pagecount) {
2746 /* Don't flush this page yet */
2747 if (dp->mp_flags & P_KEEP) {
2748 dp->mp_flags ^= P_KEEP;
2753 /* clear dirty flag */
2754 dp->mp_flags &= ~P_DIRTY;
2757 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
2762 /* Windows actually supports scatter/gather I/O, but only on
2763 * unbuffered file handles. Since we're relying on the OS page
2764 * cache for all our data, that's self-defeating. So we just
2765 * write pages one at a time. We use the ov structure to set
2766 * the write offset, to at least save the overhead of a Seek
2769 DPRINTF(("committing page %"Z"u", pgno));
2770 memset(&ov, 0, sizeof(ov));
2771 ov.Offset = pos & 0xffffffff;
2772 ov.OffsetHigh = pos >> 16 >> 16;
2773 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
2775 DPRINTF(("WriteFile: %d", rc));
2779 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
2780 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
2782 /* Write previous page(s) */
2783 #ifdef MDB_USE_PWRITEV
2784 wres = pwritev(env->me_fd, iov, n, wpos);
2787 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
2789 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
2791 DPRINTF(("lseek: %s", strerror(rc)));
2794 wres = writev(env->me_fd, iov, n);
2797 if (wres != wsize) {
2800 DPRINTF(("Write error: %s", strerror(rc)));
2802 rc = EIO; /* TODO: Use which error code? */
2803 DPUTS("short write, filesystem full?");
2814 DPRINTF(("committing page %"Z"u", pgno));
2815 next_pos = pos + size;
2816 iov[n].iov_len = size;
2817 iov[n].iov_base = (char *)dp;
2823 for (i = keep; ++i <= pagecount; ) {
2825 /* This is a page we skipped above */
2828 dl[j].mid = dp->mp_pgno;
2831 mdb_dpage_free(env, dp);
2836 txn->mt_dirty_room += i - j;
2842 mdb_txn_commit(MDB_txn *txn)
2848 if (txn == NULL || txn->mt_env == NULL)
2851 if (txn->mt_child) {
2852 rc = mdb_txn_commit(txn->mt_child);
2853 txn->mt_child = NULL;
2860 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2861 mdb_dbis_update(txn, 1);
2862 txn->mt_numdbs = 2; /* so txn_abort() doesn't close any new handles */
2867 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
2868 DPUTS("error flag is set, can't commit");
2870 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
2875 if (txn->mt_parent) {
2876 MDB_txn *parent = txn->mt_parent;
2879 unsigned x, y, len, ps_len;
2881 /* Append our free list to parent's */
2882 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
2885 mdb_midl_free(txn->mt_free_pgs);
2886 /* Failures after this must either undo the changes
2887 * to the parent or set MDB_TXN_ERROR in the parent.
2890 parent->mt_next_pgno = txn->mt_next_pgno;
2891 parent->mt_flags = txn->mt_flags;
2893 /* Merge our cursors into parent's and close them */
2894 mdb_cursors_close(txn, 1);
2896 /* Update parent's DB table. */
2897 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2898 parent->mt_numdbs = txn->mt_numdbs;
2899 parent->mt_dbflags[0] = txn->mt_dbflags[0];
2900 parent->mt_dbflags[1] = txn->mt_dbflags[1];
2901 for (i=2; i<txn->mt_numdbs; i++) {
2902 /* preserve parent's DB_NEW status */
2903 x = parent->mt_dbflags[i] & DB_NEW;
2904 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
2907 dst = parent->mt_u.dirty_list;
2908 src = txn->mt_u.dirty_list;
2909 /* Remove anything in our dirty list from parent's spill list */
2910 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
2912 pspill[0] = (pgno_t)-1;
2913 /* Mark our dirty pages as deleted in parent spill list */
2914 for (i=0, len=src[0].mid; ++i <= len; ) {
2915 MDB_ID pn = src[i].mid << 1;
2916 while (pn > pspill[x])
2918 if (pn == pspill[x]) {
2923 /* Squash deleted pagenums if we deleted any */
2924 for (x=y; ++x <= ps_len; )
2925 if (!(pspill[x] & 1))
2926 pspill[++y] = pspill[x];
2930 /* Find len = length of merging our dirty list with parent's */
2932 dst[0].mid = 0; /* simplify loops */
2933 if (parent->mt_parent) {
2934 len = x + src[0].mid;
2935 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
2936 for (i = x; y && i; y--) {
2937 pgno_t yp = src[y].mid;
2938 while (yp < dst[i].mid)
2940 if (yp == dst[i].mid) {
2945 } else { /* Simplify the above for single-ancestor case */
2946 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
2948 /* Merge our dirty list with parent's */
2950 for (i = len; y; dst[i--] = src[y--]) {
2951 pgno_t yp = src[y].mid;
2952 while (yp < dst[x].mid)
2953 dst[i--] = dst[x--];
2954 if (yp == dst[x].mid)
2955 free(dst[x--].mptr);
2959 free(txn->mt_u.dirty_list);
2960 parent->mt_dirty_room = txn->mt_dirty_room;
2961 if (txn->mt_spill_pgs) {
2962 if (parent->mt_spill_pgs) {
2963 /* TODO: Prevent failure here, so parent does not fail */
2964 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
2966 parent->mt_flags |= MDB_TXN_ERROR;
2967 mdb_midl_free(txn->mt_spill_pgs);
2968 mdb_midl_sort(parent->mt_spill_pgs);
2970 parent->mt_spill_pgs = txn->mt_spill_pgs;
2974 parent->mt_child = NULL;
2975 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
2980 if (txn != env->me_txn) {
2981 DPUTS("attempt to commit unknown transaction");
2986 mdb_cursors_close(txn, 0);
2988 if (!txn->mt_u.dirty_list[0].mid &&
2989 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
2992 DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
2993 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
2995 /* Update DB root pointers */
2996 if (txn->mt_numdbs > 2) {
3000 data.mv_size = sizeof(MDB_db);
3002 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3003 for (i = 2; i < txn->mt_numdbs; i++) {
3004 if (txn->mt_dbflags[i] & DB_DIRTY) {
3005 data.mv_data = &txn->mt_dbs[i];
3006 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
3013 rc = mdb_freelist_save(txn);
3017 mdb_midl_free(env->me_pghead);
3018 env->me_pghead = NULL;
3019 if (mdb_midl_shrink(&txn->mt_free_pgs))
3020 env->me_free_pgs = txn->mt_free_pgs;
3026 if ((rc = mdb_page_flush(txn, 0)) ||
3027 (rc = mdb_env_sync(env, 0)) ||
3028 (rc = mdb_env_write_meta(txn)))
3034 mdb_dbis_update(txn, 1);
3037 UNLOCK_MUTEX_W(env);
3047 /** Read the environment parameters of a DB environment before
3048 * mapping it into memory.
3049 * @param[in] env the environment handle
3050 * @param[out] meta address of where to store the meta information
3051 * @return 0 on success, non-zero on failure.
3054 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3060 enum { Size = sizeof(pbuf) };
3062 /* We don't know the page size yet, so use a minimum value.
3063 * Read both meta pages so we can use the latest one.
3066 for (i=off=0; i<2; i++, off = meta->mm_psize) {
3070 memset(&ov, 0, sizeof(ov));
3072 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3073 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3076 rc = pread(env->me_fd, &pbuf, Size, off);
3079 if (rc == 0 && off == 0)
3081 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3082 DPRINTF(("read: %s", mdb_strerror(rc)));
3086 p = (MDB_page *)&pbuf;
3088 if (!F_ISSET(p->mp_flags, P_META)) {
3089 DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
3094 if (m->mm_magic != MDB_MAGIC) {
3095 DPUTS("meta has invalid magic");
3099 if (m->mm_version != MDB_DATA_VERSION) {
3100 DPRINTF(("database is version %u, expected version %u",
3101 m->mm_version, MDB_DATA_VERSION));
3102 return MDB_VERSION_MISMATCH;
3105 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3111 /** Write the environment parameters of a freshly created DB environment.
3112 * @param[in] env the environment handle
3113 * @param[out] meta address of where to store the meta information
3114 * @return 0 on success, non-zero on failure.
3117 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3125 memset(&ov, 0, sizeof(ov));
3126 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3128 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3131 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3132 len = pwrite(fd, ptr, size, pos); \
3133 rc = (len >= 0); } while(0)
3136 DPUTS("writing new meta page");
3138 psize = env->me_psize;
3140 meta->mm_magic = MDB_MAGIC;
3141 meta->mm_version = MDB_DATA_VERSION;
3142 meta->mm_mapsize = env->me_mapsize;
3143 meta->mm_psize = psize;
3144 meta->mm_last_pg = 1;
3145 meta->mm_flags = env->me_flags & 0xffff;
3146 meta->mm_flags |= MDB_INTEGERKEY;
3147 meta->mm_dbs[0].md_root = P_INVALID;
3148 meta->mm_dbs[1].md_root = P_INVALID;
3150 p = calloc(2, psize);
3152 p->mp_flags = P_META;
3153 *(MDB_meta *)METADATA(p) = *meta;
3155 q = (MDB_page *)((char *)p + psize);
3157 q->mp_flags = P_META;
3158 *(MDB_meta *)METADATA(q) = *meta;
3160 DO_PWRITE(rc, env->me_fd, p, psize * 2, len, 0);
3163 else if ((unsigned) len == psize * 2)
3171 /** Update the environment info to commit a transaction.
3172 * @param[in] txn the transaction that's being committed
3173 * @return 0 on success, non-zero on failure.
3176 mdb_env_write_meta(MDB_txn *txn)
3179 MDB_meta meta, metab, *mp;
3181 int rc, len, toggle;
3190 toggle = txn->mt_txnid & 1;
3191 DPRINTF(("writing meta page %d for root page %"Z"u",
3192 toggle, txn->mt_dbs[MAIN_DBI].md_root));
3195 mp = env->me_metas[toggle];
3197 if (env->me_flags & MDB_WRITEMAP) {
3198 /* Persist any increases of mapsize config */
3199 if (env->me_mapsize > mp->mm_mapsize)
3200 mp->mm_mapsize = env->me_mapsize;
3201 mp->mm_dbs[0] = txn->mt_dbs[0];
3202 mp->mm_dbs[1] = txn->mt_dbs[1];
3203 mp->mm_last_pg = txn->mt_next_pgno - 1;
3204 mp->mm_txnid = txn->mt_txnid;
3205 if (!(env->me_flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3206 unsigned meta_size = env->me_psize;
3207 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3210 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
3211 if (meta_size < env->me_os_psize)
3212 meta_size += meta_size;
3217 if (MDB_MSYNC(ptr, meta_size, rc)) {
3224 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
3225 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
3227 ptr = (char *)&meta;
3228 if (env->me_mapsize > mp->mm_mapsize) {
3229 /* Persist any increases of mapsize config */
3230 meta.mm_mapsize = env->me_mapsize;
3231 off = offsetof(MDB_meta, mm_mapsize);
3233 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
3235 len = sizeof(MDB_meta) - off;
3238 meta.mm_dbs[0] = txn->mt_dbs[0];
3239 meta.mm_dbs[1] = txn->mt_dbs[1];
3240 meta.mm_last_pg = txn->mt_next_pgno - 1;
3241 meta.mm_txnid = txn->mt_txnid;
3244 off += env->me_psize;
3247 /* Write to the SYNC fd */
3248 mfd = env->me_flags & (MDB_NOSYNC|MDB_NOMETASYNC) ?
3249 env->me_fd : env->me_mfd;
3252 memset(&ov, 0, sizeof(ov));
3254 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3258 rc = pwrite(mfd, ptr, len, off);
3261 rc = rc < 0 ? ErrCode() : EIO;
3262 DPUTS("write failed, disk error?");
3263 /* On a failure, the pagecache still contains the new data.
3264 * Write some old data back, to prevent it from being used.
3265 * Use the non-SYNC fd; we know it will fail anyway.
3267 meta.mm_last_pg = metab.mm_last_pg;
3268 meta.mm_txnid = metab.mm_txnid;
3270 memset(&ov, 0, sizeof(ov));
3272 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3274 r2 = pwrite(env->me_fd, ptr, len, off);
3275 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
3278 env->me_flags |= MDB_FATAL_ERROR;
3282 /* Memory ordering issues are irrelevant; since the entire writer
3283 * is wrapped by wmutex, all of these changes will become visible
3284 * after the wmutex is unlocked. Since the DB is multi-version,
3285 * readers will get consistent data regardless of how fresh or
3286 * how stale their view of these values is.
3289 env->me_txns->mti_txnid = txn->mt_txnid;
3294 /** Check both meta pages to see which one is newer.
3295 * @param[in] env the environment handle
3296 * @return meta toggle (0 or 1).
3299 mdb_env_pick_meta(const MDB_env *env)
3301 return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
3305 mdb_env_create(MDB_env **env)
3309 e = calloc(1, sizeof(MDB_env));
3313 e->me_maxreaders = DEFAULT_READERS;
3314 e->me_maxdbs = e->me_numdbs = 2;
3315 e->me_fd = INVALID_HANDLE_VALUE;
3316 e->me_lfd = INVALID_HANDLE_VALUE;
3317 e->me_mfd = INVALID_HANDLE_VALUE;
3318 #ifdef MDB_USE_POSIX_SEM
3319 e->me_rmutex = SEM_FAILED;
3320 e->me_wmutex = SEM_FAILED;
3322 e->me_pid = getpid();
3323 GET_PAGESIZE(e->me_os_psize);
3324 VGMEMP_CREATE(e,0,0);
3330 mdb_env_map(MDB_env *env, void *addr, int newsize)
3333 unsigned int flags = env->me_flags;
3337 LONG sizelo, sizehi;
3338 sizelo = env->me_mapsize & 0xffffffff;
3339 sizehi = env->me_mapsize >> 16 >> 16; /* only needed on Win64 */
3341 /* Windows won't create mappings for zero length files.
3342 * Just allocate the maxsize right now.
3345 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3346 || !SetEndOfFile(env->me_fd)
3347 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3350 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3351 PAGE_READWRITE : PAGE_READONLY,
3352 sizehi, sizelo, NULL);
3355 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3356 FILE_MAP_WRITE : FILE_MAP_READ,
3357 0, 0, env->me_mapsize, addr);
3358 rc = env->me_map ? 0 : ErrCode();
3363 int prot = PROT_READ;
3364 if (flags & MDB_WRITEMAP) {
3366 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3369 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
3371 if (env->me_map == MAP_FAILED) {
3376 if (flags & MDB_NORDAHEAD) {
3377 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3379 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3381 #ifdef POSIX_MADV_RANDOM
3382 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3383 #endif /* POSIX_MADV_RANDOM */
3384 #endif /* MADV_RANDOM */
3388 /* Can happen because the address argument to mmap() is just a
3389 * hint. mmap() can pick another, e.g. if the range is in use.
3390 * The MAP_FIXED flag would prevent that, but then mmap could
3391 * instead unmap existing pages to make room for the new map.
3393 if (addr && env->me_map != addr)
3394 return EBUSY; /* TODO: Make a new MDB_* error code? */
3396 p = (MDB_page *)env->me_map;
3397 env->me_metas[0] = METADATA(p);
3398 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
3404 mdb_env_set_mapsize(MDB_env *env, size_t size)
3406 /* If env is already open, caller is responsible for making
3407 * sure there are no active txns.
3415 size = env->me_metas[mdb_env_pick_meta(env)]->mm_mapsize;
3416 else if (size < env->me_mapsize) {
3417 /* If the configured size is smaller, make sure it's
3418 * still big enough. Silently round up to minimum if not.
3420 size_t minsize = (env->me_metas[mdb_env_pick_meta(env)]->mm_last_pg + 1) * env->me_psize;
3424 munmap(env->me_map, env->me_mapsize);
3425 env->me_mapsize = size;
3426 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
3427 rc = mdb_env_map(env, old, 1);
3431 env->me_mapsize = size;
3433 env->me_maxpg = env->me_mapsize / env->me_psize;
3438 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
3442 env->me_maxdbs = dbs + 2; /* Named databases + main and free DB */
3447 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
3449 if (env->me_map || readers < 1)
3451 env->me_maxreaders = readers;
3456 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
3458 if (!env || !readers)
3460 *readers = env->me_maxreaders;
3464 /** Further setup required for opening an MDB environment
3467 mdb_env_open2(MDB_env *env)
3469 unsigned int flags = env->me_flags;
3470 int i, newenv = 0, rc;
3474 /* See if we should use QueryLimited */
3476 if ((rc & 0xff) > 5)
3477 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
3479 env->me_pidquery = PROCESS_QUERY_INFORMATION;
3482 memset(&meta, 0, sizeof(meta));
3484 if ((i = mdb_env_read_header(env, &meta)) != 0) {
3487 DPUTS("new mdbenv");
3489 env->me_psize = env->me_os_psize;
3490 if (env->me_psize > MAX_PAGESIZE)
3491 env->me_psize = MAX_PAGESIZE;
3493 env->me_psize = meta.mm_psize;
3496 /* Was a mapsize configured? */
3497 if (!env->me_mapsize) {
3498 /* If this is a new environment, take the default,
3499 * else use the size recorded in the existing env.
3501 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
3502 } else if (env->me_mapsize < meta.mm_mapsize) {
3503 /* If the configured size is smaller, make sure it's
3504 * still big enough. Silently round up to minimum if not.
3506 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
3507 if (env->me_mapsize < minsize)
3508 env->me_mapsize = minsize;
3511 rc = mdb_env_map(env, meta.mm_address, newenv);
3516 if (flags & MDB_FIXEDMAP)
3517 meta.mm_address = env->me_map;
3518 i = mdb_env_init_meta(env, &meta);
3519 if (i != MDB_SUCCESS) {
3524 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
3525 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
3527 #if !(MDB_MAXKEYSIZE)
3528 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
3530 env->me_maxpg = env->me_mapsize / env->me_psize;
3534 int toggle = mdb_env_pick_meta(env);
3535 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
3537 DPRINTF(("opened database version %u, pagesize %u",
3538 env->me_metas[0]->mm_version, env->me_psize));
3539 DPRINTF(("using meta page %d", toggle));
3540 DPRINTF(("depth: %u", db->md_depth));
3541 DPRINTF(("entries: %"Z"u", db->md_entries));
3542 DPRINTF(("branch pages: %"Z"u", db->md_branch_pages));
3543 DPRINTF(("leaf pages: %"Z"u", db->md_leaf_pages));
3544 DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
3545 DPRINTF(("root: %"Z"u", db->md_root));
3553 /** Release a reader thread's slot in the reader lock table.
3554 * This function is called automatically when a thread exits.
3555 * @param[in] ptr This points to the slot in the reader lock table.
3558 mdb_env_reader_dest(void *ptr)
3560 MDB_reader *reader = ptr;
3566 /** Junk for arranging thread-specific callbacks on Windows. This is
3567 * necessarily platform and compiler-specific. Windows supports up
3568 * to 1088 keys. Let's assume nobody opens more than 64 environments
3569 * in a single process, for now. They can override this if needed.
3571 #ifndef MAX_TLS_KEYS
3572 #define MAX_TLS_KEYS 64
3574 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
3575 static int mdb_tls_nkeys;
3577 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
3581 case DLL_PROCESS_ATTACH: break;
3582 case DLL_THREAD_ATTACH: break;
3583 case DLL_THREAD_DETACH:
3584 for (i=0; i<mdb_tls_nkeys; i++) {
3585 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
3586 mdb_env_reader_dest(r);
3589 case DLL_PROCESS_DETACH: break;
3594 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3596 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3600 /* Force some symbol references.
3601 * _tls_used forces the linker to create the TLS directory if not already done
3602 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
3604 #pragma comment(linker, "/INCLUDE:_tls_used")
3605 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
3606 #pragma const_seg(".CRT$XLB")
3607 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
3608 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3611 #pragma comment(linker, "/INCLUDE:__tls_used")
3612 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
3613 #pragma data_seg(".CRT$XLB")
3614 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3616 #endif /* WIN 32/64 */
3617 #endif /* !__GNUC__ */
3620 /** Downgrade the exclusive lock on the region back to shared */
3622 mdb_env_share_locks(MDB_env *env, int *excl)
3624 int rc = 0, toggle = mdb_env_pick_meta(env);
3626 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
3631 /* First acquire a shared lock. The Unlock will
3632 * then release the existing exclusive lock.
3634 memset(&ov, 0, sizeof(ov));
3635 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3638 UnlockFile(env->me_lfd, 0, 0, 1, 0);
3644 struct flock lock_info;
3645 /* The shared lock replaces the existing lock */
3646 memset((void *)&lock_info, 0, sizeof(lock_info));
3647 lock_info.l_type = F_RDLCK;
3648 lock_info.l_whence = SEEK_SET;
3649 lock_info.l_start = 0;
3650 lock_info.l_len = 1;
3651 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3652 (rc = ErrCode()) == EINTR) ;
3653 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
3660 /** Try to get exlusive lock, otherwise shared.
3661 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
3664 mdb_env_excl_lock(MDB_env *env, int *excl)
3668 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
3672 memset(&ov, 0, sizeof(ov));
3673 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3680 struct flock lock_info;
3681 memset((void *)&lock_info, 0, sizeof(lock_info));
3682 lock_info.l_type = F_WRLCK;
3683 lock_info.l_whence = SEEK_SET;
3684 lock_info.l_start = 0;
3685 lock_info.l_len = 1;
3686 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3687 (rc = ErrCode()) == EINTR) ;
3691 # ifdef MDB_USE_POSIX_SEM
3692 if (*excl < 0) /* always true when !MDB_USE_POSIX_SEM */
3695 lock_info.l_type = F_RDLCK;
3696 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
3697 (rc = ErrCode()) == EINTR) ;
3707 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
3709 * @(#) $Revision: 5.1 $
3710 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
3711 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
3713 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
3717 * Please do not copyright this code. This code is in the public domain.
3719 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
3720 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
3721 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
3722 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
3723 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
3724 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
3725 * PERFORMANCE OF THIS SOFTWARE.
3728 * chongo <Landon Curt Noll> /\oo/\
3729 * http://www.isthe.com/chongo/
3731 * Share and Enjoy! :-)
3734 typedef unsigned long long mdb_hash_t;
3735 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
3737 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
3738 * @param[in] val value to hash
3739 * @param[in] hval initial value for hash
3740 * @return 64 bit hash
3742 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
3743 * hval arg on the first call.
3746 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
3748 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
3749 unsigned char *end = s + val->mv_size;
3751 * FNV-1a hash each octet of the string
3754 /* xor the bottom with the current octet */
3755 hval ^= (mdb_hash_t)*s++;
3757 /* multiply by the 64 bit FNV magic prime mod 2^64 */
3758 hval += (hval << 1) + (hval << 4) + (hval << 5) +
3759 (hval << 7) + (hval << 8) + (hval << 40);
3761 /* return our new hash value */
3765 /** Hash the string and output the encoded hash.
3766 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
3767 * very short name limits. We don't care about the encoding being reversible,
3768 * we just want to preserve as many bits of the input as possible in a
3769 * small printable string.
3770 * @param[in] str string to hash
3771 * @param[out] encbuf an array of 11 chars to hold the hash
3773 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
3776 mdb_pack85(unsigned long l, char *out)
3780 for (i=0; i<5; i++) {
3781 *out++ = mdb_a85[l % 85];
3787 mdb_hash_enc(MDB_val *val, char *encbuf)
3789 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
3791 mdb_pack85(h, encbuf);
3792 mdb_pack85(h>>32, encbuf+5);
3797 /** Open and/or initialize the lock region for the environment.
3798 * @param[in] env The MDB environment.
3799 * @param[in] lpath The pathname of the file used for the lock region.
3800 * @param[in] mode The Unix permissions for the file, if we create it.
3801 * @param[out] excl Resulting file lock type: -1 none, 0 shared, 1 exclusive
3802 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
3803 * @return 0 on success, non-zero on failure.
3806 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
3809 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
3811 # define MDB_ERRCODE_ROFS EROFS
3812 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
3813 # define MDB_CLOEXEC O_CLOEXEC
3816 # define MDB_CLOEXEC 0
3823 env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
3824 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
3825 FILE_ATTRIBUTE_NORMAL, NULL);
3827 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
3829 if (env->me_lfd == INVALID_HANDLE_VALUE) {
3831 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
3836 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
3837 /* Lose record locks when exec*() */
3838 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
3839 fcntl(env->me_lfd, F_SETFD, fdflags);
3842 if (!(env->me_flags & MDB_NOTLS)) {
3843 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
3846 env->me_flags |= MDB_ENV_TXKEY;
3848 /* Windows TLS callbacks need help finding their TLS info. */
3849 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
3853 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
3857 /* Try to get exclusive lock. If we succeed, then
3858 * nobody is using the lock region and we should initialize it.
3860 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
3863 size = GetFileSize(env->me_lfd, NULL);
3865 size = lseek(env->me_lfd, 0, SEEK_END);
3866 if (size == -1) goto fail_errno;
3868 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
3869 if (size < rsize && *excl > 0) {
3871 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
3872 || !SetEndOfFile(env->me_lfd))
3875 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
3879 size = rsize - sizeof(MDB_txninfo);
3880 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
3885 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
3887 if (!mh) goto fail_errno;
3888 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
3890 if (!env->me_txns) goto fail_errno;
3892 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
3894 if (m == MAP_FAILED) goto fail_errno;
3900 BY_HANDLE_FILE_INFORMATION stbuf;
3909 if (!mdb_sec_inited) {
3910 InitializeSecurityDescriptor(&mdb_null_sd,
3911 SECURITY_DESCRIPTOR_REVISION);
3912 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
3913 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
3914 mdb_all_sa.bInheritHandle = FALSE;
3915 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
3918 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
3919 idbuf.volume = stbuf.dwVolumeSerialNumber;
3920 idbuf.nhigh = stbuf.nFileIndexHigh;
3921 idbuf.nlow = stbuf.nFileIndexLow;
3922 val.mv_data = &idbuf;
3923 val.mv_size = sizeof(idbuf);
3924 mdb_hash_enc(&val, encbuf);
3925 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
3926 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
3927 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
3928 if (!env->me_rmutex) goto fail_errno;
3929 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
3930 if (!env->me_wmutex) goto fail_errno;
3931 #elif defined(MDB_USE_POSIX_SEM)
3940 #if defined(__NetBSD__)
3941 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
3943 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
3944 idbuf.dev = stbuf.st_dev;
3945 idbuf.ino = stbuf.st_ino;
3946 val.mv_data = &idbuf;
3947 val.mv_size = sizeof(idbuf);
3948 mdb_hash_enc(&val, encbuf);
3949 #ifdef MDB_SHORT_SEMNAMES
3950 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
3952 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
3953 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
3954 /* Clean up after a previous run, if needed: Try to
3955 * remove both semaphores before doing anything else.
3957 sem_unlink(env->me_txns->mti_rmname);
3958 sem_unlink(env->me_txns->mti_wmname);
3959 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
3960 O_CREAT|O_EXCL, mode, 1);
3961 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3962 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
3963 O_CREAT|O_EXCL, mode, 1);
3964 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3965 #else /* MDB_USE_POSIX_SEM */
3966 pthread_mutexattr_t mattr;
3968 if ((rc = pthread_mutexattr_init(&mattr))
3969 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
3970 || (rc = pthread_mutex_init(&env->me_txns->mti_mutex, &mattr))
3971 || (rc = pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr)))
3973 pthread_mutexattr_destroy(&mattr);
3974 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
3976 env->me_txns->mti_magic = MDB_MAGIC;
3977 env->me_txns->mti_format = MDB_LOCK_FORMAT;
3978 env->me_txns->mti_txnid = 0;
3979 env->me_txns->mti_numreaders = 0;
3982 if (env->me_txns->mti_magic != MDB_MAGIC) {
3983 DPUTS("lock region has invalid magic");
3987 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
3988 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
3989 env->me_txns->mti_format, MDB_LOCK_FORMAT));
3990 rc = MDB_VERSION_MISMATCH;
3994 if (rc && rc != EACCES && rc != EAGAIN) {
3998 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
3999 if (!env->me_rmutex) goto fail_errno;
4000 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
4001 if (!env->me_wmutex) goto fail_errno;
4002 #elif defined(MDB_USE_POSIX_SEM)
4003 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
4004 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4005 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
4006 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4017 /** The name of the lock file in the DB environment */
4018 #define LOCKNAME "/lock.mdb"
4019 /** The name of the data file in the DB environment */
4020 #define DATANAME "/data.mdb"
4021 /** The suffix of the lock file when no subdir is used */
4022 #define LOCKSUFF "-lock"
4023 /** Only a subset of the @ref mdb_env flags can be changed
4024 * at runtime. Changing other flags requires closing the
4025 * environment and re-opening it with the new flags.
4027 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
4028 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY|MDB_WRITEMAP| \
4029 MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
4031 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
4032 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
4036 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
4038 int oflags, rc, len, excl = -1;
4039 char *lpath, *dpath;
4041 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
4045 if (flags & MDB_NOSUBDIR) {
4046 rc = len + sizeof(LOCKSUFF) + len + 1;
4048 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
4053 if (flags & MDB_NOSUBDIR) {
4054 dpath = lpath + len + sizeof(LOCKSUFF);
4055 sprintf(lpath, "%s" LOCKSUFF, path);
4056 strcpy(dpath, path);
4058 dpath = lpath + len + sizeof(LOCKNAME);
4059 sprintf(lpath, "%s" LOCKNAME, path);
4060 sprintf(dpath, "%s" DATANAME, path);
4064 flags |= env->me_flags;
4065 if (flags & MDB_RDONLY) {
4066 /* silently ignore WRITEMAP when we're only getting read access */
4067 flags &= ~MDB_WRITEMAP;
4069 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
4070 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
4073 env->me_flags = flags |= MDB_ENV_ACTIVE;
4077 env->me_path = strdup(path);
4078 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
4079 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
4080 if (!(env->me_dbxs && env->me_path && env->me_dbflags)) {
4085 /* For RDONLY, get lockfile after we know datafile exists */
4086 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
4087 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4093 if (F_ISSET(flags, MDB_RDONLY)) {
4094 oflags = GENERIC_READ;
4095 len = OPEN_EXISTING;
4097 oflags = GENERIC_READ|GENERIC_WRITE;
4100 mode = FILE_ATTRIBUTE_NORMAL;
4101 env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
4102 NULL, len, mode, NULL);
4104 if (F_ISSET(flags, MDB_RDONLY))
4107 oflags = O_RDWR | O_CREAT;
4109 env->me_fd = open(dpath, oflags, mode);
4111 if (env->me_fd == INVALID_HANDLE_VALUE) {
4116 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
4117 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4122 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
4123 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
4124 env->me_mfd = env->me_fd;
4126 /* Synchronous fd for meta writes. Needed even with
4127 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
4130 len = OPEN_EXISTING;
4131 env->me_mfd = CreateFile(dpath, oflags,
4132 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
4133 mode | FILE_FLAG_WRITE_THROUGH, NULL);
4136 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
4138 if (env->me_mfd == INVALID_HANDLE_VALUE) {
4143 DPRINTF(("opened dbenv %p", (void *) env));
4145 rc = mdb_env_share_locks(env, &excl);
4149 if (!((flags & MDB_RDONLY) ||
4150 (env->me_pbuf = calloc(1, env->me_psize))))
4156 mdb_env_close0(env, excl);
4162 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
4164 mdb_env_close0(MDB_env *env, int excl)
4168 if (!(env->me_flags & MDB_ENV_ACTIVE))
4171 /* Doing this here since me_dbxs may not exist during mdb_env_close */
4172 for (i = env->me_maxdbs; --i > MAIN_DBI; )
4173 free(env->me_dbxs[i].md_name.mv_data);
4176 free(env->me_dbflags);
4179 free(env->me_dirty_list);
4180 mdb_midl_free(env->me_free_pgs);
4182 if (env->me_flags & MDB_ENV_TXKEY) {
4183 pthread_key_delete(env->me_txkey);
4185 /* Delete our key from the global list */
4186 for (i=0; i<mdb_tls_nkeys; i++)
4187 if (mdb_tls_keys[i] == env->me_txkey) {
4188 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
4196 munmap(env->me_map, env->me_mapsize);
4198 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
4199 (void) close(env->me_mfd);
4200 if (env->me_fd != INVALID_HANDLE_VALUE)
4201 (void) close(env->me_fd);
4203 MDB_PID_T pid = env->me_pid;
4204 /* Clearing readers is done in this function because
4205 * me_txkey with its destructor must be disabled first.
4207 for (i = env->me_numreaders; --i >= 0; )
4208 if (env->me_txns->mti_readers[i].mr_pid == pid)
4209 env->me_txns->mti_readers[i].mr_pid = 0;
4211 if (env->me_rmutex) {
4212 CloseHandle(env->me_rmutex);
4213 if (env->me_wmutex) CloseHandle(env->me_wmutex);
4215 /* Windows automatically destroys the mutexes when
4216 * the last handle closes.
4218 #elif defined(MDB_USE_POSIX_SEM)
4219 if (env->me_rmutex != SEM_FAILED) {
4220 sem_close(env->me_rmutex);
4221 if (env->me_wmutex != SEM_FAILED)
4222 sem_close(env->me_wmutex);
4223 /* If we have the filelock: If we are the
4224 * only remaining user, clean up semaphores.
4227 mdb_env_excl_lock(env, &excl);
4229 sem_unlink(env->me_txns->mti_rmname);
4230 sem_unlink(env->me_txns->mti_wmname);
4234 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
4236 if (env->me_lfd != INVALID_HANDLE_VALUE) {
4239 /* Unlock the lockfile. Windows would have unlocked it
4240 * after closing anyway, but not necessarily at once.
4242 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4245 (void) close(env->me_lfd);
4248 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
4252 mdb_env_copyfd(MDB_env *env, HANDLE fd)
4254 MDB_txn *txn = NULL;
4260 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
4264 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
4267 /* Do the lock/unlock of the reader mutex before starting the
4268 * write txn. Otherwise other read txns could block writers.
4270 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
4275 /* We must start the actual read txn after blocking writers */
4276 mdb_txn_reset0(txn, "reset-stage1");
4278 /* Temporarily block writers until we snapshot the meta pages */
4281 rc = mdb_txn_renew0(txn);
4283 UNLOCK_MUTEX_W(env);
4288 wsize = env->me_psize * 2;
4292 DO_WRITE(rc, fd, ptr, w2, len);
4296 } else if (len > 0) {
4302 /* Non-blocking or async handles are not supported */
4308 UNLOCK_MUTEX_W(env);
4313 wsize = txn->mt_next_pgno * env->me_psize - wsize;
4315 if (wsize > MAX_WRITE)
4319 DO_WRITE(rc, fd, ptr, w2, len);
4323 } else if (len > 0) {
4340 mdb_env_copy(MDB_env *env, const char *path)
4344 HANDLE newfd = INVALID_HANDLE_VALUE;
4346 if (env->me_flags & MDB_NOSUBDIR) {
4347 lpath = (char *)path;
4350 len += sizeof(DATANAME);
4351 lpath = malloc(len);
4354 sprintf(lpath, "%s" DATANAME, path);
4357 /* The destination path must exist, but the destination file must not.
4358 * We don't want the OS to cache the writes, since the source data is
4359 * already in the OS cache.
4362 newfd = CreateFile(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
4363 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
4365 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
4367 if (newfd == INVALID_HANDLE_VALUE) {
4373 /* Set O_DIRECT if the file system supports it */
4374 if ((rc = fcntl(newfd, F_GETFL)) != -1)
4375 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
4377 #ifdef F_NOCACHE /* __APPLE__ */
4378 rc = fcntl(newfd, F_NOCACHE, 1);
4385 rc = mdb_env_copyfd(env, newfd);
4388 if (!(env->me_flags & MDB_NOSUBDIR))
4390 if (newfd != INVALID_HANDLE_VALUE)
4391 if (close(newfd) < 0 && rc == MDB_SUCCESS)
4398 mdb_env_close(MDB_env *env)
4405 VGMEMP_DESTROY(env);
4406 while ((dp = env->me_dpages) != NULL) {
4407 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
4408 env->me_dpages = dp->mp_next;
4412 mdb_env_close0(env, 0);
4416 /** Compare two items pointing at aligned size_t's */
4418 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
4420 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
4421 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
4424 /** Compare two items pointing at aligned unsigned int's */
4426 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
4428 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
4429 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
4432 /** Compare two items pointing at unsigned ints of unknown alignment.
4433 * Nodes and keys are guaranteed to be 2-byte aligned.
4436 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
4438 #if BYTE_ORDER == LITTLE_ENDIAN
4439 unsigned short *u, *c;
4442 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4443 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
4446 } while(!x && u > (unsigned short *)a->mv_data);
4449 return memcmp(a->mv_data, b->mv_data, a->mv_size);
4453 /** Compare two items lexically */
4455 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
4462 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4468 diff = memcmp(a->mv_data, b->mv_data, len);
4469 return diff ? diff : len_diff<0 ? -1 : len_diff;
4472 /** Compare two items in reverse byte order */
4474 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
4476 const unsigned char *p1, *p2, *p1_lim;
4480 p1_lim = (const unsigned char *)a->mv_data;
4481 p1 = (const unsigned char *)a->mv_data + a->mv_size;
4482 p2 = (const unsigned char *)b->mv_data + b->mv_size;
4484 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4490 while (p1 > p1_lim) {
4491 diff = *--p1 - *--p2;
4495 return len_diff<0 ? -1 : len_diff;
4498 /** Search for key within a page, using binary search.
4499 * Returns the smallest entry larger or equal to the key.
4500 * If exactp is non-null, stores whether the found entry was an exact match
4501 * in *exactp (1 or 0).
4502 * Updates the cursor index with the index of the found entry.
4503 * If no entry larger or equal to the key is found, returns NULL.
4506 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
4508 unsigned int i = 0, nkeys;
4511 MDB_page *mp = mc->mc_pg[mc->mc_top];
4512 MDB_node *node = NULL;
4517 nkeys = NUMKEYS(mp);
4519 DPRINTF(("searching %u keys in %s %spage %"Z"u",
4520 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
4523 low = IS_LEAF(mp) ? 0 : 1;
4525 cmp = mc->mc_dbx->md_cmp;
4527 /* Branch pages have no data, so if using integer keys,
4528 * alignment is guaranteed. Use faster mdb_cmp_int.
4530 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
4531 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
4538 nodekey.mv_size = mc->mc_db->md_pad;
4539 node = NODEPTR(mp, 0); /* fake */
4540 while (low <= high) {
4541 i = (low + high) >> 1;
4542 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
4543 rc = cmp(key, &nodekey);
4544 DPRINTF(("found leaf index %u [%s], rc = %i",
4545 i, DKEY(&nodekey), rc));
4554 while (low <= high) {
4555 i = (low + high) >> 1;
4557 node = NODEPTR(mp, i);
4558 nodekey.mv_size = NODEKSZ(node);
4559 nodekey.mv_data = NODEKEY(node);
4561 rc = cmp(key, &nodekey);
4564 DPRINTF(("found leaf index %u [%s], rc = %i",
4565 i, DKEY(&nodekey), rc));
4567 DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
4568 i, DKEY(&nodekey), NODEPGNO(node), rc));
4579 if (rc > 0) { /* Found entry is less than the key. */
4580 i++; /* Skip to get the smallest entry larger than key. */
4582 node = NODEPTR(mp, i);
4585 *exactp = (rc == 0 && nkeys > 0);
4586 /* store the key index */
4587 mc->mc_ki[mc->mc_top] = i;
4589 /* There is no entry larger or equal to the key. */
4592 /* nodeptr is fake for LEAF2 */
4598 mdb_cursor_adjust(MDB_cursor *mc, func)
4602 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4603 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
4610 /** Pop a page off the top of the cursor's stack. */
4612 mdb_cursor_pop(MDB_cursor *mc)
4616 MDB_page *top = mc->mc_pg[mc->mc_top];
4622 DPRINTF(("popped page %"Z"u off db %d cursor %p", top->mp_pgno,
4623 DDBI(mc), (void *) mc));
4627 /** Push a page onto the top of the cursor's stack. */
4629 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
4631 DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
4632 DDBI(mc), (void *) mc));
4634 if (mc->mc_snum >= CURSOR_STACK) {
4635 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4636 return MDB_CURSOR_FULL;
4639 mc->mc_top = mc->mc_snum++;
4640 mc->mc_pg[mc->mc_top] = mp;
4641 mc->mc_ki[mc->mc_top] = 0;
4646 /** Find the address of the page corresponding to a given page number.
4647 * @param[in] txn the transaction for this access.
4648 * @param[in] pgno the page number for the page to retrieve.
4649 * @param[out] ret address of a pointer where the page's address will be stored.
4650 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
4651 * @return 0 on success, non-zero on failure.
4654 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
4656 MDB_env *env = txn->mt_env;
4660 if (!((txn->mt_flags & MDB_TXN_RDONLY) | (env->me_flags & MDB_WRITEMAP))) {
4664 MDB_ID2L dl = tx2->mt_u.dirty_list;
4666 /* Spilled pages were dirtied in this txn and flushed
4667 * because the dirty list got full. Bring this page
4668 * back in from the map (but don't unspill it here,
4669 * leave that unless page_touch happens again).
4671 if (tx2->mt_spill_pgs) {
4672 MDB_ID pn = pgno << 1;
4673 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
4674 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
4675 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
4680 unsigned x = mdb_mid2l_search(dl, pgno);
4681 if (x <= dl[0].mid && dl[x].mid == pgno) {
4687 } while ((tx2 = tx2->mt_parent) != NULL);
4690 if (pgno < txn->mt_next_pgno) {
4692 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
4694 DPRINTF(("page %"Z"u not found", pgno));
4695 txn->mt_flags |= MDB_TXN_ERROR;
4696 return MDB_PAGE_NOTFOUND;
4706 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
4707 * The cursor is at the root page, set up the rest of it.
4710 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
4712 MDB_page *mp = mc->mc_pg[mc->mc_top];
4716 while (IS_BRANCH(mp)) {
4720 DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
4721 assert(NUMKEYS(mp) > 1);
4722 DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
4724 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
4726 if (flags & MDB_PS_LAST)
4727 i = NUMKEYS(mp) - 1;
4730 node = mdb_node_search(mc, key, &exact);
4732 i = NUMKEYS(mp) - 1;
4734 i = mc->mc_ki[mc->mc_top];
4740 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
4743 assert(i < NUMKEYS(mp));
4744 node = NODEPTR(mp, i);
4746 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4749 mc->mc_ki[mc->mc_top] = i;
4750 if ((rc = mdb_cursor_push(mc, mp)))
4753 if (flags & MDB_PS_MODIFY) {
4754 if ((rc = mdb_page_touch(mc)) != 0)
4756 mp = mc->mc_pg[mc->mc_top];
4761 DPRINTF(("internal error, index points to a %02X page!?",
4763 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4764 return MDB_CORRUPTED;
4767 DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
4768 key ? DKEY(key) : "null"));
4769 mc->mc_flags |= C_INITIALIZED;
4770 mc->mc_flags &= ~C_EOF;
4775 /** Search for the lowest key under the current branch page.
4776 * This just bypasses a NUMKEYS check in the current page
4777 * before calling mdb_page_search_root(), because the callers
4778 * are all in situations where the current page is known to
4782 mdb_page_search_lowest(MDB_cursor *mc)
4784 MDB_page *mp = mc->mc_pg[mc->mc_top];
4785 MDB_node *node = NODEPTR(mp, 0);
4788 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4791 mc->mc_ki[mc->mc_top] = 0;
4792 if ((rc = mdb_cursor_push(mc, mp)))
4794 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
4797 /** Search for the page a given key should be in.
4798 * Push it and its parent pages on the cursor stack.
4799 * @param[in,out] mc the cursor for this operation.
4800 * @param[in] key the key to search for, or NULL for first/last page.
4801 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
4802 * are touched (updated with new page numbers).
4803 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
4804 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
4805 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
4806 * @return 0 on success, non-zero on failure.
4809 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
4814 /* Make sure the txn is still viable, then find the root from
4815 * the txn's db table and set it as the root of the cursor's stack.
4817 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
4818 DPUTS("transaction has failed, must abort");
4821 /* Make sure we're using an up-to-date root */
4822 if (*mc->mc_dbflag & DB_STALE) {
4824 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
4825 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
4832 MDB_node *leaf = mdb_node_search(&mc2,
4833 &mc->mc_dbx->md_name, &exact);
4835 return MDB_NOTFOUND;
4836 rc = mdb_node_read(mc->mc_txn, leaf, &data);
4839 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
4841 /* The txn may not know this DBI, or another process may
4842 * have dropped and recreated the DB with other flags.
4844 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
4845 return MDB_INCOMPATIBLE;
4846 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
4848 *mc->mc_dbflag &= ~DB_STALE;
4850 root = mc->mc_db->md_root;
4852 if (root == P_INVALID) { /* Tree is empty. */
4853 DPUTS("tree is empty");
4854 return MDB_NOTFOUND;
4859 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
4860 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0], NULL)) != 0)
4866 DPRINTF(("db %d root page %"Z"u has flags 0x%X",
4867 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
4869 if (flags & MDB_PS_MODIFY) {
4870 if ((rc = mdb_page_touch(mc)))
4874 if (flags & MDB_PS_ROOTONLY)
4877 return mdb_page_search_root(mc, key, flags);
4881 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
4883 MDB_txn *txn = mc->mc_txn;
4884 pgno_t pg = mp->mp_pgno;
4885 unsigned x = 0, ovpages = mp->mp_pages;
4886 MDB_env *env = txn->mt_env;
4887 MDB_IDL sl = txn->mt_spill_pgs;
4888 MDB_ID pn = pg << 1;
4891 DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
4892 /* If the page is dirty or on the spill list we just acquired it,
4893 * so we should give it back to our current free list, if any.
4894 * Otherwise put it onto the list of pages we freed in this txn.
4896 * Won't create me_pghead: me_pglast must be inited along with it.
4897 * Unsupported in nested txns: They would need to hide the page
4898 * range in ancestor txns' dirty and spilled lists.
4900 if (env->me_pghead &&
4902 ((mp->mp_flags & P_DIRTY) ||
4903 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
4907 MDB_ID2 *dl, ix, iy;
4908 rc = mdb_midl_need(&env->me_pghead, ovpages);
4911 if (!(mp->mp_flags & P_DIRTY)) {
4912 /* This page is no longer spilled */
4919 /* Remove from dirty list */
4920 dl = txn->mt_u.dirty_list;
4922 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
4930 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
4931 txn->mt_flags |= MDB_TXN_ERROR;
4932 return MDB_CORRUPTED;
4935 if (!(env->me_flags & MDB_WRITEMAP))
4936 mdb_dpage_free(env, mp);
4938 /* Insert in me_pghead */
4939 mop = env->me_pghead;
4940 j = mop[0] + ovpages;
4941 for (i = mop[0]; i && mop[i] < pg; i--)
4947 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
4951 mc->mc_db->md_overflow_pages -= ovpages;
4955 /** Return the data associated with a given node.
4956 * @param[in] txn The transaction for this operation.
4957 * @param[in] leaf The node being read.
4958 * @param[out] data Updated to point to the node's data.
4959 * @return 0 on success, non-zero on failure.
4962 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
4964 MDB_page *omp; /* overflow page */
4968 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
4969 data->mv_size = NODEDSZ(leaf);
4970 data->mv_data = NODEDATA(leaf);
4974 /* Read overflow data.
4976 data->mv_size = NODEDSZ(leaf);
4977 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
4978 if ((rc = mdb_page_get(txn, pgno, &omp, NULL)) != 0) {
4979 DPRINTF(("read overflow page %"Z"u failed", pgno));
4982 data->mv_data = METADATA(omp);
4988 mdb_get(MDB_txn *txn, MDB_dbi dbi,
4989 MDB_val *key, MDB_val *data)
4996 if (key == NULL || data == NULL)
4999 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
5001 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
5004 if (txn->mt_flags & MDB_TXN_ERROR)
5007 mdb_cursor_init(&mc, txn, dbi, &mx);
5008 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
5011 /** Find a sibling for a page.
5012 * Replaces the page at the top of the cursor's stack with the
5013 * specified sibling, if one exists.
5014 * @param[in] mc The cursor for this operation.
5015 * @param[in] move_right Non-zero if the right sibling is requested,
5016 * otherwise the left sibling.
5017 * @return 0 on success, non-zero on failure.
5020 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
5026 if (mc->mc_snum < 2) {
5027 return MDB_NOTFOUND; /* root has no siblings */
5031 DPRINTF(("parent page is page %"Z"u, index %u",
5032 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
5034 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
5035 : (mc->mc_ki[mc->mc_top] == 0)) {
5036 DPRINTF(("no more keys left, moving to %s sibling",
5037 move_right ? "right" : "left"));
5038 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
5039 /* undo cursor_pop before returning */
5046 mc->mc_ki[mc->mc_top]++;
5048 mc->mc_ki[mc->mc_top]--;
5049 DPRINTF(("just moving to %s index key %u",
5050 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
5052 assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
5054 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5055 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL)) != 0) {
5056 /* mc will be inconsistent if caller does mc_snum++ as above */
5057 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
5061 mdb_cursor_push(mc, mp);
5063 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
5068 /** Move the cursor to the next data item. */
5070 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5076 if (mc->mc_flags & C_EOF) {
5077 return MDB_NOTFOUND;
5080 assert(mc->mc_flags & C_INITIALIZED);
5082 mp = mc->mc_pg[mc->mc_top];
5084 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5085 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5086 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5087 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
5088 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
5089 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
5090 if (rc == MDB_SUCCESS)
5091 MDB_GET_KEY(leaf, key);
5096 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5097 if (op == MDB_NEXT_DUP)
5098 return MDB_NOTFOUND;
5102 DPRINTF(("cursor_next: top page is %"Z"u in cursor %p",
5103 mdb_dbg_pgno(mp), (void *) mc));
5104 if (mc->mc_flags & C_DEL)
5107 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
5108 DPUTS("=====> move to next sibling page");
5109 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5110 mc->mc_flags |= C_EOF;
5113 mp = mc->mc_pg[mc->mc_top];
5114 DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5116 mc->mc_ki[mc->mc_top]++;
5119 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5120 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5123 key->mv_size = mc->mc_db->md_pad;
5124 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5128 assert(IS_LEAF(mp));
5129 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5131 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5132 mdb_xcursor_init1(mc, leaf);
5135 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5138 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5139 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5140 if (rc != MDB_SUCCESS)
5145 MDB_GET_KEY(leaf, key);
5149 /** Move the cursor to the previous data item. */
5151 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5157 assert(mc->mc_flags & C_INITIALIZED);
5159 mp = mc->mc_pg[mc->mc_top];
5161 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5162 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5163 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5164 if (op == MDB_PREV || op == MDB_PREV_DUP) {
5165 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
5166 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
5167 if (rc == MDB_SUCCESS)
5168 MDB_GET_KEY(leaf, key);
5172 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5173 if (op == MDB_PREV_DUP)
5174 return MDB_NOTFOUND;
5179 DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p",
5180 mdb_dbg_pgno(mp), (void *) mc));
5182 if (mc->mc_ki[mc->mc_top] == 0) {
5183 DPUTS("=====> move to prev sibling page");
5184 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
5187 mp = mc->mc_pg[mc->mc_top];
5188 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
5189 DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5191 mc->mc_ki[mc->mc_top]--;
5193 mc->mc_flags &= ~C_EOF;
5195 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5196 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5199 key->mv_size = mc->mc_db->md_pad;
5200 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5204 assert(IS_LEAF(mp));
5205 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5207 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5208 mdb_xcursor_init1(mc, leaf);
5211 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5214 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5215 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5216 if (rc != MDB_SUCCESS)
5221 MDB_GET_KEY(leaf, key);
5225 /** Set the cursor on a specific data item. */
5227 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5228 MDB_cursor_op op, int *exactp)
5232 MDB_node *leaf = NULL;
5237 if (key->mv_size == 0)
5238 return MDB_BAD_VALSIZE;
5241 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5243 /* See if we're already on the right page */
5244 if (mc->mc_flags & C_INITIALIZED) {
5247 mp = mc->mc_pg[mc->mc_top];
5249 mc->mc_ki[mc->mc_top] = 0;
5250 return MDB_NOTFOUND;
5252 if (mp->mp_flags & P_LEAF2) {
5253 nodekey.mv_size = mc->mc_db->md_pad;
5254 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
5256 leaf = NODEPTR(mp, 0);
5257 MDB_GET_KEY2(leaf, nodekey);
5259 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5261 /* Probably happens rarely, but first node on the page
5262 * was the one we wanted.
5264 mc->mc_ki[mc->mc_top] = 0;
5271 unsigned int nkeys = NUMKEYS(mp);
5273 if (mp->mp_flags & P_LEAF2) {
5274 nodekey.mv_data = LEAF2KEY(mp,
5275 nkeys-1, nodekey.mv_size);
5277 leaf = NODEPTR(mp, nkeys-1);
5278 MDB_GET_KEY2(leaf, nodekey);
5280 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5282 /* last node was the one we wanted */
5283 mc->mc_ki[mc->mc_top] = nkeys-1;
5289 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
5290 /* This is definitely the right page, skip search_page */
5291 if (mp->mp_flags & P_LEAF2) {
5292 nodekey.mv_data = LEAF2KEY(mp,
5293 mc->mc_ki[mc->mc_top], nodekey.mv_size);
5295 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5296 MDB_GET_KEY2(leaf, nodekey);
5298 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5300 /* current node was the one we wanted */
5310 /* If any parents have right-sibs, search.
5311 * Otherwise, there's nothing further.
5313 for (i=0; i<mc->mc_top; i++)
5315 NUMKEYS(mc->mc_pg[i])-1)
5317 if (i == mc->mc_top) {
5318 /* There are no other pages */
5319 mc->mc_ki[mc->mc_top] = nkeys;
5320 return MDB_NOTFOUND;
5324 /* There are no other pages */
5325 mc->mc_ki[mc->mc_top] = 0;
5326 if (op == MDB_SET_RANGE) {
5330 return MDB_NOTFOUND;
5334 rc = mdb_page_search(mc, key, 0);
5335 if (rc != MDB_SUCCESS)
5338 mp = mc->mc_pg[mc->mc_top];
5339 assert(IS_LEAF(mp));
5342 leaf = mdb_node_search(mc, key, exactp);
5343 if (exactp != NULL && !*exactp) {
5344 /* MDB_SET specified and not an exact match. */
5345 return MDB_NOTFOUND;
5349 DPUTS("===> inexact leaf not found, goto sibling");
5350 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
5351 return rc; /* no entries matched */
5352 mp = mc->mc_pg[mc->mc_top];
5353 assert(IS_LEAF(mp));
5354 leaf = NODEPTR(mp, 0);
5358 mc->mc_flags |= C_INITIALIZED;
5359 mc->mc_flags &= ~C_EOF;
5362 key->mv_size = mc->mc_db->md_pad;
5363 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5367 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5368 mdb_xcursor_init1(mc, leaf);
5371 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5372 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
5373 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5376 if (op == MDB_GET_BOTH) {
5382 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
5383 if (rc != MDB_SUCCESS)
5386 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
5388 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
5390 rc = mc->mc_dbx->md_dcmp(data, &d2);
5392 if (op == MDB_GET_BOTH || rc > 0)
5393 return MDB_NOTFOUND;
5400 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5401 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5406 /* The key already matches in all other cases */
5407 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
5408 MDB_GET_KEY(leaf, key);
5409 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
5414 /** Move the cursor to the first item in the database. */
5416 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5422 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5424 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5425 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
5426 if (rc != MDB_SUCCESS)
5429 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
5431 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
5432 mc->mc_flags |= C_INITIALIZED;
5433 mc->mc_flags &= ~C_EOF;
5435 mc->mc_ki[mc->mc_top] = 0;
5437 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5438 key->mv_size = mc->mc_db->md_pad;
5439 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
5444 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5445 mdb_xcursor_init1(mc, leaf);
5446 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5450 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5454 MDB_GET_KEY(leaf, key);
5458 /** Move the cursor to the last item in the database. */
5460 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5466 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5468 if (!(mc->mc_flags & C_EOF)) {
5470 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5471 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
5472 if (rc != MDB_SUCCESS)
5475 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
5478 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
5479 mc->mc_flags |= C_INITIALIZED|C_EOF;
5480 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5482 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5483 key->mv_size = mc->mc_db->md_pad;
5484 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
5489 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5490 mdb_xcursor_init1(mc, leaf);
5491 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5495 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5500 MDB_GET_KEY(leaf, key);
5505 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5510 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
5515 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
5519 case MDB_GET_CURRENT:
5520 if (!(mc->mc_flags & C_INITIALIZED)) {
5523 MDB_page *mp = mc->mc_pg[mc->mc_top];
5524 int nkeys = NUMKEYS(mp);
5525 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
5526 mc->mc_ki[mc->mc_top] = nkeys;
5532 key->mv_size = mc->mc_db->md_pad;
5533 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5535 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5536 MDB_GET_KEY(leaf, key);
5538 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5539 if (mc->mc_flags & C_DEL)
5540 mdb_xcursor_init1(mc, leaf);
5541 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
5543 rc = mdb_node_read(mc->mc_txn, leaf, data);
5550 case MDB_GET_BOTH_RANGE:
5555 if (mc->mc_xcursor == NULL) {
5556 rc = MDB_INCOMPATIBLE;
5566 rc = mdb_cursor_set(mc, key, data, op,
5567 op == MDB_SET_RANGE ? NULL : &exact);
5570 case MDB_GET_MULTIPLE:
5571 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5575 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5576 rc = MDB_INCOMPATIBLE;
5580 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
5581 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
5584 case MDB_NEXT_MULTIPLE:
5589 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5590 rc = MDB_INCOMPATIBLE;
5593 if (!(mc->mc_flags & C_INITIALIZED))
5594 rc = mdb_cursor_first(mc, key, data);
5596 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
5597 if (rc == MDB_SUCCESS) {
5598 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
5601 mx = &mc->mc_xcursor->mx_cursor;
5602 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
5604 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
5605 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
5613 case MDB_NEXT_NODUP:
5614 if (!(mc->mc_flags & C_INITIALIZED))
5615 rc = mdb_cursor_first(mc, key, data);
5617 rc = mdb_cursor_next(mc, key, data, op);
5621 case MDB_PREV_NODUP:
5622 if (!(mc->mc_flags & C_INITIALIZED)) {
5623 rc = mdb_cursor_last(mc, key, data);
5626 mc->mc_flags |= C_INITIALIZED;
5627 mc->mc_ki[mc->mc_top]++;
5629 rc = mdb_cursor_prev(mc, key, data, op);
5632 rc = mdb_cursor_first(mc, key, data);
5635 mfunc = mdb_cursor_first;
5637 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5641 if (mc->mc_xcursor == NULL) {
5642 rc = MDB_INCOMPATIBLE;
5645 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
5649 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
5652 rc = mdb_cursor_last(mc, key, data);
5655 mfunc = mdb_cursor_last;
5658 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
5663 if (mc->mc_flags & C_DEL)
5664 mc->mc_flags ^= C_DEL;
5669 /** Touch all the pages in the cursor stack. Set mc_top.
5670 * Makes sure all the pages are writable, before attempting a write operation.
5671 * @param[in] mc The cursor to operate on.
5674 mdb_cursor_touch(MDB_cursor *mc)
5676 int rc = MDB_SUCCESS;
5678 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
5681 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
5682 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
5685 *mc->mc_dbflag |= DB_DIRTY;
5690 rc = mdb_page_touch(mc);
5691 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
5692 mc->mc_top = mc->mc_snum-1;
5697 /** Do not spill pages to disk if txn is getting full, may fail instead */
5698 #define MDB_NOSPILL 0x8000
5701 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5704 enum { MDB_NO_ROOT = MDB_LAST_ERRCODE+10 }; /* internal code */
5705 MDB_env *env = mc->mc_txn->mt_env;
5706 MDB_node *leaf = NULL;
5709 MDB_val xdata, *rdata, dkey, olddata;
5711 int do_sub = 0, insert;
5712 unsigned int mcount = 0, dcount = 0, nospill;
5715 unsigned int nflags;
5718 /* Check this first so counter will always be zero on any
5721 if (flags & MDB_MULTIPLE) {
5722 dcount = data[1].mv_size;
5723 data[1].mv_size = 0;
5724 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
5725 return MDB_INCOMPATIBLE;
5728 nospill = flags & MDB_NOSPILL;
5729 flags &= ~MDB_NOSPILL;
5731 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
5732 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
5734 if (flags != MDB_CURRENT && key->mv_size-1 >= ENV_MAXKEY(env))
5735 return MDB_BAD_VALSIZE;
5737 #if SIZE_MAX > MAXDATASIZE
5738 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
5739 return MDB_BAD_VALSIZE;
5741 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
5742 return MDB_BAD_VALSIZE;
5745 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
5746 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
5750 if (flags == MDB_CURRENT) {
5751 if (!(mc->mc_flags & C_INITIALIZED))
5754 } else if (mc->mc_db->md_root == P_INVALID) {
5755 /* new database, cursor has nothing to point to */
5758 mc->mc_flags &= ~C_INITIALIZED;
5763 if (flags & MDB_APPEND) {
5765 rc = mdb_cursor_last(mc, &k2, &d2);
5767 rc = mc->mc_dbx->md_cmp(key, &k2);
5770 mc->mc_ki[mc->mc_top]++;
5772 /* new key is <= last key */
5777 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
5779 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
5780 DPRINTF(("duplicate key [%s]", DKEY(key)));
5782 return MDB_KEYEXIST;
5784 if (rc && rc != MDB_NOTFOUND)
5788 if (mc->mc_flags & C_DEL)
5789 mc->mc_flags ^= C_DEL;
5791 /* Cursor is positioned, check for room in the dirty list */
5793 if (flags & MDB_MULTIPLE) {
5795 xdata.mv_size = data->mv_size * dcount;
5799 if ((rc2 = mdb_page_spill(mc, key, rdata)))
5803 if (rc == MDB_NO_ROOT) {
5805 /* new database, write a root leaf page */
5806 DPUTS("allocating new root leaf page");
5807 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
5810 mdb_cursor_push(mc, np);
5811 mc->mc_db->md_root = np->mp_pgno;
5812 mc->mc_db->md_depth++;
5813 *mc->mc_dbflag |= DB_DIRTY;
5814 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
5816 np->mp_flags |= P_LEAF2;
5817 mc->mc_flags |= C_INITIALIZED;
5819 /* make sure all cursor pages are writable */
5820 rc2 = mdb_cursor_touch(mc);
5827 /* The key does not exist */
5828 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
5829 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
5830 LEAFSIZE(key, data) > env->me_nodemax)
5832 /* Too big for a node, insert in sub-DB */
5833 fp_flags = P_LEAF|P_DIRTY;
5835 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
5836 fp->mp_lower = fp->mp_upper = olddata.mv_size = PAGEHDRSZ;
5840 /* there's only a key anyway, so this is a no-op */
5841 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5842 unsigned int ksize = mc->mc_db->md_pad;
5843 if (key->mv_size != ksize)
5844 return MDB_BAD_VALSIZE;
5845 if (flags == MDB_CURRENT) {
5846 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
5847 memcpy(ptr, key->mv_data, ksize);
5853 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5854 olddata.mv_size = NODEDSZ(leaf);
5855 olddata.mv_data = NODEDATA(leaf);
5858 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
5859 /* Prepare (sub-)page/sub-DB to accept the new item,
5860 * if needed. fp: old sub-page or a header faking
5861 * it. mp: new (sub-)page. offset: growth in page
5862 * size. xdata: node data with new page or DB.
5864 ssize_t i, offset = 0;
5865 mp = fp = xdata.mv_data = env->me_pbuf;
5866 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
5868 /* Was a single item before, must convert now */
5869 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5870 /* Just overwrite the current item */
5871 if (flags == MDB_CURRENT)
5874 #if UINT_MAX < SIZE_MAX
5875 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
5876 #ifdef MISALIGNED_OK
5877 mc->mc_dbx->md_dcmp = mdb_cmp_long;
5879 mc->mc_dbx->md_dcmp = mdb_cmp_cint;
5882 /* if data matches, skip it */
5883 if (!mc->mc_dbx->md_dcmp(data, &olddata)) {
5884 if (flags & MDB_NODUPDATA)
5886 else if (flags & MDB_MULTIPLE)
5893 /* Back up original data item */
5894 dkey.mv_size = olddata.mv_size;
5895 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
5897 /* Make sub-page header for the dup items, with dummy body */
5898 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
5899 fp->mp_lower = PAGEHDRSZ;
5900 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
5901 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5902 fp->mp_flags |= P_LEAF2;
5903 fp->mp_pad = data->mv_size;
5904 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
5906 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
5907 (dkey.mv_size & 1) + (data->mv_size & 1);
5909 fp->mp_upper = xdata.mv_size;
5910 olddata.mv_size = fp->mp_upper; /* pretend olddata is fp */
5911 } else if (leaf->mn_flags & F_SUBDATA) {
5912 /* Data is on sub-DB, just store it */
5913 flags |= F_DUPDATA|F_SUBDATA;
5916 /* Data is on sub-page */
5917 fp = olddata.mv_data;
5920 i = -(ssize_t)SIZELEFT(fp);
5921 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5922 offset = i += (ssize_t) EVEN(
5923 sizeof(indx_t) + NODESIZE + data->mv_size);
5925 i += offset = fp->mp_pad;
5926 offset *= 4; /* space for 4 more */
5930 /* FALLTHRU: Sub-page is big enough */
5932 fp->mp_flags |= P_DIRTY;
5933 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
5934 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
5938 xdata.mv_size = olddata.mv_size + offset;
5941 fp_flags = fp->mp_flags;
5942 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
5943 /* Too big for a sub-page, convert to sub-DB */
5944 fp_flags &= ~P_SUBP;
5946 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5947 fp_flags |= P_LEAF2;
5948 dummy.md_pad = fp->mp_pad;
5949 dummy.md_flags = MDB_DUPFIXED;
5950 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
5951 dummy.md_flags |= MDB_INTEGERKEY;
5957 dummy.md_branch_pages = 0;
5958 dummy.md_leaf_pages = 1;
5959 dummy.md_overflow_pages = 0;
5960 dummy.md_entries = NUMKEYS(fp);
5961 xdata.mv_size = sizeof(MDB_db);
5962 xdata.mv_data = &dummy;
5963 if ((rc = mdb_page_alloc(mc, 1, &mp)))
5965 offset = env->me_psize - olddata.mv_size;
5966 flags |= F_DUPDATA|F_SUBDATA;
5967 dummy.md_root = mp->mp_pgno;
5970 mp->mp_flags = fp_flags | P_DIRTY;
5971 mp->mp_pad = fp->mp_pad;
5972 mp->mp_lower = fp->mp_lower;
5973 mp->mp_upper = fp->mp_upper + offset;
5974 if (fp_flags & P_LEAF2) {
5975 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
5977 memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper,
5978 olddata.mv_size - fp->mp_upper);
5979 for (i = NUMKEYS(fp); --i >= 0; )
5980 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
5988 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5992 /* overflow page overwrites need special handling */
5993 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5996 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
5998 memcpy(&pg, olddata.mv_data, sizeof(pg));
5999 if ((rc2 = mdb_page_get(mc->mc_txn, pg, &omp, &level)) != 0)
6001 ovpages = omp->mp_pages;
6003 /* Is the ov page large enough? */
6004 if (ovpages >= dpages) {
6005 if (!(omp->mp_flags & P_DIRTY) &&
6006 (level || (env->me_flags & MDB_WRITEMAP)))
6008 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
6011 level = 0; /* dirty in this txn or clean */
6014 if (omp->mp_flags & P_DIRTY) {
6015 /* yes, overwrite it. Note in this case we don't
6016 * bother to try shrinking the page if the new data
6017 * is smaller than the overflow threshold.
6020 /* It is writable only in a parent txn */
6021 size_t sz = (size_t) env->me_psize * ovpages, off;
6022 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
6028 mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
6029 if (!(flags & MDB_RESERVE)) {
6030 /* Copy end of page, adjusting alignment so
6031 * compiler may copy words instead of bytes.
6033 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
6034 memcpy((size_t *)((char *)np + off),
6035 (size_t *)((char *)omp + off), sz - off);
6038 memcpy(np, omp, sz); /* Copy beginning of page */
6041 SETDSZ(leaf, data->mv_size);
6042 if (F_ISSET(flags, MDB_RESERVE))
6043 data->mv_data = METADATA(omp);
6045 memcpy(METADATA(omp), data->mv_data, data->mv_size);
6049 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
6051 } else if (data->mv_size == olddata.mv_size) {
6052 /* same size, just replace it. Note that we could
6053 * also reuse this node if the new data is smaller,
6054 * but instead we opt to shrink the node in that case.
6056 if (F_ISSET(flags, MDB_RESERVE))
6057 data->mv_data = olddata.mv_data;
6058 else if (data->mv_size)
6059 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
6061 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
6064 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
6065 mc->mc_db->md_entries--;
6071 nflags = flags & NODE_ADD_FLAGS;
6072 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
6073 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
6074 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
6075 nflags &= ~MDB_APPEND;
6077 nflags |= MDB_SPLIT_REPLACE;
6078 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
6080 /* There is room already in this leaf page. */
6081 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
6082 if (rc == 0 && !do_sub && insert) {
6083 /* Adjust other cursors pointing to mp */
6084 MDB_cursor *m2, *m3;
6085 MDB_dbi dbi = mc->mc_dbi;
6086 unsigned i = mc->mc_top;
6087 MDB_page *mp = mc->mc_pg[i];
6089 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6090 if (mc->mc_flags & C_SUB)
6091 m3 = &m2->mc_xcursor->mx_cursor;
6094 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
6095 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
6102 if (rc != MDB_SUCCESS)
6103 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6105 /* Now store the actual data in the child DB. Note that we're
6106 * storing the user data in the keys field, so there are strict
6107 * size limits on dupdata. The actual data fields of the child
6108 * DB are all zero size.
6115 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6116 if (flags & MDB_CURRENT) {
6117 xflags = MDB_CURRENT|MDB_NOSPILL;
6119 mdb_xcursor_init1(mc, leaf);
6120 xflags = (flags & MDB_NODUPDATA) ?
6121 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
6123 /* converted, write the original data first */
6125 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
6129 /* Adjust other cursors pointing to mp */
6131 unsigned i = mc->mc_top;
6132 MDB_page *mp = mc->mc_pg[i];
6134 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6135 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6136 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6137 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
6138 mdb_xcursor_init1(m2, leaf);
6142 /* we've done our job */
6145 if (flags & MDB_APPENDDUP)
6146 xflags |= MDB_APPEND;
6147 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
6148 if (flags & F_SUBDATA) {
6149 void *db = NODEDATA(leaf);
6150 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6153 /* sub-writes might have failed so check rc again.
6154 * Don't increment count if we just replaced an existing item.
6156 if (!rc && !(flags & MDB_CURRENT))
6157 mc->mc_db->md_entries++;
6158 if (flags & MDB_MULTIPLE) {
6162 /* let caller know how many succeeded, if any */
6163 data[1].mv_size = mcount;
6164 if (mcount < dcount) {
6165 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
6172 /* If we succeeded and the key didn't exist before, make sure
6173 * the cursor is marked valid.
6176 mc->mc_flags |= C_INITIALIZED;
6181 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
6187 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
6188 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6190 if (!(mc->mc_flags & C_INITIALIZED))
6193 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6194 return MDB_NOTFOUND;
6196 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
6199 rc = mdb_cursor_touch(mc);
6203 mp = mc->mc_pg[mc->mc_top];
6204 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6206 if (!IS_LEAF2(mp) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6207 if (!(flags & MDB_NODUPDATA)) {
6208 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
6209 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6211 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
6212 /* If sub-DB still has entries, we're done */
6213 if (mc->mc_xcursor->mx_db.md_entries) {
6214 if (leaf->mn_flags & F_SUBDATA) {
6215 /* update subDB info */
6216 void *db = NODEDATA(leaf);
6217 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6220 /* shrink fake page */
6221 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
6222 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6223 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6224 /* fix other sub-DB cursors pointed at this fake page */
6225 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6226 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6227 if (m2->mc_pg[mc->mc_top] == mp &&
6228 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
6229 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6232 mc->mc_db->md_entries--;
6233 mc->mc_flags |= C_DEL;
6236 /* otherwise fall thru and delete the sub-DB */
6239 if (leaf->mn_flags & F_SUBDATA) {
6240 /* add all the child DB's pages to the free list */
6241 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6242 if (rc == MDB_SUCCESS) {
6243 mc->mc_db->md_entries -=
6244 mc->mc_xcursor->mx_db.md_entries;
6249 return mdb_cursor_del0(mc, leaf);
6252 /** Allocate and initialize new pages for a database.
6253 * @param[in] mc a cursor on the database being added to.
6254 * @param[in] flags flags defining what type of page is being allocated.
6255 * @param[in] num the number of pages to allocate. This is usually 1,
6256 * unless allocating overflow pages for a large record.
6257 * @param[out] mp Address of a page, or NULL on failure.
6258 * @return 0 on success, non-zero on failure.
6261 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
6266 if ((rc = mdb_page_alloc(mc, num, &np)))
6268 DPRINTF(("allocated new mpage %"Z"u, page size %u",
6269 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
6270 np->mp_flags = flags | P_DIRTY;
6271 np->mp_lower = PAGEHDRSZ;
6272 np->mp_upper = mc->mc_txn->mt_env->me_psize;
6275 mc->mc_db->md_branch_pages++;
6276 else if (IS_LEAF(np))
6277 mc->mc_db->md_leaf_pages++;
6278 else if (IS_OVERFLOW(np)) {
6279 mc->mc_db->md_overflow_pages += num;
6287 /** Calculate the size of a leaf node.
6288 * The size depends on the environment's page size; if a data item
6289 * is too large it will be put onto an overflow page and the node
6290 * size will only include the key and not the data. Sizes are always
6291 * rounded up to an even number of bytes, to guarantee 2-byte alignment
6292 * of the #MDB_node headers.
6293 * @param[in] env The environment handle.
6294 * @param[in] key The key for the node.
6295 * @param[in] data The data for the node.
6296 * @return The number of bytes needed to store the node.
6299 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
6303 sz = LEAFSIZE(key, data);
6304 if (sz > env->me_nodemax) {
6305 /* put on overflow page */
6306 sz -= data->mv_size - sizeof(pgno_t);
6309 return EVEN(sz + sizeof(indx_t));
6312 /** Calculate the size of a branch node.
6313 * The size should depend on the environment's page size but since
6314 * we currently don't support spilling large keys onto overflow
6315 * pages, it's simply the size of the #MDB_node header plus the
6316 * size of the key. Sizes are always rounded up to an even number
6317 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
6318 * @param[in] env The environment handle.
6319 * @param[in] key The key for the node.
6320 * @return The number of bytes needed to store the node.
6323 mdb_branch_size(MDB_env *env, MDB_val *key)
6328 if (sz > env->me_nodemax) {
6329 /* put on overflow page */
6330 /* not implemented */
6331 /* sz -= key->size - sizeof(pgno_t); */
6334 return sz + sizeof(indx_t);
6337 /** Add a node to the page pointed to by the cursor.
6338 * @param[in] mc The cursor for this operation.
6339 * @param[in] indx The index on the page where the new node should be added.
6340 * @param[in] key The key for the new node.
6341 * @param[in] data The data for the new node, if any.
6342 * @param[in] pgno The page number, if adding a branch node.
6343 * @param[in] flags Flags for the node.
6344 * @return 0 on success, non-zero on failure. Possible errors are:
6346 * <li>ENOMEM - failed to allocate overflow pages for the node.
6347 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
6348 * should never happen since all callers already calculate the
6349 * page's free space before calling this function.
6353 mdb_node_add(MDB_cursor *mc, indx_t indx,
6354 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
6357 size_t node_size = NODESIZE;
6361 MDB_page *mp = mc->mc_pg[mc->mc_top];
6362 MDB_page *ofp = NULL; /* overflow page */
6365 assert(mp->mp_upper >= mp->mp_lower);
6367 DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
6368 IS_LEAF(mp) ? "leaf" : "branch",
6369 IS_SUBP(mp) ? "sub-" : "",
6370 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
6371 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
6374 /* Move higher keys up one slot. */
6375 int ksize = mc->mc_db->md_pad, dif;
6376 char *ptr = LEAF2KEY(mp, indx, ksize);
6377 dif = NUMKEYS(mp) - indx;
6379 memmove(ptr+ksize, ptr, dif*ksize);
6380 /* insert new key */
6381 memcpy(ptr, key->mv_data, ksize);
6383 /* Just using these for counting */
6384 mp->mp_lower += sizeof(indx_t);
6385 mp->mp_upper -= ksize - sizeof(indx_t);
6389 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
6391 node_size += key->mv_size;
6394 if (F_ISSET(flags, F_BIGDATA)) {
6395 /* Data already on overflow page. */
6396 node_size += sizeof(pgno_t);
6397 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
6398 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
6400 /* Put data on overflow page. */
6401 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
6402 data->mv_size, node_size+data->mv_size));
6403 node_size = EVEN(node_size + sizeof(pgno_t));
6404 if ((ssize_t)node_size > room)
6406 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
6408 DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
6412 node_size += data->mv_size;
6415 node_size = EVEN(node_size);
6416 if ((ssize_t)node_size > room)
6420 /* Move higher pointers up one slot. */
6421 for (i = NUMKEYS(mp); i > indx; i--)
6422 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
6424 /* Adjust free space offsets. */
6425 ofs = mp->mp_upper - node_size;
6426 assert(ofs >= mp->mp_lower + sizeof(indx_t));
6427 mp->mp_ptrs[indx] = ofs;
6429 mp->mp_lower += sizeof(indx_t);
6431 /* Write the node data. */
6432 node = NODEPTR(mp, indx);
6433 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
6434 node->mn_flags = flags;
6436 SETDSZ(node,data->mv_size);
6441 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6446 if (F_ISSET(flags, F_BIGDATA))
6447 memcpy(node->mn_data + key->mv_size, data->mv_data,
6449 else if (F_ISSET(flags, MDB_RESERVE))
6450 data->mv_data = node->mn_data + key->mv_size;
6452 memcpy(node->mn_data + key->mv_size, data->mv_data,
6455 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
6457 if (F_ISSET(flags, MDB_RESERVE))
6458 data->mv_data = METADATA(ofp);
6460 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
6467 DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
6468 mdb_dbg_pgno(mp), NUMKEYS(mp)));
6469 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
6470 DPRINTF(("node size = %"Z"u", node_size));
6471 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6472 return MDB_PAGE_FULL;
6475 /** Delete the specified node from a page.
6476 * @param[in] mp The page to operate on.
6477 * @param[in] indx The index of the node to delete.
6478 * @param[in] ksize The size of a node. Only used if the page is
6479 * part of a #MDB_DUPFIXED database.
6482 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
6485 indx_t i, j, numkeys, ptr;
6489 DPRINTF(("delete node %u on %s page %"Z"u", indx,
6490 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
6491 assert(indx < NUMKEYS(mp));
6494 int x = NUMKEYS(mp) - 1 - indx;
6495 base = LEAF2KEY(mp, indx, ksize);
6497 memmove(base, base + ksize, x * ksize);
6498 mp->mp_lower -= sizeof(indx_t);
6499 mp->mp_upper += ksize - sizeof(indx_t);
6503 node = NODEPTR(mp, indx);
6504 sz = NODESIZE + node->mn_ksize;
6506 if (F_ISSET(node->mn_flags, F_BIGDATA))
6507 sz += sizeof(pgno_t);
6509 sz += NODEDSZ(node);
6513 ptr = mp->mp_ptrs[indx];
6514 numkeys = NUMKEYS(mp);
6515 for (i = j = 0; i < numkeys; i++) {
6517 mp->mp_ptrs[j] = mp->mp_ptrs[i];
6518 if (mp->mp_ptrs[i] < ptr)
6519 mp->mp_ptrs[j] += sz;
6524 base = (char *)mp + mp->mp_upper;
6525 memmove(base + sz, base, ptr - mp->mp_upper);
6527 mp->mp_lower -= sizeof(indx_t);
6531 /** Compact the main page after deleting a node on a subpage.
6532 * @param[in] mp The main page to operate on.
6533 * @param[in] indx The index of the subpage on the main page.
6536 mdb_node_shrink(MDB_page *mp, indx_t indx)
6542 indx_t i, numkeys, ptr;
6544 node = NODEPTR(mp, indx);
6545 sp = (MDB_page *)NODEDATA(node);
6546 delta = SIZELEFT(sp);
6547 xp = (MDB_page *)((char *)sp + delta);
6549 /* shift subpage upward */
6551 nsize = NUMKEYS(sp) * sp->mp_pad;
6553 return; /* do not make the node uneven-sized */
6554 memmove(METADATA(xp), METADATA(sp), nsize);
6557 numkeys = NUMKEYS(sp);
6558 for (i=numkeys-1; i>=0; i--)
6559 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
6561 xp->mp_upper = sp->mp_lower;
6562 xp->mp_lower = sp->mp_lower;
6563 xp->mp_flags = sp->mp_flags;
6564 xp->mp_pad = sp->mp_pad;
6565 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
6567 nsize = NODEDSZ(node) - delta;
6568 SETDSZ(node, nsize);
6570 /* shift lower nodes upward */
6571 ptr = mp->mp_ptrs[indx];
6572 numkeys = NUMKEYS(mp);
6573 for (i = 0; i < numkeys; i++) {
6574 if (mp->mp_ptrs[i] <= ptr)
6575 mp->mp_ptrs[i] += delta;
6578 base = (char *)mp + mp->mp_upper;
6579 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
6580 mp->mp_upper += delta;
6583 /** Initial setup of a sorted-dups cursor.
6584 * Sorted duplicates are implemented as a sub-database for the given key.
6585 * The duplicate data items are actually keys of the sub-database.
6586 * Operations on the duplicate data items are performed using a sub-cursor
6587 * initialized when the sub-database is first accessed. This function does
6588 * the preliminary setup of the sub-cursor, filling in the fields that
6589 * depend only on the parent DB.
6590 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6593 mdb_xcursor_init0(MDB_cursor *mc)
6595 MDB_xcursor *mx = mc->mc_xcursor;
6597 mx->mx_cursor.mc_xcursor = NULL;
6598 mx->mx_cursor.mc_txn = mc->mc_txn;
6599 mx->mx_cursor.mc_db = &mx->mx_db;
6600 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
6601 mx->mx_cursor.mc_dbi = mc->mc_dbi;
6602 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
6603 mx->mx_cursor.mc_snum = 0;
6604 mx->mx_cursor.mc_top = 0;
6605 mx->mx_cursor.mc_flags = C_SUB;
6606 mx->mx_dbx.md_name.mv_size = 0;
6607 mx->mx_dbx.md_name.mv_data = NULL;
6608 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
6609 mx->mx_dbx.md_dcmp = NULL;
6610 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
6613 /** Final setup of a sorted-dups cursor.
6614 * Sets up the fields that depend on the data from the main cursor.
6615 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6616 * @param[in] node The data containing the #MDB_db record for the
6617 * sorted-dup database.
6620 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
6622 MDB_xcursor *mx = mc->mc_xcursor;
6624 if (node->mn_flags & F_SUBDATA) {
6625 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
6626 mx->mx_cursor.mc_pg[0] = 0;
6627 mx->mx_cursor.mc_snum = 0;
6628 mx->mx_cursor.mc_top = 0;
6629 mx->mx_cursor.mc_flags = C_SUB;
6631 MDB_page *fp = NODEDATA(node);
6632 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
6633 mx->mx_db.md_flags = 0;
6634 mx->mx_db.md_depth = 1;
6635 mx->mx_db.md_branch_pages = 0;
6636 mx->mx_db.md_leaf_pages = 1;
6637 mx->mx_db.md_overflow_pages = 0;
6638 mx->mx_db.md_entries = NUMKEYS(fp);
6639 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
6640 mx->mx_cursor.mc_snum = 1;
6641 mx->mx_cursor.mc_top = 0;
6642 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
6643 mx->mx_cursor.mc_pg[0] = fp;
6644 mx->mx_cursor.mc_ki[0] = 0;
6645 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6646 mx->mx_db.md_flags = MDB_DUPFIXED;
6647 mx->mx_db.md_pad = fp->mp_pad;
6648 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6649 mx->mx_db.md_flags |= MDB_INTEGERKEY;
6652 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
6653 mx->mx_db.md_root));
6654 mx->mx_dbflag = DB_VALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
6655 #if UINT_MAX < SIZE_MAX
6656 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
6657 #ifdef MISALIGNED_OK
6658 mx->mx_dbx.md_cmp = mdb_cmp_long;
6660 mx->mx_dbx.md_cmp = mdb_cmp_cint;
6665 /** Initialize a cursor for a given transaction and database. */
6667 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
6670 mc->mc_backup = NULL;
6673 mc->mc_db = &txn->mt_dbs[dbi];
6674 mc->mc_dbx = &txn->mt_dbxs[dbi];
6675 mc->mc_dbflag = &txn->mt_dbflags[dbi];
6680 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
6682 mc->mc_xcursor = mx;
6683 mdb_xcursor_init0(mc);
6685 mc->mc_xcursor = NULL;
6687 if (*mc->mc_dbflag & DB_STALE) {
6688 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
6693 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
6696 size_t size = sizeof(MDB_cursor);
6698 if (txn == NULL || ret == NULL || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
6701 if (txn->mt_flags & MDB_TXN_ERROR)
6704 /* Allow read access to the freelist */
6705 if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
6708 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
6709 size += sizeof(MDB_xcursor);
6711 if ((mc = malloc(size)) != NULL) {
6712 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
6713 if (txn->mt_cursors) {
6714 mc->mc_next = txn->mt_cursors[dbi];
6715 txn->mt_cursors[dbi] = mc;
6716 mc->mc_flags |= C_UNTRACK;
6728 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
6730 if (txn == NULL || mc == NULL || mc->mc_dbi >= txn->mt_numdbs)
6733 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
6736 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
6740 /* Return the count of duplicate data items for the current key */
6742 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
6746 if (mc == NULL || countp == NULL)
6749 if (mc->mc_xcursor == NULL)
6750 return MDB_INCOMPATIBLE;
6752 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6753 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6756 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
6759 *countp = mc->mc_xcursor->mx_db.md_entries;
6765 mdb_cursor_close(MDB_cursor *mc)
6767 if (mc && !mc->mc_backup) {
6768 /* remove from txn, if tracked */
6769 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
6770 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
6771 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
6773 *prev = mc->mc_next;
6780 mdb_cursor_txn(MDB_cursor *mc)
6782 if (!mc) return NULL;
6787 mdb_cursor_dbi(MDB_cursor *mc)
6793 /** Replace the key for a branch node with a new key.
6794 * @param[in] mc Cursor pointing to the node to operate on.
6795 * @param[in] key The new key to use.
6796 * @return 0 on success, non-zero on failure.
6799 mdb_update_key(MDB_cursor *mc, MDB_val *key)
6805 int delta, ksize, oksize;
6806 indx_t ptr, i, numkeys, indx;
6809 indx = mc->mc_ki[mc->mc_top];
6810 mp = mc->mc_pg[mc->mc_top];
6811 node = NODEPTR(mp, indx);
6812 ptr = mp->mp_ptrs[indx];
6816 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
6817 k2.mv_data = NODEKEY(node);
6818 k2.mv_size = node->mn_ksize;
6819 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
6821 mdb_dkey(&k2, kbuf2),
6827 /* Sizes must be 2-byte aligned. */
6828 ksize = EVEN(key->mv_size);
6829 oksize = EVEN(node->mn_ksize);
6830 delta = ksize - oksize;
6832 /* Shift node contents if EVEN(key length) changed. */
6834 if (delta > 0 && SIZELEFT(mp) < delta) {
6836 /* not enough space left, do a delete and split */
6837 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
6838 pgno = NODEPGNO(node);
6839 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
6840 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
6843 numkeys = NUMKEYS(mp);
6844 for (i = 0; i < numkeys; i++) {
6845 if (mp->mp_ptrs[i] <= ptr)
6846 mp->mp_ptrs[i] -= delta;
6849 base = (char *)mp + mp->mp_upper;
6850 len = ptr - mp->mp_upper + NODESIZE;
6851 memmove(base - delta, base, len);
6852 mp->mp_upper -= delta;
6854 node = NODEPTR(mp, indx);
6857 /* But even if no shift was needed, update ksize */
6858 if (node->mn_ksize != key->mv_size)
6859 node->mn_ksize = key->mv_size;
6862 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6868 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
6870 /** Move a node from csrc to cdst.
6873 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
6880 unsigned short flags;
6884 /* Mark src and dst as dirty. */
6885 if ((rc = mdb_page_touch(csrc)) ||
6886 (rc = mdb_page_touch(cdst)))
6889 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6890 key.mv_size = csrc->mc_db->md_pad;
6891 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
6893 data.mv_data = NULL;
6897 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
6898 assert(!((size_t)srcnode&1));
6899 srcpg = NODEPGNO(srcnode);
6900 flags = srcnode->mn_flags;
6901 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6902 unsigned int snum = csrc->mc_snum;
6904 /* must find the lowest key below src */
6905 mdb_page_search_lowest(csrc);
6906 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6907 key.mv_size = csrc->mc_db->md_pad;
6908 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6910 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6911 key.mv_size = NODEKSZ(s2);
6912 key.mv_data = NODEKEY(s2);
6914 csrc->mc_snum = snum--;
6915 csrc->mc_top = snum;
6917 key.mv_size = NODEKSZ(srcnode);
6918 key.mv_data = NODEKEY(srcnode);
6920 data.mv_size = NODEDSZ(srcnode);
6921 data.mv_data = NODEDATA(srcnode);
6923 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
6924 unsigned int snum = cdst->mc_snum;
6927 /* must find the lowest key below dst */
6928 mdb_page_search_lowest(cdst);
6929 if (IS_LEAF2(cdst->mc_pg[cdst->mc_top])) {
6930 bkey.mv_size = cdst->mc_db->md_pad;
6931 bkey.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, bkey.mv_size);
6933 s2 = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
6934 bkey.mv_size = NODEKSZ(s2);
6935 bkey.mv_data = NODEKEY(s2);
6937 cdst->mc_snum = snum--;
6938 cdst->mc_top = snum;
6939 mdb_cursor_copy(cdst, &mn);
6941 rc = mdb_update_key(&mn, &bkey);
6946 DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
6947 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
6948 csrc->mc_ki[csrc->mc_top],
6950 csrc->mc_pg[csrc->mc_top]->mp_pgno,
6951 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
6953 /* Add the node to the destination page.
6955 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
6956 if (rc != MDB_SUCCESS)
6959 /* Delete the node from the source page.
6961 mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
6964 /* Adjust other cursors pointing to mp */
6965 MDB_cursor *m2, *m3;
6966 MDB_dbi dbi = csrc->mc_dbi;
6967 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
6969 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6970 if (csrc->mc_flags & C_SUB)
6971 m3 = &m2->mc_xcursor->mx_cursor;
6974 if (m3 == csrc) continue;
6975 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
6976 csrc->mc_ki[csrc->mc_top]) {
6977 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
6978 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
6983 /* Update the parent separators.
6985 if (csrc->mc_ki[csrc->mc_top] == 0) {
6986 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
6987 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6988 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6990 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6991 key.mv_size = NODEKSZ(srcnode);
6992 key.mv_data = NODEKEY(srcnode);
6994 DPRINTF(("update separator for source page %"Z"u to [%s]",
6995 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
6996 mdb_cursor_copy(csrc, &mn);
6999 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7002 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7004 indx_t ix = csrc->mc_ki[csrc->mc_top];
7005 nullkey.mv_size = 0;
7006 csrc->mc_ki[csrc->mc_top] = 0;
7007 rc = mdb_update_key(csrc, &nullkey);
7008 csrc->mc_ki[csrc->mc_top] = ix;
7009 assert(rc == MDB_SUCCESS);
7013 if (cdst->mc_ki[cdst->mc_top] == 0) {
7014 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
7015 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7016 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
7018 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
7019 key.mv_size = NODEKSZ(srcnode);
7020 key.mv_data = NODEKEY(srcnode);
7022 DPRINTF(("update separator for destination page %"Z"u to [%s]",
7023 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
7024 mdb_cursor_copy(cdst, &mn);
7027 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7030 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
7032 indx_t ix = cdst->mc_ki[cdst->mc_top];
7033 nullkey.mv_size = 0;
7034 cdst->mc_ki[cdst->mc_top] = 0;
7035 rc = mdb_update_key(cdst, &nullkey);
7036 cdst->mc_ki[cdst->mc_top] = ix;
7037 assert(rc == MDB_SUCCESS);
7044 /** Merge one page into another.
7045 * The nodes from the page pointed to by \b csrc will
7046 * be copied to the page pointed to by \b cdst and then
7047 * the \b csrc page will be freed.
7048 * @param[in] csrc Cursor pointing to the source page.
7049 * @param[in] cdst Cursor pointing to the destination page.
7052 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
7060 DPRINTF(("merging page %"Z"u into %"Z"u", csrc->mc_pg[csrc->mc_top]->mp_pgno,
7061 cdst->mc_pg[cdst->mc_top]->mp_pgno));
7063 assert(csrc->mc_snum > 1); /* can't merge root page */
7064 assert(cdst->mc_snum > 1);
7066 /* Mark dst as dirty. */
7067 if ((rc = mdb_page_touch(cdst)))
7070 /* Move all nodes from src to dst.
7072 j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
7073 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7074 key.mv_size = csrc->mc_db->md_pad;
7075 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
7076 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
7077 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
7078 if (rc != MDB_SUCCESS)
7080 key.mv_data = (char *)key.mv_data + key.mv_size;
7083 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
7084 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
7085 if (i == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7086 unsigned int snum = csrc->mc_snum;
7088 /* must find the lowest key below src */
7089 mdb_page_search_lowest(csrc);
7090 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7091 key.mv_size = csrc->mc_db->md_pad;
7092 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7094 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7095 key.mv_size = NODEKSZ(s2);
7096 key.mv_data = NODEKEY(s2);
7098 csrc->mc_snum = snum--;
7099 csrc->mc_top = snum;
7101 key.mv_size = srcnode->mn_ksize;
7102 key.mv_data = NODEKEY(srcnode);
7105 data.mv_size = NODEDSZ(srcnode);
7106 data.mv_data = NODEDATA(srcnode);
7107 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
7108 if (rc != MDB_SUCCESS)
7113 DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
7114 cdst->mc_pg[cdst->mc_top]->mp_pgno, NUMKEYS(cdst->mc_pg[cdst->mc_top]),
7115 (float)PAGEFILL(cdst->mc_txn->mt_env, cdst->mc_pg[cdst->mc_top]) / 10));
7117 /* Unlink the src page from parent and add to free list.
7119 mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
7120 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
7123 rc = mdb_update_key(csrc, &key);
7129 rc = mdb_midl_append(&csrc->mc_txn->mt_free_pgs,
7130 csrc->mc_pg[csrc->mc_top]->mp_pgno);
7133 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
7134 csrc->mc_db->md_leaf_pages--;
7136 csrc->mc_db->md_branch_pages--;
7138 /* Adjust other cursors pointing to mp */
7139 MDB_cursor *m2, *m3;
7140 MDB_dbi dbi = csrc->mc_dbi;
7141 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
7143 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7144 if (csrc->mc_flags & C_SUB)
7145 m3 = &m2->mc_xcursor->mx_cursor;
7148 if (m3 == csrc) continue;
7149 if (m3->mc_snum < csrc->mc_snum) continue;
7150 if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
7151 m3->mc_pg[csrc->mc_top] = mp;
7152 m3->mc_ki[csrc->mc_top] += nkeys;
7156 mdb_cursor_pop(csrc);
7158 return mdb_rebalance(csrc);
7161 /** Copy the contents of a cursor.
7162 * @param[in] csrc The cursor to copy from.
7163 * @param[out] cdst The cursor to copy to.
7166 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
7170 cdst->mc_txn = csrc->mc_txn;
7171 cdst->mc_dbi = csrc->mc_dbi;
7172 cdst->mc_db = csrc->mc_db;
7173 cdst->mc_dbx = csrc->mc_dbx;
7174 cdst->mc_snum = csrc->mc_snum;
7175 cdst->mc_top = csrc->mc_top;
7176 cdst->mc_flags = csrc->mc_flags;
7178 for (i=0; i<csrc->mc_snum; i++) {
7179 cdst->mc_pg[i] = csrc->mc_pg[i];
7180 cdst->mc_ki[i] = csrc->mc_ki[i];
7184 /** Rebalance the tree after a delete operation.
7185 * @param[in] mc Cursor pointing to the page where rebalancing
7187 * @return 0 on success, non-zero on failure.
7190 mdb_rebalance(MDB_cursor *mc)
7194 unsigned int ptop, minkeys;
7197 minkeys = 1 + (IS_BRANCH(mc->mc_pg[mc->mc_top]));
7198 DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
7199 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
7200 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
7201 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
7203 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD &&
7204 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
7205 DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
7206 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
7210 if (mc->mc_snum < 2) {
7211 MDB_page *mp = mc->mc_pg[0];
7213 DPUTS("Can't rebalance a subpage, ignoring");
7216 if (NUMKEYS(mp) == 0) {
7217 DPUTS("tree is completely empty");
7218 mc->mc_db->md_root = P_INVALID;
7219 mc->mc_db->md_depth = 0;
7220 mc->mc_db->md_leaf_pages = 0;
7221 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7224 /* Adjust cursors pointing to mp */
7227 mc->mc_flags &= ~C_INITIALIZED;
7229 MDB_cursor *m2, *m3;
7230 MDB_dbi dbi = mc->mc_dbi;
7232 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7233 if (mc->mc_flags & C_SUB)
7234 m3 = &m2->mc_xcursor->mx_cursor;
7237 if (m3->mc_snum < mc->mc_snum) continue;
7238 if (m3->mc_pg[0] == mp) {
7241 m3->mc_flags &= ~C_INITIALIZED;
7245 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
7246 DPUTS("collapsing root page!");
7247 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7250 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
7251 rc = mdb_page_get(mc->mc_txn,mc->mc_db->md_root,&mc->mc_pg[0],NULL);
7254 mc->mc_db->md_depth--;
7255 mc->mc_db->md_branch_pages--;
7256 mc->mc_ki[0] = mc->mc_ki[1];
7258 /* Adjust other cursors pointing to mp */
7259 MDB_cursor *m2, *m3;
7260 MDB_dbi dbi = mc->mc_dbi;
7262 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7263 if (mc->mc_flags & C_SUB)
7264 m3 = &m2->mc_xcursor->mx_cursor;
7267 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
7268 if (m3->mc_pg[0] == mp) {
7272 for (i=0; i<m3->mc_snum; i++) {
7273 m3->mc_pg[i] = m3->mc_pg[i+1];
7274 m3->mc_ki[i] = m3->mc_ki[i+1];
7280 DPUTS("root page doesn't need rebalancing");
7284 /* The parent (branch page) must have at least 2 pointers,
7285 * otherwise the tree is invalid.
7287 ptop = mc->mc_top-1;
7288 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
7290 /* Leaf page fill factor is below the threshold.
7291 * Try to move keys from left or right neighbor, or
7292 * merge with a neighbor page.
7297 mdb_cursor_copy(mc, &mn);
7298 mn.mc_xcursor = NULL;
7300 if (mc->mc_ki[ptop] == 0) {
7301 /* We're the leftmost leaf in our parent.
7303 DPUTS("reading right neighbor");
7305 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7306 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7309 mn.mc_ki[mn.mc_top] = 0;
7310 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
7312 /* There is at least one neighbor to the left.
7314 DPUTS("reading left neighbor");
7316 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7317 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7320 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
7321 mc->mc_ki[mc->mc_top] = 0;
7324 DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
7325 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
7326 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
7328 /* If the neighbor page is above threshold and has enough keys,
7329 * move one key from it. Otherwise we should try to merge them.
7330 * (A branch page must never have less than 2 keys.)
7332 minkeys = 1 + (IS_BRANCH(mn.mc_pg[mn.mc_top]));
7333 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys)
7334 return mdb_node_move(&mn, mc);
7336 if (mc->mc_ki[ptop] == 0)
7337 rc = mdb_page_merge(&mn, mc);
7339 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
7340 rc = mdb_page_merge(mc, &mn);
7341 mdb_cursor_copy(&mn, mc);
7343 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
7348 /** Complete a delete operation started by #mdb_cursor_del(). */
7350 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
7357 mp = mc->mc_pg[mc->mc_top];
7358 ki = mc->mc_ki[mc->mc_top];
7360 /* add overflow pages to free list */
7361 if (!IS_LEAF2(mp) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7365 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
7366 if ((rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL)) ||
7367 (rc = mdb_ovpage_free(mc, omp)))
7370 mdb_node_del(mp, ki, mc->mc_db->md_pad);
7371 mc->mc_db->md_entries--;
7372 rc = mdb_rebalance(mc);
7373 if (rc != MDB_SUCCESS)
7374 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7376 MDB_cursor *m2, *m3;
7377 MDB_dbi dbi = mc->mc_dbi;
7379 mp = mc->mc_pg[mc->mc_top];
7380 nkeys = NUMKEYS(mp);
7382 /* if mc points past last node in page, find next sibling */
7383 if (mc->mc_ki[mc->mc_top] >= nkeys)
7384 mdb_cursor_sibling(mc, 1);
7386 /* Adjust other cursors pointing to mp */
7387 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7388 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
7389 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
7391 if (m3 == mc || m3->mc_snum < mc->mc_snum)
7393 if (m3->mc_pg[mc->mc_top] == mp) {
7394 if (m3->mc_ki[mc->mc_top] >= ki) {
7395 m3->mc_flags |= C_DEL;
7396 if (m3->mc_ki[mc->mc_top] > ki)
7397 m3->mc_ki[mc->mc_top]--;
7399 if (m3->mc_ki[mc->mc_top] >= nkeys)
7400 mdb_cursor_sibling(m3, 1);
7403 mc->mc_flags |= C_DEL;
7410 mdb_del(MDB_txn *txn, MDB_dbi dbi,
7411 MDB_val *key, MDB_val *data)
7416 MDB_val rdata, *xdata;
7423 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
7425 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7428 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
7429 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7431 mdb_cursor_init(&mc, txn, dbi, &mx);
7434 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
7435 /* must ignore any data */
7446 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
7448 /* let mdb_page_split know about this cursor if needed:
7449 * delete will trigger a rebalance; if it needs to move
7450 * a node from one page to another, it will have to
7451 * update the parent's separator key(s). If the new sepkey
7452 * is larger than the current one, the parent page may
7453 * run out of space, triggering a split. We need this
7454 * cursor to be consistent until the end of the rebalance.
7456 mc.mc_flags |= C_UNTRACK;
7457 mc.mc_next = txn->mt_cursors[dbi];
7458 txn->mt_cursors[dbi] = &mc;
7459 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
7460 txn->mt_cursors[dbi] = mc.mc_next;
7465 /** Split a page and insert a new node.
7466 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
7467 * The cursor will be updated to point to the actual page and index where
7468 * the node got inserted after the split.
7469 * @param[in] newkey The key for the newly inserted node.
7470 * @param[in] newdata The data for the newly inserted node.
7471 * @param[in] newpgno The page number, if the new node is a branch node.
7472 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
7473 * @return 0 on success, non-zero on failure.
7476 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
7477 unsigned int nflags)
7480 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
7483 int i, j, split_indx, nkeys, pmax;
7484 MDB_env *env = mc->mc_txn->mt_env;
7486 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
7487 MDB_page *copy = NULL;
7488 MDB_page *mp, *rp, *pp;
7493 mp = mc->mc_pg[mc->mc_top];
7494 newindx = mc->mc_ki[mc->mc_top];
7495 nkeys = NUMKEYS(mp);
7497 DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i/%i",
7498 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
7499 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
7501 /* Create a right sibling. */
7502 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
7504 DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
7506 if (mc->mc_snum < 2) {
7507 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
7509 /* shift current top to make room for new parent */
7510 mc->mc_pg[1] = mc->mc_pg[0];
7511 mc->mc_ki[1] = mc->mc_ki[0];
7514 mc->mc_db->md_root = pp->mp_pgno;
7515 DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
7516 mc->mc_db->md_depth++;
7519 /* Add left (implicit) pointer. */
7520 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
7521 /* undo the pre-push */
7522 mc->mc_pg[0] = mc->mc_pg[1];
7523 mc->mc_ki[0] = mc->mc_ki[1];
7524 mc->mc_db->md_root = mp->mp_pgno;
7525 mc->mc_db->md_depth--;
7532 ptop = mc->mc_top-1;
7533 DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
7536 mc->mc_flags |= C_SPLITTING;
7537 mdb_cursor_copy(mc, &mn);
7538 mn.mc_pg[mn.mc_top] = rp;
7539 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
7541 if (nflags & MDB_APPEND) {
7542 mn.mc_ki[mn.mc_top] = 0;
7544 split_indx = newindx;
7548 split_indx = (nkeys+1) / 2;
7553 unsigned int lsize, rsize, ksize;
7554 /* Move half of the keys to the right sibling */
7556 x = mc->mc_ki[mc->mc_top] - split_indx;
7557 ksize = mc->mc_db->md_pad;
7558 split = LEAF2KEY(mp, split_indx, ksize);
7559 rsize = (nkeys - split_indx) * ksize;
7560 lsize = (nkeys - split_indx) * sizeof(indx_t);
7561 mp->mp_lower -= lsize;
7562 rp->mp_lower += lsize;
7563 mp->mp_upper += rsize - lsize;
7564 rp->mp_upper -= rsize - lsize;
7565 sepkey.mv_size = ksize;
7566 if (newindx == split_indx) {
7567 sepkey.mv_data = newkey->mv_data;
7569 sepkey.mv_data = split;
7572 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
7573 memcpy(rp->mp_ptrs, split, rsize);
7574 sepkey.mv_data = rp->mp_ptrs;
7575 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
7576 memcpy(ins, newkey->mv_data, ksize);
7577 mp->mp_lower += sizeof(indx_t);
7578 mp->mp_upper -= ksize - sizeof(indx_t);
7581 memcpy(rp->mp_ptrs, split, x * ksize);
7582 ins = LEAF2KEY(rp, x, ksize);
7583 memcpy(ins, newkey->mv_data, ksize);
7584 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
7585 rp->mp_lower += sizeof(indx_t);
7586 rp->mp_upper -= ksize - sizeof(indx_t);
7587 mc->mc_ki[mc->mc_top] = x;
7588 mc->mc_pg[mc->mc_top] = rp;
7591 int psize, nsize, k;
7592 /* Maximum free space in an empty page */
7593 pmax = env->me_psize - PAGEHDRSZ;
7595 nsize = mdb_leaf_size(env, newkey, newdata);
7597 nsize = mdb_branch_size(env, newkey);
7598 nsize = EVEN(nsize);
7600 /* grab a page to hold a temporary copy */
7601 copy = mdb_page_malloc(mc->mc_txn, 1);
7604 copy->mp_pgno = mp->mp_pgno;
7605 copy->mp_flags = mp->mp_flags;
7606 copy->mp_lower = PAGEHDRSZ;
7607 copy->mp_upper = env->me_psize;
7609 /* prepare to insert */
7610 for (i=0, j=0; i<nkeys; i++) {
7612 copy->mp_ptrs[j++] = 0;
7614 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
7617 /* When items are relatively large the split point needs
7618 * to be checked, because being off-by-one will make the
7619 * difference between success or failure in mdb_node_add.
7621 * It's also relevant if a page happens to be laid out
7622 * such that one half of its nodes are all "small" and
7623 * the other half of its nodes are "large." If the new
7624 * item is also "large" and falls on the half with
7625 * "large" nodes, it also may not fit.
7627 * As a final tweak, if the new item goes on the last
7628 * spot on the page (and thus, onto the new page), bias
7629 * the split so the new page is emptier than the old page.
7630 * This yields better packing during sequential inserts.
7632 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
7633 /* Find split point */
7635 if (newindx <= split_indx || newindx >= nkeys) {
7637 k = newindx >= nkeys ? nkeys : split_indx+2;
7642 for (; i!=k; i+=j) {
7647 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i]);
7648 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
7650 if (F_ISSET(node->mn_flags, F_BIGDATA))
7651 psize += sizeof(pgno_t);
7653 psize += NODEDSZ(node);
7655 psize = EVEN(psize);
7657 if (psize > pmax || i == k-j) {
7658 split_indx = i + (j<0);
7663 if (split_indx == newindx) {
7664 sepkey.mv_size = newkey->mv_size;
7665 sepkey.mv_data = newkey->mv_data;
7667 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx]);
7668 sepkey.mv_size = node->mn_ksize;
7669 sepkey.mv_data = NODEKEY(node);
7674 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
7676 /* Copy separator key to the parent.
7678 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
7682 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
7685 if (mn.mc_snum == mc->mc_snum) {
7686 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
7687 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
7688 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
7689 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
7694 /* Right page might now have changed parent.
7695 * Check if left page also changed parent.
7697 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7698 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7699 for (i=0; i<ptop; i++) {
7700 mc->mc_pg[i] = mn.mc_pg[i];
7701 mc->mc_ki[i] = mn.mc_ki[i];
7703 mc->mc_pg[ptop] = mn.mc_pg[ptop];
7704 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
7708 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
7711 mc->mc_flags ^= C_SPLITTING;
7712 if (rc != MDB_SUCCESS) {
7715 if (nflags & MDB_APPEND) {
7716 mc->mc_pg[mc->mc_top] = rp;
7717 mc->mc_ki[mc->mc_top] = 0;
7718 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
7721 for (i=0; i<mc->mc_top; i++)
7722 mc->mc_ki[i] = mn.mc_ki[i];
7723 } else if (!IS_LEAF2(mp)) {
7725 mc->mc_pg[mc->mc_top] = rp;
7730 rkey.mv_data = newkey->mv_data;
7731 rkey.mv_size = newkey->mv_size;
7737 /* Update index for the new key. */
7738 mc->mc_ki[mc->mc_top] = j;
7740 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i]);
7741 rkey.mv_data = NODEKEY(node);
7742 rkey.mv_size = node->mn_ksize;
7744 xdata.mv_data = NODEDATA(node);
7745 xdata.mv_size = NODEDSZ(node);
7748 pgno = NODEPGNO(node);
7749 flags = node->mn_flags;
7752 if (!IS_LEAF(mp) && j == 0) {
7753 /* First branch index doesn't need key data. */
7757 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
7759 /* return tmp page to freelist */
7760 mdb_page_free(env, copy);
7766 mc->mc_pg[mc->mc_top] = copy;
7771 } while (i != split_indx);
7773 nkeys = NUMKEYS(copy);
7774 for (i=0; i<nkeys; i++)
7775 mp->mp_ptrs[i] = copy->mp_ptrs[i];
7776 mp->mp_lower = copy->mp_lower;
7777 mp->mp_upper = copy->mp_upper;
7778 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
7779 env->me_psize - copy->mp_upper);
7781 /* reset back to original page */
7782 if (newindx < split_indx) {
7783 mc->mc_pg[mc->mc_top] = mp;
7784 if (nflags & MDB_RESERVE) {
7785 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7786 if (!(node->mn_flags & F_BIGDATA))
7787 newdata->mv_data = NODEDATA(node);
7790 mc->mc_pg[mc->mc_top] = rp;
7792 /* Make sure mc_ki is still valid.
7794 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7795 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7796 for (i=0; i<ptop; i++) {
7797 mc->mc_pg[i] = mn.mc_pg[i];
7798 mc->mc_ki[i] = mn.mc_ki[i];
7800 mc->mc_pg[ptop] = mn.mc_pg[ptop];
7801 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
7804 /* return tmp page to freelist */
7805 mdb_page_free(env, copy);
7809 /* Adjust other cursors pointing to mp */
7810 MDB_cursor *m2, *m3;
7811 MDB_dbi dbi = mc->mc_dbi;
7812 int fixup = NUMKEYS(mp);
7814 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7815 if (mc->mc_flags & C_SUB)
7816 m3 = &m2->mc_xcursor->mx_cursor;
7821 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
7823 if (m3->mc_flags & C_SPLITTING)
7828 for (k=m3->mc_top; k>=0; k--) {
7829 m3->mc_ki[k+1] = m3->mc_ki[k];
7830 m3->mc_pg[k+1] = m3->mc_pg[k];
7832 if (m3->mc_ki[0] >= split_indx) {
7837 m3->mc_pg[0] = mc->mc_pg[0];
7841 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
7842 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
7843 m3->mc_ki[mc->mc_top]++;
7844 if (m3->mc_ki[mc->mc_top] >= fixup) {
7845 m3->mc_pg[mc->mc_top] = rp;
7846 m3->mc_ki[mc->mc_top] -= fixup;
7847 m3->mc_ki[ptop] = mn.mc_ki[ptop];
7849 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
7850 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
7855 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
7860 mdb_put(MDB_txn *txn, MDB_dbi dbi,
7861 MDB_val *key, MDB_val *data, unsigned int flags)
7866 if (key == NULL || data == NULL)
7869 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7872 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP)) != flags)
7875 mdb_cursor_init(&mc, txn, dbi, &mx);
7876 return mdb_cursor_put(&mc, key, data, flags);
7880 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
7882 if ((flag & CHANGEABLE) != flag)
7885 env->me_flags |= flag;
7887 env->me_flags &= ~flag;
7892 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
7897 *arg = env->me_flags;
7902 mdb_env_get_path(MDB_env *env, const char **arg)
7907 *arg = env->me_path;
7912 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
7921 /** Common code for #mdb_stat() and #mdb_env_stat().
7922 * @param[in] env the environment to operate in.
7923 * @param[in] db the #MDB_db record containing the stats to return.
7924 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
7925 * @return 0, this function always succeeds.
7928 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
7930 arg->ms_psize = env->me_psize;
7931 arg->ms_depth = db->md_depth;
7932 arg->ms_branch_pages = db->md_branch_pages;
7933 arg->ms_leaf_pages = db->md_leaf_pages;
7934 arg->ms_overflow_pages = db->md_overflow_pages;
7935 arg->ms_entries = db->md_entries;
7940 mdb_env_stat(MDB_env *env, MDB_stat *arg)
7944 if (env == NULL || arg == NULL)
7947 toggle = mdb_env_pick_meta(env);
7949 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
7953 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
7957 if (env == NULL || arg == NULL)
7960 toggle = mdb_env_pick_meta(env);
7961 arg->me_mapaddr = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : 0;
7962 arg->me_mapsize = env->me_mapsize;
7963 arg->me_maxreaders = env->me_maxreaders;
7965 /* me_numreaders may be zero if this process never used any readers. Use
7966 * the shared numreader count if it exists.
7968 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : env->me_numreaders;
7970 arg->me_last_pgno = env->me_metas[toggle]->mm_last_pg;
7971 arg->me_last_txnid = env->me_metas[toggle]->mm_txnid;
7975 /** Set the default comparison functions for a database.
7976 * Called immediately after a database is opened to set the defaults.
7977 * The user can then override them with #mdb_set_compare() or
7978 * #mdb_set_dupsort().
7979 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
7980 * @param[in] dbi A database handle returned by #mdb_dbi_open()
7983 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
7985 uint16_t f = txn->mt_dbs[dbi].md_flags;
7987 txn->mt_dbxs[dbi].md_cmp =
7988 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
7989 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
7991 txn->mt_dbxs[dbi].md_dcmp =
7992 !(f & MDB_DUPSORT) ? 0 :
7993 ((f & MDB_INTEGERDUP)
7994 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
7995 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
7998 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
8003 int rc, dbflag, exact;
8004 unsigned int unused = 0;
8007 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
8008 mdb_default_cmp(txn, FREE_DBI);
8011 if ((flags & VALID_FLAGS) != flags)
8013 if (txn->mt_flags & MDB_TXN_ERROR)
8019 if (flags & PERSISTENT_FLAGS) {
8020 uint16_t f2 = flags & PERSISTENT_FLAGS;
8021 /* make sure flag changes get committed */
8022 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
8023 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
8024 txn->mt_flags |= MDB_TXN_DIRTY;
8027 mdb_default_cmp(txn, MAIN_DBI);
8031 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
8032 mdb_default_cmp(txn, MAIN_DBI);
8035 /* Is the DB already open? */
8037 for (i=2; i<txn->mt_numdbs; i++) {
8038 if (!txn->mt_dbxs[i].md_name.mv_size) {
8039 /* Remember this free slot */
8040 if (!unused) unused = i;
8043 if (len == txn->mt_dbxs[i].md_name.mv_size &&
8044 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
8050 /* If no free slot and max hit, fail */
8051 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
8052 return MDB_DBS_FULL;
8054 /* Cannot mix named databases with some mainDB flags */
8055 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
8056 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
8058 /* Find the DB info */
8059 dbflag = DB_NEW|DB_VALID;
8062 key.mv_data = (void *)name;
8063 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
8064 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
8065 if (rc == MDB_SUCCESS) {
8066 /* make sure this is actually a DB */
8067 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
8068 if (!(node->mn_flags & F_SUBDATA))
8069 return MDB_INCOMPATIBLE;
8070 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
8071 /* Create if requested */
8073 data.mv_size = sizeof(MDB_db);
8074 data.mv_data = &dummy;
8075 memset(&dummy, 0, sizeof(dummy));
8076 dummy.md_root = P_INVALID;
8077 dummy.md_flags = flags & PERSISTENT_FLAGS;
8078 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
8082 /* OK, got info, add to table */
8083 if (rc == MDB_SUCCESS) {
8084 unsigned int slot = unused ? unused : txn->mt_numdbs;
8085 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
8086 txn->mt_dbxs[slot].md_name.mv_size = len;
8087 txn->mt_dbxs[slot].md_rel = NULL;
8088 txn->mt_dbflags[slot] = dbflag;
8089 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
8091 mdb_default_cmp(txn, slot);
8100 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
8102 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
8105 if (txn->mt_dbflags[dbi] & DB_STALE) {
8108 /* Stale, must read the DB's root. cursor_init does it for us. */
8109 mdb_cursor_init(&mc, txn, dbi, &mx);
8111 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
8114 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
8117 if (dbi <= MAIN_DBI || dbi >= env->me_maxdbs)
8119 ptr = env->me_dbxs[dbi].md_name.mv_data;
8120 env->me_dbxs[dbi].md_name.mv_data = NULL;
8121 env->me_dbxs[dbi].md_name.mv_size = 0;
8122 env->me_dbflags[dbi] = 0;
8126 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
8128 /* We could return the flags for the FREE_DBI too but what's the point? */
8129 if (txn == NULL || dbi < MAIN_DBI || dbi >= txn->mt_numdbs)
8131 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
8135 /** Add all the DB's pages to the free list.
8136 * @param[in] mc Cursor on the DB to free.
8137 * @param[in] subs non-Zero to check for sub-DBs in this DB.
8138 * @return 0 on success, non-zero on failure.
8141 mdb_drop0(MDB_cursor *mc, int subs)
8145 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
8146 if (rc == MDB_SUCCESS) {
8147 MDB_txn *txn = mc->mc_txn;
8152 /* LEAF2 pages have no nodes, cannot have sub-DBs */
8153 if (IS_LEAF2(mc->mc_pg[mc->mc_top]))
8156 mdb_cursor_copy(mc, &mx);
8157 while (mc->mc_snum > 0) {
8158 MDB_page *mp = mc->mc_pg[mc->mc_top];
8159 unsigned n = NUMKEYS(mp);
8161 for (i=0; i<n; i++) {
8162 ni = NODEPTR(mp, i);
8163 if (ni->mn_flags & F_BIGDATA) {
8166 memcpy(&pg, NODEDATA(ni), sizeof(pg));
8167 rc = mdb_page_get(txn, pg, &omp, NULL);
8170 assert(IS_OVERFLOW(omp));
8171 rc = mdb_midl_append_range(&txn->mt_free_pgs,
8175 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
8176 mdb_xcursor_init1(mc, ni);
8177 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
8183 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
8185 for (i=0; i<n; i++) {
8187 ni = NODEPTR(mp, i);
8190 mdb_midl_xappend(txn->mt_free_pgs, pg);
8195 mc->mc_ki[mc->mc_top] = i;
8196 rc = mdb_cursor_sibling(mc, 1);
8198 /* no more siblings, go back to beginning
8199 * of previous level.
8203 for (i=1; i<mc->mc_snum; i++) {
8205 mc->mc_pg[i] = mx.mc_pg[i];
8210 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
8211 } else if (rc == MDB_NOTFOUND) {
8217 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
8219 MDB_cursor *mc, *m2;
8222 if (!txn || !dbi || dbi >= txn->mt_numdbs || (unsigned)del > 1 || !(txn->mt_dbflags[dbi] & DB_VALID))
8225 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
8228 rc = mdb_cursor_open(txn, dbi, &mc);
8232 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
8233 /* Invalidate the dropped DB's cursors */
8234 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
8235 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
8239 /* Can't delete the main DB */
8240 if (del && dbi > MAIN_DBI) {
8241 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
8243 txn->mt_dbflags[dbi] = DB_STALE;
8244 mdb_dbi_close(txn->mt_env, dbi);
8247 /* reset the DB record, mark it dirty */
8248 txn->mt_dbflags[dbi] |= DB_DIRTY;
8249 txn->mt_dbs[dbi].md_depth = 0;
8250 txn->mt_dbs[dbi].md_branch_pages = 0;
8251 txn->mt_dbs[dbi].md_leaf_pages = 0;
8252 txn->mt_dbs[dbi].md_overflow_pages = 0;
8253 txn->mt_dbs[dbi].md_entries = 0;
8254 txn->mt_dbs[dbi].md_root = P_INVALID;
8256 txn->mt_flags |= MDB_TXN_DIRTY;
8259 mdb_cursor_close(mc);
8263 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
8265 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8268 txn->mt_dbxs[dbi].md_cmp = cmp;
8272 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
8274 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8277 txn->mt_dbxs[dbi].md_dcmp = cmp;
8281 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
8283 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8286 txn->mt_dbxs[dbi].md_rel = rel;
8290 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
8292 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8295 txn->mt_dbxs[dbi].md_relctx = ctx;
8299 int mdb_env_get_maxkeysize(MDB_env *env)
8301 return ENV_MAXKEY(env);
8304 int mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
8306 unsigned int i, rdrs;
8309 int rc = 0, first = 1;
8313 if (!env->me_txns) {
8314 return func("(no reader locks)\n", ctx);
8316 rdrs = env->me_txns->mti_numreaders;
8317 mr = env->me_txns->mti_readers;
8318 for (i=0; i<rdrs; i++) {
8320 txnid_t txnid = mr[i].mr_txnid;
8321 sprintf(buf, txnid == (txnid_t)-1 ?
8322 "%10d %"Z"x -\n" : "%10d %"Z"x %"Z"u\n",
8323 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
8326 rc = func(" pid thread txnid\n", ctx);
8330 rc = func(buf, ctx);
8336 rc = func("(no active readers)\n", ctx);
8341 /** Insert pid into list if not already present.
8342 * return -1 if already present.
8344 static int mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
8346 /* binary search of pid in list */
8348 unsigned cursor = 1;
8350 unsigned n = ids[0];
8353 unsigned pivot = n >> 1;
8354 cursor = base + pivot + 1;
8355 val = pid - ids[cursor];
8360 } else if ( val > 0 ) {
8365 /* found, so it's a duplicate */
8374 for (n = ids[0]; n > cursor; n--)
8380 int mdb_reader_check(MDB_env *env, int *dead)
8382 unsigned int i, j, rdrs;
8384 MDB_PID_T *pids, pid;
8393 rdrs = env->me_txns->mti_numreaders;
8394 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
8398 mr = env->me_txns->mti_readers;
8399 for (i=0; i<rdrs; i++) {
8400 if (mr[i].mr_pid && mr[i].mr_pid != env->me_pid) {
8402 if (mdb_pid_insert(pids, pid) == 0) {
8403 if (!mdb_reader_pid(env, Pidcheck, pid)) {
8405 /* Recheck, a new process may have reused pid */
8406 if (!mdb_reader_pid(env, Pidcheck, pid)) {
8407 for (j=i; j<rdrs; j++)
8408 if (mr[j].mr_pid == pid) {
8409 DPRINTF(("clear stale reader pid %u txn %"Z"d",
8410 (unsigned) pid, mr[j].mr_txnid));
8415 UNLOCK_MUTEX_R(env);