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
45 /* We use native NT APIs to setup the memory map, so that we can
46 * let the DB file grow incrementally instead of always preallocating
47 * the full size. These APIs are defined in <wdm.h> and <ntifs.h>
48 * but those headers are meant for driver-level development and
49 * conflict with the regular user-level headers, so we explicitly
50 * declare them here. Using these APIs also means we must link to
51 * ntdll.dll, which is not linked by default in user code.
54 NtCreateSection(OUT PHANDLE sh, IN ACCESS_MASK acc,
55 IN void * oa OPTIONAL,
56 IN PLARGE_INTEGER ms OPTIONAL,
57 IN ULONG pp, IN ULONG aa, IN HANDLE fh OPTIONAL);
59 typedef enum _SECTION_INHERIT {
65 NtMapViewOfSection(IN PHANDLE sh, IN HANDLE ph,
66 IN OUT PVOID *addr, IN ULONG_PTR zbits,
67 IN SIZE_T cs, IN OUT PLARGE_INTEGER off OPTIONAL,
68 IN OUT PSIZE_T vs, IN SECTION_INHERIT ih,
69 IN ULONG at, IN ULONG pp);
74 /** getpid() returns int; MinGW defines pid_t but MinGW64 typedefs it
75 * as int64 which is wrong. MSVC doesn't define it at all, so just
79 #define MDB_THR_T DWORD
80 #include <sys/types.h>
83 # include <sys/param.h>
85 # define LITTLE_ENDIAN 1234
86 # define BIG_ENDIAN 4321
87 # define BYTE_ORDER LITTLE_ENDIAN
89 # define SSIZE_MAX INT_MAX
93 #include <sys/types.h>
95 #define MDB_PID_T pid_t
96 #define MDB_THR_T pthread_t
97 #include <sys/param.h>
100 #ifdef HAVE_SYS_FILE_H
101 #include <sys/file.h>
106 #if defined(__mips) && defined(__linux)
107 /* MIPS has cache coherency issues, requires explicit cache control */
108 #include <asm/cachectl.h>
109 extern int cacheflush(char *addr, int nbytes, int cache);
110 #define CACHEFLUSH(addr, bytes, cache) cacheflush(addr, bytes, cache)
112 #define CACHEFLUSH(addr, bytes, cache)
115 #if defined(__linux) && !defined(MDB_FDATASYNC_WORKS)
116 /** fdatasync is broken on ext3/ext4fs on older kernels, see
117 * description in #mdb_env_open2 comments. You can safely
118 * define MDB_FDATASYNC_WORKS if this code will only be run
119 * on kernels 3.6 and newer.
121 #define BROKEN_FDATASYNC
127 #include <inttypes.h>
135 typedef SSIZE_T ssize_t;
140 #if defined(__sun) || defined(ANDROID)
141 /* Most platforms have posix_memalign, older may only have memalign */
142 #define HAVE_MEMALIGN 1
146 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
147 #include <netinet/in.h>
148 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
151 #if defined(__APPLE__) || defined (BSD)
152 # if !(defined(MDB_USE_POSIX_MUTEX) || defined(MDB_USE_POSIX_SEM))
153 # define MDB_USE_SYSV_SEM 1
155 # define MDB_FDATASYNC fsync
156 #elif defined(ANDROID)
157 # define MDB_FDATASYNC fsync
162 #ifdef MDB_USE_POSIX_SEM
163 # define MDB_USE_HASH 1
164 #include <semaphore.h>
165 #elif defined(MDB_USE_SYSV_SEM)
168 #ifdef _SEM_SEMUN_UNDEFINED
171 struct semid_ds *buf;
172 unsigned short *array;
174 #endif /* _SEM_SEMUN_UNDEFINED */
176 #define MDB_USE_POSIX_MUTEX 1
177 #endif /* MDB_USE_POSIX_SEM */
180 #if defined(_WIN32) + defined(MDB_USE_POSIX_SEM) + defined(MDB_USE_SYSV_SEM) \
181 + defined(MDB_USE_POSIX_MUTEX) != 1
182 # error "Ambiguous shared-lock implementation"
186 #include <valgrind/memcheck.h>
187 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
188 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
189 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
190 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
191 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
193 #define VGMEMP_CREATE(h,r,z)
194 #define VGMEMP_ALLOC(h,a,s)
195 #define VGMEMP_FREE(h,a)
196 #define VGMEMP_DESTROY(h)
197 #define VGMEMP_DEFINED(a,s)
201 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
202 /* Solaris just defines one or the other */
203 # define LITTLE_ENDIAN 1234
204 # define BIG_ENDIAN 4321
205 # ifdef _LITTLE_ENDIAN
206 # define BYTE_ORDER LITTLE_ENDIAN
208 # define BYTE_ORDER BIG_ENDIAN
211 # define BYTE_ORDER __BYTE_ORDER
215 #ifndef LITTLE_ENDIAN
216 #define LITTLE_ENDIAN __LITTLE_ENDIAN
219 #define BIG_ENDIAN __BIG_ENDIAN
222 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
223 #define MISALIGNED_OK 1
229 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
230 # error "Unknown or unsupported endianness (BYTE_ORDER)"
231 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
232 # error "Two's complement, reasonably sized integer types, please"
236 /** Put infrequently used env functions in separate section */
238 # define ESECT __attribute__ ((section("__TEXT,text_env")))
240 # define ESECT __attribute__ ((section("text_env")))
247 #define CALL_CONV WINAPI
252 /** @defgroup internal LMDB Internals
255 /** @defgroup compat Compatibility Macros
256 * A bunch of macros to minimize the amount of platform-specific ifdefs
257 * needed throughout the rest of the code. When the features this library
258 * needs are similar enough to POSIX to be hidden in a one-or-two line
259 * replacement, this macro approach is used.
263 /** Features under development */
268 /** Wrapper around __func__, which is a C99 feature */
269 #if __STDC_VERSION__ >= 199901L
270 # define mdb_func_ __func__
271 #elif __GNUC__ >= 2 || _MSC_VER >= 1300
272 # define mdb_func_ __FUNCTION__
274 /* If a debug message says <mdb_unknown>(), update the #if statements above */
275 # define mdb_func_ "<mdb_unknown>"
278 /* Internal error codes, not exposed outside liblmdb */
279 #define MDB_NO_ROOT (MDB_LAST_ERRCODE + 10)
281 #define MDB_OWNERDEAD ((int) WAIT_ABANDONED)
282 #elif defined MDB_USE_SYSV_SEM
283 #define MDB_OWNERDEAD (MDB_LAST_ERRCODE + 11)
284 #elif defined(MDB_USE_POSIX_MUTEX) && defined(EOWNERDEAD)
285 #define MDB_OWNERDEAD EOWNERDEAD /**< #LOCK_MUTEX0() result if dead owner */
289 #define GLIBC_VER ((__GLIBC__ << 16 )| __GLIBC_MINOR__)
291 /** Some platforms define the EOWNERDEAD error code
292 * even though they don't support Robust Mutexes.
293 * Compile with -DMDB_USE_ROBUST=0, or use some other
294 * mechanism like -DMDB_USE_SYSV_SEM instead of
295 * -DMDB_USE_POSIX_MUTEX. (SysV semaphores are
296 * also Robust, but some systems don't support them
299 #ifndef MDB_USE_ROBUST
300 /* Android currently lacks Robust Mutex support. So does glibc < 2.4. */
301 # if defined(MDB_USE_POSIX_MUTEX) && (defined(ANDROID) || \
302 (defined(__GLIBC__) && GLIBC_VER < 0x020004))
303 # define MDB_USE_ROBUST 0
305 # define MDB_USE_ROBUST 1
306 /* glibc < 2.12 only provided _np API */
307 # if (defined(__GLIBC__) && GLIBC_VER < 0x02000c) || \
308 (defined(PTHREAD_MUTEX_ROBUST_NP) && !defined(PTHREAD_MUTEX_ROBUST))
309 # define PTHREAD_MUTEX_ROBUST PTHREAD_MUTEX_ROBUST_NP
310 # define pthread_mutexattr_setrobust(attr, flag) pthread_mutexattr_setrobust_np(attr, flag)
311 # define pthread_mutex_consistent(mutex) pthread_mutex_consistent_np(mutex)
314 #endif /* MDB_USE_ROBUST */
316 #if defined(MDB_OWNERDEAD) && MDB_USE_ROBUST
317 #define MDB_ROBUST_SUPPORTED 1
321 #define MDB_USE_HASH 1
322 #define MDB_PIDLOCK 0
323 #define THREAD_RET DWORD
324 #define pthread_t HANDLE
325 #define pthread_mutex_t HANDLE
326 #define pthread_cond_t HANDLE
327 typedef HANDLE mdb_mutex_t, mdb_mutexref_t;
328 #define pthread_key_t DWORD
329 #define pthread_self() GetCurrentThreadId()
330 #define pthread_key_create(x,y) \
331 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
332 #define pthread_key_delete(x) TlsFree(x)
333 #define pthread_getspecific(x) TlsGetValue(x)
334 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
335 #define pthread_mutex_unlock(x) ReleaseMutex(*x)
336 #define pthread_mutex_lock(x) WaitForSingleObject(*x, INFINITE)
337 #define pthread_cond_signal(x) SetEvent(*x)
338 #define pthread_cond_wait(cond,mutex) do{SignalObjectAndWait(*mutex, *cond, INFINITE, FALSE); WaitForSingleObject(*mutex, INFINITE);}while(0)
339 #define THREAD_CREATE(thr,start,arg) thr=CreateThread(NULL,0,start,arg,0,NULL)
340 #define THREAD_FINISH(thr) WaitForSingleObject(thr, INFINITE)
341 #define LOCK_MUTEX0(mutex) WaitForSingleObject(mutex, INFINITE)
342 #define UNLOCK_MUTEX(mutex) ReleaseMutex(mutex)
343 #define mdb_mutex_consistent(mutex) 0
344 #define getpid() GetCurrentProcessId()
345 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
346 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
347 #define ErrCode() GetLastError()
348 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
349 #define close(fd) (CloseHandle(fd) ? 0 : -1)
350 #define munmap(ptr,len) UnmapViewOfFile(ptr)
351 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
352 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
354 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
358 #define THREAD_RET void *
359 #define THREAD_CREATE(thr,start,arg) pthread_create(&thr,NULL,start,arg)
360 #define THREAD_FINISH(thr) pthread_join(thr,NULL)
361 #define Z "z" /**< printf format modifier for size_t */
363 /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
364 #define MDB_PIDLOCK 1
366 #ifdef MDB_USE_POSIX_SEM
368 typedef sem_t *mdb_mutex_t, *mdb_mutexref_t;
369 #define LOCK_MUTEX0(mutex) mdb_sem_wait(mutex)
370 #define UNLOCK_MUTEX(mutex) sem_post(mutex)
373 mdb_sem_wait(sem_t *sem)
376 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
380 #elif defined MDB_USE_SYSV_SEM
382 typedef struct mdb_mutex {
386 } mdb_mutex_t[1], *mdb_mutexref_t;
388 #define LOCK_MUTEX0(mutex) mdb_sem_wait(mutex)
389 #define UNLOCK_MUTEX(mutex) do { \
390 struct sembuf sb = { 0, 1, SEM_UNDO }; \
391 sb.sem_num = (mutex)->semnum; \
392 *(mutex)->locked = 0; \
393 semop((mutex)->semid, &sb, 1); \
397 mdb_sem_wait(mdb_mutexref_t sem)
399 int rc, *locked = sem->locked;
400 struct sembuf sb = { 0, -1, SEM_UNDO };
401 sb.sem_num = sem->semnum;
403 if (!semop(sem->semid, &sb, 1)) {
404 rc = *locked ? MDB_OWNERDEAD : MDB_SUCCESS;
408 } while ((rc = errno) == EINTR);
412 #define mdb_mutex_consistent(mutex) 0
414 #else /* MDB_USE_POSIX_MUTEX: */
415 /** Shared mutex/semaphore as it is stored (mdb_mutex_t), and as
416 * local variables keep it (mdb_mutexref_t).
418 * An mdb_mutex_t can be assigned to an mdb_mutexref_t. They can
419 * be the same, or an array[size 1] and a pointer.
422 typedef pthread_mutex_t mdb_mutex_t[1], *mdb_mutexref_t;
424 /** Lock the reader or writer mutex.
425 * Returns 0 or a code to give #mdb_mutex_failed(), as in #LOCK_MUTEX().
427 #define LOCK_MUTEX0(mutex) pthread_mutex_lock(mutex)
428 /** Unlock the reader or writer mutex.
430 #define UNLOCK_MUTEX(mutex) pthread_mutex_unlock(mutex)
431 /** Mark mutex-protected data as repaired, after death of previous owner.
433 #define mdb_mutex_consistent(mutex) pthread_mutex_consistent(mutex)
434 #endif /* MDB_USE_POSIX_SEM || MDB_USE_SYSV_SEM */
436 /** Get the error code for the last failed system function.
438 #define ErrCode() errno
440 /** An abstraction for a file handle.
441 * On POSIX systems file handles are small integers. On Windows
442 * they're opaque pointers.
446 /** A value for an invalid file handle.
447 * Mainly used to initialize file variables and signify that they are
450 #define INVALID_HANDLE_VALUE (-1)
452 /** Get the size of a memory page for the system.
453 * This is the basic size that the platform's memory manager uses, and is
454 * fundamental to the use of memory-mapped files.
456 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
469 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
471 #elif defined(MDB_USE_SYSV_SEM)
472 #define MNAME_LEN (sizeof(int))
474 #define MNAME_LEN (sizeof(pthread_mutex_t))
477 #ifdef MDB_USE_SYSV_SEM
478 #define SYSV_SEM_FLAG 1 /**< SysV sems in lockfile format */
480 #define SYSV_SEM_FLAG 0
485 #ifdef MDB_ROBUST_SUPPORTED
486 /** Lock mutex, handle any error, set rc = result.
487 * Return 0 on success, nonzero (not rc) on error.
489 #define LOCK_MUTEX(rc, env, mutex) \
490 (((rc) = LOCK_MUTEX0(mutex)) && \
491 ((rc) = mdb_mutex_failed(env, mutex, rc)))
492 static int mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc);
494 #define LOCK_MUTEX(rc, env, mutex) ((rc) = LOCK_MUTEX0(mutex))
495 #define mdb_mutex_failed(env, mutex, rc) (rc)
499 /** A flag for opening a file and requesting synchronous data writes.
500 * This is only used when writing a meta page. It's not strictly needed;
501 * we could just do a normal write and then immediately perform a flush.
502 * But if this flag is available it saves us an extra system call.
504 * @note If O_DSYNC is undefined but exists in /usr/include,
505 * preferably set some compiler flag to get the definition.
509 # define MDB_DSYNC O_DSYNC
511 # define MDB_DSYNC O_SYNC
516 /** Function for flushing the data of a file. Define this to fsync
517 * if fdatasync() is not supported.
519 #ifndef MDB_FDATASYNC
520 # define MDB_FDATASYNC fdatasync
524 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
535 /** A page number in the database.
536 * Note that 64 bit page numbers are overkill, since pages themselves
537 * already represent 12-13 bits of addressable memory, and the OS will
538 * always limit applications to a maximum of 63 bits of address space.
540 * @note In the #MDB_node structure, we only store 48 bits of this value,
541 * which thus limits us to only 60 bits of addressable data.
543 typedef MDB_ID pgno_t;
545 /** A transaction ID.
546 * See struct MDB_txn.mt_txnid for details.
548 typedef MDB_ID txnid_t;
550 /** @defgroup debug Debug Macros
554 /** Enable debug output. Needs variable argument macros (a C99 feature).
555 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
556 * read from and written to the database (used for free space management).
562 static int mdb_debug;
563 static txnid_t mdb_debug_start;
565 /** Print a debug message with printf formatting.
566 * Requires double parenthesis around 2 or more args.
568 # define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
569 # define DPRINTF0(fmt, ...) \
570 fprintf(stderr, "%s:%d " fmt "\n", mdb_func_, __LINE__, __VA_ARGS__)
572 # define DPRINTF(args) ((void) 0)
574 /** Print a debug string.
575 * The string is printed literally, with no format processing.
577 #define DPUTS(arg) DPRINTF(("%s", arg))
578 /** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
580 (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
583 /** @brief The maximum size of a database page.
585 * It is 32k or 64k, since value-PAGEBASE must fit in
586 * #MDB_page.%mp_upper.
588 * LMDB will use database pages < OS pages if needed.
589 * That causes more I/O in write transactions: The OS must
590 * know (read) the whole page before writing a partial page.
592 * Note that we don't currently support Huge pages. On Linux,
593 * regular data files cannot use Huge pages, and in general
594 * Huge pages aren't actually pageable. We rely on the OS
595 * demand-pager to read our data and page it out when memory
596 * pressure from other processes is high. So until OSs have
597 * actual paging support for Huge pages, they're not viable.
599 #define MAX_PAGESIZE (PAGEBASE ? 0x10000 : 0x8000)
601 /** The minimum number of keys required in a database page.
602 * Setting this to a larger value will place a smaller bound on the
603 * maximum size of a data item. Data items larger than this size will
604 * be pushed into overflow pages instead of being stored directly in
605 * the B-tree node. This value used to default to 4. With a page size
606 * of 4096 bytes that meant that any item larger than 1024 bytes would
607 * go into an overflow page. That also meant that on average 2-3KB of
608 * each overflow page was wasted space. The value cannot be lower than
609 * 2 because then there would no longer be a tree structure. With this
610 * value, items larger than 2KB will go into overflow pages, and on
611 * average only 1KB will be wasted.
613 #define MDB_MINKEYS 2
615 /** A stamp that identifies a file as an LMDB file.
616 * There's nothing special about this value other than that it is easily
617 * recognizable, and it will reflect any byte order mismatches.
619 #define MDB_MAGIC 0xBEEFC0DE
621 /** The version number for a database's datafile format. */
622 #define MDB_DATA_VERSION ((MDB_DEVEL) ? 999 : 1)
623 /** The version number for a database's lockfile format. */
624 #define MDB_LOCK_VERSION ((MDB_DEVEL) ? 999 : 1)
626 /** @brief The max size of a key we can write, or 0 for computed max.
628 * This macro should normally be left alone or set to 0.
629 * Note that a database with big keys or dupsort data cannot be
630 * reliably modified by a liblmdb which uses a smaller max.
631 * The default is 511 for backwards compat, or 0 when #MDB_DEVEL.
633 * Other values are allowed, for backwards compat. However:
634 * A value bigger than the computed max can break if you do not
635 * know what you are doing, and liblmdb <= 0.9.10 can break when
636 * modifying a DB with keys/dupsort data bigger than its max.
638 * Data items in an #MDB_DUPSORT database are also limited to
639 * this size, since they're actually keys of a sub-DB. Keys and
640 * #MDB_DUPSORT data items must fit on a node in a regular page.
642 #ifndef MDB_MAXKEYSIZE
643 #define MDB_MAXKEYSIZE ((MDB_DEVEL) ? 0 : 511)
646 /** The maximum size of a key we can write to the environment. */
648 #define ENV_MAXKEY(env) (MDB_MAXKEYSIZE)
650 #define ENV_MAXKEY(env) ((env)->me_maxkey)
653 /** @brief The maximum size of a data item.
655 * We only store a 32 bit value for node sizes.
657 #define MAXDATASIZE 0xffffffffUL
660 /** Key size which fits in a #DKBUF.
663 #define DKBUF_MAXKEYSIZE ((MDB_MAXKEYSIZE) > 0 ? (MDB_MAXKEYSIZE) : 511)
666 * This is used for printing a hex dump of a key's contents.
668 #define DKBUF char kbuf[DKBUF_MAXKEYSIZE*2+1]
669 /** Display a key in hex.
671 * Invoke a function to display a key in hex.
673 #define DKEY(x) mdb_dkey(x, kbuf)
679 /** An invalid page number.
680 * Mainly used to denote an empty tree.
682 #define P_INVALID (~(pgno_t)0)
684 /** Test if the flags \b f are set in a flag word \b w. */
685 #define F_ISSET(w, f) (((w) & (f)) == (f))
687 /** Round \b n up to an even number. */
688 #define EVEN(n) (((n) + 1U) & -2) /* sign-extending -2 to match n+1U */
690 /** Used for offsets within a single page.
691 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
694 typedef uint16_t indx_t;
696 /** Default size of memory map.
697 * This is certainly too small for any actual applications. Apps should always set
698 * the size explicitly using #mdb_env_set_mapsize().
700 #define DEFAULT_MAPSIZE 1048576
702 /** @defgroup readers Reader Lock Table
703 * Readers don't acquire any locks for their data access. Instead, they
704 * simply record their transaction ID in the reader table. The reader
705 * mutex is needed just to find an empty slot in the reader table. The
706 * slot's address is saved in thread-specific data so that subsequent read
707 * transactions started by the same thread need no further locking to proceed.
709 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
711 * No reader table is used if the database is on a read-only filesystem, or
712 * if #MDB_NOLOCK is set.
714 * Since the database uses multi-version concurrency control, readers don't
715 * actually need any locking. This table is used to keep track of which
716 * readers are using data from which old transactions, so that we'll know
717 * when a particular old transaction is no longer in use. Old transactions
718 * that have discarded any data pages can then have those pages reclaimed
719 * for use by a later write transaction.
721 * The lock table is constructed such that reader slots are aligned with the
722 * processor's cache line size. Any slot is only ever used by one thread.
723 * This alignment guarantees that there will be no contention or cache
724 * thrashing as threads update their own slot info, and also eliminates
725 * any need for locking when accessing a slot.
727 * A writer thread will scan every slot in the table to determine the oldest
728 * outstanding reader transaction. Any freed pages older than this will be
729 * reclaimed by the writer. The writer doesn't use any locks when scanning
730 * this table. This means that there's no guarantee that the writer will
731 * see the most up-to-date reader info, but that's not required for correct
732 * operation - all we need is to know the upper bound on the oldest reader,
733 * we don't care at all about the newest reader. So the only consequence of
734 * reading stale information here is that old pages might hang around a
735 * while longer before being reclaimed. That's actually good anyway, because
736 * the longer we delay reclaiming old pages, the more likely it is that a
737 * string of contiguous pages can be found after coalescing old pages from
738 * many old transactions together.
741 /** Number of slots in the reader table.
742 * This value was chosen somewhat arbitrarily. 126 readers plus a
743 * couple mutexes fit exactly into 8KB on my development machine.
744 * Applications should set the table size using #mdb_env_set_maxreaders().
746 #define DEFAULT_READERS 126
748 /** The size of a CPU cache line in bytes. We want our lock structures
749 * aligned to this size to avoid false cache line sharing in the
751 * This value works for most CPUs. For Itanium this should be 128.
757 /** The information we store in a single slot of the reader table.
758 * In addition to a transaction ID, we also record the process and
759 * thread ID that owns a slot, so that we can detect stale information,
760 * e.g. threads or processes that went away without cleaning up.
761 * @note We currently don't check for stale records. We simply re-init
762 * the table when we know that we're the only process opening the
765 typedef struct MDB_rxbody {
766 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
767 * Multiple readers that start at the same time will probably have the
768 * same ID here. Again, it's not important to exclude them from
769 * anything; all we need to know is which version of the DB they
770 * started from so we can avoid overwriting any data used in that
771 * particular version.
773 volatile txnid_t mrb_txnid;
774 /** The process ID of the process owning this reader txn. */
775 volatile MDB_PID_T mrb_pid;
776 /** The thread ID of the thread owning this txn. */
777 volatile MDB_THR_T mrb_tid;
780 /** The actual reader record, with cacheline padding. */
781 typedef struct MDB_reader {
784 /** shorthand for mrb_txnid */
785 #define mr_txnid mru.mrx.mrb_txnid
786 #define mr_pid mru.mrx.mrb_pid
787 #define mr_tid mru.mrx.mrb_tid
788 /** cache line alignment */
789 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
793 /** The header for the reader table.
794 * The table resides in a memory-mapped file. (This is a different file
795 * than is used for the main database.)
797 * For POSIX the actual mutexes reside in the shared memory of this
798 * mapped file. On Windows, mutexes are named objects allocated by the
799 * kernel; we store the mutex names in this mapped file so that other
800 * processes can grab them. This same approach is also used on
801 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
802 * process-shared POSIX mutexes. For these cases where a named object
803 * is used, the object name is derived from a 64 bit FNV hash of the
804 * environment pathname. As such, naming collisions are extremely
805 * unlikely. If a collision occurs, the results are unpredictable.
807 typedef struct MDB_txbody {
808 /** Stamp identifying this as an LMDB file. It must be set
811 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
813 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
814 char mtb_rmname[MNAME_LEN];
815 #elif defined(MDB_USE_SYSV_SEM)
819 /** Mutex protecting access to this table.
820 * This is the reader table lock used with LOCK_MUTEX().
822 mdb_mutex_t mtb_rmutex;
824 /** The ID of the last transaction committed to the database.
825 * This is recorded here only for convenience; the value can always
826 * be determined by reading the main database meta pages.
828 volatile txnid_t mtb_txnid;
829 /** The number of slots that have been used in the reader table.
830 * This always records the maximum count, it is not decremented
831 * when readers release their slots.
833 volatile unsigned mtb_numreaders;
836 /** The actual reader table definition. */
837 typedef struct MDB_txninfo {
840 #define mti_magic mt1.mtb.mtb_magic
841 #define mti_format mt1.mtb.mtb_format
842 #define mti_rmutex mt1.mtb.mtb_rmutex
843 #define mti_rmname mt1.mtb.mtb_rmname
844 #define mti_txnid mt1.mtb.mtb_txnid
845 #define mti_numreaders mt1.mtb.mtb_numreaders
846 #ifdef MDB_USE_SYSV_SEM
847 #define mti_semid mt1.mtb.mtb_semid
848 #define mti_rlocked mt1.mtb.mtb_rlocked
850 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
853 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
854 char mt2_wmname[MNAME_LEN];
855 #define mti_wmname mt2.mt2_wmname
856 #elif defined MDB_USE_SYSV_SEM
858 #define mti_wlocked mt2.mt2_wlocked
860 mdb_mutex_t mt2_wmutex;
861 #define mti_wmutex mt2.mt2_wmutex
863 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
865 MDB_reader mti_readers[1];
868 /** Lockfile format signature: version, features and field layout */
869 #define MDB_LOCK_FORMAT \
871 ((MDB_LOCK_VERSION) \
872 /* Flags which describe functionality */ \
873 + (SYSV_SEM_FLAG << 18) \
874 + (((MDB_PIDLOCK) != 0) << 16)))
877 /** Common header for all page types.
878 * Overflow records occupy a number of contiguous pages with no
879 * headers on any page after the first.
881 typedef struct MDB_page {
882 #define mp_pgno mp_p.p_pgno
883 #define mp_next mp_p.p_next
885 pgno_t p_pgno; /**< page number */
886 struct MDB_page *p_next; /**< for in-memory list of freed pages */
889 /** @defgroup mdb_page Page Flags
891 * Flags for the page headers.
894 #define P_BRANCH 0x01 /**< branch page */
895 #define P_LEAF 0x02 /**< leaf page */
896 #define P_OVERFLOW 0x04 /**< overflow page */
897 #define P_META 0x08 /**< meta page */
898 #define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
899 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
900 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
901 #define P_LOOSE 0x4000 /**< page was dirtied then freed, can be reused */
902 #define P_KEEP 0x8000 /**< leave this page alone during spill */
904 uint16_t mp_flags; /**< @ref mdb_page */
905 #define mp_lower mp_pb.pb.pb_lower
906 #define mp_upper mp_pb.pb.pb_upper
907 #define mp_pages mp_pb.pb_pages
910 indx_t pb_lower; /**< lower bound of free space */
911 indx_t pb_upper; /**< upper bound of free space */
913 uint32_t pb_pages; /**< number of overflow pages */
915 indx_t mp_ptrs[1]; /**< dynamic size */
918 /** Size of the page header, excluding dynamic data at the end */
919 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
921 /** Address of first usable data byte in a page, after the header */
922 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
924 /** ITS#7713, change PAGEBASE to handle 65536 byte pages */
925 #define PAGEBASE ((MDB_DEVEL) ? PAGEHDRSZ : 0)
927 /** Number of nodes on a page */
928 #define NUMKEYS(p) (((p)->mp_lower - (PAGEHDRSZ-PAGEBASE)) >> 1)
930 /** The amount of space remaining in the page */
931 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
933 /** The percentage of space used in the page, in tenths of a percent. */
934 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
935 ((env)->me_psize - PAGEHDRSZ))
936 /** The minimum page fill factor, in tenths of a percent.
937 * Pages emptier than this are candidates for merging.
939 #define FILL_THRESHOLD 250
941 /** Test if a page is a leaf page */
942 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
943 /** Test if a page is a LEAF2 page */
944 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
945 /** Test if a page is a branch page */
946 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
947 /** Test if a page is an overflow page */
948 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
949 /** Test if a page is a sub page */
950 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
952 /** The number of overflow pages needed to store the given size. */
953 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
955 /** Link in #MDB_txn.%mt_loose_pgs list */
956 #define NEXT_LOOSE_PAGE(p) (*(MDB_page **)((p) + 2))
958 /** Header for a single key/data pair within a page.
959 * Used in pages of type #P_BRANCH and #P_LEAF without #P_LEAF2.
960 * We guarantee 2-byte alignment for 'MDB_node's.
962 typedef struct MDB_node {
963 /** lo and hi are used for data size on leaf nodes and for
964 * child pgno on branch nodes. On 64 bit platforms, flags
965 * is also used for pgno. (Branch nodes have no flags).
966 * They are in host byte order in case that lets some
967 * accesses be optimized into a 32-bit word access.
969 #if BYTE_ORDER == LITTLE_ENDIAN
970 unsigned short mn_lo, mn_hi; /**< part of data size or pgno */
972 unsigned short mn_hi, mn_lo;
974 /** @defgroup mdb_node Node Flags
976 * Flags for node headers.
979 #define F_BIGDATA 0x01 /**< data put on overflow page */
980 #define F_SUBDATA 0x02 /**< data is a sub-database */
981 #define F_DUPDATA 0x04 /**< data has duplicates */
983 /** valid flags for #mdb_node_add() */
984 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
987 unsigned short mn_flags; /**< @ref mdb_node */
988 unsigned short mn_ksize; /**< key size */
989 char mn_data[1]; /**< key and data are appended here */
992 /** Size of the node header, excluding dynamic data at the end */
993 #define NODESIZE offsetof(MDB_node, mn_data)
995 /** Bit position of top word in page number, for shifting mn_flags */
996 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
998 /** Size of a node in a branch page with a given key.
999 * This is just the node header plus the key, there is no data.
1001 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
1003 /** Size of a node in a leaf page with a given key and data.
1004 * This is node header plus key plus data size.
1006 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
1008 /** Address of node \b i in page \b p */
1009 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i] + PAGEBASE))
1011 /** Address of the key for the node */
1012 #define NODEKEY(node) (void *)((node)->mn_data)
1014 /** Address of the data for a node */
1015 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
1017 /** Get the page number pointed to by a branch node */
1018 #define NODEPGNO(node) \
1019 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
1020 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
1021 /** Set the page number in a branch node */
1022 #define SETPGNO(node,pgno) do { \
1023 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
1024 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
1026 /** Get the size of the data in a leaf node */
1027 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
1028 /** Set the size of the data for a leaf node */
1029 #define SETDSZ(node,size) do { \
1030 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
1031 /** The size of a key in a node */
1032 #define NODEKSZ(node) ((node)->mn_ksize)
1034 /** Copy a page number from src to dst */
1035 #ifdef MISALIGNED_OK
1036 #define COPY_PGNO(dst,src) dst = src
1038 #if SIZE_MAX > 4294967295UL
1039 #define COPY_PGNO(dst,src) do { \
1040 unsigned short *s, *d; \
1041 s = (unsigned short *)&(src); \
1042 d = (unsigned short *)&(dst); \
1049 #define COPY_PGNO(dst,src) do { \
1050 unsigned short *s, *d; \
1051 s = (unsigned short *)&(src); \
1052 d = (unsigned short *)&(dst); \
1058 /** The address of a key in a LEAF2 page.
1059 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
1060 * There are no node headers, keys are stored contiguously.
1062 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
1064 /** Set the \b node's key into \b keyptr, if requested. */
1065 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
1066 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
1068 /** Set the \b node's key into \b key. */
1069 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
1071 /** Information about a single database in the environment. */
1072 typedef struct MDB_db {
1073 uint32_t md_pad; /**< also ksize for LEAF2 pages */
1074 uint16_t md_flags; /**< @ref mdb_dbi_open */
1075 uint16_t md_depth; /**< depth of this tree */
1076 pgno_t md_branch_pages; /**< number of internal pages */
1077 pgno_t md_leaf_pages; /**< number of leaf pages */
1078 pgno_t md_overflow_pages; /**< number of overflow pages */
1079 mdb_size_t md_entries; /**< number of data items */
1080 pgno_t md_root; /**< the root page of this tree */
1083 /** mdb_dbi_open flags */
1084 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
1085 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
1086 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
1087 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
1089 /** Handle for the DB used to track free pages. */
1091 /** Handle for the default DB. */
1093 /** Number of DBs in metapage (free and main) - also hardcoded elsewhere */
1096 /** Number of meta pages - also hardcoded elsewhere */
1099 /** Meta page content.
1100 * A meta page is the start point for accessing a database snapshot.
1101 * Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
1103 typedef struct MDB_meta {
1104 /** Stamp identifying this as an LMDB file. It must be set
1107 /** Version number of this file. Must be set to #MDB_DATA_VERSION. */
1108 uint32_t mm_version;
1110 union { /* always zero since we don't support fixed mapping in MDB_VL32 */
1114 #define mm_address mm_un.mmun_address
1116 void *mm_address; /**< address for fixed mapping */
1118 pgno_t mm_mapsize; /**< size of mmap region */
1119 MDB_db mm_dbs[CORE_DBS]; /**< first is free space, 2nd is main db */
1120 /** The size of pages used in this DB */
1121 #define mm_psize mm_dbs[FREE_DBI].md_pad
1122 /** Any persistent environment flags. @ref mdb_env */
1123 #define mm_flags mm_dbs[FREE_DBI].md_flags
1124 pgno_t mm_last_pg; /**< last used page in file */
1125 volatile txnid_t mm_txnid; /**< txnid that committed this page */
1128 /** Buffer for a stack-allocated meta page.
1129 * The members define size and alignment, and silence type
1130 * aliasing warnings. They are not used directly; that could
1131 * mean incorrectly using several union members in parallel.
1133 typedef union MDB_metabuf {
1136 char mm_pad[PAGEHDRSZ];
1141 /** Auxiliary DB info.
1142 * The information here is mostly static/read-only. There is
1143 * only a single copy of this record in the environment.
1145 typedef struct MDB_dbx {
1146 MDB_val md_name; /**< name of the database */
1147 MDB_cmp_func *md_cmp; /**< function for comparing keys */
1148 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
1149 MDB_rel_func *md_rel; /**< user relocate function */
1150 void *md_relctx; /**< user-provided context for md_rel */
1153 /** A database transaction.
1154 * Every operation requires a transaction handle.
1157 MDB_txn *mt_parent; /**< parent of a nested txn */
1158 /** Nested txn under this txn, set together with flag #MDB_TXN_HAS_CHILD */
1160 pgno_t mt_next_pgno; /**< next unallocated page */
1162 pgno_t mt_last_pgno; /**< last written page */
1164 /** The ID of this transaction. IDs are integers incrementing from 1.
1165 * Only committed write transactions increment the ID. If a transaction
1166 * aborts, the ID may be re-used by the next writer.
1169 MDB_env *mt_env; /**< the DB environment */
1170 /** The list of pages that became unused during this transaction.
1172 MDB_IDL mt_free_pgs;
1173 /** The list of loose pages that became unused and may be reused
1174 * in this transaction, linked through #NEXT_LOOSE_PAGE(page).
1176 MDB_page *mt_loose_pgs;
1177 /* #Number of loose pages (#mt_loose_pgs) */
1179 /** The sorted list of dirty pages we temporarily wrote to disk
1180 * because the dirty list was full. page numbers in here are
1181 * shifted left by 1, deleted slots have the LSB set.
1183 MDB_IDL mt_spill_pgs;
1185 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
1186 MDB_ID2L dirty_list;
1187 /** For read txns: This thread/txn's reader table slot, or NULL. */
1190 /** Array of records for each DB known in the environment. */
1192 /** Array of MDB_db records for each known DB */
1194 /** Array of sequence numbers for each DB handle */
1195 unsigned int *mt_dbiseqs;
1196 /** @defgroup mt_dbflag Transaction DB Flags
1200 #define DB_DIRTY 0x01 /**< DB was modified or is DUPSORT data */
1201 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
1202 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
1203 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
1204 #define DB_USRVALID 0x10 /**< As #DB_VALID, but not set for #FREE_DBI */
1206 /** In write txns, array of cursors for each DB */
1207 MDB_cursor **mt_cursors;
1208 /** Array of flags for each DB */
1209 unsigned char *mt_dbflags;
1211 /** List of read-only pages (actually chunks) */
1213 /** We map chunks of 16 pages. Even though Windows uses 4KB pages, all
1214 * mappings must begin on 64KB boundaries. So we round off all pgnos to
1215 * a chunk boundary. We do the same on Linux for symmetry, and also to
1216 * reduce the frequency of mmap/munmap calls.
1218 #define MDB_RPAGE_CHUNK 16
1219 #define MDB_TRPAGE_SIZE 4096 /**< size of #mt_rpages array of chunks */
1220 #define MDB_TRPAGE_MAX (MDB_TRPAGE_SIZE-1) /**< maximum chunk index */
1221 unsigned int mt_rpcheck; /**< threshold for reclaiming unref'd chunks */
1223 /** Number of DB records in use, or 0 when the txn is finished.
1224 * This number only ever increments until the txn finishes; we
1225 * don't decrement it when individual DB handles are closed.
1229 /** @defgroup mdb_txn Transaction Flags
1233 /** #mdb_txn_begin() flags */
1234 #define MDB_TXN_BEGIN_FLAGS (MDB_NOMETASYNC|MDB_NOSYNC|MDB_RDONLY)
1235 #define MDB_TXN_NOMETASYNC MDB_NOMETASYNC /**< don't sync meta for this txn on commit */
1236 #define MDB_TXN_NOSYNC MDB_NOSYNC /**< don't sync this txn on commit */
1237 #define MDB_TXN_RDONLY MDB_RDONLY /**< read-only transaction */
1238 /* internal txn flags */
1239 #define MDB_TXN_WRITEMAP MDB_WRITEMAP /**< copy of #MDB_env flag in writers */
1240 #define MDB_TXN_FINISHED 0x01 /**< txn is finished or never began */
1241 #define MDB_TXN_ERROR 0x02 /**< txn is unusable after an error */
1242 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
1243 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
1244 #define MDB_TXN_HAS_CHILD 0x10 /**< txn has an #MDB_txn.%mt_child */
1245 /** most operations on the txn are currently illegal */
1246 #define MDB_TXN_BLOCKED (MDB_TXN_FINISHED|MDB_TXN_ERROR|MDB_TXN_HAS_CHILD)
1248 unsigned int mt_flags; /**< @ref mdb_txn */
1249 /** #dirty_list room: Array size - \#dirty pages visible to this txn.
1250 * Includes ancestor txns' dirty pages not hidden by other txns'
1251 * dirty/spilled pages. Thus commit(nested txn) has room to merge
1252 * dirty_list into mt_parent after freeing hidden mt_parent pages.
1254 unsigned int mt_dirty_room;
1257 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
1258 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
1259 * raise this on a 64 bit machine.
1261 #define CURSOR_STACK 32
1265 /** Cursors are used for all DB operations.
1266 * A cursor holds a path of (page pointer, key index) from the DB
1267 * root to a position in the DB, plus other state. #MDB_DUPSORT
1268 * cursors include an xcursor to the current data item. Write txns
1269 * track their cursors and keep them up to date when data moves.
1270 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
1271 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
1274 /** Next cursor on this DB in this txn */
1275 MDB_cursor *mc_next;
1276 /** Backup of the original cursor if this cursor is a shadow */
1277 MDB_cursor *mc_backup;
1278 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
1279 struct MDB_xcursor *mc_xcursor;
1280 /** The transaction that owns this cursor */
1282 /** The database handle this cursor operates on */
1284 /** The database record for this cursor */
1286 /** The database auxiliary record for this cursor */
1288 /** The @ref mt_dbflag for this database */
1289 unsigned char *mc_dbflag;
1290 unsigned short mc_snum; /**< number of pushed pages */
1291 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
1292 /** @defgroup mdb_cursor Cursor Flags
1294 * Cursor state flags.
1297 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
1298 #define C_EOF 0x02 /**< No more data */
1299 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
1300 #define C_DEL 0x08 /**< last op was a cursor_del */
1301 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
1302 #define C_WRITEMAP MDB_TXN_WRITEMAP /**< Copy of txn flag */
1303 /** Read-only cursor into the txn's original snapshot in the map.
1304 * Set for read-only txns, and in #mdb_page_alloc() for #FREE_DBI when
1305 * #MDB_DEVEL & 2. Only implements code which is necessary for this.
1307 #define C_ORIG_RDONLY MDB_TXN_RDONLY
1309 unsigned int mc_flags; /**< @ref mdb_cursor */
1310 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
1311 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
1313 MDB_page *mc_ovpg; /**< a referenced overflow page */
1317 /** Context for sorted-dup records.
1318 * We could have gone to a fully recursive design, with arbitrarily
1319 * deep nesting of sub-databases. But for now we only handle these
1320 * levels - main DB, optional sub-DB, sorted-duplicate DB.
1322 typedef struct MDB_xcursor {
1323 /** A sub-cursor for traversing the Dup DB */
1324 MDB_cursor mx_cursor;
1325 /** The database record for this Dup DB */
1327 /** The auxiliary DB record for this Dup DB */
1329 /** The @ref mt_dbflag for this Dup DB */
1330 unsigned char mx_dbflag;
1333 /** State of FreeDB old pages, stored in the MDB_env */
1334 typedef struct MDB_pgstate {
1335 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1336 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1339 /** The database environment. */
1341 HANDLE me_fd; /**< The main data file */
1342 HANDLE me_lfd; /**< The lock file */
1343 HANDLE me_mfd; /**< just for writing the meta pages */
1344 #if defined(MDB_VL32) && defined(_WIN32)
1345 HANDLE me_fmh; /**< File Mapping handle */
1347 /** Failed to update the meta page. Probably an I/O error. */
1348 #define MDB_FATAL_ERROR 0x80000000U
1349 /** Some fields are initialized. */
1350 #define MDB_ENV_ACTIVE 0x20000000U
1351 /** me_txkey is set */
1352 #define MDB_ENV_TXKEY 0x10000000U
1353 /** fdatasync is unreliable */
1354 #define MDB_FSYNCONLY 0x08000000U
1355 uint32_t me_flags; /**< @ref mdb_env */
1356 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1357 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1358 unsigned int me_maxreaders; /**< size of the reader table */
1359 /** Max #MDB_txninfo.%mti_numreaders of interest to #mdb_env_close() */
1360 volatile int me_close_readers;
1361 MDB_dbi me_numdbs; /**< number of DBs opened */
1362 MDB_dbi me_maxdbs; /**< size of the DB table */
1363 MDB_PID_T me_pid; /**< process ID of this env */
1364 char *me_path; /**< path to the DB files */
1365 char *me_map; /**< the memory map of the data file */
1366 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1367 MDB_meta *me_metas[NUM_METAS]; /**< pointers to the two meta pages */
1368 void *me_pbuf; /**< scratch area for DUPSORT put() */
1369 MDB_txn *me_txn; /**< current write transaction */
1370 MDB_txn *me_txn0; /**< prealloc'd write transaction */
1371 mdb_size_t me_mapsize; /**< size of the data memory map */
1372 off_t me_size; /**< current file size */
1373 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1374 MDB_dbx *me_dbxs; /**< array of static DB info */
1375 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1376 unsigned int *me_dbiseqs; /**< array of dbi sequence numbers */
1377 pthread_key_t me_txkey; /**< thread-key for readers */
1378 txnid_t me_pgoldest; /**< ID of oldest reader last time we looked */
1379 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1380 # define me_pglast me_pgstate.mf_pglast
1381 # define me_pghead me_pgstate.mf_pghead
1382 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1383 /** IDL of pages that became unused in a write txn */
1384 MDB_IDL me_free_pgs;
1385 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1386 MDB_ID2L me_dirty_list;
1387 /** Max number of freelist items that can fit in a single overflow page */
1389 /** Max size of a node on a page */
1390 unsigned int me_nodemax;
1391 #if !(MDB_MAXKEYSIZE)
1392 unsigned int me_maxkey; /**< max size of a key */
1394 int me_live_reader; /**< have liveness lock in reader table */
1396 int me_pidquery; /**< Used in OpenProcess */
1398 #ifdef MDB_USE_POSIX_MUTEX /* Posix mutexes reside in shared mem */
1399 # define me_rmutex me_txns->mti_rmutex /**< Shared reader lock */
1400 # define me_wmutex me_txns->mti_wmutex /**< Shared writer lock */
1402 mdb_mutex_t me_rmutex;
1403 mdb_mutex_t me_wmutex;
1406 MDB_ID3L me_rpages; /**< like #mt_rpages, but global to env */
1407 pthread_mutex_t me_rpmutex; /**< control access to #me_rpages */
1408 #define MDB_ERPAGE_SIZE 16384
1409 #define MDB_ERPAGE_MAX (MDB_ERPAGE_SIZE-1)
1410 unsigned int me_rpcheck;
1412 void *me_userctx; /**< User-settable context */
1413 MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
1416 /** Nested transaction */
1417 typedef struct MDB_ntxn {
1418 MDB_txn mnt_txn; /**< the transaction */
1419 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1422 /** max number of pages to commit in one writev() call */
1423 #define MDB_COMMIT_PAGES 64
1424 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1425 #undef MDB_COMMIT_PAGES
1426 #define MDB_COMMIT_PAGES IOV_MAX
1429 /** max bytes to write in one call */
1430 #define MAX_WRITE (0x40000000U >> (sizeof(ssize_t) == 4))
1432 /** Check \b txn and \b dbi arguments to a function */
1433 #define TXN_DBI_EXIST(txn, dbi, validity) \
1434 ((txn) && (dbi)<(txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & (validity)))
1436 /** Check for misused \b dbi handles */
1437 #define TXN_DBI_CHANGED(txn, dbi) \
1438 ((txn)->mt_dbiseqs[dbi] != (txn)->mt_env->me_dbiseqs[dbi])
1440 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1441 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1442 static int mdb_page_touch(MDB_cursor *mc);
1444 #define MDB_END_NAMES {"committed", "empty-commit", "abort", "reset", \
1445 "reset-tmp", "fail-begin", "fail-beginchild"}
1447 /* mdb_txn_end operation number, for logging */
1448 MDB_END_COMMITTED, MDB_END_EMPTY_COMMIT, MDB_END_ABORT, MDB_END_RESET,
1449 MDB_END_RESET_TMP, MDB_END_FAIL_BEGIN, MDB_END_FAIL_BEGINCHILD
1451 #define MDB_END_OPMASK 0x0F /**< mask for #mdb_txn_end() operation number */
1452 #define MDB_END_UPDATE 0x10 /**< update env state (DBIs) */
1453 #define MDB_END_FREE 0x20 /**< free txn unless it is #MDB_env.%me_txn0 */
1454 #define MDB_END_SLOT MDB_NOTLS /**< release any reader slot if #MDB_NOTLS */
1455 static void mdb_txn_end(MDB_txn *txn, unsigned mode);
1457 static int mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **mp, int *lvl);
1458 static int mdb_page_search_root(MDB_cursor *mc,
1459 MDB_val *key, int modify);
1460 #define MDB_PS_MODIFY 1
1461 #define MDB_PS_ROOTONLY 2
1462 #define MDB_PS_FIRST 4
1463 #define MDB_PS_LAST 8
1464 static int mdb_page_search(MDB_cursor *mc,
1465 MDB_val *key, int flags);
1466 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1468 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1469 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1470 pgno_t newpgno, unsigned int nflags);
1472 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1473 static MDB_meta *mdb_env_pick_meta(const MDB_env *env);
1474 static int mdb_env_write_meta(MDB_txn *txn);
1475 #ifdef MDB_USE_POSIX_MUTEX /* Drop unused excl arg */
1476 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1478 static void mdb_env_close0(MDB_env *env, int excl);
1480 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1481 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1482 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1483 static void mdb_node_del(MDB_cursor *mc, int ksize);
1484 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1485 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft);
1486 static int mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data);
1487 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1488 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1490 static int mdb_rebalance(MDB_cursor *mc);
1491 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1493 static void mdb_cursor_pop(MDB_cursor *mc);
1494 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1496 static int mdb_cursor_del0(MDB_cursor *mc);
1497 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
1498 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1499 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1500 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1501 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1503 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1504 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1506 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1507 static void mdb_xcursor_init0(MDB_cursor *mc);
1508 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1509 static void mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int force);
1511 static int mdb_drop0(MDB_cursor *mc, int subs);
1512 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1513 static int mdb_reader_check0(MDB_env *env, int rlocked, int *dead);
1516 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1519 /** Compare two items pointing at size_t's of unknown alignment. */
1520 #ifdef MISALIGNED_OK
1521 # define mdb_cmp_clong mdb_cmp_long
1523 # define mdb_cmp_clong mdb_cmp_cint
1527 static SECURITY_DESCRIPTOR mdb_null_sd;
1528 static SECURITY_ATTRIBUTES mdb_all_sa;
1529 static int mdb_sec_inited;
1531 static int utf8_to_utf16(const char *src, int srcsize, wchar_t **dst, int *dstsize);
1534 /** Return the library version info. */
1536 mdb_version(int *major, int *minor, int *patch)
1538 if (major) *major = MDB_VERSION_MAJOR;
1539 if (minor) *minor = MDB_VERSION_MINOR;
1540 if (patch) *patch = MDB_VERSION_PATCH;
1541 return MDB_VERSION_STRING;
1544 /** Table of descriptions for LMDB @ref errors */
1545 static char *const mdb_errstr[] = {
1546 "MDB_KEYEXIST: Key/data pair already exists",
1547 "MDB_NOTFOUND: No matching key/data pair found",
1548 "MDB_PAGE_NOTFOUND: Requested page not found",
1549 "MDB_CORRUPTED: Located page was wrong type",
1550 "MDB_PANIC: Update of meta page failed or environment had fatal error",
1551 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1552 "MDB_INVALID: File is not an LMDB file",
1553 "MDB_MAP_FULL: Environment mapsize limit reached",
1554 "MDB_DBS_FULL: Environment maxdbs limit reached",
1555 "MDB_READERS_FULL: Environment maxreaders limit reached",
1556 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1557 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1558 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1559 "MDB_PAGE_FULL: Internal error - page has no more space",
1560 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1561 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1562 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1563 "MDB_BAD_TXN: Transaction must abort, has a child, or is invalid",
1564 "MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
1565 "MDB_BAD_DBI: The specified DBI handle was closed/changed unexpectedly",
1569 mdb_strerror(int err)
1572 /** HACK: pad 4KB on stack over the buf. Return system msgs in buf.
1573 * This works as long as no function between the call to mdb_strerror
1574 * and the actual use of the message uses more than 4K of stack.
1576 #define MSGSIZE 1024
1577 #define PADSIZE 4096
1578 char buf[MSGSIZE+PADSIZE], *ptr = buf;
1582 return ("Successful return: 0");
1584 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1585 i = err - MDB_KEYEXIST;
1586 return mdb_errstr[i];
1590 /* These are the C-runtime error codes we use. The comment indicates
1591 * their numeric value, and the Win32 error they would correspond to
1592 * if the error actually came from a Win32 API. A major mess, we should
1593 * have used LMDB-specific error codes for everything.
1596 case ENOENT: /* 2, FILE_NOT_FOUND */
1597 case EIO: /* 5, ACCESS_DENIED */
1598 case ENOMEM: /* 12, INVALID_ACCESS */
1599 case EACCES: /* 13, INVALID_DATA */
1600 case EBUSY: /* 16, CURRENT_DIRECTORY */
1601 case EINVAL: /* 22, BAD_COMMAND */
1602 case ENOSPC: /* 28, OUT_OF_PAPER */
1603 return strerror(err);
1608 FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
1609 FORMAT_MESSAGE_IGNORE_INSERTS,
1610 NULL, err, 0, ptr, MSGSIZE, (va_list *)buf+MSGSIZE);
1613 return strerror(err);
1617 /** assert(3) variant in cursor context */
1618 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1619 /** assert(3) variant in transaction context */
1620 #define mdb_tassert(txn, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1621 /** assert(3) variant in environment context */
1622 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1625 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1626 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1629 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1630 const char *func, const char *file, int line)
1633 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1634 file, line, expr_txt, func);
1635 if (env->me_assert_func)
1636 env->me_assert_func(env, buf);
1637 fprintf(stderr, "%s\n", buf);
1641 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1645 /** Return the page number of \b mp which may be sub-page, for debug output */
1647 mdb_dbg_pgno(MDB_page *mp)
1650 COPY_PGNO(ret, mp->mp_pgno);
1654 /** Display a key in hexadecimal and return the address of the result.
1655 * @param[in] key the key to display
1656 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1657 * @return The key in hexadecimal form.
1660 mdb_dkey(MDB_val *key, char *buf)
1663 unsigned char *c = key->mv_data;
1669 if (key->mv_size > DKBUF_MAXKEYSIZE)
1670 return "MDB_MAXKEYSIZE";
1671 /* may want to make this a dynamic check: if the key is mostly
1672 * printable characters, print it as-is instead of converting to hex.
1676 for (i=0; i<key->mv_size; i++)
1677 ptr += sprintf(ptr, "%02x", *c++);
1679 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1685 mdb_leafnode_type(MDB_node *n)
1687 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1688 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1689 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1692 /** Display all the keys in the page. */
1694 mdb_page_list(MDB_page *mp)
1696 pgno_t pgno = mdb_dbg_pgno(mp);
1697 const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
1699 unsigned int i, nkeys, nsize, total = 0;
1703 switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1704 case P_BRANCH: type = "Branch page"; break;
1705 case P_LEAF: type = "Leaf page"; break;
1706 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1707 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1708 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1710 fprintf(stderr, "Overflow page %"Y"u pages %u%s\n",
1711 pgno, mp->mp_pages, state);
1714 fprintf(stderr, "Meta-page %"Y"u txnid %"Y"u\n",
1715 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1718 fprintf(stderr, "Bad page %"Y"u flags 0x%u\n", pgno, mp->mp_flags);
1722 nkeys = NUMKEYS(mp);
1723 fprintf(stderr, "%s %"Y"u numkeys %d%s\n", type, pgno, nkeys, state);
1725 for (i=0; i<nkeys; i++) {
1726 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1727 key.mv_size = nsize = mp->mp_pad;
1728 key.mv_data = LEAF2KEY(mp, i, nsize);
1730 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1733 node = NODEPTR(mp, i);
1734 key.mv_size = node->mn_ksize;
1735 key.mv_data = node->mn_data;
1736 nsize = NODESIZE + key.mv_size;
1737 if (IS_BRANCH(mp)) {
1738 fprintf(stderr, "key %d: page %"Y"u, %s\n", i, NODEPGNO(node),
1742 if (F_ISSET(node->mn_flags, F_BIGDATA))
1743 nsize += sizeof(pgno_t);
1745 nsize += NODEDSZ(node);
1747 nsize += sizeof(indx_t);
1748 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1749 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1751 total = EVEN(total);
1753 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1754 IS_LEAF2(mp) ? PAGEHDRSZ : PAGEBASE + mp->mp_lower, total, SIZELEFT(mp));
1758 mdb_cursor_chk(MDB_cursor *mc)
1764 if (!mc->mc_snum || !(mc->mc_flags & C_INITIALIZED)) return;
1765 for (i=0; i<mc->mc_top; i++) {
1767 node = NODEPTR(mp, mc->mc_ki[i]);
1768 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1771 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1773 if (mc->mc_xcursor && (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
1774 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
1775 if (((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) &&
1776 mc->mc_xcursor->mx_cursor.mc_pg[0] != NODEDATA(node)) {
1784 /** Count all the pages in each DB and in the freelist
1785 * and make sure it matches the actual number of pages
1787 * All named DBs must be open for a correct count.
1789 static void mdb_audit(MDB_txn *txn)
1793 MDB_ID freecount, count;
1798 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1799 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1800 freecount += *(MDB_ID *)data.mv_data;
1801 mdb_tassert(txn, rc == MDB_NOTFOUND);
1804 for (i = 0; i<txn->mt_numdbs; i++) {
1806 if (!(txn->mt_dbflags[i] & DB_VALID))
1808 mdb_cursor_init(&mc, txn, i, &mx);
1809 if (txn->mt_dbs[i].md_root == P_INVALID)
1811 count += txn->mt_dbs[i].md_branch_pages +
1812 txn->mt_dbs[i].md_leaf_pages +
1813 txn->mt_dbs[i].md_overflow_pages;
1814 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1815 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1816 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
1819 mp = mc.mc_pg[mc.mc_top];
1820 for (j=0; j<NUMKEYS(mp); j++) {
1821 MDB_node *leaf = NODEPTR(mp, j);
1822 if (leaf->mn_flags & F_SUBDATA) {
1824 memcpy(&db, NODEDATA(leaf), sizeof(db));
1825 count += db.md_branch_pages + db.md_leaf_pages +
1826 db.md_overflow_pages;
1830 mdb_tassert(txn, rc == MDB_NOTFOUND);
1833 if (freecount + count + NUM_METAS != txn->mt_next_pgno) {
1834 fprintf(stderr, "audit: %"Y"u freecount: %"Y"u count: %"Y"u total: %"Y"u next_pgno: %"Y"u\n",
1835 txn->mt_txnid, freecount, count+NUM_METAS,
1836 freecount+count+NUM_METAS, txn->mt_next_pgno);
1842 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1844 return txn->mt_dbxs[dbi].md_cmp(a, b);
1848 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1850 MDB_cmp_func *dcmp = txn->mt_dbxs[dbi].md_dcmp;
1851 #if UINT_MAX < SIZE_MAX || defined(MDB_VL32)
1852 if (dcmp == mdb_cmp_int && a->mv_size == sizeof(mdb_size_t))
1853 dcmp = mdb_cmp_clong;
1858 /** Allocate memory for a page.
1859 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1862 mdb_page_malloc(MDB_txn *txn, unsigned num)
1864 MDB_env *env = txn->mt_env;
1865 MDB_page *ret = env->me_dpages;
1866 size_t psize = env->me_psize, sz = psize, off;
1867 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1868 * For a single page alloc, we init everything after the page header.
1869 * For multi-page, we init the final page; if the caller needed that
1870 * many pages they will be filling in at least up to the last page.
1874 VGMEMP_ALLOC(env, ret, sz);
1875 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1876 env->me_dpages = ret->mp_next;
1879 psize -= off = PAGEHDRSZ;
1884 if ((ret = malloc(sz)) != NULL) {
1885 VGMEMP_ALLOC(env, ret, sz);
1886 if (!(env->me_flags & MDB_NOMEMINIT)) {
1887 memset((char *)ret + off, 0, psize);
1891 txn->mt_flags |= MDB_TXN_ERROR;
1895 /** Free a single page.
1896 * Saves single pages to a list, for future reuse.
1897 * (This is not used for multi-page overflow pages.)
1900 mdb_page_free(MDB_env *env, MDB_page *mp)
1902 mp->mp_next = env->me_dpages;
1903 VGMEMP_FREE(env, mp);
1904 env->me_dpages = mp;
1907 /** Free a dirty page */
1909 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1911 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1912 mdb_page_free(env, dp);
1914 /* large pages just get freed directly */
1915 VGMEMP_FREE(env, dp);
1920 /** Return all dirty pages to dpage list */
1922 mdb_dlist_free(MDB_txn *txn)
1924 MDB_env *env = txn->mt_env;
1925 MDB_ID2L dl = txn->mt_u.dirty_list;
1926 unsigned i, n = dl[0].mid;
1928 for (i = 1; i <= n; i++) {
1929 mdb_dpage_free(env, dl[i].mptr);
1936 mdb_page_unref(MDB_txn *txn, MDB_page *mp)
1939 MDB_ID3L tl = txn->mt_rpages;
1941 if (mp->mp_flags & (P_SUBP|P_DIRTY))
1943 rem = mp->mp_pgno & (MDB_RPAGE_CHUNK-1);
1944 pgno = mp->mp_pgno ^ rem;
1945 x = mdb_mid3l_search(tl, pgno);
1946 if (x != tl[0].mid && tl[x+1].mid == mp->mp_pgno)
1951 #define MDB_PAGE_UNREF(txn, mp) mdb_page_unref(txn, mp)
1954 mdb_cursor_unref(MDB_cursor *mc)
1957 if (!mc->mc_snum || !mc->mc_pg[0] || IS_SUBP(mc->mc_pg[0]))
1959 for (i=0; i<mc->mc_snum; i++)
1960 mdb_page_unref(mc->mc_txn, mc->mc_pg[i]);
1962 mdb_page_unref(mc->mc_txn, mc->mc_ovpg);
1965 mc->mc_snum = mc->mc_top = 0;
1966 mc->mc_pg[0] = NULL;
1967 mc->mc_flags &= ~C_INITIALIZED;
1970 #define MDB_PAGE_UNREF(txn, mp)
1971 #endif /* MDB_VL32 */
1973 /** Loosen or free a single page.
1974 * Saves single pages to a list for future reuse
1975 * in this same txn. It has been pulled from the freeDB
1976 * and already resides on the dirty list, but has been
1977 * deleted. Use these pages first before pulling again
1980 * If the page wasn't dirtied in this txn, just add it
1981 * to this txn's free list.
1984 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
1987 pgno_t pgno = mp->mp_pgno;
1988 MDB_txn *txn = mc->mc_txn;
1990 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
1991 if (txn->mt_parent) {
1992 MDB_ID2 *dl = txn->mt_u.dirty_list;
1993 /* If txn has a parent, make sure the page is in our
1997 unsigned x = mdb_mid2l_search(dl, pgno);
1998 if (x <= dl[0].mid && dl[x].mid == pgno) {
1999 if (mp != dl[x].mptr) { /* bad cursor? */
2000 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2001 txn->mt_flags |= MDB_TXN_ERROR;
2002 return MDB_CORRUPTED;
2009 /* no parent txn, so it's just ours */
2014 DPRINTF(("loosen db %d page %"Y"u", DDBI(mc),
2016 NEXT_LOOSE_PAGE(mp) = txn->mt_loose_pgs;
2017 txn->mt_loose_pgs = mp;
2018 txn->mt_loose_count++;
2019 mp->mp_flags |= P_LOOSE;
2021 int rc = mdb_midl_append(&txn->mt_free_pgs, pgno);
2029 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
2030 * @param[in] mc A cursor handle for the current operation.
2031 * @param[in] pflags Flags of the pages to update:
2032 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
2033 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
2034 * @return 0 on success, non-zero on failure.
2037 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
2039 enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
2040 MDB_txn *txn = mc->mc_txn;
2041 MDB_cursor *m3, *m0 = mc;
2046 int rc = MDB_SUCCESS, level;
2048 /* Mark pages seen by cursors */
2049 if (mc->mc_flags & C_UNTRACK)
2050 mc = NULL; /* will find mc in mt_cursors */
2051 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
2052 for (; mc; mc=mc->mc_next) {
2053 if (!(mc->mc_flags & C_INITIALIZED))
2055 for (m3 = mc;; m3 = &mx->mx_cursor) {
2057 for (j=0; j<m3->mc_snum; j++) {
2059 if ((mp->mp_flags & Mask) == pflags)
2060 mp->mp_flags ^= P_KEEP;
2062 mx = m3->mc_xcursor;
2063 /* Proceed to mx if it is at a sub-database */
2064 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
2066 if (! (mp && (mp->mp_flags & P_LEAF)))
2068 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
2069 if (!(leaf->mn_flags & F_SUBDATA))
2078 /* Mark dirty root pages */
2079 for (i=0; i<txn->mt_numdbs; i++) {
2080 if (txn->mt_dbflags[i] & DB_DIRTY) {
2081 pgno_t pgno = txn->mt_dbs[i].md_root;
2082 if (pgno == P_INVALID)
2084 if ((rc = mdb_page_get(m0, pgno, &dp, &level)) != MDB_SUCCESS)
2086 if ((dp->mp_flags & Mask) == pflags && level <= 1)
2087 dp->mp_flags ^= P_KEEP;
2095 static int mdb_page_flush(MDB_txn *txn, int keep);
2097 /** Spill pages from the dirty list back to disk.
2098 * This is intended to prevent running into #MDB_TXN_FULL situations,
2099 * but note that they may still occur in a few cases:
2100 * 1) our estimate of the txn size could be too small. Currently this
2101 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
2102 * 2) child txns may run out of space if their parents dirtied a
2103 * lot of pages and never spilled them. TODO: we probably should do
2104 * a preemptive spill during #mdb_txn_begin() of a child txn, if
2105 * the parent's dirty_room is below a given threshold.
2107 * Otherwise, if not using nested txns, it is expected that apps will
2108 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
2109 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
2110 * If the txn never references them again, they can be left alone.
2111 * If the txn only reads them, they can be used without any fuss.
2112 * If the txn writes them again, they can be dirtied immediately without
2113 * going thru all of the work of #mdb_page_touch(). Such references are
2114 * handled by #mdb_page_unspill().
2116 * Also note, we never spill DB root pages, nor pages of active cursors,
2117 * because we'll need these back again soon anyway. And in nested txns,
2118 * we can't spill a page in a child txn if it was already spilled in a
2119 * parent txn. That would alter the parent txns' data even though
2120 * the child hasn't committed yet, and we'd have no way to undo it if
2121 * the child aborted.
2123 * @param[in] m0 cursor A cursor handle identifying the transaction and
2124 * database for which we are checking space.
2125 * @param[in] key For a put operation, the key being stored.
2126 * @param[in] data For a put operation, the data being stored.
2127 * @return 0 on success, non-zero on failure.
2130 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
2132 MDB_txn *txn = m0->mc_txn;
2134 MDB_ID2L dl = txn->mt_u.dirty_list;
2135 unsigned int i, j, need;
2138 if (m0->mc_flags & C_SUB)
2141 /* Estimate how much space this op will take */
2142 i = m0->mc_db->md_depth;
2143 /* Named DBs also dirty the main DB */
2144 if (m0->mc_dbi >= CORE_DBS)
2145 i += txn->mt_dbs[MAIN_DBI].md_depth;
2146 /* For puts, roughly factor in the key+data size */
2148 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
2149 i += i; /* double it for good measure */
2152 if (txn->mt_dirty_room > i)
2155 if (!txn->mt_spill_pgs) {
2156 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
2157 if (!txn->mt_spill_pgs)
2160 /* purge deleted slots */
2161 MDB_IDL sl = txn->mt_spill_pgs;
2162 unsigned int num = sl[0];
2164 for (i=1; i<=num; i++) {
2171 /* Preserve pages which may soon be dirtied again */
2172 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
2175 /* Less aggressive spill - we originally spilled the entire dirty list,
2176 * with a few exceptions for cursor pages and DB root pages. But this
2177 * turns out to be a lot of wasted effort because in a large txn many
2178 * of those pages will need to be used again. So now we spill only 1/8th
2179 * of the dirty pages. Testing revealed this to be a good tradeoff,
2180 * better than 1/2, 1/4, or 1/10.
2182 if (need < MDB_IDL_UM_MAX / 8)
2183 need = MDB_IDL_UM_MAX / 8;
2185 /* Save the page IDs of all the pages we're flushing */
2186 /* flush from the tail forward, this saves a lot of shifting later on. */
2187 for (i=dl[0].mid; i && need; i--) {
2188 MDB_ID pn = dl[i].mid << 1;
2190 if (dp->mp_flags & (P_LOOSE|P_KEEP))
2192 /* Can't spill twice, make sure it's not already in a parent's
2195 if (txn->mt_parent) {
2197 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
2198 if (tx2->mt_spill_pgs) {
2199 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
2200 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
2201 dp->mp_flags |= P_KEEP;
2209 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
2213 mdb_midl_sort(txn->mt_spill_pgs);
2215 /* Flush the spilled part of dirty list */
2216 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
2219 /* Reset any dirty pages we kept that page_flush didn't see */
2220 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
2223 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
2227 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
2229 mdb_find_oldest(MDB_txn *txn)
2232 txnid_t mr, oldest = txn->mt_txnid - 1;
2233 if (txn->mt_env->me_txns) {
2234 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
2235 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
2246 /** Add a page to the txn's dirty list */
2248 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
2251 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
2253 if (txn->mt_flags & MDB_TXN_WRITEMAP) {
2254 insert = mdb_mid2l_append;
2256 insert = mdb_mid2l_insert;
2258 mid.mid = mp->mp_pgno;
2260 rc = insert(txn->mt_u.dirty_list, &mid);
2261 mdb_tassert(txn, rc == 0);
2262 txn->mt_dirty_room--;
2265 /** Allocate page numbers and memory for writing. Maintain me_pglast,
2266 * me_pghead and mt_next_pgno.
2268 * If there are free pages available from older transactions, they
2269 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
2270 * Do not modify the freedB, just merge freeDB records into me_pghead[]
2271 * and move me_pglast to say which records were consumed. Only this
2272 * function can create me_pghead and move me_pglast/mt_next_pgno.
2273 * When #MDB_DEVEL & 2, it is not affected by #mdb_freelist_save(): it
2274 * then uses the transaction's original snapshot of the freeDB.
2275 * @param[in] mc cursor A cursor handle identifying the transaction and
2276 * database for which we are allocating.
2277 * @param[in] num the number of pages to allocate.
2278 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
2279 * will always be satisfied by a single contiguous chunk of memory.
2280 * @return 0 on success, non-zero on failure.
2283 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
2285 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
2286 /* Get at most <Max_retries> more freeDB records once me_pghead
2287 * has enough pages. If not enough, use new pages from the map.
2288 * If <Paranoid> and mc is updating the freeDB, only get new
2289 * records if me_pghead is empty. Then the freelist cannot play
2290 * catch-up with itself by growing while trying to save it.
2292 enum { Paranoid = 1, Max_retries = 500 };
2294 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
2296 int rc, retry = num * 60;
2297 MDB_txn *txn = mc->mc_txn;
2298 MDB_env *env = txn->mt_env;
2299 pgno_t pgno, *mop = env->me_pghead;
2300 unsigned i, j, mop_len = mop ? mop[0] : 0, n2 = num-1;
2302 txnid_t oldest = 0, last;
2307 /* If there are any loose pages, just use them */
2308 if (num == 1 && txn->mt_loose_pgs) {
2309 np = txn->mt_loose_pgs;
2310 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
2311 txn->mt_loose_count--;
2312 DPRINTF(("db %d use loose page %"Y"u", DDBI(mc),
2320 /* If our dirty list is already full, we can't do anything */
2321 if (txn->mt_dirty_room == 0) {
2326 for (op = MDB_FIRST;; op = MDB_NEXT) {
2331 /* Seek a big enough contiguous page range. Prefer
2332 * pages at the tail, just truncating the list.
2338 if (mop[i-n2] == pgno+n2)
2345 if (op == MDB_FIRST) { /* 1st iteration */
2346 /* Prepare to fetch more and coalesce */
2347 last = env->me_pglast;
2348 oldest = env->me_pgoldest;
2349 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
2350 #if (MDB_DEVEL) & 2 /* "& 2" so MDB_DEVEL=1 won't hide bugs breaking freeDB */
2351 /* Use original snapshot. TODO: Should need less care in code
2352 * which modifies the database. Maybe we can delete some code?
2354 m2.mc_flags |= C_ORIG_RDONLY;
2355 m2.mc_db = &env->me_metas[(txn->mt_txnid-1) & 1]->mm_dbs[FREE_DBI];
2356 m2.mc_dbflag = (unsigned char *)""; /* probably unnecessary */
2360 key.mv_data = &last; /* will look up last+1 */
2361 key.mv_size = sizeof(last);
2363 if (Paranoid && mc->mc_dbi == FREE_DBI)
2366 if (Paranoid && retry < 0 && mop_len)
2370 /* Do not fetch more if the record will be too recent */
2371 if (oldest <= last) {
2373 oldest = mdb_find_oldest(txn);
2374 env->me_pgoldest = oldest;
2380 rc = mdb_cursor_get(&m2, &key, NULL, op);
2382 if (rc == MDB_NOTFOUND)
2386 last = *(txnid_t*)key.mv_data;
2387 if (oldest <= last) {
2389 oldest = mdb_find_oldest(txn);
2390 env->me_pgoldest = oldest;
2396 np = m2.mc_pg[m2.mc_top];
2397 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
2398 if ((rc = mdb_node_read(&m2, leaf, &data)) != MDB_SUCCESS)
2401 idl = (MDB_ID *) data.mv_data;
2404 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
2409 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
2411 mop = env->me_pghead;
2413 env->me_pglast = last;
2415 DPRINTF(("IDL read txn %"Y"u root %"Y"u num %u",
2416 last, txn->mt_dbs[FREE_DBI].md_root, i));
2418 DPRINTF(("IDL %"Y"u", idl[j]));
2420 /* Merge in descending sorted order */
2421 mdb_midl_xmerge(mop, idl);
2425 /* Use new pages from the map when nothing suitable in the freeDB */
2427 pgno = txn->mt_next_pgno;
2428 if (pgno + num >= env->me_maxpg) {
2429 DPUTS("DB size maxed out");
2433 #if defined(_WIN32) && !defined(MDB_VL32)
2434 if (!(env->me_flags & MDB_RDONLY)) {
2436 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
2437 p = VirtualAlloc(p, env->me_psize * num, MEM_COMMIT,
2438 (env->me_flags & MDB_WRITEMAP) ? PAGE_READWRITE:
2441 DPUTS("VirtualAlloc failed");
2449 if (env->me_flags & MDB_WRITEMAP) {
2450 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
2452 if (!(np = mdb_page_malloc(txn, num))) {
2458 mop[0] = mop_len -= num;
2459 /* Move any stragglers down */
2460 for (j = i-num; j < mop_len; )
2461 mop[++j] = mop[++i];
2463 txn->mt_next_pgno = pgno + num;
2466 mdb_page_dirty(txn, np);
2472 txn->mt_flags |= MDB_TXN_ERROR;
2476 /** Copy the used portions of a non-overflow page.
2477 * @param[in] dst page to copy into
2478 * @param[in] src page to copy from
2479 * @param[in] psize size of a page
2482 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2484 enum { Align = sizeof(pgno_t) };
2485 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2487 /* If page isn't full, just copy the used portion. Adjust
2488 * alignment so memcpy may copy words instead of bytes.
2490 if ((unused &= -Align) && !IS_LEAF2(src)) {
2491 upper = (upper + PAGEBASE) & -Align;
2492 memcpy(dst, src, (lower + PAGEBASE + (Align-1)) & -Align);
2493 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2496 memcpy(dst, src, psize - unused);
2500 /** Pull a page off the txn's spill list, if present.
2501 * If a page being referenced was spilled to disk in this txn, bring
2502 * it back and make it dirty/writable again.
2503 * @param[in] txn the transaction handle.
2504 * @param[in] mp the page being referenced. It must not be dirty.
2505 * @param[out] ret the writable page, if any. ret is unchanged if
2506 * mp wasn't spilled.
2509 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2511 MDB_env *env = txn->mt_env;
2514 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2516 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2517 if (!tx2->mt_spill_pgs)
2519 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2520 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2523 if (txn->mt_dirty_room == 0)
2524 return MDB_TXN_FULL;
2525 if (IS_OVERFLOW(mp))
2529 if (env->me_flags & MDB_WRITEMAP) {
2532 np = mdb_page_malloc(txn, num);
2536 memcpy(np, mp, num * env->me_psize);
2538 mdb_page_copy(np, mp, env->me_psize);
2541 /* If in current txn, this page is no longer spilled.
2542 * If it happens to be the last page, truncate the spill list.
2543 * Otherwise mark it as deleted by setting the LSB.
2545 if (x == txn->mt_spill_pgs[0])
2546 txn->mt_spill_pgs[0]--;
2548 txn->mt_spill_pgs[x] |= 1;
2549 } /* otherwise, if belonging to a parent txn, the
2550 * page remains spilled until child commits
2553 mdb_page_dirty(txn, np);
2554 np->mp_flags |= P_DIRTY;
2562 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2563 * @param[in] mc cursor pointing to the page to be touched
2564 * @return 0 on success, non-zero on failure.
2567 mdb_page_touch(MDB_cursor *mc)
2569 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2570 MDB_txn *txn = mc->mc_txn;
2571 MDB_cursor *m2, *m3;
2575 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2576 if (txn->mt_flags & MDB_TXN_SPILLS) {
2578 rc = mdb_page_unspill(txn, mp, &np);
2584 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2585 (rc = mdb_page_alloc(mc, 1, &np)))
2588 DPRINTF(("touched db %d page %"Y"u -> %"Y"u", DDBI(mc),
2589 mp->mp_pgno, pgno));
2590 mdb_cassert(mc, mp->mp_pgno != pgno);
2591 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2592 /* Update the parent page, if any, to point to the new page */
2594 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2595 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2596 SETPGNO(node, pgno);
2598 mc->mc_db->md_root = pgno;
2600 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2601 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2603 /* If txn has a parent, make sure the page is in our
2607 unsigned x = mdb_mid2l_search(dl, pgno);
2608 if (x <= dl[0].mid && dl[x].mid == pgno) {
2609 if (mp != dl[x].mptr) { /* bad cursor? */
2610 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2611 txn->mt_flags |= MDB_TXN_ERROR;
2612 return MDB_CORRUPTED;
2617 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2619 np = mdb_page_malloc(txn, 1);
2624 rc = mdb_mid2l_insert(dl, &mid);
2625 mdb_cassert(mc, rc == 0);
2630 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2632 np->mp_flags |= P_DIRTY;
2635 /* Adjust cursors pointing to mp */
2636 mc->mc_pg[mc->mc_top] = np;
2637 m2 = txn->mt_cursors[mc->mc_dbi];
2638 if (mc->mc_flags & C_SUB) {
2639 for (; m2; m2=m2->mc_next) {
2640 m3 = &m2->mc_xcursor->mx_cursor;
2641 if (m3->mc_snum < mc->mc_snum) continue;
2642 if (m3->mc_pg[mc->mc_top] == mp)
2643 m3->mc_pg[mc->mc_top] = np;
2646 for (; m2; m2=m2->mc_next) {
2647 if (m2->mc_snum < mc->mc_snum) continue;
2648 if (m2 == mc) continue;
2649 if (m2->mc_pg[mc->mc_top] == mp) {
2650 m2->mc_pg[mc->mc_top] = np;
2651 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
2653 (m2->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
2655 MDB_node *leaf = NODEPTR(np, m2->mc_ki[mc->mc_top]);
2656 if ((leaf->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
2657 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
2662 MDB_PAGE_UNREF(mc->mc_txn, mp);
2666 txn->mt_flags |= MDB_TXN_ERROR;
2671 mdb_env_sync0(MDB_env *env, int force, pgno_t numpgs)
2674 if (env->me_flags & MDB_RDONLY)
2676 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2677 if (env->me_flags & MDB_WRITEMAP) {
2678 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2679 ? MS_ASYNC : MS_SYNC;
2680 if (MDB_MSYNC(env->me_map, env->me_psize * numpgs, flags))
2683 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2687 #ifdef BROKEN_FDATASYNC
2688 if (env->me_flags & MDB_FSYNCONLY) {
2689 if (fsync(env->me_fd))
2693 if (MDB_FDATASYNC(env->me_fd))
2701 mdb_env_sync(MDB_env *env, int force)
2703 MDB_meta *m = mdb_env_pick_meta(env);
2704 return mdb_env_sync0(env, force, m->mm_last_pg+1);
2707 /** Back up parent txn's cursors, then grab the originals for tracking */
2709 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2711 MDB_cursor *mc, *bk;
2716 for (i = src->mt_numdbs; --i >= 0; ) {
2717 if ((mc = src->mt_cursors[i]) != NULL) {
2718 size = sizeof(MDB_cursor);
2720 size += sizeof(MDB_xcursor);
2721 for (; mc; mc = bk->mc_next) {
2727 mc->mc_db = &dst->mt_dbs[i];
2728 /* Kill pointers into src to reduce abuse: The
2729 * user may not use mc until dst ends. But we need a valid
2730 * txn pointer here for cursor fixups to keep working.
2733 mc->mc_dbflag = &dst->mt_dbflags[i];
2734 if ((mx = mc->mc_xcursor) != NULL) {
2735 *(MDB_xcursor *)(bk+1) = *mx;
2736 mx->mx_cursor.mc_txn = dst;
2738 mc->mc_next = dst->mt_cursors[i];
2739 dst->mt_cursors[i] = mc;
2746 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2747 * @param[in] txn the transaction handle.
2748 * @param[in] merge true to keep changes to parent cursors, false to revert.
2749 * @return 0 on success, non-zero on failure.
2752 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2754 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2758 for (i = txn->mt_numdbs; --i >= 0; ) {
2759 for (mc = cursors[i]; mc; mc = next) {
2761 if ((bk = mc->mc_backup) != NULL) {
2763 /* Commit changes to parent txn */
2764 mc->mc_next = bk->mc_next;
2765 mc->mc_backup = bk->mc_backup;
2766 mc->mc_txn = bk->mc_txn;
2767 mc->mc_db = bk->mc_db;
2768 mc->mc_dbflag = bk->mc_dbflag;
2769 if ((mx = mc->mc_xcursor) != NULL)
2770 mx->mx_cursor.mc_txn = bk->mc_txn;
2772 /* Abort nested txn */
2774 if ((mx = mc->mc_xcursor) != NULL)
2775 *mx = *(MDB_xcursor *)(bk+1);
2779 /* Only malloced cursors are permanently tracked. */
2786 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2792 Pidset = F_SETLK, Pidcheck = F_GETLK
2796 /** Set or check a pid lock. Set returns 0 on success.
2797 * Check returns 0 if the process is certainly dead, nonzero if it may
2798 * be alive (the lock exists or an error happened so we do not know).
2800 * On Windows Pidset is a no-op, we merely check for the existence
2801 * of the process with the given pid. On POSIX we use a single byte
2802 * lock on the lockfile, set at an offset equal to the pid.
2805 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2807 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2810 if (op == Pidcheck) {
2811 h = OpenProcess(env->me_pidquery, FALSE, pid);
2812 /* No documented "no such process" code, but other program use this: */
2814 return ErrCode() != ERROR_INVALID_PARAMETER;
2815 /* A process exists until all handles to it close. Has it exited? */
2816 ret = WaitForSingleObject(h, 0) != 0;
2823 struct flock lock_info;
2824 memset(&lock_info, 0, sizeof(lock_info));
2825 lock_info.l_type = F_WRLCK;
2826 lock_info.l_whence = SEEK_SET;
2827 lock_info.l_start = pid;
2828 lock_info.l_len = 1;
2829 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2830 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2832 } else if ((rc = ErrCode()) == EINTR) {
2840 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2841 * @param[in] txn the transaction handle to initialize
2842 * @return 0 on success, non-zero on failure.
2845 mdb_txn_renew0(MDB_txn *txn)
2847 MDB_env *env = txn->mt_env;
2848 MDB_txninfo *ti = env->me_txns;
2850 unsigned int i, nr, flags = txn->mt_flags;
2852 int rc, new_notls = 0;
2854 if ((flags &= MDB_TXN_RDONLY) != 0) {
2856 meta = mdb_env_pick_meta(env);
2857 txn->mt_txnid = meta->mm_txnid;
2858 txn->mt_u.reader = NULL;
2860 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2861 pthread_getspecific(env->me_txkey);
2863 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2864 return MDB_BAD_RSLOT;
2866 MDB_PID_T pid = env->me_pid;
2867 MDB_THR_T tid = pthread_self();
2868 mdb_mutexref_t rmutex = env->me_rmutex;
2870 if (!env->me_live_reader) {
2871 rc = mdb_reader_pid(env, Pidset, pid);
2874 env->me_live_reader = 1;
2877 if (LOCK_MUTEX(rc, env, rmutex))
2879 nr = ti->mti_numreaders;
2880 for (i=0; i<nr; i++)
2881 if (ti->mti_readers[i].mr_pid == 0)
2883 if (i == env->me_maxreaders) {
2884 UNLOCK_MUTEX(rmutex);
2885 return MDB_READERS_FULL;
2887 r = &ti->mti_readers[i];
2888 /* Claim the reader slot, carefully since other code
2889 * uses the reader table un-mutexed: First reset the
2890 * slot, next publish it in mti_numreaders. After
2891 * that, it is safe for mdb_env_close() to touch it.
2892 * When it will be closed, we can finally claim it.
2895 r->mr_txnid = (txnid_t)-1;
2898 ti->mti_numreaders = ++nr;
2899 env->me_close_readers = nr;
2901 UNLOCK_MUTEX(rmutex);
2903 new_notls = (env->me_flags & MDB_NOTLS);
2904 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2909 do /* LY: Retry on a race, ITS#7970. */
2910 r->mr_txnid = ti->mti_txnid;
2911 while(r->mr_txnid != ti->mti_txnid);
2912 txn->mt_txnid = r->mr_txnid;
2913 txn->mt_u.reader = r;
2914 meta = env->me_metas[txn->mt_txnid & 1];
2918 /* Not yet touching txn == env->me_txn0, it may be active */
2920 if (LOCK_MUTEX(rc, env, env->me_wmutex))
2922 txn->mt_txnid = ti->mti_txnid;
2923 meta = env->me_metas[txn->mt_txnid & 1];
2925 meta = mdb_env_pick_meta(env);
2926 txn->mt_txnid = meta->mm_txnid;
2930 if (txn->mt_txnid == mdb_debug_start)
2933 txn->mt_child = NULL;
2934 txn->mt_loose_pgs = NULL;
2935 txn->mt_loose_count = 0;
2936 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2937 txn->mt_u.dirty_list = env->me_dirty_list;
2938 txn->mt_u.dirty_list[0].mid = 0;
2939 txn->mt_free_pgs = env->me_free_pgs;
2940 txn->mt_free_pgs[0] = 0;
2941 txn->mt_spill_pgs = NULL;
2943 memcpy(txn->mt_dbiseqs, env->me_dbiseqs, env->me_maxdbs * sizeof(unsigned int));
2946 /* Copy the DB info and flags */
2947 memcpy(txn->mt_dbs, meta->mm_dbs, CORE_DBS * sizeof(MDB_db));
2949 /* Moved to here to avoid a data race in read TXNs */
2950 txn->mt_next_pgno = meta->mm_last_pg+1;
2952 txn->mt_last_pgno = txn->mt_next_pgno - 1;
2955 txn->mt_flags = flags;
2958 txn->mt_numdbs = env->me_numdbs;
2959 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
2960 x = env->me_dbflags[i];
2961 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2962 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_USRVALID|DB_STALE : 0;
2964 txn->mt_dbflags[MAIN_DBI] = DB_VALID|DB_USRVALID;
2965 txn->mt_dbflags[FREE_DBI] = DB_VALID;
2967 if (env->me_flags & MDB_FATAL_ERROR) {
2968 DPUTS("environment had fatal error, must shutdown!");
2970 } else if (env->me_maxpg < txn->mt_next_pgno) {
2971 rc = MDB_MAP_RESIZED;
2975 mdb_txn_end(txn, new_notls /*0 or MDB_END_SLOT*/ | MDB_END_FAIL_BEGIN);
2980 mdb_txn_renew(MDB_txn *txn)
2984 if (!txn || !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY|MDB_TXN_FINISHED))
2987 rc = mdb_txn_renew0(txn);
2988 if (rc == MDB_SUCCESS) {
2989 DPRINTF(("renew txn %"Y"u%c %p on mdbenv %p, root page %"Y"u",
2990 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2991 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2997 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
3001 int rc, size, tsize;
3003 flags &= MDB_TXN_BEGIN_FLAGS;
3004 flags |= env->me_flags & MDB_WRITEMAP;
3006 if (env->me_flags & MDB_RDONLY & ~flags) /* write txn in RDONLY env */
3010 /* Nested transactions: Max 1 child, write txns only, no writemap */
3011 flags |= parent->mt_flags;
3012 if (flags & (MDB_RDONLY|MDB_WRITEMAP|MDB_TXN_BLOCKED)) {
3013 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
3015 /* Child txns save MDB_pgstate and use own copy of cursors */
3016 size = env->me_maxdbs * (sizeof(MDB_db)+sizeof(MDB_cursor *)+1);
3017 size += tsize = sizeof(MDB_ntxn);
3018 } else if (flags & MDB_RDONLY) {
3019 size = env->me_maxdbs * (sizeof(MDB_db)+1);
3020 size += tsize = sizeof(MDB_txn);
3022 /* Reuse preallocated write txn. However, do not touch it until
3023 * mdb_txn_renew0() succeeds, since it currently may be active.
3028 if ((txn = calloc(1, size)) == NULL) {
3029 DPRINTF(("calloc: %s", strerror(errno)));
3034 txn->mt_rpages = malloc(MDB_TRPAGE_SIZE * sizeof(MDB_ID3));
3035 if (!txn->mt_rpages) {
3039 txn->mt_rpages[0].mid = 0;
3040 txn->mt_rpcheck = MDB_TRPAGE_SIZE/2;
3043 txn->mt_dbxs = env->me_dbxs; /* static */
3044 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
3045 txn->mt_dbflags = (unsigned char *)txn + size - env->me_maxdbs;
3046 txn->mt_flags = flags;
3051 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
3052 txn->mt_dbiseqs = parent->mt_dbiseqs;
3053 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
3054 if (!txn->mt_u.dirty_list ||
3055 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
3057 free(txn->mt_u.dirty_list);
3061 txn->mt_txnid = parent->mt_txnid;
3062 txn->mt_dirty_room = parent->mt_dirty_room;
3063 txn->mt_u.dirty_list[0].mid = 0;
3064 txn->mt_spill_pgs = NULL;
3065 txn->mt_next_pgno = parent->mt_next_pgno;
3066 parent->mt_flags |= MDB_TXN_HAS_CHILD;
3067 parent->mt_child = txn;
3068 txn->mt_parent = parent;
3069 txn->mt_numdbs = parent->mt_numdbs;
3071 txn->mt_rpages = parent->mt_rpages;
3073 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3074 /* Copy parent's mt_dbflags, but clear DB_NEW */
3075 for (i=0; i<txn->mt_numdbs; i++)
3076 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
3078 ntxn = (MDB_ntxn *)txn;
3079 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
3080 if (env->me_pghead) {
3081 size = MDB_IDL_SIZEOF(env->me_pghead);
3082 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
3084 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
3089 rc = mdb_cursor_shadow(parent, txn);
3091 mdb_txn_end(txn, MDB_END_FAIL_BEGINCHILD);
3092 } else { /* MDB_RDONLY */
3093 txn->mt_dbiseqs = env->me_dbiseqs;
3095 rc = mdb_txn_renew0(txn);
3098 if (txn != env->me_txn0) {
3100 free(txn->mt_rpages);
3105 txn->mt_flags |= flags; /* could not change txn=me_txn0 earlier */
3107 DPRINTF(("begin txn %"Y"u%c %p on mdbenv %p, root page %"Y"u",
3108 txn->mt_txnid, (flags & MDB_RDONLY) ? 'r' : 'w',
3109 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
3116 mdb_txn_env(MDB_txn *txn)
3118 if(!txn) return NULL;
3123 mdb_txn_id(MDB_txn *txn)
3126 return txn->mt_txnid;
3129 /** Export or close DBI handles opened in this txn. */
3131 mdb_dbis_update(MDB_txn *txn, int keep)
3134 MDB_dbi n = txn->mt_numdbs;
3135 MDB_env *env = txn->mt_env;
3136 unsigned char *tdbflags = txn->mt_dbflags;
3138 for (i = n; --i >= CORE_DBS;) {
3139 if (tdbflags[i] & DB_NEW) {
3141 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
3143 char *ptr = env->me_dbxs[i].md_name.mv_data;
3145 env->me_dbxs[i].md_name.mv_data = NULL;
3146 env->me_dbxs[i].md_name.mv_size = 0;
3147 env->me_dbflags[i] = 0;
3148 env->me_dbiseqs[i]++;
3154 if (keep && env->me_numdbs < n)
3158 /** End a transaction, except successful commit of a nested transaction.
3159 * May be called twice for readonly txns: First reset it, then abort.
3160 * @param[in] txn the transaction handle to end
3161 * @param[in] mode why and how to end the transaction
3164 mdb_txn_end(MDB_txn *txn, unsigned mode)
3166 MDB_env *env = txn->mt_env;
3168 static const char *const names[] = MDB_END_NAMES;
3171 /* Export or close DBI handles opened in this txn */
3172 mdb_dbis_update(txn, mode & MDB_END_UPDATE);
3174 DPRINTF(("%s txn %"Y"u%c %p on mdbenv %p, root page %"Y"u",
3175 names[mode & MDB_END_OPMASK],
3176 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
3177 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
3179 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3180 if (txn->mt_u.reader) {
3181 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
3182 if (!(env->me_flags & MDB_NOTLS)) {
3183 txn->mt_u.reader = NULL; /* txn does not own reader */
3184 } else if (mode & MDB_END_SLOT) {
3185 txn->mt_u.reader->mr_pid = 0;
3186 txn->mt_u.reader = NULL;
3187 } /* else txn owns the slot until it does MDB_END_SLOT */
3189 txn->mt_numdbs = 0; /* prevent further DBI activity */
3190 txn->mt_flags |= MDB_TXN_FINISHED;
3192 } else if (!F_ISSET(txn->mt_flags, MDB_TXN_FINISHED)) {
3193 pgno_t *pghead = env->me_pghead;
3195 if (!(mode & MDB_END_UPDATE)) /* !(already closed cursors) */
3196 mdb_cursors_close(txn, 0);
3197 if (!(env->me_flags & MDB_WRITEMAP)) {
3198 mdb_dlist_free(txn);
3202 txn->mt_flags = MDB_TXN_FINISHED;
3204 if (!txn->mt_parent) {
3205 mdb_midl_shrink(&txn->mt_free_pgs);
3206 env->me_free_pgs = txn->mt_free_pgs;
3208 env->me_pghead = NULL;
3212 mode = 0; /* txn == env->me_txn0, do not free() it */
3214 /* The writer mutex was locked in mdb_txn_begin. */
3216 UNLOCK_MUTEX(env->me_wmutex);
3218 txn->mt_parent->mt_child = NULL;
3219 txn->mt_parent->mt_flags &= ~MDB_TXN_HAS_CHILD;
3220 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
3221 mdb_midl_free(txn->mt_free_pgs);
3222 mdb_midl_free(txn->mt_spill_pgs);
3223 free(txn->mt_u.dirty_list);
3226 mdb_midl_free(pghead);
3229 if (!txn->mt_parent) {
3230 MDB_ID3L el = env->me_rpages, tl = txn->mt_rpages;
3231 unsigned i, x, n = tl[0].mid;
3232 pthread_mutex_lock(&env->me_rpmutex);
3233 for (i = 1; i <= n; i++) {
3234 if (tl[i].mid & (MDB_RPAGE_CHUNK-1)) {
3235 /* tmp overflow pages that we didn't share in env */
3236 munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
3238 x = mdb_mid3l_search(el, tl[i].mid);
3239 if (tl[i].mptr == el[x].mptr) {
3242 /* another tmp overflow page */
3243 munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
3247 pthread_mutex_unlock(&env->me_rpmutex);
3249 if (mode & MDB_END_FREE)
3253 if (mode & MDB_END_FREE)
3258 mdb_txn_reset(MDB_txn *txn)
3263 /* This call is only valid for read-only txns */
3264 if (!(txn->mt_flags & MDB_TXN_RDONLY))
3267 mdb_txn_end(txn, MDB_END_RESET);
3271 mdb_txn_abort(MDB_txn *txn)
3277 mdb_txn_abort(txn->mt_child);
3279 mdb_txn_end(txn, MDB_END_ABORT|MDB_END_SLOT|MDB_END_FREE);
3282 /** Save the freelist as of this transaction to the freeDB.
3283 * This changes the freelist. Keep trying until it stabilizes.
3285 * When (MDB_DEVEL) & 2, the changes do not affect #mdb_page_alloc(),
3286 * it then uses the transaction's original snapshot of the freeDB.
3289 mdb_freelist_save(MDB_txn *txn)
3291 /* env->me_pghead[] can grow and shrink during this call.
3292 * env->me_pglast and txn->mt_free_pgs[] can only grow.
3293 * Page numbers cannot disappear from txn->mt_free_pgs[].
3296 MDB_env *env = txn->mt_env;
3297 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
3298 txnid_t pglast = 0, head_id = 0;
3299 pgno_t freecnt = 0, *free_pgs, *mop;
3300 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
3302 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
3304 if (env->me_pghead) {
3305 /* Make sure first page of freeDB is touched and on freelist */
3306 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
3307 if (rc && rc != MDB_NOTFOUND)
3311 if (!env->me_pghead && txn->mt_loose_pgs) {
3312 /* Put loose page numbers in mt_free_pgs, since
3313 * we may be unable to return them to me_pghead.
3315 MDB_page *mp = txn->mt_loose_pgs;
3316 if ((rc = mdb_midl_need(&txn->mt_free_pgs, txn->mt_loose_count)) != 0)
3318 for (; mp; mp = NEXT_LOOSE_PAGE(mp))
3319 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
3320 txn->mt_loose_pgs = NULL;
3321 txn->mt_loose_count = 0;
3324 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
3325 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
3326 ? SSIZE_MAX : maxfree_1pg;
3329 /* Come back here after each Put() in case freelist changed */
3334 /* If using records from freeDB which we have not yet
3335 * deleted, delete them and any we reserved for me_pghead.
3337 while (pglast < env->me_pglast) {
3338 rc = mdb_cursor_first(&mc, &key, NULL);
3341 pglast = head_id = *(txnid_t *)key.mv_data;
3342 total_room = head_room = 0;
3343 mdb_tassert(txn, pglast <= env->me_pglast);
3344 rc = mdb_cursor_del(&mc, 0);
3349 /* Save the IDL of pages freed by this txn, to a single record */
3350 if (freecnt < txn->mt_free_pgs[0]) {
3352 /* Make sure last page of freeDB is touched and on freelist */
3353 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
3354 if (rc && rc != MDB_NOTFOUND)
3357 free_pgs = txn->mt_free_pgs;
3358 /* Write to last page of freeDB */
3359 key.mv_size = sizeof(txn->mt_txnid);
3360 key.mv_data = &txn->mt_txnid;
3362 freecnt = free_pgs[0];
3363 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
3364 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3367 /* Retry if mt_free_pgs[] grew during the Put() */
3368 free_pgs = txn->mt_free_pgs;
3369 } while (freecnt < free_pgs[0]);
3370 mdb_midl_sort(free_pgs);
3371 memcpy(data.mv_data, free_pgs, data.mv_size);
3374 unsigned int i = free_pgs[0];
3375 DPRINTF(("IDL write txn %"Y"u root %"Y"u num %u",
3376 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
3378 DPRINTF(("IDL %"Y"u", free_pgs[i]));
3384 mop = env->me_pghead;
3385 mop_len = (mop ? mop[0] : 0) + txn->mt_loose_count;
3387 /* Reserve records for me_pghead[]. Split it if multi-page,
3388 * to avoid searching freeDB for a page range. Use keys in
3389 * range [1,me_pglast]: Smaller than txnid of oldest reader.
3391 if (total_room >= mop_len) {
3392 if (total_room == mop_len || --more < 0)
3394 } else if (head_room >= maxfree_1pg && head_id > 1) {
3395 /* Keep current record (overflow page), add a new one */
3399 /* (Re)write {key = head_id, IDL length = head_room} */
3400 total_room -= head_room;
3401 head_room = mop_len - total_room;
3402 if (head_room > maxfree_1pg && head_id > 1) {
3403 /* Overflow multi-page for part of me_pghead */
3404 head_room /= head_id; /* amortize page sizes */
3405 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
3406 } else if (head_room < 0) {
3407 /* Rare case, not bothering to delete this record */
3410 key.mv_size = sizeof(head_id);
3411 key.mv_data = &head_id;
3412 data.mv_size = (head_room + 1) * sizeof(pgno_t);
3413 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3416 /* IDL is initially empty, zero out at least the length */
3417 pgs = (pgno_t *)data.mv_data;
3418 j = head_room > clean_limit ? head_room : 0;
3422 total_room += head_room;
3425 /* Return loose page numbers to me_pghead, though usually none are
3426 * left at this point. The pages themselves remain in dirty_list.
3428 if (txn->mt_loose_pgs) {
3429 MDB_page *mp = txn->mt_loose_pgs;
3430 unsigned count = txn->mt_loose_count;
3432 /* Room for loose pages + temp IDL with same */
3433 if ((rc = mdb_midl_need(&env->me_pghead, 2*count+1)) != 0)
3435 mop = env->me_pghead;
3436 loose = mop + MDB_IDL_ALLOCLEN(mop) - count;
3437 for (count = 0; mp; mp = NEXT_LOOSE_PAGE(mp))
3438 loose[ ++count ] = mp->mp_pgno;
3440 mdb_midl_sort(loose);
3441 mdb_midl_xmerge(mop, loose);
3442 txn->mt_loose_pgs = NULL;
3443 txn->mt_loose_count = 0;
3447 /* Fill in the reserved me_pghead records */
3453 rc = mdb_cursor_first(&mc, &key, &data);
3454 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
3455 txnid_t id = *(txnid_t *)key.mv_data;
3456 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
3459 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
3461 if (len > mop_len) {
3463 data.mv_size = (len + 1) * sizeof(MDB_ID);
3465 data.mv_data = mop -= len;
3468 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
3470 if (rc || !(mop_len -= len))
3477 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
3478 * @param[in] txn the transaction that's being committed
3479 * @param[in] keep number of initial pages in dirty_list to keep dirty.
3480 * @return 0 on success, non-zero on failure.
3483 mdb_page_flush(MDB_txn *txn, int keep)
3485 MDB_env *env = txn->mt_env;
3486 MDB_ID2L dl = txn->mt_u.dirty_list;
3487 unsigned psize = env->me_psize, j;
3488 int i, pagecount = dl[0].mid, rc;
3492 MDB_page *dp = NULL;
3496 struct iovec iov[MDB_COMMIT_PAGES];
3497 ssize_t wsize = 0, wres;
3498 off_t wpos = 0, next_pos = 1; /* impossible pos, so pos != next_pos */
3504 if (env->me_flags & MDB_WRITEMAP) {
3505 /* Clear dirty flags */
3506 while (++i <= pagecount) {
3508 /* Don't flush this page yet */
3509 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3510 dp->mp_flags &= ~P_KEEP;
3514 dp->mp_flags &= ~P_DIRTY;
3519 /* Write the pages */
3521 if (++i <= pagecount) {
3523 /* Don't flush this page yet */
3524 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3525 dp->mp_flags &= ~P_KEEP;
3530 /* clear dirty flag */
3531 dp->mp_flags &= ~P_DIRTY;
3534 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
3539 /* Windows actually supports scatter/gather I/O, but only on
3540 * unbuffered file handles. Since we're relying on the OS page
3541 * cache for all our data, that's self-defeating. So we just
3542 * write pages one at a time. We use the ov structure to set
3543 * the write offset, to at least save the overhead of a Seek
3546 DPRINTF(("committing page %"Z"u", pgno));
3547 memset(&ov, 0, sizeof(ov));
3548 ov.Offset = pos & 0xffffffff;
3549 ov.OffsetHigh = pos >> 16 >> 16;
3550 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
3552 DPRINTF(("WriteFile: %d", rc));
3556 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
3557 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
3560 /* Write previous page(s) */
3561 #ifdef MDB_USE_PWRITEV
3562 wres = pwritev(env->me_fd, iov, n, wpos);
3565 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
3568 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
3572 DPRINTF(("lseek: %s", strerror(rc)));
3575 wres = writev(env->me_fd, iov, n);
3578 if (wres != wsize) {
3583 DPRINTF(("Write error: %s", strerror(rc)));
3585 rc = EIO; /* TODO: Use which error code? */
3586 DPUTS("short write, filesystem full?");
3597 DPRINTF(("committing page %"Y"u", pgno));
3598 next_pos = pos + size;
3599 iov[n].iov_len = size;
3600 iov[n].iov_base = (char *)dp;
3606 if (pgno > txn->mt_last_pgno)
3607 txn->mt_last_pgno = pgno;
3610 /* MIPS has cache coherency issues, this is a no-op everywhere else
3611 * Note: for any size >= on-chip cache size, entire on-chip cache is
3614 CACHEFLUSH(env->me_map, txn->mt_next_pgno * env->me_psize, DCACHE);
3616 for (i = keep; ++i <= pagecount; ) {
3618 /* This is a page we skipped above */
3621 dl[j].mid = dp->mp_pgno;
3624 mdb_dpage_free(env, dp);
3629 txn->mt_dirty_room += i - j;
3635 mdb_txn_commit(MDB_txn *txn)
3638 unsigned int i, end_mode;
3644 /* mdb_txn_end() mode for a commit which writes nothing */
3645 end_mode = MDB_END_EMPTY_COMMIT|MDB_END_UPDATE|MDB_END_SLOT|MDB_END_FREE;
3647 if (txn->mt_child) {
3648 rc = mdb_txn_commit(txn->mt_child);
3655 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3659 if (txn->mt_flags & (MDB_TXN_FINISHED|MDB_TXN_ERROR)) {
3660 DPUTS("txn has failed/finished, can't commit");
3662 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3667 if (txn->mt_parent) {
3668 MDB_txn *parent = txn->mt_parent;
3672 unsigned x, y, len, ps_len;
3674 /* Append our free list to parent's */
3675 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3678 mdb_midl_free(txn->mt_free_pgs);
3679 /* Failures after this must either undo the changes
3680 * to the parent or set MDB_TXN_ERROR in the parent.
3683 parent->mt_next_pgno = txn->mt_next_pgno;
3684 parent->mt_flags = txn->mt_flags;
3686 /* Merge our cursors into parent's and close them */
3687 mdb_cursors_close(txn, 1);
3689 /* Update parent's DB table. */
3690 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3691 parent->mt_numdbs = txn->mt_numdbs;
3692 parent->mt_dbflags[FREE_DBI] = txn->mt_dbflags[FREE_DBI];
3693 parent->mt_dbflags[MAIN_DBI] = txn->mt_dbflags[MAIN_DBI];
3694 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
3695 /* preserve parent's DB_NEW status */
3696 x = parent->mt_dbflags[i] & DB_NEW;
3697 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3700 dst = parent->mt_u.dirty_list;
3701 src = txn->mt_u.dirty_list;
3702 /* Remove anything in our dirty list from parent's spill list */
3703 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3705 pspill[0] = (pgno_t)-1;
3706 /* Mark our dirty pages as deleted in parent spill list */
3707 for (i=0, len=src[0].mid; ++i <= len; ) {
3708 MDB_ID pn = src[i].mid << 1;
3709 while (pn > pspill[x])
3711 if (pn == pspill[x]) {
3716 /* Squash deleted pagenums if we deleted any */
3717 for (x=y; ++x <= ps_len; )
3718 if (!(pspill[x] & 1))
3719 pspill[++y] = pspill[x];
3723 /* Remove anything in our spill list from parent's dirty list */
3724 if (txn->mt_spill_pgs && txn->mt_spill_pgs[0]) {
3725 for (i=1; i<=txn->mt_spill_pgs[0]; i++) {
3726 MDB_ID pn = txn->mt_spill_pgs[i];
3728 continue; /* deleted spillpg */
3730 y = mdb_mid2l_search(dst, pn);
3731 if (y <= dst[0].mid && dst[y].mid == pn) {
3733 while (y < dst[0].mid) {
3742 /* Find len = length of merging our dirty list with parent's */
3744 dst[0].mid = 0; /* simplify loops */
3745 if (parent->mt_parent) {
3746 len = x + src[0].mid;
3747 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3748 for (i = x; y && i; y--) {
3749 pgno_t yp = src[y].mid;
3750 while (yp < dst[i].mid)
3752 if (yp == dst[i].mid) {
3757 } else { /* Simplify the above for single-ancestor case */
3758 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3760 /* Merge our dirty list with parent's */
3762 for (i = len; y; dst[i--] = src[y--]) {
3763 pgno_t yp = src[y].mid;
3764 while (yp < dst[x].mid)
3765 dst[i--] = dst[x--];
3766 if (yp == dst[x].mid)
3767 free(dst[x--].mptr);
3769 mdb_tassert(txn, i == x);
3771 free(txn->mt_u.dirty_list);
3772 parent->mt_dirty_room = txn->mt_dirty_room;
3773 if (txn->mt_spill_pgs) {
3774 if (parent->mt_spill_pgs) {
3775 /* TODO: Prevent failure here, so parent does not fail */
3776 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3778 parent->mt_flags |= MDB_TXN_ERROR;
3779 mdb_midl_free(txn->mt_spill_pgs);
3780 mdb_midl_sort(parent->mt_spill_pgs);
3782 parent->mt_spill_pgs = txn->mt_spill_pgs;
3786 /* Append our loose page list to parent's */
3787 for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(*lp))
3789 *lp = txn->mt_loose_pgs;
3790 parent->mt_loose_count += txn->mt_loose_count;
3792 parent->mt_child = NULL;
3793 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3798 if (txn != env->me_txn) {
3799 DPUTS("attempt to commit unknown transaction");
3804 mdb_cursors_close(txn, 0);
3806 if (!txn->mt_u.dirty_list[0].mid &&
3807 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
3810 DPRINTF(("committing txn %"Y"u %p on mdbenv %p, root page %"Y"u",
3811 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3813 /* Update DB root pointers */
3814 if (txn->mt_numdbs > CORE_DBS) {
3818 data.mv_size = sizeof(MDB_db);
3820 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3821 for (i = CORE_DBS; i < txn->mt_numdbs; i++) {
3822 if (txn->mt_dbflags[i] & DB_DIRTY) {
3823 if (TXN_DBI_CHANGED(txn, i)) {
3827 data.mv_data = &txn->mt_dbs[i];
3828 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data,
3836 rc = mdb_freelist_save(txn);
3840 mdb_midl_free(env->me_pghead);
3841 env->me_pghead = NULL;
3842 mdb_midl_shrink(&txn->mt_free_pgs);
3848 if ((rc = mdb_page_flush(txn, 0)))
3850 if (!F_ISSET(txn->mt_flags, MDB_TXN_NOSYNC) &&
3851 (rc = mdb_env_sync0(env, 0, txn->mt_next_pgno)))
3853 if ((rc = mdb_env_write_meta(txn)))
3855 end_mode = MDB_END_COMMITTED|MDB_END_UPDATE;
3858 mdb_txn_end(txn, end_mode);
3866 /** Read the environment parameters of a DB environment before
3867 * mapping it into memory.
3868 * @param[in] env the environment handle
3869 * @param[out] meta address of where to store the meta information
3870 * @return 0 on success, non-zero on failure.
3873 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3879 enum { Size = sizeof(pbuf) };
3881 /* We don't know the page size yet, so use a minimum value.
3882 * Read both meta pages so we can use the latest one.
3885 for (i=off=0; i<NUM_METAS; i++, off += meta->mm_psize) {
3889 memset(&ov, 0, sizeof(ov));
3891 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3892 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3895 rc = pread(env->me_fd, &pbuf, Size, off);
3898 if (rc == 0 && off == 0)
3900 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3901 DPRINTF(("read: %s", mdb_strerror(rc)));
3905 p = (MDB_page *)&pbuf;
3907 if (!F_ISSET(p->mp_flags, P_META)) {
3908 DPRINTF(("page %"Y"u not a meta page", p->mp_pgno));
3913 if (m->mm_magic != MDB_MAGIC) {
3914 DPUTS("meta has invalid magic");
3918 if (m->mm_version != MDB_DATA_VERSION) {
3919 DPRINTF(("database is version %u, expected version %u",
3920 m->mm_version, MDB_DATA_VERSION));
3921 return MDB_VERSION_MISMATCH;
3924 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3930 /** Fill in most of the zeroed #MDB_meta for an empty database environment */
3932 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
3934 meta->mm_magic = MDB_MAGIC;
3935 meta->mm_version = MDB_DATA_VERSION;
3936 meta->mm_mapsize = env->me_mapsize;
3937 meta->mm_psize = env->me_psize;
3938 meta->mm_last_pg = NUM_METAS-1;
3939 meta->mm_flags = env->me_flags & 0xffff;
3940 meta->mm_flags |= MDB_INTEGERKEY; /* this is mm_dbs[FREE_DBI].md_flags */
3941 meta->mm_dbs[FREE_DBI].md_root = P_INVALID;
3942 meta->mm_dbs[MAIN_DBI].md_root = P_INVALID;
3945 /** Write the environment parameters of a freshly created DB environment.
3946 * @param[in] env the environment handle
3947 * @param[in] meta the #MDB_meta to write
3948 * @return 0 on success, non-zero on failure.
3951 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3959 memset(&ov, 0, sizeof(ov));
3960 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3962 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3965 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3966 len = pwrite(fd, ptr, size, pos); \
3967 if (len == -1 && ErrCode() == EINTR) continue; \
3968 rc = (len >= 0); break; } while(1)
3971 DPUTS("writing new meta page");
3973 psize = env->me_psize;
3975 p = calloc(NUM_METAS, psize);
3979 p->mp_flags = P_META;
3980 *(MDB_meta *)METADATA(p) = *meta;
3982 q = (MDB_page *)((char *)p + psize);
3984 q->mp_flags = P_META;
3985 *(MDB_meta *)METADATA(q) = *meta;
3987 DO_PWRITE(rc, env->me_fd, p, psize * NUM_METAS, len, 0);
3990 else if ((unsigned) len == psize * NUM_METAS)
3998 /** Update the environment info to commit a transaction.
3999 * @param[in] txn the transaction that's being committed
4000 * @return 0 on success, non-zero on failure.
4003 mdb_env_write_meta(MDB_txn *txn)
4006 MDB_meta meta, metab, *mp;
4010 int rc, len, toggle;
4019 toggle = txn->mt_txnid & 1;
4020 DPRINTF(("writing meta page %d for root page %"Y"u",
4021 toggle, txn->mt_dbs[MAIN_DBI].md_root));
4024 flags = txn->mt_flags | env->me_flags;
4025 mp = env->me_metas[toggle];
4026 mapsize = env->me_metas[toggle ^ 1]->mm_mapsize;
4027 /* Persist any increases of mapsize config */
4028 if (mapsize < env->me_mapsize)
4029 mapsize = env->me_mapsize;
4031 if (flags & MDB_WRITEMAP) {
4032 mp->mm_mapsize = mapsize;
4033 mp->mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
4034 mp->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
4035 mp->mm_last_pg = txn->mt_next_pgno - 1;
4036 #if (__GNUC__ * 100 + __GNUC_MINOR__ >= 404) && /* TODO: portability */ \
4037 !(defined(__i386__) || defined(__x86_64__))
4038 /* LY: issue a memory barrier, if not x86. ITS#7969 */
4039 __sync_synchronize();
4041 mp->mm_txnid = txn->mt_txnid;
4042 if (!(flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
4043 unsigned meta_size = env->me_psize;
4044 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
4045 ptr = (char *)mp - PAGEHDRSZ;
4046 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
4047 r2 = (ptr - env->me_map) & (env->me_os_psize - 1);
4051 if (MDB_MSYNC(ptr, meta_size, rc)) {
4058 metab.mm_txnid = mp->mm_txnid;
4059 metab.mm_last_pg = mp->mm_last_pg;
4061 meta.mm_mapsize = mapsize;
4062 meta.mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
4063 meta.mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
4064 meta.mm_last_pg = txn->mt_next_pgno - 1;
4065 meta.mm_txnid = txn->mt_txnid;
4067 off = offsetof(MDB_meta, mm_mapsize);
4068 ptr = (char *)&meta + off;
4069 len = sizeof(MDB_meta) - off;
4070 off += (char *)mp - env->me_map;
4072 /* Write to the SYNC fd */
4073 mfd = (flags & (MDB_NOSYNC|MDB_NOMETASYNC)) ? env->me_fd : env->me_mfd;
4076 memset(&ov, 0, sizeof(ov));
4078 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
4083 rc = pwrite(mfd, ptr, len, off);
4086 rc = rc < 0 ? ErrCode() : EIO;
4091 DPUTS("write failed, disk error?");
4092 /* On a failure, the pagecache still contains the new data.
4093 * Write some old data back, to prevent it from being used.
4094 * Use the non-SYNC fd; we know it will fail anyway.
4096 meta.mm_last_pg = metab.mm_last_pg;
4097 meta.mm_txnid = metab.mm_txnid;
4099 memset(&ov, 0, sizeof(ov));
4101 WriteFile(env->me_fd, ptr, len, NULL, &ov);
4103 r2 = pwrite(env->me_fd, ptr, len, off);
4104 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
4107 env->me_flags |= MDB_FATAL_ERROR;
4110 /* MIPS has cache coherency issues, this is a no-op everywhere else */
4111 CACHEFLUSH(env->me_map + off, len, DCACHE);
4113 /* Memory ordering issues are irrelevant; since the entire writer
4114 * is wrapped by wmutex, all of these changes will become visible
4115 * after the wmutex is unlocked. Since the DB is multi-version,
4116 * readers will get consistent data regardless of how fresh or
4117 * how stale their view of these values is.
4120 env->me_txns->mti_txnid = txn->mt_txnid;
4125 /** Check both meta pages to see which one is newer.
4126 * @param[in] env the environment handle
4127 * @return newest #MDB_meta.
4130 mdb_env_pick_meta(const MDB_env *env)
4132 MDB_meta *const *metas = env->me_metas;
4133 return metas[ metas[0]->mm_txnid < metas[1]->mm_txnid ];
4137 mdb_env_create(MDB_env **env)
4141 e = calloc(1, sizeof(MDB_env));
4145 e->me_maxreaders = DEFAULT_READERS;
4146 e->me_maxdbs = e->me_numdbs = CORE_DBS;
4147 e->me_fd = INVALID_HANDLE_VALUE;
4148 e->me_lfd = INVALID_HANDLE_VALUE;
4149 e->me_mfd = INVALID_HANDLE_VALUE;
4150 #ifdef MDB_USE_POSIX_SEM
4151 e->me_rmutex = SEM_FAILED;
4152 e->me_wmutex = SEM_FAILED;
4153 #elif defined MDB_USE_SYSV_SEM
4154 e->me_rmutex->semid = -1;
4155 e->me_wmutex->semid = -1;
4157 e->me_pid = getpid();
4158 GET_PAGESIZE(e->me_os_psize);
4159 VGMEMP_CREATE(e,0,0);
4165 /** @brief Map a result from an NTAPI call to WIN32. */
4167 mdb_nt2win32(NTSTATUS st)
4172 GetOverlappedResult(NULL, &o, &br, FALSE);
4173 return GetLastError();
4178 mdb_env_map(MDB_env *env, void *addr)
4181 unsigned int flags = env->me_flags;
4184 int access = SECTION_MAP_READ;
4188 ULONG pageprot = PAGE_READONLY, secprot, alloctype;
4190 if (flags & MDB_WRITEMAP) {
4191 access |= SECTION_MAP_WRITE;
4192 pageprot = PAGE_READWRITE;
4194 if (flags & MDB_RDONLY) {
4195 secprot = PAGE_READONLY;
4199 secprot = PAGE_READWRITE;
4200 msize = env->me_mapsize;
4201 alloctype = MEM_RESERVE;
4204 rc = NtCreateSection(&mh, access, NULL, NULL, secprot, SEC_RESERVE, env->me_fd);
4206 return mdb_nt2win32(rc);
4209 msize = NUM_METAS * env->me_psize;
4211 rc = NtMapViewOfSection(mh, GetCurrentProcess(), &map, 0, 0, NULL, &msize, ViewUnmap, alloctype, pageprot);
4218 return mdb_nt2win32(rc);
4223 env->me_map = mmap(addr, NUM_METAS * env->me_psize, PROT_READ, MAP_SHARED,
4225 if (env->me_map == MAP_FAILED) {
4230 int prot = PROT_READ;
4231 if (flags & MDB_WRITEMAP) {
4233 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
4236 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
4238 if (env->me_map == MAP_FAILED) {
4243 if (flags & MDB_NORDAHEAD) {
4244 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
4246 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
4248 #ifdef POSIX_MADV_RANDOM
4249 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
4250 #endif /* POSIX_MADV_RANDOM */
4251 #endif /* MADV_RANDOM */
4255 /* Can happen because the address argument to mmap() is just a
4256 * hint. mmap() can pick another, e.g. if the range is in use.
4257 * The MAP_FIXED flag would prevent that, but then mmap could
4258 * instead unmap existing pages to make room for the new map.
4260 if (addr && env->me_map != addr)
4261 return EBUSY; /* TODO: Make a new MDB_* error code? */
4264 p = (MDB_page *)env->me_map;
4265 env->me_metas[0] = METADATA(p);
4266 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
4272 mdb_env_set_mapsize(MDB_env *env, mdb_size_t size)
4274 /* If env is already open, caller is responsible for making
4275 * sure there are no active txns.
4285 meta = mdb_env_pick_meta(env);
4287 size = meta->mm_mapsize;
4289 /* Silently round up to minimum if the size is too small */
4290 mdb_size_t minsize = (meta->mm_last_pg + 1) * env->me_psize;
4295 /* For MDB_VL32 this bit is a noop since we dynamically remap
4296 * chunks of the DB anyway.
4298 munmap(env->me_map, env->me_mapsize);
4299 env->me_mapsize = size;
4300 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
4301 rc = mdb_env_map(env, old);
4304 #endif /* !MDB_VL32 */
4306 env->me_mapsize = size;
4308 env->me_maxpg = env->me_mapsize / env->me_psize;
4313 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
4317 env->me_maxdbs = dbs + CORE_DBS;
4322 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
4324 if (env->me_map || readers < 1)
4326 env->me_maxreaders = readers;
4331 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
4333 if (!env || !readers)
4335 *readers = env->me_maxreaders;
4340 mdb_fsize(HANDLE fd, mdb_size_t *size)
4343 LARGE_INTEGER fsize;
4345 if (!GetFileSizeEx(fd, &fsize))
4348 *size = fsize.QuadPart;
4360 #ifdef BROKEN_FDATASYNC
4361 #include <sys/utsname.h>
4362 #include <sys/vfs.h>
4365 /** Further setup required for opening an LMDB environment
4368 mdb_env_open2(MDB_env *env)
4370 unsigned int flags = env->me_flags;
4371 int i, newenv = 0, rc;
4375 /* See if we should use QueryLimited */
4377 if ((rc & 0xff) > 5)
4378 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
4380 env->me_pidquery = PROCESS_QUERY_INFORMATION;
4383 #ifdef BROKEN_FDATASYNC
4384 /* ext3/ext4 fdatasync is broken on some older Linux kernels.
4385 * https://lkml.org/lkml/2012/9/3/83
4386 * Kernels after 3.6-rc6 are known good.
4387 * https://lkml.org/lkml/2012/9/10/556
4388 * See if the DB is on ext3/ext4, then check for new enough kernel
4389 * Kernels 2.6.32.60, 2.6.34.15, 3.2.30, and 3.5.4 are also known
4394 fstatfs(env->me_fd, &st);
4395 while (st.f_type == 0xEF53) {
4399 if (uts.release[0] < '3') {
4400 if (!strncmp(uts.release, "2.6.32.", 7)) {
4401 i = atoi(uts.release+7);
4403 break; /* 2.6.32.60 and newer is OK */
4404 } else if (!strncmp(uts.release, "2.6.34.", 7)) {
4405 i = atoi(uts.release+7);
4407 break; /* 2.6.34.15 and newer is OK */
4409 } else if (uts.release[0] == '3') {
4410 i = atoi(uts.release+2);
4412 break; /* 3.6 and newer is OK */
4414 i = atoi(uts.release+4);
4416 break; /* 3.5.4 and newer is OK */
4417 } else if (i == 2) {
4418 i = atoi(uts.release+4);
4420 break; /* 3.2.30 and newer is OK */
4422 } else { /* 4.x and newer is OK */
4425 env->me_flags |= MDB_FSYNCONLY;
4431 if ((i = mdb_env_read_header(env, &meta)) != 0) {
4434 DPUTS("new mdbenv");
4436 env->me_psize = env->me_os_psize;
4437 if (env->me_psize > MAX_PAGESIZE)
4438 env->me_psize = MAX_PAGESIZE;
4439 memset(&meta, 0, sizeof(meta));
4440 mdb_env_init_meta0(env, &meta);
4441 meta.mm_mapsize = DEFAULT_MAPSIZE;
4443 env->me_psize = meta.mm_psize;
4446 /* Was a mapsize configured? */
4447 if (!env->me_mapsize) {
4448 env->me_mapsize = meta.mm_mapsize;
4451 /* Make sure mapsize >= committed data size. Even when using
4452 * mm_mapsize, which could be broken in old files (ITS#7789).
4454 mdb_size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
4455 if (env->me_mapsize < minsize)
4456 env->me_mapsize = minsize;
4458 meta.mm_mapsize = env->me_mapsize;
4460 if (newenv && !(flags & MDB_FIXEDMAP)) {
4461 /* mdb_env_map() may grow the datafile. Write the metapages
4462 * first, so the file will be valid if initialization fails.
4463 * Except with FIXEDMAP, since we do not yet know mm_address.
4464 * We could fill in mm_address later, but then a different
4465 * program might end up doing that - one with a memory layout
4466 * and map address which does not suit the main program.
4468 rc = mdb_env_init_meta(env, &meta);
4474 /* For FIXEDMAP, make sure the file is non-empty before we attempt to map it */
4478 rc = WriteFile(env->me_fd, &dummy, 1, &len, NULL);
4486 rc = mdb_env_map(env, (flags & MDB_FIXEDMAP) ? meta.mm_address : NULL);
4491 if (flags & MDB_FIXEDMAP)
4492 meta.mm_address = env->me_map;
4493 i = mdb_env_init_meta(env, &meta);
4494 if (i != MDB_SUCCESS) {
4499 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
4500 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
4502 #if !(MDB_MAXKEYSIZE)
4503 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
4505 env->me_maxpg = env->me_mapsize / env->me_psize;
4509 MDB_meta *meta = mdb_env_pick_meta(env);
4510 MDB_db *db = &meta->mm_dbs[MAIN_DBI];
4512 DPRINTF(("opened database version %u, pagesize %u",
4513 meta->mm_version, env->me_psize));
4514 DPRINTF(("using meta page %d", (int) (meta->mm_txnid & 1)));
4515 DPRINTF(("depth: %u", db->md_depth));
4516 DPRINTF(("entries: %"Y"u", db->md_entries));
4517 DPRINTF(("branch pages: %"Y"u", db->md_branch_pages));
4518 DPRINTF(("leaf pages: %"Y"u", db->md_leaf_pages));
4519 DPRINTF(("overflow pages: %"Y"u", db->md_overflow_pages));
4520 DPRINTF(("root: %"Y"u", db->md_root));
4528 /** Release a reader thread's slot in the reader lock table.
4529 * This function is called automatically when a thread exits.
4530 * @param[in] ptr This points to the slot in the reader lock table.
4533 mdb_env_reader_dest(void *ptr)
4535 MDB_reader *reader = ptr;
4541 /** Junk for arranging thread-specific callbacks on Windows. This is
4542 * necessarily platform and compiler-specific. Windows supports up
4543 * to 1088 keys. Let's assume nobody opens more than 64 environments
4544 * in a single process, for now. They can override this if needed.
4546 #ifndef MAX_TLS_KEYS
4547 #define MAX_TLS_KEYS 64
4549 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
4550 static int mdb_tls_nkeys;
4552 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
4556 case DLL_PROCESS_ATTACH: break;
4557 case DLL_THREAD_ATTACH: break;
4558 case DLL_THREAD_DETACH:
4559 for (i=0; i<mdb_tls_nkeys; i++) {
4560 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
4562 mdb_env_reader_dest(r);
4566 case DLL_PROCESS_DETACH: break;
4571 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4573 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4577 /* Force some symbol references.
4578 * _tls_used forces the linker to create the TLS directory if not already done
4579 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
4581 #pragma comment(linker, "/INCLUDE:_tls_used")
4582 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
4583 #pragma const_seg(".CRT$XLB")
4584 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
4585 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4588 #pragma comment(linker, "/INCLUDE:__tls_used")
4589 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
4590 #pragma data_seg(".CRT$XLB")
4591 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4593 #endif /* WIN 32/64 */
4594 #endif /* !__GNUC__ */
4597 /** Downgrade the exclusive lock on the region back to shared */
4599 mdb_env_share_locks(MDB_env *env, int *excl)
4602 MDB_meta *meta = mdb_env_pick_meta(env);
4604 env->me_txns->mti_txnid = meta->mm_txnid;
4609 /* First acquire a shared lock. The Unlock will
4610 * then release the existing exclusive lock.
4612 memset(&ov, 0, sizeof(ov));
4613 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4616 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4622 struct flock lock_info;
4623 /* The shared lock replaces the existing lock */
4624 memset((void *)&lock_info, 0, sizeof(lock_info));
4625 lock_info.l_type = F_RDLCK;
4626 lock_info.l_whence = SEEK_SET;
4627 lock_info.l_start = 0;
4628 lock_info.l_len = 1;
4629 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4630 (rc = ErrCode()) == EINTR) ;
4631 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
4638 /** Try to get exclusive lock, otherwise shared.
4639 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
4642 mdb_env_excl_lock(MDB_env *env, int *excl)
4646 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
4650 memset(&ov, 0, sizeof(ov));
4651 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4658 struct flock lock_info;
4659 memset((void *)&lock_info, 0, sizeof(lock_info));
4660 lock_info.l_type = F_WRLCK;
4661 lock_info.l_whence = SEEK_SET;
4662 lock_info.l_start = 0;
4663 lock_info.l_len = 1;
4664 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4665 (rc = ErrCode()) == EINTR) ;
4669 # ifndef MDB_USE_POSIX_MUTEX
4670 if (*excl < 0) /* always true when MDB_USE_POSIX_MUTEX */
4673 lock_info.l_type = F_RDLCK;
4674 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
4675 (rc = ErrCode()) == EINTR) ;
4685 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
4687 * @(#) $Revision: 5.1 $
4688 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
4689 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
4691 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
4695 * Please do not copyright this code. This code is in the public domain.
4697 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
4698 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
4699 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
4700 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
4701 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4702 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4703 * PERFORMANCE OF THIS SOFTWARE.
4706 * chongo <Landon Curt Noll> /\oo/\
4707 * http://www.isthe.com/chongo/
4709 * Share and Enjoy! :-)
4712 typedef unsigned long long mdb_hash_t;
4713 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
4715 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
4716 * @param[in] val value to hash
4717 * @param[in] hval initial value for hash
4718 * @return 64 bit hash
4720 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
4721 * hval arg on the first call.
4724 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
4726 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
4727 unsigned char *end = s + val->mv_size;
4729 * FNV-1a hash each octet of the string
4732 /* xor the bottom with the current octet */
4733 hval ^= (mdb_hash_t)*s++;
4735 /* multiply by the 64 bit FNV magic prime mod 2^64 */
4736 hval += (hval << 1) + (hval << 4) + (hval << 5) +
4737 (hval << 7) + (hval << 8) + (hval << 40);
4739 /* return our new hash value */
4743 /** Hash the string and output the encoded hash.
4744 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
4745 * very short name limits. We don't care about the encoding being reversible,
4746 * we just want to preserve as many bits of the input as possible in a
4747 * small printable string.
4748 * @param[in] str string to hash
4749 * @param[out] encbuf an array of 11 chars to hold the hash
4751 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
4754 mdb_pack85(unsigned long l, char *out)
4758 for (i=0; i<5; i++) {
4759 *out++ = mdb_a85[l % 85];
4765 mdb_hash_enc(MDB_val *val, char *encbuf)
4767 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
4769 mdb_pack85(h, encbuf);
4770 mdb_pack85(h>>32, encbuf+5);
4775 /** Open and/or initialize the lock region for the environment.
4776 * @param[in] env The LMDB environment.
4777 * @param[in] lpath The pathname of the file used for the lock region.
4778 * @param[in] mode The Unix permissions for the file, if we create it.
4779 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
4780 * @return 0 on success, non-zero on failure.
4783 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
4786 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
4788 # define MDB_ERRCODE_ROFS EROFS
4789 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
4790 # define MDB_CLOEXEC O_CLOEXEC
4793 # define MDB_CLOEXEC 0
4796 #ifdef MDB_USE_SYSV_SEM
4805 rc = utf8_to_utf16(lpath, -1, &wlpath, NULL);
4808 env->me_lfd = CreateFileW(wlpath, GENERIC_READ|GENERIC_WRITE,
4809 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
4810 FILE_ATTRIBUTE_NORMAL, NULL);
4813 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
4815 if (env->me_lfd == INVALID_HANDLE_VALUE) {
4817 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
4822 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
4823 /* Lose record locks when exec*() */
4824 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
4825 fcntl(env->me_lfd, F_SETFD, fdflags);
4828 if (!(env->me_flags & MDB_NOTLS)) {
4829 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
4832 env->me_flags |= MDB_ENV_TXKEY;
4834 /* Windows TLS callbacks need help finding their TLS info. */
4835 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
4839 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
4843 /* Try to get exclusive lock. If we succeed, then
4844 * nobody is using the lock region and we should initialize it.
4846 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
4849 size = GetFileSize(env->me_lfd, NULL);
4851 size = lseek(env->me_lfd, 0, SEEK_END);
4852 if (size == -1) goto fail_errno;
4854 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
4855 if (size < rsize && *excl > 0) {
4857 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
4858 || !SetEndOfFile(env->me_lfd))
4861 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
4865 size = rsize - sizeof(MDB_txninfo);
4866 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
4871 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
4873 if (!mh) goto fail_errno;
4874 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
4876 if (!env->me_txns) goto fail_errno;
4878 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
4880 if (m == MAP_FAILED) goto fail_errno;
4886 BY_HANDLE_FILE_INFORMATION stbuf;
4895 if (!mdb_sec_inited) {
4896 InitializeSecurityDescriptor(&mdb_null_sd,
4897 SECURITY_DESCRIPTOR_REVISION);
4898 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
4899 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
4900 mdb_all_sa.bInheritHandle = FALSE;
4901 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
4904 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
4905 idbuf.volume = stbuf.dwVolumeSerialNumber;
4906 idbuf.nhigh = stbuf.nFileIndexHigh;
4907 idbuf.nlow = stbuf.nFileIndexLow;
4908 val.mv_data = &idbuf;
4909 val.mv_size = sizeof(idbuf);
4910 mdb_hash_enc(&val, encbuf);
4911 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
4912 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
4913 env->me_rmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
4914 if (!env->me_rmutex) goto fail_errno;
4915 env->me_wmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
4916 if (!env->me_wmutex) goto fail_errno;
4917 #elif defined(MDB_USE_POSIX_SEM)
4926 #if defined(__NetBSD__)
4927 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
4929 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
4930 idbuf.dev = stbuf.st_dev;
4931 idbuf.ino = stbuf.st_ino;
4932 val.mv_data = &idbuf;
4933 val.mv_size = sizeof(idbuf);
4934 mdb_hash_enc(&val, encbuf);
4935 #ifdef MDB_SHORT_SEMNAMES
4936 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
4938 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
4939 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
4940 /* Clean up after a previous run, if needed: Try to
4941 * remove both semaphores before doing anything else.
4943 sem_unlink(env->me_txns->mti_rmname);
4944 sem_unlink(env->me_txns->mti_wmname);
4945 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
4946 O_CREAT|O_EXCL, mode, 1);
4947 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4948 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
4949 O_CREAT|O_EXCL, mode, 1);
4950 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4951 #elif defined(MDB_USE_SYSV_SEM)
4952 unsigned short vals[2] = {1, 1};
4953 key_t key = ftok(lpath, 'M');
4956 semid = semget(key, 2, (mode & 0777) | IPC_CREAT);
4960 if (semctl(semid, 0, SETALL, semu) < 0)
4962 env->me_txns->mti_semid = semid;
4963 env->me_txns->mti_rlocked = 0;
4964 env->me_txns->mti_wlocked = 0;
4965 #else /* MDB_USE_POSIX_MUTEX: */
4966 pthread_mutexattr_t mattr;
4968 /* Solaris needs this before initing a robust mutex. Otherwise
4969 * it may skip the init and return EBUSY "seems someone already
4970 * inited" or EINVAL "it was inited differently".
4972 memset(env->me_txns->mti_rmutex, 0, sizeof(*env->me_txns->mti_rmutex));
4973 memset(env->me_txns->mti_wmutex, 0, sizeof(*env->me_txns->mti_wmutex));
4975 if ((rc = pthread_mutexattr_init(&mattr)) != 0)
4977 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
4978 #ifdef MDB_ROBUST_SUPPORTED
4979 if (!rc) rc = pthread_mutexattr_setrobust(&mattr, PTHREAD_MUTEX_ROBUST);
4981 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_rmutex, &mattr);
4982 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_wmutex, &mattr);
4983 pthread_mutexattr_destroy(&mattr);
4986 #endif /* _WIN32 || ... */
4988 env->me_txns->mti_magic = MDB_MAGIC;
4989 env->me_txns->mti_format = MDB_LOCK_FORMAT;
4990 env->me_txns->mti_txnid = 0;
4991 env->me_txns->mti_numreaders = 0;
4994 #ifdef MDB_USE_SYSV_SEM
4995 struct semid_ds buf;
4997 if (env->me_txns->mti_magic != MDB_MAGIC) {
4998 DPUTS("lock region has invalid magic");
5002 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
5003 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
5004 env->me_txns->mti_format, MDB_LOCK_FORMAT));
5005 rc = MDB_VERSION_MISMATCH;
5009 if (rc && rc != EACCES && rc != EAGAIN) {
5013 env->me_rmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
5014 if (!env->me_rmutex) goto fail_errno;
5015 env->me_wmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
5016 if (!env->me_wmutex) goto fail_errno;
5017 #elif defined(MDB_USE_POSIX_SEM)
5018 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
5019 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
5020 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
5021 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
5022 #elif defined(MDB_USE_SYSV_SEM)
5023 semid = env->me_txns->mti_semid;
5025 /* check for read access */
5026 if (semctl(semid, 0, IPC_STAT, semu) < 0)
5028 /* check for write access */
5029 if (semctl(semid, 0, IPC_SET, semu) < 0)
5033 #ifdef MDB_USE_SYSV_SEM
5034 env->me_rmutex->semid = semid;
5035 env->me_wmutex->semid = semid;
5036 env->me_rmutex->semnum = 0;
5037 env->me_wmutex->semnum = 1;
5038 env->me_rmutex->locked = &env->me_txns->mti_rlocked;
5039 env->me_wmutex->locked = &env->me_txns->mti_wlocked;
5043 env->me_rpmutex = CreateMutex(NULL, FALSE, NULL);
5045 pthread_mutex_init(&env->me_rpmutex, NULL);
5057 /** The name of the lock file in the DB environment */
5058 #define LOCKNAME "/lock.mdb"
5059 /** The name of the data file in the DB environment */
5060 #define DATANAME "/data.mdb"
5061 /** The suffix of the lock file when no subdir is used */
5062 #define LOCKSUFF "-lock"
5063 /** Only a subset of the @ref mdb_env flags can be changed
5064 * at runtime. Changing other flags requires closing the
5065 * environment and re-opening it with the new flags.
5067 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
5068 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY| \
5069 MDB_WRITEMAP|MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
5071 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
5072 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
5076 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
5078 int oflags, rc, len, excl = -1;
5079 char *lpath, *dpath;
5084 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
5088 if (flags & MDB_WRITEMAP) {
5089 /* silently ignore WRITEMAP in 32 bit mode */
5090 flags ^= MDB_WRITEMAP;
5092 if (flags & MDB_FIXEDMAP) {
5093 /* cannot support FIXEDMAP */
5099 if (flags & MDB_NOSUBDIR) {
5100 rc = len + sizeof(LOCKSUFF) + len + 1;
5102 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
5107 if (flags & MDB_NOSUBDIR) {
5108 dpath = lpath + len + sizeof(LOCKSUFF);
5109 sprintf(lpath, "%s" LOCKSUFF, path);
5110 strcpy(dpath, path);
5112 dpath = lpath + len + sizeof(LOCKNAME);
5113 sprintf(lpath, "%s" LOCKNAME, path);
5114 sprintf(dpath, "%s" DATANAME, path);
5118 flags |= env->me_flags;
5119 if (flags & MDB_RDONLY) {
5120 /* silently ignore WRITEMAP when we're only getting read access */
5121 flags &= ~MDB_WRITEMAP;
5123 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
5124 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
5129 env->me_rpages = malloc(MDB_ERPAGE_SIZE * sizeof(MDB_ID3));
5130 if (!env->me_rpages) {
5134 env->me_rpages[0].mid = 0;
5135 env->me_rpcheck = MDB_ERPAGE_SIZE/2;
5138 env->me_flags = flags |= MDB_ENV_ACTIVE;
5142 env->me_path = strdup(path);
5143 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
5144 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
5145 env->me_dbiseqs = calloc(env->me_maxdbs, sizeof(unsigned int));
5146 if (!(env->me_dbxs && env->me_path && env->me_dbflags && env->me_dbiseqs)) {
5150 env->me_dbxs[FREE_DBI].md_cmp = mdb_cmp_long; /* aligned MDB_INTEGERKEY */
5152 /* For RDONLY, get lockfile after we know datafile exists */
5153 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
5154 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
5160 if (F_ISSET(flags, MDB_RDONLY)) {
5161 oflags = GENERIC_READ;
5162 len = OPEN_EXISTING;
5164 oflags = GENERIC_READ|GENERIC_WRITE;
5167 mode = FILE_ATTRIBUTE_NORMAL;
5168 rc = utf8_to_utf16(dpath, -1, &wpath, NULL);
5171 env->me_fd = CreateFileW(wpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
5172 NULL, len, mode, NULL);
5175 if (F_ISSET(flags, MDB_RDONLY))
5178 oflags = O_RDWR | O_CREAT;
5180 env->me_fd = open(dpath, oflags, mode);
5182 if (env->me_fd == INVALID_HANDLE_VALUE) {
5187 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
5188 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
5193 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
5194 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
5195 env->me_mfd = env->me_fd;
5197 /* Synchronous fd for meta writes. Needed even with
5198 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
5201 len = OPEN_EXISTING;
5202 rc = utf8_to_utf16(dpath, -1, &wpath, NULL);
5205 env->me_mfd = CreateFileW(wpath, oflags,
5206 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
5207 mode | FILE_FLAG_WRITE_THROUGH, NULL);
5211 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
5213 if (env->me_mfd == INVALID_HANDLE_VALUE) {
5218 DPRINTF(("opened dbenv %p", (void *) env));
5220 rc = mdb_env_share_locks(env, &excl);
5224 if (!(flags & MDB_RDONLY)) {
5226 int tsize = sizeof(MDB_txn), size = tsize + env->me_maxdbs *
5227 (sizeof(MDB_db)+sizeof(MDB_cursor *)+sizeof(unsigned int)+1);
5228 if ((env->me_pbuf = calloc(1, env->me_psize)) &&
5229 (txn = calloc(1, size)))
5231 txn->mt_dbs = (MDB_db *)((char *)txn + tsize);
5232 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
5233 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
5234 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
5237 txn->mt_rpages = malloc(MDB_TRPAGE_SIZE * sizeof(MDB_ID3));
5238 if (!txn->mt_rpages) {
5243 txn->mt_rpages[0].mid = 0;
5244 txn->mt_rpcheck = MDB_TRPAGE_SIZE/2;
5246 txn->mt_dbxs = env->me_dbxs;
5247 txn->mt_flags = MDB_TXN_FINISHED;
5257 mdb_env_close0(env, excl);
5263 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
5265 mdb_env_close0(MDB_env *env, int excl)
5269 if (!(env->me_flags & MDB_ENV_ACTIVE))
5272 /* Doing this here since me_dbxs may not exist during mdb_env_close */
5274 for (i = env->me_maxdbs; --i >= CORE_DBS; )
5275 free(env->me_dbxs[i].md_name.mv_data);
5280 free(env->me_dbiseqs);
5281 free(env->me_dbflags);
5283 free(env->me_dirty_list);
5285 if (env->me_txn0 && env->me_txn0->mt_rpages)
5286 free(env->me_txn0->mt_rpages);
5288 for (x=1; x<=env->me_rpages[0].mid; x++)
5289 munmap(env->me_rpages[x].mptr, env->me_rpages[x].mcnt * env->me_psize);
5291 free(env->me_rpages);
5294 mdb_midl_free(env->me_free_pgs);
5296 if (env->me_flags & MDB_ENV_TXKEY) {
5297 pthread_key_delete(env->me_txkey);
5299 /* Delete our key from the global list */
5300 for (i=0; i<mdb_tls_nkeys; i++)
5301 if (mdb_tls_keys[i] == env->me_txkey) {
5302 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
5311 munmap(env->me_map, NUM_METAS*env->me_psize);
5313 munmap(env->me_map, env->me_mapsize);
5316 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
5317 (void) close(env->me_mfd);
5318 if (env->me_fd != INVALID_HANDLE_VALUE)
5319 (void) close(env->me_fd);
5321 MDB_PID_T pid = env->me_pid;
5322 /* Clearing readers is done in this function because
5323 * me_txkey with its destructor must be disabled first.
5325 * We skip the the reader mutex, so we touch only
5326 * data owned by this process (me_close_readers and
5327 * our readers), and clear each reader atomically.
5329 for (i = env->me_close_readers; --i >= 0; )
5330 if (env->me_txns->mti_readers[i].mr_pid == pid)
5331 env->me_txns->mti_readers[i].mr_pid = 0;
5333 if (env->me_rmutex) {
5334 CloseHandle(env->me_rmutex);
5335 if (env->me_wmutex) CloseHandle(env->me_wmutex);
5337 /* Windows automatically destroys the mutexes when
5338 * the last handle closes.
5340 #elif defined(MDB_USE_POSIX_SEM)
5341 if (env->me_rmutex != SEM_FAILED) {
5342 sem_close(env->me_rmutex);
5343 if (env->me_wmutex != SEM_FAILED)
5344 sem_close(env->me_wmutex);
5345 /* If we have the filelock: If we are the
5346 * only remaining user, clean up semaphores.
5349 mdb_env_excl_lock(env, &excl);
5351 sem_unlink(env->me_txns->mti_rmname);
5352 sem_unlink(env->me_txns->mti_wmname);
5355 #elif defined(MDB_USE_SYSV_SEM)
5356 if (env->me_rmutex->semid != -1) {
5357 /* If we have the filelock: If we are the
5358 * only remaining user, clean up semaphores.
5361 mdb_env_excl_lock(env, &excl);
5363 semctl(env->me_rmutex->semid, 0, IPC_RMID);
5366 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
5368 if (env->me_lfd != INVALID_HANDLE_VALUE) {
5371 /* Unlock the lockfile. Windows would have unlocked it
5372 * after closing anyway, but not necessarily at once.
5374 UnlockFile(env->me_lfd, 0, 0, 1, 0);
5377 (void) close(env->me_lfd);
5381 if (env->me_fmh) CloseHandle(env->me_fmh);
5382 if (env->me_rpmutex) CloseHandle(env->me_rpmutex);
5384 pthread_mutex_destroy(&env->me_rpmutex);
5388 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
5392 mdb_env_close(MDB_env *env)
5399 VGMEMP_DESTROY(env);
5400 while ((dp = env->me_dpages) != NULL) {
5401 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
5402 env->me_dpages = dp->mp_next;
5406 mdb_env_close0(env, 0);
5410 /** Compare two items pointing at aligned mdb_size_t's */
5412 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
5414 return (*(mdb_size_t *)a->mv_data < *(mdb_size_t *)b->mv_data) ? -1 :
5415 *(mdb_size_t *)a->mv_data > *(mdb_size_t *)b->mv_data;
5418 /** Compare two items pointing at aligned unsigned int's.
5420 * This is also set as #MDB_INTEGERDUP|#MDB_DUPFIXED's #MDB_dbx.%md_dcmp,
5421 * but #mdb_cmp_clong() is called instead if the data type is mdb_size_t.
5424 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
5426 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
5427 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
5430 /** Compare two items pointing at unsigned ints of unknown alignment.
5431 * Nodes and keys are guaranteed to be 2-byte aligned.
5434 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
5436 #if BYTE_ORDER == LITTLE_ENDIAN
5437 unsigned short *u, *c;
5440 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5441 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
5444 } while(!x && u > (unsigned short *)a->mv_data);
5447 unsigned short *u, *c, *end;
5450 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5451 u = (unsigned short *)a->mv_data;
5452 c = (unsigned short *)b->mv_data;
5455 } while(!x && u < end);
5460 /** Compare two items lexically */
5462 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
5469 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5475 diff = memcmp(a->mv_data, b->mv_data, len);
5476 return diff ? diff : len_diff<0 ? -1 : len_diff;
5479 /** Compare two items in reverse byte order */
5481 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
5483 const unsigned char *p1, *p2, *p1_lim;
5487 p1_lim = (const unsigned char *)a->mv_data;
5488 p1 = (const unsigned char *)a->mv_data + a->mv_size;
5489 p2 = (const unsigned char *)b->mv_data + b->mv_size;
5491 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5497 while (p1 > p1_lim) {
5498 diff = *--p1 - *--p2;
5502 return len_diff<0 ? -1 : len_diff;
5505 /** Search for key within a page, using binary search.
5506 * Returns the smallest entry larger or equal to the key.
5507 * If exactp is non-null, stores whether the found entry was an exact match
5508 * in *exactp (1 or 0).
5509 * Updates the cursor index with the index of the found entry.
5510 * If no entry larger or equal to the key is found, returns NULL.
5513 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
5515 unsigned int i = 0, nkeys;
5518 MDB_page *mp = mc->mc_pg[mc->mc_top];
5519 MDB_node *node = NULL;
5524 nkeys = NUMKEYS(mp);
5526 DPRINTF(("searching %u keys in %s %spage %"Y"u",
5527 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
5530 low = IS_LEAF(mp) ? 0 : 1;
5532 cmp = mc->mc_dbx->md_cmp;
5534 /* Branch pages have no data, so if using integer keys,
5535 * alignment is guaranteed. Use faster mdb_cmp_int.
5537 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
5538 if (NODEPTR(mp, 1)->mn_ksize == sizeof(mdb_size_t))
5545 nodekey.mv_size = mc->mc_db->md_pad;
5546 node = NODEPTR(mp, 0); /* fake */
5547 while (low <= high) {
5548 i = (low + high) >> 1;
5549 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
5550 rc = cmp(key, &nodekey);
5551 DPRINTF(("found leaf index %u [%s], rc = %i",
5552 i, DKEY(&nodekey), rc));
5561 while (low <= high) {
5562 i = (low + high) >> 1;
5564 node = NODEPTR(mp, i);
5565 nodekey.mv_size = NODEKSZ(node);
5566 nodekey.mv_data = NODEKEY(node);
5568 rc = cmp(key, &nodekey);
5571 DPRINTF(("found leaf index %u [%s], rc = %i",
5572 i, DKEY(&nodekey), rc));
5574 DPRINTF(("found branch index %u [%s -> %"Y"u], rc = %i",
5575 i, DKEY(&nodekey), NODEPGNO(node), rc));
5586 if (rc > 0) { /* Found entry is less than the key. */
5587 i++; /* Skip to get the smallest entry larger than key. */
5589 node = NODEPTR(mp, i);
5592 *exactp = (rc == 0 && nkeys > 0);
5593 /* store the key index */
5594 mc->mc_ki[mc->mc_top] = i;
5596 /* There is no entry larger or equal to the key. */
5599 /* nodeptr is fake for LEAF2 */
5605 mdb_cursor_adjust(MDB_cursor *mc, func)
5609 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5610 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
5617 /** Pop a page off the top of the cursor's stack. */
5619 mdb_cursor_pop(MDB_cursor *mc)
5622 DPRINTF(("popping page %"Y"u off db %d cursor %p",
5623 mc->mc_pg[mc->mc_top]->mp_pgno, DDBI(mc), (void *) mc));
5629 mc->mc_flags &= ~C_INITIALIZED;
5634 /** Push a page onto the top of the cursor's stack. */
5636 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
5638 DPRINTF(("pushing page %"Y"u on db %d cursor %p", mp->mp_pgno,
5639 DDBI(mc), (void *) mc));
5641 if (mc->mc_snum >= CURSOR_STACK) {
5642 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5643 return MDB_CURSOR_FULL;
5646 mc->mc_top = mc->mc_snum++;
5647 mc->mc_pg[mc->mc_top] = mp;
5648 mc->mc_ki[mc->mc_top] = 0;
5654 /** Map a read-only page.
5655 * There are two levels of tracking in use, a per-txn list and a per-env list.
5656 * ref'ing and unref'ing the per-txn list is faster since it requires no
5657 * locking. Pages are cached in the per-env list for global reuse, and a lock
5658 * is required. Pages are not immediately unmapped when their refcnt goes to
5659 * zero; they hang around in case they will be reused again soon.
5661 * When the per-txn list gets full, all pages with refcnt=0 are purged from the
5662 * list and their refcnts in the per-env list are decremented.
5664 * When the per-env list gets full, all pages with refcnt=0 are purged from the
5665 * list and their pages are unmapped.
5667 * @note "full" means the list has reached its respective rpcheck threshold.
5668 * This threshold slowly raises if no pages could be purged on a given check,
5669 * and returns to its original value when enough pages were purged.
5671 * If purging doesn't free any slots, filling the per-txn list will return
5672 * MDB_TXN_FULL, and filling the per-env list returns MDB_MAP_FULL.
5674 * Reference tracking in a txn is imperfect, pages can linger with non-zero
5675 * refcnt even without active references. It was deemed to be too invasive
5676 * to add unrefs in every required location. However, all pages are unref'd
5677 * at the end of the transaction. This guarantees that no stale references
5678 * linger in the per-env list.
5680 * Usually we map chunks of 16 pages at a time, but if an overflow page begins
5681 * at the tail of the chunk we extend the chunk to include the entire overflow
5682 * page. Unfortunately, pages can be turned into overflow pages after their
5683 * chunk was already mapped. In that case we must remap the chunk if the
5684 * overflow page is referenced. If the chunk's refcnt is 0 we can just remap
5685 * it, otherwise we temporarily map a new chunk just for the overflow page.
5687 * @note this chunk handling means we cannot guarantee that a data item
5688 * returned from the DB will stay alive for the duration of the transaction:
5689 * We unref pages as soon as a cursor moves away from the page
5690 * A subsequent op may cause a purge, which may unmap any unref'd chunks
5691 * The caller must copy the data if it must be used later in the same txn.
5693 * Also - our reference counting revolves around cursors, but overflow pages
5694 * aren't pointed to by a cursor's page stack. We have to remember them
5695 * explicitly, in the added mc_ovpg field. A single cursor can only hold a
5696 * reference to one overflow page at a time.
5698 * @param[in] txn the transaction for this access.
5699 * @param[in] pgno the page number for the page to retrieve.
5700 * @param[out] ret address of a pointer where the page's address will be stored.
5701 * @return 0 on success, non-zero on failure.
5704 mdb_rpage_get(MDB_txn *txn, pgno_t pg0, MDB_page **ret)
5706 MDB_env *env = txn->mt_env;
5708 MDB_ID3L tl = txn->mt_rpages;
5709 MDB_ID3L el = env->me_rpages;
5713 int rc, retries = 1;
5717 #define SET_OFF(off,val) off.QuadPart = val
5718 #define MAP(rc,env,addr,len,off) \
5720 rc = NtMapViewOfSection(env->me_fmh, GetCurrentProcess(), &addr, 0, \
5721 len, &off, &len, ViewUnmap, (env->me_flags & MDB_RDONLY) ? 0 : MEM_RESERVE, PAGE_READONLY); \
5722 if (rc) rc = mdb_nt2win32(rc)
5726 #define SET_OFF(off,val) off = val
5727 #define MAP(rc,env,addr,len,off) \
5728 addr = mmap(NULL, len, PROT_READ, MAP_SHARED, env->me_fd, off); \
5729 rc = (addr == MAP_FAILED) ? errno : 0
5732 /* remember the offset of the actual page number, so we can
5733 * return the correct pointer at the end.
5735 rem = pg0 & (MDB_RPAGE_CHUNK-1);
5739 x = mdb_mid3l_search(tl, pgno);
5740 if (x <= tl[0].mid && tl[x].mid == pgno) {
5741 if (x != tl[0].mid && tl[x+1].mid == pg0)
5743 /* check for overflow size */
5744 p = (MDB_page *)((char *)tl[x].mptr + rem * env->me_psize);
5745 if (IS_OVERFLOW(p) && p->mp_pages + rem > tl[x].mcnt) {
5746 id3.mcnt = p->mp_pages + rem;
5747 len = id3.mcnt * env->me_psize;
5748 SET_OFF(off, pgno * env->me_psize);
5749 MAP(rc, env, id3.mptr, len, off);
5752 /* check for local-only page */
5754 mdb_tassert(txn, tl[x].mid != pg0);
5755 /* hope there's room to insert this locally.
5756 * setting mid here tells later code to just insert
5757 * this id3 instead of searching for a match.
5762 /* ignore the mapping we got from env, use new one */
5763 tl[x].mptr = id3.mptr;
5764 tl[x].mcnt = id3.mcnt;
5765 /* if no active ref, see if we can replace in env */
5768 pthread_mutex_lock(&env->me_rpmutex);
5769 i = mdb_mid3l_search(el, tl[x].mid);
5770 if (el[i].mref == 1) {
5771 /* just us, replace it */
5772 munmap(el[i].mptr, el[i].mcnt * env->me_psize);
5773 el[i].mptr = tl[x].mptr;
5774 el[i].mcnt = tl[x].mcnt;
5776 /* there are others, remove ourself */
5779 pthread_mutex_unlock(&env->me_rpmutex);
5783 id3.mptr = tl[x].mptr;
5784 id3.mcnt = tl[x].mcnt;
5790 if (tl[0].mid >= MDB_TRPAGE_MAX - txn->mt_rpcheck) {
5792 /* purge unref'd pages from our list and unref in env */
5793 pthread_mutex_lock(&env->me_rpmutex);
5796 for (i=1; i<=tl[0].mid; i++) {
5799 /* tmp overflow pages don't go to env */
5800 if (tl[i].mid & (MDB_RPAGE_CHUNK-1)) {
5801 munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
5804 x = mdb_mid3l_search(el, tl[i].mid);
5808 pthread_mutex_unlock(&env->me_rpmutex);
5810 /* we didn't find any unref'd chunks.
5811 * if we're out of room, fail.
5813 if (tl[0].mid >= MDB_TRPAGE_MAX)
5814 return MDB_TXN_FULL;
5815 /* otherwise, raise threshold for next time around
5818 txn->mt_rpcheck /= 2;
5820 /* we found some unused; consolidate the list */
5821 for (i=y+1; i<= tl[0].mid; i++)
5825 /* decrease the check threshold toward its original value */
5826 if (!txn->mt_rpcheck)
5827 txn->mt_rpcheck = 1;
5828 while (txn->mt_rpcheck < tl[0].mid && txn->mt_rpcheck < MDB_TRPAGE_SIZE/2)
5829 txn->mt_rpcheck *= 2;
5832 if (tl[0].mid < MDB_TRPAGE_SIZE) {
5836 /* don't map past last written page in read-only envs */
5837 if ((env->me_flags & MDB_RDONLY) && pgno + MDB_RPAGE_CHUNK-1 > txn->mt_last_pgno)
5838 id3.mcnt = txn->mt_last_pgno + 1 - pgno;
5840 id3.mcnt = MDB_RPAGE_CHUNK;
5841 len = id3.mcnt * env->me_psize;
5844 /* search for page in env */
5845 pthread_mutex_lock(&env->me_rpmutex);
5846 x = mdb_mid3l_search(el, pgno);
5847 if (x <= el[0].mid && el[x].mid == pgno) {
5848 id3.mptr = el[x].mptr;
5849 id3.mcnt = el[x].mcnt;
5850 /* check for overflow size */
5851 p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
5852 if (IS_OVERFLOW(p) && p->mp_pages + rem > id3.mcnt) {
5853 id3.mcnt = p->mp_pages + rem;
5854 len = id3.mcnt * env->me_psize;
5855 SET_OFF(off, pgno * env->me_psize);
5856 MAP(rc, env, id3.mptr, len, off);
5860 munmap(el[x].mptr, env->me_psize * el[x].mcnt);
5861 el[x].mptr = id3.mptr;
5862 el[x].mcnt = id3.mcnt;
5865 pthread_mutex_unlock(&env->me_rpmutex);
5870 pthread_mutex_unlock(&env->me_rpmutex);
5873 if (el[0].mid >= MDB_ERPAGE_MAX - env->me_rpcheck) {
5874 /* purge unref'd pages */
5876 for (i=1; i<=el[0].mid; i++) {
5879 munmap(el[i].mptr, env->me_psize * el[i].mcnt);
5884 /* see if we can unref some local pages */
5889 if (el[0].mid >= MDB_ERPAGE_MAX) {
5890 pthread_mutex_unlock(&env->me_rpmutex);
5891 return MDB_MAP_FULL;
5893 env->me_rpcheck /= 2;
5895 for (i=y+1; i<= el[0].mid; i++)
5899 if (!env->me_rpcheck)
5900 env->me_rpcheck = 1;
5901 while (env->me_rpcheck < el[0].mid && env->me_rpcheck < MDB_ERPAGE_SIZE/2)
5902 env->me_rpcheck *= 2;
5905 SET_OFF(off, pgno * env->me_psize);
5906 MAP(rc, env, id3.mptr, len, off);
5909 pthread_mutex_unlock(&env->me_rpmutex);
5912 /* check for overflow size */
5913 p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
5914 if (IS_OVERFLOW(p) && p->mp_pages + rem > id3.mcnt) {
5915 id3.mcnt = p->mp_pages + rem;
5916 munmap(id3.mptr, len);
5917 len = id3.mcnt * env->me_psize;
5918 MAP(rc, env, id3.mptr, len, off);
5922 mdb_mid3l_insert(el, &id3);
5923 pthread_mutex_unlock(&env->me_rpmutex);
5925 mdb_mid3l_insert(tl, &id3);
5927 return MDB_TXN_FULL;
5930 p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
5931 #if MDB_DEBUG /* we don't need this check any more */
5932 if (IS_OVERFLOW(p)) {
5933 mdb_tassert(txn, p->mp_pages + rem <= id3.mcnt);
5941 /** Find the address of the page corresponding to a given page number.
5942 * @param[in] mc the cursor accessing the page.
5943 * @param[in] pgno the page number for the page to retrieve.
5944 * @param[out] ret address of a pointer where the page's address will be stored.
5945 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
5946 * @return 0 on success, non-zero on failure.
5949 mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **ret, int *lvl)
5951 MDB_txn *txn = mc->mc_txn;
5953 MDB_env *env = txn->mt_env;
5958 if (! (mc->mc_flags & (C_ORIG_RDONLY|C_WRITEMAP))) {
5962 MDB_ID2L dl = tx2->mt_u.dirty_list;
5964 /* Spilled pages were dirtied in this txn and flushed
5965 * because the dirty list got full. Bring this page
5966 * back in from the map (but don't unspill it here,
5967 * leave that unless page_touch happens again).
5969 if (tx2->mt_spill_pgs) {
5970 MDB_ID pn = pgno << 1;
5971 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
5972 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
5974 int rc = mdb_rpage_get(txn, pgno, &p);
5978 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5984 unsigned x = mdb_mid2l_search(dl, pgno);
5985 if (x <= dl[0].mid && dl[x].mid == pgno) {
5991 } while ((tx2 = tx2->mt_parent) != NULL);
5994 if (pgno < txn->mt_next_pgno) {
5998 int rc = mdb_rpage_get(txn, pgno, &p);
6003 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
6006 DPRINTF(("page %"Y"u not found", pgno));
6007 txn->mt_flags |= MDB_TXN_ERROR;
6008 return MDB_PAGE_NOTFOUND;
6018 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
6019 * The cursor is at the root page, set up the rest of it.
6022 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
6024 MDB_page *mp = mc->mc_pg[mc->mc_top];
6028 while (IS_BRANCH(mp)) {
6032 DPRINTF(("branch page %"Y"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
6033 /* Don't assert on branch pages in the FreeDB. We can get here
6034 * while in the process of rebalancing a FreeDB branch page; we must
6035 * let that proceed. ITS#8336
6037 mdb_cassert(mc, !mc->mc_dbi || NUMKEYS(mp) > 1);
6038 DPRINTF(("found index 0 to page %"Y"u", NODEPGNO(NODEPTR(mp, 0))));
6040 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
6042 if (flags & MDB_PS_LAST)
6043 i = NUMKEYS(mp) - 1;
6046 node = mdb_node_search(mc, key, &exact);
6048 i = NUMKEYS(mp) - 1;
6050 i = mc->mc_ki[mc->mc_top];
6052 mdb_cassert(mc, i > 0);
6056 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
6059 mdb_cassert(mc, i < NUMKEYS(mp));
6060 node = NODEPTR(mp, i);
6062 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
6065 mc->mc_ki[mc->mc_top] = i;
6066 if ((rc = mdb_cursor_push(mc, mp)))
6069 if (flags & MDB_PS_MODIFY) {
6070 if ((rc = mdb_page_touch(mc)) != 0)
6072 mp = mc->mc_pg[mc->mc_top];
6077 DPRINTF(("internal error, index points to a %02X page!?",
6079 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6080 return MDB_CORRUPTED;
6083 DPRINTF(("found leaf page %"Y"u for key [%s]", mp->mp_pgno,
6084 key ? DKEY(key) : "null"));
6085 mc->mc_flags |= C_INITIALIZED;
6086 mc->mc_flags &= ~C_EOF;
6091 /** Search for the lowest key under the current branch page.
6092 * This just bypasses a NUMKEYS check in the current page
6093 * before calling mdb_page_search_root(), because the callers
6094 * are all in situations where the current page is known to
6098 mdb_page_search_lowest(MDB_cursor *mc)
6100 MDB_page *mp = mc->mc_pg[mc->mc_top];
6101 MDB_node *node = NODEPTR(mp, 0);
6104 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
6107 mc->mc_ki[mc->mc_top] = 0;
6108 if ((rc = mdb_cursor_push(mc, mp)))
6110 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
6113 /** Search for the page a given key should be in.
6114 * Push it and its parent pages on the cursor stack.
6115 * @param[in,out] mc the cursor for this operation.
6116 * @param[in] key the key to search for, or NULL for first/last page.
6117 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
6118 * are touched (updated with new page numbers).
6119 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
6120 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
6121 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
6122 * @return 0 on success, non-zero on failure.
6125 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
6130 /* Make sure the txn is still viable, then find the root from
6131 * the txn's db table and set it as the root of the cursor's stack.
6133 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED) {
6134 DPUTS("transaction may not be used now");
6137 /* Make sure we're using an up-to-date root */
6138 if (*mc->mc_dbflag & DB_STALE) {
6140 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
6142 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
6143 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
6150 MDB_node *leaf = mdb_node_search(&mc2,
6151 &mc->mc_dbx->md_name, &exact);
6153 return MDB_NOTFOUND;
6154 if ((leaf->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
6155 return MDB_INCOMPATIBLE; /* not a named DB */
6156 rc = mdb_node_read(&mc2, leaf, &data);
6159 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
6161 /* The txn may not know this DBI, or another process may
6162 * have dropped and recreated the DB with other flags.
6164 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
6165 return MDB_INCOMPATIBLE;
6166 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
6168 *mc->mc_dbflag &= ~DB_STALE;
6170 root = mc->mc_db->md_root;
6172 if (root == P_INVALID) { /* Tree is empty. */
6173 DPUTS("tree is empty");
6174 return MDB_NOTFOUND;
6178 mdb_cassert(mc, root > 1);
6179 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root) {
6182 MDB_PAGE_UNREF(mc->mc_txn, mc->mc_pg[0]);
6184 if ((rc = mdb_page_get(mc, root, &mc->mc_pg[0], NULL)) != 0)
6191 for (i=1; i<mc->mc_snum; i++)
6192 MDB_PAGE_UNREF(mc->mc_txn, mc->mc_pg[i]);
6198 DPRINTF(("db %d root page %"Y"u has flags 0x%X",
6199 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
6201 if (flags & MDB_PS_MODIFY) {
6202 if ((rc = mdb_page_touch(mc)))
6206 if (flags & MDB_PS_ROOTONLY)
6209 return mdb_page_search_root(mc, key, flags);
6213 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
6215 MDB_txn *txn = mc->mc_txn;
6216 pgno_t pg = mp->mp_pgno;
6217 unsigned x = 0, ovpages = mp->mp_pages;
6218 MDB_env *env = txn->mt_env;
6219 MDB_IDL sl = txn->mt_spill_pgs;
6220 MDB_ID pn = pg << 1;
6223 DPRINTF(("free ov page %"Y"u (%d)", pg, ovpages));
6224 /* If the page is dirty or on the spill list we just acquired it,
6225 * so we should give it back to our current free list, if any.
6226 * Otherwise put it onto the list of pages we freed in this txn.
6228 * Won't create me_pghead: me_pglast must be inited along with it.
6229 * Unsupported in nested txns: They would need to hide the page
6230 * range in ancestor txns' dirty and spilled lists.
6232 if (env->me_pghead &&
6234 ((mp->mp_flags & P_DIRTY) ||
6235 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
6239 MDB_ID2 *dl, ix, iy;
6240 rc = mdb_midl_need(&env->me_pghead, ovpages);
6243 if (!(mp->mp_flags & P_DIRTY)) {
6244 /* This page is no longer spilled */
6251 /* Remove from dirty list */
6252 dl = txn->mt_u.dirty_list;
6254 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
6260 mdb_cassert(mc, x > 1);
6262 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
6263 txn->mt_flags |= MDB_TXN_ERROR;
6264 return MDB_CORRUPTED;
6267 txn->mt_dirty_room++;
6268 if (!(env->me_flags & MDB_WRITEMAP))
6269 mdb_dpage_free(env, mp);
6271 /* Insert in me_pghead */
6272 mop = env->me_pghead;
6273 j = mop[0] + ovpages;
6274 for (i = mop[0]; i && mop[i] < pg; i--)
6280 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
6284 mc->mc_db->md_overflow_pages -= ovpages;
6288 /** Return the data associated with a given node.
6289 * @param[in] mc The cursor for this operation.
6290 * @param[in] leaf The node being read.
6291 * @param[out] data Updated to point to the node's data.
6292 * @return 0 on success, non-zero on failure.
6295 mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data)
6297 MDB_page *omp; /* overflow page */
6303 MDB_PAGE_UNREF(mc->mc_txn, mc->mc_ovpg);
6307 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6308 data->mv_size = NODEDSZ(leaf);
6309 data->mv_data = NODEDATA(leaf);
6313 /* Read overflow data.
6315 data->mv_size = NODEDSZ(leaf);
6316 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
6317 if ((rc = mdb_page_get(mc, pgno, &omp, NULL)) != 0) {
6318 DPRINTF(("read overflow page %"Y"u failed", pgno));
6321 data->mv_data = METADATA(omp);
6330 mdb_get(MDB_txn *txn, MDB_dbi dbi,
6331 MDB_val *key, MDB_val *data)
6338 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
6340 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
6343 if (txn->mt_flags & MDB_TXN_BLOCKED)
6346 mdb_cursor_init(&mc, txn, dbi, &mx);
6347 rc = mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
6350 /* unref all the pages - caller must copy the data
6351 * before doing anything else
6353 mdb_cursor_unref(&mc);
6359 /** Find a sibling for a page.
6360 * Replaces the page at the top of the cursor's stack with the
6361 * specified sibling, if one exists.
6362 * @param[in] mc The cursor for this operation.
6363 * @param[in] move_right Non-zero if the right sibling is requested,
6364 * otherwise the left sibling.
6365 * @return 0 on success, non-zero on failure.
6368 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
6377 if (mc->mc_snum < 2) {
6378 return MDB_NOTFOUND; /* root has no siblings */
6382 op = mc->mc_pg[mc->mc_top];
6385 DPRINTF(("parent page is page %"Y"u, index %u",
6386 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
6388 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6389 : (mc->mc_ki[mc->mc_top] == 0)) {
6390 DPRINTF(("no more keys left, moving to %s sibling",
6391 move_right ? "right" : "left"));
6392 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
6393 /* undo cursor_pop before returning */
6400 mc->mc_ki[mc->mc_top]++;
6402 mc->mc_ki[mc->mc_top]--;
6403 DPRINTF(("just moving to %s index key %u",
6404 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
6406 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
6408 MDB_PAGE_UNREF(mc->mc_txn, op);
6410 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6411 if ((rc = mdb_page_get(mc, NODEPGNO(indx), &mp, NULL)) != 0) {
6412 /* mc will be inconsistent if caller does mc_snum++ as above */
6413 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
6417 mdb_cursor_push(mc, mp);
6419 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
6424 /** Move the cursor to the next data item. */
6426 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
6432 if ((mc->mc_flags & C_EOF) ||
6433 ((mc->mc_flags & C_DEL) && op == MDB_NEXT_DUP)) {
6434 return MDB_NOTFOUND;
6436 if (!(mc->mc_flags & C_INITIALIZED))
6437 return mdb_cursor_first(mc, key, data);
6439 mp = mc->mc_pg[mc->mc_top];
6441 if (mc->mc_db->md_flags & MDB_DUPSORT) {
6442 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6443 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6444 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
6445 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
6446 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
6447 if (rc == MDB_SUCCESS)
6448 MDB_GET_KEY(leaf, key);
6454 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6455 mdb_cursor_unref(&mc->mc_xcursor->mx_cursor);
6460 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6461 if (op == MDB_NEXT_DUP)
6462 return MDB_NOTFOUND;
6466 DPRINTF(("cursor_next: top page is %"Y"u in cursor %p",
6467 mdb_dbg_pgno(mp), (void *) mc));
6468 if (mc->mc_flags & C_DEL) {
6469 mc->mc_flags ^= C_DEL;
6473 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
6474 DPUTS("=====> move to next sibling page");
6475 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
6476 mc->mc_flags |= C_EOF;
6479 mp = mc->mc_pg[mc->mc_top];
6480 DPRINTF(("next page is %"Y"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
6482 mc->mc_ki[mc->mc_top]++;
6485 DPRINTF(("==> cursor points to page %"Y"u with %u keys, key index %u",
6486 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
6489 key->mv_size = mc->mc_db->md_pad;
6490 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6494 mdb_cassert(mc, IS_LEAF(mp));
6495 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6497 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6498 mdb_xcursor_init1(mc, leaf);
6501 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6504 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6505 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6506 if (rc != MDB_SUCCESS)
6511 MDB_GET_KEY(leaf, key);
6515 /** Move the cursor to the previous data item. */
6517 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
6523 if (!(mc->mc_flags & C_INITIALIZED)) {
6524 rc = mdb_cursor_last(mc, key, data);
6527 mc->mc_ki[mc->mc_top]++;
6530 mp = mc->mc_pg[mc->mc_top];
6532 if (mc->mc_db->md_flags & MDB_DUPSORT) {
6533 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6534 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6535 if (op == MDB_PREV || op == MDB_PREV_DUP) {
6536 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
6537 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
6538 if (rc == MDB_SUCCESS) {
6539 MDB_GET_KEY(leaf, key);
6540 mc->mc_flags &= ~C_EOF;
6547 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6548 mdb_cursor_unref(&mc->mc_xcursor->mx_cursor);
6553 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6554 if (op == MDB_PREV_DUP)
6555 return MDB_NOTFOUND;
6559 DPRINTF(("cursor_prev: top page is %"Y"u in cursor %p",
6560 mdb_dbg_pgno(mp), (void *) mc));
6562 mc->mc_flags &= ~(C_EOF|C_DEL);
6564 if (mc->mc_ki[mc->mc_top] == 0) {
6565 DPUTS("=====> move to prev sibling page");
6566 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
6569 mp = mc->mc_pg[mc->mc_top];
6570 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
6571 DPRINTF(("prev page is %"Y"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
6573 mc->mc_ki[mc->mc_top]--;
6575 mc->mc_flags &= ~C_EOF;
6577 DPRINTF(("==> cursor points to page %"Y"u with %u keys, key index %u",
6578 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
6581 key->mv_size = mc->mc_db->md_pad;
6582 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6586 mdb_cassert(mc, IS_LEAF(mp));
6587 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6589 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6590 mdb_xcursor_init1(mc, leaf);
6593 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6596 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6597 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
6598 if (rc != MDB_SUCCESS)
6603 MDB_GET_KEY(leaf, key);
6607 /** Set the cursor on a specific data item. */
6609 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6610 MDB_cursor_op op, int *exactp)
6614 MDB_node *leaf = NULL;
6617 if (key->mv_size == 0)
6618 return MDB_BAD_VALSIZE;
6621 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6623 /* See if we're already on the right page */
6624 if (mc->mc_flags & C_INITIALIZED) {
6627 mp = mc->mc_pg[mc->mc_top];
6629 mc->mc_ki[mc->mc_top] = 0;
6630 return MDB_NOTFOUND;
6632 if (mp->mp_flags & P_LEAF2) {
6633 nodekey.mv_size = mc->mc_db->md_pad;
6634 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
6636 leaf = NODEPTR(mp, 0);
6637 MDB_GET_KEY2(leaf, nodekey);
6639 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6641 /* Probably happens rarely, but first node on the page
6642 * was the one we wanted.
6644 mc->mc_ki[mc->mc_top] = 0;
6651 unsigned int nkeys = NUMKEYS(mp);
6653 if (mp->mp_flags & P_LEAF2) {
6654 nodekey.mv_data = LEAF2KEY(mp,
6655 nkeys-1, nodekey.mv_size);
6657 leaf = NODEPTR(mp, nkeys-1);
6658 MDB_GET_KEY2(leaf, nodekey);
6660 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6662 /* last node was the one we wanted */
6663 mc->mc_ki[mc->mc_top] = nkeys-1;
6669 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
6670 /* This is definitely the right page, skip search_page */
6671 if (mp->mp_flags & P_LEAF2) {
6672 nodekey.mv_data = LEAF2KEY(mp,
6673 mc->mc_ki[mc->mc_top], nodekey.mv_size);
6675 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6676 MDB_GET_KEY2(leaf, nodekey);
6678 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6680 /* current node was the one we wanted */
6690 /* If any parents have right-sibs, search.
6691 * Otherwise, there's nothing further.
6693 for (i=0; i<mc->mc_top; i++)
6695 NUMKEYS(mc->mc_pg[i])-1)
6697 if (i == mc->mc_top) {
6698 /* There are no other pages */
6699 mc->mc_ki[mc->mc_top] = nkeys;
6700 return MDB_NOTFOUND;
6704 /* There are no other pages */
6705 mc->mc_ki[mc->mc_top] = 0;
6706 if (op == MDB_SET_RANGE && !exactp) {
6710 return MDB_NOTFOUND;
6716 rc = mdb_page_search(mc, key, 0);
6717 if (rc != MDB_SUCCESS)
6720 mp = mc->mc_pg[mc->mc_top];
6721 mdb_cassert(mc, IS_LEAF(mp));
6724 leaf = mdb_node_search(mc, key, exactp);
6725 if (exactp != NULL && !*exactp) {
6726 /* MDB_SET specified and not an exact match. */
6727 return MDB_NOTFOUND;
6731 DPUTS("===> inexact leaf not found, goto sibling");
6732 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
6733 mc->mc_flags |= C_EOF;
6734 return rc; /* no entries matched */
6736 mp = mc->mc_pg[mc->mc_top];
6737 mdb_cassert(mc, IS_LEAF(mp));
6738 leaf = NODEPTR(mp, 0);
6742 mc->mc_flags |= C_INITIALIZED;
6743 mc->mc_flags &= ~C_EOF;
6746 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
6747 key->mv_size = mc->mc_db->md_pad;
6748 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6754 if (mc->mc_xcursor && mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6755 mdb_cursor_unref(&mc->mc_xcursor->mx_cursor);
6758 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6759 mdb_xcursor_init1(mc, leaf);
6762 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6763 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
6764 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6767 if (op == MDB_GET_BOTH) {
6773 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
6774 if (rc != MDB_SUCCESS)
6777 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
6780 if ((rc = mdb_node_read(mc, leaf, &olddata)) != MDB_SUCCESS)
6782 dcmp = mc->mc_dbx->md_dcmp;
6783 #if UINT_MAX < SIZE_MAX || defined(MDB_VL32)
6784 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(mdb_size_t))
6785 dcmp = mdb_cmp_clong;
6787 rc = dcmp(data, &olddata);
6789 if (op == MDB_GET_BOTH || rc > 0)
6790 return MDB_NOTFOUND;
6797 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6798 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6803 /* The key already matches in all other cases */
6804 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
6805 MDB_GET_KEY(leaf, key);
6806 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
6811 /** Move the cursor to the first item in the database. */
6813 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6818 if (mc->mc_xcursor) {
6820 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6821 mdb_cursor_unref(&mc->mc_xcursor->mx_cursor);
6824 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6827 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6828 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
6829 if (rc != MDB_SUCCESS)
6832 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6834 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
6835 mc->mc_flags |= C_INITIALIZED;
6836 mc->mc_flags &= ~C_EOF;
6838 mc->mc_ki[mc->mc_top] = 0;
6840 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6841 key->mv_size = mc->mc_db->md_pad;
6842 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
6847 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6848 mdb_xcursor_init1(mc, leaf);
6849 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6853 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6857 MDB_GET_KEY(leaf, key);
6861 /** Move the cursor to the last item in the database. */
6863 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6868 if (mc->mc_xcursor) {
6870 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6871 mdb_cursor_unref(&mc->mc_xcursor->mx_cursor);
6874 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6877 if (!(mc->mc_flags & C_EOF)) {
6879 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6880 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
6881 if (rc != MDB_SUCCESS)
6884 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6887 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
6888 mc->mc_flags |= C_INITIALIZED|C_EOF;
6889 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6891 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6892 key->mv_size = mc->mc_db->md_pad;
6893 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
6898 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6899 mdb_xcursor_init1(mc, leaf);
6900 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
6904 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6909 MDB_GET_KEY(leaf, key);
6914 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6919 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
6924 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
6928 case MDB_GET_CURRENT:
6929 if (!(mc->mc_flags & C_INITIALIZED)) {
6932 MDB_page *mp = mc->mc_pg[mc->mc_top];
6933 int nkeys = NUMKEYS(mp);
6934 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
6935 mc->mc_ki[mc->mc_top] = nkeys;
6941 key->mv_size = mc->mc_db->md_pad;
6942 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6944 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6945 MDB_GET_KEY(leaf, key);
6947 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6948 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
6950 rc = mdb_node_read(mc, leaf, data);
6957 case MDB_GET_BOTH_RANGE:
6962 if (mc->mc_xcursor == NULL) {
6963 rc = MDB_INCOMPATIBLE;
6973 rc = mdb_cursor_set(mc, key, data, op,
6974 op == MDB_SET_RANGE ? NULL : &exact);
6977 case MDB_GET_MULTIPLE:
6978 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
6982 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6983 rc = MDB_INCOMPATIBLE;
6987 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
6988 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
6991 case MDB_NEXT_MULTIPLE:
6996 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6997 rc = MDB_INCOMPATIBLE;
7000 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
7001 if (rc == MDB_SUCCESS) {
7002 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
7005 mx = &mc->mc_xcursor->mx_cursor;
7006 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
7008 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
7009 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
7015 case MDB_PREV_MULTIPLE:
7020 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7021 rc = MDB_INCOMPATIBLE;
7024 if (!(mc->mc_flags & C_INITIALIZED))
7025 rc = mdb_cursor_last(mc, key, data);
7028 if (rc == MDB_SUCCESS) {
7029 MDB_cursor *mx = &mc->mc_xcursor->mx_cursor;
7030 if (mx->mc_flags & C_INITIALIZED) {
7031 rc = mdb_cursor_sibling(mx, 0);
7032 if (rc == MDB_SUCCESS)
7041 case MDB_NEXT_NODUP:
7042 rc = mdb_cursor_next(mc, key, data, op);
7046 case MDB_PREV_NODUP:
7047 rc = mdb_cursor_prev(mc, key, data, op);
7050 rc = mdb_cursor_first(mc, key, data);
7053 mfunc = mdb_cursor_first;
7055 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
7059 if (mc->mc_xcursor == NULL) {
7060 rc = MDB_INCOMPATIBLE;
7064 MDB_node *leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7065 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7066 MDB_GET_KEY(leaf, key);
7067 rc = mdb_node_read(mc, leaf, data);
7071 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
7075 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
7078 rc = mdb_cursor_last(mc, key, data);
7081 mfunc = mdb_cursor_last;
7084 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
7089 if (mc->mc_flags & C_DEL)
7090 mc->mc_flags ^= C_DEL;
7095 /** Touch all the pages in the cursor stack. Set mc_top.
7096 * Makes sure all the pages are writable, before attempting a write operation.
7097 * @param[in] mc The cursor to operate on.
7100 mdb_cursor_touch(MDB_cursor *mc)
7102 int rc = MDB_SUCCESS;
7104 if (mc->mc_dbi >= CORE_DBS && !(*mc->mc_dbflag & DB_DIRTY)) {
7107 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
7109 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
7110 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
7113 *mc->mc_dbflag |= DB_DIRTY;
7118 rc = mdb_page_touch(mc);
7119 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
7120 mc->mc_top = mc->mc_snum-1;
7125 /** Do not spill pages to disk if txn is getting full, may fail instead */
7126 #define MDB_NOSPILL 0x8000
7129 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
7133 MDB_node *leaf = NULL;
7134 MDB_page *fp, *mp, *sub_root = NULL;
7136 MDB_val xdata, *rdata, dkey, olddata;
7138 int do_sub = 0, insert_key, insert_data;
7139 unsigned int mcount = 0, dcount = 0, nospill;
7142 unsigned int nflags;
7145 if (mc == NULL || key == NULL)
7148 env = mc->mc_txn->mt_env;
7150 /* Check this first so counter will always be zero on any
7153 if (flags & MDB_MULTIPLE) {
7154 dcount = data[1].mv_size;
7155 data[1].mv_size = 0;
7156 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
7157 return MDB_INCOMPATIBLE;
7160 nospill = flags & MDB_NOSPILL;
7161 flags &= ~MDB_NOSPILL;
7163 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
7164 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7166 if (key->mv_size-1 >= ENV_MAXKEY(env))
7167 return MDB_BAD_VALSIZE;
7169 #if SIZE_MAX > MAXDATASIZE
7170 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
7171 return MDB_BAD_VALSIZE;
7173 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
7174 return MDB_BAD_VALSIZE;
7177 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
7178 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
7182 if (flags == MDB_CURRENT) {
7183 if (!(mc->mc_flags & C_INITIALIZED))
7186 } else if (mc->mc_db->md_root == P_INVALID) {
7187 /* new database, cursor has nothing to point to */
7190 mc->mc_flags &= ~C_INITIALIZED;
7195 if (flags & MDB_APPEND) {
7197 rc = mdb_cursor_last(mc, &k2, &d2);
7199 rc = mc->mc_dbx->md_cmp(key, &k2);
7202 mc->mc_ki[mc->mc_top]++;
7204 /* new key is <= last key */
7209 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
7211 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
7212 DPRINTF(("duplicate key [%s]", DKEY(key)));
7214 return MDB_KEYEXIST;
7216 if (rc && rc != MDB_NOTFOUND)
7220 if (mc->mc_flags & C_DEL)
7221 mc->mc_flags ^= C_DEL;
7223 /* Cursor is positioned, check for room in the dirty list */
7225 if (flags & MDB_MULTIPLE) {
7227 xdata.mv_size = data->mv_size * dcount;
7231 if ((rc2 = mdb_page_spill(mc, key, rdata)))
7235 if (rc == MDB_NO_ROOT) {
7237 /* new database, write a root leaf page */
7238 DPUTS("allocating new root leaf page");
7239 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
7242 mdb_cursor_push(mc, np);
7243 mc->mc_db->md_root = np->mp_pgno;
7244 mc->mc_db->md_depth++;
7245 *mc->mc_dbflag |= DB_DIRTY;
7246 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
7248 np->mp_flags |= P_LEAF2;
7249 mc->mc_flags |= C_INITIALIZED;
7251 /* make sure all cursor pages are writable */
7252 rc2 = mdb_cursor_touch(mc);
7257 insert_key = insert_data = rc;
7259 /* The key does not exist */
7260 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
7261 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
7262 LEAFSIZE(key, data) > env->me_nodemax)
7264 /* Too big for a node, insert in sub-DB. Set up an empty
7265 * "old sub-page" for prep_subDB to expand to a full page.
7267 fp_flags = P_LEAF|P_DIRTY;
7269 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
7270 fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
7271 olddata.mv_size = PAGEHDRSZ;
7275 /* there's only a key anyway, so this is a no-op */
7276 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
7278 unsigned int ksize = mc->mc_db->md_pad;
7279 if (key->mv_size != ksize)
7280 return MDB_BAD_VALSIZE;
7281 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
7282 memcpy(ptr, key->mv_data, ksize);
7284 /* if overwriting slot 0 of leaf, need to
7285 * update branch key if there is a parent page
7287 if (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
7288 unsigned short dtop = 1;
7290 /* slot 0 is always an empty key, find real slot */
7291 while (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
7295 if (mc->mc_ki[mc->mc_top])
7296 rc2 = mdb_update_key(mc, key);
7307 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7308 olddata.mv_size = NODEDSZ(leaf);
7309 olddata.mv_data = NODEDATA(leaf);
7312 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
7313 /* Prepare (sub-)page/sub-DB to accept the new item,
7314 * if needed. fp: old sub-page or a header faking
7315 * it. mp: new (sub-)page. offset: growth in page
7316 * size. xdata: node data with new page or DB.
7318 unsigned i, offset = 0;
7319 mp = fp = xdata.mv_data = env->me_pbuf;
7320 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
7322 /* Was a single item before, must convert now */
7323 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7325 /* Just overwrite the current item */
7326 if (flags == MDB_CURRENT)
7328 dcmp = mc->mc_dbx->md_dcmp;
7329 #if UINT_MAX < SIZE_MAX || defined(MDB_VL32)
7330 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(mdb_size_t))
7331 dcmp = mdb_cmp_clong;
7333 /* does data match? */
7334 if (!dcmp(data, &olddata)) {
7335 if (flags & (MDB_NODUPDATA|MDB_APPENDDUP))
7336 return MDB_KEYEXIST;
7341 /* Back up original data item */
7342 dkey.mv_size = olddata.mv_size;
7343 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
7345 /* Make sub-page header for the dup items, with dummy body */
7346 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
7347 fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
7348 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
7349 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7350 fp->mp_flags |= P_LEAF2;
7351 fp->mp_pad = data->mv_size;
7352 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
7354 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
7355 (dkey.mv_size & 1) + (data->mv_size & 1);
7357 fp->mp_upper = xdata.mv_size - PAGEBASE;
7358 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
7359 } else if (leaf->mn_flags & F_SUBDATA) {
7360 /* Data is on sub-DB, just store it */
7361 flags |= F_DUPDATA|F_SUBDATA;
7364 /* Data is on sub-page */
7365 fp = olddata.mv_data;
7368 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7369 offset = EVEN(NODESIZE + sizeof(indx_t) +
7373 offset = fp->mp_pad;
7374 if (SIZELEFT(fp) < offset) {
7375 offset *= 4; /* space for 4 more */
7378 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
7380 fp->mp_flags |= P_DIRTY;
7381 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
7382 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
7386 xdata.mv_size = olddata.mv_size + offset;
7389 fp_flags = fp->mp_flags;
7390 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
7391 /* Too big for a sub-page, convert to sub-DB */
7392 fp_flags &= ~P_SUBP;
7394 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7395 fp_flags |= P_LEAF2;
7396 dummy.md_pad = fp->mp_pad;
7397 dummy.md_flags = MDB_DUPFIXED;
7398 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
7399 dummy.md_flags |= MDB_INTEGERKEY;
7405 dummy.md_branch_pages = 0;
7406 dummy.md_leaf_pages = 1;
7407 dummy.md_overflow_pages = 0;
7408 dummy.md_entries = NUMKEYS(fp);
7409 xdata.mv_size = sizeof(MDB_db);
7410 xdata.mv_data = &dummy;
7411 if ((rc = mdb_page_alloc(mc, 1, &mp)))
7413 offset = env->me_psize - olddata.mv_size;
7414 flags |= F_DUPDATA|F_SUBDATA;
7415 dummy.md_root = mp->mp_pgno;
7419 mp->mp_flags = fp_flags | P_DIRTY;
7420 mp->mp_pad = fp->mp_pad;
7421 mp->mp_lower = fp->mp_lower;
7422 mp->mp_upper = fp->mp_upper + offset;
7423 if (fp_flags & P_LEAF2) {
7424 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
7426 memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
7427 olddata.mv_size - fp->mp_upper - PAGEBASE);
7428 for (i=0; i<NUMKEYS(fp); i++)
7429 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
7437 mdb_node_del(mc, 0);
7441 /* LMDB passes F_SUBDATA in 'flags' to write a DB record */
7442 if ((leaf->mn_flags ^ flags) & F_SUBDATA)
7443 return MDB_INCOMPATIBLE;
7444 /* overflow page overwrites need special handling */
7445 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7448 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
7450 memcpy(&pg, olddata.mv_data, sizeof(pg));
7451 if ((rc2 = mdb_page_get(mc, pg, &omp, &level)) != 0)
7453 ovpages = omp->mp_pages;
7455 /* Is the ov page large enough? */
7456 if (ovpages >= dpages) {
7457 if (!(omp->mp_flags & P_DIRTY) &&
7458 (level || (env->me_flags & MDB_WRITEMAP)))
7460 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
7463 level = 0; /* dirty in this txn or clean */
7466 if (omp->mp_flags & P_DIRTY) {
7467 /* yes, overwrite it. Note in this case we don't
7468 * bother to try shrinking the page if the new data
7469 * is smaller than the overflow threshold.
7472 /* It is writable only in a parent txn */
7473 size_t sz = (size_t) env->me_psize * ovpages, off;
7474 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
7480 /* Note - this page is already counted in parent's dirty_room */
7481 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
7482 mdb_cassert(mc, rc2 == 0);
7483 /* Currently we make the page look as with put() in the
7484 * parent txn, in case the user peeks at MDB_RESERVEd
7485 * or unused parts. Some users treat ovpages specially.
7487 if (!(flags & MDB_RESERVE)) {
7488 /* Skip the part where LMDB will put *data.
7489 * Copy end of page, adjusting alignment so
7490 * compiler may copy words instead of bytes.
7492 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
7493 memcpy((size_t *)((char *)np + off),
7494 (size_t *)((char *)omp + off), sz - off);
7497 memcpy(np, omp, sz); /* Copy beginning of page */
7500 SETDSZ(leaf, data->mv_size);
7501 if (F_ISSET(flags, MDB_RESERVE))
7502 data->mv_data = METADATA(omp);
7504 memcpy(METADATA(omp), data->mv_data, data->mv_size);
7508 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
7510 } else if (data->mv_size == olddata.mv_size) {
7511 /* same size, just replace it. Note that we could
7512 * also reuse this node if the new data is smaller,
7513 * but instead we opt to shrink the node in that case.
7515 if (F_ISSET(flags, MDB_RESERVE))
7516 data->mv_data = olddata.mv_data;
7517 else if (!(mc->mc_flags & C_SUB))
7518 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
7520 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
7525 mdb_node_del(mc, 0);
7531 nflags = flags & NODE_ADD_FLAGS;
7532 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
7533 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
7534 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
7535 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
7537 nflags |= MDB_SPLIT_REPLACE;
7538 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
7540 /* There is room already in this leaf page. */
7541 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
7543 /* Adjust other cursors pointing to mp */
7544 MDB_cursor *m2, *m3;
7545 MDB_dbi dbi = mc->mc_dbi;
7546 unsigned i = mc->mc_top;
7547 MDB_page *mp = mc->mc_pg[i];
7549 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7550 if (mc->mc_flags & C_SUB)
7551 m3 = &m2->mc_xcursor->mx_cursor;
7554 if (m3 == mc || m3->mc_snum < mc->mc_snum || m3->mc_pg[i] != mp) continue;
7555 if (m3->mc_ki[i] >= mc->mc_ki[i] && insert_key) {
7558 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
7559 MDB_node *n2 = NODEPTR(mp, m3->mc_ki[i]);
7560 if ((n2->mn_flags & (F_SUBDATA|F_DUPDATA)) == F_DUPDATA)
7561 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
7567 if (rc == MDB_SUCCESS) {
7568 /* Now store the actual data in the child DB. Note that we're
7569 * storing the user data in the keys field, so there are strict
7570 * size limits on dupdata. The actual data fields of the child
7571 * DB are all zero size.
7574 int xflags, new_dupdata;
7579 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7580 if (flags & MDB_CURRENT) {
7581 xflags = MDB_CURRENT|MDB_NOSPILL;
7583 mdb_xcursor_init1(mc, leaf);
7584 xflags = (flags & MDB_NODUPDATA) ?
7585 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
7588 mc->mc_xcursor->mx_cursor.mc_pg[0] = sub_root;
7589 new_dupdata = (int)dkey.mv_size;
7590 /* converted, write the original data first */
7592 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
7595 /* we've done our job */
7598 if (!(leaf->mn_flags & F_SUBDATA) || sub_root) {
7599 /* Adjust other cursors pointing to mp */
7601 MDB_xcursor *mx = mc->mc_xcursor;
7602 unsigned i = mc->mc_top;
7603 MDB_page *mp = mc->mc_pg[i];
7604 int nkeys = NUMKEYS(mp);
7606 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
7607 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
7608 if (!(m2->mc_flags & C_INITIALIZED)) continue;
7609 if (m2->mc_pg[i] == mp) {
7610 if (m2->mc_ki[i] == mc->mc_ki[i]) {
7611 mdb_xcursor_init2(m2, mx, new_dupdata);
7612 } else if (!insert_key && m2->mc_ki[i] < nkeys) {
7613 MDB_node *n2 = NODEPTR(mp, m2->mc_ki[i]);
7614 if ((n2->mn_flags & (F_SUBDATA|F_DUPDATA)) == F_DUPDATA)
7615 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
7620 ecount = mc->mc_xcursor->mx_db.md_entries;
7621 if (flags & MDB_APPENDDUP)
7622 xflags |= MDB_APPEND;
7623 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
7624 if (flags & F_SUBDATA) {
7625 void *db = NODEDATA(leaf);
7626 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
7628 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
7630 /* Increment count unless we just replaced an existing item. */
7632 mc->mc_db->md_entries++;
7634 /* Invalidate txn if we created an empty sub-DB */
7637 /* If we succeeded and the key didn't exist before,
7638 * make sure the cursor is marked valid.
7640 mc->mc_flags |= C_INITIALIZED;
7642 if (flags & MDB_MULTIPLE) {
7645 /* let caller know how many succeeded, if any */
7646 data[1].mv_size = mcount;
7647 if (mcount < dcount) {
7648 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
7649 insert_key = insert_data = 0;
7656 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
7659 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7664 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
7670 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
7671 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7673 if (!(mc->mc_flags & C_INITIALIZED))
7676 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
7677 return MDB_NOTFOUND;
7679 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
7682 rc = mdb_cursor_touch(mc);
7686 mp = mc->mc_pg[mc->mc_top];
7689 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7691 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7692 if (flags & MDB_NODUPDATA) {
7693 /* mdb_cursor_del0() will subtract the final entry */
7694 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
7695 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
7697 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
7698 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
7700 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
7703 /* If sub-DB still has entries, we're done */
7704 if (mc->mc_xcursor->mx_db.md_entries) {
7705 if (leaf->mn_flags & F_SUBDATA) {
7706 /* update subDB info */
7707 void *db = NODEDATA(leaf);
7708 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
7711 /* shrink fake page */
7712 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
7713 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7714 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
7715 /* fix other sub-DB cursors pointed at fake pages on this page */
7716 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
7717 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
7718 if (!(m2->mc_flags & C_INITIALIZED)) continue;
7719 if (m2->mc_pg[mc->mc_top] == mp) {
7720 if (m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top]) {
7721 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
7723 MDB_node *n2 = NODEPTR(mp, m2->mc_ki[mc->mc_top]);
7724 if (!(n2->mn_flags & F_SUBDATA))
7725 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
7730 mc->mc_db->md_entries--;
7733 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
7735 /* otherwise fall thru and delete the sub-DB */
7738 if (leaf->mn_flags & F_SUBDATA) {
7739 /* add all the child DB's pages to the free list */
7740 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
7745 /* LMDB passes F_SUBDATA in 'flags' to delete a DB record */
7746 else if ((leaf->mn_flags ^ flags) & F_SUBDATA) {
7747 rc = MDB_INCOMPATIBLE;
7751 /* add overflow pages to free list */
7752 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7756 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
7757 if ((rc = mdb_page_get(mc, pg, &omp, NULL)) ||
7758 (rc = mdb_ovpage_free(mc, omp)))
7763 return mdb_cursor_del0(mc);
7766 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7770 /** Allocate and initialize new pages for a database.
7771 * @param[in] mc a cursor on the database being added to.
7772 * @param[in] flags flags defining what type of page is being allocated.
7773 * @param[in] num the number of pages to allocate. This is usually 1,
7774 * unless allocating overflow pages for a large record.
7775 * @param[out] mp Address of a page, or NULL on failure.
7776 * @return 0 on success, non-zero on failure.
7779 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
7784 if ((rc = mdb_page_alloc(mc, num, &np)))
7786 DPRINTF(("allocated new mpage %"Y"u, page size %u",
7787 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
7788 np->mp_flags = flags | P_DIRTY;
7789 np->mp_lower = (PAGEHDRSZ-PAGEBASE);
7790 np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
7793 mc->mc_db->md_branch_pages++;
7794 else if (IS_LEAF(np))
7795 mc->mc_db->md_leaf_pages++;
7796 else if (IS_OVERFLOW(np)) {
7797 mc->mc_db->md_overflow_pages += num;
7805 /** Calculate the size of a leaf node.
7806 * The size depends on the environment's page size; if a data item
7807 * is too large it will be put onto an overflow page and the node
7808 * size will only include the key and not the data. Sizes are always
7809 * rounded up to an even number of bytes, to guarantee 2-byte alignment
7810 * of the #MDB_node headers.
7811 * @param[in] env The environment handle.
7812 * @param[in] key The key for the node.
7813 * @param[in] data The data for the node.
7814 * @return The number of bytes needed to store the node.
7817 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
7821 sz = LEAFSIZE(key, data);
7822 if (sz > env->me_nodemax) {
7823 /* put on overflow page */
7824 sz -= data->mv_size - sizeof(pgno_t);
7827 return EVEN(sz + sizeof(indx_t));
7830 /** Calculate the size of a branch node.
7831 * The size should depend on the environment's page size but since
7832 * we currently don't support spilling large keys onto overflow
7833 * pages, it's simply the size of the #MDB_node header plus the
7834 * size of the key. Sizes are always rounded up to an even number
7835 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
7836 * @param[in] env The environment handle.
7837 * @param[in] key The key for the node.
7838 * @return The number of bytes needed to store the node.
7841 mdb_branch_size(MDB_env *env, MDB_val *key)
7846 if (sz > env->me_nodemax) {
7847 /* put on overflow page */
7848 /* not implemented */
7849 /* sz -= key->size - sizeof(pgno_t); */
7852 return sz + sizeof(indx_t);
7855 /** Add a node to the page pointed to by the cursor.
7856 * @param[in] mc The cursor for this operation.
7857 * @param[in] indx The index on the page where the new node should be added.
7858 * @param[in] key The key for the new node.
7859 * @param[in] data The data for the new node, if any.
7860 * @param[in] pgno The page number, if adding a branch node.
7861 * @param[in] flags Flags for the node.
7862 * @return 0 on success, non-zero on failure. Possible errors are:
7864 * <li>ENOMEM - failed to allocate overflow pages for the node.
7865 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
7866 * should never happen since all callers already calculate the
7867 * page's free space before calling this function.
7871 mdb_node_add(MDB_cursor *mc, indx_t indx,
7872 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
7875 size_t node_size = NODESIZE;
7879 MDB_page *mp = mc->mc_pg[mc->mc_top];
7880 MDB_page *ofp = NULL; /* overflow page */
7884 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
7886 DPRINTF(("add to %s %spage %"Y"u index %i, data size %"Z"u key size %"Z"u [%s]",
7887 IS_LEAF(mp) ? "leaf" : "branch",
7888 IS_SUBP(mp) ? "sub-" : "",
7889 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
7890 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
7893 /* Move higher keys up one slot. */
7894 int ksize = mc->mc_db->md_pad, dif;
7895 char *ptr = LEAF2KEY(mp, indx, ksize);
7896 dif = NUMKEYS(mp) - indx;
7898 memmove(ptr+ksize, ptr, dif*ksize);
7899 /* insert new key */
7900 memcpy(ptr, key->mv_data, ksize);
7902 /* Just using these for counting */
7903 mp->mp_lower += sizeof(indx_t);
7904 mp->mp_upper -= ksize - sizeof(indx_t);
7908 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
7910 node_size += key->mv_size;
7912 mdb_cassert(mc, key && data);
7913 if (F_ISSET(flags, F_BIGDATA)) {
7914 /* Data already on overflow page. */
7915 node_size += sizeof(pgno_t);
7916 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
7917 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
7919 /* Put data on overflow page. */
7920 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
7921 data->mv_size, node_size+data->mv_size));
7922 node_size = EVEN(node_size + sizeof(pgno_t));
7923 if ((ssize_t)node_size > room)
7925 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
7927 DPRINTF(("allocated overflow page %"Y"u", ofp->mp_pgno));
7931 node_size += data->mv_size;
7934 node_size = EVEN(node_size);
7935 if ((ssize_t)node_size > room)
7939 /* Move higher pointers up one slot. */
7940 for (i = NUMKEYS(mp); i > indx; i--)
7941 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
7943 /* Adjust free space offsets. */
7944 ofs = mp->mp_upper - node_size;
7945 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
7946 mp->mp_ptrs[indx] = ofs;
7948 mp->mp_lower += sizeof(indx_t);
7950 /* Write the node data. */
7951 node = NODEPTR(mp, indx);
7952 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
7953 node->mn_flags = flags;
7955 SETDSZ(node,data->mv_size);
7960 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7963 ndata = NODEDATA(node);
7965 if (F_ISSET(flags, F_BIGDATA))
7966 memcpy(ndata, data->mv_data, sizeof(pgno_t));
7967 else if (F_ISSET(flags, MDB_RESERVE))
7968 data->mv_data = ndata;
7970 memcpy(ndata, data->mv_data, data->mv_size);
7972 memcpy(ndata, &ofp->mp_pgno, sizeof(pgno_t));
7973 ndata = METADATA(ofp);
7974 if (F_ISSET(flags, MDB_RESERVE))
7975 data->mv_data = ndata;
7977 memcpy(ndata, data->mv_data, data->mv_size);
7984 DPRINTF(("not enough room in page %"Y"u, got %u ptrs",
7985 mdb_dbg_pgno(mp), NUMKEYS(mp)));
7986 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
7987 DPRINTF(("node size = %"Z"u", node_size));
7988 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7989 return MDB_PAGE_FULL;
7992 /** Delete the specified node from a page.
7993 * @param[in] mc Cursor pointing to the node to delete.
7994 * @param[in] ksize The size of a node. Only used if the page is
7995 * part of a #MDB_DUPFIXED database.
7998 mdb_node_del(MDB_cursor *mc, int ksize)
8000 MDB_page *mp = mc->mc_pg[mc->mc_top];
8001 indx_t indx = mc->mc_ki[mc->mc_top];
8003 indx_t i, j, numkeys, ptr;
8007 DPRINTF(("delete node %u on %s page %"Y"u", indx,
8008 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
8009 numkeys = NUMKEYS(mp);
8010 mdb_cassert(mc, indx < numkeys);
8013 int x = numkeys - 1 - indx;
8014 base = LEAF2KEY(mp, indx, ksize);
8016 memmove(base, base + ksize, x * ksize);
8017 mp->mp_lower -= sizeof(indx_t);
8018 mp->mp_upper += ksize - sizeof(indx_t);
8022 node = NODEPTR(mp, indx);
8023 sz = NODESIZE + node->mn_ksize;
8025 if (F_ISSET(node->mn_flags, F_BIGDATA))
8026 sz += sizeof(pgno_t);
8028 sz += NODEDSZ(node);
8032 ptr = mp->mp_ptrs[indx];
8033 for (i = j = 0; i < numkeys; i++) {
8035 mp->mp_ptrs[j] = mp->mp_ptrs[i];
8036 if (mp->mp_ptrs[i] < ptr)
8037 mp->mp_ptrs[j] += sz;
8042 base = (char *)mp + mp->mp_upper + PAGEBASE;
8043 memmove(base + sz, base, ptr - mp->mp_upper);
8045 mp->mp_lower -= sizeof(indx_t);
8049 /** Compact the main page after deleting a node on a subpage.
8050 * @param[in] mp The main page to operate on.
8051 * @param[in] indx The index of the subpage on the main page.
8054 mdb_node_shrink(MDB_page *mp, indx_t indx)
8059 indx_t delta, nsize, len, ptr;
8062 node = NODEPTR(mp, indx);
8063 sp = (MDB_page *)NODEDATA(node);
8064 delta = SIZELEFT(sp);
8065 nsize = NODEDSZ(node) - delta;
8067 /* Prepare to shift upward, set len = length(subpage part to shift) */
8071 return; /* do not make the node uneven-sized */
8073 xp = (MDB_page *)((char *)sp + delta); /* destination subpage */
8074 for (i = NUMKEYS(sp); --i >= 0; )
8075 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
8078 sp->mp_upper = sp->mp_lower;
8079 COPY_PGNO(sp->mp_pgno, mp->mp_pgno);
8080 SETDSZ(node, nsize);
8082 /* Shift <lower nodes...initial part of subpage> upward */
8083 base = (char *)mp + mp->mp_upper + PAGEBASE;
8084 memmove(base + delta, base, (char *)sp + len - base);
8086 ptr = mp->mp_ptrs[indx];
8087 for (i = NUMKEYS(mp); --i >= 0; ) {
8088 if (mp->mp_ptrs[i] <= ptr)
8089 mp->mp_ptrs[i] += delta;
8091 mp->mp_upper += delta;
8094 /** Initial setup of a sorted-dups cursor.
8095 * Sorted duplicates are implemented as a sub-database for the given key.
8096 * The duplicate data items are actually keys of the sub-database.
8097 * Operations on the duplicate data items are performed using a sub-cursor
8098 * initialized when the sub-database is first accessed. This function does
8099 * the preliminary setup of the sub-cursor, filling in the fields that
8100 * depend only on the parent DB.
8101 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
8104 mdb_xcursor_init0(MDB_cursor *mc)
8106 MDB_xcursor *mx = mc->mc_xcursor;
8108 mx->mx_cursor.mc_xcursor = NULL;
8109 mx->mx_cursor.mc_txn = mc->mc_txn;
8110 mx->mx_cursor.mc_db = &mx->mx_db;
8111 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
8112 mx->mx_cursor.mc_dbi = mc->mc_dbi;
8113 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
8114 mx->mx_cursor.mc_snum = 0;
8115 mx->mx_cursor.mc_top = 0;
8117 mx->mx_cursor.mc_ovpg = 0;
8119 mx->mx_cursor.mc_flags = C_SUB | (mc->mc_flags & (C_ORIG_RDONLY|C_WRITEMAP));
8120 mx->mx_dbx.md_name.mv_size = 0;
8121 mx->mx_dbx.md_name.mv_data = NULL;
8122 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
8123 mx->mx_dbx.md_dcmp = NULL;
8124 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
8127 /** Final setup of a sorted-dups cursor.
8128 * Sets up the fields that depend on the data from the main cursor.
8129 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
8130 * @param[in] node The data containing the #MDB_db record for the
8131 * sorted-dup database.
8134 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
8136 MDB_xcursor *mx = mc->mc_xcursor;
8138 mx->mx_cursor.mc_flags &= C_SUB|C_ORIG_RDONLY|C_WRITEMAP;
8139 if (node->mn_flags & F_SUBDATA) {
8140 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
8141 mx->mx_cursor.mc_pg[0] = 0;
8142 mx->mx_cursor.mc_snum = 0;
8143 mx->mx_cursor.mc_top = 0;
8145 MDB_page *fp = NODEDATA(node);
8146 mx->mx_db.md_pad = 0;
8147 mx->mx_db.md_flags = 0;
8148 mx->mx_db.md_depth = 1;
8149 mx->mx_db.md_branch_pages = 0;
8150 mx->mx_db.md_leaf_pages = 1;
8151 mx->mx_db.md_overflow_pages = 0;
8152 mx->mx_db.md_entries = NUMKEYS(fp);
8153 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
8154 mx->mx_cursor.mc_snum = 1;
8155 mx->mx_cursor.mc_top = 0;
8156 mx->mx_cursor.mc_flags |= C_INITIALIZED;
8157 mx->mx_cursor.mc_pg[0] = fp;
8158 mx->mx_cursor.mc_ki[0] = 0;
8159 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
8160 mx->mx_db.md_flags = MDB_DUPFIXED;
8161 mx->mx_db.md_pad = fp->mp_pad;
8162 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
8163 mx->mx_db.md_flags |= MDB_INTEGERKEY;
8166 DPRINTF(("Sub-db -%u root page %"Y"u", mx->mx_cursor.mc_dbi,
8167 mx->mx_db.md_root));
8168 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
8169 #if UINT_MAX < SIZE_MAX || defined(MDB_VL32)
8170 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(mdb_size_t))
8171 mx->mx_dbx.md_cmp = mdb_cmp_clong;
8176 /** Fixup a sorted-dups cursor due to underlying update.
8177 * Sets up some fields that depend on the data from the main cursor.
8178 * Almost the same as init1, but skips initialization steps if the
8179 * xcursor had already been used.
8180 * @param[in] mc The main cursor whose sorted-dups cursor is to be fixed up.
8181 * @param[in] src_mx The xcursor of an up-to-date cursor.
8182 * @param[in] new_dupdata True if converting from a non-#F_DUPDATA item.
8185 mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int new_dupdata)
8187 MDB_xcursor *mx = mc->mc_xcursor;
8190 mx->mx_cursor.mc_snum = 1;
8191 mx->mx_cursor.mc_top = 0;
8192 mx->mx_cursor.mc_flags |= C_INITIALIZED;
8193 mx->mx_cursor.mc_ki[0] = 0;
8194 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
8195 #if UINT_MAX < SIZE_MAX
8196 mx->mx_dbx.md_cmp = src_mx->mx_dbx.md_cmp;
8198 } else if (!(mx->mx_cursor.mc_flags & C_INITIALIZED)) {
8201 mx->mx_db = src_mx->mx_db;
8202 mx->mx_cursor.mc_pg[0] = src_mx->mx_cursor.mc_pg[0];
8203 DPRINTF(("Sub-db -%u root page %"Y"u", mx->mx_cursor.mc_dbi,
8204 mx->mx_db.md_root));
8207 /** Initialize a cursor for a given transaction and database. */
8209 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
8212 mc->mc_backup = NULL;
8215 mc->mc_db = &txn->mt_dbs[dbi];
8216 mc->mc_dbx = &txn->mt_dbxs[dbi];
8217 mc->mc_dbflag = &txn->mt_dbflags[dbi];
8225 mc->mc_flags = txn->mt_flags & (C_ORIG_RDONLY|C_WRITEMAP);
8226 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
8227 mdb_tassert(txn, mx != NULL);
8228 mc->mc_xcursor = mx;
8229 mdb_xcursor_init0(mc);
8231 mc->mc_xcursor = NULL;
8233 if (*mc->mc_dbflag & DB_STALE) {
8234 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
8239 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
8242 size_t size = sizeof(MDB_cursor);
8244 if (!ret || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
8247 if (txn->mt_flags & MDB_TXN_BLOCKED)
8250 if (dbi == FREE_DBI && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
8253 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
8254 size += sizeof(MDB_xcursor);
8256 if ((mc = malloc(size)) != NULL) {
8257 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
8258 if (txn->mt_cursors) {
8259 mc->mc_next = txn->mt_cursors[dbi];
8260 txn->mt_cursors[dbi] = mc;
8261 mc->mc_flags |= C_UNTRACK;
8273 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
8275 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi, DB_VALID))
8278 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
8281 if (txn->mt_flags & MDB_TXN_BLOCKED)
8284 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
8288 /* Return the count of duplicate data items for the current key */
8290 mdb_cursor_count(MDB_cursor *mc, mdb_size_t *countp)
8294 if (mc == NULL || countp == NULL)
8297 if (mc->mc_xcursor == NULL)
8298 return MDB_INCOMPATIBLE;
8300 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
8303 if (!(mc->mc_flags & C_INITIALIZED))
8306 if (!mc->mc_snum || (mc->mc_flags & C_EOF))
8307 return MDB_NOTFOUND;
8309 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
8310 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
8313 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
8316 *countp = mc->mc_xcursor->mx_db.md_entries;
8322 mdb_cursor_close(MDB_cursor *mc)
8324 if (mc && !mc->mc_backup) {
8325 /* remove from txn, if tracked */
8326 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
8327 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
8328 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
8330 *prev = mc->mc_next;
8337 mdb_cursor_txn(MDB_cursor *mc)
8339 if (!mc) return NULL;
8344 mdb_cursor_dbi(MDB_cursor *mc)
8349 /** Replace the key for a branch node with a new key.
8350 * @param[in] mc Cursor pointing to the node to operate on.
8351 * @param[in] key The new key to use.
8352 * @return 0 on success, non-zero on failure.
8355 mdb_update_key(MDB_cursor *mc, MDB_val *key)
8361 int delta, ksize, oksize;
8362 indx_t ptr, i, numkeys, indx;
8365 indx = mc->mc_ki[mc->mc_top];
8366 mp = mc->mc_pg[mc->mc_top];
8367 node = NODEPTR(mp, indx);
8368 ptr = mp->mp_ptrs[indx];
8372 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
8373 k2.mv_data = NODEKEY(node);
8374 k2.mv_size = node->mn_ksize;
8375 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Y"u",
8377 mdb_dkey(&k2, kbuf2),
8383 /* Sizes must be 2-byte aligned. */
8384 ksize = EVEN(key->mv_size);
8385 oksize = EVEN(node->mn_ksize);
8386 delta = ksize - oksize;
8388 /* Shift node contents if EVEN(key length) changed. */
8390 if (delta > 0 && SIZELEFT(mp) < delta) {
8392 /* not enough space left, do a delete and split */
8393 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
8394 pgno = NODEPGNO(node);
8395 mdb_node_del(mc, 0);
8396 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
8399 numkeys = NUMKEYS(mp);
8400 for (i = 0; i < numkeys; i++) {
8401 if (mp->mp_ptrs[i] <= ptr)
8402 mp->mp_ptrs[i] -= delta;
8405 base = (char *)mp + mp->mp_upper + PAGEBASE;
8406 len = ptr - mp->mp_upper + NODESIZE;
8407 memmove(base - delta, base, len);
8408 mp->mp_upper -= delta;
8410 node = NODEPTR(mp, indx);
8413 /* But even if no shift was needed, update ksize */
8414 if (node->mn_ksize != key->mv_size)
8415 node->mn_ksize = key->mv_size;
8418 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
8424 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
8426 /** Perform \b act while tracking temporary cursor \b mn */
8427 #define WITH_CURSOR_TRACKING(mn, act) do { \
8428 MDB_cursor dummy, *tracked, **tp = &(mn).mc_txn->mt_cursors[mn.mc_dbi]; \
8429 if ((mn).mc_flags & C_SUB) { \
8430 dummy.mc_flags = C_INITIALIZED; \
8431 dummy.mc_xcursor = (MDB_xcursor *)&(mn); \
8436 tracked->mc_next = *tp; \
8439 *tp = tracked->mc_next; \
8442 /** Move a node from csrc to cdst.
8445 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft)
8452 unsigned short flags;
8456 /* Mark src and dst as dirty. */
8457 if ((rc = mdb_page_touch(csrc)) ||
8458 (rc = mdb_page_touch(cdst)))
8461 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8462 key.mv_size = csrc->mc_db->md_pad;
8463 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
8465 data.mv_data = NULL;
8469 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
8470 mdb_cassert(csrc, !((size_t)srcnode & 1));
8471 srcpg = NODEPGNO(srcnode);
8472 flags = srcnode->mn_flags;
8473 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
8474 unsigned int snum = csrc->mc_snum;
8476 /* must find the lowest key below src */
8477 rc = mdb_page_search_lowest(csrc);
8480 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8481 key.mv_size = csrc->mc_db->md_pad;
8482 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
8484 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
8485 key.mv_size = NODEKSZ(s2);
8486 key.mv_data = NODEKEY(s2);
8488 csrc->mc_snum = snum--;
8489 csrc->mc_top = snum;
8491 key.mv_size = NODEKSZ(srcnode);
8492 key.mv_data = NODEKEY(srcnode);
8494 data.mv_size = NODEDSZ(srcnode);
8495 data.mv_data = NODEDATA(srcnode);
8497 mn.mc_xcursor = NULL;
8498 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
8499 unsigned int snum = cdst->mc_snum;
8502 /* must find the lowest key below dst */
8503 mdb_cursor_copy(cdst, &mn);
8504 rc = mdb_page_search_lowest(&mn);
8507 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
8508 bkey.mv_size = mn.mc_db->md_pad;
8509 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
8511 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
8512 bkey.mv_size = NODEKSZ(s2);
8513 bkey.mv_data = NODEKEY(s2);
8515 mn.mc_snum = snum--;
8518 rc = mdb_update_key(&mn, &bkey);
8523 DPRINTF(("moving %s node %u [%s] on page %"Y"u to node %u on page %"Y"u",
8524 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
8525 csrc->mc_ki[csrc->mc_top],
8527 csrc->mc_pg[csrc->mc_top]->mp_pgno,
8528 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
8530 /* Add the node to the destination page.
8532 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
8533 if (rc != MDB_SUCCESS)
8536 /* Delete the node from the source page.
8538 mdb_node_del(csrc, key.mv_size);
8541 /* Adjust other cursors pointing to mp */
8542 MDB_cursor *m2, *m3;
8543 MDB_dbi dbi = csrc->mc_dbi;
8544 MDB_page *mpd, *mps;
8546 mps = csrc->mc_pg[csrc->mc_top];
8547 /* If we're adding on the left, bump others up */
8549 mpd = cdst->mc_pg[csrc->mc_top];
8550 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8551 if (csrc->mc_flags & C_SUB)
8552 m3 = &m2->mc_xcursor->mx_cursor;
8555 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
8558 m3->mc_pg[csrc->mc_top] == mpd &&
8559 m3->mc_ki[csrc->mc_top] >= cdst->mc_ki[csrc->mc_top]) {
8560 m3->mc_ki[csrc->mc_top]++;
8563 m3->mc_pg[csrc->mc_top] == mps &&
8564 m3->mc_ki[csrc->mc_top] == csrc->mc_ki[csrc->mc_top]) {
8565 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
8566 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
8567 m3->mc_ki[csrc->mc_top-1]++;
8569 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) &&
8571 MDB_node *node = NODEPTR(m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
8572 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
8573 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
8577 /* Adding on the right, bump others down */
8579 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8580 if (csrc->mc_flags & C_SUB)
8581 m3 = &m2->mc_xcursor->mx_cursor;
8584 if (m3 == csrc) continue;
8585 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
8587 if (m3->mc_pg[csrc->mc_top] == mps) {
8588 if (!m3->mc_ki[csrc->mc_top]) {
8589 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
8590 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
8591 m3->mc_ki[csrc->mc_top-1]--;
8593 m3->mc_ki[csrc->mc_top]--;
8595 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) &&
8597 MDB_node *node = NODEPTR(m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
8598 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
8599 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
8606 /* Update the parent separators.
8608 if (csrc->mc_ki[csrc->mc_top] == 0) {
8609 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
8610 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8611 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
8613 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
8614 key.mv_size = NODEKSZ(srcnode);
8615 key.mv_data = NODEKEY(srcnode);
8617 DPRINTF(("update separator for source page %"Y"u to [%s]",
8618 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
8619 mdb_cursor_copy(csrc, &mn);
8622 /* We want mdb_rebalance to find mn when doing fixups */
8623 WITH_CURSOR_TRACKING(mn,
8624 rc = mdb_update_key(&mn, &key));
8628 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
8630 indx_t ix = csrc->mc_ki[csrc->mc_top];
8631 nullkey.mv_size = 0;
8632 csrc->mc_ki[csrc->mc_top] = 0;
8633 rc = mdb_update_key(csrc, &nullkey);
8634 csrc->mc_ki[csrc->mc_top] = ix;
8635 mdb_cassert(csrc, rc == MDB_SUCCESS);
8639 if (cdst->mc_ki[cdst->mc_top] == 0) {
8640 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
8641 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8642 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
8644 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
8645 key.mv_size = NODEKSZ(srcnode);
8646 key.mv_data = NODEKEY(srcnode);
8648 DPRINTF(("update separator for destination page %"Y"u to [%s]",
8649 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
8650 mdb_cursor_copy(cdst, &mn);
8653 /* We want mdb_rebalance to find mn when doing fixups */
8654 WITH_CURSOR_TRACKING(mn,
8655 rc = mdb_update_key(&mn, &key));
8659 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
8661 indx_t ix = cdst->mc_ki[cdst->mc_top];
8662 nullkey.mv_size = 0;
8663 cdst->mc_ki[cdst->mc_top] = 0;
8664 rc = mdb_update_key(cdst, &nullkey);
8665 cdst->mc_ki[cdst->mc_top] = ix;
8666 mdb_cassert(cdst, rc == MDB_SUCCESS);
8673 /** Merge one page into another.
8674 * The nodes from the page pointed to by \b csrc will
8675 * be copied to the page pointed to by \b cdst and then
8676 * the \b csrc page will be freed.
8677 * @param[in] csrc Cursor pointing to the source page.
8678 * @param[in] cdst Cursor pointing to the destination page.
8679 * @return 0 on success, non-zero on failure.
8682 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
8684 MDB_page *psrc, *pdst;
8691 psrc = csrc->mc_pg[csrc->mc_top];
8692 pdst = cdst->mc_pg[cdst->mc_top];
8694 DPRINTF(("merging page %"Y"u into %"Y"u", psrc->mp_pgno, pdst->mp_pgno));
8696 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
8697 mdb_cassert(csrc, cdst->mc_snum > 1);
8699 /* Mark dst as dirty. */
8700 if ((rc = mdb_page_touch(cdst)))
8703 /* get dst page again now that we've touched it. */
8704 pdst = cdst->mc_pg[cdst->mc_top];
8706 /* Move all nodes from src to dst.
8708 j = nkeys = NUMKEYS(pdst);
8709 if (IS_LEAF2(psrc)) {
8710 key.mv_size = csrc->mc_db->md_pad;
8711 key.mv_data = METADATA(psrc);
8712 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
8713 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
8714 if (rc != MDB_SUCCESS)
8716 key.mv_data = (char *)key.mv_data + key.mv_size;
8719 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
8720 srcnode = NODEPTR(psrc, i);
8721 if (i == 0 && IS_BRANCH(psrc)) {
8724 mdb_cursor_copy(csrc, &mn);
8725 mn.mc_xcursor = NULL;
8726 /* must find the lowest key below src */
8727 rc = mdb_page_search_lowest(&mn);
8730 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
8731 key.mv_size = mn.mc_db->md_pad;
8732 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
8734 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
8735 key.mv_size = NODEKSZ(s2);
8736 key.mv_data = NODEKEY(s2);
8739 key.mv_size = srcnode->mn_ksize;
8740 key.mv_data = NODEKEY(srcnode);
8743 data.mv_size = NODEDSZ(srcnode);
8744 data.mv_data = NODEDATA(srcnode);
8745 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
8746 if (rc != MDB_SUCCESS)
8751 DPRINTF(("dst page %"Y"u now has %u keys (%.1f%% filled)",
8752 pdst->mp_pgno, NUMKEYS(pdst),
8753 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
8755 /* Unlink the src page from parent and add to free list.
8758 mdb_node_del(csrc, 0);
8759 if (csrc->mc_ki[csrc->mc_top] == 0) {
8761 rc = mdb_update_key(csrc, &key);
8769 psrc = csrc->mc_pg[csrc->mc_top];
8770 /* If not operating on FreeDB, allow this page to be reused
8771 * in this txn. Otherwise just add to free list.
8773 rc = mdb_page_loose(csrc, psrc);
8777 csrc->mc_db->md_leaf_pages--;
8779 csrc->mc_db->md_branch_pages--;
8781 /* Adjust other cursors pointing to mp */
8782 MDB_cursor *m2, *m3;
8783 MDB_dbi dbi = csrc->mc_dbi;
8784 unsigned int top = csrc->mc_top;
8786 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8787 if (csrc->mc_flags & C_SUB)
8788 m3 = &m2->mc_xcursor->mx_cursor;
8791 if (m3 == csrc) continue;
8792 if (m3->mc_snum < csrc->mc_snum) continue;
8793 if (m3->mc_pg[top] == psrc) {
8794 m3->mc_pg[top] = pdst;
8795 m3->mc_ki[top] += nkeys;
8796 m3->mc_ki[top-1] = cdst->mc_ki[top-1];
8797 } else if (m3->mc_pg[top-1] == csrc->mc_pg[top-1] &&
8798 m3->mc_ki[top-1] > csrc->mc_ki[top-1]) {
8801 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) &&
8803 MDB_node *node = NODEPTR(m3->mc_pg[top], m3->mc_ki[top]);
8804 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
8805 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
8810 unsigned int snum = cdst->mc_snum;
8811 uint16_t depth = cdst->mc_db->md_depth;
8812 mdb_cursor_pop(cdst);
8813 rc = mdb_rebalance(cdst);
8814 /* Did the tree height change? */
8815 if (depth != cdst->mc_db->md_depth)
8816 snum += cdst->mc_db->md_depth - depth;
8817 cdst->mc_snum = snum;
8818 cdst->mc_top = snum-1;
8823 /** Copy the contents of a cursor.
8824 * @param[in] csrc The cursor to copy from.
8825 * @param[out] cdst The cursor to copy to.
8828 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
8832 cdst->mc_txn = csrc->mc_txn;
8833 cdst->mc_dbi = csrc->mc_dbi;
8834 cdst->mc_db = csrc->mc_db;
8835 cdst->mc_dbx = csrc->mc_dbx;
8836 cdst->mc_snum = csrc->mc_snum;
8837 cdst->mc_top = csrc->mc_top;
8838 cdst->mc_flags = csrc->mc_flags;
8840 cdst->mc_ovpg = csrc->mc_ovpg;
8843 for (i=0; i<csrc->mc_snum; i++) {
8844 cdst->mc_pg[i] = csrc->mc_pg[i];
8845 cdst->mc_ki[i] = csrc->mc_ki[i];
8849 /** Rebalance the tree after a delete operation.
8850 * @param[in] mc Cursor pointing to the page where rebalancing
8852 * @return 0 on success, non-zero on failure.
8855 mdb_rebalance(MDB_cursor *mc)
8859 unsigned int ptop, minkeys, thresh;
8863 if (IS_BRANCH(mc->mc_pg[mc->mc_top])) {
8868 thresh = FILL_THRESHOLD;
8870 DPRINTF(("rebalancing %s page %"Y"u (has %u keys, %.1f%% full)",
8871 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
8872 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
8873 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
8875 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= thresh &&
8876 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
8877 DPRINTF(("no need to rebalance page %"Y"u, above fill threshold",
8878 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
8882 if (mc->mc_snum < 2) {
8883 MDB_page *mp = mc->mc_pg[0];
8885 DPUTS("Can't rebalance a subpage, ignoring");
8888 if (NUMKEYS(mp) == 0) {
8889 DPUTS("tree is completely empty");
8890 mc->mc_db->md_root = P_INVALID;
8891 mc->mc_db->md_depth = 0;
8892 mc->mc_db->md_leaf_pages = 0;
8893 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
8896 /* Adjust cursors pointing to mp */
8899 mc->mc_flags &= ~C_INITIALIZED;
8901 MDB_cursor *m2, *m3;
8902 MDB_dbi dbi = mc->mc_dbi;
8904 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8905 if (mc->mc_flags & C_SUB)
8906 m3 = &m2->mc_xcursor->mx_cursor;
8909 if (!(m3->mc_flags & C_INITIALIZED) || (m3->mc_snum < mc->mc_snum))
8911 if (m3->mc_pg[0] == mp) {
8914 m3->mc_flags &= ~C_INITIALIZED;
8918 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
8920 DPUTS("collapsing root page!");
8921 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
8924 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
8925 rc = mdb_page_get(mc, mc->mc_db->md_root, &mc->mc_pg[0], NULL);
8928 mc->mc_db->md_depth--;
8929 mc->mc_db->md_branch_pages--;
8930 mc->mc_ki[0] = mc->mc_ki[1];
8931 for (i = 1; i<mc->mc_db->md_depth; i++) {
8932 mc->mc_pg[i] = mc->mc_pg[i+1];
8933 mc->mc_ki[i] = mc->mc_ki[i+1];
8936 /* Adjust other cursors pointing to mp */
8937 MDB_cursor *m2, *m3;
8938 MDB_dbi dbi = mc->mc_dbi;
8940 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8941 if (mc->mc_flags & C_SUB)
8942 m3 = &m2->mc_xcursor->mx_cursor;
8945 if (m3 == mc) continue;
8946 if (!(m3->mc_flags & C_INITIALIZED))
8948 if (m3->mc_pg[0] == mp) {
8949 for (i=0; i<mc->mc_db->md_depth; i++) {
8950 m3->mc_pg[i] = m3->mc_pg[i+1];
8951 m3->mc_ki[i] = m3->mc_ki[i+1];
8959 DPUTS("root page doesn't need rebalancing");
8963 /* The parent (branch page) must have at least 2 pointers,
8964 * otherwise the tree is invalid.
8966 ptop = mc->mc_top-1;
8967 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
8969 /* Leaf page fill factor is below the threshold.
8970 * Try to move keys from left or right neighbor, or
8971 * merge with a neighbor page.
8976 mdb_cursor_copy(mc, &mn);
8977 mn.mc_xcursor = NULL;
8979 oldki = mc->mc_ki[mc->mc_top];
8980 if (mc->mc_ki[ptop] == 0) {
8981 /* We're the leftmost leaf in our parent.
8983 DPUTS("reading right neighbor");
8985 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
8986 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
8989 mn.mc_ki[mn.mc_top] = 0;
8990 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
8993 /* There is at least one neighbor to the left.
8995 DPUTS("reading left neighbor");
8997 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
8998 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
9001 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
9002 mc->mc_ki[mc->mc_top] = 0;
9006 DPRINTF(("found neighbor page %"Y"u (%u keys, %.1f%% full)",
9007 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
9008 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
9010 /* If the neighbor page is above threshold and has enough keys,
9011 * move one key from it. Otherwise we should try to merge them.
9012 * (A branch page must never have less than 2 keys.)
9014 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= thresh && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
9015 rc = mdb_node_move(&mn, mc, fromleft);
9017 /* if we inserted on left, bump position up */
9022 rc = mdb_page_merge(&mn, mc);
9024 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
9025 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
9026 /* We want mdb_rebalance to find mn when doing fixups */
9027 WITH_CURSOR_TRACKING(mn,
9028 rc = mdb_page_merge(mc, &mn));
9029 mdb_cursor_copy(&mn, mc);
9031 mc->mc_flags &= ~C_EOF;
9033 mc->mc_ki[mc->mc_top] = oldki;
9037 /** Complete a delete operation started by #mdb_cursor_del(). */
9039 mdb_cursor_del0(MDB_cursor *mc)
9045 MDB_cursor *m2, *m3;
9046 MDB_dbi dbi = mc->mc_dbi;
9048 ki = mc->mc_ki[mc->mc_top];
9049 mp = mc->mc_pg[mc->mc_top];
9050 mdb_node_del(mc, mc->mc_db->md_pad);
9051 mc->mc_db->md_entries--;
9053 /* Adjust other cursors pointing to mp */
9054 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9055 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
9056 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9058 if (m3 == mc || m3->mc_snum < mc->mc_snum)
9060 if (m3->mc_pg[mc->mc_top] == mp) {
9061 if (m3->mc_ki[mc->mc_top] == ki) {
9062 m3->mc_flags |= C_DEL;
9063 } else if (m3->mc_ki[mc->mc_top] > ki) {
9064 m3->mc_ki[mc->mc_top]--;
9066 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
9067 MDB_node *node = NODEPTR(m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
9068 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
9069 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
9074 rc = mdb_rebalance(mc);
9076 if (rc == MDB_SUCCESS) {
9077 /* DB is totally empty now, just bail out.
9078 * Other cursors adjustments were already done
9079 * by mdb_rebalance and aren't needed here.
9084 mp = mc->mc_pg[mc->mc_top];
9085 nkeys = NUMKEYS(mp);
9087 /* Adjust other cursors pointing to mp */
9088 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
9089 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
9090 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9092 if (m3->mc_snum < mc->mc_snum)
9094 if (m3->mc_pg[mc->mc_top] == mp) {
9095 /* if m3 points past last node in page, find next sibling */
9096 if (m3->mc_ki[mc->mc_top] >= mc->mc_ki[mc->mc_top]) {
9097 if (m3->mc_ki[mc->mc_top] >= nkeys) {
9098 rc = mdb_cursor_sibling(m3, 1);
9099 if (rc == MDB_NOTFOUND) {
9100 m3->mc_flags |= C_EOF;
9105 if (mc->mc_db->md_flags & MDB_DUPSORT) {
9106 MDB_node *node = NODEPTR(m3->mc_pg[m3->mc_top], m3->mc_ki[m3->mc_top]);
9107 if (node->mn_flags & F_DUPDATA) {
9108 mdb_xcursor_init1(m3, node);
9109 m3->mc_xcursor->mx_cursor.mc_flags |= C_DEL;
9115 mc->mc_flags |= C_DEL;
9119 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
9124 mdb_del(MDB_txn *txn, MDB_dbi dbi,
9125 MDB_val *key, MDB_val *data)
9127 if (!key || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9130 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
9131 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
9133 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
9134 /* must ignore any data */
9138 return mdb_del0(txn, dbi, key, data, 0);
9142 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
9143 MDB_val *key, MDB_val *data, unsigned flags)
9148 MDB_val rdata, *xdata;
9152 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
9154 mdb_cursor_init(&mc, txn, dbi, &mx);
9163 flags |= MDB_NODUPDATA;
9165 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
9167 /* let mdb_page_split know about this cursor if needed:
9168 * delete will trigger a rebalance; if it needs to move
9169 * a node from one page to another, it will have to
9170 * update the parent's separator key(s). If the new sepkey
9171 * is larger than the current one, the parent page may
9172 * run out of space, triggering a split. We need this
9173 * cursor to be consistent until the end of the rebalance.
9175 mc.mc_flags |= C_UNTRACK;
9176 mc.mc_next = txn->mt_cursors[dbi];
9177 txn->mt_cursors[dbi] = &mc;
9178 rc = mdb_cursor_del(&mc, flags);
9179 txn->mt_cursors[dbi] = mc.mc_next;
9184 /** Split a page and insert a new node.
9185 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
9186 * The cursor will be updated to point to the actual page and index where
9187 * the node got inserted after the split.
9188 * @param[in] newkey The key for the newly inserted node.
9189 * @param[in] newdata The data for the newly inserted node.
9190 * @param[in] newpgno The page number, if the new node is a branch node.
9191 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
9192 * @return 0 on success, non-zero on failure.
9195 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
9196 unsigned int nflags)
9199 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
9202 int i, j, split_indx, nkeys, pmax;
9203 MDB_env *env = mc->mc_txn->mt_env;
9205 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
9206 MDB_page *copy = NULL;
9207 MDB_page *mp, *rp, *pp;
9212 mp = mc->mc_pg[mc->mc_top];
9213 newindx = mc->mc_ki[mc->mc_top];
9214 nkeys = NUMKEYS(mp);
9216 DPRINTF(("-----> splitting %s page %"Y"u and adding [%s] at index %i/%i",
9217 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
9218 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
9220 /* Create a right sibling. */
9221 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
9223 rp->mp_pad = mp->mp_pad;
9224 DPRINTF(("new right sibling: page %"Y"u", rp->mp_pgno));
9226 /* Usually when splitting the root page, the cursor
9227 * height is 1. But when called from mdb_update_key,
9228 * the cursor height may be greater because it walks
9229 * up the stack while finding the branch slot to update.
9231 if (mc->mc_top < 1) {
9232 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
9234 /* shift current top to make room for new parent */
9235 for (i=mc->mc_snum; i>0; i--) {
9236 mc->mc_pg[i] = mc->mc_pg[i-1];
9237 mc->mc_ki[i] = mc->mc_ki[i-1];
9241 mc->mc_db->md_root = pp->mp_pgno;
9242 DPRINTF(("root split! new root = %"Y"u", pp->mp_pgno));
9243 new_root = mc->mc_db->md_depth++;
9245 /* Add left (implicit) pointer. */
9246 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
9247 /* undo the pre-push */
9248 mc->mc_pg[0] = mc->mc_pg[1];
9249 mc->mc_ki[0] = mc->mc_ki[1];
9250 mc->mc_db->md_root = mp->mp_pgno;
9251 mc->mc_db->md_depth--;
9258 ptop = mc->mc_top-1;
9259 DPRINTF(("parent branch page is %"Y"u", mc->mc_pg[ptop]->mp_pgno));
9262 mdb_cursor_copy(mc, &mn);
9263 mn.mc_xcursor = NULL;
9264 mn.mc_pg[mn.mc_top] = rp;
9265 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
9267 if (nflags & MDB_APPEND) {
9268 mn.mc_ki[mn.mc_top] = 0;
9270 split_indx = newindx;
9274 split_indx = (nkeys+1) / 2;
9279 unsigned int lsize, rsize, ksize;
9280 /* Move half of the keys to the right sibling */
9281 x = mc->mc_ki[mc->mc_top] - split_indx;
9282 ksize = mc->mc_db->md_pad;
9283 split = LEAF2KEY(mp, split_indx, ksize);
9284 rsize = (nkeys - split_indx) * ksize;
9285 lsize = (nkeys - split_indx) * sizeof(indx_t);
9286 mp->mp_lower -= lsize;
9287 rp->mp_lower += lsize;
9288 mp->mp_upper += rsize - lsize;
9289 rp->mp_upper -= rsize - lsize;
9290 sepkey.mv_size = ksize;
9291 if (newindx == split_indx) {
9292 sepkey.mv_data = newkey->mv_data;
9294 sepkey.mv_data = split;
9297 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
9298 memcpy(rp->mp_ptrs, split, rsize);
9299 sepkey.mv_data = rp->mp_ptrs;
9300 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
9301 memcpy(ins, newkey->mv_data, ksize);
9302 mp->mp_lower += sizeof(indx_t);
9303 mp->mp_upper -= ksize - sizeof(indx_t);
9306 memcpy(rp->mp_ptrs, split, x * ksize);
9307 ins = LEAF2KEY(rp, x, ksize);
9308 memcpy(ins, newkey->mv_data, ksize);
9309 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
9310 rp->mp_lower += sizeof(indx_t);
9311 rp->mp_upper -= ksize - sizeof(indx_t);
9312 mc->mc_ki[mc->mc_top] = x;
9315 int psize, nsize, k;
9316 /* Maximum free space in an empty page */
9317 pmax = env->me_psize - PAGEHDRSZ;
9319 nsize = mdb_leaf_size(env, newkey, newdata);
9321 nsize = mdb_branch_size(env, newkey);
9322 nsize = EVEN(nsize);
9324 /* grab a page to hold a temporary copy */
9325 copy = mdb_page_malloc(mc->mc_txn, 1);
9330 copy->mp_pgno = mp->mp_pgno;
9331 copy->mp_flags = mp->mp_flags;
9332 copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
9333 copy->mp_upper = env->me_psize - PAGEBASE;
9335 /* prepare to insert */
9336 for (i=0, j=0; i<nkeys; i++) {
9338 copy->mp_ptrs[j++] = 0;
9340 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
9343 /* When items are relatively large the split point needs
9344 * to be checked, because being off-by-one will make the
9345 * difference between success or failure in mdb_node_add.
9347 * It's also relevant if a page happens to be laid out
9348 * such that one half of its nodes are all "small" and
9349 * the other half of its nodes are "large." If the new
9350 * item is also "large" and falls on the half with
9351 * "large" nodes, it also may not fit.
9353 * As a final tweak, if the new item goes on the last
9354 * spot on the page (and thus, onto the new page), bias
9355 * the split so the new page is emptier than the old page.
9356 * This yields better packing during sequential inserts.
9358 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
9359 /* Find split point */
9361 if (newindx <= split_indx || newindx >= nkeys) {
9363 k = newindx >= nkeys ? nkeys : split_indx+1+IS_LEAF(mp);
9368 for (; i!=k; i+=j) {
9373 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
9374 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
9376 if (F_ISSET(node->mn_flags, F_BIGDATA))
9377 psize += sizeof(pgno_t);
9379 psize += NODEDSZ(node);
9381 psize = EVEN(psize);
9383 if (psize > pmax || i == k-j) {
9384 split_indx = i + (j<0);
9389 if (split_indx == newindx) {
9390 sepkey.mv_size = newkey->mv_size;
9391 sepkey.mv_data = newkey->mv_data;
9393 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
9394 sepkey.mv_size = node->mn_ksize;
9395 sepkey.mv_data = NODEKEY(node);
9400 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
9402 /* Copy separator key to the parent.
9404 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
9405 int snum = mc->mc_snum;
9409 /* We want other splits to find mn when doing fixups */
9410 WITH_CURSOR_TRACKING(mn,
9411 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0));
9416 if (mc->mc_snum > snum) {
9419 /* Right page might now have changed parent.
9420 * Check if left page also changed parent.
9422 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
9423 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
9424 for (i=0; i<ptop; i++) {
9425 mc->mc_pg[i] = mn.mc_pg[i];
9426 mc->mc_ki[i] = mn.mc_ki[i];
9428 mc->mc_pg[ptop] = mn.mc_pg[ptop];
9429 if (mn.mc_ki[ptop]) {
9430 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
9432 /* find right page's left sibling */
9433 mc->mc_ki[ptop] = mn.mc_ki[ptop];
9434 mdb_cursor_sibling(mc, 0);
9439 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
9442 if (rc != MDB_SUCCESS) {
9445 if (nflags & MDB_APPEND) {
9446 mc->mc_pg[mc->mc_top] = rp;
9447 mc->mc_ki[mc->mc_top] = 0;
9448 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
9451 for (i=0; i<mc->mc_top; i++)
9452 mc->mc_ki[i] = mn.mc_ki[i];
9453 } else if (!IS_LEAF2(mp)) {
9455 mc->mc_pg[mc->mc_top] = rp;
9460 rkey.mv_data = newkey->mv_data;
9461 rkey.mv_size = newkey->mv_size;
9467 /* Update index for the new key. */
9468 mc->mc_ki[mc->mc_top] = j;
9470 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
9471 rkey.mv_data = NODEKEY(node);
9472 rkey.mv_size = node->mn_ksize;
9474 xdata.mv_data = NODEDATA(node);
9475 xdata.mv_size = NODEDSZ(node);
9478 pgno = NODEPGNO(node);
9479 flags = node->mn_flags;
9482 if (!IS_LEAF(mp) && j == 0) {
9483 /* First branch index doesn't need key data. */
9487 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
9493 mc->mc_pg[mc->mc_top] = copy;
9498 } while (i != split_indx);
9500 nkeys = NUMKEYS(copy);
9501 for (i=0; i<nkeys; i++)
9502 mp->mp_ptrs[i] = copy->mp_ptrs[i];
9503 mp->mp_lower = copy->mp_lower;
9504 mp->mp_upper = copy->mp_upper;
9505 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
9506 env->me_psize - copy->mp_upper - PAGEBASE);
9508 /* reset back to original page */
9509 if (newindx < split_indx) {
9510 mc->mc_pg[mc->mc_top] = mp;
9512 mc->mc_pg[mc->mc_top] = rp;
9514 /* Make sure mc_ki is still valid.
9516 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
9517 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
9518 for (i=0; i<=ptop; i++) {
9519 mc->mc_pg[i] = mn.mc_pg[i];
9520 mc->mc_ki[i] = mn.mc_ki[i];
9524 if (nflags & MDB_RESERVE) {
9525 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
9526 if (!(node->mn_flags & F_BIGDATA))
9527 newdata->mv_data = NODEDATA(node);
9530 if (newindx >= split_indx) {
9531 mc->mc_pg[mc->mc_top] = rp;
9533 /* Make sure mc_ki is still valid.
9535 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
9536 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
9537 for (i=0; i<=ptop; i++) {
9538 mc->mc_pg[i] = mn.mc_pg[i];
9539 mc->mc_ki[i] = mn.mc_ki[i];
9546 /* Adjust other cursors pointing to mp */
9547 MDB_cursor *m2, *m3;
9548 MDB_dbi dbi = mc->mc_dbi;
9549 nkeys = NUMKEYS(mp);
9551 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9552 if (mc->mc_flags & C_SUB)
9553 m3 = &m2->mc_xcursor->mx_cursor;
9558 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9562 /* sub cursors may be on different DB */
9563 if (m3->mc_pg[0] != mp)
9566 for (k=new_root; k>=0; k--) {
9567 m3->mc_ki[k+1] = m3->mc_ki[k];
9568 m3->mc_pg[k+1] = m3->mc_pg[k];
9570 if (m3->mc_ki[0] >= nkeys) {
9575 m3->mc_pg[0] = mc->mc_pg[0];
9579 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
9580 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
9581 m3->mc_ki[mc->mc_top]++;
9582 if (m3->mc_ki[mc->mc_top] >= nkeys) {
9583 m3->mc_pg[mc->mc_top] = rp;
9584 m3->mc_ki[mc->mc_top] -= nkeys;
9585 for (i=0; i<mc->mc_top; i++) {
9586 m3->mc_ki[i] = mn.mc_ki[i];
9587 m3->mc_pg[i] = mn.mc_pg[i];
9590 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
9591 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
9594 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) &&
9596 MDB_node *node = NODEPTR(m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
9597 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
9598 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
9602 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
9605 if (copy) /* tmp page */
9606 mdb_page_free(env, copy);
9608 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
9613 mdb_put(MDB_txn *txn, MDB_dbi dbi,
9614 MDB_val *key, MDB_val *data, unsigned int flags)
9620 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9623 if (flags & ~(MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP))
9626 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
9627 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
9629 mdb_cursor_init(&mc, txn, dbi, &mx);
9630 mc.mc_next = txn->mt_cursors[dbi];
9631 txn->mt_cursors[dbi] = &mc;
9632 rc = mdb_cursor_put(&mc, key, data, flags);
9633 txn->mt_cursors[dbi] = mc.mc_next;
9638 #define MDB_WBUF (1024*1024)
9641 /** State needed for a compacting copy. */
9642 typedef struct mdb_copy {
9643 pthread_mutex_t mc_mutex;
9644 pthread_cond_t mc_cond;
9651 pgno_t mc_next_pgno;
9654 volatile int mc_new;
9659 /** Dedicated writer thread for compacting copy. */
9660 static THREAD_RET ESECT CALL_CONV
9661 mdb_env_copythr(void *arg)
9665 int toggle = 0, wsize, rc;
9668 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
9671 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
9674 pthread_mutex_lock(&my->mc_mutex);
9676 pthread_cond_signal(&my->mc_cond);
9679 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
9680 if (my->mc_new < 0) {
9685 wsize = my->mc_wlen[toggle];
9686 ptr = my->mc_wbuf[toggle];
9689 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
9693 } else if (len > 0) {
9707 /* If there's an overflow page tail, write it too */
9708 if (my->mc_olen[toggle]) {
9709 wsize = my->mc_olen[toggle];
9710 ptr = my->mc_over[toggle];
9711 my->mc_olen[toggle] = 0;
9714 my->mc_wlen[toggle] = 0;
9716 pthread_cond_signal(&my->mc_cond);
9718 pthread_cond_signal(&my->mc_cond);
9719 pthread_mutex_unlock(&my->mc_mutex);
9720 return (THREAD_RET)0;
9724 /** Tell the writer thread there's a buffer ready to write */
9726 mdb_env_cthr_toggle(mdb_copy *my, int st)
9728 int toggle = my->mc_toggle ^ 1;
9729 pthread_mutex_lock(&my->mc_mutex);
9730 if (my->mc_status) {
9731 pthread_mutex_unlock(&my->mc_mutex);
9732 return my->mc_status;
9734 while (my->mc_new == 1)
9735 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
9737 my->mc_toggle = toggle;
9738 pthread_cond_signal(&my->mc_cond);
9739 pthread_mutex_unlock(&my->mc_mutex);
9743 /** Depth-first tree traversal for compacting copy. */
9745 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
9747 MDB_cursor mc = {0};
9749 MDB_page *mo, *mp, *leaf;
9754 /* Empty DB, nothing to do */
9755 if (*pg == P_INVALID)
9759 mc.mc_txn = my->mc_txn;
9760 mc.mc_flags = my->mc_txn->mt_flags & (C_ORIG_RDONLY|C_WRITEMAP);
9762 rc = mdb_page_get(&mc, *pg, &mc.mc_pg[0], NULL);
9765 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
9769 /* Make cursor pages writable */
9770 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
9774 for (i=0; i<mc.mc_top; i++) {
9775 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
9776 mc.mc_pg[i] = (MDB_page *)ptr;
9777 ptr += my->mc_env->me_psize;
9780 /* This is writable space for a leaf page. Usually not needed. */
9781 leaf = (MDB_page *)ptr;
9783 toggle = my->mc_toggle;
9784 while (mc.mc_snum > 0) {
9786 mp = mc.mc_pg[mc.mc_top];
9790 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
9791 for (i=0; i<n; i++) {
9792 ni = NODEPTR(mp, i);
9793 if (ni->mn_flags & F_BIGDATA) {
9797 /* Need writable leaf */
9799 mc.mc_pg[mc.mc_top] = leaf;
9800 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
9802 ni = NODEPTR(mp, i);
9805 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9806 rc = mdb_page_get(&mc, pg, &omp, NULL);
9809 if (my->mc_wlen[toggle] >= MDB_WBUF) {
9810 rc = mdb_env_cthr_toggle(my, 1);
9813 toggle = my->mc_toggle;
9815 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
9816 memcpy(mo, omp, my->mc_env->me_psize);
9817 mo->mp_pgno = my->mc_next_pgno;
9818 my->mc_next_pgno += omp->mp_pages;
9819 my->mc_wlen[toggle] += my->mc_env->me_psize;
9820 if (omp->mp_pages > 1) {
9821 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
9822 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
9823 rc = mdb_env_cthr_toggle(my, 1);
9826 toggle = my->mc_toggle;
9828 memcpy(NODEDATA(ni), &mo->mp_pgno, sizeof(pgno_t));
9829 } else if (ni->mn_flags & F_SUBDATA) {
9832 /* Need writable leaf */
9834 mc.mc_pg[mc.mc_top] = leaf;
9835 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
9837 ni = NODEPTR(mp, i);
9840 memcpy(&db, NODEDATA(ni), sizeof(db));
9841 my->mc_toggle = toggle;
9842 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
9845 toggle = my->mc_toggle;
9846 memcpy(NODEDATA(ni), &db, sizeof(db));
9851 mc.mc_ki[mc.mc_top]++;
9852 if (mc.mc_ki[mc.mc_top] < n) {
9855 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
9857 rc = mdb_page_get(&mc, pg, &mp, NULL);
9862 mc.mc_ki[mc.mc_top] = 0;
9863 if (IS_BRANCH(mp)) {
9864 /* Whenever we advance to a sibling branch page,
9865 * we must proceed all the way down to its first leaf.
9867 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
9870 mc.mc_pg[mc.mc_top] = mp;
9874 if (my->mc_wlen[toggle] >= MDB_WBUF) {
9875 rc = mdb_env_cthr_toggle(my, 1);
9878 toggle = my->mc_toggle;
9880 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
9881 mdb_page_copy(mo, mp, my->mc_env->me_psize);
9882 mo->mp_pgno = my->mc_next_pgno++;
9883 my->mc_wlen[toggle] += my->mc_env->me_psize;
9885 /* Update parent if there is one */
9886 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
9887 SETPGNO(ni, mo->mp_pgno);
9888 mdb_cursor_pop(&mc);
9890 /* Otherwise we're done */
9900 /** Copy environment with compaction. */
9902 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
9907 MDB_txn *txn = NULL;
9912 my.mc_mutex = CreateMutex(NULL, FALSE, NULL);
9913 my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL);
9914 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_os_psize);
9915 if (my.mc_wbuf[0] == NULL)
9918 pthread_mutex_init(&my.mc_mutex, NULL);
9919 pthread_cond_init(&my.mc_cond, NULL);
9920 #ifdef HAVE_MEMALIGN
9921 my.mc_wbuf[0] = memalign(env->me_os_psize, MDB_WBUF*2);
9922 if (my.mc_wbuf[0] == NULL)
9925 rc = posix_memalign((void **)&my.mc_wbuf[0], env->me_os_psize, MDB_WBUF*2);
9930 memset(my.mc_wbuf[0], 0, MDB_WBUF*2);
9931 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
9936 my.mc_next_pgno = NUM_METAS;
9942 THREAD_CREATE(thr, mdb_env_copythr, &my);
9944 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
9948 mp = (MDB_page *)my.mc_wbuf[0];
9949 memset(mp, 0, NUM_METAS * env->me_psize);
9951 mp->mp_flags = P_META;
9952 mm = (MDB_meta *)METADATA(mp);
9953 mdb_env_init_meta0(env, mm);
9954 mm->mm_address = env->me_metas[0]->mm_address;
9956 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
9958 mp->mp_flags = P_META;
9959 *(MDB_meta *)METADATA(mp) = *mm;
9960 mm = (MDB_meta *)METADATA(mp);
9962 /* Count the number of free pages, subtract from lastpg to find
9963 * number of active pages
9966 MDB_ID freecount = 0;
9969 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
9970 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
9971 freecount += *(MDB_ID *)data.mv_data;
9972 freecount += txn->mt_dbs[FREE_DBI].md_branch_pages +
9973 txn->mt_dbs[FREE_DBI].md_leaf_pages +
9974 txn->mt_dbs[FREE_DBI].md_overflow_pages;
9976 /* Set metapage 1 */
9977 mm->mm_last_pg = txn->mt_next_pgno - freecount - 1;
9978 mm->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
9979 if (mm->mm_last_pg > NUM_METAS-1) {
9980 mm->mm_dbs[MAIN_DBI].md_root = mm->mm_last_pg;
9983 mm->mm_dbs[MAIN_DBI].md_root = P_INVALID;
9986 my.mc_wlen[0] = env->me_psize * NUM_METAS;
9988 pthread_mutex_lock(&my.mc_mutex);
9990 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
9991 pthread_mutex_unlock(&my.mc_mutex);
9992 rc = mdb_env_cwalk(&my, &txn->mt_dbs[MAIN_DBI].md_root, 0);
9993 if (rc == MDB_SUCCESS && my.mc_wlen[my.mc_toggle])
9994 rc = mdb_env_cthr_toggle(&my, 1);
9995 mdb_env_cthr_toggle(&my, -1);
9996 pthread_mutex_lock(&my.mc_mutex);
9998 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
9999 pthread_mutex_unlock(&my.mc_mutex);
10000 THREAD_FINISH(thr);
10002 mdb_txn_abort(txn);
10004 CloseHandle(my.mc_cond);
10005 CloseHandle(my.mc_mutex);
10006 _aligned_free(my.mc_wbuf[0]);
10008 pthread_cond_destroy(&my.mc_cond);
10009 pthread_mutex_destroy(&my.mc_mutex);
10010 free(my.mc_wbuf[0]);
10015 /** Copy environment as-is. */
10017 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
10019 MDB_txn *txn = NULL;
10020 mdb_mutexref_t wmutex = NULL;
10022 mdb_size_t wsize, w3;
10026 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
10030 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
10033 /* Do the lock/unlock of the reader mutex before starting the
10034 * write txn. Otherwise other read txns could block writers.
10036 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
10040 if (env->me_txns) {
10041 /* We must start the actual read txn after blocking writers */
10042 mdb_txn_end(txn, MDB_END_RESET_TMP);
10044 /* Temporarily block writers until we snapshot the meta pages */
10045 wmutex = env->me_wmutex;
10046 if (LOCK_MUTEX(rc, env, wmutex))
10049 rc = mdb_txn_renew0(txn);
10051 UNLOCK_MUTEX(wmutex);
10056 wsize = env->me_psize * NUM_METAS;
10060 DO_WRITE(rc, fd, ptr, w2, len);
10064 } else if (len > 0) {
10070 /* Non-blocking or async handles are not supported */
10076 UNLOCK_MUTEX(wmutex);
10081 w3 = txn->mt_next_pgno * env->me_psize;
10083 mdb_size_t fsize = 0;
10084 if ((rc = mdb_fsize(env->me_fd, &fsize)))
10089 wsize = w3 - wsize;
10090 while (wsize > 0) {
10091 if (wsize > MAX_WRITE)
10095 DO_WRITE(rc, fd, ptr, w2, len);
10099 } else if (len > 0) {
10111 mdb_txn_abort(txn);
10116 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
10118 if (flags & MDB_CP_COMPACT)
10119 return mdb_env_copyfd1(env, fd);
10121 return mdb_env_copyfd0(env, fd);
10125 mdb_env_copyfd(MDB_env *env, HANDLE fd)
10127 return mdb_env_copyfd2(env, fd, 0);
10131 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
10135 HANDLE newfd = INVALID_HANDLE_VALUE;
10140 if (env->me_flags & MDB_NOSUBDIR) {
10141 lpath = (char *)path;
10143 len = strlen(path);
10144 len += sizeof(DATANAME);
10145 lpath = malloc(len);
10148 sprintf(lpath, "%s" DATANAME, path);
10151 /* The destination path must exist, but the destination file must not.
10152 * We don't want the OS to cache the writes, since the source data is
10153 * already in the OS cache.
10156 rc = utf8_to_utf16(lpath, -1, &wpath, NULL);
10159 newfd = CreateFileW(wpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
10160 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
10163 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
10165 if (newfd == INVALID_HANDLE_VALUE) {
10170 if (env->me_psize >= env->me_os_psize) {
10172 /* Set O_DIRECT if the file system supports it */
10173 if ((rc = fcntl(newfd, F_GETFL)) != -1)
10174 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
10176 #ifdef F_NOCACHE /* __APPLE__ */
10177 rc = fcntl(newfd, F_NOCACHE, 1);
10185 rc = mdb_env_copyfd2(env, newfd, flags);
10188 if (!(env->me_flags & MDB_NOSUBDIR))
10190 if (newfd != INVALID_HANDLE_VALUE)
10191 if (close(newfd) < 0 && rc == MDB_SUCCESS)
10198 mdb_env_copy(MDB_env *env, const char *path)
10200 return mdb_env_copy2(env, path, 0);
10204 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
10206 if (flag & ~CHANGEABLE)
10209 env->me_flags |= flag;
10211 env->me_flags &= ~flag;
10212 return MDB_SUCCESS;
10216 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
10221 *arg = env->me_flags & (CHANGEABLE|CHANGELESS);
10222 return MDB_SUCCESS;
10226 mdb_env_set_userctx(MDB_env *env, void *ctx)
10230 env->me_userctx = ctx;
10231 return MDB_SUCCESS;
10235 mdb_env_get_userctx(MDB_env *env)
10237 return env ? env->me_userctx : NULL;
10241 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
10246 env->me_assert_func = func;
10248 return MDB_SUCCESS;
10252 mdb_env_get_path(MDB_env *env, const char **arg)
10257 *arg = env->me_path;
10258 return MDB_SUCCESS;
10262 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
10268 return MDB_SUCCESS;
10271 /** Common code for #mdb_stat() and #mdb_env_stat().
10272 * @param[in] env the environment to operate in.
10273 * @param[in] db the #MDB_db record containing the stats to return.
10274 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
10275 * @return 0, this function always succeeds.
10278 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
10280 arg->ms_psize = env->me_psize;
10281 arg->ms_depth = db->md_depth;
10282 arg->ms_branch_pages = db->md_branch_pages;
10283 arg->ms_leaf_pages = db->md_leaf_pages;
10284 arg->ms_overflow_pages = db->md_overflow_pages;
10285 arg->ms_entries = db->md_entries;
10287 return MDB_SUCCESS;
10291 mdb_env_stat(MDB_env *env, MDB_stat *arg)
10295 if (env == NULL || arg == NULL)
10298 meta = mdb_env_pick_meta(env);
10300 return mdb_stat0(env, &meta->mm_dbs[MAIN_DBI], arg);
10304 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
10308 if (env == NULL || arg == NULL)
10311 meta = mdb_env_pick_meta(env);
10312 arg->me_mapaddr = meta->mm_address;
10313 arg->me_last_pgno = meta->mm_last_pg;
10314 arg->me_last_txnid = meta->mm_txnid;
10316 arg->me_mapsize = env->me_mapsize;
10317 arg->me_maxreaders = env->me_maxreaders;
10318 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : 0;
10319 return MDB_SUCCESS;
10322 /** Set the default comparison functions for a database.
10323 * Called immediately after a database is opened to set the defaults.
10324 * The user can then override them with #mdb_set_compare() or
10325 * #mdb_set_dupsort().
10326 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
10327 * @param[in] dbi A database handle returned by #mdb_dbi_open()
10330 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
10332 uint16_t f = txn->mt_dbs[dbi].md_flags;
10334 txn->mt_dbxs[dbi].md_cmp =
10335 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
10336 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
10338 txn->mt_dbxs[dbi].md_dcmp =
10339 !(f & MDB_DUPSORT) ? 0 :
10340 ((f & MDB_INTEGERDUP)
10341 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
10342 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
10345 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
10351 int rc, dbflag, exact;
10352 unsigned int unused = 0, seq;
10356 if (flags & ~VALID_FLAGS)
10358 if (txn->mt_flags & MDB_TXN_BLOCKED)
10359 return MDB_BAD_TXN;
10364 if (flags & PERSISTENT_FLAGS) {
10365 uint16_t f2 = flags & PERSISTENT_FLAGS;
10366 /* make sure flag changes get committed */
10367 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
10368 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
10369 txn->mt_flags |= MDB_TXN_DIRTY;
10372 mdb_default_cmp(txn, MAIN_DBI);
10373 return MDB_SUCCESS;
10376 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
10377 mdb_default_cmp(txn, MAIN_DBI);
10380 /* Is the DB already open? */
10381 len = strlen(name);
10382 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
10383 if (!txn->mt_dbxs[i].md_name.mv_size) {
10384 /* Remember this free slot */
10385 if (!unused) unused = i;
10388 if (len == txn->mt_dbxs[i].md_name.mv_size &&
10389 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
10391 return MDB_SUCCESS;
10395 /* If no free slot and max hit, fail */
10396 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
10397 return MDB_DBS_FULL;
10399 /* Cannot mix named databases with some mainDB flags */
10400 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
10401 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
10403 /* Find the DB info */
10404 dbflag = DB_NEW|DB_VALID|DB_USRVALID;
10407 key.mv_data = (void *)name;
10408 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
10409 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
10410 if (rc == MDB_SUCCESS) {
10411 /* make sure this is actually a DB */
10412 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
10413 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
10414 return MDB_INCOMPATIBLE;
10415 } else if (! (rc == MDB_NOTFOUND && (flags & MDB_CREATE))) {
10419 /* Done here so we cannot fail after creating a new DB */
10420 if ((namedup = strdup(name)) == NULL)
10424 /* MDB_NOTFOUND and MDB_CREATE: Create new DB */
10425 data.mv_size = sizeof(MDB_db);
10426 data.mv_data = &dummy;
10427 memset(&dummy, 0, sizeof(dummy));
10428 dummy.md_root = P_INVALID;
10429 dummy.md_flags = flags & PERSISTENT_FLAGS;
10430 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
10431 dbflag |= DB_DIRTY;
10437 /* Got info, register DBI in this txn */
10438 unsigned int slot = unused ? unused : txn->mt_numdbs;
10439 txn->mt_dbxs[slot].md_name.mv_data = namedup;
10440 txn->mt_dbxs[slot].md_name.mv_size = len;
10441 txn->mt_dbxs[slot].md_rel = NULL;
10442 txn->mt_dbflags[slot] = dbflag;
10443 /* txn-> and env-> are the same in read txns, use
10444 * tmp variable to avoid undefined assignment
10446 seq = ++txn->mt_env->me_dbiseqs[slot];
10447 txn->mt_dbiseqs[slot] = seq;
10449 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
10451 mdb_default_cmp(txn, slot);
10461 mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
10463 if (!arg || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
10466 if (txn->mt_flags & MDB_TXN_BLOCKED)
10467 return MDB_BAD_TXN;
10469 if (txn->mt_dbflags[dbi] & DB_STALE) {
10472 /* Stale, must read the DB's root. cursor_init does it for us. */
10473 mdb_cursor_init(&mc, txn, dbi, &mx);
10475 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
10478 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
10481 if (dbi < CORE_DBS || dbi >= env->me_maxdbs)
10483 ptr = env->me_dbxs[dbi].md_name.mv_data;
10484 /* If there was no name, this was already closed */
10486 env->me_dbxs[dbi].md_name.mv_data = NULL;
10487 env->me_dbxs[dbi].md_name.mv_size = 0;
10488 env->me_dbflags[dbi] = 0;
10489 env->me_dbiseqs[dbi]++;
10494 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
10496 /* We could return the flags for the FREE_DBI too but what's the point? */
10497 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10499 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
10500 return MDB_SUCCESS;
10503 /** Add all the DB's pages to the free list.
10504 * @param[in] mc Cursor on the DB to free.
10505 * @param[in] subs non-Zero to check for sub-DBs in this DB.
10506 * @return 0 on success, non-zero on failure.
10509 mdb_drop0(MDB_cursor *mc, int subs)
10513 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
10514 if (rc == MDB_SUCCESS) {
10515 MDB_txn *txn = mc->mc_txn;
10520 /* DUPSORT sub-DBs have no ovpages/DBs. Omit scanning leaves.
10521 * This also avoids any P_LEAF2 pages, which have no nodes.
10522 * Also if the DB doesn't have sub-DBs and has no overflow
10523 * pages, omit scanning leaves.
10525 if ((mc->mc_flags & C_SUB) ||
10526 (!subs && !mc->mc_db->md_overflow_pages))
10527 mdb_cursor_pop(mc);
10529 mdb_cursor_copy(mc, &mx);
10531 /* bump refcount for mx's pages */
10532 for (i=0; i<mc->mc_snum; i++)
10533 mdb_page_get(&mx, mc->mc_pg[i]->mp_pgno, &mx.mc_pg[i], NULL);
10535 while (mc->mc_snum > 0) {
10536 MDB_page *mp = mc->mc_pg[mc->mc_top];
10537 unsigned n = NUMKEYS(mp);
10539 for (i=0; i<n; i++) {
10540 ni = NODEPTR(mp, i);
10541 if (ni->mn_flags & F_BIGDATA) {
10544 memcpy(&pg, NODEDATA(ni), sizeof(pg));
10545 rc = mdb_page_get(mc, pg, &omp, NULL);
10548 mdb_cassert(mc, IS_OVERFLOW(omp));
10549 rc = mdb_midl_append_range(&txn->mt_free_pgs,
10550 pg, omp->mp_pages);
10553 mc->mc_db->md_overflow_pages -= omp->mp_pages;
10554 if (!mc->mc_db->md_overflow_pages && !subs)
10556 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
10557 mdb_xcursor_init1(mc, ni);
10558 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
10563 if (!subs && !mc->mc_db->md_overflow_pages)
10566 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
10568 for (i=0; i<n; i++) {
10570 ni = NODEPTR(mp, i);
10573 mdb_midl_xappend(txn->mt_free_pgs, pg);
10578 mc->mc_ki[mc->mc_top] = i;
10579 rc = mdb_cursor_sibling(mc, 1);
10581 if (rc != MDB_NOTFOUND)
10583 /* no more siblings, go back to beginning
10584 * of previous level.
10587 mdb_cursor_pop(mc);
10589 for (i=1; i<mc->mc_snum; i++) {
10591 mc->mc_pg[i] = mx.mc_pg[i];
10596 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
10599 txn->mt_flags |= MDB_TXN_ERROR;
10601 /* drop refcount for mx's pages */
10602 mdb_cursor_unref(&mx);
10604 } else if (rc == MDB_NOTFOUND) {
10607 mc->mc_flags &= ~C_INITIALIZED;
10611 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
10613 MDB_cursor *mc, *m2;
10616 if ((unsigned)del > 1 || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10619 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
10622 if (TXN_DBI_CHANGED(txn, dbi))
10623 return MDB_BAD_DBI;
10625 rc = mdb_cursor_open(txn, dbi, &mc);
10629 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
10630 /* Invalidate the dropped DB's cursors */
10631 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
10632 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
10636 /* Can't delete the main DB */
10637 if (del && dbi >= CORE_DBS) {
10638 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, F_SUBDATA);
10640 txn->mt_dbflags[dbi] = DB_STALE;
10641 mdb_dbi_close(txn->mt_env, dbi);
10643 txn->mt_flags |= MDB_TXN_ERROR;
10646 /* reset the DB record, mark it dirty */
10647 txn->mt_dbflags[dbi] |= DB_DIRTY;
10648 txn->mt_dbs[dbi].md_depth = 0;
10649 txn->mt_dbs[dbi].md_branch_pages = 0;
10650 txn->mt_dbs[dbi].md_leaf_pages = 0;
10651 txn->mt_dbs[dbi].md_overflow_pages = 0;
10652 txn->mt_dbs[dbi].md_entries = 0;
10653 txn->mt_dbs[dbi].md_root = P_INVALID;
10655 txn->mt_flags |= MDB_TXN_DIRTY;
10658 mdb_cursor_close(mc);
10662 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
10664 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10667 txn->mt_dbxs[dbi].md_cmp = cmp;
10668 return MDB_SUCCESS;
10671 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
10673 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10676 txn->mt_dbxs[dbi].md_dcmp = cmp;
10677 return MDB_SUCCESS;
10680 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
10682 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10685 txn->mt_dbxs[dbi].md_rel = rel;
10686 return MDB_SUCCESS;
10689 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
10691 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10694 txn->mt_dbxs[dbi].md_relctx = ctx;
10695 return MDB_SUCCESS;
10699 mdb_env_get_maxkeysize(MDB_env *env)
10701 return ENV_MAXKEY(env);
10705 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
10707 unsigned int i, rdrs;
10710 int rc = 0, first = 1;
10714 if (!env->me_txns) {
10715 return func("(no reader locks)\n", ctx);
10717 rdrs = env->me_txns->mti_numreaders;
10718 mr = env->me_txns->mti_readers;
10719 for (i=0; i<rdrs; i++) {
10720 if (mr[i].mr_pid) {
10721 txnid_t txnid = mr[i].mr_txnid;
10722 sprintf(buf, txnid == (txnid_t)-1 ?
10723 "%10d %"Z"x -\n" : "%10d %"Z"x %"Y"u\n",
10724 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
10727 rc = func(" pid thread txnid\n", ctx);
10731 rc = func(buf, ctx);
10737 rc = func("(no active readers)\n", ctx);
10742 /** Insert pid into list if not already present.
10743 * return -1 if already present.
10746 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
10748 /* binary search of pid in list */
10750 unsigned cursor = 1;
10752 unsigned n = ids[0];
10755 unsigned pivot = n >> 1;
10756 cursor = base + pivot + 1;
10757 val = pid - ids[cursor];
10762 } else if ( val > 0 ) {
10767 /* found, so it's a duplicate */
10776 for (n = ids[0]; n > cursor; n--)
10783 mdb_reader_check(MDB_env *env, int *dead)
10789 return env->me_txns ? mdb_reader_check0(env, 0, dead) : MDB_SUCCESS;
10792 /** As #mdb_reader_check(). rlocked = <caller locked the reader mutex>. */
10794 mdb_reader_check0(MDB_env *env, int rlocked, int *dead)
10796 mdb_mutexref_t rmutex = rlocked ? NULL : env->me_rmutex;
10797 unsigned int i, j, rdrs;
10799 MDB_PID_T *pids, pid;
10800 int rc = MDB_SUCCESS, count = 0;
10802 rdrs = env->me_txns->mti_numreaders;
10803 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
10807 mr = env->me_txns->mti_readers;
10808 for (i=0; i<rdrs; i++) {
10809 pid = mr[i].mr_pid;
10810 if (pid && pid != env->me_pid) {
10811 if (mdb_pid_insert(pids, pid) == 0) {
10812 if (!mdb_reader_pid(env, Pidcheck, pid)) {
10813 /* Stale reader found */
10816 if ((rc = LOCK_MUTEX0(rmutex)) != 0) {
10817 if ((rc = mdb_mutex_failed(env, rmutex, rc)))
10819 rdrs = 0; /* the above checked all readers */
10821 /* Recheck, a new process may have reused pid */
10822 if (mdb_reader_pid(env, Pidcheck, pid))
10826 for (; j<rdrs; j++)
10827 if (mr[j].mr_pid == pid) {
10828 DPRINTF(("clear stale reader pid %u txn %"Y"d",
10829 (unsigned) pid, mr[j].mr_txnid));
10834 UNLOCK_MUTEX(rmutex);
10845 #ifdef MDB_ROBUST_SUPPORTED
10846 /** Handle #LOCK_MUTEX0() failure.
10847 * Try to repair the lock file if the mutex owner died.
10848 * @param[in] env the environment handle
10849 * @param[in] mutex LOCK_MUTEX0() mutex
10850 * @param[in] rc LOCK_MUTEX0() error (nonzero)
10851 * @return 0 on success with the mutex locked, or an error code on failure.
10854 mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc)
10859 if (rc == MDB_OWNERDEAD) {
10860 /* We own the mutex. Clean up after dead previous owner. */
10862 rlocked = (mutex == env->me_rmutex);
10864 /* Keep mti_txnid updated, otherwise next writer can
10865 * overwrite data which latest meta page refers to.
10867 meta = mdb_env_pick_meta(env);
10868 env->me_txns->mti_txnid = meta->mm_txnid;
10869 /* env is hosed if the dead thread was ours */
10871 env->me_flags |= MDB_FATAL_ERROR;
10872 env->me_txn = NULL;
10876 DPRINTF(("%cmutex owner died, %s", (rlocked ? 'r' : 'w'),
10877 (rc ? "this process' env is hosed" : "recovering")));
10878 rc2 = mdb_reader_check0(env, rlocked, NULL);
10880 rc2 = mdb_mutex_consistent(mutex);
10881 if (rc || (rc = rc2)) {
10882 DPRINTF(("LOCK_MUTEX recovery failed, %s", mdb_strerror(rc)));
10883 UNLOCK_MUTEX(mutex);
10889 DPRINTF(("LOCK_MUTEX failed, %s", mdb_strerror(rc)));
10894 #endif /* MDB_ROBUST_SUPPORTED */
10897 #if defined(_WIN32)
10898 static int utf8_to_utf16(const char *src, int srcsize, wchar_t **dst, int *dstsize)
10902 need = MultiByteToWideChar(CP_UTF8, 0, src, srcsize, NULL, 0);
10903 if (need == 0xFFFD)
10907 result = malloc(sizeof(wchar_t) * need);
10910 MultiByteToWideChar(CP_UTF8, 0, src, srcsize, result, need);
10916 #endif /* defined(_WIN32) */