2 * @brief Lightning memory-mapped database library
4 * A Btree-based database management library modeled loosely on the
5 * BerkeleyDB API, but much simplified.
8 * Copyright 2011-2014 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
78 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
79 #include <netinet/in.h>
80 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
83 #if defined(__APPLE__) || defined (BSD)
84 # define MDB_USE_POSIX_SEM 1
85 # define MDB_FDATASYNC fsync
86 #elif defined(ANDROID)
87 # define MDB_FDATASYNC fsync
92 #ifdef MDB_USE_POSIX_SEM
93 # define MDB_USE_HASH 1
94 #include <semaphore.h>
99 #include <valgrind/memcheck.h>
100 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
101 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
102 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
103 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
104 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
106 #define VGMEMP_CREATE(h,r,z)
107 #define VGMEMP_ALLOC(h,a,s)
108 #define VGMEMP_FREE(h,a)
109 #define VGMEMP_DESTROY(h)
110 #define VGMEMP_DEFINED(a,s)
114 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
115 /* Solaris just defines one or the other */
116 # define LITTLE_ENDIAN 1234
117 # define BIG_ENDIAN 4321
118 # ifdef _LITTLE_ENDIAN
119 # define BYTE_ORDER LITTLE_ENDIAN
121 # define BYTE_ORDER BIG_ENDIAN
124 # define BYTE_ORDER __BYTE_ORDER
128 #ifndef LITTLE_ENDIAN
129 #define LITTLE_ENDIAN __LITTLE_ENDIAN
132 #define BIG_ENDIAN __BIG_ENDIAN
135 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
136 #define MISALIGNED_OK 1
142 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
143 # error "Unknown or unsupported endianness (BYTE_ORDER)"
144 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
145 # error "Two's complement, reasonably sized integer types, please"
148 /** @defgroup internal LMDB Internals
151 /** @defgroup compat Compatibility Macros
152 * A bunch of macros to minimize the amount of platform-specific ifdefs
153 * needed throughout the rest of the code. When the features this library
154 * needs are similar enough to POSIX to be hidden in a one-or-two line
155 * replacement, this macro approach is used.
159 /** Wrapper around __func__, which is a C99 feature */
160 #if __STDC_VERSION__ >= 199901L
161 # define mdb_func_ __func__
162 #elif __GNUC__ >= 2 || _MSC_VER >= 1300
163 # define mdb_func_ __FUNCTION__
165 /* If a debug message says <mdb_unknown>(), update the #if statements above */
166 # define mdb_func_ "<mdb_unknown>"
170 #define MDB_USE_HASH 1
171 #define MDB_PIDLOCK 0
172 #define pthread_t DWORD
173 #define pthread_mutex_t HANDLE
174 #define pthread_key_t DWORD
175 #define pthread_self() GetCurrentThreadId()
176 #define pthread_key_create(x,y) \
177 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
178 #define pthread_key_delete(x) TlsFree(x)
179 #define pthread_getspecific(x) TlsGetValue(x)
180 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
181 #define pthread_mutex_unlock(x) ReleaseMutex(x)
182 #define pthread_mutex_lock(x) WaitForSingleObject(x, INFINITE)
183 #define LOCK_MUTEX_R(env) pthread_mutex_lock((env)->me_rmutex)
184 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock((env)->me_rmutex)
185 #define LOCK_MUTEX_W(env) pthread_mutex_lock((env)->me_wmutex)
186 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock((env)->me_wmutex)
187 #define getpid() GetCurrentProcessId()
188 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
189 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
190 #define ErrCode() GetLastError()
191 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
192 #define close(fd) (CloseHandle(fd) ? 0 : -1)
193 #define munmap(ptr,len) UnmapViewOfFile(ptr)
194 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
195 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
197 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
202 #define Z "z" /**< printf format modifier for size_t */
204 /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
205 #define MDB_PIDLOCK 1
207 #ifdef MDB_USE_POSIX_SEM
209 #define LOCK_MUTEX_R(env) mdb_sem_wait((env)->me_rmutex)
210 #define UNLOCK_MUTEX_R(env) sem_post((env)->me_rmutex)
211 #define LOCK_MUTEX_W(env) mdb_sem_wait((env)->me_wmutex)
212 #define UNLOCK_MUTEX_W(env) sem_post((env)->me_wmutex)
215 mdb_sem_wait(sem_t *sem)
218 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
223 /** Lock the reader mutex.
225 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
226 /** Unlock the reader mutex.
228 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
230 /** Lock the writer mutex.
231 * Only a single write transaction is allowed at a time. Other writers
232 * will block waiting for this mutex.
234 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
235 /** Unlock the writer mutex.
237 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
238 #endif /* MDB_USE_POSIX_SEM */
240 /** Get the error code for the last failed system function.
242 #define ErrCode() errno
244 /** An abstraction for a file handle.
245 * On POSIX systems file handles are small integers. On Windows
246 * they're opaque pointers.
250 /** A value for an invalid file handle.
251 * Mainly used to initialize file variables and signify that they are
254 #define INVALID_HANDLE_VALUE (-1)
256 /** Get the size of a memory page for the system.
257 * This is the basic size that the platform's memory manager uses, and is
258 * fundamental to the use of memory-mapped files.
260 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
263 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
266 #define MNAME_LEN (sizeof(pthread_mutex_t))
272 /** A flag for opening a file and requesting synchronous data writes.
273 * This is only used when writing a meta page. It's not strictly needed;
274 * we could just do a normal write and then immediately perform a flush.
275 * But if this flag is available it saves us an extra system call.
277 * @note If O_DSYNC is undefined but exists in /usr/include,
278 * preferably set some compiler flag to get the definition.
279 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
282 # define MDB_DSYNC O_DSYNC
286 /** Function for flushing the data of a file. Define this to fsync
287 * if fdatasync() is not supported.
289 #ifndef MDB_FDATASYNC
290 # define MDB_FDATASYNC fdatasync
294 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
305 /** A page number in the database.
306 * Note that 64 bit page numbers are overkill, since pages themselves
307 * already represent 12-13 bits of addressable memory, and the OS will
308 * always limit applications to a maximum of 63 bits of address space.
310 * @note In the #MDB_node structure, we only store 48 bits of this value,
311 * which thus limits us to only 60 bits of addressable data.
313 typedef MDB_ID pgno_t;
315 /** A transaction ID.
316 * See struct MDB_txn.mt_txnid for details.
318 typedef MDB_ID txnid_t;
320 /** @defgroup debug Debug Macros
324 /** Enable debug output. Needs variable argument macros (a C99 feature).
325 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
326 * read from and written to the database (used for free space management).
332 static int mdb_debug;
333 static txnid_t mdb_debug_start;
335 /** Print a debug message with printf formatting.
336 * Requires double parenthesis around 2 or more args.
338 # define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
339 # define DPRINTF0(fmt, ...) \
340 fprintf(stderr, "%s:%d " fmt "\n", mdb_func_, __LINE__, __VA_ARGS__)
342 # define DPRINTF(args) ((void) 0)
344 /** Print a debug string.
345 * The string is printed literally, with no format processing.
347 #define DPUTS(arg) DPRINTF(("%s", arg))
348 /** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
350 (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
353 /** @brief The maximum size of a database page.
355 * This is 32k, since it must fit in #MDB_page.%mp_upper.
357 * LMDB will use database pages < OS pages if needed.
358 * That causes more I/O in write transactions: The OS must
359 * know (read) the whole page before writing a partial page.
361 * Note that we don't currently support Huge pages. On Linux,
362 * regular data files cannot use Huge pages, and in general
363 * Huge pages aren't actually pageable. We rely on the OS
364 * demand-pager to read our data and page it out when memory
365 * pressure from other processes is high. So until OSs have
366 * actual paging support for Huge pages, they're not viable.
368 #define MAX_PAGESIZE 0x8000
370 /** The minimum number of keys required in a database page.
371 * Setting this to a larger value will place a smaller bound on the
372 * maximum size of a data item. Data items larger than this size will
373 * be pushed into overflow pages instead of being stored directly in
374 * the B-tree node. This value used to default to 4. With a page size
375 * of 4096 bytes that meant that any item larger than 1024 bytes would
376 * go into an overflow page. That also meant that on average 2-3KB of
377 * each overflow page was wasted space. The value cannot be lower than
378 * 2 because then there would no longer be a tree structure. With this
379 * value, items larger than 2KB will go into overflow pages, and on
380 * average only 1KB will be wasted.
382 #define MDB_MINKEYS 2
384 /** A stamp that identifies a file as an LMDB file.
385 * There's nothing special about this value other than that it is easily
386 * recognizable, and it will reflect any byte order mismatches.
388 #define MDB_MAGIC 0xBEEFC0DE
390 /** The version number for a database's datafile format. */
391 #define MDB_DATA_VERSION 1
392 /** The version number for a database's lockfile format. */
393 #define MDB_LOCK_VERSION 1
395 /** @brief The max size of a key we can write, or 0 for dynamic max.
397 * Define this as 0 to compute the max from the page size. 511
398 * is default for backwards compat: liblmdb <= 0.9.10 can break
399 * when modifying a DB with keys/dupsort data bigger than its max.
401 * Data items in an #MDB_DUPSORT database are also limited to
402 * this size, since they're actually keys of a sub-DB. Keys and
403 * #MDB_DUPSORT data items must fit on a node in a regular page.
405 #ifndef MDB_MAXKEYSIZE
406 #define MDB_MAXKEYSIZE 511
409 /** The maximum size of a key we can write to the environment. */
411 #define ENV_MAXKEY(env) (MDB_MAXKEYSIZE)
413 #define ENV_MAXKEY(env) ((env)->me_maxkey)
416 /** @brief The maximum size of a data item.
418 * We only store a 32 bit value for node sizes.
420 #define MAXDATASIZE 0xffffffffUL
423 /** Key size which fits in a #DKBUF.
426 #define DKBUF_MAXKEYSIZE ((MDB_MAXKEYSIZE) > 0 ? (MDB_MAXKEYSIZE) : 511)
429 * This is used for printing a hex dump of a key's contents.
431 #define DKBUF char kbuf[DKBUF_MAXKEYSIZE*2+1]
432 /** Display a key in hex.
434 * Invoke a function to display a key in hex.
436 #define DKEY(x) mdb_dkey(x, kbuf)
442 /** An invalid page number.
443 * Mainly used to denote an empty tree.
445 #define P_INVALID (~(pgno_t)0)
447 /** Test if the flags \b f are set in a flag word \b w. */
448 #define F_ISSET(w, f) (((w) & (f)) == (f))
450 /** Round \b n up to an even number. */
451 #define EVEN(n) (((n) + 1U) & -2) /* sign-extending -2 to match n+1U */
453 /** Used for offsets within a single page.
454 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
457 typedef uint16_t indx_t;
459 /** Default size of memory map.
460 * This is certainly too small for any actual applications. Apps should always set
461 * the size explicitly using #mdb_env_set_mapsize().
463 #define DEFAULT_MAPSIZE 1048576
465 /** @defgroup readers Reader Lock Table
466 * Readers don't acquire any locks for their data access. Instead, they
467 * simply record their transaction ID in the reader table. The reader
468 * mutex is needed just to find an empty slot in the reader table. The
469 * slot's address is saved in thread-specific data so that subsequent read
470 * transactions started by the same thread need no further locking to proceed.
472 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
474 * No reader table is used if the database is on a read-only filesystem, or
475 * if #MDB_NOLOCK is set.
477 * Since the database uses multi-version concurrency control, readers don't
478 * actually need any locking. This table is used to keep track of which
479 * readers are using data from which old transactions, so that we'll know
480 * when a particular old transaction is no longer in use. Old transactions
481 * that have discarded any data pages can then have those pages reclaimed
482 * for use by a later write transaction.
484 * The lock table is constructed such that reader slots are aligned with the
485 * processor's cache line size. Any slot is only ever used by one thread.
486 * This alignment guarantees that there will be no contention or cache
487 * thrashing as threads update their own slot info, and also eliminates
488 * any need for locking when accessing a slot.
490 * A writer thread will scan every slot in the table to determine the oldest
491 * outstanding reader transaction. Any freed pages older than this will be
492 * reclaimed by the writer. The writer doesn't use any locks when scanning
493 * this table. This means that there's no guarantee that the writer will
494 * see the most up-to-date reader info, but that's not required for correct
495 * operation - all we need is to know the upper bound on the oldest reader,
496 * we don't care at all about the newest reader. So the only consequence of
497 * reading stale information here is that old pages might hang around a
498 * while longer before being reclaimed. That's actually good anyway, because
499 * the longer we delay reclaiming old pages, the more likely it is that a
500 * string of contiguous pages can be found after coalescing old pages from
501 * many old transactions together.
504 /** Number of slots in the reader table.
505 * This value was chosen somewhat arbitrarily. 126 readers plus a
506 * couple mutexes fit exactly into 8KB on my development machine.
507 * Applications should set the table size using #mdb_env_set_maxreaders().
509 #define DEFAULT_READERS 126
511 /** The size of a CPU cache line in bytes. We want our lock structures
512 * aligned to this size to avoid false cache line sharing in the
514 * This value works for most CPUs. For Itanium this should be 128.
520 /** The information we store in a single slot of the reader table.
521 * In addition to a transaction ID, we also record the process and
522 * thread ID that owns a slot, so that we can detect stale information,
523 * e.g. threads or processes that went away without cleaning up.
524 * @note We currently don't check for stale records. We simply re-init
525 * the table when we know that we're the only process opening the
528 typedef struct MDB_rxbody {
529 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
530 * Multiple readers that start at the same time will probably have the
531 * same ID here. Again, it's not important to exclude them from
532 * anything; all we need to know is which version of the DB they
533 * started from so we can avoid overwriting any data used in that
534 * particular version.
537 /** The process ID of the process owning this reader txn. */
539 /** The thread ID of the thread owning this txn. */
543 /** The actual reader record, with cacheline padding. */
544 typedef struct MDB_reader {
547 /** shorthand for mrb_txnid */
548 #define mr_txnid mru.mrx.mrb_txnid
549 #define mr_pid mru.mrx.mrb_pid
550 #define mr_tid mru.mrx.mrb_tid
551 /** cache line alignment */
552 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
556 /** The header for the reader table.
557 * The table resides in a memory-mapped file. (This is a different file
558 * than is used for the main database.)
560 * For POSIX the actual mutexes reside in the shared memory of this
561 * mapped file. On Windows, mutexes are named objects allocated by the
562 * kernel; we store the mutex names in this mapped file so that other
563 * processes can grab them. This same approach is also used on
564 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
565 * process-shared POSIX mutexes. For these cases where a named object
566 * is used, the object name is derived from a 64 bit FNV hash of the
567 * environment pathname. As such, naming collisions are extremely
568 * unlikely. If a collision occurs, the results are unpredictable.
570 typedef struct MDB_txbody {
571 /** Stamp identifying this as an LMDB file. It must be set
574 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
576 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
577 char mtb_rmname[MNAME_LEN];
579 /** Mutex protecting access to this table.
580 * This is the reader lock that #LOCK_MUTEX_R acquires.
582 pthread_mutex_t mtb_mutex;
584 /** The ID of the last transaction committed to the database.
585 * This is recorded here only for convenience; the value can always
586 * be determined by reading the main database meta pages.
589 /** The number of slots that have been used in the reader table.
590 * This always records the maximum count, it is not decremented
591 * when readers release their slots.
593 unsigned mtb_numreaders;
596 /** The actual reader table definition. */
597 typedef struct MDB_txninfo {
600 #define mti_magic mt1.mtb.mtb_magic
601 #define mti_format mt1.mtb.mtb_format
602 #define mti_mutex mt1.mtb.mtb_mutex
603 #define mti_rmname mt1.mtb.mtb_rmname
604 #define mti_txnid mt1.mtb.mtb_txnid
605 #define mti_numreaders mt1.mtb.mtb_numreaders
606 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
609 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
610 char mt2_wmname[MNAME_LEN];
611 #define mti_wmname mt2.mt2_wmname
613 pthread_mutex_t mt2_wmutex;
614 #define mti_wmutex mt2.mt2_wmutex
616 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
618 MDB_reader mti_readers[1];
621 /** Lockfile format signature: version, features and field layout */
622 #define MDB_LOCK_FORMAT \
624 ((MDB_LOCK_VERSION) \
625 /* Flags which describe functionality */ \
626 + (((MDB_PIDLOCK) != 0) << 16)))
629 /** Common header for all page types.
630 * Overflow records occupy a number of contiguous pages with no
631 * headers on any page after the first.
633 typedef struct MDB_page {
634 #define mp_pgno mp_p.p_pgno
635 #define mp_next mp_p.p_next
637 pgno_t p_pgno; /**< page number */
638 void * p_next; /**< for in-memory list of freed structs */
641 /** @defgroup mdb_page Page Flags
643 * Flags for the page headers.
646 #define P_BRANCH 0x01 /**< branch page */
647 #define P_LEAF 0x02 /**< leaf page */
648 #define P_OVERFLOW 0x04 /**< overflow page */
649 #define P_META 0x08 /**< meta page */
650 #define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
651 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
652 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
653 #define P_LOOSE 0x4000 /**< page was dirtied then freed, can be reused */
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 LMDB 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 list of loose pages that became unused and may be reused
903 * in this transaction.
905 MDB_page *mt_loose_pgs;
906 /** The sorted list of dirty pages we temporarily wrote to disk
907 * because the dirty list was full. page numbers in here are
908 * shifted left by 1, deleted slots have the LSB set.
910 MDB_IDL mt_spill_pgs;
912 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
914 /** For read txns: This thread/txn's reader table slot, or NULL. */
917 /** Array of records for each DB known in the environment. */
919 /** Array of MDB_db records for each known DB */
921 /** @defgroup mt_dbflag Transaction DB Flags
925 #define DB_DIRTY 0x01 /**< DB was modified or is DUPSORT data */
926 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
927 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
928 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
930 /** In write txns, array of cursors for each DB */
931 MDB_cursor **mt_cursors;
932 /** Array of flags for each DB */
933 unsigned char *mt_dbflags;
934 /** Number of DB records in use. This number only ever increments;
935 * we don't decrement it when individual DB handles are closed.
939 /** @defgroup mdb_txn Transaction Flags
943 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
944 #define MDB_TXN_ERROR 0x02 /**< txn is unusable after an error */
945 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
946 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
948 unsigned int mt_flags; /**< @ref mdb_txn */
949 /** #dirty_list room: Array size - \#dirty pages visible to this txn.
950 * Includes ancestor txns' dirty pages not hidden by other txns'
951 * dirty/spilled pages. Thus commit(nested txn) has room to merge
952 * dirty_list into mt_parent after freeing hidden mt_parent pages.
954 unsigned int mt_dirty_room;
957 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
958 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
959 * raise this on a 64 bit machine.
961 #define CURSOR_STACK 32
965 /** Cursors are used for all DB operations.
966 * A cursor holds a path of (page pointer, key index) from the DB
967 * root to a position in the DB, plus other state. #MDB_DUPSORT
968 * cursors include an xcursor to the current data item. Write txns
969 * track their cursors and keep them up to date when data moves.
970 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
971 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
974 /** Next cursor on this DB in this txn */
976 /** Backup of the original cursor if this cursor is a shadow */
977 MDB_cursor *mc_backup;
978 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
979 struct MDB_xcursor *mc_xcursor;
980 /** The transaction that owns this cursor */
982 /** The database handle this cursor operates on */
984 /** The database record for this cursor */
986 /** The database auxiliary record for this cursor */
988 /** The @ref mt_dbflag for this database */
989 unsigned char *mc_dbflag;
990 unsigned short mc_snum; /**< number of pushed pages */
991 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
992 /** @defgroup mdb_cursor Cursor Flags
994 * Cursor state flags.
997 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
998 #define C_EOF 0x02 /**< No more data */
999 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
1000 #define C_DEL 0x08 /**< last op was a cursor_del */
1001 #define C_SPLITTING 0x20 /**< Cursor is in page_split */
1002 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
1004 unsigned int mc_flags; /**< @ref mdb_cursor */
1005 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
1006 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
1009 /** Context for sorted-dup records.
1010 * We could have gone to a fully recursive design, with arbitrarily
1011 * deep nesting of sub-databases. But for now we only handle these
1012 * levels - main DB, optional sub-DB, sorted-duplicate DB.
1014 typedef struct MDB_xcursor {
1015 /** A sub-cursor for traversing the Dup DB */
1016 MDB_cursor mx_cursor;
1017 /** The database record for this Dup DB */
1019 /** The auxiliary DB record for this Dup DB */
1021 /** The @ref mt_dbflag for this Dup DB */
1022 unsigned char mx_dbflag;
1025 /** State of FreeDB old pages, stored in the MDB_env */
1026 typedef struct MDB_pgstate {
1027 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1028 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1031 /** The database environment. */
1033 HANDLE me_fd; /**< The main data file */
1034 HANDLE me_lfd; /**< The lock file */
1035 HANDLE me_mfd; /**< just for writing the meta pages */
1036 /** Failed to update the meta page. Probably an I/O error. */
1037 #define MDB_FATAL_ERROR 0x80000000U
1038 /** Some fields are initialized. */
1039 #define MDB_ENV_ACTIVE 0x20000000U
1040 /** me_txkey is set */
1041 #define MDB_ENV_TXKEY 0x10000000U
1042 uint32_t me_flags; /**< @ref mdb_env */
1043 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1044 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1045 unsigned int me_maxreaders; /**< size of the reader table */
1046 unsigned int me_numreaders; /**< max numreaders set by this env */
1047 MDB_dbi me_numdbs; /**< number of DBs opened */
1048 MDB_dbi me_maxdbs; /**< size of the DB table */
1049 MDB_PID_T me_pid; /**< process ID of this env */
1050 char *me_path; /**< path to the DB files */
1051 char *me_map; /**< the memory map of the data file */
1052 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1053 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
1054 void *me_pbuf; /**< scratch area for DUPSORT put() */
1055 MDB_txn *me_txn; /**< current write transaction */
1056 size_t me_mapsize; /**< size of the data memory map */
1057 off_t me_size; /**< current file size */
1058 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1059 MDB_dbx *me_dbxs; /**< array of static DB info */
1060 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1061 pthread_key_t me_txkey; /**< thread-key for readers */
1062 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1063 # define me_pglast me_pgstate.mf_pglast
1064 # define me_pghead me_pgstate.mf_pghead
1065 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1066 /** IDL of pages that became unused in a write txn */
1067 MDB_IDL me_free_pgs;
1068 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1069 MDB_ID2L me_dirty_list;
1070 /** Max number of freelist items that can fit in a single overflow page */
1072 /** Max size of a node on a page */
1073 unsigned int me_nodemax;
1074 #if !(MDB_MAXKEYSIZE)
1075 unsigned int me_maxkey; /**< max size of a key */
1077 int me_live_reader; /**< have liveness lock in reader table */
1079 int me_pidquery; /**< Used in OpenProcess */
1080 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
1082 #elif defined(MDB_USE_POSIX_SEM)
1083 sem_t *me_rmutex; /* Shared mutexes are not supported */
1086 void *me_userctx; /**< User-settable context */
1087 MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
1090 /** Nested transaction */
1091 typedef struct MDB_ntxn {
1092 MDB_txn mnt_txn; /**< the transaction */
1093 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1096 /** max number of pages to commit in one writev() call */
1097 #define MDB_COMMIT_PAGES 64
1098 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1099 #undef MDB_COMMIT_PAGES
1100 #define MDB_COMMIT_PAGES IOV_MAX
1103 /** max bytes to write in one call */
1104 #define MAX_WRITE (0x80000000U >> (sizeof(ssize_t) == 4))
1106 /** Check \b txn and \b dbi arguments to a function */
1107 #define TXN_DBI_EXIST(txn, dbi) \
1108 ((txn) && (dbi) < (txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & DB_VALID))
1110 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1111 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1112 static int mdb_page_touch(MDB_cursor *mc);
1114 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp, int *lvl);
1115 static int mdb_page_search_root(MDB_cursor *mc,
1116 MDB_val *key, int modify);
1117 #define MDB_PS_MODIFY 1
1118 #define MDB_PS_ROOTONLY 2
1119 #define MDB_PS_FIRST 4
1120 #define MDB_PS_LAST 8
1121 static int mdb_page_search(MDB_cursor *mc,
1122 MDB_val *key, int flags);
1123 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1125 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1126 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1127 pgno_t newpgno, unsigned int nflags);
1129 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1130 static int mdb_env_pick_meta(const MDB_env *env);
1131 static int mdb_env_write_meta(MDB_txn *txn);
1132 #if !(defined(_WIN32) || defined(MDB_USE_POSIX_SEM)) /* Drop unused excl arg */
1133 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1135 static void mdb_env_close0(MDB_env *env, int excl);
1137 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1138 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1139 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1140 static void mdb_node_del(MDB_cursor *mc, int ksize);
1141 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1142 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
1143 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1144 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1145 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1147 static int mdb_rebalance(MDB_cursor *mc);
1148 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1150 static void mdb_cursor_pop(MDB_cursor *mc);
1151 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1153 static int mdb_cursor_del0(MDB_cursor *mc);
1154 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
1155 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1156 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1157 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1158 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1160 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1161 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1163 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1164 static void mdb_xcursor_init0(MDB_cursor *mc);
1165 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1167 static int mdb_drop0(MDB_cursor *mc, int subs);
1168 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1171 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1175 static SECURITY_DESCRIPTOR mdb_null_sd;
1176 static SECURITY_ATTRIBUTES mdb_all_sa;
1177 static int mdb_sec_inited;
1180 /** Return the library version info. */
1182 mdb_version(int *major, int *minor, int *patch)
1184 if (major) *major = MDB_VERSION_MAJOR;
1185 if (minor) *minor = MDB_VERSION_MINOR;
1186 if (patch) *patch = MDB_VERSION_PATCH;
1187 return MDB_VERSION_STRING;
1190 /** Table of descriptions for LMDB @ref errors */
1191 static char *const mdb_errstr[] = {
1192 "MDB_KEYEXIST: Key/data pair already exists",
1193 "MDB_NOTFOUND: No matching key/data pair found",
1194 "MDB_PAGE_NOTFOUND: Requested page not found",
1195 "MDB_CORRUPTED: Located page was wrong type",
1196 "MDB_PANIC: Update of meta page failed",
1197 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1198 "MDB_INVALID: File is not an LMDB file",
1199 "MDB_MAP_FULL: Environment mapsize limit reached",
1200 "MDB_DBS_FULL: Environment maxdbs limit reached",
1201 "MDB_READERS_FULL: Environment maxreaders limit reached",
1202 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1203 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1204 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1205 "MDB_PAGE_FULL: Internal error - page has no more space",
1206 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1207 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1208 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1209 "MDB_BAD_TXN: Transaction cannot recover - it must be aborted",
1210 "MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
1214 mdb_strerror(int err)
1218 return ("Successful return: 0");
1220 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1221 i = err - MDB_KEYEXIST;
1222 return mdb_errstr[i];
1225 return strerror(err);
1228 /** assert(3) variant in cursor context */
1229 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1230 /** assert(3) variant in transaction context */
1231 #define mdb_tassert(mc, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1232 /** assert(3) variant in environment context */
1233 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1236 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1237 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1240 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1241 const char *func, const char *file, int line)
1244 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1245 file, line, expr_txt, func);
1246 if (env->me_assert_func)
1247 env->me_assert_func(env, buf);
1248 fprintf(stderr, "%s\n", buf);
1252 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1256 /** Return the page number of \b mp which may be sub-page, for debug output */
1258 mdb_dbg_pgno(MDB_page *mp)
1261 COPY_PGNO(ret, mp->mp_pgno);
1265 /** Display a key in hexadecimal and return the address of the result.
1266 * @param[in] key the key to display
1267 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1268 * @return The key in hexadecimal form.
1271 mdb_dkey(MDB_val *key, char *buf)
1274 unsigned char *c = key->mv_data;
1280 if (key->mv_size > DKBUF_MAXKEYSIZE)
1281 return "MDB_MAXKEYSIZE";
1282 /* may want to make this a dynamic check: if the key is mostly
1283 * printable characters, print it as-is instead of converting to hex.
1287 for (i=0; i<key->mv_size; i++)
1288 ptr += sprintf(ptr, "%02x", *c++);
1290 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1296 mdb_leafnode_type(MDB_node *n)
1298 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1299 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1300 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1303 /** Display all the keys in the page. */
1305 mdb_page_list(MDB_page *mp)
1307 pgno_t pgno = mdb_dbg_pgno(mp);
1308 const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
1310 unsigned int i, nkeys, nsize, total = 0;
1314 switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1315 case P_BRANCH: type = "Branch page"; break;
1316 case P_LEAF: type = "Leaf page"; break;
1317 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1318 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1319 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1321 fprintf(stderr, "Overflow page %"Z"u pages %u%s\n",
1322 pgno, mp->mp_pages, state);
1325 fprintf(stderr, "Meta-page %"Z"u txnid %"Z"u\n",
1326 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1329 fprintf(stderr, "Bad page %"Z"u flags 0x%u\n", pgno, mp->mp_flags);
1333 nkeys = NUMKEYS(mp);
1334 fprintf(stderr, "%s %"Z"u numkeys %d%s\n", type, pgno, nkeys, state);
1336 for (i=0; i<nkeys; i++) {
1337 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1338 key.mv_size = nsize = mp->mp_pad;
1339 key.mv_data = LEAF2KEY(mp, i, nsize);
1341 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1344 node = NODEPTR(mp, i);
1345 key.mv_size = node->mn_ksize;
1346 key.mv_data = node->mn_data;
1347 nsize = NODESIZE + key.mv_size;
1348 if (IS_BRANCH(mp)) {
1349 fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
1353 if (F_ISSET(node->mn_flags, F_BIGDATA))
1354 nsize += sizeof(pgno_t);
1356 nsize += NODEDSZ(node);
1358 nsize += sizeof(indx_t);
1359 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1360 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1362 total = EVEN(total);
1364 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1365 IS_LEAF2(mp) ? PAGEHDRSZ : mp->mp_lower, total, SIZELEFT(mp));
1369 mdb_cursor_chk(MDB_cursor *mc)
1375 if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1376 for (i=0; i<mc->mc_top; i++) {
1378 node = NODEPTR(mp, mc->mc_ki[i]);
1379 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1382 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1388 /** Count all the pages in each DB and in the freelist
1389 * and make sure it matches the actual number of pages
1391 * All named DBs must be open for a correct count.
1393 static void mdb_audit(MDB_txn *txn)
1397 MDB_ID freecount, count;
1402 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1403 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1404 freecount += *(MDB_ID *)data.mv_data;
1405 mdb_tassert(txn, rc == MDB_NOTFOUND);
1408 for (i = 0; i<txn->mt_numdbs; i++) {
1410 if (!(txn->mt_dbflags[i] & DB_VALID))
1412 mdb_cursor_init(&mc, txn, i, &mx);
1413 if (txn->mt_dbs[i].md_root == P_INVALID)
1415 count += txn->mt_dbs[i].md_branch_pages +
1416 txn->mt_dbs[i].md_leaf_pages +
1417 txn->mt_dbs[i].md_overflow_pages;
1418 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1419 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1420 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
1423 mp = mc.mc_pg[mc.mc_top];
1424 for (j=0; j<NUMKEYS(mp); j++) {
1425 MDB_node *leaf = NODEPTR(mp, j);
1426 if (leaf->mn_flags & F_SUBDATA) {
1428 memcpy(&db, NODEDATA(leaf), sizeof(db));
1429 count += db.md_branch_pages + db.md_leaf_pages +
1430 db.md_overflow_pages;
1434 mdb_tassert(txn, rc == MDB_NOTFOUND);
1437 if (freecount + count + 2 /* metapages */ != txn->mt_next_pgno) {
1438 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1439 txn->mt_txnid, freecount, count+2, freecount+count+2, txn->mt_next_pgno);
1445 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1447 return txn->mt_dbxs[dbi].md_cmp(a, b);
1451 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1453 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1456 /** Allocate memory for a page.
1457 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1460 mdb_page_malloc(MDB_txn *txn, unsigned num)
1462 MDB_env *env = txn->mt_env;
1463 MDB_page *ret = env->me_dpages;
1464 size_t psize = env->me_psize, sz = psize, off;
1465 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1466 * For a single page alloc, we init everything after the page header.
1467 * For multi-page, we init the final page; if the caller needed that
1468 * many pages they will be filling in at least up to the last page.
1472 VGMEMP_ALLOC(env, ret, sz);
1473 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1474 env->me_dpages = ret->mp_next;
1477 psize -= off = PAGEHDRSZ;
1482 if ((ret = malloc(sz)) != NULL) {
1483 VGMEMP_ALLOC(env, ret, sz);
1484 if (!(env->me_flags & MDB_NOMEMINIT)) {
1485 memset((char *)ret + off, 0, psize);
1489 txn->mt_flags |= MDB_TXN_ERROR;
1493 /** Free a single page.
1494 * Saves single pages to a list, for future reuse.
1495 * (This is not used for multi-page overflow pages.)
1498 mdb_page_free(MDB_env *env, MDB_page *mp)
1500 mp->mp_next = env->me_dpages;
1501 VGMEMP_FREE(env, mp);
1502 env->me_dpages = mp;
1505 /** Free a dirty page */
1507 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1509 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1510 mdb_page_free(env, dp);
1512 /* large pages just get freed directly */
1513 VGMEMP_FREE(env, dp);
1518 /** Return all dirty pages to dpage list */
1520 mdb_dlist_free(MDB_txn *txn)
1522 MDB_env *env = txn->mt_env;
1523 MDB_ID2L dl = txn->mt_u.dirty_list;
1524 unsigned i, n = dl[0].mid;
1526 for (i = 1; i <= n; i++) {
1527 mdb_dpage_free(env, dl[i].mptr);
1532 /** Loosen or free a single page.
1533 * Saves single pages to a list for future reuse
1534 * in this same txn. It has been pulled from the freeDB
1535 * and already resides on the dirty list, but has been
1536 * deleted. Use these pages first before pulling again
1539 * If the page wasn't dirtied in this txn, just add it
1540 * to this txn's free list.
1543 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
1546 pgno_t pgno = mp->mp_pgno;
1548 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
1549 if (mc->mc_txn->mt_parent) {
1550 MDB_ID2 *dl = mc->mc_txn->mt_u.dirty_list;
1551 /* If txn has a parent, make sure the page is in our
1555 unsigned x = mdb_mid2l_search(dl, pgno);
1556 if (x <= dl[0].mid && dl[x].mid == pgno) {
1557 if (mp != dl[x].mptr) { /* bad cursor? */
1558 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1559 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
1560 return MDB_CORRUPTED;
1567 /* no parent txn, so it's just ours */
1572 pgno_t *pp = (pgno_t *)mp->mp_ptrs;
1574 mp->mp_next = mc->mc_txn->mt_loose_pgs;
1575 mc->mc_txn->mt_loose_pgs = mp;
1576 mp->mp_flags |= P_LOOSE;
1578 int rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, pgno);
1586 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
1587 * @param[in] mc A cursor handle for the current operation.
1588 * @param[in] pflags Flags of the pages to update:
1589 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1590 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
1591 * @return 0 on success, non-zero on failure.
1594 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
1596 enum { Mask = P_SUBP|P_DIRTY|P_KEEP };
1597 MDB_txn *txn = mc->mc_txn;
1603 int rc = MDB_SUCCESS, level;
1605 /* Mark pages seen by cursors */
1606 if (mc->mc_flags & C_UNTRACK)
1607 mc = NULL; /* will find mc in mt_cursors */
1608 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1609 for (; mc; mc=mc->mc_next) {
1610 if (!(mc->mc_flags & C_INITIALIZED))
1612 for (m3 = mc;; m3 = &mx->mx_cursor) {
1614 for (j=0; j<m3->mc_snum; j++) {
1616 if ((mp->mp_flags & Mask) == pflags)
1617 mp->mp_flags ^= P_KEEP;
1619 mx = m3->mc_xcursor;
1620 /* Proceed to mx if it is at a sub-database */
1621 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
1623 if (! (mp && (mp->mp_flags & P_LEAF)))
1625 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
1626 if (!(leaf->mn_flags & F_SUBDATA))
1634 /* Loose pages shouldn't be spilled */
1635 for (dp = txn->mt_loose_pgs; dp; dp=dp->mp_next) {
1636 if ((dp->mp_flags & Mask) == pflags)
1637 dp->mp_flags ^= P_KEEP;
1641 /* Mark dirty root pages */
1642 for (i=0; i<txn->mt_numdbs; i++) {
1643 if (txn->mt_dbflags[i] & DB_DIRTY) {
1644 pgno_t pgno = txn->mt_dbs[i].md_root;
1645 if (pgno == P_INVALID)
1647 if ((rc = mdb_page_get(txn, pgno, &dp, &level)) != MDB_SUCCESS)
1649 if ((dp->mp_flags & Mask) == pflags && level <= 1)
1650 dp->mp_flags ^= P_KEEP;
1658 static int mdb_page_flush(MDB_txn *txn, int keep);
1660 /** Spill pages from the dirty list back to disk.
1661 * This is intended to prevent running into #MDB_TXN_FULL situations,
1662 * but note that they may still occur in a few cases:
1663 * 1) our estimate of the txn size could be too small. Currently this
1664 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
1665 * 2) child txns may run out of space if their parents dirtied a
1666 * lot of pages and never spilled them. TODO: we probably should do
1667 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1668 * the parent's dirty_room is below a given threshold.
1670 * Otherwise, if not using nested txns, it is expected that apps will
1671 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1672 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1673 * If the txn never references them again, they can be left alone.
1674 * If the txn only reads them, they can be used without any fuss.
1675 * If the txn writes them again, they can be dirtied immediately without
1676 * going thru all of the work of #mdb_page_touch(). Such references are
1677 * handled by #mdb_page_unspill().
1679 * Also note, we never spill DB root pages, nor pages of active cursors,
1680 * because we'll need these back again soon anyway. And in nested txns,
1681 * we can't spill a page in a child txn if it was already spilled in a
1682 * parent txn. That would alter the parent txns' data even though
1683 * the child hasn't committed yet, and we'd have no way to undo it if
1684 * the child aborted.
1686 * @param[in] m0 cursor A cursor handle identifying the transaction and
1687 * database for which we are checking space.
1688 * @param[in] key For a put operation, the key being stored.
1689 * @param[in] data For a put operation, the data being stored.
1690 * @return 0 on success, non-zero on failure.
1693 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1695 MDB_txn *txn = m0->mc_txn;
1697 MDB_ID2L dl = txn->mt_u.dirty_list;
1698 unsigned int i, j, need;
1701 if (m0->mc_flags & C_SUB)
1704 /* Estimate how much space this op will take */
1705 i = m0->mc_db->md_depth;
1706 /* Named DBs also dirty the main DB */
1707 if (m0->mc_dbi > MAIN_DBI)
1708 i += txn->mt_dbs[MAIN_DBI].md_depth;
1709 /* For puts, roughly factor in the key+data size */
1711 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
1712 i += i; /* double it for good measure */
1715 if (txn->mt_dirty_room > i)
1718 if (!txn->mt_spill_pgs) {
1719 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
1720 if (!txn->mt_spill_pgs)
1723 /* purge deleted slots */
1724 MDB_IDL sl = txn->mt_spill_pgs;
1725 unsigned int num = sl[0];
1727 for (i=1; i<=num; i++) {
1734 /* Preserve pages which may soon be dirtied again */
1735 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
1738 /* Less aggressive spill - we originally spilled the entire dirty list,
1739 * with a few exceptions for cursor pages and DB root pages. But this
1740 * turns out to be a lot of wasted effort because in a large txn many
1741 * of those pages will need to be used again. So now we spill only 1/8th
1742 * of the dirty pages. Testing revealed this to be a good tradeoff,
1743 * better than 1/2, 1/4, or 1/10.
1745 if (need < MDB_IDL_UM_MAX / 8)
1746 need = MDB_IDL_UM_MAX / 8;
1748 /* Save the page IDs of all the pages we're flushing */
1749 /* flush from the tail forward, this saves a lot of shifting later on. */
1750 for (i=dl[0].mid; i && need; i--) {
1751 MDB_ID pn = dl[i].mid << 1;
1753 if (dp->mp_flags & P_KEEP)
1755 /* Can't spill twice, make sure it's not already in a parent's
1758 if (txn->mt_parent) {
1760 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1761 if (tx2->mt_spill_pgs) {
1762 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
1763 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
1764 dp->mp_flags |= P_KEEP;
1772 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
1776 mdb_midl_sort(txn->mt_spill_pgs);
1778 /* Flush the spilled part of dirty list */
1779 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
1782 /* Reset any dirty pages we kept that page_flush didn't see */
1783 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
1786 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
1790 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
1792 mdb_find_oldest(MDB_txn *txn)
1795 txnid_t mr, oldest = txn->mt_txnid - 1;
1796 if (txn->mt_env->me_txns) {
1797 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
1798 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
1809 /** Add a page to the txn's dirty list */
1811 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
1814 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
1816 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1817 insert = mdb_mid2l_append;
1819 insert = mdb_mid2l_insert;
1821 mid.mid = mp->mp_pgno;
1823 rc = insert(txn->mt_u.dirty_list, &mid);
1824 mdb_tassert(txn, rc == 0);
1825 txn->mt_dirty_room--;
1828 /** Allocate page numbers and memory for writing. Maintain me_pglast,
1829 * me_pghead and mt_next_pgno.
1831 * If there are free pages available from older transactions, they
1832 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
1833 * Do not modify the freedB, just merge freeDB records into me_pghead[]
1834 * and move me_pglast to say which records were consumed. Only this
1835 * function can create me_pghead and move me_pglast/mt_next_pgno.
1836 * @param[in] mc cursor A cursor handle identifying the transaction and
1837 * database for which we are allocating.
1838 * @param[in] num the number of pages to allocate.
1839 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
1840 * will always be satisfied by a single contiguous chunk of memory.
1841 * @return 0 on success, non-zero on failure.
1844 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
1846 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
1847 /* Get at most <Max_retries> more freeDB records once me_pghead
1848 * has enough pages. If not enough, use new pages from the map.
1849 * If <Paranoid> and mc is updating the freeDB, only get new
1850 * records if me_pghead is empty. Then the freelist cannot play
1851 * catch-up with itself by growing while trying to save it.
1853 enum { Paranoid = 1, Max_retries = 500 };
1855 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
1857 int rc, retry = num * 20;
1858 MDB_txn *txn = mc->mc_txn;
1859 MDB_env *env = txn->mt_env;
1860 pgno_t pgno, *mop = env->me_pghead;
1861 unsigned i, j, k, mop_len = mop ? mop[0] : 0, n2 = num-1;
1863 txnid_t oldest = 0, last;
1867 /* If there are any loose pages, just use them */
1868 if (num == 1 && txn->mt_loose_pgs) {
1870 np = txn->mt_loose_pgs;
1871 txn->mt_loose_pgs = np->mp_next;
1872 pp = (pgno_t *)np->mp_ptrs;
1880 /* If our dirty list is already full, we can't do anything */
1881 if (txn->mt_dirty_room == 0) {
1886 for (op = MDB_FIRST;; op = MDB_NEXT) {
1889 pgno_t *idl, old_id, new_id;
1891 /* Seek a big enough contiguous page range. Prefer
1892 * pages at the tail, just truncating the list.
1898 if (mop[i-n2] == pgno+n2)
1905 if (op == MDB_FIRST) { /* 1st iteration */
1906 /* Prepare to fetch more and coalesce */
1907 oldest = mdb_find_oldest(txn);
1908 last = env->me_pglast;
1909 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1912 key.mv_data = &last; /* will look up last+1 */
1913 key.mv_size = sizeof(last);
1915 if (Paranoid && mc->mc_dbi == FREE_DBI)
1918 if (Paranoid && retry < 0 && mop_len)
1922 /* Do not fetch more if the record will be too recent */
1925 rc = mdb_cursor_get(&m2, &key, NULL, op);
1927 if (rc == MDB_NOTFOUND)
1931 last = *(txnid_t*)key.mv_data;
1934 np = m2.mc_pg[m2.mc_top];
1935 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
1936 if ((rc = mdb_node_read(txn, leaf, &data)) != MDB_SUCCESS)
1939 idl = (MDB_ID *) data.mv_data;
1942 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
1947 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
1949 mop = env->me_pghead;
1951 env->me_pglast = last;
1953 DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
1954 last, txn->mt_dbs[FREE_DBI].md_root, i));
1956 DPRINTF(("IDL %"Z"u", idl[k]));
1958 /* Merge in descending sorted order */
1961 mop[0] = (pgno_t)-1;
1965 for (; old_id < new_id; old_id = mop[--j])
1972 /* Use new pages from the map when nothing suitable in the freeDB */
1974 pgno = txn->mt_next_pgno;
1975 if (pgno + num >= env->me_maxpg) {
1976 DPUTS("DB size maxed out");
1982 if (env->me_flags & MDB_WRITEMAP) {
1983 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
1985 if (!(np = mdb_page_malloc(txn, num))) {
1991 mop[0] = mop_len -= num;
1992 /* Move any stragglers down */
1993 for (j = i-num; j < mop_len; )
1994 mop[++j] = mop[++i];
1996 txn->mt_next_pgno = pgno + num;
1999 mdb_page_dirty(txn, np);
2005 txn->mt_flags |= MDB_TXN_ERROR;
2009 /** Copy the used portions of a non-overflow page.
2010 * @param[in] dst page to copy into
2011 * @param[in] src page to copy from
2012 * @param[in] psize size of a page
2015 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2017 enum { Align = sizeof(pgno_t) };
2018 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2020 /* If page isn't full, just copy the used portion. Adjust
2021 * alignment so memcpy may copy words instead of bytes.
2023 if ((unused &= -Align) && !IS_LEAF2(src)) {
2025 memcpy(dst, src, (lower + (Align-1)) & -Align);
2026 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2029 memcpy(dst, src, psize - unused);
2033 /** Pull a page off the txn's spill list, if present.
2034 * If a page being referenced was spilled to disk in this txn, bring
2035 * it back and make it dirty/writable again.
2036 * @param[in] txn the transaction handle.
2037 * @param[in] mp the page being referenced. It must not be dirty.
2038 * @param[out] ret the writable page, if any. ret is unchanged if
2039 * mp wasn't spilled.
2042 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2044 MDB_env *env = txn->mt_env;
2047 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2049 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2050 if (!tx2->mt_spill_pgs)
2052 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2053 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2056 if (txn->mt_dirty_room == 0)
2057 return MDB_TXN_FULL;
2058 if (IS_OVERFLOW(mp))
2062 if (env->me_flags & MDB_WRITEMAP) {
2065 np = mdb_page_malloc(txn, num);
2069 memcpy(np, mp, num * env->me_psize);
2071 mdb_page_copy(np, mp, env->me_psize);
2074 /* If in current txn, this page is no longer spilled.
2075 * If it happens to be the last page, truncate the spill list.
2076 * Otherwise mark it as deleted by setting the LSB.
2078 if (x == txn->mt_spill_pgs[0])
2079 txn->mt_spill_pgs[0]--;
2081 txn->mt_spill_pgs[x] |= 1;
2082 } /* otherwise, if belonging to a parent txn, the
2083 * page remains spilled until child commits
2086 mdb_page_dirty(txn, np);
2087 np->mp_flags |= P_DIRTY;
2095 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2096 * @param[in] mc cursor pointing to the page to be touched
2097 * @return 0 on success, non-zero on failure.
2100 mdb_page_touch(MDB_cursor *mc)
2102 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2103 MDB_txn *txn = mc->mc_txn;
2104 MDB_cursor *m2, *m3;
2108 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2109 if (txn->mt_flags & MDB_TXN_SPILLS) {
2111 rc = mdb_page_unspill(txn, mp, &np);
2117 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2118 (rc = mdb_page_alloc(mc, 1, &np)))
2121 DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
2122 mp->mp_pgno, pgno));
2123 mdb_cassert(mc, mp->mp_pgno != pgno);
2124 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2125 /* Update the parent page, if any, to point to the new page */
2127 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2128 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2129 SETPGNO(node, pgno);
2131 mc->mc_db->md_root = pgno;
2133 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2134 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2136 /* If txn has a parent, make sure the page is in our
2140 unsigned x = mdb_mid2l_search(dl, pgno);
2141 if (x <= dl[0].mid && dl[x].mid == pgno) {
2142 if (mp != dl[x].mptr) { /* bad cursor? */
2143 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2144 txn->mt_flags |= MDB_TXN_ERROR;
2145 return MDB_CORRUPTED;
2150 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2152 np = mdb_page_malloc(txn, 1);
2157 rc = mdb_mid2l_insert(dl, &mid);
2158 mdb_cassert(mc, rc == 0);
2163 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2165 np->mp_flags |= P_DIRTY;
2168 /* Adjust cursors pointing to mp */
2169 mc->mc_pg[mc->mc_top] = np;
2170 m2 = txn->mt_cursors[mc->mc_dbi];
2171 if (mc->mc_flags & C_SUB) {
2172 for (; m2; m2=m2->mc_next) {
2173 m3 = &m2->mc_xcursor->mx_cursor;
2174 if (m3->mc_snum < mc->mc_snum) continue;
2175 if (m3->mc_pg[mc->mc_top] == mp)
2176 m3->mc_pg[mc->mc_top] = np;
2179 for (; m2; m2=m2->mc_next) {
2180 if (m2->mc_snum < mc->mc_snum) continue;
2181 if (m2->mc_pg[mc->mc_top] == mp) {
2182 m2->mc_pg[mc->mc_top] = np;
2183 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
2185 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
2187 MDB_node *leaf = NODEPTR(np, mc->mc_ki[mc->mc_top]);
2188 if (!(leaf->mn_flags & F_SUBDATA))
2189 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
2197 txn->mt_flags |= MDB_TXN_ERROR;
2202 mdb_env_sync(MDB_env *env, int force)
2205 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2206 if (env->me_flags & MDB_WRITEMAP) {
2207 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2208 ? MS_ASYNC : MS_SYNC;
2209 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
2212 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2216 if (MDB_FDATASYNC(env->me_fd))
2223 /** Back up parent txn's cursors, then grab the originals for tracking */
2225 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2227 MDB_cursor *mc, *bk;
2232 for (i = src->mt_numdbs; --i >= 0; ) {
2233 if ((mc = src->mt_cursors[i]) != NULL) {
2234 size = sizeof(MDB_cursor);
2236 size += sizeof(MDB_xcursor);
2237 for (; mc; mc = bk->mc_next) {
2243 mc->mc_db = &dst->mt_dbs[i];
2244 /* Kill pointers into src - and dst to reduce abuse: The
2245 * user may not use mc until dst ends. Otherwise we'd...
2247 mc->mc_txn = NULL; /* ...set this to dst */
2248 mc->mc_dbflag = NULL; /* ...and &dst->mt_dbflags[i] */
2249 if ((mx = mc->mc_xcursor) != NULL) {
2250 *(MDB_xcursor *)(bk+1) = *mx;
2251 mx->mx_cursor.mc_txn = NULL; /* ...and dst. */
2253 mc->mc_next = dst->mt_cursors[i];
2254 dst->mt_cursors[i] = mc;
2261 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2262 * @param[in] txn the transaction handle.
2263 * @param[in] merge true to keep changes to parent cursors, false to revert.
2264 * @return 0 on success, non-zero on failure.
2267 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2269 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2273 for (i = txn->mt_numdbs; --i >= 0; ) {
2274 for (mc = cursors[i]; mc; mc = next) {
2276 if ((bk = mc->mc_backup) != NULL) {
2278 /* Commit changes to parent txn */
2279 mc->mc_next = bk->mc_next;
2280 mc->mc_backup = bk->mc_backup;
2281 mc->mc_txn = bk->mc_txn;
2282 mc->mc_db = bk->mc_db;
2283 mc->mc_dbflag = bk->mc_dbflag;
2284 if ((mx = mc->mc_xcursor) != NULL)
2285 mx->mx_cursor.mc_txn = bk->mc_txn;
2287 /* Abort nested txn */
2289 if ((mx = mc->mc_xcursor) != NULL)
2290 *mx = *(MDB_xcursor *)(bk+1);
2294 /* Only malloced cursors are permanently tracked. */
2302 #define mdb_txn_reset0(txn, act) mdb_txn_reset0(txn)
2305 mdb_txn_reset0(MDB_txn *txn, const char *act);
2307 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2313 Pidset = F_SETLK, Pidcheck = F_GETLK
2317 /** Set or check a pid lock. Set returns 0 on success.
2318 * Check returns 0 if the process is certainly dead, nonzero if it may
2319 * be alive (the lock exists or an error happened so we do not know).
2321 * On Windows Pidset is a no-op, we merely check for the existence
2322 * of the process with the given pid. On POSIX we use a single byte
2323 * lock on the lockfile, set at an offset equal to the pid.
2326 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2328 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2331 if (op == Pidcheck) {
2332 h = OpenProcess(env->me_pidquery, FALSE, pid);
2333 /* No documented "no such process" code, but other program use this: */
2335 return ErrCode() != ERROR_INVALID_PARAMETER;
2336 /* A process exists until all handles to it close. Has it exited? */
2337 ret = WaitForSingleObject(h, 0) != 0;
2344 struct flock lock_info;
2345 memset(&lock_info, 0, sizeof(lock_info));
2346 lock_info.l_type = F_WRLCK;
2347 lock_info.l_whence = SEEK_SET;
2348 lock_info.l_start = pid;
2349 lock_info.l_len = 1;
2350 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2351 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2353 } else if ((rc = ErrCode()) == EINTR) {
2361 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2362 * @param[in] txn the transaction handle to initialize
2363 * @return 0 on success, non-zero on failure.
2366 mdb_txn_renew0(MDB_txn *txn)
2368 MDB_env *env = txn->mt_env;
2369 MDB_txninfo *ti = env->me_txns;
2373 int rc, new_notls = 0;
2376 txn->mt_numdbs = env->me_numdbs;
2377 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
2379 if (txn->mt_flags & MDB_TXN_RDONLY) {
2381 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2382 txn->mt_txnid = meta->mm_txnid;
2383 txn->mt_u.reader = NULL;
2385 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2386 pthread_getspecific(env->me_txkey);
2388 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2389 return MDB_BAD_RSLOT;
2391 MDB_PID_T pid = env->me_pid;
2392 pthread_t tid = pthread_self();
2394 if (!env->me_live_reader) {
2395 rc = mdb_reader_pid(env, Pidset, pid);
2398 env->me_live_reader = 1;
2402 nr = ti->mti_numreaders;
2403 for (i=0; i<nr; i++)
2404 if (ti->mti_readers[i].mr_pid == 0)
2406 if (i == env->me_maxreaders) {
2407 UNLOCK_MUTEX_R(env);
2408 return MDB_READERS_FULL;
2410 ti->mti_readers[i].mr_pid = pid;
2411 ti->mti_readers[i].mr_tid = tid;
2413 ti->mti_numreaders = ++nr;
2414 /* Save numreaders for un-mutexed mdb_env_close() */
2415 env->me_numreaders = nr;
2416 UNLOCK_MUTEX_R(env);
2418 r = &ti->mti_readers[i];
2419 new_notls = (env->me_flags & MDB_NOTLS);
2420 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2425 txn->mt_txnid = r->mr_txnid = ti->mti_txnid;
2426 txn->mt_u.reader = r;
2427 meta = env->me_metas[txn->mt_txnid & 1];
2433 txn->mt_txnid = ti->mti_txnid;
2434 meta = env->me_metas[txn->mt_txnid & 1];
2436 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2437 txn->mt_txnid = meta->mm_txnid;
2441 if (txn->mt_txnid == mdb_debug_start)
2444 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2445 txn->mt_u.dirty_list = env->me_dirty_list;
2446 txn->mt_u.dirty_list[0].mid = 0;
2447 txn->mt_free_pgs = env->me_free_pgs;
2448 txn->mt_free_pgs[0] = 0;
2449 txn->mt_spill_pgs = NULL;
2453 /* Copy the DB info and flags */
2454 memcpy(txn->mt_dbs, meta->mm_dbs, 2 * sizeof(MDB_db));
2456 /* Moved to here to avoid a data race in read TXNs */
2457 txn->mt_next_pgno = meta->mm_last_pg+1;
2459 for (i=2; i<txn->mt_numdbs; i++) {
2460 x = env->me_dbflags[i];
2461 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2462 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_STALE : 0;
2464 txn->mt_dbflags[0] = txn->mt_dbflags[1] = DB_VALID;
2466 if (env->me_maxpg < txn->mt_next_pgno) {
2467 mdb_txn_reset0(txn, "renew0-mapfail");
2469 txn->mt_u.reader->mr_pid = 0;
2470 txn->mt_u.reader = NULL;
2472 return MDB_MAP_RESIZED;
2479 mdb_txn_renew(MDB_txn *txn)
2483 if (!txn || txn->mt_dbxs) /* A reset txn has mt_dbxs==NULL */
2486 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
2487 DPUTS("environment had fatal error, must shutdown!");
2491 rc = mdb_txn_renew0(txn);
2492 if (rc == MDB_SUCCESS) {
2493 DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2494 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2495 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2501 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2505 int rc, size, tsize = sizeof(MDB_txn);
2507 if (env->me_flags & MDB_FATAL_ERROR) {
2508 DPUTS("environment had fatal error, must shutdown!");
2511 if ((env->me_flags & MDB_RDONLY) && !(flags & MDB_RDONLY))
2514 /* Nested transactions: Max 1 child, write txns only, no writemap */
2515 if (parent->mt_child ||
2516 (flags & MDB_RDONLY) ||
2517 (parent->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR)) ||
2518 (env->me_flags & MDB_WRITEMAP))
2520 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
2522 tsize = sizeof(MDB_ntxn);
2524 size = tsize + env->me_maxdbs * (sizeof(MDB_db)+1);
2525 if (!(flags & MDB_RDONLY))
2526 size += env->me_maxdbs * sizeof(MDB_cursor *);
2528 if ((txn = calloc(1, size)) == NULL) {
2529 DPRINTF(("calloc: %s", strerror(ErrCode())));
2532 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2533 if (flags & MDB_RDONLY) {
2534 txn->mt_flags |= MDB_TXN_RDONLY;
2535 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
2537 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2538 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
2544 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2545 if (!txn->mt_u.dirty_list ||
2546 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2548 free(txn->mt_u.dirty_list);
2552 txn->mt_txnid = parent->mt_txnid;
2553 txn->mt_dirty_room = parent->mt_dirty_room;
2554 txn->mt_u.dirty_list[0].mid = 0;
2555 txn->mt_spill_pgs = NULL;
2556 txn->mt_next_pgno = parent->mt_next_pgno;
2557 parent->mt_child = txn;
2558 txn->mt_parent = parent;
2559 txn->mt_numdbs = parent->mt_numdbs;
2560 txn->mt_flags = parent->mt_flags;
2561 txn->mt_dbxs = parent->mt_dbxs;
2562 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2563 /* Copy parent's mt_dbflags, but clear DB_NEW */
2564 for (i=0; i<txn->mt_numdbs; i++)
2565 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2567 ntxn = (MDB_ntxn *)txn;
2568 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2569 if (env->me_pghead) {
2570 size = MDB_IDL_SIZEOF(env->me_pghead);
2571 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2573 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2578 rc = mdb_cursor_shadow(parent, txn);
2580 mdb_txn_reset0(txn, "beginchild-fail");
2582 rc = mdb_txn_renew0(txn);
2588 DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2589 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2590 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
2597 mdb_txn_env(MDB_txn *txn)
2599 if(!txn) return NULL;
2603 /** Export or close DBI handles opened in this txn. */
2605 mdb_dbis_update(MDB_txn *txn, int keep)
2608 MDB_dbi n = txn->mt_numdbs;
2609 MDB_env *env = txn->mt_env;
2610 unsigned char *tdbflags = txn->mt_dbflags;
2612 for (i = n; --i >= 2;) {
2613 if (tdbflags[i] & DB_NEW) {
2615 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2617 char *ptr = env->me_dbxs[i].md_name.mv_data;
2618 env->me_dbxs[i].md_name.mv_data = NULL;
2619 env->me_dbxs[i].md_name.mv_size = 0;
2620 env->me_dbflags[i] = 0;
2625 if (keep && env->me_numdbs < n)
2629 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
2630 * May be called twice for readonly txns: First reset it, then abort.
2631 * @param[in] txn the transaction handle to reset
2632 * @param[in] act why the transaction is being reset
2635 mdb_txn_reset0(MDB_txn *txn, const char *act)
2637 MDB_env *env = txn->mt_env;
2639 /* Close any DBI handles opened in this txn */
2640 mdb_dbis_update(txn, 0);
2642 DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2643 act, txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2644 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
2646 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2647 if (txn->mt_u.reader) {
2648 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2649 if (!(env->me_flags & MDB_NOTLS))
2650 txn->mt_u.reader = NULL; /* txn does not own reader */
2652 txn->mt_numdbs = 0; /* close nothing if called again */
2653 txn->mt_dbxs = NULL; /* mark txn as reset */
2655 mdb_cursors_close(txn, 0);
2657 if (!(env->me_flags & MDB_WRITEMAP)) {
2658 mdb_dlist_free(txn);
2660 mdb_midl_free(env->me_pghead);
2662 if (txn->mt_parent) {
2663 txn->mt_parent->mt_child = NULL;
2664 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2665 mdb_midl_free(txn->mt_free_pgs);
2666 mdb_midl_free(txn->mt_spill_pgs);
2667 free(txn->mt_u.dirty_list);
2671 if (mdb_midl_shrink(&txn->mt_free_pgs))
2672 env->me_free_pgs = txn->mt_free_pgs;
2673 env->me_pghead = NULL;
2677 /* The writer mutex was locked in mdb_txn_begin. */
2679 UNLOCK_MUTEX_W(env);
2684 mdb_txn_reset(MDB_txn *txn)
2689 /* This call is only valid for read-only txns */
2690 if (!(txn->mt_flags & MDB_TXN_RDONLY))
2693 mdb_txn_reset0(txn, "reset");
2697 mdb_txn_abort(MDB_txn *txn)
2703 mdb_txn_abort(txn->mt_child);
2705 mdb_txn_reset0(txn, "abort");
2706 /* Free reader slot tied to this txn (if MDB_NOTLS && writable FS) */
2707 if ((txn->mt_flags & MDB_TXN_RDONLY) && txn->mt_u.reader)
2708 txn->mt_u.reader->mr_pid = 0;
2713 /** Save the freelist as of this transaction to the freeDB.
2714 * This changes the freelist. Keep trying until it stabilizes.
2717 mdb_freelist_save(MDB_txn *txn)
2719 /* env->me_pghead[] can grow and shrink during this call.
2720 * env->me_pglast and txn->mt_free_pgs[] can only grow.
2721 * Page numbers cannot disappear from txn->mt_free_pgs[].
2724 MDB_env *env = txn->mt_env;
2725 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
2726 txnid_t pglast = 0, head_id = 0;
2727 pgno_t freecnt = 0, *free_pgs, *mop;
2728 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
2730 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
2732 if (env->me_pghead) {
2733 /* Make sure first page of freeDB is touched and on freelist */
2734 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
2735 if (rc && rc != MDB_NOTFOUND)
2739 /* Dispose of loose pages. Usually they will have all
2740 * been used up by the time we get here.
2742 if (txn->mt_loose_pgs) {
2743 MDB_page *mp = txn->mt_loose_pgs;
2745 /* Just return them to freeDB */
2746 if (env->me_pghead) {
2748 mop = env->me_pghead;
2751 pp = (pgno_t *)mp->mp_ptrs;
2754 for (i = mop[0]; i && mop[i] < pg; i--)
2761 /* Oh well, they were wasted. Put on freelist */
2763 pp = (pgno_t *)mp->mp_ptrs;
2764 mdb_midl_append(&txn->mt_free_pgs, *pp);
2768 txn->mt_loose_pgs = NULL;
2771 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
2772 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
2773 ? SSIZE_MAX : maxfree_1pg;
2776 /* Come back here after each Put() in case freelist changed */
2781 /* If using records from freeDB which we have not yet
2782 * deleted, delete them and any we reserved for me_pghead.
2784 while (pglast < env->me_pglast) {
2785 rc = mdb_cursor_first(&mc, &key, NULL);
2788 pglast = head_id = *(txnid_t *)key.mv_data;
2789 total_room = head_room = 0;
2790 mdb_tassert(txn, pglast <= env->me_pglast);
2791 rc = mdb_cursor_del(&mc, 0);
2796 /* Save the IDL of pages freed by this txn, to a single record */
2797 if (freecnt < txn->mt_free_pgs[0]) {
2799 /* Make sure last page of freeDB is touched and on freelist */
2800 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
2801 if (rc && rc != MDB_NOTFOUND)
2804 free_pgs = txn->mt_free_pgs;
2805 /* Write to last page of freeDB */
2806 key.mv_size = sizeof(txn->mt_txnid);
2807 key.mv_data = &txn->mt_txnid;
2809 freecnt = free_pgs[0];
2810 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
2811 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2814 /* Retry if mt_free_pgs[] grew during the Put() */
2815 free_pgs = txn->mt_free_pgs;
2816 } while (freecnt < free_pgs[0]);
2817 mdb_midl_sort(free_pgs);
2818 memcpy(data.mv_data, free_pgs, data.mv_size);
2821 unsigned int i = free_pgs[0];
2822 DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
2823 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
2825 DPRINTF(("IDL %"Z"u", free_pgs[i]));
2831 mop = env->me_pghead;
2832 mop_len = mop ? mop[0] : 0;
2834 /* Reserve records for me_pghead[]. Split it if multi-page,
2835 * to avoid searching freeDB for a page range. Use keys in
2836 * range [1,me_pglast]: Smaller than txnid of oldest reader.
2838 if (total_room >= mop_len) {
2839 if (total_room == mop_len || --more < 0)
2841 } else if (head_room >= maxfree_1pg && head_id > 1) {
2842 /* Keep current record (overflow page), add a new one */
2846 /* (Re)write {key = head_id, IDL length = head_room} */
2847 total_room -= head_room;
2848 head_room = mop_len - total_room;
2849 if (head_room > maxfree_1pg && head_id > 1) {
2850 /* Overflow multi-page for part of me_pghead */
2851 head_room /= head_id; /* amortize page sizes */
2852 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
2853 } else if (head_room < 0) {
2854 /* Rare case, not bothering to delete this record */
2857 key.mv_size = sizeof(head_id);
2858 key.mv_data = &head_id;
2859 data.mv_size = (head_room + 1) * sizeof(pgno_t);
2860 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2863 /* IDL is initially empty, zero out at least the length */
2864 pgs = (pgno_t *)data.mv_data;
2865 j = head_room > clean_limit ? head_room : 0;
2869 total_room += head_room;
2872 /* Fill in the reserved me_pghead records */
2878 rc = mdb_cursor_first(&mc, &key, &data);
2879 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
2880 txnid_t id = *(txnid_t *)key.mv_data;
2881 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
2884 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
2886 if (len > mop_len) {
2888 data.mv_size = (len + 1) * sizeof(MDB_ID);
2890 data.mv_data = mop -= len;
2893 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
2895 if (rc || !(mop_len -= len))
2902 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
2903 * @param[in] txn the transaction that's being committed
2904 * @param[in] keep number of initial pages in dirty_list to keep dirty.
2905 * @return 0 on success, non-zero on failure.
2908 mdb_page_flush(MDB_txn *txn, int keep)
2910 MDB_env *env = txn->mt_env;
2911 MDB_ID2L dl = txn->mt_u.dirty_list;
2912 unsigned psize = env->me_psize, j;
2913 int i, pagecount = dl[0].mid, rc;
2914 size_t size = 0, pos = 0;
2916 MDB_page *dp = NULL;
2920 struct iovec iov[MDB_COMMIT_PAGES];
2921 ssize_t wpos = 0, wsize = 0, wres;
2922 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
2928 if (env->me_flags & MDB_WRITEMAP) {
2929 /* Clear dirty flags */
2930 while (++i <= pagecount) {
2932 /* Don't flush this page yet */
2933 if (dp->mp_flags & P_KEEP) {
2934 dp->mp_flags ^= P_KEEP;
2938 dp->mp_flags &= ~P_DIRTY;
2943 /* Write the pages */
2945 if (++i <= pagecount) {
2947 /* Don't flush this page yet */
2948 if (dp->mp_flags & P_KEEP) {
2949 dp->mp_flags ^= P_KEEP;
2954 /* clear dirty flag */
2955 dp->mp_flags &= ~P_DIRTY;
2958 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
2963 /* Windows actually supports scatter/gather I/O, but only on
2964 * unbuffered file handles. Since we're relying on the OS page
2965 * cache for all our data, that's self-defeating. So we just
2966 * write pages one at a time. We use the ov structure to set
2967 * the write offset, to at least save the overhead of a Seek
2970 DPRINTF(("committing page %"Z"u", pgno));
2971 memset(&ov, 0, sizeof(ov));
2972 ov.Offset = pos & 0xffffffff;
2973 ov.OffsetHigh = pos >> 16 >> 16;
2974 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
2976 DPRINTF(("WriteFile: %d", rc));
2980 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
2981 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
2983 /* Write previous page(s) */
2984 #ifdef MDB_USE_PWRITEV
2985 wres = pwritev(env->me_fd, iov, n, wpos);
2988 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
2990 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
2992 DPRINTF(("lseek: %s", strerror(rc)));
2995 wres = writev(env->me_fd, iov, n);
2998 if (wres != wsize) {
3001 DPRINTF(("Write error: %s", strerror(rc)));
3003 rc = EIO; /* TODO: Use which error code? */
3004 DPUTS("short write, filesystem full?");
3015 DPRINTF(("committing page %"Z"u", pgno));
3016 next_pos = pos + size;
3017 iov[n].iov_len = size;
3018 iov[n].iov_base = (char *)dp;
3024 for (i = keep; ++i <= pagecount; ) {
3026 /* This is a page we skipped above */
3029 dl[j].mid = dp->mp_pgno;
3032 mdb_dpage_free(env, dp);
3037 txn->mt_dirty_room += i - j;
3043 mdb_txn_commit(MDB_txn *txn)
3049 if (txn == NULL || txn->mt_env == NULL)
3052 if (txn->mt_child) {
3053 rc = mdb_txn_commit(txn->mt_child);
3054 txn->mt_child = NULL;
3061 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3062 mdb_dbis_update(txn, 1);
3063 txn->mt_numdbs = 2; /* so txn_abort() doesn't close any new handles */
3068 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
3069 DPUTS("error flag is set, can't commit");
3071 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3076 if (txn->mt_parent) {
3077 MDB_txn *parent = txn->mt_parent;
3080 unsigned x, y, len, ps_len;
3082 /* Append our free list to parent's */
3083 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3086 mdb_midl_free(txn->mt_free_pgs);
3087 /* Failures after this must either undo the changes
3088 * to the parent or set MDB_TXN_ERROR in the parent.
3091 parent->mt_next_pgno = txn->mt_next_pgno;
3092 parent->mt_flags = txn->mt_flags;
3094 /* Merge our cursors into parent's and close them */
3095 mdb_cursors_close(txn, 1);
3097 /* Update parent's DB table. */
3098 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3099 parent->mt_numdbs = txn->mt_numdbs;
3100 parent->mt_dbflags[0] = txn->mt_dbflags[0];
3101 parent->mt_dbflags[1] = txn->mt_dbflags[1];
3102 for (i=2; i<txn->mt_numdbs; i++) {
3103 /* preserve parent's DB_NEW status */
3104 x = parent->mt_dbflags[i] & DB_NEW;
3105 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3108 dst = parent->mt_u.dirty_list;
3109 src = txn->mt_u.dirty_list;
3110 /* Remove anything in our dirty list from parent's spill list */
3111 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3113 pspill[0] = (pgno_t)-1;
3114 /* Mark our dirty pages as deleted in parent spill list */
3115 for (i=0, len=src[0].mid; ++i <= len; ) {
3116 MDB_ID pn = src[i].mid << 1;
3117 while (pn > pspill[x])
3119 if (pn == pspill[x]) {
3124 /* Squash deleted pagenums if we deleted any */
3125 for (x=y; ++x <= ps_len; )
3126 if (!(pspill[x] & 1))
3127 pspill[++y] = pspill[x];
3131 /* Find len = length of merging our dirty list with parent's */
3133 dst[0].mid = 0; /* simplify loops */
3134 if (parent->mt_parent) {
3135 len = x + src[0].mid;
3136 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3137 for (i = x; y && i; y--) {
3138 pgno_t yp = src[y].mid;
3139 while (yp < dst[i].mid)
3141 if (yp == dst[i].mid) {
3146 } else { /* Simplify the above for single-ancestor case */
3147 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3149 /* Merge our dirty list with parent's */
3151 for (i = len; y; dst[i--] = src[y--]) {
3152 pgno_t yp = src[y].mid;
3153 while (yp < dst[x].mid)
3154 dst[i--] = dst[x--];
3155 if (yp == dst[x].mid)
3156 free(dst[x--].mptr);
3158 mdb_tassert(txn, i == x);
3160 free(txn->mt_u.dirty_list);
3161 parent->mt_dirty_room = txn->mt_dirty_room;
3162 if (txn->mt_spill_pgs) {
3163 if (parent->mt_spill_pgs) {
3164 /* TODO: Prevent failure here, so parent does not fail */
3165 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3167 parent->mt_flags |= MDB_TXN_ERROR;
3168 mdb_midl_free(txn->mt_spill_pgs);
3169 mdb_midl_sort(parent->mt_spill_pgs);
3171 parent->mt_spill_pgs = txn->mt_spill_pgs;
3175 parent->mt_child = NULL;
3176 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3181 if (txn != env->me_txn) {
3182 DPUTS("attempt to commit unknown transaction");
3187 mdb_cursors_close(txn, 0);
3189 if (!txn->mt_u.dirty_list[0].mid &&
3190 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
3193 DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
3194 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3196 /* Update DB root pointers */
3197 if (txn->mt_numdbs > 2) {
3201 data.mv_size = sizeof(MDB_db);
3203 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3204 for (i = 2; i < txn->mt_numdbs; i++) {
3205 if (txn->mt_dbflags[i] & DB_DIRTY) {
3206 data.mv_data = &txn->mt_dbs[i];
3207 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
3214 rc = mdb_freelist_save(txn);
3218 mdb_midl_free(env->me_pghead);
3219 env->me_pghead = NULL;
3220 if (mdb_midl_shrink(&txn->mt_free_pgs))
3221 env->me_free_pgs = txn->mt_free_pgs;
3227 if ((rc = mdb_page_flush(txn, 0)) ||
3228 (rc = mdb_env_sync(env, 0)) ||
3229 (rc = mdb_env_write_meta(txn)))
3235 mdb_dbis_update(txn, 1);
3238 UNLOCK_MUTEX_W(env);
3248 /** Read the environment parameters of a DB environment before
3249 * mapping it into memory.
3250 * @param[in] env the environment handle
3251 * @param[out] meta address of where to store the meta information
3252 * @return 0 on success, non-zero on failure.
3255 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3261 enum { Size = sizeof(pbuf) };
3263 /* We don't know the page size yet, so use a minimum value.
3264 * Read both meta pages so we can use the latest one.
3267 for (i=off=0; i<2; i++, off = meta->mm_psize) {
3271 memset(&ov, 0, sizeof(ov));
3273 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3274 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3277 rc = pread(env->me_fd, &pbuf, Size, off);
3280 if (rc == 0 && off == 0)
3282 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3283 DPRINTF(("read: %s", mdb_strerror(rc)));
3287 p = (MDB_page *)&pbuf;
3289 if (!F_ISSET(p->mp_flags, P_META)) {
3290 DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
3295 if (m->mm_magic != MDB_MAGIC) {
3296 DPUTS("meta has invalid magic");
3300 if (m->mm_version != MDB_DATA_VERSION) {
3301 DPRINTF(("database is version %u, expected version %u",
3302 m->mm_version, MDB_DATA_VERSION));
3303 return MDB_VERSION_MISMATCH;
3306 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3312 /** Write the environment parameters of a freshly created DB environment.
3313 * @param[in] env the environment handle
3314 * @param[out] meta address of where to store the meta information
3315 * @return 0 on success, non-zero on failure.
3318 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3326 memset(&ov, 0, sizeof(ov));
3327 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3329 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3332 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3333 len = pwrite(fd, ptr, size, pos); \
3334 rc = (len >= 0); } while(0)
3337 DPUTS("writing new meta page");
3339 psize = env->me_psize;
3341 meta->mm_magic = MDB_MAGIC;
3342 meta->mm_version = MDB_DATA_VERSION;
3343 meta->mm_mapsize = env->me_mapsize;
3344 meta->mm_psize = psize;
3345 meta->mm_last_pg = 1;
3346 meta->mm_flags = env->me_flags & 0xffff;
3347 meta->mm_flags |= MDB_INTEGERKEY;
3348 meta->mm_dbs[0].md_root = P_INVALID;
3349 meta->mm_dbs[1].md_root = P_INVALID;
3351 p = calloc(2, psize);
3353 p->mp_flags = P_META;
3354 *(MDB_meta *)METADATA(p) = *meta;
3356 q = (MDB_page *)((char *)p + psize);
3358 q->mp_flags = P_META;
3359 *(MDB_meta *)METADATA(q) = *meta;
3361 DO_PWRITE(rc, env->me_fd, p, psize * 2, len, 0);
3364 else if ((unsigned) len == psize * 2)
3372 /** Update the environment info to commit a transaction.
3373 * @param[in] txn the transaction that's being committed
3374 * @return 0 on success, non-zero on failure.
3377 mdb_env_write_meta(MDB_txn *txn)
3380 MDB_meta meta, metab, *mp;
3382 int rc, len, toggle;
3391 toggle = txn->mt_txnid & 1;
3392 DPRINTF(("writing meta page %d for root page %"Z"u",
3393 toggle, txn->mt_dbs[MAIN_DBI].md_root));
3396 mp = env->me_metas[toggle];
3398 if (env->me_flags & MDB_WRITEMAP) {
3399 /* Persist any increases of mapsize config */
3400 if (env->me_mapsize > mp->mm_mapsize)
3401 mp->mm_mapsize = env->me_mapsize;
3402 mp->mm_dbs[0] = txn->mt_dbs[0];
3403 mp->mm_dbs[1] = txn->mt_dbs[1];
3404 mp->mm_last_pg = txn->mt_next_pgno - 1;
3405 mp->mm_txnid = txn->mt_txnid;
3406 if (!(env->me_flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3407 unsigned meta_size = env->me_psize;
3408 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3411 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
3412 if (meta_size < env->me_os_psize)
3413 meta_size += meta_size;
3418 if (MDB_MSYNC(ptr, meta_size, rc)) {
3425 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
3426 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
3428 ptr = (char *)&meta;
3429 if (env->me_mapsize > mp->mm_mapsize) {
3430 /* Persist any increases of mapsize config */
3431 meta.mm_mapsize = env->me_mapsize;
3432 off = offsetof(MDB_meta, mm_mapsize);
3434 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
3436 len = sizeof(MDB_meta) - off;
3439 meta.mm_dbs[0] = txn->mt_dbs[0];
3440 meta.mm_dbs[1] = txn->mt_dbs[1];
3441 meta.mm_last_pg = txn->mt_next_pgno - 1;
3442 meta.mm_txnid = txn->mt_txnid;
3445 off += env->me_psize;
3448 /* Write to the SYNC fd */
3449 mfd = env->me_flags & (MDB_NOSYNC|MDB_NOMETASYNC) ?
3450 env->me_fd : env->me_mfd;
3453 memset(&ov, 0, sizeof(ov));
3455 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3459 rc = pwrite(mfd, ptr, len, off);
3462 rc = rc < 0 ? ErrCode() : EIO;
3463 DPUTS("write failed, disk error?");
3464 /* On a failure, the pagecache still contains the new data.
3465 * Write some old data back, to prevent it from being used.
3466 * Use the non-SYNC fd; we know it will fail anyway.
3468 meta.mm_last_pg = metab.mm_last_pg;
3469 meta.mm_txnid = metab.mm_txnid;
3471 memset(&ov, 0, sizeof(ov));
3473 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3475 r2 = pwrite(env->me_fd, ptr, len, off);
3476 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
3479 env->me_flags |= MDB_FATAL_ERROR;
3483 /* Memory ordering issues are irrelevant; since the entire writer
3484 * is wrapped by wmutex, all of these changes will become visible
3485 * after the wmutex is unlocked. Since the DB is multi-version,
3486 * readers will get consistent data regardless of how fresh or
3487 * how stale their view of these values is.
3490 env->me_txns->mti_txnid = txn->mt_txnid;
3495 /** Check both meta pages to see which one is newer.
3496 * @param[in] env the environment handle
3497 * @return meta toggle (0 or 1).
3500 mdb_env_pick_meta(const MDB_env *env)
3502 return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
3506 mdb_env_create(MDB_env **env)
3510 e = calloc(1, sizeof(MDB_env));
3514 e->me_maxreaders = DEFAULT_READERS;
3515 e->me_maxdbs = e->me_numdbs = 2;
3516 e->me_fd = INVALID_HANDLE_VALUE;
3517 e->me_lfd = INVALID_HANDLE_VALUE;
3518 e->me_mfd = INVALID_HANDLE_VALUE;
3519 #ifdef MDB_USE_POSIX_SEM
3520 e->me_rmutex = SEM_FAILED;
3521 e->me_wmutex = SEM_FAILED;
3523 e->me_pid = getpid();
3524 GET_PAGESIZE(e->me_os_psize);
3525 VGMEMP_CREATE(e,0,0);
3531 mdb_env_map(MDB_env *env, void *addr, int newsize)
3534 unsigned int flags = env->me_flags;
3538 LONG sizelo, sizehi;
3539 sizelo = env->me_mapsize & 0xffffffff;
3540 sizehi = env->me_mapsize >> 16 >> 16; /* only needed on Win64 */
3542 /* Windows won't create mappings for zero length files.
3543 * Just allocate the maxsize right now.
3546 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3547 || !SetEndOfFile(env->me_fd)
3548 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3551 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3552 PAGE_READWRITE : PAGE_READONLY,
3553 sizehi, sizelo, NULL);
3556 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3557 FILE_MAP_WRITE : FILE_MAP_READ,
3558 0, 0, env->me_mapsize, addr);
3559 rc = env->me_map ? 0 : ErrCode();
3564 int prot = PROT_READ;
3565 if (flags & MDB_WRITEMAP) {
3567 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3570 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
3572 if (env->me_map == MAP_FAILED) {
3577 if (flags & MDB_NORDAHEAD) {
3578 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3580 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3582 #ifdef POSIX_MADV_RANDOM
3583 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3584 #endif /* POSIX_MADV_RANDOM */
3585 #endif /* MADV_RANDOM */
3589 /* Can happen because the address argument to mmap() is just a
3590 * hint. mmap() can pick another, e.g. if the range is in use.
3591 * The MAP_FIXED flag would prevent that, but then mmap could
3592 * instead unmap existing pages to make room for the new map.
3594 if (addr && env->me_map != addr)
3595 return EBUSY; /* TODO: Make a new MDB_* error code? */
3597 p = (MDB_page *)env->me_map;
3598 env->me_metas[0] = METADATA(p);
3599 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
3605 mdb_env_set_mapsize(MDB_env *env, size_t size)
3607 /* If env is already open, caller is responsible for making
3608 * sure there are no active txns.
3616 size = env->me_metas[mdb_env_pick_meta(env)]->mm_mapsize;
3617 else if (size < env->me_mapsize) {
3618 /* If the configured size is smaller, make sure it's
3619 * still big enough. Silently round up to minimum if not.
3621 size_t minsize = (env->me_metas[mdb_env_pick_meta(env)]->mm_last_pg + 1) * env->me_psize;
3625 munmap(env->me_map, env->me_mapsize);
3626 env->me_mapsize = size;
3627 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
3628 rc = mdb_env_map(env, old, 1);
3632 env->me_mapsize = size;
3634 env->me_maxpg = env->me_mapsize / env->me_psize;
3639 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
3643 env->me_maxdbs = dbs + 2; /* Named databases + main and free DB */
3648 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
3650 if (env->me_map || readers < 1)
3652 env->me_maxreaders = readers;
3657 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
3659 if (!env || !readers)
3661 *readers = env->me_maxreaders;
3665 /** Further setup required for opening an LMDB environment
3668 mdb_env_open2(MDB_env *env)
3670 unsigned int flags = env->me_flags;
3671 int i, newenv = 0, rc;
3675 /* See if we should use QueryLimited */
3677 if ((rc & 0xff) > 5)
3678 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
3680 env->me_pidquery = PROCESS_QUERY_INFORMATION;
3683 memset(&meta, 0, sizeof(meta));
3685 if ((i = mdb_env_read_header(env, &meta)) != 0) {
3688 DPUTS("new mdbenv");
3690 env->me_psize = env->me_os_psize;
3691 if (env->me_psize > MAX_PAGESIZE)
3692 env->me_psize = MAX_PAGESIZE;
3694 env->me_psize = meta.mm_psize;
3697 /* Was a mapsize configured? */
3698 if (!env->me_mapsize) {
3699 /* If this is a new environment, take the default,
3700 * else use the size recorded in the existing env.
3702 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
3703 } else if (env->me_mapsize < meta.mm_mapsize) {
3704 /* If the configured size is smaller, make sure it's
3705 * still big enough. Silently round up to minimum if not.
3707 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
3708 if (env->me_mapsize < minsize)
3709 env->me_mapsize = minsize;
3712 rc = mdb_env_map(env, meta.mm_address, newenv || env->me_mapsize != meta.mm_mapsize);
3717 if (flags & MDB_FIXEDMAP)
3718 meta.mm_address = env->me_map;
3719 i = mdb_env_init_meta(env, &meta);
3720 if (i != MDB_SUCCESS) {
3725 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
3726 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
3728 #if !(MDB_MAXKEYSIZE)
3729 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
3731 env->me_maxpg = env->me_mapsize / env->me_psize;
3735 int toggle = mdb_env_pick_meta(env);
3736 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
3738 DPRINTF(("opened database version %u, pagesize %u",
3739 env->me_metas[0]->mm_version, env->me_psize));
3740 DPRINTF(("using meta page %d", toggle));
3741 DPRINTF(("depth: %u", db->md_depth));
3742 DPRINTF(("entries: %"Z"u", db->md_entries));
3743 DPRINTF(("branch pages: %"Z"u", db->md_branch_pages));
3744 DPRINTF(("leaf pages: %"Z"u", db->md_leaf_pages));
3745 DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
3746 DPRINTF(("root: %"Z"u", db->md_root));
3754 /** Release a reader thread's slot in the reader lock table.
3755 * This function is called automatically when a thread exits.
3756 * @param[in] ptr This points to the slot in the reader lock table.
3759 mdb_env_reader_dest(void *ptr)
3761 MDB_reader *reader = ptr;
3767 /** Junk for arranging thread-specific callbacks on Windows. This is
3768 * necessarily platform and compiler-specific. Windows supports up
3769 * to 1088 keys. Let's assume nobody opens more than 64 environments
3770 * in a single process, for now. They can override this if needed.
3772 #ifndef MAX_TLS_KEYS
3773 #define MAX_TLS_KEYS 64
3775 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
3776 static int mdb_tls_nkeys;
3778 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
3782 case DLL_PROCESS_ATTACH: break;
3783 case DLL_THREAD_ATTACH: break;
3784 case DLL_THREAD_DETACH:
3785 for (i=0; i<mdb_tls_nkeys; i++) {
3786 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
3788 mdb_env_reader_dest(r);
3792 case DLL_PROCESS_DETACH: break;
3797 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3799 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3803 /* Force some symbol references.
3804 * _tls_used forces the linker to create the TLS directory if not already done
3805 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
3807 #pragma comment(linker, "/INCLUDE:_tls_used")
3808 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
3809 #pragma const_seg(".CRT$XLB")
3810 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
3811 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3814 #pragma comment(linker, "/INCLUDE:__tls_used")
3815 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
3816 #pragma data_seg(".CRT$XLB")
3817 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3819 #endif /* WIN 32/64 */
3820 #endif /* !__GNUC__ */
3823 /** Downgrade the exclusive lock on the region back to shared */
3825 mdb_env_share_locks(MDB_env *env, int *excl)
3827 int rc = 0, toggle = mdb_env_pick_meta(env);
3829 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
3834 /* First acquire a shared lock. The Unlock will
3835 * then release the existing exclusive lock.
3837 memset(&ov, 0, sizeof(ov));
3838 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3841 UnlockFile(env->me_lfd, 0, 0, 1, 0);
3847 struct flock lock_info;
3848 /* The shared lock replaces the existing lock */
3849 memset((void *)&lock_info, 0, sizeof(lock_info));
3850 lock_info.l_type = F_RDLCK;
3851 lock_info.l_whence = SEEK_SET;
3852 lock_info.l_start = 0;
3853 lock_info.l_len = 1;
3854 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3855 (rc = ErrCode()) == EINTR) ;
3856 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
3863 /** Try to get exlusive lock, otherwise shared.
3864 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
3867 mdb_env_excl_lock(MDB_env *env, int *excl)
3871 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
3875 memset(&ov, 0, sizeof(ov));
3876 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3883 struct flock lock_info;
3884 memset((void *)&lock_info, 0, sizeof(lock_info));
3885 lock_info.l_type = F_WRLCK;
3886 lock_info.l_whence = SEEK_SET;
3887 lock_info.l_start = 0;
3888 lock_info.l_len = 1;
3889 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3890 (rc = ErrCode()) == EINTR) ;
3894 # ifdef MDB_USE_POSIX_SEM
3895 if (*excl < 0) /* always true when !MDB_USE_POSIX_SEM */
3898 lock_info.l_type = F_RDLCK;
3899 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
3900 (rc = ErrCode()) == EINTR) ;
3910 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
3912 * @(#) $Revision: 5.1 $
3913 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
3914 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
3916 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
3920 * Please do not copyright this code. This code is in the public domain.
3922 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
3923 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
3924 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
3925 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
3926 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
3927 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
3928 * PERFORMANCE OF THIS SOFTWARE.
3931 * chongo <Landon Curt Noll> /\oo/\
3932 * http://www.isthe.com/chongo/
3934 * Share and Enjoy! :-)
3937 typedef unsigned long long mdb_hash_t;
3938 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
3940 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
3941 * @param[in] val value to hash
3942 * @param[in] hval initial value for hash
3943 * @return 64 bit hash
3945 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
3946 * hval arg on the first call.
3949 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
3951 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
3952 unsigned char *end = s + val->mv_size;
3954 * FNV-1a hash each octet of the string
3957 /* xor the bottom with the current octet */
3958 hval ^= (mdb_hash_t)*s++;
3960 /* multiply by the 64 bit FNV magic prime mod 2^64 */
3961 hval += (hval << 1) + (hval << 4) + (hval << 5) +
3962 (hval << 7) + (hval << 8) + (hval << 40);
3964 /* return our new hash value */
3968 /** Hash the string and output the encoded hash.
3969 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
3970 * very short name limits. We don't care about the encoding being reversible,
3971 * we just want to preserve as many bits of the input as possible in a
3972 * small printable string.
3973 * @param[in] str string to hash
3974 * @param[out] encbuf an array of 11 chars to hold the hash
3976 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
3979 mdb_pack85(unsigned long l, char *out)
3983 for (i=0; i<5; i++) {
3984 *out++ = mdb_a85[l % 85];
3990 mdb_hash_enc(MDB_val *val, char *encbuf)
3992 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
3994 mdb_pack85(h, encbuf);
3995 mdb_pack85(h>>32, encbuf+5);
4000 /** Open and/or initialize the lock region for the environment.
4001 * @param[in] env The LMDB environment.
4002 * @param[in] lpath The pathname of the file used for the lock region.
4003 * @param[in] mode The Unix permissions for the file, if we create it.
4004 * @param[out] excl Resulting file lock type: -1 none, 0 shared, 1 exclusive
4005 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
4006 * @return 0 on success, non-zero on failure.
4009 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
4012 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
4014 # define MDB_ERRCODE_ROFS EROFS
4015 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
4016 # define MDB_CLOEXEC O_CLOEXEC
4019 # define MDB_CLOEXEC 0
4026 env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
4027 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
4028 FILE_ATTRIBUTE_NORMAL, NULL);
4030 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
4032 if (env->me_lfd == INVALID_HANDLE_VALUE) {
4034 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
4039 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
4040 /* Lose record locks when exec*() */
4041 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
4042 fcntl(env->me_lfd, F_SETFD, fdflags);
4045 if (!(env->me_flags & MDB_NOTLS)) {
4046 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
4049 env->me_flags |= MDB_ENV_TXKEY;
4051 /* Windows TLS callbacks need help finding their TLS info. */
4052 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
4056 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
4060 /* Try to get exclusive lock. If we succeed, then
4061 * nobody is using the lock region and we should initialize it.
4063 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
4066 size = GetFileSize(env->me_lfd, NULL);
4068 size = lseek(env->me_lfd, 0, SEEK_END);
4069 if (size == -1) goto fail_errno;
4071 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
4072 if (size < rsize && *excl > 0) {
4074 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
4075 || !SetEndOfFile(env->me_lfd))
4078 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
4082 size = rsize - sizeof(MDB_txninfo);
4083 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
4088 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
4090 if (!mh) goto fail_errno;
4091 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
4093 if (!env->me_txns) goto fail_errno;
4095 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
4097 if (m == MAP_FAILED) goto fail_errno;
4103 BY_HANDLE_FILE_INFORMATION stbuf;
4112 if (!mdb_sec_inited) {
4113 InitializeSecurityDescriptor(&mdb_null_sd,
4114 SECURITY_DESCRIPTOR_REVISION);
4115 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
4116 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
4117 mdb_all_sa.bInheritHandle = FALSE;
4118 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
4121 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
4122 idbuf.volume = stbuf.dwVolumeSerialNumber;
4123 idbuf.nhigh = stbuf.nFileIndexHigh;
4124 idbuf.nlow = stbuf.nFileIndexLow;
4125 val.mv_data = &idbuf;
4126 val.mv_size = sizeof(idbuf);
4127 mdb_hash_enc(&val, encbuf);
4128 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
4129 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
4130 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
4131 if (!env->me_rmutex) goto fail_errno;
4132 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
4133 if (!env->me_wmutex) goto fail_errno;
4134 #elif defined(MDB_USE_POSIX_SEM)
4143 #if defined(__NetBSD__)
4144 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
4146 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
4147 idbuf.dev = stbuf.st_dev;
4148 idbuf.ino = stbuf.st_ino;
4149 val.mv_data = &idbuf;
4150 val.mv_size = sizeof(idbuf);
4151 mdb_hash_enc(&val, encbuf);
4152 #ifdef MDB_SHORT_SEMNAMES
4153 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
4155 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
4156 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
4157 /* Clean up after a previous run, if needed: Try to
4158 * remove both semaphores before doing anything else.
4160 sem_unlink(env->me_txns->mti_rmname);
4161 sem_unlink(env->me_txns->mti_wmname);
4162 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
4163 O_CREAT|O_EXCL, mode, 1);
4164 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4165 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
4166 O_CREAT|O_EXCL, mode, 1);
4167 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4168 #else /* MDB_USE_POSIX_SEM */
4169 pthread_mutexattr_t mattr;
4171 if ((rc = pthread_mutexattr_init(&mattr))
4172 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
4173 || (rc = pthread_mutex_init(&env->me_txns->mti_mutex, &mattr))
4174 || (rc = pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr)))
4176 pthread_mutexattr_destroy(&mattr);
4177 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
4179 env->me_txns->mti_magic = MDB_MAGIC;
4180 env->me_txns->mti_format = MDB_LOCK_FORMAT;
4181 env->me_txns->mti_txnid = 0;
4182 env->me_txns->mti_numreaders = 0;
4185 if (env->me_txns->mti_magic != MDB_MAGIC) {
4186 DPUTS("lock region has invalid magic");
4190 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
4191 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
4192 env->me_txns->mti_format, MDB_LOCK_FORMAT));
4193 rc = MDB_VERSION_MISMATCH;
4197 if (rc && rc != EACCES && rc != EAGAIN) {
4201 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
4202 if (!env->me_rmutex) goto fail_errno;
4203 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
4204 if (!env->me_wmutex) goto fail_errno;
4205 #elif defined(MDB_USE_POSIX_SEM)
4206 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
4207 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4208 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
4209 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4220 /** The name of the lock file in the DB environment */
4221 #define LOCKNAME "/lock.mdb"
4222 /** The name of the data file in the DB environment */
4223 #define DATANAME "/data.mdb"
4224 /** The suffix of the lock file when no subdir is used */
4225 #define LOCKSUFF "-lock"
4226 /** Only a subset of the @ref mdb_env flags can be changed
4227 * at runtime. Changing other flags requires closing the
4228 * environment and re-opening it with the new flags.
4230 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
4231 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY|MDB_WRITEMAP| \
4232 MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
4234 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
4235 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
4239 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
4241 int oflags, rc, len, excl = -1;
4242 char *lpath, *dpath;
4244 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
4248 if (flags & MDB_NOSUBDIR) {
4249 rc = len + sizeof(LOCKSUFF) + len + 1;
4251 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
4256 if (flags & MDB_NOSUBDIR) {
4257 dpath = lpath + len + sizeof(LOCKSUFF);
4258 sprintf(lpath, "%s" LOCKSUFF, path);
4259 strcpy(dpath, path);
4261 dpath = lpath + len + sizeof(LOCKNAME);
4262 sprintf(lpath, "%s" LOCKNAME, path);
4263 sprintf(dpath, "%s" DATANAME, path);
4267 flags |= env->me_flags;
4268 if (flags & MDB_RDONLY) {
4269 /* silently ignore WRITEMAP when we're only getting read access */
4270 flags &= ~MDB_WRITEMAP;
4272 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
4273 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
4276 env->me_flags = flags |= MDB_ENV_ACTIVE;
4280 env->me_path = strdup(path);
4281 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
4282 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
4283 if (!(env->me_dbxs && env->me_path && env->me_dbflags)) {
4288 /* For RDONLY, get lockfile after we know datafile exists */
4289 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
4290 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4296 if (F_ISSET(flags, MDB_RDONLY)) {
4297 oflags = GENERIC_READ;
4298 len = OPEN_EXISTING;
4300 oflags = GENERIC_READ|GENERIC_WRITE;
4303 mode = FILE_ATTRIBUTE_NORMAL;
4304 env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
4305 NULL, len, mode, NULL);
4307 if (F_ISSET(flags, MDB_RDONLY))
4310 oflags = O_RDWR | O_CREAT;
4312 env->me_fd = open(dpath, oflags, mode);
4314 if (env->me_fd == INVALID_HANDLE_VALUE) {
4319 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
4320 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4325 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
4326 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
4327 env->me_mfd = env->me_fd;
4329 /* Synchronous fd for meta writes. Needed even with
4330 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
4333 len = OPEN_EXISTING;
4334 env->me_mfd = CreateFile(dpath, oflags,
4335 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
4336 mode | FILE_FLAG_WRITE_THROUGH, NULL);
4339 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
4341 if (env->me_mfd == INVALID_HANDLE_VALUE) {
4346 DPRINTF(("opened dbenv %p", (void *) env));
4348 rc = mdb_env_share_locks(env, &excl);
4352 if (!((flags & MDB_RDONLY) ||
4353 (env->me_pbuf = calloc(1, env->me_psize))))
4359 mdb_env_close0(env, excl);
4365 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
4367 mdb_env_close0(MDB_env *env, int excl)
4371 if (!(env->me_flags & MDB_ENV_ACTIVE))
4374 /* Doing this here since me_dbxs may not exist during mdb_env_close */
4375 for (i = env->me_maxdbs; --i > MAIN_DBI; )
4376 free(env->me_dbxs[i].md_name.mv_data);
4379 free(env->me_dbflags);
4382 free(env->me_dirty_list);
4383 mdb_midl_free(env->me_free_pgs);
4385 if (env->me_flags & MDB_ENV_TXKEY) {
4386 pthread_key_delete(env->me_txkey);
4388 /* Delete our key from the global list */
4389 for (i=0; i<mdb_tls_nkeys; i++)
4390 if (mdb_tls_keys[i] == env->me_txkey) {
4391 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
4399 munmap(env->me_map, env->me_mapsize);
4401 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
4402 (void) close(env->me_mfd);
4403 if (env->me_fd != INVALID_HANDLE_VALUE)
4404 (void) close(env->me_fd);
4406 MDB_PID_T pid = env->me_pid;
4407 /* Clearing readers is done in this function because
4408 * me_txkey with its destructor must be disabled first.
4410 for (i = env->me_numreaders; --i >= 0; )
4411 if (env->me_txns->mti_readers[i].mr_pid == pid)
4412 env->me_txns->mti_readers[i].mr_pid = 0;
4414 if (env->me_rmutex) {
4415 CloseHandle(env->me_rmutex);
4416 if (env->me_wmutex) CloseHandle(env->me_wmutex);
4418 /* Windows automatically destroys the mutexes when
4419 * the last handle closes.
4421 #elif defined(MDB_USE_POSIX_SEM)
4422 if (env->me_rmutex != SEM_FAILED) {
4423 sem_close(env->me_rmutex);
4424 if (env->me_wmutex != SEM_FAILED)
4425 sem_close(env->me_wmutex);
4426 /* If we have the filelock: If we are the
4427 * only remaining user, clean up semaphores.
4430 mdb_env_excl_lock(env, &excl);
4432 sem_unlink(env->me_txns->mti_rmname);
4433 sem_unlink(env->me_txns->mti_wmname);
4437 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
4439 if (env->me_lfd != INVALID_HANDLE_VALUE) {
4442 /* Unlock the lockfile. Windows would have unlocked it
4443 * after closing anyway, but not necessarily at once.
4445 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4448 (void) close(env->me_lfd);
4451 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
4455 mdb_env_copyfd(MDB_env *env, HANDLE fd)
4457 MDB_txn *txn = NULL;
4463 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
4467 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
4470 /* Do the lock/unlock of the reader mutex before starting the
4471 * write txn. Otherwise other read txns could block writers.
4473 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
4478 /* We must start the actual read txn after blocking writers */
4479 mdb_txn_reset0(txn, "reset-stage1");
4481 /* Temporarily block writers until we snapshot the meta pages */
4484 rc = mdb_txn_renew0(txn);
4486 UNLOCK_MUTEX_W(env);
4491 wsize = env->me_psize * 2;
4495 DO_WRITE(rc, fd, ptr, w2, len);
4499 } else if (len > 0) {
4505 /* Non-blocking or async handles are not supported */
4511 UNLOCK_MUTEX_W(env);
4516 wsize = txn->mt_next_pgno * env->me_psize - wsize;
4518 if (wsize > MAX_WRITE)
4522 DO_WRITE(rc, fd, ptr, w2, len);
4526 } else if (len > 0) {
4543 mdb_env_copy(MDB_env *env, const char *path)
4547 HANDLE newfd = INVALID_HANDLE_VALUE;
4549 if (env->me_flags & MDB_NOSUBDIR) {
4550 lpath = (char *)path;
4553 len += sizeof(DATANAME);
4554 lpath = malloc(len);
4557 sprintf(lpath, "%s" DATANAME, path);
4560 /* The destination path must exist, but the destination file must not.
4561 * We don't want the OS to cache the writes, since the source data is
4562 * already in the OS cache.
4565 newfd = CreateFile(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
4566 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
4568 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
4570 if (newfd == INVALID_HANDLE_VALUE) {
4576 /* Set O_DIRECT if the file system supports it */
4577 if ((rc = fcntl(newfd, F_GETFL)) != -1)
4578 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
4580 #ifdef F_NOCACHE /* __APPLE__ */
4581 rc = fcntl(newfd, F_NOCACHE, 1);
4588 rc = mdb_env_copyfd(env, newfd);
4591 if (!(env->me_flags & MDB_NOSUBDIR))
4593 if (newfd != INVALID_HANDLE_VALUE)
4594 if (close(newfd) < 0 && rc == MDB_SUCCESS)
4601 mdb_env_close(MDB_env *env)
4608 VGMEMP_DESTROY(env);
4609 while ((dp = env->me_dpages) != NULL) {
4610 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
4611 env->me_dpages = dp->mp_next;
4615 mdb_env_close0(env, 0);
4619 /** Compare two items pointing at aligned size_t's */
4621 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
4623 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
4624 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
4627 /** Compare two items pointing at aligned unsigned int's */
4629 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
4631 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
4632 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
4635 /** Compare two items pointing at unsigned ints of unknown alignment.
4636 * Nodes and keys are guaranteed to be 2-byte aligned.
4639 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
4641 #if BYTE_ORDER == LITTLE_ENDIAN
4642 unsigned short *u, *c;
4645 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4646 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
4649 } while(!x && u > (unsigned short *)a->mv_data);
4652 unsigned short *u, *c, *end;
4655 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4656 u = (unsigned short *)a->mv_data;
4657 c = (unsigned short *)b->mv_data;
4660 } while(!x && u < end);
4665 /** Compare two items pointing at size_t's of unknown alignment. */
4666 #ifdef MISALIGNED_OK
4667 # define mdb_cmp_clong mdb_cmp_long
4669 # define mdb_cmp_clong mdb_cmp_cint
4672 /** Compare two items lexically */
4674 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
4681 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4687 diff = memcmp(a->mv_data, b->mv_data, len);
4688 return diff ? diff : len_diff<0 ? -1 : len_diff;
4691 /** Compare two items in reverse byte order */
4693 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
4695 const unsigned char *p1, *p2, *p1_lim;
4699 p1_lim = (const unsigned char *)a->mv_data;
4700 p1 = (const unsigned char *)a->mv_data + a->mv_size;
4701 p2 = (const unsigned char *)b->mv_data + b->mv_size;
4703 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4709 while (p1 > p1_lim) {
4710 diff = *--p1 - *--p2;
4714 return len_diff<0 ? -1 : len_diff;
4717 /** Search for key within a page, using binary search.
4718 * Returns the smallest entry larger or equal to the key.
4719 * If exactp is non-null, stores whether the found entry was an exact match
4720 * in *exactp (1 or 0).
4721 * Updates the cursor index with the index of the found entry.
4722 * If no entry larger or equal to the key is found, returns NULL.
4725 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
4727 unsigned int i = 0, nkeys;
4730 MDB_page *mp = mc->mc_pg[mc->mc_top];
4731 MDB_node *node = NULL;
4736 nkeys = NUMKEYS(mp);
4738 DPRINTF(("searching %u keys in %s %spage %"Z"u",
4739 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
4742 low = IS_LEAF(mp) ? 0 : 1;
4744 cmp = mc->mc_dbx->md_cmp;
4746 /* Branch pages have no data, so if using integer keys,
4747 * alignment is guaranteed. Use faster mdb_cmp_int.
4749 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
4750 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
4757 nodekey.mv_size = mc->mc_db->md_pad;
4758 node = NODEPTR(mp, 0); /* fake */
4759 while (low <= high) {
4760 i = (low + high) >> 1;
4761 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
4762 rc = cmp(key, &nodekey);
4763 DPRINTF(("found leaf index %u [%s], rc = %i",
4764 i, DKEY(&nodekey), rc));
4773 while (low <= high) {
4774 i = (low + high) >> 1;
4776 node = NODEPTR(mp, i);
4777 nodekey.mv_size = NODEKSZ(node);
4778 nodekey.mv_data = NODEKEY(node);
4780 rc = cmp(key, &nodekey);
4783 DPRINTF(("found leaf index %u [%s], rc = %i",
4784 i, DKEY(&nodekey), rc));
4786 DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
4787 i, DKEY(&nodekey), NODEPGNO(node), rc));
4798 if (rc > 0) { /* Found entry is less than the key. */
4799 i++; /* Skip to get the smallest entry larger than key. */
4801 node = NODEPTR(mp, i);
4804 *exactp = (rc == 0 && nkeys > 0);
4805 /* store the key index */
4806 mc->mc_ki[mc->mc_top] = i;
4808 /* There is no entry larger or equal to the key. */
4811 /* nodeptr is fake for LEAF2 */
4817 mdb_cursor_adjust(MDB_cursor *mc, func)
4821 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4822 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
4829 /** Pop a page off the top of the cursor's stack. */
4831 mdb_cursor_pop(MDB_cursor *mc)
4835 MDB_page *top = mc->mc_pg[mc->mc_top];
4841 DPRINTF(("popped page %"Z"u off db %d cursor %p", top->mp_pgno,
4842 DDBI(mc), (void *) mc));
4846 /** Push a page onto the top of the cursor's stack. */
4848 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
4850 DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
4851 DDBI(mc), (void *) mc));
4853 if (mc->mc_snum >= CURSOR_STACK) {
4854 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4855 return MDB_CURSOR_FULL;
4858 mc->mc_top = mc->mc_snum++;
4859 mc->mc_pg[mc->mc_top] = mp;
4860 mc->mc_ki[mc->mc_top] = 0;
4865 /** Find the address of the page corresponding to a given page number.
4866 * @param[in] txn the transaction for this access.
4867 * @param[in] pgno the page number for the page to retrieve.
4868 * @param[out] ret address of a pointer where the page's address will be stored.
4869 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
4870 * @return 0 on success, non-zero on failure.
4873 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
4875 MDB_env *env = txn->mt_env;
4879 if (!((txn->mt_flags & MDB_TXN_RDONLY) | (env->me_flags & MDB_WRITEMAP))) {
4883 MDB_ID2L dl = tx2->mt_u.dirty_list;
4885 /* Spilled pages were dirtied in this txn and flushed
4886 * because the dirty list got full. Bring this page
4887 * back in from the map (but don't unspill it here,
4888 * leave that unless page_touch happens again).
4890 if (tx2->mt_spill_pgs) {
4891 MDB_ID pn = pgno << 1;
4892 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
4893 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
4894 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
4899 unsigned x = mdb_mid2l_search(dl, pgno);
4900 if (x <= dl[0].mid && dl[x].mid == pgno) {
4906 } while ((tx2 = tx2->mt_parent) != NULL);
4909 if (pgno < txn->mt_next_pgno) {
4911 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
4913 DPRINTF(("page %"Z"u not found", pgno));
4914 txn->mt_flags |= MDB_TXN_ERROR;
4915 return MDB_PAGE_NOTFOUND;
4925 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
4926 * The cursor is at the root page, set up the rest of it.
4929 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
4931 MDB_page *mp = mc->mc_pg[mc->mc_top];
4935 while (IS_BRANCH(mp)) {
4939 DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
4940 mdb_cassert(mc, NUMKEYS(mp) > 1);
4941 DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
4943 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
4945 if (flags & MDB_PS_LAST)
4946 i = NUMKEYS(mp) - 1;
4949 node = mdb_node_search(mc, key, &exact);
4951 i = NUMKEYS(mp) - 1;
4953 i = mc->mc_ki[mc->mc_top];
4955 mdb_cassert(mc, i > 0);
4959 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
4962 mdb_cassert(mc, i < NUMKEYS(mp));
4963 node = NODEPTR(mp, i);
4965 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4968 mc->mc_ki[mc->mc_top] = i;
4969 if ((rc = mdb_cursor_push(mc, mp)))
4972 if (flags & MDB_PS_MODIFY) {
4973 if ((rc = mdb_page_touch(mc)) != 0)
4975 mp = mc->mc_pg[mc->mc_top];
4980 DPRINTF(("internal error, index points to a %02X page!?",
4982 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4983 return MDB_CORRUPTED;
4986 DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
4987 key ? DKEY(key) : "null"));
4988 mc->mc_flags |= C_INITIALIZED;
4989 mc->mc_flags &= ~C_EOF;
4994 /** Search for the lowest key under the current branch page.
4995 * This just bypasses a NUMKEYS check in the current page
4996 * before calling mdb_page_search_root(), because the callers
4997 * are all in situations where the current page is known to
5001 mdb_page_search_lowest(MDB_cursor *mc)
5003 MDB_page *mp = mc->mc_pg[mc->mc_top];
5004 MDB_node *node = NODEPTR(mp, 0);
5007 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
5010 mc->mc_ki[mc->mc_top] = 0;
5011 if ((rc = mdb_cursor_push(mc, mp)))
5013 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
5016 /** Search for the page a given key should be in.
5017 * Push it and its parent pages on the cursor stack.
5018 * @param[in,out] mc the cursor for this operation.
5019 * @param[in] key the key to search for, or NULL for first/last page.
5020 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
5021 * are touched (updated with new page numbers).
5022 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
5023 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
5024 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
5025 * @return 0 on success, non-zero on failure.
5028 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
5033 /* Make sure the txn is still viable, then find the root from
5034 * the txn's db table and set it as the root of the cursor's stack.
5036 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
5037 DPUTS("transaction has failed, must abort");
5040 /* Make sure we're using an up-to-date root */
5041 if (*mc->mc_dbflag & DB_STALE) {
5043 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
5044 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
5051 MDB_node *leaf = mdb_node_search(&mc2,
5052 &mc->mc_dbx->md_name, &exact);
5054 return MDB_NOTFOUND;
5055 rc = mdb_node_read(mc->mc_txn, leaf, &data);
5058 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
5060 /* The txn may not know this DBI, or another process may
5061 * have dropped and recreated the DB with other flags.
5063 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
5064 return MDB_INCOMPATIBLE;
5065 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
5067 *mc->mc_dbflag &= ~DB_STALE;
5069 root = mc->mc_db->md_root;
5071 if (root == P_INVALID) { /* Tree is empty. */
5072 DPUTS("tree is empty");
5073 return MDB_NOTFOUND;
5077 mdb_cassert(mc, root > 1);
5078 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
5079 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0], NULL)) != 0)
5085 DPRINTF(("db %d root page %"Z"u has flags 0x%X",
5086 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
5088 if (flags & MDB_PS_MODIFY) {
5089 if ((rc = mdb_page_touch(mc)))
5093 if (flags & MDB_PS_ROOTONLY)
5096 return mdb_page_search_root(mc, key, flags);
5100 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
5102 MDB_txn *txn = mc->mc_txn;
5103 pgno_t pg = mp->mp_pgno;
5104 unsigned x = 0, ovpages = mp->mp_pages;
5105 MDB_env *env = txn->mt_env;
5106 MDB_IDL sl = txn->mt_spill_pgs;
5107 MDB_ID pn = pg << 1;
5110 DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
5111 /* If the page is dirty or on the spill list we just acquired it,
5112 * so we should give it back to our current free list, if any.
5113 * Otherwise put it onto the list of pages we freed in this txn.
5115 * Won't create me_pghead: me_pglast must be inited along with it.
5116 * Unsupported in nested txns: They would need to hide the page
5117 * range in ancestor txns' dirty and spilled lists.
5119 if (env->me_pghead &&
5121 ((mp->mp_flags & P_DIRTY) ||
5122 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
5126 MDB_ID2 *dl, ix, iy;
5127 rc = mdb_midl_need(&env->me_pghead, ovpages);
5130 if (!(mp->mp_flags & P_DIRTY)) {
5131 /* This page is no longer spilled */
5138 /* Remove from dirty list */
5139 dl = txn->mt_u.dirty_list;
5141 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
5147 mdb_cassert(mc, x > 1);
5149 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
5150 txn->mt_flags |= MDB_TXN_ERROR;
5151 return MDB_CORRUPTED;
5154 if (!(env->me_flags & MDB_WRITEMAP))
5155 mdb_dpage_free(env, mp);
5157 /* Insert in me_pghead */
5158 mop = env->me_pghead;
5159 j = mop[0] + ovpages;
5160 for (i = mop[0]; i && mop[i] < pg; i--)
5166 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
5170 mc->mc_db->md_overflow_pages -= ovpages;
5174 /** Return the data associated with a given node.
5175 * @param[in] txn The transaction for this operation.
5176 * @param[in] leaf The node being read.
5177 * @param[out] data Updated to point to the node's data.
5178 * @return 0 on success, non-zero on failure.
5181 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
5183 MDB_page *omp; /* overflow page */
5187 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5188 data->mv_size = NODEDSZ(leaf);
5189 data->mv_data = NODEDATA(leaf);
5193 /* Read overflow data.
5195 data->mv_size = NODEDSZ(leaf);
5196 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
5197 if ((rc = mdb_page_get(txn, pgno, &omp, NULL)) != 0) {
5198 DPRINTF(("read overflow page %"Z"u failed", pgno));
5201 data->mv_data = METADATA(omp);
5207 mdb_get(MDB_txn *txn, MDB_dbi dbi,
5208 MDB_val *key, MDB_val *data)
5215 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
5217 if (!key || !data || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
5220 if (txn->mt_flags & MDB_TXN_ERROR)
5223 mdb_cursor_init(&mc, txn, dbi, &mx);
5224 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
5227 /** Find a sibling for a page.
5228 * Replaces the page at the top of the cursor's stack with the
5229 * specified sibling, if one exists.
5230 * @param[in] mc The cursor for this operation.
5231 * @param[in] move_right Non-zero if the right sibling is requested,
5232 * otherwise the left sibling.
5233 * @return 0 on success, non-zero on failure.
5236 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
5242 if (mc->mc_snum < 2) {
5243 return MDB_NOTFOUND; /* root has no siblings */
5247 DPRINTF(("parent page is page %"Z"u, index %u",
5248 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
5250 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
5251 : (mc->mc_ki[mc->mc_top] == 0)) {
5252 DPRINTF(("no more keys left, moving to %s sibling",
5253 move_right ? "right" : "left"));
5254 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
5255 /* undo cursor_pop before returning */
5262 mc->mc_ki[mc->mc_top]++;
5264 mc->mc_ki[mc->mc_top]--;
5265 DPRINTF(("just moving to %s index key %u",
5266 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
5268 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
5270 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5271 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL)) != 0) {
5272 /* mc will be inconsistent if caller does mc_snum++ as above */
5273 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
5277 mdb_cursor_push(mc, mp);
5279 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
5284 /** Move the cursor to the next data item. */
5286 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5292 if (mc->mc_flags & C_EOF) {
5293 return MDB_NOTFOUND;
5296 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5298 mp = mc->mc_pg[mc->mc_top];
5300 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5301 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5302 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5303 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
5304 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
5305 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
5306 if (rc == MDB_SUCCESS)
5307 MDB_GET_KEY(leaf, key);
5312 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5313 if (op == MDB_NEXT_DUP)
5314 return MDB_NOTFOUND;
5318 DPRINTF(("cursor_next: top page is %"Z"u in cursor %p",
5319 mdb_dbg_pgno(mp), (void *) mc));
5320 if (mc->mc_flags & C_DEL)
5323 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
5324 DPUTS("=====> move to next sibling page");
5325 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5326 mc->mc_flags |= C_EOF;
5329 mp = mc->mc_pg[mc->mc_top];
5330 DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5332 mc->mc_ki[mc->mc_top]++;
5335 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5336 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5339 key->mv_size = mc->mc_db->md_pad;
5340 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5344 mdb_cassert(mc, IS_LEAF(mp));
5345 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5347 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5348 mdb_xcursor_init1(mc, leaf);
5351 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5354 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5355 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5356 if (rc != MDB_SUCCESS)
5361 MDB_GET_KEY(leaf, key);
5365 /** Move the cursor to the previous data item. */
5367 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5373 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5375 mp = mc->mc_pg[mc->mc_top];
5377 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5378 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5379 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5380 if (op == MDB_PREV || op == MDB_PREV_DUP) {
5381 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
5382 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
5383 if (rc == MDB_SUCCESS)
5384 MDB_GET_KEY(leaf, key);
5388 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5389 if (op == MDB_PREV_DUP)
5390 return MDB_NOTFOUND;
5395 DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p",
5396 mdb_dbg_pgno(mp), (void *) mc));
5398 if (mc->mc_ki[mc->mc_top] == 0) {
5399 DPUTS("=====> move to prev sibling page");
5400 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
5403 mp = mc->mc_pg[mc->mc_top];
5404 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
5405 DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5407 mc->mc_ki[mc->mc_top]--;
5409 mc->mc_flags &= ~C_EOF;
5411 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5412 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5415 key->mv_size = mc->mc_db->md_pad;
5416 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5420 mdb_cassert(mc, IS_LEAF(mp));
5421 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5423 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5424 mdb_xcursor_init1(mc, leaf);
5427 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5430 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5431 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5432 if (rc != MDB_SUCCESS)
5437 MDB_GET_KEY(leaf, key);
5441 /** Set the cursor on a specific data item. */
5443 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5444 MDB_cursor_op op, int *exactp)
5448 MDB_node *leaf = NULL;
5451 if (key->mv_size == 0)
5452 return MDB_BAD_VALSIZE;
5455 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5457 /* See if we're already on the right page */
5458 if (mc->mc_flags & C_INITIALIZED) {
5461 mp = mc->mc_pg[mc->mc_top];
5463 mc->mc_ki[mc->mc_top] = 0;
5464 return MDB_NOTFOUND;
5466 if (mp->mp_flags & P_LEAF2) {
5467 nodekey.mv_size = mc->mc_db->md_pad;
5468 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
5470 leaf = NODEPTR(mp, 0);
5471 MDB_GET_KEY2(leaf, nodekey);
5473 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5475 /* Probably happens rarely, but first node on the page
5476 * was the one we wanted.
5478 mc->mc_ki[mc->mc_top] = 0;
5485 unsigned int nkeys = NUMKEYS(mp);
5487 if (mp->mp_flags & P_LEAF2) {
5488 nodekey.mv_data = LEAF2KEY(mp,
5489 nkeys-1, nodekey.mv_size);
5491 leaf = NODEPTR(mp, nkeys-1);
5492 MDB_GET_KEY2(leaf, nodekey);
5494 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5496 /* last node was the one we wanted */
5497 mc->mc_ki[mc->mc_top] = nkeys-1;
5503 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
5504 /* This is definitely the right page, skip search_page */
5505 if (mp->mp_flags & P_LEAF2) {
5506 nodekey.mv_data = LEAF2KEY(mp,
5507 mc->mc_ki[mc->mc_top], nodekey.mv_size);
5509 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5510 MDB_GET_KEY2(leaf, nodekey);
5512 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5514 /* current node was the one we wanted */
5524 /* If any parents have right-sibs, search.
5525 * Otherwise, there's nothing further.
5527 for (i=0; i<mc->mc_top; i++)
5529 NUMKEYS(mc->mc_pg[i])-1)
5531 if (i == mc->mc_top) {
5532 /* There are no other pages */
5533 mc->mc_ki[mc->mc_top] = nkeys;
5534 return MDB_NOTFOUND;
5538 /* There are no other pages */
5539 mc->mc_ki[mc->mc_top] = 0;
5540 if (op == MDB_SET_RANGE && !exactp) {
5544 return MDB_NOTFOUND;
5548 rc = mdb_page_search(mc, key, 0);
5549 if (rc != MDB_SUCCESS)
5552 mp = mc->mc_pg[mc->mc_top];
5553 mdb_cassert(mc, IS_LEAF(mp));
5556 leaf = mdb_node_search(mc, key, exactp);
5557 if (exactp != NULL && !*exactp) {
5558 /* MDB_SET specified and not an exact match. */
5559 return MDB_NOTFOUND;
5563 DPUTS("===> inexact leaf not found, goto sibling");
5564 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
5565 return rc; /* no entries matched */
5566 mp = mc->mc_pg[mc->mc_top];
5567 mdb_cassert(mc, IS_LEAF(mp));
5568 leaf = NODEPTR(mp, 0);
5572 mc->mc_flags |= C_INITIALIZED;
5573 mc->mc_flags &= ~C_EOF;
5576 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
5577 key->mv_size = mc->mc_db->md_pad;
5578 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5583 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5584 mdb_xcursor_init1(mc, leaf);
5587 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5588 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
5589 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5592 if (op == MDB_GET_BOTH) {
5598 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
5599 if (rc != MDB_SUCCESS)
5602 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
5604 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
5606 rc = mc->mc_dbx->md_dcmp(data, &d2);
5608 if (op == MDB_GET_BOTH || rc > 0)
5609 return MDB_NOTFOUND;
5616 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5617 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5622 /* The key already matches in all other cases */
5623 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
5624 MDB_GET_KEY(leaf, key);
5625 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
5630 /** Move the cursor to the first item in the database. */
5632 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5638 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5640 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5641 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
5642 if (rc != MDB_SUCCESS)
5645 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
5647 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
5648 mc->mc_flags |= C_INITIALIZED;
5649 mc->mc_flags &= ~C_EOF;
5651 mc->mc_ki[mc->mc_top] = 0;
5653 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5654 key->mv_size = mc->mc_db->md_pad;
5655 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
5660 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5661 mdb_xcursor_init1(mc, leaf);
5662 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5666 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5670 MDB_GET_KEY(leaf, key);
5674 /** Move the cursor to the last item in the database. */
5676 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5682 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5684 if (!(mc->mc_flags & C_EOF)) {
5686 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5687 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
5688 if (rc != MDB_SUCCESS)
5691 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
5694 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
5695 mc->mc_flags |= C_INITIALIZED|C_EOF;
5696 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5698 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5699 key->mv_size = mc->mc_db->md_pad;
5700 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
5705 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5706 mdb_xcursor_init1(mc, leaf);
5707 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5711 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5716 MDB_GET_KEY(leaf, key);
5721 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5726 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
5731 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
5735 case MDB_GET_CURRENT:
5736 if (!(mc->mc_flags & C_INITIALIZED)) {
5739 MDB_page *mp = mc->mc_pg[mc->mc_top];
5740 int nkeys = NUMKEYS(mp);
5741 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
5742 mc->mc_ki[mc->mc_top] = nkeys;
5748 key->mv_size = mc->mc_db->md_pad;
5749 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5751 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5752 MDB_GET_KEY(leaf, key);
5754 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5755 if (mc->mc_flags & C_DEL)
5756 mdb_xcursor_init1(mc, leaf);
5757 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
5759 rc = mdb_node_read(mc->mc_txn, leaf, data);
5766 case MDB_GET_BOTH_RANGE:
5771 if (mc->mc_xcursor == NULL) {
5772 rc = MDB_INCOMPATIBLE;
5782 rc = mdb_cursor_set(mc, key, data, op,
5783 op == MDB_SET_RANGE ? NULL : &exact);
5786 case MDB_GET_MULTIPLE:
5787 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5791 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5792 rc = MDB_INCOMPATIBLE;
5796 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
5797 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
5800 case MDB_NEXT_MULTIPLE:
5805 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5806 rc = MDB_INCOMPATIBLE;
5809 if (!(mc->mc_flags & C_INITIALIZED))
5810 rc = mdb_cursor_first(mc, key, data);
5812 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
5813 if (rc == MDB_SUCCESS) {
5814 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
5817 mx = &mc->mc_xcursor->mx_cursor;
5818 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
5820 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
5821 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
5829 case MDB_NEXT_NODUP:
5830 if (!(mc->mc_flags & C_INITIALIZED))
5831 rc = mdb_cursor_first(mc, key, data);
5833 rc = mdb_cursor_next(mc, key, data, op);
5837 case MDB_PREV_NODUP:
5838 if (!(mc->mc_flags & C_INITIALIZED)) {
5839 rc = mdb_cursor_last(mc, key, data);
5842 mc->mc_flags |= C_INITIALIZED;
5843 mc->mc_ki[mc->mc_top]++;
5845 rc = mdb_cursor_prev(mc, key, data, op);
5848 rc = mdb_cursor_first(mc, key, data);
5851 mfunc = mdb_cursor_first;
5853 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5857 if (mc->mc_xcursor == NULL) {
5858 rc = MDB_INCOMPATIBLE;
5861 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
5865 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
5868 rc = mdb_cursor_last(mc, key, data);
5871 mfunc = mdb_cursor_last;
5874 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
5879 if (mc->mc_flags & C_DEL)
5880 mc->mc_flags ^= C_DEL;
5885 /** Touch all the pages in the cursor stack. Set mc_top.
5886 * Makes sure all the pages are writable, before attempting a write operation.
5887 * @param[in] mc The cursor to operate on.
5890 mdb_cursor_touch(MDB_cursor *mc)
5892 int rc = MDB_SUCCESS;
5894 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
5897 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
5898 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
5901 *mc->mc_dbflag |= DB_DIRTY;
5906 rc = mdb_page_touch(mc);
5907 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
5908 mc->mc_top = mc->mc_snum-1;
5913 /** Do not spill pages to disk if txn is getting full, may fail instead */
5914 #define MDB_NOSPILL 0x8000
5917 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5920 enum { MDB_NO_ROOT = MDB_LAST_ERRCODE+10 }; /* internal code */
5922 MDB_node *leaf = NULL;
5925 MDB_val xdata, *rdata, dkey, olddata;
5927 int do_sub = 0, insert_key, insert_data;
5928 unsigned int mcount = 0, dcount = 0, nospill;
5931 unsigned int nflags;
5934 if (mc == NULL || key == NULL)
5937 env = mc->mc_txn->mt_env;
5939 /* Check this first so counter will always be zero on any
5942 if (flags & MDB_MULTIPLE) {
5943 dcount = data[1].mv_size;
5944 data[1].mv_size = 0;
5945 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
5946 return MDB_INCOMPATIBLE;
5949 nospill = flags & MDB_NOSPILL;
5950 flags &= ~MDB_NOSPILL;
5952 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
5953 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
5955 if (key->mv_size-1 >= ENV_MAXKEY(env))
5956 return MDB_BAD_VALSIZE;
5958 #if SIZE_MAX > MAXDATASIZE
5959 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
5960 return MDB_BAD_VALSIZE;
5962 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
5963 return MDB_BAD_VALSIZE;
5966 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
5967 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
5971 if (flags == MDB_CURRENT) {
5972 if (!(mc->mc_flags & C_INITIALIZED))
5975 } else if (mc->mc_db->md_root == P_INVALID) {
5976 /* new database, cursor has nothing to point to */
5979 mc->mc_flags &= ~C_INITIALIZED;
5984 if (flags & MDB_APPEND) {
5986 rc = mdb_cursor_last(mc, &k2, &d2);
5988 rc = mc->mc_dbx->md_cmp(key, &k2);
5991 mc->mc_ki[mc->mc_top]++;
5993 /* new key is <= last key */
5998 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
6000 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
6001 DPRINTF(("duplicate key [%s]", DKEY(key)));
6003 return MDB_KEYEXIST;
6005 if (rc && rc != MDB_NOTFOUND)
6009 if (mc->mc_flags & C_DEL)
6010 mc->mc_flags ^= C_DEL;
6012 /* Cursor is positioned, check for room in the dirty list */
6014 if (flags & MDB_MULTIPLE) {
6016 xdata.mv_size = data->mv_size * dcount;
6020 if ((rc2 = mdb_page_spill(mc, key, rdata)))
6024 if (rc == MDB_NO_ROOT) {
6026 /* new database, write a root leaf page */
6027 DPUTS("allocating new root leaf page");
6028 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
6031 mdb_cursor_push(mc, np);
6032 mc->mc_db->md_root = np->mp_pgno;
6033 mc->mc_db->md_depth++;
6034 *mc->mc_dbflag |= DB_DIRTY;
6035 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
6037 np->mp_flags |= P_LEAF2;
6038 mc->mc_flags |= C_INITIALIZED;
6040 /* make sure all cursor pages are writable */
6041 rc2 = mdb_cursor_touch(mc);
6046 insert_key = insert_data = rc;
6048 /* The key does not exist */
6049 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
6050 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
6051 LEAFSIZE(key, data) > env->me_nodemax)
6053 /* Too big for a node, insert in sub-DB */
6054 fp_flags = P_LEAF|P_DIRTY;
6056 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
6057 fp->mp_lower = fp->mp_upper = olddata.mv_size = PAGEHDRSZ;
6061 /* there's only a key anyway, so this is a no-op */
6062 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6064 unsigned int ksize = mc->mc_db->md_pad;
6065 if (key->mv_size != ksize)
6066 return MDB_BAD_VALSIZE;
6067 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
6068 memcpy(ptr, key->mv_data, ksize);
6073 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6074 olddata.mv_size = NODEDSZ(leaf);
6075 olddata.mv_data = NODEDATA(leaf);
6078 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
6079 /* Prepare (sub-)page/sub-DB to accept the new item,
6080 * if needed. fp: old sub-page or a header faking
6081 * it. mp: new (sub-)page. offset: growth in page
6082 * size. xdata: node data with new page or DB.
6084 unsigned i, offset = 0;
6085 mp = fp = xdata.mv_data = env->me_pbuf;
6086 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
6088 /* Was a single item before, must convert now */
6089 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6090 /* Just overwrite the current item */
6091 if (flags == MDB_CURRENT)
6094 #if UINT_MAX < SIZE_MAX
6095 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
6096 mc->mc_dbx->md_dcmp = mdb_cmp_clong;
6098 /* does data match? */
6099 if (!mc->mc_dbx->md_dcmp(data, &olddata)) {
6100 if (flags & MDB_NODUPDATA)
6101 return MDB_KEYEXIST;
6106 /* Back up original data item */
6107 dkey.mv_size = olddata.mv_size;
6108 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
6110 /* Make sub-page header for the dup items, with dummy body */
6111 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
6112 fp->mp_lower = PAGEHDRSZ;
6113 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
6114 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6115 fp->mp_flags |= P_LEAF2;
6116 fp->mp_pad = data->mv_size;
6117 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
6119 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
6120 (dkey.mv_size & 1) + (data->mv_size & 1);
6122 fp->mp_upper = xdata.mv_size;
6123 olddata.mv_size = fp->mp_upper; /* pretend olddata is fp */
6124 } else if (leaf->mn_flags & F_SUBDATA) {
6125 /* Data is on sub-DB, just store it */
6126 flags |= F_DUPDATA|F_SUBDATA;
6129 /* Data is on sub-page */
6130 fp = olddata.mv_data;
6133 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6134 offset = EVEN(NODESIZE + sizeof(indx_t) +
6138 offset = fp->mp_pad;
6139 if (SIZELEFT(fp) < offset) {
6140 offset *= 4; /* space for 4 more */
6143 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
6145 fp->mp_flags |= P_DIRTY;
6146 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
6147 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
6151 xdata.mv_size = olddata.mv_size + offset;
6154 fp_flags = fp->mp_flags;
6155 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
6156 /* Too big for a sub-page, convert to sub-DB */
6157 fp_flags &= ~P_SUBP;
6159 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6160 fp_flags |= P_LEAF2;
6161 dummy.md_pad = fp->mp_pad;
6162 dummy.md_flags = MDB_DUPFIXED;
6163 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6164 dummy.md_flags |= MDB_INTEGERKEY;
6170 dummy.md_branch_pages = 0;
6171 dummy.md_leaf_pages = 1;
6172 dummy.md_overflow_pages = 0;
6173 dummy.md_entries = NUMKEYS(fp);
6174 xdata.mv_size = sizeof(MDB_db);
6175 xdata.mv_data = &dummy;
6176 if ((rc = mdb_page_alloc(mc, 1, &mp)))
6178 offset = env->me_psize - olddata.mv_size;
6179 flags |= F_DUPDATA|F_SUBDATA;
6180 dummy.md_root = mp->mp_pgno;
6183 mp->mp_flags = fp_flags | P_DIRTY;
6184 mp->mp_pad = fp->mp_pad;
6185 mp->mp_lower = fp->mp_lower;
6186 mp->mp_upper = fp->mp_upper + offset;
6187 if (fp_flags & P_LEAF2) {
6188 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
6190 memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper,
6191 olddata.mv_size - fp->mp_upper);
6192 for (i=0; i<NUMKEYS(fp); i++)
6193 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
6201 mdb_node_del(mc, 0);
6205 /* overflow page overwrites need special handling */
6206 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6209 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
6211 memcpy(&pg, olddata.mv_data, sizeof(pg));
6212 if ((rc2 = mdb_page_get(mc->mc_txn, pg, &omp, &level)) != 0)
6214 ovpages = omp->mp_pages;
6216 /* Is the ov page large enough? */
6217 if (ovpages >= dpages) {
6218 if (!(omp->mp_flags & P_DIRTY) &&
6219 (level || (env->me_flags & MDB_WRITEMAP)))
6221 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
6224 level = 0; /* dirty in this txn or clean */
6227 if (omp->mp_flags & P_DIRTY) {
6228 /* yes, overwrite it. Note in this case we don't
6229 * bother to try shrinking the page if the new data
6230 * is smaller than the overflow threshold.
6233 /* It is writable only in a parent txn */
6234 size_t sz = (size_t) env->me_psize * ovpages, off;
6235 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
6241 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
6242 mdb_cassert(mc, rc2 == 0);
6243 if (!(flags & MDB_RESERVE)) {
6244 /* Copy end of page, adjusting alignment so
6245 * compiler may copy words instead of bytes.
6247 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
6248 memcpy((size_t *)((char *)np + off),
6249 (size_t *)((char *)omp + off), sz - off);
6252 memcpy(np, omp, sz); /* Copy beginning of page */
6255 SETDSZ(leaf, data->mv_size);
6256 if (F_ISSET(flags, MDB_RESERVE))
6257 data->mv_data = METADATA(omp);
6259 memcpy(METADATA(omp), data->mv_data, data->mv_size);
6263 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
6265 } else if (data->mv_size == olddata.mv_size) {
6266 /* same size, just replace it. Note that we could
6267 * also reuse this node if the new data is smaller,
6268 * but instead we opt to shrink the node in that case.
6270 if (F_ISSET(flags, MDB_RESERVE))
6271 data->mv_data = olddata.mv_data;
6272 else if (!(mc->mc_flags & C_SUB))
6273 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
6275 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
6278 mdb_node_del(mc, 0);
6284 nflags = flags & NODE_ADD_FLAGS;
6285 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
6286 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
6287 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
6288 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
6290 nflags |= MDB_SPLIT_REPLACE;
6291 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
6293 /* There is room already in this leaf page. */
6294 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
6295 if (rc == 0 && insert_key) {
6296 /* Adjust other cursors pointing to mp */
6297 MDB_cursor *m2, *m3;
6298 MDB_dbi dbi = mc->mc_dbi;
6299 unsigned i = mc->mc_top;
6300 MDB_page *mp = mc->mc_pg[i];
6302 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6303 if (mc->mc_flags & C_SUB)
6304 m3 = &m2->mc_xcursor->mx_cursor;
6307 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
6308 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
6315 if (rc == MDB_SUCCESS) {
6316 /* Now store the actual data in the child DB. Note that we're
6317 * storing the user data in the keys field, so there are strict
6318 * size limits on dupdata. The actual data fields of the child
6319 * DB are all zero size.
6327 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6328 if (flags & MDB_CURRENT) {
6329 xflags = MDB_CURRENT|MDB_NOSPILL;
6331 mdb_xcursor_init1(mc, leaf);
6332 xflags = (flags & MDB_NODUPDATA) ?
6333 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
6335 /* converted, write the original data first */
6337 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
6341 /* Adjust other cursors pointing to mp */
6343 unsigned i = mc->mc_top;
6344 MDB_page *mp = mc->mc_pg[i];
6346 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6347 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6348 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6349 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
6350 mdb_xcursor_init1(m2, leaf);
6354 /* we've done our job */
6357 ecount = mc->mc_xcursor->mx_db.md_entries;
6358 if (flags & MDB_APPENDDUP)
6359 xflags |= MDB_APPEND;
6360 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
6361 if (flags & F_SUBDATA) {
6362 void *db = NODEDATA(leaf);
6363 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6365 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
6367 /* Increment count unless we just replaced an existing item. */
6369 mc->mc_db->md_entries++;
6371 /* Invalidate txn if we created an empty sub-DB */
6374 /* If we succeeded and the key didn't exist before,
6375 * make sure the cursor is marked valid.
6377 mc->mc_flags |= C_INITIALIZED;
6379 if (flags & MDB_MULTIPLE) {
6382 /* let caller know how many succeeded, if any */
6383 data[1].mv_size = mcount;
6384 if (mcount < dcount) {
6385 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
6386 insert_key = insert_data = 0;
6393 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
6396 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6401 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
6407 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
6408 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6410 if (!(mc->mc_flags & C_INITIALIZED))
6413 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6414 return MDB_NOTFOUND;
6416 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
6419 rc = mdb_cursor_touch(mc);
6423 mp = mc->mc_pg[mc->mc_top];
6426 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6428 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6429 if (flags & MDB_NODUPDATA) {
6430 /* mdb_cursor_del0() will subtract the final entry */
6431 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
6433 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
6434 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6436 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
6439 /* If sub-DB still has entries, we're done */
6440 if (mc->mc_xcursor->mx_db.md_entries) {
6441 if (leaf->mn_flags & F_SUBDATA) {
6442 /* update subDB info */
6443 void *db = NODEDATA(leaf);
6444 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6447 /* shrink fake page */
6448 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
6449 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6450 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6451 /* fix other sub-DB cursors pointed at this fake page */
6452 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6453 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6454 if (m2->mc_pg[mc->mc_top] == mp &&
6455 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
6456 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6459 mc->mc_db->md_entries--;
6460 mc->mc_flags |= C_DEL;
6463 /* otherwise fall thru and delete the sub-DB */
6466 if (leaf->mn_flags & F_SUBDATA) {
6467 /* add all the child DB's pages to the free list */
6468 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6474 /* add overflow pages to free list */
6475 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6479 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
6480 if ((rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL)) ||
6481 (rc = mdb_ovpage_free(mc, omp)))
6486 return mdb_cursor_del0(mc);
6489 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6493 /** Allocate and initialize new pages for a database.
6494 * @param[in] mc a cursor on the database being added to.
6495 * @param[in] flags flags defining what type of page is being allocated.
6496 * @param[in] num the number of pages to allocate. This is usually 1,
6497 * unless allocating overflow pages for a large record.
6498 * @param[out] mp Address of a page, or NULL on failure.
6499 * @return 0 on success, non-zero on failure.
6502 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
6507 if ((rc = mdb_page_alloc(mc, num, &np)))
6509 DPRINTF(("allocated new mpage %"Z"u, page size %u",
6510 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
6511 np->mp_flags = flags | P_DIRTY;
6512 np->mp_lower = PAGEHDRSZ;
6513 np->mp_upper = mc->mc_txn->mt_env->me_psize;
6516 mc->mc_db->md_branch_pages++;
6517 else if (IS_LEAF(np))
6518 mc->mc_db->md_leaf_pages++;
6519 else if (IS_OVERFLOW(np)) {
6520 mc->mc_db->md_overflow_pages += num;
6528 /** Calculate the size of a leaf node.
6529 * The size depends on the environment's page size; if a data item
6530 * is too large it will be put onto an overflow page and the node
6531 * size will only include the key and not the data. Sizes are always
6532 * rounded up to an even number of bytes, to guarantee 2-byte alignment
6533 * of the #MDB_node headers.
6534 * @param[in] env The environment handle.
6535 * @param[in] key The key for the node.
6536 * @param[in] data The data for the node.
6537 * @return The number of bytes needed to store the node.
6540 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
6544 sz = LEAFSIZE(key, data);
6545 if (sz > env->me_nodemax) {
6546 /* put on overflow page */
6547 sz -= data->mv_size - sizeof(pgno_t);
6550 return EVEN(sz + sizeof(indx_t));
6553 /** Calculate the size of a branch node.
6554 * The size should depend on the environment's page size but since
6555 * we currently don't support spilling large keys onto overflow
6556 * pages, it's simply the size of the #MDB_node header plus the
6557 * size of the key. Sizes are always rounded up to an even number
6558 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
6559 * @param[in] env The environment handle.
6560 * @param[in] key The key for the node.
6561 * @return The number of bytes needed to store the node.
6564 mdb_branch_size(MDB_env *env, MDB_val *key)
6569 if (sz > env->me_nodemax) {
6570 /* put on overflow page */
6571 /* not implemented */
6572 /* sz -= key->size - sizeof(pgno_t); */
6575 return sz + sizeof(indx_t);
6578 /** Add a node to the page pointed to by the cursor.
6579 * @param[in] mc The cursor for this operation.
6580 * @param[in] indx The index on the page where the new node should be added.
6581 * @param[in] key The key for the new node.
6582 * @param[in] data The data for the new node, if any.
6583 * @param[in] pgno The page number, if adding a branch node.
6584 * @param[in] flags Flags for the node.
6585 * @return 0 on success, non-zero on failure. Possible errors are:
6587 * <li>ENOMEM - failed to allocate overflow pages for the node.
6588 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
6589 * should never happen since all callers already calculate the
6590 * page's free space before calling this function.
6594 mdb_node_add(MDB_cursor *mc, indx_t indx,
6595 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
6598 size_t node_size = NODESIZE;
6602 MDB_page *mp = mc->mc_pg[mc->mc_top];
6603 MDB_page *ofp = NULL; /* overflow page */
6606 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
6608 DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
6609 IS_LEAF(mp) ? "leaf" : "branch",
6610 IS_SUBP(mp) ? "sub-" : "",
6611 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
6612 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
6615 /* Move higher keys up one slot. */
6616 int ksize = mc->mc_db->md_pad, dif;
6617 char *ptr = LEAF2KEY(mp, indx, ksize);
6618 dif = NUMKEYS(mp) - indx;
6620 memmove(ptr+ksize, ptr, dif*ksize);
6621 /* insert new key */
6622 memcpy(ptr, key->mv_data, ksize);
6624 /* Just using these for counting */
6625 mp->mp_lower += sizeof(indx_t);
6626 mp->mp_upper -= ksize - sizeof(indx_t);
6630 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
6632 node_size += key->mv_size;
6634 mdb_cassert(mc, data);
6635 if (F_ISSET(flags, F_BIGDATA)) {
6636 /* Data already on overflow page. */
6637 node_size += sizeof(pgno_t);
6638 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
6639 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
6641 /* Put data on overflow page. */
6642 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
6643 data->mv_size, node_size+data->mv_size));
6644 node_size = EVEN(node_size + sizeof(pgno_t));
6645 if ((ssize_t)node_size > room)
6647 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
6649 DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
6653 node_size += data->mv_size;
6656 node_size = EVEN(node_size);
6657 if ((ssize_t)node_size > room)
6661 /* Move higher pointers up one slot. */
6662 for (i = NUMKEYS(mp); i > indx; i--)
6663 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
6665 /* Adjust free space offsets. */
6666 ofs = mp->mp_upper - node_size;
6667 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
6668 mp->mp_ptrs[indx] = ofs;
6670 mp->mp_lower += sizeof(indx_t);
6672 /* Write the node data. */
6673 node = NODEPTR(mp, indx);
6674 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
6675 node->mn_flags = flags;
6677 SETDSZ(node,data->mv_size);
6682 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6685 mdb_cassert(mc, key);
6687 if (F_ISSET(flags, F_BIGDATA))
6688 memcpy(node->mn_data + key->mv_size, data->mv_data,
6690 else if (F_ISSET(flags, MDB_RESERVE))
6691 data->mv_data = node->mn_data + key->mv_size;
6693 memcpy(node->mn_data + key->mv_size, data->mv_data,
6696 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
6698 if (F_ISSET(flags, MDB_RESERVE))
6699 data->mv_data = METADATA(ofp);
6701 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
6708 DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
6709 mdb_dbg_pgno(mp), NUMKEYS(mp)));
6710 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
6711 DPRINTF(("node size = %"Z"u", node_size));
6712 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6713 return MDB_PAGE_FULL;
6716 /** Delete the specified node from a page.
6717 * @param[in] mc Cursor pointing to the node to delete.
6718 * @param[in] ksize The size of a node. Only used if the page is
6719 * part of a #MDB_DUPFIXED database.
6722 mdb_node_del(MDB_cursor *mc, int ksize)
6724 MDB_page *mp = mc->mc_pg[mc->mc_top];
6725 indx_t indx = mc->mc_ki[mc->mc_top];
6727 indx_t i, j, numkeys, ptr;
6731 DPRINTF(("delete node %u on %s page %"Z"u", indx,
6732 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
6733 numkeys = NUMKEYS(mp);
6734 mdb_cassert(mc, indx < numkeys);
6737 int x = numkeys - 1 - indx;
6738 base = LEAF2KEY(mp, indx, ksize);
6740 memmove(base, base + ksize, x * ksize);
6741 mp->mp_lower -= sizeof(indx_t);
6742 mp->mp_upper += ksize - sizeof(indx_t);
6746 node = NODEPTR(mp, indx);
6747 sz = NODESIZE + node->mn_ksize;
6749 if (F_ISSET(node->mn_flags, F_BIGDATA))
6750 sz += sizeof(pgno_t);
6752 sz += NODEDSZ(node);
6756 ptr = mp->mp_ptrs[indx];
6757 for (i = j = 0; i < numkeys; i++) {
6759 mp->mp_ptrs[j] = mp->mp_ptrs[i];
6760 if (mp->mp_ptrs[i] < ptr)
6761 mp->mp_ptrs[j] += sz;
6766 base = (char *)mp + mp->mp_upper;
6767 memmove(base + sz, base, ptr - mp->mp_upper);
6769 mp->mp_lower -= sizeof(indx_t);
6773 /** Compact the main page after deleting a node on a subpage.
6774 * @param[in] mp The main page to operate on.
6775 * @param[in] indx The index of the subpage on the main page.
6778 mdb_node_shrink(MDB_page *mp, indx_t indx)
6784 indx_t i, numkeys, ptr;
6786 node = NODEPTR(mp, indx);
6787 sp = (MDB_page *)NODEDATA(node);
6788 delta = SIZELEFT(sp);
6789 xp = (MDB_page *)((char *)sp + delta);
6791 /* shift subpage upward */
6793 nsize = NUMKEYS(sp) * sp->mp_pad;
6795 return; /* do not make the node uneven-sized */
6796 memmove(METADATA(xp), METADATA(sp), nsize);
6799 numkeys = NUMKEYS(sp);
6800 for (i=numkeys-1; i>=0; i--)
6801 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
6803 xp->mp_upper = sp->mp_lower;
6804 xp->mp_lower = sp->mp_lower;
6805 xp->mp_flags = sp->mp_flags;
6806 xp->mp_pad = sp->mp_pad;
6807 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
6809 nsize = NODEDSZ(node) - delta;
6810 SETDSZ(node, nsize);
6812 /* shift lower nodes upward */
6813 ptr = mp->mp_ptrs[indx];
6814 numkeys = NUMKEYS(mp);
6815 for (i = 0; i < numkeys; i++) {
6816 if (mp->mp_ptrs[i] <= ptr)
6817 mp->mp_ptrs[i] += delta;
6820 base = (char *)mp + mp->mp_upper;
6821 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
6822 mp->mp_upper += delta;
6825 /** Initial setup of a sorted-dups cursor.
6826 * Sorted duplicates are implemented as a sub-database for the given key.
6827 * The duplicate data items are actually keys of the sub-database.
6828 * Operations on the duplicate data items are performed using a sub-cursor
6829 * initialized when the sub-database is first accessed. This function does
6830 * the preliminary setup of the sub-cursor, filling in the fields that
6831 * depend only on the parent DB.
6832 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6835 mdb_xcursor_init0(MDB_cursor *mc)
6837 MDB_xcursor *mx = mc->mc_xcursor;
6839 mx->mx_cursor.mc_xcursor = NULL;
6840 mx->mx_cursor.mc_txn = mc->mc_txn;
6841 mx->mx_cursor.mc_db = &mx->mx_db;
6842 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
6843 mx->mx_cursor.mc_dbi = mc->mc_dbi;
6844 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
6845 mx->mx_cursor.mc_snum = 0;
6846 mx->mx_cursor.mc_top = 0;
6847 mx->mx_cursor.mc_flags = C_SUB;
6848 mx->mx_dbx.md_name.mv_size = 0;
6849 mx->mx_dbx.md_name.mv_data = NULL;
6850 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
6851 mx->mx_dbx.md_dcmp = NULL;
6852 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
6855 /** Final setup of a sorted-dups cursor.
6856 * Sets up the fields that depend on the data from the main cursor.
6857 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6858 * @param[in] node The data containing the #MDB_db record for the
6859 * sorted-dup database.
6862 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
6864 MDB_xcursor *mx = mc->mc_xcursor;
6866 if (node->mn_flags & F_SUBDATA) {
6867 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
6868 mx->mx_cursor.mc_pg[0] = 0;
6869 mx->mx_cursor.mc_snum = 0;
6870 mx->mx_cursor.mc_top = 0;
6871 mx->mx_cursor.mc_flags = C_SUB;
6873 MDB_page *fp = NODEDATA(node);
6874 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
6875 mx->mx_db.md_flags = 0;
6876 mx->mx_db.md_depth = 1;
6877 mx->mx_db.md_branch_pages = 0;
6878 mx->mx_db.md_leaf_pages = 1;
6879 mx->mx_db.md_overflow_pages = 0;
6880 mx->mx_db.md_entries = NUMKEYS(fp);
6881 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
6882 mx->mx_cursor.mc_snum = 1;
6883 mx->mx_cursor.mc_top = 0;
6884 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
6885 mx->mx_cursor.mc_pg[0] = fp;
6886 mx->mx_cursor.mc_ki[0] = 0;
6887 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6888 mx->mx_db.md_flags = MDB_DUPFIXED;
6889 mx->mx_db.md_pad = fp->mp_pad;
6890 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6891 mx->mx_db.md_flags |= MDB_INTEGERKEY;
6894 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
6895 mx->mx_db.md_root));
6896 mx->mx_dbflag = DB_VALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
6897 #if UINT_MAX < SIZE_MAX
6898 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
6899 mx->mx_dbx.md_cmp = mdb_cmp_clong;
6903 /** Initialize a cursor for a given transaction and database. */
6905 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
6908 mc->mc_backup = NULL;
6911 mc->mc_db = &txn->mt_dbs[dbi];
6912 mc->mc_dbx = &txn->mt_dbxs[dbi];
6913 mc->mc_dbflag = &txn->mt_dbflags[dbi];
6918 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
6919 mdb_tassert(txn, mx != NULL);
6920 mc->mc_xcursor = mx;
6921 mdb_xcursor_init0(mc);
6923 mc->mc_xcursor = NULL;
6925 if (*mc->mc_dbflag & DB_STALE) {
6926 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
6931 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
6934 size_t size = sizeof(MDB_cursor);
6936 if (!ret || !TXN_DBI_EXIST(txn, dbi))
6939 if (txn->mt_flags & MDB_TXN_ERROR)
6942 /* Allow read access to the freelist */
6943 if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
6946 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
6947 size += sizeof(MDB_xcursor);
6949 if ((mc = malloc(size)) != NULL) {
6950 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
6951 if (txn->mt_cursors) {
6952 mc->mc_next = txn->mt_cursors[dbi];
6953 txn->mt_cursors[dbi] = mc;
6954 mc->mc_flags |= C_UNTRACK;
6966 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
6968 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi))
6971 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
6974 if (txn->mt_flags & MDB_TXN_ERROR)
6977 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
6981 /* Return the count of duplicate data items for the current key */
6983 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
6987 if (mc == NULL || countp == NULL)
6990 if (mc->mc_xcursor == NULL)
6991 return MDB_INCOMPATIBLE;
6993 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
6996 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6997 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7000 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
7003 *countp = mc->mc_xcursor->mx_db.md_entries;
7009 mdb_cursor_close(MDB_cursor *mc)
7011 if (mc && !mc->mc_backup) {
7012 /* remove from txn, if tracked */
7013 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
7014 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
7015 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
7017 *prev = mc->mc_next;
7024 mdb_cursor_txn(MDB_cursor *mc)
7026 if (!mc) return NULL;
7031 mdb_cursor_dbi(MDB_cursor *mc)
7036 /** Replace the key for a branch node with a new key.
7037 * @param[in] mc Cursor pointing to the node to operate on.
7038 * @param[in] key The new key to use.
7039 * @return 0 on success, non-zero on failure.
7042 mdb_update_key(MDB_cursor *mc, MDB_val *key)
7048 int delta, ksize, oksize;
7049 indx_t ptr, i, numkeys, indx;
7052 indx = mc->mc_ki[mc->mc_top];
7053 mp = mc->mc_pg[mc->mc_top];
7054 node = NODEPTR(mp, indx);
7055 ptr = mp->mp_ptrs[indx];
7059 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
7060 k2.mv_data = NODEKEY(node);
7061 k2.mv_size = node->mn_ksize;
7062 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
7064 mdb_dkey(&k2, kbuf2),
7070 /* Sizes must be 2-byte aligned. */
7071 ksize = EVEN(key->mv_size);
7072 oksize = EVEN(node->mn_ksize);
7073 delta = ksize - oksize;
7075 /* Shift node contents if EVEN(key length) changed. */
7077 if (delta > 0 && SIZELEFT(mp) < delta) {
7079 /* not enough space left, do a delete and split */
7080 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
7081 pgno = NODEPGNO(node);
7082 mdb_node_del(mc, 0);
7083 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
7086 numkeys = NUMKEYS(mp);
7087 for (i = 0; i < numkeys; i++) {
7088 if (mp->mp_ptrs[i] <= ptr)
7089 mp->mp_ptrs[i] -= delta;
7092 base = (char *)mp + mp->mp_upper;
7093 len = ptr - mp->mp_upper + NODESIZE;
7094 memmove(base - delta, base, len);
7095 mp->mp_upper -= delta;
7097 node = NODEPTR(mp, indx);
7100 /* But even if no shift was needed, update ksize */
7101 if (node->mn_ksize != key->mv_size)
7102 node->mn_ksize = key->mv_size;
7105 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7111 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
7113 /** Move a node from csrc to cdst.
7116 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
7123 unsigned short flags;
7127 /* Mark src and dst as dirty. */
7128 if ((rc = mdb_page_touch(csrc)) ||
7129 (rc = mdb_page_touch(cdst)))
7132 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7133 key.mv_size = csrc->mc_db->md_pad;
7134 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
7136 data.mv_data = NULL;
7140 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
7141 mdb_cassert(csrc, !((size_t)srcnode & 1));
7142 srcpg = NODEPGNO(srcnode);
7143 flags = srcnode->mn_flags;
7144 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7145 unsigned int snum = csrc->mc_snum;
7147 /* must find the lowest key below src */
7148 rc = mdb_page_search_lowest(csrc);
7151 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7152 key.mv_size = csrc->mc_db->md_pad;
7153 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7155 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7156 key.mv_size = NODEKSZ(s2);
7157 key.mv_data = NODEKEY(s2);
7159 csrc->mc_snum = snum--;
7160 csrc->mc_top = snum;
7162 key.mv_size = NODEKSZ(srcnode);
7163 key.mv_data = NODEKEY(srcnode);
7165 data.mv_size = NODEDSZ(srcnode);
7166 data.mv_data = NODEDATA(srcnode);
7168 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
7169 unsigned int snum = cdst->mc_snum;
7172 /* must find the lowest key below dst */
7173 mdb_cursor_copy(cdst, &mn);
7174 rc = mdb_page_search_lowest(&mn);
7177 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7178 bkey.mv_size = mn.mc_db->md_pad;
7179 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
7181 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7182 bkey.mv_size = NODEKSZ(s2);
7183 bkey.mv_data = NODEKEY(s2);
7185 mn.mc_snum = snum--;
7188 rc = mdb_update_key(&mn, &bkey);
7193 DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
7194 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
7195 csrc->mc_ki[csrc->mc_top],
7197 csrc->mc_pg[csrc->mc_top]->mp_pgno,
7198 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
7200 /* Add the node to the destination page.
7202 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
7203 if (rc != MDB_SUCCESS)
7206 /* Delete the node from the source page.
7208 mdb_node_del(csrc, key.mv_size);
7211 /* Adjust other cursors pointing to mp */
7212 MDB_cursor *m2, *m3;
7213 MDB_dbi dbi = csrc->mc_dbi;
7214 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
7216 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7217 if (csrc->mc_flags & C_SUB)
7218 m3 = &m2->mc_xcursor->mx_cursor;
7221 if (m3 == csrc) continue;
7222 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
7223 csrc->mc_ki[csrc->mc_top]) {
7224 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
7225 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7230 /* Update the parent separators.
7232 if (csrc->mc_ki[csrc->mc_top] == 0) {
7233 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
7234 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7235 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7237 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7238 key.mv_size = NODEKSZ(srcnode);
7239 key.mv_data = NODEKEY(srcnode);
7241 DPRINTF(("update separator for source page %"Z"u to [%s]",
7242 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
7243 mdb_cursor_copy(csrc, &mn);
7246 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7249 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7251 indx_t ix = csrc->mc_ki[csrc->mc_top];
7252 nullkey.mv_size = 0;
7253 csrc->mc_ki[csrc->mc_top] = 0;
7254 rc = mdb_update_key(csrc, &nullkey);
7255 csrc->mc_ki[csrc->mc_top] = ix;
7256 mdb_cassert(csrc, rc == MDB_SUCCESS);
7260 if (cdst->mc_ki[cdst->mc_top] == 0) {
7261 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
7262 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7263 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
7265 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
7266 key.mv_size = NODEKSZ(srcnode);
7267 key.mv_data = NODEKEY(srcnode);
7269 DPRINTF(("update separator for destination page %"Z"u to [%s]",
7270 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
7271 mdb_cursor_copy(cdst, &mn);
7274 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7277 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
7279 indx_t ix = cdst->mc_ki[cdst->mc_top];
7280 nullkey.mv_size = 0;
7281 cdst->mc_ki[cdst->mc_top] = 0;
7282 rc = mdb_update_key(cdst, &nullkey);
7283 cdst->mc_ki[cdst->mc_top] = ix;
7284 mdb_cassert(csrc, rc == MDB_SUCCESS);
7291 /** Merge one page into another.
7292 * The nodes from the page pointed to by \b csrc will
7293 * be copied to the page pointed to by \b cdst and then
7294 * the \b csrc page will be freed.
7295 * @param[in] csrc Cursor pointing to the source page.
7296 * @param[in] cdst Cursor pointing to the destination page.
7297 * @return 0 on success, non-zero on failure.
7300 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
7302 MDB_page *psrc, *pdst;
7309 psrc = csrc->mc_pg[csrc->mc_top];
7310 pdst = cdst->mc_pg[cdst->mc_top];
7312 DPRINTF(("merging page %"Z"u into %"Z"u", psrc->mp_pgno, pdst->mp_pgno));
7314 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
7315 mdb_cassert(csrc, cdst->mc_snum > 1);
7317 /* Mark dst as dirty. */
7318 if ((rc = mdb_page_touch(cdst)))
7321 /* Move all nodes from src to dst.
7323 j = nkeys = NUMKEYS(pdst);
7324 if (IS_LEAF2(psrc)) {
7325 key.mv_size = csrc->mc_db->md_pad;
7326 key.mv_data = METADATA(psrc);
7327 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7328 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
7329 if (rc != MDB_SUCCESS)
7331 key.mv_data = (char *)key.mv_data + key.mv_size;
7334 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7335 srcnode = NODEPTR(psrc, i);
7336 if (i == 0 && IS_BRANCH(psrc)) {
7339 mdb_cursor_copy(csrc, &mn);
7340 /* must find the lowest key below src */
7341 rc = mdb_page_search_lowest(&mn);
7344 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7345 key.mv_size = mn.mc_db->md_pad;
7346 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
7348 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7349 key.mv_size = NODEKSZ(s2);
7350 key.mv_data = NODEKEY(s2);
7353 key.mv_size = srcnode->mn_ksize;
7354 key.mv_data = NODEKEY(srcnode);
7357 data.mv_size = NODEDSZ(srcnode);
7358 data.mv_data = NODEDATA(srcnode);
7359 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
7360 if (rc != MDB_SUCCESS)
7365 DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
7366 pdst->mp_pgno, NUMKEYS(pdst),
7367 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
7369 /* Unlink the src page from parent and add to free list.
7372 mdb_node_del(csrc, 0);
7373 if (csrc->mc_ki[csrc->mc_top] == 0) {
7375 rc = mdb_update_key(csrc, &key);
7383 psrc = csrc->mc_pg[csrc->mc_top];
7384 /* If not operating on FreeDB, allow this page to be reused
7385 * in this txn. Otherwise just add to free list.
7387 rc = mdb_page_loose(csrc, psrc);
7391 csrc->mc_db->md_leaf_pages--;
7393 csrc->mc_db->md_branch_pages--;
7395 /* Adjust other cursors pointing to mp */
7396 MDB_cursor *m2, *m3;
7397 MDB_dbi dbi = csrc->mc_dbi;
7399 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7400 if (csrc->mc_flags & C_SUB)
7401 m3 = &m2->mc_xcursor->mx_cursor;
7404 if (m3 == csrc) continue;
7405 if (m3->mc_snum < csrc->mc_snum) continue;
7406 if (m3->mc_pg[csrc->mc_top] == psrc) {
7407 m3->mc_pg[csrc->mc_top] = pdst;
7408 m3->mc_ki[csrc->mc_top] += nkeys;
7413 unsigned int snum = cdst->mc_snum;
7414 uint16_t depth = cdst->mc_db->md_depth;
7415 mdb_cursor_pop(cdst);
7416 rc = mdb_rebalance(cdst);
7417 /* Did the tree shrink? */
7418 if (depth > cdst->mc_db->md_depth)
7420 cdst->mc_snum = snum;
7421 cdst->mc_top = snum-1;
7426 /** Copy the contents of a cursor.
7427 * @param[in] csrc The cursor to copy from.
7428 * @param[out] cdst The cursor to copy to.
7431 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
7435 cdst->mc_txn = csrc->mc_txn;
7436 cdst->mc_dbi = csrc->mc_dbi;
7437 cdst->mc_db = csrc->mc_db;
7438 cdst->mc_dbx = csrc->mc_dbx;
7439 cdst->mc_snum = csrc->mc_snum;
7440 cdst->mc_top = csrc->mc_top;
7441 cdst->mc_flags = csrc->mc_flags;
7443 for (i=0; i<csrc->mc_snum; i++) {
7444 cdst->mc_pg[i] = csrc->mc_pg[i];
7445 cdst->mc_ki[i] = csrc->mc_ki[i];
7449 /** Rebalance the tree after a delete operation.
7450 * @param[in] mc Cursor pointing to the page where rebalancing
7452 * @return 0 on success, non-zero on failure.
7455 mdb_rebalance(MDB_cursor *mc)
7459 unsigned int ptop, minkeys;
7463 minkeys = 1 + (IS_BRANCH(mc->mc_pg[mc->mc_top]));
7464 DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
7465 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
7466 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
7467 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
7469 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD &&
7470 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
7471 DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
7472 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
7476 if (mc->mc_snum < 2) {
7477 MDB_page *mp = mc->mc_pg[0];
7479 DPUTS("Can't rebalance a subpage, ignoring");
7482 if (NUMKEYS(mp) == 0) {
7483 DPUTS("tree is completely empty");
7484 mc->mc_db->md_root = P_INVALID;
7485 mc->mc_db->md_depth = 0;
7486 mc->mc_db->md_leaf_pages = 0;
7487 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7490 /* Adjust cursors pointing to mp */
7493 mc->mc_flags &= ~C_INITIALIZED;
7495 MDB_cursor *m2, *m3;
7496 MDB_dbi dbi = mc->mc_dbi;
7498 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7499 if (mc->mc_flags & C_SUB)
7500 m3 = &m2->mc_xcursor->mx_cursor;
7503 if (m3->mc_snum < mc->mc_snum) continue;
7504 if (m3->mc_pg[0] == mp) {
7507 m3->mc_flags &= ~C_INITIALIZED;
7511 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
7513 DPUTS("collapsing root page!");
7514 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7517 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
7518 rc = mdb_page_get(mc->mc_txn,mc->mc_db->md_root,&mc->mc_pg[0],NULL);
7521 mc->mc_db->md_depth--;
7522 mc->mc_db->md_branch_pages--;
7523 mc->mc_ki[0] = mc->mc_ki[1];
7524 for (i = 1; i<mc->mc_db->md_depth; i++) {
7525 mc->mc_pg[i] = mc->mc_pg[i+1];
7526 mc->mc_ki[i] = mc->mc_ki[i+1];
7529 /* Adjust other cursors pointing to mp */
7530 MDB_cursor *m2, *m3;
7531 MDB_dbi dbi = mc->mc_dbi;
7533 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7534 if (mc->mc_flags & C_SUB)
7535 m3 = &m2->mc_xcursor->mx_cursor;
7538 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
7539 if (m3->mc_pg[0] == mp) {
7542 for (i=0; i<m3->mc_snum; i++) {
7543 m3->mc_pg[i] = m3->mc_pg[i+1];
7544 m3->mc_ki[i] = m3->mc_ki[i+1];
7550 DPUTS("root page doesn't need rebalancing");
7554 /* The parent (branch page) must have at least 2 pointers,
7555 * otherwise the tree is invalid.
7557 ptop = mc->mc_top-1;
7558 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
7560 /* Leaf page fill factor is below the threshold.
7561 * Try to move keys from left or right neighbor, or
7562 * merge with a neighbor page.
7567 mdb_cursor_copy(mc, &mn);
7568 mn.mc_xcursor = NULL;
7570 oldki = mc->mc_ki[mc->mc_top];
7571 if (mc->mc_ki[ptop] == 0) {
7572 /* We're the leftmost leaf in our parent.
7574 DPUTS("reading right neighbor");
7576 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7577 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7580 mn.mc_ki[mn.mc_top] = 0;
7581 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
7583 /* There is at least one neighbor to the left.
7585 DPUTS("reading left neighbor");
7587 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7588 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7591 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
7592 mc->mc_ki[mc->mc_top] = 0;
7595 DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
7596 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
7597 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
7599 /* If the neighbor page is above threshold and has enough keys,
7600 * move one key from it. Otherwise we should try to merge them.
7601 * (A branch page must never have less than 2 keys.)
7603 minkeys = 1 + (IS_BRANCH(mn.mc_pg[mn.mc_top]));
7604 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
7605 rc = mdb_node_move(&mn, mc);
7606 if (mc->mc_ki[ptop]) {
7610 if (mc->mc_ki[ptop] == 0) {
7611 rc = mdb_page_merge(&mn, mc);
7613 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
7614 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
7615 rc = mdb_page_merge(mc, &mn);
7616 mdb_cursor_copy(&mn, mc);
7618 mc->mc_flags &= ~C_EOF;
7620 mc->mc_ki[mc->mc_top] = oldki;
7624 /** Complete a delete operation started by #mdb_cursor_del(). */
7626 mdb_cursor_del0(MDB_cursor *mc)
7633 ki = mc->mc_ki[mc->mc_top];
7634 mdb_node_del(mc, mc->mc_db->md_pad);
7635 mc->mc_db->md_entries--;
7636 rc = mdb_rebalance(mc);
7638 if (rc == MDB_SUCCESS) {
7639 MDB_cursor *m2, *m3;
7640 MDB_dbi dbi = mc->mc_dbi;
7642 mp = mc->mc_pg[mc->mc_top];
7643 nkeys = NUMKEYS(mp);
7645 /* if mc points past last node in page, find next sibling */
7646 if (mc->mc_ki[mc->mc_top] >= nkeys) {
7647 rc = mdb_cursor_sibling(mc, 1);
7648 if (rc == MDB_NOTFOUND)
7652 /* Adjust other cursors pointing to mp */
7653 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
7654 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
7655 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
7657 if (m3 == mc || m3->mc_snum < mc->mc_snum)
7659 if (m3->mc_pg[mc->mc_top] == mp) {
7660 if (m3->mc_ki[mc->mc_top] >= ki) {
7661 m3->mc_flags |= C_DEL;
7662 if (m3->mc_ki[mc->mc_top] > ki)
7663 m3->mc_ki[mc->mc_top]--;
7665 if (m3->mc_ki[mc->mc_top] >= nkeys) {
7666 rc = mdb_cursor_sibling(m3, 1);
7667 if (rc == MDB_NOTFOUND)
7672 mc->mc_flags |= C_DEL;
7676 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7681 mdb_del(MDB_txn *txn, MDB_dbi dbi,
7682 MDB_val *key, MDB_val *data)
7684 if (!key || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
7687 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
7688 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7690 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
7691 /* must ignore any data */
7695 return mdb_del0(txn, dbi, key, data, 0);
7699 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
7700 MDB_val *key, MDB_val *data, unsigned flags)
7705 MDB_val rdata, *xdata;
7709 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
7711 mdb_cursor_init(&mc, txn, dbi, &mx);
7720 flags |= MDB_NODUPDATA;
7722 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
7724 /* let mdb_page_split know about this cursor if needed:
7725 * delete will trigger a rebalance; if it needs to move
7726 * a node from one page to another, it will have to
7727 * update the parent's separator key(s). If the new sepkey
7728 * is larger than the current one, the parent page may
7729 * run out of space, triggering a split. We need this
7730 * cursor to be consistent until the end of the rebalance.
7732 mc.mc_flags |= C_UNTRACK;
7733 mc.mc_next = txn->mt_cursors[dbi];
7734 txn->mt_cursors[dbi] = &mc;
7735 rc = mdb_cursor_del(&mc, flags);
7736 txn->mt_cursors[dbi] = mc.mc_next;
7741 /** Split a page and insert a new node.
7742 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
7743 * The cursor will be updated to point to the actual page and index where
7744 * the node got inserted after the split.
7745 * @param[in] newkey The key for the newly inserted node.
7746 * @param[in] newdata The data for the newly inserted node.
7747 * @param[in] newpgno The page number, if the new node is a branch node.
7748 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
7749 * @return 0 on success, non-zero on failure.
7752 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
7753 unsigned int nflags)
7756 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
7759 int i, j, split_indx, nkeys, pmax;
7760 MDB_env *env = mc->mc_txn->mt_env;
7762 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
7763 MDB_page *copy = NULL;
7764 MDB_page *mp, *rp, *pp;
7769 mp = mc->mc_pg[mc->mc_top];
7770 newindx = mc->mc_ki[mc->mc_top];
7771 nkeys = NUMKEYS(mp);
7773 DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i/%i",
7774 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
7775 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
7777 /* Create a right sibling. */
7778 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
7780 DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
7782 if (mc->mc_snum < 2) {
7783 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
7785 /* shift current top to make room for new parent */
7786 mc->mc_pg[1] = mc->mc_pg[0];
7787 mc->mc_ki[1] = mc->mc_ki[0];
7790 mc->mc_db->md_root = pp->mp_pgno;
7791 DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
7792 mc->mc_db->md_depth++;
7795 /* Add left (implicit) pointer. */
7796 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
7797 /* undo the pre-push */
7798 mc->mc_pg[0] = mc->mc_pg[1];
7799 mc->mc_ki[0] = mc->mc_ki[1];
7800 mc->mc_db->md_root = mp->mp_pgno;
7801 mc->mc_db->md_depth--;
7808 ptop = mc->mc_top-1;
7809 DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
7812 mc->mc_flags |= C_SPLITTING;
7813 mdb_cursor_copy(mc, &mn);
7814 mn.mc_pg[mn.mc_top] = rp;
7815 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
7817 if (nflags & MDB_APPEND) {
7818 mn.mc_ki[mn.mc_top] = 0;
7820 split_indx = newindx;
7824 split_indx = (nkeys+1) / 2;
7829 unsigned int lsize, rsize, ksize;
7830 /* Move half of the keys to the right sibling */
7831 x = mc->mc_ki[mc->mc_top] - split_indx;
7832 ksize = mc->mc_db->md_pad;
7833 split = LEAF2KEY(mp, split_indx, ksize);
7834 rsize = (nkeys - split_indx) * ksize;
7835 lsize = (nkeys - split_indx) * sizeof(indx_t);
7836 mp->mp_lower -= lsize;
7837 rp->mp_lower += lsize;
7838 mp->mp_upper += rsize - lsize;
7839 rp->mp_upper -= rsize - lsize;
7840 sepkey.mv_size = ksize;
7841 if (newindx == split_indx) {
7842 sepkey.mv_data = newkey->mv_data;
7844 sepkey.mv_data = split;
7847 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
7848 memcpy(rp->mp_ptrs, split, rsize);
7849 sepkey.mv_data = rp->mp_ptrs;
7850 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
7851 memcpy(ins, newkey->mv_data, ksize);
7852 mp->mp_lower += sizeof(indx_t);
7853 mp->mp_upper -= ksize - sizeof(indx_t);
7856 memcpy(rp->mp_ptrs, split, x * ksize);
7857 ins = LEAF2KEY(rp, x, ksize);
7858 memcpy(ins, newkey->mv_data, ksize);
7859 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
7860 rp->mp_lower += sizeof(indx_t);
7861 rp->mp_upper -= ksize - sizeof(indx_t);
7862 mc->mc_ki[mc->mc_top] = x;
7863 mc->mc_pg[mc->mc_top] = rp;
7866 int psize, nsize, k;
7867 /* Maximum free space in an empty page */
7868 pmax = env->me_psize - PAGEHDRSZ;
7870 nsize = mdb_leaf_size(env, newkey, newdata);
7872 nsize = mdb_branch_size(env, newkey);
7873 nsize = EVEN(nsize);
7875 /* grab a page to hold a temporary copy */
7876 copy = mdb_page_malloc(mc->mc_txn, 1);
7881 copy->mp_pgno = mp->mp_pgno;
7882 copy->mp_flags = mp->mp_flags;
7883 copy->mp_lower = PAGEHDRSZ;
7884 copy->mp_upper = env->me_psize;
7886 /* prepare to insert */
7887 for (i=0, j=0; i<nkeys; i++) {
7889 copy->mp_ptrs[j++] = 0;
7891 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
7894 /* When items are relatively large the split point needs
7895 * to be checked, because being off-by-one will make the
7896 * difference between success or failure in mdb_node_add.
7898 * It's also relevant if a page happens to be laid out
7899 * such that one half of its nodes are all "small" and
7900 * the other half of its nodes are "large." If the new
7901 * item is also "large" and falls on the half with
7902 * "large" nodes, it also may not fit.
7904 * As a final tweak, if the new item goes on the last
7905 * spot on the page (and thus, onto the new page), bias
7906 * the split so the new page is emptier than the old page.
7907 * This yields better packing during sequential inserts.
7909 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
7910 /* Find split point */
7912 if (newindx <= split_indx || newindx >= nkeys) {
7914 k = newindx >= nkeys ? nkeys : split_indx+2;
7919 for (; i!=k; i+=j) {
7924 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i]);
7925 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
7927 if (F_ISSET(node->mn_flags, F_BIGDATA))
7928 psize += sizeof(pgno_t);
7930 psize += NODEDSZ(node);
7932 psize = EVEN(psize);
7934 if (psize > pmax || i == k-j) {
7935 split_indx = i + (j<0);
7940 if (split_indx == newindx) {
7941 sepkey.mv_size = newkey->mv_size;
7942 sepkey.mv_data = newkey->mv_data;
7944 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx]);
7945 sepkey.mv_size = node->mn_ksize;
7946 sepkey.mv_data = NODEKEY(node);
7951 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
7953 /* Copy separator key to the parent.
7955 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
7959 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
7964 if (mn.mc_snum == mc->mc_snum) {
7965 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
7966 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
7967 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
7968 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
7973 /* Right page might now have changed parent.
7974 * Check if left page also changed parent.
7976 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7977 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7978 for (i=0; i<ptop; i++) {
7979 mc->mc_pg[i] = mn.mc_pg[i];
7980 mc->mc_ki[i] = mn.mc_ki[i];
7982 mc->mc_pg[ptop] = mn.mc_pg[ptop];
7983 if (mn.mc_ki[ptop]) {
7984 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
7986 /* find right page's left sibling */
7987 mc->mc_ki[ptop] = mn.mc_ki[ptop];
7988 mdb_cursor_sibling(mc, 0);
7993 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
7996 mc->mc_flags ^= C_SPLITTING;
7997 if (rc != MDB_SUCCESS) {
8000 if (nflags & MDB_APPEND) {
8001 mc->mc_pg[mc->mc_top] = rp;
8002 mc->mc_ki[mc->mc_top] = 0;
8003 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
8006 for (i=0; i<mc->mc_top; i++)
8007 mc->mc_ki[i] = mn.mc_ki[i];
8008 } else if (!IS_LEAF2(mp)) {
8010 mc->mc_pg[mc->mc_top] = rp;
8015 rkey.mv_data = newkey->mv_data;
8016 rkey.mv_size = newkey->mv_size;
8022 /* Update index for the new key. */
8023 mc->mc_ki[mc->mc_top] = j;
8025 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i]);
8026 rkey.mv_data = NODEKEY(node);
8027 rkey.mv_size = node->mn_ksize;
8029 xdata.mv_data = NODEDATA(node);
8030 xdata.mv_size = NODEDSZ(node);
8033 pgno = NODEPGNO(node);
8034 flags = node->mn_flags;
8037 if (!IS_LEAF(mp) && j == 0) {
8038 /* First branch index doesn't need key data. */
8042 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
8048 mc->mc_pg[mc->mc_top] = copy;
8053 } while (i != split_indx);
8055 nkeys = NUMKEYS(copy);
8056 for (i=0; i<nkeys; i++)
8057 mp->mp_ptrs[i] = copy->mp_ptrs[i];
8058 mp->mp_lower = copy->mp_lower;
8059 mp->mp_upper = copy->mp_upper;
8060 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
8061 env->me_psize - copy->mp_upper);
8063 /* reset back to original page */
8064 if (newindx < split_indx) {
8065 mc->mc_pg[mc->mc_top] = mp;
8066 if (nflags & MDB_RESERVE) {
8067 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
8068 if (!(node->mn_flags & F_BIGDATA))
8069 newdata->mv_data = NODEDATA(node);
8072 mc->mc_pg[mc->mc_top] = rp;
8074 /* Make sure mc_ki is still valid.
8076 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8077 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8078 for (i=0; i<=ptop; i++) {
8079 mc->mc_pg[i] = mn.mc_pg[i];
8080 mc->mc_ki[i] = mn.mc_ki[i];
8087 /* Adjust other cursors pointing to mp */
8088 MDB_cursor *m2, *m3;
8089 MDB_dbi dbi = mc->mc_dbi;
8090 int fixup = NUMKEYS(mp);
8092 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8093 if (mc->mc_flags & C_SUB)
8094 m3 = &m2->mc_xcursor->mx_cursor;
8099 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8101 if (m3->mc_flags & C_SPLITTING)
8106 for (k=m3->mc_top; k>=0; k--) {
8107 m3->mc_ki[k+1] = m3->mc_ki[k];
8108 m3->mc_pg[k+1] = m3->mc_pg[k];
8110 if (m3->mc_ki[0] >= split_indx) {
8115 m3->mc_pg[0] = mc->mc_pg[0];
8119 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
8120 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
8121 m3->mc_ki[mc->mc_top]++;
8122 if (m3->mc_ki[mc->mc_top] >= fixup) {
8123 m3->mc_pg[mc->mc_top] = rp;
8124 m3->mc_ki[mc->mc_top] -= fixup;
8125 m3->mc_ki[ptop] = mn.mc_ki[ptop];
8127 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
8128 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
8133 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
8136 if (copy) /* tmp page */
8137 mdb_page_free(env, copy);
8139 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8144 mdb_put(MDB_txn *txn, MDB_dbi dbi,
8145 MDB_val *key, MDB_val *data, unsigned int flags)
8150 if (!key || !data || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
8153 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP)) != flags)
8156 mdb_cursor_init(&mc, txn, dbi, &mx);
8157 return mdb_cursor_put(&mc, key, data, flags);
8161 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
8163 if ((flag & CHANGEABLE) != flag)
8166 env->me_flags |= flag;
8168 env->me_flags &= ~flag;
8173 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
8178 *arg = env->me_flags;
8183 mdb_env_set_userctx(MDB_env *env, void *ctx)
8187 env->me_userctx = ctx;
8192 mdb_env_get_userctx(MDB_env *env)
8194 return env ? env->me_userctx : NULL;
8198 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
8203 env->me_assert_func = func;
8209 mdb_env_get_path(MDB_env *env, const char **arg)
8214 *arg = env->me_path;
8219 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
8228 /** Common code for #mdb_stat() and #mdb_env_stat().
8229 * @param[in] env the environment to operate in.
8230 * @param[in] db the #MDB_db record containing the stats to return.
8231 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
8232 * @return 0, this function always succeeds.
8235 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
8237 arg->ms_psize = env->me_psize;
8238 arg->ms_depth = db->md_depth;
8239 arg->ms_branch_pages = db->md_branch_pages;
8240 arg->ms_leaf_pages = db->md_leaf_pages;
8241 arg->ms_overflow_pages = db->md_overflow_pages;
8242 arg->ms_entries = db->md_entries;
8247 mdb_env_stat(MDB_env *env, MDB_stat *arg)
8251 if (env == NULL || arg == NULL)
8254 toggle = mdb_env_pick_meta(env);
8256 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
8260 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
8264 if (env == NULL || arg == NULL)
8267 toggle = mdb_env_pick_meta(env);
8268 arg->me_mapaddr = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : 0;
8269 arg->me_mapsize = env->me_mapsize;
8270 arg->me_maxreaders = env->me_maxreaders;
8272 /* me_numreaders may be zero if this process never used any readers. Use
8273 * the shared numreader count if it exists.
8275 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : env->me_numreaders;
8277 arg->me_last_pgno = env->me_metas[toggle]->mm_last_pg;
8278 arg->me_last_txnid = env->me_metas[toggle]->mm_txnid;
8282 /** Set the default comparison functions for a database.
8283 * Called immediately after a database is opened to set the defaults.
8284 * The user can then override them with #mdb_set_compare() or
8285 * #mdb_set_dupsort().
8286 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
8287 * @param[in] dbi A database handle returned by #mdb_dbi_open()
8290 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
8292 uint16_t f = txn->mt_dbs[dbi].md_flags;
8294 txn->mt_dbxs[dbi].md_cmp =
8295 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
8296 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
8298 txn->mt_dbxs[dbi].md_dcmp =
8299 !(f & MDB_DUPSORT) ? 0 :
8300 ((f & MDB_INTEGERDUP)
8301 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
8302 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
8305 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
8310 int rc, dbflag, exact;
8311 unsigned int unused = 0;
8314 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
8315 mdb_default_cmp(txn, FREE_DBI);
8318 if ((flags & VALID_FLAGS) != flags)
8320 if (txn->mt_flags & MDB_TXN_ERROR)
8326 if (flags & PERSISTENT_FLAGS) {
8327 uint16_t f2 = flags & PERSISTENT_FLAGS;
8328 /* make sure flag changes get committed */
8329 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
8330 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
8331 txn->mt_flags |= MDB_TXN_DIRTY;
8334 mdb_default_cmp(txn, MAIN_DBI);
8338 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
8339 mdb_default_cmp(txn, MAIN_DBI);
8342 /* Is the DB already open? */
8344 for (i=2; i<txn->mt_numdbs; i++) {
8345 if (!txn->mt_dbxs[i].md_name.mv_size) {
8346 /* Remember this free slot */
8347 if (!unused) unused = i;
8350 if (len == txn->mt_dbxs[i].md_name.mv_size &&
8351 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
8357 /* If no free slot and max hit, fail */
8358 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
8359 return MDB_DBS_FULL;
8361 /* Cannot mix named databases with some mainDB flags */
8362 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
8363 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
8365 /* Find the DB info */
8366 dbflag = DB_NEW|DB_VALID;
8369 key.mv_data = (void *)name;
8370 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
8371 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
8372 if (rc == MDB_SUCCESS) {
8373 /* make sure this is actually a DB */
8374 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
8375 if (!(node->mn_flags & F_SUBDATA))
8376 return MDB_INCOMPATIBLE;
8377 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
8378 /* Create if requested */
8380 data.mv_size = sizeof(MDB_db);
8381 data.mv_data = &dummy;
8382 memset(&dummy, 0, sizeof(dummy));
8383 dummy.md_root = P_INVALID;
8384 dummy.md_flags = flags & PERSISTENT_FLAGS;
8385 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
8389 /* OK, got info, add to table */
8390 if (rc == MDB_SUCCESS) {
8391 unsigned int slot = unused ? unused : txn->mt_numdbs;
8392 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
8393 txn->mt_dbxs[slot].md_name.mv_size = len;
8394 txn->mt_dbxs[slot].md_rel = NULL;
8395 txn->mt_dbflags[slot] = dbflag;
8396 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
8398 mdb_default_cmp(txn, slot);
8407 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
8409 if (!arg || !TXN_DBI_EXIST(txn, dbi))
8412 if (txn->mt_flags & MDB_TXN_ERROR)
8415 if (txn->mt_dbflags[dbi] & DB_STALE) {
8418 /* Stale, must read the DB's root. cursor_init does it for us. */
8419 mdb_cursor_init(&mc, txn, dbi, &mx);
8421 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
8424 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
8427 if (dbi <= MAIN_DBI || dbi >= env->me_maxdbs)
8429 ptr = env->me_dbxs[dbi].md_name.mv_data;
8430 env->me_dbxs[dbi].md_name.mv_data = NULL;
8431 env->me_dbxs[dbi].md_name.mv_size = 0;
8432 env->me_dbflags[dbi] = 0;
8436 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
8438 /* We could return the flags for the FREE_DBI too but what's the point? */
8439 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
8441 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
8445 /** Add all the DB's pages to the free list.
8446 * @param[in] mc Cursor on the DB to free.
8447 * @param[in] subs non-Zero to check for sub-DBs in this DB.
8448 * @return 0 on success, non-zero on failure.
8451 mdb_drop0(MDB_cursor *mc, int subs)
8455 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
8456 if (rc == MDB_SUCCESS) {
8457 MDB_txn *txn = mc->mc_txn;
8462 /* LEAF2 pages have no nodes, cannot have sub-DBs */
8463 if (IS_LEAF2(mc->mc_pg[mc->mc_top]))
8466 mdb_cursor_copy(mc, &mx);
8467 while (mc->mc_snum > 0) {
8468 MDB_page *mp = mc->mc_pg[mc->mc_top];
8469 unsigned n = NUMKEYS(mp);
8471 for (i=0; i<n; i++) {
8472 ni = NODEPTR(mp, i);
8473 if (ni->mn_flags & F_BIGDATA) {
8476 memcpy(&pg, NODEDATA(ni), sizeof(pg));
8477 rc = mdb_page_get(txn, pg, &omp, NULL);
8480 mdb_cassert(mc, IS_OVERFLOW(omp));
8481 rc = mdb_midl_append_range(&txn->mt_free_pgs,
8485 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
8486 mdb_xcursor_init1(mc, ni);
8487 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
8493 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
8495 for (i=0; i<n; i++) {
8497 ni = NODEPTR(mp, i);
8500 mdb_midl_xappend(txn->mt_free_pgs, pg);
8505 mc->mc_ki[mc->mc_top] = i;
8506 rc = mdb_cursor_sibling(mc, 1);
8508 if (rc != MDB_NOTFOUND)
8510 /* no more siblings, go back to beginning
8511 * of previous level.
8515 for (i=1; i<mc->mc_snum; i++) {
8517 mc->mc_pg[i] = mx.mc_pg[i];
8522 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
8525 txn->mt_flags |= MDB_TXN_ERROR;
8526 } else if (rc == MDB_NOTFOUND) {
8532 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
8534 MDB_cursor *mc, *m2;
8537 if ((unsigned)del > 1 || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
8540 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
8543 rc = mdb_cursor_open(txn, dbi, &mc);
8547 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
8548 /* Invalidate the dropped DB's cursors */
8549 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
8550 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
8554 /* Can't delete the main DB */
8555 if (del && dbi > MAIN_DBI) {
8556 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, 0);
8558 txn->mt_dbflags[dbi] = DB_STALE;
8559 mdb_dbi_close(txn->mt_env, dbi);
8561 txn->mt_flags |= MDB_TXN_ERROR;
8564 /* reset the DB record, mark it dirty */
8565 txn->mt_dbflags[dbi] |= DB_DIRTY;
8566 txn->mt_dbs[dbi].md_depth = 0;
8567 txn->mt_dbs[dbi].md_branch_pages = 0;
8568 txn->mt_dbs[dbi].md_leaf_pages = 0;
8569 txn->mt_dbs[dbi].md_overflow_pages = 0;
8570 txn->mt_dbs[dbi].md_entries = 0;
8571 txn->mt_dbs[dbi].md_root = P_INVALID;
8573 txn->mt_flags |= MDB_TXN_DIRTY;
8576 mdb_cursor_close(mc);
8580 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
8582 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
8585 txn->mt_dbxs[dbi].md_cmp = cmp;
8589 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
8591 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
8594 txn->mt_dbxs[dbi].md_dcmp = cmp;
8598 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
8600 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
8603 txn->mt_dbxs[dbi].md_rel = rel;
8607 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
8609 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
8612 txn->mt_dbxs[dbi].md_relctx = ctx;
8616 int mdb_env_get_maxkeysize(MDB_env *env)
8618 return ENV_MAXKEY(env);
8621 int mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
8623 unsigned int i, rdrs;
8626 int rc = 0, first = 1;
8630 if (!env->me_txns) {
8631 return func("(no reader locks)\n", ctx);
8633 rdrs = env->me_txns->mti_numreaders;
8634 mr = env->me_txns->mti_readers;
8635 for (i=0; i<rdrs; i++) {
8637 txnid_t txnid = mr[i].mr_txnid;
8638 sprintf(buf, txnid == (txnid_t)-1 ?
8639 "%10d %"Z"x -\n" : "%10d %"Z"x %"Z"u\n",
8640 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
8643 rc = func(" pid thread txnid\n", ctx);
8647 rc = func(buf, ctx);
8653 rc = func("(no active readers)\n", ctx);
8658 /** Insert pid into list if not already present.
8659 * return -1 if already present.
8661 static int mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
8663 /* binary search of pid in list */
8665 unsigned cursor = 1;
8667 unsigned n = ids[0];
8670 unsigned pivot = n >> 1;
8671 cursor = base + pivot + 1;
8672 val = pid - ids[cursor];
8677 } else if ( val > 0 ) {
8682 /* found, so it's a duplicate */
8691 for (n = ids[0]; n > cursor; n--)
8697 int mdb_reader_check(MDB_env *env, int *dead)
8699 unsigned int i, j, rdrs;
8701 MDB_PID_T *pids, pid;
8710 rdrs = env->me_txns->mti_numreaders;
8711 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
8715 mr = env->me_txns->mti_readers;
8716 for (i=0; i<rdrs; i++) {
8717 if (mr[i].mr_pid && mr[i].mr_pid != env->me_pid) {
8719 if (mdb_pid_insert(pids, pid) == 0) {
8720 if (!mdb_reader_pid(env, Pidcheck, pid)) {
8722 /* Recheck, a new process may have reused pid */
8723 if (!mdb_reader_pid(env, Pidcheck, pid)) {
8724 for (j=i; j<rdrs; j++)
8725 if (mr[j].mr_pid == pid) {
8726 DPRINTF(("clear stale reader pid %u txn %"Z"d",
8727 (unsigned) pid, mr[j].mr_txnid));
8732 UNLOCK_MUTEX_R(env);