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")))
188 /** @defgroup internal LMDB Internals
191 /** @defgroup compat Compatibility Macros
192 * A bunch of macros to minimize the amount of platform-specific ifdefs
193 * needed throughout the rest of the code. When the features this library
194 * needs are similar enough to POSIX to be hidden in a one-or-two line
195 * replacement, this macro approach is used.
199 /** Features under development */
204 /** Wrapper around __func__, which is a C99 feature */
205 #if __STDC_VERSION__ >= 199901L
206 # define mdb_func_ __func__
207 #elif __GNUC__ >= 2 || _MSC_VER >= 1300
208 # define mdb_func_ __FUNCTION__
210 /* If a debug message says <mdb_unknown>(), update the #if statements above */
211 # define mdb_func_ "<mdb_unknown>"
215 #define MDB_USE_HASH 1
216 #define MDB_PIDLOCK 0
217 #define THREAD_RET DWORD
218 #define pthread_t HANDLE
219 #define pthread_mutex_t HANDLE
220 #define pthread_cond_t HANDLE
221 #define pthread_key_t DWORD
222 #define pthread_self() GetCurrentThreadId()
223 #define pthread_key_create(x,y) \
224 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
225 #define pthread_key_delete(x) TlsFree(x)
226 #define pthread_getspecific(x) TlsGetValue(x)
227 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
228 #define pthread_mutex_unlock(x) ReleaseMutex(*x)
229 #define pthread_mutex_lock(x) WaitForSingleObject(*x, INFINITE)
230 #define pthread_cond_signal(x) SetEvent(*x)
231 #define pthread_cond_wait(cond,mutex) do{SignalObjectAndWait(*mutex, *cond, INFINITE, FALSE); WaitForSingleObject(*mutex, INFINITE);}while(0)
232 #define THREAD_CREATE(thr,start,arg) thr=CreateThread(NULL,0,start,arg,0,NULL)
233 #define THREAD_FINISH(thr) WaitForSingleObject(thr, INFINITE)
234 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_rmutex)
235 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_rmutex)
236 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_wmutex)
237 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_wmutex)
238 #define getpid() GetCurrentProcessId()
239 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
240 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
241 #define ErrCode() GetLastError()
242 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
243 #define close(fd) (CloseHandle(fd) ? 0 : -1)
244 #define munmap(ptr,len) UnmapViewOfFile(ptr)
245 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
246 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
248 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
252 #define THREAD_RET void *
253 #define THREAD_CREATE(thr,start,arg) pthread_create(&thr,NULL,start,arg)
254 #define THREAD_FINISH(thr) pthread_join(thr,NULL)
255 #define Z "z" /**< printf format modifier for size_t */
257 /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
258 #define MDB_PIDLOCK 1
260 #ifdef MDB_USE_POSIX_SEM
262 #define LOCK_MUTEX_R(env) mdb_sem_wait((env)->me_rmutex)
263 #define UNLOCK_MUTEX_R(env) sem_post((env)->me_rmutex)
264 #define LOCK_MUTEX_W(env) mdb_sem_wait((env)->me_wmutex)
265 #define UNLOCK_MUTEX_W(env) sem_post((env)->me_wmutex)
268 mdb_sem_wait(sem_t *sem)
271 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
276 /** Lock the reader mutex.
278 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
279 /** Unlock the reader mutex.
281 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
283 /** Lock the writer mutex.
284 * Only a single write transaction is allowed at a time. Other writers
285 * will block waiting for this mutex.
287 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
288 /** Unlock the writer mutex.
290 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
291 #endif /* MDB_USE_POSIX_SEM */
293 /** Get the error code for the last failed system function.
295 #define ErrCode() errno
297 /** An abstraction for a file handle.
298 * On POSIX systems file handles are small integers. On Windows
299 * they're opaque pointers.
303 /** A value for an invalid file handle.
304 * Mainly used to initialize file variables and signify that they are
307 #define INVALID_HANDLE_VALUE (-1)
309 /** Get the size of a memory page for the system.
310 * This is the basic size that the platform's memory manager uses, and is
311 * fundamental to the use of memory-mapped files.
313 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
316 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
319 #define MNAME_LEN (sizeof(pthread_mutex_t))
325 /** A flag for opening a file and requesting synchronous data writes.
326 * This is only used when writing a meta page. It's not strictly needed;
327 * we could just do a normal write and then immediately perform a flush.
328 * But if this flag is available it saves us an extra system call.
330 * @note If O_DSYNC is undefined but exists in /usr/include,
331 * preferably set some compiler flag to get the definition.
332 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
335 # define MDB_DSYNC O_DSYNC
339 /** Function for flushing the data of a file. Define this to fsync
340 * if fdatasync() is not supported.
342 #ifndef MDB_FDATASYNC
343 # define MDB_FDATASYNC fdatasync
347 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
358 /** A page number in the database.
359 * Note that 64 bit page numbers are overkill, since pages themselves
360 * already represent 12-13 bits of addressable memory, and the OS will
361 * always limit applications to a maximum of 63 bits of address space.
363 * @note In the #MDB_node structure, we only store 48 bits of this value,
364 * which thus limits us to only 60 bits of addressable data.
366 typedef MDB_ID pgno_t;
368 /** A transaction ID.
369 * See struct MDB_txn.mt_txnid for details.
371 typedef MDB_ID txnid_t;
373 /** @defgroup debug Debug Macros
377 /** Enable debug output. Needs variable argument macros (a C99 feature).
378 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
379 * read from and written to the database (used for free space management).
385 static int mdb_debug;
386 static txnid_t mdb_debug_start;
388 /** Print a debug message with printf formatting.
389 * Requires double parenthesis around 2 or more args.
391 # define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
392 # define DPRINTF0(fmt, ...) \
393 fprintf(stderr, "%s:%d " fmt "\n", mdb_func_, __LINE__, __VA_ARGS__)
395 # define DPRINTF(args) ((void) 0)
397 /** Print a debug string.
398 * The string is printed literally, with no format processing.
400 #define DPUTS(arg) DPRINTF(("%s", arg))
401 /** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
403 (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
406 /** @brief The maximum size of a database page.
408 * It is 32k or 64k, since value-PAGEBASE must fit in
409 * #MDB_page.%mp_upper.
411 * LMDB will use database pages < OS pages if needed.
412 * That causes more I/O in write transactions: The OS must
413 * know (read) the whole page before writing a partial page.
415 * Note that we don't currently support Huge pages. On Linux,
416 * regular data files cannot use Huge pages, and in general
417 * Huge pages aren't actually pageable. We rely on the OS
418 * demand-pager to read our data and page it out when memory
419 * pressure from other processes is high. So until OSs have
420 * actual paging support for Huge pages, they're not viable.
422 #define MAX_PAGESIZE (PAGEBASE ? 0x10000 : 0x8000)
424 /** The minimum number of keys required in a database page.
425 * Setting this to a larger value will place a smaller bound on the
426 * maximum size of a data item. Data items larger than this size will
427 * be pushed into overflow pages instead of being stored directly in
428 * the B-tree node. This value used to default to 4. With a page size
429 * of 4096 bytes that meant that any item larger than 1024 bytes would
430 * go into an overflow page. That also meant that on average 2-3KB of
431 * each overflow page was wasted space. The value cannot be lower than
432 * 2 because then there would no longer be a tree structure. With this
433 * value, items larger than 2KB will go into overflow pages, and on
434 * average only 1KB will be wasted.
436 #define MDB_MINKEYS 2
438 /** A stamp that identifies a file as an LMDB file.
439 * There's nothing special about this value other than that it is easily
440 * recognizable, and it will reflect any byte order mismatches.
442 #define MDB_MAGIC 0xBEEFC0DE
444 /** The version number for a database's datafile format. */
445 #define MDB_DATA_VERSION ((MDB_DEVEL) ? 999 : 1)
446 /** The version number for a database's lockfile format. */
447 #define MDB_LOCK_VERSION 1
449 /** @brief The max size of a key we can write, or 0 for dynamic max.
451 * Define this as 0 to compute the max from the page size. 511
452 * is default for backwards compat: liblmdb <= 0.9.10 can break
453 * when modifying a DB with keys/dupsort data bigger than its max.
454 * #MDB_DEVEL sets the default to 0.
456 * Data items in an #MDB_DUPSORT database are also limited to
457 * this size, since they're actually keys of a sub-DB. Keys and
458 * #MDB_DUPSORT data items must fit on a node in a regular page.
460 #ifndef MDB_MAXKEYSIZE
461 #define MDB_MAXKEYSIZE ((MDB_DEVEL) ? 0 : 511)
464 /** The maximum size of a key we can write to the environment. */
466 #define ENV_MAXKEY(env) (MDB_MAXKEYSIZE)
468 #define ENV_MAXKEY(env) ((env)->me_maxkey)
471 /** @brief The maximum size of a data item.
473 * We only store a 32 bit value for node sizes.
475 #define MAXDATASIZE 0xffffffffUL
478 /** Key size which fits in a #DKBUF.
481 #define DKBUF_MAXKEYSIZE ((MDB_MAXKEYSIZE) > 0 ? (MDB_MAXKEYSIZE) : 511)
484 * This is used for printing a hex dump of a key's contents.
486 #define DKBUF char kbuf[DKBUF_MAXKEYSIZE*2+1]
487 /** Display a key in hex.
489 * Invoke a function to display a key in hex.
491 #define DKEY(x) mdb_dkey(x, kbuf)
497 /** An invalid page number.
498 * Mainly used to denote an empty tree.
500 #define P_INVALID (~(pgno_t)0)
502 /** Test if the flags \b f are set in a flag word \b w. */
503 #define F_ISSET(w, f) (((w) & (f)) == (f))
505 /** Round \b n up to an even number. */
506 #define EVEN(n) (((n) + 1U) & -2) /* sign-extending -2 to match n+1U */
508 /** Used for offsets within a single page.
509 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
512 typedef uint16_t indx_t;
514 /** Default size of memory map.
515 * This is certainly too small for any actual applications. Apps should always set
516 * the size explicitly using #mdb_env_set_mapsize().
518 #define DEFAULT_MAPSIZE 1048576
520 /** @defgroup readers Reader Lock Table
521 * Readers don't acquire any locks for their data access. Instead, they
522 * simply record their transaction ID in the reader table. The reader
523 * mutex is needed just to find an empty slot in the reader table. The
524 * slot's address is saved in thread-specific data so that subsequent read
525 * transactions started by the same thread need no further locking to proceed.
527 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
529 * No reader table is used if the database is on a read-only filesystem, or
530 * if #MDB_NOLOCK is set.
532 * Since the database uses multi-version concurrency control, readers don't
533 * actually need any locking. This table is used to keep track of which
534 * readers are using data from which old transactions, so that we'll know
535 * when a particular old transaction is no longer in use. Old transactions
536 * that have discarded any data pages can then have those pages reclaimed
537 * for use by a later write transaction.
539 * The lock table is constructed such that reader slots are aligned with the
540 * processor's cache line size. Any slot is only ever used by one thread.
541 * This alignment guarantees that there will be no contention or cache
542 * thrashing as threads update their own slot info, and also eliminates
543 * any need for locking when accessing a slot.
545 * A writer thread will scan every slot in the table to determine the oldest
546 * outstanding reader transaction. Any freed pages older than this will be
547 * reclaimed by the writer. The writer doesn't use any locks when scanning
548 * this table. This means that there's no guarantee that the writer will
549 * see the most up-to-date reader info, but that's not required for correct
550 * operation - all we need is to know the upper bound on the oldest reader,
551 * we don't care at all about the newest reader. So the only consequence of
552 * reading stale information here is that old pages might hang around a
553 * while longer before being reclaimed. That's actually good anyway, because
554 * the longer we delay reclaiming old pages, the more likely it is that a
555 * string of contiguous pages can be found after coalescing old pages from
556 * many old transactions together.
559 /** Number of slots in the reader table.
560 * This value was chosen somewhat arbitrarily. 126 readers plus a
561 * couple mutexes fit exactly into 8KB on my development machine.
562 * Applications should set the table size using #mdb_env_set_maxreaders().
564 #define DEFAULT_READERS 126
566 /** The size of a CPU cache line in bytes. We want our lock structures
567 * aligned to this size to avoid false cache line sharing in the
569 * This value works for most CPUs. For Itanium this should be 128.
575 /** The information we store in a single slot of the reader table.
576 * In addition to a transaction ID, we also record the process and
577 * thread ID that owns a slot, so that we can detect stale information,
578 * e.g. threads or processes that went away without cleaning up.
579 * @note We currently don't check for stale records. We simply re-init
580 * the table when we know that we're the only process opening the
583 typedef struct MDB_rxbody {
584 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
585 * Multiple readers that start at the same time will probably have the
586 * same ID here. Again, it's not important to exclude them from
587 * anything; all we need to know is which version of the DB they
588 * started from so we can avoid overwriting any data used in that
589 * particular version.
591 volatile txnid_t mrb_txnid;
592 /** The process ID of the process owning this reader txn. */
593 volatile MDB_PID_T mrb_pid;
594 /** The thread ID of the thread owning this txn. */
595 volatile MDB_THR_T mrb_tid;
598 /** The actual reader record, with cacheline padding. */
599 typedef struct MDB_reader {
602 /** shorthand for mrb_txnid */
603 #define mr_txnid mru.mrx.mrb_txnid
604 #define mr_pid mru.mrx.mrb_pid
605 #define mr_tid mru.mrx.mrb_tid
606 /** cache line alignment */
607 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
611 /** The header for the reader table.
612 * The table resides in a memory-mapped file. (This is a different file
613 * than is used for the main database.)
615 * For POSIX the actual mutexes reside in the shared memory of this
616 * mapped file. On Windows, mutexes are named objects allocated by the
617 * kernel; we store the mutex names in this mapped file so that other
618 * processes can grab them. This same approach is also used on
619 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
620 * process-shared POSIX mutexes. For these cases where a named object
621 * is used, the object name is derived from a 64 bit FNV hash of the
622 * environment pathname. As such, naming collisions are extremely
623 * unlikely. If a collision occurs, the results are unpredictable.
625 typedef struct MDB_txbody {
626 /** Stamp identifying this as an LMDB file. It must be set
629 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
631 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
632 char mtb_rmname[MNAME_LEN];
634 /** Mutex protecting access to this table.
635 * This is the reader lock that #LOCK_MUTEX_R acquires.
637 pthread_mutex_t mtb_mutex;
639 /** The ID of the last transaction committed to the database.
640 * This is recorded here only for convenience; the value can always
641 * be determined by reading the main database meta pages.
643 volatile txnid_t mtb_txnid;
644 /** The number of slots that have been used in the reader table.
645 * This always records the maximum count, it is not decremented
646 * when readers release their slots.
648 volatile unsigned mtb_numreaders;
651 /** The actual reader table definition. */
652 typedef struct MDB_txninfo {
655 #define mti_magic mt1.mtb.mtb_magic
656 #define mti_format mt1.mtb.mtb_format
657 #define mti_mutex mt1.mtb.mtb_mutex
658 #define mti_rmname mt1.mtb.mtb_rmname
659 #define mti_txnid mt1.mtb.mtb_txnid
660 #define mti_numreaders mt1.mtb.mtb_numreaders
661 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
664 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
665 char mt2_wmname[MNAME_LEN];
666 #define mti_wmname mt2.mt2_wmname
668 pthread_mutex_t mt2_wmutex;
669 #define mti_wmutex mt2.mt2_wmutex
671 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
673 MDB_reader mti_readers[1];
676 /** Lockfile format signature: version, features and field layout */
677 #define MDB_LOCK_FORMAT \
679 ((MDB_LOCK_VERSION) \
680 /* Flags which describe functionality */ \
681 + (((MDB_PIDLOCK) != 0) << 16)))
684 /** Common header for all page types.
685 * Overflow records occupy a number of contiguous pages with no
686 * headers on any page after the first.
688 typedef struct MDB_page {
689 #define mp_pgno mp_p.p_pgno
690 #define mp_next mp_p.p_next
692 pgno_t p_pgno; /**< page number */
693 struct MDB_page *p_next; /**< for in-memory list of freed pages */
696 /** @defgroup mdb_page Page Flags
698 * Flags for the page headers.
701 #define P_BRANCH 0x01 /**< branch page */
702 #define P_LEAF 0x02 /**< leaf page */
703 #define P_OVERFLOW 0x04 /**< overflow page */
704 #define P_META 0x08 /**< meta page */
705 #define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
706 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
707 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
708 #define P_LOOSE 0x4000 /**< page was dirtied then freed, can be reused */
709 #define P_KEEP 0x8000 /**< leave this page alone during spill */
711 uint16_t mp_flags; /**< @ref mdb_page */
712 #define mp_lower mp_pb.pb.pb_lower
713 #define mp_upper mp_pb.pb.pb_upper
714 #define mp_pages mp_pb.pb_pages
717 indx_t pb_lower; /**< lower bound of free space */
718 indx_t pb_upper; /**< upper bound of free space */
720 uint32_t pb_pages; /**< number of overflow pages */
722 indx_t mp_ptrs[1]; /**< dynamic size */
725 /** Size of the page header, excluding dynamic data at the end */
726 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
728 /** Address of first usable data byte in a page, after the header */
729 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
731 /** ITS#7713, change PAGEBASE to handle 65536 byte pages */
732 #define PAGEBASE ((MDB_DEVEL) ? PAGEHDRSZ : 0)
734 /** Number of nodes on a page */
735 #define NUMKEYS(p) (((p)->mp_lower - (PAGEHDRSZ-PAGEBASE)) >> 1)
737 /** The amount of space remaining in the page */
738 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
740 /** The percentage of space used in the page, in tenths of a percent. */
741 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
742 ((env)->me_psize - PAGEHDRSZ))
743 /** The minimum page fill factor, in tenths of a percent.
744 * Pages emptier than this are candidates for merging.
746 #define FILL_THRESHOLD 250
748 /** Test if a page is a leaf page */
749 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
750 /** Test if a page is a LEAF2 page */
751 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
752 /** Test if a page is a branch page */
753 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
754 /** Test if a page is an overflow page */
755 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
756 /** Test if a page is a sub page */
757 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
759 /** The number of overflow pages needed to store the given size. */
760 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
762 /** Link in #MDB_txn.%mt_loose_pgs list */
763 #define NEXT_LOOSE_PAGE(p) (*(MDB_page **)((p) + 2))
765 /** Header for a single key/data pair within a page.
766 * Used in pages of type #P_BRANCH and #P_LEAF without #P_LEAF2.
767 * We guarantee 2-byte alignment for 'MDB_node's.
769 typedef struct MDB_node {
770 /** lo and hi are used for data size on leaf nodes and for
771 * child pgno on branch nodes. On 64 bit platforms, flags
772 * is also used for pgno. (Branch nodes have no flags).
773 * They are in host byte order in case that lets some
774 * accesses be optimized into a 32-bit word access.
776 #if BYTE_ORDER == LITTLE_ENDIAN
777 unsigned short mn_lo, mn_hi; /**< part of data size or pgno */
779 unsigned short mn_hi, mn_lo;
781 /** @defgroup mdb_node Node Flags
783 * Flags for node headers.
786 #define F_BIGDATA 0x01 /**< data put on overflow page */
787 #define F_SUBDATA 0x02 /**< data is a sub-database */
788 #define F_DUPDATA 0x04 /**< data has duplicates */
790 /** valid flags for #mdb_node_add() */
791 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
794 unsigned short mn_flags; /**< @ref mdb_node */
795 unsigned short mn_ksize; /**< key size */
796 char mn_data[1]; /**< key and data are appended here */
799 /** Size of the node header, excluding dynamic data at the end */
800 #define NODESIZE offsetof(MDB_node, mn_data)
802 /** Bit position of top word in page number, for shifting mn_flags */
803 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
805 /** Size of a node in a branch page with a given key.
806 * This is just the node header plus the key, there is no data.
808 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
810 /** Size of a node in a leaf page with a given key and data.
811 * This is node header plus key plus data size.
813 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
815 /** Address of node \b i in page \b p */
816 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i] + PAGEBASE))
818 /** Address of the key for the node */
819 #define NODEKEY(node) (void *)((node)->mn_data)
821 /** Address of the data for a node */
822 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
824 /** Get the page number pointed to by a branch node */
825 #define NODEPGNO(node) \
826 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
827 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
828 /** Set the page number in a branch node */
829 #define SETPGNO(node,pgno) do { \
830 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
831 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
833 /** Get the size of the data in a leaf node */
834 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
835 /** Set the size of the data for a leaf node */
836 #define SETDSZ(node,size) do { \
837 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
838 /** The size of a key in a node */
839 #define NODEKSZ(node) ((node)->mn_ksize)
841 /** Copy a page number from src to dst */
843 #define COPY_PGNO(dst,src) dst = src
845 #if SIZE_MAX > 4294967295UL
846 #define COPY_PGNO(dst,src) do { \
847 unsigned short *s, *d; \
848 s = (unsigned short *)&(src); \
849 d = (unsigned short *)&(dst); \
856 #define COPY_PGNO(dst,src) do { \
857 unsigned short *s, *d; \
858 s = (unsigned short *)&(src); \
859 d = (unsigned short *)&(dst); \
865 /** The address of a key in a LEAF2 page.
866 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
867 * There are no node headers, keys are stored contiguously.
869 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
871 /** Set the \b node's key into \b keyptr, if requested. */
872 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
873 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
875 /** Set the \b node's key into \b key. */
876 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
878 /** Information about a single database in the environment. */
879 typedef struct MDB_db {
880 uint32_t md_pad; /**< also ksize for LEAF2 pages */
881 uint16_t md_flags; /**< @ref mdb_dbi_open */
882 uint16_t md_depth; /**< depth of this tree */
883 pgno_t md_branch_pages; /**< number of internal pages */
884 pgno_t md_leaf_pages; /**< number of leaf pages */
885 pgno_t md_overflow_pages; /**< number of overflow pages */
886 size_t md_entries; /**< number of data items */
887 pgno_t md_root; /**< the root page of this tree */
890 /** mdb_dbi_open flags */
891 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
892 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
893 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
894 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
896 /** Handle for the DB used to track free pages. */
898 /** Handle for the default DB. */
901 /** Meta page content.
902 * A meta page is the start point for accessing a database snapshot.
903 * Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
905 typedef struct MDB_meta {
906 /** Stamp identifying this as an LMDB file. It must be set
909 /** Version number of this file. Must be set to #MDB_DATA_VERSION. */
911 void *mm_address; /**< address for fixed mapping */
912 size_t mm_mapsize; /**< size of mmap region */
913 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
914 /** The size of pages used in this DB */
915 #define mm_psize mm_dbs[0].md_pad
916 /** Any persistent environment flags. @ref mdb_env */
917 #define mm_flags mm_dbs[0].md_flags
918 pgno_t mm_last_pg; /**< last used page in file */
919 volatile txnid_t mm_txnid; /**< txnid that committed this page */
922 /** Buffer for a stack-allocated meta page.
923 * The members define size and alignment, and silence type
924 * aliasing warnings. They are not used directly; that could
925 * mean incorrectly using several union members in parallel.
927 typedef union MDB_metabuf {
930 char mm_pad[PAGEHDRSZ];
935 /** Auxiliary DB info.
936 * The information here is mostly static/read-only. There is
937 * only a single copy of this record in the environment.
939 typedef struct MDB_dbx {
940 MDB_val md_name; /**< name of the database */
941 MDB_cmp_func *md_cmp; /**< function for comparing keys */
942 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
943 MDB_rel_func *md_rel; /**< user relocate function */
944 void *md_relctx; /**< user-provided context for md_rel */
947 /** A database transaction.
948 * Every operation requires a transaction handle.
951 MDB_txn *mt_parent; /**< parent of a nested txn */
952 MDB_txn *mt_child; /**< nested txn under this txn */
953 pgno_t mt_next_pgno; /**< next unallocated page */
954 /** The ID of this transaction. IDs are integers incrementing from 1.
955 * Only committed write transactions increment the ID. If a transaction
956 * aborts, the ID may be re-used by the next writer.
959 MDB_env *mt_env; /**< the DB environment */
960 /** The list of pages that became unused during this transaction.
963 /** The list of loose pages that became unused and may be reused
964 * in this transaction, linked through #NEXT_LOOSE_PAGE(page).
966 MDB_page *mt_loose_pgs;
967 /* #Number of loose pages (#mt_loose_pgs) */
969 /** The sorted list of dirty pages we temporarily wrote to disk
970 * because the dirty list was full. page numbers in here are
971 * shifted left by 1, deleted slots have the LSB set.
973 MDB_IDL mt_spill_pgs;
975 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
977 /** For read txns: This thread/txn's reader table slot, or NULL. */
980 /** Array of records for each DB known in the environment. */
982 /** Array of MDB_db records for each known DB */
984 /** Array of sequence numbers for each DB handle */
985 unsigned int *mt_dbiseqs;
986 /** @defgroup mt_dbflag Transaction DB Flags
990 #define DB_DIRTY 0x01 /**< DB was modified or is DUPSORT data */
991 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
992 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
993 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
995 /** In write txns, array of cursors for each DB */
996 MDB_cursor **mt_cursors;
997 /** Array of flags for each DB */
998 unsigned char *mt_dbflags;
999 /** Number of DB records in use. This number only ever increments;
1000 * we don't decrement it when individual DB handles are closed.
1004 /** @defgroup mdb_txn Transaction Flags
1008 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
1009 #define MDB_TXN_ERROR 0x02 /**< txn is unusable after an error */
1010 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
1011 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
1013 unsigned int mt_flags; /**< @ref mdb_txn */
1014 /** #dirty_list room: Array size - \#dirty pages visible to this txn.
1015 * Includes ancestor txns' dirty pages not hidden by other txns'
1016 * dirty/spilled pages. Thus commit(nested txn) has room to merge
1017 * dirty_list into mt_parent after freeing hidden mt_parent pages.
1019 unsigned int mt_dirty_room;
1022 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
1023 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
1024 * raise this on a 64 bit machine.
1026 #define CURSOR_STACK 32
1030 /** Cursors are used for all DB operations.
1031 * A cursor holds a path of (page pointer, key index) from the DB
1032 * root to a position in the DB, plus other state. #MDB_DUPSORT
1033 * cursors include an xcursor to the current data item. Write txns
1034 * track their cursors and keep them up to date when data moves.
1035 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
1036 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
1039 /** Next cursor on this DB in this txn */
1040 MDB_cursor *mc_next;
1041 /** Backup of the original cursor if this cursor is a shadow */
1042 MDB_cursor *mc_backup;
1043 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
1044 struct MDB_xcursor *mc_xcursor;
1045 /** The transaction that owns this cursor */
1047 /** The database handle this cursor operates on */
1049 /** The database record for this cursor */
1051 /** The database auxiliary record for this cursor */
1053 /** The @ref mt_dbflag for this database */
1054 unsigned char *mc_dbflag;
1055 unsigned short mc_snum; /**< number of pushed pages */
1056 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
1057 /** @defgroup mdb_cursor Cursor Flags
1059 * Cursor state flags.
1062 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
1063 #define C_EOF 0x02 /**< No more data */
1064 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
1065 #define C_DEL 0x08 /**< last op was a cursor_del */
1066 #define C_SPLITTING 0x20 /**< Cursor is in page_split */
1067 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
1069 unsigned int mc_flags; /**< @ref mdb_cursor */
1070 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
1071 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
1074 /** Context for sorted-dup records.
1075 * We could have gone to a fully recursive design, with arbitrarily
1076 * deep nesting of sub-databases. But for now we only handle these
1077 * levels - main DB, optional sub-DB, sorted-duplicate DB.
1079 typedef struct MDB_xcursor {
1080 /** A sub-cursor for traversing the Dup DB */
1081 MDB_cursor mx_cursor;
1082 /** The database record for this Dup DB */
1084 /** The auxiliary DB record for this Dup DB */
1086 /** The @ref mt_dbflag for this Dup DB */
1087 unsigned char mx_dbflag;
1090 /** State of FreeDB old pages, stored in the MDB_env */
1091 typedef struct MDB_pgstate {
1092 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1093 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1096 /** The database environment. */
1098 HANDLE me_fd; /**< The main data file */
1099 HANDLE me_lfd; /**< The lock file */
1100 HANDLE me_mfd; /**< just for writing the meta pages */
1101 /** Failed to update the meta page. Probably an I/O error. */
1102 #define MDB_FATAL_ERROR 0x80000000U
1103 /** Some fields are initialized. */
1104 #define MDB_ENV_ACTIVE 0x20000000U
1105 /** me_txkey is set */
1106 #define MDB_ENV_TXKEY 0x10000000U
1107 /** fdatasync is unreliable */
1108 #define MDB_FSYNCONLY 0x08000000U
1109 uint32_t me_flags; /**< @ref mdb_env */
1110 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1111 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1112 unsigned int me_maxreaders; /**< size of the reader table */
1113 unsigned int me_numreaders; /**< max numreaders set by this env */
1114 MDB_dbi me_numdbs; /**< number of DBs opened */
1115 MDB_dbi me_maxdbs; /**< size of the DB table */
1116 MDB_PID_T me_pid; /**< process ID of this env */
1117 char *me_path; /**< path to the DB files */
1118 char *me_map; /**< the memory map of the data file */
1119 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1120 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
1121 void *me_pbuf; /**< scratch area for DUPSORT put() */
1122 MDB_txn *me_txn; /**< current write transaction */
1123 MDB_txn *me_txn0; /**< prealloc'd write transaction */
1124 size_t me_mapsize; /**< size of the data memory map */
1125 off_t me_size; /**< current file size */
1126 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1127 MDB_dbx *me_dbxs; /**< array of static DB info */
1128 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1129 unsigned int *me_dbiseqs; /**< array of dbi sequence numbers */
1130 pthread_key_t me_txkey; /**< thread-key for readers */
1131 txnid_t me_pgoldest; /**< ID of oldest reader last time we looked */
1132 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1133 # define me_pglast me_pgstate.mf_pglast
1134 # define me_pghead me_pgstate.mf_pghead
1135 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1136 /** IDL of pages that became unused in a write txn */
1137 MDB_IDL me_free_pgs;
1138 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1139 MDB_ID2L me_dirty_list;
1140 /** Max number of freelist items that can fit in a single overflow page */
1142 /** Max size of a node on a page */
1143 unsigned int me_nodemax;
1144 #if !(MDB_MAXKEYSIZE)
1145 unsigned int me_maxkey; /**< max size of a key */
1147 int me_live_reader; /**< have liveness lock in reader table */
1149 int me_pidquery; /**< Used in OpenProcess */
1150 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
1152 #elif defined(MDB_USE_POSIX_SEM)
1153 sem_t *me_rmutex; /* Shared mutexes are not supported */
1156 void *me_userctx; /**< User-settable context */
1157 MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
1160 /** Nested transaction */
1161 typedef struct MDB_ntxn {
1162 MDB_txn mnt_txn; /**< the transaction */
1163 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1166 /** max number of pages to commit in one writev() call */
1167 #define MDB_COMMIT_PAGES 64
1168 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1169 #undef MDB_COMMIT_PAGES
1170 #define MDB_COMMIT_PAGES IOV_MAX
1173 /** max bytes to write in one call */
1174 #define MAX_WRITE (0x80000000U >> (sizeof(ssize_t) == 4))
1176 /** Check \b txn and \b dbi arguments to a function */
1177 #define TXN_DBI_EXIST(txn, dbi) \
1178 ((txn) && (dbi) < (txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & DB_VALID))
1180 /** Check for misused \b dbi handles */
1181 #define TXN_DBI_CHANGED(txn, dbi) \
1182 ((txn)->mt_dbiseqs[dbi] != (txn)->mt_env->me_dbiseqs[dbi])
1184 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1185 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1186 static int mdb_page_touch(MDB_cursor *mc);
1188 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp, int *lvl);
1189 static int mdb_page_search_root(MDB_cursor *mc,
1190 MDB_val *key, int modify);
1191 #define MDB_PS_MODIFY 1
1192 #define MDB_PS_ROOTONLY 2
1193 #define MDB_PS_FIRST 4
1194 #define MDB_PS_LAST 8
1195 static int mdb_page_search(MDB_cursor *mc,
1196 MDB_val *key, int flags);
1197 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1199 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1200 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1201 pgno_t newpgno, unsigned int nflags);
1203 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1204 static int mdb_env_pick_meta(const MDB_env *env);
1205 static int mdb_env_write_meta(MDB_txn *txn);
1206 #if !(defined(_WIN32) || defined(MDB_USE_POSIX_SEM)) /* Drop unused excl arg */
1207 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1209 static void mdb_env_close0(MDB_env *env, int excl);
1211 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1212 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1213 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1214 static void mdb_node_del(MDB_cursor *mc, int ksize);
1215 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1216 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
1217 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1218 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1219 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1221 static int mdb_rebalance(MDB_cursor *mc);
1222 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1224 static void mdb_cursor_pop(MDB_cursor *mc);
1225 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1227 static int mdb_cursor_del0(MDB_cursor *mc);
1228 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
1229 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1230 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1231 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1232 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1234 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1235 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1237 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1238 static void mdb_xcursor_init0(MDB_cursor *mc);
1239 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1241 static int mdb_drop0(MDB_cursor *mc, int subs);
1242 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1245 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1248 /** Compare two items pointing at size_t's of unknown alignment. */
1249 #ifdef MISALIGNED_OK
1250 # define mdb_cmp_clong mdb_cmp_long
1252 # define mdb_cmp_clong mdb_cmp_cint
1256 static SECURITY_DESCRIPTOR mdb_null_sd;
1257 static SECURITY_ATTRIBUTES mdb_all_sa;
1258 static int mdb_sec_inited;
1261 /** Return the library version info. */
1263 mdb_version(int *major, int *minor, int *patch)
1265 if (major) *major = MDB_VERSION_MAJOR;
1266 if (minor) *minor = MDB_VERSION_MINOR;
1267 if (patch) *patch = MDB_VERSION_PATCH;
1268 return MDB_VERSION_STRING;
1271 /** Table of descriptions for LMDB @ref errors */
1272 static char *const mdb_errstr[] = {
1273 "MDB_KEYEXIST: Key/data pair already exists",
1274 "MDB_NOTFOUND: No matching key/data pair found",
1275 "MDB_PAGE_NOTFOUND: Requested page not found",
1276 "MDB_CORRUPTED: Located page was wrong type",
1277 "MDB_PANIC: Update of meta page failed",
1278 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1279 "MDB_INVALID: File is not an LMDB file",
1280 "MDB_MAP_FULL: Environment mapsize limit reached",
1281 "MDB_DBS_FULL: Environment maxdbs limit reached",
1282 "MDB_READERS_FULL: Environment maxreaders limit reached",
1283 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1284 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1285 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1286 "MDB_PAGE_FULL: Internal error - page has no more space",
1287 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1288 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1289 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1290 "MDB_BAD_TXN: Transaction cannot recover - it must be aborted",
1291 "MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
1292 "MDB_BAD_DBI: The specified DBI handle was closed/changed unexpectedly",
1296 mdb_strerror(int err)
1299 /** HACK: pad 4KB on stack over the buf. Return system msgs in buf.
1300 * This works as long as no function between the call to mdb_strerror
1301 * and the actual use of the message uses more than 4K of stack.
1304 char buf[1024], *ptr = buf;
1308 return ("Successful return: 0");
1310 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1311 i = err - MDB_KEYEXIST;
1312 return mdb_errstr[i];
1316 /* These are the C-runtime error codes we use. The comment indicates
1317 * their numeric value, and the Win32 error they would correspond to
1318 * if the error actually came from a Win32 API. A major mess, we should
1319 * have used LMDB-specific error codes for everything.
1322 case ENOENT: /* 2, FILE_NOT_FOUND */
1323 case EIO: /* 5, ACCESS_DENIED */
1324 case ENOMEM: /* 12, INVALID_ACCESS */
1325 case EACCES: /* 13, INVALID_DATA */
1326 case EBUSY: /* 16, CURRENT_DIRECTORY */
1327 case EINVAL: /* 22, BAD_COMMAND */
1328 case ENOSPC: /* 28, OUT_OF_PAPER */
1329 return strerror(err);
1334 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1335 FORMAT_MESSAGE_IGNORE_INSERTS,
1336 NULL, err, 0, ptr, sizeof(buf), (va_list *)pad);
1339 return strerror(err);
1343 /** assert(3) variant in cursor context */
1344 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1345 /** assert(3) variant in transaction context */
1346 #define mdb_tassert(mc, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1347 /** assert(3) variant in environment context */
1348 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1351 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1352 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1355 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1356 const char *func, const char *file, int line)
1359 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1360 file, line, expr_txt, func);
1361 if (env->me_assert_func)
1362 env->me_assert_func(env, buf);
1363 fprintf(stderr, "%s\n", buf);
1367 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1371 /** Return the page number of \b mp which may be sub-page, for debug output */
1373 mdb_dbg_pgno(MDB_page *mp)
1376 COPY_PGNO(ret, mp->mp_pgno);
1380 /** Display a key in hexadecimal and return the address of the result.
1381 * @param[in] key the key to display
1382 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1383 * @return The key in hexadecimal form.
1386 mdb_dkey(MDB_val *key, char *buf)
1389 unsigned char *c = key->mv_data;
1395 if (key->mv_size > DKBUF_MAXKEYSIZE)
1396 return "MDB_MAXKEYSIZE";
1397 /* may want to make this a dynamic check: if the key is mostly
1398 * printable characters, print it as-is instead of converting to hex.
1402 for (i=0; i<key->mv_size; i++)
1403 ptr += sprintf(ptr, "%02x", *c++);
1405 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1411 mdb_leafnode_type(MDB_node *n)
1413 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1414 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1415 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1418 /** Display all the keys in the page. */
1420 mdb_page_list(MDB_page *mp)
1422 pgno_t pgno = mdb_dbg_pgno(mp);
1423 const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
1425 unsigned int i, nkeys, nsize, total = 0;
1429 switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1430 case P_BRANCH: type = "Branch page"; break;
1431 case P_LEAF: type = "Leaf page"; break;
1432 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1433 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1434 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1436 fprintf(stderr, "Overflow page %"Z"u pages %u%s\n",
1437 pgno, mp->mp_pages, state);
1440 fprintf(stderr, "Meta-page %"Z"u txnid %"Z"u\n",
1441 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1444 fprintf(stderr, "Bad page %"Z"u flags 0x%u\n", pgno, mp->mp_flags);
1448 nkeys = NUMKEYS(mp);
1449 fprintf(stderr, "%s %"Z"u numkeys %d%s\n", type, pgno, nkeys, state);
1451 for (i=0; i<nkeys; i++) {
1452 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1453 key.mv_size = nsize = mp->mp_pad;
1454 key.mv_data = LEAF2KEY(mp, i, nsize);
1456 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1459 node = NODEPTR(mp, i);
1460 key.mv_size = node->mn_ksize;
1461 key.mv_data = node->mn_data;
1462 nsize = NODESIZE + key.mv_size;
1463 if (IS_BRANCH(mp)) {
1464 fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
1468 if (F_ISSET(node->mn_flags, F_BIGDATA))
1469 nsize += sizeof(pgno_t);
1471 nsize += NODEDSZ(node);
1473 nsize += sizeof(indx_t);
1474 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1475 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1477 total = EVEN(total);
1479 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1480 IS_LEAF2(mp) ? PAGEHDRSZ : PAGEBASE + mp->mp_lower, total, SIZELEFT(mp));
1484 mdb_cursor_chk(MDB_cursor *mc)
1490 if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1491 for (i=0; i<mc->mc_top; i++) {
1493 node = NODEPTR(mp, mc->mc_ki[i]);
1494 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1497 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1503 /** Count all the pages in each DB and in the freelist
1504 * and make sure it matches the actual number of pages
1506 * All named DBs must be open for a correct count.
1508 static void mdb_audit(MDB_txn *txn)
1512 MDB_ID freecount, count;
1517 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1518 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1519 freecount += *(MDB_ID *)data.mv_data;
1520 mdb_tassert(txn, rc == MDB_NOTFOUND);
1523 for (i = 0; i<txn->mt_numdbs; i++) {
1525 if (!(txn->mt_dbflags[i] & DB_VALID))
1527 mdb_cursor_init(&mc, txn, i, &mx);
1528 if (txn->mt_dbs[i].md_root == P_INVALID)
1530 count += txn->mt_dbs[i].md_branch_pages +
1531 txn->mt_dbs[i].md_leaf_pages +
1532 txn->mt_dbs[i].md_overflow_pages;
1533 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1534 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1535 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
1538 mp = mc.mc_pg[mc.mc_top];
1539 for (j=0; j<NUMKEYS(mp); j++) {
1540 MDB_node *leaf = NODEPTR(mp, j);
1541 if (leaf->mn_flags & F_SUBDATA) {
1543 memcpy(&db, NODEDATA(leaf), sizeof(db));
1544 count += db.md_branch_pages + db.md_leaf_pages +
1545 db.md_overflow_pages;
1549 mdb_tassert(txn, rc == MDB_NOTFOUND);
1552 if (freecount + count + 2 /* metapages */ != txn->mt_next_pgno) {
1553 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1554 txn->mt_txnid, freecount, count+2, freecount+count+2, txn->mt_next_pgno);
1560 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1562 return txn->mt_dbxs[dbi].md_cmp(a, b);
1566 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1568 MDB_cmp_func *dcmp = txn->mt_dbxs[dbi].md_dcmp;
1569 #if UINT_MAX < SIZE_MAX
1570 if (dcmp == mdb_cmp_int && a->mv_size == sizeof(size_t))
1571 dcmp = mdb_cmp_clong;
1576 /** Allocate memory for a page.
1577 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1580 mdb_page_malloc(MDB_txn *txn, unsigned num)
1582 MDB_env *env = txn->mt_env;
1583 MDB_page *ret = env->me_dpages;
1584 size_t psize = env->me_psize, sz = psize, off;
1585 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1586 * For a single page alloc, we init everything after the page header.
1587 * For multi-page, we init the final page; if the caller needed that
1588 * many pages they will be filling in at least up to the last page.
1592 VGMEMP_ALLOC(env, ret, sz);
1593 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1594 env->me_dpages = ret->mp_next;
1597 psize -= off = PAGEHDRSZ;
1602 if ((ret = malloc(sz)) != NULL) {
1603 VGMEMP_ALLOC(env, ret, sz);
1604 if (!(env->me_flags & MDB_NOMEMINIT)) {
1605 memset((char *)ret + off, 0, psize);
1609 txn->mt_flags |= MDB_TXN_ERROR;
1613 /** Free a single page.
1614 * Saves single pages to a list, for future reuse.
1615 * (This is not used for multi-page overflow pages.)
1618 mdb_page_free(MDB_env *env, MDB_page *mp)
1620 mp->mp_next = env->me_dpages;
1621 VGMEMP_FREE(env, mp);
1622 env->me_dpages = mp;
1625 /** Free a dirty page */
1627 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1629 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1630 mdb_page_free(env, dp);
1632 /* large pages just get freed directly */
1633 VGMEMP_FREE(env, dp);
1638 /** Return all dirty pages to dpage list */
1640 mdb_dlist_free(MDB_txn *txn)
1642 MDB_env *env = txn->mt_env;
1643 MDB_ID2L dl = txn->mt_u.dirty_list;
1644 unsigned i, n = dl[0].mid;
1646 for (i = 1; i <= n; i++) {
1647 mdb_dpage_free(env, dl[i].mptr);
1652 /** Loosen or free a single page.
1653 * Saves single pages to a list for future reuse
1654 * in this same txn. It has been pulled from the freeDB
1655 * and already resides on the dirty list, but has been
1656 * deleted. Use these pages first before pulling again
1659 * If the page wasn't dirtied in this txn, just add it
1660 * to this txn's free list.
1663 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
1666 pgno_t pgno = mp->mp_pgno;
1667 MDB_txn *txn = mc->mc_txn;
1669 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
1670 if (txn->mt_parent) {
1671 MDB_ID2 *dl = txn->mt_u.dirty_list;
1672 /* If txn has a parent, make sure the page is in our
1676 unsigned x = mdb_mid2l_search(dl, pgno);
1677 if (x <= dl[0].mid && dl[x].mid == pgno) {
1678 if (mp != dl[x].mptr) { /* bad cursor? */
1679 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1680 txn->mt_flags |= MDB_TXN_ERROR;
1681 return MDB_CORRUPTED;
1688 /* no parent txn, so it's just ours */
1693 DPRINTF(("loosen db %d page %"Z"u", DDBI(mc),
1695 NEXT_LOOSE_PAGE(mp) = txn->mt_loose_pgs;
1696 txn->mt_loose_pgs = mp;
1697 txn->mt_loose_count++;
1698 mp->mp_flags |= P_LOOSE;
1700 int rc = mdb_midl_append(&txn->mt_free_pgs, pgno);
1708 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
1709 * @param[in] mc A cursor handle for the current operation.
1710 * @param[in] pflags Flags of the pages to update:
1711 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1712 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
1713 * @return 0 on success, non-zero on failure.
1716 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
1718 enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
1719 MDB_txn *txn = mc->mc_txn;
1725 int rc = MDB_SUCCESS, level;
1727 /* Mark pages seen by cursors */
1728 if (mc->mc_flags & C_UNTRACK)
1729 mc = NULL; /* will find mc in mt_cursors */
1730 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1731 for (; mc; mc=mc->mc_next) {
1732 if (!(mc->mc_flags & C_INITIALIZED))
1734 for (m3 = mc;; m3 = &mx->mx_cursor) {
1736 for (j=0; j<m3->mc_snum; j++) {
1738 if ((mp->mp_flags & Mask) == pflags)
1739 mp->mp_flags ^= P_KEEP;
1741 mx = m3->mc_xcursor;
1742 /* Proceed to mx if it is at a sub-database */
1743 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
1745 if (! (mp && (mp->mp_flags & P_LEAF)))
1747 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
1748 if (!(leaf->mn_flags & F_SUBDATA))
1757 /* Mark dirty root pages */
1758 for (i=0; i<txn->mt_numdbs; i++) {
1759 if (txn->mt_dbflags[i] & DB_DIRTY) {
1760 pgno_t pgno = txn->mt_dbs[i].md_root;
1761 if (pgno == P_INVALID)
1763 if ((rc = mdb_page_get(txn, pgno, &dp, &level)) != MDB_SUCCESS)
1765 if ((dp->mp_flags & Mask) == pflags && level <= 1)
1766 dp->mp_flags ^= P_KEEP;
1774 static int mdb_page_flush(MDB_txn *txn, int keep);
1776 /** Spill pages from the dirty list back to disk.
1777 * This is intended to prevent running into #MDB_TXN_FULL situations,
1778 * but note that they may still occur in a few cases:
1779 * 1) our estimate of the txn size could be too small. Currently this
1780 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
1781 * 2) child txns may run out of space if their parents dirtied a
1782 * lot of pages and never spilled them. TODO: we probably should do
1783 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1784 * the parent's dirty_room is below a given threshold.
1786 * Otherwise, if not using nested txns, it is expected that apps will
1787 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1788 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1789 * If the txn never references them again, they can be left alone.
1790 * If the txn only reads them, they can be used without any fuss.
1791 * If the txn writes them again, they can be dirtied immediately without
1792 * going thru all of the work of #mdb_page_touch(). Such references are
1793 * handled by #mdb_page_unspill().
1795 * Also note, we never spill DB root pages, nor pages of active cursors,
1796 * because we'll need these back again soon anyway. And in nested txns,
1797 * we can't spill a page in a child txn if it was already spilled in a
1798 * parent txn. That would alter the parent txns' data even though
1799 * the child hasn't committed yet, and we'd have no way to undo it if
1800 * the child aborted.
1802 * @param[in] m0 cursor A cursor handle identifying the transaction and
1803 * database for which we are checking space.
1804 * @param[in] key For a put operation, the key being stored.
1805 * @param[in] data For a put operation, the data being stored.
1806 * @return 0 on success, non-zero on failure.
1809 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1811 MDB_txn *txn = m0->mc_txn;
1813 MDB_ID2L dl = txn->mt_u.dirty_list;
1814 unsigned int i, j, need;
1817 if (m0->mc_flags & C_SUB)
1820 /* Estimate how much space this op will take */
1821 i = m0->mc_db->md_depth;
1822 /* Named DBs also dirty the main DB */
1823 if (m0->mc_dbi > MAIN_DBI)
1824 i += txn->mt_dbs[MAIN_DBI].md_depth;
1825 /* For puts, roughly factor in the key+data size */
1827 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
1828 i += i; /* double it for good measure */
1831 if (txn->mt_dirty_room > i)
1834 if (!txn->mt_spill_pgs) {
1835 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
1836 if (!txn->mt_spill_pgs)
1839 /* purge deleted slots */
1840 MDB_IDL sl = txn->mt_spill_pgs;
1841 unsigned int num = sl[0];
1843 for (i=1; i<=num; i++) {
1850 /* Preserve pages which may soon be dirtied again */
1851 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
1854 /* Less aggressive spill - we originally spilled the entire dirty list,
1855 * with a few exceptions for cursor pages and DB root pages. But this
1856 * turns out to be a lot of wasted effort because in a large txn many
1857 * of those pages will need to be used again. So now we spill only 1/8th
1858 * of the dirty pages. Testing revealed this to be a good tradeoff,
1859 * better than 1/2, 1/4, or 1/10.
1861 if (need < MDB_IDL_UM_MAX / 8)
1862 need = MDB_IDL_UM_MAX / 8;
1864 /* Save the page IDs of all the pages we're flushing */
1865 /* flush from the tail forward, this saves a lot of shifting later on. */
1866 for (i=dl[0].mid; i && need; i--) {
1867 MDB_ID pn = dl[i].mid << 1;
1869 if (dp->mp_flags & (P_LOOSE|P_KEEP))
1871 /* Can't spill twice, make sure it's not already in a parent's
1874 if (txn->mt_parent) {
1876 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1877 if (tx2->mt_spill_pgs) {
1878 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
1879 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
1880 dp->mp_flags |= P_KEEP;
1888 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
1892 mdb_midl_sort(txn->mt_spill_pgs);
1894 /* Flush the spilled part of dirty list */
1895 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
1898 /* Reset any dirty pages we kept that page_flush didn't see */
1899 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
1902 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
1906 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
1908 mdb_find_oldest(MDB_txn *txn)
1911 txnid_t mr, oldest = txn->mt_txnid - 1;
1912 if (txn->mt_env->me_txns) {
1913 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
1914 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
1925 /** Add a page to the txn's dirty list */
1927 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
1930 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
1932 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1933 insert = mdb_mid2l_append;
1935 insert = mdb_mid2l_insert;
1937 mid.mid = mp->mp_pgno;
1939 rc = insert(txn->mt_u.dirty_list, &mid);
1940 mdb_tassert(txn, rc == 0);
1941 txn->mt_dirty_room--;
1944 /** Allocate page numbers and memory for writing. Maintain me_pglast,
1945 * me_pghead and mt_next_pgno.
1947 * If there are free pages available from older transactions, they
1948 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
1949 * Do not modify the freedB, just merge freeDB records into me_pghead[]
1950 * and move me_pglast to say which records were consumed. Only this
1951 * function can create me_pghead and move me_pglast/mt_next_pgno.
1952 * @param[in] mc cursor A cursor handle identifying the transaction and
1953 * database for which we are allocating.
1954 * @param[in] num the number of pages to allocate.
1955 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
1956 * will always be satisfied by a single contiguous chunk of memory.
1957 * @return 0 on success, non-zero on failure.
1960 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
1962 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
1963 /* Get at most <Max_retries> more freeDB records once me_pghead
1964 * has enough pages. If not enough, use new pages from the map.
1965 * If <Paranoid> and mc is updating the freeDB, only get new
1966 * records if me_pghead is empty. Then the freelist cannot play
1967 * catch-up with itself by growing while trying to save it.
1969 enum { Paranoid = 1, Max_retries = 500 };
1971 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
1973 int rc, retry = num * 60;
1974 MDB_txn *txn = mc->mc_txn;
1975 MDB_env *env = txn->mt_env;
1976 pgno_t pgno, *mop = env->me_pghead;
1977 unsigned i, j, mop_len = mop ? mop[0] : 0, n2 = num-1;
1979 txnid_t oldest = 0, last;
1984 /* If there are any loose pages, just use them */
1985 if (num == 1 && txn->mt_loose_pgs) {
1986 np = txn->mt_loose_pgs;
1987 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
1988 txn->mt_loose_count--;
1989 DPRINTF(("db %d use loose page %"Z"u", DDBI(mc),
1997 /* If our dirty list is already full, we can't do anything */
1998 if (txn->mt_dirty_room == 0) {
2003 for (op = MDB_FIRST;; op = MDB_NEXT) {
2008 /* Seek a big enough contiguous page range. Prefer
2009 * pages at the tail, just truncating the list.
2015 if (mop[i-n2] == pgno+n2)
2022 if (op == MDB_FIRST) { /* 1st iteration */
2023 /* Prepare to fetch more and coalesce */
2024 last = env->me_pglast;
2025 oldest = env->me_pgoldest;
2026 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
2029 key.mv_data = &last; /* will look up last+1 */
2030 key.mv_size = sizeof(last);
2032 if (Paranoid && mc->mc_dbi == FREE_DBI)
2035 if (Paranoid && retry < 0 && mop_len)
2039 /* Do not fetch more if the record will be too recent */
2040 if (oldest <= last) {
2042 oldest = mdb_find_oldest(txn);
2043 env->me_pgoldest = oldest;
2049 rc = mdb_cursor_get(&m2, &key, NULL, op);
2051 if (rc == MDB_NOTFOUND)
2055 last = *(txnid_t*)key.mv_data;
2056 if (oldest <= last) {
2058 oldest = mdb_find_oldest(txn);
2059 env->me_pgoldest = oldest;
2065 np = m2.mc_pg[m2.mc_top];
2066 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
2067 if ((rc = mdb_node_read(txn, leaf, &data)) != MDB_SUCCESS)
2070 idl = (MDB_ID *) data.mv_data;
2073 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
2078 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
2080 mop = env->me_pghead;
2082 env->me_pglast = last;
2084 DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
2085 last, txn->mt_dbs[FREE_DBI].md_root, i));
2087 DPRINTF(("IDL %"Z"u", idl[j]));
2089 /* Merge in descending sorted order */
2090 mdb_midl_xmerge(mop, idl);
2094 /* Use new pages from the map when nothing suitable in the freeDB */
2096 pgno = txn->mt_next_pgno;
2097 if (pgno + num >= env->me_maxpg) {
2098 DPUTS("DB size maxed out");
2104 if (env->me_flags & MDB_WRITEMAP) {
2105 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
2107 if (!(np = mdb_page_malloc(txn, num))) {
2113 mop[0] = mop_len -= num;
2114 /* Move any stragglers down */
2115 for (j = i-num; j < mop_len; )
2116 mop[++j] = mop[++i];
2118 txn->mt_next_pgno = pgno + num;
2121 mdb_page_dirty(txn, np);
2127 txn->mt_flags |= MDB_TXN_ERROR;
2131 /** Copy the used portions of a non-overflow page.
2132 * @param[in] dst page to copy into
2133 * @param[in] src page to copy from
2134 * @param[in] psize size of a page
2137 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2139 enum { Align = sizeof(pgno_t) };
2140 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2142 /* If page isn't full, just copy the used portion. Adjust
2143 * alignment so memcpy may copy words instead of bytes.
2145 if ((unused &= -Align) && !IS_LEAF2(src)) {
2146 upper = (upper + PAGEBASE) & -Align;
2147 memcpy(dst, src, (lower + PAGEBASE + (Align-1)) & -Align);
2148 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2151 memcpy(dst, src, psize - unused);
2155 /** Pull a page off the txn's spill list, if present.
2156 * If a page being referenced was spilled to disk in this txn, bring
2157 * it back and make it dirty/writable again.
2158 * @param[in] txn the transaction handle.
2159 * @param[in] mp the page being referenced. It must not be dirty.
2160 * @param[out] ret the writable page, if any. ret is unchanged if
2161 * mp wasn't spilled.
2164 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2166 MDB_env *env = txn->mt_env;
2169 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2171 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2172 if (!tx2->mt_spill_pgs)
2174 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2175 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2178 if (txn->mt_dirty_room == 0)
2179 return MDB_TXN_FULL;
2180 if (IS_OVERFLOW(mp))
2184 if (env->me_flags & MDB_WRITEMAP) {
2187 np = mdb_page_malloc(txn, num);
2191 memcpy(np, mp, num * env->me_psize);
2193 mdb_page_copy(np, mp, env->me_psize);
2196 /* If in current txn, this page is no longer spilled.
2197 * If it happens to be the last page, truncate the spill list.
2198 * Otherwise mark it as deleted by setting the LSB.
2200 if (x == txn->mt_spill_pgs[0])
2201 txn->mt_spill_pgs[0]--;
2203 txn->mt_spill_pgs[x] |= 1;
2204 } /* otherwise, if belonging to a parent txn, the
2205 * page remains spilled until child commits
2208 mdb_page_dirty(txn, np);
2209 np->mp_flags |= P_DIRTY;
2217 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2218 * @param[in] mc cursor pointing to the page to be touched
2219 * @return 0 on success, non-zero on failure.
2222 mdb_page_touch(MDB_cursor *mc)
2224 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2225 MDB_txn *txn = mc->mc_txn;
2226 MDB_cursor *m2, *m3;
2230 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2231 if (txn->mt_flags & MDB_TXN_SPILLS) {
2233 rc = mdb_page_unspill(txn, mp, &np);
2239 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2240 (rc = mdb_page_alloc(mc, 1, &np)))
2243 DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
2244 mp->mp_pgno, pgno));
2245 mdb_cassert(mc, mp->mp_pgno != pgno);
2246 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2247 /* Update the parent page, if any, to point to the new page */
2249 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2250 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2251 SETPGNO(node, pgno);
2253 mc->mc_db->md_root = pgno;
2255 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2256 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2258 /* If txn has a parent, make sure the page is in our
2262 unsigned x = mdb_mid2l_search(dl, pgno);
2263 if (x <= dl[0].mid && dl[x].mid == pgno) {
2264 if (mp != dl[x].mptr) { /* bad cursor? */
2265 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2266 txn->mt_flags |= MDB_TXN_ERROR;
2267 return MDB_CORRUPTED;
2272 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2274 np = mdb_page_malloc(txn, 1);
2279 rc = mdb_mid2l_insert(dl, &mid);
2280 mdb_cassert(mc, rc == 0);
2285 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2287 np->mp_flags |= P_DIRTY;
2290 /* Adjust cursors pointing to mp */
2291 mc->mc_pg[mc->mc_top] = np;
2292 m2 = txn->mt_cursors[mc->mc_dbi];
2293 if (mc->mc_flags & C_SUB) {
2294 for (; m2; m2=m2->mc_next) {
2295 m3 = &m2->mc_xcursor->mx_cursor;
2296 if (m3->mc_snum < mc->mc_snum) continue;
2297 if (m3->mc_pg[mc->mc_top] == mp)
2298 m3->mc_pg[mc->mc_top] = np;
2301 for (; m2; m2=m2->mc_next) {
2302 if (m2->mc_snum < mc->mc_snum) continue;
2303 if (m2->mc_pg[mc->mc_top] == mp) {
2304 m2->mc_pg[mc->mc_top] = np;
2305 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
2307 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
2309 MDB_node *leaf = NODEPTR(np, mc->mc_ki[mc->mc_top]);
2310 if (!(leaf->mn_flags & F_SUBDATA))
2311 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
2319 txn->mt_flags |= MDB_TXN_ERROR;
2324 mdb_env_sync(MDB_env *env, int force)
2327 if (env->me_flags & MDB_RDONLY)
2329 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2330 if (env->me_flags & MDB_WRITEMAP) {
2331 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2332 ? MS_ASYNC : MS_SYNC;
2333 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
2336 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2340 #ifdef BROKEN_FDATASYNC
2341 if (env->me_flags & MDB_FSYNCONLY) {
2342 if (fsync(env->me_fd))
2346 if (MDB_FDATASYNC(env->me_fd))
2353 /** Back up parent txn's cursors, then grab the originals for tracking */
2355 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2357 MDB_cursor *mc, *bk;
2362 for (i = src->mt_numdbs; --i >= 0; ) {
2363 if ((mc = src->mt_cursors[i]) != NULL) {
2364 size = sizeof(MDB_cursor);
2366 size += sizeof(MDB_xcursor);
2367 for (; mc; mc = bk->mc_next) {
2373 mc->mc_db = &dst->mt_dbs[i];
2374 /* Kill pointers into src - and dst to reduce abuse: The
2375 * user may not use mc until dst ends. Otherwise we'd...
2377 mc->mc_txn = NULL; /* ...set this to dst */
2378 mc->mc_dbflag = NULL; /* ...and &dst->mt_dbflags[i] */
2379 if ((mx = mc->mc_xcursor) != NULL) {
2380 *(MDB_xcursor *)(bk+1) = *mx;
2381 mx->mx_cursor.mc_txn = NULL; /* ...and dst. */
2383 mc->mc_next = dst->mt_cursors[i];
2384 dst->mt_cursors[i] = mc;
2391 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2392 * @param[in] txn the transaction handle.
2393 * @param[in] merge true to keep changes to parent cursors, false to revert.
2394 * @return 0 on success, non-zero on failure.
2397 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2399 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2403 for (i = txn->mt_numdbs; --i >= 0; ) {
2404 for (mc = cursors[i]; mc; mc = next) {
2406 if ((bk = mc->mc_backup) != NULL) {
2408 /* Commit changes to parent txn */
2409 mc->mc_next = bk->mc_next;
2410 mc->mc_backup = bk->mc_backup;
2411 mc->mc_txn = bk->mc_txn;
2412 mc->mc_db = bk->mc_db;
2413 mc->mc_dbflag = bk->mc_dbflag;
2414 if ((mx = mc->mc_xcursor) != NULL)
2415 mx->mx_cursor.mc_txn = bk->mc_txn;
2417 /* Abort nested txn */
2419 if ((mx = mc->mc_xcursor) != NULL)
2420 *mx = *(MDB_xcursor *)(bk+1);
2424 /* Only malloced cursors are permanently tracked. */
2432 #define mdb_txn_reset0(txn, act) mdb_txn_reset0(txn)
2435 mdb_txn_reset0(MDB_txn *txn, const char *act);
2437 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2443 Pidset = F_SETLK, Pidcheck = F_GETLK
2447 /** Set or check a pid lock. Set returns 0 on success.
2448 * Check returns 0 if the process is certainly dead, nonzero if it may
2449 * be alive (the lock exists or an error happened so we do not know).
2451 * On Windows Pidset is a no-op, we merely check for the existence
2452 * of the process with the given pid. On POSIX we use a single byte
2453 * lock on the lockfile, set at an offset equal to the pid.
2456 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2458 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2461 if (op == Pidcheck) {
2462 h = OpenProcess(env->me_pidquery, FALSE, pid);
2463 /* No documented "no such process" code, but other program use this: */
2465 return ErrCode() != ERROR_INVALID_PARAMETER;
2466 /* A process exists until all handles to it close. Has it exited? */
2467 ret = WaitForSingleObject(h, 0) != 0;
2474 struct flock lock_info;
2475 memset(&lock_info, 0, sizeof(lock_info));
2476 lock_info.l_type = F_WRLCK;
2477 lock_info.l_whence = SEEK_SET;
2478 lock_info.l_start = pid;
2479 lock_info.l_len = 1;
2480 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2481 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2483 } else if ((rc = ErrCode()) == EINTR) {
2491 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2492 * @param[in] txn the transaction handle to initialize
2493 * @return 0 on success, non-zero on failure.
2496 mdb_txn_renew0(MDB_txn *txn)
2498 MDB_env *env = txn->mt_env;
2499 MDB_txninfo *ti = env->me_txns;
2503 int rc, new_notls = 0;
2505 if (txn->mt_flags & MDB_TXN_RDONLY) {
2506 txn->mt_flags = MDB_TXN_RDONLY;
2508 txn->mt_numdbs = env->me_numdbs;
2509 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
2511 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2512 txn->mt_txnid = meta->mm_txnid;
2513 txn->mt_u.reader = NULL;
2515 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2516 pthread_getspecific(env->me_txkey);
2518 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2519 return MDB_BAD_RSLOT;
2521 MDB_PID_T pid = env->me_pid;
2522 MDB_THR_T tid = pthread_self();
2524 if (!env->me_live_reader) {
2525 rc = mdb_reader_pid(env, Pidset, pid);
2528 env->me_live_reader = 1;
2532 nr = ti->mti_numreaders;
2533 for (i=0; i<nr; i++)
2534 if (ti->mti_readers[i].mr_pid == 0)
2536 if (i == env->me_maxreaders) {
2537 UNLOCK_MUTEX_R(env);
2538 return MDB_READERS_FULL;
2540 ti->mti_readers[i].mr_pid = pid;
2541 ti->mti_readers[i].mr_tid = tid;
2543 ti->mti_numreaders = ++nr;
2544 /* Save numreaders for un-mutexed mdb_env_close() */
2545 env->me_numreaders = nr;
2546 UNLOCK_MUTEX_R(env);
2548 r = &ti->mti_readers[i];
2549 new_notls = (env->me_flags & MDB_NOTLS);
2550 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2555 do /* LY: Retry on a race, ITS#7970. */
2556 r->mr_txnid = ti->mti_txnid;
2557 while(r->mr_txnid != ti->mti_txnid);
2558 txn->mt_txnid = r->mr_txnid;
2559 txn->mt_u.reader = r;
2560 meta = env->me_metas[txn->mt_txnid & 1];
2566 txn->mt_txnid = ti->mti_txnid;
2567 meta = env->me_metas[txn->mt_txnid & 1];
2569 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2570 txn->mt_txnid = meta->mm_txnid;
2573 txn->mt_numdbs = env->me_numdbs;
2576 if (txn->mt_txnid == mdb_debug_start)
2580 txn->mt_child = NULL;
2581 txn->mt_loose_pgs = NULL;
2582 txn->mt_loose_count = 0;
2583 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2584 txn->mt_u.dirty_list = env->me_dirty_list;
2585 txn->mt_u.dirty_list[0].mid = 0;
2586 txn->mt_free_pgs = env->me_free_pgs;
2587 txn->mt_free_pgs[0] = 0;
2588 txn->mt_spill_pgs = NULL;
2590 memcpy(txn->mt_dbiseqs, env->me_dbiseqs, env->me_maxdbs * sizeof(unsigned int));
2593 /* Copy the DB info and flags */
2594 memcpy(txn->mt_dbs, meta->mm_dbs, 2 * sizeof(MDB_db));
2596 /* Moved to here to avoid a data race in read TXNs */
2597 txn->mt_next_pgno = meta->mm_last_pg+1;
2599 for (i=2; i<txn->mt_numdbs; i++) {
2600 x = env->me_dbflags[i];
2601 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2602 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_STALE : 0;
2604 txn->mt_dbflags[0] = txn->mt_dbflags[1] = DB_VALID;
2606 if (env->me_maxpg < txn->mt_next_pgno) {
2607 mdb_txn_reset0(txn, "renew0-mapfail");
2609 txn->mt_u.reader->mr_pid = 0;
2610 txn->mt_u.reader = NULL;
2612 return MDB_MAP_RESIZED;
2619 mdb_txn_renew(MDB_txn *txn)
2623 if (!txn || txn->mt_dbxs) /* A reset txn has mt_dbxs==NULL */
2626 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
2627 DPUTS("environment had fatal error, must shutdown!");
2631 rc = mdb_txn_renew0(txn);
2632 if (rc == MDB_SUCCESS) {
2633 DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2634 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2635 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2641 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2645 int rc, size, tsize = sizeof(MDB_txn);
2647 if (env->me_flags & MDB_FATAL_ERROR) {
2648 DPUTS("environment had fatal error, must shutdown!");
2651 if ((env->me_flags & MDB_RDONLY) && !(flags & MDB_RDONLY))
2654 /* Nested transactions: Max 1 child, write txns only, no writemap */
2655 if (parent->mt_child ||
2656 (flags & MDB_RDONLY) ||
2657 (parent->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR)) ||
2658 (env->me_flags & MDB_WRITEMAP))
2660 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
2662 tsize = sizeof(MDB_ntxn);
2665 if (!(flags & MDB_RDONLY)) {
2667 txn = env->me_txn0; /* just reuse preallocated write txn */
2670 /* child txns use own copy of cursors */
2671 size += env->me_maxdbs * sizeof(MDB_cursor *);
2673 size += env->me_maxdbs * (sizeof(MDB_db)+1);
2675 if ((txn = calloc(1, size)) == NULL) {
2676 DPRINTF(("calloc: %s", strerror(errno)));
2679 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2680 if (flags & MDB_RDONLY) {
2681 txn->mt_flags |= MDB_TXN_RDONLY;
2682 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
2683 txn->mt_dbiseqs = env->me_dbiseqs;
2685 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2687 txn->mt_dbiseqs = parent->mt_dbiseqs;
2688 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
2690 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
2691 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
2699 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2700 if (!txn->mt_u.dirty_list ||
2701 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2703 free(txn->mt_u.dirty_list);
2707 txn->mt_txnid = parent->mt_txnid;
2708 txn->mt_dirty_room = parent->mt_dirty_room;
2709 txn->mt_u.dirty_list[0].mid = 0;
2710 txn->mt_spill_pgs = NULL;
2711 txn->mt_next_pgno = parent->mt_next_pgno;
2712 parent->mt_child = txn;
2713 txn->mt_parent = parent;
2714 txn->mt_numdbs = parent->mt_numdbs;
2715 txn->mt_flags = parent->mt_flags;
2716 txn->mt_dbxs = parent->mt_dbxs;
2717 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2718 /* Copy parent's mt_dbflags, but clear DB_NEW */
2719 for (i=0; i<txn->mt_numdbs; i++)
2720 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2722 ntxn = (MDB_ntxn *)txn;
2723 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2724 if (env->me_pghead) {
2725 size = MDB_IDL_SIZEOF(env->me_pghead);
2726 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2728 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2733 rc = mdb_cursor_shadow(parent, txn);
2735 mdb_txn_reset0(txn, "beginchild-fail");
2737 rc = mdb_txn_renew0(txn);
2740 if (txn != env->me_txn0)
2744 DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2745 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2746 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
2753 mdb_txn_env(MDB_txn *txn)
2755 if(!txn) return NULL;
2759 /** Export or close DBI handles opened in this txn. */
2761 mdb_dbis_update(MDB_txn *txn, int keep)
2764 MDB_dbi n = txn->mt_numdbs;
2765 MDB_env *env = txn->mt_env;
2766 unsigned char *tdbflags = txn->mt_dbflags;
2768 for (i = n; --i >= 2;) {
2769 if (tdbflags[i] & DB_NEW) {
2771 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2773 char *ptr = env->me_dbxs[i].md_name.mv_data;
2775 env->me_dbxs[i].md_name.mv_data = NULL;
2776 env->me_dbxs[i].md_name.mv_size = 0;
2777 env->me_dbflags[i] = 0;
2778 env->me_dbiseqs[i]++;
2784 if (keep && env->me_numdbs < n)
2788 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
2789 * May be called twice for readonly txns: First reset it, then abort.
2790 * @param[in] txn the transaction handle to reset
2791 * @param[in] act why the transaction is being reset
2794 mdb_txn_reset0(MDB_txn *txn, const char *act)
2796 MDB_env *env = txn->mt_env;
2798 /* Close any DBI handles opened in this txn */
2799 mdb_dbis_update(txn, 0);
2801 DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2802 act, txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2803 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
2805 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2806 if (txn->mt_u.reader) {
2807 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2808 if (!(env->me_flags & MDB_NOTLS))
2809 txn->mt_u.reader = NULL; /* txn does not own reader */
2811 txn->mt_numdbs = 0; /* close nothing if called again */
2812 txn->mt_dbxs = NULL; /* mark txn as reset */
2814 pgno_t *pghead = env->me_pghead;
2816 mdb_cursors_close(txn, 0);
2817 if (!(env->me_flags & MDB_WRITEMAP)) {
2818 mdb_dlist_free(txn);
2821 if (!txn->mt_parent) {
2822 if (mdb_midl_shrink(&txn->mt_free_pgs))
2823 env->me_free_pgs = txn->mt_free_pgs;
2825 env->me_pghead = NULL;
2829 /* The writer mutex was locked in mdb_txn_begin. */
2831 UNLOCK_MUTEX_W(env);
2833 txn->mt_parent->mt_child = NULL;
2834 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2835 mdb_midl_free(txn->mt_free_pgs);
2836 mdb_midl_free(txn->mt_spill_pgs);
2837 free(txn->mt_u.dirty_list);
2840 mdb_midl_free(pghead);
2845 mdb_txn_reset(MDB_txn *txn)
2850 /* This call is only valid for read-only txns */
2851 if (!(txn->mt_flags & MDB_TXN_RDONLY))
2854 mdb_txn_reset0(txn, "reset");
2858 mdb_txn_abort(MDB_txn *txn)
2864 mdb_txn_abort(txn->mt_child);
2866 mdb_txn_reset0(txn, "abort");
2867 /* Free reader slot tied to this txn (if MDB_NOTLS && writable FS) */
2868 if ((txn->mt_flags & MDB_TXN_RDONLY) && txn->mt_u.reader)
2869 txn->mt_u.reader->mr_pid = 0;
2871 if (txn != txn->mt_env->me_txn0)
2875 /** Save the freelist as of this transaction to the freeDB.
2876 * This changes the freelist. Keep trying until it stabilizes.
2879 mdb_freelist_save(MDB_txn *txn)
2881 /* env->me_pghead[] can grow and shrink during this call.
2882 * env->me_pglast and txn->mt_free_pgs[] can only grow.
2883 * Page numbers cannot disappear from txn->mt_free_pgs[].
2886 MDB_env *env = txn->mt_env;
2887 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
2888 txnid_t pglast = 0, head_id = 0;
2889 pgno_t freecnt = 0, *free_pgs, *mop;
2890 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
2892 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
2894 if (env->me_pghead) {
2895 /* Make sure first page of freeDB is touched and on freelist */
2896 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
2897 if (rc && rc != MDB_NOTFOUND)
2901 if (!env->me_pghead && txn->mt_loose_pgs) {
2902 /* Put loose page numbers in mt_free_pgs, since
2903 * we may be unable to return them to me_pghead.
2905 MDB_page *mp = txn->mt_loose_pgs;
2906 if ((rc = mdb_midl_need(&txn->mt_free_pgs, txn->mt_loose_count)) != 0)
2908 for (; mp; mp = NEXT_LOOSE_PAGE(mp))
2909 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2910 txn->mt_loose_pgs = NULL;
2911 txn->mt_loose_count = 0;
2914 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
2915 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
2916 ? SSIZE_MAX : maxfree_1pg;
2919 /* Come back here after each Put() in case freelist changed */
2924 /* If using records from freeDB which we have not yet
2925 * deleted, delete them and any we reserved for me_pghead.
2927 while (pglast < env->me_pglast) {
2928 rc = mdb_cursor_first(&mc, &key, NULL);
2931 pglast = head_id = *(txnid_t *)key.mv_data;
2932 total_room = head_room = 0;
2933 mdb_tassert(txn, pglast <= env->me_pglast);
2934 rc = mdb_cursor_del(&mc, 0);
2939 /* Save the IDL of pages freed by this txn, to a single record */
2940 if (freecnt < txn->mt_free_pgs[0]) {
2942 /* Make sure last page of freeDB is touched and on freelist */
2943 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
2944 if (rc && rc != MDB_NOTFOUND)
2947 free_pgs = txn->mt_free_pgs;
2948 /* Write to last page of freeDB */
2949 key.mv_size = sizeof(txn->mt_txnid);
2950 key.mv_data = &txn->mt_txnid;
2952 freecnt = free_pgs[0];
2953 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
2954 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2957 /* Retry if mt_free_pgs[] grew during the Put() */
2958 free_pgs = txn->mt_free_pgs;
2959 } while (freecnt < free_pgs[0]);
2960 mdb_midl_sort(free_pgs);
2961 memcpy(data.mv_data, free_pgs, data.mv_size);
2964 unsigned int i = free_pgs[0];
2965 DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
2966 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
2968 DPRINTF(("IDL %"Z"u", free_pgs[i]));
2974 mop = env->me_pghead;
2975 mop_len = (mop ? mop[0] : 0) + txn->mt_loose_count;
2977 /* Reserve records for me_pghead[]. Split it if multi-page,
2978 * to avoid searching freeDB for a page range. Use keys in
2979 * range [1,me_pglast]: Smaller than txnid of oldest reader.
2981 if (total_room >= mop_len) {
2982 if (total_room == mop_len || --more < 0)
2984 } else if (head_room >= maxfree_1pg && head_id > 1) {
2985 /* Keep current record (overflow page), add a new one */
2989 /* (Re)write {key = head_id, IDL length = head_room} */
2990 total_room -= head_room;
2991 head_room = mop_len - total_room;
2992 if (head_room > maxfree_1pg && head_id > 1) {
2993 /* Overflow multi-page for part of me_pghead */
2994 head_room /= head_id; /* amortize page sizes */
2995 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
2996 } else if (head_room < 0) {
2997 /* Rare case, not bothering to delete this record */
3000 key.mv_size = sizeof(head_id);
3001 key.mv_data = &head_id;
3002 data.mv_size = (head_room + 1) * sizeof(pgno_t);
3003 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3006 /* IDL is initially empty, zero out at least the length */
3007 pgs = (pgno_t *)data.mv_data;
3008 j = head_room > clean_limit ? head_room : 0;
3012 total_room += head_room;
3015 /* Return loose page numbers to me_pghead, though usually none are
3016 * left at this point. The pages themselves remain in dirty_list.
3018 if (txn->mt_loose_pgs) {
3019 MDB_page *mp = txn->mt_loose_pgs;
3020 unsigned count = txn->mt_loose_count;
3022 /* Room for loose pages + temp IDL with same */
3023 if ((rc = mdb_midl_need(&env->me_pghead, 2*count+1)) != 0)
3025 mop = env->me_pghead;
3026 loose = mop + MDB_IDL_ALLOCLEN(mop) - count;
3027 for (count = 0; mp; mp = NEXT_LOOSE_PAGE(mp))
3028 loose[ ++count ] = mp->mp_pgno;
3030 mdb_midl_sort(loose);
3031 mdb_midl_xmerge(mop, loose);
3032 txn->mt_loose_pgs = NULL;
3033 txn->mt_loose_count = 0;
3037 /* Fill in the reserved me_pghead records */
3043 rc = mdb_cursor_first(&mc, &key, &data);
3044 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
3045 txnid_t id = *(txnid_t *)key.mv_data;
3046 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
3049 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
3051 if (len > mop_len) {
3053 data.mv_size = (len + 1) * sizeof(MDB_ID);
3055 data.mv_data = mop -= len;
3058 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
3060 if (rc || !(mop_len -= len))
3067 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
3068 * @param[in] txn the transaction that's being committed
3069 * @param[in] keep number of initial pages in dirty_list to keep dirty.
3070 * @return 0 on success, non-zero on failure.
3073 mdb_page_flush(MDB_txn *txn, int keep)
3075 MDB_env *env = txn->mt_env;
3076 MDB_ID2L dl = txn->mt_u.dirty_list;
3077 unsigned psize = env->me_psize, j;
3078 int i, pagecount = dl[0].mid, rc;
3079 size_t size = 0, pos = 0;
3081 MDB_page *dp = NULL;
3085 struct iovec iov[MDB_COMMIT_PAGES];
3086 ssize_t wpos = 0, wsize = 0, wres;
3087 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
3093 if (env->me_flags & MDB_WRITEMAP) {
3094 /* Clear dirty flags */
3095 while (++i <= pagecount) {
3097 /* Don't flush this page yet */
3098 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3099 dp->mp_flags &= ~P_KEEP;
3103 dp->mp_flags &= ~P_DIRTY;
3108 /* Write the pages */
3110 if (++i <= pagecount) {
3112 /* Don't flush this page yet */
3113 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3114 dp->mp_flags &= ~P_KEEP;
3119 /* clear dirty flag */
3120 dp->mp_flags &= ~P_DIRTY;
3123 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
3128 /* Windows actually supports scatter/gather I/O, but only on
3129 * unbuffered file handles. Since we're relying on the OS page
3130 * cache for all our data, that's self-defeating. So we just
3131 * write pages one at a time. We use the ov structure to set
3132 * the write offset, to at least save the overhead of a Seek
3135 DPRINTF(("committing page %"Z"u", pgno));
3136 memset(&ov, 0, sizeof(ov));
3137 ov.Offset = pos & 0xffffffff;
3138 ov.OffsetHigh = pos >> 16 >> 16;
3139 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
3141 DPRINTF(("WriteFile: %d", rc));
3145 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
3146 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
3149 /* Write previous page(s) */
3150 #ifdef MDB_USE_PWRITEV
3151 wres = pwritev(env->me_fd, iov, n, wpos);
3154 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
3157 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
3161 DPRINTF(("lseek: %s", strerror(rc)));
3164 wres = writev(env->me_fd, iov, n);
3167 if (wres != wsize) {
3172 DPRINTF(("Write error: %s", strerror(rc)));
3174 rc = EIO; /* TODO: Use which error code? */
3175 DPUTS("short write, filesystem full?");
3186 DPRINTF(("committing page %"Z"u", pgno));
3187 next_pos = pos + size;
3188 iov[n].iov_len = size;
3189 iov[n].iov_base = (char *)dp;
3195 /* MIPS has cache coherency issues, this is a no-op everywhere else
3196 * Note: for any size >= on-chip cache size, entire on-chip cache is
3199 CACHEFLUSH(env->me_map, txn->mt_next_pgno * env->me_psize, DCACHE);
3201 for (i = keep; ++i <= pagecount; ) {
3203 /* This is a page we skipped above */
3206 dl[j].mid = dp->mp_pgno;
3209 mdb_dpage_free(env, dp);
3214 txn->mt_dirty_room += i - j;
3220 mdb_txn_commit(MDB_txn *txn)
3226 if (txn == NULL || txn->mt_env == NULL)
3229 if (txn->mt_child) {
3230 rc = mdb_txn_commit(txn->mt_child);
3231 txn->mt_child = NULL;
3238 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3239 mdb_dbis_update(txn, 1);
3240 txn->mt_numdbs = 2; /* so txn_abort() doesn't close any new handles */
3245 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
3246 DPUTS("error flag is set, can't commit");
3248 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3253 if (txn->mt_parent) {
3254 MDB_txn *parent = txn->mt_parent;
3258 unsigned x, y, len, ps_len;
3260 /* Append our free list to parent's */
3261 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3264 mdb_midl_free(txn->mt_free_pgs);
3265 /* Failures after this must either undo the changes
3266 * to the parent or set MDB_TXN_ERROR in the parent.
3269 parent->mt_next_pgno = txn->mt_next_pgno;
3270 parent->mt_flags = txn->mt_flags;
3272 /* Merge our cursors into parent's and close them */
3273 mdb_cursors_close(txn, 1);
3275 /* Update parent's DB table. */
3276 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3277 parent->mt_numdbs = txn->mt_numdbs;
3278 parent->mt_dbflags[0] = txn->mt_dbflags[0];
3279 parent->mt_dbflags[1] = txn->mt_dbflags[1];
3280 for (i=2; i<txn->mt_numdbs; i++) {
3281 /* preserve parent's DB_NEW status */
3282 x = parent->mt_dbflags[i] & DB_NEW;
3283 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3286 dst = parent->mt_u.dirty_list;
3287 src = txn->mt_u.dirty_list;
3288 /* Remove anything in our dirty list from parent's spill list */
3289 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3291 pspill[0] = (pgno_t)-1;
3292 /* Mark our dirty pages as deleted in parent spill list */
3293 for (i=0, len=src[0].mid; ++i <= len; ) {
3294 MDB_ID pn = src[i].mid << 1;
3295 while (pn > pspill[x])
3297 if (pn == pspill[x]) {
3302 /* Squash deleted pagenums if we deleted any */
3303 for (x=y; ++x <= ps_len; )
3304 if (!(pspill[x] & 1))
3305 pspill[++y] = pspill[x];
3309 /* Find len = length of merging our dirty list with parent's */
3311 dst[0].mid = 0; /* simplify loops */
3312 if (parent->mt_parent) {
3313 len = x + src[0].mid;
3314 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3315 for (i = x; y && i; y--) {
3316 pgno_t yp = src[y].mid;
3317 while (yp < dst[i].mid)
3319 if (yp == dst[i].mid) {
3324 } else { /* Simplify the above for single-ancestor case */
3325 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3327 /* Merge our dirty list with parent's */
3329 for (i = len; y; dst[i--] = src[y--]) {
3330 pgno_t yp = src[y].mid;
3331 while (yp < dst[x].mid)
3332 dst[i--] = dst[x--];
3333 if (yp == dst[x].mid)
3334 free(dst[x--].mptr);
3336 mdb_tassert(txn, i == x);
3338 free(txn->mt_u.dirty_list);
3339 parent->mt_dirty_room = txn->mt_dirty_room;
3340 if (txn->mt_spill_pgs) {
3341 if (parent->mt_spill_pgs) {
3342 /* TODO: Prevent failure here, so parent does not fail */
3343 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3345 parent->mt_flags |= MDB_TXN_ERROR;
3346 mdb_midl_free(txn->mt_spill_pgs);
3347 mdb_midl_sort(parent->mt_spill_pgs);
3349 parent->mt_spill_pgs = txn->mt_spill_pgs;
3353 /* Append our loose page list to parent's */
3354 for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(lp))
3356 *lp = txn->mt_loose_pgs;
3357 parent->mt_loose_count += txn->mt_loose_count;
3359 parent->mt_child = NULL;
3360 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3365 if (txn != env->me_txn) {
3366 DPUTS("attempt to commit unknown transaction");
3371 mdb_cursors_close(txn, 0);
3373 if (!txn->mt_u.dirty_list[0].mid &&
3374 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
3377 DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
3378 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3380 /* Update DB root pointers */
3381 if (txn->mt_numdbs > 2) {
3385 data.mv_size = sizeof(MDB_db);
3387 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3388 for (i = 2; i < txn->mt_numdbs; i++) {
3389 if (txn->mt_dbflags[i] & DB_DIRTY) {
3390 if (TXN_DBI_CHANGED(txn, i)) {
3394 data.mv_data = &txn->mt_dbs[i];
3395 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
3402 rc = mdb_freelist_save(txn);
3406 mdb_midl_free(env->me_pghead);
3407 env->me_pghead = NULL;
3408 if (mdb_midl_shrink(&txn->mt_free_pgs))
3409 env->me_free_pgs = txn->mt_free_pgs;
3415 if ((rc = mdb_page_flush(txn, 0)) ||
3416 (rc = mdb_env_sync(env, 0)) ||
3417 (rc = mdb_env_write_meta(txn)))
3420 /* Free P_LOOSE pages left behind in dirty_list */
3421 if (!(env->me_flags & MDB_WRITEMAP))
3422 mdb_dlist_free(txn);
3427 mdb_dbis_update(txn, 1);
3430 UNLOCK_MUTEX_W(env);
3431 if (txn != env->me_txn0)
3441 /** Read the environment parameters of a DB environment before
3442 * mapping it into memory.
3443 * @param[in] env the environment handle
3444 * @param[out] meta address of where to store the meta information
3445 * @return 0 on success, non-zero on failure.
3448 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3454 enum { Size = sizeof(pbuf) };
3456 /* We don't know the page size yet, so use a minimum value.
3457 * Read both meta pages so we can use the latest one.
3460 for (i=off=0; i<2; i++, off = meta->mm_psize) {
3464 memset(&ov, 0, sizeof(ov));
3466 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3467 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3470 rc = pread(env->me_fd, &pbuf, Size, off);
3473 if (rc == 0 && off == 0)
3475 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3476 DPRINTF(("read: %s", mdb_strerror(rc)));
3480 p = (MDB_page *)&pbuf;
3482 if (!F_ISSET(p->mp_flags, P_META)) {
3483 DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
3488 if (m->mm_magic != MDB_MAGIC) {
3489 DPUTS("meta has invalid magic");
3493 if (m->mm_version != MDB_DATA_VERSION) {
3494 DPRINTF(("database is version %u, expected version %u",
3495 m->mm_version, MDB_DATA_VERSION));
3496 return MDB_VERSION_MISMATCH;
3499 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3506 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
3508 meta->mm_magic = MDB_MAGIC;
3509 meta->mm_version = MDB_DATA_VERSION;
3510 meta->mm_mapsize = env->me_mapsize;
3511 meta->mm_psize = env->me_psize;
3512 meta->mm_last_pg = 1;
3513 meta->mm_flags = env->me_flags & 0xffff;
3514 meta->mm_flags |= MDB_INTEGERKEY;
3515 meta->mm_dbs[0].md_root = P_INVALID;
3516 meta->mm_dbs[1].md_root = P_INVALID;
3519 /** Write the environment parameters of a freshly created DB environment.
3520 * @param[in] env the environment handle
3521 * @param[out] meta address of where to store the meta information
3522 * @return 0 on success, non-zero on failure.
3525 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3533 memset(&ov, 0, sizeof(ov));
3534 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3536 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3539 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3540 len = pwrite(fd, ptr, size, pos); \
3541 if (len == -1 && ErrCode() == EINTR) continue; \
3542 rc = (len >= 0); break; } while(1)
3545 DPUTS("writing new meta page");
3547 psize = env->me_psize;
3549 mdb_env_init_meta0(env, meta);
3551 p = calloc(2, psize);
3553 p->mp_flags = P_META;
3554 *(MDB_meta *)METADATA(p) = *meta;
3556 q = (MDB_page *)((char *)p + psize);
3558 q->mp_flags = P_META;
3559 *(MDB_meta *)METADATA(q) = *meta;
3561 DO_PWRITE(rc, env->me_fd, p, psize * 2, len, 0);
3564 else if ((unsigned) len == psize * 2)
3572 /** Update the environment info to commit a transaction.
3573 * @param[in] txn the transaction that's being committed
3574 * @return 0 on success, non-zero on failure.
3577 mdb_env_write_meta(MDB_txn *txn)
3580 MDB_meta meta, metab, *mp;
3583 int rc, len, toggle;
3592 toggle = txn->mt_txnid & 1;
3593 DPRINTF(("writing meta page %d for root page %"Z"u",
3594 toggle, txn->mt_dbs[MAIN_DBI].md_root));
3597 mp = env->me_metas[toggle];
3598 mapsize = env->me_metas[toggle ^ 1]->mm_mapsize;
3599 /* Persist any increases of mapsize config */
3600 if (mapsize < env->me_mapsize)
3601 mapsize = env->me_mapsize;
3603 if (env->me_flags & MDB_WRITEMAP) {
3604 mp->mm_mapsize = mapsize;
3605 mp->mm_dbs[0] = txn->mt_dbs[0];
3606 mp->mm_dbs[1] = txn->mt_dbs[1];
3607 mp->mm_last_pg = txn->mt_next_pgno - 1;
3608 mp->mm_txnid = txn->mt_txnid;
3609 if (!(env->me_flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3610 unsigned meta_size = env->me_psize;
3611 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3614 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
3615 if (meta_size < env->me_os_psize)
3616 meta_size += meta_size;
3621 if (MDB_MSYNC(ptr, meta_size, rc)) {
3628 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
3629 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
3631 meta.mm_mapsize = mapsize;
3632 meta.mm_dbs[0] = txn->mt_dbs[0];
3633 meta.mm_dbs[1] = txn->mt_dbs[1];
3634 meta.mm_last_pg = txn->mt_next_pgno - 1;
3635 meta.mm_txnid = txn->mt_txnid;
3637 off = offsetof(MDB_meta, mm_mapsize);
3638 ptr = (char *)&meta + off;
3639 len = sizeof(MDB_meta) - off;
3641 off += env->me_psize;
3644 /* Write to the SYNC fd */
3645 mfd = env->me_flags & (MDB_NOSYNC|MDB_NOMETASYNC) ?
3646 env->me_fd : env->me_mfd;
3650 memset(&ov, 0, sizeof(ov));
3652 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3656 rc = pwrite(mfd, ptr, len, off);
3659 rc = rc < 0 ? ErrCode() : EIO;
3662 DPUTS("write failed, disk error?");
3663 /* On a failure, the pagecache still contains the new data.
3664 * Write some old data back, to prevent it from being used.
3665 * Use the non-SYNC fd; we know it will fail anyway.
3667 meta.mm_last_pg = metab.mm_last_pg;
3668 meta.mm_txnid = metab.mm_txnid;
3670 memset(&ov, 0, sizeof(ov));
3672 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3674 r2 = pwrite(env->me_fd, ptr, len, off);
3675 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
3678 env->me_flags |= MDB_FATAL_ERROR;
3681 /* MIPS has cache coherency issues, this is a no-op everywhere else */
3682 CACHEFLUSH(env->me_map + off, len, DCACHE);
3684 /* Memory ordering issues are irrelevant; since the entire writer
3685 * is wrapped by wmutex, all of these changes will become visible
3686 * after the wmutex is unlocked. Since the DB is multi-version,
3687 * readers will get consistent data regardless of how fresh or
3688 * how stale their view of these values is.
3691 env->me_txns->mti_txnid = txn->mt_txnid;
3696 /** Check both meta pages to see which one is newer.
3697 * @param[in] env the environment handle
3698 * @return meta toggle (0 or 1).
3701 mdb_env_pick_meta(const MDB_env *env)
3703 return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
3707 mdb_env_create(MDB_env **env)
3711 e = calloc(1, sizeof(MDB_env));
3715 e->me_maxreaders = DEFAULT_READERS;
3716 e->me_maxdbs = e->me_numdbs = 2;
3717 e->me_fd = INVALID_HANDLE_VALUE;
3718 e->me_lfd = INVALID_HANDLE_VALUE;
3719 e->me_mfd = INVALID_HANDLE_VALUE;
3720 #ifdef MDB_USE_POSIX_SEM
3721 e->me_rmutex = SEM_FAILED;
3722 e->me_wmutex = SEM_FAILED;
3724 e->me_pid = getpid();
3725 GET_PAGESIZE(e->me_os_psize);
3726 VGMEMP_CREATE(e,0,0);
3732 mdb_env_map(MDB_env *env, void *addr)
3735 unsigned int flags = env->me_flags;
3739 LONG sizelo, sizehi;
3742 if (flags & MDB_RDONLY) {
3743 /* Don't set explicit map size, use whatever exists */
3748 msize = env->me_mapsize;
3749 sizelo = msize & 0xffffffff;
3750 sizehi = msize >> 16 >> 16; /* only needed on Win64 */
3752 /* Windows won't create mappings for zero length files.
3753 * and won't map more than the file size.
3754 * Just set the maxsize right now.
3756 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3757 || !SetEndOfFile(env->me_fd)
3758 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3762 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3763 PAGE_READWRITE : PAGE_READONLY,
3764 sizehi, sizelo, NULL);
3767 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3768 FILE_MAP_WRITE : FILE_MAP_READ,
3770 rc = env->me_map ? 0 : ErrCode();
3775 int prot = PROT_READ;
3776 if (flags & MDB_WRITEMAP) {
3778 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3781 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
3783 if (env->me_map == MAP_FAILED) {
3788 if (flags & MDB_NORDAHEAD) {
3789 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3791 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3793 #ifdef POSIX_MADV_RANDOM
3794 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3795 #endif /* POSIX_MADV_RANDOM */
3796 #endif /* MADV_RANDOM */
3800 /* Can happen because the address argument to mmap() is just a
3801 * hint. mmap() can pick another, e.g. if the range is in use.
3802 * The MAP_FIXED flag would prevent that, but then mmap could
3803 * instead unmap existing pages to make room for the new map.
3805 if (addr && env->me_map != addr)
3806 return EBUSY; /* TODO: Make a new MDB_* error code? */
3808 p = (MDB_page *)env->me_map;
3809 env->me_metas[0] = METADATA(p);
3810 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
3816 mdb_env_set_mapsize(MDB_env *env, size_t size)
3818 /* If env is already open, caller is responsible for making
3819 * sure there are no active txns.
3827 size = env->me_metas[mdb_env_pick_meta(env)]->mm_mapsize;
3828 else if (size < env->me_mapsize) {
3829 /* If the configured size is smaller, make sure it's
3830 * still big enough. Silently round up to minimum if not.
3832 size_t minsize = (env->me_metas[mdb_env_pick_meta(env)]->mm_last_pg + 1) * env->me_psize;
3836 munmap(env->me_map, env->me_mapsize);
3837 env->me_mapsize = size;
3838 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
3839 rc = mdb_env_map(env, old);
3843 env->me_mapsize = size;
3845 env->me_maxpg = env->me_mapsize / env->me_psize;
3850 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
3854 env->me_maxdbs = dbs + 2; /* Named databases + main and free DB */
3859 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
3861 if (env->me_map || readers < 1)
3863 env->me_maxreaders = readers;
3868 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
3870 if (!env || !readers)
3872 *readers = env->me_maxreaders;
3877 mdb_fsize(HANDLE fd, size_t *size)
3880 LARGE_INTEGER fsize;
3882 if (!GetFileSizeEx(fd, &fsize))
3885 *size = fsize.QuadPart;
3897 #ifdef BROKEN_FDATASYNC
3898 #include <sys/utsname.h>
3899 #include <sys/vfs.h>
3902 /** Further setup required for opening an LMDB environment
3905 mdb_env_open2(MDB_env *env)
3907 unsigned int flags = env->me_flags;
3908 int i, newenv = 0, rc;
3912 /* See if we should use QueryLimited */
3914 if ((rc & 0xff) > 5)
3915 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
3917 env->me_pidquery = PROCESS_QUERY_INFORMATION;
3919 #ifdef BROKEN_FDATASYNC
3920 /* ext3/ext4 fdatasync is broken on some older Linux kernels.
3921 * https://lkml.org/lkml/2012/9/3/83
3922 * Kernels after 3.6-rc6 are known good.
3923 * https://lkml.org/lkml/2012/9/10/556
3924 * See if the DB is on ext3/ext4, then check for new enough kernel
3925 * Kernels 2.6.32.60, 2.6.34.15, 3.2.30, and 3.5.4 are also known
3930 fstatfs(env->me_fd, &st);
3931 while (st.f_type == 0xEF53) {
3935 if (uts.release[0] < '3') {
3936 if (!strncmp(uts.release, "2.6.32.", 7)) {
3937 i = atoi(uts.release+7);
3939 break; /* 2.6.32.60 and newer is OK */
3940 } else if (!strncmp(uts.release, "2.6.34.", 7)) {
3941 i = atoi(uts.release+7);
3943 break; /* 2.6.34.15 and newer is OK */
3945 } else if (uts.release[0] == '3') {
3946 i = atoi(uts.release+2);
3948 break; /* 3.6 and newer is OK */
3950 i = atoi(uts.release+4);
3952 break; /* 3.5.4 and newer is OK */
3953 } else if (i == 2) {
3954 i = atoi(uts.release+4);
3956 break; /* 3.2.30 and newer is OK */
3958 } else { /* 4.x and newer is OK */
3961 env->me_flags |= MDB_FSYNCONLY;
3967 memset(&meta, 0, sizeof(meta));
3969 if ((i = mdb_env_read_header(env, &meta)) != 0) {
3972 DPUTS("new mdbenv");
3974 env->me_psize = env->me_os_psize;
3975 if (env->me_psize > MAX_PAGESIZE)
3976 env->me_psize = MAX_PAGESIZE;
3978 env->me_psize = meta.mm_psize;
3981 /* Was a mapsize configured? */
3982 if (!env->me_mapsize) {
3983 /* If this is a new environment, take the default,
3984 * else use the size recorded in the existing env.
3986 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
3987 } else if (env->me_mapsize < meta.mm_mapsize) {
3988 /* If the configured size is smaller, make sure it's
3989 * still big enough. Silently round up to minimum if not.
3991 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
3992 if (env->me_mapsize < minsize)
3993 env->me_mapsize = minsize;
3996 rc = mdb_env_map(env, (flags & MDB_FIXEDMAP) ? meta.mm_address : NULL);
4001 if (flags & MDB_FIXEDMAP)
4002 meta.mm_address = env->me_map;
4003 i = mdb_env_init_meta(env, &meta);
4004 if (i != MDB_SUCCESS) {
4009 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
4010 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
4012 #if !(MDB_MAXKEYSIZE)
4013 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
4015 env->me_maxpg = env->me_mapsize / env->me_psize;
4019 int toggle = mdb_env_pick_meta(env);
4020 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
4022 DPRINTF(("opened database version %u, pagesize %u",
4023 env->me_metas[0]->mm_version, env->me_psize));
4024 DPRINTF(("using meta page %d", toggle));
4025 DPRINTF(("depth: %u", db->md_depth));
4026 DPRINTF(("entries: %"Z"u", db->md_entries));
4027 DPRINTF(("branch pages: %"Z"u", db->md_branch_pages));
4028 DPRINTF(("leaf pages: %"Z"u", db->md_leaf_pages));
4029 DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
4030 DPRINTF(("root: %"Z"u", db->md_root));
4038 /** Release a reader thread's slot in the reader lock table.
4039 * This function is called automatically when a thread exits.
4040 * @param[in] ptr This points to the slot in the reader lock table.
4043 mdb_env_reader_dest(void *ptr)
4045 MDB_reader *reader = ptr;
4051 /** Junk for arranging thread-specific callbacks on Windows. This is
4052 * necessarily platform and compiler-specific. Windows supports up
4053 * to 1088 keys. Let's assume nobody opens more than 64 environments
4054 * in a single process, for now. They can override this if needed.
4056 #ifndef MAX_TLS_KEYS
4057 #define MAX_TLS_KEYS 64
4059 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
4060 static int mdb_tls_nkeys;
4062 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
4066 case DLL_PROCESS_ATTACH: break;
4067 case DLL_THREAD_ATTACH: break;
4068 case DLL_THREAD_DETACH:
4069 for (i=0; i<mdb_tls_nkeys; i++) {
4070 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
4072 mdb_env_reader_dest(r);
4076 case DLL_PROCESS_DETACH: break;
4081 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4083 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4087 /* Force some symbol references.
4088 * _tls_used forces the linker to create the TLS directory if not already done
4089 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
4091 #pragma comment(linker, "/INCLUDE:_tls_used")
4092 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
4093 #pragma const_seg(".CRT$XLB")
4094 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
4095 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4098 #pragma comment(linker, "/INCLUDE:__tls_used")
4099 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
4100 #pragma data_seg(".CRT$XLB")
4101 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4103 #endif /* WIN 32/64 */
4104 #endif /* !__GNUC__ */
4107 /** Downgrade the exclusive lock on the region back to shared */
4109 mdb_env_share_locks(MDB_env *env, int *excl)
4111 int rc = 0, toggle = mdb_env_pick_meta(env);
4113 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
4118 /* First acquire a shared lock. The Unlock will
4119 * then release the existing exclusive lock.
4121 memset(&ov, 0, sizeof(ov));
4122 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4125 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4131 struct flock lock_info;
4132 /* The shared lock replaces the existing lock */
4133 memset((void *)&lock_info, 0, sizeof(lock_info));
4134 lock_info.l_type = F_RDLCK;
4135 lock_info.l_whence = SEEK_SET;
4136 lock_info.l_start = 0;
4137 lock_info.l_len = 1;
4138 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4139 (rc = ErrCode()) == EINTR) ;
4140 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
4147 /** Try to get exclusive lock, otherwise shared.
4148 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
4151 mdb_env_excl_lock(MDB_env *env, int *excl)
4155 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
4159 memset(&ov, 0, sizeof(ov));
4160 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4167 struct flock lock_info;
4168 memset((void *)&lock_info, 0, sizeof(lock_info));
4169 lock_info.l_type = F_WRLCK;
4170 lock_info.l_whence = SEEK_SET;
4171 lock_info.l_start = 0;
4172 lock_info.l_len = 1;
4173 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4174 (rc = ErrCode()) == EINTR) ;
4178 # ifdef MDB_USE_POSIX_SEM
4179 if (*excl < 0) /* always true when !MDB_USE_POSIX_SEM */
4182 lock_info.l_type = F_RDLCK;
4183 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
4184 (rc = ErrCode()) == EINTR) ;
4194 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
4196 * @(#) $Revision: 5.1 $
4197 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
4198 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
4200 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
4204 * Please do not copyright this code. This code is in the public domain.
4206 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
4207 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
4208 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
4209 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
4210 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4211 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4212 * PERFORMANCE OF THIS SOFTWARE.
4215 * chongo <Landon Curt Noll> /\oo/\
4216 * http://www.isthe.com/chongo/
4218 * Share and Enjoy! :-)
4221 typedef unsigned long long mdb_hash_t;
4222 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
4224 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
4225 * @param[in] val value to hash
4226 * @param[in] hval initial value for hash
4227 * @return 64 bit hash
4229 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
4230 * hval arg on the first call.
4233 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
4235 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
4236 unsigned char *end = s + val->mv_size;
4238 * FNV-1a hash each octet of the string
4241 /* xor the bottom with the current octet */
4242 hval ^= (mdb_hash_t)*s++;
4244 /* multiply by the 64 bit FNV magic prime mod 2^64 */
4245 hval += (hval << 1) + (hval << 4) + (hval << 5) +
4246 (hval << 7) + (hval << 8) + (hval << 40);
4248 /* return our new hash value */
4252 /** Hash the string and output the encoded hash.
4253 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
4254 * very short name limits. We don't care about the encoding being reversible,
4255 * we just want to preserve as many bits of the input as possible in a
4256 * small printable string.
4257 * @param[in] str string to hash
4258 * @param[out] encbuf an array of 11 chars to hold the hash
4260 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
4263 mdb_pack85(unsigned long l, char *out)
4267 for (i=0; i<5; i++) {
4268 *out++ = mdb_a85[l % 85];
4274 mdb_hash_enc(MDB_val *val, char *encbuf)
4276 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
4278 mdb_pack85(h, encbuf);
4279 mdb_pack85(h>>32, encbuf+5);
4284 /** Open and/or initialize the lock region for the environment.
4285 * @param[in] env The LMDB environment.
4286 * @param[in] lpath The pathname of the file used for the lock region.
4287 * @param[in] mode The Unix permissions for the file, if we create it.
4288 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
4289 * @return 0 on success, non-zero on failure.
4292 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
4295 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
4297 # define MDB_ERRCODE_ROFS EROFS
4298 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
4299 # define MDB_CLOEXEC O_CLOEXEC
4302 # define MDB_CLOEXEC 0
4309 env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
4310 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
4311 FILE_ATTRIBUTE_NORMAL, NULL);
4313 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
4315 if (env->me_lfd == INVALID_HANDLE_VALUE) {
4317 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
4322 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
4323 /* Lose record locks when exec*() */
4324 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
4325 fcntl(env->me_lfd, F_SETFD, fdflags);
4328 if (!(env->me_flags & MDB_NOTLS)) {
4329 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
4332 env->me_flags |= MDB_ENV_TXKEY;
4334 /* Windows TLS callbacks need help finding their TLS info. */
4335 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
4339 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
4343 /* Try to get exclusive lock. If we succeed, then
4344 * nobody is using the lock region and we should initialize it.
4346 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
4349 size = GetFileSize(env->me_lfd, NULL);
4351 size = lseek(env->me_lfd, 0, SEEK_END);
4352 if (size == -1) goto fail_errno;
4354 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
4355 if (size < rsize && *excl > 0) {
4357 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
4358 || !SetEndOfFile(env->me_lfd))
4361 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
4365 size = rsize - sizeof(MDB_txninfo);
4366 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
4371 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
4373 if (!mh) goto fail_errno;
4374 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
4376 if (!env->me_txns) goto fail_errno;
4378 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
4380 if (m == MAP_FAILED) goto fail_errno;
4386 BY_HANDLE_FILE_INFORMATION stbuf;
4395 if (!mdb_sec_inited) {
4396 InitializeSecurityDescriptor(&mdb_null_sd,
4397 SECURITY_DESCRIPTOR_REVISION);
4398 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
4399 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
4400 mdb_all_sa.bInheritHandle = FALSE;
4401 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
4404 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
4405 idbuf.volume = stbuf.dwVolumeSerialNumber;
4406 idbuf.nhigh = stbuf.nFileIndexHigh;
4407 idbuf.nlow = stbuf.nFileIndexLow;
4408 val.mv_data = &idbuf;
4409 val.mv_size = sizeof(idbuf);
4410 mdb_hash_enc(&val, encbuf);
4411 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
4412 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
4413 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
4414 if (!env->me_rmutex) goto fail_errno;
4415 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
4416 if (!env->me_wmutex) goto fail_errno;
4417 #elif defined(MDB_USE_POSIX_SEM)
4426 #if defined(__NetBSD__)
4427 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
4429 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
4430 idbuf.dev = stbuf.st_dev;
4431 idbuf.ino = stbuf.st_ino;
4432 val.mv_data = &idbuf;
4433 val.mv_size = sizeof(idbuf);
4434 mdb_hash_enc(&val, encbuf);
4435 #ifdef MDB_SHORT_SEMNAMES
4436 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
4438 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
4439 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
4440 /* Clean up after a previous run, if needed: Try to
4441 * remove both semaphores before doing anything else.
4443 sem_unlink(env->me_txns->mti_rmname);
4444 sem_unlink(env->me_txns->mti_wmname);
4445 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
4446 O_CREAT|O_EXCL, mode, 1);
4447 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4448 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
4449 O_CREAT|O_EXCL, mode, 1);
4450 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4451 #else /* MDB_USE_POSIX_SEM */
4452 pthread_mutexattr_t mattr;
4454 if ((rc = pthread_mutexattr_init(&mattr))
4455 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
4456 || (rc = pthread_mutex_init(&env->me_txns->mti_mutex, &mattr))
4457 || (rc = pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr)))
4459 pthread_mutexattr_destroy(&mattr);
4460 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
4462 env->me_txns->mti_magic = MDB_MAGIC;
4463 env->me_txns->mti_format = MDB_LOCK_FORMAT;
4464 env->me_txns->mti_txnid = 0;
4465 env->me_txns->mti_numreaders = 0;
4468 if (env->me_txns->mti_magic != MDB_MAGIC) {
4469 DPUTS("lock region has invalid magic");
4473 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
4474 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
4475 env->me_txns->mti_format, MDB_LOCK_FORMAT));
4476 rc = MDB_VERSION_MISMATCH;
4480 if (rc && rc != EACCES && rc != EAGAIN) {
4484 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
4485 if (!env->me_rmutex) goto fail_errno;
4486 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
4487 if (!env->me_wmutex) goto fail_errno;
4488 #elif defined(MDB_USE_POSIX_SEM)
4489 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
4490 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4491 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
4492 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4503 /** The name of the lock file in the DB environment */
4504 #define LOCKNAME "/lock.mdb"
4505 /** The name of the data file in the DB environment */
4506 #define DATANAME "/data.mdb"
4507 /** The suffix of the lock file when no subdir is used */
4508 #define LOCKSUFF "-lock"
4509 /** Only a subset of the @ref mdb_env flags can be changed
4510 * at runtime. Changing other flags requires closing the
4511 * environment and re-opening it with the new flags.
4513 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
4514 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY|MDB_WRITEMAP| \
4515 MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
4517 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
4518 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
4522 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
4524 int oflags, rc, len, excl = -1;
4525 char *lpath, *dpath;
4527 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
4531 if (flags & MDB_NOSUBDIR) {
4532 rc = len + sizeof(LOCKSUFF) + len + 1;
4534 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
4539 if (flags & MDB_NOSUBDIR) {
4540 dpath = lpath + len + sizeof(LOCKSUFF);
4541 sprintf(lpath, "%s" LOCKSUFF, path);
4542 strcpy(dpath, path);
4544 dpath = lpath + len + sizeof(LOCKNAME);
4545 sprintf(lpath, "%s" LOCKNAME, path);
4546 sprintf(dpath, "%s" DATANAME, path);
4550 flags |= env->me_flags;
4551 if (flags & MDB_RDONLY) {
4552 /* silently ignore WRITEMAP when we're only getting read access */
4553 flags &= ~MDB_WRITEMAP;
4555 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
4556 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
4559 env->me_flags = flags |= MDB_ENV_ACTIVE;
4563 env->me_path = strdup(path);
4564 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
4565 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
4566 env->me_dbiseqs = calloc(env->me_maxdbs, sizeof(unsigned int));
4567 if (!(env->me_dbxs && env->me_path && env->me_dbflags && env->me_dbiseqs)) {
4572 /* For RDONLY, get lockfile after we know datafile exists */
4573 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
4574 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4580 if (F_ISSET(flags, MDB_RDONLY)) {
4581 oflags = GENERIC_READ;
4582 len = OPEN_EXISTING;
4584 oflags = GENERIC_READ|GENERIC_WRITE;
4587 mode = FILE_ATTRIBUTE_NORMAL;
4588 env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
4589 NULL, len, mode, NULL);
4591 if (F_ISSET(flags, MDB_RDONLY))
4594 oflags = O_RDWR | O_CREAT;
4596 env->me_fd = open(dpath, oflags, mode);
4598 if (env->me_fd == INVALID_HANDLE_VALUE) {
4603 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
4604 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4609 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
4610 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
4611 env->me_mfd = env->me_fd;
4613 /* Synchronous fd for meta writes. Needed even with
4614 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
4617 len = OPEN_EXISTING;
4618 env->me_mfd = CreateFile(dpath, oflags,
4619 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
4620 mode | FILE_FLAG_WRITE_THROUGH, NULL);
4623 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
4625 if (env->me_mfd == INVALID_HANDLE_VALUE) {
4630 DPRINTF(("opened dbenv %p", (void *) env));
4632 rc = mdb_env_share_locks(env, &excl);
4636 if (!((flags & MDB_RDONLY) ||
4637 (env->me_pbuf = calloc(1, env->me_psize))))
4639 if (!(flags & MDB_RDONLY)) {
4641 int tsize = sizeof(MDB_txn), size = tsize + env->me_maxdbs *
4642 (sizeof(MDB_db)+sizeof(MDB_cursor *)+sizeof(unsigned int)+1);
4643 txn = calloc(1, size);
4645 txn->mt_dbs = (MDB_db *)((char *)txn + tsize);
4646 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
4647 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
4648 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
4650 txn->mt_dbxs = env->me_dbxs;
4660 mdb_env_close0(env, excl);
4666 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
4668 mdb_env_close0(MDB_env *env, int excl)
4672 if (!(env->me_flags & MDB_ENV_ACTIVE))
4675 /* Doing this here since me_dbxs may not exist during mdb_env_close */
4677 for (i = env->me_maxdbs; --i > MAIN_DBI; )
4678 free(env->me_dbxs[i].md_name.mv_data);
4683 free(env->me_dbiseqs);
4684 free(env->me_dbflags);
4686 free(env->me_dirty_list);
4688 mdb_midl_free(env->me_free_pgs);
4690 if (env->me_flags & MDB_ENV_TXKEY) {
4691 pthread_key_delete(env->me_txkey);
4693 /* Delete our key from the global list */
4694 for (i=0; i<mdb_tls_nkeys; i++)
4695 if (mdb_tls_keys[i] == env->me_txkey) {
4696 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
4704 munmap(env->me_map, env->me_mapsize);
4706 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
4707 (void) close(env->me_mfd);
4708 if (env->me_fd != INVALID_HANDLE_VALUE)
4709 (void) close(env->me_fd);
4711 MDB_PID_T pid = env->me_pid;
4712 /* Clearing readers is done in this function because
4713 * me_txkey with its destructor must be disabled first.
4715 for (i = env->me_numreaders; --i >= 0; )
4716 if (env->me_txns->mti_readers[i].mr_pid == pid)
4717 env->me_txns->mti_readers[i].mr_pid = 0;
4719 if (env->me_rmutex) {
4720 CloseHandle(env->me_rmutex);
4721 if (env->me_wmutex) CloseHandle(env->me_wmutex);
4723 /* Windows automatically destroys the mutexes when
4724 * the last handle closes.
4726 #elif defined(MDB_USE_POSIX_SEM)
4727 if (env->me_rmutex != SEM_FAILED) {
4728 sem_close(env->me_rmutex);
4729 if (env->me_wmutex != SEM_FAILED)
4730 sem_close(env->me_wmutex);
4731 /* If we have the filelock: If we are the
4732 * only remaining user, clean up semaphores.
4735 mdb_env_excl_lock(env, &excl);
4737 sem_unlink(env->me_txns->mti_rmname);
4738 sem_unlink(env->me_txns->mti_wmname);
4742 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
4744 if (env->me_lfd != INVALID_HANDLE_VALUE) {
4747 /* Unlock the lockfile. Windows would have unlocked it
4748 * after closing anyway, but not necessarily at once.
4750 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4753 (void) close(env->me_lfd);
4756 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
4761 mdb_env_close(MDB_env *env)
4768 VGMEMP_DESTROY(env);
4769 while ((dp = env->me_dpages) != NULL) {
4770 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
4771 env->me_dpages = dp->mp_next;
4775 mdb_env_close0(env, 0);
4779 /** Compare two items pointing at aligned size_t's */
4781 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
4783 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
4784 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
4787 /** Compare two items pointing at aligned unsigned int's.
4789 * This is also set as #MDB_INTEGERDUP|#MDB_DUPFIXED's #MDB_dbx.%md_dcmp,
4790 * but #mdb_cmp_clong() is called instead if the data type is size_t.
4793 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
4795 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
4796 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
4799 /** Compare two items pointing at unsigned ints of unknown alignment.
4800 * Nodes and keys are guaranteed to be 2-byte aligned.
4803 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
4805 #if BYTE_ORDER == LITTLE_ENDIAN
4806 unsigned short *u, *c;
4809 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4810 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
4813 } while(!x && u > (unsigned short *)a->mv_data);
4816 unsigned short *u, *c, *end;
4819 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4820 u = (unsigned short *)a->mv_data;
4821 c = (unsigned short *)b->mv_data;
4824 } while(!x && u < end);
4829 /** Compare two items lexically */
4831 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
4838 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4844 diff = memcmp(a->mv_data, b->mv_data, len);
4845 return diff ? diff : len_diff<0 ? -1 : len_diff;
4848 /** Compare two items in reverse byte order */
4850 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
4852 const unsigned char *p1, *p2, *p1_lim;
4856 p1_lim = (const unsigned char *)a->mv_data;
4857 p1 = (const unsigned char *)a->mv_data + a->mv_size;
4858 p2 = (const unsigned char *)b->mv_data + b->mv_size;
4860 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4866 while (p1 > p1_lim) {
4867 diff = *--p1 - *--p2;
4871 return len_diff<0 ? -1 : len_diff;
4874 /** Search for key within a page, using binary search.
4875 * Returns the smallest entry larger or equal to the key.
4876 * If exactp is non-null, stores whether the found entry was an exact match
4877 * in *exactp (1 or 0).
4878 * Updates the cursor index with the index of the found entry.
4879 * If no entry larger or equal to the key is found, returns NULL.
4882 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
4884 unsigned int i = 0, nkeys;
4887 MDB_page *mp = mc->mc_pg[mc->mc_top];
4888 MDB_node *node = NULL;
4893 nkeys = NUMKEYS(mp);
4895 DPRINTF(("searching %u keys in %s %spage %"Z"u",
4896 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
4899 low = IS_LEAF(mp) ? 0 : 1;
4901 cmp = mc->mc_dbx->md_cmp;
4903 /* Branch pages have no data, so if using integer keys,
4904 * alignment is guaranteed. Use faster mdb_cmp_int.
4906 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
4907 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
4914 nodekey.mv_size = mc->mc_db->md_pad;
4915 node = NODEPTR(mp, 0); /* fake */
4916 while (low <= high) {
4917 i = (low + high) >> 1;
4918 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
4919 rc = cmp(key, &nodekey);
4920 DPRINTF(("found leaf index %u [%s], rc = %i",
4921 i, DKEY(&nodekey), rc));
4930 while (low <= high) {
4931 i = (low + high) >> 1;
4933 node = NODEPTR(mp, i);
4934 nodekey.mv_size = NODEKSZ(node);
4935 nodekey.mv_data = NODEKEY(node);
4937 rc = cmp(key, &nodekey);
4940 DPRINTF(("found leaf index %u [%s], rc = %i",
4941 i, DKEY(&nodekey), rc));
4943 DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
4944 i, DKEY(&nodekey), NODEPGNO(node), rc));
4955 if (rc > 0) { /* Found entry is less than the key. */
4956 i++; /* Skip to get the smallest entry larger than key. */
4958 node = NODEPTR(mp, i);
4961 *exactp = (rc == 0 && nkeys > 0);
4962 /* store the key index */
4963 mc->mc_ki[mc->mc_top] = i;
4965 /* There is no entry larger or equal to the key. */
4968 /* nodeptr is fake for LEAF2 */
4974 mdb_cursor_adjust(MDB_cursor *mc, func)
4978 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4979 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
4986 /** Pop a page off the top of the cursor's stack. */
4988 mdb_cursor_pop(MDB_cursor *mc)
4992 MDB_page *top = mc->mc_pg[mc->mc_top];
4998 DPRINTF(("popped page %"Z"u off db %d cursor %p", top->mp_pgno,
4999 DDBI(mc), (void *) mc));
5003 /** Push a page onto the top of the cursor's stack. */
5005 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
5007 DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
5008 DDBI(mc), (void *) mc));
5010 if (mc->mc_snum >= CURSOR_STACK) {
5011 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5012 return MDB_CURSOR_FULL;
5015 mc->mc_top = mc->mc_snum++;
5016 mc->mc_pg[mc->mc_top] = mp;
5017 mc->mc_ki[mc->mc_top] = 0;
5022 /** Find the address of the page corresponding to a given page number.
5023 * @param[in] txn the transaction for this access.
5024 * @param[in] pgno the page number for the page to retrieve.
5025 * @param[out] ret address of a pointer where the page's address will be stored.
5026 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
5027 * @return 0 on success, non-zero on failure.
5030 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
5032 MDB_env *env = txn->mt_env;
5036 if (!((txn->mt_flags & MDB_TXN_RDONLY) | (env->me_flags & MDB_WRITEMAP))) {
5040 MDB_ID2L dl = tx2->mt_u.dirty_list;
5042 /* Spilled pages were dirtied in this txn and flushed
5043 * because the dirty list got full. Bring this page
5044 * back in from the map (but don't unspill it here,
5045 * leave that unless page_touch happens again).
5047 if (tx2->mt_spill_pgs) {
5048 MDB_ID pn = pgno << 1;
5049 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
5050 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
5051 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5056 unsigned x = mdb_mid2l_search(dl, pgno);
5057 if (x <= dl[0].mid && dl[x].mid == pgno) {
5063 } while ((tx2 = tx2->mt_parent) != NULL);
5066 if (pgno < txn->mt_next_pgno) {
5068 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5070 DPRINTF(("page %"Z"u not found", pgno));
5071 txn->mt_flags |= MDB_TXN_ERROR;
5072 return MDB_PAGE_NOTFOUND;
5082 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
5083 * The cursor is at the root page, set up the rest of it.
5086 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
5088 MDB_page *mp = mc->mc_pg[mc->mc_top];
5092 while (IS_BRANCH(mp)) {
5096 DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
5097 mdb_cassert(mc, NUMKEYS(mp) > 1);
5098 DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
5100 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
5102 if (flags & MDB_PS_LAST)
5103 i = NUMKEYS(mp) - 1;
5106 node = mdb_node_search(mc, key, &exact);
5108 i = NUMKEYS(mp) - 1;
5110 i = mc->mc_ki[mc->mc_top];
5112 mdb_cassert(mc, i > 0);
5116 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
5119 mdb_cassert(mc, i < NUMKEYS(mp));
5120 node = NODEPTR(mp, i);
5122 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
5125 mc->mc_ki[mc->mc_top] = i;
5126 if ((rc = mdb_cursor_push(mc, mp)))
5129 if (flags & MDB_PS_MODIFY) {
5130 if ((rc = mdb_page_touch(mc)) != 0)
5132 mp = mc->mc_pg[mc->mc_top];
5137 DPRINTF(("internal error, index points to a %02X page!?",
5139 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5140 return MDB_CORRUPTED;
5143 DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
5144 key ? DKEY(key) : "null"));
5145 mc->mc_flags |= C_INITIALIZED;
5146 mc->mc_flags &= ~C_EOF;
5151 /** Search for the lowest key under the current branch page.
5152 * This just bypasses a NUMKEYS check in the current page
5153 * before calling mdb_page_search_root(), because the callers
5154 * are all in situations where the current page is known to
5158 mdb_page_search_lowest(MDB_cursor *mc)
5160 MDB_page *mp = mc->mc_pg[mc->mc_top];
5161 MDB_node *node = NODEPTR(mp, 0);
5164 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
5167 mc->mc_ki[mc->mc_top] = 0;
5168 if ((rc = mdb_cursor_push(mc, mp)))
5170 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
5173 /** Search for the page a given key should be in.
5174 * Push it and its parent pages on the cursor stack.
5175 * @param[in,out] mc the cursor for this operation.
5176 * @param[in] key the key to search for, or NULL for first/last page.
5177 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
5178 * are touched (updated with new page numbers).
5179 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
5180 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
5181 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
5182 * @return 0 on success, non-zero on failure.
5185 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
5190 /* Make sure the txn is still viable, then find the root from
5191 * the txn's db table and set it as the root of the cursor's stack.
5193 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
5194 DPUTS("transaction has failed, must abort");
5197 /* Make sure we're using an up-to-date root */
5198 if (*mc->mc_dbflag & DB_STALE) {
5200 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
5202 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
5203 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
5210 MDB_node *leaf = mdb_node_search(&mc2,
5211 &mc->mc_dbx->md_name, &exact);
5213 return MDB_NOTFOUND;
5214 rc = mdb_node_read(mc->mc_txn, leaf, &data);
5217 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
5219 /* The txn may not know this DBI, or another process may
5220 * have dropped and recreated the DB with other flags.
5222 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
5223 return MDB_INCOMPATIBLE;
5224 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
5226 *mc->mc_dbflag &= ~DB_STALE;
5228 root = mc->mc_db->md_root;
5230 if (root == P_INVALID) { /* Tree is empty. */
5231 DPUTS("tree is empty");
5232 return MDB_NOTFOUND;
5236 mdb_cassert(mc, root > 1);
5237 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
5238 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0], NULL)) != 0)
5244 DPRINTF(("db %d root page %"Z"u has flags 0x%X",
5245 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
5247 if (flags & MDB_PS_MODIFY) {
5248 if ((rc = mdb_page_touch(mc)))
5252 if (flags & MDB_PS_ROOTONLY)
5255 return mdb_page_search_root(mc, key, flags);
5259 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
5261 MDB_txn *txn = mc->mc_txn;
5262 pgno_t pg = mp->mp_pgno;
5263 unsigned x = 0, ovpages = mp->mp_pages;
5264 MDB_env *env = txn->mt_env;
5265 MDB_IDL sl = txn->mt_spill_pgs;
5266 MDB_ID pn = pg << 1;
5269 DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
5270 /* If the page is dirty or on the spill list we just acquired it,
5271 * so we should give it back to our current free list, if any.
5272 * Otherwise put it onto the list of pages we freed in this txn.
5274 * Won't create me_pghead: me_pglast must be inited along with it.
5275 * Unsupported in nested txns: They would need to hide the page
5276 * range in ancestor txns' dirty and spilled lists.
5278 if (env->me_pghead &&
5280 ((mp->mp_flags & P_DIRTY) ||
5281 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
5285 MDB_ID2 *dl, ix, iy;
5286 rc = mdb_midl_need(&env->me_pghead, ovpages);
5289 if (!(mp->mp_flags & P_DIRTY)) {
5290 /* This page is no longer spilled */
5297 /* Remove from dirty list */
5298 dl = txn->mt_u.dirty_list;
5300 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
5306 mdb_cassert(mc, x > 1);
5308 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
5309 txn->mt_flags |= MDB_TXN_ERROR;
5310 return MDB_CORRUPTED;
5313 if (!(env->me_flags & MDB_WRITEMAP))
5314 mdb_dpage_free(env, mp);
5316 /* Insert in me_pghead */
5317 mop = env->me_pghead;
5318 j = mop[0] + ovpages;
5319 for (i = mop[0]; i && mop[i] < pg; i--)
5325 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
5329 mc->mc_db->md_overflow_pages -= ovpages;
5333 /** Return the data associated with a given node.
5334 * @param[in] txn The transaction for this operation.
5335 * @param[in] leaf The node being read.
5336 * @param[out] data Updated to point to the node's data.
5337 * @return 0 on success, non-zero on failure.
5340 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
5342 MDB_page *omp; /* overflow page */
5346 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5347 data->mv_size = NODEDSZ(leaf);
5348 data->mv_data = NODEDATA(leaf);
5352 /* Read overflow data.
5354 data->mv_size = NODEDSZ(leaf);
5355 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
5356 if ((rc = mdb_page_get(txn, pgno, &omp, NULL)) != 0) {
5357 DPRINTF(("read overflow page %"Z"u failed", pgno));
5360 data->mv_data = METADATA(omp);
5366 mdb_get(MDB_txn *txn, MDB_dbi dbi,
5367 MDB_val *key, MDB_val *data)
5374 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
5376 if (!key || !data || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
5379 if (txn->mt_flags & MDB_TXN_ERROR)
5382 mdb_cursor_init(&mc, txn, dbi, &mx);
5383 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
5386 /** Find a sibling for a page.
5387 * Replaces the page at the top of the cursor's stack with the
5388 * specified sibling, if one exists.
5389 * @param[in] mc The cursor for this operation.
5390 * @param[in] move_right Non-zero if the right sibling is requested,
5391 * otherwise the left sibling.
5392 * @return 0 on success, non-zero on failure.
5395 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
5401 if (mc->mc_snum < 2) {
5402 return MDB_NOTFOUND; /* root has no siblings */
5406 DPRINTF(("parent page is page %"Z"u, index %u",
5407 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
5409 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
5410 : (mc->mc_ki[mc->mc_top] == 0)) {
5411 DPRINTF(("no more keys left, moving to %s sibling",
5412 move_right ? "right" : "left"));
5413 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
5414 /* undo cursor_pop before returning */
5421 mc->mc_ki[mc->mc_top]++;
5423 mc->mc_ki[mc->mc_top]--;
5424 DPRINTF(("just moving to %s index key %u",
5425 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
5427 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
5429 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5430 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL)) != 0) {
5431 /* mc will be inconsistent if caller does mc_snum++ as above */
5432 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
5436 mdb_cursor_push(mc, mp);
5438 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
5443 /** Move the cursor to the next data item. */
5445 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5451 if (mc->mc_flags & C_EOF) {
5452 return MDB_NOTFOUND;
5455 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5457 mp = mc->mc_pg[mc->mc_top];
5459 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5460 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5461 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5462 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
5463 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
5464 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
5465 if (rc == MDB_SUCCESS)
5466 MDB_GET_KEY(leaf, key);
5471 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5472 if (op == MDB_NEXT_DUP)
5473 return MDB_NOTFOUND;
5477 DPRINTF(("cursor_next: top page is %"Z"u in cursor %p",
5478 mdb_dbg_pgno(mp), (void *) mc));
5479 if (mc->mc_flags & C_DEL)
5482 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
5483 DPUTS("=====> move to next sibling page");
5484 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5485 mc->mc_flags |= C_EOF;
5488 mp = mc->mc_pg[mc->mc_top];
5489 DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5491 mc->mc_ki[mc->mc_top]++;
5494 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5495 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5498 key->mv_size = mc->mc_db->md_pad;
5499 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5503 mdb_cassert(mc, IS_LEAF(mp));
5504 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5506 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5507 mdb_xcursor_init1(mc, leaf);
5510 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5513 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5514 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5515 if (rc != MDB_SUCCESS)
5520 MDB_GET_KEY(leaf, key);
5524 /** Move the cursor to the previous data item. */
5526 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5532 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5534 mp = mc->mc_pg[mc->mc_top];
5536 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5537 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5538 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5539 if (op == MDB_PREV || op == MDB_PREV_DUP) {
5540 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
5541 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
5542 if (rc == MDB_SUCCESS) {
5543 MDB_GET_KEY(leaf, key);
5544 mc->mc_flags &= ~C_EOF;
5550 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5551 if (op == MDB_PREV_DUP)
5552 return MDB_NOTFOUND;
5556 DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p",
5557 mdb_dbg_pgno(mp), (void *) mc));
5559 if (mc->mc_ki[mc->mc_top] == 0) {
5560 DPUTS("=====> move to prev sibling page");
5561 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
5564 mp = mc->mc_pg[mc->mc_top];
5565 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
5566 DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5568 mc->mc_ki[mc->mc_top]--;
5570 mc->mc_flags &= ~C_EOF;
5572 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5573 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5576 key->mv_size = mc->mc_db->md_pad;
5577 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5581 mdb_cassert(mc, IS_LEAF(mp));
5582 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5584 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5585 mdb_xcursor_init1(mc, leaf);
5588 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5591 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5592 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5593 if (rc != MDB_SUCCESS)
5598 MDB_GET_KEY(leaf, key);
5602 /** Set the cursor on a specific data item. */
5604 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5605 MDB_cursor_op op, int *exactp)
5609 MDB_node *leaf = NULL;
5612 if (key->mv_size == 0)
5613 return MDB_BAD_VALSIZE;
5616 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5618 /* See if we're already on the right page */
5619 if (mc->mc_flags & C_INITIALIZED) {
5622 mp = mc->mc_pg[mc->mc_top];
5624 mc->mc_ki[mc->mc_top] = 0;
5625 return MDB_NOTFOUND;
5627 if (mp->mp_flags & P_LEAF2) {
5628 nodekey.mv_size = mc->mc_db->md_pad;
5629 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
5631 leaf = NODEPTR(mp, 0);
5632 MDB_GET_KEY2(leaf, nodekey);
5634 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5636 /* Probably happens rarely, but first node on the page
5637 * was the one we wanted.
5639 mc->mc_ki[mc->mc_top] = 0;
5646 unsigned int nkeys = NUMKEYS(mp);
5648 if (mp->mp_flags & P_LEAF2) {
5649 nodekey.mv_data = LEAF2KEY(mp,
5650 nkeys-1, nodekey.mv_size);
5652 leaf = NODEPTR(mp, nkeys-1);
5653 MDB_GET_KEY2(leaf, nodekey);
5655 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5657 /* last node was the one we wanted */
5658 mc->mc_ki[mc->mc_top] = nkeys-1;
5664 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
5665 /* This is definitely the right page, skip search_page */
5666 if (mp->mp_flags & P_LEAF2) {
5667 nodekey.mv_data = LEAF2KEY(mp,
5668 mc->mc_ki[mc->mc_top], nodekey.mv_size);
5670 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5671 MDB_GET_KEY2(leaf, nodekey);
5673 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5675 /* current node was the one we wanted */
5685 /* If any parents have right-sibs, search.
5686 * Otherwise, there's nothing further.
5688 for (i=0; i<mc->mc_top; i++)
5690 NUMKEYS(mc->mc_pg[i])-1)
5692 if (i == mc->mc_top) {
5693 /* There are no other pages */
5694 mc->mc_ki[mc->mc_top] = nkeys;
5695 return MDB_NOTFOUND;
5699 /* There are no other pages */
5700 mc->mc_ki[mc->mc_top] = 0;
5701 if (op == MDB_SET_RANGE && !exactp) {
5705 return MDB_NOTFOUND;
5709 rc = mdb_page_search(mc, key, 0);
5710 if (rc != MDB_SUCCESS)
5713 mp = mc->mc_pg[mc->mc_top];
5714 mdb_cassert(mc, IS_LEAF(mp));
5717 leaf = mdb_node_search(mc, key, exactp);
5718 if (exactp != NULL && !*exactp) {
5719 /* MDB_SET specified and not an exact match. */
5720 return MDB_NOTFOUND;
5724 DPUTS("===> inexact leaf not found, goto sibling");
5725 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
5726 return rc; /* no entries matched */
5727 mp = mc->mc_pg[mc->mc_top];
5728 mdb_cassert(mc, IS_LEAF(mp));
5729 leaf = NODEPTR(mp, 0);
5733 mc->mc_flags |= C_INITIALIZED;
5734 mc->mc_flags &= ~C_EOF;
5737 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
5738 key->mv_size = mc->mc_db->md_pad;
5739 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5744 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5745 mdb_xcursor_init1(mc, leaf);
5748 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5749 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
5750 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5753 if (op == MDB_GET_BOTH) {
5759 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
5760 if (rc != MDB_SUCCESS)
5763 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
5766 if ((rc = mdb_node_read(mc->mc_txn, leaf, &olddata)) != MDB_SUCCESS)
5768 dcmp = mc->mc_dbx->md_dcmp;
5769 #if UINT_MAX < SIZE_MAX
5770 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
5771 dcmp = mdb_cmp_clong;
5773 rc = dcmp(data, &olddata);
5775 if (op == MDB_GET_BOTH || rc > 0)
5776 return MDB_NOTFOUND;
5783 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5784 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5789 /* The key already matches in all other cases */
5790 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
5791 MDB_GET_KEY(leaf, key);
5792 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
5797 /** Move the cursor to the first item in the database. */
5799 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5805 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5807 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5808 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
5809 if (rc != MDB_SUCCESS)
5812 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
5814 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
5815 mc->mc_flags |= C_INITIALIZED;
5816 mc->mc_flags &= ~C_EOF;
5818 mc->mc_ki[mc->mc_top] = 0;
5820 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5821 key->mv_size = mc->mc_db->md_pad;
5822 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
5827 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5828 mdb_xcursor_init1(mc, leaf);
5829 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5833 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5837 MDB_GET_KEY(leaf, key);
5841 /** Move the cursor to the last item in the database. */
5843 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5849 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5851 if (!(mc->mc_flags & C_EOF)) {
5853 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5854 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
5855 if (rc != MDB_SUCCESS)
5858 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
5861 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
5862 mc->mc_flags |= C_INITIALIZED|C_EOF;
5863 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5865 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5866 key->mv_size = mc->mc_db->md_pad;
5867 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
5872 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5873 mdb_xcursor_init1(mc, leaf);
5874 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5878 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5883 MDB_GET_KEY(leaf, key);
5888 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5893 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
5898 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
5902 case MDB_GET_CURRENT:
5903 if (!(mc->mc_flags & C_INITIALIZED)) {
5906 MDB_page *mp = mc->mc_pg[mc->mc_top];
5907 int nkeys = NUMKEYS(mp);
5908 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
5909 mc->mc_ki[mc->mc_top] = nkeys;
5915 key->mv_size = mc->mc_db->md_pad;
5916 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5918 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5919 MDB_GET_KEY(leaf, key);
5921 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5922 if (mc->mc_flags & C_DEL)
5923 mdb_xcursor_init1(mc, leaf);
5924 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
5926 rc = mdb_node_read(mc->mc_txn, leaf, data);
5933 case MDB_GET_BOTH_RANGE:
5938 if (mc->mc_xcursor == NULL) {
5939 rc = MDB_INCOMPATIBLE;
5949 rc = mdb_cursor_set(mc, key, data, op,
5950 op == MDB_SET_RANGE ? NULL : &exact);
5953 case MDB_GET_MULTIPLE:
5954 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5958 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5959 rc = MDB_INCOMPATIBLE;
5963 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
5964 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
5967 case MDB_NEXT_MULTIPLE:
5972 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5973 rc = MDB_INCOMPATIBLE;
5976 if (!(mc->mc_flags & C_INITIALIZED))
5977 rc = mdb_cursor_first(mc, key, data);
5979 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
5980 if (rc == MDB_SUCCESS) {
5981 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
5984 mx = &mc->mc_xcursor->mx_cursor;
5985 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
5987 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
5988 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
5996 case MDB_NEXT_NODUP:
5997 if (!(mc->mc_flags & C_INITIALIZED))
5998 rc = mdb_cursor_first(mc, key, data);
6000 rc = mdb_cursor_next(mc, key, data, op);
6004 case MDB_PREV_NODUP:
6005 if (!(mc->mc_flags & C_INITIALIZED)) {
6006 rc = mdb_cursor_last(mc, key, data);
6009 mc->mc_flags |= C_INITIALIZED;
6010 mc->mc_ki[mc->mc_top]++;
6012 rc = mdb_cursor_prev(mc, key, data, op);
6015 rc = mdb_cursor_first(mc, key, data);
6018 mfunc = mdb_cursor_first;
6020 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
6024 if (mc->mc_xcursor == NULL) {
6025 rc = MDB_INCOMPATIBLE;
6029 MDB_node *leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6030 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6031 MDB_GET_KEY(leaf, key);
6032 rc = mdb_node_read(mc->mc_txn, leaf, data);
6036 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
6040 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
6043 rc = mdb_cursor_last(mc, key, data);
6046 mfunc = mdb_cursor_last;
6049 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
6054 if (mc->mc_flags & C_DEL)
6055 mc->mc_flags ^= C_DEL;
6060 /** Touch all the pages in the cursor stack. Set mc_top.
6061 * Makes sure all the pages are writable, before attempting a write operation.
6062 * @param[in] mc The cursor to operate on.
6065 mdb_cursor_touch(MDB_cursor *mc)
6067 int rc = MDB_SUCCESS;
6069 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
6072 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
6074 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
6075 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
6078 *mc->mc_dbflag |= DB_DIRTY;
6083 rc = mdb_page_touch(mc);
6084 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
6085 mc->mc_top = mc->mc_snum-1;
6090 /** Do not spill pages to disk if txn is getting full, may fail instead */
6091 #define MDB_NOSPILL 0x8000
6094 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6097 enum { MDB_NO_ROOT = MDB_LAST_ERRCODE+10 }; /* internal code */
6099 MDB_node *leaf = NULL;
6102 MDB_val xdata, *rdata, dkey, olddata;
6104 int do_sub = 0, insert_key, insert_data;
6105 unsigned int mcount = 0, dcount = 0, nospill;
6108 unsigned int nflags;
6111 if (mc == NULL || key == NULL)
6114 env = mc->mc_txn->mt_env;
6116 /* Check this first so counter will always be zero on any
6119 if (flags & MDB_MULTIPLE) {
6120 dcount = data[1].mv_size;
6121 data[1].mv_size = 0;
6122 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
6123 return MDB_INCOMPATIBLE;
6126 nospill = flags & MDB_NOSPILL;
6127 flags &= ~MDB_NOSPILL;
6129 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
6130 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6132 if (key->mv_size-1 >= ENV_MAXKEY(env))
6133 return MDB_BAD_VALSIZE;
6135 #if SIZE_MAX > MAXDATASIZE
6136 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
6137 return MDB_BAD_VALSIZE;
6139 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
6140 return MDB_BAD_VALSIZE;
6143 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
6144 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
6148 if (flags == MDB_CURRENT) {
6149 if (!(mc->mc_flags & C_INITIALIZED))
6152 } else if (mc->mc_db->md_root == P_INVALID) {
6153 /* new database, cursor has nothing to point to */
6156 mc->mc_flags &= ~C_INITIALIZED;
6161 if (flags & MDB_APPEND) {
6163 rc = mdb_cursor_last(mc, &k2, &d2);
6165 rc = mc->mc_dbx->md_cmp(key, &k2);
6168 mc->mc_ki[mc->mc_top]++;
6170 /* new key is <= last key */
6175 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
6177 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
6178 DPRINTF(("duplicate key [%s]", DKEY(key)));
6180 return MDB_KEYEXIST;
6182 if (rc && rc != MDB_NOTFOUND)
6186 if (mc->mc_flags & C_DEL)
6187 mc->mc_flags ^= C_DEL;
6189 /* Cursor is positioned, check for room in the dirty list */
6191 if (flags & MDB_MULTIPLE) {
6193 xdata.mv_size = data->mv_size * dcount;
6197 if ((rc2 = mdb_page_spill(mc, key, rdata)))
6201 if (rc == MDB_NO_ROOT) {
6203 /* new database, write a root leaf page */
6204 DPUTS("allocating new root leaf page");
6205 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
6208 mdb_cursor_push(mc, np);
6209 mc->mc_db->md_root = np->mp_pgno;
6210 mc->mc_db->md_depth++;
6211 *mc->mc_dbflag |= DB_DIRTY;
6212 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
6214 np->mp_flags |= P_LEAF2;
6215 mc->mc_flags |= C_INITIALIZED;
6217 /* make sure all cursor pages are writable */
6218 rc2 = mdb_cursor_touch(mc);
6223 insert_key = insert_data = rc;
6225 /* The key does not exist */
6226 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
6227 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
6228 LEAFSIZE(key, data) > env->me_nodemax)
6230 /* Too big for a node, insert in sub-DB. Set up an empty
6231 * "old sub-page" for prep_subDB to expand to a full page.
6233 fp_flags = P_LEAF|P_DIRTY;
6235 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
6236 fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
6237 olddata.mv_size = PAGEHDRSZ;
6241 /* there's only a key anyway, so this is a no-op */
6242 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6244 unsigned int ksize = mc->mc_db->md_pad;
6245 if (key->mv_size != ksize)
6246 return MDB_BAD_VALSIZE;
6247 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
6248 memcpy(ptr, key->mv_data, ksize);
6250 /* if overwriting slot 0 of leaf, need to
6251 * update branch key if there is a parent page
6253 if (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
6254 unsigned short top = mc->mc_top;
6256 /* slot 0 is always an empty key, find real slot */
6257 while (mc->mc_top && !mc->mc_ki[mc->mc_top])
6259 if (mc->mc_ki[mc->mc_top])
6260 rc2 = mdb_update_key(mc, key);
6271 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6272 olddata.mv_size = NODEDSZ(leaf);
6273 olddata.mv_data = NODEDATA(leaf);
6276 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
6277 /* Prepare (sub-)page/sub-DB to accept the new item,
6278 * if needed. fp: old sub-page or a header faking
6279 * it. mp: new (sub-)page. offset: growth in page
6280 * size. xdata: node data with new page or DB.
6282 unsigned i, offset = 0;
6283 mp = fp = xdata.mv_data = env->me_pbuf;
6284 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
6286 /* Was a single item before, must convert now */
6287 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6289 /* Just overwrite the current item */
6290 if (flags == MDB_CURRENT)
6292 dcmp = mc->mc_dbx->md_dcmp;
6293 #if UINT_MAX < SIZE_MAX
6294 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
6295 dcmp = mdb_cmp_clong;
6297 /* does data match? */
6298 if (!dcmp(data, &olddata)) {
6299 if (flags & MDB_NODUPDATA)
6300 return MDB_KEYEXIST;
6305 /* Back up original data item */
6306 dkey.mv_size = olddata.mv_size;
6307 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
6309 /* Make sub-page header for the dup items, with dummy body */
6310 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
6311 fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
6312 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
6313 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6314 fp->mp_flags |= P_LEAF2;
6315 fp->mp_pad = data->mv_size;
6316 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
6318 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
6319 (dkey.mv_size & 1) + (data->mv_size & 1);
6321 fp->mp_upper = xdata.mv_size - PAGEBASE;
6322 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
6323 } else if (leaf->mn_flags & F_SUBDATA) {
6324 /* Data is on sub-DB, just store it */
6325 flags |= F_DUPDATA|F_SUBDATA;
6328 /* Data is on sub-page */
6329 fp = olddata.mv_data;
6332 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6333 offset = EVEN(NODESIZE + sizeof(indx_t) +
6337 offset = fp->mp_pad;
6338 if (SIZELEFT(fp) < offset) {
6339 offset *= 4; /* space for 4 more */
6342 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
6344 fp->mp_flags |= P_DIRTY;
6345 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
6346 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
6350 xdata.mv_size = olddata.mv_size + offset;
6353 fp_flags = fp->mp_flags;
6354 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
6355 /* Too big for a sub-page, convert to sub-DB */
6356 fp_flags &= ~P_SUBP;
6358 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6359 fp_flags |= P_LEAF2;
6360 dummy.md_pad = fp->mp_pad;
6361 dummy.md_flags = MDB_DUPFIXED;
6362 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6363 dummy.md_flags |= MDB_INTEGERKEY;
6369 dummy.md_branch_pages = 0;
6370 dummy.md_leaf_pages = 1;
6371 dummy.md_overflow_pages = 0;
6372 dummy.md_entries = NUMKEYS(fp);
6373 xdata.mv_size = sizeof(MDB_db);
6374 xdata.mv_data = &dummy;
6375 if ((rc = mdb_page_alloc(mc, 1, &mp)))
6377 offset = env->me_psize - olddata.mv_size;
6378 flags |= F_DUPDATA|F_SUBDATA;
6379 dummy.md_root = mp->mp_pgno;
6382 mp->mp_flags = fp_flags | P_DIRTY;
6383 mp->mp_pad = fp->mp_pad;
6384 mp->mp_lower = fp->mp_lower;
6385 mp->mp_upper = fp->mp_upper + offset;
6386 if (fp_flags & P_LEAF2) {
6387 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
6389 memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
6390 olddata.mv_size - fp->mp_upper - PAGEBASE);
6391 for (i=0; i<NUMKEYS(fp); i++)
6392 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
6400 mdb_node_del(mc, 0);
6404 /* overflow page overwrites need special handling */
6405 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6408 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
6410 memcpy(&pg, olddata.mv_data, sizeof(pg));
6411 if ((rc2 = mdb_page_get(mc->mc_txn, pg, &omp, &level)) != 0)
6413 ovpages = omp->mp_pages;
6415 /* Is the ov page large enough? */
6416 if (ovpages >= dpages) {
6417 if (!(omp->mp_flags & P_DIRTY) &&
6418 (level || (env->me_flags & MDB_WRITEMAP)))
6420 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
6423 level = 0; /* dirty in this txn or clean */
6426 if (omp->mp_flags & P_DIRTY) {
6427 /* yes, overwrite it. Note in this case we don't
6428 * bother to try shrinking the page if the new data
6429 * is smaller than the overflow threshold.
6432 /* It is writable only in a parent txn */
6433 size_t sz = (size_t) env->me_psize * ovpages, off;
6434 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
6440 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
6441 mdb_cassert(mc, rc2 == 0);
6442 if (!(flags & MDB_RESERVE)) {
6443 /* Copy end of page, adjusting alignment so
6444 * compiler may copy words instead of bytes.
6446 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
6447 memcpy((size_t *)((char *)np + off),
6448 (size_t *)((char *)omp + off), sz - off);
6451 memcpy(np, omp, sz); /* Copy beginning of page */
6454 SETDSZ(leaf, data->mv_size);
6455 if (F_ISSET(flags, MDB_RESERVE))
6456 data->mv_data = METADATA(omp);
6458 memcpy(METADATA(omp), data->mv_data, data->mv_size);
6462 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
6464 } else if (data->mv_size == olddata.mv_size) {
6465 /* same size, just replace it. Note that we could
6466 * also reuse this node if the new data is smaller,
6467 * but instead we opt to shrink the node in that case.
6469 if (F_ISSET(flags, MDB_RESERVE))
6470 data->mv_data = olddata.mv_data;
6471 else if (!(mc->mc_flags & C_SUB))
6472 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
6474 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
6479 mdb_node_del(mc, 0);
6485 nflags = flags & NODE_ADD_FLAGS;
6486 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
6487 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
6488 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
6489 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
6491 nflags |= MDB_SPLIT_REPLACE;
6492 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
6494 /* There is room already in this leaf page. */
6495 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
6496 if (rc == 0 && insert_key) {
6497 /* Adjust other cursors pointing to mp */
6498 MDB_cursor *m2, *m3;
6499 MDB_dbi dbi = mc->mc_dbi;
6500 unsigned i = mc->mc_top;
6501 MDB_page *mp = mc->mc_pg[i];
6503 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6504 if (mc->mc_flags & C_SUB)
6505 m3 = &m2->mc_xcursor->mx_cursor;
6508 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
6509 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
6516 if (rc == MDB_SUCCESS) {
6517 /* Now store the actual data in the child DB. Note that we're
6518 * storing the user data in the keys field, so there are strict
6519 * size limits on dupdata. The actual data fields of the child
6520 * DB are all zero size.
6528 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6529 if (flags & MDB_CURRENT) {
6530 xflags = MDB_CURRENT|MDB_NOSPILL;
6532 mdb_xcursor_init1(mc, leaf);
6533 xflags = (flags & MDB_NODUPDATA) ?
6534 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
6536 /* converted, write the original data first */
6538 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
6542 /* Adjust other cursors pointing to mp */
6544 unsigned i = mc->mc_top;
6545 MDB_page *mp = mc->mc_pg[i];
6547 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6548 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6549 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6550 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
6551 mdb_xcursor_init1(m2, leaf);
6555 /* we've done our job */
6558 ecount = mc->mc_xcursor->mx_db.md_entries;
6559 if (flags & MDB_APPENDDUP)
6560 xflags |= MDB_APPEND;
6561 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
6562 if (flags & F_SUBDATA) {
6563 void *db = NODEDATA(leaf);
6564 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6566 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
6568 /* Increment count unless we just replaced an existing item. */
6570 mc->mc_db->md_entries++;
6572 /* Invalidate txn if we created an empty sub-DB */
6575 /* If we succeeded and the key didn't exist before,
6576 * make sure the cursor is marked valid.
6578 mc->mc_flags |= C_INITIALIZED;
6580 if (flags & MDB_MULTIPLE) {
6583 /* let caller know how many succeeded, if any */
6584 data[1].mv_size = mcount;
6585 if (mcount < dcount) {
6586 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
6587 insert_key = insert_data = 0;
6594 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
6597 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6602 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
6608 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
6609 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6611 if (!(mc->mc_flags & C_INITIALIZED))
6614 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6615 return MDB_NOTFOUND;
6617 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
6620 rc = mdb_cursor_touch(mc);
6624 mp = mc->mc_pg[mc->mc_top];
6627 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6629 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6630 if (flags & MDB_NODUPDATA) {
6631 /* mdb_cursor_del0() will subtract the final entry */
6632 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
6634 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
6635 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6637 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
6640 /* If sub-DB still has entries, we're done */
6641 if (mc->mc_xcursor->mx_db.md_entries) {
6642 if (leaf->mn_flags & F_SUBDATA) {
6643 /* update subDB info */
6644 void *db = NODEDATA(leaf);
6645 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6648 /* shrink fake page */
6649 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
6650 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6651 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6652 /* fix other sub-DB cursors pointed at this fake page */
6653 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6654 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6655 if (m2->mc_pg[mc->mc_top] == mp &&
6656 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
6657 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6660 mc->mc_db->md_entries--;
6661 mc->mc_flags |= C_DEL;
6664 /* otherwise fall thru and delete the sub-DB */
6667 if (leaf->mn_flags & F_SUBDATA) {
6668 /* add all the child DB's pages to the free list */
6669 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6675 /* add overflow pages to free list */
6676 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6680 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
6681 if ((rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL)) ||
6682 (rc = mdb_ovpage_free(mc, omp)))
6687 return mdb_cursor_del0(mc);
6690 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6694 /** Allocate and initialize new pages for a database.
6695 * @param[in] mc a cursor on the database being added to.
6696 * @param[in] flags flags defining what type of page is being allocated.
6697 * @param[in] num the number of pages to allocate. This is usually 1,
6698 * unless allocating overflow pages for a large record.
6699 * @param[out] mp Address of a page, or NULL on failure.
6700 * @return 0 on success, non-zero on failure.
6703 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
6708 if ((rc = mdb_page_alloc(mc, num, &np)))
6710 DPRINTF(("allocated new mpage %"Z"u, page size %u",
6711 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
6712 np->mp_flags = flags | P_DIRTY;
6713 np->mp_lower = (PAGEHDRSZ-PAGEBASE);
6714 np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
6717 mc->mc_db->md_branch_pages++;
6718 else if (IS_LEAF(np))
6719 mc->mc_db->md_leaf_pages++;
6720 else if (IS_OVERFLOW(np)) {
6721 mc->mc_db->md_overflow_pages += num;
6729 /** Calculate the size of a leaf node.
6730 * The size depends on the environment's page size; if a data item
6731 * is too large it will be put onto an overflow page and the node
6732 * size will only include the key and not the data. Sizes are always
6733 * rounded up to an even number of bytes, to guarantee 2-byte alignment
6734 * of the #MDB_node headers.
6735 * @param[in] env The environment handle.
6736 * @param[in] key The key for the node.
6737 * @param[in] data The data for the node.
6738 * @return The number of bytes needed to store the node.
6741 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
6745 sz = LEAFSIZE(key, data);
6746 if (sz > env->me_nodemax) {
6747 /* put on overflow page */
6748 sz -= data->mv_size - sizeof(pgno_t);
6751 return EVEN(sz + sizeof(indx_t));
6754 /** Calculate the size of a branch node.
6755 * The size should depend on the environment's page size but since
6756 * we currently don't support spilling large keys onto overflow
6757 * pages, it's simply the size of the #MDB_node header plus the
6758 * size of the key. Sizes are always rounded up to an even number
6759 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
6760 * @param[in] env The environment handle.
6761 * @param[in] key The key for the node.
6762 * @return The number of bytes needed to store the node.
6765 mdb_branch_size(MDB_env *env, MDB_val *key)
6770 if (sz > env->me_nodemax) {
6771 /* put on overflow page */
6772 /* not implemented */
6773 /* sz -= key->size - sizeof(pgno_t); */
6776 return sz + sizeof(indx_t);
6779 /** Add a node to the page pointed to by the cursor.
6780 * @param[in] mc The cursor for this operation.
6781 * @param[in] indx The index on the page where the new node should be added.
6782 * @param[in] key The key for the new node.
6783 * @param[in] data The data for the new node, if any.
6784 * @param[in] pgno The page number, if adding a branch node.
6785 * @param[in] flags Flags for the node.
6786 * @return 0 on success, non-zero on failure. Possible errors are:
6788 * <li>ENOMEM - failed to allocate overflow pages for the node.
6789 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
6790 * should never happen since all callers already calculate the
6791 * page's free space before calling this function.
6795 mdb_node_add(MDB_cursor *mc, indx_t indx,
6796 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
6799 size_t node_size = NODESIZE;
6803 MDB_page *mp = mc->mc_pg[mc->mc_top];
6804 MDB_page *ofp = NULL; /* overflow page */
6807 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
6809 DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
6810 IS_LEAF(mp) ? "leaf" : "branch",
6811 IS_SUBP(mp) ? "sub-" : "",
6812 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
6813 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
6816 /* Move higher keys up one slot. */
6817 int ksize = mc->mc_db->md_pad, dif;
6818 char *ptr = LEAF2KEY(mp, indx, ksize);
6819 dif = NUMKEYS(mp) - indx;
6821 memmove(ptr+ksize, ptr, dif*ksize);
6822 /* insert new key */
6823 memcpy(ptr, key->mv_data, ksize);
6825 /* Just using these for counting */
6826 mp->mp_lower += sizeof(indx_t);
6827 mp->mp_upper -= ksize - sizeof(indx_t);
6831 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
6833 node_size += key->mv_size;
6835 mdb_cassert(mc, data);
6836 if (F_ISSET(flags, F_BIGDATA)) {
6837 /* Data already on overflow page. */
6838 node_size += sizeof(pgno_t);
6839 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
6840 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
6842 /* Put data on overflow page. */
6843 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
6844 data->mv_size, node_size+data->mv_size));
6845 node_size = EVEN(node_size + sizeof(pgno_t));
6846 if ((ssize_t)node_size > room)
6848 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
6850 DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
6854 node_size += data->mv_size;
6857 node_size = EVEN(node_size);
6858 if ((ssize_t)node_size > room)
6862 /* Move higher pointers up one slot. */
6863 for (i = NUMKEYS(mp); i > indx; i--)
6864 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
6866 /* Adjust free space offsets. */
6867 ofs = mp->mp_upper - node_size;
6868 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
6869 mp->mp_ptrs[indx] = ofs;
6871 mp->mp_lower += sizeof(indx_t);
6873 /* Write the node data. */
6874 node = NODEPTR(mp, indx);
6875 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
6876 node->mn_flags = flags;
6878 SETDSZ(node,data->mv_size);
6883 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6886 mdb_cassert(mc, key);
6888 if (F_ISSET(flags, F_BIGDATA))
6889 memcpy(node->mn_data + key->mv_size, data->mv_data,
6891 else if (F_ISSET(flags, MDB_RESERVE))
6892 data->mv_data = node->mn_data + key->mv_size;
6894 memcpy(node->mn_data + key->mv_size, data->mv_data,
6897 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
6899 if (F_ISSET(flags, MDB_RESERVE))
6900 data->mv_data = METADATA(ofp);
6902 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
6909 DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
6910 mdb_dbg_pgno(mp), NUMKEYS(mp)));
6911 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
6912 DPRINTF(("node size = %"Z"u", node_size));
6913 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6914 return MDB_PAGE_FULL;
6917 /** Delete the specified node from a page.
6918 * @param[in] mc Cursor pointing to the node to delete.
6919 * @param[in] ksize The size of a node. Only used if the page is
6920 * part of a #MDB_DUPFIXED database.
6923 mdb_node_del(MDB_cursor *mc, int ksize)
6925 MDB_page *mp = mc->mc_pg[mc->mc_top];
6926 indx_t indx = mc->mc_ki[mc->mc_top];
6928 indx_t i, j, numkeys, ptr;
6932 DPRINTF(("delete node %u on %s page %"Z"u", indx,
6933 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
6934 numkeys = NUMKEYS(mp);
6935 mdb_cassert(mc, indx < numkeys);
6938 int x = numkeys - 1 - indx;
6939 base = LEAF2KEY(mp, indx, ksize);
6941 memmove(base, base + ksize, x * ksize);
6942 mp->mp_lower -= sizeof(indx_t);
6943 mp->mp_upper += ksize - sizeof(indx_t);
6947 node = NODEPTR(mp, indx);
6948 sz = NODESIZE + node->mn_ksize;
6950 if (F_ISSET(node->mn_flags, F_BIGDATA))
6951 sz += sizeof(pgno_t);
6953 sz += NODEDSZ(node);
6957 ptr = mp->mp_ptrs[indx];
6958 for (i = j = 0; i < numkeys; i++) {
6960 mp->mp_ptrs[j] = mp->mp_ptrs[i];
6961 if (mp->mp_ptrs[i] < ptr)
6962 mp->mp_ptrs[j] += sz;
6967 base = (char *)mp + mp->mp_upper + PAGEBASE;
6968 memmove(base + sz, base, ptr - mp->mp_upper);
6970 mp->mp_lower -= sizeof(indx_t);
6974 /** Compact the main page after deleting a node on a subpage.
6975 * @param[in] mp The main page to operate on.
6976 * @param[in] indx The index of the subpage on the main page.
6979 mdb_node_shrink(MDB_page *mp, indx_t indx)
6985 indx_t i, numkeys, ptr;
6987 node = NODEPTR(mp, indx);
6988 sp = (MDB_page *)NODEDATA(node);
6989 delta = SIZELEFT(sp);
6990 xp = (MDB_page *)((char *)sp + delta);
6992 /* shift subpage upward */
6994 nsize = NUMKEYS(sp) * sp->mp_pad;
6996 return; /* do not make the node uneven-sized */
6997 memmove(METADATA(xp), METADATA(sp), nsize);
7000 numkeys = NUMKEYS(sp);
7001 for (i=numkeys-1; i>=0; i--)
7002 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
7004 xp->mp_upper = sp->mp_lower;
7005 xp->mp_lower = sp->mp_lower;
7006 xp->mp_flags = sp->mp_flags;
7007 xp->mp_pad = sp->mp_pad;
7008 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
7010 nsize = NODEDSZ(node) - delta;
7011 SETDSZ(node, nsize);
7013 /* shift lower nodes upward */
7014 ptr = mp->mp_ptrs[indx];
7015 numkeys = NUMKEYS(mp);
7016 for (i = 0; i < numkeys; i++) {
7017 if (mp->mp_ptrs[i] <= ptr)
7018 mp->mp_ptrs[i] += delta;
7021 base = (char *)mp + mp->mp_upper + PAGEBASE;
7022 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
7023 mp->mp_upper += delta;
7026 /** Initial setup of a sorted-dups cursor.
7027 * Sorted duplicates are implemented as a sub-database for the given key.
7028 * The duplicate data items are actually keys of the sub-database.
7029 * Operations on the duplicate data items are performed using a sub-cursor
7030 * initialized when the sub-database is first accessed. This function does
7031 * the preliminary setup of the sub-cursor, filling in the fields that
7032 * depend only on the parent DB.
7033 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
7036 mdb_xcursor_init0(MDB_cursor *mc)
7038 MDB_xcursor *mx = mc->mc_xcursor;
7040 mx->mx_cursor.mc_xcursor = NULL;
7041 mx->mx_cursor.mc_txn = mc->mc_txn;
7042 mx->mx_cursor.mc_db = &mx->mx_db;
7043 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
7044 mx->mx_cursor.mc_dbi = mc->mc_dbi;
7045 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
7046 mx->mx_cursor.mc_snum = 0;
7047 mx->mx_cursor.mc_top = 0;
7048 mx->mx_cursor.mc_flags = C_SUB;
7049 mx->mx_dbx.md_name.mv_size = 0;
7050 mx->mx_dbx.md_name.mv_data = NULL;
7051 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
7052 mx->mx_dbx.md_dcmp = NULL;
7053 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
7056 /** Final setup of a sorted-dups cursor.
7057 * Sets up the fields that depend on the data from the main cursor.
7058 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
7059 * @param[in] node The data containing the #MDB_db record for the
7060 * sorted-dup database.
7063 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
7065 MDB_xcursor *mx = mc->mc_xcursor;
7067 if (node->mn_flags & F_SUBDATA) {
7068 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
7069 mx->mx_cursor.mc_pg[0] = 0;
7070 mx->mx_cursor.mc_snum = 0;
7071 mx->mx_cursor.mc_top = 0;
7072 mx->mx_cursor.mc_flags = C_SUB;
7074 MDB_page *fp = NODEDATA(node);
7075 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
7076 mx->mx_db.md_flags = 0;
7077 mx->mx_db.md_depth = 1;
7078 mx->mx_db.md_branch_pages = 0;
7079 mx->mx_db.md_leaf_pages = 1;
7080 mx->mx_db.md_overflow_pages = 0;
7081 mx->mx_db.md_entries = NUMKEYS(fp);
7082 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
7083 mx->mx_cursor.mc_snum = 1;
7084 mx->mx_cursor.mc_top = 0;
7085 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
7086 mx->mx_cursor.mc_pg[0] = fp;
7087 mx->mx_cursor.mc_ki[0] = 0;
7088 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7089 mx->mx_db.md_flags = MDB_DUPFIXED;
7090 mx->mx_db.md_pad = fp->mp_pad;
7091 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
7092 mx->mx_db.md_flags |= MDB_INTEGERKEY;
7095 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
7096 mx->mx_db.md_root));
7097 mx->mx_dbflag = DB_VALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
7098 #if UINT_MAX < SIZE_MAX
7099 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
7100 mx->mx_dbx.md_cmp = mdb_cmp_clong;
7104 /** Initialize a cursor for a given transaction and database. */
7106 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
7109 mc->mc_backup = NULL;
7112 mc->mc_db = &txn->mt_dbs[dbi];
7113 mc->mc_dbx = &txn->mt_dbxs[dbi];
7114 mc->mc_dbflag = &txn->mt_dbflags[dbi];
7120 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
7121 mdb_tassert(txn, mx != NULL);
7122 mc->mc_xcursor = mx;
7123 mdb_xcursor_init0(mc);
7125 mc->mc_xcursor = NULL;
7127 if (*mc->mc_dbflag & DB_STALE) {
7128 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
7133 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
7136 size_t size = sizeof(MDB_cursor);
7138 if (!ret || !TXN_DBI_EXIST(txn, dbi))
7141 if (txn->mt_flags & MDB_TXN_ERROR)
7144 /* Allow read access to the freelist */
7145 if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
7148 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
7149 size += sizeof(MDB_xcursor);
7151 if ((mc = malloc(size)) != NULL) {
7152 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
7153 if (txn->mt_cursors) {
7154 mc->mc_next = txn->mt_cursors[dbi];
7155 txn->mt_cursors[dbi] = mc;
7156 mc->mc_flags |= C_UNTRACK;
7168 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
7170 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi))
7173 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
7176 if (txn->mt_flags & MDB_TXN_ERROR)
7179 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
7183 /* Return the count of duplicate data items for the current key */
7185 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
7189 if (mc == NULL || countp == NULL)
7192 if (mc->mc_xcursor == NULL)
7193 return MDB_INCOMPATIBLE;
7195 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
7198 if (!(mc->mc_flags & C_INITIALIZED))
7201 if (!mc->mc_snum || (mc->mc_flags & C_EOF))
7202 return MDB_NOTFOUND;
7204 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7205 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7208 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
7211 *countp = mc->mc_xcursor->mx_db.md_entries;
7217 mdb_cursor_close(MDB_cursor *mc)
7219 if (mc && !mc->mc_backup) {
7220 /* remove from txn, if tracked */
7221 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
7222 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
7223 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
7225 *prev = mc->mc_next;
7232 mdb_cursor_txn(MDB_cursor *mc)
7234 if (!mc) return NULL;
7239 mdb_cursor_dbi(MDB_cursor *mc)
7244 /** Replace the key for a branch node with a new key.
7245 * @param[in] mc Cursor pointing to the node to operate on.
7246 * @param[in] key The new key to use.
7247 * @return 0 on success, non-zero on failure.
7250 mdb_update_key(MDB_cursor *mc, MDB_val *key)
7256 int delta, ksize, oksize;
7257 indx_t ptr, i, numkeys, indx;
7260 indx = mc->mc_ki[mc->mc_top];
7261 mp = mc->mc_pg[mc->mc_top];
7262 node = NODEPTR(mp, indx);
7263 ptr = mp->mp_ptrs[indx];
7267 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
7268 k2.mv_data = NODEKEY(node);
7269 k2.mv_size = node->mn_ksize;
7270 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
7272 mdb_dkey(&k2, kbuf2),
7278 /* Sizes must be 2-byte aligned. */
7279 ksize = EVEN(key->mv_size);
7280 oksize = EVEN(node->mn_ksize);
7281 delta = ksize - oksize;
7283 /* Shift node contents if EVEN(key length) changed. */
7285 if (delta > 0 && SIZELEFT(mp) < delta) {
7287 /* not enough space left, do a delete and split */
7288 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
7289 pgno = NODEPGNO(node);
7290 mdb_node_del(mc, 0);
7291 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
7294 numkeys = NUMKEYS(mp);
7295 for (i = 0; i < numkeys; i++) {
7296 if (mp->mp_ptrs[i] <= ptr)
7297 mp->mp_ptrs[i] -= delta;
7300 base = (char *)mp + mp->mp_upper + PAGEBASE;
7301 len = ptr - mp->mp_upper + NODESIZE;
7302 memmove(base - delta, base, len);
7303 mp->mp_upper -= delta;
7305 node = NODEPTR(mp, indx);
7308 /* But even if no shift was needed, update ksize */
7309 if (node->mn_ksize != key->mv_size)
7310 node->mn_ksize = key->mv_size;
7313 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7319 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
7321 /** Move a node from csrc to cdst.
7324 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
7331 unsigned short flags;
7335 /* Mark src and dst as dirty. */
7336 if ((rc = mdb_page_touch(csrc)) ||
7337 (rc = mdb_page_touch(cdst)))
7340 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7341 key.mv_size = csrc->mc_db->md_pad;
7342 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
7344 data.mv_data = NULL;
7348 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
7349 mdb_cassert(csrc, !((size_t)srcnode & 1));
7350 srcpg = NODEPGNO(srcnode);
7351 flags = srcnode->mn_flags;
7352 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7353 unsigned int snum = csrc->mc_snum;
7355 /* must find the lowest key below src */
7356 rc = mdb_page_search_lowest(csrc);
7359 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7360 key.mv_size = csrc->mc_db->md_pad;
7361 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7363 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7364 key.mv_size = NODEKSZ(s2);
7365 key.mv_data = NODEKEY(s2);
7367 csrc->mc_snum = snum--;
7368 csrc->mc_top = snum;
7370 key.mv_size = NODEKSZ(srcnode);
7371 key.mv_data = NODEKEY(srcnode);
7373 data.mv_size = NODEDSZ(srcnode);
7374 data.mv_data = NODEDATA(srcnode);
7376 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
7377 unsigned int snum = cdst->mc_snum;
7380 /* must find the lowest key below dst */
7381 mdb_cursor_copy(cdst, &mn);
7382 rc = mdb_page_search_lowest(&mn);
7385 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7386 bkey.mv_size = mn.mc_db->md_pad;
7387 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
7389 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7390 bkey.mv_size = NODEKSZ(s2);
7391 bkey.mv_data = NODEKEY(s2);
7393 mn.mc_snum = snum--;
7396 rc = mdb_update_key(&mn, &bkey);
7401 DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
7402 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
7403 csrc->mc_ki[csrc->mc_top],
7405 csrc->mc_pg[csrc->mc_top]->mp_pgno,
7406 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
7408 /* Add the node to the destination page.
7410 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
7411 if (rc != MDB_SUCCESS)
7414 /* Delete the node from the source page.
7416 mdb_node_del(csrc, key.mv_size);
7419 /* Adjust other cursors pointing to mp */
7420 MDB_cursor *m2, *m3;
7421 MDB_dbi dbi = csrc->mc_dbi;
7422 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
7424 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7425 if (csrc->mc_flags & C_SUB)
7426 m3 = &m2->mc_xcursor->mx_cursor;
7429 if (m3 == csrc) continue;
7430 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
7431 csrc->mc_ki[csrc->mc_top]) {
7432 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
7433 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7438 /* Update the parent separators.
7440 if (csrc->mc_ki[csrc->mc_top] == 0) {
7441 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
7442 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7443 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7445 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7446 key.mv_size = NODEKSZ(srcnode);
7447 key.mv_data = NODEKEY(srcnode);
7449 DPRINTF(("update separator for source page %"Z"u to [%s]",
7450 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
7451 mdb_cursor_copy(csrc, &mn);
7454 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7457 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7459 indx_t ix = csrc->mc_ki[csrc->mc_top];
7460 nullkey.mv_size = 0;
7461 csrc->mc_ki[csrc->mc_top] = 0;
7462 rc = mdb_update_key(csrc, &nullkey);
7463 csrc->mc_ki[csrc->mc_top] = ix;
7464 mdb_cassert(csrc, rc == MDB_SUCCESS);
7468 if (cdst->mc_ki[cdst->mc_top] == 0) {
7469 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
7470 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7471 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
7473 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
7474 key.mv_size = NODEKSZ(srcnode);
7475 key.mv_data = NODEKEY(srcnode);
7477 DPRINTF(("update separator for destination page %"Z"u to [%s]",
7478 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
7479 mdb_cursor_copy(cdst, &mn);
7482 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7485 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
7487 indx_t ix = cdst->mc_ki[cdst->mc_top];
7488 nullkey.mv_size = 0;
7489 cdst->mc_ki[cdst->mc_top] = 0;
7490 rc = mdb_update_key(cdst, &nullkey);
7491 cdst->mc_ki[cdst->mc_top] = ix;
7492 mdb_cassert(cdst, rc == MDB_SUCCESS);
7499 /** Merge one page into another.
7500 * The nodes from the page pointed to by \b csrc will
7501 * be copied to the page pointed to by \b cdst and then
7502 * the \b csrc page will be freed.
7503 * @param[in] csrc Cursor pointing to the source page.
7504 * @param[in] cdst Cursor pointing to the destination page.
7505 * @return 0 on success, non-zero on failure.
7508 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
7510 MDB_page *psrc, *pdst;
7517 psrc = csrc->mc_pg[csrc->mc_top];
7518 pdst = cdst->mc_pg[cdst->mc_top];
7520 DPRINTF(("merging page %"Z"u into %"Z"u", psrc->mp_pgno, pdst->mp_pgno));
7522 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
7523 mdb_cassert(csrc, cdst->mc_snum > 1);
7525 /* Mark dst as dirty. */
7526 if ((rc = mdb_page_touch(cdst)))
7529 /* Move all nodes from src to dst.
7531 j = nkeys = NUMKEYS(pdst);
7532 if (IS_LEAF2(psrc)) {
7533 key.mv_size = csrc->mc_db->md_pad;
7534 key.mv_data = METADATA(psrc);
7535 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7536 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
7537 if (rc != MDB_SUCCESS)
7539 key.mv_data = (char *)key.mv_data + key.mv_size;
7542 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7543 srcnode = NODEPTR(psrc, i);
7544 if (i == 0 && IS_BRANCH(psrc)) {
7547 mdb_cursor_copy(csrc, &mn);
7548 /* must find the lowest key below src */
7549 rc = mdb_page_search_lowest(&mn);
7552 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7553 key.mv_size = mn.mc_db->md_pad;
7554 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
7556 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7557 key.mv_size = NODEKSZ(s2);
7558 key.mv_data = NODEKEY(s2);
7561 key.mv_size = srcnode->mn_ksize;
7562 key.mv_data = NODEKEY(srcnode);
7565 data.mv_size = NODEDSZ(srcnode);
7566 data.mv_data = NODEDATA(srcnode);
7567 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
7568 if (rc != MDB_SUCCESS)
7573 DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
7574 pdst->mp_pgno, NUMKEYS(pdst),
7575 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
7577 /* Unlink the src page from parent and add to free list.
7580 mdb_node_del(csrc, 0);
7581 if (csrc->mc_ki[csrc->mc_top] == 0) {
7583 rc = mdb_update_key(csrc, &key);
7591 psrc = csrc->mc_pg[csrc->mc_top];
7592 /* If not operating on FreeDB, allow this page to be reused
7593 * in this txn. Otherwise just add to free list.
7595 rc = mdb_page_loose(csrc, psrc);
7599 csrc->mc_db->md_leaf_pages--;
7601 csrc->mc_db->md_branch_pages--;
7603 /* Adjust other cursors pointing to mp */
7604 MDB_cursor *m2, *m3;
7605 MDB_dbi dbi = csrc->mc_dbi;
7607 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7608 if (csrc->mc_flags & C_SUB)
7609 m3 = &m2->mc_xcursor->mx_cursor;
7612 if (m3 == csrc) continue;
7613 if (m3->mc_snum < csrc->mc_snum) continue;
7614 if (m3->mc_pg[csrc->mc_top] == psrc) {
7615 m3->mc_pg[csrc->mc_top] = pdst;
7616 m3->mc_ki[csrc->mc_top] += nkeys;
7621 unsigned int snum = cdst->mc_snum;
7622 uint16_t depth = cdst->mc_db->md_depth;
7623 mdb_cursor_pop(cdst);
7624 rc = mdb_rebalance(cdst);
7625 /* Did the tree shrink? */
7626 if (depth > cdst->mc_db->md_depth)
7628 cdst->mc_snum = snum;
7629 cdst->mc_top = snum-1;
7634 /** Copy the contents of a cursor.
7635 * @param[in] csrc The cursor to copy from.
7636 * @param[out] cdst The cursor to copy to.
7639 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
7643 cdst->mc_txn = csrc->mc_txn;
7644 cdst->mc_dbi = csrc->mc_dbi;
7645 cdst->mc_db = csrc->mc_db;
7646 cdst->mc_dbx = csrc->mc_dbx;
7647 cdst->mc_snum = csrc->mc_snum;
7648 cdst->mc_top = csrc->mc_top;
7649 cdst->mc_flags = csrc->mc_flags;
7651 for (i=0; i<csrc->mc_snum; i++) {
7652 cdst->mc_pg[i] = csrc->mc_pg[i];
7653 cdst->mc_ki[i] = csrc->mc_ki[i];
7657 /** Rebalance the tree after a delete operation.
7658 * @param[in] mc Cursor pointing to the page where rebalancing
7660 * @return 0 on success, non-zero on failure.
7663 mdb_rebalance(MDB_cursor *mc)
7667 unsigned int ptop, minkeys;
7671 minkeys = 1 + (IS_BRANCH(mc->mc_pg[mc->mc_top]));
7672 DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
7673 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
7674 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
7675 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
7677 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD &&
7678 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
7679 DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
7680 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
7684 if (mc->mc_snum < 2) {
7685 MDB_page *mp = mc->mc_pg[0];
7687 DPUTS("Can't rebalance a subpage, ignoring");
7690 if (NUMKEYS(mp) == 0) {
7691 DPUTS("tree is completely empty");
7692 mc->mc_db->md_root = P_INVALID;
7693 mc->mc_db->md_depth = 0;
7694 mc->mc_db->md_leaf_pages = 0;
7695 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7698 /* Adjust cursors pointing to mp */
7701 mc->mc_flags &= ~C_INITIALIZED;
7703 MDB_cursor *m2, *m3;
7704 MDB_dbi dbi = mc->mc_dbi;
7706 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7707 if (mc->mc_flags & C_SUB)
7708 m3 = &m2->mc_xcursor->mx_cursor;
7711 if (m3->mc_snum < mc->mc_snum) continue;
7712 if (m3->mc_pg[0] == mp) {
7715 m3->mc_flags &= ~C_INITIALIZED;
7719 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
7721 DPUTS("collapsing root page!");
7722 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7725 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
7726 rc = mdb_page_get(mc->mc_txn,mc->mc_db->md_root,&mc->mc_pg[0],NULL);
7729 mc->mc_db->md_depth--;
7730 mc->mc_db->md_branch_pages--;
7731 mc->mc_ki[0] = mc->mc_ki[1];
7732 for (i = 1; i<mc->mc_db->md_depth; i++) {
7733 mc->mc_pg[i] = mc->mc_pg[i+1];
7734 mc->mc_ki[i] = mc->mc_ki[i+1];
7737 /* Adjust other cursors pointing to mp */
7738 MDB_cursor *m2, *m3;
7739 MDB_dbi dbi = mc->mc_dbi;
7741 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7742 if (mc->mc_flags & C_SUB)
7743 m3 = &m2->mc_xcursor->mx_cursor;
7746 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
7747 if (m3->mc_pg[0] == mp) {
7748 for (i=0; i<m3->mc_snum; i++) {
7749 m3->mc_pg[i] = m3->mc_pg[i+1];
7750 m3->mc_ki[i] = m3->mc_ki[i+1];
7758 DPUTS("root page doesn't need rebalancing");
7762 /* The parent (branch page) must have at least 2 pointers,
7763 * otherwise the tree is invalid.
7765 ptop = mc->mc_top-1;
7766 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
7768 /* Leaf page fill factor is below the threshold.
7769 * Try to move keys from left or right neighbor, or
7770 * merge with a neighbor page.
7775 mdb_cursor_copy(mc, &mn);
7776 mn.mc_xcursor = NULL;
7778 oldki = mc->mc_ki[mc->mc_top];
7779 if (mc->mc_ki[ptop] == 0) {
7780 /* We're the leftmost leaf in our parent.
7782 DPUTS("reading right neighbor");
7784 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7785 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7788 mn.mc_ki[mn.mc_top] = 0;
7789 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
7791 /* There is at least one neighbor to the left.
7793 DPUTS("reading left neighbor");
7795 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7796 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7799 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
7800 mc->mc_ki[mc->mc_top] = 0;
7803 DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
7804 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
7805 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
7807 /* If the neighbor page is above threshold and has enough keys,
7808 * move one key from it. Otherwise we should try to merge them.
7809 * (A branch page must never have less than 2 keys.)
7811 minkeys = 1 + (IS_BRANCH(mn.mc_pg[mn.mc_top]));
7812 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
7813 rc = mdb_node_move(&mn, mc);
7814 if (mc->mc_ki[ptop]) {
7818 if (mc->mc_ki[ptop] == 0) {
7819 rc = mdb_page_merge(&mn, mc);
7822 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
7823 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
7824 /* We want mdb_rebalance to find mn when doing fixups */
7825 if (mc->mc_flags & C_SUB) {
7826 dummy.mc_next = mc->mc_txn->mt_cursors[mc->mc_dbi];
7827 mc->mc_txn->mt_cursors[mc->mc_dbi] = &dummy;
7828 dummy.mc_xcursor = (MDB_xcursor *)&mn;
7830 mn.mc_next = mc->mc_txn->mt_cursors[mc->mc_dbi];
7831 mc->mc_txn->mt_cursors[mc->mc_dbi] = &mn;
7833 rc = mdb_page_merge(mc, &mn);
7834 if (mc->mc_flags & C_SUB)
7835 mc->mc_txn->mt_cursors[mc->mc_dbi] = dummy.mc_next;
7837 mc->mc_txn->mt_cursors[mc->mc_dbi] = mn.mc_next;
7838 mdb_cursor_copy(&mn, mc);
7840 mc->mc_flags &= ~C_EOF;
7842 mc->mc_ki[mc->mc_top] = oldki;
7846 /** Complete a delete operation started by #mdb_cursor_del(). */
7848 mdb_cursor_del0(MDB_cursor *mc)
7855 ki = mc->mc_ki[mc->mc_top];
7856 mdb_node_del(mc, mc->mc_db->md_pad);
7857 mc->mc_db->md_entries--;
7858 rc = mdb_rebalance(mc);
7860 if (rc == MDB_SUCCESS) {
7861 MDB_cursor *m2, *m3;
7862 MDB_dbi dbi = mc->mc_dbi;
7864 /* DB is totally empty now, just bail out.
7865 * Other cursors adjustments were already done
7866 * by mdb_rebalance and aren't needed here.
7871 mp = mc->mc_pg[mc->mc_top];
7872 nkeys = NUMKEYS(mp);
7874 /* if mc points past last node in page, find next sibling */
7875 if (mc->mc_ki[mc->mc_top] >= nkeys) {
7876 rc = mdb_cursor_sibling(mc, 1);
7877 if (rc == MDB_NOTFOUND) {
7878 mc->mc_flags |= C_EOF;
7883 /* Adjust other cursors pointing to mp */
7884 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
7885 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
7886 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
7888 if (m3 == mc || m3->mc_snum < mc->mc_snum)
7890 if (m3->mc_pg[mc->mc_top] == mp) {
7891 if (m3->mc_ki[mc->mc_top] >= ki) {
7892 m3->mc_flags |= C_DEL;
7893 if (m3->mc_ki[mc->mc_top] > ki)
7894 m3->mc_ki[mc->mc_top]--;
7895 else if (mc->mc_db->md_flags & MDB_DUPSORT)
7896 m3->mc_xcursor->mx_cursor.mc_flags |= C_EOF;
7898 if (m3->mc_ki[mc->mc_top] >= nkeys) {
7899 rc = mdb_cursor_sibling(m3, 1);
7900 if (rc == MDB_NOTFOUND) {
7901 m3->mc_flags |= C_EOF;
7907 mc->mc_flags |= C_DEL;
7911 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7916 mdb_del(MDB_txn *txn, MDB_dbi dbi,
7917 MDB_val *key, MDB_val *data)
7919 if (!key || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
7922 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
7923 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7925 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
7926 /* must ignore any data */
7930 return mdb_del0(txn, dbi, key, data, 0);
7934 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
7935 MDB_val *key, MDB_val *data, unsigned flags)
7940 MDB_val rdata, *xdata;
7944 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
7946 mdb_cursor_init(&mc, txn, dbi, &mx);
7955 flags |= MDB_NODUPDATA;
7957 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
7959 /* let mdb_page_split know about this cursor if needed:
7960 * delete will trigger a rebalance; if it needs to move
7961 * a node from one page to another, it will have to
7962 * update the parent's separator key(s). If the new sepkey
7963 * is larger than the current one, the parent page may
7964 * run out of space, triggering a split. We need this
7965 * cursor to be consistent until the end of the rebalance.
7967 mc.mc_flags |= C_UNTRACK;
7968 mc.mc_next = txn->mt_cursors[dbi];
7969 txn->mt_cursors[dbi] = &mc;
7970 rc = mdb_cursor_del(&mc, flags);
7971 txn->mt_cursors[dbi] = mc.mc_next;
7976 /** Split a page and insert a new node.
7977 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
7978 * The cursor will be updated to point to the actual page and index where
7979 * the node got inserted after the split.
7980 * @param[in] newkey The key for the newly inserted node.
7981 * @param[in] newdata The data for the newly inserted node.
7982 * @param[in] newpgno The page number, if the new node is a branch node.
7983 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
7984 * @return 0 on success, non-zero on failure.
7987 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
7988 unsigned int nflags)
7991 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
7994 int i, j, split_indx, nkeys, pmax;
7995 MDB_env *env = mc->mc_txn->mt_env;
7997 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
7998 MDB_page *copy = NULL;
7999 MDB_page *mp, *rp, *pp;
8004 mp = mc->mc_pg[mc->mc_top];
8005 newindx = mc->mc_ki[mc->mc_top];
8006 nkeys = NUMKEYS(mp);
8008 DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i/%i",
8009 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
8010 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
8012 /* Create a right sibling. */
8013 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
8015 DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
8017 if (mc->mc_snum < 2) {
8018 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
8020 /* shift current top to make room for new parent */
8021 mc->mc_pg[1] = mc->mc_pg[0];
8022 mc->mc_ki[1] = mc->mc_ki[0];
8025 mc->mc_db->md_root = pp->mp_pgno;
8026 DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
8027 mc->mc_db->md_depth++;
8030 /* Add left (implicit) pointer. */
8031 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
8032 /* undo the pre-push */
8033 mc->mc_pg[0] = mc->mc_pg[1];
8034 mc->mc_ki[0] = mc->mc_ki[1];
8035 mc->mc_db->md_root = mp->mp_pgno;
8036 mc->mc_db->md_depth--;
8043 ptop = mc->mc_top-1;
8044 DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
8047 mc->mc_flags |= C_SPLITTING;
8048 mdb_cursor_copy(mc, &mn);
8049 mn.mc_pg[mn.mc_top] = rp;
8050 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
8052 if (nflags & MDB_APPEND) {
8053 mn.mc_ki[mn.mc_top] = 0;
8055 split_indx = newindx;
8059 split_indx = (nkeys+1) / 2;
8064 unsigned int lsize, rsize, ksize;
8065 /* Move half of the keys to the right sibling */
8066 x = mc->mc_ki[mc->mc_top] - split_indx;
8067 ksize = mc->mc_db->md_pad;
8068 split = LEAF2KEY(mp, split_indx, ksize);
8069 rsize = (nkeys - split_indx) * ksize;
8070 lsize = (nkeys - split_indx) * sizeof(indx_t);
8071 mp->mp_lower -= lsize;
8072 rp->mp_lower += lsize;
8073 mp->mp_upper += rsize - lsize;
8074 rp->mp_upper -= rsize - lsize;
8075 sepkey.mv_size = ksize;
8076 if (newindx == split_indx) {
8077 sepkey.mv_data = newkey->mv_data;
8079 sepkey.mv_data = split;
8082 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
8083 memcpy(rp->mp_ptrs, split, rsize);
8084 sepkey.mv_data = rp->mp_ptrs;
8085 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
8086 memcpy(ins, newkey->mv_data, ksize);
8087 mp->mp_lower += sizeof(indx_t);
8088 mp->mp_upper -= ksize - sizeof(indx_t);
8091 memcpy(rp->mp_ptrs, split, x * ksize);
8092 ins = LEAF2KEY(rp, x, ksize);
8093 memcpy(ins, newkey->mv_data, ksize);
8094 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
8095 rp->mp_lower += sizeof(indx_t);
8096 rp->mp_upper -= ksize - sizeof(indx_t);
8097 mc->mc_ki[mc->mc_top] = x;
8098 mc->mc_pg[mc->mc_top] = rp;
8101 int psize, nsize, k;
8102 /* Maximum free space in an empty page */
8103 pmax = env->me_psize - PAGEHDRSZ;
8105 nsize = mdb_leaf_size(env, newkey, newdata);
8107 nsize = mdb_branch_size(env, newkey);
8108 nsize = EVEN(nsize);
8110 /* grab a page to hold a temporary copy */
8111 copy = mdb_page_malloc(mc->mc_txn, 1);
8116 copy->mp_pgno = mp->mp_pgno;
8117 copy->mp_flags = mp->mp_flags;
8118 copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
8119 copy->mp_upper = env->me_psize - PAGEBASE;
8121 /* prepare to insert */
8122 for (i=0, j=0; i<nkeys; i++) {
8124 copy->mp_ptrs[j++] = 0;
8126 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
8129 /* When items are relatively large the split point needs
8130 * to be checked, because being off-by-one will make the
8131 * difference between success or failure in mdb_node_add.
8133 * It's also relevant if a page happens to be laid out
8134 * such that one half of its nodes are all "small" and
8135 * the other half of its nodes are "large." If the new
8136 * item is also "large" and falls on the half with
8137 * "large" nodes, it also may not fit.
8139 * As a final tweak, if the new item goes on the last
8140 * spot on the page (and thus, onto the new page), bias
8141 * the split so the new page is emptier than the old page.
8142 * This yields better packing during sequential inserts.
8144 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
8145 /* Find split point */
8147 if (newindx <= split_indx || newindx >= nkeys) {
8149 k = newindx >= nkeys ? nkeys : split_indx+2;
8154 for (; i!=k; i+=j) {
8159 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8160 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
8162 if (F_ISSET(node->mn_flags, F_BIGDATA))
8163 psize += sizeof(pgno_t);
8165 psize += NODEDSZ(node);
8167 psize = EVEN(psize);
8169 if (psize > pmax || i == k-j) {
8170 split_indx = i + (j<0);
8175 if (split_indx == newindx) {
8176 sepkey.mv_size = newkey->mv_size;
8177 sepkey.mv_data = newkey->mv_data;
8179 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
8180 sepkey.mv_size = node->mn_ksize;
8181 sepkey.mv_data = NODEKEY(node);
8186 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
8188 /* Copy separator key to the parent.
8190 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
8194 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
8199 if (mn.mc_snum == mc->mc_snum) {
8200 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
8201 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
8202 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
8203 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
8208 /* Right page might now have changed parent.
8209 * Check if left page also changed parent.
8211 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8212 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8213 for (i=0; i<ptop; i++) {
8214 mc->mc_pg[i] = mn.mc_pg[i];
8215 mc->mc_ki[i] = mn.mc_ki[i];
8217 mc->mc_pg[ptop] = mn.mc_pg[ptop];
8218 if (mn.mc_ki[ptop]) {
8219 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
8221 /* find right page's left sibling */
8222 mc->mc_ki[ptop] = mn.mc_ki[ptop];
8223 mdb_cursor_sibling(mc, 0);
8228 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
8231 mc->mc_flags ^= C_SPLITTING;
8232 if (rc != MDB_SUCCESS) {
8235 if (nflags & MDB_APPEND) {
8236 mc->mc_pg[mc->mc_top] = rp;
8237 mc->mc_ki[mc->mc_top] = 0;
8238 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
8241 for (i=0; i<mc->mc_top; i++)
8242 mc->mc_ki[i] = mn.mc_ki[i];
8243 } else if (!IS_LEAF2(mp)) {
8245 mc->mc_pg[mc->mc_top] = rp;
8250 rkey.mv_data = newkey->mv_data;
8251 rkey.mv_size = newkey->mv_size;
8257 /* Update index for the new key. */
8258 mc->mc_ki[mc->mc_top] = j;
8260 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8261 rkey.mv_data = NODEKEY(node);
8262 rkey.mv_size = node->mn_ksize;
8264 xdata.mv_data = NODEDATA(node);
8265 xdata.mv_size = NODEDSZ(node);
8268 pgno = NODEPGNO(node);
8269 flags = node->mn_flags;
8272 if (!IS_LEAF(mp) && j == 0) {
8273 /* First branch index doesn't need key data. */
8277 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
8283 mc->mc_pg[mc->mc_top] = copy;
8288 } while (i != split_indx);
8290 nkeys = NUMKEYS(copy);
8291 for (i=0; i<nkeys; i++)
8292 mp->mp_ptrs[i] = copy->mp_ptrs[i];
8293 mp->mp_lower = copy->mp_lower;
8294 mp->mp_upper = copy->mp_upper;
8295 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
8296 env->me_psize - copy->mp_upper - PAGEBASE);
8298 /* reset back to original page */
8299 if (newindx < split_indx) {
8300 mc->mc_pg[mc->mc_top] = mp;
8301 if (nflags & MDB_RESERVE) {
8302 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
8303 if (!(node->mn_flags & F_BIGDATA))
8304 newdata->mv_data = NODEDATA(node);
8307 mc->mc_pg[mc->mc_top] = rp;
8309 /* Make sure mc_ki is still valid.
8311 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8312 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8313 for (i=0; i<=ptop; i++) {
8314 mc->mc_pg[i] = mn.mc_pg[i];
8315 mc->mc_ki[i] = mn.mc_ki[i];
8322 /* Adjust other cursors pointing to mp */
8323 MDB_cursor *m2, *m3;
8324 MDB_dbi dbi = mc->mc_dbi;
8325 int fixup = NUMKEYS(mp);
8327 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8328 if (mc->mc_flags & C_SUB)
8329 m3 = &m2->mc_xcursor->mx_cursor;
8334 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8336 if (m3->mc_flags & C_SPLITTING)
8341 for (k=m3->mc_top; k>=0; k--) {
8342 m3->mc_ki[k+1] = m3->mc_ki[k];
8343 m3->mc_pg[k+1] = m3->mc_pg[k];
8345 if (m3->mc_ki[0] >= split_indx) {
8350 m3->mc_pg[0] = mc->mc_pg[0];
8354 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
8355 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
8356 m3->mc_ki[mc->mc_top]++;
8357 if (m3->mc_ki[mc->mc_top] >= fixup) {
8358 m3->mc_pg[mc->mc_top] = rp;
8359 m3->mc_ki[mc->mc_top] -= fixup;
8360 m3->mc_ki[ptop] = mn.mc_ki[ptop];
8362 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
8363 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
8368 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
8371 if (copy) /* tmp page */
8372 mdb_page_free(env, copy);
8374 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8379 mdb_put(MDB_txn *txn, MDB_dbi dbi,
8380 MDB_val *key, MDB_val *data, unsigned int flags)
8385 if (!key || !data || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
8388 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP)) != flags)
8391 mdb_cursor_init(&mc, txn, dbi, &mx);
8392 return mdb_cursor_put(&mc, key, data, flags);
8396 #define MDB_WBUF (1024*1024)
8399 /** State needed for a compacting copy. */
8400 typedef struct mdb_copy {
8401 pthread_mutex_t mc_mutex;
8402 pthread_cond_t mc_cond;
8409 pgno_t mc_next_pgno;
8412 volatile int mc_new;
8417 /** Dedicated writer thread for compacting copy. */
8418 static THREAD_RET ESECT
8419 mdb_env_copythr(void *arg)
8423 int toggle = 0, wsize, rc;
8426 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8429 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8432 pthread_mutex_lock(&my->mc_mutex);
8434 pthread_cond_signal(&my->mc_cond);
8437 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8438 if (my->mc_new < 0) {
8443 wsize = my->mc_wlen[toggle];
8444 ptr = my->mc_wbuf[toggle];
8447 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
8451 } else if (len > 0) {
8465 /* If there's an overflow page tail, write it too */
8466 if (my->mc_olen[toggle]) {
8467 wsize = my->mc_olen[toggle];
8468 ptr = my->mc_over[toggle];
8469 my->mc_olen[toggle] = 0;
8472 my->mc_wlen[toggle] = 0;
8474 pthread_cond_signal(&my->mc_cond);
8476 pthread_cond_signal(&my->mc_cond);
8477 pthread_mutex_unlock(&my->mc_mutex);
8478 return (THREAD_RET)0;
8482 /** Tell the writer thread there's a buffer ready to write */
8484 mdb_env_cthr_toggle(mdb_copy *my, int st)
8486 int toggle = my->mc_toggle ^ 1;
8487 pthread_mutex_lock(&my->mc_mutex);
8488 if (my->mc_status) {
8489 pthread_mutex_unlock(&my->mc_mutex);
8490 return my->mc_status;
8492 while (my->mc_new == 1)
8493 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8495 my->mc_toggle = toggle;
8496 pthread_cond_signal(&my->mc_cond);
8497 pthread_mutex_unlock(&my->mc_mutex);
8501 /** Depth-first tree traversal for compacting copy. */
8503 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
8506 MDB_txn *txn = my->mc_txn;
8508 MDB_page *mo, *mp, *leaf;
8513 /* Empty DB, nothing to do */
8514 if (*pg == P_INVALID)
8521 rc = mdb_page_get(my->mc_txn, *pg, &mc.mc_pg[0], NULL);
8524 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
8528 /* Make cursor pages writable */
8529 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
8533 for (i=0; i<mc.mc_top; i++) {
8534 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
8535 mc.mc_pg[i] = (MDB_page *)ptr;
8536 ptr += my->mc_env->me_psize;
8539 /* This is writable space for a leaf page. Usually not needed. */
8540 leaf = (MDB_page *)ptr;
8542 toggle = my->mc_toggle;
8543 while (mc.mc_snum > 0) {
8545 mp = mc.mc_pg[mc.mc_top];
8549 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
8550 for (i=0; i<n; i++) {
8551 ni = NODEPTR(mp, i);
8552 if (ni->mn_flags & F_BIGDATA) {
8556 /* Need writable leaf */
8558 mc.mc_pg[mc.mc_top] = leaf;
8559 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8561 ni = NODEPTR(mp, i);
8564 memcpy(&pg, NODEDATA(ni), sizeof(pg));
8565 rc = mdb_page_get(txn, pg, &omp, NULL);
8568 if (my->mc_wlen[toggle] >= MDB_WBUF) {
8569 rc = mdb_env_cthr_toggle(my, 1);
8572 toggle = my->mc_toggle;
8574 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
8575 memcpy(mo, omp, my->mc_env->me_psize);
8576 mo->mp_pgno = my->mc_next_pgno;
8577 my->mc_next_pgno += omp->mp_pages;
8578 my->mc_wlen[toggle] += my->mc_env->me_psize;
8579 if (omp->mp_pages > 1) {
8580 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
8581 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
8582 rc = mdb_env_cthr_toggle(my, 1);
8585 toggle = my->mc_toggle;
8587 memcpy(NODEDATA(ni), &mo->mp_pgno, sizeof(pgno_t));
8588 } else if (ni->mn_flags & F_SUBDATA) {
8591 /* Need writable leaf */
8593 mc.mc_pg[mc.mc_top] = leaf;
8594 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8596 ni = NODEPTR(mp, i);
8599 memcpy(&db, NODEDATA(ni), sizeof(db));
8600 my->mc_toggle = toggle;
8601 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
8604 toggle = my->mc_toggle;
8605 memcpy(NODEDATA(ni), &db, sizeof(db));
8610 mc.mc_ki[mc.mc_top]++;
8611 if (mc.mc_ki[mc.mc_top] < n) {
8614 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
8616 rc = mdb_page_get(txn, pg, &mp, NULL);
8621 mc.mc_ki[mc.mc_top] = 0;
8622 if (IS_BRANCH(mp)) {
8623 /* Whenever we advance to a sibling branch page,
8624 * we must proceed all the way down to its first leaf.
8626 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
8629 mc.mc_pg[mc.mc_top] = mp;
8633 if (my->mc_wlen[toggle] >= MDB_WBUF) {
8634 rc = mdb_env_cthr_toggle(my, 1);
8637 toggle = my->mc_toggle;
8639 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
8640 mdb_page_copy(mo, mp, my->mc_env->me_psize);
8641 mo->mp_pgno = my->mc_next_pgno++;
8642 my->mc_wlen[toggle] += my->mc_env->me_psize;
8644 /* Update parent if there is one */
8645 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
8646 SETPGNO(ni, mo->mp_pgno);
8647 mdb_cursor_pop(&mc);
8649 /* Otherwise we're done */
8659 /** Copy environment with compaction. */
8661 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
8666 MDB_txn *txn = NULL;
8671 my.mc_mutex = CreateMutex(NULL, FALSE, NULL);
8672 my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL);
8673 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_os_psize);
8674 if (my.mc_wbuf[0] == NULL)
8677 pthread_mutex_init(&my.mc_mutex, NULL);
8678 pthread_cond_init(&my.mc_cond, NULL);
8679 #ifdef HAVE_MEMALIGN
8680 my.mc_wbuf[0] = memalign(env->me_os_psize, MDB_WBUF*2);
8681 if (my.mc_wbuf[0] == NULL)
8684 rc = posix_memalign((void **)&my.mc_wbuf[0], env->me_os_psize, MDB_WBUF*2);
8689 memset(my.mc_wbuf[0], 0, MDB_WBUF*2);
8690 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
8695 my.mc_next_pgno = 2;
8701 THREAD_CREATE(thr, mdb_env_copythr, &my);
8703 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
8707 mp = (MDB_page *)my.mc_wbuf[0];
8708 memset(mp, 0, 2*env->me_psize);
8710 mp->mp_flags = P_META;
8711 mm = (MDB_meta *)METADATA(mp);
8712 mdb_env_init_meta0(env, mm);
8713 mm->mm_address = env->me_metas[0]->mm_address;
8715 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
8717 mp->mp_flags = P_META;
8718 *(MDB_meta *)METADATA(mp) = *mm;
8719 mm = (MDB_meta *)METADATA(mp);
8721 /* Count the number of free pages, subtract from lastpg to find
8722 * number of active pages
8725 MDB_ID freecount = 0;
8728 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
8729 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
8730 freecount += *(MDB_ID *)data.mv_data;
8731 freecount += txn->mt_dbs[0].md_branch_pages +
8732 txn->mt_dbs[0].md_leaf_pages +
8733 txn->mt_dbs[0].md_overflow_pages;
8735 /* Set metapage 1 */
8736 mm->mm_last_pg = txn->mt_next_pgno - freecount - 1;
8737 mm->mm_dbs[1] = txn->mt_dbs[1];
8738 if (mm->mm_last_pg > 1) {
8739 mm->mm_dbs[1].md_root = mm->mm_last_pg;
8742 mm->mm_dbs[1].md_root = P_INVALID;
8745 my.mc_wlen[0] = env->me_psize * 2;
8747 pthread_mutex_lock(&my.mc_mutex);
8749 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
8750 pthread_mutex_unlock(&my.mc_mutex);
8751 rc = mdb_env_cwalk(&my, &txn->mt_dbs[1].md_root, 0);
8752 if (rc == MDB_SUCCESS && my.mc_wlen[my.mc_toggle])
8753 rc = mdb_env_cthr_toggle(&my, 1);
8754 mdb_env_cthr_toggle(&my, -1);
8755 pthread_mutex_lock(&my.mc_mutex);
8757 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
8758 pthread_mutex_unlock(&my.mc_mutex);
8763 CloseHandle(my.mc_cond);
8764 CloseHandle(my.mc_mutex);
8765 _aligned_free(my.mc_wbuf[0]);
8767 pthread_cond_destroy(&my.mc_cond);
8768 pthread_mutex_destroy(&my.mc_mutex);
8769 free(my.mc_wbuf[0]);
8774 /** Copy environment as-is. */
8776 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
8778 MDB_txn *txn = NULL;
8784 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8788 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8791 /* Do the lock/unlock of the reader mutex before starting the
8792 * write txn. Otherwise other read txns could block writers.
8794 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
8799 /* We must start the actual read txn after blocking writers */
8800 mdb_txn_reset0(txn, "reset-stage1");
8802 /* Temporarily block writers until we snapshot the meta pages */
8805 rc = mdb_txn_renew0(txn);
8807 UNLOCK_MUTEX_W(env);
8812 wsize = env->me_psize * 2;
8816 DO_WRITE(rc, fd, ptr, w2, len);
8820 } else if (len > 0) {
8826 /* Non-blocking or async handles are not supported */
8832 UNLOCK_MUTEX_W(env);
8837 w2 = txn->mt_next_pgno * env->me_psize;
8840 if ((rc = mdb_fsize(env->me_fd, &fsize)))
8847 if (wsize > MAX_WRITE)
8851 DO_WRITE(rc, fd, ptr, w2, len);
8855 } else if (len > 0) {
8872 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
8874 if (flags & MDB_CP_COMPACT)
8875 return mdb_env_copyfd1(env, fd);
8877 return mdb_env_copyfd0(env, fd);
8881 mdb_env_copyfd(MDB_env *env, HANDLE fd)
8883 return mdb_env_copyfd2(env, fd, 0);
8887 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
8891 HANDLE newfd = INVALID_HANDLE_VALUE;
8893 if (env->me_flags & MDB_NOSUBDIR) {
8894 lpath = (char *)path;
8897 len += sizeof(DATANAME);
8898 lpath = malloc(len);
8901 sprintf(lpath, "%s" DATANAME, path);
8904 /* The destination path must exist, but the destination file must not.
8905 * We don't want the OS to cache the writes, since the source data is
8906 * already in the OS cache.
8909 newfd = CreateFile(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
8910 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
8912 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
8914 if (newfd == INVALID_HANDLE_VALUE) {
8919 if (env->me_psize >= env->me_os_psize) {
8921 /* Set O_DIRECT if the file system supports it */
8922 if ((rc = fcntl(newfd, F_GETFL)) != -1)
8923 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
8925 #ifdef F_NOCACHE /* __APPLE__ */
8926 rc = fcntl(newfd, F_NOCACHE, 1);
8934 rc = mdb_env_copyfd2(env, newfd, flags);
8937 if (!(env->me_flags & MDB_NOSUBDIR))
8939 if (newfd != INVALID_HANDLE_VALUE)
8940 if (close(newfd) < 0 && rc == MDB_SUCCESS)
8947 mdb_env_copy(MDB_env *env, const char *path)
8949 return mdb_env_copy2(env, path, 0);
8953 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
8955 if ((flag & CHANGEABLE) != flag)
8958 env->me_flags |= flag;
8960 env->me_flags &= ~flag;
8965 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
8970 *arg = env->me_flags;
8975 mdb_env_set_userctx(MDB_env *env, void *ctx)
8979 env->me_userctx = ctx;
8984 mdb_env_get_userctx(MDB_env *env)
8986 return env ? env->me_userctx : NULL;
8990 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
8995 env->me_assert_func = func;
9001 mdb_env_get_path(MDB_env *env, const char **arg)
9006 *arg = env->me_path;
9011 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
9020 /** Common code for #mdb_stat() and #mdb_env_stat().
9021 * @param[in] env the environment to operate in.
9022 * @param[in] db the #MDB_db record containing the stats to return.
9023 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
9024 * @return 0, this function always succeeds.
9027 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
9029 arg->ms_psize = env->me_psize;
9030 arg->ms_depth = db->md_depth;
9031 arg->ms_branch_pages = db->md_branch_pages;
9032 arg->ms_leaf_pages = db->md_leaf_pages;
9033 arg->ms_overflow_pages = db->md_overflow_pages;
9034 arg->ms_entries = db->md_entries;
9040 mdb_env_stat(MDB_env *env, MDB_stat *arg)
9044 if (env == NULL || arg == NULL)
9047 toggle = mdb_env_pick_meta(env);
9049 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
9053 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
9057 if (env == NULL || arg == NULL)
9060 toggle = mdb_env_pick_meta(env);
9061 arg->me_mapaddr = env->me_metas[toggle]->mm_address;
9062 arg->me_mapsize = env->me_mapsize;
9063 arg->me_maxreaders = env->me_maxreaders;
9065 /* me_numreaders may be zero if this process never used any readers. Use
9066 * the shared numreader count if it exists.
9068 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : env->me_numreaders;
9070 arg->me_last_pgno = env->me_metas[toggle]->mm_last_pg;
9071 arg->me_last_txnid = env->me_metas[toggle]->mm_txnid;
9075 /** Set the default comparison functions for a database.
9076 * Called immediately after a database is opened to set the defaults.
9077 * The user can then override them with #mdb_set_compare() or
9078 * #mdb_set_dupsort().
9079 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
9080 * @param[in] dbi A database handle returned by #mdb_dbi_open()
9083 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
9085 uint16_t f = txn->mt_dbs[dbi].md_flags;
9087 txn->mt_dbxs[dbi].md_cmp =
9088 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
9089 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
9091 txn->mt_dbxs[dbi].md_dcmp =
9092 !(f & MDB_DUPSORT) ? 0 :
9093 ((f & MDB_INTEGERDUP)
9094 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
9095 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
9098 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
9104 int rc, dbflag, exact;
9105 unsigned int unused = 0, seq;
9108 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
9109 mdb_default_cmp(txn, FREE_DBI);
9112 if ((flags & VALID_FLAGS) != flags)
9114 if (txn->mt_flags & MDB_TXN_ERROR)
9120 if (flags & PERSISTENT_FLAGS) {
9121 uint16_t f2 = flags & PERSISTENT_FLAGS;
9122 /* make sure flag changes get committed */
9123 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
9124 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
9125 txn->mt_flags |= MDB_TXN_DIRTY;
9128 mdb_default_cmp(txn, MAIN_DBI);
9132 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
9133 mdb_default_cmp(txn, MAIN_DBI);
9136 /* Is the DB already open? */
9138 for (i=2; i<txn->mt_numdbs; i++) {
9139 if (!txn->mt_dbxs[i].md_name.mv_size) {
9140 /* Remember this free slot */
9141 if (!unused) unused = i;
9144 if (len == txn->mt_dbxs[i].md_name.mv_size &&
9145 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
9151 /* If no free slot and max hit, fail */
9152 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
9153 return MDB_DBS_FULL;
9155 /* Cannot mix named databases with some mainDB flags */
9156 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
9157 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
9159 /* Find the DB info */
9160 dbflag = DB_NEW|DB_VALID;
9163 key.mv_data = (void *)name;
9164 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
9165 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
9166 if (rc == MDB_SUCCESS) {
9167 /* make sure this is actually a DB */
9168 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
9169 if (!(node->mn_flags & F_SUBDATA))
9170 return MDB_INCOMPATIBLE;
9171 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
9172 /* Create if requested */
9173 data.mv_size = sizeof(MDB_db);
9174 data.mv_data = &dummy;
9175 memset(&dummy, 0, sizeof(dummy));
9176 dummy.md_root = P_INVALID;
9177 dummy.md_flags = flags & PERSISTENT_FLAGS;
9178 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
9182 /* OK, got info, add to table */
9183 if (rc == MDB_SUCCESS) {
9184 unsigned int slot = unused ? unused : txn->mt_numdbs;
9185 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
9186 txn->mt_dbxs[slot].md_name.mv_size = len;
9187 txn->mt_dbxs[slot].md_rel = NULL;
9188 txn->mt_dbflags[slot] = dbflag;
9189 /* txn-> and env-> are the same in read txns, use
9190 * tmp variable to avoid undefined assignment
9192 seq = ++txn->mt_env->me_dbiseqs[slot];
9193 txn->mt_dbiseqs[slot] = seq;
9195 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
9197 mdb_default_cmp(txn, slot);
9206 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
9208 if (!arg || !TXN_DBI_EXIST(txn, dbi))
9211 if (txn->mt_flags & MDB_TXN_ERROR)
9214 if (txn->mt_dbflags[dbi] & DB_STALE) {
9217 /* Stale, must read the DB's root. cursor_init does it for us. */
9218 mdb_cursor_init(&mc, txn, dbi, &mx);
9220 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
9223 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
9226 if (dbi <= MAIN_DBI || dbi >= env->me_maxdbs)
9228 ptr = env->me_dbxs[dbi].md_name.mv_data;
9229 /* If there was no name, this was already closed */
9231 env->me_dbxs[dbi].md_name.mv_data = NULL;
9232 env->me_dbxs[dbi].md_name.mv_size = 0;
9233 env->me_dbflags[dbi] = 0;
9234 env->me_dbiseqs[dbi]++;
9239 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
9241 /* We could return the flags for the FREE_DBI too but what's the point? */
9242 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9244 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
9248 /** Add all the DB's pages to the free list.
9249 * @param[in] mc Cursor on the DB to free.
9250 * @param[in] subs non-Zero to check for sub-DBs in this DB.
9251 * @return 0 on success, non-zero on failure.
9254 mdb_drop0(MDB_cursor *mc, int subs)
9258 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
9259 if (rc == MDB_SUCCESS) {
9260 MDB_txn *txn = mc->mc_txn;
9265 /* LEAF2 pages have no nodes, cannot have sub-DBs */
9266 if (IS_LEAF2(mc->mc_pg[mc->mc_top]))
9269 mdb_cursor_copy(mc, &mx);
9270 while (mc->mc_snum > 0) {
9271 MDB_page *mp = mc->mc_pg[mc->mc_top];
9272 unsigned n = NUMKEYS(mp);
9274 for (i=0; i<n; i++) {
9275 ni = NODEPTR(mp, i);
9276 if (ni->mn_flags & F_BIGDATA) {
9279 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9280 rc = mdb_page_get(txn, pg, &omp, NULL);
9283 mdb_cassert(mc, IS_OVERFLOW(omp));
9284 rc = mdb_midl_append_range(&txn->mt_free_pgs,
9288 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
9289 mdb_xcursor_init1(mc, ni);
9290 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
9296 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
9298 for (i=0; i<n; i++) {
9300 ni = NODEPTR(mp, i);
9303 mdb_midl_xappend(txn->mt_free_pgs, pg);
9308 mc->mc_ki[mc->mc_top] = i;
9309 rc = mdb_cursor_sibling(mc, 1);
9311 if (rc != MDB_NOTFOUND)
9313 /* no more siblings, go back to beginning
9314 * of previous level.
9318 for (i=1; i<mc->mc_snum; i++) {
9320 mc->mc_pg[i] = mx.mc_pg[i];
9325 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
9328 txn->mt_flags |= MDB_TXN_ERROR;
9329 } else if (rc == MDB_NOTFOUND) {
9335 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
9337 MDB_cursor *mc, *m2;
9340 if ((unsigned)del > 1 || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9343 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
9346 if (dbi > MAIN_DBI && TXN_DBI_CHANGED(txn, dbi))
9349 rc = mdb_cursor_open(txn, dbi, &mc);
9353 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
9354 /* Invalidate the dropped DB's cursors */
9355 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
9356 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
9360 /* Can't delete the main DB */
9361 if (del && dbi > MAIN_DBI) {
9362 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, 0);
9364 txn->mt_dbflags[dbi] = DB_STALE;
9365 mdb_dbi_close(txn->mt_env, dbi);
9367 txn->mt_flags |= MDB_TXN_ERROR;
9370 /* reset the DB record, mark it dirty */
9371 txn->mt_dbflags[dbi] |= DB_DIRTY;
9372 txn->mt_dbs[dbi].md_depth = 0;
9373 txn->mt_dbs[dbi].md_branch_pages = 0;
9374 txn->mt_dbs[dbi].md_leaf_pages = 0;
9375 txn->mt_dbs[dbi].md_overflow_pages = 0;
9376 txn->mt_dbs[dbi].md_entries = 0;
9377 txn->mt_dbs[dbi].md_root = P_INVALID;
9379 txn->mt_flags |= MDB_TXN_DIRTY;
9382 mdb_cursor_close(mc);
9386 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9388 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9391 txn->mt_dbxs[dbi].md_cmp = cmp;
9395 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9397 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9400 txn->mt_dbxs[dbi].md_dcmp = cmp;
9404 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
9406 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9409 txn->mt_dbxs[dbi].md_rel = rel;
9413 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
9415 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9418 txn->mt_dbxs[dbi].md_relctx = ctx;
9423 mdb_env_get_maxkeysize(MDB_env *env)
9425 return ENV_MAXKEY(env);
9429 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
9431 unsigned int i, rdrs;
9434 int rc = 0, first = 1;
9438 if (!env->me_txns) {
9439 return func("(no reader locks)\n", ctx);
9441 rdrs = env->me_txns->mti_numreaders;
9442 mr = env->me_txns->mti_readers;
9443 for (i=0; i<rdrs; i++) {
9445 txnid_t txnid = mr[i].mr_txnid;
9446 sprintf(buf, txnid == (txnid_t)-1 ?
9447 "%10d %"Z"x -\n" : "%10d %"Z"x %"Z"u\n",
9448 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
9451 rc = func(" pid thread txnid\n", ctx);
9455 rc = func(buf, ctx);
9461 rc = func("(no active readers)\n", ctx);
9466 /** Insert pid into list if not already present.
9467 * return -1 if already present.
9470 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
9472 /* binary search of pid in list */
9474 unsigned cursor = 1;
9476 unsigned n = ids[0];
9479 unsigned pivot = n >> 1;
9480 cursor = base + pivot + 1;
9481 val = pid - ids[cursor];
9486 } else if ( val > 0 ) {
9491 /* found, so it's a duplicate */
9500 for (n = ids[0]; n > cursor; n--)
9507 mdb_reader_check(MDB_env *env, int *dead)
9509 unsigned int i, j, rdrs;
9511 MDB_PID_T *pids, pid;
9520 rdrs = env->me_txns->mti_numreaders;
9521 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
9525 mr = env->me_txns->mti_readers;
9526 for (i=0; i<rdrs; i++) {
9527 if (mr[i].mr_pid && mr[i].mr_pid != env->me_pid) {
9529 if (mdb_pid_insert(pids, pid) == 0) {
9530 if (!mdb_reader_pid(env, Pidcheck, pid)) {
9532 /* Recheck, a new process may have reused pid */
9533 if (!mdb_reader_pid(env, Pidcheck, pid)) {
9534 for (j=i; j<rdrs; j++)
9535 if (mr[j].mr_pid == pid) {
9536 DPRINTF(("clear stale reader pid %u txn %"Z"d",
9537 (unsigned) pid, mr[j].mr_txnid));
9542 UNLOCK_MUTEX_R(env);