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-2021 Howard Chu, Symas Corp.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted only as authorized by the OpenLDAP
15 * A copy of this license is available in the file LICENSE in the
16 * top-level directory of the distribution or, alternatively, at
17 * <http://www.OpenLDAP.org/license.html>.
19 * This code is derived from btree.c written by Martin Hedenfalk.
21 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
23 * Permission to use, copy, modify, and distribute this software for any
24 * purpose with or without fee is hereby granted, provided that the above
25 * copyright notice and this permission notice appear in all copies.
27 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
28 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
29 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
30 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
31 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
32 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
33 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
38 #if defined(MDB_VL32) || defined(__WIN64__)
39 #define _FILE_OFFSET_BITS 64
44 #include <wchar.h> /* get wcscpy() */
46 /* We use native NT APIs to setup the memory map, so that we can
47 * let the DB file grow incrementally instead of always preallocating
48 * the full size. These APIs are defined in <wdm.h> and <ntifs.h>
49 * but those headers are meant for driver-level development and
50 * conflict with the regular user-level headers, so we explicitly
51 * declare them here. We get pointers to these functions from
52 * NTDLL.DLL at runtime, to avoid buildtime dependencies on any
53 * NTDLL import libraries.
55 typedef NTSTATUS (WINAPI NtCreateSectionFunc)
56 (OUT PHANDLE sh, IN ACCESS_MASK acc,
57 IN void * oa OPTIONAL,
58 IN PLARGE_INTEGER ms OPTIONAL,
59 IN ULONG pp, IN ULONG aa, IN HANDLE fh OPTIONAL);
61 static NtCreateSectionFunc *NtCreateSection;
63 typedef enum _SECTION_INHERIT {
68 typedef NTSTATUS (WINAPI NtMapViewOfSectionFunc)
69 (IN PHANDLE sh, IN HANDLE ph,
70 IN OUT PVOID *addr, IN ULONG_PTR zbits,
71 IN SIZE_T cs, IN OUT PLARGE_INTEGER off OPTIONAL,
72 IN OUT PSIZE_T vs, IN SECTION_INHERIT ih,
73 IN ULONG at, IN ULONG pp);
75 static NtMapViewOfSectionFunc *NtMapViewOfSection;
77 typedef NTSTATUS (WINAPI NtCloseFunc)(HANDLE h);
79 static NtCloseFunc *NtClose;
81 /** getpid() returns int; MinGW defines pid_t but MinGW64 typedefs it
82 * as int64 which is wrong. MSVC doesn't define it at all, so just
86 #define MDB_THR_T DWORD
87 #include <sys/types.h>
90 # include <sys/param.h>
92 # define LITTLE_ENDIAN 1234
93 # define BIG_ENDIAN 4321
94 # define BYTE_ORDER LITTLE_ENDIAN
96 # define SSIZE_MAX INT_MAX
99 #define MDB_OFF_T int64_t
101 #include <sys/types.h>
102 #include <sys/stat.h>
103 #define MDB_PID_T pid_t
104 #define MDB_THR_T pthread_t
105 #include <sys/param.h>
107 #include <sys/mman.h>
108 #ifdef HAVE_SYS_FILE_H
109 #include <sys/file.h>
112 #define MDB_OFF_T off_t
115 #if defined(__mips) && defined(__linux)
116 /* MIPS has cache coherency issues, requires explicit cache control */
117 #include <sys/cachectl.h>
118 #define CACHEFLUSH(addr, bytes, cache) cacheflush(addr, bytes, cache)
120 #define CACHEFLUSH(addr, bytes, cache)
123 #if defined(__linux) && !defined(MDB_FDATASYNC_WORKS)
124 /** fdatasync is broken on ext3/ext4fs on older kernels, see
125 * description in #mdb_env_open2 comments. You can safely
126 * define MDB_FDATASYNC_WORKS if this code will only be run
127 * on kernels 3.6 and newer.
129 #define BROKEN_FDATASYNC
135 #include <inttypes.h>
143 typedef SSIZE_T ssize_t;
148 #if defined(__sun) || defined(__ANDROID__)
149 /* Most platforms have posix_memalign, older may only have memalign */
150 #define HAVE_MEMALIGN 1
152 /* On Solaris, we need the POSIX sigwait function */
154 # define _POSIX_PTHREAD_SEMANTICS 1
158 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
159 #include <netinet/in.h>
160 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
163 #if defined(__FreeBSD__) && defined(__FreeBSD_version) && __FreeBSD_version >= 1100110
164 # define MDB_USE_POSIX_MUTEX 1
165 # define MDB_USE_ROBUST 1
166 #elif defined(__APPLE__) || defined (BSD) || defined(__FreeBSD_kernel__)
167 # if !(defined(MDB_USE_POSIX_MUTEX) || defined(MDB_USE_POSIX_SEM))
168 # define MDB_USE_SYSV_SEM 1
170 # define MDB_FDATASYNC fsync
171 #elif defined(__ANDROID__)
172 # define MDB_FDATASYNC fsync
178 #ifdef MDB_USE_POSIX_SEM
179 # define MDB_USE_HASH 1
180 #include <semaphore.h>
181 #elif defined(MDB_USE_SYSV_SEM)
184 #ifdef _SEM_SEMUN_UNDEFINED
187 struct semid_ds *buf;
188 unsigned short *array;
190 #endif /* _SEM_SEMUN_UNDEFINED */
192 #define MDB_USE_POSIX_MUTEX 1
193 #endif /* MDB_USE_POSIX_SEM */
196 #if defined(_WIN32) + defined(MDB_USE_POSIX_SEM) + defined(MDB_USE_SYSV_SEM) \
197 + defined(MDB_USE_POSIX_MUTEX) != 1
198 # error "Ambiguous shared-lock implementation"
202 #include <valgrind/memcheck.h>
203 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
204 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
205 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
206 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
207 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
209 #define VGMEMP_CREATE(h,r,z)
210 #define VGMEMP_ALLOC(h,a,s)
211 #define VGMEMP_FREE(h,a)
212 #define VGMEMP_DESTROY(h)
213 #define VGMEMP_DEFINED(a,s)
217 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
218 /* Solaris just defines one or the other */
219 # define LITTLE_ENDIAN 1234
220 # define BIG_ENDIAN 4321
221 # ifdef _LITTLE_ENDIAN
222 # define BYTE_ORDER LITTLE_ENDIAN
224 # define BYTE_ORDER BIG_ENDIAN
227 # define BYTE_ORDER __BYTE_ORDER
231 #ifndef LITTLE_ENDIAN
232 #define LITTLE_ENDIAN __LITTLE_ENDIAN
235 #define BIG_ENDIAN __BIG_ENDIAN
238 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
239 #define MISALIGNED_OK 1
245 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
246 # error "Unknown or unsupported endianness (BYTE_ORDER)"
247 #elif (-6 & 5) || CHAR_BIT!=8 || UINT_MAX!=0xffffffff || MDB_SIZE_MAX%UINT_MAX
248 # error "Two's complement, reasonably sized integer types, please"
251 #if (((__clang_major__ << 8) | __clang_minor__) >= 0x0302) || (((__GNUC__ << 8) | __GNUC_MINOR__) >= 0x0403)
252 /** Mark infrequently used env functions as cold. This puts them in a separate
253 * section, and optimizes them for size */
254 #define ESECT __attribute__ ((cold))
256 /* On older compilers, use a separate section */
259 # define ESECT __attribute__ ((section("__TEXT,text_env")))
261 # define ESECT __attribute__ ((section("text_env")))
269 #define CALL_CONV WINAPI
274 /** @defgroup internal LMDB Internals
277 /** @defgroup compat Compatibility Macros
278 * A bunch of macros to minimize the amount of platform-specific ifdefs
279 * needed throughout the rest of the code. When the features this library
280 * needs are similar enough to POSIX to be hidden in a one-or-two line
281 * replacement, this macro approach is used.
285 /** Features under development */
290 /** Wrapper around __func__, which is a C99 feature */
291 #if __STDC_VERSION__ >= 199901L
292 # define mdb_func_ __func__
293 #elif __GNUC__ >= 2 || _MSC_VER >= 1300
294 # define mdb_func_ __FUNCTION__
296 /* If a debug message says <mdb_unknown>(), update the #if statements above */
297 # define mdb_func_ "<mdb_unknown>"
300 /* Internal error codes, not exposed outside liblmdb */
301 #define MDB_NO_ROOT (MDB_LAST_ERRCODE + 10)
303 #define MDB_OWNERDEAD ((int) WAIT_ABANDONED)
304 #elif defined MDB_USE_SYSV_SEM
305 #define MDB_OWNERDEAD (MDB_LAST_ERRCODE + 11)
306 #elif defined(MDB_USE_POSIX_MUTEX) && defined(EOWNERDEAD)
307 #define MDB_OWNERDEAD EOWNERDEAD /**< #LOCK_MUTEX0() result if dead owner */
311 #define GLIBC_VER ((__GLIBC__ << 16 )| __GLIBC_MINOR__)
313 /** Some platforms define the EOWNERDEAD error code
314 * even though they don't support Robust Mutexes.
315 * Compile with -DMDB_USE_ROBUST=0, or use some other
316 * mechanism like -DMDB_USE_SYSV_SEM instead of
317 * -DMDB_USE_POSIX_MUTEX. (SysV semaphores are
318 * also Robust, but some systems don't support them
321 #ifndef MDB_USE_ROBUST
322 /* Android currently lacks Robust Mutex support. So does glibc < 2.4. */
323 # if defined(MDB_USE_POSIX_MUTEX) && (defined(__ANDROID__) || \
324 (defined(__GLIBC__) && GLIBC_VER < 0x020004))
325 # define MDB_USE_ROBUST 0
327 # define MDB_USE_ROBUST 1
329 #endif /* !MDB_USE_ROBUST */
331 #if defined(MDB_USE_POSIX_MUTEX) && (MDB_USE_ROBUST)
332 /* glibc < 2.12 only provided _np API */
333 # if (defined(__GLIBC__) && GLIBC_VER < 0x02000c) || \
334 (defined(PTHREAD_MUTEX_ROBUST_NP) && !defined(PTHREAD_MUTEX_ROBUST))
335 # define PTHREAD_MUTEX_ROBUST PTHREAD_MUTEX_ROBUST_NP
336 # define pthread_mutexattr_setrobust(attr, flag) pthread_mutexattr_setrobust_np(attr, flag)
337 # define pthread_mutex_consistent(mutex) pthread_mutex_consistent_np(mutex)
339 #endif /* MDB_USE_POSIX_MUTEX && MDB_USE_ROBUST */
341 #if defined(MDB_OWNERDEAD) && (MDB_USE_ROBUST)
342 #define MDB_ROBUST_SUPPORTED 1
346 #define MDB_USE_HASH 1
347 #define MDB_PIDLOCK 0
348 #define THREAD_RET DWORD
349 #define pthread_t HANDLE
350 #define pthread_mutex_t HANDLE
351 #define pthread_cond_t HANDLE
352 typedef HANDLE mdb_mutex_t, mdb_mutexref_t;
353 #define pthread_key_t DWORD
354 #define pthread_self() GetCurrentThreadId()
355 #define pthread_key_create(x,y) \
356 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
357 #define pthread_key_delete(x) TlsFree(x)
358 #define pthread_getspecific(x) TlsGetValue(x)
359 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
360 #define pthread_mutex_unlock(x) ReleaseMutex(*x)
361 #define pthread_mutex_lock(x) WaitForSingleObject(*x, INFINITE)
362 #define pthread_cond_signal(x) SetEvent(*x)
363 #define pthread_cond_wait(cond,mutex) do{SignalObjectAndWait(*mutex, *cond, INFINITE, FALSE); WaitForSingleObject(*mutex, INFINITE);}while(0)
364 #define THREAD_CREATE(thr,start,arg) \
365 (((thr) = CreateThread(NULL, 0, start, arg, 0, NULL)) ? 0 : ErrCode())
366 #define THREAD_FINISH(thr) \
367 (WaitForSingleObject(thr, INFINITE) ? ErrCode() : 0)
368 #define LOCK_MUTEX0(mutex) WaitForSingleObject(mutex, INFINITE)
369 #define UNLOCK_MUTEX(mutex) ReleaseMutex(mutex)
370 #define mdb_mutex_consistent(mutex) 0
371 #define getpid() GetCurrentProcessId()
372 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
373 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
374 #define ErrCode() GetLastError()
375 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
376 #define close(fd) (CloseHandle(fd) ? 0 : -1)
377 #define munmap(ptr,len) UnmapViewOfFile(ptr)
378 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
379 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
381 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
384 #define THREAD_RET void *
385 #define THREAD_CREATE(thr,start,arg) pthread_create(&thr,NULL,start,arg)
386 #define THREAD_FINISH(thr) pthread_join(thr,NULL)
388 /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
389 #define MDB_PIDLOCK 1
391 #ifdef MDB_USE_POSIX_SEM
393 typedef sem_t *mdb_mutex_t, *mdb_mutexref_t;
394 #define LOCK_MUTEX0(mutex) mdb_sem_wait(mutex)
395 #define UNLOCK_MUTEX(mutex) sem_post(mutex)
398 mdb_sem_wait(sem_t *sem)
401 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
405 #elif defined MDB_USE_SYSV_SEM
407 typedef struct mdb_mutex {
411 } mdb_mutex_t[1], *mdb_mutexref_t;
413 #define LOCK_MUTEX0(mutex) mdb_sem_wait(mutex)
414 #define UNLOCK_MUTEX(mutex) do { \
415 struct sembuf sb = { 0, 1, SEM_UNDO }; \
416 sb.sem_num = (mutex)->semnum; \
417 *(mutex)->locked = 0; \
418 semop((mutex)->semid, &sb, 1); \
422 mdb_sem_wait(mdb_mutexref_t sem)
424 int rc, *locked = sem->locked;
425 struct sembuf sb = { 0, -1, SEM_UNDO };
426 sb.sem_num = sem->semnum;
428 if (!semop(sem->semid, &sb, 1)) {
429 rc = *locked ? MDB_OWNERDEAD : MDB_SUCCESS;
433 } while ((rc = errno) == EINTR);
437 #define mdb_mutex_consistent(mutex) 0
439 #else /* MDB_USE_POSIX_MUTEX: */
440 /** Shared mutex/semaphore as the original is stored.
442 * Not for copies. Instead it can be assigned to an #mdb_mutexref_t.
443 * When mdb_mutexref_t is a pointer and mdb_mutex_t is not, then it
444 * is array[size 1] so it can be assigned to the pointer.
446 typedef pthread_mutex_t mdb_mutex_t[1];
447 /** Reference to an #mdb_mutex_t */
448 typedef pthread_mutex_t *mdb_mutexref_t;
449 /** Lock the reader or writer mutex.
450 * Returns 0 or a code to give #mdb_mutex_failed(), as in #LOCK_MUTEX().
452 #define LOCK_MUTEX0(mutex) pthread_mutex_lock(mutex)
453 /** Unlock the reader or writer mutex.
455 #define UNLOCK_MUTEX(mutex) pthread_mutex_unlock(mutex)
456 /** Mark mutex-protected data as repaired, after death of previous owner.
458 #define mdb_mutex_consistent(mutex) pthread_mutex_consistent(mutex)
459 #endif /* MDB_USE_POSIX_SEM || MDB_USE_SYSV_SEM */
461 /** Get the error code for the last failed system function.
463 #define ErrCode() errno
465 /** An abstraction for a file handle.
466 * On POSIX systems file handles are small integers. On Windows
467 * they're opaque pointers.
471 /** A value for an invalid file handle.
472 * Mainly used to initialize file variables and signify that they are
475 #define INVALID_HANDLE_VALUE (-1)
477 /** Get the size of a memory page for the system.
478 * This is the basic size that the platform's memory manager uses, and is
479 * fundamental to the use of memory-mapped files.
481 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
484 #define Z MDB_FMT_Z /**< printf/scanf format modifier for size_t */
485 #define Yu MDB_PRIy(u) /**< printf format for #mdb_size_t */
486 #define Yd MDB_PRIy(d) /**< printf format for 'signed #mdb_size_t' */
488 #ifdef MDB_USE_SYSV_SEM
489 #define MNAME_LEN (sizeof(int))
491 #define MNAME_LEN (sizeof(pthread_mutex_t))
494 /** Initial part of #MDB_env.me_mutexname[].
495 * Changes to this code must be reflected in #MDB_LOCK_FORMAT.
498 #define MUTEXNAME_PREFIX "Global\\MDB"
499 #elif defined MDB_USE_POSIX_SEM
500 #define MUTEXNAME_PREFIX "/MDB"
505 #ifdef MDB_ROBUST_SUPPORTED
506 /** Lock mutex, handle any error, set rc = result.
507 * Return 0 on success, nonzero (not rc) on error.
509 #define LOCK_MUTEX(rc, env, mutex) \
510 (((rc) = LOCK_MUTEX0(mutex)) && \
511 ((rc) = mdb_mutex_failed(env, mutex, rc)))
512 static int mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc);
514 #define LOCK_MUTEX(rc, env, mutex) ((rc) = LOCK_MUTEX0(mutex))
515 #define mdb_mutex_failed(env, mutex, rc) (rc)
519 /** A flag for opening a file and requesting synchronous data writes.
520 * This is only used when writing a meta page. It's not strictly needed;
521 * we could just do a normal write and then immediately perform a flush.
522 * But if this flag is available it saves us an extra system call.
524 * @note If O_DSYNC is undefined but exists in /usr/include,
525 * preferably set some compiler flag to get the definition.
529 # define MDB_DSYNC O_DSYNC
531 # define MDB_DSYNC O_SYNC
536 /** Function for flushing the data of a file. Define this to fsync
537 * if fdatasync() is not supported.
539 #ifndef MDB_FDATASYNC
540 # define MDB_FDATASYNC fdatasync
544 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
555 /** A page number in the database.
556 * Note that 64 bit page numbers are overkill, since pages themselves
557 * already represent 12-13 bits of addressable memory, and the OS will
558 * always limit applications to a maximum of 63 bits of address space.
560 * @note In the #MDB_node structure, we only store 48 bits of this value,
561 * which thus limits us to only 60 bits of addressable data.
563 typedef MDB_ID pgno_t;
565 /** A transaction ID.
566 * See struct MDB_txn.mt_txnid for details.
568 typedef MDB_ID txnid_t;
570 /** @defgroup debug Debug Macros
574 /** Enable debug output. Needs variable argument macros (a C99 feature).
575 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
576 * read from and written to the database (used for free space management).
581 #define MDB_DBG_INFO 1
582 #define MDB_DBG_TRACE 2
585 static int mdb_debug = MDB_DBG_TRACE;
586 static txnid_t mdb_debug_start;
588 /** Print a debug message with printf formatting.
589 * Requires double parenthesis around 2 or more args.
591 # define DPRINTF(args) ((void) ((mdb_debug & MDB_DBG_INFO) && DPRINTF0 args))
592 # define DPRINTF0(fmt, ...) \
593 fprintf(stderr, "%s:%d " fmt "\n", mdb_func_, __LINE__, __VA_ARGS__)
594 /** Trace info for replaying */
595 # define MDB_TRACE(args) ((void) ((mdb_debug & MDB_DBG_TRACE) && DPRINTF1 args))
596 # define DPRINTF1(fmt, ...) \
597 fprintf(stderr, ">%d:%s: " fmt "\n", getpid(), mdb_func_, __VA_ARGS__)
599 # define DPRINTF(args) ((void) 0)
600 # define MDB_TRACE(args) ((void) 0)
602 /** Print a debug string.
603 * The string is printed literally, with no format processing.
605 #define DPUTS(arg) DPRINTF(("%s", arg))
606 /** Debugging output value of a cursor DBI: Negative in a sub-cursor. */
608 (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
611 /** @brief The maximum size of a database page.
613 * It is 32k or 64k, since value-PAGEBASE must fit in
614 * #MDB_page.%mp_upper.
616 * LMDB will use database pages < OS pages if needed.
617 * That causes more I/O in write transactions: The OS must
618 * know (read) the whole page before writing a partial page.
620 * Note that we don't currently support Huge pages. On Linux,
621 * regular data files cannot use Huge pages, and in general
622 * Huge pages aren't actually pageable. We rely on the OS
623 * demand-pager to read our data and page it out when memory
624 * pressure from other processes is high. So until OSs have
625 * actual paging support for Huge pages, they're not viable.
627 #define MAX_PAGESIZE (PAGEBASE ? 0x10000 : 0x8000)
629 /** The minimum number of keys required in a database page.
630 * Setting this to a larger value will place a smaller bound on the
631 * maximum size of a data item. Data items larger than this size will
632 * be pushed into overflow pages instead of being stored directly in
633 * the B-tree node. This value used to default to 4. With a page size
634 * of 4096 bytes that meant that any item larger than 1024 bytes would
635 * go into an overflow page. That also meant that on average 2-3KB of
636 * each overflow page was wasted space. The value cannot be lower than
637 * 2 because then there would no longer be a tree structure. With this
638 * value, items larger than 2KB will go into overflow pages, and on
639 * average only 1KB will be wasted.
641 #define MDB_MINKEYS 2
643 /** A stamp that identifies a file as an LMDB file.
644 * There's nothing special about this value other than that it is easily
645 * recognizable, and it will reflect any byte order mismatches.
647 #define MDB_MAGIC 0xBEEFC0DE
649 /** The version number for a database's datafile format. */
650 #define MDB_DATA_VERSION ((MDB_DEVEL) ? 999 : 1)
651 /** The version number for a database's lockfile format. */
652 #define MDB_LOCK_VERSION ((MDB_DEVEL) ? 999 : 2)
653 /** Number of bits representing #MDB_LOCK_VERSION in #MDB_LOCK_FORMAT.
654 * The remaining bits must leave room for #MDB_lock_desc.
656 #define MDB_LOCK_VERSION_BITS 12
658 /** @brief The max size of a key we can write, or 0 for computed max.
660 * This macro should normally be left alone or set to 0.
661 * Note that a database with big keys or dupsort data cannot be
662 * reliably modified by a liblmdb which uses a smaller max.
663 * The default is 511 for backwards compat, or 0 when #MDB_DEVEL.
665 * Other values are allowed, for backwards compat. However:
666 * A value bigger than the computed max can break if you do not
667 * know what you are doing, and liblmdb <= 0.9.10 can break when
668 * modifying a DB with keys/dupsort data bigger than its max.
670 * Data items in an #MDB_DUPSORT database are also limited to
671 * this size, since they're actually keys of a sub-DB. Keys and
672 * #MDB_DUPSORT data items must fit on a node in a regular page.
674 #ifndef MDB_MAXKEYSIZE
675 #define MDB_MAXKEYSIZE ((MDB_DEVEL) ? 0 : 511)
678 /** The maximum size of a key we can write to the environment. */
680 #define ENV_MAXKEY(env) (MDB_MAXKEYSIZE)
682 #define ENV_MAXKEY(env) ((env)->me_maxkey)
685 /** @brief The maximum size of a data item.
687 * We only store a 32 bit value for node sizes.
689 #define MAXDATASIZE 0xffffffffUL
692 /** Key size which fits in a #DKBUF.
695 #define DKBUF_MAXKEYSIZE ((MDB_MAXKEYSIZE) > 0 ? (MDB_MAXKEYSIZE) : 511)
698 * This is used for printing a hex dump of a key's contents.
700 #define DKBUF char kbuf[DKBUF_MAXKEYSIZE*2+1]
701 /** A data value buffer.
703 * This is used for printing a hex dump of a #MDB_DUPSORT value's contents.
705 #define DDBUF char dbuf[DKBUF_MAXKEYSIZE*2+1+2]
706 /** Display a key in hex.
708 * Invoke a function to display a key in hex.
710 #define DKEY(x) mdb_dkey(x, kbuf)
717 /** An invalid page number.
718 * Mainly used to denote an empty tree.
720 #define P_INVALID (~(pgno_t)0)
722 /** Test if the flags \b f are set in a flag word \b w. */
723 #define F_ISSET(w, f) (((w) & (f)) == (f))
725 /** Round \b n up to an even number. */
726 #define EVEN(n) (((n) + 1U) & -2) /* sign-extending -2 to match n+1U */
728 /** Least significant 1-bit of \b n. n must be of an unsigned type. */
729 #define LOW_BIT(n) ((n) & (-(n)))
731 /** (log2(\b p2) % \b n), for p2 = power of 2 and 0 < n < 8. */
732 #define LOG2_MOD(p2, n) (7 - 86 / ((p2) % ((1U<<(n))-1) + 11))
733 /* Explanation: Let p2 = 2**(n*y + x), x<n and M = (1U<<n)-1. Now p2 =
734 * (M+1)**y * 2**x = 2**x (mod M). Finally "/" "happens" to return 7-x.
737 /** Should be alignment of \b type. Ensure it is a power of 2. */
738 #define ALIGNOF2(type) \
739 LOW_BIT(offsetof(struct { char ch_; type align_; }, align_))
741 /** Used for offsets within a single page.
742 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
745 typedef uint16_t indx_t;
747 typedef unsigned long long mdb_hash_t;
749 /** Default size of memory map.
750 * This is certainly too small for any actual applications. Apps should always set
751 * the size explicitly using #mdb_env_set_mapsize().
753 #define DEFAULT_MAPSIZE 1048576
755 /** @defgroup readers Reader Lock Table
756 * Readers don't acquire any locks for their data access. Instead, they
757 * simply record their transaction ID in the reader table. The reader
758 * mutex is needed just to find an empty slot in the reader table. The
759 * slot's address is saved in thread-specific data so that subsequent read
760 * transactions started by the same thread need no further locking to proceed.
762 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
764 * No reader table is used if the database is on a read-only filesystem, or
765 * if #MDB_NOLOCK is set.
767 * Since the database uses multi-version concurrency control, readers don't
768 * actually need any locking. This table is used to keep track of which
769 * readers are using data from which old transactions, so that we'll know
770 * when a particular old transaction is no longer in use. Old transactions
771 * that have discarded any data pages can then have those pages reclaimed
772 * for use by a later write transaction.
774 * The lock table is constructed such that reader slots are aligned with the
775 * processor's cache line size. Any slot is only ever used by one thread.
776 * This alignment guarantees that there will be no contention or cache
777 * thrashing as threads update their own slot info, and also eliminates
778 * any need for locking when accessing a slot.
780 * A writer thread will scan every slot in the table to determine the oldest
781 * outstanding reader transaction. Any freed pages older than this will be
782 * reclaimed by the writer. The writer doesn't use any locks when scanning
783 * this table. This means that there's no guarantee that the writer will
784 * see the most up-to-date reader info, but that's not required for correct
785 * operation - all we need is to know the upper bound on the oldest reader,
786 * we don't care at all about the newest reader. So the only consequence of
787 * reading stale information here is that old pages might hang around a
788 * while longer before being reclaimed. That's actually good anyway, because
789 * the longer we delay reclaiming old pages, the more likely it is that a
790 * string of contiguous pages can be found after coalescing old pages from
791 * many old transactions together.
794 /** Number of slots in the reader table.
795 * This value was chosen somewhat arbitrarily. 126 readers plus a
796 * couple mutexes fit exactly into 8KB on my development machine.
797 * Applications should set the table size using #mdb_env_set_maxreaders().
799 #define DEFAULT_READERS 126
801 /** The size of a CPU cache line in bytes. We want our lock structures
802 * aligned to this size to avoid false cache line sharing in the
804 * This value works for most CPUs. For Itanium this should be 128.
810 /** The information we store in a single slot of the reader table.
811 * In addition to a transaction ID, we also record the process and
812 * thread ID that owns a slot, so that we can detect stale information,
813 * e.g. threads or processes that went away without cleaning up.
814 * @note We currently don't check for stale records. We simply re-init
815 * the table when we know that we're the only process opening the
818 typedef struct MDB_rxbody {
819 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
820 * Multiple readers that start at the same time will probably have the
821 * same ID here. Again, it's not important to exclude them from
822 * anything; all we need to know is which version of the DB they
823 * started from so we can avoid overwriting any data used in that
824 * particular version.
826 volatile txnid_t mrb_txnid;
827 /** The process ID of the process owning this reader txn. */
828 volatile MDB_PID_T mrb_pid;
829 /** The thread ID of the thread owning this txn. */
830 volatile MDB_THR_T mrb_tid;
833 /** The actual reader record, with cacheline padding. */
834 typedef struct MDB_reader {
837 /** shorthand for mrb_txnid */
838 #define mr_txnid mru.mrx.mrb_txnid
839 #define mr_pid mru.mrx.mrb_pid
840 #define mr_tid mru.mrx.mrb_tid
841 /** cache line alignment */
842 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
846 /** The header for the reader table.
847 * The table resides in a memory-mapped file. (This is a different file
848 * than is used for the main database.)
850 * For POSIX the actual mutexes reside in the shared memory of this
851 * mapped file. On Windows, mutexes are named objects allocated by the
852 * kernel; we store the mutex names in this mapped file so that other
853 * processes can grab them. This same approach is also used on
854 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
855 * process-shared POSIX mutexes. For these cases where a named object
856 * is used, the object name is derived from a 64 bit FNV hash of the
857 * environment pathname. As such, naming collisions are extremely
858 * unlikely. If a collision occurs, the results are unpredictable.
860 typedef struct MDB_txbody {
861 /** Stamp identifying this as an LMDB file. It must be set
864 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
866 /** The ID of the last transaction committed to the database.
867 * This is recorded here only for convenience; the value can always
868 * be determined by reading the main database meta pages.
870 volatile txnid_t mtb_txnid;
871 /** The number of slots that have been used in the reader table.
872 * This always records the maximum count, it is not decremented
873 * when readers release their slots.
875 volatile unsigned mtb_numreaders;
876 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
877 /** Binary form of names of the reader/writer locks */
878 mdb_hash_t mtb_mutexid;
879 #elif defined(MDB_USE_SYSV_SEM)
883 /** Mutex protecting access to this table.
884 * This is the reader table lock used with LOCK_MUTEX().
886 mdb_mutex_t mtb_rmutex;
890 /** The actual reader table definition. */
891 typedef struct MDB_txninfo {
894 #define mti_magic mt1.mtb.mtb_magic
895 #define mti_format mt1.mtb.mtb_format
896 #define mti_rmutex mt1.mtb.mtb_rmutex
897 #define mti_txnid mt1.mtb.mtb_txnid
898 #define mti_numreaders mt1.mtb.mtb_numreaders
899 #define mti_mutexid mt1.mtb.mtb_mutexid
900 #ifdef MDB_USE_SYSV_SEM
901 #define mti_semid mt1.mtb.mtb_semid
902 #define mti_rlocked mt1.mtb.mtb_rlocked
904 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
906 #if !(defined(_WIN32) || defined(MDB_USE_POSIX_SEM))
908 #ifdef MDB_USE_SYSV_SEM
910 #define mti_wlocked mt2.mt2_wlocked
912 mdb_mutex_t mt2_wmutex;
913 #define mti_wmutex mt2.mt2_wmutex
915 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
918 MDB_reader mti_readers[1];
921 /** Lockfile format signature: version, features and field layout */
922 #define MDB_LOCK_FORMAT \
924 (((MDB_LOCK_VERSION) % (1U << MDB_LOCK_VERSION_BITS)) \
925 + MDB_lock_desc * (1U << MDB_LOCK_VERSION_BITS)))
927 /** Lock type and layout. Values 0-119. _WIN32 implies #MDB_PIDLOCK.
928 * Some low values are reserved for future tweaks.
931 # define MDB_LOCK_TYPE (0 + ALIGNOF2(mdb_hash_t)/8 % 2)
932 #elif defined MDB_USE_POSIX_SEM
933 # define MDB_LOCK_TYPE (4 + ALIGNOF2(mdb_hash_t)/8 % 2)
934 #elif defined MDB_USE_SYSV_SEM
935 # define MDB_LOCK_TYPE (8)
936 #elif defined MDB_USE_POSIX_MUTEX
937 /* We do not know the inside of a POSIX mutex and how to check if mutexes
938 * used by two executables are compatible. Just check alignment and size.
940 # define MDB_LOCK_TYPE (10 + \
941 LOG2_MOD(ALIGNOF2(pthread_mutex_t), 5) + \
942 sizeof(pthread_mutex_t) / 4U % 22 * 5)
946 /** Magic number for lockfile layout and features.
948 * This *attempts* to stop liblmdb variants compiled with conflicting
949 * options from using the lockfile at the same time and thus breaking
950 * it. It describes locking types, and sizes and sometimes alignment
951 * of the various lockfile items.
953 * The detected ranges are mostly guesswork, or based simply on how
954 * big they could be without using more bits. So we can tweak them
955 * in good conscience when updating #MDB_LOCK_VERSION.
958 /* Default CACHELINE=64 vs. other values (have seen mention of 32-256) */
959 (CACHELINE==64 ? 0 : 1 + LOG2_MOD(CACHELINE >> (CACHELINE>64), 5))
960 + 6 * (sizeof(MDB_PID_T)/4 % 3) /* legacy(2) to word(4/8)? */
961 + 18 * (sizeof(pthread_t)/4 % 5) /* can be struct{id, active data} */
962 + 90 * (sizeof(MDB_txbody) / CACHELINE % 3)
963 + 270 * (MDB_LOCK_TYPE % 120)
964 /* The above is < 270*120 < 2**15 */
965 + ((sizeof(txnid_t) == 8) << 15) /* 32bit/64bit */
966 + ((sizeof(MDB_reader) > CACHELINE) << 16)
967 /* Not really needed - implied by MDB_LOCK_TYPE != (_WIN32 locking) */
968 + (((MDB_PIDLOCK) != 0) << 17)
969 /* 18 bits total: Must be <= (32 - MDB_LOCK_VERSION_BITS). */
973 /** Common header for all page types. The page type depends on #mp_flags.
975 * #P_BRANCH and #P_LEAF pages have unsorted '#MDB_node's at the end, with
976 * sorted #mp_ptrs[] entries referring to them. Exception: #P_LEAF2 pages
977 * omit mp_ptrs and pack sorted #MDB_DUPFIXED values after the page header.
979 * #P_OVERFLOW records occupy one or more contiguous pages where only the
980 * first has a page header. They hold the real data of #F_BIGDATA nodes.
982 * #P_SUBP sub-pages are small leaf "pages" with duplicate data.
983 * A node with flag #F_DUPDATA but not #F_SUBDATA contains a sub-page.
984 * (Duplicate data can also go in sub-databases, which use normal pages.)
986 * #P_META pages contain #MDB_meta, the start point of an LMDB snapshot.
988 * Each non-metapage up to #MDB_meta.%mm_last_pg is reachable exactly once
989 * in the snapshot: Either used by a database or listed in a freeDB record.
991 typedef struct MDB_page {
992 #define mp_pgno mp_p.p_pgno
993 #define mp_next mp_p.p_next
995 pgno_t p_pgno; /**< page number */
996 struct MDB_page *p_next; /**< for in-memory list of freed pages */
998 uint16_t mp_pad; /**< key size if this is a LEAF2 page */
999 /** @defgroup mdb_page Page Flags
1001 * Flags for the page headers.
1004 #define P_BRANCH 0x01 /**< branch page */
1005 #define P_LEAF 0x02 /**< leaf page */
1006 #define P_OVERFLOW 0x04 /**< overflow page */
1007 #define P_META 0x08 /**< meta page */
1008 #define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
1009 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
1010 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
1011 #define P_LOOSE 0x4000 /**< page was dirtied then freed, can be reused */
1012 #define P_KEEP 0x8000 /**< leave this page alone during spill */
1014 uint16_t mp_flags; /**< @ref mdb_page */
1015 #define mp_lower mp_pb.pb.pb_lower
1016 #define mp_upper mp_pb.pb.pb_upper
1017 #define mp_pages mp_pb.pb_pages
1020 indx_t pb_lower; /**< lower bound of free space */
1021 indx_t pb_upper; /**< upper bound of free space */
1023 uint32_t pb_pages; /**< number of overflow pages */
1025 indx_t mp_ptrs[0]; /**< dynamic size */
1028 /** Alternate page header, for 2-byte aligned access */
1029 typedef struct MDB_page2 {
1030 uint16_t mp2_p[sizeof(pgno_t)/2];
1038 #define MP_PGNO(p) (((MDB_page2 *)(void *)(p))->mp2_p)
1039 #define MP_PAD(p) (((MDB_page2 *)(void *)(p))->mp2_pad)
1040 #define MP_FLAGS(p) (((MDB_page2 *)(void *)(p))->mp2_flags)
1041 #define MP_LOWER(p) (((MDB_page2 *)(void *)(p))->mp2_lower)
1042 #define MP_UPPER(p) (((MDB_page2 *)(void *)(p))->mp2_upper)
1043 #define MP_PTRS(p) (((MDB_page2 *)(void *)(p))->mp2_ptrs)
1045 /** Size of the page header, excluding dynamic data at the end */
1046 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
1048 /** Address of first usable data byte in a page, after the header */
1049 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
1051 /** ITS#7713, change PAGEBASE to handle 65536 byte pages */
1052 #define PAGEBASE ((MDB_DEVEL) ? PAGEHDRSZ : 0)
1054 /** Number of nodes on a page */
1055 #define NUMKEYS(p) ((MP_LOWER(p) - (PAGEHDRSZ-PAGEBASE)) >> 1)
1057 /** The amount of space remaining in the page */
1058 #define SIZELEFT(p) (indx_t)(MP_UPPER(p) - MP_LOWER(p))
1060 /** The percentage of space used in the page, in tenths of a percent. */
1061 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
1062 ((env)->me_psize - PAGEHDRSZ))
1063 /** The minimum page fill factor, in tenths of a percent.
1064 * Pages emptier than this are candidates for merging.
1066 #define FILL_THRESHOLD 250
1068 /** Test if a page is a leaf page */
1069 #define IS_LEAF(p) F_ISSET(MP_FLAGS(p), P_LEAF)
1070 /** Test if a page is a LEAF2 page */
1071 #define IS_LEAF2(p) F_ISSET(MP_FLAGS(p), P_LEAF2)
1072 /** Test if a page is a branch page */
1073 #define IS_BRANCH(p) F_ISSET(MP_FLAGS(p), P_BRANCH)
1074 /** Test if a page is an overflow page */
1075 #define IS_OVERFLOW(p) F_ISSET(MP_FLAGS(p), P_OVERFLOW)
1076 /** Test if a page is a sub page */
1077 #define IS_SUBP(p) F_ISSET(MP_FLAGS(p), P_SUBP)
1079 /** The number of overflow pages needed to store the given size. */
1080 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
1082 /** Link in #MDB_txn.%mt_loose_pgs list.
1083 * Kept outside the page header, which is needed when reusing the page.
1085 #define NEXT_LOOSE_PAGE(p) (*(MDB_page **)((p) + 2))
1087 /** Header for a single key/data pair within a page.
1088 * Used in pages of type #P_BRANCH and #P_LEAF without #P_LEAF2.
1089 * We guarantee 2-byte alignment for 'MDB_node's.
1091 * #mn_lo and #mn_hi are used for data size on leaf nodes, and for child
1092 * pgno on branch nodes. On 64 bit platforms, #mn_flags is also used
1093 * for pgno. (Branch nodes have no flags). Lo and hi are in host byte
1094 * order in case some accesses can be optimized to 32-bit word access.
1096 * Leaf node flags describe node contents. #F_BIGDATA says the node's
1097 * data part is the page number of an overflow page with actual data.
1098 * #F_DUPDATA and #F_SUBDATA can be combined giving duplicate data in
1099 * a sub-page/sub-database, and named databases (just #F_SUBDATA).
1101 typedef struct MDB_node {
1102 /** part of data size or pgno
1104 #if BYTE_ORDER == LITTLE_ENDIAN
1105 unsigned short mn_lo, mn_hi;
1107 unsigned short mn_hi, mn_lo;
1110 /** @defgroup mdb_node Node Flags
1112 * Flags for node headers.
1115 #define F_BIGDATA 0x01 /**< data put on overflow page */
1116 #define F_SUBDATA 0x02 /**< data is a sub-database */
1117 #define F_DUPDATA 0x04 /**< data has duplicates */
1119 /** valid flags for #mdb_node_add() */
1120 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
1123 unsigned short mn_flags; /**< @ref mdb_node */
1124 unsigned short mn_ksize; /**< key size */
1125 char mn_data[1]; /**< key and data are appended here */
1128 /** Size of the node header, excluding dynamic data at the end */
1129 #define NODESIZE offsetof(MDB_node, mn_data)
1131 /** Bit position of top word in page number, for shifting mn_flags */
1132 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
1134 /** Size of a node in a branch page with a given key.
1135 * This is just the node header plus the key, there is no data.
1137 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
1139 /** Size of a node in a leaf page with a given key and data.
1140 * This is node header plus key plus data size.
1142 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
1144 /** Address of node \b i in page \b p */
1145 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + MP_PTRS(p)[i] + PAGEBASE))
1147 /** Address of the key for the node */
1148 #define NODEKEY(node) (void *)((node)->mn_data)
1150 /** Address of the data for a node */
1151 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
1153 /** Get the page number pointed to by a branch node */
1154 #define NODEPGNO(node) \
1155 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
1156 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
1157 /** Set the page number in a branch node */
1158 #define SETPGNO(node,pgno) do { \
1159 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
1160 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
1162 /** Get the size of the data in a leaf node */
1163 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
1164 /** Set the size of the data for a leaf node */
1165 #define SETDSZ(node,size) do { \
1166 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
1167 /** The size of a key in a node */
1168 #define NODEKSZ(node) ((node)->mn_ksize)
1170 /** Copy a page number from src to dst */
1171 #ifdef MISALIGNED_OK
1172 #define COPY_PGNO(dst,src) dst = src
1174 #define MP_PGNO(p) ((p)->mp_pgno)
1176 #if MDB_SIZE_MAX > 0xffffffffU
1177 #define COPY_PGNO(dst,src) do { \
1178 unsigned short *s, *d; \
1179 s = (unsigned short *)&(src); \
1180 d = (unsigned short *)&(dst); \
1187 #define COPY_PGNO(dst,src) do { \
1188 unsigned short *s, *d; \
1189 s = (unsigned short *)&(src); \
1190 d = (unsigned short *)&(dst); \
1196 /** The address of a key in a LEAF2 page.
1197 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
1198 * There are no node headers, keys are stored contiguously.
1200 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
1202 /** Set the \b node's key into \b keyptr, if requested. */
1203 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
1204 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
1206 /** Set the \b node's key into \b key. */
1207 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
1209 /** Information about a single database in the environment. */
1210 typedef struct MDB_db {
1211 uint32_t md_pad; /**< also ksize for LEAF2 pages */
1212 uint16_t md_flags; /**< @ref mdb_dbi_open */
1213 uint16_t md_depth; /**< depth of this tree */
1214 pgno_t md_branch_pages; /**< number of internal pages */
1215 pgno_t md_leaf_pages; /**< number of leaf pages */
1216 pgno_t md_overflow_pages; /**< number of overflow pages */
1217 mdb_size_t md_entries; /**< number of data items */
1218 pgno_t md_root; /**< the root page of this tree */
1221 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
1222 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
1223 /** #mdb_dbi_open() flags */
1224 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
1225 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
1227 /** Handle for the DB used to track free pages. */
1229 /** Handle for the default DB. */
1231 /** Number of DBs in metapage (free and main) - also hardcoded elsewhere */
1234 /** Number of meta pages - also hardcoded elsewhere */
1237 /** Meta page content.
1238 * A meta page is the start point for accessing a database snapshot.
1239 * Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
1241 typedef struct MDB_meta {
1242 /** Stamp identifying this as an LMDB file. It must be set
1245 /** Version number of this file. Must be set to #MDB_DATA_VERSION. */
1246 uint32_t mm_version;
1248 union { /* always zero since we don't support fixed mapping in MDB_VL32 */
1252 #define mm_address mm_un.mmun_address
1254 void *mm_address; /**< address for fixed mapping */
1256 mdb_size_t mm_mapsize; /**< size of mmap region */
1257 MDB_db mm_dbs[CORE_DBS]; /**< first is free space, 2nd is main db */
1258 /** The size of pages used in this DB */
1259 #define mm_psize mm_dbs[FREE_DBI].md_pad
1260 /** Any persistent environment flags. @ref mdb_env */
1261 #define mm_flags mm_dbs[FREE_DBI].md_flags
1262 /** Last used page in the datafile.
1263 * Actually the file may be shorter if the freeDB lists the final pages.
1266 volatile txnid_t mm_txnid; /**< txnid that committed this page */
1269 /** Buffer for a stack-allocated meta page.
1270 * The members define size and alignment, and silence type
1271 * aliasing warnings. They are not used directly; that could
1272 * mean incorrectly using several union members in parallel.
1274 typedef union MDB_metabuf {
1277 char mm_pad[PAGEHDRSZ];
1282 /** Auxiliary DB info.
1283 * The information here is mostly static/read-only. There is
1284 * only a single copy of this record in the environment.
1286 typedef struct MDB_dbx {
1287 MDB_val md_name; /**< name of the database */
1288 MDB_cmp_func *md_cmp; /**< function for comparing keys */
1289 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
1290 MDB_rel_func *md_rel; /**< user relocate function */
1291 void *md_relctx; /**< user-provided context for md_rel */
1294 /** A database transaction.
1295 * Every operation requires a transaction handle.
1298 MDB_txn *mt_parent; /**< parent of a nested txn */
1299 /** Nested txn under this txn, set together with flag #MDB_TXN_HAS_CHILD */
1301 pgno_t mt_next_pgno; /**< next unallocated page */
1303 pgno_t mt_last_pgno; /**< last written page */
1305 /** The ID of this transaction. IDs are integers incrementing from 1.
1306 * Only committed write transactions increment the ID. If a transaction
1307 * aborts, the ID may be re-used by the next writer.
1310 MDB_env *mt_env; /**< the DB environment */
1311 /** The list of pages that became unused during this transaction.
1313 MDB_IDL mt_free_pgs;
1314 /** The list of loose pages that became unused and may be reused
1315 * in this transaction, linked through #NEXT_LOOSE_PAGE(page).
1317 MDB_page *mt_loose_pgs;
1318 /** Number of loose pages (#mt_loose_pgs) */
1320 /** The sorted list of dirty pages we temporarily wrote to disk
1321 * because the dirty list was full. page numbers in here are
1322 * shifted left by 1, deleted slots have the LSB set.
1324 MDB_IDL mt_spill_pgs;
1326 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
1327 MDB_ID2L dirty_list;
1328 /** For read txns: This thread/txn's reader table slot, or NULL. */
1331 /** Array of records for each DB known in the environment. */
1333 /** Array of MDB_db records for each known DB */
1335 /** Array of sequence numbers for each DB handle */
1336 unsigned int *mt_dbiseqs;
1337 /** @defgroup mt_dbflag Transaction DB Flags
1341 #define DB_DIRTY 0x01 /**< DB was written in this txn */
1342 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
1343 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
1344 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
1345 #define DB_USRVALID 0x10 /**< As #DB_VALID, but not set for #FREE_DBI */
1346 #define DB_DUPDATA 0x20 /**< DB is #MDB_DUPSORT data */
1348 /** In write txns, array of cursors for each DB */
1349 MDB_cursor **mt_cursors;
1350 /** Array of flags for each DB */
1351 unsigned char *mt_dbflags;
1353 /** List of read-only pages (actually chunks) */
1355 /** We map chunks of 16 pages. Even though Windows uses 4KB pages, all
1356 * mappings must begin on 64KB boundaries. So we round off all pgnos to
1357 * a chunk boundary. We do the same on Linux for symmetry, and also to
1358 * reduce the frequency of mmap/munmap calls.
1360 #define MDB_RPAGE_CHUNK 16
1361 #define MDB_TRPAGE_SIZE 4096 /**< size of #mt_rpages array of chunks */
1362 #define MDB_TRPAGE_MAX (MDB_TRPAGE_SIZE-1) /**< maximum chunk index */
1363 unsigned int mt_rpcheck; /**< threshold for reclaiming unref'd chunks */
1365 /** Number of DB records in use, or 0 when the txn is finished.
1366 * This number only ever increments until the txn finishes; we
1367 * don't decrement it when individual DB handles are closed.
1371 /** @defgroup mdb_txn Transaction Flags
1375 /** #mdb_txn_begin() flags */
1376 #define MDB_TXN_BEGIN_FLAGS (MDB_NOMETASYNC|MDB_NOSYNC|MDB_RDONLY)
1377 #define MDB_TXN_NOMETASYNC MDB_NOMETASYNC /**< don't sync meta for this txn on commit */
1378 #define MDB_TXN_NOSYNC MDB_NOSYNC /**< don't sync this txn on commit */
1379 #define MDB_TXN_RDONLY MDB_RDONLY /**< read-only transaction */
1380 /* internal txn flags */
1381 #define MDB_TXN_WRITEMAP MDB_WRITEMAP /**< copy of #MDB_env flag in writers */
1382 #define MDB_TXN_FINISHED 0x01 /**< txn is finished or never began */
1383 #define MDB_TXN_ERROR 0x02 /**< txn is unusable after an error */
1384 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
1385 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
1386 #define MDB_TXN_HAS_CHILD 0x10 /**< txn has an #MDB_txn.%mt_child */
1387 /** most operations on the txn are currently illegal */
1388 #define MDB_TXN_BLOCKED (MDB_TXN_FINISHED|MDB_TXN_ERROR|MDB_TXN_HAS_CHILD)
1390 unsigned int mt_flags; /**< @ref mdb_txn */
1391 /** #dirty_list room: Array size - \#dirty pages visible to this txn.
1392 * Includes ancestor txns' dirty pages not hidden by other txns'
1393 * dirty/spilled pages. Thus commit(nested txn) has room to merge
1394 * dirty_list into mt_parent after freeing hidden mt_parent pages.
1396 unsigned int mt_dirty_room;
1399 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
1400 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
1401 * raise this on a 64 bit machine.
1403 #define CURSOR_STACK 32
1407 /** Cursors are used for all DB operations.
1408 * A cursor holds a path of (page pointer, key index) from the DB
1409 * root to a position in the DB, plus other state. #MDB_DUPSORT
1410 * cursors include an xcursor to the current data item. Write txns
1411 * track their cursors and keep them up to date when data moves.
1412 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
1413 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
1416 /** Next cursor on this DB in this txn */
1417 MDB_cursor *mc_next;
1418 /** Backup of the original cursor if this cursor is a shadow */
1419 MDB_cursor *mc_backup;
1420 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
1421 struct MDB_xcursor *mc_xcursor;
1422 /** The transaction that owns this cursor */
1424 /** The database handle this cursor operates on */
1426 /** The database record for this cursor */
1428 /** The database auxiliary record for this cursor */
1430 /** The @ref mt_dbflag for this database */
1431 unsigned char *mc_dbflag;
1432 unsigned short mc_snum; /**< number of pushed pages */
1433 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
1434 /** @defgroup mdb_cursor Cursor Flags
1436 * Cursor state flags.
1439 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
1440 #define C_EOF 0x02 /**< No more data */
1441 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
1442 #define C_DEL 0x08 /**< last op was a cursor_del */
1443 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
1444 #define C_WRITEMAP MDB_TXN_WRITEMAP /**< Copy of txn flag */
1445 /** Read-only cursor into the txn's original snapshot in the map.
1446 * Set for read-only txns, and in #mdb_page_alloc() for #FREE_DBI when
1447 * #MDB_DEVEL & 2. Only implements code which is necessary for this.
1449 #define C_ORIG_RDONLY MDB_TXN_RDONLY
1451 unsigned int mc_flags; /**< @ref mdb_cursor */
1452 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
1453 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
1455 MDB_page *mc_ovpg; /**< a referenced overflow page */
1456 # define MC_OVPG(mc) ((mc)->mc_ovpg)
1457 # define MC_SET_OVPG(mc, pg) ((mc)->mc_ovpg = (pg))
1459 # define MC_OVPG(mc) ((MDB_page *)0)
1460 # define MC_SET_OVPG(mc, pg) ((void)0)
1464 /** Context for sorted-dup records.
1465 * We could have gone to a fully recursive design, with arbitrarily
1466 * deep nesting of sub-databases. But for now we only handle these
1467 * levels - main DB, optional sub-DB, sorted-duplicate DB.
1469 typedef struct MDB_xcursor {
1470 /** A sub-cursor for traversing the Dup DB */
1471 MDB_cursor mx_cursor;
1472 /** The database record for this Dup DB */
1474 /** The auxiliary DB record for this Dup DB */
1476 /** The @ref mt_dbflag for this Dup DB */
1477 unsigned char mx_dbflag;
1480 /** Check if there is an inited xcursor */
1481 #define XCURSOR_INITED(mc) \
1482 ((mc)->mc_xcursor && ((mc)->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
1484 /** Update the xcursor's sub-page pointer, if any, in \b mc. Needed
1485 * when the node which contains the sub-page may have moved. Called
1486 * with leaf page \b mp = mc->mc_pg[\b top].
1488 #define XCURSOR_REFRESH(mc, top, mp) do { \
1489 MDB_page *xr_pg = (mp); \
1490 MDB_node *xr_node; \
1491 if (!XCURSOR_INITED(mc) || (mc)->mc_ki[top] >= NUMKEYS(xr_pg)) break; \
1492 xr_node = NODEPTR(xr_pg, (mc)->mc_ki[top]); \
1493 if ((xr_node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) \
1494 (mc)->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(xr_node); \
1497 /** State of FreeDB old pages, stored in the MDB_env */
1498 typedef struct MDB_pgstate {
1499 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1500 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1503 /** The database environment. */
1505 HANDLE me_fd; /**< The main data file */
1506 HANDLE me_lfd; /**< The lock file */
1507 HANDLE me_mfd; /**< For writing and syncing the meta pages */
1510 HANDLE me_fmh; /**< File Mapping handle */
1511 #endif /* MDB_VL32 */
1512 HANDLE me_ovfd; /**< Overlapped/async with write-through file handle */
1514 /** Failed to update the meta page. Probably an I/O error. */
1515 #define MDB_FATAL_ERROR 0x80000000U
1516 /** Some fields are initialized. */
1517 #define MDB_ENV_ACTIVE 0x20000000U
1518 /** me_txkey is set */
1519 #define MDB_ENV_TXKEY 0x10000000U
1520 /** fdatasync is unreliable */
1521 #define MDB_FSYNCONLY 0x08000000U
1522 uint32_t me_flags; /**< @ref mdb_env */
1523 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1524 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1525 unsigned int me_maxreaders; /**< size of the reader table */
1526 /** Max #MDB_txninfo.%mti_numreaders of interest to #mdb_env_close() */
1527 volatile int me_close_readers;
1528 MDB_dbi me_numdbs; /**< number of DBs opened */
1529 MDB_dbi me_maxdbs; /**< size of the DB table */
1530 MDB_PID_T me_pid; /**< process ID of this env */
1531 char *me_path; /**< path to the DB files */
1532 char *me_map; /**< the memory map of the data file */
1533 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1534 MDB_meta *me_metas[NUM_METAS]; /**< pointers to the two meta pages */
1535 void *me_pbuf; /**< scratch area for DUPSORT put() */
1536 MDB_txn *me_txn; /**< current write transaction */
1537 MDB_txn *me_txn0; /**< prealloc'd write transaction */
1538 mdb_size_t me_mapsize; /**< size of the data memory map */
1539 MDB_OFF_T me_size; /**< current file size */
1540 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1541 MDB_dbx *me_dbxs; /**< array of static DB info */
1542 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1543 unsigned int *me_dbiseqs; /**< array of dbi sequence numbers */
1544 pthread_key_t me_txkey; /**< thread-key for readers */
1545 txnid_t me_pgoldest; /**< ID of oldest reader last time we looked */
1546 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1547 # define me_pglast me_pgstate.mf_pglast
1548 # define me_pghead me_pgstate.mf_pghead
1549 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1550 /** IDL of pages that became unused in a write txn */
1551 MDB_IDL me_free_pgs;
1552 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1553 MDB_ID2L me_dirty_list;
1554 /** Max number of freelist items that can fit in a single overflow page */
1556 /** Max size of a node on a page */
1557 unsigned int me_nodemax;
1558 #if !(MDB_MAXKEYSIZE)
1559 unsigned int me_maxkey; /**< max size of a key */
1561 int me_live_reader; /**< have liveness lock in reader table */
1563 int me_pidquery; /**< Used in OpenProcess */
1564 OVERLAPPED *ov; /**< Used for for overlapping I/O requests */
1565 int ovs; /**< Count of OVERLAPPEDs */
1567 #ifdef MDB_USE_POSIX_MUTEX /* Posix mutexes reside in shared mem */
1568 # define me_rmutex me_txns->mti_rmutex /**< Shared reader lock */
1569 # define me_wmutex me_txns->mti_wmutex /**< Shared writer lock */
1571 mdb_mutex_t me_rmutex;
1572 mdb_mutex_t me_wmutex;
1573 # if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
1574 /** Half-initialized name of mutexes, to be completed by #MUTEXNAME() */
1575 char me_mutexname[sizeof(MUTEXNAME_PREFIX) + 11];
1579 MDB_ID3L me_rpages; /**< like #mt_rpages, but global to env */
1580 pthread_mutex_t me_rpmutex; /**< control access to #me_rpages */
1581 #define MDB_ERPAGE_SIZE 16384
1582 #define MDB_ERPAGE_MAX (MDB_ERPAGE_SIZE-1)
1583 unsigned int me_rpcheck;
1585 void *me_userctx; /**< User-settable context */
1586 MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
1589 /** Nested transaction */
1590 typedef struct MDB_ntxn {
1591 MDB_txn mnt_txn; /**< the transaction */
1592 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1595 /** max number of pages to commit in one writev() call */
1596 #define MDB_COMMIT_PAGES 64
1597 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1598 #undef MDB_COMMIT_PAGES
1599 #define MDB_COMMIT_PAGES IOV_MAX
1602 /** max bytes to write in one call */
1603 #define MAX_WRITE (0x40000000U >> (sizeof(ssize_t) == 4))
1605 /** Check \b txn and \b dbi arguments to a function */
1606 #define TXN_DBI_EXIST(txn, dbi, validity) \
1607 ((txn) && (dbi)<(txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & (validity)))
1609 /** Check for misused \b dbi handles */
1610 #define TXN_DBI_CHANGED(txn, dbi) \
1611 ((txn)->mt_dbiseqs[dbi] != (txn)->mt_env->me_dbiseqs[dbi])
1613 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1614 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1615 static int mdb_page_touch(MDB_cursor *mc);
1617 #define MDB_END_NAMES {"committed", "empty-commit", "abort", "reset", \
1618 "reset-tmp", "fail-begin", "fail-beginchild"}
1620 /* mdb_txn_end operation number, for logging */
1621 MDB_END_COMMITTED, MDB_END_EMPTY_COMMIT, MDB_END_ABORT, MDB_END_RESET,
1622 MDB_END_RESET_TMP, MDB_END_FAIL_BEGIN, MDB_END_FAIL_BEGINCHILD
1624 #define MDB_END_OPMASK 0x0F /**< mask for #mdb_txn_end() operation number */
1625 #define MDB_END_UPDATE 0x10 /**< update env state (DBIs) */
1626 #define MDB_END_FREE 0x20 /**< free txn unless it is #MDB_env.%me_txn0 */
1627 #define MDB_END_SLOT MDB_NOTLS /**< release any reader slot if #MDB_NOTLS */
1628 static void mdb_txn_end(MDB_txn *txn, unsigned mode);
1630 static int mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **mp, int *lvl);
1631 static int mdb_page_search_root(MDB_cursor *mc,
1632 MDB_val *key, int modify);
1633 #define MDB_PS_MODIFY 1
1634 #define MDB_PS_ROOTONLY 2
1635 #define MDB_PS_FIRST 4
1636 #define MDB_PS_LAST 8
1637 static int mdb_page_search(MDB_cursor *mc,
1638 MDB_val *key, int flags);
1639 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1641 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1642 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1643 pgno_t newpgno, unsigned int nflags);
1645 static int mdb_env_read_header(MDB_env *env, int prev, MDB_meta *meta);
1646 static MDB_meta *mdb_env_pick_meta(const MDB_env *env);
1647 static int mdb_env_write_meta(MDB_txn *txn);
1648 #if defined(MDB_USE_POSIX_MUTEX) && !defined(MDB_ROBUST_SUPPORTED) /* Drop unused excl arg */
1649 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1651 static void mdb_env_close0(MDB_env *env, int excl);
1653 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1654 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1655 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1656 static void mdb_node_del(MDB_cursor *mc, int ksize);
1657 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1658 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft);
1659 static int mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data);
1660 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1661 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1663 static int mdb_rebalance(MDB_cursor *mc);
1664 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1666 static void mdb_cursor_pop(MDB_cursor *mc);
1667 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1669 static int _mdb_cursor_del(MDB_cursor *mc, unsigned int flags);
1670 static int _mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data, unsigned int flags);
1672 static int mdb_cursor_del0(MDB_cursor *mc);
1673 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
1674 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1675 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1676 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1677 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1679 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1680 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1682 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1683 static void mdb_xcursor_init0(MDB_cursor *mc);
1684 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1685 static void mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int force);
1687 static int mdb_drop0(MDB_cursor *mc, int subs);
1688 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1689 static int mdb_reader_check0(MDB_env *env, int rlocked, int *dead);
1692 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1695 /** Compare two items pointing at '#mdb_size_t's of unknown alignment. */
1696 #ifdef MISALIGNED_OK
1697 # define mdb_cmp_clong mdb_cmp_long
1699 # define mdb_cmp_clong mdb_cmp_cint
1702 /** True if we need #mdb_cmp_clong() instead of \b cmp for #MDB_INTEGERDUP */
1703 #define NEED_CMP_CLONG(cmp, ksize) \
1704 (UINT_MAX < MDB_SIZE_MAX && \
1705 (cmp) == mdb_cmp_int && (ksize) == sizeof(mdb_size_t))
1708 static SECURITY_DESCRIPTOR mdb_null_sd;
1709 static SECURITY_ATTRIBUTES mdb_all_sa;
1710 static int mdb_sec_inited;
1713 static int utf8_to_utf16(const char *src, struct MDB_name *dst, int xtra);
1716 /** Return the library version info. */
1718 mdb_version(int *major, int *minor, int *patch)
1720 if (major) *major = MDB_VERSION_MAJOR;
1721 if (minor) *minor = MDB_VERSION_MINOR;
1722 if (patch) *patch = MDB_VERSION_PATCH;
1723 return MDB_VERSION_STRING;
1726 /** Table of descriptions for LMDB @ref errors */
1727 static char *const mdb_errstr[] = {
1728 "MDB_KEYEXIST: Key/data pair already exists",
1729 "MDB_NOTFOUND: No matching key/data pair found",
1730 "MDB_PAGE_NOTFOUND: Requested page not found",
1731 "MDB_CORRUPTED: Located page was wrong type",
1732 "MDB_PANIC: Update of meta page failed or environment had fatal error",
1733 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1734 "MDB_INVALID: File is not an LMDB file",
1735 "MDB_MAP_FULL: Environment mapsize limit reached",
1736 "MDB_DBS_FULL: Environment maxdbs limit reached",
1737 "MDB_READERS_FULL: Environment maxreaders limit reached",
1738 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1739 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1740 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1741 "MDB_PAGE_FULL: Internal error - page has no more space",
1742 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1743 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1744 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1745 "MDB_BAD_TXN: Transaction must abort, has a child, or is invalid",
1746 "MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
1747 "MDB_BAD_DBI: The specified DBI handle was closed/changed unexpectedly",
1748 "MDB_PROBLEM: Unexpected problem - txn should abort",
1752 mdb_strerror(int err)
1755 /** HACK: pad 4KB on stack over the buf. Return system msgs in buf.
1756 * This works as long as no function between the call to mdb_strerror
1757 * and the actual use of the message uses more than 4K of stack.
1759 #define MSGSIZE 1024
1760 #define PADSIZE 4096
1761 char buf[MSGSIZE+PADSIZE], *ptr = buf;
1765 return ("Successful return: 0");
1767 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1768 i = err - MDB_KEYEXIST;
1769 return mdb_errstr[i];
1773 /* These are the C-runtime error codes we use. The comment indicates
1774 * their numeric value, and the Win32 error they would correspond to
1775 * if the error actually came from a Win32 API. A major mess, we should
1776 * have used LMDB-specific error codes for everything.
1779 case ENOENT: /* 2, FILE_NOT_FOUND */
1780 case EIO: /* 5, ACCESS_DENIED */
1781 case ENOMEM: /* 12, INVALID_ACCESS */
1782 case EACCES: /* 13, INVALID_DATA */
1783 case EBUSY: /* 16, CURRENT_DIRECTORY */
1784 case EINVAL: /* 22, BAD_COMMAND */
1785 case ENOSPC: /* 28, OUT_OF_PAPER */
1786 return strerror(err);
1791 FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
1792 FORMAT_MESSAGE_IGNORE_INSERTS,
1793 NULL, err, 0, ptr, MSGSIZE, NULL);
1797 return "Invalid error code";
1798 return strerror(err);
1802 /** assert(3) variant in cursor context */
1803 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1804 /** assert(3) variant in transaction context */
1805 #define mdb_tassert(txn, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1806 /** assert(3) variant in environment context */
1807 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1810 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1811 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1814 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1815 const char *func, const char *file, int line)
1818 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1819 file, line, expr_txt, func);
1820 if (env->me_assert_func)
1821 env->me_assert_func(env, buf);
1822 fprintf(stderr, "%s\n", buf);
1826 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1830 /** Return the page number of \b mp which may be sub-page, for debug output */
1832 mdb_dbg_pgno(MDB_page *mp)
1835 COPY_PGNO(ret, MP_PGNO(mp));
1839 /** Display a key in hexadecimal and return the address of the result.
1840 * @param[in] key the key to display
1841 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1842 * @return The key in hexadecimal form.
1845 mdb_dkey(MDB_val *key, char *buf)
1848 unsigned char *c = key->mv_data;
1854 if (key->mv_size > DKBUF_MAXKEYSIZE)
1855 return "MDB_MAXKEYSIZE";
1856 /* may want to make this a dynamic check: if the key is mostly
1857 * printable characters, print it as-is instead of converting to hex.
1861 for (i=0; i<key->mv_size; i++)
1862 ptr += sprintf(ptr, "%02x", *c++);
1864 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1870 mdb_dval(MDB_txn *txn, MDB_dbi dbi, MDB_val *data, char *buf)
1872 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
1873 mdb_dkey(data, buf+1);
1875 strcpy(buf + data->mv_size * 2 + 1, "]");
1882 mdb_leafnode_type(MDB_node *n)
1884 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1885 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1886 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1889 /** Display all the keys in the page. */
1891 mdb_page_list(MDB_page *mp)
1893 pgno_t pgno = mdb_dbg_pgno(mp);
1894 const char *type, *state = (MP_FLAGS(mp) & P_DIRTY) ? ", dirty" : "";
1896 unsigned int i, nkeys, nsize, total = 0;
1900 switch (MP_FLAGS(mp) & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1901 case P_BRANCH: type = "Branch page"; break;
1902 case P_LEAF: type = "Leaf page"; break;
1903 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1904 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1905 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1907 fprintf(stderr, "Overflow page %"Yu" pages %u%s\n",
1908 pgno, mp->mp_pages, state);
1911 fprintf(stderr, "Meta-page %"Yu" txnid %"Yu"\n",
1912 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1915 fprintf(stderr, "Bad page %"Yu" flags 0x%X\n", pgno, MP_FLAGS(mp));
1919 nkeys = NUMKEYS(mp);
1920 fprintf(stderr, "%s %"Yu" numkeys %d%s\n", type, pgno, nkeys, state);
1922 for (i=0; i<nkeys; i++) {
1923 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1924 key.mv_size = nsize = mp->mp_pad;
1925 key.mv_data = LEAF2KEY(mp, i, nsize);
1927 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1930 node = NODEPTR(mp, i);
1931 key.mv_size = node->mn_ksize;
1932 key.mv_data = node->mn_data;
1933 nsize = NODESIZE + key.mv_size;
1934 if (IS_BRANCH(mp)) {
1935 fprintf(stderr, "key %d: page %"Yu", %s\n", i, NODEPGNO(node),
1939 if (F_ISSET(node->mn_flags, F_BIGDATA))
1940 nsize += sizeof(pgno_t);
1942 nsize += NODEDSZ(node);
1944 nsize += sizeof(indx_t);
1945 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1946 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1948 total = EVEN(total);
1950 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1951 IS_LEAF2(mp) ? PAGEHDRSZ : PAGEBASE + MP_LOWER(mp), total, SIZELEFT(mp));
1955 mdb_cursor_chk(MDB_cursor *mc)
1961 if (!mc->mc_snum || !(mc->mc_flags & C_INITIALIZED)) return;
1962 for (i=0; i<mc->mc_top; i++) {
1964 node = NODEPTR(mp, mc->mc_ki[i]);
1965 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1968 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1970 if (XCURSOR_INITED(mc)) {
1971 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
1972 if (((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) &&
1973 mc->mc_xcursor->mx_cursor.mc_pg[0] != NODEDATA(node)) {
1981 /** Count all the pages in each DB and in the freelist
1982 * and make sure it matches the actual number of pages
1984 * All named DBs must be open for a correct count.
1986 static void mdb_audit(MDB_txn *txn)
1990 MDB_ID freecount, count;
1995 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1996 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1997 freecount += *(MDB_ID *)data.mv_data;
1998 mdb_tassert(txn, rc == MDB_NOTFOUND);
2001 for (i = 0; i<txn->mt_numdbs; i++) {
2003 if (!(txn->mt_dbflags[i] & DB_VALID))
2005 mdb_cursor_init(&mc, txn, i, &mx);
2006 if (txn->mt_dbs[i].md_root == P_INVALID)
2008 count += txn->mt_dbs[i].md_branch_pages +
2009 txn->mt_dbs[i].md_leaf_pages +
2010 txn->mt_dbs[i].md_overflow_pages;
2011 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
2012 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
2013 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
2016 mp = mc.mc_pg[mc.mc_top];
2017 for (j=0; j<NUMKEYS(mp); j++) {
2018 MDB_node *leaf = NODEPTR(mp, j);
2019 if (leaf->mn_flags & F_SUBDATA) {
2021 memcpy(&db, NODEDATA(leaf), sizeof(db));
2022 count += db.md_branch_pages + db.md_leaf_pages +
2023 db.md_overflow_pages;
2027 mdb_tassert(txn, rc == MDB_NOTFOUND);
2030 if (freecount + count + NUM_METAS != txn->mt_next_pgno) {
2031 fprintf(stderr, "audit: %"Yu" freecount: %"Yu" count: %"Yu" total: %"Yu" next_pgno: %"Yu"\n",
2032 txn->mt_txnid, freecount, count+NUM_METAS,
2033 freecount+count+NUM_METAS, txn->mt_next_pgno);
2039 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
2041 return txn->mt_dbxs[dbi].md_cmp(a, b);
2045 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
2047 MDB_cmp_func *dcmp = txn->mt_dbxs[dbi].md_dcmp;
2048 if (NEED_CMP_CLONG(dcmp, a->mv_size))
2049 dcmp = mdb_cmp_clong;
2053 /** Allocate memory for a page.
2054 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
2055 * Set #MDB_TXN_ERROR on failure.
2058 mdb_page_malloc(MDB_txn *txn, unsigned num)
2060 MDB_env *env = txn->mt_env;
2061 MDB_page *ret = env->me_dpages;
2062 size_t psize = env->me_psize, sz = psize, off;
2063 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
2064 * For a single page alloc, we init everything after the page header.
2065 * For multi-page, we init the final page; if the caller needed that
2066 * many pages they will be filling in at least up to the last page.
2070 VGMEMP_ALLOC(env, ret, sz);
2071 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
2072 env->me_dpages = ret->mp_next;
2075 psize -= off = PAGEHDRSZ;
2080 if ((ret = malloc(sz)) != NULL) {
2081 VGMEMP_ALLOC(env, ret, sz);
2082 if (!(env->me_flags & MDB_NOMEMINIT)) {
2083 memset((char *)ret + off, 0, psize);
2087 txn->mt_flags |= MDB_TXN_ERROR;
2091 /** Free a single page.
2092 * Saves single pages to a list, for future reuse.
2093 * (This is not used for multi-page overflow pages.)
2096 mdb_page_free(MDB_env *env, MDB_page *mp)
2098 mp->mp_next = env->me_dpages;
2099 VGMEMP_FREE(env, mp);
2100 env->me_dpages = mp;
2103 /** Free a dirty page */
2105 mdb_dpage_free(MDB_env *env, MDB_page *dp)
2107 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
2108 mdb_page_free(env, dp);
2110 /* large pages just get freed directly */
2111 VGMEMP_FREE(env, dp);
2116 /** Return all dirty pages to dpage list */
2118 mdb_dlist_free(MDB_txn *txn)
2120 MDB_env *env = txn->mt_env;
2121 MDB_ID2L dl = txn->mt_u.dirty_list;
2122 unsigned i, n = dl[0].mid;
2124 for (i = 1; i <= n; i++) {
2125 mdb_dpage_free(env, dl[i].mptr);
2132 mdb_page_unref(MDB_txn *txn, MDB_page *mp)
2135 MDB_ID3L tl = txn->mt_rpages;
2137 if (mp->mp_flags & (P_SUBP|P_DIRTY))
2139 rem = mp->mp_pgno & (MDB_RPAGE_CHUNK-1);
2140 pgno = mp->mp_pgno ^ rem;
2141 x = mdb_mid3l_search(tl, pgno);
2142 if (x != tl[0].mid && tl[x+1].mid == mp->mp_pgno)
2147 #define MDB_PAGE_UNREF(txn, mp) mdb_page_unref(txn, mp)
2150 mdb_cursor_unref(MDB_cursor *mc)
2153 if (mc->mc_txn->mt_rpages[0].mid) {
2154 if (!mc->mc_snum || !mc->mc_pg[0] || IS_SUBP(mc->mc_pg[0]))
2156 for (i=0; i<mc->mc_snum; i++)
2157 mdb_page_unref(mc->mc_txn, mc->mc_pg[i]);
2159 mdb_page_unref(mc->mc_txn, mc->mc_ovpg);
2163 mc->mc_snum = mc->mc_top = 0;
2164 mc->mc_pg[0] = NULL;
2165 mc->mc_flags &= ~C_INITIALIZED;
2167 #define MDB_CURSOR_UNREF(mc, force) \
2168 (((force) || ((mc)->mc_flags & C_INITIALIZED)) \
2169 ? mdb_cursor_unref(mc) \
2173 #define MDB_PAGE_UNREF(txn, mp)
2174 #define MDB_CURSOR_UNREF(mc, force) ((void)0)
2175 #endif /* MDB_VL32 */
2177 /** Loosen or free a single page.
2178 * Saves single pages to a list for future reuse
2179 * in this same txn. It has been pulled from the freeDB
2180 * and already resides on the dirty list, but has been
2181 * deleted. Use these pages first before pulling again
2184 * If the page wasn't dirtied in this txn, just add it
2185 * to this txn's free list.
2188 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
2191 pgno_t pgno = mp->mp_pgno;
2192 MDB_txn *txn = mc->mc_txn;
2194 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
2195 if (txn->mt_parent) {
2196 MDB_ID2 *dl = txn->mt_u.dirty_list;
2197 /* If txn has a parent, make sure the page is in our
2201 unsigned x = mdb_mid2l_search(dl, pgno);
2202 if (x <= dl[0].mid && dl[x].mid == pgno) {
2203 if (mp != dl[x].mptr) { /* bad cursor? */
2204 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2205 txn->mt_flags |= MDB_TXN_ERROR;
2213 /* no parent txn, so it's just ours */
2218 DPRINTF(("loosen db %d page %"Yu, DDBI(mc), mp->mp_pgno));
2219 NEXT_LOOSE_PAGE(mp) = txn->mt_loose_pgs;
2220 txn->mt_loose_pgs = mp;
2221 txn->mt_loose_count++;
2222 mp->mp_flags |= P_LOOSE;
2224 int rc = mdb_midl_append(&txn->mt_free_pgs, pgno);
2232 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
2233 * @param[in] mc A cursor handle for the current operation.
2234 * @param[in] pflags Flags of the pages to update:
2235 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
2236 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
2237 * @return 0 on success, non-zero on failure.
2240 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
2242 enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
2243 MDB_txn *txn = mc->mc_txn;
2244 MDB_cursor *m3, *m0 = mc;
2249 int rc = MDB_SUCCESS, level;
2251 /* Mark pages seen by cursors: First m0, then tracked cursors */
2252 for (i = txn->mt_numdbs;; ) {
2253 if (mc->mc_flags & C_INITIALIZED) {
2254 for (m3 = mc;; m3 = &mx->mx_cursor) {
2256 for (j=0; j<m3->mc_snum; j++) {
2258 if ((mp->mp_flags & Mask) == pflags)
2259 mp->mp_flags ^= P_KEEP;
2261 mx = m3->mc_xcursor;
2262 /* Proceed to mx if it is at a sub-database */
2263 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
2265 if (! (mp && (mp->mp_flags & P_LEAF)))
2267 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
2268 if (!(leaf->mn_flags & F_SUBDATA))
2273 for (; !mc || mc == m0; mc = txn->mt_cursors[--i])
2280 /* Mark dirty root pages */
2281 for (i=0; i<txn->mt_numdbs; i++) {
2282 if (txn->mt_dbflags[i] & DB_DIRTY) {
2283 pgno_t pgno = txn->mt_dbs[i].md_root;
2284 if (pgno == P_INVALID)
2286 if ((rc = mdb_page_get(m0, pgno, &dp, &level)) != MDB_SUCCESS)
2288 if ((dp->mp_flags & Mask) == pflags && level <= 1)
2289 dp->mp_flags ^= P_KEEP;
2297 static int mdb_page_flush(MDB_txn *txn, int keep);
2299 /** Spill pages from the dirty list back to disk.
2300 * This is intended to prevent running into #MDB_TXN_FULL situations,
2301 * but note that they may still occur in a few cases:
2302 * 1) our estimate of the txn size could be too small. Currently this
2303 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
2304 * 2) child txns may run out of space if their parents dirtied a
2305 * lot of pages and never spilled them. TODO: we probably should do
2306 * a preemptive spill during #mdb_txn_begin() of a child txn, if
2307 * the parent's dirty_room is below a given threshold.
2309 * Otherwise, if not using nested txns, it is expected that apps will
2310 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
2311 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
2312 * If the txn never references them again, they can be left alone.
2313 * If the txn only reads them, they can be used without any fuss.
2314 * If the txn writes them again, they can be dirtied immediately without
2315 * going thru all of the work of #mdb_page_touch(). Such references are
2316 * handled by #mdb_page_unspill().
2318 * Also note, we never spill DB root pages, nor pages of active cursors,
2319 * because we'll need these back again soon anyway. And in nested txns,
2320 * we can't spill a page in a child txn if it was already spilled in a
2321 * parent txn. That would alter the parent txns' data even though
2322 * the child hasn't committed yet, and we'd have no way to undo it if
2323 * the child aborted.
2325 * @param[in] m0 cursor A cursor handle identifying the transaction and
2326 * database for which we are checking space.
2327 * @param[in] key For a put operation, the key being stored.
2328 * @param[in] data For a put operation, the data being stored.
2329 * @return 0 on success, non-zero on failure.
2332 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
2334 MDB_txn *txn = m0->mc_txn;
2336 MDB_ID2L dl = txn->mt_u.dirty_list;
2337 unsigned int i, j, need;
2340 if (m0->mc_flags & C_SUB)
2343 /* Estimate how much space this op will take */
2344 i = m0->mc_db->md_depth;
2345 /* Named DBs also dirty the main DB */
2346 if (m0->mc_dbi >= CORE_DBS)
2347 i += txn->mt_dbs[MAIN_DBI].md_depth;
2348 /* For puts, roughly factor in the key+data size */
2350 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
2351 i += i; /* double it for good measure */
2354 if (txn->mt_dirty_room > i)
2357 if (!txn->mt_spill_pgs) {
2358 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
2359 if (!txn->mt_spill_pgs)
2362 /* purge deleted slots */
2363 MDB_IDL sl = txn->mt_spill_pgs;
2364 unsigned int num = sl[0];
2366 for (i=1; i<=num; i++) {
2373 /* Preserve pages which may soon be dirtied again */
2374 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
2377 /* Less aggressive spill - we originally spilled the entire dirty list,
2378 * with a few exceptions for cursor pages and DB root pages. But this
2379 * turns out to be a lot of wasted effort because in a large txn many
2380 * of those pages will need to be used again. So now we spill only 1/8th
2381 * of the dirty pages. Testing revealed this to be a good tradeoff,
2382 * better than 1/2, 1/4, or 1/10.
2384 if (need < MDB_IDL_UM_MAX / 8)
2385 need = MDB_IDL_UM_MAX / 8;
2387 /* Save the page IDs of all the pages we're flushing */
2388 /* flush from the tail forward, this saves a lot of shifting later on. */
2389 for (i=dl[0].mid; i && need; i--) {
2390 MDB_ID pn = dl[i].mid << 1;
2392 if (dp->mp_flags & (P_LOOSE|P_KEEP))
2394 /* Can't spill twice, make sure it's not already in a parent's
2397 if (txn->mt_parent) {
2399 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
2400 if (tx2->mt_spill_pgs) {
2401 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
2402 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
2403 dp->mp_flags |= P_KEEP;
2411 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
2415 mdb_midl_sort(txn->mt_spill_pgs);
2417 /* Flush the spilled part of dirty list */
2418 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
2421 /* Reset any dirty pages we kept that page_flush didn't see */
2422 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
2425 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
2429 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
2431 mdb_find_oldest(MDB_txn *txn)
2434 txnid_t mr, oldest = txn->mt_txnid - 1;
2435 if (txn->mt_env->me_txns) {
2436 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
2437 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
2448 /** Add a page to the txn's dirty list */
2450 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
2453 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
2454 #ifdef _WIN32 /* With Windows we always write dirty pages with WriteFile,
2455 * so we always want them ordered */
2456 insert = mdb_mid2l_insert;
2457 #else /* but otherwise with writemaps, we just use msync, we
2458 * don't need the ordering and just append */
2459 if (txn->mt_flags & MDB_TXN_WRITEMAP)
2460 insert = mdb_mid2l_append;
2462 insert = mdb_mid2l_insert;
2464 mid.mid = mp->mp_pgno;
2466 rc = insert(txn->mt_u.dirty_list, &mid);
2467 mdb_tassert(txn, rc == 0);
2468 txn->mt_dirty_room--;
2471 /** Allocate page numbers and memory for writing. Maintain me_pglast,
2472 * me_pghead and mt_next_pgno. Set #MDB_TXN_ERROR on failure.
2474 * If there are free pages available from older transactions, they
2475 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
2476 * Do not modify the freedB, just merge freeDB records into me_pghead[]
2477 * and move me_pglast to say which records were consumed. Only this
2478 * function can create me_pghead and move me_pglast/mt_next_pgno.
2479 * When #MDB_DEVEL & 2, it is not affected by #mdb_freelist_save(): it
2480 * then uses the transaction's original snapshot of the freeDB.
2481 * @param[in] mc cursor A cursor handle identifying the transaction and
2482 * database for which we are allocating.
2483 * @param[in] num the number of pages to allocate.
2484 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
2485 * will always be satisfied by a single contiguous chunk of memory.
2486 * @return 0 on success, non-zero on failure.
2489 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
2491 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
2492 /* Get at most <Max_retries> more freeDB records once me_pghead
2493 * has enough pages. If not enough, use new pages from the map.
2494 * If <Paranoid> and mc is updating the freeDB, only get new
2495 * records if me_pghead is empty. Then the freelist cannot play
2496 * catch-up with itself by growing while trying to save it.
2498 enum { Paranoid = 1, Max_retries = 500 };
2500 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
2502 int rc, retry = num * 60;
2503 MDB_txn *txn = mc->mc_txn;
2504 MDB_env *env = txn->mt_env;
2505 pgno_t pgno, *mop = env->me_pghead;
2506 unsigned i, j, mop_len = mop ? mop[0] : 0, n2 = num-1;
2508 txnid_t oldest = 0, last;
2513 /* If there are any loose pages, just use them */
2514 if (num == 1 && txn->mt_loose_pgs) {
2515 np = txn->mt_loose_pgs;
2516 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
2517 txn->mt_loose_count--;
2518 DPRINTF(("db %d use loose page %"Yu, DDBI(mc), np->mp_pgno));
2525 /* If our dirty list is already full, we can't do anything */
2526 if (txn->mt_dirty_room == 0) {
2531 for (op = MDB_FIRST;; op = MDB_NEXT) {
2536 /* Seek a big enough contiguous page range. Prefer
2537 * pages at the tail, just truncating the list.
2543 if (mop[i-n2] == pgno+n2)
2550 if (op == MDB_FIRST) { /* 1st iteration */
2551 /* Prepare to fetch more and coalesce */
2552 last = env->me_pglast;
2553 oldest = env->me_pgoldest;
2554 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
2555 #if (MDB_DEVEL) & 2 /* "& 2" so MDB_DEVEL=1 won't hide bugs breaking freeDB */
2556 /* Use original snapshot. TODO: Should need less care in code
2557 * which modifies the database. Maybe we can delete some code?
2559 m2.mc_flags |= C_ORIG_RDONLY;
2560 m2.mc_db = &env->me_metas[(txn->mt_txnid-1) & 1]->mm_dbs[FREE_DBI];
2561 m2.mc_dbflag = (unsigned char *)""; /* probably unnecessary */
2565 key.mv_data = &last; /* will look up last+1 */
2566 key.mv_size = sizeof(last);
2568 if (Paranoid && mc->mc_dbi == FREE_DBI)
2571 if (Paranoid && retry < 0 && mop_len)
2575 /* Do not fetch more if the record will be too recent */
2576 if (oldest <= last) {
2578 oldest = mdb_find_oldest(txn);
2579 env->me_pgoldest = oldest;
2585 rc = mdb_cursor_get(&m2, &key, NULL, op);
2587 if (rc == MDB_NOTFOUND)
2591 last = *(txnid_t*)key.mv_data;
2592 if (oldest <= last) {
2594 oldest = mdb_find_oldest(txn);
2595 env->me_pgoldest = oldest;
2601 np = m2.mc_pg[m2.mc_top];
2602 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
2603 if ((rc = mdb_node_read(&m2, leaf, &data)) != MDB_SUCCESS)
2606 idl = (MDB_ID *) data.mv_data;
2609 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
2614 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
2616 mop = env->me_pghead;
2618 env->me_pglast = last;
2620 DPRINTF(("IDL read txn %"Yu" root %"Yu" num %u",
2621 last, txn->mt_dbs[FREE_DBI].md_root, i));
2623 DPRINTF(("IDL %"Yu, idl[j]));
2625 /* Merge in descending sorted order */
2626 mdb_midl_xmerge(mop, idl);
2630 /* Use new pages from the map when nothing suitable in the freeDB */
2632 pgno = txn->mt_next_pgno;
2633 if (pgno + num >= env->me_maxpg) {
2634 DPUTS("DB size maxed out");
2638 #if defined(_WIN32) && !defined(MDB_VL32)
2639 if (!(env->me_flags & MDB_RDONLY)) {
2641 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
2642 p = VirtualAlloc(p, env->me_psize * num, MEM_COMMIT,
2643 (env->me_flags & MDB_WRITEMAP) ? PAGE_READWRITE:
2646 DPUTS("VirtualAlloc failed");
2654 if (env->me_flags & MDB_WRITEMAP) {
2655 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
2657 if (!(np = mdb_page_malloc(txn, num))) {
2663 mop[0] = mop_len -= num;
2664 /* Move any stragglers down */
2665 for (j = i-num; j < mop_len; )
2666 mop[++j] = mop[++i];
2668 txn->mt_next_pgno = pgno + num;
2671 mdb_page_dirty(txn, np);
2677 txn->mt_flags |= MDB_TXN_ERROR;
2681 /** Copy the used portions of a non-overflow page.
2682 * @param[in] dst page to copy into
2683 * @param[in] src page to copy from
2684 * @param[in] psize size of a page
2687 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2689 enum { Align = sizeof(pgno_t) };
2690 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2692 /* If page isn't full, just copy the used portion. Adjust
2693 * alignment so memcpy may copy words instead of bytes.
2695 if ((unused &= -Align) && !IS_LEAF2(src)) {
2696 upper = (upper + PAGEBASE) & -Align;
2697 memcpy(dst, src, (lower + PAGEBASE + (Align-1)) & -Align);
2698 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2701 memcpy(dst, src, psize - unused);
2705 /** Pull a page off the txn's spill list, if present.
2706 * If a page being referenced was spilled to disk in this txn, bring
2707 * it back and make it dirty/writable again.
2708 * @param[in] txn the transaction handle.
2709 * @param[in] mp the page being referenced. It must not be dirty.
2710 * @param[out] ret the writable page, if any. ret is unchanged if
2711 * mp wasn't spilled.
2714 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2716 MDB_env *env = txn->mt_env;
2719 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2721 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2722 if (!tx2->mt_spill_pgs)
2724 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2725 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2728 if (txn->mt_dirty_room == 0)
2729 return MDB_TXN_FULL;
2730 if (IS_OVERFLOW(mp))
2734 if (env->me_flags & MDB_WRITEMAP) {
2737 np = mdb_page_malloc(txn, num);
2741 memcpy(np, mp, num * env->me_psize);
2743 mdb_page_copy(np, mp, env->me_psize);
2746 /* If in current txn, this page is no longer spilled.
2747 * If it happens to be the last page, truncate the spill list.
2748 * Otherwise mark it as deleted by setting the LSB.
2750 if (x == txn->mt_spill_pgs[0])
2751 txn->mt_spill_pgs[0]--;
2753 txn->mt_spill_pgs[x] |= 1;
2754 } /* otherwise, if belonging to a parent txn, the
2755 * page remains spilled until child commits
2758 mdb_page_dirty(txn, np);
2759 np->mp_flags |= P_DIRTY;
2767 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2768 * Set #MDB_TXN_ERROR on failure.
2769 * @param[in] mc cursor pointing to the page to be touched
2770 * @return 0 on success, non-zero on failure.
2773 mdb_page_touch(MDB_cursor *mc)
2775 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2776 MDB_txn *txn = mc->mc_txn;
2777 MDB_cursor *m2, *m3;
2781 if (!F_ISSET(MP_FLAGS(mp), P_DIRTY)) {
2782 if (txn->mt_flags & MDB_TXN_SPILLS) {
2784 rc = mdb_page_unspill(txn, mp, &np);
2790 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2791 (rc = mdb_page_alloc(mc, 1, &np)))
2794 DPRINTF(("touched db %d page %"Yu" -> %"Yu, DDBI(mc),
2795 mp->mp_pgno, pgno));
2796 mdb_cassert(mc, mp->mp_pgno != pgno);
2797 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2798 /* Update the parent page, if any, to point to the new page */
2800 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2801 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2802 SETPGNO(node, pgno);
2804 mc->mc_db->md_root = pgno;
2806 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2807 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2809 /* If txn has a parent, make sure the page is in our
2813 unsigned x = mdb_mid2l_search(dl, pgno);
2814 if (x <= dl[0].mid && dl[x].mid == pgno) {
2815 if (mp != dl[x].mptr) { /* bad cursor? */
2816 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2817 txn->mt_flags |= MDB_TXN_ERROR;
2823 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2825 np = mdb_page_malloc(txn, 1);
2830 rc = mdb_mid2l_insert(dl, &mid);
2831 mdb_cassert(mc, rc == 0);
2836 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2838 np->mp_flags |= P_DIRTY;
2841 /* Adjust cursors pointing to mp */
2842 mc->mc_pg[mc->mc_top] = np;
2843 m2 = txn->mt_cursors[mc->mc_dbi];
2844 if (mc->mc_flags & C_SUB) {
2845 for (; m2; m2=m2->mc_next) {
2846 m3 = &m2->mc_xcursor->mx_cursor;
2847 if (m3->mc_snum < mc->mc_snum) continue;
2848 if (m3->mc_pg[mc->mc_top] == mp)
2849 m3->mc_pg[mc->mc_top] = np;
2852 for (; m2; m2=m2->mc_next) {
2853 if (m2->mc_snum < mc->mc_snum) continue;
2854 if (m2 == mc) continue;
2855 if (m2->mc_pg[mc->mc_top] == mp) {
2856 m2->mc_pg[mc->mc_top] = np;
2858 XCURSOR_REFRESH(m2, mc->mc_top, np);
2862 MDB_PAGE_UNREF(mc->mc_txn, mp);
2866 txn->mt_flags |= MDB_TXN_ERROR;
2871 mdb_env_sync0(MDB_env *env, int force, pgno_t numpgs)
2874 if (env->me_flags & MDB_RDONLY)
2877 #ifndef _WIN32 /* Sync is normally achieved in Windows by doing WRITE_THROUGH writes */
2878 || !(env->me_flags & MDB_NOSYNC)
2881 if (env->me_flags & MDB_WRITEMAP) {
2882 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2883 ? MS_ASYNC : MS_SYNC;
2884 if (MDB_MSYNC(env->me_map, env->me_psize * numpgs, flags))
2887 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2891 #ifdef BROKEN_FDATASYNC
2892 if (env->me_flags & MDB_FSYNCONLY) {
2893 if (fsync(env->me_fd))
2897 if (MDB_FDATASYNC(env->me_fd))
2905 mdb_env_sync(MDB_env *env, int force)
2907 MDB_meta *m = mdb_env_pick_meta(env);
2908 return mdb_env_sync0(env, force, m->mm_last_pg+1);
2911 /** Back up parent txn's cursors, then grab the originals for tracking */
2913 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2915 MDB_cursor *mc, *bk;
2920 for (i = src->mt_numdbs; --i >= 0; ) {
2921 if ((mc = src->mt_cursors[i]) != NULL) {
2922 size = sizeof(MDB_cursor);
2924 size += sizeof(MDB_xcursor);
2925 for (; mc; mc = bk->mc_next) {
2931 mc->mc_db = &dst->mt_dbs[i];
2932 /* Kill pointers into src to reduce abuse: The
2933 * user may not use mc until dst ends. But we need a valid
2934 * txn pointer here for cursor fixups to keep working.
2937 mc->mc_dbflag = &dst->mt_dbflags[i];
2938 if ((mx = mc->mc_xcursor) != NULL) {
2939 *(MDB_xcursor *)(bk+1) = *mx;
2940 mx->mx_cursor.mc_txn = dst;
2942 mc->mc_next = dst->mt_cursors[i];
2943 dst->mt_cursors[i] = mc;
2950 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2951 * @param[in] txn the transaction handle.
2952 * @param[in] merge true to keep changes to parent cursors, false to revert.
2953 * @return 0 on success, non-zero on failure.
2956 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2958 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2962 for (i = txn->mt_numdbs; --i >= 0; ) {
2963 for (mc = cursors[i]; mc; mc = next) {
2965 if ((bk = mc->mc_backup) != NULL) {
2967 /* Commit changes to parent txn */
2968 mc->mc_next = bk->mc_next;
2969 mc->mc_backup = bk->mc_backup;
2970 mc->mc_txn = bk->mc_txn;
2971 mc->mc_db = bk->mc_db;
2972 mc->mc_dbflag = bk->mc_dbflag;
2973 if ((mx = mc->mc_xcursor) != NULL)
2974 mx->mx_cursor.mc_txn = bk->mc_txn;
2976 /* Abort nested txn */
2978 if ((mx = mc->mc_xcursor) != NULL)
2979 *mx = *(MDB_xcursor *)(bk+1);
2983 /* Only malloced cursors are permanently tracked. */
2990 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2996 Pidset = F_SETLK, Pidcheck = F_GETLK
3000 /** Set or check a pid lock. Set returns 0 on success.
3001 * Check returns 0 if the process is certainly dead, nonzero if it may
3002 * be alive (the lock exists or an error happened so we do not know).
3004 * On Windows Pidset is a no-op, we merely check for the existence
3005 * of the process with the given pid. On POSIX we use a single byte
3006 * lock on the lockfile, set at an offset equal to the pid.
3009 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
3011 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
3014 if (op == Pidcheck) {
3015 h = OpenProcess(env->me_pidquery, FALSE, pid);
3016 /* No documented "no such process" code, but other program use this: */
3018 return ErrCode() != ERROR_INVALID_PARAMETER;
3019 /* A process exists until all handles to it close. Has it exited? */
3020 ret = WaitForSingleObject(h, 0) != 0;
3027 struct flock lock_info;
3028 memset(&lock_info, 0, sizeof(lock_info));
3029 lock_info.l_type = F_WRLCK;
3030 lock_info.l_whence = SEEK_SET;
3031 lock_info.l_start = pid;
3032 lock_info.l_len = 1;
3033 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
3034 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
3036 } else if ((rc = ErrCode()) == EINTR) {
3044 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
3045 * @param[in] txn the transaction handle to initialize
3046 * @return 0 on success, non-zero on failure.
3049 mdb_txn_renew0(MDB_txn *txn)
3051 MDB_env *env = txn->mt_env;
3052 MDB_txninfo *ti = env->me_txns;
3054 unsigned int i, nr, flags = txn->mt_flags;
3056 int rc, new_notls = 0;
3058 if ((flags &= MDB_TXN_RDONLY) != 0) {
3060 meta = mdb_env_pick_meta(env);
3061 txn->mt_txnid = meta->mm_txnid;
3062 txn->mt_u.reader = NULL;
3064 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
3065 pthread_getspecific(env->me_txkey);
3067 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
3068 return MDB_BAD_RSLOT;
3070 MDB_PID_T pid = env->me_pid;
3071 MDB_THR_T tid = pthread_self();
3072 mdb_mutexref_t rmutex = env->me_rmutex;
3074 if (!env->me_live_reader) {
3075 rc = mdb_reader_pid(env, Pidset, pid);
3078 env->me_live_reader = 1;
3081 if (LOCK_MUTEX(rc, env, rmutex))
3083 nr = ti->mti_numreaders;
3084 for (i=0; i<nr; i++)
3085 if (ti->mti_readers[i].mr_pid == 0)
3087 if (i == env->me_maxreaders) {
3088 UNLOCK_MUTEX(rmutex);
3089 return MDB_READERS_FULL;
3091 r = &ti->mti_readers[i];
3092 /* Claim the reader slot, carefully since other code
3093 * uses the reader table un-mutexed: First reset the
3094 * slot, next publish it in mti_numreaders. After
3095 * that, it is safe for mdb_env_close() to touch it.
3096 * When it will be closed, we can finally claim it.
3099 r->mr_txnid = (txnid_t)-1;
3102 ti->mti_numreaders = ++nr;
3103 env->me_close_readers = nr;
3105 UNLOCK_MUTEX(rmutex);
3107 new_notls = (env->me_flags & MDB_NOTLS);
3108 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
3113 do /* LY: Retry on a race, ITS#7970. */
3114 r->mr_txnid = ti->mti_txnid;
3115 while(r->mr_txnid != ti->mti_txnid);
3116 if (!r->mr_txnid && (env->me_flags & MDB_RDONLY)) {
3117 meta = mdb_env_pick_meta(env);
3118 r->mr_txnid = meta->mm_txnid;
3120 meta = env->me_metas[r->mr_txnid & 1];
3122 txn->mt_txnid = r->mr_txnid;
3123 txn->mt_u.reader = r;
3127 /* Not yet touching txn == env->me_txn0, it may be active */
3129 if (LOCK_MUTEX(rc, env, env->me_wmutex))
3131 txn->mt_txnid = ti->mti_txnid;
3132 meta = env->me_metas[txn->mt_txnid & 1];
3134 meta = mdb_env_pick_meta(env);
3135 txn->mt_txnid = meta->mm_txnid;
3139 if (txn->mt_txnid == mdb_debug_start)
3140 mdb_debug = MDB_DBG_INFO;
3142 txn->mt_child = NULL;
3143 txn->mt_loose_pgs = NULL;
3144 txn->mt_loose_count = 0;
3145 txn->mt_dirty_room = MDB_IDL_UM_MAX;
3146 txn->mt_u.dirty_list = env->me_dirty_list;
3147 txn->mt_u.dirty_list[0].mid = 0;
3148 txn->mt_free_pgs = env->me_free_pgs;
3149 txn->mt_free_pgs[0] = 0;
3150 txn->mt_spill_pgs = NULL;
3152 memcpy(txn->mt_dbiseqs, env->me_dbiseqs, env->me_maxdbs * sizeof(unsigned int));
3155 /* Copy the DB info and flags */
3156 memcpy(txn->mt_dbs, meta->mm_dbs, CORE_DBS * sizeof(MDB_db));
3158 /* Moved to here to avoid a data race in read TXNs */
3159 txn->mt_next_pgno = meta->mm_last_pg+1;
3161 txn->mt_last_pgno = txn->mt_next_pgno - 1;
3164 txn->mt_flags = flags;
3167 txn->mt_numdbs = env->me_numdbs;
3168 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
3169 x = env->me_dbflags[i];
3170 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
3171 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_USRVALID|DB_STALE : 0;
3173 txn->mt_dbflags[MAIN_DBI] = DB_VALID|DB_USRVALID;
3174 txn->mt_dbflags[FREE_DBI] = DB_VALID;
3176 if (env->me_flags & MDB_FATAL_ERROR) {
3177 DPUTS("environment had fatal error, must shutdown!");
3179 } else if (env->me_maxpg < txn->mt_next_pgno) {
3180 rc = MDB_MAP_RESIZED;
3184 mdb_txn_end(txn, new_notls /*0 or MDB_END_SLOT*/ | MDB_END_FAIL_BEGIN);
3189 mdb_txn_renew(MDB_txn *txn)
3193 if (!txn || !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY|MDB_TXN_FINISHED))
3196 rc = mdb_txn_renew0(txn);
3197 if (rc == MDB_SUCCESS) {
3198 DPRINTF(("renew txn %"Yu"%c %p on mdbenv %p, root page %"Yu,
3199 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
3200 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
3206 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
3210 int rc, size, tsize;
3212 flags &= MDB_TXN_BEGIN_FLAGS;
3213 flags |= env->me_flags & MDB_WRITEMAP;
3215 if (env->me_flags & MDB_RDONLY & ~flags) /* write txn in RDONLY env */
3219 /* Nested transactions: Max 1 child, write txns only, no writemap */
3220 flags |= parent->mt_flags;
3221 if (flags & (MDB_RDONLY|MDB_WRITEMAP|MDB_TXN_BLOCKED)) {
3222 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
3224 /* Child txns save MDB_pgstate and use own copy of cursors */
3225 size = env->me_maxdbs * (sizeof(MDB_db)+sizeof(MDB_cursor *)+1);
3226 size += tsize = sizeof(MDB_ntxn);
3227 } else if (flags & MDB_RDONLY) {
3228 size = env->me_maxdbs * (sizeof(MDB_db)+1);
3229 size += tsize = sizeof(MDB_txn);
3231 /* Reuse preallocated write txn. However, do not touch it until
3232 * mdb_txn_renew0() succeeds, since it currently may be active.
3237 if ((txn = calloc(1, size)) == NULL) {
3238 DPRINTF(("calloc: %s", strerror(errno)));
3243 txn->mt_rpages = malloc(MDB_TRPAGE_SIZE * sizeof(MDB_ID3));
3244 if (!txn->mt_rpages) {
3248 txn->mt_rpages[0].mid = 0;
3249 txn->mt_rpcheck = MDB_TRPAGE_SIZE/2;
3252 txn->mt_dbxs = env->me_dbxs; /* static */
3253 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
3254 txn->mt_dbflags = (unsigned char *)txn + size - env->me_maxdbs;
3255 txn->mt_flags = flags;
3260 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
3261 txn->mt_dbiseqs = parent->mt_dbiseqs;
3262 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
3263 if (!txn->mt_u.dirty_list ||
3264 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
3266 free(txn->mt_u.dirty_list);
3270 txn->mt_txnid = parent->mt_txnid;
3271 txn->mt_dirty_room = parent->mt_dirty_room;
3272 txn->mt_u.dirty_list[0].mid = 0;
3273 txn->mt_spill_pgs = NULL;
3274 txn->mt_next_pgno = parent->mt_next_pgno;
3275 parent->mt_flags |= MDB_TXN_HAS_CHILD;
3276 parent->mt_child = txn;
3277 txn->mt_parent = parent;
3278 txn->mt_numdbs = parent->mt_numdbs;
3280 txn->mt_rpages = parent->mt_rpages;
3282 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3283 /* Copy parent's mt_dbflags, but clear DB_NEW */
3284 for (i=0; i<txn->mt_numdbs; i++)
3285 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
3287 ntxn = (MDB_ntxn *)txn;
3288 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
3289 if (env->me_pghead) {
3290 size = MDB_IDL_SIZEOF(env->me_pghead);
3291 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
3293 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
3298 rc = mdb_cursor_shadow(parent, txn);
3300 mdb_txn_end(txn, MDB_END_FAIL_BEGINCHILD);
3301 } else { /* MDB_RDONLY */
3302 txn->mt_dbiseqs = env->me_dbiseqs;
3304 rc = mdb_txn_renew0(txn);
3307 if (txn != env->me_txn0) {
3309 free(txn->mt_rpages);
3314 txn->mt_flags |= flags; /* could not change txn=me_txn0 earlier */
3316 DPRINTF(("begin txn %"Yu"%c %p on mdbenv %p, root page %"Yu,
3317 txn->mt_txnid, (flags & MDB_RDONLY) ? 'r' : 'w',
3318 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
3320 MDB_TRACE(("%p, %p, %u = %p", env, parent, flags, txn));
3326 mdb_txn_env(MDB_txn *txn)
3328 if(!txn) return NULL;
3333 mdb_txn_id(MDB_txn *txn)
3336 return txn->mt_txnid;
3339 /** Export or close DBI handles opened in this txn. */
3341 mdb_dbis_update(MDB_txn *txn, int keep)
3344 MDB_dbi n = txn->mt_numdbs;
3345 MDB_env *env = txn->mt_env;
3346 unsigned char *tdbflags = txn->mt_dbflags;
3348 for (i = n; --i >= CORE_DBS;) {
3349 if (tdbflags[i] & DB_NEW) {
3351 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
3353 char *ptr = env->me_dbxs[i].md_name.mv_data;
3355 env->me_dbxs[i].md_name.mv_data = NULL;
3356 env->me_dbxs[i].md_name.mv_size = 0;
3357 env->me_dbflags[i] = 0;
3358 env->me_dbiseqs[i]++;
3364 if (keep && env->me_numdbs < n)
3368 /** End a transaction, except successful commit of a nested transaction.
3369 * May be called twice for readonly txns: First reset it, then abort.
3370 * @param[in] txn the transaction handle to end
3371 * @param[in] mode why and how to end the transaction
3374 mdb_txn_end(MDB_txn *txn, unsigned mode)
3376 MDB_env *env = txn->mt_env;
3378 static const char *const names[] = MDB_END_NAMES;
3381 /* Export or close DBI handles opened in this txn */
3382 mdb_dbis_update(txn, mode & MDB_END_UPDATE);
3384 DPRINTF(("%s txn %"Yu"%c %p on mdbenv %p, root page %"Yu,
3385 names[mode & MDB_END_OPMASK],
3386 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
3387 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
3389 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3390 if (txn->mt_u.reader) {
3391 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
3392 if (!(env->me_flags & MDB_NOTLS)) {
3393 txn->mt_u.reader = NULL; /* txn does not own reader */
3394 } else if (mode & MDB_END_SLOT) {
3395 txn->mt_u.reader->mr_pid = 0;
3396 txn->mt_u.reader = NULL;
3397 } /* else txn owns the slot until it does MDB_END_SLOT */
3399 txn->mt_numdbs = 0; /* prevent further DBI activity */
3400 txn->mt_flags |= MDB_TXN_FINISHED;
3402 } else if (!F_ISSET(txn->mt_flags, MDB_TXN_FINISHED)) {
3403 pgno_t *pghead = env->me_pghead;
3405 if (!(mode & MDB_END_UPDATE)) /* !(already closed cursors) */
3406 mdb_cursors_close(txn, 0);
3407 if (!(env->me_flags & MDB_WRITEMAP)) {
3408 mdb_dlist_free(txn);
3412 txn->mt_flags = MDB_TXN_FINISHED;
3414 if (!txn->mt_parent) {
3415 mdb_midl_shrink(&txn->mt_free_pgs);
3416 env->me_free_pgs = txn->mt_free_pgs;
3418 env->me_pghead = NULL;
3422 mode = 0; /* txn == env->me_txn0, do not free() it */
3424 /* The writer mutex was locked in mdb_txn_begin. */
3426 UNLOCK_MUTEX(env->me_wmutex);
3428 txn->mt_parent->mt_child = NULL;
3429 txn->mt_parent->mt_flags &= ~MDB_TXN_HAS_CHILD;
3430 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
3431 mdb_midl_free(txn->mt_free_pgs);
3432 free(txn->mt_u.dirty_list);
3434 mdb_midl_free(txn->mt_spill_pgs);
3436 mdb_midl_free(pghead);
3439 if (!txn->mt_parent) {
3440 MDB_ID3L el = env->me_rpages, tl = txn->mt_rpages;
3441 unsigned i, x, n = tl[0].mid;
3442 pthread_mutex_lock(&env->me_rpmutex);
3443 for (i = 1; i <= n; i++) {
3444 if (tl[i].mid & (MDB_RPAGE_CHUNK-1)) {
3445 /* tmp overflow pages that we didn't share in env */
3446 munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
3448 x = mdb_mid3l_search(el, tl[i].mid);
3449 if (tl[i].mptr == el[x].mptr) {
3452 /* another tmp overflow page */
3453 munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
3457 pthread_mutex_unlock(&env->me_rpmutex);
3459 if (mode & MDB_END_FREE)
3463 if (mode & MDB_END_FREE)
3468 mdb_txn_reset(MDB_txn *txn)
3473 /* This call is only valid for read-only txns */
3474 if (!(txn->mt_flags & MDB_TXN_RDONLY))
3477 mdb_txn_end(txn, MDB_END_RESET);
3481 _mdb_txn_abort(MDB_txn *txn)
3487 _mdb_txn_abort(txn->mt_child);
3489 mdb_txn_end(txn, MDB_END_ABORT|MDB_END_SLOT|MDB_END_FREE);
3493 mdb_txn_abort(MDB_txn *txn)
3495 MDB_TRACE(("%p", txn));
3496 _mdb_txn_abort(txn);
3499 /** Save the freelist as of this transaction to the freeDB.
3500 * This changes the freelist. Keep trying until it stabilizes.
3502 * When (MDB_DEVEL) & 2, the changes do not affect #mdb_page_alloc(),
3503 * it then uses the transaction's original snapshot of the freeDB.
3506 mdb_freelist_save(MDB_txn *txn)
3508 /* env->me_pghead[] can grow and shrink during this call.
3509 * env->me_pglast and txn->mt_free_pgs[] can only grow.
3510 * Page numbers cannot disappear from txn->mt_free_pgs[].
3513 MDB_env *env = txn->mt_env;
3514 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
3515 txnid_t pglast = 0, head_id = 0;
3516 pgno_t freecnt = 0, *free_pgs, *mop;
3517 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
3519 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
3521 if (env->me_pghead) {
3522 /* Make sure first page of freeDB is touched and on freelist */
3523 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
3524 if (rc && rc != MDB_NOTFOUND)
3528 if (!env->me_pghead && txn->mt_loose_pgs) {
3529 /* Put loose page numbers in mt_free_pgs, since
3530 * we may be unable to return them to me_pghead.
3532 MDB_page *mp = txn->mt_loose_pgs;
3533 MDB_ID2 *dl = txn->mt_u.dirty_list;
3535 if ((rc = mdb_midl_need(&txn->mt_free_pgs, txn->mt_loose_count)) != 0)
3537 for (; mp; mp = NEXT_LOOSE_PAGE(mp)) {
3538 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
3539 /* must also remove from dirty list */
3540 if (txn->mt_flags & MDB_TXN_WRITEMAP) {
3541 for (x=1; x<=dl[0].mid; x++)
3542 if (dl[x].mid == mp->mp_pgno)
3544 mdb_tassert(txn, x <= dl[0].mid);
3546 x = mdb_mid2l_search(dl, mp->mp_pgno);
3547 mdb_tassert(txn, dl[x].mid == mp->mp_pgno);
3548 mdb_dpage_free(env, mp);
3553 /* squash freed slots out of the dirty list */
3555 for (y=1; dl[y].mptr && y <= dl[0].mid; y++);
3556 if (y <= dl[0].mid) {
3558 while (!dl[y].mptr && y <= dl[0].mid) y++;
3559 if (y > dl[0].mid) break;
3564 /* all slots freed */
3568 txn->mt_loose_pgs = NULL;
3569 txn->mt_loose_count = 0;
3572 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
3573 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
3574 ? SSIZE_MAX : maxfree_1pg;
3577 /* Come back here after each Put() in case freelist changed */
3582 /* If using records from freeDB which we have not yet
3583 * deleted, delete them and any we reserved for me_pghead.
3585 while (pglast < env->me_pglast) {
3586 rc = mdb_cursor_first(&mc, &key, NULL);
3589 pglast = head_id = *(txnid_t *)key.mv_data;
3590 total_room = head_room = 0;
3591 mdb_tassert(txn, pglast <= env->me_pglast);
3592 rc = _mdb_cursor_del(&mc, 0);
3597 /* Save the IDL of pages freed by this txn, to a single record */
3598 if (freecnt < txn->mt_free_pgs[0]) {
3600 /* Make sure last page of freeDB is touched and on freelist */
3601 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
3602 if (rc && rc != MDB_NOTFOUND)
3605 free_pgs = txn->mt_free_pgs;
3606 /* Write to last page of freeDB */
3607 key.mv_size = sizeof(txn->mt_txnid);
3608 key.mv_data = &txn->mt_txnid;
3610 freecnt = free_pgs[0];
3611 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
3612 rc = _mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3615 /* Retry if mt_free_pgs[] grew during the Put() */
3616 free_pgs = txn->mt_free_pgs;
3617 } while (freecnt < free_pgs[0]);
3618 mdb_midl_sort(free_pgs);
3619 memcpy(data.mv_data, free_pgs, data.mv_size);
3622 unsigned int i = free_pgs[0];
3623 DPRINTF(("IDL write txn %"Yu" root %"Yu" num %u",
3624 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
3626 DPRINTF(("IDL %"Yu, free_pgs[i]));
3632 mop = env->me_pghead;
3633 mop_len = (mop ? mop[0] : 0) + txn->mt_loose_count;
3635 /* Reserve records for me_pghead[]. Split it if multi-page,
3636 * to avoid searching freeDB for a page range. Use keys in
3637 * range [1,me_pglast]: Smaller than txnid of oldest reader.
3639 if (total_room >= mop_len) {
3640 if (total_room == mop_len || --more < 0)
3642 } else if (head_room >= maxfree_1pg && head_id > 1) {
3643 /* Keep current record (overflow page), add a new one */
3647 /* (Re)write {key = head_id, IDL length = head_room} */
3648 total_room -= head_room;
3649 head_room = mop_len - total_room;
3650 if (head_room > maxfree_1pg && head_id > 1) {
3651 /* Overflow multi-page for part of me_pghead */
3652 head_room /= head_id; /* amortize page sizes */
3653 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
3654 } else if (head_room < 0) {
3655 /* Rare case, not bothering to delete this record */
3658 key.mv_size = sizeof(head_id);
3659 key.mv_data = &head_id;
3660 data.mv_size = (head_room + 1) * sizeof(pgno_t);
3661 rc = _mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3664 /* IDL is initially empty, zero out at least the length */
3665 pgs = (pgno_t *)data.mv_data;
3666 j = head_room > clean_limit ? head_room : 0;
3670 total_room += head_room;
3673 /* Return loose page numbers to me_pghead, though usually none are
3674 * left at this point. The pages themselves remain in dirty_list.
3676 if (txn->mt_loose_pgs) {
3677 MDB_page *mp = txn->mt_loose_pgs;
3678 unsigned count = txn->mt_loose_count;
3680 /* Room for loose pages + temp IDL with same */
3681 if ((rc = mdb_midl_need(&env->me_pghead, 2*count+1)) != 0)
3683 mop = env->me_pghead;
3684 loose = mop + MDB_IDL_ALLOCLEN(mop) - count;
3685 for (count = 0; mp; mp = NEXT_LOOSE_PAGE(mp))
3686 loose[ ++count ] = mp->mp_pgno;
3688 mdb_midl_sort(loose);
3689 mdb_midl_xmerge(mop, loose);
3690 txn->mt_loose_pgs = NULL;
3691 txn->mt_loose_count = 0;
3695 /* Fill in the reserved me_pghead records */
3701 rc = mdb_cursor_first(&mc, &key, &data);
3702 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
3703 txnid_t id = *(txnid_t *)key.mv_data;
3704 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
3707 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
3709 if (len > mop_len) {
3711 data.mv_size = (len + 1) * sizeof(MDB_ID);
3713 data.mv_data = mop -= len;
3716 rc = _mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
3718 if (rc || !(mop_len -= len))
3725 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
3726 * @param[in] txn the transaction that's being committed
3727 * @param[in] keep number of initial pages in dirty_list to keep dirty.
3728 * @return 0 on success, non-zero on failure.
3731 mdb_page_flush(MDB_txn *txn, int keep)
3733 MDB_env *env = txn->mt_env;
3734 MDB_ID2L dl = txn->mt_u.dirty_list;
3735 unsigned psize = env->me_psize, j;
3736 int i, pagecount = dl[0].mid, rc;
3740 MDB_page *dp = NULL;
3742 OVERLAPPED *ov = env->ov;
3745 HANDLE fd = (env->me_flags & MDB_NOSYNC) ? env->me_fd : env->me_ovfd;
3747 struct iovec iov[MDB_COMMIT_PAGES];
3748 HANDLE fd = env->me_fd;
3750 ssize_t wsize = 0, wres;
3751 MDB_OFF_T wpos = 0, next_pos = 1; /* impossible pos, so pos != next_pos */
3755 if (env->me_flags & MDB_WRITEMAP
3757 /* In windows, we still do writes to the file (with write-through enabled in sync mode),
3758 * as this is faster than FlushViewOfFile/FlushFileBuffers */
3759 && (env->me_flags & MDB_NOSYNC)
3762 /* Clear dirty flags */
3763 while (++i <= pagecount) {
3765 /* Don't flush this page yet */
3766 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3767 dp->mp_flags &= ~P_KEEP;
3771 dp->mp_flags &= ~P_DIRTY;
3777 if (pagecount - keep >= env->ovs) {
3778 /* ran out of room in ov array, and re-malloc, copy handles and free previous */
3779 int ovs = (pagecount - keep) * 1.5; /* provide extra padding to reduce number of re-allocations */
3780 int new_size = ovs * sizeof(OVERLAPPED);
3781 ov = malloc(new_size);
3784 int previous_size = env->ovs * sizeof(OVERLAPPED);
3785 memcpy(ov, env->ov, previous_size); /* Copy previous OVERLAPPED data to retain event handles */
3786 /* And clear rest of memory */
3787 memset(&ov[env->ovs], 0, new_size - previous_size);
3789 free(env->ov); /* release previous allocation */
3797 /* Write the pages */
3799 if (++i <= pagecount) {
3801 /* Don't flush this page yet */
3802 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3803 dp->mp_flags &= ~P_KEEP;
3808 /* clear dirty flag */
3809 dp->mp_flags &= ~P_DIRTY;
3812 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
3814 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
3815 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE
3817 /* If writemap is enabled, consecutive page positions infer
3818 * contiguous (mapped) memory.
3819 * Otherwise force write pages one at a time.
3820 * Windows actually supports scatter/gather I/O, but only on
3821 * unbuffered file handles. Since we're relying on the OS page
3822 * cache for all our data, that's self-defeating. So we just
3823 * write pages one at a time. We use the ov structure to set
3824 * the write offset, to at least save the overhead of a Seek
3827 || !(env->me_flags & MDB_WRITEMAP)
3832 /* Write previous page(s) */
3833 DPRINTF(("committing page %"Z"u", pgno));
3835 OVERLAPPED *this_ov = &ov[async_i];
3836 /* Clear status, and keep hEvent, we reuse that */
3837 this_ov->Internal = 0;
3838 this_ov->Offset = wpos & 0xffffffff;
3839 this_ov->OffsetHigh = wpos >> 16 >> 16;
3840 if (!F_ISSET(env->me_flags, MDB_NOSYNC) && !this_ov->hEvent) {
3841 HANDLE event = CreateEvent(NULL, FALSE, FALSE, NULL);
3844 DPRINTF(("CreateEvent: %s", strerror(rc)));
3847 this_ov->hEvent = event;
3849 if (!WriteFile(fd, wdp, wsize, NULL, this_ov)) {
3851 if (rc != ERROR_IO_PENDING) {
3852 DPRINTF(("WriteFile: %d", rc));
3858 #ifdef MDB_USE_PWRITEV
3859 wres = pwritev(fd, iov, n, wpos);
3862 wres = pwrite(fd, iov[0].iov_base, wsize, wpos);
3865 if (lseek(fd, wpos, SEEK_SET) == -1) {
3869 DPRINTF(("lseek: %s", strerror(rc)));
3872 wres = writev(fd, iov, n);
3875 if (wres != wsize) {
3880 DPRINTF(("Write error: %s", strerror(rc)));
3882 rc = EIO; /* TODO: Use which error code? */
3883 DPUTS("short write, filesystem full?");
3899 iov[n].iov_len = size;
3900 iov[n].iov_base = (char *)dp;
3902 DPRINTF(("committing page %"Yu, pgno));
3903 next_pos = pos + size;
3908 if (pgno > txn->mt_last_pgno)
3909 txn->mt_last_pgno = pgno;
3913 if (!F_ISSET(env->me_flags, MDB_NOSYNC)) {
3914 /* Now wait for all the asynchronous/overlapped sync/write-through writes to complete.
3915 * We start with the last one so that all the others should already be complete and
3916 * we reduce thread suspend/resuming (in practice, typically about 99.5% of writes are
3917 * done after the last write is done) */
3919 while (--async_i >= 0) {
3920 if (ov[async_i].hEvent) {
3922 if (!GetOverlappedResult(fd, &ov[async_i], &temp_wres, TRUE)) {
3923 rc = ErrCode(); /* Continue on so that all the event signals are reset */
3928 if (rc) { /* any error on GetOverlappedResult, exit now */
3934 if (!(env->me_flags & MDB_WRITEMAP)) {
3935 /* Don't free pages when using writemap (can only get here in NOSYNC mode in Windows)
3936 * MIPS has cache coherency issues, this is a no-op everywhere else
3937 * Note: for any size >= on-chip cache size, entire on-chip cache is
3940 CACHEFLUSH(env->me_map, txn->mt_next_pgno * env->me_psize, DCACHE);
3942 for (i = keep; ++i <= pagecount; ) {
3944 /* This is a page we skipped above */
3947 dl[j].mid = dp->mp_pgno;
3950 mdb_dpage_free(env, dp);
3956 txn->mt_dirty_room += i - j;
3961 static int ESECT mdb_env_share_locks(MDB_env *env, int *excl);
3964 _mdb_txn_commit(MDB_txn *txn)
3967 unsigned int i, end_mode;
3973 /* mdb_txn_end() mode for a commit which writes nothing */
3974 end_mode = MDB_END_EMPTY_COMMIT|MDB_END_UPDATE|MDB_END_SLOT|MDB_END_FREE;
3976 if (txn->mt_child) {
3977 rc = _mdb_txn_commit(txn->mt_child);
3984 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3988 if (txn->mt_flags & (MDB_TXN_FINISHED|MDB_TXN_ERROR)) {
3989 DPUTS("txn has failed/finished, can't commit");
3991 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3996 if (txn->mt_parent) {
3997 MDB_txn *parent = txn->mt_parent;
4001 unsigned x, y, len, ps_len;
4003 /* Append our free list to parent's */
4004 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
4007 mdb_midl_free(txn->mt_free_pgs);
4008 /* Failures after this must either undo the changes
4009 * to the parent or set MDB_TXN_ERROR in the parent.
4012 parent->mt_next_pgno = txn->mt_next_pgno;
4013 parent->mt_flags = txn->mt_flags;
4015 /* Merge our cursors into parent's and close them */
4016 mdb_cursors_close(txn, 1);
4018 /* Update parent's DB table. */
4019 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
4020 parent->mt_numdbs = txn->mt_numdbs;
4021 parent->mt_dbflags[FREE_DBI] = txn->mt_dbflags[FREE_DBI];
4022 parent->mt_dbflags[MAIN_DBI] = txn->mt_dbflags[MAIN_DBI];
4023 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
4024 /* preserve parent's DB_NEW status */
4025 x = parent->mt_dbflags[i] & DB_NEW;
4026 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
4029 dst = parent->mt_u.dirty_list;
4030 src = txn->mt_u.dirty_list;
4031 /* Remove anything in our dirty list from parent's spill list */
4032 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
4034 pspill[0] = (pgno_t)-1;
4035 /* Mark our dirty pages as deleted in parent spill list */
4036 for (i=0, len=src[0].mid; ++i <= len; ) {
4037 MDB_ID pn = src[i].mid << 1;
4038 while (pn > pspill[x])
4040 if (pn == pspill[x]) {
4045 /* Squash deleted pagenums if we deleted any */
4046 for (x=y; ++x <= ps_len; )
4047 if (!(pspill[x] & 1))
4048 pspill[++y] = pspill[x];
4052 /* Remove anything in our spill list from parent's dirty list */
4053 if (txn->mt_spill_pgs && txn->mt_spill_pgs[0]) {
4054 for (i=1; i<=txn->mt_spill_pgs[0]; i++) {
4055 MDB_ID pn = txn->mt_spill_pgs[i];
4057 continue; /* deleted spillpg */
4059 y = mdb_mid2l_search(dst, pn);
4060 if (y <= dst[0].mid && dst[y].mid == pn) {
4062 while (y < dst[0].mid) {
4071 /* Find len = length of merging our dirty list with parent's */
4073 dst[0].mid = 0; /* simplify loops */
4074 if (parent->mt_parent) {
4075 len = x + src[0].mid;
4076 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
4077 for (i = x; y && i; y--) {
4078 pgno_t yp = src[y].mid;
4079 while (yp < dst[i].mid)
4081 if (yp == dst[i].mid) {
4086 } else { /* Simplify the above for single-ancestor case */
4087 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
4089 /* Merge our dirty list with parent's */
4091 for (i = len; y; dst[i--] = src[y--]) {
4092 pgno_t yp = src[y].mid;
4093 while (yp < dst[x].mid)
4094 dst[i--] = dst[x--];
4095 if (yp == dst[x].mid)
4096 free(dst[x--].mptr);
4098 mdb_tassert(txn, i == x);
4100 free(txn->mt_u.dirty_list);
4101 parent->mt_dirty_room = txn->mt_dirty_room;
4102 if (txn->mt_spill_pgs) {
4103 if (parent->mt_spill_pgs) {
4104 /* TODO: Prevent failure here, so parent does not fail */
4105 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
4107 parent->mt_flags |= MDB_TXN_ERROR;
4108 mdb_midl_free(txn->mt_spill_pgs);
4109 mdb_midl_sort(parent->mt_spill_pgs);
4111 parent->mt_spill_pgs = txn->mt_spill_pgs;
4115 /* Append our loose page list to parent's */
4116 for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(*lp))
4118 *lp = txn->mt_loose_pgs;
4119 parent->mt_loose_count += txn->mt_loose_count;
4121 parent->mt_child = NULL;
4122 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
4127 if (txn != env->me_txn) {
4128 DPUTS("attempt to commit unknown transaction");
4133 mdb_cursors_close(txn, 0);
4135 if (!txn->mt_u.dirty_list[0].mid &&
4136 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
4139 DPRINTF(("committing txn %"Yu" %p on mdbenv %p, root page %"Yu,
4140 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
4142 /* Update DB root pointers */
4143 if (txn->mt_numdbs > CORE_DBS) {
4147 data.mv_size = sizeof(MDB_db);
4149 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
4150 for (i = CORE_DBS; i < txn->mt_numdbs; i++) {
4151 if (txn->mt_dbflags[i] & DB_DIRTY) {
4152 if (TXN_DBI_CHANGED(txn, i)) {
4156 data.mv_data = &txn->mt_dbs[i];
4157 rc = _mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data,
4165 rc = mdb_freelist_save(txn);
4169 mdb_midl_free(env->me_pghead);
4170 env->me_pghead = NULL;
4171 mdb_midl_shrink(&txn->mt_free_pgs);
4177 if ((rc = mdb_page_flush(txn, 0)))
4179 if (!F_ISSET(txn->mt_flags, MDB_TXN_NOSYNC) &&
4180 (rc = mdb_env_sync0(env, 0, txn->mt_next_pgno)))
4182 if ((rc = mdb_env_write_meta(txn)))
4184 end_mode = MDB_END_COMMITTED|MDB_END_UPDATE;
4185 if (env->me_flags & MDB_PREVSNAPSHOT) {
4186 if (!(env->me_flags & MDB_NOLOCK)) {
4188 rc = mdb_env_share_locks(env, &excl);
4192 env->me_flags ^= MDB_PREVSNAPSHOT;
4196 mdb_txn_end(txn, end_mode);
4200 _mdb_txn_abort(txn);
4205 mdb_txn_commit(MDB_txn *txn)
4207 MDB_TRACE(("%p", txn));
4208 return _mdb_txn_commit(txn);
4211 /** Read the environment parameters of a DB environment before
4212 * mapping it into memory.
4213 * @param[in] env the environment handle
4214 * @param[in] prev whether to read the backup meta page
4215 * @param[out] meta address of where to store the meta information
4216 * @return 0 on success, non-zero on failure.
4219 mdb_env_read_header(MDB_env *env, int prev, MDB_meta *meta)
4225 enum { Size = sizeof(pbuf) };
4227 /* We don't know the page size yet, so use a minimum value.
4228 * Read both meta pages so we can use the latest one.
4231 for (i=off=0; i<NUM_METAS; i++, off += meta->mm_psize) {
4235 memset(&ov, 0, sizeof(ov));
4237 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
4238 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
4241 rc = pread(env->me_fd, &pbuf, Size, off);
4244 if (rc == 0 && off == 0)
4246 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
4247 DPRINTF(("read: %s", mdb_strerror(rc)));
4251 p = (MDB_page *)&pbuf;
4253 if (!F_ISSET(p->mp_flags, P_META)) {
4254 DPRINTF(("page %"Yu" not a meta page", p->mp_pgno));
4259 if (m->mm_magic != MDB_MAGIC) {
4260 DPUTS("meta has invalid magic");
4264 if (m->mm_version != MDB_DATA_VERSION) {
4265 DPRINTF(("database is version %u, expected version %u",
4266 m->mm_version, MDB_DATA_VERSION));
4267 return MDB_VERSION_MISMATCH;
4270 if (off == 0 || (prev ? m->mm_txnid < meta->mm_txnid : m->mm_txnid > meta->mm_txnid))
4276 /** Fill in most of the zeroed #MDB_meta for an empty database environment */
4278 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
4280 meta->mm_magic = MDB_MAGIC;
4281 meta->mm_version = MDB_DATA_VERSION;
4282 meta->mm_mapsize = env->me_mapsize;
4283 meta->mm_psize = env->me_psize;
4284 meta->mm_last_pg = NUM_METAS-1;
4285 meta->mm_flags = env->me_flags & 0xffff;
4286 meta->mm_flags |= MDB_INTEGERKEY; /* this is mm_dbs[FREE_DBI].md_flags */
4287 meta->mm_dbs[FREE_DBI].md_root = P_INVALID;
4288 meta->mm_dbs[MAIN_DBI].md_root = P_INVALID;
4291 /** Write the environment parameters of a freshly created DB environment.
4292 * @param[in] env the environment handle
4293 * @param[in] meta the #MDB_meta to write
4294 * @return 0 on success, non-zero on failure.
4297 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
4305 memset(&ov, 0, sizeof(ov));
4306 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
4308 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
4311 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
4312 len = pwrite(fd, ptr, size, pos); \
4313 if (len == -1 && ErrCode() == EINTR) continue; \
4314 rc = (len >= 0); break; } while(1)
4316 DPUTS("writing new meta page");
4318 psize = env->me_psize;
4320 p = calloc(NUM_METAS, psize);
4324 p->mp_flags = P_META;
4325 *(MDB_meta *)METADATA(p) = *meta;
4327 q = (MDB_page *)((char *)p + psize);
4329 q->mp_flags = P_META;
4330 *(MDB_meta *)METADATA(q) = *meta;
4332 DO_PWRITE(rc, env->me_fd, p, psize * NUM_METAS, len, 0);
4335 else if ((unsigned) len == psize * NUM_METAS)
4343 /** Update the environment info to commit a transaction.
4344 * @param[in] txn the transaction that's being committed
4345 * @return 0 on success, non-zero on failure.
4348 mdb_env_write_meta(MDB_txn *txn)
4351 MDB_meta meta, metab, *mp;
4355 int rc, len, toggle;
4364 toggle = txn->mt_txnid & 1;
4365 DPRINTF(("writing meta page %d for root page %"Yu,
4366 toggle, txn->mt_dbs[MAIN_DBI].md_root));
4369 flags = txn->mt_flags | env->me_flags;
4370 mp = env->me_metas[toggle];
4371 mapsize = env->me_metas[toggle ^ 1]->mm_mapsize;
4372 /* Persist any increases of mapsize config */
4373 if (mapsize < env->me_mapsize)
4374 mapsize = env->me_mapsize;
4376 #ifndef _WIN32 /* We don't want to ever use MSYNC/FlushViewOfFile in Windows */
4377 if (flags & MDB_WRITEMAP) {
4378 mp->mm_mapsize = mapsize;
4379 mp->mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
4380 mp->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
4381 mp->mm_last_pg = txn->mt_next_pgno - 1;
4382 #if (__GNUC__ * 100 + __GNUC_MINOR__ >= 404) && /* TODO: portability */ \
4383 !(defined(__i386__) || defined(__x86_64__))
4384 /* LY: issue a memory barrier, if not x86. ITS#7969 */
4385 __sync_synchronize();
4387 mp->mm_txnid = txn->mt_txnid;
4388 if (!(flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
4389 unsigned meta_size = env->me_psize;
4390 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
4391 ptr = (char *)mp - PAGEHDRSZ;
4392 /* POSIX msync() requires ptr = start of OS page */
4393 r2 = (ptr - env->me_map) & (env->me_os_psize - 1);
4396 if (MDB_MSYNC(ptr, meta_size, rc)) {
4404 metab.mm_txnid = mp->mm_txnid;
4405 metab.mm_last_pg = mp->mm_last_pg;
4407 meta.mm_mapsize = mapsize;
4408 meta.mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
4409 meta.mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
4410 meta.mm_last_pg = txn->mt_next_pgno - 1;
4411 meta.mm_txnid = txn->mt_txnid;
4413 off = offsetof(MDB_meta, mm_mapsize);
4414 ptr = (char *)&meta + off;
4415 len = sizeof(MDB_meta) - off;
4416 off += (char *)mp - env->me_map;
4418 /* Write to the SYNC fd unless MDB_NOSYNC/MDB_NOMETASYNC.
4419 * (me_mfd goes to the same file as me_fd, but writing to it
4420 * also syncs to disk. Avoids a separate fdatasync() call.)
4422 mfd = (flags & (MDB_NOSYNC|MDB_NOMETASYNC)) ? env->me_fd : env->me_mfd;
4425 memset(&ov, 0, sizeof(ov));
4427 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
4432 rc = pwrite(mfd, ptr, len, off);
4435 rc = rc < 0 ? ErrCode() : EIO;
4440 DPUTS("write failed, disk error?");
4441 /* On a failure, the pagecache still contains the new data.
4442 * Write some old data back, to prevent it from being used.
4443 * Use the non-SYNC fd; we know it will fail anyway.
4445 meta.mm_last_pg = metab.mm_last_pg;
4446 meta.mm_txnid = metab.mm_txnid;
4448 memset(&ov, 0, sizeof(ov));
4450 WriteFile(env->me_fd, ptr, len, NULL, &ov);
4452 r2 = pwrite(env->me_fd, ptr, len, off);
4453 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
4456 env->me_flags |= MDB_FATAL_ERROR;
4459 /* MIPS has cache coherency issues, this is a no-op everywhere else */
4460 CACHEFLUSH(env->me_map + off, len, DCACHE);
4462 /* Memory ordering issues are irrelevant; since the entire writer
4463 * is wrapped by wmutex, all of these changes will become visible
4464 * after the wmutex is unlocked. Since the DB is multi-version,
4465 * readers will get consistent data regardless of how fresh or
4466 * how stale their view of these values is.
4469 env->me_txns->mti_txnid = txn->mt_txnid;
4474 /** Check both meta pages to see which one is newer.
4475 * @param[in] env the environment handle
4476 * @return newest #MDB_meta.
4479 mdb_env_pick_meta(const MDB_env *env)
4481 MDB_meta *const *metas = env->me_metas;
4482 return metas[ (metas[0]->mm_txnid < metas[1]->mm_txnid) ^
4483 ((env->me_flags & MDB_PREVSNAPSHOT) != 0) ];
4487 mdb_env_create(MDB_env **env)
4491 e = calloc(1, sizeof(MDB_env));
4495 e->me_maxreaders = DEFAULT_READERS;
4496 e->me_maxdbs = e->me_numdbs = CORE_DBS;
4497 e->me_fd = INVALID_HANDLE_VALUE;
4498 e->me_lfd = INVALID_HANDLE_VALUE;
4499 e->me_mfd = INVALID_HANDLE_VALUE;
4500 #ifdef MDB_USE_POSIX_SEM
4501 e->me_rmutex = SEM_FAILED;
4502 e->me_wmutex = SEM_FAILED;
4503 #elif defined MDB_USE_SYSV_SEM
4504 e->me_rmutex->semid = -1;
4505 e->me_wmutex->semid = -1;
4507 e->me_pid = getpid();
4508 GET_PAGESIZE(e->me_os_psize);
4509 VGMEMP_CREATE(e,0,0);
4511 MDB_TRACE(("%p", e));
4516 /** @brief Map a result from an NTAPI call to WIN32. */
4518 mdb_nt2win32(NTSTATUS st)
4523 GetOverlappedResult(NULL, &o, &br, FALSE);
4524 return GetLastError();
4529 mdb_env_map(MDB_env *env, void *addr)
4532 unsigned int flags = env->me_flags;
4535 int access = SECTION_MAP_READ;
4539 ULONG pageprot = PAGE_READONLY, secprot, alloctype;
4541 if (flags & MDB_WRITEMAP) {
4542 access |= SECTION_MAP_WRITE;
4543 pageprot = PAGE_READWRITE;
4545 if (flags & MDB_RDONLY) {
4546 secprot = PAGE_READONLY;
4550 secprot = PAGE_READWRITE;
4551 msize = env->me_mapsize;
4552 alloctype = MEM_RESERVE;
4555 /** Some users are afraid of seeing their disk space getting used
4556 * all at once, so the default is now to do incremental file growth.
4557 * But that has a large performance impact, so give the option of
4558 * allocating the file up front.
4560 #ifdef MDB_FIXEDSIZE
4561 LARGE_INTEGER fsize;
4562 fsize.LowPart = msize & 0xffffffff;
4563 fsize.HighPart = msize >> 16 >> 16;
4564 rc = NtCreateSection(&mh, access, NULL, &fsize, secprot, SEC_RESERVE, env->me_fd);
4566 rc = NtCreateSection(&mh, access, NULL, NULL, secprot, SEC_RESERVE, env->me_fd);
4569 return mdb_nt2win32(rc);
4572 msize = NUM_METAS * env->me_psize;
4574 rc = NtMapViewOfSection(mh, GetCurrentProcess(), &map, 0, 0, NULL, &msize, ViewUnmap, alloctype, pageprot);
4581 return mdb_nt2win32(rc);
4584 int mmap_flags = MAP_SHARED;
4585 int prot = PROT_READ;
4586 #ifdef MAP_NOSYNC /* Used on FreeBSD */
4587 if (flags & MDB_NOSYNC)
4588 mmap_flags |= MAP_NOSYNC;
4592 env->me_map = mmap(addr, NUM_METAS * env->me_psize, prot, mmap_flags,
4594 if (env->me_map == MAP_FAILED) {
4599 if (flags & MDB_WRITEMAP) {
4601 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
4604 env->me_map = mmap(addr, env->me_mapsize, prot, mmap_flags,
4606 if (env->me_map == MAP_FAILED) {
4611 if (flags & MDB_NORDAHEAD) {
4612 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
4614 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
4616 #ifdef POSIX_MADV_RANDOM
4617 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
4618 #endif /* POSIX_MADV_RANDOM */
4619 #endif /* MADV_RANDOM */
4623 /* Can happen because the address argument to mmap() is just a
4624 * hint. mmap() can pick another, e.g. if the range is in use.
4625 * The MAP_FIXED flag would prevent that, but then mmap could
4626 * instead unmap existing pages to make room for the new map.
4628 if (addr && env->me_map != addr)
4629 return EBUSY; /* TODO: Make a new MDB_* error code? */
4632 p = (MDB_page *)env->me_map;
4633 env->me_metas[0] = METADATA(p);
4634 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
4640 mdb_env_set_mapsize(MDB_env *env, mdb_size_t size)
4642 /* If env is already open, caller is responsible for making
4643 * sure there are no active txns.
4653 meta = mdb_env_pick_meta(env);
4655 size = meta->mm_mapsize;
4657 /* Silently round up to minimum if the size is too small */
4658 mdb_size_t minsize = (meta->mm_last_pg + 1) * env->me_psize;
4663 /* For MDB_VL32 this bit is a noop since we dynamically remap
4664 * chunks of the DB anyway.
4666 munmap(env->me_map, env->me_mapsize);
4667 env->me_mapsize = size;
4668 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
4669 rc = mdb_env_map(env, old);
4672 #endif /* !MDB_VL32 */
4674 env->me_mapsize = size;
4676 env->me_maxpg = env->me_mapsize / env->me_psize;
4677 MDB_TRACE(("%p, %"Yu"", env, size));
4682 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
4686 env->me_maxdbs = dbs + CORE_DBS;
4687 MDB_TRACE(("%p, %u", env, dbs));
4692 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
4694 if (env->me_map || readers < 1)
4696 env->me_maxreaders = readers;
4697 MDB_TRACE(("%p, %u", env, readers));
4702 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
4704 if (!env || !readers)
4706 *readers = env->me_maxreaders;
4711 mdb_fsize(HANDLE fd, mdb_size_t *size)
4714 LARGE_INTEGER fsize;
4716 if (!GetFileSizeEx(fd, &fsize))
4719 *size = fsize.QuadPart;
4733 typedef wchar_t mdb_nchar_t;
4734 # define MDB_NAME(str) L##str
4735 # define mdb_name_cpy wcscpy
4737 /** Character type for file names: char on Unix, wchar_t on Windows */
4738 typedef char mdb_nchar_t;
4739 # define MDB_NAME(str) str /**< #mdb_nchar_t[] string literal */
4740 # define mdb_name_cpy strcpy /**< Copy name (#mdb_nchar_t string) */
4743 /** Filename - string of #mdb_nchar_t[] */
4744 typedef struct MDB_name {
4745 int mn_len; /**< Length */
4746 int mn_alloced; /**< True if #mn_val was malloced */
4747 mdb_nchar_t *mn_val; /**< Contents */
4750 /** Filename suffixes [datafile,lockfile][without,with MDB_NOSUBDIR] */
4751 static const mdb_nchar_t *const mdb_suffixes[2][2] = {
4752 { MDB_NAME("/data.mdb"), MDB_NAME("") },
4753 { MDB_NAME("/lock.mdb"), MDB_NAME("-lock") }
4756 #define MDB_SUFFLEN 9 /**< Max string length in #mdb_suffixes[] */
4758 /** Set up filename + scratch area for filename suffix, for opening files.
4759 * It should be freed with #mdb_fname_destroy().
4760 * On Windows, paths are converted from char *UTF-8 to wchar_t *UTF-16.
4762 * @param[in] path Pathname for #mdb_env_open().
4763 * @param[in] envflags Whether a subdir and/or lockfile will be used.
4764 * @param[out] fname Resulting filename, with room for a suffix if necessary.
4767 mdb_fname_init(const char *path, unsigned envflags, MDB_name *fname)
4769 int no_suffix = F_ISSET(envflags, MDB_NOSUBDIR|MDB_NOLOCK);
4770 fname->mn_alloced = 0;
4772 return utf8_to_utf16(path, fname, no_suffix ? 0 : MDB_SUFFLEN);
4774 fname->mn_len = strlen(path);
4776 fname->mn_val = (char *) path;
4777 else if ((fname->mn_val = malloc(fname->mn_len + MDB_SUFFLEN+1)) != NULL) {
4778 fname->mn_alloced = 1;
4779 strcpy(fname->mn_val, path);
4787 /** Destroy \b fname from #mdb_fname_init() */
4788 #define mdb_fname_destroy(fname) \
4789 do { if ((fname).mn_alloced) free((fname).mn_val); } while (0)
4791 #ifdef O_CLOEXEC /* POSIX.1-2008: Set FD_CLOEXEC atomically at open() */
4792 # define MDB_CLOEXEC O_CLOEXEC
4794 # define MDB_CLOEXEC 0
4797 /** File type, access mode etc. for #mdb_fopen() */
4798 enum mdb_fopen_type {
4800 MDB_O_RDONLY, MDB_O_RDWR, MDB_O_OVERLAPPED, MDB_O_META, MDB_O_COPY, MDB_O_LOCKS
4802 /* A comment in mdb_fopen() explains some O_* flag choices. */
4803 MDB_O_RDONLY= O_RDONLY, /**< for RDONLY me_fd */
4804 MDB_O_RDWR = O_RDWR |O_CREAT, /**< for me_fd */
4805 MDB_O_META = O_WRONLY|MDB_DSYNC |MDB_CLOEXEC, /**< for me_mfd */
4806 MDB_O_COPY = O_WRONLY|O_CREAT|O_EXCL|MDB_CLOEXEC, /**< for #mdb_env_copy() */
4807 /** Bitmask for open() flags in enum #mdb_fopen_type. The other bits
4808 * distinguish otherwise-equal MDB_O_* constants from each other.
4810 MDB_O_MASK = MDB_O_RDWR|MDB_CLOEXEC | MDB_O_RDONLY|MDB_O_META|MDB_O_COPY,
4811 MDB_O_LOCKS = MDB_O_RDWR|MDB_CLOEXEC | ((MDB_O_MASK+1) & ~MDB_O_MASK) /**< for me_lfd */
4815 /** Open an LMDB file.
4816 * @param[in] env The LMDB environment.
4817 * @param[in,out] fname Path from from #mdb_fname_init(). A suffix is
4818 * appended if necessary to create the filename, without changing mn_len.
4819 * @param[in] which Determines file type, access mode, etc.
4820 * @param[in] mode The Unix permissions for the file, if we create it.
4821 * @param[out] res Resulting file handle.
4822 * @return 0 on success, non-zero on failure.
4825 mdb_fopen(const MDB_env *env, MDB_name *fname,
4826 enum mdb_fopen_type which, mdb_mode_t mode,
4829 int rc = MDB_SUCCESS;
4832 DWORD acc, share, disp, attrs;
4837 if (fname->mn_alloced) /* modifiable copy */
4838 mdb_name_cpy(fname->mn_val + fname->mn_len,
4839 mdb_suffixes[which==MDB_O_LOCKS][F_ISSET(env->me_flags, MDB_NOSUBDIR)]);
4841 /* The directory must already exist. Usually the file need not.
4842 * MDB_O_META requires the file because we already created it using
4843 * MDB_O_RDWR. MDB_O_COPY must not overwrite an existing file.
4845 * With MDB_O_COPY we do not want the OS to cache the writes, since
4846 * the source data is already in the OS cache.
4848 * The lockfile needs FD_CLOEXEC (close file descriptor on exec*())
4849 * to avoid the flock() issues noted under Caveats in lmdb.h.
4850 * Also set it for other filehandles which the user cannot get at
4851 * and close himself, which he may need after fork(). I.e. all but
4852 * me_fd, which programs do use via mdb_env_get_fd().
4856 acc = GENERIC_READ|GENERIC_WRITE;
4857 share = FILE_SHARE_READ|FILE_SHARE_WRITE;
4859 attrs = FILE_ATTRIBUTE_NORMAL;
4861 case MDB_O_OVERLAPPED: /* for unbuffered asynchronous writes (write-through mode)*/
4862 acc = GENERIC_WRITE;
4863 disp = OPEN_EXISTING;
4864 attrs = FILE_FLAG_OVERLAPPED|FILE_FLAG_WRITE_THROUGH;
4866 case MDB_O_RDONLY: /* read-only datafile */
4868 disp = OPEN_EXISTING;
4870 case MDB_O_META: /* for writing metapages */
4871 acc = GENERIC_WRITE;
4872 disp = OPEN_EXISTING;
4873 attrs = FILE_ATTRIBUTE_NORMAL|FILE_FLAG_WRITE_THROUGH;
4875 case MDB_O_COPY: /* mdb_env_copy() & co */
4876 acc = GENERIC_WRITE;
4879 attrs = FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH;
4881 default: break; /* silence gcc -Wswitch (not all enum values handled) */
4883 fd = CreateFileW(fname->mn_val, acc, share, NULL, disp, attrs, NULL);
4885 fd = open(fname->mn_val, which & MDB_O_MASK, mode);
4888 if (fd == INVALID_HANDLE_VALUE)
4892 if (which != MDB_O_RDONLY && which != MDB_O_RDWR) {
4893 /* Set CLOEXEC if we could not pass it to open() */
4894 if (!MDB_CLOEXEC && (flags = fcntl(fd, F_GETFD)) != -1)
4895 (void) fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
4897 if (which == MDB_O_COPY && env->me_psize >= env->me_os_psize) {
4898 /* This may require buffer alignment. There is no portable
4899 * way to ask how much, so we require OS pagesize alignment.
4901 # ifdef F_NOCACHE /* __APPLE__ */
4902 (void) fcntl(fd, F_NOCACHE, 1);
4903 # elif defined O_DIRECT
4904 /* open(...O_DIRECT...) would break on filesystems without
4905 * O_DIRECT support (ITS#7682). Try to set it here instead.
4907 if ((flags = fcntl(fd, F_GETFL)) != -1)
4908 (void) fcntl(fd, F_SETFL, flags | O_DIRECT);
4912 #endif /* !_WIN32 */
4919 #ifdef BROKEN_FDATASYNC
4920 #include <sys/utsname.h>
4921 #include <sys/vfs.h>
4924 /** Further setup required for opening an LMDB environment
4927 mdb_env_open2(MDB_env *env, int prev)
4929 unsigned int flags = env->me_flags;
4930 int i, newenv = 0, rc;
4934 /* See if we should use QueryLimited */
4936 if ((rc & 0xff) > 5)
4937 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
4939 env->me_pidquery = PROCESS_QUERY_INFORMATION;
4940 /* Grab functions we need from NTDLL */
4941 if (!NtCreateSection) {
4942 HMODULE h = GetModuleHandleW(L"NTDLL.DLL");
4945 NtClose = (NtCloseFunc *)GetProcAddress(h, "NtClose");
4948 NtMapViewOfSection = (NtMapViewOfSectionFunc *)GetProcAddress(h, "NtMapViewOfSection");
4949 if (!NtMapViewOfSection)
4951 NtCreateSection = (NtCreateSectionFunc *)GetProcAddress(h, "NtCreateSection");
4952 if (!NtCreateSection)
4958 #ifdef BROKEN_FDATASYNC
4959 /* ext3/ext4 fdatasync is broken on some older Linux kernels.
4960 * https://lkml.org/lkml/2012/9/3/83
4961 * Kernels after 3.6-rc6 are known good.
4962 * https://lkml.org/lkml/2012/9/10/556
4963 * See if the DB is on ext3/ext4, then check for new enough kernel
4964 * Kernels 2.6.32.60, 2.6.34.15, 3.2.30, and 3.5.4 are also known
4969 fstatfs(env->me_fd, &st);
4970 while (st.f_type == 0xEF53) {
4974 if (uts.release[0] < '3') {
4975 if (!strncmp(uts.release, "2.6.32.", 7)) {
4976 i = atoi(uts.release+7);
4978 break; /* 2.6.32.60 and newer is OK */
4979 } else if (!strncmp(uts.release, "2.6.34.", 7)) {
4980 i = atoi(uts.release+7);
4982 break; /* 2.6.34.15 and newer is OK */
4984 } else if (uts.release[0] == '3') {
4985 i = atoi(uts.release+2);
4987 break; /* 3.6 and newer is OK */
4989 i = atoi(uts.release+4);
4991 break; /* 3.5.4 and newer is OK */
4992 } else if (i == 2) {
4993 i = atoi(uts.release+4);
4995 break; /* 3.2.30 and newer is OK */
4997 } else { /* 4.x and newer is OK */
5000 env->me_flags |= MDB_FSYNCONLY;
5006 if ((i = mdb_env_read_header(env, prev, &meta)) != 0) {
5009 DPUTS("new mdbenv");
5011 env->me_psize = env->me_os_psize;
5012 if (env->me_psize > MAX_PAGESIZE)
5013 env->me_psize = MAX_PAGESIZE;
5014 memset(&meta, 0, sizeof(meta));
5015 mdb_env_init_meta0(env, &meta);
5016 meta.mm_mapsize = DEFAULT_MAPSIZE;
5018 env->me_psize = meta.mm_psize;
5021 /* Was a mapsize configured? */
5022 if (!env->me_mapsize) {
5023 env->me_mapsize = meta.mm_mapsize;
5026 /* Make sure mapsize >= committed data size. Even when using
5027 * mm_mapsize, which could be broken in old files (ITS#7789).
5029 mdb_size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
5030 if (env->me_mapsize < minsize)
5031 env->me_mapsize = minsize;
5033 meta.mm_mapsize = env->me_mapsize;
5035 if (newenv && !(flags & MDB_FIXEDMAP)) {
5036 /* mdb_env_map() may grow the datafile. Write the metapages
5037 * first, so the file will be valid if initialization fails.
5038 * Except with FIXEDMAP, since we do not yet know mm_address.
5039 * We could fill in mm_address later, but then a different
5040 * program might end up doing that - one with a memory layout
5041 * and map address which does not suit the main program.
5043 rc = mdb_env_init_meta(env, &meta);
5049 /* For FIXEDMAP, make sure the file is non-empty before we attempt to map it */
5053 rc = WriteFile(env->me_fd, &dummy, 1, &len, NULL);
5061 rc = mdb_env_map(env, (flags & MDB_FIXEDMAP) ? meta.mm_address : NULL);
5066 if (flags & MDB_FIXEDMAP)
5067 meta.mm_address = env->me_map;
5068 i = mdb_env_init_meta(env, &meta);
5069 if (i != MDB_SUCCESS) {
5074 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
5075 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
5077 #if !(MDB_MAXKEYSIZE)
5078 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
5080 env->me_maxpg = env->me_mapsize / env->me_psize;
5084 MDB_meta *meta = mdb_env_pick_meta(env);
5085 MDB_db *db = &meta->mm_dbs[MAIN_DBI];
5087 DPRINTF(("opened database version %u, pagesize %u",
5088 meta->mm_version, env->me_psize));
5089 DPRINTF(("using meta page %d", (int) (meta->mm_txnid & 1)));
5090 DPRINTF(("depth: %u", db->md_depth));
5091 DPRINTF(("entries: %"Yu, db->md_entries));
5092 DPRINTF(("branch pages: %"Yu, db->md_branch_pages));
5093 DPRINTF(("leaf pages: %"Yu, db->md_leaf_pages));
5094 DPRINTF(("overflow pages: %"Yu, db->md_overflow_pages));
5095 DPRINTF(("root: %"Yu, db->md_root));
5103 /** Release a reader thread's slot in the reader lock table.
5104 * This function is called automatically when a thread exits.
5105 * @param[in] ptr This points to the slot in the reader lock table.
5108 mdb_env_reader_dest(void *ptr)
5110 MDB_reader *reader = ptr;
5113 if (reader->mr_pid == getpid()) /* catch pthread_exit() in child process */
5115 /* We omit the mutex, so do this atomically (i.e. skip mr_txnid) */
5120 /** Junk for arranging thread-specific callbacks on Windows. This is
5121 * necessarily platform and compiler-specific. Windows supports up
5122 * to 1088 keys. Let's assume nobody opens more than 64 environments
5123 * in a single process, for now. They can override this if needed.
5125 #ifndef MAX_TLS_KEYS
5126 #define MAX_TLS_KEYS 64
5128 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
5129 static int mdb_tls_nkeys;
5131 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
5135 case DLL_PROCESS_ATTACH: break;
5136 case DLL_THREAD_ATTACH: break;
5137 case DLL_THREAD_DETACH:
5138 for (i=0; i<mdb_tls_nkeys; i++) {
5139 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
5141 mdb_env_reader_dest(r);
5145 case DLL_PROCESS_DETACH: break;
5150 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
5152 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
5156 /* Force some symbol references.
5157 * _tls_used forces the linker to create the TLS directory if not already done
5158 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
5160 #pragma comment(linker, "/INCLUDE:_tls_used")
5161 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
5162 #pragma const_seg(".CRT$XLB")
5163 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
5164 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
5167 #pragma comment(linker, "/INCLUDE:__tls_used")
5168 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
5169 #pragma data_seg(".CRT$XLB")
5170 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
5172 #endif /* WIN 32/64 */
5173 #endif /* !__GNUC__ */
5176 /** Downgrade the exclusive lock on the region back to shared */
5178 mdb_env_share_locks(MDB_env *env, int *excl)
5181 MDB_meta *meta = mdb_env_pick_meta(env);
5183 env->me_txns->mti_txnid = meta->mm_txnid;
5188 /* First acquire a shared lock. The Unlock will
5189 * then release the existing exclusive lock.
5191 memset(&ov, 0, sizeof(ov));
5192 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
5195 UnlockFile(env->me_lfd, 0, 0, 1, 0);
5201 struct flock lock_info;
5202 /* The shared lock replaces the existing lock */
5203 memset((void *)&lock_info, 0, sizeof(lock_info));
5204 lock_info.l_type = F_RDLCK;
5205 lock_info.l_whence = SEEK_SET;
5206 lock_info.l_start = 0;
5207 lock_info.l_len = 1;
5208 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
5209 (rc = ErrCode()) == EINTR) ;
5210 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
5217 /** Try to get exclusive lock, otherwise shared.
5218 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
5221 mdb_env_excl_lock(MDB_env *env, int *excl)
5225 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
5229 memset(&ov, 0, sizeof(ov));
5230 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
5237 struct flock lock_info;
5238 memset((void *)&lock_info, 0, sizeof(lock_info));
5239 lock_info.l_type = F_WRLCK;
5240 lock_info.l_whence = SEEK_SET;
5241 lock_info.l_start = 0;
5242 lock_info.l_len = 1;
5243 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
5244 (rc = ErrCode()) == EINTR) ;
5248 # ifndef MDB_USE_POSIX_MUTEX
5249 if (*excl < 0) /* always true when MDB_USE_POSIX_MUTEX */
5252 lock_info.l_type = F_RDLCK;
5253 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
5254 (rc = ErrCode()) == EINTR) ;
5264 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
5266 * @(#) $Revision: 5.1 $
5267 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
5268 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
5270 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
5274 * Please do not copyright this code. This code is in the public domain.
5276 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
5277 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
5278 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
5279 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
5280 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
5281 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
5282 * PERFORMANCE OF THIS SOFTWARE.
5285 * chongo <Landon Curt Noll> /\oo/\
5286 * http://www.isthe.com/chongo/
5288 * Share and Enjoy! :-)
5291 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
5292 * @param[in] val value to hash
5293 * @param[in] len length of value
5294 * @return 64 bit hash
5297 mdb_hash(const void *val, size_t len)
5299 const unsigned char *s = (const unsigned char *) val, *end = s + len;
5300 mdb_hash_t hval = 0xcbf29ce484222325ULL;
5302 * FNV-1a hash each octet of the buffer
5305 hval = (hval ^ *s++) * 0x100000001b3ULL;
5307 /* return our new hash value */
5311 /** Hash the string and output the encoded hash.
5312 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
5313 * very short name limits. We don't care about the encoding being reversible,
5314 * we just want to preserve as many bits of the input as possible in a
5315 * small printable string.
5316 * @param[in] str string to hash
5317 * @param[out] encbuf an array of 11 chars to hold the hash
5319 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
5322 mdb_pack85(unsigned long long l, char *out)
5326 for (i=0; i<10 && l; i++) {
5327 *out++ = mdb_a85[l % 85];
5333 /** Init #MDB_env.me_mutexname[] except the char which #MUTEXNAME() will set.
5334 * Changes to this code must be reflected in #MDB_LOCK_FORMAT.
5337 mdb_env_mname_init(MDB_env *env)
5339 char *nm = env->me_mutexname;
5340 strcpy(nm, MUTEXNAME_PREFIX);
5341 mdb_pack85(env->me_txns->mti_mutexid, nm + sizeof(MUTEXNAME_PREFIX));
5344 /** Return env->me_mutexname after filling in ch ('r'/'w') for convenience */
5345 #define MUTEXNAME(env, ch) ( \
5346 (void) ((env)->me_mutexname[sizeof(MUTEXNAME_PREFIX)-1] = (ch)), \
5347 (env)->me_mutexname)
5351 /** Open and/or initialize the lock region for the environment.
5352 * @param[in] env The LMDB environment.
5353 * @param[in] fname Filename + scratch area, from #mdb_fname_init().
5354 * @param[in] mode The Unix permissions for the file, if we create it.
5355 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
5356 * @return 0 on success, non-zero on failure.
5359 mdb_env_setup_locks(MDB_env *env, MDB_name *fname, int mode, int *excl)
5362 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
5364 # define MDB_ERRCODE_ROFS EROFS
5366 #ifdef MDB_USE_SYSV_SEM
5371 MDB_OFF_T size, rsize;
5373 rc = mdb_fopen(env, fname, MDB_O_LOCKS, mode, &env->me_lfd);
5375 /* Omit lockfile if read-only env on read-only filesystem */
5376 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
5382 if (!(env->me_flags & MDB_NOTLS)) {
5383 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
5386 env->me_flags |= MDB_ENV_TXKEY;
5388 /* Windows TLS callbacks need help finding their TLS info. */
5389 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
5393 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
5397 /* Try to get exclusive lock. If we succeed, then
5398 * nobody is using the lock region and we should initialize it.
5400 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
5403 size = GetFileSize(env->me_lfd, NULL);
5405 size = lseek(env->me_lfd, 0, SEEK_END);
5406 if (size == -1) goto fail_errno;
5408 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
5409 if (size < rsize && *excl > 0) {
5411 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
5412 || !SetEndOfFile(env->me_lfd))
5415 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
5419 size = rsize - sizeof(MDB_txninfo);
5420 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
5425 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
5427 if (!mh) goto fail_errno;
5428 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
5430 if (!env->me_txns) goto fail_errno;
5432 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
5434 if (m == MAP_FAILED) goto fail_errno;
5440 BY_HANDLE_FILE_INFORMATION stbuf;
5447 if (!mdb_sec_inited) {
5448 InitializeSecurityDescriptor(&mdb_null_sd,
5449 SECURITY_DESCRIPTOR_REVISION);
5450 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
5451 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
5452 mdb_all_sa.bInheritHandle = FALSE;
5453 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
5456 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
5457 idbuf.volume = stbuf.dwVolumeSerialNumber;
5458 idbuf.nhigh = stbuf.nFileIndexHigh;
5459 idbuf.nlow = stbuf.nFileIndexLow;
5460 env->me_txns->mti_mutexid = mdb_hash(&idbuf, sizeof(idbuf));
5461 mdb_env_mname_init(env);
5462 env->me_rmutex = CreateMutexA(&mdb_all_sa, FALSE, MUTEXNAME(env, 'r'));
5463 if (!env->me_rmutex) goto fail_errno;
5464 env->me_wmutex = CreateMutexA(&mdb_all_sa, FALSE, MUTEXNAME(env, 'w'));
5465 if (!env->me_wmutex) goto fail_errno;
5466 #elif defined(MDB_USE_POSIX_SEM)
5473 #if defined(__NetBSD__)
5474 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
5476 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
5477 memset(&idbuf, 0, sizeof(idbuf));
5478 idbuf.dev = stbuf.st_dev;
5479 idbuf.ino = stbuf.st_ino;
5480 env->me_txns->mti_mutexid = mdb_hash(&idbuf, sizeof(idbuf))
5481 #ifdef MDB_SHORT_SEMNAMES
5482 /* Max 9 base85-digits. We truncate here instead of in
5483 * mdb_env_mname_init() to keep the latter portable.
5485 % ((mdb_hash_t)85*85*85*85*85*85*85*85*85)
5488 mdb_env_mname_init(env);
5489 /* Clean up after a previous run, if needed: Try to
5490 * remove both semaphores before doing anything else.
5492 sem_unlink(MUTEXNAME(env, 'r'));
5493 sem_unlink(MUTEXNAME(env, 'w'));
5494 env->me_rmutex = sem_open(MUTEXNAME(env, 'r'), O_CREAT|O_EXCL, mode, 1);
5495 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
5496 env->me_wmutex = sem_open(MUTEXNAME(env, 'w'), O_CREAT|O_EXCL, mode, 1);
5497 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
5498 #elif defined(MDB_USE_SYSV_SEM)
5499 unsigned short vals[2] = {1, 1};
5500 key_t key = ftok(fname->mn_val, 'M'); /* fname is lockfile path now */
5503 semid = semget(key, 2, (mode & 0777) | IPC_CREAT);
5507 if (semctl(semid, 0, SETALL, semu) < 0)
5509 env->me_txns->mti_semid = semid;
5510 env->me_txns->mti_rlocked = 0;
5511 env->me_txns->mti_wlocked = 0;
5512 #else /* MDB_USE_POSIX_MUTEX: */
5513 pthread_mutexattr_t mattr;
5515 /* Solaris needs this before initing a robust mutex. Otherwise
5516 * it may skip the init and return EBUSY "seems someone already
5517 * inited" or EINVAL "it was inited differently".
5519 memset(env->me_txns->mti_rmutex, 0, sizeof(*env->me_txns->mti_rmutex));
5520 memset(env->me_txns->mti_wmutex, 0, sizeof(*env->me_txns->mti_wmutex));
5522 if ((rc = pthread_mutexattr_init(&mattr)) != 0)
5524 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
5525 #ifdef MDB_ROBUST_SUPPORTED
5526 if (!rc) rc = pthread_mutexattr_setrobust(&mattr, PTHREAD_MUTEX_ROBUST);
5528 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_rmutex, &mattr);
5529 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_wmutex, &mattr);
5530 pthread_mutexattr_destroy(&mattr);
5533 #endif /* _WIN32 || ... */
5535 env->me_txns->mti_magic = MDB_MAGIC;
5536 env->me_txns->mti_format = MDB_LOCK_FORMAT;
5537 env->me_txns->mti_txnid = 0;
5538 env->me_txns->mti_numreaders = 0;
5541 #ifdef MDB_USE_SYSV_SEM
5542 struct semid_ds buf;
5544 if (env->me_txns->mti_magic != MDB_MAGIC) {
5545 DPUTS("lock region has invalid magic");
5549 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
5550 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
5551 env->me_txns->mti_format, MDB_LOCK_FORMAT));
5552 rc = MDB_VERSION_MISMATCH;
5556 if (rc && rc != EACCES && rc != EAGAIN) {
5560 mdb_env_mname_init(env);
5561 env->me_rmutex = OpenMutexA(SYNCHRONIZE, FALSE, MUTEXNAME(env, 'r'));
5562 if (!env->me_rmutex) goto fail_errno;
5563 env->me_wmutex = OpenMutexA(SYNCHRONIZE, FALSE, MUTEXNAME(env, 'w'));
5564 if (!env->me_wmutex) goto fail_errno;
5565 #elif defined(MDB_USE_POSIX_SEM)
5566 mdb_env_mname_init(env);
5567 env->me_rmutex = sem_open(MUTEXNAME(env, 'r'), 0);
5568 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
5569 env->me_wmutex = sem_open(MUTEXNAME(env, 'w'), 0);
5570 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
5571 #elif defined(MDB_USE_SYSV_SEM)
5572 semid = env->me_txns->mti_semid;
5574 /* check for read access */
5575 if (semctl(semid, 0, IPC_STAT, semu) < 0)
5577 /* check for write access */
5578 if (semctl(semid, 0, IPC_SET, semu) < 0)
5582 #ifdef MDB_USE_SYSV_SEM
5583 env->me_rmutex->semid = semid;
5584 env->me_wmutex->semid = semid;
5585 env->me_rmutex->semnum = 0;
5586 env->me_wmutex->semnum = 1;
5587 env->me_rmutex->locked = &env->me_txns->mti_rlocked;
5588 env->me_wmutex->locked = &env->me_txns->mti_wlocked;
5599 /** Only a subset of the @ref mdb_env flags can be changed
5600 * at runtime. Changing other flags requires closing the
5601 * environment and re-opening it with the new flags.
5603 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
5604 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY| \
5605 MDB_WRITEMAP|MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD|MDB_PREVSNAPSHOT)
5607 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
5608 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
5612 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
5617 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
5621 if (flags & MDB_WRITEMAP) {
5622 /* silently ignore WRITEMAP in 32 bit mode */
5623 flags ^= MDB_WRITEMAP;
5625 if (flags & MDB_FIXEDMAP) {
5626 /* cannot support FIXEDMAP */
5630 flags |= env->me_flags;
5632 rc = mdb_fname_init(path, flags, &fname);
5638 env->me_rpmutex = CreateMutex(NULL, FALSE, NULL);
5639 if (!env->me_rpmutex) {
5644 rc = pthread_mutex_init(&env->me_rpmutex, NULL);
5649 flags |= MDB_ENV_ACTIVE; /* tell mdb_env_close0() to clean up */
5651 if (flags & MDB_RDONLY) {
5652 /* silently ignore WRITEMAP when we're only getting read access */
5653 flags &= ~MDB_WRITEMAP;
5655 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
5656 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
5660 env->me_flags = flags;
5666 env->me_rpages = malloc(MDB_ERPAGE_SIZE * sizeof(MDB_ID3));
5667 if (!env->me_rpages) {
5671 env->me_rpages[0].mid = 0;
5672 env->me_rpcheck = MDB_ERPAGE_SIZE/2;
5676 env->me_path = strdup(path);
5677 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
5678 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
5679 env->me_dbiseqs = calloc(env->me_maxdbs, sizeof(unsigned int));
5680 if (!(env->me_dbxs && env->me_path && env->me_dbflags && env->me_dbiseqs)) {
5684 env->me_dbxs[FREE_DBI].md_cmp = mdb_cmp_long; /* aligned MDB_INTEGERKEY */
5686 /* For RDONLY, get lockfile after we know datafile exists */
5687 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
5688 rc = mdb_env_setup_locks(env, &fname, mode, &excl);
5691 if ((flags & MDB_PREVSNAPSHOT) && !excl) {
5697 rc = mdb_fopen(env, &fname,
5698 (flags & MDB_RDONLY) ? MDB_O_RDONLY : MDB_O_RDWR,
5703 rc = mdb_fopen(env, &fname, MDB_O_OVERLAPPED, mode, &env->me_ovfd);
5708 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
5709 rc = mdb_env_setup_locks(env, &fname, mode, &excl);
5714 if ((rc = mdb_env_open2(env, flags & MDB_PREVSNAPSHOT)) == MDB_SUCCESS) {
5715 /* Synchronous fd for meta writes. Needed even with
5716 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
5718 if (!(flags & (MDB_RDONLY|MDB_WRITEMAP))) {
5719 rc = mdb_fopen(env, &fname, MDB_O_META, mode, &env->me_mfd);
5723 DPRINTF(("opened dbenv %p", (void *) env));
5724 if (excl > 0 && !(flags & MDB_PREVSNAPSHOT)) {
5725 rc = mdb_env_share_locks(env, &excl);
5729 if (!(flags & MDB_RDONLY)) {
5731 int tsize = sizeof(MDB_txn), size = tsize + env->me_maxdbs *
5732 (sizeof(MDB_db)+sizeof(MDB_cursor *)+sizeof(unsigned int)+1);
5733 if ((env->me_pbuf = calloc(1, env->me_psize)) &&
5734 (txn = calloc(1, size)))
5736 txn->mt_dbs = (MDB_db *)((char *)txn + tsize);
5737 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
5738 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
5739 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
5742 txn->mt_rpages = malloc(MDB_TRPAGE_SIZE * sizeof(MDB_ID3));
5743 if (!txn->mt_rpages) {
5748 txn->mt_rpages[0].mid = 0;
5749 txn->mt_rpcheck = MDB_TRPAGE_SIZE/2;
5751 txn->mt_dbxs = env->me_dbxs;
5752 txn->mt_flags = MDB_TXN_FINISHED;
5761 MDB_TRACE(("%p, %s, %u, %04o", env, path, flags & (CHANGEABLE|CHANGELESS), mode));
5763 mdb_env_close0(env, excl);
5765 mdb_fname_destroy(fname);
5769 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
5771 mdb_env_close0(MDB_env *env, int excl)
5775 if (!(env->me_flags & MDB_ENV_ACTIVE))
5778 /* Doing this here since me_dbxs may not exist during mdb_env_close */
5780 for (i = env->me_maxdbs; --i >= CORE_DBS; )
5781 free(env->me_dbxs[i].md_name.mv_data);
5786 free(env->me_dbiseqs);
5787 free(env->me_dbflags);
5789 free(env->me_dirty_list);
5791 if (env->me_txn0 && env->me_txn0->mt_rpages)
5792 free(env->me_txn0->mt_rpages);
5793 if (env->me_rpages) {
5794 MDB_ID3L el = env->me_rpages;
5796 for (x=1; x<=el[0].mid; x++)
5797 munmap(el[x].mptr, el[x].mcnt * env->me_psize);
5802 mdb_midl_free(env->me_free_pgs);
5804 if (env->me_flags & MDB_ENV_TXKEY) {
5805 pthread_key_delete(env->me_txkey);
5807 /* Delete our key from the global list */
5808 for (i=0; i<mdb_tls_nkeys; i++)
5809 if (mdb_tls_keys[i] == env->me_txkey) {
5810 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
5819 munmap(env->me_map, NUM_METAS*env->me_psize);
5821 munmap(env->me_map, env->me_mapsize);
5824 if (env->me_mfd != INVALID_HANDLE_VALUE)
5825 (void) close(env->me_mfd);
5828 for (i = 0; i < env->ovs; i++) {
5829 CloseHandle(env->ov[i].hEvent);
5833 if (env->me_ovfd != INVALID_HANDLE_VALUE)
5834 (void) close(env->me_ovfd);
5836 if (env->me_fd != INVALID_HANDLE_VALUE)
5837 (void) close(env->me_fd);
5839 MDB_PID_T pid = getpid();
5840 /* Clearing readers is done in this function because
5841 * me_txkey with its destructor must be disabled first.
5843 * We skip the the reader mutex, so we touch only
5844 * data owned by this process (me_close_readers and
5845 * our readers), and clear each reader atomically.
5847 for (i = env->me_close_readers; --i >= 0; )
5848 if (env->me_txns->mti_readers[i].mr_pid == pid)
5849 env->me_txns->mti_readers[i].mr_pid = 0;
5851 if (env->me_rmutex) {
5852 CloseHandle(env->me_rmutex);
5853 if (env->me_wmutex) CloseHandle(env->me_wmutex);
5855 /* Windows automatically destroys the mutexes when
5856 * the last handle closes.
5858 #elif defined(MDB_USE_POSIX_SEM)
5859 if (env->me_rmutex != SEM_FAILED) {
5860 sem_close(env->me_rmutex);
5861 if (env->me_wmutex != SEM_FAILED)
5862 sem_close(env->me_wmutex);
5863 /* If we have the filelock: If we are the
5864 * only remaining user, clean up semaphores.
5867 mdb_env_excl_lock(env, &excl);
5869 sem_unlink(MUTEXNAME(env, 'r'));
5870 sem_unlink(MUTEXNAME(env, 'w'));
5873 #elif defined(MDB_USE_SYSV_SEM)
5874 if (env->me_rmutex->semid != -1) {
5875 /* If we have the filelock: If we are the
5876 * only remaining user, clean up semaphores.
5879 mdb_env_excl_lock(env, &excl);
5881 semctl(env->me_rmutex->semid, 0, IPC_RMID);
5884 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
5886 if (env->me_lfd != INVALID_HANDLE_VALUE) {
5889 /* Unlock the lockfile. Windows would have unlocked it
5890 * after closing anyway, but not necessarily at once.
5892 UnlockFile(env->me_lfd, 0, 0, 1, 0);
5895 (void) close(env->me_lfd);
5899 if (env->me_fmh) CloseHandle(env->me_fmh);
5900 if (env->me_rpmutex) CloseHandle(env->me_rpmutex);
5902 pthread_mutex_destroy(&env->me_rpmutex);
5906 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
5910 mdb_env_close(MDB_env *env)
5917 MDB_TRACE(("%p", env));
5918 VGMEMP_DESTROY(env);
5919 while ((dp = env->me_dpages) != NULL) {
5920 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
5921 env->me_dpages = dp->mp_next;
5925 mdb_env_close0(env, 0);
5929 /** Compare two items pointing at aligned #mdb_size_t's */
5931 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
5933 return (*(mdb_size_t *)a->mv_data < *(mdb_size_t *)b->mv_data) ? -1 :
5934 *(mdb_size_t *)a->mv_data > *(mdb_size_t *)b->mv_data;
5937 /** Compare two items pointing at aligned unsigned int's.
5939 * This is also set as #MDB_INTEGERDUP|#MDB_DUPFIXED's #MDB_dbx.%md_dcmp,
5940 * but #mdb_cmp_clong() is called instead if the data type is #mdb_size_t.
5943 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
5945 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
5946 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
5949 /** Compare two items pointing at unsigned ints of unknown alignment.
5950 * Nodes and keys are guaranteed to be 2-byte aligned.
5953 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
5955 #if BYTE_ORDER == LITTLE_ENDIAN
5956 unsigned short *u, *c;
5959 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5960 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
5963 } while(!x && u > (unsigned short *)a->mv_data);
5966 unsigned short *u, *c, *end;
5969 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5970 u = (unsigned short *)a->mv_data;
5971 c = (unsigned short *)b->mv_data;
5974 } while(!x && u < end);
5979 /** Compare two items lexically */
5981 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
5988 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5994 diff = memcmp(a->mv_data, b->mv_data, len);
5995 return diff ? diff : len_diff<0 ? -1 : len_diff;
5998 /** Compare two items in reverse byte order */
6000 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
6002 const unsigned char *p1, *p2, *p1_lim;
6006 p1_lim = (const unsigned char *)a->mv_data;
6007 p1 = (const unsigned char *)a->mv_data + a->mv_size;
6008 p2 = (const unsigned char *)b->mv_data + b->mv_size;
6010 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
6016 while (p1 > p1_lim) {
6017 diff = *--p1 - *--p2;
6021 return len_diff<0 ? -1 : len_diff;
6024 /** Search for key within a page, using binary search.
6025 * Returns the smallest entry larger or equal to the key.
6026 * If exactp is non-null, stores whether the found entry was an exact match
6027 * in *exactp (1 or 0).
6028 * Updates the cursor index with the index of the found entry.
6029 * If no entry larger or equal to the key is found, returns NULL.
6032 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
6034 unsigned int i = 0, nkeys;
6037 MDB_page *mp = mc->mc_pg[mc->mc_top];
6038 MDB_node *node = NULL;
6043 nkeys = NUMKEYS(mp);
6045 DPRINTF(("searching %u keys in %s %spage %"Yu,
6046 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
6049 low = IS_LEAF(mp) ? 0 : 1;
6051 cmp = mc->mc_dbx->md_cmp;
6053 /* Branch pages have no data, so if using integer keys,
6054 * alignment is guaranteed. Use faster mdb_cmp_int.
6056 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
6057 if (NODEPTR(mp, 1)->mn_ksize == sizeof(mdb_size_t))
6064 nodekey.mv_size = mc->mc_db->md_pad;
6065 node = NODEPTR(mp, 0); /* fake */
6066 while (low <= high) {
6067 i = (low + high) >> 1;
6068 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
6069 rc = cmp(key, &nodekey);
6070 DPRINTF(("found leaf index %u [%s], rc = %i",
6071 i, DKEY(&nodekey), rc));
6080 while (low <= high) {
6081 i = (low + high) >> 1;
6083 node = NODEPTR(mp, i);
6084 nodekey.mv_size = NODEKSZ(node);
6085 nodekey.mv_data = NODEKEY(node);
6087 rc = cmp(key, &nodekey);
6090 DPRINTF(("found leaf index %u [%s], rc = %i",
6091 i, DKEY(&nodekey), rc));
6093 DPRINTF(("found branch index %u [%s -> %"Yu"], rc = %i",
6094 i, DKEY(&nodekey), NODEPGNO(node), rc));
6105 if (rc > 0) { /* Found entry is less than the key. */
6106 i++; /* Skip to get the smallest entry larger than key. */
6108 node = NODEPTR(mp, i);
6111 *exactp = (rc == 0 && nkeys > 0);
6112 /* store the key index */
6113 mc->mc_ki[mc->mc_top] = i;
6115 /* There is no entry larger or equal to the key. */
6118 /* nodeptr is fake for LEAF2 */
6124 mdb_cursor_adjust(MDB_cursor *mc, func)
6128 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6129 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
6136 /** Pop a page off the top of the cursor's stack. */
6138 mdb_cursor_pop(MDB_cursor *mc)
6141 DPRINTF(("popping page %"Yu" off db %d cursor %p",
6142 mc->mc_pg[mc->mc_top]->mp_pgno, DDBI(mc), (void *) mc));
6148 mc->mc_flags &= ~C_INITIALIZED;
6153 /** Push a page onto the top of the cursor's stack.
6154 * Set #MDB_TXN_ERROR on failure.
6157 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
6159 DPRINTF(("pushing page %"Yu" on db %d cursor %p", mp->mp_pgno,
6160 DDBI(mc), (void *) mc));
6162 if (mc->mc_snum >= CURSOR_STACK) {
6163 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6164 return MDB_CURSOR_FULL;
6167 mc->mc_top = mc->mc_snum++;
6168 mc->mc_pg[mc->mc_top] = mp;
6169 mc->mc_ki[mc->mc_top] = 0;
6175 /** Map a read-only page.
6176 * There are two levels of tracking in use, a per-txn list and a per-env list.
6177 * ref'ing and unref'ing the per-txn list is faster since it requires no
6178 * locking. Pages are cached in the per-env list for global reuse, and a lock
6179 * is required. Pages are not immediately unmapped when their refcnt goes to
6180 * zero; they hang around in case they will be reused again soon.
6182 * When the per-txn list gets full, all pages with refcnt=0 are purged from the
6183 * list and their refcnts in the per-env list are decremented.
6185 * When the per-env list gets full, all pages with refcnt=0 are purged from the
6186 * list and their pages are unmapped.
6188 * @note "full" means the list has reached its respective rpcheck threshold.
6189 * This threshold slowly raises if no pages could be purged on a given check,
6190 * and returns to its original value when enough pages were purged.
6192 * If purging doesn't free any slots, filling the per-txn list will return
6193 * MDB_TXN_FULL, and filling the per-env list returns MDB_MAP_FULL.
6195 * Reference tracking in a txn is imperfect, pages can linger with non-zero
6196 * refcnt even without active references. It was deemed to be too invasive
6197 * to add unrefs in every required location. However, all pages are unref'd
6198 * at the end of the transaction. This guarantees that no stale references
6199 * linger in the per-env list.
6201 * Usually we map chunks of 16 pages at a time, but if an overflow page begins
6202 * at the tail of the chunk we extend the chunk to include the entire overflow
6203 * page. Unfortunately, pages can be turned into overflow pages after their
6204 * chunk was already mapped. In that case we must remap the chunk if the
6205 * overflow page is referenced. If the chunk's refcnt is 0 we can just remap
6206 * it, otherwise we temporarily map a new chunk just for the overflow page.
6208 * @note this chunk handling means we cannot guarantee that a data item
6209 * returned from the DB will stay alive for the duration of the transaction:
6210 * We unref pages as soon as a cursor moves away from the page
6211 * A subsequent op may cause a purge, which may unmap any unref'd chunks
6212 * The caller must copy the data if it must be used later in the same txn.
6214 * Also - our reference counting revolves around cursors, but overflow pages
6215 * aren't pointed to by a cursor's page stack. We have to remember them
6216 * explicitly, in the added mc_ovpg field. A single cursor can only hold a
6217 * reference to one overflow page at a time.
6219 * @param[in] txn the transaction for this access.
6220 * @param[in] pgno the page number for the page to retrieve.
6221 * @param[out] ret address of a pointer where the page's address will be stored.
6222 * @return 0 on success, non-zero on failure.
6225 mdb_rpage_get(MDB_txn *txn, pgno_t pg0, MDB_page **ret)
6227 MDB_env *env = txn->mt_env;
6229 MDB_ID3L tl = txn->mt_rpages;
6230 MDB_ID3L el = env->me_rpages;
6234 int rc, retries = 1;
6238 #define SET_OFF(off,val) off.QuadPart = val
6239 #define MAP(rc,env,addr,len,off) \
6241 rc = NtMapViewOfSection(env->me_fmh, GetCurrentProcess(), &addr, 0, \
6242 len, &off, &len, ViewUnmap, (env->me_flags & MDB_RDONLY) ? 0 : MEM_RESERVE, PAGE_READONLY); \
6243 if (rc) rc = mdb_nt2win32(rc)
6247 #define SET_OFF(off,val) off = val
6248 #define MAP(rc,env,addr,len,off) \
6249 addr = mmap(NULL, len, PROT_READ, MAP_SHARED, env->me_fd, off); \
6250 rc = (addr == MAP_FAILED) ? errno : 0
6253 /* remember the offset of the actual page number, so we can
6254 * return the correct pointer at the end.
6256 rem = pg0 & (MDB_RPAGE_CHUNK-1);
6260 x = mdb_mid3l_search(tl, pgno);
6261 if (x <= tl[0].mid && tl[x].mid == pgno) {
6262 if (x != tl[0].mid && tl[x+1].mid == pg0)
6264 /* check for overflow size */
6265 p = (MDB_page *)((char *)tl[x].mptr + rem * env->me_psize);
6266 if (IS_OVERFLOW(p) && p->mp_pages + rem > tl[x].mcnt) {
6267 id3.mcnt = p->mp_pages + rem;
6268 len = id3.mcnt * env->me_psize;
6269 SET_OFF(off, pgno * env->me_psize);
6270 MAP(rc, env, id3.mptr, len, off);
6273 /* check for local-only page */
6275 mdb_tassert(txn, tl[x].mid != pg0);
6276 /* hope there's room to insert this locally.
6277 * setting mid here tells later code to just insert
6278 * this id3 instead of searching for a match.
6283 /* ignore the mapping we got from env, use new one */
6284 tl[x].mptr = id3.mptr;
6285 tl[x].mcnt = id3.mcnt;
6286 /* if no active ref, see if we can replace in env */
6289 pthread_mutex_lock(&env->me_rpmutex);
6290 i = mdb_mid3l_search(el, tl[x].mid);
6291 if (el[i].mref == 1) {
6292 /* just us, replace it */
6293 munmap(el[i].mptr, el[i].mcnt * env->me_psize);
6294 el[i].mptr = tl[x].mptr;
6295 el[i].mcnt = tl[x].mcnt;
6297 /* there are others, remove ourself */
6300 pthread_mutex_unlock(&env->me_rpmutex);
6304 id3.mptr = tl[x].mptr;
6305 id3.mcnt = tl[x].mcnt;
6311 if (tl[0].mid >= MDB_TRPAGE_MAX - txn->mt_rpcheck) {
6313 /* purge unref'd pages from our list and unref in env */
6314 pthread_mutex_lock(&env->me_rpmutex);
6317 for (i=1; i<=tl[0].mid; i++) {
6320 /* tmp overflow pages don't go to env */
6321 if (tl[i].mid & (MDB_RPAGE_CHUNK-1)) {
6322 munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
6325 x = mdb_mid3l_search(el, tl[i].mid);
6329 pthread_mutex_unlock(&env->me_rpmutex);
6331 /* we didn't find any unref'd chunks.
6332 * if we're out of room, fail.
6334 if (tl[0].mid >= MDB_TRPAGE_MAX)
6335 return MDB_TXN_FULL;
6336 /* otherwise, raise threshold for next time around
6339 txn->mt_rpcheck /= 2;
6341 /* we found some unused; consolidate the list */
6342 for (i=y+1; i<= tl[0].mid; i++)
6346 /* decrease the check threshold toward its original value */
6347 if (!txn->mt_rpcheck)
6348 txn->mt_rpcheck = 1;
6349 while (txn->mt_rpcheck < tl[0].mid && txn->mt_rpcheck < MDB_TRPAGE_SIZE/2)
6350 txn->mt_rpcheck *= 2;
6353 if (tl[0].mid < MDB_TRPAGE_SIZE) {
6357 /* don't map past last written page in read-only envs */
6358 if ((env->me_flags & MDB_RDONLY) && pgno + MDB_RPAGE_CHUNK-1 > txn->mt_last_pgno)
6359 id3.mcnt = txn->mt_last_pgno + 1 - pgno;
6361 id3.mcnt = MDB_RPAGE_CHUNK;
6362 len = id3.mcnt * env->me_psize;
6365 /* search for page in env */
6366 pthread_mutex_lock(&env->me_rpmutex);
6367 x = mdb_mid3l_search(el, pgno);
6368 if (x <= el[0].mid && el[x].mid == pgno) {
6369 id3.mptr = el[x].mptr;
6370 id3.mcnt = el[x].mcnt;
6371 /* check for overflow size */
6372 p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
6373 if (IS_OVERFLOW(p) && p->mp_pages + rem > id3.mcnt) {
6374 id3.mcnt = p->mp_pages + rem;
6375 len = id3.mcnt * env->me_psize;
6376 SET_OFF(off, pgno * env->me_psize);
6377 MAP(rc, env, id3.mptr, len, off);
6381 munmap(el[x].mptr, env->me_psize * el[x].mcnt);
6382 el[x].mptr = id3.mptr;
6383 el[x].mcnt = id3.mcnt;
6386 pthread_mutex_unlock(&env->me_rpmutex);
6391 pthread_mutex_unlock(&env->me_rpmutex);
6394 if (el[0].mid >= MDB_ERPAGE_MAX - env->me_rpcheck) {
6395 /* purge unref'd pages */
6397 for (i=1; i<=el[0].mid; i++) {
6400 munmap(el[i].mptr, env->me_psize * el[i].mcnt);
6405 /* see if we can unref some local pages */
6410 if (el[0].mid >= MDB_ERPAGE_MAX) {
6411 pthread_mutex_unlock(&env->me_rpmutex);
6412 return MDB_MAP_FULL;
6414 env->me_rpcheck /= 2;
6416 for (i=y+1; i<= el[0].mid; i++)
6420 if (!env->me_rpcheck)
6421 env->me_rpcheck = 1;
6422 while (env->me_rpcheck < el[0].mid && env->me_rpcheck < MDB_ERPAGE_SIZE/2)
6423 env->me_rpcheck *= 2;
6426 SET_OFF(off, pgno * env->me_psize);
6427 MAP(rc, env, id3.mptr, len, off);
6430 pthread_mutex_unlock(&env->me_rpmutex);
6433 /* check for overflow size */
6434 p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
6435 if (IS_OVERFLOW(p) && p->mp_pages + rem > id3.mcnt) {
6436 id3.mcnt = p->mp_pages + rem;
6437 munmap(id3.mptr, len);
6438 len = id3.mcnt * env->me_psize;
6439 MAP(rc, env, id3.mptr, len, off);
6443 mdb_mid3l_insert(el, &id3);
6444 pthread_mutex_unlock(&env->me_rpmutex);
6446 mdb_mid3l_insert(tl, &id3);
6448 return MDB_TXN_FULL;
6451 p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
6452 #if MDB_DEBUG /* we don't need this check any more */
6453 if (IS_OVERFLOW(p)) {
6454 mdb_tassert(txn, p->mp_pages + rem <= id3.mcnt);
6462 /** Find the address of the page corresponding to a given page number.
6463 * Set #MDB_TXN_ERROR on failure.
6464 * @param[in] mc the cursor accessing the page.
6465 * @param[in] pgno the page number for the page to retrieve.
6466 * @param[out] ret address of a pointer where the page's address will be stored.
6467 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
6468 * @return 0 on success, non-zero on failure.
6471 mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **ret, int *lvl)
6473 MDB_txn *txn = mc->mc_txn;
6477 if (! (mc->mc_flags & (C_ORIG_RDONLY|C_WRITEMAP))) {
6481 MDB_ID2L dl = tx2->mt_u.dirty_list;
6483 /* Spilled pages were dirtied in this txn and flushed
6484 * because the dirty list got full. Bring this page
6485 * back in from the map (but don't unspill it here,
6486 * leave that unless page_touch happens again).
6488 if (tx2->mt_spill_pgs) {
6489 MDB_ID pn = pgno << 1;
6490 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
6491 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
6496 unsigned x = mdb_mid2l_search(dl, pgno);
6497 if (x <= dl[0].mid && dl[x].mid == pgno) {
6503 } while ((tx2 = tx2->mt_parent) != NULL);
6506 if (pgno >= txn->mt_next_pgno) {
6507 DPRINTF(("page %"Yu" not found", pgno));
6508 txn->mt_flags |= MDB_TXN_ERROR;
6509 return MDB_PAGE_NOTFOUND;
6517 int rc = mdb_rpage_get(txn, pgno, &p);
6519 txn->mt_flags |= MDB_TXN_ERROR;
6523 MDB_env *env = txn->mt_env;
6524 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
6535 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
6536 * The cursor is at the root page, set up the rest of it.
6539 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
6541 MDB_page *mp = mc->mc_pg[mc->mc_top];
6545 while (IS_BRANCH(mp)) {
6549 DPRINTF(("branch page %"Yu" has %u keys", mp->mp_pgno, NUMKEYS(mp)));
6550 /* Don't assert on branch pages in the FreeDB. We can get here
6551 * while in the process of rebalancing a FreeDB branch page; we must
6552 * let that proceed. ITS#8336
6554 mdb_cassert(mc, !mc->mc_dbi || NUMKEYS(mp) > 1);
6555 DPRINTF(("found index 0 to page %"Yu, NODEPGNO(NODEPTR(mp, 0))));
6557 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
6559 if (flags & MDB_PS_LAST) {
6560 i = NUMKEYS(mp) - 1;
6561 /* if already init'd, see if we're already in right place */
6562 if (mc->mc_flags & C_INITIALIZED) {
6563 if (mc->mc_ki[mc->mc_top] == i) {
6564 mc->mc_top = mc->mc_snum++;
6565 mp = mc->mc_pg[mc->mc_top];
6572 node = mdb_node_search(mc, key, &exact);
6574 i = NUMKEYS(mp) - 1;
6576 i = mc->mc_ki[mc->mc_top];
6578 mdb_cassert(mc, i > 0);
6582 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
6585 mdb_cassert(mc, i < NUMKEYS(mp));
6586 node = NODEPTR(mp, i);
6588 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
6591 mc->mc_ki[mc->mc_top] = i;
6592 if ((rc = mdb_cursor_push(mc, mp)))
6596 if (flags & MDB_PS_MODIFY) {
6597 if ((rc = mdb_page_touch(mc)) != 0)
6599 mp = mc->mc_pg[mc->mc_top];
6604 DPRINTF(("internal error, index points to a %02X page!?",
6606 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6607 return MDB_CORRUPTED;
6610 DPRINTF(("found leaf page %"Yu" for key [%s]", mp->mp_pgno,
6611 key ? DKEY(key) : "null"));
6612 mc->mc_flags |= C_INITIALIZED;
6613 mc->mc_flags &= ~C_EOF;
6618 /** Search for the lowest key under the current branch page.
6619 * This just bypasses a NUMKEYS check in the current page
6620 * before calling mdb_page_search_root(), because the callers
6621 * are all in situations where the current page is known to
6625 mdb_page_search_lowest(MDB_cursor *mc)
6627 MDB_page *mp = mc->mc_pg[mc->mc_top];
6628 MDB_node *node = NODEPTR(mp, 0);
6631 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
6634 mc->mc_ki[mc->mc_top] = 0;
6635 if ((rc = mdb_cursor_push(mc, mp)))
6637 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
6640 /** Search for the page a given key should be in.
6641 * Push it and its parent pages on the cursor stack.
6642 * @param[in,out] mc the cursor for this operation.
6643 * @param[in] key the key to search for, or NULL for first/last page.
6644 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
6645 * are touched (updated with new page numbers).
6646 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
6647 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
6648 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
6649 * @return 0 on success, non-zero on failure.
6652 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
6657 /* Make sure the txn is still viable, then find the root from
6658 * the txn's db table and set it as the root of the cursor's stack.
6660 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED) {
6661 DPUTS("transaction may not be used now");
6664 /* Make sure we're using an up-to-date root */
6665 if (*mc->mc_dbflag & DB_STALE) {
6667 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
6669 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
6670 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
6677 MDB_node *leaf = mdb_node_search(&mc2,
6678 &mc->mc_dbx->md_name, &exact);
6681 if ((leaf->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
6682 return MDB_INCOMPATIBLE; /* not a named DB */
6683 rc = mdb_node_read(&mc2, leaf, &data);
6686 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
6688 /* The txn may not know this DBI, or another process may
6689 * have dropped and recreated the DB with other flags.
6691 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
6692 return MDB_INCOMPATIBLE;
6693 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
6695 *mc->mc_dbflag &= ~DB_STALE;
6697 root = mc->mc_db->md_root;
6699 if (root == P_INVALID) { /* Tree is empty. */
6700 DPUTS("tree is empty");
6701 return MDB_NOTFOUND;
6705 mdb_cassert(mc, root > 1);
6706 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root) {
6709 MDB_PAGE_UNREF(mc->mc_txn, mc->mc_pg[0]);
6711 if ((rc = mdb_page_get(mc, root, &mc->mc_pg[0], NULL)) != 0)
6718 for (i=1; i<mc->mc_snum; i++)
6719 MDB_PAGE_UNREF(mc->mc_txn, mc->mc_pg[i]);
6725 DPRINTF(("db %d root page %"Yu" has flags 0x%X",
6726 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
6728 if (flags & MDB_PS_MODIFY) {
6729 if ((rc = mdb_page_touch(mc)))
6733 if (flags & MDB_PS_ROOTONLY)
6736 return mdb_page_search_root(mc, key, flags);
6740 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
6742 MDB_txn *txn = mc->mc_txn;
6743 pgno_t pg = mp->mp_pgno;
6744 unsigned x = 0, ovpages = mp->mp_pages;
6745 MDB_env *env = txn->mt_env;
6746 MDB_IDL sl = txn->mt_spill_pgs;
6747 MDB_ID pn = pg << 1;
6750 DPRINTF(("free ov page %"Yu" (%d)", pg, ovpages));
6751 /* If the page is dirty or on the spill list we just acquired it,
6752 * so we should give it back to our current free list, if any.
6753 * Otherwise put it onto the list of pages we freed in this txn.
6755 * Won't create me_pghead: me_pglast must be inited along with it.
6756 * Unsupported in nested txns: They would need to hide the page
6757 * range in ancestor txns' dirty and spilled lists.
6759 if (env->me_pghead &&
6761 ((mp->mp_flags & P_DIRTY) ||
6762 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
6766 MDB_ID2 *dl, ix, iy;
6767 rc = mdb_midl_need(&env->me_pghead, ovpages);
6770 if (!(mp->mp_flags & P_DIRTY)) {
6771 /* This page is no longer spilled */
6778 /* Remove from dirty list */
6779 dl = txn->mt_u.dirty_list;
6781 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
6787 mdb_cassert(mc, x > 1);
6789 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
6790 txn->mt_flags |= MDB_TXN_ERROR;
6794 txn->mt_dirty_room++;
6795 if (!(env->me_flags & MDB_WRITEMAP))
6796 mdb_dpage_free(env, mp);
6798 /* Insert in me_pghead */
6799 mop = env->me_pghead;
6800 j = mop[0] + ovpages;
6801 for (i = mop[0]; i && mop[i] < pg; i--)
6807 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
6812 if (mc->mc_ovpg == mp)
6815 mc->mc_db->md_overflow_pages -= ovpages;
6819 /** Return the data associated with a given node.
6820 * @param[in] mc The cursor for this operation.
6821 * @param[in] leaf The node being read.
6822 * @param[out] data Updated to point to the node's data.
6823 * @return 0 on success, non-zero on failure.
6826 mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data)
6828 MDB_page *omp; /* overflow page */
6833 MDB_PAGE_UNREF(mc->mc_txn, MC_OVPG(mc));
6834 MC_SET_OVPG(mc, NULL);
6836 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6837 data->mv_size = NODEDSZ(leaf);
6838 data->mv_data = NODEDATA(leaf);
6842 /* Read overflow data.
6844 data->mv_size = NODEDSZ(leaf);
6845 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
6846 if ((rc = mdb_page_get(mc, pgno, &omp, NULL)) != 0) {
6847 DPRINTF(("read overflow page %"Yu" failed", pgno));
6850 data->mv_data = METADATA(omp);
6851 MC_SET_OVPG(mc, omp);
6857 mdb_get(MDB_txn *txn, MDB_dbi dbi,
6858 MDB_val *key, MDB_val *data)
6865 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
6867 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
6870 if (txn->mt_flags & MDB_TXN_BLOCKED)
6873 mdb_cursor_init(&mc, txn, dbi, &mx);
6874 rc = mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
6875 /* unref all the pages when MDB_VL32 - caller must copy the data
6876 * before doing anything else
6878 MDB_CURSOR_UNREF(&mc, 1);
6882 /** Find a sibling for a page.
6883 * Replaces the page at the top of the cursor's stack with the
6884 * specified sibling, if one exists.
6885 * @param[in] mc The cursor for this operation.
6886 * @param[in] move_right Non-zero if the right sibling is requested,
6887 * otherwise the left sibling.
6888 * @return 0 on success, non-zero on failure.
6891 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
6900 if (mc->mc_snum < 2) {
6901 return MDB_NOTFOUND; /* root has no siblings */
6905 op = mc->mc_pg[mc->mc_top];
6908 DPRINTF(("parent page is page %"Yu", index %u",
6909 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
6911 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6912 : (mc->mc_ki[mc->mc_top] == 0)) {
6913 DPRINTF(("no more keys left, moving to %s sibling",
6914 move_right ? "right" : "left"));
6915 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
6916 /* undo cursor_pop before returning */
6923 mc->mc_ki[mc->mc_top]++;
6925 mc->mc_ki[mc->mc_top]--;
6926 DPRINTF(("just moving to %s index key %u",
6927 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
6929 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
6931 MDB_PAGE_UNREF(mc->mc_txn, op);
6933 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6934 if ((rc = mdb_page_get(mc, NODEPGNO(indx), &mp, NULL)) != 0) {
6935 /* mc will be inconsistent if caller does mc_snum++ as above */
6936 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
6940 mdb_cursor_push(mc, mp);
6942 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
6947 /** Move the cursor to the next data item. */
6949 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
6955 if ((mc->mc_flags & C_DEL && op == MDB_NEXT_DUP))
6956 return MDB_NOTFOUND;
6958 if (!(mc->mc_flags & C_INITIALIZED))
6959 return mdb_cursor_first(mc, key, data);
6961 mp = mc->mc_pg[mc->mc_top];
6963 if (mc->mc_flags & C_EOF) {
6964 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mp)-1)
6965 return MDB_NOTFOUND;
6966 mc->mc_flags ^= C_EOF;
6969 if (mc->mc_db->md_flags & MDB_DUPSORT) {
6970 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6971 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6972 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
6973 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
6974 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
6975 if (rc == MDB_SUCCESS)
6976 MDB_GET_KEY(leaf, key);
6981 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
6984 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6985 if (op == MDB_NEXT_DUP)
6986 return MDB_NOTFOUND;
6990 DPRINTF(("cursor_next: top page is %"Yu" in cursor %p",
6991 mdb_dbg_pgno(mp), (void *) mc));
6992 if (mc->mc_flags & C_DEL) {
6993 mc->mc_flags ^= C_DEL;
6997 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
6998 DPUTS("=====> move to next sibling page");
6999 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
7000 mc->mc_flags |= C_EOF;
7003 mp = mc->mc_pg[mc->mc_top];
7004 DPRINTF(("next page is %"Yu", key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
7006 mc->mc_ki[mc->mc_top]++;
7009 DPRINTF(("==> cursor points to page %"Yu" with %u keys, key index %u",
7010 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
7013 key->mv_size = mc->mc_db->md_pad;
7014 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
7018 mdb_cassert(mc, IS_LEAF(mp));
7019 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7021 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7022 mdb_xcursor_init1(mc, leaf);
7023 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
7024 if (rc != MDB_SUCCESS)
7027 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
7031 MDB_GET_KEY(leaf, key);
7035 /** Move the cursor to the previous data item. */
7037 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
7043 if (!(mc->mc_flags & C_INITIALIZED)) {
7044 rc = mdb_cursor_last(mc, key, data);
7047 mc->mc_ki[mc->mc_top]++;
7050 mp = mc->mc_pg[mc->mc_top];
7052 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
7053 mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
7054 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7055 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7056 if (op == MDB_PREV || op == MDB_PREV_DUP) {
7057 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
7058 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
7059 if (rc == MDB_SUCCESS) {
7060 MDB_GET_KEY(leaf, key);
7061 mc->mc_flags &= ~C_EOF;
7067 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
7070 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
7071 if (op == MDB_PREV_DUP)
7072 return MDB_NOTFOUND;
7076 DPRINTF(("cursor_prev: top page is %"Yu" in cursor %p",
7077 mdb_dbg_pgno(mp), (void *) mc));
7079 mc->mc_flags &= ~(C_EOF|C_DEL);
7081 if (mc->mc_ki[mc->mc_top] == 0) {
7082 DPUTS("=====> move to prev sibling page");
7083 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
7086 mp = mc->mc_pg[mc->mc_top];
7087 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
7088 DPRINTF(("prev page is %"Yu", key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
7090 mc->mc_ki[mc->mc_top]--;
7092 DPRINTF(("==> cursor points to page %"Yu" with %u keys, key index %u",
7093 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
7096 return MDB_CORRUPTED;
7099 key->mv_size = mc->mc_db->md_pad;
7100 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
7104 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7106 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7107 mdb_xcursor_init1(mc, leaf);
7108 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
7109 if (rc != MDB_SUCCESS)
7112 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
7116 MDB_GET_KEY(leaf, key);
7120 /** Set the cursor on a specific data item. */
7122 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
7123 MDB_cursor_op op, int *exactp)
7127 MDB_node *leaf = NULL;
7130 if (key->mv_size == 0)
7131 return MDB_BAD_VALSIZE;
7133 if (mc->mc_xcursor) {
7134 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
7135 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
7138 /* See if we're already on the right page */
7139 if (mc->mc_flags & C_INITIALIZED) {
7142 mp = mc->mc_pg[mc->mc_top];
7144 mc->mc_ki[mc->mc_top] = 0;
7145 return MDB_NOTFOUND;
7147 if (MP_FLAGS(mp) & P_LEAF2) {
7148 nodekey.mv_size = mc->mc_db->md_pad;
7149 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
7151 leaf = NODEPTR(mp, 0);
7152 MDB_GET_KEY2(leaf, nodekey);
7154 rc = mc->mc_dbx->md_cmp(key, &nodekey);
7156 /* Probably happens rarely, but first node on the page
7157 * was the one we wanted.
7159 mc->mc_ki[mc->mc_top] = 0;
7166 unsigned int nkeys = NUMKEYS(mp);
7168 if (MP_FLAGS(mp) & P_LEAF2) {
7169 nodekey.mv_data = LEAF2KEY(mp,
7170 nkeys-1, nodekey.mv_size);
7172 leaf = NODEPTR(mp, nkeys-1);
7173 MDB_GET_KEY2(leaf, nodekey);
7175 rc = mc->mc_dbx->md_cmp(key, &nodekey);
7177 /* last node was the one we wanted */
7178 mc->mc_ki[mc->mc_top] = nkeys-1;
7184 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
7185 /* This is definitely the right page, skip search_page */
7186 if (MP_FLAGS(mp) & P_LEAF2) {
7187 nodekey.mv_data = LEAF2KEY(mp,
7188 mc->mc_ki[mc->mc_top], nodekey.mv_size);
7190 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7191 MDB_GET_KEY2(leaf, nodekey);
7193 rc = mc->mc_dbx->md_cmp(key, &nodekey);
7195 /* current node was the one we wanted */
7202 mc->mc_flags &= ~C_EOF;
7206 /* If any parents have right-sibs, search.
7207 * Otherwise, there's nothing further.
7209 for (i=0; i<mc->mc_top; i++)
7211 NUMKEYS(mc->mc_pg[i])-1)
7213 if (i == mc->mc_top) {
7214 /* There are no other pages */
7215 mc->mc_ki[mc->mc_top] = nkeys;
7216 return MDB_NOTFOUND;
7220 /* There are no other pages */
7221 mc->mc_ki[mc->mc_top] = 0;
7222 if (op == MDB_SET_RANGE && !exactp) {
7226 return MDB_NOTFOUND;
7232 rc = mdb_page_search(mc, key, 0);
7233 if (rc != MDB_SUCCESS)
7236 mp = mc->mc_pg[mc->mc_top];
7237 mdb_cassert(mc, IS_LEAF(mp));
7240 leaf = mdb_node_search(mc, key, exactp);
7241 if (exactp != NULL && !*exactp) {
7242 /* MDB_SET specified and not an exact match. */
7243 return MDB_NOTFOUND;
7247 DPUTS("===> inexact leaf not found, goto sibling");
7248 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
7249 mc->mc_flags |= C_EOF;
7250 return rc; /* no entries matched */
7252 mp = mc->mc_pg[mc->mc_top];
7253 mdb_cassert(mc, IS_LEAF(mp));
7254 leaf = NODEPTR(mp, 0);
7258 mc->mc_flags |= C_INITIALIZED;
7259 mc->mc_flags &= ~C_EOF;
7262 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
7263 key->mv_size = mc->mc_db->md_pad;
7264 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
7269 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7270 mdb_xcursor_init1(mc, leaf);
7271 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
7272 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
7275 if (op == MDB_GET_BOTH) {
7281 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
7282 if (rc != MDB_SUCCESS)
7286 if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
7289 if ((rc = mdb_node_read(mc, leaf, &olddata)) != MDB_SUCCESS)
7291 dcmp = mc->mc_dbx->md_dcmp;
7292 if (NEED_CMP_CLONG(dcmp, olddata.mv_size))
7293 dcmp = mdb_cmp_clong;
7294 rc = dcmp(data, &olddata);
7296 if (op == MDB_GET_BOTH || rc > 0)
7297 return MDB_NOTFOUND;
7304 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
7305 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
7310 /* The key already matches in all other cases */
7311 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
7312 MDB_GET_KEY(leaf, key);
7313 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
7318 /** Move the cursor to the first item in the database. */
7320 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
7325 if (mc->mc_xcursor) {
7326 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
7327 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
7330 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
7331 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
7332 if (rc != MDB_SUCCESS)
7335 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
7337 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
7338 mc->mc_flags |= C_INITIALIZED;
7339 mc->mc_flags &= ~C_EOF;
7341 mc->mc_ki[mc->mc_top] = 0;
7343 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
7345 key->mv_size = mc->mc_db->md_pad;
7346 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
7351 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7352 mdb_xcursor_init1(mc, leaf);
7353 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
7357 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
7361 MDB_GET_KEY(leaf, key);
7365 /** Move the cursor to the last item in the database. */
7367 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
7372 if (mc->mc_xcursor) {
7373 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
7374 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
7377 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
7378 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
7379 if (rc != MDB_SUCCESS)
7382 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
7384 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
7385 mc->mc_flags |= C_INITIALIZED|C_EOF;
7386 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7388 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
7390 key->mv_size = mc->mc_db->md_pad;
7391 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
7396 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7397 mdb_xcursor_init1(mc, leaf);
7398 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
7402 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
7406 MDB_GET_KEY(leaf, key);
7411 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
7416 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
7421 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
7425 case MDB_GET_CURRENT:
7426 if (!(mc->mc_flags & C_INITIALIZED)) {
7429 MDB_page *mp = mc->mc_pg[mc->mc_top];
7430 int nkeys = NUMKEYS(mp);
7431 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
7432 mc->mc_ki[mc->mc_top] = nkeys;
7438 key->mv_size = mc->mc_db->md_pad;
7439 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
7441 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7442 MDB_GET_KEY(leaf, key);
7444 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7445 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
7447 rc = mdb_node_read(mc, leaf, data);
7454 case MDB_GET_BOTH_RANGE:
7459 if (mc->mc_xcursor == NULL) {
7460 rc = MDB_INCOMPATIBLE;
7470 rc = mdb_cursor_set(mc, key, data, op,
7471 op == MDB_SET_RANGE ? NULL : &exact);
7474 case MDB_GET_MULTIPLE:
7475 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
7479 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7480 rc = MDB_INCOMPATIBLE;
7484 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
7485 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
7488 case MDB_NEXT_MULTIPLE:
7493 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7494 rc = MDB_INCOMPATIBLE;
7497 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
7498 if (rc == MDB_SUCCESS) {
7499 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
7502 mx = &mc->mc_xcursor->mx_cursor;
7503 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
7505 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
7506 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
7512 case MDB_PREV_MULTIPLE:
7517 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7518 rc = MDB_INCOMPATIBLE;
7521 if (!(mc->mc_flags & C_INITIALIZED))
7522 rc = mdb_cursor_last(mc, key, data);
7525 if (rc == MDB_SUCCESS) {
7526 MDB_cursor *mx = &mc->mc_xcursor->mx_cursor;
7527 if (mx->mc_flags & C_INITIALIZED) {
7528 rc = mdb_cursor_sibling(mx, 0);
7529 if (rc == MDB_SUCCESS)
7538 case MDB_NEXT_NODUP:
7539 rc = mdb_cursor_next(mc, key, data, op);
7543 case MDB_PREV_NODUP:
7544 rc = mdb_cursor_prev(mc, key, data, op);
7547 rc = mdb_cursor_first(mc, key, data);
7550 mfunc = mdb_cursor_first;
7552 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
7556 if (mc->mc_xcursor == NULL) {
7557 rc = MDB_INCOMPATIBLE;
7560 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top])) {
7561 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
7565 mc->mc_flags &= ~C_EOF;
7567 MDB_node *leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7568 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7569 MDB_GET_KEY(leaf, key);
7570 rc = mdb_node_read(mc, leaf, data);
7574 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
7578 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
7581 rc = mdb_cursor_last(mc, key, data);
7584 mfunc = mdb_cursor_last;
7587 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
7592 if (mc->mc_flags & C_DEL)
7593 mc->mc_flags ^= C_DEL;
7598 /** Touch all the pages in the cursor stack. Set mc_top.
7599 * Makes sure all the pages are writable, before attempting a write operation.
7600 * @param[in] mc The cursor to operate on.
7603 mdb_cursor_touch(MDB_cursor *mc)
7605 int rc = MDB_SUCCESS;
7607 if (mc->mc_dbi >= CORE_DBS && !(*mc->mc_dbflag & (DB_DIRTY|DB_DUPDATA))) {
7608 /* Touch DB record of named DB */
7611 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
7613 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
7614 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
7617 *mc->mc_dbflag |= DB_DIRTY;
7622 rc = mdb_page_touch(mc);
7623 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
7624 mc->mc_top = mc->mc_snum-1;
7629 /** Do not spill pages to disk if txn is getting full, may fail instead */
7630 #define MDB_NOSPILL 0x8000
7633 _mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
7637 MDB_node *leaf = NULL;
7638 MDB_page *fp, *mp, *sub_root = NULL;
7640 MDB_val xdata, *rdata, dkey, olddata;
7642 int do_sub = 0, insert_key, insert_data;
7643 unsigned int mcount = 0, dcount = 0, nospill;
7646 unsigned int nflags;
7649 if (mc == NULL || key == NULL)
7652 env = mc->mc_txn->mt_env;
7654 /* Check this first so counter will always be zero on any
7657 if (flags & MDB_MULTIPLE) {
7658 dcount = data[1].mv_size;
7659 data[1].mv_size = 0;
7660 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
7661 return MDB_INCOMPATIBLE;
7664 nospill = flags & MDB_NOSPILL;
7665 flags &= ~MDB_NOSPILL;
7667 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
7668 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7670 if (key->mv_size-1 >= ENV_MAXKEY(env))
7671 return MDB_BAD_VALSIZE;
7673 #if SIZE_MAX > MAXDATASIZE
7674 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
7675 return MDB_BAD_VALSIZE;
7677 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
7678 return MDB_BAD_VALSIZE;
7681 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
7682 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
7686 if (flags & MDB_CURRENT) {
7687 if (!(mc->mc_flags & C_INITIALIZED))
7690 } else if (mc->mc_db->md_root == P_INVALID) {
7691 /* new database, cursor has nothing to point to */
7694 mc->mc_flags &= ~C_INITIALIZED;
7699 if (flags & MDB_APPEND) {
7701 rc = mdb_cursor_last(mc, &k2, &d2);
7703 rc = mc->mc_dbx->md_cmp(key, &k2);
7706 mc->mc_ki[mc->mc_top]++;
7708 /* new key is <= last key */
7713 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
7715 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
7716 DPRINTF(("duplicate key [%s]", DKEY(key)));
7718 return MDB_KEYEXIST;
7720 if (rc && rc != MDB_NOTFOUND)
7724 if (mc->mc_flags & C_DEL)
7725 mc->mc_flags ^= C_DEL;
7727 /* Cursor is positioned, check for room in the dirty list */
7729 if (flags & MDB_MULTIPLE) {
7731 xdata.mv_size = data->mv_size * dcount;
7735 if ((rc2 = mdb_page_spill(mc, key, rdata)))
7739 if (rc == MDB_NO_ROOT) {
7741 /* new database, write a root leaf page */
7742 DPUTS("allocating new root leaf page");
7743 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
7746 mdb_cursor_push(mc, np);
7747 mc->mc_db->md_root = np->mp_pgno;
7748 mc->mc_db->md_depth++;
7749 *mc->mc_dbflag |= DB_DIRTY;
7750 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
7752 MP_FLAGS(np) |= P_LEAF2;
7753 mc->mc_flags |= C_INITIALIZED;
7755 /* make sure all cursor pages are writable */
7756 rc2 = mdb_cursor_touch(mc);
7761 insert_key = insert_data = rc;
7763 /* The key does not exist */
7764 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
7765 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
7766 LEAFSIZE(key, data) > env->me_nodemax)
7768 /* Too big for a node, insert in sub-DB. Set up an empty
7769 * "old sub-page" for prep_subDB to expand to a full page.
7771 fp_flags = P_LEAF|P_DIRTY;
7773 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
7774 MP_LOWER(fp) = MP_UPPER(fp) = (PAGEHDRSZ-PAGEBASE);
7775 olddata.mv_size = PAGEHDRSZ;
7779 /* there's only a key anyway, so this is a no-op */
7780 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
7782 unsigned int ksize = mc->mc_db->md_pad;
7783 if (key->mv_size != ksize)
7784 return MDB_BAD_VALSIZE;
7785 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
7786 memcpy(ptr, key->mv_data, ksize);
7788 /* if overwriting slot 0 of leaf, need to
7789 * update branch key if there is a parent page
7791 if (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
7792 unsigned short dtop = 1;
7794 /* slot 0 is always an empty key, find real slot */
7795 while (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
7799 if (mc->mc_ki[mc->mc_top])
7800 rc2 = mdb_update_key(mc, key);
7811 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7812 olddata.mv_size = NODEDSZ(leaf);
7813 olddata.mv_data = NODEDATA(leaf);
7816 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
7817 /* Prepare (sub-)page/sub-DB to accept the new item,
7818 * if needed. fp: old sub-page or a header faking
7819 * it. mp: new (sub-)page. offset: growth in page
7820 * size. xdata: node data with new page or DB.
7822 unsigned i, offset = 0;
7823 mp = fp = xdata.mv_data = env->me_pbuf;
7824 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
7826 /* Was a single item before, must convert now */
7827 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7829 /* Just overwrite the current item */
7830 if (flags == MDB_CURRENT)
7832 dcmp = mc->mc_dbx->md_dcmp;
7833 if (NEED_CMP_CLONG(dcmp, olddata.mv_size))
7834 dcmp = mdb_cmp_clong;
7835 /* does data match? */
7836 if (!dcmp(data, &olddata)) {
7837 if (flags & (MDB_NODUPDATA|MDB_APPENDDUP))
7838 return MDB_KEYEXIST;
7843 /* Back up original data item */
7844 dkey.mv_size = olddata.mv_size;
7845 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
7847 /* Make sub-page header for the dup items, with dummy body */
7848 MP_FLAGS(fp) = P_LEAF|P_DIRTY|P_SUBP;
7849 MP_LOWER(fp) = (PAGEHDRSZ-PAGEBASE);
7850 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
7851 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7852 MP_FLAGS(fp) |= P_LEAF2;
7853 fp->mp_pad = data->mv_size;
7854 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
7856 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
7857 (dkey.mv_size & 1) + (data->mv_size & 1);
7859 MP_UPPER(fp) = xdata.mv_size - PAGEBASE;
7860 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
7861 } else if (leaf->mn_flags & F_SUBDATA) {
7862 /* Data is on sub-DB, just store it */
7863 flags |= F_DUPDATA|F_SUBDATA;
7866 /* Data is on sub-page */
7867 fp = olddata.mv_data;
7870 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7871 offset = EVEN(NODESIZE + sizeof(indx_t) +
7875 offset = fp->mp_pad;
7876 if (SIZELEFT(fp) < offset) {
7877 offset *= 4; /* space for 4 more */
7880 /* FALLTHRU */ /* Big enough MDB_DUPFIXED sub-page */
7882 MP_FLAGS(fp) |= P_DIRTY;
7883 COPY_PGNO(MP_PGNO(fp), MP_PGNO(mp));
7884 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
7888 xdata.mv_size = olddata.mv_size + offset;
7891 fp_flags = MP_FLAGS(fp);
7892 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
7893 /* Too big for a sub-page, convert to sub-DB */
7894 fp_flags &= ~P_SUBP;
7896 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7897 fp_flags |= P_LEAF2;
7898 dummy.md_pad = fp->mp_pad;
7899 dummy.md_flags = MDB_DUPFIXED;
7900 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
7901 dummy.md_flags |= MDB_INTEGERKEY;
7907 dummy.md_branch_pages = 0;
7908 dummy.md_leaf_pages = 1;
7909 dummy.md_overflow_pages = 0;
7910 dummy.md_entries = NUMKEYS(fp);
7911 xdata.mv_size = sizeof(MDB_db);
7912 xdata.mv_data = &dummy;
7913 if ((rc = mdb_page_alloc(mc, 1, &mp)))
7915 offset = env->me_psize - olddata.mv_size;
7916 flags |= F_DUPDATA|F_SUBDATA;
7917 dummy.md_root = mp->mp_pgno;
7921 MP_FLAGS(mp) = fp_flags | P_DIRTY;
7922 MP_PAD(mp) = MP_PAD(fp);
7923 MP_LOWER(mp) = MP_LOWER(fp);
7924 MP_UPPER(mp) = MP_UPPER(fp) + offset;
7925 if (fp_flags & P_LEAF2) {
7926 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
7928 memcpy((char *)mp + MP_UPPER(mp) + PAGEBASE, (char *)fp + MP_UPPER(fp) + PAGEBASE,
7929 olddata.mv_size - MP_UPPER(fp) - PAGEBASE);
7930 memcpy((char *)MP_PTRS(mp), (char *)MP_PTRS(fp), NUMKEYS(fp) * sizeof(mp->mp_ptrs[0]));
7931 for (i=0; i<NUMKEYS(fp); i++)
7932 mp->mp_ptrs[i] += offset;
7940 mdb_node_del(mc, 0);
7944 /* LMDB passes F_SUBDATA in 'flags' to write a DB record */
7945 if ((leaf->mn_flags ^ flags) & F_SUBDATA)
7946 return MDB_INCOMPATIBLE;
7947 /* overflow page overwrites need special handling */
7948 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7951 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
7953 memcpy(&pg, olddata.mv_data, sizeof(pg));
7954 if ((rc2 = mdb_page_get(mc, pg, &omp, &level)) != 0)
7956 ovpages = omp->mp_pages;
7958 /* Is the ov page large enough? */
7959 if (ovpages >= dpages) {
7960 if (!(omp->mp_flags & P_DIRTY) &&
7961 (level || (env->me_flags & MDB_WRITEMAP)))
7963 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
7966 level = 0; /* dirty in this txn or clean */
7969 if (omp->mp_flags & P_DIRTY) {
7970 /* yes, overwrite it. Note in this case we don't
7971 * bother to try shrinking the page if the new data
7972 * is smaller than the overflow threshold.
7975 /* It is writable only in a parent txn */
7976 size_t sz = (size_t) env->me_psize * ovpages, off;
7977 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
7983 /* Note - this page is already counted in parent's dirty_room */
7984 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
7985 mdb_cassert(mc, rc2 == 0);
7986 /* Currently we make the page look as with put() in the
7987 * parent txn, in case the user peeks at MDB_RESERVEd
7988 * or unused parts. Some users treat ovpages specially.
7990 if (!(flags & MDB_RESERVE)) {
7991 /* Skip the part where LMDB will put *data.
7992 * Copy end of page, adjusting alignment so
7993 * compiler may copy words instead of bytes.
7995 off = (PAGEHDRSZ + data->mv_size) & -(int)sizeof(size_t);
7996 memcpy((size_t *)((char *)np + off),
7997 (size_t *)((char *)omp + off), sz - off);
8000 memcpy(np, omp, sz); /* Copy beginning of page */
8003 SETDSZ(leaf, data->mv_size);
8004 if (F_ISSET(flags, MDB_RESERVE))
8005 data->mv_data = METADATA(omp);
8007 memcpy(METADATA(omp), data->mv_data, data->mv_size);
8011 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
8013 } else if (data->mv_size == olddata.mv_size) {
8014 /* same size, just replace it. Note that we could
8015 * also reuse this node if the new data is smaller,
8016 * but instead we opt to shrink the node in that case.
8018 if (F_ISSET(flags, MDB_RESERVE))
8019 data->mv_data = olddata.mv_data;
8020 else if (!(mc->mc_flags & C_SUB))
8021 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
8023 if (key->mv_size != NODEKSZ(leaf))
8025 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
8031 mdb_node_del(mc, 0);
8037 nflags = flags & NODE_ADD_FLAGS;
8038 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
8039 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
8040 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
8041 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
8043 nflags |= MDB_SPLIT_REPLACE;
8044 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
8046 /* There is room already in this leaf page. */
8047 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
8049 /* Adjust other cursors pointing to mp */
8050 MDB_cursor *m2, *m3;
8051 MDB_dbi dbi = mc->mc_dbi;
8052 unsigned i = mc->mc_top;
8053 MDB_page *mp = mc->mc_pg[i];
8055 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8056 if (mc->mc_flags & C_SUB)
8057 m3 = &m2->mc_xcursor->mx_cursor;
8060 if (m3 == mc || m3->mc_snum < mc->mc_snum || m3->mc_pg[i] != mp) continue;
8061 if (m3->mc_ki[i] >= mc->mc_ki[i] && insert_key) {
8064 XCURSOR_REFRESH(m3, i, mp);
8069 if (rc == MDB_SUCCESS) {
8070 /* Now store the actual data in the child DB. Note that we're
8071 * storing the user data in the keys field, so there are strict
8072 * size limits on dupdata. The actual data fields of the child
8073 * DB are all zero size.
8076 int xflags, new_dupdata;
8081 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
8082 if ((flags & (MDB_CURRENT|MDB_APPENDDUP)) == MDB_CURRENT) {
8083 xflags = MDB_CURRENT|MDB_NOSPILL;
8085 mdb_xcursor_init1(mc, leaf);
8086 xflags = (flags & MDB_NODUPDATA) ?
8087 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
8090 mc->mc_xcursor->mx_cursor.mc_pg[0] = sub_root;
8091 new_dupdata = (int)dkey.mv_size;
8092 /* converted, write the original data first */
8094 rc = _mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
8097 /* we've done our job */
8100 if (!(leaf->mn_flags & F_SUBDATA) || sub_root) {
8101 /* Adjust other cursors pointing to mp */
8103 MDB_xcursor *mx = mc->mc_xcursor;
8104 unsigned i = mc->mc_top;
8105 MDB_page *mp = mc->mc_pg[i];
8107 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
8108 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
8109 if (!(m2->mc_flags & C_INITIALIZED)) continue;
8110 if (m2->mc_pg[i] == mp) {
8111 if (m2->mc_ki[i] == mc->mc_ki[i]) {
8112 mdb_xcursor_init2(m2, mx, new_dupdata);
8113 } else if (!insert_key) {
8114 XCURSOR_REFRESH(m2, i, mp);
8119 ecount = mc->mc_xcursor->mx_db.md_entries;
8120 if (flags & MDB_APPENDDUP)
8121 xflags |= MDB_APPEND;
8122 rc = _mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
8123 if (flags & F_SUBDATA) {
8124 void *db = NODEDATA(leaf);
8125 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
8127 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
8129 /* Increment count unless we just replaced an existing item. */
8131 mc->mc_db->md_entries++;
8133 /* Invalidate txn if we created an empty sub-DB */
8136 /* If we succeeded and the key didn't exist before,
8137 * make sure the cursor is marked valid.
8139 mc->mc_flags |= C_INITIALIZED;
8141 if (flags & MDB_MULTIPLE) {
8144 /* let caller know how many succeeded, if any */
8145 data[1].mv_size = mcount;
8146 if (mcount < dcount) {
8147 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
8148 insert_key = insert_data = 0;
8155 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
8158 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8163 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
8168 int rc = _mdb_cursor_put(mc, key, data, flags);
8169 MDB_TRACE(("%p, %"Z"u[%s], %"Z"u%s, %u",
8170 mc, key ? key->mv_size:0, DKEY(key), data ? data->mv_size:0,
8171 data ? mdb_dval(mc->mc_txn, mc->mc_dbi, data, dbuf):"", flags));
8176 _mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
8182 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
8183 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
8185 if (!(mc->mc_flags & C_INITIALIZED))
8188 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
8189 return MDB_NOTFOUND;
8191 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
8194 rc = mdb_cursor_touch(mc);
8198 mp = mc->mc_pg[mc->mc_top];
8200 return MDB_CORRUPTED;
8203 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
8205 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
8206 if (flags & MDB_NODUPDATA) {
8207 /* mdb_cursor_del0() will subtract the final entry */
8208 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
8209 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
8211 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
8212 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
8214 rc = _mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
8217 /* If sub-DB still has entries, we're done */
8218 if (mc->mc_xcursor->mx_db.md_entries) {
8219 if (leaf->mn_flags & F_SUBDATA) {
8220 /* update subDB info */
8221 void *db = NODEDATA(leaf);
8222 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
8225 /* shrink fake page */
8226 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
8227 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
8228 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
8229 /* fix other sub-DB cursors pointed at fake pages on this page */
8230 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
8231 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
8232 if (!(m2->mc_flags & C_INITIALIZED)) continue;
8233 if (m2->mc_pg[mc->mc_top] == mp) {
8234 XCURSOR_REFRESH(m2, mc->mc_top, mp);
8238 mc->mc_db->md_entries--;
8241 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
8243 /* otherwise fall thru and delete the sub-DB */
8246 if (leaf->mn_flags & F_SUBDATA) {
8247 /* add all the child DB's pages to the free list */
8248 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
8253 /* LMDB passes F_SUBDATA in 'flags' to delete a DB record */
8254 else if ((leaf->mn_flags ^ flags) & F_SUBDATA) {
8255 rc = MDB_INCOMPATIBLE;
8259 /* add overflow pages to free list */
8260 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
8264 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
8265 if ((rc = mdb_page_get(mc, pg, &omp, NULL)) ||
8266 (rc = mdb_ovpage_free(mc, omp)))
8271 return mdb_cursor_del0(mc);
8274 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8279 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
8281 MDB_TRACE(("%p, %u",
8283 return _mdb_cursor_del(mc, flags);
8286 /** Allocate and initialize new pages for a database.
8287 * Set #MDB_TXN_ERROR on failure.
8288 * @param[in] mc a cursor on the database being added to.
8289 * @param[in] flags flags defining what type of page is being allocated.
8290 * @param[in] num the number of pages to allocate. This is usually 1,
8291 * unless allocating overflow pages for a large record.
8292 * @param[out] mp Address of a page, or NULL on failure.
8293 * @return 0 on success, non-zero on failure.
8296 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
8301 if ((rc = mdb_page_alloc(mc, num, &np)))
8303 DPRINTF(("allocated new mpage %"Yu", page size %u",
8304 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
8305 np->mp_flags = flags | P_DIRTY;
8306 np->mp_lower = (PAGEHDRSZ-PAGEBASE);
8307 np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
8310 mc->mc_db->md_branch_pages++;
8311 else if (IS_LEAF(np))
8312 mc->mc_db->md_leaf_pages++;
8313 else if (IS_OVERFLOW(np)) {
8314 mc->mc_db->md_overflow_pages += num;
8322 /** Calculate the size of a leaf node.
8323 * The size depends on the environment's page size; if a data item
8324 * is too large it will be put onto an overflow page and the node
8325 * size will only include the key and not the data. Sizes are always
8326 * rounded up to an even number of bytes, to guarantee 2-byte alignment
8327 * of the #MDB_node headers.
8328 * @param[in] env The environment handle.
8329 * @param[in] key The key for the node.
8330 * @param[in] data The data for the node.
8331 * @return The number of bytes needed to store the node.
8334 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
8338 sz = LEAFSIZE(key, data);
8339 if (sz > env->me_nodemax) {
8340 /* put on overflow page */
8341 sz -= data->mv_size - sizeof(pgno_t);
8344 return EVEN(sz + sizeof(indx_t));
8347 /** Calculate the size of a branch node.
8348 * The size should depend on the environment's page size but since
8349 * we currently don't support spilling large keys onto overflow
8350 * pages, it's simply the size of the #MDB_node header plus the
8351 * size of the key. Sizes are always rounded up to an even number
8352 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
8353 * @param[in] env The environment handle.
8354 * @param[in] key The key for the node.
8355 * @return The number of bytes needed to store the node.
8358 mdb_branch_size(MDB_env *env, MDB_val *key)
8363 if (sz > env->me_nodemax) {
8364 /* put on overflow page */
8365 /* not implemented */
8366 /* sz -= key->size - sizeof(pgno_t); */
8369 return sz + sizeof(indx_t);
8372 /** Add a node to the page pointed to by the cursor.
8373 * Set #MDB_TXN_ERROR on failure.
8374 * @param[in] mc The cursor for this operation.
8375 * @param[in] indx The index on the page where the new node should be added.
8376 * @param[in] key The key for the new node.
8377 * @param[in] data The data for the new node, if any.
8378 * @param[in] pgno The page number, if adding a branch node.
8379 * @param[in] flags Flags for the node.
8380 * @return 0 on success, non-zero on failure. Possible errors are:
8382 * <li>ENOMEM - failed to allocate overflow pages for the node.
8383 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
8384 * should never happen since all callers already calculate the
8385 * page's free space before calling this function.
8389 mdb_node_add(MDB_cursor *mc, indx_t indx,
8390 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
8393 size_t node_size = NODESIZE;
8397 MDB_page *mp = mc->mc_pg[mc->mc_top];
8398 MDB_page *ofp = NULL; /* overflow page */
8402 mdb_cassert(mc, MP_UPPER(mp) >= MP_LOWER(mp));
8404 DPRINTF(("add to %s %spage %"Yu" index %i, data size %"Z"u key size %"Z"u [%s]",
8405 IS_LEAF(mp) ? "leaf" : "branch",
8406 IS_SUBP(mp) ? "sub-" : "",
8407 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
8408 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
8411 /* Move higher keys up one slot. */
8412 int ksize = mc->mc_db->md_pad, dif;
8413 char *ptr = LEAF2KEY(mp, indx, ksize);
8414 dif = NUMKEYS(mp) - indx;
8416 memmove(ptr+ksize, ptr, dif*ksize);
8417 /* insert new key */
8418 memcpy(ptr, key->mv_data, ksize);
8420 /* Just using these for counting */
8421 MP_LOWER(mp) += sizeof(indx_t);
8422 MP_UPPER(mp) -= ksize - sizeof(indx_t);
8426 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
8428 node_size += key->mv_size;
8430 mdb_cassert(mc, key && data);
8431 if (F_ISSET(flags, F_BIGDATA)) {
8432 /* Data already on overflow page. */
8433 node_size += sizeof(pgno_t);
8434 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
8435 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
8437 /* Put data on overflow page. */
8438 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
8439 data->mv_size, node_size+data->mv_size));
8440 node_size = EVEN(node_size + sizeof(pgno_t));
8441 if ((ssize_t)node_size > room)
8443 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
8445 DPRINTF(("allocated overflow page %"Yu, ofp->mp_pgno));
8449 node_size += data->mv_size;
8452 node_size = EVEN(node_size);
8453 if ((ssize_t)node_size > room)
8457 /* Move higher pointers up one slot. */
8458 for (i = NUMKEYS(mp); i > indx; i--)
8459 MP_PTRS(mp)[i] = MP_PTRS(mp)[i - 1];
8461 /* Adjust free space offsets. */
8462 ofs = MP_UPPER(mp) - node_size;
8463 mdb_cassert(mc, ofs >= MP_LOWER(mp) + sizeof(indx_t));
8464 MP_PTRS(mp)[indx] = ofs;
8466 MP_LOWER(mp) += sizeof(indx_t);
8468 /* Write the node data. */
8469 node = NODEPTR(mp, indx);
8470 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
8471 node->mn_flags = flags;
8473 SETDSZ(node,data->mv_size);
8478 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
8481 ndata = NODEDATA(node);
8483 if (F_ISSET(flags, F_BIGDATA))
8484 memcpy(ndata, data->mv_data, sizeof(pgno_t));
8485 else if (F_ISSET(flags, MDB_RESERVE))
8486 data->mv_data = ndata;
8488 memcpy(ndata, data->mv_data, data->mv_size);
8490 memcpy(ndata, &ofp->mp_pgno, sizeof(pgno_t));
8491 ndata = METADATA(ofp);
8492 if (F_ISSET(flags, MDB_RESERVE))
8493 data->mv_data = ndata;
8495 memcpy(ndata, data->mv_data, data->mv_size);
8502 DPRINTF(("not enough room in page %"Yu", got %u ptrs",
8503 mdb_dbg_pgno(mp), NUMKEYS(mp)));
8504 DPRINTF(("upper-lower = %u - %u = %"Z"d", MP_UPPER(mp),MP_LOWER(mp),room));
8505 DPRINTF(("node size = %"Z"u", node_size));
8506 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8507 return MDB_PAGE_FULL;
8510 /** Delete the specified node from a page.
8511 * @param[in] mc Cursor pointing to the node to delete.
8512 * @param[in] ksize The size of a node. Only used if the page is
8513 * part of a #MDB_DUPFIXED database.
8516 mdb_node_del(MDB_cursor *mc, int ksize)
8518 MDB_page *mp = mc->mc_pg[mc->mc_top];
8519 indx_t indx = mc->mc_ki[mc->mc_top];
8521 indx_t i, j, numkeys, ptr;
8525 DPRINTF(("delete node %u on %s page %"Yu, indx,
8526 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
8527 numkeys = NUMKEYS(mp);
8528 mdb_cassert(mc, indx < numkeys);
8531 int x = numkeys - 1 - indx;
8532 base = LEAF2KEY(mp, indx, ksize);
8534 memmove(base, base + ksize, x * ksize);
8535 MP_LOWER(mp) -= sizeof(indx_t);
8536 MP_UPPER(mp) += ksize - sizeof(indx_t);
8540 node = NODEPTR(mp, indx);
8541 sz = NODESIZE + node->mn_ksize;
8543 if (F_ISSET(node->mn_flags, F_BIGDATA))
8544 sz += sizeof(pgno_t);
8546 sz += NODEDSZ(node);
8550 ptr = MP_PTRS(mp)[indx];
8551 for (i = j = 0; i < numkeys; i++) {
8553 MP_PTRS(mp)[j] = MP_PTRS(mp)[i];
8554 if (MP_PTRS(mp)[i] < ptr)
8555 MP_PTRS(mp)[j] += sz;
8560 base = (char *)mp + MP_UPPER(mp) + PAGEBASE;
8561 memmove(base + sz, base, ptr - MP_UPPER(mp));
8563 MP_LOWER(mp) -= sizeof(indx_t);
8567 /** Compact the main page after deleting a node on a subpage.
8568 * @param[in] mp The main page to operate on.
8569 * @param[in] indx The index of the subpage on the main page.
8572 mdb_node_shrink(MDB_page *mp, indx_t indx)
8577 indx_t delta, nsize, len, ptr;
8580 node = NODEPTR(mp, indx);
8581 sp = (MDB_page *)NODEDATA(node);
8582 delta = SIZELEFT(sp);
8583 nsize = NODEDSZ(node) - delta;
8585 /* Prepare to shift upward, set len = length(subpage part to shift) */
8589 return; /* do not make the node uneven-sized */
8591 xp = (MDB_page *)((char *)sp + delta); /* destination subpage */
8592 for (i = NUMKEYS(sp); --i >= 0; )
8593 MP_PTRS(xp)[i] = MP_PTRS(sp)[i] - delta;
8596 MP_UPPER(sp) = MP_LOWER(sp);
8597 COPY_PGNO(MP_PGNO(sp), mp->mp_pgno);
8598 SETDSZ(node, nsize);
8600 /* Shift <lower nodes...initial part of subpage> upward */
8601 base = (char *)mp + mp->mp_upper + PAGEBASE;
8602 memmove(base + delta, base, (char *)sp + len - base);
8604 ptr = mp->mp_ptrs[indx];
8605 for (i = NUMKEYS(mp); --i >= 0; ) {
8606 if (mp->mp_ptrs[i] <= ptr)
8607 mp->mp_ptrs[i] += delta;
8609 mp->mp_upper += delta;
8612 /** Initial setup of a sorted-dups cursor.
8613 * Sorted duplicates are implemented as a sub-database for the given key.
8614 * The duplicate data items are actually keys of the sub-database.
8615 * Operations on the duplicate data items are performed using a sub-cursor
8616 * initialized when the sub-database is first accessed. This function does
8617 * the preliminary setup of the sub-cursor, filling in the fields that
8618 * depend only on the parent DB.
8619 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
8622 mdb_xcursor_init0(MDB_cursor *mc)
8624 MDB_xcursor *mx = mc->mc_xcursor;
8626 mx->mx_cursor.mc_xcursor = NULL;
8627 mx->mx_cursor.mc_txn = mc->mc_txn;
8628 mx->mx_cursor.mc_db = &mx->mx_db;
8629 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
8630 mx->mx_cursor.mc_dbi = mc->mc_dbi;
8631 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
8632 mx->mx_cursor.mc_snum = 0;
8633 mx->mx_cursor.mc_top = 0;
8634 MC_SET_OVPG(&mx->mx_cursor, NULL);
8635 mx->mx_cursor.mc_flags = C_SUB | (mc->mc_flags & (C_ORIG_RDONLY|C_WRITEMAP));
8636 mx->mx_dbx.md_name.mv_size = 0;
8637 mx->mx_dbx.md_name.mv_data = NULL;
8638 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
8639 mx->mx_dbx.md_dcmp = NULL;
8640 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
8643 /** Final setup of a sorted-dups cursor.
8644 * Sets up the fields that depend on the data from the main cursor.
8645 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
8646 * @param[in] node The data containing the #MDB_db record for the
8647 * sorted-dup database.
8650 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
8652 MDB_xcursor *mx = mc->mc_xcursor;
8654 mx->mx_cursor.mc_flags &= C_SUB|C_ORIG_RDONLY|C_WRITEMAP;
8655 if (node->mn_flags & F_SUBDATA) {
8656 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
8657 mx->mx_cursor.mc_pg[0] = 0;
8658 mx->mx_cursor.mc_snum = 0;
8659 mx->mx_cursor.mc_top = 0;
8661 MDB_page *fp = NODEDATA(node);
8662 mx->mx_db.md_pad = 0;
8663 mx->mx_db.md_flags = 0;
8664 mx->mx_db.md_depth = 1;
8665 mx->mx_db.md_branch_pages = 0;
8666 mx->mx_db.md_leaf_pages = 1;
8667 mx->mx_db.md_overflow_pages = 0;
8668 mx->mx_db.md_entries = NUMKEYS(fp);
8669 COPY_PGNO(mx->mx_db.md_root, MP_PGNO(fp));
8670 mx->mx_cursor.mc_snum = 1;
8671 mx->mx_cursor.mc_top = 0;
8672 mx->mx_cursor.mc_flags |= C_INITIALIZED;
8673 mx->mx_cursor.mc_pg[0] = fp;
8674 mx->mx_cursor.mc_ki[0] = 0;
8675 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
8676 mx->mx_db.md_flags = MDB_DUPFIXED;
8677 mx->mx_db.md_pad = fp->mp_pad;
8678 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
8679 mx->mx_db.md_flags |= MDB_INTEGERKEY;
8682 DPRINTF(("Sub-db -%u root page %"Yu, mx->mx_cursor.mc_dbi,
8683 mx->mx_db.md_root));
8684 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DUPDATA;
8685 if (NEED_CMP_CLONG(mx->mx_dbx.md_cmp, mx->mx_db.md_pad))
8686 mx->mx_dbx.md_cmp = mdb_cmp_clong;
8690 /** Fixup a sorted-dups cursor due to underlying update.
8691 * Sets up some fields that depend on the data from the main cursor.
8692 * Almost the same as init1, but skips initialization steps if the
8693 * xcursor had already been used.
8694 * @param[in] mc The main cursor whose sorted-dups cursor is to be fixed up.
8695 * @param[in] src_mx The xcursor of an up-to-date cursor.
8696 * @param[in] new_dupdata True if converting from a non-#F_DUPDATA item.
8699 mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int new_dupdata)
8701 MDB_xcursor *mx = mc->mc_xcursor;
8704 mx->mx_cursor.mc_snum = 1;
8705 mx->mx_cursor.mc_top = 0;
8706 mx->mx_cursor.mc_flags |= C_INITIALIZED;
8707 mx->mx_cursor.mc_ki[0] = 0;
8708 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DUPDATA;
8709 #if UINT_MAX < MDB_SIZE_MAX /* matches mdb_xcursor_init1:NEED_CMP_CLONG() */
8710 mx->mx_dbx.md_cmp = src_mx->mx_dbx.md_cmp;
8712 } else if (!(mx->mx_cursor.mc_flags & C_INITIALIZED)) {
8715 mx->mx_db = src_mx->mx_db;
8716 mx->mx_cursor.mc_pg[0] = src_mx->mx_cursor.mc_pg[0];
8717 DPRINTF(("Sub-db -%u root page %"Yu, mx->mx_cursor.mc_dbi,
8718 mx->mx_db.md_root));
8721 /** Initialize a cursor for a given transaction and database. */
8723 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
8726 mc->mc_backup = NULL;
8729 mc->mc_db = &txn->mt_dbs[dbi];
8730 mc->mc_dbx = &txn->mt_dbxs[dbi];
8731 mc->mc_dbflag = &txn->mt_dbflags[dbi];
8736 MC_SET_OVPG(mc, NULL);
8737 mc->mc_flags = txn->mt_flags & (C_ORIG_RDONLY|C_WRITEMAP);
8738 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
8739 mdb_tassert(txn, mx != NULL);
8740 mc->mc_xcursor = mx;
8741 mdb_xcursor_init0(mc);
8743 mc->mc_xcursor = NULL;
8745 if (*mc->mc_dbflag & DB_STALE) {
8746 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
8751 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
8754 size_t size = sizeof(MDB_cursor);
8756 if (!ret || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
8759 if (txn->mt_flags & MDB_TXN_BLOCKED)
8762 if (dbi == FREE_DBI && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
8765 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
8766 size += sizeof(MDB_xcursor);
8768 if ((mc = malloc(size)) != NULL) {
8769 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
8770 if (txn->mt_cursors) {
8771 mc->mc_next = txn->mt_cursors[dbi];
8772 txn->mt_cursors[dbi] = mc;
8773 mc->mc_flags |= C_UNTRACK;
8779 MDB_TRACE(("%p, %u = %p", txn, dbi, mc));
8786 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
8788 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi, DB_VALID))
8791 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
8794 if (txn->mt_flags & MDB_TXN_BLOCKED)
8797 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
8801 /* Return the count of duplicate data items for the current key */
8803 mdb_cursor_count(MDB_cursor *mc, mdb_size_t *countp)
8807 if (mc == NULL || countp == NULL)
8810 if (mc->mc_xcursor == NULL)
8811 return MDB_INCOMPATIBLE;
8813 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
8816 if (!(mc->mc_flags & C_INITIALIZED))
8820 return MDB_NOTFOUND;
8822 if (mc->mc_flags & C_EOF) {
8823 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
8824 return MDB_NOTFOUND;
8825 mc->mc_flags ^= C_EOF;
8828 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
8829 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
8832 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
8835 *countp = mc->mc_xcursor->mx_db.md_entries;
8841 mdb_cursor_close(MDB_cursor *mc)
8843 MDB_TRACE(("%p", mc));
8845 MDB_CURSOR_UNREF(mc, 0);
8847 if (mc && !mc->mc_backup) {
8848 /* Remove from txn, if tracked.
8849 * A read-only txn (!C_UNTRACK) may have been freed already,
8850 * so do not peek inside it. Only write txns track cursors.
8852 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
8853 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
8854 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
8856 *prev = mc->mc_next;
8863 mdb_cursor_txn(MDB_cursor *mc)
8865 if (!mc) return NULL;
8870 mdb_cursor_dbi(MDB_cursor *mc)
8875 /** Replace the key for a branch node with a new key.
8876 * Set #MDB_TXN_ERROR on failure.
8877 * @param[in] mc Cursor pointing to the node to operate on.
8878 * @param[in] key The new key to use.
8879 * @return 0 on success, non-zero on failure.
8882 mdb_update_key(MDB_cursor *mc, MDB_val *key)
8888 int delta, ksize, oksize;
8889 indx_t ptr, i, numkeys, indx;
8892 indx = mc->mc_ki[mc->mc_top];
8893 mp = mc->mc_pg[mc->mc_top];
8894 node = NODEPTR(mp, indx);
8895 ptr = mp->mp_ptrs[indx];
8899 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
8900 k2.mv_data = NODEKEY(node);
8901 k2.mv_size = node->mn_ksize;
8902 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Yu,
8904 mdb_dkey(&k2, kbuf2),
8910 /* Sizes must be 2-byte aligned. */
8911 ksize = EVEN(key->mv_size);
8912 oksize = EVEN(node->mn_ksize);
8913 delta = ksize - oksize;
8915 /* Shift node contents if EVEN(key length) changed. */
8917 if (delta > 0 && SIZELEFT(mp) < delta) {
8919 /* not enough space left, do a delete and split */
8920 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
8921 pgno = NODEPGNO(node);
8922 mdb_node_del(mc, 0);
8923 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
8926 numkeys = NUMKEYS(mp);
8927 for (i = 0; i < numkeys; i++) {
8928 if (mp->mp_ptrs[i] <= ptr)
8929 mp->mp_ptrs[i] -= delta;
8932 base = (char *)mp + mp->mp_upper + PAGEBASE;
8933 len = ptr - mp->mp_upper + NODESIZE;
8934 memmove(base - delta, base, len);
8935 mp->mp_upper -= delta;
8937 node = NODEPTR(mp, indx);
8940 /* But even if no shift was needed, update ksize */
8941 if (node->mn_ksize != key->mv_size)
8942 node->mn_ksize = key->mv_size;
8945 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
8951 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
8953 /** Perform \b act while tracking temporary cursor \b mn */
8954 #define WITH_CURSOR_TRACKING(mn, act) do { \
8955 MDB_cursor dummy, *tracked, **tp = &(mn).mc_txn->mt_cursors[mn.mc_dbi]; \
8956 if ((mn).mc_flags & C_SUB) { \
8957 dummy.mc_flags = C_INITIALIZED; \
8958 dummy.mc_xcursor = (MDB_xcursor *)&(mn); \
8963 tracked->mc_next = *tp; \
8966 *tp = tracked->mc_next; \
8969 /** Move a node from csrc to cdst.
8972 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft)
8979 unsigned short flags;
8983 /* Mark src and dst as dirty. */
8984 if ((rc = mdb_page_touch(csrc)) ||
8985 (rc = mdb_page_touch(cdst)))
8988 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8989 key.mv_size = csrc->mc_db->md_pad;
8990 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
8992 data.mv_data = NULL;
8996 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
8997 mdb_cassert(csrc, !((size_t)srcnode & 1));
8998 srcpg = NODEPGNO(srcnode);
8999 flags = srcnode->mn_flags;
9000 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
9001 unsigned int snum = csrc->mc_snum;
9003 /* must find the lowest key below src */
9004 rc = mdb_page_search_lowest(csrc);
9007 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
9008 key.mv_size = csrc->mc_db->md_pad;
9009 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
9011 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
9012 key.mv_size = NODEKSZ(s2);
9013 key.mv_data = NODEKEY(s2);
9015 csrc->mc_snum = snum--;
9016 csrc->mc_top = snum;
9018 key.mv_size = NODEKSZ(srcnode);
9019 key.mv_data = NODEKEY(srcnode);
9021 data.mv_size = NODEDSZ(srcnode);
9022 data.mv_data = NODEDATA(srcnode);
9024 mn.mc_xcursor = NULL;
9025 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
9026 unsigned int snum = cdst->mc_snum;
9029 /* must find the lowest key below dst */
9030 mdb_cursor_copy(cdst, &mn);
9031 rc = mdb_page_search_lowest(&mn);
9034 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
9035 bkey.mv_size = mn.mc_db->md_pad;
9036 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
9038 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
9039 bkey.mv_size = NODEKSZ(s2);
9040 bkey.mv_data = NODEKEY(s2);
9042 mn.mc_snum = snum--;
9045 rc = mdb_update_key(&mn, &bkey);
9050 DPRINTF(("moving %s node %u [%s] on page %"Yu" to node %u on page %"Yu,
9051 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
9052 csrc->mc_ki[csrc->mc_top],
9054 csrc->mc_pg[csrc->mc_top]->mp_pgno,
9055 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
9057 /* Add the node to the destination page.
9059 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
9060 if (rc != MDB_SUCCESS)
9063 /* Delete the node from the source page.
9065 mdb_node_del(csrc, key.mv_size);
9068 /* Adjust other cursors pointing to mp */
9069 MDB_cursor *m2, *m3;
9070 MDB_dbi dbi = csrc->mc_dbi;
9071 MDB_page *mpd, *mps;
9073 mps = csrc->mc_pg[csrc->mc_top];
9074 /* If we're adding on the left, bump others up */
9076 mpd = cdst->mc_pg[csrc->mc_top];
9077 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9078 if (csrc->mc_flags & C_SUB)
9079 m3 = &m2->mc_xcursor->mx_cursor;
9082 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
9085 m3->mc_pg[csrc->mc_top] == mpd &&
9086 m3->mc_ki[csrc->mc_top] >= cdst->mc_ki[csrc->mc_top]) {
9087 m3->mc_ki[csrc->mc_top]++;
9090 m3->mc_pg[csrc->mc_top] == mps &&
9091 m3->mc_ki[csrc->mc_top] == csrc->mc_ki[csrc->mc_top]) {
9092 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
9093 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
9094 m3->mc_ki[csrc->mc_top-1]++;
9097 XCURSOR_REFRESH(m3, csrc->mc_top, m3->mc_pg[csrc->mc_top]);
9100 /* Adding on the right, bump others down */
9102 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9103 if (csrc->mc_flags & C_SUB)
9104 m3 = &m2->mc_xcursor->mx_cursor;
9107 if (m3 == csrc) continue;
9108 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
9110 if (m3->mc_pg[csrc->mc_top] == mps) {
9111 if (!m3->mc_ki[csrc->mc_top]) {
9112 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
9113 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
9114 m3->mc_ki[csrc->mc_top-1]--;
9116 m3->mc_ki[csrc->mc_top]--;
9119 XCURSOR_REFRESH(m3, csrc->mc_top, m3->mc_pg[csrc->mc_top]);
9125 /* Update the parent separators.
9127 if (csrc->mc_ki[csrc->mc_top] == 0) {
9128 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
9129 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
9130 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
9132 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
9133 key.mv_size = NODEKSZ(srcnode);
9134 key.mv_data = NODEKEY(srcnode);
9136 DPRINTF(("update separator for source page %"Yu" to [%s]",
9137 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
9138 mdb_cursor_copy(csrc, &mn);
9141 /* We want mdb_rebalance to find mn when doing fixups */
9142 WITH_CURSOR_TRACKING(mn,
9143 rc = mdb_update_key(&mn, &key));
9147 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
9149 indx_t ix = csrc->mc_ki[csrc->mc_top];
9150 nullkey.mv_size = 0;
9151 csrc->mc_ki[csrc->mc_top] = 0;
9152 rc = mdb_update_key(csrc, &nullkey);
9153 csrc->mc_ki[csrc->mc_top] = ix;
9154 mdb_cassert(csrc, rc == MDB_SUCCESS);
9158 if (cdst->mc_ki[cdst->mc_top] == 0) {
9159 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
9160 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
9161 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
9163 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
9164 key.mv_size = NODEKSZ(srcnode);
9165 key.mv_data = NODEKEY(srcnode);
9167 DPRINTF(("update separator for destination page %"Yu" to [%s]",
9168 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
9169 mdb_cursor_copy(cdst, &mn);
9172 /* We want mdb_rebalance to find mn when doing fixups */
9173 WITH_CURSOR_TRACKING(mn,
9174 rc = mdb_update_key(&mn, &key));
9178 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
9180 indx_t ix = cdst->mc_ki[cdst->mc_top];
9181 nullkey.mv_size = 0;
9182 cdst->mc_ki[cdst->mc_top] = 0;
9183 rc = mdb_update_key(cdst, &nullkey);
9184 cdst->mc_ki[cdst->mc_top] = ix;
9185 mdb_cassert(cdst, rc == MDB_SUCCESS);
9192 /** Merge one page into another.
9193 * The nodes from the page pointed to by \b csrc will
9194 * be copied to the page pointed to by \b cdst and then
9195 * the \b csrc page will be freed.
9196 * @param[in] csrc Cursor pointing to the source page.
9197 * @param[in] cdst Cursor pointing to the destination page.
9198 * @return 0 on success, non-zero on failure.
9201 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
9203 MDB_page *psrc, *pdst;
9210 psrc = csrc->mc_pg[csrc->mc_top];
9211 pdst = cdst->mc_pg[cdst->mc_top];
9213 DPRINTF(("merging page %"Yu" into %"Yu, psrc->mp_pgno, pdst->mp_pgno));
9215 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
9216 mdb_cassert(csrc, cdst->mc_snum > 1);
9218 /* Mark dst as dirty. */
9219 if ((rc = mdb_page_touch(cdst)))
9222 /* get dst page again now that we've touched it. */
9223 pdst = cdst->mc_pg[cdst->mc_top];
9225 /* Move all nodes from src to dst.
9227 j = nkeys = NUMKEYS(pdst);
9228 if (IS_LEAF2(psrc)) {
9229 key.mv_size = csrc->mc_db->md_pad;
9230 key.mv_data = METADATA(psrc);
9231 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
9232 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
9233 if (rc != MDB_SUCCESS)
9235 key.mv_data = (char *)key.mv_data + key.mv_size;
9238 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
9239 srcnode = NODEPTR(psrc, i);
9240 if (i == 0 && IS_BRANCH(psrc)) {
9243 mdb_cursor_copy(csrc, &mn);
9244 mn.mc_xcursor = NULL;
9245 /* must find the lowest key below src */
9246 rc = mdb_page_search_lowest(&mn);
9249 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
9250 key.mv_size = mn.mc_db->md_pad;
9251 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
9253 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
9254 key.mv_size = NODEKSZ(s2);
9255 key.mv_data = NODEKEY(s2);
9258 key.mv_size = srcnode->mn_ksize;
9259 key.mv_data = NODEKEY(srcnode);
9262 data.mv_size = NODEDSZ(srcnode);
9263 data.mv_data = NODEDATA(srcnode);
9264 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
9265 if (rc != MDB_SUCCESS)
9270 DPRINTF(("dst page %"Yu" now has %u keys (%.1f%% filled)",
9271 pdst->mp_pgno, NUMKEYS(pdst),
9272 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
9274 /* Unlink the src page from parent and add to free list.
9277 mdb_node_del(csrc, 0);
9278 if (csrc->mc_ki[csrc->mc_top] == 0) {
9280 rc = mdb_update_key(csrc, &key);
9288 psrc = csrc->mc_pg[csrc->mc_top];
9289 /* If not operating on FreeDB, allow this page to be reused
9290 * in this txn. Otherwise just add to free list.
9292 rc = mdb_page_loose(csrc, psrc);
9296 csrc->mc_db->md_leaf_pages--;
9298 csrc->mc_db->md_branch_pages--;
9300 /* Adjust other cursors pointing to mp */
9301 MDB_cursor *m2, *m3;
9302 MDB_dbi dbi = csrc->mc_dbi;
9303 unsigned int top = csrc->mc_top;
9305 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9306 if (csrc->mc_flags & C_SUB)
9307 m3 = &m2->mc_xcursor->mx_cursor;
9310 if (m3 == csrc) continue;
9311 if (m3->mc_snum < csrc->mc_snum) continue;
9312 if (m3->mc_pg[top] == psrc) {
9313 m3->mc_pg[top] = pdst;
9314 m3->mc_ki[top] += nkeys;
9315 m3->mc_ki[top-1] = cdst->mc_ki[top-1];
9316 } else if (m3->mc_pg[top-1] == csrc->mc_pg[top-1] &&
9317 m3->mc_ki[top-1] > csrc->mc_ki[top-1]) {
9321 XCURSOR_REFRESH(m3, top, m3->mc_pg[top]);
9325 unsigned int snum = cdst->mc_snum;
9326 uint16_t depth = cdst->mc_db->md_depth;
9327 mdb_cursor_pop(cdst);
9328 rc = mdb_rebalance(cdst);
9329 /* Did the tree height change? */
9330 if (depth != cdst->mc_db->md_depth)
9331 snum += cdst->mc_db->md_depth - depth;
9332 cdst->mc_snum = snum;
9333 cdst->mc_top = snum-1;
9338 /** Copy the contents of a cursor.
9339 * @param[in] csrc The cursor to copy from.
9340 * @param[out] cdst The cursor to copy to.
9343 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
9347 cdst->mc_txn = csrc->mc_txn;
9348 cdst->mc_dbi = csrc->mc_dbi;
9349 cdst->mc_db = csrc->mc_db;
9350 cdst->mc_dbx = csrc->mc_dbx;
9351 cdst->mc_snum = csrc->mc_snum;
9352 cdst->mc_top = csrc->mc_top;
9353 cdst->mc_flags = csrc->mc_flags;
9354 MC_SET_OVPG(cdst, MC_OVPG(csrc));
9356 for (i=0; i<csrc->mc_snum; i++) {
9357 cdst->mc_pg[i] = csrc->mc_pg[i];
9358 cdst->mc_ki[i] = csrc->mc_ki[i];
9362 /** Rebalance the tree after a delete operation.
9363 * @param[in] mc Cursor pointing to the page where rebalancing
9365 * @return 0 on success, non-zero on failure.
9368 mdb_rebalance(MDB_cursor *mc)
9372 unsigned int ptop, minkeys, thresh;
9376 if (IS_BRANCH(mc->mc_pg[mc->mc_top])) {
9381 thresh = FILL_THRESHOLD;
9383 DPRINTF(("rebalancing %s page %"Yu" (has %u keys, %.1f%% full)",
9384 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
9385 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
9386 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
9388 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= thresh &&
9389 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
9390 DPRINTF(("no need to rebalance page %"Yu", above fill threshold",
9391 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
9395 if (mc->mc_snum < 2) {
9396 MDB_page *mp = mc->mc_pg[0];
9398 DPUTS("Can't rebalance a subpage, ignoring");
9401 if (NUMKEYS(mp) == 0) {
9402 DPUTS("tree is completely empty");
9403 mc->mc_db->md_root = P_INVALID;
9404 mc->mc_db->md_depth = 0;
9405 mc->mc_db->md_leaf_pages = 0;
9406 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
9409 /* Adjust cursors pointing to mp */
9412 mc->mc_flags &= ~C_INITIALIZED;
9414 MDB_cursor *m2, *m3;
9415 MDB_dbi dbi = mc->mc_dbi;
9417 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9418 if (mc->mc_flags & C_SUB)
9419 m3 = &m2->mc_xcursor->mx_cursor;
9422 if (!(m3->mc_flags & C_INITIALIZED) || (m3->mc_snum < mc->mc_snum))
9424 if (m3->mc_pg[0] == mp) {
9427 m3->mc_flags &= ~C_INITIALIZED;
9431 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
9433 DPUTS("collapsing root page!");
9434 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
9437 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
9438 rc = mdb_page_get(mc, mc->mc_db->md_root, &mc->mc_pg[0], NULL);
9441 mc->mc_db->md_depth--;
9442 mc->mc_db->md_branch_pages--;
9443 mc->mc_ki[0] = mc->mc_ki[1];
9444 for (i = 1; i<mc->mc_db->md_depth; i++) {
9445 mc->mc_pg[i] = mc->mc_pg[i+1];
9446 mc->mc_ki[i] = mc->mc_ki[i+1];
9449 /* Adjust other cursors pointing to mp */
9450 MDB_cursor *m2, *m3;
9451 MDB_dbi dbi = mc->mc_dbi;
9453 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9454 if (mc->mc_flags & C_SUB)
9455 m3 = &m2->mc_xcursor->mx_cursor;
9458 if (m3 == mc) continue;
9459 if (!(m3->mc_flags & C_INITIALIZED))
9461 if (m3->mc_pg[0] == mp) {
9462 for (i=0; i<mc->mc_db->md_depth; i++) {
9463 m3->mc_pg[i] = m3->mc_pg[i+1];
9464 m3->mc_ki[i] = m3->mc_ki[i+1];
9472 DPUTS("root page doesn't need rebalancing");
9476 /* The parent (branch page) must have at least 2 pointers,
9477 * otherwise the tree is invalid.
9479 ptop = mc->mc_top-1;
9480 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
9482 /* Leaf page fill factor is below the threshold.
9483 * Try to move keys from left or right neighbor, or
9484 * merge with a neighbor page.
9489 mdb_cursor_copy(mc, &mn);
9490 mn.mc_xcursor = NULL;
9492 oldki = mc->mc_ki[mc->mc_top];
9493 if (mc->mc_ki[ptop] == 0) {
9494 /* We're the leftmost leaf in our parent.
9496 DPUTS("reading right neighbor");
9498 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
9499 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
9502 mn.mc_ki[mn.mc_top] = 0;
9503 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
9506 /* There is at least one neighbor to the left.
9508 DPUTS("reading left neighbor");
9510 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
9511 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
9514 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
9515 mc->mc_ki[mc->mc_top] = 0;
9519 DPRINTF(("found neighbor page %"Yu" (%u keys, %.1f%% full)",
9520 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
9521 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
9523 /* If the neighbor page is above threshold and has enough keys,
9524 * move one key from it. Otherwise we should try to merge them.
9525 * (A branch page must never have less than 2 keys.)
9527 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= thresh && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
9528 rc = mdb_node_move(&mn, mc, fromleft);
9530 /* if we inserted on left, bump position up */
9535 rc = mdb_page_merge(&mn, mc);
9537 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
9538 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
9539 /* We want mdb_rebalance to find mn when doing fixups */
9540 WITH_CURSOR_TRACKING(mn,
9541 rc = mdb_page_merge(mc, &mn));
9542 mdb_cursor_copy(&mn, mc);
9544 mc->mc_flags &= ~C_EOF;
9546 mc->mc_ki[mc->mc_top] = oldki;
9550 /** Complete a delete operation started by #mdb_cursor_del(). */
9552 mdb_cursor_del0(MDB_cursor *mc)
9558 MDB_cursor *m2, *m3;
9559 MDB_dbi dbi = mc->mc_dbi;
9561 ki = mc->mc_ki[mc->mc_top];
9562 mp = mc->mc_pg[mc->mc_top];
9563 mdb_node_del(mc, mc->mc_db->md_pad);
9564 mc->mc_db->md_entries--;
9566 /* Adjust other cursors pointing to mp */
9567 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9568 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
9569 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9571 if (m3 == mc || m3->mc_snum < mc->mc_snum)
9573 if (m3->mc_pg[mc->mc_top] == mp) {
9574 if (m3->mc_ki[mc->mc_top] == ki) {
9575 m3->mc_flags |= C_DEL;
9576 if (mc->mc_db->md_flags & MDB_DUPSORT) {
9577 /* Sub-cursor referred into dataset which is gone */
9578 m3->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
9581 } else if (m3->mc_ki[mc->mc_top] > ki) {
9582 m3->mc_ki[mc->mc_top]--;
9584 XCURSOR_REFRESH(m3, mc->mc_top, mp);
9588 rc = mdb_rebalance(mc);
9592 /* DB is totally empty now, just bail out.
9593 * Other cursors adjustments were already done
9594 * by mdb_rebalance and aren't needed here.
9597 mc->mc_flags |= C_EOF;
9601 mp = mc->mc_pg[mc->mc_top];
9602 nkeys = NUMKEYS(mp);
9604 /* Adjust other cursors pointing to mp */
9605 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
9606 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
9607 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9609 if (m3->mc_snum < mc->mc_snum)
9611 if (m3->mc_pg[mc->mc_top] == mp) {
9612 if (m3->mc_ki[mc->mc_top] >= mc->mc_ki[mc->mc_top]) {
9613 /* if m3 points past last node in page, find next sibling */
9614 if (m3->mc_ki[mc->mc_top] >= nkeys) {
9615 rc = mdb_cursor_sibling(m3, 1);
9616 if (rc == MDB_NOTFOUND) {
9617 m3->mc_flags |= C_EOF;
9624 if (m3->mc_xcursor && !(m3->mc_flags & C_EOF)) {
9625 MDB_node *node = NODEPTR(m3->mc_pg[m3->mc_top], m3->mc_ki[m3->mc_top]);
9626 /* If this node has dupdata, it may need to be reinited
9627 * because its data has moved.
9628 * If the xcursor was not initd it must be reinited.
9629 * Else if node points to a subDB, nothing is needed.
9630 * Else (xcursor was initd, not a subDB) needs mc_pg[0] reset.
9632 if (node->mn_flags & F_DUPDATA) {
9633 if (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
9634 if (!(node->mn_flags & F_SUBDATA))
9635 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
9637 mdb_xcursor_init1(m3, node);
9638 rc = mdb_cursor_first(&m3->mc_xcursor->mx_cursor, NULL, NULL);
9643 m3->mc_xcursor->mx_cursor.mc_flags |= C_DEL;
9648 mc->mc_flags |= C_DEL;
9652 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
9657 mdb_del(MDB_txn *txn, MDB_dbi dbi,
9658 MDB_val *key, MDB_val *data)
9662 if (!key || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9665 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
9666 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
9668 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
9669 /* must ignore any data */
9673 MDB_TRACE(("%p, %u, %"Z"u[%s], %"Z"u%s",
9674 txn, dbi, key ? key->mv_size:0, DKEY(key), data ? data->mv_size:0,
9675 data ? mdb_dval(txn, dbi, data, dbuf):""));
9676 return mdb_del0(txn, dbi, key, data, 0);
9680 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
9681 MDB_val *key, MDB_val *data, unsigned flags)
9686 MDB_val rdata, *xdata;
9690 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
9692 mdb_cursor_init(&mc, txn, dbi, &mx);
9701 flags |= MDB_NODUPDATA;
9703 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
9705 /* let mdb_page_split know about this cursor if needed:
9706 * delete will trigger a rebalance; if it needs to move
9707 * a node from one page to another, it will have to
9708 * update the parent's separator key(s). If the new sepkey
9709 * is larger than the current one, the parent page may
9710 * run out of space, triggering a split. We need this
9711 * cursor to be consistent until the end of the rebalance.
9713 mc.mc_next = txn->mt_cursors[dbi];
9714 txn->mt_cursors[dbi] = &mc;
9715 rc = _mdb_cursor_del(&mc, flags);
9716 txn->mt_cursors[dbi] = mc.mc_next;
9721 /** Split a page and insert a new node.
9722 * Set #MDB_TXN_ERROR on failure.
9723 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
9724 * The cursor will be updated to point to the actual page and index where
9725 * the node got inserted after the split.
9726 * @param[in] newkey The key for the newly inserted node.
9727 * @param[in] newdata The data for the newly inserted node.
9728 * @param[in] newpgno The page number, if the new node is a branch node.
9729 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
9730 * @return 0 on success, non-zero on failure.
9733 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
9734 unsigned int nflags)
9737 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
9740 int i, j, split_indx, nkeys, pmax;
9741 MDB_env *env = mc->mc_txn->mt_env;
9743 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
9744 MDB_page *copy = NULL;
9745 MDB_page *mp, *rp, *pp;
9750 mp = mc->mc_pg[mc->mc_top];
9751 newindx = mc->mc_ki[mc->mc_top];
9752 nkeys = NUMKEYS(mp);
9754 DPRINTF(("-----> splitting %s page %"Yu" and adding [%s] at index %i/%i",
9755 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
9756 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
9758 /* Create a right sibling. */
9759 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
9761 rp->mp_pad = mp->mp_pad;
9762 DPRINTF(("new right sibling: page %"Yu, rp->mp_pgno));
9764 /* Usually when splitting the root page, the cursor
9765 * height is 1. But when called from mdb_update_key,
9766 * the cursor height may be greater because it walks
9767 * up the stack while finding the branch slot to update.
9769 if (mc->mc_top < 1) {
9770 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
9772 /* shift current top to make room for new parent */
9773 for (i=mc->mc_snum; i>0; i--) {
9774 mc->mc_pg[i] = mc->mc_pg[i-1];
9775 mc->mc_ki[i] = mc->mc_ki[i-1];
9779 mc->mc_db->md_root = pp->mp_pgno;
9780 DPRINTF(("root split! new root = %"Yu, pp->mp_pgno));
9781 new_root = mc->mc_db->md_depth++;
9783 /* Add left (implicit) pointer. */
9784 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
9785 /* undo the pre-push */
9786 mc->mc_pg[0] = mc->mc_pg[1];
9787 mc->mc_ki[0] = mc->mc_ki[1];
9788 mc->mc_db->md_root = mp->mp_pgno;
9789 mc->mc_db->md_depth--;
9796 ptop = mc->mc_top-1;
9797 DPRINTF(("parent branch page is %"Yu, mc->mc_pg[ptop]->mp_pgno));
9800 mdb_cursor_copy(mc, &mn);
9801 mn.mc_xcursor = NULL;
9802 mn.mc_pg[mn.mc_top] = rp;
9803 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
9805 if (nflags & MDB_APPEND) {
9806 mn.mc_ki[mn.mc_top] = 0;
9808 split_indx = newindx;
9812 split_indx = (nkeys+1) / 2;
9817 unsigned int lsize, rsize, ksize;
9818 /* Move half of the keys to the right sibling */
9819 x = mc->mc_ki[mc->mc_top] - split_indx;
9820 ksize = mc->mc_db->md_pad;
9821 split = LEAF2KEY(mp, split_indx, ksize);
9822 rsize = (nkeys - split_indx) * ksize;
9823 lsize = (nkeys - split_indx) * sizeof(indx_t);
9824 mp->mp_lower -= lsize;
9825 rp->mp_lower += lsize;
9826 mp->mp_upper += rsize - lsize;
9827 rp->mp_upper -= rsize - lsize;
9828 sepkey.mv_size = ksize;
9829 if (newindx == split_indx) {
9830 sepkey.mv_data = newkey->mv_data;
9832 sepkey.mv_data = split;
9835 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
9836 memcpy(rp->mp_ptrs, split, rsize);
9837 sepkey.mv_data = rp->mp_ptrs;
9838 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
9839 memcpy(ins, newkey->mv_data, ksize);
9840 mp->mp_lower += sizeof(indx_t);
9841 mp->mp_upper -= ksize - sizeof(indx_t);
9844 memcpy(rp->mp_ptrs, split, x * ksize);
9845 ins = LEAF2KEY(rp, x, ksize);
9846 memcpy(ins, newkey->mv_data, ksize);
9847 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
9848 rp->mp_lower += sizeof(indx_t);
9849 rp->mp_upper -= ksize - sizeof(indx_t);
9850 mc->mc_ki[mc->mc_top] = x;
9853 int psize, nsize, k, keythresh;
9855 /* Maximum free space in an empty page */
9856 pmax = env->me_psize - PAGEHDRSZ;
9857 /* Threshold number of keys considered "small" */
9858 keythresh = env->me_psize >> 7;
9861 nsize = mdb_leaf_size(env, newkey, newdata);
9863 nsize = mdb_branch_size(env, newkey);
9864 nsize = EVEN(nsize);
9866 /* grab a page to hold a temporary copy */
9867 copy = mdb_page_malloc(mc->mc_txn, 1);
9872 copy->mp_pgno = mp->mp_pgno;
9873 copy->mp_flags = mp->mp_flags;
9874 copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
9875 copy->mp_upper = env->me_psize - PAGEBASE;
9877 /* prepare to insert */
9878 for (i=0, j=0; i<nkeys; i++) {
9880 copy->mp_ptrs[j++] = 0;
9882 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
9885 /* When items are relatively large the split point needs
9886 * to be checked, because being off-by-one will make the
9887 * difference between success or failure in mdb_node_add.
9889 * It's also relevant if a page happens to be laid out
9890 * such that one half of its nodes are all "small" and
9891 * the other half of its nodes are "large." If the new
9892 * item is also "large" and falls on the half with
9893 * "large" nodes, it also may not fit.
9895 * As a final tweak, if the new item goes on the last
9896 * spot on the page (and thus, onto the new page), bias
9897 * the split so the new page is emptier than the old page.
9898 * This yields better packing during sequential inserts.
9900 if (nkeys < keythresh || nsize > pmax/16 || newindx >= nkeys) {
9901 /* Find split point */
9903 if (newindx <= split_indx || newindx >= nkeys) {
9905 k = newindx >= nkeys ? nkeys : split_indx+1+IS_LEAF(mp);
9910 for (; i!=k; i+=j) {
9915 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
9916 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
9918 if (F_ISSET(node->mn_flags, F_BIGDATA))
9919 psize += sizeof(pgno_t);
9921 psize += NODEDSZ(node);
9923 psize = EVEN(psize);
9925 if (psize > pmax || i == k-j) {
9926 split_indx = i + (j<0);
9931 if (split_indx == newindx) {
9932 sepkey.mv_size = newkey->mv_size;
9933 sepkey.mv_data = newkey->mv_data;
9935 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
9936 sepkey.mv_size = node->mn_ksize;
9937 sepkey.mv_data = NODEKEY(node);
9942 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
9944 /* Copy separator key to the parent.
9946 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
9947 int snum = mc->mc_snum;
9951 /* We want other splits to find mn when doing fixups */
9952 WITH_CURSOR_TRACKING(mn,
9953 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0));
9958 if (mc->mc_snum > snum) {
9961 /* Right page might now have changed parent.
9962 * Check if left page also changed parent.
9964 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
9965 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
9966 for (i=0; i<ptop; i++) {
9967 mc->mc_pg[i] = mn.mc_pg[i];
9968 mc->mc_ki[i] = mn.mc_ki[i];
9970 mc->mc_pg[ptop] = mn.mc_pg[ptop];
9971 if (mn.mc_ki[ptop]) {
9972 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
9974 /* find right page's left sibling */
9975 mc->mc_ki[ptop] = mn.mc_ki[ptop];
9976 rc = mdb_cursor_sibling(mc, 0);
9981 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
9984 if (rc != MDB_SUCCESS) {
9985 if (rc == MDB_NOTFOUND) /* improper mdb_cursor_sibling() result */
9989 if (nflags & MDB_APPEND) {
9990 mc->mc_pg[mc->mc_top] = rp;
9991 mc->mc_ki[mc->mc_top] = 0;
9992 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
9995 for (i=0; i<mc->mc_top; i++)
9996 mc->mc_ki[i] = mn.mc_ki[i];
9997 } else if (!IS_LEAF2(mp)) {
9999 mc->mc_pg[mc->mc_top] = rp;
10003 if (i == newindx) {
10004 rkey.mv_data = newkey->mv_data;
10005 rkey.mv_size = newkey->mv_size;
10011 /* Update index for the new key. */
10012 mc->mc_ki[mc->mc_top] = j;
10014 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
10015 rkey.mv_data = NODEKEY(node);
10016 rkey.mv_size = node->mn_ksize;
10018 xdata.mv_data = NODEDATA(node);
10019 xdata.mv_size = NODEDSZ(node);
10022 pgno = NODEPGNO(node);
10023 flags = node->mn_flags;
10026 if (!IS_LEAF(mp) && j == 0) {
10027 /* First branch index doesn't need key data. */
10031 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
10037 mc->mc_pg[mc->mc_top] = copy;
10042 } while (i != split_indx);
10044 nkeys = NUMKEYS(copy);
10045 for (i=0; i<nkeys; i++)
10046 mp->mp_ptrs[i] = copy->mp_ptrs[i];
10047 mp->mp_lower = copy->mp_lower;
10048 mp->mp_upper = copy->mp_upper;
10049 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
10050 env->me_psize - copy->mp_upper - PAGEBASE);
10052 /* reset back to original page */
10053 if (newindx < split_indx) {
10054 mc->mc_pg[mc->mc_top] = mp;
10056 mc->mc_pg[mc->mc_top] = rp;
10058 /* Make sure mc_ki is still valid.
10060 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
10061 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
10062 for (i=0; i<=ptop; i++) {
10063 mc->mc_pg[i] = mn.mc_pg[i];
10064 mc->mc_ki[i] = mn.mc_ki[i];
10068 if (nflags & MDB_RESERVE) {
10069 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
10070 if (!(node->mn_flags & F_BIGDATA))
10071 newdata->mv_data = NODEDATA(node);
10074 if (newindx >= split_indx) {
10075 mc->mc_pg[mc->mc_top] = rp;
10077 /* Make sure mc_ki is still valid.
10079 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
10080 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
10081 for (i=0; i<=ptop; i++) {
10082 mc->mc_pg[i] = mn.mc_pg[i];
10083 mc->mc_ki[i] = mn.mc_ki[i];
10090 /* Adjust other cursors pointing to mp */
10091 MDB_cursor *m2, *m3;
10092 MDB_dbi dbi = mc->mc_dbi;
10093 nkeys = NUMKEYS(mp);
10095 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
10096 if (mc->mc_flags & C_SUB)
10097 m3 = &m2->mc_xcursor->mx_cursor;
10102 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
10106 /* sub cursors may be on different DB */
10107 if (m3->mc_pg[0] != mp)
10110 for (k=new_root; k>=0; k--) {
10111 m3->mc_ki[k+1] = m3->mc_ki[k];
10112 m3->mc_pg[k+1] = m3->mc_pg[k];
10114 if (m3->mc_ki[0] >= nkeys) {
10119 m3->mc_pg[0] = mc->mc_pg[0];
10123 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
10124 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
10125 m3->mc_ki[mc->mc_top]++;
10126 if (m3->mc_ki[mc->mc_top] >= nkeys) {
10127 m3->mc_pg[mc->mc_top] = rp;
10128 m3->mc_ki[mc->mc_top] -= nkeys;
10129 for (i=0; i<mc->mc_top; i++) {
10130 m3->mc_ki[i] = mn.mc_ki[i];
10131 m3->mc_pg[i] = mn.mc_pg[i];
10134 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
10135 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
10139 XCURSOR_REFRESH(m3, mc->mc_top, m3->mc_pg[mc->mc_top]);
10142 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
10145 if (copy) /* tmp page */
10146 mdb_page_free(env, copy);
10148 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
10153 mdb_put(MDB_txn *txn, MDB_dbi dbi,
10154 MDB_val *key, MDB_val *data, unsigned int flags)
10162 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10165 if (flags & ~(MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP))
10168 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
10169 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
10171 MDB_TRACE(("%p, %u, %"Z"u[%s], %"Z"u%s, %u",
10172 txn, dbi, key ? key->mv_size:0, DKEY(key), data->mv_size, mdb_dval(txn, dbi, data, dbuf), flags));
10173 mdb_cursor_init(&mc, txn, dbi, &mx);
10174 mc.mc_next = txn->mt_cursors[dbi];
10175 txn->mt_cursors[dbi] = &mc;
10176 rc = _mdb_cursor_put(&mc, key, data, flags);
10177 txn->mt_cursors[dbi] = mc.mc_next;
10182 #define MDB_WBUF (1024*1024)
10184 #define MDB_EOF 0x10 /**< #mdb_env_copyfd1() is done reading */
10186 /** State needed for a double-buffering compacting copy. */
10187 typedef struct mdb_copy {
10190 pthread_mutex_t mc_mutex;
10191 pthread_cond_t mc_cond; /**< Condition variable for #mc_new */
10196 pgno_t mc_next_pgno;
10198 int mc_toggle; /**< Buffer number in provider */
10199 int mc_new; /**< (0-2 buffers to write) | (#MDB_EOF at end) */
10200 /** Error code. Never cleared if set. Both threads can set nonzero
10201 * to fail the copy. Not mutex-protected, LMDB expects atomic int.
10203 volatile int mc_error;
10206 /** Dedicated writer thread for compacting copy. */
10207 static THREAD_RET ESECT CALL_CONV
10208 mdb_env_copythr(void *arg)
10210 mdb_copy *my = arg;
10212 int toggle = 0, wsize, rc;
10215 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
10218 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
10222 sigaddset(&set, SIGPIPE);
10223 if ((rc = pthread_sigmask(SIG_BLOCK, &set, NULL)) != 0)
10228 pthread_mutex_lock(&my->mc_mutex);
10230 while (!my->mc_new)
10231 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
10232 if (my->mc_new == 0 + MDB_EOF) /* 0 buffers, just EOF */
10234 wsize = my->mc_wlen[toggle];
10235 ptr = my->mc_wbuf[toggle];
10238 while (wsize > 0 && !my->mc_error) {
10239 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
10242 #if defined(SIGPIPE) && !defined(_WIN32)
10244 /* Collect the pending SIGPIPE, otherwise at least OS X
10245 * gives it to the process on thread-exit (ITS#8504).
10248 sigwait(&set, &tmp);
10252 } else if (len > 0) {
10265 /* If there's an overflow page tail, write it too */
10266 if (my->mc_olen[toggle]) {
10267 wsize = my->mc_olen[toggle];
10268 ptr = my->mc_over[toggle];
10269 my->mc_olen[toggle] = 0;
10272 my->mc_wlen[toggle] = 0;
10274 /* Return the empty buffer to provider */
10276 pthread_cond_signal(&my->mc_cond);
10278 pthread_mutex_unlock(&my->mc_mutex);
10279 return (THREAD_RET)0;
10283 /** Give buffer and/or #MDB_EOF to writer thread, await unused buffer.
10285 * @param[in] my control structure.
10286 * @param[in] adjust (1 to hand off 1 buffer) | (MDB_EOF when ending).
10289 mdb_env_cthr_toggle(mdb_copy *my, int adjust)
10291 pthread_mutex_lock(&my->mc_mutex);
10292 my->mc_new += adjust;
10293 pthread_cond_signal(&my->mc_cond);
10294 while (my->mc_new & 2) /* both buffers in use */
10295 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
10296 pthread_mutex_unlock(&my->mc_mutex);
10298 my->mc_toggle ^= (adjust & 1);
10299 /* Both threads reset mc_wlen, to be safe from threading errors */
10300 my->mc_wlen[my->mc_toggle] = 0;
10301 return my->mc_error;
10304 /** Depth-first tree traversal for compacting copy.
10305 * @param[in] my control structure.
10306 * @param[in,out] pg database root.
10307 * @param[in] flags includes #F_DUPDATA if it is a sorted-duplicate sub-DB.
10310 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
10312 MDB_cursor mc = {0};
10314 MDB_page *mo, *mp, *leaf;
10319 /* Empty DB, nothing to do */
10320 if (*pg == P_INVALID)
10321 return MDB_SUCCESS;
10324 mc.mc_txn = my->mc_txn;
10325 mc.mc_flags = my->mc_txn->mt_flags & (C_ORIG_RDONLY|C_WRITEMAP);
10327 rc = mdb_page_get(&mc, *pg, &mc.mc_pg[0], NULL);
10330 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
10334 /* Make cursor pages writable */
10335 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
10339 for (i=0; i<mc.mc_top; i++) {
10340 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
10341 mc.mc_pg[i] = (MDB_page *)ptr;
10342 ptr += my->mc_env->me_psize;
10345 /* This is writable space for a leaf page. Usually not needed. */
10346 leaf = (MDB_page *)ptr;
10348 toggle = my->mc_toggle;
10349 while (mc.mc_snum > 0) {
10351 mp = mc.mc_pg[mc.mc_top];
10355 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
10356 for (i=0; i<n; i++) {
10357 ni = NODEPTR(mp, i);
10358 if (ni->mn_flags & F_BIGDATA) {
10362 /* Need writable leaf */
10364 mc.mc_pg[mc.mc_top] = leaf;
10365 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
10367 ni = NODEPTR(mp, i);
10370 memcpy(&pg, NODEDATA(ni), sizeof(pg));
10371 memcpy(NODEDATA(ni), &my->mc_next_pgno, sizeof(pgno_t));
10372 rc = mdb_page_get(&mc, pg, &omp, NULL);
10375 if (my->mc_wlen[toggle] >= MDB_WBUF) {
10376 rc = mdb_env_cthr_toggle(my, 1);
10379 toggle = my->mc_toggle;
10381 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
10382 memcpy(mo, omp, my->mc_env->me_psize);
10383 mo->mp_pgno = my->mc_next_pgno;
10384 my->mc_next_pgno += omp->mp_pages;
10385 my->mc_wlen[toggle] += my->mc_env->me_psize;
10386 if (omp->mp_pages > 1) {
10387 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
10388 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
10389 rc = mdb_env_cthr_toggle(my, 1);
10392 toggle = my->mc_toggle;
10394 } else if (ni->mn_flags & F_SUBDATA) {
10397 /* Need writable leaf */
10399 mc.mc_pg[mc.mc_top] = leaf;
10400 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
10402 ni = NODEPTR(mp, i);
10405 memcpy(&db, NODEDATA(ni), sizeof(db));
10406 my->mc_toggle = toggle;
10407 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
10410 toggle = my->mc_toggle;
10411 memcpy(NODEDATA(ni), &db, sizeof(db));
10416 mc.mc_ki[mc.mc_top]++;
10417 if (mc.mc_ki[mc.mc_top] < n) {
10420 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
10422 rc = mdb_page_get(&mc, pg, &mp, NULL);
10427 mc.mc_ki[mc.mc_top] = 0;
10428 if (IS_BRANCH(mp)) {
10429 /* Whenever we advance to a sibling branch page,
10430 * we must proceed all the way down to its first leaf.
10432 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
10435 mc.mc_pg[mc.mc_top] = mp;
10439 if (my->mc_wlen[toggle] >= MDB_WBUF) {
10440 rc = mdb_env_cthr_toggle(my, 1);
10443 toggle = my->mc_toggle;
10445 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
10446 mdb_page_copy(mo, mp, my->mc_env->me_psize);
10447 mo->mp_pgno = my->mc_next_pgno++;
10448 my->mc_wlen[toggle] += my->mc_env->me_psize;
10450 /* Update parent if there is one */
10451 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
10452 SETPGNO(ni, mo->mp_pgno);
10453 mdb_cursor_pop(&mc);
10455 /* Otherwise we're done */
10465 /** Copy environment with compaction. */
10467 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
10472 MDB_txn *txn = NULL;
10474 pgno_t root, new_root;
10475 int rc = MDB_SUCCESS;
10478 if (!(my.mc_mutex = CreateMutex(NULL, FALSE, NULL)) ||
10479 !(my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL))) {
10483 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_os_psize);
10484 if (my.mc_wbuf[0] == NULL) {
10485 /* _aligned_malloc() sets errno, but we use Windows error codes */
10486 rc = ERROR_NOT_ENOUGH_MEMORY;
10490 if ((rc = pthread_mutex_init(&my.mc_mutex, NULL)) != 0)
10492 if ((rc = pthread_cond_init(&my.mc_cond, NULL)) != 0)
10494 #ifdef HAVE_MEMALIGN
10495 my.mc_wbuf[0] = memalign(env->me_os_psize, MDB_WBUF*2);
10496 if (my.mc_wbuf[0] == NULL) {
10503 if ((rc = posix_memalign(&p, env->me_os_psize, MDB_WBUF*2)) != 0)
10509 memset(my.mc_wbuf[0], 0, MDB_WBUF*2);
10510 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
10511 my.mc_next_pgno = NUM_METAS;
10514 rc = THREAD_CREATE(thr, mdb_env_copythr, &my);
10518 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
10522 mp = (MDB_page *)my.mc_wbuf[0];
10523 memset(mp, 0, NUM_METAS * env->me_psize);
10525 mp->mp_flags = P_META;
10526 mm = (MDB_meta *)METADATA(mp);
10527 mdb_env_init_meta0(env, mm);
10528 mm->mm_address = env->me_metas[0]->mm_address;
10530 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
10532 mp->mp_flags = P_META;
10533 *(MDB_meta *)METADATA(mp) = *mm;
10534 mm = (MDB_meta *)METADATA(mp);
10536 /* Set metapage 1 with current main DB */
10537 root = new_root = txn->mt_dbs[MAIN_DBI].md_root;
10538 if (root != P_INVALID) {
10539 /* Count free pages + freeDB pages. Subtract from last_pg
10540 * to find the new last_pg, which also becomes the new root.
10542 MDB_ID freecount = 0;
10545 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
10546 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
10547 freecount += *(MDB_ID *)data.mv_data;
10548 if (rc != MDB_NOTFOUND)
10550 freecount += txn->mt_dbs[FREE_DBI].md_branch_pages +
10551 txn->mt_dbs[FREE_DBI].md_leaf_pages +
10552 txn->mt_dbs[FREE_DBI].md_overflow_pages;
10554 new_root = txn->mt_next_pgno - 1 - freecount;
10555 mm->mm_last_pg = new_root;
10556 mm->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
10557 mm->mm_dbs[MAIN_DBI].md_root = new_root;
10559 /* When the DB is empty, handle it specially to
10560 * fix any breakage like page leaks from ITS#8174.
10562 mm->mm_dbs[MAIN_DBI].md_flags = txn->mt_dbs[MAIN_DBI].md_flags;
10564 if (root != P_INVALID || mm->mm_dbs[MAIN_DBI].md_flags) {
10565 mm->mm_txnid = 1; /* use metapage 1 */
10568 my.mc_wlen[0] = env->me_psize * NUM_METAS;
10570 rc = mdb_env_cwalk(&my, &root, 0);
10571 if (rc == MDB_SUCCESS && root != new_root) {
10572 rc = MDB_INCOMPATIBLE; /* page leak or corrupt DB */
10578 mdb_env_cthr_toggle(&my, 1 | MDB_EOF);
10579 rc = THREAD_FINISH(thr);
10580 _mdb_txn_abort(txn);
10584 if (my.mc_wbuf[0]) _aligned_free(my.mc_wbuf[0]);
10585 if (my.mc_cond) CloseHandle(my.mc_cond);
10586 if (my.mc_mutex) CloseHandle(my.mc_mutex);
10588 free(my.mc_wbuf[0]);
10589 pthread_cond_destroy(&my.mc_cond);
10591 pthread_mutex_destroy(&my.mc_mutex);
10593 return rc ? rc : my.mc_error;
10596 /** Copy environment as-is. */
10598 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
10600 MDB_txn *txn = NULL;
10601 mdb_mutexref_t wmutex = NULL;
10603 mdb_size_t wsize, w3;
10607 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
10611 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
10614 /* Do the lock/unlock of the reader mutex before starting the
10615 * write txn. Otherwise other read txns could block writers.
10617 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
10621 if (env->me_txns) {
10622 /* We must start the actual read txn after blocking writers */
10623 mdb_txn_end(txn, MDB_END_RESET_TMP);
10625 /* Temporarily block writers until we snapshot the meta pages */
10626 wmutex = env->me_wmutex;
10627 if (LOCK_MUTEX(rc, env, wmutex))
10630 rc = mdb_txn_renew0(txn);
10632 UNLOCK_MUTEX(wmutex);
10637 wsize = env->me_psize * NUM_METAS;
10641 DO_WRITE(rc, fd, ptr, w2, len);
10645 } else if (len > 0) {
10651 /* Non-blocking or async handles are not supported */
10657 UNLOCK_MUTEX(wmutex);
10662 w3 = txn->mt_next_pgno * env->me_psize;
10664 mdb_size_t fsize = 0;
10665 if ((rc = mdb_fsize(env->me_fd, &fsize)))
10670 wsize = w3 - wsize;
10671 while (wsize > 0) {
10672 if (wsize > MAX_WRITE)
10676 DO_WRITE(rc, fd, ptr, w2, len);
10680 } else if (len > 0) {
10692 _mdb_txn_abort(txn);
10697 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
10699 if (flags & MDB_CP_COMPACT)
10700 return mdb_env_copyfd1(env, fd);
10702 return mdb_env_copyfd0(env, fd);
10706 mdb_env_copyfd(MDB_env *env, HANDLE fd)
10708 return mdb_env_copyfd2(env, fd, 0);
10712 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
10716 HANDLE newfd = INVALID_HANDLE_VALUE;
10718 rc = mdb_fname_init(path, env->me_flags | MDB_NOLOCK, &fname);
10719 if (rc == MDB_SUCCESS) {
10720 rc = mdb_fopen(env, &fname, MDB_O_COPY, 0666, &newfd);
10721 mdb_fname_destroy(fname);
10723 if (rc == MDB_SUCCESS) {
10724 rc = mdb_env_copyfd2(env, newfd, flags);
10725 if (close(newfd) < 0 && rc == MDB_SUCCESS)
10732 mdb_env_copy(MDB_env *env, const char *path)
10734 return mdb_env_copy2(env, path, 0);
10738 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
10740 if (flag & ~CHANGEABLE)
10743 env->me_flags |= flag;
10745 env->me_flags &= ~flag;
10746 return MDB_SUCCESS;
10750 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
10755 *arg = env->me_flags & (CHANGEABLE|CHANGELESS);
10756 return MDB_SUCCESS;
10760 mdb_env_set_userctx(MDB_env *env, void *ctx)
10764 env->me_userctx = ctx;
10765 return MDB_SUCCESS;
10769 mdb_env_get_userctx(MDB_env *env)
10771 return env ? env->me_userctx : NULL;
10775 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
10780 env->me_assert_func = func;
10782 return MDB_SUCCESS;
10786 mdb_env_get_path(MDB_env *env, const char **arg)
10791 *arg = env->me_path;
10792 return MDB_SUCCESS;
10796 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
10802 return MDB_SUCCESS;
10805 /** Common code for #mdb_stat() and #mdb_env_stat().
10806 * @param[in] env the environment to operate in.
10807 * @param[in] db the #MDB_db record containing the stats to return.
10808 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
10809 * @return 0, this function always succeeds.
10812 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
10814 arg->ms_psize = env->me_psize;
10815 arg->ms_depth = db->md_depth;
10816 arg->ms_branch_pages = db->md_branch_pages;
10817 arg->ms_leaf_pages = db->md_leaf_pages;
10818 arg->ms_overflow_pages = db->md_overflow_pages;
10819 arg->ms_entries = db->md_entries;
10821 return MDB_SUCCESS;
10825 mdb_env_stat(MDB_env *env, MDB_stat *arg)
10829 if (env == NULL || arg == NULL)
10832 meta = mdb_env_pick_meta(env);
10834 return mdb_stat0(env, &meta->mm_dbs[MAIN_DBI], arg);
10838 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
10842 if (env == NULL || arg == NULL)
10845 meta = mdb_env_pick_meta(env);
10846 arg->me_mapaddr = meta->mm_address;
10847 arg->me_last_pgno = meta->mm_last_pg;
10848 arg->me_last_txnid = meta->mm_txnid;
10850 arg->me_mapsize = env->me_mapsize;
10851 arg->me_maxreaders = env->me_maxreaders;
10852 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : 0;
10853 return MDB_SUCCESS;
10856 /** Set the default comparison functions for a database.
10857 * Called immediately after a database is opened to set the defaults.
10858 * The user can then override them with #mdb_set_compare() or
10859 * #mdb_set_dupsort().
10860 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
10861 * @param[in] dbi A database handle returned by #mdb_dbi_open()
10864 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
10866 uint16_t f = txn->mt_dbs[dbi].md_flags;
10868 txn->mt_dbxs[dbi].md_cmp =
10869 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
10870 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
10872 txn->mt_dbxs[dbi].md_dcmp =
10873 !(f & MDB_DUPSORT) ? 0 :
10874 ((f & MDB_INTEGERDUP)
10875 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
10876 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
10879 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
10885 int rc, dbflag, exact;
10886 unsigned int unused = 0, seq;
10890 if (flags & ~VALID_FLAGS)
10892 if (txn->mt_flags & MDB_TXN_BLOCKED)
10893 return MDB_BAD_TXN;
10898 if (flags & PERSISTENT_FLAGS) {
10899 uint16_t f2 = flags & PERSISTENT_FLAGS;
10900 /* make sure flag changes get committed */
10901 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
10902 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
10903 txn->mt_flags |= MDB_TXN_DIRTY;
10906 mdb_default_cmp(txn, MAIN_DBI);
10907 MDB_TRACE(("%p, (null), %u = %u", txn, flags, MAIN_DBI));
10908 return MDB_SUCCESS;
10911 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
10912 mdb_default_cmp(txn, MAIN_DBI);
10915 /* Is the DB already open? */
10916 len = strlen(name);
10917 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
10918 if (!txn->mt_dbxs[i].md_name.mv_size) {
10919 /* Remember this free slot */
10920 if (!unused) unused = i;
10923 if (len == txn->mt_dbxs[i].md_name.mv_size &&
10924 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
10926 return MDB_SUCCESS;
10930 /* If no free slot and max hit, fail */
10931 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
10932 return MDB_DBS_FULL;
10934 /* Cannot mix named databases with some mainDB flags */
10935 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
10936 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
10938 /* Find the DB info */
10939 dbflag = DB_NEW|DB_VALID|DB_USRVALID;
10942 key.mv_data = (void *)name;
10943 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
10944 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
10945 if (rc == MDB_SUCCESS) {
10946 /* make sure this is actually a DB */
10947 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
10948 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
10949 return MDB_INCOMPATIBLE;
10951 if (rc != MDB_NOTFOUND || !(flags & MDB_CREATE))
10953 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
10957 /* Done here so we cannot fail after creating a new DB */
10958 if ((namedup = strdup(name)) == NULL)
10962 /* MDB_NOTFOUND and MDB_CREATE: Create new DB */
10963 data.mv_size = sizeof(MDB_db);
10964 data.mv_data = &dummy;
10965 memset(&dummy, 0, sizeof(dummy));
10966 dummy.md_root = P_INVALID;
10967 dummy.md_flags = flags & PERSISTENT_FLAGS;
10968 WITH_CURSOR_TRACKING(mc,
10969 rc = _mdb_cursor_put(&mc, &key, &data, F_SUBDATA));
10970 dbflag |= DB_DIRTY;
10976 /* Got info, register DBI in this txn */
10977 unsigned int slot = unused ? unused : txn->mt_numdbs;
10978 txn->mt_dbxs[slot].md_name.mv_data = namedup;
10979 txn->mt_dbxs[slot].md_name.mv_size = len;
10980 txn->mt_dbxs[slot].md_rel = NULL;
10981 txn->mt_dbflags[slot] = dbflag;
10982 /* txn-> and env-> are the same in read txns, use
10983 * tmp variable to avoid undefined assignment
10985 seq = ++txn->mt_env->me_dbiseqs[slot];
10986 txn->mt_dbiseqs[slot] = seq;
10988 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
10990 mdb_default_cmp(txn, slot);
10994 MDB_TRACE(("%p, %s, %u = %u", txn, name, flags, slot));
11001 mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
11003 if (!arg || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
11006 if (txn->mt_flags & MDB_TXN_BLOCKED)
11007 return MDB_BAD_TXN;
11009 if (txn->mt_dbflags[dbi] & DB_STALE) {
11012 /* Stale, must read the DB's root. cursor_init does it for us. */
11013 mdb_cursor_init(&mc, txn, dbi, &mx);
11015 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
11018 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
11021 if (dbi < CORE_DBS || dbi >= env->me_maxdbs)
11023 ptr = env->me_dbxs[dbi].md_name.mv_data;
11024 /* If there was no name, this was already closed */
11026 MDB_TRACE(("%p, %u", env, dbi));
11027 env->me_dbxs[dbi].md_name.mv_data = NULL;
11028 env->me_dbxs[dbi].md_name.mv_size = 0;
11029 env->me_dbflags[dbi] = 0;
11030 env->me_dbiseqs[dbi]++;
11035 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
11037 /* We could return the flags for the FREE_DBI too but what's the point? */
11038 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
11040 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
11041 return MDB_SUCCESS;
11044 /** Add all the DB's pages to the free list.
11045 * @param[in] mc Cursor on the DB to free.
11046 * @param[in] subs non-Zero to check for sub-DBs in this DB.
11047 * @return 0 on success, non-zero on failure.
11050 mdb_drop0(MDB_cursor *mc, int subs)
11054 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
11055 if (rc == MDB_SUCCESS) {
11056 MDB_txn *txn = mc->mc_txn;
11061 /* DUPSORT sub-DBs have no ovpages/DBs. Omit scanning leaves.
11062 * This also avoids any P_LEAF2 pages, which have no nodes.
11063 * Also if the DB doesn't have sub-DBs and has no overflow
11064 * pages, omit scanning leaves.
11066 if ((mc->mc_flags & C_SUB) ||
11067 (!subs && !mc->mc_db->md_overflow_pages))
11068 mdb_cursor_pop(mc);
11070 mdb_cursor_copy(mc, &mx);
11072 /* bump refcount for mx's pages */
11073 for (i=0; i<mc->mc_snum; i++)
11074 mdb_page_get(&mx, mc->mc_pg[i]->mp_pgno, &mx.mc_pg[i], NULL);
11076 while (mc->mc_snum > 0) {
11077 MDB_page *mp = mc->mc_pg[mc->mc_top];
11078 unsigned n = NUMKEYS(mp);
11080 for (i=0; i<n; i++) {
11081 ni = NODEPTR(mp, i);
11082 if (ni->mn_flags & F_BIGDATA) {
11085 memcpy(&pg, NODEDATA(ni), sizeof(pg));
11086 rc = mdb_page_get(mc, pg, &omp, NULL);
11089 mdb_cassert(mc, IS_OVERFLOW(omp));
11090 rc = mdb_midl_append_range(&txn->mt_free_pgs,
11091 pg, omp->mp_pages);
11094 mc->mc_db->md_overflow_pages -= omp->mp_pages;
11095 if (!mc->mc_db->md_overflow_pages && !subs)
11097 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
11098 mdb_xcursor_init1(mc, ni);
11099 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
11104 if (!subs && !mc->mc_db->md_overflow_pages)
11107 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
11109 for (i=0; i<n; i++) {
11111 ni = NODEPTR(mp, i);
11114 mdb_midl_xappend(txn->mt_free_pgs, pg);
11119 mc->mc_ki[mc->mc_top] = i;
11120 rc = mdb_cursor_sibling(mc, 1);
11122 if (rc != MDB_NOTFOUND)
11124 /* no more siblings, go back to beginning
11125 * of previous level.
11128 mdb_cursor_pop(mc);
11130 for (i=1; i<mc->mc_snum; i++) {
11132 mc->mc_pg[i] = mx.mc_pg[i];
11137 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
11140 txn->mt_flags |= MDB_TXN_ERROR;
11141 /* drop refcount for mx's pages */
11142 MDB_CURSOR_UNREF(&mx, 0);
11143 } else if (rc == MDB_NOTFOUND) {
11146 mc->mc_flags &= ~C_INITIALIZED;
11150 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
11152 MDB_cursor *mc, *m2;
11155 if ((unsigned)del > 1 || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
11158 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
11161 if (TXN_DBI_CHANGED(txn, dbi))
11162 return MDB_BAD_DBI;
11164 rc = mdb_cursor_open(txn, dbi, &mc);
11168 MDB_TRACE(("%u, %d", dbi, del));
11169 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
11170 /* Invalidate the dropped DB's cursors */
11171 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
11172 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
11176 /* Can't delete the main DB */
11177 if (del && dbi >= CORE_DBS) {
11178 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, F_SUBDATA);
11180 txn->mt_dbflags[dbi] = DB_STALE;
11181 mdb_dbi_close(txn->mt_env, dbi);
11183 txn->mt_flags |= MDB_TXN_ERROR;
11186 /* reset the DB record, mark it dirty */
11187 txn->mt_dbflags[dbi] |= DB_DIRTY;
11188 txn->mt_dbs[dbi].md_depth = 0;
11189 txn->mt_dbs[dbi].md_branch_pages = 0;
11190 txn->mt_dbs[dbi].md_leaf_pages = 0;
11191 txn->mt_dbs[dbi].md_overflow_pages = 0;
11192 txn->mt_dbs[dbi].md_entries = 0;
11193 txn->mt_dbs[dbi].md_root = P_INVALID;
11195 txn->mt_flags |= MDB_TXN_DIRTY;
11198 mdb_cursor_close(mc);
11202 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
11204 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
11207 txn->mt_dbxs[dbi].md_cmp = cmp;
11208 return MDB_SUCCESS;
11211 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
11213 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
11216 txn->mt_dbxs[dbi].md_dcmp = cmp;
11217 return MDB_SUCCESS;
11220 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
11222 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
11225 txn->mt_dbxs[dbi].md_rel = rel;
11226 return MDB_SUCCESS;
11229 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
11231 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
11234 txn->mt_dbxs[dbi].md_relctx = ctx;
11235 return MDB_SUCCESS;
11239 mdb_env_get_maxkeysize(MDB_env *env)
11241 return ENV_MAXKEY(env);
11245 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
11247 unsigned int i, rdrs;
11250 int rc = 0, first = 1;
11254 if (!env->me_txns) {
11255 return func("(no reader locks)\n", ctx);
11257 rdrs = env->me_txns->mti_numreaders;
11258 mr = env->me_txns->mti_readers;
11259 for (i=0; i<rdrs; i++) {
11260 if (mr[i].mr_pid) {
11261 txnid_t txnid = mr[i].mr_txnid;
11262 sprintf(buf, txnid == (txnid_t)-1 ?
11263 "%10d %"Z"x -\n" : "%10d %"Z"x %"Yu"\n",
11264 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
11267 rc = func(" pid thread txnid\n", ctx);
11271 rc = func(buf, ctx);
11277 rc = func("(no active readers)\n", ctx);
11282 /** Insert pid into list if not already present.
11283 * return -1 if already present.
11286 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
11288 /* binary search of pid in list */
11290 unsigned cursor = 1;
11292 unsigned n = ids[0];
11295 unsigned pivot = n >> 1;
11296 cursor = base + pivot + 1;
11297 val = pid - ids[cursor];
11302 } else if ( val > 0 ) {
11307 /* found, so it's a duplicate */
11316 for (n = ids[0]; n > cursor; n--)
11323 mdb_reader_check(MDB_env *env, int *dead)
11329 return env->me_txns ? mdb_reader_check0(env, 0, dead) : MDB_SUCCESS;
11332 /** As #mdb_reader_check(). \b rlocked is set if caller locked #me_rmutex. */
11334 mdb_reader_check0(MDB_env *env, int rlocked, int *dead)
11336 mdb_mutexref_t rmutex = rlocked ? NULL : env->me_rmutex;
11337 unsigned int i, j, rdrs;
11339 MDB_PID_T *pids, pid;
11340 int rc = MDB_SUCCESS, count = 0;
11342 rdrs = env->me_txns->mti_numreaders;
11343 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
11347 mr = env->me_txns->mti_readers;
11348 for (i=0; i<rdrs; i++) {
11349 pid = mr[i].mr_pid;
11350 if (pid && pid != env->me_pid) {
11351 if (mdb_pid_insert(pids, pid) == 0) {
11352 if (!mdb_reader_pid(env, Pidcheck, pid)) {
11353 /* Stale reader found */
11356 if ((rc = LOCK_MUTEX0(rmutex)) != 0) {
11357 if ((rc = mdb_mutex_failed(env, rmutex, rc)))
11359 rdrs = 0; /* the above checked all readers */
11361 /* Recheck, a new process may have reused pid */
11362 if (mdb_reader_pid(env, Pidcheck, pid))
11366 for (; j<rdrs; j++)
11367 if (mr[j].mr_pid == pid) {
11368 DPRINTF(("clear stale reader pid %u txn %"Yd,
11369 (unsigned) pid, mr[j].mr_txnid));
11374 UNLOCK_MUTEX(rmutex);
11385 #ifdef MDB_ROBUST_SUPPORTED
11386 /** Handle #LOCK_MUTEX0() failure.
11387 * Try to repair the lock file if the mutex owner died.
11388 * @param[in] env the environment handle
11389 * @param[in] mutex LOCK_MUTEX0() mutex
11390 * @param[in] rc LOCK_MUTEX0() error (nonzero)
11391 * @return 0 on success with the mutex locked, or an error code on failure.
11394 mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc)
11399 if (rc == MDB_OWNERDEAD) {
11400 /* We own the mutex. Clean up after dead previous owner. */
11402 rlocked = (mutex == env->me_rmutex);
11404 /* Keep mti_txnid updated, otherwise next writer can
11405 * overwrite data which latest meta page refers to.
11407 meta = mdb_env_pick_meta(env);
11408 env->me_txns->mti_txnid = meta->mm_txnid;
11409 /* env is hosed if the dead thread was ours */
11411 env->me_flags |= MDB_FATAL_ERROR;
11412 env->me_txn = NULL;
11416 DPRINTF(("%cmutex owner died, %s", (rlocked ? 'r' : 'w'),
11417 (rc ? "this process' env is hosed" : "recovering")));
11418 rc2 = mdb_reader_check0(env, rlocked, NULL);
11420 rc2 = mdb_mutex_consistent(mutex);
11421 if (rc || (rc = rc2)) {
11422 DPRINTF(("LOCK_MUTEX recovery failed, %s", mdb_strerror(rc)));
11423 UNLOCK_MUTEX(mutex);
11429 DPRINTF(("LOCK_MUTEX failed, %s", mdb_strerror(rc)));
11434 #endif /* MDB_ROBUST_SUPPORTED */
11436 #if defined(_WIN32)
11437 /** Convert \b src to new wchar_t[] string with room for \b xtra extra chars */
11439 utf8_to_utf16(const char *src, MDB_name *dst, int xtra)
11442 wchar_t *result = NULL;
11443 for (;;) { /* malloc result, then fill it in */
11444 need = MultiByteToWideChar(CP_UTF8, 0, src, -1, result, need);
11451 result = malloc(sizeof(wchar_t) * (need + xtra));
11456 dst->mn_alloced = 1;
11457 dst->mn_len = need - 1;
11458 dst->mn_val = result;
11459 return MDB_SUCCESS;
11462 #endif /* defined(_WIN32) */