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.
41 /** getpid() returns int; MinGW defines pid_t but MinGW64 typedefs it
42 * as int64 which is wrong. MSVC doesn't define it at all, so just
46 #define MDB_THR_T DWORD
47 #include <sys/types.h>
50 # include <sys/param.h>
52 # define LITTLE_ENDIAN 1234
53 # define BIG_ENDIAN 4321
54 # define BYTE_ORDER LITTLE_ENDIAN
56 # define SSIZE_MAX INT_MAX
60 #include <sys/types.h>
62 #define MDB_PID_T pid_t
63 #define MDB_THR_T pthread_t
64 #include <sys/param.h>
67 #ifdef HAVE_SYS_FILE_H
83 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
84 #include <netinet/in.h>
85 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
88 #if defined(__APPLE__) || defined (BSD)
89 # define MDB_USE_POSIX_SEM 1
90 # define MDB_FDATASYNC fsync
91 #elif defined(ANDROID)
92 # define MDB_FDATASYNC fsync
97 #ifdef MDB_USE_POSIX_SEM
98 # define MDB_USE_HASH 1
99 #include <semaphore.h>
104 #include <valgrind/memcheck.h>
105 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
106 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
107 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
108 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
109 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
111 #define VGMEMP_CREATE(h,r,z)
112 #define VGMEMP_ALLOC(h,a,s)
113 #define VGMEMP_FREE(h,a)
114 #define VGMEMP_DESTROY(h)
115 #define VGMEMP_DEFINED(a,s)
119 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
120 /* Solaris just defines one or the other */
121 # define LITTLE_ENDIAN 1234
122 # define BIG_ENDIAN 4321
123 # ifdef _LITTLE_ENDIAN
124 # define BYTE_ORDER LITTLE_ENDIAN
126 # define BYTE_ORDER BIG_ENDIAN
129 # define BYTE_ORDER __BYTE_ORDER
133 #ifndef LITTLE_ENDIAN
134 #define LITTLE_ENDIAN __LITTLE_ENDIAN
137 #define BIG_ENDIAN __BIG_ENDIAN
140 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
141 #define MISALIGNED_OK 1
147 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
148 # error "Unknown or unsupported endianness (BYTE_ORDER)"
149 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
150 # error "Two's complement, reasonably sized integer types, please"
154 /** Put infrequently used env functions in separate section */
156 # define ESECT __attribute__ ((section("__TEXT,text_env")))
158 # define ESECT __attribute__ ((section("text_env")))
164 /** @defgroup internal LMDB Internals
167 /** @defgroup compat Compatibility Macros
168 * A bunch of macros to minimize the amount of platform-specific ifdefs
169 * needed throughout the rest of the code. When the features this library
170 * needs are similar enough to POSIX to be hidden in a one-or-two line
171 * replacement, this macro approach is used.
175 /** Features under development */
180 /** Wrapper around __func__, which is a C99 feature */
181 #if __STDC_VERSION__ >= 199901L
182 # define mdb_func_ __func__
183 #elif __GNUC__ >= 2 || _MSC_VER >= 1300
184 # define mdb_func_ __FUNCTION__
186 /* If a debug message says <mdb_unknown>(), update the #if statements above */
187 # define mdb_func_ "<mdb_unknown>"
191 #define MDB_USE_HASH 1
192 #define MDB_PIDLOCK 0
193 #define THREAD_RET DWORD
194 #define pthread_t HANDLE
195 #define pthread_mutex_t HANDLE
196 #define pthread_cond_t HANDLE
197 #define pthread_key_t DWORD
198 #define pthread_self() GetCurrentThreadId()
199 #define pthread_key_create(x,y) \
200 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
201 #define pthread_key_delete(x) TlsFree(x)
202 #define pthread_getspecific(x) TlsGetValue(x)
203 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
204 #define pthread_mutex_unlock(x) ReleaseMutex(*x)
205 #define pthread_mutex_lock(x) WaitForSingleObject(*x, INFINITE)
206 #define pthread_cond_signal(x) SetEvent(*x)
207 #define pthread_cond_wait(cond,mutex) do{SignalObjectAndWait(*mutex, *cond, INFINITE, FALSE); WaitForSingleObject(*mutex, INFINITE);}while(0)
208 #define THREAD_CREATE(thr,start,arg) thr=CreateThread(NULL,0,start,arg,0,NULL)
209 #define THREAD_FINISH(thr) WaitForSingleObject(thr, INFINITE)
210 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_rmutex)
211 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_rmutex)
212 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_wmutex)
213 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_wmutex)
214 #define getpid() GetCurrentProcessId()
215 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
216 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
217 #define ErrCode() GetLastError()
218 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
219 #define close(fd) (CloseHandle(fd) ? 0 : -1)
220 #define munmap(ptr,len) UnmapViewOfFile(ptr)
221 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
222 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
224 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
228 #define THREAD_RET void *
229 #define THREAD_CREATE(thr,start,arg) pthread_create(&thr,NULL,start,arg)
230 #define THREAD_FINISH(thr) pthread_join(thr,NULL)
231 #define Z "z" /**< printf format modifier for size_t */
233 /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
234 #define MDB_PIDLOCK 1
236 #ifdef MDB_USE_POSIX_SEM
238 #define LOCK_MUTEX_R(env) mdb_sem_wait((env)->me_rmutex)
239 #define UNLOCK_MUTEX_R(env) sem_post((env)->me_rmutex)
240 #define LOCK_MUTEX_W(env) mdb_sem_wait((env)->me_wmutex)
241 #define UNLOCK_MUTEX_W(env) sem_post((env)->me_wmutex)
244 mdb_sem_wait(sem_t *sem)
247 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
252 /** Lock the reader mutex.
254 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
255 /** Unlock the reader mutex.
257 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
259 /** Lock the writer mutex.
260 * Only a single write transaction is allowed at a time. Other writers
261 * will block waiting for this mutex.
263 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
264 /** Unlock the writer mutex.
266 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
267 #endif /* MDB_USE_POSIX_SEM */
269 /** Get the error code for the last failed system function.
271 #define ErrCode() errno
273 /** An abstraction for a file handle.
274 * On POSIX systems file handles are small integers. On Windows
275 * they're opaque pointers.
279 /** A value for an invalid file handle.
280 * Mainly used to initialize file variables and signify that they are
283 #define INVALID_HANDLE_VALUE (-1)
285 /** Get the size of a memory page for the system.
286 * This is the basic size that the platform's memory manager uses, and is
287 * fundamental to the use of memory-mapped files.
289 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
292 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
295 #define MNAME_LEN (sizeof(pthread_mutex_t))
301 /** A flag for opening a file and requesting synchronous data writes.
302 * This is only used when writing a meta page. It's not strictly needed;
303 * we could just do a normal write and then immediately perform a flush.
304 * But if this flag is available it saves us an extra system call.
306 * @note If O_DSYNC is undefined but exists in /usr/include,
307 * preferably set some compiler flag to get the definition.
308 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
311 # define MDB_DSYNC O_DSYNC
315 /** Function for flushing the data of a file. Define this to fsync
316 * if fdatasync() is not supported.
318 #ifndef MDB_FDATASYNC
319 # define MDB_FDATASYNC fdatasync
323 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
334 /** A page number in the database.
335 * Note that 64 bit page numbers are overkill, since pages themselves
336 * already represent 12-13 bits of addressable memory, and the OS will
337 * always limit applications to a maximum of 63 bits of address space.
339 * @note In the #MDB_node structure, we only store 48 bits of this value,
340 * which thus limits us to only 60 bits of addressable data.
342 typedef MDB_ID pgno_t;
344 /** A transaction ID.
345 * See struct MDB_txn.mt_txnid for details.
347 typedef MDB_ID txnid_t;
349 /** @defgroup debug Debug Macros
353 /** Enable debug output. Needs variable argument macros (a C99 feature).
354 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
355 * read from and written to the database (used for free space management).
361 static int mdb_debug;
362 static txnid_t mdb_debug_start;
364 /** Print a debug message with printf formatting.
365 * Requires double parenthesis around 2 or more args.
367 # define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
368 # define DPRINTF0(fmt, ...) \
369 fprintf(stderr, "%s:%d " fmt "\n", mdb_func_, __LINE__, __VA_ARGS__)
371 # define DPRINTF(args) ((void) 0)
373 /** Print a debug string.
374 * The string is printed literally, with no format processing.
376 #define DPUTS(arg) DPRINTF(("%s", arg))
377 /** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
379 (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
382 /** @brief The maximum size of a database page.
384 * It is 32k or 64k, since value-PAGEBASE must fit in
385 * #MDB_page.%mp_upper.
387 * LMDB will use database pages < OS pages if needed.
388 * That causes more I/O in write transactions: The OS must
389 * know (read) the whole page before writing a partial page.
391 * Note that we don't currently support Huge pages. On Linux,
392 * regular data files cannot use Huge pages, and in general
393 * Huge pages aren't actually pageable. We rely on the OS
394 * demand-pager to read our data and page it out when memory
395 * pressure from other processes is high. So until OSs have
396 * actual paging support for Huge pages, they're not viable.
398 #define MAX_PAGESIZE (PAGEBASE ? 0x10000 : 0x8000)
400 /** The minimum number of keys required in a database page.
401 * Setting this to a larger value will place a smaller bound on the
402 * maximum size of a data item. Data items larger than this size will
403 * be pushed into overflow pages instead of being stored directly in
404 * the B-tree node. This value used to default to 4. With a page size
405 * of 4096 bytes that meant that any item larger than 1024 bytes would
406 * go into an overflow page. That also meant that on average 2-3KB of
407 * each overflow page was wasted space. The value cannot be lower than
408 * 2 because then there would no longer be a tree structure. With this
409 * value, items larger than 2KB will go into overflow pages, and on
410 * average only 1KB will be wasted.
412 #define MDB_MINKEYS 2
414 /** A stamp that identifies a file as an LMDB file.
415 * There's nothing special about this value other than that it is easily
416 * recognizable, and it will reflect any byte order mismatches.
418 #define MDB_MAGIC 0xBEEFC0DE
420 /** The version number for a database's datafile format. */
421 #define MDB_DATA_VERSION ((MDB_DEVEL) ? 999 : 1)
422 /** The version number for a database's lockfile format. */
423 #define MDB_LOCK_VERSION 1
425 /** @brief The max size of a key we can write, or 0 for dynamic max.
427 * Define this as 0 to compute the max from the page size. 511
428 * is default for backwards compat: liblmdb <= 0.9.10 can break
429 * when modifying a DB with keys/dupsort data bigger than its max.
430 * #MDB_DEVEL sets the default to 0.
432 * Data items in an #MDB_DUPSORT database are also limited to
433 * this size, since they're actually keys of a sub-DB. Keys and
434 * #MDB_DUPSORT data items must fit on a node in a regular page.
436 #ifndef MDB_MAXKEYSIZE
437 #define MDB_MAXKEYSIZE ((MDB_DEVEL) ? 0 : 511)
440 /** The maximum size of a key we can write to the environment. */
442 #define ENV_MAXKEY(env) (MDB_MAXKEYSIZE)
444 #define ENV_MAXKEY(env) ((env)->me_maxkey)
447 /** @brief The maximum size of a data item.
449 * We only store a 32 bit value for node sizes.
451 #define MAXDATASIZE 0xffffffffUL
454 /** Key size which fits in a #DKBUF.
457 #define DKBUF_MAXKEYSIZE ((MDB_MAXKEYSIZE) > 0 ? (MDB_MAXKEYSIZE) : 511)
460 * This is used for printing a hex dump of a key's contents.
462 #define DKBUF char kbuf[DKBUF_MAXKEYSIZE*2+1]
463 /** Display a key in hex.
465 * Invoke a function to display a key in hex.
467 #define DKEY(x) mdb_dkey(x, kbuf)
473 /** An invalid page number.
474 * Mainly used to denote an empty tree.
476 #define P_INVALID (~(pgno_t)0)
478 /** Test if the flags \b f are set in a flag word \b w. */
479 #define F_ISSET(w, f) (((w) & (f)) == (f))
481 /** Round \b n up to an even number. */
482 #define EVEN(n) (((n) + 1U) & -2) /* sign-extending -2 to match n+1U */
484 /** Used for offsets within a single page.
485 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
488 typedef uint16_t indx_t;
490 /** Default size of memory map.
491 * This is certainly too small for any actual applications. Apps should always set
492 * the size explicitly using #mdb_env_set_mapsize().
494 #define DEFAULT_MAPSIZE 1048576
496 /** @defgroup readers Reader Lock Table
497 * Readers don't acquire any locks for their data access. Instead, they
498 * simply record their transaction ID in the reader table. The reader
499 * mutex is needed just to find an empty slot in the reader table. The
500 * slot's address is saved in thread-specific data so that subsequent read
501 * transactions started by the same thread need no further locking to proceed.
503 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
505 * No reader table is used if the database is on a read-only filesystem, or
506 * if #MDB_NOLOCK is set.
508 * Since the database uses multi-version concurrency control, readers don't
509 * actually need any locking. This table is used to keep track of which
510 * readers are using data from which old transactions, so that we'll know
511 * when a particular old transaction is no longer in use. Old transactions
512 * that have discarded any data pages can then have those pages reclaimed
513 * for use by a later write transaction.
515 * The lock table is constructed such that reader slots are aligned with the
516 * processor's cache line size. Any slot is only ever used by one thread.
517 * This alignment guarantees that there will be no contention or cache
518 * thrashing as threads update their own slot info, and also eliminates
519 * any need for locking when accessing a slot.
521 * A writer thread will scan every slot in the table to determine the oldest
522 * outstanding reader transaction. Any freed pages older than this will be
523 * reclaimed by the writer. The writer doesn't use any locks when scanning
524 * this table. This means that there's no guarantee that the writer will
525 * see the most up-to-date reader info, but that's not required for correct
526 * operation - all we need is to know the upper bound on the oldest reader,
527 * we don't care at all about the newest reader. So the only consequence of
528 * reading stale information here is that old pages might hang around a
529 * while longer before being reclaimed. That's actually good anyway, because
530 * the longer we delay reclaiming old pages, the more likely it is that a
531 * string of contiguous pages can be found after coalescing old pages from
532 * many old transactions together.
535 /** Number of slots in the reader table.
536 * This value was chosen somewhat arbitrarily. 126 readers plus a
537 * couple mutexes fit exactly into 8KB on my development machine.
538 * Applications should set the table size using #mdb_env_set_maxreaders().
540 #define DEFAULT_READERS 126
542 /** The size of a CPU cache line in bytes. We want our lock structures
543 * aligned to this size to avoid false cache line sharing in the
545 * This value works for most CPUs. For Itanium this should be 128.
551 /** The information we store in a single slot of the reader table.
552 * In addition to a transaction ID, we also record the process and
553 * thread ID that owns a slot, so that we can detect stale information,
554 * e.g. threads or processes that went away without cleaning up.
555 * @note We currently don't check for stale records. We simply re-init
556 * the table when we know that we're the only process opening the
559 typedef struct MDB_rxbody {
560 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
561 * Multiple readers that start at the same time will probably have the
562 * same ID here. Again, it's not important to exclude them from
563 * anything; all we need to know is which version of the DB they
564 * started from so we can avoid overwriting any data used in that
565 * particular version.
568 /** The process ID of the process owning this reader txn. */
570 /** The thread ID of the thread owning this txn. */
574 /** The actual reader record, with cacheline padding. */
575 typedef struct MDB_reader {
578 /** shorthand for mrb_txnid */
579 #define mr_txnid mru.mrx.mrb_txnid
580 #define mr_pid mru.mrx.mrb_pid
581 #define mr_tid mru.mrx.mrb_tid
582 /** cache line alignment */
583 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
587 /** The header for the reader table.
588 * The table resides in a memory-mapped file. (This is a different file
589 * than is used for the main database.)
591 * For POSIX the actual mutexes reside in the shared memory of this
592 * mapped file. On Windows, mutexes are named objects allocated by the
593 * kernel; we store the mutex names in this mapped file so that other
594 * processes can grab them. This same approach is also used on
595 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
596 * process-shared POSIX mutexes. For these cases where a named object
597 * is used, the object name is derived from a 64 bit FNV hash of the
598 * environment pathname. As such, naming collisions are extremely
599 * unlikely. If a collision occurs, the results are unpredictable.
601 typedef struct MDB_txbody {
602 /** Stamp identifying this as an LMDB file. It must be set
605 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
607 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
608 char mtb_rmname[MNAME_LEN];
610 /** Mutex protecting access to this table.
611 * This is the reader lock that #LOCK_MUTEX_R acquires.
613 pthread_mutex_t mtb_mutex;
615 /** The ID of the last transaction committed to the database.
616 * This is recorded here only for convenience; the value can always
617 * be determined by reading the main database meta pages.
620 /** The number of slots that have been used in the reader table.
621 * This always records the maximum count, it is not decremented
622 * when readers release their slots.
624 unsigned mtb_numreaders;
627 /** The actual reader table definition. */
628 typedef struct MDB_txninfo {
631 #define mti_magic mt1.mtb.mtb_magic
632 #define mti_format mt1.mtb.mtb_format
633 #define mti_mutex mt1.mtb.mtb_mutex
634 #define mti_rmname mt1.mtb.mtb_rmname
635 #define mti_txnid mt1.mtb.mtb_txnid
636 #define mti_numreaders mt1.mtb.mtb_numreaders
637 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
640 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
641 char mt2_wmname[MNAME_LEN];
642 #define mti_wmname mt2.mt2_wmname
644 pthread_mutex_t mt2_wmutex;
645 #define mti_wmutex mt2.mt2_wmutex
647 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
649 MDB_reader mti_readers[1];
652 /** Lockfile format signature: version, features and field layout */
653 #define MDB_LOCK_FORMAT \
655 ((MDB_LOCK_VERSION) \
656 /* Flags which describe functionality */ \
657 + (((MDB_PIDLOCK) != 0) << 16)))
660 /** Common header for all page types.
661 * Overflow records occupy a number of contiguous pages with no
662 * headers on any page after the first.
664 typedef struct MDB_page {
665 #define mp_pgno mp_p.p_pgno
666 #define mp_next mp_p.p_next
668 pgno_t p_pgno; /**< page number */
669 struct MDB_page *p_next; /**< for in-memory list of freed pages */
672 /** @defgroup mdb_page Page Flags
674 * Flags for the page headers.
677 #define P_BRANCH 0x01 /**< branch page */
678 #define P_LEAF 0x02 /**< leaf page */
679 #define P_OVERFLOW 0x04 /**< overflow page */
680 #define P_META 0x08 /**< meta page */
681 #define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
682 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
683 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
684 #define P_LOOSE 0x4000 /**< page was dirtied then freed, can be reused */
685 #define P_KEEP 0x8000 /**< leave this page alone during spill */
687 uint16_t mp_flags; /**< @ref mdb_page */
688 #define mp_lower mp_pb.pb.pb_lower
689 #define mp_upper mp_pb.pb.pb_upper
690 #define mp_pages mp_pb.pb_pages
693 indx_t pb_lower; /**< lower bound of free space */
694 indx_t pb_upper; /**< upper bound of free space */
696 uint32_t pb_pages; /**< number of overflow pages */
698 indx_t mp_ptrs[1]; /**< dynamic size */
701 /** Size of the page header, excluding dynamic data at the end */
702 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
704 /** Address of first usable data byte in a page, after the header */
705 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
707 /** ITS#7713, change PAGEBASE to handle 65536 byte pages */
708 #define PAGEBASE ((MDB_DEVEL) ? PAGEHDRSZ : 0)
710 /** Number of nodes on a page */
711 #define NUMKEYS(p) (((p)->mp_lower - (PAGEHDRSZ-PAGEBASE)) >> 1)
713 /** The amount of space remaining in the page */
714 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
716 /** The percentage of space used in the page, in tenths of a percent. */
717 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
718 ((env)->me_psize - PAGEHDRSZ))
719 /** The minimum page fill factor, in tenths of a percent.
720 * Pages emptier than this are candidates for merging.
722 #define FILL_THRESHOLD 250
724 /** Test if a page is a leaf page */
725 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
726 /** Test if a page is a LEAF2 page */
727 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
728 /** Test if a page is a branch page */
729 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
730 /** Test if a page is an overflow page */
731 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
732 /** Test if a page is a sub page */
733 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
735 /** The number of overflow pages needed to store the given size. */
736 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
738 /** Link in #MDB_txn.%mt_loose_pages list */
739 #define NEXT_LOOSE_PAGE(p) (*(MDB_page **)((p) + 2))
741 /** Header for a single key/data pair within a page.
742 * Used in pages of type #P_BRANCH and #P_LEAF without #P_LEAF2.
743 * We guarantee 2-byte alignment for 'MDB_node's.
745 typedef struct MDB_node {
746 /** lo and hi are used for data size on leaf nodes and for
747 * child pgno on branch nodes. On 64 bit platforms, flags
748 * is also used for pgno. (Branch nodes have no flags).
749 * They are in host byte order in case that lets some
750 * accesses be optimized into a 32-bit word access.
752 #if BYTE_ORDER == LITTLE_ENDIAN
753 unsigned short mn_lo, mn_hi; /**< part of data size or pgno */
755 unsigned short mn_hi, mn_lo;
757 /** @defgroup mdb_node Node Flags
759 * Flags for node headers.
762 #define F_BIGDATA 0x01 /**< data put on overflow page */
763 #define F_SUBDATA 0x02 /**< data is a sub-database */
764 #define F_DUPDATA 0x04 /**< data has duplicates */
766 /** valid flags for #mdb_node_add() */
767 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
770 unsigned short mn_flags; /**< @ref mdb_node */
771 unsigned short mn_ksize; /**< key size */
772 char mn_data[1]; /**< key and data are appended here */
775 /** Size of the node header, excluding dynamic data at the end */
776 #define NODESIZE offsetof(MDB_node, mn_data)
778 /** Bit position of top word in page number, for shifting mn_flags */
779 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
781 /** Size of a node in a branch page with a given key.
782 * This is just the node header plus the key, there is no data.
784 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
786 /** Size of a node in a leaf page with a given key and data.
787 * This is node header plus key plus data size.
789 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
791 /** Address of node \b i in page \b p */
792 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i] + PAGEBASE))
794 /** Address of the key for the node */
795 #define NODEKEY(node) (void *)((node)->mn_data)
797 /** Address of the data for a node */
798 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
800 /** Get the page number pointed to by a branch node */
801 #define NODEPGNO(node) \
802 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
803 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
804 /** Set the page number in a branch node */
805 #define SETPGNO(node,pgno) do { \
806 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
807 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
809 /** Get the size of the data in a leaf node */
810 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
811 /** Set the size of the data for a leaf node */
812 #define SETDSZ(node,size) do { \
813 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
814 /** The size of a key in a node */
815 #define NODEKSZ(node) ((node)->mn_ksize)
817 /** Copy a page number from src to dst */
819 #define COPY_PGNO(dst,src) dst = src
821 #if SIZE_MAX > 4294967295UL
822 #define COPY_PGNO(dst,src) do { \
823 unsigned short *s, *d; \
824 s = (unsigned short *)&(src); \
825 d = (unsigned short *)&(dst); \
832 #define COPY_PGNO(dst,src) do { \
833 unsigned short *s, *d; \
834 s = (unsigned short *)&(src); \
835 d = (unsigned short *)&(dst); \
841 /** The address of a key in a LEAF2 page.
842 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
843 * There are no node headers, keys are stored contiguously.
845 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
847 /** Set the \b node's key into \b keyptr, if requested. */
848 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
849 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
851 /** Set the \b node's key into \b key. */
852 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
854 /** Information about a single database in the environment. */
855 typedef struct MDB_db {
856 uint32_t md_pad; /**< also ksize for LEAF2 pages */
857 uint16_t md_flags; /**< @ref mdb_dbi_open */
858 uint16_t md_depth; /**< depth of this tree */
859 pgno_t md_branch_pages; /**< number of internal pages */
860 pgno_t md_leaf_pages; /**< number of leaf pages */
861 pgno_t md_overflow_pages; /**< number of overflow pages */
862 size_t md_entries; /**< number of data items */
863 pgno_t md_root; /**< the root page of this tree */
866 /** mdb_dbi_open flags */
867 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
868 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
869 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
870 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
872 /** Handle for the DB used to track free pages. */
874 /** Handle for the default DB. */
877 /** Meta page content.
878 * A meta page is the start point for accessing a database snapshot.
879 * Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
881 typedef struct MDB_meta {
882 /** Stamp identifying this as an LMDB file. It must be set
885 /** Version number of this lock file. Must be set to #MDB_DATA_VERSION. */
887 void *mm_address; /**< address for fixed mapping */
888 size_t mm_mapsize; /**< size of mmap region */
889 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
890 /** The size of pages used in this DB */
891 #define mm_psize mm_dbs[0].md_pad
892 /** Any persistent environment flags. @ref mdb_env */
893 #define mm_flags mm_dbs[0].md_flags
894 pgno_t mm_last_pg; /**< last used page in file */
895 txnid_t mm_txnid; /**< txnid that committed this page */
898 /** Buffer for a stack-allocated meta page.
899 * The members define size and alignment, and silence type
900 * aliasing warnings. They are not used directly; that could
901 * mean incorrectly using several union members in parallel.
903 typedef union MDB_metabuf {
906 char mm_pad[PAGEHDRSZ];
911 /** Auxiliary DB info.
912 * The information here is mostly static/read-only. There is
913 * only a single copy of this record in the environment.
915 typedef struct MDB_dbx {
916 MDB_val md_name; /**< name of the database */
917 MDB_cmp_func *md_cmp; /**< function for comparing keys */
918 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
919 MDB_rel_func *md_rel; /**< user relocate function */
920 void *md_relctx; /**< user-provided context for md_rel */
923 /** A database transaction.
924 * Every operation requires a transaction handle.
927 MDB_txn *mt_parent; /**< parent of a nested txn */
928 MDB_txn *mt_child; /**< nested txn under this txn */
929 pgno_t mt_next_pgno; /**< next unallocated page */
930 /** The ID of this transaction. IDs are integers incrementing from 1.
931 * Only committed write transactions increment the ID. If a transaction
932 * aborts, the ID may be re-used by the next writer.
935 MDB_env *mt_env; /**< the DB environment */
936 /** The list of pages that became unused during this transaction.
939 /** The list of loose pages that became unused and may be reused
940 * in this transaction, linked through #NEXT_LOOSE_PAGE(page).
942 MDB_page *mt_loose_pgs;
943 /** The sorted list of dirty pages we temporarily wrote to disk
944 * because the dirty list was full. page numbers in here are
945 * shifted left by 1, deleted slots have the LSB set.
947 MDB_IDL mt_spill_pgs;
949 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
951 /** For read txns: This thread/txn's reader table slot, or NULL. */
954 /** Array of records for each DB known in the environment. */
956 /** Array of MDB_db records for each known DB */
958 /** Array of sequence numbers for each DB handle */
959 unsigned int *mt_dbiseqs;
960 /** @defgroup mt_dbflag Transaction DB Flags
964 #define DB_DIRTY 0x01 /**< DB was modified or is DUPSORT data */
965 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
966 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
967 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
969 /** In write txns, array of cursors for each DB */
970 MDB_cursor **mt_cursors;
971 /** Array of flags for each DB */
972 unsigned char *mt_dbflags;
973 /** Number of DB records in use. This number only ever increments;
974 * we don't decrement it when individual DB handles are closed.
978 /** @defgroup mdb_txn Transaction Flags
982 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
983 #define MDB_TXN_ERROR 0x02 /**< txn is unusable after an error */
984 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
985 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
987 unsigned int mt_flags; /**< @ref mdb_txn */
988 /** #dirty_list room: Array size - \#dirty pages visible to this txn.
989 * Includes ancestor txns' dirty pages not hidden by other txns'
990 * dirty/spilled pages. Thus commit(nested txn) has room to merge
991 * dirty_list into mt_parent after freeing hidden mt_parent pages.
993 unsigned int mt_dirty_room;
996 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
997 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
998 * raise this on a 64 bit machine.
1000 #define CURSOR_STACK 32
1004 /** Cursors are used for all DB operations.
1005 * A cursor holds a path of (page pointer, key index) from the DB
1006 * root to a position in the DB, plus other state. #MDB_DUPSORT
1007 * cursors include an xcursor to the current data item. Write txns
1008 * track their cursors and keep them up to date when data moves.
1009 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
1010 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
1013 /** Next cursor on this DB in this txn */
1014 MDB_cursor *mc_next;
1015 /** Backup of the original cursor if this cursor is a shadow */
1016 MDB_cursor *mc_backup;
1017 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
1018 struct MDB_xcursor *mc_xcursor;
1019 /** The transaction that owns this cursor */
1021 /** The database handle this cursor operates on */
1023 /** The database record for this cursor */
1025 /** The database auxiliary record for this cursor */
1027 /** The @ref mt_dbflag for this database */
1028 unsigned char *mc_dbflag;
1029 unsigned short mc_snum; /**< number of pushed pages */
1030 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
1031 /** @defgroup mdb_cursor Cursor Flags
1033 * Cursor state flags.
1036 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
1037 #define C_EOF 0x02 /**< No more data */
1038 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
1039 #define C_DEL 0x08 /**< last op was a cursor_del */
1040 #define C_SPLITTING 0x20 /**< Cursor is in page_split */
1041 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
1043 unsigned int mc_flags; /**< @ref mdb_cursor */
1044 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
1045 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
1048 /** Context for sorted-dup records.
1049 * We could have gone to a fully recursive design, with arbitrarily
1050 * deep nesting of sub-databases. But for now we only handle these
1051 * levels - main DB, optional sub-DB, sorted-duplicate DB.
1053 typedef struct MDB_xcursor {
1054 /** A sub-cursor for traversing the Dup DB */
1055 MDB_cursor mx_cursor;
1056 /** The database record for this Dup DB */
1058 /** The auxiliary DB record for this Dup DB */
1060 /** The @ref mt_dbflag for this Dup DB */
1061 unsigned char mx_dbflag;
1064 /** State of FreeDB old pages, stored in the MDB_env */
1065 typedef struct MDB_pgstate {
1066 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1067 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1070 /** The database environment. */
1072 HANDLE me_fd; /**< The main data file */
1073 HANDLE me_lfd; /**< The lock file */
1074 HANDLE me_mfd; /**< just for writing the meta pages */
1075 /** Failed to update the meta page. Probably an I/O error. */
1076 #define MDB_FATAL_ERROR 0x80000000U
1077 /** We're explicitly changing the mapsize. */
1078 #define MDB_RESIZING 0x40000000U
1079 /** Some fields are initialized. */
1080 #define MDB_ENV_ACTIVE 0x20000000U
1081 /** me_txkey is set */
1082 #define MDB_ENV_TXKEY 0x10000000U
1083 uint32_t me_flags; /**< @ref mdb_env */
1084 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1085 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1086 unsigned int me_maxreaders; /**< size of the reader table */
1087 unsigned int me_numreaders; /**< max numreaders set by this env */
1088 MDB_dbi me_numdbs; /**< number of DBs opened */
1089 MDB_dbi me_maxdbs; /**< size of the DB table */
1090 MDB_PID_T me_pid; /**< process ID of this env */
1091 char *me_path; /**< path to the DB files */
1092 char *me_map; /**< the memory map of the data file */
1093 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1094 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
1095 void *me_pbuf; /**< scratch area for DUPSORT put() */
1096 MDB_txn *me_txn; /**< current write transaction */
1097 size_t me_mapsize; /**< size of the data memory map */
1098 off_t me_size; /**< current file size */
1099 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1100 MDB_dbx *me_dbxs; /**< array of static DB info */
1101 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1102 unsigned int *me_dbiseqs; /**< array of dbi sequence numbers */
1103 pthread_key_t me_txkey; /**< thread-key for readers */
1104 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1105 # define me_pglast me_pgstate.mf_pglast
1106 # define me_pghead me_pgstate.mf_pghead
1107 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1108 /** IDL of pages that became unused in a write txn */
1109 MDB_IDL me_free_pgs;
1110 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1111 MDB_ID2L me_dirty_list;
1112 /** Max number of freelist items that can fit in a single overflow page */
1114 /** Max size of a node on a page */
1115 unsigned int me_nodemax;
1116 #if !(MDB_MAXKEYSIZE)
1117 unsigned int me_maxkey; /**< max size of a key */
1119 int me_live_reader; /**< have liveness lock in reader table */
1121 int me_pidquery; /**< Used in OpenProcess */
1122 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
1124 #elif defined(MDB_USE_POSIX_SEM)
1125 sem_t *me_rmutex; /* Shared mutexes are not supported */
1128 void *me_userctx; /**< User-settable context */
1129 MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
1132 /** Nested transaction */
1133 typedef struct MDB_ntxn {
1134 MDB_txn mnt_txn; /**< the transaction */
1135 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1138 /** max number of pages to commit in one writev() call */
1139 #define MDB_COMMIT_PAGES 64
1140 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1141 #undef MDB_COMMIT_PAGES
1142 #define MDB_COMMIT_PAGES IOV_MAX
1145 /** max bytes to write in one call */
1146 #define MAX_WRITE (0x80000000U >> (sizeof(ssize_t) == 4))
1148 /** Check \b txn and \b dbi arguments to a function */
1149 #define TXN_DBI_EXIST(txn, dbi) \
1150 ((txn) && (dbi) < (txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & DB_VALID))
1152 /** Check for misused \b dbi handles */
1153 #define TXN_DBI_CHANGED(txn, dbi) \
1154 ((txn)->mt_dbiseqs[dbi] != (txn)->mt_env->me_dbiseqs[dbi])
1156 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1157 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1158 static int mdb_page_touch(MDB_cursor *mc);
1160 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp, int *lvl);
1161 static int mdb_page_search_root(MDB_cursor *mc,
1162 MDB_val *key, int modify);
1163 #define MDB_PS_MODIFY 1
1164 #define MDB_PS_ROOTONLY 2
1165 #define MDB_PS_FIRST 4
1166 #define MDB_PS_LAST 8
1167 static int mdb_page_search(MDB_cursor *mc,
1168 MDB_val *key, int flags);
1169 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1171 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1172 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1173 pgno_t newpgno, unsigned int nflags);
1175 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1176 static int mdb_env_pick_meta(const MDB_env *env);
1177 static int mdb_env_write_meta(MDB_txn *txn);
1178 #if !(defined(_WIN32) || defined(MDB_USE_POSIX_SEM)) /* Drop unused excl arg */
1179 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1181 static void mdb_env_close0(MDB_env *env, int excl);
1183 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1184 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1185 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1186 static void mdb_node_del(MDB_cursor *mc, int ksize);
1187 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1188 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
1189 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1190 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1191 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1193 static int mdb_rebalance(MDB_cursor *mc);
1194 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1196 static void mdb_cursor_pop(MDB_cursor *mc);
1197 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1199 static int mdb_cursor_del0(MDB_cursor *mc);
1200 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
1201 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1202 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1203 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1204 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1206 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1207 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1209 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1210 static void mdb_xcursor_init0(MDB_cursor *mc);
1211 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1213 static int mdb_drop0(MDB_cursor *mc, int subs);
1214 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1217 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1221 static SECURITY_DESCRIPTOR mdb_null_sd;
1222 static SECURITY_ATTRIBUTES mdb_all_sa;
1223 static int mdb_sec_inited;
1226 /** Return the library version info. */
1228 mdb_version(int *major, int *minor, int *patch)
1230 if (major) *major = MDB_VERSION_MAJOR;
1231 if (minor) *minor = MDB_VERSION_MINOR;
1232 if (patch) *patch = MDB_VERSION_PATCH;
1233 return MDB_VERSION_STRING;
1236 /** Table of descriptions for LMDB @ref errors */
1237 static char *const mdb_errstr[] = {
1238 "MDB_KEYEXIST: Key/data pair already exists",
1239 "MDB_NOTFOUND: No matching key/data pair found",
1240 "MDB_PAGE_NOTFOUND: Requested page not found",
1241 "MDB_CORRUPTED: Located page was wrong type",
1242 "MDB_PANIC: Update of meta page failed",
1243 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1244 "MDB_INVALID: File is not an LMDB file",
1245 "MDB_MAP_FULL: Environment mapsize limit reached",
1246 "MDB_DBS_FULL: Environment maxdbs limit reached",
1247 "MDB_READERS_FULL: Environment maxreaders limit reached",
1248 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1249 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1250 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1251 "MDB_PAGE_FULL: Internal error - page has no more space",
1252 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1253 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1254 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1255 "MDB_BAD_TXN: Transaction cannot recover - it must be aborted",
1256 "MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
1257 "MDB_BAD_DBI: The specified DBI handle was closed/changed unexpectedly",
1261 mdb_strerror(int err)
1264 /** HACK: pad 4KB on stack over the buf. Return system msgs in buf.
1265 * This works as long as no function between the call to mdb_strerror
1266 * and the actual use of the message uses more than 4K of stack.
1269 char buf[1024], *ptr = buf;
1273 return ("Successful return: 0");
1275 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1276 i = err - MDB_KEYEXIST;
1277 return mdb_errstr[i];
1281 /* These are the C-runtime error codes we use. The comment indicates
1282 * their numeric value, and the Win32 error they would correspond to
1283 * if the error actually came from a Win32 API. A major mess, we should
1284 * have used LMDB-specific error codes for everything.
1287 case ENOENT: /* 2, FILE_NOT_FOUND */
1288 case EIO: /* 5, ACCESS_DENIED */
1289 case ENOMEM: /* 12, INVALID_ACCESS */
1290 case EACCES: /* 13, INVALID_DATA */
1291 case EBUSY: /* 16, CURRENT_DIRECTORY */
1292 case EINVAL: /* 22, BAD_COMMAND */
1293 case ENOSPC: /* 28, OUT_OF_PAPER */
1294 return strerror(err);
1299 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1300 FORMAT_MESSAGE_IGNORE_INSERTS,
1301 NULL, err, 0, ptr, sizeof(buf), pad);
1304 return strerror(err);
1308 /** assert(3) variant in cursor context */
1309 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1310 /** assert(3) variant in transaction context */
1311 #define mdb_tassert(mc, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1312 /** assert(3) variant in environment context */
1313 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1316 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1317 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1320 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1321 const char *func, const char *file, int line)
1324 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1325 file, line, expr_txt, func);
1326 if (env->me_assert_func)
1327 env->me_assert_func(env, buf);
1328 fprintf(stderr, "%s\n", buf);
1332 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1336 /** Return the page number of \b mp which may be sub-page, for debug output */
1338 mdb_dbg_pgno(MDB_page *mp)
1341 COPY_PGNO(ret, mp->mp_pgno);
1345 /** Display a key in hexadecimal and return the address of the result.
1346 * @param[in] key the key to display
1347 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1348 * @return The key in hexadecimal form.
1351 mdb_dkey(MDB_val *key, char *buf)
1354 unsigned char *c = key->mv_data;
1360 if (key->mv_size > DKBUF_MAXKEYSIZE)
1361 return "MDB_MAXKEYSIZE";
1362 /* may want to make this a dynamic check: if the key is mostly
1363 * printable characters, print it as-is instead of converting to hex.
1367 for (i=0; i<key->mv_size; i++)
1368 ptr += sprintf(ptr, "%02x", *c++);
1370 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1376 mdb_leafnode_type(MDB_node *n)
1378 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1379 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1380 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1383 /** Display all the keys in the page. */
1385 mdb_page_list(MDB_page *mp)
1387 pgno_t pgno = mdb_dbg_pgno(mp);
1388 const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
1390 unsigned int i, nkeys, nsize, total = 0;
1394 switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1395 case P_BRANCH: type = "Branch page"; break;
1396 case P_LEAF: type = "Leaf page"; break;
1397 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1398 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1399 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1401 fprintf(stderr, "Overflow page %"Z"u pages %u%s\n",
1402 pgno, mp->mp_pages, state);
1405 fprintf(stderr, "Meta-page %"Z"u txnid %"Z"u\n",
1406 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1409 fprintf(stderr, "Bad page %"Z"u flags 0x%u\n", pgno, mp->mp_flags);
1413 nkeys = NUMKEYS(mp);
1414 fprintf(stderr, "%s %"Z"u numkeys %d%s\n", type, pgno, nkeys, state);
1416 for (i=0; i<nkeys; i++) {
1417 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1418 key.mv_size = nsize = mp->mp_pad;
1419 key.mv_data = LEAF2KEY(mp, i, nsize);
1421 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1424 node = NODEPTR(mp, i);
1425 key.mv_size = node->mn_ksize;
1426 key.mv_data = node->mn_data;
1427 nsize = NODESIZE + key.mv_size;
1428 if (IS_BRANCH(mp)) {
1429 fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
1433 if (F_ISSET(node->mn_flags, F_BIGDATA))
1434 nsize += sizeof(pgno_t);
1436 nsize += NODEDSZ(node);
1438 nsize += sizeof(indx_t);
1439 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1440 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1442 total = EVEN(total);
1444 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1445 IS_LEAF2(mp) ? PAGEHDRSZ : PAGEBASE + mp->mp_lower, total, SIZELEFT(mp));
1449 mdb_cursor_chk(MDB_cursor *mc)
1455 if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1456 for (i=0; i<mc->mc_top; i++) {
1458 node = NODEPTR(mp, mc->mc_ki[i]);
1459 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1462 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1468 /** Count all the pages in each DB and in the freelist
1469 * and make sure it matches the actual number of pages
1471 * All named DBs must be open for a correct count.
1473 static void mdb_audit(MDB_txn *txn)
1477 MDB_ID freecount, count;
1482 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1483 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1484 freecount += *(MDB_ID *)data.mv_data;
1485 mdb_tassert(txn, rc == MDB_NOTFOUND);
1488 for (i = 0; i<txn->mt_numdbs; i++) {
1490 if (!(txn->mt_dbflags[i] & DB_VALID))
1492 mdb_cursor_init(&mc, txn, i, &mx);
1493 if (txn->mt_dbs[i].md_root == P_INVALID)
1495 count += txn->mt_dbs[i].md_branch_pages +
1496 txn->mt_dbs[i].md_leaf_pages +
1497 txn->mt_dbs[i].md_overflow_pages;
1498 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1499 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1500 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
1503 mp = mc.mc_pg[mc.mc_top];
1504 for (j=0; j<NUMKEYS(mp); j++) {
1505 MDB_node *leaf = NODEPTR(mp, j);
1506 if (leaf->mn_flags & F_SUBDATA) {
1508 memcpy(&db, NODEDATA(leaf), sizeof(db));
1509 count += db.md_branch_pages + db.md_leaf_pages +
1510 db.md_overflow_pages;
1514 mdb_tassert(txn, rc == MDB_NOTFOUND);
1517 if (freecount + count + 2 /* metapages */ != txn->mt_next_pgno) {
1518 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1519 txn->mt_txnid, freecount, count+2, freecount+count+2, txn->mt_next_pgno);
1525 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1527 return txn->mt_dbxs[dbi].md_cmp(a, b);
1531 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1533 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1536 /** Allocate memory for a page.
1537 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1540 mdb_page_malloc(MDB_txn *txn, unsigned num)
1542 MDB_env *env = txn->mt_env;
1543 MDB_page *ret = env->me_dpages;
1544 size_t psize = env->me_psize, sz = psize, off;
1545 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1546 * For a single page alloc, we init everything after the page header.
1547 * For multi-page, we init the final page; if the caller needed that
1548 * many pages they will be filling in at least up to the last page.
1552 VGMEMP_ALLOC(env, ret, sz);
1553 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1554 env->me_dpages = ret->mp_next;
1557 psize -= off = PAGEHDRSZ;
1562 if ((ret = malloc(sz)) != NULL) {
1563 VGMEMP_ALLOC(env, ret, sz);
1564 if (!(env->me_flags & MDB_NOMEMINIT)) {
1565 memset((char *)ret + off, 0, psize);
1569 txn->mt_flags |= MDB_TXN_ERROR;
1573 /** Free a single page.
1574 * Saves single pages to a list, for future reuse.
1575 * (This is not used for multi-page overflow pages.)
1578 mdb_page_free(MDB_env *env, MDB_page *mp)
1580 mp->mp_next = env->me_dpages;
1581 VGMEMP_FREE(env, mp);
1582 env->me_dpages = mp;
1585 /** Free a dirty page */
1587 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1589 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1590 mdb_page_free(env, dp);
1592 /* large pages just get freed directly */
1593 VGMEMP_FREE(env, dp);
1598 /** Return all dirty pages to dpage list */
1600 mdb_dlist_free(MDB_txn *txn)
1602 MDB_env *env = txn->mt_env;
1603 MDB_ID2L dl = txn->mt_u.dirty_list;
1604 unsigned i, n = dl[0].mid;
1606 for (i = 1; i <= n; i++) {
1607 mdb_dpage_free(env, dl[i].mptr);
1612 /** Loosen or free a single page.
1613 * Saves single pages to a list for future reuse
1614 * in this same txn. It has been pulled from the freeDB
1615 * and already resides on the dirty list, but has been
1616 * deleted. Use these pages first before pulling again
1619 * If the page wasn't dirtied in this txn, just add it
1620 * to this txn's free list.
1623 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
1626 pgno_t pgno = mp->mp_pgno;
1628 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
1629 if (mc->mc_txn->mt_parent) {
1630 MDB_ID2 *dl = mc->mc_txn->mt_u.dirty_list;
1631 /* If txn has a parent, make sure the page is in our
1635 unsigned x = mdb_mid2l_search(dl, pgno);
1636 if (x <= dl[0].mid && dl[x].mid == pgno) {
1637 if (mp != dl[x].mptr) { /* bad cursor? */
1638 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1639 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
1640 return MDB_CORRUPTED;
1647 /* no parent txn, so it's just ours */
1652 DPRINTF(("loosen db %d page %"Z"u", DDBI(mc),
1654 NEXT_LOOSE_PAGE(mp) = mc->mc_txn->mt_loose_pgs;
1655 mc->mc_txn->mt_loose_pgs = mp;
1656 mp->mp_flags |= P_LOOSE;
1658 int rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, pgno);
1666 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
1667 * @param[in] mc A cursor handle for the current operation.
1668 * @param[in] pflags Flags of the pages to update:
1669 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1670 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
1671 * @return 0 on success, non-zero on failure.
1674 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
1676 enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
1677 MDB_txn *txn = mc->mc_txn;
1683 int rc = MDB_SUCCESS, level;
1685 /* Mark pages seen by cursors */
1686 if (mc->mc_flags & C_UNTRACK)
1687 mc = NULL; /* will find mc in mt_cursors */
1688 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1689 for (; mc; mc=mc->mc_next) {
1690 if (!(mc->mc_flags & C_INITIALIZED))
1692 for (m3 = mc;; m3 = &mx->mx_cursor) {
1694 for (j=0; j<m3->mc_snum; j++) {
1696 if ((mp->mp_flags & Mask) == pflags)
1697 mp->mp_flags ^= P_KEEP;
1699 mx = m3->mc_xcursor;
1700 /* Proceed to mx if it is at a sub-database */
1701 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
1703 if (! (mp && (mp->mp_flags & P_LEAF)))
1705 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
1706 if (!(leaf->mn_flags & F_SUBDATA))
1715 /* Mark dirty root pages */
1716 for (i=0; i<txn->mt_numdbs; i++) {
1717 if (txn->mt_dbflags[i] & DB_DIRTY) {
1718 pgno_t pgno = txn->mt_dbs[i].md_root;
1719 if (pgno == P_INVALID)
1721 if ((rc = mdb_page_get(txn, pgno, &dp, &level)) != MDB_SUCCESS)
1723 if ((dp->mp_flags & Mask) == pflags && level <= 1)
1724 dp->mp_flags ^= P_KEEP;
1732 static int mdb_page_flush(MDB_txn *txn, int keep);
1734 /** Spill pages from the dirty list back to disk.
1735 * This is intended to prevent running into #MDB_TXN_FULL situations,
1736 * but note that they may still occur in a few cases:
1737 * 1) our estimate of the txn size could be too small. Currently this
1738 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
1739 * 2) child txns may run out of space if their parents dirtied a
1740 * lot of pages and never spilled them. TODO: we probably should do
1741 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1742 * the parent's dirty_room is below a given threshold.
1744 * Otherwise, if not using nested txns, it is expected that apps will
1745 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1746 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1747 * If the txn never references them again, they can be left alone.
1748 * If the txn only reads them, they can be used without any fuss.
1749 * If the txn writes them again, they can be dirtied immediately without
1750 * going thru all of the work of #mdb_page_touch(). Such references are
1751 * handled by #mdb_page_unspill().
1753 * Also note, we never spill DB root pages, nor pages of active cursors,
1754 * because we'll need these back again soon anyway. And in nested txns,
1755 * we can't spill a page in a child txn if it was already spilled in a
1756 * parent txn. That would alter the parent txns' data even though
1757 * the child hasn't committed yet, and we'd have no way to undo it if
1758 * the child aborted.
1760 * @param[in] m0 cursor A cursor handle identifying the transaction and
1761 * database for which we are checking space.
1762 * @param[in] key For a put operation, the key being stored.
1763 * @param[in] data For a put operation, the data being stored.
1764 * @return 0 on success, non-zero on failure.
1767 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1769 MDB_txn *txn = m0->mc_txn;
1771 MDB_ID2L dl = txn->mt_u.dirty_list;
1772 unsigned int i, j, need;
1775 if (m0->mc_flags & C_SUB)
1778 /* Estimate how much space this op will take */
1779 i = m0->mc_db->md_depth;
1780 /* Named DBs also dirty the main DB */
1781 if (m0->mc_dbi > MAIN_DBI)
1782 i += txn->mt_dbs[MAIN_DBI].md_depth;
1783 /* For puts, roughly factor in the key+data size */
1785 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
1786 i += i; /* double it for good measure */
1789 if (txn->mt_dirty_room > i)
1792 if (!txn->mt_spill_pgs) {
1793 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
1794 if (!txn->mt_spill_pgs)
1797 /* purge deleted slots */
1798 MDB_IDL sl = txn->mt_spill_pgs;
1799 unsigned int num = sl[0];
1801 for (i=1; i<=num; i++) {
1808 /* Preserve pages which may soon be dirtied again */
1809 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
1812 /* Less aggressive spill - we originally spilled the entire dirty list,
1813 * with a few exceptions for cursor pages and DB root pages. But this
1814 * turns out to be a lot of wasted effort because in a large txn many
1815 * of those pages will need to be used again. So now we spill only 1/8th
1816 * of the dirty pages. Testing revealed this to be a good tradeoff,
1817 * better than 1/2, 1/4, or 1/10.
1819 if (need < MDB_IDL_UM_MAX / 8)
1820 need = MDB_IDL_UM_MAX / 8;
1822 /* Save the page IDs of all the pages we're flushing */
1823 /* flush from the tail forward, this saves a lot of shifting later on. */
1824 for (i=dl[0].mid; i && need; i--) {
1825 MDB_ID pn = dl[i].mid << 1;
1827 if (dp->mp_flags & (P_LOOSE|P_KEEP))
1829 /* Can't spill twice, make sure it's not already in a parent's
1832 if (txn->mt_parent) {
1834 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1835 if (tx2->mt_spill_pgs) {
1836 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
1837 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
1838 dp->mp_flags |= P_KEEP;
1846 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
1850 mdb_midl_sort(txn->mt_spill_pgs);
1852 /* Flush the spilled part of dirty list */
1853 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
1856 /* Reset any dirty pages we kept that page_flush didn't see */
1857 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
1860 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
1864 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
1866 mdb_find_oldest(MDB_txn *txn)
1869 txnid_t mr, oldest = txn->mt_txnid - 1;
1870 if (txn->mt_env->me_txns) {
1871 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
1872 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
1883 /** Add a page to the txn's dirty list */
1885 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
1888 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
1890 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1891 insert = mdb_mid2l_append;
1893 insert = mdb_mid2l_insert;
1895 mid.mid = mp->mp_pgno;
1897 rc = insert(txn->mt_u.dirty_list, &mid);
1898 mdb_tassert(txn, rc == 0);
1899 txn->mt_dirty_room--;
1902 /** Allocate page numbers and memory for writing. Maintain me_pglast,
1903 * me_pghead and mt_next_pgno.
1905 * If there are free pages available from older transactions, they
1906 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
1907 * Do not modify the freedB, just merge freeDB records into me_pghead[]
1908 * and move me_pglast to say which records were consumed. Only this
1909 * function can create me_pghead and move me_pglast/mt_next_pgno.
1910 * @param[in] mc cursor A cursor handle identifying the transaction and
1911 * database for which we are allocating.
1912 * @param[in] num the number of pages to allocate.
1913 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
1914 * will always be satisfied by a single contiguous chunk of memory.
1915 * @return 0 on success, non-zero on failure.
1918 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
1920 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
1921 /* Get at most <Max_retries> more freeDB records once me_pghead
1922 * has enough pages. If not enough, use new pages from the map.
1923 * If <Paranoid> and mc is updating the freeDB, only get new
1924 * records if me_pghead is empty. Then the freelist cannot play
1925 * catch-up with itself by growing while trying to save it.
1927 enum { Paranoid = 1, Max_retries = 500 };
1929 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
1931 int rc, retry = num * 20;
1932 MDB_txn *txn = mc->mc_txn;
1933 MDB_env *env = txn->mt_env;
1934 pgno_t pgno, *mop = env->me_pghead;
1935 unsigned i, j, k, mop_len = mop ? mop[0] : 0, n2 = num-1;
1937 txnid_t oldest = 0, last;
1941 /* If there are any loose pages, just use them */
1942 if (num == 1 && txn->mt_loose_pgs) {
1943 np = txn->mt_loose_pgs;
1944 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
1945 DPRINTF(("db %d use loose page %"Z"u", DDBI(mc),
1953 /* If our dirty list is already full, we can't do anything */
1954 if (txn->mt_dirty_room == 0) {
1959 for (op = MDB_FIRST;; op = MDB_NEXT) {
1962 pgno_t *idl, old_id, new_id;
1964 /* Seek a big enough contiguous page range. Prefer
1965 * pages at the tail, just truncating the list.
1971 if (mop[i-n2] == pgno+n2)
1978 if (op == MDB_FIRST) { /* 1st iteration */
1979 /* Prepare to fetch more and coalesce */
1980 oldest = mdb_find_oldest(txn);
1981 last = env->me_pglast;
1982 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1985 key.mv_data = &last; /* will look up last+1 */
1986 key.mv_size = sizeof(last);
1988 if (Paranoid && mc->mc_dbi == FREE_DBI)
1991 if (Paranoid && retry < 0 && mop_len)
1995 /* Do not fetch more if the record will be too recent */
1998 rc = mdb_cursor_get(&m2, &key, NULL, op);
2000 if (rc == MDB_NOTFOUND)
2004 last = *(txnid_t*)key.mv_data;
2007 np = m2.mc_pg[m2.mc_top];
2008 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
2009 if ((rc = mdb_node_read(txn, leaf, &data)) != MDB_SUCCESS)
2012 idl = (MDB_ID *) data.mv_data;
2015 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
2020 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
2022 mop = env->me_pghead;
2024 env->me_pglast = last;
2026 DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
2027 last, txn->mt_dbs[FREE_DBI].md_root, i));
2029 DPRINTF(("IDL %"Z"u", idl[k]));
2031 /* Merge in descending sorted order */
2034 mop[0] = (pgno_t)-1;
2038 for (; old_id < new_id; old_id = mop[--j])
2045 /* Use new pages from the map when nothing suitable in the freeDB */
2047 pgno = txn->mt_next_pgno;
2048 if (pgno + num >= env->me_maxpg) {
2049 DPUTS("DB size maxed out");
2055 if (env->me_flags & MDB_WRITEMAP) {
2056 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
2058 if (!(np = mdb_page_malloc(txn, num))) {
2064 mop[0] = mop_len -= num;
2065 /* Move any stragglers down */
2066 for (j = i-num; j < mop_len; )
2067 mop[++j] = mop[++i];
2069 txn->mt_next_pgno = pgno + num;
2072 mdb_page_dirty(txn, np);
2078 txn->mt_flags |= MDB_TXN_ERROR;
2082 /** Copy the used portions of a non-overflow page.
2083 * @param[in] dst page to copy into
2084 * @param[in] src page to copy from
2085 * @param[in] psize size of a page
2088 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2090 enum { Align = sizeof(pgno_t) };
2091 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2093 /* If page isn't full, just copy the used portion. Adjust
2094 * alignment so memcpy may copy words instead of bytes.
2096 if ((unused &= -Align) && !IS_LEAF2(src)) {
2097 upper = (upper + PAGEBASE) & -Align;
2098 memcpy(dst, src, (lower + PAGEBASE + (Align-1)) & -Align);
2099 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2102 memcpy(dst, src, psize - unused);
2106 /** Pull a page off the txn's spill list, if present.
2107 * If a page being referenced was spilled to disk in this txn, bring
2108 * it back and make it dirty/writable again.
2109 * @param[in] txn the transaction handle.
2110 * @param[in] mp the page being referenced. It must not be dirty.
2111 * @param[out] ret the writable page, if any. ret is unchanged if
2112 * mp wasn't spilled.
2115 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2117 MDB_env *env = txn->mt_env;
2120 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2122 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2123 if (!tx2->mt_spill_pgs)
2125 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2126 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2129 if (txn->mt_dirty_room == 0)
2130 return MDB_TXN_FULL;
2131 if (IS_OVERFLOW(mp))
2135 if (env->me_flags & MDB_WRITEMAP) {
2138 np = mdb_page_malloc(txn, num);
2142 memcpy(np, mp, num * env->me_psize);
2144 mdb_page_copy(np, mp, env->me_psize);
2147 /* If in current txn, this page is no longer spilled.
2148 * If it happens to be the last page, truncate the spill list.
2149 * Otherwise mark it as deleted by setting the LSB.
2151 if (x == txn->mt_spill_pgs[0])
2152 txn->mt_spill_pgs[0]--;
2154 txn->mt_spill_pgs[x] |= 1;
2155 } /* otherwise, if belonging to a parent txn, the
2156 * page remains spilled until child commits
2159 mdb_page_dirty(txn, np);
2160 np->mp_flags |= P_DIRTY;
2168 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2169 * @param[in] mc cursor pointing to the page to be touched
2170 * @return 0 on success, non-zero on failure.
2173 mdb_page_touch(MDB_cursor *mc)
2175 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2176 MDB_txn *txn = mc->mc_txn;
2177 MDB_cursor *m2, *m3;
2181 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2182 if (txn->mt_flags & MDB_TXN_SPILLS) {
2184 rc = mdb_page_unspill(txn, mp, &np);
2190 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2191 (rc = mdb_page_alloc(mc, 1, &np)))
2194 DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
2195 mp->mp_pgno, pgno));
2196 mdb_cassert(mc, mp->mp_pgno != pgno);
2197 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2198 /* Update the parent page, if any, to point to the new page */
2200 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2201 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2202 SETPGNO(node, pgno);
2204 mc->mc_db->md_root = pgno;
2206 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2207 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2209 /* If txn has a parent, make sure the page is in our
2213 unsigned x = mdb_mid2l_search(dl, pgno);
2214 if (x <= dl[0].mid && dl[x].mid == pgno) {
2215 if (mp != dl[x].mptr) { /* bad cursor? */
2216 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2217 txn->mt_flags |= MDB_TXN_ERROR;
2218 return MDB_CORRUPTED;
2223 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2225 np = mdb_page_malloc(txn, 1);
2230 rc = mdb_mid2l_insert(dl, &mid);
2231 mdb_cassert(mc, rc == 0);
2236 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2238 np->mp_flags |= P_DIRTY;
2241 /* Adjust cursors pointing to mp */
2242 mc->mc_pg[mc->mc_top] = np;
2243 m2 = txn->mt_cursors[mc->mc_dbi];
2244 if (mc->mc_flags & C_SUB) {
2245 for (; m2; m2=m2->mc_next) {
2246 m3 = &m2->mc_xcursor->mx_cursor;
2247 if (m3->mc_snum < mc->mc_snum) continue;
2248 if (m3->mc_pg[mc->mc_top] == mp)
2249 m3->mc_pg[mc->mc_top] = np;
2252 for (; m2; m2=m2->mc_next) {
2253 if (m2->mc_snum < mc->mc_snum) continue;
2254 if (m2->mc_pg[mc->mc_top] == mp) {
2255 m2->mc_pg[mc->mc_top] = np;
2256 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
2258 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
2260 MDB_node *leaf = NODEPTR(np, mc->mc_ki[mc->mc_top]);
2261 if (!(leaf->mn_flags & F_SUBDATA))
2262 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
2270 txn->mt_flags |= MDB_TXN_ERROR;
2275 mdb_env_sync(MDB_env *env, int force)
2278 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2279 if (env->me_flags & MDB_WRITEMAP) {
2280 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2281 ? MS_ASYNC : MS_SYNC;
2282 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
2285 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2289 if (MDB_FDATASYNC(env->me_fd))
2296 /** Back up parent txn's cursors, then grab the originals for tracking */
2298 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2300 MDB_cursor *mc, *bk;
2305 for (i = src->mt_numdbs; --i >= 0; ) {
2306 if ((mc = src->mt_cursors[i]) != NULL) {
2307 size = sizeof(MDB_cursor);
2309 size += sizeof(MDB_xcursor);
2310 for (; mc; mc = bk->mc_next) {
2316 mc->mc_db = &dst->mt_dbs[i];
2317 /* Kill pointers into src - and dst to reduce abuse: The
2318 * user may not use mc until dst ends. Otherwise we'd...
2320 mc->mc_txn = NULL; /* ...set this to dst */
2321 mc->mc_dbflag = NULL; /* ...and &dst->mt_dbflags[i] */
2322 if ((mx = mc->mc_xcursor) != NULL) {
2323 *(MDB_xcursor *)(bk+1) = *mx;
2324 mx->mx_cursor.mc_txn = NULL; /* ...and dst. */
2326 mc->mc_next = dst->mt_cursors[i];
2327 dst->mt_cursors[i] = mc;
2334 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2335 * @param[in] txn the transaction handle.
2336 * @param[in] merge true to keep changes to parent cursors, false to revert.
2337 * @return 0 on success, non-zero on failure.
2340 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2342 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2346 for (i = txn->mt_numdbs; --i >= 0; ) {
2347 for (mc = cursors[i]; mc; mc = next) {
2349 if ((bk = mc->mc_backup) != NULL) {
2351 /* Commit changes to parent txn */
2352 mc->mc_next = bk->mc_next;
2353 mc->mc_backup = bk->mc_backup;
2354 mc->mc_txn = bk->mc_txn;
2355 mc->mc_db = bk->mc_db;
2356 mc->mc_dbflag = bk->mc_dbflag;
2357 if ((mx = mc->mc_xcursor) != NULL)
2358 mx->mx_cursor.mc_txn = bk->mc_txn;
2360 /* Abort nested txn */
2362 if ((mx = mc->mc_xcursor) != NULL)
2363 *mx = *(MDB_xcursor *)(bk+1);
2367 /* Only malloced cursors are permanently tracked. */
2375 #define mdb_txn_reset0(txn, act) mdb_txn_reset0(txn)
2378 mdb_txn_reset0(MDB_txn *txn, const char *act);
2380 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2386 Pidset = F_SETLK, Pidcheck = F_GETLK
2390 /** Set or check a pid lock. Set returns 0 on success.
2391 * Check returns 0 if the process is certainly dead, nonzero if it may
2392 * be alive (the lock exists or an error happened so we do not know).
2394 * On Windows Pidset is a no-op, we merely check for the existence
2395 * of the process with the given pid. On POSIX we use a single byte
2396 * lock on the lockfile, set at an offset equal to the pid.
2399 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2401 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2404 if (op == Pidcheck) {
2405 h = OpenProcess(env->me_pidquery, FALSE, pid);
2406 /* No documented "no such process" code, but other program use this: */
2408 return ErrCode() != ERROR_INVALID_PARAMETER;
2409 /* A process exists until all handles to it close. Has it exited? */
2410 ret = WaitForSingleObject(h, 0) != 0;
2417 struct flock lock_info;
2418 memset(&lock_info, 0, sizeof(lock_info));
2419 lock_info.l_type = F_WRLCK;
2420 lock_info.l_whence = SEEK_SET;
2421 lock_info.l_start = pid;
2422 lock_info.l_len = 1;
2423 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2424 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2426 } else if ((rc = ErrCode()) == EINTR) {
2434 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2435 * @param[in] txn the transaction handle to initialize
2436 * @return 0 on success, non-zero on failure.
2439 mdb_txn_renew0(MDB_txn *txn)
2441 MDB_env *env = txn->mt_env;
2442 MDB_txninfo *ti = env->me_txns;
2446 int rc, new_notls = 0;
2449 txn->mt_numdbs = env->me_numdbs;
2450 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
2452 if (txn->mt_flags & MDB_TXN_RDONLY) {
2454 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2455 txn->mt_txnid = meta->mm_txnid;
2456 txn->mt_u.reader = NULL;
2458 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2459 pthread_getspecific(env->me_txkey);
2461 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2462 return MDB_BAD_RSLOT;
2464 MDB_PID_T pid = env->me_pid;
2465 MDB_THR_T tid = pthread_self();
2467 if (!env->me_live_reader) {
2468 rc = mdb_reader_pid(env, Pidset, pid);
2471 env->me_live_reader = 1;
2475 nr = ti->mti_numreaders;
2476 for (i=0; i<nr; i++)
2477 if (ti->mti_readers[i].mr_pid == 0)
2479 if (i == env->me_maxreaders) {
2480 UNLOCK_MUTEX_R(env);
2481 return MDB_READERS_FULL;
2483 ti->mti_readers[i].mr_pid = pid;
2484 ti->mti_readers[i].mr_tid = tid;
2486 ti->mti_numreaders = ++nr;
2487 /* Save numreaders for un-mutexed mdb_env_close() */
2488 env->me_numreaders = nr;
2489 UNLOCK_MUTEX_R(env);
2491 r = &ti->mti_readers[i];
2492 new_notls = (env->me_flags & MDB_NOTLS);
2493 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2498 txn->mt_txnid = r->mr_txnid = ti->mti_txnid;
2499 txn->mt_u.reader = r;
2500 meta = env->me_metas[txn->mt_txnid & 1];
2506 txn->mt_txnid = ti->mti_txnid;
2507 meta = env->me_metas[txn->mt_txnid & 1];
2509 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2510 txn->mt_txnid = meta->mm_txnid;
2514 if (txn->mt_txnid == mdb_debug_start)
2517 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2518 txn->mt_u.dirty_list = env->me_dirty_list;
2519 txn->mt_u.dirty_list[0].mid = 0;
2520 txn->mt_free_pgs = env->me_free_pgs;
2521 txn->mt_free_pgs[0] = 0;
2522 txn->mt_spill_pgs = NULL;
2524 memcpy(txn->mt_dbiseqs, env->me_dbiseqs, env->me_maxdbs * sizeof(unsigned int));
2527 /* Copy the DB info and flags */
2528 memcpy(txn->mt_dbs, meta->mm_dbs, 2 * sizeof(MDB_db));
2530 /* Moved to here to avoid a data race in read TXNs */
2531 txn->mt_next_pgno = meta->mm_last_pg+1;
2533 for (i=2; i<txn->mt_numdbs; i++) {
2534 x = env->me_dbflags[i];
2535 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2536 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_STALE : 0;
2538 txn->mt_dbflags[0] = txn->mt_dbflags[1] = DB_VALID;
2540 /* If we didn't ask for a resize, but the size grew, fail */
2541 if (!(env->me_flags & MDB_RESIZING)
2542 && env->me_mapsize < meta->mm_mapsize) {
2543 mdb_txn_reset0(txn, "renew0-mapfail");
2545 txn->mt_u.reader->mr_pid = 0;
2546 txn->mt_u.reader = NULL;
2548 return MDB_MAP_RESIZED;
2555 mdb_txn_renew(MDB_txn *txn)
2559 if (!txn || txn->mt_dbxs) /* A reset txn has mt_dbxs==NULL */
2562 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
2563 DPUTS("environment had fatal error, must shutdown!");
2567 rc = mdb_txn_renew0(txn);
2568 if (rc == MDB_SUCCESS) {
2569 DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2570 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2571 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2577 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2581 int rc, size, tsize = sizeof(MDB_txn);
2583 if (env->me_flags & MDB_FATAL_ERROR) {
2584 DPUTS("environment had fatal error, must shutdown!");
2587 if ((env->me_flags & MDB_RDONLY) && !(flags & MDB_RDONLY))
2590 /* Nested transactions: Max 1 child, write txns only, no writemap */
2591 if (parent->mt_child ||
2592 (flags & MDB_RDONLY) ||
2593 (parent->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR)) ||
2594 (env->me_flags & MDB_WRITEMAP))
2596 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
2598 tsize = sizeof(MDB_ntxn);
2600 size = tsize + env->me_maxdbs * (sizeof(MDB_db)+1);
2601 if (!(flags & MDB_RDONLY)) {
2602 size += env->me_maxdbs * sizeof(MDB_cursor *);
2603 /* child txns use parent's dbiseqs */
2605 size += env->me_maxdbs * sizeof(unsigned int);
2608 if ((txn = calloc(1, size)) == NULL) {
2609 DPRINTF(("calloc: %s", strerror(errno)));
2612 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2613 if (flags & MDB_RDONLY) {
2614 txn->mt_flags |= MDB_TXN_RDONLY;
2615 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
2616 txn->mt_dbiseqs = env->me_dbiseqs;
2618 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2620 txn->mt_dbiseqs = parent->mt_dbiseqs;
2621 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
2623 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
2624 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
2631 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2632 if (!txn->mt_u.dirty_list ||
2633 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2635 free(txn->mt_u.dirty_list);
2639 txn->mt_txnid = parent->mt_txnid;
2640 txn->mt_dirty_room = parent->mt_dirty_room;
2641 txn->mt_u.dirty_list[0].mid = 0;
2642 txn->mt_spill_pgs = NULL;
2643 txn->mt_next_pgno = parent->mt_next_pgno;
2644 parent->mt_child = txn;
2645 txn->mt_parent = parent;
2646 txn->mt_numdbs = parent->mt_numdbs;
2647 txn->mt_flags = parent->mt_flags;
2648 txn->mt_dbxs = parent->mt_dbxs;
2649 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2650 /* Copy parent's mt_dbflags, but clear DB_NEW */
2651 for (i=0; i<txn->mt_numdbs; i++)
2652 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2654 ntxn = (MDB_ntxn *)txn;
2655 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2656 if (env->me_pghead) {
2657 size = MDB_IDL_SIZEOF(env->me_pghead);
2658 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2660 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2665 rc = mdb_cursor_shadow(parent, txn);
2667 mdb_txn_reset0(txn, "beginchild-fail");
2669 rc = mdb_txn_renew0(txn);
2675 DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2676 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2677 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
2684 mdb_txn_env(MDB_txn *txn)
2686 if(!txn) return NULL;
2690 /** Export or close DBI handles opened in this txn. */
2692 mdb_dbis_update(MDB_txn *txn, int keep)
2695 MDB_dbi n = txn->mt_numdbs;
2696 MDB_env *env = txn->mt_env;
2697 unsigned char *tdbflags = txn->mt_dbflags;
2699 for (i = n; --i >= 2;) {
2700 if (tdbflags[i] & DB_NEW) {
2702 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2704 char *ptr = env->me_dbxs[i].md_name.mv_data;
2706 env->me_dbxs[i].md_name.mv_data = NULL;
2707 env->me_dbxs[i].md_name.mv_size = 0;
2708 env->me_dbflags[i] = 0;
2709 env->me_dbiseqs[i]++;
2715 if (keep && env->me_numdbs < n)
2719 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
2720 * May be called twice for readonly txns: First reset it, then abort.
2721 * @param[in] txn the transaction handle to reset
2722 * @param[in] act why the transaction is being reset
2725 mdb_txn_reset0(MDB_txn *txn, const char *act)
2727 MDB_env *env = txn->mt_env;
2729 /* Close any DBI handles opened in this txn */
2730 mdb_dbis_update(txn, 0);
2732 DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2733 act, txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2734 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
2736 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2737 if (txn->mt_u.reader) {
2738 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2739 if (!(env->me_flags & MDB_NOTLS))
2740 txn->mt_u.reader = NULL; /* txn does not own reader */
2742 txn->mt_numdbs = 0; /* close nothing if called again */
2743 txn->mt_dbxs = NULL; /* mark txn as reset */
2745 mdb_cursors_close(txn, 0);
2747 if (!(env->me_flags & MDB_WRITEMAP)) {
2748 mdb_dlist_free(txn);
2750 mdb_midl_free(env->me_pghead);
2752 if (txn->mt_parent) {
2753 txn->mt_parent->mt_child = NULL;
2754 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2755 mdb_midl_free(txn->mt_free_pgs);
2756 mdb_midl_free(txn->mt_spill_pgs);
2757 free(txn->mt_u.dirty_list);
2761 if (mdb_midl_shrink(&txn->mt_free_pgs))
2762 env->me_free_pgs = txn->mt_free_pgs;
2763 env->me_pghead = NULL;
2767 /* The writer mutex was locked in mdb_txn_begin. */
2769 UNLOCK_MUTEX_W(env);
2774 mdb_txn_reset(MDB_txn *txn)
2779 /* This call is only valid for read-only txns */
2780 if (!(txn->mt_flags & MDB_TXN_RDONLY))
2783 mdb_txn_reset0(txn, "reset");
2787 mdb_txn_abort(MDB_txn *txn)
2793 mdb_txn_abort(txn->mt_child);
2795 mdb_txn_reset0(txn, "abort");
2796 /* Free reader slot tied to this txn (if MDB_NOTLS && writable FS) */
2797 if ((txn->mt_flags & MDB_TXN_RDONLY) && txn->mt_u.reader)
2798 txn->mt_u.reader->mr_pid = 0;
2803 /** Save the freelist as of this transaction to the freeDB.
2804 * This changes the freelist. Keep trying until it stabilizes.
2807 mdb_freelist_save(MDB_txn *txn)
2809 /* env->me_pghead[] can grow and shrink during this call.
2810 * env->me_pglast and txn->mt_free_pgs[] can only grow.
2811 * Page numbers cannot disappear from txn->mt_free_pgs[].
2814 MDB_env *env = txn->mt_env;
2815 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
2816 txnid_t pglast = 0, head_id = 0;
2817 pgno_t freecnt = 0, *free_pgs, *mop;
2818 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
2820 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
2822 if (env->me_pghead) {
2823 /* Make sure first page of freeDB is touched and on freelist */
2824 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
2825 if (rc && rc != MDB_NOTFOUND)
2829 /* Dispose of loose pages. Usually they will have all
2830 * been used up by the time we get here.
2832 if (txn->mt_loose_pgs) {
2833 MDB_page *mp = txn->mt_loose_pgs;
2834 /* Just return them to freeDB */
2835 if (env->me_pghead) {
2837 mop = env->me_pghead;
2838 for (; mp; mp = NEXT_LOOSE_PAGE(mp)) {
2839 pgno_t pg = mp->mp_pgno;
2841 for (i = mop[0]; i && mop[i] < pg; i--)
2847 /* Oh well, they were wasted. Put on freelist */
2848 for (; mp; mp = NEXT_LOOSE_PAGE(mp)) {
2849 mdb_midl_append(&txn->mt_free_pgs, mp->mp_pgno);
2852 txn->mt_loose_pgs = NULL;
2855 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
2856 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
2857 ? SSIZE_MAX : maxfree_1pg;
2860 /* Come back here after each Put() in case freelist changed */
2865 /* If using records from freeDB which we have not yet
2866 * deleted, delete them and any we reserved for me_pghead.
2868 while (pglast < env->me_pglast) {
2869 rc = mdb_cursor_first(&mc, &key, NULL);
2872 pglast = head_id = *(txnid_t *)key.mv_data;
2873 total_room = head_room = 0;
2874 mdb_tassert(txn, pglast <= env->me_pglast);
2875 rc = mdb_cursor_del(&mc, 0);
2880 /* Save the IDL of pages freed by this txn, to a single record */
2881 if (freecnt < txn->mt_free_pgs[0]) {
2883 /* Make sure last page of freeDB is touched and on freelist */
2884 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
2885 if (rc && rc != MDB_NOTFOUND)
2888 free_pgs = txn->mt_free_pgs;
2889 /* Write to last page of freeDB */
2890 key.mv_size = sizeof(txn->mt_txnid);
2891 key.mv_data = &txn->mt_txnid;
2893 freecnt = free_pgs[0];
2894 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
2895 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2898 /* Retry if mt_free_pgs[] grew during the Put() */
2899 free_pgs = txn->mt_free_pgs;
2900 } while (freecnt < free_pgs[0]);
2901 mdb_midl_sort(free_pgs);
2902 memcpy(data.mv_data, free_pgs, data.mv_size);
2905 unsigned int i = free_pgs[0];
2906 DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
2907 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
2909 DPRINTF(("IDL %"Z"u", free_pgs[i]));
2915 mop = env->me_pghead;
2916 mop_len = mop ? mop[0] : 0;
2918 /* Reserve records for me_pghead[]. Split it if multi-page,
2919 * to avoid searching freeDB for a page range. Use keys in
2920 * range [1,me_pglast]: Smaller than txnid of oldest reader.
2922 if (total_room >= mop_len) {
2923 if (total_room == mop_len || --more < 0)
2925 } else if (head_room >= maxfree_1pg && head_id > 1) {
2926 /* Keep current record (overflow page), add a new one */
2930 /* (Re)write {key = head_id, IDL length = head_room} */
2931 total_room -= head_room;
2932 head_room = mop_len - total_room;
2933 if (head_room > maxfree_1pg && head_id > 1) {
2934 /* Overflow multi-page for part of me_pghead */
2935 head_room /= head_id; /* amortize page sizes */
2936 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
2937 } else if (head_room < 0) {
2938 /* Rare case, not bothering to delete this record */
2941 key.mv_size = sizeof(head_id);
2942 key.mv_data = &head_id;
2943 data.mv_size = (head_room + 1) * sizeof(pgno_t);
2944 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2947 /* IDL is initially empty, zero out at least the length */
2948 pgs = (pgno_t *)data.mv_data;
2949 j = head_room > clean_limit ? head_room : 0;
2953 total_room += head_room;
2956 /* Fill in the reserved me_pghead records */
2962 rc = mdb_cursor_first(&mc, &key, &data);
2963 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
2964 txnid_t id = *(txnid_t *)key.mv_data;
2965 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
2968 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
2970 if (len > mop_len) {
2972 data.mv_size = (len + 1) * sizeof(MDB_ID);
2974 data.mv_data = mop -= len;
2977 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
2979 if (rc || !(mop_len -= len))
2986 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
2987 * @param[in] txn the transaction that's being committed
2988 * @param[in] keep number of initial pages in dirty_list to keep dirty.
2989 * @return 0 on success, non-zero on failure.
2992 mdb_page_flush(MDB_txn *txn, int keep)
2994 MDB_env *env = txn->mt_env;
2995 MDB_ID2L dl = txn->mt_u.dirty_list;
2996 unsigned psize = env->me_psize, j;
2997 int i, pagecount = dl[0].mid, rc;
2998 size_t size = 0, pos = 0;
3000 MDB_page *dp = NULL;
3004 struct iovec iov[MDB_COMMIT_PAGES];
3005 ssize_t wpos = 0, wsize = 0, wres;
3006 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
3012 if (env->me_flags & MDB_WRITEMAP) {
3013 /* Clear dirty flags */
3014 while (++i <= pagecount) {
3016 /* Don't flush this page yet */
3017 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3018 dp->mp_flags &= ~P_KEEP;
3022 dp->mp_flags &= ~P_DIRTY;
3027 /* Write the pages */
3029 if (++i <= pagecount) {
3031 /* Don't flush this page yet */
3032 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3033 dp->mp_flags &= ~P_KEEP;
3038 /* clear dirty flag */
3039 dp->mp_flags &= ~P_DIRTY;
3042 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
3047 /* Windows actually supports scatter/gather I/O, but only on
3048 * unbuffered file handles. Since we're relying on the OS page
3049 * cache for all our data, that's self-defeating. So we just
3050 * write pages one at a time. We use the ov structure to set
3051 * the write offset, to at least save the overhead of a Seek
3054 DPRINTF(("committing page %"Z"u", pgno));
3055 memset(&ov, 0, sizeof(ov));
3056 ov.Offset = pos & 0xffffffff;
3057 ov.OffsetHigh = pos >> 16 >> 16;
3058 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
3060 DPRINTF(("WriteFile: %d", rc));
3064 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
3065 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
3067 /* Write previous page(s) */
3068 #ifdef MDB_USE_PWRITEV
3069 wres = pwritev(env->me_fd, iov, n, wpos);
3072 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
3074 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
3076 DPRINTF(("lseek: %s", strerror(rc)));
3079 wres = writev(env->me_fd, iov, n);
3082 if (wres != wsize) {
3085 DPRINTF(("Write error: %s", strerror(rc)));
3087 rc = EIO; /* TODO: Use which error code? */
3088 DPUTS("short write, filesystem full?");
3099 DPRINTF(("committing page %"Z"u", pgno));
3100 next_pos = pos + size;
3101 iov[n].iov_len = size;
3102 iov[n].iov_base = (char *)dp;
3108 for (i = keep; ++i <= pagecount; ) {
3110 /* This is a page we skipped above */
3113 dl[j].mid = dp->mp_pgno;
3116 mdb_dpage_free(env, dp);
3121 txn->mt_dirty_room += i - j;
3127 mdb_txn_commit(MDB_txn *txn)
3133 if (txn == NULL || txn->mt_env == NULL)
3136 if (txn->mt_child) {
3137 rc = mdb_txn_commit(txn->mt_child);
3138 txn->mt_child = NULL;
3145 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3146 mdb_dbis_update(txn, 1);
3147 txn->mt_numdbs = 2; /* so txn_abort() doesn't close any new handles */
3152 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
3153 DPUTS("error flag is set, can't commit");
3155 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3160 if (txn->mt_parent) {
3161 MDB_txn *parent = txn->mt_parent;
3165 unsigned x, y, len, ps_len;
3167 /* Append our free list to parent's */
3168 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3171 mdb_midl_free(txn->mt_free_pgs);
3172 /* Failures after this must either undo the changes
3173 * to the parent or set MDB_TXN_ERROR in the parent.
3176 parent->mt_next_pgno = txn->mt_next_pgno;
3177 parent->mt_flags = txn->mt_flags;
3179 /* Merge our cursors into parent's and close them */
3180 mdb_cursors_close(txn, 1);
3182 /* Update parent's DB table. */
3183 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3184 parent->mt_numdbs = txn->mt_numdbs;
3185 parent->mt_dbflags[0] = txn->mt_dbflags[0];
3186 parent->mt_dbflags[1] = txn->mt_dbflags[1];
3187 for (i=2; i<txn->mt_numdbs; i++) {
3188 /* preserve parent's DB_NEW status */
3189 x = parent->mt_dbflags[i] & DB_NEW;
3190 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3193 dst = parent->mt_u.dirty_list;
3194 src = txn->mt_u.dirty_list;
3195 /* Remove anything in our dirty list from parent's spill list */
3196 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3198 pspill[0] = (pgno_t)-1;
3199 /* Mark our dirty pages as deleted in parent spill list */
3200 for (i=0, len=src[0].mid; ++i <= len; ) {
3201 MDB_ID pn = src[i].mid << 1;
3202 while (pn > pspill[x])
3204 if (pn == pspill[x]) {
3209 /* Squash deleted pagenums if we deleted any */
3210 for (x=y; ++x <= ps_len; )
3211 if (!(pspill[x] & 1))
3212 pspill[++y] = pspill[x];
3216 /* Find len = length of merging our dirty list with parent's */
3218 dst[0].mid = 0; /* simplify loops */
3219 if (parent->mt_parent) {
3220 len = x + src[0].mid;
3221 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3222 for (i = x; y && i; y--) {
3223 pgno_t yp = src[y].mid;
3224 while (yp < dst[i].mid)
3226 if (yp == dst[i].mid) {
3231 } else { /* Simplify the above for single-ancestor case */
3232 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3234 /* Merge our dirty list with parent's */
3236 for (i = len; y; dst[i--] = src[y--]) {
3237 pgno_t yp = src[y].mid;
3238 while (yp < dst[x].mid)
3239 dst[i--] = dst[x--];
3240 if (yp == dst[x].mid)
3241 free(dst[x--].mptr);
3243 mdb_tassert(txn, i == x);
3245 free(txn->mt_u.dirty_list);
3246 parent->mt_dirty_room = txn->mt_dirty_room;
3247 if (txn->mt_spill_pgs) {
3248 if (parent->mt_spill_pgs) {
3249 /* TODO: Prevent failure here, so parent does not fail */
3250 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3252 parent->mt_flags |= MDB_TXN_ERROR;
3253 mdb_midl_free(txn->mt_spill_pgs);
3254 mdb_midl_sort(parent->mt_spill_pgs);
3256 parent->mt_spill_pgs = txn->mt_spill_pgs;
3260 /* Append our loose page list to parent's */
3261 for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(lp))
3263 *lp = txn->mt_loose_pgs;
3265 parent->mt_child = NULL;
3266 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3271 if (txn != env->me_txn) {
3272 DPUTS("attempt to commit unknown transaction");
3277 mdb_cursors_close(txn, 0);
3279 if (!txn->mt_u.dirty_list[0].mid &&
3280 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS))) {
3281 if ((env->me_flags & MDB_RESIZING)
3282 && (rc = mdb_env_write_meta(txn))) {
3288 DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
3289 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3291 /* Update DB root pointers */
3292 if (txn->mt_numdbs > 2) {
3296 data.mv_size = sizeof(MDB_db);
3298 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3299 for (i = 2; i < txn->mt_numdbs; i++) {
3300 if (txn->mt_dbflags[i] & DB_DIRTY) {
3301 if (TXN_DBI_CHANGED(txn, i)) {
3305 data.mv_data = &txn->mt_dbs[i];
3306 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
3313 rc = mdb_freelist_save(txn);
3317 mdb_midl_free(env->me_pghead);
3318 env->me_pghead = NULL;
3319 if (mdb_midl_shrink(&txn->mt_free_pgs))
3320 env->me_free_pgs = txn->mt_free_pgs;
3326 if ((rc = mdb_page_flush(txn, 0)) ||
3327 (rc = mdb_env_write_meta(txn)))
3333 mdb_dbis_update(txn, 1);
3336 UNLOCK_MUTEX_W(env);
3346 /** Read the environment parameters of a DB environment before
3347 * mapping it into memory.
3348 * @param[in] env the environment handle
3349 * @param[out] meta address of where to store the meta information
3350 * @return 0 on success, non-zero on failure.
3353 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3359 enum { Size = sizeof(pbuf) };
3361 /* We don't know the page size yet, so use a minimum value.
3362 * Read both meta pages so we can use the latest one.
3365 for (i=off=0; i<2; i++, off = meta->mm_psize) {
3369 memset(&ov, 0, sizeof(ov));
3371 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3372 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3375 rc = pread(env->me_fd, &pbuf, Size, off);
3378 if (rc == 0 && off == 0)
3380 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3381 DPRINTF(("read: %s", mdb_strerror(rc)));
3385 p = (MDB_page *)&pbuf;
3387 if (!F_ISSET(p->mp_flags, P_META)) {
3388 DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
3393 if (m->mm_magic != MDB_MAGIC) {
3394 DPUTS("meta has invalid magic");
3398 if (m->mm_version != MDB_DATA_VERSION) {
3399 DPRINTF(("database is version %u, expected version %u",
3400 m->mm_version, MDB_DATA_VERSION));
3401 return MDB_VERSION_MISMATCH;
3404 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3411 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
3413 meta->mm_magic = MDB_MAGIC;
3414 meta->mm_version = MDB_DATA_VERSION;
3415 meta->mm_mapsize = env->me_mapsize;
3416 meta->mm_psize = env->me_psize;
3417 meta->mm_last_pg = 1;
3418 meta->mm_flags = env->me_flags & 0xffff;
3419 meta->mm_flags |= MDB_INTEGERKEY;
3420 meta->mm_dbs[0].md_root = P_INVALID;
3421 meta->mm_dbs[1].md_root = P_INVALID;
3424 /** Write the environment parameters of a freshly created DB environment.
3425 * @param[in] env the environment handle
3426 * @param[out] meta address of where to store the meta information
3427 * @return 0 on success, non-zero on failure.
3430 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3438 memset(&ov, 0, sizeof(ov));
3439 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3441 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3444 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3445 len = pwrite(fd, ptr, size, pos); \
3446 rc = (len >= 0); } while(0)
3449 DPUTS("writing new meta page");
3451 psize = env->me_psize;
3453 mdb_env_init_meta0(env, meta);
3455 p = calloc(2, psize);
3457 p->mp_flags = P_META;
3458 *(MDB_meta *)METADATA(p) = *meta;
3460 q = (MDB_page *)((char *)p + psize);
3462 q->mp_flags = P_META;
3463 *(MDB_meta *)METADATA(q) = *meta;
3465 DO_PWRITE(rc, env->me_fd, p, psize * 2, len, 0);
3468 else if ((unsigned) len == psize * 2)
3476 /** Update the environment info to commit a transaction.
3477 * @param[in] txn the transaction that's being committed
3478 * @return 0 on success, non-zero on failure.
3481 mdb_env_write_meta(MDB_txn *txn)
3483 MDB_env *env = txn->mt_env;
3484 MDB_meta meta, metab, *mp;
3486 int rc, len, toggle;
3495 /* Sync data and previous metapage before writing a new metapage */
3496 if ((rc = mdb_env_sync(env, 0)) != MDB_SUCCESS)
3499 toggle = txn->mt_txnid & 1;
3500 DPRINTF(("writing meta page %d for root page %"Z"u",
3501 toggle, txn->mt_dbs[MAIN_DBI].md_root));
3503 mp = env->me_metas[toggle];
3505 if (env->me_flags & MDB_WRITEMAP) {
3506 /* Persist any changes of mapsize config */
3507 if (env->me_flags & MDB_RESIZING) {
3508 mp->mm_mapsize = env->me_mapsize;
3509 env->me_flags ^= MDB_RESIZING;
3511 mp->mm_dbs[0] = txn->mt_dbs[0];
3512 mp->mm_dbs[1] = txn->mt_dbs[1];
3513 mp->mm_last_pg = txn->mt_next_pgno - 1;
3514 mp->mm_txnid = txn->mt_txnid;
3515 if (!(env->me_flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3516 unsigned meta_size = env->me_psize;
3517 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3520 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
3521 if (meta_size < env->me_os_psize)
3522 meta_size += meta_size;
3527 if (MDB_MSYNC(ptr, meta_size, rc)) {
3534 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
3535 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
3537 ptr = (char *)&meta;
3538 if (env->me_flags & MDB_RESIZING) {
3539 /* Persist any changes of mapsize config */
3540 meta.mm_mapsize = env->me_mapsize;
3541 off = offsetof(MDB_meta, mm_mapsize);
3542 env->me_flags ^= MDB_RESIZING;
3544 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
3546 len = sizeof(MDB_meta) - off;
3549 meta.mm_dbs[0] = txn->mt_dbs[0];
3550 meta.mm_dbs[1] = txn->mt_dbs[1];
3551 meta.mm_last_pg = txn->mt_next_pgno - 1;
3552 meta.mm_txnid = txn->mt_txnid;
3555 off += env->me_psize;
3558 /* Write to the SYNC fd */
3559 mfd = env->me_flags & (MDB_NOSYNC|MDB_NOMETASYNC) ?
3560 env->me_fd : env->me_mfd;
3563 memset(&ov, 0, sizeof(ov));
3565 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3569 rc = pwrite(mfd, ptr, len, off);
3572 rc = rc < 0 ? ErrCode() : EIO;
3573 DPUTS("write failed, disk error?");
3574 /* On a failure, the pagecache still contains the new data.
3575 * Write some old data back, to prevent it from being used.
3576 * Use the non-SYNC fd; we know it will fail anyway.
3578 meta.mm_last_pg = metab.mm_last_pg;
3579 meta.mm_txnid = metab.mm_txnid;
3581 memset(&ov, 0, sizeof(ov));
3583 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3585 r2 = pwrite(env->me_fd, ptr, len, off);
3586 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
3589 env->me_flags |= MDB_FATAL_ERROR;
3593 /* Memory ordering issues are irrelevant; since the entire writer
3594 * is wrapped by wmutex, all of these changes will become visible
3595 * after the wmutex is unlocked. Since the DB is multi-version,
3596 * readers will get consistent data regardless of how fresh or
3597 * how stale their view of these values is.
3600 env->me_txns->mti_txnid = txn->mt_txnid;
3605 /** Check both meta pages to see which one is newer.
3606 * @param[in] env the environment handle
3607 * @return meta toggle (0 or 1).
3610 mdb_env_pick_meta(const MDB_env *env)
3612 return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
3616 mdb_env_create(MDB_env **env)
3620 e = calloc(1, sizeof(MDB_env));
3624 e->me_maxreaders = DEFAULT_READERS;
3625 e->me_maxdbs = e->me_numdbs = 2;
3626 e->me_fd = INVALID_HANDLE_VALUE;
3627 e->me_lfd = INVALID_HANDLE_VALUE;
3628 e->me_mfd = INVALID_HANDLE_VALUE;
3629 #ifdef MDB_USE_POSIX_SEM
3630 e->me_rmutex = SEM_FAILED;
3631 e->me_wmutex = SEM_FAILED;
3633 e->me_pid = getpid();
3634 GET_PAGESIZE(e->me_os_psize);
3635 VGMEMP_CREATE(e,0,0);
3641 mdb_env_map(MDB_env *env, void *addr)
3644 unsigned int flags = env->me_flags;
3648 LONG sizelo, sizehi;
3651 if (flags & MDB_RDONLY) {
3652 /* Don't set explicit map size, use whatever exists */
3657 msize = env->me_mapsize;
3658 sizelo = msize & 0xffffffff;
3659 sizehi = msize >> 16 >> 16; /* only needed on Win64 */
3661 /* Windows won't create mappings for zero length files.
3662 * and won't map more than the file size.
3663 * Just set the maxsize right now.
3665 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3666 || !SetEndOfFile(env->me_fd)
3667 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3671 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3672 PAGE_READWRITE : PAGE_READONLY,
3673 sizehi, sizelo, NULL);
3676 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3677 FILE_MAP_WRITE : FILE_MAP_READ,
3679 rc = env->me_map ? 0 : ErrCode();
3684 int prot = PROT_READ;
3685 if (flags & MDB_WRITEMAP) {
3687 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3690 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
3692 if (env->me_map == MAP_FAILED) {
3697 if (flags & MDB_NORDAHEAD) {
3698 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3700 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3702 #ifdef POSIX_MADV_RANDOM
3703 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3704 #endif /* POSIX_MADV_RANDOM */
3705 #endif /* MADV_RANDOM */
3709 /* Can happen because the address argument to mmap() is just a
3710 * hint. mmap() can pick another, e.g. if the range is in use.
3711 * The MAP_FIXED flag would prevent that, but then mmap could
3712 * instead unmap existing pages to make room for the new map.
3714 if (addr && env->me_map != addr)
3715 return EBUSY; /* TODO: Make a new MDB_* error code? */
3717 p = (MDB_page *)env->me_map;
3718 env->me_metas[0] = METADATA(p);
3719 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
3725 mdb_env_set_mapsize(MDB_env *env, size_t size)
3727 /* If env is already open, caller is responsible for making
3728 * sure there are no active txns.
3736 size = env->me_metas[mdb_env_pick_meta(env)]->mm_mapsize;
3738 if (size < env->me_mapsize) {
3739 /* If the configured size is smaller, make sure it's
3740 * still big enough. Silently round up to minimum if not.
3742 size_t minsize = (env->me_metas[mdb_env_pick_meta(env)]->mm_last_pg + 1) * env->me_psize;
3746 /* nothing actually changed */
3747 if (size == env->me_mapsize)
3751 munmap(env->me_map, env->me_mapsize);
3752 env->me_mapsize = size;
3753 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
3754 rc = mdb_env_map(env, old);
3758 env->me_flags |= MDB_RESIZING;
3760 env->me_mapsize = size;
3762 env->me_maxpg = env->me_mapsize / env->me_psize;
3767 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
3771 env->me_maxdbs = dbs + 2; /* Named databases + main and free DB */
3776 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
3778 if (env->me_map || readers < 1)
3780 env->me_maxreaders = readers;
3785 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
3787 if (!env || !readers)
3789 *readers = env->me_maxreaders;
3793 /** Further setup required for opening an LMDB environment
3796 mdb_env_open2(MDB_env *env)
3798 unsigned int flags = env->me_flags;
3799 int i, newenv = 0, rc;
3803 /* See if we should use QueryLimited */
3805 if ((rc & 0xff) > 5)
3806 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
3808 env->me_pidquery = PROCESS_QUERY_INFORMATION;
3811 memset(&meta, 0, sizeof(meta));
3813 if ((i = mdb_env_read_header(env, &meta)) != 0) {
3816 DPUTS("new mdbenv");
3818 env->me_psize = env->me_os_psize;
3819 if (env->me_psize > MAX_PAGESIZE)
3820 env->me_psize = MAX_PAGESIZE;
3822 env->me_psize = meta.mm_psize;
3825 /* Was a mapsize configured? */
3826 if (!env->me_mapsize) {
3827 /* If this is a new environment, take the default,
3828 * else use the size recorded in the existing env.
3830 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
3832 if (env->me_mapsize < meta.mm_mapsize) {
3833 /* If the configured size is smaller, make sure it's
3834 * still big enough. Silently round up to minimum if not.
3836 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
3837 if (env->me_mapsize < minsize)
3838 env->me_mapsize = minsize;
3840 if (env->me_mapsize != meta.mm_mapsize)
3841 env->me_flags |= MDB_RESIZING;
3844 rc = mdb_env_map(env, (flags & MDB_FIXEDMAP) ? meta.mm_address : NULL);
3849 if (flags & MDB_FIXEDMAP)
3850 meta.mm_address = env->me_map;
3851 i = mdb_env_init_meta(env, &meta);
3852 if (i != MDB_SUCCESS) {
3857 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
3858 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
3860 #if !(MDB_MAXKEYSIZE)
3861 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
3863 env->me_maxpg = env->me_mapsize / env->me_psize;
3867 int toggle = mdb_env_pick_meta(env);
3868 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
3870 DPRINTF(("opened database version %u, pagesize %u",
3871 env->me_metas[0]->mm_version, env->me_psize));
3872 DPRINTF(("using meta page %d", toggle));
3873 DPRINTF(("depth: %u", db->md_depth));
3874 DPRINTF(("entries: %"Z"u", db->md_entries));
3875 DPRINTF(("branch pages: %"Z"u", db->md_branch_pages));
3876 DPRINTF(("leaf pages: %"Z"u", db->md_leaf_pages));
3877 DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
3878 DPRINTF(("root: %"Z"u", db->md_root));
3886 /** Release a reader thread's slot in the reader lock table.
3887 * This function is called automatically when a thread exits.
3888 * @param[in] ptr This points to the slot in the reader lock table.
3891 mdb_env_reader_dest(void *ptr)
3893 MDB_reader *reader = ptr;
3899 /** Junk for arranging thread-specific callbacks on Windows. This is
3900 * necessarily platform and compiler-specific. Windows supports up
3901 * to 1088 keys. Let's assume nobody opens more than 64 environments
3902 * in a single process, for now. They can override this if needed.
3904 #ifndef MAX_TLS_KEYS
3905 #define MAX_TLS_KEYS 64
3907 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
3908 static int mdb_tls_nkeys;
3910 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
3914 case DLL_PROCESS_ATTACH: break;
3915 case DLL_THREAD_ATTACH: break;
3916 case DLL_THREAD_DETACH:
3917 for (i=0; i<mdb_tls_nkeys; i++) {
3918 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
3920 mdb_env_reader_dest(r);
3924 case DLL_PROCESS_DETACH: break;
3929 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3931 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3935 /* Force some symbol references.
3936 * _tls_used forces the linker to create the TLS directory if not already done
3937 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
3939 #pragma comment(linker, "/INCLUDE:_tls_used")
3940 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
3941 #pragma const_seg(".CRT$XLB")
3942 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
3943 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3946 #pragma comment(linker, "/INCLUDE:__tls_used")
3947 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
3948 #pragma data_seg(".CRT$XLB")
3949 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3951 #endif /* WIN 32/64 */
3952 #endif /* !__GNUC__ */
3955 /** Downgrade the exclusive lock on the region back to shared */
3957 mdb_env_share_locks(MDB_env *env, int *excl)
3959 int rc = 0, toggle = mdb_env_pick_meta(env);
3961 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
3966 /* First acquire a shared lock. The Unlock will
3967 * then release the existing exclusive lock.
3969 memset(&ov, 0, sizeof(ov));
3970 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3973 UnlockFile(env->me_lfd, 0, 0, 1, 0);
3979 struct flock lock_info;
3980 /* The shared lock replaces the existing lock */
3981 memset((void *)&lock_info, 0, sizeof(lock_info));
3982 lock_info.l_type = F_RDLCK;
3983 lock_info.l_whence = SEEK_SET;
3984 lock_info.l_start = 0;
3985 lock_info.l_len = 1;
3986 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3987 (rc = ErrCode()) == EINTR) ;
3988 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
3995 /** Try to get exlusive lock, otherwise shared.
3996 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
3999 mdb_env_excl_lock(MDB_env *env, int *excl)
4003 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
4007 memset(&ov, 0, sizeof(ov));
4008 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4015 struct flock lock_info;
4016 memset((void *)&lock_info, 0, sizeof(lock_info));
4017 lock_info.l_type = F_WRLCK;
4018 lock_info.l_whence = SEEK_SET;
4019 lock_info.l_start = 0;
4020 lock_info.l_len = 1;
4021 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4022 (rc = ErrCode()) == EINTR) ;
4026 # ifdef MDB_USE_POSIX_SEM
4027 if (*excl < 0) /* always true when !MDB_USE_POSIX_SEM */
4030 lock_info.l_type = F_RDLCK;
4031 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
4032 (rc = ErrCode()) == EINTR) ;
4042 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
4044 * @(#) $Revision: 5.1 $
4045 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
4046 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
4048 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
4052 * Please do not copyright this code. This code is in the public domain.
4054 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
4055 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
4056 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
4057 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
4058 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4059 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4060 * PERFORMANCE OF THIS SOFTWARE.
4063 * chongo <Landon Curt Noll> /\oo/\
4064 * http://www.isthe.com/chongo/
4066 * Share and Enjoy! :-)
4069 typedef unsigned long long mdb_hash_t;
4070 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
4072 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
4073 * @param[in] val value to hash
4074 * @param[in] hval initial value for hash
4075 * @return 64 bit hash
4077 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
4078 * hval arg on the first call.
4081 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
4083 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
4084 unsigned char *end = s + val->mv_size;
4086 * FNV-1a hash each octet of the string
4089 /* xor the bottom with the current octet */
4090 hval ^= (mdb_hash_t)*s++;
4092 /* multiply by the 64 bit FNV magic prime mod 2^64 */
4093 hval += (hval << 1) + (hval << 4) + (hval << 5) +
4094 (hval << 7) + (hval << 8) + (hval << 40);
4096 /* return our new hash value */
4100 /** Hash the string and output the encoded hash.
4101 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
4102 * very short name limits. We don't care about the encoding being reversible,
4103 * we just want to preserve as many bits of the input as possible in a
4104 * small printable string.
4105 * @param[in] str string to hash
4106 * @param[out] encbuf an array of 11 chars to hold the hash
4108 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
4111 mdb_pack85(unsigned long l, char *out)
4115 for (i=0; i<5; i++) {
4116 *out++ = mdb_a85[l % 85];
4122 mdb_hash_enc(MDB_val *val, char *encbuf)
4124 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
4126 mdb_pack85(h, encbuf);
4127 mdb_pack85(h>>32, encbuf+5);
4132 /** Open and/or initialize the lock region for the environment.
4133 * @param[in] env The LMDB environment.
4134 * @param[in] lpath The pathname of the file used for the lock region.
4135 * @param[in] mode The Unix permissions for the file, if we create it.
4136 * @param[out] excl Resulting file lock type: -1 none, 0 shared, 1 exclusive
4137 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
4138 * @return 0 on success, non-zero on failure.
4141 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
4144 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
4146 # define MDB_ERRCODE_ROFS EROFS
4147 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
4148 # define MDB_CLOEXEC O_CLOEXEC
4151 # define MDB_CLOEXEC 0
4158 env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
4159 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
4160 FILE_ATTRIBUTE_NORMAL, NULL);
4162 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
4164 if (env->me_lfd == INVALID_HANDLE_VALUE) {
4166 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
4171 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
4172 /* Lose record locks when exec*() */
4173 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
4174 fcntl(env->me_lfd, F_SETFD, fdflags);
4177 if (!(env->me_flags & MDB_NOTLS)) {
4178 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
4181 env->me_flags |= MDB_ENV_TXKEY;
4183 /* Windows TLS callbacks need help finding their TLS info. */
4184 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
4188 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
4192 /* Try to get exclusive lock. If we succeed, then
4193 * nobody is using the lock region and we should initialize it.
4195 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
4198 size = GetFileSize(env->me_lfd, NULL);
4200 size = lseek(env->me_lfd, 0, SEEK_END);
4201 if (size == -1) goto fail_errno;
4203 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
4204 if (size < rsize && *excl > 0) {
4206 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
4207 || !SetEndOfFile(env->me_lfd))
4210 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
4214 size = rsize - sizeof(MDB_txninfo);
4215 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
4220 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
4222 if (!mh) goto fail_errno;
4223 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
4225 if (!env->me_txns) goto fail_errno;
4227 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
4229 if (m == MAP_FAILED) goto fail_errno;
4235 BY_HANDLE_FILE_INFORMATION stbuf;
4244 if (!mdb_sec_inited) {
4245 InitializeSecurityDescriptor(&mdb_null_sd,
4246 SECURITY_DESCRIPTOR_REVISION);
4247 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
4248 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
4249 mdb_all_sa.bInheritHandle = FALSE;
4250 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
4253 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
4254 idbuf.volume = stbuf.dwVolumeSerialNumber;
4255 idbuf.nhigh = stbuf.nFileIndexHigh;
4256 idbuf.nlow = stbuf.nFileIndexLow;
4257 val.mv_data = &idbuf;
4258 val.mv_size = sizeof(idbuf);
4259 mdb_hash_enc(&val, encbuf);
4260 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
4261 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
4262 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
4263 if (!env->me_rmutex) goto fail_errno;
4264 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
4265 if (!env->me_wmutex) goto fail_errno;
4266 #elif defined(MDB_USE_POSIX_SEM)
4275 #if defined(__NetBSD__)
4276 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
4278 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
4279 idbuf.dev = stbuf.st_dev;
4280 idbuf.ino = stbuf.st_ino;
4281 val.mv_data = &idbuf;
4282 val.mv_size = sizeof(idbuf);
4283 mdb_hash_enc(&val, encbuf);
4284 #ifdef MDB_SHORT_SEMNAMES
4285 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
4287 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
4288 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
4289 /* Clean up after a previous run, if needed: Try to
4290 * remove both semaphores before doing anything else.
4292 sem_unlink(env->me_txns->mti_rmname);
4293 sem_unlink(env->me_txns->mti_wmname);
4294 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
4295 O_CREAT|O_EXCL, mode, 1);
4296 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4297 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
4298 O_CREAT|O_EXCL, mode, 1);
4299 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4300 #else /* MDB_USE_POSIX_SEM */
4301 pthread_mutexattr_t mattr;
4303 if ((rc = pthread_mutexattr_init(&mattr))
4304 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
4305 || (rc = pthread_mutex_init(&env->me_txns->mti_mutex, &mattr))
4306 || (rc = pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr)))
4308 pthread_mutexattr_destroy(&mattr);
4309 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
4311 env->me_txns->mti_magic = MDB_MAGIC;
4312 env->me_txns->mti_format = MDB_LOCK_FORMAT;
4313 env->me_txns->mti_txnid = 0;
4314 env->me_txns->mti_numreaders = 0;
4317 if (env->me_txns->mti_magic != MDB_MAGIC) {
4318 DPUTS("lock region has invalid magic");
4322 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
4323 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
4324 env->me_txns->mti_format, MDB_LOCK_FORMAT));
4325 rc = MDB_VERSION_MISMATCH;
4329 if (rc && rc != EACCES && rc != EAGAIN) {
4333 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
4334 if (!env->me_rmutex) goto fail_errno;
4335 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
4336 if (!env->me_wmutex) goto fail_errno;
4337 #elif defined(MDB_USE_POSIX_SEM)
4338 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
4339 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4340 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
4341 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4352 /** The name of the lock file in the DB environment */
4353 #define LOCKNAME "/lock.mdb"
4354 /** The name of the data file in the DB environment */
4355 #define DATANAME "/data.mdb"
4356 /** The suffix of the lock file when no subdir is used */
4357 #define LOCKSUFF "-lock"
4358 /** Only a subset of the @ref mdb_env flags can be changed
4359 * at runtime. Changing other flags requires closing the
4360 * environment and re-opening it with the new flags.
4362 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
4363 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY|MDB_WRITEMAP| \
4364 MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
4366 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
4367 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
4371 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
4373 int oflags, rc, len, excl = -1;
4374 char *lpath, *dpath;
4376 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
4380 if (flags & MDB_NOSUBDIR) {
4381 rc = len + sizeof(LOCKSUFF) + len + 1;
4383 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
4388 if (flags & MDB_NOSUBDIR) {
4389 dpath = lpath + len + sizeof(LOCKSUFF);
4390 sprintf(lpath, "%s" LOCKSUFF, path);
4391 strcpy(dpath, path);
4393 dpath = lpath + len + sizeof(LOCKNAME);
4394 sprintf(lpath, "%s" LOCKNAME, path);
4395 sprintf(dpath, "%s" DATANAME, path);
4399 flags |= env->me_flags;
4400 if (flags & MDB_RDONLY) {
4401 /* silently ignore WRITEMAP when we're only getting read access */
4402 flags &= ~MDB_WRITEMAP;
4404 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
4405 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
4408 env->me_flags = flags |= MDB_ENV_ACTIVE;
4412 env->me_path = strdup(path);
4413 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
4414 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
4415 env->me_dbiseqs = calloc(env->me_maxdbs, sizeof(unsigned int));
4416 if (!(env->me_dbxs && env->me_path && env->me_dbflags && env->me_dbiseqs)) {
4421 /* For RDONLY, get lockfile after we know datafile exists */
4422 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
4423 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4429 if (F_ISSET(flags, MDB_RDONLY)) {
4430 oflags = GENERIC_READ;
4431 len = OPEN_EXISTING;
4433 oflags = GENERIC_READ|GENERIC_WRITE;
4436 mode = FILE_ATTRIBUTE_NORMAL;
4437 env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
4438 NULL, len, mode, NULL);
4440 if (F_ISSET(flags, MDB_RDONLY))
4443 oflags = O_RDWR | O_CREAT;
4445 env->me_fd = open(dpath, oflags, mode);
4447 if (env->me_fd == INVALID_HANDLE_VALUE) {
4452 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
4453 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4458 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
4459 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
4460 env->me_mfd = env->me_fd;
4462 /* Synchronous fd for meta writes. Needed even with
4463 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
4466 len = OPEN_EXISTING;
4467 env->me_mfd = CreateFile(dpath, oflags,
4468 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
4469 mode | FILE_FLAG_WRITE_THROUGH, NULL);
4472 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
4474 if (env->me_mfd == INVALID_HANDLE_VALUE) {
4479 DPRINTF(("opened dbenv %p", (void *) env));
4481 rc = mdb_env_share_locks(env, &excl);
4485 if (!((flags & MDB_RDONLY) ||
4486 (env->me_pbuf = calloc(1, env->me_psize))))
4492 mdb_env_close0(env, excl);
4498 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
4500 mdb_env_close0(MDB_env *env, int excl)
4504 if (!(env->me_flags & MDB_ENV_ACTIVE))
4507 /* Doing this here since me_dbxs may not exist during mdb_env_close */
4508 for (i = env->me_maxdbs; --i > MAIN_DBI; )
4509 free(env->me_dbxs[i].md_name.mv_data);
4512 free(env->me_dbiseqs);
4513 free(env->me_dbflags);
4516 free(env->me_dirty_list);
4517 mdb_midl_free(env->me_free_pgs);
4519 if (env->me_flags & MDB_ENV_TXKEY) {
4520 pthread_key_delete(env->me_txkey);
4522 /* Delete our key from the global list */
4523 for (i=0; i<mdb_tls_nkeys; i++)
4524 if (mdb_tls_keys[i] == env->me_txkey) {
4525 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
4533 munmap(env->me_map, env->me_mapsize);
4535 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
4536 (void) close(env->me_mfd);
4537 if (env->me_fd != INVALID_HANDLE_VALUE)
4538 (void) close(env->me_fd);
4540 MDB_PID_T pid = env->me_pid;
4541 /* Clearing readers is done in this function because
4542 * me_txkey with its destructor must be disabled first.
4544 for (i = env->me_numreaders; --i >= 0; )
4545 if (env->me_txns->mti_readers[i].mr_pid == pid)
4546 env->me_txns->mti_readers[i].mr_pid = 0;
4548 if (env->me_rmutex) {
4549 CloseHandle(env->me_rmutex);
4550 if (env->me_wmutex) CloseHandle(env->me_wmutex);
4552 /* Windows automatically destroys the mutexes when
4553 * the last handle closes.
4555 #elif defined(MDB_USE_POSIX_SEM)
4556 if (env->me_rmutex != SEM_FAILED) {
4557 sem_close(env->me_rmutex);
4558 if (env->me_wmutex != SEM_FAILED)
4559 sem_close(env->me_wmutex);
4560 /* If we have the filelock: If we are the
4561 * only remaining user, clean up semaphores.
4564 mdb_env_excl_lock(env, &excl);
4566 sem_unlink(env->me_txns->mti_rmname);
4567 sem_unlink(env->me_txns->mti_wmname);
4571 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
4573 if (env->me_lfd != INVALID_HANDLE_VALUE) {
4576 /* Unlock the lockfile. Windows would have unlocked it
4577 * after closing anyway, but not necessarily at once.
4579 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4582 (void) close(env->me_lfd);
4585 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
4590 mdb_env_close(MDB_env *env)
4597 VGMEMP_DESTROY(env);
4598 while ((dp = env->me_dpages) != NULL) {
4599 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
4600 env->me_dpages = dp->mp_next;
4604 mdb_env_close0(env, 0);
4608 /** Compare two items pointing at aligned size_t's */
4610 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
4612 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
4613 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
4616 /** Compare two items pointing at aligned unsigned int's */
4618 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
4620 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
4621 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
4624 /** Compare two items pointing at unsigned ints of unknown alignment.
4625 * Nodes and keys are guaranteed to be 2-byte aligned.
4628 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
4630 #if BYTE_ORDER == LITTLE_ENDIAN
4631 unsigned short *u, *c;
4634 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4635 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
4638 } while(!x && u > (unsigned short *)a->mv_data);
4641 unsigned short *u, *c, *end;
4644 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4645 u = (unsigned short *)a->mv_data;
4646 c = (unsigned short *)b->mv_data;
4649 } while(!x && u < end);
4654 /** Compare two items pointing at size_t's of unknown alignment. */
4655 #ifdef MISALIGNED_OK
4656 # define mdb_cmp_clong mdb_cmp_long
4658 # define mdb_cmp_clong mdb_cmp_cint
4661 /** Compare two items lexically */
4663 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
4670 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4676 diff = memcmp(a->mv_data, b->mv_data, len);
4677 return diff ? diff : len_diff<0 ? -1 : len_diff;
4680 /** Compare two items in reverse byte order */
4682 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
4684 const unsigned char *p1, *p2, *p1_lim;
4688 p1_lim = (const unsigned char *)a->mv_data;
4689 p1 = (const unsigned char *)a->mv_data + a->mv_size;
4690 p2 = (const unsigned char *)b->mv_data + b->mv_size;
4692 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4698 while (p1 > p1_lim) {
4699 diff = *--p1 - *--p2;
4703 return len_diff<0 ? -1 : len_diff;
4706 /** Search for key within a page, using binary search.
4707 * Returns the smallest entry larger or equal to the key.
4708 * If exactp is non-null, stores whether the found entry was an exact match
4709 * in *exactp (1 or 0).
4710 * Updates the cursor index with the index of the found entry.
4711 * If no entry larger or equal to the key is found, returns NULL.
4714 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
4716 unsigned int i = 0, nkeys;
4719 MDB_page *mp = mc->mc_pg[mc->mc_top];
4720 MDB_node *node = NULL;
4725 nkeys = NUMKEYS(mp);
4727 DPRINTF(("searching %u keys in %s %spage %"Z"u",
4728 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
4731 low = IS_LEAF(mp) ? 0 : 1;
4733 cmp = mc->mc_dbx->md_cmp;
4735 /* Branch pages have no data, so if using integer keys,
4736 * alignment is guaranteed. Use faster mdb_cmp_int.
4738 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
4739 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
4746 nodekey.mv_size = mc->mc_db->md_pad;
4747 node = NODEPTR(mp, 0); /* fake */
4748 while (low <= high) {
4749 i = (low + high) >> 1;
4750 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
4751 rc = cmp(key, &nodekey);
4752 DPRINTF(("found leaf index %u [%s], rc = %i",
4753 i, DKEY(&nodekey), rc));
4762 while (low <= high) {
4763 i = (low + high) >> 1;
4765 node = NODEPTR(mp, i);
4766 nodekey.mv_size = NODEKSZ(node);
4767 nodekey.mv_data = NODEKEY(node);
4769 rc = cmp(key, &nodekey);
4772 DPRINTF(("found leaf index %u [%s], rc = %i",
4773 i, DKEY(&nodekey), rc));
4775 DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
4776 i, DKEY(&nodekey), NODEPGNO(node), rc));
4787 if (rc > 0) { /* Found entry is less than the key. */
4788 i++; /* Skip to get the smallest entry larger than key. */
4790 node = NODEPTR(mp, i);
4793 *exactp = (rc == 0 && nkeys > 0);
4794 /* store the key index */
4795 mc->mc_ki[mc->mc_top] = i;
4797 /* There is no entry larger or equal to the key. */
4800 /* nodeptr is fake for LEAF2 */
4806 mdb_cursor_adjust(MDB_cursor *mc, func)
4810 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4811 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
4818 /** Pop a page off the top of the cursor's stack. */
4820 mdb_cursor_pop(MDB_cursor *mc)
4824 MDB_page *top = mc->mc_pg[mc->mc_top];
4830 DPRINTF(("popped page %"Z"u off db %d cursor %p", top->mp_pgno,
4831 DDBI(mc), (void *) mc));
4835 /** Push a page onto the top of the cursor's stack. */
4837 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
4839 DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
4840 DDBI(mc), (void *) mc));
4842 if (mc->mc_snum >= CURSOR_STACK) {
4843 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4844 return MDB_CURSOR_FULL;
4847 mc->mc_top = mc->mc_snum++;
4848 mc->mc_pg[mc->mc_top] = mp;
4849 mc->mc_ki[mc->mc_top] = 0;
4854 /** Find the address of the page corresponding to a given page number.
4855 * @param[in] txn the transaction for this access.
4856 * @param[in] pgno the page number for the page to retrieve.
4857 * @param[out] ret address of a pointer where the page's address will be stored.
4858 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
4859 * @return 0 on success, non-zero on failure.
4862 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
4864 MDB_env *env = txn->mt_env;
4868 if (!((txn->mt_flags & MDB_TXN_RDONLY) | (env->me_flags & MDB_WRITEMAP))) {
4872 MDB_ID2L dl = tx2->mt_u.dirty_list;
4874 /* Spilled pages were dirtied in this txn and flushed
4875 * because the dirty list got full. Bring this page
4876 * back in from the map (but don't unspill it here,
4877 * leave that unless page_touch happens again).
4879 if (tx2->mt_spill_pgs) {
4880 MDB_ID pn = pgno << 1;
4881 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
4882 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
4883 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
4888 unsigned x = mdb_mid2l_search(dl, pgno);
4889 if (x <= dl[0].mid && dl[x].mid == pgno) {
4895 } while ((tx2 = tx2->mt_parent) != NULL);
4898 if (pgno < txn->mt_next_pgno) {
4900 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
4902 DPRINTF(("page %"Z"u not found", pgno));
4903 txn->mt_flags |= MDB_TXN_ERROR;
4904 return MDB_PAGE_NOTFOUND;
4914 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
4915 * The cursor is at the root page, set up the rest of it.
4918 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
4920 MDB_page *mp = mc->mc_pg[mc->mc_top];
4924 while (IS_BRANCH(mp)) {
4928 DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
4929 mdb_cassert(mc, NUMKEYS(mp) > 1);
4930 DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
4932 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
4934 if (flags & MDB_PS_LAST)
4935 i = NUMKEYS(mp) - 1;
4938 node = mdb_node_search(mc, key, &exact);
4940 i = NUMKEYS(mp) - 1;
4942 i = mc->mc_ki[mc->mc_top];
4944 mdb_cassert(mc, i > 0);
4948 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
4951 mdb_cassert(mc, i < NUMKEYS(mp));
4952 node = NODEPTR(mp, i);
4954 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4957 mc->mc_ki[mc->mc_top] = i;
4958 if ((rc = mdb_cursor_push(mc, mp)))
4961 if (flags & MDB_PS_MODIFY) {
4962 if ((rc = mdb_page_touch(mc)) != 0)
4964 mp = mc->mc_pg[mc->mc_top];
4969 DPRINTF(("internal error, index points to a %02X page!?",
4971 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4972 return MDB_CORRUPTED;
4975 DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
4976 key ? DKEY(key) : "null"));
4977 mc->mc_flags |= C_INITIALIZED;
4978 mc->mc_flags &= ~C_EOF;
4983 /** Search for the lowest key under the current branch page.
4984 * This just bypasses a NUMKEYS check in the current page
4985 * before calling mdb_page_search_root(), because the callers
4986 * are all in situations where the current page is known to
4990 mdb_page_search_lowest(MDB_cursor *mc)
4992 MDB_page *mp = mc->mc_pg[mc->mc_top];
4993 MDB_node *node = NODEPTR(mp, 0);
4996 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4999 mc->mc_ki[mc->mc_top] = 0;
5000 if ((rc = mdb_cursor_push(mc, mp)))
5002 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
5005 /** Search for the page a given key should be in.
5006 * Push it and its parent pages on the cursor stack.
5007 * @param[in,out] mc the cursor for this operation.
5008 * @param[in] key the key to search for, or NULL for first/last page.
5009 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
5010 * are touched (updated with new page numbers).
5011 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
5012 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
5013 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
5014 * @return 0 on success, non-zero on failure.
5017 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
5022 /* Make sure the txn is still viable, then find the root from
5023 * the txn's db table and set it as the root of the cursor's stack.
5025 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
5026 DPUTS("transaction has failed, must abort");
5029 /* Make sure we're using an up-to-date root */
5030 if (*mc->mc_dbflag & DB_STALE) {
5032 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
5034 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
5035 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
5042 MDB_node *leaf = mdb_node_search(&mc2,
5043 &mc->mc_dbx->md_name, &exact);
5045 return MDB_NOTFOUND;
5046 rc = mdb_node_read(mc->mc_txn, leaf, &data);
5049 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
5051 /* The txn may not know this DBI, or another process may
5052 * have dropped and recreated the DB with other flags.
5054 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
5055 return MDB_INCOMPATIBLE;
5056 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
5058 *mc->mc_dbflag &= ~DB_STALE;
5060 root = mc->mc_db->md_root;
5062 if (root == P_INVALID) { /* Tree is empty. */
5063 DPUTS("tree is empty");
5064 return MDB_NOTFOUND;
5068 mdb_cassert(mc, root > 1);
5069 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
5070 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0], NULL)) != 0)
5076 DPRINTF(("db %d root page %"Z"u has flags 0x%X",
5077 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
5079 if (flags & MDB_PS_MODIFY) {
5080 if ((rc = mdb_page_touch(mc)))
5084 if (flags & MDB_PS_ROOTONLY)
5087 return mdb_page_search_root(mc, key, flags);
5091 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
5093 MDB_txn *txn = mc->mc_txn;
5094 pgno_t pg = mp->mp_pgno;
5095 unsigned x = 0, ovpages = mp->mp_pages;
5096 MDB_env *env = txn->mt_env;
5097 MDB_IDL sl = txn->mt_spill_pgs;
5098 MDB_ID pn = pg << 1;
5101 DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
5102 /* If the page is dirty or on the spill list we just acquired it,
5103 * so we should give it back to our current free list, if any.
5104 * Otherwise put it onto the list of pages we freed in this txn.
5106 * Won't create me_pghead: me_pglast must be inited along with it.
5107 * Unsupported in nested txns: They would need to hide the page
5108 * range in ancestor txns' dirty and spilled lists.
5110 if (env->me_pghead &&
5112 ((mp->mp_flags & P_DIRTY) ||
5113 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
5117 MDB_ID2 *dl, ix, iy;
5118 rc = mdb_midl_need(&env->me_pghead, ovpages);
5121 if (!(mp->mp_flags & P_DIRTY)) {
5122 /* This page is no longer spilled */
5129 /* Remove from dirty list */
5130 dl = txn->mt_u.dirty_list;
5132 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
5138 mdb_cassert(mc, x > 1);
5140 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
5141 txn->mt_flags |= MDB_TXN_ERROR;
5142 return MDB_CORRUPTED;
5145 if (!(env->me_flags & MDB_WRITEMAP))
5146 mdb_dpage_free(env, mp);
5148 /* Insert in me_pghead */
5149 mop = env->me_pghead;
5150 j = mop[0] + ovpages;
5151 for (i = mop[0]; i && mop[i] < pg; i--)
5157 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
5161 mc->mc_db->md_overflow_pages -= ovpages;
5165 /** Return the data associated with a given node.
5166 * @param[in] txn The transaction for this operation.
5167 * @param[in] leaf The node being read.
5168 * @param[out] data Updated to point to the node's data.
5169 * @return 0 on success, non-zero on failure.
5172 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
5174 MDB_page *omp; /* overflow page */
5178 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5179 data->mv_size = NODEDSZ(leaf);
5180 data->mv_data = NODEDATA(leaf);
5184 /* Read overflow data.
5186 data->mv_size = NODEDSZ(leaf);
5187 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
5188 if ((rc = mdb_page_get(txn, pgno, &omp, NULL)) != 0) {
5189 DPRINTF(("read overflow page %"Z"u failed", pgno));
5192 data->mv_data = METADATA(omp);
5198 mdb_get(MDB_txn *txn, MDB_dbi dbi,
5199 MDB_val *key, MDB_val *data)
5206 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
5208 if (!key || !data || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
5211 if (txn->mt_flags & MDB_TXN_ERROR)
5214 mdb_cursor_init(&mc, txn, dbi, &mx);
5215 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
5218 /** Find a sibling for a page.
5219 * Replaces the page at the top of the cursor's stack with the
5220 * specified sibling, if one exists.
5221 * @param[in] mc The cursor for this operation.
5222 * @param[in] move_right Non-zero if the right sibling is requested,
5223 * otherwise the left sibling.
5224 * @return 0 on success, non-zero on failure.
5227 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
5233 if (mc->mc_snum < 2) {
5234 return MDB_NOTFOUND; /* root has no siblings */
5238 DPRINTF(("parent page is page %"Z"u, index %u",
5239 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
5241 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
5242 : (mc->mc_ki[mc->mc_top] == 0)) {
5243 DPRINTF(("no more keys left, moving to %s sibling",
5244 move_right ? "right" : "left"));
5245 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
5246 /* undo cursor_pop before returning */
5253 mc->mc_ki[mc->mc_top]++;
5255 mc->mc_ki[mc->mc_top]--;
5256 DPRINTF(("just moving to %s index key %u",
5257 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
5259 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
5261 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5262 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL)) != 0) {
5263 /* mc will be inconsistent if caller does mc_snum++ as above */
5264 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
5268 mdb_cursor_push(mc, mp);
5270 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
5275 /** Move the cursor to the next data item. */
5277 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5283 if (mc->mc_flags & C_EOF) {
5284 return MDB_NOTFOUND;
5287 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5289 mp = mc->mc_pg[mc->mc_top];
5291 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5292 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5293 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5294 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
5295 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
5296 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
5297 if (rc == MDB_SUCCESS)
5298 MDB_GET_KEY(leaf, key);
5303 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5304 if (op == MDB_NEXT_DUP)
5305 return MDB_NOTFOUND;
5309 DPRINTF(("cursor_next: top page is %"Z"u in cursor %p",
5310 mdb_dbg_pgno(mp), (void *) mc));
5311 if (mc->mc_flags & C_DEL)
5314 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
5315 DPUTS("=====> move to next sibling page");
5316 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5317 mc->mc_flags |= C_EOF;
5320 mp = mc->mc_pg[mc->mc_top];
5321 DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5323 mc->mc_ki[mc->mc_top]++;
5326 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5327 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5330 key->mv_size = mc->mc_db->md_pad;
5331 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5335 mdb_cassert(mc, IS_LEAF(mp));
5336 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5338 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5339 mdb_xcursor_init1(mc, leaf);
5342 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5345 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5346 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5347 if (rc != MDB_SUCCESS)
5352 MDB_GET_KEY(leaf, key);
5356 /** Move the cursor to the previous data item. */
5358 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5364 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5366 mp = mc->mc_pg[mc->mc_top];
5368 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5369 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5370 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5371 if (op == MDB_PREV || op == MDB_PREV_DUP) {
5372 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
5373 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
5374 if (rc == MDB_SUCCESS)
5375 MDB_GET_KEY(leaf, key);
5379 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5380 if (op == MDB_PREV_DUP)
5381 return MDB_NOTFOUND;
5386 DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p",
5387 mdb_dbg_pgno(mp), (void *) mc));
5389 if (mc->mc_ki[mc->mc_top] == 0) {
5390 DPUTS("=====> move to prev sibling page");
5391 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
5394 mp = mc->mc_pg[mc->mc_top];
5395 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
5396 DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5398 mc->mc_ki[mc->mc_top]--;
5400 mc->mc_flags &= ~C_EOF;
5402 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5403 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5406 key->mv_size = mc->mc_db->md_pad;
5407 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5411 mdb_cassert(mc, IS_LEAF(mp));
5412 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5414 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5415 mdb_xcursor_init1(mc, leaf);
5418 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5421 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5422 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5423 if (rc != MDB_SUCCESS)
5428 MDB_GET_KEY(leaf, key);
5432 /** Set the cursor on a specific data item. */
5434 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5435 MDB_cursor_op op, int *exactp)
5439 MDB_node *leaf = NULL;
5442 if (key->mv_size == 0)
5443 return MDB_BAD_VALSIZE;
5446 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5448 /* See if we're already on the right page */
5449 if (mc->mc_flags & C_INITIALIZED) {
5452 mp = mc->mc_pg[mc->mc_top];
5454 mc->mc_ki[mc->mc_top] = 0;
5455 return MDB_NOTFOUND;
5457 if (mp->mp_flags & P_LEAF2) {
5458 nodekey.mv_size = mc->mc_db->md_pad;
5459 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
5461 leaf = NODEPTR(mp, 0);
5462 MDB_GET_KEY2(leaf, nodekey);
5464 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5466 /* Probably happens rarely, but first node on the page
5467 * was the one we wanted.
5469 mc->mc_ki[mc->mc_top] = 0;
5476 unsigned int nkeys = NUMKEYS(mp);
5478 if (mp->mp_flags & P_LEAF2) {
5479 nodekey.mv_data = LEAF2KEY(mp,
5480 nkeys-1, nodekey.mv_size);
5482 leaf = NODEPTR(mp, nkeys-1);
5483 MDB_GET_KEY2(leaf, nodekey);
5485 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5487 /* last node was the one we wanted */
5488 mc->mc_ki[mc->mc_top] = nkeys-1;
5494 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
5495 /* This is definitely the right page, skip search_page */
5496 if (mp->mp_flags & P_LEAF2) {
5497 nodekey.mv_data = LEAF2KEY(mp,
5498 mc->mc_ki[mc->mc_top], nodekey.mv_size);
5500 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5501 MDB_GET_KEY2(leaf, nodekey);
5503 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5505 /* current node was the one we wanted */
5515 /* If any parents have right-sibs, search.
5516 * Otherwise, there's nothing further.
5518 for (i=0; i<mc->mc_top; i++)
5520 NUMKEYS(mc->mc_pg[i])-1)
5522 if (i == mc->mc_top) {
5523 /* There are no other pages */
5524 mc->mc_ki[mc->mc_top] = nkeys;
5525 return MDB_NOTFOUND;
5529 /* There are no other pages */
5530 mc->mc_ki[mc->mc_top] = 0;
5531 if (op == MDB_SET_RANGE && !exactp) {
5535 return MDB_NOTFOUND;
5539 rc = mdb_page_search(mc, key, 0);
5540 if (rc != MDB_SUCCESS)
5543 mp = mc->mc_pg[mc->mc_top];
5544 mdb_cassert(mc, IS_LEAF(mp));
5547 leaf = mdb_node_search(mc, key, exactp);
5548 if (exactp != NULL && !*exactp) {
5549 /* MDB_SET specified and not an exact match. */
5550 return MDB_NOTFOUND;
5554 DPUTS("===> inexact leaf not found, goto sibling");
5555 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
5556 return rc; /* no entries matched */
5557 mp = mc->mc_pg[mc->mc_top];
5558 mdb_cassert(mc, IS_LEAF(mp));
5559 leaf = NODEPTR(mp, 0);
5563 mc->mc_flags |= C_INITIALIZED;
5564 mc->mc_flags &= ~C_EOF;
5567 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
5568 key->mv_size = mc->mc_db->md_pad;
5569 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5574 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5575 mdb_xcursor_init1(mc, leaf);
5578 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5579 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
5580 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5583 if (op == MDB_GET_BOTH) {
5589 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
5590 if (rc != MDB_SUCCESS)
5593 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
5595 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
5597 rc = mc->mc_dbx->md_dcmp(data, &d2);
5599 if (op == MDB_GET_BOTH || rc > 0)
5600 return MDB_NOTFOUND;
5607 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5608 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5613 /* The key already matches in all other cases */
5614 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
5615 MDB_GET_KEY(leaf, key);
5616 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
5621 /** Move the cursor to the first item in the database. */
5623 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5629 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5631 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5632 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
5633 if (rc != MDB_SUCCESS)
5636 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
5638 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
5639 mc->mc_flags |= C_INITIALIZED;
5640 mc->mc_flags &= ~C_EOF;
5642 mc->mc_ki[mc->mc_top] = 0;
5644 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5645 key->mv_size = mc->mc_db->md_pad;
5646 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
5651 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5652 mdb_xcursor_init1(mc, leaf);
5653 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5657 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5661 MDB_GET_KEY(leaf, key);
5665 /** Move the cursor to the last item in the database. */
5667 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5673 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5675 if (!(mc->mc_flags & C_EOF)) {
5677 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5678 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
5679 if (rc != MDB_SUCCESS)
5682 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
5685 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
5686 mc->mc_flags |= C_INITIALIZED|C_EOF;
5687 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5689 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5690 key->mv_size = mc->mc_db->md_pad;
5691 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
5696 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5697 mdb_xcursor_init1(mc, leaf);
5698 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5702 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5707 MDB_GET_KEY(leaf, key);
5712 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5717 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
5722 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
5726 case MDB_GET_CURRENT:
5727 if (!(mc->mc_flags & C_INITIALIZED)) {
5730 MDB_page *mp = mc->mc_pg[mc->mc_top];
5731 int nkeys = NUMKEYS(mp);
5732 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
5733 mc->mc_ki[mc->mc_top] = nkeys;
5739 key->mv_size = mc->mc_db->md_pad;
5740 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5742 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5743 MDB_GET_KEY(leaf, key);
5745 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5746 if (mc->mc_flags & C_DEL)
5747 mdb_xcursor_init1(mc, leaf);
5748 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
5750 rc = mdb_node_read(mc->mc_txn, leaf, data);
5757 case MDB_GET_BOTH_RANGE:
5762 if (mc->mc_xcursor == NULL) {
5763 rc = MDB_INCOMPATIBLE;
5773 rc = mdb_cursor_set(mc, key, data, op,
5774 op == MDB_SET_RANGE ? NULL : &exact);
5777 case MDB_GET_MULTIPLE:
5778 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5782 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5783 rc = MDB_INCOMPATIBLE;
5787 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
5788 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
5791 case MDB_NEXT_MULTIPLE:
5796 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5797 rc = MDB_INCOMPATIBLE;
5800 if (!(mc->mc_flags & C_INITIALIZED))
5801 rc = mdb_cursor_first(mc, key, data);
5803 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
5804 if (rc == MDB_SUCCESS) {
5805 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
5808 mx = &mc->mc_xcursor->mx_cursor;
5809 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
5811 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
5812 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
5820 case MDB_NEXT_NODUP:
5821 if (!(mc->mc_flags & C_INITIALIZED))
5822 rc = mdb_cursor_first(mc, key, data);
5824 rc = mdb_cursor_next(mc, key, data, op);
5828 case MDB_PREV_NODUP:
5829 if (!(mc->mc_flags & C_INITIALIZED)) {
5830 rc = mdb_cursor_last(mc, key, data);
5833 mc->mc_flags |= C_INITIALIZED;
5834 mc->mc_ki[mc->mc_top]++;
5836 rc = mdb_cursor_prev(mc, key, data, op);
5839 rc = mdb_cursor_first(mc, key, data);
5842 mfunc = mdb_cursor_first;
5844 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5848 if (mc->mc_xcursor == NULL) {
5849 rc = MDB_INCOMPATIBLE;
5852 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
5856 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
5859 rc = mdb_cursor_last(mc, key, data);
5862 mfunc = mdb_cursor_last;
5865 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
5870 if (mc->mc_flags & C_DEL)
5871 mc->mc_flags ^= C_DEL;
5876 /** Touch all the pages in the cursor stack. Set mc_top.
5877 * Makes sure all the pages are writable, before attempting a write operation.
5878 * @param[in] mc The cursor to operate on.
5881 mdb_cursor_touch(MDB_cursor *mc)
5883 int rc = MDB_SUCCESS;
5885 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
5888 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
5890 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
5891 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
5894 *mc->mc_dbflag |= DB_DIRTY;
5899 rc = mdb_page_touch(mc);
5900 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
5901 mc->mc_top = mc->mc_snum-1;
5906 /** Do not spill pages to disk if txn is getting full, may fail instead */
5907 #define MDB_NOSPILL 0x8000
5910 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5913 enum { MDB_NO_ROOT = MDB_LAST_ERRCODE+10 }; /* internal code */
5915 MDB_node *leaf = NULL;
5918 MDB_val xdata, *rdata, dkey, olddata;
5920 int do_sub = 0, insert_key, insert_data;
5921 unsigned int mcount = 0, dcount = 0, nospill;
5924 unsigned int nflags;
5927 if (mc == NULL || key == NULL)
5930 env = mc->mc_txn->mt_env;
5932 /* Check this first so counter will always be zero on any
5935 if (flags & MDB_MULTIPLE) {
5936 dcount = data[1].mv_size;
5937 data[1].mv_size = 0;
5938 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
5939 return MDB_INCOMPATIBLE;
5942 nospill = flags & MDB_NOSPILL;
5943 flags &= ~MDB_NOSPILL;
5945 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
5946 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
5948 if (key->mv_size-1 >= ENV_MAXKEY(env))
5949 return MDB_BAD_VALSIZE;
5951 #if SIZE_MAX > MAXDATASIZE
5952 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
5953 return MDB_BAD_VALSIZE;
5955 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
5956 return MDB_BAD_VALSIZE;
5959 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
5960 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
5964 if (flags == MDB_CURRENT) {
5965 if (!(mc->mc_flags & C_INITIALIZED))
5968 } else if (mc->mc_db->md_root == P_INVALID) {
5969 /* new database, cursor has nothing to point to */
5972 mc->mc_flags &= ~C_INITIALIZED;
5977 if (flags & MDB_APPEND) {
5979 rc = mdb_cursor_last(mc, &k2, &d2);
5981 rc = mc->mc_dbx->md_cmp(key, &k2);
5984 mc->mc_ki[mc->mc_top]++;
5986 /* new key is <= last key */
5991 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
5993 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
5994 DPRINTF(("duplicate key [%s]", DKEY(key)));
5996 return MDB_KEYEXIST;
5998 if (rc && rc != MDB_NOTFOUND)
6002 if (mc->mc_flags & C_DEL)
6003 mc->mc_flags ^= C_DEL;
6005 /* Cursor is positioned, check for room in the dirty list */
6007 if (flags & MDB_MULTIPLE) {
6009 xdata.mv_size = data->mv_size * dcount;
6013 if ((rc2 = mdb_page_spill(mc, key, rdata)))
6017 if (rc == MDB_NO_ROOT) {
6019 /* new database, write a root leaf page */
6020 DPUTS("allocating new root leaf page");
6021 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
6024 mdb_cursor_push(mc, np);
6025 mc->mc_db->md_root = np->mp_pgno;
6026 mc->mc_db->md_depth++;
6027 *mc->mc_dbflag |= DB_DIRTY;
6028 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
6030 np->mp_flags |= P_LEAF2;
6031 mc->mc_flags |= C_INITIALIZED;
6033 /* make sure all cursor pages are writable */
6034 rc2 = mdb_cursor_touch(mc);
6039 insert_key = insert_data = rc;
6041 /* The key does not exist */
6042 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
6043 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
6044 LEAFSIZE(key, data) > env->me_nodemax)
6046 /* Too big for a node, insert in sub-DB. Set up an empty
6047 * "old sub-page" for prep_subDB to expand to a full page.
6049 fp_flags = P_LEAF|P_DIRTY;
6051 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
6052 fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
6053 olddata.mv_size = PAGEHDRSZ;
6057 /* there's only a key anyway, so this is a no-op */
6058 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6060 unsigned int ksize = mc->mc_db->md_pad;
6061 if (key->mv_size != ksize)
6062 return MDB_BAD_VALSIZE;
6063 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
6064 memcpy(ptr, key->mv_data, ksize);
6069 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6070 olddata.mv_size = NODEDSZ(leaf);
6071 olddata.mv_data = NODEDATA(leaf);
6074 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
6075 /* Prepare (sub-)page/sub-DB to accept the new item,
6076 * if needed. fp: old sub-page or a header faking
6077 * it. mp: new (sub-)page. offset: growth in page
6078 * size. xdata: node data with new page or DB.
6080 unsigned i, offset = 0;
6081 mp = fp = xdata.mv_data = env->me_pbuf;
6082 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
6084 /* Was a single item before, must convert now */
6085 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6086 /* Just overwrite the current item */
6087 if (flags == MDB_CURRENT)
6090 #if UINT_MAX < SIZE_MAX
6091 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
6092 mc->mc_dbx->md_dcmp = mdb_cmp_clong;
6094 /* does data match? */
6095 if (!mc->mc_dbx->md_dcmp(data, &olddata)) {
6096 if (flags & MDB_NODUPDATA)
6097 return MDB_KEYEXIST;
6102 /* Back up original data item */
6103 dkey.mv_size = olddata.mv_size;
6104 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
6106 /* Make sub-page header for the dup items, with dummy body */
6107 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
6108 fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
6109 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
6110 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6111 fp->mp_flags |= P_LEAF2;
6112 fp->mp_pad = data->mv_size;
6113 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
6115 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
6116 (dkey.mv_size & 1) + (data->mv_size & 1);
6118 fp->mp_upper = xdata.mv_size - PAGEBASE;
6119 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
6120 } else if (leaf->mn_flags & F_SUBDATA) {
6121 /* Data is on sub-DB, just store it */
6122 flags |= F_DUPDATA|F_SUBDATA;
6125 /* Data is on sub-page */
6126 fp = olddata.mv_data;
6129 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6130 offset = EVEN(NODESIZE + sizeof(indx_t) +
6134 offset = fp->mp_pad;
6135 if (SIZELEFT(fp) < offset) {
6136 offset *= 4; /* space for 4 more */
6139 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
6141 fp->mp_flags |= P_DIRTY;
6142 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
6143 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
6147 xdata.mv_size = olddata.mv_size + offset;
6150 fp_flags = fp->mp_flags;
6151 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
6152 /* Too big for a sub-page, convert to sub-DB */
6153 fp_flags &= ~P_SUBP;
6155 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6156 fp_flags |= P_LEAF2;
6157 dummy.md_pad = fp->mp_pad;
6158 dummy.md_flags = MDB_DUPFIXED;
6159 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6160 dummy.md_flags |= MDB_INTEGERKEY;
6166 dummy.md_branch_pages = 0;
6167 dummy.md_leaf_pages = 1;
6168 dummy.md_overflow_pages = 0;
6169 dummy.md_entries = NUMKEYS(fp);
6170 xdata.mv_size = sizeof(MDB_db);
6171 xdata.mv_data = &dummy;
6172 if ((rc = mdb_page_alloc(mc, 1, &mp)))
6174 offset = env->me_psize - olddata.mv_size;
6175 flags |= F_DUPDATA|F_SUBDATA;
6176 dummy.md_root = mp->mp_pgno;
6179 mp->mp_flags = fp_flags | P_DIRTY;
6180 mp->mp_pad = fp->mp_pad;
6181 mp->mp_lower = fp->mp_lower;
6182 mp->mp_upper = fp->mp_upper + offset;
6183 if (fp_flags & P_LEAF2) {
6184 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
6186 memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
6187 olddata.mv_size - fp->mp_upper - PAGEBASE);
6188 for (i=0; i<NUMKEYS(fp); i++)
6189 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
6197 mdb_node_del(mc, 0);
6201 /* overflow page overwrites need special handling */
6202 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6205 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
6207 memcpy(&pg, olddata.mv_data, sizeof(pg));
6208 if ((rc2 = mdb_page_get(mc->mc_txn, pg, &omp, &level)) != 0)
6210 ovpages = omp->mp_pages;
6212 /* Is the ov page large enough? */
6213 if (ovpages >= dpages) {
6214 if (!(omp->mp_flags & P_DIRTY) &&
6215 (level || (env->me_flags & MDB_WRITEMAP)))
6217 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
6220 level = 0; /* dirty in this txn or clean */
6223 if (omp->mp_flags & P_DIRTY) {
6224 /* yes, overwrite it. Note in this case we don't
6225 * bother to try shrinking the page if the new data
6226 * is smaller than the overflow threshold.
6229 /* It is writable only in a parent txn */
6230 size_t sz = (size_t) env->me_psize * ovpages, off;
6231 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
6237 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
6238 mdb_cassert(mc, rc2 == 0);
6239 if (!(flags & MDB_RESERVE)) {
6240 /* Copy end of page, adjusting alignment so
6241 * compiler may copy words instead of bytes.
6243 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
6244 memcpy((size_t *)((char *)np + off),
6245 (size_t *)((char *)omp + off), sz - off);
6248 memcpy(np, omp, sz); /* Copy beginning of page */
6251 SETDSZ(leaf, data->mv_size);
6252 if (F_ISSET(flags, MDB_RESERVE))
6253 data->mv_data = METADATA(omp);
6255 memcpy(METADATA(omp), data->mv_data, data->mv_size);
6259 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
6261 } else if (data->mv_size == olddata.mv_size) {
6262 /* same size, just replace it. Note that we could
6263 * also reuse this node if the new data is smaller,
6264 * but instead we opt to shrink the node in that case.
6266 if (F_ISSET(flags, MDB_RESERVE))
6267 data->mv_data = olddata.mv_data;
6268 else if (!(mc->mc_flags & C_SUB))
6269 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
6271 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
6274 mdb_node_del(mc, 0);
6280 nflags = flags & NODE_ADD_FLAGS;
6281 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
6282 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
6283 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
6284 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
6286 nflags |= MDB_SPLIT_REPLACE;
6287 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
6289 /* There is room already in this leaf page. */
6290 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
6291 if (rc == 0 && insert_key) {
6292 /* Adjust other cursors pointing to mp */
6293 MDB_cursor *m2, *m3;
6294 MDB_dbi dbi = mc->mc_dbi;
6295 unsigned i = mc->mc_top;
6296 MDB_page *mp = mc->mc_pg[i];
6298 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6299 if (mc->mc_flags & C_SUB)
6300 m3 = &m2->mc_xcursor->mx_cursor;
6303 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
6304 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
6311 if (rc == MDB_SUCCESS) {
6312 /* Now store the actual data in the child DB. Note that we're
6313 * storing the user data in the keys field, so there are strict
6314 * size limits on dupdata. The actual data fields of the child
6315 * DB are all zero size.
6323 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6324 if (flags & MDB_CURRENT) {
6325 xflags = MDB_CURRENT|MDB_NOSPILL;
6327 mdb_xcursor_init1(mc, leaf);
6328 xflags = (flags & MDB_NODUPDATA) ?
6329 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
6331 /* converted, write the original data first */
6333 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
6337 /* Adjust other cursors pointing to mp */
6339 unsigned i = mc->mc_top;
6340 MDB_page *mp = mc->mc_pg[i];
6342 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6343 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6344 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6345 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
6346 mdb_xcursor_init1(m2, leaf);
6350 /* we've done our job */
6353 ecount = mc->mc_xcursor->mx_db.md_entries;
6354 if (flags & MDB_APPENDDUP)
6355 xflags |= MDB_APPEND;
6356 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
6357 if (flags & F_SUBDATA) {
6358 void *db = NODEDATA(leaf);
6359 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6361 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
6363 /* Increment count unless we just replaced an existing item. */
6365 mc->mc_db->md_entries++;
6367 /* Invalidate txn if we created an empty sub-DB */
6370 /* If we succeeded and the key didn't exist before,
6371 * make sure the cursor is marked valid.
6373 mc->mc_flags |= C_INITIALIZED;
6375 if (flags & MDB_MULTIPLE) {
6378 /* let caller know how many succeeded, if any */
6379 data[1].mv_size = mcount;
6380 if (mcount < dcount) {
6381 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
6382 insert_key = insert_data = 0;
6389 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
6392 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6397 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
6403 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
6404 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6406 if (!(mc->mc_flags & C_INITIALIZED))
6409 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6410 return MDB_NOTFOUND;
6412 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
6415 rc = mdb_cursor_touch(mc);
6419 mp = mc->mc_pg[mc->mc_top];
6422 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6424 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6425 if (flags & MDB_NODUPDATA) {
6426 /* mdb_cursor_del0() will subtract the final entry */
6427 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
6429 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
6430 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6432 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
6435 /* If sub-DB still has entries, we're done */
6436 if (mc->mc_xcursor->mx_db.md_entries) {
6437 if (leaf->mn_flags & F_SUBDATA) {
6438 /* update subDB info */
6439 void *db = NODEDATA(leaf);
6440 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6443 /* shrink fake page */
6444 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
6445 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6446 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6447 /* fix other sub-DB cursors pointed at this fake page */
6448 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6449 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6450 if (m2->mc_pg[mc->mc_top] == mp &&
6451 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
6452 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6455 mc->mc_db->md_entries--;
6456 mc->mc_flags |= C_DEL;
6459 /* otherwise fall thru and delete the sub-DB */
6462 if (leaf->mn_flags & F_SUBDATA) {
6463 /* add all the child DB's pages to the free list */
6464 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6470 /* add overflow pages to free list */
6471 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6475 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
6476 if ((rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL)) ||
6477 (rc = mdb_ovpage_free(mc, omp)))
6482 return mdb_cursor_del0(mc);
6485 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6489 /** Allocate and initialize new pages for a database.
6490 * @param[in] mc a cursor on the database being added to.
6491 * @param[in] flags flags defining what type of page is being allocated.
6492 * @param[in] num the number of pages to allocate. This is usually 1,
6493 * unless allocating overflow pages for a large record.
6494 * @param[out] mp Address of a page, or NULL on failure.
6495 * @return 0 on success, non-zero on failure.
6498 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
6503 if ((rc = mdb_page_alloc(mc, num, &np)))
6505 DPRINTF(("allocated new mpage %"Z"u, page size %u",
6506 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
6507 np->mp_flags = flags | P_DIRTY;
6508 np->mp_lower = (PAGEHDRSZ-PAGEBASE);
6509 np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
6512 mc->mc_db->md_branch_pages++;
6513 else if (IS_LEAF(np))
6514 mc->mc_db->md_leaf_pages++;
6515 else if (IS_OVERFLOW(np)) {
6516 mc->mc_db->md_overflow_pages += num;
6524 /** Calculate the size of a leaf node.
6525 * The size depends on the environment's page size; if a data item
6526 * is too large it will be put onto an overflow page and the node
6527 * size will only include the key and not the data. Sizes are always
6528 * rounded up to an even number of bytes, to guarantee 2-byte alignment
6529 * of the #MDB_node headers.
6530 * @param[in] env The environment handle.
6531 * @param[in] key The key for the node.
6532 * @param[in] data The data for the node.
6533 * @return The number of bytes needed to store the node.
6536 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
6540 sz = LEAFSIZE(key, data);
6541 if (sz > env->me_nodemax) {
6542 /* put on overflow page */
6543 sz -= data->mv_size - sizeof(pgno_t);
6546 return EVEN(sz + sizeof(indx_t));
6549 /** Calculate the size of a branch node.
6550 * The size should depend on the environment's page size but since
6551 * we currently don't support spilling large keys onto overflow
6552 * pages, it's simply the size of the #MDB_node header plus the
6553 * size of the key. Sizes are always rounded up to an even number
6554 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
6555 * @param[in] env The environment handle.
6556 * @param[in] key The key for the node.
6557 * @return The number of bytes needed to store the node.
6560 mdb_branch_size(MDB_env *env, MDB_val *key)
6565 if (sz > env->me_nodemax) {
6566 /* put on overflow page */
6567 /* not implemented */
6568 /* sz -= key->size - sizeof(pgno_t); */
6571 return sz + sizeof(indx_t);
6574 /** Add a node to the page pointed to by the cursor.
6575 * @param[in] mc The cursor for this operation.
6576 * @param[in] indx The index on the page where the new node should be added.
6577 * @param[in] key The key for the new node.
6578 * @param[in] data The data for the new node, if any.
6579 * @param[in] pgno The page number, if adding a branch node.
6580 * @param[in] flags Flags for the node.
6581 * @return 0 on success, non-zero on failure. Possible errors are:
6583 * <li>ENOMEM - failed to allocate overflow pages for the node.
6584 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
6585 * should never happen since all callers already calculate the
6586 * page's free space before calling this function.
6590 mdb_node_add(MDB_cursor *mc, indx_t indx,
6591 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
6594 size_t node_size = NODESIZE;
6598 MDB_page *mp = mc->mc_pg[mc->mc_top];
6599 MDB_page *ofp = NULL; /* overflow page */
6602 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
6604 DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
6605 IS_LEAF(mp) ? "leaf" : "branch",
6606 IS_SUBP(mp) ? "sub-" : "",
6607 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
6608 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
6611 /* Move higher keys up one slot. */
6612 int ksize = mc->mc_db->md_pad, dif;
6613 char *ptr = LEAF2KEY(mp, indx, ksize);
6614 dif = NUMKEYS(mp) - indx;
6616 memmove(ptr+ksize, ptr, dif*ksize);
6617 /* insert new key */
6618 memcpy(ptr, key->mv_data, ksize);
6620 /* Just using these for counting */
6621 mp->mp_lower += sizeof(indx_t);
6622 mp->mp_upper -= ksize - sizeof(indx_t);
6626 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
6628 node_size += key->mv_size;
6630 mdb_cassert(mc, data);
6631 if (F_ISSET(flags, F_BIGDATA)) {
6632 /* Data already on overflow page. */
6633 node_size += sizeof(pgno_t);
6634 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
6635 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
6637 /* Put data on overflow page. */
6638 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
6639 data->mv_size, node_size+data->mv_size));
6640 node_size = EVEN(node_size + sizeof(pgno_t));
6641 if ((ssize_t)node_size > room)
6643 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
6645 DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
6649 node_size += data->mv_size;
6652 node_size = EVEN(node_size);
6653 if ((ssize_t)node_size > room)
6657 /* Move higher pointers up one slot. */
6658 for (i = NUMKEYS(mp); i > indx; i--)
6659 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
6661 /* Adjust free space offsets. */
6662 ofs = mp->mp_upper - node_size;
6663 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
6664 mp->mp_ptrs[indx] = ofs;
6666 mp->mp_lower += sizeof(indx_t);
6668 /* Write the node data. */
6669 node = NODEPTR(mp, indx);
6670 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
6671 node->mn_flags = flags;
6673 SETDSZ(node,data->mv_size);
6678 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6681 mdb_cassert(mc, key);
6683 if (F_ISSET(flags, F_BIGDATA))
6684 memcpy(node->mn_data + key->mv_size, data->mv_data,
6686 else if (F_ISSET(flags, MDB_RESERVE))
6687 data->mv_data = node->mn_data + key->mv_size;
6689 memcpy(node->mn_data + key->mv_size, data->mv_data,
6692 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
6694 if (F_ISSET(flags, MDB_RESERVE))
6695 data->mv_data = METADATA(ofp);
6697 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
6704 DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
6705 mdb_dbg_pgno(mp), NUMKEYS(mp)));
6706 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
6707 DPRINTF(("node size = %"Z"u", node_size));
6708 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6709 return MDB_PAGE_FULL;
6712 /** Delete the specified node from a page.
6713 * @param[in] mc Cursor pointing to the node to delete.
6714 * @param[in] ksize The size of a node. Only used if the page is
6715 * part of a #MDB_DUPFIXED database.
6718 mdb_node_del(MDB_cursor *mc, int ksize)
6720 MDB_page *mp = mc->mc_pg[mc->mc_top];
6721 indx_t indx = mc->mc_ki[mc->mc_top];
6723 indx_t i, j, numkeys, ptr;
6727 DPRINTF(("delete node %u on %s page %"Z"u", indx,
6728 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
6729 numkeys = NUMKEYS(mp);
6730 mdb_cassert(mc, indx < numkeys);
6733 int x = numkeys - 1 - indx;
6734 base = LEAF2KEY(mp, indx, ksize);
6736 memmove(base, base + ksize, x * ksize);
6737 mp->mp_lower -= sizeof(indx_t);
6738 mp->mp_upper += ksize - sizeof(indx_t);
6742 node = NODEPTR(mp, indx);
6743 sz = NODESIZE + node->mn_ksize;
6745 if (F_ISSET(node->mn_flags, F_BIGDATA))
6746 sz += sizeof(pgno_t);
6748 sz += NODEDSZ(node);
6752 ptr = mp->mp_ptrs[indx];
6753 for (i = j = 0; i < numkeys; i++) {
6755 mp->mp_ptrs[j] = mp->mp_ptrs[i];
6756 if (mp->mp_ptrs[i] < ptr)
6757 mp->mp_ptrs[j] += sz;
6762 base = (char *)mp + mp->mp_upper + PAGEBASE;
6763 memmove(base + sz, base, ptr - mp->mp_upper);
6765 mp->mp_lower -= sizeof(indx_t);
6769 /** Compact the main page after deleting a node on a subpage.
6770 * @param[in] mp The main page to operate on.
6771 * @param[in] indx The index of the subpage on the main page.
6774 mdb_node_shrink(MDB_page *mp, indx_t indx)
6780 indx_t i, numkeys, ptr;
6782 node = NODEPTR(mp, indx);
6783 sp = (MDB_page *)NODEDATA(node);
6784 delta = SIZELEFT(sp);
6785 xp = (MDB_page *)((char *)sp + delta);
6787 /* shift subpage upward */
6789 nsize = NUMKEYS(sp) * sp->mp_pad;
6791 return; /* do not make the node uneven-sized */
6792 memmove(METADATA(xp), METADATA(sp), nsize);
6795 numkeys = NUMKEYS(sp);
6796 for (i=numkeys-1; i>=0; i--)
6797 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
6799 xp->mp_upper = sp->mp_lower;
6800 xp->mp_lower = sp->mp_lower;
6801 xp->mp_flags = sp->mp_flags;
6802 xp->mp_pad = sp->mp_pad;
6803 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
6805 nsize = NODEDSZ(node) - delta;
6806 SETDSZ(node, nsize);
6808 /* shift lower nodes upward */
6809 ptr = mp->mp_ptrs[indx];
6810 numkeys = NUMKEYS(mp);
6811 for (i = 0; i < numkeys; i++) {
6812 if (mp->mp_ptrs[i] <= ptr)
6813 mp->mp_ptrs[i] += delta;
6816 base = (char *)mp + mp->mp_upper + PAGEBASE;
6817 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
6818 mp->mp_upper += delta;
6821 /** Initial setup of a sorted-dups cursor.
6822 * Sorted duplicates are implemented as a sub-database for the given key.
6823 * The duplicate data items are actually keys of the sub-database.
6824 * Operations on the duplicate data items are performed using a sub-cursor
6825 * initialized when the sub-database is first accessed. This function does
6826 * the preliminary setup of the sub-cursor, filling in the fields that
6827 * depend only on the parent DB.
6828 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6831 mdb_xcursor_init0(MDB_cursor *mc)
6833 MDB_xcursor *mx = mc->mc_xcursor;
6835 mx->mx_cursor.mc_xcursor = NULL;
6836 mx->mx_cursor.mc_txn = mc->mc_txn;
6837 mx->mx_cursor.mc_db = &mx->mx_db;
6838 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
6839 mx->mx_cursor.mc_dbi = mc->mc_dbi;
6840 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
6841 mx->mx_cursor.mc_snum = 0;
6842 mx->mx_cursor.mc_top = 0;
6843 mx->mx_cursor.mc_flags = C_SUB;
6844 mx->mx_dbx.md_name.mv_size = 0;
6845 mx->mx_dbx.md_name.mv_data = NULL;
6846 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
6847 mx->mx_dbx.md_dcmp = NULL;
6848 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
6851 /** Final setup of a sorted-dups cursor.
6852 * Sets up the fields that depend on the data from the main cursor.
6853 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6854 * @param[in] node The data containing the #MDB_db record for the
6855 * sorted-dup database.
6858 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
6860 MDB_xcursor *mx = mc->mc_xcursor;
6862 if (node->mn_flags & F_SUBDATA) {
6863 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
6864 mx->mx_cursor.mc_pg[0] = 0;
6865 mx->mx_cursor.mc_snum = 0;
6866 mx->mx_cursor.mc_top = 0;
6867 mx->mx_cursor.mc_flags = C_SUB;
6869 MDB_page *fp = NODEDATA(node);
6870 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
6871 mx->mx_db.md_flags = 0;
6872 mx->mx_db.md_depth = 1;
6873 mx->mx_db.md_branch_pages = 0;
6874 mx->mx_db.md_leaf_pages = 1;
6875 mx->mx_db.md_overflow_pages = 0;
6876 mx->mx_db.md_entries = NUMKEYS(fp);
6877 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
6878 mx->mx_cursor.mc_snum = 1;
6879 mx->mx_cursor.mc_top = 0;
6880 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
6881 mx->mx_cursor.mc_pg[0] = fp;
6882 mx->mx_cursor.mc_ki[0] = 0;
6883 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6884 mx->mx_db.md_flags = MDB_DUPFIXED;
6885 mx->mx_db.md_pad = fp->mp_pad;
6886 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6887 mx->mx_db.md_flags |= MDB_INTEGERKEY;
6890 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
6891 mx->mx_db.md_root));
6892 mx->mx_dbflag = DB_VALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
6893 #if UINT_MAX < SIZE_MAX
6894 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
6895 mx->mx_dbx.md_cmp = mdb_cmp_clong;
6899 /** Initialize a cursor for a given transaction and database. */
6901 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
6904 mc->mc_backup = NULL;
6907 mc->mc_db = &txn->mt_dbs[dbi];
6908 mc->mc_dbx = &txn->mt_dbxs[dbi];
6909 mc->mc_dbflag = &txn->mt_dbflags[dbi];
6914 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
6915 mdb_tassert(txn, mx != NULL);
6916 mc->mc_xcursor = mx;
6917 mdb_xcursor_init0(mc);
6919 mc->mc_xcursor = NULL;
6921 if (*mc->mc_dbflag & DB_STALE) {
6922 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
6927 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
6930 size_t size = sizeof(MDB_cursor);
6932 if (!ret || !TXN_DBI_EXIST(txn, dbi))
6935 if (txn->mt_flags & MDB_TXN_ERROR)
6938 /* Allow read access to the freelist */
6939 if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
6942 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
6943 size += sizeof(MDB_xcursor);
6945 if ((mc = malloc(size)) != NULL) {
6946 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
6947 if (txn->mt_cursors) {
6948 mc->mc_next = txn->mt_cursors[dbi];
6949 txn->mt_cursors[dbi] = mc;
6950 mc->mc_flags |= C_UNTRACK;
6962 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
6964 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi))
6967 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
6970 if (txn->mt_flags & MDB_TXN_ERROR)
6973 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
6977 /* Return the count of duplicate data items for the current key */
6979 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
6983 if (mc == NULL || countp == NULL)
6986 if (mc->mc_xcursor == NULL)
6987 return MDB_INCOMPATIBLE;
6989 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
6992 if (!(mc->mc_flags & C_INITIALIZED))
6995 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6996 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6999 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
7002 *countp = mc->mc_xcursor->mx_db.md_entries;
7008 mdb_cursor_close(MDB_cursor *mc)
7010 if (mc && !mc->mc_backup) {
7011 /* remove from txn, if tracked */
7012 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
7013 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
7014 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
7016 *prev = mc->mc_next;
7023 mdb_cursor_txn(MDB_cursor *mc)
7025 if (!mc) return NULL;
7030 mdb_cursor_dbi(MDB_cursor *mc)
7035 /** Replace the key for a branch node with a new key.
7036 * @param[in] mc Cursor pointing to the node to operate on.
7037 * @param[in] key The new key to use.
7038 * @return 0 on success, non-zero on failure.
7041 mdb_update_key(MDB_cursor *mc, MDB_val *key)
7047 int delta, ksize, oksize;
7048 indx_t ptr, i, numkeys, indx;
7051 indx = mc->mc_ki[mc->mc_top];
7052 mp = mc->mc_pg[mc->mc_top];
7053 node = NODEPTR(mp, indx);
7054 ptr = mp->mp_ptrs[indx];
7058 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
7059 k2.mv_data = NODEKEY(node);
7060 k2.mv_size = node->mn_ksize;
7061 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
7063 mdb_dkey(&k2, kbuf2),
7069 /* Sizes must be 2-byte aligned. */
7070 ksize = EVEN(key->mv_size);
7071 oksize = EVEN(node->mn_ksize);
7072 delta = ksize - oksize;
7074 /* Shift node contents if EVEN(key length) changed. */
7076 if (delta > 0 && SIZELEFT(mp) < delta) {
7078 /* not enough space left, do a delete and split */
7079 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
7080 pgno = NODEPGNO(node);
7081 mdb_node_del(mc, 0);
7082 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
7085 numkeys = NUMKEYS(mp);
7086 for (i = 0; i < numkeys; i++) {
7087 if (mp->mp_ptrs[i] <= ptr)
7088 mp->mp_ptrs[i] -= delta;
7091 base = (char *)mp + mp->mp_upper + PAGEBASE;
7092 len = ptr - mp->mp_upper + NODESIZE;
7093 memmove(base - delta, base, len);
7094 mp->mp_upper -= delta;
7096 node = NODEPTR(mp, indx);
7099 /* But even if no shift was needed, update ksize */
7100 if (node->mn_ksize != key->mv_size)
7101 node->mn_ksize = key->mv_size;
7104 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7110 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
7112 /** Move a node from csrc to cdst.
7115 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
7122 unsigned short flags;
7126 /* Mark src and dst as dirty. */
7127 if ((rc = mdb_page_touch(csrc)) ||
7128 (rc = mdb_page_touch(cdst)))
7131 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7132 key.mv_size = csrc->mc_db->md_pad;
7133 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
7135 data.mv_data = NULL;
7139 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
7140 mdb_cassert(csrc, !((size_t)srcnode & 1));
7141 srcpg = NODEPGNO(srcnode);
7142 flags = srcnode->mn_flags;
7143 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7144 unsigned int snum = csrc->mc_snum;
7146 /* must find the lowest key below src */
7147 rc = mdb_page_search_lowest(csrc);
7150 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7151 key.mv_size = csrc->mc_db->md_pad;
7152 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7154 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7155 key.mv_size = NODEKSZ(s2);
7156 key.mv_data = NODEKEY(s2);
7158 csrc->mc_snum = snum--;
7159 csrc->mc_top = snum;
7161 key.mv_size = NODEKSZ(srcnode);
7162 key.mv_data = NODEKEY(srcnode);
7164 data.mv_size = NODEDSZ(srcnode);
7165 data.mv_data = NODEDATA(srcnode);
7167 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
7168 unsigned int snum = cdst->mc_snum;
7171 /* must find the lowest key below dst */
7172 mdb_cursor_copy(cdst, &mn);
7173 rc = mdb_page_search_lowest(&mn);
7176 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7177 bkey.mv_size = mn.mc_db->md_pad;
7178 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
7180 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7181 bkey.mv_size = NODEKSZ(s2);
7182 bkey.mv_data = NODEKEY(s2);
7184 mn.mc_snum = snum--;
7187 rc = mdb_update_key(&mn, &bkey);
7192 DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
7193 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
7194 csrc->mc_ki[csrc->mc_top],
7196 csrc->mc_pg[csrc->mc_top]->mp_pgno,
7197 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
7199 /* Add the node to the destination page.
7201 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
7202 if (rc != MDB_SUCCESS)
7205 /* Delete the node from the source page.
7207 mdb_node_del(csrc, key.mv_size);
7210 /* Adjust other cursors pointing to mp */
7211 MDB_cursor *m2, *m3;
7212 MDB_dbi dbi = csrc->mc_dbi;
7213 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
7215 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7216 if (csrc->mc_flags & C_SUB)
7217 m3 = &m2->mc_xcursor->mx_cursor;
7220 if (m3 == csrc) continue;
7221 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
7222 csrc->mc_ki[csrc->mc_top]) {
7223 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
7224 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7229 /* Update the parent separators.
7231 if (csrc->mc_ki[csrc->mc_top] == 0) {
7232 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
7233 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7234 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7236 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7237 key.mv_size = NODEKSZ(srcnode);
7238 key.mv_data = NODEKEY(srcnode);
7240 DPRINTF(("update separator for source page %"Z"u to [%s]",
7241 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
7242 mdb_cursor_copy(csrc, &mn);
7245 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7248 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7250 indx_t ix = csrc->mc_ki[csrc->mc_top];
7251 nullkey.mv_size = 0;
7252 csrc->mc_ki[csrc->mc_top] = 0;
7253 rc = mdb_update_key(csrc, &nullkey);
7254 csrc->mc_ki[csrc->mc_top] = ix;
7255 mdb_cassert(csrc, rc == MDB_SUCCESS);
7259 if (cdst->mc_ki[cdst->mc_top] == 0) {
7260 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
7261 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7262 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
7264 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
7265 key.mv_size = NODEKSZ(srcnode);
7266 key.mv_data = NODEKEY(srcnode);
7268 DPRINTF(("update separator for destination page %"Z"u to [%s]",
7269 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
7270 mdb_cursor_copy(cdst, &mn);
7273 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7276 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
7278 indx_t ix = cdst->mc_ki[cdst->mc_top];
7279 nullkey.mv_size = 0;
7280 cdst->mc_ki[cdst->mc_top] = 0;
7281 rc = mdb_update_key(cdst, &nullkey);
7282 cdst->mc_ki[cdst->mc_top] = ix;
7283 mdb_cassert(csrc, rc == MDB_SUCCESS);
7290 /** Merge one page into another.
7291 * The nodes from the page pointed to by \b csrc will
7292 * be copied to the page pointed to by \b cdst and then
7293 * the \b csrc page will be freed.
7294 * @param[in] csrc Cursor pointing to the source page.
7295 * @param[in] cdst Cursor pointing to the destination page.
7296 * @return 0 on success, non-zero on failure.
7299 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
7301 MDB_page *psrc, *pdst;
7308 psrc = csrc->mc_pg[csrc->mc_top];
7309 pdst = cdst->mc_pg[cdst->mc_top];
7311 DPRINTF(("merging page %"Z"u into %"Z"u", psrc->mp_pgno, pdst->mp_pgno));
7313 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
7314 mdb_cassert(csrc, cdst->mc_snum > 1);
7316 /* Mark dst as dirty. */
7317 if ((rc = mdb_page_touch(cdst)))
7320 /* Move all nodes from src to dst.
7322 j = nkeys = NUMKEYS(pdst);
7323 if (IS_LEAF2(psrc)) {
7324 key.mv_size = csrc->mc_db->md_pad;
7325 key.mv_data = METADATA(psrc);
7326 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7327 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
7328 if (rc != MDB_SUCCESS)
7330 key.mv_data = (char *)key.mv_data + key.mv_size;
7333 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7334 srcnode = NODEPTR(psrc, i);
7335 if (i == 0 && IS_BRANCH(psrc)) {
7338 mdb_cursor_copy(csrc, &mn);
7339 /* must find the lowest key below src */
7340 rc = mdb_page_search_lowest(&mn);
7343 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7344 key.mv_size = mn.mc_db->md_pad;
7345 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
7347 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7348 key.mv_size = NODEKSZ(s2);
7349 key.mv_data = NODEKEY(s2);
7352 key.mv_size = srcnode->mn_ksize;
7353 key.mv_data = NODEKEY(srcnode);
7356 data.mv_size = NODEDSZ(srcnode);
7357 data.mv_data = NODEDATA(srcnode);
7358 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
7359 if (rc != MDB_SUCCESS)
7364 DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
7365 pdst->mp_pgno, NUMKEYS(pdst),
7366 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
7368 /* Unlink the src page from parent and add to free list.
7371 mdb_node_del(csrc, 0);
7372 if (csrc->mc_ki[csrc->mc_top] == 0) {
7374 rc = mdb_update_key(csrc, &key);
7382 psrc = csrc->mc_pg[csrc->mc_top];
7383 /* If not operating on FreeDB, allow this page to be reused
7384 * in this txn. Otherwise just add to free list.
7386 rc = mdb_page_loose(csrc, psrc);
7390 csrc->mc_db->md_leaf_pages--;
7392 csrc->mc_db->md_branch_pages--;
7394 /* Adjust other cursors pointing to mp */
7395 MDB_cursor *m2, *m3;
7396 MDB_dbi dbi = csrc->mc_dbi;
7398 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7399 if (csrc->mc_flags & C_SUB)
7400 m3 = &m2->mc_xcursor->mx_cursor;
7403 if (m3 == csrc) continue;
7404 if (m3->mc_snum < csrc->mc_snum) continue;
7405 if (m3->mc_pg[csrc->mc_top] == psrc) {
7406 m3->mc_pg[csrc->mc_top] = pdst;
7407 m3->mc_ki[csrc->mc_top] += nkeys;
7412 unsigned int snum = cdst->mc_snum;
7413 uint16_t depth = cdst->mc_db->md_depth;
7414 mdb_cursor_pop(cdst);
7415 rc = mdb_rebalance(cdst);
7416 /* Did the tree shrink? */
7417 if (depth > cdst->mc_db->md_depth)
7419 cdst->mc_snum = snum;
7420 cdst->mc_top = snum-1;
7425 /** Copy the contents of a cursor.
7426 * @param[in] csrc The cursor to copy from.
7427 * @param[out] cdst The cursor to copy to.
7430 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
7434 cdst->mc_txn = csrc->mc_txn;
7435 cdst->mc_dbi = csrc->mc_dbi;
7436 cdst->mc_db = csrc->mc_db;
7437 cdst->mc_dbx = csrc->mc_dbx;
7438 cdst->mc_snum = csrc->mc_snum;
7439 cdst->mc_top = csrc->mc_top;
7440 cdst->mc_flags = csrc->mc_flags;
7442 for (i=0; i<csrc->mc_snum; i++) {
7443 cdst->mc_pg[i] = csrc->mc_pg[i];
7444 cdst->mc_ki[i] = csrc->mc_ki[i];
7448 /** Rebalance the tree after a delete operation.
7449 * @param[in] mc Cursor pointing to the page where rebalancing
7451 * @return 0 on success, non-zero on failure.
7454 mdb_rebalance(MDB_cursor *mc)
7458 unsigned int ptop, minkeys;
7462 minkeys = 1 + (IS_BRANCH(mc->mc_pg[mc->mc_top]));
7463 DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
7464 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
7465 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
7466 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
7468 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD &&
7469 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
7470 DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
7471 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
7475 if (mc->mc_snum < 2) {
7476 MDB_page *mp = mc->mc_pg[0];
7478 DPUTS("Can't rebalance a subpage, ignoring");
7481 if (NUMKEYS(mp) == 0) {
7482 DPUTS("tree is completely empty");
7483 mc->mc_db->md_root = P_INVALID;
7484 mc->mc_db->md_depth = 0;
7485 mc->mc_db->md_leaf_pages = 0;
7486 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7489 /* Adjust cursors pointing to mp */
7492 mc->mc_flags &= ~C_INITIALIZED;
7494 MDB_cursor *m2, *m3;
7495 MDB_dbi dbi = mc->mc_dbi;
7497 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7498 if (mc->mc_flags & C_SUB)
7499 m3 = &m2->mc_xcursor->mx_cursor;
7502 if (m3->mc_snum < mc->mc_snum) continue;
7503 if (m3->mc_pg[0] == mp) {
7506 m3->mc_flags &= ~C_INITIALIZED;
7510 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
7512 DPUTS("collapsing root page!");
7513 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7516 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
7517 rc = mdb_page_get(mc->mc_txn,mc->mc_db->md_root,&mc->mc_pg[0],NULL);
7520 mc->mc_db->md_depth--;
7521 mc->mc_db->md_branch_pages--;
7522 mc->mc_ki[0] = mc->mc_ki[1];
7523 for (i = 1; i<mc->mc_db->md_depth; i++) {
7524 mc->mc_pg[i] = mc->mc_pg[i+1];
7525 mc->mc_ki[i] = mc->mc_ki[i+1];
7528 /* Adjust other cursors pointing to mp */
7529 MDB_cursor *m2, *m3;
7530 MDB_dbi dbi = mc->mc_dbi;
7532 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7533 if (mc->mc_flags & C_SUB)
7534 m3 = &m2->mc_xcursor->mx_cursor;
7537 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
7538 if (m3->mc_pg[0] == mp) {
7541 for (i=0; i<m3->mc_snum; i++) {
7542 m3->mc_pg[i] = m3->mc_pg[i+1];
7543 m3->mc_ki[i] = m3->mc_ki[i+1];
7549 DPUTS("root page doesn't need rebalancing");
7553 /* The parent (branch page) must have at least 2 pointers,
7554 * otherwise the tree is invalid.
7556 ptop = mc->mc_top-1;
7557 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
7559 /* Leaf page fill factor is below the threshold.
7560 * Try to move keys from left or right neighbor, or
7561 * merge with a neighbor page.
7566 mdb_cursor_copy(mc, &mn);
7567 mn.mc_xcursor = NULL;
7569 oldki = mc->mc_ki[mc->mc_top];
7570 if (mc->mc_ki[ptop] == 0) {
7571 /* We're the leftmost leaf in our parent.
7573 DPUTS("reading right neighbor");
7575 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7576 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7579 mn.mc_ki[mn.mc_top] = 0;
7580 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
7582 /* There is at least one neighbor to the left.
7584 DPUTS("reading left neighbor");
7586 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7587 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7590 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
7591 mc->mc_ki[mc->mc_top] = 0;
7594 DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
7595 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
7596 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
7598 /* If the neighbor page is above threshold and has enough keys,
7599 * move one key from it. Otherwise we should try to merge them.
7600 * (A branch page must never have less than 2 keys.)
7602 minkeys = 1 + (IS_BRANCH(mn.mc_pg[mn.mc_top]));
7603 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
7604 rc = mdb_node_move(&mn, mc);
7605 if (mc->mc_ki[ptop]) {
7609 if (mc->mc_ki[ptop] == 0) {
7610 rc = mdb_page_merge(&mn, mc);
7612 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
7613 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
7614 rc = mdb_page_merge(mc, &mn);
7615 mdb_cursor_copy(&mn, mc);
7617 mc->mc_flags &= ~C_EOF;
7619 mc->mc_ki[mc->mc_top] = oldki;
7623 /** Complete a delete operation started by #mdb_cursor_del(). */
7625 mdb_cursor_del0(MDB_cursor *mc)
7632 ki = mc->mc_ki[mc->mc_top];
7633 mdb_node_del(mc, mc->mc_db->md_pad);
7634 mc->mc_db->md_entries--;
7635 rc = mdb_rebalance(mc);
7637 if (rc == MDB_SUCCESS) {
7638 MDB_cursor *m2, *m3;
7639 MDB_dbi dbi = mc->mc_dbi;
7641 mp = mc->mc_pg[mc->mc_top];
7642 nkeys = NUMKEYS(mp);
7644 /* if mc points past last node in page, find next sibling */
7645 if (mc->mc_ki[mc->mc_top] >= nkeys) {
7646 rc = mdb_cursor_sibling(mc, 1);
7647 if (rc == MDB_NOTFOUND) {
7648 mc->mc_flags |= C_EOF;
7653 /* Adjust other cursors pointing to mp */
7654 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
7655 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
7656 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
7658 if (m3 == mc || m3->mc_snum < mc->mc_snum)
7660 if (m3->mc_pg[mc->mc_top] == mp) {
7661 if (m3->mc_ki[mc->mc_top] >= ki) {
7662 m3->mc_flags |= C_DEL;
7663 if (m3->mc_ki[mc->mc_top] > ki)
7664 m3->mc_ki[mc->mc_top]--;
7665 else if (mc->mc_db->md_flags & MDB_DUPSORT)
7666 m3->mc_xcursor->mx_cursor.mc_flags |= C_EOF;
7668 if (m3->mc_ki[mc->mc_top] >= nkeys) {
7669 rc = mdb_cursor_sibling(m3, 1);
7670 if (rc == MDB_NOTFOUND) {
7671 m3->mc_flags |= C_EOF;
7677 mc->mc_flags |= C_DEL;
7681 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7686 mdb_del(MDB_txn *txn, MDB_dbi dbi,
7687 MDB_val *key, MDB_val *data)
7689 if (!key || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
7692 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
7693 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7695 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
7696 /* must ignore any data */
7700 return mdb_del0(txn, dbi, key, data, 0);
7704 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
7705 MDB_val *key, MDB_val *data, unsigned flags)
7710 MDB_val rdata, *xdata;
7714 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
7716 mdb_cursor_init(&mc, txn, dbi, &mx);
7725 flags |= MDB_NODUPDATA;
7727 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
7729 /* let mdb_page_split know about this cursor if needed:
7730 * delete will trigger a rebalance; if it needs to move
7731 * a node from one page to another, it will have to
7732 * update the parent's separator key(s). If the new sepkey
7733 * is larger than the current one, the parent page may
7734 * run out of space, triggering a split. We need this
7735 * cursor to be consistent until the end of the rebalance.
7737 mc.mc_flags |= C_UNTRACK;
7738 mc.mc_next = txn->mt_cursors[dbi];
7739 txn->mt_cursors[dbi] = &mc;
7740 rc = mdb_cursor_del(&mc, flags);
7741 txn->mt_cursors[dbi] = mc.mc_next;
7746 /** Split a page and insert a new node.
7747 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
7748 * The cursor will be updated to point to the actual page and index where
7749 * the node got inserted after the split.
7750 * @param[in] newkey The key for the newly inserted node.
7751 * @param[in] newdata The data for the newly inserted node.
7752 * @param[in] newpgno The page number, if the new node is a branch node.
7753 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
7754 * @return 0 on success, non-zero on failure.
7757 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
7758 unsigned int nflags)
7761 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
7764 int i, j, split_indx, nkeys, pmax;
7765 MDB_env *env = mc->mc_txn->mt_env;
7767 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
7768 MDB_page *copy = NULL;
7769 MDB_page *mp, *rp, *pp;
7774 mp = mc->mc_pg[mc->mc_top];
7775 newindx = mc->mc_ki[mc->mc_top];
7776 nkeys = NUMKEYS(mp);
7778 DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i/%i",
7779 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
7780 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
7782 /* Create a right sibling. */
7783 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
7785 DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
7787 if (mc->mc_snum < 2) {
7788 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
7790 /* shift current top to make room for new parent */
7791 mc->mc_pg[1] = mc->mc_pg[0];
7792 mc->mc_ki[1] = mc->mc_ki[0];
7795 mc->mc_db->md_root = pp->mp_pgno;
7796 DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
7797 mc->mc_db->md_depth++;
7800 /* Add left (implicit) pointer. */
7801 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
7802 /* undo the pre-push */
7803 mc->mc_pg[0] = mc->mc_pg[1];
7804 mc->mc_ki[0] = mc->mc_ki[1];
7805 mc->mc_db->md_root = mp->mp_pgno;
7806 mc->mc_db->md_depth--;
7813 ptop = mc->mc_top-1;
7814 DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
7817 mc->mc_flags |= C_SPLITTING;
7818 mdb_cursor_copy(mc, &mn);
7819 mn.mc_pg[mn.mc_top] = rp;
7820 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
7822 if (nflags & MDB_APPEND) {
7823 mn.mc_ki[mn.mc_top] = 0;
7825 split_indx = newindx;
7829 split_indx = (nkeys+1) / 2;
7834 unsigned int lsize, rsize, ksize;
7835 /* Move half of the keys to the right sibling */
7836 x = mc->mc_ki[mc->mc_top] - split_indx;
7837 ksize = mc->mc_db->md_pad;
7838 split = LEAF2KEY(mp, split_indx, ksize);
7839 rsize = (nkeys - split_indx) * ksize;
7840 lsize = (nkeys - split_indx) * sizeof(indx_t);
7841 mp->mp_lower -= lsize;
7842 rp->mp_lower += lsize;
7843 mp->mp_upper += rsize - lsize;
7844 rp->mp_upper -= rsize - lsize;
7845 sepkey.mv_size = ksize;
7846 if (newindx == split_indx) {
7847 sepkey.mv_data = newkey->mv_data;
7849 sepkey.mv_data = split;
7852 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
7853 memcpy(rp->mp_ptrs, split, rsize);
7854 sepkey.mv_data = rp->mp_ptrs;
7855 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
7856 memcpy(ins, newkey->mv_data, ksize);
7857 mp->mp_lower += sizeof(indx_t);
7858 mp->mp_upper -= ksize - sizeof(indx_t);
7861 memcpy(rp->mp_ptrs, split, x * ksize);
7862 ins = LEAF2KEY(rp, x, ksize);
7863 memcpy(ins, newkey->mv_data, ksize);
7864 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
7865 rp->mp_lower += sizeof(indx_t);
7866 rp->mp_upper -= ksize - sizeof(indx_t);
7867 mc->mc_ki[mc->mc_top] = x;
7868 mc->mc_pg[mc->mc_top] = rp;
7871 int psize, nsize, k;
7872 /* Maximum free space in an empty page */
7873 pmax = env->me_psize - PAGEHDRSZ;
7875 nsize = mdb_leaf_size(env, newkey, newdata);
7877 nsize = mdb_branch_size(env, newkey);
7878 nsize = EVEN(nsize);
7880 /* grab a page to hold a temporary copy */
7881 copy = mdb_page_malloc(mc->mc_txn, 1);
7886 copy->mp_pgno = mp->mp_pgno;
7887 copy->mp_flags = mp->mp_flags;
7888 copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
7889 copy->mp_upper = env->me_psize - PAGEBASE;
7891 /* prepare to insert */
7892 for (i=0, j=0; i<nkeys; i++) {
7894 copy->mp_ptrs[j++] = 0;
7896 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
7899 /* When items are relatively large the split point needs
7900 * to be checked, because being off-by-one will make the
7901 * difference between success or failure in mdb_node_add.
7903 * It's also relevant if a page happens to be laid out
7904 * such that one half of its nodes are all "small" and
7905 * the other half of its nodes are "large." If the new
7906 * item is also "large" and falls on the half with
7907 * "large" nodes, it also may not fit.
7909 * As a final tweak, if the new item goes on the last
7910 * spot on the page (and thus, onto the new page), bias
7911 * the split so the new page is emptier than the old page.
7912 * This yields better packing during sequential inserts.
7914 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
7915 /* Find split point */
7917 if (newindx <= split_indx || newindx >= nkeys) {
7919 k = newindx >= nkeys ? nkeys : split_indx+2;
7924 for (; i!=k; i+=j) {
7929 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
7930 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
7932 if (F_ISSET(node->mn_flags, F_BIGDATA))
7933 psize += sizeof(pgno_t);
7935 psize += NODEDSZ(node);
7937 psize = EVEN(psize);
7939 if (psize > pmax || i == k-j) {
7940 split_indx = i + (j<0);
7945 if (split_indx == newindx) {
7946 sepkey.mv_size = newkey->mv_size;
7947 sepkey.mv_data = newkey->mv_data;
7949 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
7950 sepkey.mv_size = node->mn_ksize;
7951 sepkey.mv_data = NODEKEY(node);
7956 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
7958 /* Copy separator key to the parent.
7960 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
7964 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
7969 if (mn.mc_snum == mc->mc_snum) {
7970 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
7971 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
7972 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
7973 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
7978 /* Right page might now have changed parent.
7979 * Check if left page also changed parent.
7981 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7982 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7983 for (i=0; i<ptop; i++) {
7984 mc->mc_pg[i] = mn.mc_pg[i];
7985 mc->mc_ki[i] = mn.mc_ki[i];
7987 mc->mc_pg[ptop] = mn.mc_pg[ptop];
7988 if (mn.mc_ki[ptop]) {
7989 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
7991 /* find right page's left sibling */
7992 mc->mc_ki[ptop] = mn.mc_ki[ptop];
7993 mdb_cursor_sibling(mc, 0);
7998 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
8001 mc->mc_flags ^= C_SPLITTING;
8002 if (rc != MDB_SUCCESS) {
8005 if (nflags & MDB_APPEND) {
8006 mc->mc_pg[mc->mc_top] = rp;
8007 mc->mc_ki[mc->mc_top] = 0;
8008 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
8011 for (i=0; i<mc->mc_top; i++)
8012 mc->mc_ki[i] = mn.mc_ki[i];
8013 } else if (!IS_LEAF2(mp)) {
8015 mc->mc_pg[mc->mc_top] = rp;
8020 rkey.mv_data = newkey->mv_data;
8021 rkey.mv_size = newkey->mv_size;
8027 /* Update index for the new key. */
8028 mc->mc_ki[mc->mc_top] = j;
8030 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8031 rkey.mv_data = NODEKEY(node);
8032 rkey.mv_size = node->mn_ksize;
8034 xdata.mv_data = NODEDATA(node);
8035 xdata.mv_size = NODEDSZ(node);
8038 pgno = NODEPGNO(node);
8039 flags = node->mn_flags;
8042 if (!IS_LEAF(mp) && j == 0) {
8043 /* First branch index doesn't need key data. */
8047 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
8053 mc->mc_pg[mc->mc_top] = copy;
8058 } while (i != split_indx);
8060 nkeys = NUMKEYS(copy);
8061 for (i=0; i<nkeys; i++)
8062 mp->mp_ptrs[i] = copy->mp_ptrs[i];
8063 mp->mp_lower = copy->mp_lower;
8064 mp->mp_upper = copy->mp_upper;
8065 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
8066 env->me_psize - copy->mp_upper - PAGEBASE);
8068 /* reset back to original page */
8069 if (newindx < split_indx) {
8070 mc->mc_pg[mc->mc_top] = mp;
8071 if (nflags & MDB_RESERVE) {
8072 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
8073 if (!(node->mn_flags & F_BIGDATA))
8074 newdata->mv_data = NODEDATA(node);
8077 mc->mc_pg[mc->mc_top] = rp;
8079 /* Make sure mc_ki is still valid.
8081 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8082 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8083 for (i=0; i<=ptop; i++) {
8084 mc->mc_pg[i] = mn.mc_pg[i];
8085 mc->mc_ki[i] = mn.mc_ki[i];
8092 /* Adjust other cursors pointing to mp */
8093 MDB_cursor *m2, *m3;
8094 MDB_dbi dbi = mc->mc_dbi;
8095 int fixup = NUMKEYS(mp);
8097 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8098 if (mc->mc_flags & C_SUB)
8099 m3 = &m2->mc_xcursor->mx_cursor;
8104 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8106 if (m3->mc_flags & C_SPLITTING)
8111 for (k=m3->mc_top; k>=0; k--) {
8112 m3->mc_ki[k+1] = m3->mc_ki[k];
8113 m3->mc_pg[k+1] = m3->mc_pg[k];
8115 if (m3->mc_ki[0] >= split_indx) {
8120 m3->mc_pg[0] = mc->mc_pg[0];
8124 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
8125 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
8126 m3->mc_ki[mc->mc_top]++;
8127 if (m3->mc_ki[mc->mc_top] >= fixup) {
8128 m3->mc_pg[mc->mc_top] = rp;
8129 m3->mc_ki[mc->mc_top] -= fixup;
8130 m3->mc_ki[ptop] = mn.mc_ki[ptop];
8132 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
8133 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
8138 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
8141 if (copy) /* tmp page */
8142 mdb_page_free(env, copy);
8144 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8149 mdb_put(MDB_txn *txn, MDB_dbi dbi,
8150 MDB_val *key, MDB_val *data, unsigned int flags)
8155 if (!key || !data || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
8158 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP)) != flags)
8161 mdb_cursor_init(&mc, txn, dbi, &mx);
8162 return mdb_cursor_put(&mc, key, data, flags);
8166 #define MDB_WBUF (1024*1024)
8169 /** State needed for a compacting copy. */
8170 typedef struct mdb_copy {
8171 pthread_mutex_t mc_mutex;
8172 pthread_cond_t mc_cond;
8179 pgno_t mc_next_pgno;
8182 volatile int mc_new;
8187 /** Dedicated writer thread for compacting copy. */
8188 static THREAD_RET ESECT
8189 mdb_env_copythr(void *arg)
8193 int toggle = 0, wsize, rc;
8196 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8199 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8202 pthread_mutex_lock(&my->mc_mutex);
8204 pthread_cond_signal(&my->mc_cond);
8207 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8208 if (my->mc_new < 0) {
8213 wsize = my->mc_wlen[toggle];
8214 ptr = my->mc_wbuf[toggle];
8217 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
8221 } else if (len > 0) {
8235 /* If there's an overflow page tail, write it too */
8236 if (my->mc_olen[toggle]) {
8237 wsize = my->mc_olen[toggle];
8238 ptr = my->mc_over[toggle];
8239 my->mc_olen[toggle] = 0;
8242 my->mc_wlen[toggle] = 0;
8244 pthread_cond_signal(&my->mc_cond);
8246 pthread_cond_signal(&my->mc_cond);
8247 pthread_mutex_unlock(&my->mc_mutex);
8248 return (THREAD_RET)0;
8252 /** Tell the writer thread there's a buffer ready to write */
8254 mdb_env_cthr_toggle(mdb_copy *my, int st)
8256 int toggle = my->mc_toggle ^ 1;
8257 pthread_mutex_lock(&my->mc_mutex);
8258 if (my->mc_status) {
8259 pthread_mutex_unlock(&my->mc_mutex);
8260 return my->mc_status;
8262 while (my->mc_new == 1)
8263 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8265 my->mc_toggle = toggle;
8266 pthread_cond_signal(&my->mc_cond);
8267 pthread_mutex_unlock(&my->mc_mutex);
8271 /** Depth-first tree traversal for compacting copy. */
8273 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
8276 MDB_txn *txn = my->mc_txn;
8278 MDB_page *mo, *mp, *leaf;
8283 /* Empty DB, nothing to do */
8284 if (*pg == P_INVALID)
8291 rc = mdb_page_get(my->mc_txn, *pg, &mc.mc_pg[0], NULL);
8294 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
8298 /* Make cursor pages writable */
8299 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
8303 for (i=0; i<mc.mc_top; i++) {
8304 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
8305 mc.mc_pg[i] = (MDB_page *)ptr;
8306 ptr += my->mc_env->me_psize;
8309 /* This is writable space for a leaf page. Usually not needed. */
8310 leaf = (MDB_page *)ptr;
8312 toggle = my->mc_toggle;
8313 while (mc.mc_snum > 0) {
8315 mp = mc.mc_pg[mc.mc_top];
8319 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
8320 for (i=0; i<n; i++) {
8321 ni = NODEPTR(mp, i);
8322 if (ni->mn_flags & F_BIGDATA) {
8326 /* Need writable leaf */
8328 mc.mc_pg[mc.mc_top] = leaf;
8329 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8331 ni = NODEPTR(mp, i);
8334 memcpy(&pg, NODEDATA(ni), sizeof(pg));
8335 rc = mdb_page_get(txn, pg, &omp, NULL);
8338 if (my->mc_wlen[toggle] >= MDB_WBUF) {
8339 rc = mdb_env_cthr_toggle(my, 1);
8342 toggle = my->mc_toggle;
8344 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
8345 memcpy(mo, omp, my->mc_env->me_psize);
8346 mo->mp_pgno = my->mc_next_pgno;
8347 my->mc_next_pgno += omp->mp_pages;
8348 my->mc_wlen[toggle] += my->mc_env->me_psize;
8349 if (omp->mp_pages > 1) {
8350 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
8351 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
8352 rc = mdb_env_cthr_toggle(my, 1);
8355 toggle = my->mc_toggle;
8357 memcpy(NODEDATA(ni), &mo->mp_pgno, sizeof(pgno_t));
8358 } else if (ni->mn_flags & F_SUBDATA) {
8361 /* Need writable leaf */
8363 mc.mc_pg[mc.mc_top] = leaf;
8364 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8366 ni = NODEPTR(mp, i);
8369 memcpy(&db, NODEDATA(ni), sizeof(db));
8370 my->mc_toggle = toggle;
8371 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
8374 toggle = my->mc_toggle;
8375 memcpy(NODEDATA(ni), &db, sizeof(db));
8380 mc.mc_ki[mc.mc_top]++;
8381 if (mc.mc_ki[mc.mc_top] < n) {
8384 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
8386 rc = mdb_page_get(txn, pg, &mp, NULL);
8391 mc.mc_ki[mc.mc_top] = 0;
8392 if (IS_BRANCH(mp)) {
8393 /* Whenever we advance to a sibling branch page,
8394 * we must proceed all the way down to its first leaf.
8396 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
8399 mc.mc_pg[mc.mc_top] = mp;
8403 if (my->mc_wlen[toggle] >= MDB_WBUF) {
8404 rc = mdb_env_cthr_toggle(my, 1);
8407 toggle = my->mc_toggle;
8409 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
8410 mdb_page_copy(mo, mp, my->mc_env->me_psize);
8411 mo->mp_pgno = my->mc_next_pgno++;
8412 my->mc_wlen[toggle] += my->mc_env->me_psize;
8414 /* Update parent if there is one */
8415 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
8416 SETPGNO(ni, mo->mp_pgno);
8417 mdb_cursor_pop(&mc);
8419 /* Otherwise we're done */
8429 /** Copy environment with compaction. */
8431 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
8436 MDB_txn *txn = NULL;
8441 my.mc_mutex = CreateMutex(NULL, FALSE, NULL);
8442 my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL);
8443 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_psize);
8444 if (my.mc_wbuf[0] == NULL)
8447 pthread_mutex_init(&my.mc_mutex, NULL);
8448 pthread_cond_init(&my.mc_cond, NULL);
8449 rc = posix_memalign((void **)&my.mc_wbuf[0], env->me_psize, MDB_WBUF*2);
8453 memset(my.mc_wbuf[0], 0, MDB_WBUF*2);
8454 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
8459 my.mc_next_pgno = 2;
8465 THREAD_CREATE(thr, mdb_env_copythr, &my);
8467 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
8471 mp = (MDB_page *)my.mc_wbuf[0];
8472 memset(mp, 0, 2*env->me_psize);
8474 mp->mp_flags = P_META;
8475 mm = (MDB_meta *)METADATA(mp);
8476 mdb_env_init_meta0(env, mm);
8477 mm->mm_address = env->me_metas[0]->mm_address;
8479 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
8481 mp->mp_flags = P_META;
8482 *(MDB_meta *)METADATA(mp) = *mm;
8483 mm = (MDB_meta *)METADATA(mp);
8485 /* Count the number of free pages, subtract from lastpg to find
8486 * number of active pages
8489 MDB_ID freecount = 0;
8492 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
8493 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
8494 freecount += *(MDB_ID *)data.mv_data;
8495 freecount += txn->mt_dbs[0].md_branch_pages +
8496 txn->mt_dbs[0].md_leaf_pages +
8497 txn->mt_dbs[0].md_overflow_pages;
8499 /* Set metapage 1 */
8500 mm->mm_last_pg = txn->mt_next_pgno - freecount - 1;
8501 mm->mm_dbs[1] = txn->mt_dbs[1];
8502 mm->mm_dbs[1].md_root = mm->mm_last_pg;
8505 my.mc_wlen[0] = env->me_psize * 2;
8507 pthread_mutex_lock(&my.mc_mutex);
8509 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
8510 pthread_mutex_unlock(&my.mc_mutex);
8511 rc = mdb_env_cwalk(&my, &txn->mt_dbs[1].md_root, 0);
8512 if (rc == MDB_SUCCESS && my.mc_wlen[my.mc_toggle])
8513 rc = mdb_env_cthr_toggle(&my, 1);
8514 mdb_env_cthr_toggle(&my, -1);
8515 pthread_mutex_lock(&my.mc_mutex);
8517 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
8518 pthread_mutex_unlock(&my.mc_mutex);
8523 CloseHandle(my.mc_cond);
8524 CloseHandle(my.mc_mutex);
8525 _aligned_free(my.mc_wbuf[0]);
8527 pthread_cond_destroy(&my.mc_cond);
8528 pthread_mutex_destroy(&my.mc_mutex);
8529 free(my.mc_wbuf[0]);
8534 /** Copy environment as-is. */
8536 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
8538 MDB_txn *txn = NULL;
8544 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8548 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8551 /* Do the lock/unlock of the reader mutex before starting the
8552 * write txn. Otherwise other read txns could block writers.
8554 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
8559 /* We must start the actual read txn after blocking writers */
8560 mdb_txn_reset0(txn, "reset-stage1");
8562 /* Temporarily block writers until we snapshot the meta pages */
8565 rc = mdb_txn_renew0(txn);
8567 UNLOCK_MUTEX_W(env);
8572 wsize = env->me_psize * 2;
8576 DO_WRITE(rc, fd, ptr, w2, len);
8580 } else if (len > 0) {
8586 /* Non-blocking or async handles are not supported */
8592 UNLOCK_MUTEX_W(env);
8597 w2 = txn->mt_next_pgno * env->me_psize;
8600 LARGE_INTEGER fsize;
8601 GetFileSizeEx(env->me_fd, &fsize);
8602 if (w2 > fsize.QuadPart)
8603 w2 = fsize.QuadPart;
8608 fstat(env->me_fd, &st);
8609 if (w2 > (size_t)st.st_size)
8615 if (wsize > MAX_WRITE)
8619 DO_WRITE(rc, fd, ptr, w2, len);
8623 } else if (len > 0) {
8640 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
8642 if (flags & MDB_CP_COMPACT)
8643 return mdb_env_copyfd1(env, fd);
8645 return mdb_env_copyfd0(env, fd);
8649 mdb_env_copyfd(MDB_env *env, HANDLE fd)
8651 return mdb_env_copyfd2(env, fd, 0);
8655 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
8659 HANDLE newfd = INVALID_HANDLE_VALUE;
8661 if (env->me_flags & MDB_NOSUBDIR) {
8662 lpath = (char *)path;
8665 len += sizeof(DATANAME);
8666 lpath = malloc(len);
8669 sprintf(lpath, "%s" DATANAME, path);
8672 /* The destination path must exist, but the destination file must not.
8673 * We don't want the OS to cache the writes, since the source data is
8674 * already in the OS cache.
8677 newfd = CreateFile(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
8678 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
8680 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
8682 if (newfd == INVALID_HANDLE_VALUE) {
8688 /* Set O_DIRECT if the file system supports it */
8689 if ((rc = fcntl(newfd, F_GETFL)) != -1)
8690 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
8692 #ifdef F_NOCACHE /* __APPLE__ */
8693 rc = fcntl(newfd, F_NOCACHE, 1);
8700 rc = mdb_env_copyfd2(env, newfd, flags);
8703 if (!(env->me_flags & MDB_NOSUBDIR))
8705 if (newfd != INVALID_HANDLE_VALUE)
8706 if (close(newfd) < 0 && rc == MDB_SUCCESS)
8713 mdb_env_copy(MDB_env *env, const char *path)
8715 return mdb_env_copy2(env, path, 0);
8719 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
8721 if ((flag & CHANGEABLE) != flag)
8724 env->me_flags |= flag;
8726 env->me_flags &= ~flag;
8731 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
8736 *arg = env->me_flags;
8741 mdb_env_set_userctx(MDB_env *env, void *ctx)
8745 env->me_userctx = ctx;
8750 mdb_env_get_userctx(MDB_env *env)
8752 return env ? env->me_userctx : NULL;
8756 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
8761 env->me_assert_func = func;
8767 mdb_env_get_path(MDB_env *env, const char **arg)
8772 *arg = env->me_path;
8777 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
8786 /** Common code for #mdb_stat() and #mdb_env_stat().
8787 * @param[in] env the environment to operate in.
8788 * @param[in] db the #MDB_db record containing the stats to return.
8789 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
8790 * @return 0, this function always succeeds.
8793 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
8795 arg->ms_psize = env->me_psize;
8796 arg->ms_depth = db->md_depth;
8797 arg->ms_branch_pages = db->md_branch_pages;
8798 arg->ms_leaf_pages = db->md_leaf_pages;
8799 arg->ms_overflow_pages = db->md_overflow_pages;
8800 arg->ms_entries = db->md_entries;
8806 mdb_env_stat(MDB_env *env, MDB_stat *arg)
8810 if (env == NULL || arg == NULL)
8813 toggle = mdb_env_pick_meta(env);
8815 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
8819 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
8823 if (env == NULL || arg == NULL)
8826 toggle = mdb_env_pick_meta(env);
8827 arg->me_mapaddr = env->me_metas[toggle]->mm_address;
8828 arg->me_mapsize = env->me_mapsize;
8829 arg->me_maxreaders = env->me_maxreaders;
8831 /* me_numreaders may be zero if this process never used any readers. Use
8832 * the shared numreader count if it exists.
8834 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : env->me_numreaders;
8836 arg->me_last_pgno = env->me_metas[toggle]->mm_last_pg;
8837 arg->me_last_txnid = env->me_metas[toggle]->mm_txnid;
8841 /** Set the default comparison functions for a database.
8842 * Called immediately after a database is opened to set the defaults.
8843 * The user can then override them with #mdb_set_compare() or
8844 * #mdb_set_dupsort().
8845 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
8846 * @param[in] dbi A database handle returned by #mdb_dbi_open()
8849 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
8851 uint16_t f = txn->mt_dbs[dbi].md_flags;
8853 txn->mt_dbxs[dbi].md_cmp =
8854 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
8855 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
8857 txn->mt_dbxs[dbi].md_dcmp =
8858 !(f & MDB_DUPSORT) ? 0 :
8859 ((f & MDB_INTEGERDUP)
8860 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
8861 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
8864 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
8869 int rc, dbflag, exact;
8870 unsigned int unused = 0, seq;
8873 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
8874 mdb_default_cmp(txn, FREE_DBI);
8877 if ((flags & VALID_FLAGS) != flags)
8879 if (txn->mt_flags & MDB_TXN_ERROR)
8885 if (flags & PERSISTENT_FLAGS) {
8886 uint16_t f2 = flags & PERSISTENT_FLAGS;
8887 /* make sure flag changes get committed */
8888 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
8889 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
8890 txn->mt_flags |= MDB_TXN_DIRTY;
8893 mdb_default_cmp(txn, MAIN_DBI);
8897 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
8898 mdb_default_cmp(txn, MAIN_DBI);
8901 /* Is the DB already open? */
8903 for (i=2; i<txn->mt_numdbs; i++) {
8904 if (!txn->mt_dbxs[i].md_name.mv_size) {
8905 /* Remember this free slot */
8906 if (!unused) unused = i;
8909 if (len == txn->mt_dbxs[i].md_name.mv_size &&
8910 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
8916 /* If no free slot and max hit, fail */
8917 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
8918 return MDB_DBS_FULL;
8920 /* Cannot mix named databases with some mainDB flags */
8921 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
8922 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
8924 /* Find the DB info */
8925 dbflag = DB_NEW|DB_VALID;
8928 key.mv_data = (void *)name;
8929 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
8930 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
8931 if (rc == MDB_SUCCESS) {
8932 /* make sure this is actually a DB */
8933 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
8934 if (!(node->mn_flags & F_SUBDATA))
8935 return MDB_INCOMPATIBLE;
8936 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
8937 /* Create if requested */
8939 data.mv_size = sizeof(MDB_db);
8940 data.mv_data = &dummy;
8941 memset(&dummy, 0, sizeof(dummy));
8942 dummy.md_root = P_INVALID;
8943 dummy.md_flags = flags & PERSISTENT_FLAGS;
8944 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
8948 /* OK, got info, add to table */
8949 if (rc == MDB_SUCCESS) {
8950 unsigned int slot = unused ? unused : txn->mt_numdbs;
8951 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
8952 txn->mt_dbxs[slot].md_name.mv_size = len;
8953 txn->mt_dbxs[slot].md_rel = NULL;
8954 txn->mt_dbflags[slot] = dbflag;
8955 /* txn-> and env-> are the same in read txns, use
8956 * tmp variable to avoid undefined assignment
8958 seq = ++txn->mt_env->me_dbiseqs[slot];
8959 txn->mt_dbiseqs[slot] = seq;
8961 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
8963 mdb_default_cmp(txn, slot);
8972 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
8974 if (!arg || !TXN_DBI_EXIST(txn, dbi))
8977 if (txn->mt_flags & MDB_TXN_ERROR)
8980 if (txn->mt_dbflags[dbi] & DB_STALE) {
8983 /* Stale, must read the DB's root. cursor_init does it for us. */
8984 mdb_cursor_init(&mc, txn, dbi, &mx);
8986 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
8989 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
8992 if (dbi <= MAIN_DBI || dbi >= env->me_maxdbs)
8994 ptr = env->me_dbxs[dbi].md_name.mv_data;
8995 /* If there was no name, this was already closed */
8997 env->me_dbxs[dbi].md_name.mv_data = NULL;
8998 env->me_dbxs[dbi].md_name.mv_size = 0;
8999 env->me_dbflags[dbi] = 0;
9000 env->me_dbiseqs[dbi]++;
9005 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
9007 /* We could return the flags for the FREE_DBI too but what's the point? */
9008 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9010 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
9014 /** Add all the DB's pages to the free list.
9015 * @param[in] mc Cursor on the DB to free.
9016 * @param[in] subs non-Zero to check for sub-DBs in this DB.
9017 * @return 0 on success, non-zero on failure.
9020 mdb_drop0(MDB_cursor *mc, int subs)
9024 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
9025 if (rc == MDB_SUCCESS) {
9026 MDB_txn *txn = mc->mc_txn;
9031 /* LEAF2 pages have no nodes, cannot have sub-DBs */
9032 if (IS_LEAF2(mc->mc_pg[mc->mc_top]))
9035 mdb_cursor_copy(mc, &mx);
9036 while (mc->mc_snum > 0) {
9037 MDB_page *mp = mc->mc_pg[mc->mc_top];
9038 unsigned n = NUMKEYS(mp);
9040 for (i=0; i<n; i++) {
9041 ni = NODEPTR(mp, i);
9042 if (ni->mn_flags & F_BIGDATA) {
9045 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9046 rc = mdb_page_get(txn, pg, &omp, NULL);
9049 mdb_cassert(mc, IS_OVERFLOW(omp));
9050 rc = mdb_midl_append_range(&txn->mt_free_pgs,
9054 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
9055 mdb_xcursor_init1(mc, ni);
9056 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
9062 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
9064 for (i=0; i<n; i++) {
9066 ni = NODEPTR(mp, i);
9069 mdb_midl_xappend(txn->mt_free_pgs, pg);
9074 mc->mc_ki[mc->mc_top] = i;
9075 rc = mdb_cursor_sibling(mc, 1);
9077 if (rc != MDB_NOTFOUND)
9079 /* no more siblings, go back to beginning
9080 * of previous level.
9084 for (i=1; i<mc->mc_snum; i++) {
9086 mc->mc_pg[i] = mx.mc_pg[i];
9091 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
9094 txn->mt_flags |= MDB_TXN_ERROR;
9095 } else if (rc == MDB_NOTFOUND) {
9101 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
9103 MDB_cursor *mc, *m2;
9106 if ((unsigned)del > 1 || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9109 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
9112 if (dbi > MAIN_DBI && TXN_DBI_CHANGED(txn, dbi))
9115 rc = mdb_cursor_open(txn, dbi, &mc);
9119 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
9120 /* Invalidate the dropped DB's cursors */
9121 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
9122 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
9126 /* Can't delete the main DB */
9127 if (del && dbi > MAIN_DBI) {
9128 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, 0);
9130 txn->mt_dbflags[dbi] = DB_STALE;
9131 mdb_dbi_close(txn->mt_env, dbi);
9133 txn->mt_flags |= MDB_TXN_ERROR;
9136 /* reset the DB record, mark it dirty */
9137 txn->mt_dbflags[dbi] |= DB_DIRTY;
9138 txn->mt_dbs[dbi].md_depth = 0;
9139 txn->mt_dbs[dbi].md_branch_pages = 0;
9140 txn->mt_dbs[dbi].md_leaf_pages = 0;
9141 txn->mt_dbs[dbi].md_overflow_pages = 0;
9142 txn->mt_dbs[dbi].md_entries = 0;
9143 txn->mt_dbs[dbi].md_root = P_INVALID;
9145 txn->mt_flags |= MDB_TXN_DIRTY;
9148 mdb_cursor_close(mc);
9152 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9154 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9157 txn->mt_dbxs[dbi].md_cmp = cmp;
9161 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9163 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9166 txn->mt_dbxs[dbi].md_dcmp = cmp;
9170 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
9172 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9175 txn->mt_dbxs[dbi].md_rel = rel;
9179 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
9181 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9184 txn->mt_dbxs[dbi].md_relctx = ctx;
9189 mdb_env_get_maxkeysize(MDB_env *env)
9191 return ENV_MAXKEY(env);
9195 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
9197 unsigned int i, rdrs;
9200 int rc = 0, first = 1;
9204 if (!env->me_txns) {
9205 return func("(no reader locks)\n", ctx);
9207 rdrs = env->me_txns->mti_numreaders;
9208 mr = env->me_txns->mti_readers;
9209 for (i=0; i<rdrs; i++) {
9211 txnid_t txnid = mr[i].mr_txnid;
9212 sprintf(buf, txnid == (txnid_t)-1 ?
9213 "%10d %"Z"x -\n" : "%10d %"Z"x %"Z"u\n",
9214 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
9217 rc = func(" pid thread txnid\n", ctx);
9221 rc = func(buf, ctx);
9227 rc = func("(no active readers)\n", ctx);
9232 /** Insert pid into list if not already present.
9233 * return -1 if already present.
9236 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
9238 /* binary search of pid in list */
9240 unsigned cursor = 1;
9242 unsigned n = ids[0];
9245 unsigned pivot = n >> 1;
9246 cursor = base + pivot + 1;
9247 val = pid - ids[cursor];
9252 } else if ( val > 0 ) {
9257 /* found, so it's a duplicate */
9266 for (n = ids[0]; n > cursor; n--)
9273 mdb_reader_check(MDB_env *env, int *dead)
9275 unsigned int i, j, rdrs;
9277 MDB_PID_T *pids, pid;
9286 rdrs = env->me_txns->mti_numreaders;
9287 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
9291 mr = env->me_txns->mti_readers;
9292 for (i=0; i<rdrs; i++) {
9293 if (mr[i].mr_pid && mr[i].mr_pid != env->me_pid) {
9295 if (mdb_pid_insert(pids, pid) == 0) {
9296 if (!mdb_reader_pid(env, Pidcheck, pid)) {
9298 /* Recheck, a new process may have reused pid */
9299 if (!mdb_reader_pid(env, Pidcheck, pid)) {
9300 for (j=i; j<rdrs; j++)
9301 if (mr[j].mr_pid == pid) {
9302 DPRINTF(("clear stale reader pid %u txn %"Z"d",
9303 (unsigned) pid, mr[j].mr_txnid));
9308 UNLOCK_MUTEX_R(env);