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-2016 Howard Chu, Symas Corp.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted only as authorized by the OpenLDAP
15 * A copy of this license is available in the file LICENSE in the
16 * top-level directory of the distribution or, alternatively, at
17 * <http://www.OpenLDAP.org/license.html>.
19 * This code is derived from btree.c written by Martin Hedenfalk.
21 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
23 * Permission to use, copy, modify, and distribute this software for any
24 * purpose with or without fee is hereby granted, provided that the above
25 * copyright notice and this permission notice appear in all copies.
27 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
28 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
29 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
30 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
31 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
32 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
33 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
38 #if defined(__WIN64__)
39 #define _FILE_OFFSET_BITS 64
44 /** getpid() returns int; MinGW defines pid_t but MinGW64 typedefs it
45 * as int64 which is wrong. MSVC doesn't define it at all, so just
49 #define MDB_THR_T DWORD
50 #include <sys/types.h>
53 # include <sys/param.h>
55 # define LITTLE_ENDIAN 1234
56 # define BIG_ENDIAN 4321
57 # define BYTE_ORDER LITTLE_ENDIAN
59 # define SSIZE_MAX INT_MAX
63 #include <sys/types.h>
65 #define MDB_PID_T pid_t
66 #define MDB_THR_T pthread_t
67 #include <sys/param.h>
70 #ifdef HAVE_SYS_FILE_H
76 #if defined(__mips) && defined(__linux)
77 /* MIPS has cache coherency issues, requires explicit cache control */
78 #include <asm/cachectl.h>
79 extern int cacheflush(char *addr, int nbytes, int cache);
80 #define CACHEFLUSH(addr, bytes, cache) cacheflush(addr, bytes, cache)
82 #define CACHEFLUSH(addr, bytes, cache)
85 #if defined(__linux) && !defined(MDB_FDATASYNC_WORKS)
86 /** fdatasync is broken on ext3/ext4fs on older kernels, see
87 * description in #mdb_env_open2 comments. You can safely
88 * define MDB_FDATASYNC_WORKS if this code will only be run
89 * on kernels 3.6 and newer.
91 #define BROKEN_FDATASYNC
105 typedef SSIZE_T ssize_t;
110 #if defined(__sun) || defined(ANDROID)
111 /* Most platforms have posix_memalign, older may only have memalign */
112 #define HAVE_MEMALIGN 1
116 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
117 #include <netinet/in.h>
118 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
121 #if defined(__APPLE__) || defined (BSD)
122 # define MDB_USE_POSIX_SEM 1
123 # define MDB_FDATASYNC fsync
124 #elif defined(ANDROID)
125 # define MDB_FDATASYNC fsync
130 #ifdef MDB_USE_POSIX_SEM
131 # define MDB_USE_HASH 1
132 #include <semaphore.h>
134 #define MDB_USE_POSIX_MUTEX 1
138 #if defined(_WIN32) + defined(MDB_USE_POSIX_SEM) \
139 + defined(MDB_USE_POSIX_MUTEX) != 1
140 # error "Ambiguous shared-lock implementation"
144 #include <valgrind/memcheck.h>
145 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
146 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
147 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
148 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
149 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
151 #define VGMEMP_CREATE(h,r,z)
152 #define VGMEMP_ALLOC(h,a,s)
153 #define VGMEMP_FREE(h,a)
154 #define VGMEMP_DESTROY(h)
155 #define VGMEMP_DEFINED(a,s)
159 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
160 /* Solaris just defines one or the other */
161 # define LITTLE_ENDIAN 1234
162 # define BIG_ENDIAN 4321
163 # ifdef _LITTLE_ENDIAN
164 # define BYTE_ORDER LITTLE_ENDIAN
166 # define BYTE_ORDER BIG_ENDIAN
169 # define BYTE_ORDER __BYTE_ORDER
173 #ifndef LITTLE_ENDIAN
174 #define LITTLE_ENDIAN __LITTLE_ENDIAN
177 #define BIG_ENDIAN __BIG_ENDIAN
180 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
181 #define MISALIGNED_OK 1
187 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
188 # error "Unknown or unsupported endianness (BYTE_ORDER)"
189 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
190 # error "Two's complement, reasonably sized integer types, please"
194 /** Put infrequently used env functions in separate section */
196 # define ESECT __attribute__ ((section("__TEXT,text_env")))
198 # define ESECT __attribute__ ((section("text_env")))
205 #define CALL_CONV WINAPI
210 /** @defgroup internal LMDB Internals
213 /** @defgroup compat Compatibility Macros
214 * A bunch of macros to minimize the amount of platform-specific ifdefs
215 * needed throughout the rest of the code. When the features this library
216 * needs are similar enough to POSIX to be hidden in a one-or-two line
217 * replacement, this macro approach is used.
221 /** Features under development */
226 /** Wrapper around __func__, which is a C99 feature */
227 #if __STDC_VERSION__ >= 199901L
228 # define mdb_func_ __func__
229 #elif __GNUC__ >= 2 || _MSC_VER >= 1300
230 # define mdb_func_ __FUNCTION__
232 /* If a debug message says <mdb_unknown>(), update the #if statements above */
233 # define mdb_func_ "<mdb_unknown>"
236 /* Internal error codes, not exposed outside liblmdb */
237 #define MDB_NO_ROOT (MDB_LAST_ERRCODE + 10)
239 #define MDB_OWNERDEAD ((int) WAIT_ABANDONED)
240 #elif defined(MDB_USE_POSIX_MUTEX) && defined(EOWNERDEAD)
241 #define MDB_OWNERDEAD EOWNERDEAD /**< #LOCK_MUTEX0() result if dead owner */
245 #define GLIBC_VER ((__GLIBC__ << 16 )| __GLIBC_MINOR__)
247 /** Some platforms define the EOWNERDEAD error code
248 * even though they don't support Robust Mutexes.
249 * Compile with -DMDB_USE_ROBUST=0, or use some other
250 * mechanism like -DMDB_USE_POSIX_SEM instead of
251 * -DMDB_USE_POSIX_MUTEX.
252 * (Posix semaphores are not robust.)
254 #ifndef MDB_USE_ROBUST
255 /* Android currently lacks Robust Mutex support. So does glibc < 2.4. */
256 # if defined(MDB_USE_POSIX_MUTEX) && (defined(ANDROID) || \
257 (defined(__GLIBC__) && GLIBC_VER < 0x020004))
258 # define MDB_USE_ROBUST 0
260 # define MDB_USE_ROBUST 1
261 /* glibc < 2.12 only provided _np API */
262 # if (defined(__GLIBC__) && GLIBC_VER < 0x02000c) || \
263 (defined(PTHREAD_MUTEX_ROBUST_NP) && !defined(PTHREAD_MUTEX_ROBUST))
264 # define PTHREAD_MUTEX_ROBUST PTHREAD_MUTEX_ROBUST_NP
265 # define pthread_mutexattr_setrobust(attr, flag) pthread_mutexattr_setrobust_np(attr, flag)
266 # define pthread_mutex_consistent(mutex) pthread_mutex_consistent_np(mutex)
269 #endif /* MDB_USE_ROBUST */
271 #if defined(MDB_OWNERDEAD) && MDB_USE_ROBUST
272 #define MDB_ROBUST_SUPPORTED 1
276 #define MDB_USE_HASH 1
277 #define MDB_PIDLOCK 0
278 #define THREAD_RET DWORD
279 #define pthread_t HANDLE
280 #define pthread_mutex_t HANDLE
281 #define pthread_cond_t HANDLE
282 typedef HANDLE mdb_mutex_t, mdb_mutexref_t;
283 #define pthread_key_t DWORD
284 #define pthread_self() GetCurrentThreadId()
285 #define pthread_key_create(x,y) \
286 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
287 #define pthread_key_delete(x) TlsFree(x)
288 #define pthread_getspecific(x) TlsGetValue(x)
289 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
290 #define pthread_mutex_unlock(x) ReleaseMutex(*x)
291 #define pthread_mutex_lock(x) WaitForSingleObject(*x, INFINITE)
292 #define pthread_cond_signal(x) SetEvent(*x)
293 #define pthread_cond_wait(cond,mutex) do{SignalObjectAndWait(*mutex, *cond, INFINITE, FALSE); WaitForSingleObject(*mutex, INFINITE);}while(0)
294 #define THREAD_CREATE(thr,start,arg) \
295 (((thr) = CreateThread(NULL, 0, start, arg, 0, NULL)) ? 0 : ErrCode())
296 #define THREAD_FINISH(thr) \
297 (WaitForSingleObject(thr, INFINITE) ? ErrCode() : 0)
298 #define LOCK_MUTEX0(mutex) WaitForSingleObject(mutex, INFINITE)
299 #define UNLOCK_MUTEX(mutex) ReleaseMutex(mutex)
300 #define mdb_mutex_consistent(mutex) 0
301 #define getpid() GetCurrentProcessId()
302 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
303 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
304 #define ErrCode() GetLastError()
305 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
306 #define close(fd) (CloseHandle(fd) ? 0 : -1)
307 #define munmap(ptr,len) UnmapViewOfFile(ptr)
308 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
309 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
311 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
315 #define THREAD_RET void *
316 #define THREAD_CREATE(thr,start,arg) pthread_create(&thr,NULL,start,arg)
317 #define THREAD_FINISH(thr) pthread_join(thr,NULL)
318 #define Z "z" /**< printf format modifier for size_t */
320 /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
321 #define MDB_PIDLOCK 1
323 #ifdef MDB_USE_POSIX_SEM
325 typedef sem_t *mdb_mutex_t, *mdb_mutexref_t;
326 #define LOCK_MUTEX0(mutex) mdb_sem_wait(mutex)
327 #define UNLOCK_MUTEX(mutex) sem_post(mutex)
330 mdb_sem_wait(sem_t *sem)
333 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
337 #else /* MDB_USE_POSIX_MUTEX: */
338 /** Shared mutex/semaphore as it is stored (mdb_mutex_t), and as
339 * local variables keep it (mdb_mutexref_t).
341 * When #mdb_mutexref_t is a pointer declaration and #mdb_mutex_t is
342 * not, then it is array[size 1] so it can be assigned to a pointer.
345 typedef pthread_mutex_t mdb_mutex_t[1], *mdb_mutexref_t;
347 /** Lock the reader or writer mutex.
348 * Returns 0 or a code to give #mdb_mutex_failed(), as in #LOCK_MUTEX().
350 #define LOCK_MUTEX0(mutex) pthread_mutex_lock(mutex)
351 /** Unlock the reader or writer mutex.
353 #define UNLOCK_MUTEX(mutex) pthread_mutex_unlock(mutex)
354 /** Mark mutex-protected data as repaired, after death of previous owner.
356 #define mdb_mutex_consistent(mutex) pthread_mutex_consistent(mutex)
357 #endif /* MDB_USE_POSIX_SEM */
359 /** Get the error code for the last failed system function.
361 #define ErrCode() errno
363 /** An abstraction for a file handle.
364 * On POSIX systems file handles are small integers. On Windows
365 * they're opaque pointers.
369 /** A value for an invalid file handle.
370 * Mainly used to initialize file variables and signify that they are
373 #define INVALID_HANDLE_VALUE (-1)
375 /** Get the size of a memory page for the system.
376 * This is the basic size that the platform's memory manager uses, and is
377 * fundamental to the use of memory-mapped files.
379 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
382 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
385 #define MNAME_LEN (sizeof(pthread_mutex_t))
390 #ifdef MDB_ROBUST_SUPPORTED
391 /** Lock mutex, handle any error, set rc = result.
392 * Return 0 on success, nonzero (not rc) on error.
394 #define LOCK_MUTEX(rc, env, mutex) \
395 (((rc) = LOCK_MUTEX0(mutex)) && \
396 ((rc) = mdb_mutex_failed(env, mutex, rc)))
397 static int mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc);
399 #define LOCK_MUTEX(rc, env, mutex) ((rc) = LOCK_MUTEX0(mutex))
400 #define mdb_mutex_failed(env, mutex, rc) (rc)
404 /** A flag for opening a file and requesting synchronous data writes.
405 * This is only used when writing a meta page. It's not strictly needed;
406 * we could just do a normal write and then immediately perform a flush.
407 * But if this flag is available it saves us an extra system call.
409 * @note If O_DSYNC is undefined but exists in /usr/include,
410 * preferably set some compiler flag to get the definition.
414 # define MDB_DSYNC O_DSYNC
416 # define MDB_DSYNC O_SYNC
421 /** Function for flushing the data of a file. Define this to fsync
422 * if fdatasync() is not supported.
424 #ifndef MDB_FDATASYNC
425 # define MDB_FDATASYNC fdatasync
429 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
440 /** A page number in the database.
441 * Note that 64 bit page numbers are overkill, since pages themselves
442 * already represent 12-13 bits of addressable memory, and the OS will
443 * always limit applications to a maximum of 63 bits of address space.
445 * @note In the #MDB_node structure, we only store 48 bits of this value,
446 * which thus limits us to only 60 bits of addressable data.
448 typedef MDB_ID pgno_t;
450 /** A transaction ID.
451 * See struct MDB_txn.mt_txnid for details.
453 typedef MDB_ID txnid_t;
455 /** @defgroup debug Debug Macros
459 /** Enable debug output. Needs variable argument macros (a C99 feature).
460 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
461 * read from and written to the database (used for free space management).
467 static int mdb_debug;
468 static txnid_t mdb_debug_start;
470 /** Print a debug message with printf formatting.
471 * Requires double parenthesis around 2 or more args.
473 # define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
474 # define DPRINTF0(fmt, ...) \
475 fprintf(stderr, "%s:%d " fmt "\n", mdb_func_, __LINE__, __VA_ARGS__)
477 # define DPRINTF(args) ((void) 0)
479 /** Print a debug string.
480 * The string is printed literally, with no format processing.
482 #define DPUTS(arg) DPRINTF(("%s", arg))
483 /** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
485 (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
488 /** @brief The maximum size of a database page.
490 * It is 32k or 64k, since value-PAGEBASE must fit in
491 * #MDB_page.%mp_upper.
493 * LMDB will use database pages < OS pages if needed.
494 * That causes more I/O in write transactions: The OS must
495 * know (read) the whole page before writing a partial page.
497 * Note that we don't currently support Huge pages. On Linux,
498 * regular data files cannot use Huge pages, and in general
499 * Huge pages aren't actually pageable. We rely on the OS
500 * demand-pager to read our data and page it out when memory
501 * pressure from other processes is high. So until OSs have
502 * actual paging support for Huge pages, they're not viable.
504 #define MAX_PAGESIZE (PAGEBASE ? 0x10000 : 0x8000)
506 /** The minimum number of keys required in a database page.
507 * Setting this to a larger value will place a smaller bound on the
508 * maximum size of a data item. Data items larger than this size will
509 * be pushed into overflow pages instead of being stored directly in
510 * the B-tree node. This value used to default to 4. With a page size
511 * of 4096 bytes that meant that any item larger than 1024 bytes would
512 * go into an overflow page. That also meant that on average 2-3KB of
513 * each overflow page was wasted space. The value cannot be lower than
514 * 2 because then there would no longer be a tree structure. With this
515 * value, items larger than 2KB will go into overflow pages, and on
516 * average only 1KB will be wasted.
518 #define MDB_MINKEYS 2
520 /** A stamp that identifies a file as an LMDB file.
521 * There's nothing special about this value other than that it is easily
522 * recognizable, and it will reflect any byte order mismatches.
524 #define MDB_MAGIC 0xBEEFC0DE
526 /** The version number for a database's datafile format. */
527 #define MDB_DATA_VERSION ((MDB_DEVEL) ? 999 : 1)
528 /** The version number for a database's lockfile format. */
529 #define MDB_LOCK_VERSION 1
531 /** @brief The max size of a key we can write, or 0 for computed max.
533 * This macro should normally be left alone or set to 0.
534 * Note that a database with big keys or dupsort data cannot be
535 * reliably modified by a liblmdb which uses a smaller max.
536 * The default is 511 for backwards compat, or 0 when #MDB_DEVEL.
538 * Other values are allowed, for backwards compat. However:
539 * A value bigger than the computed max can break if you do not
540 * know what you are doing, and liblmdb <= 0.9.10 can break when
541 * modifying a DB with keys/dupsort data bigger than its max.
543 * Data items in an #MDB_DUPSORT database are also limited to
544 * this size, since they're actually keys of a sub-DB. Keys and
545 * #MDB_DUPSORT data items must fit on a node in a regular page.
547 #ifndef MDB_MAXKEYSIZE
548 #define MDB_MAXKEYSIZE ((MDB_DEVEL) ? 0 : 511)
551 /** The maximum size of a key we can write to the environment. */
553 #define ENV_MAXKEY(env) (MDB_MAXKEYSIZE)
555 #define ENV_MAXKEY(env) ((env)->me_maxkey)
558 /** @brief The maximum size of a data item.
560 * We only store a 32 bit value for node sizes.
562 #define MAXDATASIZE 0xffffffffUL
565 /** Key size which fits in a #DKBUF.
568 #define DKBUF_MAXKEYSIZE ((MDB_MAXKEYSIZE) > 0 ? (MDB_MAXKEYSIZE) : 511)
571 * This is used for printing a hex dump of a key's contents.
573 #define DKBUF char kbuf[DKBUF_MAXKEYSIZE*2+1]
574 /** Display a key in hex.
576 * Invoke a function to display a key in hex.
578 #define DKEY(x) mdb_dkey(x, kbuf)
584 /** An invalid page number.
585 * Mainly used to denote an empty tree.
587 #define P_INVALID (~(pgno_t)0)
589 /** Test if the flags \b f are set in a flag word \b w. */
590 #define F_ISSET(w, f) (((w) & (f)) == (f))
592 /** Round \b n up to an even number. */
593 #define EVEN(n) (((n) + 1U) & -2) /* sign-extending -2 to match n+1U */
595 /** Used for offsets within a single page.
596 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
599 typedef uint16_t indx_t;
601 /** Default size of memory map.
602 * This is certainly too small for any actual applications. Apps should always set
603 * the size explicitly using #mdb_env_set_mapsize().
605 #define DEFAULT_MAPSIZE 1048576
607 /** @defgroup readers Reader Lock Table
608 * Readers don't acquire any locks for their data access. Instead, they
609 * simply record their transaction ID in the reader table. The reader
610 * mutex is needed just to find an empty slot in the reader table. The
611 * slot's address is saved in thread-specific data so that subsequent read
612 * transactions started by the same thread need no further locking to proceed.
614 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
616 * No reader table is used if the database is on a read-only filesystem, or
617 * if #MDB_NOLOCK is set.
619 * Since the database uses multi-version concurrency control, readers don't
620 * actually need any locking. This table is used to keep track of which
621 * readers are using data from which old transactions, so that we'll know
622 * when a particular old transaction is no longer in use. Old transactions
623 * that have discarded any data pages can then have those pages reclaimed
624 * for use by a later write transaction.
626 * The lock table is constructed such that reader slots are aligned with the
627 * processor's cache line size. Any slot is only ever used by one thread.
628 * This alignment guarantees that there will be no contention or cache
629 * thrashing as threads update their own slot info, and also eliminates
630 * any need for locking when accessing a slot.
632 * A writer thread will scan every slot in the table to determine the oldest
633 * outstanding reader transaction. Any freed pages older than this will be
634 * reclaimed by the writer. The writer doesn't use any locks when scanning
635 * this table. This means that there's no guarantee that the writer will
636 * see the most up-to-date reader info, but that's not required for correct
637 * operation - all we need is to know the upper bound on the oldest reader,
638 * we don't care at all about the newest reader. So the only consequence of
639 * reading stale information here is that old pages might hang around a
640 * while longer before being reclaimed. That's actually good anyway, because
641 * the longer we delay reclaiming old pages, the more likely it is that a
642 * string of contiguous pages can be found after coalescing old pages from
643 * many old transactions together.
646 /** Number of slots in the reader table.
647 * This value was chosen somewhat arbitrarily. 126 readers plus a
648 * couple mutexes fit exactly into 8KB on my development machine.
649 * Applications should set the table size using #mdb_env_set_maxreaders().
651 #define DEFAULT_READERS 126
653 /** The size of a CPU cache line in bytes. We want our lock structures
654 * aligned to this size to avoid false cache line sharing in the
656 * This value works for most CPUs. For Itanium this should be 128.
662 /** The information we store in a single slot of the reader table.
663 * In addition to a transaction ID, we also record the process and
664 * thread ID that owns a slot, so that we can detect stale information,
665 * e.g. threads or processes that went away without cleaning up.
666 * @note We currently don't check for stale records. We simply re-init
667 * the table when we know that we're the only process opening the
670 typedef struct MDB_rxbody {
671 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
672 * Multiple readers that start at the same time will probably have the
673 * same ID here. Again, it's not important to exclude them from
674 * anything; all we need to know is which version of the DB they
675 * started from so we can avoid overwriting any data used in that
676 * particular version.
678 volatile txnid_t mrb_txnid;
679 /** The process ID of the process owning this reader txn. */
680 volatile MDB_PID_T mrb_pid;
681 /** The thread ID of the thread owning this txn. */
682 volatile MDB_THR_T mrb_tid;
685 /** The actual reader record, with cacheline padding. */
686 typedef struct MDB_reader {
689 /** shorthand for mrb_txnid */
690 #define mr_txnid mru.mrx.mrb_txnid
691 #define mr_pid mru.mrx.mrb_pid
692 #define mr_tid mru.mrx.mrb_tid
693 /** cache line alignment */
694 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
698 /** The header for the reader table.
699 * The table resides in a memory-mapped file. (This is a different file
700 * than is used for the main database.)
702 * For POSIX the actual mutexes reside in the shared memory of this
703 * mapped file. On Windows, mutexes are named objects allocated by the
704 * kernel; we store the mutex names in this mapped file so that other
705 * processes can grab them. This same approach is also used on
706 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
707 * process-shared POSIX mutexes. For these cases where a named object
708 * is used, the object name is derived from a 64 bit FNV hash of the
709 * environment pathname. As such, naming collisions are extremely
710 * unlikely. If a collision occurs, the results are unpredictable.
712 typedef struct MDB_txbody {
713 /** Stamp identifying this as an LMDB file. It must be set
716 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
718 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
719 char mtb_rmname[MNAME_LEN];
721 /** Mutex protecting access to this table.
722 * This is the reader table lock used with LOCK_MUTEX().
724 mdb_mutex_t mtb_rmutex;
726 /** The ID of the last transaction committed to the database.
727 * This is recorded here only for convenience; the value can always
728 * be determined by reading the main database meta pages.
730 volatile txnid_t mtb_txnid;
731 /** The number of slots that have been used in the reader table.
732 * This always records the maximum count, it is not decremented
733 * when readers release their slots.
735 volatile unsigned mtb_numreaders;
738 /** The actual reader table definition. */
739 typedef struct MDB_txninfo {
742 #define mti_magic mt1.mtb.mtb_magic
743 #define mti_format mt1.mtb.mtb_format
744 #define mti_rmutex mt1.mtb.mtb_rmutex
745 #define mti_rmname mt1.mtb.mtb_rmname
746 #define mti_txnid mt1.mtb.mtb_txnid
747 #define mti_numreaders mt1.mtb.mtb_numreaders
748 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
751 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
752 char mt2_wmname[MNAME_LEN];
753 #define mti_wmname mt2.mt2_wmname
755 mdb_mutex_t mt2_wmutex;
756 #define mti_wmutex mt2.mt2_wmutex
758 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
760 MDB_reader mti_readers[1];
763 /** Lockfile format signature: version, features and field layout */
764 #define MDB_LOCK_FORMAT \
766 ((MDB_LOCK_VERSION) \
767 /* Flags which describe functionality */ \
768 + (((MDB_PIDLOCK) != 0) << 16)))
771 /** Common header for all page types. The page type depends on #mp_flags.
773 * #P_BRANCH and #P_LEAF pages have unsorted '#MDB_node's at the end, with
774 * sorted #mp_ptrs[] entries referring to them. Exception: #P_LEAF2 pages
775 * omit mp_ptrs and pack sorted #MDB_DUPFIXED values after the page header.
777 * #P_OVERFLOW records occupy one or more contiguous pages where only the
778 * first has a page header. They hold the real data of #F_BIGDATA nodes.
780 * #P_SUBP sub-pages are small leaf "pages" with duplicate data.
781 * A node with flag #F_DUPDATA but not #F_SUBDATA contains a sub-page.
782 * (Duplicate data can also go in sub-databases, which use normal pages.)
784 * #P_META pages contain #MDB_meta, the start point of an LMDB snapshot.
786 * Each non-metapage up to #MDB_meta.%mm_last_pg is reachable exactly once
787 * in the snapshot: Either used by a database or listed in a freeDB record.
789 typedef struct MDB_page {
790 #define mp_pgno mp_p.p_pgno
791 #define mp_next mp_p.p_next
793 pgno_t p_pgno; /**< page number */
794 struct MDB_page *p_next; /**< for in-memory list of freed pages */
796 uint16_t mp_pad; /**< key size if this is a LEAF2 page */
797 /** @defgroup mdb_page Page Flags
799 * Flags for the page headers.
802 #define P_BRANCH 0x01 /**< branch page */
803 #define P_LEAF 0x02 /**< leaf page */
804 #define P_OVERFLOW 0x04 /**< overflow page */
805 #define P_META 0x08 /**< meta page */
806 #define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
807 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
808 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
809 #define P_LOOSE 0x4000 /**< page was dirtied then freed, can be reused */
810 #define P_KEEP 0x8000 /**< leave this page alone during spill */
812 uint16_t mp_flags; /**< @ref mdb_page */
813 #define mp_lower mp_pb.pb.pb_lower
814 #define mp_upper mp_pb.pb.pb_upper
815 #define mp_pages mp_pb.pb_pages
818 indx_t pb_lower; /**< lower bound of free space */
819 indx_t pb_upper; /**< upper bound of free space */
821 uint32_t pb_pages; /**< number of overflow pages */
823 indx_t mp_ptrs[1]; /**< dynamic size */
826 /** Size of the page header, excluding dynamic data at the end */
827 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
829 /** Address of first usable data byte in a page, after the header */
830 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
832 /** ITS#7713, change PAGEBASE to handle 65536 byte pages */
833 #define PAGEBASE ((MDB_DEVEL) ? PAGEHDRSZ : 0)
835 /** Number of nodes on a page */
836 #define NUMKEYS(p) (((p)->mp_lower - (PAGEHDRSZ-PAGEBASE)) >> 1)
838 /** The amount of space remaining in the page */
839 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
841 /** The percentage of space used in the page, in tenths of a percent. */
842 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
843 ((env)->me_psize - PAGEHDRSZ))
844 /** The minimum page fill factor, in tenths of a percent.
845 * Pages emptier than this are candidates for merging.
847 #define FILL_THRESHOLD 250
849 /** Test if a page is a leaf page */
850 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
851 /** Test if a page is a LEAF2 page */
852 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
853 /** Test if a page is a branch page */
854 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
855 /** Test if a page is an overflow page */
856 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
857 /** Test if a page is a sub page */
858 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
860 /** The number of overflow pages needed to store the given size. */
861 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
863 /** Link in #MDB_txn.%mt_loose_pgs list.
864 * Kept outside the page header, which is needed when reusing the page.
866 #define NEXT_LOOSE_PAGE(p) (*(MDB_page **)((p) + 2))
868 /** Header for a single key/data pair within a page.
869 * Used in pages of type #P_BRANCH and #P_LEAF without #P_LEAF2.
870 * We guarantee 2-byte alignment for 'MDB_node's.
872 typedef struct MDB_node {
873 /** lo and hi are used for data size on leaf nodes and for
874 * child pgno on branch nodes. On 64 bit platforms, flags
875 * is also used for pgno. (Branch nodes have no flags).
876 * They are in host byte order in case that lets some
877 * accesses be optimized into a 32-bit word access.
879 #if BYTE_ORDER == LITTLE_ENDIAN
880 unsigned short mn_lo, mn_hi; /**< part of data size or pgno */
882 unsigned short mn_hi, mn_lo;
884 /** @defgroup mdb_node Node Flags
886 * Flags for node headers.
889 #define F_BIGDATA 0x01 /**< data put on overflow page */
890 #define F_SUBDATA 0x02 /**< data is a sub-database */
891 #define F_DUPDATA 0x04 /**< data has duplicates */
893 /** valid flags for #mdb_node_add() */
894 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
897 unsigned short mn_flags; /**< @ref mdb_node */
898 unsigned short mn_ksize; /**< key size */
899 char mn_data[1]; /**< key and data are appended here */
902 /** Size of the node header, excluding dynamic data at the end */
903 #define NODESIZE offsetof(MDB_node, mn_data)
905 /** Bit position of top word in page number, for shifting mn_flags */
906 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
908 /** Size of a node in a branch page with a given key.
909 * This is just the node header plus the key, there is no data.
911 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
913 /** Size of a node in a leaf page with a given key and data.
914 * This is node header plus key plus data size.
916 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
918 /** Address of node \b i in page \b p */
919 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i] + PAGEBASE))
921 /** Address of the key for the node */
922 #define NODEKEY(node) (void *)((node)->mn_data)
924 /** Address of the data for a node */
925 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
927 /** Get the page number pointed to by a branch node */
928 #define NODEPGNO(node) \
929 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
930 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
931 /** Set the page number in a branch node */
932 #define SETPGNO(node,pgno) do { \
933 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
934 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
936 /** Get the size of the data in a leaf node */
937 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
938 /** Set the size of the data for a leaf node */
939 #define SETDSZ(node,size) do { \
940 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
941 /** The size of a key in a node */
942 #define NODEKSZ(node) ((node)->mn_ksize)
944 /** Copy a page number from src to dst */
946 #define COPY_PGNO(dst,src) dst = src
948 #if SIZE_MAX > 4294967295UL
949 #define COPY_PGNO(dst,src) do { \
950 unsigned short *s, *d; \
951 s = (unsigned short *)&(src); \
952 d = (unsigned short *)&(dst); \
959 #define COPY_PGNO(dst,src) do { \
960 unsigned short *s, *d; \
961 s = (unsigned short *)&(src); \
962 d = (unsigned short *)&(dst); \
968 /** The address of a key in a LEAF2 page.
969 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
970 * There are no node headers, keys are stored contiguously.
972 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
974 /** Set the \b node's key into \b keyptr, if requested. */
975 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
976 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
978 /** Set the \b node's key into \b key. */
979 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
981 /** Information about a single database in the environment. */
982 typedef struct MDB_db {
983 uint32_t md_pad; /**< also ksize for LEAF2 pages */
984 uint16_t md_flags; /**< @ref mdb_dbi_open */
985 uint16_t md_depth; /**< depth of this tree */
986 pgno_t md_branch_pages; /**< number of internal pages */
987 pgno_t md_leaf_pages; /**< number of leaf pages */
988 pgno_t md_overflow_pages; /**< number of overflow pages */
989 size_t md_entries; /**< number of data items */
990 pgno_t md_root; /**< the root page of this tree */
993 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
994 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
995 /** #mdb_dbi_open() flags */
996 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
997 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
999 /** Handle for the DB used to track free pages. */
1001 /** Handle for the default DB. */
1003 /** Number of DBs in metapage (free and main) - also hardcoded elsewhere */
1006 /** Number of meta pages - also hardcoded elsewhere */
1009 /** Meta page content.
1010 * A meta page is the start point for accessing a database snapshot.
1011 * Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
1013 typedef struct MDB_meta {
1014 /** Stamp identifying this as an LMDB file. It must be set
1017 /** Version number of this file. Must be set to #MDB_DATA_VERSION. */
1018 uint32_t mm_version;
1019 void *mm_address; /**< address for fixed mapping */
1020 size_t mm_mapsize; /**< size of mmap region */
1021 MDB_db mm_dbs[CORE_DBS]; /**< first is free space, 2nd is main db */
1022 /** The size of pages used in this DB */
1023 #define mm_psize mm_dbs[FREE_DBI].md_pad
1024 /** Any persistent environment flags. @ref mdb_env */
1025 #define mm_flags mm_dbs[FREE_DBI].md_flags
1026 /** Last used page in the datafile.
1027 * Actually the file may be shorter if the freeDB lists the final pages.
1030 volatile txnid_t mm_txnid; /**< txnid that committed this page */
1033 /** Buffer for a stack-allocated meta page.
1034 * The members define size and alignment, and silence type
1035 * aliasing warnings. They are not used directly; that could
1036 * mean incorrectly using several union members in parallel.
1038 typedef union MDB_metabuf {
1041 char mm_pad[PAGEHDRSZ];
1046 /** Auxiliary DB info.
1047 * The information here is mostly static/read-only. There is
1048 * only a single copy of this record in the environment.
1050 typedef struct MDB_dbx {
1051 MDB_val md_name; /**< name of the database */
1052 MDB_cmp_func *md_cmp; /**< function for comparing keys */
1053 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
1054 MDB_rel_func *md_rel; /**< user relocate function */
1055 void *md_relctx; /**< user-provided context for md_rel */
1058 /** A database transaction.
1059 * Every operation requires a transaction handle.
1062 MDB_txn *mt_parent; /**< parent of a nested txn */
1063 /** Nested txn under this txn, set together with flag #MDB_TXN_HAS_CHILD */
1065 pgno_t mt_next_pgno; /**< next unallocated page */
1066 /** The ID of this transaction. IDs are integers incrementing from 1.
1067 * Only committed write transactions increment the ID. If a transaction
1068 * aborts, the ID may be re-used by the next writer.
1071 MDB_env *mt_env; /**< the DB environment */
1072 /** The list of pages that became unused during this transaction.
1074 MDB_IDL mt_free_pgs;
1075 /** The list of loose pages that became unused and may be reused
1076 * in this transaction, linked through #NEXT_LOOSE_PAGE(page).
1078 MDB_page *mt_loose_pgs;
1079 /** Number of loose pages (#mt_loose_pgs) */
1081 /** The sorted list of dirty pages we temporarily wrote to disk
1082 * because the dirty list was full. page numbers in here are
1083 * shifted left by 1, deleted slots have the LSB set.
1085 MDB_IDL mt_spill_pgs;
1087 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
1088 MDB_ID2L dirty_list;
1089 /** For read txns: This thread/txn's reader table slot, or NULL. */
1092 /** Array of records for each DB known in the environment. */
1094 /** Array of MDB_db records for each known DB */
1096 /** Array of sequence numbers for each DB handle */
1097 unsigned int *mt_dbiseqs;
1098 /** @defgroup mt_dbflag Transaction DB Flags
1102 #define DB_DIRTY 0x01 /**< DB was written in this txn */
1103 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
1104 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
1105 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
1106 #define DB_USRVALID 0x10 /**< As #DB_VALID, but not set for #FREE_DBI */
1107 #define DB_DUPDATA 0x20 /**< DB is #MDB_DUPSORT data */
1109 /** In write txns, array of cursors for each DB */
1110 MDB_cursor **mt_cursors;
1111 /** Array of flags for each DB */
1112 unsigned char *mt_dbflags;
1113 /** Number of DB records in use, or 0 when the txn is finished.
1114 * This number only ever increments until the txn finishes; we
1115 * don't decrement it when individual DB handles are closed.
1119 /** @defgroup mdb_txn Transaction Flags
1123 /** #mdb_txn_begin() flags */
1124 #define MDB_TXN_BEGIN_FLAGS MDB_RDONLY
1125 #define MDB_TXN_RDONLY MDB_RDONLY /**< read-only transaction */
1126 /* internal txn flags */
1127 #define MDB_TXN_WRITEMAP MDB_WRITEMAP /**< copy of #MDB_env flag in writers */
1128 #define MDB_TXN_FINISHED 0x01 /**< txn is finished or never began */
1129 #define MDB_TXN_ERROR 0x02 /**< txn is unusable after an error */
1130 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
1131 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
1132 #define MDB_TXN_HAS_CHILD 0x10 /**< txn has an #MDB_txn.%mt_child */
1133 /** most operations on the txn are currently illegal */
1134 #define MDB_TXN_BLOCKED (MDB_TXN_FINISHED|MDB_TXN_ERROR|MDB_TXN_HAS_CHILD)
1136 unsigned int mt_flags; /**< @ref mdb_txn */
1137 /** #dirty_list room: Array size - \#dirty pages visible to this txn.
1138 * Includes ancestor txns' dirty pages not hidden by other txns'
1139 * dirty/spilled pages. Thus commit(nested txn) has room to merge
1140 * dirty_list into mt_parent after freeing hidden mt_parent pages.
1142 unsigned int mt_dirty_room;
1145 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
1146 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
1147 * raise this on a 64 bit machine.
1149 #define CURSOR_STACK 32
1153 /** Cursors are used for all DB operations.
1154 * A cursor holds a path of (page pointer, key index) from the DB
1155 * root to a position in the DB, plus other state. #MDB_DUPSORT
1156 * cursors include an xcursor to the current data item. Write txns
1157 * track their cursors and keep them up to date when data moves.
1158 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
1159 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
1162 /** Next cursor on this DB in this txn */
1163 MDB_cursor *mc_next;
1164 /** Backup of the original cursor if this cursor is a shadow */
1165 MDB_cursor *mc_backup;
1166 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
1167 struct MDB_xcursor *mc_xcursor;
1168 /** The transaction that owns this cursor */
1170 /** The database handle this cursor operates on */
1172 /** The database record for this cursor */
1174 /** The database auxiliary record for this cursor */
1176 /** The @ref mt_dbflag for this database */
1177 unsigned char *mc_dbflag;
1178 unsigned short mc_snum; /**< number of pushed pages */
1179 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
1180 /** @defgroup mdb_cursor Cursor Flags
1182 * Cursor state flags.
1185 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
1186 #define C_EOF 0x02 /**< No more data */
1187 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
1188 #define C_DEL 0x08 /**< last op was a cursor_del */
1189 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
1191 unsigned int mc_flags; /**< @ref mdb_cursor */
1192 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
1193 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
1196 /** Context for sorted-dup records.
1197 * We could have gone to a fully recursive design, with arbitrarily
1198 * deep nesting of sub-databases. But for now we only handle these
1199 * levels - main DB, optional sub-DB, sorted-duplicate DB.
1201 typedef struct MDB_xcursor {
1202 /** A sub-cursor for traversing the Dup DB */
1203 MDB_cursor mx_cursor;
1204 /** The database record for this Dup DB */
1206 /** The auxiliary DB record for this Dup DB */
1208 /** The @ref mt_dbflag for this Dup DB */
1209 unsigned char mx_dbflag;
1212 /** Check if there is an inited xcursor, so #XCURSOR_REFRESH() is proper */
1213 #define XCURSOR_INITED(mc) \
1214 ((mc)->mc_xcursor && ((mc)->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
1216 /** Update sub-page pointer, if any, in \b mc->mc_xcursor. Needed
1217 * when the node which contains the sub-page may have moved. Called
1218 * with \b mp = mc->mc_pg[mc->mc_top], \b ki = mc->mc_ki[mc->mc_top].
1220 #define XCURSOR_REFRESH(mc, mp, ki) do { \
1221 MDB_page *xr_pg = (mp); \
1222 MDB_node *xr_node = NODEPTR(xr_pg, ki); \
1223 if ((xr_node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) \
1224 (mc)->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(xr_node); \
1227 /** State of FreeDB old pages, stored in the MDB_env */
1228 typedef struct MDB_pgstate {
1229 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1230 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1233 /** The database environment. */
1235 HANDLE me_fd; /**< The main data file */
1236 HANDLE me_lfd; /**< The lock file */
1237 HANDLE me_mfd; /**< just for writing the meta pages */
1238 /** Failed to update the meta page. Probably an I/O error. */
1239 #define MDB_FATAL_ERROR 0x80000000U
1240 /** Some fields are initialized. */
1241 #define MDB_ENV_ACTIVE 0x20000000U
1242 /** me_txkey is set */
1243 #define MDB_ENV_TXKEY 0x10000000U
1244 /** fdatasync is unreliable */
1245 #define MDB_FSYNCONLY 0x08000000U
1246 uint32_t me_flags; /**< @ref mdb_env */
1247 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1248 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1249 unsigned int me_maxreaders; /**< size of the reader table */
1250 /** Max #MDB_txninfo.%mti_numreaders of interest to #mdb_env_close() */
1251 volatile int me_close_readers;
1252 MDB_dbi me_numdbs; /**< number of DBs opened */
1253 MDB_dbi me_maxdbs; /**< size of the DB table */
1254 MDB_PID_T me_pid; /**< process ID of this env */
1255 char *me_path; /**< path to the DB files */
1256 char *me_map; /**< the memory map of the data file */
1257 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1258 MDB_meta *me_metas[NUM_METAS]; /**< pointers to the two meta pages */
1259 void *me_pbuf; /**< scratch area for DUPSORT put() */
1260 MDB_txn *me_txn; /**< current write transaction */
1261 MDB_txn *me_txn0; /**< prealloc'd write transaction */
1262 size_t me_mapsize; /**< size of the data memory map */
1263 off_t me_size; /**< current file size */
1264 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1265 MDB_dbx *me_dbxs; /**< array of static DB info */
1266 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1267 unsigned int *me_dbiseqs; /**< array of dbi sequence numbers */
1268 pthread_key_t me_txkey; /**< thread-key for readers */
1269 txnid_t me_pgoldest; /**< ID of oldest reader last time we looked */
1270 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1271 # define me_pglast me_pgstate.mf_pglast
1272 # define me_pghead me_pgstate.mf_pghead
1273 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1274 /** IDL of pages that became unused in a write txn */
1275 MDB_IDL me_free_pgs;
1276 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1277 MDB_ID2L me_dirty_list;
1278 /** Max number of freelist items that can fit in a single overflow page */
1280 /** Max size of a node on a page */
1281 unsigned int me_nodemax;
1282 #if !(MDB_MAXKEYSIZE)
1283 unsigned int me_maxkey; /**< max size of a key */
1285 int me_live_reader; /**< have liveness lock in reader table */
1287 int me_pidquery; /**< Used in OpenProcess */
1289 #ifdef MDB_USE_POSIX_MUTEX /* Posix mutexes reside in shared mem */
1290 # define me_rmutex me_txns->mti_rmutex /**< Shared reader lock */
1291 # define me_wmutex me_txns->mti_wmutex /**< Shared writer lock */
1293 mdb_mutex_t me_rmutex;
1294 mdb_mutex_t me_wmutex;
1296 void *me_userctx; /**< User-settable context */
1297 MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
1300 /** Nested transaction */
1301 typedef struct MDB_ntxn {
1302 MDB_txn mnt_txn; /**< the transaction */
1303 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1306 /** max number of pages to commit in one writev() call */
1307 #define MDB_COMMIT_PAGES 64
1308 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1309 #undef MDB_COMMIT_PAGES
1310 #define MDB_COMMIT_PAGES IOV_MAX
1313 /** max bytes to write in one call */
1314 #define MAX_WRITE (0x40000000U >> (sizeof(ssize_t) == 4))
1316 /** Check \b txn and \b dbi arguments to a function */
1317 #define TXN_DBI_EXIST(txn, dbi, validity) \
1318 ((txn) && (dbi)<(txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & (validity)))
1320 /** Check for misused \b dbi handles */
1321 #define TXN_DBI_CHANGED(txn, dbi) \
1322 ((txn)->mt_dbiseqs[dbi] != (txn)->mt_env->me_dbiseqs[dbi])
1324 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1325 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1326 static int mdb_page_touch(MDB_cursor *mc);
1328 #define MDB_END_NAMES {"committed", "empty-commit", "abort", "reset", \
1329 "reset-tmp", "fail-begin", "fail-beginchild"}
1331 /* mdb_txn_end operation number, for logging */
1332 MDB_END_COMMITTED, MDB_END_EMPTY_COMMIT, MDB_END_ABORT, MDB_END_RESET,
1333 MDB_END_RESET_TMP, MDB_END_FAIL_BEGIN, MDB_END_FAIL_BEGINCHILD
1335 #define MDB_END_OPMASK 0x0F /**< mask for #mdb_txn_end() operation number */
1336 #define MDB_END_UPDATE 0x10 /**< update env state (DBIs) */
1337 #define MDB_END_FREE 0x20 /**< free txn unless it is #MDB_env.%me_txn0 */
1338 #define MDB_END_SLOT MDB_NOTLS /**< release any reader slot if #MDB_NOTLS */
1339 static void mdb_txn_end(MDB_txn *txn, unsigned mode);
1341 static int mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **mp, int *lvl);
1342 static int mdb_page_search_root(MDB_cursor *mc,
1343 MDB_val *key, int modify);
1344 #define MDB_PS_MODIFY 1
1345 #define MDB_PS_ROOTONLY 2
1346 #define MDB_PS_FIRST 4
1347 #define MDB_PS_LAST 8
1348 static int mdb_page_search(MDB_cursor *mc,
1349 MDB_val *key, int flags);
1350 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1352 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1353 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1354 pgno_t newpgno, unsigned int nflags);
1356 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1357 static MDB_meta *mdb_env_pick_meta(const MDB_env *env);
1358 static int mdb_env_write_meta(MDB_txn *txn);
1359 #ifdef MDB_USE_POSIX_MUTEX /* Drop unused excl arg */
1360 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1362 static void mdb_env_close0(MDB_env *env, int excl);
1364 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1365 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1366 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1367 static void mdb_node_del(MDB_cursor *mc, int ksize);
1368 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1369 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft);
1370 static int mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data);
1371 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1372 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1374 static int mdb_rebalance(MDB_cursor *mc);
1375 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1377 static void mdb_cursor_pop(MDB_cursor *mc);
1378 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1380 static int mdb_cursor_del0(MDB_cursor *mc);
1381 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
1382 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1383 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1384 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1385 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1387 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1388 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1390 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1391 static void mdb_xcursor_init0(MDB_cursor *mc);
1392 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1393 static void mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int force);
1395 static int mdb_drop0(MDB_cursor *mc, int subs);
1396 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1397 static int mdb_reader_check0(MDB_env *env, int rlocked, int *dead);
1400 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1403 /** Compare two items pointing at size_t's of unknown alignment. */
1404 #ifdef MISALIGNED_OK
1405 # define mdb_cmp_clong mdb_cmp_long
1407 # define mdb_cmp_clong mdb_cmp_cint
1411 static SECURITY_DESCRIPTOR mdb_null_sd;
1412 static SECURITY_ATTRIBUTES mdb_all_sa;
1413 static int mdb_sec_inited;
1415 static int utf8_to_utf16(const char *src, int srcsize, wchar_t **dst, int *dstsize);
1418 /** Return the library version info. */
1420 mdb_version(int *major, int *minor, int *patch)
1422 if (major) *major = MDB_VERSION_MAJOR;
1423 if (minor) *minor = MDB_VERSION_MINOR;
1424 if (patch) *patch = MDB_VERSION_PATCH;
1425 return MDB_VERSION_STRING;
1428 /** Table of descriptions for LMDB @ref errors */
1429 static char *const mdb_errstr[] = {
1430 "MDB_KEYEXIST: Key/data pair already exists",
1431 "MDB_NOTFOUND: No matching key/data pair found",
1432 "MDB_PAGE_NOTFOUND: Requested page not found",
1433 "MDB_CORRUPTED: Located page was wrong type",
1434 "MDB_PANIC: Update of meta page failed or environment had fatal error",
1435 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1436 "MDB_INVALID: File is not an LMDB file",
1437 "MDB_MAP_FULL: Environment mapsize limit reached",
1438 "MDB_DBS_FULL: Environment maxdbs limit reached",
1439 "MDB_READERS_FULL: Environment maxreaders limit reached",
1440 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1441 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1442 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1443 "MDB_PAGE_FULL: Internal error - page has no more space",
1444 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1445 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1446 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1447 "MDB_BAD_TXN: Transaction must abort, has a child, or is invalid",
1448 "MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
1449 "MDB_BAD_DBI: The specified DBI handle was closed/changed unexpectedly",
1453 mdb_strerror(int err)
1456 /** HACK: pad 4KB on stack over the buf. Return system msgs in buf.
1457 * This works as long as no function between the call to mdb_strerror
1458 * and the actual use of the message uses more than 4K of stack.
1460 #define MSGSIZE 1024
1461 #define PADSIZE 4096
1462 char buf[MSGSIZE+PADSIZE], *ptr = buf;
1466 return ("Successful return: 0");
1468 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1469 i = err - MDB_KEYEXIST;
1470 return mdb_errstr[i];
1474 /* These are the C-runtime error codes we use. The comment indicates
1475 * their numeric value, and the Win32 error they would correspond to
1476 * if the error actually came from a Win32 API. A major mess, we should
1477 * have used LMDB-specific error codes for everything.
1480 case ENOENT: /* 2, FILE_NOT_FOUND */
1481 case EIO: /* 5, ACCESS_DENIED */
1482 case ENOMEM: /* 12, INVALID_ACCESS */
1483 case EACCES: /* 13, INVALID_DATA */
1484 case EBUSY: /* 16, CURRENT_DIRECTORY */
1485 case EINVAL: /* 22, BAD_COMMAND */
1486 case ENOSPC: /* 28, OUT_OF_PAPER */
1487 return strerror(err);
1492 FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
1493 FORMAT_MESSAGE_IGNORE_INSERTS,
1494 NULL, err, 0, ptr, MSGSIZE, (va_list *)buf+MSGSIZE);
1497 return strerror(err);
1501 /** assert(3) variant in cursor context */
1502 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1503 /** assert(3) variant in transaction context */
1504 #define mdb_tassert(txn, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1505 /** assert(3) variant in environment context */
1506 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1509 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1510 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1513 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1514 const char *func, const char *file, int line)
1517 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1518 file, line, expr_txt, func);
1519 if (env->me_assert_func)
1520 env->me_assert_func(env, buf);
1521 fprintf(stderr, "%s\n", buf);
1525 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1529 /** Return the page number of \b mp which may be sub-page, for debug output */
1531 mdb_dbg_pgno(MDB_page *mp)
1534 COPY_PGNO(ret, mp->mp_pgno);
1538 /** Display a key in hexadecimal and return the address of the result.
1539 * @param[in] key the key to display
1540 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1541 * @return The key in hexadecimal form.
1544 mdb_dkey(MDB_val *key, char *buf)
1547 unsigned char *c = key->mv_data;
1553 if (key->mv_size > DKBUF_MAXKEYSIZE)
1554 return "MDB_MAXKEYSIZE";
1555 /* may want to make this a dynamic check: if the key is mostly
1556 * printable characters, print it as-is instead of converting to hex.
1560 for (i=0; i<key->mv_size; i++)
1561 ptr += sprintf(ptr, "%02x", *c++);
1563 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1569 mdb_leafnode_type(MDB_node *n)
1571 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1572 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1573 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1576 /** Display all the keys in the page. */
1578 mdb_page_list(MDB_page *mp)
1580 pgno_t pgno = mdb_dbg_pgno(mp);
1581 const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
1583 unsigned int i, nkeys, nsize, total = 0;
1587 switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1588 case P_BRANCH: type = "Branch page"; break;
1589 case P_LEAF: type = "Leaf page"; break;
1590 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1591 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1592 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1594 fprintf(stderr, "Overflow page %"Z"u pages %u%s\n",
1595 pgno, mp->mp_pages, state);
1598 fprintf(stderr, "Meta-page %"Z"u txnid %"Z"u\n",
1599 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1602 fprintf(stderr, "Bad page %"Z"u flags 0x%u\n", pgno, mp->mp_flags);
1606 nkeys = NUMKEYS(mp);
1607 fprintf(stderr, "%s %"Z"u numkeys %d%s\n", type, pgno, nkeys, state);
1609 for (i=0; i<nkeys; i++) {
1610 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1611 key.mv_size = nsize = mp->mp_pad;
1612 key.mv_data = LEAF2KEY(mp, i, nsize);
1614 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1617 node = NODEPTR(mp, i);
1618 key.mv_size = node->mn_ksize;
1619 key.mv_data = node->mn_data;
1620 nsize = NODESIZE + key.mv_size;
1621 if (IS_BRANCH(mp)) {
1622 fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
1626 if (F_ISSET(node->mn_flags, F_BIGDATA))
1627 nsize += sizeof(pgno_t);
1629 nsize += NODEDSZ(node);
1631 nsize += sizeof(indx_t);
1632 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1633 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1635 total = EVEN(total);
1637 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1638 IS_LEAF2(mp) ? PAGEHDRSZ : PAGEBASE + mp->mp_lower, total, SIZELEFT(mp));
1642 mdb_cursor_chk(MDB_cursor *mc)
1648 if (!mc->mc_snum || !(mc->mc_flags & C_INITIALIZED)) return;
1649 for (i=0; i<mc->mc_top; i++) {
1651 node = NODEPTR(mp, mc->mc_ki[i]);
1652 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1655 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1657 if (XCURSOR_INITED(mc)) {
1658 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
1659 if (((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) &&
1660 mc->mc_xcursor->mx_cursor.mc_pg[0] != NODEDATA(node)) {
1668 /** Count all the pages in each DB and in the freelist
1669 * and make sure it matches the actual number of pages
1671 * All named DBs must be open for a correct count.
1673 static void mdb_audit(MDB_txn *txn)
1677 MDB_ID freecount, count;
1682 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1683 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1684 freecount += *(MDB_ID *)data.mv_data;
1685 mdb_tassert(txn, rc == MDB_NOTFOUND);
1688 for (i = 0; i<txn->mt_numdbs; i++) {
1690 if (!(txn->mt_dbflags[i] & DB_VALID))
1692 mdb_cursor_init(&mc, txn, i, &mx);
1693 if (txn->mt_dbs[i].md_root == P_INVALID)
1695 count += txn->mt_dbs[i].md_branch_pages +
1696 txn->mt_dbs[i].md_leaf_pages +
1697 txn->mt_dbs[i].md_overflow_pages;
1698 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1699 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1700 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
1703 mp = mc.mc_pg[mc.mc_top];
1704 for (j=0; j<NUMKEYS(mp); j++) {
1705 MDB_node *leaf = NODEPTR(mp, j);
1706 if (leaf->mn_flags & F_SUBDATA) {
1708 memcpy(&db, NODEDATA(leaf), sizeof(db));
1709 count += db.md_branch_pages + db.md_leaf_pages +
1710 db.md_overflow_pages;
1714 mdb_tassert(txn, rc == MDB_NOTFOUND);
1717 if (freecount + count + NUM_METAS != txn->mt_next_pgno) {
1718 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1719 txn->mt_txnid, freecount, count+NUM_METAS,
1720 freecount+count+NUM_METAS, txn->mt_next_pgno);
1726 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1728 return txn->mt_dbxs[dbi].md_cmp(a, b);
1732 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1734 MDB_cmp_func *dcmp = txn->mt_dbxs[dbi].md_dcmp;
1735 #if UINT_MAX < SIZE_MAX
1736 if (dcmp == mdb_cmp_int && a->mv_size == sizeof(size_t))
1737 dcmp = mdb_cmp_clong;
1742 /** Allocate memory for a page.
1743 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1746 mdb_page_malloc(MDB_txn *txn, unsigned num)
1748 MDB_env *env = txn->mt_env;
1749 MDB_page *ret = env->me_dpages;
1750 size_t psize = env->me_psize, sz = psize, off;
1751 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1752 * For a single page alloc, we init everything after the page header.
1753 * For multi-page, we init the final page; if the caller needed that
1754 * many pages they will be filling in at least up to the last page.
1758 VGMEMP_ALLOC(env, ret, sz);
1759 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1760 env->me_dpages = ret->mp_next;
1763 psize -= off = PAGEHDRSZ;
1768 if ((ret = malloc(sz)) != NULL) {
1769 VGMEMP_ALLOC(env, ret, sz);
1770 if (!(env->me_flags & MDB_NOMEMINIT)) {
1771 memset((char *)ret + off, 0, psize);
1775 txn->mt_flags |= MDB_TXN_ERROR;
1779 /** Free a single page.
1780 * Saves single pages to a list, for future reuse.
1781 * (This is not used for multi-page overflow pages.)
1784 mdb_page_free(MDB_env *env, MDB_page *mp)
1786 mp->mp_next = env->me_dpages;
1787 VGMEMP_FREE(env, mp);
1788 env->me_dpages = mp;
1791 /** Free a dirty page */
1793 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1795 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1796 mdb_page_free(env, dp);
1798 /* large pages just get freed directly */
1799 VGMEMP_FREE(env, dp);
1804 /** Return all dirty pages to dpage list */
1806 mdb_dlist_free(MDB_txn *txn)
1808 MDB_env *env = txn->mt_env;
1809 MDB_ID2L dl = txn->mt_u.dirty_list;
1810 unsigned i, n = dl[0].mid;
1812 for (i = 1; i <= n; i++) {
1813 mdb_dpage_free(env, dl[i].mptr);
1818 /** Loosen or free a single page.
1819 * Saves single pages to a list for future reuse
1820 * in this same txn. It has been pulled from the freeDB
1821 * and already resides on the dirty list, but has been
1822 * deleted. Use these pages first before pulling again
1825 * If the page wasn't dirtied in this txn, just add it
1826 * to this txn's free list.
1829 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
1832 pgno_t pgno = mp->mp_pgno;
1833 MDB_txn *txn = mc->mc_txn;
1835 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
1836 if (txn->mt_parent) {
1837 MDB_ID2 *dl = txn->mt_u.dirty_list;
1838 /* If txn has a parent, make sure the page is in our
1842 unsigned x = mdb_mid2l_search(dl, pgno);
1843 if (x <= dl[0].mid && dl[x].mid == pgno) {
1844 if (mp != dl[x].mptr) { /* bad cursor? */
1845 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1846 txn->mt_flags |= MDB_TXN_ERROR;
1847 return MDB_CORRUPTED;
1854 /* no parent txn, so it's just ours */
1859 DPRINTF(("loosen db %d page %"Z"u", DDBI(mc),
1861 NEXT_LOOSE_PAGE(mp) = txn->mt_loose_pgs;
1862 txn->mt_loose_pgs = mp;
1863 txn->mt_loose_count++;
1864 mp->mp_flags |= P_LOOSE;
1866 int rc = mdb_midl_append(&txn->mt_free_pgs, pgno);
1874 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
1875 * @param[in] mc A cursor handle for the current operation.
1876 * @param[in] pflags Flags of the pages to update:
1877 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1878 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
1879 * @return 0 on success, non-zero on failure.
1882 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
1884 enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
1885 MDB_txn *txn = mc->mc_txn;
1886 MDB_cursor *m3, *m0 = mc;
1891 int rc = MDB_SUCCESS, level;
1893 /* Mark pages seen by cursors */
1894 if (mc->mc_flags & C_UNTRACK)
1895 mc = NULL; /* will find mc in mt_cursors */
1896 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1897 for (; mc; mc=mc->mc_next) {
1898 if (!(mc->mc_flags & C_INITIALIZED))
1900 for (m3 = mc;; m3 = &mx->mx_cursor) {
1902 for (j=0; j<m3->mc_snum; j++) {
1904 if ((mp->mp_flags & Mask) == pflags)
1905 mp->mp_flags ^= P_KEEP;
1907 mx = m3->mc_xcursor;
1908 /* Proceed to mx if it is at a sub-database */
1909 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
1911 if (! (mp && (mp->mp_flags & P_LEAF)))
1913 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
1914 if (!(leaf->mn_flags & F_SUBDATA))
1923 /* Mark dirty root pages */
1924 for (i=0; i<txn->mt_numdbs; i++) {
1925 if (txn->mt_dbflags[i] & DB_DIRTY) {
1926 pgno_t pgno = txn->mt_dbs[i].md_root;
1927 if (pgno == P_INVALID)
1929 if ((rc = mdb_page_get(m0, pgno, &dp, &level)) != MDB_SUCCESS)
1931 if ((dp->mp_flags & Mask) == pflags && level <= 1)
1932 dp->mp_flags ^= P_KEEP;
1940 static int mdb_page_flush(MDB_txn *txn, int keep);
1942 /** Spill pages from the dirty list back to disk.
1943 * This is intended to prevent running into #MDB_TXN_FULL situations,
1944 * but note that they may still occur in a few cases:
1945 * 1) our estimate of the txn size could be too small. Currently this
1946 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
1947 * 2) child txns may run out of space if their parents dirtied a
1948 * lot of pages and never spilled them. TODO: we probably should do
1949 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1950 * the parent's dirty_room is below a given threshold.
1952 * Otherwise, if not using nested txns, it is expected that apps will
1953 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1954 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1955 * If the txn never references them again, they can be left alone.
1956 * If the txn only reads them, they can be used without any fuss.
1957 * If the txn writes them again, they can be dirtied immediately without
1958 * going thru all of the work of #mdb_page_touch(). Such references are
1959 * handled by #mdb_page_unspill().
1961 * Also note, we never spill DB root pages, nor pages of active cursors,
1962 * because we'll need these back again soon anyway. And in nested txns,
1963 * we can't spill a page in a child txn if it was already spilled in a
1964 * parent txn. That would alter the parent txns' data even though
1965 * the child hasn't committed yet, and we'd have no way to undo it if
1966 * the child aborted.
1968 * @param[in] m0 cursor A cursor handle identifying the transaction and
1969 * database for which we are checking space.
1970 * @param[in] key For a put operation, the key being stored.
1971 * @param[in] data For a put operation, the data being stored.
1972 * @return 0 on success, non-zero on failure.
1975 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1977 MDB_txn *txn = m0->mc_txn;
1979 MDB_ID2L dl = txn->mt_u.dirty_list;
1980 unsigned int i, j, need;
1983 if (m0->mc_flags & C_SUB)
1986 /* Estimate how much space this op will take */
1987 i = m0->mc_db->md_depth;
1988 /* Named DBs also dirty the main DB */
1989 if (m0->mc_dbi >= CORE_DBS)
1990 i += txn->mt_dbs[MAIN_DBI].md_depth;
1991 /* For puts, roughly factor in the key+data size */
1993 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
1994 i += i; /* double it for good measure */
1997 if (txn->mt_dirty_room > i)
2000 if (!txn->mt_spill_pgs) {
2001 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
2002 if (!txn->mt_spill_pgs)
2005 /* purge deleted slots */
2006 MDB_IDL sl = txn->mt_spill_pgs;
2007 unsigned int num = sl[0];
2009 for (i=1; i<=num; i++) {
2016 /* Preserve pages which may soon be dirtied again */
2017 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
2020 /* Less aggressive spill - we originally spilled the entire dirty list,
2021 * with a few exceptions for cursor pages and DB root pages. But this
2022 * turns out to be a lot of wasted effort because in a large txn many
2023 * of those pages will need to be used again. So now we spill only 1/8th
2024 * of the dirty pages. Testing revealed this to be a good tradeoff,
2025 * better than 1/2, 1/4, or 1/10.
2027 if (need < MDB_IDL_UM_MAX / 8)
2028 need = MDB_IDL_UM_MAX / 8;
2030 /* Save the page IDs of all the pages we're flushing */
2031 /* flush from the tail forward, this saves a lot of shifting later on. */
2032 for (i=dl[0].mid; i && need; i--) {
2033 MDB_ID pn = dl[i].mid << 1;
2035 if (dp->mp_flags & (P_LOOSE|P_KEEP))
2037 /* Can't spill twice, make sure it's not already in a parent's
2040 if (txn->mt_parent) {
2042 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
2043 if (tx2->mt_spill_pgs) {
2044 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
2045 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
2046 dp->mp_flags |= P_KEEP;
2054 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
2058 mdb_midl_sort(txn->mt_spill_pgs);
2060 /* Flush the spilled part of dirty list */
2061 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
2064 /* Reset any dirty pages we kept that page_flush didn't see */
2065 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
2068 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
2072 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
2074 mdb_find_oldest(MDB_txn *txn)
2077 txnid_t mr, oldest = txn->mt_txnid - 1;
2078 if (txn->mt_env->me_txns) {
2079 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
2080 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
2091 /** Add a page to the txn's dirty list */
2093 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
2096 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
2098 if (txn->mt_flags & MDB_TXN_WRITEMAP) {
2099 insert = mdb_mid2l_append;
2101 insert = mdb_mid2l_insert;
2103 mid.mid = mp->mp_pgno;
2105 rc = insert(txn->mt_u.dirty_list, &mid);
2106 mdb_tassert(txn, rc == 0);
2107 txn->mt_dirty_room--;
2110 /** Allocate page numbers and memory for writing. Maintain me_pglast,
2111 * me_pghead and mt_next_pgno.
2113 * If there are free pages available from older transactions, they
2114 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
2115 * Do not modify the freedB, just merge freeDB records into me_pghead[]
2116 * and move me_pglast to say which records were consumed. Only this
2117 * function can create me_pghead and move me_pglast/mt_next_pgno.
2118 * @param[in] mc cursor A cursor handle identifying the transaction and
2119 * database for which we are allocating.
2120 * @param[in] num the number of pages to allocate.
2121 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
2122 * will always be satisfied by a single contiguous chunk of memory.
2123 * @return 0 on success, non-zero on failure.
2126 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
2128 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
2129 /* Get at most <Max_retries> more freeDB records once me_pghead
2130 * has enough pages. If not enough, use new pages from the map.
2131 * If <Paranoid> and mc is updating the freeDB, only get new
2132 * records if me_pghead is empty. Then the freelist cannot play
2133 * catch-up with itself by growing while trying to save it.
2135 enum { Paranoid = 1, Max_retries = 500 };
2137 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
2139 int rc, retry = num * 60;
2140 MDB_txn *txn = mc->mc_txn;
2141 MDB_env *env = txn->mt_env;
2142 pgno_t pgno, *mop = env->me_pghead;
2143 unsigned i, j, mop_len = mop ? mop[0] : 0, n2 = num-1;
2145 txnid_t oldest = 0, last;
2150 /* If there are any loose pages, just use them */
2151 if (num == 1 && txn->mt_loose_pgs) {
2152 np = txn->mt_loose_pgs;
2153 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
2154 txn->mt_loose_count--;
2155 DPRINTF(("db %d use loose page %"Z"u", DDBI(mc),
2163 /* If our dirty list is already full, we can't do anything */
2164 if (txn->mt_dirty_room == 0) {
2169 for (op = MDB_FIRST;; op = MDB_NEXT) {
2174 /* Seek a big enough contiguous page range. Prefer
2175 * pages at the tail, just truncating the list.
2181 if (mop[i-n2] == pgno+n2)
2188 if (op == MDB_FIRST) { /* 1st iteration */
2189 /* Prepare to fetch more and coalesce */
2190 last = env->me_pglast;
2191 oldest = env->me_pgoldest;
2192 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
2195 key.mv_data = &last; /* will look up last+1 */
2196 key.mv_size = sizeof(last);
2198 if (Paranoid && mc->mc_dbi == FREE_DBI)
2201 if (Paranoid && retry < 0 && mop_len)
2205 /* Do not fetch more if the record will be too recent */
2206 if (oldest <= last) {
2208 oldest = mdb_find_oldest(txn);
2209 env->me_pgoldest = oldest;
2215 rc = mdb_cursor_get(&m2, &key, NULL, op);
2217 if (rc == MDB_NOTFOUND)
2221 last = *(txnid_t*)key.mv_data;
2222 if (oldest <= last) {
2224 oldest = mdb_find_oldest(txn);
2225 env->me_pgoldest = oldest;
2231 np = m2.mc_pg[m2.mc_top];
2232 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
2233 if ((rc = mdb_node_read(&m2, leaf, &data)) != MDB_SUCCESS)
2236 idl = (MDB_ID *) data.mv_data;
2239 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
2244 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
2246 mop = env->me_pghead;
2248 env->me_pglast = last;
2250 DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
2251 last, txn->mt_dbs[FREE_DBI].md_root, i));
2253 DPRINTF(("IDL %"Z"u", idl[j]));
2255 /* Merge in descending sorted order */
2256 mdb_midl_xmerge(mop, idl);
2260 /* Use new pages from the map when nothing suitable in the freeDB */
2262 pgno = txn->mt_next_pgno;
2263 if (pgno + num >= env->me_maxpg) {
2264 DPUTS("DB size maxed out");
2270 if (env->me_flags & MDB_WRITEMAP) {
2271 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
2273 if (!(np = mdb_page_malloc(txn, num))) {
2279 mop[0] = mop_len -= num;
2280 /* Move any stragglers down */
2281 for (j = i-num; j < mop_len; )
2282 mop[++j] = mop[++i];
2284 txn->mt_next_pgno = pgno + num;
2287 mdb_page_dirty(txn, np);
2293 txn->mt_flags |= MDB_TXN_ERROR;
2297 /** Copy the used portions of a non-overflow page.
2298 * @param[in] dst page to copy into
2299 * @param[in] src page to copy from
2300 * @param[in] psize size of a page
2303 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2305 enum { Align = sizeof(pgno_t) };
2306 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2308 /* If page isn't full, just copy the used portion. Adjust
2309 * alignment so memcpy may copy words instead of bytes.
2311 if ((unused &= -Align) && !IS_LEAF2(src)) {
2312 upper = (upper + PAGEBASE) & -Align;
2313 memcpy(dst, src, (lower + PAGEBASE + (Align-1)) & -Align);
2314 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2317 memcpy(dst, src, psize - unused);
2321 /** Pull a page off the txn's spill list, if present.
2322 * If a page being referenced was spilled to disk in this txn, bring
2323 * it back and make it dirty/writable again.
2324 * @param[in] txn the transaction handle.
2325 * @param[in] mp the page being referenced. It must not be dirty.
2326 * @param[out] ret the writable page, if any. ret is unchanged if
2327 * mp wasn't spilled.
2330 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2332 MDB_env *env = txn->mt_env;
2335 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2337 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2338 if (!tx2->mt_spill_pgs)
2340 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2341 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2344 if (txn->mt_dirty_room == 0)
2345 return MDB_TXN_FULL;
2346 if (IS_OVERFLOW(mp))
2350 if (env->me_flags & MDB_WRITEMAP) {
2353 np = mdb_page_malloc(txn, num);
2357 memcpy(np, mp, num * env->me_psize);
2359 mdb_page_copy(np, mp, env->me_psize);
2362 /* If in current txn, this page is no longer spilled.
2363 * If it happens to be the last page, truncate the spill list.
2364 * Otherwise mark it as deleted by setting the LSB.
2366 if (x == txn->mt_spill_pgs[0])
2367 txn->mt_spill_pgs[0]--;
2369 txn->mt_spill_pgs[x] |= 1;
2370 } /* otherwise, if belonging to a parent txn, the
2371 * page remains spilled until child commits
2374 mdb_page_dirty(txn, np);
2375 np->mp_flags |= P_DIRTY;
2383 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2384 * @param[in] mc cursor pointing to the page to be touched
2385 * @return 0 on success, non-zero on failure.
2388 mdb_page_touch(MDB_cursor *mc)
2390 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2391 MDB_txn *txn = mc->mc_txn;
2392 MDB_cursor *m2, *m3;
2396 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2397 if (txn->mt_flags & MDB_TXN_SPILLS) {
2399 rc = mdb_page_unspill(txn, mp, &np);
2405 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2406 (rc = mdb_page_alloc(mc, 1, &np)))
2409 DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
2410 mp->mp_pgno, pgno));
2411 mdb_cassert(mc, mp->mp_pgno != pgno);
2412 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2413 /* Update the parent page, if any, to point to the new page */
2415 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2416 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2417 SETPGNO(node, pgno);
2419 mc->mc_db->md_root = pgno;
2421 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2422 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2424 /* If txn has a parent, make sure the page is in our
2428 unsigned x = mdb_mid2l_search(dl, pgno);
2429 if (x <= dl[0].mid && dl[x].mid == pgno) {
2430 if (mp != dl[x].mptr) { /* bad cursor? */
2431 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2432 txn->mt_flags |= MDB_TXN_ERROR;
2433 return MDB_CORRUPTED;
2438 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2440 np = mdb_page_malloc(txn, 1);
2445 rc = mdb_mid2l_insert(dl, &mid);
2446 mdb_cassert(mc, rc == 0);
2451 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2453 np->mp_flags |= P_DIRTY;
2456 /* Adjust cursors pointing to mp */
2457 mc->mc_pg[mc->mc_top] = np;
2458 m2 = txn->mt_cursors[mc->mc_dbi];
2459 if (mc->mc_flags & C_SUB) {
2460 for (; m2; m2=m2->mc_next) {
2461 m3 = &m2->mc_xcursor->mx_cursor;
2462 if (m3->mc_snum < mc->mc_snum) continue;
2463 if (m3->mc_pg[mc->mc_top] == mp)
2464 m3->mc_pg[mc->mc_top] = np;
2467 for (; m2; m2=m2->mc_next) {
2468 if (m2->mc_snum < mc->mc_snum) continue;
2469 if (m2 == mc) continue;
2470 if (m2->mc_pg[mc->mc_top] == mp) {
2471 m2->mc_pg[mc->mc_top] = np;
2472 if (XCURSOR_INITED(m2) && IS_LEAF(np))
2473 XCURSOR_REFRESH(m2, np, m2->mc_ki[mc->mc_top]);
2480 txn->mt_flags |= MDB_TXN_ERROR;
2485 mdb_env_sync(MDB_env *env, int force)
2488 if (env->me_flags & MDB_RDONLY)
2490 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2491 if (env->me_flags & MDB_WRITEMAP) {
2492 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2493 ? MS_ASYNC : MS_SYNC;
2494 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
2497 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2501 #ifdef BROKEN_FDATASYNC
2502 if (env->me_flags & MDB_FSYNCONLY) {
2503 if (fsync(env->me_fd))
2507 if (MDB_FDATASYNC(env->me_fd))
2514 /** Back up parent txn's cursors, then grab the originals for tracking */
2516 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2518 MDB_cursor *mc, *bk;
2523 for (i = src->mt_numdbs; --i >= 0; ) {
2524 if ((mc = src->mt_cursors[i]) != NULL) {
2525 size = sizeof(MDB_cursor);
2527 size += sizeof(MDB_xcursor);
2528 for (; mc; mc = bk->mc_next) {
2534 mc->mc_db = &dst->mt_dbs[i];
2535 /* Kill pointers into src to reduce abuse: The
2536 * user may not use mc until dst ends. But we need a valid
2537 * txn pointer here for cursor fixups to keep working.
2540 mc->mc_dbflag = &dst->mt_dbflags[i];
2541 if ((mx = mc->mc_xcursor) != NULL) {
2542 *(MDB_xcursor *)(bk+1) = *mx;
2543 mx->mx_cursor.mc_txn = dst;
2545 mc->mc_next = dst->mt_cursors[i];
2546 dst->mt_cursors[i] = mc;
2553 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2554 * @param[in] txn the transaction handle.
2555 * @param[in] merge true to keep changes to parent cursors, false to revert.
2556 * @return 0 on success, non-zero on failure.
2559 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2561 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2565 for (i = txn->mt_numdbs; --i >= 0; ) {
2566 for (mc = cursors[i]; mc; mc = next) {
2568 if ((bk = mc->mc_backup) != NULL) {
2570 /* Commit changes to parent txn */
2571 mc->mc_next = bk->mc_next;
2572 mc->mc_backup = bk->mc_backup;
2573 mc->mc_txn = bk->mc_txn;
2574 mc->mc_db = bk->mc_db;
2575 mc->mc_dbflag = bk->mc_dbflag;
2576 if ((mx = mc->mc_xcursor) != NULL)
2577 mx->mx_cursor.mc_txn = bk->mc_txn;
2579 /* Abort nested txn */
2581 if ((mx = mc->mc_xcursor) != NULL)
2582 *mx = *(MDB_xcursor *)(bk+1);
2586 /* Only malloced cursors are permanently tracked. */
2593 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2599 Pidset = F_SETLK, Pidcheck = F_GETLK
2603 /** Set or check a pid lock. Set returns 0 on success.
2604 * Check returns 0 if the process is certainly dead, nonzero if it may
2605 * be alive (the lock exists or an error happened so we do not know).
2607 * On Windows Pidset is a no-op, we merely check for the existence
2608 * of the process with the given pid. On POSIX we use a single byte
2609 * lock on the lockfile, set at an offset equal to the pid.
2612 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2614 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2617 if (op == Pidcheck) {
2618 h = OpenProcess(env->me_pidquery, FALSE, pid);
2619 /* No documented "no such process" code, but other program use this: */
2621 return ErrCode() != ERROR_INVALID_PARAMETER;
2622 /* A process exists until all handles to it close. Has it exited? */
2623 ret = WaitForSingleObject(h, 0) != 0;
2630 struct flock lock_info;
2631 memset(&lock_info, 0, sizeof(lock_info));
2632 lock_info.l_type = F_WRLCK;
2633 lock_info.l_whence = SEEK_SET;
2634 lock_info.l_start = pid;
2635 lock_info.l_len = 1;
2636 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2637 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2639 } else if ((rc = ErrCode()) == EINTR) {
2647 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2648 * @param[in] txn the transaction handle to initialize
2649 * @return 0 on success, non-zero on failure.
2652 mdb_txn_renew0(MDB_txn *txn)
2654 MDB_env *env = txn->mt_env;
2655 MDB_txninfo *ti = env->me_txns;
2657 unsigned int i, nr, flags = txn->mt_flags;
2659 int rc, new_notls = 0;
2661 if ((flags &= MDB_TXN_RDONLY) != 0) {
2663 meta = mdb_env_pick_meta(env);
2664 txn->mt_txnid = meta->mm_txnid;
2665 txn->mt_u.reader = NULL;
2667 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2668 pthread_getspecific(env->me_txkey);
2670 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2671 return MDB_BAD_RSLOT;
2673 MDB_PID_T pid = env->me_pid;
2674 MDB_THR_T tid = pthread_self();
2675 mdb_mutexref_t rmutex = env->me_rmutex;
2677 if (!env->me_live_reader) {
2678 rc = mdb_reader_pid(env, Pidset, pid);
2681 env->me_live_reader = 1;
2684 if (LOCK_MUTEX(rc, env, rmutex))
2686 nr = ti->mti_numreaders;
2687 for (i=0; i<nr; i++)
2688 if (ti->mti_readers[i].mr_pid == 0)
2690 if (i == env->me_maxreaders) {
2691 UNLOCK_MUTEX(rmutex);
2692 return MDB_READERS_FULL;
2694 r = &ti->mti_readers[i];
2695 /* Claim the reader slot, carefully since other code
2696 * uses the reader table un-mutexed: First reset the
2697 * slot, next publish it in mti_numreaders. After
2698 * that, it is safe for mdb_env_close() to touch it.
2699 * When it will be closed, we can finally claim it.
2702 r->mr_txnid = (txnid_t)-1;
2705 ti->mti_numreaders = ++nr;
2706 env->me_close_readers = nr;
2708 UNLOCK_MUTEX(rmutex);
2710 new_notls = (env->me_flags & MDB_NOTLS);
2711 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2716 do /* LY: Retry on a race, ITS#7970. */
2717 r->mr_txnid = ti->mti_txnid;
2718 while(r->mr_txnid != ti->mti_txnid);
2719 txn->mt_txnid = r->mr_txnid;
2720 txn->mt_u.reader = r;
2721 meta = env->me_metas[txn->mt_txnid & 1];
2725 /* Not yet touching txn == env->me_txn0, it may be active */
2727 if (LOCK_MUTEX(rc, env, env->me_wmutex))
2729 txn->mt_txnid = ti->mti_txnid;
2730 meta = env->me_metas[txn->mt_txnid & 1];
2732 meta = mdb_env_pick_meta(env);
2733 txn->mt_txnid = meta->mm_txnid;
2737 if (txn->mt_txnid == mdb_debug_start)
2740 txn->mt_child = NULL;
2741 txn->mt_loose_pgs = NULL;
2742 txn->mt_loose_count = 0;
2743 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2744 txn->mt_u.dirty_list = env->me_dirty_list;
2745 txn->mt_u.dirty_list[0].mid = 0;
2746 txn->mt_free_pgs = env->me_free_pgs;
2747 txn->mt_free_pgs[0] = 0;
2748 txn->mt_spill_pgs = NULL;
2750 memcpy(txn->mt_dbiseqs, env->me_dbiseqs, env->me_maxdbs * sizeof(unsigned int));
2753 /* Copy the DB info and flags */
2754 memcpy(txn->mt_dbs, meta->mm_dbs, CORE_DBS * sizeof(MDB_db));
2756 /* Moved to here to avoid a data race in read TXNs */
2757 txn->mt_next_pgno = meta->mm_last_pg+1;
2759 txn->mt_flags = flags;
2762 txn->mt_numdbs = env->me_numdbs;
2763 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
2764 x = env->me_dbflags[i];
2765 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2766 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_USRVALID|DB_STALE : 0;
2768 txn->mt_dbflags[MAIN_DBI] = DB_VALID|DB_USRVALID;
2769 txn->mt_dbflags[FREE_DBI] = DB_VALID;
2771 if (env->me_flags & MDB_FATAL_ERROR) {
2772 DPUTS("environment had fatal error, must shutdown!");
2774 } else if (env->me_maxpg < txn->mt_next_pgno) {
2775 rc = MDB_MAP_RESIZED;
2779 mdb_txn_end(txn, new_notls /*0 or MDB_END_SLOT*/ | MDB_END_FAIL_BEGIN);
2784 mdb_txn_renew(MDB_txn *txn)
2788 if (!txn || !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY|MDB_TXN_FINISHED))
2791 rc = mdb_txn_renew0(txn);
2792 if (rc == MDB_SUCCESS) {
2793 DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2794 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2795 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2801 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2805 int rc, size, tsize;
2807 flags &= MDB_TXN_BEGIN_FLAGS;
2808 flags |= env->me_flags & MDB_WRITEMAP;
2810 if (env->me_flags & MDB_RDONLY & ~flags) /* write txn in RDONLY env */
2814 /* Nested transactions: Max 1 child, write txns only, no writemap */
2815 flags |= parent->mt_flags;
2816 if (flags & (MDB_RDONLY|MDB_WRITEMAP|MDB_TXN_BLOCKED)) {
2817 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
2819 /* Child txns save MDB_pgstate and use own copy of cursors */
2820 size = env->me_maxdbs * (sizeof(MDB_db)+sizeof(MDB_cursor *)+1);
2821 size += tsize = sizeof(MDB_ntxn);
2822 } else if (flags & MDB_RDONLY) {
2823 size = env->me_maxdbs * (sizeof(MDB_db)+1);
2824 size += tsize = sizeof(MDB_txn);
2826 /* Reuse preallocated write txn. However, do not touch it until
2827 * mdb_txn_renew0() succeeds, since it currently may be active.
2832 if ((txn = calloc(1, size)) == NULL) {
2833 DPRINTF(("calloc: %s", strerror(errno)));
2836 txn->mt_dbxs = env->me_dbxs; /* static */
2837 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2838 txn->mt_dbflags = (unsigned char *)txn + size - env->me_maxdbs;
2839 txn->mt_flags = flags;
2844 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2845 txn->mt_dbiseqs = parent->mt_dbiseqs;
2846 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2847 if (!txn->mt_u.dirty_list ||
2848 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2850 free(txn->mt_u.dirty_list);
2854 txn->mt_txnid = parent->mt_txnid;
2855 txn->mt_dirty_room = parent->mt_dirty_room;
2856 txn->mt_u.dirty_list[0].mid = 0;
2857 txn->mt_spill_pgs = NULL;
2858 txn->mt_next_pgno = parent->mt_next_pgno;
2859 parent->mt_flags |= MDB_TXN_HAS_CHILD;
2860 parent->mt_child = txn;
2861 txn->mt_parent = parent;
2862 txn->mt_numdbs = parent->mt_numdbs;
2863 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2864 /* Copy parent's mt_dbflags, but clear DB_NEW */
2865 for (i=0; i<txn->mt_numdbs; i++)
2866 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2868 ntxn = (MDB_ntxn *)txn;
2869 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2870 if (env->me_pghead) {
2871 size = MDB_IDL_SIZEOF(env->me_pghead);
2872 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2874 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2879 rc = mdb_cursor_shadow(parent, txn);
2881 mdb_txn_end(txn, MDB_END_FAIL_BEGINCHILD);
2882 } else { /* MDB_RDONLY */
2883 txn->mt_dbiseqs = env->me_dbiseqs;
2885 rc = mdb_txn_renew0(txn);
2888 if (txn != env->me_txn0)
2891 txn->mt_flags |= flags; /* could not change txn=me_txn0 earlier */
2893 DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2894 txn->mt_txnid, (flags & MDB_RDONLY) ? 'r' : 'w',
2895 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
2902 mdb_txn_env(MDB_txn *txn)
2904 if(!txn) return NULL;
2909 mdb_txn_id(MDB_txn *txn)
2912 return txn->mt_txnid;
2915 /** Export or close DBI handles opened in this txn. */
2917 mdb_dbis_update(MDB_txn *txn, int keep)
2920 MDB_dbi n = txn->mt_numdbs;
2921 MDB_env *env = txn->mt_env;
2922 unsigned char *tdbflags = txn->mt_dbflags;
2924 for (i = n; --i >= CORE_DBS;) {
2925 if (tdbflags[i] & DB_NEW) {
2927 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2929 char *ptr = env->me_dbxs[i].md_name.mv_data;
2931 env->me_dbxs[i].md_name.mv_data = NULL;
2932 env->me_dbxs[i].md_name.mv_size = 0;
2933 env->me_dbflags[i] = 0;
2934 env->me_dbiseqs[i]++;
2940 if (keep && env->me_numdbs < n)
2944 /** End a transaction, except successful commit of a nested transaction.
2945 * May be called twice for readonly txns: First reset it, then abort.
2946 * @param[in] txn the transaction handle to end
2947 * @param[in] mode why and how to end the transaction
2950 mdb_txn_end(MDB_txn *txn, unsigned mode)
2952 MDB_env *env = txn->mt_env;
2954 static const char *const names[] = MDB_END_NAMES;
2957 /* Export or close DBI handles opened in this txn */
2958 mdb_dbis_update(txn, mode & MDB_END_UPDATE);
2960 DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2961 names[mode & MDB_END_OPMASK],
2962 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2963 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
2965 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2966 if (txn->mt_u.reader) {
2967 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2968 if (!(env->me_flags & MDB_NOTLS)) {
2969 txn->mt_u.reader = NULL; /* txn does not own reader */
2970 } else if (mode & MDB_END_SLOT) {
2971 txn->mt_u.reader->mr_pid = 0;
2972 txn->mt_u.reader = NULL;
2973 } /* else txn owns the slot until it does MDB_END_SLOT */
2975 txn->mt_numdbs = 0; /* prevent further DBI activity */
2976 txn->mt_flags |= MDB_TXN_FINISHED;
2978 } else if (!F_ISSET(txn->mt_flags, MDB_TXN_FINISHED)) {
2979 pgno_t *pghead = env->me_pghead;
2981 if (!(mode & MDB_END_UPDATE)) /* !(already closed cursors) */
2982 mdb_cursors_close(txn, 0);
2983 if (!(env->me_flags & MDB_WRITEMAP)) {
2984 mdb_dlist_free(txn);
2988 txn->mt_flags = MDB_TXN_FINISHED;
2990 if (!txn->mt_parent) {
2991 mdb_midl_shrink(&txn->mt_free_pgs);
2992 env->me_free_pgs = txn->mt_free_pgs;
2994 env->me_pghead = NULL;
2998 mode = 0; /* txn == env->me_txn0, do not free() it */
3000 /* The writer mutex was locked in mdb_txn_begin. */
3002 UNLOCK_MUTEX(env->me_wmutex);
3004 txn->mt_parent->mt_child = NULL;
3005 txn->mt_parent->mt_flags &= ~MDB_TXN_HAS_CHILD;
3006 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
3007 mdb_midl_free(txn->mt_free_pgs);
3008 mdb_midl_free(txn->mt_spill_pgs);
3009 free(txn->mt_u.dirty_list);
3012 mdb_midl_free(pghead);
3015 if (mode & MDB_END_FREE)
3020 mdb_txn_reset(MDB_txn *txn)
3025 /* This call is only valid for read-only txns */
3026 if (!(txn->mt_flags & MDB_TXN_RDONLY))
3029 mdb_txn_end(txn, MDB_END_RESET);
3033 mdb_txn_abort(MDB_txn *txn)
3039 mdb_txn_abort(txn->mt_child);
3041 mdb_txn_end(txn, MDB_END_ABORT|MDB_END_SLOT|MDB_END_FREE);
3044 /** Save the freelist as of this transaction to the freeDB.
3045 * This changes the freelist. Keep trying until it stabilizes.
3048 mdb_freelist_save(MDB_txn *txn)
3050 /* env->me_pghead[] can grow and shrink during this call.
3051 * env->me_pglast and txn->mt_free_pgs[] can only grow.
3052 * Page numbers cannot disappear from txn->mt_free_pgs[].
3055 MDB_env *env = txn->mt_env;
3056 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
3057 txnid_t pglast = 0, head_id = 0;
3058 pgno_t freecnt = 0, *free_pgs, *mop;
3059 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
3061 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
3063 if (env->me_pghead) {
3064 /* Make sure first page of freeDB is touched and on freelist */
3065 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
3066 if (rc && rc != MDB_NOTFOUND)
3070 if (!env->me_pghead && txn->mt_loose_pgs) {
3071 /* Put loose page numbers in mt_free_pgs, since
3072 * we may be unable to return them to me_pghead.
3074 MDB_page *mp = txn->mt_loose_pgs;
3075 if ((rc = mdb_midl_need(&txn->mt_free_pgs, txn->mt_loose_count)) != 0)
3077 for (; mp; mp = NEXT_LOOSE_PAGE(mp))
3078 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
3079 txn->mt_loose_pgs = NULL;
3080 txn->mt_loose_count = 0;
3083 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
3084 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
3085 ? SSIZE_MAX : maxfree_1pg;
3088 /* Come back here after each Put() in case freelist changed */
3093 /* If using records from freeDB which we have not yet
3094 * deleted, delete them and any we reserved for me_pghead.
3096 while (pglast < env->me_pglast) {
3097 rc = mdb_cursor_first(&mc, &key, NULL);
3100 pglast = head_id = *(txnid_t *)key.mv_data;
3101 total_room = head_room = 0;
3102 mdb_tassert(txn, pglast <= env->me_pglast);
3103 rc = mdb_cursor_del(&mc, 0);
3108 /* Save the IDL of pages freed by this txn, to a single record */
3109 if (freecnt < txn->mt_free_pgs[0]) {
3111 /* Make sure last page of freeDB is touched and on freelist */
3112 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
3113 if (rc && rc != MDB_NOTFOUND)
3116 free_pgs = txn->mt_free_pgs;
3117 /* Write to last page of freeDB */
3118 key.mv_size = sizeof(txn->mt_txnid);
3119 key.mv_data = &txn->mt_txnid;
3121 freecnt = free_pgs[0];
3122 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
3123 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3126 /* Retry if mt_free_pgs[] grew during the Put() */
3127 free_pgs = txn->mt_free_pgs;
3128 } while (freecnt < free_pgs[0]);
3129 mdb_midl_sort(free_pgs);
3130 memcpy(data.mv_data, free_pgs, data.mv_size);
3133 unsigned int i = free_pgs[0];
3134 DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
3135 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
3137 DPRINTF(("IDL %"Z"u", free_pgs[i]));
3143 mop = env->me_pghead;
3144 mop_len = (mop ? mop[0] : 0) + txn->mt_loose_count;
3146 /* Reserve records for me_pghead[]. Split it if multi-page,
3147 * to avoid searching freeDB for a page range. Use keys in
3148 * range [1,me_pglast]: Smaller than txnid of oldest reader.
3150 if (total_room >= mop_len) {
3151 if (total_room == mop_len || --more < 0)
3153 } else if (head_room >= maxfree_1pg && head_id > 1) {
3154 /* Keep current record (overflow page), add a new one */
3158 /* (Re)write {key = head_id, IDL length = head_room} */
3159 total_room -= head_room;
3160 head_room = mop_len - total_room;
3161 if (head_room > maxfree_1pg && head_id > 1) {
3162 /* Overflow multi-page for part of me_pghead */
3163 head_room /= head_id; /* amortize page sizes */
3164 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
3165 } else if (head_room < 0) {
3166 /* Rare case, not bothering to delete this record */
3169 key.mv_size = sizeof(head_id);
3170 key.mv_data = &head_id;
3171 data.mv_size = (head_room + 1) * sizeof(pgno_t);
3172 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3175 /* IDL is initially empty, zero out at least the length */
3176 pgs = (pgno_t *)data.mv_data;
3177 j = head_room > clean_limit ? head_room : 0;
3181 total_room += head_room;
3184 /* Return loose page numbers to me_pghead, though usually none are
3185 * left at this point. The pages themselves remain in dirty_list.
3187 if (txn->mt_loose_pgs) {
3188 MDB_page *mp = txn->mt_loose_pgs;
3189 unsigned count = txn->mt_loose_count;
3191 /* Room for loose pages + temp IDL with same */
3192 if ((rc = mdb_midl_need(&env->me_pghead, 2*count+1)) != 0)
3194 mop = env->me_pghead;
3195 loose = mop + MDB_IDL_ALLOCLEN(mop) - count;
3196 for (count = 0; mp; mp = NEXT_LOOSE_PAGE(mp))
3197 loose[ ++count ] = mp->mp_pgno;
3199 mdb_midl_sort(loose);
3200 mdb_midl_xmerge(mop, loose);
3201 txn->mt_loose_pgs = NULL;
3202 txn->mt_loose_count = 0;
3206 /* Fill in the reserved me_pghead records */
3212 rc = mdb_cursor_first(&mc, &key, &data);
3213 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
3214 txnid_t id = *(txnid_t *)key.mv_data;
3215 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
3218 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
3220 if (len > mop_len) {
3222 data.mv_size = (len + 1) * sizeof(MDB_ID);
3224 data.mv_data = mop -= len;
3227 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
3229 if (rc || !(mop_len -= len))
3236 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
3237 * @param[in] txn the transaction that's being committed
3238 * @param[in] keep number of initial pages in dirty_list to keep dirty.
3239 * @return 0 on success, non-zero on failure.
3242 mdb_page_flush(MDB_txn *txn, int keep)
3244 MDB_env *env = txn->mt_env;
3245 MDB_ID2L dl = txn->mt_u.dirty_list;
3246 unsigned psize = env->me_psize, j;
3247 int i, pagecount = dl[0].mid, rc;
3248 size_t size = 0, pos = 0;
3250 MDB_page *dp = NULL;
3254 struct iovec iov[MDB_COMMIT_PAGES];
3255 ssize_t wpos = 0, wsize = 0, wres;
3256 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
3262 if (env->me_flags & MDB_WRITEMAP) {
3263 /* Clear dirty flags */
3264 while (++i <= pagecount) {
3266 /* Don't flush this page yet */
3267 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3268 dp->mp_flags &= ~P_KEEP;
3272 dp->mp_flags &= ~P_DIRTY;
3277 /* Write the pages */
3279 if (++i <= pagecount) {
3281 /* Don't flush this page yet */
3282 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3283 dp->mp_flags &= ~P_KEEP;
3288 /* clear dirty flag */
3289 dp->mp_flags &= ~P_DIRTY;
3292 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
3297 /* Windows actually supports scatter/gather I/O, but only on
3298 * unbuffered file handles. Since we're relying on the OS page
3299 * cache for all our data, that's self-defeating. So we just
3300 * write pages one at a time. We use the ov structure to set
3301 * the write offset, to at least save the overhead of a Seek
3304 DPRINTF(("committing page %"Z"u", pgno));
3305 memset(&ov, 0, sizeof(ov));
3306 ov.Offset = pos & 0xffffffff;
3307 ov.OffsetHigh = pos >> 16 >> 16;
3308 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
3310 DPRINTF(("WriteFile: %d", rc));
3314 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
3315 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
3318 /* Write previous page(s) */
3319 #ifdef MDB_USE_PWRITEV
3320 wres = pwritev(env->me_fd, iov, n, wpos);
3323 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
3326 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
3330 DPRINTF(("lseek: %s", strerror(rc)));
3333 wres = writev(env->me_fd, iov, n);
3336 if (wres != wsize) {
3341 DPRINTF(("Write error: %s", strerror(rc)));
3343 rc = EIO; /* TODO: Use which error code? */
3344 DPUTS("short write, filesystem full?");
3355 DPRINTF(("committing page %"Z"u", pgno));
3356 next_pos = pos + size;
3357 iov[n].iov_len = size;
3358 iov[n].iov_base = (char *)dp;
3364 /* MIPS has cache coherency issues, this is a no-op everywhere else
3365 * Note: for any size >= on-chip cache size, entire on-chip cache is
3368 CACHEFLUSH(env->me_map, txn->mt_next_pgno * env->me_psize, DCACHE);
3370 for (i = keep; ++i <= pagecount; ) {
3372 /* This is a page we skipped above */
3375 dl[j].mid = dp->mp_pgno;
3378 mdb_dpage_free(env, dp);
3383 txn->mt_dirty_room += i - j;
3389 mdb_txn_commit(MDB_txn *txn)
3392 unsigned int i, end_mode;
3398 /* mdb_txn_end() mode for a commit which writes nothing */
3399 end_mode = MDB_END_EMPTY_COMMIT|MDB_END_UPDATE|MDB_END_SLOT|MDB_END_FREE;
3401 if (txn->mt_child) {
3402 rc = mdb_txn_commit(txn->mt_child);
3409 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3413 if (txn->mt_flags & (MDB_TXN_FINISHED|MDB_TXN_ERROR)) {
3414 DPUTS("txn has failed/finished, can't commit");
3416 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3421 if (txn->mt_parent) {
3422 MDB_txn *parent = txn->mt_parent;
3426 unsigned x, y, len, ps_len;
3428 /* Append our free list to parent's */
3429 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3432 mdb_midl_free(txn->mt_free_pgs);
3433 /* Failures after this must either undo the changes
3434 * to the parent or set MDB_TXN_ERROR in the parent.
3437 parent->mt_next_pgno = txn->mt_next_pgno;
3438 parent->mt_flags = txn->mt_flags;
3440 /* Merge our cursors into parent's and close them */
3441 mdb_cursors_close(txn, 1);
3443 /* Update parent's DB table. */
3444 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3445 parent->mt_numdbs = txn->mt_numdbs;
3446 parent->mt_dbflags[FREE_DBI] = txn->mt_dbflags[FREE_DBI];
3447 parent->mt_dbflags[MAIN_DBI] = txn->mt_dbflags[MAIN_DBI];
3448 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
3449 /* preserve parent's DB_NEW status */
3450 x = parent->mt_dbflags[i] & DB_NEW;
3451 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3454 dst = parent->mt_u.dirty_list;
3455 src = txn->mt_u.dirty_list;
3456 /* Remove anything in our dirty list from parent's spill list */
3457 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3459 pspill[0] = (pgno_t)-1;
3460 /* Mark our dirty pages as deleted in parent spill list */
3461 for (i=0, len=src[0].mid; ++i <= len; ) {
3462 MDB_ID pn = src[i].mid << 1;
3463 while (pn > pspill[x])
3465 if (pn == pspill[x]) {
3470 /* Squash deleted pagenums if we deleted any */
3471 for (x=y; ++x <= ps_len; )
3472 if (!(pspill[x] & 1))
3473 pspill[++y] = pspill[x];
3477 /* Remove anything in our spill list from parent's dirty list */
3478 if (txn->mt_spill_pgs && txn->mt_spill_pgs[0]) {
3479 for (i=1; i<=txn->mt_spill_pgs[0]; i++) {
3480 MDB_ID pn = txn->mt_spill_pgs[i];
3482 continue; /* deleted spillpg */
3484 y = mdb_mid2l_search(dst, pn);
3485 if (y <= dst[0].mid && dst[y].mid == pn) {
3487 while (y < dst[0].mid) {
3496 /* Find len = length of merging our dirty list with parent's */
3498 dst[0].mid = 0; /* simplify loops */
3499 if (parent->mt_parent) {
3500 len = x + src[0].mid;
3501 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3502 for (i = x; y && i; y--) {
3503 pgno_t yp = src[y].mid;
3504 while (yp < dst[i].mid)
3506 if (yp == dst[i].mid) {
3511 } else { /* Simplify the above for single-ancestor case */
3512 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3514 /* Merge our dirty list with parent's */
3516 for (i = len; y; dst[i--] = src[y--]) {
3517 pgno_t yp = src[y].mid;
3518 while (yp < dst[x].mid)
3519 dst[i--] = dst[x--];
3520 if (yp == dst[x].mid)
3521 free(dst[x--].mptr);
3523 mdb_tassert(txn, i == x);
3525 free(txn->mt_u.dirty_list);
3526 parent->mt_dirty_room = txn->mt_dirty_room;
3527 if (txn->mt_spill_pgs) {
3528 if (parent->mt_spill_pgs) {
3529 /* TODO: Prevent failure here, so parent does not fail */
3530 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3532 parent->mt_flags |= MDB_TXN_ERROR;
3533 mdb_midl_free(txn->mt_spill_pgs);
3534 mdb_midl_sort(parent->mt_spill_pgs);
3536 parent->mt_spill_pgs = txn->mt_spill_pgs;
3540 /* Append our loose page list to parent's */
3541 for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(*lp))
3543 *lp = txn->mt_loose_pgs;
3544 parent->mt_loose_count += txn->mt_loose_count;
3546 parent->mt_child = NULL;
3547 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3552 if (txn != env->me_txn) {
3553 DPUTS("attempt to commit unknown transaction");
3558 mdb_cursors_close(txn, 0);
3560 if (!txn->mt_u.dirty_list[0].mid &&
3561 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
3564 DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
3565 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3567 /* Update DB root pointers */
3568 if (txn->mt_numdbs > CORE_DBS) {
3572 data.mv_size = sizeof(MDB_db);
3574 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3575 for (i = CORE_DBS; i < txn->mt_numdbs; i++) {
3576 if (txn->mt_dbflags[i] & DB_DIRTY) {
3577 if (TXN_DBI_CHANGED(txn, i)) {
3581 data.mv_data = &txn->mt_dbs[i];
3582 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data,
3590 rc = mdb_freelist_save(txn);
3594 mdb_midl_free(env->me_pghead);
3595 env->me_pghead = NULL;
3596 mdb_midl_shrink(&txn->mt_free_pgs);
3602 if ((rc = mdb_page_flush(txn, 0)) ||
3603 (rc = mdb_env_sync(env, 0)) ||
3604 (rc = mdb_env_write_meta(txn)))
3606 end_mode = MDB_END_COMMITTED|MDB_END_UPDATE;
3609 mdb_txn_end(txn, end_mode);
3617 /** Read the environment parameters of a DB environment before
3618 * mapping it into memory.
3619 * @param[in] env the environment handle
3620 * @param[out] meta address of where to store the meta information
3621 * @return 0 on success, non-zero on failure.
3624 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3630 enum { Size = sizeof(pbuf) };
3632 /* We don't know the page size yet, so use a minimum value.
3633 * Read both meta pages so we can use the latest one.
3636 for (i=off=0; i<NUM_METAS; i++, off += meta->mm_psize) {
3640 memset(&ov, 0, sizeof(ov));
3642 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3643 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3646 rc = pread(env->me_fd, &pbuf, Size, off);
3649 if (rc == 0 && off == 0)
3651 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3652 DPRINTF(("read: %s", mdb_strerror(rc)));
3656 p = (MDB_page *)&pbuf;
3658 if (!F_ISSET(p->mp_flags, P_META)) {
3659 DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
3664 if (m->mm_magic != MDB_MAGIC) {
3665 DPUTS("meta has invalid magic");
3669 if (m->mm_version != MDB_DATA_VERSION) {
3670 DPRINTF(("database is version %u, expected version %u",
3671 m->mm_version, MDB_DATA_VERSION));
3672 return MDB_VERSION_MISMATCH;
3675 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3681 /** Fill in most of the zeroed #MDB_meta for an empty database environment */
3683 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
3685 meta->mm_magic = MDB_MAGIC;
3686 meta->mm_version = MDB_DATA_VERSION;
3687 meta->mm_mapsize = env->me_mapsize;
3688 meta->mm_psize = env->me_psize;
3689 meta->mm_last_pg = NUM_METAS-1;
3690 meta->mm_flags = env->me_flags & 0xffff;
3691 meta->mm_flags |= MDB_INTEGERKEY; /* this is mm_dbs[FREE_DBI].md_flags */
3692 meta->mm_dbs[FREE_DBI].md_root = P_INVALID;
3693 meta->mm_dbs[MAIN_DBI].md_root = P_INVALID;
3696 /** Write the environment parameters of a freshly created DB environment.
3697 * @param[in] env the environment handle
3698 * @param[in] meta the #MDB_meta to write
3699 * @return 0 on success, non-zero on failure.
3702 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3710 memset(&ov, 0, sizeof(ov));
3711 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3713 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3716 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3717 len = pwrite(fd, ptr, size, pos); \
3718 if (len == -1 && ErrCode() == EINTR) continue; \
3719 rc = (len >= 0); break; } while(1)
3722 DPUTS("writing new meta page");
3724 psize = env->me_psize;
3726 p = calloc(NUM_METAS, psize);
3731 p->mp_flags = P_META;
3732 *(MDB_meta *)METADATA(p) = *meta;
3734 q = (MDB_page *)((char *)p + psize);
3736 q->mp_flags = P_META;
3737 *(MDB_meta *)METADATA(q) = *meta;
3739 DO_PWRITE(rc, env->me_fd, p, psize * NUM_METAS, len, 0);
3742 else if ((unsigned) len == psize * NUM_METAS)
3750 /** Update the environment info to commit a transaction.
3751 * @param[in] txn the transaction that's being committed
3752 * @return 0 on success, non-zero on failure.
3755 mdb_env_write_meta(MDB_txn *txn)
3758 MDB_meta meta, metab, *mp;
3762 int rc, len, toggle;
3771 toggle = txn->mt_txnid & 1;
3772 DPRINTF(("writing meta page %d for root page %"Z"u",
3773 toggle, txn->mt_dbs[MAIN_DBI].md_root));
3776 flags = env->me_flags;
3777 mp = env->me_metas[toggle];
3778 mapsize = env->me_metas[toggle ^ 1]->mm_mapsize;
3779 /* Persist any increases of mapsize config */
3780 if (mapsize < env->me_mapsize)
3781 mapsize = env->me_mapsize;
3783 if (flags & MDB_WRITEMAP) {
3784 mp->mm_mapsize = mapsize;
3785 mp->mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
3786 mp->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
3787 mp->mm_last_pg = txn->mt_next_pgno - 1;
3788 #if (__GNUC__ * 100 + __GNUC_MINOR__ >= 404) && /* TODO: portability */ \
3789 !(defined(__i386__) || defined(__x86_64__))
3790 /* LY: issue a memory barrier, if not x86. ITS#7969 */
3791 __sync_synchronize();
3793 mp->mm_txnid = txn->mt_txnid;
3794 if (!(flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3795 unsigned meta_size = env->me_psize;
3796 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3797 ptr = (char *)mp - PAGEHDRSZ;
3798 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
3799 r2 = (ptr - env->me_map) & (env->me_os_psize - 1);
3803 if (MDB_MSYNC(ptr, meta_size, rc)) {
3810 metab.mm_txnid = mp->mm_txnid;
3811 metab.mm_last_pg = mp->mm_last_pg;
3813 meta.mm_mapsize = mapsize;
3814 meta.mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
3815 meta.mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
3816 meta.mm_last_pg = txn->mt_next_pgno - 1;
3817 meta.mm_txnid = txn->mt_txnid;
3819 off = offsetof(MDB_meta, mm_mapsize);
3820 ptr = (char *)&meta + off;
3821 len = sizeof(MDB_meta) - off;
3822 off += (char *)mp - env->me_map;
3824 /* Write to the SYNC fd */
3825 mfd = (flags & (MDB_NOSYNC|MDB_NOMETASYNC)) ? env->me_fd : env->me_mfd;
3828 memset(&ov, 0, sizeof(ov));
3830 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3835 rc = pwrite(mfd, ptr, len, off);
3838 rc = rc < 0 ? ErrCode() : EIO;
3843 DPUTS("write failed, disk error?");
3844 /* On a failure, the pagecache still contains the new data.
3845 * Write some old data back, to prevent it from being used.
3846 * Use the non-SYNC fd; we know it will fail anyway.
3848 meta.mm_last_pg = metab.mm_last_pg;
3849 meta.mm_txnid = metab.mm_txnid;
3851 memset(&ov, 0, sizeof(ov));
3853 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3855 r2 = pwrite(env->me_fd, ptr, len, off);
3856 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
3859 env->me_flags |= MDB_FATAL_ERROR;
3862 /* MIPS has cache coherency issues, this is a no-op everywhere else */
3863 CACHEFLUSH(env->me_map + off, len, DCACHE);
3865 /* Memory ordering issues are irrelevant; since the entire writer
3866 * is wrapped by wmutex, all of these changes will become visible
3867 * after the wmutex is unlocked. Since the DB is multi-version,
3868 * readers will get consistent data regardless of how fresh or
3869 * how stale their view of these values is.
3872 env->me_txns->mti_txnid = txn->mt_txnid;
3877 /** Check both meta pages to see which one is newer.
3878 * @param[in] env the environment handle
3879 * @return newest #MDB_meta.
3882 mdb_env_pick_meta(const MDB_env *env)
3884 MDB_meta *const *metas = env->me_metas;
3885 return metas[ metas[0]->mm_txnid < metas[1]->mm_txnid ];
3889 mdb_env_create(MDB_env **env)
3893 e = calloc(1, sizeof(MDB_env));
3897 e->me_maxreaders = DEFAULT_READERS;
3898 e->me_maxdbs = e->me_numdbs = CORE_DBS;
3899 e->me_fd = INVALID_HANDLE_VALUE;
3900 e->me_lfd = INVALID_HANDLE_VALUE;
3901 e->me_mfd = INVALID_HANDLE_VALUE;
3902 #ifdef MDB_USE_POSIX_SEM
3903 e->me_rmutex = SEM_FAILED;
3904 e->me_wmutex = SEM_FAILED;
3906 e->me_pid = getpid();
3907 GET_PAGESIZE(e->me_os_psize);
3908 VGMEMP_CREATE(e,0,0);
3914 mdb_env_map(MDB_env *env, void *addr)
3917 unsigned int flags = env->me_flags;
3921 LONG sizelo, sizehi;
3924 if (flags & MDB_RDONLY) {
3925 /* Don't set explicit map size, use whatever exists */
3930 msize = env->me_mapsize;
3931 sizelo = msize & 0xffffffff;
3932 sizehi = msize >> 16 >> 16; /* only needed on Win64 */
3934 /* Windows won't create mappings for zero length files.
3935 * and won't map more than the file size.
3936 * Just set the maxsize right now.
3938 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3939 || !SetEndOfFile(env->me_fd)
3940 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3944 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3945 PAGE_READWRITE : PAGE_READONLY,
3946 sizehi, sizelo, NULL);
3949 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3950 FILE_MAP_WRITE : FILE_MAP_READ,
3952 rc = env->me_map ? 0 : ErrCode();
3957 int prot = PROT_READ;
3958 if (flags & MDB_WRITEMAP) {
3960 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3963 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
3965 if (env->me_map == MAP_FAILED) {
3970 if (flags & MDB_NORDAHEAD) {
3971 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3973 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3975 #ifdef POSIX_MADV_RANDOM
3976 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3977 #endif /* POSIX_MADV_RANDOM */
3978 #endif /* MADV_RANDOM */
3982 /* Can happen because the address argument to mmap() is just a
3983 * hint. mmap() can pick another, e.g. if the range is in use.
3984 * The MAP_FIXED flag would prevent that, but then mmap could
3985 * instead unmap existing pages to make room for the new map.
3987 if (addr && env->me_map != addr)
3988 return EBUSY; /* TODO: Make a new MDB_* error code? */
3990 p = (MDB_page *)env->me_map;
3991 env->me_metas[0] = METADATA(p);
3992 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
3998 mdb_env_set_mapsize(MDB_env *env, size_t size)
4000 /* If env is already open, caller is responsible for making
4001 * sure there are no active txns.
4009 meta = mdb_env_pick_meta(env);
4011 size = meta->mm_mapsize;
4013 /* Silently round up to minimum if the size is too small */
4014 size_t minsize = (meta->mm_last_pg + 1) * env->me_psize;
4018 munmap(env->me_map, env->me_mapsize);
4019 env->me_mapsize = size;
4020 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
4021 rc = mdb_env_map(env, old);
4025 env->me_mapsize = size;
4027 env->me_maxpg = env->me_mapsize / env->me_psize;
4032 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
4036 env->me_maxdbs = dbs + CORE_DBS;
4041 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
4043 if (env->me_map || readers < 1)
4045 env->me_maxreaders = readers;
4050 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
4052 if (!env || !readers)
4054 *readers = env->me_maxreaders;
4059 mdb_fsize(HANDLE fd, size_t *size)
4062 LARGE_INTEGER fsize;
4064 if (!GetFileSizeEx(fd, &fsize))
4067 *size = fsize.QuadPart;
4079 #ifdef BROKEN_FDATASYNC
4080 #include <sys/utsname.h>
4081 #include <sys/vfs.h>
4084 /** Further setup required for opening an LMDB environment
4087 mdb_env_open2(MDB_env *env)
4089 unsigned int flags = env->me_flags;
4090 int i, newenv = 0, rc;
4094 /* See if we should use QueryLimited */
4096 if ((rc & 0xff) > 5)
4097 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
4099 env->me_pidquery = PROCESS_QUERY_INFORMATION;
4102 #ifdef BROKEN_FDATASYNC
4103 /* ext3/ext4 fdatasync is broken on some older Linux kernels.
4104 * https://lkml.org/lkml/2012/9/3/83
4105 * Kernels after 3.6-rc6 are known good.
4106 * https://lkml.org/lkml/2012/9/10/556
4107 * See if the DB is on ext3/ext4, then check for new enough kernel
4108 * Kernels 2.6.32.60, 2.6.34.15, 3.2.30, and 3.5.4 are also known
4113 fstatfs(env->me_fd, &st);
4114 while (st.f_type == 0xEF53) {
4118 if (uts.release[0] < '3') {
4119 if (!strncmp(uts.release, "2.6.32.", 7)) {
4120 i = atoi(uts.release+7);
4122 break; /* 2.6.32.60 and newer is OK */
4123 } else if (!strncmp(uts.release, "2.6.34.", 7)) {
4124 i = atoi(uts.release+7);
4126 break; /* 2.6.34.15 and newer is OK */
4128 } else if (uts.release[0] == '3') {
4129 i = atoi(uts.release+2);
4131 break; /* 3.6 and newer is OK */
4133 i = atoi(uts.release+4);
4135 break; /* 3.5.4 and newer is OK */
4136 } else if (i == 2) {
4137 i = atoi(uts.release+4);
4139 break; /* 3.2.30 and newer is OK */
4141 } else { /* 4.x and newer is OK */
4144 env->me_flags |= MDB_FSYNCONLY;
4150 if ((i = mdb_env_read_header(env, &meta)) != 0) {
4153 DPUTS("new mdbenv");
4155 env->me_psize = env->me_os_psize;
4156 if (env->me_psize > MAX_PAGESIZE)
4157 env->me_psize = MAX_PAGESIZE;
4158 memset(&meta, 0, sizeof(meta));
4159 mdb_env_init_meta0(env, &meta);
4160 meta.mm_mapsize = DEFAULT_MAPSIZE;
4162 env->me_psize = meta.mm_psize;
4165 /* Was a mapsize configured? */
4166 if (!env->me_mapsize) {
4167 env->me_mapsize = meta.mm_mapsize;
4170 /* Make sure mapsize >= committed data size. Even when using
4171 * mm_mapsize, which could be broken in old files (ITS#7789).
4173 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
4174 if (env->me_mapsize < minsize)
4175 env->me_mapsize = minsize;
4177 meta.mm_mapsize = env->me_mapsize;
4179 if (newenv && !(flags & MDB_FIXEDMAP)) {
4180 /* mdb_env_map() may grow the datafile. Write the metapages
4181 * first, so the file will be valid if initialization fails.
4182 * Except with FIXEDMAP, since we do not yet know mm_address.
4183 * We could fill in mm_address later, but then a different
4184 * program might end up doing that - one with a memory layout
4185 * and map address which does not suit the main program.
4187 rc = mdb_env_init_meta(env, &meta);
4193 rc = mdb_env_map(env, (flags & MDB_FIXEDMAP) ? meta.mm_address : NULL);
4198 if (flags & MDB_FIXEDMAP)
4199 meta.mm_address = env->me_map;
4200 i = mdb_env_init_meta(env, &meta);
4201 if (i != MDB_SUCCESS) {
4206 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
4207 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
4209 #if !(MDB_MAXKEYSIZE)
4210 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
4212 env->me_maxpg = env->me_mapsize / env->me_psize;
4216 MDB_meta *meta = mdb_env_pick_meta(env);
4217 MDB_db *db = &meta->mm_dbs[MAIN_DBI];
4219 DPRINTF(("opened database version %u, pagesize %u",
4220 meta->mm_version, env->me_psize));
4221 DPRINTF(("using meta page %d", (int) (meta->mm_txnid & 1)));
4222 DPRINTF(("depth: %u", db->md_depth));
4223 DPRINTF(("entries: %"Z"u", db->md_entries));
4224 DPRINTF(("branch pages: %"Z"u", db->md_branch_pages));
4225 DPRINTF(("leaf pages: %"Z"u", db->md_leaf_pages));
4226 DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
4227 DPRINTF(("root: %"Z"u", db->md_root));
4235 /** Release a reader thread's slot in the reader lock table.
4236 * This function is called automatically when a thread exits.
4237 * @param[in] ptr This points to the slot in the reader lock table.
4240 mdb_env_reader_dest(void *ptr)
4242 MDB_reader *reader = ptr;
4248 /** Junk for arranging thread-specific callbacks on Windows. This is
4249 * necessarily platform and compiler-specific. Windows supports up
4250 * to 1088 keys. Let's assume nobody opens more than 64 environments
4251 * in a single process, for now. They can override this if needed.
4253 #ifndef MAX_TLS_KEYS
4254 #define MAX_TLS_KEYS 64
4256 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
4257 static int mdb_tls_nkeys;
4259 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
4263 case DLL_PROCESS_ATTACH: break;
4264 case DLL_THREAD_ATTACH: break;
4265 case DLL_THREAD_DETACH:
4266 for (i=0; i<mdb_tls_nkeys; i++) {
4267 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
4269 mdb_env_reader_dest(r);
4273 case DLL_PROCESS_DETACH: break;
4278 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4280 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4284 /* Force some symbol references.
4285 * _tls_used forces the linker to create the TLS directory if not already done
4286 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
4288 #pragma comment(linker, "/INCLUDE:_tls_used")
4289 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
4290 #pragma const_seg(".CRT$XLB")
4291 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
4292 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4295 #pragma comment(linker, "/INCLUDE:__tls_used")
4296 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
4297 #pragma data_seg(".CRT$XLB")
4298 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4300 #endif /* WIN 32/64 */
4301 #endif /* !__GNUC__ */
4304 /** Downgrade the exclusive lock on the region back to shared */
4306 mdb_env_share_locks(MDB_env *env, int *excl)
4309 MDB_meta *meta = mdb_env_pick_meta(env);
4311 env->me_txns->mti_txnid = meta->mm_txnid;
4316 /* First acquire a shared lock. The Unlock will
4317 * then release the existing exclusive lock.
4319 memset(&ov, 0, sizeof(ov));
4320 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4323 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4329 struct flock lock_info;
4330 /* The shared lock replaces the existing lock */
4331 memset((void *)&lock_info, 0, sizeof(lock_info));
4332 lock_info.l_type = F_RDLCK;
4333 lock_info.l_whence = SEEK_SET;
4334 lock_info.l_start = 0;
4335 lock_info.l_len = 1;
4336 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4337 (rc = ErrCode()) == EINTR) ;
4338 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
4345 /** Try to get exclusive lock, otherwise shared.
4346 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
4349 mdb_env_excl_lock(MDB_env *env, int *excl)
4353 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
4357 memset(&ov, 0, sizeof(ov));
4358 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4365 struct flock lock_info;
4366 memset((void *)&lock_info, 0, sizeof(lock_info));
4367 lock_info.l_type = F_WRLCK;
4368 lock_info.l_whence = SEEK_SET;
4369 lock_info.l_start = 0;
4370 lock_info.l_len = 1;
4371 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4372 (rc = ErrCode()) == EINTR) ;
4376 # ifndef MDB_USE_POSIX_MUTEX
4377 if (*excl < 0) /* always true when MDB_USE_POSIX_MUTEX */
4380 lock_info.l_type = F_RDLCK;
4381 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
4382 (rc = ErrCode()) == EINTR) ;
4392 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
4394 * @(#) $Revision: 5.1 $
4395 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
4396 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
4398 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
4402 * Please do not copyright this code. This code is in the public domain.
4404 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
4405 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
4406 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
4407 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
4408 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4409 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4410 * PERFORMANCE OF THIS SOFTWARE.
4413 * chongo <Landon Curt Noll> /\oo/\
4414 * http://www.isthe.com/chongo/
4416 * Share and Enjoy! :-)
4419 typedef unsigned long long mdb_hash_t;
4420 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
4422 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
4423 * @param[in] val value to hash
4424 * @param[in] hval initial value for hash
4425 * @return 64 bit hash
4427 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
4428 * hval arg on the first call.
4431 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
4433 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
4434 unsigned char *end = s + val->mv_size;
4436 * FNV-1a hash each octet of the string
4439 /* xor the bottom with the current octet */
4440 hval ^= (mdb_hash_t)*s++;
4442 /* multiply by the 64 bit FNV magic prime mod 2^64 */
4443 hval += (hval << 1) + (hval << 4) + (hval << 5) +
4444 (hval << 7) + (hval << 8) + (hval << 40);
4446 /* return our new hash value */
4450 /** Hash the string and output the encoded hash.
4451 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
4452 * very short name limits. We don't care about the encoding being reversible,
4453 * we just want to preserve as many bits of the input as possible in a
4454 * small printable string.
4455 * @param[in] str string to hash
4456 * @param[out] encbuf an array of 11 chars to hold the hash
4458 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
4461 mdb_pack85(unsigned long l, char *out)
4465 for (i=0; i<5; i++) {
4466 *out++ = mdb_a85[l % 85];
4472 mdb_hash_enc(MDB_val *val, char *encbuf)
4474 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
4476 mdb_pack85(h, encbuf);
4477 mdb_pack85(h>>32, encbuf+5);
4482 /** Open and/or initialize the lock region for the environment.
4483 * @param[in] env The LMDB environment.
4484 * @param[in] lpath The pathname of the file used for the lock region.
4485 * @param[in] mode The Unix permissions for the file, if we create it.
4486 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
4487 * @return 0 on success, non-zero on failure.
4490 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
4493 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
4495 # define MDB_ERRCODE_ROFS EROFS
4496 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
4497 # define MDB_CLOEXEC O_CLOEXEC
4500 # define MDB_CLOEXEC 0
4508 rc = utf8_to_utf16(lpath, -1, &wlpath, NULL);
4511 env->me_lfd = CreateFileW(wlpath, GENERIC_READ|GENERIC_WRITE,
4512 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
4513 FILE_ATTRIBUTE_NORMAL, NULL);
4516 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
4518 if (env->me_lfd == INVALID_HANDLE_VALUE) {
4520 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
4525 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
4526 /* Lose record locks when exec*() */
4527 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
4528 fcntl(env->me_lfd, F_SETFD, fdflags);
4531 if (!(env->me_flags & MDB_NOTLS)) {
4532 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
4535 env->me_flags |= MDB_ENV_TXKEY;
4537 /* Windows TLS callbacks need help finding their TLS info. */
4538 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
4542 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
4546 /* Try to get exclusive lock. If we succeed, then
4547 * nobody is using the lock region and we should initialize it.
4549 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
4552 size = GetFileSize(env->me_lfd, NULL);
4554 size = lseek(env->me_lfd, 0, SEEK_END);
4555 if (size == -1) goto fail_errno;
4557 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
4558 if (size < rsize && *excl > 0) {
4560 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
4561 || !SetEndOfFile(env->me_lfd))
4564 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
4568 size = rsize - sizeof(MDB_txninfo);
4569 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
4574 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
4576 if (!mh) goto fail_errno;
4577 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
4579 if (!env->me_txns) goto fail_errno;
4581 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
4583 if (m == MAP_FAILED) goto fail_errno;
4589 BY_HANDLE_FILE_INFORMATION stbuf;
4598 if (!mdb_sec_inited) {
4599 InitializeSecurityDescriptor(&mdb_null_sd,
4600 SECURITY_DESCRIPTOR_REVISION);
4601 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
4602 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
4603 mdb_all_sa.bInheritHandle = FALSE;
4604 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
4607 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
4608 idbuf.volume = stbuf.dwVolumeSerialNumber;
4609 idbuf.nhigh = stbuf.nFileIndexHigh;
4610 idbuf.nlow = stbuf.nFileIndexLow;
4611 val.mv_data = &idbuf;
4612 val.mv_size = sizeof(idbuf);
4613 mdb_hash_enc(&val, encbuf);
4614 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
4615 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
4616 env->me_rmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
4617 if (!env->me_rmutex) goto fail_errno;
4618 env->me_wmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
4619 if (!env->me_wmutex) goto fail_errno;
4620 #elif defined(MDB_USE_POSIX_SEM)
4629 #if defined(__NetBSD__)
4630 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
4632 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
4633 idbuf.dev = stbuf.st_dev;
4634 idbuf.ino = stbuf.st_ino;
4635 val.mv_data = &idbuf;
4636 val.mv_size = sizeof(idbuf);
4637 mdb_hash_enc(&val, encbuf);
4638 #ifdef MDB_SHORT_SEMNAMES
4639 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
4641 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
4642 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
4643 /* Clean up after a previous run, if needed: Try to
4644 * remove both semaphores before doing anything else.
4646 sem_unlink(env->me_txns->mti_rmname);
4647 sem_unlink(env->me_txns->mti_wmname);
4648 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
4649 O_CREAT|O_EXCL, mode, 1);
4650 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4651 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
4652 O_CREAT|O_EXCL, mode, 1);
4653 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4654 #else /* MDB_USE_POSIX_MUTEX: */
4655 pthread_mutexattr_t mattr;
4657 /* Solaris needs this before initing a robust mutex. Otherwise
4658 * it may skip the init and return EBUSY "seems someone already
4659 * inited" or EINVAL "it was inited differently".
4661 memset(env->me_txns->mti_rmutex, 0, sizeof(*env->me_txns->mti_rmutex));
4662 memset(env->me_txns->mti_wmutex, 0, sizeof(*env->me_txns->mti_wmutex));
4664 if ((rc = pthread_mutexattr_init(&mattr)))
4667 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
4668 #ifdef MDB_ROBUST_SUPPORTED
4669 if (!rc) rc = pthread_mutexattr_setrobust(&mattr, PTHREAD_MUTEX_ROBUST);
4671 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_rmutex, &mattr);
4672 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_wmutex, &mattr);
4673 pthread_mutexattr_destroy(&mattr);
4676 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
4678 env->me_txns->mti_magic = MDB_MAGIC;
4679 env->me_txns->mti_format = MDB_LOCK_FORMAT;
4680 env->me_txns->mti_txnid = 0;
4681 env->me_txns->mti_numreaders = 0;
4684 if (env->me_txns->mti_magic != MDB_MAGIC) {
4685 DPUTS("lock region has invalid magic");
4689 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
4690 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
4691 env->me_txns->mti_format, MDB_LOCK_FORMAT));
4692 rc = MDB_VERSION_MISMATCH;
4696 if (rc && rc != EACCES && rc != EAGAIN) {
4700 env->me_rmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
4701 if (!env->me_rmutex) goto fail_errno;
4702 env->me_wmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
4703 if (!env->me_wmutex) goto fail_errno;
4704 #elif defined(MDB_USE_POSIX_SEM)
4705 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
4706 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4707 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
4708 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4719 /** The name of the lock file in the DB environment */
4720 #define LOCKNAME "/lock.mdb"
4721 /** The name of the data file in the DB environment */
4722 #define DATANAME "/data.mdb"
4723 /** The suffix of the lock file when no subdir is used */
4724 #define LOCKSUFF "-lock"
4725 /** Only a subset of the @ref mdb_env flags can be changed
4726 * at runtime. Changing other flags requires closing the
4727 * environment and re-opening it with the new flags.
4729 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
4730 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY| \
4731 MDB_WRITEMAP|MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
4733 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
4734 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
4738 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
4740 int oflags, rc, len, excl = -1;
4741 char *lpath, *dpath;
4746 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
4750 if (flags & MDB_NOSUBDIR) {
4751 rc = len + sizeof(LOCKSUFF) + len + 1;
4753 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
4758 if (flags & MDB_NOSUBDIR) {
4759 dpath = lpath + len + sizeof(LOCKSUFF);
4760 sprintf(lpath, "%s" LOCKSUFF, path);
4761 strcpy(dpath, path);
4763 dpath = lpath + len + sizeof(LOCKNAME);
4764 sprintf(lpath, "%s" LOCKNAME, path);
4765 sprintf(dpath, "%s" DATANAME, path);
4769 flags |= env->me_flags;
4770 if (flags & MDB_RDONLY) {
4771 /* silently ignore WRITEMAP when we're only getting read access */
4772 flags &= ~MDB_WRITEMAP;
4774 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
4775 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
4778 env->me_flags = flags |= MDB_ENV_ACTIVE;
4782 env->me_path = strdup(path);
4783 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
4784 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
4785 env->me_dbiseqs = calloc(env->me_maxdbs, sizeof(unsigned int));
4786 if (!(env->me_dbxs && env->me_path && env->me_dbflags && env->me_dbiseqs)) {
4790 env->me_dbxs[FREE_DBI].md_cmp = mdb_cmp_long; /* aligned MDB_INTEGERKEY */
4792 /* For RDONLY, get lockfile after we know datafile exists */
4793 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
4794 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4800 if (F_ISSET(flags, MDB_RDONLY)) {
4801 oflags = GENERIC_READ;
4802 len = OPEN_EXISTING;
4804 oflags = GENERIC_READ|GENERIC_WRITE;
4807 mode = FILE_ATTRIBUTE_NORMAL;
4808 rc = utf8_to_utf16(dpath, -1, &wpath, NULL);
4811 env->me_fd = CreateFileW(wpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
4812 NULL, len, mode, NULL);
4815 if (F_ISSET(flags, MDB_RDONLY))
4818 oflags = O_RDWR | O_CREAT;
4820 env->me_fd = open(dpath, oflags, mode);
4822 if (env->me_fd == INVALID_HANDLE_VALUE) {
4827 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
4828 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4833 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
4834 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
4835 env->me_mfd = env->me_fd;
4837 /* Synchronous fd for meta writes. Needed even with
4838 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
4841 len = OPEN_EXISTING;
4842 rc = utf8_to_utf16(dpath, -1, &wpath, NULL);
4845 env->me_mfd = CreateFileW(wpath, oflags,
4846 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
4847 mode | FILE_FLAG_WRITE_THROUGH, NULL);
4851 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
4853 if (env->me_mfd == INVALID_HANDLE_VALUE) {
4858 DPRINTF(("opened dbenv %p", (void *) env));
4860 rc = mdb_env_share_locks(env, &excl);
4864 if (!(flags & MDB_RDONLY)) {
4866 int tsize = sizeof(MDB_txn), size = tsize + env->me_maxdbs *
4867 (sizeof(MDB_db)+sizeof(MDB_cursor *)+sizeof(unsigned int)+1);
4868 if ((env->me_pbuf = calloc(1, env->me_psize)) &&
4869 (txn = calloc(1, size)))
4871 txn->mt_dbs = (MDB_db *)((char *)txn + tsize);
4872 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
4873 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
4874 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
4876 txn->mt_dbxs = env->me_dbxs;
4877 txn->mt_flags = MDB_TXN_FINISHED;
4887 mdb_env_close0(env, excl);
4893 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
4895 mdb_env_close0(MDB_env *env, int excl)
4899 if (!(env->me_flags & MDB_ENV_ACTIVE))
4902 /* Doing this here since me_dbxs may not exist during mdb_env_close */
4904 for (i = env->me_maxdbs; --i >= CORE_DBS; )
4905 free(env->me_dbxs[i].md_name.mv_data);
4910 free(env->me_dbiseqs);
4911 free(env->me_dbflags);
4913 free(env->me_dirty_list);
4915 mdb_midl_free(env->me_free_pgs);
4917 if (env->me_flags & MDB_ENV_TXKEY) {
4918 pthread_key_delete(env->me_txkey);
4920 /* Delete our key from the global list */
4921 for (i=0; i<mdb_tls_nkeys; i++)
4922 if (mdb_tls_keys[i] == env->me_txkey) {
4923 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
4931 munmap(env->me_map, env->me_mapsize);
4933 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
4934 (void) close(env->me_mfd);
4935 if (env->me_fd != INVALID_HANDLE_VALUE)
4936 (void) close(env->me_fd);
4938 MDB_PID_T pid = env->me_pid;
4939 /* Clearing readers is done in this function because
4940 * me_txkey with its destructor must be disabled first.
4942 * We skip the the reader mutex, so we touch only
4943 * data owned by this process (me_close_readers and
4944 * our readers), and clear each reader atomically.
4946 for (i = env->me_close_readers; --i >= 0; )
4947 if (env->me_txns->mti_readers[i].mr_pid == pid)
4948 env->me_txns->mti_readers[i].mr_pid = 0;
4950 if (env->me_rmutex) {
4951 CloseHandle(env->me_rmutex);
4952 if (env->me_wmutex) CloseHandle(env->me_wmutex);
4954 /* Windows automatically destroys the mutexes when
4955 * the last handle closes.
4957 #elif defined(MDB_USE_POSIX_SEM)
4958 if (env->me_rmutex != SEM_FAILED) {
4959 sem_close(env->me_rmutex);
4960 if (env->me_wmutex != SEM_FAILED)
4961 sem_close(env->me_wmutex);
4962 /* If we have the filelock: If we are the
4963 * only remaining user, clean up semaphores.
4966 mdb_env_excl_lock(env, &excl);
4968 sem_unlink(env->me_txns->mti_rmname);
4969 sem_unlink(env->me_txns->mti_wmname);
4973 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
4975 if (env->me_lfd != INVALID_HANDLE_VALUE) {
4978 /* Unlock the lockfile. Windows would have unlocked it
4979 * after closing anyway, but not necessarily at once.
4981 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4984 (void) close(env->me_lfd);
4987 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
4991 mdb_env_close(MDB_env *env)
4998 VGMEMP_DESTROY(env);
4999 while ((dp = env->me_dpages) != NULL) {
5000 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
5001 env->me_dpages = dp->mp_next;
5005 mdb_env_close0(env, 0);
5009 /** Compare two items pointing at aligned size_t's */
5011 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
5013 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
5014 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
5017 /** Compare two items pointing at aligned unsigned int's.
5019 * This is also set as #MDB_INTEGERDUP|#MDB_DUPFIXED's #MDB_dbx.%md_dcmp,
5020 * but #mdb_cmp_clong() is called instead if the data type is size_t.
5023 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
5025 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
5026 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
5029 /** Compare two items pointing at unsigned ints of unknown alignment.
5030 * Nodes and keys are guaranteed to be 2-byte aligned.
5033 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
5035 #if BYTE_ORDER == LITTLE_ENDIAN
5036 unsigned short *u, *c;
5039 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5040 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
5043 } while(!x && u > (unsigned short *)a->mv_data);
5046 unsigned short *u, *c, *end;
5049 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5050 u = (unsigned short *)a->mv_data;
5051 c = (unsigned short *)b->mv_data;
5054 } while(!x && u < end);
5059 /** Compare two items lexically */
5061 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
5068 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5074 diff = memcmp(a->mv_data, b->mv_data, len);
5075 return diff ? diff : len_diff<0 ? -1 : len_diff;
5078 /** Compare two items in reverse byte order */
5080 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
5082 const unsigned char *p1, *p2, *p1_lim;
5086 p1_lim = (const unsigned char *)a->mv_data;
5087 p1 = (const unsigned char *)a->mv_data + a->mv_size;
5088 p2 = (const unsigned char *)b->mv_data + b->mv_size;
5090 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5096 while (p1 > p1_lim) {
5097 diff = *--p1 - *--p2;
5101 return len_diff<0 ? -1 : len_diff;
5104 /** Search for key within a page, using binary search.
5105 * Returns the smallest entry larger or equal to the key.
5106 * If exactp is non-null, stores whether the found entry was an exact match
5107 * in *exactp (1 or 0).
5108 * Updates the cursor index with the index of the found entry.
5109 * If no entry larger or equal to the key is found, returns NULL.
5112 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
5114 unsigned int i = 0, nkeys;
5117 MDB_page *mp = mc->mc_pg[mc->mc_top];
5118 MDB_node *node = NULL;
5123 nkeys = NUMKEYS(mp);
5125 DPRINTF(("searching %u keys in %s %spage %"Z"u",
5126 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
5129 low = IS_LEAF(mp) ? 0 : 1;
5131 cmp = mc->mc_dbx->md_cmp;
5133 /* Branch pages have no data, so if using integer keys,
5134 * alignment is guaranteed. Use faster mdb_cmp_int.
5136 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
5137 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
5144 nodekey.mv_size = mc->mc_db->md_pad;
5145 node = NODEPTR(mp, 0); /* fake */
5146 while (low <= high) {
5147 i = (low + high) >> 1;
5148 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
5149 rc = cmp(key, &nodekey);
5150 DPRINTF(("found leaf index %u [%s], rc = %i",
5151 i, DKEY(&nodekey), rc));
5160 while (low <= high) {
5161 i = (low + high) >> 1;
5163 node = NODEPTR(mp, i);
5164 nodekey.mv_size = NODEKSZ(node);
5165 nodekey.mv_data = NODEKEY(node);
5167 rc = cmp(key, &nodekey);
5170 DPRINTF(("found leaf index %u [%s], rc = %i",
5171 i, DKEY(&nodekey), rc));
5173 DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
5174 i, DKEY(&nodekey), NODEPGNO(node), rc));
5185 if (rc > 0) { /* Found entry is less than the key. */
5186 i++; /* Skip to get the smallest entry larger than key. */
5188 node = NODEPTR(mp, i);
5191 *exactp = (rc == 0 && nkeys > 0);
5192 /* store the key index */
5193 mc->mc_ki[mc->mc_top] = i;
5195 /* There is no entry larger or equal to the key. */
5198 /* nodeptr is fake for LEAF2 */
5204 mdb_cursor_adjust(MDB_cursor *mc, func)
5208 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5209 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
5216 /** Pop a page off the top of the cursor's stack. */
5218 mdb_cursor_pop(MDB_cursor *mc)
5221 DPRINTF(("popping page %"Z"u off db %d cursor %p",
5222 mc->mc_pg[mc->mc_top]->mp_pgno, DDBI(mc), (void *) mc));
5228 mc->mc_flags &= ~C_INITIALIZED;
5233 /** Push a page onto the top of the cursor's stack. */
5235 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
5237 DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
5238 DDBI(mc), (void *) mc));
5240 if (mc->mc_snum >= CURSOR_STACK) {
5241 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5242 return MDB_CURSOR_FULL;
5245 mc->mc_top = mc->mc_snum++;
5246 mc->mc_pg[mc->mc_top] = mp;
5247 mc->mc_ki[mc->mc_top] = 0;
5252 /** Find the address of the page corresponding to a given page number.
5253 * @param[in] mc the cursor accessing the page.
5254 * @param[in] pgno the page number for the page to retrieve.
5255 * @param[out] ret address of a pointer where the page's address will be stored.
5256 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
5257 * @return 0 on success, non-zero on failure.
5260 mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **ret, int *lvl)
5262 MDB_txn *txn = mc->mc_txn;
5263 MDB_env *env = txn->mt_env;
5267 if (! (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_WRITEMAP))) {
5271 MDB_ID2L dl = tx2->mt_u.dirty_list;
5273 /* Spilled pages were dirtied in this txn and flushed
5274 * because the dirty list got full. Bring this page
5275 * back in from the map (but don't unspill it here,
5276 * leave that unless page_touch happens again).
5278 if (tx2->mt_spill_pgs) {
5279 MDB_ID pn = pgno << 1;
5280 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
5281 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
5282 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5287 unsigned x = mdb_mid2l_search(dl, pgno);
5288 if (x <= dl[0].mid && dl[x].mid == pgno) {
5294 } while ((tx2 = tx2->mt_parent) != NULL);
5297 if (pgno < txn->mt_next_pgno) {
5299 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5301 DPRINTF(("page %"Z"u not found", pgno));
5302 txn->mt_flags |= MDB_TXN_ERROR;
5303 return MDB_PAGE_NOTFOUND;
5313 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
5314 * The cursor is at the root page, set up the rest of it.
5317 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
5319 MDB_page *mp = mc->mc_pg[mc->mc_top];
5323 while (IS_BRANCH(mp)) {
5327 DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
5328 /* Don't assert on branch pages in the FreeDB. We can get here
5329 * while in the process of rebalancing a FreeDB branch page; we must
5330 * let that proceed. ITS#8336
5332 mdb_cassert(mc, !mc->mc_dbi || NUMKEYS(mp) > 1);
5333 DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
5335 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
5337 if (flags & MDB_PS_LAST)
5338 i = NUMKEYS(mp) - 1;
5341 node = mdb_node_search(mc, key, &exact);
5343 i = NUMKEYS(mp) - 1;
5345 i = mc->mc_ki[mc->mc_top];
5347 mdb_cassert(mc, i > 0);
5351 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
5354 mdb_cassert(mc, i < NUMKEYS(mp));
5355 node = NODEPTR(mp, i);
5357 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
5360 mc->mc_ki[mc->mc_top] = i;
5361 if ((rc = mdb_cursor_push(mc, mp)))
5364 if (flags & MDB_PS_MODIFY) {
5365 if ((rc = mdb_page_touch(mc)) != 0)
5367 mp = mc->mc_pg[mc->mc_top];
5372 DPRINTF(("internal error, index points to a %02X page!?",
5374 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5375 return MDB_CORRUPTED;
5378 DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
5379 key ? DKEY(key) : "null"));
5380 mc->mc_flags |= C_INITIALIZED;
5381 mc->mc_flags &= ~C_EOF;
5386 /** Search for the lowest key under the current branch page.
5387 * This just bypasses a NUMKEYS check in the current page
5388 * before calling mdb_page_search_root(), because the callers
5389 * are all in situations where the current page is known to
5393 mdb_page_search_lowest(MDB_cursor *mc)
5395 MDB_page *mp = mc->mc_pg[mc->mc_top];
5396 MDB_node *node = NODEPTR(mp, 0);
5399 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
5402 mc->mc_ki[mc->mc_top] = 0;
5403 if ((rc = mdb_cursor_push(mc, mp)))
5405 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
5408 /** Search for the page a given key should be in.
5409 * Push it and its parent pages on the cursor stack.
5410 * @param[in,out] mc the cursor for this operation.
5411 * @param[in] key the key to search for, or NULL for first/last page.
5412 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
5413 * are touched (updated with new page numbers).
5414 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
5415 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
5416 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
5417 * @return 0 on success, non-zero on failure.
5420 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
5425 /* Make sure the txn is still viable, then find the root from
5426 * the txn's db table and set it as the root of the cursor's stack.
5428 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED) {
5429 DPUTS("transaction may not be used now");
5432 /* Make sure we're using an up-to-date root */
5433 if (*mc->mc_dbflag & DB_STALE) {
5435 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
5437 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
5438 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
5445 MDB_node *leaf = mdb_node_search(&mc2,
5446 &mc->mc_dbx->md_name, &exact);
5448 return MDB_NOTFOUND;
5449 if ((leaf->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
5450 return MDB_INCOMPATIBLE; /* not a named DB */
5451 rc = mdb_node_read(&mc2, leaf, &data);
5454 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
5456 /* The txn may not know this DBI, or another process may
5457 * have dropped and recreated the DB with other flags.
5459 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
5460 return MDB_INCOMPATIBLE;
5461 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
5463 *mc->mc_dbflag &= ~DB_STALE;
5465 root = mc->mc_db->md_root;
5467 if (root == P_INVALID) { /* Tree is empty. */
5468 DPUTS("tree is empty");
5469 return MDB_NOTFOUND;
5473 mdb_cassert(mc, root > 1);
5474 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
5475 if ((rc = mdb_page_get(mc, root, &mc->mc_pg[0], NULL)) != 0)
5481 DPRINTF(("db %d root page %"Z"u has flags 0x%X",
5482 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
5484 if (flags & MDB_PS_MODIFY) {
5485 if ((rc = mdb_page_touch(mc)))
5489 if (flags & MDB_PS_ROOTONLY)
5492 return mdb_page_search_root(mc, key, flags);
5496 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
5498 MDB_txn *txn = mc->mc_txn;
5499 pgno_t pg = mp->mp_pgno;
5500 unsigned x = 0, ovpages = mp->mp_pages;
5501 MDB_env *env = txn->mt_env;
5502 MDB_IDL sl = txn->mt_spill_pgs;
5503 MDB_ID pn = pg << 1;
5506 DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
5507 /* If the page is dirty or on the spill list we just acquired it,
5508 * so we should give it back to our current free list, if any.
5509 * Otherwise put it onto the list of pages we freed in this txn.
5511 * Won't create me_pghead: me_pglast must be inited along with it.
5512 * Unsupported in nested txns: They would need to hide the page
5513 * range in ancestor txns' dirty and spilled lists.
5515 if (env->me_pghead &&
5517 ((mp->mp_flags & P_DIRTY) ||
5518 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
5522 MDB_ID2 *dl, ix, iy;
5523 rc = mdb_midl_need(&env->me_pghead, ovpages);
5526 if (!(mp->mp_flags & P_DIRTY)) {
5527 /* This page is no longer spilled */
5534 /* Remove from dirty list */
5535 dl = txn->mt_u.dirty_list;
5537 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
5543 mdb_cassert(mc, x > 1);
5545 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
5546 txn->mt_flags |= MDB_TXN_ERROR;
5547 return MDB_CORRUPTED;
5550 txn->mt_dirty_room++;
5551 if (!(env->me_flags & MDB_WRITEMAP))
5552 mdb_dpage_free(env, mp);
5554 /* Insert in me_pghead */
5555 mop = env->me_pghead;
5556 j = mop[0] + ovpages;
5557 for (i = mop[0]; i && mop[i] < pg; i--)
5563 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
5567 mc->mc_db->md_overflow_pages -= ovpages;
5571 /** Return the data associated with a given node.
5572 * @param[in] mc The cursor for this operation.
5573 * @param[in] leaf The node being read.
5574 * @param[out] data Updated to point to the node's data.
5575 * @return 0 on success, non-zero on failure.
5578 mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data)
5580 MDB_page *omp; /* overflow page */
5584 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5585 data->mv_size = NODEDSZ(leaf);
5586 data->mv_data = NODEDATA(leaf);
5590 /* Read overflow data.
5592 data->mv_size = NODEDSZ(leaf);
5593 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
5594 if ((rc = mdb_page_get(mc, pgno, &omp, NULL)) != 0) {
5595 DPRINTF(("read overflow page %"Z"u failed", pgno));
5598 data->mv_data = METADATA(omp);
5604 mdb_get(MDB_txn *txn, MDB_dbi dbi,
5605 MDB_val *key, MDB_val *data)
5612 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
5614 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
5617 if (txn->mt_flags & MDB_TXN_BLOCKED)
5620 mdb_cursor_init(&mc, txn, dbi, &mx);
5621 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
5624 /** Find a sibling for a page.
5625 * Replaces the page at the top of the cursor's stack with the
5626 * specified sibling, if one exists.
5627 * @param[in] mc The cursor for this operation.
5628 * @param[in] move_right Non-zero if the right sibling is requested,
5629 * otherwise the left sibling.
5630 * @return 0 on success, non-zero on failure.
5633 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
5639 if (mc->mc_snum < 2) {
5640 return MDB_NOTFOUND; /* root has no siblings */
5644 DPRINTF(("parent page is page %"Z"u, index %u",
5645 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
5647 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
5648 : (mc->mc_ki[mc->mc_top] == 0)) {
5649 DPRINTF(("no more keys left, moving to %s sibling",
5650 move_right ? "right" : "left"));
5651 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
5652 /* undo cursor_pop before returning */
5659 mc->mc_ki[mc->mc_top]++;
5661 mc->mc_ki[mc->mc_top]--;
5662 DPRINTF(("just moving to %s index key %u",
5663 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
5665 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
5667 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5668 if ((rc = mdb_page_get(mc, NODEPGNO(indx), &mp, NULL)) != 0) {
5669 /* mc will be inconsistent if caller does mc_snum++ as above */
5670 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
5674 mdb_cursor_push(mc, mp);
5676 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
5681 /** Move the cursor to the next data item. */
5683 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5689 if ((mc->mc_flags & C_EOF) ||
5690 ((mc->mc_flags & C_DEL) && op == MDB_NEXT_DUP)) {
5691 return MDB_NOTFOUND;
5693 if (!(mc->mc_flags & C_INITIALIZED))
5694 return mdb_cursor_first(mc, key, data);
5696 mp = mc->mc_pg[mc->mc_top];
5698 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5699 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5700 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5701 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
5702 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
5703 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
5704 if (rc == MDB_SUCCESS)
5705 MDB_GET_KEY(leaf, key);
5710 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5711 if (op == MDB_NEXT_DUP)
5712 return MDB_NOTFOUND;
5716 DPRINTF(("cursor_next: top page is %"Z"u in cursor %p",
5717 mdb_dbg_pgno(mp), (void *) mc));
5718 if (mc->mc_flags & C_DEL) {
5719 mc->mc_flags ^= C_DEL;
5723 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
5724 DPUTS("=====> move to next sibling page");
5725 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5726 mc->mc_flags |= C_EOF;
5729 mp = mc->mc_pg[mc->mc_top];
5730 DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5732 mc->mc_ki[mc->mc_top]++;
5735 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5736 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5739 key->mv_size = mc->mc_db->md_pad;
5740 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5744 mdb_cassert(mc, IS_LEAF(mp));
5745 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5747 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5748 mdb_xcursor_init1(mc, leaf);
5751 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
5754 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5755 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5756 if (rc != MDB_SUCCESS)
5761 MDB_GET_KEY(leaf, key);
5765 /** Move the cursor to the previous data item. */
5767 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5773 if (!(mc->mc_flags & C_INITIALIZED)) {
5774 rc = mdb_cursor_last(mc, key, data);
5777 mc->mc_ki[mc->mc_top]++;
5780 mp = mc->mc_pg[mc->mc_top];
5782 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5783 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5784 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5785 if (op == MDB_PREV || op == MDB_PREV_DUP) {
5786 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
5787 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
5788 if (rc == MDB_SUCCESS) {
5789 MDB_GET_KEY(leaf, key);
5790 mc->mc_flags &= ~C_EOF;
5796 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5797 if (op == MDB_PREV_DUP)
5798 return MDB_NOTFOUND;
5802 DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p",
5803 mdb_dbg_pgno(mp), (void *) mc));
5805 mc->mc_flags &= ~(C_EOF|C_DEL);
5807 if (mc->mc_ki[mc->mc_top] == 0) {
5808 DPUTS("=====> move to prev sibling page");
5809 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
5812 mp = mc->mc_pg[mc->mc_top];
5813 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
5814 DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5816 mc->mc_ki[mc->mc_top]--;
5818 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5819 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5822 key->mv_size = mc->mc_db->md_pad;
5823 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5827 mdb_cassert(mc, IS_LEAF(mp));
5828 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5830 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5831 mdb_xcursor_init1(mc, leaf);
5834 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
5837 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5838 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5839 if (rc != MDB_SUCCESS)
5844 MDB_GET_KEY(leaf, key);
5848 /** Set the cursor on a specific data item. */
5850 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5851 MDB_cursor_op op, int *exactp)
5855 MDB_node *leaf = NULL;
5858 if (key->mv_size == 0)
5859 return MDB_BAD_VALSIZE;
5862 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5864 /* See if we're already on the right page */
5865 if (mc->mc_flags & C_INITIALIZED) {
5868 mp = mc->mc_pg[mc->mc_top];
5870 mc->mc_ki[mc->mc_top] = 0;
5871 return MDB_NOTFOUND;
5873 if (mp->mp_flags & P_LEAF2) {
5874 nodekey.mv_size = mc->mc_db->md_pad;
5875 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
5877 leaf = NODEPTR(mp, 0);
5878 MDB_GET_KEY2(leaf, nodekey);
5880 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5882 /* Probably happens rarely, but first node on the page
5883 * was the one we wanted.
5885 mc->mc_ki[mc->mc_top] = 0;
5892 unsigned int nkeys = NUMKEYS(mp);
5894 if (mp->mp_flags & P_LEAF2) {
5895 nodekey.mv_data = LEAF2KEY(mp,
5896 nkeys-1, nodekey.mv_size);
5898 leaf = NODEPTR(mp, nkeys-1);
5899 MDB_GET_KEY2(leaf, nodekey);
5901 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5903 /* last node was the one we wanted */
5904 mc->mc_ki[mc->mc_top] = nkeys-1;
5910 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
5911 /* This is definitely the right page, skip search_page */
5912 if (mp->mp_flags & P_LEAF2) {
5913 nodekey.mv_data = LEAF2KEY(mp,
5914 mc->mc_ki[mc->mc_top], nodekey.mv_size);
5916 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5917 MDB_GET_KEY2(leaf, nodekey);
5919 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5921 /* current node was the one we wanted */
5931 /* If any parents have right-sibs, search.
5932 * Otherwise, there's nothing further.
5934 for (i=0; i<mc->mc_top; i++)
5936 NUMKEYS(mc->mc_pg[i])-1)
5938 if (i == mc->mc_top) {
5939 /* There are no other pages */
5940 mc->mc_ki[mc->mc_top] = nkeys;
5941 return MDB_NOTFOUND;
5945 /* There are no other pages */
5946 mc->mc_ki[mc->mc_top] = 0;
5947 if (op == MDB_SET_RANGE && !exactp) {
5951 return MDB_NOTFOUND;
5957 rc = mdb_page_search(mc, key, 0);
5958 if (rc != MDB_SUCCESS)
5961 mp = mc->mc_pg[mc->mc_top];
5962 mdb_cassert(mc, IS_LEAF(mp));
5965 leaf = mdb_node_search(mc, key, exactp);
5966 if (exactp != NULL && !*exactp) {
5967 /* MDB_SET specified and not an exact match. */
5968 return MDB_NOTFOUND;
5972 DPUTS("===> inexact leaf not found, goto sibling");
5973 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5974 mc->mc_flags |= C_EOF;
5975 return rc; /* no entries matched */
5977 mp = mc->mc_pg[mc->mc_top];
5978 mdb_cassert(mc, IS_LEAF(mp));
5979 leaf = NODEPTR(mp, 0);
5983 mc->mc_flags |= C_INITIALIZED;
5984 mc->mc_flags &= ~C_EOF;
5987 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
5988 key->mv_size = mc->mc_db->md_pad;
5989 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5994 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5995 mdb_xcursor_init1(mc, leaf);
5998 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5999 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
6000 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6003 if (op == MDB_GET_BOTH) {
6009 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
6010 if (rc != MDB_SUCCESS)
6013 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
6016 if ((rc = mdb_node_read(mc, leaf, &olddata)) != MDB_SUCCESS)
6018 dcmp = mc->mc_dbx->md_dcmp;
6019 #if UINT_MAX < SIZE_MAX
6020 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
6021 dcmp = mdb_cmp_clong;
6023 rc = dcmp(data, &olddata);
6025 if (op == MDB_GET_BOTH || rc > 0)
6026 return MDB_NOTFOUND;
6033 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6034 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6039 /* The key already matches in all other cases */
6040 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
6041 MDB_GET_KEY(leaf, key);
6042 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
6047 /** Move the cursor to the first item in the database. */
6049 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6055 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6057 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6058 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
6059 if (rc != MDB_SUCCESS)
6062 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6064 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
6065 mc->mc_flags |= C_INITIALIZED;
6066 mc->mc_flags &= ~C_EOF;
6068 mc->mc_ki[mc->mc_top] = 0;
6070 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6071 key->mv_size = mc->mc_db->md_pad;
6072 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
6077 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6078 mdb_xcursor_init1(mc, leaf);
6079 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6083 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6087 MDB_GET_KEY(leaf, key);
6091 /** Move the cursor to the last item in the database. */
6093 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6099 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6101 if (!(mc->mc_flags & C_EOF)) {
6103 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6104 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
6105 if (rc != MDB_SUCCESS)
6108 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6111 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
6112 mc->mc_flags |= C_INITIALIZED|C_EOF;
6113 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6115 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6116 key->mv_size = mc->mc_db->md_pad;
6117 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
6122 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6123 mdb_xcursor_init1(mc, leaf);
6124 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
6128 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6133 MDB_GET_KEY(leaf, key);
6138 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6143 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
6148 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
6152 case MDB_GET_CURRENT:
6153 if (!(mc->mc_flags & C_INITIALIZED)) {
6156 MDB_page *mp = mc->mc_pg[mc->mc_top];
6157 int nkeys = NUMKEYS(mp);
6158 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
6159 mc->mc_ki[mc->mc_top] = nkeys;
6165 key->mv_size = mc->mc_db->md_pad;
6166 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6168 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6169 MDB_GET_KEY(leaf, key);
6171 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6172 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
6174 rc = mdb_node_read(mc, leaf, data);
6181 case MDB_GET_BOTH_RANGE:
6186 if (mc->mc_xcursor == NULL) {
6187 rc = MDB_INCOMPATIBLE;
6197 rc = mdb_cursor_set(mc, key, data, op,
6198 op == MDB_SET_RANGE ? NULL : &exact);
6201 case MDB_GET_MULTIPLE:
6202 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
6206 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6207 rc = MDB_INCOMPATIBLE;
6211 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
6212 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
6215 case MDB_NEXT_MULTIPLE:
6220 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6221 rc = MDB_INCOMPATIBLE;
6224 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
6225 if (rc == MDB_SUCCESS) {
6226 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6229 mx = &mc->mc_xcursor->mx_cursor;
6230 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
6232 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
6233 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
6239 case MDB_PREV_MULTIPLE:
6244 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6245 rc = MDB_INCOMPATIBLE;
6248 if (!(mc->mc_flags & C_INITIALIZED))
6249 rc = mdb_cursor_last(mc, key, data);
6252 if (rc == MDB_SUCCESS) {
6253 MDB_cursor *mx = &mc->mc_xcursor->mx_cursor;
6254 if (mx->mc_flags & C_INITIALIZED) {
6255 rc = mdb_cursor_sibling(mx, 0);
6256 if (rc == MDB_SUCCESS)
6265 case MDB_NEXT_NODUP:
6266 rc = mdb_cursor_next(mc, key, data, op);
6270 case MDB_PREV_NODUP:
6271 rc = mdb_cursor_prev(mc, key, data, op);
6274 rc = mdb_cursor_first(mc, key, data);
6277 mfunc = mdb_cursor_first;
6279 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
6283 if (mc->mc_xcursor == NULL) {
6284 rc = MDB_INCOMPATIBLE;
6288 MDB_node *leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6289 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6290 MDB_GET_KEY(leaf, key);
6291 rc = mdb_node_read(mc, leaf, data);
6295 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
6299 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
6302 rc = mdb_cursor_last(mc, key, data);
6305 mfunc = mdb_cursor_last;
6308 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
6313 if (mc->mc_flags & C_DEL)
6314 mc->mc_flags ^= C_DEL;
6319 /** Touch all the pages in the cursor stack. Set mc_top.
6320 * Makes sure all the pages are writable, before attempting a write operation.
6321 * @param[in] mc The cursor to operate on.
6324 mdb_cursor_touch(MDB_cursor *mc)
6326 int rc = MDB_SUCCESS;
6328 if (mc->mc_dbi >= CORE_DBS && !(*mc->mc_dbflag & (DB_DIRTY|DB_DUPDATA))) {
6329 /* Touch DB record of named DB */
6332 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
6334 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
6335 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
6338 *mc->mc_dbflag |= DB_DIRTY;
6343 rc = mdb_page_touch(mc);
6344 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
6345 mc->mc_top = mc->mc_snum-1;
6350 /** Do not spill pages to disk if txn is getting full, may fail instead */
6351 #define MDB_NOSPILL 0x8000
6354 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6358 MDB_node *leaf = NULL;
6359 MDB_page *fp, *mp, *sub_root = NULL;
6361 MDB_val xdata, *rdata, dkey, olddata;
6363 int do_sub = 0, insert_key, insert_data;
6364 unsigned int mcount = 0, dcount = 0, nospill;
6367 unsigned int nflags;
6370 if (mc == NULL || key == NULL)
6373 env = mc->mc_txn->mt_env;
6375 /* Check this first so counter will always be zero on any
6378 if (flags & MDB_MULTIPLE) {
6379 dcount = data[1].mv_size;
6380 data[1].mv_size = 0;
6381 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
6382 return MDB_INCOMPATIBLE;
6385 nospill = flags & MDB_NOSPILL;
6386 flags &= ~MDB_NOSPILL;
6388 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
6389 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6391 if (key->mv_size-1 >= ENV_MAXKEY(env))
6392 return MDB_BAD_VALSIZE;
6394 #if SIZE_MAX > MAXDATASIZE
6395 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
6396 return MDB_BAD_VALSIZE;
6398 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
6399 return MDB_BAD_VALSIZE;
6402 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
6403 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
6407 if (flags == MDB_CURRENT) {
6408 if (!(mc->mc_flags & C_INITIALIZED))
6411 } else if (mc->mc_db->md_root == P_INVALID) {
6412 /* new database, cursor has nothing to point to */
6415 mc->mc_flags &= ~C_INITIALIZED;
6420 if (flags & MDB_APPEND) {
6422 rc = mdb_cursor_last(mc, &k2, &d2);
6424 rc = mc->mc_dbx->md_cmp(key, &k2);
6427 mc->mc_ki[mc->mc_top]++;
6429 /* new key is <= last key */
6434 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
6436 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
6437 DPRINTF(("duplicate key [%s]", DKEY(key)));
6439 return MDB_KEYEXIST;
6441 if (rc && rc != MDB_NOTFOUND)
6445 if (mc->mc_flags & C_DEL)
6446 mc->mc_flags ^= C_DEL;
6448 /* Cursor is positioned, check for room in the dirty list */
6450 if (flags & MDB_MULTIPLE) {
6452 xdata.mv_size = data->mv_size * dcount;
6456 if ((rc2 = mdb_page_spill(mc, key, rdata)))
6460 if (rc == MDB_NO_ROOT) {
6462 /* new database, write a root leaf page */
6463 DPUTS("allocating new root leaf page");
6464 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
6467 mdb_cursor_push(mc, np);
6468 mc->mc_db->md_root = np->mp_pgno;
6469 mc->mc_db->md_depth++;
6470 *mc->mc_dbflag |= DB_DIRTY;
6471 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
6473 np->mp_flags |= P_LEAF2;
6474 mc->mc_flags |= C_INITIALIZED;
6476 /* make sure all cursor pages are writable */
6477 rc2 = mdb_cursor_touch(mc);
6482 insert_key = insert_data = rc;
6484 /* The key does not exist */
6485 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
6486 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
6487 LEAFSIZE(key, data) > env->me_nodemax)
6489 /* Too big for a node, insert in sub-DB. Set up an empty
6490 * "old sub-page" for prep_subDB to expand to a full page.
6492 fp_flags = P_LEAF|P_DIRTY;
6494 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
6495 fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
6496 olddata.mv_size = PAGEHDRSZ;
6500 /* there's only a key anyway, so this is a no-op */
6501 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6503 unsigned int ksize = mc->mc_db->md_pad;
6504 if (key->mv_size != ksize)
6505 return MDB_BAD_VALSIZE;
6506 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
6507 memcpy(ptr, key->mv_data, ksize);
6509 /* if overwriting slot 0 of leaf, need to
6510 * update branch key if there is a parent page
6512 if (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
6513 unsigned short dtop = 1;
6515 /* slot 0 is always an empty key, find real slot */
6516 while (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
6520 if (mc->mc_ki[mc->mc_top])
6521 rc2 = mdb_update_key(mc, key);
6532 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6533 olddata.mv_size = NODEDSZ(leaf);
6534 olddata.mv_data = NODEDATA(leaf);
6537 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
6538 /* Prepare (sub-)page/sub-DB to accept the new item,
6539 * if needed. fp: old sub-page or a header faking
6540 * it. mp: new (sub-)page. offset: growth in page
6541 * size. xdata: node data with new page or DB.
6543 unsigned i, offset = 0;
6544 mp = fp = xdata.mv_data = env->me_pbuf;
6545 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
6547 /* Was a single item before, must convert now */
6548 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6550 /* Just overwrite the current item */
6551 if (flags == MDB_CURRENT)
6553 dcmp = mc->mc_dbx->md_dcmp;
6554 #if UINT_MAX < SIZE_MAX
6555 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
6556 dcmp = mdb_cmp_clong;
6558 /* does data match? */
6559 if (!dcmp(data, &olddata)) {
6560 if (flags & (MDB_NODUPDATA|MDB_APPENDDUP))
6561 return MDB_KEYEXIST;
6566 /* Back up original data item */
6567 dkey.mv_size = olddata.mv_size;
6568 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
6570 /* Make sub-page header for the dup items, with dummy body */
6571 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
6572 fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
6573 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
6574 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6575 fp->mp_flags |= P_LEAF2;
6576 fp->mp_pad = data->mv_size;
6577 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
6579 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
6580 (dkey.mv_size & 1) + (data->mv_size & 1);
6582 fp->mp_upper = xdata.mv_size - PAGEBASE;
6583 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
6584 } else if (leaf->mn_flags & F_SUBDATA) {
6585 /* Data is on sub-DB, just store it */
6586 flags |= F_DUPDATA|F_SUBDATA;
6589 /* Data is on sub-page */
6590 fp = olddata.mv_data;
6593 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6594 offset = EVEN(NODESIZE + sizeof(indx_t) +
6598 offset = fp->mp_pad;
6599 if (SIZELEFT(fp) < offset) {
6600 offset *= 4; /* space for 4 more */
6603 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
6605 fp->mp_flags |= P_DIRTY;
6606 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
6607 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
6611 xdata.mv_size = olddata.mv_size + offset;
6614 fp_flags = fp->mp_flags;
6615 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
6616 /* Too big for a sub-page, convert to sub-DB */
6617 fp_flags &= ~P_SUBP;
6619 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6620 fp_flags |= P_LEAF2;
6621 dummy.md_pad = fp->mp_pad;
6622 dummy.md_flags = MDB_DUPFIXED;
6623 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6624 dummy.md_flags |= MDB_INTEGERKEY;
6630 dummy.md_branch_pages = 0;
6631 dummy.md_leaf_pages = 1;
6632 dummy.md_overflow_pages = 0;
6633 dummy.md_entries = NUMKEYS(fp);
6634 xdata.mv_size = sizeof(MDB_db);
6635 xdata.mv_data = &dummy;
6636 if ((rc = mdb_page_alloc(mc, 1, &mp)))
6638 offset = env->me_psize - olddata.mv_size;
6639 flags |= F_DUPDATA|F_SUBDATA;
6640 dummy.md_root = mp->mp_pgno;
6644 mp->mp_flags = fp_flags | P_DIRTY;
6645 mp->mp_pad = fp->mp_pad;
6646 mp->mp_lower = fp->mp_lower;
6647 mp->mp_upper = fp->mp_upper + offset;
6648 if (fp_flags & P_LEAF2) {
6649 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
6651 memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
6652 olddata.mv_size - fp->mp_upper - PAGEBASE);
6653 for (i=0; i<NUMKEYS(fp); i++)
6654 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
6662 mdb_node_del(mc, 0);
6666 /* LMDB passes F_SUBDATA in 'flags' to write a DB record */
6667 if ((leaf->mn_flags ^ flags) & F_SUBDATA)
6668 return MDB_INCOMPATIBLE;
6669 /* overflow page overwrites need special handling */
6670 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6673 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
6675 memcpy(&pg, olddata.mv_data, sizeof(pg));
6676 if ((rc2 = mdb_page_get(mc, pg, &omp, &level)) != 0)
6678 ovpages = omp->mp_pages;
6680 /* Is the ov page large enough? */
6681 if (ovpages >= dpages) {
6682 if (!(omp->mp_flags & P_DIRTY) &&
6683 (level || (env->me_flags & MDB_WRITEMAP)))
6685 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
6688 level = 0; /* dirty in this txn or clean */
6691 if (omp->mp_flags & P_DIRTY) {
6692 /* yes, overwrite it. Note in this case we don't
6693 * bother to try shrinking the page if the new data
6694 * is smaller than the overflow threshold.
6697 /* It is writable only in a parent txn */
6698 size_t sz = (size_t) env->me_psize * ovpages, off;
6699 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
6705 /* Note - this page is already counted in parent's dirty_room */
6706 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
6707 mdb_cassert(mc, rc2 == 0);
6708 /* Currently we make the page look as with put() in the
6709 * parent txn, in case the user peeks at MDB_RESERVEd
6710 * or unused parts. Some users treat ovpages specially.
6712 if (!(flags & MDB_RESERVE)) {
6713 /* Skip the part where LMDB will put *data.
6714 * Copy end of page, adjusting alignment so
6715 * compiler may copy words instead of bytes.
6717 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
6718 memcpy((size_t *)((char *)np + off),
6719 (size_t *)((char *)omp + off), sz - off);
6722 memcpy(np, omp, sz); /* Copy beginning of page */
6725 SETDSZ(leaf, data->mv_size);
6726 if (F_ISSET(flags, MDB_RESERVE))
6727 data->mv_data = METADATA(omp);
6729 memcpy(METADATA(omp), data->mv_data, data->mv_size);
6733 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
6735 } else if (data->mv_size == olddata.mv_size) {
6736 /* same size, just replace it. Note that we could
6737 * also reuse this node if the new data is smaller,
6738 * but instead we opt to shrink the node in that case.
6740 if (F_ISSET(flags, MDB_RESERVE))
6741 data->mv_data = olddata.mv_data;
6742 else if (!(mc->mc_flags & C_SUB))
6743 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
6745 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
6750 mdb_node_del(mc, 0);
6756 nflags = flags & NODE_ADD_FLAGS;
6757 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
6758 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
6759 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
6760 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
6762 nflags |= MDB_SPLIT_REPLACE;
6763 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
6765 /* There is room already in this leaf page. */
6766 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
6768 /* Adjust other cursors pointing to mp */
6769 MDB_cursor *m2, *m3;
6770 MDB_dbi dbi = mc->mc_dbi;
6771 unsigned i = mc->mc_top;
6772 MDB_page *mp = mc->mc_pg[i];
6774 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6775 if (mc->mc_flags & C_SUB)
6776 m3 = &m2->mc_xcursor->mx_cursor;
6779 if (m3 == mc || m3->mc_snum < mc->mc_snum || m3->mc_pg[i] != mp) continue;
6780 if (m3->mc_ki[i] >= mc->mc_ki[i] && insert_key) {
6783 if (XCURSOR_INITED(m3))
6784 XCURSOR_REFRESH(m3, mp, m3->mc_ki[i]);
6789 if (rc == MDB_SUCCESS) {
6790 /* Now store the actual data in the child DB. Note that we're
6791 * storing the user data in the keys field, so there are strict
6792 * size limits on dupdata. The actual data fields of the child
6793 * DB are all zero size.
6796 int xflags, new_dupdata;
6801 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6802 if (flags & MDB_CURRENT) {
6803 xflags = MDB_CURRENT|MDB_NOSPILL;
6805 mdb_xcursor_init1(mc, leaf);
6806 xflags = (flags & MDB_NODUPDATA) ?
6807 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
6810 mc->mc_xcursor->mx_cursor.mc_pg[0] = sub_root;
6811 new_dupdata = (int)dkey.mv_size;
6812 /* converted, write the original data first */
6814 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
6817 /* we've done our job */
6820 if (!(leaf->mn_flags & F_SUBDATA) || sub_root) {
6821 /* Adjust other cursors pointing to mp */
6823 MDB_xcursor *mx = mc->mc_xcursor;
6824 unsigned i = mc->mc_top;
6825 MDB_page *mp = mc->mc_pg[i];
6826 int nkeys = NUMKEYS(mp);
6828 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6829 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6830 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6831 if (m2->mc_pg[i] == mp) {
6832 if (m2->mc_ki[i] == mc->mc_ki[i]) {
6833 mdb_xcursor_init2(m2, mx, new_dupdata);
6834 } else if (!insert_key && m2->mc_ki[i] < nkeys) {
6835 XCURSOR_REFRESH(m2, mp, m2->mc_ki[i]);
6840 ecount = mc->mc_xcursor->mx_db.md_entries;
6841 if (flags & MDB_APPENDDUP)
6842 xflags |= MDB_APPEND;
6843 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
6844 if (flags & F_SUBDATA) {
6845 void *db = NODEDATA(leaf);
6846 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6848 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
6850 /* Increment count unless we just replaced an existing item. */
6852 mc->mc_db->md_entries++;
6854 /* Invalidate txn if we created an empty sub-DB */
6857 /* If we succeeded and the key didn't exist before,
6858 * make sure the cursor is marked valid.
6860 mc->mc_flags |= C_INITIALIZED;
6862 if (flags & MDB_MULTIPLE) {
6865 /* let caller know how many succeeded, if any */
6866 data[1].mv_size = mcount;
6867 if (mcount < dcount) {
6868 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
6869 insert_key = insert_data = 0;
6876 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
6879 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6884 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
6890 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
6891 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6893 if (!(mc->mc_flags & C_INITIALIZED))
6896 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6897 return MDB_NOTFOUND;
6899 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
6902 rc = mdb_cursor_touch(mc);
6906 mp = mc->mc_pg[mc->mc_top];
6909 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6911 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6912 if (flags & MDB_NODUPDATA) {
6913 /* mdb_cursor_del0() will subtract the final entry */
6914 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
6915 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
6917 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
6918 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6920 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
6923 /* If sub-DB still has entries, we're done */
6924 if (mc->mc_xcursor->mx_db.md_entries) {
6925 if (leaf->mn_flags & F_SUBDATA) {
6926 /* update subDB info */
6927 void *db = NODEDATA(leaf);
6928 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6931 /* shrink fake page */
6932 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
6933 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6934 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6935 /* fix other sub-DB cursors pointed at fake pages on this page */
6936 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6937 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6938 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6939 if (m2->mc_pg[mc->mc_top] == mp) {
6940 MDB_node *n2 = leaf;
6941 if (m2->mc_ki[mc->mc_top] != mc->mc_ki[mc->mc_top]) {
6942 n2 = NODEPTR(mp, m2->mc_ki[mc->mc_top]);
6943 if (n2->mn_flags & F_SUBDATA) continue;
6945 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
6949 mc->mc_db->md_entries--;
6952 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
6954 /* otherwise fall thru and delete the sub-DB */
6957 if (leaf->mn_flags & F_SUBDATA) {
6958 /* add all the child DB's pages to the free list */
6959 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6964 /* LMDB passes F_SUBDATA in 'flags' to delete a DB record */
6965 else if ((leaf->mn_flags ^ flags) & F_SUBDATA) {
6966 rc = MDB_INCOMPATIBLE;
6970 /* add overflow pages to free list */
6971 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6975 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
6976 if ((rc = mdb_page_get(mc, pg, &omp, NULL)) ||
6977 (rc = mdb_ovpage_free(mc, omp)))
6982 return mdb_cursor_del0(mc);
6985 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6989 /** Allocate and initialize new pages for a database.
6990 * @param[in] mc a cursor on the database being added to.
6991 * @param[in] flags flags defining what type of page is being allocated.
6992 * @param[in] num the number of pages to allocate. This is usually 1,
6993 * unless allocating overflow pages for a large record.
6994 * @param[out] mp Address of a page, or NULL on failure.
6995 * @return 0 on success, non-zero on failure.
6998 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
7003 if ((rc = mdb_page_alloc(mc, num, &np)))
7005 DPRINTF(("allocated new mpage %"Z"u, page size %u",
7006 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
7007 np->mp_flags = flags | P_DIRTY;
7008 np->mp_lower = (PAGEHDRSZ-PAGEBASE);
7009 np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
7012 mc->mc_db->md_branch_pages++;
7013 else if (IS_LEAF(np))
7014 mc->mc_db->md_leaf_pages++;
7015 else if (IS_OVERFLOW(np)) {
7016 mc->mc_db->md_overflow_pages += num;
7024 /** Calculate the size of a leaf node.
7025 * The size depends on the environment's page size; if a data item
7026 * is too large it will be put onto an overflow page and the node
7027 * size will only include the key and not the data. Sizes are always
7028 * rounded up to an even number of bytes, to guarantee 2-byte alignment
7029 * of the #MDB_node headers.
7030 * @param[in] env The environment handle.
7031 * @param[in] key The key for the node.
7032 * @param[in] data The data for the node.
7033 * @return The number of bytes needed to store the node.
7036 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
7040 sz = LEAFSIZE(key, data);
7041 if (sz > env->me_nodemax) {
7042 /* put on overflow page */
7043 sz -= data->mv_size - sizeof(pgno_t);
7046 return EVEN(sz + sizeof(indx_t));
7049 /** Calculate the size of a branch node.
7050 * The size should depend on the environment's page size but since
7051 * we currently don't support spilling large keys onto overflow
7052 * pages, it's simply the size of the #MDB_node header plus the
7053 * size of the key. Sizes are always rounded up to an even number
7054 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
7055 * @param[in] env The environment handle.
7056 * @param[in] key The key for the node.
7057 * @return The number of bytes needed to store the node.
7060 mdb_branch_size(MDB_env *env, MDB_val *key)
7065 if (sz > env->me_nodemax) {
7066 /* put on overflow page */
7067 /* not implemented */
7068 /* sz -= key->size - sizeof(pgno_t); */
7071 return sz + sizeof(indx_t);
7074 /** Add a node to the page pointed to by the cursor.
7075 * @param[in] mc The cursor for this operation.
7076 * @param[in] indx The index on the page where the new node should be added.
7077 * @param[in] key The key for the new node.
7078 * @param[in] data The data for the new node, if any.
7079 * @param[in] pgno The page number, if adding a branch node.
7080 * @param[in] flags Flags for the node.
7081 * @return 0 on success, non-zero on failure. Possible errors are:
7083 * <li>ENOMEM - failed to allocate overflow pages for the node.
7084 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
7085 * should never happen since all callers already calculate the
7086 * page's free space before calling this function.
7090 mdb_node_add(MDB_cursor *mc, indx_t indx,
7091 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
7094 size_t node_size = NODESIZE;
7098 MDB_page *mp = mc->mc_pg[mc->mc_top];
7099 MDB_page *ofp = NULL; /* overflow page */
7103 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
7105 DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
7106 IS_LEAF(mp) ? "leaf" : "branch",
7107 IS_SUBP(mp) ? "sub-" : "",
7108 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
7109 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
7112 /* Move higher keys up one slot. */
7113 int ksize = mc->mc_db->md_pad, dif;
7114 char *ptr = LEAF2KEY(mp, indx, ksize);
7115 dif = NUMKEYS(mp) - indx;
7117 memmove(ptr+ksize, ptr, dif*ksize);
7118 /* insert new key */
7119 memcpy(ptr, key->mv_data, ksize);
7121 /* Just using these for counting */
7122 mp->mp_lower += sizeof(indx_t);
7123 mp->mp_upper -= ksize - sizeof(indx_t);
7127 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
7129 node_size += key->mv_size;
7131 mdb_cassert(mc, key && data);
7132 if (F_ISSET(flags, F_BIGDATA)) {
7133 /* Data already on overflow page. */
7134 node_size += sizeof(pgno_t);
7135 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
7136 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
7138 /* Put data on overflow page. */
7139 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
7140 data->mv_size, node_size+data->mv_size));
7141 node_size = EVEN(node_size + sizeof(pgno_t));
7142 if ((ssize_t)node_size > room)
7144 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
7146 DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
7150 node_size += data->mv_size;
7153 node_size = EVEN(node_size);
7154 if ((ssize_t)node_size > room)
7158 /* Move higher pointers up one slot. */
7159 for (i = NUMKEYS(mp); i > indx; i--)
7160 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
7162 /* Adjust free space offsets. */
7163 ofs = mp->mp_upper - node_size;
7164 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
7165 mp->mp_ptrs[indx] = ofs;
7167 mp->mp_lower += sizeof(indx_t);
7169 /* Write the node data. */
7170 node = NODEPTR(mp, indx);
7171 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
7172 node->mn_flags = flags;
7174 SETDSZ(node,data->mv_size);
7179 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7182 ndata = NODEDATA(node);
7184 if (F_ISSET(flags, F_BIGDATA))
7185 memcpy(ndata, data->mv_data, sizeof(pgno_t));
7186 else if (F_ISSET(flags, MDB_RESERVE))
7187 data->mv_data = ndata;
7189 memcpy(ndata, data->mv_data, data->mv_size);
7191 memcpy(ndata, &ofp->mp_pgno, sizeof(pgno_t));
7192 ndata = METADATA(ofp);
7193 if (F_ISSET(flags, MDB_RESERVE))
7194 data->mv_data = ndata;
7196 memcpy(ndata, data->mv_data, data->mv_size);
7203 DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
7204 mdb_dbg_pgno(mp), NUMKEYS(mp)));
7205 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
7206 DPRINTF(("node size = %"Z"u", node_size));
7207 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7208 return MDB_PAGE_FULL;
7211 /** Delete the specified node from a page.
7212 * @param[in] mc Cursor pointing to the node to delete.
7213 * @param[in] ksize The size of a node. Only used if the page is
7214 * part of a #MDB_DUPFIXED database.
7217 mdb_node_del(MDB_cursor *mc, int ksize)
7219 MDB_page *mp = mc->mc_pg[mc->mc_top];
7220 indx_t indx = mc->mc_ki[mc->mc_top];
7222 indx_t i, j, numkeys, ptr;
7226 DPRINTF(("delete node %u on %s page %"Z"u", indx,
7227 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
7228 numkeys = NUMKEYS(mp);
7229 mdb_cassert(mc, indx < numkeys);
7232 int x = numkeys - 1 - indx;
7233 base = LEAF2KEY(mp, indx, ksize);
7235 memmove(base, base + ksize, x * ksize);
7236 mp->mp_lower -= sizeof(indx_t);
7237 mp->mp_upper += ksize - sizeof(indx_t);
7241 node = NODEPTR(mp, indx);
7242 sz = NODESIZE + node->mn_ksize;
7244 if (F_ISSET(node->mn_flags, F_BIGDATA))
7245 sz += sizeof(pgno_t);
7247 sz += NODEDSZ(node);
7251 ptr = mp->mp_ptrs[indx];
7252 for (i = j = 0; i < numkeys; i++) {
7254 mp->mp_ptrs[j] = mp->mp_ptrs[i];
7255 if (mp->mp_ptrs[i] < ptr)
7256 mp->mp_ptrs[j] += sz;
7261 base = (char *)mp + mp->mp_upper + PAGEBASE;
7262 memmove(base + sz, base, ptr - mp->mp_upper);
7264 mp->mp_lower -= sizeof(indx_t);
7268 /** Compact the main page after deleting a node on a subpage.
7269 * @param[in] mp The main page to operate on.
7270 * @param[in] indx The index of the subpage on the main page.
7273 mdb_node_shrink(MDB_page *mp, indx_t indx)
7278 indx_t delta, nsize, len, ptr;
7281 node = NODEPTR(mp, indx);
7282 sp = (MDB_page *)NODEDATA(node);
7283 delta = SIZELEFT(sp);
7284 nsize = NODEDSZ(node) - delta;
7286 /* Prepare to shift upward, set len = length(subpage part to shift) */
7290 return; /* do not make the node uneven-sized */
7292 xp = (MDB_page *)((char *)sp + delta); /* destination subpage */
7293 for (i = NUMKEYS(sp); --i >= 0; )
7294 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
7297 sp->mp_upper = sp->mp_lower;
7298 COPY_PGNO(sp->mp_pgno, mp->mp_pgno);
7299 SETDSZ(node, nsize);
7301 /* Shift <lower nodes...initial part of subpage> upward */
7302 base = (char *)mp + mp->mp_upper + PAGEBASE;
7303 memmove(base + delta, base, (char *)sp + len - base);
7305 ptr = mp->mp_ptrs[indx];
7306 for (i = NUMKEYS(mp); --i >= 0; ) {
7307 if (mp->mp_ptrs[i] <= ptr)
7308 mp->mp_ptrs[i] += delta;
7310 mp->mp_upper += delta;
7313 /** Initial setup of a sorted-dups cursor.
7314 * Sorted duplicates are implemented as a sub-database for the given key.
7315 * The duplicate data items are actually keys of the sub-database.
7316 * Operations on the duplicate data items are performed using a sub-cursor
7317 * initialized when the sub-database is first accessed. This function does
7318 * the preliminary setup of the sub-cursor, filling in the fields that
7319 * depend only on the parent DB.
7320 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
7323 mdb_xcursor_init0(MDB_cursor *mc)
7325 MDB_xcursor *mx = mc->mc_xcursor;
7327 mx->mx_cursor.mc_xcursor = NULL;
7328 mx->mx_cursor.mc_txn = mc->mc_txn;
7329 mx->mx_cursor.mc_db = &mx->mx_db;
7330 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
7331 mx->mx_cursor.mc_dbi = mc->mc_dbi;
7332 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
7333 mx->mx_cursor.mc_snum = 0;
7334 mx->mx_cursor.mc_top = 0;
7335 mx->mx_cursor.mc_flags = C_SUB;
7336 mx->mx_dbx.md_name.mv_size = 0;
7337 mx->mx_dbx.md_name.mv_data = NULL;
7338 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
7339 mx->mx_dbx.md_dcmp = NULL;
7340 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
7343 /** Final setup of a sorted-dups cursor.
7344 * Sets up the fields that depend on the data from the main cursor.
7345 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
7346 * @param[in] node The data containing the #MDB_db record for the
7347 * sorted-dup database.
7350 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
7352 MDB_xcursor *mx = mc->mc_xcursor;
7354 if (node->mn_flags & F_SUBDATA) {
7355 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
7356 mx->mx_cursor.mc_pg[0] = 0;
7357 mx->mx_cursor.mc_snum = 0;
7358 mx->mx_cursor.mc_top = 0;
7359 mx->mx_cursor.mc_flags = C_SUB;
7361 MDB_page *fp = NODEDATA(node);
7362 mx->mx_db.md_pad = 0;
7363 mx->mx_db.md_flags = 0;
7364 mx->mx_db.md_depth = 1;
7365 mx->mx_db.md_branch_pages = 0;
7366 mx->mx_db.md_leaf_pages = 1;
7367 mx->mx_db.md_overflow_pages = 0;
7368 mx->mx_db.md_entries = NUMKEYS(fp);
7369 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
7370 mx->mx_cursor.mc_snum = 1;
7371 mx->mx_cursor.mc_top = 0;
7372 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
7373 mx->mx_cursor.mc_pg[0] = fp;
7374 mx->mx_cursor.mc_ki[0] = 0;
7375 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7376 mx->mx_db.md_flags = MDB_DUPFIXED;
7377 mx->mx_db.md_pad = fp->mp_pad;
7378 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
7379 mx->mx_db.md_flags |= MDB_INTEGERKEY;
7382 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
7383 mx->mx_db.md_root));
7384 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DUPDATA;
7385 #if UINT_MAX < SIZE_MAX
7386 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
7387 mx->mx_dbx.md_cmp = mdb_cmp_clong;
7392 /** Fixup a sorted-dups cursor due to underlying update.
7393 * Sets up some fields that depend on the data from the main cursor.
7394 * Almost the same as init1, but skips initialization steps if the
7395 * xcursor had already been used.
7396 * @param[in] mc The main cursor whose sorted-dups cursor is to be fixed up.
7397 * @param[in] src_mx The xcursor of an up-to-date cursor.
7398 * @param[in] new_dupdata True if converting from a non-#F_DUPDATA item.
7401 mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int new_dupdata)
7403 MDB_xcursor *mx = mc->mc_xcursor;
7406 mx->mx_cursor.mc_snum = 1;
7407 mx->mx_cursor.mc_top = 0;
7408 mx->mx_cursor.mc_flags |= C_INITIALIZED;
7409 mx->mx_cursor.mc_ki[0] = 0;
7410 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DUPDATA;
7411 #if UINT_MAX < SIZE_MAX
7412 mx->mx_dbx.md_cmp = src_mx->mx_dbx.md_cmp;
7414 } else if (!(mx->mx_cursor.mc_flags & C_INITIALIZED)) {
7417 mx->mx_db = src_mx->mx_db;
7418 mx->mx_cursor.mc_pg[0] = src_mx->mx_cursor.mc_pg[0];
7419 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
7420 mx->mx_db.md_root));
7423 /** Initialize a cursor for a given transaction and database. */
7425 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
7428 mc->mc_backup = NULL;
7431 mc->mc_db = &txn->mt_dbs[dbi];
7432 mc->mc_dbx = &txn->mt_dbxs[dbi];
7433 mc->mc_dbflag = &txn->mt_dbflags[dbi];
7439 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
7440 mdb_tassert(txn, mx != NULL);
7441 mc->mc_xcursor = mx;
7442 mdb_xcursor_init0(mc);
7444 mc->mc_xcursor = NULL;
7446 if (*mc->mc_dbflag & DB_STALE) {
7447 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
7452 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
7455 size_t size = sizeof(MDB_cursor);
7457 if (!ret || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
7460 if (txn->mt_flags & MDB_TXN_BLOCKED)
7463 if (dbi == FREE_DBI && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
7466 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
7467 size += sizeof(MDB_xcursor);
7469 if ((mc = malloc(size)) != NULL) {
7470 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
7471 if (txn->mt_cursors) {
7472 mc->mc_next = txn->mt_cursors[dbi];
7473 txn->mt_cursors[dbi] = mc;
7474 mc->mc_flags |= C_UNTRACK;
7486 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
7488 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi, DB_VALID))
7491 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
7494 if (txn->mt_flags & MDB_TXN_BLOCKED)
7497 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
7501 /* Return the count of duplicate data items for the current key */
7503 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
7507 if (mc == NULL || countp == NULL)
7510 if (mc->mc_xcursor == NULL)
7511 return MDB_INCOMPATIBLE;
7513 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
7516 if (!(mc->mc_flags & C_INITIALIZED))
7519 if (!mc->mc_snum || (mc->mc_flags & C_EOF))
7520 return MDB_NOTFOUND;
7522 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7523 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7526 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
7529 *countp = mc->mc_xcursor->mx_db.md_entries;
7535 mdb_cursor_close(MDB_cursor *mc)
7537 if (mc && !mc->mc_backup) {
7538 /* remove from txn, if tracked */
7539 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
7540 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
7541 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
7543 *prev = mc->mc_next;
7550 mdb_cursor_txn(MDB_cursor *mc)
7552 if (!mc) return NULL;
7557 mdb_cursor_dbi(MDB_cursor *mc)
7562 /** Replace the key for a branch node with a new key.
7563 * @param[in] mc Cursor pointing to the node to operate on.
7564 * @param[in] key The new key to use.
7565 * @return 0 on success, non-zero on failure.
7568 mdb_update_key(MDB_cursor *mc, MDB_val *key)
7574 int delta, ksize, oksize;
7575 indx_t ptr, i, numkeys, indx;
7578 indx = mc->mc_ki[mc->mc_top];
7579 mp = mc->mc_pg[mc->mc_top];
7580 node = NODEPTR(mp, indx);
7581 ptr = mp->mp_ptrs[indx];
7585 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
7586 k2.mv_data = NODEKEY(node);
7587 k2.mv_size = node->mn_ksize;
7588 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
7590 mdb_dkey(&k2, kbuf2),
7596 /* Sizes must be 2-byte aligned. */
7597 ksize = EVEN(key->mv_size);
7598 oksize = EVEN(node->mn_ksize);
7599 delta = ksize - oksize;
7601 /* Shift node contents if EVEN(key length) changed. */
7603 if (delta > 0 && SIZELEFT(mp) < delta) {
7605 /* not enough space left, do a delete and split */
7606 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
7607 pgno = NODEPGNO(node);
7608 mdb_node_del(mc, 0);
7609 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
7612 numkeys = NUMKEYS(mp);
7613 for (i = 0; i < numkeys; i++) {
7614 if (mp->mp_ptrs[i] <= ptr)
7615 mp->mp_ptrs[i] -= delta;
7618 base = (char *)mp + mp->mp_upper + PAGEBASE;
7619 len = ptr - mp->mp_upper + NODESIZE;
7620 memmove(base - delta, base, len);
7621 mp->mp_upper -= delta;
7623 node = NODEPTR(mp, indx);
7626 /* But even if no shift was needed, update ksize */
7627 if (node->mn_ksize != key->mv_size)
7628 node->mn_ksize = key->mv_size;
7631 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7637 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
7639 /** Perform \b act while tracking temporary cursor \b mn */
7640 #define WITH_CURSOR_TRACKING(mn, act) do { \
7641 MDB_cursor dummy, *tracked, **tp = &(mn).mc_txn->mt_cursors[mn.mc_dbi]; \
7642 if ((mn).mc_flags & C_SUB) { \
7643 dummy.mc_flags = C_INITIALIZED; \
7644 dummy.mc_xcursor = (MDB_xcursor *)&(mn); \
7649 tracked->mc_next = *tp; \
7652 *tp = tracked->mc_next; \
7655 /** Move a node from csrc to cdst.
7658 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft)
7665 unsigned short flags;
7669 /* Mark src and dst as dirty. */
7670 if ((rc = mdb_page_touch(csrc)) ||
7671 (rc = mdb_page_touch(cdst)))
7674 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7675 key.mv_size = csrc->mc_db->md_pad;
7676 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
7678 data.mv_data = NULL;
7682 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
7683 mdb_cassert(csrc, !((size_t)srcnode & 1));
7684 srcpg = NODEPGNO(srcnode);
7685 flags = srcnode->mn_flags;
7686 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7687 unsigned int snum = csrc->mc_snum;
7689 /* must find the lowest key below src */
7690 rc = mdb_page_search_lowest(csrc);
7693 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7694 key.mv_size = csrc->mc_db->md_pad;
7695 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7697 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7698 key.mv_size = NODEKSZ(s2);
7699 key.mv_data = NODEKEY(s2);
7701 csrc->mc_snum = snum--;
7702 csrc->mc_top = snum;
7704 key.mv_size = NODEKSZ(srcnode);
7705 key.mv_data = NODEKEY(srcnode);
7707 data.mv_size = NODEDSZ(srcnode);
7708 data.mv_data = NODEDATA(srcnode);
7710 mn.mc_xcursor = NULL;
7711 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
7712 unsigned int snum = cdst->mc_snum;
7715 /* must find the lowest key below dst */
7716 mdb_cursor_copy(cdst, &mn);
7717 rc = mdb_page_search_lowest(&mn);
7720 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7721 bkey.mv_size = mn.mc_db->md_pad;
7722 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
7724 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7725 bkey.mv_size = NODEKSZ(s2);
7726 bkey.mv_data = NODEKEY(s2);
7728 mn.mc_snum = snum--;
7731 rc = mdb_update_key(&mn, &bkey);
7736 DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
7737 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
7738 csrc->mc_ki[csrc->mc_top],
7740 csrc->mc_pg[csrc->mc_top]->mp_pgno,
7741 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
7743 /* Add the node to the destination page.
7745 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
7746 if (rc != MDB_SUCCESS)
7749 /* Delete the node from the source page.
7751 mdb_node_del(csrc, key.mv_size);
7754 /* Adjust other cursors pointing to mp */
7755 MDB_cursor *m2, *m3;
7756 MDB_dbi dbi = csrc->mc_dbi;
7757 MDB_page *mpd, *mps;
7759 mps = csrc->mc_pg[csrc->mc_top];
7760 /* If we're adding on the left, bump others up */
7762 mpd = cdst->mc_pg[csrc->mc_top];
7763 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7764 if (csrc->mc_flags & C_SUB)
7765 m3 = &m2->mc_xcursor->mx_cursor;
7768 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
7771 m3->mc_pg[csrc->mc_top] == mpd &&
7772 m3->mc_ki[csrc->mc_top] >= cdst->mc_ki[csrc->mc_top]) {
7773 m3->mc_ki[csrc->mc_top]++;
7776 m3->mc_pg[csrc->mc_top] == mps &&
7777 m3->mc_ki[csrc->mc_top] == csrc->mc_ki[csrc->mc_top]) {
7778 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
7779 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7780 m3->mc_ki[csrc->mc_top-1]++;
7782 if (XCURSOR_INITED(m3) && IS_LEAF(mps))
7783 XCURSOR_REFRESH(m3, m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
7786 /* Adding on the right, bump others down */
7788 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7789 if (csrc->mc_flags & C_SUB)
7790 m3 = &m2->mc_xcursor->mx_cursor;
7793 if (m3 == csrc) continue;
7794 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
7796 if (m3->mc_pg[csrc->mc_top] == mps) {
7797 if (!m3->mc_ki[csrc->mc_top]) {
7798 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
7799 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7800 m3->mc_ki[csrc->mc_top-1]--;
7802 m3->mc_ki[csrc->mc_top]--;
7804 if (XCURSOR_INITED(m3) && IS_LEAF(mps))
7805 XCURSOR_REFRESH(m3, m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
7811 /* Update the parent separators.
7813 if (csrc->mc_ki[csrc->mc_top] == 0) {
7814 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
7815 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7816 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7818 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7819 key.mv_size = NODEKSZ(srcnode);
7820 key.mv_data = NODEKEY(srcnode);
7822 DPRINTF(("update separator for source page %"Z"u to [%s]",
7823 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
7824 mdb_cursor_copy(csrc, &mn);
7827 /* We want mdb_rebalance to find mn when doing fixups */
7828 WITH_CURSOR_TRACKING(mn,
7829 rc = mdb_update_key(&mn, &key));
7833 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7835 indx_t ix = csrc->mc_ki[csrc->mc_top];
7836 nullkey.mv_size = 0;
7837 csrc->mc_ki[csrc->mc_top] = 0;
7838 rc = mdb_update_key(csrc, &nullkey);
7839 csrc->mc_ki[csrc->mc_top] = ix;
7840 mdb_cassert(csrc, rc == MDB_SUCCESS);
7844 if (cdst->mc_ki[cdst->mc_top] == 0) {
7845 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
7846 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7847 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
7849 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
7850 key.mv_size = NODEKSZ(srcnode);
7851 key.mv_data = NODEKEY(srcnode);
7853 DPRINTF(("update separator for destination page %"Z"u to [%s]",
7854 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
7855 mdb_cursor_copy(cdst, &mn);
7858 /* We want mdb_rebalance to find mn when doing fixups */
7859 WITH_CURSOR_TRACKING(mn,
7860 rc = mdb_update_key(&mn, &key));
7864 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
7866 indx_t ix = cdst->mc_ki[cdst->mc_top];
7867 nullkey.mv_size = 0;
7868 cdst->mc_ki[cdst->mc_top] = 0;
7869 rc = mdb_update_key(cdst, &nullkey);
7870 cdst->mc_ki[cdst->mc_top] = ix;
7871 mdb_cassert(cdst, rc == MDB_SUCCESS);
7878 /** Merge one page into another.
7879 * The nodes from the page pointed to by \b csrc will
7880 * be copied to the page pointed to by \b cdst and then
7881 * the \b csrc page will be freed.
7882 * @param[in] csrc Cursor pointing to the source page.
7883 * @param[in] cdst Cursor pointing to the destination page.
7884 * @return 0 on success, non-zero on failure.
7887 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
7889 MDB_page *psrc, *pdst;
7896 psrc = csrc->mc_pg[csrc->mc_top];
7897 pdst = cdst->mc_pg[cdst->mc_top];
7899 DPRINTF(("merging page %"Z"u into %"Z"u", psrc->mp_pgno, pdst->mp_pgno));
7901 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
7902 mdb_cassert(csrc, cdst->mc_snum > 1);
7904 /* Mark dst as dirty. */
7905 if ((rc = mdb_page_touch(cdst)))
7908 /* get dst page again now that we've touched it. */
7909 pdst = cdst->mc_pg[cdst->mc_top];
7911 /* Move all nodes from src to dst.
7913 j = nkeys = NUMKEYS(pdst);
7914 if (IS_LEAF2(psrc)) {
7915 key.mv_size = csrc->mc_db->md_pad;
7916 key.mv_data = METADATA(psrc);
7917 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7918 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
7919 if (rc != MDB_SUCCESS)
7921 key.mv_data = (char *)key.mv_data + key.mv_size;
7924 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7925 srcnode = NODEPTR(psrc, i);
7926 if (i == 0 && IS_BRANCH(psrc)) {
7929 mdb_cursor_copy(csrc, &mn);
7930 mn.mc_xcursor = NULL;
7931 /* must find the lowest key below src */
7932 rc = mdb_page_search_lowest(&mn);
7935 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7936 key.mv_size = mn.mc_db->md_pad;
7937 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
7939 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7940 key.mv_size = NODEKSZ(s2);
7941 key.mv_data = NODEKEY(s2);
7944 key.mv_size = srcnode->mn_ksize;
7945 key.mv_data = NODEKEY(srcnode);
7948 data.mv_size = NODEDSZ(srcnode);
7949 data.mv_data = NODEDATA(srcnode);
7950 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
7951 if (rc != MDB_SUCCESS)
7956 DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
7957 pdst->mp_pgno, NUMKEYS(pdst),
7958 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
7960 /* Unlink the src page from parent and add to free list.
7963 mdb_node_del(csrc, 0);
7964 if (csrc->mc_ki[csrc->mc_top] == 0) {
7966 rc = mdb_update_key(csrc, &key);
7974 psrc = csrc->mc_pg[csrc->mc_top];
7975 /* If not operating on FreeDB, allow this page to be reused
7976 * in this txn. Otherwise just add to free list.
7978 rc = mdb_page_loose(csrc, psrc);
7982 csrc->mc_db->md_leaf_pages--;
7984 csrc->mc_db->md_branch_pages--;
7986 /* Adjust other cursors pointing to mp */
7987 MDB_cursor *m2, *m3;
7988 MDB_dbi dbi = csrc->mc_dbi;
7989 unsigned int top = csrc->mc_top;
7991 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7992 if (csrc->mc_flags & C_SUB)
7993 m3 = &m2->mc_xcursor->mx_cursor;
7996 if (m3 == csrc) continue;
7997 if (m3->mc_snum < csrc->mc_snum) continue;
7998 if (m3->mc_pg[top] == psrc) {
7999 m3->mc_pg[top] = pdst;
8000 m3->mc_ki[top] += nkeys;
8001 m3->mc_ki[top-1] = cdst->mc_ki[top-1];
8002 } else if (m3->mc_pg[top-1] == csrc->mc_pg[top-1] &&
8003 m3->mc_ki[top-1] > csrc->mc_ki[top-1]) {
8006 if (XCURSOR_INITED(m3) && IS_LEAF(psrc))
8007 XCURSOR_REFRESH(m3, m3->mc_pg[top], m3->mc_ki[top]);
8011 unsigned int snum = cdst->mc_snum;
8012 uint16_t depth = cdst->mc_db->md_depth;
8013 mdb_cursor_pop(cdst);
8014 rc = mdb_rebalance(cdst);
8015 /* Did the tree height change? */
8016 if (depth != cdst->mc_db->md_depth)
8017 snum += cdst->mc_db->md_depth - depth;
8018 cdst->mc_snum = snum;
8019 cdst->mc_top = snum-1;
8024 /** Copy the contents of a cursor.
8025 * @param[in] csrc The cursor to copy from.
8026 * @param[out] cdst The cursor to copy to.
8029 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
8033 cdst->mc_txn = csrc->mc_txn;
8034 cdst->mc_dbi = csrc->mc_dbi;
8035 cdst->mc_db = csrc->mc_db;
8036 cdst->mc_dbx = csrc->mc_dbx;
8037 cdst->mc_snum = csrc->mc_snum;
8038 cdst->mc_top = csrc->mc_top;
8039 cdst->mc_flags = csrc->mc_flags;
8041 for (i=0; i<csrc->mc_snum; i++) {
8042 cdst->mc_pg[i] = csrc->mc_pg[i];
8043 cdst->mc_ki[i] = csrc->mc_ki[i];
8047 /** Rebalance the tree after a delete operation.
8048 * @param[in] mc Cursor pointing to the page where rebalancing
8050 * @return 0 on success, non-zero on failure.
8053 mdb_rebalance(MDB_cursor *mc)
8057 unsigned int ptop, minkeys, thresh;
8061 if (IS_BRANCH(mc->mc_pg[mc->mc_top])) {
8066 thresh = FILL_THRESHOLD;
8068 DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
8069 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
8070 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
8071 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
8073 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= thresh &&
8074 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
8075 DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
8076 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
8080 if (mc->mc_snum < 2) {
8081 MDB_page *mp = mc->mc_pg[0];
8083 DPUTS("Can't rebalance a subpage, ignoring");
8086 if (NUMKEYS(mp) == 0) {
8087 DPUTS("tree is completely empty");
8088 mc->mc_db->md_root = P_INVALID;
8089 mc->mc_db->md_depth = 0;
8090 mc->mc_db->md_leaf_pages = 0;
8091 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
8094 /* Adjust cursors pointing to mp */
8097 mc->mc_flags &= ~C_INITIALIZED;
8099 MDB_cursor *m2, *m3;
8100 MDB_dbi dbi = mc->mc_dbi;
8102 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8103 if (mc->mc_flags & C_SUB)
8104 m3 = &m2->mc_xcursor->mx_cursor;
8107 if (!(m3->mc_flags & C_INITIALIZED) || (m3->mc_snum < mc->mc_snum))
8109 if (m3->mc_pg[0] == mp) {
8112 m3->mc_flags &= ~C_INITIALIZED;
8116 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
8118 DPUTS("collapsing root page!");
8119 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
8122 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
8123 rc = mdb_page_get(mc, mc->mc_db->md_root, &mc->mc_pg[0], NULL);
8126 mc->mc_db->md_depth--;
8127 mc->mc_db->md_branch_pages--;
8128 mc->mc_ki[0] = mc->mc_ki[1];
8129 for (i = 1; i<mc->mc_db->md_depth; i++) {
8130 mc->mc_pg[i] = mc->mc_pg[i+1];
8131 mc->mc_ki[i] = mc->mc_ki[i+1];
8134 /* Adjust other cursors pointing to mp */
8135 MDB_cursor *m2, *m3;
8136 MDB_dbi dbi = mc->mc_dbi;
8138 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8139 if (mc->mc_flags & C_SUB)
8140 m3 = &m2->mc_xcursor->mx_cursor;
8143 if (m3 == mc) continue;
8144 if (!(m3->mc_flags & C_INITIALIZED))
8146 if (m3->mc_pg[0] == mp) {
8147 for (i=0; i<mc->mc_db->md_depth; i++) {
8148 m3->mc_pg[i] = m3->mc_pg[i+1];
8149 m3->mc_ki[i] = m3->mc_ki[i+1];
8157 DPUTS("root page doesn't need rebalancing");
8161 /* The parent (branch page) must have at least 2 pointers,
8162 * otherwise the tree is invalid.
8164 ptop = mc->mc_top-1;
8165 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
8167 /* Leaf page fill factor is below the threshold.
8168 * Try to move keys from left or right neighbor, or
8169 * merge with a neighbor page.
8174 mdb_cursor_copy(mc, &mn);
8175 mn.mc_xcursor = NULL;
8177 oldki = mc->mc_ki[mc->mc_top];
8178 if (mc->mc_ki[ptop] == 0) {
8179 /* We're the leftmost leaf in our parent.
8181 DPUTS("reading right neighbor");
8183 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
8184 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
8187 mn.mc_ki[mn.mc_top] = 0;
8188 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
8191 /* There is at least one neighbor to the left.
8193 DPUTS("reading left neighbor");
8195 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
8196 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
8199 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
8200 mc->mc_ki[mc->mc_top] = 0;
8204 DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
8205 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
8206 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
8208 /* If the neighbor page is above threshold and has enough keys,
8209 * move one key from it. Otherwise we should try to merge them.
8210 * (A branch page must never have less than 2 keys.)
8212 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= thresh && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
8213 rc = mdb_node_move(&mn, mc, fromleft);
8215 /* if we inserted on left, bump position up */
8220 rc = mdb_page_merge(&mn, mc);
8222 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
8223 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
8224 /* We want mdb_rebalance to find mn when doing fixups */
8225 WITH_CURSOR_TRACKING(mn,
8226 rc = mdb_page_merge(mc, &mn));
8227 mdb_cursor_copy(&mn, mc);
8229 mc->mc_flags &= ~C_EOF;
8231 mc->mc_ki[mc->mc_top] = oldki;
8235 /** Complete a delete operation started by #mdb_cursor_del(). */
8237 mdb_cursor_del0(MDB_cursor *mc)
8243 MDB_cursor *m2, *m3;
8244 MDB_dbi dbi = mc->mc_dbi;
8246 ki = mc->mc_ki[mc->mc_top];
8247 mp = mc->mc_pg[mc->mc_top];
8248 mdb_node_del(mc, mc->mc_db->md_pad);
8249 mc->mc_db->md_entries--;
8251 /* Adjust other cursors pointing to mp */
8252 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8253 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
8254 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8256 if (m3 == mc || m3->mc_snum < mc->mc_snum)
8258 if (m3->mc_pg[mc->mc_top] == mp) {
8259 if (m3->mc_ki[mc->mc_top] == ki) {
8260 m3->mc_flags |= C_DEL;
8261 if (mc->mc_db->md_flags & MDB_DUPSORT) {
8262 /* Sub-cursor referred into dataset which is gone */
8263 m3->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
8266 } else if (m3->mc_ki[mc->mc_top] > ki) {
8267 m3->mc_ki[mc->mc_top]--;
8269 if (XCURSOR_INITED(m3))
8270 XCURSOR_REFRESH(m3, m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
8274 rc = mdb_rebalance(mc);
8276 if (rc == MDB_SUCCESS) {
8277 /* DB is totally empty now, just bail out.
8278 * Other cursors adjustments were already done
8279 * by mdb_rebalance and aren't needed here.
8284 mp = mc->mc_pg[mc->mc_top];
8285 nkeys = NUMKEYS(mp);
8287 /* Adjust other cursors pointing to mp */
8288 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
8289 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
8290 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8292 if (m3->mc_snum < mc->mc_snum)
8294 if (m3->mc_pg[mc->mc_top] == mp) {
8295 /* if m3 points past last node in page, find next sibling */
8296 if (m3->mc_ki[mc->mc_top] >= mc->mc_ki[mc->mc_top]) {
8297 if (m3->mc_ki[mc->mc_top] >= nkeys) {
8298 rc = mdb_cursor_sibling(m3, 1);
8299 if (rc == MDB_NOTFOUND) {
8300 m3->mc_flags |= C_EOF;
8305 if (mc->mc_db->md_flags & MDB_DUPSORT) {
8306 MDB_node *node = NODEPTR(m3->mc_pg[m3->mc_top], m3->mc_ki[m3->mc_top]);
8307 /* If this node is a fake page, it needs to be reinited
8308 * because its data has moved. But just reset mc_pg[0]
8309 * if the xcursor is already live.
8311 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) {
8312 if (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)
8313 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
8315 mdb_xcursor_init1(m3, node);
8321 mc->mc_flags |= C_DEL;
8325 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8330 mdb_del(MDB_txn *txn, MDB_dbi dbi,
8331 MDB_val *key, MDB_val *data)
8333 if (!key || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
8336 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
8337 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
8339 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
8340 /* must ignore any data */
8344 return mdb_del0(txn, dbi, key, data, 0);
8348 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
8349 MDB_val *key, MDB_val *data, unsigned flags)
8354 MDB_val rdata, *xdata;
8358 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
8360 mdb_cursor_init(&mc, txn, dbi, &mx);
8369 flags |= MDB_NODUPDATA;
8371 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
8373 /* let mdb_page_split know about this cursor if needed:
8374 * delete will trigger a rebalance; if it needs to move
8375 * a node from one page to another, it will have to
8376 * update the parent's separator key(s). If the new sepkey
8377 * is larger than the current one, the parent page may
8378 * run out of space, triggering a split. We need this
8379 * cursor to be consistent until the end of the rebalance.
8381 mc.mc_flags |= C_UNTRACK;
8382 mc.mc_next = txn->mt_cursors[dbi];
8383 txn->mt_cursors[dbi] = &mc;
8384 rc = mdb_cursor_del(&mc, flags);
8385 txn->mt_cursors[dbi] = mc.mc_next;
8390 /** Split a page and insert a new node.
8391 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
8392 * The cursor will be updated to point to the actual page and index where
8393 * the node got inserted after the split.
8394 * @param[in] newkey The key for the newly inserted node.
8395 * @param[in] newdata The data for the newly inserted node.
8396 * @param[in] newpgno The page number, if the new node is a branch node.
8397 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
8398 * @return 0 on success, non-zero on failure.
8401 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
8402 unsigned int nflags)
8405 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
8408 int i, j, split_indx, nkeys, pmax;
8409 MDB_env *env = mc->mc_txn->mt_env;
8411 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
8412 MDB_page *copy = NULL;
8413 MDB_page *mp, *rp, *pp;
8418 mp = mc->mc_pg[mc->mc_top];
8419 newindx = mc->mc_ki[mc->mc_top];
8420 nkeys = NUMKEYS(mp);
8422 DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i/%i",
8423 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
8424 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
8426 /* Create a right sibling. */
8427 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
8429 rp->mp_pad = mp->mp_pad;
8430 DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
8432 /* Usually when splitting the root page, the cursor
8433 * height is 1. But when called from mdb_update_key,
8434 * the cursor height may be greater because it walks
8435 * up the stack while finding the branch slot to update.
8437 if (mc->mc_top < 1) {
8438 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
8440 /* shift current top to make room for new parent */
8441 for (i=mc->mc_snum; i>0; i--) {
8442 mc->mc_pg[i] = mc->mc_pg[i-1];
8443 mc->mc_ki[i] = mc->mc_ki[i-1];
8447 mc->mc_db->md_root = pp->mp_pgno;
8448 DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
8449 new_root = mc->mc_db->md_depth++;
8451 /* Add left (implicit) pointer. */
8452 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
8453 /* undo the pre-push */
8454 mc->mc_pg[0] = mc->mc_pg[1];
8455 mc->mc_ki[0] = mc->mc_ki[1];
8456 mc->mc_db->md_root = mp->mp_pgno;
8457 mc->mc_db->md_depth--;
8464 ptop = mc->mc_top-1;
8465 DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
8468 mdb_cursor_copy(mc, &mn);
8469 mn.mc_xcursor = NULL;
8470 mn.mc_pg[mn.mc_top] = rp;
8471 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
8473 if (nflags & MDB_APPEND) {
8474 mn.mc_ki[mn.mc_top] = 0;
8476 split_indx = newindx;
8480 split_indx = (nkeys+1) / 2;
8485 unsigned int lsize, rsize, ksize;
8486 /* Move half of the keys to the right sibling */
8487 x = mc->mc_ki[mc->mc_top] - split_indx;
8488 ksize = mc->mc_db->md_pad;
8489 split = LEAF2KEY(mp, split_indx, ksize);
8490 rsize = (nkeys - split_indx) * ksize;
8491 lsize = (nkeys - split_indx) * sizeof(indx_t);
8492 mp->mp_lower -= lsize;
8493 rp->mp_lower += lsize;
8494 mp->mp_upper += rsize - lsize;
8495 rp->mp_upper -= rsize - lsize;
8496 sepkey.mv_size = ksize;
8497 if (newindx == split_indx) {
8498 sepkey.mv_data = newkey->mv_data;
8500 sepkey.mv_data = split;
8503 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
8504 memcpy(rp->mp_ptrs, split, rsize);
8505 sepkey.mv_data = rp->mp_ptrs;
8506 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
8507 memcpy(ins, newkey->mv_data, ksize);
8508 mp->mp_lower += sizeof(indx_t);
8509 mp->mp_upper -= ksize - sizeof(indx_t);
8512 memcpy(rp->mp_ptrs, split, x * ksize);
8513 ins = LEAF2KEY(rp, x, ksize);
8514 memcpy(ins, newkey->mv_data, ksize);
8515 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
8516 rp->mp_lower += sizeof(indx_t);
8517 rp->mp_upper -= ksize - sizeof(indx_t);
8518 mc->mc_ki[mc->mc_top] = x;
8521 int psize, nsize, k;
8522 /* Maximum free space in an empty page */
8523 pmax = env->me_psize - PAGEHDRSZ;
8525 nsize = mdb_leaf_size(env, newkey, newdata);
8527 nsize = mdb_branch_size(env, newkey);
8528 nsize = EVEN(nsize);
8530 /* grab a page to hold a temporary copy */
8531 copy = mdb_page_malloc(mc->mc_txn, 1);
8536 copy->mp_pgno = mp->mp_pgno;
8537 copy->mp_flags = mp->mp_flags;
8538 copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
8539 copy->mp_upper = env->me_psize - PAGEBASE;
8541 /* prepare to insert */
8542 for (i=0, j=0; i<nkeys; i++) {
8544 copy->mp_ptrs[j++] = 0;
8546 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
8549 /* When items are relatively large the split point needs
8550 * to be checked, because being off-by-one will make the
8551 * difference between success or failure in mdb_node_add.
8553 * It's also relevant if a page happens to be laid out
8554 * such that one half of its nodes are all "small" and
8555 * the other half of its nodes are "large." If the new
8556 * item is also "large" and falls on the half with
8557 * "large" nodes, it also may not fit.
8559 * As a final tweak, if the new item goes on the last
8560 * spot on the page (and thus, onto the new page), bias
8561 * the split so the new page is emptier than the old page.
8562 * This yields better packing during sequential inserts.
8564 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
8565 /* Find split point */
8567 if (newindx <= split_indx || newindx >= nkeys) {
8569 k = newindx >= nkeys ? nkeys : split_indx+1+IS_LEAF(mp);
8574 for (; i!=k; i+=j) {
8579 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8580 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
8582 if (F_ISSET(node->mn_flags, F_BIGDATA))
8583 psize += sizeof(pgno_t);
8585 psize += NODEDSZ(node);
8587 psize = EVEN(psize);
8589 if (psize > pmax || i == k-j) {
8590 split_indx = i + (j<0);
8595 if (split_indx == newindx) {
8596 sepkey.mv_size = newkey->mv_size;
8597 sepkey.mv_data = newkey->mv_data;
8599 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
8600 sepkey.mv_size = node->mn_ksize;
8601 sepkey.mv_data = NODEKEY(node);
8606 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
8608 /* Copy separator key to the parent.
8610 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
8611 int snum = mc->mc_snum;
8615 /* We want other splits to find mn when doing fixups */
8616 WITH_CURSOR_TRACKING(mn,
8617 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0));
8622 if (mc->mc_snum > snum) {
8625 /* Right page might now have changed parent.
8626 * Check if left page also changed parent.
8628 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8629 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8630 for (i=0; i<ptop; i++) {
8631 mc->mc_pg[i] = mn.mc_pg[i];
8632 mc->mc_ki[i] = mn.mc_ki[i];
8634 mc->mc_pg[ptop] = mn.mc_pg[ptop];
8635 if (mn.mc_ki[ptop]) {
8636 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
8638 /* find right page's left sibling */
8639 mc->mc_ki[ptop] = mn.mc_ki[ptop];
8640 mdb_cursor_sibling(mc, 0);
8645 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
8648 if (rc != MDB_SUCCESS) {
8651 if (nflags & MDB_APPEND) {
8652 mc->mc_pg[mc->mc_top] = rp;
8653 mc->mc_ki[mc->mc_top] = 0;
8654 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
8657 for (i=0; i<mc->mc_top; i++)
8658 mc->mc_ki[i] = mn.mc_ki[i];
8659 } else if (!IS_LEAF2(mp)) {
8661 mc->mc_pg[mc->mc_top] = rp;
8666 rkey.mv_data = newkey->mv_data;
8667 rkey.mv_size = newkey->mv_size;
8673 /* Update index for the new key. */
8674 mc->mc_ki[mc->mc_top] = j;
8676 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8677 rkey.mv_data = NODEKEY(node);
8678 rkey.mv_size = node->mn_ksize;
8680 xdata.mv_data = NODEDATA(node);
8681 xdata.mv_size = NODEDSZ(node);
8684 pgno = NODEPGNO(node);
8685 flags = node->mn_flags;
8688 if (!IS_LEAF(mp) && j == 0) {
8689 /* First branch index doesn't need key data. */
8693 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
8699 mc->mc_pg[mc->mc_top] = copy;
8704 } while (i != split_indx);
8706 nkeys = NUMKEYS(copy);
8707 for (i=0; i<nkeys; i++)
8708 mp->mp_ptrs[i] = copy->mp_ptrs[i];
8709 mp->mp_lower = copy->mp_lower;
8710 mp->mp_upper = copy->mp_upper;
8711 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
8712 env->me_psize - copy->mp_upper - PAGEBASE);
8714 /* reset back to original page */
8715 if (newindx < split_indx) {
8716 mc->mc_pg[mc->mc_top] = mp;
8718 mc->mc_pg[mc->mc_top] = rp;
8720 /* Make sure mc_ki is still valid.
8722 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8723 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8724 for (i=0; i<=ptop; i++) {
8725 mc->mc_pg[i] = mn.mc_pg[i];
8726 mc->mc_ki[i] = mn.mc_ki[i];
8730 if (nflags & MDB_RESERVE) {
8731 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
8732 if (!(node->mn_flags & F_BIGDATA))
8733 newdata->mv_data = NODEDATA(node);
8736 if (newindx >= split_indx) {
8737 mc->mc_pg[mc->mc_top] = rp;
8739 /* Make sure mc_ki is still valid.
8741 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8742 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8743 for (i=0; i<=ptop; i++) {
8744 mc->mc_pg[i] = mn.mc_pg[i];
8745 mc->mc_ki[i] = mn.mc_ki[i];
8752 /* Adjust other cursors pointing to mp */
8753 MDB_cursor *m2, *m3;
8754 MDB_dbi dbi = mc->mc_dbi;
8755 nkeys = NUMKEYS(mp);
8757 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8758 if (mc->mc_flags & C_SUB)
8759 m3 = &m2->mc_xcursor->mx_cursor;
8764 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8768 /* sub cursors may be on different DB */
8769 if (m3->mc_pg[0] != mp)
8772 for (k=new_root; k>=0; k--) {
8773 m3->mc_ki[k+1] = m3->mc_ki[k];
8774 m3->mc_pg[k+1] = m3->mc_pg[k];
8776 if (m3->mc_ki[0] >= nkeys) {
8781 m3->mc_pg[0] = mc->mc_pg[0];
8785 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
8786 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
8787 m3->mc_ki[mc->mc_top]++;
8788 if (m3->mc_ki[mc->mc_top] >= nkeys) {
8789 m3->mc_pg[mc->mc_top] = rp;
8790 m3->mc_ki[mc->mc_top] -= nkeys;
8791 for (i=0; i<mc->mc_top; i++) {
8792 m3->mc_ki[i] = mn.mc_ki[i];
8793 m3->mc_pg[i] = mn.mc_pg[i];
8796 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
8797 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
8800 if (XCURSOR_INITED(m3) && IS_LEAF(mp))
8801 XCURSOR_REFRESH(m3, m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
8804 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
8807 if (copy) /* tmp page */
8808 mdb_page_free(env, copy);
8810 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8815 mdb_put(MDB_txn *txn, MDB_dbi dbi,
8816 MDB_val *key, MDB_val *data, unsigned int flags)
8822 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
8825 if (flags & ~(MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP))
8828 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
8829 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
8831 mdb_cursor_init(&mc, txn, dbi, &mx);
8832 mc.mc_next = txn->mt_cursors[dbi];
8833 txn->mt_cursors[dbi] = &mc;
8834 rc = mdb_cursor_put(&mc, key, data, flags);
8835 txn->mt_cursors[dbi] = mc.mc_next;
8840 #define MDB_WBUF (1024*1024)
8842 #define MDB_EOF 0x10 /**< #mdb_env_copyfd1() is done reading */
8844 /** State needed for a double-buffering compacting copy. */
8845 typedef struct mdb_copy {
8848 pthread_mutex_t mc_mutex;
8849 pthread_cond_t mc_cond; /**< Condition variable for #mc_new */
8854 pgno_t mc_next_pgno;
8856 int mc_toggle; /**< Buffer number in provider */
8857 int mc_new; /**< (0-2 buffers to write) | (#MDB_EOF at end) */
8858 /** Error code. Never cleared if set. Both threads can set nonzero
8859 * to fail the copy. Not mutex-protected, LMDB expects atomic int.
8861 volatile int mc_error;
8864 /** Dedicated writer thread for compacting copy. */
8865 static THREAD_RET ESECT CALL_CONV
8866 mdb_env_copythr(void *arg)
8870 int toggle = 0, wsize, rc;
8873 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8876 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8879 pthread_mutex_lock(&my->mc_mutex);
8882 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8883 if (my->mc_new == 0 + MDB_EOF) /* 0 buffers, just EOF */
8885 wsize = my->mc_wlen[toggle];
8886 ptr = my->mc_wbuf[toggle];
8889 while (wsize > 0 && !my->mc_error) {
8890 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
8894 } else if (len > 0) {
8907 /* If there's an overflow page tail, write it too */
8908 if (my->mc_olen[toggle]) {
8909 wsize = my->mc_olen[toggle];
8910 ptr = my->mc_over[toggle];
8911 my->mc_olen[toggle] = 0;
8914 my->mc_wlen[toggle] = 0;
8916 /* Return the empty buffer to provider */
8918 pthread_cond_signal(&my->mc_cond);
8920 pthread_mutex_unlock(&my->mc_mutex);
8921 return (THREAD_RET)0;
8925 /** Give buffer and/or #MDB_EOF to writer thread, await unused buffer.
8927 * @param[in] my control structure.
8928 * @param[in] adjust (1 to hand off 1 buffer) | (MDB_EOF when ending).
8931 mdb_env_cthr_toggle(mdb_copy *my, int adjust)
8933 pthread_mutex_lock(&my->mc_mutex);
8934 my->mc_new += adjust;
8935 pthread_cond_signal(&my->mc_cond);
8936 while (my->mc_new & 2) /* both buffers in use */
8937 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8938 pthread_mutex_unlock(&my->mc_mutex);
8940 my->mc_toggle ^= (adjust & 1);
8941 /* Both threads reset mc_wlen, to be safe from threading errors */
8942 my->mc_wlen[my->mc_toggle] = 0;
8943 return my->mc_error;
8946 /** Depth-first tree traversal for compacting copy.
8947 * @param[in] my control structure.
8948 * @param[in,out] pg database root.
8949 * @param[in] flags includes #F_DUPDATA if it is a sorted-duplicate sub-DB.
8952 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
8954 MDB_cursor mc = {0};
8956 MDB_page *mo, *mp, *leaf;
8961 /* Empty DB, nothing to do */
8962 if (*pg == P_INVALID)
8966 mc.mc_txn = my->mc_txn;
8968 rc = mdb_page_get(&mc, *pg, &mc.mc_pg[0], NULL);
8971 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
8975 /* Make cursor pages writable */
8976 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
8980 for (i=0; i<mc.mc_top; i++) {
8981 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
8982 mc.mc_pg[i] = (MDB_page *)ptr;
8983 ptr += my->mc_env->me_psize;
8986 /* This is writable space for a leaf page. Usually not needed. */
8987 leaf = (MDB_page *)ptr;
8989 toggle = my->mc_toggle;
8990 while (mc.mc_snum > 0) {
8992 mp = mc.mc_pg[mc.mc_top];
8996 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
8997 for (i=0; i<n; i++) {
8998 ni = NODEPTR(mp, i);
8999 if (ni->mn_flags & F_BIGDATA) {
9003 /* Need writable leaf */
9005 mc.mc_pg[mc.mc_top] = leaf;
9006 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
9008 ni = NODEPTR(mp, i);
9011 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9012 memcpy(NODEDATA(ni), &my->mc_next_pgno, sizeof(pgno_t));
9013 rc = mdb_page_get(&mc, pg, &omp, NULL);
9016 if (my->mc_wlen[toggle] >= MDB_WBUF) {
9017 rc = mdb_env_cthr_toggle(my, 1);
9020 toggle = my->mc_toggle;
9022 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
9023 memcpy(mo, omp, my->mc_env->me_psize);
9024 mo->mp_pgno = my->mc_next_pgno;
9025 my->mc_next_pgno += omp->mp_pages;
9026 my->mc_wlen[toggle] += my->mc_env->me_psize;
9027 if (omp->mp_pages > 1) {
9028 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
9029 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
9030 rc = mdb_env_cthr_toggle(my, 1);
9033 toggle = my->mc_toggle;
9035 } else if (ni->mn_flags & F_SUBDATA) {
9038 /* Need writable leaf */
9040 mc.mc_pg[mc.mc_top] = leaf;
9041 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
9043 ni = NODEPTR(mp, i);
9046 memcpy(&db, NODEDATA(ni), sizeof(db));
9047 my->mc_toggle = toggle;
9048 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
9051 toggle = my->mc_toggle;
9052 memcpy(NODEDATA(ni), &db, sizeof(db));
9057 mc.mc_ki[mc.mc_top]++;
9058 if (mc.mc_ki[mc.mc_top] < n) {
9061 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
9063 rc = mdb_page_get(&mc, pg, &mp, NULL);
9068 mc.mc_ki[mc.mc_top] = 0;
9069 if (IS_BRANCH(mp)) {
9070 /* Whenever we advance to a sibling branch page,
9071 * we must proceed all the way down to its first leaf.
9073 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
9076 mc.mc_pg[mc.mc_top] = mp;
9080 if (my->mc_wlen[toggle] >= MDB_WBUF) {
9081 rc = mdb_env_cthr_toggle(my, 1);
9084 toggle = my->mc_toggle;
9086 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
9087 mdb_page_copy(mo, mp, my->mc_env->me_psize);
9088 mo->mp_pgno = my->mc_next_pgno++;
9089 my->mc_wlen[toggle] += my->mc_env->me_psize;
9091 /* Update parent if there is one */
9092 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
9093 SETPGNO(ni, mo->mp_pgno);
9094 mdb_cursor_pop(&mc);
9096 /* Otherwise we're done */
9106 /** Copy environment with compaction. */
9108 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
9113 MDB_txn *txn = NULL;
9115 pgno_t root, new_root;
9116 int rc = MDB_SUCCESS;
9119 if (!(my.mc_mutex = CreateMutex(NULL, FALSE, NULL)) ||
9120 !(my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL))) {
9124 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_os_psize);
9125 if (my.mc_wbuf[0] == NULL) {
9126 /* _aligned_malloc() sets errno, but we use Windows error codes */
9127 rc = ERROR_NOT_ENOUGH_MEMORY;
9131 if ((rc = pthread_mutex_init(&my.mc_mutex, NULL)) != 0)
9133 if ((rc = pthread_cond_init(&my.mc_cond, NULL)) != 0)
9135 #ifdef HAVE_MEMALIGN
9136 my.mc_wbuf[0] = memalign(env->me_os_psize, MDB_WBUF*2);
9137 if (my.mc_wbuf[0] == NULL) {
9144 if ((rc = posix_memalign(&p, env->me_os_psize, MDB_WBUF*2)) != 0)
9150 memset(my.mc_wbuf[0], 0, MDB_WBUF*2);
9151 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
9152 my.mc_next_pgno = NUM_METAS;
9155 rc = THREAD_CREATE(thr, mdb_env_copythr, &my);
9159 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
9163 mp = (MDB_page *)my.mc_wbuf[0];
9164 memset(mp, 0, NUM_METAS * env->me_psize);
9166 mp->mp_flags = P_META;
9167 mm = (MDB_meta *)METADATA(mp);
9168 mdb_env_init_meta0(env, mm);
9169 mm->mm_address = env->me_metas[0]->mm_address;
9171 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
9173 mp->mp_flags = P_META;
9174 *(MDB_meta *)METADATA(mp) = *mm;
9175 mm = (MDB_meta *)METADATA(mp);
9177 /* Set metapage 1 with current main DB */
9178 root = new_root = txn->mt_dbs[MAIN_DBI].md_root;
9179 if (root != P_INVALID) {
9180 /* Count free pages + freeDB pages. Subtract from last_pg
9181 * to find the new last_pg, which also becomes the new root.
9183 MDB_ID freecount = 0;
9186 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
9187 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
9188 freecount += *(MDB_ID *)data.mv_data;
9189 if (rc != MDB_NOTFOUND)
9191 freecount += txn->mt_dbs[FREE_DBI].md_branch_pages +
9192 txn->mt_dbs[FREE_DBI].md_leaf_pages +
9193 txn->mt_dbs[FREE_DBI].md_overflow_pages;
9195 new_root = txn->mt_next_pgno - 1 - freecount;
9196 mm->mm_last_pg = new_root;
9197 mm->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
9198 mm->mm_dbs[MAIN_DBI].md_root = new_root;
9200 /* When the DB is empty, handle it specially to
9201 * fix any breakage like page leaks from ITS#8174.
9203 mm->mm_dbs[MAIN_DBI].md_flags = txn->mt_dbs[MAIN_DBI].md_flags;
9205 if (root != P_INVALID || mm->mm_dbs[MAIN_DBI].md_flags) {
9206 mm->mm_txnid = 1; /* use metapage 1 */
9209 my.mc_wlen[0] = env->me_psize * NUM_METAS;
9211 rc = mdb_env_cwalk(&my, &root, 0);
9212 if (rc == MDB_SUCCESS && root != new_root) {
9213 rc = MDB_INCOMPATIBLE; /* page leak or corrupt DB */
9219 mdb_env_cthr_toggle(&my, 1 | MDB_EOF);
9220 rc = THREAD_FINISH(thr);
9225 if (my.mc_wbuf[0]) _aligned_free(my.mc_wbuf[0]);
9226 if (my.mc_cond) CloseHandle(my.mc_cond);
9227 if (my.mc_mutex) CloseHandle(my.mc_mutex);
9229 free(my.mc_wbuf[0]);
9230 pthread_cond_destroy(&my.mc_cond);
9232 pthread_mutex_destroy(&my.mc_mutex);
9234 return rc ? rc : my.mc_error;
9237 /** Copy environment as-is. */
9239 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
9241 MDB_txn *txn = NULL;
9242 mdb_mutexref_t wmutex = NULL;
9248 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
9252 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
9255 /* Do the lock/unlock of the reader mutex before starting the
9256 * write txn. Otherwise other read txns could block writers.
9258 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
9263 /* We must start the actual read txn after blocking writers */
9264 mdb_txn_end(txn, MDB_END_RESET_TMP);
9266 /* Temporarily block writers until we snapshot the meta pages */
9267 wmutex = env->me_wmutex;
9268 if (LOCK_MUTEX(rc, env, wmutex))
9271 rc = mdb_txn_renew0(txn);
9273 UNLOCK_MUTEX(wmutex);
9278 wsize = env->me_psize * NUM_METAS;
9282 DO_WRITE(rc, fd, ptr, w2, len);
9286 } else if (len > 0) {
9292 /* Non-blocking or async handles are not supported */
9298 UNLOCK_MUTEX(wmutex);
9303 w3 = txn->mt_next_pgno * env->me_psize;
9306 if ((rc = mdb_fsize(env->me_fd, &fsize)))
9313 if (wsize > MAX_WRITE)
9317 DO_WRITE(rc, fd, ptr, w2, len);
9321 } else if (len > 0) {
9338 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
9340 if (flags & MDB_CP_COMPACT)
9341 return mdb_env_copyfd1(env, fd);
9343 return mdb_env_copyfd0(env, fd);
9347 mdb_env_copyfd(MDB_env *env, HANDLE fd)
9349 return mdb_env_copyfd2(env, fd, 0);
9353 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
9357 HANDLE newfd = INVALID_HANDLE_VALUE;
9362 if (env->me_flags & MDB_NOSUBDIR) {
9363 lpath = (char *)path;
9366 len += sizeof(DATANAME);
9367 lpath = malloc(len);
9370 sprintf(lpath, "%s" DATANAME, path);
9373 /* The destination path must exist, but the destination file must not.
9374 * We don't want the OS to cache the writes, since the source data is
9375 * already in the OS cache.
9378 rc = utf8_to_utf16(lpath, -1, &wpath, NULL);
9381 newfd = CreateFileW(wpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
9382 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
9385 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
9387 if (newfd == INVALID_HANDLE_VALUE) {
9392 if (env->me_psize >= env->me_os_psize) {
9394 /* Set O_DIRECT if the file system supports it */
9395 if ((rc = fcntl(newfd, F_GETFL)) != -1)
9396 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
9398 #ifdef F_NOCACHE /* __APPLE__ */
9399 rc = fcntl(newfd, F_NOCACHE, 1);
9407 rc = mdb_env_copyfd2(env, newfd, flags);
9410 if (!(env->me_flags & MDB_NOSUBDIR))
9412 if (newfd != INVALID_HANDLE_VALUE)
9413 if (close(newfd) < 0 && rc == MDB_SUCCESS)
9420 mdb_env_copy(MDB_env *env, const char *path)
9422 return mdb_env_copy2(env, path, 0);
9426 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
9428 if (flag & ~CHANGEABLE)
9431 env->me_flags |= flag;
9433 env->me_flags &= ~flag;
9438 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
9443 *arg = env->me_flags & (CHANGEABLE|CHANGELESS);
9448 mdb_env_set_userctx(MDB_env *env, void *ctx)
9452 env->me_userctx = ctx;
9457 mdb_env_get_userctx(MDB_env *env)
9459 return env ? env->me_userctx : NULL;
9463 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
9468 env->me_assert_func = func;
9474 mdb_env_get_path(MDB_env *env, const char **arg)
9479 *arg = env->me_path;
9484 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
9493 /** Common code for #mdb_stat() and #mdb_env_stat().
9494 * @param[in] env the environment to operate in.
9495 * @param[in] db the #MDB_db record containing the stats to return.
9496 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
9497 * @return 0, this function always succeeds.
9500 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
9502 arg->ms_psize = env->me_psize;
9503 arg->ms_depth = db->md_depth;
9504 arg->ms_branch_pages = db->md_branch_pages;
9505 arg->ms_leaf_pages = db->md_leaf_pages;
9506 arg->ms_overflow_pages = db->md_overflow_pages;
9507 arg->ms_entries = db->md_entries;
9513 mdb_env_stat(MDB_env *env, MDB_stat *arg)
9517 if (env == NULL || arg == NULL)
9520 meta = mdb_env_pick_meta(env);
9522 return mdb_stat0(env, &meta->mm_dbs[MAIN_DBI], arg);
9526 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
9530 if (env == NULL || arg == NULL)
9533 meta = mdb_env_pick_meta(env);
9534 arg->me_mapaddr = meta->mm_address;
9535 arg->me_last_pgno = meta->mm_last_pg;
9536 arg->me_last_txnid = meta->mm_txnid;
9538 arg->me_mapsize = env->me_mapsize;
9539 arg->me_maxreaders = env->me_maxreaders;
9540 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : 0;
9544 /** Set the default comparison functions for a database.
9545 * Called immediately after a database is opened to set the defaults.
9546 * The user can then override them with #mdb_set_compare() or
9547 * #mdb_set_dupsort().
9548 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
9549 * @param[in] dbi A database handle returned by #mdb_dbi_open()
9552 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
9554 uint16_t f = txn->mt_dbs[dbi].md_flags;
9556 txn->mt_dbxs[dbi].md_cmp =
9557 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
9558 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
9560 txn->mt_dbxs[dbi].md_dcmp =
9561 !(f & MDB_DUPSORT) ? 0 :
9562 ((f & MDB_INTEGERDUP)
9563 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
9564 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
9567 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
9573 int rc, dbflag, exact;
9574 unsigned int unused = 0, seq;
9578 if (flags & ~VALID_FLAGS)
9580 if (txn->mt_flags & MDB_TXN_BLOCKED)
9586 if (flags & PERSISTENT_FLAGS) {
9587 uint16_t f2 = flags & PERSISTENT_FLAGS;
9588 /* make sure flag changes get committed */
9589 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
9590 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
9591 txn->mt_flags |= MDB_TXN_DIRTY;
9594 mdb_default_cmp(txn, MAIN_DBI);
9598 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
9599 mdb_default_cmp(txn, MAIN_DBI);
9602 /* Is the DB already open? */
9604 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
9605 if (!txn->mt_dbxs[i].md_name.mv_size) {
9606 /* Remember this free slot */
9607 if (!unused) unused = i;
9610 if (len == txn->mt_dbxs[i].md_name.mv_size &&
9611 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
9617 /* If no free slot and max hit, fail */
9618 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
9619 return MDB_DBS_FULL;
9621 /* Cannot mix named databases with some mainDB flags */
9622 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
9623 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
9625 /* Find the DB info */
9626 dbflag = DB_NEW|DB_VALID|DB_USRVALID;
9629 key.mv_data = (void *)name;
9630 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
9631 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
9632 if (rc == MDB_SUCCESS) {
9633 /* make sure this is actually a DB */
9634 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
9635 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
9636 return MDB_INCOMPATIBLE;
9637 } else if (! (rc == MDB_NOTFOUND && (flags & MDB_CREATE))) {
9641 /* Done here so we cannot fail after creating a new DB */
9642 if ((namedup = strdup(name)) == NULL)
9646 /* MDB_NOTFOUND and MDB_CREATE: Create new DB */
9647 data.mv_size = sizeof(MDB_db);
9648 data.mv_data = &dummy;
9649 memset(&dummy, 0, sizeof(dummy));
9650 dummy.md_root = P_INVALID;
9651 dummy.md_flags = flags & PERSISTENT_FLAGS;
9652 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
9659 /* Got info, register DBI in this txn */
9660 unsigned int slot = unused ? unused : txn->mt_numdbs;
9661 txn->mt_dbxs[slot].md_name.mv_data = namedup;
9662 txn->mt_dbxs[slot].md_name.mv_size = len;
9663 txn->mt_dbxs[slot].md_rel = NULL;
9664 txn->mt_dbflags[slot] = dbflag;
9665 /* txn-> and env-> are the same in read txns, use
9666 * tmp variable to avoid undefined assignment
9668 seq = ++txn->mt_env->me_dbiseqs[slot];
9669 txn->mt_dbiseqs[slot] = seq;
9671 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
9673 mdb_default_cmp(txn, slot);
9683 mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
9685 if (!arg || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
9688 if (txn->mt_flags & MDB_TXN_BLOCKED)
9691 if (txn->mt_dbflags[dbi] & DB_STALE) {
9694 /* Stale, must read the DB's root. cursor_init does it for us. */
9695 mdb_cursor_init(&mc, txn, dbi, &mx);
9697 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
9700 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
9703 if (dbi < CORE_DBS || dbi >= env->me_maxdbs)
9705 ptr = env->me_dbxs[dbi].md_name.mv_data;
9706 /* If there was no name, this was already closed */
9708 env->me_dbxs[dbi].md_name.mv_data = NULL;
9709 env->me_dbxs[dbi].md_name.mv_size = 0;
9710 env->me_dbflags[dbi] = 0;
9711 env->me_dbiseqs[dbi]++;
9716 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
9718 /* We could return the flags for the FREE_DBI too but what's the point? */
9719 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9721 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
9725 /** Add all the DB's pages to the free list.
9726 * @param[in] mc Cursor on the DB to free.
9727 * @param[in] subs non-Zero to check for sub-DBs in this DB.
9728 * @return 0 on success, non-zero on failure.
9731 mdb_drop0(MDB_cursor *mc, int subs)
9735 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
9736 if (rc == MDB_SUCCESS) {
9737 MDB_txn *txn = mc->mc_txn;
9742 /* DUPSORT sub-DBs have no ovpages/DBs. Omit scanning leaves.
9743 * This also avoids any P_LEAF2 pages, which have no nodes.
9744 * Also if the DB doesn't have sub-DBs and has no overflow
9745 * pages, omit scanning leaves.
9747 if ((mc->mc_flags & C_SUB) ||
9748 (!subs && !mc->mc_db->md_overflow_pages))
9751 mdb_cursor_copy(mc, &mx);
9752 while (mc->mc_snum > 0) {
9753 MDB_page *mp = mc->mc_pg[mc->mc_top];
9754 unsigned n = NUMKEYS(mp);
9756 for (i=0; i<n; i++) {
9757 ni = NODEPTR(mp, i);
9758 if (ni->mn_flags & F_BIGDATA) {
9761 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9762 rc = mdb_page_get(mc, pg, &omp, NULL);
9765 mdb_cassert(mc, IS_OVERFLOW(omp));
9766 rc = mdb_midl_append_range(&txn->mt_free_pgs,
9770 mc->mc_db->md_overflow_pages -= omp->mp_pages;
9771 if (!mc->mc_db->md_overflow_pages && !subs)
9773 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
9774 mdb_xcursor_init1(mc, ni);
9775 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
9780 if (!subs && !mc->mc_db->md_overflow_pages)
9783 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
9785 for (i=0; i<n; i++) {
9787 ni = NODEPTR(mp, i);
9790 mdb_midl_xappend(txn->mt_free_pgs, pg);
9795 mc->mc_ki[mc->mc_top] = i;
9796 rc = mdb_cursor_sibling(mc, 1);
9798 if (rc != MDB_NOTFOUND)
9800 /* no more siblings, go back to beginning
9801 * of previous level.
9806 for (i=1; i<mc->mc_snum; i++) {
9808 mc->mc_pg[i] = mx.mc_pg[i];
9813 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
9816 txn->mt_flags |= MDB_TXN_ERROR;
9817 } else if (rc == MDB_NOTFOUND) {
9820 mc->mc_flags &= ~C_INITIALIZED;
9824 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
9826 MDB_cursor *mc, *m2;
9829 if ((unsigned)del > 1 || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9832 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
9835 if (TXN_DBI_CHANGED(txn, dbi))
9838 rc = mdb_cursor_open(txn, dbi, &mc);
9842 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
9843 /* Invalidate the dropped DB's cursors */
9844 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
9845 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
9849 /* Can't delete the main DB */
9850 if (del && dbi >= CORE_DBS) {
9851 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, F_SUBDATA);
9853 txn->mt_dbflags[dbi] = DB_STALE;
9854 mdb_dbi_close(txn->mt_env, dbi);
9856 txn->mt_flags |= MDB_TXN_ERROR;
9859 /* reset the DB record, mark it dirty */
9860 txn->mt_dbflags[dbi] |= DB_DIRTY;
9861 txn->mt_dbs[dbi].md_depth = 0;
9862 txn->mt_dbs[dbi].md_branch_pages = 0;
9863 txn->mt_dbs[dbi].md_leaf_pages = 0;
9864 txn->mt_dbs[dbi].md_overflow_pages = 0;
9865 txn->mt_dbs[dbi].md_entries = 0;
9866 txn->mt_dbs[dbi].md_root = P_INVALID;
9868 txn->mt_flags |= MDB_TXN_DIRTY;
9871 mdb_cursor_close(mc);
9875 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9877 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9880 txn->mt_dbxs[dbi].md_cmp = cmp;
9884 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9886 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9889 txn->mt_dbxs[dbi].md_dcmp = cmp;
9893 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
9895 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9898 txn->mt_dbxs[dbi].md_rel = rel;
9902 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
9904 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9907 txn->mt_dbxs[dbi].md_relctx = ctx;
9912 mdb_env_get_maxkeysize(MDB_env *env)
9914 return ENV_MAXKEY(env);
9918 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
9920 unsigned int i, rdrs;
9923 int rc = 0, first = 1;
9927 if (!env->me_txns) {
9928 return func("(no reader locks)\n", ctx);
9930 rdrs = env->me_txns->mti_numreaders;
9931 mr = env->me_txns->mti_readers;
9932 for (i=0; i<rdrs; i++) {
9934 txnid_t txnid = mr[i].mr_txnid;
9935 sprintf(buf, txnid == (txnid_t)-1 ?
9936 "%10d %"Z"x -\n" : "%10d %"Z"x %"Z"u\n",
9937 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
9940 rc = func(" pid thread txnid\n", ctx);
9944 rc = func(buf, ctx);
9950 rc = func("(no active readers)\n", ctx);
9955 /** Insert pid into list if not already present.
9956 * return -1 if already present.
9959 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
9961 /* binary search of pid in list */
9963 unsigned cursor = 1;
9965 unsigned n = ids[0];
9968 unsigned pivot = n >> 1;
9969 cursor = base + pivot + 1;
9970 val = pid - ids[cursor];
9975 } else if ( val > 0 ) {
9980 /* found, so it's a duplicate */
9989 for (n = ids[0]; n > cursor; n--)
9996 mdb_reader_check(MDB_env *env, int *dead)
10002 return env->me_txns ? mdb_reader_check0(env, 0, dead) : MDB_SUCCESS;
10005 /** As #mdb_reader_check(). rlocked = <caller locked the reader mutex>. */
10007 mdb_reader_check0(MDB_env *env, int rlocked, int *dead)
10009 mdb_mutexref_t rmutex = rlocked ? NULL : env->me_rmutex;
10010 unsigned int i, j, rdrs;
10012 MDB_PID_T *pids, pid;
10013 int rc = MDB_SUCCESS, count = 0;
10015 rdrs = env->me_txns->mti_numreaders;
10016 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
10020 mr = env->me_txns->mti_readers;
10021 for (i=0; i<rdrs; i++) {
10022 pid = mr[i].mr_pid;
10023 if (pid && pid != env->me_pid) {
10024 if (mdb_pid_insert(pids, pid) == 0) {
10025 if (!mdb_reader_pid(env, Pidcheck, pid)) {
10026 /* Stale reader found */
10029 if ((rc = LOCK_MUTEX0(rmutex)) != 0) {
10030 if ((rc = mdb_mutex_failed(env, rmutex, rc)))
10032 rdrs = 0; /* the above checked all readers */
10034 /* Recheck, a new process may have reused pid */
10035 if (mdb_reader_pid(env, Pidcheck, pid))
10039 for (; j<rdrs; j++)
10040 if (mr[j].mr_pid == pid) {
10041 DPRINTF(("clear stale reader pid %u txn %"Z"d",
10042 (unsigned) pid, mr[j].mr_txnid));
10047 UNLOCK_MUTEX(rmutex);
10058 #ifdef MDB_ROBUST_SUPPORTED
10059 /** Handle #LOCK_MUTEX0() failure.
10060 * Try to repair the lock file if the mutex owner died.
10061 * @param[in] env the environment handle
10062 * @param[in] mutex LOCK_MUTEX0() mutex
10063 * @param[in] rc LOCK_MUTEX0() error (nonzero)
10064 * @return 0 on success with the mutex locked, or an error code on failure.
10067 mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc)
10072 if (rc == MDB_OWNERDEAD) {
10073 /* We own the mutex. Clean up after dead previous owner. */
10075 rlocked = (mutex == env->me_rmutex);
10077 /* Keep mti_txnid updated, otherwise next writer can
10078 * overwrite data which latest meta page refers to.
10080 meta = mdb_env_pick_meta(env);
10081 env->me_txns->mti_txnid = meta->mm_txnid;
10082 /* env is hosed if the dead thread was ours */
10084 env->me_flags |= MDB_FATAL_ERROR;
10085 env->me_txn = NULL;
10089 DPRINTF(("%cmutex owner died, %s", (rlocked ? 'r' : 'w'),
10090 (rc ? "this process' env is hosed" : "recovering")));
10091 rc2 = mdb_reader_check0(env, rlocked, NULL);
10093 rc2 = mdb_mutex_consistent(mutex);
10094 if (rc || (rc = rc2)) {
10095 DPRINTF(("LOCK_MUTEX recovery failed, %s", mdb_strerror(rc)));
10096 UNLOCK_MUTEX(mutex);
10102 DPRINTF(("LOCK_MUTEX failed, %s", mdb_strerror(rc)));
10107 #endif /* MDB_ROBUST_SUPPORTED */
10110 #if defined(_WIN32)
10111 static int utf8_to_utf16(const char *src, int srcsize, wchar_t **dst, int *dstsize)
10115 need = MultiByteToWideChar(CP_UTF8, 0, src, srcsize, NULL, 0);
10116 if (need == 0xFFFD)
10120 result = malloc(sizeof(wchar_t) * need);
10123 MultiByteToWideChar(CP_UTF8, 0, src, srcsize, result, need);
10129 #endif /* defined(_WIN32) */