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 /** Link in #MDB_txn.%mt_loose_pages list */
705 #define NEXT_LOOSE_PAGE(p) (*(MDB_page **)METADATA(p))
707 /** Header for a single key/data pair within a page.
708 * Used in pages of type #P_BRANCH and #P_LEAF without #P_LEAF2.
709 * We guarantee 2-byte alignment for 'MDB_node's.
711 typedef struct MDB_node {
712 /** lo and hi are used for data size on leaf nodes and for
713 * child pgno on branch nodes. On 64 bit platforms, flags
714 * is also used for pgno. (Branch nodes have no flags).
715 * They are in host byte order in case that lets some
716 * accesses be optimized into a 32-bit word access.
718 #if BYTE_ORDER == LITTLE_ENDIAN
719 unsigned short mn_lo, mn_hi; /**< part of data size or pgno */
721 unsigned short mn_hi, mn_lo;
723 /** @defgroup mdb_node Node Flags
725 * Flags for node headers.
728 #define F_BIGDATA 0x01 /**< data put on overflow page */
729 #define F_SUBDATA 0x02 /**< data is a sub-database */
730 #define F_DUPDATA 0x04 /**< data has duplicates */
732 /** valid flags for #mdb_node_add() */
733 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
736 unsigned short mn_flags; /**< @ref mdb_node */
737 unsigned short mn_ksize; /**< key size */
738 char mn_data[1]; /**< key and data are appended here */
741 /** Size of the node header, excluding dynamic data at the end */
742 #define NODESIZE offsetof(MDB_node, mn_data)
744 /** Bit position of top word in page number, for shifting mn_flags */
745 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
747 /** Size of a node in a branch page with a given key.
748 * This is just the node header plus the key, there is no data.
750 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
752 /** Size of a node in a leaf page with a given key and data.
753 * This is node header plus key plus data size.
755 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
757 /** Address of node \b i in page \b p */
758 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
760 /** Address of the key for the node */
761 #define NODEKEY(node) (void *)((node)->mn_data)
763 /** Address of the data for a node */
764 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
766 /** Get the page number pointed to by a branch node */
767 #define NODEPGNO(node) \
768 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
769 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
770 /** Set the page number in a branch node */
771 #define SETPGNO(node,pgno) do { \
772 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
773 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
775 /** Get the size of the data in a leaf node */
776 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
777 /** Set the size of the data for a leaf node */
778 #define SETDSZ(node,size) do { \
779 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
780 /** The size of a key in a node */
781 #define NODEKSZ(node) ((node)->mn_ksize)
783 /** Copy a page number from src to dst */
785 #define COPY_PGNO(dst,src) dst = src
787 #if SIZE_MAX > 4294967295UL
788 #define COPY_PGNO(dst,src) do { \
789 unsigned short *s, *d; \
790 s = (unsigned short *)&(src); \
791 d = (unsigned short *)&(dst); \
798 #define COPY_PGNO(dst,src) do { \
799 unsigned short *s, *d; \
800 s = (unsigned short *)&(src); \
801 d = (unsigned short *)&(dst); \
807 /** The address of a key in a LEAF2 page.
808 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
809 * There are no node headers, keys are stored contiguously.
811 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
813 /** Set the \b node's key into \b keyptr, if requested. */
814 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
815 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
817 /** Set the \b node's key into \b key. */
818 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
820 /** Information about a single database in the environment. */
821 typedef struct MDB_db {
822 uint32_t md_pad; /**< also ksize for LEAF2 pages */
823 uint16_t md_flags; /**< @ref mdb_dbi_open */
824 uint16_t md_depth; /**< depth of this tree */
825 pgno_t md_branch_pages; /**< number of internal pages */
826 pgno_t md_leaf_pages; /**< number of leaf pages */
827 pgno_t md_overflow_pages; /**< number of overflow pages */
828 size_t md_entries; /**< number of data items */
829 pgno_t md_root; /**< the root page of this tree */
832 /** mdb_dbi_open flags */
833 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
834 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
835 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
836 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
838 /** Handle for the DB used to track free pages. */
840 /** Handle for the default DB. */
843 /** Meta page content.
844 * A meta page is the start point for accessing a database snapshot.
845 * Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
847 typedef struct MDB_meta {
848 /** Stamp identifying this as an LMDB file. It must be set
851 /** Version number of this lock file. Must be set to #MDB_DATA_VERSION. */
853 void *mm_address; /**< address for fixed mapping */
854 size_t mm_mapsize; /**< size of mmap region */
855 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
856 /** The size of pages used in this DB */
857 #define mm_psize mm_dbs[0].md_pad
858 /** Any persistent environment flags. @ref mdb_env */
859 #define mm_flags mm_dbs[0].md_flags
860 pgno_t mm_last_pg; /**< last used page in file */
861 txnid_t mm_txnid; /**< txnid that committed this page */
864 /** Buffer for a stack-allocated meta page.
865 * The members define size and alignment, and silence type
866 * aliasing warnings. They are not used directly; that could
867 * mean incorrectly using several union members in parallel.
869 typedef union MDB_metabuf {
872 char mm_pad[PAGEHDRSZ];
877 /** Auxiliary DB info.
878 * The information here is mostly static/read-only. There is
879 * only a single copy of this record in the environment.
881 typedef struct MDB_dbx {
882 MDB_val md_name; /**< name of the database */
883 MDB_cmp_func *md_cmp; /**< function for comparing keys */
884 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
885 MDB_rel_func *md_rel; /**< user relocate function */
886 void *md_relctx; /**< user-provided context for md_rel */
889 /** A database transaction.
890 * Every operation requires a transaction handle.
893 MDB_txn *mt_parent; /**< parent of a nested txn */
894 MDB_txn *mt_child; /**< nested txn under this txn */
895 pgno_t mt_next_pgno; /**< next unallocated page */
896 /** The ID of this transaction. IDs are integers incrementing from 1.
897 * Only committed write transactions increment the ID. If a transaction
898 * aborts, the ID may be re-used by the next writer.
901 MDB_env *mt_env; /**< the DB environment */
902 /** The list of pages that became unused during this transaction.
905 /** The list of loose pages that became unused and may be reused
906 * in this transaction, linked through #NEXT_LOOSE_PAGE(page).
908 MDB_page *mt_loose_pgs;
909 /** The sorted list of dirty pages we temporarily wrote to disk
910 * because the dirty list was full. page numbers in here are
911 * shifted left by 1, deleted slots have the LSB set.
913 MDB_IDL mt_spill_pgs;
915 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
917 /** For read txns: This thread/txn's reader table slot, or NULL. */
920 /** Array of records for each DB known in the environment. */
922 /** Array of MDB_db records for each known DB */
924 /** @defgroup mt_dbflag Transaction DB Flags
928 #define DB_DIRTY 0x01 /**< DB was modified or is DUPSORT data */
929 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
930 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
931 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
933 /** In write txns, array of cursors for each DB */
934 MDB_cursor **mt_cursors;
935 /** Array of flags for each DB */
936 unsigned char *mt_dbflags;
937 /** Number of DB records in use. This number only ever increments;
938 * we don't decrement it when individual DB handles are closed.
942 /** @defgroup mdb_txn Transaction Flags
946 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
947 #define MDB_TXN_ERROR 0x02 /**< txn is unusable after an error */
948 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
949 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
951 unsigned int mt_flags; /**< @ref mdb_txn */
952 /** #dirty_list room: Array size - \#dirty pages visible to this txn.
953 * Includes ancestor txns' dirty pages not hidden by other txns'
954 * dirty/spilled pages. Thus commit(nested txn) has room to merge
955 * dirty_list into mt_parent after freeing hidden mt_parent pages.
957 unsigned int mt_dirty_room;
960 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
961 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
962 * raise this on a 64 bit machine.
964 #define CURSOR_STACK 32
968 /** Cursors are used for all DB operations.
969 * A cursor holds a path of (page pointer, key index) from the DB
970 * root to a position in the DB, plus other state. #MDB_DUPSORT
971 * cursors include an xcursor to the current data item. Write txns
972 * track their cursors and keep them up to date when data moves.
973 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
974 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
977 /** Next cursor on this DB in this txn */
979 /** Backup of the original cursor if this cursor is a shadow */
980 MDB_cursor *mc_backup;
981 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
982 struct MDB_xcursor *mc_xcursor;
983 /** The transaction that owns this cursor */
985 /** The database handle this cursor operates on */
987 /** The database record for this cursor */
989 /** The database auxiliary record for this cursor */
991 /** The @ref mt_dbflag for this database */
992 unsigned char *mc_dbflag;
993 unsigned short mc_snum; /**< number of pushed pages */
994 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
995 /** @defgroup mdb_cursor Cursor Flags
997 * Cursor state flags.
1000 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
1001 #define C_EOF 0x02 /**< No more data */
1002 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
1003 #define C_DEL 0x08 /**< last op was a cursor_del */
1004 #define C_SPLITTING 0x20 /**< Cursor is in page_split */
1005 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
1007 unsigned int mc_flags; /**< @ref mdb_cursor */
1008 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
1009 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
1012 /** Context for sorted-dup records.
1013 * We could have gone to a fully recursive design, with arbitrarily
1014 * deep nesting of sub-databases. But for now we only handle these
1015 * levels - main DB, optional sub-DB, sorted-duplicate DB.
1017 typedef struct MDB_xcursor {
1018 /** A sub-cursor for traversing the Dup DB */
1019 MDB_cursor mx_cursor;
1020 /** The database record for this Dup DB */
1022 /** The auxiliary DB record for this Dup DB */
1024 /** The @ref mt_dbflag for this Dup DB */
1025 unsigned char mx_dbflag;
1028 /** State of FreeDB old pages, stored in the MDB_env */
1029 typedef struct MDB_pgstate {
1030 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1031 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1034 /** The database environment. */
1036 HANDLE me_fd; /**< The main data file */
1037 HANDLE me_lfd; /**< The lock file */
1038 HANDLE me_mfd; /**< just for writing the meta pages */
1039 /** Failed to update the meta page. Probably an I/O error. */
1040 #define MDB_FATAL_ERROR 0x80000000U
1041 /** Some fields are initialized. */
1042 #define MDB_ENV_ACTIVE 0x20000000U
1043 /** me_txkey is set */
1044 #define MDB_ENV_TXKEY 0x10000000U
1045 uint32_t me_flags; /**< @ref mdb_env */
1046 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1047 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1048 unsigned int me_maxreaders; /**< size of the reader table */
1049 unsigned int me_numreaders; /**< max numreaders set by this env */
1050 MDB_dbi me_numdbs; /**< number of DBs opened */
1051 MDB_dbi me_maxdbs; /**< size of the DB table */
1052 MDB_PID_T me_pid; /**< process ID of this env */
1053 char *me_path; /**< path to the DB files */
1054 char *me_map; /**< the memory map of the data file */
1055 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1056 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
1057 void *me_pbuf; /**< scratch area for DUPSORT put() */
1058 MDB_txn *me_txn; /**< current write transaction */
1059 size_t me_mapsize; /**< size of the data memory map */
1060 off_t me_size; /**< current file size */
1061 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1062 MDB_dbx *me_dbxs; /**< array of static DB info */
1063 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1064 pthread_key_t me_txkey; /**< thread-key for readers */
1065 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1066 # define me_pglast me_pgstate.mf_pglast
1067 # define me_pghead me_pgstate.mf_pghead
1068 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1069 /** IDL of pages that became unused in a write txn */
1070 MDB_IDL me_free_pgs;
1071 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1072 MDB_ID2L me_dirty_list;
1073 /** Max number of freelist items that can fit in a single overflow page */
1075 /** Max size of a node on a page */
1076 unsigned int me_nodemax;
1077 #if !(MDB_MAXKEYSIZE)
1078 unsigned int me_maxkey; /**< max size of a key */
1080 int me_live_reader; /**< have liveness lock in reader table */
1082 int me_pidquery; /**< Used in OpenProcess */
1083 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
1085 #elif defined(MDB_USE_POSIX_SEM)
1086 sem_t *me_rmutex; /* Shared mutexes are not supported */
1089 void *me_userctx; /**< User-settable context */
1090 MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
1093 /** Nested transaction */
1094 typedef struct MDB_ntxn {
1095 MDB_txn mnt_txn; /**< the transaction */
1096 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1099 /** max number of pages to commit in one writev() call */
1100 #define MDB_COMMIT_PAGES 64
1101 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1102 #undef MDB_COMMIT_PAGES
1103 #define MDB_COMMIT_PAGES IOV_MAX
1106 /** max bytes to write in one call */
1107 #define MAX_WRITE (0x80000000U >> (sizeof(ssize_t) == 4))
1109 /** Check \b txn and \b dbi arguments to a function */
1110 #define TXN_DBI_EXIST(txn, dbi) \
1111 ((txn) && (dbi) < (txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & DB_VALID))
1113 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1114 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1115 static int mdb_page_touch(MDB_cursor *mc);
1117 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp, int *lvl);
1118 static int mdb_page_search_root(MDB_cursor *mc,
1119 MDB_val *key, int modify);
1120 #define MDB_PS_MODIFY 1
1121 #define MDB_PS_ROOTONLY 2
1122 #define MDB_PS_FIRST 4
1123 #define MDB_PS_LAST 8
1124 static int mdb_page_search(MDB_cursor *mc,
1125 MDB_val *key, int flags);
1126 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1128 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1129 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1130 pgno_t newpgno, unsigned int nflags);
1132 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1133 static int mdb_env_pick_meta(const MDB_env *env);
1134 static int mdb_env_write_meta(MDB_txn *txn);
1135 #if !(defined(_WIN32) || defined(MDB_USE_POSIX_SEM)) /* Drop unused excl arg */
1136 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1138 static void mdb_env_close0(MDB_env *env, int excl);
1140 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1141 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1142 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1143 static void mdb_node_del(MDB_cursor *mc, int ksize);
1144 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1145 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
1146 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1147 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1148 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1150 static int mdb_rebalance(MDB_cursor *mc);
1151 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1153 static void mdb_cursor_pop(MDB_cursor *mc);
1154 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1156 static int mdb_cursor_del0(MDB_cursor *mc);
1157 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
1158 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1159 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1160 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1161 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1163 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1164 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1166 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1167 static void mdb_xcursor_init0(MDB_cursor *mc);
1168 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1170 static int mdb_drop0(MDB_cursor *mc, int subs);
1171 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1174 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1178 static SECURITY_DESCRIPTOR mdb_null_sd;
1179 static SECURITY_ATTRIBUTES mdb_all_sa;
1180 static int mdb_sec_inited;
1183 /** Return the library version info. */
1185 mdb_version(int *major, int *minor, int *patch)
1187 if (major) *major = MDB_VERSION_MAJOR;
1188 if (minor) *minor = MDB_VERSION_MINOR;
1189 if (patch) *patch = MDB_VERSION_PATCH;
1190 return MDB_VERSION_STRING;
1193 /** Table of descriptions for LMDB @ref errors */
1194 static char *const mdb_errstr[] = {
1195 "MDB_KEYEXIST: Key/data pair already exists",
1196 "MDB_NOTFOUND: No matching key/data pair found",
1197 "MDB_PAGE_NOTFOUND: Requested page not found",
1198 "MDB_CORRUPTED: Located page was wrong type",
1199 "MDB_PANIC: Update of meta page failed",
1200 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1201 "MDB_INVALID: File is not an LMDB file",
1202 "MDB_MAP_FULL: Environment mapsize limit reached",
1203 "MDB_DBS_FULL: Environment maxdbs limit reached",
1204 "MDB_READERS_FULL: Environment maxreaders limit reached",
1205 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1206 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1207 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1208 "MDB_PAGE_FULL: Internal error - page has no more space",
1209 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1210 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1211 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1212 "MDB_BAD_TXN: Transaction cannot recover - it must be aborted",
1213 "MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
1217 mdb_strerror(int err)
1221 return ("Successful return: 0");
1223 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1224 i = err - MDB_KEYEXIST;
1225 return mdb_errstr[i];
1228 return strerror(err);
1231 /** assert(3) variant in cursor context */
1232 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1233 /** assert(3) variant in transaction context */
1234 #define mdb_tassert(mc, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1235 /** assert(3) variant in environment context */
1236 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1239 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1240 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1243 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1244 const char *func, const char *file, int line)
1247 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1248 file, line, expr_txt, func);
1249 if (env->me_assert_func)
1250 env->me_assert_func(env, buf);
1251 fprintf(stderr, "%s\n", buf);
1255 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1259 /** Return the page number of \b mp which may be sub-page, for debug output */
1261 mdb_dbg_pgno(MDB_page *mp)
1264 COPY_PGNO(ret, mp->mp_pgno);
1268 /** Display a key in hexadecimal and return the address of the result.
1269 * @param[in] key the key to display
1270 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1271 * @return The key in hexadecimal form.
1274 mdb_dkey(MDB_val *key, char *buf)
1277 unsigned char *c = key->mv_data;
1283 if (key->mv_size > DKBUF_MAXKEYSIZE)
1284 return "MDB_MAXKEYSIZE";
1285 /* may want to make this a dynamic check: if the key is mostly
1286 * printable characters, print it as-is instead of converting to hex.
1290 for (i=0; i<key->mv_size; i++)
1291 ptr += sprintf(ptr, "%02x", *c++);
1293 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1299 mdb_leafnode_type(MDB_node *n)
1301 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1302 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1303 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1306 /** Display all the keys in the page. */
1308 mdb_page_list(MDB_page *mp)
1310 pgno_t pgno = mdb_dbg_pgno(mp);
1311 const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
1313 unsigned int i, nkeys, nsize, total = 0;
1317 switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1318 case P_BRANCH: type = "Branch page"; break;
1319 case P_LEAF: type = "Leaf page"; break;
1320 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1321 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1322 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1324 fprintf(stderr, "Overflow page %"Z"u pages %u%s\n",
1325 pgno, mp->mp_pages, state);
1328 fprintf(stderr, "Meta-page %"Z"u txnid %"Z"u\n",
1329 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1332 fprintf(stderr, "Bad page %"Z"u flags 0x%u\n", pgno, mp->mp_flags);
1336 nkeys = NUMKEYS(mp);
1337 fprintf(stderr, "%s %"Z"u numkeys %d%s\n", type, pgno, nkeys, state);
1339 for (i=0; i<nkeys; i++) {
1340 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1341 key.mv_size = nsize = mp->mp_pad;
1342 key.mv_data = LEAF2KEY(mp, i, nsize);
1344 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1347 node = NODEPTR(mp, i);
1348 key.mv_size = node->mn_ksize;
1349 key.mv_data = node->mn_data;
1350 nsize = NODESIZE + key.mv_size;
1351 if (IS_BRANCH(mp)) {
1352 fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
1356 if (F_ISSET(node->mn_flags, F_BIGDATA))
1357 nsize += sizeof(pgno_t);
1359 nsize += NODEDSZ(node);
1361 nsize += sizeof(indx_t);
1362 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1363 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1365 total = EVEN(total);
1367 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1368 IS_LEAF2(mp) ? PAGEHDRSZ : mp->mp_lower, total, SIZELEFT(mp));
1372 mdb_cursor_chk(MDB_cursor *mc)
1378 if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1379 for (i=0; i<mc->mc_top; i++) {
1381 node = NODEPTR(mp, mc->mc_ki[i]);
1382 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1385 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1391 /** Count all the pages in each DB and in the freelist
1392 * and make sure it matches the actual number of pages
1394 * All named DBs must be open for a correct count.
1396 static void mdb_audit(MDB_txn *txn)
1400 MDB_ID freecount, count;
1405 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1406 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1407 freecount += *(MDB_ID *)data.mv_data;
1408 mdb_tassert(txn, rc == MDB_NOTFOUND);
1411 for (i = 0; i<txn->mt_numdbs; i++) {
1413 if (!(txn->mt_dbflags[i] & DB_VALID))
1415 mdb_cursor_init(&mc, txn, i, &mx);
1416 if (txn->mt_dbs[i].md_root == P_INVALID)
1418 count += txn->mt_dbs[i].md_branch_pages +
1419 txn->mt_dbs[i].md_leaf_pages +
1420 txn->mt_dbs[i].md_overflow_pages;
1421 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1422 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1423 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
1426 mp = mc.mc_pg[mc.mc_top];
1427 for (j=0; j<NUMKEYS(mp); j++) {
1428 MDB_node *leaf = NODEPTR(mp, j);
1429 if (leaf->mn_flags & F_SUBDATA) {
1431 memcpy(&db, NODEDATA(leaf), sizeof(db));
1432 count += db.md_branch_pages + db.md_leaf_pages +
1433 db.md_overflow_pages;
1437 mdb_tassert(txn, rc == MDB_NOTFOUND);
1440 if (freecount + count + 2 /* metapages */ != txn->mt_next_pgno) {
1441 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1442 txn->mt_txnid, freecount, count+2, freecount+count+2, txn->mt_next_pgno);
1448 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1450 return txn->mt_dbxs[dbi].md_cmp(a, b);
1454 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1456 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1459 /** Allocate memory for a page.
1460 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1463 mdb_page_malloc(MDB_txn *txn, unsigned num)
1465 MDB_env *env = txn->mt_env;
1466 MDB_page *ret = env->me_dpages;
1467 size_t psize = env->me_psize, sz = psize, off;
1468 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1469 * For a single page alloc, we init everything after the page header.
1470 * For multi-page, we init the final page; if the caller needed that
1471 * many pages they will be filling in at least up to the last page.
1475 VGMEMP_ALLOC(env, ret, sz);
1476 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1477 env->me_dpages = ret->mp_next;
1480 psize -= off = PAGEHDRSZ;
1485 if ((ret = malloc(sz)) != NULL) {
1486 VGMEMP_ALLOC(env, ret, sz);
1487 if (!(env->me_flags & MDB_NOMEMINIT)) {
1488 memset((char *)ret + off, 0, psize);
1492 txn->mt_flags |= MDB_TXN_ERROR;
1496 /** Free a single page.
1497 * Saves single pages to a list, for future reuse.
1498 * (This is not used for multi-page overflow pages.)
1501 mdb_page_free(MDB_env *env, MDB_page *mp)
1503 mp->mp_next = env->me_dpages;
1504 VGMEMP_FREE(env, mp);
1505 env->me_dpages = mp;
1508 /** Free a dirty page */
1510 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1512 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1513 mdb_page_free(env, dp);
1515 /* large pages just get freed directly */
1516 VGMEMP_FREE(env, dp);
1521 /** Return all dirty pages to dpage list */
1523 mdb_dlist_free(MDB_txn *txn)
1525 MDB_env *env = txn->mt_env;
1526 MDB_ID2L dl = txn->mt_u.dirty_list;
1527 unsigned i, n = dl[0].mid;
1529 for (i = 1; i <= n; i++) {
1530 mdb_dpage_free(env, dl[i].mptr);
1535 /** Loosen or free a single page.
1536 * Saves single pages to a list for future reuse
1537 * in this same txn. It has been pulled from the freeDB
1538 * and already resides on the dirty list, but has been
1539 * deleted. Use these pages first before pulling again
1542 * If the page wasn't dirtied in this txn, just add it
1543 * to this txn's free list.
1546 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
1549 pgno_t pgno = mp->mp_pgno;
1551 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
1552 if (mc->mc_txn->mt_parent) {
1553 MDB_ID2 *dl = mc->mc_txn->mt_u.dirty_list;
1554 /* If txn has a parent, make sure the page is in our
1558 unsigned x = mdb_mid2l_search(dl, pgno);
1559 if (x <= dl[0].mid && dl[x].mid == pgno) {
1560 if (mp != dl[x].mptr) { /* bad cursor? */
1561 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1562 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
1563 return MDB_CORRUPTED;
1570 /* no parent txn, so it's just ours */
1575 NEXT_LOOSE_PAGE(mp) = mc->mc_txn->mt_loose_pgs;
1576 mc->mc_txn->mt_loose_pgs = mp;
1577 mp->mp_flags |= P_LOOSE;
1579 int rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, pgno);
1587 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
1588 * @param[in] mc A cursor handle for the current operation.
1589 * @param[in] pflags Flags of the pages to update:
1590 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1591 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
1592 * @return 0 on success, non-zero on failure.
1595 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
1597 enum { Mask = P_SUBP|P_DIRTY|P_KEEP };
1598 MDB_txn *txn = mc->mc_txn;
1604 int rc = MDB_SUCCESS, level;
1606 /* Mark pages seen by cursors */
1607 if (mc->mc_flags & C_UNTRACK)
1608 mc = NULL; /* will find mc in mt_cursors */
1609 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1610 for (; mc; mc=mc->mc_next) {
1611 if (!(mc->mc_flags & C_INITIALIZED))
1613 for (m3 = mc;; m3 = &mx->mx_cursor) {
1615 for (j=0; j<m3->mc_snum; j++) {
1617 if ((mp->mp_flags & Mask) == pflags)
1618 mp->mp_flags ^= P_KEEP;
1620 mx = m3->mc_xcursor;
1621 /* Proceed to mx if it is at a sub-database */
1622 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
1624 if (! (mp && (mp->mp_flags & P_LEAF)))
1626 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
1627 if (!(leaf->mn_flags & F_SUBDATA))
1635 /* Loose pages shouldn't be spilled */
1636 for (dp = txn->mt_loose_pgs; dp; dp = NEXT_LOOSE_PAGE(dp)) {
1637 if ((dp->mp_flags & Mask) == pflags)
1638 dp->mp_flags ^= P_KEEP;
1642 /* Mark dirty root pages */
1643 for (i=0; i<txn->mt_numdbs; i++) {
1644 if (txn->mt_dbflags[i] & DB_DIRTY) {
1645 pgno_t pgno = txn->mt_dbs[i].md_root;
1646 if (pgno == P_INVALID)
1648 if ((rc = mdb_page_get(txn, pgno, &dp, &level)) != MDB_SUCCESS)
1650 if ((dp->mp_flags & Mask) == pflags && level <= 1)
1651 dp->mp_flags ^= P_KEEP;
1659 static int mdb_page_flush(MDB_txn *txn, int keep);
1661 /** Spill pages from the dirty list back to disk.
1662 * This is intended to prevent running into #MDB_TXN_FULL situations,
1663 * but note that they may still occur in a few cases:
1664 * 1) our estimate of the txn size could be too small. Currently this
1665 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
1666 * 2) child txns may run out of space if their parents dirtied a
1667 * lot of pages and never spilled them. TODO: we probably should do
1668 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1669 * the parent's dirty_room is below a given threshold.
1671 * Otherwise, if not using nested txns, it is expected that apps will
1672 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1673 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1674 * If the txn never references them again, they can be left alone.
1675 * If the txn only reads them, they can be used without any fuss.
1676 * If the txn writes them again, they can be dirtied immediately without
1677 * going thru all of the work of #mdb_page_touch(). Such references are
1678 * handled by #mdb_page_unspill().
1680 * Also note, we never spill DB root pages, nor pages of active cursors,
1681 * because we'll need these back again soon anyway. And in nested txns,
1682 * we can't spill a page in a child txn if it was already spilled in a
1683 * parent txn. That would alter the parent txns' data even though
1684 * the child hasn't committed yet, and we'd have no way to undo it if
1685 * the child aborted.
1687 * @param[in] m0 cursor A cursor handle identifying the transaction and
1688 * database for which we are checking space.
1689 * @param[in] key For a put operation, the key being stored.
1690 * @param[in] data For a put operation, the data being stored.
1691 * @return 0 on success, non-zero on failure.
1694 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1696 MDB_txn *txn = m0->mc_txn;
1698 MDB_ID2L dl = txn->mt_u.dirty_list;
1699 unsigned int i, j, need;
1702 if (m0->mc_flags & C_SUB)
1705 /* Estimate how much space this op will take */
1706 i = m0->mc_db->md_depth;
1707 /* Named DBs also dirty the main DB */
1708 if (m0->mc_dbi > MAIN_DBI)
1709 i += txn->mt_dbs[MAIN_DBI].md_depth;
1710 /* For puts, roughly factor in the key+data size */
1712 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
1713 i += i; /* double it for good measure */
1716 if (txn->mt_dirty_room > i)
1719 if (!txn->mt_spill_pgs) {
1720 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
1721 if (!txn->mt_spill_pgs)
1724 /* purge deleted slots */
1725 MDB_IDL sl = txn->mt_spill_pgs;
1726 unsigned int num = sl[0];
1728 for (i=1; i<=num; i++) {
1735 /* Preserve pages which may soon be dirtied again */
1736 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
1739 /* Less aggressive spill - we originally spilled the entire dirty list,
1740 * with a few exceptions for cursor pages and DB root pages. But this
1741 * turns out to be a lot of wasted effort because in a large txn many
1742 * of those pages will need to be used again. So now we spill only 1/8th
1743 * of the dirty pages. Testing revealed this to be a good tradeoff,
1744 * better than 1/2, 1/4, or 1/10.
1746 if (need < MDB_IDL_UM_MAX / 8)
1747 need = MDB_IDL_UM_MAX / 8;
1749 /* Save the page IDs of all the pages we're flushing */
1750 /* flush from the tail forward, this saves a lot of shifting later on. */
1751 for (i=dl[0].mid; i && need; i--) {
1752 MDB_ID pn = dl[i].mid << 1;
1754 if (dp->mp_flags & P_KEEP)
1756 /* Can't spill twice, make sure it's not already in a parent's
1759 if (txn->mt_parent) {
1761 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1762 if (tx2->mt_spill_pgs) {
1763 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
1764 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
1765 dp->mp_flags |= P_KEEP;
1773 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
1777 mdb_midl_sort(txn->mt_spill_pgs);
1779 /* Flush the spilled part of dirty list */
1780 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
1783 /* Reset any dirty pages we kept that page_flush didn't see */
1784 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
1787 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
1791 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
1793 mdb_find_oldest(MDB_txn *txn)
1796 txnid_t mr, oldest = txn->mt_txnid - 1;
1797 if (txn->mt_env->me_txns) {
1798 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
1799 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
1810 /** Add a page to the txn's dirty list */
1812 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
1815 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
1817 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1818 insert = mdb_mid2l_append;
1820 insert = mdb_mid2l_insert;
1822 mid.mid = mp->mp_pgno;
1824 rc = insert(txn->mt_u.dirty_list, &mid);
1825 mdb_tassert(txn, rc == 0);
1826 txn->mt_dirty_room--;
1829 /** Allocate page numbers and memory for writing. Maintain me_pglast,
1830 * me_pghead and mt_next_pgno.
1832 * If there are free pages available from older transactions, they
1833 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
1834 * Do not modify the freedB, just merge freeDB records into me_pghead[]
1835 * and move me_pglast to say which records were consumed. Only this
1836 * function can create me_pghead and move me_pglast/mt_next_pgno.
1837 * @param[in] mc cursor A cursor handle identifying the transaction and
1838 * database for which we are allocating.
1839 * @param[in] num the number of pages to allocate.
1840 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
1841 * will always be satisfied by a single contiguous chunk of memory.
1842 * @return 0 on success, non-zero on failure.
1845 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
1847 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
1848 /* Get at most <Max_retries> more freeDB records once me_pghead
1849 * has enough pages. If not enough, use new pages from the map.
1850 * If <Paranoid> and mc is updating the freeDB, only get new
1851 * records if me_pghead is empty. Then the freelist cannot play
1852 * catch-up with itself by growing while trying to save it.
1854 enum { Paranoid = 1, Max_retries = 500 };
1856 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
1858 int rc, retry = num * 20;
1859 MDB_txn *txn = mc->mc_txn;
1860 MDB_env *env = txn->mt_env;
1861 pgno_t pgno, *mop = env->me_pghead;
1862 unsigned i, j, k, mop_len = mop ? mop[0] : 0, n2 = num-1;
1864 txnid_t oldest = 0, last;
1868 /* If there are any loose pages, just use them */
1869 if (num == 1 && txn->mt_loose_pgs) {
1870 np = txn->mt_loose_pgs;
1871 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
1878 /* If our dirty list is already full, we can't do anything */
1879 if (txn->mt_dirty_room == 0) {
1884 for (op = MDB_FIRST;; op = MDB_NEXT) {
1887 pgno_t *idl, old_id, new_id;
1889 /* Seek a big enough contiguous page range. Prefer
1890 * pages at the tail, just truncating the list.
1896 if (mop[i-n2] == pgno+n2)
1903 if (op == MDB_FIRST) { /* 1st iteration */
1904 /* Prepare to fetch more and coalesce */
1905 oldest = mdb_find_oldest(txn);
1906 last = env->me_pglast;
1907 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1910 key.mv_data = &last; /* will look up last+1 */
1911 key.mv_size = sizeof(last);
1913 if (Paranoid && mc->mc_dbi == FREE_DBI)
1916 if (Paranoid && retry < 0 && mop_len)
1920 /* Do not fetch more if the record will be too recent */
1923 rc = mdb_cursor_get(&m2, &key, NULL, op);
1925 if (rc == MDB_NOTFOUND)
1929 last = *(txnid_t*)key.mv_data;
1932 np = m2.mc_pg[m2.mc_top];
1933 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
1934 if ((rc = mdb_node_read(txn, leaf, &data)) != MDB_SUCCESS)
1937 idl = (MDB_ID *) data.mv_data;
1940 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
1945 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
1947 mop = env->me_pghead;
1949 env->me_pglast = last;
1951 DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
1952 last, txn->mt_dbs[FREE_DBI].md_root, i));
1954 DPRINTF(("IDL %"Z"u", idl[k]));
1956 /* Merge in descending sorted order */
1959 mop[0] = (pgno_t)-1;
1963 for (; old_id < new_id; old_id = mop[--j])
1970 /* Use new pages from the map when nothing suitable in the freeDB */
1972 pgno = txn->mt_next_pgno;
1973 if (pgno + num >= env->me_maxpg) {
1974 DPUTS("DB size maxed out");
1980 if (env->me_flags & MDB_WRITEMAP) {
1981 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
1983 if (!(np = mdb_page_malloc(txn, num))) {
1989 mop[0] = mop_len -= num;
1990 /* Move any stragglers down */
1991 for (j = i-num; j < mop_len; )
1992 mop[++j] = mop[++i];
1994 txn->mt_next_pgno = pgno + num;
1997 mdb_page_dirty(txn, np);
2003 txn->mt_flags |= MDB_TXN_ERROR;
2007 /** Copy the used portions of a non-overflow page.
2008 * @param[in] dst page to copy into
2009 * @param[in] src page to copy from
2010 * @param[in] psize size of a page
2013 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2015 enum { Align = sizeof(pgno_t) };
2016 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2018 /* If page isn't full, just copy the used portion. Adjust
2019 * alignment so memcpy may copy words instead of bytes.
2021 if ((unused &= -Align) && !IS_LEAF2(src)) {
2023 memcpy(dst, src, (lower + (Align-1)) & -Align);
2024 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2027 memcpy(dst, src, psize - unused);
2031 /** Pull a page off the txn's spill list, if present.
2032 * If a page being referenced was spilled to disk in this txn, bring
2033 * it back and make it dirty/writable again.
2034 * @param[in] txn the transaction handle.
2035 * @param[in] mp the page being referenced. It must not be dirty.
2036 * @param[out] ret the writable page, if any. ret is unchanged if
2037 * mp wasn't spilled.
2040 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2042 MDB_env *env = txn->mt_env;
2045 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2047 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2048 if (!tx2->mt_spill_pgs)
2050 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2051 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2054 if (txn->mt_dirty_room == 0)
2055 return MDB_TXN_FULL;
2056 if (IS_OVERFLOW(mp))
2060 if (env->me_flags & MDB_WRITEMAP) {
2063 np = mdb_page_malloc(txn, num);
2067 memcpy(np, mp, num * env->me_psize);
2069 mdb_page_copy(np, mp, env->me_psize);
2072 /* If in current txn, this page is no longer spilled.
2073 * If it happens to be the last page, truncate the spill list.
2074 * Otherwise mark it as deleted by setting the LSB.
2076 if (x == txn->mt_spill_pgs[0])
2077 txn->mt_spill_pgs[0]--;
2079 txn->mt_spill_pgs[x] |= 1;
2080 } /* otherwise, if belonging to a parent txn, the
2081 * page remains spilled until child commits
2084 mdb_page_dirty(txn, np);
2085 np->mp_flags |= P_DIRTY;
2093 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2094 * @param[in] mc cursor pointing to the page to be touched
2095 * @return 0 on success, non-zero on failure.
2098 mdb_page_touch(MDB_cursor *mc)
2100 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2101 MDB_txn *txn = mc->mc_txn;
2102 MDB_cursor *m2, *m3;
2106 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2107 if (txn->mt_flags & MDB_TXN_SPILLS) {
2109 rc = mdb_page_unspill(txn, mp, &np);
2115 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2116 (rc = mdb_page_alloc(mc, 1, &np)))
2119 DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
2120 mp->mp_pgno, pgno));
2121 mdb_cassert(mc, mp->mp_pgno != pgno);
2122 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2123 /* Update the parent page, if any, to point to the new page */
2125 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2126 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2127 SETPGNO(node, pgno);
2129 mc->mc_db->md_root = pgno;
2131 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2132 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2134 /* If txn has a parent, make sure the page is in our
2138 unsigned x = mdb_mid2l_search(dl, pgno);
2139 if (x <= dl[0].mid && dl[x].mid == pgno) {
2140 if (mp != dl[x].mptr) { /* bad cursor? */
2141 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2142 txn->mt_flags |= MDB_TXN_ERROR;
2143 return MDB_CORRUPTED;
2148 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2150 np = mdb_page_malloc(txn, 1);
2155 rc = mdb_mid2l_insert(dl, &mid);
2156 mdb_cassert(mc, rc == 0);
2161 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2163 np->mp_flags |= P_DIRTY;
2166 /* Adjust cursors pointing to mp */
2167 mc->mc_pg[mc->mc_top] = np;
2168 m2 = txn->mt_cursors[mc->mc_dbi];
2169 if (mc->mc_flags & C_SUB) {
2170 for (; m2; m2=m2->mc_next) {
2171 m3 = &m2->mc_xcursor->mx_cursor;
2172 if (m3->mc_snum < mc->mc_snum) continue;
2173 if (m3->mc_pg[mc->mc_top] == mp)
2174 m3->mc_pg[mc->mc_top] = np;
2177 for (; m2; m2=m2->mc_next) {
2178 if (m2->mc_snum < mc->mc_snum) continue;
2179 if (m2->mc_pg[mc->mc_top] == mp) {
2180 m2->mc_pg[mc->mc_top] = np;
2181 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
2183 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
2185 MDB_node *leaf = NODEPTR(np, mc->mc_ki[mc->mc_top]);
2186 if (!(leaf->mn_flags & F_SUBDATA))
2187 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
2195 txn->mt_flags |= MDB_TXN_ERROR;
2200 mdb_env_sync(MDB_env *env, int force)
2203 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2204 if (env->me_flags & MDB_WRITEMAP) {
2205 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2206 ? MS_ASYNC : MS_SYNC;
2207 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
2210 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2214 if (MDB_FDATASYNC(env->me_fd))
2221 /** Back up parent txn's cursors, then grab the originals for tracking */
2223 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2225 MDB_cursor *mc, *bk;
2230 for (i = src->mt_numdbs; --i >= 0; ) {
2231 if ((mc = src->mt_cursors[i]) != NULL) {
2232 size = sizeof(MDB_cursor);
2234 size += sizeof(MDB_xcursor);
2235 for (; mc; mc = bk->mc_next) {
2241 mc->mc_db = &dst->mt_dbs[i];
2242 /* Kill pointers into src - and dst to reduce abuse: The
2243 * user may not use mc until dst ends. Otherwise we'd...
2245 mc->mc_txn = NULL; /* ...set this to dst */
2246 mc->mc_dbflag = NULL; /* ...and &dst->mt_dbflags[i] */
2247 if ((mx = mc->mc_xcursor) != NULL) {
2248 *(MDB_xcursor *)(bk+1) = *mx;
2249 mx->mx_cursor.mc_txn = NULL; /* ...and dst. */
2251 mc->mc_next = dst->mt_cursors[i];
2252 dst->mt_cursors[i] = mc;
2259 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2260 * @param[in] txn the transaction handle.
2261 * @param[in] merge true to keep changes to parent cursors, false to revert.
2262 * @return 0 on success, non-zero on failure.
2265 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2267 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2271 for (i = txn->mt_numdbs; --i >= 0; ) {
2272 for (mc = cursors[i]; mc; mc = next) {
2274 if ((bk = mc->mc_backup) != NULL) {
2276 /* Commit changes to parent txn */
2277 mc->mc_next = bk->mc_next;
2278 mc->mc_backup = bk->mc_backup;
2279 mc->mc_txn = bk->mc_txn;
2280 mc->mc_db = bk->mc_db;
2281 mc->mc_dbflag = bk->mc_dbflag;
2282 if ((mx = mc->mc_xcursor) != NULL)
2283 mx->mx_cursor.mc_txn = bk->mc_txn;
2285 /* Abort nested txn */
2287 if ((mx = mc->mc_xcursor) != NULL)
2288 *mx = *(MDB_xcursor *)(bk+1);
2292 /* Only malloced cursors are permanently tracked. */
2300 #define mdb_txn_reset0(txn, act) mdb_txn_reset0(txn)
2303 mdb_txn_reset0(MDB_txn *txn, const char *act);
2305 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2311 Pidset = F_SETLK, Pidcheck = F_GETLK
2315 /** Set or check a pid lock. Set returns 0 on success.
2316 * Check returns 0 if the process is certainly dead, nonzero if it may
2317 * be alive (the lock exists or an error happened so we do not know).
2319 * On Windows Pidset is a no-op, we merely check for the existence
2320 * of the process with the given pid. On POSIX we use a single byte
2321 * lock on the lockfile, set at an offset equal to the pid.
2324 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2326 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2329 if (op == Pidcheck) {
2330 h = OpenProcess(env->me_pidquery, FALSE, pid);
2331 /* No documented "no such process" code, but other program use this: */
2333 return ErrCode() != ERROR_INVALID_PARAMETER;
2334 /* A process exists until all handles to it close. Has it exited? */
2335 ret = WaitForSingleObject(h, 0) != 0;
2342 struct flock lock_info;
2343 memset(&lock_info, 0, sizeof(lock_info));
2344 lock_info.l_type = F_WRLCK;
2345 lock_info.l_whence = SEEK_SET;
2346 lock_info.l_start = pid;
2347 lock_info.l_len = 1;
2348 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2349 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2351 } else if ((rc = ErrCode()) == EINTR) {
2359 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2360 * @param[in] txn the transaction handle to initialize
2361 * @return 0 on success, non-zero on failure.
2364 mdb_txn_renew0(MDB_txn *txn)
2366 MDB_env *env = txn->mt_env;
2367 MDB_txninfo *ti = env->me_txns;
2371 int rc, new_notls = 0;
2374 txn->mt_numdbs = env->me_numdbs;
2375 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
2377 if (txn->mt_flags & MDB_TXN_RDONLY) {
2379 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2380 txn->mt_txnid = meta->mm_txnid;
2381 txn->mt_u.reader = NULL;
2383 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2384 pthread_getspecific(env->me_txkey);
2386 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2387 return MDB_BAD_RSLOT;
2389 MDB_PID_T pid = env->me_pid;
2390 pthread_t tid = pthread_self();
2392 if (!env->me_live_reader) {
2393 rc = mdb_reader_pid(env, Pidset, pid);
2396 env->me_live_reader = 1;
2400 nr = ti->mti_numreaders;
2401 for (i=0; i<nr; i++)
2402 if (ti->mti_readers[i].mr_pid == 0)
2404 if (i == env->me_maxreaders) {
2405 UNLOCK_MUTEX_R(env);
2406 return MDB_READERS_FULL;
2408 ti->mti_readers[i].mr_pid = pid;
2409 ti->mti_readers[i].mr_tid = tid;
2411 ti->mti_numreaders = ++nr;
2412 /* Save numreaders for un-mutexed mdb_env_close() */
2413 env->me_numreaders = nr;
2414 UNLOCK_MUTEX_R(env);
2416 r = &ti->mti_readers[i];
2417 new_notls = (env->me_flags & MDB_NOTLS);
2418 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2423 txn->mt_txnid = r->mr_txnid = ti->mti_txnid;
2424 txn->mt_u.reader = r;
2425 meta = env->me_metas[txn->mt_txnid & 1];
2431 txn->mt_txnid = ti->mti_txnid;
2432 meta = env->me_metas[txn->mt_txnid & 1];
2434 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2435 txn->mt_txnid = meta->mm_txnid;
2439 if (txn->mt_txnid == mdb_debug_start)
2442 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2443 txn->mt_u.dirty_list = env->me_dirty_list;
2444 txn->mt_u.dirty_list[0].mid = 0;
2445 txn->mt_free_pgs = env->me_free_pgs;
2446 txn->mt_free_pgs[0] = 0;
2447 txn->mt_spill_pgs = NULL;
2451 /* Copy the DB info and flags */
2452 memcpy(txn->mt_dbs, meta->mm_dbs, 2 * sizeof(MDB_db));
2454 /* Moved to here to avoid a data race in read TXNs */
2455 txn->mt_next_pgno = meta->mm_last_pg+1;
2457 for (i=2; i<txn->mt_numdbs; i++) {
2458 x = env->me_dbflags[i];
2459 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2460 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_STALE : 0;
2462 txn->mt_dbflags[0] = txn->mt_dbflags[1] = DB_VALID;
2464 if (env->me_maxpg < txn->mt_next_pgno) {
2465 mdb_txn_reset0(txn, "renew0-mapfail");
2467 txn->mt_u.reader->mr_pid = 0;
2468 txn->mt_u.reader = NULL;
2470 return MDB_MAP_RESIZED;
2477 mdb_txn_renew(MDB_txn *txn)
2481 if (!txn || txn->mt_dbxs) /* A reset txn has mt_dbxs==NULL */
2484 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
2485 DPUTS("environment had fatal error, must shutdown!");
2489 rc = mdb_txn_renew0(txn);
2490 if (rc == MDB_SUCCESS) {
2491 DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2492 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2493 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2499 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2503 int rc, size, tsize = sizeof(MDB_txn);
2505 if (env->me_flags & MDB_FATAL_ERROR) {
2506 DPUTS("environment had fatal error, must shutdown!");
2509 if ((env->me_flags & MDB_RDONLY) && !(flags & MDB_RDONLY))
2512 /* Nested transactions: Max 1 child, write txns only, no writemap */
2513 if (parent->mt_child ||
2514 (flags & MDB_RDONLY) ||
2515 (parent->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR)) ||
2516 (env->me_flags & MDB_WRITEMAP))
2518 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
2520 tsize = sizeof(MDB_ntxn);
2522 size = tsize + env->me_maxdbs * (sizeof(MDB_db)+1);
2523 if (!(flags & MDB_RDONLY))
2524 size += env->me_maxdbs * sizeof(MDB_cursor *);
2526 if ((txn = calloc(1, size)) == NULL) {
2527 DPRINTF(("calloc: %s", strerror(ErrCode())));
2530 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2531 if (flags & MDB_RDONLY) {
2532 txn->mt_flags |= MDB_TXN_RDONLY;
2533 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
2535 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2536 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
2542 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2543 if (!txn->mt_u.dirty_list ||
2544 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2546 free(txn->mt_u.dirty_list);
2550 txn->mt_txnid = parent->mt_txnid;
2551 txn->mt_dirty_room = parent->mt_dirty_room;
2552 txn->mt_u.dirty_list[0].mid = 0;
2553 txn->mt_spill_pgs = NULL;
2554 txn->mt_next_pgno = parent->mt_next_pgno;
2555 parent->mt_child = txn;
2556 txn->mt_parent = parent;
2557 txn->mt_numdbs = parent->mt_numdbs;
2558 txn->mt_flags = parent->mt_flags;
2559 txn->mt_dbxs = parent->mt_dbxs;
2560 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2561 /* Copy parent's mt_dbflags, but clear DB_NEW */
2562 for (i=0; i<txn->mt_numdbs; i++)
2563 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2565 ntxn = (MDB_ntxn *)txn;
2566 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2567 if (env->me_pghead) {
2568 size = MDB_IDL_SIZEOF(env->me_pghead);
2569 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2571 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2576 rc = mdb_cursor_shadow(parent, txn);
2578 mdb_txn_reset0(txn, "beginchild-fail");
2580 rc = mdb_txn_renew0(txn);
2586 DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2587 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2588 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
2595 mdb_txn_env(MDB_txn *txn)
2597 if(!txn) return NULL;
2601 /** Export or close DBI handles opened in this txn. */
2603 mdb_dbis_update(MDB_txn *txn, int keep)
2606 MDB_dbi n = txn->mt_numdbs;
2607 MDB_env *env = txn->mt_env;
2608 unsigned char *tdbflags = txn->mt_dbflags;
2610 for (i = n; --i >= 2;) {
2611 if (tdbflags[i] & DB_NEW) {
2613 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2615 char *ptr = env->me_dbxs[i].md_name.mv_data;
2616 env->me_dbxs[i].md_name.mv_data = NULL;
2617 env->me_dbxs[i].md_name.mv_size = 0;
2618 env->me_dbflags[i] = 0;
2623 if (keep && env->me_numdbs < n)
2627 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
2628 * May be called twice for readonly txns: First reset it, then abort.
2629 * @param[in] txn the transaction handle to reset
2630 * @param[in] act why the transaction is being reset
2633 mdb_txn_reset0(MDB_txn *txn, const char *act)
2635 MDB_env *env = txn->mt_env;
2637 /* Close any DBI handles opened in this txn */
2638 mdb_dbis_update(txn, 0);
2640 DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2641 act, txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2642 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
2644 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2645 if (txn->mt_u.reader) {
2646 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2647 if (!(env->me_flags & MDB_NOTLS))
2648 txn->mt_u.reader = NULL; /* txn does not own reader */
2650 txn->mt_numdbs = 0; /* close nothing if called again */
2651 txn->mt_dbxs = NULL; /* mark txn as reset */
2653 mdb_cursors_close(txn, 0);
2655 if (!(env->me_flags & MDB_WRITEMAP)) {
2656 mdb_dlist_free(txn);
2658 mdb_midl_free(env->me_pghead);
2660 if (txn->mt_parent) {
2661 txn->mt_parent->mt_child = NULL;
2662 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2663 mdb_midl_free(txn->mt_free_pgs);
2664 mdb_midl_free(txn->mt_spill_pgs);
2665 free(txn->mt_u.dirty_list);
2669 if (mdb_midl_shrink(&txn->mt_free_pgs))
2670 env->me_free_pgs = txn->mt_free_pgs;
2671 env->me_pghead = NULL;
2675 /* The writer mutex was locked in mdb_txn_begin. */
2677 UNLOCK_MUTEX_W(env);
2682 mdb_txn_reset(MDB_txn *txn)
2687 /* This call is only valid for read-only txns */
2688 if (!(txn->mt_flags & MDB_TXN_RDONLY))
2691 mdb_txn_reset0(txn, "reset");
2695 mdb_txn_abort(MDB_txn *txn)
2701 mdb_txn_abort(txn->mt_child);
2703 mdb_txn_reset0(txn, "abort");
2704 /* Free reader slot tied to this txn (if MDB_NOTLS && writable FS) */
2705 if ((txn->mt_flags & MDB_TXN_RDONLY) && txn->mt_u.reader)
2706 txn->mt_u.reader->mr_pid = 0;
2711 /** Save the freelist as of this transaction to the freeDB.
2712 * This changes the freelist. Keep trying until it stabilizes.
2715 mdb_freelist_save(MDB_txn *txn)
2717 /* env->me_pghead[] can grow and shrink during this call.
2718 * env->me_pglast and txn->mt_free_pgs[] can only grow.
2719 * Page numbers cannot disappear from txn->mt_free_pgs[].
2722 MDB_env *env = txn->mt_env;
2723 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
2724 txnid_t pglast = 0, head_id = 0;
2725 pgno_t freecnt = 0, *free_pgs, *mop;
2726 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
2728 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
2730 if (env->me_pghead) {
2731 /* Make sure first page of freeDB is touched and on freelist */
2732 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
2733 if (rc && rc != MDB_NOTFOUND)
2737 /* Dispose of loose pages. Usually they will have all
2738 * been used up by the time we get here.
2740 if (txn->mt_loose_pgs) {
2741 MDB_page *mp = txn->mt_loose_pgs;
2742 /* Just return them to freeDB */
2743 if (env->me_pghead) {
2745 mop = env->me_pghead;
2746 for (; mp; mp = NEXT_LOOSE_PAGE(mp)) {
2747 pgno_t pg = mp->mp_pgno;
2749 for (i = mop[0]; i && mop[i] < pg; i--)
2755 /* Oh well, they were wasted. Put on freelist */
2756 for (; mp; mp = NEXT_LOOSE_PAGE(mp)) {
2757 mdb_midl_append(&txn->mt_free_pgs, mp->mp_pgno);
2760 txn->mt_loose_pgs = NULL;
2763 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
2764 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
2765 ? SSIZE_MAX : maxfree_1pg;
2768 /* Come back here after each Put() in case freelist changed */
2773 /* If using records from freeDB which we have not yet
2774 * deleted, delete them and any we reserved for me_pghead.
2776 while (pglast < env->me_pglast) {
2777 rc = mdb_cursor_first(&mc, &key, NULL);
2780 pglast = head_id = *(txnid_t *)key.mv_data;
2781 total_room = head_room = 0;
2782 mdb_tassert(txn, pglast <= env->me_pglast);
2783 rc = mdb_cursor_del(&mc, 0);
2788 /* Save the IDL of pages freed by this txn, to a single record */
2789 if (freecnt < txn->mt_free_pgs[0]) {
2791 /* Make sure last page of freeDB is touched and on freelist */
2792 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
2793 if (rc && rc != MDB_NOTFOUND)
2796 free_pgs = txn->mt_free_pgs;
2797 /* Write to last page of freeDB */
2798 key.mv_size = sizeof(txn->mt_txnid);
2799 key.mv_data = &txn->mt_txnid;
2801 freecnt = free_pgs[0];
2802 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
2803 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2806 /* Retry if mt_free_pgs[] grew during the Put() */
2807 free_pgs = txn->mt_free_pgs;
2808 } while (freecnt < free_pgs[0]);
2809 mdb_midl_sort(free_pgs);
2810 memcpy(data.mv_data, free_pgs, data.mv_size);
2813 unsigned int i = free_pgs[0];
2814 DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
2815 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
2817 DPRINTF(("IDL %"Z"u", free_pgs[i]));
2823 mop = env->me_pghead;
2824 mop_len = mop ? mop[0] : 0;
2826 /* Reserve records for me_pghead[]. Split it if multi-page,
2827 * to avoid searching freeDB for a page range. Use keys in
2828 * range [1,me_pglast]: Smaller than txnid of oldest reader.
2830 if (total_room >= mop_len) {
2831 if (total_room == mop_len || --more < 0)
2833 } else if (head_room >= maxfree_1pg && head_id > 1) {
2834 /* Keep current record (overflow page), add a new one */
2838 /* (Re)write {key = head_id, IDL length = head_room} */
2839 total_room -= head_room;
2840 head_room = mop_len - total_room;
2841 if (head_room > maxfree_1pg && head_id > 1) {
2842 /* Overflow multi-page for part of me_pghead */
2843 head_room /= head_id; /* amortize page sizes */
2844 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
2845 } else if (head_room < 0) {
2846 /* Rare case, not bothering to delete this record */
2849 key.mv_size = sizeof(head_id);
2850 key.mv_data = &head_id;
2851 data.mv_size = (head_room + 1) * sizeof(pgno_t);
2852 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2855 /* IDL is initially empty, zero out at least the length */
2856 pgs = (pgno_t *)data.mv_data;
2857 j = head_room > clean_limit ? head_room : 0;
2861 total_room += head_room;
2864 /* Fill in the reserved me_pghead records */
2870 rc = mdb_cursor_first(&mc, &key, &data);
2871 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
2872 txnid_t id = *(txnid_t *)key.mv_data;
2873 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
2876 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
2878 if (len > mop_len) {
2880 data.mv_size = (len + 1) * sizeof(MDB_ID);
2882 data.mv_data = mop -= len;
2885 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
2887 if (rc || !(mop_len -= len))
2894 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
2895 * @param[in] txn the transaction that's being committed
2896 * @param[in] keep number of initial pages in dirty_list to keep dirty.
2897 * @return 0 on success, non-zero on failure.
2900 mdb_page_flush(MDB_txn *txn, int keep)
2902 MDB_env *env = txn->mt_env;
2903 MDB_ID2L dl = txn->mt_u.dirty_list;
2904 unsigned psize = env->me_psize, j;
2905 int i, pagecount = dl[0].mid, rc;
2906 size_t size = 0, pos = 0;
2908 MDB_page *dp = NULL;
2912 struct iovec iov[MDB_COMMIT_PAGES];
2913 ssize_t wpos = 0, wsize = 0, wres;
2914 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
2920 if (env->me_flags & MDB_WRITEMAP) {
2921 /* Clear dirty flags */
2922 while (++i <= pagecount) {
2924 /* Don't flush this page yet */
2925 if (dp->mp_flags & P_KEEP) {
2926 dp->mp_flags ^= P_KEEP;
2930 dp->mp_flags &= ~P_DIRTY;
2935 /* Write the pages */
2937 if (++i <= pagecount) {
2939 /* Don't flush this page yet */
2940 if (dp->mp_flags & P_KEEP) {
2941 dp->mp_flags ^= P_KEEP;
2946 /* clear dirty flag */
2947 dp->mp_flags &= ~P_DIRTY;
2950 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
2955 /* Windows actually supports scatter/gather I/O, but only on
2956 * unbuffered file handles. Since we're relying on the OS page
2957 * cache for all our data, that's self-defeating. So we just
2958 * write pages one at a time. We use the ov structure to set
2959 * the write offset, to at least save the overhead of a Seek
2962 DPRINTF(("committing page %"Z"u", pgno));
2963 memset(&ov, 0, sizeof(ov));
2964 ov.Offset = pos & 0xffffffff;
2965 ov.OffsetHigh = pos >> 16 >> 16;
2966 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
2968 DPRINTF(("WriteFile: %d", rc));
2972 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
2973 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
2975 /* Write previous page(s) */
2976 #ifdef MDB_USE_PWRITEV
2977 wres = pwritev(env->me_fd, iov, n, wpos);
2980 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
2982 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
2984 DPRINTF(("lseek: %s", strerror(rc)));
2987 wres = writev(env->me_fd, iov, n);
2990 if (wres != wsize) {
2993 DPRINTF(("Write error: %s", strerror(rc)));
2995 rc = EIO; /* TODO: Use which error code? */
2996 DPUTS("short write, filesystem full?");
3007 DPRINTF(("committing page %"Z"u", pgno));
3008 next_pos = pos + size;
3009 iov[n].iov_len = size;
3010 iov[n].iov_base = (char *)dp;
3016 for (i = keep; ++i <= pagecount; ) {
3018 /* This is a page we skipped above */
3021 dl[j].mid = dp->mp_pgno;
3024 mdb_dpage_free(env, dp);
3029 txn->mt_dirty_room += i - j;
3035 mdb_txn_commit(MDB_txn *txn)
3041 if (txn == NULL || txn->mt_env == NULL)
3044 if (txn->mt_child) {
3045 rc = mdb_txn_commit(txn->mt_child);
3046 txn->mt_child = NULL;
3053 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3054 mdb_dbis_update(txn, 1);
3055 txn->mt_numdbs = 2; /* so txn_abort() doesn't close any new handles */
3060 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
3061 DPUTS("error flag is set, can't commit");
3063 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3068 if (txn->mt_parent) {
3069 MDB_txn *parent = txn->mt_parent;
3072 unsigned x, y, len, ps_len;
3074 /* Append our free list to parent's */
3075 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3078 mdb_midl_free(txn->mt_free_pgs);
3079 /* Failures after this must either undo the changes
3080 * to the parent or set MDB_TXN_ERROR in the parent.
3083 parent->mt_next_pgno = txn->mt_next_pgno;
3084 parent->mt_flags = txn->mt_flags;
3086 /* Merge our cursors into parent's and close them */
3087 mdb_cursors_close(txn, 1);
3089 /* Update parent's DB table. */
3090 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3091 parent->mt_numdbs = txn->mt_numdbs;
3092 parent->mt_dbflags[0] = txn->mt_dbflags[0];
3093 parent->mt_dbflags[1] = txn->mt_dbflags[1];
3094 for (i=2; i<txn->mt_numdbs; i++) {
3095 /* preserve parent's DB_NEW status */
3096 x = parent->mt_dbflags[i] & DB_NEW;
3097 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3100 dst = parent->mt_u.dirty_list;
3101 src = txn->mt_u.dirty_list;
3102 /* Remove anything in our dirty list from parent's spill list */
3103 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3105 pspill[0] = (pgno_t)-1;
3106 /* Mark our dirty pages as deleted in parent spill list */
3107 for (i=0, len=src[0].mid; ++i <= len; ) {
3108 MDB_ID pn = src[i].mid << 1;
3109 while (pn > pspill[x])
3111 if (pn == pspill[x]) {
3116 /* Squash deleted pagenums if we deleted any */
3117 for (x=y; ++x <= ps_len; )
3118 if (!(pspill[x] & 1))
3119 pspill[++y] = pspill[x];
3123 /* Find len = length of merging our dirty list with parent's */
3125 dst[0].mid = 0; /* simplify loops */
3126 if (parent->mt_parent) {
3127 len = x + src[0].mid;
3128 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3129 for (i = x; y && i; y--) {
3130 pgno_t yp = src[y].mid;
3131 while (yp < dst[i].mid)
3133 if (yp == dst[i].mid) {
3138 } else { /* Simplify the above for single-ancestor case */
3139 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3141 /* Merge our dirty list with parent's */
3143 for (i = len; y; dst[i--] = src[y--]) {
3144 pgno_t yp = src[y].mid;
3145 while (yp < dst[x].mid)
3146 dst[i--] = dst[x--];
3147 if (yp == dst[x].mid)
3148 free(dst[x--].mptr);
3150 mdb_tassert(txn, i == x);
3152 free(txn->mt_u.dirty_list);
3153 parent->mt_dirty_room = txn->mt_dirty_room;
3154 if (txn->mt_spill_pgs) {
3155 if (parent->mt_spill_pgs) {
3156 /* TODO: Prevent failure here, so parent does not fail */
3157 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3159 parent->mt_flags |= MDB_TXN_ERROR;
3160 mdb_midl_free(txn->mt_spill_pgs);
3161 mdb_midl_sort(parent->mt_spill_pgs);
3163 parent->mt_spill_pgs = txn->mt_spill_pgs;
3167 parent->mt_child = NULL;
3168 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3173 if (txn != env->me_txn) {
3174 DPUTS("attempt to commit unknown transaction");
3179 mdb_cursors_close(txn, 0);
3181 if (!txn->mt_u.dirty_list[0].mid &&
3182 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
3185 DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
3186 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3188 /* Update DB root pointers */
3189 if (txn->mt_numdbs > 2) {
3193 data.mv_size = sizeof(MDB_db);
3195 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3196 for (i = 2; i < txn->mt_numdbs; i++) {
3197 if (txn->mt_dbflags[i] & DB_DIRTY) {
3198 data.mv_data = &txn->mt_dbs[i];
3199 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
3206 rc = mdb_freelist_save(txn);
3210 mdb_midl_free(env->me_pghead);
3211 env->me_pghead = NULL;
3212 if (mdb_midl_shrink(&txn->mt_free_pgs))
3213 env->me_free_pgs = txn->mt_free_pgs;
3219 if ((rc = mdb_page_flush(txn, 0)) ||
3220 (rc = mdb_env_sync(env, 0)) ||
3221 (rc = mdb_env_write_meta(txn)))
3227 mdb_dbis_update(txn, 1);
3230 UNLOCK_MUTEX_W(env);
3240 /** Read the environment parameters of a DB environment before
3241 * mapping it into memory.
3242 * @param[in] env the environment handle
3243 * @param[out] meta address of where to store the meta information
3244 * @return 0 on success, non-zero on failure.
3247 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3253 enum { Size = sizeof(pbuf) };
3255 /* We don't know the page size yet, so use a minimum value.
3256 * Read both meta pages so we can use the latest one.
3259 for (i=off=0; i<2; i++, off = meta->mm_psize) {
3263 memset(&ov, 0, sizeof(ov));
3265 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3266 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3269 rc = pread(env->me_fd, &pbuf, Size, off);
3272 if (rc == 0 && off == 0)
3274 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3275 DPRINTF(("read: %s", mdb_strerror(rc)));
3279 p = (MDB_page *)&pbuf;
3281 if (!F_ISSET(p->mp_flags, P_META)) {
3282 DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
3287 if (m->mm_magic != MDB_MAGIC) {
3288 DPUTS("meta has invalid magic");
3292 if (m->mm_version != MDB_DATA_VERSION) {
3293 DPRINTF(("database is version %u, expected version %u",
3294 m->mm_version, MDB_DATA_VERSION));
3295 return MDB_VERSION_MISMATCH;
3298 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3305 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
3307 meta->mm_magic = MDB_MAGIC;
3308 meta->mm_version = MDB_DATA_VERSION;
3309 meta->mm_mapsize = env->me_mapsize;
3310 meta->mm_psize = env->me_psize;
3311 meta->mm_last_pg = 1;
3312 meta->mm_flags = env->me_flags & 0xffff;
3313 meta->mm_flags |= MDB_INTEGERKEY;
3314 meta->mm_dbs[0].md_root = P_INVALID;
3315 meta->mm_dbs[1].md_root = P_INVALID;
3318 /** Write the environment parameters of a freshly created DB environment.
3319 * @param[in] env the environment handle
3320 * @param[out] meta address of where to store the meta information
3321 * @return 0 on success, non-zero on failure.
3324 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3332 memset(&ov, 0, sizeof(ov));
3333 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3335 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3338 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3339 len = pwrite(fd, ptr, size, pos); \
3340 rc = (len >= 0); } while(0)
3343 DPUTS("writing new meta page");
3345 psize = env->me_psize;
3347 mdb_env_init_meta0(env, meta);
3349 p = calloc(2, psize);
3351 p->mp_flags = P_META;
3352 *(MDB_meta *)METADATA(p) = *meta;
3354 q = (MDB_page *)((char *)p + psize);
3356 q->mp_flags = P_META;
3357 *(MDB_meta *)METADATA(q) = *meta;
3359 DO_PWRITE(rc, env->me_fd, p, psize * 2, len, 0);
3362 else if ((unsigned) len == psize * 2)
3370 /** Update the environment info to commit a transaction.
3371 * @param[in] txn the transaction that's being committed
3372 * @return 0 on success, non-zero on failure.
3375 mdb_env_write_meta(MDB_txn *txn)
3378 MDB_meta meta, metab, *mp;
3380 int rc, len, toggle;
3389 toggle = txn->mt_txnid & 1;
3390 DPRINTF(("writing meta page %d for root page %"Z"u",
3391 toggle, txn->mt_dbs[MAIN_DBI].md_root));
3394 mp = env->me_metas[toggle];
3396 if (env->me_flags & MDB_WRITEMAP) {
3397 /* Persist any increases of mapsize config */
3398 if (env->me_mapsize > mp->mm_mapsize)
3399 mp->mm_mapsize = env->me_mapsize;
3400 mp->mm_dbs[0] = txn->mt_dbs[0];
3401 mp->mm_dbs[1] = txn->mt_dbs[1];
3402 mp->mm_last_pg = txn->mt_next_pgno - 1;
3403 mp->mm_txnid = txn->mt_txnid;
3404 if (!(env->me_flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3405 unsigned meta_size = env->me_psize;
3406 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3409 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
3410 if (meta_size < env->me_os_psize)
3411 meta_size += meta_size;
3416 if (MDB_MSYNC(ptr, meta_size, rc)) {
3423 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
3424 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
3426 ptr = (char *)&meta;
3427 if (env->me_mapsize > mp->mm_mapsize) {
3428 /* Persist any increases of mapsize config */
3429 meta.mm_mapsize = env->me_mapsize;
3430 off = offsetof(MDB_meta, mm_mapsize);
3432 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
3434 len = sizeof(MDB_meta) - off;
3437 meta.mm_dbs[0] = txn->mt_dbs[0];
3438 meta.mm_dbs[1] = txn->mt_dbs[1];
3439 meta.mm_last_pg = txn->mt_next_pgno - 1;
3440 meta.mm_txnid = txn->mt_txnid;
3443 off += env->me_psize;
3446 /* Write to the SYNC fd */
3447 mfd = env->me_flags & (MDB_NOSYNC|MDB_NOMETASYNC) ?
3448 env->me_fd : env->me_mfd;
3451 memset(&ov, 0, sizeof(ov));
3453 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3457 rc = pwrite(mfd, ptr, len, off);
3460 rc = rc < 0 ? ErrCode() : EIO;
3461 DPUTS("write failed, disk error?");
3462 /* On a failure, the pagecache still contains the new data.
3463 * Write some old data back, to prevent it from being used.
3464 * Use the non-SYNC fd; we know it will fail anyway.
3466 meta.mm_last_pg = metab.mm_last_pg;
3467 meta.mm_txnid = metab.mm_txnid;
3469 memset(&ov, 0, sizeof(ov));
3471 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3473 r2 = pwrite(env->me_fd, ptr, len, off);
3474 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
3477 env->me_flags |= MDB_FATAL_ERROR;
3481 /* Memory ordering issues are irrelevant; since the entire writer
3482 * is wrapped by wmutex, all of these changes will become visible
3483 * after the wmutex is unlocked. Since the DB is multi-version,
3484 * readers will get consistent data regardless of how fresh or
3485 * how stale their view of these values is.
3488 env->me_txns->mti_txnid = txn->mt_txnid;
3493 /** Check both meta pages to see which one is newer.
3494 * @param[in] env the environment handle
3495 * @return meta toggle (0 or 1).
3498 mdb_env_pick_meta(const MDB_env *env)
3500 return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
3504 mdb_env_create(MDB_env **env)
3508 e = calloc(1, sizeof(MDB_env));
3512 e->me_maxreaders = DEFAULT_READERS;
3513 e->me_maxdbs = e->me_numdbs = 2;
3514 e->me_fd = INVALID_HANDLE_VALUE;
3515 e->me_lfd = INVALID_HANDLE_VALUE;
3516 e->me_mfd = INVALID_HANDLE_VALUE;
3517 #ifdef MDB_USE_POSIX_SEM
3518 e->me_rmutex = SEM_FAILED;
3519 e->me_wmutex = SEM_FAILED;
3521 e->me_pid = getpid();
3522 GET_PAGESIZE(e->me_os_psize);
3523 VGMEMP_CREATE(e,0,0);
3529 mdb_env_map(MDB_env *env, void *addr, int newsize)
3532 unsigned int flags = env->me_flags;
3536 LONG sizelo, sizehi;
3537 sizelo = env->me_mapsize & 0xffffffff;
3538 sizehi = env->me_mapsize >> 16 >> 16; /* only needed on Win64 */
3540 /* Windows won't create mappings for zero length files.
3541 * Just allocate the maxsize right now.
3544 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3545 || !SetEndOfFile(env->me_fd)
3546 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3549 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3550 PAGE_READWRITE : PAGE_READONLY,
3551 sizehi, sizelo, NULL);
3554 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3555 FILE_MAP_WRITE : FILE_MAP_READ,
3556 0, 0, env->me_mapsize, addr);
3557 rc = env->me_map ? 0 : ErrCode();
3562 int prot = PROT_READ;
3563 if (flags & MDB_WRITEMAP) {
3565 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3568 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
3570 if (env->me_map == MAP_FAILED) {
3575 if (flags & MDB_NORDAHEAD) {
3576 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3578 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3580 #ifdef POSIX_MADV_RANDOM
3581 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3582 #endif /* POSIX_MADV_RANDOM */
3583 #endif /* MADV_RANDOM */
3587 /* Can happen because the address argument to mmap() is just a
3588 * hint. mmap() can pick another, e.g. if the range is in use.
3589 * The MAP_FIXED flag would prevent that, but then mmap could
3590 * instead unmap existing pages to make room for the new map.
3592 if (addr && env->me_map != addr)
3593 return EBUSY; /* TODO: Make a new MDB_* error code? */
3595 p = (MDB_page *)env->me_map;
3596 env->me_metas[0] = METADATA(p);
3597 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
3603 mdb_env_set_mapsize(MDB_env *env, size_t size)
3605 /* If env is already open, caller is responsible for making
3606 * sure there are no active txns.
3614 size = env->me_metas[mdb_env_pick_meta(env)]->mm_mapsize;
3615 else if (size < env->me_mapsize) {
3616 /* If the configured size is smaller, make sure it's
3617 * still big enough. Silently round up to minimum if not.
3619 size_t minsize = (env->me_metas[mdb_env_pick_meta(env)]->mm_last_pg + 1) * env->me_psize;
3623 munmap(env->me_map, env->me_mapsize);
3624 env->me_mapsize = size;
3625 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
3626 rc = mdb_env_map(env, old, 1);
3630 env->me_mapsize = size;
3632 env->me_maxpg = env->me_mapsize / env->me_psize;
3637 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
3641 env->me_maxdbs = dbs + 2; /* Named databases + main and free DB */
3646 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
3648 if (env->me_map || readers < 1)
3650 env->me_maxreaders = readers;
3655 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
3657 if (!env || !readers)
3659 *readers = env->me_maxreaders;
3663 /** Further setup required for opening an LMDB environment
3666 mdb_env_open2(MDB_env *env)
3668 unsigned int flags = env->me_flags;
3669 int i, newenv = 0, rc;
3673 /* See if we should use QueryLimited */
3675 if ((rc & 0xff) > 5)
3676 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
3678 env->me_pidquery = PROCESS_QUERY_INFORMATION;
3681 memset(&meta, 0, sizeof(meta));
3683 if ((i = mdb_env_read_header(env, &meta)) != 0) {
3686 DPUTS("new mdbenv");
3688 env->me_psize = env->me_os_psize;
3689 if (env->me_psize > MAX_PAGESIZE)
3690 env->me_psize = MAX_PAGESIZE;
3692 env->me_psize = meta.mm_psize;
3695 /* Was a mapsize configured? */
3696 if (!env->me_mapsize) {
3697 /* If this is a new environment, take the default,
3698 * else use the size recorded in the existing env.
3700 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
3701 } else if (env->me_mapsize < meta.mm_mapsize) {
3702 /* If the configured size is smaller, make sure it's
3703 * still big enough. Silently round up to minimum if not.
3705 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
3706 if (env->me_mapsize < minsize)
3707 env->me_mapsize = minsize;
3710 rc = mdb_env_map(env, meta.mm_address, newenv || env->me_mapsize != meta.mm_mapsize);
3715 if (flags & MDB_FIXEDMAP)
3716 meta.mm_address = env->me_map;
3717 i = mdb_env_init_meta(env, &meta);
3718 if (i != MDB_SUCCESS) {
3723 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
3724 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
3726 #if !(MDB_MAXKEYSIZE)
3727 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
3729 env->me_maxpg = env->me_mapsize / env->me_psize;
3733 int toggle = mdb_env_pick_meta(env);
3734 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
3736 DPRINTF(("opened database version %u, pagesize %u",
3737 env->me_metas[0]->mm_version, env->me_psize));
3738 DPRINTF(("using meta page %d", toggle));
3739 DPRINTF(("depth: %u", db->md_depth));
3740 DPRINTF(("entries: %"Z"u", db->md_entries));
3741 DPRINTF(("branch pages: %"Z"u", db->md_branch_pages));
3742 DPRINTF(("leaf pages: %"Z"u", db->md_leaf_pages));
3743 DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
3744 DPRINTF(("root: %"Z"u", db->md_root));
3752 /** Release a reader thread's slot in the reader lock table.
3753 * This function is called automatically when a thread exits.
3754 * @param[in] ptr This points to the slot in the reader lock table.
3757 mdb_env_reader_dest(void *ptr)
3759 MDB_reader *reader = ptr;
3765 /** Junk for arranging thread-specific callbacks on Windows. This is
3766 * necessarily platform and compiler-specific. Windows supports up
3767 * to 1088 keys. Let's assume nobody opens more than 64 environments
3768 * in a single process, for now. They can override this if needed.
3770 #ifndef MAX_TLS_KEYS
3771 #define MAX_TLS_KEYS 64
3773 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
3774 static int mdb_tls_nkeys;
3776 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
3780 case DLL_PROCESS_ATTACH: break;
3781 case DLL_THREAD_ATTACH: break;
3782 case DLL_THREAD_DETACH:
3783 for (i=0; i<mdb_tls_nkeys; i++) {
3784 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
3786 mdb_env_reader_dest(r);
3790 case DLL_PROCESS_DETACH: break;
3795 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3797 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3801 /* Force some symbol references.
3802 * _tls_used forces the linker to create the TLS directory if not already done
3803 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
3805 #pragma comment(linker, "/INCLUDE:_tls_used")
3806 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
3807 #pragma const_seg(".CRT$XLB")
3808 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
3809 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3812 #pragma comment(linker, "/INCLUDE:__tls_used")
3813 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
3814 #pragma data_seg(".CRT$XLB")
3815 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3817 #endif /* WIN 32/64 */
3818 #endif /* !__GNUC__ */
3821 /** Downgrade the exclusive lock on the region back to shared */
3823 mdb_env_share_locks(MDB_env *env, int *excl)
3825 int rc = 0, toggle = mdb_env_pick_meta(env);
3827 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
3832 /* First acquire a shared lock. The Unlock will
3833 * then release the existing exclusive lock.
3835 memset(&ov, 0, sizeof(ov));
3836 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3839 UnlockFile(env->me_lfd, 0, 0, 1, 0);
3845 struct flock lock_info;
3846 /* The shared lock replaces the existing lock */
3847 memset((void *)&lock_info, 0, sizeof(lock_info));
3848 lock_info.l_type = F_RDLCK;
3849 lock_info.l_whence = SEEK_SET;
3850 lock_info.l_start = 0;
3851 lock_info.l_len = 1;
3852 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3853 (rc = ErrCode()) == EINTR) ;
3854 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
3861 /** Try to get exlusive lock, otherwise shared.
3862 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
3865 mdb_env_excl_lock(MDB_env *env, int *excl)
3869 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
3873 memset(&ov, 0, sizeof(ov));
3874 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3881 struct flock lock_info;
3882 memset((void *)&lock_info, 0, sizeof(lock_info));
3883 lock_info.l_type = F_WRLCK;
3884 lock_info.l_whence = SEEK_SET;
3885 lock_info.l_start = 0;
3886 lock_info.l_len = 1;
3887 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3888 (rc = ErrCode()) == EINTR) ;
3892 # ifdef MDB_USE_POSIX_SEM
3893 if (*excl < 0) /* always true when !MDB_USE_POSIX_SEM */
3896 lock_info.l_type = F_RDLCK;
3897 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
3898 (rc = ErrCode()) == EINTR) ;
3908 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
3910 * @(#) $Revision: 5.1 $
3911 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
3912 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
3914 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
3918 * Please do not copyright this code. This code is in the public domain.
3920 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
3921 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
3922 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
3923 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
3924 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
3925 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
3926 * PERFORMANCE OF THIS SOFTWARE.
3929 * chongo <Landon Curt Noll> /\oo/\
3930 * http://www.isthe.com/chongo/
3932 * Share and Enjoy! :-)
3935 typedef unsigned long long mdb_hash_t;
3936 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
3938 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
3939 * @param[in] val value to hash
3940 * @param[in] hval initial value for hash
3941 * @return 64 bit hash
3943 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
3944 * hval arg on the first call.
3947 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
3949 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
3950 unsigned char *end = s + val->mv_size;
3952 * FNV-1a hash each octet of the string
3955 /* xor the bottom with the current octet */
3956 hval ^= (mdb_hash_t)*s++;
3958 /* multiply by the 64 bit FNV magic prime mod 2^64 */
3959 hval += (hval << 1) + (hval << 4) + (hval << 5) +
3960 (hval << 7) + (hval << 8) + (hval << 40);
3962 /* return our new hash value */
3966 /** Hash the string and output the encoded hash.
3967 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
3968 * very short name limits. We don't care about the encoding being reversible,
3969 * we just want to preserve as many bits of the input as possible in a
3970 * small printable string.
3971 * @param[in] str string to hash
3972 * @param[out] encbuf an array of 11 chars to hold the hash
3974 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
3977 mdb_pack85(unsigned long l, char *out)
3981 for (i=0; i<5; i++) {
3982 *out++ = mdb_a85[l % 85];
3988 mdb_hash_enc(MDB_val *val, char *encbuf)
3990 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
3992 mdb_pack85(h, encbuf);
3993 mdb_pack85(h>>32, encbuf+5);
3998 /** Open and/or initialize the lock region for the environment.
3999 * @param[in] env The LMDB environment.
4000 * @param[in] lpath The pathname of the file used for the lock region.
4001 * @param[in] mode The Unix permissions for the file, if we create it.
4002 * @param[out] excl Resulting file lock type: -1 none, 0 shared, 1 exclusive
4003 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
4004 * @return 0 on success, non-zero on failure.
4007 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
4010 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
4012 # define MDB_ERRCODE_ROFS EROFS
4013 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
4014 # define MDB_CLOEXEC O_CLOEXEC
4017 # define MDB_CLOEXEC 0
4024 env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
4025 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
4026 FILE_ATTRIBUTE_NORMAL, NULL);
4028 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
4030 if (env->me_lfd == INVALID_HANDLE_VALUE) {
4032 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
4037 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
4038 /* Lose record locks when exec*() */
4039 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
4040 fcntl(env->me_lfd, F_SETFD, fdflags);
4043 if (!(env->me_flags & MDB_NOTLS)) {
4044 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
4047 env->me_flags |= MDB_ENV_TXKEY;
4049 /* Windows TLS callbacks need help finding their TLS info. */
4050 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
4054 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
4058 /* Try to get exclusive lock. If we succeed, then
4059 * nobody is using the lock region and we should initialize it.
4061 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
4064 size = GetFileSize(env->me_lfd, NULL);
4066 size = lseek(env->me_lfd, 0, SEEK_END);
4067 if (size == -1) goto fail_errno;
4069 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
4070 if (size < rsize && *excl > 0) {
4072 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
4073 || !SetEndOfFile(env->me_lfd))
4076 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
4080 size = rsize - sizeof(MDB_txninfo);
4081 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
4086 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
4088 if (!mh) goto fail_errno;
4089 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
4091 if (!env->me_txns) goto fail_errno;
4093 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
4095 if (m == MAP_FAILED) goto fail_errno;
4101 BY_HANDLE_FILE_INFORMATION stbuf;
4110 if (!mdb_sec_inited) {
4111 InitializeSecurityDescriptor(&mdb_null_sd,
4112 SECURITY_DESCRIPTOR_REVISION);
4113 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
4114 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
4115 mdb_all_sa.bInheritHandle = FALSE;
4116 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
4119 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
4120 idbuf.volume = stbuf.dwVolumeSerialNumber;
4121 idbuf.nhigh = stbuf.nFileIndexHigh;
4122 idbuf.nlow = stbuf.nFileIndexLow;
4123 val.mv_data = &idbuf;
4124 val.mv_size = sizeof(idbuf);
4125 mdb_hash_enc(&val, encbuf);
4126 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
4127 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
4128 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
4129 if (!env->me_rmutex) goto fail_errno;
4130 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
4131 if (!env->me_wmutex) goto fail_errno;
4132 #elif defined(MDB_USE_POSIX_SEM)
4141 #if defined(__NetBSD__)
4142 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
4144 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
4145 idbuf.dev = stbuf.st_dev;
4146 idbuf.ino = stbuf.st_ino;
4147 val.mv_data = &idbuf;
4148 val.mv_size = sizeof(idbuf);
4149 mdb_hash_enc(&val, encbuf);
4150 #ifdef MDB_SHORT_SEMNAMES
4151 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
4153 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
4154 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
4155 /* Clean up after a previous run, if needed: Try to
4156 * remove both semaphores before doing anything else.
4158 sem_unlink(env->me_txns->mti_rmname);
4159 sem_unlink(env->me_txns->mti_wmname);
4160 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
4161 O_CREAT|O_EXCL, mode, 1);
4162 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4163 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
4164 O_CREAT|O_EXCL, mode, 1);
4165 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4166 #else /* MDB_USE_POSIX_SEM */
4167 pthread_mutexattr_t mattr;
4169 if ((rc = pthread_mutexattr_init(&mattr))
4170 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
4171 || (rc = pthread_mutex_init(&env->me_txns->mti_mutex, &mattr))
4172 || (rc = pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr)))
4174 pthread_mutexattr_destroy(&mattr);
4175 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
4177 env->me_txns->mti_magic = MDB_MAGIC;
4178 env->me_txns->mti_format = MDB_LOCK_FORMAT;
4179 env->me_txns->mti_txnid = 0;
4180 env->me_txns->mti_numreaders = 0;
4183 if (env->me_txns->mti_magic != MDB_MAGIC) {
4184 DPUTS("lock region has invalid magic");
4188 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
4189 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
4190 env->me_txns->mti_format, MDB_LOCK_FORMAT));
4191 rc = MDB_VERSION_MISMATCH;
4195 if (rc && rc != EACCES && rc != EAGAIN) {
4199 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
4200 if (!env->me_rmutex) goto fail_errno;
4201 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
4202 if (!env->me_wmutex) goto fail_errno;
4203 #elif defined(MDB_USE_POSIX_SEM)
4204 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
4205 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4206 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
4207 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4218 /** The name of the lock file in the DB environment */
4219 #define LOCKNAME "/lock.mdb"
4220 /** The name of the data file in the DB environment */
4221 #define DATANAME "/data.mdb"
4222 /** The suffix of the lock file when no subdir is used */
4223 #define LOCKSUFF "-lock"
4224 /** Only a subset of the @ref mdb_env flags can be changed
4225 * at runtime. Changing other flags requires closing the
4226 * environment and re-opening it with the new flags.
4228 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
4229 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY|MDB_WRITEMAP| \
4230 MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
4232 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
4233 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
4237 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
4239 int oflags, rc, len, excl = -1;
4240 char *lpath, *dpath;
4242 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
4246 if (flags & MDB_NOSUBDIR) {
4247 rc = len + sizeof(LOCKSUFF) + len + 1;
4249 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
4254 if (flags & MDB_NOSUBDIR) {
4255 dpath = lpath + len + sizeof(LOCKSUFF);
4256 sprintf(lpath, "%s" LOCKSUFF, path);
4257 strcpy(dpath, path);
4259 dpath = lpath + len + sizeof(LOCKNAME);
4260 sprintf(lpath, "%s" LOCKNAME, path);
4261 sprintf(dpath, "%s" DATANAME, path);
4265 flags |= env->me_flags;
4266 if (flags & MDB_RDONLY) {
4267 /* silently ignore WRITEMAP when we're only getting read access */
4268 flags &= ~MDB_WRITEMAP;
4270 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
4271 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
4274 env->me_flags = flags |= MDB_ENV_ACTIVE;
4278 env->me_path = strdup(path);
4279 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
4280 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
4281 if (!(env->me_dbxs && env->me_path && env->me_dbflags)) {
4286 /* For RDONLY, get lockfile after we know datafile exists */
4287 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
4288 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4294 if (F_ISSET(flags, MDB_RDONLY)) {
4295 oflags = GENERIC_READ;
4296 len = OPEN_EXISTING;
4298 oflags = GENERIC_READ|GENERIC_WRITE;
4301 mode = FILE_ATTRIBUTE_NORMAL;
4302 env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
4303 NULL, len, mode, NULL);
4305 if (F_ISSET(flags, MDB_RDONLY))
4308 oflags = O_RDWR | O_CREAT;
4310 env->me_fd = open(dpath, oflags, mode);
4312 if (env->me_fd == INVALID_HANDLE_VALUE) {
4317 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
4318 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4323 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
4324 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
4325 env->me_mfd = env->me_fd;
4327 /* Synchronous fd for meta writes. Needed even with
4328 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
4331 len = OPEN_EXISTING;
4332 env->me_mfd = CreateFile(dpath, oflags,
4333 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
4334 mode | FILE_FLAG_WRITE_THROUGH, NULL);
4337 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
4339 if (env->me_mfd == INVALID_HANDLE_VALUE) {
4344 DPRINTF(("opened dbenv %p", (void *) env));
4346 rc = mdb_env_share_locks(env, &excl);
4350 if (!((flags & MDB_RDONLY) ||
4351 (env->me_pbuf = calloc(1, env->me_psize))))
4357 mdb_env_close0(env, excl);
4363 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
4365 mdb_env_close0(MDB_env *env, int excl)
4369 if (!(env->me_flags & MDB_ENV_ACTIVE))
4372 /* Doing this here since me_dbxs may not exist during mdb_env_close */
4373 for (i = env->me_maxdbs; --i > MAIN_DBI; )
4374 free(env->me_dbxs[i].md_name.mv_data);
4377 free(env->me_dbflags);
4380 free(env->me_dirty_list);
4381 mdb_midl_free(env->me_free_pgs);
4383 if (env->me_flags & MDB_ENV_TXKEY) {
4384 pthread_key_delete(env->me_txkey);
4386 /* Delete our key from the global list */
4387 for (i=0; i<mdb_tls_nkeys; i++)
4388 if (mdb_tls_keys[i] == env->me_txkey) {
4389 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
4397 munmap(env->me_map, env->me_mapsize);
4399 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
4400 (void) close(env->me_mfd);
4401 if (env->me_fd != INVALID_HANDLE_VALUE)
4402 (void) close(env->me_fd);
4404 MDB_PID_T pid = env->me_pid;
4405 /* Clearing readers is done in this function because
4406 * me_txkey with its destructor must be disabled first.
4408 for (i = env->me_numreaders; --i >= 0; )
4409 if (env->me_txns->mti_readers[i].mr_pid == pid)
4410 env->me_txns->mti_readers[i].mr_pid = 0;
4412 if (env->me_rmutex) {
4413 CloseHandle(env->me_rmutex);
4414 if (env->me_wmutex) CloseHandle(env->me_wmutex);
4416 /* Windows automatically destroys the mutexes when
4417 * the last handle closes.
4419 #elif defined(MDB_USE_POSIX_SEM)
4420 if (env->me_rmutex != SEM_FAILED) {
4421 sem_close(env->me_rmutex);
4422 if (env->me_wmutex != SEM_FAILED)
4423 sem_close(env->me_wmutex);
4424 /* If we have the filelock: If we are the
4425 * only remaining user, clean up semaphores.
4428 mdb_env_excl_lock(env, &excl);
4430 sem_unlink(env->me_txns->mti_rmname);
4431 sem_unlink(env->me_txns->mti_wmname);
4435 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
4437 if (env->me_lfd != INVALID_HANDLE_VALUE) {
4440 /* Unlock the lockfile. Windows would have unlocked it
4441 * after closing anyway, but not necessarily at once.
4443 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4446 (void) close(env->me_lfd);
4449 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
4454 mdb_env_close(MDB_env *env)
4461 VGMEMP_DESTROY(env);
4462 while ((dp = env->me_dpages) != NULL) {
4463 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
4464 env->me_dpages = dp->mp_next;
4468 mdb_env_close0(env, 0);
4472 /** Compare two items pointing at aligned size_t's */
4474 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
4476 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
4477 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
4480 /** Compare two items pointing at aligned unsigned int's */
4482 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
4484 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
4485 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
4488 /** Compare two items pointing at unsigned ints of unknown alignment.
4489 * Nodes and keys are guaranteed to be 2-byte aligned.
4492 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
4494 #if BYTE_ORDER == LITTLE_ENDIAN
4495 unsigned short *u, *c;
4498 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4499 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
4502 } while(!x && u > (unsigned short *)a->mv_data);
4505 unsigned short *u, *c, *end;
4508 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4509 u = (unsigned short *)a->mv_data;
4510 c = (unsigned short *)b->mv_data;
4513 } while(!x && u < end);
4518 /** Compare two items pointing at size_t's of unknown alignment. */
4519 #ifdef MISALIGNED_OK
4520 # define mdb_cmp_clong mdb_cmp_long
4522 # define mdb_cmp_clong mdb_cmp_cint
4525 /** Compare two items lexically */
4527 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
4534 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4540 diff = memcmp(a->mv_data, b->mv_data, len);
4541 return diff ? diff : len_diff<0 ? -1 : len_diff;
4544 /** Compare two items in reverse byte order */
4546 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
4548 const unsigned char *p1, *p2, *p1_lim;
4552 p1_lim = (const unsigned char *)a->mv_data;
4553 p1 = (const unsigned char *)a->mv_data + a->mv_size;
4554 p2 = (const unsigned char *)b->mv_data + b->mv_size;
4556 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4562 while (p1 > p1_lim) {
4563 diff = *--p1 - *--p2;
4567 return len_diff<0 ? -1 : len_diff;
4570 /** Search for key within a page, using binary search.
4571 * Returns the smallest entry larger or equal to the key.
4572 * If exactp is non-null, stores whether the found entry was an exact match
4573 * in *exactp (1 or 0).
4574 * Updates the cursor index with the index of the found entry.
4575 * If no entry larger or equal to the key is found, returns NULL.
4578 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
4580 unsigned int i = 0, nkeys;
4583 MDB_page *mp = mc->mc_pg[mc->mc_top];
4584 MDB_node *node = NULL;
4589 nkeys = NUMKEYS(mp);
4591 DPRINTF(("searching %u keys in %s %spage %"Z"u",
4592 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
4595 low = IS_LEAF(mp) ? 0 : 1;
4597 cmp = mc->mc_dbx->md_cmp;
4599 /* Branch pages have no data, so if using integer keys,
4600 * alignment is guaranteed. Use faster mdb_cmp_int.
4602 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
4603 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
4610 nodekey.mv_size = mc->mc_db->md_pad;
4611 node = NODEPTR(mp, 0); /* fake */
4612 while (low <= high) {
4613 i = (low + high) >> 1;
4614 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
4615 rc = cmp(key, &nodekey);
4616 DPRINTF(("found leaf index %u [%s], rc = %i",
4617 i, DKEY(&nodekey), rc));
4626 while (low <= high) {
4627 i = (low + high) >> 1;
4629 node = NODEPTR(mp, i);
4630 nodekey.mv_size = NODEKSZ(node);
4631 nodekey.mv_data = NODEKEY(node);
4633 rc = cmp(key, &nodekey);
4636 DPRINTF(("found leaf index %u [%s], rc = %i",
4637 i, DKEY(&nodekey), rc));
4639 DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
4640 i, DKEY(&nodekey), NODEPGNO(node), rc));
4651 if (rc > 0) { /* Found entry is less than the key. */
4652 i++; /* Skip to get the smallest entry larger than key. */
4654 node = NODEPTR(mp, i);
4657 *exactp = (rc == 0 && nkeys > 0);
4658 /* store the key index */
4659 mc->mc_ki[mc->mc_top] = i;
4661 /* There is no entry larger or equal to the key. */
4664 /* nodeptr is fake for LEAF2 */
4670 mdb_cursor_adjust(MDB_cursor *mc, func)
4674 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4675 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
4682 /** Pop a page off the top of the cursor's stack. */
4684 mdb_cursor_pop(MDB_cursor *mc)
4688 MDB_page *top = mc->mc_pg[mc->mc_top];
4694 DPRINTF(("popped page %"Z"u off db %d cursor %p", top->mp_pgno,
4695 DDBI(mc), (void *) mc));
4699 /** Push a page onto the top of the cursor's stack. */
4701 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
4703 DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
4704 DDBI(mc), (void *) mc));
4706 if (mc->mc_snum >= CURSOR_STACK) {
4707 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4708 return MDB_CURSOR_FULL;
4711 mc->mc_top = mc->mc_snum++;
4712 mc->mc_pg[mc->mc_top] = mp;
4713 mc->mc_ki[mc->mc_top] = 0;
4718 /** Find the address of the page corresponding to a given page number.
4719 * @param[in] txn the transaction for this access.
4720 * @param[in] pgno the page number for the page to retrieve.
4721 * @param[out] ret address of a pointer where the page's address will be stored.
4722 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
4723 * @return 0 on success, non-zero on failure.
4726 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
4728 MDB_env *env = txn->mt_env;
4732 if (!((txn->mt_flags & MDB_TXN_RDONLY) | (env->me_flags & MDB_WRITEMAP))) {
4736 MDB_ID2L dl = tx2->mt_u.dirty_list;
4738 /* Spilled pages were dirtied in this txn and flushed
4739 * because the dirty list got full. Bring this page
4740 * back in from the map (but don't unspill it here,
4741 * leave that unless page_touch happens again).
4743 if (tx2->mt_spill_pgs) {
4744 MDB_ID pn = pgno << 1;
4745 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
4746 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
4747 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
4752 unsigned x = mdb_mid2l_search(dl, pgno);
4753 if (x <= dl[0].mid && dl[x].mid == pgno) {
4759 } while ((tx2 = tx2->mt_parent) != NULL);
4762 if (pgno < txn->mt_next_pgno) {
4764 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
4766 DPRINTF(("page %"Z"u not found", pgno));
4767 txn->mt_flags |= MDB_TXN_ERROR;
4768 return MDB_PAGE_NOTFOUND;
4778 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
4779 * The cursor is at the root page, set up the rest of it.
4782 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
4784 MDB_page *mp = mc->mc_pg[mc->mc_top];
4788 while (IS_BRANCH(mp)) {
4792 DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
4793 mdb_cassert(mc, NUMKEYS(mp) > 1);
4794 DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
4796 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
4798 if (flags & MDB_PS_LAST)
4799 i = NUMKEYS(mp) - 1;
4802 node = mdb_node_search(mc, key, &exact);
4804 i = NUMKEYS(mp) - 1;
4806 i = mc->mc_ki[mc->mc_top];
4808 mdb_cassert(mc, i > 0);
4812 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
4815 mdb_cassert(mc, i < NUMKEYS(mp));
4816 node = NODEPTR(mp, i);
4818 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4821 mc->mc_ki[mc->mc_top] = i;
4822 if ((rc = mdb_cursor_push(mc, mp)))
4825 if (flags & MDB_PS_MODIFY) {
4826 if ((rc = mdb_page_touch(mc)) != 0)
4828 mp = mc->mc_pg[mc->mc_top];
4833 DPRINTF(("internal error, index points to a %02X page!?",
4835 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4836 return MDB_CORRUPTED;
4839 DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
4840 key ? DKEY(key) : "null"));
4841 mc->mc_flags |= C_INITIALIZED;
4842 mc->mc_flags &= ~C_EOF;
4847 /** Search for the lowest key under the current branch page.
4848 * This just bypasses a NUMKEYS check in the current page
4849 * before calling mdb_page_search_root(), because the callers
4850 * are all in situations where the current page is known to
4854 mdb_page_search_lowest(MDB_cursor *mc)
4856 MDB_page *mp = mc->mc_pg[mc->mc_top];
4857 MDB_node *node = NODEPTR(mp, 0);
4860 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4863 mc->mc_ki[mc->mc_top] = 0;
4864 if ((rc = mdb_cursor_push(mc, mp)))
4866 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
4869 /** Search for the page a given key should be in.
4870 * Push it and its parent pages on the cursor stack.
4871 * @param[in,out] mc the cursor for this operation.
4872 * @param[in] key the key to search for, or NULL for first/last page.
4873 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
4874 * are touched (updated with new page numbers).
4875 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
4876 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
4877 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
4878 * @return 0 on success, non-zero on failure.
4881 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
4886 /* Make sure the txn is still viable, then find the root from
4887 * the txn's db table and set it as the root of the cursor's stack.
4889 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
4890 DPUTS("transaction has failed, must abort");
4893 /* Make sure we're using an up-to-date root */
4894 if (*mc->mc_dbflag & DB_STALE) {
4896 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
4897 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
4904 MDB_node *leaf = mdb_node_search(&mc2,
4905 &mc->mc_dbx->md_name, &exact);
4907 return MDB_NOTFOUND;
4908 rc = mdb_node_read(mc->mc_txn, leaf, &data);
4911 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
4913 /* The txn may not know this DBI, or another process may
4914 * have dropped and recreated the DB with other flags.
4916 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
4917 return MDB_INCOMPATIBLE;
4918 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
4920 *mc->mc_dbflag &= ~DB_STALE;
4922 root = mc->mc_db->md_root;
4924 if (root == P_INVALID) { /* Tree is empty. */
4925 DPUTS("tree is empty");
4926 return MDB_NOTFOUND;
4930 mdb_cassert(mc, root > 1);
4931 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
4932 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0], NULL)) != 0)
4938 DPRINTF(("db %d root page %"Z"u has flags 0x%X",
4939 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
4941 if (flags & MDB_PS_MODIFY) {
4942 if ((rc = mdb_page_touch(mc)))
4946 if (flags & MDB_PS_ROOTONLY)
4949 return mdb_page_search_root(mc, key, flags);
4953 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
4955 MDB_txn *txn = mc->mc_txn;
4956 pgno_t pg = mp->mp_pgno;
4957 unsigned x = 0, ovpages = mp->mp_pages;
4958 MDB_env *env = txn->mt_env;
4959 MDB_IDL sl = txn->mt_spill_pgs;
4960 MDB_ID pn = pg << 1;
4963 DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
4964 /* If the page is dirty or on the spill list we just acquired it,
4965 * so we should give it back to our current free list, if any.
4966 * Otherwise put it onto the list of pages we freed in this txn.
4968 * Won't create me_pghead: me_pglast must be inited along with it.
4969 * Unsupported in nested txns: They would need to hide the page
4970 * range in ancestor txns' dirty and spilled lists.
4972 if (env->me_pghead &&
4974 ((mp->mp_flags & P_DIRTY) ||
4975 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
4979 MDB_ID2 *dl, ix, iy;
4980 rc = mdb_midl_need(&env->me_pghead, ovpages);
4983 if (!(mp->mp_flags & P_DIRTY)) {
4984 /* This page is no longer spilled */
4991 /* Remove from dirty list */
4992 dl = txn->mt_u.dirty_list;
4994 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
5000 mdb_cassert(mc, x > 1);
5002 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
5003 txn->mt_flags |= MDB_TXN_ERROR;
5004 return MDB_CORRUPTED;
5007 if (!(env->me_flags & MDB_WRITEMAP))
5008 mdb_dpage_free(env, mp);
5010 /* Insert in me_pghead */
5011 mop = env->me_pghead;
5012 j = mop[0] + ovpages;
5013 for (i = mop[0]; i && mop[i] < pg; i--)
5019 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
5023 mc->mc_db->md_overflow_pages -= ovpages;
5027 /** Return the data associated with a given node.
5028 * @param[in] txn The transaction for this operation.
5029 * @param[in] leaf The node being read.
5030 * @param[out] data Updated to point to the node's data.
5031 * @return 0 on success, non-zero on failure.
5034 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
5036 MDB_page *omp; /* overflow page */
5040 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5041 data->mv_size = NODEDSZ(leaf);
5042 data->mv_data = NODEDATA(leaf);
5046 /* Read overflow data.
5048 data->mv_size = NODEDSZ(leaf);
5049 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
5050 if ((rc = mdb_page_get(txn, pgno, &omp, NULL)) != 0) {
5051 DPRINTF(("read overflow page %"Z"u failed", pgno));
5054 data->mv_data = METADATA(omp);
5060 mdb_get(MDB_txn *txn, MDB_dbi dbi,
5061 MDB_val *key, MDB_val *data)
5068 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
5070 if (!key || !data || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
5073 if (txn->mt_flags & MDB_TXN_ERROR)
5076 mdb_cursor_init(&mc, txn, dbi, &mx);
5077 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
5080 /** Find a sibling for a page.
5081 * Replaces the page at the top of the cursor's stack with the
5082 * specified sibling, if one exists.
5083 * @param[in] mc The cursor for this operation.
5084 * @param[in] move_right Non-zero if the right sibling is requested,
5085 * otherwise the left sibling.
5086 * @return 0 on success, non-zero on failure.
5089 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
5095 if (mc->mc_snum < 2) {
5096 return MDB_NOTFOUND; /* root has no siblings */
5100 DPRINTF(("parent page is page %"Z"u, index %u",
5101 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
5103 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
5104 : (mc->mc_ki[mc->mc_top] == 0)) {
5105 DPRINTF(("no more keys left, moving to %s sibling",
5106 move_right ? "right" : "left"));
5107 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
5108 /* undo cursor_pop before returning */
5115 mc->mc_ki[mc->mc_top]++;
5117 mc->mc_ki[mc->mc_top]--;
5118 DPRINTF(("just moving to %s index key %u",
5119 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
5121 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
5123 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5124 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL)) != 0) {
5125 /* mc will be inconsistent if caller does mc_snum++ as above */
5126 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
5130 mdb_cursor_push(mc, mp);
5132 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
5137 /** Move the cursor to the next data item. */
5139 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5145 if (mc->mc_flags & C_EOF) {
5146 return MDB_NOTFOUND;
5149 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5151 mp = mc->mc_pg[mc->mc_top];
5153 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5154 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5155 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5156 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
5157 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
5158 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
5159 if (rc == MDB_SUCCESS)
5160 MDB_GET_KEY(leaf, key);
5165 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5166 if (op == MDB_NEXT_DUP)
5167 return MDB_NOTFOUND;
5171 DPRINTF(("cursor_next: top page is %"Z"u in cursor %p",
5172 mdb_dbg_pgno(mp), (void *) mc));
5173 if (mc->mc_flags & C_DEL)
5176 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
5177 DPUTS("=====> move to next sibling page");
5178 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5179 mc->mc_flags |= C_EOF;
5182 mp = mc->mc_pg[mc->mc_top];
5183 DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5185 mc->mc_ki[mc->mc_top]++;
5188 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5189 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5192 key->mv_size = mc->mc_db->md_pad;
5193 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5197 mdb_cassert(mc, IS_LEAF(mp));
5198 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5200 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5201 mdb_xcursor_init1(mc, leaf);
5204 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5207 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5208 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5209 if (rc != MDB_SUCCESS)
5214 MDB_GET_KEY(leaf, key);
5218 /** Move the cursor to the previous data item. */
5220 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5226 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5228 mp = mc->mc_pg[mc->mc_top];
5230 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5231 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5232 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5233 if (op == MDB_PREV || op == MDB_PREV_DUP) {
5234 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
5235 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
5236 if (rc == MDB_SUCCESS)
5237 MDB_GET_KEY(leaf, key);
5241 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5242 if (op == MDB_PREV_DUP)
5243 return MDB_NOTFOUND;
5248 DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p",
5249 mdb_dbg_pgno(mp), (void *) mc));
5251 if (mc->mc_ki[mc->mc_top] == 0) {
5252 DPUTS("=====> move to prev sibling page");
5253 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
5256 mp = mc->mc_pg[mc->mc_top];
5257 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
5258 DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5260 mc->mc_ki[mc->mc_top]--;
5262 mc->mc_flags &= ~C_EOF;
5264 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5265 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5268 key->mv_size = mc->mc_db->md_pad;
5269 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5273 mdb_cassert(mc, IS_LEAF(mp));
5274 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5276 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5277 mdb_xcursor_init1(mc, leaf);
5280 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5283 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5284 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5285 if (rc != MDB_SUCCESS)
5290 MDB_GET_KEY(leaf, key);
5294 /** Set the cursor on a specific data item. */
5296 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5297 MDB_cursor_op op, int *exactp)
5301 MDB_node *leaf = NULL;
5304 if (key->mv_size == 0)
5305 return MDB_BAD_VALSIZE;
5308 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5310 /* See if we're already on the right page */
5311 if (mc->mc_flags & C_INITIALIZED) {
5314 mp = mc->mc_pg[mc->mc_top];
5316 mc->mc_ki[mc->mc_top] = 0;
5317 return MDB_NOTFOUND;
5319 if (mp->mp_flags & P_LEAF2) {
5320 nodekey.mv_size = mc->mc_db->md_pad;
5321 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
5323 leaf = NODEPTR(mp, 0);
5324 MDB_GET_KEY2(leaf, nodekey);
5326 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5328 /* Probably happens rarely, but first node on the page
5329 * was the one we wanted.
5331 mc->mc_ki[mc->mc_top] = 0;
5338 unsigned int nkeys = NUMKEYS(mp);
5340 if (mp->mp_flags & P_LEAF2) {
5341 nodekey.mv_data = LEAF2KEY(mp,
5342 nkeys-1, nodekey.mv_size);
5344 leaf = NODEPTR(mp, nkeys-1);
5345 MDB_GET_KEY2(leaf, nodekey);
5347 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5349 /* last node was the one we wanted */
5350 mc->mc_ki[mc->mc_top] = nkeys-1;
5356 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
5357 /* This is definitely the right page, skip search_page */
5358 if (mp->mp_flags & P_LEAF2) {
5359 nodekey.mv_data = LEAF2KEY(mp,
5360 mc->mc_ki[mc->mc_top], nodekey.mv_size);
5362 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5363 MDB_GET_KEY2(leaf, nodekey);
5365 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5367 /* current node was the one we wanted */
5377 /* If any parents have right-sibs, search.
5378 * Otherwise, there's nothing further.
5380 for (i=0; i<mc->mc_top; i++)
5382 NUMKEYS(mc->mc_pg[i])-1)
5384 if (i == mc->mc_top) {
5385 /* There are no other pages */
5386 mc->mc_ki[mc->mc_top] = nkeys;
5387 return MDB_NOTFOUND;
5391 /* There are no other pages */
5392 mc->mc_ki[mc->mc_top] = 0;
5393 if (op == MDB_SET_RANGE && !exactp) {
5397 return MDB_NOTFOUND;
5401 rc = mdb_page_search(mc, key, 0);
5402 if (rc != MDB_SUCCESS)
5405 mp = mc->mc_pg[mc->mc_top];
5406 mdb_cassert(mc, IS_LEAF(mp));
5409 leaf = mdb_node_search(mc, key, exactp);
5410 if (exactp != NULL && !*exactp) {
5411 /* MDB_SET specified and not an exact match. */
5412 return MDB_NOTFOUND;
5416 DPUTS("===> inexact leaf not found, goto sibling");
5417 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
5418 return rc; /* no entries matched */
5419 mp = mc->mc_pg[mc->mc_top];
5420 mdb_cassert(mc, IS_LEAF(mp));
5421 leaf = NODEPTR(mp, 0);
5425 mc->mc_flags |= C_INITIALIZED;
5426 mc->mc_flags &= ~C_EOF;
5429 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
5430 key->mv_size = mc->mc_db->md_pad;
5431 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5436 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5437 mdb_xcursor_init1(mc, leaf);
5440 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5441 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
5442 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5445 if (op == MDB_GET_BOTH) {
5451 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
5452 if (rc != MDB_SUCCESS)
5455 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
5457 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
5459 rc = mc->mc_dbx->md_dcmp(data, &d2);
5461 if (op == MDB_GET_BOTH || rc > 0)
5462 return MDB_NOTFOUND;
5469 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5470 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5475 /* The key already matches in all other cases */
5476 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
5477 MDB_GET_KEY(leaf, key);
5478 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
5483 /** Move the cursor to the first item in the database. */
5485 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5491 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5493 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5494 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
5495 if (rc != MDB_SUCCESS)
5498 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
5500 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
5501 mc->mc_flags |= C_INITIALIZED;
5502 mc->mc_flags &= ~C_EOF;
5504 mc->mc_ki[mc->mc_top] = 0;
5506 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5507 key->mv_size = mc->mc_db->md_pad;
5508 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
5513 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5514 mdb_xcursor_init1(mc, leaf);
5515 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5519 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5523 MDB_GET_KEY(leaf, key);
5527 /** Move the cursor to the last item in the database. */
5529 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5535 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5537 if (!(mc->mc_flags & C_EOF)) {
5539 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5540 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
5541 if (rc != MDB_SUCCESS)
5544 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
5547 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
5548 mc->mc_flags |= C_INITIALIZED|C_EOF;
5549 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5551 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5552 key->mv_size = mc->mc_db->md_pad;
5553 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
5558 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5559 mdb_xcursor_init1(mc, leaf);
5560 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5564 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5569 MDB_GET_KEY(leaf, key);
5574 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5579 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
5584 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
5588 case MDB_GET_CURRENT:
5589 if (!(mc->mc_flags & C_INITIALIZED)) {
5592 MDB_page *mp = mc->mc_pg[mc->mc_top];
5593 int nkeys = NUMKEYS(mp);
5594 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
5595 mc->mc_ki[mc->mc_top] = nkeys;
5601 key->mv_size = mc->mc_db->md_pad;
5602 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5604 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5605 MDB_GET_KEY(leaf, key);
5607 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5608 if (mc->mc_flags & C_DEL)
5609 mdb_xcursor_init1(mc, leaf);
5610 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
5612 rc = mdb_node_read(mc->mc_txn, leaf, data);
5619 case MDB_GET_BOTH_RANGE:
5624 if (mc->mc_xcursor == NULL) {
5625 rc = MDB_INCOMPATIBLE;
5635 rc = mdb_cursor_set(mc, key, data, op,
5636 op == MDB_SET_RANGE ? NULL : &exact);
5639 case MDB_GET_MULTIPLE:
5640 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5644 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5645 rc = MDB_INCOMPATIBLE;
5649 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
5650 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
5653 case MDB_NEXT_MULTIPLE:
5658 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5659 rc = MDB_INCOMPATIBLE;
5662 if (!(mc->mc_flags & C_INITIALIZED))
5663 rc = mdb_cursor_first(mc, key, data);
5665 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
5666 if (rc == MDB_SUCCESS) {
5667 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
5670 mx = &mc->mc_xcursor->mx_cursor;
5671 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
5673 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
5674 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
5682 case MDB_NEXT_NODUP:
5683 if (!(mc->mc_flags & C_INITIALIZED))
5684 rc = mdb_cursor_first(mc, key, data);
5686 rc = mdb_cursor_next(mc, key, data, op);
5690 case MDB_PREV_NODUP:
5691 if (!(mc->mc_flags & C_INITIALIZED)) {
5692 rc = mdb_cursor_last(mc, key, data);
5695 mc->mc_flags |= C_INITIALIZED;
5696 mc->mc_ki[mc->mc_top]++;
5698 rc = mdb_cursor_prev(mc, key, data, op);
5701 rc = mdb_cursor_first(mc, key, data);
5704 mfunc = mdb_cursor_first;
5706 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5710 if (mc->mc_xcursor == NULL) {
5711 rc = MDB_INCOMPATIBLE;
5714 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
5718 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
5721 rc = mdb_cursor_last(mc, key, data);
5724 mfunc = mdb_cursor_last;
5727 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
5732 if (mc->mc_flags & C_DEL)
5733 mc->mc_flags ^= C_DEL;
5738 /** Touch all the pages in the cursor stack. Set mc_top.
5739 * Makes sure all the pages are writable, before attempting a write operation.
5740 * @param[in] mc The cursor to operate on.
5743 mdb_cursor_touch(MDB_cursor *mc)
5745 int rc = MDB_SUCCESS;
5747 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
5750 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
5751 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
5754 *mc->mc_dbflag |= DB_DIRTY;
5759 rc = mdb_page_touch(mc);
5760 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
5761 mc->mc_top = mc->mc_snum-1;
5766 /** Do not spill pages to disk if txn is getting full, may fail instead */
5767 #define MDB_NOSPILL 0x8000
5770 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5773 enum { MDB_NO_ROOT = MDB_LAST_ERRCODE+10 }; /* internal code */
5775 MDB_node *leaf = NULL;
5778 MDB_val xdata, *rdata, dkey, olddata;
5780 int do_sub = 0, insert_key, insert_data;
5781 unsigned int mcount = 0, dcount = 0, nospill;
5784 unsigned int nflags;
5787 if (mc == NULL || key == NULL)
5790 env = mc->mc_txn->mt_env;
5792 /* Check this first so counter will always be zero on any
5795 if (flags & MDB_MULTIPLE) {
5796 dcount = data[1].mv_size;
5797 data[1].mv_size = 0;
5798 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
5799 return MDB_INCOMPATIBLE;
5802 nospill = flags & MDB_NOSPILL;
5803 flags &= ~MDB_NOSPILL;
5805 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
5806 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
5808 if (key->mv_size-1 >= ENV_MAXKEY(env))
5809 return MDB_BAD_VALSIZE;
5811 #if SIZE_MAX > MAXDATASIZE
5812 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
5813 return MDB_BAD_VALSIZE;
5815 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
5816 return MDB_BAD_VALSIZE;
5819 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
5820 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
5824 if (flags == MDB_CURRENT) {
5825 if (!(mc->mc_flags & C_INITIALIZED))
5828 } else if (mc->mc_db->md_root == P_INVALID) {
5829 /* new database, cursor has nothing to point to */
5832 mc->mc_flags &= ~C_INITIALIZED;
5837 if (flags & MDB_APPEND) {
5839 rc = mdb_cursor_last(mc, &k2, &d2);
5841 rc = mc->mc_dbx->md_cmp(key, &k2);
5844 mc->mc_ki[mc->mc_top]++;
5846 /* new key is <= last key */
5851 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
5853 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
5854 DPRINTF(("duplicate key [%s]", DKEY(key)));
5856 return MDB_KEYEXIST;
5858 if (rc && rc != MDB_NOTFOUND)
5862 if (mc->mc_flags & C_DEL)
5863 mc->mc_flags ^= C_DEL;
5865 /* Cursor is positioned, check for room in the dirty list */
5867 if (flags & MDB_MULTIPLE) {
5869 xdata.mv_size = data->mv_size * dcount;
5873 if ((rc2 = mdb_page_spill(mc, key, rdata)))
5877 if (rc == MDB_NO_ROOT) {
5879 /* new database, write a root leaf page */
5880 DPUTS("allocating new root leaf page");
5881 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
5884 mdb_cursor_push(mc, np);
5885 mc->mc_db->md_root = np->mp_pgno;
5886 mc->mc_db->md_depth++;
5887 *mc->mc_dbflag |= DB_DIRTY;
5888 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
5890 np->mp_flags |= P_LEAF2;
5891 mc->mc_flags |= C_INITIALIZED;
5893 /* make sure all cursor pages are writable */
5894 rc2 = mdb_cursor_touch(mc);
5899 insert_key = insert_data = rc;
5901 /* The key does not exist */
5902 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
5903 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
5904 LEAFSIZE(key, data) > env->me_nodemax)
5906 /* Too big for a node, insert in sub-DB */
5907 fp_flags = P_LEAF|P_DIRTY;
5909 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
5910 fp->mp_lower = fp->mp_upper = olddata.mv_size = PAGEHDRSZ;
5914 /* there's only a key anyway, so this is a no-op */
5915 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5917 unsigned int ksize = mc->mc_db->md_pad;
5918 if (key->mv_size != ksize)
5919 return MDB_BAD_VALSIZE;
5920 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
5921 memcpy(ptr, key->mv_data, ksize);
5926 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5927 olddata.mv_size = NODEDSZ(leaf);
5928 olddata.mv_data = NODEDATA(leaf);
5931 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
5932 /* Prepare (sub-)page/sub-DB to accept the new item,
5933 * if needed. fp: old sub-page or a header faking
5934 * it. mp: new (sub-)page. offset: growth in page
5935 * size. xdata: node data with new page or DB.
5937 unsigned i, offset = 0;
5938 mp = fp = xdata.mv_data = env->me_pbuf;
5939 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
5941 /* Was a single item before, must convert now */
5942 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5943 /* Just overwrite the current item */
5944 if (flags == MDB_CURRENT)
5947 #if UINT_MAX < SIZE_MAX
5948 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
5949 mc->mc_dbx->md_dcmp = mdb_cmp_clong;
5951 /* does data match? */
5952 if (!mc->mc_dbx->md_dcmp(data, &olddata)) {
5953 if (flags & MDB_NODUPDATA)
5954 return MDB_KEYEXIST;
5959 /* Back up original data item */
5960 dkey.mv_size = olddata.mv_size;
5961 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
5963 /* Make sub-page header for the dup items, with dummy body */
5964 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
5965 fp->mp_lower = PAGEHDRSZ;
5966 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
5967 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5968 fp->mp_flags |= P_LEAF2;
5969 fp->mp_pad = data->mv_size;
5970 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
5972 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
5973 (dkey.mv_size & 1) + (data->mv_size & 1);
5975 fp->mp_upper = xdata.mv_size;
5976 olddata.mv_size = fp->mp_upper; /* pretend olddata is fp */
5977 } else if (leaf->mn_flags & F_SUBDATA) {
5978 /* Data is on sub-DB, just store it */
5979 flags |= F_DUPDATA|F_SUBDATA;
5982 /* Data is on sub-page */
5983 fp = olddata.mv_data;
5986 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5987 offset = EVEN(NODESIZE + sizeof(indx_t) +
5991 offset = fp->mp_pad;
5992 if (SIZELEFT(fp) < offset) {
5993 offset *= 4; /* space for 4 more */
5996 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
5998 fp->mp_flags |= P_DIRTY;
5999 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
6000 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
6004 xdata.mv_size = olddata.mv_size + offset;
6007 fp_flags = fp->mp_flags;
6008 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
6009 /* Too big for a sub-page, convert to sub-DB */
6010 fp_flags &= ~P_SUBP;
6012 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6013 fp_flags |= P_LEAF2;
6014 dummy.md_pad = fp->mp_pad;
6015 dummy.md_flags = MDB_DUPFIXED;
6016 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6017 dummy.md_flags |= MDB_INTEGERKEY;
6023 dummy.md_branch_pages = 0;
6024 dummy.md_leaf_pages = 1;
6025 dummy.md_overflow_pages = 0;
6026 dummy.md_entries = NUMKEYS(fp);
6027 xdata.mv_size = sizeof(MDB_db);
6028 xdata.mv_data = &dummy;
6029 if ((rc = mdb_page_alloc(mc, 1, &mp)))
6031 offset = env->me_psize - olddata.mv_size;
6032 flags |= F_DUPDATA|F_SUBDATA;
6033 dummy.md_root = mp->mp_pgno;
6036 mp->mp_flags = fp_flags | P_DIRTY;
6037 mp->mp_pad = fp->mp_pad;
6038 mp->mp_lower = fp->mp_lower;
6039 mp->mp_upper = fp->mp_upper + offset;
6040 if (fp_flags & P_LEAF2) {
6041 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
6043 memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper,
6044 olddata.mv_size - fp->mp_upper);
6045 for (i=0; i<NUMKEYS(fp); i++)
6046 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
6054 mdb_node_del(mc, 0);
6058 /* overflow page overwrites need special handling */
6059 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6062 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
6064 memcpy(&pg, olddata.mv_data, sizeof(pg));
6065 if ((rc2 = mdb_page_get(mc->mc_txn, pg, &omp, &level)) != 0)
6067 ovpages = omp->mp_pages;
6069 /* Is the ov page large enough? */
6070 if (ovpages >= dpages) {
6071 if (!(omp->mp_flags & P_DIRTY) &&
6072 (level || (env->me_flags & MDB_WRITEMAP)))
6074 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
6077 level = 0; /* dirty in this txn or clean */
6080 if (omp->mp_flags & P_DIRTY) {
6081 /* yes, overwrite it. Note in this case we don't
6082 * bother to try shrinking the page if the new data
6083 * is smaller than the overflow threshold.
6086 /* It is writable only in a parent txn */
6087 size_t sz = (size_t) env->me_psize * ovpages, off;
6088 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
6094 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
6095 mdb_cassert(mc, rc2 == 0);
6096 if (!(flags & MDB_RESERVE)) {
6097 /* Copy end of page, adjusting alignment so
6098 * compiler may copy words instead of bytes.
6100 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
6101 memcpy((size_t *)((char *)np + off),
6102 (size_t *)((char *)omp + off), sz - off);
6105 memcpy(np, omp, sz); /* Copy beginning of page */
6108 SETDSZ(leaf, data->mv_size);
6109 if (F_ISSET(flags, MDB_RESERVE))
6110 data->mv_data = METADATA(omp);
6112 memcpy(METADATA(omp), data->mv_data, data->mv_size);
6116 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
6118 } else if (data->mv_size == olddata.mv_size) {
6119 /* same size, just replace it. Note that we could
6120 * also reuse this node if the new data is smaller,
6121 * but instead we opt to shrink the node in that case.
6123 if (F_ISSET(flags, MDB_RESERVE))
6124 data->mv_data = olddata.mv_data;
6125 else if (!(mc->mc_flags & C_SUB))
6126 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
6128 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
6131 mdb_node_del(mc, 0);
6137 nflags = flags & NODE_ADD_FLAGS;
6138 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
6139 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
6140 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
6141 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
6143 nflags |= MDB_SPLIT_REPLACE;
6144 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
6146 /* There is room already in this leaf page. */
6147 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
6148 if (rc == 0 && insert_key) {
6149 /* Adjust other cursors pointing to mp */
6150 MDB_cursor *m2, *m3;
6151 MDB_dbi dbi = mc->mc_dbi;
6152 unsigned i = mc->mc_top;
6153 MDB_page *mp = mc->mc_pg[i];
6155 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6156 if (mc->mc_flags & C_SUB)
6157 m3 = &m2->mc_xcursor->mx_cursor;
6160 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
6161 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
6168 if (rc == MDB_SUCCESS) {
6169 /* Now store the actual data in the child DB. Note that we're
6170 * storing the user data in the keys field, so there are strict
6171 * size limits on dupdata. The actual data fields of the child
6172 * DB are all zero size.
6180 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6181 if (flags & MDB_CURRENT) {
6182 xflags = MDB_CURRENT|MDB_NOSPILL;
6184 mdb_xcursor_init1(mc, leaf);
6185 xflags = (flags & MDB_NODUPDATA) ?
6186 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
6188 /* converted, write the original data first */
6190 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
6194 /* Adjust other cursors pointing to mp */
6196 unsigned i = mc->mc_top;
6197 MDB_page *mp = mc->mc_pg[i];
6199 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6200 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6201 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6202 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
6203 mdb_xcursor_init1(m2, leaf);
6207 /* we've done our job */
6210 ecount = mc->mc_xcursor->mx_db.md_entries;
6211 if (flags & MDB_APPENDDUP)
6212 xflags |= MDB_APPEND;
6213 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
6214 if (flags & F_SUBDATA) {
6215 void *db = NODEDATA(leaf);
6216 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6218 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
6220 /* Increment count unless we just replaced an existing item. */
6222 mc->mc_db->md_entries++;
6224 /* Invalidate txn if we created an empty sub-DB */
6227 /* If we succeeded and the key didn't exist before,
6228 * make sure the cursor is marked valid.
6230 mc->mc_flags |= C_INITIALIZED;
6232 if (flags & MDB_MULTIPLE) {
6235 /* let caller know how many succeeded, if any */
6236 data[1].mv_size = mcount;
6237 if (mcount < dcount) {
6238 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
6239 insert_key = insert_data = 0;
6246 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
6249 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6254 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
6260 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
6261 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6263 if (!(mc->mc_flags & C_INITIALIZED))
6266 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6267 return MDB_NOTFOUND;
6269 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
6272 rc = mdb_cursor_touch(mc);
6276 mp = mc->mc_pg[mc->mc_top];
6279 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6281 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6282 if (flags & MDB_NODUPDATA) {
6283 /* mdb_cursor_del0() will subtract the final entry */
6284 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
6286 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
6287 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6289 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
6292 /* If sub-DB still has entries, we're done */
6293 if (mc->mc_xcursor->mx_db.md_entries) {
6294 if (leaf->mn_flags & F_SUBDATA) {
6295 /* update subDB info */
6296 void *db = NODEDATA(leaf);
6297 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6300 /* shrink fake page */
6301 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
6302 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6303 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6304 /* fix other sub-DB cursors pointed at this fake page */
6305 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6306 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6307 if (m2->mc_pg[mc->mc_top] == mp &&
6308 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
6309 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6312 mc->mc_db->md_entries--;
6313 mc->mc_flags |= C_DEL;
6316 /* otherwise fall thru and delete the sub-DB */
6319 if (leaf->mn_flags & F_SUBDATA) {
6320 /* add all the child DB's pages to the free list */
6321 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6327 /* add overflow pages to free list */
6328 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6332 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
6333 if ((rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL)) ||
6334 (rc = mdb_ovpage_free(mc, omp)))
6339 return mdb_cursor_del0(mc);
6342 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6346 /** Allocate and initialize new pages for a database.
6347 * @param[in] mc a cursor on the database being added to.
6348 * @param[in] flags flags defining what type of page is being allocated.
6349 * @param[in] num the number of pages to allocate. This is usually 1,
6350 * unless allocating overflow pages for a large record.
6351 * @param[out] mp Address of a page, or NULL on failure.
6352 * @return 0 on success, non-zero on failure.
6355 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
6360 if ((rc = mdb_page_alloc(mc, num, &np)))
6362 DPRINTF(("allocated new mpage %"Z"u, page size %u",
6363 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
6364 np->mp_flags = flags | P_DIRTY;
6365 np->mp_lower = PAGEHDRSZ;
6366 np->mp_upper = mc->mc_txn->mt_env->me_psize;
6369 mc->mc_db->md_branch_pages++;
6370 else if (IS_LEAF(np))
6371 mc->mc_db->md_leaf_pages++;
6372 else if (IS_OVERFLOW(np)) {
6373 mc->mc_db->md_overflow_pages += num;
6381 /** Calculate the size of a leaf node.
6382 * The size depends on the environment's page size; if a data item
6383 * is too large it will be put onto an overflow page and the node
6384 * size will only include the key and not the data. Sizes are always
6385 * rounded up to an even number of bytes, to guarantee 2-byte alignment
6386 * of the #MDB_node headers.
6387 * @param[in] env The environment handle.
6388 * @param[in] key The key for the node.
6389 * @param[in] data The data for the node.
6390 * @return The number of bytes needed to store the node.
6393 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
6397 sz = LEAFSIZE(key, data);
6398 if (sz > env->me_nodemax) {
6399 /* put on overflow page */
6400 sz -= data->mv_size - sizeof(pgno_t);
6403 return EVEN(sz + sizeof(indx_t));
6406 /** Calculate the size of a branch node.
6407 * The size should depend on the environment's page size but since
6408 * we currently don't support spilling large keys onto overflow
6409 * pages, it's simply the size of the #MDB_node header plus the
6410 * size of the key. Sizes are always rounded up to an even number
6411 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
6412 * @param[in] env The environment handle.
6413 * @param[in] key The key for the node.
6414 * @return The number of bytes needed to store the node.
6417 mdb_branch_size(MDB_env *env, MDB_val *key)
6422 if (sz > env->me_nodemax) {
6423 /* put on overflow page */
6424 /* not implemented */
6425 /* sz -= key->size - sizeof(pgno_t); */
6428 return sz + sizeof(indx_t);
6431 /** Add a node to the page pointed to by the cursor.
6432 * @param[in] mc The cursor for this operation.
6433 * @param[in] indx The index on the page where the new node should be added.
6434 * @param[in] key The key for the new node.
6435 * @param[in] data The data for the new node, if any.
6436 * @param[in] pgno The page number, if adding a branch node.
6437 * @param[in] flags Flags for the node.
6438 * @return 0 on success, non-zero on failure. Possible errors are:
6440 * <li>ENOMEM - failed to allocate overflow pages for the node.
6441 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
6442 * should never happen since all callers already calculate the
6443 * page's free space before calling this function.
6447 mdb_node_add(MDB_cursor *mc, indx_t indx,
6448 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
6451 size_t node_size = NODESIZE;
6455 MDB_page *mp = mc->mc_pg[mc->mc_top];
6456 MDB_page *ofp = NULL; /* overflow page */
6459 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
6461 DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
6462 IS_LEAF(mp) ? "leaf" : "branch",
6463 IS_SUBP(mp) ? "sub-" : "",
6464 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
6465 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
6468 /* Move higher keys up one slot. */
6469 int ksize = mc->mc_db->md_pad, dif;
6470 char *ptr = LEAF2KEY(mp, indx, ksize);
6471 dif = NUMKEYS(mp) - indx;
6473 memmove(ptr+ksize, ptr, dif*ksize);
6474 /* insert new key */
6475 memcpy(ptr, key->mv_data, ksize);
6477 /* Just using these for counting */
6478 mp->mp_lower += sizeof(indx_t);
6479 mp->mp_upper -= ksize - sizeof(indx_t);
6483 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
6485 node_size += key->mv_size;
6487 mdb_cassert(mc, data);
6488 if (F_ISSET(flags, F_BIGDATA)) {
6489 /* Data already on overflow page. */
6490 node_size += sizeof(pgno_t);
6491 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
6492 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
6494 /* Put data on overflow page. */
6495 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
6496 data->mv_size, node_size+data->mv_size));
6497 node_size = EVEN(node_size + sizeof(pgno_t));
6498 if ((ssize_t)node_size > room)
6500 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
6502 DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
6506 node_size += data->mv_size;
6509 node_size = EVEN(node_size);
6510 if ((ssize_t)node_size > room)
6514 /* Move higher pointers up one slot. */
6515 for (i = NUMKEYS(mp); i > indx; i--)
6516 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
6518 /* Adjust free space offsets. */
6519 ofs = mp->mp_upper - node_size;
6520 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
6521 mp->mp_ptrs[indx] = ofs;
6523 mp->mp_lower += sizeof(indx_t);
6525 /* Write the node data. */
6526 node = NODEPTR(mp, indx);
6527 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
6528 node->mn_flags = flags;
6530 SETDSZ(node,data->mv_size);
6535 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6538 mdb_cassert(mc, key);
6540 if (F_ISSET(flags, F_BIGDATA))
6541 memcpy(node->mn_data + key->mv_size, data->mv_data,
6543 else if (F_ISSET(flags, MDB_RESERVE))
6544 data->mv_data = node->mn_data + key->mv_size;
6546 memcpy(node->mn_data + key->mv_size, data->mv_data,
6549 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
6551 if (F_ISSET(flags, MDB_RESERVE))
6552 data->mv_data = METADATA(ofp);
6554 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
6561 DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
6562 mdb_dbg_pgno(mp), NUMKEYS(mp)));
6563 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
6564 DPRINTF(("node size = %"Z"u", node_size));
6565 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6566 return MDB_PAGE_FULL;
6569 /** Delete the specified node from a page.
6570 * @param[in] mc Cursor pointing to the node to delete.
6571 * @param[in] ksize The size of a node. Only used if the page is
6572 * part of a #MDB_DUPFIXED database.
6575 mdb_node_del(MDB_cursor *mc, int ksize)
6577 MDB_page *mp = mc->mc_pg[mc->mc_top];
6578 indx_t indx = mc->mc_ki[mc->mc_top];
6580 indx_t i, j, numkeys, ptr;
6584 DPRINTF(("delete node %u on %s page %"Z"u", indx,
6585 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
6586 numkeys = NUMKEYS(mp);
6587 mdb_cassert(mc, indx < numkeys);
6590 int x = numkeys - 1 - indx;
6591 base = LEAF2KEY(mp, indx, ksize);
6593 memmove(base, base + ksize, x * ksize);
6594 mp->mp_lower -= sizeof(indx_t);
6595 mp->mp_upper += ksize - sizeof(indx_t);
6599 node = NODEPTR(mp, indx);
6600 sz = NODESIZE + node->mn_ksize;
6602 if (F_ISSET(node->mn_flags, F_BIGDATA))
6603 sz += sizeof(pgno_t);
6605 sz += NODEDSZ(node);
6609 ptr = mp->mp_ptrs[indx];
6610 for (i = j = 0; i < numkeys; i++) {
6612 mp->mp_ptrs[j] = mp->mp_ptrs[i];
6613 if (mp->mp_ptrs[i] < ptr)
6614 mp->mp_ptrs[j] += sz;
6619 base = (char *)mp + mp->mp_upper;
6620 memmove(base + sz, base, ptr - mp->mp_upper);
6622 mp->mp_lower -= sizeof(indx_t);
6626 /** Compact the main page after deleting a node on a subpage.
6627 * @param[in] mp The main page to operate on.
6628 * @param[in] indx The index of the subpage on the main page.
6631 mdb_node_shrink(MDB_page *mp, indx_t indx)
6637 indx_t i, numkeys, ptr;
6639 node = NODEPTR(mp, indx);
6640 sp = (MDB_page *)NODEDATA(node);
6641 delta = SIZELEFT(sp);
6642 xp = (MDB_page *)((char *)sp + delta);
6644 /* shift subpage upward */
6646 nsize = NUMKEYS(sp) * sp->mp_pad;
6648 return; /* do not make the node uneven-sized */
6649 memmove(METADATA(xp), METADATA(sp), nsize);
6652 numkeys = NUMKEYS(sp);
6653 for (i=numkeys-1; i>=0; i--)
6654 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
6656 xp->mp_upper = sp->mp_lower;
6657 xp->mp_lower = sp->mp_lower;
6658 xp->mp_flags = sp->mp_flags;
6659 xp->mp_pad = sp->mp_pad;
6660 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
6662 nsize = NODEDSZ(node) - delta;
6663 SETDSZ(node, nsize);
6665 /* shift lower nodes upward */
6666 ptr = mp->mp_ptrs[indx];
6667 numkeys = NUMKEYS(mp);
6668 for (i = 0; i < numkeys; i++) {
6669 if (mp->mp_ptrs[i] <= ptr)
6670 mp->mp_ptrs[i] += delta;
6673 base = (char *)mp + mp->mp_upper;
6674 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
6675 mp->mp_upper += delta;
6678 /** Initial setup of a sorted-dups cursor.
6679 * Sorted duplicates are implemented as a sub-database for the given key.
6680 * The duplicate data items are actually keys of the sub-database.
6681 * Operations on the duplicate data items are performed using a sub-cursor
6682 * initialized when the sub-database is first accessed. This function does
6683 * the preliminary setup of the sub-cursor, filling in the fields that
6684 * depend only on the parent DB.
6685 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6688 mdb_xcursor_init0(MDB_cursor *mc)
6690 MDB_xcursor *mx = mc->mc_xcursor;
6692 mx->mx_cursor.mc_xcursor = NULL;
6693 mx->mx_cursor.mc_txn = mc->mc_txn;
6694 mx->mx_cursor.mc_db = &mx->mx_db;
6695 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
6696 mx->mx_cursor.mc_dbi = mc->mc_dbi;
6697 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
6698 mx->mx_cursor.mc_snum = 0;
6699 mx->mx_cursor.mc_top = 0;
6700 mx->mx_cursor.mc_flags = C_SUB;
6701 mx->mx_dbx.md_name.mv_size = 0;
6702 mx->mx_dbx.md_name.mv_data = NULL;
6703 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
6704 mx->mx_dbx.md_dcmp = NULL;
6705 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
6708 /** Final setup of a sorted-dups cursor.
6709 * Sets up the fields that depend on the data from the main cursor.
6710 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6711 * @param[in] node The data containing the #MDB_db record for the
6712 * sorted-dup database.
6715 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
6717 MDB_xcursor *mx = mc->mc_xcursor;
6719 if (node->mn_flags & F_SUBDATA) {
6720 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
6721 mx->mx_cursor.mc_pg[0] = 0;
6722 mx->mx_cursor.mc_snum = 0;
6723 mx->mx_cursor.mc_top = 0;
6724 mx->mx_cursor.mc_flags = C_SUB;
6726 MDB_page *fp = NODEDATA(node);
6727 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
6728 mx->mx_db.md_flags = 0;
6729 mx->mx_db.md_depth = 1;
6730 mx->mx_db.md_branch_pages = 0;
6731 mx->mx_db.md_leaf_pages = 1;
6732 mx->mx_db.md_overflow_pages = 0;
6733 mx->mx_db.md_entries = NUMKEYS(fp);
6734 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
6735 mx->mx_cursor.mc_snum = 1;
6736 mx->mx_cursor.mc_top = 0;
6737 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
6738 mx->mx_cursor.mc_pg[0] = fp;
6739 mx->mx_cursor.mc_ki[0] = 0;
6740 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6741 mx->mx_db.md_flags = MDB_DUPFIXED;
6742 mx->mx_db.md_pad = fp->mp_pad;
6743 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6744 mx->mx_db.md_flags |= MDB_INTEGERKEY;
6747 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
6748 mx->mx_db.md_root));
6749 mx->mx_dbflag = DB_VALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
6750 #if UINT_MAX < SIZE_MAX
6751 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
6752 mx->mx_dbx.md_cmp = mdb_cmp_clong;
6756 /** Initialize a cursor for a given transaction and database. */
6758 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
6761 mc->mc_backup = NULL;
6764 mc->mc_db = &txn->mt_dbs[dbi];
6765 mc->mc_dbx = &txn->mt_dbxs[dbi];
6766 mc->mc_dbflag = &txn->mt_dbflags[dbi];
6771 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
6772 mdb_tassert(txn, mx != NULL);
6773 mc->mc_xcursor = mx;
6774 mdb_xcursor_init0(mc);
6776 mc->mc_xcursor = NULL;
6778 if (*mc->mc_dbflag & DB_STALE) {
6779 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
6784 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
6787 size_t size = sizeof(MDB_cursor);
6789 if (!ret || !TXN_DBI_EXIST(txn, dbi))
6792 if (txn->mt_flags & MDB_TXN_ERROR)
6795 /* Allow read access to the freelist */
6796 if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
6799 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
6800 size += sizeof(MDB_xcursor);
6802 if ((mc = malloc(size)) != NULL) {
6803 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
6804 if (txn->mt_cursors) {
6805 mc->mc_next = txn->mt_cursors[dbi];
6806 txn->mt_cursors[dbi] = mc;
6807 mc->mc_flags |= C_UNTRACK;
6819 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
6821 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi))
6824 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
6827 if (txn->mt_flags & MDB_TXN_ERROR)
6830 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
6834 /* Return the count of duplicate data items for the current key */
6836 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
6840 if (mc == NULL || countp == NULL)
6843 if (mc->mc_xcursor == NULL)
6844 return MDB_INCOMPATIBLE;
6846 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
6849 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6850 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6853 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
6856 *countp = mc->mc_xcursor->mx_db.md_entries;
6862 mdb_cursor_close(MDB_cursor *mc)
6864 if (mc && !mc->mc_backup) {
6865 /* remove from txn, if tracked */
6866 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
6867 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
6868 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
6870 *prev = mc->mc_next;
6877 mdb_cursor_txn(MDB_cursor *mc)
6879 if (!mc) return NULL;
6884 mdb_cursor_dbi(MDB_cursor *mc)
6889 /** Replace the key for a branch node with a new key.
6890 * @param[in] mc Cursor pointing to the node to operate on.
6891 * @param[in] key The new key to use.
6892 * @return 0 on success, non-zero on failure.
6895 mdb_update_key(MDB_cursor *mc, MDB_val *key)
6901 int delta, ksize, oksize;
6902 indx_t ptr, i, numkeys, indx;
6905 indx = mc->mc_ki[mc->mc_top];
6906 mp = mc->mc_pg[mc->mc_top];
6907 node = NODEPTR(mp, indx);
6908 ptr = mp->mp_ptrs[indx];
6912 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
6913 k2.mv_data = NODEKEY(node);
6914 k2.mv_size = node->mn_ksize;
6915 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
6917 mdb_dkey(&k2, kbuf2),
6923 /* Sizes must be 2-byte aligned. */
6924 ksize = EVEN(key->mv_size);
6925 oksize = EVEN(node->mn_ksize);
6926 delta = ksize - oksize;
6928 /* Shift node contents if EVEN(key length) changed. */
6930 if (delta > 0 && SIZELEFT(mp) < delta) {
6932 /* not enough space left, do a delete and split */
6933 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
6934 pgno = NODEPGNO(node);
6935 mdb_node_del(mc, 0);
6936 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
6939 numkeys = NUMKEYS(mp);
6940 for (i = 0; i < numkeys; i++) {
6941 if (mp->mp_ptrs[i] <= ptr)
6942 mp->mp_ptrs[i] -= delta;
6945 base = (char *)mp + mp->mp_upper;
6946 len = ptr - mp->mp_upper + NODESIZE;
6947 memmove(base - delta, base, len);
6948 mp->mp_upper -= delta;
6950 node = NODEPTR(mp, indx);
6953 /* But even if no shift was needed, update ksize */
6954 if (node->mn_ksize != key->mv_size)
6955 node->mn_ksize = key->mv_size;
6958 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6964 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
6966 /** Move a node from csrc to cdst.
6969 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
6976 unsigned short flags;
6980 /* Mark src and dst as dirty. */
6981 if ((rc = mdb_page_touch(csrc)) ||
6982 (rc = mdb_page_touch(cdst)))
6985 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6986 key.mv_size = csrc->mc_db->md_pad;
6987 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
6989 data.mv_data = NULL;
6993 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
6994 mdb_cassert(csrc, !((size_t)srcnode & 1));
6995 srcpg = NODEPGNO(srcnode);
6996 flags = srcnode->mn_flags;
6997 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6998 unsigned int snum = csrc->mc_snum;
7000 /* must find the lowest key below src */
7001 rc = mdb_page_search_lowest(csrc);
7004 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7005 key.mv_size = csrc->mc_db->md_pad;
7006 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7008 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7009 key.mv_size = NODEKSZ(s2);
7010 key.mv_data = NODEKEY(s2);
7012 csrc->mc_snum = snum--;
7013 csrc->mc_top = snum;
7015 key.mv_size = NODEKSZ(srcnode);
7016 key.mv_data = NODEKEY(srcnode);
7018 data.mv_size = NODEDSZ(srcnode);
7019 data.mv_data = NODEDATA(srcnode);
7021 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
7022 unsigned int snum = cdst->mc_snum;
7025 /* must find the lowest key below dst */
7026 mdb_cursor_copy(cdst, &mn);
7027 rc = mdb_page_search_lowest(&mn);
7030 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7031 bkey.mv_size = mn.mc_db->md_pad;
7032 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
7034 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7035 bkey.mv_size = NODEKSZ(s2);
7036 bkey.mv_data = NODEKEY(s2);
7038 mn.mc_snum = snum--;
7041 rc = mdb_update_key(&mn, &bkey);
7046 DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
7047 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
7048 csrc->mc_ki[csrc->mc_top],
7050 csrc->mc_pg[csrc->mc_top]->mp_pgno,
7051 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
7053 /* Add the node to the destination page.
7055 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
7056 if (rc != MDB_SUCCESS)
7059 /* Delete the node from the source page.
7061 mdb_node_del(csrc, key.mv_size);
7064 /* Adjust other cursors pointing to mp */
7065 MDB_cursor *m2, *m3;
7066 MDB_dbi dbi = csrc->mc_dbi;
7067 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
7069 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7070 if (csrc->mc_flags & C_SUB)
7071 m3 = &m2->mc_xcursor->mx_cursor;
7074 if (m3 == csrc) continue;
7075 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
7076 csrc->mc_ki[csrc->mc_top]) {
7077 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
7078 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7083 /* Update the parent separators.
7085 if (csrc->mc_ki[csrc->mc_top] == 0) {
7086 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
7087 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7088 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7090 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7091 key.mv_size = NODEKSZ(srcnode);
7092 key.mv_data = NODEKEY(srcnode);
7094 DPRINTF(("update separator for source page %"Z"u to [%s]",
7095 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
7096 mdb_cursor_copy(csrc, &mn);
7099 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7102 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7104 indx_t ix = csrc->mc_ki[csrc->mc_top];
7105 nullkey.mv_size = 0;
7106 csrc->mc_ki[csrc->mc_top] = 0;
7107 rc = mdb_update_key(csrc, &nullkey);
7108 csrc->mc_ki[csrc->mc_top] = ix;
7109 mdb_cassert(csrc, rc == MDB_SUCCESS);
7113 if (cdst->mc_ki[cdst->mc_top] == 0) {
7114 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
7115 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7116 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
7118 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
7119 key.mv_size = NODEKSZ(srcnode);
7120 key.mv_data = NODEKEY(srcnode);
7122 DPRINTF(("update separator for destination page %"Z"u to [%s]",
7123 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
7124 mdb_cursor_copy(cdst, &mn);
7127 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7130 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
7132 indx_t ix = cdst->mc_ki[cdst->mc_top];
7133 nullkey.mv_size = 0;
7134 cdst->mc_ki[cdst->mc_top] = 0;
7135 rc = mdb_update_key(cdst, &nullkey);
7136 cdst->mc_ki[cdst->mc_top] = ix;
7137 mdb_cassert(csrc, rc == MDB_SUCCESS);
7144 /** Merge one page into another.
7145 * The nodes from the page pointed to by \b csrc will
7146 * be copied to the page pointed to by \b cdst and then
7147 * the \b csrc page will be freed.
7148 * @param[in] csrc Cursor pointing to the source page.
7149 * @param[in] cdst Cursor pointing to the destination page.
7150 * @return 0 on success, non-zero on failure.
7153 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
7155 MDB_page *psrc, *pdst;
7162 psrc = csrc->mc_pg[csrc->mc_top];
7163 pdst = cdst->mc_pg[cdst->mc_top];
7165 DPRINTF(("merging page %"Z"u into %"Z"u", psrc->mp_pgno, pdst->mp_pgno));
7167 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
7168 mdb_cassert(csrc, cdst->mc_snum > 1);
7170 /* Mark dst as dirty. */
7171 if ((rc = mdb_page_touch(cdst)))
7174 /* Move all nodes from src to dst.
7176 j = nkeys = NUMKEYS(pdst);
7177 if (IS_LEAF2(psrc)) {
7178 key.mv_size = csrc->mc_db->md_pad;
7179 key.mv_data = METADATA(psrc);
7180 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7181 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
7182 if (rc != MDB_SUCCESS)
7184 key.mv_data = (char *)key.mv_data + key.mv_size;
7187 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7188 srcnode = NODEPTR(psrc, i);
7189 if (i == 0 && IS_BRANCH(psrc)) {
7192 mdb_cursor_copy(csrc, &mn);
7193 /* must find the lowest key below src */
7194 rc = mdb_page_search_lowest(&mn);
7197 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7198 key.mv_size = mn.mc_db->md_pad;
7199 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
7201 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7202 key.mv_size = NODEKSZ(s2);
7203 key.mv_data = NODEKEY(s2);
7206 key.mv_size = srcnode->mn_ksize;
7207 key.mv_data = NODEKEY(srcnode);
7210 data.mv_size = NODEDSZ(srcnode);
7211 data.mv_data = NODEDATA(srcnode);
7212 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
7213 if (rc != MDB_SUCCESS)
7218 DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
7219 pdst->mp_pgno, NUMKEYS(pdst),
7220 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
7222 /* Unlink the src page from parent and add to free list.
7225 mdb_node_del(csrc, 0);
7226 if (csrc->mc_ki[csrc->mc_top] == 0) {
7228 rc = mdb_update_key(csrc, &key);
7236 psrc = csrc->mc_pg[csrc->mc_top];
7237 /* If not operating on FreeDB, allow this page to be reused
7238 * in this txn. Otherwise just add to free list.
7240 rc = mdb_page_loose(csrc, psrc);
7244 csrc->mc_db->md_leaf_pages--;
7246 csrc->mc_db->md_branch_pages--;
7248 /* Adjust other cursors pointing to mp */
7249 MDB_cursor *m2, *m3;
7250 MDB_dbi dbi = csrc->mc_dbi;
7252 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7253 if (csrc->mc_flags & C_SUB)
7254 m3 = &m2->mc_xcursor->mx_cursor;
7257 if (m3 == csrc) continue;
7258 if (m3->mc_snum < csrc->mc_snum) continue;
7259 if (m3->mc_pg[csrc->mc_top] == psrc) {
7260 m3->mc_pg[csrc->mc_top] = pdst;
7261 m3->mc_ki[csrc->mc_top] += nkeys;
7266 unsigned int snum = cdst->mc_snum;
7267 uint16_t depth = cdst->mc_db->md_depth;
7268 mdb_cursor_pop(cdst);
7269 rc = mdb_rebalance(cdst);
7270 /* Did the tree shrink? */
7271 if (depth > cdst->mc_db->md_depth)
7273 cdst->mc_snum = snum;
7274 cdst->mc_top = snum-1;
7279 /** Copy the contents of a cursor.
7280 * @param[in] csrc The cursor to copy from.
7281 * @param[out] cdst The cursor to copy to.
7284 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
7288 cdst->mc_txn = csrc->mc_txn;
7289 cdst->mc_dbi = csrc->mc_dbi;
7290 cdst->mc_db = csrc->mc_db;
7291 cdst->mc_dbx = csrc->mc_dbx;
7292 cdst->mc_snum = csrc->mc_snum;
7293 cdst->mc_top = csrc->mc_top;
7294 cdst->mc_flags = csrc->mc_flags;
7296 for (i=0; i<csrc->mc_snum; i++) {
7297 cdst->mc_pg[i] = csrc->mc_pg[i];
7298 cdst->mc_ki[i] = csrc->mc_ki[i];
7302 /** Rebalance the tree after a delete operation.
7303 * @param[in] mc Cursor pointing to the page where rebalancing
7305 * @return 0 on success, non-zero on failure.
7308 mdb_rebalance(MDB_cursor *mc)
7312 unsigned int ptop, minkeys;
7316 minkeys = 1 + (IS_BRANCH(mc->mc_pg[mc->mc_top]));
7317 DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
7318 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
7319 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
7320 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
7322 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD &&
7323 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
7324 DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
7325 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
7329 if (mc->mc_snum < 2) {
7330 MDB_page *mp = mc->mc_pg[0];
7332 DPUTS("Can't rebalance a subpage, ignoring");
7335 if (NUMKEYS(mp) == 0) {
7336 DPUTS("tree is completely empty");
7337 mc->mc_db->md_root = P_INVALID;
7338 mc->mc_db->md_depth = 0;
7339 mc->mc_db->md_leaf_pages = 0;
7340 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7343 /* Adjust cursors pointing to mp */
7346 mc->mc_flags &= ~C_INITIALIZED;
7348 MDB_cursor *m2, *m3;
7349 MDB_dbi dbi = mc->mc_dbi;
7351 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7352 if (mc->mc_flags & C_SUB)
7353 m3 = &m2->mc_xcursor->mx_cursor;
7356 if (m3->mc_snum < mc->mc_snum) continue;
7357 if (m3->mc_pg[0] == mp) {
7360 m3->mc_flags &= ~C_INITIALIZED;
7364 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
7366 DPUTS("collapsing root page!");
7367 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7370 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
7371 rc = mdb_page_get(mc->mc_txn,mc->mc_db->md_root,&mc->mc_pg[0],NULL);
7374 mc->mc_db->md_depth--;
7375 mc->mc_db->md_branch_pages--;
7376 mc->mc_ki[0] = mc->mc_ki[1];
7377 for (i = 1; i<mc->mc_db->md_depth; i++) {
7378 mc->mc_pg[i] = mc->mc_pg[i+1];
7379 mc->mc_ki[i] = mc->mc_ki[i+1];
7382 /* Adjust other cursors pointing to mp */
7383 MDB_cursor *m2, *m3;
7384 MDB_dbi dbi = mc->mc_dbi;
7386 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7387 if (mc->mc_flags & C_SUB)
7388 m3 = &m2->mc_xcursor->mx_cursor;
7391 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
7392 if (m3->mc_pg[0] == mp) {
7395 for (i=0; i<m3->mc_snum; i++) {
7396 m3->mc_pg[i] = m3->mc_pg[i+1];
7397 m3->mc_ki[i] = m3->mc_ki[i+1];
7403 DPUTS("root page doesn't need rebalancing");
7407 /* The parent (branch page) must have at least 2 pointers,
7408 * otherwise the tree is invalid.
7410 ptop = mc->mc_top-1;
7411 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
7413 /* Leaf page fill factor is below the threshold.
7414 * Try to move keys from left or right neighbor, or
7415 * merge with a neighbor page.
7420 mdb_cursor_copy(mc, &mn);
7421 mn.mc_xcursor = NULL;
7423 oldki = mc->mc_ki[mc->mc_top];
7424 if (mc->mc_ki[ptop] == 0) {
7425 /* We're the leftmost leaf in our parent.
7427 DPUTS("reading right neighbor");
7429 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7430 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7433 mn.mc_ki[mn.mc_top] = 0;
7434 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
7436 /* There is at least one neighbor to the left.
7438 DPUTS("reading left neighbor");
7440 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7441 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7444 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
7445 mc->mc_ki[mc->mc_top] = 0;
7448 DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
7449 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
7450 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
7452 /* If the neighbor page is above threshold and has enough keys,
7453 * move one key from it. Otherwise we should try to merge them.
7454 * (A branch page must never have less than 2 keys.)
7456 minkeys = 1 + (IS_BRANCH(mn.mc_pg[mn.mc_top]));
7457 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
7458 rc = mdb_node_move(&mn, mc);
7459 if (mc->mc_ki[ptop]) {
7463 if (mc->mc_ki[ptop] == 0) {
7464 rc = mdb_page_merge(&mn, mc);
7466 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
7467 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
7468 rc = mdb_page_merge(mc, &mn);
7469 mdb_cursor_copy(&mn, mc);
7471 mc->mc_flags &= ~C_EOF;
7473 mc->mc_ki[mc->mc_top] = oldki;
7477 /** Complete a delete operation started by #mdb_cursor_del(). */
7479 mdb_cursor_del0(MDB_cursor *mc)
7486 ki = mc->mc_ki[mc->mc_top];
7487 mdb_node_del(mc, mc->mc_db->md_pad);
7488 mc->mc_db->md_entries--;
7489 rc = mdb_rebalance(mc);
7491 if (rc == MDB_SUCCESS) {
7492 MDB_cursor *m2, *m3;
7493 MDB_dbi dbi = mc->mc_dbi;
7495 mp = mc->mc_pg[mc->mc_top];
7496 nkeys = NUMKEYS(mp);
7498 /* if mc points past last node in page, find next sibling */
7499 if (mc->mc_ki[mc->mc_top] >= nkeys) {
7500 rc = mdb_cursor_sibling(mc, 1);
7501 if (rc == MDB_NOTFOUND)
7505 /* Adjust other cursors pointing to mp */
7506 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
7507 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
7508 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
7510 if (m3 == mc || m3->mc_snum < mc->mc_snum)
7512 if (m3->mc_pg[mc->mc_top] == mp) {
7513 if (m3->mc_ki[mc->mc_top] >= ki) {
7514 m3->mc_flags |= C_DEL;
7515 if (m3->mc_ki[mc->mc_top] > ki)
7516 m3->mc_ki[mc->mc_top]--;
7518 if (m3->mc_ki[mc->mc_top] >= nkeys) {
7519 rc = mdb_cursor_sibling(m3, 1);
7520 if (rc == MDB_NOTFOUND)
7525 mc->mc_flags |= C_DEL;
7529 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7534 mdb_del(MDB_txn *txn, MDB_dbi dbi,
7535 MDB_val *key, MDB_val *data)
7537 if (!key || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
7540 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
7541 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7543 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
7544 /* must ignore any data */
7548 return mdb_del0(txn, dbi, key, data, 0);
7552 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
7553 MDB_val *key, MDB_val *data, unsigned flags)
7558 MDB_val rdata, *xdata;
7562 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
7564 mdb_cursor_init(&mc, txn, dbi, &mx);
7573 flags |= MDB_NODUPDATA;
7575 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
7577 /* let mdb_page_split know about this cursor if needed:
7578 * delete will trigger a rebalance; if it needs to move
7579 * a node from one page to another, it will have to
7580 * update the parent's separator key(s). If the new sepkey
7581 * is larger than the current one, the parent page may
7582 * run out of space, triggering a split. We need this
7583 * cursor to be consistent until the end of the rebalance.
7585 mc.mc_flags |= C_UNTRACK;
7586 mc.mc_next = txn->mt_cursors[dbi];
7587 txn->mt_cursors[dbi] = &mc;
7588 rc = mdb_cursor_del(&mc, flags);
7589 txn->mt_cursors[dbi] = mc.mc_next;
7594 /** Split a page and insert a new node.
7595 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
7596 * The cursor will be updated to point to the actual page and index where
7597 * the node got inserted after the split.
7598 * @param[in] newkey The key for the newly inserted node.
7599 * @param[in] newdata The data for the newly inserted node.
7600 * @param[in] newpgno The page number, if the new node is a branch node.
7601 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
7602 * @return 0 on success, non-zero on failure.
7605 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
7606 unsigned int nflags)
7609 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
7612 int i, j, split_indx, nkeys, pmax;
7613 MDB_env *env = mc->mc_txn->mt_env;
7615 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
7616 MDB_page *copy = NULL;
7617 MDB_page *mp, *rp, *pp;
7622 mp = mc->mc_pg[mc->mc_top];
7623 newindx = mc->mc_ki[mc->mc_top];
7624 nkeys = NUMKEYS(mp);
7626 DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i/%i",
7627 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
7628 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
7630 /* Create a right sibling. */
7631 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
7633 DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
7635 if (mc->mc_snum < 2) {
7636 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
7638 /* shift current top to make room for new parent */
7639 mc->mc_pg[1] = mc->mc_pg[0];
7640 mc->mc_ki[1] = mc->mc_ki[0];
7643 mc->mc_db->md_root = pp->mp_pgno;
7644 DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
7645 mc->mc_db->md_depth++;
7648 /* Add left (implicit) pointer. */
7649 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
7650 /* undo the pre-push */
7651 mc->mc_pg[0] = mc->mc_pg[1];
7652 mc->mc_ki[0] = mc->mc_ki[1];
7653 mc->mc_db->md_root = mp->mp_pgno;
7654 mc->mc_db->md_depth--;
7661 ptop = mc->mc_top-1;
7662 DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
7665 mc->mc_flags |= C_SPLITTING;
7666 mdb_cursor_copy(mc, &mn);
7667 mn.mc_pg[mn.mc_top] = rp;
7668 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
7670 if (nflags & MDB_APPEND) {
7671 mn.mc_ki[mn.mc_top] = 0;
7673 split_indx = newindx;
7677 split_indx = (nkeys+1) / 2;
7682 unsigned int lsize, rsize, ksize;
7683 /* Move half of the keys to the right sibling */
7684 x = mc->mc_ki[mc->mc_top] - split_indx;
7685 ksize = mc->mc_db->md_pad;
7686 split = LEAF2KEY(mp, split_indx, ksize);
7687 rsize = (nkeys - split_indx) * ksize;
7688 lsize = (nkeys - split_indx) * sizeof(indx_t);
7689 mp->mp_lower -= lsize;
7690 rp->mp_lower += lsize;
7691 mp->mp_upper += rsize - lsize;
7692 rp->mp_upper -= rsize - lsize;
7693 sepkey.mv_size = ksize;
7694 if (newindx == split_indx) {
7695 sepkey.mv_data = newkey->mv_data;
7697 sepkey.mv_data = split;
7700 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
7701 memcpy(rp->mp_ptrs, split, rsize);
7702 sepkey.mv_data = rp->mp_ptrs;
7703 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
7704 memcpy(ins, newkey->mv_data, ksize);
7705 mp->mp_lower += sizeof(indx_t);
7706 mp->mp_upper -= ksize - sizeof(indx_t);
7709 memcpy(rp->mp_ptrs, split, x * ksize);
7710 ins = LEAF2KEY(rp, x, ksize);
7711 memcpy(ins, newkey->mv_data, ksize);
7712 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
7713 rp->mp_lower += sizeof(indx_t);
7714 rp->mp_upper -= ksize - sizeof(indx_t);
7715 mc->mc_ki[mc->mc_top] = x;
7716 mc->mc_pg[mc->mc_top] = rp;
7719 int psize, nsize, k;
7720 /* Maximum free space in an empty page */
7721 pmax = env->me_psize - PAGEHDRSZ;
7723 nsize = mdb_leaf_size(env, newkey, newdata);
7725 nsize = mdb_branch_size(env, newkey);
7726 nsize = EVEN(nsize);
7728 /* grab a page to hold a temporary copy */
7729 copy = mdb_page_malloc(mc->mc_txn, 1);
7734 copy->mp_pgno = mp->mp_pgno;
7735 copy->mp_flags = mp->mp_flags;
7736 copy->mp_lower = PAGEHDRSZ;
7737 copy->mp_upper = env->me_psize;
7739 /* prepare to insert */
7740 for (i=0, j=0; i<nkeys; i++) {
7742 copy->mp_ptrs[j++] = 0;
7744 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
7747 /* When items are relatively large the split point needs
7748 * to be checked, because being off-by-one will make the
7749 * difference between success or failure in mdb_node_add.
7751 * It's also relevant if a page happens to be laid out
7752 * such that one half of its nodes are all "small" and
7753 * the other half of its nodes are "large." If the new
7754 * item is also "large" and falls on the half with
7755 * "large" nodes, it also may not fit.
7757 * As a final tweak, if the new item goes on the last
7758 * spot on the page (and thus, onto the new page), bias
7759 * the split so the new page is emptier than the old page.
7760 * This yields better packing during sequential inserts.
7762 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
7763 /* Find split point */
7765 if (newindx <= split_indx || newindx >= nkeys) {
7767 k = newindx >= nkeys ? nkeys : split_indx+2;
7772 for (; i!=k; i+=j) {
7777 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i]);
7778 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
7780 if (F_ISSET(node->mn_flags, F_BIGDATA))
7781 psize += sizeof(pgno_t);
7783 psize += NODEDSZ(node);
7785 psize = EVEN(psize);
7787 if (psize > pmax || i == k-j) {
7788 split_indx = i + (j<0);
7793 if (split_indx == newindx) {
7794 sepkey.mv_size = newkey->mv_size;
7795 sepkey.mv_data = newkey->mv_data;
7797 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx]);
7798 sepkey.mv_size = node->mn_ksize;
7799 sepkey.mv_data = NODEKEY(node);
7804 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
7806 /* Copy separator key to the parent.
7808 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
7812 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
7817 if (mn.mc_snum == mc->mc_snum) {
7818 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
7819 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
7820 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
7821 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
7826 /* Right page might now have changed parent.
7827 * Check if left page also changed parent.
7829 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7830 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7831 for (i=0; i<ptop; i++) {
7832 mc->mc_pg[i] = mn.mc_pg[i];
7833 mc->mc_ki[i] = mn.mc_ki[i];
7835 mc->mc_pg[ptop] = mn.mc_pg[ptop];
7836 if (mn.mc_ki[ptop]) {
7837 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
7839 /* find right page's left sibling */
7840 mc->mc_ki[ptop] = mn.mc_ki[ptop];
7841 mdb_cursor_sibling(mc, 0);
7846 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
7849 mc->mc_flags ^= C_SPLITTING;
7850 if (rc != MDB_SUCCESS) {
7853 if (nflags & MDB_APPEND) {
7854 mc->mc_pg[mc->mc_top] = rp;
7855 mc->mc_ki[mc->mc_top] = 0;
7856 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
7859 for (i=0; i<mc->mc_top; i++)
7860 mc->mc_ki[i] = mn.mc_ki[i];
7861 } else if (!IS_LEAF2(mp)) {
7863 mc->mc_pg[mc->mc_top] = rp;
7868 rkey.mv_data = newkey->mv_data;
7869 rkey.mv_size = newkey->mv_size;
7875 /* Update index for the new key. */
7876 mc->mc_ki[mc->mc_top] = j;
7878 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i]);
7879 rkey.mv_data = NODEKEY(node);
7880 rkey.mv_size = node->mn_ksize;
7882 xdata.mv_data = NODEDATA(node);
7883 xdata.mv_size = NODEDSZ(node);
7886 pgno = NODEPGNO(node);
7887 flags = node->mn_flags;
7890 if (!IS_LEAF(mp) && j == 0) {
7891 /* First branch index doesn't need key data. */
7895 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
7901 mc->mc_pg[mc->mc_top] = copy;
7906 } while (i != split_indx);
7908 nkeys = NUMKEYS(copy);
7909 for (i=0; i<nkeys; i++)
7910 mp->mp_ptrs[i] = copy->mp_ptrs[i];
7911 mp->mp_lower = copy->mp_lower;
7912 mp->mp_upper = copy->mp_upper;
7913 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
7914 env->me_psize - copy->mp_upper);
7916 /* reset back to original page */
7917 if (newindx < split_indx) {
7918 mc->mc_pg[mc->mc_top] = mp;
7919 if (nflags & MDB_RESERVE) {
7920 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7921 if (!(node->mn_flags & F_BIGDATA))
7922 newdata->mv_data = NODEDATA(node);
7925 mc->mc_pg[mc->mc_top] = rp;
7927 /* Make sure mc_ki is still valid.
7929 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7930 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7931 for (i=0; i<=ptop; i++) {
7932 mc->mc_pg[i] = mn.mc_pg[i];
7933 mc->mc_ki[i] = mn.mc_ki[i];
7940 /* Adjust other cursors pointing to mp */
7941 MDB_cursor *m2, *m3;
7942 MDB_dbi dbi = mc->mc_dbi;
7943 int fixup = NUMKEYS(mp);
7945 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7946 if (mc->mc_flags & C_SUB)
7947 m3 = &m2->mc_xcursor->mx_cursor;
7952 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
7954 if (m3->mc_flags & C_SPLITTING)
7959 for (k=m3->mc_top; k>=0; k--) {
7960 m3->mc_ki[k+1] = m3->mc_ki[k];
7961 m3->mc_pg[k+1] = m3->mc_pg[k];
7963 if (m3->mc_ki[0] >= split_indx) {
7968 m3->mc_pg[0] = mc->mc_pg[0];
7972 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
7973 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
7974 m3->mc_ki[mc->mc_top]++;
7975 if (m3->mc_ki[mc->mc_top] >= fixup) {
7976 m3->mc_pg[mc->mc_top] = rp;
7977 m3->mc_ki[mc->mc_top] -= fixup;
7978 m3->mc_ki[ptop] = mn.mc_ki[ptop];
7980 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
7981 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
7986 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
7989 if (copy) /* tmp page */
7990 mdb_page_free(env, copy);
7992 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7997 mdb_put(MDB_txn *txn, MDB_dbi dbi,
7998 MDB_val *key, MDB_val *data, unsigned int flags)
8003 if (!key || !data || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
8006 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP)) != flags)
8009 mdb_cursor_init(&mc, txn, dbi, &mx);
8010 return mdb_cursor_put(&mc, key, data, flags);
8014 #define MDB_WBUF (1024*1024)
8017 typedef struct mdb_copy {
8018 pthread_mutex_t mc_mutex[2];
8026 pgno_t mc_next_pgno;
8033 mdb_env_copythr(void *arg)
8038 int toggle = 0, len, rc;
8040 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8042 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8045 pthread_mutex_lock(&my->mc_mutex[toggle^1]);
8047 pthread_mutex_lock(&my->mc_mutex[toggle]);
8048 pthread_mutex_unlock(&my->mc_mutex[toggle^1]);
8049 if (!my->mc_wlen[toggle]) {
8050 pthread_mutex_unlock(&my->mc_mutex[toggle]);
8053 wsize = my->mc_wlen[toggle];
8054 ptr = my->mc_wbuf[toggle];
8057 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
8061 } else if (len > 0) {
8071 my->mc_wlen[toggle] = wsize;
8074 pthread_mutex_unlock(&my->mc_mutex[toggle]);
8077 /* If there's an overflow page tail, write it too */
8078 if (my->mc_olen[toggle]) {
8079 wsize = my->mc_olen[toggle];
8080 ptr = my->mc_over[toggle];
8081 my->mc_olen[toggle] = 0;
8091 mdb_env_cthr_toggle(mdb_copy *my)
8093 int toggle = my->mc_toggle ^ 1;
8095 pthread_mutex_unlock(&my->mc_mutex[my->mc_toggle]);
8096 pthread_mutex_lock(&my->mc_mutex[toggle]);
8097 if (my->mc_status) {
8098 pthread_mutex_unlock(&my->mc_mutex[toggle]);
8099 return my->mc_status;
8101 my->mc_wlen[toggle] = 0;
8102 my->mc_olen[toggle] = 0;
8103 my->mc_toggle = toggle;
8108 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
8111 MDB_txn *txn = my->mc_txn;
8113 MDB_page *mo, *mp, *leaf;
8122 rc = mdb_page_get(my->mc_txn, *pg, &mc.mc_pg[0], NULL);
8125 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
8129 /* Make cursor pages writable */
8130 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
8134 for (i=0; i<mc.mc_top; i++) {
8135 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
8136 mc.mc_pg[i] = (MDB_page *)ptr;
8137 ptr += my->mc_env->me_psize;
8140 /* This is writable space for a leaf page. Usually not needed. */
8141 leaf = (MDB_page *)ptr;
8143 toggle = my->mc_toggle;
8144 while (mc.mc_snum > 0) {
8146 mp = mc.mc_pg[mc.mc_top];
8150 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
8151 for (i=0; i<n; i++) {
8152 ni = NODEPTR(mp, i);
8153 if (ni->mn_flags & F_BIGDATA) {
8157 /* Need writable leaf */
8159 mc.mc_pg[mc.mc_top] = leaf;
8160 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8162 ni = NODEPTR(mp, i);
8165 memcpy(&pg, NODEDATA(ni), sizeof(pg));
8166 rc = mdb_page_get(txn, pg, &omp, NULL);
8169 if (my->mc_wlen[toggle] >= MDB_WBUF) {
8170 rc = mdb_env_cthr_toggle(my);
8175 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
8176 memcpy(mo, omp, my->mc_env->me_psize);
8177 mo->mp_pgno = my->mc_next_pgno;
8178 my->mc_next_pgno += omp->mp_pages;
8179 my->mc_wlen[toggle] += my->mc_env->me_psize;
8180 if (omp->mp_pages > 1) {
8181 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
8182 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
8183 rc = mdb_env_cthr_toggle(my);
8188 memcpy(NODEDATA(ni), &mo->mp_pgno, sizeof(pgno_t));
8189 } else if (ni->mn_flags & F_SUBDATA) {
8192 /* Need writable leaf */
8194 mc.mc_pg[mc.mc_top] = leaf;
8195 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8197 ni = NODEPTR(mp, i);
8200 memcpy(&db, NODEDATA(ni), sizeof(db));
8201 my->mc_toggle = toggle;
8202 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
8205 toggle = my->mc_toggle;
8206 memcpy(NODEDATA(ni), &db, sizeof(db));
8211 mc.mc_ki[mc.mc_top]++;
8212 if (mc.mc_ki[mc.mc_top] < n) {
8215 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
8217 rc = mdb_page_get(txn, pg, &mp, NULL);
8222 mc.mc_ki[mc.mc_top] = 0;
8223 if (IS_BRANCH(mp)) {
8224 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
8227 mc.mc_pg[mc.mc_top] = mp;
8232 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
8233 SETPGNO(ni, my->mc_next_pgno);
8235 if (my->mc_wlen[toggle] >= MDB_WBUF) {
8236 rc = mdb_env_cthr_toggle(my);
8241 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
8242 mdb_page_copy(mo, mp, my->mc_env->me_psize);
8243 mo->mp_pgno = my->mc_next_pgno++;
8244 my->mc_wlen[toggle] += my->mc_env->me_psize;
8245 mdb_cursor_pop(&mc);
8254 mdb_env_copyfd2(MDB_env *env, HANDLE fd)
8259 MDB_txn *txn = NULL;
8263 rc = posix_memalign(&my.mc_free, env->me_psize, MDB_WBUF*2);
8266 my.mc_wbuf[0] = my.mc_free;
8267 my.mc_wbuf[1] = my.mc_free + MDB_WBUF;
8268 pthread_mutex_init(&my.mc_mutex[0], NULL);
8269 pthread_mutex_init(&my.mc_mutex[1], NULL);
8274 my.mc_next_pgno = 2;
8279 pthread_mutex_lock(&my.mc_mutex[0]);
8281 /* Do the lock/unlock of the reader mutex before starting the
8282 * write txn. Otherwise other read txns could block writers.
8284 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
8289 /* We must start the actual read txn after blocking writers */
8290 mdb_txn_reset0(txn, "reset-stage1");
8292 /* Temporarily block writers until we snapshot the meta pages */
8295 rc = mdb_txn_renew0(txn);
8297 UNLOCK_MUTEX_W(env);
8302 mp = (MDB_page *)my.mc_wbuf[0];
8303 memset(mp, 0, 2*env->me_psize);
8305 mp->mp_flags = P_META;
8306 mm = (MDB_meta *)METADATA(mp);
8307 mdb_env_init_meta0(env, mm);
8308 mm->mm_address = env->me_metas[0]->mm_address;
8310 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
8312 mp->mp_flags = P_META;
8313 *(MDB_meta *)METADATA(mp) = *mm;
8314 mm = (MDB_meta *)METADATA(mp);
8316 /* Count the number of free pages, subtract from lastpg to find
8317 * number of active pages
8320 MDB_ID freecount = 0;
8323 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
8324 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
8325 freecount += *(MDB_ID *)data.mv_data;
8326 freecount += txn->mt_dbs[0].md_branch_pages +
8327 txn->mt_dbs[0].md_leaf_pages +
8328 txn->mt_dbs[0].md_overflow_pages;
8330 /* Set metapage 1 */
8331 mm->mm_last_pg = txn->mt_next_pgno - freecount - 1;
8332 mm->mm_dbs[1] = txn->mt_dbs[1];
8333 mm->mm_dbs[1].md_root = mm->mm_last_pg;
8336 my.mc_wlen[0] = env->me_psize * 2;
8338 pthread_create(&thr, NULL, mdb_env_copythr, &my);
8339 rc = mdb_env_cwalk(&my, &txn->mt_dbs[1].md_root, 0);
8340 if (rc == MDB_SUCCESS && my.mc_wlen[my.mc_toggle])
8341 rc = mdb_env_cthr_toggle(&my);
8342 my.mc_wlen[my.mc_toggle] = 0;
8343 pthread_mutex_unlock(&my.mc_mutex[my.mc_toggle]);
8344 pthread_join(thr, NULL);
8352 mdb_env_copyfd(MDB_env *env, HANDLE fd)
8354 MDB_txn *txn = NULL;
8360 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8364 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8367 /* Do the lock/unlock of the reader mutex before starting the
8368 * write txn. Otherwise other read txns could block writers.
8370 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
8375 /* We must start the actual read txn after blocking writers */
8376 mdb_txn_reset0(txn, "reset-stage1");
8378 /* Temporarily block writers until we snapshot the meta pages */
8381 rc = mdb_txn_renew0(txn);
8383 UNLOCK_MUTEX_W(env);
8388 wsize = env->me_psize * 2;
8392 DO_WRITE(rc, fd, ptr, w2, len);
8396 } else if (len > 0) {
8402 /* Non-blocking or async handles are not supported */
8408 UNLOCK_MUTEX_W(env);
8413 w2 = txn->mt_next_pgno * env->me_psize;
8416 LARGE_INTEGER fsize;
8417 GetFileSizeEx(env->me_fd, &fsize);
8418 if (w2 > fsize.QuadPart)
8419 w2 = fsize.QuadPart;
8424 fstat(env->me_fd, &st);
8425 if (w2 > (size_t)st.st_size)
8431 if (wsize > MAX_WRITE)
8435 DO_WRITE(rc, fd, ptr, w2, len);
8439 } else if (len > 0) {
8456 mdb_env_copy0(MDB_env *env, const char *path, int flag)
8460 HANDLE newfd = INVALID_HANDLE_VALUE;
8462 if (env->me_flags & MDB_NOSUBDIR) {
8463 lpath = (char *)path;
8466 len += sizeof(DATANAME);
8467 lpath = malloc(len);
8470 sprintf(lpath, "%s" DATANAME, path);
8473 /* The destination path must exist, but the destination file must not.
8474 * We don't want the OS to cache the writes, since the source data is
8475 * already in the OS cache.
8478 newfd = CreateFile(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
8479 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
8481 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
8483 if (newfd == INVALID_HANDLE_VALUE) {
8489 /* Set O_DIRECT if the file system supports it */
8490 if ((rc = fcntl(newfd, F_GETFL)) != -1)
8491 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
8493 #ifdef F_NOCACHE /* __APPLE__ */
8494 rc = fcntl(newfd, F_NOCACHE, 1);
8502 rc = mdb_env_copyfd2(env, newfd);
8504 rc = mdb_env_copyfd(env, newfd);
8507 if (!(env->me_flags & MDB_NOSUBDIR))
8509 if (newfd != INVALID_HANDLE_VALUE)
8510 if (close(newfd) < 0 && rc == MDB_SUCCESS)
8517 mdb_env_copy(MDB_env *env, const char *path)
8519 return mdb_env_copy0(env, path, 0);
8523 mdb_env_copy2(MDB_env *env, const char *path)
8525 return mdb_env_copy0(env, path, 1);
8529 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
8531 if ((flag & CHANGEABLE) != flag)
8534 env->me_flags |= flag;
8536 env->me_flags &= ~flag;
8541 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
8546 *arg = env->me_flags;
8551 mdb_env_set_userctx(MDB_env *env, void *ctx)
8555 env->me_userctx = ctx;
8560 mdb_env_get_userctx(MDB_env *env)
8562 return env ? env->me_userctx : NULL;
8566 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
8571 env->me_assert_func = func;
8577 mdb_env_get_path(MDB_env *env, const char **arg)
8582 *arg = env->me_path;
8587 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
8596 /** Common code for #mdb_stat() and #mdb_env_stat().
8597 * @param[in] env the environment to operate in.
8598 * @param[in] db the #MDB_db record containing the stats to return.
8599 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
8600 * @return 0, this function always succeeds.
8603 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
8605 arg->ms_psize = env->me_psize;
8606 arg->ms_depth = db->md_depth;
8607 arg->ms_branch_pages = db->md_branch_pages;
8608 arg->ms_leaf_pages = db->md_leaf_pages;
8609 arg->ms_overflow_pages = db->md_overflow_pages;
8610 arg->ms_entries = db->md_entries;
8615 mdb_env_stat(MDB_env *env, MDB_stat *arg)
8619 if (env == NULL || arg == NULL)
8622 toggle = mdb_env_pick_meta(env);
8624 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
8628 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
8632 if (env == NULL || arg == NULL)
8635 toggle = mdb_env_pick_meta(env);
8636 arg->me_mapaddr = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : 0;
8637 arg->me_mapsize = env->me_mapsize;
8638 arg->me_maxreaders = env->me_maxreaders;
8640 /* me_numreaders may be zero if this process never used any readers. Use
8641 * the shared numreader count if it exists.
8643 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : env->me_numreaders;
8645 arg->me_last_pgno = env->me_metas[toggle]->mm_last_pg;
8646 arg->me_last_txnid = env->me_metas[toggle]->mm_txnid;
8650 /** Set the default comparison functions for a database.
8651 * Called immediately after a database is opened to set the defaults.
8652 * The user can then override them with #mdb_set_compare() or
8653 * #mdb_set_dupsort().
8654 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
8655 * @param[in] dbi A database handle returned by #mdb_dbi_open()
8658 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
8660 uint16_t f = txn->mt_dbs[dbi].md_flags;
8662 txn->mt_dbxs[dbi].md_cmp =
8663 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
8664 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
8666 txn->mt_dbxs[dbi].md_dcmp =
8667 !(f & MDB_DUPSORT) ? 0 :
8668 ((f & MDB_INTEGERDUP)
8669 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
8670 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
8673 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
8678 int rc, dbflag, exact;
8679 unsigned int unused = 0;
8682 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
8683 mdb_default_cmp(txn, FREE_DBI);
8686 if ((flags & VALID_FLAGS) != flags)
8688 if (txn->mt_flags & MDB_TXN_ERROR)
8694 if (flags & PERSISTENT_FLAGS) {
8695 uint16_t f2 = flags & PERSISTENT_FLAGS;
8696 /* make sure flag changes get committed */
8697 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
8698 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
8699 txn->mt_flags |= MDB_TXN_DIRTY;
8702 mdb_default_cmp(txn, MAIN_DBI);
8706 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
8707 mdb_default_cmp(txn, MAIN_DBI);
8710 /* Is the DB already open? */
8712 for (i=2; i<txn->mt_numdbs; i++) {
8713 if (!txn->mt_dbxs[i].md_name.mv_size) {
8714 /* Remember this free slot */
8715 if (!unused) unused = i;
8718 if (len == txn->mt_dbxs[i].md_name.mv_size &&
8719 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
8725 /* If no free slot and max hit, fail */
8726 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
8727 return MDB_DBS_FULL;
8729 /* Cannot mix named databases with some mainDB flags */
8730 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
8731 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
8733 /* Find the DB info */
8734 dbflag = DB_NEW|DB_VALID;
8737 key.mv_data = (void *)name;
8738 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
8739 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
8740 if (rc == MDB_SUCCESS) {
8741 /* make sure this is actually a DB */
8742 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
8743 if (!(node->mn_flags & F_SUBDATA))
8744 return MDB_INCOMPATIBLE;
8745 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
8746 /* Create if requested */
8748 data.mv_size = sizeof(MDB_db);
8749 data.mv_data = &dummy;
8750 memset(&dummy, 0, sizeof(dummy));
8751 dummy.md_root = P_INVALID;
8752 dummy.md_flags = flags & PERSISTENT_FLAGS;
8753 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
8757 /* OK, got info, add to table */
8758 if (rc == MDB_SUCCESS) {
8759 unsigned int slot = unused ? unused : txn->mt_numdbs;
8760 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
8761 txn->mt_dbxs[slot].md_name.mv_size = len;
8762 txn->mt_dbxs[slot].md_rel = NULL;
8763 txn->mt_dbflags[slot] = dbflag;
8764 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
8766 mdb_default_cmp(txn, slot);
8775 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
8777 if (!arg || !TXN_DBI_EXIST(txn, dbi))
8780 if (txn->mt_flags & MDB_TXN_ERROR)
8783 if (txn->mt_dbflags[dbi] & DB_STALE) {
8786 /* Stale, must read the DB's root. cursor_init does it for us. */
8787 mdb_cursor_init(&mc, txn, dbi, &mx);
8789 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
8792 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
8795 if (dbi <= MAIN_DBI || dbi >= env->me_maxdbs)
8797 ptr = env->me_dbxs[dbi].md_name.mv_data;
8798 env->me_dbxs[dbi].md_name.mv_data = NULL;
8799 env->me_dbxs[dbi].md_name.mv_size = 0;
8800 env->me_dbflags[dbi] = 0;
8804 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
8806 /* We could return the flags for the FREE_DBI too but what's the point? */
8807 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
8809 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
8813 /** Add all the DB's pages to the free list.
8814 * @param[in] mc Cursor on the DB to free.
8815 * @param[in] subs non-Zero to check for sub-DBs in this DB.
8816 * @return 0 on success, non-zero on failure.
8819 mdb_drop0(MDB_cursor *mc, int subs)
8823 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
8824 if (rc == MDB_SUCCESS) {
8825 MDB_txn *txn = mc->mc_txn;
8830 /* LEAF2 pages have no nodes, cannot have sub-DBs */
8831 if (IS_LEAF2(mc->mc_pg[mc->mc_top]))
8834 mdb_cursor_copy(mc, &mx);
8835 while (mc->mc_snum > 0) {
8836 MDB_page *mp = mc->mc_pg[mc->mc_top];
8837 unsigned n = NUMKEYS(mp);
8839 for (i=0; i<n; i++) {
8840 ni = NODEPTR(mp, i);
8841 if (ni->mn_flags & F_BIGDATA) {
8844 memcpy(&pg, NODEDATA(ni), sizeof(pg));
8845 rc = mdb_page_get(txn, pg, &omp, NULL);
8848 mdb_cassert(mc, IS_OVERFLOW(omp));
8849 rc = mdb_midl_append_range(&txn->mt_free_pgs,
8853 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
8854 mdb_xcursor_init1(mc, ni);
8855 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
8861 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
8863 for (i=0; i<n; i++) {
8865 ni = NODEPTR(mp, i);
8868 mdb_midl_xappend(txn->mt_free_pgs, pg);
8873 mc->mc_ki[mc->mc_top] = i;
8874 rc = mdb_cursor_sibling(mc, 1);
8876 if (rc != MDB_NOTFOUND)
8878 /* no more siblings, go back to beginning
8879 * of previous level.
8883 for (i=1; i<mc->mc_snum; i++) {
8885 mc->mc_pg[i] = mx.mc_pg[i];
8890 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
8893 txn->mt_flags |= MDB_TXN_ERROR;
8894 } else if (rc == MDB_NOTFOUND) {
8900 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
8902 MDB_cursor *mc, *m2;
8905 if ((unsigned)del > 1 || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
8908 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
8911 rc = mdb_cursor_open(txn, dbi, &mc);
8915 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
8916 /* Invalidate the dropped DB's cursors */
8917 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
8918 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
8922 /* Can't delete the main DB */
8923 if (del && dbi > MAIN_DBI) {
8924 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, 0);
8926 txn->mt_dbflags[dbi] = DB_STALE;
8927 mdb_dbi_close(txn->mt_env, dbi);
8929 txn->mt_flags |= MDB_TXN_ERROR;
8932 /* reset the DB record, mark it dirty */
8933 txn->mt_dbflags[dbi] |= DB_DIRTY;
8934 txn->mt_dbs[dbi].md_depth = 0;
8935 txn->mt_dbs[dbi].md_branch_pages = 0;
8936 txn->mt_dbs[dbi].md_leaf_pages = 0;
8937 txn->mt_dbs[dbi].md_overflow_pages = 0;
8938 txn->mt_dbs[dbi].md_entries = 0;
8939 txn->mt_dbs[dbi].md_root = P_INVALID;
8941 txn->mt_flags |= MDB_TXN_DIRTY;
8944 mdb_cursor_close(mc);
8948 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
8950 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
8953 txn->mt_dbxs[dbi].md_cmp = cmp;
8957 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
8959 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
8962 txn->mt_dbxs[dbi].md_dcmp = cmp;
8966 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
8968 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
8971 txn->mt_dbxs[dbi].md_rel = rel;
8975 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
8977 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
8980 txn->mt_dbxs[dbi].md_relctx = ctx;
8984 int mdb_env_get_maxkeysize(MDB_env *env)
8986 return ENV_MAXKEY(env);
8989 int mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
8991 unsigned int i, rdrs;
8994 int rc = 0, first = 1;
8998 if (!env->me_txns) {
8999 return func("(no reader locks)\n", ctx);
9001 rdrs = env->me_txns->mti_numreaders;
9002 mr = env->me_txns->mti_readers;
9003 for (i=0; i<rdrs; i++) {
9005 txnid_t txnid = mr[i].mr_txnid;
9006 sprintf(buf, txnid == (txnid_t)-1 ?
9007 "%10d %"Z"x -\n" : "%10d %"Z"x %"Z"u\n",
9008 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
9011 rc = func(" pid thread txnid\n", ctx);
9015 rc = func(buf, ctx);
9021 rc = func("(no active readers)\n", ctx);
9026 /** Insert pid into list if not already present.
9027 * return -1 if already present.
9029 static int mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
9031 /* binary search of pid in list */
9033 unsigned cursor = 1;
9035 unsigned n = ids[0];
9038 unsigned pivot = n >> 1;
9039 cursor = base + pivot + 1;
9040 val = pid - ids[cursor];
9045 } else if ( val > 0 ) {
9050 /* found, so it's a duplicate */
9059 for (n = ids[0]; n > cursor; n--)
9065 int mdb_reader_check(MDB_env *env, int *dead)
9067 unsigned int i, j, rdrs;
9069 MDB_PID_T *pids, pid;
9078 rdrs = env->me_txns->mti_numreaders;
9079 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
9083 mr = env->me_txns->mti_readers;
9084 for (i=0; i<rdrs; i++) {
9085 if (mr[i].mr_pid && mr[i].mr_pid != env->me_pid) {
9087 if (mdb_pid_insert(pids, pid) == 0) {
9088 if (!mdb_reader_pid(env, Pidcheck, pid)) {
9090 /* Recheck, a new process may have reused pid */
9091 if (!mdb_reader_pid(env, Pidcheck, pid)) {
9092 for (j=i; j<rdrs; j++)
9093 if (mr[j].mr_pid == pid) {
9094 DPRINTF(("clear stale reader pid %u txn %"Z"d",
9095 (unsigned) pid, mr[j].mr_txnid));
9100 UNLOCK_MUTEX_R(env);