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-2017 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. Using these APIs also means we must link to
52 * ntdll.dll, which is not linked by default in user code.
55 NtCreateSection(OUT PHANDLE sh, IN ACCESS_MASK acc,
56 IN void * oa OPTIONAL,
57 IN PLARGE_INTEGER ms OPTIONAL,
58 IN ULONG pp, IN ULONG aa, IN HANDLE fh OPTIONAL);
60 typedef enum _SECTION_INHERIT {
66 NtMapViewOfSection(IN PHANDLE sh, IN HANDLE ph,
67 IN OUT PVOID *addr, IN ULONG_PTR zbits,
68 IN SIZE_T cs, IN OUT PLARGE_INTEGER off OPTIONAL,
69 IN OUT PSIZE_T vs, IN SECTION_INHERIT ih,
70 IN ULONG at, IN ULONG pp);
75 /** getpid() returns int; MinGW defines pid_t but MinGW64 typedefs it
76 * as int64 which is wrong. MSVC doesn't define it at all, so just
80 #define MDB_THR_T DWORD
81 #include <sys/types.h>
84 # include <sys/param.h>
86 # define LITTLE_ENDIAN 1234
87 # define BIG_ENDIAN 4321
88 # define BYTE_ORDER LITTLE_ENDIAN
90 # define SSIZE_MAX INT_MAX
94 #include <sys/types.h>
96 #define MDB_PID_T pid_t
97 #define MDB_THR_T pthread_t
98 #include <sys/param.h>
100 #include <sys/mman.h>
101 #ifdef HAVE_SYS_FILE_H
102 #include <sys/file.h>
107 #if defined(__mips) && defined(__linux)
108 /* MIPS has cache coherency issues, requires explicit cache control */
109 #include <asm/cachectl.h>
110 extern int cacheflush(char *addr, int nbytes, int cache);
111 #define CACHEFLUSH(addr, bytes, cache) cacheflush(addr, bytes, cache)
113 #define CACHEFLUSH(addr, bytes, cache)
116 #if defined(__linux) && !defined(MDB_FDATASYNC_WORKS)
117 /** fdatasync is broken on ext3/ext4fs on older kernels, see
118 * description in #mdb_env_open2 comments. You can safely
119 * define MDB_FDATASYNC_WORKS if this code will only be run
120 * on kernels 3.6 and newer.
122 #define BROKEN_FDATASYNC
128 #include <inttypes.h>
136 typedef SSIZE_T ssize_t;
141 #if defined(__sun) || defined(ANDROID)
142 /* Most platforms have posix_memalign, older may only have memalign */
143 #define HAVE_MEMALIGN 1
147 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
148 #include <netinet/in.h>
149 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
152 #if defined(__APPLE__) || defined (BSD) || defined(__FreeBSD_kernel__)
153 # if !(defined(MDB_USE_POSIX_MUTEX) || defined(MDB_USE_POSIX_SEM))
154 # define MDB_USE_SYSV_SEM 1
156 # define MDB_FDATASYNC fsync
157 #elif defined(ANDROID)
158 # define MDB_FDATASYNC fsync
164 #ifdef MDB_USE_POSIX_SEM
165 # define MDB_USE_HASH 1
166 #include <semaphore.h>
167 #elif defined(MDB_USE_SYSV_SEM)
170 #ifdef _SEM_SEMUN_UNDEFINED
173 struct semid_ds *buf;
174 unsigned short *array;
176 #endif /* _SEM_SEMUN_UNDEFINED */
178 #define MDB_USE_POSIX_MUTEX 1
179 #endif /* MDB_USE_POSIX_SEM */
182 #if defined(_WIN32) + defined(MDB_USE_POSIX_SEM) + defined(MDB_USE_SYSV_SEM) \
183 + defined(MDB_USE_POSIX_MUTEX) != 1
184 # error "Ambiguous shared-lock implementation"
188 #include <valgrind/memcheck.h>
189 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
190 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
191 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
192 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
193 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
195 #define VGMEMP_CREATE(h,r,z)
196 #define VGMEMP_ALLOC(h,a,s)
197 #define VGMEMP_FREE(h,a)
198 #define VGMEMP_DESTROY(h)
199 #define VGMEMP_DEFINED(a,s)
203 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
204 /* Solaris just defines one or the other */
205 # define LITTLE_ENDIAN 1234
206 # define BIG_ENDIAN 4321
207 # ifdef _LITTLE_ENDIAN
208 # define BYTE_ORDER LITTLE_ENDIAN
210 # define BYTE_ORDER BIG_ENDIAN
213 # define BYTE_ORDER __BYTE_ORDER
217 #ifndef LITTLE_ENDIAN
218 #define LITTLE_ENDIAN __LITTLE_ENDIAN
221 #define BIG_ENDIAN __BIG_ENDIAN
224 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
225 #define MISALIGNED_OK 1
231 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
232 # error "Unknown or unsupported endianness (BYTE_ORDER)"
233 #elif (-6 & 5) || CHAR_BIT!=8 || UINT_MAX!=0xffffffff || MDB_SIZE_MAX%UINT_MAX
234 # error "Two's complement, reasonably sized integer types, please"
238 /** Put infrequently used env functions in separate section */
240 # define ESECT __attribute__ ((section("__TEXT,text_env")))
242 # define ESECT __attribute__ ((section("text_env")))
249 #define CALL_CONV WINAPI
254 /** @defgroup internal LMDB Internals
257 /** @defgroup compat Compatibility Macros
258 * A bunch of macros to minimize the amount of platform-specific ifdefs
259 * needed throughout the rest of the code. When the features this library
260 * needs are similar enough to POSIX to be hidden in a one-or-two line
261 * replacement, this macro approach is used.
265 /** Features under development */
270 /** Wrapper around __func__, which is a C99 feature */
271 #if __STDC_VERSION__ >= 199901L
272 # define mdb_func_ __func__
273 #elif __GNUC__ >= 2 || _MSC_VER >= 1300
274 # define mdb_func_ __FUNCTION__
276 /* If a debug message says <mdb_unknown>(), update the #if statements above */
277 # define mdb_func_ "<mdb_unknown>"
280 /* Internal error codes, not exposed outside liblmdb */
281 #define MDB_NO_ROOT (MDB_LAST_ERRCODE + 10)
283 #define MDB_OWNERDEAD ((int) WAIT_ABANDONED)
284 #elif defined MDB_USE_SYSV_SEM
285 #define MDB_OWNERDEAD (MDB_LAST_ERRCODE + 11)
286 #elif defined(MDB_USE_POSIX_MUTEX) && defined(EOWNERDEAD)
287 #define MDB_OWNERDEAD EOWNERDEAD /**< #LOCK_MUTEX0() result if dead owner */
291 #define GLIBC_VER ((__GLIBC__ << 16 )| __GLIBC_MINOR__)
293 /** Some platforms define the EOWNERDEAD error code
294 * even though they don't support Robust Mutexes.
295 * Compile with -DMDB_USE_ROBUST=0, or use some other
296 * mechanism like -DMDB_USE_SYSV_SEM instead of
297 * -DMDB_USE_POSIX_MUTEX. (SysV semaphores are
298 * also Robust, but some systems don't support them
301 #ifndef MDB_USE_ROBUST
302 /* Android currently lacks Robust Mutex support. So does glibc < 2.4. */
303 # if defined(MDB_USE_POSIX_MUTEX) && (defined(ANDROID) || \
304 (defined(__GLIBC__) && GLIBC_VER < 0x020004))
305 # define MDB_USE_ROBUST 0
307 # define MDB_USE_ROBUST 1
309 #endif /* !MDB_USE_ROBUST */
311 #if defined(MDB_USE_POSIX_MUTEX) && (MDB_USE_ROBUST)
312 /* glibc < 2.12 only provided _np API */
313 # if (defined(__GLIBC__) && GLIBC_VER < 0x02000c) || \
314 (defined(PTHREAD_MUTEX_ROBUST_NP) && !defined(PTHREAD_MUTEX_ROBUST))
315 # define PTHREAD_MUTEX_ROBUST PTHREAD_MUTEX_ROBUST_NP
316 # define pthread_mutexattr_setrobust(attr, flag) pthread_mutexattr_setrobust_np(attr, flag)
317 # define pthread_mutex_consistent(mutex) pthread_mutex_consistent_np(mutex)
319 #endif /* MDB_USE_POSIX_MUTEX && MDB_USE_ROBUST */
321 #if defined(MDB_OWNERDEAD) && (MDB_USE_ROBUST)
322 #define MDB_ROBUST_SUPPORTED 1
326 #define MDB_USE_HASH 1
327 #define MDB_PIDLOCK 0
328 #define THREAD_RET DWORD
329 #define pthread_t HANDLE
330 #define pthread_mutex_t HANDLE
331 #define pthread_cond_t HANDLE
332 typedef HANDLE mdb_mutex_t, mdb_mutexref_t;
333 #define pthread_key_t DWORD
334 #define pthread_self() GetCurrentThreadId()
335 #define pthread_key_create(x,y) \
336 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
337 #define pthread_key_delete(x) TlsFree(x)
338 #define pthread_getspecific(x) TlsGetValue(x)
339 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
340 #define pthread_mutex_unlock(x) ReleaseMutex(*x)
341 #define pthread_mutex_lock(x) WaitForSingleObject(*x, INFINITE)
342 #define pthread_cond_signal(x) SetEvent(*x)
343 #define pthread_cond_wait(cond,mutex) do{SignalObjectAndWait(*mutex, *cond, INFINITE, FALSE); WaitForSingleObject(*mutex, INFINITE);}while(0)
344 #define THREAD_CREATE(thr,start,arg) \
345 (((thr) = CreateThread(NULL, 0, start, arg, 0, NULL)) ? 0 : ErrCode())
346 #define THREAD_FINISH(thr) \
347 (WaitForSingleObject(thr, INFINITE) ? ErrCode() : 0)
348 #define LOCK_MUTEX0(mutex) WaitForSingleObject(mutex, INFINITE)
349 #define UNLOCK_MUTEX(mutex) ReleaseMutex(mutex)
350 #define mdb_mutex_consistent(mutex) 0
351 #define getpid() GetCurrentProcessId()
352 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
353 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
354 #define ErrCode() GetLastError()
355 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
356 #define close(fd) (CloseHandle(fd) ? 0 : -1)
357 #define munmap(ptr,len) UnmapViewOfFile(ptr)
358 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
359 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
361 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
364 #define THREAD_RET void *
365 #define THREAD_CREATE(thr,start,arg) pthread_create(&thr,NULL,start,arg)
366 #define THREAD_FINISH(thr) pthread_join(thr,NULL)
368 /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
369 #define MDB_PIDLOCK 1
371 #ifdef MDB_USE_POSIX_SEM
373 typedef sem_t *mdb_mutex_t, *mdb_mutexref_t;
374 #define LOCK_MUTEX0(mutex) mdb_sem_wait(mutex)
375 #define UNLOCK_MUTEX(mutex) sem_post(mutex)
378 mdb_sem_wait(sem_t *sem)
381 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
385 #elif defined MDB_USE_SYSV_SEM
387 typedef struct mdb_mutex {
391 } mdb_mutex_t[1], *mdb_mutexref_t;
393 #define LOCK_MUTEX0(mutex) mdb_sem_wait(mutex)
394 #define UNLOCK_MUTEX(mutex) do { \
395 struct sembuf sb = { 0, 1, SEM_UNDO }; \
396 sb.sem_num = (mutex)->semnum; \
397 *(mutex)->locked = 0; \
398 semop((mutex)->semid, &sb, 1); \
402 mdb_sem_wait(mdb_mutexref_t sem)
404 int rc, *locked = sem->locked;
405 struct sembuf sb = { 0, -1, SEM_UNDO };
406 sb.sem_num = sem->semnum;
408 if (!semop(sem->semid, &sb, 1)) {
409 rc = *locked ? MDB_OWNERDEAD : MDB_SUCCESS;
413 } while ((rc = errno) == EINTR);
417 #define mdb_mutex_consistent(mutex) 0
419 #else /* MDB_USE_POSIX_MUTEX: */
420 /** Shared mutex/semaphore as the original is stored.
422 * Not for copies. Instead it can be assigned to an #mdb_mutexref_t.
423 * When mdb_mutexref_t is a pointer and mdb_mutex_t is not, then it
424 * is array[size 1] so it can be assigned to the pointer.
426 typedef pthread_mutex_t mdb_mutex_t[1];
427 /** Reference to an #mdb_mutex_t */
428 typedef pthread_mutex_t *mdb_mutexref_t;
429 /** Lock the reader or writer mutex.
430 * Returns 0 or a code to give #mdb_mutex_failed(), as in #LOCK_MUTEX().
432 #define LOCK_MUTEX0(mutex) pthread_mutex_lock(mutex)
433 /** Unlock the reader or writer mutex.
435 #define UNLOCK_MUTEX(mutex) pthread_mutex_unlock(mutex)
436 /** Mark mutex-protected data as repaired, after death of previous owner.
438 #define mdb_mutex_consistent(mutex) pthread_mutex_consistent(mutex)
439 #endif /* MDB_USE_POSIX_SEM || MDB_USE_SYSV_SEM */
441 /** Get the error code for the last failed system function.
443 #define ErrCode() errno
445 /** An abstraction for a file handle.
446 * On POSIX systems file handles are small integers. On Windows
447 * they're opaque pointers.
451 /** A value for an invalid file handle.
452 * Mainly used to initialize file variables and signify that they are
455 #define INVALID_HANDLE_VALUE (-1)
457 /** Get the size of a memory page for the system.
458 * This is the basic size that the platform's memory manager uses, and is
459 * fundamental to the use of memory-mapped files.
461 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
464 #define Z MDB_FMT_Z /**< printf/scanf format modifier for size_t */
465 #define Yu MDB_PRIy(u) /**< printf format for #mdb_size_t */
466 #define Yd MDB_PRIy(d) /**< printf format for 'signed #mdb_size_t' */
468 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
470 #elif defined(MDB_USE_SYSV_SEM)
471 #define MNAME_LEN (sizeof(int))
473 #define MNAME_LEN (sizeof(pthread_mutex_t))
476 #ifdef MDB_USE_SYSV_SEM
477 #define SYSV_SEM_FLAG 1 /**< SysV sems in lockfile format */
479 #define SYSV_SEM_FLAG 0
484 #ifdef MDB_ROBUST_SUPPORTED
485 /** Lock mutex, handle any error, set rc = result.
486 * Return 0 on success, nonzero (not rc) on error.
488 #define LOCK_MUTEX(rc, env, mutex) \
489 (((rc) = LOCK_MUTEX0(mutex)) && \
490 ((rc) = mdb_mutex_failed(env, mutex, rc)))
491 static int mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc);
493 #define LOCK_MUTEX(rc, env, mutex) ((rc) = LOCK_MUTEX0(mutex))
494 #define mdb_mutex_failed(env, mutex, rc) (rc)
498 /** A flag for opening a file and requesting synchronous data writes.
499 * This is only used when writing a meta page. It's not strictly needed;
500 * we could just do a normal write and then immediately perform a flush.
501 * But if this flag is available it saves us an extra system call.
503 * @note If O_DSYNC is undefined but exists in /usr/include,
504 * preferably set some compiler flag to get the definition.
508 # define MDB_DSYNC O_DSYNC
510 # define MDB_DSYNC O_SYNC
515 /** Function for flushing the data of a file. Define this to fsync
516 * if fdatasync() is not supported.
518 #ifndef MDB_FDATASYNC
519 # define MDB_FDATASYNC fdatasync
523 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
534 /** A page number in the database.
535 * Note that 64 bit page numbers are overkill, since pages themselves
536 * already represent 12-13 bits of addressable memory, and the OS will
537 * always limit applications to a maximum of 63 bits of address space.
539 * @note In the #MDB_node structure, we only store 48 bits of this value,
540 * which thus limits us to only 60 bits of addressable data.
542 typedef MDB_ID pgno_t;
544 /** A transaction ID.
545 * See struct MDB_txn.mt_txnid for details.
547 typedef MDB_ID txnid_t;
549 /** @defgroup debug Debug Macros
553 /** Enable debug output. Needs variable argument macros (a C99 feature).
554 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
555 * read from and written to the database (used for free space management).
561 static int mdb_debug;
562 static txnid_t mdb_debug_start;
564 /** Print a debug message with printf formatting.
565 * Requires double parenthesis around 2 or more args.
567 # define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
568 # define DPRINTF0(fmt, ...) \
569 fprintf(stderr, "%s:%d " fmt "\n", mdb_func_, __LINE__, __VA_ARGS__)
571 # define DPRINTF(args) ((void) 0)
573 /** Print a debug string.
574 * The string is printed literally, with no format processing.
576 #define DPUTS(arg) DPRINTF(("%s", arg))
577 /** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
579 (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
582 /** @brief The maximum size of a database page.
584 * It is 32k or 64k, since value-PAGEBASE must fit in
585 * #MDB_page.%mp_upper.
587 * LMDB will use database pages < OS pages if needed.
588 * That causes more I/O in write transactions: The OS must
589 * know (read) the whole page before writing a partial page.
591 * Note that we don't currently support Huge pages. On Linux,
592 * regular data files cannot use Huge pages, and in general
593 * Huge pages aren't actually pageable. We rely on the OS
594 * demand-pager to read our data and page it out when memory
595 * pressure from other processes is high. So until OSs have
596 * actual paging support for Huge pages, they're not viable.
598 #define MAX_PAGESIZE (PAGEBASE ? 0x10000 : 0x8000)
600 /** The minimum number of keys required in a database page.
601 * Setting this to a larger value will place a smaller bound on the
602 * maximum size of a data item. Data items larger than this size will
603 * be pushed into overflow pages instead of being stored directly in
604 * the B-tree node. This value used to default to 4. With a page size
605 * of 4096 bytes that meant that any item larger than 1024 bytes would
606 * go into an overflow page. That also meant that on average 2-3KB of
607 * each overflow page was wasted space. The value cannot be lower than
608 * 2 because then there would no longer be a tree structure. With this
609 * value, items larger than 2KB will go into overflow pages, and on
610 * average only 1KB will be wasted.
612 #define MDB_MINKEYS 2
614 /** A stamp that identifies a file as an LMDB file.
615 * There's nothing special about this value other than that it is easily
616 * recognizable, and it will reflect any byte order mismatches.
618 #define MDB_MAGIC 0xBEEFC0DE
620 /** The version number for a database's datafile format. */
621 #define MDB_DATA_VERSION ((MDB_DEVEL) ? 999 : 1)
622 /** The version number for a database's lockfile format. */
623 #define MDB_LOCK_VERSION ((MDB_DEVEL) ? 999 : 2)
625 /** @brief The max size of a key we can write, or 0 for computed max.
627 * This macro should normally be left alone or set to 0.
628 * Note that a database with big keys or dupsort data cannot be
629 * reliably modified by a liblmdb which uses a smaller max.
630 * The default is 511 for backwards compat, or 0 when #MDB_DEVEL.
632 * Other values are allowed, for backwards compat. However:
633 * A value bigger than the computed max can break if you do not
634 * know what you are doing, and liblmdb <= 0.9.10 can break when
635 * modifying a DB with keys/dupsort data bigger than its max.
637 * Data items in an #MDB_DUPSORT database are also limited to
638 * this size, since they're actually keys of a sub-DB. Keys and
639 * #MDB_DUPSORT data items must fit on a node in a regular page.
641 #ifndef MDB_MAXKEYSIZE
642 #define MDB_MAXKEYSIZE ((MDB_DEVEL) ? 0 : 511)
645 /** The maximum size of a key we can write to the environment. */
647 #define ENV_MAXKEY(env) (MDB_MAXKEYSIZE)
649 #define ENV_MAXKEY(env) ((env)->me_maxkey)
652 /** @brief The maximum size of a data item.
654 * We only store a 32 bit value for node sizes.
656 #define MAXDATASIZE 0xffffffffUL
659 /** Key size which fits in a #DKBUF.
662 #define DKBUF_MAXKEYSIZE ((MDB_MAXKEYSIZE) > 0 ? (MDB_MAXKEYSIZE) : 511)
665 * This is used for printing a hex dump of a key's contents.
667 #define DKBUF char kbuf[DKBUF_MAXKEYSIZE*2+1]
668 /** Display a key in hex.
670 * Invoke a function to display a key in hex.
672 #define DKEY(x) mdb_dkey(x, kbuf)
678 /** An invalid page number.
679 * Mainly used to denote an empty tree.
681 #define P_INVALID (~(pgno_t)0)
683 /** Test if the flags \b f are set in a flag word \b w. */
684 #define F_ISSET(w, f) (((w) & (f)) == (f))
686 /** Round \b n up to an even number. */
687 #define EVEN(n) (((n) + 1U) & -2) /* sign-extending -2 to match n+1U */
689 /** Used for offsets within a single page.
690 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
693 typedef uint16_t indx_t;
695 /** Default size of memory map.
696 * This is certainly too small for any actual applications. Apps should always set
697 * the size explicitly using #mdb_env_set_mapsize().
699 #define DEFAULT_MAPSIZE 1048576
701 /** @defgroup readers Reader Lock Table
702 * Readers don't acquire any locks for their data access. Instead, they
703 * simply record their transaction ID in the reader table. The reader
704 * mutex is needed just to find an empty slot in the reader table. The
705 * slot's address is saved in thread-specific data so that subsequent read
706 * transactions started by the same thread need no further locking to proceed.
708 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
710 * No reader table is used if the database is on a read-only filesystem, or
711 * if #MDB_NOLOCK is set.
713 * Since the database uses multi-version concurrency control, readers don't
714 * actually need any locking. This table is used to keep track of which
715 * readers are using data from which old transactions, so that we'll know
716 * when a particular old transaction is no longer in use. Old transactions
717 * that have discarded any data pages can then have those pages reclaimed
718 * for use by a later write transaction.
720 * The lock table is constructed such that reader slots are aligned with the
721 * processor's cache line size. Any slot is only ever used by one thread.
722 * This alignment guarantees that there will be no contention or cache
723 * thrashing as threads update their own slot info, and also eliminates
724 * any need for locking when accessing a slot.
726 * A writer thread will scan every slot in the table to determine the oldest
727 * outstanding reader transaction. Any freed pages older than this will be
728 * reclaimed by the writer. The writer doesn't use any locks when scanning
729 * this table. This means that there's no guarantee that the writer will
730 * see the most up-to-date reader info, but that's not required for correct
731 * operation - all we need is to know the upper bound on the oldest reader,
732 * we don't care at all about the newest reader. So the only consequence of
733 * reading stale information here is that old pages might hang around a
734 * while longer before being reclaimed. That's actually good anyway, because
735 * the longer we delay reclaiming old pages, the more likely it is that a
736 * string of contiguous pages can be found after coalescing old pages from
737 * many old transactions together.
740 /** Number of slots in the reader table.
741 * This value was chosen somewhat arbitrarily. 126 readers plus a
742 * couple mutexes fit exactly into 8KB on my development machine.
743 * Applications should set the table size using #mdb_env_set_maxreaders().
745 #define DEFAULT_READERS 126
747 /** The size of a CPU cache line in bytes. We want our lock structures
748 * aligned to this size to avoid false cache line sharing in the
750 * This value works for most CPUs. For Itanium this should be 128.
756 /** The information we store in a single slot of the reader table.
757 * In addition to a transaction ID, we also record the process and
758 * thread ID that owns a slot, so that we can detect stale information,
759 * e.g. threads or processes that went away without cleaning up.
760 * @note We currently don't check for stale records. We simply re-init
761 * the table when we know that we're the only process opening the
764 typedef struct MDB_rxbody {
765 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
766 * Multiple readers that start at the same time will probably have the
767 * same ID here. Again, it's not important to exclude them from
768 * anything; all we need to know is which version of the DB they
769 * started from so we can avoid overwriting any data used in that
770 * particular version.
772 volatile txnid_t mrb_txnid;
773 /** The process ID of the process owning this reader txn. */
774 volatile MDB_PID_T mrb_pid;
775 /** The thread ID of the thread owning this txn. */
776 volatile MDB_THR_T mrb_tid;
779 /** The actual reader record, with cacheline padding. */
780 typedef struct MDB_reader {
783 /** shorthand for mrb_txnid */
784 #define mr_txnid mru.mrx.mrb_txnid
785 #define mr_pid mru.mrx.mrb_pid
786 #define mr_tid mru.mrx.mrb_tid
787 /** cache line alignment */
788 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
792 /** The header for the reader table.
793 * The table resides in a memory-mapped file. (This is a different file
794 * than is used for the main database.)
796 * For POSIX the actual mutexes reside in the shared memory of this
797 * mapped file. On Windows, mutexes are named objects allocated by the
798 * kernel; we store the mutex names in this mapped file so that other
799 * processes can grab them. This same approach is also used on
800 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
801 * process-shared POSIX mutexes. For these cases where a named object
802 * is used, the object name is derived from a 64 bit FNV hash of the
803 * environment pathname. As such, naming collisions are extremely
804 * unlikely. If a collision occurs, the results are unpredictable.
806 typedef struct MDB_txbody {
807 /** Stamp identifying this as an LMDB file. It must be set
810 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
812 /** The ID of the last transaction committed to the database.
813 * This is recorded here only for convenience; the value can always
814 * be determined by reading the main database meta pages.
816 volatile txnid_t mtb_txnid;
817 /** The number of slots that have been used in the reader table.
818 * This always records the maximum count, it is not decremented
819 * when readers release their slots.
821 volatile unsigned mtb_numreaders;
822 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
823 char mtb_rmname[MNAME_LEN];
824 #elif defined(MDB_USE_SYSV_SEM)
828 /** Mutex protecting access to this table.
829 * This is the reader table lock used with LOCK_MUTEX().
831 mdb_mutex_t mtb_rmutex;
835 /** The actual reader table definition. */
836 typedef struct MDB_txninfo {
839 #define mti_magic mt1.mtb.mtb_magic
840 #define mti_format mt1.mtb.mtb_format
841 #define mti_rmutex mt1.mtb.mtb_rmutex
842 #define mti_rmname mt1.mtb.mtb_rmname
843 #define mti_txnid mt1.mtb.mtb_txnid
844 #define mti_numreaders mt1.mtb.mtb_numreaders
845 #ifdef MDB_USE_SYSV_SEM
846 #define mti_semid mt1.mtb.mtb_semid
847 #define mti_rlocked mt1.mtb.mtb_rlocked
849 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
852 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
853 char mt2_wmname[MNAME_LEN];
854 #define mti_wmname mt2.mt2_wmname
855 #elif defined MDB_USE_SYSV_SEM
857 #define mti_wlocked mt2.mt2_wlocked
859 mdb_mutex_t mt2_wmutex;
860 #define mti_wmutex mt2.mt2_wmutex
862 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
864 MDB_reader mti_readers[1];
867 /** Lockfile format signature: version, features and field layout */
868 #define MDB_LOCK_FORMAT \
870 ((MDB_LOCK_VERSION) \
871 /* Flags which describe functionality */ \
872 + (SYSV_SEM_FLAG << 18) \
873 + (((MDB_PIDLOCK) != 0) << 16)))
876 /** Common header for all page types. The page type depends on #mp_flags.
878 * #P_BRANCH and #P_LEAF pages have unsorted '#MDB_node's at the end, with
879 * sorted #mp_ptrs[] entries referring to them. Exception: #P_LEAF2 pages
880 * omit mp_ptrs and pack sorted #MDB_DUPFIXED values after the page header.
882 * #P_OVERFLOW records occupy one or more contiguous pages where only the
883 * first has a page header. They hold the real data of #F_BIGDATA nodes.
885 * #P_SUBP sub-pages are small leaf "pages" with duplicate data.
886 * A node with flag #F_DUPDATA but not #F_SUBDATA contains a sub-page.
887 * (Duplicate data can also go in sub-databases, which use normal pages.)
889 * #P_META pages contain #MDB_meta, the start point of an LMDB snapshot.
891 * Each non-metapage up to #MDB_meta.%mm_last_pg is reachable exactly once
892 * in the snapshot: Either used by a database or listed in a freeDB record.
894 typedef struct MDB_page {
895 #define mp_pgno mp_p.p_pgno
896 #define mp_next mp_p.p_next
898 pgno_t p_pgno; /**< page number */
899 struct MDB_page *p_next; /**< for in-memory list of freed pages */
901 uint16_t mp_pad; /**< key size if this is a LEAF2 page */
902 /** @defgroup mdb_page Page Flags
904 * Flags for the page headers.
907 #define P_BRANCH 0x01 /**< branch page */
908 #define P_LEAF 0x02 /**< leaf page */
909 #define P_OVERFLOW 0x04 /**< overflow page */
910 #define P_META 0x08 /**< meta page */
911 #define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
912 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
913 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
914 #define P_LOOSE 0x4000 /**< page was dirtied then freed, can be reused */
915 #define P_KEEP 0x8000 /**< leave this page alone during spill */
917 uint16_t mp_flags; /**< @ref mdb_page */
918 #define mp_lower mp_pb.pb.pb_lower
919 #define mp_upper mp_pb.pb.pb_upper
920 #define mp_pages mp_pb.pb_pages
923 indx_t pb_lower; /**< lower bound of free space */
924 indx_t pb_upper; /**< upper bound of free space */
926 uint32_t pb_pages; /**< number of overflow pages */
928 indx_t mp_ptrs[1]; /**< dynamic size */
931 /** Size of the page header, excluding dynamic data at the end */
932 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
934 /** Address of first usable data byte in a page, after the header */
935 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
937 /** ITS#7713, change PAGEBASE to handle 65536 byte pages */
938 #define PAGEBASE ((MDB_DEVEL) ? PAGEHDRSZ : 0)
940 /** Number of nodes on a page */
941 #define NUMKEYS(p) (((p)->mp_lower - (PAGEHDRSZ-PAGEBASE)) >> 1)
943 /** The amount of space remaining in the page */
944 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
946 /** The percentage of space used in the page, in tenths of a percent. */
947 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
948 ((env)->me_psize - PAGEHDRSZ))
949 /** The minimum page fill factor, in tenths of a percent.
950 * Pages emptier than this are candidates for merging.
952 #define FILL_THRESHOLD 250
954 /** Test if a page is a leaf page */
955 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
956 /** Test if a page is a LEAF2 page */
957 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
958 /** Test if a page is a branch page */
959 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
960 /** Test if a page is an overflow page */
961 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
962 /** Test if a page is a sub page */
963 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
965 /** The number of overflow pages needed to store the given size. */
966 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
968 /** Link in #MDB_txn.%mt_loose_pgs list.
969 * Kept outside the page header, which is needed when reusing the page.
971 #define NEXT_LOOSE_PAGE(p) (*(MDB_page **)((p) + 2))
973 /** Header for a single key/data pair within a page.
974 * Used in pages of type #P_BRANCH and #P_LEAF without #P_LEAF2.
975 * We guarantee 2-byte alignment for 'MDB_node's.
977 * #mn_lo and #mn_hi are used for data size on leaf nodes, and for child
978 * pgno on branch nodes. On 64 bit platforms, #mn_flags is also used
979 * for pgno. (Branch nodes have no flags). Lo and hi are in host byte
980 * order in case some accesses can be optimized to 32-bit word access.
982 * Leaf node flags describe node contents. #F_BIGDATA says the node's
983 * data part is the page number of an overflow page with actual data.
984 * #F_DUPDATA and #F_SUBDATA can be combined giving duplicate data in
985 * a sub-page/sub-database, and named databases (just #F_SUBDATA).
987 typedef struct MDB_node {
988 /** part of data size or pgno
990 #if BYTE_ORDER == LITTLE_ENDIAN
991 unsigned short mn_lo, mn_hi;
993 unsigned short mn_hi, mn_lo;
996 /** @defgroup mdb_node Node Flags
998 * Flags for node headers.
1001 #define F_BIGDATA 0x01 /**< data put on overflow page */
1002 #define F_SUBDATA 0x02 /**< data is a sub-database */
1003 #define F_DUPDATA 0x04 /**< data has duplicates */
1005 /** valid flags for #mdb_node_add() */
1006 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
1009 unsigned short mn_flags; /**< @ref mdb_node */
1010 unsigned short mn_ksize; /**< key size */
1011 char mn_data[1]; /**< key and data are appended here */
1014 /** Size of the node header, excluding dynamic data at the end */
1015 #define NODESIZE offsetof(MDB_node, mn_data)
1017 /** Bit position of top word in page number, for shifting mn_flags */
1018 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
1020 /** Size of a node in a branch page with a given key.
1021 * This is just the node header plus the key, there is no data.
1023 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
1025 /** Size of a node in a leaf page with a given key and data.
1026 * This is node header plus key plus data size.
1028 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
1030 /** Address of node \b i in page \b p */
1031 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i] + PAGEBASE))
1033 /** Address of the key for the node */
1034 #define NODEKEY(node) (void *)((node)->mn_data)
1036 /** Address of the data for a node */
1037 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
1039 /** Get the page number pointed to by a branch node */
1040 #define NODEPGNO(node) \
1041 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
1042 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
1043 /** Set the page number in a branch node */
1044 #define SETPGNO(node,pgno) do { \
1045 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
1046 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
1048 /** Get the size of the data in a leaf node */
1049 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
1050 /** Set the size of the data for a leaf node */
1051 #define SETDSZ(node,size) do { \
1052 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
1053 /** The size of a key in a node */
1054 #define NODEKSZ(node) ((node)->mn_ksize)
1056 /** Copy a page number from src to dst */
1057 #ifdef MISALIGNED_OK
1058 #define COPY_PGNO(dst,src) dst = src
1060 #if MDB_SIZE_MAX > 0xffffffffU
1061 #define COPY_PGNO(dst,src) do { \
1062 unsigned short *s, *d; \
1063 s = (unsigned short *)&(src); \
1064 d = (unsigned short *)&(dst); \
1071 #define COPY_PGNO(dst,src) do { \
1072 unsigned short *s, *d; \
1073 s = (unsigned short *)&(src); \
1074 d = (unsigned short *)&(dst); \
1080 /** The address of a key in a LEAF2 page.
1081 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
1082 * There are no node headers, keys are stored contiguously.
1084 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
1086 /** Set the \b node's key into \b keyptr, if requested. */
1087 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
1088 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
1090 /** Set the \b node's key into \b key. */
1091 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
1093 /** Information about a single database in the environment. */
1094 typedef struct MDB_db {
1095 uint32_t md_pad; /**< also ksize for LEAF2 pages */
1096 uint16_t md_flags; /**< @ref mdb_dbi_open */
1097 uint16_t md_depth; /**< depth of this tree */
1098 pgno_t md_branch_pages; /**< number of internal pages */
1099 pgno_t md_leaf_pages; /**< number of leaf pages */
1100 pgno_t md_overflow_pages; /**< number of overflow pages */
1101 mdb_size_t md_entries; /**< number of data items */
1102 pgno_t md_root; /**< the root page of this tree */
1105 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
1106 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
1107 /** #mdb_dbi_open() flags */
1108 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
1109 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
1111 /** Handle for the DB used to track free pages. */
1113 /** Handle for the default DB. */
1115 /** Number of DBs in metapage (free and main) - also hardcoded elsewhere */
1118 /** Number of meta pages - also hardcoded elsewhere */
1121 /** Meta page content.
1122 * A meta page is the start point for accessing a database snapshot.
1123 * Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
1125 typedef struct MDB_meta {
1126 /** Stamp identifying this as an LMDB file. It must be set
1129 /** Version number of this file. Must be set to #MDB_DATA_VERSION. */
1130 uint32_t mm_version;
1132 union { /* always zero since we don't support fixed mapping in MDB_VL32 */
1136 #define mm_address mm_un.mmun_address
1138 void *mm_address; /**< address for fixed mapping */
1140 mdb_size_t mm_mapsize; /**< size of mmap region */
1141 MDB_db mm_dbs[CORE_DBS]; /**< first is free space, 2nd is main db */
1142 /** The size of pages used in this DB */
1143 #define mm_psize mm_dbs[FREE_DBI].md_pad
1144 /** Any persistent environment flags. @ref mdb_env */
1145 #define mm_flags mm_dbs[FREE_DBI].md_flags
1146 /** Last used page in the datafile.
1147 * Actually the file may be shorter if the freeDB lists the final pages.
1150 volatile txnid_t mm_txnid; /**< txnid that committed this page */
1153 /** Buffer for a stack-allocated meta page.
1154 * The members define size and alignment, and silence type
1155 * aliasing warnings. They are not used directly; that could
1156 * mean incorrectly using several union members in parallel.
1158 typedef union MDB_metabuf {
1161 char mm_pad[PAGEHDRSZ];
1166 /** Auxiliary DB info.
1167 * The information here is mostly static/read-only. There is
1168 * only a single copy of this record in the environment.
1170 typedef struct MDB_dbx {
1171 MDB_val md_name; /**< name of the database */
1172 MDB_cmp_func *md_cmp; /**< function for comparing keys */
1173 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
1174 MDB_rel_func *md_rel; /**< user relocate function */
1175 void *md_relctx; /**< user-provided context for md_rel */
1178 /** A database transaction.
1179 * Every operation requires a transaction handle.
1182 MDB_txn *mt_parent; /**< parent of a nested txn */
1183 /** Nested txn under this txn, set together with flag #MDB_TXN_HAS_CHILD */
1185 pgno_t mt_next_pgno; /**< next unallocated page */
1187 pgno_t mt_last_pgno; /**< last written page */
1189 /** The ID of this transaction. IDs are integers incrementing from 1.
1190 * Only committed write transactions increment the ID. If a transaction
1191 * aborts, the ID may be re-used by the next writer.
1194 MDB_env *mt_env; /**< the DB environment */
1195 /** The list of pages that became unused during this transaction.
1197 MDB_IDL mt_free_pgs;
1198 /** The list of loose pages that became unused and may be reused
1199 * in this transaction, linked through #NEXT_LOOSE_PAGE(page).
1201 MDB_page *mt_loose_pgs;
1202 /** Number of loose pages (#mt_loose_pgs) */
1204 /** The sorted list of dirty pages we temporarily wrote to disk
1205 * because the dirty list was full. page numbers in here are
1206 * shifted left by 1, deleted slots have the LSB set.
1208 MDB_IDL mt_spill_pgs;
1210 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
1211 MDB_ID2L dirty_list;
1212 /** For read txns: This thread/txn's reader table slot, or NULL. */
1215 /** Array of records for each DB known in the environment. */
1217 /** Array of MDB_db records for each known DB */
1219 /** Array of sequence numbers for each DB handle */
1220 unsigned int *mt_dbiseqs;
1221 /** @defgroup mt_dbflag Transaction DB Flags
1225 #define DB_DIRTY 0x01 /**< DB was written in this txn */
1226 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
1227 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
1228 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
1229 #define DB_USRVALID 0x10 /**< As #DB_VALID, but not set for #FREE_DBI */
1230 #define DB_DUPDATA 0x20 /**< DB is #MDB_DUPSORT data */
1232 /** In write txns, array of cursors for each DB */
1233 MDB_cursor **mt_cursors;
1234 /** Array of flags for each DB */
1235 unsigned char *mt_dbflags;
1237 /** List of read-only pages (actually chunks) */
1239 /** We map chunks of 16 pages. Even though Windows uses 4KB pages, all
1240 * mappings must begin on 64KB boundaries. So we round off all pgnos to
1241 * a chunk boundary. We do the same on Linux for symmetry, and also to
1242 * reduce the frequency of mmap/munmap calls.
1244 #define MDB_RPAGE_CHUNK 16
1245 #define MDB_TRPAGE_SIZE 4096 /**< size of #mt_rpages array of chunks */
1246 #define MDB_TRPAGE_MAX (MDB_TRPAGE_SIZE-1) /**< maximum chunk index */
1247 unsigned int mt_rpcheck; /**< threshold for reclaiming unref'd chunks */
1249 /** Number of DB records in use, or 0 when the txn is finished.
1250 * This number only ever increments until the txn finishes; we
1251 * don't decrement it when individual DB handles are closed.
1255 /** @defgroup mdb_txn Transaction Flags
1259 /** #mdb_txn_begin() flags */
1260 #define MDB_TXN_BEGIN_FLAGS (MDB_NOMETASYNC|MDB_NOSYNC|MDB_RDONLY)
1261 #define MDB_TXN_NOMETASYNC MDB_NOMETASYNC /**< don't sync meta for this txn on commit */
1262 #define MDB_TXN_NOSYNC MDB_NOSYNC /**< don't sync this txn on commit */
1263 #define MDB_TXN_RDONLY MDB_RDONLY /**< read-only transaction */
1264 /* internal txn flags */
1265 #define MDB_TXN_WRITEMAP MDB_WRITEMAP /**< copy of #MDB_env flag in writers */
1266 #define MDB_TXN_FINISHED 0x01 /**< txn is finished or never began */
1267 #define MDB_TXN_ERROR 0x02 /**< txn is unusable after an error */
1268 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
1269 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
1270 #define MDB_TXN_HAS_CHILD 0x10 /**< txn has an #MDB_txn.%mt_child */
1271 /** most operations on the txn are currently illegal */
1272 #define MDB_TXN_BLOCKED (MDB_TXN_FINISHED|MDB_TXN_ERROR|MDB_TXN_HAS_CHILD)
1274 unsigned int mt_flags; /**< @ref mdb_txn */
1275 /** #dirty_list room: Array size - \#dirty pages visible to this txn.
1276 * Includes ancestor txns' dirty pages not hidden by other txns'
1277 * dirty/spilled pages. Thus commit(nested txn) has room to merge
1278 * dirty_list into mt_parent after freeing hidden mt_parent pages.
1280 unsigned int mt_dirty_room;
1283 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
1284 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
1285 * raise this on a 64 bit machine.
1287 #define CURSOR_STACK 32
1291 /** Cursors are used for all DB operations.
1292 * A cursor holds a path of (page pointer, key index) from the DB
1293 * root to a position in the DB, plus other state. #MDB_DUPSORT
1294 * cursors include an xcursor to the current data item. Write txns
1295 * track their cursors and keep them up to date when data moves.
1296 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
1297 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
1300 /** Next cursor on this DB in this txn */
1301 MDB_cursor *mc_next;
1302 /** Backup of the original cursor if this cursor is a shadow */
1303 MDB_cursor *mc_backup;
1304 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
1305 struct MDB_xcursor *mc_xcursor;
1306 /** The transaction that owns this cursor */
1308 /** The database handle this cursor operates on */
1310 /** The database record for this cursor */
1312 /** The database auxiliary record for this cursor */
1314 /** The @ref mt_dbflag for this database */
1315 unsigned char *mc_dbflag;
1316 unsigned short mc_snum; /**< number of pushed pages */
1317 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
1318 /** @defgroup mdb_cursor Cursor Flags
1320 * Cursor state flags.
1323 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
1324 #define C_EOF 0x02 /**< No more data */
1325 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
1326 #define C_DEL 0x08 /**< last op was a cursor_del */
1327 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
1328 #define C_WRITEMAP MDB_TXN_WRITEMAP /**< Copy of txn flag */
1329 /** Read-only cursor into the txn's original snapshot in the map.
1330 * Set for read-only txns, and in #mdb_page_alloc() for #FREE_DBI when
1331 * #MDB_DEVEL & 2. Only implements code which is necessary for this.
1333 #define C_ORIG_RDONLY MDB_TXN_RDONLY
1335 unsigned int mc_flags; /**< @ref mdb_cursor */
1336 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
1337 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
1339 MDB_page *mc_ovpg; /**< a referenced overflow page */
1340 # define MC_OVPG(mc) ((mc)->mc_ovpg)
1341 # define MC_SET_OVPG(mc, pg) ((mc)->mc_ovpg = (pg))
1343 # define MC_OVPG(mc) ((MDB_page *)0)
1344 # define MC_SET_OVPG(mc, pg) ((void)0)
1348 /** Context for sorted-dup records.
1349 * We could have gone to a fully recursive design, with arbitrarily
1350 * deep nesting of sub-databases. But for now we only handle these
1351 * levels - main DB, optional sub-DB, sorted-duplicate DB.
1353 typedef struct MDB_xcursor {
1354 /** A sub-cursor for traversing the Dup DB */
1355 MDB_cursor mx_cursor;
1356 /** The database record for this Dup DB */
1358 /** The auxiliary DB record for this Dup DB */
1360 /** The @ref mt_dbflag for this Dup DB */
1361 unsigned char mx_dbflag;
1364 /** Check if there is an inited xcursor, so #XCURSOR_REFRESH() is proper */
1365 #define XCURSOR_INITED(mc) \
1366 ((mc)->mc_xcursor && ((mc)->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
1368 /** Update sub-page pointer, if any, in \b mc->mc_xcursor. Needed
1369 * when the node which contains the sub-page may have moved. Called
1370 * with \b mp = mc->mc_pg[mc->mc_top], \b ki = mc->mc_ki[mc->mc_top].
1372 #define XCURSOR_REFRESH(mc, mp, ki) do { \
1373 MDB_page *xr_pg = (mp); \
1374 MDB_node *xr_node = NODEPTR(xr_pg, ki); \
1375 if ((xr_node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) \
1376 (mc)->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(xr_node); \
1379 /** State of FreeDB old pages, stored in the MDB_env */
1380 typedef struct MDB_pgstate {
1381 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1382 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1385 /** The database environment. */
1387 HANDLE me_fd; /**< The main data file */
1388 HANDLE me_lfd; /**< The lock file */
1389 HANDLE me_mfd; /**< For writing and syncing the meta pages */
1390 #if defined(MDB_VL32) && defined(_WIN32)
1391 HANDLE me_fmh; /**< File Mapping handle */
1393 /** Failed to update the meta page. Probably an I/O error. */
1394 #define MDB_FATAL_ERROR 0x80000000U
1395 /** Some fields are initialized. */
1396 #define MDB_ENV_ACTIVE 0x20000000U
1397 /** me_txkey is set */
1398 #define MDB_ENV_TXKEY 0x10000000U
1399 /** fdatasync is unreliable */
1400 #define MDB_FSYNCONLY 0x08000000U
1401 uint32_t me_flags; /**< @ref mdb_env */
1402 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1403 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1404 unsigned int me_maxreaders; /**< size of the reader table */
1405 /** Max #MDB_txninfo.%mti_numreaders of interest to #mdb_env_close() */
1406 volatile int me_close_readers;
1407 MDB_dbi me_numdbs; /**< number of DBs opened */
1408 MDB_dbi me_maxdbs; /**< size of the DB table */
1409 MDB_PID_T me_pid; /**< process ID of this env */
1410 char *me_path; /**< path to the DB files */
1411 char *me_map; /**< the memory map of the data file */
1412 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1413 MDB_meta *me_metas[NUM_METAS]; /**< pointers to the two meta pages */
1414 void *me_pbuf; /**< scratch area for DUPSORT put() */
1415 MDB_txn *me_txn; /**< current write transaction */
1416 MDB_txn *me_txn0; /**< prealloc'd write transaction */
1417 mdb_size_t me_mapsize; /**< size of the data memory map */
1418 off_t me_size; /**< current file size */
1419 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1420 MDB_dbx *me_dbxs; /**< array of static DB info */
1421 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1422 unsigned int *me_dbiseqs; /**< array of dbi sequence numbers */
1423 pthread_key_t me_txkey; /**< thread-key for readers */
1424 txnid_t me_pgoldest; /**< ID of oldest reader last time we looked */
1425 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1426 # define me_pglast me_pgstate.mf_pglast
1427 # define me_pghead me_pgstate.mf_pghead
1428 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1429 /** IDL of pages that became unused in a write txn */
1430 MDB_IDL me_free_pgs;
1431 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1432 MDB_ID2L me_dirty_list;
1433 /** Max number of freelist items that can fit in a single overflow page */
1435 /** Max size of a node on a page */
1436 unsigned int me_nodemax;
1437 #if !(MDB_MAXKEYSIZE)
1438 unsigned int me_maxkey; /**< max size of a key */
1440 int me_live_reader; /**< have liveness lock in reader table */
1442 int me_pidquery; /**< Used in OpenProcess */
1444 #ifdef MDB_USE_POSIX_MUTEX /* Posix mutexes reside in shared mem */
1445 # define me_rmutex me_txns->mti_rmutex /**< Shared reader lock */
1446 # define me_wmutex me_txns->mti_wmutex /**< Shared writer lock */
1448 mdb_mutex_t me_rmutex;
1449 mdb_mutex_t me_wmutex;
1452 MDB_ID3L me_rpages; /**< like #mt_rpages, but global to env */
1453 pthread_mutex_t me_rpmutex; /**< control access to #me_rpages */
1454 #define MDB_ERPAGE_SIZE 16384
1455 #define MDB_ERPAGE_MAX (MDB_ERPAGE_SIZE-1)
1456 unsigned int me_rpcheck;
1458 void *me_userctx; /**< User-settable context */
1459 MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
1462 /** Nested transaction */
1463 typedef struct MDB_ntxn {
1464 MDB_txn mnt_txn; /**< the transaction */
1465 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1468 /** max number of pages to commit in one writev() call */
1469 #define MDB_COMMIT_PAGES 64
1470 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1471 #undef MDB_COMMIT_PAGES
1472 #define MDB_COMMIT_PAGES IOV_MAX
1475 /** max bytes to write in one call */
1476 #define MAX_WRITE (0x40000000U >> (sizeof(ssize_t) == 4))
1478 /** Check \b txn and \b dbi arguments to a function */
1479 #define TXN_DBI_EXIST(txn, dbi, validity) \
1480 ((txn) && (dbi)<(txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & (validity)))
1482 /** Check for misused \b dbi handles */
1483 #define TXN_DBI_CHANGED(txn, dbi) \
1484 ((txn)->mt_dbiseqs[dbi] != (txn)->mt_env->me_dbiseqs[dbi])
1486 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1487 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1488 static int mdb_page_touch(MDB_cursor *mc);
1490 #define MDB_END_NAMES {"committed", "empty-commit", "abort", "reset", \
1491 "reset-tmp", "fail-begin", "fail-beginchild"}
1493 /* mdb_txn_end operation number, for logging */
1494 MDB_END_COMMITTED, MDB_END_EMPTY_COMMIT, MDB_END_ABORT, MDB_END_RESET,
1495 MDB_END_RESET_TMP, MDB_END_FAIL_BEGIN, MDB_END_FAIL_BEGINCHILD
1497 #define MDB_END_OPMASK 0x0F /**< mask for #mdb_txn_end() operation number */
1498 #define MDB_END_UPDATE 0x10 /**< update env state (DBIs) */
1499 #define MDB_END_FREE 0x20 /**< free txn unless it is #MDB_env.%me_txn0 */
1500 #define MDB_END_SLOT MDB_NOTLS /**< release any reader slot if #MDB_NOTLS */
1501 static void mdb_txn_end(MDB_txn *txn, unsigned mode);
1503 static int mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **mp, int *lvl);
1504 static int mdb_page_search_root(MDB_cursor *mc,
1505 MDB_val *key, int modify);
1506 #define MDB_PS_MODIFY 1
1507 #define MDB_PS_ROOTONLY 2
1508 #define MDB_PS_FIRST 4
1509 #define MDB_PS_LAST 8
1510 static int mdb_page_search(MDB_cursor *mc,
1511 MDB_val *key, int flags);
1512 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1514 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1515 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1516 pgno_t newpgno, unsigned int nflags);
1518 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1519 static MDB_meta *mdb_env_pick_meta(const MDB_env *env);
1520 static int mdb_env_write_meta(MDB_txn *txn);
1521 #ifdef MDB_USE_POSIX_MUTEX /* Drop unused excl arg */
1522 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1524 static void mdb_env_close0(MDB_env *env, int excl);
1526 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1527 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1528 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1529 static void mdb_node_del(MDB_cursor *mc, int ksize);
1530 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1531 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft);
1532 static int mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data);
1533 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1534 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1536 static int mdb_rebalance(MDB_cursor *mc);
1537 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1539 static void mdb_cursor_pop(MDB_cursor *mc);
1540 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1542 static int mdb_cursor_del0(MDB_cursor *mc);
1543 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
1544 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1545 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1546 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1547 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1549 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1550 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1552 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1553 static void mdb_xcursor_init0(MDB_cursor *mc);
1554 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1555 static void mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int force);
1557 static int mdb_drop0(MDB_cursor *mc, int subs);
1558 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1559 static int mdb_reader_check0(MDB_env *env, int rlocked, int *dead);
1562 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1565 /** Compare two items pointing at '#mdb_size_t's of unknown alignment. */
1566 #ifdef MISALIGNED_OK
1567 # define mdb_cmp_clong mdb_cmp_long
1569 # define mdb_cmp_clong mdb_cmp_cint
1572 /** True if we need #mdb_cmp_clong() instead of \b cmp for #MDB_INTEGERDUP */
1573 #define NEED_CMP_CLONG(cmp, ksize) \
1574 (UINT_MAX < MDB_SIZE_MAX && \
1575 (cmp) == mdb_cmp_int && (ksize) == sizeof(mdb_size_t))
1578 static SECURITY_DESCRIPTOR mdb_null_sd;
1579 static SECURITY_ATTRIBUTES mdb_all_sa;
1580 static int mdb_sec_inited;
1583 static int utf8_to_utf16(const char *src, struct MDB_name *dst, int xtra);
1586 /** Return the library version info. */
1588 mdb_version(int *major, int *minor, int *patch)
1590 if (major) *major = MDB_VERSION_MAJOR;
1591 if (minor) *minor = MDB_VERSION_MINOR;
1592 if (patch) *patch = MDB_VERSION_PATCH;
1593 return MDB_VERSION_STRING;
1596 /** Table of descriptions for LMDB @ref errors */
1597 static char *const mdb_errstr[] = {
1598 "MDB_KEYEXIST: Key/data pair already exists",
1599 "MDB_NOTFOUND: No matching key/data pair found",
1600 "MDB_PAGE_NOTFOUND: Requested page not found",
1601 "MDB_CORRUPTED: Located page was wrong type",
1602 "MDB_PANIC: Update of meta page failed or environment had fatal error",
1603 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1604 "MDB_INVALID: File is not an LMDB file",
1605 "MDB_MAP_FULL: Environment mapsize limit reached",
1606 "MDB_DBS_FULL: Environment maxdbs limit reached",
1607 "MDB_READERS_FULL: Environment maxreaders limit reached",
1608 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1609 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1610 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1611 "MDB_PAGE_FULL: Internal error - page has no more space",
1612 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1613 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1614 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1615 "MDB_BAD_TXN: Transaction must abort, has a child, or is invalid",
1616 "MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
1617 "MDB_BAD_DBI: The specified DBI handle was closed/changed unexpectedly",
1618 "MDB_PROBLEM: Unexpected problem - txn should abort",
1622 mdb_strerror(int err)
1625 /** HACK: pad 4KB on stack over the buf. Return system msgs in buf.
1626 * This works as long as no function between the call to mdb_strerror
1627 * and the actual use of the message uses more than 4K of stack.
1629 #define MSGSIZE 1024
1630 #define PADSIZE 4096
1631 char buf[MSGSIZE+PADSIZE], *ptr = buf;
1635 return ("Successful return: 0");
1637 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1638 i = err - MDB_KEYEXIST;
1639 return mdb_errstr[i];
1643 /* These are the C-runtime error codes we use. The comment indicates
1644 * their numeric value, and the Win32 error they would correspond to
1645 * if the error actually came from a Win32 API. A major mess, we should
1646 * have used LMDB-specific error codes for everything.
1649 case ENOENT: /* 2, FILE_NOT_FOUND */
1650 case EIO: /* 5, ACCESS_DENIED */
1651 case ENOMEM: /* 12, INVALID_ACCESS */
1652 case EACCES: /* 13, INVALID_DATA */
1653 case EBUSY: /* 16, CURRENT_DIRECTORY */
1654 case EINVAL: /* 22, BAD_COMMAND */
1655 case ENOSPC: /* 28, OUT_OF_PAPER */
1656 return strerror(err);
1661 FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
1662 FORMAT_MESSAGE_IGNORE_INSERTS,
1663 NULL, err, 0, ptr, MSGSIZE, (va_list *)buf+MSGSIZE);
1666 return strerror(err);
1670 /** assert(3) variant in cursor context */
1671 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1672 /** assert(3) variant in transaction context */
1673 #define mdb_tassert(txn, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1674 /** assert(3) variant in environment context */
1675 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1678 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1679 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1682 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1683 const char *func, const char *file, int line)
1686 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1687 file, line, expr_txt, func);
1688 if (env->me_assert_func)
1689 env->me_assert_func(env, buf);
1690 fprintf(stderr, "%s\n", buf);
1694 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1698 /** Return the page number of \b mp which may be sub-page, for debug output */
1700 mdb_dbg_pgno(MDB_page *mp)
1703 COPY_PGNO(ret, mp->mp_pgno);
1707 /** Display a key in hexadecimal and return the address of the result.
1708 * @param[in] key the key to display
1709 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1710 * @return The key in hexadecimal form.
1713 mdb_dkey(MDB_val *key, char *buf)
1716 unsigned char *c = key->mv_data;
1722 if (key->mv_size > DKBUF_MAXKEYSIZE)
1723 return "MDB_MAXKEYSIZE";
1724 /* may want to make this a dynamic check: if the key is mostly
1725 * printable characters, print it as-is instead of converting to hex.
1729 for (i=0; i<key->mv_size; i++)
1730 ptr += sprintf(ptr, "%02x", *c++);
1732 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1738 mdb_leafnode_type(MDB_node *n)
1740 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1741 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1742 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1745 /** Display all the keys in the page. */
1747 mdb_page_list(MDB_page *mp)
1749 pgno_t pgno = mdb_dbg_pgno(mp);
1750 const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
1752 unsigned int i, nkeys, nsize, total = 0;
1756 switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1757 case P_BRANCH: type = "Branch page"; break;
1758 case P_LEAF: type = "Leaf page"; break;
1759 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1760 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1761 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1763 fprintf(stderr, "Overflow page %"Yu" pages %u%s\n",
1764 pgno, mp->mp_pages, state);
1767 fprintf(stderr, "Meta-page %"Yu" txnid %"Yu"\n",
1768 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1771 fprintf(stderr, "Bad page %"Yu" flags 0x%X\n", pgno, mp->mp_flags);
1775 nkeys = NUMKEYS(mp);
1776 fprintf(stderr, "%s %"Yu" numkeys %d%s\n", type, pgno, nkeys, state);
1778 for (i=0; i<nkeys; i++) {
1779 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1780 key.mv_size = nsize = mp->mp_pad;
1781 key.mv_data = LEAF2KEY(mp, i, nsize);
1783 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1786 node = NODEPTR(mp, i);
1787 key.mv_size = node->mn_ksize;
1788 key.mv_data = node->mn_data;
1789 nsize = NODESIZE + key.mv_size;
1790 if (IS_BRANCH(mp)) {
1791 fprintf(stderr, "key %d: page %"Yu", %s\n", i, NODEPGNO(node),
1795 if (F_ISSET(node->mn_flags, F_BIGDATA))
1796 nsize += sizeof(pgno_t);
1798 nsize += NODEDSZ(node);
1800 nsize += sizeof(indx_t);
1801 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1802 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1804 total = EVEN(total);
1806 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1807 IS_LEAF2(mp) ? PAGEHDRSZ : PAGEBASE + mp->mp_lower, total, SIZELEFT(mp));
1811 mdb_cursor_chk(MDB_cursor *mc)
1817 if (!mc->mc_snum || !(mc->mc_flags & C_INITIALIZED)) return;
1818 for (i=0; i<mc->mc_top; i++) {
1820 node = NODEPTR(mp, mc->mc_ki[i]);
1821 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1824 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1826 if (XCURSOR_INITED(mc)) {
1827 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
1828 if (((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) &&
1829 mc->mc_xcursor->mx_cursor.mc_pg[0] != NODEDATA(node)) {
1837 /** Count all the pages in each DB and in the freelist
1838 * and make sure it matches the actual number of pages
1840 * All named DBs must be open for a correct count.
1842 static void mdb_audit(MDB_txn *txn)
1846 MDB_ID freecount, count;
1851 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1852 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1853 freecount += *(MDB_ID *)data.mv_data;
1854 mdb_tassert(txn, rc == MDB_NOTFOUND);
1857 for (i = 0; i<txn->mt_numdbs; i++) {
1859 if (!(txn->mt_dbflags[i] & DB_VALID))
1861 mdb_cursor_init(&mc, txn, i, &mx);
1862 if (txn->mt_dbs[i].md_root == P_INVALID)
1864 count += txn->mt_dbs[i].md_branch_pages +
1865 txn->mt_dbs[i].md_leaf_pages +
1866 txn->mt_dbs[i].md_overflow_pages;
1867 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1868 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1869 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
1872 mp = mc.mc_pg[mc.mc_top];
1873 for (j=0; j<NUMKEYS(mp); j++) {
1874 MDB_node *leaf = NODEPTR(mp, j);
1875 if (leaf->mn_flags & F_SUBDATA) {
1877 memcpy(&db, NODEDATA(leaf), sizeof(db));
1878 count += db.md_branch_pages + db.md_leaf_pages +
1879 db.md_overflow_pages;
1883 mdb_tassert(txn, rc == MDB_NOTFOUND);
1886 if (freecount + count + NUM_METAS != txn->mt_next_pgno) {
1887 fprintf(stderr, "audit: %"Yu" freecount: %"Yu" count: %"Yu" total: %"Yu" next_pgno: %"Yu"\n",
1888 txn->mt_txnid, freecount, count+NUM_METAS,
1889 freecount+count+NUM_METAS, txn->mt_next_pgno);
1895 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1897 return txn->mt_dbxs[dbi].md_cmp(a, b);
1901 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1903 MDB_cmp_func *dcmp = txn->mt_dbxs[dbi].md_dcmp;
1904 if (NEED_CMP_CLONG(dcmp, a->mv_size))
1905 dcmp = mdb_cmp_clong;
1909 /** Allocate memory for a page.
1910 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1911 * Set #MDB_TXN_ERROR on failure.
1914 mdb_page_malloc(MDB_txn *txn, unsigned num)
1916 MDB_env *env = txn->mt_env;
1917 MDB_page *ret = env->me_dpages;
1918 size_t psize = env->me_psize, sz = psize, off;
1919 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1920 * For a single page alloc, we init everything after the page header.
1921 * For multi-page, we init the final page; if the caller needed that
1922 * many pages they will be filling in at least up to the last page.
1926 VGMEMP_ALLOC(env, ret, sz);
1927 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1928 env->me_dpages = ret->mp_next;
1931 psize -= off = PAGEHDRSZ;
1936 if ((ret = malloc(sz)) != NULL) {
1937 VGMEMP_ALLOC(env, ret, sz);
1938 if (!(env->me_flags & MDB_NOMEMINIT)) {
1939 memset((char *)ret + off, 0, psize);
1943 txn->mt_flags |= MDB_TXN_ERROR;
1947 /** Free a single page.
1948 * Saves single pages to a list, for future reuse.
1949 * (This is not used for multi-page overflow pages.)
1952 mdb_page_free(MDB_env *env, MDB_page *mp)
1954 mp->mp_next = env->me_dpages;
1955 VGMEMP_FREE(env, mp);
1956 env->me_dpages = mp;
1959 /** Free a dirty page */
1961 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1963 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1964 mdb_page_free(env, dp);
1966 /* large pages just get freed directly */
1967 VGMEMP_FREE(env, dp);
1972 /** Return all dirty pages to dpage list */
1974 mdb_dlist_free(MDB_txn *txn)
1976 MDB_env *env = txn->mt_env;
1977 MDB_ID2L dl = txn->mt_u.dirty_list;
1978 unsigned i, n = dl[0].mid;
1980 for (i = 1; i <= n; i++) {
1981 mdb_dpage_free(env, dl[i].mptr);
1988 mdb_page_unref(MDB_txn *txn, MDB_page *mp)
1991 MDB_ID3L tl = txn->mt_rpages;
1993 if (mp->mp_flags & (P_SUBP|P_DIRTY))
1995 rem = mp->mp_pgno & (MDB_RPAGE_CHUNK-1);
1996 pgno = mp->mp_pgno ^ rem;
1997 x = mdb_mid3l_search(tl, pgno);
1998 if (x != tl[0].mid && tl[x+1].mid == mp->mp_pgno)
2003 #define MDB_PAGE_UNREF(txn, mp) mdb_page_unref(txn, mp)
2006 mdb_cursor_unref(MDB_cursor *mc)
2009 if (mc->mc_txn->mt_rpages[0].mid) {
2010 if (!mc->mc_snum || !mc->mc_pg[0] || IS_SUBP(mc->mc_pg[0]))
2012 for (i=0; i<mc->mc_snum; i++)
2013 mdb_page_unref(mc->mc_txn, mc->mc_pg[i]);
2015 mdb_page_unref(mc->mc_txn, mc->mc_ovpg);
2019 mc->mc_snum = mc->mc_top = 0;
2020 mc->mc_pg[0] = NULL;
2021 mc->mc_flags &= ~C_INITIALIZED;
2023 #define MDB_CURSOR_UNREF(mc, force) \
2024 (((force) || ((mc)->mc_flags & C_INITIALIZED)) \
2025 ? mdb_cursor_unref(mc) \
2029 #define MDB_PAGE_UNREF(txn, mp)
2030 #define MDB_CURSOR_UNREF(mc, force) ((void)0)
2031 #endif /* MDB_VL32 */
2033 /** Loosen or free a single page.
2034 * Saves single pages to a list for future reuse
2035 * in this same txn. It has been pulled from the freeDB
2036 * and already resides on the dirty list, but has been
2037 * deleted. Use these pages first before pulling again
2040 * If the page wasn't dirtied in this txn, just add it
2041 * to this txn's free list.
2044 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
2047 pgno_t pgno = mp->mp_pgno;
2048 MDB_txn *txn = mc->mc_txn;
2050 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
2051 if (txn->mt_parent) {
2052 MDB_ID2 *dl = txn->mt_u.dirty_list;
2053 /* If txn has a parent, make sure the page is in our
2057 unsigned x = mdb_mid2l_search(dl, pgno);
2058 if (x <= dl[0].mid && dl[x].mid == pgno) {
2059 if (mp != dl[x].mptr) { /* bad cursor? */
2060 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2061 txn->mt_flags |= MDB_TXN_ERROR;
2069 /* no parent txn, so it's just ours */
2074 DPRINTF(("loosen db %d page %"Yu, DDBI(mc), mp->mp_pgno));
2075 NEXT_LOOSE_PAGE(mp) = txn->mt_loose_pgs;
2076 txn->mt_loose_pgs = mp;
2077 txn->mt_loose_count++;
2078 mp->mp_flags |= P_LOOSE;
2080 int rc = mdb_midl_append(&txn->mt_free_pgs, pgno);
2088 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
2089 * @param[in] mc A cursor handle for the current operation.
2090 * @param[in] pflags Flags of the pages to update:
2091 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
2092 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
2093 * @return 0 on success, non-zero on failure.
2096 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
2098 enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
2099 MDB_txn *txn = mc->mc_txn;
2100 MDB_cursor *m3, *m0 = mc;
2105 int rc = MDB_SUCCESS, level;
2107 /* Mark pages seen by cursors: First m0, then tracked cursors */
2108 for (i = txn->mt_numdbs;; ) {
2109 if (mc->mc_flags & C_INITIALIZED) {
2110 for (m3 = mc;; m3 = &mx->mx_cursor) {
2112 for (j=0; j<m3->mc_snum; j++) {
2114 if ((mp->mp_flags & Mask) == pflags)
2115 mp->mp_flags ^= P_KEEP;
2117 mx = m3->mc_xcursor;
2118 /* Proceed to mx if it is at a sub-database */
2119 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
2121 if (! (mp && (mp->mp_flags & P_LEAF)))
2123 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
2124 if (!(leaf->mn_flags & F_SUBDATA))
2129 for (; !mc || mc == m0; mc = txn->mt_cursors[--i])
2136 /* Mark dirty root pages */
2137 for (i=0; i<txn->mt_numdbs; i++) {
2138 if (txn->mt_dbflags[i] & DB_DIRTY) {
2139 pgno_t pgno = txn->mt_dbs[i].md_root;
2140 if (pgno == P_INVALID)
2142 if ((rc = mdb_page_get(m0, pgno, &dp, &level)) != MDB_SUCCESS)
2144 if ((dp->mp_flags & Mask) == pflags && level <= 1)
2145 dp->mp_flags ^= P_KEEP;
2153 static int mdb_page_flush(MDB_txn *txn, int keep);
2155 /** Spill pages from the dirty list back to disk.
2156 * This is intended to prevent running into #MDB_TXN_FULL situations,
2157 * but note that they may still occur in a few cases:
2158 * 1) our estimate of the txn size could be too small. Currently this
2159 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
2160 * 2) child txns may run out of space if their parents dirtied a
2161 * lot of pages and never spilled them. TODO: we probably should do
2162 * a preemptive spill during #mdb_txn_begin() of a child txn, if
2163 * the parent's dirty_room is below a given threshold.
2165 * Otherwise, if not using nested txns, it is expected that apps will
2166 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
2167 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
2168 * If the txn never references them again, they can be left alone.
2169 * If the txn only reads them, they can be used without any fuss.
2170 * If the txn writes them again, they can be dirtied immediately without
2171 * going thru all of the work of #mdb_page_touch(). Such references are
2172 * handled by #mdb_page_unspill().
2174 * Also note, we never spill DB root pages, nor pages of active cursors,
2175 * because we'll need these back again soon anyway. And in nested txns,
2176 * we can't spill a page in a child txn if it was already spilled in a
2177 * parent txn. That would alter the parent txns' data even though
2178 * the child hasn't committed yet, and we'd have no way to undo it if
2179 * the child aborted.
2181 * @param[in] m0 cursor A cursor handle identifying the transaction and
2182 * database for which we are checking space.
2183 * @param[in] key For a put operation, the key being stored.
2184 * @param[in] data For a put operation, the data being stored.
2185 * @return 0 on success, non-zero on failure.
2188 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
2190 MDB_txn *txn = m0->mc_txn;
2192 MDB_ID2L dl = txn->mt_u.dirty_list;
2193 unsigned int i, j, need;
2196 if (m0->mc_flags & C_SUB)
2199 /* Estimate how much space this op will take */
2200 i = m0->mc_db->md_depth;
2201 /* Named DBs also dirty the main DB */
2202 if (m0->mc_dbi >= CORE_DBS)
2203 i += txn->mt_dbs[MAIN_DBI].md_depth;
2204 /* For puts, roughly factor in the key+data size */
2206 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
2207 i += i; /* double it for good measure */
2210 if (txn->mt_dirty_room > i)
2213 if (!txn->mt_spill_pgs) {
2214 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
2215 if (!txn->mt_spill_pgs)
2218 /* purge deleted slots */
2219 MDB_IDL sl = txn->mt_spill_pgs;
2220 unsigned int num = sl[0];
2222 for (i=1; i<=num; i++) {
2229 /* Preserve pages which may soon be dirtied again */
2230 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
2233 /* Less aggressive spill - we originally spilled the entire dirty list,
2234 * with a few exceptions for cursor pages and DB root pages. But this
2235 * turns out to be a lot of wasted effort because in a large txn many
2236 * of those pages will need to be used again. So now we spill only 1/8th
2237 * of the dirty pages. Testing revealed this to be a good tradeoff,
2238 * better than 1/2, 1/4, or 1/10.
2240 if (need < MDB_IDL_UM_MAX / 8)
2241 need = MDB_IDL_UM_MAX / 8;
2243 /* Save the page IDs of all the pages we're flushing */
2244 /* flush from the tail forward, this saves a lot of shifting later on. */
2245 for (i=dl[0].mid; i && need; i--) {
2246 MDB_ID pn = dl[i].mid << 1;
2248 if (dp->mp_flags & (P_LOOSE|P_KEEP))
2250 /* Can't spill twice, make sure it's not already in a parent's
2253 if (txn->mt_parent) {
2255 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
2256 if (tx2->mt_spill_pgs) {
2257 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
2258 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
2259 dp->mp_flags |= P_KEEP;
2267 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
2271 mdb_midl_sort(txn->mt_spill_pgs);
2273 /* Flush the spilled part of dirty list */
2274 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
2277 /* Reset any dirty pages we kept that page_flush didn't see */
2278 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
2281 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
2285 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
2287 mdb_find_oldest(MDB_txn *txn)
2290 txnid_t mr, oldest = txn->mt_txnid - 1;
2291 if (txn->mt_env->me_txns) {
2292 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
2293 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
2304 /** Add a page to the txn's dirty list */
2306 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
2309 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
2311 if (txn->mt_flags & MDB_TXN_WRITEMAP) {
2312 insert = mdb_mid2l_append;
2314 insert = mdb_mid2l_insert;
2316 mid.mid = mp->mp_pgno;
2318 rc = insert(txn->mt_u.dirty_list, &mid);
2319 mdb_tassert(txn, rc == 0);
2320 txn->mt_dirty_room--;
2323 /** Allocate page numbers and memory for writing. Maintain me_pglast,
2324 * me_pghead and mt_next_pgno. Set #MDB_TXN_ERROR on failure.
2326 * If there are free pages available from older transactions, they
2327 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
2328 * Do not modify the freedB, just merge freeDB records into me_pghead[]
2329 * and move me_pglast to say which records were consumed. Only this
2330 * function can create me_pghead and move me_pglast/mt_next_pgno.
2331 * When #MDB_DEVEL & 2, it is not affected by #mdb_freelist_save(): it
2332 * then uses the transaction's original snapshot of the freeDB.
2333 * @param[in] mc cursor A cursor handle identifying the transaction and
2334 * database for which we are allocating.
2335 * @param[in] num the number of pages to allocate.
2336 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
2337 * will always be satisfied by a single contiguous chunk of memory.
2338 * @return 0 on success, non-zero on failure.
2341 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
2343 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
2344 /* Get at most <Max_retries> more freeDB records once me_pghead
2345 * has enough pages. If not enough, use new pages from the map.
2346 * If <Paranoid> and mc is updating the freeDB, only get new
2347 * records if me_pghead is empty. Then the freelist cannot play
2348 * catch-up with itself by growing while trying to save it.
2350 enum { Paranoid = 1, Max_retries = 500 };
2352 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
2354 int rc, retry = num * 60;
2355 MDB_txn *txn = mc->mc_txn;
2356 MDB_env *env = txn->mt_env;
2357 pgno_t pgno, *mop = env->me_pghead;
2358 unsigned i, j, mop_len = mop ? mop[0] : 0, n2 = num-1;
2360 txnid_t oldest = 0, last;
2365 /* If there are any loose pages, just use them */
2366 if (num == 1 && txn->mt_loose_pgs) {
2367 np = txn->mt_loose_pgs;
2368 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
2369 txn->mt_loose_count--;
2370 DPRINTF(("db %d use loose page %"Yu, DDBI(mc), np->mp_pgno));
2377 /* If our dirty list is already full, we can't do anything */
2378 if (txn->mt_dirty_room == 0) {
2383 for (op = MDB_FIRST;; op = MDB_NEXT) {
2388 /* Seek a big enough contiguous page range. Prefer
2389 * pages at the tail, just truncating the list.
2395 if (mop[i-n2] == pgno+n2)
2402 if (op == MDB_FIRST) { /* 1st iteration */
2403 /* Prepare to fetch more and coalesce */
2404 last = env->me_pglast;
2405 oldest = env->me_pgoldest;
2406 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
2407 #if (MDB_DEVEL) & 2 /* "& 2" so MDB_DEVEL=1 won't hide bugs breaking freeDB */
2408 /* Use original snapshot. TODO: Should need less care in code
2409 * which modifies the database. Maybe we can delete some code?
2411 m2.mc_flags |= C_ORIG_RDONLY;
2412 m2.mc_db = &env->me_metas[(txn->mt_txnid-1) & 1]->mm_dbs[FREE_DBI];
2413 m2.mc_dbflag = (unsigned char *)""; /* probably unnecessary */
2417 key.mv_data = &last; /* will look up last+1 */
2418 key.mv_size = sizeof(last);
2420 if (Paranoid && mc->mc_dbi == FREE_DBI)
2423 if (Paranoid && retry < 0 && mop_len)
2427 /* Do not fetch more if the record will be too recent */
2428 if (oldest <= last) {
2430 oldest = mdb_find_oldest(txn);
2431 env->me_pgoldest = oldest;
2437 rc = mdb_cursor_get(&m2, &key, NULL, op);
2439 if (rc == MDB_NOTFOUND)
2443 last = *(txnid_t*)key.mv_data;
2444 if (oldest <= last) {
2446 oldest = mdb_find_oldest(txn);
2447 env->me_pgoldest = oldest;
2453 np = m2.mc_pg[m2.mc_top];
2454 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
2455 if ((rc = mdb_node_read(&m2, leaf, &data)) != MDB_SUCCESS)
2458 idl = (MDB_ID *) data.mv_data;
2461 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
2466 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
2468 mop = env->me_pghead;
2470 env->me_pglast = last;
2472 DPRINTF(("IDL read txn %"Yu" root %"Yu" num %u",
2473 last, txn->mt_dbs[FREE_DBI].md_root, i));
2475 DPRINTF(("IDL %"Yu, idl[j]));
2477 /* Merge in descending sorted order */
2478 mdb_midl_xmerge(mop, idl);
2482 /* Use new pages from the map when nothing suitable in the freeDB */
2484 pgno = txn->mt_next_pgno;
2485 if (pgno + num >= env->me_maxpg) {
2486 DPUTS("DB size maxed out");
2490 #if defined(_WIN32) && !defined(MDB_VL32)
2491 if (!(env->me_flags & MDB_RDONLY)) {
2493 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
2494 p = VirtualAlloc(p, env->me_psize * num, MEM_COMMIT,
2495 (env->me_flags & MDB_WRITEMAP) ? PAGE_READWRITE:
2498 DPUTS("VirtualAlloc failed");
2506 if (env->me_flags & MDB_WRITEMAP) {
2507 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
2509 if (!(np = mdb_page_malloc(txn, num))) {
2515 mop[0] = mop_len -= num;
2516 /* Move any stragglers down */
2517 for (j = i-num; j < mop_len; )
2518 mop[++j] = mop[++i];
2520 txn->mt_next_pgno = pgno + num;
2523 mdb_page_dirty(txn, np);
2529 txn->mt_flags |= MDB_TXN_ERROR;
2533 /** Copy the used portions of a non-overflow page.
2534 * @param[in] dst page to copy into
2535 * @param[in] src page to copy from
2536 * @param[in] psize size of a page
2539 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2541 enum { Align = sizeof(pgno_t) };
2542 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2544 /* If page isn't full, just copy the used portion. Adjust
2545 * alignment so memcpy may copy words instead of bytes.
2547 if ((unused &= -Align) && !IS_LEAF2(src)) {
2548 upper = (upper + PAGEBASE) & -Align;
2549 memcpy(dst, src, (lower + PAGEBASE + (Align-1)) & -Align);
2550 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2553 memcpy(dst, src, psize - unused);
2557 /** Pull a page off the txn's spill list, if present.
2558 * If a page being referenced was spilled to disk in this txn, bring
2559 * it back and make it dirty/writable again.
2560 * @param[in] txn the transaction handle.
2561 * @param[in] mp the page being referenced. It must not be dirty.
2562 * @param[out] ret the writable page, if any. ret is unchanged if
2563 * mp wasn't spilled.
2566 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2568 MDB_env *env = txn->mt_env;
2571 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2573 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2574 if (!tx2->mt_spill_pgs)
2576 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2577 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2580 if (txn->mt_dirty_room == 0)
2581 return MDB_TXN_FULL;
2582 if (IS_OVERFLOW(mp))
2586 if (env->me_flags & MDB_WRITEMAP) {
2589 np = mdb_page_malloc(txn, num);
2593 memcpy(np, mp, num * env->me_psize);
2595 mdb_page_copy(np, mp, env->me_psize);
2598 /* If in current txn, this page is no longer spilled.
2599 * If it happens to be the last page, truncate the spill list.
2600 * Otherwise mark it as deleted by setting the LSB.
2602 if (x == txn->mt_spill_pgs[0])
2603 txn->mt_spill_pgs[0]--;
2605 txn->mt_spill_pgs[x] |= 1;
2606 } /* otherwise, if belonging to a parent txn, the
2607 * page remains spilled until child commits
2610 mdb_page_dirty(txn, np);
2611 np->mp_flags |= P_DIRTY;
2619 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2620 * Set #MDB_TXN_ERROR on failure.
2621 * @param[in] mc cursor pointing to the page to be touched
2622 * @return 0 on success, non-zero on failure.
2625 mdb_page_touch(MDB_cursor *mc)
2627 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2628 MDB_txn *txn = mc->mc_txn;
2629 MDB_cursor *m2, *m3;
2633 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2634 if (txn->mt_flags & MDB_TXN_SPILLS) {
2636 rc = mdb_page_unspill(txn, mp, &np);
2642 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2643 (rc = mdb_page_alloc(mc, 1, &np)))
2646 DPRINTF(("touched db %d page %"Yu" -> %"Yu, DDBI(mc),
2647 mp->mp_pgno, pgno));
2648 mdb_cassert(mc, mp->mp_pgno != pgno);
2649 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2650 /* Update the parent page, if any, to point to the new page */
2652 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2653 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2654 SETPGNO(node, pgno);
2656 mc->mc_db->md_root = pgno;
2658 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2659 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2661 /* If txn has a parent, make sure the page is in our
2665 unsigned x = mdb_mid2l_search(dl, pgno);
2666 if (x <= dl[0].mid && dl[x].mid == pgno) {
2667 if (mp != dl[x].mptr) { /* bad cursor? */
2668 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2669 txn->mt_flags |= MDB_TXN_ERROR;
2675 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2677 np = mdb_page_malloc(txn, 1);
2682 rc = mdb_mid2l_insert(dl, &mid);
2683 mdb_cassert(mc, rc == 0);
2688 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2690 np->mp_flags |= P_DIRTY;
2693 /* Adjust cursors pointing to mp */
2694 mc->mc_pg[mc->mc_top] = np;
2695 m2 = txn->mt_cursors[mc->mc_dbi];
2696 if (mc->mc_flags & C_SUB) {
2697 for (; m2; m2=m2->mc_next) {
2698 m3 = &m2->mc_xcursor->mx_cursor;
2699 if (m3->mc_snum < mc->mc_snum) continue;
2700 if (m3->mc_pg[mc->mc_top] == mp)
2701 m3->mc_pg[mc->mc_top] = np;
2704 for (; m2; m2=m2->mc_next) {
2705 if (m2->mc_snum < mc->mc_snum) continue;
2706 if (m2 == mc) continue;
2707 if (m2->mc_pg[mc->mc_top] == mp) {
2708 m2->mc_pg[mc->mc_top] = np;
2709 if (XCURSOR_INITED(m2) && IS_LEAF(np))
2710 XCURSOR_REFRESH(m2, np, m2->mc_ki[mc->mc_top]);
2714 MDB_PAGE_UNREF(mc->mc_txn, mp);
2718 txn->mt_flags |= MDB_TXN_ERROR;
2723 mdb_env_sync0(MDB_env *env, int force, pgno_t numpgs)
2726 if (env->me_flags & MDB_RDONLY)
2728 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2729 if (env->me_flags & MDB_WRITEMAP) {
2730 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2731 ? MS_ASYNC : MS_SYNC;
2732 if (MDB_MSYNC(env->me_map, env->me_psize * numpgs, flags))
2735 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2739 #ifdef BROKEN_FDATASYNC
2740 if (env->me_flags & MDB_FSYNCONLY) {
2741 if (fsync(env->me_fd))
2745 if (MDB_FDATASYNC(env->me_fd))
2753 mdb_env_sync(MDB_env *env, int force)
2755 MDB_meta *m = mdb_env_pick_meta(env);
2756 return mdb_env_sync0(env, force, m->mm_last_pg+1);
2759 /** Back up parent txn's cursors, then grab the originals for tracking */
2761 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2763 MDB_cursor *mc, *bk;
2768 for (i = src->mt_numdbs; --i >= 0; ) {
2769 if ((mc = src->mt_cursors[i]) != NULL) {
2770 size = sizeof(MDB_cursor);
2772 size += sizeof(MDB_xcursor);
2773 for (; mc; mc = bk->mc_next) {
2779 mc->mc_db = &dst->mt_dbs[i];
2780 /* Kill pointers into src to reduce abuse: The
2781 * user may not use mc until dst ends. But we need a valid
2782 * txn pointer here for cursor fixups to keep working.
2785 mc->mc_dbflag = &dst->mt_dbflags[i];
2786 if ((mx = mc->mc_xcursor) != NULL) {
2787 *(MDB_xcursor *)(bk+1) = *mx;
2788 mx->mx_cursor.mc_txn = dst;
2790 mc->mc_next = dst->mt_cursors[i];
2791 dst->mt_cursors[i] = mc;
2798 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2799 * @param[in] txn the transaction handle.
2800 * @param[in] merge true to keep changes to parent cursors, false to revert.
2801 * @return 0 on success, non-zero on failure.
2804 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2806 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2810 for (i = txn->mt_numdbs; --i >= 0; ) {
2811 for (mc = cursors[i]; mc; mc = next) {
2813 if ((bk = mc->mc_backup) != NULL) {
2815 /* Commit changes to parent txn */
2816 mc->mc_next = bk->mc_next;
2817 mc->mc_backup = bk->mc_backup;
2818 mc->mc_txn = bk->mc_txn;
2819 mc->mc_db = bk->mc_db;
2820 mc->mc_dbflag = bk->mc_dbflag;
2821 if ((mx = mc->mc_xcursor) != NULL)
2822 mx->mx_cursor.mc_txn = bk->mc_txn;
2824 /* Abort nested txn */
2826 if ((mx = mc->mc_xcursor) != NULL)
2827 *mx = *(MDB_xcursor *)(bk+1);
2831 /* Only malloced cursors are permanently tracked. */
2838 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2844 Pidset = F_SETLK, Pidcheck = F_GETLK
2848 /** Set or check a pid lock. Set returns 0 on success.
2849 * Check returns 0 if the process is certainly dead, nonzero if it may
2850 * be alive (the lock exists or an error happened so we do not know).
2852 * On Windows Pidset is a no-op, we merely check for the existence
2853 * of the process with the given pid. On POSIX we use a single byte
2854 * lock on the lockfile, set at an offset equal to the pid.
2857 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2859 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2862 if (op == Pidcheck) {
2863 h = OpenProcess(env->me_pidquery, FALSE, pid);
2864 /* No documented "no such process" code, but other program use this: */
2866 return ErrCode() != ERROR_INVALID_PARAMETER;
2867 /* A process exists until all handles to it close. Has it exited? */
2868 ret = WaitForSingleObject(h, 0) != 0;
2875 struct flock lock_info;
2876 memset(&lock_info, 0, sizeof(lock_info));
2877 lock_info.l_type = F_WRLCK;
2878 lock_info.l_whence = SEEK_SET;
2879 lock_info.l_start = pid;
2880 lock_info.l_len = 1;
2881 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2882 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2884 } else if ((rc = ErrCode()) == EINTR) {
2892 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2893 * @param[in] txn the transaction handle to initialize
2894 * @return 0 on success, non-zero on failure.
2897 mdb_txn_renew0(MDB_txn *txn)
2899 MDB_env *env = txn->mt_env;
2900 MDB_txninfo *ti = env->me_txns;
2902 unsigned int i, nr, flags = txn->mt_flags;
2904 int rc, new_notls = 0;
2906 if ((flags &= MDB_TXN_RDONLY) != 0) {
2908 meta = mdb_env_pick_meta(env);
2909 txn->mt_txnid = meta->mm_txnid;
2910 txn->mt_u.reader = NULL;
2912 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2913 pthread_getspecific(env->me_txkey);
2915 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2916 return MDB_BAD_RSLOT;
2918 MDB_PID_T pid = env->me_pid;
2919 MDB_THR_T tid = pthread_self();
2920 mdb_mutexref_t rmutex = env->me_rmutex;
2922 if (!env->me_live_reader) {
2923 rc = mdb_reader_pid(env, Pidset, pid);
2926 env->me_live_reader = 1;
2929 if (LOCK_MUTEX(rc, env, rmutex))
2931 nr = ti->mti_numreaders;
2932 for (i=0; i<nr; i++)
2933 if (ti->mti_readers[i].mr_pid == 0)
2935 if (i == env->me_maxreaders) {
2936 UNLOCK_MUTEX(rmutex);
2937 return MDB_READERS_FULL;
2939 r = &ti->mti_readers[i];
2940 /* Claim the reader slot, carefully since other code
2941 * uses the reader table un-mutexed: First reset the
2942 * slot, next publish it in mti_numreaders. After
2943 * that, it is safe for mdb_env_close() to touch it.
2944 * When it will be closed, we can finally claim it.
2947 r->mr_txnid = (txnid_t)-1;
2950 ti->mti_numreaders = ++nr;
2951 env->me_close_readers = nr;
2953 UNLOCK_MUTEX(rmutex);
2955 new_notls = (env->me_flags & MDB_NOTLS);
2956 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2961 do /* LY: Retry on a race, ITS#7970. */
2962 r->mr_txnid = ti->mti_txnid;
2963 while(r->mr_txnid != ti->mti_txnid);
2964 txn->mt_txnid = r->mr_txnid;
2965 txn->mt_u.reader = r;
2966 meta = env->me_metas[txn->mt_txnid & 1];
2970 /* Not yet touching txn == env->me_txn0, it may be active */
2972 if (LOCK_MUTEX(rc, env, env->me_wmutex))
2974 txn->mt_txnid = ti->mti_txnid;
2975 meta = env->me_metas[txn->mt_txnid & 1];
2977 meta = mdb_env_pick_meta(env);
2978 txn->mt_txnid = meta->mm_txnid;
2982 if (txn->mt_txnid == mdb_debug_start)
2985 txn->mt_child = NULL;
2986 txn->mt_loose_pgs = NULL;
2987 txn->mt_loose_count = 0;
2988 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2989 txn->mt_u.dirty_list = env->me_dirty_list;
2990 txn->mt_u.dirty_list[0].mid = 0;
2991 txn->mt_free_pgs = env->me_free_pgs;
2992 txn->mt_free_pgs[0] = 0;
2993 txn->mt_spill_pgs = NULL;
2995 memcpy(txn->mt_dbiseqs, env->me_dbiseqs, env->me_maxdbs * sizeof(unsigned int));
2998 /* Copy the DB info and flags */
2999 memcpy(txn->mt_dbs, meta->mm_dbs, CORE_DBS * sizeof(MDB_db));
3001 /* Moved to here to avoid a data race in read TXNs */
3002 txn->mt_next_pgno = meta->mm_last_pg+1;
3004 txn->mt_last_pgno = txn->mt_next_pgno - 1;
3007 txn->mt_flags = flags;
3010 txn->mt_numdbs = env->me_numdbs;
3011 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
3012 x = env->me_dbflags[i];
3013 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
3014 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_USRVALID|DB_STALE : 0;
3016 txn->mt_dbflags[MAIN_DBI] = DB_VALID|DB_USRVALID;
3017 txn->mt_dbflags[FREE_DBI] = DB_VALID;
3019 if (env->me_flags & MDB_FATAL_ERROR) {
3020 DPUTS("environment had fatal error, must shutdown!");
3022 } else if (env->me_maxpg < txn->mt_next_pgno) {
3023 rc = MDB_MAP_RESIZED;
3027 mdb_txn_end(txn, new_notls /*0 or MDB_END_SLOT*/ | MDB_END_FAIL_BEGIN);
3032 mdb_txn_renew(MDB_txn *txn)
3036 if (!txn || !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY|MDB_TXN_FINISHED))
3039 rc = mdb_txn_renew0(txn);
3040 if (rc == MDB_SUCCESS) {
3041 DPRINTF(("renew txn %"Yu"%c %p on mdbenv %p, root page %"Yu,
3042 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
3043 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
3049 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
3053 int rc, size, tsize;
3055 flags &= MDB_TXN_BEGIN_FLAGS;
3056 flags |= env->me_flags & MDB_WRITEMAP;
3058 if (env->me_flags & MDB_RDONLY & ~flags) /* write txn in RDONLY env */
3062 /* Nested transactions: Max 1 child, write txns only, no writemap */
3063 flags |= parent->mt_flags;
3064 if (flags & (MDB_RDONLY|MDB_WRITEMAP|MDB_TXN_BLOCKED)) {
3065 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
3067 /* Child txns save MDB_pgstate and use own copy of cursors */
3068 size = env->me_maxdbs * (sizeof(MDB_db)+sizeof(MDB_cursor *)+1);
3069 size += tsize = sizeof(MDB_ntxn);
3070 } else if (flags & MDB_RDONLY) {
3071 size = env->me_maxdbs * (sizeof(MDB_db)+1);
3072 size += tsize = sizeof(MDB_txn);
3074 /* Reuse preallocated write txn. However, do not touch it until
3075 * mdb_txn_renew0() succeeds, since it currently may be active.
3080 if ((txn = calloc(1, size)) == NULL) {
3081 DPRINTF(("calloc: %s", strerror(errno)));
3086 txn->mt_rpages = malloc(MDB_TRPAGE_SIZE * sizeof(MDB_ID3));
3087 if (!txn->mt_rpages) {
3091 txn->mt_rpages[0].mid = 0;
3092 txn->mt_rpcheck = MDB_TRPAGE_SIZE/2;
3095 txn->mt_dbxs = env->me_dbxs; /* static */
3096 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
3097 txn->mt_dbflags = (unsigned char *)txn + size - env->me_maxdbs;
3098 txn->mt_flags = flags;
3103 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
3104 txn->mt_dbiseqs = parent->mt_dbiseqs;
3105 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
3106 if (!txn->mt_u.dirty_list ||
3107 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
3109 free(txn->mt_u.dirty_list);
3113 txn->mt_txnid = parent->mt_txnid;
3114 txn->mt_dirty_room = parent->mt_dirty_room;
3115 txn->mt_u.dirty_list[0].mid = 0;
3116 txn->mt_spill_pgs = NULL;
3117 txn->mt_next_pgno = parent->mt_next_pgno;
3118 parent->mt_flags |= MDB_TXN_HAS_CHILD;
3119 parent->mt_child = txn;
3120 txn->mt_parent = parent;
3121 txn->mt_numdbs = parent->mt_numdbs;
3123 txn->mt_rpages = parent->mt_rpages;
3125 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3126 /* Copy parent's mt_dbflags, but clear DB_NEW */
3127 for (i=0; i<txn->mt_numdbs; i++)
3128 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
3130 ntxn = (MDB_ntxn *)txn;
3131 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
3132 if (env->me_pghead) {
3133 size = MDB_IDL_SIZEOF(env->me_pghead);
3134 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
3136 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
3141 rc = mdb_cursor_shadow(parent, txn);
3143 mdb_txn_end(txn, MDB_END_FAIL_BEGINCHILD);
3144 } else { /* MDB_RDONLY */
3145 txn->mt_dbiseqs = env->me_dbiseqs;
3147 rc = mdb_txn_renew0(txn);
3150 if (txn != env->me_txn0) {
3152 free(txn->mt_rpages);
3157 txn->mt_flags |= flags; /* could not change txn=me_txn0 earlier */
3159 DPRINTF(("begin txn %"Yu"%c %p on mdbenv %p, root page %"Yu,
3160 txn->mt_txnid, (flags & MDB_RDONLY) ? 'r' : 'w',
3161 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
3168 mdb_txn_env(MDB_txn *txn)
3170 if(!txn) return NULL;
3175 mdb_txn_id(MDB_txn *txn)
3178 return txn->mt_txnid;
3181 /** Export or close DBI handles opened in this txn. */
3183 mdb_dbis_update(MDB_txn *txn, int keep)
3186 MDB_dbi n = txn->mt_numdbs;
3187 MDB_env *env = txn->mt_env;
3188 unsigned char *tdbflags = txn->mt_dbflags;
3190 for (i = n; --i >= CORE_DBS;) {
3191 if (tdbflags[i] & DB_NEW) {
3193 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
3195 char *ptr = env->me_dbxs[i].md_name.mv_data;
3197 env->me_dbxs[i].md_name.mv_data = NULL;
3198 env->me_dbxs[i].md_name.mv_size = 0;
3199 env->me_dbflags[i] = 0;
3200 env->me_dbiseqs[i]++;
3206 if (keep && env->me_numdbs < n)
3210 /** End a transaction, except successful commit of a nested transaction.
3211 * May be called twice for readonly txns: First reset it, then abort.
3212 * @param[in] txn the transaction handle to end
3213 * @param[in] mode why and how to end the transaction
3216 mdb_txn_end(MDB_txn *txn, unsigned mode)
3218 MDB_env *env = txn->mt_env;
3220 static const char *const names[] = MDB_END_NAMES;
3223 /* Export or close DBI handles opened in this txn */
3224 mdb_dbis_update(txn, mode & MDB_END_UPDATE);
3226 DPRINTF(("%s txn %"Yu"%c %p on mdbenv %p, root page %"Yu,
3227 names[mode & MDB_END_OPMASK],
3228 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
3229 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
3231 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3232 if (txn->mt_u.reader) {
3233 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
3234 if (!(env->me_flags & MDB_NOTLS)) {
3235 txn->mt_u.reader = NULL; /* txn does not own reader */
3236 } else if (mode & MDB_END_SLOT) {
3237 txn->mt_u.reader->mr_pid = 0;
3238 txn->mt_u.reader = NULL;
3239 } /* else txn owns the slot until it does MDB_END_SLOT */
3241 txn->mt_numdbs = 0; /* prevent further DBI activity */
3242 txn->mt_flags |= MDB_TXN_FINISHED;
3244 } else if (!F_ISSET(txn->mt_flags, MDB_TXN_FINISHED)) {
3245 pgno_t *pghead = env->me_pghead;
3247 if (!(mode & MDB_END_UPDATE)) /* !(already closed cursors) */
3248 mdb_cursors_close(txn, 0);
3249 if (!(env->me_flags & MDB_WRITEMAP)) {
3250 mdb_dlist_free(txn);
3254 txn->mt_flags = MDB_TXN_FINISHED;
3256 if (!txn->mt_parent) {
3257 mdb_midl_shrink(&txn->mt_free_pgs);
3258 env->me_free_pgs = txn->mt_free_pgs;
3260 env->me_pghead = NULL;
3264 mode = 0; /* txn == env->me_txn0, do not free() it */
3266 /* The writer mutex was locked in mdb_txn_begin. */
3268 UNLOCK_MUTEX(env->me_wmutex);
3270 txn->mt_parent->mt_child = NULL;
3271 txn->mt_parent->mt_flags &= ~MDB_TXN_HAS_CHILD;
3272 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
3273 mdb_midl_free(txn->mt_free_pgs);
3274 mdb_midl_free(txn->mt_spill_pgs);
3275 free(txn->mt_u.dirty_list);
3278 mdb_midl_free(pghead);
3281 if (!txn->mt_parent) {
3282 MDB_ID3L el = env->me_rpages, tl = txn->mt_rpages;
3283 unsigned i, x, n = tl[0].mid;
3284 pthread_mutex_lock(&env->me_rpmutex);
3285 for (i = 1; i <= n; i++) {
3286 if (tl[i].mid & (MDB_RPAGE_CHUNK-1)) {
3287 /* tmp overflow pages that we didn't share in env */
3288 munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
3290 x = mdb_mid3l_search(el, tl[i].mid);
3291 if (tl[i].mptr == el[x].mptr) {
3294 /* another tmp overflow page */
3295 munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
3299 pthread_mutex_unlock(&env->me_rpmutex);
3301 if (mode & MDB_END_FREE)
3305 if (mode & MDB_END_FREE)
3310 mdb_txn_reset(MDB_txn *txn)
3315 /* This call is only valid for read-only txns */
3316 if (!(txn->mt_flags & MDB_TXN_RDONLY))
3319 mdb_txn_end(txn, MDB_END_RESET);
3323 mdb_txn_abort(MDB_txn *txn)
3329 mdb_txn_abort(txn->mt_child);
3331 mdb_txn_end(txn, MDB_END_ABORT|MDB_END_SLOT|MDB_END_FREE);
3334 /** Save the freelist as of this transaction to the freeDB.
3335 * This changes the freelist. Keep trying until it stabilizes.
3337 * When (MDB_DEVEL) & 2, the changes do not affect #mdb_page_alloc(),
3338 * it then uses the transaction's original snapshot of the freeDB.
3341 mdb_freelist_save(MDB_txn *txn)
3343 /* env->me_pghead[] can grow and shrink during this call.
3344 * env->me_pglast and txn->mt_free_pgs[] can only grow.
3345 * Page numbers cannot disappear from txn->mt_free_pgs[].
3348 MDB_env *env = txn->mt_env;
3349 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
3350 txnid_t pglast = 0, head_id = 0;
3351 pgno_t freecnt = 0, *free_pgs, *mop;
3352 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
3354 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
3356 if (env->me_pghead) {
3357 /* Make sure first page of freeDB is touched and on freelist */
3358 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
3359 if (rc && rc != MDB_NOTFOUND)
3363 if (!env->me_pghead && txn->mt_loose_pgs) {
3364 /* Put loose page numbers in mt_free_pgs, since
3365 * we may be unable to return them to me_pghead.
3367 MDB_page *mp = txn->mt_loose_pgs;
3368 if ((rc = mdb_midl_need(&txn->mt_free_pgs, txn->mt_loose_count)) != 0)
3370 for (; mp; mp = NEXT_LOOSE_PAGE(mp))
3371 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
3372 txn->mt_loose_pgs = NULL;
3373 txn->mt_loose_count = 0;
3376 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
3377 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
3378 ? SSIZE_MAX : maxfree_1pg;
3381 /* Come back here after each Put() in case freelist changed */
3386 /* If using records from freeDB which we have not yet
3387 * deleted, delete them and any we reserved for me_pghead.
3389 while (pglast < env->me_pglast) {
3390 rc = mdb_cursor_first(&mc, &key, NULL);
3393 pglast = head_id = *(txnid_t *)key.mv_data;
3394 total_room = head_room = 0;
3395 mdb_tassert(txn, pglast <= env->me_pglast);
3396 rc = mdb_cursor_del(&mc, 0);
3401 /* Save the IDL of pages freed by this txn, to a single record */
3402 if (freecnt < txn->mt_free_pgs[0]) {
3404 /* Make sure last page of freeDB is touched and on freelist */
3405 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
3406 if (rc && rc != MDB_NOTFOUND)
3409 free_pgs = txn->mt_free_pgs;
3410 /* Write to last page of freeDB */
3411 key.mv_size = sizeof(txn->mt_txnid);
3412 key.mv_data = &txn->mt_txnid;
3414 freecnt = free_pgs[0];
3415 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
3416 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3419 /* Retry if mt_free_pgs[] grew during the Put() */
3420 free_pgs = txn->mt_free_pgs;
3421 } while (freecnt < free_pgs[0]);
3422 mdb_midl_sort(free_pgs);
3423 memcpy(data.mv_data, free_pgs, data.mv_size);
3426 unsigned int i = free_pgs[0];
3427 DPRINTF(("IDL write txn %"Yu" root %"Yu" num %u",
3428 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
3430 DPRINTF(("IDL %"Yu, free_pgs[i]));
3436 mop = env->me_pghead;
3437 mop_len = (mop ? mop[0] : 0) + txn->mt_loose_count;
3439 /* Reserve records for me_pghead[]. Split it if multi-page,
3440 * to avoid searching freeDB for a page range. Use keys in
3441 * range [1,me_pglast]: Smaller than txnid of oldest reader.
3443 if (total_room >= mop_len) {
3444 if (total_room == mop_len || --more < 0)
3446 } else if (head_room >= maxfree_1pg && head_id > 1) {
3447 /* Keep current record (overflow page), add a new one */
3451 /* (Re)write {key = head_id, IDL length = head_room} */
3452 total_room -= head_room;
3453 head_room = mop_len - total_room;
3454 if (head_room > maxfree_1pg && head_id > 1) {
3455 /* Overflow multi-page for part of me_pghead */
3456 head_room /= head_id; /* amortize page sizes */
3457 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
3458 } else if (head_room < 0) {
3459 /* Rare case, not bothering to delete this record */
3462 key.mv_size = sizeof(head_id);
3463 key.mv_data = &head_id;
3464 data.mv_size = (head_room + 1) * sizeof(pgno_t);
3465 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3468 /* IDL is initially empty, zero out at least the length */
3469 pgs = (pgno_t *)data.mv_data;
3470 j = head_room > clean_limit ? head_room : 0;
3474 total_room += head_room;
3477 /* Return loose page numbers to me_pghead, though usually none are
3478 * left at this point. The pages themselves remain in dirty_list.
3480 if (txn->mt_loose_pgs) {
3481 MDB_page *mp = txn->mt_loose_pgs;
3482 unsigned count = txn->mt_loose_count;
3484 /* Room for loose pages + temp IDL with same */
3485 if ((rc = mdb_midl_need(&env->me_pghead, 2*count+1)) != 0)
3487 mop = env->me_pghead;
3488 loose = mop + MDB_IDL_ALLOCLEN(mop) - count;
3489 for (count = 0; mp; mp = NEXT_LOOSE_PAGE(mp))
3490 loose[ ++count ] = mp->mp_pgno;
3492 mdb_midl_sort(loose);
3493 mdb_midl_xmerge(mop, loose);
3494 txn->mt_loose_pgs = NULL;
3495 txn->mt_loose_count = 0;
3499 /* Fill in the reserved me_pghead records */
3505 rc = mdb_cursor_first(&mc, &key, &data);
3506 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
3507 txnid_t id = *(txnid_t *)key.mv_data;
3508 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
3511 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
3513 if (len > mop_len) {
3515 data.mv_size = (len + 1) * sizeof(MDB_ID);
3517 data.mv_data = mop -= len;
3520 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
3522 if (rc || !(mop_len -= len))
3529 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
3530 * @param[in] txn the transaction that's being committed
3531 * @param[in] keep number of initial pages in dirty_list to keep dirty.
3532 * @return 0 on success, non-zero on failure.
3535 mdb_page_flush(MDB_txn *txn, int keep)
3537 MDB_env *env = txn->mt_env;
3538 MDB_ID2L dl = txn->mt_u.dirty_list;
3539 unsigned psize = env->me_psize, j;
3540 int i, pagecount = dl[0].mid, rc;
3544 MDB_page *dp = NULL;
3548 struct iovec iov[MDB_COMMIT_PAGES];
3549 ssize_t wsize = 0, wres;
3550 off_t wpos = 0, next_pos = 1; /* impossible pos, so pos != next_pos */
3556 if (env->me_flags & MDB_WRITEMAP) {
3557 /* Clear dirty flags */
3558 while (++i <= pagecount) {
3560 /* Don't flush this page yet */
3561 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3562 dp->mp_flags &= ~P_KEEP;
3566 dp->mp_flags &= ~P_DIRTY;
3571 /* Write the pages */
3573 if (++i <= pagecount) {
3575 /* Don't flush this page yet */
3576 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3577 dp->mp_flags &= ~P_KEEP;
3582 /* clear dirty flag */
3583 dp->mp_flags &= ~P_DIRTY;
3586 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
3591 /* Windows actually supports scatter/gather I/O, but only on
3592 * unbuffered file handles. Since we're relying on the OS page
3593 * cache for all our data, that's self-defeating. So we just
3594 * write pages one at a time. We use the ov structure to set
3595 * the write offset, to at least save the overhead of a Seek
3598 DPRINTF(("committing page %"Yu, pgno));
3599 memset(&ov, 0, sizeof(ov));
3600 ov.Offset = pos & 0xffffffff;
3601 ov.OffsetHigh = pos >> 16 >> 16;
3602 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
3604 DPRINTF(("WriteFile: %d", rc));
3608 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
3609 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
3612 /* Write previous page(s) */
3613 #ifdef MDB_USE_PWRITEV
3614 wres = pwritev(env->me_fd, iov, n, wpos);
3617 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
3620 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
3624 DPRINTF(("lseek: %s", strerror(rc)));
3627 wres = writev(env->me_fd, iov, n);
3630 if (wres != wsize) {
3635 DPRINTF(("Write error: %s", strerror(rc)));
3637 rc = EIO; /* TODO: Use which error code? */
3638 DPUTS("short write, filesystem full?");
3649 DPRINTF(("committing page %"Yu, pgno));
3650 next_pos = pos + size;
3651 iov[n].iov_len = size;
3652 iov[n].iov_base = (char *)dp;
3658 if (pgno > txn->mt_last_pgno)
3659 txn->mt_last_pgno = pgno;
3662 /* MIPS has cache coherency issues, this is a no-op everywhere else
3663 * Note: for any size >= on-chip cache size, entire on-chip cache is
3666 CACHEFLUSH(env->me_map, txn->mt_next_pgno * env->me_psize, DCACHE);
3668 for (i = keep; ++i <= pagecount; ) {
3670 /* This is a page we skipped above */
3673 dl[j].mid = dp->mp_pgno;
3676 mdb_dpage_free(env, dp);
3681 txn->mt_dirty_room += i - j;
3687 mdb_txn_commit(MDB_txn *txn)
3690 unsigned int i, end_mode;
3696 /* mdb_txn_end() mode for a commit which writes nothing */
3697 end_mode = MDB_END_EMPTY_COMMIT|MDB_END_UPDATE|MDB_END_SLOT|MDB_END_FREE;
3699 if (txn->mt_child) {
3700 rc = mdb_txn_commit(txn->mt_child);
3707 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3711 if (txn->mt_flags & (MDB_TXN_FINISHED|MDB_TXN_ERROR)) {
3712 DPUTS("txn has failed/finished, can't commit");
3714 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3719 if (txn->mt_parent) {
3720 MDB_txn *parent = txn->mt_parent;
3724 unsigned x, y, len, ps_len;
3726 /* Append our free list to parent's */
3727 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3730 mdb_midl_free(txn->mt_free_pgs);
3731 /* Failures after this must either undo the changes
3732 * to the parent or set MDB_TXN_ERROR in the parent.
3735 parent->mt_next_pgno = txn->mt_next_pgno;
3736 parent->mt_flags = txn->mt_flags;
3738 /* Merge our cursors into parent's and close them */
3739 mdb_cursors_close(txn, 1);
3741 /* Update parent's DB table. */
3742 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3743 parent->mt_numdbs = txn->mt_numdbs;
3744 parent->mt_dbflags[FREE_DBI] = txn->mt_dbflags[FREE_DBI];
3745 parent->mt_dbflags[MAIN_DBI] = txn->mt_dbflags[MAIN_DBI];
3746 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
3747 /* preserve parent's DB_NEW status */
3748 x = parent->mt_dbflags[i] & DB_NEW;
3749 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3752 dst = parent->mt_u.dirty_list;
3753 src = txn->mt_u.dirty_list;
3754 /* Remove anything in our dirty list from parent's spill list */
3755 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3757 pspill[0] = (pgno_t)-1;
3758 /* Mark our dirty pages as deleted in parent spill list */
3759 for (i=0, len=src[0].mid; ++i <= len; ) {
3760 MDB_ID pn = src[i].mid << 1;
3761 while (pn > pspill[x])
3763 if (pn == pspill[x]) {
3768 /* Squash deleted pagenums if we deleted any */
3769 for (x=y; ++x <= ps_len; )
3770 if (!(pspill[x] & 1))
3771 pspill[++y] = pspill[x];
3775 /* Remove anything in our spill list from parent's dirty list */
3776 if (txn->mt_spill_pgs && txn->mt_spill_pgs[0]) {
3777 for (i=1; i<=txn->mt_spill_pgs[0]; i++) {
3778 MDB_ID pn = txn->mt_spill_pgs[i];
3780 continue; /* deleted spillpg */
3782 y = mdb_mid2l_search(dst, pn);
3783 if (y <= dst[0].mid && dst[y].mid == pn) {
3785 while (y < dst[0].mid) {
3794 /* Find len = length of merging our dirty list with parent's */
3796 dst[0].mid = 0; /* simplify loops */
3797 if (parent->mt_parent) {
3798 len = x + src[0].mid;
3799 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3800 for (i = x; y && i; y--) {
3801 pgno_t yp = src[y].mid;
3802 while (yp < dst[i].mid)
3804 if (yp == dst[i].mid) {
3809 } else { /* Simplify the above for single-ancestor case */
3810 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3812 /* Merge our dirty list with parent's */
3814 for (i = len; y; dst[i--] = src[y--]) {
3815 pgno_t yp = src[y].mid;
3816 while (yp < dst[x].mid)
3817 dst[i--] = dst[x--];
3818 if (yp == dst[x].mid)
3819 free(dst[x--].mptr);
3821 mdb_tassert(txn, i == x);
3823 free(txn->mt_u.dirty_list);
3824 parent->mt_dirty_room = txn->mt_dirty_room;
3825 if (txn->mt_spill_pgs) {
3826 if (parent->mt_spill_pgs) {
3827 /* TODO: Prevent failure here, so parent does not fail */
3828 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3830 parent->mt_flags |= MDB_TXN_ERROR;
3831 mdb_midl_free(txn->mt_spill_pgs);
3832 mdb_midl_sort(parent->mt_spill_pgs);
3834 parent->mt_spill_pgs = txn->mt_spill_pgs;
3838 /* Append our loose page list to parent's */
3839 for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(*lp))
3841 *lp = txn->mt_loose_pgs;
3842 parent->mt_loose_count += txn->mt_loose_count;
3844 parent->mt_child = NULL;
3845 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3850 if (txn != env->me_txn) {
3851 DPUTS("attempt to commit unknown transaction");
3856 mdb_cursors_close(txn, 0);
3858 if (!txn->mt_u.dirty_list[0].mid &&
3859 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
3862 DPRINTF(("committing txn %"Yu" %p on mdbenv %p, root page %"Yu,
3863 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3865 /* Update DB root pointers */
3866 if (txn->mt_numdbs > CORE_DBS) {
3870 data.mv_size = sizeof(MDB_db);
3872 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3873 for (i = CORE_DBS; i < txn->mt_numdbs; i++) {
3874 if (txn->mt_dbflags[i] & DB_DIRTY) {
3875 if (TXN_DBI_CHANGED(txn, i)) {
3879 data.mv_data = &txn->mt_dbs[i];
3880 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data,
3888 rc = mdb_freelist_save(txn);
3892 mdb_midl_free(env->me_pghead);
3893 env->me_pghead = NULL;
3894 mdb_midl_shrink(&txn->mt_free_pgs);
3900 if ((rc = mdb_page_flush(txn, 0)))
3902 if (!F_ISSET(txn->mt_flags, MDB_TXN_NOSYNC) &&
3903 (rc = mdb_env_sync0(env, 0, txn->mt_next_pgno)))
3905 if ((rc = mdb_env_write_meta(txn)))
3907 end_mode = MDB_END_COMMITTED|MDB_END_UPDATE;
3910 mdb_txn_end(txn, end_mode);
3918 /** Read the environment parameters of a DB environment before
3919 * mapping it into memory.
3920 * @param[in] env the environment handle
3921 * @param[out] meta address of where to store the meta information
3922 * @return 0 on success, non-zero on failure.
3925 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3931 enum { Size = sizeof(pbuf) };
3933 /* We don't know the page size yet, so use a minimum value.
3934 * Read both meta pages so we can use the latest one.
3937 for (i=off=0; i<NUM_METAS; i++, off += meta->mm_psize) {
3941 memset(&ov, 0, sizeof(ov));
3943 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3944 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3947 rc = pread(env->me_fd, &pbuf, Size, off);
3950 if (rc == 0 && off == 0)
3952 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3953 DPRINTF(("read: %s", mdb_strerror(rc)));
3957 p = (MDB_page *)&pbuf;
3959 if (!F_ISSET(p->mp_flags, P_META)) {
3960 DPRINTF(("page %"Yu" not a meta page", p->mp_pgno));
3965 if (m->mm_magic != MDB_MAGIC) {
3966 DPUTS("meta has invalid magic");
3970 if (m->mm_version != MDB_DATA_VERSION) {
3971 DPRINTF(("database is version %u, expected version %u",
3972 m->mm_version, MDB_DATA_VERSION));
3973 return MDB_VERSION_MISMATCH;
3976 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3982 /** Fill in most of the zeroed #MDB_meta for an empty database environment */
3984 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
3986 meta->mm_magic = MDB_MAGIC;
3987 meta->mm_version = MDB_DATA_VERSION;
3988 meta->mm_mapsize = env->me_mapsize;
3989 meta->mm_psize = env->me_psize;
3990 meta->mm_last_pg = NUM_METAS-1;
3991 meta->mm_flags = env->me_flags & 0xffff;
3992 meta->mm_flags |= MDB_INTEGERKEY; /* this is mm_dbs[FREE_DBI].md_flags */
3993 meta->mm_dbs[FREE_DBI].md_root = P_INVALID;
3994 meta->mm_dbs[MAIN_DBI].md_root = P_INVALID;
3997 /** Write the environment parameters of a freshly created DB environment.
3998 * @param[in] env the environment handle
3999 * @param[in] meta the #MDB_meta to write
4000 * @return 0 on success, non-zero on failure.
4003 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
4011 memset(&ov, 0, sizeof(ov));
4012 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
4014 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
4017 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
4018 len = pwrite(fd, ptr, size, pos); \
4019 if (len == -1 && ErrCode() == EINTR) continue; \
4020 rc = (len >= 0); break; } while(1)
4023 DPUTS("writing new meta page");
4025 psize = env->me_psize;
4027 p = calloc(NUM_METAS, psize);
4031 p->mp_flags = P_META;
4032 *(MDB_meta *)METADATA(p) = *meta;
4034 q = (MDB_page *)((char *)p + psize);
4036 q->mp_flags = P_META;
4037 *(MDB_meta *)METADATA(q) = *meta;
4039 DO_PWRITE(rc, env->me_fd, p, psize * NUM_METAS, len, 0);
4042 else if ((unsigned) len == psize * NUM_METAS)
4050 /** Update the environment info to commit a transaction.
4051 * @param[in] txn the transaction that's being committed
4052 * @return 0 on success, non-zero on failure.
4055 mdb_env_write_meta(MDB_txn *txn)
4058 MDB_meta meta, metab, *mp;
4062 int rc, len, toggle;
4071 toggle = txn->mt_txnid & 1;
4072 DPRINTF(("writing meta page %d for root page %"Yu,
4073 toggle, txn->mt_dbs[MAIN_DBI].md_root));
4076 flags = txn->mt_flags | env->me_flags;
4077 mp = env->me_metas[toggle];
4078 mapsize = env->me_metas[toggle ^ 1]->mm_mapsize;
4079 /* Persist any increases of mapsize config */
4080 if (mapsize < env->me_mapsize)
4081 mapsize = env->me_mapsize;
4083 if (flags & MDB_WRITEMAP) {
4084 mp->mm_mapsize = mapsize;
4085 mp->mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
4086 mp->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
4087 mp->mm_last_pg = txn->mt_next_pgno - 1;
4088 #if (__GNUC__ * 100 + __GNUC_MINOR__ >= 404) && /* TODO: portability */ \
4089 !(defined(__i386__) || defined(__x86_64__))
4090 /* LY: issue a memory barrier, if not x86. ITS#7969 */
4091 __sync_synchronize();
4093 mp->mm_txnid = txn->mt_txnid;
4094 if (!(flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
4095 unsigned meta_size = env->me_psize;
4096 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
4097 ptr = (char *)mp - PAGEHDRSZ;
4098 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
4099 r2 = (ptr - env->me_map) & (env->me_os_psize - 1);
4103 if (MDB_MSYNC(ptr, meta_size, rc)) {
4110 metab.mm_txnid = mp->mm_txnid;
4111 metab.mm_last_pg = mp->mm_last_pg;
4113 meta.mm_mapsize = mapsize;
4114 meta.mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
4115 meta.mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
4116 meta.mm_last_pg = txn->mt_next_pgno - 1;
4117 meta.mm_txnid = txn->mt_txnid;
4119 off = offsetof(MDB_meta, mm_mapsize);
4120 ptr = (char *)&meta + off;
4121 len = sizeof(MDB_meta) - off;
4122 off += (char *)mp - env->me_map;
4124 /* Write to the SYNC fd unless MDB_NOSYNC/MDB_NOMETASYNC.
4125 * (me_mfd goes to the same file as me_fd, but writing to it
4126 * also syncs to disk. Avoids a separate fdatasync() call.)
4128 mfd = (flags & (MDB_NOSYNC|MDB_NOMETASYNC)) ? env->me_fd : env->me_mfd;
4131 memset(&ov, 0, sizeof(ov));
4133 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
4138 rc = pwrite(mfd, ptr, len, off);
4141 rc = rc < 0 ? ErrCode() : EIO;
4146 DPUTS("write failed, disk error?");
4147 /* On a failure, the pagecache still contains the new data.
4148 * Write some old data back, to prevent it from being used.
4149 * Use the non-SYNC fd; we know it will fail anyway.
4151 meta.mm_last_pg = metab.mm_last_pg;
4152 meta.mm_txnid = metab.mm_txnid;
4154 memset(&ov, 0, sizeof(ov));
4156 WriteFile(env->me_fd, ptr, len, NULL, &ov);
4158 r2 = pwrite(env->me_fd, ptr, len, off);
4159 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
4162 env->me_flags |= MDB_FATAL_ERROR;
4165 /* MIPS has cache coherency issues, this is a no-op everywhere else */
4166 CACHEFLUSH(env->me_map + off, len, DCACHE);
4168 /* Memory ordering issues are irrelevant; since the entire writer
4169 * is wrapped by wmutex, all of these changes will become visible
4170 * after the wmutex is unlocked. Since the DB is multi-version,
4171 * readers will get consistent data regardless of how fresh or
4172 * how stale their view of these values is.
4175 env->me_txns->mti_txnid = txn->mt_txnid;
4180 /** Check both meta pages to see which one is newer.
4181 * @param[in] env the environment handle
4182 * @return newest #MDB_meta.
4185 mdb_env_pick_meta(const MDB_env *env)
4187 MDB_meta *const *metas = env->me_metas;
4188 return metas[ metas[0]->mm_txnid < metas[1]->mm_txnid ];
4192 mdb_env_create(MDB_env **env)
4196 e = calloc(1, sizeof(MDB_env));
4200 e->me_maxreaders = DEFAULT_READERS;
4201 e->me_maxdbs = e->me_numdbs = CORE_DBS;
4202 e->me_fd = INVALID_HANDLE_VALUE;
4203 e->me_lfd = INVALID_HANDLE_VALUE;
4204 e->me_mfd = INVALID_HANDLE_VALUE;
4205 #ifdef MDB_USE_POSIX_SEM
4206 e->me_rmutex = SEM_FAILED;
4207 e->me_wmutex = SEM_FAILED;
4208 #elif defined MDB_USE_SYSV_SEM
4209 e->me_rmutex->semid = -1;
4210 e->me_wmutex->semid = -1;
4212 e->me_pid = getpid();
4213 GET_PAGESIZE(e->me_os_psize);
4214 VGMEMP_CREATE(e,0,0);
4220 /** @brief Map a result from an NTAPI call to WIN32. */
4222 mdb_nt2win32(NTSTATUS st)
4227 GetOverlappedResult(NULL, &o, &br, FALSE);
4228 return GetLastError();
4233 mdb_env_map(MDB_env *env, void *addr)
4236 unsigned int flags = env->me_flags;
4239 int access = SECTION_MAP_READ;
4243 ULONG pageprot = PAGE_READONLY, secprot, alloctype;
4245 if (flags & MDB_WRITEMAP) {
4246 access |= SECTION_MAP_WRITE;
4247 pageprot = PAGE_READWRITE;
4249 if (flags & MDB_RDONLY) {
4250 secprot = PAGE_READONLY;
4254 secprot = PAGE_READWRITE;
4255 msize = env->me_mapsize;
4256 alloctype = MEM_RESERVE;
4259 rc = NtCreateSection(&mh, access, NULL, NULL, secprot, SEC_RESERVE, env->me_fd);
4261 return mdb_nt2win32(rc);
4264 msize = NUM_METAS * env->me_psize;
4266 rc = NtMapViewOfSection(mh, GetCurrentProcess(), &map, 0, 0, NULL, &msize, ViewUnmap, alloctype, pageprot);
4273 return mdb_nt2win32(rc);
4278 env->me_map = mmap(addr, NUM_METAS * env->me_psize, PROT_READ, MAP_SHARED,
4280 if (env->me_map == MAP_FAILED) {
4285 int prot = PROT_READ;
4286 if (flags & MDB_WRITEMAP) {
4288 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
4291 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
4293 if (env->me_map == MAP_FAILED) {
4298 if (flags & MDB_NORDAHEAD) {
4299 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
4301 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
4303 #ifdef POSIX_MADV_RANDOM
4304 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
4305 #endif /* POSIX_MADV_RANDOM */
4306 #endif /* MADV_RANDOM */
4310 /* Can happen because the address argument to mmap() is just a
4311 * hint. mmap() can pick another, e.g. if the range is in use.
4312 * The MAP_FIXED flag would prevent that, but then mmap could
4313 * instead unmap existing pages to make room for the new map.
4315 if (addr && env->me_map != addr)
4316 return EBUSY; /* TODO: Make a new MDB_* error code? */
4319 p = (MDB_page *)env->me_map;
4320 env->me_metas[0] = METADATA(p);
4321 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
4327 mdb_env_set_mapsize(MDB_env *env, mdb_size_t size)
4329 /* If env is already open, caller is responsible for making
4330 * sure there are no active txns.
4340 meta = mdb_env_pick_meta(env);
4342 size = meta->mm_mapsize;
4344 /* Silently round up to minimum if the size is too small */
4345 mdb_size_t minsize = (meta->mm_last_pg + 1) * env->me_psize;
4350 /* For MDB_VL32 this bit is a noop since we dynamically remap
4351 * chunks of the DB anyway.
4353 munmap(env->me_map, env->me_mapsize);
4354 env->me_mapsize = size;
4355 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
4356 rc = mdb_env_map(env, old);
4359 #endif /* !MDB_VL32 */
4361 env->me_mapsize = size;
4363 env->me_maxpg = env->me_mapsize / env->me_psize;
4368 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
4372 env->me_maxdbs = dbs + CORE_DBS;
4377 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
4379 if (env->me_map || readers < 1)
4381 env->me_maxreaders = readers;
4386 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
4388 if (!env || !readers)
4390 *readers = env->me_maxreaders;
4395 mdb_fsize(HANDLE fd, mdb_size_t *size)
4398 LARGE_INTEGER fsize;
4400 if (!GetFileSizeEx(fd, &fsize))
4403 *size = fsize.QuadPart;
4417 typedef wchar_t mdb_nchar_t;
4418 # define MDB_NAME(str) L##str
4419 # define mdb_name_cpy wcscpy
4421 /** Character type for file names: char on Unix, wchar_t on Windows */
4422 typedef char mdb_nchar_t;
4423 # define MDB_NAME(str) str /**< #mdb_nchar_t[] string literal */
4424 # define mdb_name_cpy strcpy /**< Copy name (#mdb_nchar_t string) */
4427 /** Filename - string of #mdb_nchar_t[] */
4428 typedef struct MDB_name {
4429 int mn_len; /**< Length */
4430 int mn_alloced; /**< True if #mn_val was malloced */
4431 mdb_nchar_t *mn_val; /**< Contents */
4434 /** Filename suffixes [datafile,lockfile][without,with MDB_NOSUBDIR] */
4435 static const mdb_nchar_t *const mdb_suffixes[2][2] = {
4436 { MDB_NAME("/data.mdb"), MDB_NAME("") },
4437 { MDB_NAME("/lock.mdb"), MDB_NAME("-lock") }
4440 #define MDB_SUFFLEN 9 /**< Max string length in #mdb_suffixes[] */
4442 /** Set up filename + scratch area for filename suffix, for opening files.
4443 * It should be freed with #mdb_fname_destroy().
4444 * On Windows, paths are converted from char *UTF-8 to wchar_t *UTF-16.
4446 * @param[in] path Pathname for #mdb_env_open().
4447 * @param[in] envflags Whether a subdir and/or lockfile will be used.
4448 * @param[out] fname Resulting filename, with room for a suffix if necessary.
4451 mdb_fname_init(const char *path, unsigned envflags, MDB_name *fname)
4453 int no_suffix = F_ISSET(envflags, MDB_NOSUBDIR|MDB_NOLOCK);
4454 fname->mn_alloced = 0;
4456 return utf8_to_utf16(path, fname, no_suffix ? 0 : MDB_SUFFLEN);
4458 fname->mn_len = strlen(path);
4460 fname->mn_val = (char *) path;
4461 else if ((fname->mn_val = malloc(fname->mn_len + MDB_SUFFLEN+1)) != NULL) {
4462 fname->mn_alloced = 1;
4463 strcpy(fname->mn_val, path);
4471 /** Destroy \b fname from #mdb_fname_init() */
4472 #define mdb_fname_destroy(fname) \
4473 do { if ((fname).mn_alloced) free((fname).mn_val); } while (0)
4475 #ifdef O_CLOEXEC /* POSIX.1-2008: Set FD_CLOEXEC atomically at open() */
4476 # define MDB_CLOEXEC O_CLOEXEC
4478 # define MDB_CLOEXEC 0
4481 /** File type, access mode etc. for #mdb_fopen() */
4482 enum mdb_fopen_type {
4484 MDB_O_RDONLY, MDB_O_RDWR, MDB_O_META, MDB_O_COPY, MDB_O_LOCKS
4486 /* A comment in mdb_fopen() explains some O_* flag choices. */
4487 MDB_O_RDONLY= O_RDONLY, /**< for RDONLY me_fd */
4488 MDB_O_RDWR = O_RDWR |O_CREAT, /**< for me_fd */
4489 MDB_O_META = O_WRONLY|MDB_DSYNC |MDB_CLOEXEC, /**< for me_mfd */
4490 MDB_O_COPY = O_WRONLY|O_CREAT|O_EXCL|MDB_CLOEXEC, /**< for #mdb_env_copy() */
4491 /** Bitmask for open() flags in enum #mdb_fopen_type. The other bits
4492 * distinguish otherwise-equal MDB_O_* constants from each other.
4494 MDB_O_MASK = MDB_O_RDWR|MDB_CLOEXEC | MDB_O_RDONLY|MDB_O_META|MDB_O_COPY,
4495 MDB_O_LOCKS = MDB_O_RDWR|MDB_CLOEXEC | ((MDB_O_MASK+1) & ~MDB_O_MASK) /**< for me_lfd */
4499 /** Open an LMDB file.
4500 * @param[in] env The LMDB environment.
4501 * @param[in,out] fname Path from from #mdb_fname_init(). A suffix is
4502 * appended if necessary to create the filename, without changing mn_len.
4503 * @param[in] which Determines file type, access mode, etc.
4504 * @param[in] mode The Unix permissions for the file, if we create it.
4505 * @param[out] res Resulting file handle.
4506 * @return 0 on success, non-zero on failure.
4509 mdb_fopen(const MDB_env *env, MDB_name *fname,
4510 enum mdb_fopen_type which, mdb_mode_t mode,
4513 int rc = MDB_SUCCESS;
4516 DWORD acc, share, disp, attrs;
4521 if (fname->mn_alloced) /* modifiable copy */
4522 mdb_name_cpy(fname->mn_val + fname->mn_len,
4523 mdb_suffixes[which==MDB_O_LOCKS][F_ISSET(env->me_flags, MDB_NOSUBDIR)]);
4525 /* The directory must already exist. Usually the file need not.
4526 * MDB_O_META requires the file because we already created it using
4527 * MDB_O_RDWR. MDB_O_COPY must not overwrite an existing file.
4529 * With MDB_O_COPY we do not want the OS to cache the writes, since
4530 * the source data is already in the OS cache.
4532 * The lockfile needs FD_CLOEXEC (close file descriptor on exec*())
4533 * to avoid the flock() issues noted under Caveats in lmdb.h.
4534 * Also set it for other filehandles which the user cannot get at
4535 * and close himself, which he may need after fork(). I.e. all but
4536 * me_fd, which programs do use via mdb_env_get_fd().
4540 acc = GENERIC_READ|GENERIC_WRITE;
4541 share = FILE_SHARE_READ|FILE_SHARE_WRITE;
4543 attrs = FILE_ATTRIBUTE_NORMAL;
4545 case MDB_O_RDONLY: /* read-only datafile */
4547 disp = OPEN_EXISTING;
4549 case MDB_O_META: /* for writing metapages */
4550 acc = GENERIC_WRITE;
4551 disp = OPEN_EXISTING;
4552 attrs = FILE_ATTRIBUTE_NORMAL|FILE_FLAG_WRITE_THROUGH;
4554 case MDB_O_COPY: /* mdb_env_copy() & co */
4555 acc = GENERIC_WRITE;
4558 attrs = FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH;
4560 default: break; /* silence gcc -Wswitch (not all enum values handled) */
4562 fd = CreateFileW(fname->mn_val, acc, share, NULL, disp, attrs, NULL);
4564 fd = open(fname->mn_val, which & MDB_O_MASK, mode);
4567 if (fd == INVALID_HANDLE_VALUE)
4571 if (which != MDB_O_RDONLY && which != MDB_O_RDWR) {
4572 /* Set CLOEXEC if we could not pass it to open() */
4573 if (!MDB_CLOEXEC && (flags = fcntl(fd, F_GETFD)) != -1)
4574 (void) fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
4576 if (which == MDB_O_COPY && env->me_psize >= env->me_os_psize) {
4577 /* This may require buffer alignment. There is no portable
4578 * way to ask how much, so we require OS pagesize alignment.
4580 # ifdef F_NOCACHE /* __APPLE__ */
4581 (void) fcntl(fd, F_NOCACHE, 1);
4582 # elif defined O_DIRECT
4583 /* open(...O_DIRECT...) would break on filesystems without
4584 * O_DIRECT support (ITS#7682). Try to set it here instead.
4586 if ((flags = fcntl(fd, F_GETFL)) != -1)
4587 (void) fcntl(fd, F_SETFL, flags | O_DIRECT);
4591 #endif /* !_WIN32 */
4598 #ifdef BROKEN_FDATASYNC
4599 #include <sys/utsname.h>
4600 #include <sys/vfs.h>
4603 /** Further setup required for opening an LMDB environment
4606 mdb_env_open2(MDB_env *env)
4608 unsigned int flags = env->me_flags;
4609 int i, newenv = 0, rc;
4613 /* See if we should use QueryLimited */
4615 if ((rc & 0xff) > 5)
4616 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
4618 env->me_pidquery = PROCESS_QUERY_INFORMATION;
4621 #ifdef BROKEN_FDATASYNC
4622 /* ext3/ext4 fdatasync is broken on some older Linux kernels.
4623 * https://lkml.org/lkml/2012/9/3/83
4624 * Kernels after 3.6-rc6 are known good.
4625 * https://lkml.org/lkml/2012/9/10/556
4626 * See if the DB is on ext3/ext4, then check for new enough kernel
4627 * Kernels 2.6.32.60, 2.6.34.15, 3.2.30, and 3.5.4 are also known
4632 fstatfs(env->me_fd, &st);
4633 while (st.f_type == 0xEF53) {
4637 if (uts.release[0] < '3') {
4638 if (!strncmp(uts.release, "2.6.32.", 7)) {
4639 i = atoi(uts.release+7);
4641 break; /* 2.6.32.60 and newer is OK */
4642 } else if (!strncmp(uts.release, "2.6.34.", 7)) {
4643 i = atoi(uts.release+7);
4645 break; /* 2.6.34.15 and newer is OK */
4647 } else if (uts.release[0] == '3') {
4648 i = atoi(uts.release+2);
4650 break; /* 3.6 and newer is OK */
4652 i = atoi(uts.release+4);
4654 break; /* 3.5.4 and newer is OK */
4655 } else if (i == 2) {
4656 i = atoi(uts.release+4);
4658 break; /* 3.2.30 and newer is OK */
4660 } else { /* 4.x and newer is OK */
4663 env->me_flags |= MDB_FSYNCONLY;
4669 if ((i = mdb_env_read_header(env, &meta)) != 0) {
4672 DPUTS("new mdbenv");
4674 env->me_psize = env->me_os_psize;
4675 if (env->me_psize > MAX_PAGESIZE)
4676 env->me_psize = MAX_PAGESIZE;
4677 memset(&meta, 0, sizeof(meta));
4678 mdb_env_init_meta0(env, &meta);
4679 meta.mm_mapsize = DEFAULT_MAPSIZE;
4681 env->me_psize = meta.mm_psize;
4684 /* Was a mapsize configured? */
4685 if (!env->me_mapsize) {
4686 env->me_mapsize = meta.mm_mapsize;
4689 /* Make sure mapsize >= committed data size. Even when using
4690 * mm_mapsize, which could be broken in old files (ITS#7789).
4692 mdb_size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
4693 if (env->me_mapsize < minsize)
4694 env->me_mapsize = minsize;
4696 meta.mm_mapsize = env->me_mapsize;
4698 if (newenv && !(flags & MDB_FIXEDMAP)) {
4699 /* mdb_env_map() may grow the datafile. Write the metapages
4700 * first, so the file will be valid if initialization fails.
4701 * Except with FIXEDMAP, since we do not yet know mm_address.
4702 * We could fill in mm_address later, but then a different
4703 * program might end up doing that - one with a memory layout
4704 * and map address which does not suit the main program.
4706 rc = mdb_env_init_meta(env, &meta);
4712 /* For FIXEDMAP, make sure the file is non-empty before we attempt to map it */
4716 rc = WriteFile(env->me_fd, &dummy, 1, &len, NULL);
4724 rc = mdb_env_map(env, (flags & MDB_FIXEDMAP) ? meta.mm_address : NULL);
4729 if (flags & MDB_FIXEDMAP)
4730 meta.mm_address = env->me_map;
4731 i = mdb_env_init_meta(env, &meta);
4732 if (i != MDB_SUCCESS) {
4737 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
4738 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
4740 #if !(MDB_MAXKEYSIZE)
4741 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
4743 env->me_maxpg = env->me_mapsize / env->me_psize;
4747 MDB_meta *meta = mdb_env_pick_meta(env);
4748 MDB_db *db = &meta->mm_dbs[MAIN_DBI];
4750 DPRINTF(("opened database version %u, pagesize %u",
4751 meta->mm_version, env->me_psize));
4752 DPRINTF(("using meta page %d", (int) (meta->mm_txnid & 1)));
4753 DPRINTF(("depth: %u", db->md_depth));
4754 DPRINTF(("entries: %"Yu, db->md_entries));
4755 DPRINTF(("branch pages: %"Yu, db->md_branch_pages));
4756 DPRINTF(("leaf pages: %"Yu, db->md_leaf_pages));
4757 DPRINTF(("overflow pages: %"Yu, db->md_overflow_pages));
4758 DPRINTF(("root: %"Yu, db->md_root));
4766 /** Release a reader thread's slot in the reader lock table.
4767 * This function is called automatically when a thread exits.
4768 * @param[in] ptr This points to the slot in the reader lock table.
4771 mdb_env_reader_dest(void *ptr)
4773 MDB_reader *reader = ptr;
4776 if (reader->mr_pid == getpid()) /* catch pthread_exit() in child process */
4778 /* We omit the mutex, so do this atomically (i.e. skip mr_txnid) */
4783 /** Junk for arranging thread-specific callbacks on Windows. This is
4784 * necessarily platform and compiler-specific. Windows supports up
4785 * to 1088 keys. Let's assume nobody opens more than 64 environments
4786 * in a single process, for now. They can override this if needed.
4788 #ifndef MAX_TLS_KEYS
4789 #define MAX_TLS_KEYS 64
4791 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
4792 static int mdb_tls_nkeys;
4794 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
4798 case DLL_PROCESS_ATTACH: break;
4799 case DLL_THREAD_ATTACH: break;
4800 case DLL_THREAD_DETACH:
4801 for (i=0; i<mdb_tls_nkeys; i++) {
4802 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
4804 mdb_env_reader_dest(r);
4808 case DLL_PROCESS_DETACH: break;
4813 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4815 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4819 /* Force some symbol references.
4820 * _tls_used forces the linker to create the TLS directory if not already done
4821 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
4823 #pragma comment(linker, "/INCLUDE:_tls_used")
4824 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
4825 #pragma const_seg(".CRT$XLB")
4826 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
4827 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4830 #pragma comment(linker, "/INCLUDE:__tls_used")
4831 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
4832 #pragma data_seg(".CRT$XLB")
4833 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4835 #endif /* WIN 32/64 */
4836 #endif /* !__GNUC__ */
4839 /** Downgrade the exclusive lock on the region back to shared */
4841 mdb_env_share_locks(MDB_env *env, int *excl)
4844 MDB_meta *meta = mdb_env_pick_meta(env);
4846 env->me_txns->mti_txnid = meta->mm_txnid;
4851 /* First acquire a shared lock. The Unlock will
4852 * then release the existing exclusive lock.
4854 memset(&ov, 0, sizeof(ov));
4855 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4858 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4864 struct flock lock_info;
4865 /* The shared lock replaces the existing lock */
4866 memset((void *)&lock_info, 0, sizeof(lock_info));
4867 lock_info.l_type = F_RDLCK;
4868 lock_info.l_whence = SEEK_SET;
4869 lock_info.l_start = 0;
4870 lock_info.l_len = 1;
4871 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4872 (rc = ErrCode()) == EINTR) ;
4873 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
4880 /** Try to get exclusive lock, otherwise shared.
4881 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
4884 mdb_env_excl_lock(MDB_env *env, int *excl)
4888 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
4892 memset(&ov, 0, sizeof(ov));
4893 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4900 struct flock lock_info;
4901 memset((void *)&lock_info, 0, sizeof(lock_info));
4902 lock_info.l_type = F_WRLCK;
4903 lock_info.l_whence = SEEK_SET;
4904 lock_info.l_start = 0;
4905 lock_info.l_len = 1;
4906 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4907 (rc = ErrCode()) == EINTR) ;
4911 # ifndef MDB_USE_POSIX_MUTEX
4912 if (*excl < 0) /* always true when MDB_USE_POSIX_MUTEX */
4915 lock_info.l_type = F_RDLCK;
4916 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
4917 (rc = ErrCode()) == EINTR) ;
4927 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
4929 * @(#) $Revision: 5.1 $
4930 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
4931 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
4933 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
4937 * Please do not copyright this code. This code is in the public domain.
4939 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
4940 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
4941 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
4942 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
4943 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4944 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4945 * PERFORMANCE OF THIS SOFTWARE.
4948 * chongo <Landon Curt Noll> /\oo/\
4949 * http://www.isthe.com/chongo/
4951 * Share and Enjoy! :-)
4954 typedef unsigned long long mdb_hash_t;
4955 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
4957 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
4958 * @param[in] val value to hash
4959 * @param[in] hval initial value for hash
4960 * @return 64 bit hash
4962 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
4963 * hval arg on the first call.
4966 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
4968 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
4969 unsigned char *end = s + val->mv_size;
4971 * FNV-1a hash each octet of the string
4974 /* xor the bottom with the current octet */
4975 hval ^= (mdb_hash_t)*s++;
4977 /* multiply by the 64 bit FNV magic prime mod 2^64 */
4978 hval += (hval << 1) + (hval << 4) + (hval << 5) +
4979 (hval << 7) + (hval << 8) + (hval << 40);
4981 /* return our new hash value */
4985 /** Hash the string and output the encoded hash.
4986 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
4987 * very short name limits. We don't care about the encoding being reversible,
4988 * we just want to preserve as many bits of the input as possible in a
4989 * small printable string.
4990 * @param[in] str string to hash
4991 * @param[out] encbuf an array of 11 chars to hold the hash
4993 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
4996 mdb_pack85(unsigned long l, char *out)
5000 for (i=0; i<5; i++) {
5001 *out++ = mdb_a85[l % 85];
5007 mdb_hash_enc(MDB_val *val, char *encbuf)
5009 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
5011 mdb_pack85(h, encbuf);
5012 mdb_pack85(h>>32, encbuf+5);
5017 /** Open and/or initialize the lock region for the environment.
5018 * @param[in] env The LMDB environment.
5019 * @param[in] fname Filename + scratch area, from #mdb_fname_init().
5020 * @param[in] mode The Unix permissions for the file, if we create it.
5021 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
5022 * @return 0 on success, non-zero on failure.
5025 mdb_env_setup_locks(MDB_env *env, MDB_name *fname, int mode, int *excl)
5028 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
5030 # define MDB_ERRCODE_ROFS EROFS
5032 #ifdef MDB_USE_SYSV_SEM
5039 rc = mdb_fopen(env, fname, MDB_O_LOCKS, mode, &env->me_lfd);
5041 /* Omit lockfile if read-only env on read-only filesystem */
5042 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
5048 if (!(env->me_flags & MDB_NOTLS)) {
5049 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
5052 env->me_flags |= MDB_ENV_TXKEY;
5054 /* Windows TLS callbacks need help finding their TLS info. */
5055 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
5059 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
5063 /* Try to get exclusive lock. If we succeed, then
5064 * nobody is using the lock region and we should initialize it.
5066 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
5069 size = GetFileSize(env->me_lfd, NULL);
5071 size = lseek(env->me_lfd, 0, SEEK_END);
5072 if (size == -1) goto fail_errno;
5074 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
5075 if (size < rsize && *excl > 0) {
5077 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
5078 || !SetEndOfFile(env->me_lfd))
5081 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
5085 size = rsize - sizeof(MDB_txninfo);
5086 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
5091 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
5093 if (!mh) goto fail_errno;
5094 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
5096 if (!env->me_txns) goto fail_errno;
5098 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
5100 if (m == MAP_FAILED) goto fail_errno;
5106 BY_HANDLE_FILE_INFORMATION stbuf;
5115 if (!mdb_sec_inited) {
5116 InitializeSecurityDescriptor(&mdb_null_sd,
5117 SECURITY_DESCRIPTOR_REVISION);
5118 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
5119 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
5120 mdb_all_sa.bInheritHandle = FALSE;
5121 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
5124 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
5125 idbuf.volume = stbuf.dwVolumeSerialNumber;
5126 idbuf.nhigh = stbuf.nFileIndexHigh;
5127 idbuf.nlow = stbuf.nFileIndexLow;
5128 val.mv_data = &idbuf;
5129 val.mv_size = sizeof(idbuf);
5130 mdb_hash_enc(&val, encbuf);
5131 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
5132 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
5133 env->me_rmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
5134 if (!env->me_rmutex) goto fail_errno;
5135 env->me_wmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
5136 if (!env->me_wmutex) goto fail_errno;
5137 #elif defined(MDB_USE_POSIX_SEM)
5146 #if defined(__NetBSD__)
5147 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
5149 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
5150 idbuf.dev = stbuf.st_dev;
5151 idbuf.ino = stbuf.st_ino;
5152 val.mv_data = &idbuf;
5153 val.mv_size = sizeof(idbuf);
5154 mdb_hash_enc(&val, encbuf);
5155 #ifdef MDB_SHORT_SEMNAMES
5156 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
5158 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
5159 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
5160 /* Clean up after a previous run, if needed: Try to
5161 * remove both semaphores before doing anything else.
5163 sem_unlink(env->me_txns->mti_rmname);
5164 sem_unlink(env->me_txns->mti_wmname);
5165 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
5166 O_CREAT|O_EXCL, mode, 1);
5167 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
5168 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
5169 O_CREAT|O_EXCL, mode, 1);
5170 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
5171 #elif defined(MDB_USE_SYSV_SEM)
5172 unsigned short vals[2] = {1, 1};
5173 key_t key = ftok(fname->mn_val, 'M'); /* fname is lockfile path now */
5176 semid = semget(key, 2, (mode & 0777) | IPC_CREAT);
5180 if (semctl(semid, 0, SETALL, semu) < 0)
5182 env->me_txns->mti_semid = semid;
5183 env->me_txns->mti_rlocked = 0;
5184 env->me_txns->mti_wlocked = 0;
5185 #else /* MDB_USE_POSIX_MUTEX: */
5186 pthread_mutexattr_t mattr;
5188 /* Solaris needs this before initing a robust mutex. Otherwise
5189 * it may skip the init and return EBUSY "seems someone already
5190 * inited" or EINVAL "it was inited differently".
5192 memset(env->me_txns->mti_rmutex, 0, sizeof(*env->me_txns->mti_rmutex));
5193 memset(env->me_txns->mti_wmutex, 0, sizeof(*env->me_txns->mti_wmutex));
5195 if ((rc = pthread_mutexattr_init(&mattr)) != 0)
5197 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
5198 #ifdef MDB_ROBUST_SUPPORTED
5199 if (!rc) rc = pthread_mutexattr_setrobust(&mattr, PTHREAD_MUTEX_ROBUST);
5201 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_rmutex, &mattr);
5202 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_wmutex, &mattr);
5203 pthread_mutexattr_destroy(&mattr);
5206 #endif /* _WIN32 || ... */
5208 env->me_txns->mti_magic = MDB_MAGIC;
5209 env->me_txns->mti_format = MDB_LOCK_FORMAT;
5210 env->me_txns->mti_txnid = 0;
5211 env->me_txns->mti_numreaders = 0;
5214 #ifdef MDB_USE_SYSV_SEM
5215 struct semid_ds buf;
5217 if (env->me_txns->mti_magic != MDB_MAGIC) {
5218 DPUTS("lock region has invalid magic");
5222 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
5223 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
5224 env->me_txns->mti_format, MDB_LOCK_FORMAT));
5225 rc = MDB_VERSION_MISMATCH;
5229 if (rc && rc != EACCES && rc != EAGAIN) {
5233 env->me_rmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
5234 if (!env->me_rmutex) goto fail_errno;
5235 env->me_wmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
5236 if (!env->me_wmutex) goto fail_errno;
5237 #elif defined(MDB_USE_POSIX_SEM)
5238 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
5239 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
5240 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
5241 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
5242 #elif defined(MDB_USE_SYSV_SEM)
5243 semid = env->me_txns->mti_semid;
5245 /* check for read access */
5246 if (semctl(semid, 0, IPC_STAT, semu) < 0)
5248 /* check for write access */
5249 if (semctl(semid, 0, IPC_SET, semu) < 0)
5253 #ifdef MDB_USE_SYSV_SEM
5254 env->me_rmutex->semid = semid;
5255 env->me_wmutex->semid = semid;
5256 env->me_rmutex->semnum = 0;
5257 env->me_wmutex->semnum = 1;
5258 env->me_rmutex->locked = &env->me_txns->mti_rlocked;
5259 env->me_wmutex->locked = &env->me_txns->mti_wlocked;
5270 /** Only a subset of the @ref mdb_env flags can be changed
5271 * at runtime. Changing other flags requires closing the
5272 * environment and re-opening it with the new flags.
5274 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
5275 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY| \
5276 MDB_WRITEMAP|MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
5278 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
5279 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
5283 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
5288 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
5292 if (flags & MDB_WRITEMAP) {
5293 /* silently ignore WRITEMAP in 32 bit mode */
5294 flags ^= MDB_WRITEMAP;
5296 if (flags & MDB_FIXEDMAP) {
5297 /* cannot support FIXEDMAP */
5301 flags |= env->me_flags;
5303 rc = mdb_fname_init(path, flags, &fname);
5309 env->me_rpmutex = CreateMutex(NULL, FALSE, NULL);
5310 if (!env->me_rpmutex) {
5315 rc = pthread_mutex_init(&env->me_rpmutex, NULL);
5320 flags |= MDB_ENV_ACTIVE; /* tell mdb_env_close0() to clean up */
5322 if (flags & MDB_RDONLY) {
5323 /* silently ignore WRITEMAP when we're only getting read access */
5324 flags &= ~MDB_WRITEMAP;
5326 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
5327 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
5331 env->me_flags = flags;
5337 env->me_rpages = malloc(MDB_ERPAGE_SIZE * sizeof(MDB_ID3));
5338 if (!env->me_rpages) {
5342 env->me_rpages[0].mid = 0;
5343 env->me_rpcheck = MDB_ERPAGE_SIZE/2;
5347 env->me_path = strdup(path);
5348 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
5349 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
5350 env->me_dbiseqs = calloc(env->me_maxdbs, sizeof(unsigned int));
5351 if (!(env->me_dbxs && env->me_path && env->me_dbflags && env->me_dbiseqs)) {
5355 env->me_dbxs[FREE_DBI].md_cmp = mdb_cmp_long; /* aligned MDB_INTEGERKEY */
5357 /* For RDONLY, get lockfile after we know datafile exists */
5358 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
5359 rc = mdb_env_setup_locks(env, &fname, mode, &excl);
5364 rc = mdb_fopen(env, &fname,
5365 (flags & MDB_RDONLY) ? MDB_O_RDONLY : MDB_O_RDWR,
5370 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
5371 rc = mdb_env_setup_locks(env, &fname, mode, &excl);
5376 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
5377 if (!(flags & (MDB_RDONLY|MDB_WRITEMAP))) {
5378 /* Synchronous fd for meta writes. Needed even with
5379 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
5381 rc = mdb_fopen(env, &fname, MDB_O_META, mode, &env->me_mfd);
5385 DPRINTF(("opened dbenv %p", (void *) env));
5387 rc = mdb_env_share_locks(env, &excl);
5391 if (!(flags & MDB_RDONLY)) {
5393 int tsize = sizeof(MDB_txn), size = tsize + env->me_maxdbs *
5394 (sizeof(MDB_db)+sizeof(MDB_cursor *)+sizeof(unsigned int)+1);
5395 if ((env->me_pbuf = calloc(1, env->me_psize)) &&
5396 (txn = calloc(1, size)))
5398 txn->mt_dbs = (MDB_db *)((char *)txn + tsize);
5399 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
5400 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
5401 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
5404 txn->mt_rpages = malloc(MDB_TRPAGE_SIZE * sizeof(MDB_ID3));
5405 if (!txn->mt_rpages) {
5410 txn->mt_rpages[0].mid = 0;
5411 txn->mt_rpcheck = MDB_TRPAGE_SIZE/2;
5413 txn->mt_dbxs = env->me_dbxs;
5414 txn->mt_flags = MDB_TXN_FINISHED;
5424 mdb_env_close0(env, excl);
5426 mdb_fname_destroy(fname);
5430 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
5432 mdb_env_close0(MDB_env *env, int excl)
5436 if (!(env->me_flags & MDB_ENV_ACTIVE))
5439 /* Doing this here since me_dbxs may not exist during mdb_env_close */
5441 for (i = env->me_maxdbs; --i >= CORE_DBS; )
5442 free(env->me_dbxs[i].md_name.mv_data);
5447 free(env->me_dbiseqs);
5448 free(env->me_dbflags);
5450 free(env->me_dirty_list);
5452 if (env->me_txn0 && env->me_txn0->mt_rpages)
5453 free(env->me_txn0->mt_rpages);
5454 if (env->me_rpages) {
5455 MDB_ID3L el = env->me_rpages;
5457 for (x=1; x<=el[0].mid; x++)
5458 munmap(el[x].mptr, el[x].mcnt * env->me_psize);
5463 mdb_midl_free(env->me_free_pgs);
5465 if (env->me_flags & MDB_ENV_TXKEY) {
5466 pthread_key_delete(env->me_txkey);
5468 /* Delete our key from the global list */
5469 for (i=0; i<mdb_tls_nkeys; i++)
5470 if (mdb_tls_keys[i] == env->me_txkey) {
5471 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
5480 munmap(env->me_map, NUM_METAS*env->me_psize);
5482 munmap(env->me_map, env->me_mapsize);
5485 if (env->me_mfd != INVALID_HANDLE_VALUE)
5486 (void) close(env->me_mfd);
5487 if (env->me_fd != INVALID_HANDLE_VALUE)
5488 (void) close(env->me_fd);
5490 MDB_PID_T pid = env->me_pid;
5491 /* Clearing readers is done in this function because
5492 * me_txkey with its destructor must be disabled first.
5494 * We skip the the reader mutex, so we touch only
5495 * data owned by this process (me_close_readers and
5496 * our readers), and clear each reader atomically.
5498 for (i = env->me_close_readers; --i >= 0; )
5499 if (env->me_txns->mti_readers[i].mr_pid == pid)
5500 env->me_txns->mti_readers[i].mr_pid = 0;
5502 if (env->me_rmutex) {
5503 CloseHandle(env->me_rmutex);
5504 if (env->me_wmutex) CloseHandle(env->me_wmutex);
5506 /* Windows automatically destroys the mutexes when
5507 * the last handle closes.
5509 #elif defined(MDB_USE_POSIX_SEM)
5510 if (env->me_rmutex != SEM_FAILED) {
5511 sem_close(env->me_rmutex);
5512 if (env->me_wmutex != SEM_FAILED)
5513 sem_close(env->me_wmutex);
5514 /* If we have the filelock: If we are the
5515 * only remaining user, clean up semaphores.
5518 mdb_env_excl_lock(env, &excl);
5520 sem_unlink(env->me_txns->mti_rmname);
5521 sem_unlink(env->me_txns->mti_wmname);
5524 #elif defined(MDB_USE_SYSV_SEM)
5525 if (env->me_rmutex->semid != -1) {
5526 /* If we have the filelock: If we are the
5527 * only remaining user, clean up semaphores.
5530 mdb_env_excl_lock(env, &excl);
5532 semctl(env->me_rmutex->semid, 0, IPC_RMID);
5535 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
5537 if (env->me_lfd != INVALID_HANDLE_VALUE) {
5540 /* Unlock the lockfile. Windows would have unlocked it
5541 * after closing anyway, but not necessarily at once.
5543 UnlockFile(env->me_lfd, 0, 0, 1, 0);
5546 (void) close(env->me_lfd);
5550 if (env->me_fmh) CloseHandle(env->me_fmh);
5551 if (env->me_rpmutex) CloseHandle(env->me_rpmutex);
5553 pthread_mutex_destroy(&env->me_rpmutex);
5557 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
5561 mdb_env_close(MDB_env *env)
5568 VGMEMP_DESTROY(env);
5569 while ((dp = env->me_dpages) != NULL) {
5570 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
5571 env->me_dpages = dp->mp_next;
5575 mdb_env_close0(env, 0);
5579 /** Compare two items pointing at aligned #mdb_size_t's */
5581 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
5583 return (*(mdb_size_t *)a->mv_data < *(mdb_size_t *)b->mv_data) ? -1 :
5584 *(mdb_size_t *)a->mv_data > *(mdb_size_t *)b->mv_data;
5587 /** Compare two items pointing at aligned unsigned int's.
5589 * This is also set as #MDB_INTEGERDUP|#MDB_DUPFIXED's #MDB_dbx.%md_dcmp,
5590 * but #mdb_cmp_clong() is called instead if the data type is #mdb_size_t.
5593 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
5595 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
5596 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
5599 /** Compare two items pointing at unsigned ints of unknown alignment.
5600 * Nodes and keys are guaranteed to be 2-byte aligned.
5603 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
5605 #if BYTE_ORDER == LITTLE_ENDIAN
5606 unsigned short *u, *c;
5609 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5610 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
5613 } while(!x && u > (unsigned short *)a->mv_data);
5616 unsigned short *u, *c, *end;
5619 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5620 u = (unsigned short *)a->mv_data;
5621 c = (unsigned short *)b->mv_data;
5624 } while(!x && u < end);
5629 /** Compare two items lexically */
5631 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
5638 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5644 diff = memcmp(a->mv_data, b->mv_data, len);
5645 return diff ? diff : len_diff<0 ? -1 : len_diff;
5648 /** Compare two items in reverse byte order */
5650 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
5652 const unsigned char *p1, *p2, *p1_lim;
5656 p1_lim = (const unsigned char *)a->mv_data;
5657 p1 = (const unsigned char *)a->mv_data + a->mv_size;
5658 p2 = (const unsigned char *)b->mv_data + b->mv_size;
5660 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5666 while (p1 > p1_lim) {
5667 diff = *--p1 - *--p2;
5671 return len_diff<0 ? -1 : len_diff;
5674 /** Search for key within a page, using binary search.
5675 * Returns the smallest entry larger or equal to the key.
5676 * If exactp is non-null, stores whether the found entry was an exact match
5677 * in *exactp (1 or 0).
5678 * Updates the cursor index with the index of the found entry.
5679 * If no entry larger or equal to the key is found, returns NULL.
5682 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
5684 unsigned int i = 0, nkeys;
5687 MDB_page *mp = mc->mc_pg[mc->mc_top];
5688 MDB_node *node = NULL;
5693 nkeys = NUMKEYS(mp);
5695 DPRINTF(("searching %u keys in %s %spage %"Yu,
5696 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
5699 low = IS_LEAF(mp) ? 0 : 1;
5701 cmp = mc->mc_dbx->md_cmp;
5703 /* Branch pages have no data, so if using integer keys,
5704 * alignment is guaranteed. Use faster mdb_cmp_int.
5706 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
5707 if (NODEPTR(mp, 1)->mn_ksize == sizeof(mdb_size_t))
5714 nodekey.mv_size = mc->mc_db->md_pad;
5715 node = NODEPTR(mp, 0); /* fake */
5716 while (low <= high) {
5717 i = (low + high) >> 1;
5718 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
5719 rc = cmp(key, &nodekey);
5720 DPRINTF(("found leaf index %u [%s], rc = %i",
5721 i, DKEY(&nodekey), rc));
5730 while (low <= high) {
5731 i = (low + high) >> 1;
5733 node = NODEPTR(mp, i);
5734 nodekey.mv_size = NODEKSZ(node);
5735 nodekey.mv_data = NODEKEY(node);
5737 rc = cmp(key, &nodekey);
5740 DPRINTF(("found leaf index %u [%s], rc = %i",
5741 i, DKEY(&nodekey), rc));
5743 DPRINTF(("found branch index %u [%s -> %"Yu"], rc = %i",
5744 i, DKEY(&nodekey), NODEPGNO(node), rc));
5755 if (rc > 0) { /* Found entry is less than the key. */
5756 i++; /* Skip to get the smallest entry larger than key. */
5758 node = NODEPTR(mp, i);
5761 *exactp = (rc == 0 && nkeys > 0);
5762 /* store the key index */
5763 mc->mc_ki[mc->mc_top] = i;
5765 /* There is no entry larger or equal to the key. */
5768 /* nodeptr is fake for LEAF2 */
5774 mdb_cursor_adjust(MDB_cursor *mc, func)
5778 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5779 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
5786 /** Pop a page off the top of the cursor's stack. */
5788 mdb_cursor_pop(MDB_cursor *mc)
5791 DPRINTF(("popping page %"Yu" off db %d cursor %p",
5792 mc->mc_pg[mc->mc_top]->mp_pgno, DDBI(mc), (void *) mc));
5798 mc->mc_flags &= ~C_INITIALIZED;
5803 /** Push a page onto the top of the cursor's stack.
5804 * Set #MDB_TXN_ERROR on failure.
5807 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
5809 DPRINTF(("pushing page %"Yu" on db %d cursor %p", mp->mp_pgno,
5810 DDBI(mc), (void *) mc));
5812 if (mc->mc_snum >= CURSOR_STACK) {
5813 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5814 return MDB_CURSOR_FULL;
5817 mc->mc_top = mc->mc_snum++;
5818 mc->mc_pg[mc->mc_top] = mp;
5819 mc->mc_ki[mc->mc_top] = 0;
5825 /** Map a read-only page.
5826 * There are two levels of tracking in use, a per-txn list and a per-env list.
5827 * ref'ing and unref'ing the per-txn list is faster since it requires no
5828 * locking. Pages are cached in the per-env list for global reuse, and a lock
5829 * is required. Pages are not immediately unmapped when their refcnt goes to
5830 * zero; they hang around in case they will be reused again soon.
5832 * When the per-txn list gets full, all pages with refcnt=0 are purged from the
5833 * list and their refcnts in the per-env list are decremented.
5835 * When the per-env list gets full, all pages with refcnt=0 are purged from the
5836 * list and their pages are unmapped.
5838 * @note "full" means the list has reached its respective rpcheck threshold.
5839 * This threshold slowly raises if no pages could be purged on a given check,
5840 * and returns to its original value when enough pages were purged.
5842 * If purging doesn't free any slots, filling the per-txn list will return
5843 * MDB_TXN_FULL, and filling the per-env list returns MDB_MAP_FULL.
5845 * Reference tracking in a txn is imperfect, pages can linger with non-zero
5846 * refcnt even without active references. It was deemed to be too invasive
5847 * to add unrefs in every required location. However, all pages are unref'd
5848 * at the end of the transaction. This guarantees that no stale references
5849 * linger in the per-env list.
5851 * Usually we map chunks of 16 pages at a time, but if an overflow page begins
5852 * at the tail of the chunk we extend the chunk to include the entire overflow
5853 * page. Unfortunately, pages can be turned into overflow pages after their
5854 * chunk was already mapped. In that case we must remap the chunk if the
5855 * overflow page is referenced. If the chunk's refcnt is 0 we can just remap
5856 * it, otherwise we temporarily map a new chunk just for the overflow page.
5858 * @note this chunk handling means we cannot guarantee that a data item
5859 * returned from the DB will stay alive for the duration of the transaction:
5860 * We unref pages as soon as a cursor moves away from the page
5861 * A subsequent op may cause a purge, which may unmap any unref'd chunks
5862 * The caller must copy the data if it must be used later in the same txn.
5864 * Also - our reference counting revolves around cursors, but overflow pages
5865 * aren't pointed to by a cursor's page stack. We have to remember them
5866 * explicitly, in the added mc_ovpg field. A single cursor can only hold a
5867 * reference to one overflow page at a time.
5869 * @param[in] txn the transaction for this access.
5870 * @param[in] pgno the page number for the page to retrieve.
5871 * @param[out] ret address of a pointer where the page's address will be stored.
5872 * @return 0 on success, non-zero on failure.
5875 mdb_rpage_get(MDB_txn *txn, pgno_t pg0, MDB_page **ret)
5877 MDB_env *env = txn->mt_env;
5879 MDB_ID3L tl = txn->mt_rpages;
5880 MDB_ID3L el = env->me_rpages;
5884 int rc, retries = 1;
5888 #define SET_OFF(off,val) off.QuadPart = val
5889 #define MAP(rc,env,addr,len,off) \
5891 rc = NtMapViewOfSection(env->me_fmh, GetCurrentProcess(), &addr, 0, \
5892 len, &off, &len, ViewUnmap, (env->me_flags & MDB_RDONLY) ? 0 : MEM_RESERVE, PAGE_READONLY); \
5893 if (rc) rc = mdb_nt2win32(rc)
5897 #define SET_OFF(off,val) off = val
5898 #define MAP(rc,env,addr,len,off) \
5899 addr = mmap(NULL, len, PROT_READ, MAP_SHARED, env->me_fd, off); \
5900 rc = (addr == MAP_FAILED) ? errno : 0
5903 /* remember the offset of the actual page number, so we can
5904 * return the correct pointer at the end.
5906 rem = pg0 & (MDB_RPAGE_CHUNK-1);
5910 x = mdb_mid3l_search(tl, pgno);
5911 if (x <= tl[0].mid && tl[x].mid == pgno) {
5912 if (x != tl[0].mid && tl[x+1].mid == pg0)
5914 /* check for overflow size */
5915 p = (MDB_page *)((char *)tl[x].mptr + rem * env->me_psize);
5916 if (IS_OVERFLOW(p) && p->mp_pages + rem > tl[x].mcnt) {
5917 id3.mcnt = p->mp_pages + rem;
5918 len = id3.mcnt * env->me_psize;
5919 SET_OFF(off, pgno * env->me_psize);
5920 MAP(rc, env, id3.mptr, len, off);
5923 /* check for local-only page */
5925 mdb_tassert(txn, tl[x].mid != pg0);
5926 /* hope there's room to insert this locally.
5927 * setting mid here tells later code to just insert
5928 * this id3 instead of searching for a match.
5933 /* ignore the mapping we got from env, use new one */
5934 tl[x].mptr = id3.mptr;
5935 tl[x].mcnt = id3.mcnt;
5936 /* if no active ref, see if we can replace in env */
5939 pthread_mutex_lock(&env->me_rpmutex);
5940 i = mdb_mid3l_search(el, tl[x].mid);
5941 if (el[i].mref == 1) {
5942 /* just us, replace it */
5943 munmap(el[i].mptr, el[i].mcnt * env->me_psize);
5944 el[i].mptr = tl[x].mptr;
5945 el[i].mcnt = tl[x].mcnt;
5947 /* there are others, remove ourself */
5950 pthread_mutex_unlock(&env->me_rpmutex);
5954 id3.mptr = tl[x].mptr;
5955 id3.mcnt = tl[x].mcnt;
5961 if (tl[0].mid >= MDB_TRPAGE_MAX - txn->mt_rpcheck) {
5963 /* purge unref'd pages from our list and unref in env */
5964 pthread_mutex_lock(&env->me_rpmutex);
5967 for (i=1; i<=tl[0].mid; i++) {
5970 /* tmp overflow pages don't go to env */
5971 if (tl[i].mid & (MDB_RPAGE_CHUNK-1)) {
5972 munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
5975 x = mdb_mid3l_search(el, tl[i].mid);
5979 pthread_mutex_unlock(&env->me_rpmutex);
5981 /* we didn't find any unref'd chunks.
5982 * if we're out of room, fail.
5984 if (tl[0].mid >= MDB_TRPAGE_MAX)
5985 return MDB_TXN_FULL;
5986 /* otherwise, raise threshold for next time around
5989 txn->mt_rpcheck /= 2;
5991 /* we found some unused; consolidate the list */
5992 for (i=y+1; i<= tl[0].mid; i++)
5996 /* decrease the check threshold toward its original value */
5997 if (!txn->mt_rpcheck)
5998 txn->mt_rpcheck = 1;
5999 while (txn->mt_rpcheck < tl[0].mid && txn->mt_rpcheck < MDB_TRPAGE_SIZE/2)
6000 txn->mt_rpcheck *= 2;
6003 if (tl[0].mid < MDB_TRPAGE_SIZE) {
6007 /* don't map past last written page in read-only envs */
6008 if ((env->me_flags & MDB_RDONLY) && pgno + MDB_RPAGE_CHUNK-1 > txn->mt_last_pgno)
6009 id3.mcnt = txn->mt_last_pgno + 1 - pgno;
6011 id3.mcnt = MDB_RPAGE_CHUNK;
6012 len = id3.mcnt * env->me_psize;
6015 /* search for page in env */
6016 pthread_mutex_lock(&env->me_rpmutex);
6017 x = mdb_mid3l_search(el, pgno);
6018 if (x <= el[0].mid && el[x].mid == pgno) {
6019 id3.mptr = el[x].mptr;
6020 id3.mcnt = el[x].mcnt;
6021 /* check for overflow size */
6022 p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
6023 if (IS_OVERFLOW(p) && p->mp_pages + rem > id3.mcnt) {
6024 id3.mcnt = p->mp_pages + rem;
6025 len = id3.mcnt * env->me_psize;
6026 SET_OFF(off, pgno * env->me_psize);
6027 MAP(rc, env, id3.mptr, len, off);
6031 munmap(el[x].mptr, env->me_psize * el[x].mcnt);
6032 el[x].mptr = id3.mptr;
6033 el[x].mcnt = id3.mcnt;
6036 pthread_mutex_unlock(&env->me_rpmutex);
6041 pthread_mutex_unlock(&env->me_rpmutex);
6044 if (el[0].mid >= MDB_ERPAGE_MAX - env->me_rpcheck) {
6045 /* purge unref'd pages */
6047 for (i=1; i<=el[0].mid; i++) {
6050 munmap(el[i].mptr, env->me_psize * el[i].mcnt);
6055 /* see if we can unref some local pages */
6060 if (el[0].mid >= MDB_ERPAGE_MAX) {
6061 pthread_mutex_unlock(&env->me_rpmutex);
6062 return MDB_MAP_FULL;
6064 env->me_rpcheck /= 2;
6066 for (i=y+1; i<= el[0].mid; i++)
6070 if (!env->me_rpcheck)
6071 env->me_rpcheck = 1;
6072 while (env->me_rpcheck < el[0].mid && env->me_rpcheck < MDB_ERPAGE_SIZE/2)
6073 env->me_rpcheck *= 2;
6076 SET_OFF(off, pgno * env->me_psize);
6077 MAP(rc, env, id3.mptr, len, off);
6080 pthread_mutex_unlock(&env->me_rpmutex);
6083 /* check for overflow size */
6084 p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
6085 if (IS_OVERFLOW(p) && p->mp_pages + rem > id3.mcnt) {
6086 id3.mcnt = p->mp_pages + rem;
6087 munmap(id3.mptr, len);
6088 len = id3.mcnt * env->me_psize;
6089 MAP(rc, env, id3.mptr, len, off);
6093 mdb_mid3l_insert(el, &id3);
6094 pthread_mutex_unlock(&env->me_rpmutex);
6096 mdb_mid3l_insert(tl, &id3);
6098 return MDB_TXN_FULL;
6101 p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
6102 #if MDB_DEBUG /* we don't need this check any more */
6103 if (IS_OVERFLOW(p)) {
6104 mdb_tassert(txn, p->mp_pages + rem <= id3.mcnt);
6112 /** Find the address of the page corresponding to a given page number.
6113 * Set #MDB_TXN_ERROR on failure.
6114 * @param[in] mc the cursor accessing the page.
6115 * @param[in] pgno the page number for the page to retrieve.
6116 * @param[out] ret address of a pointer where the page's address will be stored.
6117 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
6118 * @return 0 on success, non-zero on failure.
6121 mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **ret, int *lvl)
6123 MDB_txn *txn = mc->mc_txn;
6127 if (! (mc->mc_flags & (C_ORIG_RDONLY|C_WRITEMAP))) {
6131 MDB_ID2L dl = tx2->mt_u.dirty_list;
6133 /* Spilled pages were dirtied in this txn and flushed
6134 * because the dirty list got full. Bring this page
6135 * back in from the map (but don't unspill it here,
6136 * leave that unless page_touch happens again).
6138 if (tx2->mt_spill_pgs) {
6139 MDB_ID pn = pgno << 1;
6140 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
6141 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
6146 unsigned x = mdb_mid2l_search(dl, pgno);
6147 if (x <= dl[0].mid && dl[x].mid == pgno) {
6153 } while ((tx2 = tx2->mt_parent) != NULL);
6156 if (pgno >= txn->mt_next_pgno) {
6157 DPRINTF(("page %"Yu" not found", pgno));
6158 txn->mt_flags |= MDB_TXN_ERROR;
6159 return MDB_PAGE_NOTFOUND;
6167 int rc = mdb_rpage_get(txn, pgno, &p);
6169 txn->mt_flags |= MDB_TXN_ERROR;
6173 MDB_env *env = txn->mt_env;
6174 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
6185 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
6186 * The cursor is at the root page, set up the rest of it.
6189 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
6191 MDB_page *mp = mc->mc_pg[mc->mc_top];
6195 while (IS_BRANCH(mp)) {
6199 DPRINTF(("branch page %"Yu" has %u keys", mp->mp_pgno, NUMKEYS(mp)));
6200 /* Don't assert on branch pages in the FreeDB. We can get here
6201 * while in the process of rebalancing a FreeDB branch page; we must
6202 * let that proceed. ITS#8336
6204 mdb_cassert(mc, !mc->mc_dbi || NUMKEYS(mp) > 1);
6205 DPRINTF(("found index 0 to page %"Yu, NODEPGNO(NODEPTR(mp, 0))));
6207 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
6209 if (flags & MDB_PS_LAST) {
6210 i = NUMKEYS(mp) - 1;
6211 /* if already init'd, see if we're already in right place */
6212 if (mc->mc_flags & C_INITIALIZED) {
6213 if (mc->mc_ki[mc->mc_top] == i) {
6214 mc->mc_top = mc->mc_snum++;
6215 mp = mc->mc_pg[mc->mc_top];
6222 node = mdb_node_search(mc, key, &exact);
6224 i = NUMKEYS(mp) - 1;
6226 i = mc->mc_ki[mc->mc_top];
6228 mdb_cassert(mc, i > 0);
6232 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
6235 mdb_cassert(mc, i < NUMKEYS(mp));
6236 node = NODEPTR(mp, i);
6238 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
6241 mc->mc_ki[mc->mc_top] = i;
6242 if ((rc = mdb_cursor_push(mc, mp)))
6246 if (flags & MDB_PS_MODIFY) {
6247 if ((rc = mdb_page_touch(mc)) != 0)
6249 mp = mc->mc_pg[mc->mc_top];
6254 DPRINTF(("internal error, index points to a %02X page!?",
6256 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6257 return MDB_CORRUPTED;
6260 DPRINTF(("found leaf page %"Yu" for key [%s]", mp->mp_pgno,
6261 key ? DKEY(key) : "null"));
6262 mc->mc_flags |= C_INITIALIZED;
6263 mc->mc_flags &= ~C_EOF;
6268 /** Search for the lowest key under the current branch page.
6269 * This just bypasses a NUMKEYS check in the current page
6270 * before calling mdb_page_search_root(), because the callers
6271 * are all in situations where the current page is known to
6275 mdb_page_search_lowest(MDB_cursor *mc)
6277 MDB_page *mp = mc->mc_pg[mc->mc_top];
6278 MDB_node *node = NODEPTR(mp, 0);
6281 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
6284 mc->mc_ki[mc->mc_top] = 0;
6285 if ((rc = mdb_cursor_push(mc, mp)))
6287 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
6290 /** Search for the page a given key should be in.
6291 * Push it and its parent pages on the cursor stack.
6292 * @param[in,out] mc the cursor for this operation.
6293 * @param[in] key the key to search for, or NULL for first/last page.
6294 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
6295 * are touched (updated with new page numbers).
6296 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
6297 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
6298 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
6299 * @return 0 on success, non-zero on failure.
6302 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
6307 /* Make sure the txn is still viable, then find the root from
6308 * the txn's db table and set it as the root of the cursor's stack.
6310 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED) {
6311 DPUTS("transaction may not be used now");
6314 /* Make sure we're using an up-to-date root */
6315 if (*mc->mc_dbflag & DB_STALE) {
6317 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
6319 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
6320 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
6327 MDB_node *leaf = mdb_node_search(&mc2,
6328 &mc->mc_dbx->md_name, &exact);
6330 return MDB_NOTFOUND;
6331 if ((leaf->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
6332 return MDB_INCOMPATIBLE; /* not a named DB */
6333 rc = mdb_node_read(&mc2, leaf, &data);
6336 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
6338 /* The txn may not know this DBI, or another process may
6339 * have dropped and recreated the DB with other flags.
6341 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
6342 return MDB_INCOMPATIBLE;
6343 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
6345 *mc->mc_dbflag &= ~DB_STALE;
6347 root = mc->mc_db->md_root;
6349 if (root == P_INVALID) { /* Tree is empty. */
6350 DPUTS("tree is empty");
6351 return MDB_NOTFOUND;
6355 mdb_cassert(mc, root > 1);
6356 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root) {
6359 MDB_PAGE_UNREF(mc->mc_txn, mc->mc_pg[0]);
6361 if ((rc = mdb_page_get(mc, root, &mc->mc_pg[0], NULL)) != 0)
6368 for (i=1; i<mc->mc_snum; i++)
6369 MDB_PAGE_UNREF(mc->mc_txn, mc->mc_pg[i]);
6375 DPRINTF(("db %d root page %"Yu" has flags 0x%X",
6376 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
6378 if (flags & MDB_PS_MODIFY) {
6379 if ((rc = mdb_page_touch(mc)))
6383 if (flags & MDB_PS_ROOTONLY)
6386 return mdb_page_search_root(mc, key, flags);
6390 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
6392 MDB_txn *txn = mc->mc_txn;
6393 pgno_t pg = mp->mp_pgno;
6394 unsigned x = 0, ovpages = mp->mp_pages;
6395 MDB_env *env = txn->mt_env;
6396 MDB_IDL sl = txn->mt_spill_pgs;
6397 MDB_ID pn = pg << 1;
6400 DPRINTF(("free ov page %"Yu" (%d)", pg, ovpages));
6401 /* If the page is dirty or on the spill list we just acquired it,
6402 * so we should give it back to our current free list, if any.
6403 * Otherwise put it onto the list of pages we freed in this txn.
6405 * Won't create me_pghead: me_pglast must be inited along with it.
6406 * Unsupported in nested txns: They would need to hide the page
6407 * range in ancestor txns' dirty and spilled lists.
6409 if (env->me_pghead &&
6411 ((mp->mp_flags & P_DIRTY) ||
6412 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
6416 MDB_ID2 *dl, ix, iy;
6417 rc = mdb_midl_need(&env->me_pghead, ovpages);
6420 if (!(mp->mp_flags & P_DIRTY)) {
6421 /* This page is no longer spilled */
6428 /* Remove from dirty list */
6429 dl = txn->mt_u.dirty_list;
6431 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
6437 mdb_cassert(mc, x > 1);
6439 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
6440 txn->mt_flags |= MDB_TXN_ERROR;
6444 txn->mt_dirty_room++;
6445 if (!(env->me_flags & MDB_WRITEMAP))
6446 mdb_dpage_free(env, mp);
6448 /* Insert in me_pghead */
6449 mop = env->me_pghead;
6450 j = mop[0] + ovpages;
6451 for (i = mop[0]; i && mop[i] < pg; i--)
6457 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
6461 mc->mc_db->md_overflow_pages -= ovpages;
6465 /** Return the data associated with a given node.
6466 * @param[in] mc The cursor for this operation.
6467 * @param[in] leaf The node being read.
6468 * @param[out] data Updated to point to the node's data.
6469 * @return 0 on success, non-zero on failure.
6472 mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data)
6474 MDB_page *omp; /* overflow page */
6479 MDB_PAGE_UNREF(mc->mc_txn, MC_OVPG(mc));
6480 MC_SET_OVPG(mc, NULL);
6482 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6483 data->mv_size = NODEDSZ(leaf);
6484 data->mv_data = NODEDATA(leaf);
6488 /* Read overflow data.
6490 data->mv_size = NODEDSZ(leaf);
6491 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
6492 if ((rc = mdb_page_get(mc, pgno, &omp, NULL)) != 0) {
6493 DPRINTF(("read overflow page %"Yu" failed", pgno));
6496 data->mv_data = METADATA(omp);
6497 MC_SET_OVPG(mc, omp);
6503 mdb_get(MDB_txn *txn, MDB_dbi dbi,
6504 MDB_val *key, MDB_val *data)
6511 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
6513 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
6516 if (txn->mt_flags & MDB_TXN_BLOCKED)
6519 mdb_cursor_init(&mc, txn, dbi, &mx);
6520 rc = mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
6521 /* unref all the pages when MDB_VL32 - caller must copy the data
6522 * before doing anything else
6524 MDB_CURSOR_UNREF(&mc, 1);
6528 /** Find a sibling for a page.
6529 * Replaces the page at the top of the cursor's stack with the
6530 * specified sibling, if one exists.
6531 * @param[in] mc The cursor for this operation.
6532 * @param[in] move_right Non-zero if the right sibling is requested,
6533 * otherwise the left sibling.
6534 * @return 0 on success, non-zero on failure.
6537 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
6546 if (mc->mc_snum < 2) {
6547 return MDB_NOTFOUND; /* root has no siblings */
6551 op = mc->mc_pg[mc->mc_top];
6554 DPRINTF(("parent page is page %"Yu", index %u",
6555 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
6557 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6558 : (mc->mc_ki[mc->mc_top] == 0)) {
6559 DPRINTF(("no more keys left, moving to %s sibling",
6560 move_right ? "right" : "left"));
6561 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
6562 /* undo cursor_pop before returning */
6569 mc->mc_ki[mc->mc_top]++;
6571 mc->mc_ki[mc->mc_top]--;
6572 DPRINTF(("just moving to %s index key %u",
6573 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
6575 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
6577 MDB_PAGE_UNREF(mc->mc_txn, op);
6579 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6580 if ((rc = mdb_page_get(mc, NODEPGNO(indx), &mp, NULL)) != 0) {
6581 /* mc will be inconsistent if caller does mc_snum++ as above */
6582 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
6586 mdb_cursor_push(mc, mp);
6588 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
6593 /** Move the cursor to the next data item. */
6595 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
6601 if ((mc->mc_flags & C_DEL && op == MDB_NEXT_DUP))
6602 return MDB_NOTFOUND;
6604 if (!(mc->mc_flags & C_INITIALIZED))
6605 return mdb_cursor_first(mc, key, data);
6607 mp = mc->mc_pg[mc->mc_top];
6609 if (mc->mc_flags & C_EOF) {
6610 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mp)-1)
6611 return MDB_NOTFOUND;
6612 mc->mc_flags ^= C_EOF;
6615 if (mc->mc_db->md_flags & MDB_DUPSORT) {
6616 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6617 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6618 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
6619 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
6620 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
6621 if (rc == MDB_SUCCESS)
6622 MDB_GET_KEY(leaf, key);
6627 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
6630 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6631 if (op == MDB_NEXT_DUP)
6632 return MDB_NOTFOUND;
6636 DPRINTF(("cursor_next: top page is %"Yu" in cursor %p",
6637 mdb_dbg_pgno(mp), (void *) mc));
6638 if (mc->mc_flags & C_DEL) {
6639 mc->mc_flags ^= C_DEL;
6643 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
6644 DPUTS("=====> move to next sibling page");
6645 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
6646 mc->mc_flags |= C_EOF;
6649 mp = mc->mc_pg[mc->mc_top];
6650 DPRINTF(("next page is %"Yu", key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
6652 mc->mc_ki[mc->mc_top]++;
6655 DPRINTF(("==> cursor points to page %"Yu" with %u keys, key index %u",
6656 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
6659 key->mv_size = mc->mc_db->md_pad;
6660 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6664 mdb_cassert(mc, IS_LEAF(mp));
6665 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6667 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6668 mdb_xcursor_init1(mc, leaf);
6671 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6674 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6675 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6676 if (rc != MDB_SUCCESS)
6681 MDB_GET_KEY(leaf, key);
6685 /** Move the cursor to the previous data item. */
6687 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
6693 if (!(mc->mc_flags & C_INITIALIZED)) {
6694 rc = mdb_cursor_last(mc, key, data);
6697 mc->mc_ki[mc->mc_top]++;
6700 mp = mc->mc_pg[mc->mc_top];
6702 if (mc->mc_db->md_flags & MDB_DUPSORT) {
6703 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6704 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6705 if (op == MDB_PREV || op == MDB_PREV_DUP) {
6706 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
6707 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
6708 if (rc == MDB_SUCCESS) {
6709 MDB_GET_KEY(leaf, key);
6710 mc->mc_flags &= ~C_EOF;
6716 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
6719 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6720 if (op == MDB_PREV_DUP)
6721 return MDB_NOTFOUND;
6725 DPRINTF(("cursor_prev: top page is %"Yu" in cursor %p",
6726 mdb_dbg_pgno(mp), (void *) mc));
6728 mc->mc_flags &= ~(C_EOF|C_DEL);
6730 if (mc->mc_ki[mc->mc_top] == 0) {
6731 DPUTS("=====> move to prev sibling page");
6732 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
6735 mp = mc->mc_pg[mc->mc_top];
6736 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
6737 DPRINTF(("prev page is %"Yu", key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
6739 mc->mc_ki[mc->mc_top]--;
6741 DPRINTF(("==> cursor points to page %"Yu" with %u keys, key index %u",
6742 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
6745 key->mv_size = mc->mc_db->md_pad;
6746 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6750 mdb_cassert(mc, IS_LEAF(mp));
6751 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6753 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6754 mdb_xcursor_init1(mc, leaf);
6757 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6760 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6761 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
6762 if (rc != MDB_SUCCESS)
6767 MDB_GET_KEY(leaf, key);
6771 /** Set the cursor on a specific data item. */
6773 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6774 MDB_cursor_op op, int *exactp)
6778 MDB_node *leaf = NULL;
6781 if (key->mv_size == 0)
6782 return MDB_BAD_VALSIZE;
6784 if (mc->mc_xcursor) {
6785 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
6786 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6789 /* See if we're already on the right page */
6790 if (mc->mc_flags & C_INITIALIZED) {
6793 mp = mc->mc_pg[mc->mc_top];
6795 mc->mc_ki[mc->mc_top] = 0;
6796 return MDB_NOTFOUND;
6798 if (mp->mp_flags & P_LEAF2) {
6799 nodekey.mv_size = mc->mc_db->md_pad;
6800 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
6802 leaf = NODEPTR(mp, 0);
6803 MDB_GET_KEY2(leaf, nodekey);
6805 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6807 /* Probably happens rarely, but first node on the page
6808 * was the one we wanted.
6810 mc->mc_ki[mc->mc_top] = 0;
6817 unsigned int nkeys = NUMKEYS(mp);
6819 if (mp->mp_flags & P_LEAF2) {
6820 nodekey.mv_data = LEAF2KEY(mp,
6821 nkeys-1, nodekey.mv_size);
6823 leaf = NODEPTR(mp, nkeys-1);
6824 MDB_GET_KEY2(leaf, nodekey);
6826 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6828 /* last node was the one we wanted */
6829 mc->mc_ki[mc->mc_top] = nkeys-1;
6835 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
6836 /* This is definitely the right page, skip search_page */
6837 if (mp->mp_flags & P_LEAF2) {
6838 nodekey.mv_data = LEAF2KEY(mp,
6839 mc->mc_ki[mc->mc_top], nodekey.mv_size);
6841 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6842 MDB_GET_KEY2(leaf, nodekey);
6844 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6846 /* current node was the one we wanted */
6853 mc->mc_flags &= ~C_EOF;
6857 /* If any parents have right-sibs, search.
6858 * Otherwise, there's nothing further.
6860 for (i=0; i<mc->mc_top; i++)
6862 NUMKEYS(mc->mc_pg[i])-1)
6864 if (i == mc->mc_top) {
6865 /* There are no other pages */
6866 mc->mc_ki[mc->mc_top] = nkeys;
6867 return MDB_NOTFOUND;
6871 /* There are no other pages */
6872 mc->mc_ki[mc->mc_top] = 0;
6873 if (op == MDB_SET_RANGE && !exactp) {
6877 return MDB_NOTFOUND;
6883 rc = mdb_page_search(mc, key, 0);
6884 if (rc != MDB_SUCCESS)
6887 mp = mc->mc_pg[mc->mc_top];
6888 mdb_cassert(mc, IS_LEAF(mp));
6891 leaf = mdb_node_search(mc, key, exactp);
6892 if (exactp != NULL && !*exactp) {
6893 /* MDB_SET specified and not an exact match. */
6894 return MDB_NOTFOUND;
6898 DPUTS("===> inexact leaf not found, goto sibling");
6899 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
6900 mc->mc_flags |= C_EOF;
6901 return rc; /* no entries matched */
6903 mp = mc->mc_pg[mc->mc_top];
6904 mdb_cassert(mc, IS_LEAF(mp));
6905 leaf = NODEPTR(mp, 0);
6909 mc->mc_flags |= C_INITIALIZED;
6910 mc->mc_flags &= ~C_EOF;
6913 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
6914 key->mv_size = mc->mc_db->md_pad;
6915 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6920 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6921 mdb_xcursor_init1(mc, leaf);
6924 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6925 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
6926 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6929 if (op == MDB_GET_BOTH) {
6935 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
6936 if (rc != MDB_SUCCESS)
6939 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
6942 if ((rc = mdb_node_read(mc, leaf, &olddata)) != MDB_SUCCESS)
6944 dcmp = mc->mc_dbx->md_dcmp;
6945 if (NEED_CMP_CLONG(dcmp, olddata.mv_size))
6946 dcmp = mdb_cmp_clong;
6947 rc = dcmp(data, &olddata);
6949 if (op == MDB_GET_BOTH || rc > 0)
6950 return MDB_NOTFOUND;
6957 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6958 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6963 /* The key already matches in all other cases */
6964 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
6965 MDB_GET_KEY(leaf, key);
6966 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
6971 /** Move the cursor to the first item in the database. */
6973 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6978 if (mc->mc_xcursor) {
6979 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
6980 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6983 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6984 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
6985 if (rc != MDB_SUCCESS)
6988 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6990 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
6991 mc->mc_flags |= C_INITIALIZED;
6992 mc->mc_flags &= ~C_EOF;
6994 mc->mc_ki[mc->mc_top] = 0;
6996 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6997 key->mv_size = mc->mc_db->md_pad;
6998 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
7003 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7004 mdb_xcursor_init1(mc, leaf);
7005 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
7009 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
7013 MDB_GET_KEY(leaf, key);
7017 /** Move the cursor to the last item in the database. */
7019 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
7024 if (mc->mc_xcursor) {
7025 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
7026 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
7029 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
7030 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
7031 if (rc != MDB_SUCCESS)
7034 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
7036 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
7037 mc->mc_flags |= C_INITIALIZED|C_EOF;
7038 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7040 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
7041 key->mv_size = mc->mc_db->md_pad;
7042 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
7047 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7048 mdb_xcursor_init1(mc, leaf);
7049 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
7053 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
7058 MDB_GET_KEY(leaf, key);
7063 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
7068 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
7073 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
7077 case MDB_GET_CURRENT:
7078 if (!(mc->mc_flags & C_INITIALIZED)) {
7081 MDB_page *mp = mc->mc_pg[mc->mc_top];
7082 int nkeys = NUMKEYS(mp);
7083 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
7084 mc->mc_ki[mc->mc_top] = nkeys;
7090 key->mv_size = mc->mc_db->md_pad;
7091 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
7093 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7094 MDB_GET_KEY(leaf, key);
7096 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7097 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
7099 rc = mdb_node_read(mc, leaf, data);
7106 case MDB_GET_BOTH_RANGE:
7111 if (mc->mc_xcursor == NULL) {
7112 rc = MDB_INCOMPATIBLE;
7122 rc = mdb_cursor_set(mc, key, data, op,
7123 op == MDB_SET_RANGE ? NULL : &exact);
7126 case MDB_GET_MULTIPLE:
7127 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
7131 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7132 rc = MDB_INCOMPATIBLE;
7136 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
7137 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
7140 case MDB_NEXT_MULTIPLE:
7145 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7146 rc = MDB_INCOMPATIBLE;
7149 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
7150 if (rc == MDB_SUCCESS) {
7151 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
7154 mx = &mc->mc_xcursor->mx_cursor;
7155 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
7157 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
7158 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
7164 case MDB_PREV_MULTIPLE:
7169 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7170 rc = MDB_INCOMPATIBLE;
7173 if (!(mc->mc_flags & C_INITIALIZED))
7174 rc = mdb_cursor_last(mc, key, data);
7177 if (rc == MDB_SUCCESS) {
7178 MDB_cursor *mx = &mc->mc_xcursor->mx_cursor;
7179 if (mx->mc_flags & C_INITIALIZED) {
7180 rc = mdb_cursor_sibling(mx, 0);
7181 if (rc == MDB_SUCCESS)
7190 case MDB_NEXT_NODUP:
7191 rc = mdb_cursor_next(mc, key, data, op);
7195 case MDB_PREV_NODUP:
7196 rc = mdb_cursor_prev(mc, key, data, op);
7199 rc = mdb_cursor_first(mc, key, data);
7202 mfunc = mdb_cursor_first;
7204 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
7208 if (mc->mc_xcursor == NULL) {
7209 rc = MDB_INCOMPATIBLE;
7213 MDB_node *leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7214 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7215 MDB_GET_KEY(leaf, key);
7216 rc = mdb_node_read(mc, leaf, data);
7220 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
7224 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
7227 rc = mdb_cursor_last(mc, key, data);
7230 mfunc = mdb_cursor_last;
7233 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
7238 if (mc->mc_flags & C_DEL)
7239 mc->mc_flags ^= C_DEL;
7244 /** Touch all the pages in the cursor stack. Set mc_top.
7245 * Makes sure all the pages are writable, before attempting a write operation.
7246 * @param[in] mc The cursor to operate on.
7249 mdb_cursor_touch(MDB_cursor *mc)
7251 int rc = MDB_SUCCESS;
7253 if (mc->mc_dbi >= CORE_DBS && !(*mc->mc_dbflag & (DB_DIRTY|DB_DUPDATA))) {
7254 /* Touch DB record of named DB */
7257 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
7259 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
7260 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
7263 *mc->mc_dbflag |= DB_DIRTY;
7268 rc = mdb_page_touch(mc);
7269 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
7270 mc->mc_top = mc->mc_snum-1;
7275 /** Do not spill pages to disk if txn is getting full, may fail instead */
7276 #define MDB_NOSPILL 0x8000
7279 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
7283 MDB_node *leaf = NULL;
7284 MDB_page *fp, *mp, *sub_root = NULL;
7286 MDB_val xdata, *rdata, dkey, olddata;
7288 int do_sub = 0, insert_key, insert_data;
7289 unsigned int mcount = 0, dcount = 0, nospill;
7292 unsigned int nflags;
7295 if (mc == NULL || key == NULL)
7298 env = mc->mc_txn->mt_env;
7300 /* Check this first so counter will always be zero on any
7303 if (flags & MDB_MULTIPLE) {
7304 dcount = data[1].mv_size;
7305 data[1].mv_size = 0;
7306 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
7307 return MDB_INCOMPATIBLE;
7310 nospill = flags & MDB_NOSPILL;
7311 flags &= ~MDB_NOSPILL;
7313 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
7314 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7316 if (key->mv_size-1 >= ENV_MAXKEY(env))
7317 return MDB_BAD_VALSIZE;
7319 #if SIZE_MAX > MAXDATASIZE
7320 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
7321 return MDB_BAD_VALSIZE;
7323 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
7324 return MDB_BAD_VALSIZE;
7327 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
7328 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
7332 if (flags == MDB_CURRENT) {
7333 if (!(mc->mc_flags & C_INITIALIZED))
7336 } else if (mc->mc_db->md_root == P_INVALID) {
7337 /* new database, cursor has nothing to point to */
7340 mc->mc_flags &= ~C_INITIALIZED;
7345 if (flags & MDB_APPEND) {
7347 rc = mdb_cursor_last(mc, &k2, &d2);
7349 rc = mc->mc_dbx->md_cmp(key, &k2);
7352 mc->mc_ki[mc->mc_top]++;
7354 /* new key is <= last key */
7359 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
7361 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
7362 DPRINTF(("duplicate key [%s]", DKEY(key)));
7364 return MDB_KEYEXIST;
7366 if (rc && rc != MDB_NOTFOUND)
7370 if (mc->mc_flags & C_DEL)
7371 mc->mc_flags ^= C_DEL;
7373 /* Cursor is positioned, check for room in the dirty list */
7375 if (flags & MDB_MULTIPLE) {
7377 xdata.mv_size = data->mv_size * dcount;
7381 if ((rc2 = mdb_page_spill(mc, key, rdata)))
7385 if (rc == MDB_NO_ROOT) {
7387 /* new database, write a root leaf page */
7388 DPUTS("allocating new root leaf page");
7389 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
7392 mdb_cursor_push(mc, np);
7393 mc->mc_db->md_root = np->mp_pgno;
7394 mc->mc_db->md_depth++;
7395 *mc->mc_dbflag |= DB_DIRTY;
7396 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
7398 np->mp_flags |= P_LEAF2;
7399 mc->mc_flags |= C_INITIALIZED;
7401 /* make sure all cursor pages are writable */
7402 rc2 = mdb_cursor_touch(mc);
7407 insert_key = insert_data = rc;
7409 /* The key does not exist */
7410 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
7411 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
7412 LEAFSIZE(key, data) > env->me_nodemax)
7414 /* Too big for a node, insert in sub-DB. Set up an empty
7415 * "old sub-page" for prep_subDB to expand to a full page.
7417 fp_flags = P_LEAF|P_DIRTY;
7419 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
7420 fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
7421 olddata.mv_size = PAGEHDRSZ;
7425 /* there's only a key anyway, so this is a no-op */
7426 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
7428 unsigned int ksize = mc->mc_db->md_pad;
7429 if (key->mv_size != ksize)
7430 return MDB_BAD_VALSIZE;
7431 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
7432 memcpy(ptr, key->mv_data, ksize);
7434 /* if overwriting slot 0 of leaf, need to
7435 * update branch key if there is a parent page
7437 if (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
7438 unsigned short dtop = 1;
7440 /* slot 0 is always an empty key, find real slot */
7441 while (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
7445 if (mc->mc_ki[mc->mc_top])
7446 rc2 = mdb_update_key(mc, key);
7457 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7458 olddata.mv_size = NODEDSZ(leaf);
7459 olddata.mv_data = NODEDATA(leaf);
7462 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
7463 /* Prepare (sub-)page/sub-DB to accept the new item,
7464 * if needed. fp: old sub-page or a header faking
7465 * it. mp: new (sub-)page. offset: growth in page
7466 * size. xdata: node data with new page or DB.
7468 unsigned i, offset = 0;
7469 mp = fp = xdata.mv_data = env->me_pbuf;
7470 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
7472 /* Was a single item before, must convert now */
7473 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7475 /* Just overwrite the current item */
7476 if (flags == MDB_CURRENT)
7478 dcmp = mc->mc_dbx->md_dcmp;
7479 if (NEED_CMP_CLONG(dcmp, olddata.mv_size))
7480 dcmp = mdb_cmp_clong;
7481 /* does data match? */
7482 if (!dcmp(data, &olddata)) {
7483 if (flags & (MDB_NODUPDATA|MDB_APPENDDUP))
7484 return MDB_KEYEXIST;
7489 /* Back up original data item */
7490 dkey.mv_size = olddata.mv_size;
7491 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
7493 /* Make sub-page header for the dup items, with dummy body */
7494 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
7495 fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
7496 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
7497 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7498 fp->mp_flags |= P_LEAF2;
7499 fp->mp_pad = data->mv_size;
7500 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
7502 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
7503 (dkey.mv_size & 1) + (data->mv_size & 1);
7505 fp->mp_upper = xdata.mv_size - PAGEBASE;
7506 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
7507 } else if (leaf->mn_flags & F_SUBDATA) {
7508 /* Data is on sub-DB, just store it */
7509 flags |= F_DUPDATA|F_SUBDATA;
7512 /* Data is on sub-page */
7513 fp = olddata.mv_data;
7516 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7517 offset = EVEN(NODESIZE + sizeof(indx_t) +
7521 offset = fp->mp_pad;
7522 if (SIZELEFT(fp) < offset) {
7523 offset *= 4; /* space for 4 more */
7526 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
7528 fp->mp_flags |= P_DIRTY;
7529 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
7530 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
7534 xdata.mv_size = olddata.mv_size + offset;
7537 fp_flags = fp->mp_flags;
7538 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
7539 /* Too big for a sub-page, convert to sub-DB */
7540 fp_flags &= ~P_SUBP;
7542 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7543 fp_flags |= P_LEAF2;
7544 dummy.md_pad = fp->mp_pad;
7545 dummy.md_flags = MDB_DUPFIXED;
7546 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
7547 dummy.md_flags |= MDB_INTEGERKEY;
7553 dummy.md_branch_pages = 0;
7554 dummy.md_leaf_pages = 1;
7555 dummy.md_overflow_pages = 0;
7556 dummy.md_entries = NUMKEYS(fp);
7557 xdata.mv_size = sizeof(MDB_db);
7558 xdata.mv_data = &dummy;
7559 if ((rc = mdb_page_alloc(mc, 1, &mp)))
7561 offset = env->me_psize - olddata.mv_size;
7562 flags |= F_DUPDATA|F_SUBDATA;
7563 dummy.md_root = mp->mp_pgno;
7567 mp->mp_flags = fp_flags | P_DIRTY;
7568 mp->mp_pad = fp->mp_pad;
7569 mp->mp_lower = fp->mp_lower;
7570 mp->mp_upper = fp->mp_upper + offset;
7571 if (fp_flags & P_LEAF2) {
7572 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
7574 memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
7575 olddata.mv_size - fp->mp_upper - PAGEBASE);
7576 for (i=0; i<NUMKEYS(fp); i++)
7577 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
7585 mdb_node_del(mc, 0);
7589 /* LMDB passes F_SUBDATA in 'flags' to write a DB record */
7590 if ((leaf->mn_flags ^ flags) & F_SUBDATA)
7591 return MDB_INCOMPATIBLE;
7592 /* overflow page overwrites need special handling */
7593 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7596 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
7598 memcpy(&pg, olddata.mv_data, sizeof(pg));
7599 if ((rc2 = mdb_page_get(mc, pg, &omp, &level)) != 0)
7601 ovpages = omp->mp_pages;
7603 /* Is the ov page large enough? */
7604 if (ovpages >= dpages) {
7605 if (!(omp->mp_flags & P_DIRTY) &&
7606 (level || (env->me_flags & MDB_WRITEMAP)))
7608 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
7611 level = 0; /* dirty in this txn or clean */
7614 if (omp->mp_flags & P_DIRTY) {
7615 /* yes, overwrite it. Note in this case we don't
7616 * bother to try shrinking the page if the new data
7617 * is smaller than the overflow threshold.
7620 /* It is writable only in a parent txn */
7621 size_t sz = (size_t) env->me_psize * ovpages, off;
7622 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
7628 /* Note - this page is already counted in parent's dirty_room */
7629 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
7630 mdb_cassert(mc, rc2 == 0);
7631 /* Currently we make the page look as with put() in the
7632 * parent txn, in case the user peeks at MDB_RESERVEd
7633 * or unused parts. Some users treat ovpages specially.
7635 if (!(flags & MDB_RESERVE)) {
7636 /* Skip the part where LMDB will put *data.
7637 * Copy end of page, adjusting alignment so
7638 * compiler may copy words instead of bytes.
7640 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
7641 memcpy((size_t *)((char *)np + off),
7642 (size_t *)((char *)omp + off), sz - off);
7645 memcpy(np, omp, sz); /* Copy beginning of page */
7648 SETDSZ(leaf, data->mv_size);
7649 if (F_ISSET(flags, MDB_RESERVE))
7650 data->mv_data = METADATA(omp);
7652 memcpy(METADATA(omp), data->mv_data, data->mv_size);
7656 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
7658 } else if (data->mv_size == olddata.mv_size) {
7659 /* same size, just replace it. Note that we could
7660 * also reuse this node if the new data is smaller,
7661 * but instead we opt to shrink the node in that case.
7663 if (F_ISSET(flags, MDB_RESERVE))
7664 data->mv_data = olddata.mv_data;
7665 else if (!(mc->mc_flags & C_SUB))
7666 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
7668 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
7673 mdb_node_del(mc, 0);
7679 nflags = flags & NODE_ADD_FLAGS;
7680 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
7681 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
7682 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
7683 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
7685 nflags |= MDB_SPLIT_REPLACE;
7686 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
7688 /* There is room already in this leaf page. */
7689 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
7691 /* Adjust other cursors pointing to mp */
7692 MDB_cursor *m2, *m3;
7693 MDB_dbi dbi = mc->mc_dbi;
7694 unsigned i = mc->mc_top;
7695 MDB_page *mp = mc->mc_pg[i];
7697 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7698 if (mc->mc_flags & C_SUB)
7699 m3 = &m2->mc_xcursor->mx_cursor;
7702 if (m3 == mc || m3->mc_snum < mc->mc_snum || m3->mc_pg[i] != mp) continue;
7703 if (m3->mc_ki[i] >= mc->mc_ki[i] && insert_key) {
7706 if (XCURSOR_INITED(m3))
7707 XCURSOR_REFRESH(m3, mp, m3->mc_ki[i]);
7712 if (rc == MDB_SUCCESS) {
7713 /* Now store the actual data in the child DB. Note that we're
7714 * storing the user data in the keys field, so there are strict
7715 * size limits on dupdata. The actual data fields of the child
7716 * DB are all zero size.
7719 int xflags, new_dupdata;
7724 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7725 if (flags & MDB_CURRENT) {
7726 xflags = MDB_CURRENT|MDB_NOSPILL;
7728 mdb_xcursor_init1(mc, leaf);
7729 xflags = (flags & MDB_NODUPDATA) ?
7730 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
7733 mc->mc_xcursor->mx_cursor.mc_pg[0] = sub_root;
7734 new_dupdata = (int)dkey.mv_size;
7735 /* converted, write the original data first */
7737 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
7740 /* we've done our job */
7743 if (!(leaf->mn_flags & F_SUBDATA) || sub_root) {
7744 /* Adjust other cursors pointing to mp */
7746 MDB_xcursor *mx = mc->mc_xcursor;
7747 unsigned i = mc->mc_top;
7748 MDB_page *mp = mc->mc_pg[i];
7749 int nkeys = NUMKEYS(mp);
7751 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
7752 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
7753 if (!(m2->mc_flags & C_INITIALIZED)) continue;
7754 if (m2->mc_pg[i] == mp) {
7755 if (m2->mc_ki[i] == mc->mc_ki[i]) {
7756 mdb_xcursor_init2(m2, mx, new_dupdata);
7757 } else if (!insert_key && m2->mc_ki[i] < nkeys) {
7758 XCURSOR_REFRESH(m2, mp, m2->mc_ki[i]);
7763 ecount = mc->mc_xcursor->mx_db.md_entries;
7764 if (flags & MDB_APPENDDUP)
7765 xflags |= MDB_APPEND;
7766 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
7767 if (flags & F_SUBDATA) {
7768 void *db = NODEDATA(leaf);
7769 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
7771 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
7773 /* Increment count unless we just replaced an existing item. */
7775 mc->mc_db->md_entries++;
7777 /* Invalidate txn if we created an empty sub-DB */
7780 /* If we succeeded and the key didn't exist before,
7781 * make sure the cursor is marked valid.
7783 mc->mc_flags |= C_INITIALIZED;
7785 if (flags & MDB_MULTIPLE) {
7788 /* let caller know how many succeeded, if any */
7789 data[1].mv_size = mcount;
7790 if (mcount < dcount) {
7791 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
7792 insert_key = insert_data = 0;
7799 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
7802 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7807 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
7813 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
7814 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7816 if (!(mc->mc_flags & C_INITIALIZED))
7819 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
7820 return MDB_NOTFOUND;
7822 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
7825 rc = mdb_cursor_touch(mc);
7829 mp = mc->mc_pg[mc->mc_top];
7832 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7834 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7835 if (flags & MDB_NODUPDATA) {
7836 /* mdb_cursor_del0() will subtract the final entry */
7837 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
7838 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
7840 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
7841 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
7843 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
7846 /* If sub-DB still has entries, we're done */
7847 if (mc->mc_xcursor->mx_db.md_entries) {
7848 if (leaf->mn_flags & F_SUBDATA) {
7849 /* update subDB info */
7850 void *db = NODEDATA(leaf);
7851 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
7854 /* shrink fake page */
7855 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
7856 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7857 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
7858 /* fix other sub-DB cursors pointed at fake pages on this page */
7859 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
7860 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
7861 if (!(m2->mc_flags & C_INITIALIZED)) continue;
7862 if (m2->mc_pg[mc->mc_top] == mp) {
7863 MDB_node *n2 = leaf;
7864 if (m2->mc_ki[mc->mc_top] != mc->mc_ki[mc->mc_top]) {
7865 n2 = NODEPTR(mp, m2->mc_ki[mc->mc_top]);
7866 if (n2->mn_flags & F_SUBDATA) continue;
7868 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
7872 mc->mc_db->md_entries--;
7875 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
7877 /* otherwise fall thru and delete the sub-DB */
7880 if (leaf->mn_flags & F_SUBDATA) {
7881 /* add all the child DB's pages to the free list */
7882 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
7887 /* LMDB passes F_SUBDATA in 'flags' to delete a DB record */
7888 else if ((leaf->mn_flags ^ flags) & F_SUBDATA) {
7889 rc = MDB_INCOMPATIBLE;
7893 /* add overflow pages to free list */
7894 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7898 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
7899 if ((rc = mdb_page_get(mc, pg, &omp, NULL)) ||
7900 (rc = mdb_ovpage_free(mc, omp)))
7905 return mdb_cursor_del0(mc);
7908 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7912 /** Allocate and initialize new pages for a database.
7913 * Set #MDB_TXN_ERROR on failure.
7914 * @param[in] mc a cursor on the database being added to.
7915 * @param[in] flags flags defining what type of page is being allocated.
7916 * @param[in] num the number of pages to allocate. This is usually 1,
7917 * unless allocating overflow pages for a large record.
7918 * @param[out] mp Address of a page, or NULL on failure.
7919 * @return 0 on success, non-zero on failure.
7922 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
7927 if ((rc = mdb_page_alloc(mc, num, &np)))
7929 DPRINTF(("allocated new mpage %"Yu", page size %u",
7930 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
7931 np->mp_flags = flags | P_DIRTY;
7932 np->mp_lower = (PAGEHDRSZ-PAGEBASE);
7933 np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
7936 mc->mc_db->md_branch_pages++;
7937 else if (IS_LEAF(np))
7938 mc->mc_db->md_leaf_pages++;
7939 else if (IS_OVERFLOW(np)) {
7940 mc->mc_db->md_overflow_pages += num;
7948 /** Calculate the size of a leaf node.
7949 * The size depends on the environment's page size; if a data item
7950 * is too large it will be put onto an overflow page and the node
7951 * size will only include the key and not the data. Sizes are always
7952 * rounded up to an even number of bytes, to guarantee 2-byte alignment
7953 * of the #MDB_node headers.
7954 * @param[in] env The environment handle.
7955 * @param[in] key The key for the node.
7956 * @param[in] data The data for the node.
7957 * @return The number of bytes needed to store the node.
7960 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
7964 sz = LEAFSIZE(key, data);
7965 if (sz > env->me_nodemax) {
7966 /* put on overflow page */
7967 sz -= data->mv_size - sizeof(pgno_t);
7970 return EVEN(sz + sizeof(indx_t));
7973 /** Calculate the size of a branch node.
7974 * The size should depend on the environment's page size but since
7975 * we currently don't support spilling large keys onto overflow
7976 * pages, it's simply the size of the #MDB_node header plus the
7977 * size of the key. Sizes are always rounded up to an even number
7978 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
7979 * @param[in] env The environment handle.
7980 * @param[in] key The key for the node.
7981 * @return The number of bytes needed to store the node.
7984 mdb_branch_size(MDB_env *env, MDB_val *key)
7989 if (sz > env->me_nodemax) {
7990 /* put on overflow page */
7991 /* not implemented */
7992 /* sz -= key->size - sizeof(pgno_t); */
7995 return sz + sizeof(indx_t);
7998 /** Add a node to the page pointed to by the cursor.
7999 * Set #MDB_TXN_ERROR on failure.
8000 * @param[in] mc The cursor for this operation.
8001 * @param[in] indx The index on the page where the new node should be added.
8002 * @param[in] key The key for the new node.
8003 * @param[in] data The data for the new node, if any.
8004 * @param[in] pgno The page number, if adding a branch node.
8005 * @param[in] flags Flags for the node.
8006 * @return 0 on success, non-zero on failure. Possible errors are:
8008 * <li>ENOMEM - failed to allocate overflow pages for the node.
8009 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
8010 * should never happen since all callers already calculate the
8011 * page's free space before calling this function.
8015 mdb_node_add(MDB_cursor *mc, indx_t indx,
8016 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
8019 size_t node_size = NODESIZE;
8023 MDB_page *mp = mc->mc_pg[mc->mc_top];
8024 MDB_page *ofp = NULL; /* overflow page */
8028 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
8030 DPRINTF(("add to %s %spage %"Yu" index %i, data size %"Z"u key size %"Z"u [%s]",
8031 IS_LEAF(mp) ? "leaf" : "branch",
8032 IS_SUBP(mp) ? "sub-" : "",
8033 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
8034 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
8037 /* Move higher keys up one slot. */
8038 int ksize = mc->mc_db->md_pad, dif;
8039 char *ptr = LEAF2KEY(mp, indx, ksize);
8040 dif = NUMKEYS(mp) - indx;
8042 memmove(ptr+ksize, ptr, dif*ksize);
8043 /* insert new key */
8044 memcpy(ptr, key->mv_data, ksize);
8046 /* Just using these for counting */
8047 mp->mp_lower += sizeof(indx_t);
8048 mp->mp_upper -= ksize - sizeof(indx_t);
8052 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
8054 node_size += key->mv_size;
8056 mdb_cassert(mc, key && data);
8057 if (F_ISSET(flags, F_BIGDATA)) {
8058 /* Data already on overflow page. */
8059 node_size += sizeof(pgno_t);
8060 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
8061 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
8063 /* Put data on overflow page. */
8064 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
8065 data->mv_size, node_size+data->mv_size));
8066 node_size = EVEN(node_size + sizeof(pgno_t));
8067 if ((ssize_t)node_size > room)
8069 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
8071 DPRINTF(("allocated overflow page %"Yu, ofp->mp_pgno));
8075 node_size += data->mv_size;
8078 node_size = EVEN(node_size);
8079 if ((ssize_t)node_size > room)
8083 /* Move higher pointers up one slot. */
8084 for (i = NUMKEYS(mp); i > indx; i--)
8085 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
8087 /* Adjust free space offsets. */
8088 ofs = mp->mp_upper - node_size;
8089 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
8090 mp->mp_ptrs[indx] = ofs;
8092 mp->mp_lower += sizeof(indx_t);
8094 /* Write the node data. */
8095 node = NODEPTR(mp, indx);
8096 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
8097 node->mn_flags = flags;
8099 SETDSZ(node,data->mv_size);
8104 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
8107 ndata = NODEDATA(node);
8109 if (F_ISSET(flags, F_BIGDATA))
8110 memcpy(ndata, data->mv_data, sizeof(pgno_t));
8111 else if (F_ISSET(flags, MDB_RESERVE))
8112 data->mv_data = ndata;
8114 memcpy(ndata, data->mv_data, data->mv_size);
8116 memcpy(ndata, &ofp->mp_pgno, sizeof(pgno_t));
8117 ndata = METADATA(ofp);
8118 if (F_ISSET(flags, MDB_RESERVE))
8119 data->mv_data = ndata;
8121 memcpy(ndata, data->mv_data, data->mv_size);
8128 DPRINTF(("not enough room in page %"Yu", got %u ptrs",
8129 mdb_dbg_pgno(mp), NUMKEYS(mp)));
8130 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
8131 DPRINTF(("node size = %"Z"u", node_size));
8132 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8133 return MDB_PAGE_FULL;
8136 /** Delete the specified node from a page.
8137 * @param[in] mc Cursor pointing to the node to delete.
8138 * @param[in] ksize The size of a node. Only used if the page is
8139 * part of a #MDB_DUPFIXED database.
8142 mdb_node_del(MDB_cursor *mc, int ksize)
8144 MDB_page *mp = mc->mc_pg[mc->mc_top];
8145 indx_t indx = mc->mc_ki[mc->mc_top];
8147 indx_t i, j, numkeys, ptr;
8151 DPRINTF(("delete node %u on %s page %"Yu, indx,
8152 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
8153 numkeys = NUMKEYS(mp);
8154 mdb_cassert(mc, indx < numkeys);
8157 int x = numkeys - 1 - indx;
8158 base = LEAF2KEY(mp, indx, ksize);
8160 memmove(base, base + ksize, x * ksize);
8161 mp->mp_lower -= sizeof(indx_t);
8162 mp->mp_upper += ksize - sizeof(indx_t);
8166 node = NODEPTR(mp, indx);
8167 sz = NODESIZE + node->mn_ksize;
8169 if (F_ISSET(node->mn_flags, F_BIGDATA))
8170 sz += sizeof(pgno_t);
8172 sz += NODEDSZ(node);
8176 ptr = mp->mp_ptrs[indx];
8177 for (i = j = 0; i < numkeys; i++) {
8179 mp->mp_ptrs[j] = mp->mp_ptrs[i];
8180 if (mp->mp_ptrs[i] < ptr)
8181 mp->mp_ptrs[j] += sz;
8186 base = (char *)mp + mp->mp_upper + PAGEBASE;
8187 memmove(base + sz, base, ptr - mp->mp_upper);
8189 mp->mp_lower -= sizeof(indx_t);
8193 /** Compact the main page after deleting a node on a subpage.
8194 * @param[in] mp The main page to operate on.
8195 * @param[in] indx The index of the subpage on the main page.
8198 mdb_node_shrink(MDB_page *mp, indx_t indx)
8203 indx_t delta, nsize, len, ptr;
8206 node = NODEPTR(mp, indx);
8207 sp = (MDB_page *)NODEDATA(node);
8208 delta = SIZELEFT(sp);
8209 nsize = NODEDSZ(node) - delta;
8211 /* Prepare to shift upward, set len = length(subpage part to shift) */
8215 return; /* do not make the node uneven-sized */
8217 xp = (MDB_page *)((char *)sp + delta); /* destination subpage */
8218 for (i = NUMKEYS(sp); --i >= 0; )
8219 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
8222 sp->mp_upper = sp->mp_lower;
8223 COPY_PGNO(sp->mp_pgno, mp->mp_pgno);
8224 SETDSZ(node, nsize);
8226 /* Shift <lower nodes...initial part of subpage> upward */
8227 base = (char *)mp + mp->mp_upper + PAGEBASE;
8228 memmove(base + delta, base, (char *)sp + len - base);
8230 ptr = mp->mp_ptrs[indx];
8231 for (i = NUMKEYS(mp); --i >= 0; ) {
8232 if (mp->mp_ptrs[i] <= ptr)
8233 mp->mp_ptrs[i] += delta;
8235 mp->mp_upper += delta;
8238 /** Initial setup of a sorted-dups cursor.
8239 * Sorted duplicates are implemented as a sub-database for the given key.
8240 * The duplicate data items are actually keys of the sub-database.
8241 * Operations on the duplicate data items are performed using a sub-cursor
8242 * initialized when the sub-database is first accessed. This function does
8243 * the preliminary setup of the sub-cursor, filling in the fields that
8244 * depend only on the parent DB.
8245 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
8248 mdb_xcursor_init0(MDB_cursor *mc)
8250 MDB_xcursor *mx = mc->mc_xcursor;
8252 mx->mx_cursor.mc_xcursor = NULL;
8253 mx->mx_cursor.mc_txn = mc->mc_txn;
8254 mx->mx_cursor.mc_db = &mx->mx_db;
8255 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
8256 mx->mx_cursor.mc_dbi = mc->mc_dbi;
8257 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
8258 mx->mx_cursor.mc_snum = 0;
8259 mx->mx_cursor.mc_top = 0;
8260 MC_SET_OVPG(&mx->mx_cursor, NULL);
8261 mx->mx_cursor.mc_flags = C_SUB | (mc->mc_flags & (C_ORIG_RDONLY|C_WRITEMAP));
8262 mx->mx_dbx.md_name.mv_size = 0;
8263 mx->mx_dbx.md_name.mv_data = NULL;
8264 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
8265 mx->mx_dbx.md_dcmp = NULL;
8266 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
8269 /** Final setup of a sorted-dups cursor.
8270 * Sets up the fields that depend on the data from the main cursor.
8271 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
8272 * @param[in] node The data containing the #MDB_db record for the
8273 * sorted-dup database.
8276 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
8278 MDB_xcursor *mx = mc->mc_xcursor;
8280 mx->mx_cursor.mc_flags &= C_SUB|C_ORIG_RDONLY|C_WRITEMAP;
8281 if (node->mn_flags & F_SUBDATA) {
8282 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
8283 mx->mx_cursor.mc_pg[0] = 0;
8284 mx->mx_cursor.mc_snum = 0;
8285 mx->mx_cursor.mc_top = 0;
8287 MDB_page *fp = NODEDATA(node);
8288 mx->mx_db.md_pad = 0;
8289 mx->mx_db.md_flags = 0;
8290 mx->mx_db.md_depth = 1;
8291 mx->mx_db.md_branch_pages = 0;
8292 mx->mx_db.md_leaf_pages = 1;
8293 mx->mx_db.md_overflow_pages = 0;
8294 mx->mx_db.md_entries = NUMKEYS(fp);
8295 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
8296 mx->mx_cursor.mc_snum = 1;
8297 mx->mx_cursor.mc_top = 0;
8298 mx->mx_cursor.mc_flags |= C_INITIALIZED;
8299 mx->mx_cursor.mc_pg[0] = fp;
8300 mx->mx_cursor.mc_ki[0] = 0;
8301 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
8302 mx->mx_db.md_flags = MDB_DUPFIXED;
8303 mx->mx_db.md_pad = fp->mp_pad;
8304 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
8305 mx->mx_db.md_flags |= MDB_INTEGERKEY;
8308 DPRINTF(("Sub-db -%u root page %"Yu, mx->mx_cursor.mc_dbi,
8309 mx->mx_db.md_root));
8310 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DUPDATA;
8311 if (NEED_CMP_CLONG(mx->mx_dbx.md_cmp, mx->mx_db.md_pad))
8312 mx->mx_dbx.md_cmp = mdb_cmp_clong;
8316 /** Fixup a sorted-dups cursor due to underlying update.
8317 * Sets up some fields that depend on the data from the main cursor.
8318 * Almost the same as init1, but skips initialization steps if the
8319 * xcursor had already been used.
8320 * @param[in] mc The main cursor whose sorted-dups cursor is to be fixed up.
8321 * @param[in] src_mx The xcursor of an up-to-date cursor.
8322 * @param[in] new_dupdata True if converting from a non-#F_DUPDATA item.
8325 mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int new_dupdata)
8327 MDB_xcursor *mx = mc->mc_xcursor;
8330 mx->mx_cursor.mc_snum = 1;
8331 mx->mx_cursor.mc_top = 0;
8332 mx->mx_cursor.mc_flags |= C_INITIALIZED;
8333 mx->mx_cursor.mc_ki[0] = 0;
8334 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DUPDATA;
8335 #if UINT_MAX < MDB_SIZE_MAX /* matches mdb_xcursor_init1:NEED_CMP_CLONG() */
8336 mx->mx_dbx.md_cmp = src_mx->mx_dbx.md_cmp;
8338 } else if (!(mx->mx_cursor.mc_flags & C_INITIALIZED)) {
8341 mx->mx_db = src_mx->mx_db;
8342 mx->mx_cursor.mc_pg[0] = src_mx->mx_cursor.mc_pg[0];
8343 DPRINTF(("Sub-db -%u root page %"Yu, mx->mx_cursor.mc_dbi,
8344 mx->mx_db.md_root));
8347 /** Initialize a cursor for a given transaction and database. */
8349 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
8352 mc->mc_backup = NULL;
8355 mc->mc_db = &txn->mt_dbs[dbi];
8356 mc->mc_dbx = &txn->mt_dbxs[dbi];
8357 mc->mc_dbflag = &txn->mt_dbflags[dbi];
8362 MC_SET_OVPG(mc, NULL);
8363 mc->mc_flags = txn->mt_flags & (C_ORIG_RDONLY|C_WRITEMAP);
8364 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
8365 mdb_tassert(txn, mx != NULL);
8366 mc->mc_xcursor = mx;
8367 mdb_xcursor_init0(mc);
8369 mc->mc_xcursor = NULL;
8371 if (*mc->mc_dbflag & DB_STALE) {
8372 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
8377 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
8380 size_t size = sizeof(MDB_cursor);
8382 if (!ret || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
8385 if (txn->mt_flags & MDB_TXN_BLOCKED)
8388 if (dbi == FREE_DBI && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
8391 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
8392 size += sizeof(MDB_xcursor);
8394 if ((mc = malloc(size)) != NULL) {
8395 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
8396 if (txn->mt_cursors) {
8397 mc->mc_next = txn->mt_cursors[dbi];
8398 txn->mt_cursors[dbi] = mc;
8399 mc->mc_flags |= C_UNTRACK;
8411 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
8413 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi, DB_VALID))
8416 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
8419 if (txn->mt_flags & MDB_TXN_BLOCKED)
8422 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
8426 /* Return the count of duplicate data items for the current key */
8428 mdb_cursor_count(MDB_cursor *mc, mdb_size_t *countp)
8432 if (mc == NULL || countp == NULL)
8435 if (mc->mc_xcursor == NULL)
8436 return MDB_INCOMPATIBLE;
8438 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
8441 if (!(mc->mc_flags & C_INITIALIZED))
8445 return MDB_NOTFOUND;
8447 if (mc->mc_flags & C_EOF) {
8448 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
8449 return MDB_NOTFOUND;
8450 mc->mc_flags ^= C_EOF;
8453 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
8454 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
8457 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
8460 *countp = mc->mc_xcursor->mx_db.md_entries;
8466 mdb_cursor_close(MDB_cursor *mc)
8469 MDB_CURSOR_UNREF(mc, 0);
8471 if (mc && !mc->mc_backup) {
8472 /* Remove from txn, if tracked.
8473 * A read-only txn (!C_UNTRACK) may have been freed already,
8474 * so do not peek inside it. Only write txns track cursors.
8476 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
8477 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
8478 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
8480 *prev = mc->mc_next;
8487 mdb_cursor_txn(MDB_cursor *mc)
8489 if (!mc) return NULL;
8494 mdb_cursor_dbi(MDB_cursor *mc)
8499 /** Replace the key for a branch node with a new key.
8500 * Set #MDB_TXN_ERROR on failure.
8501 * @param[in] mc Cursor pointing to the node to operate on.
8502 * @param[in] key The new key to use.
8503 * @return 0 on success, non-zero on failure.
8506 mdb_update_key(MDB_cursor *mc, MDB_val *key)
8512 int delta, ksize, oksize;
8513 indx_t ptr, i, numkeys, indx;
8516 indx = mc->mc_ki[mc->mc_top];
8517 mp = mc->mc_pg[mc->mc_top];
8518 node = NODEPTR(mp, indx);
8519 ptr = mp->mp_ptrs[indx];
8523 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
8524 k2.mv_data = NODEKEY(node);
8525 k2.mv_size = node->mn_ksize;
8526 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Yu,
8528 mdb_dkey(&k2, kbuf2),
8534 /* Sizes must be 2-byte aligned. */
8535 ksize = EVEN(key->mv_size);
8536 oksize = EVEN(node->mn_ksize);
8537 delta = ksize - oksize;
8539 /* Shift node contents if EVEN(key length) changed. */
8541 if (delta > 0 && SIZELEFT(mp) < delta) {
8543 /* not enough space left, do a delete and split */
8544 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
8545 pgno = NODEPGNO(node);
8546 mdb_node_del(mc, 0);
8547 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
8550 numkeys = NUMKEYS(mp);
8551 for (i = 0; i < numkeys; i++) {
8552 if (mp->mp_ptrs[i] <= ptr)
8553 mp->mp_ptrs[i] -= delta;
8556 base = (char *)mp + mp->mp_upper + PAGEBASE;
8557 len = ptr - mp->mp_upper + NODESIZE;
8558 memmove(base - delta, base, len);
8559 mp->mp_upper -= delta;
8561 node = NODEPTR(mp, indx);
8564 /* But even if no shift was needed, update ksize */
8565 if (node->mn_ksize != key->mv_size)
8566 node->mn_ksize = key->mv_size;
8569 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
8575 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
8577 /** Perform \b act while tracking temporary cursor \b mn */
8578 #define WITH_CURSOR_TRACKING(mn, act) do { \
8579 MDB_cursor dummy, *tracked, **tp = &(mn).mc_txn->mt_cursors[mn.mc_dbi]; \
8580 if ((mn).mc_flags & C_SUB) { \
8581 dummy.mc_flags = C_INITIALIZED; \
8582 dummy.mc_xcursor = (MDB_xcursor *)&(mn); \
8587 tracked->mc_next = *tp; \
8590 *tp = tracked->mc_next; \
8593 /** Move a node from csrc to cdst.
8596 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft)
8603 unsigned short flags;
8607 /* Mark src and dst as dirty. */
8608 if ((rc = mdb_page_touch(csrc)) ||
8609 (rc = mdb_page_touch(cdst)))
8612 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8613 key.mv_size = csrc->mc_db->md_pad;
8614 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
8616 data.mv_data = NULL;
8620 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
8621 mdb_cassert(csrc, !((size_t)srcnode & 1));
8622 srcpg = NODEPGNO(srcnode);
8623 flags = srcnode->mn_flags;
8624 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
8625 unsigned int snum = csrc->mc_snum;
8627 /* must find the lowest key below src */
8628 rc = mdb_page_search_lowest(csrc);
8631 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8632 key.mv_size = csrc->mc_db->md_pad;
8633 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
8635 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
8636 key.mv_size = NODEKSZ(s2);
8637 key.mv_data = NODEKEY(s2);
8639 csrc->mc_snum = snum--;
8640 csrc->mc_top = snum;
8642 key.mv_size = NODEKSZ(srcnode);
8643 key.mv_data = NODEKEY(srcnode);
8645 data.mv_size = NODEDSZ(srcnode);
8646 data.mv_data = NODEDATA(srcnode);
8648 mn.mc_xcursor = NULL;
8649 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
8650 unsigned int snum = cdst->mc_snum;
8653 /* must find the lowest key below dst */
8654 mdb_cursor_copy(cdst, &mn);
8655 rc = mdb_page_search_lowest(&mn);
8658 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
8659 bkey.mv_size = mn.mc_db->md_pad;
8660 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
8662 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
8663 bkey.mv_size = NODEKSZ(s2);
8664 bkey.mv_data = NODEKEY(s2);
8666 mn.mc_snum = snum--;
8669 rc = mdb_update_key(&mn, &bkey);
8674 DPRINTF(("moving %s node %u [%s] on page %"Yu" to node %u on page %"Yu,
8675 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
8676 csrc->mc_ki[csrc->mc_top],
8678 csrc->mc_pg[csrc->mc_top]->mp_pgno,
8679 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
8681 /* Add the node to the destination page.
8683 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
8684 if (rc != MDB_SUCCESS)
8687 /* Delete the node from the source page.
8689 mdb_node_del(csrc, key.mv_size);
8692 /* Adjust other cursors pointing to mp */
8693 MDB_cursor *m2, *m3;
8694 MDB_dbi dbi = csrc->mc_dbi;
8695 MDB_page *mpd, *mps;
8697 mps = csrc->mc_pg[csrc->mc_top];
8698 /* If we're adding on the left, bump others up */
8700 mpd = cdst->mc_pg[csrc->mc_top];
8701 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8702 if (csrc->mc_flags & C_SUB)
8703 m3 = &m2->mc_xcursor->mx_cursor;
8706 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
8709 m3->mc_pg[csrc->mc_top] == mpd &&
8710 m3->mc_ki[csrc->mc_top] >= cdst->mc_ki[csrc->mc_top]) {
8711 m3->mc_ki[csrc->mc_top]++;
8714 m3->mc_pg[csrc->mc_top] == mps &&
8715 m3->mc_ki[csrc->mc_top] == csrc->mc_ki[csrc->mc_top]) {
8716 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
8717 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
8718 m3->mc_ki[csrc->mc_top-1]++;
8720 if (XCURSOR_INITED(m3) && IS_LEAF(mps))
8721 XCURSOR_REFRESH(m3, m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
8724 /* Adding on the right, bump others down */
8726 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8727 if (csrc->mc_flags & C_SUB)
8728 m3 = &m2->mc_xcursor->mx_cursor;
8731 if (m3 == csrc) continue;
8732 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
8734 if (m3->mc_pg[csrc->mc_top] == mps) {
8735 if (!m3->mc_ki[csrc->mc_top]) {
8736 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
8737 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
8738 m3->mc_ki[csrc->mc_top-1]--;
8740 m3->mc_ki[csrc->mc_top]--;
8742 if (XCURSOR_INITED(m3) && IS_LEAF(mps))
8743 XCURSOR_REFRESH(m3, m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
8749 /* Update the parent separators.
8751 if (csrc->mc_ki[csrc->mc_top] == 0) {
8752 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
8753 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8754 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
8756 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
8757 key.mv_size = NODEKSZ(srcnode);
8758 key.mv_data = NODEKEY(srcnode);
8760 DPRINTF(("update separator for source page %"Yu" to [%s]",
8761 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
8762 mdb_cursor_copy(csrc, &mn);
8765 /* We want mdb_rebalance to find mn when doing fixups */
8766 WITH_CURSOR_TRACKING(mn,
8767 rc = mdb_update_key(&mn, &key));
8771 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
8773 indx_t ix = csrc->mc_ki[csrc->mc_top];
8774 nullkey.mv_size = 0;
8775 csrc->mc_ki[csrc->mc_top] = 0;
8776 rc = mdb_update_key(csrc, &nullkey);
8777 csrc->mc_ki[csrc->mc_top] = ix;
8778 mdb_cassert(csrc, rc == MDB_SUCCESS);
8782 if (cdst->mc_ki[cdst->mc_top] == 0) {
8783 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
8784 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8785 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
8787 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
8788 key.mv_size = NODEKSZ(srcnode);
8789 key.mv_data = NODEKEY(srcnode);
8791 DPRINTF(("update separator for destination page %"Yu" to [%s]",
8792 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
8793 mdb_cursor_copy(cdst, &mn);
8796 /* We want mdb_rebalance to find mn when doing fixups */
8797 WITH_CURSOR_TRACKING(mn,
8798 rc = mdb_update_key(&mn, &key));
8802 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
8804 indx_t ix = cdst->mc_ki[cdst->mc_top];
8805 nullkey.mv_size = 0;
8806 cdst->mc_ki[cdst->mc_top] = 0;
8807 rc = mdb_update_key(cdst, &nullkey);
8808 cdst->mc_ki[cdst->mc_top] = ix;
8809 mdb_cassert(cdst, rc == MDB_SUCCESS);
8816 /** Merge one page into another.
8817 * The nodes from the page pointed to by \b csrc will
8818 * be copied to the page pointed to by \b cdst and then
8819 * the \b csrc page will be freed.
8820 * @param[in] csrc Cursor pointing to the source page.
8821 * @param[in] cdst Cursor pointing to the destination page.
8822 * @return 0 on success, non-zero on failure.
8825 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
8827 MDB_page *psrc, *pdst;
8834 psrc = csrc->mc_pg[csrc->mc_top];
8835 pdst = cdst->mc_pg[cdst->mc_top];
8837 DPRINTF(("merging page %"Yu" into %"Yu, psrc->mp_pgno, pdst->mp_pgno));
8839 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
8840 mdb_cassert(csrc, cdst->mc_snum > 1);
8842 /* Mark dst as dirty. */
8843 if ((rc = mdb_page_touch(cdst)))
8846 /* get dst page again now that we've touched it. */
8847 pdst = cdst->mc_pg[cdst->mc_top];
8849 /* Move all nodes from src to dst.
8851 j = nkeys = NUMKEYS(pdst);
8852 if (IS_LEAF2(psrc)) {
8853 key.mv_size = csrc->mc_db->md_pad;
8854 key.mv_data = METADATA(psrc);
8855 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
8856 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
8857 if (rc != MDB_SUCCESS)
8859 key.mv_data = (char *)key.mv_data + key.mv_size;
8862 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
8863 srcnode = NODEPTR(psrc, i);
8864 if (i == 0 && IS_BRANCH(psrc)) {
8867 mdb_cursor_copy(csrc, &mn);
8868 mn.mc_xcursor = NULL;
8869 /* must find the lowest key below src */
8870 rc = mdb_page_search_lowest(&mn);
8873 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
8874 key.mv_size = mn.mc_db->md_pad;
8875 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
8877 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
8878 key.mv_size = NODEKSZ(s2);
8879 key.mv_data = NODEKEY(s2);
8882 key.mv_size = srcnode->mn_ksize;
8883 key.mv_data = NODEKEY(srcnode);
8886 data.mv_size = NODEDSZ(srcnode);
8887 data.mv_data = NODEDATA(srcnode);
8888 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
8889 if (rc != MDB_SUCCESS)
8894 DPRINTF(("dst page %"Yu" now has %u keys (%.1f%% filled)",
8895 pdst->mp_pgno, NUMKEYS(pdst),
8896 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
8898 /* Unlink the src page from parent and add to free list.
8901 mdb_node_del(csrc, 0);
8902 if (csrc->mc_ki[csrc->mc_top] == 0) {
8904 rc = mdb_update_key(csrc, &key);
8912 psrc = csrc->mc_pg[csrc->mc_top];
8913 /* If not operating on FreeDB, allow this page to be reused
8914 * in this txn. Otherwise just add to free list.
8916 rc = mdb_page_loose(csrc, psrc);
8920 csrc->mc_db->md_leaf_pages--;
8922 csrc->mc_db->md_branch_pages--;
8924 /* Adjust other cursors pointing to mp */
8925 MDB_cursor *m2, *m3;
8926 MDB_dbi dbi = csrc->mc_dbi;
8927 unsigned int top = csrc->mc_top;
8929 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8930 if (csrc->mc_flags & C_SUB)
8931 m3 = &m2->mc_xcursor->mx_cursor;
8934 if (m3 == csrc) continue;
8935 if (m3->mc_snum < csrc->mc_snum) continue;
8936 if (m3->mc_pg[top] == psrc) {
8937 m3->mc_pg[top] = pdst;
8938 m3->mc_ki[top] += nkeys;
8939 m3->mc_ki[top-1] = cdst->mc_ki[top-1];
8940 } else if (m3->mc_pg[top-1] == csrc->mc_pg[top-1] &&
8941 m3->mc_ki[top-1] > csrc->mc_ki[top-1]) {
8944 if (XCURSOR_INITED(m3) && IS_LEAF(psrc))
8945 XCURSOR_REFRESH(m3, m3->mc_pg[top], m3->mc_ki[top]);
8949 unsigned int snum = cdst->mc_snum;
8950 uint16_t depth = cdst->mc_db->md_depth;
8951 mdb_cursor_pop(cdst);
8952 rc = mdb_rebalance(cdst);
8953 /* Did the tree height change? */
8954 if (depth != cdst->mc_db->md_depth)
8955 snum += cdst->mc_db->md_depth - depth;
8956 cdst->mc_snum = snum;
8957 cdst->mc_top = snum-1;
8962 /** Copy the contents of a cursor.
8963 * @param[in] csrc The cursor to copy from.
8964 * @param[out] cdst The cursor to copy to.
8967 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
8971 cdst->mc_txn = csrc->mc_txn;
8972 cdst->mc_dbi = csrc->mc_dbi;
8973 cdst->mc_db = csrc->mc_db;
8974 cdst->mc_dbx = csrc->mc_dbx;
8975 cdst->mc_snum = csrc->mc_snum;
8976 cdst->mc_top = csrc->mc_top;
8977 cdst->mc_flags = csrc->mc_flags;
8978 MC_SET_OVPG(cdst, MC_OVPG(csrc));
8980 for (i=0; i<csrc->mc_snum; i++) {
8981 cdst->mc_pg[i] = csrc->mc_pg[i];
8982 cdst->mc_ki[i] = csrc->mc_ki[i];
8986 /** Rebalance the tree after a delete operation.
8987 * @param[in] mc Cursor pointing to the page where rebalancing
8989 * @return 0 on success, non-zero on failure.
8992 mdb_rebalance(MDB_cursor *mc)
8996 unsigned int ptop, minkeys, thresh;
9000 if (IS_BRANCH(mc->mc_pg[mc->mc_top])) {
9005 thresh = FILL_THRESHOLD;
9007 DPRINTF(("rebalancing %s page %"Yu" (has %u keys, %.1f%% full)",
9008 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
9009 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
9010 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
9012 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= thresh &&
9013 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
9014 DPRINTF(("no need to rebalance page %"Yu", above fill threshold",
9015 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
9019 if (mc->mc_snum < 2) {
9020 MDB_page *mp = mc->mc_pg[0];
9022 DPUTS("Can't rebalance a subpage, ignoring");
9025 if (NUMKEYS(mp) == 0) {
9026 DPUTS("tree is completely empty");
9027 mc->mc_db->md_root = P_INVALID;
9028 mc->mc_db->md_depth = 0;
9029 mc->mc_db->md_leaf_pages = 0;
9030 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
9033 /* Adjust cursors pointing to mp */
9036 mc->mc_flags &= ~C_INITIALIZED;
9038 MDB_cursor *m2, *m3;
9039 MDB_dbi dbi = mc->mc_dbi;
9041 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9042 if (mc->mc_flags & C_SUB)
9043 m3 = &m2->mc_xcursor->mx_cursor;
9046 if (!(m3->mc_flags & C_INITIALIZED) || (m3->mc_snum < mc->mc_snum))
9048 if (m3->mc_pg[0] == mp) {
9051 m3->mc_flags &= ~C_INITIALIZED;
9055 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
9057 DPUTS("collapsing root page!");
9058 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
9061 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
9062 rc = mdb_page_get(mc, mc->mc_db->md_root, &mc->mc_pg[0], NULL);
9065 mc->mc_db->md_depth--;
9066 mc->mc_db->md_branch_pages--;
9067 mc->mc_ki[0] = mc->mc_ki[1];
9068 for (i = 1; i<mc->mc_db->md_depth; i++) {
9069 mc->mc_pg[i] = mc->mc_pg[i+1];
9070 mc->mc_ki[i] = mc->mc_ki[i+1];
9073 /* Adjust other cursors pointing to mp */
9074 MDB_cursor *m2, *m3;
9075 MDB_dbi dbi = mc->mc_dbi;
9077 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9078 if (mc->mc_flags & C_SUB)
9079 m3 = &m2->mc_xcursor->mx_cursor;
9082 if (m3 == mc) continue;
9083 if (!(m3->mc_flags & C_INITIALIZED))
9085 if (m3->mc_pg[0] == mp) {
9086 for (i=0; i<mc->mc_db->md_depth; i++) {
9087 m3->mc_pg[i] = m3->mc_pg[i+1];
9088 m3->mc_ki[i] = m3->mc_ki[i+1];
9096 DPUTS("root page doesn't need rebalancing");
9100 /* The parent (branch page) must have at least 2 pointers,
9101 * otherwise the tree is invalid.
9103 ptop = mc->mc_top-1;
9104 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
9106 /* Leaf page fill factor is below the threshold.
9107 * Try to move keys from left or right neighbor, or
9108 * merge with a neighbor page.
9113 mdb_cursor_copy(mc, &mn);
9114 mn.mc_xcursor = NULL;
9116 oldki = mc->mc_ki[mc->mc_top];
9117 if (mc->mc_ki[ptop] == 0) {
9118 /* We're the leftmost leaf in our parent.
9120 DPUTS("reading right neighbor");
9122 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
9123 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
9126 mn.mc_ki[mn.mc_top] = 0;
9127 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
9130 /* There is at least one neighbor to the left.
9132 DPUTS("reading left neighbor");
9134 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
9135 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
9138 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
9139 mc->mc_ki[mc->mc_top] = 0;
9143 DPRINTF(("found neighbor page %"Yu" (%u keys, %.1f%% full)",
9144 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
9145 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
9147 /* If the neighbor page is above threshold and has enough keys,
9148 * move one key from it. Otherwise we should try to merge them.
9149 * (A branch page must never have less than 2 keys.)
9151 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= thresh && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
9152 rc = mdb_node_move(&mn, mc, fromleft);
9154 /* if we inserted on left, bump position up */
9159 rc = mdb_page_merge(&mn, mc);
9161 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
9162 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
9163 /* We want mdb_rebalance to find mn when doing fixups */
9164 WITH_CURSOR_TRACKING(mn,
9165 rc = mdb_page_merge(mc, &mn));
9166 mdb_cursor_copy(&mn, mc);
9168 mc->mc_flags &= ~C_EOF;
9170 mc->mc_ki[mc->mc_top] = oldki;
9174 /** Complete a delete operation started by #mdb_cursor_del(). */
9176 mdb_cursor_del0(MDB_cursor *mc)
9182 MDB_cursor *m2, *m3;
9183 MDB_dbi dbi = mc->mc_dbi;
9185 ki = mc->mc_ki[mc->mc_top];
9186 mp = mc->mc_pg[mc->mc_top];
9187 mdb_node_del(mc, mc->mc_db->md_pad);
9188 mc->mc_db->md_entries--;
9190 /* Adjust other cursors pointing to mp */
9191 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9192 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
9193 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9195 if (m3 == mc || m3->mc_snum < mc->mc_snum)
9197 if (m3->mc_pg[mc->mc_top] == mp) {
9198 if (m3->mc_ki[mc->mc_top] == ki) {
9199 m3->mc_flags |= C_DEL;
9200 if (mc->mc_db->md_flags & MDB_DUPSORT) {
9201 /* Sub-cursor referred into dataset which is gone */
9202 m3->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
9205 } else if (m3->mc_ki[mc->mc_top] > ki) {
9206 m3->mc_ki[mc->mc_top]--;
9208 if (XCURSOR_INITED(m3))
9209 XCURSOR_REFRESH(m3, m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
9213 rc = mdb_rebalance(mc);
9215 if (rc == MDB_SUCCESS) {
9216 /* DB is totally empty now, just bail out.
9217 * Other cursors adjustments were already done
9218 * by mdb_rebalance and aren't needed here.
9223 mp = mc->mc_pg[mc->mc_top];
9224 nkeys = NUMKEYS(mp);
9226 /* Adjust other cursors pointing to mp */
9227 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
9228 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
9229 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9231 if (m3->mc_snum < mc->mc_snum)
9233 if (m3->mc_pg[mc->mc_top] == mp) {
9234 /* if m3 points past last node in page, find next sibling */
9235 if (m3->mc_ki[mc->mc_top] >= mc->mc_ki[mc->mc_top]) {
9236 if (m3->mc_ki[mc->mc_top] >= nkeys) {
9237 rc = mdb_cursor_sibling(m3, 1);
9238 if (rc == MDB_NOTFOUND) {
9239 m3->mc_flags |= C_EOF;
9244 if (mc->mc_db->md_flags & MDB_DUPSORT) {
9245 MDB_node *node = NODEPTR(m3->mc_pg[m3->mc_top], m3->mc_ki[m3->mc_top]);
9246 /* If this node is a fake page, it needs to be reinited
9247 * because its data has moved. But just reset mc_pg[0]
9248 * if the xcursor is already live.
9250 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) {
9251 if (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)
9252 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
9254 mdb_xcursor_init1(m3, node);
9260 mc->mc_flags |= C_DEL;
9264 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
9269 mdb_del(MDB_txn *txn, MDB_dbi dbi,
9270 MDB_val *key, MDB_val *data)
9272 if (!key || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9275 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
9276 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
9278 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
9279 /* must ignore any data */
9283 return mdb_del0(txn, dbi, key, data, 0);
9287 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
9288 MDB_val *key, MDB_val *data, unsigned flags)
9293 MDB_val rdata, *xdata;
9297 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
9299 mdb_cursor_init(&mc, txn, dbi, &mx);
9308 flags |= MDB_NODUPDATA;
9310 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
9312 /* let mdb_page_split know about this cursor if needed:
9313 * delete will trigger a rebalance; if it needs to move
9314 * a node from one page to another, it will have to
9315 * update the parent's separator key(s). If the new sepkey
9316 * is larger than the current one, the parent page may
9317 * run out of space, triggering a split. We need this
9318 * cursor to be consistent until the end of the rebalance.
9320 mc.mc_next = txn->mt_cursors[dbi];
9321 txn->mt_cursors[dbi] = &mc;
9322 rc = mdb_cursor_del(&mc, flags);
9323 txn->mt_cursors[dbi] = mc.mc_next;
9328 /** Split a page and insert a new node.
9329 * Set #MDB_TXN_ERROR on failure.
9330 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
9331 * The cursor will be updated to point to the actual page and index where
9332 * the node got inserted after the split.
9333 * @param[in] newkey The key for the newly inserted node.
9334 * @param[in] newdata The data for the newly inserted node.
9335 * @param[in] newpgno The page number, if the new node is a branch node.
9336 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
9337 * @return 0 on success, non-zero on failure.
9340 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
9341 unsigned int nflags)
9344 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
9347 int i, j, split_indx, nkeys, pmax;
9348 MDB_env *env = mc->mc_txn->mt_env;
9350 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
9351 MDB_page *copy = NULL;
9352 MDB_page *mp, *rp, *pp;
9357 mp = mc->mc_pg[mc->mc_top];
9358 newindx = mc->mc_ki[mc->mc_top];
9359 nkeys = NUMKEYS(mp);
9361 DPRINTF(("-----> splitting %s page %"Yu" and adding [%s] at index %i/%i",
9362 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
9363 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
9365 /* Create a right sibling. */
9366 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
9368 rp->mp_pad = mp->mp_pad;
9369 DPRINTF(("new right sibling: page %"Yu, rp->mp_pgno));
9371 /* Usually when splitting the root page, the cursor
9372 * height is 1. But when called from mdb_update_key,
9373 * the cursor height may be greater because it walks
9374 * up the stack while finding the branch slot to update.
9376 if (mc->mc_top < 1) {
9377 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
9379 /* shift current top to make room for new parent */
9380 for (i=mc->mc_snum; i>0; i--) {
9381 mc->mc_pg[i] = mc->mc_pg[i-1];
9382 mc->mc_ki[i] = mc->mc_ki[i-1];
9386 mc->mc_db->md_root = pp->mp_pgno;
9387 DPRINTF(("root split! new root = %"Yu, pp->mp_pgno));
9388 new_root = mc->mc_db->md_depth++;
9390 /* Add left (implicit) pointer. */
9391 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
9392 /* undo the pre-push */
9393 mc->mc_pg[0] = mc->mc_pg[1];
9394 mc->mc_ki[0] = mc->mc_ki[1];
9395 mc->mc_db->md_root = mp->mp_pgno;
9396 mc->mc_db->md_depth--;
9403 ptop = mc->mc_top-1;
9404 DPRINTF(("parent branch page is %"Yu, mc->mc_pg[ptop]->mp_pgno));
9407 mdb_cursor_copy(mc, &mn);
9408 mn.mc_xcursor = NULL;
9409 mn.mc_pg[mn.mc_top] = rp;
9410 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
9412 if (nflags & MDB_APPEND) {
9413 mn.mc_ki[mn.mc_top] = 0;
9415 split_indx = newindx;
9419 split_indx = (nkeys+1) / 2;
9424 unsigned int lsize, rsize, ksize;
9425 /* Move half of the keys to the right sibling */
9426 x = mc->mc_ki[mc->mc_top] - split_indx;
9427 ksize = mc->mc_db->md_pad;
9428 split = LEAF2KEY(mp, split_indx, ksize);
9429 rsize = (nkeys - split_indx) * ksize;
9430 lsize = (nkeys - split_indx) * sizeof(indx_t);
9431 mp->mp_lower -= lsize;
9432 rp->mp_lower += lsize;
9433 mp->mp_upper += rsize - lsize;
9434 rp->mp_upper -= rsize - lsize;
9435 sepkey.mv_size = ksize;
9436 if (newindx == split_indx) {
9437 sepkey.mv_data = newkey->mv_data;
9439 sepkey.mv_data = split;
9442 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
9443 memcpy(rp->mp_ptrs, split, rsize);
9444 sepkey.mv_data = rp->mp_ptrs;
9445 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
9446 memcpy(ins, newkey->mv_data, ksize);
9447 mp->mp_lower += sizeof(indx_t);
9448 mp->mp_upper -= ksize - sizeof(indx_t);
9451 memcpy(rp->mp_ptrs, split, x * ksize);
9452 ins = LEAF2KEY(rp, x, ksize);
9453 memcpy(ins, newkey->mv_data, ksize);
9454 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
9455 rp->mp_lower += sizeof(indx_t);
9456 rp->mp_upper -= ksize - sizeof(indx_t);
9457 mc->mc_ki[mc->mc_top] = x;
9460 int psize, nsize, k;
9461 /* Maximum free space in an empty page */
9462 pmax = env->me_psize - PAGEHDRSZ;
9464 nsize = mdb_leaf_size(env, newkey, newdata);
9466 nsize = mdb_branch_size(env, newkey);
9467 nsize = EVEN(nsize);
9469 /* grab a page to hold a temporary copy */
9470 copy = mdb_page_malloc(mc->mc_txn, 1);
9475 copy->mp_pgno = mp->mp_pgno;
9476 copy->mp_flags = mp->mp_flags;
9477 copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
9478 copy->mp_upper = env->me_psize - PAGEBASE;
9480 /* prepare to insert */
9481 for (i=0, j=0; i<nkeys; i++) {
9483 copy->mp_ptrs[j++] = 0;
9485 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
9488 /* When items are relatively large the split point needs
9489 * to be checked, because being off-by-one will make the
9490 * difference between success or failure in mdb_node_add.
9492 * It's also relevant if a page happens to be laid out
9493 * such that one half of its nodes are all "small" and
9494 * the other half of its nodes are "large." If the new
9495 * item is also "large" and falls on the half with
9496 * "large" nodes, it also may not fit.
9498 * As a final tweak, if the new item goes on the last
9499 * spot on the page (and thus, onto the new page), bias
9500 * the split so the new page is emptier than the old page.
9501 * This yields better packing during sequential inserts.
9503 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
9504 /* Find split point */
9506 if (newindx <= split_indx || newindx >= nkeys) {
9508 k = newindx >= nkeys ? nkeys : split_indx+1+IS_LEAF(mp);
9513 for (; i!=k; i+=j) {
9518 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
9519 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
9521 if (F_ISSET(node->mn_flags, F_BIGDATA))
9522 psize += sizeof(pgno_t);
9524 psize += NODEDSZ(node);
9526 psize = EVEN(psize);
9528 if (psize > pmax || i == k-j) {
9529 split_indx = i + (j<0);
9534 if (split_indx == newindx) {
9535 sepkey.mv_size = newkey->mv_size;
9536 sepkey.mv_data = newkey->mv_data;
9538 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
9539 sepkey.mv_size = node->mn_ksize;
9540 sepkey.mv_data = NODEKEY(node);
9545 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
9547 /* Copy separator key to the parent.
9549 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
9550 int snum = mc->mc_snum;
9554 /* We want other splits to find mn when doing fixups */
9555 WITH_CURSOR_TRACKING(mn,
9556 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0));
9561 if (mc->mc_snum > snum) {
9564 /* Right page might now have changed parent.
9565 * Check if left page also changed parent.
9567 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
9568 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
9569 for (i=0; i<ptop; i++) {
9570 mc->mc_pg[i] = mn.mc_pg[i];
9571 mc->mc_ki[i] = mn.mc_ki[i];
9573 mc->mc_pg[ptop] = mn.mc_pg[ptop];
9574 if (mn.mc_ki[ptop]) {
9575 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
9577 /* find right page's left sibling */
9578 mc->mc_ki[ptop] = mn.mc_ki[ptop];
9579 rc = mdb_cursor_sibling(mc, 0);
9584 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
9587 if (rc != MDB_SUCCESS) {
9588 if (rc == MDB_NOTFOUND) /* improper mdb_cursor_sibling() result */
9592 if (nflags & MDB_APPEND) {
9593 mc->mc_pg[mc->mc_top] = rp;
9594 mc->mc_ki[mc->mc_top] = 0;
9595 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
9598 for (i=0; i<mc->mc_top; i++)
9599 mc->mc_ki[i] = mn.mc_ki[i];
9600 } else if (!IS_LEAF2(mp)) {
9602 mc->mc_pg[mc->mc_top] = rp;
9607 rkey.mv_data = newkey->mv_data;
9608 rkey.mv_size = newkey->mv_size;
9614 /* Update index for the new key. */
9615 mc->mc_ki[mc->mc_top] = j;
9617 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
9618 rkey.mv_data = NODEKEY(node);
9619 rkey.mv_size = node->mn_ksize;
9621 xdata.mv_data = NODEDATA(node);
9622 xdata.mv_size = NODEDSZ(node);
9625 pgno = NODEPGNO(node);
9626 flags = node->mn_flags;
9629 if (!IS_LEAF(mp) && j == 0) {
9630 /* First branch index doesn't need key data. */
9634 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
9640 mc->mc_pg[mc->mc_top] = copy;
9645 } while (i != split_indx);
9647 nkeys = NUMKEYS(copy);
9648 for (i=0; i<nkeys; i++)
9649 mp->mp_ptrs[i] = copy->mp_ptrs[i];
9650 mp->mp_lower = copy->mp_lower;
9651 mp->mp_upper = copy->mp_upper;
9652 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
9653 env->me_psize - copy->mp_upper - PAGEBASE);
9655 /* reset back to original page */
9656 if (newindx < split_indx) {
9657 mc->mc_pg[mc->mc_top] = mp;
9659 mc->mc_pg[mc->mc_top] = rp;
9661 /* Make sure mc_ki is still valid.
9663 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
9664 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
9665 for (i=0; i<=ptop; i++) {
9666 mc->mc_pg[i] = mn.mc_pg[i];
9667 mc->mc_ki[i] = mn.mc_ki[i];
9671 if (nflags & MDB_RESERVE) {
9672 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
9673 if (!(node->mn_flags & F_BIGDATA))
9674 newdata->mv_data = NODEDATA(node);
9677 if (newindx >= split_indx) {
9678 mc->mc_pg[mc->mc_top] = rp;
9680 /* Make sure mc_ki is still valid.
9682 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
9683 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
9684 for (i=0; i<=ptop; i++) {
9685 mc->mc_pg[i] = mn.mc_pg[i];
9686 mc->mc_ki[i] = mn.mc_ki[i];
9693 /* Adjust other cursors pointing to mp */
9694 MDB_cursor *m2, *m3;
9695 MDB_dbi dbi = mc->mc_dbi;
9696 nkeys = NUMKEYS(mp);
9698 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9699 if (mc->mc_flags & C_SUB)
9700 m3 = &m2->mc_xcursor->mx_cursor;
9705 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9709 /* sub cursors may be on different DB */
9710 if (m3->mc_pg[0] != mp)
9713 for (k=new_root; k>=0; k--) {
9714 m3->mc_ki[k+1] = m3->mc_ki[k];
9715 m3->mc_pg[k+1] = m3->mc_pg[k];
9717 if (m3->mc_ki[0] >= nkeys) {
9722 m3->mc_pg[0] = mc->mc_pg[0];
9726 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
9727 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
9728 m3->mc_ki[mc->mc_top]++;
9729 if (m3->mc_ki[mc->mc_top] >= nkeys) {
9730 m3->mc_pg[mc->mc_top] = rp;
9731 m3->mc_ki[mc->mc_top] -= nkeys;
9732 for (i=0; i<mc->mc_top; i++) {
9733 m3->mc_ki[i] = mn.mc_ki[i];
9734 m3->mc_pg[i] = mn.mc_pg[i];
9737 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
9738 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
9741 if (XCURSOR_INITED(m3) && IS_LEAF(mp))
9742 XCURSOR_REFRESH(m3, m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
9745 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
9748 if (copy) /* tmp page */
9749 mdb_page_free(env, copy);
9751 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
9756 mdb_put(MDB_txn *txn, MDB_dbi dbi,
9757 MDB_val *key, MDB_val *data, unsigned int flags)
9763 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9766 if (flags & ~(MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP))
9769 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
9770 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
9772 mdb_cursor_init(&mc, txn, dbi, &mx);
9773 mc.mc_next = txn->mt_cursors[dbi];
9774 txn->mt_cursors[dbi] = &mc;
9775 rc = mdb_cursor_put(&mc, key, data, flags);
9776 txn->mt_cursors[dbi] = mc.mc_next;
9781 #define MDB_WBUF (1024*1024)
9783 #define MDB_EOF 0x10 /**< #mdb_env_copyfd1() is done reading */
9785 /** State needed for a double-buffering compacting copy. */
9786 typedef struct mdb_copy {
9789 pthread_mutex_t mc_mutex;
9790 pthread_cond_t mc_cond; /**< Condition variable for #mc_new */
9795 pgno_t mc_next_pgno;
9797 int mc_toggle; /**< Buffer number in provider */
9798 int mc_new; /**< (0-2 buffers to write) | (#MDB_EOF at end) */
9799 /** Error code. Never cleared if set. Both threads can set nonzero
9800 * to fail the copy. Not mutex-protected, LMDB expects atomic int.
9802 volatile int mc_error;
9805 /** Dedicated writer thread for compacting copy. */
9806 static THREAD_RET ESECT CALL_CONV
9807 mdb_env_copythr(void *arg)
9811 int toggle = 0, wsize, rc;
9814 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
9817 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
9821 sigaddset(&set, SIGPIPE);
9822 if ((rc = pthread_sigmask(SIG_BLOCK, &set, NULL)) != 0)
9827 pthread_mutex_lock(&my->mc_mutex);
9830 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
9831 if (my->mc_new == 0 + MDB_EOF) /* 0 buffers, just EOF */
9833 wsize = my->mc_wlen[toggle];
9834 ptr = my->mc_wbuf[toggle];
9837 while (wsize > 0 && !my->mc_error) {
9838 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
9841 #if defined(SIGPIPE) && !defined(_WIN32)
9843 /* Collect the pending SIGPIPE, otherwise at least OS X
9844 * gives it to the process on thread-exit (ITS#8504).
9847 sigwait(&set, &tmp);
9851 } else if (len > 0) {
9864 /* If there's an overflow page tail, write it too */
9865 if (my->mc_olen[toggle]) {
9866 wsize = my->mc_olen[toggle];
9867 ptr = my->mc_over[toggle];
9868 my->mc_olen[toggle] = 0;
9871 my->mc_wlen[toggle] = 0;
9873 /* Return the empty buffer to provider */
9875 pthread_cond_signal(&my->mc_cond);
9877 pthread_mutex_unlock(&my->mc_mutex);
9878 return (THREAD_RET)0;
9882 /** Give buffer and/or #MDB_EOF to writer thread, await unused buffer.
9884 * @param[in] my control structure.
9885 * @param[in] adjust (1 to hand off 1 buffer) | (MDB_EOF when ending).
9888 mdb_env_cthr_toggle(mdb_copy *my, int adjust)
9890 pthread_mutex_lock(&my->mc_mutex);
9891 my->mc_new += adjust;
9892 pthread_cond_signal(&my->mc_cond);
9893 while (my->mc_new & 2) /* both buffers in use */
9894 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
9895 pthread_mutex_unlock(&my->mc_mutex);
9897 my->mc_toggle ^= (adjust & 1);
9898 /* Both threads reset mc_wlen, to be safe from threading errors */
9899 my->mc_wlen[my->mc_toggle] = 0;
9900 return my->mc_error;
9903 /** Depth-first tree traversal for compacting copy.
9904 * @param[in] my control structure.
9905 * @param[in,out] pg database root.
9906 * @param[in] flags includes #F_DUPDATA if it is a sorted-duplicate sub-DB.
9909 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
9911 MDB_cursor mc = {0};
9913 MDB_page *mo, *mp, *leaf;
9918 /* Empty DB, nothing to do */
9919 if (*pg == P_INVALID)
9923 mc.mc_txn = my->mc_txn;
9924 mc.mc_flags = my->mc_txn->mt_flags & (C_ORIG_RDONLY|C_WRITEMAP);
9926 rc = mdb_page_get(&mc, *pg, &mc.mc_pg[0], NULL);
9929 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
9933 /* Make cursor pages writable */
9934 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
9938 for (i=0; i<mc.mc_top; i++) {
9939 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
9940 mc.mc_pg[i] = (MDB_page *)ptr;
9941 ptr += my->mc_env->me_psize;
9944 /* This is writable space for a leaf page. Usually not needed. */
9945 leaf = (MDB_page *)ptr;
9947 toggle = my->mc_toggle;
9948 while (mc.mc_snum > 0) {
9950 mp = mc.mc_pg[mc.mc_top];
9954 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
9955 for (i=0; i<n; i++) {
9956 ni = NODEPTR(mp, i);
9957 if (ni->mn_flags & F_BIGDATA) {
9961 /* Need writable leaf */
9963 mc.mc_pg[mc.mc_top] = leaf;
9964 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
9966 ni = NODEPTR(mp, i);
9969 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9970 memcpy(NODEDATA(ni), &my->mc_next_pgno, sizeof(pgno_t));
9971 rc = mdb_page_get(&mc, pg, &omp, NULL);
9974 if (my->mc_wlen[toggle] >= MDB_WBUF) {
9975 rc = mdb_env_cthr_toggle(my, 1);
9978 toggle = my->mc_toggle;
9980 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
9981 memcpy(mo, omp, my->mc_env->me_psize);
9982 mo->mp_pgno = my->mc_next_pgno;
9983 my->mc_next_pgno += omp->mp_pages;
9984 my->mc_wlen[toggle] += my->mc_env->me_psize;
9985 if (omp->mp_pages > 1) {
9986 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
9987 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
9988 rc = mdb_env_cthr_toggle(my, 1);
9991 toggle = my->mc_toggle;
9993 } else if (ni->mn_flags & F_SUBDATA) {
9996 /* Need writable leaf */
9998 mc.mc_pg[mc.mc_top] = leaf;
9999 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
10001 ni = NODEPTR(mp, i);
10004 memcpy(&db, NODEDATA(ni), sizeof(db));
10005 my->mc_toggle = toggle;
10006 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
10009 toggle = my->mc_toggle;
10010 memcpy(NODEDATA(ni), &db, sizeof(db));
10015 mc.mc_ki[mc.mc_top]++;
10016 if (mc.mc_ki[mc.mc_top] < n) {
10019 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
10021 rc = mdb_page_get(&mc, pg, &mp, NULL);
10026 mc.mc_ki[mc.mc_top] = 0;
10027 if (IS_BRANCH(mp)) {
10028 /* Whenever we advance to a sibling branch page,
10029 * we must proceed all the way down to its first leaf.
10031 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
10034 mc.mc_pg[mc.mc_top] = mp;
10038 if (my->mc_wlen[toggle] >= MDB_WBUF) {
10039 rc = mdb_env_cthr_toggle(my, 1);
10042 toggle = my->mc_toggle;
10044 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
10045 mdb_page_copy(mo, mp, my->mc_env->me_psize);
10046 mo->mp_pgno = my->mc_next_pgno++;
10047 my->mc_wlen[toggle] += my->mc_env->me_psize;
10049 /* Update parent if there is one */
10050 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
10051 SETPGNO(ni, mo->mp_pgno);
10052 mdb_cursor_pop(&mc);
10054 /* Otherwise we're done */
10064 /** Copy environment with compaction. */
10066 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
10071 MDB_txn *txn = NULL;
10073 pgno_t root, new_root;
10074 int rc = MDB_SUCCESS;
10077 if (!(my.mc_mutex = CreateMutex(NULL, FALSE, NULL)) ||
10078 !(my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL))) {
10082 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_os_psize);
10083 if (my.mc_wbuf[0] == NULL) {
10084 /* _aligned_malloc() sets errno, but we use Windows error codes */
10085 rc = ERROR_NOT_ENOUGH_MEMORY;
10089 if ((rc = pthread_mutex_init(&my.mc_mutex, NULL)) != 0)
10091 if ((rc = pthread_cond_init(&my.mc_cond, NULL)) != 0)
10093 #ifdef HAVE_MEMALIGN
10094 my.mc_wbuf[0] = memalign(env->me_os_psize, MDB_WBUF*2);
10095 if (my.mc_wbuf[0] == NULL) {
10102 if ((rc = posix_memalign(&p, env->me_os_psize, MDB_WBUF*2)) != 0)
10108 memset(my.mc_wbuf[0], 0, MDB_WBUF*2);
10109 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
10110 my.mc_next_pgno = NUM_METAS;
10113 rc = THREAD_CREATE(thr, mdb_env_copythr, &my);
10117 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
10121 mp = (MDB_page *)my.mc_wbuf[0];
10122 memset(mp, 0, NUM_METAS * env->me_psize);
10124 mp->mp_flags = P_META;
10125 mm = (MDB_meta *)METADATA(mp);
10126 mdb_env_init_meta0(env, mm);
10127 mm->mm_address = env->me_metas[0]->mm_address;
10129 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
10131 mp->mp_flags = P_META;
10132 *(MDB_meta *)METADATA(mp) = *mm;
10133 mm = (MDB_meta *)METADATA(mp);
10135 /* Set metapage 1 with current main DB */
10136 root = new_root = txn->mt_dbs[MAIN_DBI].md_root;
10137 if (root != P_INVALID) {
10138 /* Count free pages + freeDB pages. Subtract from last_pg
10139 * to find the new last_pg, which also becomes the new root.
10141 MDB_ID freecount = 0;
10144 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
10145 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
10146 freecount += *(MDB_ID *)data.mv_data;
10147 if (rc != MDB_NOTFOUND)
10149 freecount += txn->mt_dbs[FREE_DBI].md_branch_pages +
10150 txn->mt_dbs[FREE_DBI].md_leaf_pages +
10151 txn->mt_dbs[FREE_DBI].md_overflow_pages;
10153 new_root = txn->mt_next_pgno - 1 - freecount;
10154 mm->mm_last_pg = new_root;
10155 mm->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
10156 mm->mm_dbs[MAIN_DBI].md_root = new_root;
10158 /* When the DB is empty, handle it specially to
10159 * fix any breakage like page leaks from ITS#8174.
10161 mm->mm_dbs[MAIN_DBI].md_flags = txn->mt_dbs[MAIN_DBI].md_flags;
10163 if (root != P_INVALID || mm->mm_dbs[MAIN_DBI].md_flags) {
10164 mm->mm_txnid = 1; /* use metapage 1 */
10167 my.mc_wlen[0] = env->me_psize * NUM_METAS;
10169 rc = mdb_env_cwalk(&my, &root, 0);
10170 if (rc == MDB_SUCCESS && root != new_root) {
10171 rc = MDB_INCOMPATIBLE; /* page leak or corrupt DB */
10177 mdb_env_cthr_toggle(&my, 1 | MDB_EOF);
10178 rc = THREAD_FINISH(thr);
10179 mdb_txn_abort(txn);
10183 if (my.mc_wbuf[0]) _aligned_free(my.mc_wbuf[0]);
10184 if (my.mc_cond) CloseHandle(my.mc_cond);
10185 if (my.mc_mutex) CloseHandle(my.mc_mutex);
10187 free(my.mc_wbuf[0]);
10188 pthread_cond_destroy(&my.mc_cond);
10190 pthread_mutex_destroy(&my.mc_mutex);
10192 return rc ? rc : my.mc_error;
10195 /** Copy environment as-is. */
10197 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
10199 MDB_txn *txn = NULL;
10200 mdb_mutexref_t wmutex = NULL;
10202 mdb_size_t wsize, w3;
10206 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
10210 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
10213 /* Do the lock/unlock of the reader mutex before starting the
10214 * write txn. Otherwise other read txns could block writers.
10216 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
10220 if (env->me_txns) {
10221 /* We must start the actual read txn after blocking writers */
10222 mdb_txn_end(txn, MDB_END_RESET_TMP);
10224 /* Temporarily block writers until we snapshot the meta pages */
10225 wmutex = env->me_wmutex;
10226 if (LOCK_MUTEX(rc, env, wmutex))
10229 rc = mdb_txn_renew0(txn);
10231 UNLOCK_MUTEX(wmutex);
10236 wsize = env->me_psize * NUM_METAS;
10240 DO_WRITE(rc, fd, ptr, w2, len);
10244 } else if (len > 0) {
10250 /* Non-blocking or async handles are not supported */
10256 UNLOCK_MUTEX(wmutex);
10261 w3 = txn->mt_next_pgno * env->me_psize;
10263 mdb_size_t fsize = 0;
10264 if ((rc = mdb_fsize(env->me_fd, &fsize)))
10269 wsize = w3 - wsize;
10270 while (wsize > 0) {
10271 if (wsize > MAX_WRITE)
10275 DO_WRITE(rc, fd, ptr, w2, len);
10279 } else if (len > 0) {
10291 mdb_txn_abort(txn);
10296 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
10298 if (flags & MDB_CP_COMPACT)
10299 return mdb_env_copyfd1(env, fd);
10301 return mdb_env_copyfd0(env, fd);
10305 mdb_env_copyfd(MDB_env *env, HANDLE fd)
10307 return mdb_env_copyfd2(env, fd, 0);
10311 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
10315 HANDLE newfd = INVALID_HANDLE_VALUE;
10317 rc = mdb_fname_init(path, env->me_flags | MDB_NOLOCK, &fname);
10318 if (rc == MDB_SUCCESS) {
10319 rc = mdb_fopen(env, &fname, MDB_O_COPY, 0666, &newfd);
10320 mdb_fname_destroy(fname);
10322 if (rc == MDB_SUCCESS) {
10323 rc = mdb_env_copyfd2(env, newfd, flags);
10324 if (close(newfd) < 0 && rc == MDB_SUCCESS)
10331 mdb_env_copy(MDB_env *env, const char *path)
10333 return mdb_env_copy2(env, path, 0);
10337 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
10339 if (flag & ~CHANGEABLE)
10342 env->me_flags |= flag;
10344 env->me_flags &= ~flag;
10345 return MDB_SUCCESS;
10349 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
10354 *arg = env->me_flags & (CHANGEABLE|CHANGELESS);
10355 return MDB_SUCCESS;
10359 mdb_env_set_userctx(MDB_env *env, void *ctx)
10363 env->me_userctx = ctx;
10364 return MDB_SUCCESS;
10368 mdb_env_get_userctx(MDB_env *env)
10370 return env ? env->me_userctx : NULL;
10374 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
10379 env->me_assert_func = func;
10381 return MDB_SUCCESS;
10385 mdb_env_get_path(MDB_env *env, const char **arg)
10390 *arg = env->me_path;
10391 return MDB_SUCCESS;
10395 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
10401 return MDB_SUCCESS;
10404 /** Common code for #mdb_stat() and #mdb_env_stat().
10405 * @param[in] env the environment to operate in.
10406 * @param[in] db the #MDB_db record containing the stats to return.
10407 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
10408 * @return 0, this function always succeeds.
10411 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
10413 arg->ms_psize = env->me_psize;
10414 arg->ms_depth = db->md_depth;
10415 arg->ms_branch_pages = db->md_branch_pages;
10416 arg->ms_leaf_pages = db->md_leaf_pages;
10417 arg->ms_overflow_pages = db->md_overflow_pages;
10418 arg->ms_entries = db->md_entries;
10420 return MDB_SUCCESS;
10424 mdb_env_stat(MDB_env *env, MDB_stat *arg)
10428 if (env == NULL || arg == NULL)
10431 meta = mdb_env_pick_meta(env);
10433 return mdb_stat0(env, &meta->mm_dbs[MAIN_DBI], arg);
10437 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
10441 if (env == NULL || arg == NULL)
10444 meta = mdb_env_pick_meta(env);
10445 arg->me_mapaddr = meta->mm_address;
10446 arg->me_last_pgno = meta->mm_last_pg;
10447 arg->me_last_txnid = meta->mm_txnid;
10449 arg->me_mapsize = env->me_mapsize;
10450 arg->me_maxreaders = env->me_maxreaders;
10451 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : 0;
10452 return MDB_SUCCESS;
10455 /** Set the default comparison functions for a database.
10456 * Called immediately after a database is opened to set the defaults.
10457 * The user can then override them with #mdb_set_compare() or
10458 * #mdb_set_dupsort().
10459 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
10460 * @param[in] dbi A database handle returned by #mdb_dbi_open()
10463 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
10465 uint16_t f = txn->mt_dbs[dbi].md_flags;
10467 txn->mt_dbxs[dbi].md_cmp =
10468 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
10469 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
10471 txn->mt_dbxs[dbi].md_dcmp =
10472 !(f & MDB_DUPSORT) ? 0 :
10473 ((f & MDB_INTEGERDUP)
10474 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
10475 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
10478 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
10484 int rc, dbflag, exact;
10485 unsigned int unused = 0, seq;
10489 if (flags & ~VALID_FLAGS)
10491 if (txn->mt_flags & MDB_TXN_BLOCKED)
10492 return MDB_BAD_TXN;
10497 if (flags & PERSISTENT_FLAGS) {
10498 uint16_t f2 = flags & PERSISTENT_FLAGS;
10499 /* make sure flag changes get committed */
10500 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
10501 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
10502 txn->mt_flags |= MDB_TXN_DIRTY;
10505 mdb_default_cmp(txn, MAIN_DBI);
10506 return MDB_SUCCESS;
10509 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
10510 mdb_default_cmp(txn, MAIN_DBI);
10513 /* Is the DB already open? */
10514 len = strlen(name);
10515 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
10516 if (!txn->mt_dbxs[i].md_name.mv_size) {
10517 /* Remember this free slot */
10518 if (!unused) unused = i;
10521 if (len == txn->mt_dbxs[i].md_name.mv_size &&
10522 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
10524 return MDB_SUCCESS;
10528 /* If no free slot and max hit, fail */
10529 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
10530 return MDB_DBS_FULL;
10532 /* Cannot mix named databases with some mainDB flags */
10533 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
10534 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
10536 /* Find the DB info */
10537 dbflag = DB_NEW|DB_VALID|DB_USRVALID;
10540 key.mv_data = (void *)name;
10541 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
10542 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
10543 if (rc == MDB_SUCCESS) {
10544 /* make sure this is actually a DB */
10545 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
10546 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
10547 return MDB_INCOMPATIBLE;
10548 } else if (! (rc == MDB_NOTFOUND && (flags & MDB_CREATE))) {
10552 /* Done here so we cannot fail after creating a new DB */
10553 if ((namedup = strdup(name)) == NULL)
10557 /* MDB_NOTFOUND and MDB_CREATE: Create new DB */
10558 data.mv_size = sizeof(MDB_db);
10559 data.mv_data = &dummy;
10560 memset(&dummy, 0, sizeof(dummy));
10561 dummy.md_root = P_INVALID;
10562 dummy.md_flags = flags & PERSISTENT_FLAGS;
10563 WITH_CURSOR_TRACKING(mc,
10564 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA));
10565 dbflag |= DB_DIRTY;
10571 /* Got info, register DBI in this txn */
10572 unsigned int slot = unused ? unused : txn->mt_numdbs;
10573 txn->mt_dbxs[slot].md_name.mv_data = namedup;
10574 txn->mt_dbxs[slot].md_name.mv_size = len;
10575 txn->mt_dbxs[slot].md_rel = NULL;
10576 txn->mt_dbflags[slot] = dbflag;
10577 /* txn-> and env-> are the same in read txns, use
10578 * tmp variable to avoid undefined assignment
10580 seq = ++txn->mt_env->me_dbiseqs[slot];
10581 txn->mt_dbiseqs[slot] = seq;
10583 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
10585 mdb_default_cmp(txn, slot);
10595 mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
10597 if (!arg || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
10600 if (txn->mt_flags & MDB_TXN_BLOCKED)
10601 return MDB_BAD_TXN;
10603 if (txn->mt_dbflags[dbi] & DB_STALE) {
10606 /* Stale, must read the DB's root. cursor_init does it for us. */
10607 mdb_cursor_init(&mc, txn, dbi, &mx);
10609 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
10612 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
10615 if (dbi < CORE_DBS || dbi >= env->me_maxdbs)
10617 ptr = env->me_dbxs[dbi].md_name.mv_data;
10618 /* If there was no name, this was already closed */
10620 env->me_dbxs[dbi].md_name.mv_data = NULL;
10621 env->me_dbxs[dbi].md_name.mv_size = 0;
10622 env->me_dbflags[dbi] = 0;
10623 env->me_dbiseqs[dbi]++;
10628 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
10630 /* We could return the flags for the FREE_DBI too but what's the point? */
10631 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10633 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
10634 return MDB_SUCCESS;
10637 /** Add all the DB's pages to the free list.
10638 * @param[in] mc Cursor on the DB to free.
10639 * @param[in] subs non-Zero to check for sub-DBs in this DB.
10640 * @return 0 on success, non-zero on failure.
10643 mdb_drop0(MDB_cursor *mc, int subs)
10647 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
10648 if (rc == MDB_SUCCESS) {
10649 MDB_txn *txn = mc->mc_txn;
10654 /* DUPSORT sub-DBs have no ovpages/DBs. Omit scanning leaves.
10655 * This also avoids any P_LEAF2 pages, which have no nodes.
10656 * Also if the DB doesn't have sub-DBs and has no overflow
10657 * pages, omit scanning leaves.
10659 if ((mc->mc_flags & C_SUB) ||
10660 (!subs && !mc->mc_db->md_overflow_pages))
10661 mdb_cursor_pop(mc);
10663 mdb_cursor_copy(mc, &mx);
10665 /* bump refcount for mx's pages */
10666 for (i=0; i<mc->mc_snum; i++)
10667 mdb_page_get(&mx, mc->mc_pg[i]->mp_pgno, &mx.mc_pg[i], NULL);
10669 while (mc->mc_snum > 0) {
10670 MDB_page *mp = mc->mc_pg[mc->mc_top];
10671 unsigned n = NUMKEYS(mp);
10673 for (i=0; i<n; i++) {
10674 ni = NODEPTR(mp, i);
10675 if (ni->mn_flags & F_BIGDATA) {
10678 memcpy(&pg, NODEDATA(ni), sizeof(pg));
10679 rc = mdb_page_get(mc, pg, &omp, NULL);
10682 mdb_cassert(mc, IS_OVERFLOW(omp));
10683 rc = mdb_midl_append_range(&txn->mt_free_pgs,
10684 pg, omp->mp_pages);
10687 mc->mc_db->md_overflow_pages -= omp->mp_pages;
10688 if (!mc->mc_db->md_overflow_pages && !subs)
10690 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
10691 mdb_xcursor_init1(mc, ni);
10692 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
10697 if (!subs && !mc->mc_db->md_overflow_pages)
10700 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
10702 for (i=0; i<n; i++) {
10704 ni = NODEPTR(mp, i);
10707 mdb_midl_xappend(txn->mt_free_pgs, pg);
10712 mc->mc_ki[mc->mc_top] = i;
10713 rc = mdb_cursor_sibling(mc, 1);
10715 if (rc != MDB_NOTFOUND)
10717 /* no more siblings, go back to beginning
10718 * of previous level.
10721 mdb_cursor_pop(mc);
10723 for (i=1; i<mc->mc_snum; i++) {
10725 mc->mc_pg[i] = mx.mc_pg[i];
10730 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
10733 txn->mt_flags |= MDB_TXN_ERROR;
10734 /* drop refcount for mx's pages */
10735 MDB_CURSOR_UNREF(&mx, 0);
10736 } else if (rc == MDB_NOTFOUND) {
10739 mc->mc_flags &= ~C_INITIALIZED;
10743 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
10745 MDB_cursor *mc, *m2;
10748 if ((unsigned)del > 1 || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10751 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
10754 if (TXN_DBI_CHANGED(txn, dbi))
10755 return MDB_BAD_DBI;
10757 rc = mdb_cursor_open(txn, dbi, &mc);
10761 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
10762 /* Invalidate the dropped DB's cursors */
10763 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
10764 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
10768 /* Can't delete the main DB */
10769 if (del && dbi >= CORE_DBS) {
10770 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, F_SUBDATA);
10772 txn->mt_dbflags[dbi] = DB_STALE;
10773 mdb_dbi_close(txn->mt_env, dbi);
10775 txn->mt_flags |= MDB_TXN_ERROR;
10778 /* reset the DB record, mark it dirty */
10779 txn->mt_dbflags[dbi] |= DB_DIRTY;
10780 txn->mt_dbs[dbi].md_depth = 0;
10781 txn->mt_dbs[dbi].md_branch_pages = 0;
10782 txn->mt_dbs[dbi].md_leaf_pages = 0;
10783 txn->mt_dbs[dbi].md_overflow_pages = 0;
10784 txn->mt_dbs[dbi].md_entries = 0;
10785 txn->mt_dbs[dbi].md_root = P_INVALID;
10787 txn->mt_flags |= MDB_TXN_DIRTY;
10790 mdb_cursor_close(mc);
10794 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
10796 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10799 txn->mt_dbxs[dbi].md_cmp = cmp;
10800 return MDB_SUCCESS;
10803 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
10805 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10808 txn->mt_dbxs[dbi].md_dcmp = cmp;
10809 return MDB_SUCCESS;
10812 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
10814 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10817 txn->mt_dbxs[dbi].md_rel = rel;
10818 return MDB_SUCCESS;
10821 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
10823 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10826 txn->mt_dbxs[dbi].md_relctx = ctx;
10827 return MDB_SUCCESS;
10831 mdb_env_get_maxkeysize(MDB_env *env)
10833 return ENV_MAXKEY(env);
10837 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
10839 unsigned int i, rdrs;
10842 int rc = 0, first = 1;
10846 if (!env->me_txns) {
10847 return func("(no reader locks)\n", ctx);
10849 rdrs = env->me_txns->mti_numreaders;
10850 mr = env->me_txns->mti_readers;
10851 for (i=0; i<rdrs; i++) {
10852 if (mr[i].mr_pid) {
10853 txnid_t txnid = mr[i].mr_txnid;
10854 sprintf(buf, txnid == (txnid_t)-1 ?
10855 "%10d %"Z"x -\n" : "%10d %"Z"x %"Yu"\n",
10856 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
10859 rc = func(" pid thread txnid\n", ctx);
10863 rc = func(buf, ctx);
10869 rc = func("(no active readers)\n", ctx);
10874 /** Insert pid into list if not already present.
10875 * return -1 if already present.
10878 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
10880 /* binary search of pid in list */
10882 unsigned cursor = 1;
10884 unsigned n = ids[0];
10887 unsigned pivot = n >> 1;
10888 cursor = base + pivot + 1;
10889 val = pid - ids[cursor];
10894 } else if ( val > 0 ) {
10899 /* found, so it's a duplicate */
10908 for (n = ids[0]; n > cursor; n--)
10915 mdb_reader_check(MDB_env *env, int *dead)
10921 return env->me_txns ? mdb_reader_check0(env, 0, dead) : MDB_SUCCESS;
10924 /** As #mdb_reader_check(). \b rlocked is set if caller locked #me_rmutex. */
10926 mdb_reader_check0(MDB_env *env, int rlocked, int *dead)
10928 mdb_mutexref_t rmutex = rlocked ? NULL : env->me_rmutex;
10929 unsigned int i, j, rdrs;
10931 MDB_PID_T *pids, pid;
10932 int rc = MDB_SUCCESS, count = 0;
10934 rdrs = env->me_txns->mti_numreaders;
10935 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
10939 mr = env->me_txns->mti_readers;
10940 for (i=0; i<rdrs; i++) {
10941 pid = mr[i].mr_pid;
10942 if (pid && pid != env->me_pid) {
10943 if (mdb_pid_insert(pids, pid) == 0) {
10944 if (!mdb_reader_pid(env, Pidcheck, pid)) {
10945 /* Stale reader found */
10948 if ((rc = LOCK_MUTEX0(rmutex)) != 0) {
10949 if ((rc = mdb_mutex_failed(env, rmutex, rc)))
10951 rdrs = 0; /* the above checked all readers */
10953 /* Recheck, a new process may have reused pid */
10954 if (mdb_reader_pid(env, Pidcheck, pid))
10958 for (; j<rdrs; j++)
10959 if (mr[j].mr_pid == pid) {
10960 DPRINTF(("clear stale reader pid %u txn %"Yd,
10961 (unsigned) pid, mr[j].mr_txnid));
10966 UNLOCK_MUTEX(rmutex);
10977 #ifdef MDB_ROBUST_SUPPORTED
10978 /** Handle #LOCK_MUTEX0() failure.
10979 * Try to repair the lock file if the mutex owner died.
10980 * @param[in] env the environment handle
10981 * @param[in] mutex LOCK_MUTEX0() mutex
10982 * @param[in] rc LOCK_MUTEX0() error (nonzero)
10983 * @return 0 on success with the mutex locked, or an error code on failure.
10986 mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc)
10991 if (rc == MDB_OWNERDEAD) {
10992 /* We own the mutex. Clean up after dead previous owner. */
10994 rlocked = (mutex == env->me_rmutex);
10996 /* Keep mti_txnid updated, otherwise next writer can
10997 * overwrite data which latest meta page refers to.
10999 meta = mdb_env_pick_meta(env);
11000 env->me_txns->mti_txnid = meta->mm_txnid;
11001 /* env is hosed if the dead thread was ours */
11003 env->me_flags |= MDB_FATAL_ERROR;
11004 env->me_txn = NULL;
11008 DPRINTF(("%cmutex owner died, %s", (rlocked ? 'r' : 'w'),
11009 (rc ? "this process' env is hosed" : "recovering")));
11010 rc2 = mdb_reader_check0(env, rlocked, NULL);
11012 rc2 = mdb_mutex_consistent(mutex);
11013 if (rc || (rc = rc2)) {
11014 DPRINTF(("LOCK_MUTEX recovery failed, %s", mdb_strerror(rc)));
11015 UNLOCK_MUTEX(mutex);
11021 DPRINTF(("LOCK_MUTEX failed, %s", mdb_strerror(rc)));
11026 #endif /* MDB_ROBUST_SUPPORTED */
11028 #if defined(_WIN32)
11029 /** Convert \b src to new wchar_t[] string with room for \b xtra extra chars */
11031 utf8_to_utf16(const char *src, MDB_name *dst, int xtra)
11034 wchar_t *result = NULL;
11035 for (;;) { /* malloc result, then fill it in */
11036 need = MultiByteToWideChar(CP_UTF8, 0, src, -1, result, need);
11043 result = malloc(sizeof(wchar_t) * (need + xtra));
11048 dst->mn_alloced = 1;
11049 dst->mn_len = need - 1;
11050 dst->mn_val = result;
11051 return MDB_SUCCESS;
11054 #endif /* defined(_WIN32) */