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-2015 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
73 #if defined(__mips) && defined(__linux)
74 /* MIPS has cache coherency issues, requires explicit cache control */
75 #include <asm/cachectl.h>
76 extern int cacheflush(char *addr, int nbytes, int cache);
77 #define CACHEFLUSH(addr, bytes, cache) cacheflush(addr, bytes, cache)
79 #define CACHEFLUSH(addr, bytes, cache)
82 #if defined(__linux) && !defined(MDB_FDATASYNC_WORKS)
83 /** fdatasync is broken on ext3/ext4fs on older kernels, see
84 * description in #mdb_env_open2 comments. You can safely
85 * define MDB_FDATASYNC_WORKS if this code will only be run
86 * on kernels 3.6 and newer.
88 #define BROKEN_FDATASYNC
101 #if defined(__sun) || defined(ANDROID)
102 /* Most platforms have posix_memalign, older may only have memalign */
103 #define HAVE_MEMALIGN 1
107 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
108 #include <netinet/in.h>
109 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
112 #if defined(__APPLE__) || defined (BSD)
113 # define MDB_USE_POSIX_SEM 1
114 # define MDB_FDATASYNC fsync
115 #elif defined(ANDROID)
116 # define MDB_FDATASYNC fsync
121 #ifdef MDB_USE_POSIX_SEM
122 # define MDB_USE_HASH 1
123 #include <semaphore.h>
128 #include <valgrind/memcheck.h>
129 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
130 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
131 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
132 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
133 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
135 #define VGMEMP_CREATE(h,r,z)
136 #define VGMEMP_ALLOC(h,a,s)
137 #define VGMEMP_FREE(h,a)
138 #define VGMEMP_DESTROY(h)
139 #define VGMEMP_DEFINED(a,s)
143 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
144 /* Solaris just defines one or the other */
145 # define LITTLE_ENDIAN 1234
146 # define BIG_ENDIAN 4321
147 # ifdef _LITTLE_ENDIAN
148 # define BYTE_ORDER LITTLE_ENDIAN
150 # define BYTE_ORDER BIG_ENDIAN
153 # define BYTE_ORDER __BYTE_ORDER
157 #ifndef LITTLE_ENDIAN
158 #define LITTLE_ENDIAN __LITTLE_ENDIAN
161 #define BIG_ENDIAN __BIG_ENDIAN
164 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
165 #define MISALIGNED_OK 1
171 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
172 # error "Unknown or unsupported endianness (BYTE_ORDER)"
173 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
174 # error "Two's complement, reasonably sized integer types, please"
178 /** Put infrequently used env functions in separate section */
180 # define ESECT __attribute__ ((section("__TEXT,text_env")))
182 # define ESECT __attribute__ ((section("text_env")))
189 #define CALL_CONV WINAPI
194 /** @defgroup internal LMDB Internals
197 /** @defgroup compat Compatibility Macros
198 * A bunch of macros to minimize the amount of platform-specific ifdefs
199 * needed throughout the rest of the code. When the features this library
200 * needs are similar enough to POSIX to be hidden in a one-or-two line
201 * replacement, this macro approach is used.
205 /** Features under development */
210 /** Wrapper around __func__, which is a C99 feature */
211 #if __STDC_VERSION__ >= 199901L
212 # define mdb_func_ __func__
213 #elif __GNUC__ >= 2 || _MSC_VER >= 1300
214 # define mdb_func_ __FUNCTION__
216 /* If a debug message says <mdb_unknown>(), update the #if statements above */
217 # define mdb_func_ "<mdb_unknown>"
221 #define MDB_USE_HASH 1
222 #define MDB_PIDLOCK 0
223 #define THREAD_RET DWORD
224 #define pthread_t HANDLE
225 #define pthread_mutex_t HANDLE
226 #define pthread_cond_t HANDLE
227 #define pthread_key_t DWORD
228 #define pthread_self() GetCurrentThreadId()
229 #define pthread_key_create(x,y) \
230 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
231 #define pthread_key_delete(x) TlsFree(x)
232 #define pthread_getspecific(x) TlsGetValue(x)
233 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
234 #define pthread_mutex_unlock(x) ReleaseMutex(*x)
235 #define pthread_mutex_lock(x) WaitForSingleObject(*x, INFINITE)
236 #define pthread_cond_signal(x) SetEvent(*x)
237 #define pthread_cond_wait(cond,mutex) do{SignalObjectAndWait(*mutex, *cond, INFINITE, FALSE); WaitForSingleObject(*mutex, INFINITE);}while(0)
238 #define THREAD_CREATE(thr,start,arg) thr=CreateThread(NULL,0,start,arg,0,NULL)
239 #define THREAD_FINISH(thr) WaitForSingleObject(thr, INFINITE)
240 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_rmutex)
241 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_rmutex)
242 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_wmutex)
243 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_wmutex)
244 #define getpid() GetCurrentProcessId()
245 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
246 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
247 #define ErrCode() GetLastError()
248 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
249 #define close(fd) (CloseHandle(fd) ? 0 : -1)
250 #define munmap(ptr,len) UnmapViewOfFile(ptr)
251 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
252 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
254 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
258 #define THREAD_RET void *
259 #define THREAD_CREATE(thr,start,arg) pthread_create(&thr,NULL,start,arg)
260 #define THREAD_FINISH(thr) pthread_join(thr,NULL)
261 #define Z "z" /**< printf format modifier for size_t */
263 /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
264 #define MDB_PIDLOCK 1
266 #ifdef MDB_USE_POSIX_SEM
268 #define LOCK_MUTEX_R(env) mdb_sem_wait((env)->me_rmutex)
269 #define UNLOCK_MUTEX_R(env) sem_post((env)->me_rmutex)
270 #define LOCK_MUTEX_W(env) mdb_sem_wait((env)->me_wmutex)
271 #define UNLOCK_MUTEX_W(env) sem_post((env)->me_wmutex)
274 mdb_sem_wait(sem_t *sem)
277 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
282 /** Lock the reader mutex.
284 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
285 /** Unlock the reader mutex.
287 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
289 /** Lock the writer mutex.
290 * Only a single write transaction is allowed at a time. Other writers
291 * will block waiting for this mutex.
293 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
294 /** Unlock the writer mutex.
296 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
297 #endif /* MDB_USE_POSIX_SEM */
299 /** Get the error code for the last failed system function.
301 #define ErrCode() errno
303 /** An abstraction for a file handle.
304 * On POSIX systems file handles are small integers. On Windows
305 * they're opaque pointers.
309 /** A value for an invalid file handle.
310 * Mainly used to initialize file variables and signify that they are
313 #define INVALID_HANDLE_VALUE (-1)
315 /** Get the size of a memory page for the system.
316 * This is the basic size that the platform's memory manager uses, and is
317 * fundamental to the use of memory-mapped files.
319 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
322 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
325 #define MNAME_LEN (sizeof(pthread_mutex_t))
331 /** A flag for opening a file and requesting synchronous data writes.
332 * This is only used when writing a meta page. It's not strictly needed;
333 * we could just do a normal write and then immediately perform a flush.
334 * But if this flag is available it saves us an extra system call.
336 * @note If O_DSYNC is undefined but exists in /usr/include,
337 * preferably set some compiler flag to get the definition.
338 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
341 # define MDB_DSYNC O_DSYNC
345 /** Function for flushing the data of a file. Define this to fsync
346 * if fdatasync() is not supported.
348 #ifndef MDB_FDATASYNC
349 # define MDB_FDATASYNC fdatasync
353 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
364 /** A page number in the database.
365 * Note that 64 bit page numbers are overkill, since pages themselves
366 * already represent 12-13 bits of addressable memory, and the OS will
367 * always limit applications to a maximum of 63 bits of address space.
369 * @note In the #MDB_node structure, we only store 48 bits of this value,
370 * which thus limits us to only 60 bits of addressable data.
372 typedef MDB_ID pgno_t;
374 /** A transaction ID.
375 * See struct MDB_txn.mt_txnid for details.
377 typedef MDB_ID txnid_t;
379 /** @defgroup debug Debug Macros
383 /** Enable debug output. Needs variable argument macros (a C99 feature).
384 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
385 * read from and written to the database (used for free space management).
391 static int mdb_debug;
392 static txnid_t mdb_debug_start;
394 /** Print a debug message with printf formatting.
395 * Requires double parenthesis around 2 or more args.
397 # define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
398 # define DPRINTF0(fmt, ...) \
399 fprintf(stderr, "%s:%d " fmt "\n", mdb_func_, __LINE__, __VA_ARGS__)
401 # define DPRINTF(args) ((void) 0)
403 /** Print a debug string.
404 * The string is printed literally, with no format processing.
406 #define DPUTS(arg) DPRINTF(("%s", arg))
407 /** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
409 (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
412 /** @brief The maximum size of a database page.
414 * It is 32k or 64k, since value-PAGEBASE must fit in
415 * #MDB_page.%mp_upper.
417 * LMDB will use database pages < OS pages if needed.
418 * That causes more I/O in write transactions: The OS must
419 * know (read) the whole page before writing a partial page.
421 * Note that we don't currently support Huge pages. On Linux,
422 * regular data files cannot use Huge pages, and in general
423 * Huge pages aren't actually pageable. We rely on the OS
424 * demand-pager to read our data and page it out when memory
425 * pressure from other processes is high. So until OSs have
426 * actual paging support for Huge pages, they're not viable.
428 #define MAX_PAGESIZE (PAGEBASE ? 0x10000 : 0x8000)
430 /** The minimum number of keys required in a database page.
431 * Setting this to a larger value will place a smaller bound on the
432 * maximum size of a data item. Data items larger than this size will
433 * be pushed into overflow pages instead of being stored directly in
434 * the B-tree node. This value used to default to 4. With a page size
435 * of 4096 bytes that meant that any item larger than 1024 bytes would
436 * go into an overflow page. That also meant that on average 2-3KB of
437 * each overflow page was wasted space. The value cannot be lower than
438 * 2 because then there would no longer be a tree structure. With this
439 * value, items larger than 2KB will go into overflow pages, and on
440 * average only 1KB will be wasted.
442 #define MDB_MINKEYS 2
444 /** A stamp that identifies a file as an LMDB file.
445 * There's nothing special about this value other than that it is easily
446 * recognizable, and it will reflect any byte order mismatches.
448 #define MDB_MAGIC 0xBEEFC0DE
450 /** The version number for a database's datafile format. */
451 #define MDB_DATA_VERSION ((MDB_DEVEL) ? 999 : 1)
452 /** The version number for a database's lockfile format. */
453 #define MDB_LOCK_VERSION 1
455 /** @brief The max size of a key we can write, or 0 for computed max.
457 * This macro should normally be left alone or set to 0.
458 * Note that a database with big keys or dupsort data cannot be
459 * reliably modified by a liblmdb which uses a smaller max.
460 * The default is 511 for backwards compat, or 0 when #MDB_DEVEL.
462 * Other values are allowed, for backwards compat. However:
463 * A value bigger than the computed max can break if you do not
464 * know what you are doing, and liblmdb <= 0.9.10 can break when
465 * modifying a DB with keys/dupsort data bigger than its max.
467 * Data items in an #MDB_DUPSORT database are also limited to
468 * this size, since they're actually keys of a sub-DB. Keys and
469 * #MDB_DUPSORT data items must fit on a node in a regular page.
471 #ifndef MDB_MAXKEYSIZE
472 #define MDB_MAXKEYSIZE ((MDB_DEVEL) ? 0 : 511)
475 /** The maximum size of a key we can write to the environment. */
477 #define ENV_MAXKEY(env) (MDB_MAXKEYSIZE)
479 #define ENV_MAXKEY(env) ((env)->me_maxkey)
482 /** @brief The maximum size of a data item.
484 * We only store a 32 bit value for node sizes.
486 #define MAXDATASIZE 0xffffffffUL
489 /** Key size which fits in a #DKBUF.
492 #define DKBUF_MAXKEYSIZE ((MDB_MAXKEYSIZE) > 0 ? (MDB_MAXKEYSIZE) : 511)
495 * This is used for printing a hex dump of a key's contents.
497 #define DKBUF char kbuf[DKBUF_MAXKEYSIZE*2+1]
498 /** Display a key in hex.
500 * Invoke a function to display a key in hex.
502 #define DKEY(x) mdb_dkey(x, kbuf)
508 /** An invalid page number.
509 * Mainly used to denote an empty tree.
511 #define P_INVALID (~(pgno_t)0)
513 /** Test if the flags \b f are set in a flag word \b w. */
514 #define F_ISSET(w, f) (((w) & (f)) == (f))
516 /** Round \b n up to an even number. */
517 #define EVEN(n) (((n) + 1U) & -2) /* sign-extending -2 to match n+1U */
519 /** Used for offsets within a single page.
520 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
523 typedef uint16_t indx_t;
525 /** Default size of memory map.
526 * This is certainly too small for any actual applications. Apps should always set
527 * the size explicitly using #mdb_env_set_mapsize().
529 #define DEFAULT_MAPSIZE 1048576
531 /** @defgroup readers Reader Lock Table
532 * Readers don't acquire any locks for their data access. Instead, they
533 * simply record their transaction ID in the reader table. The reader
534 * mutex is needed just to find an empty slot in the reader table. The
535 * slot's address is saved in thread-specific data so that subsequent read
536 * transactions started by the same thread need no further locking to proceed.
538 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
540 * No reader table is used if the database is on a read-only filesystem, or
541 * if #MDB_NOLOCK is set.
543 * Since the database uses multi-version concurrency control, readers don't
544 * actually need any locking. This table is used to keep track of which
545 * readers are using data from which old transactions, so that we'll know
546 * when a particular old transaction is no longer in use. Old transactions
547 * that have discarded any data pages can then have those pages reclaimed
548 * for use by a later write transaction.
550 * The lock table is constructed such that reader slots are aligned with the
551 * processor's cache line size. Any slot is only ever used by one thread.
552 * This alignment guarantees that there will be no contention or cache
553 * thrashing as threads update their own slot info, and also eliminates
554 * any need for locking when accessing a slot.
556 * A writer thread will scan every slot in the table to determine the oldest
557 * outstanding reader transaction. Any freed pages older than this will be
558 * reclaimed by the writer. The writer doesn't use any locks when scanning
559 * this table. This means that there's no guarantee that the writer will
560 * see the most up-to-date reader info, but that's not required for correct
561 * operation - all we need is to know the upper bound on the oldest reader,
562 * we don't care at all about the newest reader. So the only consequence of
563 * reading stale information here is that old pages might hang around a
564 * while longer before being reclaimed. That's actually good anyway, because
565 * the longer we delay reclaiming old pages, the more likely it is that a
566 * string of contiguous pages can be found after coalescing old pages from
567 * many old transactions together.
570 /** Number of slots in the reader table.
571 * This value was chosen somewhat arbitrarily. 126 readers plus a
572 * couple mutexes fit exactly into 8KB on my development machine.
573 * Applications should set the table size using #mdb_env_set_maxreaders().
575 #define DEFAULT_READERS 126
577 /** The size of a CPU cache line in bytes. We want our lock structures
578 * aligned to this size to avoid false cache line sharing in the
580 * This value works for most CPUs. For Itanium this should be 128.
586 /** The information we store in a single slot of the reader table.
587 * In addition to a transaction ID, we also record the process and
588 * thread ID that owns a slot, so that we can detect stale information,
589 * e.g. threads or processes that went away without cleaning up.
590 * @note We currently don't check for stale records. We simply re-init
591 * the table when we know that we're the only process opening the
594 typedef struct MDB_rxbody {
595 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
596 * Multiple readers that start at the same time will probably have the
597 * same ID here. Again, it's not important to exclude them from
598 * anything; all we need to know is which version of the DB they
599 * started from so we can avoid overwriting any data used in that
600 * particular version.
602 volatile txnid_t mrb_txnid;
603 /** The process ID of the process owning this reader txn. */
604 volatile MDB_PID_T mrb_pid;
605 /** The thread ID of the thread owning this txn. */
606 volatile MDB_THR_T mrb_tid;
609 /** The actual reader record, with cacheline padding. */
610 typedef struct MDB_reader {
613 /** shorthand for mrb_txnid */
614 #define mr_txnid mru.mrx.mrb_txnid
615 #define mr_pid mru.mrx.mrb_pid
616 #define mr_tid mru.mrx.mrb_tid
617 /** cache line alignment */
618 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
622 /** The header for the reader table.
623 * The table resides in a memory-mapped file. (This is a different file
624 * than is used for the main database.)
626 * For POSIX the actual mutexes reside in the shared memory of this
627 * mapped file. On Windows, mutexes are named objects allocated by the
628 * kernel; we store the mutex names in this mapped file so that other
629 * processes can grab them. This same approach is also used on
630 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
631 * process-shared POSIX mutexes. For these cases where a named object
632 * is used, the object name is derived from a 64 bit FNV hash of the
633 * environment pathname. As such, naming collisions are extremely
634 * unlikely. If a collision occurs, the results are unpredictable.
636 typedef struct MDB_txbody {
637 /** Stamp identifying this as an LMDB file. It must be set
640 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
642 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
643 char mtb_rmname[MNAME_LEN];
645 /** Mutex protecting access to this table.
646 * This is the reader lock that #LOCK_MUTEX_R acquires.
648 pthread_mutex_t mtb_mutex;
650 /** The ID of the last transaction committed to the database.
651 * This is recorded here only for convenience; the value can always
652 * be determined by reading the main database meta pages.
654 volatile txnid_t mtb_txnid;
655 /** The number of slots that have been used in the reader table.
656 * This always records the maximum count, it is not decremented
657 * when readers release their slots.
659 volatile unsigned mtb_numreaders;
662 /** The actual reader table definition. */
663 typedef struct MDB_txninfo {
666 #define mti_magic mt1.mtb.mtb_magic
667 #define mti_format mt1.mtb.mtb_format
668 #define mti_mutex mt1.mtb.mtb_mutex
669 #define mti_rmname mt1.mtb.mtb_rmname
670 #define mti_txnid mt1.mtb.mtb_txnid
671 #define mti_numreaders mt1.mtb.mtb_numreaders
672 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
675 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
676 char mt2_wmname[MNAME_LEN];
677 #define mti_wmname mt2.mt2_wmname
679 pthread_mutex_t mt2_wmutex;
680 #define mti_wmutex mt2.mt2_wmutex
682 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
684 MDB_reader mti_readers[1];
687 /** Lockfile format signature: version, features and field layout */
688 #define MDB_LOCK_FORMAT \
690 ((MDB_LOCK_VERSION) \
691 /* Flags which describe functionality */ \
692 + (((MDB_PIDLOCK) != 0) << 16)))
695 /** Common header for all page types.
696 * Overflow records occupy a number of contiguous pages with no
697 * headers on any page after the first.
699 typedef struct MDB_page {
700 #define mp_pgno mp_p.p_pgno
701 #define mp_next mp_p.p_next
703 pgno_t p_pgno; /**< page number */
704 struct MDB_page *p_next; /**< for in-memory list of freed pages */
707 /** @defgroup mdb_page Page Flags
709 * Flags for the page headers.
712 #define P_BRANCH 0x01 /**< branch page */
713 #define P_LEAF 0x02 /**< leaf page */
714 #define P_OVERFLOW 0x04 /**< overflow page */
715 #define P_META 0x08 /**< meta page */
716 #define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
717 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
718 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
719 #define P_LOOSE 0x4000 /**< page was dirtied then freed, can be reused */
720 #define P_KEEP 0x8000 /**< leave this page alone during spill */
722 uint16_t mp_flags; /**< @ref mdb_page */
723 #define mp_lower mp_pb.pb.pb_lower
724 #define mp_upper mp_pb.pb.pb_upper
725 #define mp_pages mp_pb.pb_pages
728 indx_t pb_lower; /**< lower bound of free space */
729 indx_t pb_upper; /**< upper bound of free space */
731 uint32_t pb_pages; /**< number of overflow pages */
733 indx_t mp_ptrs[1]; /**< dynamic size */
736 /** Size of the page header, excluding dynamic data at the end */
737 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
739 /** Address of first usable data byte in a page, after the header */
740 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
742 /** ITS#7713, change PAGEBASE to handle 65536 byte pages */
743 #define PAGEBASE ((MDB_DEVEL) ? PAGEHDRSZ : 0)
745 /** Number of nodes on a page */
746 #define NUMKEYS(p) (((p)->mp_lower - (PAGEHDRSZ-PAGEBASE)) >> 1)
748 /** The amount of space remaining in the page */
749 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
751 /** The percentage of space used in the page, in tenths of a percent. */
752 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
753 ((env)->me_psize - PAGEHDRSZ))
754 /** The minimum page fill factor, in tenths of a percent.
755 * Pages emptier than this are candidates for merging.
757 #define FILL_THRESHOLD 250
759 /** Test if a page is a leaf page */
760 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
761 /** Test if a page is a LEAF2 page */
762 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
763 /** Test if a page is a branch page */
764 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
765 /** Test if a page is an overflow page */
766 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
767 /** Test if a page is a sub page */
768 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
770 /** The number of overflow pages needed to store the given size. */
771 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
773 /** Link in #MDB_txn.%mt_loose_pgs list */
774 #define NEXT_LOOSE_PAGE(p) (*(MDB_page **)((p) + 2))
776 /** Header for a single key/data pair within a page.
777 * Used in pages of type #P_BRANCH and #P_LEAF without #P_LEAF2.
778 * We guarantee 2-byte alignment for 'MDB_node's.
780 typedef struct MDB_node {
781 /** lo and hi are used for data size on leaf nodes and for
782 * child pgno on branch nodes. On 64 bit platforms, flags
783 * is also used for pgno. (Branch nodes have no flags).
784 * They are in host byte order in case that lets some
785 * accesses be optimized into a 32-bit word access.
787 #if BYTE_ORDER == LITTLE_ENDIAN
788 unsigned short mn_lo, mn_hi; /**< part of data size or pgno */
790 unsigned short mn_hi, mn_lo;
792 /** @defgroup mdb_node Node Flags
794 * Flags for node headers.
797 #define F_BIGDATA 0x01 /**< data put on overflow page */
798 #define F_SUBDATA 0x02 /**< data is a sub-database */
799 #define F_DUPDATA 0x04 /**< data has duplicates */
801 /** valid flags for #mdb_node_add() */
802 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
805 unsigned short mn_flags; /**< @ref mdb_node */
806 unsigned short mn_ksize; /**< key size */
807 char mn_data[1]; /**< key and data are appended here */
810 /** Size of the node header, excluding dynamic data at the end */
811 #define NODESIZE offsetof(MDB_node, mn_data)
813 /** Bit position of top word in page number, for shifting mn_flags */
814 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
816 /** Size of a node in a branch page with a given key.
817 * This is just the node header plus the key, there is no data.
819 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
821 /** Size of a node in a leaf page with a given key and data.
822 * This is node header plus key plus data size.
824 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
826 /** Address of node \b i in page \b p */
827 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i] + PAGEBASE))
829 /** Address of the key for the node */
830 #define NODEKEY(node) (void *)((node)->mn_data)
832 /** Address of the data for a node */
833 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
835 /** Get the page number pointed to by a branch node */
836 #define NODEPGNO(node) \
837 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
838 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
839 /** Set the page number in a branch node */
840 #define SETPGNO(node,pgno) do { \
841 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
842 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
844 /** Get the size of the data in a leaf node */
845 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
846 /** Set the size of the data for a leaf node */
847 #define SETDSZ(node,size) do { \
848 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
849 /** The size of a key in a node */
850 #define NODEKSZ(node) ((node)->mn_ksize)
852 /** Copy a page number from src to dst */
854 #define COPY_PGNO(dst,src) dst = src
856 #if SIZE_MAX > 4294967295UL
857 #define COPY_PGNO(dst,src) do { \
858 unsigned short *s, *d; \
859 s = (unsigned short *)&(src); \
860 d = (unsigned short *)&(dst); \
867 #define COPY_PGNO(dst,src) do { \
868 unsigned short *s, *d; \
869 s = (unsigned short *)&(src); \
870 d = (unsigned short *)&(dst); \
876 /** The address of a key in a LEAF2 page.
877 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
878 * There are no node headers, keys are stored contiguously.
880 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
882 /** Set the \b node's key into \b keyptr, if requested. */
883 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
884 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
886 /** Set the \b node's key into \b key. */
887 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
889 /** Information about a single database in the environment. */
890 typedef struct MDB_db {
891 uint32_t md_pad; /**< also ksize for LEAF2 pages */
892 uint16_t md_flags; /**< @ref mdb_dbi_open */
893 uint16_t md_depth; /**< depth of this tree */
894 pgno_t md_branch_pages; /**< number of internal pages */
895 pgno_t md_leaf_pages; /**< number of leaf pages */
896 pgno_t md_overflow_pages; /**< number of overflow pages */
897 size_t md_entries; /**< number of data items */
898 pgno_t md_root; /**< the root page of this tree */
901 /** mdb_dbi_open flags */
902 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
903 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
904 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
905 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
907 /** Handle for the DB used to track free pages. */
909 /** Handle for the default DB. */
912 /** Meta page content.
913 * A meta page is the start point for accessing a database snapshot.
914 * Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
916 typedef struct MDB_meta {
917 /** Stamp identifying this as an LMDB file. It must be set
920 /** Version number of this file. Must be set to #MDB_DATA_VERSION. */
922 void *mm_address; /**< address for fixed mapping */
923 size_t mm_mapsize; /**< size of mmap region */
924 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
925 /** The size of pages used in this DB */
926 #define mm_psize mm_dbs[0].md_pad
927 /** Any persistent environment flags. @ref mdb_env */
928 #define mm_flags mm_dbs[0].md_flags
929 pgno_t mm_last_pg; /**< last used page in file */
930 volatile txnid_t mm_txnid; /**< txnid that committed this page */
933 /** Buffer for a stack-allocated meta page.
934 * The members define size and alignment, and silence type
935 * aliasing warnings. They are not used directly; that could
936 * mean incorrectly using several union members in parallel.
938 typedef union MDB_metabuf {
941 char mm_pad[PAGEHDRSZ];
946 /** Auxiliary DB info.
947 * The information here is mostly static/read-only. There is
948 * only a single copy of this record in the environment.
950 typedef struct MDB_dbx {
951 MDB_val md_name; /**< name of the database */
952 MDB_cmp_func *md_cmp; /**< function for comparing keys */
953 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
954 MDB_rel_func *md_rel; /**< user relocate function */
955 void *md_relctx; /**< user-provided context for md_rel */
958 /** A database transaction.
959 * Every operation requires a transaction handle.
962 MDB_txn *mt_parent; /**< parent of a nested txn */
963 MDB_txn *mt_child; /**< nested txn under this txn */
964 pgno_t mt_next_pgno; /**< next unallocated page */
965 /** The ID of this transaction. IDs are integers incrementing from 1.
966 * Only committed write transactions increment the ID. If a transaction
967 * aborts, the ID may be re-used by the next writer.
970 MDB_env *mt_env; /**< the DB environment */
971 /** The list of pages that became unused during this transaction.
974 /** The list of loose pages that became unused and may be reused
975 * in this transaction, linked through #NEXT_LOOSE_PAGE(page).
977 MDB_page *mt_loose_pgs;
978 /* #Number of loose pages (#mt_loose_pgs) */
980 /** The sorted list of dirty pages we temporarily wrote to disk
981 * because the dirty list was full. page numbers in here are
982 * shifted left by 1, deleted slots have the LSB set.
984 MDB_IDL mt_spill_pgs;
986 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
988 /** For read txns: This thread/txn's reader table slot, or NULL. */
991 /** Array of records for each DB known in the environment. */
993 /** Array of MDB_db records for each known DB */
995 /** Array of sequence numbers for each DB handle */
996 unsigned int *mt_dbiseqs;
997 /** @defgroup mt_dbflag Transaction DB Flags
1001 #define DB_DIRTY 0x01 /**< DB was modified or is DUPSORT data */
1002 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
1003 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
1004 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
1006 /** In write txns, array of cursors for each DB */
1007 MDB_cursor **mt_cursors;
1008 /** Array of flags for each DB */
1009 unsigned char *mt_dbflags;
1010 /** Number of DB records in use. This number only ever increments;
1011 * we don't decrement it when individual DB handles are closed.
1015 /** @defgroup mdb_txn Transaction Flags
1019 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
1020 #define MDB_TXN_ERROR 0x02 /**< txn is unusable after an error */
1021 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
1022 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
1024 unsigned int mt_flags; /**< @ref mdb_txn */
1025 /** #dirty_list room: Array size - \#dirty pages visible to this txn.
1026 * Includes ancestor txns' dirty pages not hidden by other txns'
1027 * dirty/spilled pages. Thus commit(nested txn) has room to merge
1028 * dirty_list into mt_parent after freeing hidden mt_parent pages.
1030 unsigned int mt_dirty_room;
1033 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
1034 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
1035 * raise this on a 64 bit machine.
1037 #define CURSOR_STACK 32
1041 /** Cursors are used for all DB operations.
1042 * A cursor holds a path of (page pointer, key index) from the DB
1043 * root to a position in the DB, plus other state. #MDB_DUPSORT
1044 * cursors include an xcursor to the current data item. Write txns
1045 * track their cursors and keep them up to date when data moves.
1046 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
1047 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
1050 /** Next cursor on this DB in this txn */
1051 MDB_cursor *mc_next;
1052 /** Backup of the original cursor if this cursor is a shadow */
1053 MDB_cursor *mc_backup;
1054 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
1055 struct MDB_xcursor *mc_xcursor;
1056 /** The transaction that owns this cursor */
1058 /** The database handle this cursor operates on */
1060 /** The database record for this cursor */
1062 /** The database auxiliary record for this cursor */
1064 /** The @ref mt_dbflag for this database */
1065 unsigned char *mc_dbflag;
1066 unsigned short mc_snum; /**< number of pushed pages */
1067 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
1068 /** @defgroup mdb_cursor Cursor Flags
1070 * Cursor state flags.
1073 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
1074 #define C_EOF 0x02 /**< No more data */
1075 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
1076 #define C_DEL 0x08 /**< last op was a cursor_del */
1077 #define C_SPLITTING 0x20 /**< Cursor is in page_split */
1078 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
1080 unsigned int mc_flags; /**< @ref mdb_cursor */
1081 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
1082 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
1085 /** Context for sorted-dup records.
1086 * We could have gone to a fully recursive design, with arbitrarily
1087 * deep nesting of sub-databases. But for now we only handle these
1088 * levels - main DB, optional sub-DB, sorted-duplicate DB.
1090 typedef struct MDB_xcursor {
1091 /** A sub-cursor for traversing the Dup DB */
1092 MDB_cursor mx_cursor;
1093 /** The database record for this Dup DB */
1095 /** The auxiliary DB record for this Dup DB */
1097 /** The @ref mt_dbflag for this Dup DB */
1098 unsigned char mx_dbflag;
1101 /** State of FreeDB old pages, stored in the MDB_env */
1102 typedef struct MDB_pgstate {
1103 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1104 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1107 /** The database environment. */
1109 HANDLE me_fd; /**< The main data file */
1110 HANDLE me_lfd; /**< The lock file */
1111 HANDLE me_mfd; /**< just for writing the meta pages */
1112 /** Failed to update the meta page. Probably an I/O error. */
1113 #define MDB_FATAL_ERROR 0x80000000U
1114 /** Some fields are initialized. */
1115 #define MDB_ENV_ACTIVE 0x20000000U
1116 /** me_txkey is set */
1117 #define MDB_ENV_TXKEY 0x10000000U
1118 /** fdatasync is unreliable */
1119 #define MDB_FSYNCONLY 0x08000000U
1120 uint32_t me_flags; /**< @ref mdb_env */
1121 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1122 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1123 unsigned int me_maxreaders; /**< size of the reader table */
1124 unsigned int me_numreaders; /**< max numreaders set by this env */
1125 MDB_dbi me_numdbs; /**< number of DBs opened */
1126 MDB_dbi me_maxdbs; /**< size of the DB table */
1127 MDB_PID_T me_pid; /**< process ID of this env */
1128 char *me_path; /**< path to the DB files */
1129 char *me_map; /**< the memory map of the data file */
1130 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1131 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
1132 void *me_pbuf; /**< scratch area for DUPSORT put() */
1133 MDB_txn *me_txn; /**< current write transaction */
1134 MDB_txn *me_txn0; /**< prealloc'd write transaction */
1135 size_t me_mapsize; /**< size of the data memory map */
1136 off_t me_size; /**< current file size */
1137 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1138 MDB_dbx *me_dbxs; /**< array of static DB info */
1139 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1140 unsigned int *me_dbiseqs; /**< array of dbi sequence numbers */
1141 pthread_key_t me_txkey; /**< thread-key for readers */
1142 txnid_t me_pgoldest; /**< ID of oldest reader last time we looked */
1143 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1144 # define me_pglast me_pgstate.mf_pglast
1145 # define me_pghead me_pgstate.mf_pghead
1146 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1147 /** IDL of pages that became unused in a write txn */
1148 MDB_IDL me_free_pgs;
1149 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1150 MDB_ID2L me_dirty_list;
1151 /** Max number of freelist items that can fit in a single overflow page */
1153 /** Max size of a node on a page */
1154 unsigned int me_nodemax;
1155 #if !(MDB_MAXKEYSIZE)
1156 unsigned int me_maxkey; /**< max size of a key */
1158 int me_live_reader; /**< have liveness lock in reader table */
1160 int me_pidquery; /**< Used in OpenProcess */
1161 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
1163 #elif defined(MDB_USE_POSIX_SEM)
1164 sem_t *me_rmutex; /* Shared mutexes are not supported */
1167 void *me_userctx; /**< User-settable context */
1168 MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
1171 /** Nested transaction */
1172 typedef struct MDB_ntxn {
1173 MDB_txn mnt_txn; /**< the transaction */
1174 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1177 /** max number of pages to commit in one writev() call */
1178 #define MDB_COMMIT_PAGES 64
1179 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1180 #undef MDB_COMMIT_PAGES
1181 #define MDB_COMMIT_PAGES IOV_MAX
1184 /** max bytes to write in one call */
1185 #define MAX_WRITE (0x80000000U >> (sizeof(ssize_t) == 4))
1187 /** Check \b txn and \b dbi arguments to a function */
1188 #define TXN_DBI_EXIST(txn, dbi) \
1189 ((txn) && (dbi) < (txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & DB_VALID))
1191 /** Check for misused \b dbi handles */
1192 #define TXN_DBI_CHANGED(txn, dbi) \
1193 ((txn)->mt_dbiseqs[dbi] != (txn)->mt_env->me_dbiseqs[dbi])
1195 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1196 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1197 static int mdb_page_touch(MDB_cursor *mc);
1199 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp, int *lvl);
1200 static int mdb_page_search_root(MDB_cursor *mc,
1201 MDB_val *key, int modify);
1202 #define MDB_PS_MODIFY 1
1203 #define MDB_PS_ROOTONLY 2
1204 #define MDB_PS_FIRST 4
1205 #define MDB_PS_LAST 8
1206 static int mdb_page_search(MDB_cursor *mc,
1207 MDB_val *key, int flags);
1208 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1210 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1211 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1212 pgno_t newpgno, unsigned int nflags);
1214 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1215 static int mdb_env_pick_meta(const MDB_env *env);
1216 static int mdb_env_write_meta(MDB_txn *txn);
1217 #if !(defined(_WIN32) || defined(MDB_USE_POSIX_SEM)) /* Drop unused excl arg */
1218 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1220 static void mdb_env_close0(MDB_env *env, int excl);
1222 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1223 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1224 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1225 static void mdb_node_del(MDB_cursor *mc, int ksize);
1226 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1227 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
1228 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1229 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1230 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1232 static int mdb_rebalance(MDB_cursor *mc);
1233 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1235 static void mdb_cursor_pop(MDB_cursor *mc);
1236 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1238 static int mdb_cursor_del0(MDB_cursor *mc);
1239 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
1240 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1241 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1242 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1243 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1245 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1246 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1248 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1249 static void mdb_xcursor_init0(MDB_cursor *mc);
1250 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1251 static void mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int force);
1253 static int mdb_drop0(MDB_cursor *mc, int subs);
1254 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1257 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1260 /** Compare two items pointing at size_t's of unknown alignment. */
1261 #ifdef MISALIGNED_OK
1262 # define mdb_cmp_clong mdb_cmp_long
1264 # define mdb_cmp_clong mdb_cmp_cint
1268 static SECURITY_DESCRIPTOR mdb_null_sd;
1269 static SECURITY_ATTRIBUTES mdb_all_sa;
1270 static int mdb_sec_inited;
1273 /** Return the library version info. */
1275 mdb_version(int *major, int *minor, int *patch)
1277 if (major) *major = MDB_VERSION_MAJOR;
1278 if (minor) *minor = MDB_VERSION_MINOR;
1279 if (patch) *patch = MDB_VERSION_PATCH;
1280 return MDB_VERSION_STRING;
1283 /** Table of descriptions for LMDB @ref errors */
1284 static char *const mdb_errstr[] = {
1285 "MDB_KEYEXIST: Key/data pair already exists",
1286 "MDB_NOTFOUND: No matching key/data pair found",
1287 "MDB_PAGE_NOTFOUND: Requested page not found",
1288 "MDB_CORRUPTED: Located page was wrong type",
1289 "MDB_PANIC: Update of meta page failed",
1290 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1291 "MDB_INVALID: File is not an LMDB file",
1292 "MDB_MAP_FULL: Environment mapsize limit reached",
1293 "MDB_DBS_FULL: Environment maxdbs limit reached",
1294 "MDB_READERS_FULL: Environment maxreaders limit reached",
1295 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1296 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1297 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1298 "MDB_PAGE_FULL: Internal error - page has no more space",
1299 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1300 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1301 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1302 "MDB_BAD_TXN: Transaction cannot recover - it must be aborted",
1303 "MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
1304 "MDB_BAD_DBI: The specified DBI handle was closed/changed unexpectedly",
1308 mdb_strerror(int err)
1311 /** HACK: pad 4KB on stack over the buf. Return system msgs in buf.
1312 * This works as long as no function between the call to mdb_strerror
1313 * and the actual use of the message uses more than 4K of stack.
1316 char buf[1024], *ptr = buf;
1320 return ("Successful return: 0");
1322 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1323 i = err - MDB_KEYEXIST;
1324 return mdb_errstr[i];
1328 /* These are the C-runtime error codes we use. The comment indicates
1329 * their numeric value, and the Win32 error they would correspond to
1330 * if the error actually came from a Win32 API. A major mess, we should
1331 * have used LMDB-specific error codes for everything.
1334 case ENOENT: /* 2, FILE_NOT_FOUND */
1335 case EIO: /* 5, ACCESS_DENIED */
1336 case ENOMEM: /* 12, INVALID_ACCESS */
1337 case EACCES: /* 13, INVALID_DATA */
1338 case EBUSY: /* 16, CURRENT_DIRECTORY */
1339 case EINVAL: /* 22, BAD_COMMAND */
1340 case ENOSPC: /* 28, OUT_OF_PAPER */
1341 return strerror(err);
1346 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1347 FORMAT_MESSAGE_IGNORE_INSERTS,
1348 NULL, err, 0, ptr, sizeof(buf), (va_list *)pad);
1351 return strerror(err);
1355 /** assert(3) variant in cursor context */
1356 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1357 /** assert(3) variant in transaction context */
1358 #define mdb_tassert(mc, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1359 /** assert(3) variant in environment context */
1360 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1363 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1364 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1367 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1368 const char *func, const char *file, int line)
1371 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1372 file, line, expr_txt, func);
1373 if (env->me_assert_func)
1374 env->me_assert_func(env, buf);
1375 fprintf(stderr, "%s\n", buf);
1379 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1383 /** Return the page number of \b mp which may be sub-page, for debug output */
1385 mdb_dbg_pgno(MDB_page *mp)
1388 COPY_PGNO(ret, mp->mp_pgno);
1392 /** Display a key in hexadecimal and return the address of the result.
1393 * @param[in] key the key to display
1394 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1395 * @return The key in hexadecimal form.
1398 mdb_dkey(MDB_val *key, char *buf)
1401 unsigned char *c = key->mv_data;
1407 if (key->mv_size > DKBUF_MAXKEYSIZE)
1408 return "MDB_MAXKEYSIZE";
1409 /* may want to make this a dynamic check: if the key is mostly
1410 * printable characters, print it as-is instead of converting to hex.
1414 for (i=0; i<key->mv_size; i++)
1415 ptr += sprintf(ptr, "%02x", *c++);
1417 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1423 mdb_leafnode_type(MDB_node *n)
1425 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1426 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1427 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1430 /** Display all the keys in the page. */
1432 mdb_page_list(MDB_page *mp)
1434 pgno_t pgno = mdb_dbg_pgno(mp);
1435 const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
1437 unsigned int i, nkeys, nsize, total = 0;
1441 switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1442 case P_BRANCH: type = "Branch page"; break;
1443 case P_LEAF: type = "Leaf page"; break;
1444 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1445 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1446 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1448 fprintf(stderr, "Overflow page %"Z"u pages %u%s\n",
1449 pgno, mp->mp_pages, state);
1452 fprintf(stderr, "Meta-page %"Z"u txnid %"Z"u\n",
1453 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1456 fprintf(stderr, "Bad page %"Z"u flags 0x%u\n", pgno, mp->mp_flags);
1460 nkeys = NUMKEYS(mp);
1461 fprintf(stderr, "%s %"Z"u numkeys %d%s\n", type, pgno, nkeys, state);
1463 for (i=0; i<nkeys; i++) {
1464 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1465 key.mv_size = nsize = mp->mp_pad;
1466 key.mv_data = LEAF2KEY(mp, i, nsize);
1468 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1471 node = NODEPTR(mp, i);
1472 key.mv_size = node->mn_ksize;
1473 key.mv_data = node->mn_data;
1474 nsize = NODESIZE + key.mv_size;
1475 if (IS_BRANCH(mp)) {
1476 fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
1480 if (F_ISSET(node->mn_flags, F_BIGDATA))
1481 nsize += sizeof(pgno_t);
1483 nsize += NODEDSZ(node);
1485 nsize += sizeof(indx_t);
1486 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1487 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1489 total = EVEN(total);
1491 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1492 IS_LEAF2(mp) ? PAGEHDRSZ : PAGEBASE + mp->mp_lower, total, SIZELEFT(mp));
1496 mdb_cursor_chk(MDB_cursor *mc)
1502 if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1503 for (i=0; i<mc->mc_top; i++) {
1505 node = NODEPTR(mp, mc->mc_ki[i]);
1506 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1509 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1515 /** Count all the pages in each DB and in the freelist
1516 * and make sure it matches the actual number of pages
1518 * All named DBs must be open for a correct count.
1520 static void mdb_audit(MDB_txn *txn)
1524 MDB_ID freecount, count;
1529 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1530 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1531 freecount += *(MDB_ID *)data.mv_data;
1532 mdb_tassert(txn, rc == MDB_NOTFOUND);
1535 for (i = 0; i<txn->mt_numdbs; i++) {
1537 if (!(txn->mt_dbflags[i] & DB_VALID))
1539 mdb_cursor_init(&mc, txn, i, &mx);
1540 if (txn->mt_dbs[i].md_root == P_INVALID)
1542 count += txn->mt_dbs[i].md_branch_pages +
1543 txn->mt_dbs[i].md_leaf_pages +
1544 txn->mt_dbs[i].md_overflow_pages;
1545 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1546 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1547 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
1550 mp = mc.mc_pg[mc.mc_top];
1551 for (j=0; j<NUMKEYS(mp); j++) {
1552 MDB_node *leaf = NODEPTR(mp, j);
1553 if (leaf->mn_flags & F_SUBDATA) {
1555 memcpy(&db, NODEDATA(leaf), sizeof(db));
1556 count += db.md_branch_pages + db.md_leaf_pages +
1557 db.md_overflow_pages;
1561 mdb_tassert(txn, rc == MDB_NOTFOUND);
1564 if (freecount + count + 2 /* metapages */ != txn->mt_next_pgno) {
1565 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1566 txn->mt_txnid, freecount, count+2, freecount+count+2, txn->mt_next_pgno);
1572 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1574 return txn->mt_dbxs[dbi].md_cmp(a, b);
1578 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1580 MDB_cmp_func *dcmp = txn->mt_dbxs[dbi].md_dcmp;
1581 #if UINT_MAX < SIZE_MAX
1582 if (dcmp == mdb_cmp_int && a->mv_size == sizeof(size_t))
1583 dcmp = mdb_cmp_clong;
1588 /** Allocate memory for a page.
1589 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1592 mdb_page_malloc(MDB_txn *txn, unsigned num)
1594 MDB_env *env = txn->mt_env;
1595 MDB_page *ret = env->me_dpages;
1596 size_t psize = env->me_psize, sz = psize, off;
1597 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1598 * For a single page alloc, we init everything after the page header.
1599 * For multi-page, we init the final page; if the caller needed that
1600 * many pages they will be filling in at least up to the last page.
1604 VGMEMP_ALLOC(env, ret, sz);
1605 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1606 env->me_dpages = ret->mp_next;
1609 psize -= off = PAGEHDRSZ;
1614 if ((ret = malloc(sz)) != NULL) {
1615 VGMEMP_ALLOC(env, ret, sz);
1616 if (!(env->me_flags & MDB_NOMEMINIT)) {
1617 memset((char *)ret + off, 0, psize);
1621 txn->mt_flags |= MDB_TXN_ERROR;
1625 /** Free a single page.
1626 * Saves single pages to a list, for future reuse.
1627 * (This is not used for multi-page overflow pages.)
1630 mdb_page_free(MDB_env *env, MDB_page *mp)
1632 mp->mp_next = env->me_dpages;
1633 VGMEMP_FREE(env, mp);
1634 env->me_dpages = mp;
1637 /** Free a dirty page */
1639 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1641 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1642 mdb_page_free(env, dp);
1644 /* large pages just get freed directly */
1645 VGMEMP_FREE(env, dp);
1650 /** Return all dirty pages to dpage list */
1652 mdb_dlist_free(MDB_txn *txn)
1654 MDB_env *env = txn->mt_env;
1655 MDB_ID2L dl = txn->mt_u.dirty_list;
1656 unsigned i, n = dl[0].mid;
1658 for (i = 1; i <= n; i++) {
1659 mdb_dpage_free(env, dl[i].mptr);
1664 /** Loosen or free a single page.
1665 * Saves single pages to a list for future reuse
1666 * in this same txn. It has been pulled from the freeDB
1667 * and already resides on the dirty list, but has been
1668 * deleted. Use these pages first before pulling again
1671 * If the page wasn't dirtied in this txn, just add it
1672 * to this txn's free list.
1675 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
1678 pgno_t pgno = mp->mp_pgno;
1679 MDB_txn *txn = mc->mc_txn;
1681 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
1682 if (txn->mt_parent) {
1683 MDB_ID2 *dl = txn->mt_u.dirty_list;
1684 /* If txn has a parent, make sure the page is in our
1688 unsigned x = mdb_mid2l_search(dl, pgno);
1689 if (x <= dl[0].mid && dl[x].mid == pgno) {
1690 if (mp != dl[x].mptr) { /* bad cursor? */
1691 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1692 txn->mt_flags |= MDB_TXN_ERROR;
1693 return MDB_CORRUPTED;
1700 /* no parent txn, so it's just ours */
1705 DPRINTF(("loosen db %d page %"Z"u", DDBI(mc),
1707 NEXT_LOOSE_PAGE(mp) = txn->mt_loose_pgs;
1708 txn->mt_loose_pgs = mp;
1709 txn->mt_loose_count++;
1710 mp->mp_flags |= P_LOOSE;
1712 int rc = mdb_midl_append(&txn->mt_free_pgs, pgno);
1720 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
1721 * @param[in] mc A cursor handle for the current operation.
1722 * @param[in] pflags Flags of the pages to update:
1723 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1724 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
1725 * @return 0 on success, non-zero on failure.
1728 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
1730 enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
1731 MDB_txn *txn = mc->mc_txn;
1737 int rc = MDB_SUCCESS, level;
1739 /* Mark pages seen by cursors */
1740 if (mc->mc_flags & C_UNTRACK)
1741 mc = NULL; /* will find mc in mt_cursors */
1742 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1743 for (; mc; mc=mc->mc_next) {
1744 if (!(mc->mc_flags & C_INITIALIZED))
1746 for (m3 = mc;; m3 = &mx->mx_cursor) {
1748 for (j=0; j<m3->mc_snum; j++) {
1750 if ((mp->mp_flags & Mask) == pflags)
1751 mp->mp_flags ^= P_KEEP;
1753 mx = m3->mc_xcursor;
1754 /* Proceed to mx if it is at a sub-database */
1755 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
1757 if (! (mp && (mp->mp_flags & P_LEAF)))
1759 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
1760 if (!(leaf->mn_flags & F_SUBDATA))
1769 /* Mark dirty root pages */
1770 for (i=0; i<txn->mt_numdbs; i++) {
1771 if (txn->mt_dbflags[i] & DB_DIRTY) {
1772 pgno_t pgno = txn->mt_dbs[i].md_root;
1773 if (pgno == P_INVALID)
1775 if ((rc = mdb_page_get(txn, pgno, &dp, &level)) != MDB_SUCCESS)
1777 if ((dp->mp_flags & Mask) == pflags && level <= 1)
1778 dp->mp_flags ^= P_KEEP;
1786 static int mdb_page_flush(MDB_txn *txn, int keep);
1788 /** Spill pages from the dirty list back to disk.
1789 * This is intended to prevent running into #MDB_TXN_FULL situations,
1790 * but note that they may still occur in a few cases:
1791 * 1) our estimate of the txn size could be too small. Currently this
1792 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
1793 * 2) child txns may run out of space if their parents dirtied a
1794 * lot of pages and never spilled them. TODO: we probably should do
1795 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1796 * the parent's dirty_room is below a given threshold.
1798 * Otherwise, if not using nested txns, it is expected that apps will
1799 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1800 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1801 * If the txn never references them again, they can be left alone.
1802 * If the txn only reads them, they can be used without any fuss.
1803 * If the txn writes them again, they can be dirtied immediately without
1804 * going thru all of the work of #mdb_page_touch(). Such references are
1805 * handled by #mdb_page_unspill().
1807 * Also note, we never spill DB root pages, nor pages of active cursors,
1808 * because we'll need these back again soon anyway. And in nested txns,
1809 * we can't spill a page in a child txn if it was already spilled in a
1810 * parent txn. That would alter the parent txns' data even though
1811 * the child hasn't committed yet, and we'd have no way to undo it if
1812 * the child aborted.
1814 * @param[in] m0 cursor A cursor handle identifying the transaction and
1815 * database for which we are checking space.
1816 * @param[in] key For a put operation, the key being stored.
1817 * @param[in] data For a put operation, the data being stored.
1818 * @return 0 on success, non-zero on failure.
1821 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1823 MDB_txn *txn = m0->mc_txn;
1825 MDB_ID2L dl = txn->mt_u.dirty_list;
1826 unsigned int i, j, need;
1829 if (m0->mc_flags & C_SUB)
1832 /* Estimate how much space this op will take */
1833 i = m0->mc_db->md_depth;
1834 /* Named DBs also dirty the main DB */
1835 if (m0->mc_dbi > MAIN_DBI)
1836 i += txn->mt_dbs[MAIN_DBI].md_depth;
1837 /* For puts, roughly factor in the key+data size */
1839 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
1840 i += i; /* double it for good measure */
1843 if (txn->mt_dirty_room > i)
1846 if (!txn->mt_spill_pgs) {
1847 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
1848 if (!txn->mt_spill_pgs)
1851 /* purge deleted slots */
1852 MDB_IDL sl = txn->mt_spill_pgs;
1853 unsigned int num = sl[0];
1855 for (i=1; i<=num; i++) {
1862 /* Preserve pages which may soon be dirtied again */
1863 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
1866 /* Less aggressive spill - we originally spilled the entire dirty list,
1867 * with a few exceptions for cursor pages and DB root pages. But this
1868 * turns out to be a lot of wasted effort because in a large txn many
1869 * of those pages will need to be used again. So now we spill only 1/8th
1870 * of the dirty pages. Testing revealed this to be a good tradeoff,
1871 * better than 1/2, 1/4, or 1/10.
1873 if (need < MDB_IDL_UM_MAX / 8)
1874 need = MDB_IDL_UM_MAX / 8;
1876 /* Save the page IDs of all the pages we're flushing */
1877 /* flush from the tail forward, this saves a lot of shifting later on. */
1878 for (i=dl[0].mid; i && need; i--) {
1879 MDB_ID pn = dl[i].mid << 1;
1881 if (dp->mp_flags & (P_LOOSE|P_KEEP))
1883 /* Can't spill twice, make sure it's not already in a parent's
1886 if (txn->mt_parent) {
1888 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1889 if (tx2->mt_spill_pgs) {
1890 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
1891 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
1892 dp->mp_flags |= P_KEEP;
1900 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
1904 mdb_midl_sort(txn->mt_spill_pgs);
1906 /* Flush the spilled part of dirty list */
1907 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
1910 /* Reset any dirty pages we kept that page_flush didn't see */
1911 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
1914 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
1918 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
1920 mdb_find_oldest(MDB_txn *txn)
1923 txnid_t mr, oldest = txn->mt_txnid - 1;
1924 if (txn->mt_env->me_txns) {
1925 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
1926 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
1937 /** Add a page to the txn's dirty list */
1939 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
1942 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
1944 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1945 insert = mdb_mid2l_append;
1947 insert = mdb_mid2l_insert;
1949 mid.mid = mp->mp_pgno;
1951 rc = insert(txn->mt_u.dirty_list, &mid);
1952 mdb_tassert(txn, rc == 0);
1953 txn->mt_dirty_room--;
1956 /** Allocate page numbers and memory for writing. Maintain me_pglast,
1957 * me_pghead and mt_next_pgno.
1959 * If there are free pages available from older transactions, they
1960 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
1961 * Do not modify the freedB, just merge freeDB records into me_pghead[]
1962 * and move me_pglast to say which records were consumed. Only this
1963 * function can create me_pghead and move me_pglast/mt_next_pgno.
1964 * @param[in] mc cursor A cursor handle identifying the transaction and
1965 * database for which we are allocating.
1966 * @param[in] num the number of pages to allocate.
1967 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
1968 * will always be satisfied by a single contiguous chunk of memory.
1969 * @return 0 on success, non-zero on failure.
1972 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
1974 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
1975 /* Get at most <Max_retries> more freeDB records once me_pghead
1976 * has enough pages. If not enough, use new pages from the map.
1977 * If <Paranoid> and mc is updating the freeDB, only get new
1978 * records if me_pghead is empty. Then the freelist cannot play
1979 * catch-up with itself by growing while trying to save it.
1981 enum { Paranoid = 1, Max_retries = 500 };
1983 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
1985 int rc, retry = num * 60;
1986 MDB_txn *txn = mc->mc_txn;
1987 MDB_env *env = txn->mt_env;
1988 pgno_t pgno, *mop = env->me_pghead;
1989 unsigned i, j, mop_len = mop ? mop[0] : 0, n2 = num-1;
1991 txnid_t oldest = 0, last;
1996 /* If there are any loose pages, just use them */
1997 if (num == 1 && txn->mt_loose_pgs) {
1998 np = txn->mt_loose_pgs;
1999 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
2000 txn->mt_loose_count--;
2001 DPRINTF(("db %d use loose page %"Z"u", DDBI(mc),
2009 /* If our dirty list is already full, we can't do anything */
2010 if (txn->mt_dirty_room == 0) {
2015 for (op = MDB_FIRST;; op = MDB_NEXT) {
2020 /* Seek a big enough contiguous page range. Prefer
2021 * pages at the tail, just truncating the list.
2027 if (mop[i-n2] == pgno+n2)
2034 if (op == MDB_FIRST) { /* 1st iteration */
2035 /* Prepare to fetch more and coalesce */
2036 last = env->me_pglast;
2037 oldest = env->me_pgoldest;
2038 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
2041 key.mv_data = &last; /* will look up last+1 */
2042 key.mv_size = sizeof(last);
2044 if (Paranoid && mc->mc_dbi == FREE_DBI)
2047 if (Paranoid && retry < 0 && mop_len)
2051 /* Do not fetch more if the record will be too recent */
2052 if (oldest <= last) {
2054 oldest = mdb_find_oldest(txn);
2055 env->me_pgoldest = oldest;
2061 rc = mdb_cursor_get(&m2, &key, NULL, op);
2063 if (rc == MDB_NOTFOUND)
2067 last = *(txnid_t*)key.mv_data;
2068 if (oldest <= last) {
2070 oldest = mdb_find_oldest(txn);
2071 env->me_pgoldest = oldest;
2077 np = m2.mc_pg[m2.mc_top];
2078 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
2079 if ((rc = mdb_node_read(txn, leaf, &data)) != MDB_SUCCESS)
2082 idl = (MDB_ID *) data.mv_data;
2085 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
2090 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
2092 mop = env->me_pghead;
2094 env->me_pglast = last;
2096 DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
2097 last, txn->mt_dbs[FREE_DBI].md_root, i));
2099 DPRINTF(("IDL %"Z"u", idl[j]));
2101 /* Merge in descending sorted order */
2102 mdb_midl_xmerge(mop, idl);
2106 /* Use new pages from the map when nothing suitable in the freeDB */
2108 pgno = txn->mt_next_pgno;
2109 if (pgno + num >= env->me_maxpg) {
2110 DPUTS("DB size maxed out");
2116 if (env->me_flags & MDB_WRITEMAP) {
2117 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
2119 if (!(np = mdb_page_malloc(txn, num))) {
2125 mop[0] = mop_len -= num;
2126 /* Move any stragglers down */
2127 for (j = i-num; j < mop_len; )
2128 mop[++j] = mop[++i];
2130 txn->mt_next_pgno = pgno + num;
2133 mdb_page_dirty(txn, np);
2139 txn->mt_flags |= MDB_TXN_ERROR;
2143 /** Copy the used portions of a non-overflow page.
2144 * @param[in] dst page to copy into
2145 * @param[in] src page to copy from
2146 * @param[in] psize size of a page
2149 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2151 enum { Align = sizeof(pgno_t) };
2152 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2154 /* If page isn't full, just copy the used portion. Adjust
2155 * alignment so memcpy may copy words instead of bytes.
2157 if ((unused &= -Align) && !IS_LEAF2(src)) {
2158 upper = (upper + PAGEBASE) & -Align;
2159 memcpy(dst, src, (lower + PAGEBASE + (Align-1)) & -Align);
2160 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2163 memcpy(dst, src, psize - unused);
2167 /** Pull a page off the txn's spill list, if present.
2168 * If a page being referenced was spilled to disk in this txn, bring
2169 * it back and make it dirty/writable again.
2170 * @param[in] txn the transaction handle.
2171 * @param[in] mp the page being referenced. It must not be dirty.
2172 * @param[out] ret the writable page, if any. ret is unchanged if
2173 * mp wasn't spilled.
2176 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2178 MDB_env *env = txn->mt_env;
2181 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2183 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2184 if (!tx2->mt_spill_pgs)
2186 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2187 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2190 if (txn->mt_dirty_room == 0)
2191 return MDB_TXN_FULL;
2192 if (IS_OVERFLOW(mp))
2196 if (env->me_flags & MDB_WRITEMAP) {
2199 np = mdb_page_malloc(txn, num);
2203 memcpy(np, mp, num * env->me_psize);
2205 mdb_page_copy(np, mp, env->me_psize);
2208 /* If in current txn, this page is no longer spilled.
2209 * If it happens to be the last page, truncate the spill list.
2210 * Otherwise mark it as deleted by setting the LSB.
2212 if (x == txn->mt_spill_pgs[0])
2213 txn->mt_spill_pgs[0]--;
2215 txn->mt_spill_pgs[x] |= 1;
2216 } /* otherwise, if belonging to a parent txn, the
2217 * page remains spilled until child commits
2220 mdb_page_dirty(txn, np);
2221 np->mp_flags |= P_DIRTY;
2229 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2230 * @param[in] mc cursor pointing to the page to be touched
2231 * @return 0 on success, non-zero on failure.
2234 mdb_page_touch(MDB_cursor *mc)
2236 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2237 MDB_txn *txn = mc->mc_txn;
2238 MDB_cursor *m2, *m3;
2242 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2243 if (txn->mt_flags & MDB_TXN_SPILLS) {
2245 rc = mdb_page_unspill(txn, mp, &np);
2251 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2252 (rc = mdb_page_alloc(mc, 1, &np)))
2255 DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
2256 mp->mp_pgno, pgno));
2257 mdb_cassert(mc, mp->mp_pgno != pgno);
2258 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2259 /* Update the parent page, if any, to point to the new page */
2261 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2262 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2263 SETPGNO(node, pgno);
2265 mc->mc_db->md_root = pgno;
2267 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2268 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2270 /* If txn has a parent, make sure the page is in our
2274 unsigned x = mdb_mid2l_search(dl, pgno);
2275 if (x <= dl[0].mid && dl[x].mid == pgno) {
2276 if (mp != dl[x].mptr) { /* bad cursor? */
2277 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2278 txn->mt_flags |= MDB_TXN_ERROR;
2279 return MDB_CORRUPTED;
2284 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2286 np = mdb_page_malloc(txn, 1);
2291 rc = mdb_mid2l_insert(dl, &mid);
2292 mdb_cassert(mc, rc == 0);
2297 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2299 np->mp_flags |= P_DIRTY;
2302 /* Adjust cursors pointing to mp */
2303 mc->mc_pg[mc->mc_top] = np;
2304 m2 = txn->mt_cursors[mc->mc_dbi];
2305 if (mc->mc_flags & C_SUB) {
2306 for (; m2; m2=m2->mc_next) {
2307 m3 = &m2->mc_xcursor->mx_cursor;
2308 if (m3->mc_snum < mc->mc_snum) continue;
2309 if (m3->mc_pg[mc->mc_top] == mp)
2310 m3->mc_pg[mc->mc_top] = np;
2313 for (; m2; m2=m2->mc_next) {
2314 if (m2->mc_snum < mc->mc_snum) continue;
2315 if (m2->mc_pg[mc->mc_top] == mp) {
2316 m2->mc_pg[mc->mc_top] = np;
2317 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
2319 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
2321 MDB_node *leaf = NODEPTR(np, mc->mc_ki[mc->mc_top]);
2322 if (!(leaf->mn_flags & F_SUBDATA))
2323 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
2331 txn->mt_flags |= MDB_TXN_ERROR;
2336 mdb_env_sync(MDB_env *env, int force)
2339 if (env->me_flags & MDB_RDONLY)
2341 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2342 if (env->me_flags & MDB_WRITEMAP) {
2343 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2344 ? MS_ASYNC : MS_SYNC;
2345 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
2348 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2352 #ifdef BROKEN_FDATASYNC
2353 if (env->me_flags & MDB_FSYNCONLY) {
2354 if (fsync(env->me_fd))
2358 if (MDB_FDATASYNC(env->me_fd))
2365 /** Back up parent txn's cursors, then grab the originals for tracking */
2367 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2369 MDB_cursor *mc, *bk;
2374 for (i = src->mt_numdbs; --i >= 0; ) {
2375 if ((mc = src->mt_cursors[i]) != NULL) {
2376 size = sizeof(MDB_cursor);
2378 size += sizeof(MDB_xcursor);
2379 for (; mc; mc = bk->mc_next) {
2385 mc->mc_db = &dst->mt_dbs[i];
2386 /* Kill pointers into src - and dst to reduce abuse: The
2387 * user may not use mc until dst ends. Otherwise we'd...
2389 mc->mc_txn = NULL; /* ...set this to dst */
2390 mc->mc_dbflag = NULL; /* ...and &dst->mt_dbflags[i] */
2391 if ((mx = mc->mc_xcursor) != NULL) {
2392 *(MDB_xcursor *)(bk+1) = *mx;
2393 mx->mx_cursor.mc_txn = NULL; /* ...and dst. */
2395 mc->mc_next = dst->mt_cursors[i];
2396 dst->mt_cursors[i] = mc;
2403 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2404 * @param[in] txn the transaction handle.
2405 * @param[in] merge true to keep changes to parent cursors, false to revert.
2406 * @return 0 on success, non-zero on failure.
2409 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2411 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2415 for (i = txn->mt_numdbs; --i >= 0; ) {
2416 for (mc = cursors[i]; mc; mc = next) {
2418 if ((bk = mc->mc_backup) != NULL) {
2420 /* Commit changes to parent txn */
2421 mc->mc_next = bk->mc_next;
2422 mc->mc_backup = bk->mc_backup;
2423 mc->mc_txn = bk->mc_txn;
2424 mc->mc_db = bk->mc_db;
2425 mc->mc_dbflag = bk->mc_dbflag;
2426 if ((mx = mc->mc_xcursor) != NULL)
2427 mx->mx_cursor.mc_txn = bk->mc_txn;
2429 /* Abort nested txn */
2431 if ((mx = mc->mc_xcursor) != NULL)
2432 *mx = *(MDB_xcursor *)(bk+1);
2436 /* Only malloced cursors are permanently tracked. */
2444 #define mdb_txn_reset0(txn, act) mdb_txn_reset0(txn)
2447 mdb_txn_reset0(MDB_txn *txn, const char *act);
2449 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2455 Pidset = F_SETLK, Pidcheck = F_GETLK
2459 /** Set or check a pid lock. Set returns 0 on success.
2460 * Check returns 0 if the process is certainly dead, nonzero if it may
2461 * be alive (the lock exists or an error happened so we do not know).
2463 * On Windows Pidset is a no-op, we merely check for the existence
2464 * of the process with the given pid. On POSIX we use a single byte
2465 * lock on the lockfile, set at an offset equal to the pid.
2468 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2470 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2473 if (op == Pidcheck) {
2474 h = OpenProcess(env->me_pidquery, FALSE, pid);
2475 /* No documented "no such process" code, but other program use this: */
2477 return ErrCode() != ERROR_INVALID_PARAMETER;
2478 /* A process exists until all handles to it close. Has it exited? */
2479 ret = WaitForSingleObject(h, 0) != 0;
2486 struct flock lock_info;
2487 memset(&lock_info, 0, sizeof(lock_info));
2488 lock_info.l_type = F_WRLCK;
2489 lock_info.l_whence = SEEK_SET;
2490 lock_info.l_start = pid;
2491 lock_info.l_len = 1;
2492 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2493 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2495 } else if ((rc = ErrCode()) == EINTR) {
2503 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2504 * @param[in] txn the transaction handle to initialize
2505 * @return 0 on success, non-zero on failure.
2508 mdb_txn_renew0(MDB_txn *txn)
2510 MDB_env *env = txn->mt_env;
2511 MDB_txninfo *ti = env->me_txns;
2513 unsigned int i, nr, flags = txn->mt_flags;
2515 int rc, new_notls = 0;
2517 if ((flags &= MDB_TXN_RDONLY) != 0) {
2519 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2520 txn->mt_txnid = meta->mm_txnid;
2521 txn->mt_u.reader = NULL;
2523 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2524 pthread_getspecific(env->me_txkey);
2526 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2527 return MDB_BAD_RSLOT;
2529 MDB_PID_T pid = env->me_pid;
2530 MDB_THR_T tid = pthread_self();
2532 if (!env->me_live_reader) {
2533 rc = mdb_reader_pid(env, Pidset, pid);
2536 env->me_live_reader = 1;
2540 nr = ti->mti_numreaders;
2541 for (i=0; i<nr; i++)
2542 if (ti->mti_readers[i].mr_pid == 0)
2544 if (i == env->me_maxreaders) {
2545 UNLOCK_MUTEX_R(env);
2546 return MDB_READERS_FULL;
2548 ti->mti_readers[i].mr_pid = pid;
2549 ti->mti_readers[i].mr_tid = tid;
2551 ti->mti_numreaders = ++nr;
2552 /* Save numreaders for un-mutexed mdb_env_close() */
2553 env->me_numreaders = nr;
2554 UNLOCK_MUTEX_R(env);
2556 r = &ti->mti_readers[i];
2557 new_notls = (env->me_flags & MDB_NOTLS);
2558 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2563 do /* LY: Retry on a race, ITS#7970. */
2564 r->mr_txnid = ti->mti_txnid;
2565 while(r->mr_txnid != ti->mti_txnid);
2566 txn->mt_txnid = r->mr_txnid;
2567 txn->mt_u.reader = r;
2568 meta = env->me_metas[txn->mt_txnid & 1];
2570 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
2575 txn->mt_txnid = ti->mti_txnid;
2576 meta = env->me_metas[txn->mt_txnid & 1];
2578 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2579 txn->mt_txnid = meta->mm_txnid;
2583 if (txn->mt_txnid == mdb_debug_start)
2586 txn->mt_child = NULL;
2587 txn->mt_loose_pgs = NULL;
2588 txn->mt_loose_count = 0;
2589 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2590 txn->mt_u.dirty_list = env->me_dirty_list;
2591 txn->mt_u.dirty_list[0].mid = 0;
2592 txn->mt_free_pgs = env->me_free_pgs;
2593 txn->mt_free_pgs[0] = 0;
2594 txn->mt_spill_pgs = NULL;
2596 memcpy(txn->mt_dbiseqs, env->me_dbiseqs, env->me_maxdbs * sizeof(unsigned int));
2599 /* Copy the DB info and flags */
2600 memcpy(txn->mt_dbs, meta->mm_dbs, 2 * sizeof(MDB_db));
2602 /* Moved to here to avoid a data race in read TXNs */
2603 txn->mt_next_pgno = meta->mm_last_pg+1;
2605 txn->mt_flags = flags;
2608 txn->mt_numdbs = env->me_numdbs;
2609 for (i=2; i<txn->mt_numdbs; i++) {
2610 x = env->me_dbflags[i];
2611 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2612 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_STALE : 0;
2614 txn->mt_dbflags[0] = txn->mt_dbflags[1] = DB_VALID;
2616 if (env->me_maxpg < txn->mt_next_pgno) {
2617 mdb_txn_reset0(txn, "renew0-mapfail");
2619 txn->mt_u.reader->mr_pid = 0;
2620 txn->mt_u.reader = NULL;
2622 return MDB_MAP_RESIZED;
2629 mdb_txn_renew(MDB_txn *txn)
2633 if (!txn || txn->mt_dbxs) /* A reset txn has mt_dbxs==NULL */
2636 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
2637 DPUTS("environment had fatal error, must shutdown!");
2641 rc = mdb_txn_renew0(txn);
2642 if (rc == MDB_SUCCESS) {
2643 DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2644 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2645 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2651 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2655 int rc, size, tsize = sizeof(MDB_txn);
2657 if (env->me_flags & MDB_FATAL_ERROR) {
2658 DPUTS("environment had fatal error, must shutdown!");
2661 if ((env->me_flags & MDB_RDONLY) && !(flags & MDB_RDONLY))
2664 /* Nested transactions: Max 1 child, write txns only, no writemap */
2665 if (parent->mt_child ||
2666 (flags & MDB_RDONLY) ||
2667 (parent->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR)) ||
2668 (env->me_flags & MDB_WRITEMAP))
2670 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
2672 tsize = sizeof(MDB_ntxn);
2675 if (!(flags & MDB_RDONLY)) {
2677 txn = env->me_txn0; /* just reuse preallocated write txn */
2680 /* child txns use own copy of cursors */
2681 size += env->me_maxdbs * sizeof(MDB_cursor *);
2683 size += env->me_maxdbs * (sizeof(MDB_db)+1);
2685 if ((txn = calloc(1, size)) == NULL) {
2686 DPRINTF(("calloc: %s", strerror(errno)));
2689 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2690 if (flags & MDB_RDONLY) {
2691 txn->mt_flags |= MDB_TXN_RDONLY;
2692 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
2693 txn->mt_dbiseqs = env->me_dbiseqs;
2695 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2697 txn->mt_dbiseqs = parent->mt_dbiseqs;
2698 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
2700 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
2701 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
2709 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2710 if (!txn->mt_u.dirty_list ||
2711 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2713 free(txn->mt_u.dirty_list);
2717 txn->mt_txnid = parent->mt_txnid;
2718 txn->mt_dirty_room = parent->mt_dirty_room;
2719 txn->mt_u.dirty_list[0].mid = 0;
2720 txn->mt_spill_pgs = NULL;
2721 txn->mt_next_pgno = parent->mt_next_pgno;
2722 parent->mt_child = txn;
2723 txn->mt_parent = parent;
2724 txn->mt_numdbs = parent->mt_numdbs;
2725 txn->mt_flags = parent->mt_flags;
2726 txn->mt_dbxs = parent->mt_dbxs;
2727 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2728 /* Copy parent's mt_dbflags, but clear DB_NEW */
2729 for (i=0; i<txn->mt_numdbs; i++)
2730 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2732 ntxn = (MDB_ntxn *)txn;
2733 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2734 if (env->me_pghead) {
2735 size = MDB_IDL_SIZEOF(env->me_pghead);
2736 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2738 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2743 rc = mdb_cursor_shadow(parent, txn);
2745 mdb_txn_reset0(txn, "beginchild-fail");
2747 rc = mdb_txn_renew0(txn);
2750 if (txn != env->me_txn0)
2754 DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2755 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2756 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
2763 mdb_txn_env(MDB_txn *txn)
2765 if(!txn) return NULL;
2769 /** Export or close DBI handles opened in this txn. */
2771 mdb_dbis_update(MDB_txn *txn, int keep)
2774 MDB_dbi n = txn->mt_numdbs;
2775 MDB_env *env = txn->mt_env;
2776 unsigned char *tdbflags = txn->mt_dbflags;
2778 for (i = n; --i >= 2;) {
2779 if (tdbflags[i] & DB_NEW) {
2781 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2783 char *ptr = env->me_dbxs[i].md_name.mv_data;
2785 env->me_dbxs[i].md_name.mv_data = NULL;
2786 env->me_dbxs[i].md_name.mv_size = 0;
2787 env->me_dbflags[i] = 0;
2788 env->me_dbiseqs[i]++;
2794 if (keep && env->me_numdbs < n)
2798 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
2799 * May be called twice for readonly txns: First reset it, then abort.
2800 * @param[in] txn the transaction handle to reset
2801 * @param[in] act why the transaction is being reset
2804 mdb_txn_reset0(MDB_txn *txn, const char *act)
2806 MDB_env *env = txn->mt_env;
2808 /* Close any DBI handles opened in this txn */
2809 mdb_dbis_update(txn, 0);
2811 DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2812 act, txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2813 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
2815 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2816 if (txn->mt_u.reader) {
2817 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2818 if (!(env->me_flags & MDB_NOTLS))
2819 txn->mt_u.reader = NULL; /* txn does not own reader */
2821 txn->mt_numdbs = 0; /* close nothing if called again */
2822 txn->mt_dbxs = NULL; /* mark txn as reset */
2824 pgno_t *pghead = env->me_pghead;
2826 mdb_cursors_close(txn, 0);
2827 if (!(env->me_flags & MDB_WRITEMAP)) {
2828 mdb_dlist_free(txn);
2831 if (!txn->mt_parent) {
2832 mdb_midl_shrink(&txn->mt_free_pgs);
2833 env->me_free_pgs = txn->mt_free_pgs;
2835 env->me_pghead = NULL;
2839 /* The writer mutex was locked in mdb_txn_begin. */
2841 UNLOCK_MUTEX_W(env);
2843 txn->mt_parent->mt_child = NULL;
2844 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2845 mdb_midl_free(txn->mt_free_pgs);
2846 mdb_midl_free(txn->mt_spill_pgs);
2847 free(txn->mt_u.dirty_list);
2850 mdb_midl_free(pghead);
2855 mdb_txn_reset(MDB_txn *txn)
2860 /* This call is only valid for read-only txns */
2861 if (!(txn->mt_flags & MDB_TXN_RDONLY))
2864 mdb_txn_reset0(txn, "reset");
2868 mdb_txn_abort(MDB_txn *txn)
2874 mdb_txn_abort(txn->mt_child);
2876 mdb_txn_reset0(txn, "abort");
2877 /* Free reader slot tied to this txn (if MDB_NOTLS && writable FS) */
2878 if ((txn->mt_flags & MDB_TXN_RDONLY) && txn->mt_u.reader)
2879 txn->mt_u.reader->mr_pid = 0;
2881 if (txn != txn->mt_env->me_txn0)
2885 /** Save the freelist as of this transaction to the freeDB.
2886 * This changes the freelist. Keep trying until it stabilizes.
2889 mdb_freelist_save(MDB_txn *txn)
2891 /* env->me_pghead[] can grow and shrink during this call.
2892 * env->me_pglast and txn->mt_free_pgs[] can only grow.
2893 * Page numbers cannot disappear from txn->mt_free_pgs[].
2896 MDB_env *env = txn->mt_env;
2897 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
2898 txnid_t pglast = 0, head_id = 0;
2899 pgno_t freecnt = 0, *free_pgs, *mop;
2900 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
2902 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
2904 if (env->me_pghead) {
2905 /* Make sure first page of freeDB is touched and on freelist */
2906 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
2907 if (rc && rc != MDB_NOTFOUND)
2911 if (!env->me_pghead && txn->mt_loose_pgs) {
2912 /* Put loose page numbers in mt_free_pgs, since
2913 * we may be unable to return them to me_pghead.
2915 MDB_page *mp = txn->mt_loose_pgs;
2916 if ((rc = mdb_midl_need(&txn->mt_free_pgs, txn->mt_loose_count)) != 0)
2918 for (; mp; mp = NEXT_LOOSE_PAGE(mp))
2919 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2920 txn->mt_loose_pgs = NULL;
2921 txn->mt_loose_count = 0;
2924 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
2925 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
2926 ? SSIZE_MAX : maxfree_1pg;
2929 /* Come back here after each Put() in case freelist changed */
2934 /* If using records from freeDB which we have not yet
2935 * deleted, delete them and any we reserved for me_pghead.
2937 while (pglast < env->me_pglast) {
2938 rc = mdb_cursor_first(&mc, &key, NULL);
2941 pglast = head_id = *(txnid_t *)key.mv_data;
2942 total_room = head_room = 0;
2943 mdb_tassert(txn, pglast <= env->me_pglast);
2944 rc = mdb_cursor_del(&mc, 0);
2949 /* Save the IDL of pages freed by this txn, to a single record */
2950 if (freecnt < txn->mt_free_pgs[0]) {
2952 /* Make sure last page of freeDB is touched and on freelist */
2953 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
2954 if (rc && rc != MDB_NOTFOUND)
2957 free_pgs = txn->mt_free_pgs;
2958 /* Write to last page of freeDB */
2959 key.mv_size = sizeof(txn->mt_txnid);
2960 key.mv_data = &txn->mt_txnid;
2962 freecnt = free_pgs[0];
2963 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
2964 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2967 /* Retry if mt_free_pgs[] grew during the Put() */
2968 free_pgs = txn->mt_free_pgs;
2969 } while (freecnt < free_pgs[0]);
2970 mdb_midl_sort(free_pgs);
2971 memcpy(data.mv_data, free_pgs, data.mv_size);
2974 unsigned int i = free_pgs[0];
2975 DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
2976 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
2978 DPRINTF(("IDL %"Z"u", free_pgs[i]));
2984 mop = env->me_pghead;
2985 mop_len = (mop ? mop[0] : 0) + txn->mt_loose_count;
2987 /* Reserve records for me_pghead[]. Split it if multi-page,
2988 * to avoid searching freeDB for a page range. Use keys in
2989 * range [1,me_pglast]: Smaller than txnid of oldest reader.
2991 if (total_room >= mop_len) {
2992 if (total_room == mop_len || --more < 0)
2994 } else if (head_room >= maxfree_1pg && head_id > 1) {
2995 /* Keep current record (overflow page), add a new one */
2999 /* (Re)write {key = head_id, IDL length = head_room} */
3000 total_room -= head_room;
3001 head_room = mop_len - total_room;
3002 if (head_room > maxfree_1pg && head_id > 1) {
3003 /* Overflow multi-page for part of me_pghead */
3004 head_room /= head_id; /* amortize page sizes */
3005 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
3006 } else if (head_room < 0) {
3007 /* Rare case, not bothering to delete this record */
3010 key.mv_size = sizeof(head_id);
3011 key.mv_data = &head_id;
3012 data.mv_size = (head_room + 1) * sizeof(pgno_t);
3013 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3016 /* IDL is initially empty, zero out at least the length */
3017 pgs = (pgno_t *)data.mv_data;
3018 j = head_room > clean_limit ? head_room : 0;
3022 total_room += head_room;
3025 /* Return loose page numbers to me_pghead, though usually none are
3026 * left at this point. The pages themselves remain in dirty_list.
3028 if (txn->mt_loose_pgs) {
3029 MDB_page *mp = txn->mt_loose_pgs;
3030 unsigned count = txn->mt_loose_count;
3032 /* Room for loose pages + temp IDL with same */
3033 if ((rc = mdb_midl_need(&env->me_pghead, 2*count+1)) != 0)
3035 mop = env->me_pghead;
3036 loose = mop + MDB_IDL_ALLOCLEN(mop) - count;
3037 for (count = 0; mp; mp = NEXT_LOOSE_PAGE(mp))
3038 loose[ ++count ] = mp->mp_pgno;
3040 mdb_midl_sort(loose);
3041 mdb_midl_xmerge(mop, loose);
3042 txn->mt_loose_pgs = NULL;
3043 txn->mt_loose_count = 0;
3047 /* Fill in the reserved me_pghead records */
3053 rc = mdb_cursor_first(&mc, &key, &data);
3054 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
3055 txnid_t id = *(txnid_t *)key.mv_data;
3056 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
3059 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
3061 if (len > mop_len) {
3063 data.mv_size = (len + 1) * sizeof(MDB_ID);
3065 data.mv_data = mop -= len;
3068 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
3070 if (rc || !(mop_len -= len))
3077 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
3078 * @param[in] txn the transaction that's being committed
3079 * @param[in] keep number of initial pages in dirty_list to keep dirty.
3080 * @return 0 on success, non-zero on failure.
3083 mdb_page_flush(MDB_txn *txn, int keep)
3085 MDB_env *env = txn->mt_env;
3086 MDB_ID2L dl = txn->mt_u.dirty_list;
3087 unsigned psize = env->me_psize, j;
3088 int i, pagecount = dl[0].mid, rc;
3089 size_t size = 0, pos = 0;
3091 MDB_page *dp = NULL;
3095 struct iovec iov[MDB_COMMIT_PAGES];
3096 ssize_t wpos = 0, wsize = 0, wres;
3097 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
3103 if (env->me_flags & MDB_WRITEMAP) {
3104 /* Clear dirty flags */
3105 while (++i <= pagecount) {
3107 /* Don't flush this page yet */
3108 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3109 dp->mp_flags &= ~P_KEEP;
3113 dp->mp_flags &= ~P_DIRTY;
3118 /* Write the pages */
3120 if (++i <= pagecount) {
3122 /* Don't flush this page yet */
3123 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3124 dp->mp_flags &= ~P_KEEP;
3129 /* clear dirty flag */
3130 dp->mp_flags &= ~P_DIRTY;
3133 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
3138 /* Windows actually supports scatter/gather I/O, but only on
3139 * unbuffered file handles. Since we're relying on the OS page
3140 * cache for all our data, that's self-defeating. So we just
3141 * write pages one at a time. We use the ov structure to set
3142 * the write offset, to at least save the overhead of a Seek
3145 DPRINTF(("committing page %"Z"u", pgno));
3146 memset(&ov, 0, sizeof(ov));
3147 ov.Offset = pos & 0xffffffff;
3148 ov.OffsetHigh = pos >> 16 >> 16;
3149 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
3151 DPRINTF(("WriteFile: %d", rc));
3155 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
3156 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
3159 /* Write previous page(s) */
3160 #ifdef MDB_USE_PWRITEV
3161 wres = pwritev(env->me_fd, iov, n, wpos);
3164 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
3167 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
3171 DPRINTF(("lseek: %s", strerror(rc)));
3174 wres = writev(env->me_fd, iov, n);
3177 if (wres != wsize) {
3182 DPRINTF(("Write error: %s", strerror(rc)));
3184 rc = EIO; /* TODO: Use which error code? */
3185 DPUTS("short write, filesystem full?");
3196 DPRINTF(("committing page %"Z"u", pgno));
3197 next_pos = pos + size;
3198 iov[n].iov_len = size;
3199 iov[n].iov_base = (char *)dp;
3205 /* MIPS has cache coherency issues, this is a no-op everywhere else
3206 * Note: for any size >= on-chip cache size, entire on-chip cache is
3209 CACHEFLUSH(env->me_map, txn->mt_next_pgno * env->me_psize, DCACHE);
3211 for (i = keep; ++i <= pagecount; ) {
3213 /* This is a page we skipped above */
3216 dl[j].mid = dp->mp_pgno;
3219 mdb_dpage_free(env, dp);
3224 txn->mt_dirty_room += i - j;
3230 mdb_txn_commit(MDB_txn *txn)
3236 if (txn == NULL || txn->mt_env == NULL)
3239 if (txn->mt_child) {
3240 rc = mdb_txn_commit(txn->mt_child);
3241 txn->mt_child = NULL;
3248 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3249 mdb_dbis_update(txn, 1);
3250 txn->mt_numdbs = 2; /* so txn_abort() doesn't close any new handles */
3255 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
3256 DPUTS("error flag is set, can't commit");
3258 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3263 if (txn->mt_parent) {
3264 MDB_txn *parent = txn->mt_parent;
3268 unsigned x, y, len, ps_len;
3270 /* Append our free list to parent's */
3271 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3274 mdb_midl_free(txn->mt_free_pgs);
3275 /* Failures after this must either undo the changes
3276 * to the parent or set MDB_TXN_ERROR in the parent.
3279 parent->mt_next_pgno = txn->mt_next_pgno;
3280 parent->mt_flags = txn->mt_flags;
3282 /* Merge our cursors into parent's and close them */
3283 mdb_cursors_close(txn, 1);
3285 /* Update parent's DB table. */
3286 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3287 parent->mt_numdbs = txn->mt_numdbs;
3288 parent->mt_dbflags[0] = txn->mt_dbflags[0];
3289 parent->mt_dbflags[1] = txn->mt_dbflags[1];
3290 for (i=2; i<txn->mt_numdbs; i++) {
3291 /* preserve parent's DB_NEW status */
3292 x = parent->mt_dbflags[i] & DB_NEW;
3293 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3296 dst = parent->mt_u.dirty_list;
3297 src = txn->mt_u.dirty_list;
3298 /* Remove anything in our dirty list from parent's spill list */
3299 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3301 pspill[0] = (pgno_t)-1;
3302 /* Mark our dirty pages as deleted in parent spill list */
3303 for (i=0, len=src[0].mid; ++i <= len; ) {
3304 MDB_ID pn = src[i].mid << 1;
3305 while (pn > pspill[x])
3307 if (pn == pspill[x]) {
3312 /* Squash deleted pagenums if we deleted any */
3313 for (x=y; ++x <= ps_len; )
3314 if (!(pspill[x] & 1))
3315 pspill[++y] = pspill[x];
3319 /* Find len = length of merging our dirty list with parent's */
3321 dst[0].mid = 0; /* simplify loops */
3322 if (parent->mt_parent) {
3323 len = x + src[0].mid;
3324 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3325 for (i = x; y && i; y--) {
3326 pgno_t yp = src[y].mid;
3327 while (yp < dst[i].mid)
3329 if (yp == dst[i].mid) {
3334 } else { /* Simplify the above for single-ancestor case */
3335 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3337 /* Merge our dirty list with parent's */
3339 for (i = len; y; dst[i--] = src[y--]) {
3340 pgno_t yp = src[y].mid;
3341 while (yp < dst[x].mid)
3342 dst[i--] = dst[x--];
3343 if (yp == dst[x].mid)
3344 free(dst[x--].mptr);
3346 mdb_tassert(txn, i == x);
3348 free(txn->mt_u.dirty_list);
3349 parent->mt_dirty_room = txn->mt_dirty_room;
3350 if (txn->mt_spill_pgs) {
3351 if (parent->mt_spill_pgs) {
3352 /* TODO: Prevent failure here, so parent does not fail */
3353 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3355 parent->mt_flags |= MDB_TXN_ERROR;
3356 mdb_midl_free(txn->mt_spill_pgs);
3357 mdb_midl_sort(parent->mt_spill_pgs);
3359 parent->mt_spill_pgs = txn->mt_spill_pgs;
3363 /* Append our loose page list to parent's */
3364 for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(lp))
3366 *lp = txn->mt_loose_pgs;
3367 parent->mt_loose_count += txn->mt_loose_count;
3369 parent->mt_child = NULL;
3370 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3375 if (txn != env->me_txn) {
3376 DPUTS("attempt to commit unknown transaction");
3381 mdb_cursors_close(txn, 0);
3383 if (!txn->mt_u.dirty_list[0].mid &&
3384 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
3387 DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
3388 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3390 /* Update DB root pointers */
3391 if (txn->mt_numdbs > 2) {
3395 data.mv_size = sizeof(MDB_db);
3397 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3398 for (i = 2; i < txn->mt_numdbs; i++) {
3399 if (txn->mt_dbflags[i] & DB_DIRTY) {
3400 if (TXN_DBI_CHANGED(txn, i)) {
3404 data.mv_data = &txn->mt_dbs[i];
3405 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data,
3413 rc = mdb_freelist_save(txn);
3417 mdb_midl_free(env->me_pghead);
3418 env->me_pghead = NULL;
3419 mdb_midl_shrink(&txn->mt_free_pgs);
3420 env->me_free_pgs = txn->mt_free_pgs;
3426 if ((rc = mdb_page_flush(txn, 0)) ||
3427 (rc = mdb_env_sync(env, 0)) ||
3428 (rc = mdb_env_write_meta(txn)))
3431 /* Free P_LOOSE pages left behind in dirty_list */
3432 if (!(env->me_flags & MDB_WRITEMAP))
3433 mdb_dlist_free(txn);
3438 mdb_dbis_update(txn, 1);
3441 UNLOCK_MUTEX_W(env);
3442 if (txn != env->me_txn0)
3452 /** Read the environment parameters of a DB environment before
3453 * mapping it into memory.
3454 * @param[in] env the environment handle
3455 * @param[out] meta address of where to store the meta information
3456 * @return 0 on success, non-zero on failure.
3459 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3465 enum { Size = sizeof(pbuf) };
3467 /* We don't know the page size yet, so use a minimum value.
3468 * Read both meta pages so we can use the latest one.
3471 for (i=off=0; i<2; i++, off = meta->mm_psize) {
3475 memset(&ov, 0, sizeof(ov));
3477 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3478 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3481 rc = pread(env->me_fd, &pbuf, Size, off);
3484 if (rc == 0 && off == 0)
3486 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3487 DPRINTF(("read: %s", mdb_strerror(rc)));
3491 p = (MDB_page *)&pbuf;
3493 if (!F_ISSET(p->mp_flags, P_META)) {
3494 DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
3499 if (m->mm_magic != MDB_MAGIC) {
3500 DPUTS("meta has invalid magic");
3504 if (m->mm_version != MDB_DATA_VERSION) {
3505 DPRINTF(("database is version %u, expected version %u",
3506 m->mm_version, MDB_DATA_VERSION));
3507 return MDB_VERSION_MISMATCH;
3510 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3516 /** Fill in most of the zeroed #MDB_meta for an empty database environment */
3518 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
3520 meta->mm_magic = MDB_MAGIC;
3521 meta->mm_version = MDB_DATA_VERSION;
3522 meta->mm_mapsize = env->me_mapsize;
3523 meta->mm_psize = env->me_psize;
3524 meta->mm_last_pg = 1;
3525 meta->mm_flags = env->me_flags & 0xffff;
3526 meta->mm_flags |= MDB_INTEGERKEY;
3527 meta->mm_dbs[0].md_root = P_INVALID;
3528 meta->mm_dbs[1].md_root = P_INVALID;
3531 /** Write the environment parameters of a freshly created DB environment.
3532 * @param[in] env the environment handle
3533 * @param[in] meta the #MDB_meta to write
3534 * @return 0 on success, non-zero on failure.
3537 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3545 memset(&ov, 0, sizeof(ov));
3546 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3548 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3551 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3552 len = pwrite(fd, ptr, size, pos); \
3553 if (len == -1 && ErrCode() == EINTR) continue; \
3554 rc = (len >= 0); break; } while(1)
3557 DPUTS("writing new meta page");
3559 psize = env->me_psize;
3561 p = calloc(2, psize);
3566 p->mp_flags = P_META;
3567 *(MDB_meta *)METADATA(p) = *meta;
3569 q = (MDB_page *)((char *)p + psize);
3571 q->mp_flags = P_META;
3572 *(MDB_meta *)METADATA(q) = *meta;
3574 DO_PWRITE(rc, env->me_fd, p, psize * 2, len, 0);
3577 else if ((unsigned) len == psize * 2)
3585 /** Update the environment info to commit a transaction.
3586 * @param[in] txn the transaction that's being committed
3587 * @return 0 on success, non-zero on failure.
3590 mdb_env_write_meta(MDB_txn *txn)
3593 MDB_meta meta, metab, *mp;
3596 int rc, len, toggle;
3605 toggle = txn->mt_txnid & 1;
3606 DPRINTF(("writing meta page %d for root page %"Z"u",
3607 toggle, txn->mt_dbs[MAIN_DBI].md_root));
3610 mp = env->me_metas[toggle];
3611 mapsize = env->me_metas[toggle ^ 1]->mm_mapsize;
3612 /* Persist any increases of mapsize config */
3613 if (mapsize < env->me_mapsize)
3614 mapsize = env->me_mapsize;
3616 if (env->me_flags & MDB_WRITEMAP) {
3617 mp->mm_mapsize = mapsize;
3618 mp->mm_dbs[0] = txn->mt_dbs[0];
3619 mp->mm_dbs[1] = txn->mt_dbs[1];
3620 mp->mm_last_pg = txn->mt_next_pgno - 1;
3621 mp->mm_txnid = txn->mt_txnid;
3622 if (!(env->me_flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3623 unsigned meta_size = env->me_psize;
3624 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3627 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
3628 if (meta_size < env->me_os_psize)
3629 meta_size += meta_size;
3634 if (MDB_MSYNC(ptr, meta_size, rc)) {
3641 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
3642 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
3644 meta.mm_mapsize = mapsize;
3645 meta.mm_dbs[0] = txn->mt_dbs[0];
3646 meta.mm_dbs[1] = txn->mt_dbs[1];
3647 meta.mm_last_pg = txn->mt_next_pgno - 1;
3648 meta.mm_txnid = txn->mt_txnid;
3650 off = offsetof(MDB_meta, mm_mapsize);
3651 ptr = (char *)&meta + off;
3652 len = sizeof(MDB_meta) - off;
3654 off += env->me_psize;
3657 /* Write to the SYNC fd */
3658 mfd = env->me_flags & (MDB_NOSYNC|MDB_NOMETASYNC) ?
3659 env->me_fd : env->me_mfd;
3662 memset(&ov, 0, sizeof(ov));
3664 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3669 rc = pwrite(mfd, ptr, len, off);
3672 rc = rc < 0 ? ErrCode() : EIO;
3677 DPUTS("write failed, disk error?");
3678 /* On a failure, the pagecache still contains the new data.
3679 * Write some old data back, to prevent it from being used.
3680 * Use the non-SYNC fd; we know it will fail anyway.
3682 meta.mm_last_pg = metab.mm_last_pg;
3683 meta.mm_txnid = metab.mm_txnid;
3685 memset(&ov, 0, sizeof(ov));
3687 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3689 r2 = pwrite(env->me_fd, ptr, len, off);
3690 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
3693 env->me_flags |= MDB_FATAL_ERROR;
3696 /* MIPS has cache coherency issues, this is a no-op everywhere else */
3697 CACHEFLUSH(env->me_map + off, len, DCACHE);
3699 /* Memory ordering issues are irrelevant; since the entire writer
3700 * is wrapped by wmutex, all of these changes will become visible
3701 * after the wmutex is unlocked. Since the DB is multi-version,
3702 * readers will get consistent data regardless of how fresh or
3703 * how stale their view of these values is.
3706 env->me_txns->mti_txnid = txn->mt_txnid;
3711 /** Check both meta pages to see which one is newer.
3712 * @param[in] env the environment handle
3713 * @return meta toggle (0 or 1).
3716 mdb_env_pick_meta(const MDB_env *env)
3718 return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
3722 mdb_env_create(MDB_env **env)
3726 e = calloc(1, sizeof(MDB_env));
3730 e->me_maxreaders = DEFAULT_READERS;
3731 e->me_maxdbs = e->me_numdbs = 2;
3732 e->me_fd = INVALID_HANDLE_VALUE;
3733 e->me_lfd = INVALID_HANDLE_VALUE;
3734 e->me_mfd = INVALID_HANDLE_VALUE;
3735 #ifdef MDB_USE_POSIX_SEM
3736 e->me_rmutex = SEM_FAILED;
3737 e->me_wmutex = SEM_FAILED;
3739 e->me_pid = getpid();
3740 GET_PAGESIZE(e->me_os_psize);
3741 VGMEMP_CREATE(e,0,0);
3747 mdb_env_map(MDB_env *env, void *addr)
3750 unsigned int flags = env->me_flags;
3754 LONG sizelo, sizehi;
3757 if (flags & MDB_RDONLY) {
3758 /* Don't set explicit map size, use whatever exists */
3763 msize = env->me_mapsize;
3764 sizelo = msize & 0xffffffff;
3765 sizehi = msize >> 16 >> 16; /* only needed on Win64 */
3767 /* Windows won't create mappings for zero length files.
3768 * and won't map more than the file size.
3769 * Just set the maxsize right now.
3771 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3772 || !SetEndOfFile(env->me_fd)
3773 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3777 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3778 PAGE_READWRITE : PAGE_READONLY,
3779 sizehi, sizelo, NULL);
3782 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3783 FILE_MAP_WRITE : FILE_MAP_READ,
3785 rc = env->me_map ? 0 : ErrCode();
3790 int prot = PROT_READ;
3791 if (flags & MDB_WRITEMAP) {
3793 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3796 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
3798 if (env->me_map == MAP_FAILED) {
3803 if (flags & MDB_NORDAHEAD) {
3804 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3806 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3808 #ifdef POSIX_MADV_RANDOM
3809 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3810 #endif /* POSIX_MADV_RANDOM */
3811 #endif /* MADV_RANDOM */
3815 /* Can happen because the address argument to mmap() is just a
3816 * hint. mmap() can pick another, e.g. if the range is in use.
3817 * The MAP_FIXED flag would prevent that, but then mmap could
3818 * instead unmap existing pages to make room for the new map.
3820 if (addr && env->me_map != addr)
3821 return EBUSY; /* TODO: Make a new MDB_* error code? */
3823 p = (MDB_page *)env->me_map;
3824 env->me_metas[0] = METADATA(p);
3825 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
3831 mdb_env_set_mapsize(MDB_env *env, size_t size)
3833 /* If env is already open, caller is responsible for making
3834 * sure there are no active txns.
3842 meta = env->me_metas[mdb_env_pick_meta(env)];
3844 size = meta->mm_mapsize;
3846 /* Silently round up to minimum if the size is too small */
3847 size_t minsize = (meta->mm_last_pg + 1) * env->me_psize;
3851 munmap(env->me_map, env->me_mapsize);
3852 env->me_mapsize = size;
3853 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
3854 rc = mdb_env_map(env, old);
3858 env->me_mapsize = size;
3860 env->me_maxpg = env->me_mapsize / env->me_psize;
3865 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
3869 env->me_maxdbs = dbs + 2; /* Named databases + main and free DB */
3874 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
3876 if (env->me_map || readers < 1)
3878 env->me_maxreaders = readers;
3883 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
3885 if (!env || !readers)
3887 *readers = env->me_maxreaders;
3892 mdb_fsize(HANDLE fd, size_t *size)
3895 LARGE_INTEGER fsize;
3897 if (!GetFileSizeEx(fd, &fsize))
3900 *size = fsize.QuadPart;
3912 #ifdef BROKEN_FDATASYNC
3913 #include <sys/utsname.h>
3914 #include <sys/vfs.h>
3917 /** Further setup required for opening an LMDB environment
3920 mdb_env_open2(MDB_env *env)
3922 unsigned int flags = env->me_flags;
3923 int i, newenv = 0, rc;
3927 /* See if we should use QueryLimited */
3929 if ((rc & 0xff) > 5)
3930 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
3932 env->me_pidquery = PROCESS_QUERY_INFORMATION;
3934 #ifdef BROKEN_FDATASYNC
3935 /* ext3/ext4 fdatasync is broken on some older Linux kernels.
3936 * https://lkml.org/lkml/2012/9/3/83
3937 * Kernels after 3.6-rc6 are known good.
3938 * https://lkml.org/lkml/2012/9/10/556
3939 * See if the DB is on ext3/ext4, then check for new enough kernel
3940 * Kernels 2.6.32.60, 2.6.34.15, 3.2.30, and 3.5.4 are also known
3945 fstatfs(env->me_fd, &st);
3946 while (st.f_type == 0xEF53) {
3950 if (uts.release[0] < '3') {
3951 if (!strncmp(uts.release, "2.6.32.", 7)) {
3952 i = atoi(uts.release+7);
3954 break; /* 2.6.32.60 and newer is OK */
3955 } else if (!strncmp(uts.release, "2.6.34.", 7)) {
3956 i = atoi(uts.release+7);
3958 break; /* 2.6.34.15 and newer is OK */
3960 } else if (uts.release[0] == '3') {
3961 i = atoi(uts.release+2);
3963 break; /* 3.6 and newer is OK */
3965 i = atoi(uts.release+4);
3967 break; /* 3.5.4 and newer is OK */
3968 } else if (i == 2) {
3969 i = atoi(uts.release+4);
3971 break; /* 3.2.30 and newer is OK */
3973 } else { /* 4.x and newer is OK */
3976 env->me_flags |= MDB_FSYNCONLY;
3982 if ((i = mdb_env_read_header(env, &meta)) != 0) {
3985 DPUTS("new mdbenv");
3987 env->me_psize = env->me_os_psize;
3988 if (env->me_psize > MAX_PAGESIZE)
3989 env->me_psize = MAX_PAGESIZE;
3990 memset(&meta, 0, sizeof(meta));
3991 mdb_env_init_meta0(env, &meta);
3992 meta.mm_mapsize = DEFAULT_MAPSIZE;
3994 env->me_psize = meta.mm_psize;
3997 /* Was a mapsize configured? */
3998 if (!env->me_mapsize) {
3999 env->me_mapsize = meta.mm_mapsize;
4002 /* Make sure mapsize >= committed data size. Even when using
4003 * mm_mapsize, which could be broken in old files (ITS#7789).
4005 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
4006 if (env->me_mapsize < minsize)
4007 env->me_mapsize = minsize;
4009 meta.mm_mapsize = env->me_mapsize;
4011 if (newenv && !(flags & MDB_FIXEDMAP)) {
4012 /* mdb_env_map() may grow the datafile. Write the metapages
4013 * first, so the file will be valid if initialization fails.
4014 * Except with FIXEDMAP, since we do not yet know mm_address.
4015 * We could fill in mm_address later, but then a different
4016 * program might end up doing that - one with a memory layout
4017 * and map address which does not suit the main program.
4019 rc = mdb_env_init_meta(env, &meta);
4025 rc = mdb_env_map(env, (flags & MDB_FIXEDMAP) ? meta.mm_address : NULL);
4030 if (flags & MDB_FIXEDMAP)
4031 meta.mm_address = env->me_map;
4032 i = mdb_env_init_meta(env, &meta);
4033 if (i != MDB_SUCCESS) {
4038 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
4039 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
4041 #if !(MDB_MAXKEYSIZE)
4042 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
4044 env->me_maxpg = env->me_mapsize / env->me_psize;
4048 int toggle = mdb_env_pick_meta(env);
4049 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
4051 DPRINTF(("opened database version %u, pagesize %u",
4052 env->me_metas[0]->mm_version, env->me_psize));
4053 DPRINTF(("using meta page %d", toggle));
4054 DPRINTF(("depth: %u", db->md_depth));
4055 DPRINTF(("entries: %"Z"u", db->md_entries));
4056 DPRINTF(("branch pages: %"Z"u", db->md_branch_pages));
4057 DPRINTF(("leaf pages: %"Z"u", db->md_leaf_pages));
4058 DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
4059 DPRINTF(("root: %"Z"u", db->md_root));
4067 /** Release a reader thread's slot in the reader lock table.
4068 * This function is called automatically when a thread exits.
4069 * @param[in] ptr This points to the slot in the reader lock table.
4072 mdb_env_reader_dest(void *ptr)
4074 MDB_reader *reader = ptr;
4080 /** Junk for arranging thread-specific callbacks on Windows. This is
4081 * necessarily platform and compiler-specific. Windows supports up
4082 * to 1088 keys. Let's assume nobody opens more than 64 environments
4083 * in a single process, for now. They can override this if needed.
4085 #ifndef MAX_TLS_KEYS
4086 #define MAX_TLS_KEYS 64
4088 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
4089 static int mdb_tls_nkeys;
4091 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
4095 case DLL_PROCESS_ATTACH: break;
4096 case DLL_THREAD_ATTACH: break;
4097 case DLL_THREAD_DETACH:
4098 for (i=0; i<mdb_tls_nkeys; i++) {
4099 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
4101 mdb_env_reader_dest(r);
4105 case DLL_PROCESS_DETACH: break;
4110 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4112 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4116 /* Force some symbol references.
4117 * _tls_used forces the linker to create the TLS directory if not already done
4118 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
4120 #pragma comment(linker, "/INCLUDE:_tls_used")
4121 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
4122 #pragma const_seg(".CRT$XLB")
4123 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
4124 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4127 #pragma comment(linker, "/INCLUDE:__tls_used")
4128 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
4129 #pragma data_seg(".CRT$XLB")
4130 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4132 #endif /* WIN 32/64 */
4133 #endif /* !__GNUC__ */
4136 /** Downgrade the exclusive lock on the region back to shared */
4138 mdb_env_share_locks(MDB_env *env, int *excl)
4140 int rc = 0, toggle = mdb_env_pick_meta(env);
4142 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
4147 /* First acquire a shared lock. The Unlock will
4148 * then release the existing exclusive lock.
4150 memset(&ov, 0, sizeof(ov));
4151 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4154 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4160 struct flock lock_info;
4161 /* The shared lock replaces the existing lock */
4162 memset((void *)&lock_info, 0, sizeof(lock_info));
4163 lock_info.l_type = F_RDLCK;
4164 lock_info.l_whence = SEEK_SET;
4165 lock_info.l_start = 0;
4166 lock_info.l_len = 1;
4167 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4168 (rc = ErrCode()) == EINTR) ;
4169 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
4176 /** Try to get exclusive lock, otherwise shared.
4177 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
4180 mdb_env_excl_lock(MDB_env *env, int *excl)
4184 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
4188 memset(&ov, 0, sizeof(ov));
4189 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4196 struct flock lock_info;
4197 memset((void *)&lock_info, 0, sizeof(lock_info));
4198 lock_info.l_type = F_WRLCK;
4199 lock_info.l_whence = SEEK_SET;
4200 lock_info.l_start = 0;
4201 lock_info.l_len = 1;
4202 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4203 (rc = ErrCode()) == EINTR) ;
4207 # ifdef MDB_USE_POSIX_SEM
4208 if (*excl < 0) /* always true when !MDB_USE_POSIX_SEM */
4211 lock_info.l_type = F_RDLCK;
4212 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
4213 (rc = ErrCode()) == EINTR) ;
4223 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
4225 * @(#) $Revision: 5.1 $
4226 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
4227 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
4229 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
4233 * Please do not copyright this code. This code is in the public domain.
4235 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
4236 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
4237 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
4238 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
4239 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4240 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4241 * PERFORMANCE OF THIS SOFTWARE.
4244 * chongo <Landon Curt Noll> /\oo/\
4245 * http://www.isthe.com/chongo/
4247 * Share and Enjoy! :-)
4250 typedef unsigned long long mdb_hash_t;
4251 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
4253 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
4254 * @param[in] val value to hash
4255 * @param[in] hval initial value for hash
4256 * @return 64 bit hash
4258 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
4259 * hval arg on the first call.
4262 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
4264 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
4265 unsigned char *end = s + val->mv_size;
4267 * FNV-1a hash each octet of the string
4270 /* xor the bottom with the current octet */
4271 hval ^= (mdb_hash_t)*s++;
4273 /* multiply by the 64 bit FNV magic prime mod 2^64 */
4274 hval += (hval << 1) + (hval << 4) + (hval << 5) +
4275 (hval << 7) + (hval << 8) + (hval << 40);
4277 /* return our new hash value */
4281 /** Hash the string and output the encoded hash.
4282 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
4283 * very short name limits. We don't care about the encoding being reversible,
4284 * we just want to preserve as many bits of the input as possible in a
4285 * small printable string.
4286 * @param[in] str string to hash
4287 * @param[out] encbuf an array of 11 chars to hold the hash
4289 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
4292 mdb_pack85(unsigned long l, char *out)
4296 for (i=0; i<5; i++) {
4297 *out++ = mdb_a85[l % 85];
4303 mdb_hash_enc(MDB_val *val, char *encbuf)
4305 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
4307 mdb_pack85(h, encbuf);
4308 mdb_pack85(h>>32, encbuf+5);
4313 /** Open and/or initialize the lock region for the environment.
4314 * @param[in] env The LMDB environment.
4315 * @param[in] lpath The pathname of the file used for the lock region.
4316 * @param[in] mode The Unix permissions for the file, if we create it.
4317 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
4318 * @return 0 on success, non-zero on failure.
4321 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
4324 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
4326 # define MDB_ERRCODE_ROFS EROFS
4327 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
4328 # define MDB_CLOEXEC O_CLOEXEC
4331 # define MDB_CLOEXEC 0
4338 env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
4339 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
4340 FILE_ATTRIBUTE_NORMAL, NULL);
4342 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
4344 if (env->me_lfd == INVALID_HANDLE_VALUE) {
4346 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
4351 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
4352 /* Lose record locks when exec*() */
4353 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
4354 fcntl(env->me_lfd, F_SETFD, fdflags);
4357 if (!(env->me_flags & MDB_NOTLS)) {
4358 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
4361 env->me_flags |= MDB_ENV_TXKEY;
4363 /* Windows TLS callbacks need help finding their TLS info. */
4364 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
4368 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
4372 /* Try to get exclusive lock. If we succeed, then
4373 * nobody is using the lock region and we should initialize it.
4375 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
4378 size = GetFileSize(env->me_lfd, NULL);
4380 size = lseek(env->me_lfd, 0, SEEK_END);
4381 if (size == -1) goto fail_errno;
4383 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
4384 if (size < rsize && *excl > 0) {
4386 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
4387 || !SetEndOfFile(env->me_lfd))
4390 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
4394 size = rsize - sizeof(MDB_txninfo);
4395 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
4400 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
4402 if (!mh) goto fail_errno;
4403 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
4405 if (!env->me_txns) goto fail_errno;
4407 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
4409 if (m == MAP_FAILED) goto fail_errno;
4415 BY_HANDLE_FILE_INFORMATION stbuf;
4424 if (!mdb_sec_inited) {
4425 InitializeSecurityDescriptor(&mdb_null_sd,
4426 SECURITY_DESCRIPTOR_REVISION);
4427 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
4428 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
4429 mdb_all_sa.bInheritHandle = FALSE;
4430 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
4433 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
4434 idbuf.volume = stbuf.dwVolumeSerialNumber;
4435 idbuf.nhigh = stbuf.nFileIndexHigh;
4436 idbuf.nlow = stbuf.nFileIndexLow;
4437 val.mv_data = &idbuf;
4438 val.mv_size = sizeof(idbuf);
4439 mdb_hash_enc(&val, encbuf);
4440 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
4441 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
4442 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
4443 if (!env->me_rmutex) goto fail_errno;
4444 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
4445 if (!env->me_wmutex) goto fail_errno;
4446 #elif defined(MDB_USE_POSIX_SEM)
4455 #if defined(__NetBSD__)
4456 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
4458 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
4459 idbuf.dev = stbuf.st_dev;
4460 idbuf.ino = stbuf.st_ino;
4461 val.mv_data = &idbuf;
4462 val.mv_size = sizeof(idbuf);
4463 mdb_hash_enc(&val, encbuf);
4464 #ifdef MDB_SHORT_SEMNAMES
4465 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
4467 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
4468 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
4469 /* Clean up after a previous run, if needed: Try to
4470 * remove both semaphores before doing anything else.
4472 sem_unlink(env->me_txns->mti_rmname);
4473 sem_unlink(env->me_txns->mti_wmname);
4474 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
4475 O_CREAT|O_EXCL, mode, 1);
4476 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4477 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
4478 O_CREAT|O_EXCL, mode, 1);
4479 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4480 #else /* MDB_USE_POSIX_SEM */
4481 pthread_mutexattr_t mattr;
4483 if ((rc = pthread_mutexattr_init(&mattr))
4484 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
4485 || (rc = pthread_mutex_init(&env->me_txns->mti_mutex, &mattr))
4486 || (rc = pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr)))
4488 pthread_mutexattr_destroy(&mattr);
4489 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
4491 env->me_txns->mti_magic = MDB_MAGIC;
4492 env->me_txns->mti_format = MDB_LOCK_FORMAT;
4493 env->me_txns->mti_txnid = 0;
4494 env->me_txns->mti_numreaders = 0;
4497 if (env->me_txns->mti_magic != MDB_MAGIC) {
4498 DPUTS("lock region has invalid magic");
4502 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
4503 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
4504 env->me_txns->mti_format, MDB_LOCK_FORMAT));
4505 rc = MDB_VERSION_MISMATCH;
4509 if (rc && rc != EACCES && rc != EAGAIN) {
4513 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
4514 if (!env->me_rmutex) goto fail_errno;
4515 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
4516 if (!env->me_wmutex) goto fail_errno;
4517 #elif defined(MDB_USE_POSIX_SEM)
4518 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
4519 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4520 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
4521 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4532 /** The name of the lock file in the DB environment */
4533 #define LOCKNAME "/lock.mdb"
4534 /** The name of the data file in the DB environment */
4535 #define DATANAME "/data.mdb"
4536 /** The suffix of the lock file when no subdir is used */
4537 #define LOCKSUFF "-lock"
4538 /** Only a subset of the @ref mdb_env flags can be changed
4539 * at runtime. Changing other flags requires closing the
4540 * environment and re-opening it with the new flags.
4542 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
4543 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY|MDB_WRITEMAP| \
4544 MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
4546 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
4547 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
4551 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
4553 int oflags, rc, len, excl = -1;
4554 char *lpath, *dpath;
4556 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
4560 if (flags & MDB_NOSUBDIR) {
4561 rc = len + sizeof(LOCKSUFF) + len + 1;
4563 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
4568 if (flags & MDB_NOSUBDIR) {
4569 dpath = lpath + len + sizeof(LOCKSUFF);
4570 sprintf(lpath, "%s" LOCKSUFF, path);
4571 strcpy(dpath, path);
4573 dpath = lpath + len + sizeof(LOCKNAME);
4574 sprintf(lpath, "%s" LOCKNAME, path);
4575 sprintf(dpath, "%s" DATANAME, path);
4579 flags |= env->me_flags;
4580 if (flags & MDB_RDONLY) {
4581 /* silently ignore WRITEMAP when we're only getting read access */
4582 flags &= ~MDB_WRITEMAP;
4584 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
4585 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
4588 env->me_flags = flags |= MDB_ENV_ACTIVE;
4592 env->me_path = strdup(path);
4593 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
4594 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
4595 env->me_dbiseqs = calloc(env->me_maxdbs, sizeof(unsigned int));
4596 if (!(env->me_dbxs && env->me_path && env->me_dbflags && env->me_dbiseqs)) {
4601 /* For RDONLY, get lockfile after we know datafile exists */
4602 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
4603 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4609 if (F_ISSET(flags, MDB_RDONLY)) {
4610 oflags = GENERIC_READ;
4611 len = OPEN_EXISTING;
4613 oflags = GENERIC_READ|GENERIC_WRITE;
4616 mode = FILE_ATTRIBUTE_NORMAL;
4617 env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
4618 NULL, len, mode, NULL);
4620 if (F_ISSET(flags, MDB_RDONLY))
4623 oflags = O_RDWR | O_CREAT;
4625 env->me_fd = open(dpath, oflags, mode);
4627 if (env->me_fd == INVALID_HANDLE_VALUE) {
4632 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
4633 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4638 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
4639 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
4640 env->me_mfd = env->me_fd;
4642 /* Synchronous fd for meta writes. Needed even with
4643 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
4646 len = OPEN_EXISTING;
4647 env->me_mfd = CreateFile(dpath, oflags,
4648 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
4649 mode | FILE_FLAG_WRITE_THROUGH, NULL);
4652 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
4654 if (env->me_mfd == INVALID_HANDLE_VALUE) {
4659 DPRINTF(("opened dbenv %p", (void *) env));
4661 rc = mdb_env_share_locks(env, &excl);
4665 if (!((flags & MDB_RDONLY) ||
4666 (env->me_pbuf = calloc(1, env->me_psize))))
4668 if (!(flags & MDB_RDONLY)) {
4670 int tsize = sizeof(MDB_txn), size = tsize + env->me_maxdbs *
4671 (sizeof(MDB_db)+sizeof(MDB_cursor *)+sizeof(unsigned int)+1);
4672 txn = calloc(1, size);
4674 txn->mt_dbs = (MDB_db *)((char *)txn + tsize);
4675 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
4676 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
4677 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
4679 txn->mt_dbxs = env->me_dbxs;
4689 mdb_env_close0(env, excl);
4695 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
4697 mdb_env_close0(MDB_env *env, int excl)
4701 if (!(env->me_flags & MDB_ENV_ACTIVE))
4704 /* Doing this here since me_dbxs may not exist during mdb_env_close */
4706 for (i = env->me_maxdbs; --i > MAIN_DBI; )
4707 free(env->me_dbxs[i].md_name.mv_data);
4712 free(env->me_dbiseqs);
4713 free(env->me_dbflags);
4715 free(env->me_dirty_list);
4717 mdb_midl_free(env->me_free_pgs);
4719 if (env->me_flags & MDB_ENV_TXKEY) {
4720 pthread_key_delete(env->me_txkey);
4722 /* Delete our key from the global list */
4723 for (i=0; i<mdb_tls_nkeys; i++)
4724 if (mdb_tls_keys[i] == env->me_txkey) {
4725 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
4733 munmap(env->me_map, env->me_mapsize);
4735 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
4736 (void) close(env->me_mfd);
4737 if (env->me_fd != INVALID_HANDLE_VALUE)
4738 (void) close(env->me_fd);
4740 MDB_PID_T pid = env->me_pid;
4741 /* Clearing readers is done in this function because
4742 * me_txkey with its destructor must be disabled first.
4744 for (i = env->me_numreaders; --i >= 0; )
4745 if (env->me_txns->mti_readers[i].mr_pid == pid)
4746 env->me_txns->mti_readers[i].mr_pid = 0;
4748 if (env->me_rmutex) {
4749 CloseHandle(env->me_rmutex);
4750 if (env->me_wmutex) CloseHandle(env->me_wmutex);
4752 /* Windows automatically destroys the mutexes when
4753 * the last handle closes.
4755 #elif defined(MDB_USE_POSIX_SEM)
4756 if (env->me_rmutex != SEM_FAILED) {
4757 sem_close(env->me_rmutex);
4758 if (env->me_wmutex != SEM_FAILED)
4759 sem_close(env->me_wmutex);
4760 /* If we have the filelock: If we are the
4761 * only remaining user, clean up semaphores.
4764 mdb_env_excl_lock(env, &excl);
4766 sem_unlink(env->me_txns->mti_rmname);
4767 sem_unlink(env->me_txns->mti_wmname);
4771 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
4773 if (env->me_lfd != INVALID_HANDLE_VALUE) {
4776 /* Unlock the lockfile. Windows would have unlocked it
4777 * after closing anyway, but not necessarily at once.
4779 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4782 (void) close(env->me_lfd);
4785 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
4790 mdb_env_close(MDB_env *env)
4797 VGMEMP_DESTROY(env);
4798 while ((dp = env->me_dpages) != NULL) {
4799 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
4800 env->me_dpages = dp->mp_next;
4804 mdb_env_close0(env, 0);
4808 /** Compare two items pointing at aligned size_t's */
4810 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
4812 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
4813 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
4816 /** Compare two items pointing at aligned unsigned int's.
4818 * This is also set as #MDB_INTEGERDUP|#MDB_DUPFIXED's #MDB_dbx.%md_dcmp,
4819 * but #mdb_cmp_clong() is called instead if the data type is size_t.
4822 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
4824 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
4825 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
4828 /** Compare two items pointing at unsigned ints of unknown alignment.
4829 * Nodes and keys are guaranteed to be 2-byte aligned.
4832 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
4834 #if BYTE_ORDER == LITTLE_ENDIAN
4835 unsigned short *u, *c;
4838 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4839 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
4842 } while(!x && u > (unsigned short *)a->mv_data);
4845 unsigned short *u, *c, *end;
4848 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4849 u = (unsigned short *)a->mv_data;
4850 c = (unsigned short *)b->mv_data;
4853 } while(!x && u < end);
4858 /** Compare two items lexically */
4860 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
4867 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4873 diff = memcmp(a->mv_data, b->mv_data, len);
4874 return diff ? diff : len_diff<0 ? -1 : len_diff;
4877 /** Compare two items in reverse byte order */
4879 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
4881 const unsigned char *p1, *p2, *p1_lim;
4885 p1_lim = (const unsigned char *)a->mv_data;
4886 p1 = (const unsigned char *)a->mv_data + a->mv_size;
4887 p2 = (const unsigned char *)b->mv_data + b->mv_size;
4889 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4895 while (p1 > p1_lim) {
4896 diff = *--p1 - *--p2;
4900 return len_diff<0 ? -1 : len_diff;
4903 /** Search for key within a page, using binary search.
4904 * Returns the smallest entry larger or equal to the key.
4905 * If exactp is non-null, stores whether the found entry was an exact match
4906 * in *exactp (1 or 0).
4907 * Updates the cursor index with the index of the found entry.
4908 * If no entry larger or equal to the key is found, returns NULL.
4911 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
4913 unsigned int i = 0, nkeys;
4916 MDB_page *mp = mc->mc_pg[mc->mc_top];
4917 MDB_node *node = NULL;
4922 nkeys = NUMKEYS(mp);
4924 DPRINTF(("searching %u keys in %s %spage %"Z"u",
4925 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
4928 low = IS_LEAF(mp) ? 0 : 1;
4930 cmp = mc->mc_dbx->md_cmp;
4932 /* Branch pages have no data, so if using integer keys,
4933 * alignment is guaranteed. Use faster mdb_cmp_int.
4935 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
4936 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
4943 nodekey.mv_size = mc->mc_db->md_pad;
4944 node = NODEPTR(mp, 0); /* fake */
4945 while (low <= high) {
4946 i = (low + high) >> 1;
4947 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
4948 rc = cmp(key, &nodekey);
4949 DPRINTF(("found leaf index %u [%s], rc = %i",
4950 i, DKEY(&nodekey), rc));
4959 while (low <= high) {
4960 i = (low + high) >> 1;
4962 node = NODEPTR(mp, i);
4963 nodekey.mv_size = NODEKSZ(node);
4964 nodekey.mv_data = NODEKEY(node);
4966 rc = cmp(key, &nodekey);
4969 DPRINTF(("found leaf index %u [%s], rc = %i",
4970 i, DKEY(&nodekey), rc));
4972 DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
4973 i, DKEY(&nodekey), NODEPGNO(node), rc));
4984 if (rc > 0) { /* Found entry is less than the key. */
4985 i++; /* Skip to get the smallest entry larger than key. */
4987 node = NODEPTR(mp, i);
4990 *exactp = (rc == 0 && nkeys > 0);
4991 /* store the key index */
4992 mc->mc_ki[mc->mc_top] = i;
4994 /* There is no entry larger or equal to the key. */
4997 /* nodeptr is fake for LEAF2 */
5003 mdb_cursor_adjust(MDB_cursor *mc, func)
5007 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5008 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
5015 /** Pop a page off the top of the cursor's stack. */
5017 mdb_cursor_pop(MDB_cursor *mc)
5021 MDB_page *top = mc->mc_pg[mc->mc_top];
5027 DPRINTF(("popped page %"Z"u off db %d cursor %p", top->mp_pgno,
5028 DDBI(mc), (void *) mc));
5032 /** Push a page onto the top of the cursor's stack. */
5034 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
5036 DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
5037 DDBI(mc), (void *) mc));
5039 if (mc->mc_snum >= CURSOR_STACK) {
5040 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5041 return MDB_CURSOR_FULL;
5044 mc->mc_top = mc->mc_snum++;
5045 mc->mc_pg[mc->mc_top] = mp;
5046 mc->mc_ki[mc->mc_top] = 0;
5051 /** Find the address of the page corresponding to a given page number.
5052 * @param[in] txn the transaction for this access.
5053 * @param[in] pgno the page number for the page to retrieve.
5054 * @param[out] ret address of a pointer where the page's address will be stored.
5055 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
5056 * @return 0 on success, non-zero on failure.
5059 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
5061 MDB_env *env = txn->mt_env;
5065 if (!((txn->mt_flags & MDB_TXN_RDONLY) | (env->me_flags & MDB_WRITEMAP))) {
5069 MDB_ID2L dl = tx2->mt_u.dirty_list;
5071 /* Spilled pages were dirtied in this txn and flushed
5072 * because the dirty list got full. Bring this page
5073 * back in from the map (but don't unspill it here,
5074 * leave that unless page_touch happens again).
5076 if (tx2->mt_spill_pgs) {
5077 MDB_ID pn = pgno << 1;
5078 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
5079 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
5080 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5085 unsigned x = mdb_mid2l_search(dl, pgno);
5086 if (x <= dl[0].mid && dl[x].mid == pgno) {
5092 } while ((tx2 = tx2->mt_parent) != NULL);
5095 if (pgno < txn->mt_next_pgno) {
5097 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5099 DPRINTF(("page %"Z"u not found", pgno));
5100 txn->mt_flags |= MDB_TXN_ERROR;
5101 return MDB_PAGE_NOTFOUND;
5111 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
5112 * The cursor is at the root page, set up the rest of it.
5115 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
5117 MDB_page *mp = mc->mc_pg[mc->mc_top];
5121 while (IS_BRANCH(mp)) {
5125 DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
5126 mdb_cassert(mc, NUMKEYS(mp) > 1);
5127 DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
5129 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
5131 if (flags & MDB_PS_LAST)
5132 i = NUMKEYS(mp) - 1;
5135 node = mdb_node_search(mc, key, &exact);
5137 i = NUMKEYS(mp) - 1;
5139 i = mc->mc_ki[mc->mc_top];
5141 mdb_cassert(mc, i > 0);
5145 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
5148 mdb_cassert(mc, i < NUMKEYS(mp));
5149 node = NODEPTR(mp, i);
5151 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
5154 mc->mc_ki[mc->mc_top] = i;
5155 if ((rc = mdb_cursor_push(mc, mp)))
5158 if (flags & MDB_PS_MODIFY) {
5159 if ((rc = mdb_page_touch(mc)) != 0)
5161 mp = mc->mc_pg[mc->mc_top];
5166 DPRINTF(("internal error, index points to a %02X page!?",
5168 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5169 return MDB_CORRUPTED;
5172 DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
5173 key ? DKEY(key) : "null"));
5174 mc->mc_flags |= C_INITIALIZED;
5175 mc->mc_flags &= ~C_EOF;
5180 /** Search for the lowest key under the current branch page.
5181 * This just bypasses a NUMKEYS check in the current page
5182 * before calling mdb_page_search_root(), because the callers
5183 * are all in situations where the current page is known to
5187 mdb_page_search_lowest(MDB_cursor *mc)
5189 MDB_page *mp = mc->mc_pg[mc->mc_top];
5190 MDB_node *node = NODEPTR(mp, 0);
5193 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
5196 mc->mc_ki[mc->mc_top] = 0;
5197 if ((rc = mdb_cursor_push(mc, mp)))
5199 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
5202 /** Search for the page a given key should be in.
5203 * Push it and its parent pages on the cursor stack.
5204 * @param[in,out] mc the cursor for this operation.
5205 * @param[in] key the key to search for, or NULL for first/last page.
5206 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
5207 * are touched (updated with new page numbers).
5208 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
5209 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
5210 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
5211 * @return 0 on success, non-zero on failure.
5214 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
5219 /* Make sure the txn is still viable, then find the root from
5220 * the txn's db table and set it as the root of the cursor's stack.
5222 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
5223 DPUTS("transaction has failed, must abort");
5226 /* Make sure we're using an up-to-date root */
5227 if (*mc->mc_dbflag & DB_STALE) {
5229 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
5231 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
5232 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
5239 MDB_node *leaf = mdb_node_search(&mc2,
5240 &mc->mc_dbx->md_name, &exact);
5242 return MDB_NOTFOUND;
5243 if ((leaf->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
5244 return MDB_INCOMPATIBLE; /* not a named DB */
5245 rc = mdb_node_read(mc->mc_txn, leaf, &data);
5248 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
5250 /* The txn may not know this DBI, or another process may
5251 * have dropped and recreated the DB with other flags.
5253 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
5254 return MDB_INCOMPATIBLE;
5255 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
5257 *mc->mc_dbflag &= ~DB_STALE;
5259 root = mc->mc_db->md_root;
5261 if (root == P_INVALID) { /* Tree is empty. */
5262 DPUTS("tree is empty");
5263 return MDB_NOTFOUND;
5267 mdb_cassert(mc, root > 1);
5268 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
5269 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0], NULL)) != 0)
5275 DPRINTF(("db %d root page %"Z"u has flags 0x%X",
5276 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
5278 if (flags & MDB_PS_MODIFY) {
5279 if ((rc = mdb_page_touch(mc)))
5283 if (flags & MDB_PS_ROOTONLY)
5286 return mdb_page_search_root(mc, key, flags);
5290 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
5292 MDB_txn *txn = mc->mc_txn;
5293 pgno_t pg = mp->mp_pgno;
5294 unsigned x = 0, ovpages = mp->mp_pages;
5295 MDB_env *env = txn->mt_env;
5296 MDB_IDL sl = txn->mt_spill_pgs;
5297 MDB_ID pn = pg << 1;
5300 DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
5301 /* If the page is dirty or on the spill list we just acquired it,
5302 * so we should give it back to our current free list, if any.
5303 * Otherwise put it onto the list of pages we freed in this txn.
5305 * Won't create me_pghead: me_pglast must be inited along with it.
5306 * Unsupported in nested txns: They would need to hide the page
5307 * range in ancestor txns' dirty and spilled lists.
5309 if (env->me_pghead &&
5311 ((mp->mp_flags & P_DIRTY) ||
5312 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
5316 MDB_ID2 *dl, ix, iy;
5317 rc = mdb_midl_need(&env->me_pghead, ovpages);
5320 if (!(mp->mp_flags & P_DIRTY)) {
5321 /* This page is no longer spilled */
5328 /* Remove from dirty list */
5329 dl = txn->mt_u.dirty_list;
5331 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
5337 mdb_cassert(mc, x > 1);
5339 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
5340 txn->mt_flags |= MDB_TXN_ERROR;
5341 return MDB_CORRUPTED;
5344 if (!(env->me_flags & MDB_WRITEMAP))
5345 mdb_dpage_free(env, mp);
5347 /* Insert in me_pghead */
5348 mop = env->me_pghead;
5349 j = mop[0] + ovpages;
5350 for (i = mop[0]; i && mop[i] < pg; i--)
5356 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
5360 mc->mc_db->md_overflow_pages -= ovpages;
5364 /** Return the data associated with a given node.
5365 * @param[in] txn The transaction for this operation.
5366 * @param[in] leaf The node being read.
5367 * @param[out] data Updated to point to the node's data.
5368 * @return 0 on success, non-zero on failure.
5371 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
5373 MDB_page *omp; /* overflow page */
5377 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5378 data->mv_size = NODEDSZ(leaf);
5379 data->mv_data = NODEDATA(leaf);
5383 /* Read overflow data.
5385 data->mv_size = NODEDSZ(leaf);
5386 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
5387 if ((rc = mdb_page_get(txn, pgno, &omp, NULL)) != 0) {
5388 DPRINTF(("read overflow page %"Z"u failed", pgno));
5391 data->mv_data = METADATA(omp);
5397 mdb_get(MDB_txn *txn, MDB_dbi dbi,
5398 MDB_val *key, MDB_val *data)
5405 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
5407 if (!key || !data || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
5410 if (txn->mt_flags & MDB_TXN_ERROR)
5413 mdb_cursor_init(&mc, txn, dbi, &mx);
5414 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
5417 /** Find a sibling for a page.
5418 * Replaces the page at the top of the cursor's stack with the
5419 * specified sibling, if one exists.
5420 * @param[in] mc The cursor for this operation.
5421 * @param[in] move_right Non-zero if the right sibling is requested,
5422 * otherwise the left sibling.
5423 * @return 0 on success, non-zero on failure.
5426 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
5432 if (mc->mc_snum < 2) {
5433 return MDB_NOTFOUND; /* root has no siblings */
5437 DPRINTF(("parent page is page %"Z"u, index %u",
5438 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
5440 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
5441 : (mc->mc_ki[mc->mc_top] == 0)) {
5442 DPRINTF(("no more keys left, moving to %s sibling",
5443 move_right ? "right" : "left"));
5444 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
5445 /* undo cursor_pop before returning */
5452 mc->mc_ki[mc->mc_top]++;
5454 mc->mc_ki[mc->mc_top]--;
5455 DPRINTF(("just moving to %s index key %u",
5456 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
5458 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
5460 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5461 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL)) != 0) {
5462 /* mc will be inconsistent if caller does mc_snum++ as above */
5463 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
5467 mdb_cursor_push(mc, mp);
5469 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
5474 /** Move the cursor to the next data item. */
5476 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5482 if (mc->mc_flags & C_EOF) {
5483 return MDB_NOTFOUND;
5486 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5488 mp = mc->mc_pg[mc->mc_top];
5490 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5491 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5492 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5493 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
5494 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
5495 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
5496 if (rc == MDB_SUCCESS)
5497 MDB_GET_KEY(leaf, key);
5502 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5503 if (op == MDB_NEXT_DUP)
5504 return MDB_NOTFOUND;
5508 DPRINTF(("cursor_next: top page is %"Z"u in cursor %p",
5509 mdb_dbg_pgno(mp), (void *) mc));
5510 if (mc->mc_flags & C_DEL)
5513 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
5514 DPUTS("=====> move to next sibling page");
5515 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5516 mc->mc_flags |= C_EOF;
5519 mp = mc->mc_pg[mc->mc_top];
5520 DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5522 mc->mc_ki[mc->mc_top]++;
5525 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5526 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5529 key->mv_size = mc->mc_db->md_pad;
5530 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5534 mdb_cassert(mc, IS_LEAF(mp));
5535 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5537 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5538 mdb_xcursor_init1(mc, leaf);
5541 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5544 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5545 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5546 if (rc != MDB_SUCCESS)
5551 MDB_GET_KEY(leaf, key);
5555 /** Move the cursor to the previous data item. */
5557 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5563 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5565 mp = mc->mc_pg[mc->mc_top];
5567 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5568 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5569 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5570 if (op == MDB_PREV || op == MDB_PREV_DUP) {
5571 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
5572 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
5573 if (rc == MDB_SUCCESS) {
5574 MDB_GET_KEY(leaf, key);
5575 mc->mc_flags &= ~C_EOF;
5581 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5582 if (op == MDB_PREV_DUP)
5583 return MDB_NOTFOUND;
5587 DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p",
5588 mdb_dbg_pgno(mp), (void *) mc));
5590 if (mc->mc_ki[mc->mc_top] == 0) {
5591 DPUTS("=====> move to prev sibling page");
5592 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
5595 mp = mc->mc_pg[mc->mc_top];
5596 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
5597 DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5599 mc->mc_ki[mc->mc_top]--;
5601 mc->mc_flags &= ~C_EOF;
5603 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5604 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5607 key->mv_size = mc->mc_db->md_pad;
5608 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5612 mdb_cassert(mc, IS_LEAF(mp));
5613 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5615 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5616 mdb_xcursor_init1(mc, leaf);
5619 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5622 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5623 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5624 if (rc != MDB_SUCCESS)
5629 MDB_GET_KEY(leaf, key);
5633 /** Set the cursor on a specific data item. */
5635 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5636 MDB_cursor_op op, int *exactp)
5640 MDB_node *leaf = NULL;
5643 if (key->mv_size == 0)
5644 return MDB_BAD_VALSIZE;
5647 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5649 /* See if we're already on the right page */
5650 if (mc->mc_flags & C_INITIALIZED) {
5653 mp = mc->mc_pg[mc->mc_top];
5655 mc->mc_ki[mc->mc_top] = 0;
5656 return MDB_NOTFOUND;
5658 if (mp->mp_flags & P_LEAF2) {
5659 nodekey.mv_size = mc->mc_db->md_pad;
5660 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
5662 leaf = NODEPTR(mp, 0);
5663 MDB_GET_KEY2(leaf, nodekey);
5665 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5667 /* Probably happens rarely, but first node on the page
5668 * was the one we wanted.
5670 mc->mc_ki[mc->mc_top] = 0;
5677 unsigned int nkeys = NUMKEYS(mp);
5679 if (mp->mp_flags & P_LEAF2) {
5680 nodekey.mv_data = LEAF2KEY(mp,
5681 nkeys-1, nodekey.mv_size);
5683 leaf = NODEPTR(mp, nkeys-1);
5684 MDB_GET_KEY2(leaf, nodekey);
5686 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5688 /* last node was the one we wanted */
5689 mc->mc_ki[mc->mc_top] = nkeys-1;
5695 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
5696 /* This is definitely the right page, skip search_page */
5697 if (mp->mp_flags & P_LEAF2) {
5698 nodekey.mv_data = LEAF2KEY(mp,
5699 mc->mc_ki[mc->mc_top], nodekey.mv_size);
5701 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5702 MDB_GET_KEY2(leaf, nodekey);
5704 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5706 /* current node was the one we wanted */
5716 /* If any parents have right-sibs, search.
5717 * Otherwise, there's nothing further.
5719 for (i=0; i<mc->mc_top; i++)
5721 NUMKEYS(mc->mc_pg[i])-1)
5723 if (i == mc->mc_top) {
5724 /* There are no other pages */
5725 mc->mc_ki[mc->mc_top] = nkeys;
5726 return MDB_NOTFOUND;
5730 /* There are no other pages */
5731 mc->mc_ki[mc->mc_top] = 0;
5732 if (op == MDB_SET_RANGE && !exactp) {
5736 return MDB_NOTFOUND;
5740 rc = mdb_page_search(mc, key, 0);
5741 if (rc != MDB_SUCCESS)
5744 mp = mc->mc_pg[mc->mc_top];
5745 mdb_cassert(mc, IS_LEAF(mp));
5748 leaf = mdb_node_search(mc, key, exactp);
5749 if (exactp != NULL && !*exactp) {
5750 /* MDB_SET specified and not an exact match. */
5751 return MDB_NOTFOUND;
5755 DPUTS("===> inexact leaf not found, goto sibling");
5756 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5757 mc->mc_flags |= C_EOF;
5758 return rc; /* no entries matched */
5760 mp = mc->mc_pg[mc->mc_top];
5761 mdb_cassert(mc, IS_LEAF(mp));
5762 leaf = NODEPTR(mp, 0);
5766 mc->mc_flags |= C_INITIALIZED;
5767 mc->mc_flags &= ~C_EOF;
5770 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
5771 key->mv_size = mc->mc_db->md_pad;
5772 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5777 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5778 mdb_xcursor_init1(mc, leaf);
5781 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5782 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
5783 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5786 if (op == MDB_GET_BOTH) {
5792 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
5793 if (rc != MDB_SUCCESS)
5796 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
5799 if ((rc = mdb_node_read(mc->mc_txn, leaf, &olddata)) != MDB_SUCCESS)
5801 dcmp = mc->mc_dbx->md_dcmp;
5802 #if UINT_MAX < SIZE_MAX
5803 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
5804 dcmp = mdb_cmp_clong;
5806 rc = dcmp(data, &olddata);
5808 if (op == MDB_GET_BOTH || rc > 0)
5809 return MDB_NOTFOUND;
5816 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5817 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5822 /* The key already matches in all other cases */
5823 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
5824 MDB_GET_KEY(leaf, key);
5825 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
5830 /** Move the cursor to the first item in the database. */
5832 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5838 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5840 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5841 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
5842 if (rc != MDB_SUCCESS)
5845 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
5847 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
5848 mc->mc_flags |= C_INITIALIZED;
5849 mc->mc_flags &= ~C_EOF;
5851 mc->mc_ki[mc->mc_top] = 0;
5853 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5854 key->mv_size = mc->mc_db->md_pad;
5855 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
5860 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5861 mdb_xcursor_init1(mc, leaf);
5862 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5866 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5870 MDB_GET_KEY(leaf, key);
5874 /** Move the cursor to the last item in the database. */
5876 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5882 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5884 if (!(mc->mc_flags & C_EOF)) {
5886 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5887 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
5888 if (rc != MDB_SUCCESS)
5891 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
5894 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
5895 mc->mc_flags |= C_INITIALIZED|C_EOF;
5896 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5898 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5899 key->mv_size = mc->mc_db->md_pad;
5900 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
5905 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5906 mdb_xcursor_init1(mc, leaf);
5907 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5911 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5916 MDB_GET_KEY(leaf, key);
5921 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5926 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
5931 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
5935 case MDB_GET_CURRENT:
5936 if (!(mc->mc_flags & C_INITIALIZED)) {
5939 MDB_page *mp = mc->mc_pg[mc->mc_top];
5940 int nkeys = NUMKEYS(mp);
5941 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
5942 mc->mc_ki[mc->mc_top] = nkeys;
5948 key->mv_size = mc->mc_db->md_pad;
5949 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5951 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5952 MDB_GET_KEY(leaf, key);
5954 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5955 if (mc->mc_flags & C_DEL)
5956 mdb_xcursor_init1(mc, leaf);
5957 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
5959 rc = mdb_node_read(mc->mc_txn, leaf, data);
5966 case MDB_GET_BOTH_RANGE:
5971 if (mc->mc_xcursor == NULL) {
5972 rc = MDB_INCOMPATIBLE;
5982 rc = mdb_cursor_set(mc, key, data, op,
5983 op == MDB_SET_RANGE ? NULL : &exact);
5986 case MDB_GET_MULTIPLE:
5987 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5991 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5992 rc = MDB_INCOMPATIBLE;
5996 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
5997 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
6000 case MDB_NEXT_MULTIPLE:
6005 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6006 rc = MDB_INCOMPATIBLE;
6009 if (!(mc->mc_flags & C_INITIALIZED))
6010 rc = mdb_cursor_first(mc, key, data);
6012 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
6013 if (rc == MDB_SUCCESS) {
6014 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6017 mx = &mc->mc_xcursor->mx_cursor;
6018 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
6020 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
6021 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
6029 case MDB_NEXT_NODUP:
6030 if (!(mc->mc_flags & C_INITIALIZED))
6031 rc = mdb_cursor_first(mc, key, data);
6033 rc = mdb_cursor_next(mc, key, data, op);
6037 case MDB_PREV_NODUP:
6038 if (!(mc->mc_flags & C_INITIALIZED)) {
6039 rc = mdb_cursor_last(mc, key, data);
6042 mc->mc_flags |= C_INITIALIZED;
6043 mc->mc_ki[mc->mc_top]++;
6045 rc = mdb_cursor_prev(mc, key, data, op);
6048 rc = mdb_cursor_first(mc, key, data);
6051 mfunc = mdb_cursor_first;
6053 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
6057 if (mc->mc_xcursor == NULL) {
6058 rc = MDB_INCOMPATIBLE;
6062 MDB_node *leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6063 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6064 MDB_GET_KEY(leaf, key);
6065 rc = mdb_node_read(mc->mc_txn, leaf, data);
6069 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
6073 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
6076 rc = mdb_cursor_last(mc, key, data);
6079 mfunc = mdb_cursor_last;
6082 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
6087 if (mc->mc_flags & C_DEL)
6088 mc->mc_flags ^= C_DEL;
6093 /** Touch all the pages in the cursor stack. Set mc_top.
6094 * Makes sure all the pages are writable, before attempting a write operation.
6095 * @param[in] mc The cursor to operate on.
6098 mdb_cursor_touch(MDB_cursor *mc)
6100 int rc = MDB_SUCCESS;
6102 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
6105 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
6107 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
6108 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
6111 *mc->mc_dbflag |= DB_DIRTY;
6116 rc = mdb_page_touch(mc);
6117 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
6118 mc->mc_top = mc->mc_snum-1;
6123 /** Do not spill pages to disk if txn is getting full, may fail instead */
6124 #define MDB_NOSPILL 0x8000
6127 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6130 enum { MDB_NO_ROOT = MDB_LAST_ERRCODE+10 }; /* internal code */
6132 MDB_node *leaf = NULL;
6133 MDB_page *fp, *mp, *sub_root = NULL;
6135 MDB_val xdata, *rdata, dkey, olddata;
6137 int do_sub = 0, insert_key, insert_data;
6138 unsigned int mcount = 0, dcount = 0, nospill;
6141 unsigned int nflags;
6144 if (mc == NULL || key == NULL)
6147 env = mc->mc_txn->mt_env;
6149 /* Check this first so counter will always be zero on any
6152 if (flags & MDB_MULTIPLE) {
6153 dcount = data[1].mv_size;
6154 data[1].mv_size = 0;
6155 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
6156 return MDB_INCOMPATIBLE;
6159 nospill = flags & MDB_NOSPILL;
6160 flags &= ~MDB_NOSPILL;
6162 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
6163 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6165 if (key->mv_size-1 >= ENV_MAXKEY(env))
6166 return MDB_BAD_VALSIZE;
6168 #if SIZE_MAX > MAXDATASIZE
6169 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
6170 return MDB_BAD_VALSIZE;
6172 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
6173 return MDB_BAD_VALSIZE;
6176 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
6177 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
6181 if (flags == MDB_CURRENT) {
6182 if (!(mc->mc_flags & C_INITIALIZED))
6185 } else if (mc->mc_db->md_root == P_INVALID) {
6186 /* new database, cursor has nothing to point to */
6189 mc->mc_flags &= ~C_INITIALIZED;
6194 if (flags & MDB_APPEND) {
6196 rc = mdb_cursor_last(mc, &k2, &d2);
6198 rc = mc->mc_dbx->md_cmp(key, &k2);
6201 mc->mc_ki[mc->mc_top]++;
6203 /* new key is <= last key */
6208 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
6210 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
6211 DPRINTF(("duplicate key [%s]", DKEY(key)));
6213 return MDB_KEYEXIST;
6215 if (rc && rc != MDB_NOTFOUND)
6219 if (mc->mc_flags & C_DEL)
6220 mc->mc_flags ^= C_DEL;
6222 /* Cursor is positioned, check for room in the dirty list */
6224 if (flags & MDB_MULTIPLE) {
6226 xdata.mv_size = data->mv_size * dcount;
6230 if ((rc2 = mdb_page_spill(mc, key, rdata)))
6234 if (rc == MDB_NO_ROOT) {
6236 /* new database, write a root leaf page */
6237 DPUTS("allocating new root leaf page");
6238 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
6241 mdb_cursor_push(mc, np);
6242 mc->mc_db->md_root = np->mp_pgno;
6243 mc->mc_db->md_depth++;
6244 *mc->mc_dbflag |= DB_DIRTY;
6245 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
6247 np->mp_flags |= P_LEAF2;
6248 mc->mc_flags |= C_INITIALIZED;
6250 /* make sure all cursor pages are writable */
6251 rc2 = mdb_cursor_touch(mc);
6256 insert_key = insert_data = rc;
6258 /* The key does not exist */
6259 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
6260 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
6261 LEAFSIZE(key, data) > env->me_nodemax)
6263 /* Too big for a node, insert in sub-DB. Set up an empty
6264 * "old sub-page" for prep_subDB to expand to a full page.
6266 fp_flags = P_LEAF|P_DIRTY;
6268 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
6269 fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
6270 olddata.mv_size = PAGEHDRSZ;
6274 /* there's only a key anyway, so this is a no-op */
6275 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6277 unsigned int ksize = mc->mc_db->md_pad;
6278 if (key->mv_size != ksize)
6279 return MDB_BAD_VALSIZE;
6280 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
6281 memcpy(ptr, key->mv_data, ksize);
6283 /* if overwriting slot 0 of leaf, need to
6284 * update branch key if there is a parent page
6286 if (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
6287 unsigned short top = mc->mc_top;
6289 /* slot 0 is always an empty key, find real slot */
6290 while (mc->mc_top && !mc->mc_ki[mc->mc_top])
6292 if (mc->mc_ki[mc->mc_top])
6293 rc2 = mdb_update_key(mc, key);
6304 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6305 olddata.mv_size = NODEDSZ(leaf);
6306 olddata.mv_data = NODEDATA(leaf);
6309 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
6310 /* Prepare (sub-)page/sub-DB to accept the new item,
6311 * if needed. fp: old sub-page or a header faking
6312 * it. mp: new (sub-)page. offset: growth in page
6313 * size. xdata: node data with new page or DB.
6315 unsigned i, offset = 0;
6316 mp = fp = xdata.mv_data = env->me_pbuf;
6317 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
6319 /* Was a single item before, must convert now */
6320 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6322 /* Just overwrite the current item */
6323 if (flags == MDB_CURRENT)
6325 dcmp = mc->mc_dbx->md_dcmp;
6326 #if UINT_MAX < SIZE_MAX
6327 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
6328 dcmp = mdb_cmp_clong;
6330 /* does data match? */
6331 if (!dcmp(data, &olddata)) {
6332 if (flags & MDB_NODUPDATA)
6333 return MDB_KEYEXIST;
6338 /* Back up original data item */
6339 dkey.mv_size = olddata.mv_size;
6340 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
6342 /* Make sub-page header for the dup items, with dummy body */
6343 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
6344 fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
6345 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
6346 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6347 fp->mp_flags |= P_LEAF2;
6348 fp->mp_pad = data->mv_size;
6349 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
6351 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
6352 (dkey.mv_size & 1) + (data->mv_size & 1);
6354 fp->mp_upper = xdata.mv_size - PAGEBASE;
6355 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
6356 } else if (leaf->mn_flags & F_SUBDATA) {
6357 /* Data is on sub-DB, just store it */
6358 flags |= F_DUPDATA|F_SUBDATA;
6361 /* Data is on sub-page */
6362 fp = olddata.mv_data;
6365 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6366 offset = EVEN(NODESIZE + sizeof(indx_t) +
6370 offset = fp->mp_pad;
6371 if (SIZELEFT(fp) < offset) {
6372 offset *= 4; /* space for 4 more */
6375 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
6377 fp->mp_flags |= P_DIRTY;
6378 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
6379 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
6383 xdata.mv_size = olddata.mv_size + offset;
6386 fp_flags = fp->mp_flags;
6387 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
6388 /* Too big for a sub-page, convert to sub-DB */
6389 fp_flags &= ~P_SUBP;
6391 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6392 fp_flags |= P_LEAF2;
6393 dummy.md_pad = fp->mp_pad;
6394 dummy.md_flags = MDB_DUPFIXED;
6395 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6396 dummy.md_flags |= MDB_INTEGERKEY;
6402 dummy.md_branch_pages = 0;
6403 dummy.md_leaf_pages = 1;
6404 dummy.md_overflow_pages = 0;
6405 dummy.md_entries = NUMKEYS(fp);
6406 xdata.mv_size = sizeof(MDB_db);
6407 xdata.mv_data = &dummy;
6408 if ((rc = mdb_page_alloc(mc, 1, &mp)))
6410 offset = env->me_psize - olddata.mv_size;
6411 flags |= F_DUPDATA|F_SUBDATA;
6412 dummy.md_root = mp->mp_pgno;
6416 mp->mp_flags = fp_flags | P_DIRTY;
6417 mp->mp_pad = fp->mp_pad;
6418 mp->mp_lower = fp->mp_lower;
6419 mp->mp_upper = fp->mp_upper + offset;
6420 if (fp_flags & P_LEAF2) {
6421 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
6423 memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
6424 olddata.mv_size - fp->mp_upper - PAGEBASE);
6425 for (i=0; i<NUMKEYS(fp); i++)
6426 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
6434 mdb_node_del(mc, 0);
6438 /* LMDB passes F_SUBDATA in 'flags' to write a DB record */
6439 if ((leaf->mn_flags ^ flags) & F_SUBDATA)
6440 return MDB_INCOMPATIBLE;
6441 /* overflow page overwrites need special handling */
6442 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6445 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
6447 memcpy(&pg, olddata.mv_data, sizeof(pg));
6448 if ((rc2 = mdb_page_get(mc->mc_txn, pg, &omp, &level)) != 0)
6450 ovpages = omp->mp_pages;
6452 /* Is the ov page large enough? */
6453 if (ovpages >= dpages) {
6454 if (!(omp->mp_flags & P_DIRTY) &&
6455 (level || (env->me_flags & MDB_WRITEMAP)))
6457 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
6460 level = 0; /* dirty in this txn or clean */
6463 if (omp->mp_flags & P_DIRTY) {
6464 /* yes, overwrite it. Note in this case we don't
6465 * bother to try shrinking the page if the new data
6466 * is smaller than the overflow threshold.
6469 /* It is writable only in a parent txn */
6470 size_t sz = (size_t) env->me_psize * ovpages, off;
6471 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
6477 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
6478 mdb_cassert(mc, rc2 == 0);
6479 if (!(flags & MDB_RESERVE)) {
6480 /* Copy end of page, adjusting alignment so
6481 * compiler may copy words instead of bytes.
6483 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
6484 memcpy((size_t *)((char *)np + off),
6485 (size_t *)((char *)omp + off), sz - off);
6488 memcpy(np, omp, sz); /* Copy beginning of page */
6491 SETDSZ(leaf, data->mv_size);
6492 if (F_ISSET(flags, MDB_RESERVE))
6493 data->mv_data = METADATA(omp);
6495 memcpy(METADATA(omp), data->mv_data, data->mv_size);
6499 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
6501 } else if (data->mv_size == olddata.mv_size) {
6502 /* same size, just replace it. Note that we could
6503 * also reuse this node if the new data is smaller,
6504 * but instead we opt to shrink the node in that case.
6506 if (F_ISSET(flags, MDB_RESERVE))
6507 data->mv_data = olddata.mv_data;
6508 else if (!(mc->mc_flags & C_SUB))
6509 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
6511 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
6516 mdb_node_del(mc, 0);
6522 nflags = flags & NODE_ADD_FLAGS;
6523 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
6524 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
6525 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
6526 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
6528 nflags |= MDB_SPLIT_REPLACE;
6529 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
6531 /* There is room already in this leaf page. */
6532 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
6533 if (rc == 0 && insert_key) {
6534 /* Adjust other cursors pointing to mp */
6535 MDB_cursor *m2, *m3;
6536 MDB_dbi dbi = mc->mc_dbi;
6537 unsigned i = mc->mc_top;
6538 MDB_page *mp = mc->mc_pg[i];
6540 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6541 if (mc->mc_flags & C_SUB)
6542 m3 = &m2->mc_xcursor->mx_cursor;
6545 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
6546 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
6553 if (rc == MDB_SUCCESS) {
6554 /* Now store the actual data in the child DB. Note that we're
6555 * storing the user data in the keys field, so there are strict
6556 * size limits on dupdata. The actual data fields of the child
6557 * DB are all zero size.
6560 int xflags, new_dupdata;
6565 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6566 if (flags & MDB_CURRENT) {
6567 xflags = MDB_CURRENT|MDB_NOSPILL;
6569 mdb_xcursor_init1(mc, leaf);
6570 xflags = (flags & MDB_NODUPDATA) ?
6571 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
6574 mc->mc_xcursor->mx_cursor.mc_pg[0] = sub_root;
6575 new_dupdata = (int)dkey.mv_size;
6576 /* converted, write the original data first */
6578 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
6581 /* we've done our job */
6584 if (!(leaf->mn_flags & F_SUBDATA) || sub_root) {
6585 /* Adjust other cursors pointing to mp */
6587 MDB_xcursor *mx = mc->mc_xcursor;
6588 unsigned i = mc->mc_top;
6589 MDB_page *mp = mc->mc_pg[i];
6591 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6592 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6593 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6594 if (m2->mc_pg[i] == mp) {
6595 if (m2->mc_ki[i] == mc->mc_ki[i]) {
6596 mdb_xcursor_init2(m2, mx, new_dupdata);
6597 } else if (!insert_key) {
6598 MDB_node *n2 = NODEPTR(mp, m2->mc_ki[i]);
6599 if (!(n2->mn_flags & F_SUBDATA))
6600 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
6605 ecount = mc->mc_xcursor->mx_db.md_entries;
6606 if (flags & MDB_APPENDDUP)
6607 xflags |= MDB_APPEND;
6608 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
6609 if (flags & F_SUBDATA) {
6610 void *db = NODEDATA(leaf);
6611 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6613 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
6615 /* Increment count unless we just replaced an existing item. */
6617 mc->mc_db->md_entries++;
6619 /* Invalidate txn if we created an empty sub-DB */
6622 /* If we succeeded and the key didn't exist before,
6623 * make sure the cursor is marked valid.
6625 mc->mc_flags |= C_INITIALIZED;
6627 if (flags & MDB_MULTIPLE) {
6630 /* let caller know how many succeeded, if any */
6631 data[1].mv_size = mcount;
6632 if (mcount < dcount) {
6633 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
6634 insert_key = insert_data = 0;
6641 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
6644 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6649 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
6655 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
6656 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6658 if (!(mc->mc_flags & C_INITIALIZED))
6661 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6662 return MDB_NOTFOUND;
6664 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
6667 rc = mdb_cursor_touch(mc);
6671 mp = mc->mc_pg[mc->mc_top];
6674 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6676 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6677 if (flags & MDB_NODUPDATA) {
6678 /* mdb_cursor_del0() will subtract the final entry */
6679 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
6681 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
6682 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6684 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
6687 /* If sub-DB still has entries, we're done */
6688 if (mc->mc_xcursor->mx_db.md_entries) {
6689 if (leaf->mn_flags & F_SUBDATA) {
6690 /* update subDB info */
6691 void *db = NODEDATA(leaf);
6692 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6695 /* shrink fake page */
6696 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
6697 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6698 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6699 /* fix other sub-DB cursors pointed at fake pages on this page */
6700 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6701 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6702 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6703 if (m2->mc_pg[mc->mc_top] == mp) {
6704 if (m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top]) {
6705 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6707 MDB_node *n2 = NODEPTR(mp, m2->mc_ki[mc->mc_top]);
6708 if (!(n2->mn_flags & F_SUBDATA))
6709 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
6714 mc->mc_db->md_entries--;
6715 mc->mc_flags |= C_DEL;
6718 /* otherwise fall thru and delete the sub-DB */
6721 if (leaf->mn_flags & F_SUBDATA) {
6722 /* add all the child DB's pages to the free list */
6723 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6728 /* LMDB passes F_SUBDATA in 'flags' to delete a DB record */
6729 else if ((leaf->mn_flags ^ flags) & F_SUBDATA) {
6730 rc = MDB_INCOMPATIBLE;
6734 /* add overflow pages to free list */
6735 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6739 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
6740 if ((rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL)) ||
6741 (rc = mdb_ovpage_free(mc, omp)))
6746 return mdb_cursor_del0(mc);
6749 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6753 /** Allocate and initialize new pages for a database.
6754 * @param[in] mc a cursor on the database being added to.
6755 * @param[in] flags flags defining what type of page is being allocated.
6756 * @param[in] num the number of pages to allocate. This is usually 1,
6757 * unless allocating overflow pages for a large record.
6758 * @param[out] mp Address of a page, or NULL on failure.
6759 * @return 0 on success, non-zero on failure.
6762 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
6767 if ((rc = mdb_page_alloc(mc, num, &np)))
6769 DPRINTF(("allocated new mpage %"Z"u, page size %u",
6770 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
6771 np->mp_flags = flags | P_DIRTY;
6772 np->mp_lower = (PAGEHDRSZ-PAGEBASE);
6773 np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
6776 mc->mc_db->md_branch_pages++;
6777 else if (IS_LEAF(np))
6778 mc->mc_db->md_leaf_pages++;
6779 else if (IS_OVERFLOW(np)) {
6780 mc->mc_db->md_overflow_pages += num;
6788 /** Calculate the size of a leaf node.
6789 * The size depends on the environment's page size; if a data item
6790 * is too large it will be put onto an overflow page and the node
6791 * size will only include the key and not the data. Sizes are always
6792 * rounded up to an even number of bytes, to guarantee 2-byte alignment
6793 * of the #MDB_node headers.
6794 * @param[in] env The environment handle.
6795 * @param[in] key The key for the node.
6796 * @param[in] data The data for the node.
6797 * @return The number of bytes needed to store the node.
6800 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
6804 sz = LEAFSIZE(key, data);
6805 if (sz > env->me_nodemax) {
6806 /* put on overflow page */
6807 sz -= data->mv_size - sizeof(pgno_t);
6810 return EVEN(sz + sizeof(indx_t));
6813 /** Calculate the size of a branch node.
6814 * The size should depend on the environment's page size but since
6815 * we currently don't support spilling large keys onto overflow
6816 * pages, it's simply the size of the #MDB_node header plus the
6817 * size of the key. Sizes are always rounded up to an even number
6818 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
6819 * @param[in] env The environment handle.
6820 * @param[in] key The key for the node.
6821 * @return The number of bytes needed to store the node.
6824 mdb_branch_size(MDB_env *env, MDB_val *key)
6829 if (sz > env->me_nodemax) {
6830 /* put on overflow page */
6831 /* not implemented */
6832 /* sz -= key->size - sizeof(pgno_t); */
6835 return sz + sizeof(indx_t);
6838 /** Add a node to the page pointed to by the cursor.
6839 * @param[in] mc The cursor for this operation.
6840 * @param[in] indx The index on the page where the new node should be added.
6841 * @param[in] key The key for the new node.
6842 * @param[in] data The data for the new node, if any.
6843 * @param[in] pgno The page number, if adding a branch node.
6844 * @param[in] flags Flags for the node.
6845 * @return 0 on success, non-zero on failure. Possible errors are:
6847 * <li>ENOMEM - failed to allocate overflow pages for the node.
6848 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
6849 * should never happen since all callers already calculate the
6850 * page's free space before calling this function.
6854 mdb_node_add(MDB_cursor *mc, indx_t indx,
6855 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
6858 size_t node_size = NODESIZE;
6862 MDB_page *mp = mc->mc_pg[mc->mc_top];
6863 MDB_page *ofp = NULL; /* overflow page */
6866 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
6868 DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
6869 IS_LEAF(mp) ? "leaf" : "branch",
6870 IS_SUBP(mp) ? "sub-" : "",
6871 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
6872 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
6875 /* Move higher keys up one slot. */
6876 int ksize = mc->mc_db->md_pad, dif;
6877 char *ptr = LEAF2KEY(mp, indx, ksize);
6878 dif = NUMKEYS(mp) - indx;
6880 memmove(ptr+ksize, ptr, dif*ksize);
6881 /* insert new key */
6882 memcpy(ptr, key->mv_data, ksize);
6884 /* Just using these for counting */
6885 mp->mp_lower += sizeof(indx_t);
6886 mp->mp_upper -= ksize - sizeof(indx_t);
6890 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
6892 node_size += key->mv_size;
6894 mdb_cassert(mc, data);
6895 if (F_ISSET(flags, F_BIGDATA)) {
6896 /* Data already on overflow page. */
6897 node_size += sizeof(pgno_t);
6898 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
6899 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
6901 /* Put data on overflow page. */
6902 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
6903 data->mv_size, node_size+data->mv_size));
6904 node_size = EVEN(node_size + sizeof(pgno_t));
6905 if ((ssize_t)node_size > room)
6907 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
6909 DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
6913 node_size += data->mv_size;
6916 node_size = EVEN(node_size);
6917 if ((ssize_t)node_size > room)
6921 /* Move higher pointers up one slot. */
6922 for (i = NUMKEYS(mp); i > indx; i--)
6923 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
6925 /* Adjust free space offsets. */
6926 ofs = mp->mp_upper - node_size;
6927 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
6928 mp->mp_ptrs[indx] = ofs;
6930 mp->mp_lower += sizeof(indx_t);
6932 /* Write the node data. */
6933 node = NODEPTR(mp, indx);
6934 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
6935 node->mn_flags = flags;
6937 SETDSZ(node,data->mv_size);
6942 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6945 mdb_cassert(mc, key);
6947 if (F_ISSET(flags, F_BIGDATA))
6948 memcpy(node->mn_data + key->mv_size, data->mv_data,
6950 else if (F_ISSET(flags, MDB_RESERVE))
6951 data->mv_data = node->mn_data + key->mv_size;
6953 memcpy(node->mn_data + key->mv_size, data->mv_data,
6956 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
6958 if (F_ISSET(flags, MDB_RESERVE))
6959 data->mv_data = METADATA(ofp);
6961 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
6968 DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
6969 mdb_dbg_pgno(mp), NUMKEYS(mp)));
6970 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
6971 DPRINTF(("node size = %"Z"u", node_size));
6972 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6973 return MDB_PAGE_FULL;
6976 /** Delete the specified node from a page.
6977 * @param[in] mc Cursor pointing to the node to delete.
6978 * @param[in] ksize The size of a node. Only used if the page is
6979 * part of a #MDB_DUPFIXED database.
6982 mdb_node_del(MDB_cursor *mc, int ksize)
6984 MDB_page *mp = mc->mc_pg[mc->mc_top];
6985 indx_t indx = mc->mc_ki[mc->mc_top];
6987 indx_t i, j, numkeys, ptr;
6991 DPRINTF(("delete node %u on %s page %"Z"u", indx,
6992 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
6993 numkeys = NUMKEYS(mp);
6994 mdb_cassert(mc, indx < numkeys);
6997 int x = numkeys - 1 - indx;
6998 base = LEAF2KEY(mp, indx, ksize);
7000 memmove(base, base + ksize, x * ksize);
7001 mp->mp_lower -= sizeof(indx_t);
7002 mp->mp_upper += ksize - sizeof(indx_t);
7006 node = NODEPTR(mp, indx);
7007 sz = NODESIZE + node->mn_ksize;
7009 if (F_ISSET(node->mn_flags, F_BIGDATA))
7010 sz += sizeof(pgno_t);
7012 sz += NODEDSZ(node);
7016 ptr = mp->mp_ptrs[indx];
7017 for (i = j = 0; i < numkeys; i++) {
7019 mp->mp_ptrs[j] = mp->mp_ptrs[i];
7020 if (mp->mp_ptrs[i] < ptr)
7021 mp->mp_ptrs[j] += sz;
7026 base = (char *)mp + mp->mp_upper + PAGEBASE;
7027 memmove(base + sz, base, ptr - mp->mp_upper);
7029 mp->mp_lower -= sizeof(indx_t);
7033 /** Compact the main page after deleting a node on a subpage.
7034 * @param[in] mp The main page to operate on.
7035 * @param[in] indx The index of the subpage on the main page.
7038 mdb_node_shrink(MDB_page *mp, indx_t indx)
7044 indx_t i, numkeys, ptr;
7046 node = NODEPTR(mp, indx);
7047 sp = (MDB_page *)NODEDATA(node);
7048 delta = SIZELEFT(sp);
7049 xp = (MDB_page *)((char *)sp + delta);
7051 /* shift subpage upward */
7053 nsize = NUMKEYS(sp) * sp->mp_pad;
7055 return; /* do not make the node uneven-sized */
7056 memmove(METADATA(xp), METADATA(sp), nsize);
7059 numkeys = NUMKEYS(sp);
7060 for (i=numkeys-1; i>=0; i--)
7061 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
7063 xp->mp_upper = sp->mp_lower;
7064 xp->mp_lower = sp->mp_lower;
7065 xp->mp_flags = sp->mp_flags;
7066 xp->mp_pad = sp->mp_pad;
7067 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
7069 nsize = NODEDSZ(node) - delta;
7070 SETDSZ(node, nsize);
7072 /* shift lower nodes upward */
7073 ptr = mp->mp_ptrs[indx];
7074 numkeys = NUMKEYS(mp);
7075 for (i = 0; i < numkeys; i++) {
7076 if (mp->mp_ptrs[i] <= ptr)
7077 mp->mp_ptrs[i] += delta;
7080 base = (char *)mp + mp->mp_upper + PAGEBASE;
7081 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
7082 mp->mp_upper += delta;
7085 /** Initial setup of a sorted-dups cursor.
7086 * Sorted duplicates are implemented as a sub-database for the given key.
7087 * The duplicate data items are actually keys of the sub-database.
7088 * Operations on the duplicate data items are performed using a sub-cursor
7089 * initialized when the sub-database is first accessed. This function does
7090 * the preliminary setup of the sub-cursor, filling in the fields that
7091 * depend only on the parent DB.
7092 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
7095 mdb_xcursor_init0(MDB_cursor *mc)
7097 MDB_xcursor *mx = mc->mc_xcursor;
7099 mx->mx_cursor.mc_xcursor = NULL;
7100 mx->mx_cursor.mc_txn = mc->mc_txn;
7101 mx->mx_cursor.mc_db = &mx->mx_db;
7102 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
7103 mx->mx_cursor.mc_dbi = mc->mc_dbi;
7104 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
7105 mx->mx_cursor.mc_snum = 0;
7106 mx->mx_cursor.mc_top = 0;
7107 mx->mx_cursor.mc_flags = C_SUB;
7108 mx->mx_dbx.md_name.mv_size = 0;
7109 mx->mx_dbx.md_name.mv_data = NULL;
7110 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
7111 mx->mx_dbx.md_dcmp = NULL;
7112 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
7115 /** Final setup of a sorted-dups cursor.
7116 * Sets up the fields that depend on the data from the main cursor.
7117 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
7118 * @param[in] node The data containing the #MDB_db record for the
7119 * sorted-dup database.
7122 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
7124 MDB_xcursor *mx = mc->mc_xcursor;
7126 if (node->mn_flags & F_SUBDATA) {
7127 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
7128 mx->mx_cursor.mc_pg[0] = 0;
7129 mx->mx_cursor.mc_snum = 0;
7130 mx->mx_cursor.mc_top = 0;
7131 mx->mx_cursor.mc_flags = C_SUB;
7133 MDB_page *fp = NODEDATA(node);
7134 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
7135 mx->mx_db.md_flags = 0;
7136 mx->mx_db.md_depth = 1;
7137 mx->mx_db.md_branch_pages = 0;
7138 mx->mx_db.md_leaf_pages = 1;
7139 mx->mx_db.md_overflow_pages = 0;
7140 mx->mx_db.md_entries = NUMKEYS(fp);
7141 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
7142 mx->mx_cursor.mc_snum = 1;
7143 mx->mx_cursor.mc_top = 0;
7144 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
7145 mx->mx_cursor.mc_pg[0] = fp;
7146 mx->mx_cursor.mc_ki[0] = 0;
7147 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7148 mx->mx_db.md_flags = MDB_DUPFIXED;
7149 mx->mx_db.md_pad = fp->mp_pad;
7150 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
7151 mx->mx_db.md_flags |= MDB_INTEGERKEY;
7154 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
7155 mx->mx_db.md_root));
7156 mx->mx_dbflag = DB_VALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
7157 #if UINT_MAX < SIZE_MAX
7158 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
7159 mx->mx_dbx.md_cmp = mdb_cmp_clong;
7164 /** Fixup a sorted-dups cursor due to underlying update.
7165 * Sets up some fields that depend on the data from the main cursor.
7166 * Almost the same as init1, but skips initialization steps if the
7167 * xcursor had already been used.
7168 * @param[in] mc The main cursor whose sorted-dups cursor is to be fixed up.
7169 * @param[in] src_mx The xcursor of an up-to-date cursor.
7170 * @param[in] new_dupdata True if converting from a non-#F_DUPDATA item.
7173 mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int new_dupdata)
7175 MDB_xcursor *mx = mc->mc_xcursor;
7178 mx->mx_cursor.mc_snum = 1;
7179 mx->mx_cursor.mc_top = 0;
7180 mx->mx_cursor.mc_flags |= C_INITIALIZED;
7181 mx->mx_cursor.mc_ki[0] = 0;
7182 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
7183 #if UINT_MAX < SIZE_MAX
7184 mx->mx_dbx.md_cmp = src_mx->mx_dbx.md_cmp;
7186 } else if (!(mx->mx_cursor.mc_flags & C_INITIALIZED)) {
7189 mx->mx_db = src_mx->mx_db;
7190 mx->mx_cursor.mc_pg[0] = src_mx->mx_cursor.mc_pg[0];
7191 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
7192 mx->mx_db.md_root));
7195 /** Initialize a cursor for a given transaction and database. */
7197 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
7200 mc->mc_backup = NULL;
7203 mc->mc_db = &txn->mt_dbs[dbi];
7204 mc->mc_dbx = &txn->mt_dbxs[dbi];
7205 mc->mc_dbflag = &txn->mt_dbflags[dbi];
7211 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
7212 mdb_tassert(txn, mx != NULL);
7213 mc->mc_xcursor = mx;
7214 mdb_xcursor_init0(mc);
7216 mc->mc_xcursor = NULL;
7218 if (*mc->mc_dbflag & DB_STALE) {
7219 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
7224 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
7227 size_t size = sizeof(MDB_cursor);
7229 if (!ret || !TXN_DBI_EXIST(txn, dbi))
7232 if (txn->mt_flags & MDB_TXN_ERROR)
7235 /* Allow read access to the freelist */
7236 if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
7239 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
7240 size += sizeof(MDB_xcursor);
7242 if ((mc = malloc(size)) != NULL) {
7243 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
7244 if (txn->mt_cursors) {
7245 mc->mc_next = txn->mt_cursors[dbi];
7246 txn->mt_cursors[dbi] = mc;
7247 mc->mc_flags |= C_UNTRACK;
7259 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
7261 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi))
7264 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
7267 if (txn->mt_flags & MDB_TXN_ERROR)
7270 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
7274 /* Return the count of duplicate data items for the current key */
7276 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
7280 if (mc == NULL || countp == NULL)
7283 if (mc->mc_xcursor == NULL)
7284 return MDB_INCOMPATIBLE;
7286 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
7289 if (!(mc->mc_flags & C_INITIALIZED))
7292 if (!mc->mc_snum || (mc->mc_flags & C_EOF))
7293 return MDB_NOTFOUND;
7295 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7296 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7299 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
7302 *countp = mc->mc_xcursor->mx_db.md_entries;
7308 mdb_cursor_close(MDB_cursor *mc)
7310 if (mc && !mc->mc_backup) {
7311 /* remove from txn, if tracked */
7312 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
7313 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
7314 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
7316 *prev = mc->mc_next;
7323 mdb_cursor_txn(MDB_cursor *mc)
7325 if (!mc) return NULL;
7330 mdb_cursor_dbi(MDB_cursor *mc)
7335 /** Replace the key for a branch node with a new key.
7336 * @param[in] mc Cursor pointing to the node to operate on.
7337 * @param[in] key The new key to use.
7338 * @return 0 on success, non-zero on failure.
7341 mdb_update_key(MDB_cursor *mc, MDB_val *key)
7347 int delta, ksize, oksize;
7348 indx_t ptr, i, numkeys, indx;
7351 indx = mc->mc_ki[mc->mc_top];
7352 mp = mc->mc_pg[mc->mc_top];
7353 node = NODEPTR(mp, indx);
7354 ptr = mp->mp_ptrs[indx];
7358 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
7359 k2.mv_data = NODEKEY(node);
7360 k2.mv_size = node->mn_ksize;
7361 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
7363 mdb_dkey(&k2, kbuf2),
7369 /* Sizes must be 2-byte aligned. */
7370 ksize = EVEN(key->mv_size);
7371 oksize = EVEN(node->mn_ksize);
7372 delta = ksize - oksize;
7374 /* Shift node contents if EVEN(key length) changed. */
7376 if (delta > 0 && SIZELEFT(mp) < delta) {
7378 /* not enough space left, do a delete and split */
7379 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
7380 pgno = NODEPGNO(node);
7381 mdb_node_del(mc, 0);
7382 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
7385 numkeys = NUMKEYS(mp);
7386 for (i = 0; i < numkeys; i++) {
7387 if (mp->mp_ptrs[i] <= ptr)
7388 mp->mp_ptrs[i] -= delta;
7391 base = (char *)mp + mp->mp_upper + PAGEBASE;
7392 len = ptr - mp->mp_upper + NODESIZE;
7393 memmove(base - delta, base, len);
7394 mp->mp_upper -= delta;
7396 node = NODEPTR(mp, indx);
7399 /* But even if no shift was needed, update ksize */
7400 if (node->mn_ksize != key->mv_size)
7401 node->mn_ksize = key->mv_size;
7404 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7410 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
7412 /** Move a node from csrc to cdst.
7415 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
7422 unsigned short flags;
7426 /* Mark src and dst as dirty. */
7427 if ((rc = mdb_page_touch(csrc)) ||
7428 (rc = mdb_page_touch(cdst)))
7431 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7432 key.mv_size = csrc->mc_db->md_pad;
7433 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
7435 data.mv_data = NULL;
7439 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
7440 mdb_cassert(csrc, !((size_t)srcnode & 1));
7441 srcpg = NODEPGNO(srcnode);
7442 flags = srcnode->mn_flags;
7443 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7444 unsigned int snum = csrc->mc_snum;
7446 /* must find the lowest key below src */
7447 rc = mdb_page_search_lowest(csrc);
7450 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7451 key.mv_size = csrc->mc_db->md_pad;
7452 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7454 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7455 key.mv_size = NODEKSZ(s2);
7456 key.mv_data = NODEKEY(s2);
7458 csrc->mc_snum = snum--;
7459 csrc->mc_top = snum;
7461 key.mv_size = NODEKSZ(srcnode);
7462 key.mv_data = NODEKEY(srcnode);
7464 data.mv_size = NODEDSZ(srcnode);
7465 data.mv_data = NODEDATA(srcnode);
7467 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
7468 unsigned int snum = cdst->mc_snum;
7471 /* must find the lowest key below dst */
7472 mdb_cursor_copy(cdst, &mn);
7473 rc = mdb_page_search_lowest(&mn);
7476 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7477 bkey.mv_size = mn.mc_db->md_pad;
7478 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
7480 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7481 bkey.mv_size = NODEKSZ(s2);
7482 bkey.mv_data = NODEKEY(s2);
7484 mn.mc_snum = snum--;
7487 rc = mdb_update_key(&mn, &bkey);
7492 DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
7493 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
7494 csrc->mc_ki[csrc->mc_top],
7496 csrc->mc_pg[csrc->mc_top]->mp_pgno,
7497 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
7499 /* Add the node to the destination page.
7501 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
7502 if (rc != MDB_SUCCESS)
7505 /* Delete the node from the source page.
7507 mdb_node_del(csrc, key.mv_size);
7510 /* Adjust other cursors pointing to mp */
7511 MDB_cursor *m2, *m3;
7512 MDB_dbi dbi = csrc->mc_dbi;
7515 mp = cdst->mc_pg[csrc->mc_top];
7516 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7517 if (csrc->mc_flags & C_SUB)
7518 m3 = &m2->mc_xcursor->mx_cursor;
7521 if (m3 == cdst) continue;
7522 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] >=
7523 cdst->mc_ki[csrc->mc_top]) {
7524 m3->mc_ki[csrc->mc_top]++;
7528 mp = csrc->mc_pg[csrc->mc_top];
7529 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7530 if (csrc->mc_flags & C_SUB)
7531 m3 = &m2->mc_xcursor->mx_cursor;
7534 if (m3 == csrc) continue;
7535 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
7536 csrc->mc_ki[csrc->mc_top]) {
7537 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
7538 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7543 /* Update the parent separators.
7545 if (csrc->mc_ki[csrc->mc_top] == 0) {
7546 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
7547 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7548 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7550 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7551 key.mv_size = NODEKSZ(srcnode);
7552 key.mv_data = NODEKEY(srcnode);
7554 DPRINTF(("update separator for source page %"Z"u to [%s]",
7555 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
7556 mdb_cursor_copy(csrc, &mn);
7559 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7562 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7564 indx_t ix = csrc->mc_ki[csrc->mc_top];
7565 nullkey.mv_size = 0;
7566 csrc->mc_ki[csrc->mc_top] = 0;
7567 rc = mdb_update_key(csrc, &nullkey);
7568 csrc->mc_ki[csrc->mc_top] = ix;
7569 mdb_cassert(csrc, rc == MDB_SUCCESS);
7573 if (cdst->mc_ki[cdst->mc_top] == 0) {
7574 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
7575 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7576 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
7578 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
7579 key.mv_size = NODEKSZ(srcnode);
7580 key.mv_data = NODEKEY(srcnode);
7582 DPRINTF(("update separator for destination page %"Z"u to [%s]",
7583 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
7584 mdb_cursor_copy(cdst, &mn);
7587 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7590 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
7592 indx_t ix = cdst->mc_ki[cdst->mc_top];
7593 nullkey.mv_size = 0;
7594 cdst->mc_ki[cdst->mc_top] = 0;
7595 rc = mdb_update_key(cdst, &nullkey);
7596 cdst->mc_ki[cdst->mc_top] = ix;
7597 mdb_cassert(cdst, rc == MDB_SUCCESS);
7604 /** Merge one page into another.
7605 * The nodes from the page pointed to by \b csrc will
7606 * be copied to the page pointed to by \b cdst and then
7607 * the \b csrc page will be freed.
7608 * @param[in] csrc Cursor pointing to the source page.
7609 * @param[in] cdst Cursor pointing to the destination page.
7610 * @return 0 on success, non-zero on failure.
7613 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
7615 MDB_page *psrc, *pdst;
7622 psrc = csrc->mc_pg[csrc->mc_top];
7623 pdst = cdst->mc_pg[cdst->mc_top];
7625 DPRINTF(("merging page %"Z"u into %"Z"u", psrc->mp_pgno, pdst->mp_pgno));
7627 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
7628 mdb_cassert(csrc, cdst->mc_snum > 1);
7630 /* Mark dst as dirty. */
7631 if ((rc = mdb_page_touch(cdst)))
7634 /* Move all nodes from src to dst.
7636 j = nkeys = NUMKEYS(pdst);
7637 if (IS_LEAF2(psrc)) {
7638 key.mv_size = csrc->mc_db->md_pad;
7639 key.mv_data = METADATA(psrc);
7640 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7641 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
7642 if (rc != MDB_SUCCESS)
7644 key.mv_data = (char *)key.mv_data + key.mv_size;
7647 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7648 srcnode = NODEPTR(psrc, i);
7649 if (i == 0 && IS_BRANCH(psrc)) {
7652 mdb_cursor_copy(csrc, &mn);
7653 /* must find the lowest key below src */
7654 rc = mdb_page_search_lowest(&mn);
7657 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7658 key.mv_size = mn.mc_db->md_pad;
7659 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
7661 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7662 key.mv_size = NODEKSZ(s2);
7663 key.mv_data = NODEKEY(s2);
7666 key.mv_size = srcnode->mn_ksize;
7667 key.mv_data = NODEKEY(srcnode);
7670 data.mv_size = NODEDSZ(srcnode);
7671 data.mv_data = NODEDATA(srcnode);
7672 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
7673 if (rc != MDB_SUCCESS)
7678 DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
7679 pdst->mp_pgno, NUMKEYS(pdst),
7680 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
7682 /* Unlink the src page from parent and add to free list.
7685 mdb_node_del(csrc, 0);
7686 if (csrc->mc_ki[csrc->mc_top] == 0) {
7688 rc = mdb_update_key(csrc, &key);
7696 psrc = csrc->mc_pg[csrc->mc_top];
7697 /* If not operating on FreeDB, allow this page to be reused
7698 * in this txn. Otherwise just add to free list.
7700 rc = mdb_page_loose(csrc, psrc);
7704 csrc->mc_db->md_leaf_pages--;
7706 csrc->mc_db->md_branch_pages--;
7708 /* Adjust other cursors pointing to mp */
7709 MDB_cursor *m2, *m3;
7710 MDB_dbi dbi = csrc->mc_dbi;
7712 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7713 if (csrc->mc_flags & C_SUB)
7714 m3 = &m2->mc_xcursor->mx_cursor;
7717 if (m3 == csrc) continue;
7718 if (m3->mc_snum < csrc->mc_snum) continue;
7719 if (m3->mc_pg[csrc->mc_top] == psrc) {
7720 m3->mc_pg[csrc->mc_top] = pdst;
7721 m3->mc_ki[csrc->mc_top] += nkeys;
7726 unsigned int snum = cdst->mc_snum;
7727 uint16_t depth = cdst->mc_db->md_depth;
7728 mdb_cursor_pop(cdst);
7729 rc = mdb_rebalance(cdst);
7730 /* Did the tree height change? */
7731 if (depth != cdst->mc_db->md_depth)
7732 snum += cdst->mc_db->md_depth - depth;
7733 cdst->mc_snum = snum;
7734 cdst->mc_top = snum-1;
7739 /** Copy the contents of a cursor.
7740 * @param[in] csrc The cursor to copy from.
7741 * @param[out] cdst The cursor to copy to.
7744 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
7748 cdst->mc_txn = csrc->mc_txn;
7749 cdst->mc_dbi = csrc->mc_dbi;
7750 cdst->mc_db = csrc->mc_db;
7751 cdst->mc_dbx = csrc->mc_dbx;
7752 cdst->mc_snum = csrc->mc_snum;
7753 cdst->mc_top = csrc->mc_top;
7754 cdst->mc_flags = csrc->mc_flags;
7756 for (i=0; i<csrc->mc_snum; i++) {
7757 cdst->mc_pg[i] = csrc->mc_pg[i];
7758 cdst->mc_ki[i] = csrc->mc_ki[i];
7762 /** Rebalance the tree after a delete operation.
7763 * @param[in] mc Cursor pointing to the page where rebalancing
7765 * @return 0 on success, non-zero on failure.
7768 mdb_rebalance(MDB_cursor *mc)
7772 unsigned int ptop, minkeys, thresh;
7776 if (IS_BRANCH(mc->mc_pg[mc->mc_top])) {
7781 thresh = FILL_THRESHOLD;
7783 DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
7784 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
7785 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
7786 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
7788 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= thresh &&
7789 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
7790 DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
7791 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
7795 if (mc->mc_snum < 2) {
7796 MDB_page *mp = mc->mc_pg[0];
7798 DPUTS("Can't rebalance a subpage, ignoring");
7801 if (NUMKEYS(mp) == 0) {
7802 DPUTS("tree is completely empty");
7803 mc->mc_db->md_root = P_INVALID;
7804 mc->mc_db->md_depth = 0;
7805 mc->mc_db->md_leaf_pages = 0;
7806 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7809 /* Adjust cursors pointing to mp */
7812 mc->mc_flags &= ~C_INITIALIZED;
7814 MDB_cursor *m2, *m3;
7815 MDB_dbi dbi = mc->mc_dbi;
7817 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7818 if (mc->mc_flags & C_SUB)
7819 m3 = &m2->mc_xcursor->mx_cursor;
7822 if (m3->mc_snum < mc->mc_snum) continue;
7823 if (m3->mc_pg[0] == mp) {
7826 m3->mc_flags &= ~C_INITIALIZED;
7830 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
7832 DPUTS("collapsing root page!");
7833 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7836 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
7837 rc = mdb_page_get(mc->mc_txn,mc->mc_db->md_root,&mc->mc_pg[0],NULL);
7840 mc->mc_db->md_depth--;
7841 mc->mc_db->md_branch_pages--;
7842 mc->mc_ki[0] = mc->mc_ki[1];
7843 for (i = 1; i<mc->mc_db->md_depth; i++) {
7844 mc->mc_pg[i] = mc->mc_pg[i+1];
7845 mc->mc_ki[i] = mc->mc_ki[i+1];
7848 /* Adjust other cursors pointing to mp */
7849 MDB_cursor *m2, *m3;
7850 MDB_dbi dbi = mc->mc_dbi;
7852 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7853 if (mc->mc_flags & C_SUB)
7854 m3 = &m2->mc_xcursor->mx_cursor;
7857 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
7858 if (m3->mc_pg[0] == mp) {
7859 for (i=0; i<m3->mc_snum; i++) {
7860 m3->mc_pg[i] = m3->mc_pg[i+1];
7861 m3->mc_ki[i] = m3->mc_ki[i+1];
7869 DPUTS("root page doesn't need rebalancing");
7873 /* The parent (branch page) must have at least 2 pointers,
7874 * otherwise the tree is invalid.
7876 ptop = mc->mc_top-1;
7877 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
7879 /* Leaf page fill factor is below the threshold.
7880 * Try to move keys from left or right neighbor, or
7881 * merge with a neighbor page.
7886 mdb_cursor_copy(mc, &mn);
7887 mn.mc_xcursor = NULL;
7889 oldki = mc->mc_ki[mc->mc_top];
7890 if (mc->mc_ki[ptop] == 0) {
7891 /* We're the leftmost leaf in our parent.
7893 DPUTS("reading right neighbor");
7895 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7896 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7899 mn.mc_ki[mn.mc_top] = 0;
7900 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
7902 /* There is at least one neighbor to the left.
7904 DPUTS("reading left neighbor");
7906 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7907 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7910 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
7911 mc->mc_ki[mc->mc_top] = 0;
7914 DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
7915 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
7916 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
7918 /* If the neighbor page is above threshold and has enough keys,
7919 * move one key from it. Otherwise we should try to merge them.
7920 * (A branch page must never have less than 2 keys.)
7922 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= thresh && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
7923 rc = mdb_node_move(&mn, mc);
7924 if (mc->mc_ki[mc->mc_top-1]) {
7928 if (mc->mc_ki[ptop] == 0) {
7929 rc = mdb_page_merge(&mn, mc);
7932 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
7933 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
7934 /* We want mdb_rebalance to find mn when doing fixups */
7935 if (mc->mc_flags & C_SUB) {
7936 dummy.mc_next = mc->mc_txn->mt_cursors[mc->mc_dbi];
7937 mc->mc_txn->mt_cursors[mc->mc_dbi] = &dummy;
7938 dummy.mc_xcursor = (MDB_xcursor *)&mn;
7940 mn.mc_next = mc->mc_txn->mt_cursors[mc->mc_dbi];
7941 mc->mc_txn->mt_cursors[mc->mc_dbi] = &mn;
7943 rc = mdb_page_merge(mc, &mn);
7944 if (mc->mc_flags & C_SUB)
7945 mc->mc_txn->mt_cursors[mc->mc_dbi] = dummy.mc_next;
7947 mc->mc_txn->mt_cursors[mc->mc_dbi] = mn.mc_next;
7948 mdb_cursor_copy(&mn, mc);
7950 mc->mc_flags &= ~C_EOF;
7952 mc->mc_ki[mc->mc_top] = oldki;
7956 /** Complete a delete operation started by #mdb_cursor_del(). */
7958 mdb_cursor_del0(MDB_cursor *mc)
7964 MDB_cursor *m2, *m3;
7965 MDB_dbi dbi = mc->mc_dbi;
7967 ki = mc->mc_ki[mc->mc_top];
7968 mp = mc->mc_pg[mc->mc_top];
7969 mdb_node_del(mc, mc->mc_db->md_pad);
7970 mc->mc_db->md_entries--;
7972 /* Adjust other cursors pointing to mp */
7973 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7974 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
7975 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
7977 if (m3 == mc || m3->mc_snum < mc->mc_snum)
7979 if (m3->mc_pg[mc->mc_top] == mp) {
7980 if (m3->mc_ki[mc->mc_top] >= ki) {
7981 m3->mc_flags |= C_DEL;
7982 if (m3->mc_ki[mc->mc_top] > ki)
7983 m3->mc_ki[mc->mc_top]--;
7984 else if (mc->mc_db->md_flags & MDB_DUPSORT)
7985 m3->mc_xcursor->mx_cursor.mc_flags |= C_EOF;
7990 rc = mdb_rebalance(mc);
7992 if (rc == MDB_SUCCESS) {
7993 /* DB is totally empty now, just bail out.
7994 * Other cursors adjustments were already done
7995 * by mdb_rebalance and aren't needed here.
8000 mp = mc->mc_pg[mc->mc_top];
8001 nkeys = NUMKEYS(mp);
8003 /* Adjust other cursors pointing to mp */
8004 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
8005 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
8006 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8008 if (m3->mc_snum < mc->mc_snum)
8010 if (m3->mc_pg[mc->mc_top] == mp) {
8011 /* if m3 points past last node in page, find next sibling */
8012 if (m3->mc_ki[mc->mc_top] >= nkeys) {
8013 rc = mdb_cursor_sibling(m3, 1);
8014 if (rc == MDB_NOTFOUND) {
8015 m3->mc_flags |= C_EOF;
8021 mc->mc_flags |= C_DEL;
8025 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8030 mdb_del(MDB_txn *txn, MDB_dbi dbi,
8031 MDB_val *key, MDB_val *data)
8033 if (!key || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
8036 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
8037 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
8039 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
8040 /* must ignore any data */
8044 return mdb_del0(txn, dbi, key, data, 0);
8048 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
8049 MDB_val *key, MDB_val *data, unsigned flags)
8054 MDB_val rdata, *xdata;
8058 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
8060 mdb_cursor_init(&mc, txn, dbi, &mx);
8069 flags |= MDB_NODUPDATA;
8071 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
8073 /* let mdb_page_split know about this cursor if needed:
8074 * delete will trigger a rebalance; if it needs to move
8075 * a node from one page to another, it will have to
8076 * update the parent's separator key(s). If the new sepkey
8077 * is larger than the current one, the parent page may
8078 * run out of space, triggering a split. We need this
8079 * cursor to be consistent until the end of the rebalance.
8081 mc.mc_flags |= C_UNTRACK;
8082 mc.mc_next = txn->mt_cursors[dbi];
8083 txn->mt_cursors[dbi] = &mc;
8084 rc = mdb_cursor_del(&mc, flags);
8085 txn->mt_cursors[dbi] = mc.mc_next;
8090 /** Split a page and insert a new node.
8091 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
8092 * The cursor will be updated to point to the actual page and index where
8093 * the node got inserted after the split.
8094 * @param[in] newkey The key for the newly inserted node.
8095 * @param[in] newdata The data for the newly inserted node.
8096 * @param[in] newpgno The page number, if the new node is a branch node.
8097 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
8098 * @return 0 on success, non-zero on failure.
8101 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
8102 unsigned int nflags)
8105 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
8108 int i, j, split_indx, nkeys, pmax;
8109 MDB_env *env = mc->mc_txn->mt_env;
8111 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
8112 MDB_page *copy = NULL;
8113 MDB_page *mp, *rp, *pp;
8118 mp = mc->mc_pg[mc->mc_top];
8119 newindx = mc->mc_ki[mc->mc_top];
8120 nkeys = NUMKEYS(mp);
8122 DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i/%i",
8123 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
8124 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
8126 /* Create a right sibling. */
8127 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
8129 DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
8131 if (mc->mc_snum < 2) {
8132 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
8134 /* shift current top to make room for new parent */
8135 mc->mc_pg[1] = mc->mc_pg[0];
8136 mc->mc_ki[1] = mc->mc_ki[0];
8139 mc->mc_db->md_root = pp->mp_pgno;
8140 DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
8141 new_root = mc->mc_db->md_depth++;
8143 /* Add left (implicit) pointer. */
8144 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
8145 /* undo the pre-push */
8146 mc->mc_pg[0] = mc->mc_pg[1];
8147 mc->mc_ki[0] = mc->mc_ki[1];
8148 mc->mc_db->md_root = mp->mp_pgno;
8149 mc->mc_db->md_depth--;
8156 ptop = mc->mc_top-1;
8157 DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
8160 mc->mc_flags |= C_SPLITTING;
8161 mdb_cursor_copy(mc, &mn);
8162 mn.mc_pg[mn.mc_top] = rp;
8163 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
8165 if (nflags & MDB_APPEND) {
8166 mn.mc_ki[mn.mc_top] = 0;
8168 split_indx = newindx;
8172 split_indx = (nkeys+1) / 2;
8177 unsigned int lsize, rsize, ksize;
8178 /* Move half of the keys to the right sibling */
8179 x = mc->mc_ki[mc->mc_top] - split_indx;
8180 ksize = mc->mc_db->md_pad;
8181 split = LEAF2KEY(mp, split_indx, ksize);
8182 rsize = (nkeys - split_indx) * ksize;
8183 lsize = (nkeys - split_indx) * sizeof(indx_t);
8184 mp->mp_lower -= lsize;
8185 rp->mp_lower += lsize;
8186 mp->mp_upper += rsize - lsize;
8187 rp->mp_upper -= rsize - lsize;
8188 sepkey.mv_size = ksize;
8189 if (newindx == split_indx) {
8190 sepkey.mv_data = newkey->mv_data;
8192 sepkey.mv_data = split;
8195 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
8196 memcpy(rp->mp_ptrs, split, rsize);
8197 sepkey.mv_data = rp->mp_ptrs;
8198 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
8199 memcpy(ins, newkey->mv_data, ksize);
8200 mp->mp_lower += sizeof(indx_t);
8201 mp->mp_upper -= ksize - sizeof(indx_t);
8204 memcpy(rp->mp_ptrs, split, x * ksize);
8205 ins = LEAF2KEY(rp, x, ksize);
8206 memcpy(ins, newkey->mv_data, ksize);
8207 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
8208 rp->mp_lower += sizeof(indx_t);
8209 rp->mp_upper -= ksize - sizeof(indx_t);
8210 mc->mc_ki[mc->mc_top] = x;
8211 mc->mc_pg[mc->mc_top] = rp;
8214 int psize, nsize, k;
8215 /* Maximum free space in an empty page */
8216 pmax = env->me_psize - PAGEHDRSZ;
8218 nsize = mdb_leaf_size(env, newkey, newdata);
8220 nsize = mdb_branch_size(env, newkey);
8221 nsize = EVEN(nsize);
8223 /* grab a page to hold a temporary copy */
8224 copy = mdb_page_malloc(mc->mc_txn, 1);
8229 copy->mp_pgno = mp->mp_pgno;
8230 copy->mp_flags = mp->mp_flags;
8231 copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
8232 copy->mp_upper = env->me_psize - PAGEBASE;
8234 /* prepare to insert */
8235 for (i=0, j=0; i<nkeys; i++) {
8237 copy->mp_ptrs[j++] = 0;
8239 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
8242 /* When items are relatively large the split point needs
8243 * to be checked, because being off-by-one will make the
8244 * difference between success or failure in mdb_node_add.
8246 * It's also relevant if a page happens to be laid out
8247 * such that one half of its nodes are all "small" and
8248 * the other half of its nodes are "large." If the new
8249 * item is also "large" and falls on the half with
8250 * "large" nodes, it also may not fit.
8252 * As a final tweak, if the new item goes on the last
8253 * spot on the page (and thus, onto the new page), bias
8254 * the split so the new page is emptier than the old page.
8255 * This yields better packing during sequential inserts.
8257 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
8258 /* Find split point */
8260 if (newindx <= split_indx || newindx >= nkeys) {
8262 k = newindx >= nkeys ? nkeys : split_indx+1+IS_LEAF(mp);
8267 for (; i!=k; i+=j) {
8272 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8273 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
8275 if (F_ISSET(node->mn_flags, F_BIGDATA))
8276 psize += sizeof(pgno_t);
8278 psize += NODEDSZ(node);
8280 psize = EVEN(psize);
8282 if (psize > pmax || i == k-j) {
8283 split_indx = i + (j<0);
8288 if (split_indx == newindx) {
8289 sepkey.mv_size = newkey->mv_size;
8290 sepkey.mv_data = newkey->mv_data;
8292 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
8293 sepkey.mv_size = node->mn_ksize;
8294 sepkey.mv_data = NODEKEY(node);
8299 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
8301 /* Copy separator key to the parent.
8303 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
8307 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
8312 if (mn.mc_snum == mc->mc_snum) {
8313 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
8314 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
8315 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
8316 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
8321 /* Right page might now have changed parent.
8322 * Check if left page also changed parent.
8324 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8325 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8326 for (i=0; i<ptop; i++) {
8327 mc->mc_pg[i] = mn.mc_pg[i];
8328 mc->mc_ki[i] = mn.mc_ki[i];
8330 mc->mc_pg[ptop] = mn.mc_pg[ptop];
8331 if (mn.mc_ki[ptop]) {
8332 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
8334 /* find right page's left sibling */
8335 mc->mc_ki[ptop] = mn.mc_ki[ptop];
8336 mdb_cursor_sibling(mc, 0);
8341 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
8344 mc->mc_flags ^= C_SPLITTING;
8345 if (rc != MDB_SUCCESS) {
8348 if (nflags & MDB_APPEND) {
8349 mc->mc_pg[mc->mc_top] = rp;
8350 mc->mc_ki[mc->mc_top] = 0;
8351 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
8354 for (i=0; i<mc->mc_top; i++)
8355 mc->mc_ki[i] = mn.mc_ki[i];
8356 } else if (!IS_LEAF2(mp)) {
8358 mc->mc_pg[mc->mc_top] = rp;
8363 rkey.mv_data = newkey->mv_data;
8364 rkey.mv_size = newkey->mv_size;
8370 /* Update index for the new key. */
8371 mc->mc_ki[mc->mc_top] = j;
8373 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8374 rkey.mv_data = NODEKEY(node);
8375 rkey.mv_size = node->mn_ksize;
8377 xdata.mv_data = NODEDATA(node);
8378 xdata.mv_size = NODEDSZ(node);
8381 pgno = NODEPGNO(node);
8382 flags = node->mn_flags;
8385 if (!IS_LEAF(mp) && j == 0) {
8386 /* First branch index doesn't need key data. */
8390 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
8396 mc->mc_pg[mc->mc_top] = copy;
8401 } while (i != split_indx);
8403 nkeys = NUMKEYS(copy);
8404 for (i=0; i<nkeys; i++)
8405 mp->mp_ptrs[i] = copy->mp_ptrs[i];
8406 mp->mp_lower = copy->mp_lower;
8407 mp->mp_upper = copy->mp_upper;
8408 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
8409 env->me_psize - copy->mp_upper - PAGEBASE);
8411 /* reset back to original page */
8412 if (newindx < split_indx) {
8413 mc->mc_pg[mc->mc_top] = mp;
8414 if (nflags & MDB_RESERVE) {
8415 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
8416 if (!(node->mn_flags & F_BIGDATA))
8417 newdata->mv_data = NODEDATA(node);
8420 mc->mc_pg[mc->mc_top] = rp;
8422 /* Make sure mc_ki is still valid.
8424 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8425 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8426 for (i=0; i<=ptop; i++) {
8427 mc->mc_pg[i] = mn.mc_pg[i];
8428 mc->mc_ki[i] = mn.mc_ki[i];
8435 /* Adjust other cursors pointing to mp */
8436 MDB_cursor *m2, *m3;
8437 MDB_dbi dbi = mc->mc_dbi;
8438 int fixup = NUMKEYS(mp);
8440 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8441 if (mc->mc_flags & C_SUB)
8442 m3 = &m2->mc_xcursor->mx_cursor;
8447 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8449 if (m3->mc_flags & C_SPLITTING)
8454 for (k=new_root; k>=0; k--) {
8455 m3->mc_ki[k+1] = m3->mc_ki[k];
8456 m3->mc_pg[k+1] = m3->mc_pg[k];
8458 if (m3->mc_ki[0] >= split_indx) {
8463 m3->mc_pg[0] = mc->mc_pg[0];
8467 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
8468 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
8469 m3->mc_ki[mc->mc_top]++;
8470 if (m3->mc_ki[mc->mc_top] >= fixup) {
8471 m3->mc_pg[mc->mc_top] = rp;
8472 m3->mc_ki[mc->mc_top] -= fixup;
8473 m3->mc_ki[ptop] = mn.mc_ki[ptop];
8475 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
8476 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
8481 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
8484 if (copy) /* tmp page */
8485 mdb_page_free(env, copy);
8487 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8492 mdb_put(MDB_txn *txn, MDB_dbi dbi,
8493 MDB_val *key, MDB_val *data, unsigned int flags)
8498 if (!key || !data || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
8501 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP)) != flags)
8504 mdb_cursor_init(&mc, txn, dbi, &mx);
8505 return mdb_cursor_put(&mc, key, data, flags);
8509 #define MDB_WBUF (1024*1024)
8512 /** State needed for a compacting copy. */
8513 typedef struct mdb_copy {
8514 pthread_mutex_t mc_mutex;
8515 pthread_cond_t mc_cond;
8522 pgno_t mc_next_pgno;
8525 volatile int mc_new;
8530 /** Dedicated writer thread for compacting copy. */
8531 static THREAD_RET ESECT CALL_CONV
8532 mdb_env_copythr(void *arg)
8536 int toggle = 0, wsize, rc;
8539 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8542 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8545 pthread_mutex_lock(&my->mc_mutex);
8547 pthread_cond_signal(&my->mc_cond);
8550 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8551 if (my->mc_new < 0) {
8556 wsize = my->mc_wlen[toggle];
8557 ptr = my->mc_wbuf[toggle];
8560 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
8564 } else if (len > 0) {
8578 /* If there's an overflow page tail, write it too */
8579 if (my->mc_olen[toggle]) {
8580 wsize = my->mc_olen[toggle];
8581 ptr = my->mc_over[toggle];
8582 my->mc_olen[toggle] = 0;
8585 my->mc_wlen[toggle] = 0;
8587 pthread_cond_signal(&my->mc_cond);
8589 pthread_cond_signal(&my->mc_cond);
8590 pthread_mutex_unlock(&my->mc_mutex);
8591 return (THREAD_RET)0;
8595 /** Tell the writer thread there's a buffer ready to write */
8597 mdb_env_cthr_toggle(mdb_copy *my, int st)
8599 int toggle = my->mc_toggle ^ 1;
8600 pthread_mutex_lock(&my->mc_mutex);
8601 if (my->mc_status) {
8602 pthread_mutex_unlock(&my->mc_mutex);
8603 return my->mc_status;
8605 while (my->mc_new == 1)
8606 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8608 my->mc_toggle = toggle;
8609 pthread_cond_signal(&my->mc_cond);
8610 pthread_mutex_unlock(&my->mc_mutex);
8614 /** Depth-first tree traversal for compacting copy. */
8616 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
8619 MDB_txn *txn = my->mc_txn;
8621 MDB_page *mo, *mp, *leaf;
8626 /* Empty DB, nothing to do */
8627 if (*pg == P_INVALID)
8634 rc = mdb_page_get(my->mc_txn, *pg, &mc.mc_pg[0], NULL);
8637 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
8641 /* Make cursor pages writable */
8642 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
8646 for (i=0; i<mc.mc_top; i++) {
8647 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
8648 mc.mc_pg[i] = (MDB_page *)ptr;
8649 ptr += my->mc_env->me_psize;
8652 /* This is writable space for a leaf page. Usually not needed. */
8653 leaf = (MDB_page *)ptr;
8655 toggle = my->mc_toggle;
8656 while (mc.mc_snum > 0) {
8658 mp = mc.mc_pg[mc.mc_top];
8662 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
8663 for (i=0; i<n; i++) {
8664 ni = NODEPTR(mp, i);
8665 if (ni->mn_flags & F_BIGDATA) {
8669 /* Need writable leaf */
8671 mc.mc_pg[mc.mc_top] = leaf;
8672 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8674 ni = NODEPTR(mp, i);
8677 memcpy(&pg, NODEDATA(ni), sizeof(pg));
8678 rc = mdb_page_get(txn, pg, &omp, NULL);
8681 if (my->mc_wlen[toggle] >= MDB_WBUF) {
8682 rc = mdb_env_cthr_toggle(my, 1);
8685 toggle = my->mc_toggle;
8687 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
8688 memcpy(mo, omp, my->mc_env->me_psize);
8689 mo->mp_pgno = my->mc_next_pgno;
8690 my->mc_next_pgno += omp->mp_pages;
8691 my->mc_wlen[toggle] += my->mc_env->me_psize;
8692 if (omp->mp_pages > 1) {
8693 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
8694 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
8695 rc = mdb_env_cthr_toggle(my, 1);
8698 toggle = my->mc_toggle;
8700 memcpy(NODEDATA(ni), &mo->mp_pgno, sizeof(pgno_t));
8701 } else if (ni->mn_flags & F_SUBDATA) {
8704 /* Need writable leaf */
8706 mc.mc_pg[mc.mc_top] = leaf;
8707 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8709 ni = NODEPTR(mp, i);
8712 memcpy(&db, NODEDATA(ni), sizeof(db));
8713 my->mc_toggle = toggle;
8714 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
8717 toggle = my->mc_toggle;
8718 memcpy(NODEDATA(ni), &db, sizeof(db));
8723 mc.mc_ki[mc.mc_top]++;
8724 if (mc.mc_ki[mc.mc_top] < n) {
8727 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
8729 rc = mdb_page_get(txn, pg, &mp, NULL);
8734 mc.mc_ki[mc.mc_top] = 0;
8735 if (IS_BRANCH(mp)) {
8736 /* Whenever we advance to a sibling branch page,
8737 * we must proceed all the way down to its first leaf.
8739 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
8742 mc.mc_pg[mc.mc_top] = mp;
8746 if (my->mc_wlen[toggle] >= MDB_WBUF) {
8747 rc = mdb_env_cthr_toggle(my, 1);
8750 toggle = my->mc_toggle;
8752 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
8753 mdb_page_copy(mo, mp, my->mc_env->me_psize);
8754 mo->mp_pgno = my->mc_next_pgno++;
8755 my->mc_wlen[toggle] += my->mc_env->me_psize;
8757 /* Update parent if there is one */
8758 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
8759 SETPGNO(ni, mo->mp_pgno);
8760 mdb_cursor_pop(&mc);
8762 /* Otherwise we're done */
8772 /** Copy environment with compaction. */
8774 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
8779 MDB_txn *txn = NULL;
8784 my.mc_mutex = CreateMutex(NULL, FALSE, NULL);
8785 my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL);
8786 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_os_psize);
8787 if (my.mc_wbuf[0] == NULL)
8790 pthread_mutex_init(&my.mc_mutex, NULL);
8791 pthread_cond_init(&my.mc_cond, NULL);
8792 #ifdef HAVE_MEMALIGN
8793 my.mc_wbuf[0] = memalign(env->me_os_psize, MDB_WBUF*2);
8794 if (my.mc_wbuf[0] == NULL)
8797 rc = posix_memalign((void **)&my.mc_wbuf[0], env->me_os_psize, MDB_WBUF*2);
8802 memset(my.mc_wbuf[0], 0, MDB_WBUF*2);
8803 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
8808 my.mc_next_pgno = 2;
8814 THREAD_CREATE(thr, mdb_env_copythr, &my);
8816 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
8820 mp = (MDB_page *)my.mc_wbuf[0];
8821 memset(mp, 0, 2*env->me_psize);
8823 mp->mp_flags = P_META;
8824 mm = (MDB_meta *)METADATA(mp);
8825 mdb_env_init_meta0(env, mm);
8826 mm->mm_address = env->me_metas[0]->mm_address;
8828 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
8830 mp->mp_flags = P_META;
8831 *(MDB_meta *)METADATA(mp) = *mm;
8832 mm = (MDB_meta *)METADATA(mp);
8834 /* Count the number of free pages, subtract from lastpg to find
8835 * number of active pages
8838 MDB_ID freecount = 0;
8841 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
8842 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
8843 freecount += *(MDB_ID *)data.mv_data;
8844 freecount += txn->mt_dbs[0].md_branch_pages +
8845 txn->mt_dbs[0].md_leaf_pages +
8846 txn->mt_dbs[0].md_overflow_pages;
8848 /* Set metapage 1 */
8849 mm->mm_last_pg = txn->mt_next_pgno - freecount - 1;
8850 mm->mm_dbs[1] = txn->mt_dbs[1];
8851 if (mm->mm_last_pg > 1) {
8852 mm->mm_dbs[1].md_root = mm->mm_last_pg;
8855 mm->mm_dbs[1].md_root = P_INVALID;
8858 my.mc_wlen[0] = env->me_psize * 2;
8860 pthread_mutex_lock(&my.mc_mutex);
8862 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
8863 pthread_mutex_unlock(&my.mc_mutex);
8864 rc = mdb_env_cwalk(&my, &txn->mt_dbs[1].md_root, 0);
8865 if (rc == MDB_SUCCESS && my.mc_wlen[my.mc_toggle])
8866 rc = mdb_env_cthr_toggle(&my, 1);
8867 mdb_env_cthr_toggle(&my, -1);
8868 pthread_mutex_lock(&my.mc_mutex);
8870 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
8871 pthread_mutex_unlock(&my.mc_mutex);
8876 CloseHandle(my.mc_cond);
8877 CloseHandle(my.mc_mutex);
8878 _aligned_free(my.mc_wbuf[0]);
8880 pthread_cond_destroy(&my.mc_cond);
8881 pthread_mutex_destroy(&my.mc_mutex);
8882 free(my.mc_wbuf[0]);
8887 /** Copy environment as-is. */
8889 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
8891 MDB_txn *txn = NULL;
8897 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8901 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8904 /* Do the lock/unlock of the reader mutex before starting the
8905 * write txn. Otherwise other read txns could block writers.
8907 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
8912 /* We must start the actual read txn after blocking writers */
8913 mdb_txn_reset0(txn, "reset-stage1");
8915 /* Temporarily block writers until we snapshot the meta pages */
8918 rc = mdb_txn_renew0(txn);
8920 UNLOCK_MUTEX_W(env);
8925 wsize = env->me_psize * 2;
8929 DO_WRITE(rc, fd, ptr, w2, len);
8933 } else if (len > 0) {
8939 /* Non-blocking or async handles are not supported */
8945 UNLOCK_MUTEX_W(env);
8950 w2 = txn->mt_next_pgno * env->me_psize;
8953 if ((rc = mdb_fsize(env->me_fd, &fsize)))
8960 if (wsize > MAX_WRITE)
8964 DO_WRITE(rc, fd, ptr, w2, len);
8968 } else if (len > 0) {
8985 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
8987 if (flags & MDB_CP_COMPACT)
8988 return mdb_env_copyfd1(env, fd);
8990 return mdb_env_copyfd0(env, fd);
8994 mdb_env_copyfd(MDB_env *env, HANDLE fd)
8996 return mdb_env_copyfd2(env, fd, 0);
9000 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
9004 HANDLE newfd = INVALID_HANDLE_VALUE;
9006 if (env->me_flags & MDB_NOSUBDIR) {
9007 lpath = (char *)path;
9010 len += sizeof(DATANAME);
9011 lpath = malloc(len);
9014 sprintf(lpath, "%s" DATANAME, path);
9017 /* The destination path must exist, but the destination file must not.
9018 * We don't want the OS to cache the writes, since the source data is
9019 * already in the OS cache.
9022 newfd = CreateFile(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
9023 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
9025 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
9027 if (newfd == INVALID_HANDLE_VALUE) {
9032 if (env->me_psize >= env->me_os_psize) {
9034 /* Set O_DIRECT if the file system supports it */
9035 if ((rc = fcntl(newfd, F_GETFL)) != -1)
9036 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
9038 #ifdef F_NOCACHE /* __APPLE__ */
9039 rc = fcntl(newfd, F_NOCACHE, 1);
9047 rc = mdb_env_copyfd2(env, newfd, flags);
9050 if (!(env->me_flags & MDB_NOSUBDIR))
9052 if (newfd != INVALID_HANDLE_VALUE)
9053 if (close(newfd) < 0 && rc == MDB_SUCCESS)
9060 mdb_env_copy(MDB_env *env, const char *path)
9062 return mdb_env_copy2(env, path, 0);
9066 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
9068 if ((flag & CHANGEABLE) != flag)
9071 env->me_flags |= flag;
9073 env->me_flags &= ~flag;
9078 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
9083 *arg = env->me_flags;
9088 mdb_env_set_userctx(MDB_env *env, void *ctx)
9092 env->me_userctx = ctx;
9097 mdb_env_get_userctx(MDB_env *env)
9099 return env ? env->me_userctx : NULL;
9103 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
9108 env->me_assert_func = func;
9114 mdb_env_get_path(MDB_env *env, const char **arg)
9119 *arg = env->me_path;
9124 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
9133 /** Common code for #mdb_stat() and #mdb_env_stat().
9134 * @param[in] env the environment to operate in.
9135 * @param[in] db the #MDB_db record containing the stats to return.
9136 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
9137 * @return 0, this function always succeeds.
9140 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
9142 arg->ms_psize = env->me_psize;
9143 arg->ms_depth = db->md_depth;
9144 arg->ms_branch_pages = db->md_branch_pages;
9145 arg->ms_leaf_pages = db->md_leaf_pages;
9146 arg->ms_overflow_pages = db->md_overflow_pages;
9147 arg->ms_entries = db->md_entries;
9153 mdb_env_stat(MDB_env *env, MDB_stat *arg)
9157 if (env == NULL || arg == NULL)
9160 toggle = mdb_env_pick_meta(env);
9162 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
9166 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
9170 if (env == NULL || arg == NULL)
9173 toggle = mdb_env_pick_meta(env);
9174 arg->me_mapaddr = env->me_metas[toggle]->mm_address;
9175 arg->me_mapsize = env->me_mapsize;
9176 arg->me_maxreaders = env->me_maxreaders;
9178 /* me_numreaders may be zero if this process never used any readers. Use
9179 * the shared numreader count if it exists.
9181 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : env->me_numreaders;
9183 arg->me_last_pgno = env->me_metas[toggle]->mm_last_pg;
9184 arg->me_last_txnid = env->me_metas[toggle]->mm_txnid;
9188 /** Set the default comparison functions for a database.
9189 * Called immediately after a database is opened to set the defaults.
9190 * The user can then override them with #mdb_set_compare() or
9191 * #mdb_set_dupsort().
9192 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
9193 * @param[in] dbi A database handle returned by #mdb_dbi_open()
9196 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
9198 uint16_t f = txn->mt_dbs[dbi].md_flags;
9200 txn->mt_dbxs[dbi].md_cmp =
9201 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
9202 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
9204 txn->mt_dbxs[dbi].md_dcmp =
9205 !(f & MDB_DUPSORT) ? 0 :
9206 ((f & MDB_INTEGERDUP)
9207 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
9208 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
9211 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
9217 int rc, dbflag, exact;
9218 unsigned int unused = 0, seq;
9221 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
9222 mdb_default_cmp(txn, FREE_DBI);
9225 if ((flags & VALID_FLAGS) != flags)
9227 if (txn->mt_flags & MDB_TXN_ERROR)
9233 if (flags & PERSISTENT_FLAGS) {
9234 uint16_t f2 = flags & PERSISTENT_FLAGS;
9235 /* make sure flag changes get committed */
9236 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
9237 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
9238 txn->mt_flags |= MDB_TXN_DIRTY;
9241 mdb_default_cmp(txn, MAIN_DBI);
9245 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
9246 mdb_default_cmp(txn, MAIN_DBI);
9249 /* Is the DB already open? */
9251 for (i=2; i<txn->mt_numdbs; i++) {
9252 if (!txn->mt_dbxs[i].md_name.mv_size) {
9253 /* Remember this free slot */
9254 if (!unused) unused = i;
9257 if (len == txn->mt_dbxs[i].md_name.mv_size &&
9258 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
9264 /* If no free slot and max hit, fail */
9265 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
9266 return MDB_DBS_FULL;
9268 /* Cannot mix named databases with some mainDB flags */
9269 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
9270 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
9272 /* Find the DB info */
9273 dbflag = DB_NEW|DB_VALID;
9276 key.mv_data = (void *)name;
9277 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
9278 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
9279 if (rc == MDB_SUCCESS) {
9280 /* make sure this is actually a DB */
9281 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
9282 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
9283 return MDB_INCOMPATIBLE;
9284 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
9285 /* Create if requested */
9286 data.mv_size = sizeof(MDB_db);
9287 data.mv_data = &dummy;
9288 memset(&dummy, 0, sizeof(dummy));
9289 dummy.md_root = P_INVALID;
9290 dummy.md_flags = flags & PERSISTENT_FLAGS;
9291 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
9295 /* OK, got info, add to table */
9296 if (rc == MDB_SUCCESS) {
9297 unsigned int slot = unused ? unused : txn->mt_numdbs;
9298 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
9299 txn->mt_dbxs[slot].md_name.mv_size = len;
9300 txn->mt_dbxs[slot].md_rel = NULL;
9301 txn->mt_dbflags[slot] = dbflag;
9302 /* txn-> and env-> are the same in read txns, use
9303 * tmp variable to avoid undefined assignment
9305 seq = ++txn->mt_env->me_dbiseqs[slot];
9306 txn->mt_dbiseqs[slot] = seq;
9308 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
9310 mdb_default_cmp(txn, slot);
9319 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
9321 if (!arg || !TXN_DBI_EXIST(txn, dbi))
9324 if (txn->mt_flags & MDB_TXN_ERROR)
9327 if (txn->mt_dbflags[dbi] & DB_STALE) {
9330 /* Stale, must read the DB's root. cursor_init does it for us. */
9331 mdb_cursor_init(&mc, txn, dbi, &mx);
9333 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
9336 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
9339 if (dbi <= MAIN_DBI || dbi >= env->me_maxdbs)
9341 ptr = env->me_dbxs[dbi].md_name.mv_data;
9342 /* If there was no name, this was already closed */
9344 env->me_dbxs[dbi].md_name.mv_data = NULL;
9345 env->me_dbxs[dbi].md_name.mv_size = 0;
9346 env->me_dbflags[dbi] = 0;
9347 env->me_dbiseqs[dbi]++;
9352 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
9354 /* We could return the flags for the FREE_DBI too but what's the point? */
9355 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9357 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
9361 /** Add all the DB's pages to the free list.
9362 * @param[in] mc Cursor on the DB to free.
9363 * @param[in] subs non-Zero to check for sub-DBs in this DB.
9364 * @return 0 on success, non-zero on failure.
9367 mdb_drop0(MDB_cursor *mc, int subs)
9371 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
9372 if (rc == MDB_SUCCESS) {
9373 MDB_txn *txn = mc->mc_txn;
9378 /* LEAF2 pages have no nodes, cannot have sub-DBs */
9379 if (IS_LEAF2(mc->mc_pg[mc->mc_top]))
9382 mdb_cursor_copy(mc, &mx);
9383 while (mc->mc_snum > 0) {
9384 MDB_page *mp = mc->mc_pg[mc->mc_top];
9385 unsigned n = NUMKEYS(mp);
9387 for (i=0; i<n; i++) {
9388 ni = NODEPTR(mp, i);
9389 if (ni->mn_flags & F_BIGDATA) {
9392 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9393 rc = mdb_page_get(txn, pg, &omp, NULL);
9396 mdb_cassert(mc, IS_OVERFLOW(omp));
9397 rc = mdb_midl_append_range(&txn->mt_free_pgs,
9401 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
9402 mdb_xcursor_init1(mc, ni);
9403 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
9409 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
9411 for (i=0; i<n; i++) {
9413 ni = NODEPTR(mp, i);
9416 mdb_midl_xappend(txn->mt_free_pgs, pg);
9421 mc->mc_ki[mc->mc_top] = i;
9422 rc = mdb_cursor_sibling(mc, 1);
9424 if (rc != MDB_NOTFOUND)
9426 /* no more siblings, go back to beginning
9427 * of previous level.
9431 for (i=1; i<mc->mc_snum; i++) {
9433 mc->mc_pg[i] = mx.mc_pg[i];
9438 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
9441 txn->mt_flags |= MDB_TXN_ERROR;
9442 } else if (rc == MDB_NOTFOUND) {
9448 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
9450 MDB_cursor *mc, *m2;
9453 if ((unsigned)del > 1 || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9456 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
9459 if (dbi > MAIN_DBI && TXN_DBI_CHANGED(txn, dbi))
9462 rc = mdb_cursor_open(txn, dbi, &mc);
9466 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
9467 /* Invalidate the dropped DB's cursors */
9468 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
9469 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
9473 /* Can't delete the main DB */
9474 if (del && dbi > MAIN_DBI) {
9475 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, F_SUBDATA);
9477 txn->mt_dbflags[dbi] = DB_STALE;
9478 mdb_dbi_close(txn->mt_env, dbi);
9480 txn->mt_flags |= MDB_TXN_ERROR;
9483 /* reset the DB record, mark it dirty */
9484 txn->mt_dbflags[dbi] |= DB_DIRTY;
9485 txn->mt_dbs[dbi].md_depth = 0;
9486 txn->mt_dbs[dbi].md_branch_pages = 0;
9487 txn->mt_dbs[dbi].md_leaf_pages = 0;
9488 txn->mt_dbs[dbi].md_overflow_pages = 0;
9489 txn->mt_dbs[dbi].md_entries = 0;
9490 txn->mt_dbs[dbi].md_root = P_INVALID;
9492 txn->mt_flags |= MDB_TXN_DIRTY;
9495 mdb_cursor_close(mc);
9499 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9501 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9504 txn->mt_dbxs[dbi].md_cmp = cmp;
9508 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9510 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9513 txn->mt_dbxs[dbi].md_dcmp = cmp;
9517 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
9519 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9522 txn->mt_dbxs[dbi].md_rel = rel;
9526 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
9528 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9531 txn->mt_dbxs[dbi].md_relctx = ctx;
9536 mdb_env_get_maxkeysize(MDB_env *env)
9538 return ENV_MAXKEY(env);
9542 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
9544 unsigned int i, rdrs;
9547 int rc = 0, first = 1;
9551 if (!env->me_txns) {
9552 return func("(no reader locks)\n", ctx);
9554 rdrs = env->me_txns->mti_numreaders;
9555 mr = env->me_txns->mti_readers;
9556 for (i=0; i<rdrs; i++) {
9558 txnid_t txnid = mr[i].mr_txnid;
9559 sprintf(buf, txnid == (txnid_t)-1 ?
9560 "%10d %"Z"x -\n" : "%10d %"Z"x %"Z"u\n",
9561 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
9564 rc = func(" pid thread txnid\n", ctx);
9568 rc = func(buf, ctx);
9574 rc = func("(no active readers)\n", ctx);
9579 /** Insert pid into list if not already present.
9580 * return -1 if already present.
9583 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
9585 /* binary search of pid in list */
9587 unsigned cursor = 1;
9589 unsigned n = ids[0];
9592 unsigned pivot = n >> 1;
9593 cursor = base + pivot + 1;
9594 val = pid - ids[cursor];
9599 } else if ( val > 0 ) {
9604 /* found, so it's a duplicate */
9613 for (n = ids[0]; n > cursor; n--)
9620 mdb_reader_check(MDB_env *env, int *dead)
9622 unsigned int i, j, rdrs;
9624 MDB_PID_T *pids, pid;
9633 rdrs = env->me_txns->mti_numreaders;
9634 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
9638 mr = env->me_txns->mti_readers;
9639 for (i=0; i<rdrs; i++) {
9640 if (mr[i].mr_pid && mr[i].mr_pid != env->me_pid) {
9642 if (mdb_pid_insert(pids, pid) == 0) {
9643 if (!mdb_reader_pid(env, Pidcheck, pid)) {
9645 /* Recheck, a new process may have reused pid */
9646 if (!mdb_reader_pid(env, Pidcheck, pid)) {
9647 for (j=i; j<rdrs; j++)
9648 if (mr[j].mr_pid == pid) {
9649 DPRINTF(("clear stale reader pid %u txn %"Z"d",
9650 (unsigned) pid, mr[j].mr_txnid));
9655 UNLOCK_MUTEX_R(env);