2 * @brief Lightning memory-mapped database library
4 * A Btree-based database management library modeled loosely on the
5 * BerkeleyDB API, but much simplified.
8 * Copyright 2011-2016 Howard Chu, Symas Corp.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted only as authorized by the OpenLDAP
15 * A copy of this license is available in the file LICENSE in the
16 * top-level directory of the distribution or, alternatively, at
17 * <http://www.OpenLDAP.org/license.html>.
19 * This code is derived from btree.c written by Martin Hedenfalk.
21 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
23 * Permission to use, copy, modify, and distribute this software for any
24 * purpose with or without fee is hereby granted, provided that the above
25 * copyright notice and this permission notice appear in all copies.
27 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
28 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
29 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
30 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
31 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
32 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
33 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
38 #if defined(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 : 1)
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 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
813 char mtb_rmname[MNAME_LEN];
814 #elif defined(MDB_USE_SYSV_SEM)
818 /** Mutex protecting access to this table.
819 * This is the reader table lock used with LOCK_MUTEX().
821 mdb_mutex_t mtb_rmutex;
823 /** The ID of the last transaction committed to the database.
824 * This is recorded here only for convenience; the value can always
825 * be determined by reading the main database meta pages.
827 volatile txnid_t mtb_txnid;
828 /** The number of slots that have been used in the reader table.
829 * This always records the maximum count, it is not decremented
830 * when readers release their slots.
832 volatile unsigned mtb_numreaders;
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_snum || !mc->mc_pg[0] || IS_SUBP(mc->mc_pg[0]))
2011 for (i=0; i<mc->mc_snum; i++)
2012 mdb_page_unref(mc->mc_txn, mc->mc_pg[i]);
2014 mdb_page_unref(mc->mc_txn, mc->mc_ovpg);
2017 mc->mc_snum = mc->mc_top = 0;
2018 mc->mc_pg[0] = NULL;
2019 mc->mc_flags &= ~C_INITIALIZED;
2021 #define MDB_CURSOR_UNREF(mc, force) \
2022 (((force) || ((mc)->mc_flags & C_INITIALIZED)) \
2023 ? mdb_cursor_unref(mc) \
2027 #define MDB_PAGE_UNREF(txn, mp)
2028 #define MDB_CURSOR_UNREF(mc, force) ((void)0)
2029 #endif /* MDB_VL32 */
2031 /** Loosen or free a single page.
2032 * Saves single pages to a list for future reuse
2033 * in this same txn. It has been pulled from the freeDB
2034 * and already resides on the dirty list, but has been
2035 * deleted. Use these pages first before pulling again
2038 * If the page wasn't dirtied in this txn, just add it
2039 * to this txn's free list.
2042 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
2045 pgno_t pgno = mp->mp_pgno;
2046 MDB_txn *txn = mc->mc_txn;
2048 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
2049 if (txn->mt_parent) {
2050 MDB_ID2 *dl = txn->mt_u.dirty_list;
2051 /* If txn has a parent, make sure the page is in our
2055 unsigned x = mdb_mid2l_search(dl, pgno);
2056 if (x <= dl[0].mid && dl[x].mid == pgno) {
2057 if (mp != dl[x].mptr) { /* bad cursor? */
2058 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2059 txn->mt_flags |= MDB_TXN_ERROR;
2067 /* no parent txn, so it's just ours */
2072 DPRINTF(("loosen db %d page %"Yu, DDBI(mc), mp->mp_pgno));
2073 NEXT_LOOSE_PAGE(mp) = txn->mt_loose_pgs;
2074 txn->mt_loose_pgs = mp;
2075 txn->mt_loose_count++;
2076 mp->mp_flags |= P_LOOSE;
2078 int rc = mdb_midl_append(&txn->mt_free_pgs, pgno);
2086 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
2087 * @param[in] mc A cursor handle for the current operation.
2088 * @param[in] pflags Flags of the pages to update:
2089 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
2090 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
2091 * @return 0 on success, non-zero on failure.
2094 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
2096 enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
2097 MDB_txn *txn = mc->mc_txn;
2098 MDB_cursor *m3, *m0 = mc;
2103 int rc = MDB_SUCCESS, level;
2105 /* Mark pages seen by cursors: First m0, then tracked cursors */
2106 for (i = txn->mt_numdbs;; ) {
2107 if (mc->mc_flags & C_INITIALIZED) {
2108 for (m3 = mc;; m3 = &mx->mx_cursor) {
2110 for (j=0; j<m3->mc_snum; j++) {
2112 if ((mp->mp_flags & Mask) == pflags)
2113 mp->mp_flags ^= P_KEEP;
2115 mx = m3->mc_xcursor;
2116 /* Proceed to mx if it is at a sub-database */
2117 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
2119 if (! (mp && (mp->mp_flags & P_LEAF)))
2121 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
2122 if (!(leaf->mn_flags & F_SUBDATA))
2127 for (; !mc || mc == m0; mc = txn->mt_cursors[--i])
2134 /* Mark dirty root pages */
2135 for (i=0; i<txn->mt_numdbs; i++) {
2136 if (txn->mt_dbflags[i] & DB_DIRTY) {
2137 pgno_t pgno = txn->mt_dbs[i].md_root;
2138 if (pgno == P_INVALID)
2140 if ((rc = mdb_page_get(m0, pgno, &dp, &level)) != MDB_SUCCESS)
2142 if ((dp->mp_flags & Mask) == pflags && level <= 1)
2143 dp->mp_flags ^= P_KEEP;
2151 static int mdb_page_flush(MDB_txn *txn, int keep);
2153 /** Spill pages from the dirty list back to disk.
2154 * This is intended to prevent running into #MDB_TXN_FULL situations,
2155 * but note that they may still occur in a few cases:
2156 * 1) our estimate of the txn size could be too small. Currently this
2157 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
2158 * 2) child txns may run out of space if their parents dirtied a
2159 * lot of pages and never spilled them. TODO: we probably should do
2160 * a preemptive spill during #mdb_txn_begin() of a child txn, if
2161 * the parent's dirty_room is below a given threshold.
2163 * Otherwise, if not using nested txns, it is expected that apps will
2164 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
2165 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
2166 * If the txn never references them again, they can be left alone.
2167 * If the txn only reads them, they can be used without any fuss.
2168 * If the txn writes them again, they can be dirtied immediately without
2169 * going thru all of the work of #mdb_page_touch(). Such references are
2170 * handled by #mdb_page_unspill().
2172 * Also note, we never spill DB root pages, nor pages of active cursors,
2173 * because we'll need these back again soon anyway. And in nested txns,
2174 * we can't spill a page in a child txn if it was already spilled in a
2175 * parent txn. That would alter the parent txns' data even though
2176 * the child hasn't committed yet, and we'd have no way to undo it if
2177 * the child aborted.
2179 * @param[in] m0 cursor A cursor handle identifying the transaction and
2180 * database for which we are checking space.
2181 * @param[in] key For a put operation, the key being stored.
2182 * @param[in] data For a put operation, the data being stored.
2183 * @return 0 on success, non-zero on failure.
2186 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
2188 MDB_txn *txn = m0->mc_txn;
2190 MDB_ID2L dl = txn->mt_u.dirty_list;
2191 unsigned int i, j, need;
2194 if (m0->mc_flags & C_SUB)
2197 /* Estimate how much space this op will take */
2198 i = m0->mc_db->md_depth;
2199 /* Named DBs also dirty the main DB */
2200 if (m0->mc_dbi >= CORE_DBS)
2201 i += txn->mt_dbs[MAIN_DBI].md_depth;
2202 /* For puts, roughly factor in the key+data size */
2204 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
2205 i += i; /* double it for good measure */
2208 if (txn->mt_dirty_room > i)
2211 if (!txn->mt_spill_pgs) {
2212 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
2213 if (!txn->mt_spill_pgs)
2216 /* purge deleted slots */
2217 MDB_IDL sl = txn->mt_spill_pgs;
2218 unsigned int num = sl[0];
2220 for (i=1; i<=num; i++) {
2227 /* Preserve pages which may soon be dirtied again */
2228 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
2231 /* Less aggressive spill - we originally spilled the entire dirty list,
2232 * with a few exceptions for cursor pages and DB root pages. But this
2233 * turns out to be a lot of wasted effort because in a large txn many
2234 * of those pages will need to be used again. So now we spill only 1/8th
2235 * of the dirty pages. Testing revealed this to be a good tradeoff,
2236 * better than 1/2, 1/4, or 1/10.
2238 if (need < MDB_IDL_UM_MAX / 8)
2239 need = MDB_IDL_UM_MAX / 8;
2241 /* Save the page IDs of all the pages we're flushing */
2242 /* flush from the tail forward, this saves a lot of shifting later on. */
2243 for (i=dl[0].mid; i && need; i--) {
2244 MDB_ID pn = dl[i].mid << 1;
2246 if (dp->mp_flags & (P_LOOSE|P_KEEP))
2248 /* Can't spill twice, make sure it's not already in a parent's
2251 if (txn->mt_parent) {
2253 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
2254 if (tx2->mt_spill_pgs) {
2255 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
2256 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
2257 dp->mp_flags |= P_KEEP;
2265 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
2269 mdb_midl_sort(txn->mt_spill_pgs);
2271 /* Flush the spilled part of dirty list */
2272 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
2275 /* Reset any dirty pages we kept that page_flush didn't see */
2276 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
2279 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
2283 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
2285 mdb_find_oldest(MDB_txn *txn)
2288 txnid_t mr, oldest = txn->mt_txnid - 1;
2289 if (txn->mt_env->me_txns) {
2290 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
2291 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
2302 /** Add a page to the txn's dirty list */
2304 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
2307 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
2309 if (txn->mt_flags & MDB_TXN_WRITEMAP) {
2310 insert = mdb_mid2l_append;
2312 insert = mdb_mid2l_insert;
2314 mid.mid = mp->mp_pgno;
2316 rc = insert(txn->mt_u.dirty_list, &mid);
2317 mdb_tassert(txn, rc == 0);
2318 txn->mt_dirty_room--;
2321 /** Allocate page numbers and memory for writing. Maintain me_pglast,
2322 * me_pghead and mt_next_pgno. Set #MDB_TXN_ERROR on failure.
2324 * If there are free pages available from older transactions, they
2325 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
2326 * Do not modify the freedB, just merge freeDB records into me_pghead[]
2327 * and move me_pglast to say which records were consumed. Only this
2328 * function can create me_pghead and move me_pglast/mt_next_pgno.
2329 * When #MDB_DEVEL & 2, it is not affected by #mdb_freelist_save(): it
2330 * then uses the transaction's original snapshot of the freeDB.
2331 * @param[in] mc cursor A cursor handle identifying the transaction and
2332 * database for which we are allocating.
2333 * @param[in] num the number of pages to allocate.
2334 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
2335 * will always be satisfied by a single contiguous chunk of memory.
2336 * @return 0 on success, non-zero on failure.
2339 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
2341 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
2342 /* Get at most <Max_retries> more freeDB records once me_pghead
2343 * has enough pages. If not enough, use new pages from the map.
2344 * If <Paranoid> and mc is updating the freeDB, only get new
2345 * records if me_pghead is empty. Then the freelist cannot play
2346 * catch-up with itself by growing while trying to save it.
2348 enum { Paranoid = 1, Max_retries = 500 };
2350 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
2352 int rc, retry = num * 60;
2353 MDB_txn *txn = mc->mc_txn;
2354 MDB_env *env = txn->mt_env;
2355 pgno_t pgno, *mop = env->me_pghead;
2356 unsigned i, j, mop_len = mop ? mop[0] : 0, n2 = num-1;
2358 txnid_t oldest = 0, last;
2363 /* If there are any loose pages, just use them */
2364 if (num == 1 && txn->mt_loose_pgs) {
2365 np = txn->mt_loose_pgs;
2366 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
2367 txn->mt_loose_count--;
2368 DPRINTF(("db %d use loose page %"Yu, DDBI(mc), np->mp_pgno));
2375 /* If our dirty list is already full, we can't do anything */
2376 if (txn->mt_dirty_room == 0) {
2381 for (op = MDB_FIRST;; op = MDB_NEXT) {
2386 /* Seek a big enough contiguous page range. Prefer
2387 * pages at the tail, just truncating the list.
2393 if (mop[i-n2] == pgno+n2)
2400 if (op == MDB_FIRST) { /* 1st iteration */
2401 /* Prepare to fetch more and coalesce */
2402 last = env->me_pglast;
2403 oldest = env->me_pgoldest;
2404 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
2405 #if (MDB_DEVEL) & 2 /* "& 2" so MDB_DEVEL=1 won't hide bugs breaking freeDB */
2406 /* Use original snapshot. TODO: Should need less care in code
2407 * which modifies the database. Maybe we can delete some code?
2409 m2.mc_flags |= C_ORIG_RDONLY;
2410 m2.mc_db = &env->me_metas[(txn->mt_txnid-1) & 1]->mm_dbs[FREE_DBI];
2411 m2.mc_dbflag = (unsigned char *)""; /* probably unnecessary */
2415 key.mv_data = &last; /* will look up last+1 */
2416 key.mv_size = sizeof(last);
2418 if (Paranoid && mc->mc_dbi == FREE_DBI)
2421 if (Paranoid && retry < 0 && mop_len)
2425 /* Do not fetch more if the record will be too recent */
2426 if (oldest <= last) {
2428 oldest = mdb_find_oldest(txn);
2429 env->me_pgoldest = oldest;
2435 rc = mdb_cursor_get(&m2, &key, NULL, op);
2437 if (rc == MDB_NOTFOUND)
2441 last = *(txnid_t*)key.mv_data;
2442 if (oldest <= last) {
2444 oldest = mdb_find_oldest(txn);
2445 env->me_pgoldest = oldest;
2451 np = m2.mc_pg[m2.mc_top];
2452 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
2453 if ((rc = mdb_node_read(&m2, leaf, &data)) != MDB_SUCCESS)
2456 idl = (MDB_ID *) data.mv_data;
2459 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
2464 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
2466 mop = env->me_pghead;
2468 env->me_pglast = last;
2470 DPRINTF(("IDL read txn %"Yu" root %"Yu" num %u",
2471 last, txn->mt_dbs[FREE_DBI].md_root, i));
2473 DPRINTF(("IDL %"Yu, idl[j]));
2475 /* Merge in descending sorted order */
2476 mdb_midl_xmerge(mop, idl);
2480 /* Use new pages from the map when nothing suitable in the freeDB */
2482 pgno = txn->mt_next_pgno;
2483 if (pgno + num >= env->me_maxpg) {
2484 DPUTS("DB size maxed out");
2488 #if defined(_WIN32) && !defined(MDB_VL32)
2489 if (!(env->me_flags & MDB_RDONLY)) {
2491 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
2492 p = VirtualAlloc(p, env->me_psize * num, MEM_COMMIT,
2493 (env->me_flags & MDB_WRITEMAP) ? PAGE_READWRITE:
2496 DPUTS("VirtualAlloc failed");
2504 if (env->me_flags & MDB_WRITEMAP) {
2505 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
2507 if (!(np = mdb_page_malloc(txn, num))) {
2513 mop[0] = mop_len -= num;
2514 /* Move any stragglers down */
2515 for (j = i-num; j < mop_len; )
2516 mop[++j] = mop[++i];
2518 txn->mt_next_pgno = pgno + num;
2521 mdb_page_dirty(txn, np);
2527 txn->mt_flags |= MDB_TXN_ERROR;
2531 /** Copy the used portions of a non-overflow page.
2532 * @param[in] dst page to copy into
2533 * @param[in] src page to copy from
2534 * @param[in] psize size of a page
2537 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2539 enum { Align = sizeof(pgno_t) };
2540 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2542 /* If page isn't full, just copy the used portion. Adjust
2543 * alignment so memcpy may copy words instead of bytes.
2545 if ((unused &= -Align) && !IS_LEAF2(src)) {
2546 upper = (upper + PAGEBASE) & -Align;
2547 memcpy(dst, src, (lower + PAGEBASE + (Align-1)) & -Align);
2548 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2551 memcpy(dst, src, psize - unused);
2555 /** Pull a page off the txn's spill list, if present.
2556 * If a page being referenced was spilled to disk in this txn, bring
2557 * it back and make it dirty/writable again.
2558 * @param[in] txn the transaction handle.
2559 * @param[in] mp the page being referenced. It must not be dirty.
2560 * @param[out] ret the writable page, if any. ret is unchanged if
2561 * mp wasn't spilled.
2564 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2566 MDB_env *env = txn->mt_env;
2569 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2571 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2572 if (!tx2->mt_spill_pgs)
2574 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2575 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2578 if (txn->mt_dirty_room == 0)
2579 return MDB_TXN_FULL;
2580 if (IS_OVERFLOW(mp))
2584 if (env->me_flags & MDB_WRITEMAP) {
2587 np = mdb_page_malloc(txn, num);
2591 memcpy(np, mp, num * env->me_psize);
2593 mdb_page_copy(np, mp, env->me_psize);
2596 /* If in current txn, this page is no longer spilled.
2597 * If it happens to be the last page, truncate the spill list.
2598 * Otherwise mark it as deleted by setting the LSB.
2600 if (x == txn->mt_spill_pgs[0])
2601 txn->mt_spill_pgs[0]--;
2603 txn->mt_spill_pgs[x] |= 1;
2604 } /* otherwise, if belonging to a parent txn, the
2605 * page remains spilled until child commits
2608 mdb_page_dirty(txn, np);
2609 np->mp_flags |= P_DIRTY;
2617 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2618 * Set #MDB_TXN_ERROR on failure.
2619 * @param[in] mc cursor pointing to the page to be touched
2620 * @return 0 on success, non-zero on failure.
2623 mdb_page_touch(MDB_cursor *mc)
2625 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2626 MDB_txn *txn = mc->mc_txn;
2627 MDB_cursor *m2, *m3;
2631 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2632 if (txn->mt_flags & MDB_TXN_SPILLS) {
2634 rc = mdb_page_unspill(txn, mp, &np);
2640 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2641 (rc = mdb_page_alloc(mc, 1, &np)))
2644 DPRINTF(("touched db %d page %"Yu" -> %"Yu, DDBI(mc),
2645 mp->mp_pgno, pgno));
2646 mdb_cassert(mc, mp->mp_pgno != pgno);
2647 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2648 /* Update the parent page, if any, to point to the new page */
2650 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2651 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2652 SETPGNO(node, pgno);
2654 mc->mc_db->md_root = pgno;
2656 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2657 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2659 /* If txn has a parent, make sure the page is in our
2663 unsigned x = mdb_mid2l_search(dl, pgno);
2664 if (x <= dl[0].mid && dl[x].mid == pgno) {
2665 if (mp != dl[x].mptr) { /* bad cursor? */
2666 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2667 txn->mt_flags |= MDB_TXN_ERROR;
2673 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2675 np = mdb_page_malloc(txn, 1);
2680 rc = mdb_mid2l_insert(dl, &mid);
2681 mdb_cassert(mc, rc == 0);
2686 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2688 np->mp_flags |= P_DIRTY;
2691 /* Adjust cursors pointing to mp */
2692 mc->mc_pg[mc->mc_top] = np;
2693 m2 = txn->mt_cursors[mc->mc_dbi];
2694 if (mc->mc_flags & C_SUB) {
2695 for (; m2; m2=m2->mc_next) {
2696 m3 = &m2->mc_xcursor->mx_cursor;
2697 if (m3->mc_snum < mc->mc_snum) continue;
2698 if (m3->mc_pg[mc->mc_top] == mp)
2699 m3->mc_pg[mc->mc_top] = np;
2702 for (; m2; m2=m2->mc_next) {
2703 if (m2->mc_snum < mc->mc_snum) continue;
2704 if (m2 == mc) continue;
2705 if (m2->mc_pg[mc->mc_top] == mp) {
2706 m2->mc_pg[mc->mc_top] = np;
2707 if (XCURSOR_INITED(m2) && IS_LEAF(np))
2708 XCURSOR_REFRESH(m2, np, m2->mc_ki[mc->mc_top]);
2712 MDB_PAGE_UNREF(mc->mc_txn, mp);
2716 txn->mt_flags |= MDB_TXN_ERROR;
2721 mdb_env_sync0(MDB_env *env, int force, pgno_t numpgs)
2724 if (env->me_flags & MDB_RDONLY)
2726 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2727 if (env->me_flags & MDB_WRITEMAP) {
2728 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2729 ? MS_ASYNC : MS_SYNC;
2730 if (MDB_MSYNC(env->me_map, env->me_psize * numpgs, flags))
2733 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2737 #ifdef BROKEN_FDATASYNC
2738 if (env->me_flags & MDB_FSYNCONLY) {
2739 if (fsync(env->me_fd))
2743 if (MDB_FDATASYNC(env->me_fd))
2751 mdb_env_sync(MDB_env *env, int force)
2753 MDB_meta *m = mdb_env_pick_meta(env);
2754 return mdb_env_sync0(env, force, m->mm_last_pg+1);
2757 /** Back up parent txn's cursors, then grab the originals for tracking */
2759 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2761 MDB_cursor *mc, *bk;
2766 for (i = src->mt_numdbs; --i >= 0; ) {
2767 if ((mc = src->mt_cursors[i]) != NULL) {
2768 size = sizeof(MDB_cursor);
2770 size += sizeof(MDB_xcursor);
2771 for (; mc; mc = bk->mc_next) {
2777 mc->mc_db = &dst->mt_dbs[i];
2778 /* Kill pointers into src to reduce abuse: The
2779 * user may not use mc until dst ends. But we need a valid
2780 * txn pointer here for cursor fixups to keep working.
2783 mc->mc_dbflag = &dst->mt_dbflags[i];
2784 if ((mx = mc->mc_xcursor) != NULL) {
2785 *(MDB_xcursor *)(bk+1) = *mx;
2786 mx->mx_cursor.mc_txn = dst;
2788 mc->mc_next = dst->mt_cursors[i];
2789 dst->mt_cursors[i] = mc;
2796 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2797 * @param[in] txn the transaction handle.
2798 * @param[in] merge true to keep changes to parent cursors, false to revert.
2799 * @return 0 on success, non-zero on failure.
2802 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2804 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2808 for (i = txn->mt_numdbs; --i >= 0; ) {
2809 for (mc = cursors[i]; mc; mc = next) {
2811 if ((bk = mc->mc_backup) != NULL) {
2813 /* Commit changes to parent txn */
2814 mc->mc_next = bk->mc_next;
2815 mc->mc_backup = bk->mc_backup;
2816 mc->mc_txn = bk->mc_txn;
2817 mc->mc_db = bk->mc_db;
2818 mc->mc_dbflag = bk->mc_dbflag;
2819 if ((mx = mc->mc_xcursor) != NULL)
2820 mx->mx_cursor.mc_txn = bk->mc_txn;
2822 /* Abort nested txn */
2824 if ((mx = mc->mc_xcursor) != NULL)
2825 *mx = *(MDB_xcursor *)(bk+1);
2829 /* Only malloced cursors are permanently tracked. */
2836 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2842 Pidset = F_SETLK, Pidcheck = F_GETLK
2846 /** Set or check a pid lock. Set returns 0 on success.
2847 * Check returns 0 if the process is certainly dead, nonzero if it may
2848 * be alive (the lock exists or an error happened so we do not know).
2850 * On Windows Pidset is a no-op, we merely check for the existence
2851 * of the process with the given pid. On POSIX we use a single byte
2852 * lock on the lockfile, set at an offset equal to the pid.
2855 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2857 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2860 if (op == Pidcheck) {
2861 h = OpenProcess(env->me_pidquery, FALSE, pid);
2862 /* No documented "no such process" code, but other program use this: */
2864 return ErrCode() != ERROR_INVALID_PARAMETER;
2865 /* A process exists until all handles to it close. Has it exited? */
2866 ret = WaitForSingleObject(h, 0) != 0;
2873 struct flock lock_info;
2874 memset(&lock_info, 0, sizeof(lock_info));
2875 lock_info.l_type = F_WRLCK;
2876 lock_info.l_whence = SEEK_SET;
2877 lock_info.l_start = pid;
2878 lock_info.l_len = 1;
2879 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2880 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2882 } else if ((rc = ErrCode()) == EINTR) {
2890 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2891 * @param[in] txn the transaction handle to initialize
2892 * @return 0 on success, non-zero on failure.
2895 mdb_txn_renew0(MDB_txn *txn)
2897 MDB_env *env = txn->mt_env;
2898 MDB_txninfo *ti = env->me_txns;
2900 unsigned int i, nr, flags = txn->mt_flags;
2902 int rc, new_notls = 0;
2904 if ((flags &= MDB_TXN_RDONLY) != 0) {
2906 meta = mdb_env_pick_meta(env);
2907 txn->mt_txnid = meta->mm_txnid;
2908 txn->mt_u.reader = NULL;
2910 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2911 pthread_getspecific(env->me_txkey);
2913 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2914 return MDB_BAD_RSLOT;
2916 MDB_PID_T pid = env->me_pid;
2917 MDB_THR_T tid = pthread_self();
2918 mdb_mutexref_t rmutex = env->me_rmutex;
2920 if (!env->me_live_reader) {
2921 rc = mdb_reader_pid(env, Pidset, pid);
2924 env->me_live_reader = 1;
2927 if (LOCK_MUTEX(rc, env, rmutex))
2929 nr = ti->mti_numreaders;
2930 for (i=0; i<nr; i++)
2931 if (ti->mti_readers[i].mr_pid == 0)
2933 if (i == env->me_maxreaders) {
2934 UNLOCK_MUTEX(rmutex);
2935 return MDB_READERS_FULL;
2937 r = &ti->mti_readers[i];
2938 /* Claim the reader slot, carefully since other code
2939 * uses the reader table un-mutexed: First reset the
2940 * slot, next publish it in mti_numreaders. After
2941 * that, it is safe for mdb_env_close() to touch it.
2942 * When it will be closed, we can finally claim it.
2945 r->mr_txnid = (txnid_t)-1;
2948 ti->mti_numreaders = ++nr;
2949 env->me_close_readers = nr;
2951 UNLOCK_MUTEX(rmutex);
2953 new_notls = (env->me_flags & MDB_NOTLS);
2954 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2959 do /* LY: Retry on a race, ITS#7970. */
2960 r->mr_txnid = ti->mti_txnid;
2961 while(r->mr_txnid != ti->mti_txnid);
2962 txn->mt_txnid = r->mr_txnid;
2963 txn->mt_u.reader = r;
2964 meta = env->me_metas[txn->mt_txnid & 1];
2968 /* Not yet touching txn == env->me_txn0, it may be active */
2970 if (LOCK_MUTEX(rc, env, env->me_wmutex))
2972 txn->mt_txnid = ti->mti_txnid;
2973 meta = env->me_metas[txn->mt_txnid & 1];
2975 meta = mdb_env_pick_meta(env);
2976 txn->mt_txnid = meta->mm_txnid;
2980 if (txn->mt_txnid == mdb_debug_start)
2983 txn->mt_child = NULL;
2984 txn->mt_loose_pgs = NULL;
2985 txn->mt_loose_count = 0;
2986 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2987 txn->mt_u.dirty_list = env->me_dirty_list;
2988 txn->mt_u.dirty_list[0].mid = 0;
2989 txn->mt_free_pgs = env->me_free_pgs;
2990 txn->mt_free_pgs[0] = 0;
2991 txn->mt_spill_pgs = NULL;
2993 memcpy(txn->mt_dbiseqs, env->me_dbiseqs, env->me_maxdbs * sizeof(unsigned int));
2996 /* Copy the DB info and flags */
2997 memcpy(txn->mt_dbs, meta->mm_dbs, CORE_DBS * sizeof(MDB_db));
2999 /* Moved to here to avoid a data race in read TXNs */
3000 txn->mt_next_pgno = meta->mm_last_pg+1;
3002 txn->mt_last_pgno = txn->mt_next_pgno - 1;
3005 txn->mt_flags = flags;
3008 txn->mt_numdbs = env->me_numdbs;
3009 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
3010 x = env->me_dbflags[i];
3011 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
3012 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_USRVALID|DB_STALE : 0;
3014 txn->mt_dbflags[MAIN_DBI] = DB_VALID|DB_USRVALID;
3015 txn->mt_dbflags[FREE_DBI] = DB_VALID;
3017 if (env->me_flags & MDB_FATAL_ERROR) {
3018 DPUTS("environment had fatal error, must shutdown!");
3020 } else if (env->me_maxpg < txn->mt_next_pgno) {
3021 rc = MDB_MAP_RESIZED;
3025 mdb_txn_end(txn, new_notls /*0 or MDB_END_SLOT*/ | MDB_END_FAIL_BEGIN);
3030 mdb_txn_renew(MDB_txn *txn)
3034 if (!txn || !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY|MDB_TXN_FINISHED))
3037 rc = mdb_txn_renew0(txn);
3038 if (rc == MDB_SUCCESS) {
3039 DPRINTF(("renew txn %"Yu"%c %p on mdbenv %p, root page %"Yu,
3040 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
3041 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
3047 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
3051 int rc, size, tsize;
3053 flags &= MDB_TXN_BEGIN_FLAGS;
3054 flags |= env->me_flags & MDB_WRITEMAP;
3056 if (env->me_flags & MDB_RDONLY & ~flags) /* write txn in RDONLY env */
3060 /* Nested transactions: Max 1 child, write txns only, no writemap */
3061 flags |= parent->mt_flags;
3062 if (flags & (MDB_RDONLY|MDB_WRITEMAP|MDB_TXN_BLOCKED)) {
3063 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
3065 /* Child txns save MDB_pgstate and use own copy of cursors */
3066 size = env->me_maxdbs * (sizeof(MDB_db)+sizeof(MDB_cursor *)+1);
3067 size += tsize = sizeof(MDB_ntxn);
3068 } else if (flags & MDB_RDONLY) {
3069 size = env->me_maxdbs * (sizeof(MDB_db)+1);
3070 size += tsize = sizeof(MDB_txn);
3072 /* Reuse preallocated write txn. However, do not touch it until
3073 * mdb_txn_renew0() succeeds, since it currently may be active.
3078 if ((txn = calloc(1, size)) == NULL) {
3079 DPRINTF(("calloc: %s", strerror(errno)));
3084 txn->mt_rpages = malloc(MDB_TRPAGE_SIZE * sizeof(MDB_ID3));
3085 if (!txn->mt_rpages) {
3089 txn->mt_rpages[0].mid = 0;
3090 txn->mt_rpcheck = MDB_TRPAGE_SIZE/2;
3093 txn->mt_dbxs = env->me_dbxs; /* static */
3094 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
3095 txn->mt_dbflags = (unsigned char *)txn + size - env->me_maxdbs;
3096 txn->mt_flags = flags;
3101 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
3102 txn->mt_dbiseqs = parent->mt_dbiseqs;
3103 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
3104 if (!txn->mt_u.dirty_list ||
3105 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
3107 free(txn->mt_u.dirty_list);
3111 txn->mt_txnid = parent->mt_txnid;
3112 txn->mt_dirty_room = parent->mt_dirty_room;
3113 txn->mt_u.dirty_list[0].mid = 0;
3114 txn->mt_spill_pgs = NULL;
3115 txn->mt_next_pgno = parent->mt_next_pgno;
3116 parent->mt_flags |= MDB_TXN_HAS_CHILD;
3117 parent->mt_child = txn;
3118 txn->mt_parent = parent;
3119 txn->mt_numdbs = parent->mt_numdbs;
3121 txn->mt_rpages = parent->mt_rpages;
3123 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3124 /* Copy parent's mt_dbflags, but clear DB_NEW */
3125 for (i=0; i<txn->mt_numdbs; i++)
3126 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
3128 ntxn = (MDB_ntxn *)txn;
3129 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
3130 if (env->me_pghead) {
3131 size = MDB_IDL_SIZEOF(env->me_pghead);
3132 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
3134 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
3139 rc = mdb_cursor_shadow(parent, txn);
3141 mdb_txn_end(txn, MDB_END_FAIL_BEGINCHILD);
3142 } else { /* MDB_RDONLY */
3143 txn->mt_dbiseqs = env->me_dbiseqs;
3145 rc = mdb_txn_renew0(txn);
3148 if (txn != env->me_txn0) {
3150 free(txn->mt_rpages);
3155 txn->mt_flags |= flags; /* could not change txn=me_txn0 earlier */
3157 DPRINTF(("begin txn %"Yu"%c %p on mdbenv %p, root page %"Yu,
3158 txn->mt_txnid, (flags & MDB_RDONLY) ? 'r' : 'w',
3159 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
3166 mdb_txn_env(MDB_txn *txn)
3168 if(!txn) return NULL;
3173 mdb_txn_id(MDB_txn *txn)
3176 return txn->mt_txnid;
3179 /** Export or close DBI handles opened in this txn. */
3181 mdb_dbis_update(MDB_txn *txn, int keep)
3184 MDB_dbi n = txn->mt_numdbs;
3185 MDB_env *env = txn->mt_env;
3186 unsigned char *tdbflags = txn->mt_dbflags;
3188 for (i = n; --i >= CORE_DBS;) {
3189 if (tdbflags[i] & DB_NEW) {
3191 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
3193 char *ptr = env->me_dbxs[i].md_name.mv_data;
3195 env->me_dbxs[i].md_name.mv_data = NULL;
3196 env->me_dbxs[i].md_name.mv_size = 0;
3197 env->me_dbflags[i] = 0;
3198 env->me_dbiseqs[i]++;
3204 if (keep && env->me_numdbs < n)
3208 /** End a transaction, except successful commit of a nested transaction.
3209 * May be called twice for readonly txns: First reset it, then abort.
3210 * @param[in] txn the transaction handle to end
3211 * @param[in] mode why and how to end the transaction
3214 mdb_txn_end(MDB_txn *txn, unsigned mode)
3216 MDB_env *env = txn->mt_env;
3218 static const char *const names[] = MDB_END_NAMES;
3221 /* Export or close DBI handles opened in this txn */
3222 mdb_dbis_update(txn, mode & MDB_END_UPDATE);
3224 DPRINTF(("%s txn %"Yu"%c %p on mdbenv %p, root page %"Yu,
3225 names[mode & MDB_END_OPMASK],
3226 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
3227 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
3229 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3230 if (txn->mt_u.reader) {
3231 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
3232 if (!(env->me_flags & MDB_NOTLS)) {
3233 txn->mt_u.reader = NULL; /* txn does not own reader */
3234 } else if (mode & MDB_END_SLOT) {
3235 txn->mt_u.reader->mr_pid = 0;
3236 txn->mt_u.reader = NULL;
3237 } /* else txn owns the slot until it does MDB_END_SLOT */
3239 txn->mt_numdbs = 0; /* prevent further DBI activity */
3240 txn->mt_flags |= MDB_TXN_FINISHED;
3242 } else if (!F_ISSET(txn->mt_flags, MDB_TXN_FINISHED)) {
3243 pgno_t *pghead = env->me_pghead;
3245 if (!(mode & MDB_END_UPDATE)) /* !(already closed cursors) */
3246 mdb_cursors_close(txn, 0);
3247 if (!(env->me_flags & MDB_WRITEMAP)) {
3248 mdb_dlist_free(txn);
3252 txn->mt_flags = MDB_TXN_FINISHED;
3254 if (!txn->mt_parent) {
3255 mdb_midl_shrink(&txn->mt_free_pgs);
3256 env->me_free_pgs = txn->mt_free_pgs;
3258 env->me_pghead = NULL;
3262 mode = 0; /* txn == env->me_txn0, do not free() it */
3264 /* The writer mutex was locked in mdb_txn_begin. */
3266 UNLOCK_MUTEX(env->me_wmutex);
3268 txn->mt_parent->mt_child = NULL;
3269 txn->mt_parent->mt_flags &= ~MDB_TXN_HAS_CHILD;
3270 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
3271 mdb_midl_free(txn->mt_free_pgs);
3272 mdb_midl_free(txn->mt_spill_pgs);
3273 free(txn->mt_u.dirty_list);
3276 mdb_midl_free(pghead);
3279 if (!txn->mt_parent) {
3280 MDB_ID3L el = env->me_rpages, tl = txn->mt_rpages;
3281 unsigned i, x, n = tl[0].mid;
3282 pthread_mutex_lock(&env->me_rpmutex);
3283 for (i = 1; i <= n; i++) {
3284 if (tl[i].mid & (MDB_RPAGE_CHUNK-1)) {
3285 /* tmp overflow pages that we didn't share in env */
3286 munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
3288 x = mdb_mid3l_search(el, tl[i].mid);
3289 if (tl[i].mptr == el[x].mptr) {
3292 /* another tmp overflow page */
3293 munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
3297 pthread_mutex_unlock(&env->me_rpmutex);
3299 if (mode & MDB_END_FREE)
3303 if (mode & MDB_END_FREE)
3308 mdb_txn_reset(MDB_txn *txn)
3313 /* This call is only valid for read-only txns */
3314 if (!(txn->mt_flags & MDB_TXN_RDONLY))
3317 mdb_txn_end(txn, MDB_END_RESET);
3321 mdb_txn_abort(MDB_txn *txn)
3327 mdb_txn_abort(txn->mt_child);
3329 mdb_txn_end(txn, MDB_END_ABORT|MDB_END_SLOT|MDB_END_FREE);
3332 /** Save the freelist as of this transaction to the freeDB.
3333 * This changes the freelist. Keep trying until it stabilizes.
3335 * When (MDB_DEVEL) & 2, the changes do not affect #mdb_page_alloc(),
3336 * it then uses the transaction's original snapshot of the freeDB.
3339 mdb_freelist_save(MDB_txn *txn)
3341 /* env->me_pghead[] can grow and shrink during this call.
3342 * env->me_pglast and txn->mt_free_pgs[] can only grow.
3343 * Page numbers cannot disappear from txn->mt_free_pgs[].
3346 MDB_env *env = txn->mt_env;
3347 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
3348 txnid_t pglast = 0, head_id = 0;
3349 pgno_t freecnt = 0, *free_pgs, *mop;
3350 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
3352 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
3354 if (env->me_pghead) {
3355 /* Make sure first page of freeDB is touched and on freelist */
3356 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
3357 if (rc && rc != MDB_NOTFOUND)
3361 if (!env->me_pghead && txn->mt_loose_pgs) {
3362 /* Put loose page numbers in mt_free_pgs, since
3363 * we may be unable to return them to me_pghead.
3365 MDB_page *mp = txn->mt_loose_pgs;
3366 if ((rc = mdb_midl_need(&txn->mt_free_pgs, txn->mt_loose_count)) != 0)
3368 for (; mp; mp = NEXT_LOOSE_PAGE(mp))
3369 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
3370 txn->mt_loose_pgs = NULL;
3371 txn->mt_loose_count = 0;
3374 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
3375 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
3376 ? SSIZE_MAX : maxfree_1pg;
3379 /* Come back here after each Put() in case freelist changed */
3384 /* If using records from freeDB which we have not yet
3385 * deleted, delete them and any we reserved for me_pghead.
3387 while (pglast < env->me_pglast) {
3388 rc = mdb_cursor_first(&mc, &key, NULL);
3391 pglast = head_id = *(txnid_t *)key.mv_data;
3392 total_room = head_room = 0;
3393 mdb_tassert(txn, pglast <= env->me_pglast);
3394 rc = mdb_cursor_del(&mc, 0);
3399 /* Save the IDL of pages freed by this txn, to a single record */
3400 if (freecnt < txn->mt_free_pgs[0]) {
3402 /* Make sure last page of freeDB is touched and on freelist */
3403 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
3404 if (rc && rc != MDB_NOTFOUND)
3407 free_pgs = txn->mt_free_pgs;
3408 /* Write to last page of freeDB */
3409 key.mv_size = sizeof(txn->mt_txnid);
3410 key.mv_data = &txn->mt_txnid;
3412 freecnt = free_pgs[0];
3413 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
3414 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3417 /* Retry if mt_free_pgs[] grew during the Put() */
3418 free_pgs = txn->mt_free_pgs;
3419 } while (freecnt < free_pgs[0]);
3420 mdb_midl_sort(free_pgs);
3421 memcpy(data.mv_data, free_pgs, data.mv_size);
3424 unsigned int i = free_pgs[0];
3425 DPRINTF(("IDL write txn %"Yu" root %"Yu" num %u",
3426 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
3428 DPRINTF(("IDL %"Yu, free_pgs[i]));
3434 mop = env->me_pghead;
3435 mop_len = (mop ? mop[0] : 0) + txn->mt_loose_count;
3437 /* Reserve records for me_pghead[]. Split it if multi-page,
3438 * to avoid searching freeDB for a page range. Use keys in
3439 * range [1,me_pglast]: Smaller than txnid of oldest reader.
3441 if (total_room >= mop_len) {
3442 if (total_room == mop_len || --more < 0)
3444 } else if (head_room >= maxfree_1pg && head_id > 1) {
3445 /* Keep current record (overflow page), add a new one */
3449 /* (Re)write {key = head_id, IDL length = head_room} */
3450 total_room -= head_room;
3451 head_room = mop_len - total_room;
3452 if (head_room > maxfree_1pg && head_id > 1) {
3453 /* Overflow multi-page for part of me_pghead */
3454 head_room /= head_id; /* amortize page sizes */
3455 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
3456 } else if (head_room < 0) {
3457 /* Rare case, not bothering to delete this record */
3460 key.mv_size = sizeof(head_id);
3461 key.mv_data = &head_id;
3462 data.mv_size = (head_room + 1) * sizeof(pgno_t);
3463 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3466 /* IDL is initially empty, zero out at least the length */
3467 pgs = (pgno_t *)data.mv_data;
3468 j = head_room > clean_limit ? head_room : 0;
3472 total_room += head_room;
3475 /* Return loose page numbers to me_pghead, though usually none are
3476 * left at this point. The pages themselves remain in dirty_list.
3478 if (txn->mt_loose_pgs) {
3479 MDB_page *mp = txn->mt_loose_pgs;
3480 unsigned count = txn->mt_loose_count;
3482 /* Room for loose pages + temp IDL with same */
3483 if ((rc = mdb_midl_need(&env->me_pghead, 2*count+1)) != 0)
3485 mop = env->me_pghead;
3486 loose = mop + MDB_IDL_ALLOCLEN(mop) - count;
3487 for (count = 0; mp; mp = NEXT_LOOSE_PAGE(mp))
3488 loose[ ++count ] = mp->mp_pgno;
3490 mdb_midl_sort(loose);
3491 mdb_midl_xmerge(mop, loose);
3492 txn->mt_loose_pgs = NULL;
3493 txn->mt_loose_count = 0;
3497 /* Fill in the reserved me_pghead records */
3503 rc = mdb_cursor_first(&mc, &key, &data);
3504 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
3505 txnid_t id = *(txnid_t *)key.mv_data;
3506 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
3509 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
3511 if (len > mop_len) {
3513 data.mv_size = (len + 1) * sizeof(MDB_ID);
3515 data.mv_data = mop -= len;
3518 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
3520 if (rc || !(mop_len -= len))
3527 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
3528 * @param[in] txn the transaction that's being committed
3529 * @param[in] keep number of initial pages in dirty_list to keep dirty.
3530 * @return 0 on success, non-zero on failure.
3533 mdb_page_flush(MDB_txn *txn, int keep)
3535 MDB_env *env = txn->mt_env;
3536 MDB_ID2L dl = txn->mt_u.dirty_list;
3537 unsigned psize = env->me_psize, j;
3538 int i, pagecount = dl[0].mid, rc;
3542 MDB_page *dp = NULL;
3546 struct iovec iov[MDB_COMMIT_PAGES];
3547 ssize_t wsize = 0, wres;
3548 off_t wpos = 0, next_pos = 1; /* impossible pos, so pos != next_pos */
3554 if (env->me_flags & MDB_WRITEMAP) {
3555 /* Clear dirty flags */
3556 while (++i <= pagecount) {
3558 /* Don't flush this page yet */
3559 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3560 dp->mp_flags &= ~P_KEEP;
3564 dp->mp_flags &= ~P_DIRTY;
3569 /* Write the pages */
3571 if (++i <= pagecount) {
3573 /* Don't flush this page yet */
3574 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3575 dp->mp_flags &= ~P_KEEP;
3580 /* clear dirty flag */
3581 dp->mp_flags &= ~P_DIRTY;
3584 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
3589 /* Windows actually supports scatter/gather I/O, but only on
3590 * unbuffered file handles. Since we're relying on the OS page
3591 * cache for all our data, that's self-defeating. So we just
3592 * write pages one at a time. We use the ov structure to set
3593 * the write offset, to at least save the overhead of a Seek
3596 DPRINTF(("committing page %"Yu, pgno));
3597 memset(&ov, 0, sizeof(ov));
3598 ov.Offset = pos & 0xffffffff;
3599 ov.OffsetHigh = pos >> 16 >> 16;
3600 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
3602 DPRINTF(("WriteFile: %d", rc));
3606 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
3607 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
3610 /* Write previous page(s) */
3611 #ifdef MDB_USE_PWRITEV
3612 wres = pwritev(env->me_fd, iov, n, wpos);
3615 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
3618 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
3622 DPRINTF(("lseek: %s", strerror(rc)));
3625 wres = writev(env->me_fd, iov, n);
3628 if (wres != wsize) {
3633 DPRINTF(("Write error: %s", strerror(rc)));
3635 rc = EIO; /* TODO: Use which error code? */
3636 DPUTS("short write, filesystem full?");
3647 DPRINTF(("committing page %"Yu, pgno));
3648 next_pos = pos + size;
3649 iov[n].iov_len = size;
3650 iov[n].iov_base = (char *)dp;
3656 if (pgno > txn->mt_last_pgno)
3657 txn->mt_last_pgno = pgno;
3660 /* MIPS has cache coherency issues, this is a no-op everywhere else
3661 * Note: for any size >= on-chip cache size, entire on-chip cache is
3664 CACHEFLUSH(env->me_map, txn->mt_next_pgno * env->me_psize, DCACHE);
3666 for (i = keep; ++i <= pagecount; ) {
3668 /* This is a page we skipped above */
3671 dl[j].mid = dp->mp_pgno;
3674 mdb_dpage_free(env, dp);
3679 txn->mt_dirty_room += i - j;
3685 mdb_txn_commit(MDB_txn *txn)
3688 unsigned int i, end_mode;
3694 /* mdb_txn_end() mode for a commit which writes nothing */
3695 end_mode = MDB_END_EMPTY_COMMIT|MDB_END_UPDATE|MDB_END_SLOT|MDB_END_FREE;
3697 if (txn->mt_child) {
3698 rc = mdb_txn_commit(txn->mt_child);
3705 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3709 if (txn->mt_flags & (MDB_TXN_FINISHED|MDB_TXN_ERROR)) {
3710 DPUTS("txn has failed/finished, can't commit");
3712 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3717 if (txn->mt_parent) {
3718 MDB_txn *parent = txn->mt_parent;
3722 unsigned x, y, len, ps_len;
3724 /* Append our free list to parent's */
3725 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3728 mdb_midl_free(txn->mt_free_pgs);
3729 /* Failures after this must either undo the changes
3730 * to the parent or set MDB_TXN_ERROR in the parent.
3733 parent->mt_next_pgno = txn->mt_next_pgno;
3734 parent->mt_flags = txn->mt_flags;
3736 /* Merge our cursors into parent's and close them */
3737 mdb_cursors_close(txn, 1);
3739 /* Update parent's DB table. */
3740 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3741 parent->mt_numdbs = txn->mt_numdbs;
3742 parent->mt_dbflags[FREE_DBI] = txn->mt_dbflags[FREE_DBI];
3743 parent->mt_dbflags[MAIN_DBI] = txn->mt_dbflags[MAIN_DBI];
3744 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
3745 /* preserve parent's DB_NEW status */
3746 x = parent->mt_dbflags[i] & DB_NEW;
3747 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3750 dst = parent->mt_u.dirty_list;
3751 src = txn->mt_u.dirty_list;
3752 /* Remove anything in our dirty list from parent's spill list */
3753 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3755 pspill[0] = (pgno_t)-1;
3756 /* Mark our dirty pages as deleted in parent spill list */
3757 for (i=0, len=src[0].mid; ++i <= len; ) {
3758 MDB_ID pn = src[i].mid << 1;
3759 while (pn > pspill[x])
3761 if (pn == pspill[x]) {
3766 /* Squash deleted pagenums if we deleted any */
3767 for (x=y; ++x <= ps_len; )
3768 if (!(pspill[x] & 1))
3769 pspill[++y] = pspill[x];
3773 /* Remove anything in our spill list from parent's dirty list */
3774 if (txn->mt_spill_pgs && txn->mt_spill_pgs[0]) {
3775 for (i=1; i<=txn->mt_spill_pgs[0]; i++) {
3776 MDB_ID pn = txn->mt_spill_pgs[i];
3778 continue; /* deleted spillpg */
3780 y = mdb_mid2l_search(dst, pn);
3781 if (y <= dst[0].mid && dst[y].mid == pn) {
3783 while (y < dst[0].mid) {
3792 /* Find len = length of merging our dirty list with parent's */
3794 dst[0].mid = 0; /* simplify loops */
3795 if (parent->mt_parent) {
3796 len = x + src[0].mid;
3797 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3798 for (i = x; y && i; y--) {
3799 pgno_t yp = src[y].mid;
3800 while (yp < dst[i].mid)
3802 if (yp == dst[i].mid) {
3807 } else { /* Simplify the above for single-ancestor case */
3808 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3810 /* Merge our dirty list with parent's */
3812 for (i = len; y; dst[i--] = src[y--]) {
3813 pgno_t yp = src[y].mid;
3814 while (yp < dst[x].mid)
3815 dst[i--] = dst[x--];
3816 if (yp == dst[x].mid)
3817 free(dst[x--].mptr);
3819 mdb_tassert(txn, i == x);
3821 free(txn->mt_u.dirty_list);
3822 parent->mt_dirty_room = txn->mt_dirty_room;
3823 if (txn->mt_spill_pgs) {
3824 if (parent->mt_spill_pgs) {
3825 /* TODO: Prevent failure here, so parent does not fail */
3826 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3828 parent->mt_flags |= MDB_TXN_ERROR;
3829 mdb_midl_free(txn->mt_spill_pgs);
3830 mdb_midl_sort(parent->mt_spill_pgs);
3832 parent->mt_spill_pgs = txn->mt_spill_pgs;
3836 /* Append our loose page list to parent's */
3837 for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(*lp))
3839 *lp = txn->mt_loose_pgs;
3840 parent->mt_loose_count += txn->mt_loose_count;
3842 parent->mt_child = NULL;
3843 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3848 if (txn != env->me_txn) {
3849 DPUTS("attempt to commit unknown transaction");
3854 mdb_cursors_close(txn, 0);
3856 if (!txn->mt_u.dirty_list[0].mid &&
3857 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
3860 DPRINTF(("committing txn %"Yu" %p on mdbenv %p, root page %"Yu,
3861 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3863 /* Update DB root pointers */
3864 if (txn->mt_numdbs > CORE_DBS) {
3868 data.mv_size = sizeof(MDB_db);
3870 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3871 for (i = CORE_DBS; i < txn->mt_numdbs; i++) {
3872 if (txn->mt_dbflags[i] & DB_DIRTY) {
3873 if (TXN_DBI_CHANGED(txn, i)) {
3877 data.mv_data = &txn->mt_dbs[i];
3878 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data,
3886 rc = mdb_freelist_save(txn);
3890 mdb_midl_free(env->me_pghead);
3891 env->me_pghead = NULL;
3892 mdb_midl_shrink(&txn->mt_free_pgs);
3898 if ((rc = mdb_page_flush(txn, 0)))
3900 if (!F_ISSET(txn->mt_flags, MDB_TXN_NOSYNC) &&
3901 (rc = mdb_env_sync0(env, 0, txn->mt_next_pgno)))
3903 if ((rc = mdb_env_write_meta(txn)))
3905 end_mode = MDB_END_COMMITTED|MDB_END_UPDATE;
3908 mdb_txn_end(txn, end_mode);
3916 /** Read the environment parameters of a DB environment before
3917 * mapping it into memory.
3918 * @param[in] env the environment handle
3919 * @param[out] meta address of where to store the meta information
3920 * @return 0 on success, non-zero on failure.
3923 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3929 enum { Size = sizeof(pbuf) };
3931 /* We don't know the page size yet, so use a minimum value.
3932 * Read both meta pages so we can use the latest one.
3935 for (i=off=0; i<NUM_METAS; i++, off += meta->mm_psize) {
3939 memset(&ov, 0, sizeof(ov));
3941 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3942 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3945 rc = pread(env->me_fd, &pbuf, Size, off);
3948 if (rc == 0 && off == 0)
3950 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3951 DPRINTF(("read: %s", mdb_strerror(rc)));
3955 p = (MDB_page *)&pbuf;
3957 if (!F_ISSET(p->mp_flags, P_META)) {
3958 DPRINTF(("page %"Yu" not a meta page", p->mp_pgno));
3963 if (m->mm_magic != MDB_MAGIC) {
3964 DPUTS("meta has invalid magic");
3968 if (m->mm_version != MDB_DATA_VERSION) {
3969 DPRINTF(("database is version %u, expected version %u",
3970 m->mm_version, MDB_DATA_VERSION));
3971 return MDB_VERSION_MISMATCH;
3974 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3980 /** Fill in most of the zeroed #MDB_meta for an empty database environment */
3982 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
3984 meta->mm_magic = MDB_MAGIC;
3985 meta->mm_version = MDB_DATA_VERSION;
3986 meta->mm_mapsize = env->me_mapsize;
3987 meta->mm_psize = env->me_psize;
3988 meta->mm_last_pg = NUM_METAS-1;
3989 meta->mm_flags = env->me_flags & 0xffff;
3990 meta->mm_flags |= MDB_INTEGERKEY; /* this is mm_dbs[FREE_DBI].md_flags */
3991 meta->mm_dbs[FREE_DBI].md_root = P_INVALID;
3992 meta->mm_dbs[MAIN_DBI].md_root = P_INVALID;
3995 /** Write the environment parameters of a freshly created DB environment.
3996 * @param[in] env the environment handle
3997 * @param[in] meta the #MDB_meta to write
3998 * @return 0 on success, non-zero on failure.
4001 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
4009 memset(&ov, 0, sizeof(ov));
4010 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
4012 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
4015 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
4016 len = pwrite(fd, ptr, size, pos); \
4017 if (len == -1 && ErrCode() == EINTR) continue; \
4018 rc = (len >= 0); break; } while(1)
4021 DPUTS("writing new meta page");
4023 psize = env->me_psize;
4025 p = calloc(NUM_METAS, psize);
4029 p->mp_flags = P_META;
4030 *(MDB_meta *)METADATA(p) = *meta;
4032 q = (MDB_page *)((char *)p + psize);
4034 q->mp_flags = P_META;
4035 *(MDB_meta *)METADATA(q) = *meta;
4037 DO_PWRITE(rc, env->me_fd, p, psize * NUM_METAS, len, 0);
4040 else if ((unsigned) len == psize * NUM_METAS)
4048 /** Update the environment info to commit a transaction.
4049 * @param[in] txn the transaction that's being committed
4050 * @return 0 on success, non-zero on failure.
4053 mdb_env_write_meta(MDB_txn *txn)
4056 MDB_meta meta, metab, *mp;
4060 int rc, len, toggle;
4069 toggle = txn->mt_txnid & 1;
4070 DPRINTF(("writing meta page %d for root page %"Yu,
4071 toggle, txn->mt_dbs[MAIN_DBI].md_root));
4074 flags = txn->mt_flags | env->me_flags;
4075 mp = env->me_metas[toggle];
4076 mapsize = env->me_metas[toggle ^ 1]->mm_mapsize;
4077 /* Persist any increases of mapsize config */
4078 if (mapsize < env->me_mapsize)
4079 mapsize = env->me_mapsize;
4081 if (flags & MDB_WRITEMAP) {
4082 mp->mm_mapsize = mapsize;
4083 mp->mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
4084 mp->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
4085 mp->mm_last_pg = txn->mt_next_pgno - 1;
4086 #if (__GNUC__ * 100 + __GNUC_MINOR__ >= 404) && /* TODO: portability */ \
4087 !(defined(__i386__) || defined(__x86_64__))
4088 /* LY: issue a memory barrier, if not x86. ITS#7969 */
4089 __sync_synchronize();
4091 mp->mm_txnid = txn->mt_txnid;
4092 if (!(flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
4093 unsigned meta_size = env->me_psize;
4094 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
4095 ptr = (char *)mp - PAGEHDRSZ;
4096 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
4097 r2 = (ptr - env->me_map) & (env->me_os_psize - 1);
4101 if (MDB_MSYNC(ptr, meta_size, rc)) {
4108 metab.mm_txnid = mp->mm_txnid;
4109 metab.mm_last_pg = mp->mm_last_pg;
4111 meta.mm_mapsize = mapsize;
4112 meta.mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
4113 meta.mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
4114 meta.mm_last_pg = txn->mt_next_pgno - 1;
4115 meta.mm_txnid = txn->mt_txnid;
4117 off = offsetof(MDB_meta, mm_mapsize);
4118 ptr = (char *)&meta + off;
4119 len = sizeof(MDB_meta) - off;
4120 off += (char *)mp - env->me_map;
4122 /* Write to the SYNC fd unless MDB_NOSYNC/MDB_NOMETASYNC.
4123 * (me_mfd goes to the same file as me_fd, but writing to it
4124 * also syncs to disk. Avoids a separate fdatasync() call.)
4126 mfd = (flags & (MDB_NOSYNC|MDB_NOMETASYNC)) ? env->me_fd : env->me_mfd;
4129 memset(&ov, 0, sizeof(ov));
4131 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
4136 rc = pwrite(mfd, ptr, len, off);
4139 rc = rc < 0 ? ErrCode() : EIO;
4144 DPUTS("write failed, disk error?");
4145 /* On a failure, the pagecache still contains the new data.
4146 * Write some old data back, to prevent it from being used.
4147 * Use the non-SYNC fd; we know it will fail anyway.
4149 meta.mm_last_pg = metab.mm_last_pg;
4150 meta.mm_txnid = metab.mm_txnid;
4152 memset(&ov, 0, sizeof(ov));
4154 WriteFile(env->me_fd, ptr, len, NULL, &ov);
4156 r2 = pwrite(env->me_fd, ptr, len, off);
4157 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
4160 env->me_flags |= MDB_FATAL_ERROR;
4163 /* MIPS has cache coherency issues, this is a no-op everywhere else */
4164 CACHEFLUSH(env->me_map + off, len, DCACHE);
4166 /* Memory ordering issues are irrelevant; since the entire writer
4167 * is wrapped by wmutex, all of these changes will become visible
4168 * after the wmutex is unlocked. Since the DB is multi-version,
4169 * readers will get consistent data regardless of how fresh or
4170 * how stale their view of these values is.
4173 env->me_txns->mti_txnid = txn->mt_txnid;
4178 /** Check both meta pages to see which one is newer.
4179 * @param[in] env the environment handle
4180 * @return newest #MDB_meta.
4183 mdb_env_pick_meta(const MDB_env *env)
4185 MDB_meta *const *metas = env->me_metas;
4186 return metas[ metas[0]->mm_txnid < metas[1]->mm_txnid ];
4190 mdb_env_create(MDB_env **env)
4194 e = calloc(1, sizeof(MDB_env));
4198 e->me_maxreaders = DEFAULT_READERS;
4199 e->me_maxdbs = e->me_numdbs = CORE_DBS;
4200 e->me_fd = INVALID_HANDLE_VALUE;
4201 e->me_lfd = INVALID_HANDLE_VALUE;
4202 e->me_mfd = INVALID_HANDLE_VALUE;
4203 #ifdef MDB_USE_POSIX_SEM
4204 e->me_rmutex = SEM_FAILED;
4205 e->me_wmutex = SEM_FAILED;
4206 #elif defined MDB_USE_SYSV_SEM
4207 e->me_rmutex->semid = -1;
4208 e->me_wmutex->semid = -1;
4210 e->me_pid = getpid();
4211 GET_PAGESIZE(e->me_os_psize);
4212 VGMEMP_CREATE(e,0,0);
4218 /** @brief Map a result from an NTAPI call to WIN32. */
4220 mdb_nt2win32(NTSTATUS st)
4225 GetOverlappedResult(NULL, &o, &br, FALSE);
4226 return GetLastError();
4231 mdb_env_map(MDB_env *env, void *addr)
4234 unsigned int flags = env->me_flags;
4237 int access = SECTION_MAP_READ;
4241 ULONG pageprot = PAGE_READONLY, secprot, alloctype;
4243 if (flags & MDB_WRITEMAP) {
4244 access |= SECTION_MAP_WRITE;
4245 pageprot = PAGE_READWRITE;
4247 if (flags & MDB_RDONLY) {
4248 secprot = PAGE_READONLY;
4252 secprot = PAGE_READWRITE;
4253 msize = env->me_mapsize;
4254 alloctype = MEM_RESERVE;
4257 rc = NtCreateSection(&mh, access, NULL, NULL, secprot, SEC_RESERVE, env->me_fd);
4259 return mdb_nt2win32(rc);
4262 msize = NUM_METAS * env->me_psize;
4264 rc = NtMapViewOfSection(mh, GetCurrentProcess(), &map, 0, 0, NULL, &msize, ViewUnmap, alloctype, pageprot);
4271 return mdb_nt2win32(rc);
4276 env->me_map = mmap(addr, NUM_METAS * env->me_psize, PROT_READ, MAP_SHARED,
4278 if (env->me_map == MAP_FAILED) {
4283 int prot = PROT_READ;
4284 if (flags & MDB_WRITEMAP) {
4286 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
4289 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
4291 if (env->me_map == MAP_FAILED) {
4296 if (flags & MDB_NORDAHEAD) {
4297 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
4299 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
4301 #ifdef POSIX_MADV_RANDOM
4302 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
4303 #endif /* POSIX_MADV_RANDOM */
4304 #endif /* MADV_RANDOM */
4308 /* Can happen because the address argument to mmap() is just a
4309 * hint. mmap() can pick another, e.g. if the range is in use.
4310 * The MAP_FIXED flag would prevent that, but then mmap could
4311 * instead unmap existing pages to make room for the new map.
4313 if (addr && env->me_map != addr)
4314 return EBUSY; /* TODO: Make a new MDB_* error code? */
4317 p = (MDB_page *)env->me_map;
4318 env->me_metas[0] = METADATA(p);
4319 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
4325 mdb_env_set_mapsize(MDB_env *env, mdb_size_t size)
4327 /* If env is already open, caller is responsible for making
4328 * sure there are no active txns.
4338 meta = mdb_env_pick_meta(env);
4340 size = meta->mm_mapsize;
4342 /* Silently round up to minimum if the size is too small */
4343 mdb_size_t minsize = (meta->mm_last_pg + 1) * env->me_psize;
4348 /* For MDB_VL32 this bit is a noop since we dynamically remap
4349 * chunks of the DB anyway.
4351 munmap(env->me_map, env->me_mapsize);
4352 env->me_mapsize = size;
4353 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
4354 rc = mdb_env_map(env, old);
4357 #endif /* !MDB_VL32 */
4359 env->me_mapsize = size;
4361 env->me_maxpg = env->me_mapsize / env->me_psize;
4366 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
4370 env->me_maxdbs = dbs + CORE_DBS;
4375 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
4377 if (env->me_map || readers < 1)
4379 env->me_maxreaders = readers;
4384 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
4386 if (!env || !readers)
4388 *readers = env->me_maxreaders;
4393 mdb_fsize(HANDLE fd, mdb_size_t *size)
4396 LARGE_INTEGER fsize;
4398 if (!GetFileSizeEx(fd, &fsize))
4401 *size = fsize.QuadPart;
4415 typedef wchar_t mdb_nchar_t;
4416 # define MDB_NAME(str) L##str
4417 # define mdb_name_cpy wcscpy
4419 /** Character type for file names: char on Unix, wchar_t on Windows */
4420 typedef char mdb_nchar_t;
4421 # define MDB_NAME(str) str /**< #mdb_nchar_t[] string literal */
4422 # define mdb_name_cpy strcpy /**< Copy name (#mdb_nchar_t string) */
4425 /** Filename - string of #mdb_nchar_t[] */
4426 typedef struct MDB_name {
4427 int mn_len; /**< Length */
4428 int mn_alloced; /**< True if #mn_val was malloced */
4429 mdb_nchar_t *mn_val; /**< Contents */
4432 /** Filename suffixes [datafile,lockfile][without,with MDB_NOSUBDIR] */
4433 static const mdb_nchar_t *const mdb_suffixes[2][2] = {
4434 { MDB_NAME("/data.mdb"), MDB_NAME("") },
4435 { MDB_NAME("/lock.mdb"), MDB_NAME("-lock") }
4438 #define MDB_SUFFLEN 9 /**< Max string length in #mdb_suffixes[] */
4440 /** Set up filename + scratch area for filename suffix, for opening files.
4441 * It should be freed with #mdb_fname_destroy().
4442 * On Windows, paths are converted from char *UTF-8 to wchar_t *UTF-16.
4444 * @param[in] path Pathname for #mdb_env_open().
4445 * @param[in] envflags Whether a subdir and/or lockfile will be used.
4446 * @param[out] fname Resulting filename, with room for a suffix if necessary.
4449 mdb_fname_init(const char *path, unsigned envflags, MDB_name *fname)
4451 int no_suffix = F_ISSET(envflags, MDB_NOSUBDIR|MDB_NOLOCK);
4452 fname->mn_alloced = 0;
4454 return utf8_to_utf16(path, fname, no_suffix ? 0 : MDB_SUFFLEN);
4456 fname->mn_len = strlen(path);
4458 fname->mn_val = (char *) path;
4459 else if ((fname->mn_val = malloc(fname->mn_len + MDB_SUFFLEN+1)) != NULL) {
4460 fname->mn_alloced = 1;
4461 strcpy(fname->mn_val, path);
4469 /** Destroy \b fname from #mdb_fname_init() */
4470 #define mdb_fname_destroy(fname) \
4471 do { if ((fname).mn_alloced) free((fname).mn_val); } while (0)
4473 #ifdef O_CLOEXEC /* POSIX.1-2008: Set FD_CLOEXEC atomically at open() */
4474 # define MDB_CLOEXEC O_CLOEXEC
4476 # define MDB_CLOEXEC 0
4479 /** File type, access mode etc. for #mdb_fopen() */
4480 enum mdb_fopen_type {
4482 MDB_O_RDONLY, MDB_O_RDWR, MDB_O_META, MDB_O_COPY, MDB_O_LOCKS
4484 /* A comment in mdb_fopen() explains some O_* flag choices. */
4485 MDB_O_RDONLY= O_RDONLY, /**< for RDONLY me_fd */
4486 MDB_O_RDWR = O_RDWR |O_CREAT, /**< for me_fd */
4487 MDB_O_META = O_WRONLY|MDB_DSYNC |MDB_CLOEXEC, /**< for me_mfd */
4488 MDB_O_COPY = O_WRONLY|O_CREAT|O_EXCL|MDB_CLOEXEC, /**< for #mdb_env_copy() */
4489 /** Bitmask for open() flags in enum #mdb_fopen_type. The other bits
4490 * distinguish otherwise-equal MDB_O_* constants from each other.
4492 MDB_O_MASK = MDB_O_RDWR|MDB_CLOEXEC | MDB_O_RDONLY|MDB_O_META|MDB_O_COPY,
4493 MDB_O_LOCKS = MDB_O_RDWR|MDB_CLOEXEC | ((MDB_O_MASK+1) & ~MDB_O_MASK) /**< for me_lfd */
4497 /** Open an LMDB file.
4498 * @param[in] env The LMDB environment.
4499 * @param[in,out] fname Path from from #mdb_fname_init(). A suffix is
4500 * appended if necessary to create the filename, without changing mn_len.
4501 * @param[in] which Determines file type, access mode, etc.
4502 * @param[in] mode The Unix permissions for the file, if we create it.
4503 * @param[out] res Resulting file handle.
4504 * @return 0 on success, non-zero on failure.
4507 mdb_fopen(const MDB_env *env, MDB_name *fname,
4508 enum mdb_fopen_type which, mdb_mode_t mode,
4511 int rc = MDB_SUCCESS;
4514 DWORD acc, share, disp, attrs;
4519 if (fname->mn_alloced) /* modifiable copy */
4520 mdb_name_cpy(fname->mn_val + fname->mn_len,
4521 mdb_suffixes[which==MDB_O_LOCKS][F_ISSET(env->me_flags, MDB_NOSUBDIR)]);
4523 /* The directory must already exist. Usually the file need not.
4524 * MDB_O_META requires the file because we already created it using
4525 * MDB_O_RDWR. MDB_O_COPY must not overwrite an existing file.
4527 * With MDB_O_COPY we do not want the OS to cache the writes, since
4528 * the source data is already in the OS cache.
4530 * The lockfile needs FD_CLOEXEC (close file descriptor on exec*())
4531 * to avoid the flock() issues noted under Caveats in lmdb.h.
4532 * Also set it for other filehandles which the user cannot get at
4533 * and close himself, which he may need after fork(). I.e. all but
4534 * me_fd, which programs do use via mdb_env_get_fd().
4538 acc = GENERIC_READ|GENERIC_WRITE;
4539 share = FILE_SHARE_READ|FILE_SHARE_WRITE;
4541 attrs = FILE_ATTRIBUTE_NORMAL;
4543 case MDB_O_RDONLY: /* read-only datafile */
4545 disp = OPEN_EXISTING;
4547 case MDB_O_META: /* for writing metapages */
4548 acc = GENERIC_WRITE;
4549 disp = OPEN_EXISTING;
4550 attrs = FILE_ATTRIBUTE_NORMAL|FILE_FLAG_WRITE_THROUGH;
4552 case MDB_O_COPY: /* mdb_env_copy() & co */
4553 acc = GENERIC_WRITE;
4556 attrs = FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH;
4558 default: break; /* silence gcc -Wswitch (not all enum values handled) */
4560 fd = CreateFileW(fname->mn_val, acc, share, NULL, disp, attrs, NULL);
4562 fd = open(fname->mn_val, which & MDB_O_MASK, mode);
4565 if (fd == INVALID_HANDLE_VALUE)
4569 if (which != MDB_O_RDONLY && which != MDB_O_RDWR) {
4570 /* Set CLOEXEC if we could not pass it to open() */
4571 if (!MDB_CLOEXEC && (flags = fcntl(fd, F_GETFD)) != -1)
4572 (void) fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
4574 if (which == MDB_O_COPY && env->me_psize >= env->me_os_psize) {
4575 /* This may require buffer alignment. There is no portable
4576 * way to ask how much, so we require OS pagesize alignment.
4578 # ifdef F_NOCACHE /* __APPLE__ */
4579 (void) fcntl(fd, F_NOCACHE, 1);
4580 # elif defined O_DIRECT
4581 /* open(...O_DIRECT...) would break on filesystems without
4582 * O_DIRECT support (ITS#7682). Try to set it here instead.
4584 if ((flags = fcntl(fd, F_GETFL)) != -1)
4585 (void) fcntl(fd, F_SETFL, flags | O_DIRECT);
4589 #endif /* !_WIN32 */
4596 #ifdef BROKEN_FDATASYNC
4597 #include <sys/utsname.h>
4598 #include <sys/vfs.h>
4601 /** Further setup required for opening an LMDB environment
4604 mdb_env_open2(MDB_env *env)
4606 unsigned int flags = env->me_flags;
4607 int i, newenv = 0, rc;
4611 /* See if we should use QueryLimited */
4613 if ((rc & 0xff) > 5)
4614 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
4616 env->me_pidquery = PROCESS_QUERY_INFORMATION;
4619 #ifdef BROKEN_FDATASYNC
4620 /* ext3/ext4 fdatasync is broken on some older Linux kernels.
4621 * https://lkml.org/lkml/2012/9/3/83
4622 * Kernels after 3.6-rc6 are known good.
4623 * https://lkml.org/lkml/2012/9/10/556
4624 * See if the DB is on ext3/ext4, then check for new enough kernel
4625 * Kernels 2.6.32.60, 2.6.34.15, 3.2.30, and 3.5.4 are also known
4630 fstatfs(env->me_fd, &st);
4631 while (st.f_type == 0xEF53) {
4635 if (uts.release[0] < '3') {
4636 if (!strncmp(uts.release, "2.6.32.", 7)) {
4637 i = atoi(uts.release+7);
4639 break; /* 2.6.32.60 and newer is OK */
4640 } else if (!strncmp(uts.release, "2.6.34.", 7)) {
4641 i = atoi(uts.release+7);
4643 break; /* 2.6.34.15 and newer is OK */
4645 } else if (uts.release[0] == '3') {
4646 i = atoi(uts.release+2);
4648 break; /* 3.6 and newer is OK */
4650 i = atoi(uts.release+4);
4652 break; /* 3.5.4 and newer is OK */
4653 } else if (i == 2) {
4654 i = atoi(uts.release+4);
4656 break; /* 3.2.30 and newer is OK */
4658 } else { /* 4.x and newer is OK */
4661 env->me_flags |= MDB_FSYNCONLY;
4667 if ((i = mdb_env_read_header(env, &meta)) != 0) {
4670 DPUTS("new mdbenv");
4672 env->me_psize = env->me_os_psize;
4673 if (env->me_psize > MAX_PAGESIZE)
4674 env->me_psize = MAX_PAGESIZE;
4675 memset(&meta, 0, sizeof(meta));
4676 mdb_env_init_meta0(env, &meta);
4677 meta.mm_mapsize = DEFAULT_MAPSIZE;
4679 env->me_psize = meta.mm_psize;
4682 /* Was a mapsize configured? */
4683 if (!env->me_mapsize) {
4684 env->me_mapsize = meta.mm_mapsize;
4687 /* Make sure mapsize >= committed data size. Even when using
4688 * mm_mapsize, which could be broken in old files (ITS#7789).
4690 mdb_size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
4691 if (env->me_mapsize < minsize)
4692 env->me_mapsize = minsize;
4694 meta.mm_mapsize = env->me_mapsize;
4696 if (newenv && !(flags & MDB_FIXEDMAP)) {
4697 /* mdb_env_map() may grow the datafile. Write the metapages
4698 * first, so the file will be valid if initialization fails.
4699 * Except with FIXEDMAP, since we do not yet know mm_address.
4700 * We could fill in mm_address later, but then a different
4701 * program might end up doing that - one with a memory layout
4702 * and map address which does not suit the main program.
4704 rc = mdb_env_init_meta(env, &meta);
4710 /* For FIXEDMAP, make sure the file is non-empty before we attempt to map it */
4714 rc = WriteFile(env->me_fd, &dummy, 1, &len, NULL);
4722 rc = mdb_env_map(env, (flags & MDB_FIXEDMAP) ? meta.mm_address : NULL);
4727 if (flags & MDB_FIXEDMAP)
4728 meta.mm_address = env->me_map;
4729 i = mdb_env_init_meta(env, &meta);
4730 if (i != MDB_SUCCESS) {
4735 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
4736 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
4738 #if !(MDB_MAXKEYSIZE)
4739 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
4741 env->me_maxpg = env->me_mapsize / env->me_psize;
4745 MDB_meta *meta = mdb_env_pick_meta(env);
4746 MDB_db *db = &meta->mm_dbs[MAIN_DBI];
4748 DPRINTF(("opened database version %u, pagesize %u",
4749 meta->mm_version, env->me_psize));
4750 DPRINTF(("using meta page %d", (int) (meta->mm_txnid & 1)));
4751 DPRINTF(("depth: %u", db->md_depth));
4752 DPRINTF(("entries: %"Yu, db->md_entries));
4753 DPRINTF(("branch pages: %"Yu, db->md_branch_pages));
4754 DPRINTF(("leaf pages: %"Yu, db->md_leaf_pages));
4755 DPRINTF(("overflow pages: %"Yu, db->md_overflow_pages));
4756 DPRINTF(("root: %"Yu, db->md_root));
4764 /** Release a reader thread's slot in the reader lock table.
4765 * This function is called automatically when a thread exits.
4766 * @param[in] ptr This points to the slot in the reader lock table.
4769 mdb_env_reader_dest(void *ptr)
4771 MDB_reader *reader = ptr;
4774 if (reader->mr_pid == getpid()) /* catch pthread_exit() in child process */
4776 /* We omit the mutex, so do this atomically (i.e. skip mr_txnid) */
4781 /** Junk for arranging thread-specific callbacks on Windows. This is
4782 * necessarily platform and compiler-specific. Windows supports up
4783 * to 1088 keys. Let's assume nobody opens more than 64 environments
4784 * in a single process, for now. They can override this if needed.
4786 #ifndef MAX_TLS_KEYS
4787 #define MAX_TLS_KEYS 64
4789 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
4790 static int mdb_tls_nkeys;
4792 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
4796 case DLL_PROCESS_ATTACH: break;
4797 case DLL_THREAD_ATTACH: break;
4798 case DLL_THREAD_DETACH:
4799 for (i=0; i<mdb_tls_nkeys; i++) {
4800 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
4802 mdb_env_reader_dest(r);
4806 case DLL_PROCESS_DETACH: break;
4811 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4813 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4817 /* Force some symbol references.
4818 * _tls_used forces the linker to create the TLS directory if not already done
4819 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
4821 #pragma comment(linker, "/INCLUDE:_tls_used")
4822 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
4823 #pragma const_seg(".CRT$XLB")
4824 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
4825 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4828 #pragma comment(linker, "/INCLUDE:__tls_used")
4829 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
4830 #pragma data_seg(".CRT$XLB")
4831 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4833 #endif /* WIN 32/64 */
4834 #endif /* !__GNUC__ */
4837 /** Downgrade the exclusive lock on the region back to shared */
4839 mdb_env_share_locks(MDB_env *env, int *excl)
4842 MDB_meta *meta = mdb_env_pick_meta(env);
4844 env->me_txns->mti_txnid = meta->mm_txnid;
4849 /* First acquire a shared lock. The Unlock will
4850 * then release the existing exclusive lock.
4852 memset(&ov, 0, sizeof(ov));
4853 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4856 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4862 struct flock lock_info;
4863 /* The shared lock replaces the existing lock */
4864 memset((void *)&lock_info, 0, sizeof(lock_info));
4865 lock_info.l_type = F_RDLCK;
4866 lock_info.l_whence = SEEK_SET;
4867 lock_info.l_start = 0;
4868 lock_info.l_len = 1;
4869 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4870 (rc = ErrCode()) == EINTR) ;
4871 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
4878 /** Try to get exclusive lock, otherwise shared.
4879 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
4882 mdb_env_excl_lock(MDB_env *env, int *excl)
4886 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
4890 memset(&ov, 0, sizeof(ov));
4891 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4898 struct flock lock_info;
4899 memset((void *)&lock_info, 0, sizeof(lock_info));
4900 lock_info.l_type = F_WRLCK;
4901 lock_info.l_whence = SEEK_SET;
4902 lock_info.l_start = 0;
4903 lock_info.l_len = 1;
4904 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4905 (rc = ErrCode()) == EINTR) ;
4909 # ifndef MDB_USE_POSIX_MUTEX
4910 if (*excl < 0) /* always true when MDB_USE_POSIX_MUTEX */
4913 lock_info.l_type = F_RDLCK;
4914 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
4915 (rc = ErrCode()) == EINTR) ;
4925 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
4927 * @(#) $Revision: 5.1 $
4928 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
4929 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
4931 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
4935 * Please do not copyright this code. This code is in the public domain.
4937 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
4938 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
4939 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
4940 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
4941 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4942 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4943 * PERFORMANCE OF THIS SOFTWARE.
4946 * chongo <Landon Curt Noll> /\oo/\
4947 * http://www.isthe.com/chongo/
4949 * Share and Enjoy! :-)
4952 typedef unsigned long long mdb_hash_t;
4953 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
4955 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
4956 * @param[in] val value to hash
4957 * @param[in] hval initial value for hash
4958 * @return 64 bit hash
4960 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
4961 * hval arg on the first call.
4964 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
4966 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
4967 unsigned char *end = s + val->mv_size;
4969 * FNV-1a hash each octet of the string
4972 /* xor the bottom with the current octet */
4973 hval ^= (mdb_hash_t)*s++;
4975 /* multiply by the 64 bit FNV magic prime mod 2^64 */
4976 hval += (hval << 1) + (hval << 4) + (hval << 5) +
4977 (hval << 7) + (hval << 8) + (hval << 40);
4979 /* return our new hash value */
4983 /** Hash the string and output the encoded hash.
4984 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
4985 * very short name limits. We don't care about the encoding being reversible,
4986 * we just want to preserve as many bits of the input as possible in a
4987 * small printable string.
4988 * @param[in] str string to hash
4989 * @param[out] encbuf an array of 11 chars to hold the hash
4991 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
4994 mdb_pack85(unsigned long l, char *out)
4998 for (i=0; i<5; i++) {
4999 *out++ = mdb_a85[l % 85];
5005 mdb_hash_enc(MDB_val *val, char *encbuf)
5007 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
5009 mdb_pack85(h, encbuf);
5010 mdb_pack85(h>>32, encbuf+5);
5015 /** Open and/or initialize the lock region for the environment.
5016 * @param[in] env The LMDB environment.
5017 * @param[in] fname Filename + scratch area, from #mdb_fname_init().
5018 * @param[in] mode The Unix permissions for the file, if we create it.
5019 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
5020 * @return 0 on success, non-zero on failure.
5023 mdb_env_setup_locks(MDB_env *env, MDB_name *fname, int mode, int *excl)
5026 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
5028 # define MDB_ERRCODE_ROFS EROFS
5030 #ifdef MDB_USE_SYSV_SEM
5037 rc = mdb_fopen(env, fname, MDB_O_LOCKS, mode, &env->me_lfd);
5039 /* Omit lockfile if read-only env on read-only filesystem */
5040 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
5046 if (!(env->me_flags & MDB_NOTLS)) {
5047 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
5050 env->me_flags |= MDB_ENV_TXKEY;
5052 /* Windows TLS callbacks need help finding their TLS info. */
5053 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
5057 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
5061 /* Try to get exclusive lock. If we succeed, then
5062 * nobody is using the lock region and we should initialize it.
5064 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
5067 size = GetFileSize(env->me_lfd, NULL);
5069 size = lseek(env->me_lfd, 0, SEEK_END);
5070 if (size == -1) goto fail_errno;
5072 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
5073 if (size < rsize && *excl > 0) {
5075 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
5076 || !SetEndOfFile(env->me_lfd))
5079 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
5083 size = rsize - sizeof(MDB_txninfo);
5084 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
5089 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
5091 if (!mh) goto fail_errno;
5092 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
5094 if (!env->me_txns) goto fail_errno;
5096 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
5098 if (m == MAP_FAILED) goto fail_errno;
5104 BY_HANDLE_FILE_INFORMATION stbuf;
5113 if (!mdb_sec_inited) {
5114 InitializeSecurityDescriptor(&mdb_null_sd,
5115 SECURITY_DESCRIPTOR_REVISION);
5116 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
5117 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
5118 mdb_all_sa.bInheritHandle = FALSE;
5119 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
5122 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
5123 idbuf.volume = stbuf.dwVolumeSerialNumber;
5124 idbuf.nhigh = stbuf.nFileIndexHigh;
5125 idbuf.nlow = stbuf.nFileIndexLow;
5126 val.mv_data = &idbuf;
5127 val.mv_size = sizeof(idbuf);
5128 mdb_hash_enc(&val, encbuf);
5129 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
5130 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
5131 env->me_rmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
5132 if (!env->me_rmutex) goto fail_errno;
5133 env->me_wmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
5134 if (!env->me_wmutex) goto fail_errno;
5135 #elif defined(MDB_USE_POSIX_SEM)
5144 #if defined(__NetBSD__)
5145 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
5147 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
5148 idbuf.dev = stbuf.st_dev;
5149 idbuf.ino = stbuf.st_ino;
5150 val.mv_data = &idbuf;
5151 val.mv_size = sizeof(idbuf);
5152 mdb_hash_enc(&val, encbuf);
5153 #ifdef MDB_SHORT_SEMNAMES
5154 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
5156 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
5157 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
5158 /* Clean up after a previous run, if needed: Try to
5159 * remove both semaphores before doing anything else.
5161 sem_unlink(env->me_txns->mti_rmname);
5162 sem_unlink(env->me_txns->mti_wmname);
5163 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
5164 O_CREAT|O_EXCL, mode, 1);
5165 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
5166 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
5167 O_CREAT|O_EXCL, mode, 1);
5168 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
5169 #elif defined(MDB_USE_SYSV_SEM)
5170 unsigned short vals[2] = {1, 1};
5171 key_t key = ftok(fname->mn_val, 'M'); /* fname is lockfile path now */
5174 semid = semget(key, 2, (mode & 0777) | IPC_CREAT);
5178 if (semctl(semid, 0, SETALL, semu) < 0)
5180 env->me_txns->mti_semid = semid;
5181 env->me_txns->mti_rlocked = 0;
5182 env->me_txns->mti_wlocked = 0;
5183 #else /* MDB_USE_POSIX_MUTEX: */
5184 pthread_mutexattr_t mattr;
5186 /* Solaris needs this before initing a robust mutex. Otherwise
5187 * it may skip the init and return EBUSY "seems someone already
5188 * inited" or EINVAL "it was inited differently".
5190 memset(env->me_txns->mti_rmutex, 0, sizeof(*env->me_txns->mti_rmutex));
5191 memset(env->me_txns->mti_wmutex, 0, sizeof(*env->me_txns->mti_wmutex));
5193 if ((rc = pthread_mutexattr_init(&mattr)) != 0)
5195 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
5196 #ifdef MDB_ROBUST_SUPPORTED
5197 if (!rc) rc = pthread_mutexattr_setrobust(&mattr, PTHREAD_MUTEX_ROBUST);
5199 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_rmutex, &mattr);
5200 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_wmutex, &mattr);
5201 pthread_mutexattr_destroy(&mattr);
5204 #endif /* _WIN32 || ... */
5206 env->me_txns->mti_magic = MDB_MAGIC;
5207 env->me_txns->mti_format = MDB_LOCK_FORMAT;
5208 env->me_txns->mti_txnid = 0;
5209 env->me_txns->mti_numreaders = 0;
5212 #ifdef MDB_USE_SYSV_SEM
5213 struct semid_ds buf;
5215 if (env->me_txns->mti_magic != MDB_MAGIC) {
5216 DPUTS("lock region has invalid magic");
5220 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
5221 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
5222 env->me_txns->mti_format, MDB_LOCK_FORMAT));
5223 rc = MDB_VERSION_MISMATCH;
5227 if (rc && rc != EACCES && rc != EAGAIN) {
5231 env->me_rmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
5232 if (!env->me_rmutex) goto fail_errno;
5233 env->me_wmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
5234 if (!env->me_wmutex) goto fail_errno;
5235 #elif defined(MDB_USE_POSIX_SEM)
5236 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
5237 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
5238 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
5239 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
5240 #elif defined(MDB_USE_SYSV_SEM)
5241 semid = env->me_txns->mti_semid;
5243 /* check for read access */
5244 if (semctl(semid, 0, IPC_STAT, semu) < 0)
5246 /* check for write access */
5247 if (semctl(semid, 0, IPC_SET, semu) < 0)
5251 #ifdef MDB_USE_SYSV_SEM
5252 env->me_rmutex->semid = semid;
5253 env->me_wmutex->semid = semid;
5254 env->me_rmutex->semnum = 0;
5255 env->me_wmutex->semnum = 1;
5256 env->me_rmutex->locked = &env->me_txns->mti_rlocked;
5257 env->me_wmutex->locked = &env->me_txns->mti_wlocked;
5268 /** Only a subset of the @ref mdb_env flags can be changed
5269 * at runtime. Changing other flags requires closing the
5270 * environment and re-opening it with the new flags.
5272 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
5273 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY| \
5274 MDB_WRITEMAP|MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
5276 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
5277 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
5281 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
5286 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
5290 if (flags & MDB_WRITEMAP) {
5291 /* silently ignore WRITEMAP in 32 bit mode */
5292 flags ^= MDB_WRITEMAP;
5294 if (flags & MDB_FIXEDMAP) {
5295 /* cannot support FIXEDMAP */
5299 flags |= env->me_flags;
5301 rc = mdb_fname_init(path, flags, &fname);
5307 env->me_rpmutex = CreateMutex(NULL, FALSE, NULL);
5308 if (!env->me_rpmutex) {
5313 rc = pthread_mutex_init(&env->me_rpmutex, NULL);
5318 flags |= MDB_ENV_ACTIVE; /* tell mdb_env_close0() to clean up */
5320 if (flags & MDB_RDONLY) {
5321 /* silently ignore WRITEMAP when we're only getting read access */
5322 flags &= ~MDB_WRITEMAP;
5324 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
5325 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
5329 env->me_flags = flags;
5335 env->me_rpages = malloc(MDB_ERPAGE_SIZE * sizeof(MDB_ID3));
5336 if (!env->me_rpages) {
5340 env->me_rpages[0].mid = 0;
5341 env->me_rpcheck = MDB_ERPAGE_SIZE/2;
5345 env->me_path = strdup(path);
5346 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
5347 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
5348 env->me_dbiseqs = calloc(env->me_maxdbs, sizeof(unsigned int));
5349 if (!(env->me_dbxs && env->me_path && env->me_dbflags && env->me_dbiseqs)) {
5353 env->me_dbxs[FREE_DBI].md_cmp = mdb_cmp_long; /* aligned MDB_INTEGERKEY */
5355 /* For RDONLY, get lockfile after we know datafile exists */
5356 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
5357 rc = mdb_env_setup_locks(env, &fname, mode, &excl);
5362 rc = mdb_fopen(env, &fname,
5363 (flags & MDB_RDONLY) ? MDB_O_RDONLY : MDB_O_RDWR,
5368 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
5369 rc = mdb_env_setup_locks(env, &fname, mode, &excl);
5374 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
5375 if (!(flags & (MDB_RDONLY|MDB_WRITEMAP))) {
5376 /* Synchronous fd for meta writes. Needed even with
5377 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
5379 rc = mdb_fopen(env, &fname, MDB_O_META, mode, &env->me_mfd);
5383 DPRINTF(("opened dbenv %p", (void *) env));
5385 rc = mdb_env_share_locks(env, &excl);
5389 if (!(flags & MDB_RDONLY)) {
5391 int tsize = sizeof(MDB_txn), size = tsize + env->me_maxdbs *
5392 (sizeof(MDB_db)+sizeof(MDB_cursor *)+sizeof(unsigned int)+1);
5393 if ((env->me_pbuf = calloc(1, env->me_psize)) &&
5394 (txn = calloc(1, size)))
5396 txn->mt_dbs = (MDB_db *)((char *)txn + tsize);
5397 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
5398 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
5399 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
5402 txn->mt_rpages = malloc(MDB_TRPAGE_SIZE * sizeof(MDB_ID3));
5403 if (!txn->mt_rpages) {
5408 txn->mt_rpages[0].mid = 0;
5409 txn->mt_rpcheck = MDB_TRPAGE_SIZE/2;
5411 txn->mt_dbxs = env->me_dbxs;
5412 txn->mt_flags = MDB_TXN_FINISHED;
5422 mdb_env_close0(env, excl);
5424 mdb_fname_destroy(fname);
5428 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
5430 mdb_env_close0(MDB_env *env, int excl)
5434 if (!(env->me_flags & MDB_ENV_ACTIVE))
5437 /* Doing this here since me_dbxs may not exist during mdb_env_close */
5439 for (i = env->me_maxdbs; --i >= CORE_DBS; )
5440 free(env->me_dbxs[i].md_name.mv_data);
5445 free(env->me_dbiseqs);
5446 free(env->me_dbflags);
5448 free(env->me_dirty_list);
5450 if (env->me_txn0 && env->me_txn0->mt_rpages)
5451 free(env->me_txn0->mt_rpages);
5452 if (env->me_rpages) {
5453 MDB_ID3L el = env->me_rpages;
5455 for (x=1; x<=el[0].mid; x++)
5456 munmap(el[x].mptr, el[x].mcnt * env->me_psize);
5461 mdb_midl_free(env->me_free_pgs);
5463 if (env->me_flags & MDB_ENV_TXKEY) {
5464 pthread_key_delete(env->me_txkey);
5466 /* Delete our key from the global list */
5467 for (i=0; i<mdb_tls_nkeys; i++)
5468 if (mdb_tls_keys[i] == env->me_txkey) {
5469 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
5478 munmap(env->me_map, NUM_METAS*env->me_psize);
5480 munmap(env->me_map, env->me_mapsize);
5483 if (env->me_mfd != INVALID_HANDLE_VALUE)
5484 (void) close(env->me_mfd);
5485 if (env->me_fd != INVALID_HANDLE_VALUE)
5486 (void) close(env->me_fd);
5488 MDB_PID_T pid = env->me_pid;
5489 /* Clearing readers is done in this function because
5490 * me_txkey with its destructor must be disabled first.
5492 * We skip the the reader mutex, so we touch only
5493 * data owned by this process (me_close_readers and
5494 * our readers), and clear each reader atomically.
5496 for (i = env->me_close_readers; --i >= 0; )
5497 if (env->me_txns->mti_readers[i].mr_pid == pid)
5498 env->me_txns->mti_readers[i].mr_pid = 0;
5500 if (env->me_rmutex) {
5501 CloseHandle(env->me_rmutex);
5502 if (env->me_wmutex) CloseHandle(env->me_wmutex);
5504 /* Windows automatically destroys the mutexes when
5505 * the last handle closes.
5507 #elif defined(MDB_USE_POSIX_SEM)
5508 if (env->me_rmutex != SEM_FAILED) {
5509 sem_close(env->me_rmutex);
5510 if (env->me_wmutex != SEM_FAILED)
5511 sem_close(env->me_wmutex);
5512 /* If we have the filelock: If we are the
5513 * only remaining user, clean up semaphores.
5516 mdb_env_excl_lock(env, &excl);
5518 sem_unlink(env->me_txns->mti_rmname);
5519 sem_unlink(env->me_txns->mti_wmname);
5522 #elif defined(MDB_USE_SYSV_SEM)
5523 if (env->me_rmutex->semid != -1) {
5524 /* If we have the filelock: If we are the
5525 * only remaining user, clean up semaphores.
5528 mdb_env_excl_lock(env, &excl);
5530 semctl(env->me_rmutex->semid, 0, IPC_RMID);
5533 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
5535 if (env->me_lfd != INVALID_HANDLE_VALUE) {
5538 /* Unlock the lockfile. Windows would have unlocked it
5539 * after closing anyway, but not necessarily at once.
5541 UnlockFile(env->me_lfd, 0, 0, 1, 0);
5544 (void) close(env->me_lfd);
5548 if (env->me_fmh) CloseHandle(env->me_fmh);
5549 if (env->me_rpmutex) CloseHandle(env->me_rpmutex);
5551 pthread_mutex_destroy(&env->me_rpmutex);
5555 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
5559 mdb_env_close(MDB_env *env)
5566 VGMEMP_DESTROY(env);
5567 while ((dp = env->me_dpages) != NULL) {
5568 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
5569 env->me_dpages = dp->mp_next;
5573 mdb_env_close0(env, 0);
5577 /** Compare two items pointing at aligned #mdb_size_t's */
5579 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
5581 return (*(mdb_size_t *)a->mv_data < *(mdb_size_t *)b->mv_data) ? -1 :
5582 *(mdb_size_t *)a->mv_data > *(mdb_size_t *)b->mv_data;
5585 /** Compare two items pointing at aligned unsigned int's.
5587 * This is also set as #MDB_INTEGERDUP|#MDB_DUPFIXED's #MDB_dbx.%md_dcmp,
5588 * but #mdb_cmp_clong() is called instead if the data type is #mdb_size_t.
5591 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
5593 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
5594 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
5597 /** Compare two items pointing at unsigned ints of unknown alignment.
5598 * Nodes and keys are guaranteed to be 2-byte aligned.
5601 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
5603 #if BYTE_ORDER == LITTLE_ENDIAN
5604 unsigned short *u, *c;
5607 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5608 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
5611 } while(!x && u > (unsigned short *)a->mv_data);
5614 unsigned short *u, *c, *end;
5617 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5618 u = (unsigned short *)a->mv_data;
5619 c = (unsigned short *)b->mv_data;
5622 } while(!x && u < end);
5627 /** Compare two items lexically */
5629 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
5636 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5642 diff = memcmp(a->mv_data, b->mv_data, len);
5643 return diff ? diff : len_diff<0 ? -1 : len_diff;
5646 /** Compare two items in reverse byte order */
5648 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
5650 const unsigned char *p1, *p2, *p1_lim;
5654 p1_lim = (const unsigned char *)a->mv_data;
5655 p1 = (const unsigned char *)a->mv_data + a->mv_size;
5656 p2 = (const unsigned char *)b->mv_data + b->mv_size;
5658 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5664 while (p1 > p1_lim) {
5665 diff = *--p1 - *--p2;
5669 return len_diff<0 ? -1 : len_diff;
5672 /** Search for key within a page, using binary search.
5673 * Returns the smallest entry larger or equal to the key.
5674 * If exactp is non-null, stores whether the found entry was an exact match
5675 * in *exactp (1 or 0).
5676 * Updates the cursor index with the index of the found entry.
5677 * If no entry larger or equal to the key is found, returns NULL.
5680 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
5682 unsigned int i = 0, nkeys;
5685 MDB_page *mp = mc->mc_pg[mc->mc_top];
5686 MDB_node *node = NULL;
5691 nkeys = NUMKEYS(mp);
5693 DPRINTF(("searching %u keys in %s %spage %"Yu,
5694 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
5697 low = IS_LEAF(mp) ? 0 : 1;
5699 cmp = mc->mc_dbx->md_cmp;
5701 /* Branch pages have no data, so if using integer keys,
5702 * alignment is guaranteed. Use faster mdb_cmp_int.
5704 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
5705 if (NODEPTR(mp, 1)->mn_ksize == sizeof(mdb_size_t))
5712 nodekey.mv_size = mc->mc_db->md_pad;
5713 node = NODEPTR(mp, 0); /* fake */
5714 while (low <= high) {
5715 i = (low + high) >> 1;
5716 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
5717 rc = cmp(key, &nodekey);
5718 DPRINTF(("found leaf index %u [%s], rc = %i",
5719 i, DKEY(&nodekey), rc));
5728 while (low <= high) {
5729 i = (low + high) >> 1;
5731 node = NODEPTR(mp, i);
5732 nodekey.mv_size = NODEKSZ(node);
5733 nodekey.mv_data = NODEKEY(node);
5735 rc = cmp(key, &nodekey);
5738 DPRINTF(("found leaf index %u [%s], rc = %i",
5739 i, DKEY(&nodekey), rc));
5741 DPRINTF(("found branch index %u [%s -> %"Yu"], rc = %i",
5742 i, DKEY(&nodekey), NODEPGNO(node), rc));
5753 if (rc > 0) { /* Found entry is less than the key. */
5754 i++; /* Skip to get the smallest entry larger than key. */
5756 node = NODEPTR(mp, i);
5759 *exactp = (rc == 0 && nkeys > 0);
5760 /* store the key index */
5761 mc->mc_ki[mc->mc_top] = i;
5763 /* There is no entry larger or equal to the key. */
5766 /* nodeptr is fake for LEAF2 */
5772 mdb_cursor_adjust(MDB_cursor *mc, func)
5776 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5777 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
5784 /** Pop a page off the top of the cursor's stack. */
5786 mdb_cursor_pop(MDB_cursor *mc)
5789 DPRINTF(("popping page %"Yu" off db %d cursor %p",
5790 mc->mc_pg[mc->mc_top]->mp_pgno, DDBI(mc), (void *) mc));
5796 mc->mc_flags &= ~C_INITIALIZED;
5801 /** Push a page onto the top of the cursor's stack.
5802 * Set #MDB_TXN_ERROR on failure.
5805 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
5807 DPRINTF(("pushing page %"Yu" on db %d cursor %p", mp->mp_pgno,
5808 DDBI(mc), (void *) mc));
5810 if (mc->mc_snum >= CURSOR_STACK) {
5811 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5812 return MDB_CURSOR_FULL;
5815 mc->mc_top = mc->mc_snum++;
5816 mc->mc_pg[mc->mc_top] = mp;
5817 mc->mc_ki[mc->mc_top] = 0;
5823 /** Map a read-only page.
5824 * There are two levels of tracking in use, a per-txn list and a per-env list.
5825 * ref'ing and unref'ing the per-txn list is faster since it requires no
5826 * locking. Pages are cached in the per-env list for global reuse, and a lock
5827 * is required. Pages are not immediately unmapped when their refcnt goes to
5828 * zero; they hang around in case they will be reused again soon.
5830 * When the per-txn list gets full, all pages with refcnt=0 are purged from the
5831 * list and their refcnts in the per-env list are decremented.
5833 * When the per-env list gets full, all pages with refcnt=0 are purged from the
5834 * list and their pages are unmapped.
5836 * @note "full" means the list has reached its respective rpcheck threshold.
5837 * This threshold slowly raises if no pages could be purged on a given check,
5838 * and returns to its original value when enough pages were purged.
5840 * If purging doesn't free any slots, filling the per-txn list will return
5841 * MDB_TXN_FULL, and filling the per-env list returns MDB_MAP_FULL.
5843 * Reference tracking in a txn is imperfect, pages can linger with non-zero
5844 * refcnt even without active references. It was deemed to be too invasive
5845 * to add unrefs in every required location. However, all pages are unref'd
5846 * at the end of the transaction. This guarantees that no stale references
5847 * linger in the per-env list.
5849 * Usually we map chunks of 16 pages at a time, but if an overflow page begins
5850 * at the tail of the chunk we extend the chunk to include the entire overflow
5851 * page. Unfortunately, pages can be turned into overflow pages after their
5852 * chunk was already mapped. In that case we must remap the chunk if the
5853 * overflow page is referenced. If the chunk's refcnt is 0 we can just remap
5854 * it, otherwise we temporarily map a new chunk just for the overflow page.
5856 * @note this chunk handling means we cannot guarantee that a data item
5857 * returned from the DB will stay alive for the duration of the transaction:
5858 * We unref pages as soon as a cursor moves away from the page
5859 * A subsequent op may cause a purge, which may unmap any unref'd chunks
5860 * The caller must copy the data if it must be used later in the same txn.
5862 * Also - our reference counting revolves around cursors, but overflow pages
5863 * aren't pointed to by a cursor's page stack. We have to remember them
5864 * explicitly, in the added mc_ovpg field. A single cursor can only hold a
5865 * reference to one overflow page at a time.
5867 * @param[in] txn the transaction for this access.
5868 * @param[in] pgno the page number for the page to retrieve.
5869 * @param[out] ret address of a pointer where the page's address will be stored.
5870 * @return 0 on success, non-zero on failure.
5873 mdb_rpage_get(MDB_txn *txn, pgno_t pg0, MDB_page **ret)
5875 MDB_env *env = txn->mt_env;
5877 MDB_ID3L tl = txn->mt_rpages;
5878 MDB_ID3L el = env->me_rpages;
5882 int rc, retries = 1;
5886 #define SET_OFF(off,val) off.QuadPart = val
5887 #define MAP(rc,env,addr,len,off) \
5889 rc = NtMapViewOfSection(env->me_fmh, GetCurrentProcess(), &addr, 0, \
5890 len, &off, &len, ViewUnmap, (env->me_flags & MDB_RDONLY) ? 0 : MEM_RESERVE, PAGE_READONLY); \
5891 if (rc) rc = mdb_nt2win32(rc)
5895 #define SET_OFF(off,val) off = val
5896 #define MAP(rc,env,addr,len,off) \
5897 addr = mmap(NULL, len, PROT_READ, MAP_SHARED, env->me_fd, off); \
5898 rc = (addr == MAP_FAILED) ? errno : 0
5901 /* remember the offset of the actual page number, so we can
5902 * return the correct pointer at the end.
5904 rem = pg0 & (MDB_RPAGE_CHUNK-1);
5908 x = mdb_mid3l_search(tl, pgno);
5909 if (x <= tl[0].mid && tl[x].mid == pgno) {
5910 if (x != tl[0].mid && tl[x+1].mid == pg0)
5912 /* check for overflow size */
5913 p = (MDB_page *)((char *)tl[x].mptr + rem * env->me_psize);
5914 if (IS_OVERFLOW(p) && p->mp_pages + rem > tl[x].mcnt) {
5915 id3.mcnt = p->mp_pages + rem;
5916 len = id3.mcnt * env->me_psize;
5917 SET_OFF(off, pgno * env->me_psize);
5918 MAP(rc, env, id3.mptr, len, off);
5921 /* check for local-only page */
5923 mdb_tassert(txn, tl[x].mid != pg0);
5924 /* hope there's room to insert this locally.
5925 * setting mid here tells later code to just insert
5926 * this id3 instead of searching for a match.
5931 /* ignore the mapping we got from env, use new one */
5932 tl[x].mptr = id3.mptr;
5933 tl[x].mcnt = id3.mcnt;
5934 /* if no active ref, see if we can replace in env */
5937 pthread_mutex_lock(&env->me_rpmutex);
5938 i = mdb_mid3l_search(el, tl[x].mid);
5939 if (el[i].mref == 1) {
5940 /* just us, replace it */
5941 munmap(el[i].mptr, el[i].mcnt * env->me_psize);
5942 el[i].mptr = tl[x].mptr;
5943 el[i].mcnt = tl[x].mcnt;
5945 /* there are others, remove ourself */
5948 pthread_mutex_unlock(&env->me_rpmutex);
5952 id3.mptr = tl[x].mptr;
5953 id3.mcnt = tl[x].mcnt;
5959 if (tl[0].mid >= MDB_TRPAGE_MAX - txn->mt_rpcheck) {
5961 /* purge unref'd pages from our list and unref in env */
5962 pthread_mutex_lock(&env->me_rpmutex);
5965 for (i=1; i<=tl[0].mid; i++) {
5968 /* tmp overflow pages don't go to env */
5969 if (tl[i].mid & (MDB_RPAGE_CHUNK-1)) {
5970 munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
5973 x = mdb_mid3l_search(el, tl[i].mid);
5977 pthread_mutex_unlock(&env->me_rpmutex);
5979 /* we didn't find any unref'd chunks.
5980 * if we're out of room, fail.
5982 if (tl[0].mid >= MDB_TRPAGE_MAX)
5983 return MDB_TXN_FULL;
5984 /* otherwise, raise threshold for next time around
5987 txn->mt_rpcheck /= 2;
5989 /* we found some unused; consolidate the list */
5990 for (i=y+1; i<= tl[0].mid; i++)
5994 /* decrease the check threshold toward its original value */
5995 if (!txn->mt_rpcheck)
5996 txn->mt_rpcheck = 1;
5997 while (txn->mt_rpcheck < tl[0].mid && txn->mt_rpcheck < MDB_TRPAGE_SIZE/2)
5998 txn->mt_rpcheck *= 2;
6001 if (tl[0].mid < MDB_TRPAGE_SIZE) {
6005 /* don't map past last written page in read-only envs */
6006 if ((env->me_flags & MDB_RDONLY) && pgno + MDB_RPAGE_CHUNK-1 > txn->mt_last_pgno)
6007 id3.mcnt = txn->mt_last_pgno + 1 - pgno;
6009 id3.mcnt = MDB_RPAGE_CHUNK;
6010 len = id3.mcnt * env->me_psize;
6013 /* search for page in env */
6014 pthread_mutex_lock(&env->me_rpmutex);
6015 x = mdb_mid3l_search(el, pgno);
6016 if (x <= el[0].mid && el[x].mid == pgno) {
6017 id3.mptr = el[x].mptr;
6018 id3.mcnt = el[x].mcnt;
6019 /* check for overflow size */
6020 p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
6021 if (IS_OVERFLOW(p) && p->mp_pages + rem > id3.mcnt) {
6022 id3.mcnt = p->mp_pages + rem;
6023 len = id3.mcnt * env->me_psize;
6024 SET_OFF(off, pgno * env->me_psize);
6025 MAP(rc, env, id3.mptr, len, off);
6029 munmap(el[x].mptr, env->me_psize * el[x].mcnt);
6030 el[x].mptr = id3.mptr;
6031 el[x].mcnt = id3.mcnt;
6034 pthread_mutex_unlock(&env->me_rpmutex);
6039 pthread_mutex_unlock(&env->me_rpmutex);
6042 if (el[0].mid >= MDB_ERPAGE_MAX - env->me_rpcheck) {
6043 /* purge unref'd pages */
6045 for (i=1; i<=el[0].mid; i++) {
6048 munmap(el[i].mptr, env->me_psize * el[i].mcnt);
6053 /* see if we can unref some local pages */
6058 if (el[0].mid >= MDB_ERPAGE_MAX) {
6059 pthread_mutex_unlock(&env->me_rpmutex);
6060 return MDB_MAP_FULL;
6062 env->me_rpcheck /= 2;
6064 for (i=y+1; i<= el[0].mid; i++)
6068 if (!env->me_rpcheck)
6069 env->me_rpcheck = 1;
6070 while (env->me_rpcheck < el[0].mid && env->me_rpcheck < MDB_ERPAGE_SIZE/2)
6071 env->me_rpcheck *= 2;
6074 SET_OFF(off, pgno * env->me_psize);
6075 MAP(rc, env, id3.mptr, len, off);
6078 pthread_mutex_unlock(&env->me_rpmutex);
6081 /* check for overflow size */
6082 p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
6083 if (IS_OVERFLOW(p) && p->mp_pages + rem > id3.mcnt) {
6084 id3.mcnt = p->mp_pages + rem;
6085 munmap(id3.mptr, len);
6086 len = id3.mcnt * env->me_psize;
6087 MAP(rc, env, id3.mptr, len, off);
6091 mdb_mid3l_insert(el, &id3);
6092 pthread_mutex_unlock(&env->me_rpmutex);
6094 mdb_mid3l_insert(tl, &id3);
6096 return MDB_TXN_FULL;
6099 p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
6100 #if MDB_DEBUG /* we don't need this check any more */
6101 if (IS_OVERFLOW(p)) {
6102 mdb_tassert(txn, p->mp_pages + rem <= id3.mcnt);
6110 /** Find the address of the page corresponding to a given page number.
6111 * Set #MDB_TXN_ERROR on failure.
6112 * @param[in] mc the cursor accessing the page.
6113 * @param[in] pgno the page number for the page to retrieve.
6114 * @param[out] ret address of a pointer where the page's address will be stored.
6115 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
6116 * @return 0 on success, non-zero on failure.
6119 mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **ret, int *lvl)
6121 MDB_txn *txn = mc->mc_txn;
6125 if (! (mc->mc_flags & (C_ORIG_RDONLY|C_WRITEMAP))) {
6129 MDB_ID2L dl = tx2->mt_u.dirty_list;
6131 /* Spilled pages were dirtied in this txn and flushed
6132 * because the dirty list got full. Bring this page
6133 * back in from the map (but don't unspill it here,
6134 * leave that unless page_touch happens again).
6136 if (tx2->mt_spill_pgs) {
6137 MDB_ID pn = pgno << 1;
6138 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
6139 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
6144 unsigned x = mdb_mid2l_search(dl, pgno);
6145 if (x <= dl[0].mid && dl[x].mid == pgno) {
6151 } while ((tx2 = tx2->mt_parent) != NULL);
6154 if (pgno >= txn->mt_next_pgno) {
6155 DPRINTF(("page %"Yu" not found", pgno));
6156 txn->mt_flags |= MDB_TXN_ERROR;
6157 return MDB_PAGE_NOTFOUND;
6165 int rc = mdb_rpage_get(txn, pgno, &p);
6167 txn->mt_flags |= MDB_TXN_ERROR;
6171 MDB_env *env = txn->mt_env;
6172 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
6183 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
6184 * The cursor is at the root page, set up the rest of it.
6187 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
6189 MDB_page *mp = mc->mc_pg[mc->mc_top];
6193 while (IS_BRANCH(mp)) {
6197 DPRINTF(("branch page %"Yu" has %u keys", mp->mp_pgno, NUMKEYS(mp)));
6198 /* Don't assert on branch pages in the FreeDB. We can get here
6199 * while in the process of rebalancing a FreeDB branch page; we must
6200 * let that proceed. ITS#8336
6202 mdb_cassert(mc, !mc->mc_dbi || NUMKEYS(mp) > 1);
6203 DPRINTF(("found index 0 to page %"Yu, NODEPGNO(NODEPTR(mp, 0))));
6205 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
6207 if (flags & MDB_PS_LAST) {
6208 i = NUMKEYS(mp) - 1;
6209 /* if already init'd, see if we're already in right place */
6210 if (mc->mc_flags & C_INITIALIZED) {
6211 if (mc->mc_ki[mc->mc_top] == i) {
6212 mp = mc->mc_pg[mc->mc_top];
6213 mc->mc_top = mc->mc_snum++;
6220 node = mdb_node_search(mc, key, &exact);
6222 i = NUMKEYS(mp) - 1;
6224 i = mc->mc_ki[mc->mc_top];
6226 mdb_cassert(mc, i > 0);
6230 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
6233 mdb_cassert(mc, i < NUMKEYS(mp));
6234 node = NODEPTR(mp, i);
6236 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
6239 mc->mc_ki[mc->mc_top] = i;
6240 if ((rc = mdb_cursor_push(mc, mp)))
6244 if (flags & MDB_PS_MODIFY) {
6245 if ((rc = mdb_page_touch(mc)) != 0)
6247 mp = mc->mc_pg[mc->mc_top];
6252 DPRINTF(("internal error, index points to a %02X page!?",
6254 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6255 return MDB_CORRUPTED;
6258 DPRINTF(("found leaf page %"Yu" for key [%s]", mp->mp_pgno,
6259 key ? DKEY(key) : "null"));
6260 mc->mc_flags |= C_INITIALIZED;
6261 mc->mc_flags &= ~C_EOF;
6266 /** Search for the lowest key under the current branch page.
6267 * This just bypasses a NUMKEYS check in the current page
6268 * before calling mdb_page_search_root(), because the callers
6269 * are all in situations where the current page is known to
6273 mdb_page_search_lowest(MDB_cursor *mc)
6275 MDB_page *mp = mc->mc_pg[mc->mc_top];
6276 MDB_node *node = NODEPTR(mp, 0);
6279 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
6282 mc->mc_ki[mc->mc_top] = 0;
6283 if ((rc = mdb_cursor_push(mc, mp)))
6285 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
6288 /** Search for the page a given key should be in.
6289 * Push it and its parent pages on the cursor stack.
6290 * @param[in,out] mc the cursor for this operation.
6291 * @param[in] key the key to search for, or NULL for first/last page.
6292 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
6293 * are touched (updated with new page numbers).
6294 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
6295 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
6296 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
6297 * @return 0 on success, non-zero on failure.
6300 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
6305 /* Make sure the txn is still viable, then find the root from
6306 * the txn's db table and set it as the root of the cursor's stack.
6308 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED) {
6309 DPUTS("transaction may not be used now");
6312 /* Make sure we're using an up-to-date root */
6313 if (*mc->mc_dbflag & DB_STALE) {
6315 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
6317 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
6318 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
6325 MDB_node *leaf = mdb_node_search(&mc2,
6326 &mc->mc_dbx->md_name, &exact);
6328 return MDB_NOTFOUND;
6329 if ((leaf->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
6330 return MDB_INCOMPATIBLE; /* not a named DB */
6331 rc = mdb_node_read(&mc2, leaf, &data);
6334 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
6336 /* The txn may not know this DBI, or another process may
6337 * have dropped and recreated the DB with other flags.
6339 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
6340 return MDB_INCOMPATIBLE;
6341 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
6343 *mc->mc_dbflag &= ~DB_STALE;
6345 root = mc->mc_db->md_root;
6347 if (root == P_INVALID) { /* Tree is empty. */
6348 DPUTS("tree is empty");
6349 return MDB_NOTFOUND;
6353 mdb_cassert(mc, root > 1);
6354 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root) {
6357 MDB_PAGE_UNREF(mc->mc_txn, mc->mc_pg[0]);
6359 if ((rc = mdb_page_get(mc, root, &mc->mc_pg[0], NULL)) != 0)
6366 for (i=1; i<mc->mc_snum; i++)
6367 MDB_PAGE_UNREF(mc->mc_txn, mc->mc_pg[i]);
6373 DPRINTF(("db %d root page %"Yu" has flags 0x%X",
6374 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
6376 if (flags & MDB_PS_MODIFY) {
6377 if ((rc = mdb_page_touch(mc)))
6381 if (flags & MDB_PS_ROOTONLY)
6384 return mdb_page_search_root(mc, key, flags);
6388 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
6390 MDB_txn *txn = mc->mc_txn;
6391 pgno_t pg = mp->mp_pgno;
6392 unsigned x = 0, ovpages = mp->mp_pages;
6393 MDB_env *env = txn->mt_env;
6394 MDB_IDL sl = txn->mt_spill_pgs;
6395 MDB_ID pn = pg << 1;
6398 DPRINTF(("free ov page %"Yu" (%d)", pg, ovpages));
6399 /* If the page is dirty or on the spill list we just acquired it,
6400 * so we should give it back to our current free list, if any.
6401 * Otherwise put it onto the list of pages we freed in this txn.
6403 * Won't create me_pghead: me_pglast must be inited along with it.
6404 * Unsupported in nested txns: They would need to hide the page
6405 * range in ancestor txns' dirty and spilled lists.
6407 if (env->me_pghead &&
6409 ((mp->mp_flags & P_DIRTY) ||
6410 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
6414 MDB_ID2 *dl, ix, iy;
6415 rc = mdb_midl_need(&env->me_pghead, ovpages);
6418 if (!(mp->mp_flags & P_DIRTY)) {
6419 /* This page is no longer spilled */
6426 /* Remove from dirty list */
6427 dl = txn->mt_u.dirty_list;
6429 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
6435 mdb_cassert(mc, x > 1);
6437 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
6438 txn->mt_flags |= MDB_TXN_ERROR;
6442 txn->mt_dirty_room++;
6443 if (!(env->me_flags & MDB_WRITEMAP))
6444 mdb_dpage_free(env, mp);
6446 /* Insert in me_pghead */
6447 mop = env->me_pghead;
6448 j = mop[0] + ovpages;
6449 for (i = mop[0]; i && mop[i] < pg; i--)
6455 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
6459 mc->mc_db->md_overflow_pages -= ovpages;
6463 /** Return the data associated with a given node.
6464 * @param[in] mc The cursor for this operation.
6465 * @param[in] leaf The node being read.
6466 * @param[out] data Updated to point to the node's data.
6467 * @return 0 on success, non-zero on failure.
6470 mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data)
6472 MDB_page *omp; /* overflow page */
6477 MDB_PAGE_UNREF(mc->mc_txn, MC_OVPG(mc));
6478 MC_SET_OVPG(mc, NULL);
6480 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6481 data->mv_size = NODEDSZ(leaf);
6482 data->mv_data = NODEDATA(leaf);
6486 /* Read overflow data.
6488 data->mv_size = NODEDSZ(leaf);
6489 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
6490 if ((rc = mdb_page_get(mc, pgno, &omp, NULL)) != 0) {
6491 DPRINTF(("read overflow page %"Yu" failed", pgno));
6494 data->mv_data = METADATA(omp);
6495 MC_SET_OVPG(mc, omp);
6501 mdb_get(MDB_txn *txn, MDB_dbi dbi,
6502 MDB_val *key, MDB_val *data)
6509 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
6511 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
6514 if (txn->mt_flags & MDB_TXN_BLOCKED)
6517 mdb_cursor_init(&mc, txn, dbi, &mx);
6518 rc = mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
6519 /* unref all the pages when MDB_VL32 - caller must copy the data
6520 * before doing anything else
6522 MDB_CURSOR_UNREF(&mc, 1);
6526 /** Find a sibling for a page.
6527 * Replaces the page at the top of the cursor's stack with the
6528 * specified sibling, if one exists.
6529 * @param[in] mc The cursor for this operation.
6530 * @param[in] move_right Non-zero if the right sibling is requested,
6531 * otherwise the left sibling.
6532 * @return 0 on success, non-zero on failure.
6535 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
6544 if (mc->mc_snum < 2) {
6545 return MDB_NOTFOUND; /* root has no siblings */
6549 op = mc->mc_pg[mc->mc_top];
6552 DPRINTF(("parent page is page %"Yu", index %u",
6553 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
6555 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6556 : (mc->mc_ki[mc->mc_top] == 0)) {
6557 DPRINTF(("no more keys left, moving to %s sibling",
6558 move_right ? "right" : "left"));
6559 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
6560 /* undo cursor_pop before returning */
6567 mc->mc_ki[mc->mc_top]++;
6569 mc->mc_ki[mc->mc_top]--;
6570 DPRINTF(("just moving to %s index key %u",
6571 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
6573 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
6575 MDB_PAGE_UNREF(mc->mc_txn, op);
6577 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6578 if ((rc = mdb_page_get(mc, NODEPGNO(indx), &mp, NULL)) != 0) {
6579 /* mc will be inconsistent if caller does mc_snum++ as above */
6580 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
6584 mdb_cursor_push(mc, mp);
6586 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
6591 /** Move the cursor to the next data item. */
6593 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
6599 if ((mc->mc_flags & C_DEL && op == MDB_NEXT_DUP))
6600 return MDB_NOTFOUND;
6602 if (!(mc->mc_flags & C_INITIALIZED))
6603 return mdb_cursor_first(mc, key, data);
6605 mp = mc->mc_pg[mc->mc_top];
6607 if ((mc->mc_flags & C_EOF) && mc->mc_ki[mc->mc_top] >= NUMKEYS(mp)-1)
6608 return MDB_NOTFOUND;
6610 if (mc->mc_db->md_flags & MDB_DUPSORT) {
6611 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6612 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6613 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
6614 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
6615 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
6616 if (rc == MDB_SUCCESS)
6617 MDB_GET_KEY(leaf, key);
6622 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
6625 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6626 if (op == MDB_NEXT_DUP)
6627 return MDB_NOTFOUND;
6631 DPRINTF(("cursor_next: top page is %"Yu" in cursor %p",
6632 mdb_dbg_pgno(mp), (void *) mc));
6633 if (mc->mc_flags & C_DEL) {
6634 mc->mc_flags ^= C_DEL;
6638 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
6639 DPUTS("=====> move to next sibling page");
6640 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
6641 mc->mc_flags |= C_EOF;
6644 mp = mc->mc_pg[mc->mc_top];
6645 DPRINTF(("next page is %"Yu", key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
6647 mc->mc_ki[mc->mc_top]++;
6650 DPRINTF(("==> cursor points to page %"Yu" with %u keys, key index %u",
6651 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
6654 key->mv_size = mc->mc_db->md_pad;
6655 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6659 mdb_cassert(mc, IS_LEAF(mp));
6660 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6662 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6663 mdb_xcursor_init1(mc, leaf);
6666 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6669 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6670 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6671 if (rc != MDB_SUCCESS)
6676 MDB_GET_KEY(leaf, key);
6680 /** Move the cursor to the previous data item. */
6682 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
6688 if (!(mc->mc_flags & C_INITIALIZED)) {
6689 rc = mdb_cursor_last(mc, key, data);
6692 mc->mc_ki[mc->mc_top]++;
6695 mp = mc->mc_pg[mc->mc_top];
6697 if (mc->mc_db->md_flags & MDB_DUPSORT) {
6698 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6699 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6700 if (op == MDB_PREV || op == MDB_PREV_DUP) {
6701 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
6702 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
6703 if (rc == MDB_SUCCESS) {
6704 MDB_GET_KEY(leaf, key);
6705 mc->mc_flags &= ~C_EOF;
6711 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
6714 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6715 if (op == MDB_PREV_DUP)
6716 return MDB_NOTFOUND;
6720 DPRINTF(("cursor_prev: top page is %"Yu" in cursor %p",
6721 mdb_dbg_pgno(mp), (void *) mc));
6723 mc->mc_flags &= ~(C_EOF|C_DEL);
6725 if (mc->mc_ki[mc->mc_top] == 0) {
6726 DPUTS("=====> move to prev sibling page");
6727 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
6730 mp = mc->mc_pg[mc->mc_top];
6731 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
6732 DPRINTF(("prev page is %"Yu", key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
6734 mc->mc_ki[mc->mc_top]--;
6736 DPRINTF(("==> cursor points to page %"Yu" with %u keys, key index %u",
6737 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
6740 key->mv_size = mc->mc_db->md_pad;
6741 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6745 mdb_cassert(mc, IS_LEAF(mp));
6746 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6748 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6749 mdb_xcursor_init1(mc, leaf);
6752 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6755 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6756 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
6757 if (rc != MDB_SUCCESS)
6762 MDB_GET_KEY(leaf, key);
6766 /** Set the cursor on a specific data item. */
6768 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6769 MDB_cursor_op op, int *exactp)
6773 MDB_node *leaf = NULL;
6776 if (key->mv_size == 0)
6777 return MDB_BAD_VALSIZE;
6779 if (mc->mc_xcursor) {
6780 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
6781 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6784 /* See if we're already on the right page */
6785 if (mc->mc_flags & C_INITIALIZED) {
6788 mp = mc->mc_pg[mc->mc_top];
6790 mc->mc_ki[mc->mc_top] = 0;
6791 return MDB_NOTFOUND;
6793 if (mp->mp_flags & P_LEAF2) {
6794 nodekey.mv_size = mc->mc_db->md_pad;
6795 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
6797 leaf = NODEPTR(mp, 0);
6798 MDB_GET_KEY2(leaf, nodekey);
6800 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6802 /* Probably happens rarely, but first node on the page
6803 * was the one we wanted.
6805 mc->mc_ki[mc->mc_top] = 0;
6812 unsigned int nkeys = NUMKEYS(mp);
6814 if (mp->mp_flags & P_LEAF2) {
6815 nodekey.mv_data = LEAF2KEY(mp,
6816 nkeys-1, nodekey.mv_size);
6818 leaf = NODEPTR(mp, nkeys-1);
6819 MDB_GET_KEY2(leaf, nodekey);
6821 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6823 /* last node was the one we wanted */
6824 mc->mc_ki[mc->mc_top] = nkeys-1;
6830 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
6831 /* This is definitely the right page, skip search_page */
6832 if (mp->mp_flags & P_LEAF2) {
6833 nodekey.mv_data = LEAF2KEY(mp,
6834 mc->mc_ki[mc->mc_top], nodekey.mv_size);
6836 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6837 MDB_GET_KEY2(leaf, nodekey);
6839 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6841 /* current node was the one we wanted */
6848 mc->mc_flags &= ~C_EOF;
6852 /* If any parents have right-sibs, search.
6853 * Otherwise, there's nothing further.
6855 for (i=0; i<mc->mc_top; i++)
6857 NUMKEYS(mc->mc_pg[i])-1)
6859 if (i == mc->mc_top) {
6860 /* There are no other pages */
6861 mc->mc_ki[mc->mc_top] = nkeys;
6862 return MDB_NOTFOUND;
6866 /* There are no other pages */
6867 mc->mc_ki[mc->mc_top] = 0;
6868 if (op == MDB_SET_RANGE && !exactp) {
6872 return MDB_NOTFOUND;
6878 rc = mdb_page_search(mc, key, 0);
6879 if (rc != MDB_SUCCESS)
6882 mp = mc->mc_pg[mc->mc_top];
6883 mdb_cassert(mc, IS_LEAF(mp));
6886 leaf = mdb_node_search(mc, key, exactp);
6887 if (exactp != NULL && !*exactp) {
6888 /* MDB_SET specified and not an exact match. */
6889 return MDB_NOTFOUND;
6893 DPUTS("===> inexact leaf not found, goto sibling");
6894 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
6895 mc->mc_flags |= C_EOF;
6896 return rc; /* no entries matched */
6898 mp = mc->mc_pg[mc->mc_top];
6899 mdb_cassert(mc, IS_LEAF(mp));
6900 leaf = NODEPTR(mp, 0);
6904 mc->mc_flags |= C_INITIALIZED;
6905 mc->mc_flags &= ~C_EOF;
6908 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
6909 key->mv_size = mc->mc_db->md_pad;
6910 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6915 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6916 mdb_xcursor_init1(mc, leaf);
6919 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6920 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
6921 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6924 if (op == MDB_GET_BOTH) {
6930 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
6931 if (rc != MDB_SUCCESS)
6934 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
6937 if ((rc = mdb_node_read(mc, leaf, &olddata)) != MDB_SUCCESS)
6939 dcmp = mc->mc_dbx->md_dcmp;
6940 if (NEED_CMP_CLONG(dcmp, olddata.mv_size))
6941 dcmp = mdb_cmp_clong;
6942 rc = dcmp(data, &olddata);
6944 if (op == MDB_GET_BOTH || rc > 0)
6945 return MDB_NOTFOUND;
6952 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6953 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6958 /* The key already matches in all other cases */
6959 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
6960 MDB_GET_KEY(leaf, key);
6961 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
6966 /** Move the cursor to the first item in the database. */
6968 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6973 if (mc->mc_xcursor) {
6974 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
6975 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6978 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6979 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
6980 if (rc != MDB_SUCCESS)
6983 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6985 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
6986 mc->mc_flags |= C_INITIALIZED;
6987 mc->mc_flags &= ~C_EOF;
6989 mc->mc_ki[mc->mc_top] = 0;
6991 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6992 key->mv_size = mc->mc_db->md_pad;
6993 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
6998 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6999 mdb_xcursor_init1(mc, leaf);
7000 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
7004 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
7008 MDB_GET_KEY(leaf, key);
7012 /** Move the cursor to the last item in the database. */
7014 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
7019 if (mc->mc_xcursor) {
7020 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
7021 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
7024 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
7025 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
7026 if (rc != MDB_SUCCESS)
7029 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
7031 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
7032 mc->mc_flags |= C_INITIALIZED|C_EOF;
7033 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7035 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
7036 key->mv_size = mc->mc_db->md_pad;
7037 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
7042 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7043 mdb_xcursor_init1(mc, leaf);
7044 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
7048 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
7053 MDB_GET_KEY(leaf, key);
7058 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
7063 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
7068 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
7072 case MDB_GET_CURRENT:
7073 if (!(mc->mc_flags & C_INITIALIZED)) {
7076 MDB_page *mp = mc->mc_pg[mc->mc_top];
7077 int nkeys = NUMKEYS(mp);
7078 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
7079 mc->mc_ki[mc->mc_top] = nkeys;
7085 key->mv_size = mc->mc_db->md_pad;
7086 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
7088 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7089 MDB_GET_KEY(leaf, key);
7091 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7092 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
7094 rc = mdb_node_read(mc, leaf, data);
7101 case MDB_GET_BOTH_RANGE:
7106 if (mc->mc_xcursor == NULL) {
7107 rc = MDB_INCOMPATIBLE;
7117 rc = mdb_cursor_set(mc, key, data, op,
7118 op == MDB_SET_RANGE ? NULL : &exact);
7121 case MDB_GET_MULTIPLE:
7122 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
7126 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7127 rc = MDB_INCOMPATIBLE;
7131 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
7132 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
7135 case MDB_NEXT_MULTIPLE:
7140 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7141 rc = MDB_INCOMPATIBLE;
7144 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
7145 if (rc == MDB_SUCCESS) {
7146 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
7149 mx = &mc->mc_xcursor->mx_cursor;
7150 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
7152 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
7153 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
7159 case MDB_PREV_MULTIPLE:
7164 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7165 rc = MDB_INCOMPATIBLE;
7168 if (!(mc->mc_flags & C_INITIALIZED))
7169 rc = mdb_cursor_last(mc, key, data);
7172 if (rc == MDB_SUCCESS) {
7173 MDB_cursor *mx = &mc->mc_xcursor->mx_cursor;
7174 if (mx->mc_flags & C_INITIALIZED) {
7175 rc = mdb_cursor_sibling(mx, 0);
7176 if (rc == MDB_SUCCESS)
7185 case MDB_NEXT_NODUP:
7186 rc = mdb_cursor_next(mc, key, data, op);
7190 case MDB_PREV_NODUP:
7191 rc = mdb_cursor_prev(mc, key, data, op);
7194 rc = mdb_cursor_first(mc, key, data);
7197 mfunc = mdb_cursor_first;
7199 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
7203 if (mc->mc_xcursor == NULL) {
7204 rc = MDB_INCOMPATIBLE;
7208 MDB_node *leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7209 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7210 MDB_GET_KEY(leaf, key);
7211 rc = mdb_node_read(mc, leaf, data);
7215 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
7219 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
7222 rc = mdb_cursor_last(mc, key, data);
7225 mfunc = mdb_cursor_last;
7228 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
7233 if (mc->mc_flags & C_DEL)
7234 mc->mc_flags ^= C_DEL;
7239 /** Touch all the pages in the cursor stack. Set mc_top.
7240 * Makes sure all the pages are writable, before attempting a write operation.
7241 * @param[in] mc The cursor to operate on.
7244 mdb_cursor_touch(MDB_cursor *mc)
7246 int rc = MDB_SUCCESS;
7248 if (mc->mc_dbi >= CORE_DBS && !(*mc->mc_dbflag & (DB_DIRTY|DB_DUPDATA))) {
7249 /* Touch DB record of named DB */
7252 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
7254 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
7255 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
7258 *mc->mc_dbflag |= DB_DIRTY;
7263 rc = mdb_page_touch(mc);
7264 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
7265 mc->mc_top = mc->mc_snum-1;
7270 /** Do not spill pages to disk if txn is getting full, may fail instead */
7271 #define MDB_NOSPILL 0x8000
7274 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
7278 MDB_node *leaf = NULL;
7279 MDB_page *fp, *mp, *sub_root = NULL;
7281 MDB_val xdata, *rdata, dkey, olddata;
7283 int do_sub = 0, insert_key, insert_data;
7284 unsigned int mcount = 0, dcount = 0, nospill;
7287 unsigned int nflags;
7290 if (mc == NULL || key == NULL)
7293 env = mc->mc_txn->mt_env;
7295 /* Check this first so counter will always be zero on any
7298 if (flags & MDB_MULTIPLE) {
7299 dcount = data[1].mv_size;
7300 data[1].mv_size = 0;
7301 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
7302 return MDB_INCOMPATIBLE;
7305 nospill = flags & MDB_NOSPILL;
7306 flags &= ~MDB_NOSPILL;
7308 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
7309 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7311 if (key->mv_size-1 >= ENV_MAXKEY(env))
7312 return MDB_BAD_VALSIZE;
7314 #if SIZE_MAX > MAXDATASIZE
7315 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
7316 return MDB_BAD_VALSIZE;
7318 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
7319 return MDB_BAD_VALSIZE;
7322 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
7323 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
7327 if (flags == MDB_CURRENT) {
7328 if (!(mc->mc_flags & C_INITIALIZED))
7331 } else if (mc->mc_db->md_root == P_INVALID) {
7332 /* new database, cursor has nothing to point to */
7335 mc->mc_flags &= ~C_INITIALIZED;
7340 if (flags & MDB_APPEND) {
7342 rc = mdb_cursor_last(mc, &k2, &d2);
7344 rc = mc->mc_dbx->md_cmp(key, &k2);
7347 mc->mc_ki[mc->mc_top]++;
7349 /* new key is <= last key */
7354 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
7356 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
7357 DPRINTF(("duplicate key [%s]", DKEY(key)));
7359 return MDB_KEYEXIST;
7361 if (rc && rc != MDB_NOTFOUND)
7365 if (mc->mc_flags & C_DEL)
7366 mc->mc_flags ^= C_DEL;
7368 /* Cursor is positioned, check for room in the dirty list */
7370 if (flags & MDB_MULTIPLE) {
7372 xdata.mv_size = data->mv_size * dcount;
7376 if ((rc2 = mdb_page_spill(mc, key, rdata)))
7380 if (rc == MDB_NO_ROOT) {
7382 /* new database, write a root leaf page */
7383 DPUTS("allocating new root leaf page");
7384 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
7387 mdb_cursor_push(mc, np);
7388 mc->mc_db->md_root = np->mp_pgno;
7389 mc->mc_db->md_depth++;
7390 *mc->mc_dbflag |= DB_DIRTY;
7391 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
7393 np->mp_flags |= P_LEAF2;
7394 mc->mc_flags |= C_INITIALIZED;
7396 /* make sure all cursor pages are writable */
7397 rc2 = mdb_cursor_touch(mc);
7402 insert_key = insert_data = rc;
7404 /* The key does not exist */
7405 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
7406 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
7407 LEAFSIZE(key, data) > env->me_nodemax)
7409 /* Too big for a node, insert in sub-DB. Set up an empty
7410 * "old sub-page" for prep_subDB to expand to a full page.
7412 fp_flags = P_LEAF|P_DIRTY;
7414 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
7415 fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
7416 olddata.mv_size = PAGEHDRSZ;
7420 /* there's only a key anyway, so this is a no-op */
7421 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
7423 unsigned int ksize = mc->mc_db->md_pad;
7424 if (key->mv_size != ksize)
7425 return MDB_BAD_VALSIZE;
7426 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
7427 memcpy(ptr, key->mv_data, ksize);
7429 /* if overwriting slot 0 of leaf, need to
7430 * update branch key if there is a parent page
7432 if (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
7433 unsigned short dtop = 1;
7435 /* slot 0 is always an empty key, find real slot */
7436 while (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
7440 if (mc->mc_ki[mc->mc_top])
7441 rc2 = mdb_update_key(mc, key);
7452 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7453 olddata.mv_size = NODEDSZ(leaf);
7454 olddata.mv_data = NODEDATA(leaf);
7457 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
7458 /* Prepare (sub-)page/sub-DB to accept the new item,
7459 * if needed. fp: old sub-page or a header faking
7460 * it. mp: new (sub-)page. offset: growth in page
7461 * size. xdata: node data with new page or DB.
7463 unsigned i, offset = 0;
7464 mp = fp = xdata.mv_data = env->me_pbuf;
7465 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
7467 /* Was a single item before, must convert now */
7468 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7470 /* Just overwrite the current item */
7471 if (flags == MDB_CURRENT)
7473 dcmp = mc->mc_dbx->md_dcmp;
7474 if (NEED_CMP_CLONG(dcmp, olddata.mv_size))
7475 dcmp = mdb_cmp_clong;
7476 /* does data match? */
7477 if (!dcmp(data, &olddata)) {
7478 if (flags & (MDB_NODUPDATA|MDB_APPENDDUP))
7479 return MDB_KEYEXIST;
7484 /* Back up original data item */
7485 dkey.mv_size = olddata.mv_size;
7486 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
7488 /* Make sub-page header for the dup items, with dummy body */
7489 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
7490 fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
7491 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
7492 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7493 fp->mp_flags |= P_LEAF2;
7494 fp->mp_pad = data->mv_size;
7495 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
7497 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
7498 (dkey.mv_size & 1) + (data->mv_size & 1);
7500 fp->mp_upper = xdata.mv_size - PAGEBASE;
7501 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
7502 } else if (leaf->mn_flags & F_SUBDATA) {
7503 /* Data is on sub-DB, just store it */
7504 flags |= F_DUPDATA|F_SUBDATA;
7507 /* Data is on sub-page */
7508 fp = olddata.mv_data;
7511 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7512 offset = EVEN(NODESIZE + sizeof(indx_t) +
7516 offset = fp->mp_pad;
7517 if (SIZELEFT(fp) < offset) {
7518 offset *= 4; /* space for 4 more */
7521 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
7523 fp->mp_flags |= P_DIRTY;
7524 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
7525 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
7529 xdata.mv_size = olddata.mv_size + offset;
7532 fp_flags = fp->mp_flags;
7533 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
7534 /* Too big for a sub-page, convert to sub-DB */
7535 fp_flags &= ~P_SUBP;
7537 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7538 fp_flags |= P_LEAF2;
7539 dummy.md_pad = fp->mp_pad;
7540 dummy.md_flags = MDB_DUPFIXED;
7541 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
7542 dummy.md_flags |= MDB_INTEGERKEY;
7548 dummy.md_branch_pages = 0;
7549 dummy.md_leaf_pages = 1;
7550 dummy.md_overflow_pages = 0;
7551 dummy.md_entries = NUMKEYS(fp);
7552 xdata.mv_size = sizeof(MDB_db);
7553 xdata.mv_data = &dummy;
7554 if ((rc = mdb_page_alloc(mc, 1, &mp)))
7556 offset = env->me_psize - olddata.mv_size;
7557 flags |= F_DUPDATA|F_SUBDATA;
7558 dummy.md_root = mp->mp_pgno;
7562 mp->mp_flags = fp_flags | P_DIRTY;
7563 mp->mp_pad = fp->mp_pad;
7564 mp->mp_lower = fp->mp_lower;
7565 mp->mp_upper = fp->mp_upper + offset;
7566 if (fp_flags & P_LEAF2) {
7567 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
7569 memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
7570 olddata.mv_size - fp->mp_upper - PAGEBASE);
7571 for (i=0; i<NUMKEYS(fp); i++)
7572 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
7580 mdb_node_del(mc, 0);
7584 /* LMDB passes F_SUBDATA in 'flags' to write a DB record */
7585 if ((leaf->mn_flags ^ flags) & F_SUBDATA)
7586 return MDB_INCOMPATIBLE;
7587 /* overflow page overwrites need special handling */
7588 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7591 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
7593 memcpy(&pg, olddata.mv_data, sizeof(pg));
7594 if ((rc2 = mdb_page_get(mc, pg, &omp, &level)) != 0)
7596 ovpages = omp->mp_pages;
7598 /* Is the ov page large enough? */
7599 if (ovpages >= dpages) {
7600 if (!(omp->mp_flags & P_DIRTY) &&
7601 (level || (env->me_flags & MDB_WRITEMAP)))
7603 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
7606 level = 0; /* dirty in this txn or clean */
7609 if (omp->mp_flags & P_DIRTY) {
7610 /* yes, overwrite it. Note in this case we don't
7611 * bother to try shrinking the page if the new data
7612 * is smaller than the overflow threshold.
7615 /* It is writable only in a parent txn */
7616 size_t sz = (size_t) env->me_psize * ovpages, off;
7617 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
7623 /* Note - this page is already counted in parent's dirty_room */
7624 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
7625 mdb_cassert(mc, rc2 == 0);
7626 /* Currently we make the page look as with put() in the
7627 * parent txn, in case the user peeks at MDB_RESERVEd
7628 * or unused parts. Some users treat ovpages specially.
7630 if (!(flags & MDB_RESERVE)) {
7631 /* Skip the part where LMDB will put *data.
7632 * Copy end of page, adjusting alignment so
7633 * compiler may copy words instead of bytes.
7635 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
7636 memcpy((size_t *)((char *)np + off),
7637 (size_t *)((char *)omp + off), sz - off);
7640 memcpy(np, omp, sz); /* Copy beginning of page */
7643 SETDSZ(leaf, data->mv_size);
7644 if (F_ISSET(flags, MDB_RESERVE))
7645 data->mv_data = METADATA(omp);
7647 memcpy(METADATA(omp), data->mv_data, data->mv_size);
7651 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
7653 } else if (data->mv_size == olddata.mv_size) {
7654 /* same size, just replace it. Note that we could
7655 * also reuse this node if the new data is smaller,
7656 * but instead we opt to shrink the node in that case.
7658 if (F_ISSET(flags, MDB_RESERVE))
7659 data->mv_data = olddata.mv_data;
7660 else if (!(mc->mc_flags & C_SUB))
7661 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
7663 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
7668 mdb_node_del(mc, 0);
7674 nflags = flags & NODE_ADD_FLAGS;
7675 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
7676 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
7677 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
7678 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
7680 nflags |= MDB_SPLIT_REPLACE;
7681 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
7683 /* There is room already in this leaf page. */
7684 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
7686 /* Adjust other cursors pointing to mp */
7687 MDB_cursor *m2, *m3;
7688 MDB_dbi dbi = mc->mc_dbi;
7689 unsigned i = mc->mc_top;
7690 MDB_page *mp = mc->mc_pg[i];
7692 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7693 if (mc->mc_flags & C_SUB)
7694 m3 = &m2->mc_xcursor->mx_cursor;
7697 if (m3 == mc || m3->mc_snum < mc->mc_snum || m3->mc_pg[i] != mp) continue;
7698 if (m3->mc_ki[i] >= mc->mc_ki[i] && insert_key) {
7701 if (XCURSOR_INITED(m3))
7702 XCURSOR_REFRESH(m3, mp, m3->mc_ki[i]);
7707 if (rc == MDB_SUCCESS) {
7708 /* Now store the actual data in the child DB. Note that we're
7709 * storing the user data in the keys field, so there are strict
7710 * size limits on dupdata. The actual data fields of the child
7711 * DB are all zero size.
7714 int xflags, new_dupdata;
7719 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7720 if (flags & MDB_CURRENT) {
7721 xflags = MDB_CURRENT|MDB_NOSPILL;
7723 mdb_xcursor_init1(mc, leaf);
7724 xflags = (flags & MDB_NODUPDATA) ?
7725 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
7728 mc->mc_xcursor->mx_cursor.mc_pg[0] = sub_root;
7729 new_dupdata = (int)dkey.mv_size;
7730 /* converted, write the original data first */
7732 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
7735 /* we've done our job */
7738 if (!(leaf->mn_flags & F_SUBDATA) || sub_root) {
7739 /* Adjust other cursors pointing to mp */
7741 MDB_xcursor *mx = mc->mc_xcursor;
7742 unsigned i = mc->mc_top;
7743 MDB_page *mp = mc->mc_pg[i];
7744 int nkeys = NUMKEYS(mp);
7746 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
7747 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
7748 if (!(m2->mc_flags & C_INITIALIZED)) continue;
7749 if (m2->mc_pg[i] == mp) {
7750 if (m2->mc_ki[i] == mc->mc_ki[i]) {
7751 mdb_xcursor_init2(m2, mx, new_dupdata);
7752 } else if (!insert_key && m2->mc_ki[i] < nkeys) {
7753 XCURSOR_REFRESH(m2, mp, m2->mc_ki[i]);
7758 ecount = mc->mc_xcursor->mx_db.md_entries;
7759 if (flags & MDB_APPENDDUP)
7760 xflags |= MDB_APPEND;
7761 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
7762 if (flags & F_SUBDATA) {
7763 void *db = NODEDATA(leaf);
7764 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
7766 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
7768 /* Increment count unless we just replaced an existing item. */
7770 mc->mc_db->md_entries++;
7772 /* Invalidate txn if we created an empty sub-DB */
7775 /* If we succeeded and the key didn't exist before,
7776 * make sure the cursor is marked valid.
7778 mc->mc_flags |= C_INITIALIZED;
7780 if (flags & MDB_MULTIPLE) {
7783 /* let caller know how many succeeded, if any */
7784 data[1].mv_size = mcount;
7785 if (mcount < dcount) {
7786 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
7787 insert_key = insert_data = 0;
7794 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
7797 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7802 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
7808 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
7809 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7811 if (!(mc->mc_flags & C_INITIALIZED))
7814 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
7815 return MDB_NOTFOUND;
7817 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
7820 rc = mdb_cursor_touch(mc);
7824 mp = mc->mc_pg[mc->mc_top];
7827 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7829 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7830 if (flags & MDB_NODUPDATA) {
7831 /* mdb_cursor_del0() will subtract the final entry */
7832 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
7833 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
7835 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
7836 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
7838 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
7841 /* If sub-DB still has entries, we're done */
7842 if (mc->mc_xcursor->mx_db.md_entries) {
7843 if (leaf->mn_flags & F_SUBDATA) {
7844 /* update subDB info */
7845 void *db = NODEDATA(leaf);
7846 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
7849 /* shrink fake page */
7850 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
7851 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7852 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
7853 /* fix other sub-DB cursors pointed at fake pages on this page */
7854 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
7855 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
7856 if (!(m2->mc_flags & C_INITIALIZED)) continue;
7857 if (m2->mc_pg[mc->mc_top] == mp) {
7858 MDB_node *n2 = leaf;
7859 if (m2->mc_ki[mc->mc_top] != mc->mc_ki[mc->mc_top]) {
7860 n2 = NODEPTR(mp, m2->mc_ki[mc->mc_top]);
7861 if (n2->mn_flags & F_SUBDATA) continue;
7863 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
7867 mc->mc_db->md_entries--;
7870 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
7872 /* otherwise fall thru and delete the sub-DB */
7875 if (leaf->mn_flags & F_SUBDATA) {
7876 /* add all the child DB's pages to the free list */
7877 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
7882 /* LMDB passes F_SUBDATA in 'flags' to delete a DB record */
7883 else if ((leaf->mn_flags ^ flags) & F_SUBDATA) {
7884 rc = MDB_INCOMPATIBLE;
7888 /* add overflow pages to free list */
7889 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7893 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
7894 if ((rc = mdb_page_get(mc, pg, &omp, NULL)) ||
7895 (rc = mdb_ovpage_free(mc, omp)))
7900 return mdb_cursor_del0(mc);
7903 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7907 /** Allocate and initialize new pages for a database.
7908 * Set #MDB_TXN_ERROR on failure.
7909 * @param[in] mc a cursor on the database being added to.
7910 * @param[in] flags flags defining what type of page is being allocated.
7911 * @param[in] num the number of pages to allocate. This is usually 1,
7912 * unless allocating overflow pages for a large record.
7913 * @param[out] mp Address of a page, or NULL on failure.
7914 * @return 0 on success, non-zero on failure.
7917 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
7922 if ((rc = mdb_page_alloc(mc, num, &np)))
7924 DPRINTF(("allocated new mpage %"Yu", page size %u",
7925 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
7926 np->mp_flags = flags | P_DIRTY;
7927 np->mp_lower = (PAGEHDRSZ-PAGEBASE);
7928 np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
7931 mc->mc_db->md_branch_pages++;
7932 else if (IS_LEAF(np))
7933 mc->mc_db->md_leaf_pages++;
7934 else if (IS_OVERFLOW(np)) {
7935 mc->mc_db->md_overflow_pages += num;
7943 /** Calculate the size of a leaf node.
7944 * The size depends on the environment's page size; if a data item
7945 * is too large it will be put onto an overflow page and the node
7946 * size will only include the key and not the data. Sizes are always
7947 * rounded up to an even number of bytes, to guarantee 2-byte alignment
7948 * of the #MDB_node headers.
7949 * @param[in] env The environment handle.
7950 * @param[in] key The key for the node.
7951 * @param[in] data The data for the node.
7952 * @return The number of bytes needed to store the node.
7955 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
7959 sz = LEAFSIZE(key, data);
7960 if (sz > env->me_nodemax) {
7961 /* put on overflow page */
7962 sz -= data->mv_size - sizeof(pgno_t);
7965 return EVEN(sz + sizeof(indx_t));
7968 /** Calculate the size of a branch node.
7969 * The size should depend on the environment's page size but since
7970 * we currently don't support spilling large keys onto overflow
7971 * pages, it's simply the size of the #MDB_node header plus the
7972 * size of the key. Sizes are always rounded up to an even number
7973 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
7974 * @param[in] env The environment handle.
7975 * @param[in] key The key for the node.
7976 * @return The number of bytes needed to store the node.
7979 mdb_branch_size(MDB_env *env, MDB_val *key)
7984 if (sz > env->me_nodemax) {
7985 /* put on overflow page */
7986 /* not implemented */
7987 /* sz -= key->size - sizeof(pgno_t); */
7990 return sz + sizeof(indx_t);
7993 /** Add a node to the page pointed to by the cursor.
7994 * Set #MDB_TXN_ERROR on failure.
7995 * @param[in] mc The cursor for this operation.
7996 * @param[in] indx The index on the page where the new node should be added.
7997 * @param[in] key The key for the new node.
7998 * @param[in] data The data for the new node, if any.
7999 * @param[in] pgno The page number, if adding a branch node.
8000 * @param[in] flags Flags for the node.
8001 * @return 0 on success, non-zero on failure. Possible errors are:
8003 * <li>ENOMEM - failed to allocate overflow pages for the node.
8004 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
8005 * should never happen since all callers already calculate the
8006 * page's free space before calling this function.
8010 mdb_node_add(MDB_cursor *mc, indx_t indx,
8011 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
8014 size_t node_size = NODESIZE;
8018 MDB_page *mp = mc->mc_pg[mc->mc_top];
8019 MDB_page *ofp = NULL; /* overflow page */
8023 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
8025 DPRINTF(("add to %s %spage %"Yu" index %i, data size %"Z"u key size %"Z"u [%s]",
8026 IS_LEAF(mp) ? "leaf" : "branch",
8027 IS_SUBP(mp) ? "sub-" : "",
8028 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
8029 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
8032 /* Move higher keys up one slot. */
8033 int ksize = mc->mc_db->md_pad, dif;
8034 char *ptr = LEAF2KEY(mp, indx, ksize);
8035 dif = NUMKEYS(mp) - indx;
8037 memmove(ptr+ksize, ptr, dif*ksize);
8038 /* insert new key */
8039 memcpy(ptr, key->mv_data, ksize);
8041 /* Just using these for counting */
8042 mp->mp_lower += sizeof(indx_t);
8043 mp->mp_upper -= ksize - sizeof(indx_t);
8047 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
8049 node_size += key->mv_size;
8051 mdb_cassert(mc, key && data);
8052 if (F_ISSET(flags, F_BIGDATA)) {
8053 /* Data already on overflow page. */
8054 node_size += sizeof(pgno_t);
8055 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
8056 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
8058 /* Put data on overflow page. */
8059 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
8060 data->mv_size, node_size+data->mv_size));
8061 node_size = EVEN(node_size + sizeof(pgno_t));
8062 if ((ssize_t)node_size > room)
8064 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
8066 DPRINTF(("allocated overflow page %"Yu, ofp->mp_pgno));
8070 node_size += data->mv_size;
8073 node_size = EVEN(node_size);
8074 if ((ssize_t)node_size > room)
8078 /* Move higher pointers up one slot. */
8079 for (i = NUMKEYS(mp); i > indx; i--)
8080 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
8082 /* Adjust free space offsets. */
8083 ofs = mp->mp_upper - node_size;
8084 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
8085 mp->mp_ptrs[indx] = ofs;
8087 mp->mp_lower += sizeof(indx_t);
8089 /* Write the node data. */
8090 node = NODEPTR(mp, indx);
8091 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
8092 node->mn_flags = flags;
8094 SETDSZ(node,data->mv_size);
8099 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
8102 ndata = NODEDATA(node);
8104 if (F_ISSET(flags, F_BIGDATA))
8105 memcpy(ndata, data->mv_data, sizeof(pgno_t));
8106 else if (F_ISSET(flags, MDB_RESERVE))
8107 data->mv_data = ndata;
8109 memcpy(ndata, data->mv_data, data->mv_size);
8111 memcpy(ndata, &ofp->mp_pgno, sizeof(pgno_t));
8112 ndata = METADATA(ofp);
8113 if (F_ISSET(flags, MDB_RESERVE))
8114 data->mv_data = ndata;
8116 memcpy(ndata, data->mv_data, data->mv_size);
8123 DPRINTF(("not enough room in page %"Yu", got %u ptrs",
8124 mdb_dbg_pgno(mp), NUMKEYS(mp)));
8125 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
8126 DPRINTF(("node size = %"Z"u", node_size));
8127 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8128 return MDB_PAGE_FULL;
8131 /** Delete the specified node from a page.
8132 * @param[in] mc Cursor pointing to the node to delete.
8133 * @param[in] ksize The size of a node. Only used if the page is
8134 * part of a #MDB_DUPFIXED database.
8137 mdb_node_del(MDB_cursor *mc, int ksize)
8139 MDB_page *mp = mc->mc_pg[mc->mc_top];
8140 indx_t indx = mc->mc_ki[mc->mc_top];
8142 indx_t i, j, numkeys, ptr;
8146 DPRINTF(("delete node %u on %s page %"Yu, indx,
8147 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
8148 numkeys = NUMKEYS(mp);
8149 mdb_cassert(mc, indx < numkeys);
8152 int x = numkeys - 1 - indx;
8153 base = LEAF2KEY(mp, indx, ksize);
8155 memmove(base, base + ksize, x * ksize);
8156 mp->mp_lower -= sizeof(indx_t);
8157 mp->mp_upper += ksize - sizeof(indx_t);
8161 node = NODEPTR(mp, indx);
8162 sz = NODESIZE + node->mn_ksize;
8164 if (F_ISSET(node->mn_flags, F_BIGDATA))
8165 sz += sizeof(pgno_t);
8167 sz += NODEDSZ(node);
8171 ptr = mp->mp_ptrs[indx];
8172 for (i = j = 0; i < numkeys; i++) {
8174 mp->mp_ptrs[j] = mp->mp_ptrs[i];
8175 if (mp->mp_ptrs[i] < ptr)
8176 mp->mp_ptrs[j] += sz;
8181 base = (char *)mp + mp->mp_upper + PAGEBASE;
8182 memmove(base + sz, base, ptr - mp->mp_upper);
8184 mp->mp_lower -= sizeof(indx_t);
8188 /** Compact the main page after deleting a node on a subpage.
8189 * @param[in] mp The main page to operate on.
8190 * @param[in] indx The index of the subpage on the main page.
8193 mdb_node_shrink(MDB_page *mp, indx_t indx)
8198 indx_t delta, nsize, len, ptr;
8201 node = NODEPTR(mp, indx);
8202 sp = (MDB_page *)NODEDATA(node);
8203 delta = SIZELEFT(sp);
8204 nsize = NODEDSZ(node) - delta;
8206 /* Prepare to shift upward, set len = length(subpage part to shift) */
8210 return; /* do not make the node uneven-sized */
8212 xp = (MDB_page *)((char *)sp + delta); /* destination subpage */
8213 for (i = NUMKEYS(sp); --i >= 0; )
8214 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
8217 sp->mp_upper = sp->mp_lower;
8218 COPY_PGNO(sp->mp_pgno, mp->mp_pgno);
8219 SETDSZ(node, nsize);
8221 /* Shift <lower nodes...initial part of subpage> upward */
8222 base = (char *)mp + mp->mp_upper + PAGEBASE;
8223 memmove(base + delta, base, (char *)sp + len - base);
8225 ptr = mp->mp_ptrs[indx];
8226 for (i = NUMKEYS(mp); --i >= 0; ) {
8227 if (mp->mp_ptrs[i] <= ptr)
8228 mp->mp_ptrs[i] += delta;
8230 mp->mp_upper += delta;
8233 /** Initial setup of a sorted-dups cursor.
8234 * Sorted duplicates are implemented as a sub-database for the given key.
8235 * The duplicate data items are actually keys of the sub-database.
8236 * Operations on the duplicate data items are performed using a sub-cursor
8237 * initialized when the sub-database is first accessed. This function does
8238 * the preliminary setup of the sub-cursor, filling in the fields that
8239 * depend only on the parent DB.
8240 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
8243 mdb_xcursor_init0(MDB_cursor *mc)
8245 MDB_xcursor *mx = mc->mc_xcursor;
8247 mx->mx_cursor.mc_xcursor = NULL;
8248 mx->mx_cursor.mc_txn = mc->mc_txn;
8249 mx->mx_cursor.mc_db = &mx->mx_db;
8250 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
8251 mx->mx_cursor.mc_dbi = mc->mc_dbi;
8252 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
8253 mx->mx_cursor.mc_snum = 0;
8254 mx->mx_cursor.mc_top = 0;
8255 MC_SET_OVPG(&mx->mx_cursor, NULL);
8256 mx->mx_cursor.mc_flags = C_SUB | (mc->mc_flags & (C_ORIG_RDONLY|C_WRITEMAP));
8257 mx->mx_dbx.md_name.mv_size = 0;
8258 mx->mx_dbx.md_name.mv_data = NULL;
8259 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
8260 mx->mx_dbx.md_dcmp = NULL;
8261 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
8264 /** Final setup of a sorted-dups cursor.
8265 * Sets up the fields that depend on the data from the main cursor.
8266 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
8267 * @param[in] node The data containing the #MDB_db record for the
8268 * sorted-dup database.
8271 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
8273 MDB_xcursor *mx = mc->mc_xcursor;
8275 mx->mx_cursor.mc_flags &= C_SUB|C_ORIG_RDONLY|C_WRITEMAP;
8276 if (node->mn_flags & F_SUBDATA) {
8277 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
8278 mx->mx_cursor.mc_pg[0] = 0;
8279 mx->mx_cursor.mc_snum = 0;
8280 mx->mx_cursor.mc_top = 0;
8282 MDB_page *fp = NODEDATA(node);
8283 mx->mx_db.md_pad = 0;
8284 mx->mx_db.md_flags = 0;
8285 mx->mx_db.md_depth = 1;
8286 mx->mx_db.md_branch_pages = 0;
8287 mx->mx_db.md_leaf_pages = 1;
8288 mx->mx_db.md_overflow_pages = 0;
8289 mx->mx_db.md_entries = NUMKEYS(fp);
8290 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
8291 mx->mx_cursor.mc_snum = 1;
8292 mx->mx_cursor.mc_top = 0;
8293 mx->mx_cursor.mc_flags |= C_INITIALIZED;
8294 mx->mx_cursor.mc_pg[0] = fp;
8295 mx->mx_cursor.mc_ki[0] = 0;
8296 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
8297 mx->mx_db.md_flags = MDB_DUPFIXED;
8298 mx->mx_db.md_pad = fp->mp_pad;
8299 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
8300 mx->mx_db.md_flags |= MDB_INTEGERKEY;
8303 DPRINTF(("Sub-db -%u root page %"Yu, mx->mx_cursor.mc_dbi,
8304 mx->mx_db.md_root));
8305 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DUPDATA;
8306 if (NEED_CMP_CLONG(mx->mx_dbx.md_cmp, mx->mx_db.md_pad))
8307 mx->mx_dbx.md_cmp = mdb_cmp_clong;
8311 /** Fixup a sorted-dups cursor due to underlying update.
8312 * Sets up some fields that depend on the data from the main cursor.
8313 * Almost the same as init1, but skips initialization steps if the
8314 * xcursor had already been used.
8315 * @param[in] mc The main cursor whose sorted-dups cursor is to be fixed up.
8316 * @param[in] src_mx The xcursor of an up-to-date cursor.
8317 * @param[in] new_dupdata True if converting from a non-#F_DUPDATA item.
8320 mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int new_dupdata)
8322 MDB_xcursor *mx = mc->mc_xcursor;
8325 mx->mx_cursor.mc_snum = 1;
8326 mx->mx_cursor.mc_top = 0;
8327 mx->mx_cursor.mc_flags |= C_INITIALIZED;
8328 mx->mx_cursor.mc_ki[0] = 0;
8329 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DUPDATA;
8330 #if UINT_MAX < MDB_SIZE_MAX /* matches mdb_xcursor_init1:NEED_CMP_CLONG() */
8331 mx->mx_dbx.md_cmp = src_mx->mx_dbx.md_cmp;
8333 } else if (!(mx->mx_cursor.mc_flags & C_INITIALIZED)) {
8336 mx->mx_db = src_mx->mx_db;
8337 mx->mx_cursor.mc_pg[0] = src_mx->mx_cursor.mc_pg[0];
8338 DPRINTF(("Sub-db -%u root page %"Yu, mx->mx_cursor.mc_dbi,
8339 mx->mx_db.md_root));
8342 /** Initialize a cursor for a given transaction and database. */
8344 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
8347 mc->mc_backup = NULL;
8350 mc->mc_db = &txn->mt_dbs[dbi];
8351 mc->mc_dbx = &txn->mt_dbxs[dbi];
8352 mc->mc_dbflag = &txn->mt_dbflags[dbi];
8357 MC_SET_OVPG(mc, NULL);
8358 mc->mc_flags = txn->mt_flags & (C_ORIG_RDONLY|C_WRITEMAP);
8359 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
8360 mdb_tassert(txn, mx != NULL);
8361 mc->mc_xcursor = mx;
8362 mdb_xcursor_init0(mc);
8364 mc->mc_xcursor = NULL;
8366 if (*mc->mc_dbflag & DB_STALE) {
8367 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
8372 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
8375 size_t size = sizeof(MDB_cursor);
8377 if (!ret || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
8380 if (txn->mt_flags & MDB_TXN_BLOCKED)
8383 if (dbi == FREE_DBI && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
8386 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
8387 size += sizeof(MDB_xcursor);
8389 if ((mc = malloc(size)) != NULL) {
8390 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
8391 if (txn->mt_cursors) {
8392 mc->mc_next = txn->mt_cursors[dbi];
8393 txn->mt_cursors[dbi] = mc;
8394 mc->mc_flags |= C_UNTRACK;
8406 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
8408 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi, DB_VALID))
8411 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
8414 if (txn->mt_flags & MDB_TXN_BLOCKED)
8417 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
8421 /* Return the count of duplicate data items for the current key */
8423 mdb_cursor_count(MDB_cursor *mc, mdb_size_t *countp)
8427 if (mc == NULL || countp == NULL)
8430 if (mc->mc_xcursor == NULL)
8431 return MDB_INCOMPATIBLE;
8433 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
8436 if (!(mc->mc_flags & C_INITIALIZED))
8439 if (!mc->mc_snum || (mc->mc_flags & C_EOF))
8440 return MDB_NOTFOUND;
8442 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
8443 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
8446 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
8449 *countp = mc->mc_xcursor->mx_db.md_entries;
8455 mdb_cursor_close(MDB_cursor *mc)
8458 MDB_CURSOR_UNREF(mc, 0);
8460 if (mc && !mc->mc_backup) {
8461 /* Remove from txn, if tracked.
8462 * A read-only txn (!C_UNTRACK) may have been freed already,
8463 * so do not peek inside it. Only write txns track cursors.
8465 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
8466 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
8467 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
8469 *prev = mc->mc_next;
8476 mdb_cursor_txn(MDB_cursor *mc)
8478 if (!mc) return NULL;
8483 mdb_cursor_dbi(MDB_cursor *mc)
8488 /** Replace the key for a branch node with a new key.
8489 * Set #MDB_TXN_ERROR on failure.
8490 * @param[in] mc Cursor pointing to the node to operate on.
8491 * @param[in] key The new key to use.
8492 * @return 0 on success, non-zero on failure.
8495 mdb_update_key(MDB_cursor *mc, MDB_val *key)
8501 int delta, ksize, oksize;
8502 indx_t ptr, i, numkeys, indx;
8505 indx = mc->mc_ki[mc->mc_top];
8506 mp = mc->mc_pg[mc->mc_top];
8507 node = NODEPTR(mp, indx);
8508 ptr = mp->mp_ptrs[indx];
8512 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
8513 k2.mv_data = NODEKEY(node);
8514 k2.mv_size = node->mn_ksize;
8515 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Yu,
8517 mdb_dkey(&k2, kbuf2),
8523 /* Sizes must be 2-byte aligned. */
8524 ksize = EVEN(key->mv_size);
8525 oksize = EVEN(node->mn_ksize);
8526 delta = ksize - oksize;
8528 /* Shift node contents if EVEN(key length) changed. */
8530 if (delta > 0 && SIZELEFT(mp) < delta) {
8532 /* not enough space left, do a delete and split */
8533 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
8534 pgno = NODEPGNO(node);
8535 mdb_node_del(mc, 0);
8536 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
8539 numkeys = NUMKEYS(mp);
8540 for (i = 0; i < numkeys; i++) {
8541 if (mp->mp_ptrs[i] <= ptr)
8542 mp->mp_ptrs[i] -= delta;
8545 base = (char *)mp + mp->mp_upper + PAGEBASE;
8546 len = ptr - mp->mp_upper + NODESIZE;
8547 memmove(base - delta, base, len);
8548 mp->mp_upper -= delta;
8550 node = NODEPTR(mp, indx);
8553 /* But even if no shift was needed, update ksize */
8554 if (node->mn_ksize != key->mv_size)
8555 node->mn_ksize = key->mv_size;
8558 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
8564 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
8566 /** Perform \b act while tracking temporary cursor \b mn */
8567 #define WITH_CURSOR_TRACKING(mn, act) do { \
8568 MDB_cursor dummy, *tracked, **tp = &(mn).mc_txn->mt_cursors[mn.mc_dbi]; \
8569 if ((mn).mc_flags & C_SUB) { \
8570 dummy.mc_flags = C_INITIALIZED; \
8571 dummy.mc_xcursor = (MDB_xcursor *)&(mn); \
8576 tracked->mc_next = *tp; \
8579 *tp = tracked->mc_next; \
8582 /** Move a node from csrc to cdst.
8585 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft)
8592 unsigned short flags;
8596 /* Mark src and dst as dirty. */
8597 if ((rc = mdb_page_touch(csrc)) ||
8598 (rc = mdb_page_touch(cdst)))
8601 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8602 key.mv_size = csrc->mc_db->md_pad;
8603 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
8605 data.mv_data = NULL;
8609 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
8610 mdb_cassert(csrc, !((size_t)srcnode & 1));
8611 srcpg = NODEPGNO(srcnode);
8612 flags = srcnode->mn_flags;
8613 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
8614 unsigned int snum = csrc->mc_snum;
8616 /* must find the lowest key below src */
8617 rc = mdb_page_search_lowest(csrc);
8620 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8621 key.mv_size = csrc->mc_db->md_pad;
8622 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
8624 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
8625 key.mv_size = NODEKSZ(s2);
8626 key.mv_data = NODEKEY(s2);
8628 csrc->mc_snum = snum--;
8629 csrc->mc_top = snum;
8631 key.mv_size = NODEKSZ(srcnode);
8632 key.mv_data = NODEKEY(srcnode);
8634 data.mv_size = NODEDSZ(srcnode);
8635 data.mv_data = NODEDATA(srcnode);
8637 mn.mc_xcursor = NULL;
8638 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
8639 unsigned int snum = cdst->mc_snum;
8642 /* must find the lowest key below dst */
8643 mdb_cursor_copy(cdst, &mn);
8644 rc = mdb_page_search_lowest(&mn);
8647 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
8648 bkey.mv_size = mn.mc_db->md_pad;
8649 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
8651 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
8652 bkey.mv_size = NODEKSZ(s2);
8653 bkey.mv_data = NODEKEY(s2);
8655 mn.mc_snum = snum--;
8658 rc = mdb_update_key(&mn, &bkey);
8663 DPRINTF(("moving %s node %u [%s] on page %"Yu" to node %u on page %"Yu,
8664 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
8665 csrc->mc_ki[csrc->mc_top],
8667 csrc->mc_pg[csrc->mc_top]->mp_pgno,
8668 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
8670 /* Add the node to the destination page.
8672 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
8673 if (rc != MDB_SUCCESS)
8676 /* Delete the node from the source page.
8678 mdb_node_del(csrc, key.mv_size);
8681 /* Adjust other cursors pointing to mp */
8682 MDB_cursor *m2, *m3;
8683 MDB_dbi dbi = csrc->mc_dbi;
8684 MDB_page *mpd, *mps;
8686 mps = csrc->mc_pg[csrc->mc_top];
8687 /* If we're adding on the left, bump others up */
8689 mpd = cdst->mc_pg[csrc->mc_top];
8690 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8691 if (csrc->mc_flags & C_SUB)
8692 m3 = &m2->mc_xcursor->mx_cursor;
8695 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
8698 m3->mc_pg[csrc->mc_top] == mpd &&
8699 m3->mc_ki[csrc->mc_top] >= cdst->mc_ki[csrc->mc_top]) {
8700 m3->mc_ki[csrc->mc_top]++;
8703 m3->mc_pg[csrc->mc_top] == mps &&
8704 m3->mc_ki[csrc->mc_top] == csrc->mc_ki[csrc->mc_top]) {
8705 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
8706 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
8707 m3->mc_ki[csrc->mc_top-1]++;
8709 if (XCURSOR_INITED(m3) && IS_LEAF(mps))
8710 XCURSOR_REFRESH(m3, m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
8713 /* Adding on the right, bump others down */
8715 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8716 if (csrc->mc_flags & C_SUB)
8717 m3 = &m2->mc_xcursor->mx_cursor;
8720 if (m3 == csrc) continue;
8721 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
8723 if (m3->mc_pg[csrc->mc_top] == mps) {
8724 if (!m3->mc_ki[csrc->mc_top]) {
8725 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
8726 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
8727 m3->mc_ki[csrc->mc_top-1]--;
8729 m3->mc_ki[csrc->mc_top]--;
8731 if (XCURSOR_INITED(m3) && IS_LEAF(mps))
8732 XCURSOR_REFRESH(m3, m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
8738 /* Update the parent separators.
8740 if (csrc->mc_ki[csrc->mc_top] == 0) {
8741 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
8742 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8743 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
8745 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
8746 key.mv_size = NODEKSZ(srcnode);
8747 key.mv_data = NODEKEY(srcnode);
8749 DPRINTF(("update separator for source page %"Yu" to [%s]",
8750 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
8751 mdb_cursor_copy(csrc, &mn);
8754 /* We want mdb_rebalance to find mn when doing fixups */
8755 WITH_CURSOR_TRACKING(mn,
8756 rc = mdb_update_key(&mn, &key));
8760 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
8762 indx_t ix = csrc->mc_ki[csrc->mc_top];
8763 nullkey.mv_size = 0;
8764 csrc->mc_ki[csrc->mc_top] = 0;
8765 rc = mdb_update_key(csrc, &nullkey);
8766 csrc->mc_ki[csrc->mc_top] = ix;
8767 mdb_cassert(csrc, rc == MDB_SUCCESS);
8771 if (cdst->mc_ki[cdst->mc_top] == 0) {
8772 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
8773 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8774 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
8776 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
8777 key.mv_size = NODEKSZ(srcnode);
8778 key.mv_data = NODEKEY(srcnode);
8780 DPRINTF(("update separator for destination page %"Yu" to [%s]",
8781 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
8782 mdb_cursor_copy(cdst, &mn);
8785 /* We want mdb_rebalance to find mn when doing fixups */
8786 WITH_CURSOR_TRACKING(mn,
8787 rc = mdb_update_key(&mn, &key));
8791 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
8793 indx_t ix = cdst->mc_ki[cdst->mc_top];
8794 nullkey.mv_size = 0;
8795 cdst->mc_ki[cdst->mc_top] = 0;
8796 rc = mdb_update_key(cdst, &nullkey);
8797 cdst->mc_ki[cdst->mc_top] = ix;
8798 mdb_cassert(cdst, rc == MDB_SUCCESS);
8805 /** Merge one page into another.
8806 * The nodes from the page pointed to by \b csrc will
8807 * be copied to the page pointed to by \b cdst and then
8808 * the \b csrc page will be freed.
8809 * @param[in] csrc Cursor pointing to the source page.
8810 * @param[in] cdst Cursor pointing to the destination page.
8811 * @return 0 on success, non-zero on failure.
8814 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
8816 MDB_page *psrc, *pdst;
8823 psrc = csrc->mc_pg[csrc->mc_top];
8824 pdst = cdst->mc_pg[cdst->mc_top];
8826 DPRINTF(("merging page %"Yu" into %"Yu, psrc->mp_pgno, pdst->mp_pgno));
8828 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
8829 mdb_cassert(csrc, cdst->mc_snum > 1);
8831 /* Mark dst as dirty. */
8832 if ((rc = mdb_page_touch(cdst)))
8835 /* get dst page again now that we've touched it. */
8836 pdst = cdst->mc_pg[cdst->mc_top];
8838 /* Move all nodes from src to dst.
8840 j = nkeys = NUMKEYS(pdst);
8841 if (IS_LEAF2(psrc)) {
8842 key.mv_size = csrc->mc_db->md_pad;
8843 key.mv_data = METADATA(psrc);
8844 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
8845 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
8846 if (rc != MDB_SUCCESS)
8848 key.mv_data = (char *)key.mv_data + key.mv_size;
8851 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
8852 srcnode = NODEPTR(psrc, i);
8853 if (i == 0 && IS_BRANCH(psrc)) {
8856 mdb_cursor_copy(csrc, &mn);
8857 mn.mc_xcursor = NULL;
8858 /* must find the lowest key below src */
8859 rc = mdb_page_search_lowest(&mn);
8862 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
8863 key.mv_size = mn.mc_db->md_pad;
8864 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
8866 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
8867 key.mv_size = NODEKSZ(s2);
8868 key.mv_data = NODEKEY(s2);
8871 key.mv_size = srcnode->mn_ksize;
8872 key.mv_data = NODEKEY(srcnode);
8875 data.mv_size = NODEDSZ(srcnode);
8876 data.mv_data = NODEDATA(srcnode);
8877 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
8878 if (rc != MDB_SUCCESS)
8883 DPRINTF(("dst page %"Yu" now has %u keys (%.1f%% filled)",
8884 pdst->mp_pgno, NUMKEYS(pdst),
8885 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
8887 /* Unlink the src page from parent and add to free list.
8890 mdb_node_del(csrc, 0);
8891 if (csrc->mc_ki[csrc->mc_top] == 0) {
8893 rc = mdb_update_key(csrc, &key);
8901 psrc = csrc->mc_pg[csrc->mc_top];
8902 /* If not operating on FreeDB, allow this page to be reused
8903 * in this txn. Otherwise just add to free list.
8905 rc = mdb_page_loose(csrc, psrc);
8909 csrc->mc_db->md_leaf_pages--;
8911 csrc->mc_db->md_branch_pages--;
8913 /* Adjust other cursors pointing to mp */
8914 MDB_cursor *m2, *m3;
8915 MDB_dbi dbi = csrc->mc_dbi;
8916 unsigned int top = csrc->mc_top;
8918 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8919 if (csrc->mc_flags & C_SUB)
8920 m3 = &m2->mc_xcursor->mx_cursor;
8923 if (m3 == csrc) continue;
8924 if (m3->mc_snum < csrc->mc_snum) continue;
8925 if (m3->mc_pg[top] == psrc) {
8926 m3->mc_pg[top] = pdst;
8927 m3->mc_ki[top] += nkeys;
8928 m3->mc_ki[top-1] = cdst->mc_ki[top-1];
8929 } else if (m3->mc_pg[top-1] == csrc->mc_pg[top-1] &&
8930 m3->mc_ki[top-1] > csrc->mc_ki[top-1]) {
8933 if (XCURSOR_INITED(m3) && IS_LEAF(psrc))
8934 XCURSOR_REFRESH(m3, m3->mc_pg[top], m3->mc_ki[top]);
8938 unsigned int snum = cdst->mc_snum;
8939 uint16_t depth = cdst->mc_db->md_depth;
8940 mdb_cursor_pop(cdst);
8941 rc = mdb_rebalance(cdst);
8942 /* Did the tree height change? */
8943 if (depth != cdst->mc_db->md_depth)
8944 snum += cdst->mc_db->md_depth - depth;
8945 cdst->mc_snum = snum;
8946 cdst->mc_top = snum-1;
8951 /** Copy the contents of a cursor.
8952 * @param[in] csrc The cursor to copy from.
8953 * @param[out] cdst The cursor to copy to.
8956 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
8960 cdst->mc_txn = csrc->mc_txn;
8961 cdst->mc_dbi = csrc->mc_dbi;
8962 cdst->mc_db = csrc->mc_db;
8963 cdst->mc_dbx = csrc->mc_dbx;
8964 cdst->mc_snum = csrc->mc_snum;
8965 cdst->mc_top = csrc->mc_top;
8966 cdst->mc_flags = csrc->mc_flags;
8967 MC_SET_OVPG(cdst, MC_OVPG(csrc));
8969 for (i=0; i<csrc->mc_snum; i++) {
8970 cdst->mc_pg[i] = csrc->mc_pg[i];
8971 cdst->mc_ki[i] = csrc->mc_ki[i];
8975 /** Rebalance the tree after a delete operation.
8976 * @param[in] mc Cursor pointing to the page where rebalancing
8978 * @return 0 on success, non-zero on failure.
8981 mdb_rebalance(MDB_cursor *mc)
8985 unsigned int ptop, minkeys, thresh;
8989 if (IS_BRANCH(mc->mc_pg[mc->mc_top])) {
8994 thresh = FILL_THRESHOLD;
8996 DPRINTF(("rebalancing %s page %"Yu" (has %u keys, %.1f%% full)",
8997 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
8998 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
8999 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
9001 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= thresh &&
9002 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
9003 DPRINTF(("no need to rebalance page %"Yu", above fill threshold",
9004 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
9008 if (mc->mc_snum < 2) {
9009 MDB_page *mp = mc->mc_pg[0];
9011 DPUTS("Can't rebalance a subpage, ignoring");
9014 if (NUMKEYS(mp) == 0) {
9015 DPUTS("tree is completely empty");
9016 mc->mc_db->md_root = P_INVALID;
9017 mc->mc_db->md_depth = 0;
9018 mc->mc_db->md_leaf_pages = 0;
9019 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
9022 /* Adjust cursors pointing to mp */
9025 mc->mc_flags &= ~C_INITIALIZED;
9027 MDB_cursor *m2, *m3;
9028 MDB_dbi dbi = mc->mc_dbi;
9030 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9031 if (mc->mc_flags & C_SUB)
9032 m3 = &m2->mc_xcursor->mx_cursor;
9035 if (!(m3->mc_flags & C_INITIALIZED) || (m3->mc_snum < mc->mc_snum))
9037 if (m3->mc_pg[0] == mp) {
9040 m3->mc_flags &= ~C_INITIALIZED;
9044 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
9046 DPUTS("collapsing root page!");
9047 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
9050 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
9051 rc = mdb_page_get(mc, mc->mc_db->md_root, &mc->mc_pg[0], NULL);
9054 mc->mc_db->md_depth--;
9055 mc->mc_db->md_branch_pages--;
9056 mc->mc_ki[0] = mc->mc_ki[1];
9057 for (i = 1; i<mc->mc_db->md_depth; i++) {
9058 mc->mc_pg[i] = mc->mc_pg[i+1];
9059 mc->mc_ki[i] = mc->mc_ki[i+1];
9062 /* Adjust other cursors pointing to mp */
9063 MDB_cursor *m2, *m3;
9064 MDB_dbi dbi = mc->mc_dbi;
9066 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9067 if (mc->mc_flags & C_SUB)
9068 m3 = &m2->mc_xcursor->mx_cursor;
9071 if (m3 == mc) continue;
9072 if (!(m3->mc_flags & C_INITIALIZED))
9074 if (m3->mc_pg[0] == mp) {
9075 for (i=0; i<mc->mc_db->md_depth; i++) {
9076 m3->mc_pg[i] = m3->mc_pg[i+1];
9077 m3->mc_ki[i] = m3->mc_ki[i+1];
9085 DPUTS("root page doesn't need rebalancing");
9089 /* The parent (branch page) must have at least 2 pointers,
9090 * otherwise the tree is invalid.
9092 ptop = mc->mc_top-1;
9093 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
9095 /* Leaf page fill factor is below the threshold.
9096 * Try to move keys from left or right neighbor, or
9097 * merge with a neighbor page.
9102 mdb_cursor_copy(mc, &mn);
9103 mn.mc_xcursor = NULL;
9105 oldki = mc->mc_ki[mc->mc_top];
9106 if (mc->mc_ki[ptop] == 0) {
9107 /* We're the leftmost leaf in our parent.
9109 DPUTS("reading right neighbor");
9111 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
9112 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
9115 mn.mc_ki[mn.mc_top] = 0;
9116 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
9119 /* There is at least one neighbor to the left.
9121 DPUTS("reading left neighbor");
9123 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
9124 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
9127 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
9128 mc->mc_ki[mc->mc_top] = 0;
9132 DPRINTF(("found neighbor page %"Yu" (%u keys, %.1f%% full)",
9133 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
9134 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
9136 /* If the neighbor page is above threshold and has enough keys,
9137 * move one key from it. Otherwise we should try to merge them.
9138 * (A branch page must never have less than 2 keys.)
9140 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= thresh && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
9141 rc = mdb_node_move(&mn, mc, fromleft);
9143 /* if we inserted on left, bump position up */
9148 rc = mdb_page_merge(&mn, mc);
9150 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
9151 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
9152 /* We want mdb_rebalance to find mn when doing fixups */
9153 WITH_CURSOR_TRACKING(mn,
9154 rc = mdb_page_merge(mc, &mn));
9155 mdb_cursor_copy(&mn, mc);
9157 mc->mc_flags &= ~C_EOF;
9159 mc->mc_ki[mc->mc_top] = oldki;
9163 /** Complete a delete operation started by #mdb_cursor_del(). */
9165 mdb_cursor_del0(MDB_cursor *mc)
9171 MDB_cursor *m2, *m3;
9172 MDB_dbi dbi = mc->mc_dbi;
9174 ki = mc->mc_ki[mc->mc_top];
9175 mp = mc->mc_pg[mc->mc_top];
9176 mdb_node_del(mc, mc->mc_db->md_pad);
9177 mc->mc_db->md_entries--;
9179 /* Adjust other cursors pointing to mp */
9180 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9181 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
9182 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9184 if (m3 == mc || m3->mc_snum < mc->mc_snum)
9186 if (m3->mc_pg[mc->mc_top] == mp) {
9187 if (m3->mc_ki[mc->mc_top] == ki) {
9188 m3->mc_flags |= C_DEL;
9189 if (mc->mc_db->md_flags & MDB_DUPSORT) {
9190 /* Sub-cursor referred into dataset which is gone */
9191 m3->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
9194 } else if (m3->mc_ki[mc->mc_top] > ki) {
9195 m3->mc_ki[mc->mc_top]--;
9197 if (XCURSOR_INITED(m3))
9198 XCURSOR_REFRESH(m3, m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
9202 rc = mdb_rebalance(mc);
9204 if (rc == MDB_SUCCESS) {
9205 /* DB is totally empty now, just bail out.
9206 * Other cursors adjustments were already done
9207 * by mdb_rebalance and aren't needed here.
9212 mp = mc->mc_pg[mc->mc_top];
9213 nkeys = NUMKEYS(mp);
9215 /* Adjust other cursors pointing to mp */
9216 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
9217 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
9218 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9220 if (m3->mc_snum < mc->mc_snum)
9222 if (m3->mc_pg[mc->mc_top] == mp) {
9223 /* if m3 points past last node in page, find next sibling */
9224 if (m3->mc_ki[mc->mc_top] >= mc->mc_ki[mc->mc_top]) {
9225 if (m3->mc_ki[mc->mc_top] >= nkeys) {
9226 rc = mdb_cursor_sibling(m3, 1);
9227 if (rc == MDB_NOTFOUND) {
9228 m3->mc_flags |= C_EOF;
9233 if (mc->mc_db->md_flags & MDB_DUPSORT) {
9234 MDB_node *node = NODEPTR(m3->mc_pg[m3->mc_top], m3->mc_ki[m3->mc_top]);
9235 /* If this node is a fake page, it needs to be reinited
9236 * because its data has moved. But just reset mc_pg[0]
9237 * if the xcursor is already live.
9239 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) {
9240 if (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)
9241 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
9243 mdb_xcursor_init1(m3, node);
9249 mc->mc_flags |= C_DEL;
9253 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
9258 mdb_del(MDB_txn *txn, MDB_dbi dbi,
9259 MDB_val *key, MDB_val *data)
9261 if (!key || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9264 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
9265 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
9267 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
9268 /* must ignore any data */
9272 return mdb_del0(txn, dbi, key, data, 0);
9276 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
9277 MDB_val *key, MDB_val *data, unsigned flags)
9282 MDB_val rdata, *xdata;
9286 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
9288 mdb_cursor_init(&mc, txn, dbi, &mx);
9297 flags |= MDB_NODUPDATA;
9299 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
9301 /* let mdb_page_split know about this cursor if needed:
9302 * delete will trigger a rebalance; if it needs to move
9303 * a node from one page to another, it will have to
9304 * update the parent's separator key(s). If the new sepkey
9305 * is larger than the current one, the parent page may
9306 * run out of space, triggering a split. We need this
9307 * cursor to be consistent until the end of the rebalance.
9309 mc.mc_next = txn->mt_cursors[dbi];
9310 txn->mt_cursors[dbi] = &mc;
9311 rc = mdb_cursor_del(&mc, flags);
9312 txn->mt_cursors[dbi] = mc.mc_next;
9317 /** Split a page and insert a new node.
9318 * Set #MDB_TXN_ERROR on failure.
9319 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
9320 * The cursor will be updated to point to the actual page and index where
9321 * the node got inserted after the split.
9322 * @param[in] newkey The key for the newly inserted node.
9323 * @param[in] newdata The data for the newly inserted node.
9324 * @param[in] newpgno The page number, if the new node is a branch node.
9325 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
9326 * @return 0 on success, non-zero on failure.
9329 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
9330 unsigned int nflags)
9333 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
9336 int i, j, split_indx, nkeys, pmax;
9337 MDB_env *env = mc->mc_txn->mt_env;
9339 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
9340 MDB_page *copy = NULL;
9341 MDB_page *mp, *rp, *pp;
9346 mp = mc->mc_pg[mc->mc_top];
9347 newindx = mc->mc_ki[mc->mc_top];
9348 nkeys = NUMKEYS(mp);
9350 DPRINTF(("-----> splitting %s page %"Yu" and adding [%s] at index %i/%i",
9351 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
9352 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
9354 /* Create a right sibling. */
9355 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
9357 rp->mp_pad = mp->mp_pad;
9358 DPRINTF(("new right sibling: page %"Yu, rp->mp_pgno));
9360 /* Usually when splitting the root page, the cursor
9361 * height is 1. But when called from mdb_update_key,
9362 * the cursor height may be greater because it walks
9363 * up the stack while finding the branch slot to update.
9365 if (mc->mc_top < 1) {
9366 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
9368 /* shift current top to make room for new parent */
9369 for (i=mc->mc_snum; i>0; i--) {
9370 mc->mc_pg[i] = mc->mc_pg[i-1];
9371 mc->mc_ki[i] = mc->mc_ki[i-1];
9375 mc->mc_db->md_root = pp->mp_pgno;
9376 DPRINTF(("root split! new root = %"Yu, pp->mp_pgno));
9377 new_root = mc->mc_db->md_depth++;
9379 /* Add left (implicit) pointer. */
9380 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
9381 /* undo the pre-push */
9382 mc->mc_pg[0] = mc->mc_pg[1];
9383 mc->mc_ki[0] = mc->mc_ki[1];
9384 mc->mc_db->md_root = mp->mp_pgno;
9385 mc->mc_db->md_depth--;
9392 ptop = mc->mc_top-1;
9393 DPRINTF(("parent branch page is %"Yu, mc->mc_pg[ptop]->mp_pgno));
9396 mdb_cursor_copy(mc, &mn);
9397 mn.mc_xcursor = NULL;
9398 mn.mc_pg[mn.mc_top] = rp;
9399 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
9401 if (nflags & MDB_APPEND) {
9402 mn.mc_ki[mn.mc_top] = 0;
9404 split_indx = newindx;
9408 split_indx = (nkeys+1) / 2;
9413 unsigned int lsize, rsize, ksize;
9414 /* Move half of the keys to the right sibling */
9415 x = mc->mc_ki[mc->mc_top] - split_indx;
9416 ksize = mc->mc_db->md_pad;
9417 split = LEAF2KEY(mp, split_indx, ksize);
9418 rsize = (nkeys - split_indx) * ksize;
9419 lsize = (nkeys - split_indx) * sizeof(indx_t);
9420 mp->mp_lower -= lsize;
9421 rp->mp_lower += lsize;
9422 mp->mp_upper += rsize - lsize;
9423 rp->mp_upper -= rsize - lsize;
9424 sepkey.mv_size = ksize;
9425 if (newindx == split_indx) {
9426 sepkey.mv_data = newkey->mv_data;
9428 sepkey.mv_data = split;
9431 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
9432 memcpy(rp->mp_ptrs, split, rsize);
9433 sepkey.mv_data = rp->mp_ptrs;
9434 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
9435 memcpy(ins, newkey->mv_data, ksize);
9436 mp->mp_lower += sizeof(indx_t);
9437 mp->mp_upper -= ksize - sizeof(indx_t);
9440 memcpy(rp->mp_ptrs, split, x * ksize);
9441 ins = LEAF2KEY(rp, x, ksize);
9442 memcpy(ins, newkey->mv_data, ksize);
9443 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
9444 rp->mp_lower += sizeof(indx_t);
9445 rp->mp_upper -= ksize - sizeof(indx_t);
9446 mc->mc_ki[mc->mc_top] = x;
9449 int psize, nsize, k;
9450 /* Maximum free space in an empty page */
9451 pmax = env->me_psize - PAGEHDRSZ;
9453 nsize = mdb_leaf_size(env, newkey, newdata);
9455 nsize = mdb_branch_size(env, newkey);
9456 nsize = EVEN(nsize);
9458 /* grab a page to hold a temporary copy */
9459 copy = mdb_page_malloc(mc->mc_txn, 1);
9464 copy->mp_pgno = mp->mp_pgno;
9465 copy->mp_flags = mp->mp_flags;
9466 copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
9467 copy->mp_upper = env->me_psize - PAGEBASE;
9469 /* prepare to insert */
9470 for (i=0, j=0; i<nkeys; i++) {
9472 copy->mp_ptrs[j++] = 0;
9474 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
9477 /* When items are relatively large the split point needs
9478 * to be checked, because being off-by-one will make the
9479 * difference between success or failure in mdb_node_add.
9481 * It's also relevant if a page happens to be laid out
9482 * such that one half of its nodes are all "small" and
9483 * the other half of its nodes are "large." If the new
9484 * item is also "large" and falls on the half with
9485 * "large" nodes, it also may not fit.
9487 * As a final tweak, if the new item goes on the last
9488 * spot on the page (and thus, onto the new page), bias
9489 * the split so the new page is emptier than the old page.
9490 * This yields better packing during sequential inserts.
9492 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
9493 /* Find split point */
9495 if (newindx <= split_indx || newindx >= nkeys) {
9497 k = newindx >= nkeys ? nkeys : split_indx+1+IS_LEAF(mp);
9502 for (; i!=k; i+=j) {
9507 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
9508 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
9510 if (F_ISSET(node->mn_flags, F_BIGDATA))
9511 psize += sizeof(pgno_t);
9513 psize += NODEDSZ(node);
9515 psize = EVEN(psize);
9517 if (psize > pmax || i == k-j) {
9518 split_indx = i + (j<0);
9523 if (split_indx == newindx) {
9524 sepkey.mv_size = newkey->mv_size;
9525 sepkey.mv_data = newkey->mv_data;
9527 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
9528 sepkey.mv_size = node->mn_ksize;
9529 sepkey.mv_data = NODEKEY(node);
9534 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
9536 /* Copy separator key to the parent.
9538 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
9539 int snum = mc->mc_snum;
9543 /* We want other splits to find mn when doing fixups */
9544 WITH_CURSOR_TRACKING(mn,
9545 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0));
9550 if (mc->mc_snum > snum) {
9553 /* Right page might now have changed parent.
9554 * Check if left page also changed parent.
9556 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
9557 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
9558 for (i=0; i<ptop; i++) {
9559 mc->mc_pg[i] = mn.mc_pg[i];
9560 mc->mc_ki[i] = mn.mc_ki[i];
9562 mc->mc_pg[ptop] = mn.mc_pg[ptop];
9563 if (mn.mc_ki[ptop]) {
9564 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
9566 /* find right page's left sibling */
9567 mc->mc_ki[ptop] = mn.mc_ki[ptop];
9568 rc = mdb_cursor_sibling(mc, 0);
9573 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
9576 if (rc != MDB_SUCCESS) {
9577 if (rc == MDB_NOTFOUND) /* improper mdb_cursor_sibling() result */
9581 if (nflags & MDB_APPEND) {
9582 mc->mc_pg[mc->mc_top] = rp;
9583 mc->mc_ki[mc->mc_top] = 0;
9584 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
9587 for (i=0; i<mc->mc_top; i++)
9588 mc->mc_ki[i] = mn.mc_ki[i];
9589 } else if (!IS_LEAF2(mp)) {
9591 mc->mc_pg[mc->mc_top] = rp;
9596 rkey.mv_data = newkey->mv_data;
9597 rkey.mv_size = newkey->mv_size;
9603 /* Update index for the new key. */
9604 mc->mc_ki[mc->mc_top] = j;
9606 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
9607 rkey.mv_data = NODEKEY(node);
9608 rkey.mv_size = node->mn_ksize;
9610 xdata.mv_data = NODEDATA(node);
9611 xdata.mv_size = NODEDSZ(node);
9614 pgno = NODEPGNO(node);
9615 flags = node->mn_flags;
9618 if (!IS_LEAF(mp) && j == 0) {
9619 /* First branch index doesn't need key data. */
9623 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
9629 mc->mc_pg[mc->mc_top] = copy;
9634 } while (i != split_indx);
9636 nkeys = NUMKEYS(copy);
9637 for (i=0; i<nkeys; i++)
9638 mp->mp_ptrs[i] = copy->mp_ptrs[i];
9639 mp->mp_lower = copy->mp_lower;
9640 mp->mp_upper = copy->mp_upper;
9641 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
9642 env->me_psize - copy->mp_upper - PAGEBASE);
9644 /* reset back to original page */
9645 if (newindx < split_indx) {
9646 mc->mc_pg[mc->mc_top] = mp;
9648 mc->mc_pg[mc->mc_top] = rp;
9650 /* Make sure mc_ki is still valid.
9652 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
9653 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
9654 for (i=0; i<=ptop; i++) {
9655 mc->mc_pg[i] = mn.mc_pg[i];
9656 mc->mc_ki[i] = mn.mc_ki[i];
9660 if (nflags & MDB_RESERVE) {
9661 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
9662 if (!(node->mn_flags & F_BIGDATA))
9663 newdata->mv_data = NODEDATA(node);
9666 if (newindx >= split_indx) {
9667 mc->mc_pg[mc->mc_top] = rp;
9669 /* Make sure mc_ki is still valid.
9671 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
9672 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
9673 for (i=0; i<=ptop; i++) {
9674 mc->mc_pg[i] = mn.mc_pg[i];
9675 mc->mc_ki[i] = mn.mc_ki[i];
9682 /* Adjust other cursors pointing to mp */
9683 MDB_cursor *m2, *m3;
9684 MDB_dbi dbi = mc->mc_dbi;
9685 nkeys = NUMKEYS(mp);
9687 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9688 if (mc->mc_flags & C_SUB)
9689 m3 = &m2->mc_xcursor->mx_cursor;
9694 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9698 /* sub cursors may be on different DB */
9699 if (m3->mc_pg[0] != mp)
9702 for (k=new_root; k>=0; k--) {
9703 m3->mc_ki[k+1] = m3->mc_ki[k];
9704 m3->mc_pg[k+1] = m3->mc_pg[k];
9706 if (m3->mc_ki[0] >= nkeys) {
9711 m3->mc_pg[0] = mc->mc_pg[0];
9715 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
9716 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
9717 m3->mc_ki[mc->mc_top]++;
9718 if (m3->mc_ki[mc->mc_top] >= nkeys) {
9719 m3->mc_pg[mc->mc_top] = rp;
9720 m3->mc_ki[mc->mc_top] -= nkeys;
9721 for (i=0; i<mc->mc_top; i++) {
9722 m3->mc_ki[i] = mn.mc_ki[i];
9723 m3->mc_pg[i] = mn.mc_pg[i];
9726 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
9727 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
9730 if (XCURSOR_INITED(m3) && IS_LEAF(mp))
9731 XCURSOR_REFRESH(m3, m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
9734 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
9737 if (copy) /* tmp page */
9738 mdb_page_free(env, copy);
9740 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
9745 mdb_put(MDB_txn *txn, MDB_dbi dbi,
9746 MDB_val *key, MDB_val *data, unsigned int flags)
9752 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9755 if (flags & ~(MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP))
9758 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
9759 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
9761 mdb_cursor_init(&mc, txn, dbi, &mx);
9762 mc.mc_next = txn->mt_cursors[dbi];
9763 txn->mt_cursors[dbi] = &mc;
9764 rc = mdb_cursor_put(&mc, key, data, flags);
9765 txn->mt_cursors[dbi] = mc.mc_next;
9770 #define MDB_WBUF (1024*1024)
9772 #define MDB_EOF 0x10 /**< #mdb_env_copyfd1() is done reading */
9774 /** State needed for a double-buffering compacting copy. */
9775 typedef struct mdb_copy {
9778 pthread_mutex_t mc_mutex;
9779 pthread_cond_t mc_cond; /**< Condition variable for #mc_new */
9784 pgno_t mc_next_pgno;
9786 int mc_toggle; /**< Buffer number in provider */
9787 int mc_new; /**< (0-2 buffers to write) | (#MDB_EOF at end) */
9788 /** Error code. Never cleared if set. Both threads can set nonzero
9789 * to fail the copy. Not mutex-protected, LMDB expects atomic int.
9791 volatile int mc_error;
9794 /** Dedicated writer thread for compacting copy. */
9795 static THREAD_RET ESECT CALL_CONV
9796 mdb_env_copythr(void *arg)
9800 int toggle = 0, wsize, rc;
9803 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
9806 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
9810 sigaddset(&set, SIGPIPE);
9811 if ((rc = pthread_sigmask(SIG_BLOCK, &set, NULL)) != 0)
9816 pthread_mutex_lock(&my->mc_mutex);
9819 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
9820 if (my->mc_new == 0 + MDB_EOF) /* 0 buffers, just EOF */
9822 wsize = my->mc_wlen[toggle];
9823 ptr = my->mc_wbuf[toggle];
9826 while (wsize > 0 && !my->mc_error) {
9827 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
9830 #if defined(SIGPIPE) && !defined(_WIN32)
9832 /* Collect the pending SIGPIPE, otherwise at least OS X
9833 * gives it to the process on thread-exit (ITS#8504).
9836 sigwait(&set, &tmp);
9840 } else if (len > 0) {
9853 /* If there's an overflow page tail, write it too */
9854 if (my->mc_olen[toggle]) {
9855 wsize = my->mc_olen[toggle];
9856 ptr = my->mc_over[toggle];
9857 my->mc_olen[toggle] = 0;
9860 my->mc_wlen[toggle] = 0;
9862 /* Return the empty buffer to provider */
9864 pthread_cond_signal(&my->mc_cond);
9866 pthread_mutex_unlock(&my->mc_mutex);
9867 return (THREAD_RET)0;
9871 /** Give buffer and/or #MDB_EOF to writer thread, await unused buffer.
9873 * @param[in] my control structure.
9874 * @param[in] adjust (1 to hand off 1 buffer) | (MDB_EOF when ending).
9877 mdb_env_cthr_toggle(mdb_copy *my, int adjust)
9879 pthread_mutex_lock(&my->mc_mutex);
9880 my->mc_new += adjust;
9881 pthread_cond_signal(&my->mc_cond);
9882 while (my->mc_new & 2) /* both buffers in use */
9883 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
9884 pthread_mutex_unlock(&my->mc_mutex);
9886 my->mc_toggle ^= (adjust & 1);
9887 /* Both threads reset mc_wlen, to be safe from threading errors */
9888 my->mc_wlen[my->mc_toggle] = 0;
9889 return my->mc_error;
9892 /** Depth-first tree traversal for compacting copy.
9893 * @param[in] my control structure.
9894 * @param[in,out] pg database root.
9895 * @param[in] flags includes #F_DUPDATA if it is a sorted-duplicate sub-DB.
9898 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
9900 MDB_cursor mc = {0};
9902 MDB_page *mo, *mp, *leaf;
9907 /* Empty DB, nothing to do */
9908 if (*pg == P_INVALID)
9912 mc.mc_txn = my->mc_txn;
9913 mc.mc_flags = my->mc_txn->mt_flags & (C_ORIG_RDONLY|C_WRITEMAP);
9915 rc = mdb_page_get(&mc, *pg, &mc.mc_pg[0], NULL);
9918 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
9922 /* Make cursor pages writable */
9923 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
9927 for (i=0; i<mc.mc_top; i++) {
9928 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
9929 mc.mc_pg[i] = (MDB_page *)ptr;
9930 ptr += my->mc_env->me_psize;
9933 /* This is writable space for a leaf page. Usually not needed. */
9934 leaf = (MDB_page *)ptr;
9936 toggle = my->mc_toggle;
9937 while (mc.mc_snum > 0) {
9939 mp = mc.mc_pg[mc.mc_top];
9943 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
9944 for (i=0; i<n; i++) {
9945 ni = NODEPTR(mp, i);
9946 if (ni->mn_flags & F_BIGDATA) {
9950 /* Need writable leaf */
9952 mc.mc_pg[mc.mc_top] = leaf;
9953 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
9955 ni = NODEPTR(mp, i);
9958 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9959 memcpy(NODEDATA(ni), &my->mc_next_pgno, sizeof(pgno_t));
9960 rc = mdb_page_get(&mc, pg, &omp, NULL);
9963 if (my->mc_wlen[toggle] >= MDB_WBUF) {
9964 rc = mdb_env_cthr_toggle(my, 1);
9967 toggle = my->mc_toggle;
9969 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
9970 memcpy(mo, omp, my->mc_env->me_psize);
9971 mo->mp_pgno = my->mc_next_pgno;
9972 my->mc_next_pgno += omp->mp_pages;
9973 my->mc_wlen[toggle] += my->mc_env->me_psize;
9974 if (omp->mp_pages > 1) {
9975 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
9976 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
9977 rc = mdb_env_cthr_toggle(my, 1);
9980 toggle = my->mc_toggle;
9982 } else if (ni->mn_flags & F_SUBDATA) {
9985 /* Need writable leaf */
9987 mc.mc_pg[mc.mc_top] = leaf;
9988 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
9990 ni = NODEPTR(mp, i);
9993 memcpy(&db, NODEDATA(ni), sizeof(db));
9994 my->mc_toggle = toggle;
9995 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
9998 toggle = my->mc_toggle;
9999 memcpy(NODEDATA(ni), &db, sizeof(db));
10004 mc.mc_ki[mc.mc_top]++;
10005 if (mc.mc_ki[mc.mc_top] < n) {
10008 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
10010 rc = mdb_page_get(&mc, pg, &mp, NULL);
10015 mc.mc_ki[mc.mc_top] = 0;
10016 if (IS_BRANCH(mp)) {
10017 /* Whenever we advance to a sibling branch page,
10018 * we must proceed all the way down to its first leaf.
10020 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
10023 mc.mc_pg[mc.mc_top] = mp;
10027 if (my->mc_wlen[toggle] >= MDB_WBUF) {
10028 rc = mdb_env_cthr_toggle(my, 1);
10031 toggle = my->mc_toggle;
10033 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
10034 mdb_page_copy(mo, mp, my->mc_env->me_psize);
10035 mo->mp_pgno = my->mc_next_pgno++;
10036 my->mc_wlen[toggle] += my->mc_env->me_psize;
10038 /* Update parent if there is one */
10039 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
10040 SETPGNO(ni, mo->mp_pgno);
10041 mdb_cursor_pop(&mc);
10043 /* Otherwise we're done */
10053 /** Copy environment with compaction. */
10055 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
10060 MDB_txn *txn = NULL;
10062 pgno_t root, new_root;
10063 int rc = MDB_SUCCESS;
10066 if (!(my.mc_mutex = CreateMutex(NULL, FALSE, NULL)) ||
10067 !(my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL))) {
10071 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_os_psize);
10072 if (my.mc_wbuf[0] == NULL) {
10073 /* _aligned_malloc() sets errno, but we use Windows error codes */
10074 rc = ERROR_NOT_ENOUGH_MEMORY;
10078 if ((rc = pthread_mutex_init(&my.mc_mutex, NULL)) != 0)
10080 if ((rc = pthread_cond_init(&my.mc_cond, NULL)) != 0)
10082 #ifdef HAVE_MEMALIGN
10083 my.mc_wbuf[0] = memalign(env->me_os_psize, MDB_WBUF*2);
10084 if (my.mc_wbuf[0] == NULL) {
10091 if ((rc = posix_memalign(&p, env->me_os_psize, MDB_WBUF*2)) != 0)
10097 memset(my.mc_wbuf[0], 0, MDB_WBUF*2);
10098 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
10099 my.mc_next_pgno = NUM_METAS;
10102 rc = THREAD_CREATE(thr, mdb_env_copythr, &my);
10106 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
10110 mp = (MDB_page *)my.mc_wbuf[0];
10111 memset(mp, 0, NUM_METAS * env->me_psize);
10113 mp->mp_flags = P_META;
10114 mm = (MDB_meta *)METADATA(mp);
10115 mdb_env_init_meta0(env, mm);
10116 mm->mm_address = env->me_metas[0]->mm_address;
10118 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
10120 mp->mp_flags = P_META;
10121 *(MDB_meta *)METADATA(mp) = *mm;
10122 mm = (MDB_meta *)METADATA(mp);
10124 /* Set metapage 1 with current main DB */
10125 root = new_root = txn->mt_dbs[MAIN_DBI].md_root;
10126 if (root != P_INVALID) {
10127 /* Count free pages + freeDB pages. Subtract from last_pg
10128 * to find the new last_pg, which also becomes the new root.
10130 MDB_ID freecount = 0;
10133 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
10134 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
10135 freecount += *(MDB_ID *)data.mv_data;
10136 if (rc != MDB_NOTFOUND)
10138 freecount += txn->mt_dbs[FREE_DBI].md_branch_pages +
10139 txn->mt_dbs[FREE_DBI].md_leaf_pages +
10140 txn->mt_dbs[FREE_DBI].md_overflow_pages;
10142 new_root = txn->mt_next_pgno - 1 - freecount;
10143 mm->mm_last_pg = new_root;
10144 mm->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
10145 mm->mm_dbs[MAIN_DBI].md_root = new_root;
10147 /* When the DB is empty, handle it specially to
10148 * fix any breakage like page leaks from ITS#8174.
10150 mm->mm_dbs[MAIN_DBI].md_flags = txn->mt_dbs[MAIN_DBI].md_flags;
10152 if (root != P_INVALID || mm->mm_dbs[MAIN_DBI].md_flags) {
10153 mm->mm_txnid = 1; /* use metapage 1 */
10156 my.mc_wlen[0] = env->me_psize * NUM_METAS;
10158 rc = mdb_env_cwalk(&my, &root, 0);
10159 if (rc == MDB_SUCCESS && root != new_root) {
10160 rc = MDB_INCOMPATIBLE; /* page leak or corrupt DB */
10166 mdb_env_cthr_toggle(&my, 1 | MDB_EOF);
10167 rc = THREAD_FINISH(thr);
10168 mdb_txn_abort(txn);
10172 if (my.mc_wbuf[0]) _aligned_free(my.mc_wbuf[0]);
10173 if (my.mc_cond) CloseHandle(my.mc_cond);
10174 if (my.mc_mutex) CloseHandle(my.mc_mutex);
10176 free(my.mc_wbuf[0]);
10177 pthread_cond_destroy(&my.mc_cond);
10179 pthread_mutex_destroy(&my.mc_mutex);
10181 return rc ? rc : my.mc_error;
10184 /** Copy environment as-is. */
10186 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
10188 MDB_txn *txn = NULL;
10189 mdb_mutexref_t wmutex = NULL;
10191 mdb_size_t wsize, w3;
10195 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
10199 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
10202 /* Do the lock/unlock of the reader mutex before starting the
10203 * write txn. Otherwise other read txns could block writers.
10205 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
10209 if (env->me_txns) {
10210 /* We must start the actual read txn after blocking writers */
10211 mdb_txn_end(txn, MDB_END_RESET_TMP);
10213 /* Temporarily block writers until we snapshot the meta pages */
10214 wmutex = env->me_wmutex;
10215 if (LOCK_MUTEX(rc, env, wmutex))
10218 rc = mdb_txn_renew0(txn);
10220 UNLOCK_MUTEX(wmutex);
10225 wsize = env->me_psize * NUM_METAS;
10229 DO_WRITE(rc, fd, ptr, w2, len);
10233 } else if (len > 0) {
10239 /* Non-blocking or async handles are not supported */
10245 UNLOCK_MUTEX(wmutex);
10250 w3 = txn->mt_next_pgno * env->me_psize;
10252 mdb_size_t fsize = 0;
10253 if ((rc = mdb_fsize(env->me_fd, &fsize)))
10258 wsize = w3 - wsize;
10259 while (wsize > 0) {
10260 if (wsize > MAX_WRITE)
10264 DO_WRITE(rc, fd, ptr, w2, len);
10268 } else if (len > 0) {
10280 mdb_txn_abort(txn);
10285 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
10287 if (flags & MDB_CP_COMPACT)
10288 return mdb_env_copyfd1(env, fd);
10290 return mdb_env_copyfd0(env, fd);
10294 mdb_env_copyfd(MDB_env *env, HANDLE fd)
10296 return mdb_env_copyfd2(env, fd, 0);
10300 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
10304 HANDLE newfd = INVALID_HANDLE_VALUE;
10306 rc = mdb_fname_init(path, env->me_flags | MDB_NOLOCK, &fname);
10307 if (rc == MDB_SUCCESS) {
10308 rc = mdb_fopen(env, &fname, MDB_O_COPY, 0666, &newfd);
10309 mdb_fname_destroy(fname);
10311 if (rc == MDB_SUCCESS) {
10312 rc = mdb_env_copyfd2(env, newfd, flags);
10313 if (close(newfd) < 0 && rc == MDB_SUCCESS)
10320 mdb_env_copy(MDB_env *env, const char *path)
10322 return mdb_env_copy2(env, path, 0);
10326 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
10328 if (flag & ~CHANGEABLE)
10331 env->me_flags |= flag;
10333 env->me_flags &= ~flag;
10334 return MDB_SUCCESS;
10338 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
10343 *arg = env->me_flags & (CHANGEABLE|CHANGELESS);
10344 return MDB_SUCCESS;
10348 mdb_env_set_userctx(MDB_env *env, void *ctx)
10352 env->me_userctx = ctx;
10353 return MDB_SUCCESS;
10357 mdb_env_get_userctx(MDB_env *env)
10359 return env ? env->me_userctx : NULL;
10363 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
10368 env->me_assert_func = func;
10370 return MDB_SUCCESS;
10374 mdb_env_get_path(MDB_env *env, const char **arg)
10379 *arg = env->me_path;
10380 return MDB_SUCCESS;
10384 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
10390 return MDB_SUCCESS;
10393 /** Common code for #mdb_stat() and #mdb_env_stat().
10394 * @param[in] env the environment to operate in.
10395 * @param[in] db the #MDB_db record containing the stats to return.
10396 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
10397 * @return 0, this function always succeeds.
10400 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
10402 arg->ms_psize = env->me_psize;
10403 arg->ms_depth = db->md_depth;
10404 arg->ms_branch_pages = db->md_branch_pages;
10405 arg->ms_leaf_pages = db->md_leaf_pages;
10406 arg->ms_overflow_pages = db->md_overflow_pages;
10407 arg->ms_entries = db->md_entries;
10409 return MDB_SUCCESS;
10413 mdb_env_stat(MDB_env *env, MDB_stat *arg)
10417 if (env == NULL || arg == NULL)
10420 meta = mdb_env_pick_meta(env);
10422 return mdb_stat0(env, &meta->mm_dbs[MAIN_DBI], arg);
10426 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
10430 if (env == NULL || arg == NULL)
10433 meta = mdb_env_pick_meta(env);
10434 arg->me_mapaddr = meta->mm_address;
10435 arg->me_last_pgno = meta->mm_last_pg;
10436 arg->me_last_txnid = meta->mm_txnid;
10438 arg->me_mapsize = env->me_mapsize;
10439 arg->me_maxreaders = env->me_maxreaders;
10440 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : 0;
10441 return MDB_SUCCESS;
10444 /** Set the default comparison functions for a database.
10445 * Called immediately after a database is opened to set the defaults.
10446 * The user can then override them with #mdb_set_compare() or
10447 * #mdb_set_dupsort().
10448 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
10449 * @param[in] dbi A database handle returned by #mdb_dbi_open()
10452 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
10454 uint16_t f = txn->mt_dbs[dbi].md_flags;
10456 txn->mt_dbxs[dbi].md_cmp =
10457 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
10458 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
10460 txn->mt_dbxs[dbi].md_dcmp =
10461 !(f & MDB_DUPSORT) ? 0 :
10462 ((f & MDB_INTEGERDUP)
10463 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
10464 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
10467 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
10473 int rc, dbflag, exact;
10474 unsigned int unused = 0, seq;
10478 if (flags & ~VALID_FLAGS)
10480 if (txn->mt_flags & MDB_TXN_BLOCKED)
10481 return MDB_BAD_TXN;
10486 if (flags & PERSISTENT_FLAGS) {
10487 uint16_t f2 = flags & PERSISTENT_FLAGS;
10488 /* make sure flag changes get committed */
10489 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
10490 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
10491 txn->mt_flags |= MDB_TXN_DIRTY;
10494 mdb_default_cmp(txn, MAIN_DBI);
10495 return MDB_SUCCESS;
10498 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
10499 mdb_default_cmp(txn, MAIN_DBI);
10502 /* Is the DB already open? */
10503 len = strlen(name);
10504 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
10505 if (!txn->mt_dbxs[i].md_name.mv_size) {
10506 /* Remember this free slot */
10507 if (!unused) unused = i;
10510 if (len == txn->mt_dbxs[i].md_name.mv_size &&
10511 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
10513 return MDB_SUCCESS;
10517 /* If no free slot and max hit, fail */
10518 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
10519 return MDB_DBS_FULL;
10521 /* Cannot mix named databases with some mainDB flags */
10522 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
10523 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
10525 /* Find the DB info */
10526 dbflag = DB_NEW|DB_VALID|DB_USRVALID;
10529 key.mv_data = (void *)name;
10530 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
10531 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
10532 if (rc == MDB_SUCCESS) {
10533 /* make sure this is actually a DB */
10534 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
10535 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
10536 return MDB_INCOMPATIBLE;
10537 } else if (! (rc == MDB_NOTFOUND && (flags & MDB_CREATE))) {
10541 /* Done here so we cannot fail after creating a new DB */
10542 if ((namedup = strdup(name)) == NULL)
10546 /* MDB_NOTFOUND and MDB_CREATE: Create new DB */
10547 data.mv_size = sizeof(MDB_db);
10548 data.mv_data = &dummy;
10549 memset(&dummy, 0, sizeof(dummy));
10550 dummy.md_root = P_INVALID;
10551 dummy.md_flags = flags & PERSISTENT_FLAGS;
10552 WITH_CURSOR_TRACKING(mc,
10553 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA));
10554 dbflag |= DB_DIRTY;
10560 /* Got info, register DBI in this txn */
10561 unsigned int slot = unused ? unused : txn->mt_numdbs;
10562 txn->mt_dbxs[slot].md_name.mv_data = namedup;
10563 txn->mt_dbxs[slot].md_name.mv_size = len;
10564 txn->mt_dbxs[slot].md_rel = NULL;
10565 txn->mt_dbflags[slot] = dbflag;
10566 /* txn-> and env-> are the same in read txns, use
10567 * tmp variable to avoid undefined assignment
10569 seq = ++txn->mt_env->me_dbiseqs[slot];
10570 txn->mt_dbiseqs[slot] = seq;
10572 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
10574 mdb_default_cmp(txn, slot);
10584 mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
10586 if (!arg || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
10589 if (txn->mt_flags & MDB_TXN_BLOCKED)
10590 return MDB_BAD_TXN;
10592 if (txn->mt_dbflags[dbi] & DB_STALE) {
10595 /* Stale, must read the DB's root. cursor_init does it for us. */
10596 mdb_cursor_init(&mc, txn, dbi, &mx);
10598 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
10601 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
10604 if (dbi < CORE_DBS || dbi >= env->me_maxdbs)
10606 ptr = env->me_dbxs[dbi].md_name.mv_data;
10607 /* If there was no name, this was already closed */
10609 env->me_dbxs[dbi].md_name.mv_data = NULL;
10610 env->me_dbxs[dbi].md_name.mv_size = 0;
10611 env->me_dbflags[dbi] = 0;
10612 env->me_dbiseqs[dbi]++;
10617 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
10619 /* We could return the flags for the FREE_DBI too but what's the point? */
10620 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10622 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
10623 return MDB_SUCCESS;
10626 /** Add all the DB's pages to the free list.
10627 * @param[in] mc Cursor on the DB to free.
10628 * @param[in] subs non-Zero to check for sub-DBs in this DB.
10629 * @return 0 on success, non-zero on failure.
10632 mdb_drop0(MDB_cursor *mc, int subs)
10636 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
10637 if (rc == MDB_SUCCESS) {
10638 MDB_txn *txn = mc->mc_txn;
10643 /* DUPSORT sub-DBs have no ovpages/DBs. Omit scanning leaves.
10644 * This also avoids any P_LEAF2 pages, which have no nodes.
10645 * Also if the DB doesn't have sub-DBs and has no overflow
10646 * pages, omit scanning leaves.
10648 if ((mc->mc_flags & C_SUB) ||
10649 (!subs && !mc->mc_db->md_overflow_pages))
10650 mdb_cursor_pop(mc);
10652 mdb_cursor_copy(mc, &mx);
10654 /* bump refcount for mx's pages */
10655 for (i=0; i<mc->mc_snum; i++)
10656 mdb_page_get(&mx, mc->mc_pg[i]->mp_pgno, &mx.mc_pg[i], NULL);
10658 while (mc->mc_snum > 0) {
10659 MDB_page *mp = mc->mc_pg[mc->mc_top];
10660 unsigned n = NUMKEYS(mp);
10662 for (i=0; i<n; i++) {
10663 ni = NODEPTR(mp, i);
10664 if (ni->mn_flags & F_BIGDATA) {
10667 memcpy(&pg, NODEDATA(ni), sizeof(pg));
10668 rc = mdb_page_get(mc, pg, &omp, NULL);
10671 mdb_cassert(mc, IS_OVERFLOW(omp));
10672 rc = mdb_midl_append_range(&txn->mt_free_pgs,
10673 pg, omp->mp_pages);
10676 mc->mc_db->md_overflow_pages -= omp->mp_pages;
10677 if (!mc->mc_db->md_overflow_pages && !subs)
10679 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
10680 mdb_xcursor_init1(mc, ni);
10681 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
10686 if (!subs && !mc->mc_db->md_overflow_pages)
10689 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
10691 for (i=0; i<n; i++) {
10693 ni = NODEPTR(mp, i);
10696 mdb_midl_xappend(txn->mt_free_pgs, pg);
10701 mc->mc_ki[mc->mc_top] = i;
10702 rc = mdb_cursor_sibling(mc, 1);
10704 if (rc != MDB_NOTFOUND)
10706 /* no more siblings, go back to beginning
10707 * of previous level.
10710 mdb_cursor_pop(mc);
10712 for (i=1; i<mc->mc_snum; i++) {
10714 mc->mc_pg[i] = mx.mc_pg[i];
10719 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
10722 txn->mt_flags |= MDB_TXN_ERROR;
10723 /* drop refcount for mx's pages */
10724 MDB_CURSOR_UNREF(&mx, 0);
10725 } else if (rc == MDB_NOTFOUND) {
10728 mc->mc_flags &= ~C_INITIALIZED;
10732 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
10734 MDB_cursor *mc, *m2;
10737 if ((unsigned)del > 1 || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10740 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
10743 if (TXN_DBI_CHANGED(txn, dbi))
10744 return MDB_BAD_DBI;
10746 rc = mdb_cursor_open(txn, dbi, &mc);
10750 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
10751 /* Invalidate the dropped DB's cursors */
10752 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
10753 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
10757 /* Can't delete the main DB */
10758 if (del && dbi >= CORE_DBS) {
10759 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, F_SUBDATA);
10761 txn->mt_dbflags[dbi] = DB_STALE;
10762 mdb_dbi_close(txn->mt_env, dbi);
10764 txn->mt_flags |= MDB_TXN_ERROR;
10767 /* reset the DB record, mark it dirty */
10768 txn->mt_dbflags[dbi] |= DB_DIRTY;
10769 txn->mt_dbs[dbi].md_depth = 0;
10770 txn->mt_dbs[dbi].md_branch_pages = 0;
10771 txn->mt_dbs[dbi].md_leaf_pages = 0;
10772 txn->mt_dbs[dbi].md_overflow_pages = 0;
10773 txn->mt_dbs[dbi].md_entries = 0;
10774 txn->mt_dbs[dbi].md_root = P_INVALID;
10776 txn->mt_flags |= MDB_TXN_DIRTY;
10779 mdb_cursor_close(mc);
10783 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
10785 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10788 txn->mt_dbxs[dbi].md_cmp = cmp;
10789 return MDB_SUCCESS;
10792 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
10794 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10797 txn->mt_dbxs[dbi].md_dcmp = cmp;
10798 return MDB_SUCCESS;
10801 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
10803 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10806 txn->mt_dbxs[dbi].md_rel = rel;
10807 return MDB_SUCCESS;
10810 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
10812 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10815 txn->mt_dbxs[dbi].md_relctx = ctx;
10816 return MDB_SUCCESS;
10820 mdb_env_get_maxkeysize(MDB_env *env)
10822 return ENV_MAXKEY(env);
10826 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
10828 unsigned int i, rdrs;
10831 int rc = 0, first = 1;
10835 if (!env->me_txns) {
10836 return func("(no reader locks)\n", ctx);
10838 rdrs = env->me_txns->mti_numreaders;
10839 mr = env->me_txns->mti_readers;
10840 for (i=0; i<rdrs; i++) {
10841 if (mr[i].mr_pid) {
10842 txnid_t txnid = mr[i].mr_txnid;
10843 sprintf(buf, txnid == (txnid_t)-1 ?
10844 "%10d %"Z"x -\n" : "%10d %"Z"x %"Yu"\n",
10845 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
10848 rc = func(" pid thread txnid\n", ctx);
10852 rc = func(buf, ctx);
10858 rc = func("(no active readers)\n", ctx);
10863 /** Insert pid into list if not already present.
10864 * return -1 if already present.
10867 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
10869 /* binary search of pid in list */
10871 unsigned cursor = 1;
10873 unsigned n = ids[0];
10876 unsigned pivot = n >> 1;
10877 cursor = base + pivot + 1;
10878 val = pid - ids[cursor];
10883 } else if ( val > 0 ) {
10888 /* found, so it's a duplicate */
10897 for (n = ids[0]; n > cursor; n--)
10904 mdb_reader_check(MDB_env *env, int *dead)
10910 return env->me_txns ? mdb_reader_check0(env, 0, dead) : MDB_SUCCESS;
10913 /** As #mdb_reader_check(). \b rlocked is set if caller locked #me_rmutex. */
10915 mdb_reader_check0(MDB_env *env, int rlocked, int *dead)
10917 mdb_mutexref_t rmutex = rlocked ? NULL : env->me_rmutex;
10918 unsigned int i, j, rdrs;
10920 MDB_PID_T *pids, pid;
10921 int rc = MDB_SUCCESS, count = 0;
10923 rdrs = env->me_txns->mti_numreaders;
10924 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
10928 mr = env->me_txns->mti_readers;
10929 for (i=0; i<rdrs; i++) {
10930 pid = mr[i].mr_pid;
10931 if (pid && pid != env->me_pid) {
10932 if (mdb_pid_insert(pids, pid) == 0) {
10933 if (!mdb_reader_pid(env, Pidcheck, pid)) {
10934 /* Stale reader found */
10937 if ((rc = LOCK_MUTEX0(rmutex)) != 0) {
10938 if ((rc = mdb_mutex_failed(env, rmutex, rc)))
10940 rdrs = 0; /* the above checked all readers */
10942 /* Recheck, a new process may have reused pid */
10943 if (mdb_reader_pid(env, Pidcheck, pid))
10947 for (; j<rdrs; j++)
10948 if (mr[j].mr_pid == pid) {
10949 DPRINTF(("clear stale reader pid %u txn %"Yd,
10950 (unsigned) pid, mr[j].mr_txnid));
10955 UNLOCK_MUTEX(rmutex);
10966 #ifdef MDB_ROBUST_SUPPORTED
10967 /** Handle #LOCK_MUTEX0() failure.
10968 * Try to repair the lock file if the mutex owner died.
10969 * @param[in] env the environment handle
10970 * @param[in] mutex LOCK_MUTEX0() mutex
10971 * @param[in] rc LOCK_MUTEX0() error (nonzero)
10972 * @return 0 on success with the mutex locked, or an error code on failure.
10975 mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc)
10980 if (rc == MDB_OWNERDEAD) {
10981 /* We own the mutex. Clean up after dead previous owner. */
10983 rlocked = (mutex == env->me_rmutex);
10985 /* Keep mti_txnid updated, otherwise next writer can
10986 * overwrite data which latest meta page refers to.
10988 meta = mdb_env_pick_meta(env);
10989 env->me_txns->mti_txnid = meta->mm_txnid;
10990 /* env is hosed if the dead thread was ours */
10992 env->me_flags |= MDB_FATAL_ERROR;
10993 env->me_txn = NULL;
10997 DPRINTF(("%cmutex owner died, %s", (rlocked ? 'r' : 'w'),
10998 (rc ? "this process' env is hosed" : "recovering")));
10999 rc2 = mdb_reader_check0(env, rlocked, NULL);
11001 rc2 = mdb_mutex_consistent(mutex);
11002 if (rc || (rc = rc2)) {
11003 DPRINTF(("LOCK_MUTEX recovery failed, %s", mdb_strerror(rc)));
11004 UNLOCK_MUTEX(mutex);
11010 DPRINTF(("LOCK_MUTEX failed, %s", mdb_strerror(rc)));
11015 #endif /* MDB_ROBUST_SUPPORTED */
11017 #if defined(_WIN32)
11018 /** Convert \b src to new wchar_t[] string with room for \b xtra extra chars */
11020 utf8_to_utf16(const char *src, MDB_name *dst, int xtra)
11023 wchar_t *result = NULL;
11024 for (;;) { /* malloc result, then fill it in */
11025 need = MultiByteToWideChar(CP_UTF8, 0, src, -1, result, need);
11032 result = malloc(sizeof(wchar_t) * (need + xtra));
11037 dst->mn_alloced = 1;
11038 dst->mn_len = need - 1;
11039 dst->mn_val = result;
11040 return MDB_SUCCESS;
11043 #endif /* defined(_WIN32) */