2 * @brief Lightning memory-mapped database library
4 * A Btree-based database management library modeled loosely on the
5 * BerkeleyDB API, but much simplified.
8 * Copyright 2011-2015 Howard Chu, Symas Corp.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted only as authorized by the OpenLDAP
15 * A copy of this license is available in the file LICENSE in the
16 * top-level directory of the distribution or, alternatively, at
17 * <http://www.OpenLDAP.org/license.html>.
19 * This code is derived from btree.c written by Martin Hedenfalk.
21 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
23 * Permission to use, copy, modify, and distribute this software for any
24 * purpose with or without fee is hereby granted, provided that the above
25 * copyright notice and this permission notice appear in all copies.
27 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
28 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
29 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
30 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
31 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
32 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
33 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
41 /** getpid() returns int; MinGW defines pid_t but MinGW64 typedefs it
42 * as int64 which is wrong. MSVC doesn't define it at all, so just
46 #define MDB_THR_T DWORD
47 #include <sys/types.h>
50 # include <sys/param.h>
52 # define LITTLE_ENDIAN 1234
53 # define BIG_ENDIAN 4321
54 # define BYTE_ORDER LITTLE_ENDIAN
56 # define SSIZE_MAX INT_MAX
60 #include <sys/types.h>
62 #define MDB_PID_T pid_t
63 #define MDB_THR_T pthread_t
64 #include <sys/param.h>
67 #ifdef HAVE_SYS_FILE_H
73 #if defined(__mips) && defined(__linux)
74 /* MIPS has cache coherency issues, requires explicit cache control */
75 #include <asm/cachectl.h>
76 extern int cacheflush(char *addr, int nbytes, int cache);
77 #define CACHEFLUSH(addr, bytes, cache) cacheflush(addr, bytes, cache)
79 #define CACHEFLUSH(addr, bytes, cache)
82 #if defined(__linux) && !defined(MDB_FDATASYNC_WORKS)
83 /** fdatasync is broken on ext3/ext4fs on older kernels, see
84 * description in #mdb_env_open2 comments. You can safely
85 * define MDB_FDATASYNC_WORKS if this code will only be run
86 * on kernels 3.6 and newer.
88 #define BROKEN_FDATASYNC
102 typedef SSIZE_T ssize_t;
107 #if defined(__sun) || defined(ANDROID)
108 /* Most platforms have posix_memalign, older may only have memalign */
109 #define HAVE_MEMALIGN 1
113 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
114 #include <netinet/in.h>
115 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
118 #if defined(__APPLE__) || defined (BSD)
119 # if !(defined(MDB_USE_POSIX_MUTEX) || defined(MDB_USE_POSIX_SEM))
120 # define MDB_USE_SYSV_SEM 1
122 # define MDB_FDATASYNC fsync
123 #elif defined(ANDROID)
124 # define MDB_FDATASYNC fsync
129 #ifdef MDB_USE_POSIX_SEM
130 # define MDB_USE_HASH 1
131 #include <semaphore.h>
132 #elif defined(MDB_USE_SYSV_SEM)
135 #ifdef _SEM_SEMUN_UNDEFINED
138 struct semid_ds *buf;
139 unsigned short *array;
141 #endif /* _SEM_SEMUN_UNDEFINED */
143 #define MDB_USE_POSIX_MUTEX 1
144 #endif /* MDB_USE_POSIX_SEM */
147 #if defined(_WIN32) + defined(MDB_USE_POSIX_SEM) + defined(MDB_USE_SYSV_SEM) \
148 + defined(MDB_USE_POSIX_MUTEX) != 1
149 # error "Ambiguous shared-lock implementation"
153 #include <valgrind/memcheck.h>
154 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
155 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
156 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
157 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
158 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
160 #define VGMEMP_CREATE(h,r,z)
161 #define VGMEMP_ALLOC(h,a,s)
162 #define VGMEMP_FREE(h,a)
163 #define VGMEMP_DESTROY(h)
164 #define VGMEMP_DEFINED(a,s)
168 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
169 /* Solaris just defines one or the other */
170 # define LITTLE_ENDIAN 1234
171 # define BIG_ENDIAN 4321
172 # ifdef _LITTLE_ENDIAN
173 # define BYTE_ORDER LITTLE_ENDIAN
175 # define BYTE_ORDER BIG_ENDIAN
178 # define BYTE_ORDER __BYTE_ORDER
182 #ifndef LITTLE_ENDIAN
183 #define LITTLE_ENDIAN __LITTLE_ENDIAN
186 #define BIG_ENDIAN __BIG_ENDIAN
189 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
190 #define MISALIGNED_OK 1
196 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
197 # error "Unknown or unsupported endianness (BYTE_ORDER)"
198 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
199 # error "Two's complement, reasonably sized integer types, please"
203 /** Put infrequently used env functions in separate section */
205 # define ESECT __attribute__ ((section("__TEXT,text_env")))
207 # define ESECT __attribute__ ((section("text_env")))
214 #define CALL_CONV WINAPI
219 /** @defgroup internal LMDB Internals
222 /** @defgroup compat Compatibility Macros
223 * A bunch of macros to minimize the amount of platform-specific ifdefs
224 * needed throughout the rest of the code. When the features this library
225 * needs are similar enough to POSIX to be hidden in a one-or-two line
226 * replacement, this macro approach is used.
230 /** Features under development */
235 /** Wrapper around __func__, which is a C99 feature */
236 #if __STDC_VERSION__ >= 199901L
237 # define mdb_func_ __func__
238 #elif __GNUC__ >= 2 || _MSC_VER >= 1300
239 # define mdb_func_ __FUNCTION__
241 /* If a debug message says <mdb_unknown>(), update the #if statements above */
242 # define mdb_func_ "<mdb_unknown>"
245 /* Internal error codes, not exposed outside liblmdb */
246 #define MDB_NO_ROOT (MDB_LAST_ERRCODE + 10)
248 #define MDB_OWNERDEAD ((int) WAIT_ABANDONED)
249 #elif defined MDB_USE_SYSV_SEM
250 #define MDB_OWNERDEAD (MDB_LAST_ERRCODE + 11)
251 #elif defined(MDB_USE_POSIX_MUTEX) && defined(EOWNERDEAD)
252 #define MDB_OWNERDEAD EOWNERDEAD /**< #LOCK_MUTEX0() result if dead owner */
256 #define GLIBC_VER ((__GLIBC__ << 16 )| __GLIBC_MINOR__)
258 /** Some platforms define the EOWNERDEAD error code
259 * even though they don't support Robust Mutexes.
260 * Compile with -DMDB_USE_ROBUST=0, or use some other
261 * mechanism like -DMDB_USE_SYSV_SEM instead of
262 * -DMDB_USE_POSIX_MUTEX. (SysV semaphores are
263 * also Robust, but some systems don't support them
266 #ifndef MDB_USE_ROBUST
267 /* Android currently lacks Robust Mutex support. So does glibc < 2.4. */
268 # if defined(MDB_USE_POSIX_MUTEX) && (defined(ANDROID) || \
269 (defined(__GLIBC__) && GLIBC_VER < 0x020004))
270 # define MDB_USE_ROBUST 0
272 # define MDB_USE_ROBUST 1
273 /* glibc < 2.10 only provided _np API */
274 # if defined(__GLIBC__) && GLIBC_VER < 0x02000a
275 # define PTHREAD_MUTEX_ROBUST PTHREAD_MUTEX_ROBUST_NP
276 # define pthread_mutexattr_setrobust(attr, flag) pthread_mutexattr_setrobust_np(attr, flag)
277 # define pthread_mutex_consistent(mutex) pthread_mutex_consistent_np(mutex)
280 #endif /* MDB_USE_ROBUST */
282 #if defined(MDB_OWNERDEAD) && MDB_USE_ROBUST
283 #define MDB_ROBUST_SUPPORTED 1
287 #define MDB_USE_HASH 1
288 #define MDB_PIDLOCK 0
289 #define THREAD_RET DWORD
290 #define pthread_t HANDLE
291 #define pthread_mutex_t HANDLE
292 #define pthread_cond_t HANDLE
293 typedef HANDLE mdb_mutex_t, mdb_mutexref_t;
294 #define pthread_key_t DWORD
295 #define pthread_self() GetCurrentThreadId()
296 #define pthread_key_create(x,y) \
297 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
298 #define pthread_key_delete(x) TlsFree(x)
299 #define pthread_getspecific(x) TlsGetValue(x)
300 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
301 #define pthread_mutex_unlock(x) ReleaseMutex(*x)
302 #define pthread_mutex_lock(x) WaitForSingleObject(*x, INFINITE)
303 #define pthread_cond_signal(x) SetEvent(*x)
304 #define pthread_cond_wait(cond,mutex) do{SignalObjectAndWait(*mutex, *cond, INFINITE, FALSE); WaitForSingleObject(*mutex, INFINITE);}while(0)
305 #define THREAD_CREATE(thr,start,arg) thr=CreateThread(NULL,0,start,arg,0,NULL)
306 #define THREAD_FINISH(thr) WaitForSingleObject(thr, INFINITE)
307 #define LOCK_MUTEX0(mutex) WaitForSingleObject(mutex, INFINITE)
308 #define UNLOCK_MUTEX(mutex) ReleaseMutex(mutex)
309 #define mdb_mutex_consistent(mutex) 0
310 #define getpid() GetCurrentProcessId()
311 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
312 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
313 #define ErrCode() GetLastError()
314 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
315 #define close(fd) (CloseHandle(fd) ? 0 : -1)
316 #define munmap(ptr,len) UnmapViewOfFile(ptr)
317 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
318 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
320 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
324 #define THREAD_RET void *
325 #define THREAD_CREATE(thr,start,arg) pthread_create(&thr,NULL,start,arg)
326 #define THREAD_FINISH(thr) pthread_join(thr,NULL)
327 #define Z "z" /**< printf format modifier for size_t */
329 /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
330 #define MDB_PIDLOCK 1
332 #ifdef MDB_USE_POSIX_SEM
334 typedef sem_t *mdb_mutex_t, *mdb_mutexref_t;
335 #define LOCK_MUTEX0(mutex) mdb_sem_wait(mutex)
336 #define UNLOCK_MUTEX(mutex) sem_post(mutex)
339 mdb_sem_wait(sem_t *sem)
342 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
346 #elif defined MDB_USE_SYSV_SEM
348 typedef struct mdb_mutex {
352 } mdb_mutex_t[1], *mdb_mutexref_t;
354 #define LOCK_MUTEX0(mutex) mdb_sem_wait(mutex)
355 #define UNLOCK_MUTEX(mutex) do { \
356 struct sembuf sb = { 0, 1, SEM_UNDO }; \
357 sb.sem_num = (mutex)->semnum; \
358 *(mutex)->locked = 0; \
359 semop((mutex)->semid, &sb, 1); \
363 mdb_sem_wait(mdb_mutexref_t sem)
365 int rc, *locked = sem->locked;
366 struct sembuf sb = { 0, -1, SEM_UNDO };
367 sb.sem_num = sem->semnum;
369 if (!semop(sem->semid, &sb, 1)) {
370 rc = *locked ? MDB_OWNERDEAD : MDB_SUCCESS;
374 } while ((rc = errno) == EINTR);
378 #define mdb_mutex_consistent(mutex) 0
380 #else /* MDB_USE_POSIX_MUTEX: */
381 /** Shared mutex/semaphore as it is stored (mdb_mutex_t), and as
382 * local variables keep it (mdb_mutexref_t).
384 * An mdb_mutex_t can be assigned to an mdb_mutexref_t. They can
385 * be the same, or an array[size 1] and a pointer.
388 typedef pthread_mutex_t mdb_mutex_t[1], *mdb_mutexref_t;
390 /** Lock the reader or writer mutex.
391 * Returns 0 or a code to give #mdb_mutex_failed(), as in #LOCK_MUTEX().
393 #define LOCK_MUTEX0(mutex) pthread_mutex_lock(mutex)
394 /** Unlock the reader or writer mutex.
396 #define UNLOCK_MUTEX(mutex) pthread_mutex_unlock(mutex)
397 /** Mark mutex-protected data as repaired, after death of previous owner.
399 #define mdb_mutex_consistent(mutex) pthread_mutex_consistent(mutex)
400 #endif /* MDB_USE_POSIX_SEM || MDB_USE_SYSV_SEM */
402 /** Get the error code for the last failed system function.
404 #define ErrCode() errno
406 /** An abstraction for a file handle.
407 * On POSIX systems file handles are small integers. On Windows
408 * they're opaque pointers.
412 /** A value for an invalid file handle.
413 * Mainly used to initialize file variables and signify that they are
416 #define INVALID_HANDLE_VALUE (-1)
418 /** Get the size of a memory page for the system.
419 * This is the basic size that the platform's memory manager uses, and is
420 * fundamental to the use of memory-mapped files.
422 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
425 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
427 #elif defined(MDB_USE_SYSV_SEM)
428 #define MNAME_LEN (sizeof(int))
430 #define MNAME_LEN (sizeof(pthread_mutex_t))
433 #ifdef MDB_USE_SYSV_SEM
434 #define SYSV_SEM_FLAG 1 /**< SysV sems in lockfile format */
436 #define SYSV_SEM_FLAG 0
441 #ifdef MDB_ROBUST_SUPPORTED
442 /** Lock mutex, handle any error, set rc = result.
443 * Return 0 on success, nonzero (not rc) on error.
445 #define LOCK_MUTEX(rc, env, mutex) \
446 (((rc) = LOCK_MUTEX0(mutex)) && \
447 ((rc) = mdb_mutex_failed(env, mutex, rc)))
448 static int mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc);
450 #define LOCK_MUTEX(rc, env, mutex) ((rc) = LOCK_MUTEX0(mutex))
451 #define mdb_mutex_failed(env, mutex, rc) (rc)
455 /** A flag for opening a file and requesting synchronous data writes.
456 * This is only used when writing a meta page. It's not strictly needed;
457 * we could just do a normal write and then immediately perform a flush.
458 * But if this flag is available it saves us an extra system call.
460 * @note If O_DSYNC is undefined but exists in /usr/include,
461 * preferably set some compiler flag to get the definition.
465 # define MDB_DSYNC O_DSYNC
467 # define MDB_DSYNC O_SYNC
472 /** Function for flushing the data of a file. Define this to fsync
473 * if fdatasync() is not supported.
475 #ifndef MDB_FDATASYNC
476 # define MDB_FDATASYNC fdatasync
480 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
491 /** A page number in the database.
492 * Note that 64 bit page numbers are overkill, since pages themselves
493 * already represent 12-13 bits of addressable memory, and the OS will
494 * always limit applications to a maximum of 63 bits of address space.
496 * @note In the #MDB_node structure, we only store 48 bits of this value,
497 * which thus limits us to only 60 bits of addressable data.
499 typedef MDB_ID pgno_t;
501 /** A transaction ID.
502 * See struct MDB_txn.mt_txnid for details.
504 typedef MDB_ID txnid_t;
506 /** @defgroup debug Debug Macros
510 /** Enable debug output. Needs variable argument macros (a C99 feature).
511 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
512 * read from and written to the database (used for free space management).
518 static int mdb_debug;
519 static txnid_t mdb_debug_start;
521 /** Print a debug message with printf formatting.
522 * Requires double parenthesis around 2 or more args.
524 # define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
525 # define DPRINTF0(fmt, ...) \
526 fprintf(stderr, "%s:%d " fmt "\n", mdb_func_, __LINE__, __VA_ARGS__)
528 # define DPRINTF(args) ((void) 0)
530 /** Print a debug string.
531 * The string is printed literally, with no format processing.
533 #define DPUTS(arg) DPRINTF(("%s", arg))
534 /** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
536 (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
539 /** @brief The maximum size of a database page.
541 * It is 32k or 64k, since value-PAGEBASE must fit in
542 * #MDB_page.%mp_upper.
544 * LMDB will use database pages < OS pages if needed.
545 * That causes more I/O in write transactions: The OS must
546 * know (read) the whole page before writing a partial page.
548 * Note that we don't currently support Huge pages. On Linux,
549 * regular data files cannot use Huge pages, and in general
550 * Huge pages aren't actually pageable. We rely on the OS
551 * demand-pager to read our data and page it out when memory
552 * pressure from other processes is high. So until OSs have
553 * actual paging support for Huge pages, they're not viable.
555 #define MAX_PAGESIZE (PAGEBASE ? 0x10000 : 0x8000)
557 /** The minimum number of keys required in a database page.
558 * Setting this to a larger value will place a smaller bound on the
559 * maximum size of a data item. Data items larger than this size will
560 * be pushed into overflow pages instead of being stored directly in
561 * the B-tree node. This value used to default to 4. With a page size
562 * of 4096 bytes that meant that any item larger than 1024 bytes would
563 * go into an overflow page. That also meant that on average 2-3KB of
564 * each overflow page was wasted space. The value cannot be lower than
565 * 2 because then there would no longer be a tree structure. With this
566 * value, items larger than 2KB will go into overflow pages, and on
567 * average only 1KB will be wasted.
569 #define MDB_MINKEYS 2
571 /** A stamp that identifies a file as an LMDB file.
572 * There's nothing special about this value other than that it is easily
573 * recognizable, and it will reflect any byte order mismatches.
575 #define MDB_MAGIC 0xBEEFC0DE
577 /** The version number for a database's datafile format. */
578 #define MDB_DATA_VERSION ((MDB_DEVEL) ? 999 : 1)
579 /** The version number for a database's lockfile format. */
580 #define MDB_LOCK_VERSION ((MDB_DEVEL) ? 999 : 1)
582 /** @brief The max size of a key we can write, or 0 for computed max.
584 * This macro should normally be left alone or set to 0.
585 * Note that a database with big keys or dupsort data cannot be
586 * reliably modified by a liblmdb which uses a smaller max.
587 * The default is 511 for backwards compat, or 0 when #MDB_DEVEL.
589 * Other values are allowed, for backwards compat. However:
590 * A value bigger than the computed max can break if you do not
591 * know what you are doing, and liblmdb <= 0.9.10 can break when
592 * modifying a DB with keys/dupsort data bigger than its max.
594 * Data items in an #MDB_DUPSORT database are also limited to
595 * this size, since they're actually keys of a sub-DB. Keys and
596 * #MDB_DUPSORT data items must fit on a node in a regular page.
598 #ifndef MDB_MAXKEYSIZE
599 #define MDB_MAXKEYSIZE ((MDB_DEVEL) ? 0 : 511)
602 /** The maximum size of a key we can write to the environment. */
604 #define ENV_MAXKEY(env) (MDB_MAXKEYSIZE)
606 #define ENV_MAXKEY(env) ((env)->me_maxkey)
609 /** @brief The maximum size of a data item.
611 * We only store a 32 bit value for node sizes.
613 #define MAXDATASIZE 0xffffffffUL
616 /** Key size which fits in a #DKBUF.
619 #define DKBUF_MAXKEYSIZE ((MDB_MAXKEYSIZE) > 0 ? (MDB_MAXKEYSIZE) : 511)
622 * This is used for printing a hex dump of a key's contents.
624 #define DKBUF char kbuf[DKBUF_MAXKEYSIZE*2+1]
625 /** Display a key in hex.
627 * Invoke a function to display a key in hex.
629 #define DKEY(x) mdb_dkey(x, kbuf)
635 /** An invalid page number.
636 * Mainly used to denote an empty tree.
638 #define P_INVALID (~(pgno_t)0)
640 /** Test if the flags \b f are set in a flag word \b w. */
641 #define F_ISSET(w, f) (((w) & (f)) == (f))
643 /** Round \b n up to an even number. */
644 #define EVEN(n) (((n) + 1U) & -2) /* sign-extending -2 to match n+1U */
646 /** Used for offsets within a single page.
647 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
650 typedef uint16_t indx_t;
652 /** Default size of memory map.
653 * This is certainly too small for any actual applications. Apps should always set
654 * the size explicitly using #mdb_env_set_mapsize().
656 #define DEFAULT_MAPSIZE 1048576
658 /** @defgroup readers Reader Lock Table
659 * Readers don't acquire any locks for their data access. Instead, they
660 * simply record their transaction ID in the reader table. The reader
661 * mutex is needed just to find an empty slot in the reader table. The
662 * slot's address is saved in thread-specific data so that subsequent read
663 * transactions started by the same thread need no further locking to proceed.
665 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
667 * No reader table is used if the database is on a read-only filesystem, or
668 * if #MDB_NOLOCK is set.
670 * Since the database uses multi-version concurrency control, readers don't
671 * actually need any locking. This table is used to keep track of which
672 * readers are using data from which old transactions, so that we'll know
673 * when a particular old transaction is no longer in use. Old transactions
674 * that have discarded any data pages can then have those pages reclaimed
675 * for use by a later write transaction.
677 * The lock table is constructed such that reader slots are aligned with the
678 * processor's cache line size. Any slot is only ever used by one thread.
679 * This alignment guarantees that there will be no contention or cache
680 * thrashing as threads update their own slot info, and also eliminates
681 * any need for locking when accessing a slot.
683 * A writer thread will scan every slot in the table to determine the oldest
684 * outstanding reader transaction. Any freed pages older than this will be
685 * reclaimed by the writer. The writer doesn't use any locks when scanning
686 * this table. This means that there's no guarantee that the writer will
687 * see the most up-to-date reader info, but that's not required for correct
688 * operation - all we need is to know the upper bound on the oldest reader,
689 * we don't care at all about the newest reader. So the only consequence of
690 * reading stale information here is that old pages might hang around a
691 * while longer before being reclaimed. That's actually good anyway, because
692 * the longer we delay reclaiming old pages, the more likely it is that a
693 * string of contiguous pages can be found after coalescing old pages from
694 * many old transactions together.
697 /** Number of slots in the reader table.
698 * This value was chosen somewhat arbitrarily. 126 readers plus a
699 * couple mutexes fit exactly into 8KB on my development machine.
700 * Applications should set the table size using #mdb_env_set_maxreaders().
702 #define DEFAULT_READERS 126
704 /** The size of a CPU cache line in bytes. We want our lock structures
705 * aligned to this size to avoid false cache line sharing in the
707 * This value works for most CPUs. For Itanium this should be 128.
713 /** The information we store in a single slot of the reader table.
714 * In addition to a transaction ID, we also record the process and
715 * thread ID that owns a slot, so that we can detect stale information,
716 * e.g. threads or processes that went away without cleaning up.
717 * @note We currently don't check for stale records. We simply re-init
718 * the table when we know that we're the only process opening the
721 typedef struct MDB_rxbody {
722 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
723 * Multiple readers that start at the same time will probably have the
724 * same ID here. Again, it's not important to exclude them from
725 * anything; all we need to know is which version of the DB they
726 * started from so we can avoid overwriting any data used in that
727 * particular version.
729 volatile txnid_t mrb_txnid;
730 /** The process ID of the process owning this reader txn. */
731 volatile MDB_PID_T mrb_pid;
732 /** The thread ID of the thread owning this txn. */
733 volatile MDB_THR_T mrb_tid;
736 /** The actual reader record, with cacheline padding. */
737 typedef struct MDB_reader {
740 /** shorthand for mrb_txnid */
741 #define mr_txnid mru.mrx.mrb_txnid
742 #define mr_pid mru.mrx.mrb_pid
743 #define mr_tid mru.mrx.mrb_tid
744 /** cache line alignment */
745 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
749 /** The header for the reader table.
750 * The table resides in a memory-mapped file. (This is a different file
751 * than is used for the main database.)
753 * For POSIX the actual mutexes reside in the shared memory of this
754 * mapped file. On Windows, mutexes are named objects allocated by the
755 * kernel; we store the mutex names in this mapped file so that other
756 * processes can grab them. This same approach is also used on
757 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
758 * process-shared POSIX mutexes. For these cases where a named object
759 * is used, the object name is derived from a 64 bit FNV hash of the
760 * environment pathname. As such, naming collisions are extremely
761 * unlikely. If a collision occurs, the results are unpredictable.
763 typedef struct MDB_txbody {
764 /** Stamp identifying this as an LMDB file. It must be set
767 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
769 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
770 char mtb_rmname[MNAME_LEN];
771 #elif defined(MDB_USE_SYSV_SEM)
775 /** Mutex protecting access to this table.
776 * This is the reader table lock used with LOCK_MUTEX().
778 mdb_mutex_t mtb_rmutex;
780 /** The ID of the last transaction committed to the database.
781 * This is recorded here only for convenience; the value can always
782 * be determined by reading the main database meta pages.
784 volatile txnid_t mtb_txnid;
785 /** The number of slots that have been used in the reader table.
786 * This always records the maximum count, it is not decremented
787 * when readers release their slots.
789 volatile unsigned mtb_numreaders;
792 /** The actual reader table definition. */
793 typedef struct MDB_txninfo {
796 #define mti_magic mt1.mtb.mtb_magic
797 #define mti_format mt1.mtb.mtb_format
798 #define mti_rmutex mt1.mtb.mtb_rmutex
799 #define mti_rmname mt1.mtb.mtb_rmname
800 #define mti_txnid mt1.mtb.mtb_txnid
801 #define mti_numreaders mt1.mtb.mtb_numreaders
802 #ifdef MDB_USE_SYSV_SEM
803 #define mti_semid mt1.mtb.mtb_semid
804 #define mti_rlocked mt1.mtb.mtb_rlocked
806 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
809 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
810 char mt2_wmname[MNAME_LEN];
811 #define mti_wmname mt2.mt2_wmname
812 #elif defined MDB_USE_SYSV_SEM
814 #define mti_wlocked mt2.mt2_wlocked
816 mdb_mutex_t mt2_wmutex;
817 #define mti_wmutex mt2.mt2_wmutex
819 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
821 MDB_reader mti_readers[1];
824 /** Lockfile format signature: version, features and field layout */
825 #define MDB_LOCK_FORMAT \
827 ((MDB_LOCK_VERSION) \
828 /* Flags which describe functionality */ \
829 + (SYSV_SEM_FLAG << 18) \
830 + (((MDB_PIDLOCK) != 0) << 16)))
833 /** Common header for all page types.
834 * Overflow records occupy a number of contiguous pages with no
835 * headers on any page after the first.
837 typedef struct MDB_page {
838 #define mp_pgno mp_p.p_pgno
839 #define mp_next mp_p.p_next
841 pgno_t p_pgno; /**< page number */
842 struct MDB_page *p_next; /**< for in-memory list of freed pages */
845 /** @defgroup mdb_page Page Flags
847 * Flags for the page headers.
850 #define P_BRANCH 0x01 /**< branch page */
851 #define P_LEAF 0x02 /**< leaf page */
852 #define P_OVERFLOW 0x04 /**< overflow page */
853 #define P_META 0x08 /**< meta page */
854 #define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
855 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
856 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
857 #define P_LOOSE 0x4000 /**< page was dirtied then freed, can be reused */
858 #define P_KEEP 0x8000 /**< leave this page alone during spill */
860 uint16_t mp_flags; /**< @ref mdb_page */
861 #define mp_lower mp_pb.pb.pb_lower
862 #define mp_upper mp_pb.pb.pb_upper
863 #define mp_pages mp_pb.pb_pages
866 indx_t pb_lower; /**< lower bound of free space */
867 indx_t pb_upper; /**< upper bound of free space */
869 uint32_t pb_pages; /**< number of overflow pages */
871 indx_t mp_ptrs[1]; /**< dynamic size */
874 /** Size of the page header, excluding dynamic data at the end */
875 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
877 /** Address of first usable data byte in a page, after the header */
878 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
880 /** ITS#7713, change PAGEBASE to handle 65536 byte pages */
881 #define PAGEBASE ((MDB_DEVEL) ? PAGEHDRSZ : 0)
883 /** Number of nodes on a page */
884 #define NUMKEYS(p) (((p)->mp_lower - (PAGEHDRSZ-PAGEBASE)) >> 1)
886 /** The amount of space remaining in the page */
887 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
889 /** The percentage of space used in the page, in tenths of a percent. */
890 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
891 ((env)->me_psize - PAGEHDRSZ))
892 /** The minimum page fill factor, in tenths of a percent.
893 * Pages emptier than this are candidates for merging.
895 #define FILL_THRESHOLD 250
897 /** Test if a page is a leaf page */
898 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
899 /** Test if a page is a LEAF2 page */
900 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
901 /** Test if a page is a branch page */
902 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
903 /** Test if a page is an overflow page */
904 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
905 /** Test if a page is a sub page */
906 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
908 /** The number of overflow pages needed to store the given size. */
909 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
911 /** Link in #MDB_txn.%mt_loose_pgs list */
912 #define NEXT_LOOSE_PAGE(p) (*(MDB_page **)((p) + 2))
914 /** Header for a single key/data pair within a page.
915 * Used in pages of type #P_BRANCH and #P_LEAF without #P_LEAF2.
916 * We guarantee 2-byte alignment for 'MDB_node's.
918 typedef struct MDB_node {
919 /** lo and hi are used for data size on leaf nodes and for
920 * child pgno on branch nodes. On 64 bit platforms, flags
921 * is also used for pgno. (Branch nodes have no flags).
922 * They are in host byte order in case that lets some
923 * accesses be optimized into a 32-bit word access.
925 #if BYTE_ORDER == LITTLE_ENDIAN
926 unsigned short mn_lo, mn_hi; /**< part of data size or pgno */
928 unsigned short mn_hi, mn_lo;
930 /** @defgroup mdb_node Node Flags
932 * Flags for node headers.
935 #define F_BIGDATA 0x01 /**< data put on overflow page */
936 #define F_SUBDATA 0x02 /**< data is a sub-database */
937 #define F_DUPDATA 0x04 /**< data has duplicates */
939 /** valid flags for #mdb_node_add() */
940 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
943 unsigned short mn_flags; /**< @ref mdb_node */
944 unsigned short mn_ksize; /**< key size */
945 char mn_data[1]; /**< key and data are appended here */
948 /** Size of the node header, excluding dynamic data at the end */
949 #define NODESIZE offsetof(MDB_node, mn_data)
951 /** Bit position of top word in page number, for shifting mn_flags */
952 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
954 /** Size of a node in a branch page with a given key.
955 * This is just the node header plus the key, there is no data.
957 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
959 /** Size of a node in a leaf page with a given key and data.
960 * This is node header plus key plus data size.
962 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
964 /** Address of node \b i in page \b p */
965 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i] + PAGEBASE))
967 /** Address of the key for the node */
968 #define NODEKEY(node) (void *)((node)->mn_data)
970 /** Address of the data for a node */
971 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
973 /** Get the page number pointed to by a branch node */
974 #define NODEPGNO(node) \
975 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
976 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
977 /** Set the page number in a branch node */
978 #define SETPGNO(node,pgno) do { \
979 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
980 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
982 /** Get the size of the data in a leaf node */
983 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
984 /** Set the size of the data for a leaf node */
985 #define SETDSZ(node,size) do { \
986 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
987 /** The size of a key in a node */
988 #define NODEKSZ(node) ((node)->mn_ksize)
990 /** Copy a page number from src to dst */
992 #define COPY_PGNO(dst,src) dst = src
994 #if SIZE_MAX > 4294967295UL
995 #define COPY_PGNO(dst,src) do { \
996 unsigned short *s, *d; \
997 s = (unsigned short *)&(src); \
998 d = (unsigned short *)&(dst); \
1005 #define COPY_PGNO(dst,src) do { \
1006 unsigned short *s, *d; \
1007 s = (unsigned short *)&(src); \
1008 d = (unsigned short *)&(dst); \
1014 /** The address of a key in a LEAF2 page.
1015 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
1016 * There are no node headers, keys are stored contiguously.
1018 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
1020 /** Set the \b node's key into \b keyptr, if requested. */
1021 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
1022 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
1024 /** Set the \b node's key into \b key. */
1025 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
1027 /** Information about a single database in the environment. */
1028 typedef struct MDB_db {
1029 uint32_t md_pad; /**< also ksize for LEAF2 pages */
1030 uint16_t md_flags; /**< @ref mdb_dbi_open */
1031 uint16_t md_depth; /**< depth of this tree */
1032 pgno_t md_branch_pages; /**< number of internal pages */
1033 pgno_t md_leaf_pages; /**< number of leaf pages */
1034 pgno_t md_overflow_pages; /**< number of overflow pages */
1035 size_t md_entries; /**< number of data items */
1036 pgno_t md_root; /**< the root page of this tree */
1039 /** mdb_dbi_open flags */
1040 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
1041 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
1042 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
1043 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
1045 /** Handle for the DB used to track free pages. */
1047 /** Handle for the default DB. */
1049 /** Number of DBs in metapage (free and main) - also hardcoded elsewhere */
1052 /** Number of meta pages - also hardcoded elsewhere */
1055 /** Meta page content.
1056 * A meta page is the start point for accessing a database snapshot.
1057 * Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
1059 typedef struct MDB_meta {
1060 /** Stamp identifying this as an LMDB file. It must be set
1063 /** Version number of this file. Must be set to #MDB_DATA_VERSION. */
1064 uint32_t mm_version;
1065 void *mm_address; /**< address for fixed mapping */
1066 size_t mm_mapsize; /**< size of mmap region */
1067 MDB_db mm_dbs[CORE_DBS]; /**< first is free space, 2nd is main db */
1068 /** The size of pages used in this DB */
1069 #define mm_psize mm_dbs[FREE_DBI].md_pad
1070 /** Any persistent environment flags. @ref mdb_env */
1071 #define mm_flags mm_dbs[FREE_DBI].md_flags
1072 pgno_t mm_last_pg; /**< last used page in file */
1073 volatile txnid_t mm_txnid; /**< txnid that committed this page */
1076 /** Buffer for a stack-allocated meta page.
1077 * The members define size and alignment, and silence type
1078 * aliasing warnings. They are not used directly; that could
1079 * mean incorrectly using several union members in parallel.
1081 typedef union MDB_metabuf {
1084 char mm_pad[PAGEHDRSZ];
1089 /** Auxiliary DB info.
1090 * The information here is mostly static/read-only. There is
1091 * only a single copy of this record in the environment.
1093 typedef struct MDB_dbx {
1094 MDB_val md_name; /**< name of the database */
1095 MDB_cmp_func *md_cmp; /**< function for comparing keys */
1096 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
1097 MDB_rel_func *md_rel; /**< user relocate function */
1098 void *md_relctx; /**< user-provided context for md_rel */
1101 /** A database transaction.
1102 * Every operation requires a transaction handle.
1105 MDB_txn *mt_parent; /**< parent of a nested txn */
1106 /** Nested txn under this txn, set together with flag #MDB_TXN_HAS_CHILD */
1108 pgno_t mt_next_pgno; /**< next unallocated page */
1109 /** The ID of this transaction. IDs are integers incrementing from 1.
1110 * Only committed write transactions increment the ID. If a transaction
1111 * aborts, the ID may be re-used by the next writer.
1114 MDB_env *mt_env; /**< the DB environment */
1115 /** The list of pages that became unused during this transaction.
1117 MDB_IDL mt_free_pgs;
1118 /** The list of loose pages that became unused and may be reused
1119 * in this transaction, linked through #NEXT_LOOSE_PAGE(page).
1121 MDB_page *mt_loose_pgs;
1122 /* #Number of loose pages (#mt_loose_pgs) */
1124 /** The sorted list of dirty pages we temporarily wrote to disk
1125 * because the dirty list was full. page numbers in here are
1126 * shifted left by 1, deleted slots have the LSB set.
1128 MDB_IDL mt_spill_pgs;
1130 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
1131 MDB_ID2L dirty_list;
1132 /** For read txns: This thread/txn's reader table slot, or NULL. */
1135 /** Array of records for each DB known in the environment. */
1137 /** Array of MDB_db records for each known DB */
1139 /** Array of sequence numbers for each DB handle */
1140 unsigned int *mt_dbiseqs;
1141 /** @defgroup mt_dbflag Transaction DB Flags
1145 #define DB_DIRTY 0x01 /**< DB was modified or is DUPSORT data */
1146 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
1147 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
1148 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
1149 #define DB_USRVALID 0x10 /**< As #DB_VALID, but not set for #FREE_DBI */
1151 /** In write txns, array of cursors for each DB */
1152 MDB_cursor **mt_cursors;
1153 /** Array of flags for each DB */
1154 unsigned char *mt_dbflags;
1155 /** Number of DB records in use, or 0 when the txn is finished.
1156 * This number only ever increments until the txn finishes; we
1157 * don't decrement it when individual DB handles are closed.
1161 /** @defgroup mdb_txn Transaction Flags
1165 /** #mdb_txn_begin() flags */
1166 #define MDB_TXN_BEGIN_FLAGS (MDB_NOMETASYNC|MDB_NOSYNC|MDB_RDONLY)
1167 #define MDB_TXN_NOMETASYNC MDB_NOMETASYNC /**< don't sync meta for this txn on commit */
1168 #define MDB_TXN_NOSYNC MDB_NOSYNC /**< don't sync this txn on commit */
1169 #define MDB_TXN_RDONLY MDB_RDONLY /**< read-only transaction */
1170 /* internal txn flags */
1171 #define MDB_TXN_WRITEMAP MDB_WRITEMAP /**< copy of #MDB_env flag in writers */
1172 #define MDB_TXN_FINISHED 0x01 /**< txn is finished or never began */
1173 #define MDB_TXN_ERROR 0x02 /**< txn is unusable after an error */
1174 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
1175 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
1176 #define MDB_TXN_HAS_CHILD 0x10 /**< txn has an #MDB_txn.%mt_child */
1177 /** most operations on the txn are currently illegal */
1178 #define MDB_TXN_BLOCKED (MDB_TXN_FINISHED|MDB_TXN_ERROR|MDB_TXN_HAS_CHILD)
1180 unsigned int mt_flags; /**< @ref mdb_txn */
1181 /** #dirty_list room: Array size - \#dirty pages visible to this txn.
1182 * Includes ancestor txns' dirty pages not hidden by other txns'
1183 * dirty/spilled pages. Thus commit(nested txn) has room to merge
1184 * dirty_list into mt_parent after freeing hidden mt_parent pages.
1186 unsigned int mt_dirty_room;
1189 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
1190 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
1191 * raise this on a 64 bit machine.
1193 #define CURSOR_STACK 32
1197 /** Cursors are used for all DB operations.
1198 * A cursor holds a path of (page pointer, key index) from the DB
1199 * root to a position in the DB, plus other state. #MDB_DUPSORT
1200 * cursors include an xcursor to the current data item. Write txns
1201 * track their cursors and keep them up to date when data moves.
1202 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
1203 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
1206 /** Next cursor on this DB in this txn */
1207 MDB_cursor *mc_next;
1208 /** Backup of the original cursor if this cursor is a shadow */
1209 MDB_cursor *mc_backup;
1210 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
1211 struct MDB_xcursor *mc_xcursor;
1212 /** The transaction that owns this cursor */
1214 /** The database handle this cursor operates on */
1216 /** The database record for this cursor */
1218 /** The database auxiliary record for this cursor */
1220 /** The @ref mt_dbflag for this database */
1221 unsigned char *mc_dbflag;
1222 unsigned short mc_snum; /**< number of pushed pages */
1223 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
1224 /** @defgroup mdb_cursor Cursor Flags
1226 * Cursor state flags.
1229 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
1230 #define C_EOF 0x02 /**< No more data */
1231 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
1232 #define C_DEL 0x08 /**< last op was a cursor_del */
1233 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
1235 unsigned int mc_flags; /**< @ref mdb_cursor */
1236 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
1237 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
1240 /** Context for sorted-dup records.
1241 * We could have gone to a fully recursive design, with arbitrarily
1242 * deep nesting of sub-databases. But for now we only handle these
1243 * levels - main DB, optional sub-DB, sorted-duplicate DB.
1245 typedef struct MDB_xcursor {
1246 /** A sub-cursor for traversing the Dup DB */
1247 MDB_cursor mx_cursor;
1248 /** The database record for this Dup DB */
1250 /** The auxiliary DB record for this Dup DB */
1252 /** The @ref mt_dbflag for this Dup DB */
1253 unsigned char mx_dbflag;
1256 /** State of FreeDB old pages, stored in the MDB_env */
1257 typedef struct MDB_pgstate {
1258 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1259 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1262 /** The database environment. */
1264 HANDLE me_fd; /**< The main data file */
1265 HANDLE me_lfd; /**< The lock file */
1266 HANDLE me_mfd; /**< just for writing the meta pages */
1267 /** Failed to update the meta page. Probably an I/O error. */
1268 #define MDB_FATAL_ERROR 0x80000000U
1269 /** Some fields are initialized. */
1270 #define MDB_ENV_ACTIVE 0x20000000U
1271 /** me_txkey is set */
1272 #define MDB_ENV_TXKEY 0x10000000U
1273 /** fdatasync is unreliable */
1274 #define MDB_FSYNCONLY 0x08000000U
1275 uint32_t me_flags; /**< @ref mdb_env */
1276 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1277 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1278 unsigned int me_maxreaders; /**< size of the reader table */
1279 /** Max #MDB_txninfo.%mti_numreaders of interest to #mdb_env_close() */
1280 volatile int me_close_readers;
1281 MDB_dbi me_numdbs; /**< number of DBs opened */
1282 MDB_dbi me_maxdbs; /**< size of the DB table */
1283 MDB_PID_T me_pid; /**< process ID of this env */
1284 char *me_path; /**< path to the DB files */
1285 char *me_map; /**< the memory map of the data file */
1286 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1287 MDB_meta *me_metas[NUM_METAS]; /**< pointers to the two meta pages */
1288 void *me_pbuf; /**< scratch area for DUPSORT put() */
1289 MDB_txn *me_txn; /**< current write transaction */
1290 MDB_txn *me_txn0; /**< prealloc'd write transaction */
1291 size_t me_mapsize; /**< size of the data memory map */
1292 off_t me_size; /**< current file size */
1293 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1294 MDB_dbx *me_dbxs; /**< array of static DB info */
1295 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1296 unsigned int *me_dbiseqs; /**< array of dbi sequence numbers */
1297 pthread_key_t me_txkey; /**< thread-key for readers */
1298 txnid_t me_pgoldest; /**< ID of oldest reader last time we looked */
1299 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1300 # define me_pglast me_pgstate.mf_pglast
1301 # define me_pghead me_pgstate.mf_pghead
1302 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1303 /** IDL of pages that became unused in a write txn */
1304 MDB_IDL me_free_pgs;
1305 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1306 MDB_ID2L me_dirty_list;
1307 /** Max number of freelist items that can fit in a single overflow page */
1309 /** Max size of a node on a page */
1310 unsigned int me_nodemax;
1311 #if !(MDB_MAXKEYSIZE)
1312 unsigned int me_maxkey; /**< max size of a key */
1314 int me_live_reader; /**< have liveness lock in reader table */
1316 int me_pidquery; /**< Used in OpenProcess */
1318 #ifdef MDB_USE_POSIX_MUTEX /* Posix mutexes reside in shared mem */
1319 # define me_rmutex me_txns->mti_rmutex /**< Shared reader lock */
1320 # define me_wmutex me_txns->mti_wmutex /**< Shared writer lock */
1322 mdb_mutex_t me_rmutex;
1323 mdb_mutex_t me_wmutex;
1325 void *me_userctx; /**< User-settable context */
1326 MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
1329 /** Nested transaction */
1330 typedef struct MDB_ntxn {
1331 MDB_txn mnt_txn; /**< the transaction */
1332 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1335 /** max number of pages to commit in one writev() call */
1336 #define MDB_COMMIT_PAGES 64
1337 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1338 #undef MDB_COMMIT_PAGES
1339 #define MDB_COMMIT_PAGES IOV_MAX
1342 /** max bytes to write in one call */
1343 #define MAX_WRITE (0x80000000U >> (sizeof(ssize_t) == 4))
1345 /** Check \b txn and \b dbi arguments to a function */
1346 #define TXN_DBI_EXIST(txn, dbi, validity) \
1347 ((txn) && (dbi)<(txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & (validity)))
1349 /** Check for misused \b dbi handles */
1350 #define TXN_DBI_CHANGED(txn, dbi) \
1351 ((txn)->mt_dbiseqs[dbi] != (txn)->mt_env->me_dbiseqs[dbi])
1353 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1354 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1355 static int mdb_page_touch(MDB_cursor *mc);
1357 #define MDB_END_NAMES {"committed", "empty-commit", "abort", "reset", \
1358 "reset-tmp", "fail-begin", "fail-beginchild"}
1360 /* mdb_txn_end operation number, for logging */
1361 MDB_END_COMMITTED, MDB_END_EMPTY_COMMIT, MDB_END_ABORT, MDB_END_RESET,
1362 MDB_END_RESET_TMP, MDB_END_FAIL_BEGIN, MDB_END_FAIL_BEGINCHILD
1364 #define MDB_END_OPMASK 0x0F /**< mask for #mdb_txn_end() operation number */
1365 #define MDB_END_UPDATE 0x10 /**< update env state (DBIs) */
1366 #define MDB_END_FREE 0x20 /**< free txn unless it is #MDB_env.%me_txn0 */
1367 #define MDB_END_SLOT MDB_NOTLS /**< release any reader slot if #MDB_NOTLS */
1368 static void mdb_txn_end(MDB_txn *txn, unsigned mode);
1370 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp, int *lvl);
1371 static int mdb_page_search_root(MDB_cursor *mc,
1372 MDB_val *key, int modify);
1373 #define MDB_PS_MODIFY 1
1374 #define MDB_PS_ROOTONLY 2
1375 #define MDB_PS_FIRST 4
1376 #define MDB_PS_LAST 8
1377 static int mdb_page_search(MDB_cursor *mc,
1378 MDB_val *key, int flags);
1379 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1381 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1382 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1383 pgno_t newpgno, unsigned int nflags);
1385 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1386 static MDB_meta *mdb_env_pick_meta(const MDB_env *env);
1387 static int mdb_env_write_meta(MDB_txn *txn);
1388 #ifdef MDB_USE_POSIX_MUTEX /* Drop unused excl arg */
1389 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1391 static void mdb_env_close0(MDB_env *env, int excl);
1393 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1394 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1395 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1396 static void mdb_node_del(MDB_cursor *mc, int ksize);
1397 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1398 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft);
1399 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1400 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1401 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1403 static int mdb_rebalance(MDB_cursor *mc);
1404 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1406 static void mdb_cursor_pop(MDB_cursor *mc);
1407 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1409 static int mdb_cursor_del0(MDB_cursor *mc);
1410 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
1411 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1412 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1413 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1414 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1416 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1417 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1419 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1420 static void mdb_xcursor_init0(MDB_cursor *mc);
1421 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1422 static void mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int force);
1424 static int mdb_drop0(MDB_cursor *mc, int subs);
1425 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1426 static int mdb_reader_check0(MDB_env *env, int rlocked, int *dead);
1429 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1432 /** Compare two items pointing at size_t's of unknown alignment. */
1433 #ifdef MISALIGNED_OK
1434 # define mdb_cmp_clong mdb_cmp_long
1436 # define mdb_cmp_clong mdb_cmp_cint
1440 static SECURITY_DESCRIPTOR mdb_null_sd;
1441 static SECURITY_ATTRIBUTES mdb_all_sa;
1442 static int mdb_sec_inited;
1444 static int utf8_to_utf16(const char *src, int srcsize, wchar_t **dst, int *dstsize);
1447 /** Return the library version info. */
1449 mdb_version(int *major, int *minor, int *patch)
1451 if (major) *major = MDB_VERSION_MAJOR;
1452 if (minor) *minor = MDB_VERSION_MINOR;
1453 if (patch) *patch = MDB_VERSION_PATCH;
1454 return MDB_VERSION_STRING;
1457 /** Table of descriptions for LMDB @ref errors */
1458 static char *const mdb_errstr[] = {
1459 "MDB_KEYEXIST: Key/data pair already exists",
1460 "MDB_NOTFOUND: No matching key/data pair found",
1461 "MDB_PAGE_NOTFOUND: Requested page not found",
1462 "MDB_CORRUPTED: Located page was wrong type",
1463 "MDB_PANIC: Update of meta page failed or environment had fatal error",
1464 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1465 "MDB_INVALID: File is not an LMDB file",
1466 "MDB_MAP_FULL: Environment mapsize limit reached",
1467 "MDB_DBS_FULL: Environment maxdbs limit reached",
1468 "MDB_READERS_FULL: Environment maxreaders limit reached",
1469 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1470 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1471 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1472 "MDB_PAGE_FULL: Internal error - page has no more space",
1473 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1474 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1475 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1476 "MDB_BAD_TXN: Transaction must abort, has a child, or is invalid",
1477 "MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
1478 "MDB_BAD_DBI: The specified DBI handle was closed/changed unexpectedly",
1482 mdb_strerror(int err)
1485 /** HACK: pad 4KB on stack over the buf. Return system msgs in buf.
1486 * This works as long as no function between the call to mdb_strerror
1487 * and the actual use of the message uses more than 4K of stack.
1490 char buf[1024], *ptr = buf;
1494 return ("Successful return: 0");
1496 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1497 i = err - MDB_KEYEXIST;
1498 return mdb_errstr[i];
1502 /* These are the C-runtime error codes we use. The comment indicates
1503 * their numeric value, and the Win32 error they would correspond to
1504 * if the error actually came from a Win32 API. A major mess, we should
1505 * have used LMDB-specific error codes for everything.
1508 case ENOENT: /* 2, FILE_NOT_FOUND */
1509 case EIO: /* 5, ACCESS_DENIED */
1510 case ENOMEM: /* 12, INVALID_ACCESS */
1511 case EACCES: /* 13, INVALID_DATA */
1512 case EBUSY: /* 16, CURRENT_DIRECTORY */
1513 case EINVAL: /* 22, BAD_COMMAND */
1514 case ENOSPC: /* 28, OUT_OF_PAPER */
1515 return strerror(err);
1520 FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
1521 FORMAT_MESSAGE_IGNORE_INSERTS,
1522 NULL, err, 0, ptr, sizeof(buf), (va_list *)pad);
1525 return strerror(err);
1529 /** assert(3) variant in cursor context */
1530 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1531 /** assert(3) variant in transaction context */
1532 #define mdb_tassert(txn, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1533 /** assert(3) variant in environment context */
1534 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1537 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1538 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1541 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1542 const char *func, const char *file, int line)
1545 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1546 file, line, expr_txt, func);
1547 if (env->me_assert_func)
1548 env->me_assert_func(env, buf);
1549 fprintf(stderr, "%s\n", buf);
1553 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1557 /** Return the page number of \b mp which may be sub-page, for debug output */
1559 mdb_dbg_pgno(MDB_page *mp)
1562 COPY_PGNO(ret, mp->mp_pgno);
1566 /** Display a key in hexadecimal and return the address of the result.
1567 * @param[in] key the key to display
1568 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1569 * @return The key in hexadecimal form.
1572 mdb_dkey(MDB_val *key, char *buf)
1575 unsigned char *c = key->mv_data;
1581 if (key->mv_size > DKBUF_MAXKEYSIZE)
1582 return "MDB_MAXKEYSIZE";
1583 /* may want to make this a dynamic check: if the key is mostly
1584 * printable characters, print it as-is instead of converting to hex.
1588 for (i=0; i<key->mv_size; i++)
1589 ptr += sprintf(ptr, "%02x", *c++);
1591 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1597 mdb_leafnode_type(MDB_node *n)
1599 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1600 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1601 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1604 /** Display all the keys in the page. */
1606 mdb_page_list(MDB_page *mp)
1608 pgno_t pgno = mdb_dbg_pgno(mp);
1609 const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
1611 unsigned int i, nkeys, nsize, total = 0;
1615 switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1616 case P_BRANCH: type = "Branch page"; break;
1617 case P_LEAF: type = "Leaf page"; break;
1618 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1619 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1620 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1622 fprintf(stderr, "Overflow page %"Z"u pages %u%s\n",
1623 pgno, mp->mp_pages, state);
1626 fprintf(stderr, "Meta-page %"Z"u txnid %"Z"u\n",
1627 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1630 fprintf(stderr, "Bad page %"Z"u flags 0x%u\n", pgno, mp->mp_flags);
1634 nkeys = NUMKEYS(mp);
1635 fprintf(stderr, "%s %"Z"u numkeys %d%s\n", type, pgno, nkeys, state);
1637 for (i=0; i<nkeys; i++) {
1638 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1639 key.mv_size = nsize = mp->mp_pad;
1640 key.mv_data = LEAF2KEY(mp, i, nsize);
1642 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1645 node = NODEPTR(mp, i);
1646 key.mv_size = node->mn_ksize;
1647 key.mv_data = node->mn_data;
1648 nsize = NODESIZE + key.mv_size;
1649 if (IS_BRANCH(mp)) {
1650 fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
1654 if (F_ISSET(node->mn_flags, F_BIGDATA))
1655 nsize += sizeof(pgno_t);
1657 nsize += NODEDSZ(node);
1659 nsize += sizeof(indx_t);
1660 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1661 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1663 total = EVEN(total);
1665 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1666 IS_LEAF2(mp) ? PAGEHDRSZ : PAGEBASE + mp->mp_lower, total, SIZELEFT(mp));
1670 mdb_cursor_chk(MDB_cursor *mc)
1676 if (!mc->mc_snum || !(mc->mc_flags & C_INITIALIZED)) return;
1677 for (i=0; i<mc->mc_top; i++) {
1679 node = NODEPTR(mp, mc->mc_ki[i]);
1680 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1683 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1685 if (mc->mc_xcursor && (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
1686 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
1687 if (((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) &&
1688 mc->mc_xcursor->mx_cursor.mc_pg[0] != NODEDATA(node)) {
1696 /** Count all the pages in each DB and in the freelist
1697 * and make sure it matches the actual number of pages
1699 * All named DBs must be open for a correct count.
1701 static void mdb_audit(MDB_txn *txn)
1705 MDB_ID freecount, count;
1710 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1711 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1712 freecount += *(MDB_ID *)data.mv_data;
1713 mdb_tassert(txn, rc == MDB_NOTFOUND);
1716 for (i = 0; i<txn->mt_numdbs; i++) {
1718 if (!(txn->mt_dbflags[i] & DB_VALID))
1720 mdb_cursor_init(&mc, txn, i, &mx);
1721 if (txn->mt_dbs[i].md_root == P_INVALID)
1723 count += txn->mt_dbs[i].md_branch_pages +
1724 txn->mt_dbs[i].md_leaf_pages +
1725 txn->mt_dbs[i].md_overflow_pages;
1726 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1727 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1728 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
1731 mp = mc.mc_pg[mc.mc_top];
1732 for (j=0; j<NUMKEYS(mp); j++) {
1733 MDB_node *leaf = NODEPTR(mp, j);
1734 if (leaf->mn_flags & F_SUBDATA) {
1736 memcpy(&db, NODEDATA(leaf), sizeof(db));
1737 count += db.md_branch_pages + db.md_leaf_pages +
1738 db.md_overflow_pages;
1742 mdb_tassert(txn, rc == MDB_NOTFOUND);
1745 if (freecount + count + NUM_METAS != txn->mt_next_pgno) {
1746 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1747 txn->mt_txnid, freecount, count+NUM_METAS,
1748 freecount+count+NUM_METAS, txn->mt_next_pgno);
1754 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1756 return txn->mt_dbxs[dbi].md_cmp(a, b);
1760 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1762 MDB_cmp_func *dcmp = txn->mt_dbxs[dbi].md_dcmp;
1763 #if UINT_MAX < SIZE_MAX
1764 if (dcmp == mdb_cmp_int && a->mv_size == sizeof(size_t))
1765 dcmp = mdb_cmp_clong;
1770 /** Allocate memory for a page.
1771 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1774 mdb_page_malloc(MDB_txn *txn, unsigned num)
1776 MDB_env *env = txn->mt_env;
1777 MDB_page *ret = env->me_dpages;
1778 size_t psize = env->me_psize, sz = psize, off;
1779 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1780 * For a single page alloc, we init everything after the page header.
1781 * For multi-page, we init the final page; if the caller needed that
1782 * many pages they will be filling in at least up to the last page.
1786 VGMEMP_ALLOC(env, ret, sz);
1787 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1788 env->me_dpages = ret->mp_next;
1791 psize -= off = PAGEHDRSZ;
1796 if ((ret = malloc(sz)) != NULL) {
1797 VGMEMP_ALLOC(env, ret, sz);
1798 if (!(env->me_flags & MDB_NOMEMINIT)) {
1799 memset((char *)ret + off, 0, psize);
1803 txn->mt_flags |= MDB_TXN_ERROR;
1807 /** Free a single page.
1808 * Saves single pages to a list, for future reuse.
1809 * (This is not used for multi-page overflow pages.)
1812 mdb_page_free(MDB_env *env, MDB_page *mp)
1814 mp->mp_next = env->me_dpages;
1815 VGMEMP_FREE(env, mp);
1816 env->me_dpages = mp;
1819 /** Free a dirty page */
1821 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1823 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1824 mdb_page_free(env, dp);
1826 /* large pages just get freed directly */
1827 VGMEMP_FREE(env, dp);
1832 /** Return all dirty pages to dpage list */
1834 mdb_dlist_free(MDB_txn *txn)
1836 MDB_env *env = txn->mt_env;
1837 MDB_ID2L dl = txn->mt_u.dirty_list;
1838 unsigned i, n = dl[0].mid;
1840 for (i = 1; i <= n; i++) {
1841 mdb_dpage_free(env, dl[i].mptr);
1846 /** Loosen or free a single page.
1847 * Saves single pages to a list for future reuse
1848 * in this same txn. It has been pulled from the freeDB
1849 * and already resides on the dirty list, but has been
1850 * deleted. Use these pages first before pulling again
1853 * If the page wasn't dirtied in this txn, just add it
1854 * to this txn's free list.
1857 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
1860 pgno_t pgno = mp->mp_pgno;
1861 MDB_txn *txn = mc->mc_txn;
1863 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
1864 if (txn->mt_parent) {
1865 MDB_ID2 *dl = txn->mt_u.dirty_list;
1866 /* If txn has a parent, make sure the page is in our
1870 unsigned x = mdb_mid2l_search(dl, pgno);
1871 if (x <= dl[0].mid && dl[x].mid == pgno) {
1872 if (mp != dl[x].mptr) { /* bad cursor? */
1873 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1874 txn->mt_flags |= MDB_TXN_ERROR;
1875 return MDB_CORRUPTED;
1882 /* no parent txn, so it's just ours */
1887 DPRINTF(("loosen db %d page %"Z"u", DDBI(mc),
1889 NEXT_LOOSE_PAGE(mp) = txn->mt_loose_pgs;
1890 txn->mt_loose_pgs = mp;
1891 txn->mt_loose_count++;
1892 mp->mp_flags |= P_LOOSE;
1894 int rc = mdb_midl_append(&txn->mt_free_pgs, pgno);
1902 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
1903 * @param[in] mc A cursor handle for the current operation.
1904 * @param[in] pflags Flags of the pages to update:
1905 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1906 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
1907 * @return 0 on success, non-zero on failure.
1910 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
1912 enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
1913 MDB_txn *txn = mc->mc_txn;
1919 int rc = MDB_SUCCESS, level;
1921 /* Mark pages seen by cursors */
1922 if (mc->mc_flags & C_UNTRACK)
1923 mc = NULL; /* will find mc in mt_cursors */
1924 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1925 for (; mc; mc=mc->mc_next) {
1926 if (!(mc->mc_flags & C_INITIALIZED))
1928 for (m3 = mc;; m3 = &mx->mx_cursor) {
1930 for (j=0; j<m3->mc_snum; j++) {
1932 if ((mp->mp_flags & Mask) == pflags)
1933 mp->mp_flags ^= P_KEEP;
1935 mx = m3->mc_xcursor;
1936 /* Proceed to mx if it is at a sub-database */
1937 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
1939 if (! (mp && (mp->mp_flags & P_LEAF)))
1941 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
1942 if (!(leaf->mn_flags & F_SUBDATA))
1951 /* Mark dirty root pages */
1952 for (i=0; i<txn->mt_numdbs; i++) {
1953 if (txn->mt_dbflags[i] & DB_DIRTY) {
1954 pgno_t pgno = txn->mt_dbs[i].md_root;
1955 if (pgno == P_INVALID)
1957 if ((rc = mdb_page_get(txn, pgno, &dp, &level)) != MDB_SUCCESS)
1959 if ((dp->mp_flags & Mask) == pflags && level <= 1)
1960 dp->mp_flags ^= P_KEEP;
1968 static int mdb_page_flush(MDB_txn *txn, int keep);
1970 /** Spill pages from the dirty list back to disk.
1971 * This is intended to prevent running into #MDB_TXN_FULL situations,
1972 * but note that they may still occur in a few cases:
1973 * 1) our estimate of the txn size could be too small. Currently this
1974 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
1975 * 2) child txns may run out of space if their parents dirtied a
1976 * lot of pages and never spilled them. TODO: we probably should do
1977 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1978 * the parent's dirty_room is below a given threshold.
1980 * Otherwise, if not using nested txns, it is expected that apps will
1981 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1982 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1983 * If the txn never references them again, they can be left alone.
1984 * If the txn only reads them, they can be used without any fuss.
1985 * If the txn writes them again, they can be dirtied immediately without
1986 * going thru all of the work of #mdb_page_touch(). Such references are
1987 * handled by #mdb_page_unspill().
1989 * Also note, we never spill DB root pages, nor pages of active cursors,
1990 * because we'll need these back again soon anyway. And in nested txns,
1991 * we can't spill a page in a child txn if it was already spilled in a
1992 * parent txn. That would alter the parent txns' data even though
1993 * the child hasn't committed yet, and we'd have no way to undo it if
1994 * the child aborted.
1996 * @param[in] m0 cursor A cursor handle identifying the transaction and
1997 * database for which we are checking space.
1998 * @param[in] key For a put operation, the key being stored.
1999 * @param[in] data For a put operation, the data being stored.
2000 * @return 0 on success, non-zero on failure.
2003 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
2005 MDB_txn *txn = m0->mc_txn;
2007 MDB_ID2L dl = txn->mt_u.dirty_list;
2008 unsigned int i, j, need;
2011 if (m0->mc_flags & C_SUB)
2014 /* Estimate how much space this op will take */
2015 i = m0->mc_db->md_depth;
2016 /* Named DBs also dirty the main DB */
2017 if (m0->mc_dbi >= CORE_DBS)
2018 i += txn->mt_dbs[MAIN_DBI].md_depth;
2019 /* For puts, roughly factor in the key+data size */
2021 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
2022 i += i; /* double it for good measure */
2025 if (txn->mt_dirty_room > i)
2028 if (!txn->mt_spill_pgs) {
2029 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
2030 if (!txn->mt_spill_pgs)
2033 /* purge deleted slots */
2034 MDB_IDL sl = txn->mt_spill_pgs;
2035 unsigned int num = sl[0];
2037 for (i=1; i<=num; i++) {
2044 /* Preserve pages which may soon be dirtied again */
2045 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
2048 /* Less aggressive spill - we originally spilled the entire dirty list,
2049 * with a few exceptions for cursor pages and DB root pages. But this
2050 * turns out to be a lot of wasted effort because in a large txn many
2051 * of those pages will need to be used again. So now we spill only 1/8th
2052 * of the dirty pages. Testing revealed this to be a good tradeoff,
2053 * better than 1/2, 1/4, or 1/10.
2055 if (need < MDB_IDL_UM_MAX / 8)
2056 need = MDB_IDL_UM_MAX / 8;
2058 /* Save the page IDs of all the pages we're flushing */
2059 /* flush from the tail forward, this saves a lot of shifting later on. */
2060 for (i=dl[0].mid; i && need; i--) {
2061 MDB_ID pn = dl[i].mid << 1;
2063 if (dp->mp_flags & (P_LOOSE|P_KEEP))
2065 /* Can't spill twice, make sure it's not already in a parent's
2068 if (txn->mt_parent) {
2070 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
2071 if (tx2->mt_spill_pgs) {
2072 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
2073 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
2074 dp->mp_flags |= P_KEEP;
2082 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
2086 mdb_midl_sort(txn->mt_spill_pgs);
2088 /* Flush the spilled part of dirty list */
2089 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
2092 /* Reset any dirty pages we kept that page_flush didn't see */
2093 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
2096 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
2100 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
2102 mdb_find_oldest(MDB_txn *txn)
2105 txnid_t mr, oldest = txn->mt_txnid - 1;
2106 if (txn->mt_env->me_txns) {
2107 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
2108 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
2119 /** Add a page to the txn's dirty list */
2121 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
2124 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
2126 if (txn->mt_flags & MDB_TXN_WRITEMAP) {
2127 insert = mdb_mid2l_append;
2129 insert = mdb_mid2l_insert;
2131 mid.mid = mp->mp_pgno;
2133 rc = insert(txn->mt_u.dirty_list, &mid);
2134 mdb_tassert(txn, rc == 0);
2135 txn->mt_dirty_room--;
2138 /** Allocate page numbers and memory for writing. Maintain me_pglast,
2139 * me_pghead and mt_next_pgno.
2141 * If there are free pages available from older transactions, they
2142 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
2143 * Do not modify the freedB, just merge freeDB records into me_pghead[]
2144 * and move me_pglast to say which records were consumed. Only this
2145 * function can create me_pghead and move me_pglast/mt_next_pgno.
2146 * @param[in] mc cursor A cursor handle identifying the transaction and
2147 * database for which we are allocating.
2148 * @param[in] num the number of pages to allocate.
2149 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
2150 * will always be satisfied by a single contiguous chunk of memory.
2151 * @return 0 on success, non-zero on failure.
2154 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
2156 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
2157 /* Get at most <Max_retries> more freeDB records once me_pghead
2158 * has enough pages. If not enough, use new pages from the map.
2159 * If <Paranoid> and mc is updating the freeDB, only get new
2160 * records if me_pghead is empty. Then the freelist cannot play
2161 * catch-up with itself by growing while trying to save it.
2163 enum { Paranoid = 1, Max_retries = 500 };
2165 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
2167 int rc, retry = num * 60;
2168 MDB_txn *txn = mc->mc_txn;
2169 MDB_env *env = txn->mt_env;
2170 pgno_t pgno, *mop = env->me_pghead;
2171 unsigned i, j, mop_len = mop ? mop[0] : 0, n2 = num-1;
2173 txnid_t oldest = 0, last;
2178 /* If there are any loose pages, just use them */
2179 if (num == 1 && txn->mt_loose_pgs) {
2180 np = txn->mt_loose_pgs;
2181 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
2182 txn->mt_loose_count--;
2183 DPRINTF(("db %d use loose page %"Z"u", DDBI(mc),
2191 /* If our dirty list is already full, we can't do anything */
2192 if (txn->mt_dirty_room == 0) {
2197 for (op = MDB_FIRST;; op = MDB_NEXT) {
2202 /* Seek a big enough contiguous page range. Prefer
2203 * pages at the tail, just truncating the list.
2209 if (mop[i-n2] == pgno+n2)
2216 if (op == MDB_FIRST) { /* 1st iteration */
2217 /* Prepare to fetch more and coalesce */
2218 last = env->me_pglast;
2219 oldest = env->me_pgoldest;
2220 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
2223 key.mv_data = &last; /* will look up last+1 */
2224 key.mv_size = sizeof(last);
2226 if (Paranoid && mc->mc_dbi == FREE_DBI)
2229 if (Paranoid && retry < 0 && mop_len)
2233 /* Do not fetch more if the record will be too recent */
2234 if (oldest <= last) {
2236 oldest = mdb_find_oldest(txn);
2237 env->me_pgoldest = oldest;
2243 rc = mdb_cursor_get(&m2, &key, NULL, op);
2245 if (rc == MDB_NOTFOUND)
2249 last = *(txnid_t*)key.mv_data;
2250 if (oldest <= last) {
2252 oldest = mdb_find_oldest(txn);
2253 env->me_pgoldest = oldest;
2259 np = m2.mc_pg[m2.mc_top];
2260 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
2261 if ((rc = mdb_node_read(txn, leaf, &data)) != MDB_SUCCESS)
2264 idl = (MDB_ID *) data.mv_data;
2267 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
2272 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
2274 mop = env->me_pghead;
2276 env->me_pglast = last;
2278 DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
2279 last, txn->mt_dbs[FREE_DBI].md_root, i));
2281 DPRINTF(("IDL %"Z"u", idl[j]));
2283 /* Merge in descending sorted order */
2284 mdb_midl_xmerge(mop, idl);
2288 /* Use new pages from the map when nothing suitable in the freeDB */
2290 pgno = txn->mt_next_pgno;
2291 if (pgno + num >= env->me_maxpg) {
2292 DPUTS("DB size maxed out");
2298 if (env->me_flags & MDB_WRITEMAP) {
2299 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
2301 if (!(np = mdb_page_malloc(txn, num))) {
2307 mop[0] = mop_len -= num;
2308 /* Move any stragglers down */
2309 for (j = i-num; j < mop_len; )
2310 mop[++j] = mop[++i];
2312 txn->mt_next_pgno = pgno + num;
2315 mdb_page_dirty(txn, np);
2321 txn->mt_flags |= MDB_TXN_ERROR;
2325 /** Copy the used portions of a non-overflow page.
2326 * @param[in] dst page to copy into
2327 * @param[in] src page to copy from
2328 * @param[in] psize size of a page
2331 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2333 enum { Align = sizeof(pgno_t) };
2334 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2336 /* If page isn't full, just copy the used portion. Adjust
2337 * alignment so memcpy may copy words instead of bytes.
2339 if ((unused &= -Align) && !IS_LEAF2(src)) {
2340 upper = (upper + PAGEBASE) & -Align;
2341 memcpy(dst, src, (lower + PAGEBASE + (Align-1)) & -Align);
2342 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2345 memcpy(dst, src, psize - unused);
2349 /** Pull a page off the txn's spill list, if present.
2350 * If a page being referenced was spilled to disk in this txn, bring
2351 * it back and make it dirty/writable again.
2352 * @param[in] txn the transaction handle.
2353 * @param[in] mp the page being referenced. It must not be dirty.
2354 * @param[out] ret the writable page, if any. ret is unchanged if
2355 * mp wasn't spilled.
2358 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2360 MDB_env *env = txn->mt_env;
2363 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2365 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2366 if (!tx2->mt_spill_pgs)
2368 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2369 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2372 if (txn->mt_dirty_room == 0)
2373 return MDB_TXN_FULL;
2374 if (IS_OVERFLOW(mp))
2378 if (env->me_flags & MDB_WRITEMAP) {
2381 np = mdb_page_malloc(txn, num);
2385 memcpy(np, mp, num * env->me_psize);
2387 mdb_page_copy(np, mp, env->me_psize);
2390 /* If in current txn, this page is no longer spilled.
2391 * If it happens to be the last page, truncate the spill list.
2392 * Otherwise mark it as deleted by setting the LSB.
2394 if (x == txn->mt_spill_pgs[0])
2395 txn->mt_spill_pgs[0]--;
2397 txn->mt_spill_pgs[x] |= 1;
2398 } /* otherwise, if belonging to a parent txn, the
2399 * page remains spilled until child commits
2402 mdb_page_dirty(txn, np);
2403 np->mp_flags |= P_DIRTY;
2411 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2412 * @param[in] mc cursor pointing to the page to be touched
2413 * @return 0 on success, non-zero on failure.
2416 mdb_page_touch(MDB_cursor *mc)
2418 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2419 MDB_txn *txn = mc->mc_txn;
2420 MDB_cursor *m2, *m3;
2424 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2425 if (txn->mt_flags & MDB_TXN_SPILLS) {
2427 rc = mdb_page_unspill(txn, mp, &np);
2433 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2434 (rc = mdb_page_alloc(mc, 1, &np)))
2437 DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
2438 mp->mp_pgno, pgno));
2439 mdb_cassert(mc, mp->mp_pgno != pgno);
2440 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2441 /* Update the parent page, if any, to point to the new page */
2443 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2444 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2445 SETPGNO(node, pgno);
2447 mc->mc_db->md_root = pgno;
2449 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2450 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2452 /* If txn has a parent, make sure the page is in our
2456 unsigned x = mdb_mid2l_search(dl, pgno);
2457 if (x <= dl[0].mid && dl[x].mid == pgno) {
2458 if (mp != dl[x].mptr) { /* bad cursor? */
2459 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2460 txn->mt_flags |= MDB_TXN_ERROR;
2461 return MDB_CORRUPTED;
2466 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2468 np = mdb_page_malloc(txn, 1);
2473 rc = mdb_mid2l_insert(dl, &mid);
2474 mdb_cassert(mc, rc == 0);
2479 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2481 np->mp_flags |= P_DIRTY;
2484 /* Adjust cursors pointing to mp */
2485 mc->mc_pg[mc->mc_top] = np;
2486 m2 = txn->mt_cursors[mc->mc_dbi];
2487 if (mc->mc_flags & C_SUB) {
2488 for (; m2; m2=m2->mc_next) {
2489 m3 = &m2->mc_xcursor->mx_cursor;
2490 if (m3->mc_snum < mc->mc_snum) continue;
2491 if (m3->mc_pg[mc->mc_top] == mp)
2492 m3->mc_pg[mc->mc_top] = np;
2495 for (; m2; m2=m2->mc_next) {
2496 if (m2->mc_snum < mc->mc_snum) continue;
2497 if (m2 == mc) continue;
2498 if (m2->mc_pg[mc->mc_top] == mp) {
2499 m2->mc_pg[mc->mc_top] = np;
2500 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
2502 (m2->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
2504 MDB_node *leaf = NODEPTR(np, m2->mc_ki[mc->mc_top]);
2505 if ((leaf->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
2506 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
2514 txn->mt_flags |= MDB_TXN_ERROR;
2519 mdb_env_sync(MDB_env *env, int force)
2522 if (env->me_flags & MDB_RDONLY)
2524 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2525 if (env->me_flags & MDB_WRITEMAP) {
2526 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2527 ? MS_ASYNC : MS_SYNC;
2528 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
2531 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2535 #ifdef BROKEN_FDATASYNC
2536 if (env->me_flags & MDB_FSYNCONLY) {
2537 if (fsync(env->me_fd))
2541 if (MDB_FDATASYNC(env->me_fd))
2548 /** Back up parent txn's cursors, then grab the originals for tracking */
2550 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2552 MDB_cursor *mc, *bk;
2557 for (i = src->mt_numdbs; --i >= 0; ) {
2558 if ((mc = src->mt_cursors[i]) != NULL) {
2559 size = sizeof(MDB_cursor);
2561 size += sizeof(MDB_xcursor);
2562 for (; mc; mc = bk->mc_next) {
2568 mc->mc_db = &dst->mt_dbs[i];
2569 /* Kill pointers into src to reduce abuse: The
2570 * user may not use mc until dst ends. But we need a valid
2571 * txn pointer here for cursor fixups to keep working.
2574 mc->mc_dbflag = &dst->mt_dbflags[i];
2575 if ((mx = mc->mc_xcursor) != NULL) {
2576 *(MDB_xcursor *)(bk+1) = *mx;
2577 mx->mx_cursor.mc_txn = dst;
2579 mc->mc_next = dst->mt_cursors[i];
2580 dst->mt_cursors[i] = mc;
2587 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2588 * @param[in] txn the transaction handle.
2589 * @param[in] merge true to keep changes to parent cursors, false to revert.
2590 * @return 0 on success, non-zero on failure.
2593 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2595 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2599 for (i = txn->mt_numdbs; --i >= 0; ) {
2600 for (mc = cursors[i]; mc; mc = next) {
2602 if ((bk = mc->mc_backup) != NULL) {
2604 /* Commit changes to parent txn */
2605 mc->mc_next = bk->mc_next;
2606 mc->mc_backup = bk->mc_backup;
2607 mc->mc_txn = bk->mc_txn;
2608 mc->mc_db = bk->mc_db;
2609 mc->mc_dbflag = bk->mc_dbflag;
2610 if ((mx = mc->mc_xcursor) != NULL)
2611 mx->mx_cursor.mc_txn = bk->mc_txn;
2613 /* Abort nested txn */
2615 if ((mx = mc->mc_xcursor) != NULL)
2616 *mx = *(MDB_xcursor *)(bk+1);
2620 /* Only malloced cursors are permanently tracked. */
2627 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2633 Pidset = F_SETLK, Pidcheck = F_GETLK
2637 /** Set or check a pid lock. Set returns 0 on success.
2638 * Check returns 0 if the process is certainly dead, nonzero if it may
2639 * be alive (the lock exists or an error happened so we do not know).
2641 * On Windows Pidset is a no-op, we merely check for the existence
2642 * of the process with the given pid. On POSIX we use a single byte
2643 * lock on the lockfile, set at an offset equal to the pid.
2646 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2648 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2651 if (op == Pidcheck) {
2652 h = OpenProcess(env->me_pidquery, FALSE, pid);
2653 /* No documented "no such process" code, but other program use this: */
2655 return ErrCode() != ERROR_INVALID_PARAMETER;
2656 /* A process exists until all handles to it close. Has it exited? */
2657 ret = WaitForSingleObject(h, 0) != 0;
2664 struct flock lock_info;
2665 memset(&lock_info, 0, sizeof(lock_info));
2666 lock_info.l_type = F_WRLCK;
2667 lock_info.l_whence = SEEK_SET;
2668 lock_info.l_start = pid;
2669 lock_info.l_len = 1;
2670 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2671 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2673 } else if ((rc = ErrCode()) == EINTR) {
2681 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2682 * @param[in] txn the transaction handle to initialize
2683 * @return 0 on success, non-zero on failure.
2686 mdb_txn_renew0(MDB_txn *txn)
2688 MDB_env *env = txn->mt_env;
2689 MDB_txninfo *ti = env->me_txns;
2691 unsigned int i, nr, flags = txn->mt_flags;
2693 int rc, new_notls = 0;
2695 if ((flags &= MDB_TXN_RDONLY) != 0) {
2697 meta = mdb_env_pick_meta(env);
2698 txn->mt_txnid = meta->mm_txnid;
2699 txn->mt_u.reader = NULL;
2701 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2702 pthread_getspecific(env->me_txkey);
2704 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2705 return MDB_BAD_RSLOT;
2707 MDB_PID_T pid = env->me_pid;
2708 MDB_THR_T tid = pthread_self();
2709 mdb_mutexref_t rmutex = env->me_rmutex;
2711 if (!env->me_live_reader) {
2712 rc = mdb_reader_pid(env, Pidset, pid);
2715 env->me_live_reader = 1;
2718 if (LOCK_MUTEX(rc, env, rmutex))
2720 nr = ti->mti_numreaders;
2721 for (i=0; i<nr; i++)
2722 if (ti->mti_readers[i].mr_pid == 0)
2724 if (i == env->me_maxreaders) {
2725 UNLOCK_MUTEX(rmutex);
2726 return MDB_READERS_FULL;
2728 r = &ti->mti_readers[i];
2729 /* Claim the reader slot, carefully since other code
2730 * uses the reader table un-mutexed: First reset the
2731 * slot, next publish it in mti_numreaders. After
2732 * that, it is safe for mdb_env_close() to touch it.
2733 * When it will be closed, we can finally claim it.
2736 r->mr_txnid = (txnid_t)-1;
2739 ti->mti_numreaders = ++nr;
2740 env->me_close_readers = nr;
2742 UNLOCK_MUTEX(rmutex);
2744 new_notls = (env->me_flags & MDB_NOTLS);
2745 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2750 do /* LY: Retry on a race, ITS#7970. */
2751 r->mr_txnid = ti->mti_txnid;
2752 while(r->mr_txnid != ti->mti_txnid);
2753 txn->mt_txnid = r->mr_txnid;
2754 txn->mt_u.reader = r;
2755 meta = env->me_metas[txn->mt_txnid & 1];
2759 /* Not yet touching txn == env->me_txn0, it may be active */
2761 if (LOCK_MUTEX(rc, env, env->me_wmutex))
2763 txn->mt_txnid = ti->mti_txnid;
2764 meta = env->me_metas[txn->mt_txnid & 1];
2766 meta = mdb_env_pick_meta(env);
2767 txn->mt_txnid = meta->mm_txnid;
2771 if (txn->mt_txnid == mdb_debug_start)
2774 txn->mt_child = NULL;
2775 txn->mt_loose_pgs = NULL;
2776 txn->mt_loose_count = 0;
2777 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2778 txn->mt_u.dirty_list = env->me_dirty_list;
2779 txn->mt_u.dirty_list[0].mid = 0;
2780 txn->mt_free_pgs = env->me_free_pgs;
2781 txn->mt_free_pgs[0] = 0;
2782 txn->mt_spill_pgs = NULL;
2784 memcpy(txn->mt_dbiseqs, env->me_dbiseqs, env->me_maxdbs * sizeof(unsigned int));
2787 /* Copy the DB info and flags */
2788 memcpy(txn->mt_dbs, meta->mm_dbs, CORE_DBS * sizeof(MDB_db));
2790 /* Moved to here to avoid a data race in read TXNs */
2791 txn->mt_next_pgno = meta->mm_last_pg+1;
2793 txn->mt_flags = flags;
2796 txn->mt_numdbs = env->me_numdbs;
2797 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
2798 x = env->me_dbflags[i];
2799 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2800 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_USRVALID|DB_STALE : 0;
2802 txn->mt_dbflags[MAIN_DBI] = DB_VALID|DB_USRVALID;
2803 txn->mt_dbflags[FREE_DBI] = DB_VALID;
2805 if (env->me_flags & MDB_FATAL_ERROR) {
2806 DPUTS("environment had fatal error, must shutdown!");
2808 } else if (env->me_maxpg < txn->mt_next_pgno) {
2809 rc = MDB_MAP_RESIZED;
2813 mdb_txn_end(txn, new_notls /*0 or MDB_END_SLOT*/ | MDB_END_FAIL_BEGIN);
2818 mdb_txn_renew(MDB_txn *txn)
2822 if (!txn || !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY|MDB_TXN_FINISHED))
2825 rc = mdb_txn_renew0(txn);
2826 if (rc == MDB_SUCCESS) {
2827 DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2828 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2829 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2835 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2839 int rc, size, tsize;
2841 flags &= MDB_TXN_BEGIN_FLAGS;
2842 flags |= env->me_flags & MDB_WRITEMAP;
2844 if (env->me_flags & MDB_RDONLY & ~flags) /* write txn in RDONLY env */
2848 /* Nested transactions: Max 1 child, write txns only, no writemap */
2849 flags |= parent->mt_flags;
2850 if (flags & (MDB_RDONLY|MDB_WRITEMAP|MDB_TXN_BLOCKED)) {
2851 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
2853 /* Child txns save MDB_pgstate and use own copy of cursors */
2854 size = env->me_maxdbs * (sizeof(MDB_db)+sizeof(MDB_cursor *)+1);
2855 size += tsize = sizeof(MDB_ntxn);
2856 } else if (flags & MDB_RDONLY) {
2857 size = env->me_maxdbs * (sizeof(MDB_db)+1);
2858 size += tsize = sizeof(MDB_txn);
2860 /* Reuse preallocated write txn. However, do not touch it until
2861 * mdb_txn_renew0() succeeds, since it currently may be active.
2866 if ((txn = calloc(1, size)) == NULL) {
2867 DPRINTF(("calloc: %s", strerror(errno)));
2870 txn->mt_dbxs = env->me_dbxs; /* static */
2871 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2872 txn->mt_dbflags = (unsigned char *)txn + size - env->me_maxdbs;
2873 txn->mt_flags = flags;
2878 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2879 txn->mt_dbiseqs = parent->mt_dbiseqs;
2880 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2881 if (!txn->mt_u.dirty_list ||
2882 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2884 free(txn->mt_u.dirty_list);
2888 txn->mt_txnid = parent->mt_txnid;
2889 txn->mt_dirty_room = parent->mt_dirty_room;
2890 txn->mt_u.dirty_list[0].mid = 0;
2891 txn->mt_spill_pgs = NULL;
2892 txn->mt_next_pgno = parent->mt_next_pgno;
2893 parent->mt_flags |= MDB_TXN_HAS_CHILD;
2894 parent->mt_child = txn;
2895 txn->mt_parent = parent;
2896 txn->mt_numdbs = parent->mt_numdbs;
2897 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2898 /* Copy parent's mt_dbflags, but clear DB_NEW */
2899 for (i=0; i<txn->mt_numdbs; i++)
2900 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2902 ntxn = (MDB_ntxn *)txn;
2903 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2904 if (env->me_pghead) {
2905 size = MDB_IDL_SIZEOF(env->me_pghead);
2906 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2908 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2913 rc = mdb_cursor_shadow(parent, txn);
2915 mdb_txn_end(txn, MDB_END_FAIL_BEGINCHILD);
2916 } else { /* MDB_RDONLY */
2917 txn->mt_dbiseqs = env->me_dbiseqs;
2919 rc = mdb_txn_renew0(txn);
2922 if (txn != env->me_txn0)
2925 txn->mt_flags |= flags; /* could not change txn=me_txn0 earlier */
2927 DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2928 txn->mt_txnid, (flags & MDB_RDONLY) ? 'r' : 'w',
2929 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
2936 mdb_txn_env(MDB_txn *txn)
2938 if(!txn) return NULL;
2943 mdb_txn_id(MDB_txn *txn)
2946 return txn->mt_txnid;
2949 /** Export or close DBI handles opened in this txn. */
2951 mdb_dbis_update(MDB_txn *txn, int keep)
2954 MDB_dbi n = txn->mt_numdbs;
2955 MDB_env *env = txn->mt_env;
2956 unsigned char *tdbflags = txn->mt_dbflags;
2958 for (i = n; --i >= CORE_DBS;) {
2959 if (tdbflags[i] & DB_NEW) {
2961 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2963 char *ptr = env->me_dbxs[i].md_name.mv_data;
2965 env->me_dbxs[i].md_name.mv_data = NULL;
2966 env->me_dbxs[i].md_name.mv_size = 0;
2967 env->me_dbflags[i] = 0;
2968 env->me_dbiseqs[i]++;
2974 if (keep && env->me_numdbs < n)
2978 /** End a transaction, except successful commit of a nested transaction.
2979 * May be called twice for readonly txns: First reset it, then abort.
2980 * @param[in] txn the transaction handle to end
2981 * @param[in] mode why and how to end the transaction
2984 mdb_txn_end(MDB_txn *txn, unsigned mode)
2986 MDB_env *env = txn->mt_env;
2988 static const char *const names[] = MDB_END_NAMES;
2991 /* Export or close DBI handles opened in this txn */
2992 mdb_dbis_update(txn, mode & MDB_END_UPDATE);
2994 DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2995 names[mode & MDB_END_OPMASK],
2996 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2997 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
2999 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3000 if (txn->mt_u.reader) {
3001 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
3002 if (!(env->me_flags & MDB_NOTLS)) {
3003 txn->mt_u.reader = NULL; /* txn does not own reader */
3004 } else if (mode & MDB_END_SLOT) {
3005 txn->mt_u.reader->mr_pid = 0;
3006 txn->mt_u.reader = NULL;
3007 } /* else txn owns the slot until it does MDB_END_SLOT */
3009 txn->mt_numdbs = 0; /* prevent further DBI activity */
3010 txn->mt_flags |= MDB_TXN_FINISHED;
3012 } else if (!F_ISSET(txn->mt_flags, MDB_TXN_FINISHED)) {
3013 pgno_t *pghead = env->me_pghead;
3015 if (!(mode & MDB_END_UPDATE)) /* !(already closed cursors) */
3016 mdb_cursors_close(txn, 0);
3017 if (!(env->me_flags & MDB_WRITEMAP)) {
3018 mdb_dlist_free(txn);
3022 txn->mt_flags = MDB_TXN_FINISHED;
3024 if (!txn->mt_parent) {
3025 mdb_midl_shrink(&txn->mt_free_pgs);
3026 env->me_free_pgs = txn->mt_free_pgs;
3028 env->me_pghead = NULL;
3032 mode = 0; /* txn == env->me_txn0, do not free() it */
3034 /* The writer mutex was locked in mdb_txn_begin. */
3036 UNLOCK_MUTEX(env->me_wmutex);
3038 txn->mt_parent->mt_child = NULL;
3039 txn->mt_parent->mt_flags &= ~MDB_TXN_HAS_CHILD;
3040 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
3041 mdb_midl_free(txn->mt_free_pgs);
3042 mdb_midl_free(txn->mt_spill_pgs);
3043 free(txn->mt_u.dirty_list);
3046 mdb_midl_free(pghead);
3049 if (mode & MDB_END_FREE)
3054 mdb_txn_reset(MDB_txn *txn)
3059 /* This call is only valid for read-only txns */
3060 if (!(txn->mt_flags & MDB_TXN_RDONLY))
3063 mdb_txn_end(txn, MDB_END_RESET);
3067 mdb_txn_abort(MDB_txn *txn)
3073 mdb_txn_abort(txn->mt_child);
3075 mdb_txn_end(txn, MDB_END_ABORT|MDB_END_SLOT|MDB_END_FREE);
3078 /** Save the freelist as of this transaction to the freeDB.
3079 * This changes the freelist. Keep trying until it stabilizes.
3082 mdb_freelist_save(MDB_txn *txn)
3084 /* env->me_pghead[] can grow and shrink during this call.
3085 * env->me_pglast and txn->mt_free_pgs[] can only grow.
3086 * Page numbers cannot disappear from txn->mt_free_pgs[].
3089 MDB_env *env = txn->mt_env;
3090 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
3091 txnid_t pglast = 0, head_id = 0;
3092 pgno_t freecnt = 0, *free_pgs, *mop;
3093 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
3095 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
3097 if (env->me_pghead) {
3098 /* Make sure first page of freeDB is touched and on freelist */
3099 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
3100 if (rc && rc != MDB_NOTFOUND)
3104 if (!env->me_pghead && txn->mt_loose_pgs) {
3105 /* Put loose page numbers in mt_free_pgs, since
3106 * we may be unable to return them to me_pghead.
3108 MDB_page *mp = txn->mt_loose_pgs;
3109 if ((rc = mdb_midl_need(&txn->mt_free_pgs, txn->mt_loose_count)) != 0)
3111 for (; mp; mp = NEXT_LOOSE_PAGE(mp))
3112 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
3113 txn->mt_loose_pgs = NULL;
3114 txn->mt_loose_count = 0;
3117 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
3118 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
3119 ? SSIZE_MAX : maxfree_1pg;
3122 /* Come back here after each Put() in case freelist changed */
3127 /* If using records from freeDB which we have not yet
3128 * deleted, delete them and any we reserved for me_pghead.
3130 while (pglast < env->me_pglast) {
3131 rc = mdb_cursor_first(&mc, &key, NULL);
3134 pglast = head_id = *(txnid_t *)key.mv_data;
3135 total_room = head_room = 0;
3136 mdb_tassert(txn, pglast <= env->me_pglast);
3137 rc = mdb_cursor_del(&mc, 0);
3142 /* Save the IDL of pages freed by this txn, to a single record */
3143 if (freecnt < txn->mt_free_pgs[0]) {
3145 /* Make sure last page of freeDB is touched and on freelist */
3146 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
3147 if (rc && rc != MDB_NOTFOUND)
3150 free_pgs = txn->mt_free_pgs;
3151 /* Write to last page of freeDB */
3152 key.mv_size = sizeof(txn->mt_txnid);
3153 key.mv_data = &txn->mt_txnid;
3155 freecnt = free_pgs[0];
3156 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
3157 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3160 /* Retry if mt_free_pgs[] grew during the Put() */
3161 free_pgs = txn->mt_free_pgs;
3162 } while (freecnt < free_pgs[0]);
3163 mdb_midl_sort(free_pgs);
3164 memcpy(data.mv_data, free_pgs, data.mv_size);
3167 unsigned int i = free_pgs[0];
3168 DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
3169 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
3171 DPRINTF(("IDL %"Z"u", free_pgs[i]));
3177 mop = env->me_pghead;
3178 mop_len = (mop ? mop[0] : 0) + txn->mt_loose_count;
3180 /* Reserve records for me_pghead[]. Split it if multi-page,
3181 * to avoid searching freeDB for a page range. Use keys in
3182 * range [1,me_pglast]: Smaller than txnid of oldest reader.
3184 if (total_room >= mop_len) {
3185 if (total_room == mop_len || --more < 0)
3187 } else if (head_room >= maxfree_1pg && head_id > 1) {
3188 /* Keep current record (overflow page), add a new one */
3192 /* (Re)write {key = head_id, IDL length = head_room} */
3193 total_room -= head_room;
3194 head_room = mop_len - total_room;
3195 if (head_room > maxfree_1pg && head_id > 1) {
3196 /* Overflow multi-page for part of me_pghead */
3197 head_room /= head_id; /* amortize page sizes */
3198 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
3199 } else if (head_room < 0) {
3200 /* Rare case, not bothering to delete this record */
3203 key.mv_size = sizeof(head_id);
3204 key.mv_data = &head_id;
3205 data.mv_size = (head_room + 1) * sizeof(pgno_t);
3206 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3209 /* IDL is initially empty, zero out at least the length */
3210 pgs = (pgno_t *)data.mv_data;
3211 j = head_room > clean_limit ? head_room : 0;
3215 total_room += head_room;
3218 /* Return loose page numbers to me_pghead, though usually none are
3219 * left at this point. The pages themselves remain in dirty_list.
3221 if (txn->mt_loose_pgs) {
3222 MDB_page *mp = txn->mt_loose_pgs;
3223 unsigned count = txn->mt_loose_count;
3225 /* Room for loose pages + temp IDL with same */
3226 if ((rc = mdb_midl_need(&env->me_pghead, 2*count+1)) != 0)
3228 mop = env->me_pghead;
3229 loose = mop + MDB_IDL_ALLOCLEN(mop) - count;
3230 for (count = 0; mp; mp = NEXT_LOOSE_PAGE(mp))
3231 loose[ ++count ] = mp->mp_pgno;
3233 mdb_midl_sort(loose);
3234 mdb_midl_xmerge(mop, loose);
3235 txn->mt_loose_pgs = NULL;
3236 txn->mt_loose_count = 0;
3240 /* Fill in the reserved me_pghead records */
3246 rc = mdb_cursor_first(&mc, &key, &data);
3247 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
3248 txnid_t id = *(txnid_t *)key.mv_data;
3249 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
3252 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
3254 if (len > mop_len) {
3256 data.mv_size = (len + 1) * sizeof(MDB_ID);
3258 data.mv_data = mop -= len;
3261 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
3263 if (rc || !(mop_len -= len))
3270 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
3271 * @param[in] txn the transaction that's being committed
3272 * @param[in] keep number of initial pages in dirty_list to keep dirty.
3273 * @return 0 on success, non-zero on failure.
3276 mdb_page_flush(MDB_txn *txn, int keep)
3278 MDB_env *env = txn->mt_env;
3279 MDB_ID2L dl = txn->mt_u.dirty_list;
3280 unsigned psize = env->me_psize, j;
3281 int i, pagecount = dl[0].mid, rc;
3282 size_t size = 0, pos = 0;
3284 MDB_page *dp = NULL;
3288 struct iovec iov[MDB_COMMIT_PAGES];
3289 ssize_t wpos = 0, wsize = 0, wres;
3290 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
3296 if (env->me_flags & MDB_WRITEMAP) {
3297 /* Clear dirty flags */
3298 while (++i <= pagecount) {
3300 /* Don't flush this page yet */
3301 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3302 dp->mp_flags &= ~P_KEEP;
3306 dp->mp_flags &= ~P_DIRTY;
3311 /* Write the pages */
3313 if (++i <= pagecount) {
3315 /* Don't flush this page yet */
3316 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3317 dp->mp_flags &= ~P_KEEP;
3322 /* clear dirty flag */
3323 dp->mp_flags &= ~P_DIRTY;
3326 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
3331 /* Windows actually supports scatter/gather I/O, but only on
3332 * unbuffered file handles. Since we're relying on the OS page
3333 * cache for all our data, that's self-defeating. So we just
3334 * write pages one at a time. We use the ov structure to set
3335 * the write offset, to at least save the overhead of a Seek
3338 DPRINTF(("committing page %"Z"u", pgno));
3339 memset(&ov, 0, sizeof(ov));
3340 ov.Offset = pos & 0xffffffff;
3341 ov.OffsetHigh = pos >> 16 >> 16;
3342 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
3344 DPRINTF(("WriteFile: %d", rc));
3348 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
3349 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
3352 /* Write previous page(s) */
3353 #ifdef MDB_USE_PWRITEV
3354 wres = pwritev(env->me_fd, iov, n, wpos);
3357 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
3360 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
3364 DPRINTF(("lseek: %s", strerror(rc)));
3367 wres = writev(env->me_fd, iov, n);
3370 if (wres != wsize) {
3375 DPRINTF(("Write error: %s", strerror(rc)));
3377 rc = EIO; /* TODO: Use which error code? */
3378 DPUTS("short write, filesystem full?");
3389 DPRINTF(("committing page %"Z"u", pgno));
3390 next_pos = pos + size;
3391 iov[n].iov_len = size;
3392 iov[n].iov_base = (char *)dp;
3398 /* MIPS has cache coherency issues, this is a no-op everywhere else
3399 * Note: for any size >= on-chip cache size, entire on-chip cache is
3402 CACHEFLUSH(env->me_map, txn->mt_next_pgno * env->me_psize, DCACHE);
3404 for (i = keep; ++i <= pagecount; ) {
3406 /* This is a page we skipped above */
3409 dl[j].mid = dp->mp_pgno;
3412 mdb_dpage_free(env, dp);
3417 txn->mt_dirty_room += i - j;
3423 mdb_txn_commit(MDB_txn *txn)
3426 unsigned int i, end_mode;
3432 /* mdb_txn_end() mode for a commit which writes nothing */
3433 end_mode = MDB_END_EMPTY_COMMIT|MDB_END_UPDATE|MDB_END_SLOT|MDB_END_FREE;
3435 if (txn->mt_child) {
3436 rc = mdb_txn_commit(txn->mt_child);
3443 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3447 if (txn->mt_flags & (MDB_TXN_FINISHED|MDB_TXN_ERROR)) {
3448 DPUTS("txn has failed/finished, can't commit");
3450 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3455 if (txn->mt_parent) {
3456 MDB_txn *parent = txn->mt_parent;
3460 unsigned x, y, len, ps_len;
3462 /* Append our free list to parent's */
3463 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3466 mdb_midl_free(txn->mt_free_pgs);
3467 /* Failures after this must either undo the changes
3468 * to the parent or set MDB_TXN_ERROR in the parent.
3471 parent->mt_next_pgno = txn->mt_next_pgno;
3472 parent->mt_flags = txn->mt_flags;
3474 /* Merge our cursors into parent's and close them */
3475 mdb_cursors_close(txn, 1);
3477 /* Update parent's DB table. */
3478 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3479 parent->mt_numdbs = txn->mt_numdbs;
3480 parent->mt_dbflags[FREE_DBI] = txn->mt_dbflags[FREE_DBI];
3481 parent->mt_dbflags[MAIN_DBI] = txn->mt_dbflags[MAIN_DBI];
3482 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
3483 /* preserve parent's DB_NEW status */
3484 x = parent->mt_dbflags[i] & DB_NEW;
3485 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3488 dst = parent->mt_u.dirty_list;
3489 src = txn->mt_u.dirty_list;
3490 /* Remove anything in our dirty list from parent's spill list */
3491 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3493 pspill[0] = (pgno_t)-1;
3494 /* Mark our dirty pages as deleted in parent spill list */
3495 for (i=0, len=src[0].mid; ++i <= len; ) {
3496 MDB_ID pn = src[i].mid << 1;
3497 while (pn > pspill[x])
3499 if (pn == pspill[x]) {
3504 /* Squash deleted pagenums if we deleted any */
3505 for (x=y; ++x <= ps_len; )
3506 if (!(pspill[x] & 1))
3507 pspill[++y] = pspill[x];
3511 /* Remove anything in our spill list from parent's dirty list */
3512 if (txn->mt_spill_pgs && txn->mt_spill_pgs[0]) {
3513 for (i=1; i<=txn->mt_spill_pgs[0]; i++) {
3514 MDB_ID pn = txn->mt_spill_pgs[i];
3516 continue; /* deleted spillpg */
3518 y = mdb_mid2l_search(dst, pn);
3519 if (y <= dst[0].mid && dst[y].mid == pn) {
3521 while (y < dst[0].mid) {
3530 /* Find len = length of merging our dirty list with parent's */
3532 dst[0].mid = 0; /* simplify loops */
3533 if (parent->mt_parent) {
3534 len = x + src[0].mid;
3535 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3536 for (i = x; y && i; y--) {
3537 pgno_t yp = src[y].mid;
3538 while (yp < dst[i].mid)
3540 if (yp == dst[i].mid) {
3545 } else { /* Simplify the above for single-ancestor case */
3546 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3548 /* Merge our dirty list with parent's */
3550 for (i = len; y; dst[i--] = src[y--]) {
3551 pgno_t yp = src[y].mid;
3552 while (yp < dst[x].mid)
3553 dst[i--] = dst[x--];
3554 if (yp == dst[x].mid)
3555 free(dst[x--].mptr);
3557 mdb_tassert(txn, i == x);
3559 free(txn->mt_u.dirty_list);
3560 parent->mt_dirty_room = txn->mt_dirty_room;
3561 if (txn->mt_spill_pgs) {
3562 if (parent->mt_spill_pgs) {
3563 /* TODO: Prevent failure here, so parent does not fail */
3564 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3566 parent->mt_flags |= MDB_TXN_ERROR;
3567 mdb_midl_free(txn->mt_spill_pgs);
3568 mdb_midl_sort(parent->mt_spill_pgs);
3570 parent->mt_spill_pgs = txn->mt_spill_pgs;
3574 /* Append our loose page list to parent's */
3575 for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(*lp))
3577 *lp = txn->mt_loose_pgs;
3578 parent->mt_loose_count += txn->mt_loose_count;
3580 parent->mt_child = NULL;
3581 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3586 if (txn != env->me_txn) {
3587 DPUTS("attempt to commit unknown transaction");
3592 mdb_cursors_close(txn, 0);
3594 if (!txn->mt_u.dirty_list[0].mid &&
3595 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
3598 DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
3599 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3601 /* Update DB root pointers */
3602 if (txn->mt_numdbs > CORE_DBS) {
3606 data.mv_size = sizeof(MDB_db);
3608 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3609 for (i = CORE_DBS; i < txn->mt_numdbs; i++) {
3610 if (txn->mt_dbflags[i] & DB_DIRTY) {
3611 if (TXN_DBI_CHANGED(txn, i)) {
3615 data.mv_data = &txn->mt_dbs[i];
3616 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data,
3624 rc = mdb_freelist_save(txn);
3628 mdb_midl_free(env->me_pghead);
3629 env->me_pghead = NULL;
3630 mdb_midl_shrink(&txn->mt_free_pgs);
3636 if ((rc = mdb_page_flush(txn, 0)))
3638 if (!F_ISSET(txn->mt_flags, MDB_TXN_NOSYNC) &&
3639 (rc = mdb_env_sync(env, 0)))
3641 if ((rc = mdb_env_write_meta(txn)))
3643 end_mode = MDB_END_COMMITTED|MDB_END_UPDATE;
3646 mdb_txn_end(txn, end_mode);
3654 /** Read the environment parameters of a DB environment before
3655 * mapping it into memory.
3656 * @param[in] env the environment handle
3657 * @param[out] meta address of where to store the meta information
3658 * @return 0 on success, non-zero on failure.
3661 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3667 enum { Size = sizeof(pbuf) };
3669 /* We don't know the page size yet, so use a minimum value.
3670 * Read both meta pages so we can use the latest one.
3673 for (i=off=0; i<NUM_METAS; i++, off += meta->mm_psize) {
3677 memset(&ov, 0, sizeof(ov));
3679 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3680 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3683 rc = pread(env->me_fd, &pbuf, Size, off);
3686 if (rc == 0 && off == 0)
3688 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3689 DPRINTF(("read: %s", mdb_strerror(rc)));
3693 p = (MDB_page *)&pbuf;
3695 if (!F_ISSET(p->mp_flags, P_META)) {
3696 DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
3701 if (m->mm_magic != MDB_MAGIC) {
3702 DPUTS("meta has invalid magic");
3706 if (m->mm_version != MDB_DATA_VERSION) {
3707 DPRINTF(("database is version %u, expected version %u",
3708 m->mm_version, MDB_DATA_VERSION));
3709 return MDB_VERSION_MISMATCH;
3712 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3718 /** Fill in most of the zeroed #MDB_meta for an empty database environment */
3720 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
3722 meta->mm_magic = MDB_MAGIC;
3723 meta->mm_version = MDB_DATA_VERSION;
3724 meta->mm_mapsize = env->me_mapsize;
3725 meta->mm_psize = env->me_psize;
3726 meta->mm_last_pg = NUM_METAS-1;
3727 meta->mm_flags = env->me_flags & 0xffff;
3728 meta->mm_flags |= MDB_INTEGERKEY; /* this is mm_dbs[FREE_DBI].md_flags */
3729 meta->mm_dbs[FREE_DBI].md_root = P_INVALID;
3730 meta->mm_dbs[MAIN_DBI].md_root = P_INVALID;
3733 /** Write the environment parameters of a freshly created DB environment.
3734 * @param[in] env the environment handle
3735 * @param[in] meta the #MDB_meta to write
3736 * @return 0 on success, non-zero on failure.
3739 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3747 memset(&ov, 0, sizeof(ov));
3748 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3750 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3753 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3754 len = pwrite(fd, ptr, size, pos); \
3755 if (len == -1 && ErrCode() == EINTR) continue; \
3756 rc = (len >= 0); break; } while(1)
3759 DPUTS("writing new meta page");
3761 psize = env->me_psize;
3763 p = calloc(NUM_METAS, psize);
3767 p->mp_flags = P_META;
3768 *(MDB_meta *)METADATA(p) = *meta;
3770 q = (MDB_page *)((char *)p + psize);
3772 q->mp_flags = P_META;
3773 *(MDB_meta *)METADATA(q) = *meta;
3775 DO_PWRITE(rc, env->me_fd, p, psize * NUM_METAS, len, 0);
3778 else if ((unsigned) len == psize * NUM_METAS)
3786 /** Update the environment info to commit a transaction.
3787 * @param[in] txn the transaction that's being committed
3788 * @return 0 on success, non-zero on failure.
3791 mdb_env_write_meta(MDB_txn *txn)
3794 MDB_meta meta, metab, *mp;
3798 int rc, len, toggle;
3807 toggle = txn->mt_txnid & 1;
3808 DPRINTF(("writing meta page %d for root page %"Z"u",
3809 toggle, txn->mt_dbs[MAIN_DBI].md_root));
3812 flags = txn->mt_flags | env->me_flags;
3813 mp = env->me_metas[toggle];
3814 mapsize = env->me_metas[toggle ^ 1]->mm_mapsize;
3815 /* Persist any increases of mapsize config */
3816 if (mapsize < env->me_mapsize)
3817 mapsize = env->me_mapsize;
3819 if (flags & MDB_WRITEMAP) {
3820 mp->mm_mapsize = mapsize;
3821 mp->mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
3822 mp->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
3823 mp->mm_last_pg = txn->mt_next_pgno - 1;
3824 #if (__GNUC__ * 100 + __GNUC_MINOR__ >= 404) && /* TODO: portability */ \
3825 !(defined(__i386__) || defined(__x86_64__))
3826 /* LY: issue a memory barrier, if not x86. ITS#7969 */
3827 __sync_synchronize();
3829 mp->mm_txnid = txn->mt_txnid;
3830 if (!(flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3831 unsigned meta_size = env->me_psize;
3832 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3833 ptr = (char *)mp - PAGEHDRSZ;
3834 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
3835 r2 = (ptr - env->me_map) & (env->me_os_psize - 1);
3839 if (MDB_MSYNC(ptr, meta_size, rc)) {
3846 metab.mm_txnid = mp->mm_txnid;
3847 metab.mm_last_pg = mp->mm_last_pg;
3849 meta.mm_mapsize = mapsize;
3850 meta.mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
3851 meta.mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
3852 meta.mm_last_pg = txn->mt_next_pgno - 1;
3853 meta.mm_txnid = txn->mt_txnid;
3855 off = offsetof(MDB_meta, mm_mapsize);
3856 ptr = (char *)&meta + off;
3857 len = sizeof(MDB_meta) - off;
3858 off += (char *)mp - env->me_map;
3860 /* Write to the SYNC fd */
3861 mfd = (flags & (MDB_NOSYNC|MDB_NOMETASYNC)) ? env->me_fd : env->me_mfd;
3864 memset(&ov, 0, sizeof(ov));
3866 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3871 rc = pwrite(mfd, ptr, len, off);
3874 rc = rc < 0 ? ErrCode() : EIO;
3879 DPUTS("write failed, disk error?");
3880 /* On a failure, the pagecache still contains the new data.
3881 * Write some old data back, to prevent it from being used.
3882 * Use the non-SYNC fd; we know it will fail anyway.
3884 meta.mm_last_pg = metab.mm_last_pg;
3885 meta.mm_txnid = metab.mm_txnid;
3887 memset(&ov, 0, sizeof(ov));
3889 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3891 r2 = pwrite(env->me_fd, ptr, len, off);
3892 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
3895 env->me_flags |= MDB_FATAL_ERROR;
3898 /* MIPS has cache coherency issues, this is a no-op everywhere else */
3899 CACHEFLUSH(env->me_map + off, len, DCACHE);
3901 /* Memory ordering issues are irrelevant; since the entire writer
3902 * is wrapped by wmutex, all of these changes will become visible
3903 * after the wmutex is unlocked. Since the DB is multi-version,
3904 * readers will get consistent data regardless of how fresh or
3905 * how stale their view of these values is.
3908 env->me_txns->mti_txnid = txn->mt_txnid;
3913 /** Check both meta pages to see which one is newer.
3914 * @param[in] env the environment handle
3915 * @return newest #MDB_meta.
3918 mdb_env_pick_meta(const MDB_env *env)
3920 MDB_meta *const *metas = env->me_metas;
3921 return metas[ metas[0]->mm_txnid < metas[1]->mm_txnid ];
3925 mdb_env_create(MDB_env **env)
3929 e = calloc(1, sizeof(MDB_env));
3933 e->me_maxreaders = DEFAULT_READERS;
3934 e->me_maxdbs = e->me_numdbs = CORE_DBS;
3935 e->me_fd = INVALID_HANDLE_VALUE;
3936 e->me_lfd = INVALID_HANDLE_VALUE;
3937 e->me_mfd = INVALID_HANDLE_VALUE;
3938 #ifdef MDB_USE_POSIX_SEM
3939 e->me_rmutex = SEM_FAILED;
3940 e->me_wmutex = SEM_FAILED;
3941 #elif defined MDB_USE_SYSV_SEM
3942 e->me_rmutex->semid = -1;
3943 e->me_wmutex->semid = -1;
3945 e->me_pid = getpid();
3946 GET_PAGESIZE(e->me_os_psize);
3947 VGMEMP_CREATE(e,0,0);
3953 mdb_env_map(MDB_env *env, void *addr)
3956 unsigned int flags = env->me_flags;
3960 LONG sizelo, sizehi;
3963 if (flags & MDB_RDONLY) {
3964 /* Don't set explicit map size, use whatever exists */
3969 msize = env->me_mapsize;
3970 sizelo = msize & 0xffffffff;
3971 sizehi = msize >> 16 >> 16; /* only needed on Win64 */
3973 /* Windows won't create mappings for zero length files.
3974 * and won't map more than the file size.
3975 * Just set the maxsize right now.
3977 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3978 || !SetEndOfFile(env->me_fd)
3979 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3983 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3984 PAGE_READWRITE : PAGE_READONLY,
3985 sizehi, sizelo, NULL);
3988 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3989 FILE_MAP_WRITE : FILE_MAP_READ,
3991 rc = env->me_map ? 0 : ErrCode();
3996 int prot = PROT_READ;
3997 if (flags & MDB_WRITEMAP) {
3999 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
4002 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
4004 if (env->me_map == MAP_FAILED) {
4009 if (flags & MDB_NORDAHEAD) {
4010 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
4012 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
4014 #ifdef POSIX_MADV_RANDOM
4015 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
4016 #endif /* POSIX_MADV_RANDOM */
4017 #endif /* MADV_RANDOM */
4021 /* Can happen because the address argument to mmap() is just a
4022 * hint. mmap() can pick another, e.g. if the range is in use.
4023 * The MAP_FIXED flag would prevent that, but then mmap could
4024 * instead unmap existing pages to make room for the new map.
4026 if (addr && env->me_map != addr)
4027 return EBUSY; /* TODO: Make a new MDB_* error code? */
4029 p = (MDB_page *)env->me_map;
4030 env->me_metas[0] = METADATA(p);
4031 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
4037 mdb_env_set_mapsize(MDB_env *env, size_t size)
4039 /* If env is already open, caller is responsible for making
4040 * sure there are no active txns.
4048 meta = mdb_env_pick_meta(env);
4050 size = meta->mm_mapsize;
4052 /* Silently round up to minimum if the size is too small */
4053 size_t minsize = (meta->mm_last_pg + 1) * env->me_psize;
4057 munmap(env->me_map, env->me_mapsize);
4058 env->me_mapsize = size;
4059 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
4060 rc = mdb_env_map(env, old);
4064 env->me_mapsize = size;
4066 env->me_maxpg = env->me_mapsize / env->me_psize;
4071 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
4075 env->me_maxdbs = dbs + CORE_DBS;
4080 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
4082 if (env->me_map || readers < 1)
4084 env->me_maxreaders = readers;
4089 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
4091 if (!env || !readers)
4093 *readers = env->me_maxreaders;
4098 mdb_fsize(HANDLE fd, size_t *size)
4101 LARGE_INTEGER fsize;
4103 if (!GetFileSizeEx(fd, &fsize))
4106 *size = fsize.QuadPart;
4118 #ifdef BROKEN_FDATASYNC
4119 #include <sys/utsname.h>
4120 #include <sys/vfs.h>
4123 /** Further setup required for opening an LMDB environment
4126 mdb_env_open2(MDB_env *env)
4128 unsigned int flags = env->me_flags;
4129 int i, newenv = 0, rc;
4133 /* See if we should use QueryLimited */
4135 if ((rc & 0xff) > 5)
4136 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
4138 env->me_pidquery = PROCESS_QUERY_INFORMATION;
4141 #ifdef BROKEN_FDATASYNC
4142 /* ext3/ext4 fdatasync is broken on some older Linux kernels.
4143 * https://lkml.org/lkml/2012/9/3/83
4144 * Kernels after 3.6-rc6 are known good.
4145 * https://lkml.org/lkml/2012/9/10/556
4146 * See if the DB is on ext3/ext4, then check for new enough kernel
4147 * Kernels 2.6.32.60, 2.6.34.15, 3.2.30, and 3.5.4 are also known
4152 fstatfs(env->me_fd, &st);
4153 while (st.f_type == 0xEF53) {
4157 if (uts.release[0] < '3') {
4158 if (!strncmp(uts.release, "2.6.32.", 7)) {
4159 i = atoi(uts.release+7);
4161 break; /* 2.6.32.60 and newer is OK */
4162 } else if (!strncmp(uts.release, "2.6.34.", 7)) {
4163 i = atoi(uts.release+7);
4165 break; /* 2.6.34.15 and newer is OK */
4167 } else if (uts.release[0] == '3') {
4168 i = atoi(uts.release+2);
4170 break; /* 3.6 and newer is OK */
4172 i = atoi(uts.release+4);
4174 break; /* 3.5.4 and newer is OK */
4175 } else if (i == 2) {
4176 i = atoi(uts.release+4);
4178 break; /* 3.2.30 and newer is OK */
4180 } else { /* 4.x and newer is OK */
4183 env->me_flags |= MDB_FSYNCONLY;
4189 if ((i = mdb_env_read_header(env, &meta)) != 0) {
4192 DPUTS("new mdbenv");
4194 env->me_psize = env->me_os_psize;
4195 if (env->me_psize > MAX_PAGESIZE)
4196 env->me_psize = MAX_PAGESIZE;
4197 memset(&meta, 0, sizeof(meta));
4198 mdb_env_init_meta0(env, &meta);
4199 meta.mm_mapsize = DEFAULT_MAPSIZE;
4201 env->me_psize = meta.mm_psize;
4204 /* Was a mapsize configured? */
4205 if (!env->me_mapsize) {
4206 env->me_mapsize = meta.mm_mapsize;
4209 /* Make sure mapsize >= committed data size. Even when using
4210 * mm_mapsize, which could be broken in old files (ITS#7789).
4212 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
4213 if (env->me_mapsize < minsize)
4214 env->me_mapsize = minsize;
4216 meta.mm_mapsize = env->me_mapsize;
4218 if (newenv && !(flags & MDB_FIXEDMAP)) {
4219 /* mdb_env_map() may grow the datafile. Write the metapages
4220 * first, so the file will be valid if initialization fails.
4221 * Except with FIXEDMAP, since we do not yet know mm_address.
4222 * We could fill in mm_address later, but then a different
4223 * program might end up doing that - one with a memory layout
4224 * and map address which does not suit the main program.
4226 rc = mdb_env_init_meta(env, &meta);
4232 rc = mdb_env_map(env, (flags & MDB_FIXEDMAP) ? meta.mm_address : NULL);
4237 if (flags & MDB_FIXEDMAP)
4238 meta.mm_address = env->me_map;
4239 i = mdb_env_init_meta(env, &meta);
4240 if (i != MDB_SUCCESS) {
4245 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
4246 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
4248 #if !(MDB_MAXKEYSIZE)
4249 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
4251 env->me_maxpg = env->me_mapsize / env->me_psize;
4255 MDB_meta *meta = mdb_env_pick_meta(env);
4256 MDB_db *db = &meta->mm_dbs[MAIN_DBI];
4258 DPRINTF(("opened database version %u, pagesize %u",
4259 meta->mm_version, env->me_psize));
4260 DPRINTF(("using meta page %d", (int) (meta->mm_txnid & 1)));
4261 DPRINTF(("depth: %u", db->md_depth));
4262 DPRINTF(("entries: %"Z"u", db->md_entries));
4263 DPRINTF(("branch pages: %"Z"u", db->md_branch_pages));
4264 DPRINTF(("leaf pages: %"Z"u", db->md_leaf_pages));
4265 DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
4266 DPRINTF(("root: %"Z"u", db->md_root));
4274 /** Release a reader thread's slot in the reader lock table.
4275 * This function is called automatically when a thread exits.
4276 * @param[in] ptr This points to the slot in the reader lock table.
4279 mdb_env_reader_dest(void *ptr)
4281 MDB_reader *reader = ptr;
4287 /** Junk for arranging thread-specific callbacks on Windows. This is
4288 * necessarily platform and compiler-specific. Windows supports up
4289 * to 1088 keys. Let's assume nobody opens more than 64 environments
4290 * in a single process, for now. They can override this if needed.
4292 #ifndef MAX_TLS_KEYS
4293 #define MAX_TLS_KEYS 64
4295 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
4296 static int mdb_tls_nkeys;
4298 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
4302 case DLL_PROCESS_ATTACH: break;
4303 case DLL_THREAD_ATTACH: break;
4304 case DLL_THREAD_DETACH:
4305 for (i=0; i<mdb_tls_nkeys; i++) {
4306 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
4308 mdb_env_reader_dest(r);
4312 case DLL_PROCESS_DETACH: break;
4317 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4319 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4323 /* Force some symbol references.
4324 * _tls_used forces the linker to create the TLS directory if not already done
4325 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
4327 #pragma comment(linker, "/INCLUDE:_tls_used")
4328 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
4329 #pragma const_seg(".CRT$XLB")
4330 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
4331 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4334 #pragma comment(linker, "/INCLUDE:__tls_used")
4335 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
4336 #pragma data_seg(".CRT$XLB")
4337 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4339 #endif /* WIN 32/64 */
4340 #endif /* !__GNUC__ */
4343 /** Downgrade the exclusive lock on the region back to shared */
4345 mdb_env_share_locks(MDB_env *env, int *excl)
4348 MDB_meta *meta = mdb_env_pick_meta(env);
4350 env->me_txns->mti_txnid = meta->mm_txnid;
4355 /* First acquire a shared lock. The Unlock will
4356 * then release the existing exclusive lock.
4358 memset(&ov, 0, sizeof(ov));
4359 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4362 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4368 struct flock lock_info;
4369 /* The shared lock replaces the existing lock */
4370 memset((void *)&lock_info, 0, sizeof(lock_info));
4371 lock_info.l_type = F_RDLCK;
4372 lock_info.l_whence = SEEK_SET;
4373 lock_info.l_start = 0;
4374 lock_info.l_len = 1;
4375 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4376 (rc = ErrCode()) == EINTR) ;
4377 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
4384 /** Try to get exclusive lock, otherwise shared.
4385 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
4388 mdb_env_excl_lock(MDB_env *env, int *excl)
4392 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
4396 memset(&ov, 0, sizeof(ov));
4397 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4404 struct flock lock_info;
4405 memset((void *)&lock_info, 0, sizeof(lock_info));
4406 lock_info.l_type = F_WRLCK;
4407 lock_info.l_whence = SEEK_SET;
4408 lock_info.l_start = 0;
4409 lock_info.l_len = 1;
4410 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4411 (rc = ErrCode()) == EINTR) ;
4415 # ifndef MDB_USE_POSIX_MUTEX
4416 if (*excl < 0) /* always true when MDB_USE_POSIX_MUTEX */
4419 lock_info.l_type = F_RDLCK;
4420 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
4421 (rc = ErrCode()) == EINTR) ;
4431 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
4433 * @(#) $Revision: 5.1 $
4434 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
4435 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
4437 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
4441 * Please do not copyright this code. This code is in the public domain.
4443 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
4444 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
4445 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
4446 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
4447 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4448 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4449 * PERFORMANCE OF THIS SOFTWARE.
4452 * chongo <Landon Curt Noll> /\oo/\
4453 * http://www.isthe.com/chongo/
4455 * Share and Enjoy! :-)
4458 typedef unsigned long long mdb_hash_t;
4459 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
4461 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
4462 * @param[in] val value to hash
4463 * @param[in] hval initial value for hash
4464 * @return 64 bit hash
4466 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
4467 * hval arg on the first call.
4470 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
4472 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
4473 unsigned char *end = s + val->mv_size;
4475 * FNV-1a hash each octet of the string
4478 /* xor the bottom with the current octet */
4479 hval ^= (mdb_hash_t)*s++;
4481 /* multiply by the 64 bit FNV magic prime mod 2^64 */
4482 hval += (hval << 1) + (hval << 4) + (hval << 5) +
4483 (hval << 7) + (hval << 8) + (hval << 40);
4485 /* return our new hash value */
4489 /** Hash the string and output the encoded hash.
4490 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
4491 * very short name limits. We don't care about the encoding being reversible,
4492 * we just want to preserve as many bits of the input as possible in a
4493 * small printable string.
4494 * @param[in] str string to hash
4495 * @param[out] encbuf an array of 11 chars to hold the hash
4497 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
4500 mdb_pack85(unsigned long l, char *out)
4504 for (i=0; i<5; i++) {
4505 *out++ = mdb_a85[l % 85];
4511 mdb_hash_enc(MDB_val *val, char *encbuf)
4513 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
4515 mdb_pack85(h, encbuf);
4516 mdb_pack85(h>>32, encbuf+5);
4521 /** Open and/or initialize the lock region for the environment.
4522 * @param[in] env The LMDB environment.
4523 * @param[in] lpath The pathname of the file used for the lock region.
4524 * @param[in] mode The Unix permissions for the file, if we create it.
4525 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
4526 * @return 0 on success, non-zero on failure.
4529 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
4532 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
4534 # define MDB_ERRCODE_ROFS EROFS
4535 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
4536 # define MDB_CLOEXEC O_CLOEXEC
4539 # define MDB_CLOEXEC 0
4542 #ifdef MDB_USE_SYSV_SEM
4551 utf8_to_utf16(lpath, -1, &wlpath, NULL);
4552 env->me_lfd = CreateFileW(wlpath, GENERIC_READ|GENERIC_WRITE,
4553 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
4554 FILE_ATTRIBUTE_NORMAL, NULL);
4557 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
4559 if (env->me_lfd == INVALID_HANDLE_VALUE) {
4561 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
4566 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
4567 /* Lose record locks when exec*() */
4568 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
4569 fcntl(env->me_lfd, F_SETFD, fdflags);
4572 if (!(env->me_flags & MDB_NOTLS)) {
4573 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
4576 env->me_flags |= MDB_ENV_TXKEY;
4578 /* Windows TLS callbacks need help finding their TLS info. */
4579 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
4583 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
4587 /* Try to get exclusive lock. If we succeed, then
4588 * nobody is using the lock region and we should initialize it.
4590 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
4593 size = GetFileSize(env->me_lfd, NULL);
4595 size = lseek(env->me_lfd, 0, SEEK_END);
4596 if (size == -1) goto fail_errno;
4598 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
4599 if (size < rsize && *excl > 0) {
4601 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
4602 || !SetEndOfFile(env->me_lfd))
4605 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
4609 size = rsize - sizeof(MDB_txninfo);
4610 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
4615 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
4617 if (!mh) goto fail_errno;
4618 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
4620 if (!env->me_txns) goto fail_errno;
4622 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
4624 if (m == MAP_FAILED) goto fail_errno;
4630 BY_HANDLE_FILE_INFORMATION stbuf;
4639 if (!mdb_sec_inited) {
4640 InitializeSecurityDescriptor(&mdb_null_sd,
4641 SECURITY_DESCRIPTOR_REVISION);
4642 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
4643 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
4644 mdb_all_sa.bInheritHandle = FALSE;
4645 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
4648 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
4649 idbuf.volume = stbuf.dwVolumeSerialNumber;
4650 idbuf.nhigh = stbuf.nFileIndexHigh;
4651 idbuf.nlow = stbuf.nFileIndexLow;
4652 val.mv_data = &idbuf;
4653 val.mv_size = sizeof(idbuf);
4654 mdb_hash_enc(&val, encbuf);
4655 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
4656 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
4657 env->me_rmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
4658 if (!env->me_rmutex) goto fail_errno;
4659 env->me_wmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
4660 if (!env->me_wmutex) goto fail_errno;
4661 #elif defined(MDB_USE_POSIX_SEM)
4670 #if defined(__NetBSD__)
4671 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
4673 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
4674 idbuf.dev = stbuf.st_dev;
4675 idbuf.ino = stbuf.st_ino;
4676 val.mv_data = &idbuf;
4677 val.mv_size = sizeof(idbuf);
4678 mdb_hash_enc(&val, encbuf);
4679 #ifdef MDB_SHORT_SEMNAMES
4680 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
4682 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
4683 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
4684 /* Clean up after a previous run, if needed: Try to
4685 * remove both semaphores before doing anything else.
4687 sem_unlink(env->me_txns->mti_rmname);
4688 sem_unlink(env->me_txns->mti_wmname);
4689 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
4690 O_CREAT|O_EXCL, mode, 1);
4691 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4692 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
4693 O_CREAT|O_EXCL, mode, 1);
4694 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4695 #elif defined(MDB_USE_SYSV_SEM)
4696 unsigned short vals[2] = {1, 1};
4697 key_t key = ftok(lpath, 'M');
4700 semid = semget(key, 2, (mode & 0777) | IPC_CREAT);
4704 if (semctl(semid, 0, SETALL, semu) < 0)
4706 env->me_txns->mti_semid = semid;
4707 #else /* MDB_USE_POSIX_MUTEX: */
4708 pthread_mutexattr_t mattr;
4710 if ((rc = pthread_mutexattr_init(&mattr))
4711 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
4712 #ifdef MDB_ROBUST_SUPPORTED
4713 || (rc = pthread_mutexattr_setrobust(&mattr, PTHREAD_MUTEX_ROBUST))
4715 || (rc = pthread_mutex_init(env->me_txns->mti_rmutex, &mattr))
4716 || (rc = pthread_mutex_init(env->me_txns->mti_wmutex, &mattr)))
4718 pthread_mutexattr_destroy(&mattr);
4719 #endif /* _WIN32 || ... */
4721 env->me_txns->mti_magic = MDB_MAGIC;
4722 env->me_txns->mti_format = MDB_LOCK_FORMAT;
4723 env->me_txns->mti_txnid = 0;
4724 env->me_txns->mti_numreaders = 0;
4727 #ifdef MDB_USE_SYSV_SEM
4728 struct semid_ds buf;
4730 if (env->me_txns->mti_magic != MDB_MAGIC) {
4731 DPUTS("lock region has invalid magic");
4735 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
4736 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
4737 env->me_txns->mti_format, MDB_LOCK_FORMAT));
4738 rc = MDB_VERSION_MISMATCH;
4742 if (rc && rc != EACCES && rc != EAGAIN) {
4746 env->me_rmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
4747 if (!env->me_rmutex) goto fail_errno;
4748 env->me_wmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
4749 if (!env->me_wmutex) goto fail_errno;
4750 #elif defined(MDB_USE_POSIX_SEM)
4751 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
4752 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4753 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
4754 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4755 #elif defined(MDB_USE_SYSV_SEM)
4756 semid = env->me_txns->mti_semid;
4758 /* check for read access */
4759 if (semctl(semid, 0, IPC_STAT, semu) < 0)
4761 /* check for write access */
4762 if (semctl(semid, 0, IPC_SET, semu) < 0)
4766 #ifdef MDB_USE_SYSV_SEM
4767 env->me_rmutex->semid = semid;
4768 env->me_wmutex->semid = semid;
4769 env->me_rmutex->semnum = 0;
4770 env->me_wmutex->semnum = 1;
4771 env->me_rmutex->locked = &env->me_txns->mti_rlocked;
4772 env->me_wmutex->locked = &env->me_txns->mti_wlocked;
4783 /** The name of the lock file in the DB environment */
4784 #define LOCKNAME "/lock.mdb"
4785 /** The name of the data file in the DB environment */
4786 #define DATANAME "/data.mdb"
4787 /** The suffix of the lock file when no subdir is used */
4788 #define LOCKSUFF "-lock"
4789 /** Only a subset of the @ref mdb_env flags can be changed
4790 * at runtime. Changing other flags requires closing the
4791 * environment and re-opening it with the new flags.
4793 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
4794 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY| \
4795 MDB_WRITEMAP|MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
4797 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
4798 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
4802 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
4804 int oflags, rc, len, excl = -1;
4805 char *lpath, *dpath;
4810 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
4814 if (flags & MDB_NOSUBDIR) {
4815 rc = len + sizeof(LOCKSUFF) + len + 1;
4817 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
4822 if (flags & MDB_NOSUBDIR) {
4823 dpath = lpath + len + sizeof(LOCKSUFF);
4824 sprintf(lpath, "%s" LOCKSUFF, path);
4825 strcpy(dpath, path);
4827 dpath = lpath + len + sizeof(LOCKNAME);
4828 sprintf(lpath, "%s" LOCKNAME, path);
4829 sprintf(dpath, "%s" DATANAME, path);
4833 flags |= env->me_flags;
4834 if (flags & MDB_RDONLY) {
4835 /* silently ignore WRITEMAP when we're only getting read access */
4836 flags &= ~MDB_WRITEMAP;
4838 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
4839 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
4842 env->me_flags = flags |= MDB_ENV_ACTIVE;
4846 env->me_path = strdup(path);
4847 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
4848 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
4849 env->me_dbiseqs = calloc(env->me_maxdbs, sizeof(unsigned int));
4850 if (!(env->me_dbxs && env->me_path && env->me_dbflags && env->me_dbiseqs)) {
4854 env->me_dbxs[FREE_DBI].md_cmp = mdb_cmp_long; /* aligned MDB_INTEGERKEY */
4856 /* For RDONLY, get lockfile after we know datafile exists */
4857 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
4858 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4864 if (F_ISSET(flags, MDB_RDONLY)) {
4865 oflags = GENERIC_READ;
4866 len = OPEN_EXISTING;
4868 oflags = GENERIC_READ|GENERIC_WRITE;
4871 mode = FILE_ATTRIBUTE_NORMAL;
4872 utf8_to_utf16(dpath, -1, &wpath, NULL);
4873 env->me_fd = CreateFileW(wpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
4874 NULL, len, mode, NULL);
4877 if (F_ISSET(flags, MDB_RDONLY))
4880 oflags = O_RDWR | O_CREAT;
4882 env->me_fd = open(dpath, oflags, mode);
4884 if (env->me_fd == INVALID_HANDLE_VALUE) {
4889 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
4890 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4895 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
4896 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
4897 env->me_mfd = env->me_fd;
4899 /* Synchronous fd for meta writes. Needed even with
4900 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
4903 len = OPEN_EXISTING;
4904 utf8_to_utf16(dpath, -1, &wpath, NULL);
4905 env->me_mfd = CreateFileW(wpath, oflags,
4906 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
4907 mode | FILE_FLAG_WRITE_THROUGH, NULL);
4911 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
4913 if (env->me_mfd == INVALID_HANDLE_VALUE) {
4918 DPRINTF(("opened dbenv %p", (void *) env));
4920 rc = mdb_env_share_locks(env, &excl);
4924 if (!(flags & MDB_RDONLY)) {
4926 int tsize = sizeof(MDB_txn), size = tsize + env->me_maxdbs *
4927 (sizeof(MDB_db)+sizeof(MDB_cursor *)+sizeof(unsigned int)+1);
4928 if ((env->me_pbuf = calloc(1, env->me_psize)) &&
4929 (txn = calloc(1, size)))
4931 txn->mt_dbs = (MDB_db *)((char *)txn + tsize);
4932 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
4933 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
4934 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
4936 txn->mt_dbxs = env->me_dbxs;
4937 txn->mt_flags = MDB_TXN_FINISHED;
4947 mdb_env_close0(env, excl);
4953 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
4955 mdb_env_close0(MDB_env *env, int excl)
4959 if (!(env->me_flags & MDB_ENV_ACTIVE))
4962 /* Doing this here since me_dbxs may not exist during mdb_env_close */
4964 for (i = env->me_maxdbs; --i >= CORE_DBS; )
4965 free(env->me_dbxs[i].md_name.mv_data);
4970 free(env->me_dbiseqs);
4971 free(env->me_dbflags);
4973 free(env->me_dirty_list);
4975 mdb_midl_free(env->me_free_pgs);
4977 if (env->me_flags & MDB_ENV_TXKEY) {
4978 pthread_key_delete(env->me_txkey);
4980 /* Delete our key from the global list */
4981 for (i=0; i<mdb_tls_nkeys; i++)
4982 if (mdb_tls_keys[i] == env->me_txkey) {
4983 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
4991 munmap(env->me_map, env->me_mapsize);
4993 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
4994 (void) close(env->me_mfd);
4995 if (env->me_fd != INVALID_HANDLE_VALUE)
4996 (void) close(env->me_fd);
4998 MDB_PID_T pid = env->me_pid;
4999 /* Clearing readers is done in this function because
5000 * me_txkey with its destructor must be disabled first.
5002 * We skip the the reader mutex, so we touch only
5003 * data owned by this process (me_close_readers and
5004 * our readers), and clear each reader atomically.
5006 for (i = env->me_close_readers; --i >= 0; )
5007 if (env->me_txns->mti_readers[i].mr_pid == pid)
5008 env->me_txns->mti_readers[i].mr_pid = 0;
5010 if (env->me_rmutex) {
5011 CloseHandle(env->me_rmutex);
5012 if (env->me_wmutex) CloseHandle(env->me_wmutex);
5014 /* Windows automatically destroys the mutexes when
5015 * the last handle closes.
5017 #elif defined(MDB_USE_POSIX_SEM)
5018 if (env->me_rmutex != SEM_FAILED) {
5019 sem_close(env->me_rmutex);
5020 if (env->me_wmutex != SEM_FAILED)
5021 sem_close(env->me_wmutex);
5022 /* If we have the filelock: If we are the
5023 * only remaining user, clean up semaphores.
5026 mdb_env_excl_lock(env, &excl);
5028 sem_unlink(env->me_txns->mti_rmname);
5029 sem_unlink(env->me_txns->mti_wmname);
5032 #elif defined(MDB_USE_SYSV_SEM)
5033 if (env->me_rmutex->semid != -1) {
5034 /* If we have the filelock: If we are the
5035 * only remaining user, clean up semaphores.
5038 mdb_env_excl_lock(env, &excl);
5040 semctl(env->me_rmutex->semid, 0, IPC_RMID);
5043 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
5045 if (env->me_lfd != INVALID_HANDLE_VALUE) {
5048 /* Unlock the lockfile. Windows would have unlocked it
5049 * after closing anyway, but not necessarily at once.
5051 UnlockFile(env->me_lfd, 0, 0, 1, 0);
5054 (void) close(env->me_lfd);
5057 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
5061 mdb_env_close(MDB_env *env)
5068 VGMEMP_DESTROY(env);
5069 while ((dp = env->me_dpages) != NULL) {
5070 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
5071 env->me_dpages = dp->mp_next;
5075 mdb_env_close0(env, 0);
5079 /** Compare two items pointing at aligned size_t's */
5081 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
5083 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
5084 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
5087 /** Compare two items pointing at aligned unsigned int's.
5089 * This is also set as #MDB_INTEGERDUP|#MDB_DUPFIXED's #MDB_dbx.%md_dcmp,
5090 * but #mdb_cmp_clong() is called instead if the data type is size_t.
5093 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
5095 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
5096 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
5099 /** Compare two items pointing at unsigned ints of unknown alignment.
5100 * Nodes and keys are guaranteed to be 2-byte aligned.
5103 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
5105 #if BYTE_ORDER == LITTLE_ENDIAN
5106 unsigned short *u, *c;
5109 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5110 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
5113 } while(!x && u > (unsigned short *)a->mv_data);
5116 unsigned short *u, *c, *end;
5119 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5120 u = (unsigned short *)a->mv_data;
5121 c = (unsigned short *)b->mv_data;
5124 } while(!x && u < end);
5129 /** Compare two items lexically */
5131 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
5138 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5144 diff = memcmp(a->mv_data, b->mv_data, len);
5145 return diff ? diff : len_diff<0 ? -1 : len_diff;
5148 /** Compare two items in reverse byte order */
5150 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
5152 const unsigned char *p1, *p2, *p1_lim;
5156 p1_lim = (const unsigned char *)a->mv_data;
5157 p1 = (const unsigned char *)a->mv_data + a->mv_size;
5158 p2 = (const unsigned char *)b->mv_data + b->mv_size;
5160 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5166 while (p1 > p1_lim) {
5167 diff = *--p1 - *--p2;
5171 return len_diff<0 ? -1 : len_diff;
5174 /** Search for key within a page, using binary search.
5175 * Returns the smallest entry larger or equal to the key.
5176 * If exactp is non-null, stores whether the found entry was an exact match
5177 * in *exactp (1 or 0).
5178 * Updates the cursor index with the index of the found entry.
5179 * If no entry larger or equal to the key is found, returns NULL.
5182 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
5184 unsigned int i = 0, nkeys;
5187 MDB_page *mp = mc->mc_pg[mc->mc_top];
5188 MDB_node *node = NULL;
5193 nkeys = NUMKEYS(mp);
5195 DPRINTF(("searching %u keys in %s %spage %"Z"u",
5196 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
5199 low = IS_LEAF(mp) ? 0 : 1;
5201 cmp = mc->mc_dbx->md_cmp;
5203 /* Branch pages have no data, so if using integer keys,
5204 * alignment is guaranteed. Use faster mdb_cmp_int.
5206 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
5207 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
5214 nodekey.mv_size = mc->mc_db->md_pad;
5215 node = NODEPTR(mp, 0); /* fake */
5216 while (low <= high) {
5217 i = (low + high) >> 1;
5218 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
5219 rc = cmp(key, &nodekey);
5220 DPRINTF(("found leaf index %u [%s], rc = %i",
5221 i, DKEY(&nodekey), rc));
5230 while (low <= high) {
5231 i = (low + high) >> 1;
5233 node = NODEPTR(mp, i);
5234 nodekey.mv_size = NODEKSZ(node);
5235 nodekey.mv_data = NODEKEY(node);
5237 rc = cmp(key, &nodekey);
5240 DPRINTF(("found leaf index %u [%s], rc = %i",
5241 i, DKEY(&nodekey), rc));
5243 DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
5244 i, DKEY(&nodekey), NODEPGNO(node), rc));
5255 if (rc > 0) { /* Found entry is less than the key. */
5256 i++; /* Skip to get the smallest entry larger than key. */
5258 node = NODEPTR(mp, i);
5261 *exactp = (rc == 0 && nkeys > 0);
5262 /* store the key index */
5263 mc->mc_ki[mc->mc_top] = i;
5265 /* There is no entry larger or equal to the key. */
5268 /* nodeptr is fake for LEAF2 */
5274 mdb_cursor_adjust(MDB_cursor *mc, func)
5278 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5279 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
5286 /** Pop a page off the top of the cursor's stack. */
5288 mdb_cursor_pop(MDB_cursor *mc)
5291 DPRINTF(("popping page %"Z"u off db %d cursor %p",
5292 mc->mc_pg[mc->mc_top]->mp_pgno, DDBI(mc), (void *) mc));
5298 mc->mc_flags &= ~C_INITIALIZED;
5303 /** Push a page onto the top of the cursor's stack. */
5305 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
5307 DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
5308 DDBI(mc), (void *) mc));
5310 if (mc->mc_snum >= CURSOR_STACK) {
5311 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5312 return MDB_CURSOR_FULL;
5315 mc->mc_top = mc->mc_snum++;
5316 mc->mc_pg[mc->mc_top] = mp;
5317 mc->mc_ki[mc->mc_top] = 0;
5322 /** Find the address of the page corresponding to a given page number.
5323 * @param[in] txn the transaction for this access.
5324 * @param[in] pgno the page number for the page to retrieve.
5325 * @param[out] ret address of a pointer where the page's address will be stored.
5326 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
5327 * @return 0 on success, non-zero on failure.
5330 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
5332 MDB_env *env = txn->mt_env;
5336 if (! (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_WRITEMAP))) {
5340 MDB_ID2L dl = tx2->mt_u.dirty_list;
5342 /* Spilled pages were dirtied in this txn and flushed
5343 * because the dirty list got full. Bring this page
5344 * back in from the map (but don't unspill it here,
5345 * leave that unless page_touch happens again).
5347 if (tx2->mt_spill_pgs) {
5348 MDB_ID pn = pgno << 1;
5349 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
5350 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
5351 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5356 unsigned x = mdb_mid2l_search(dl, pgno);
5357 if (x <= dl[0].mid && dl[x].mid == pgno) {
5363 } while ((tx2 = tx2->mt_parent) != NULL);
5366 if (pgno < txn->mt_next_pgno) {
5368 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5370 DPRINTF(("page %"Z"u not found", pgno));
5371 txn->mt_flags |= MDB_TXN_ERROR;
5372 return MDB_PAGE_NOTFOUND;
5382 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
5383 * The cursor is at the root page, set up the rest of it.
5386 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
5388 MDB_page *mp = mc->mc_pg[mc->mc_top];
5392 while (IS_BRANCH(mp)) {
5396 DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
5397 mdb_cassert(mc, NUMKEYS(mp) > 1);
5398 DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
5400 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
5402 if (flags & MDB_PS_LAST)
5403 i = NUMKEYS(mp) - 1;
5406 node = mdb_node_search(mc, key, &exact);
5408 i = NUMKEYS(mp) - 1;
5410 i = mc->mc_ki[mc->mc_top];
5412 mdb_cassert(mc, i > 0);
5416 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
5419 mdb_cassert(mc, i < NUMKEYS(mp));
5420 node = NODEPTR(mp, i);
5422 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
5425 mc->mc_ki[mc->mc_top] = i;
5426 if ((rc = mdb_cursor_push(mc, mp)))
5429 if (flags & MDB_PS_MODIFY) {
5430 if ((rc = mdb_page_touch(mc)) != 0)
5432 mp = mc->mc_pg[mc->mc_top];
5437 DPRINTF(("internal error, index points to a %02X page!?",
5439 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5440 return MDB_CORRUPTED;
5443 DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
5444 key ? DKEY(key) : "null"));
5445 mc->mc_flags |= C_INITIALIZED;
5446 mc->mc_flags &= ~C_EOF;
5451 /** Search for the lowest key under the current branch page.
5452 * This just bypasses a NUMKEYS check in the current page
5453 * before calling mdb_page_search_root(), because the callers
5454 * are all in situations where the current page is known to
5458 mdb_page_search_lowest(MDB_cursor *mc)
5460 MDB_page *mp = mc->mc_pg[mc->mc_top];
5461 MDB_node *node = NODEPTR(mp, 0);
5464 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
5467 mc->mc_ki[mc->mc_top] = 0;
5468 if ((rc = mdb_cursor_push(mc, mp)))
5470 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
5473 /** Search for the page a given key should be in.
5474 * Push it and its parent pages on the cursor stack.
5475 * @param[in,out] mc the cursor for this operation.
5476 * @param[in] key the key to search for, or NULL for first/last page.
5477 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
5478 * are touched (updated with new page numbers).
5479 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
5480 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
5481 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
5482 * @return 0 on success, non-zero on failure.
5485 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
5490 /* Make sure the txn is still viable, then find the root from
5491 * the txn's db table and set it as the root of the cursor's stack.
5493 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED) {
5494 DPUTS("transaction may not be used now");
5497 /* Make sure we're using an up-to-date root */
5498 if (*mc->mc_dbflag & DB_STALE) {
5500 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
5502 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
5503 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
5510 MDB_node *leaf = mdb_node_search(&mc2,
5511 &mc->mc_dbx->md_name, &exact);
5513 return MDB_NOTFOUND;
5514 if ((leaf->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
5515 return MDB_INCOMPATIBLE; /* not a named DB */
5516 rc = mdb_node_read(mc->mc_txn, leaf, &data);
5519 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
5521 /* The txn may not know this DBI, or another process may
5522 * have dropped and recreated the DB with other flags.
5524 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
5525 return MDB_INCOMPATIBLE;
5526 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
5528 *mc->mc_dbflag &= ~DB_STALE;
5530 root = mc->mc_db->md_root;
5532 if (root == P_INVALID) { /* Tree is empty. */
5533 DPUTS("tree is empty");
5534 return MDB_NOTFOUND;
5538 mdb_cassert(mc, root > 1);
5539 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
5540 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0], NULL)) != 0)
5546 DPRINTF(("db %d root page %"Z"u has flags 0x%X",
5547 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
5549 if (flags & MDB_PS_MODIFY) {
5550 if ((rc = mdb_page_touch(mc)))
5554 if (flags & MDB_PS_ROOTONLY)
5557 return mdb_page_search_root(mc, key, flags);
5561 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
5563 MDB_txn *txn = mc->mc_txn;
5564 pgno_t pg = mp->mp_pgno;
5565 unsigned x = 0, ovpages = mp->mp_pages;
5566 MDB_env *env = txn->mt_env;
5567 MDB_IDL sl = txn->mt_spill_pgs;
5568 MDB_ID pn = pg << 1;
5571 DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
5572 /* If the page is dirty or on the spill list we just acquired it,
5573 * so we should give it back to our current free list, if any.
5574 * Otherwise put it onto the list of pages we freed in this txn.
5576 * Won't create me_pghead: me_pglast must be inited along with it.
5577 * Unsupported in nested txns: They would need to hide the page
5578 * range in ancestor txns' dirty and spilled lists.
5580 if (env->me_pghead &&
5582 ((mp->mp_flags & P_DIRTY) ||
5583 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
5587 MDB_ID2 *dl, ix, iy;
5588 rc = mdb_midl_need(&env->me_pghead, ovpages);
5591 if (!(mp->mp_flags & P_DIRTY)) {
5592 /* This page is no longer spilled */
5599 /* Remove from dirty list */
5600 dl = txn->mt_u.dirty_list;
5602 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
5608 mdb_cassert(mc, x > 1);
5610 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
5611 txn->mt_flags |= MDB_TXN_ERROR;
5612 return MDB_CORRUPTED;
5615 txn->mt_dirty_room++;
5616 if (!(env->me_flags & MDB_WRITEMAP))
5617 mdb_dpage_free(env, mp);
5619 /* Insert in me_pghead */
5620 mop = env->me_pghead;
5621 j = mop[0] + ovpages;
5622 for (i = mop[0]; i && mop[i] < pg; i--)
5628 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
5632 mc->mc_db->md_overflow_pages -= ovpages;
5636 /** Return the data associated with a given node.
5637 * @param[in] txn The transaction for this operation.
5638 * @param[in] leaf The node being read.
5639 * @param[out] data Updated to point to the node's data.
5640 * @return 0 on success, non-zero on failure.
5643 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
5645 MDB_page *omp; /* overflow page */
5649 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5650 data->mv_size = NODEDSZ(leaf);
5651 data->mv_data = NODEDATA(leaf);
5655 /* Read overflow data.
5657 data->mv_size = NODEDSZ(leaf);
5658 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
5659 if ((rc = mdb_page_get(txn, pgno, &omp, NULL)) != 0) {
5660 DPRINTF(("read overflow page %"Z"u failed", pgno));
5663 data->mv_data = METADATA(omp);
5669 mdb_get(MDB_txn *txn, MDB_dbi dbi,
5670 MDB_val *key, MDB_val *data)
5677 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
5679 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
5682 if (txn->mt_flags & MDB_TXN_BLOCKED)
5685 mdb_cursor_init(&mc, txn, dbi, &mx);
5686 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
5689 /** Find a sibling for a page.
5690 * Replaces the page at the top of the cursor's stack with the
5691 * specified sibling, if one exists.
5692 * @param[in] mc The cursor for this operation.
5693 * @param[in] move_right Non-zero if the right sibling is requested,
5694 * otherwise the left sibling.
5695 * @return 0 on success, non-zero on failure.
5698 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
5704 if (mc->mc_snum < 2) {
5705 return MDB_NOTFOUND; /* root has no siblings */
5709 DPRINTF(("parent page is page %"Z"u, index %u",
5710 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
5712 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
5713 : (mc->mc_ki[mc->mc_top] == 0)) {
5714 DPRINTF(("no more keys left, moving to %s sibling",
5715 move_right ? "right" : "left"));
5716 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
5717 /* undo cursor_pop before returning */
5724 mc->mc_ki[mc->mc_top]++;
5726 mc->mc_ki[mc->mc_top]--;
5727 DPRINTF(("just moving to %s index key %u",
5728 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
5730 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
5732 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5733 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL)) != 0) {
5734 /* mc will be inconsistent if caller does mc_snum++ as above */
5735 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
5739 mdb_cursor_push(mc, mp);
5741 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
5746 /** Move the cursor to the next data item. */
5748 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5754 if (mc->mc_flags & C_EOF) {
5755 return MDB_NOTFOUND;
5758 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5760 mp = mc->mc_pg[mc->mc_top];
5762 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5763 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5764 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5765 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
5766 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
5767 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
5768 if (rc == MDB_SUCCESS)
5769 MDB_GET_KEY(leaf, key);
5774 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5775 if (op == MDB_NEXT_DUP)
5776 return MDB_NOTFOUND;
5780 DPRINTF(("cursor_next: top page is %"Z"u in cursor %p",
5781 mdb_dbg_pgno(mp), (void *) mc));
5782 if (mc->mc_flags & C_DEL)
5785 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
5786 DPUTS("=====> move to next sibling page");
5787 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5788 mc->mc_flags |= C_EOF;
5791 mp = mc->mc_pg[mc->mc_top];
5792 DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5794 mc->mc_ki[mc->mc_top]++;
5797 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5798 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5801 key->mv_size = mc->mc_db->md_pad;
5802 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5806 mdb_cassert(mc, IS_LEAF(mp));
5807 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5809 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5810 mdb_xcursor_init1(mc, leaf);
5813 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5816 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5817 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5818 if (rc != MDB_SUCCESS)
5823 MDB_GET_KEY(leaf, key);
5827 /** Move the cursor to the previous data item. */
5829 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5835 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5837 mp = mc->mc_pg[mc->mc_top];
5839 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5840 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5841 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5842 if (op == MDB_PREV || op == MDB_PREV_DUP) {
5843 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
5844 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
5845 if (rc == MDB_SUCCESS) {
5846 MDB_GET_KEY(leaf, key);
5847 mc->mc_flags &= ~C_EOF;
5853 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5854 if (op == MDB_PREV_DUP)
5855 return MDB_NOTFOUND;
5859 DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p",
5860 mdb_dbg_pgno(mp), (void *) mc));
5862 if (mc->mc_ki[mc->mc_top] == 0) {
5863 DPUTS("=====> move to prev sibling page");
5864 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
5867 mp = mc->mc_pg[mc->mc_top];
5868 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
5869 DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5871 mc->mc_ki[mc->mc_top]--;
5873 mc->mc_flags &= ~C_EOF;
5875 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5876 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5879 key->mv_size = mc->mc_db->md_pad;
5880 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5884 mdb_cassert(mc, IS_LEAF(mp));
5885 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5887 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5888 mdb_xcursor_init1(mc, leaf);
5891 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5894 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5895 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5896 if (rc != MDB_SUCCESS)
5901 MDB_GET_KEY(leaf, key);
5905 /** Set the cursor on a specific data item. */
5907 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5908 MDB_cursor_op op, int *exactp)
5912 MDB_node *leaf = NULL;
5915 if (key->mv_size == 0)
5916 return MDB_BAD_VALSIZE;
5919 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5921 /* See if we're already on the right page */
5922 if (mc->mc_flags & C_INITIALIZED) {
5925 mp = mc->mc_pg[mc->mc_top];
5927 mc->mc_ki[mc->mc_top] = 0;
5928 return MDB_NOTFOUND;
5930 if (mp->mp_flags & P_LEAF2) {
5931 nodekey.mv_size = mc->mc_db->md_pad;
5932 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
5934 leaf = NODEPTR(mp, 0);
5935 MDB_GET_KEY2(leaf, nodekey);
5937 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5939 /* Probably happens rarely, but first node on the page
5940 * was the one we wanted.
5942 mc->mc_ki[mc->mc_top] = 0;
5949 unsigned int nkeys = NUMKEYS(mp);
5951 if (mp->mp_flags & P_LEAF2) {
5952 nodekey.mv_data = LEAF2KEY(mp,
5953 nkeys-1, nodekey.mv_size);
5955 leaf = NODEPTR(mp, nkeys-1);
5956 MDB_GET_KEY2(leaf, nodekey);
5958 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5960 /* last node was the one we wanted */
5961 mc->mc_ki[mc->mc_top] = nkeys-1;
5967 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
5968 /* This is definitely the right page, skip search_page */
5969 if (mp->mp_flags & P_LEAF2) {
5970 nodekey.mv_data = LEAF2KEY(mp,
5971 mc->mc_ki[mc->mc_top], nodekey.mv_size);
5973 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5974 MDB_GET_KEY2(leaf, nodekey);
5976 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5978 /* current node was the one we wanted */
5988 /* If any parents have right-sibs, search.
5989 * Otherwise, there's nothing further.
5991 for (i=0; i<mc->mc_top; i++)
5993 NUMKEYS(mc->mc_pg[i])-1)
5995 if (i == mc->mc_top) {
5996 /* There are no other pages */
5997 mc->mc_ki[mc->mc_top] = nkeys;
5998 return MDB_NOTFOUND;
6002 /* There are no other pages */
6003 mc->mc_ki[mc->mc_top] = 0;
6004 if (op == MDB_SET_RANGE && !exactp) {
6008 return MDB_NOTFOUND;
6014 rc = mdb_page_search(mc, key, 0);
6015 if (rc != MDB_SUCCESS)
6018 mp = mc->mc_pg[mc->mc_top];
6019 mdb_cassert(mc, IS_LEAF(mp));
6022 leaf = mdb_node_search(mc, key, exactp);
6023 if (exactp != NULL && !*exactp) {
6024 /* MDB_SET specified and not an exact match. */
6025 return MDB_NOTFOUND;
6029 DPUTS("===> inexact leaf not found, goto sibling");
6030 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
6031 mc->mc_flags |= C_EOF;
6032 return rc; /* no entries matched */
6034 mp = mc->mc_pg[mc->mc_top];
6035 mdb_cassert(mc, IS_LEAF(mp));
6036 leaf = NODEPTR(mp, 0);
6040 mc->mc_flags |= C_INITIALIZED;
6041 mc->mc_flags &= ~C_EOF;
6044 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
6045 key->mv_size = mc->mc_db->md_pad;
6046 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6051 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6052 mdb_xcursor_init1(mc, leaf);
6055 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6056 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
6057 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6060 if (op == MDB_GET_BOTH) {
6066 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
6067 if (rc != MDB_SUCCESS)
6070 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
6073 if ((rc = mdb_node_read(mc->mc_txn, leaf, &olddata)) != MDB_SUCCESS)
6075 dcmp = mc->mc_dbx->md_dcmp;
6076 #if UINT_MAX < SIZE_MAX
6077 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
6078 dcmp = mdb_cmp_clong;
6080 rc = dcmp(data, &olddata);
6082 if (op == MDB_GET_BOTH || rc > 0)
6083 return MDB_NOTFOUND;
6090 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6091 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
6096 /* The key already matches in all other cases */
6097 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
6098 MDB_GET_KEY(leaf, key);
6099 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
6104 /** Move the cursor to the first item in the database. */
6106 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6112 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6114 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6115 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
6116 if (rc != MDB_SUCCESS)
6119 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6121 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
6122 mc->mc_flags |= C_INITIALIZED;
6123 mc->mc_flags &= ~C_EOF;
6125 mc->mc_ki[mc->mc_top] = 0;
6127 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6128 key->mv_size = mc->mc_db->md_pad;
6129 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
6134 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6135 mdb_xcursor_init1(mc, leaf);
6136 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6140 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
6144 MDB_GET_KEY(leaf, key);
6148 /** Move the cursor to the last item in the database. */
6150 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6156 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6158 if (!(mc->mc_flags & C_EOF)) {
6160 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6161 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
6162 if (rc != MDB_SUCCESS)
6165 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6168 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
6169 mc->mc_flags |= C_INITIALIZED|C_EOF;
6170 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6172 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6173 key->mv_size = mc->mc_db->md_pad;
6174 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
6179 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6180 mdb_xcursor_init1(mc, leaf);
6181 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
6185 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
6190 MDB_GET_KEY(leaf, key);
6195 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6200 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
6205 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
6209 case MDB_GET_CURRENT:
6210 if (!(mc->mc_flags & C_INITIALIZED)) {
6213 MDB_page *mp = mc->mc_pg[mc->mc_top];
6214 int nkeys = NUMKEYS(mp);
6215 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
6216 mc->mc_ki[mc->mc_top] = nkeys;
6222 key->mv_size = mc->mc_db->md_pad;
6223 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6225 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6226 MDB_GET_KEY(leaf, key);
6228 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6229 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
6231 rc = mdb_node_read(mc->mc_txn, leaf, data);
6238 case MDB_GET_BOTH_RANGE:
6243 if (mc->mc_xcursor == NULL) {
6244 rc = MDB_INCOMPATIBLE;
6254 rc = mdb_cursor_set(mc, key, data, op,
6255 op == MDB_SET_RANGE ? NULL : &exact);
6258 case MDB_GET_MULTIPLE:
6259 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
6263 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6264 rc = MDB_INCOMPATIBLE;
6268 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
6269 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
6272 case MDB_NEXT_MULTIPLE:
6277 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6278 rc = MDB_INCOMPATIBLE;
6281 if (!(mc->mc_flags & C_INITIALIZED))
6282 rc = mdb_cursor_first(mc, key, data);
6284 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
6285 if (rc == MDB_SUCCESS) {
6286 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6289 mx = &mc->mc_xcursor->mx_cursor;
6290 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
6292 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
6293 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
6301 case MDB_NEXT_NODUP:
6302 if (!(mc->mc_flags & C_INITIALIZED))
6303 rc = mdb_cursor_first(mc, key, data);
6305 rc = mdb_cursor_next(mc, key, data, op);
6309 case MDB_PREV_NODUP:
6310 if (!(mc->mc_flags & C_INITIALIZED)) {
6311 rc = mdb_cursor_last(mc, key, data);
6314 mc->mc_flags |= C_INITIALIZED;
6315 mc->mc_ki[mc->mc_top]++;
6317 rc = mdb_cursor_prev(mc, key, data, op);
6320 rc = mdb_cursor_first(mc, key, data);
6323 mfunc = mdb_cursor_first;
6325 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
6329 if (mc->mc_xcursor == NULL) {
6330 rc = MDB_INCOMPATIBLE;
6334 MDB_node *leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6335 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6336 MDB_GET_KEY(leaf, key);
6337 rc = mdb_node_read(mc->mc_txn, leaf, data);
6341 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
6345 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
6348 rc = mdb_cursor_last(mc, key, data);
6351 mfunc = mdb_cursor_last;
6354 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
6359 if (mc->mc_flags & C_DEL)
6360 mc->mc_flags ^= C_DEL;
6365 /** Touch all the pages in the cursor stack. Set mc_top.
6366 * Makes sure all the pages are writable, before attempting a write operation.
6367 * @param[in] mc The cursor to operate on.
6370 mdb_cursor_touch(MDB_cursor *mc)
6372 int rc = MDB_SUCCESS;
6374 if (mc->mc_dbi >= CORE_DBS && !(*mc->mc_dbflag & DB_DIRTY)) {
6377 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
6379 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
6380 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
6383 *mc->mc_dbflag |= DB_DIRTY;
6388 rc = mdb_page_touch(mc);
6389 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
6390 mc->mc_top = mc->mc_snum-1;
6395 /** Do not spill pages to disk if txn is getting full, may fail instead */
6396 #define MDB_NOSPILL 0x8000
6399 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6403 MDB_node *leaf = NULL;
6404 MDB_page *fp, *mp, *sub_root = NULL;
6406 MDB_val xdata, *rdata, dkey, olddata;
6408 int do_sub = 0, insert_key, insert_data;
6409 unsigned int mcount = 0, dcount = 0, nospill;
6412 unsigned int nflags;
6415 if (mc == NULL || key == NULL)
6418 env = mc->mc_txn->mt_env;
6420 /* Check this first so counter will always be zero on any
6423 if (flags & MDB_MULTIPLE) {
6424 dcount = data[1].mv_size;
6425 data[1].mv_size = 0;
6426 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
6427 return MDB_INCOMPATIBLE;
6430 nospill = flags & MDB_NOSPILL;
6431 flags &= ~MDB_NOSPILL;
6433 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
6434 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6436 if (key->mv_size-1 >= ENV_MAXKEY(env))
6437 return MDB_BAD_VALSIZE;
6439 #if SIZE_MAX > MAXDATASIZE
6440 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
6441 return MDB_BAD_VALSIZE;
6443 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
6444 return MDB_BAD_VALSIZE;
6447 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
6448 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
6452 if (flags == MDB_CURRENT) {
6453 if (!(mc->mc_flags & C_INITIALIZED))
6456 } else if (mc->mc_db->md_root == P_INVALID) {
6457 /* new database, cursor has nothing to point to */
6460 mc->mc_flags &= ~C_INITIALIZED;
6465 if (flags & MDB_APPEND) {
6467 rc = mdb_cursor_last(mc, &k2, &d2);
6469 rc = mc->mc_dbx->md_cmp(key, &k2);
6472 mc->mc_ki[mc->mc_top]++;
6474 /* new key is <= last key */
6479 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
6481 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
6482 DPRINTF(("duplicate key [%s]", DKEY(key)));
6484 return MDB_KEYEXIST;
6486 if (rc && rc != MDB_NOTFOUND)
6490 if (mc->mc_flags & C_DEL)
6491 mc->mc_flags ^= C_DEL;
6493 /* Cursor is positioned, check for room in the dirty list */
6495 if (flags & MDB_MULTIPLE) {
6497 xdata.mv_size = data->mv_size * dcount;
6501 if ((rc2 = mdb_page_spill(mc, key, rdata)))
6505 if (rc == MDB_NO_ROOT) {
6507 /* new database, write a root leaf page */
6508 DPUTS("allocating new root leaf page");
6509 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
6512 mdb_cursor_push(mc, np);
6513 mc->mc_db->md_root = np->mp_pgno;
6514 mc->mc_db->md_depth++;
6515 *mc->mc_dbflag |= DB_DIRTY;
6516 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
6518 np->mp_flags |= P_LEAF2;
6519 mc->mc_flags |= C_INITIALIZED;
6521 /* make sure all cursor pages are writable */
6522 rc2 = mdb_cursor_touch(mc);
6527 insert_key = insert_data = rc;
6529 /* The key does not exist */
6530 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
6531 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
6532 LEAFSIZE(key, data) > env->me_nodemax)
6534 /* Too big for a node, insert in sub-DB. Set up an empty
6535 * "old sub-page" for prep_subDB to expand to a full page.
6537 fp_flags = P_LEAF|P_DIRTY;
6539 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
6540 fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
6541 olddata.mv_size = PAGEHDRSZ;
6545 /* there's only a key anyway, so this is a no-op */
6546 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6548 unsigned int ksize = mc->mc_db->md_pad;
6549 if (key->mv_size != ksize)
6550 return MDB_BAD_VALSIZE;
6551 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
6552 memcpy(ptr, key->mv_data, ksize);
6554 /* if overwriting slot 0 of leaf, need to
6555 * update branch key if there is a parent page
6557 if (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
6558 unsigned short dtop = 1;
6560 /* slot 0 is always an empty key, find real slot */
6561 while (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
6565 if (mc->mc_ki[mc->mc_top])
6566 rc2 = mdb_update_key(mc, key);
6577 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6578 olddata.mv_size = NODEDSZ(leaf);
6579 olddata.mv_data = NODEDATA(leaf);
6582 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
6583 /* Prepare (sub-)page/sub-DB to accept the new item,
6584 * if needed. fp: old sub-page or a header faking
6585 * it. mp: new (sub-)page. offset: growth in page
6586 * size. xdata: node data with new page or DB.
6588 unsigned i, offset = 0;
6589 mp = fp = xdata.mv_data = env->me_pbuf;
6590 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
6592 /* Was a single item before, must convert now */
6593 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6595 /* Just overwrite the current item */
6596 if (flags == MDB_CURRENT)
6598 dcmp = mc->mc_dbx->md_dcmp;
6599 #if UINT_MAX < SIZE_MAX
6600 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
6601 dcmp = mdb_cmp_clong;
6603 /* does data match? */
6604 if (!dcmp(data, &olddata)) {
6605 if (flags & MDB_NODUPDATA)
6606 return MDB_KEYEXIST;
6611 /* Back up original data item */
6612 dkey.mv_size = olddata.mv_size;
6613 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
6615 /* Make sub-page header for the dup items, with dummy body */
6616 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
6617 fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
6618 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
6619 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6620 fp->mp_flags |= P_LEAF2;
6621 fp->mp_pad = data->mv_size;
6622 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
6624 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
6625 (dkey.mv_size & 1) + (data->mv_size & 1);
6627 fp->mp_upper = xdata.mv_size - PAGEBASE;
6628 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
6629 } else if (leaf->mn_flags & F_SUBDATA) {
6630 /* Data is on sub-DB, just store it */
6631 flags |= F_DUPDATA|F_SUBDATA;
6634 /* Data is on sub-page */
6635 fp = olddata.mv_data;
6638 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6639 offset = EVEN(NODESIZE + sizeof(indx_t) +
6643 offset = fp->mp_pad;
6644 if (SIZELEFT(fp) < offset) {
6645 offset *= 4; /* space for 4 more */
6648 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
6650 fp->mp_flags |= P_DIRTY;
6651 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
6652 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
6656 xdata.mv_size = olddata.mv_size + offset;
6659 fp_flags = fp->mp_flags;
6660 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
6661 /* Too big for a sub-page, convert to sub-DB */
6662 fp_flags &= ~P_SUBP;
6664 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6665 fp_flags |= P_LEAF2;
6666 dummy.md_pad = fp->mp_pad;
6667 dummy.md_flags = MDB_DUPFIXED;
6668 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6669 dummy.md_flags |= MDB_INTEGERKEY;
6675 dummy.md_branch_pages = 0;
6676 dummy.md_leaf_pages = 1;
6677 dummy.md_overflow_pages = 0;
6678 dummy.md_entries = NUMKEYS(fp);
6679 xdata.mv_size = sizeof(MDB_db);
6680 xdata.mv_data = &dummy;
6681 if ((rc = mdb_page_alloc(mc, 1, &mp)))
6683 offset = env->me_psize - olddata.mv_size;
6684 flags |= F_DUPDATA|F_SUBDATA;
6685 dummy.md_root = mp->mp_pgno;
6689 mp->mp_flags = fp_flags | P_DIRTY;
6690 mp->mp_pad = fp->mp_pad;
6691 mp->mp_lower = fp->mp_lower;
6692 mp->mp_upper = fp->mp_upper + offset;
6693 if (fp_flags & P_LEAF2) {
6694 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
6696 memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
6697 olddata.mv_size - fp->mp_upper - PAGEBASE);
6698 for (i=0; i<NUMKEYS(fp); i++)
6699 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
6707 mdb_node_del(mc, 0);
6711 /* LMDB passes F_SUBDATA in 'flags' to write a DB record */
6712 if ((leaf->mn_flags ^ flags) & F_SUBDATA)
6713 return MDB_INCOMPATIBLE;
6714 /* overflow page overwrites need special handling */
6715 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6718 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
6720 memcpy(&pg, olddata.mv_data, sizeof(pg));
6721 if ((rc2 = mdb_page_get(mc->mc_txn, pg, &omp, &level)) != 0)
6723 ovpages = omp->mp_pages;
6725 /* Is the ov page large enough? */
6726 if (ovpages >= dpages) {
6727 if (!(omp->mp_flags & P_DIRTY) &&
6728 (level || (env->me_flags & MDB_WRITEMAP)))
6730 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
6733 level = 0; /* dirty in this txn or clean */
6736 if (omp->mp_flags & P_DIRTY) {
6737 /* yes, overwrite it. Note in this case we don't
6738 * bother to try shrinking the page if the new data
6739 * is smaller than the overflow threshold.
6742 /* It is writable only in a parent txn */
6743 size_t sz = (size_t) env->me_psize * ovpages, off;
6744 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
6750 /* Note - this page is already counted in parent's dirty_room */
6751 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
6752 mdb_cassert(mc, rc2 == 0);
6753 if (!(flags & MDB_RESERVE)) {
6754 /* Copy end of page, adjusting alignment so
6755 * compiler may copy words instead of bytes.
6757 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
6758 memcpy((size_t *)((char *)np + off),
6759 (size_t *)((char *)omp + off), sz - off);
6762 memcpy(np, omp, sz); /* Copy beginning of page */
6765 SETDSZ(leaf, data->mv_size);
6766 if (F_ISSET(flags, MDB_RESERVE))
6767 data->mv_data = METADATA(omp);
6769 memcpy(METADATA(omp), data->mv_data, data->mv_size);
6773 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
6775 } else if (data->mv_size == olddata.mv_size) {
6776 /* same size, just replace it. Note that we could
6777 * also reuse this node if the new data is smaller,
6778 * but instead we opt to shrink the node in that case.
6780 if (F_ISSET(flags, MDB_RESERVE))
6781 data->mv_data = olddata.mv_data;
6782 else if (!(mc->mc_flags & C_SUB))
6783 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
6785 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
6790 mdb_node_del(mc, 0);
6796 nflags = flags & NODE_ADD_FLAGS;
6797 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
6798 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
6799 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
6800 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
6802 nflags |= MDB_SPLIT_REPLACE;
6803 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
6805 /* There is room already in this leaf page. */
6806 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
6807 if (rc == 0 && insert_key) {
6808 /* Adjust other cursors pointing to mp */
6809 MDB_cursor *m2, *m3;
6810 MDB_dbi dbi = mc->mc_dbi;
6811 unsigned i = mc->mc_top;
6812 MDB_page *mp = mc->mc_pg[i];
6814 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6815 if (mc->mc_flags & C_SUB)
6816 m3 = &m2->mc_xcursor->mx_cursor;
6819 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
6820 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
6827 if (rc == MDB_SUCCESS) {
6828 /* Now store the actual data in the child DB. Note that we're
6829 * storing the user data in the keys field, so there are strict
6830 * size limits on dupdata. The actual data fields of the child
6831 * DB are all zero size.
6834 int xflags, new_dupdata;
6839 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6840 if (flags & MDB_CURRENT) {
6841 xflags = MDB_CURRENT|MDB_NOSPILL;
6843 mdb_xcursor_init1(mc, leaf);
6844 xflags = (flags & MDB_NODUPDATA) ?
6845 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
6848 mc->mc_xcursor->mx_cursor.mc_pg[0] = sub_root;
6849 new_dupdata = (int)dkey.mv_size;
6850 /* converted, write the original data first */
6852 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
6855 /* we've done our job */
6858 if (!(leaf->mn_flags & F_SUBDATA) || sub_root) {
6859 /* Adjust other cursors pointing to mp */
6861 MDB_xcursor *mx = mc->mc_xcursor;
6862 unsigned i = mc->mc_top;
6863 MDB_page *mp = mc->mc_pg[i];
6864 int nkeys = NUMKEYS(mp);
6866 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6867 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6868 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6869 if (m2->mc_pg[i] == mp) {
6870 if (m2->mc_ki[i] == mc->mc_ki[i]) {
6871 mdb_xcursor_init2(m2, mx, new_dupdata);
6872 } else if (!insert_key && m2->mc_ki[i] < nkeys) {
6873 MDB_node *n2 = NODEPTR(mp, m2->mc_ki[i]);
6874 if ((n2->mn_flags & (F_SUBDATA|F_DUPDATA)) == F_DUPDATA)
6875 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
6880 ecount = mc->mc_xcursor->mx_db.md_entries;
6881 if (flags & MDB_APPENDDUP)
6882 xflags |= MDB_APPEND;
6883 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
6884 if (flags & F_SUBDATA) {
6885 void *db = NODEDATA(leaf);
6886 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6888 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
6890 /* Increment count unless we just replaced an existing item. */
6892 mc->mc_db->md_entries++;
6894 /* Invalidate txn if we created an empty sub-DB */
6897 /* If we succeeded and the key didn't exist before,
6898 * make sure the cursor is marked valid.
6900 mc->mc_flags |= C_INITIALIZED;
6902 if (flags & MDB_MULTIPLE) {
6905 /* let caller know how many succeeded, if any */
6906 data[1].mv_size = mcount;
6907 if (mcount < dcount) {
6908 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
6909 insert_key = insert_data = 0;
6916 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
6919 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6924 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
6930 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
6931 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6933 if (!(mc->mc_flags & C_INITIALIZED))
6936 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6937 return MDB_NOTFOUND;
6939 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
6942 rc = mdb_cursor_touch(mc);
6946 mp = mc->mc_pg[mc->mc_top];
6949 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6951 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6952 if (flags & MDB_NODUPDATA) {
6953 /* mdb_cursor_del0() will subtract the final entry */
6954 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
6955 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
6957 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
6958 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6960 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
6963 /* If sub-DB still has entries, we're done */
6964 if (mc->mc_xcursor->mx_db.md_entries) {
6965 if (leaf->mn_flags & F_SUBDATA) {
6966 /* update subDB info */
6967 void *db = NODEDATA(leaf);
6968 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6971 /* shrink fake page */
6972 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
6973 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6974 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6975 /* fix other sub-DB cursors pointed at fake pages on this page */
6976 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6977 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6978 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6979 if (m2->mc_pg[mc->mc_top] == mp) {
6980 if (m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top]) {
6981 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6983 MDB_node *n2 = NODEPTR(mp, m2->mc_ki[mc->mc_top]);
6984 if (!(n2->mn_flags & F_SUBDATA))
6985 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
6990 mc->mc_db->md_entries--;
6993 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
6995 /* otherwise fall thru and delete the sub-DB */
6998 if (leaf->mn_flags & F_SUBDATA) {
6999 /* add all the child DB's pages to the free list */
7000 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
7005 /* LMDB passes F_SUBDATA in 'flags' to delete a DB record */
7006 else if ((leaf->mn_flags ^ flags) & F_SUBDATA) {
7007 rc = MDB_INCOMPATIBLE;
7011 /* add overflow pages to free list */
7012 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7016 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
7017 if ((rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL)) ||
7018 (rc = mdb_ovpage_free(mc, omp)))
7023 return mdb_cursor_del0(mc);
7026 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7030 /** Allocate and initialize new pages for a database.
7031 * @param[in] mc a cursor on the database being added to.
7032 * @param[in] flags flags defining what type of page is being allocated.
7033 * @param[in] num the number of pages to allocate. This is usually 1,
7034 * unless allocating overflow pages for a large record.
7035 * @param[out] mp Address of a page, or NULL on failure.
7036 * @return 0 on success, non-zero on failure.
7039 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
7044 if ((rc = mdb_page_alloc(mc, num, &np)))
7046 DPRINTF(("allocated new mpage %"Z"u, page size %u",
7047 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
7048 np->mp_flags = flags | P_DIRTY;
7049 np->mp_lower = (PAGEHDRSZ-PAGEBASE);
7050 np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
7053 mc->mc_db->md_branch_pages++;
7054 else if (IS_LEAF(np))
7055 mc->mc_db->md_leaf_pages++;
7056 else if (IS_OVERFLOW(np)) {
7057 mc->mc_db->md_overflow_pages += num;
7065 /** Calculate the size of a leaf node.
7066 * The size depends on the environment's page size; if a data item
7067 * is too large it will be put onto an overflow page and the node
7068 * size will only include the key and not the data. Sizes are always
7069 * rounded up to an even number of bytes, to guarantee 2-byte alignment
7070 * of the #MDB_node headers.
7071 * @param[in] env The environment handle.
7072 * @param[in] key The key for the node.
7073 * @param[in] data The data for the node.
7074 * @return The number of bytes needed to store the node.
7077 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
7081 sz = LEAFSIZE(key, data);
7082 if (sz > env->me_nodemax) {
7083 /* put on overflow page */
7084 sz -= data->mv_size - sizeof(pgno_t);
7087 return EVEN(sz + sizeof(indx_t));
7090 /** Calculate the size of a branch node.
7091 * The size should depend on the environment's page size but since
7092 * we currently don't support spilling large keys onto overflow
7093 * pages, it's simply the size of the #MDB_node header plus the
7094 * size of the key. Sizes are always rounded up to an even number
7095 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
7096 * @param[in] env The environment handle.
7097 * @param[in] key The key for the node.
7098 * @return The number of bytes needed to store the node.
7101 mdb_branch_size(MDB_env *env, MDB_val *key)
7106 if (sz > env->me_nodemax) {
7107 /* put on overflow page */
7108 /* not implemented */
7109 /* sz -= key->size - sizeof(pgno_t); */
7112 return sz + sizeof(indx_t);
7115 /** Add a node to the page pointed to by the cursor.
7116 * @param[in] mc The cursor for this operation.
7117 * @param[in] indx The index on the page where the new node should be added.
7118 * @param[in] key The key for the new node.
7119 * @param[in] data The data for the new node, if any.
7120 * @param[in] pgno The page number, if adding a branch node.
7121 * @param[in] flags Flags for the node.
7122 * @return 0 on success, non-zero on failure. Possible errors are:
7124 * <li>ENOMEM - failed to allocate overflow pages for the node.
7125 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
7126 * should never happen since all callers already calculate the
7127 * page's free space before calling this function.
7131 mdb_node_add(MDB_cursor *mc, indx_t indx,
7132 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
7135 size_t node_size = NODESIZE;
7139 MDB_page *mp = mc->mc_pg[mc->mc_top];
7140 MDB_page *ofp = NULL; /* overflow page */
7144 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
7146 DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
7147 IS_LEAF(mp) ? "leaf" : "branch",
7148 IS_SUBP(mp) ? "sub-" : "",
7149 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
7150 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
7153 /* Move higher keys up one slot. */
7154 int ksize = mc->mc_db->md_pad, dif;
7155 char *ptr = LEAF2KEY(mp, indx, ksize);
7156 dif = NUMKEYS(mp) - indx;
7158 memmove(ptr+ksize, ptr, dif*ksize);
7159 /* insert new key */
7160 memcpy(ptr, key->mv_data, ksize);
7162 /* Just using these for counting */
7163 mp->mp_lower += sizeof(indx_t);
7164 mp->mp_upper -= ksize - sizeof(indx_t);
7168 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
7170 node_size += key->mv_size;
7172 mdb_cassert(mc, key && data);
7173 if (F_ISSET(flags, F_BIGDATA)) {
7174 /* Data already on overflow page. */
7175 node_size += sizeof(pgno_t);
7176 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
7177 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
7179 /* Put data on overflow page. */
7180 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
7181 data->mv_size, node_size+data->mv_size));
7182 node_size = EVEN(node_size + sizeof(pgno_t));
7183 if ((ssize_t)node_size > room)
7185 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
7187 DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
7191 node_size += data->mv_size;
7194 node_size = EVEN(node_size);
7195 if ((ssize_t)node_size > room)
7199 /* Move higher pointers up one slot. */
7200 for (i = NUMKEYS(mp); i > indx; i--)
7201 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
7203 /* Adjust free space offsets. */
7204 ofs = mp->mp_upper - node_size;
7205 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
7206 mp->mp_ptrs[indx] = ofs;
7208 mp->mp_lower += sizeof(indx_t);
7210 /* Write the node data. */
7211 node = NODEPTR(mp, indx);
7212 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
7213 node->mn_flags = flags;
7215 SETDSZ(node,data->mv_size);
7220 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7223 ndata = NODEDATA(node);
7225 if (F_ISSET(flags, F_BIGDATA))
7226 memcpy(ndata, data->mv_data, sizeof(pgno_t));
7227 else if (F_ISSET(flags, MDB_RESERVE))
7228 data->mv_data = ndata;
7230 memcpy(ndata, data->mv_data, data->mv_size);
7232 memcpy(ndata, &ofp->mp_pgno, sizeof(pgno_t));
7233 ndata = METADATA(ofp);
7234 if (F_ISSET(flags, MDB_RESERVE))
7235 data->mv_data = ndata;
7237 memcpy(ndata, data->mv_data, data->mv_size);
7244 DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
7245 mdb_dbg_pgno(mp), NUMKEYS(mp)));
7246 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
7247 DPRINTF(("node size = %"Z"u", node_size));
7248 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7249 return MDB_PAGE_FULL;
7252 /** Delete the specified node from a page.
7253 * @param[in] mc Cursor pointing to the node to delete.
7254 * @param[in] ksize The size of a node. Only used if the page is
7255 * part of a #MDB_DUPFIXED database.
7258 mdb_node_del(MDB_cursor *mc, int ksize)
7260 MDB_page *mp = mc->mc_pg[mc->mc_top];
7261 indx_t indx = mc->mc_ki[mc->mc_top];
7263 indx_t i, j, numkeys, ptr;
7267 DPRINTF(("delete node %u on %s page %"Z"u", indx,
7268 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
7269 numkeys = NUMKEYS(mp);
7270 mdb_cassert(mc, indx < numkeys);
7273 int x = numkeys - 1 - indx;
7274 base = LEAF2KEY(mp, indx, ksize);
7276 memmove(base, base + ksize, x * ksize);
7277 mp->mp_lower -= sizeof(indx_t);
7278 mp->mp_upper += ksize - sizeof(indx_t);
7282 node = NODEPTR(mp, indx);
7283 sz = NODESIZE + node->mn_ksize;
7285 if (F_ISSET(node->mn_flags, F_BIGDATA))
7286 sz += sizeof(pgno_t);
7288 sz += NODEDSZ(node);
7292 ptr = mp->mp_ptrs[indx];
7293 for (i = j = 0; i < numkeys; i++) {
7295 mp->mp_ptrs[j] = mp->mp_ptrs[i];
7296 if (mp->mp_ptrs[i] < ptr)
7297 mp->mp_ptrs[j] += sz;
7302 base = (char *)mp + mp->mp_upper + PAGEBASE;
7303 memmove(base + sz, base, ptr - mp->mp_upper);
7305 mp->mp_lower -= sizeof(indx_t);
7309 /** Compact the main page after deleting a node on a subpage.
7310 * @param[in] mp The main page to operate on.
7311 * @param[in] indx The index of the subpage on the main page.
7314 mdb_node_shrink(MDB_page *mp, indx_t indx)
7319 indx_t delta, nsize, len, ptr;
7322 node = NODEPTR(mp, indx);
7323 sp = (MDB_page *)NODEDATA(node);
7324 delta = SIZELEFT(sp);
7325 nsize = NODEDSZ(node) - delta;
7327 /* Prepare to shift upward, set len = length(subpage part to shift) */
7331 return; /* do not make the node uneven-sized */
7333 xp = (MDB_page *)((char *)sp + delta); /* destination subpage */
7334 for (i = NUMKEYS(sp); --i >= 0; )
7335 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
7338 sp->mp_upper = sp->mp_lower;
7339 COPY_PGNO(sp->mp_pgno, mp->mp_pgno);
7340 SETDSZ(node, nsize);
7342 /* Shift <lower nodes...initial part of subpage> upward */
7343 base = (char *)mp + mp->mp_upper + PAGEBASE;
7344 memmove(base + delta, base, (char *)sp + len - base);
7346 ptr = mp->mp_ptrs[indx];
7347 for (i = NUMKEYS(mp); --i >= 0; ) {
7348 if (mp->mp_ptrs[i] <= ptr)
7349 mp->mp_ptrs[i] += delta;
7351 mp->mp_upper += delta;
7354 /** Initial setup of a sorted-dups cursor.
7355 * Sorted duplicates are implemented as a sub-database for the given key.
7356 * The duplicate data items are actually keys of the sub-database.
7357 * Operations on the duplicate data items are performed using a sub-cursor
7358 * initialized when the sub-database is first accessed. This function does
7359 * the preliminary setup of the sub-cursor, filling in the fields that
7360 * depend only on the parent DB.
7361 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
7364 mdb_xcursor_init0(MDB_cursor *mc)
7366 MDB_xcursor *mx = mc->mc_xcursor;
7368 mx->mx_cursor.mc_xcursor = NULL;
7369 mx->mx_cursor.mc_txn = mc->mc_txn;
7370 mx->mx_cursor.mc_db = &mx->mx_db;
7371 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
7372 mx->mx_cursor.mc_dbi = mc->mc_dbi;
7373 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
7374 mx->mx_cursor.mc_snum = 0;
7375 mx->mx_cursor.mc_top = 0;
7376 mx->mx_cursor.mc_flags = C_SUB;
7377 mx->mx_dbx.md_name.mv_size = 0;
7378 mx->mx_dbx.md_name.mv_data = NULL;
7379 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
7380 mx->mx_dbx.md_dcmp = NULL;
7381 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
7384 /** Final setup of a sorted-dups cursor.
7385 * Sets up the fields that depend on the data from the main cursor.
7386 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
7387 * @param[in] node The data containing the #MDB_db record for the
7388 * sorted-dup database.
7391 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
7393 MDB_xcursor *mx = mc->mc_xcursor;
7395 if (node->mn_flags & F_SUBDATA) {
7396 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
7397 mx->mx_cursor.mc_pg[0] = 0;
7398 mx->mx_cursor.mc_snum = 0;
7399 mx->mx_cursor.mc_top = 0;
7400 mx->mx_cursor.mc_flags = C_SUB;
7402 MDB_page *fp = NODEDATA(node);
7403 mx->mx_db.md_pad = 0;
7404 mx->mx_db.md_flags = 0;
7405 mx->mx_db.md_depth = 1;
7406 mx->mx_db.md_branch_pages = 0;
7407 mx->mx_db.md_leaf_pages = 1;
7408 mx->mx_db.md_overflow_pages = 0;
7409 mx->mx_db.md_entries = NUMKEYS(fp);
7410 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
7411 mx->mx_cursor.mc_snum = 1;
7412 mx->mx_cursor.mc_top = 0;
7413 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
7414 mx->mx_cursor.mc_pg[0] = fp;
7415 mx->mx_cursor.mc_ki[0] = 0;
7416 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7417 mx->mx_db.md_flags = MDB_DUPFIXED;
7418 mx->mx_db.md_pad = fp->mp_pad;
7419 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
7420 mx->mx_db.md_flags |= MDB_INTEGERKEY;
7423 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
7424 mx->mx_db.md_root));
7425 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
7426 #if UINT_MAX < SIZE_MAX
7427 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
7428 mx->mx_dbx.md_cmp = mdb_cmp_clong;
7433 /** Fixup a sorted-dups cursor due to underlying update.
7434 * Sets up some fields that depend on the data from the main cursor.
7435 * Almost the same as init1, but skips initialization steps if the
7436 * xcursor had already been used.
7437 * @param[in] mc The main cursor whose sorted-dups cursor is to be fixed up.
7438 * @param[in] src_mx The xcursor of an up-to-date cursor.
7439 * @param[in] new_dupdata True if converting from a non-#F_DUPDATA item.
7442 mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int new_dupdata)
7444 MDB_xcursor *mx = mc->mc_xcursor;
7447 mx->mx_cursor.mc_snum = 1;
7448 mx->mx_cursor.mc_top = 0;
7449 mx->mx_cursor.mc_flags |= C_INITIALIZED;
7450 mx->mx_cursor.mc_ki[0] = 0;
7451 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
7452 #if UINT_MAX < SIZE_MAX
7453 mx->mx_dbx.md_cmp = src_mx->mx_dbx.md_cmp;
7455 } else if (!(mx->mx_cursor.mc_flags & C_INITIALIZED)) {
7458 mx->mx_db = src_mx->mx_db;
7459 mx->mx_cursor.mc_pg[0] = src_mx->mx_cursor.mc_pg[0];
7460 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
7461 mx->mx_db.md_root));
7464 /** Initialize a cursor for a given transaction and database. */
7466 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
7469 mc->mc_backup = NULL;
7472 mc->mc_db = &txn->mt_dbs[dbi];
7473 mc->mc_dbx = &txn->mt_dbxs[dbi];
7474 mc->mc_dbflag = &txn->mt_dbflags[dbi];
7480 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
7481 mdb_tassert(txn, mx != NULL);
7482 mc->mc_xcursor = mx;
7483 mdb_xcursor_init0(mc);
7485 mc->mc_xcursor = NULL;
7487 if (*mc->mc_dbflag & DB_STALE) {
7488 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
7493 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
7496 size_t size = sizeof(MDB_cursor);
7498 if (!ret || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
7501 if (txn->mt_flags & MDB_TXN_BLOCKED)
7504 if (dbi == FREE_DBI && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
7507 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
7508 size += sizeof(MDB_xcursor);
7510 if ((mc = malloc(size)) != NULL) {
7511 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
7512 if (txn->mt_cursors) {
7513 mc->mc_next = txn->mt_cursors[dbi];
7514 txn->mt_cursors[dbi] = mc;
7515 mc->mc_flags |= C_UNTRACK;
7527 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
7529 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi, DB_VALID))
7532 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
7535 if (txn->mt_flags & MDB_TXN_BLOCKED)
7538 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
7542 /* Return the count of duplicate data items for the current key */
7544 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
7548 if (mc == NULL || countp == NULL)
7551 if (mc->mc_xcursor == NULL)
7552 return MDB_INCOMPATIBLE;
7554 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
7557 if (!(mc->mc_flags & C_INITIALIZED))
7560 if (!mc->mc_snum || (mc->mc_flags & C_EOF))
7561 return MDB_NOTFOUND;
7563 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7564 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7567 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
7570 *countp = mc->mc_xcursor->mx_db.md_entries;
7576 mdb_cursor_close(MDB_cursor *mc)
7578 if (mc && !mc->mc_backup) {
7579 /* remove from txn, if tracked */
7580 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
7581 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
7582 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
7584 *prev = mc->mc_next;
7591 mdb_cursor_txn(MDB_cursor *mc)
7593 if (!mc) return NULL;
7598 mdb_cursor_dbi(MDB_cursor *mc)
7603 /** Replace the key for a branch node with a new key.
7604 * @param[in] mc Cursor pointing to the node to operate on.
7605 * @param[in] key The new key to use.
7606 * @return 0 on success, non-zero on failure.
7609 mdb_update_key(MDB_cursor *mc, MDB_val *key)
7615 int delta, ksize, oksize;
7616 indx_t ptr, i, numkeys, indx;
7619 indx = mc->mc_ki[mc->mc_top];
7620 mp = mc->mc_pg[mc->mc_top];
7621 node = NODEPTR(mp, indx);
7622 ptr = mp->mp_ptrs[indx];
7626 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
7627 k2.mv_data = NODEKEY(node);
7628 k2.mv_size = node->mn_ksize;
7629 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
7631 mdb_dkey(&k2, kbuf2),
7637 /* Sizes must be 2-byte aligned. */
7638 ksize = EVEN(key->mv_size);
7639 oksize = EVEN(node->mn_ksize);
7640 delta = ksize - oksize;
7642 /* Shift node contents if EVEN(key length) changed. */
7644 if (delta > 0 && SIZELEFT(mp) < delta) {
7646 /* not enough space left, do a delete and split */
7647 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
7648 pgno = NODEPGNO(node);
7649 mdb_node_del(mc, 0);
7650 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
7653 numkeys = NUMKEYS(mp);
7654 for (i = 0; i < numkeys; i++) {
7655 if (mp->mp_ptrs[i] <= ptr)
7656 mp->mp_ptrs[i] -= delta;
7659 base = (char *)mp + mp->mp_upper + PAGEBASE;
7660 len = ptr - mp->mp_upper + NODESIZE;
7661 memmove(base - delta, base, len);
7662 mp->mp_upper -= delta;
7664 node = NODEPTR(mp, indx);
7667 /* But even if no shift was needed, update ksize */
7668 if (node->mn_ksize != key->mv_size)
7669 node->mn_ksize = key->mv_size;
7672 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7678 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
7680 /** Perform \b act while tracking temporary cursor \b mn */
7681 #define WITH_CURSOR_TRACKING(mn, act) do { \
7682 MDB_cursor dummy, *tracked, **tp = &(mn).mc_txn->mt_cursors[mn.mc_dbi]; \
7683 if ((mn).mc_flags & C_SUB) { \
7684 dummy.mc_flags = C_INITIALIZED; \
7685 dummy.mc_xcursor = (MDB_xcursor *)&(mn); \
7690 tracked->mc_next = *tp; \
7693 *tp = tracked->mc_next; \
7696 /** Move a node from csrc to cdst.
7699 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft)
7706 unsigned short flags;
7710 /* Mark src and dst as dirty. */
7711 if ((rc = mdb_page_touch(csrc)) ||
7712 (rc = mdb_page_touch(cdst)))
7715 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7716 key.mv_size = csrc->mc_db->md_pad;
7717 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
7719 data.mv_data = NULL;
7723 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
7724 mdb_cassert(csrc, !((size_t)srcnode & 1));
7725 srcpg = NODEPGNO(srcnode);
7726 flags = srcnode->mn_flags;
7727 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7728 unsigned int snum = csrc->mc_snum;
7730 /* must find the lowest key below src */
7731 rc = mdb_page_search_lowest(csrc);
7734 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7735 key.mv_size = csrc->mc_db->md_pad;
7736 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7738 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7739 key.mv_size = NODEKSZ(s2);
7740 key.mv_data = NODEKEY(s2);
7742 csrc->mc_snum = snum--;
7743 csrc->mc_top = snum;
7745 key.mv_size = NODEKSZ(srcnode);
7746 key.mv_data = NODEKEY(srcnode);
7748 data.mv_size = NODEDSZ(srcnode);
7749 data.mv_data = NODEDATA(srcnode);
7751 mn.mc_xcursor = NULL;
7752 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
7753 unsigned int snum = cdst->mc_snum;
7756 /* must find the lowest key below dst */
7757 mdb_cursor_copy(cdst, &mn);
7758 rc = mdb_page_search_lowest(&mn);
7761 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7762 bkey.mv_size = mn.mc_db->md_pad;
7763 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
7765 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7766 bkey.mv_size = NODEKSZ(s2);
7767 bkey.mv_data = NODEKEY(s2);
7769 mn.mc_snum = snum--;
7772 rc = mdb_update_key(&mn, &bkey);
7777 DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
7778 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
7779 csrc->mc_ki[csrc->mc_top],
7781 csrc->mc_pg[csrc->mc_top]->mp_pgno,
7782 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
7784 /* Add the node to the destination page.
7786 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
7787 if (rc != MDB_SUCCESS)
7790 /* Delete the node from the source page.
7792 mdb_node_del(csrc, key.mv_size);
7795 /* Adjust other cursors pointing to mp */
7796 MDB_cursor *m2, *m3;
7797 MDB_dbi dbi = csrc->mc_dbi;
7798 MDB_page *mpd, *mps;
7800 mps = csrc->mc_pg[csrc->mc_top];
7801 /* If we're adding on the left, bump others up */
7803 mpd = cdst->mc_pg[csrc->mc_top];
7804 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7805 if (csrc->mc_flags & C_SUB)
7806 m3 = &m2->mc_xcursor->mx_cursor;
7809 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
7812 m3->mc_pg[csrc->mc_top] == mpd &&
7813 m3->mc_ki[csrc->mc_top] >= cdst->mc_ki[csrc->mc_top]) {
7814 m3->mc_ki[csrc->mc_top]++;
7817 m3->mc_pg[csrc->mc_top] == mps &&
7818 m3->mc_ki[csrc->mc_top] == csrc->mc_ki[csrc->mc_top]) {
7819 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
7820 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7821 m3->mc_ki[csrc->mc_top-1]++;
7823 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) &&
7825 MDB_node *node = NODEPTR(m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
7826 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
7827 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
7831 /* Adding on the right, bump others down */
7833 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7834 if (csrc->mc_flags & C_SUB)
7835 m3 = &m2->mc_xcursor->mx_cursor;
7838 if (m3 == csrc) continue;
7839 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
7841 if (m3->mc_pg[csrc->mc_top] == mps) {
7842 if (!m3->mc_ki[csrc->mc_top]) {
7843 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
7844 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7845 m3->mc_ki[csrc->mc_top-1]--;
7847 m3->mc_ki[csrc->mc_top]--;
7849 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) &&
7851 MDB_node *node = NODEPTR(m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
7852 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
7853 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
7860 /* Update the parent separators.
7862 if (csrc->mc_ki[csrc->mc_top] == 0) {
7863 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
7864 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7865 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7867 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7868 key.mv_size = NODEKSZ(srcnode);
7869 key.mv_data = NODEKEY(srcnode);
7871 DPRINTF(("update separator for source page %"Z"u to [%s]",
7872 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
7873 mdb_cursor_copy(csrc, &mn);
7876 /* We want mdb_rebalance to find mn when doing fixups */
7877 WITH_CURSOR_TRACKING(mn,
7878 rc = mdb_update_key(&mn, &key));
7882 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7884 indx_t ix = csrc->mc_ki[csrc->mc_top];
7885 nullkey.mv_size = 0;
7886 csrc->mc_ki[csrc->mc_top] = 0;
7887 rc = mdb_update_key(csrc, &nullkey);
7888 csrc->mc_ki[csrc->mc_top] = ix;
7889 mdb_cassert(csrc, rc == MDB_SUCCESS);
7893 if (cdst->mc_ki[cdst->mc_top] == 0) {
7894 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
7895 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7896 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
7898 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
7899 key.mv_size = NODEKSZ(srcnode);
7900 key.mv_data = NODEKEY(srcnode);
7902 DPRINTF(("update separator for destination page %"Z"u to [%s]",
7903 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
7904 mdb_cursor_copy(cdst, &mn);
7907 /* We want mdb_rebalance to find mn when doing fixups */
7908 WITH_CURSOR_TRACKING(mn,
7909 rc = mdb_update_key(&mn, &key));
7913 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
7915 indx_t ix = cdst->mc_ki[cdst->mc_top];
7916 nullkey.mv_size = 0;
7917 cdst->mc_ki[cdst->mc_top] = 0;
7918 rc = mdb_update_key(cdst, &nullkey);
7919 cdst->mc_ki[cdst->mc_top] = ix;
7920 mdb_cassert(cdst, rc == MDB_SUCCESS);
7927 /** Merge one page into another.
7928 * The nodes from the page pointed to by \b csrc will
7929 * be copied to the page pointed to by \b cdst and then
7930 * the \b csrc page will be freed.
7931 * @param[in] csrc Cursor pointing to the source page.
7932 * @param[in] cdst Cursor pointing to the destination page.
7933 * @return 0 on success, non-zero on failure.
7936 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
7938 MDB_page *psrc, *pdst;
7945 psrc = csrc->mc_pg[csrc->mc_top];
7946 pdst = cdst->mc_pg[cdst->mc_top];
7948 DPRINTF(("merging page %"Z"u into %"Z"u", psrc->mp_pgno, pdst->mp_pgno));
7950 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
7951 mdb_cassert(csrc, cdst->mc_snum > 1);
7953 /* Mark dst as dirty. */
7954 if ((rc = mdb_page_touch(cdst)))
7957 /* get dst page again now that we've touched it. */
7958 pdst = cdst->mc_pg[cdst->mc_top];
7960 /* Move all nodes from src to dst.
7962 j = nkeys = NUMKEYS(pdst);
7963 if (IS_LEAF2(psrc)) {
7964 key.mv_size = csrc->mc_db->md_pad;
7965 key.mv_data = METADATA(psrc);
7966 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7967 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
7968 if (rc != MDB_SUCCESS)
7970 key.mv_data = (char *)key.mv_data + key.mv_size;
7973 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7974 srcnode = NODEPTR(psrc, i);
7975 if (i == 0 && IS_BRANCH(psrc)) {
7978 mdb_cursor_copy(csrc, &mn);
7979 mn.mc_xcursor = NULL;
7980 /* must find the lowest key below src */
7981 rc = mdb_page_search_lowest(&mn);
7984 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7985 key.mv_size = mn.mc_db->md_pad;
7986 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
7988 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7989 key.mv_size = NODEKSZ(s2);
7990 key.mv_data = NODEKEY(s2);
7993 key.mv_size = srcnode->mn_ksize;
7994 key.mv_data = NODEKEY(srcnode);
7997 data.mv_size = NODEDSZ(srcnode);
7998 data.mv_data = NODEDATA(srcnode);
7999 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
8000 if (rc != MDB_SUCCESS)
8005 DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
8006 pdst->mp_pgno, NUMKEYS(pdst),
8007 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
8009 /* Unlink the src page from parent and add to free list.
8012 mdb_node_del(csrc, 0);
8013 if (csrc->mc_ki[csrc->mc_top] == 0) {
8015 rc = mdb_update_key(csrc, &key);
8023 psrc = csrc->mc_pg[csrc->mc_top];
8024 /* If not operating on FreeDB, allow this page to be reused
8025 * in this txn. Otherwise just add to free list.
8027 rc = mdb_page_loose(csrc, psrc);
8031 csrc->mc_db->md_leaf_pages--;
8033 csrc->mc_db->md_branch_pages--;
8035 /* Adjust other cursors pointing to mp */
8036 MDB_cursor *m2, *m3;
8037 MDB_dbi dbi = csrc->mc_dbi;
8038 unsigned int top = csrc->mc_top;
8040 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8041 if (csrc->mc_flags & C_SUB)
8042 m3 = &m2->mc_xcursor->mx_cursor;
8045 if (m3 == csrc) continue;
8046 if (m3->mc_snum < csrc->mc_snum) continue;
8047 if (m3->mc_pg[top] == psrc) {
8048 m3->mc_pg[top] = pdst;
8049 m3->mc_ki[top] += nkeys;
8050 m3->mc_ki[top-1] = cdst->mc_ki[top-1];
8051 } else if (m3->mc_pg[top-1] == csrc->mc_pg[top-1] &&
8052 m3->mc_ki[top-1] > csrc->mc_ki[top-1]) {
8055 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) &&
8057 MDB_node *node = NODEPTR(m3->mc_pg[top], m3->mc_ki[top]);
8058 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
8059 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
8064 unsigned int snum = cdst->mc_snum;
8065 uint16_t depth = cdst->mc_db->md_depth;
8066 mdb_cursor_pop(cdst);
8067 rc = mdb_rebalance(cdst);
8068 /* Did the tree height change? */
8069 if (depth != cdst->mc_db->md_depth)
8070 snum += cdst->mc_db->md_depth - depth;
8071 cdst->mc_snum = snum;
8072 cdst->mc_top = snum-1;
8077 /** Copy the contents of a cursor.
8078 * @param[in] csrc The cursor to copy from.
8079 * @param[out] cdst The cursor to copy to.
8082 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
8086 cdst->mc_txn = csrc->mc_txn;
8087 cdst->mc_dbi = csrc->mc_dbi;
8088 cdst->mc_db = csrc->mc_db;
8089 cdst->mc_dbx = csrc->mc_dbx;
8090 cdst->mc_snum = csrc->mc_snum;
8091 cdst->mc_top = csrc->mc_top;
8092 cdst->mc_flags = csrc->mc_flags;
8094 for (i=0; i<csrc->mc_snum; i++) {
8095 cdst->mc_pg[i] = csrc->mc_pg[i];
8096 cdst->mc_ki[i] = csrc->mc_ki[i];
8100 /** Rebalance the tree after a delete operation.
8101 * @param[in] mc Cursor pointing to the page where rebalancing
8103 * @return 0 on success, non-zero on failure.
8106 mdb_rebalance(MDB_cursor *mc)
8110 unsigned int ptop, minkeys, thresh;
8114 if (IS_BRANCH(mc->mc_pg[mc->mc_top])) {
8119 thresh = FILL_THRESHOLD;
8121 DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
8122 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
8123 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
8124 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
8126 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= thresh &&
8127 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
8128 DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
8129 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
8133 if (mc->mc_snum < 2) {
8134 MDB_page *mp = mc->mc_pg[0];
8136 DPUTS("Can't rebalance a subpage, ignoring");
8139 if (NUMKEYS(mp) == 0) {
8140 DPUTS("tree is completely empty");
8141 mc->mc_db->md_root = P_INVALID;
8142 mc->mc_db->md_depth = 0;
8143 mc->mc_db->md_leaf_pages = 0;
8144 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
8147 /* Adjust cursors pointing to mp */
8150 mc->mc_flags &= ~C_INITIALIZED;
8152 MDB_cursor *m2, *m3;
8153 MDB_dbi dbi = mc->mc_dbi;
8155 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8156 if (mc->mc_flags & C_SUB)
8157 m3 = &m2->mc_xcursor->mx_cursor;
8160 if (!(m3->mc_flags & C_INITIALIZED) || (m3->mc_snum < mc->mc_snum))
8162 if (m3->mc_pg[0] == mp) {
8165 m3->mc_flags &= ~C_INITIALIZED;
8169 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
8171 DPUTS("collapsing root page!");
8172 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
8175 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
8176 rc = mdb_page_get(mc->mc_txn,mc->mc_db->md_root,&mc->mc_pg[0],NULL);
8179 mc->mc_db->md_depth--;
8180 mc->mc_db->md_branch_pages--;
8181 mc->mc_ki[0] = mc->mc_ki[1];
8182 for (i = 1; i<mc->mc_db->md_depth; i++) {
8183 mc->mc_pg[i] = mc->mc_pg[i+1];
8184 mc->mc_ki[i] = mc->mc_ki[i+1];
8187 /* Adjust other cursors pointing to mp */
8188 MDB_cursor *m2, *m3;
8189 MDB_dbi dbi = mc->mc_dbi;
8191 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8192 if (mc->mc_flags & C_SUB)
8193 m3 = &m2->mc_xcursor->mx_cursor;
8196 if (m3 == mc) continue;
8197 if (!(m3->mc_flags & C_INITIALIZED))
8199 if (m3->mc_pg[0] == mp) {
8200 for (i=0; i<mc->mc_db->md_depth; i++) {
8201 m3->mc_pg[i] = m3->mc_pg[i+1];
8202 m3->mc_ki[i] = m3->mc_ki[i+1];
8210 DPUTS("root page doesn't need rebalancing");
8214 /* The parent (branch page) must have at least 2 pointers,
8215 * otherwise the tree is invalid.
8217 ptop = mc->mc_top-1;
8218 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
8220 /* Leaf page fill factor is below the threshold.
8221 * Try to move keys from left or right neighbor, or
8222 * merge with a neighbor page.
8227 mdb_cursor_copy(mc, &mn);
8228 mn.mc_xcursor = NULL;
8230 oldki = mc->mc_ki[mc->mc_top];
8231 if (mc->mc_ki[ptop] == 0) {
8232 /* We're the leftmost leaf in our parent.
8234 DPUTS("reading right neighbor");
8236 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
8237 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
8240 mn.mc_ki[mn.mc_top] = 0;
8241 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
8244 /* There is at least one neighbor to the left.
8246 DPUTS("reading left neighbor");
8248 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
8249 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
8252 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
8253 mc->mc_ki[mc->mc_top] = 0;
8257 DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
8258 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
8259 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
8261 /* If the neighbor page is above threshold and has enough keys,
8262 * move one key from it. Otherwise we should try to merge them.
8263 * (A branch page must never have less than 2 keys.)
8265 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= thresh && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
8266 rc = mdb_node_move(&mn, mc, fromleft);
8268 /* if we inserted on left, bump position up */
8273 rc = mdb_page_merge(&mn, mc);
8275 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
8276 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
8277 /* We want mdb_rebalance to find mn when doing fixups */
8278 WITH_CURSOR_TRACKING(mn,
8279 rc = mdb_page_merge(mc, &mn));
8280 mdb_cursor_copy(&mn, mc);
8282 mc->mc_flags &= ~C_EOF;
8284 mc->mc_ki[mc->mc_top] = oldki;
8288 /** Complete a delete operation started by #mdb_cursor_del(). */
8290 mdb_cursor_del0(MDB_cursor *mc)
8296 MDB_cursor *m2, *m3;
8297 MDB_dbi dbi = mc->mc_dbi;
8299 ki = mc->mc_ki[mc->mc_top];
8300 mp = mc->mc_pg[mc->mc_top];
8301 mdb_node_del(mc, mc->mc_db->md_pad);
8302 mc->mc_db->md_entries--;
8304 /* Adjust other cursors pointing to mp */
8305 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8306 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
8307 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8309 if (m3 == mc || m3->mc_snum < mc->mc_snum)
8311 if (m3->mc_pg[mc->mc_top] == mp) {
8312 if (m3->mc_ki[mc->mc_top] == ki) {
8313 m3->mc_flags |= C_DEL;
8314 if (mc->mc_db->md_flags & MDB_DUPSORT)
8315 m3->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
8316 } else if (m3->mc_ki[mc->mc_top] > ki) {
8317 m3->mc_ki[mc->mc_top]--;
8319 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
8320 MDB_node *node = NODEPTR(m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
8321 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
8322 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
8327 rc = mdb_rebalance(mc);
8329 if (rc == MDB_SUCCESS) {
8330 /* DB is totally empty now, just bail out.
8331 * Other cursors adjustments were already done
8332 * by mdb_rebalance and aren't needed here.
8337 mp = mc->mc_pg[mc->mc_top];
8338 nkeys = NUMKEYS(mp);
8340 /* Adjust other cursors pointing to mp */
8341 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
8342 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
8343 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8345 if (m3->mc_snum < mc->mc_snum)
8347 if (m3->mc_pg[mc->mc_top] == mp) {
8348 /* if m3 points past last node in page, find next sibling */
8349 if (m3->mc_ki[mc->mc_top] >= nkeys) {
8350 rc = mdb_cursor_sibling(m3, 1);
8351 if (rc == MDB_NOTFOUND) {
8352 m3->mc_flags |= C_EOF;
8358 mc->mc_flags |= C_DEL;
8362 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8367 mdb_del(MDB_txn *txn, MDB_dbi dbi,
8368 MDB_val *key, MDB_val *data)
8370 if (!key || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
8373 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
8374 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
8376 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
8377 /* must ignore any data */
8381 return mdb_del0(txn, dbi, key, data, 0);
8385 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
8386 MDB_val *key, MDB_val *data, unsigned flags)
8391 MDB_val rdata, *xdata;
8395 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
8397 mdb_cursor_init(&mc, txn, dbi, &mx);
8406 flags |= MDB_NODUPDATA;
8408 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
8410 /* let mdb_page_split know about this cursor if needed:
8411 * delete will trigger a rebalance; if it needs to move
8412 * a node from one page to another, it will have to
8413 * update the parent's separator key(s). If the new sepkey
8414 * is larger than the current one, the parent page may
8415 * run out of space, triggering a split. We need this
8416 * cursor to be consistent until the end of the rebalance.
8418 mc.mc_flags |= C_UNTRACK;
8419 mc.mc_next = txn->mt_cursors[dbi];
8420 txn->mt_cursors[dbi] = &mc;
8421 rc = mdb_cursor_del(&mc, flags);
8422 txn->mt_cursors[dbi] = mc.mc_next;
8427 /** Split a page and insert a new node.
8428 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
8429 * The cursor will be updated to point to the actual page and index where
8430 * the node got inserted after the split.
8431 * @param[in] newkey The key for the newly inserted node.
8432 * @param[in] newdata The data for the newly inserted node.
8433 * @param[in] newpgno The page number, if the new node is a branch node.
8434 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
8435 * @return 0 on success, non-zero on failure.
8438 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
8439 unsigned int nflags)
8442 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
8445 int i, j, split_indx, nkeys, pmax;
8446 MDB_env *env = mc->mc_txn->mt_env;
8448 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
8449 MDB_page *copy = NULL;
8450 MDB_page *mp, *rp, *pp;
8455 mp = mc->mc_pg[mc->mc_top];
8456 newindx = mc->mc_ki[mc->mc_top];
8457 nkeys = NUMKEYS(mp);
8459 DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i/%i",
8460 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
8461 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
8463 /* Create a right sibling. */
8464 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
8466 rp->mp_pad = mp->mp_pad;
8467 DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
8469 /* Usually when splitting the root page, the cursor
8470 * height is 1. But when called from mdb_update_key,
8471 * the cursor height may be greater because it walks
8472 * up the stack while finding the branch slot to update.
8474 if (mc->mc_top < 1) {
8475 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
8477 /* shift current top to make room for new parent */
8478 for (i=mc->mc_snum; i>0; i--) {
8479 mc->mc_pg[i] = mc->mc_pg[i-1];
8480 mc->mc_ki[i] = mc->mc_ki[i-1];
8484 mc->mc_db->md_root = pp->mp_pgno;
8485 DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
8486 new_root = mc->mc_db->md_depth++;
8488 /* Add left (implicit) pointer. */
8489 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
8490 /* undo the pre-push */
8491 mc->mc_pg[0] = mc->mc_pg[1];
8492 mc->mc_ki[0] = mc->mc_ki[1];
8493 mc->mc_db->md_root = mp->mp_pgno;
8494 mc->mc_db->md_depth--;
8501 ptop = mc->mc_top-1;
8502 DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
8505 mdb_cursor_copy(mc, &mn);
8506 mn.mc_xcursor = NULL;
8507 mn.mc_pg[mn.mc_top] = rp;
8508 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
8510 if (nflags & MDB_APPEND) {
8511 mn.mc_ki[mn.mc_top] = 0;
8513 split_indx = newindx;
8517 split_indx = (nkeys+1) / 2;
8522 unsigned int lsize, rsize, ksize;
8523 /* Move half of the keys to the right sibling */
8524 x = mc->mc_ki[mc->mc_top] - split_indx;
8525 ksize = mc->mc_db->md_pad;
8526 split = LEAF2KEY(mp, split_indx, ksize);
8527 rsize = (nkeys - split_indx) * ksize;
8528 lsize = (nkeys - split_indx) * sizeof(indx_t);
8529 mp->mp_lower -= lsize;
8530 rp->mp_lower += lsize;
8531 mp->mp_upper += rsize - lsize;
8532 rp->mp_upper -= rsize - lsize;
8533 sepkey.mv_size = ksize;
8534 if (newindx == split_indx) {
8535 sepkey.mv_data = newkey->mv_data;
8537 sepkey.mv_data = split;
8540 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
8541 memcpy(rp->mp_ptrs, split, rsize);
8542 sepkey.mv_data = rp->mp_ptrs;
8543 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
8544 memcpy(ins, newkey->mv_data, ksize);
8545 mp->mp_lower += sizeof(indx_t);
8546 mp->mp_upper -= ksize - sizeof(indx_t);
8549 memcpy(rp->mp_ptrs, split, x * ksize);
8550 ins = LEAF2KEY(rp, x, ksize);
8551 memcpy(ins, newkey->mv_data, ksize);
8552 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
8553 rp->mp_lower += sizeof(indx_t);
8554 rp->mp_upper -= ksize - sizeof(indx_t);
8555 mc->mc_ki[mc->mc_top] = x;
8558 int psize, nsize, k;
8559 /* Maximum free space in an empty page */
8560 pmax = env->me_psize - PAGEHDRSZ;
8562 nsize = mdb_leaf_size(env, newkey, newdata);
8564 nsize = mdb_branch_size(env, newkey);
8565 nsize = EVEN(nsize);
8567 /* grab a page to hold a temporary copy */
8568 copy = mdb_page_malloc(mc->mc_txn, 1);
8573 copy->mp_pgno = mp->mp_pgno;
8574 copy->mp_flags = mp->mp_flags;
8575 copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
8576 copy->mp_upper = env->me_psize - PAGEBASE;
8578 /* prepare to insert */
8579 for (i=0, j=0; i<nkeys; i++) {
8581 copy->mp_ptrs[j++] = 0;
8583 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
8586 /* When items are relatively large the split point needs
8587 * to be checked, because being off-by-one will make the
8588 * difference between success or failure in mdb_node_add.
8590 * It's also relevant if a page happens to be laid out
8591 * such that one half of its nodes are all "small" and
8592 * the other half of its nodes are "large." If the new
8593 * item is also "large" and falls on the half with
8594 * "large" nodes, it also may not fit.
8596 * As a final tweak, if the new item goes on the last
8597 * spot on the page (and thus, onto the new page), bias
8598 * the split so the new page is emptier than the old page.
8599 * This yields better packing during sequential inserts.
8601 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
8602 /* Find split point */
8604 if (newindx <= split_indx || newindx >= nkeys) {
8606 k = newindx >= nkeys ? nkeys : split_indx+1+IS_LEAF(mp);
8611 for (; i!=k; i+=j) {
8616 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8617 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
8619 if (F_ISSET(node->mn_flags, F_BIGDATA))
8620 psize += sizeof(pgno_t);
8622 psize += NODEDSZ(node);
8624 psize = EVEN(psize);
8626 if (psize > pmax || i == k-j) {
8627 split_indx = i + (j<0);
8632 if (split_indx == newindx) {
8633 sepkey.mv_size = newkey->mv_size;
8634 sepkey.mv_data = newkey->mv_data;
8636 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
8637 sepkey.mv_size = node->mn_ksize;
8638 sepkey.mv_data = NODEKEY(node);
8643 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
8645 /* Copy separator key to the parent.
8647 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
8648 int snum = mc->mc_snum;
8652 /* We want other splits to find mn when doing fixups */
8653 WITH_CURSOR_TRACKING(mn,
8654 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0));
8659 if (mc->mc_snum > snum) {
8662 /* Right page might now have changed parent.
8663 * Check if left page also changed parent.
8665 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8666 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8667 for (i=0; i<ptop; i++) {
8668 mc->mc_pg[i] = mn.mc_pg[i];
8669 mc->mc_ki[i] = mn.mc_ki[i];
8671 mc->mc_pg[ptop] = mn.mc_pg[ptop];
8672 if (mn.mc_ki[ptop]) {
8673 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
8675 /* find right page's left sibling */
8676 mc->mc_ki[ptop] = mn.mc_ki[ptop];
8677 mdb_cursor_sibling(mc, 0);
8682 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
8685 if (rc != MDB_SUCCESS) {
8688 if (nflags & MDB_APPEND) {
8689 mc->mc_pg[mc->mc_top] = rp;
8690 mc->mc_ki[mc->mc_top] = 0;
8691 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
8694 for (i=0; i<mc->mc_top; i++)
8695 mc->mc_ki[i] = mn.mc_ki[i];
8696 } else if (!IS_LEAF2(mp)) {
8698 mc->mc_pg[mc->mc_top] = rp;
8703 rkey.mv_data = newkey->mv_data;
8704 rkey.mv_size = newkey->mv_size;
8710 /* Update index for the new key. */
8711 mc->mc_ki[mc->mc_top] = j;
8713 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8714 rkey.mv_data = NODEKEY(node);
8715 rkey.mv_size = node->mn_ksize;
8717 xdata.mv_data = NODEDATA(node);
8718 xdata.mv_size = NODEDSZ(node);
8721 pgno = NODEPGNO(node);
8722 flags = node->mn_flags;
8725 if (!IS_LEAF(mp) && j == 0) {
8726 /* First branch index doesn't need key data. */
8730 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
8736 mc->mc_pg[mc->mc_top] = copy;
8741 } while (i != split_indx);
8743 nkeys = NUMKEYS(copy);
8744 for (i=0; i<nkeys; i++)
8745 mp->mp_ptrs[i] = copy->mp_ptrs[i];
8746 mp->mp_lower = copy->mp_lower;
8747 mp->mp_upper = copy->mp_upper;
8748 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
8749 env->me_psize - copy->mp_upper - PAGEBASE);
8751 /* reset back to original page */
8752 if (newindx < split_indx) {
8753 mc->mc_pg[mc->mc_top] = mp;
8755 mc->mc_pg[mc->mc_top] = rp;
8757 /* Make sure mc_ki is still valid.
8759 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8760 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8761 for (i=0; i<=ptop; i++) {
8762 mc->mc_pg[i] = mn.mc_pg[i];
8763 mc->mc_ki[i] = mn.mc_ki[i];
8767 if (nflags & MDB_RESERVE) {
8768 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
8769 if (!(node->mn_flags & F_BIGDATA))
8770 newdata->mv_data = NODEDATA(node);
8773 if (newindx >= split_indx) {
8774 mc->mc_pg[mc->mc_top] = rp;
8776 /* Make sure mc_ki is still valid.
8778 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8779 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8780 for (i=0; i<=ptop; i++) {
8781 mc->mc_pg[i] = mn.mc_pg[i];
8782 mc->mc_ki[i] = mn.mc_ki[i];
8789 /* Adjust other cursors pointing to mp */
8790 MDB_cursor *m2, *m3;
8791 MDB_dbi dbi = mc->mc_dbi;
8792 nkeys = NUMKEYS(mp);
8794 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8795 if (mc->mc_flags & C_SUB)
8796 m3 = &m2->mc_xcursor->mx_cursor;
8801 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8805 /* sub cursors may be on different DB */
8806 if (m3->mc_pg[0] != mp)
8809 for (k=new_root; k>=0; k--) {
8810 m3->mc_ki[k+1] = m3->mc_ki[k];
8811 m3->mc_pg[k+1] = m3->mc_pg[k];
8813 if (m3->mc_ki[0] >= nkeys) {
8818 m3->mc_pg[0] = mc->mc_pg[0];
8822 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
8823 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
8824 m3->mc_ki[mc->mc_top]++;
8825 if (m3->mc_ki[mc->mc_top] >= nkeys) {
8826 m3->mc_pg[mc->mc_top] = rp;
8827 m3->mc_ki[mc->mc_top] -= nkeys;
8828 for (i=0; i<mc->mc_top; i++) {
8829 m3->mc_ki[i] = mn.mc_ki[i];
8830 m3->mc_pg[i] = mn.mc_pg[i];
8833 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
8834 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
8837 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) &&
8839 MDB_node *node = NODEPTR(m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
8840 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
8841 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
8845 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
8848 if (copy) /* tmp page */
8849 mdb_page_free(env, copy);
8851 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8856 mdb_put(MDB_txn *txn, MDB_dbi dbi,
8857 MDB_val *key, MDB_val *data, unsigned int flags)
8863 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
8866 if (flags & ~(MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP))
8869 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
8870 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
8872 mdb_cursor_init(&mc, txn, dbi, &mx);
8873 mc.mc_next = txn->mt_cursors[dbi];
8874 txn->mt_cursors[dbi] = &mc;
8875 rc = mdb_cursor_put(&mc, key, data, flags);
8876 txn->mt_cursors[dbi] = mc.mc_next;
8881 #define MDB_WBUF (1024*1024)
8884 /** State needed for a compacting copy. */
8885 typedef struct mdb_copy {
8886 pthread_mutex_t mc_mutex;
8887 pthread_cond_t mc_cond;
8894 pgno_t mc_next_pgno;
8897 volatile int mc_new;
8902 /** Dedicated writer thread for compacting copy. */
8903 static THREAD_RET ESECT CALL_CONV
8904 mdb_env_copythr(void *arg)
8908 int toggle = 0, wsize, rc;
8911 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8914 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8917 pthread_mutex_lock(&my->mc_mutex);
8919 pthread_cond_signal(&my->mc_cond);
8922 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8923 if (my->mc_new < 0) {
8928 wsize = my->mc_wlen[toggle];
8929 ptr = my->mc_wbuf[toggle];
8932 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
8936 } else if (len > 0) {
8950 /* If there's an overflow page tail, write it too */
8951 if (my->mc_olen[toggle]) {
8952 wsize = my->mc_olen[toggle];
8953 ptr = my->mc_over[toggle];
8954 my->mc_olen[toggle] = 0;
8957 my->mc_wlen[toggle] = 0;
8959 pthread_cond_signal(&my->mc_cond);
8961 pthread_cond_signal(&my->mc_cond);
8962 pthread_mutex_unlock(&my->mc_mutex);
8963 return (THREAD_RET)0;
8967 /** Tell the writer thread there's a buffer ready to write */
8969 mdb_env_cthr_toggle(mdb_copy *my, int st)
8971 int toggle = my->mc_toggle ^ 1;
8972 pthread_mutex_lock(&my->mc_mutex);
8973 if (my->mc_status) {
8974 pthread_mutex_unlock(&my->mc_mutex);
8975 return my->mc_status;
8977 while (my->mc_new == 1)
8978 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8980 my->mc_toggle = toggle;
8981 pthread_cond_signal(&my->mc_cond);
8982 pthread_mutex_unlock(&my->mc_mutex);
8986 /** Depth-first tree traversal for compacting copy. */
8988 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
8991 MDB_txn *txn = my->mc_txn;
8993 MDB_page *mo, *mp, *leaf;
8998 /* Empty DB, nothing to do */
8999 if (*pg == P_INVALID)
9006 rc = mdb_page_get(my->mc_txn, *pg, &mc.mc_pg[0], NULL);
9009 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
9013 /* Make cursor pages writable */
9014 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
9018 for (i=0; i<mc.mc_top; i++) {
9019 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
9020 mc.mc_pg[i] = (MDB_page *)ptr;
9021 ptr += my->mc_env->me_psize;
9024 /* This is writable space for a leaf page. Usually not needed. */
9025 leaf = (MDB_page *)ptr;
9027 toggle = my->mc_toggle;
9028 while (mc.mc_snum > 0) {
9030 mp = mc.mc_pg[mc.mc_top];
9034 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
9035 for (i=0; i<n; i++) {
9036 ni = NODEPTR(mp, i);
9037 if (ni->mn_flags & F_BIGDATA) {
9041 /* Need writable leaf */
9043 mc.mc_pg[mc.mc_top] = leaf;
9044 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
9046 ni = NODEPTR(mp, i);
9049 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9050 rc = mdb_page_get(txn, pg, &omp, NULL);
9053 if (my->mc_wlen[toggle] >= MDB_WBUF) {
9054 rc = mdb_env_cthr_toggle(my, 1);
9057 toggle = my->mc_toggle;
9059 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
9060 memcpy(mo, omp, my->mc_env->me_psize);
9061 mo->mp_pgno = my->mc_next_pgno;
9062 my->mc_next_pgno += omp->mp_pages;
9063 my->mc_wlen[toggle] += my->mc_env->me_psize;
9064 if (omp->mp_pages > 1) {
9065 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
9066 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
9067 rc = mdb_env_cthr_toggle(my, 1);
9070 toggle = my->mc_toggle;
9072 memcpy(NODEDATA(ni), &mo->mp_pgno, sizeof(pgno_t));
9073 } else if (ni->mn_flags & F_SUBDATA) {
9076 /* Need writable leaf */
9078 mc.mc_pg[mc.mc_top] = leaf;
9079 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
9081 ni = NODEPTR(mp, i);
9084 memcpy(&db, NODEDATA(ni), sizeof(db));
9085 my->mc_toggle = toggle;
9086 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
9089 toggle = my->mc_toggle;
9090 memcpy(NODEDATA(ni), &db, sizeof(db));
9095 mc.mc_ki[mc.mc_top]++;
9096 if (mc.mc_ki[mc.mc_top] < n) {
9099 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
9101 rc = mdb_page_get(txn, pg, &mp, NULL);
9106 mc.mc_ki[mc.mc_top] = 0;
9107 if (IS_BRANCH(mp)) {
9108 /* Whenever we advance to a sibling branch page,
9109 * we must proceed all the way down to its first leaf.
9111 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
9114 mc.mc_pg[mc.mc_top] = mp;
9118 if (my->mc_wlen[toggle] >= MDB_WBUF) {
9119 rc = mdb_env_cthr_toggle(my, 1);
9122 toggle = my->mc_toggle;
9124 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
9125 mdb_page_copy(mo, mp, my->mc_env->me_psize);
9126 mo->mp_pgno = my->mc_next_pgno++;
9127 my->mc_wlen[toggle] += my->mc_env->me_psize;
9129 /* Update parent if there is one */
9130 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
9131 SETPGNO(ni, mo->mp_pgno);
9132 mdb_cursor_pop(&mc);
9134 /* Otherwise we're done */
9144 /** Copy environment with compaction. */
9146 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
9151 MDB_txn *txn = NULL;
9156 my.mc_mutex = CreateMutex(NULL, FALSE, NULL);
9157 my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL);
9158 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_os_psize);
9159 if (my.mc_wbuf[0] == NULL)
9162 pthread_mutex_init(&my.mc_mutex, NULL);
9163 pthread_cond_init(&my.mc_cond, NULL);
9164 #ifdef HAVE_MEMALIGN
9165 my.mc_wbuf[0] = memalign(env->me_os_psize, MDB_WBUF*2);
9166 if (my.mc_wbuf[0] == NULL)
9169 rc = posix_memalign((void **)&my.mc_wbuf[0], env->me_os_psize, MDB_WBUF*2);
9174 memset(my.mc_wbuf[0], 0, MDB_WBUF*2);
9175 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
9180 my.mc_next_pgno = NUM_METAS;
9186 THREAD_CREATE(thr, mdb_env_copythr, &my);
9188 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
9192 mp = (MDB_page *)my.mc_wbuf[0];
9193 memset(mp, 0, NUM_METAS * env->me_psize);
9195 mp->mp_flags = P_META;
9196 mm = (MDB_meta *)METADATA(mp);
9197 mdb_env_init_meta0(env, mm);
9198 mm->mm_address = env->me_metas[0]->mm_address;
9200 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
9202 mp->mp_flags = P_META;
9203 *(MDB_meta *)METADATA(mp) = *mm;
9204 mm = (MDB_meta *)METADATA(mp);
9206 /* Count the number of free pages, subtract from lastpg to find
9207 * number of active pages
9210 MDB_ID freecount = 0;
9213 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
9214 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
9215 freecount += *(MDB_ID *)data.mv_data;
9216 freecount += txn->mt_dbs[FREE_DBI].md_branch_pages +
9217 txn->mt_dbs[FREE_DBI].md_leaf_pages +
9218 txn->mt_dbs[FREE_DBI].md_overflow_pages;
9220 /* Set metapage 1 */
9221 mm->mm_last_pg = txn->mt_next_pgno - freecount - 1;
9222 mm->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
9223 if (mm->mm_last_pg > NUM_METAS-1) {
9224 mm->mm_dbs[MAIN_DBI].md_root = mm->mm_last_pg;
9227 mm->mm_dbs[MAIN_DBI].md_root = P_INVALID;
9230 my.mc_wlen[0] = env->me_psize * NUM_METAS;
9232 pthread_mutex_lock(&my.mc_mutex);
9234 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
9235 pthread_mutex_unlock(&my.mc_mutex);
9236 rc = mdb_env_cwalk(&my, &txn->mt_dbs[MAIN_DBI].md_root, 0);
9237 if (rc == MDB_SUCCESS && my.mc_wlen[my.mc_toggle])
9238 rc = mdb_env_cthr_toggle(&my, 1);
9239 mdb_env_cthr_toggle(&my, -1);
9240 pthread_mutex_lock(&my.mc_mutex);
9242 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
9243 pthread_mutex_unlock(&my.mc_mutex);
9248 CloseHandle(my.mc_cond);
9249 CloseHandle(my.mc_mutex);
9250 _aligned_free(my.mc_wbuf[0]);
9252 pthread_cond_destroy(&my.mc_cond);
9253 pthread_mutex_destroy(&my.mc_mutex);
9254 free(my.mc_wbuf[0]);
9259 /** Copy environment as-is. */
9261 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
9263 MDB_txn *txn = NULL;
9264 mdb_mutexref_t wmutex = NULL;
9270 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
9274 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
9277 /* Do the lock/unlock of the reader mutex before starting the
9278 * write txn. Otherwise other read txns could block writers.
9280 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
9285 /* We must start the actual read txn after blocking writers */
9286 mdb_txn_end(txn, MDB_END_RESET_TMP);
9288 /* Temporarily block writers until we snapshot the meta pages */
9289 wmutex = env->me_wmutex;
9290 if (LOCK_MUTEX(rc, env, wmutex))
9293 rc = mdb_txn_renew0(txn);
9295 UNLOCK_MUTEX(wmutex);
9300 wsize = env->me_psize * NUM_METAS;
9304 DO_WRITE(rc, fd, ptr, w2, len);
9308 } else if (len > 0) {
9314 /* Non-blocking or async handles are not supported */
9320 UNLOCK_MUTEX(wmutex);
9325 w2 = txn->mt_next_pgno * env->me_psize;
9328 if ((rc = mdb_fsize(env->me_fd, &fsize)))
9335 if (wsize > MAX_WRITE)
9339 DO_WRITE(rc, fd, ptr, w2, len);
9343 } else if (len > 0) {
9360 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
9362 if (flags & MDB_CP_COMPACT)
9363 return mdb_env_copyfd1(env, fd);
9365 return mdb_env_copyfd0(env, fd);
9369 mdb_env_copyfd(MDB_env *env, HANDLE fd)
9371 return mdb_env_copyfd2(env, fd, 0);
9375 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
9379 HANDLE newfd = INVALID_HANDLE_VALUE;
9384 if (env->me_flags & MDB_NOSUBDIR) {
9385 lpath = (char *)path;
9388 len += sizeof(DATANAME);
9389 lpath = malloc(len);
9392 sprintf(lpath, "%s" DATANAME, path);
9395 /* The destination path must exist, but the destination file must not.
9396 * We don't want the OS to cache the writes, since the source data is
9397 * already in the OS cache.
9400 utf8_to_utf16(lpath, -1, &wpath, NULL);
9401 newfd = CreateFileW(wpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
9402 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
9405 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
9407 if (newfd == INVALID_HANDLE_VALUE) {
9412 if (env->me_psize >= env->me_os_psize) {
9414 /* Set O_DIRECT if the file system supports it */
9415 if ((rc = fcntl(newfd, F_GETFL)) != -1)
9416 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
9418 #ifdef F_NOCACHE /* __APPLE__ */
9419 rc = fcntl(newfd, F_NOCACHE, 1);
9427 rc = mdb_env_copyfd2(env, newfd, flags);
9430 if (!(env->me_flags & MDB_NOSUBDIR))
9432 if (newfd != INVALID_HANDLE_VALUE)
9433 if (close(newfd) < 0 && rc == MDB_SUCCESS)
9440 mdb_env_copy(MDB_env *env, const char *path)
9442 return mdb_env_copy2(env, path, 0);
9446 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
9448 if (flag & ~CHANGEABLE)
9451 env->me_flags |= flag;
9453 env->me_flags &= ~flag;
9458 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
9463 *arg = env->me_flags & (CHANGEABLE|CHANGELESS);
9468 mdb_env_set_userctx(MDB_env *env, void *ctx)
9472 env->me_userctx = ctx;
9477 mdb_env_get_userctx(MDB_env *env)
9479 return env ? env->me_userctx : NULL;
9483 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
9488 env->me_assert_func = func;
9494 mdb_env_get_path(MDB_env *env, const char **arg)
9499 *arg = env->me_path;
9504 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
9513 /** Common code for #mdb_stat() and #mdb_env_stat().
9514 * @param[in] env the environment to operate in.
9515 * @param[in] db the #MDB_db record containing the stats to return.
9516 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
9517 * @return 0, this function always succeeds.
9520 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
9522 arg->ms_psize = env->me_psize;
9523 arg->ms_depth = db->md_depth;
9524 arg->ms_branch_pages = db->md_branch_pages;
9525 arg->ms_leaf_pages = db->md_leaf_pages;
9526 arg->ms_overflow_pages = db->md_overflow_pages;
9527 arg->ms_entries = db->md_entries;
9533 mdb_env_stat(MDB_env *env, MDB_stat *arg)
9537 if (env == NULL || arg == NULL)
9540 meta = mdb_env_pick_meta(env);
9542 return mdb_stat0(env, &meta->mm_dbs[MAIN_DBI], arg);
9546 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
9550 if (env == NULL || arg == NULL)
9553 meta = mdb_env_pick_meta(env);
9554 arg->me_mapaddr = meta->mm_address;
9555 arg->me_last_pgno = meta->mm_last_pg;
9556 arg->me_last_txnid = meta->mm_txnid;
9558 arg->me_mapsize = env->me_mapsize;
9559 arg->me_maxreaders = env->me_maxreaders;
9560 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : 0;
9564 /** Set the default comparison functions for a database.
9565 * Called immediately after a database is opened to set the defaults.
9566 * The user can then override them with #mdb_set_compare() or
9567 * #mdb_set_dupsort().
9568 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
9569 * @param[in] dbi A database handle returned by #mdb_dbi_open()
9572 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
9574 uint16_t f = txn->mt_dbs[dbi].md_flags;
9576 txn->mt_dbxs[dbi].md_cmp =
9577 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
9578 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
9580 txn->mt_dbxs[dbi].md_dcmp =
9581 !(f & MDB_DUPSORT) ? 0 :
9582 ((f & MDB_INTEGERDUP)
9583 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
9584 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
9587 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
9593 int rc, dbflag, exact;
9594 unsigned int unused = 0, seq;
9597 if (flags & ~VALID_FLAGS)
9599 if (txn->mt_flags & MDB_TXN_BLOCKED)
9605 if (flags & PERSISTENT_FLAGS) {
9606 uint16_t f2 = flags & PERSISTENT_FLAGS;
9607 /* make sure flag changes get committed */
9608 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
9609 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
9610 txn->mt_flags |= MDB_TXN_DIRTY;
9613 mdb_default_cmp(txn, MAIN_DBI);
9617 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
9618 mdb_default_cmp(txn, MAIN_DBI);
9621 /* Is the DB already open? */
9623 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
9624 if (!txn->mt_dbxs[i].md_name.mv_size) {
9625 /* Remember this free slot */
9626 if (!unused) unused = i;
9629 if (len == txn->mt_dbxs[i].md_name.mv_size &&
9630 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
9636 /* If no free slot and max hit, fail */
9637 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
9638 return MDB_DBS_FULL;
9640 /* Cannot mix named databases with some mainDB flags */
9641 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
9642 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
9644 /* Find the DB info */
9645 dbflag = DB_NEW|DB_VALID|DB_USRVALID;
9648 key.mv_data = (void *)name;
9649 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
9650 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
9651 if (rc == MDB_SUCCESS) {
9652 /* make sure this is actually a DB */
9653 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
9654 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
9655 return MDB_INCOMPATIBLE;
9656 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
9657 /* Create if requested */
9658 data.mv_size = sizeof(MDB_db);
9659 data.mv_data = &dummy;
9660 memset(&dummy, 0, sizeof(dummy));
9661 dummy.md_root = P_INVALID;
9662 dummy.md_flags = flags & PERSISTENT_FLAGS;
9663 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
9667 /* OK, got info, add to table */
9668 if (rc == MDB_SUCCESS) {
9669 unsigned int slot = unused ? unused : txn->mt_numdbs;
9670 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
9671 txn->mt_dbxs[slot].md_name.mv_size = len;
9672 txn->mt_dbxs[slot].md_rel = NULL;
9673 txn->mt_dbflags[slot] = dbflag;
9674 /* txn-> and env-> are the same in read txns, use
9675 * tmp variable to avoid undefined assignment
9677 seq = ++txn->mt_env->me_dbiseqs[slot];
9678 txn->mt_dbiseqs[slot] = seq;
9680 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
9682 mdb_default_cmp(txn, slot);
9692 mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
9694 if (!arg || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
9697 if (txn->mt_flags & MDB_TXN_BLOCKED)
9700 if (txn->mt_dbflags[dbi] & DB_STALE) {
9703 /* Stale, must read the DB's root. cursor_init does it for us. */
9704 mdb_cursor_init(&mc, txn, dbi, &mx);
9706 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
9709 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
9712 if (dbi < CORE_DBS || dbi >= env->me_maxdbs)
9714 ptr = env->me_dbxs[dbi].md_name.mv_data;
9715 /* If there was no name, this was already closed */
9717 env->me_dbxs[dbi].md_name.mv_data = NULL;
9718 env->me_dbxs[dbi].md_name.mv_size = 0;
9719 env->me_dbflags[dbi] = 0;
9720 env->me_dbiseqs[dbi]++;
9725 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
9727 /* We could return the flags for the FREE_DBI too but what's the point? */
9728 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9730 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
9734 /** Add all the DB's pages to the free list.
9735 * @param[in] mc Cursor on the DB to free.
9736 * @param[in] subs non-Zero to check for sub-DBs in this DB.
9737 * @return 0 on success, non-zero on failure.
9740 mdb_drop0(MDB_cursor *mc, int subs)
9744 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
9745 if (rc == MDB_SUCCESS) {
9746 MDB_txn *txn = mc->mc_txn;
9751 /* DUPSORT sub-DBs have no ovpages/DBs. Omit scanning leaves.
9752 * This also avoids any P_LEAF2 pages, which have no nodes.
9754 if (mc->mc_flags & C_SUB)
9757 mdb_cursor_copy(mc, &mx);
9758 while (mc->mc_snum > 0) {
9759 MDB_page *mp = mc->mc_pg[mc->mc_top];
9760 unsigned n = NUMKEYS(mp);
9762 for (i=0; i<n; i++) {
9763 ni = NODEPTR(mp, i);
9764 if (ni->mn_flags & F_BIGDATA) {
9767 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9768 rc = mdb_page_get(txn, pg, &omp, NULL);
9771 mdb_cassert(mc, IS_OVERFLOW(omp));
9772 rc = mdb_midl_append_range(&txn->mt_free_pgs,
9776 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
9777 mdb_xcursor_init1(mc, ni);
9778 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
9784 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
9786 for (i=0; i<n; i++) {
9788 ni = NODEPTR(mp, i);
9791 mdb_midl_xappend(txn->mt_free_pgs, pg);
9796 mc->mc_ki[mc->mc_top] = i;
9797 rc = mdb_cursor_sibling(mc, 1);
9799 if (rc != MDB_NOTFOUND)
9801 /* no more siblings, go back to beginning
9802 * of previous level.
9806 for (i=1; i<mc->mc_snum; i++) {
9808 mc->mc_pg[i] = mx.mc_pg[i];
9813 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
9816 txn->mt_flags |= MDB_TXN_ERROR;
9817 } else if (rc == MDB_NOTFOUND) {
9820 mc->mc_flags &= ~C_INITIALIZED;
9824 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
9826 MDB_cursor *mc, *m2;
9829 if ((unsigned)del > 1 || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9832 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
9835 if (TXN_DBI_CHANGED(txn, dbi))
9838 rc = mdb_cursor_open(txn, dbi, &mc);
9842 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
9843 /* Invalidate the dropped DB's cursors */
9844 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
9845 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
9849 /* Can't delete the main DB */
9850 if (del && dbi >= CORE_DBS) {
9851 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, F_SUBDATA);
9853 txn->mt_dbflags[dbi] = DB_STALE;
9854 mdb_dbi_close(txn->mt_env, dbi);
9856 txn->mt_flags |= MDB_TXN_ERROR;
9859 /* reset the DB record, mark it dirty */
9860 txn->mt_dbflags[dbi] |= DB_DIRTY;
9861 txn->mt_dbs[dbi].md_depth = 0;
9862 txn->mt_dbs[dbi].md_branch_pages = 0;
9863 txn->mt_dbs[dbi].md_leaf_pages = 0;
9864 txn->mt_dbs[dbi].md_overflow_pages = 0;
9865 txn->mt_dbs[dbi].md_entries = 0;
9866 txn->mt_dbs[dbi].md_root = P_INVALID;
9868 txn->mt_flags |= MDB_TXN_DIRTY;
9871 mdb_cursor_close(mc);
9875 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9877 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9880 txn->mt_dbxs[dbi].md_cmp = cmp;
9884 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9886 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9889 txn->mt_dbxs[dbi].md_dcmp = cmp;
9893 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
9895 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9898 txn->mt_dbxs[dbi].md_rel = rel;
9902 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
9904 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9907 txn->mt_dbxs[dbi].md_relctx = ctx;
9912 mdb_env_get_maxkeysize(MDB_env *env)
9914 return ENV_MAXKEY(env);
9918 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
9920 unsigned int i, rdrs;
9923 int rc = 0, first = 1;
9927 if (!env->me_txns) {
9928 return func("(no reader locks)\n", ctx);
9930 rdrs = env->me_txns->mti_numreaders;
9931 mr = env->me_txns->mti_readers;
9932 for (i=0; i<rdrs; i++) {
9934 txnid_t txnid = mr[i].mr_txnid;
9935 sprintf(buf, txnid == (txnid_t)-1 ?
9936 "%10d %"Z"x -\n" : "%10d %"Z"x %"Z"u\n",
9937 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
9940 rc = func(" pid thread txnid\n", ctx);
9944 rc = func(buf, ctx);
9950 rc = func("(no active readers)\n", ctx);
9955 /** Insert pid into list if not already present.
9956 * return -1 if already present.
9959 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
9961 /* binary search of pid in list */
9963 unsigned cursor = 1;
9965 unsigned n = ids[0];
9968 unsigned pivot = n >> 1;
9969 cursor = base + pivot + 1;
9970 val = pid - ids[cursor];
9975 } else if ( val > 0 ) {
9980 /* found, so it's a duplicate */
9989 for (n = ids[0]; n > cursor; n--)
9996 mdb_reader_check(MDB_env *env, int *dead)
10002 return env->me_txns ? mdb_reader_check0(env, 0, dead) : MDB_SUCCESS;
10005 /** As #mdb_reader_check(). rlocked = <caller locked the reader mutex>. */
10007 mdb_reader_check0(MDB_env *env, int rlocked, int *dead)
10009 mdb_mutexref_t rmutex = rlocked ? NULL : env->me_rmutex;
10010 unsigned int i, j, rdrs;
10012 MDB_PID_T *pids, pid;
10013 int rc = MDB_SUCCESS, count = 0;
10015 rdrs = env->me_txns->mti_numreaders;
10016 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
10020 mr = env->me_txns->mti_readers;
10021 for (i=0; i<rdrs; i++) {
10022 pid = mr[i].mr_pid;
10023 if (pid && pid != env->me_pid) {
10024 if (mdb_pid_insert(pids, pid) == 0) {
10025 if (!mdb_reader_pid(env, Pidcheck, pid)) {
10026 /* Stale reader found */
10029 if ((rc = LOCK_MUTEX0(rmutex)) != 0) {
10030 if ((rc = mdb_mutex_failed(env, rmutex, rc)))
10032 rdrs = 0; /* the above checked all readers */
10034 /* Recheck, a new process may have reused pid */
10035 if (mdb_reader_pid(env, Pidcheck, pid))
10039 for (; j<rdrs; j++)
10040 if (mr[j].mr_pid == pid) {
10041 DPRINTF(("clear stale reader pid %u txn %"Z"d",
10042 (unsigned) pid, mr[j].mr_txnid));
10047 UNLOCK_MUTEX(rmutex);
10058 #ifdef MDB_ROBUST_SUPPORTED
10059 /** Handle #LOCK_MUTEX0() failure.
10060 * Try to repair the lock file if the mutex owner died.
10061 * @param[in] env the environment handle
10062 * @param[in] mutex LOCK_MUTEX0() mutex
10063 * @param[in] rc LOCK_MUTEX0() error (nonzero)
10064 * @return 0 on success with the mutex locked, or an error code on failure.
10067 mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc)
10072 if (rc == MDB_OWNERDEAD) {
10073 /* We own the mutex. Clean up after dead previous owner. */
10075 rlocked = (mutex == env->me_rmutex);
10077 /* Keep mti_txnid updated, otherwise next writer can
10078 * overwrite data which latest meta page refers to.
10080 meta = mdb_env_pick_meta(env);
10081 env->me_txns->mti_txnid = meta->mm_txnid;
10082 /* env is hosed if the dead thread was ours */
10084 env->me_flags |= MDB_FATAL_ERROR;
10085 env->me_txn = NULL;
10089 DPRINTF(("%cmutex owner died, %s", (rlocked ? 'r' : 'w'),
10090 (rc ? "this process' env is hosed" : "recovering")));
10091 rc2 = mdb_reader_check0(env, rlocked, NULL);
10093 rc2 = mdb_mutex_consistent(mutex);
10094 if (rc || (rc = rc2)) {
10095 DPRINTF(("LOCK_MUTEX recovery failed, %s", mdb_strerror(rc)));
10096 UNLOCK_MUTEX(mutex);
10102 DPRINTF(("LOCK_MUTEX failed, %s", mdb_strerror(rc)));
10107 #endif /* MDB_ROBUST_SUPPORTED */
10110 #if defined(_WIN32)
10111 static int utf8_to_utf16(const char *src, int srcsize, wchar_t **dst, int *dstsize)
10115 need = MultiByteToWideChar(CP_UTF8, 0, src, srcsize, NULL, 0);
10116 if (need == 0xFFFD)
10120 result = malloc(sizeof(wchar_t) * need);
10121 MultiByteToWideChar(CP_UTF8, 0, src, srcsize, result, need);
10127 #endif /* defined(_WIN32) */