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
262 #endif /* !MDB_USE_ROBUST */
264 #if defined(MDB_USE_POSIX_MUTEX) && (MDB_USE_ROBUST)
265 /* glibc < 2.12 only provided _np API */
266 # if (defined(__GLIBC__) && GLIBC_VER < 0x02000c) || \
267 (defined(PTHREAD_MUTEX_ROBUST_NP) && !defined(PTHREAD_MUTEX_ROBUST))
268 # define PTHREAD_MUTEX_ROBUST PTHREAD_MUTEX_ROBUST_NP
269 # define pthread_mutexattr_setrobust(attr, flag) pthread_mutexattr_setrobust_np(attr, flag)
270 # define pthread_mutex_consistent(mutex) pthread_mutex_consistent_np(mutex)
272 #endif /* MDB_USE_POSIX_MUTEX && MDB_USE_ROBUST */
274 #if defined(MDB_OWNERDEAD) && (MDB_USE_ROBUST)
275 #define MDB_ROBUST_SUPPORTED 1
279 #define MDB_USE_HASH 1
280 #define MDB_PIDLOCK 0
281 #define THREAD_RET DWORD
282 #define pthread_t HANDLE
283 #define pthread_mutex_t HANDLE
284 #define pthread_cond_t HANDLE
285 typedef HANDLE mdb_mutex_t, mdb_mutexref_t;
286 #define pthread_key_t DWORD
287 #define pthread_self() GetCurrentThreadId()
288 #define pthread_key_create(x,y) \
289 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
290 #define pthread_key_delete(x) TlsFree(x)
291 #define pthread_getspecific(x) TlsGetValue(x)
292 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
293 #define pthread_mutex_unlock(x) ReleaseMutex(*x)
294 #define pthread_mutex_lock(x) WaitForSingleObject(*x, INFINITE)
295 #define pthread_cond_signal(x) SetEvent(*x)
296 #define pthread_cond_wait(cond,mutex) do{SignalObjectAndWait(*mutex, *cond, INFINITE, FALSE); WaitForSingleObject(*mutex, INFINITE);}while(0)
297 #define THREAD_CREATE(thr,start,arg) \
298 (((thr) = CreateThread(NULL, 0, start, arg, 0, NULL)) ? 0 : ErrCode())
299 #define THREAD_FINISH(thr) \
300 (WaitForSingleObject(thr, INFINITE) ? ErrCode() : 0)
301 #define LOCK_MUTEX0(mutex) WaitForSingleObject(mutex, INFINITE)
302 #define UNLOCK_MUTEX(mutex) ReleaseMutex(mutex)
303 #define mdb_mutex_consistent(mutex) 0
304 #define getpid() GetCurrentProcessId()
305 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
306 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
307 #define ErrCode() GetLastError()
308 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
309 #define close(fd) (CloseHandle(fd) ? 0 : -1)
310 #define munmap(ptr,len) UnmapViewOfFile(ptr)
311 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
312 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
314 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
318 #define THREAD_RET void *
319 #define THREAD_CREATE(thr,start,arg) pthread_create(&thr,NULL,start,arg)
320 #define THREAD_FINISH(thr) pthread_join(thr,NULL)
321 #define Z "z" /**< printf format modifier for size_t */
323 /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
324 #define MDB_PIDLOCK 1
326 #ifdef MDB_USE_POSIX_SEM
328 typedef sem_t *mdb_mutex_t, *mdb_mutexref_t;
329 #define LOCK_MUTEX0(mutex) mdb_sem_wait(mutex)
330 #define UNLOCK_MUTEX(mutex) sem_post(mutex)
333 mdb_sem_wait(sem_t *sem)
336 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
340 #else /* MDB_USE_POSIX_MUTEX: */
341 /** Shared mutex/semaphore as it is stored (mdb_mutex_t), and as
342 * local variables keep it (mdb_mutexref_t).
344 * When #mdb_mutexref_t is a pointer declaration and #mdb_mutex_t is
345 * not, then it is array[size 1] so it can be assigned to a pointer.
348 typedef pthread_mutex_t mdb_mutex_t[1], *mdb_mutexref_t;
350 /** Lock the reader or writer mutex.
351 * Returns 0 or a code to give #mdb_mutex_failed(), as in #LOCK_MUTEX().
353 #define LOCK_MUTEX0(mutex) pthread_mutex_lock(mutex)
354 /** Unlock the reader or writer mutex.
356 #define UNLOCK_MUTEX(mutex) pthread_mutex_unlock(mutex)
357 /** Mark mutex-protected data as repaired, after death of previous owner.
359 #define mdb_mutex_consistent(mutex) pthread_mutex_consistent(mutex)
360 #endif /* MDB_USE_POSIX_SEM */
362 /** Get the error code for the last failed system function.
364 #define ErrCode() errno
366 /** An abstraction for a file handle.
367 * On POSIX systems file handles are small integers. On Windows
368 * they're opaque pointers.
372 /** A value for an invalid file handle.
373 * Mainly used to initialize file variables and signify that they are
376 #define INVALID_HANDLE_VALUE (-1)
378 /** Get the size of a memory page for the system.
379 * This is the basic size that the platform's memory manager uses, and is
380 * fundamental to the use of memory-mapped files.
382 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
385 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
388 #define MNAME_LEN (sizeof(pthread_mutex_t))
393 #ifdef MDB_ROBUST_SUPPORTED
394 /** Lock mutex, handle any error, set rc = result.
395 * Return 0 on success, nonzero (not rc) on error.
397 #define LOCK_MUTEX(rc, env, mutex) \
398 (((rc) = LOCK_MUTEX0(mutex)) && \
399 ((rc) = mdb_mutex_failed(env, mutex, rc)))
400 static int mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc);
402 #define LOCK_MUTEX(rc, env, mutex) ((rc) = LOCK_MUTEX0(mutex))
403 #define mdb_mutex_failed(env, mutex, rc) (rc)
407 /** A flag for opening a file and requesting synchronous data writes.
408 * This is only used when writing a meta page. It's not strictly needed;
409 * we could just do a normal write and then immediately perform a flush.
410 * But if this flag is available it saves us an extra system call.
412 * @note If O_DSYNC is undefined but exists in /usr/include,
413 * preferably set some compiler flag to get the definition.
417 # define MDB_DSYNC O_DSYNC
419 # define MDB_DSYNC O_SYNC
424 /** Function for flushing the data of a file. Define this to fsync
425 * if fdatasync() is not supported.
427 #ifndef MDB_FDATASYNC
428 # define MDB_FDATASYNC fdatasync
432 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
443 /** A page number in the database.
444 * Note that 64 bit page numbers are overkill, since pages themselves
445 * already represent 12-13 bits of addressable memory, and the OS will
446 * always limit applications to a maximum of 63 bits of address space.
448 * @note In the #MDB_node structure, we only store 48 bits of this value,
449 * which thus limits us to only 60 bits of addressable data.
451 typedef MDB_ID pgno_t;
453 /** A transaction ID.
454 * See struct MDB_txn.mt_txnid for details.
456 typedef MDB_ID txnid_t;
458 /** @defgroup debug Debug Macros
462 /** Enable debug output. Needs variable argument macros (a C99 feature).
463 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
464 * read from and written to the database (used for free space management).
470 static int mdb_debug;
471 static txnid_t mdb_debug_start;
473 /** Print a debug message with printf formatting.
474 * Requires double parenthesis around 2 or more args.
476 # define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
477 # define DPRINTF0(fmt, ...) \
478 fprintf(stderr, "%s:%d " fmt "\n", mdb_func_, __LINE__, __VA_ARGS__)
480 # define DPRINTF(args) ((void) 0)
482 /** Print a debug string.
483 * The string is printed literally, with no format processing.
485 #define DPUTS(arg) DPRINTF(("%s", arg))
486 /** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
488 (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
491 /** @brief The maximum size of a database page.
493 * It is 32k or 64k, since value-PAGEBASE must fit in
494 * #MDB_page.%mp_upper.
496 * LMDB will use database pages < OS pages if needed.
497 * That causes more I/O in write transactions: The OS must
498 * know (read) the whole page before writing a partial page.
500 * Note that we don't currently support Huge pages. On Linux,
501 * regular data files cannot use Huge pages, and in general
502 * Huge pages aren't actually pageable. We rely on the OS
503 * demand-pager to read our data and page it out when memory
504 * pressure from other processes is high. So until OSs have
505 * actual paging support for Huge pages, they're not viable.
507 #define MAX_PAGESIZE (PAGEBASE ? 0x10000 : 0x8000)
509 /** The minimum number of keys required in a database page.
510 * Setting this to a larger value will place a smaller bound on the
511 * maximum size of a data item. Data items larger than this size will
512 * be pushed into overflow pages instead of being stored directly in
513 * the B-tree node. This value used to default to 4. With a page size
514 * of 4096 bytes that meant that any item larger than 1024 bytes would
515 * go into an overflow page. That also meant that on average 2-3KB of
516 * each overflow page was wasted space. The value cannot be lower than
517 * 2 because then there would no longer be a tree structure. With this
518 * value, items larger than 2KB will go into overflow pages, and on
519 * average only 1KB will be wasted.
521 #define MDB_MINKEYS 2
523 /** A stamp that identifies a file as an LMDB file.
524 * There's nothing special about this value other than that it is easily
525 * recognizable, and it will reflect any byte order mismatches.
527 #define MDB_MAGIC 0xBEEFC0DE
529 /** The version number for a database's datafile format. */
530 #define MDB_DATA_VERSION ((MDB_DEVEL) ? 999 : 1)
531 /** The version number for a database's lockfile format. */
532 #define MDB_LOCK_VERSION 1
534 /** @brief The max size of a key we can write, or 0 for computed max.
536 * This macro should normally be left alone or set to 0.
537 * Note that a database with big keys or dupsort data cannot be
538 * reliably modified by a liblmdb which uses a smaller max.
539 * The default is 511 for backwards compat, or 0 when #MDB_DEVEL.
541 * Other values are allowed, for backwards compat. However:
542 * A value bigger than the computed max can break if you do not
543 * know what you are doing, and liblmdb <= 0.9.10 can break when
544 * modifying a DB with keys/dupsort data bigger than its max.
546 * Data items in an #MDB_DUPSORT database are also limited to
547 * this size, since they're actually keys of a sub-DB. Keys and
548 * #MDB_DUPSORT data items must fit on a node in a regular page.
550 #ifndef MDB_MAXKEYSIZE
551 #define MDB_MAXKEYSIZE ((MDB_DEVEL) ? 0 : 511)
554 /** The maximum size of a key we can write to the environment. */
556 #define ENV_MAXKEY(env) (MDB_MAXKEYSIZE)
558 #define ENV_MAXKEY(env) ((env)->me_maxkey)
561 /** @brief The maximum size of a data item.
563 * We only store a 32 bit value for node sizes.
565 #define MAXDATASIZE 0xffffffffUL
568 /** Key size which fits in a #DKBUF.
571 #define DKBUF_MAXKEYSIZE ((MDB_MAXKEYSIZE) > 0 ? (MDB_MAXKEYSIZE) : 511)
574 * This is used for printing a hex dump of a key's contents.
576 #define DKBUF char kbuf[DKBUF_MAXKEYSIZE*2+1]
577 /** Display a key in hex.
579 * Invoke a function to display a key in hex.
581 #define DKEY(x) mdb_dkey(x, kbuf)
587 /** An invalid page number.
588 * Mainly used to denote an empty tree.
590 #define P_INVALID (~(pgno_t)0)
592 /** Test if the flags \b f are set in a flag word \b w. */
593 #define F_ISSET(w, f) (((w) & (f)) == (f))
595 /** Round \b n up to an even number. */
596 #define EVEN(n) (((n) + 1U) & -2) /* sign-extending -2 to match n+1U */
598 /** Used for offsets within a single page.
599 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
602 typedef uint16_t indx_t;
604 /** Default size of memory map.
605 * This is certainly too small for any actual applications. Apps should always set
606 * the size explicitly using #mdb_env_set_mapsize().
608 #define DEFAULT_MAPSIZE 1048576
610 /** @defgroup readers Reader Lock Table
611 * Readers don't acquire any locks for their data access. Instead, they
612 * simply record their transaction ID in the reader table. The reader
613 * mutex is needed just to find an empty slot in the reader table. The
614 * slot's address is saved in thread-specific data so that subsequent read
615 * transactions started by the same thread need no further locking to proceed.
617 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
619 * No reader table is used if the database is on a read-only filesystem, or
620 * if #MDB_NOLOCK is set.
622 * Since the database uses multi-version concurrency control, readers don't
623 * actually need any locking. This table is used to keep track of which
624 * readers are using data from which old transactions, so that we'll know
625 * when a particular old transaction is no longer in use. Old transactions
626 * that have discarded any data pages can then have those pages reclaimed
627 * for use by a later write transaction.
629 * The lock table is constructed such that reader slots are aligned with the
630 * processor's cache line size. Any slot is only ever used by one thread.
631 * This alignment guarantees that there will be no contention or cache
632 * thrashing as threads update their own slot info, and also eliminates
633 * any need for locking when accessing a slot.
635 * A writer thread will scan every slot in the table to determine the oldest
636 * outstanding reader transaction. Any freed pages older than this will be
637 * reclaimed by the writer. The writer doesn't use any locks when scanning
638 * this table. This means that there's no guarantee that the writer will
639 * see the most up-to-date reader info, but that's not required for correct
640 * operation - all we need is to know the upper bound on the oldest reader,
641 * we don't care at all about the newest reader. So the only consequence of
642 * reading stale information here is that old pages might hang around a
643 * while longer before being reclaimed. That's actually good anyway, because
644 * the longer we delay reclaiming old pages, the more likely it is that a
645 * string of contiguous pages can be found after coalescing old pages from
646 * many old transactions together.
649 /** Number of slots in the reader table.
650 * This value was chosen somewhat arbitrarily. 126 readers plus a
651 * couple mutexes fit exactly into 8KB on my development machine.
652 * Applications should set the table size using #mdb_env_set_maxreaders().
654 #define DEFAULT_READERS 126
656 /** The size of a CPU cache line in bytes. We want our lock structures
657 * aligned to this size to avoid false cache line sharing in the
659 * This value works for most CPUs. For Itanium this should be 128.
665 /** The information we store in a single slot of the reader table.
666 * In addition to a transaction ID, we also record the process and
667 * thread ID that owns a slot, so that we can detect stale information,
668 * e.g. threads or processes that went away without cleaning up.
669 * @note We currently don't check for stale records. We simply re-init
670 * the table when we know that we're the only process opening the
673 typedef struct MDB_rxbody {
674 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
675 * Multiple readers that start at the same time will probably have the
676 * same ID here. Again, it's not important to exclude them from
677 * anything; all we need to know is which version of the DB they
678 * started from so we can avoid overwriting any data used in that
679 * particular version.
681 volatile txnid_t mrb_txnid;
682 /** The process ID of the process owning this reader txn. */
683 volatile MDB_PID_T mrb_pid;
684 /** The thread ID of the thread owning this txn. */
685 volatile MDB_THR_T mrb_tid;
688 /** The actual reader record, with cacheline padding. */
689 typedef struct MDB_reader {
692 /** shorthand for mrb_txnid */
693 #define mr_txnid mru.mrx.mrb_txnid
694 #define mr_pid mru.mrx.mrb_pid
695 #define mr_tid mru.mrx.mrb_tid
696 /** cache line alignment */
697 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
701 /** The header for the reader table.
702 * The table resides in a memory-mapped file. (This is a different file
703 * than is used for the main database.)
705 * For POSIX the actual mutexes reside in the shared memory of this
706 * mapped file. On Windows, mutexes are named objects allocated by the
707 * kernel; we store the mutex names in this mapped file so that other
708 * processes can grab them. This same approach is also used on
709 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
710 * process-shared POSIX mutexes. For these cases where a named object
711 * is used, the object name is derived from a 64 bit FNV hash of the
712 * environment pathname. As such, naming collisions are extremely
713 * unlikely. If a collision occurs, the results are unpredictable.
715 typedef struct MDB_txbody {
716 /** Stamp identifying this as an LMDB file. It must be set
719 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
721 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
722 char mtb_rmname[MNAME_LEN];
724 /** Mutex protecting access to this table.
725 * This is the reader table lock used with LOCK_MUTEX().
727 mdb_mutex_t mtb_rmutex;
729 /** The ID of the last transaction committed to the database.
730 * This is recorded here only for convenience; the value can always
731 * be determined by reading the main database meta pages.
733 volatile txnid_t mtb_txnid;
734 /** The number of slots that have been used in the reader table.
735 * This always records the maximum count, it is not decremented
736 * when readers release their slots.
738 volatile unsigned mtb_numreaders;
741 /** The actual reader table definition. */
742 typedef struct MDB_txninfo {
745 #define mti_magic mt1.mtb.mtb_magic
746 #define mti_format mt1.mtb.mtb_format
747 #define mti_rmutex mt1.mtb.mtb_rmutex
748 #define mti_rmname mt1.mtb.mtb_rmname
749 #define mti_txnid mt1.mtb.mtb_txnid
750 #define mti_numreaders mt1.mtb.mtb_numreaders
751 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
754 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
755 char mt2_wmname[MNAME_LEN];
756 #define mti_wmname mt2.mt2_wmname
758 mdb_mutex_t mt2_wmutex;
759 #define mti_wmutex mt2.mt2_wmutex
761 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
763 MDB_reader mti_readers[1];
766 /** Lockfile format signature: version, features and field layout */
767 #define MDB_LOCK_FORMAT \
769 ((MDB_LOCK_VERSION) \
770 /* Flags which describe functionality */ \
771 + (((MDB_PIDLOCK) != 0) << 16)))
774 /** Common header for all page types. The page type depends on #mp_flags.
776 * #P_BRANCH and #P_LEAF pages have unsorted '#MDB_node's at the end, with
777 * sorted #mp_ptrs[] entries referring to them. Exception: #P_LEAF2 pages
778 * omit mp_ptrs and pack sorted #MDB_DUPFIXED values after the page header.
780 * #P_OVERFLOW records occupy one or more contiguous pages where only the
781 * first has a page header. They hold the real data of #F_BIGDATA nodes.
783 * #P_SUBP sub-pages are small leaf "pages" with duplicate data.
784 * A node with flag #F_DUPDATA but not #F_SUBDATA contains a sub-page.
785 * (Duplicate data can also go in sub-databases, which use normal pages.)
787 * #P_META pages contain #MDB_meta, the start point of an LMDB snapshot.
789 * Each non-metapage up to #MDB_meta.%mm_last_pg is reachable exactly once
790 * in the snapshot: Either used by a database or listed in a freeDB record.
792 typedef struct MDB_page {
793 #define mp_pgno mp_p.p_pgno
794 #define mp_next mp_p.p_next
796 pgno_t p_pgno; /**< page number */
797 struct MDB_page *p_next; /**< for in-memory list of freed pages */
799 uint16_t mp_pad; /**< key size if this is a LEAF2 page */
800 /** @defgroup mdb_page Page Flags
802 * Flags for the page headers.
805 #define P_BRANCH 0x01 /**< branch page */
806 #define P_LEAF 0x02 /**< leaf page */
807 #define P_OVERFLOW 0x04 /**< overflow page */
808 #define P_META 0x08 /**< meta page */
809 #define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
810 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
811 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
812 #define P_LOOSE 0x4000 /**< page was dirtied then freed, can be reused */
813 #define P_KEEP 0x8000 /**< leave this page alone during spill */
815 uint16_t mp_flags; /**< @ref mdb_page */
816 #define mp_lower mp_pb.pb.pb_lower
817 #define mp_upper mp_pb.pb.pb_upper
818 #define mp_pages mp_pb.pb_pages
821 indx_t pb_lower; /**< lower bound of free space */
822 indx_t pb_upper; /**< upper bound of free space */
824 uint32_t pb_pages; /**< number of overflow pages */
826 indx_t mp_ptrs[1]; /**< dynamic size */
829 /** Size of the page header, excluding dynamic data at the end */
830 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
832 /** Address of first usable data byte in a page, after the header */
833 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
835 /** ITS#7713, change PAGEBASE to handle 65536 byte pages */
836 #define PAGEBASE ((MDB_DEVEL) ? PAGEHDRSZ : 0)
838 /** Number of nodes on a page */
839 #define NUMKEYS(p) (((p)->mp_lower - (PAGEHDRSZ-PAGEBASE)) >> 1)
841 /** The amount of space remaining in the page */
842 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
844 /** The percentage of space used in the page, in tenths of a percent. */
845 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
846 ((env)->me_psize - PAGEHDRSZ))
847 /** The minimum page fill factor, in tenths of a percent.
848 * Pages emptier than this are candidates for merging.
850 #define FILL_THRESHOLD 250
852 /** Test if a page is a leaf page */
853 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
854 /** Test if a page is a LEAF2 page */
855 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
856 /** Test if a page is a branch page */
857 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
858 /** Test if a page is an overflow page */
859 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
860 /** Test if a page is a sub page */
861 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
863 /** The number of overflow pages needed to store the given size. */
864 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
866 /** Link in #MDB_txn.%mt_loose_pgs list.
867 * Kept outside the page header, which is needed when reusing the page.
869 #define NEXT_LOOSE_PAGE(p) (*(MDB_page **)((p) + 2))
871 /** Header for a single key/data pair within a page.
872 * Used in pages of type #P_BRANCH and #P_LEAF without #P_LEAF2.
873 * We guarantee 2-byte alignment for 'MDB_node's.
875 typedef struct MDB_node {
876 /** lo and hi are used for data size on leaf nodes and for
877 * child pgno on branch nodes. On 64 bit platforms, flags
878 * is also used for pgno. (Branch nodes have no flags).
879 * They are in host byte order in case that lets some
880 * accesses be optimized into a 32-bit word access.
882 #if BYTE_ORDER == LITTLE_ENDIAN
883 unsigned short mn_lo, mn_hi; /**< part of data size or pgno */
885 unsigned short mn_hi, mn_lo;
887 /** @defgroup mdb_node Node Flags
889 * Flags for node headers.
892 #define F_BIGDATA 0x01 /**< data put on overflow page */
893 #define F_SUBDATA 0x02 /**< data is a sub-database */
894 #define F_DUPDATA 0x04 /**< data has duplicates */
896 /** valid flags for #mdb_node_add() */
897 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
900 unsigned short mn_flags; /**< @ref mdb_node */
901 unsigned short mn_ksize; /**< key size */
902 char mn_data[1]; /**< key and data are appended here */
905 /** Size of the node header, excluding dynamic data at the end */
906 #define NODESIZE offsetof(MDB_node, mn_data)
908 /** Bit position of top word in page number, for shifting mn_flags */
909 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
911 /** Size of a node in a branch page with a given key.
912 * This is just the node header plus the key, there is no data.
914 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
916 /** Size of a node in a leaf page with a given key and data.
917 * This is node header plus key plus data size.
919 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
921 /** Address of node \b i in page \b p */
922 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i] + PAGEBASE))
924 /** Address of the key for the node */
925 #define NODEKEY(node) (void *)((node)->mn_data)
927 /** Address of the data for a node */
928 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
930 /** Get the page number pointed to by a branch node */
931 #define NODEPGNO(node) \
932 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
933 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
934 /** Set the page number in a branch node */
935 #define SETPGNO(node,pgno) do { \
936 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
937 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
939 /** Get the size of the data in a leaf node */
940 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
941 /** Set the size of the data for a leaf node */
942 #define SETDSZ(node,size) do { \
943 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
944 /** The size of a key in a node */
945 #define NODEKSZ(node) ((node)->mn_ksize)
947 /** Copy a page number from src to dst */
949 #define COPY_PGNO(dst,src) dst = src
951 #if SIZE_MAX > 4294967295UL
952 #define COPY_PGNO(dst,src) do { \
953 unsigned short *s, *d; \
954 s = (unsigned short *)&(src); \
955 d = (unsigned short *)&(dst); \
962 #define COPY_PGNO(dst,src) do { \
963 unsigned short *s, *d; \
964 s = (unsigned short *)&(src); \
965 d = (unsigned short *)&(dst); \
971 /** The address of a key in a LEAF2 page.
972 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
973 * There are no node headers, keys are stored contiguously.
975 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
977 /** Set the \b node's key into \b keyptr, if requested. */
978 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
979 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
981 /** Set the \b node's key into \b key. */
982 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
984 /** Information about a single database in the environment. */
985 typedef struct MDB_db {
986 uint32_t md_pad; /**< also ksize for LEAF2 pages */
987 uint16_t md_flags; /**< @ref mdb_dbi_open */
988 uint16_t md_depth; /**< depth of this tree */
989 pgno_t md_branch_pages; /**< number of internal pages */
990 pgno_t md_leaf_pages; /**< number of leaf pages */
991 pgno_t md_overflow_pages; /**< number of overflow pages */
992 size_t md_entries; /**< number of data items */
993 pgno_t md_root; /**< the root page of this tree */
996 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
997 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
998 /** #mdb_dbi_open() flags */
999 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
1000 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
1002 /** Handle for the DB used to track free pages. */
1004 /** Handle for the default DB. */
1006 /** Number of DBs in metapage (free and main) - also hardcoded elsewhere */
1009 /** Number of meta pages - also hardcoded elsewhere */
1012 /** Meta page content.
1013 * A meta page is the start point for accessing a database snapshot.
1014 * Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
1016 typedef struct MDB_meta {
1017 /** Stamp identifying this as an LMDB file. It must be set
1020 /** Version number of this file. Must be set to #MDB_DATA_VERSION. */
1021 uint32_t mm_version;
1022 void *mm_address; /**< address for fixed mapping */
1023 size_t mm_mapsize; /**< size of mmap region */
1024 MDB_db mm_dbs[CORE_DBS]; /**< first is free space, 2nd is main db */
1025 /** The size of pages used in this DB */
1026 #define mm_psize mm_dbs[FREE_DBI].md_pad
1027 /** Any persistent environment flags. @ref mdb_env */
1028 #define mm_flags mm_dbs[FREE_DBI].md_flags
1029 /** Last used page in the datafile.
1030 * Actually the file may be shorter if the freeDB lists the final pages.
1033 volatile txnid_t mm_txnid; /**< txnid that committed this page */
1036 /** Buffer for a stack-allocated meta page.
1037 * The members define size and alignment, and silence type
1038 * aliasing warnings. They are not used directly; that could
1039 * mean incorrectly using several union members in parallel.
1041 typedef union MDB_metabuf {
1044 char mm_pad[PAGEHDRSZ];
1049 /** Auxiliary DB info.
1050 * The information here is mostly static/read-only. There is
1051 * only a single copy of this record in the environment.
1053 typedef struct MDB_dbx {
1054 MDB_val md_name; /**< name of the database */
1055 MDB_cmp_func *md_cmp; /**< function for comparing keys */
1056 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
1057 MDB_rel_func *md_rel; /**< user relocate function */
1058 void *md_relctx; /**< user-provided context for md_rel */
1061 /** A database transaction.
1062 * Every operation requires a transaction handle.
1065 MDB_txn *mt_parent; /**< parent of a nested txn */
1066 /** Nested txn under this txn, set together with flag #MDB_TXN_HAS_CHILD */
1068 pgno_t mt_next_pgno; /**< next unallocated page */
1069 /** The ID of this transaction. IDs are integers incrementing from 1.
1070 * Only committed write transactions increment the ID. If a transaction
1071 * aborts, the ID may be re-used by the next writer.
1074 MDB_env *mt_env; /**< the DB environment */
1075 /** The list of pages that became unused during this transaction.
1077 MDB_IDL mt_free_pgs;
1078 /** The list of loose pages that became unused and may be reused
1079 * in this transaction, linked through #NEXT_LOOSE_PAGE(page).
1081 MDB_page *mt_loose_pgs;
1082 /** Number of loose pages (#mt_loose_pgs) */
1084 /** The sorted list of dirty pages we temporarily wrote to disk
1085 * because the dirty list was full. page numbers in here are
1086 * shifted left by 1, deleted slots have the LSB set.
1088 MDB_IDL mt_spill_pgs;
1090 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
1091 MDB_ID2L dirty_list;
1092 /** For read txns: This thread/txn's reader table slot, or NULL. */
1095 /** Array of records for each DB known in the environment. */
1097 /** Array of MDB_db records for each known DB */
1099 /** Array of sequence numbers for each DB handle */
1100 unsigned int *mt_dbiseqs;
1101 /** @defgroup mt_dbflag Transaction DB Flags
1105 #define DB_DIRTY 0x01 /**< DB was written in this txn */
1106 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
1107 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
1108 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
1109 #define DB_USRVALID 0x10 /**< As #DB_VALID, but not set for #FREE_DBI */
1110 #define DB_DUPDATA 0x20 /**< DB is #MDB_DUPSORT data */
1112 /** In write txns, array of cursors for each DB */
1113 MDB_cursor **mt_cursors;
1114 /** Array of flags for each DB */
1115 unsigned char *mt_dbflags;
1116 /** Number of DB records in use, or 0 when the txn is finished.
1117 * This number only ever increments until the txn finishes; we
1118 * don't decrement it when individual DB handles are closed.
1122 /** @defgroup mdb_txn Transaction Flags
1126 /** #mdb_txn_begin() flags */
1127 #define MDB_TXN_BEGIN_FLAGS MDB_RDONLY
1128 #define MDB_TXN_RDONLY MDB_RDONLY /**< read-only transaction */
1129 /* internal txn flags */
1130 #define MDB_TXN_WRITEMAP MDB_WRITEMAP /**< copy of #MDB_env flag in writers */
1131 #define MDB_TXN_FINISHED 0x01 /**< txn is finished or never began */
1132 #define MDB_TXN_ERROR 0x02 /**< txn is unusable after an error */
1133 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
1134 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
1135 #define MDB_TXN_HAS_CHILD 0x10 /**< txn has an #MDB_txn.%mt_child */
1136 /** most operations on the txn are currently illegal */
1137 #define MDB_TXN_BLOCKED (MDB_TXN_FINISHED|MDB_TXN_ERROR|MDB_TXN_HAS_CHILD)
1139 unsigned int mt_flags; /**< @ref mdb_txn */
1140 /** #dirty_list room: Array size - \#dirty pages visible to this txn.
1141 * Includes ancestor txns' dirty pages not hidden by other txns'
1142 * dirty/spilled pages. Thus commit(nested txn) has room to merge
1143 * dirty_list into mt_parent after freeing hidden mt_parent pages.
1145 unsigned int mt_dirty_room;
1148 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
1149 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
1150 * raise this on a 64 bit machine.
1152 #define CURSOR_STACK 32
1156 /** Cursors are used for all DB operations.
1157 * A cursor holds a path of (page pointer, key index) from the DB
1158 * root to a position in the DB, plus other state. #MDB_DUPSORT
1159 * cursors include an xcursor to the current data item. Write txns
1160 * track their cursors and keep them up to date when data moves.
1161 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
1162 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
1165 /** Next cursor on this DB in this txn */
1166 MDB_cursor *mc_next;
1167 /** Backup of the original cursor if this cursor is a shadow */
1168 MDB_cursor *mc_backup;
1169 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
1170 struct MDB_xcursor *mc_xcursor;
1171 /** The transaction that owns this cursor */
1173 /** The database handle this cursor operates on */
1175 /** The database record for this cursor */
1177 /** The database auxiliary record for this cursor */
1179 /** The @ref mt_dbflag for this database */
1180 unsigned char *mc_dbflag;
1181 unsigned short mc_snum; /**< number of pushed pages */
1182 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
1183 /** @defgroup mdb_cursor Cursor Flags
1185 * Cursor state flags.
1188 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
1189 #define C_EOF 0x02 /**< No more data */
1190 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
1191 #define C_DEL 0x08 /**< last op was a cursor_del */
1192 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
1194 unsigned int mc_flags; /**< @ref mdb_cursor */
1195 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
1196 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
1199 /** Context for sorted-dup records.
1200 * We could have gone to a fully recursive design, with arbitrarily
1201 * deep nesting of sub-databases. But for now we only handle these
1202 * levels - main DB, optional sub-DB, sorted-duplicate DB.
1204 typedef struct MDB_xcursor {
1205 /** A sub-cursor for traversing the Dup DB */
1206 MDB_cursor mx_cursor;
1207 /** The database record for this Dup DB */
1209 /** The auxiliary DB record for this Dup DB */
1211 /** The @ref mt_dbflag for this Dup DB */
1212 unsigned char mx_dbflag;
1215 /** Check if there is an inited xcursor, so #XCURSOR_REFRESH() is proper */
1216 #define XCURSOR_INITED(mc) \
1217 ((mc)->mc_xcursor && ((mc)->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
1219 /** Update sub-page pointer, if any, in \b mc->mc_xcursor. Needed
1220 * when the node which contains the sub-page may have moved. Called
1221 * with \b mp = mc->mc_pg[mc->mc_top], \b ki = mc->mc_ki[mc->mc_top].
1223 #define XCURSOR_REFRESH(mc, mp, ki) do { \
1224 MDB_page *xr_pg = (mp); \
1225 MDB_node *xr_node = NODEPTR(xr_pg, ki); \
1226 if ((xr_node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) \
1227 (mc)->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(xr_node); \
1230 /** State of FreeDB old pages, stored in the MDB_env */
1231 typedef struct MDB_pgstate {
1232 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1233 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1236 /** The database environment. */
1238 HANDLE me_fd; /**< The main data file */
1239 HANDLE me_lfd; /**< The lock file */
1240 HANDLE me_mfd; /**< just for writing the meta pages */
1241 /** Failed to update the meta page. Probably an I/O error. */
1242 #define MDB_FATAL_ERROR 0x80000000U
1243 /** Some fields are initialized. */
1244 #define MDB_ENV_ACTIVE 0x20000000U
1245 /** me_txkey is set */
1246 #define MDB_ENV_TXKEY 0x10000000U
1247 /** fdatasync is unreliable */
1248 #define MDB_FSYNCONLY 0x08000000U
1249 uint32_t me_flags; /**< @ref mdb_env */
1250 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1251 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1252 unsigned int me_maxreaders; /**< size of the reader table */
1253 /** Max #MDB_txninfo.%mti_numreaders of interest to #mdb_env_close() */
1254 volatile int me_close_readers;
1255 MDB_dbi me_numdbs; /**< number of DBs opened */
1256 MDB_dbi me_maxdbs; /**< size of the DB table */
1257 MDB_PID_T me_pid; /**< process ID of this env */
1258 char *me_path; /**< path to the DB files */
1259 char *me_map; /**< the memory map of the data file */
1260 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1261 MDB_meta *me_metas[NUM_METAS]; /**< pointers to the two meta pages */
1262 void *me_pbuf; /**< scratch area for DUPSORT put() */
1263 MDB_txn *me_txn; /**< current write transaction */
1264 MDB_txn *me_txn0; /**< prealloc'd write transaction */
1265 size_t me_mapsize; /**< size of the data memory map */
1266 off_t me_size; /**< current file size */
1267 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1268 MDB_dbx *me_dbxs; /**< array of static DB info */
1269 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1270 unsigned int *me_dbiseqs; /**< array of dbi sequence numbers */
1271 pthread_key_t me_txkey; /**< thread-key for readers */
1272 txnid_t me_pgoldest; /**< ID of oldest reader last time we looked */
1273 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1274 # define me_pglast me_pgstate.mf_pglast
1275 # define me_pghead me_pgstate.mf_pghead
1276 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1277 /** IDL of pages that became unused in a write txn */
1278 MDB_IDL me_free_pgs;
1279 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1280 MDB_ID2L me_dirty_list;
1281 /** Max number of freelist items that can fit in a single overflow page */
1283 /** Max size of a node on a page */
1284 unsigned int me_nodemax;
1285 #if !(MDB_MAXKEYSIZE)
1286 unsigned int me_maxkey; /**< max size of a key */
1288 int me_live_reader; /**< have liveness lock in reader table */
1290 int me_pidquery; /**< Used in OpenProcess */
1292 #ifdef MDB_USE_POSIX_MUTEX /* Posix mutexes reside in shared mem */
1293 # define me_rmutex me_txns->mti_rmutex /**< Shared reader lock */
1294 # define me_wmutex me_txns->mti_wmutex /**< Shared writer lock */
1296 mdb_mutex_t me_rmutex;
1297 mdb_mutex_t me_wmutex;
1299 void *me_userctx; /**< User-settable context */
1300 MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
1303 /** Nested transaction */
1304 typedef struct MDB_ntxn {
1305 MDB_txn mnt_txn; /**< the transaction */
1306 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1309 /** max number of pages to commit in one writev() call */
1310 #define MDB_COMMIT_PAGES 64
1311 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1312 #undef MDB_COMMIT_PAGES
1313 #define MDB_COMMIT_PAGES IOV_MAX
1316 /** max bytes to write in one call */
1317 #define MAX_WRITE (0x40000000U >> (sizeof(ssize_t) == 4))
1319 /** Check \b txn and \b dbi arguments to a function */
1320 #define TXN_DBI_EXIST(txn, dbi, validity) \
1321 ((txn) && (dbi)<(txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & (validity)))
1323 /** Check for misused \b dbi handles */
1324 #define TXN_DBI_CHANGED(txn, dbi) \
1325 ((txn)->mt_dbiseqs[dbi] != (txn)->mt_env->me_dbiseqs[dbi])
1327 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1328 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1329 static int mdb_page_touch(MDB_cursor *mc);
1331 #define MDB_END_NAMES {"committed", "empty-commit", "abort", "reset", \
1332 "reset-tmp", "fail-begin", "fail-beginchild"}
1334 /* mdb_txn_end operation number, for logging */
1335 MDB_END_COMMITTED, MDB_END_EMPTY_COMMIT, MDB_END_ABORT, MDB_END_RESET,
1336 MDB_END_RESET_TMP, MDB_END_FAIL_BEGIN, MDB_END_FAIL_BEGINCHILD
1338 #define MDB_END_OPMASK 0x0F /**< mask for #mdb_txn_end() operation number */
1339 #define MDB_END_UPDATE 0x10 /**< update env state (DBIs) */
1340 #define MDB_END_FREE 0x20 /**< free txn unless it is #MDB_env.%me_txn0 */
1341 #define MDB_END_SLOT MDB_NOTLS /**< release any reader slot if #MDB_NOTLS */
1342 static void mdb_txn_end(MDB_txn *txn, unsigned mode);
1344 static int mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **mp, int *lvl);
1345 static int mdb_page_search_root(MDB_cursor *mc,
1346 MDB_val *key, int modify);
1347 #define MDB_PS_MODIFY 1
1348 #define MDB_PS_ROOTONLY 2
1349 #define MDB_PS_FIRST 4
1350 #define MDB_PS_LAST 8
1351 static int mdb_page_search(MDB_cursor *mc,
1352 MDB_val *key, int flags);
1353 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1355 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1356 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1357 pgno_t newpgno, unsigned int nflags);
1359 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1360 static MDB_meta *mdb_env_pick_meta(const MDB_env *env);
1361 static int mdb_env_write_meta(MDB_txn *txn);
1362 #ifdef MDB_USE_POSIX_MUTEX /* Drop unused excl arg */
1363 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1365 static void mdb_env_close0(MDB_env *env, int excl);
1367 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1368 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1369 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1370 static void mdb_node_del(MDB_cursor *mc, int ksize);
1371 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1372 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft);
1373 static int mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data);
1374 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1375 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1377 static int mdb_rebalance(MDB_cursor *mc);
1378 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1380 static void mdb_cursor_pop(MDB_cursor *mc);
1381 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1383 static int mdb_cursor_del0(MDB_cursor *mc);
1384 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
1385 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1386 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1387 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1388 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1390 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1391 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1393 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1394 static void mdb_xcursor_init0(MDB_cursor *mc);
1395 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1396 static void mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int force);
1398 static int mdb_drop0(MDB_cursor *mc, int subs);
1399 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1400 static int mdb_reader_check0(MDB_env *env, int rlocked, int *dead);
1403 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1406 /** Compare two items pointing at size_t's of unknown alignment. */
1407 #ifdef MISALIGNED_OK
1408 # define mdb_cmp_clong mdb_cmp_long
1410 # define mdb_cmp_clong mdb_cmp_cint
1414 static SECURITY_DESCRIPTOR mdb_null_sd;
1415 static SECURITY_ATTRIBUTES mdb_all_sa;
1416 static int mdb_sec_inited;
1418 static int utf8_to_utf16(const char *src, int srcsize, wchar_t **dst, int *dstsize);
1421 /** Return the library version info. */
1423 mdb_version(int *major, int *minor, int *patch)
1425 if (major) *major = MDB_VERSION_MAJOR;
1426 if (minor) *minor = MDB_VERSION_MINOR;
1427 if (patch) *patch = MDB_VERSION_PATCH;
1428 return MDB_VERSION_STRING;
1431 /** Table of descriptions for LMDB @ref errors */
1432 static char *const mdb_errstr[] = {
1433 "MDB_KEYEXIST: Key/data pair already exists",
1434 "MDB_NOTFOUND: No matching key/data pair found",
1435 "MDB_PAGE_NOTFOUND: Requested page not found",
1436 "MDB_CORRUPTED: Located page was wrong type",
1437 "MDB_PANIC: Update of meta page failed or environment had fatal error",
1438 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1439 "MDB_INVALID: File is not an LMDB file",
1440 "MDB_MAP_FULL: Environment mapsize limit reached",
1441 "MDB_DBS_FULL: Environment maxdbs limit reached",
1442 "MDB_READERS_FULL: Environment maxreaders limit reached",
1443 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1444 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1445 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1446 "MDB_PAGE_FULL: Internal error - page has no more space",
1447 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1448 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1449 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1450 "MDB_BAD_TXN: Transaction must abort, has a child, or is invalid",
1451 "MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
1452 "MDB_BAD_DBI: The specified DBI handle was closed/changed unexpectedly",
1456 mdb_strerror(int err)
1459 /** HACK: pad 4KB on stack over the buf. Return system msgs in buf.
1460 * This works as long as no function between the call to mdb_strerror
1461 * and the actual use of the message uses more than 4K of stack.
1463 #define MSGSIZE 1024
1464 #define PADSIZE 4096
1465 char buf[MSGSIZE+PADSIZE], *ptr = buf;
1469 return ("Successful return: 0");
1471 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1472 i = err - MDB_KEYEXIST;
1473 return mdb_errstr[i];
1477 /* These are the C-runtime error codes we use. The comment indicates
1478 * their numeric value, and the Win32 error they would correspond to
1479 * if the error actually came from a Win32 API. A major mess, we should
1480 * have used LMDB-specific error codes for everything.
1483 case ENOENT: /* 2, FILE_NOT_FOUND */
1484 case EIO: /* 5, ACCESS_DENIED */
1485 case ENOMEM: /* 12, INVALID_ACCESS */
1486 case EACCES: /* 13, INVALID_DATA */
1487 case EBUSY: /* 16, CURRENT_DIRECTORY */
1488 case EINVAL: /* 22, BAD_COMMAND */
1489 case ENOSPC: /* 28, OUT_OF_PAPER */
1490 return strerror(err);
1495 FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
1496 FORMAT_MESSAGE_IGNORE_INSERTS,
1497 NULL, err, 0, ptr, MSGSIZE, (va_list *)buf+MSGSIZE);
1500 return strerror(err);
1504 /** assert(3) variant in cursor context */
1505 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1506 /** assert(3) variant in transaction context */
1507 #define mdb_tassert(txn, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1508 /** assert(3) variant in environment context */
1509 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1512 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1513 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1516 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1517 const char *func, const char *file, int line)
1520 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1521 file, line, expr_txt, func);
1522 if (env->me_assert_func)
1523 env->me_assert_func(env, buf);
1524 fprintf(stderr, "%s\n", buf);
1528 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1532 /** Return the page number of \b mp which may be sub-page, for debug output */
1534 mdb_dbg_pgno(MDB_page *mp)
1537 COPY_PGNO(ret, mp->mp_pgno);
1541 /** Display a key in hexadecimal and return the address of the result.
1542 * @param[in] key the key to display
1543 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1544 * @return The key in hexadecimal form.
1547 mdb_dkey(MDB_val *key, char *buf)
1550 unsigned char *c = key->mv_data;
1556 if (key->mv_size > DKBUF_MAXKEYSIZE)
1557 return "MDB_MAXKEYSIZE";
1558 /* may want to make this a dynamic check: if the key is mostly
1559 * printable characters, print it as-is instead of converting to hex.
1563 for (i=0; i<key->mv_size; i++)
1564 ptr += sprintf(ptr, "%02x", *c++);
1566 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1572 mdb_leafnode_type(MDB_node *n)
1574 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1575 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1576 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1579 /** Display all the keys in the page. */
1581 mdb_page_list(MDB_page *mp)
1583 pgno_t pgno = mdb_dbg_pgno(mp);
1584 const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
1586 unsigned int i, nkeys, nsize, total = 0;
1590 switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1591 case P_BRANCH: type = "Branch page"; break;
1592 case P_LEAF: type = "Leaf page"; break;
1593 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1594 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1595 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1597 fprintf(stderr, "Overflow page %"Z"u pages %u%s\n",
1598 pgno, mp->mp_pages, state);
1601 fprintf(stderr, "Meta-page %"Z"u txnid %"Z"u\n",
1602 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1605 fprintf(stderr, "Bad page %"Z"u flags 0x%X\n", pgno, mp->mp_flags);
1609 nkeys = NUMKEYS(mp);
1610 fprintf(stderr, "%s %"Z"u numkeys %d%s\n", type, pgno, nkeys, state);
1612 for (i=0; i<nkeys; i++) {
1613 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1614 key.mv_size = nsize = mp->mp_pad;
1615 key.mv_data = LEAF2KEY(mp, i, nsize);
1617 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1620 node = NODEPTR(mp, i);
1621 key.mv_size = node->mn_ksize;
1622 key.mv_data = node->mn_data;
1623 nsize = NODESIZE + key.mv_size;
1624 if (IS_BRANCH(mp)) {
1625 fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
1629 if (F_ISSET(node->mn_flags, F_BIGDATA))
1630 nsize += sizeof(pgno_t);
1632 nsize += NODEDSZ(node);
1634 nsize += sizeof(indx_t);
1635 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1636 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1638 total = EVEN(total);
1640 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1641 IS_LEAF2(mp) ? PAGEHDRSZ : PAGEBASE + mp->mp_lower, total, SIZELEFT(mp));
1645 mdb_cursor_chk(MDB_cursor *mc)
1651 if (!mc->mc_snum || !(mc->mc_flags & C_INITIALIZED)) return;
1652 for (i=0; i<mc->mc_top; i++) {
1654 node = NODEPTR(mp, mc->mc_ki[i]);
1655 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1658 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1660 if (XCURSOR_INITED(mc)) {
1661 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
1662 if (((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) &&
1663 mc->mc_xcursor->mx_cursor.mc_pg[0] != NODEDATA(node)) {
1671 /** Count all the pages in each DB and in the freelist
1672 * and make sure it matches the actual number of pages
1674 * All named DBs must be open for a correct count.
1676 static void mdb_audit(MDB_txn *txn)
1680 MDB_ID freecount, count;
1685 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1686 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1687 freecount += *(MDB_ID *)data.mv_data;
1688 mdb_tassert(txn, rc == MDB_NOTFOUND);
1691 for (i = 0; i<txn->mt_numdbs; i++) {
1693 if (!(txn->mt_dbflags[i] & DB_VALID))
1695 mdb_cursor_init(&mc, txn, i, &mx);
1696 if (txn->mt_dbs[i].md_root == P_INVALID)
1698 count += txn->mt_dbs[i].md_branch_pages +
1699 txn->mt_dbs[i].md_leaf_pages +
1700 txn->mt_dbs[i].md_overflow_pages;
1701 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1702 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1703 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
1706 mp = mc.mc_pg[mc.mc_top];
1707 for (j=0; j<NUMKEYS(mp); j++) {
1708 MDB_node *leaf = NODEPTR(mp, j);
1709 if (leaf->mn_flags & F_SUBDATA) {
1711 memcpy(&db, NODEDATA(leaf), sizeof(db));
1712 count += db.md_branch_pages + db.md_leaf_pages +
1713 db.md_overflow_pages;
1717 mdb_tassert(txn, rc == MDB_NOTFOUND);
1720 if (freecount + count + NUM_METAS != txn->mt_next_pgno) {
1721 fprintf(stderr, "audit: %"Z"u freecount: %"Z"u count: %"Z"u total: %"Z"u next_pgno: %"Z"u\n",
1722 txn->mt_txnid, freecount, count+NUM_METAS,
1723 freecount+count+NUM_METAS, txn->mt_next_pgno);
1729 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1731 return txn->mt_dbxs[dbi].md_cmp(a, b);
1735 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1737 MDB_cmp_func *dcmp = txn->mt_dbxs[dbi].md_dcmp;
1738 #if UINT_MAX < SIZE_MAX
1739 if (dcmp == mdb_cmp_int && a->mv_size == sizeof(size_t))
1740 dcmp = mdb_cmp_clong;
1745 /** Allocate memory for a page.
1746 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1749 mdb_page_malloc(MDB_txn *txn, unsigned num)
1751 MDB_env *env = txn->mt_env;
1752 MDB_page *ret = env->me_dpages;
1753 size_t psize = env->me_psize, sz = psize, off;
1754 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1755 * For a single page alloc, we init everything after the page header.
1756 * For multi-page, we init the final page; if the caller needed that
1757 * many pages they will be filling in at least up to the last page.
1761 VGMEMP_ALLOC(env, ret, sz);
1762 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1763 env->me_dpages = ret->mp_next;
1766 psize -= off = PAGEHDRSZ;
1771 if ((ret = malloc(sz)) != NULL) {
1772 VGMEMP_ALLOC(env, ret, sz);
1773 if (!(env->me_flags & MDB_NOMEMINIT)) {
1774 memset((char *)ret + off, 0, psize);
1778 txn->mt_flags |= MDB_TXN_ERROR;
1782 /** Free a single page.
1783 * Saves single pages to a list, for future reuse.
1784 * (This is not used for multi-page overflow pages.)
1787 mdb_page_free(MDB_env *env, MDB_page *mp)
1789 mp->mp_next = env->me_dpages;
1790 VGMEMP_FREE(env, mp);
1791 env->me_dpages = mp;
1794 /** Free a dirty page */
1796 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1798 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1799 mdb_page_free(env, dp);
1801 /* large pages just get freed directly */
1802 VGMEMP_FREE(env, dp);
1807 /** Return all dirty pages to dpage list */
1809 mdb_dlist_free(MDB_txn *txn)
1811 MDB_env *env = txn->mt_env;
1812 MDB_ID2L dl = txn->mt_u.dirty_list;
1813 unsigned i, n = dl[0].mid;
1815 for (i = 1; i <= n; i++) {
1816 mdb_dpage_free(env, dl[i].mptr);
1821 /** Loosen or free a single page.
1822 * Saves single pages to a list for future reuse
1823 * in this same txn. It has been pulled from the freeDB
1824 * and already resides on the dirty list, but has been
1825 * deleted. Use these pages first before pulling again
1828 * If the page wasn't dirtied in this txn, just add it
1829 * to this txn's free list.
1832 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
1835 pgno_t pgno = mp->mp_pgno;
1836 MDB_txn *txn = mc->mc_txn;
1838 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
1839 if (txn->mt_parent) {
1840 MDB_ID2 *dl = txn->mt_u.dirty_list;
1841 /* If txn has a parent, make sure the page is in our
1845 unsigned x = mdb_mid2l_search(dl, pgno);
1846 if (x <= dl[0].mid && dl[x].mid == pgno) {
1847 if (mp != dl[x].mptr) { /* bad cursor? */
1848 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1849 txn->mt_flags |= MDB_TXN_ERROR;
1850 return MDB_CORRUPTED;
1857 /* no parent txn, so it's just ours */
1862 DPRINTF(("loosen db %d page %"Z"u", DDBI(mc),
1864 NEXT_LOOSE_PAGE(mp) = txn->mt_loose_pgs;
1865 txn->mt_loose_pgs = mp;
1866 txn->mt_loose_count++;
1867 mp->mp_flags |= P_LOOSE;
1869 int rc = mdb_midl_append(&txn->mt_free_pgs, pgno);
1877 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
1878 * @param[in] mc A cursor handle for the current operation.
1879 * @param[in] pflags Flags of the pages to update:
1880 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1881 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
1882 * @return 0 on success, non-zero on failure.
1885 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
1887 enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
1888 MDB_txn *txn = mc->mc_txn;
1889 MDB_cursor *m3, *m0 = mc;
1894 int rc = MDB_SUCCESS, level;
1896 /* Mark pages seen by cursors */
1897 if (mc->mc_flags & C_UNTRACK)
1898 mc = NULL; /* will find mc in mt_cursors */
1899 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1900 for (; mc; mc=mc->mc_next) {
1901 if (!(mc->mc_flags & C_INITIALIZED))
1903 for (m3 = mc;; m3 = &mx->mx_cursor) {
1905 for (j=0; j<m3->mc_snum; j++) {
1907 if ((mp->mp_flags & Mask) == pflags)
1908 mp->mp_flags ^= P_KEEP;
1910 mx = m3->mc_xcursor;
1911 /* Proceed to mx if it is at a sub-database */
1912 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
1914 if (! (mp && (mp->mp_flags & P_LEAF)))
1916 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
1917 if (!(leaf->mn_flags & F_SUBDATA))
1926 /* Mark dirty root pages */
1927 for (i=0; i<txn->mt_numdbs; i++) {
1928 if (txn->mt_dbflags[i] & DB_DIRTY) {
1929 pgno_t pgno = txn->mt_dbs[i].md_root;
1930 if (pgno == P_INVALID)
1932 if ((rc = mdb_page_get(m0, pgno, &dp, &level)) != MDB_SUCCESS)
1934 if ((dp->mp_flags & Mask) == pflags && level <= 1)
1935 dp->mp_flags ^= P_KEEP;
1943 static int mdb_page_flush(MDB_txn *txn, int keep);
1945 /** Spill pages from the dirty list back to disk.
1946 * This is intended to prevent running into #MDB_TXN_FULL situations,
1947 * but note that they may still occur in a few cases:
1948 * 1) our estimate of the txn size could be too small. Currently this
1949 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
1950 * 2) child txns may run out of space if their parents dirtied a
1951 * lot of pages and never spilled them. TODO: we probably should do
1952 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1953 * the parent's dirty_room is below a given threshold.
1955 * Otherwise, if not using nested txns, it is expected that apps will
1956 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1957 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1958 * If the txn never references them again, they can be left alone.
1959 * If the txn only reads them, they can be used without any fuss.
1960 * If the txn writes them again, they can be dirtied immediately without
1961 * going thru all of the work of #mdb_page_touch(). Such references are
1962 * handled by #mdb_page_unspill().
1964 * Also note, we never spill DB root pages, nor pages of active cursors,
1965 * because we'll need these back again soon anyway. And in nested txns,
1966 * we can't spill a page in a child txn if it was already spilled in a
1967 * parent txn. That would alter the parent txns' data even though
1968 * the child hasn't committed yet, and we'd have no way to undo it if
1969 * the child aborted.
1971 * @param[in] m0 cursor A cursor handle identifying the transaction and
1972 * database for which we are checking space.
1973 * @param[in] key For a put operation, the key being stored.
1974 * @param[in] data For a put operation, the data being stored.
1975 * @return 0 on success, non-zero on failure.
1978 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1980 MDB_txn *txn = m0->mc_txn;
1982 MDB_ID2L dl = txn->mt_u.dirty_list;
1983 unsigned int i, j, need;
1986 if (m0->mc_flags & C_SUB)
1989 /* Estimate how much space this op will take */
1990 i = m0->mc_db->md_depth;
1991 /* Named DBs also dirty the main DB */
1992 if (m0->mc_dbi >= CORE_DBS)
1993 i += txn->mt_dbs[MAIN_DBI].md_depth;
1994 /* For puts, roughly factor in the key+data size */
1996 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
1997 i += i; /* double it for good measure */
2000 if (txn->mt_dirty_room > i)
2003 if (!txn->mt_spill_pgs) {
2004 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
2005 if (!txn->mt_spill_pgs)
2008 /* purge deleted slots */
2009 MDB_IDL sl = txn->mt_spill_pgs;
2010 unsigned int num = sl[0];
2012 for (i=1; i<=num; i++) {
2019 /* Preserve pages which may soon be dirtied again */
2020 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
2023 /* Less aggressive spill - we originally spilled the entire dirty list,
2024 * with a few exceptions for cursor pages and DB root pages. But this
2025 * turns out to be a lot of wasted effort because in a large txn many
2026 * of those pages will need to be used again. So now we spill only 1/8th
2027 * of the dirty pages. Testing revealed this to be a good tradeoff,
2028 * better than 1/2, 1/4, or 1/10.
2030 if (need < MDB_IDL_UM_MAX / 8)
2031 need = MDB_IDL_UM_MAX / 8;
2033 /* Save the page IDs of all the pages we're flushing */
2034 /* flush from the tail forward, this saves a lot of shifting later on. */
2035 for (i=dl[0].mid; i && need; i--) {
2036 MDB_ID pn = dl[i].mid << 1;
2038 if (dp->mp_flags & (P_LOOSE|P_KEEP))
2040 /* Can't spill twice, make sure it's not already in a parent's
2043 if (txn->mt_parent) {
2045 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
2046 if (tx2->mt_spill_pgs) {
2047 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
2048 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
2049 dp->mp_flags |= P_KEEP;
2057 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
2061 mdb_midl_sort(txn->mt_spill_pgs);
2063 /* Flush the spilled part of dirty list */
2064 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
2067 /* Reset any dirty pages we kept that page_flush didn't see */
2068 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
2071 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
2075 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
2077 mdb_find_oldest(MDB_txn *txn)
2080 txnid_t mr, oldest = txn->mt_txnid - 1;
2081 if (txn->mt_env->me_txns) {
2082 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
2083 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
2094 /** Add a page to the txn's dirty list */
2096 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
2099 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
2101 if (txn->mt_flags & MDB_TXN_WRITEMAP) {
2102 insert = mdb_mid2l_append;
2104 insert = mdb_mid2l_insert;
2106 mid.mid = mp->mp_pgno;
2108 rc = insert(txn->mt_u.dirty_list, &mid);
2109 mdb_tassert(txn, rc == 0);
2110 txn->mt_dirty_room--;
2113 /** Allocate page numbers and memory for writing. Maintain me_pglast,
2114 * me_pghead and mt_next_pgno.
2116 * If there are free pages available from older transactions, they
2117 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
2118 * Do not modify the freedB, just merge freeDB records into me_pghead[]
2119 * and move me_pglast to say which records were consumed. Only this
2120 * function can create me_pghead and move me_pglast/mt_next_pgno.
2121 * @param[in] mc cursor A cursor handle identifying the transaction and
2122 * database for which we are allocating.
2123 * @param[in] num the number of pages to allocate.
2124 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
2125 * will always be satisfied by a single contiguous chunk of memory.
2126 * @return 0 on success, non-zero on failure.
2129 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
2131 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
2132 /* Get at most <Max_retries> more freeDB records once me_pghead
2133 * has enough pages. If not enough, use new pages from the map.
2134 * If <Paranoid> and mc is updating the freeDB, only get new
2135 * records if me_pghead is empty. Then the freelist cannot play
2136 * catch-up with itself by growing while trying to save it.
2138 enum { Paranoid = 1, Max_retries = 500 };
2140 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
2142 int rc, retry = num * 60;
2143 MDB_txn *txn = mc->mc_txn;
2144 MDB_env *env = txn->mt_env;
2145 pgno_t pgno, *mop = env->me_pghead;
2146 unsigned i, j, mop_len = mop ? mop[0] : 0, n2 = num-1;
2148 txnid_t oldest = 0, last;
2153 /* If there are any loose pages, just use them */
2154 if (num == 1 && txn->mt_loose_pgs) {
2155 np = txn->mt_loose_pgs;
2156 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
2157 txn->mt_loose_count--;
2158 DPRINTF(("db %d use loose page %"Z"u", DDBI(mc),
2166 /* If our dirty list is already full, we can't do anything */
2167 if (txn->mt_dirty_room == 0) {
2172 for (op = MDB_FIRST;; op = MDB_NEXT) {
2177 /* Seek a big enough contiguous page range. Prefer
2178 * pages at the tail, just truncating the list.
2184 if (mop[i-n2] == pgno+n2)
2191 if (op == MDB_FIRST) { /* 1st iteration */
2192 /* Prepare to fetch more and coalesce */
2193 last = env->me_pglast;
2194 oldest = env->me_pgoldest;
2195 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
2198 key.mv_data = &last; /* will look up last+1 */
2199 key.mv_size = sizeof(last);
2201 if (Paranoid && mc->mc_dbi == FREE_DBI)
2204 if (Paranoid && retry < 0 && mop_len)
2208 /* Do not fetch more if the record will be too recent */
2209 if (oldest <= last) {
2211 oldest = mdb_find_oldest(txn);
2212 env->me_pgoldest = oldest;
2218 rc = mdb_cursor_get(&m2, &key, NULL, op);
2220 if (rc == MDB_NOTFOUND)
2224 last = *(txnid_t*)key.mv_data;
2225 if (oldest <= last) {
2227 oldest = mdb_find_oldest(txn);
2228 env->me_pgoldest = oldest;
2234 np = m2.mc_pg[m2.mc_top];
2235 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
2236 if ((rc = mdb_node_read(&m2, leaf, &data)) != MDB_SUCCESS)
2239 idl = (MDB_ID *) data.mv_data;
2242 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
2247 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
2249 mop = env->me_pghead;
2251 env->me_pglast = last;
2253 DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
2254 last, txn->mt_dbs[FREE_DBI].md_root, i));
2256 DPRINTF(("IDL %"Z"u", idl[j]));
2258 /* Merge in descending sorted order */
2259 mdb_midl_xmerge(mop, idl);
2263 /* Use new pages from the map when nothing suitable in the freeDB */
2265 pgno = txn->mt_next_pgno;
2266 if (pgno + num >= env->me_maxpg) {
2267 DPUTS("DB size maxed out");
2273 if (env->me_flags & MDB_WRITEMAP) {
2274 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
2276 if (!(np = mdb_page_malloc(txn, num))) {
2282 mop[0] = mop_len -= num;
2283 /* Move any stragglers down */
2284 for (j = i-num; j < mop_len; )
2285 mop[++j] = mop[++i];
2287 txn->mt_next_pgno = pgno + num;
2290 mdb_page_dirty(txn, np);
2296 txn->mt_flags |= MDB_TXN_ERROR;
2300 /** Copy the used portions of a non-overflow page.
2301 * @param[in] dst page to copy into
2302 * @param[in] src page to copy from
2303 * @param[in] psize size of a page
2306 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2308 enum { Align = sizeof(pgno_t) };
2309 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2311 /* If page isn't full, just copy the used portion. Adjust
2312 * alignment so memcpy may copy words instead of bytes.
2314 if ((unused &= -Align) && !IS_LEAF2(src)) {
2315 upper = (upper + PAGEBASE) & -Align;
2316 memcpy(dst, src, (lower + PAGEBASE + (Align-1)) & -Align);
2317 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2320 memcpy(dst, src, psize - unused);
2324 /** Pull a page off the txn's spill list, if present.
2325 * If a page being referenced was spilled to disk in this txn, bring
2326 * it back and make it dirty/writable again.
2327 * @param[in] txn the transaction handle.
2328 * @param[in] mp the page being referenced. It must not be dirty.
2329 * @param[out] ret the writable page, if any. ret is unchanged if
2330 * mp wasn't spilled.
2333 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2335 MDB_env *env = txn->mt_env;
2338 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2340 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2341 if (!tx2->mt_spill_pgs)
2343 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2344 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2347 if (txn->mt_dirty_room == 0)
2348 return MDB_TXN_FULL;
2349 if (IS_OVERFLOW(mp))
2353 if (env->me_flags & MDB_WRITEMAP) {
2356 np = mdb_page_malloc(txn, num);
2360 memcpy(np, mp, num * env->me_psize);
2362 mdb_page_copy(np, mp, env->me_psize);
2365 /* If in current txn, this page is no longer spilled.
2366 * If it happens to be the last page, truncate the spill list.
2367 * Otherwise mark it as deleted by setting the LSB.
2369 if (x == txn->mt_spill_pgs[0])
2370 txn->mt_spill_pgs[0]--;
2372 txn->mt_spill_pgs[x] |= 1;
2373 } /* otherwise, if belonging to a parent txn, the
2374 * page remains spilled until child commits
2377 mdb_page_dirty(txn, np);
2378 np->mp_flags |= P_DIRTY;
2386 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2387 * @param[in] mc cursor pointing to the page to be touched
2388 * @return 0 on success, non-zero on failure.
2391 mdb_page_touch(MDB_cursor *mc)
2393 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2394 MDB_txn *txn = mc->mc_txn;
2395 MDB_cursor *m2, *m3;
2399 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2400 if (txn->mt_flags & MDB_TXN_SPILLS) {
2402 rc = mdb_page_unspill(txn, mp, &np);
2408 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2409 (rc = mdb_page_alloc(mc, 1, &np)))
2412 DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
2413 mp->mp_pgno, pgno));
2414 mdb_cassert(mc, mp->mp_pgno != pgno);
2415 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2416 /* Update the parent page, if any, to point to the new page */
2418 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2419 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2420 SETPGNO(node, pgno);
2422 mc->mc_db->md_root = pgno;
2424 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2425 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2427 /* If txn has a parent, make sure the page is in our
2431 unsigned x = mdb_mid2l_search(dl, pgno);
2432 if (x <= dl[0].mid && dl[x].mid == pgno) {
2433 if (mp != dl[x].mptr) { /* bad cursor? */
2434 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2435 txn->mt_flags |= MDB_TXN_ERROR;
2436 return MDB_CORRUPTED;
2441 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2443 np = mdb_page_malloc(txn, 1);
2448 rc = mdb_mid2l_insert(dl, &mid);
2449 mdb_cassert(mc, rc == 0);
2454 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2456 np->mp_flags |= P_DIRTY;
2459 /* Adjust cursors pointing to mp */
2460 mc->mc_pg[mc->mc_top] = np;
2461 m2 = txn->mt_cursors[mc->mc_dbi];
2462 if (mc->mc_flags & C_SUB) {
2463 for (; m2; m2=m2->mc_next) {
2464 m3 = &m2->mc_xcursor->mx_cursor;
2465 if (m3->mc_snum < mc->mc_snum) continue;
2466 if (m3->mc_pg[mc->mc_top] == mp)
2467 m3->mc_pg[mc->mc_top] = np;
2470 for (; m2; m2=m2->mc_next) {
2471 if (m2->mc_snum < mc->mc_snum) continue;
2472 if (m2 == mc) continue;
2473 if (m2->mc_pg[mc->mc_top] == mp) {
2474 m2->mc_pg[mc->mc_top] = np;
2475 if (XCURSOR_INITED(m2) && IS_LEAF(np))
2476 XCURSOR_REFRESH(m2, np, m2->mc_ki[mc->mc_top]);
2483 txn->mt_flags |= MDB_TXN_ERROR;
2488 mdb_env_sync(MDB_env *env, int force)
2491 if (env->me_flags & MDB_RDONLY)
2493 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2494 if (env->me_flags & MDB_WRITEMAP) {
2495 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2496 ? MS_ASYNC : MS_SYNC;
2497 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
2500 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2504 #ifdef BROKEN_FDATASYNC
2505 if (env->me_flags & MDB_FSYNCONLY) {
2506 if (fsync(env->me_fd))
2510 if (MDB_FDATASYNC(env->me_fd))
2517 /** Back up parent txn's cursors, then grab the originals for tracking */
2519 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2521 MDB_cursor *mc, *bk;
2526 for (i = src->mt_numdbs; --i >= 0; ) {
2527 if ((mc = src->mt_cursors[i]) != NULL) {
2528 size = sizeof(MDB_cursor);
2530 size += sizeof(MDB_xcursor);
2531 for (; mc; mc = bk->mc_next) {
2537 mc->mc_db = &dst->mt_dbs[i];
2538 /* Kill pointers into src to reduce abuse: The
2539 * user may not use mc until dst ends. But we need a valid
2540 * txn pointer here for cursor fixups to keep working.
2543 mc->mc_dbflag = &dst->mt_dbflags[i];
2544 if ((mx = mc->mc_xcursor) != NULL) {
2545 *(MDB_xcursor *)(bk+1) = *mx;
2546 mx->mx_cursor.mc_txn = dst;
2548 mc->mc_next = dst->mt_cursors[i];
2549 dst->mt_cursors[i] = mc;
2556 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2557 * @param[in] txn the transaction handle.
2558 * @param[in] merge true to keep changes to parent cursors, false to revert.
2559 * @return 0 on success, non-zero on failure.
2562 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2564 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2568 for (i = txn->mt_numdbs; --i >= 0; ) {
2569 for (mc = cursors[i]; mc; mc = next) {
2571 if ((bk = mc->mc_backup) != NULL) {
2573 /* Commit changes to parent txn */
2574 mc->mc_next = bk->mc_next;
2575 mc->mc_backup = bk->mc_backup;
2576 mc->mc_txn = bk->mc_txn;
2577 mc->mc_db = bk->mc_db;
2578 mc->mc_dbflag = bk->mc_dbflag;
2579 if ((mx = mc->mc_xcursor) != NULL)
2580 mx->mx_cursor.mc_txn = bk->mc_txn;
2582 /* Abort nested txn */
2584 if ((mx = mc->mc_xcursor) != NULL)
2585 *mx = *(MDB_xcursor *)(bk+1);
2589 /* Only malloced cursors are permanently tracked. */
2596 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2602 Pidset = F_SETLK, Pidcheck = F_GETLK
2606 /** Set or check a pid lock. Set returns 0 on success.
2607 * Check returns 0 if the process is certainly dead, nonzero if it may
2608 * be alive (the lock exists or an error happened so we do not know).
2610 * On Windows Pidset is a no-op, we merely check for the existence
2611 * of the process with the given pid. On POSIX we use a single byte
2612 * lock on the lockfile, set at an offset equal to the pid.
2615 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2617 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2620 if (op == Pidcheck) {
2621 h = OpenProcess(env->me_pidquery, FALSE, pid);
2622 /* No documented "no such process" code, but other program use this: */
2624 return ErrCode() != ERROR_INVALID_PARAMETER;
2625 /* A process exists until all handles to it close. Has it exited? */
2626 ret = WaitForSingleObject(h, 0) != 0;
2633 struct flock lock_info;
2634 memset(&lock_info, 0, sizeof(lock_info));
2635 lock_info.l_type = F_WRLCK;
2636 lock_info.l_whence = SEEK_SET;
2637 lock_info.l_start = pid;
2638 lock_info.l_len = 1;
2639 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2640 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2642 } else if ((rc = ErrCode()) == EINTR) {
2650 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2651 * @param[in] txn the transaction handle to initialize
2652 * @return 0 on success, non-zero on failure.
2655 mdb_txn_renew0(MDB_txn *txn)
2657 MDB_env *env = txn->mt_env;
2658 MDB_txninfo *ti = env->me_txns;
2660 unsigned int i, nr, flags = txn->mt_flags;
2662 int rc, new_notls = 0;
2664 if ((flags &= MDB_TXN_RDONLY) != 0) {
2666 meta = mdb_env_pick_meta(env);
2667 txn->mt_txnid = meta->mm_txnid;
2668 txn->mt_u.reader = NULL;
2670 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2671 pthread_getspecific(env->me_txkey);
2673 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2674 return MDB_BAD_RSLOT;
2676 MDB_PID_T pid = env->me_pid;
2677 MDB_THR_T tid = pthread_self();
2678 mdb_mutexref_t rmutex = env->me_rmutex;
2680 if (!env->me_live_reader) {
2681 rc = mdb_reader_pid(env, Pidset, pid);
2684 env->me_live_reader = 1;
2687 if (LOCK_MUTEX(rc, env, rmutex))
2689 nr = ti->mti_numreaders;
2690 for (i=0; i<nr; i++)
2691 if (ti->mti_readers[i].mr_pid == 0)
2693 if (i == env->me_maxreaders) {
2694 UNLOCK_MUTEX(rmutex);
2695 return MDB_READERS_FULL;
2697 r = &ti->mti_readers[i];
2698 /* Claim the reader slot, carefully since other code
2699 * uses the reader table un-mutexed: First reset the
2700 * slot, next publish it in mti_numreaders. After
2701 * that, it is safe for mdb_env_close() to touch it.
2702 * When it will be closed, we can finally claim it.
2705 r->mr_txnid = (txnid_t)-1;
2708 ti->mti_numreaders = ++nr;
2709 env->me_close_readers = nr;
2711 UNLOCK_MUTEX(rmutex);
2713 new_notls = (env->me_flags & MDB_NOTLS);
2714 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2719 do /* LY: Retry on a race, ITS#7970. */
2720 r->mr_txnid = ti->mti_txnid;
2721 while(r->mr_txnid != ti->mti_txnid);
2722 txn->mt_txnid = r->mr_txnid;
2723 txn->mt_u.reader = r;
2724 meta = env->me_metas[txn->mt_txnid & 1];
2728 /* Not yet touching txn == env->me_txn0, it may be active */
2730 if (LOCK_MUTEX(rc, env, env->me_wmutex))
2732 txn->mt_txnid = ti->mti_txnid;
2733 meta = env->me_metas[txn->mt_txnid & 1];
2735 meta = mdb_env_pick_meta(env);
2736 txn->mt_txnid = meta->mm_txnid;
2740 if (txn->mt_txnid == mdb_debug_start)
2743 txn->mt_child = NULL;
2744 txn->mt_loose_pgs = NULL;
2745 txn->mt_loose_count = 0;
2746 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2747 txn->mt_u.dirty_list = env->me_dirty_list;
2748 txn->mt_u.dirty_list[0].mid = 0;
2749 txn->mt_free_pgs = env->me_free_pgs;
2750 txn->mt_free_pgs[0] = 0;
2751 txn->mt_spill_pgs = NULL;
2753 memcpy(txn->mt_dbiseqs, env->me_dbiseqs, env->me_maxdbs * sizeof(unsigned int));
2756 /* Copy the DB info and flags */
2757 memcpy(txn->mt_dbs, meta->mm_dbs, CORE_DBS * sizeof(MDB_db));
2759 /* Moved to here to avoid a data race in read TXNs */
2760 txn->mt_next_pgno = meta->mm_last_pg+1;
2762 txn->mt_flags = flags;
2765 txn->mt_numdbs = env->me_numdbs;
2766 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
2767 x = env->me_dbflags[i];
2768 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2769 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_USRVALID|DB_STALE : 0;
2771 txn->mt_dbflags[MAIN_DBI] = DB_VALID|DB_USRVALID;
2772 txn->mt_dbflags[FREE_DBI] = DB_VALID;
2774 if (env->me_flags & MDB_FATAL_ERROR) {
2775 DPUTS("environment had fatal error, must shutdown!");
2777 } else if (env->me_maxpg < txn->mt_next_pgno) {
2778 rc = MDB_MAP_RESIZED;
2782 mdb_txn_end(txn, new_notls /*0 or MDB_END_SLOT*/ | MDB_END_FAIL_BEGIN);
2787 mdb_txn_renew(MDB_txn *txn)
2791 if (!txn || !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY|MDB_TXN_FINISHED))
2794 rc = mdb_txn_renew0(txn);
2795 if (rc == MDB_SUCCESS) {
2796 DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2797 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2798 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2804 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2808 int rc, size, tsize;
2810 flags &= MDB_TXN_BEGIN_FLAGS;
2811 flags |= env->me_flags & MDB_WRITEMAP;
2813 if (env->me_flags & MDB_RDONLY & ~flags) /* write txn in RDONLY env */
2817 /* Nested transactions: Max 1 child, write txns only, no writemap */
2818 flags |= parent->mt_flags;
2819 if (flags & (MDB_RDONLY|MDB_WRITEMAP|MDB_TXN_BLOCKED)) {
2820 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
2822 /* Child txns save MDB_pgstate and use own copy of cursors */
2823 size = env->me_maxdbs * (sizeof(MDB_db)+sizeof(MDB_cursor *)+1);
2824 size += tsize = sizeof(MDB_ntxn);
2825 } else if (flags & MDB_RDONLY) {
2826 size = env->me_maxdbs * (sizeof(MDB_db)+1);
2827 size += tsize = sizeof(MDB_txn);
2829 /* Reuse preallocated write txn. However, do not touch it until
2830 * mdb_txn_renew0() succeeds, since it currently may be active.
2835 if ((txn = calloc(1, size)) == NULL) {
2836 DPRINTF(("calloc: %s", strerror(errno)));
2839 txn->mt_dbxs = env->me_dbxs; /* static */
2840 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2841 txn->mt_dbflags = (unsigned char *)txn + size - env->me_maxdbs;
2842 txn->mt_flags = flags;
2847 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2848 txn->mt_dbiseqs = parent->mt_dbiseqs;
2849 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2850 if (!txn->mt_u.dirty_list ||
2851 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2853 free(txn->mt_u.dirty_list);
2857 txn->mt_txnid = parent->mt_txnid;
2858 txn->mt_dirty_room = parent->mt_dirty_room;
2859 txn->mt_u.dirty_list[0].mid = 0;
2860 txn->mt_spill_pgs = NULL;
2861 txn->mt_next_pgno = parent->mt_next_pgno;
2862 parent->mt_flags |= MDB_TXN_HAS_CHILD;
2863 parent->mt_child = txn;
2864 txn->mt_parent = parent;
2865 txn->mt_numdbs = parent->mt_numdbs;
2866 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2867 /* Copy parent's mt_dbflags, but clear DB_NEW */
2868 for (i=0; i<txn->mt_numdbs; i++)
2869 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2871 ntxn = (MDB_ntxn *)txn;
2872 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2873 if (env->me_pghead) {
2874 size = MDB_IDL_SIZEOF(env->me_pghead);
2875 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2877 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2882 rc = mdb_cursor_shadow(parent, txn);
2884 mdb_txn_end(txn, MDB_END_FAIL_BEGINCHILD);
2885 } else { /* MDB_RDONLY */
2886 txn->mt_dbiseqs = env->me_dbiseqs;
2888 rc = mdb_txn_renew0(txn);
2891 if (txn != env->me_txn0)
2894 txn->mt_flags |= flags; /* could not change txn=me_txn0 earlier */
2896 DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2897 txn->mt_txnid, (flags & MDB_RDONLY) ? 'r' : 'w',
2898 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
2905 mdb_txn_env(MDB_txn *txn)
2907 if(!txn) return NULL;
2912 mdb_txn_id(MDB_txn *txn)
2915 return txn->mt_txnid;
2918 /** Export or close DBI handles opened in this txn. */
2920 mdb_dbis_update(MDB_txn *txn, int keep)
2923 MDB_dbi n = txn->mt_numdbs;
2924 MDB_env *env = txn->mt_env;
2925 unsigned char *tdbflags = txn->mt_dbflags;
2927 for (i = n; --i >= CORE_DBS;) {
2928 if (tdbflags[i] & DB_NEW) {
2930 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2932 char *ptr = env->me_dbxs[i].md_name.mv_data;
2934 env->me_dbxs[i].md_name.mv_data = NULL;
2935 env->me_dbxs[i].md_name.mv_size = 0;
2936 env->me_dbflags[i] = 0;
2937 env->me_dbiseqs[i]++;
2943 if (keep && env->me_numdbs < n)
2947 /** End a transaction, except successful commit of a nested transaction.
2948 * May be called twice for readonly txns: First reset it, then abort.
2949 * @param[in] txn the transaction handle to end
2950 * @param[in] mode why and how to end the transaction
2953 mdb_txn_end(MDB_txn *txn, unsigned mode)
2955 MDB_env *env = txn->mt_env;
2957 static const char *const names[] = MDB_END_NAMES;
2960 /* Export or close DBI handles opened in this txn */
2961 mdb_dbis_update(txn, mode & MDB_END_UPDATE);
2963 DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2964 names[mode & MDB_END_OPMASK],
2965 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2966 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
2968 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2969 if (txn->mt_u.reader) {
2970 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2971 if (!(env->me_flags & MDB_NOTLS)) {
2972 txn->mt_u.reader = NULL; /* txn does not own reader */
2973 } else if (mode & MDB_END_SLOT) {
2974 txn->mt_u.reader->mr_pid = 0;
2975 txn->mt_u.reader = NULL;
2976 } /* else txn owns the slot until it does MDB_END_SLOT */
2978 txn->mt_numdbs = 0; /* prevent further DBI activity */
2979 txn->mt_flags |= MDB_TXN_FINISHED;
2981 } else if (!F_ISSET(txn->mt_flags, MDB_TXN_FINISHED)) {
2982 pgno_t *pghead = env->me_pghead;
2984 if (!(mode & MDB_END_UPDATE)) /* !(already closed cursors) */
2985 mdb_cursors_close(txn, 0);
2986 if (!(env->me_flags & MDB_WRITEMAP)) {
2987 mdb_dlist_free(txn);
2991 txn->mt_flags = MDB_TXN_FINISHED;
2993 if (!txn->mt_parent) {
2994 mdb_midl_shrink(&txn->mt_free_pgs);
2995 env->me_free_pgs = txn->mt_free_pgs;
2997 env->me_pghead = NULL;
3001 mode = 0; /* txn == env->me_txn0, do not free() it */
3003 /* The writer mutex was locked in mdb_txn_begin. */
3005 UNLOCK_MUTEX(env->me_wmutex);
3007 txn->mt_parent->mt_child = NULL;
3008 txn->mt_parent->mt_flags &= ~MDB_TXN_HAS_CHILD;
3009 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
3010 mdb_midl_free(txn->mt_free_pgs);
3011 mdb_midl_free(txn->mt_spill_pgs);
3012 free(txn->mt_u.dirty_list);
3015 mdb_midl_free(pghead);
3018 if (mode & MDB_END_FREE)
3023 mdb_txn_reset(MDB_txn *txn)
3028 /* This call is only valid for read-only txns */
3029 if (!(txn->mt_flags & MDB_TXN_RDONLY))
3032 mdb_txn_end(txn, MDB_END_RESET);
3036 mdb_txn_abort(MDB_txn *txn)
3042 mdb_txn_abort(txn->mt_child);
3044 mdb_txn_end(txn, MDB_END_ABORT|MDB_END_SLOT|MDB_END_FREE);
3047 /** Save the freelist as of this transaction to the freeDB.
3048 * This changes the freelist. Keep trying until it stabilizes.
3051 mdb_freelist_save(MDB_txn *txn)
3053 /* env->me_pghead[] can grow and shrink during this call.
3054 * env->me_pglast and txn->mt_free_pgs[] can only grow.
3055 * Page numbers cannot disappear from txn->mt_free_pgs[].
3058 MDB_env *env = txn->mt_env;
3059 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
3060 txnid_t pglast = 0, head_id = 0;
3061 pgno_t freecnt = 0, *free_pgs, *mop;
3062 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
3064 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
3066 if (env->me_pghead) {
3067 /* Make sure first page of freeDB is touched and on freelist */
3068 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
3069 if (rc && rc != MDB_NOTFOUND)
3073 if (!env->me_pghead && txn->mt_loose_pgs) {
3074 /* Put loose page numbers in mt_free_pgs, since
3075 * we may be unable to return them to me_pghead.
3077 MDB_page *mp = txn->mt_loose_pgs;
3078 if ((rc = mdb_midl_need(&txn->mt_free_pgs, txn->mt_loose_count)) != 0)
3080 for (; mp; mp = NEXT_LOOSE_PAGE(mp))
3081 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
3082 txn->mt_loose_pgs = NULL;
3083 txn->mt_loose_count = 0;
3086 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
3087 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
3088 ? SSIZE_MAX : maxfree_1pg;
3091 /* Come back here after each Put() in case freelist changed */
3096 /* If using records from freeDB which we have not yet
3097 * deleted, delete them and any we reserved for me_pghead.
3099 while (pglast < env->me_pglast) {
3100 rc = mdb_cursor_first(&mc, &key, NULL);
3103 pglast = head_id = *(txnid_t *)key.mv_data;
3104 total_room = head_room = 0;
3105 mdb_tassert(txn, pglast <= env->me_pglast);
3106 rc = mdb_cursor_del(&mc, 0);
3111 /* Save the IDL of pages freed by this txn, to a single record */
3112 if (freecnt < txn->mt_free_pgs[0]) {
3114 /* Make sure last page of freeDB is touched and on freelist */
3115 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
3116 if (rc && rc != MDB_NOTFOUND)
3119 free_pgs = txn->mt_free_pgs;
3120 /* Write to last page of freeDB */
3121 key.mv_size = sizeof(txn->mt_txnid);
3122 key.mv_data = &txn->mt_txnid;
3124 freecnt = free_pgs[0];
3125 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
3126 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3129 /* Retry if mt_free_pgs[] grew during the Put() */
3130 free_pgs = txn->mt_free_pgs;
3131 } while (freecnt < free_pgs[0]);
3132 mdb_midl_sort(free_pgs);
3133 memcpy(data.mv_data, free_pgs, data.mv_size);
3136 unsigned int i = free_pgs[0];
3137 DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
3138 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
3140 DPRINTF(("IDL %"Z"u", free_pgs[i]));
3146 mop = env->me_pghead;
3147 mop_len = (mop ? mop[0] : 0) + txn->mt_loose_count;
3149 /* Reserve records for me_pghead[]. Split it if multi-page,
3150 * to avoid searching freeDB for a page range. Use keys in
3151 * range [1,me_pglast]: Smaller than txnid of oldest reader.
3153 if (total_room >= mop_len) {
3154 if (total_room == mop_len || --more < 0)
3156 } else if (head_room >= maxfree_1pg && head_id > 1) {
3157 /* Keep current record (overflow page), add a new one */
3161 /* (Re)write {key = head_id, IDL length = head_room} */
3162 total_room -= head_room;
3163 head_room = mop_len - total_room;
3164 if (head_room > maxfree_1pg && head_id > 1) {
3165 /* Overflow multi-page for part of me_pghead */
3166 head_room /= head_id; /* amortize page sizes */
3167 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
3168 } else if (head_room < 0) {
3169 /* Rare case, not bothering to delete this record */
3172 key.mv_size = sizeof(head_id);
3173 key.mv_data = &head_id;
3174 data.mv_size = (head_room + 1) * sizeof(pgno_t);
3175 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3178 /* IDL is initially empty, zero out at least the length */
3179 pgs = (pgno_t *)data.mv_data;
3180 j = head_room > clean_limit ? head_room : 0;
3184 total_room += head_room;
3187 /* Return loose page numbers to me_pghead, though usually none are
3188 * left at this point. The pages themselves remain in dirty_list.
3190 if (txn->mt_loose_pgs) {
3191 MDB_page *mp = txn->mt_loose_pgs;
3192 unsigned count = txn->mt_loose_count;
3194 /* Room for loose pages + temp IDL with same */
3195 if ((rc = mdb_midl_need(&env->me_pghead, 2*count+1)) != 0)
3197 mop = env->me_pghead;
3198 loose = mop + MDB_IDL_ALLOCLEN(mop) - count;
3199 for (count = 0; mp; mp = NEXT_LOOSE_PAGE(mp))
3200 loose[ ++count ] = mp->mp_pgno;
3202 mdb_midl_sort(loose);
3203 mdb_midl_xmerge(mop, loose);
3204 txn->mt_loose_pgs = NULL;
3205 txn->mt_loose_count = 0;
3209 /* Fill in the reserved me_pghead records */
3215 rc = mdb_cursor_first(&mc, &key, &data);
3216 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
3217 txnid_t id = *(txnid_t *)key.mv_data;
3218 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
3221 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
3223 if (len > mop_len) {
3225 data.mv_size = (len + 1) * sizeof(MDB_ID);
3227 data.mv_data = mop -= len;
3230 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
3232 if (rc || !(mop_len -= len))
3239 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
3240 * @param[in] txn the transaction that's being committed
3241 * @param[in] keep number of initial pages in dirty_list to keep dirty.
3242 * @return 0 on success, non-zero on failure.
3245 mdb_page_flush(MDB_txn *txn, int keep)
3247 MDB_env *env = txn->mt_env;
3248 MDB_ID2L dl = txn->mt_u.dirty_list;
3249 unsigned psize = env->me_psize, j;
3250 int i, pagecount = dl[0].mid, rc;
3251 size_t size = 0, pos = 0;
3253 MDB_page *dp = NULL;
3257 struct iovec iov[MDB_COMMIT_PAGES];
3258 ssize_t wpos = 0, wsize = 0, wres;
3259 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
3265 if (env->me_flags & MDB_WRITEMAP) {
3266 /* Clear dirty flags */
3267 while (++i <= pagecount) {
3269 /* Don't flush this page yet */
3270 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3271 dp->mp_flags &= ~P_KEEP;
3275 dp->mp_flags &= ~P_DIRTY;
3280 /* Write the pages */
3282 if (++i <= pagecount) {
3284 /* Don't flush this page yet */
3285 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3286 dp->mp_flags &= ~P_KEEP;
3291 /* clear dirty flag */
3292 dp->mp_flags &= ~P_DIRTY;
3295 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
3300 /* Windows actually supports scatter/gather I/O, but only on
3301 * unbuffered file handles. Since we're relying on the OS page
3302 * cache for all our data, that's self-defeating. So we just
3303 * write pages one at a time. We use the ov structure to set
3304 * the write offset, to at least save the overhead of a Seek
3307 DPRINTF(("committing page %"Z"u", pgno));
3308 memset(&ov, 0, sizeof(ov));
3309 ov.Offset = pos & 0xffffffff;
3310 ov.OffsetHigh = pos >> 16 >> 16;
3311 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
3313 DPRINTF(("WriteFile: %d", rc));
3317 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
3318 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
3321 /* Write previous page(s) */
3322 #ifdef MDB_USE_PWRITEV
3323 wres = pwritev(env->me_fd, iov, n, wpos);
3326 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
3329 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
3333 DPRINTF(("lseek: %s", strerror(rc)));
3336 wres = writev(env->me_fd, iov, n);
3339 if (wres != wsize) {
3344 DPRINTF(("Write error: %s", strerror(rc)));
3346 rc = EIO; /* TODO: Use which error code? */
3347 DPUTS("short write, filesystem full?");
3358 DPRINTF(("committing page %"Z"u", pgno));
3359 next_pos = pos + size;
3360 iov[n].iov_len = size;
3361 iov[n].iov_base = (char *)dp;
3367 /* MIPS has cache coherency issues, this is a no-op everywhere else
3368 * Note: for any size >= on-chip cache size, entire on-chip cache is
3371 CACHEFLUSH(env->me_map, txn->mt_next_pgno * env->me_psize, DCACHE);
3373 for (i = keep; ++i <= pagecount; ) {
3375 /* This is a page we skipped above */
3378 dl[j].mid = dp->mp_pgno;
3381 mdb_dpage_free(env, dp);
3386 txn->mt_dirty_room += i - j;
3392 mdb_txn_commit(MDB_txn *txn)
3395 unsigned int i, end_mode;
3401 /* mdb_txn_end() mode for a commit which writes nothing */
3402 end_mode = MDB_END_EMPTY_COMMIT|MDB_END_UPDATE|MDB_END_SLOT|MDB_END_FREE;
3404 if (txn->mt_child) {
3405 rc = mdb_txn_commit(txn->mt_child);
3412 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3416 if (txn->mt_flags & (MDB_TXN_FINISHED|MDB_TXN_ERROR)) {
3417 DPUTS("txn has failed/finished, can't commit");
3419 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3424 if (txn->mt_parent) {
3425 MDB_txn *parent = txn->mt_parent;
3429 unsigned x, y, len, ps_len;
3431 /* Append our free list to parent's */
3432 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3435 mdb_midl_free(txn->mt_free_pgs);
3436 /* Failures after this must either undo the changes
3437 * to the parent or set MDB_TXN_ERROR in the parent.
3440 parent->mt_next_pgno = txn->mt_next_pgno;
3441 parent->mt_flags = txn->mt_flags;
3443 /* Merge our cursors into parent's and close them */
3444 mdb_cursors_close(txn, 1);
3446 /* Update parent's DB table. */
3447 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3448 parent->mt_numdbs = txn->mt_numdbs;
3449 parent->mt_dbflags[FREE_DBI] = txn->mt_dbflags[FREE_DBI];
3450 parent->mt_dbflags[MAIN_DBI] = txn->mt_dbflags[MAIN_DBI];
3451 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
3452 /* preserve parent's DB_NEW status */
3453 x = parent->mt_dbflags[i] & DB_NEW;
3454 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3457 dst = parent->mt_u.dirty_list;
3458 src = txn->mt_u.dirty_list;
3459 /* Remove anything in our dirty list from parent's spill list */
3460 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3462 pspill[0] = (pgno_t)-1;
3463 /* Mark our dirty pages as deleted in parent spill list */
3464 for (i=0, len=src[0].mid; ++i <= len; ) {
3465 MDB_ID pn = src[i].mid << 1;
3466 while (pn > pspill[x])
3468 if (pn == pspill[x]) {
3473 /* Squash deleted pagenums if we deleted any */
3474 for (x=y; ++x <= ps_len; )
3475 if (!(pspill[x] & 1))
3476 pspill[++y] = pspill[x];
3480 /* Remove anything in our spill list from parent's dirty list */
3481 if (txn->mt_spill_pgs && txn->mt_spill_pgs[0]) {
3482 for (i=1; i<=txn->mt_spill_pgs[0]; i++) {
3483 MDB_ID pn = txn->mt_spill_pgs[i];
3485 continue; /* deleted spillpg */
3487 y = mdb_mid2l_search(dst, pn);
3488 if (y <= dst[0].mid && dst[y].mid == pn) {
3490 while (y < dst[0].mid) {
3499 /* Find len = length of merging our dirty list with parent's */
3501 dst[0].mid = 0; /* simplify loops */
3502 if (parent->mt_parent) {
3503 len = x + src[0].mid;
3504 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3505 for (i = x; y && i; y--) {
3506 pgno_t yp = src[y].mid;
3507 while (yp < dst[i].mid)
3509 if (yp == dst[i].mid) {
3514 } else { /* Simplify the above for single-ancestor case */
3515 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3517 /* Merge our dirty list with parent's */
3519 for (i = len; y; dst[i--] = src[y--]) {
3520 pgno_t yp = src[y].mid;
3521 while (yp < dst[x].mid)
3522 dst[i--] = dst[x--];
3523 if (yp == dst[x].mid)
3524 free(dst[x--].mptr);
3526 mdb_tassert(txn, i == x);
3528 free(txn->mt_u.dirty_list);
3529 parent->mt_dirty_room = txn->mt_dirty_room;
3530 if (txn->mt_spill_pgs) {
3531 if (parent->mt_spill_pgs) {
3532 /* TODO: Prevent failure here, so parent does not fail */
3533 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3535 parent->mt_flags |= MDB_TXN_ERROR;
3536 mdb_midl_free(txn->mt_spill_pgs);
3537 mdb_midl_sort(parent->mt_spill_pgs);
3539 parent->mt_spill_pgs = txn->mt_spill_pgs;
3543 /* Append our loose page list to parent's */
3544 for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(*lp))
3546 *lp = txn->mt_loose_pgs;
3547 parent->mt_loose_count += txn->mt_loose_count;
3549 parent->mt_child = NULL;
3550 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3555 if (txn != env->me_txn) {
3556 DPUTS("attempt to commit unknown transaction");
3561 mdb_cursors_close(txn, 0);
3563 if (!txn->mt_u.dirty_list[0].mid &&
3564 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
3567 DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
3568 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3570 /* Update DB root pointers */
3571 if (txn->mt_numdbs > CORE_DBS) {
3575 data.mv_size = sizeof(MDB_db);
3577 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3578 for (i = CORE_DBS; i < txn->mt_numdbs; i++) {
3579 if (txn->mt_dbflags[i] & DB_DIRTY) {
3580 if (TXN_DBI_CHANGED(txn, i)) {
3584 data.mv_data = &txn->mt_dbs[i];
3585 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data,
3593 rc = mdb_freelist_save(txn);
3597 mdb_midl_free(env->me_pghead);
3598 env->me_pghead = NULL;
3599 mdb_midl_shrink(&txn->mt_free_pgs);
3605 if ((rc = mdb_page_flush(txn, 0)) ||
3606 (rc = mdb_env_sync(env, 0)) ||
3607 (rc = mdb_env_write_meta(txn)))
3609 end_mode = MDB_END_COMMITTED|MDB_END_UPDATE;
3612 mdb_txn_end(txn, end_mode);
3620 /** Read the environment parameters of a DB environment before
3621 * mapping it into memory.
3622 * @param[in] env the environment handle
3623 * @param[out] meta address of where to store the meta information
3624 * @return 0 on success, non-zero on failure.
3627 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3633 enum { Size = sizeof(pbuf) };
3635 /* We don't know the page size yet, so use a minimum value.
3636 * Read both meta pages so we can use the latest one.
3639 for (i=off=0; i<NUM_METAS; i++, off += meta->mm_psize) {
3643 memset(&ov, 0, sizeof(ov));
3645 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3646 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3649 rc = pread(env->me_fd, &pbuf, Size, off);
3652 if (rc == 0 && off == 0)
3654 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3655 DPRINTF(("read: %s", mdb_strerror(rc)));
3659 p = (MDB_page *)&pbuf;
3661 if (!F_ISSET(p->mp_flags, P_META)) {
3662 DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
3667 if (m->mm_magic != MDB_MAGIC) {
3668 DPUTS("meta has invalid magic");
3672 if (m->mm_version != MDB_DATA_VERSION) {
3673 DPRINTF(("database is version %u, expected version %u",
3674 m->mm_version, MDB_DATA_VERSION));
3675 return MDB_VERSION_MISMATCH;
3678 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3684 /** Fill in most of the zeroed #MDB_meta for an empty database environment */
3686 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
3688 meta->mm_magic = MDB_MAGIC;
3689 meta->mm_version = MDB_DATA_VERSION;
3690 meta->mm_mapsize = env->me_mapsize;
3691 meta->mm_psize = env->me_psize;
3692 meta->mm_last_pg = NUM_METAS-1;
3693 meta->mm_flags = env->me_flags & 0xffff;
3694 meta->mm_flags |= MDB_INTEGERKEY; /* this is mm_dbs[FREE_DBI].md_flags */
3695 meta->mm_dbs[FREE_DBI].md_root = P_INVALID;
3696 meta->mm_dbs[MAIN_DBI].md_root = P_INVALID;
3699 /** Write the environment parameters of a freshly created DB environment.
3700 * @param[in] env the environment handle
3701 * @param[in] meta the #MDB_meta to write
3702 * @return 0 on success, non-zero on failure.
3705 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3713 memset(&ov, 0, sizeof(ov));
3714 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3716 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3719 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3720 len = pwrite(fd, ptr, size, pos); \
3721 if (len == -1 && ErrCode() == EINTR) continue; \
3722 rc = (len >= 0); break; } while(1)
3725 DPUTS("writing new meta page");
3727 psize = env->me_psize;
3729 p = calloc(NUM_METAS, psize);
3734 p->mp_flags = P_META;
3735 *(MDB_meta *)METADATA(p) = *meta;
3737 q = (MDB_page *)((char *)p + psize);
3739 q->mp_flags = P_META;
3740 *(MDB_meta *)METADATA(q) = *meta;
3742 DO_PWRITE(rc, env->me_fd, p, psize * NUM_METAS, len, 0);
3745 else if ((unsigned) len == psize * NUM_METAS)
3753 /** Update the environment info to commit a transaction.
3754 * @param[in] txn the transaction that's being committed
3755 * @return 0 on success, non-zero on failure.
3758 mdb_env_write_meta(MDB_txn *txn)
3761 MDB_meta meta, metab, *mp;
3765 int rc, len, toggle;
3774 toggle = txn->mt_txnid & 1;
3775 DPRINTF(("writing meta page %d for root page %"Z"u",
3776 toggle, txn->mt_dbs[MAIN_DBI].md_root));
3779 flags = env->me_flags;
3780 mp = env->me_metas[toggle];
3781 mapsize = env->me_metas[toggle ^ 1]->mm_mapsize;
3782 /* Persist any increases of mapsize config */
3783 if (mapsize < env->me_mapsize)
3784 mapsize = env->me_mapsize;
3786 if (flags & MDB_WRITEMAP) {
3787 mp->mm_mapsize = mapsize;
3788 mp->mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
3789 mp->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
3790 mp->mm_last_pg = txn->mt_next_pgno - 1;
3791 #if (__GNUC__ * 100 + __GNUC_MINOR__ >= 404) && /* TODO: portability */ \
3792 !(defined(__i386__) || defined(__x86_64__))
3793 /* LY: issue a memory barrier, if not x86. ITS#7969 */
3794 __sync_synchronize();
3796 mp->mm_txnid = txn->mt_txnid;
3797 if (!(flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3798 unsigned meta_size = env->me_psize;
3799 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3800 ptr = (char *)mp - PAGEHDRSZ;
3801 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
3802 r2 = (ptr - env->me_map) & (env->me_os_psize - 1);
3806 if (MDB_MSYNC(ptr, meta_size, rc)) {
3813 metab.mm_txnid = mp->mm_txnid;
3814 metab.mm_last_pg = mp->mm_last_pg;
3816 meta.mm_mapsize = mapsize;
3817 meta.mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
3818 meta.mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
3819 meta.mm_last_pg = txn->mt_next_pgno - 1;
3820 meta.mm_txnid = txn->mt_txnid;
3822 off = offsetof(MDB_meta, mm_mapsize);
3823 ptr = (char *)&meta + off;
3824 len = sizeof(MDB_meta) - off;
3825 off += (char *)mp - env->me_map;
3827 /* Write to the SYNC fd */
3828 mfd = (flags & (MDB_NOSYNC|MDB_NOMETASYNC)) ? env->me_fd : env->me_mfd;
3831 memset(&ov, 0, sizeof(ov));
3833 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3838 rc = pwrite(mfd, ptr, len, off);
3841 rc = rc < 0 ? ErrCode() : EIO;
3846 DPUTS("write failed, disk error?");
3847 /* On a failure, the pagecache still contains the new data.
3848 * Write some old data back, to prevent it from being used.
3849 * Use the non-SYNC fd; we know it will fail anyway.
3851 meta.mm_last_pg = metab.mm_last_pg;
3852 meta.mm_txnid = metab.mm_txnid;
3854 memset(&ov, 0, sizeof(ov));
3856 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3858 r2 = pwrite(env->me_fd, ptr, len, off);
3859 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
3862 env->me_flags |= MDB_FATAL_ERROR;
3865 /* MIPS has cache coherency issues, this is a no-op everywhere else */
3866 CACHEFLUSH(env->me_map + off, len, DCACHE);
3868 /* Memory ordering issues are irrelevant; since the entire writer
3869 * is wrapped by wmutex, all of these changes will become visible
3870 * after the wmutex is unlocked. Since the DB is multi-version,
3871 * readers will get consistent data regardless of how fresh or
3872 * how stale their view of these values is.
3875 env->me_txns->mti_txnid = txn->mt_txnid;
3880 /** Check both meta pages to see which one is newer.
3881 * @param[in] env the environment handle
3882 * @return newest #MDB_meta.
3885 mdb_env_pick_meta(const MDB_env *env)
3887 MDB_meta *const *metas = env->me_metas;
3888 return metas[ metas[0]->mm_txnid < metas[1]->mm_txnid ];
3892 mdb_env_create(MDB_env **env)
3896 e = calloc(1, sizeof(MDB_env));
3900 e->me_maxreaders = DEFAULT_READERS;
3901 e->me_maxdbs = e->me_numdbs = CORE_DBS;
3902 e->me_fd = INVALID_HANDLE_VALUE;
3903 e->me_lfd = INVALID_HANDLE_VALUE;
3904 e->me_mfd = INVALID_HANDLE_VALUE;
3905 #ifdef MDB_USE_POSIX_SEM
3906 e->me_rmutex = SEM_FAILED;
3907 e->me_wmutex = SEM_FAILED;
3909 e->me_pid = getpid();
3910 GET_PAGESIZE(e->me_os_psize);
3911 VGMEMP_CREATE(e,0,0);
3917 mdb_env_map(MDB_env *env, void *addr)
3920 unsigned int flags = env->me_flags;
3924 LONG sizelo, sizehi;
3927 if (flags & MDB_RDONLY) {
3928 /* Don't set explicit map size, use whatever exists */
3933 msize = env->me_mapsize;
3934 sizelo = msize & 0xffffffff;
3935 sizehi = msize >> 16 >> 16; /* only needed on Win64 */
3937 /* Windows won't create mappings for zero length files.
3938 * and won't map more than the file size.
3939 * Just set the maxsize right now.
3941 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3942 || !SetEndOfFile(env->me_fd)
3943 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3947 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3948 PAGE_READWRITE : PAGE_READONLY,
3949 sizehi, sizelo, NULL);
3952 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3953 FILE_MAP_WRITE : FILE_MAP_READ,
3955 rc = env->me_map ? 0 : ErrCode();
3960 int prot = PROT_READ;
3961 if (flags & MDB_WRITEMAP) {
3963 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3966 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
3968 if (env->me_map == MAP_FAILED) {
3973 if (flags & MDB_NORDAHEAD) {
3974 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3976 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3978 #ifdef POSIX_MADV_RANDOM
3979 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3980 #endif /* POSIX_MADV_RANDOM */
3981 #endif /* MADV_RANDOM */
3985 /* Can happen because the address argument to mmap() is just a
3986 * hint. mmap() can pick another, e.g. if the range is in use.
3987 * The MAP_FIXED flag would prevent that, but then mmap could
3988 * instead unmap existing pages to make room for the new map.
3990 if (addr && env->me_map != addr)
3991 return EBUSY; /* TODO: Make a new MDB_* error code? */
3993 p = (MDB_page *)env->me_map;
3994 env->me_metas[0] = METADATA(p);
3995 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
4001 mdb_env_set_mapsize(MDB_env *env, size_t size)
4003 /* If env is already open, caller is responsible for making
4004 * sure there are no active txns.
4012 meta = mdb_env_pick_meta(env);
4014 size = meta->mm_mapsize;
4016 /* Silently round up to minimum if the size is too small */
4017 size_t minsize = (meta->mm_last_pg + 1) * env->me_psize;
4021 munmap(env->me_map, env->me_mapsize);
4022 env->me_mapsize = size;
4023 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
4024 rc = mdb_env_map(env, old);
4028 env->me_mapsize = size;
4030 env->me_maxpg = env->me_mapsize / env->me_psize;
4035 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
4039 env->me_maxdbs = dbs + CORE_DBS;
4044 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
4046 if (env->me_map || readers < 1)
4048 env->me_maxreaders = readers;
4053 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
4055 if (!env || !readers)
4057 *readers = env->me_maxreaders;
4062 mdb_fsize(HANDLE fd, size_t *size)
4065 LARGE_INTEGER fsize;
4067 if (!GetFileSizeEx(fd, &fsize))
4070 *size = fsize.QuadPart;
4082 #ifdef BROKEN_FDATASYNC
4083 #include <sys/utsname.h>
4084 #include <sys/vfs.h>
4087 /** Further setup required for opening an LMDB environment
4090 mdb_env_open2(MDB_env *env)
4092 unsigned int flags = env->me_flags;
4093 int i, newenv = 0, rc;
4097 /* See if we should use QueryLimited */
4099 if ((rc & 0xff) > 5)
4100 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
4102 env->me_pidquery = PROCESS_QUERY_INFORMATION;
4105 #ifdef BROKEN_FDATASYNC
4106 /* ext3/ext4 fdatasync is broken on some older Linux kernels.
4107 * https://lkml.org/lkml/2012/9/3/83
4108 * Kernels after 3.6-rc6 are known good.
4109 * https://lkml.org/lkml/2012/9/10/556
4110 * See if the DB is on ext3/ext4, then check for new enough kernel
4111 * Kernels 2.6.32.60, 2.6.34.15, 3.2.30, and 3.5.4 are also known
4116 fstatfs(env->me_fd, &st);
4117 while (st.f_type == 0xEF53) {
4121 if (uts.release[0] < '3') {
4122 if (!strncmp(uts.release, "2.6.32.", 7)) {
4123 i = atoi(uts.release+7);
4125 break; /* 2.6.32.60 and newer is OK */
4126 } else if (!strncmp(uts.release, "2.6.34.", 7)) {
4127 i = atoi(uts.release+7);
4129 break; /* 2.6.34.15 and newer is OK */
4131 } else if (uts.release[0] == '3') {
4132 i = atoi(uts.release+2);
4134 break; /* 3.6 and newer is OK */
4136 i = atoi(uts.release+4);
4138 break; /* 3.5.4 and newer is OK */
4139 } else if (i == 2) {
4140 i = atoi(uts.release+4);
4142 break; /* 3.2.30 and newer is OK */
4144 } else { /* 4.x and newer is OK */
4147 env->me_flags |= MDB_FSYNCONLY;
4153 if ((i = mdb_env_read_header(env, &meta)) != 0) {
4156 DPUTS("new mdbenv");
4158 env->me_psize = env->me_os_psize;
4159 if (env->me_psize > MAX_PAGESIZE)
4160 env->me_psize = MAX_PAGESIZE;
4161 memset(&meta, 0, sizeof(meta));
4162 mdb_env_init_meta0(env, &meta);
4163 meta.mm_mapsize = DEFAULT_MAPSIZE;
4165 env->me_psize = meta.mm_psize;
4168 /* Was a mapsize configured? */
4169 if (!env->me_mapsize) {
4170 env->me_mapsize = meta.mm_mapsize;
4173 /* Make sure mapsize >= committed data size. Even when using
4174 * mm_mapsize, which could be broken in old files (ITS#7789).
4176 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
4177 if (env->me_mapsize < minsize)
4178 env->me_mapsize = minsize;
4180 meta.mm_mapsize = env->me_mapsize;
4182 if (newenv && !(flags & MDB_FIXEDMAP)) {
4183 /* mdb_env_map() may grow the datafile. Write the metapages
4184 * first, so the file will be valid if initialization fails.
4185 * Except with FIXEDMAP, since we do not yet know mm_address.
4186 * We could fill in mm_address later, but then a different
4187 * program might end up doing that - one with a memory layout
4188 * and map address which does not suit the main program.
4190 rc = mdb_env_init_meta(env, &meta);
4196 rc = mdb_env_map(env, (flags & MDB_FIXEDMAP) ? meta.mm_address : NULL);
4201 if (flags & MDB_FIXEDMAP)
4202 meta.mm_address = env->me_map;
4203 i = mdb_env_init_meta(env, &meta);
4204 if (i != MDB_SUCCESS) {
4209 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
4210 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
4212 #if !(MDB_MAXKEYSIZE)
4213 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
4215 env->me_maxpg = env->me_mapsize / env->me_psize;
4219 MDB_meta *meta = mdb_env_pick_meta(env);
4220 MDB_db *db = &meta->mm_dbs[MAIN_DBI];
4222 DPRINTF(("opened database version %u, pagesize %u",
4223 meta->mm_version, env->me_psize));
4224 DPRINTF(("using meta page %d", (int) (meta->mm_txnid & 1)));
4225 DPRINTF(("depth: %u", db->md_depth));
4226 DPRINTF(("entries: %"Z"u", db->md_entries));
4227 DPRINTF(("branch pages: %"Z"u", db->md_branch_pages));
4228 DPRINTF(("leaf pages: %"Z"u", db->md_leaf_pages));
4229 DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
4230 DPRINTF(("root: %"Z"u", db->md_root));
4238 /** Release a reader thread's slot in the reader lock table.
4239 * This function is called automatically when a thread exits.
4240 * @param[in] ptr This points to the slot in the reader lock table.
4243 mdb_env_reader_dest(void *ptr)
4245 MDB_reader *reader = ptr;
4251 /** Junk for arranging thread-specific callbacks on Windows. This is
4252 * necessarily platform and compiler-specific. Windows supports up
4253 * to 1088 keys. Let's assume nobody opens more than 64 environments
4254 * in a single process, for now. They can override this if needed.
4256 #ifndef MAX_TLS_KEYS
4257 #define MAX_TLS_KEYS 64
4259 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
4260 static int mdb_tls_nkeys;
4262 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
4266 case DLL_PROCESS_ATTACH: break;
4267 case DLL_THREAD_ATTACH: break;
4268 case DLL_THREAD_DETACH:
4269 for (i=0; i<mdb_tls_nkeys; i++) {
4270 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
4272 mdb_env_reader_dest(r);
4276 case DLL_PROCESS_DETACH: break;
4281 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4283 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4287 /* Force some symbol references.
4288 * _tls_used forces the linker to create the TLS directory if not already done
4289 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
4291 #pragma comment(linker, "/INCLUDE:_tls_used")
4292 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
4293 #pragma const_seg(".CRT$XLB")
4294 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
4295 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4298 #pragma comment(linker, "/INCLUDE:__tls_used")
4299 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
4300 #pragma data_seg(".CRT$XLB")
4301 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4303 #endif /* WIN 32/64 */
4304 #endif /* !__GNUC__ */
4307 /** Downgrade the exclusive lock on the region back to shared */
4309 mdb_env_share_locks(MDB_env *env, int *excl)
4312 MDB_meta *meta = mdb_env_pick_meta(env);
4314 env->me_txns->mti_txnid = meta->mm_txnid;
4319 /* First acquire a shared lock. The Unlock will
4320 * then release the existing exclusive lock.
4322 memset(&ov, 0, sizeof(ov));
4323 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4326 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4332 struct flock lock_info;
4333 /* The shared lock replaces the existing lock */
4334 memset((void *)&lock_info, 0, sizeof(lock_info));
4335 lock_info.l_type = F_RDLCK;
4336 lock_info.l_whence = SEEK_SET;
4337 lock_info.l_start = 0;
4338 lock_info.l_len = 1;
4339 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4340 (rc = ErrCode()) == EINTR) ;
4341 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
4348 /** Try to get exclusive lock, otherwise shared.
4349 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
4352 mdb_env_excl_lock(MDB_env *env, int *excl)
4356 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
4360 memset(&ov, 0, sizeof(ov));
4361 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4368 struct flock lock_info;
4369 memset((void *)&lock_info, 0, sizeof(lock_info));
4370 lock_info.l_type = F_WRLCK;
4371 lock_info.l_whence = SEEK_SET;
4372 lock_info.l_start = 0;
4373 lock_info.l_len = 1;
4374 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4375 (rc = ErrCode()) == EINTR) ;
4379 # ifndef MDB_USE_POSIX_MUTEX
4380 if (*excl < 0) /* always true when MDB_USE_POSIX_MUTEX */
4383 lock_info.l_type = F_RDLCK;
4384 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
4385 (rc = ErrCode()) == EINTR) ;
4395 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
4397 * @(#) $Revision: 5.1 $
4398 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
4399 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
4401 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
4405 * Please do not copyright this code. This code is in the public domain.
4407 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
4408 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
4409 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
4410 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
4411 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4412 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4413 * PERFORMANCE OF THIS SOFTWARE.
4416 * chongo <Landon Curt Noll> /\oo/\
4417 * http://www.isthe.com/chongo/
4419 * Share and Enjoy! :-)
4422 typedef unsigned long long mdb_hash_t;
4423 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
4425 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
4426 * @param[in] val value to hash
4427 * @param[in] hval initial value for hash
4428 * @return 64 bit hash
4430 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
4431 * hval arg on the first call.
4434 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
4436 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
4437 unsigned char *end = s + val->mv_size;
4439 * FNV-1a hash each octet of the string
4442 /* xor the bottom with the current octet */
4443 hval ^= (mdb_hash_t)*s++;
4445 /* multiply by the 64 bit FNV magic prime mod 2^64 */
4446 hval += (hval << 1) + (hval << 4) + (hval << 5) +
4447 (hval << 7) + (hval << 8) + (hval << 40);
4449 /* return our new hash value */
4453 /** Hash the string and output the encoded hash.
4454 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
4455 * very short name limits. We don't care about the encoding being reversible,
4456 * we just want to preserve as many bits of the input as possible in a
4457 * small printable string.
4458 * @param[in] str string to hash
4459 * @param[out] encbuf an array of 11 chars to hold the hash
4461 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
4464 mdb_pack85(unsigned long l, char *out)
4468 for (i=0; i<5; i++) {
4469 *out++ = mdb_a85[l % 85];
4475 mdb_hash_enc(MDB_val *val, char *encbuf)
4477 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
4479 mdb_pack85(h, encbuf);
4480 mdb_pack85(h>>32, encbuf+5);
4485 /** Open and/or initialize the lock region for the environment.
4486 * @param[in] env The LMDB environment.
4487 * @param[in] lpath The pathname of the file used for the lock region.
4488 * @param[in] mode The Unix permissions for the file, if we create it.
4489 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
4490 * @return 0 on success, non-zero on failure.
4493 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
4496 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
4498 # define MDB_ERRCODE_ROFS EROFS
4499 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
4500 # define MDB_CLOEXEC O_CLOEXEC
4502 # define MDB_CLOEXEC 0
4511 rc = utf8_to_utf16(lpath, -1, &wlpath, NULL);
4514 env->me_lfd = CreateFileW(wlpath, GENERIC_READ|GENERIC_WRITE,
4515 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
4516 FILE_ATTRIBUTE_NORMAL, NULL);
4519 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
4521 if (env->me_lfd == INVALID_HANDLE_VALUE) {
4523 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
4529 /* Lose record locks when exec*() */
4530 if (!(MDB_CLOEXEC) && (fdflags = fcntl(env->me_lfd, F_GETFD)) != -1)
4531 fcntl(env->me_lfd, F_SETFD, fdflags | FD_CLOEXEC);
4534 if (!(env->me_flags & MDB_NOTLS)) {
4535 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
4538 env->me_flags |= MDB_ENV_TXKEY;
4540 /* Windows TLS callbacks need help finding their TLS info. */
4541 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
4545 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
4549 /* Try to get exclusive lock. If we succeed, then
4550 * nobody is using the lock region and we should initialize it.
4552 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
4555 size = GetFileSize(env->me_lfd, NULL);
4557 size = lseek(env->me_lfd, 0, SEEK_END);
4558 if (size == -1) goto fail_errno;
4560 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
4561 if (size < rsize && *excl > 0) {
4563 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
4564 || !SetEndOfFile(env->me_lfd))
4567 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
4571 size = rsize - sizeof(MDB_txninfo);
4572 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
4577 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
4579 if (!mh) goto fail_errno;
4580 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
4582 if (!env->me_txns) goto fail_errno;
4584 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
4586 if (m == MAP_FAILED) goto fail_errno;
4592 BY_HANDLE_FILE_INFORMATION stbuf;
4601 if (!mdb_sec_inited) {
4602 InitializeSecurityDescriptor(&mdb_null_sd,
4603 SECURITY_DESCRIPTOR_REVISION);
4604 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
4605 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
4606 mdb_all_sa.bInheritHandle = FALSE;
4607 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
4610 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
4611 idbuf.volume = stbuf.dwVolumeSerialNumber;
4612 idbuf.nhigh = stbuf.nFileIndexHigh;
4613 idbuf.nlow = stbuf.nFileIndexLow;
4614 val.mv_data = &idbuf;
4615 val.mv_size = sizeof(idbuf);
4616 mdb_hash_enc(&val, encbuf);
4617 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
4618 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
4619 env->me_rmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
4620 if (!env->me_rmutex) goto fail_errno;
4621 env->me_wmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
4622 if (!env->me_wmutex) goto fail_errno;
4623 #elif defined(MDB_USE_POSIX_SEM)
4632 #if defined(__NetBSD__)
4633 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
4635 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
4636 idbuf.dev = stbuf.st_dev;
4637 idbuf.ino = stbuf.st_ino;
4638 val.mv_data = &idbuf;
4639 val.mv_size = sizeof(idbuf);
4640 mdb_hash_enc(&val, encbuf);
4641 #ifdef MDB_SHORT_SEMNAMES
4642 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
4644 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
4645 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
4646 /* Clean up after a previous run, if needed: Try to
4647 * remove both semaphores before doing anything else.
4649 sem_unlink(env->me_txns->mti_rmname);
4650 sem_unlink(env->me_txns->mti_wmname);
4651 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
4652 O_CREAT|O_EXCL, mode, 1);
4653 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4654 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
4655 O_CREAT|O_EXCL, mode, 1);
4656 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4657 #else /* MDB_USE_POSIX_MUTEX: */
4658 pthread_mutexattr_t mattr;
4660 /* Solaris needs this before initing a robust mutex. Otherwise
4661 * it may skip the init and return EBUSY "seems someone already
4662 * inited" or EINVAL "it was inited differently".
4664 memset(env->me_txns->mti_rmutex, 0, sizeof(*env->me_txns->mti_rmutex));
4665 memset(env->me_txns->mti_wmutex, 0, sizeof(*env->me_txns->mti_wmutex));
4667 if ((rc = pthread_mutexattr_init(&mattr)))
4670 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
4671 #ifdef MDB_ROBUST_SUPPORTED
4672 if (!rc) rc = pthread_mutexattr_setrobust(&mattr, PTHREAD_MUTEX_ROBUST);
4674 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_rmutex, &mattr);
4675 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_wmutex, &mattr);
4676 pthread_mutexattr_destroy(&mattr);
4679 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
4681 env->me_txns->mti_magic = MDB_MAGIC;
4682 env->me_txns->mti_format = MDB_LOCK_FORMAT;
4683 env->me_txns->mti_txnid = 0;
4684 env->me_txns->mti_numreaders = 0;
4687 if (env->me_txns->mti_magic != MDB_MAGIC) {
4688 DPUTS("lock region has invalid magic");
4692 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
4693 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
4694 env->me_txns->mti_format, MDB_LOCK_FORMAT));
4695 rc = MDB_VERSION_MISMATCH;
4699 if (rc && rc != EACCES && rc != EAGAIN) {
4703 env->me_rmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
4704 if (!env->me_rmutex) goto fail_errno;
4705 env->me_wmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
4706 if (!env->me_wmutex) goto fail_errno;
4707 #elif defined(MDB_USE_POSIX_SEM)
4708 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
4709 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4710 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
4711 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4722 /** The name of the lock file in the DB environment */
4723 #define LOCKNAME "/lock.mdb"
4724 /** The name of the data file in the DB environment */
4725 #define DATANAME "/data.mdb"
4726 /** The suffix of the lock file when no subdir is used */
4727 #define LOCKSUFF "-lock"
4728 /** Only a subset of the @ref mdb_env flags can be changed
4729 * at runtime. Changing other flags requires closing the
4730 * environment and re-opening it with the new flags.
4732 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
4733 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY| \
4734 MDB_WRITEMAP|MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
4736 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
4737 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
4741 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
4743 int oflags, rc, len, excl = -1;
4744 char *lpath, *dpath;
4749 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
4753 if (flags & MDB_NOSUBDIR) {
4754 rc = len + sizeof(LOCKSUFF) + len + 1;
4756 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
4761 if (flags & MDB_NOSUBDIR) {
4762 dpath = lpath + len + sizeof(LOCKSUFF);
4763 sprintf(lpath, "%s" LOCKSUFF, path);
4764 strcpy(dpath, path);
4766 dpath = lpath + len + sizeof(LOCKNAME);
4767 sprintf(lpath, "%s" LOCKNAME, path);
4768 sprintf(dpath, "%s" DATANAME, path);
4772 flags |= env->me_flags;
4773 if (flags & MDB_RDONLY) {
4774 /* silently ignore WRITEMAP when we're only getting read access */
4775 flags &= ~MDB_WRITEMAP;
4777 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
4778 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
4781 env->me_flags = flags |= MDB_ENV_ACTIVE;
4785 env->me_path = strdup(path);
4786 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
4787 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
4788 env->me_dbiseqs = calloc(env->me_maxdbs, sizeof(unsigned int));
4789 if (!(env->me_dbxs && env->me_path && env->me_dbflags && env->me_dbiseqs)) {
4793 env->me_dbxs[FREE_DBI].md_cmp = mdb_cmp_long; /* aligned MDB_INTEGERKEY */
4795 /* For RDONLY, get lockfile after we know datafile exists */
4796 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
4797 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4803 if (F_ISSET(flags, MDB_RDONLY)) {
4804 oflags = GENERIC_READ;
4805 len = OPEN_EXISTING;
4807 oflags = GENERIC_READ|GENERIC_WRITE;
4810 mode = FILE_ATTRIBUTE_NORMAL;
4811 rc = utf8_to_utf16(dpath, -1, &wpath, NULL);
4814 env->me_fd = CreateFileW(wpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
4815 NULL, len, mode, NULL);
4818 if (F_ISSET(flags, MDB_RDONLY))
4821 oflags = O_RDWR | O_CREAT;
4823 env->me_fd = open(dpath, oflags, mode);
4825 if (env->me_fd == INVALID_HANDLE_VALUE) {
4830 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
4831 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4836 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
4837 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
4838 env->me_mfd = env->me_fd;
4840 /* Synchronous fd for meta writes. Needed even with
4841 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
4844 len = OPEN_EXISTING;
4845 rc = utf8_to_utf16(dpath, -1, &wpath, NULL);
4848 env->me_mfd = CreateFileW(wpath, oflags,
4849 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
4850 mode | FILE_FLAG_WRITE_THROUGH, NULL);
4854 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
4856 if (env->me_mfd == INVALID_HANDLE_VALUE) {
4861 DPRINTF(("opened dbenv %p", (void *) env));
4863 rc = mdb_env_share_locks(env, &excl);
4867 if (!(flags & MDB_RDONLY)) {
4869 int tsize = sizeof(MDB_txn), size = tsize + env->me_maxdbs *
4870 (sizeof(MDB_db)+sizeof(MDB_cursor *)+sizeof(unsigned int)+1);
4871 if ((env->me_pbuf = calloc(1, env->me_psize)) &&
4872 (txn = calloc(1, size)))
4874 txn->mt_dbs = (MDB_db *)((char *)txn + tsize);
4875 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
4876 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
4877 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
4879 txn->mt_dbxs = env->me_dbxs;
4880 txn->mt_flags = MDB_TXN_FINISHED;
4890 mdb_env_close0(env, excl);
4896 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
4898 mdb_env_close0(MDB_env *env, int excl)
4902 if (!(env->me_flags & MDB_ENV_ACTIVE))
4905 /* Doing this here since me_dbxs may not exist during mdb_env_close */
4907 for (i = env->me_maxdbs; --i >= CORE_DBS; )
4908 free(env->me_dbxs[i].md_name.mv_data);
4913 free(env->me_dbiseqs);
4914 free(env->me_dbflags);
4916 free(env->me_dirty_list);
4918 mdb_midl_free(env->me_free_pgs);
4920 if (env->me_flags & MDB_ENV_TXKEY) {
4921 pthread_key_delete(env->me_txkey);
4923 /* Delete our key from the global list */
4924 for (i=0; i<mdb_tls_nkeys; i++)
4925 if (mdb_tls_keys[i] == env->me_txkey) {
4926 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
4934 munmap(env->me_map, env->me_mapsize);
4936 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
4937 (void) close(env->me_mfd);
4938 if (env->me_fd != INVALID_HANDLE_VALUE)
4939 (void) close(env->me_fd);
4941 MDB_PID_T pid = env->me_pid;
4942 /* Clearing readers is done in this function because
4943 * me_txkey with its destructor must be disabled first.
4945 * We skip the the reader mutex, so we touch only
4946 * data owned by this process (me_close_readers and
4947 * our readers), and clear each reader atomically.
4949 for (i = env->me_close_readers; --i >= 0; )
4950 if (env->me_txns->mti_readers[i].mr_pid == pid)
4951 env->me_txns->mti_readers[i].mr_pid = 0;
4953 if (env->me_rmutex) {
4954 CloseHandle(env->me_rmutex);
4955 if (env->me_wmutex) CloseHandle(env->me_wmutex);
4957 /* Windows automatically destroys the mutexes when
4958 * the last handle closes.
4960 #elif defined(MDB_USE_POSIX_SEM)
4961 if (env->me_rmutex != SEM_FAILED) {
4962 sem_close(env->me_rmutex);
4963 if (env->me_wmutex != SEM_FAILED)
4964 sem_close(env->me_wmutex);
4965 /* If we have the filelock: If we are the
4966 * only remaining user, clean up semaphores.
4969 mdb_env_excl_lock(env, &excl);
4971 sem_unlink(env->me_txns->mti_rmname);
4972 sem_unlink(env->me_txns->mti_wmname);
4976 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
4978 if (env->me_lfd != INVALID_HANDLE_VALUE) {
4981 /* Unlock the lockfile. Windows would have unlocked it
4982 * after closing anyway, but not necessarily at once.
4984 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4987 (void) close(env->me_lfd);
4990 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
4994 mdb_env_close(MDB_env *env)
5001 VGMEMP_DESTROY(env);
5002 while ((dp = env->me_dpages) != NULL) {
5003 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
5004 env->me_dpages = dp->mp_next;
5008 mdb_env_close0(env, 0);
5012 /** Compare two items pointing at aligned size_t's */
5014 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
5016 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
5017 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
5020 /** Compare two items pointing at aligned unsigned int's.
5022 * This is also set as #MDB_INTEGERDUP|#MDB_DUPFIXED's #MDB_dbx.%md_dcmp,
5023 * but #mdb_cmp_clong() is called instead if the data type is size_t.
5026 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
5028 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
5029 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
5032 /** Compare two items pointing at unsigned ints of unknown alignment.
5033 * Nodes and keys are guaranteed to be 2-byte aligned.
5036 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
5038 #if BYTE_ORDER == LITTLE_ENDIAN
5039 unsigned short *u, *c;
5042 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5043 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
5046 } while(!x && u > (unsigned short *)a->mv_data);
5049 unsigned short *u, *c, *end;
5052 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5053 u = (unsigned short *)a->mv_data;
5054 c = (unsigned short *)b->mv_data;
5057 } while(!x && u < end);
5062 /** Compare two items lexically */
5064 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
5071 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5077 diff = memcmp(a->mv_data, b->mv_data, len);
5078 return diff ? diff : len_diff<0 ? -1 : len_diff;
5081 /** Compare two items in reverse byte order */
5083 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
5085 const unsigned char *p1, *p2, *p1_lim;
5089 p1_lim = (const unsigned char *)a->mv_data;
5090 p1 = (const unsigned char *)a->mv_data + a->mv_size;
5091 p2 = (const unsigned char *)b->mv_data + b->mv_size;
5093 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5099 while (p1 > p1_lim) {
5100 diff = *--p1 - *--p2;
5104 return len_diff<0 ? -1 : len_diff;
5107 /** Search for key within a page, using binary search.
5108 * Returns the smallest entry larger or equal to the key.
5109 * If exactp is non-null, stores whether the found entry was an exact match
5110 * in *exactp (1 or 0).
5111 * Updates the cursor index with the index of the found entry.
5112 * If no entry larger or equal to the key is found, returns NULL.
5115 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
5117 unsigned int i = 0, nkeys;
5120 MDB_page *mp = mc->mc_pg[mc->mc_top];
5121 MDB_node *node = NULL;
5126 nkeys = NUMKEYS(mp);
5128 DPRINTF(("searching %u keys in %s %spage %"Z"u",
5129 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
5132 low = IS_LEAF(mp) ? 0 : 1;
5134 cmp = mc->mc_dbx->md_cmp;
5136 /* Branch pages have no data, so if using integer keys,
5137 * alignment is guaranteed. Use faster mdb_cmp_int.
5139 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
5140 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
5147 nodekey.mv_size = mc->mc_db->md_pad;
5148 node = NODEPTR(mp, 0); /* fake */
5149 while (low <= high) {
5150 i = (low + high) >> 1;
5151 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
5152 rc = cmp(key, &nodekey);
5153 DPRINTF(("found leaf index %u [%s], rc = %i",
5154 i, DKEY(&nodekey), rc));
5163 while (low <= high) {
5164 i = (low + high) >> 1;
5166 node = NODEPTR(mp, i);
5167 nodekey.mv_size = NODEKSZ(node);
5168 nodekey.mv_data = NODEKEY(node);
5170 rc = cmp(key, &nodekey);
5173 DPRINTF(("found leaf index %u [%s], rc = %i",
5174 i, DKEY(&nodekey), rc));
5176 DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
5177 i, DKEY(&nodekey), NODEPGNO(node), rc));
5188 if (rc > 0) { /* Found entry is less than the key. */
5189 i++; /* Skip to get the smallest entry larger than key. */
5191 node = NODEPTR(mp, i);
5194 *exactp = (rc == 0 && nkeys > 0);
5195 /* store the key index */
5196 mc->mc_ki[mc->mc_top] = i;
5198 /* There is no entry larger or equal to the key. */
5201 /* nodeptr is fake for LEAF2 */
5207 mdb_cursor_adjust(MDB_cursor *mc, func)
5211 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5212 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
5219 /** Pop a page off the top of the cursor's stack. */
5221 mdb_cursor_pop(MDB_cursor *mc)
5224 DPRINTF(("popping page %"Z"u off db %d cursor %p",
5225 mc->mc_pg[mc->mc_top]->mp_pgno, DDBI(mc), (void *) mc));
5231 mc->mc_flags &= ~C_INITIALIZED;
5236 /** Push a page onto the top of the cursor's stack. */
5238 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
5240 DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
5241 DDBI(mc), (void *) mc));
5243 if (mc->mc_snum >= CURSOR_STACK) {
5244 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5245 return MDB_CURSOR_FULL;
5248 mc->mc_top = mc->mc_snum++;
5249 mc->mc_pg[mc->mc_top] = mp;
5250 mc->mc_ki[mc->mc_top] = 0;
5255 /** Find the address of the page corresponding to a given page number.
5256 * @param[in] mc the cursor accessing the page.
5257 * @param[in] pgno the page number for the page to retrieve.
5258 * @param[out] ret address of a pointer where the page's address will be stored.
5259 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
5260 * @return 0 on success, non-zero on failure.
5263 mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **ret, int *lvl)
5265 MDB_txn *txn = mc->mc_txn;
5266 MDB_env *env = txn->mt_env;
5270 if (! (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_WRITEMAP))) {
5274 MDB_ID2L dl = tx2->mt_u.dirty_list;
5276 /* Spilled pages were dirtied in this txn and flushed
5277 * because the dirty list got full. Bring this page
5278 * back in from the map (but don't unspill it here,
5279 * leave that unless page_touch happens again).
5281 if (tx2->mt_spill_pgs) {
5282 MDB_ID pn = pgno << 1;
5283 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
5284 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
5285 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5290 unsigned x = mdb_mid2l_search(dl, pgno);
5291 if (x <= dl[0].mid && dl[x].mid == pgno) {
5297 } while ((tx2 = tx2->mt_parent) != NULL);
5300 if (pgno < txn->mt_next_pgno) {
5302 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5304 DPRINTF(("page %"Z"u not found", pgno));
5305 txn->mt_flags |= MDB_TXN_ERROR;
5306 return MDB_PAGE_NOTFOUND;
5316 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
5317 * The cursor is at the root page, set up the rest of it.
5320 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
5322 MDB_page *mp = mc->mc_pg[mc->mc_top];
5326 while (IS_BRANCH(mp)) {
5330 DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
5331 /* Don't assert on branch pages in the FreeDB. We can get here
5332 * while in the process of rebalancing a FreeDB branch page; we must
5333 * let that proceed. ITS#8336
5335 mdb_cassert(mc, !mc->mc_dbi || NUMKEYS(mp) > 1);
5336 DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
5338 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
5340 if (flags & MDB_PS_LAST)
5341 i = NUMKEYS(mp) - 1;
5344 node = mdb_node_search(mc, key, &exact);
5346 i = NUMKEYS(mp) - 1;
5348 i = mc->mc_ki[mc->mc_top];
5350 mdb_cassert(mc, i > 0);
5354 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
5357 mdb_cassert(mc, i < NUMKEYS(mp));
5358 node = NODEPTR(mp, i);
5360 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
5363 mc->mc_ki[mc->mc_top] = i;
5364 if ((rc = mdb_cursor_push(mc, mp)))
5367 if (flags & MDB_PS_MODIFY) {
5368 if ((rc = mdb_page_touch(mc)) != 0)
5370 mp = mc->mc_pg[mc->mc_top];
5375 DPRINTF(("internal error, index points to a %02X page!?",
5377 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5378 return MDB_CORRUPTED;
5381 DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
5382 key ? DKEY(key) : "null"));
5383 mc->mc_flags |= C_INITIALIZED;
5384 mc->mc_flags &= ~C_EOF;
5389 /** Search for the lowest key under the current branch page.
5390 * This just bypasses a NUMKEYS check in the current page
5391 * before calling mdb_page_search_root(), because the callers
5392 * are all in situations where the current page is known to
5396 mdb_page_search_lowest(MDB_cursor *mc)
5398 MDB_page *mp = mc->mc_pg[mc->mc_top];
5399 MDB_node *node = NODEPTR(mp, 0);
5402 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
5405 mc->mc_ki[mc->mc_top] = 0;
5406 if ((rc = mdb_cursor_push(mc, mp)))
5408 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
5411 /** Search for the page a given key should be in.
5412 * Push it and its parent pages on the cursor stack.
5413 * @param[in,out] mc the cursor for this operation.
5414 * @param[in] key the key to search for, or NULL for first/last page.
5415 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
5416 * are touched (updated with new page numbers).
5417 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
5418 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
5419 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
5420 * @return 0 on success, non-zero on failure.
5423 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
5428 /* Make sure the txn is still viable, then find the root from
5429 * the txn's db table and set it as the root of the cursor's stack.
5431 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED) {
5432 DPUTS("transaction may not be used now");
5435 /* Make sure we're using an up-to-date root */
5436 if (*mc->mc_dbflag & DB_STALE) {
5438 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
5440 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
5441 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
5448 MDB_node *leaf = mdb_node_search(&mc2,
5449 &mc->mc_dbx->md_name, &exact);
5451 return MDB_NOTFOUND;
5452 if ((leaf->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
5453 return MDB_INCOMPATIBLE; /* not a named DB */
5454 rc = mdb_node_read(&mc2, leaf, &data);
5457 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
5459 /* The txn may not know this DBI, or another process may
5460 * have dropped and recreated the DB with other flags.
5462 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
5463 return MDB_INCOMPATIBLE;
5464 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
5466 *mc->mc_dbflag &= ~DB_STALE;
5468 root = mc->mc_db->md_root;
5470 if (root == P_INVALID) { /* Tree is empty. */
5471 DPUTS("tree is empty");
5472 return MDB_NOTFOUND;
5476 mdb_cassert(mc, root > 1);
5477 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
5478 if ((rc = mdb_page_get(mc, root, &mc->mc_pg[0], NULL)) != 0)
5484 DPRINTF(("db %d root page %"Z"u has flags 0x%X",
5485 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
5487 if (flags & MDB_PS_MODIFY) {
5488 if ((rc = mdb_page_touch(mc)))
5492 if (flags & MDB_PS_ROOTONLY)
5495 return mdb_page_search_root(mc, key, flags);
5499 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
5501 MDB_txn *txn = mc->mc_txn;
5502 pgno_t pg = mp->mp_pgno;
5503 unsigned x = 0, ovpages = mp->mp_pages;
5504 MDB_env *env = txn->mt_env;
5505 MDB_IDL sl = txn->mt_spill_pgs;
5506 MDB_ID pn = pg << 1;
5509 DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
5510 /* If the page is dirty or on the spill list we just acquired it,
5511 * so we should give it back to our current free list, if any.
5512 * Otherwise put it onto the list of pages we freed in this txn.
5514 * Won't create me_pghead: me_pglast must be inited along with it.
5515 * Unsupported in nested txns: They would need to hide the page
5516 * range in ancestor txns' dirty and spilled lists.
5518 if (env->me_pghead &&
5520 ((mp->mp_flags & P_DIRTY) ||
5521 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
5525 MDB_ID2 *dl, ix, iy;
5526 rc = mdb_midl_need(&env->me_pghead, ovpages);
5529 if (!(mp->mp_flags & P_DIRTY)) {
5530 /* This page is no longer spilled */
5537 /* Remove from dirty list */
5538 dl = txn->mt_u.dirty_list;
5540 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
5546 mdb_cassert(mc, x > 1);
5548 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
5549 txn->mt_flags |= MDB_TXN_ERROR;
5550 return MDB_CORRUPTED;
5553 txn->mt_dirty_room++;
5554 if (!(env->me_flags & MDB_WRITEMAP))
5555 mdb_dpage_free(env, mp);
5557 /* Insert in me_pghead */
5558 mop = env->me_pghead;
5559 j = mop[0] + ovpages;
5560 for (i = mop[0]; i && mop[i] < pg; i--)
5566 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
5570 mc->mc_db->md_overflow_pages -= ovpages;
5574 /** Return the data associated with a given node.
5575 * @param[in] mc The cursor for this operation.
5576 * @param[in] leaf The node being read.
5577 * @param[out] data Updated to point to the node's data.
5578 * @return 0 on success, non-zero on failure.
5581 mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data)
5583 MDB_page *omp; /* overflow page */
5587 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5588 data->mv_size = NODEDSZ(leaf);
5589 data->mv_data = NODEDATA(leaf);
5593 /* Read overflow data.
5595 data->mv_size = NODEDSZ(leaf);
5596 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
5597 if ((rc = mdb_page_get(mc, pgno, &omp, NULL)) != 0) {
5598 DPRINTF(("read overflow page %"Z"u failed", pgno));
5601 data->mv_data = METADATA(omp);
5607 mdb_get(MDB_txn *txn, MDB_dbi dbi,
5608 MDB_val *key, MDB_val *data)
5615 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
5617 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
5620 if (txn->mt_flags & MDB_TXN_BLOCKED)
5623 mdb_cursor_init(&mc, txn, dbi, &mx);
5624 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
5627 /** Find a sibling for a page.
5628 * Replaces the page at the top of the cursor's stack with the
5629 * specified sibling, if one exists.
5630 * @param[in] mc The cursor for this operation.
5631 * @param[in] move_right Non-zero if the right sibling is requested,
5632 * otherwise the left sibling.
5633 * @return 0 on success, non-zero on failure.
5636 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
5642 if (mc->mc_snum < 2) {
5643 return MDB_NOTFOUND; /* root has no siblings */
5647 DPRINTF(("parent page is page %"Z"u, index %u",
5648 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
5650 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
5651 : (mc->mc_ki[mc->mc_top] == 0)) {
5652 DPRINTF(("no more keys left, moving to %s sibling",
5653 move_right ? "right" : "left"));
5654 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
5655 /* undo cursor_pop before returning */
5662 mc->mc_ki[mc->mc_top]++;
5664 mc->mc_ki[mc->mc_top]--;
5665 DPRINTF(("just moving to %s index key %u",
5666 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
5668 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
5670 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5671 if ((rc = mdb_page_get(mc, NODEPGNO(indx), &mp, NULL)) != 0) {
5672 /* mc will be inconsistent if caller does mc_snum++ as above */
5673 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
5677 mdb_cursor_push(mc, mp);
5679 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
5684 /** Move the cursor to the next data item. */
5686 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5692 if ((mc->mc_flags & C_EOF) ||
5693 ((mc->mc_flags & C_DEL) && op == MDB_NEXT_DUP)) {
5694 return MDB_NOTFOUND;
5696 if (!(mc->mc_flags & C_INITIALIZED))
5697 return mdb_cursor_first(mc, key, data);
5699 mp = mc->mc_pg[mc->mc_top];
5701 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5702 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5703 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5704 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
5705 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
5706 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
5707 if (rc == MDB_SUCCESS)
5708 MDB_GET_KEY(leaf, key);
5713 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5714 if (op == MDB_NEXT_DUP)
5715 return MDB_NOTFOUND;
5719 DPRINTF(("cursor_next: top page is %"Z"u in cursor %p",
5720 mdb_dbg_pgno(mp), (void *) mc));
5721 if (mc->mc_flags & C_DEL) {
5722 mc->mc_flags ^= C_DEL;
5726 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
5727 DPUTS("=====> move to next sibling page");
5728 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5729 mc->mc_flags |= C_EOF;
5732 mp = mc->mc_pg[mc->mc_top];
5733 DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5735 mc->mc_ki[mc->mc_top]++;
5738 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5739 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5742 key->mv_size = mc->mc_db->md_pad;
5743 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5747 mdb_cassert(mc, IS_LEAF(mp));
5748 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5750 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5751 mdb_xcursor_init1(mc, leaf);
5754 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
5757 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5758 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5759 if (rc != MDB_SUCCESS)
5764 MDB_GET_KEY(leaf, key);
5768 /** Move the cursor to the previous data item. */
5770 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5776 if (!(mc->mc_flags & C_INITIALIZED)) {
5777 rc = mdb_cursor_last(mc, key, data);
5780 mc->mc_ki[mc->mc_top]++;
5783 mp = mc->mc_pg[mc->mc_top];
5785 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5786 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5787 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5788 if (op == MDB_PREV || op == MDB_PREV_DUP) {
5789 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
5790 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
5791 if (rc == MDB_SUCCESS) {
5792 MDB_GET_KEY(leaf, key);
5793 mc->mc_flags &= ~C_EOF;
5799 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5800 if (op == MDB_PREV_DUP)
5801 return MDB_NOTFOUND;
5805 DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p",
5806 mdb_dbg_pgno(mp), (void *) mc));
5808 mc->mc_flags &= ~(C_EOF|C_DEL);
5810 if (mc->mc_ki[mc->mc_top] == 0) {
5811 DPUTS("=====> move to prev sibling page");
5812 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
5815 mp = mc->mc_pg[mc->mc_top];
5816 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
5817 DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5819 mc->mc_ki[mc->mc_top]--;
5821 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5822 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5825 key->mv_size = mc->mc_db->md_pad;
5826 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5830 mdb_cassert(mc, IS_LEAF(mp));
5831 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5833 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5834 mdb_xcursor_init1(mc, leaf);
5837 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
5840 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5841 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5842 if (rc != MDB_SUCCESS)
5847 MDB_GET_KEY(leaf, key);
5851 /** Set the cursor on a specific data item. */
5853 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5854 MDB_cursor_op op, int *exactp)
5858 MDB_node *leaf = NULL;
5861 if (key->mv_size == 0)
5862 return MDB_BAD_VALSIZE;
5865 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5867 /* See if we're already on the right page */
5868 if (mc->mc_flags & C_INITIALIZED) {
5871 mp = mc->mc_pg[mc->mc_top];
5873 mc->mc_ki[mc->mc_top] = 0;
5874 return MDB_NOTFOUND;
5876 if (mp->mp_flags & P_LEAF2) {
5877 nodekey.mv_size = mc->mc_db->md_pad;
5878 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
5880 leaf = NODEPTR(mp, 0);
5881 MDB_GET_KEY2(leaf, nodekey);
5883 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5885 /* Probably happens rarely, but first node on the page
5886 * was the one we wanted.
5888 mc->mc_ki[mc->mc_top] = 0;
5895 unsigned int nkeys = NUMKEYS(mp);
5897 if (mp->mp_flags & P_LEAF2) {
5898 nodekey.mv_data = LEAF2KEY(mp,
5899 nkeys-1, nodekey.mv_size);
5901 leaf = NODEPTR(mp, nkeys-1);
5902 MDB_GET_KEY2(leaf, nodekey);
5904 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5906 /* last node was the one we wanted */
5907 mc->mc_ki[mc->mc_top] = nkeys-1;
5913 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
5914 /* This is definitely the right page, skip search_page */
5915 if (mp->mp_flags & P_LEAF2) {
5916 nodekey.mv_data = LEAF2KEY(mp,
5917 mc->mc_ki[mc->mc_top], nodekey.mv_size);
5919 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5920 MDB_GET_KEY2(leaf, nodekey);
5922 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5924 /* current node was the one we wanted */
5931 mc->mc_flags &= ~C_EOF;
5935 /* If any parents have right-sibs, search.
5936 * Otherwise, there's nothing further.
5938 for (i=0; i<mc->mc_top; i++)
5940 NUMKEYS(mc->mc_pg[i])-1)
5942 if (i == mc->mc_top) {
5943 /* There are no other pages */
5944 mc->mc_ki[mc->mc_top] = nkeys;
5945 return MDB_NOTFOUND;
5949 /* There are no other pages */
5950 mc->mc_ki[mc->mc_top] = 0;
5951 if (op == MDB_SET_RANGE && !exactp) {
5955 return MDB_NOTFOUND;
5961 rc = mdb_page_search(mc, key, 0);
5962 if (rc != MDB_SUCCESS)
5965 mp = mc->mc_pg[mc->mc_top];
5966 mdb_cassert(mc, IS_LEAF(mp));
5969 leaf = mdb_node_search(mc, key, exactp);
5970 if (exactp != NULL && !*exactp) {
5971 /* MDB_SET specified and not an exact match. */
5972 return MDB_NOTFOUND;
5976 DPUTS("===> inexact leaf not found, goto sibling");
5977 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5978 mc->mc_flags |= C_EOF;
5979 return rc; /* no entries matched */
5981 mp = mc->mc_pg[mc->mc_top];
5982 mdb_cassert(mc, IS_LEAF(mp));
5983 leaf = NODEPTR(mp, 0);
5987 mc->mc_flags |= C_INITIALIZED;
5988 mc->mc_flags &= ~C_EOF;
5991 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
5992 key->mv_size = mc->mc_db->md_pad;
5993 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5998 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5999 mdb_xcursor_init1(mc, leaf);
6002 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6003 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
6004 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6007 if (op == MDB_GET_BOTH) {
6013 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
6014 if (rc != MDB_SUCCESS)
6017 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
6020 if ((rc = mdb_node_read(mc, leaf, &olddata)) != MDB_SUCCESS)
6022 dcmp = mc->mc_dbx->md_dcmp;
6023 #if UINT_MAX < SIZE_MAX
6024 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
6025 dcmp = mdb_cmp_clong;
6027 rc = dcmp(data, &olddata);
6029 if (op == MDB_GET_BOTH || rc > 0)
6030 return MDB_NOTFOUND;
6037 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6038 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6043 /* The key already matches in all other cases */
6044 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
6045 MDB_GET_KEY(leaf, key);
6046 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
6051 /** Move the cursor to the first item in the database. */
6053 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6059 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6061 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6062 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
6063 if (rc != MDB_SUCCESS)
6066 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6068 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
6069 mc->mc_flags |= C_INITIALIZED;
6070 mc->mc_flags &= ~C_EOF;
6072 mc->mc_ki[mc->mc_top] = 0;
6074 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6075 key->mv_size = mc->mc_db->md_pad;
6076 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
6081 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6082 mdb_xcursor_init1(mc, leaf);
6083 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6087 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6091 MDB_GET_KEY(leaf, key);
6095 /** Move the cursor to the last item in the database. */
6097 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6103 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6105 if (!(mc->mc_flags & C_EOF)) {
6107 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6108 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
6109 if (rc != MDB_SUCCESS)
6112 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6115 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
6116 mc->mc_flags |= C_INITIALIZED|C_EOF;
6117 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6119 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6120 key->mv_size = mc->mc_db->md_pad;
6121 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
6126 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6127 mdb_xcursor_init1(mc, leaf);
6128 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
6132 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6137 MDB_GET_KEY(leaf, key);
6142 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6147 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
6152 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
6156 case MDB_GET_CURRENT:
6157 if (!(mc->mc_flags & C_INITIALIZED)) {
6160 MDB_page *mp = mc->mc_pg[mc->mc_top];
6161 int nkeys = NUMKEYS(mp);
6162 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
6163 mc->mc_ki[mc->mc_top] = nkeys;
6169 key->mv_size = mc->mc_db->md_pad;
6170 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6172 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6173 MDB_GET_KEY(leaf, key);
6175 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6176 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
6178 rc = mdb_node_read(mc, leaf, data);
6185 case MDB_GET_BOTH_RANGE:
6190 if (mc->mc_xcursor == NULL) {
6191 rc = MDB_INCOMPATIBLE;
6201 rc = mdb_cursor_set(mc, key, data, op,
6202 op == MDB_SET_RANGE ? NULL : &exact);
6205 case MDB_GET_MULTIPLE:
6206 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
6210 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6211 rc = MDB_INCOMPATIBLE;
6215 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
6216 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
6219 case MDB_NEXT_MULTIPLE:
6224 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6225 rc = MDB_INCOMPATIBLE;
6228 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
6229 if (rc == MDB_SUCCESS) {
6230 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6233 mx = &mc->mc_xcursor->mx_cursor;
6234 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
6236 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
6237 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
6243 case MDB_PREV_MULTIPLE:
6248 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6249 rc = MDB_INCOMPATIBLE;
6252 if (!(mc->mc_flags & C_INITIALIZED))
6253 rc = mdb_cursor_last(mc, key, data);
6256 if (rc == MDB_SUCCESS) {
6257 MDB_cursor *mx = &mc->mc_xcursor->mx_cursor;
6258 if (mx->mc_flags & C_INITIALIZED) {
6259 rc = mdb_cursor_sibling(mx, 0);
6260 if (rc == MDB_SUCCESS)
6269 case MDB_NEXT_NODUP:
6270 rc = mdb_cursor_next(mc, key, data, op);
6274 case MDB_PREV_NODUP:
6275 rc = mdb_cursor_prev(mc, key, data, op);
6278 rc = mdb_cursor_first(mc, key, data);
6281 mfunc = mdb_cursor_first;
6283 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
6287 if (mc->mc_xcursor == NULL) {
6288 rc = MDB_INCOMPATIBLE;
6292 MDB_node *leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6293 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6294 MDB_GET_KEY(leaf, key);
6295 rc = mdb_node_read(mc, leaf, data);
6299 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
6303 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
6306 rc = mdb_cursor_last(mc, key, data);
6309 mfunc = mdb_cursor_last;
6312 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
6317 if (mc->mc_flags & C_DEL)
6318 mc->mc_flags ^= C_DEL;
6323 /** Touch all the pages in the cursor stack. Set mc_top.
6324 * Makes sure all the pages are writable, before attempting a write operation.
6325 * @param[in] mc The cursor to operate on.
6328 mdb_cursor_touch(MDB_cursor *mc)
6330 int rc = MDB_SUCCESS;
6332 if (mc->mc_dbi >= CORE_DBS && !(*mc->mc_dbflag & (DB_DIRTY|DB_DUPDATA))) {
6333 /* Touch DB record of named DB */
6336 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
6338 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
6339 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
6342 *mc->mc_dbflag |= DB_DIRTY;
6347 rc = mdb_page_touch(mc);
6348 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
6349 mc->mc_top = mc->mc_snum-1;
6354 /** Do not spill pages to disk if txn is getting full, may fail instead */
6355 #define MDB_NOSPILL 0x8000
6358 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6362 MDB_node *leaf = NULL;
6363 MDB_page *fp, *mp, *sub_root = NULL;
6365 MDB_val xdata, *rdata, dkey, olddata;
6367 int do_sub = 0, insert_key, insert_data;
6368 unsigned int mcount = 0, dcount = 0, nospill;
6371 unsigned int nflags;
6374 if (mc == NULL || key == NULL)
6377 env = mc->mc_txn->mt_env;
6379 /* Check this first so counter will always be zero on any
6382 if (flags & MDB_MULTIPLE) {
6383 dcount = data[1].mv_size;
6384 data[1].mv_size = 0;
6385 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
6386 return MDB_INCOMPATIBLE;
6389 nospill = flags & MDB_NOSPILL;
6390 flags &= ~MDB_NOSPILL;
6392 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
6393 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6395 if (key->mv_size-1 >= ENV_MAXKEY(env))
6396 return MDB_BAD_VALSIZE;
6398 #if SIZE_MAX > MAXDATASIZE
6399 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
6400 return MDB_BAD_VALSIZE;
6402 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
6403 return MDB_BAD_VALSIZE;
6406 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
6407 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
6411 if (flags == MDB_CURRENT) {
6412 if (!(mc->mc_flags & C_INITIALIZED))
6415 } else if (mc->mc_db->md_root == P_INVALID) {
6416 /* new database, cursor has nothing to point to */
6419 mc->mc_flags &= ~C_INITIALIZED;
6424 if (flags & MDB_APPEND) {
6426 rc = mdb_cursor_last(mc, &k2, &d2);
6428 rc = mc->mc_dbx->md_cmp(key, &k2);
6431 mc->mc_ki[mc->mc_top]++;
6433 /* new key is <= last key */
6438 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
6440 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
6441 DPRINTF(("duplicate key [%s]", DKEY(key)));
6443 return MDB_KEYEXIST;
6445 if (rc && rc != MDB_NOTFOUND)
6449 if (mc->mc_flags & C_DEL)
6450 mc->mc_flags ^= C_DEL;
6452 /* Cursor is positioned, check for room in the dirty list */
6454 if (flags & MDB_MULTIPLE) {
6456 xdata.mv_size = data->mv_size * dcount;
6460 if ((rc2 = mdb_page_spill(mc, key, rdata)))
6464 if (rc == MDB_NO_ROOT) {
6466 /* new database, write a root leaf page */
6467 DPUTS("allocating new root leaf page");
6468 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
6471 mdb_cursor_push(mc, np);
6472 mc->mc_db->md_root = np->mp_pgno;
6473 mc->mc_db->md_depth++;
6474 *mc->mc_dbflag |= DB_DIRTY;
6475 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
6477 np->mp_flags |= P_LEAF2;
6478 mc->mc_flags |= C_INITIALIZED;
6480 /* make sure all cursor pages are writable */
6481 rc2 = mdb_cursor_touch(mc);
6486 insert_key = insert_data = rc;
6488 /* The key does not exist */
6489 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
6490 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
6491 LEAFSIZE(key, data) > env->me_nodemax)
6493 /* Too big for a node, insert in sub-DB. Set up an empty
6494 * "old sub-page" for prep_subDB to expand to a full page.
6496 fp_flags = P_LEAF|P_DIRTY;
6498 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
6499 fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
6500 olddata.mv_size = PAGEHDRSZ;
6504 /* there's only a key anyway, so this is a no-op */
6505 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6507 unsigned int ksize = mc->mc_db->md_pad;
6508 if (key->mv_size != ksize)
6509 return MDB_BAD_VALSIZE;
6510 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
6511 memcpy(ptr, key->mv_data, ksize);
6513 /* if overwriting slot 0 of leaf, need to
6514 * update branch key if there is a parent page
6516 if (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
6517 unsigned short dtop = 1;
6519 /* slot 0 is always an empty key, find real slot */
6520 while (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
6524 if (mc->mc_ki[mc->mc_top])
6525 rc2 = mdb_update_key(mc, key);
6536 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6537 olddata.mv_size = NODEDSZ(leaf);
6538 olddata.mv_data = NODEDATA(leaf);
6541 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
6542 /* Prepare (sub-)page/sub-DB to accept the new item,
6543 * if needed. fp: old sub-page or a header faking
6544 * it. mp: new (sub-)page. offset: growth in page
6545 * size. xdata: node data with new page or DB.
6547 unsigned i, offset = 0;
6548 mp = fp = xdata.mv_data = env->me_pbuf;
6549 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
6551 /* Was a single item before, must convert now */
6552 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6554 /* Just overwrite the current item */
6555 if (flags == MDB_CURRENT)
6557 dcmp = mc->mc_dbx->md_dcmp;
6558 #if UINT_MAX < SIZE_MAX
6559 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
6560 dcmp = mdb_cmp_clong;
6562 /* does data match? */
6563 if (!dcmp(data, &olddata)) {
6564 if (flags & (MDB_NODUPDATA|MDB_APPENDDUP))
6565 return MDB_KEYEXIST;
6570 /* Back up original data item */
6571 dkey.mv_size = olddata.mv_size;
6572 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
6574 /* Make sub-page header for the dup items, with dummy body */
6575 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
6576 fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
6577 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
6578 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6579 fp->mp_flags |= P_LEAF2;
6580 fp->mp_pad = data->mv_size;
6581 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
6583 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
6584 (dkey.mv_size & 1) + (data->mv_size & 1);
6586 fp->mp_upper = xdata.mv_size - PAGEBASE;
6587 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
6588 } else if (leaf->mn_flags & F_SUBDATA) {
6589 /* Data is on sub-DB, just store it */
6590 flags |= F_DUPDATA|F_SUBDATA;
6593 /* Data is on sub-page */
6594 fp = olddata.mv_data;
6597 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6598 offset = EVEN(NODESIZE + sizeof(indx_t) +
6602 offset = fp->mp_pad;
6603 if (SIZELEFT(fp) < offset) {
6604 offset *= 4; /* space for 4 more */
6607 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
6609 fp->mp_flags |= P_DIRTY;
6610 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
6611 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
6615 xdata.mv_size = olddata.mv_size + offset;
6618 fp_flags = fp->mp_flags;
6619 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
6620 /* Too big for a sub-page, convert to sub-DB */
6621 fp_flags &= ~P_SUBP;
6623 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6624 fp_flags |= P_LEAF2;
6625 dummy.md_pad = fp->mp_pad;
6626 dummy.md_flags = MDB_DUPFIXED;
6627 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6628 dummy.md_flags |= MDB_INTEGERKEY;
6634 dummy.md_branch_pages = 0;
6635 dummy.md_leaf_pages = 1;
6636 dummy.md_overflow_pages = 0;
6637 dummy.md_entries = NUMKEYS(fp);
6638 xdata.mv_size = sizeof(MDB_db);
6639 xdata.mv_data = &dummy;
6640 if ((rc = mdb_page_alloc(mc, 1, &mp)))
6642 offset = env->me_psize - olddata.mv_size;
6643 flags |= F_DUPDATA|F_SUBDATA;
6644 dummy.md_root = mp->mp_pgno;
6648 mp->mp_flags = fp_flags | P_DIRTY;
6649 mp->mp_pad = fp->mp_pad;
6650 mp->mp_lower = fp->mp_lower;
6651 mp->mp_upper = fp->mp_upper + offset;
6652 if (fp_flags & P_LEAF2) {
6653 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
6655 memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
6656 olddata.mv_size - fp->mp_upper - PAGEBASE);
6657 for (i=0; i<NUMKEYS(fp); i++)
6658 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
6666 mdb_node_del(mc, 0);
6670 /* LMDB passes F_SUBDATA in 'flags' to write a DB record */
6671 if ((leaf->mn_flags ^ flags) & F_SUBDATA)
6672 return MDB_INCOMPATIBLE;
6673 /* overflow page overwrites need special handling */
6674 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6677 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
6679 memcpy(&pg, olddata.mv_data, sizeof(pg));
6680 if ((rc2 = mdb_page_get(mc, pg, &omp, &level)) != 0)
6682 ovpages = omp->mp_pages;
6684 /* Is the ov page large enough? */
6685 if (ovpages >= dpages) {
6686 if (!(omp->mp_flags & P_DIRTY) &&
6687 (level || (env->me_flags & MDB_WRITEMAP)))
6689 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
6692 level = 0; /* dirty in this txn or clean */
6695 if (omp->mp_flags & P_DIRTY) {
6696 /* yes, overwrite it. Note in this case we don't
6697 * bother to try shrinking the page if the new data
6698 * is smaller than the overflow threshold.
6701 /* It is writable only in a parent txn */
6702 size_t sz = (size_t) env->me_psize * ovpages, off;
6703 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
6709 /* Note - this page is already counted in parent's dirty_room */
6710 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
6711 mdb_cassert(mc, rc2 == 0);
6712 /* Currently we make the page look as with put() in the
6713 * parent txn, in case the user peeks at MDB_RESERVEd
6714 * or unused parts. Some users treat ovpages specially.
6716 if (!(flags & MDB_RESERVE)) {
6717 /* Skip the part where LMDB will put *data.
6718 * Copy end of page, adjusting alignment so
6719 * compiler may copy words instead of bytes.
6721 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
6722 memcpy((size_t *)((char *)np + off),
6723 (size_t *)((char *)omp + off), sz - off);
6726 memcpy(np, omp, sz); /* Copy beginning of page */
6729 SETDSZ(leaf, data->mv_size);
6730 if (F_ISSET(flags, MDB_RESERVE))
6731 data->mv_data = METADATA(omp);
6733 memcpy(METADATA(omp), data->mv_data, data->mv_size);
6737 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
6739 } else if (data->mv_size == olddata.mv_size) {
6740 /* same size, just replace it. Note that we could
6741 * also reuse this node if the new data is smaller,
6742 * but instead we opt to shrink the node in that case.
6744 if (F_ISSET(flags, MDB_RESERVE))
6745 data->mv_data = olddata.mv_data;
6746 else if (!(mc->mc_flags & C_SUB))
6747 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
6749 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
6754 mdb_node_del(mc, 0);
6760 nflags = flags & NODE_ADD_FLAGS;
6761 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
6762 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
6763 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
6764 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
6766 nflags |= MDB_SPLIT_REPLACE;
6767 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
6769 /* There is room already in this leaf page. */
6770 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
6772 /* Adjust other cursors pointing to mp */
6773 MDB_cursor *m2, *m3;
6774 MDB_dbi dbi = mc->mc_dbi;
6775 unsigned i = mc->mc_top;
6776 MDB_page *mp = mc->mc_pg[i];
6778 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6779 if (mc->mc_flags & C_SUB)
6780 m3 = &m2->mc_xcursor->mx_cursor;
6783 if (m3 == mc || m3->mc_snum < mc->mc_snum || m3->mc_pg[i] != mp) continue;
6784 if (m3->mc_ki[i] >= mc->mc_ki[i] && insert_key) {
6787 if (XCURSOR_INITED(m3))
6788 XCURSOR_REFRESH(m3, mp, m3->mc_ki[i]);
6793 if (rc == MDB_SUCCESS) {
6794 /* Now store the actual data in the child DB. Note that we're
6795 * storing the user data in the keys field, so there are strict
6796 * size limits on dupdata. The actual data fields of the child
6797 * DB are all zero size.
6800 int xflags, new_dupdata;
6805 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6806 if (flags & MDB_CURRENT) {
6807 xflags = MDB_CURRENT|MDB_NOSPILL;
6809 mdb_xcursor_init1(mc, leaf);
6810 xflags = (flags & MDB_NODUPDATA) ?
6811 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
6814 mc->mc_xcursor->mx_cursor.mc_pg[0] = sub_root;
6815 new_dupdata = (int)dkey.mv_size;
6816 /* converted, write the original data first */
6818 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
6821 /* we've done our job */
6824 if (!(leaf->mn_flags & F_SUBDATA) || sub_root) {
6825 /* Adjust other cursors pointing to mp */
6827 MDB_xcursor *mx = mc->mc_xcursor;
6828 unsigned i = mc->mc_top;
6829 MDB_page *mp = mc->mc_pg[i];
6830 int nkeys = NUMKEYS(mp);
6832 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6833 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6834 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6835 if (m2->mc_pg[i] == mp) {
6836 if (m2->mc_ki[i] == mc->mc_ki[i]) {
6837 mdb_xcursor_init2(m2, mx, new_dupdata);
6838 } else if (!insert_key && m2->mc_ki[i] < nkeys) {
6839 XCURSOR_REFRESH(m2, mp, m2->mc_ki[i]);
6844 ecount = mc->mc_xcursor->mx_db.md_entries;
6845 if (flags & MDB_APPENDDUP)
6846 xflags |= MDB_APPEND;
6847 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
6848 if (flags & F_SUBDATA) {
6849 void *db = NODEDATA(leaf);
6850 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6852 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
6854 /* Increment count unless we just replaced an existing item. */
6856 mc->mc_db->md_entries++;
6858 /* Invalidate txn if we created an empty sub-DB */
6861 /* If we succeeded and the key didn't exist before,
6862 * make sure the cursor is marked valid.
6864 mc->mc_flags |= C_INITIALIZED;
6866 if (flags & MDB_MULTIPLE) {
6869 /* let caller know how many succeeded, if any */
6870 data[1].mv_size = mcount;
6871 if (mcount < dcount) {
6872 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
6873 insert_key = insert_data = 0;
6880 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
6883 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6888 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
6894 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
6895 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6897 if (!(mc->mc_flags & C_INITIALIZED))
6900 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6901 return MDB_NOTFOUND;
6903 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
6906 rc = mdb_cursor_touch(mc);
6910 mp = mc->mc_pg[mc->mc_top];
6913 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6915 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6916 if (flags & MDB_NODUPDATA) {
6917 /* mdb_cursor_del0() will subtract the final entry */
6918 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
6919 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
6921 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
6922 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6924 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
6927 /* If sub-DB still has entries, we're done */
6928 if (mc->mc_xcursor->mx_db.md_entries) {
6929 if (leaf->mn_flags & F_SUBDATA) {
6930 /* update subDB info */
6931 void *db = NODEDATA(leaf);
6932 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6935 /* shrink fake page */
6936 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
6937 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6938 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6939 /* fix other sub-DB cursors pointed at fake pages on this page */
6940 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6941 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6942 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6943 if (m2->mc_pg[mc->mc_top] == mp) {
6944 MDB_node *n2 = leaf;
6945 if (m2->mc_ki[mc->mc_top] != mc->mc_ki[mc->mc_top]) {
6946 n2 = NODEPTR(mp, m2->mc_ki[mc->mc_top]);
6947 if (n2->mn_flags & F_SUBDATA) continue;
6949 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
6953 mc->mc_db->md_entries--;
6956 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
6958 /* otherwise fall thru and delete the sub-DB */
6961 if (leaf->mn_flags & F_SUBDATA) {
6962 /* add all the child DB's pages to the free list */
6963 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6968 /* LMDB passes F_SUBDATA in 'flags' to delete a DB record */
6969 else if ((leaf->mn_flags ^ flags) & F_SUBDATA) {
6970 rc = MDB_INCOMPATIBLE;
6974 /* add overflow pages to free list */
6975 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6979 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
6980 if ((rc = mdb_page_get(mc, pg, &omp, NULL)) ||
6981 (rc = mdb_ovpage_free(mc, omp)))
6986 return mdb_cursor_del0(mc);
6989 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6993 /** Allocate and initialize new pages for a database.
6994 * @param[in] mc a cursor on the database being added to.
6995 * @param[in] flags flags defining what type of page is being allocated.
6996 * @param[in] num the number of pages to allocate. This is usually 1,
6997 * unless allocating overflow pages for a large record.
6998 * @param[out] mp Address of a page, or NULL on failure.
6999 * @return 0 on success, non-zero on failure.
7002 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
7007 if ((rc = mdb_page_alloc(mc, num, &np)))
7009 DPRINTF(("allocated new mpage %"Z"u, page size %u",
7010 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
7011 np->mp_flags = flags | P_DIRTY;
7012 np->mp_lower = (PAGEHDRSZ-PAGEBASE);
7013 np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
7016 mc->mc_db->md_branch_pages++;
7017 else if (IS_LEAF(np))
7018 mc->mc_db->md_leaf_pages++;
7019 else if (IS_OVERFLOW(np)) {
7020 mc->mc_db->md_overflow_pages += num;
7028 /** Calculate the size of a leaf node.
7029 * The size depends on the environment's page size; if a data item
7030 * is too large it will be put onto an overflow page and the node
7031 * size will only include the key and not the data. Sizes are always
7032 * rounded up to an even number of bytes, to guarantee 2-byte alignment
7033 * of the #MDB_node headers.
7034 * @param[in] env The environment handle.
7035 * @param[in] key The key for the node.
7036 * @param[in] data The data for the node.
7037 * @return The number of bytes needed to store the node.
7040 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
7044 sz = LEAFSIZE(key, data);
7045 if (sz > env->me_nodemax) {
7046 /* put on overflow page */
7047 sz -= data->mv_size - sizeof(pgno_t);
7050 return EVEN(sz + sizeof(indx_t));
7053 /** Calculate the size of a branch node.
7054 * The size should depend on the environment's page size but since
7055 * we currently don't support spilling large keys onto overflow
7056 * pages, it's simply the size of the #MDB_node header plus the
7057 * size of the key. Sizes are always rounded up to an even number
7058 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
7059 * @param[in] env The environment handle.
7060 * @param[in] key The key for the node.
7061 * @return The number of bytes needed to store the node.
7064 mdb_branch_size(MDB_env *env, MDB_val *key)
7069 if (sz > env->me_nodemax) {
7070 /* put on overflow page */
7071 /* not implemented */
7072 /* sz -= key->size - sizeof(pgno_t); */
7075 return sz + sizeof(indx_t);
7078 /** Add a node to the page pointed to by the cursor.
7079 * @param[in] mc The cursor for this operation.
7080 * @param[in] indx The index on the page where the new node should be added.
7081 * @param[in] key The key for the new node.
7082 * @param[in] data The data for the new node, if any.
7083 * @param[in] pgno The page number, if adding a branch node.
7084 * @param[in] flags Flags for the node.
7085 * @return 0 on success, non-zero on failure. Possible errors are:
7087 * <li>ENOMEM - failed to allocate overflow pages for the node.
7088 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
7089 * should never happen since all callers already calculate the
7090 * page's free space before calling this function.
7094 mdb_node_add(MDB_cursor *mc, indx_t indx,
7095 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
7098 size_t node_size = NODESIZE;
7102 MDB_page *mp = mc->mc_pg[mc->mc_top];
7103 MDB_page *ofp = NULL; /* overflow page */
7107 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
7109 DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
7110 IS_LEAF(mp) ? "leaf" : "branch",
7111 IS_SUBP(mp) ? "sub-" : "",
7112 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
7113 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
7116 /* Move higher keys up one slot. */
7117 int ksize = mc->mc_db->md_pad, dif;
7118 char *ptr = LEAF2KEY(mp, indx, ksize);
7119 dif = NUMKEYS(mp) - indx;
7121 memmove(ptr+ksize, ptr, dif*ksize);
7122 /* insert new key */
7123 memcpy(ptr, key->mv_data, ksize);
7125 /* Just using these for counting */
7126 mp->mp_lower += sizeof(indx_t);
7127 mp->mp_upper -= ksize - sizeof(indx_t);
7131 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
7133 node_size += key->mv_size;
7135 mdb_cassert(mc, key && data);
7136 if (F_ISSET(flags, F_BIGDATA)) {
7137 /* Data already on overflow page. */
7138 node_size += sizeof(pgno_t);
7139 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
7140 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
7142 /* Put data on overflow page. */
7143 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
7144 data->mv_size, node_size+data->mv_size));
7145 node_size = EVEN(node_size + sizeof(pgno_t));
7146 if ((ssize_t)node_size > room)
7148 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
7150 DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
7154 node_size += data->mv_size;
7157 node_size = EVEN(node_size);
7158 if ((ssize_t)node_size > room)
7162 /* Move higher pointers up one slot. */
7163 for (i = NUMKEYS(mp); i > indx; i--)
7164 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
7166 /* Adjust free space offsets. */
7167 ofs = mp->mp_upper - node_size;
7168 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
7169 mp->mp_ptrs[indx] = ofs;
7171 mp->mp_lower += sizeof(indx_t);
7173 /* Write the node data. */
7174 node = NODEPTR(mp, indx);
7175 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
7176 node->mn_flags = flags;
7178 SETDSZ(node,data->mv_size);
7183 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7186 ndata = NODEDATA(node);
7188 if (F_ISSET(flags, F_BIGDATA))
7189 memcpy(ndata, data->mv_data, sizeof(pgno_t));
7190 else if (F_ISSET(flags, MDB_RESERVE))
7191 data->mv_data = ndata;
7193 memcpy(ndata, data->mv_data, data->mv_size);
7195 memcpy(ndata, &ofp->mp_pgno, sizeof(pgno_t));
7196 ndata = METADATA(ofp);
7197 if (F_ISSET(flags, MDB_RESERVE))
7198 data->mv_data = ndata;
7200 memcpy(ndata, data->mv_data, data->mv_size);
7207 DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
7208 mdb_dbg_pgno(mp), NUMKEYS(mp)));
7209 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
7210 DPRINTF(("node size = %"Z"u", node_size));
7211 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7212 return MDB_PAGE_FULL;
7215 /** Delete the specified node from a page.
7216 * @param[in] mc Cursor pointing to the node to delete.
7217 * @param[in] ksize The size of a node. Only used if the page is
7218 * part of a #MDB_DUPFIXED database.
7221 mdb_node_del(MDB_cursor *mc, int ksize)
7223 MDB_page *mp = mc->mc_pg[mc->mc_top];
7224 indx_t indx = mc->mc_ki[mc->mc_top];
7226 indx_t i, j, numkeys, ptr;
7230 DPRINTF(("delete node %u on %s page %"Z"u", indx,
7231 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
7232 numkeys = NUMKEYS(mp);
7233 mdb_cassert(mc, indx < numkeys);
7236 int x = numkeys - 1 - indx;
7237 base = LEAF2KEY(mp, indx, ksize);
7239 memmove(base, base + ksize, x * ksize);
7240 mp->mp_lower -= sizeof(indx_t);
7241 mp->mp_upper += ksize - sizeof(indx_t);
7245 node = NODEPTR(mp, indx);
7246 sz = NODESIZE + node->mn_ksize;
7248 if (F_ISSET(node->mn_flags, F_BIGDATA))
7249 sz += sizeof(pgno_t);
7251 sz += NODEDSZ(node);
7255 ptr = mp->mp_ptrs[indx];
7256 for (i = j = 0; i < numkeys; i++) {
7258 mp->mp_ptrs[j] = mp->mp_ptrs[i];
7259 if (mp->mp_ptrs[i] < ptr)
7260 mp->mp_ptrs[j] += sz;
7265 base = (char *)mp + mp->mp_upper + PAGEBASE;
7266 memmove(base + sz, base, ptr - mp->mp_upper);
7268 mp->mp_lower -= sizeof(indx_t);
7272 /** Compact the main page after deleting a node on a subpage.
7273 * @param[in] mp The main page to operate on.
7274 * @param[in] indx The index of the subpage on the main page.
7277 mdb_node_shrink(MDB_page *mp, indx_t indx)
7282 indx_t delta, nsize, len, ptr;
7285 node = NODEPTR(mp, indx);
7286 sp = (MDB_page *)NODEDATA(node);
7287 delta = SIZELEFT(sp);
7288 nsize = NODEDSZ(node) - delta;
7290 /* Prepare to shift upward, set len = length(subpage part to shift) */
7294 return; /* do not make the node uneven-sized */
7296 xp = (MDB_page *)((char *)sp + delta); /* destination subpage */
7297 for (i = NUMKEYS(sp); --i >= 0; )
7298 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
7301 sp->mp_upper = sp->mp_lower;
7302 COPY_PGNO(sp->mp_pgno, mp->mp_pgno);
7303 SETDSZ(node, nsize);
7305 /* Shift <lower nodes...initial part of subpage> upward */
7306 base = (char *)mp + mp->mp_upper + PAGEBASE;
7307 memmove(base + delta, base, (char *)sp + len - base);
7309 ptr = mp->mp_ptrs[indx];
7310 for (i = NUMKEYS(mp); --i >= 0; ) {
7311 if (mp->mp_ptrs[i] <= ptr)
7312 mp->mp_ptrs[i] += delta;
7314 mp->mp_upper += delta;
7317 /** Initial setup of a sorted-dups cursor.
7318 * Sorted duplicates are implemented as a sub-database for the given key.
7319 * The duplicate data items are actually keys of the sub-database.
7320 * Operations on the duplicate data items are performed using a sub-cursor
7321 * initialized when the sub-database is first accessed. This function does
7322 * the preliminary setup of the sub-cursor, filling in the fields that
7323 * depend only on the parent DB.
7324 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
7327 mdb_xcursor_init0(MDB_cursor *mc)
7329 MDB_xcursor *mx = mc->mc_xcursor;
7331 mx->mx_cursor.mc_xcursor = NULL;
7332 mx->mx_cursor.mc_txn = mc->mc_txn;
7333 mx->mx_cursor.mc_db = &mx->mx_db;
7334 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
7335 mx->mx_cursor.mc_dbi = mc->mc_dbi;
7336 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
7337 mx->mx_cursor.mc_snum = 0;
7338 mx->mx_cursor.mc_top = 0;
7339 mx->mx_cursor.mc_flags = C_SUB;
7340 mx->mx_dbx.md_name.mv_size = 0;
7341 mx->mx_dbx.md_name.mv_data = NULL;
7342 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
7343 mx->mx_dbx.md_dcmp = NULL;
7344 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
7347 /** Final setup of a sorted-dups cursor.
7348 * Sets up the fields that depend on the data from the main cursor.
7349 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
7350 * @param[in] node The data containing the #MDB_db record for the
7351 * sorted-dup database.
7354 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
7356 MDB_xcursor *mx = mc->mc_xcursor;
7358 if (node->mn_flags & F_SUBDATA) {
7359 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
7360 mx->mx_cursor.mc_pg[0] = 0;
7361 mx->mx_cursor.mc_snum = 0;
7362 mx->mx_cursor.mc_top = 0;
7363 mx->mx_cursor.mc_flags = C_SUB;
7365 MDB_page *fp = NODEDATA(node);
7366 mx->mx_db.md_pad = 0;
7367 mx->mx_db.md_flags = 0;
7368 mx->mx_db.md_depth = 1;
7369 mx->mx_db.md_branch_pages = 0;
7370 mx->mx_db.md_leaf_pages = 1;
7371 mx->mx_db.md_overflow_pages = 0;
7372 mx->mx_db.md_entries = NUMKEYS(fp);
7373 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
7374 mx->mx_cursor.mc_snum = 1;
7375 mx->mx_cursor.mc_top = 0;
7376 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
7377 mx->mx_cursor.mc_pg[0] = fp;
7378 mx->mx_cursor.mc_ki[0] = 0;
7379 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7380 mx->mx_db.md_flags = MDB_DUPFIXED;
7381 mx->mx_db.md_pad = fp->mp_pad;
7382 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
7383 mx->mx_db.md_flags |= MDB_INTEGERKEY;
7386 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
7387 mx->mx_db.md_root));
7388 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DUPDATA;
7389 #if UINT_MAX < SIZE_MAX
7390 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
7391 mx->mx_dbx.md_cmp = mdb_cmp_clong;
7396 /** Fixup a sorted-dups cursor due to underlying update.
7397 * Sets up some fields that depend on the data from the main cursor.
7398 * Almost the same as init1, but skips initialization steps if the
7399 * xcursor had already been used.
7400 * @param[in] mc The main cursor whose sorted-dups cursor is to be fixed up.
7401 * @param[in] src_mx The xcursor of an up-to-date cursor.
7402 * @param[in] new_dupdata True if converting from a non-#F_DUPDATA item.
7405 mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int new_dupdata)
7407 MDB_xcursor *mx = mc->mc_xcursor;
7410 mx->mx_cursor.mc_snum = 1;
7411 mx->mx_cursor.mc_top = 0;
7412 mx->mx_cursor.mc_flags |= C_INITIALIZED;
7413 mx->mx_cursor.mc_ki[0] = 0;
7414 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DUPDATA;
7415 #if UINT_MAX < SIZE_MAX
7416 mx->mx_dbx.md_cmp = src_mx->mx_dbx.md_cmp;
7418 } else if (!(mx->mx_cursor.mc_flags & C_INITIALIZED)) {
7421 mx->mx_db = src_mx->mx_db;
7422 mx->mx_cursor.mc_pg[0] = src_mx->mx_cursor.mc_pg[0];
7423 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
7424 mx->mx_db.md_root));
7427 /** Initialize a cursor for a given transaction and database. */
7429 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
7432 mc->mc_backup = NULL;
7435 mc->mc_db = &txn->mt_dbs[dbi];
7436 mc->mc_dbx = &txn->mt_dbxs[dbi];
7437 mc->mc_dbflag = &txn->mt_dbflags[dbi];
7443 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
7444 mdb_tassert(txn, mx != NULL);
7445 mc->mc_xcursor = mx;
7446 mdb_xcursor_init0(mc);
7448 mc->mc_xcursor = NULL;
7450 if (*mc->mc_dbflag & DB_STALE) {
7451 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
7456 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
7459 size_t size = sizeof(MDB_cursor);
7461 if (!ret || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
7464 if (txn->mt_flags & MDB_TXN_BLOCKED)
7467 if (dbi == FREE_DBI && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
7470 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
7471 size += sizeof(MDB_xcursor);
7473 if ((mc = malloc(size)) != NULL) {
7474 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
7475 if (txn->mt_cursors) {
7476 mc->mc_next = txn->mt_cursors[dbi];
7477 txn->mt_cursors[dbi] = mc;
7478 mc->mc_flags |= C_UNTRACK;
7490 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
7492 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi, DB_VALID))
7495 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
7498 if (txn->mt_flags & MDB_TXN_BLOCKED)
7501 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
7505 /* Return the count of duplicate data items for the current key */
7507 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
7511 if (mc == NULL || countp == NULL)
7514 if (mc->mc_xcursor == NULL)
7515 return MDB_INCOMPATIBLE;
7517 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
7520 if (!(mc->mc_flags & C_INITIALIZED))
7523 if (!mc->mc_snum || (mc->mc_flags & C_EOF))
7524 return MDB_NOTFOUND;
7526 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7527 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7530 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
7533 *countp = mc->mc_xcursor->mx_db.md_entries;
7539 mdb_cursor_close(MDB_cursor *mc)
7541 if (mc && !mc->mc_backup) {
7542 /* remove from txn, if tracked */
7543 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
7544 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
7545 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
7547 *prev = mc->mc_next;
7554 mdb_cursor_txn(MDB_cursor *mc)
7556 if (!mc) return NULL;
7561 mdb_cursor_dbi(MDB_cursor *mc)
7566 /** Replace the key for a branch node with a new key.
7567 * @param[in] mc Cursor pointing to the node to operate on.
7568 * @param[in] key The new key to use.
7569 * @return 0 on success, non-zero on failure.
7572 mdb_update_key(MDB_cursor *mc, MDB_val *key)
7578 int delta, ksize, oksize;
7579 indx_t ptr, i, numkeys, indx;
7582 indx = mc->mc_ki[mc->mc_top];
7583 mp = mc->mc_pg[mc->mc_top];
7584 node = NODEPTR(mp, indx);
7585 ptr = mp->mp_ptrs[indx];
7589 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
7590 k2.mv_data = NODEKEY(node);
7591 k2.mv_size = node->mn_ksize;
7592 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
7594 mdb_dkey(&k2, kbuf2),
7600 /* Sizes must be 2-byte aligned. */
7601 ksize = EVEN(key->mv_size);
7602 oksize = EVEN(node->mn_ksize);
7603 delta = ksize - oksize;
7605 /* Shift node contents if EVEN(key length) changed. */
7607 if (delta > 0 && SIZELEFT(mp) < delta) {
7609 /* not enough space left, do a delete and split */
7610 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
7611 pgno = NODEPGNO(node);
7612 mdb_node_del(mc, 0);
7613 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
7616 numkeys = NUMKEYS(mp);
7617 for (i = 0; i < numkeys; i++) {
7618 if (mp->mp_ptrs[i] <= ptr)
7619 mp->mp_ptrs[i] -= delta;
7622 base = (char *)mp + mp->mp_upper + PAGEBASE;
7623 len = ptr - mp->mp_upper + NODESIZE;
7624 memmove(base - delta, base, len);
7625 mp->mp_upper -= delta;
7627 node = NODEPTR(mp, indx);
7630 /* But even if no shift was needed, update ksize */
7631 if (node->mn_ksize != key->mv_size)
7632 node->mn_ksize = key->mv_size;
7635 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7641 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
7643 /** Perform \b act while tracking temporary cursor \b mn */
7644 #define WITH_CURSOR_TRACKING(mn, act) do { \
7645 MDB_cursor dummy, *tracked, **tp = &(mn).mc_txn->mt_cursors[mn.mc_dbi]; \
7646 if ((mn).mc_flags & C_SUB) { \
7647 dummy.mc_flags = C_INITIALIZED; \
7648 dummy.mc_xcursor = (MDB_xcursor *)&(mn); \
7653 tracked->mc_next = *tp; \
7656 *tp = tracked->mc_next; \
7659 /** Move a node from csrc to cdst.
7662 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft)
7669 unsigned short flags;
7673 /* Mark src and dst as dirty. */
7674 if ((rc = mdb_page_touch(csrc)) ||
7675 (rc = mdb_page_touch(cdst)))
7678 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7679 key.mv_size = csrc->mc_db->md_pad;
7680 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
7682 data.mv_data = NULL;
7686 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
7687 mdb_cassert(csrc, !((size_t)srcnode & 1));
7688 srcpg = NODEPGNO(srcnode);
7689 flags = srcnode->mn_flags;
7690 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7691 unsigned int snum = csrc->mc_snum;
7693 /* must find the lowest key below src */
7694 rc = mdb_page_search_lowest(csrc);
7697 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7698 key.mv_size = csrc->mc_db->md_pad;
7699 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7701 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7702 key.mv_size = NODEKSZ(s2);
7703 key.mv_data = NODEKEY(s2);
7705 csrc->mc_snum = snum--;
7706 csrc->mc_top = snum;
7708 key.mv_size = NODEKSZ(srcnode);
7709 key.mv_data = NODEKEY(srcnode);
7711 data.mv_size = NODEDSZ(srcnode);
7712 data.mv_data = NODEDATA(srcnode);
7714 mn.mc_xcursor = NULL;
7715 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
7716 unsigned int snum = cdst->mc_snum;
7719 /* must find the lowest key below dst */
7720 mdb_cursor_copy(cdst, &mn);
7721 rc = mdb_page_search_lowest(&mn);
7724 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7725 bkey.mv_size = mn.mc_db->md_pad;
7726 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
7728 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7729 bkey.mv_size = NODEKSZ(s2);
7730 bkey.mv_data = NODEKEY(s2);
7732 mn.mc_snum = snum--;
7735 rc = mdb_update_key(&mn, &bkey);
7740 DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
7741 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
7742 csrc->mc_ki[csrc->mc_top],
7744 csrc->mc_pg[csrc->mc_top]->mp_pgno,
7745 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
7747 /* Add the node to the destination page.
7749 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
7750 if (rc != MDB_SUCCESS)
7753 /* Delete the node from the source page.
7755 mdb_node_del(csrc, key.mv_size);
7758 /* Adjust other cursors pointing to mp */
7759 MDB_cursor *m2, *m3;
7760 MDB_dbi dbi = csrc->mc_dbi;
7761 MDB_page *mpd, *mps;
7763 mps = csrc->mc_pg[csrc->mc_top];
7764 /* If we're adding on the left, bump others up */
7766 mpd = cdst->mc_pg[csrc->mc_top];
7767 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7768 if (csrc->mc_flags & C_SUB)
7769 m3 = &m2->mc_xcursor->mx_cursor;
7772 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
7775 m3->mc_pg[csrc->mc_top] == mpd &&
7776 m3->mc_ki[csrc->mc_top] >= cdst->mc_ki[csrc->mc_top]) {
7777 m3->mc_ki[csrc->mc_top]++;
7780 m3->mc_pg[csrc->mc_top] == mps &&
7781 m3->mc_ki[csrc->mc_top] == csrc->mc_ki[csrc->mc_top]) {
7782 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
7783 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7784 m3->mc_ki[csrc->mc_top-1]++;
7786 if (XCURSOR_INITED(m3) && IS_LEAF(mps))
7787 XCURSOR_REFRESH(m3, m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
7790 /* Adding on the right, bump others down */
7792 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7793 if (csrc->mc_flags & C_SUB)
7794 m3 = &m2->mc_xcursor->mx_cursor;
7797 if (m3 == csrc) continue;
7798 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
7800 if (m3->mc_pg[csrc->mc_top] == mps) {
7801 if (!m3->mc_ki[csrc->mc_top]) {
7802 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
7803 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7804 m3->mc_ki[csrc->mc_top-1]--;
7806 m3->mc_ki[csrc->mc_top]--;
7808 if (XCURSOR_INITED(m3) && IS_LEAF(mps))
7809 XCURSOR_REFRESH(m3, m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
7815 /* Update the parent separators.
7817 if (csrc->mc_ki[csrc->mc_top] == 0) {
7818 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
7819 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7820 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7822 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7823 key.mv_size = NODEKSZ(srcnode);
7824 key.mv_data = NODEKEY(srcnode);
7826 DPRINTF(("update separator for source page %"Z"u to [%s]",
7827 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
7828 mdb_cursor_copy(csrc, &mn);
7831 /* We want mdb_rebalance to find mn when doing fixups */
7832 WITH_CURSOR_TRACKING(mn,
7833 rc = mdb_update_key(&mn, &key));
7837 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7839 indx_t ix = csrc->mc_ki[csrc->mc_top];
7840 nullkey.mv_size = 0;
7841 csrc->mc_ki[csrc->mc_top] = 0;
7842 rc = mdb_update_key(csrc, &nullkey);
7843 csrc->mc_ki[csrc->mc_top] = ix;
7844 mdb_cassert(csrc, rc == MDB_SUCCESS);
7848 if (cdst->mc_ki[cdst->mc_top] == 0) {
7849 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
7850 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7851 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
7853 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
7854 key.mv_size = NODEKSZ(srcnode);
7855 key.mv_data = NODEKEY(srcnode);
7857 DPRINTF(("update separator for destination page %"Z"u to [%s]",
7858 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
7859 mdb_cursor_copy(cdst, &mn);
7862 /* We want mdb_rebalance to find mn when doing fixups */
7863 WITH_CURSOR_TRACKING(mn,
7864 rc = mdb_update_key(&mn, &key));
7868 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
7870 indx_t ix = cdst->mc_ki[cdst->mc_top];
7871 nullkey.mv_size = 0;
7872 cdst->mc_ki[cdst->mc_top] = 0;
7873 rc = mdb_update_key(cdst, &nullkey);
7874 cdst->mc_ki[cdst->mc_top] = ix;
7875 mdb_cassert(cdst, rc == MDB_SUCCESS);
7882 /** Merge one page into another.
7883 * The nodes from the page pointed to by \b csrc will
7884 * be copied to the page pointed to by \b cdst and then
7885 * the \b csrc page will be freed.
7886 * @param[in] csrc Cursor pointing to the source page.
7887 * @param[in] cdst Cursor pointing to the destination page.
7888 * @return 0 on success, non-zero on failure.
7891 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
7893 MDB_page *psrc, *pdst;
7900 psrc = csrc->mc_pg[csrc->mc_top];
7901 pdst = cdst->mc_pg[cdst->mc_top];
7903 DPRINTF(("merging page %"Z"u into %"Z"u", psrc->mp_pgno, pdst->mp_pgno));
7905 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
7906 mdb_cassert(csrc, cdst->mc_snum > 1);
7908 /* Mark dst as dirty. */
7909 if ((rc = mdb_page_touch(cdst)))
7912 /* get dst page again now that we've touched it. */
7913 pdst = cdst->mc_pg[cdst->mc_top];
7915 /* Move all nodes from src to dst.
7917 j = nkeys = NUMKEYS(pdst);
7918 if (IS_LEAF2(psrc)) {
7919 key.mv_size = csrc->mc_db->md_pad;
7920 key.mv_data = METADATA(psrc);
7921 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7922 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
7923 if (rc != MDB_SUCCESS)
7925 key.mv_data = (char *)key.mv_data + key.mv_size;
7928 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7929 srcnode = NODEPTR(psrc, i);
7930 if (i == 0 && IS_BRANCH(psrc)) {
7933 mdb_cursor_copy(csrc, &mn);
7934 mn.mc_xcursor = NULL;
7935 /* must find the lowest key below src */
7936 rc = mdb_page_search_lowest(&mn);
7939 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7940 key.mv_size = mn.mc_db->md_pad;
7941 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
7943 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7944 key.mv_size = NODEKSZ(s2);
7945 key.mv_data = NODEKEY(s2);
7948 key.mv_size = srcnode->mn_ksize;
7949 key.mv_data = NODEKEY(srcnode);
7952 data.mv_size = NODEDSZ(srcnode);
7953 data.mv_data = NODEDATA(srcnode);
7954 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
7955 if (rc != MDB_SUCCESS)
7960 DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
7961 pdst->mp_pgno, NUMKEYS(pdst),
7962 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
7964 /* Unlink the src page from parent and add to free list.
7967 mdb_node_del(csrc, 0);
7968 if (csrc->mc_ki[csrc->mc_top] == 0) {
7970 rc = mdb_update_key(csrc, &key);
7978 psrc = csrc->mc_pg[csrc->mc_top];
7979 /* If not operating on FreeDB, allow this page to be reused
7980 * in this txn. Otherwise just add to free list.
7982 rc = mdb_page_loose(csrc, psrc);
7986 csrc->mc_db->md_leaf_pages--;
7988 csrc->mc_db->md_branch_pages--;
7990 /* Adjust other cursors pointing to mp */
7991 MDB_cursor *m2, *m3;
7992 MDB_dbi dbi = csrc->mc_dbi;
7993 unsigned int top = csrc->mc_top;
7995 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7996 if (csrc->mc_flags & C_SUB)
7997 m3 = &m2->mc_xcursor->mx_cursor;
8000 if (m3 == csrc) continue;
8001 if (m3->mc_snum < csrc->mc_snum) continue;
8002 if (m3->mc_pg[top] == psrc) {
8003 m3->mc_pg[top] = pdst;
8004 m3->mc_ki[top] += nkeys;
8005 m3->mc_ki[top-1] = cdst->mc_ki[top-1];
8006 } else if (m3->mc_pg[top-1] == csrc->mc_pg[top-1] &&
8007 m3->mc_ki[top-1] > csrc->mc_ki[top-1]) {
8010 if (XCURSOR_INITED(m3) && IS_LEAF(psrc))
8011 XCURSOR_REFRESH(m3, m3->mc_pg[top], m3->mc_ki[top]);
8015 unsigned int snum = cdst->mc_snum;
8016 uint16_t depth = cdst->mc_db->md_depth;
8017 mdb_cursor_pop(cdst);
8018 rc = mdb_rebalance(cdst);
8019 /* Did the tree height change? */
8020 if (depth != cdst->mc_db->md_depth)
8021 snum += cdst->mc_db->md_depth - depth;
8022 cdst->mc_snum = snum;
8023 cdst->mc_top = snum-1;
8028 /** Copy the contents of a cursor.
8029 * @param[in] csrc The cursor to copy from.
8030 * @param[out] cdst The cursor to copy to.
8033 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
8037 cdst->mc_txn = csrc->mc_txn;
8038 cdst->mc_dbi = csrc->mc_dbi;
8039 cdst->mc_db = csrc->mc_db;
8040 cdst->mc_dbx = csrc->mc_dbx;
8041 cdst->mc_snum = csrc->mc_snum;
8042 cdst->mc_top = csrc->mc_top;
8043 cdst->mc_flags = csrc->mc_flags;
8045 for (i=0; i<csrc->mc_snum; i++) {
8046 cdst->mc_pg[i] = csrc->mc_pg[i];
8047 cdst->mc_ki[i] = csrc->mc_ki[i];
8051 /** Rebalance the tree after a delete operation.
8052 * @param[in] mc Cursor pointing to the page where rebalancing
8054 * @return 0 on success, non-zero on failure.
8057 mdb_rebalance(MDB_cursor *mc)
8061 unsigned int ptop, minkeys, thresh;
8065 if (IS_BRANCH(mc->mc_pg[mc->mc_top])) {
8070 thresh = FILL_THRESHOLD;
8072 DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
8073 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
8074 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
8075 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
8077 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= thresh &&
8078 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
8079 DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
8080 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
8084 if (mc->mc_snum < 2) {
8085 MDB_page *mp = mc->mc_pg[0];
8087 DPUTS("Can't rebalance a subpage, ignoring");
8090 if (NUMKEYS(mp) == 0) {
8091 DPUTS("tree is completely empty");
8092 mc->mc_db->md_root = P_INVALID;
8093 mc->mc_db->md_depth = 0;
8094 mc->mc_db->md_leaf_pages = 0;
8095 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
8098 /* Adjust cursors pointing to mp */
8101 mc->mc_flags &= ~C_INITIALIZED;
8103 MDB_cursor *m2, *m3;
8104 MDB_dbi dbi = mc->mc_dbi;
8106 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8107 if (mc->mc_flags & C_SUB)
8108 m3 = &m2->mc_xcursor->mx_cursor;
8111 if (!(m3->mc_flags & C_INITIALIZED) || (m3->mc_snum < mc->mc_snum))
8113 if (m3->mc_pg[0] == mp) {
8116 m3->mc_flags &= ~C_INITIALIZED;
8120 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
8122 DPUTS("collapsing root page!");
8123 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
8126 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
8127 rc = mdb_page_get(mc, mc->mc_db->md_root, &mc->mc_pg[0], NULL);
8130 mc->mc_db->md_depth--;
8131 mc->mc_db->md_branch_pages--;
8132 mc->mc_ki[0] = mc->mc_ki[1];
8133 for (i = 1; i<mc->mc_db->md_depth; i++) {
8134 mc->mc_pg[i] = mc->mc_pg[i+1];
8135 mc->mc_ki[i] = mc->mc_ki[i+1];
8138 /* Adjust other cursors pointing to mp */
8139 MDB_cursor *m2, *m3;
8140 MDB_dbi dbi = mc->mc_dbi;
8142 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8143 if (mc->mc_flags & C_SUB)
8144 m3 = &m2->mc_xcursor->mx_cursor;
8147 if (m3 == mc) continue;
8148 if (!(m3->mc_flags & C_INITIALIZED))
8150 if (m3->mc_pg[0] == mp) {
8151 for (i=0; i<mc->mc_db->md_depth; i++) {
8152 m3->mc_pg[i] = m3->mc_pg[i+1];
8153 m3->mc_ki[i] = m3->mc_ki[i+1];
8161 DPUTS("root page doesn't need rebalancing");
8165 /* The parent (branch page) must have at least 2 pointers,
8166 * otherwise the tree is invalid.
8168 ptop = mc->mc_top-1;
8169 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
8171 /* Leaf page fill factor is below the threshold.
8172 * Try to move keys from left or right neighbor, or
8173 * merge with a neighbor page.
8178 mdb_cursor_copy(mc, &mn);
8179 mn.mc_xcursor = NULL;
8181 oldki = mc->mc_ki[mc->mc_top];
8182 if (mc->mc_ki[ptop] == 0) {
8183 /* We're the leftmost leaf in our parent.
8185 DPUTS("reading right neighbor");
8187 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
8188 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
8191 mn.mc_ki[mn.mc_top] = 0;
8192 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
8195 /* There is at least one neighbor to the left.
8197 DPUTS("reading left neighbor");
8199 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
8200 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
8203 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
8204 mc->mc_ki[mc->mc_top] = 0;
8208 DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
8209 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
8210 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
8212 /* If the neighbor page is above threshold and has enough keys,
8213 * move one key from it. Otherwise we should try to merge them.
8214 * (A branch page must never have less than 2 keys.)
8216 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= thresh && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
8217 rc = mdb_node_move(&mn, mc, fromleft);
8219 /* if we inserted on left, bump position up */
8224 rc = mdb_page_merge(&mn, mc);
8226 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
8227 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
8228 /* We want mdb_rebalance to find mn when doing fixups */
8229 WITH_CURSOR_TRACKING(mn,
8230 rc = mdb_page_merge(mc, &mn));
8231 mdb_cursor_copy(&mn, mc);
8233 mc->mc_flags &= ~C_EOF;
8235 mc->mc_ki[mc->mc_top] = oldki;
8239 /** Complete a delete operation started by #mdb_cursor_del(). */
8241 mdb_cursor_del0(MDB_cursor *mc)
8247 MDB_cursor *m2, *m3;
8248 MDB_dbi dbi = mc->mc_dbi;
8250 ki = mc->mc_ki[mc->mc_top];
8251 mp = mc->mc_pg[mc->mc_top];
8252 mdb_node_del(mc, mc->mc_db->md_pad);
8253 mc->mc_db->md_entries--;
8255 /* Adjust other cursors pointing to mp */
8256 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8257 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
8258 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8260 if (m3 == mc || m3->mc_snum < mc->mc_snum)
8262 if (m3->mc_pg[mc->mc_top] == mp) {
8263 if (m3->mc_ki[mc->mc_top] == ki) {
8264 m3->mc_flags |= C_DEL;
8265 if (mc->mc_db->md_flags & MDB_DUPSORT) {
8266 /* Sub-cursor referred into dataset which is gone */
8267 m3->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
8270 } else if (m3->mc_ki[mc->mc_top] > ki) {
8271 m3->mc_ki[mc->mc_top]--;
8273 if (XCURSOR_INITED(m3))
8274 XCURSOR_REFRESH(m3, m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
8278 rc = mdb_rebalance(mc);
8280 if (rc == MDB_SUCCESS) {
8281 /* DB is totally empty now, just bail out.
8282 * Other cursors adjustments were already done
8283 * by mdb_rebalance and aren't needed here.
8288 mp = mc->mc_pg[mc->mc_top];
8289 nkeys = NUMKEYS(mp);
8291 /* Adjust other cursors pointing to mp */
8292 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
8293 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
8294 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8296 if (m3->mc_snum < mc->mc_snum)
8298 if (m3->mc_pg[mc->mc_top] == mp) {
8299 /* if m3 points past last node in page, find next sibling */
8300 if (m3->mc_ki[mc->mc_top] >= mc->mc_ki[mc->mc_top]) {
8301 if (m3->mc_ki[mc->mc_top] >= nkeys) {
8302 rc = mdb_cursor_sibling(m3, 1);
8303 if (rc == MDB_NOTFOUND) {
8304 m3->mc_flags |= C_EOF;
8309 if (mc->mc_db->md_flags & MDB_DUPSORT) {
8310 MDB_node *node = NODEPTR(m3->mc_pg[m3->mc_top], m3->mc_ki[m3->mc_top]);
8311 /* If this node is a fake page, it needs to be reinited
8312 * because its data has moved. But just reset mc_pg[0]
8313 * if the xcursor is already live.
8315 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) {
8316 if (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)
8317 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
8319 mdb_xcursor_init1(m3, node);
8325 mc->mc_flags |= C_DEL;
8329 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8334 mdb_del(MDB_txn *txn, MDB_dbi dbi,
8335 MDB_val *key, MDB_val *data)
8337 if (!key || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
8340 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
8341 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
8343 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
8344 /* must ignore any data */
8348 return mdb_del0(txn, dbi, key, data, 0);
8352 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
8353 MDB_val *key, MDB_val *data, unsigned flags)
8358 MDB_val rdata, *xdata;
8362 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
8364 mdb_cursor_init(&mc, txn, dbi, &mx);
8373 flags |= MDB_NODUPDATA;
8375 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
8377 /* let mdb_page_split know about this cursor if needed:
8378 * delete will trigger a rebalance; if it needs to move
8379 * a node from one page to another, it will have to
8380 * update the parent's separator key(s). If the new sepkey
8381 * is larger than the current one, the parent page may
8382 * run out of space, triggering a split. We need this
8383 * cursor to be consistent until the end of the rebalance.
8385 mc.mc_flags |= C_UNTRACK;
8386 mc.mc_next = txn->mt_cursors[dbi];
8387 txn->mt_cursors[dbi] = &mc;
8388 rc = mdb_cursor_del(&mc, flags);
8389 txn->mt_cursors[dbi] = mc.mc_next;
8394 /** Split a page and insert a new node.
8395 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
8396 * The cursor will be updated to point to the actual page and index where
8397 * the node got inserted after the split.
8398 * @param[in] newkey The key for the newly inserted node.
8399 * @param[in] newdata The data for the newly inserted node.
8400 * @param[in] newpgno The page number, if the new node is a branch node.
8401 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
8402 * @return 0 on success, non-zero on failure.
8405 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
8406 unsigned int nflags)
8409 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
8412 int i, j, split_indx, nkeys, pmax;
8413 MDB_env *env = mc->mc_txn->mt_env;
8415 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
8416 MDB_page *copy = NULL;
8417 MDB_page *mp, *rp, *pp;
8422 mp = mc->mc_pg[mc->mc_top];
8423 newindx = mc->mc_ki[mc->mc_top];
8424 nkeys = NUMKEYS(mp);
8426 DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i/%i",
8427 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
8428 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
8430 /* Create a right sibling. */
8431 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
8433 rp->mp_pad = mp->mp_pad;
8434 DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
8436 /* Usually when splitting the root page, the cursor
8437 * height is 1. But when called from mdb_update_key,
8438 * the cursor height may be greater because it walks
8439 * up the stack while finding the branch slot to update.
8441 if (mc->mc_top < 1) {
8442 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
8444 /* shift current top to make room for new parent */
8445 for (i=mc->mc_snum; i>0; i--) {
8446 mc->mc_pg[i] = mc->mc_pg[i-1];
8447 mc->mc_ki[i] = mc->mc_ki[i-1];
8451 mc->mc_db->md_root = pp->mp_pgno;
8452 DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
8453 new_root = mc->mc_db->md_depth++;
8455 /* Add left (implicit) pointer. */
8456 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
8457 /* undo the pre-push */
8458 mc->mc_pg[0] = mc->mc_pg[1];
8459 mc->mc_ki[0] = mc->mc_ki[1];
8460 mc->mc_db->md_root = mp->mp_pgno;
8461 mc->mc_db->md_depth--;
8468 ptop = mc->mc_top-1;
8469 DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
8472 mdb_cursor_copy(mc, &mn);
8473 mn.mc_xcursor = NULL;
8474 mn.mc_pg[mn.mc_top] = rp;
8475 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
8477 if (nflags & MDB_APPEND) {
8478 mn.mc_ki[mn.mc_top] = 0;
8480 split_indx = newindx;
8484 split_indx = (nkeys+1) / 2;
8489 unsigned int lsize, rsize, ksize;
8490 /* Move half of the keys to the right sibling */
8491 x = mc->mc_ki[mc->mc_top] - split_indx;
8492 ksize = mc->mc_db->md_pad;
8493 split = LEAF2KEY(mp, split_indx, ksize);
8494 rsize = (nkeys - split_indx) * ksize;
8495 lsize = (nkeys - split_indx) * sizeof(indx_t);
8496 mp->mp_lower -= lsize;
8497 rp->mp_lower += lsize;
8498 mp->mp_upper += rsize - lsize;
8499 rp->mp_upper -= rsize - lsize;
8500 sepkey.mv_size = ksize;
8501 if (newindx == split_indx) {
8502 sepkey.mv_data = newkey->mv_data;
8504 sepkey.mv_data = split;
8507 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
8508 memcpy(rp->mp_ptrs, split, rsize);
8509 sepkey.mv_data = rp->mp_ptrs;
8510 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
8511 memcpy(ins, newkey->mv_data, ksize);
8512 mp->mp_lower += sizeof(indx_t);
8513 mp->mp_upper -= ksize - sizeof(indx_t);
8516 memcpy(rp->mp_ptrs, split, x * ksize);
8517 ins = LEAF2KEY(rp, x, ksize);
8518 memcpy(ins, newkey->mv_data, ksize);
8519 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
8520 rp->mp_lower += sizeof(indx_t);
8521 rp->mp_upper -= ksize - sizeof(indx_t);
8522 mc->mc_ki[mc->mc_top] = x;
8525 int psize, nsize, k;
8526 /* Maximum free space in an empty page */
8527 pmax = env->me_psize - PAGEHDRSZ;
8529 nsize = mdb_leaf_size(env, newkey, newdata);
8531 nsize = mdb_branch_size(env, newkey);
8532 nsize = EVEN(nsize);
8534 /* grab a page to hold a temporary copy */
8535 copy = mdb_page_malloc(mc->mc_txn, 1);
8540 copy->mp_pgno = mp->mp_pgno;
8541 copy->mp_flags = mp->mp_flags;
8542 copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
8543 copy->mp_upper = env->me_psize - PAGEBASE;
8545 /* prepare to insert */
8546 for (i=0, j=0; i<nkeys; i++) {
8548 copy->mp_ptrs[j++] = 0;
8550 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
8553 /* When items are relatively large the split point needs
8554 * to be checked, because being off-by-one will make the
8555 * difference between success or failure in mdb_node_add.
8557 * It's also relevant if a page happens to be laid out
8558 * such that one half of its nodes are all "small" and
8559 * the other half of its nodes are "large." If the new
8560 * item is also "large" and falls on the half with
8561 * "large" nodes, it also may not fit.
8563 * As a final tweak, if the new item goes on the last
8564 * spot on the page (and thus, onto the new page), bias
8565 * the split so the new page is emptier than the old page.
8566 * This yields better packing during sequential inserts.
8568 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
8569 /* Find split point */
8571 if (newindx <= split_indx || newindx >= nkeys) {
8573 k = newindx >= nkeys ? nkeys : split_indx+1+IS_LEAF(mp);
8578 for (; i!=k; i+=j) {
8583 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8584 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
8586 if (F_ISSET(node->mn_flags, F_BIGDATA))
8587 psize += sizeof(pgno_t);
8589 psize += NODEDSZ(node);
8591 psize = EVEN(psize);
8593 if (psize > pmax || i == k-j) {
8594 split_indx = i + (j<0);
8599 if (split_indx == newindx) {
8600 sepkey.mv_size = newkey->mv_size;
8601 sepkey.mv_data = newkey->mv_data;
8603 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
8604 sepkey.mv_size = node->mn_ksize;
8605 sepkey.mv_data = NODEKEY(node);
8610 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
8612 /* Copy separator key to the parent.
8614 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
8615 int snum = mc->mc_snum;
8619 /* We want other splits to find mn when doing fixups */
8620 WITH_CURSOR_TRACKING(mn,
8621 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0));
8626 if (mc->mc_snum > snum) {
8629 /* Right page might now have changed parent.
8630 * Check if left page also changed parent.
8632 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8633 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8634 for (i=0; i<ptop; i++) {
8635 mc->mc_pg[i] = mn.mc_pg[i];
8636 mc->mc_ki[i] = mn.mc_ki[i];
8638 mc->mc_pg[ptop] = mn.mc_pg[ptop];
8639 if (mn.mc_ki[ptop]) {
8640 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
8642 /* find right page's left sibling */
8643 mc->mc_ki[ptop] = mn.mc_ki[ptop];
8644 mdb_cursor_sibling(mc, 0);
8649 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
8652 if (rc != MDB_SUCCESS) {
8655 if (nflags & MDB_APPEND) {
8656 mc->mc_pg[mc->mc_top] = rp;
8657 mc->mc_ki[mc->mc_top] = 0;
8658 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
8661 for (i=0; i<mc->mc_top; i++)
8662 mc->mc_ki[i] = mn.mc_ki[i];
8663 } else if (!IS_LEAF2(mp)) {
8665 mc->mc_pg[mc->mc_top] = rp;
8670 rkey.mv_data = newkey->mv_data;
8671 rkey.mv_size = newkey->mv_size;
8677 /* Update index for the new key. */
8678 mc->mc_ki[mc->mc_top] = j;
8680 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8681 rkey.mv_data = NODEKEY(node);
8682 rkey.mv_size = node->mn_ksize;
8684 xdata.mv_data = NODEDATA(node);
8685 xdata.mv_size = NODEDSZ(node);
8688 pgno = NODEPGNO(node);
8689 flags = node->mn_flags;
8692 if (!IS_LEAF(mp) && j == 0) {
8693 /* First branch index doesn't need key data. */
8697 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
8703 mc->mc_pg[mc->mc_top] = copy;
8708 } while (i != split_indx);
8710 nkeys = NUMKEYS(copy);
8711 for (i=0; i<nkeys; i++)
8712 mp->mp_ptrs[i] = copy->mp_ptrs[i];
8713 mp->mp_lower = copy->mp_lower;
8714 mp->mp_upper = copy->mp_upper;
8715 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
8716 env->me_psize - copy->mp_upper - PAGEBASE);
8718 /* reset back to original page */
8719 if (newindx < split_indx) {
8720 mc->mc_pg[mc->mc_top] = mp;
8722 mc->mc_pg[mc->mc_top] = rp;
8724 /* Make sure mc_ki is still valid.
8726 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8727 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8728 for (i=0; i<=ptop; i++) {
8729 mc->mc_pg[i] = mn.mc_pg[i];
8730 mc->mc_ki[i] = mn.mc_ki[i];
8734 if (nflags & MDB_RESERVE) {
8735 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
8736 if (!(node->mn_flags & F_BIGDATA))
8737 newdata->mv_data = NODEDATA(node);
8740 if (newindx >= split_indx) {
8741 mc->mc_pg[mc->mc_top] = rp;
8743 /* Make sure mc_ki is still valid.
8745 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8746 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8747 for (i=0; i<=ptop; i++) {
8748 mc->mc_pg[i] = mn.mc_pg[i];
8749 mc->mc_ki[i] = mn.mc_ki[i];
8756 /* Adjust other cursors pointing to mp */
8757 MDB_cursor *m2, *m3;
8758 MDB_dbi dbi = mc->mc_dbi;
8759 nkeys = NUMKEYS(mp);
8761 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8762 if (mc->mc_flags & C_SUB)
8763 m3 = &m2->mc_xcursor->mx_cursor;
8768 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8772 /* sub cursors may be on different DB */
8773 if (m3->mc_pg[0] != mp)
8776 for (k=new_root; k>=0; k--) {
8777 m3->mc_ki[k+1] = m3->mc_ki[k];
8778 m3->mc_pg[k+1] = m3->mc_pg[k];
8780 if (m3->mc_ki[0] >= nkeys) {
8785 m3->mc_pg[0] = mc->mc_pg[0];
8789 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
8790 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
8791 m3->mc_ki[mc->mc_top]++;
8792 if (m3->mc_ki[mc->mc_top] >= nkeys) {
8793 m3->mc_pg[mc->mc_top] = rp;
8794 m3->mc_ki[mc->mc_top] -= nkeys;
8795 for (i=0; i<mc->mc_top; i++) {
8796 m3->mc_ki[i] = mn.mc_ki[i];
8797 m3->mc_pg[i] = mn.mc_pg[i];
8800 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
8801 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
8804 if (XCURSOR_INITED(m3) && IS_LEAF(mp))
8805 XCURSOR_REFRESH(m3, m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
8808 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
8811 if (copy) /* tmp page */
8812 mdb_page_free(env, copy);
8814 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8819 mdb_put(MDB_txn *txn, MDB_dbi dbi,
8820 MDB_val *key, MDB_val *data, unsigned int flags)
8826 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
8829 if (flags & ~(MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP))
8832 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
8833 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
8835 mdb_cursor_init(&mc, txn, dbi, &mx);
8836 mc.mc_next = txn->mt_cursors[dbi];
8837 txn->mt_cursors[dbi] = &mc;
8838 rc = mdb_cursor_put(&mc, key, data, flags);
8839 txn->mt_cursors[dbi] = mc.mc_next;
8844 #define MDB_WBUF (1024*1024)
8846 #define MDB_EOF 0x10 /**< #mdb_env_copyfd1() is done reading */
8848 /** State needed for a double-buffering compacting copy. */
8849 typedef struct mdb_copy {
8852 pthread_mutex_t mc_mutex;
8853 pthread_cond_t mc_cond; /**< Condition variable for #mc_new */
8858 pgno_t mc_next_pgno;
8860 int mc_toggle; /**< Buffer number in provider */
8861 int mc_new; /**< (0-2 buffers to write) | (#MDB_EOF at end) */
8862 /** Error code. Never cleared if set. Both threads can set nonzero
8863 * to fail the copy. Not mutex-protected, LMDB expects atomic int.
8865 volatile int mc_error;
8868 /** Dedicated writer thread for compacting copy. */
8869 static THREAD_RET ESECT CALL_CONV
8870 mdb_env_copythr(void *arg)
8874 int toggle = 0, wsize, rc;
8877 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8880 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8883 pthread_mutex_lock(&my->mc_mutex);
8886 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8887 if (my->mc_new == 0 + MDB_EOF) /* 0 buffers, just EOF */
8889 wsize = my->mc_wlen[toggle];
8890 ptr = my->mc_wbuf[toggle];
8893 while (wsize > 0 && !my->mc_error) {
8894 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
8898 } else if (len > 0) {
8911 /* If there's an overflow page tail, write it too */
8912 if (my->mc_olen[toggle]) {
8913 wsize = my->mc_olen[toggle];
8914 ptr = my->mc_over[toggle];
8915 my->mc_olen[toggle] = 0;
8918 my->mc_wlen[toggle] = 0;
8920 /* Return the empty buffer to provider */
8922 pthread_cond_signal(&my->mc_cond);
8924 pthread_mutex_unlock(&my->mc_mutex);
8925 return (THREAD_RET)0;
8929 /** Give buffer and/or #MDB_EOF to writer thread, await unused buffer.
8931 * @param[in] my control structure.
8932 * @param[in] adjust (1 to hand off 1 buffer) | (MDB_EOF when ending).
8935 mdb_env_cthr_toggle(mdb_copy *my, int adjust)
8937 pthread_mutex_lock(&my->mc_mutex);
8938 my->mc_new += adjust;
8939 pthread_cond_signal(&my->mc_cond);
8940 while (my->mc_new & 2) /* both buffers in use */
8941 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8942 pthread_mutex_unlock(&my->mc_mutex);
8944 my->mc_toggle ^= (adjust & 1);
8945 /* Both threads reset mc_wlen, to be safe from threading errors */
8946 my->mc_wlen[my->mc_toggle] = 0;
8947 return my->mc_error;
8950 /** Depth-first tree traversal for compacting copy.
8951 * @param[in] my control structure.
8952 * @param[in,out] pg database root.
8953 * @param[in] flags includes #F_DUPDATA if it is a sorted-duplicate sub-DB.
8956 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
8958 MDB_cursor mc = {0};
8960 MDB_page *mo, *mp, *leaf;
8965 /* Empty DB, nothing to do */
8966 if (*pg == P_INVALID)
8970 mc.mc_txn = my->mc_txn;
8972 rc = mdb_page_get(&mc, *pg, &mc.mc_pg[0], NULL);
8975 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
8979 /* Make cursor pages writable */
8980 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
8984 for (i=0; i<mc.mc_top; i++) {
8985 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
8986 mc.mc_pg[i] = (MDB_page *)ptr;
8987 ptr += my->mc_env->me_psize;
8990 /* This is writable space for a leaf page. Usually not needed. */
8991 leaf = (MDB_page *)ptr;
8993 toggle = my->mc_toggle;
8994 while (mc.mc_snum > 0) {
8996 mp = mc.mc_pg[mc.mc_top];
9000 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
9001 for (i=0; i<n; i++) {
9002 ni = NODEPTR(mp, i);
9003 if (ni->mn_flags & F_BIGDATA) {
9007 /* Need writable leaf */
9009 mc.mc_pg[mc.mc_top] = leaf;
9010 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
9012 ni = NODEPTR(mp, i);
9015 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9016 memcpy(NODEDATA(ni), &my->mc_next_pgno, sizeof(pgno_t));
9017 rc = mdb_page_get(&mc, pg, &omp, NULL);
9020 if (my->mc_wlen[toggle] >= MDB_WBUF) {
9021 rc = mdb_env_cthr_toggle(my, 1);
9024 toggle = my->mc_toggle;
9026 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
9027 memcpy(mo, omp, my->mc_env->me_psize);
9028 mo->mp_pgno = my->mc_next_pgno;
9029 my->mc_next_pgno += omp->mp_pages;
9030 my->mc_wlen[toggle] += my->mc_env->me_psize;
9031 if (omp->mp_pages > 1) {
9032 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
9033 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
9034 rc = mdb_env_cthr_toggle(my, 1);
9037 toggle = my->mc_toggle;
9039 } else if (ni->mn_flags & F_SUBDATA) {
9042 /* Need writable leaf */
9044 mc.mc_pg[mc.mc_top] = leaf;
9045 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
9047 ni = NODEPTR(mp, i);
9050 memcpy(&db, NODEDATA(ni), sizeof(db));
9051 my->mc_toggle = toggle;
9052 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
9055 toggle = my->mc_toggle;
9056 memcpy(NODEDATA(ni), &db, sizeof(db));
9061 mc.mc_ki[mc.mc_top]++;
9062 if (mc.mc_ki[mc.mc_top] < n) {
9065 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
9067 rc = mdb_page_get(&mc, pg, &mp, NULL);
9072 mc.mc_ki[mc.mc_top] = 0;
9073 if (IS_BRANCH(mp)) {
9074 /* Whenever we advance to a sibling branch page,
9075 * we must proceed all the way down to its first leaf.
9077 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
9080 mc.mc_pg[mc.mc_top] = mp;
9084 if (my->mc_wlen[toggle] >= MDB_WBUF) {
9085 rc = mdb_env_cthr_toggle(my, 1);
9088 toggle = my->mc_toggle;
9090 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
9091 mdb_page_copy(mo, mp, my->mc_env->me_psize);
9092 mo->mp_pgno = my->mc_next_pgno++;
9093 my->mc_wlen[toggle] += my->mc_env->me_psize;
9095 /* Update parent if there is one */
9096 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
9097 SETPGNO(ni, mo->mp_pgno);
9098 mdb_cursor_pop(&mc);
9100 /* Otherwise we're done */
9110 /** Copy environment with compaction. */
9112 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
9117 MDB_txn *txn = NULL;
9119 pgno_t root, new_root;
9120 int rc = MDB_SUCCESS;
9123 if (!(my.mc_mutex = CreateMutex(NULL, FALSE, NULL)) ||
9124 !(my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL))) {
9128 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_os_psize);
9129 if (my.mc_wbuf[0] == NULL) {
9130 /* _aligned_malloc() sets errno, but we use Windows error codes */
9131 rc = ERROR_NOT_ENOUGH_MEMORY;
9135 if ((rc = pthread_mutex_init(&my.mc_mutex, NULL)) != 0)
9137 if ((rc = pthread_cond_init(&my.mc_cond, NULL)) != 0)
9139 #ifdef HAVE_MEMALIGN
9140 my.mc_wbuf[0] = memalign(env->me_os_psize, MDB_WBUF*2);
9141 if (my.mc_wbuf[0] == NULL) {
9148 if ((rc = posix_memalign(&p, env->me_os_psize, MDB_WBUF*2)) != 0)
9154 memset(my.mc_wbuf[0], 0, MDB_WBUF*2);
9155 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
9156 my.mc_next_pgno = NUM_METAS;
9159 rc = THREAD_CREATE(thr, mdb_env_copythr, &my);
9163 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
9167 mp = (MDB_page *)my.mc_wbuf[0];
9168 memset(mp, 0, NUM_METAS * env->me_psize);
9170 mp->mp_flags = P_META;
9171 mm = (MDB_meta *)METADATA(mp);
9172 mdb_env_init_meta0(env, mm);
9173 mm->mm_address = env->me_metas[0]->mm_address;
9175 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
9177 mp->mp_flags = P_META;
9178 *(MDB_meta *)METADATA(mp) = *mm;
9179 mm = (MDB_meta *)METADATA(mp);
9181 /* Set metapage 1 with current main DB */
9182 root = new_root = txn->mt_dbs[MAIN_DBI].md_root;
9183 if (root != P_INVALID) {
9184 /* Count free pages + freeDB pages. Subtract from last_pg
9185 * to find the new last_pg, which also becomes the new root.
9187 MDB_ID freecount = 0;
9190 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
9191 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
9192 freecount += *(MDB_ID *)data.mv_data;
9193 if (rc != MDB_NOTFOUND)
9195 freecount += txn->mt_dbs[FREE_DBI].md_branch_pages +
9196 txn->mt_dbs[FREE_DBI].md_leaf_pages +
9197 txn->mt_dbs[FREE_DBI].md_overflow_pages;
9199 new_root = txn->mt_next_pgno - 1 - freecount;
9200 mm->mm_last_pg = new_root;
9201 mm->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
9202 mm->mm_dbs[MAIN_DBI].md_root = new_root;
9204 /* When the DB is empty, handle it specially to
9205 * fix any breakage like page leaks from ITS#8174.
9207 mm->mm_dbs[MAIN_DBI].md_flags = txn->mt_dbs[MAIN_DBI].md_flags;
9209 if (root != P_INVALID || mm->mm_dbs[MAIN_DBI].md_flags) {
9210 mm->mm_txnid = 1; /* use metapage 1 */
9213 my.mc_wlen[0] = env->me_psize * NUM_METAS;
9215 rc = mdb_env_cwalk(&my, &root, 0);
9216 if (rc == MDB_SUCCESS && root != new_root) {
9217 rc = MDB_INCOMPATIBLE; /* page leak or corrupt DB */
9223 mdb_env_cthr_toggle(&my, 1 | MDB_EOF);
9224 rc = THREAD_FINISH(thr);
9229 if (my.mc_wbuf[0]) _aligned_free(my.mc_wbuf[0]);
9230 if (my.mc_cond) CloseHandle(my.mc_cond);
9231 if (my.mc_mutex) CloseHandle(my.mc_mutex);
9233 free(my.mc_wbuf[0]);
9234 pthread_cond_destroy(&my.mc_cond);
9236 pthread_mutex_destroy(&my.mc_mutex);
9238 return rc ? rc : my.mc_error;
9241 /** Copy environment as-is. */
9243 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
9245 MDB_txn *txn = NULL;
9246 mdb_mutexref_t wmutex = NULL;
9252 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
9256 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
9259 /* Do the lock/unlock of the reader mutex before starting the
9260 * write txn. Otherwise other read txns could block writers.
9262 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
9267 /* We must start the actual read txn after blocking writers */
9268 mdb_txn_end(txn, MDB_END_RESET_TMP);
9270 /* Temporarily block writers until we snapshot the meta pages */
9271 wmutex = env->me_wmutex;
9272 if (LOCK_MUTEX(rc, env, wmutex))
9275 rc = mdb_txn_renew0(txn);
9277 UNLOCK_MUTEX(wmutex);
9282 wsize = env->me_psize * NUM_METAS;
9286 DO_WRITE(rc, fd, ptr, w2, len);
9290 } else if (len > 0) {
9296 /* Non-blocking or async handles are not supported */
9302 UNLOCK_MUTEX(wmutex);
9307 w3 = txn->mt_next_pgno * env->me_psize;
9310 if ((rc = mdb_fsize(env->me_fd, &fsize)))
9317 if (wsize > MAX_WRITE)
9321 DO_WRITE(rc, fd, ptr, w2, len);
9325 } else if (len > 0) {
9342 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
9344 if (flags & MDB_CP_COMPACT)
9345 return mdb_env_copyfd1(env, fd);
9347 return mdb_env_copyfd0(env, fd);
9351 mdb_env_copyfd(MDB_env *env, HANDLE fd)
9353 return mdb_env_copyfd2(env, fd, 0);
9357 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
9361 HANDLE newfd = INVALID_HANDLE_VALUE;
9366 if (env->me_flags & MDB_NOSUBDIR) {
9367 lpath = (char *)path;
9370 len += sizeof(DATANAME);
9371 lpath = malloc(len);
9374 sprintf(lpath, "%s" DATANAME, path);
9377 /* The destination path must exist, but the destination file must not.
9378 * We don't want the OS to cache the writes, since the source data is
9379 * already in the OS cache.
9382 rc = utf8_to_utf16(lpath, -1, &wpath, NULL);
9385 newfd = CreateFileW(wpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
9386 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
9389 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
9391 if (newfd == INVALID_HANDLE_VALUE) {
9396 if (env->me_psize >= env->me_os_psize) {
9397 #ifdef F_NOCACHE /* __APPLE__ */
9398 (void) fcntl(newfd, F_NOCACHE, 1);
9399 #elif defined O_DIRECT
9400 /* Set O_DIRECT if the file system supports it */
9401 if ((rc = fcntl(newfd, F_GETFL)) != -1)
9402 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
9406 rc = mdb_env_copyfd2(env, newfd, flags);
9409 if (!(env->me_flags & MDB_NOSUBDIR))
9411 if (newfd != INVALID_HANDLE_VALUE)
9412 if (close(newfd) < 0 && rc == MDB_SUCCESS)
9419 mdb_env_copy(MDB_env *env, const char *path)
9421 return mdb_env_copy2(env, path, 0);
9425 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
9427 if (flag & ~CHANGEABLE)
9430 env->me_flags |= flag;
9432 env->me_flags &= ~flag;
9437 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
9442 *arg = env->me_flags & (CHANGEABLE|CHANGELESS);
9447 mdb_env_set_userctx(MDB_env *env, void *ctx)
9451 env->me_userctx = ctx;
9456 mdb_env_get_userctx(MDB_env *env)
9458 return env ? env->me_userctx : NULL;
9462 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
9467 env->me_assert_func = func;
9473 mdb_env_get_path(MDB_env *env, const char **arg)
9478 *arg = env->me_path;
9483 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
9492 /** Common code for #mdb_stat() and #mdb_env_stat().
9493 * @param[in] env the environment to operate in.
9494 * @param[in] db the #MDB_db record containing the stats to return.
9495 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
9496 * @return 0, this function always succeeds.
9499 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
9501 arg->ms_psize = env->me_psize;
9502 arg->ms_depth = db->md_depth;
9503 arg->ms_branch_pages = db->md_branch_pages;
9504 arg->ms_leaf_pages = db->md_leaf_pages;
9505 arg->ms_overflow_pages = db->md_overflow_pages;
9506 arg->ms_entries = db->md_entries;
9512 mdb_env_stat(MDB_env *env, MDB_stat *arg)
9516 if (env == NULL || arg == NULL)
9519 meta = mdb_env_pick_meta(env);
9521 return mdb_stat0(env, &meta->mm_dbs[MAIN_DBI], arg);
9525 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
9529 if (env == NULL || arg == NULL)
9532 meta = mdb_env_pick_meta(env);
9533 arg->me_mapaddr = meta->mm_address;
9534 arg->me_last_pgno = meta->mm_last_pg;
9535 arg->me_last_txnid = meta->mm_txnid;
9537 arg->me_mapsize = env->me_mapsize;
9538 arg->me_maxreaders = env->me_maxreaders;
9539 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : 0;
9543 /** Set the default comparison functions for a database.
9544 * Called immediately after a database is opened to set the defaults.
9545 * The user can then override them with #mdb_set_compare() or
9546 * #mdb_set_dupsort().
9547 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
9548 * @param[in] dbi A database handle returned by #mdb_dbi_open()
9551 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
9553 uint16_t f = txn->mt_dbs[dbi].md_flags;
9555 txn->mt_dbxs[dbi].md_cmp =
9556 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
9557 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
9559 txn->mt_dbxs[dbi].md_dcmp =
9560 !(f & MDB_DUPSORT) ? 0 :
9561 ((f & MDB_INTEGERDUP)
9562 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
9563 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
9566 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
9572 int rc, dbflag, exact;
9573 unsigned int unused = 0, seq;
9577 if (flags & ~VALID_FLAGS)
9579 if (txn->mt_flags & MDB_TXN_BLOCKED)
9585 if (flags & PERSISTENT_FLAGS) {
9586 uint16_t f2 = flags & PERSISTENT_FLAGS;
9587 /* make sure flag changes get committed */
9588 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
9589 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
9590 txn->mt_flags |= MDB_TXN_DIRTY;
9593 mdb_default_cmp(txn, MAIN_DBI);
9597 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
9598 mdb_default_cmp(txn, MAIN_DBI);
9601 /* Is the DB already open? */
9603 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
9604 if (!txn->mt_dbxs[i].md_name.mv_size) {
9605 /* Remember this free slot */
9606 if (!unused) unused = i;
9609 if (len == txn->mt_dbxs[i].md_name.mv_size &&
9610 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
9616 /* If no free slot and max hit, fail */
9617 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
9618 return MDB_DBS_FULL;
9620 /* Cannot mix named databases with some mainDB flags */
9621 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
9622 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
9624 /* Find the DB info */
9625 dbflag = DB_NEW|DB_VALID|DB_USRVALID;
9628 key.mv_data = (void *)name;
9629 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
9630 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
9631 if (rc == MDB_SUCCESS) {
9632 /* make sure this is actually a DB */
9633 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
9634 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
9635 return MDB_INCOMPATIBLE;
9636 } else if (! (rc == MDB_NOTFOUND && (flags & MDB_CREATE))) {
9640 /* Done here so we cannot fail after creating a new DB */
9641 if ((namedup = strdup(name)) == NULL)
9645 /* MDB_NOTFOUND and MDB_CREATE: Create new DB */
9646 data.mv_size = sizeof(MDB_db);
9647 data.mv_data = &dummy;
9648 memset(&dummy, 0, sizeof(dummy));
9649 dummy.md_root = P_INVALID;
9650 dummy.md_flags = flags & PERSISTENT_FLAGS;
9651 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
9658 /* Got info, register DBI in this txn */
9659 unsigned int slot = unused ? unused : txn->mt_numdbs;
9660 txn->mt_dbxs[slot].md_name.mv_data = namedup;
9661 txn->mt_dbxs[slot].md_name.mv_size = len;
9662 txn->mt_dbxs[slot].md_rel = NULL;
9663 txn->mt_dbflags[slot] = dbflag;
9664 /* txn-> and env-> are the same in read txns, use
9665 * tmp variable to avoid undefined assignment
9667 seq = ++txn->mt_env->me_dbiseqs[slot];
9668 txn->mt_dbiseqs[slot] = seq;
9670 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
9672 mdb_default_cmp(txn, slot);
9682 mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
9684 if (!arg || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
9687 if (txn->mt_flags & MDB_TXN_BLOCKED)
9690 if (txn->mt_dbflags[dbi] & DB_STALE) {
9693 /* Stale, must read the DB's root. cursor_init does it for us. */
9694 mdb_cursor_init(&mc, txn, dbi, &mx);
9696 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
9699 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
9702 if (dbi < CORE_DBS || dbi >= env->me_maxdbs)
9704 ptr = env->me_dbxs[dbi].md_name.mv_data;
9705 /* If there was no name, this was already closed */
9707 env->me_dbxs[dbi].md_name.mv_data = NULL;
9708 env->me_dbxs[dbi].md_name.mv_size = 0;
9709 env->me_dbflags[dbi] = 0;
9710 env->me_dbiseqs[dbi]++;
9715 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
9717 /* We could return the flags for the FREE_DBI too but what's the point? */
9718 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9720 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
9724 /** Add all the DB's pages to the free list.
9725 * @param[in] mc Cursor on the DB to free.
9726 * @param[in] subs non-Zero to check for sub-DBs in this DB.
9727 * @return 0 on success, non-zero on failure.
9730 mdb_drop0(MDB_cursor *mc, int subs)
9734 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
9735 if (rc == MDB_SUCCESS) {
9736 MDB_txn *txn = mc->mc_txn;
9741 /* DUPSORT sub-DBs have no ovpages/DBs. Omit scanning leaves.
9742 * This also avoids any P_LEAF2 pages, which have no nodes.
9743 * Also if the DB doesn't have sub-DBs and has no overflow
9744 * pages, omit scanning leaves.
9746 if ((mc->mc_flags & C_SUB) ||
9747 (!subs && !mc->mc_db->md_overflow_pages))
9750 mdb_cursor_copy(mc, &mx);
9751 while (mc->mc_snum > 0) {
9752 MDB_page *mp = mc->mc_pg[mc->mc_top];
9753 unsigned n = NUMKEYS(mp);
9755 for (i=0; i<n; i++) {
9756 ni = NODEPTR(mp, i);
9757 if (ni->mn_flags & F_BIGDATA) {
9760 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9761 rc = mdb_page_get(mc, pg, &omp, NULL);
9764 mdb_cassert(mc, IS_OVERFLOW(omp));
9765 rc = mdb_midl_append_range(&txn->mt_free_pgs,
9769 mc->mc_db->md_overflow_pages -= omp->mp_pages;
9770 if (!mc->mc_db->md_overflow_pages && !subs)
9772 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
9773 mdb_xcursor_init1(mc, ni);
9774 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
9779 if (!subs && !mc->mc_db->md_overflow_pages)
9782 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
9784 for (i=0; i<n; i++) {
9786 ni = NODEPTR(mp, i);
9789 mdb_midl_xappend(txn->mt_free_pgs, pg);
9794 mc->mc_ki[mc->mc_top] = i;
9795 rc = mdb_cursor_sibling(mc, 1);
9797 if (rc != MDB_NOTFOUND)
9799 /* no more siblings, go back to beginning
9800 * of previous level.
9805 for (i=1; i<mc->mc_snum; i++) {
9807 mc->mc_pg[i] = mx.mc_pg[i];
9812 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
9815 txn->mt_flags |= MDB_TXN_ERROR;
9816 } else if (rc == MDB_NOTFOUND) {
9819 mc->mc_flags &= ~C_INITIALIZED;
9823 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
9825 MDB_cursor *mc, *m2;
9828 if ((unsigned)del > 1 || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9831 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
9834 if (TXN_DBI_CHANGED(txn, dbi))
9837 rc = mdb_cursor_open(txn, dbi, &mc);
9841 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
9842 /* Invalidate the dropped DB's cursors */
9843 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
9844 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
9848 /* Can't delete the main DB */
9849 if (del && dbi >= CORE_DBS) {
9850 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, F_SUBDATA);
9852 txn->mt_dbflags[dbi] = DB_STALE;
9853 mdb_dbi_close(txn->mt_env, dbi);
9855 txn->mt_flags |= MDB_TXN_ERROR;
9858 /* reset the DB record, mark it dirty */
9859 txn->mt_dbflags[dbi] |= DB_DIRTY;
9860 txn->mt_dbs[dbi].md_depth = 0;
9861 txn->mt_dbs[dbi].md_branch_pages = 0;
9862 txn->mt_dbs[dbi].md_leaf_pages = 0;
9863 txn->mt_dbs[dbi].md_overflow_pages = 0;
9864 txn->mt_dbs[dbi].md_entries = 0;
9865 txn->mt_dbs[dbi].md_root = P_INVALID;
9867 txn->mt_flags |= MDB_TXN_DIRTY;
9870 mdb_cursor_close(mc);
9874 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9876 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9879 txn->mt_dbxs[dbi].md_cmp = cmp;
9883 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9885 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9888 txn->mt_dbxs[dbi].md_dcmp = cmp;
9892 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
9894 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9897 txn->mt_dbxs[dbi].md_rel = rel;
9901 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
9903 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9906 txn->mt_dbxs[dbi].md_relctx = ctx;
9911 mdb_env_get_maxkeysize(MDB_env *env)
9913 return ENV_MAXKEY(env);
9917 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
9919 unsigned int i, rdrs;
9922 int rc = 0, first = 1;
9926 if (!env->me_txns) {
9927 return func("(no reader locks)\n", ctx);
9929 rdrs = env->me_txns->mti_numreaders;
9930 mr = env->me_txns->mti_readers;
9931 for (i=0; i<rdrs; i++) {
9933 txnid_t txnid = mr[i].mr_txnid;
9934 sprintf(buf, txnid == (txnid_t)-1 ?
9935 "%10d %"Z"x -\n" : "%10d %"Z"x %"Z"u\n",
9936 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
9939 rc = func(" pid thread txnid\n", ctx);
9943 rc = func(buf, ctx);
9949 rc = func("(no active readers)\n", ctx);
9954 /** Insert pid into list if not already present.
9955 * return -1 if already present.
9958 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
9960 /* binary search of pid in list */
9962 unsigned cursor = 1;
9964 unsigned n = ids[0];
9967 unsigned pivot = n >> 1;
9968 cursor = base + pivot + 1;
9969 val = pid - ids[cursor];
9974 } else if ( val > 0 ) {
9979 /* found, so it's a duplicate */
9988 for (n = ids[0]; n > cursor; n--)
9995 mdb_reader_check(MDB_env *env, int *dead)
10001 return env->me_txns ? mdb_reader_check0(env, 0, dead) : MDB_SUCCESS;
10004 /** As #mdb_reader_check(). rlocked = <caller locked the reader mutex>. */
10006 mdb_reader_check0(MDB_env *env, int rlocked, int *dead)
10008 mdb_mutexref_t rmutex = rlocked ? NULL : env->me_rmutex;
10009 unsigned int i, j, rdrs;
10011 MDB_PID_T *pids, pid;
10012 int rc = MDB_SUCCESS, count = 0;
10014 rdrs = env->me_txns->mti_numreaders;
10015 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
10019 mr = env->me_txns->mti_readers;
10020 for (i=0; i<rdrs; i++) {
10021 pid = mr[i].mr_pid;
10022 if (pid && pid != env->me_pid) {
10023 if (mdb_pid_insert(pids, pid) == 0) {
10024 if (!mdb_reader_pid(env, Pidcheck, pid)) {
10025 /* Stale reader found */
10028 if ((rc = LOCK_MUTEX0(rmutex)) != 0) {
10029 if ((rc = mdb_mutex_failed(env, rmutex, rc)))
10031 rdrs = 0; /* the above checked all readers */
10033 /* Recheck, a new process may have reused pid */
10034 if (mdb_reader_pid(env, Pidcheck, pid))
10038 for (; j<rdrs; j++)
10039 if (mr[j].mr_pid == pid) {
10040 DPRINTF(("clear stale reader pid %u txn %"Z"d",
10041 (unsigned) pid, mr[j].mr_txnid));
10046 UNLOCK_MUTEX(rmutex);
10057 #ifdef MDB_ROBUST_SUPPORTED
10058 /** Handle #LOCK_MUTEX0() failure.
10059 * Try to repair the lock file if the mutex owner died.
10060 * @param[in] env the environment handle
10061 * @param[in] mutex LOCK_MUTEX0() mutex
10062 * @param[in] rc LOCK_MUTEX0() error (nonzero)
10063 * @return 0 on success with the mutex locked, or an error code on failure.
10066 mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc)
10071 if (rc == MDB_OWNERDEAD) {
10072 /* We own the mutex. Clean up after dead previous owner. */
10074 rlocked = (mutex == env->me_rmutex);
10076 /* Keep mti_txnid updated, otherwise next writer can
10077 * overwrite data which latest meta page refers to.
10079 meta = mdb_env_pick_meta(env);
10080 env->me_txns->mti_txnid = meta->mm_txnid;
10081 /* env is hosed if the dead thread was ours */
10083 env->me_flags |= MDB_FATAL_ERROR;
10084 env->me_txn = NULL;
10088 DPRINTF(("%cmutex owner died, %s", (rlocked ? 'r' : 'w'),
10089 (rc ? "this process' env is hosed" : "recovering")));
10090 rc2 = mdb_reader_check0(env, rlocked, NULL);
10092 rc2 = mdb_mutex_consistent(mutex);
10093 if (rc || (rc = rc2)) {
10094 DPRINTF(("LOCK_MUTEX recovery failed, %s", mdb_strerror(rc)));
10095 UNLOCK_MUTEX(mutex);
10101 DPRINTF(("LOCK_MUTEX failed, %s", mdb_strerror(rc)));
10106 #endif /* MDB_ROBUST_SUPPORTED */
10109 #if defined(_WIN32)
10110 static int utf8_to_utf16(const char *src, int srcsize, wchar_t **dst, int *dstsize)
10114 need = MultiByteToWideChar(CP_UTF8, 0, src, srcsize, NULL, 0);
10115 if (need == 0xFFFD)
10119 result = malloc(sizeof(wchar_t) * need);
10122 MultiByteToWideChar(CP_UTF8, 0, src, srcsize, result, need);
10128 #endif /* defined(_WIN32) */