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))
4976 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
4977 #ifdef MDB_ROBUST_SUPPORTED
4978 || (rc = pthread_mutexattr_setrobust(&mattr, PTHREAD_MUTEX_ROBUST))
4980 || (rc = pthread_mutex_init(env->me_txns->mti_rmutex, &mattr))
4981 || (rc = pthread_mutex_init(env->me_txns->mti_wmutex, &mattr)))
4983 pthread_mutexattr_destroy(&mattr);
4984 #endif /* _WIN32 || ... */
4986 env->me_txns->mti_magic = MDB_MAGIC;
4987 env->me_txns->mti_format = MDB_LOCK_FORMAT;
4988 env->me_txns->mti_txnid = 0;
4989 env->me_txns->mti_numreaders = 0;
4992 #ifdef MDB_USE_SYSV_SEM
4993 struct semid_ds buf;
4995 if (env->me_txns->mti_magic != MDB_MAGIC) {
4996 DPUTS("lock region has invalid magic");
5000 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
5001 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
5002 env->me_txns->mti_format, MDB_LOCK_FORMAT));
5003 rc = MDB_VERSION_MISMATCH;
5007 if (rc && rc != EACCES && rc != EAGAIN) {
5011 env->me_rmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
5012 if (!env->me_rmutex) goto fail_errno;
5013 env->me_wmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
5014 if (!env->me_wmutex) goto fail_errno;
5015 #elif defined(MDB_USE_POSIX_SEM)
5016 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
5017 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
5018 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
5019 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
5020 #elif defined(MDB_USE_SYSV_SEM)
5021 semid = env->me_txns->mti_semid;
5023 /* check for read access */
5024 if (semctl(semid, 0, IPC_STAT, semu) < 0)
5026 /* check for write access */
5027 if (semctl(semid, 0, IPC_SET, semu) < 0)
5031 #ifdef MDB_USE_SYSV_SEM
5032 env->me_rmutex->semid = semid;
5033 env->me_wmutex->semid = semid;
5034 env->me_rmutex->semnum = 0;
5035 env->me_wmutex->semnum = 1;
5036 env->me_rmutex->locked = &env->me_txns->mti_rlocked;
5037 env->me_wmutex->locked = &env->me_txns->mti_wlocked;
5041 env->me_rpmutex = CreateMutex(NULL, FALSE, NULL);
5043 pthread_mutex_init(&env->me_rpmutex, NULL);
5055 /** The name of the lock file in the DB environment */
5056 #define LOCKNAME "/lock.mdb"
5057 /** The name of the data file in the DB environment */
5058 #define DATANAME "/data.mdb"
5059 /** The suffix of the lock file when no subdir is used */
5060 #define LOCKSUFF "-lock"
5061 /** Only a subset of the @ref mdb_env flags can be changed
5062 * at runtime. Changing other flags requires closing the
5063 * environment and re-opening it with the new flags.
5065 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
5066 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY| \
5067 MDB_WRITEMAP|MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
5069 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
5070 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
5074 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
5076 int oflags, rc, len, excl = -1;
5077 char *lpath, *dpath;
5082 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
5086 if (flags & MDB_WRITEMAP) {
5087 /* silently ignore WRITEMAP in 32 bit mode */
5088 flags ^= MDB_WRITEMAP;
5090 if (flags & MDB_FIXEDMAP) {
5091 /* cannot support FIXEDMAP */
5097 if (flags & MDB_NOSUBDIR) {
5098 rc = len + sizeof(LOCKSUFF) + len + 1;
5100 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
5105 if (flags & MDB_NOSUBDIR) {
5106 dpath = lpath + len + sizeof(LOCKSUFF);
5107 sprintf(lpath, "%s" LOCKSUFF, path);
5108 strcpy(dpath, path);
5110 dpath = lpath + len + sizeof(LOCKNAME);
5111 sprintf(lpath, "%s" LOCKNAME, path);
5112 sprintf(dpath, "%s" DATANAME, path);
5116 flags |= env->me_flags;
5117 if (flags & MDB_RDONLY) {
5118 /* silently ignore WRITEMAP when we're only getting read access */
5119 flags &= ~MDB_WRITEMAP;
5121 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
5122 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
5127 env->me_rpages = malloc(MDB_ERPAGE_SIZE * sizeof(MDB_ID3));
5128 if (!env->me_rpages) {
5132 env->me_rpages[0].mid = 0;
5133 env->me_rpcheck = MDB_ERPAGE_SIZE/2;
5136 env->me_flags = flags |= MDB_ENV_ACTIVE;
5140 env->me_path = strdup(path);
5141 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
5142 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
5143 env->me_dbiseqs = calloc(env->me_maxdbs, sizeof(unsigned int));
5144 if (!(env->me_dbxs && env->me_path && env->me_dbflags && env->me_dbiseqs)) {
5148 env->me_dbxs[FREE_DBI].md_cmp = mdb_cmp_long; /* aligned MDB_INTEGERKEY */
5150 /* For RDONLY, get lockfile after we know datafile exists */
5151 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
5152 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
5158 if (F_ISSET(flags, MDB_RDONLY)) {
5159 oflags = GENERIC_READ;
5160 len = OPEN_EXISTING;
5162 oflags = GENERIC_READ|GENERIC_WRITE;
5165 mode = FILE_ATTRIBUTE_NORMAL;
5166 rc = utf8_to_utf16(dpath, -1, &wpath, NULL);
5169 env->me_fd = CreateFileW(wpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
5170 NULL, len, mode, NULL);
5173 if (F_ISSET(flags, MDB_RDONLY))
5176 oflags = O_RDWR | O_CREAT;
5178 env->me_fd = open(dpath, oflags, mode);
5180 if (env->me_fd == INVALID_HANDLE_VALUE) {
5185 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
5186 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
5191 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
5192 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
5193 env->me_mfd = env->me_fd;
5195 /* Synchronous fd for meta writes. Needed even with
5196 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
5199 len = OPEN_EXISTING;
5200 rc = utf8_to_utf16(dpath, -1, &wpath, NULL);
5203 env->me_mfd = CreateFileW(wpath, oflags,
5204 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
5205 mode | FILE_FLAG_WRITE_THROUGH, NULL);
5209 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
5211 if (env->me_mfd == INVALID_HANDLE_VALUE) {
5216 DPRINTF(("opened dbenv %p", (void *) env));
5218 rc = mdb_env_share_locks(env, &excl);
5222 if (!(flags & MDB_RDONLY)) {
5224 int tsize = sizeof(MDB_txn), size = tsize + env->me_maxdbs *
5225 (sizeof(MDB_db)+sizeof(MDB_cursor *)+sizeof(unsigned int)+1);
5226 if ((env->me_pbuf = calloc(1, env->me_psize)) &&
5227 (txn = calloc(1, size)))
5229 txn->mt_dbs = (MDB_db *)((char *)txn + tsize);
5230 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
5231 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
5232 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
5235 txn->mt_rpages = malloc(MDB_TRPAGE_SIZE * sizeof(MDB_ID3));
5236 if (!txn->mt_rpages) {
5241 txn->mt_rpages[0].mid = 0;
5242 txn->mt_rpcheck = MDB_TRPAGE_SIZE/2;
5244 txn->mt_dbxs = env->me_dbxs;
5245 txn->mt_flags = MDB_TXN_FINISHED;
5255 mdb_env_close0(env, excl);
5261 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
5263 mdb_env_close0(MDB_env *env, int excl)
5267 if (!(env->me_flags & MDB_ENV_ACTIVE))
5270 /* Doing this here since me_dbxs may not exist during mdb_env_close */
5272 for (i = env->me_maxdbs; --i >= CORE_DBS; )
5273 free(env->me_dbxs[i].md_name.mv_data);
5278 free(env->me_dbiseqs);
5279 free(env->me_dbflags);
5281 free(env->me_dirty_list);
5283 if (env->me_txn0 && env->me_txn0->mt_rpages)
5284 free(env->me_txn0->mt_rpages);
5286 for (x=1; x<=env->me_rpages[0].mid; x++)
5287 munmap(env->me_rpages[x].mptr, env->me_rpages[x].mcnt * env->me_psize);
5289 free(env->me_rpages);
5292 mdb_midl_free(env->me_free_pgs);
5294 if (env->me_flags & MDB_ENV_TXKEY) {
5295 pthread_key_delete(env->me_txkey);
5297 /* Delete our key from the global list */
5298 for (i=0; i<mdb_tls_nkeys; i++)
5299 if (mdb_tls_keys[i] == env->me_txkey) {
5300 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
5309 munmap(env->me_map, NUM_METAS*env->me_psize);
5311 munmap(env->me_map, env->me_mapsize);
5314 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
5315 (void) close(env->me_mfd);
5316 if (env->me_fd != INVALID_HANDLE_VALUE)
5317 (void) close(env->me_fd);
5319 MDB_PID_T pid = env->me_pid;
5320 /* Clearing readers is done in this function because
5321 * me_txkey with its destructor must be disabled first.
5323 * We skip the the reader mutex, so we touch only
5324 * data owned by this process (me_close_readers and
5325 * our readers), and clear each reader atomically.
5327 for (i = env->me_close_readers; --i >= 0; )
5328 if (env->me_txns->mti_readers[i].mr_pid == pid)
5329 env->me_txns->mti_readers[i].mr_pid = 0;
5331 if (env->me_rmutex) {
5332 CloseHandle(env->me_rmutex);
5333 if (env->me_wmutex) CloseHandle(env->me_wmutex);
5335 /* Windows automatically destroys the mutexes when
5336 * the last handle closes.
5338 #elif defined(MDB_USE_POSIX_SEM)
5339 if (env->me_rmutex != SEM_FAILED) {
5340 sem_close(env->me_rmutex);
5341 if (env->me_wmutex != SEM_FAILED)
5342 sem_close(env->me_wmutex);
5343 /* If we have the filelock: If we are the
5344 * only remaining user, clean up semaphores.
5347 mdb_env_excl_lock(env, &excl);
5349 sem_unlink(env->me_txns->mti_rmname);
5350 sem_unlink(env->me_txns->mti_wmname);
5353 #elif defined(MDB_USE_SYSV_SEM)
5354 if (env->me_rmutex->semid != -1) {
5355 /* If we have the filelock: If we are the
5356 * only remaining user, clean up semaphores.
5359 mdb_env_excl_lock(env, &excl);
5361 semctl(env->me_rmutex->semid, 0, IPC_RMID);
5364 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
5366 if (env->me_lfd != INVALID_HANDLE_VALUE) {
5369 /* Unlock the lockfile. Windows would have unlocked it
5370 * after closing anyway, but not necessarily at once.
5372 UnlockFile(env->me_lfd, 0, 0, 1, 0);
5375 (void) close(env->me_lfd);
5379 if (env->me_fmh) CloseHandle(env->me_fmh);
5380 if (env->me_rpmutex) CloseHandle(env->me_rpmutex);
5382 pthread_mutex_destroy(&env->me_rpmutex);
5386 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
5390 mdb_env_close(MDB_env *env)
5397 VGMEMP_DESTROY(env);
5398 while ((dp = env->me_dpages) != NULL) {
5399 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
5400 env->me_dpages = dp->mp_next;
5404 mdb_env_close0(env, 0);
5408 /** Compare two items pointing at aligned mdb_size_t's */
5410 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
5412 return (*(mdb_size_t *)a->mv_data < *(mdb_size_t *)b->mv_data) ? -1 :
5413 *(mdb_size_t *)a->mv_data > *(mdb_size_t *)b->mv_data;
5416 /** Compare two items pointing at aligned unsigned int's.
5418 * This is also set as #MDB_INTEGERDUP|#MDB_DUPFIXED's #MDB_dbx.%md_dcmp,
5419 * but #mdb_cmp_clong() is called instead if the data type is mdb_size_t.
5422 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
5424 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
5425 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
5428 /** Compare two items pointing at unsigned ints of unknown alignment.
5429 * Nodes and keys are guaranteed to be 2-byte aligned.
5432 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
5434 #if BYTE_ORDER == LITTLE_ENDIAN
5435 unsigned short *u, *c;
5438 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5439 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
5442 } while(!x && u > (unsigned short *)a->mv_data);
5445 unsigned short *u, *c, *end;
5448 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5449 u = (unsigned short *)a->mv_data;
5450 c = (unsigned short *)b->mv_data;
5453 } while(!x && u < end);
5458 /** Compare two items lexically */
5460 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
5467 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5473 diff = memcmp(a->mv_data, b->mv_data, len);
5474 return diff ? diff : len_diff<0 ? -1 : len_diff;
5477 /** Compare two items in reverse byte order */
5479 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
5481 const unsigned char *p1, *p2, *p1_lim;
5485 p1_lim = (const unsigned char *)a->mv_data;
5486 p1 = (const unsigned char *)a->mv_data + a->mv_size;
5487 p2 = (const unsigned char *)b->mv_data + b->mv_size;
5489 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5495 while (p1 > p1_lim) {
5496 diff = *--p1 - *--p2;
5500 return len_diff<0 ? -1 : len_diff;
5503 /** Search for key within a page, using binary search.
5504 * Returns the smallest entry larger or equal to the key.
5505 * If exactp is non-null, stores whether the found entry was an exact match
5506 * in *exactp (1 or 0).
5507 * Updates the cursor index with the index of the found entry.
5508 * If no entry larger or equal to the key is found, returns NULL.
5511 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
5513 unsigned int i = 0, nkeys;
5516 MDB_page *mp = mc->mc_pg[mc->mc_top];
5517 MDB_node *node = NULL;
5522 nkeys = NUMKEYS(mp);
5524 DPRINTF(("searching %u keys in %s %spage %"Y"u",
5525 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
5528 low = IS_LEAF(mp) ? 0 : 1;
5530 cmp = mc->mc_dbx->md_cmp;
5532 /* Branch pages have no data, so if using integer keys,
5533 * alignment is guaranteed. Use faster mdb_cmp_int.
5535 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
5536 if (NODEPTR(mp, 1)->mn_ksize == sizeof(mdb_size_t))
5543 nodekey.mv_size = mc->mc_db->md_pad;
5544 node = NODEPTR(mp, 0); /* fake */
5545 while (low <= high) {
5546 i = (low + high) >> 1;
5547 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
5548 rc = cmp(key, &nodekey);
5549 DPRINTF(("found leaf index %u [%s], rc = %i",
5550 i, DKEY(&nodekey), rc));
5559 while (low <= high) {
5560 i = (low + high) >> 1;
5562 node = NODEPTR(mp, i);
5563 nodekey.mv_size = NODEKSZ(node);
5564 nodekey.mv_data = NODEKEY(node);
5566 rc = cmp(key, &nodekey);
5569 DPRINTF(("found leaf index %u [%s], rc = %i",
5570 i, DKEY(&nodekey), rc));
5572 DPRINTF(("found branch index %u [%s -> %"Y"u], rc = %i",
5573 i, DKEY(&nodekey), NODEPGNO(node), rc));
5584 if (rc > 0) { /* Found entry is less than the key. */
5585 i++; /* Skip to get the smallest entry larger than key. */
5587 node = NODEPTR(mp, i);
5590 *exactp = (rc == 0 && nkeys > 0);
5591 /* store the key index */
5592 mc->mc_ki[mc->mc_top] = i;
5594 /* There is no entry larger or equal to the key. */
5597 /* nodeptr is fake for LEAF2 */
5603 mdb_cursor_adjust(MDB_cursor *mc, func)
5607 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5608 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
5615 /** Pop a page off the top of the cursor's stack. */
5617 mdb_cursor_pop(MDB_cursor *mc)
5620 DPRINTF(("popping page %"Y"u off db %d cursor %p",
5621 mc->mc_pg[mc->mc_top]->mp_pgno, DDBI(mc), (void *) mc));
5627 mc->mc_flags &= ~C_INITIALIZED;
5632 /** Push a page onto the top of the cursor's stack. */
5634 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
5636 DPRINTF(("pushing page %"Y"u on db %d cursor %p", mp->mp_pgno,
5637 DDBI(mc), (void *) mc));
5639 if (mc->mc_snum >= CURSOR_STACK) {
5640 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5641 return MDB_CURSOR_FULL;
5644 mc->mc_top = mc->mc_snum++;
5645 mc->mc_pg[mc->mc_top] = mp;
5646 mc->mc_ki[mc->mc_top] = 0;
5652 /** Map a read-only page.
5653 * There are two levels of tracking in use, a per-txn list and a per-env list.
5654 * ref'ing and unref'ing the per-txn list is faster since it requires no
5655 * locking. Pages are cached in the per-env list for global reuse, and a lock
5656 * is required. Pages are not immediately unmapped when their refcnt goes to
5657 * zero; they hang around in case they will be reused again soon.
5659 * When the per-txn list gets full, all pages with refcnt=0 are purged from the
5660 * list and their refcnts in the per-env list are decremented.
5662 * When the per-env list gets full, all pages with refcnt=0 are purged from the
5663 * list and their pages are unmapped.
5665 * @note "full" means the list has reached its respective rpcheck threshold.
5666 * This threshold slowly raises if no pages could be purged on a given check,
5667 * and returns to its original value when enough pages were purged.
5669 * If purging doesn't free any slots, filling the per-txn list will return
5670 * MDB_TXN_FULL, and filling the per-env list returns MDB_MAP_FULL.
5672 * Reference tracking in a txn is imperfect, pages can linger with non-zero
5673 * refcnt even without active references. It was deemed to be too invasive
5674 * to add unrefs in every required location. However, all pages are unref'd
5675 * at the end of the transaction. This guarantees that no stale references
5676 * linger in the per-env list.
5678 * Usually we map chunks of 16 pages at a time, but if an overflow page begins
5679 * at the tail of the chunk we extend the chunk to include the entire overflow
5680 * page. Unfortunately, pages can be turned into overflow pages after their
5681 * chunk was already mapped. In that case we must remap the chunk if the
5682 * overflow page is referenced. If the chunk's refcnt is 0 we can just remap
5683 * it, otherwise we temporarily map a new chunk just for the overflow page.
5685 * @note this chunk handling means we cannot guarantee that a data item
5686 * returned from the DB will stay alive for the duration of the transaction:
5687 * We unref pages as soon as a cursor moves away from the page
5688 * A subsequent op may cause a purge, which may unmap any unref'd chunks
5689 * The caller must copy the data if it must be used later in the same txn.
5691 * Also - our reference counting revolves around cursors, but overflow pages
5692 * aren't pointed to by a cursor's page stack. We have to remember them
5693 * explicitly, in the added mc_ovpg field. A single cursor can only hold a
5694 * reference to one overflow page at a time.
5696 * @param[in] txn the transaction for this access.
5697 * @param[in] pgno the page number for the page to retrieve.
5698 * @param[out] ret address of a pointer where the page's address will be stored.
5699 * @return 0 on success, non-zero on failure.
5702 mdb_rpage_get(MDB_txn *txn, pgno_t pg0, MDB_page **ret)
5704 MDB_env *env = txn->mt_env;
5706 MDB_ID3L tl = txn->mt_rpages;
5707 MDB_ID3L el = env->me_rpages;
5711 int rc, retries = 1;
5715 #define SET_OFF(off,val) off.QuadPart = val
5716 #define MAP(rc,env,addr,len,off) \
5718 rc = NtMapViewOfSection(env->me_fmh, GetCurrentProcess(), &addr, 0, \
5719 len, &off, &len, ViewUnmap, (env->me_flags & MDB_RDONLY) ? 0 : MEM_RESERVE, PAGE_READONLY); \
5720 if (rc) rc = mdb_nt2win32(rc)
5724 #define SET_OFF(off,val) off = val
5725 #define MAP(rc,env,addr,len,off) \
5726 addr = mmap(NULL, len, PROT_READ, MAP_SHARED, env->me_fd, off); \
5727 rc = (addr == MAP_FAILED) ? errno : 0
5730 /* remember the offset of the actual page number, so we can
5731 * return the correct pointer at the end.
5733 rem = pg0 & (MDB_RPAGE_CHUNK-1);
5737 x = mdb_mid3l_search(tl, pgno);
5738 if (x <= tl[0].mid && tl[x].mid == pgno) {
5739 if (x != tl[0].mid && tl[x+1].mid == pg0)
5741 /* check for overflow size */
5742 p = (MDB_page *)((char *)tl[x].mptr + rem * env->me_psize);
5743 if (IS_OVERFLOW(p) && p->mp_pages + rem > tl[x].mcnt) {
5744 id3.mcnt = p->mp_pages + rem;
5745 len = id3.mcnt * env->me_psize;
5746 SET_OFF(off, pgno * env->me_psize);
5747 MAP(rc, env, id3.mptr, len, off);
5750 /* check for local-only page */
5752 mdb_tassert(txn, tl[x].mid != pg0);
5753 /* hope there's room to insert this locally.
5754 * setting mid here tells later code to just insert
5755 * this id3 instead of searching for a match.
5760 /* ignore the mapping we got from env, use new one */
5761 tl[x].mptr = id3.mptr;
5762 tl[x].mcnt = id3.mcnt;
5763 /* if no active ref, see if we can replace in env */
5766 pthread_mutex_lock(&env->me_rpmutex);
5767 i = mdb_mid3l_search(el, tl[x].mid);
5768 if (el[i].mref == 1) {
5769 /* just us, replace it */
5770 munmap(el[i].mptr, el[i].mcnt * env->me_psize);
5771 el[i].mptr = tl[x].mptr;
5772 el[i].mcnt = tl[x].mcnt;
5774 /* there are others, remove ourself */
5777 pthread_mutex_unlock(&env->me_rpmutex);
5781 id3.mptr = tl[x].mptr;
5782 id3.mcnt = tl[x].mcnt;
5788 if (tl[0].mid >= MDB_TRPAGE_MAX - txn->mt_rpcheck) {
5790 /* purge unref'd pages from our list and unref in env */
5791 pthread_mutex_lock(&env->me_rpmutex);
5794 for (i=1; i<=tl[0].mid; i++) {
5797 /* tmp overflow pages don't go to env */
5798 if (tl[i].mid & (MDB_RPAGE_CHUNK-1)) {
5799 munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
5802 x = mdb_mid3l_search(el, tl[i].mid);
5806 pthread_mutex_unlock(&env->me_rpmutex);
5808 /* we didn't find any unref'd chunks.
5809 * if we're out of room, fail.
5811 if (tl[0].mid >= MDB_TRPAGE_MAX)
5812 return MDB_TXN_FULL;
5813 /* otherwise, raise threshold for next time around
5816 txn->mt_rpcheck /= 2;
5818 /* we found some unused; consolidate the list */
5819 for (i=y+1; i<= tl[0].mid; i++)
5823 /* decrease the check threshold toward its original value */
5824 if (!txn->mt_rpcheck)
5825 txn->mt_rpcheck = 1;
5826 while (txn->mt_rpcheck < tl[0].mid && txn->mt_rpcheck < MDB_TRPAGE_SIZE/2)
5827 txn->mt_rpcheck *= 2;
5830 if (tl[0].mid < MDB_TRPAGE_SIZE) {
5834 /* don't map past last written page in read-only envs */
5835 if ((env->me_flags & MDB_RDONLY) && pgno + MDB_RPAGE_CHUNK-1 > txn->mt_last_pgno)
5836 id3.mcnt = txn->mt_last_pgno + 1 - pgno;
5838 id3.mcnt = MDB_RPAGE_CHUNK;
5839 len = id3.mcnt * env->me_psize;
5842 /* search for page in env */
5843 pthread_mutex_lock(&env->me_rpmutex);
5844 x = mdb_mid3l_search(el, pgno);
5845 if (x <= el[0].mid && el[x].mid == pgno) {
5846 id3.mptr = el[x].mptr;
5847 id3.mcnt = el[x].mcnt;
5848 /* check for overflow size */
5849 p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
5850 if (IS_OVERFLOW(p) && p->mp_pages + rem > id3.mcnt) {
5851 id3.mcnt = p->mp_pages + rem;
5852 len = id3.mcnt * env->me_psize;
5853 SET_OFF(off, pgno * env->me_psize);
5854 MAP(rc, env, id3.mptr, len, off);
5858 munmap(el[x].mptr, env->me_psize * el[x].mcnt);
5859 el[x].mptr = id3.mptr;
5860 el[x].mcnt = id3.mcnt;
5863 pthread_mutex_unlock(&env->me_rpmutex);
5868 pthread_mutex_unlock(&env->me_rpmutex);
5871 if (el[0].mid >= MDB_ERPAGE_MAX - env->me_rpcheck) {
5872 /* purge unref'd pages */
5874 for (i=1; i<=el[0].mid; i++) {
5877 munmap(el[i].mptr, env->me_psize * el[i].mcnt);
5882 /* see if we can unref some local pages */
5887 if (el[0].mid >= MDB_ERPAGE_MAX) {
5888 pthread_mutex_unlock(&env->me_rpmutex);
5889 return MDB_MAP_FULL;
5891 env->me_rpcheck /= 2;
5893 for (i=y+1; i<= el[0].mid; i++)
5897 if (!env->me_rpcheck)
5898 env->me_rpcheck = 1;
5899 while (env->me_rpcheck < el[0].mid && env->me_rpcheck < MDB_ERPAGE_SIZE/2)
5900 env->me_rpcheck *= 2;
5903 SET_OFF(off, pgno * env->me_psize);
5904 MAP(rc, env, id3.mptr, len, off);
5907 pthread_mutex_unlock(&env->me_rpmutex);
5910 /* check for overflow size */
5911 p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
5912 if (IS_OVERFLOW(p) && p->mp_pages + rem > id3.mcnt) {
5913 id3.mcnt = p->mp_pages + rem;
5914 munmap(id3.mptr, len);
5915 len = id3.mcnt * env->me_psize;
5916 MAP(rc, env, id3.mptr, len, off);
5920 mdb_mid3l_insert(el, &id3);
5921 pthread_mutex_unlock(&env->me_rpmutex);
5923 mdb_mid3l_insert(tl, &id3);
5925 return MDB_TXN_FULL;
5928 p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
5929 #if MDB_DEBUG /* we don't need this check any more */
5930 if (IS_OVERFLOW(p)) {
5931 mdb_tassert(txn, p->mp_pages + rem <= id3.mcnt);
5939 /** Find the address of the page corresponding to a given page number.
5940 * @param[in] mc the cursor accessing the page.
5941 * @param[in] pgno the page number for the page to retrieve.
5942 * @param[out] ret address of a pointer where the page's address will be stored.
5943 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
5944 * @return 0 on success, non-zero on failure.
5947 mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **ret, int *lvl)
5949 MDB_txn *txn = mc->mc_txn;
5951 MDB_env *env = txn->mt_env;
5956 if (! (mc->mc_flags & (C_ORIG_RDONLY|C_WRITEMAP))) {
5960 MDB_ID2L dl = tx2->mt_u.dirty_list;
5962 /* Spilled pages were dirtied in this txn and flushed
5963 * because the dirty list got full. Bring this page
5964 * back in from the map (but don't unspill it here,
5965 * leave that unless page_touch happens again).
5967 if (tx2->mt_spill_pgs) {
5968 MDB_ID pn = pgno << 1;
5969 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
5970 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
5972 int rc = mdb_rpage_get(txn, pgno, &p);
5976 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5982 unsigned x = mdb_mid2l_search(dl, pgno);
5983 if (x <= dl[0].mid && dl[x].mid == pgno) {
5989 } while ((tx2 = tx2->mt_parent) != NULL);
5992 if (pgno < txn->mt_next_pgno) {
5996 int rc = mdb_rpage_get(txn, pgno, &p);
6001 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
6004 DPRINTF(("page %"Y"u not found", pgno));
6005 txn->mt_flags |= MDB_TXN_ERROR;
6006 return MDB_PAGE_NOTFOUND;
6016 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
6017 * The cursor is at the root page, set up the rest of it.
6020 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
6022 MDB_page *mp = mc->mc_pg[mc->mc_top];
6026 while (IS_BRANCH(mp)) {
6030 DPRINTF(("branch page %"Y"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
6031 /* Don't assert on branch pages in the FreeDB. We can get here
6032 * while in the process of rebalancing a FreeDB branch page; we must
6033 * let that proceed. ITS#8336
6035 mdb_cassert(mc, !mc->mc_dbi || NUMKEYS(mp) > 1);
6036 DPRINTF(("found index 0 to page %"Y"u", NODEPGNO(NODEPTR(mp, 0))));
6038 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
6040 if (flags & MDB_PS_LAST)
6041 i = NUMKEYS(mp) - 1;
6044 node = mdb_node_search(mc, key, &exact);
6046 i = NUMKEYS(mp) - 1;
6048 i = mc->mc_ki[mc->mc_top];
6050 mdb_cassert(mc, i > 0);
6054 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
6057 mdb_cassert(mc, i < NUMKEYS(mp));
6058 node = NODEPTR(mp, i);
6060 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
6063 mc->mc_ki[mc->mc_top] = i;
6064 if ((rc = mdb_cursor_push(mc, mp)))
6067 if (flags & MDB_PS_MODIFY) {
6068 if ((rc = mdb_page_touch(mc)) != 0)
6070 mp = mc->mc_pg[mc->mc_top];
6075 DPRINTF(("internal error, index points to a %02X page!?",
6077 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6078 return MDB_CORRUPTED;
6081 DPRINTF(("found leaf page %"Y"u for key [%s]", mp->mp_pgno,
6082 key ? DKEY(key) : "null"));
6083 mc->mc_flags |= C_INITIALIZED;
6084 mc->mc_flags &= ~C_EOF;
6089 /** Search for the lowest key under the current branch page.
6090 * This just bypasses a NUMKEYS check in the current page
6091 * before calling mdb_page_search_root(), because the callers
6092 * are all in situations where the current page is known to
6096 mdb_page_search_lowest(MDB_cursor *mc)
6098 MDB_page *mp = mc->mc_pg[mc->mc_top];
6099 MDB_node *node = NODEPTR(mp, 0);
6102 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
6105 mc->mc_ki[mc->mc_top] = 0;
6106 if ((rc = mdb_cursor_push(mc, mp)))
6108 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
6111 /** Search for the page a given key should be in.
6112 * Push it and its parent pages on the cursor stack.
6113 * @param[in,out] mc the cursor for this operation.
6114 * @param[in] key the key to search for, or NULL for first/last page.
6115 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
6116 * are touched (updated with new page numbers).
6117 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
6118 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
6119 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
6120 * @return 0 on success, non-zero on failure.
6123 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
6128 /* Make sure the txn is still viable, then find the root from
6129 * the txn's db table and set it as the root of the cursor's stack.
6131 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED) {
6132 DPUTS("transaction may not be used now");
6135 /* Make sure we're using an up-to-date root */
6136 if (*mc->mc_dbflag & DB_STALE) {
6138 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
6140 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
6141 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
6148 MDB_node *leaf = mdb_node_search(&mc2,
6149 &mc->mc_dbx->md_name, &exact);
6151 return MDB_NOTFOUND;
6152 if ((leaf->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
6153 return MDB_INCOMPATIBLE; /* not a named DB */
6154 rc = mdb_node_read(&mc2, leaf, &data);
6157 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
6159 /* The txn may not know this DBI, or another process may
6160 * have dropped and recreated the DB with other flags.
6162 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
6163 return MDB_INCOMPATIBLE;
6164 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
6166 *mc->mc_dbflag &= ~DB_STALE;
6168 root = mc->mc_db->md_root;
6170 if (root == P_INVALID) { /* Tree is empty. */
6171 DPUTS("tree is empty");
6172 return MDB_NOTFOUND;
6176 mdb_cassert(mc, root > 1);
6177 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root) {
6180 MDB_PAGE_UNREF(mc->mc_txn, mc->mc_pg[0]);
6182 if ((rc = mdb_page_get(mc, root, &mc->mc_pg[0], NULL)) != 0)
6189 for (i=1; i<mc->mc_snum; i++)
6190 MDB_PAGE_UNREF(mc->mc_txn, mc->mc_pg[i]);
6196 DPRINTF(("db %d root page %"Y"u has flags 0x%X",
6197 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
6199 if (flags & MDB_PS_MODIFY) {
6200 if ((rc = mdb_page_touch(mc)))
6204 if (flags & MDB_PS_ROOTONLY)
6207 return mdb_page_search_root(mc, key, flags);
6211 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
6213 MDB_txn *txn = mc->mc_txn;
6214 pgno_t pg = mp->mp_pgno;
6215 unsigned x = 0, ovpages = mp->mp_pages;
6216 MDB_env *env = txn->mt_env;
6217 MDB_IDL sl = txn->mt_spill_pgs;
6218 MDB_ID pn = pg << 1;
6221 DPRINTF(("free ov page %"Y"u (%d)", pg, ovpages));
6222 /* If the page is dirty or on the spill list we just acquired it,
6223 * so we should give it back to our current free list, if any.
6224 * Otherwise put it onto the list of pages we freed in this txn.
6226 * Won't create me_pghead: me_pglast must be inited along with it.
6227 * Unsupported in nested txns: They would need to hide the page
6228 * range in ancestor txns' dirty and spilled lists.
6230 if (env->me_pghead &&
6232 ((mp->mp_flags & P_DIRTY) ||
6233 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
6237 MDB_ID2 *dl, ix, iy;
6238 rc = mdb_midl_need(&env->me_pghead, ovpages);
6241 if (!(mp->mp_flags & P_DIRTY)) {
6242 /* This page is no longer spilled */
6249 /* Remove from dirty list */
6250 dl = txn->mt_u.dirty_list;
6252 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
6258 mdb_cassert(mc, x > 1);
6260 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
6261 txn->mt_flags |= MDB_TXN_ERROR;
6262 return MDB_CORRUPTED;
6265 txn->mt_dirty_room++;
6266 if (!(env->me_flags & MDB_WRITEMAP))
6267 mdb_dpage_free(env, mp);
6269 /* Insert in me_pghead */
6270 mop = env->me_pghead;
6271 j = mop[0] + ovpages;
6272 for (i = mop[0]; i && mop[i] < pg; i--)
6278 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
6282 mc->mc_db->md_overflow_pages -= ovpages;
6286 /** Return the data associated with a given node.
6287 * @param[in] mc The cursor for this operation.
6288 * @param[in] leaf The node being read.
6289 * @param[out] data Updated to point to the node's data.
6290 * @return 0 on success, non-zero on failure.
6293 mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data)
6295 MDB_page *omp; /* overflow page */
6301 MDB_PAGE_UNREF(mc->mc_txn, mc->mc_ovpg);
6305 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6306 data->mv_size = NODEDSZ(leaf);
6307 data->mv_data = NODEDATA(leaf);
6311 /* Read overflow data.
6313 data->mv_size = NODEDSZ(leaf);
6314 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
6315 if ((rc = mdb_page_get(mc, pgno, &omp, NULL)) != 0) {
6316 DPRINTF(("read overflow page %"Y"u failed", pgno));
6319 data->mv_data = METADATA(omp);
6328 mdb_get(MDB_txn *txn, MDB_dbi dbi,
6329 MDB_val *key, MDB_val *data)
6336 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
6338 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
6341 if (txn->mt_flags & MDB_TXN_BLOCKED)
6344 mdb_cursor_init(&mc, txn, dbi, &mx);
6345 rc = mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
6348 /* unref all the pages - caller must copy the data
6349 * before doing anything else
6351 mdb_cursor_unref(&mc);
6357 /** Find a sibling for a page.
6358 * Replaces the page at the top of the cursor's stack with the
6359 * specified sibling, if one exists.
6360 * @param[in] mc The cursor for this operation.
6361 * @param[in] move_right Non-zero if the right sibling is requested,
6362 * otherwise the left sibling.
6363 * @return 0 on success, non-zero on failure.
6366 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
6375 if (mc->mc_snum < 2) {
6376 return MDB_NOTFOUND; /* root has no siblings */
6380 op = mc->mc_pg[mc->mc_top];
6383 DPRINTF(("parent page is page %"Y"u, index %u",
6384 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
6386 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6387 : (mc->mc_ki[mc->mc_top] == 0)) {
6388 DPRINTF(("no more keys left, moving to %s sibling",
6389 move_right ? "right" : "left"));
6390 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
6391 /* undo cursor_pop before returning */
6398 mc->mc_ki[mc->mc_top]++;
6400 mc->mc_ki[mc->mc_top]--;
6401 DPRINTF(("just moving to %s index key %u",
6402 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
6404 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
6406 MDB_PAGE_UNREF(mc->mc_txn, op);
6408 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6409 if ((rc = mdb_page_get(mc, NODEPGNO(indx), &mp, NULL)) != 0) {
6410 /* mc will be inconsistent if caller does mc_snum++ as above */
6411 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
6415 mdb_cursor_push(mc, mp);
6417 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
6422 /** Move the cursor to the next data item. */
6424 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
6430 if ((mc->mc_flags & C_EOF) ||
6431 ((mc->mc_flags & C_DEL) && op == MDB_NEXT_DUP)) {
6432 return MDB_NOTFOUND;
6434 if (!(mc->mc_flags & C_INITIALIZED))
6435 return mdb_cursor_first(mc, key, data);
6437 mp = mc->mc_pg[mc->mc_top];
6439 if (mc->mc_db->md_flags & MDB_DUPSORT) {
6440 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6441 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6442 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
6443 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
6444 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
6445 if (rc == MDB_SUCCESS)
6446 MDB_GET_KEY(leaf, key);
6452 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6453 mdb_cursor_unref(&mc->mc_xcursor->mx_cursor);
6458 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6459 if (op == MDB_NEXT_DUP)
6460 return MDB_NOTFOUND;
6464 DPRINTF(("cursor_next: top page is %"Y"u in cursor %p",
6465 mdb_dbg_pgno(mp), (void *) mc));
6466 if (mc->mc_flags & C_DEL) {
6467 mc->mc_flags ^= C_DEL;
6471 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
6472 DPUTS("=====> move to next sibling page");
6473 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
6474 mc->mc_flags |= C_EOF;
6477 mp = mc->mc_pg[mc->mc_top];
6478 DPRINTF(("next page is %"Y"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
6480 mc->mc_ki[mc->mc_top]++;
6483 DPRINTF(("==> cursor points to page %"Y"u with %u keys, key index %u",
6484 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
6487 key->mv_size = mc->mc_db->md_pad;
6488 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6492 mdb_cassert(mc, IS_LEAF(mp));
6493 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6495 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6496 mdb_xcursor_init1(mc, leaf);
6499 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6502 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6503 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6504 if (rc != MDB_SUCCESS)
6509 MDB_GET_KEY(leaf, key);
6513 /** Move the cursor to the previous data item. */
6515 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
6521 if (!(mc->mc_flags & C_INITIALIZED)) {
6522 rc = mdb_cursor_last(mc, key, data);
6525 mc->mc_ki[mc->mc_top]++;
6528 mp = mc->mc_pg[mc->mc_top];
6530 if (mc->mc_db->md_flags & MDB_DUPSORT) {
6531 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6532 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6533 if (op == MDB_PREV || op == MDB_PREV_DUP) {
6534 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
6535 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
6536 if (rc == MDB_SUCCESS) {
6537 MDB_GET_KEY(leaf, key);
6538 mc->mc_flags &= ~C_EOF;
6545 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6546 mdb_cursor_unref(&mc->mc_xcursor->mx_cursor);
6551 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6552 if (op == MDB_PREV_DUP)
6553 return MDB_NOTFOUND;
6557 DPRINTF(("cursor_prev: top page is %"Y"u in cursor %p",
6558 mdb_dbg_pgno(mp), (void *) mc));
6560 mc->mc_flags &= ~(C_EOF|C_DEL);
6562 if (mc->mc_ki[mc->mc_top] == 0) {
6563 DPUTS("=====> move to prev sibling page");
6564 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
6567 mp = mc->mc_pg[mc->mc_top];
6568 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
6569 DPRINTF(("prev page is %"Y"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
6571 mc->mc_ki[mc->mc_top]--;
6573 mc->mc_flags &= ~C_EOF;
6575 DPRINTF(("==> cursor points to page %"Y"u with %u keys, key index %u",
6576 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
6579 key->mv_size = mc->mc_db->md_pad;
6580 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6584 mdb_cassert(mc, IS_LEAF(mp));
6585 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6587 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6588 mdb_xcursor_init1(mc, leaf);
6591 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6594 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6595 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
6596 if (rc != MDB_SUCCESS)
6601 MDB_GET_KEY(leaf, key);
6605 /** Set the cursor on a specific data item. */
6607 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6608 MDB_cursor_op op, int *exactp)
6612 MDB_node *leaf = NULL;
6615 if (key->mv_size == 0)
6616 return MDB_BAD_VALSIZE;
6619 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6621 /* See if we're already on the right page */
6622 if (mc->mc_flags & C_INITIALIZED) {
6625 mp = mc->mc_pg[mc->mc_top];
6627 mc->mc_ki[mc->mc_top] = 0;
6628 return MDB_NOTFOUND;
6630 if (mp->mp_flags & P_LEAF2) {
6631 nodekey.mv_size = mc->mc_db->md_pad;
6632 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
6634 leaf = NODEPTR(mp, 0);
6635 MDB_GET_KEY2(leaf, nodekey);
6637 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6639 /* Probably happens rarely, but first node on the page
6640 * was the one we wanted.
6642 mc->mc_ki[mc->mc_top] = 0;
6649 unsigned int nkeys = NUMKEYS(mp);
6651 if (mp->mp_flags & P_LEAF2) {
6652 nodekey.mv_data = LEAF2KEY(mp,
6653 nkeys-1, nodekey.mv_size);
6655 leaf = NODEPTR(mp, nkeys-1);
6656 MDB_GET_KEY2(leaf, nodekey);
6658 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6660 /* last node was the one we wanted */
6661 mc->mc_ki[mc->mc_top] = nkeys-1;
6667 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
6668 /* This is definitely the right page, skip search_page */
6669 if (mp->mp_flags & P_LEAF2) {
6670 nodekey.mv_data = LEAF2KEY(mp,
6671 mc->mc_ki[mc->mc_top], nodekey.mv_size);
6673 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6674 MDB_GET_KEY2(leaf, nodekey);
6676 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6678 /* current node was the one we wanted */
6688 /* If any parents have right-sibs, search.
6689 * Otherwise, there's nothing further.
6691 for (i=0; i<mc->mc_top; i++)
6693 NUMKEYS(mc->mc_pg[i])-1)
6695 if (i == mc->mc_top) {
6696 /* There are no other pages */
6697 mc->mc_ki[mc->mc_top] = nkeys;
6698 return MDB_NOTFOUND;
6702 /* There are no other pages */
6703 mc->mc_ki[mc->mc_top] = 0;
6704 if (op == MDB_SET_RANGE && !exactp) {
6708 return MDB_NOTFOUND;
6714 rc = mdb_page_search(mc, key, 0);
6715 if (rc != MDB_SUCCESS)
6718 mp = mc->mc_pg[mc->mc_top];
6719 mdb_cassert(mc, IS_LEAF(mp));
6722 leaf = mdb_node_search(mc, key, exactp);
6723 if (exactp != NULL && !*exactp) {
6724 /* MDB_SET specified and not an exact match. */
6725 return MDB_NOTFOUND;
6729 DPUTS("===> inexact leaf not found, goto sibling");
6730 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
6731 mc->mc_flags |= C_EOF;
6732 return rc; /* no entries matched */
6734 mp = mc->mc_pg[mc->mc_top];
6735 mdb_cassert(mc, IS_LEAF(mp));
6736 leaf = NODEPTR(mp, 0);
6740 mc->mc_flags |= C_INITIALIZED;
6741 mc->mc_flags &= ~C_EOF;
6744 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
6745 key->mv_size = mc->mc_db->md_pad;
6746 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6752 if (mc->mc_xcursor && mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6753 mdb_cursor_unref(&mc->mc_xcursor->mx_cursor);
6756 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6757 mdb_xcursor_init1(mc, leaf);
6760 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6761 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
6762 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6765 if (op == MDB_GET_BOTH) {
6771 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
6772 if (rc != MDB_SUCCESS)
6775 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
6778 if ((rc = mdb_node_read(mc, leaf, &olddata)) != MDB_SUCCESS)
6780 dcmp = mc->mc_dbx->md_dcmp;
6781 #if UINT_MAX < SIZE_MAX || defined(MDB_VL32)
6782 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(mdb_size_t))
6783 dcmp = mdb_cmp_clong;
6785 rc = dcmp(data, &olddata);
6787 if (op == MDB_GET_BOTH || rc > 0)
6788 return MDB_NOTFOUND;
6795 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6796 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6801 /* The key already matches in all other cases */
6802 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
6803 MDB_GET_KEY(leaf, key);
6804 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
6809 /** Move the cursor to the first item in the database. */
6811 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6816 if (mc->mc_xcursor) {
6818 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6819 mdb_cursor_unref(&mc->mc_xcursor->mx_cursor);
6822 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6825 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6826 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
6827 if (rc != MDB_SUCCESS)
6830 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6832 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
6833 mc->mc_flags |= C_INITIALIZED;
6834 mc->mc_flags &= ~C_EOF;
6836 mc->mc_ki[mc->mc_top] = 0;
6838 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6839 key->mv_size = mc->mc_db->md_pad;
6840 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
6845 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6846 mdb_xcursor_init1(mc, leaf);
6847 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6851 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6855 MDB_GET_KEY(leaf, key);
6859 /** Move the cursor to the last item in the database. */
6861 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6866 if (mc->mc_xcursor) {
6868 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6869 mdb_cursor_unref(&mc->mc_xcursor->mx_cursor);
6872 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6875 if (!(mc->mc_flags & C_EOF)) {
6877 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6878 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
6879 if (rc != MDB_SUCCESS)
6882 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6885 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
6886 mc->mc_flags |= C_INITIALIZED|C_EOF;
6887 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6889 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6890 key->mv_size = mc->mc_db->md_pad;
6891 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
6896 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6897 mdb_xcursor_init1(mc, leaf);
6898 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
6902 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6907 MDB_GET_KEY(leaf, key);
6912 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6917 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
6922 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
6926 case MDB_GET_CURRENT:
6927 if (!(mc->mc_flags & C_INITIALIZED)) {
6930 MDB_page *mp = mc->mc_pg[mc->mc_top];
6931 int nkeys = NUMKEYS(mp);
6932 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
6933 mc->mc_ki[mc->mc_top] = nkeys;
6939 key->mv_size = mc->mc_db->md_pad;
6940 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6942 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6943 MDB_GET_KEY(leaf, key);
6945 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6946 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
6948 rc = mdb_node_read(mc, leaf, data);
6955 case MDB_GET_BOTH_RANGE:
6960 if (mc->mc_xcursor == NULL) {
6961 rc = MDB_INCOMPATIBLE;
6971 rc = mdb_cursor_set(mc, key, data, op,
6972 op == MDB_SET_RANGE ? NULL : &exact);
6975 case MDB_GET_MULTIPLE:
6976 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
6980 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6981 rc = MDB_INCOMPATIBLE;
6985 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
6986 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
6989 case MDB_NEXT_MULTIPLE:
6994 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6995 rc = MDB_INCOMPATIBLE;
6998 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
6999 if (rc == MDB_SUCCESS) {
7000 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
7003 mx = &mc->mc_xcursor->mx_cursor;
7004 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
7006 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
7007 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
7013 case MDB_PREV_MULTIPLE:
7018 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7019 rc = MDB_INCOMPATIBLE;
7022 if (!(mc->mc_flags & C_INITIALIZED))
7023 rc = mdb_cursor_last(mc, key, data);
7026 if (rc == MDB_SUCCESS) {
7027 MDB_cursor *mx = &mc->mc_xcursor->mx_cursor;
7028 if (mx->mc_flags & C_INITIALIZED) {
7029 rc = mdb_cursor_sibling(mx, 0);
7030 if (rc == MDB_SUCCESS)
7039 case MDB_NEXT_NODUP:
7040 rc = mdb_cursor_next(mc, key, data, op);
7044 case MDB_PREV_NODUP:
7045 rc = mdb_cursor_prev(mc, key, data, op);
7048 rc = mdb_cursor_first(mc, key, data);
7051 mfunc = mdb_cursor_first;
7053 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
7057 if (mc->mc_xcursor == NULL) {
7058 rc = MDB_INCOMPATIBLE;
7062 MDB_node *leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7063 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7064 MDB_GET_KEY(leaf, key);
7065 rc = mdb_node_read(mc, leaf, data);
7069 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
7073 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
7076 rc = mdb_cursor_last(mc, key, data);
7079 mfunc = mdb_cursor_last;
7082 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
7087 if (mc->mc_flags & C_DEL)
7088 mc->mc_flags ^= C_DEL;
7093 /** Touch all the pages in the cursor stack. Set mc_top.
7094 * Makes sure all the pages are writable, before attempting a write operation.
7095 * @param[in] mc The cursor to operate on.
7098 mdb_cursor_touch(MDB_cursor *mc)
7100 int rc = MDB_SUCCESS;
7102 if (mc->mc_dbi >= CORE_DBS && !(*mc->mc_dbflag & DB_DIRTY)) {
7105 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
7107 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
7108 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
7111 *mc->mc_dbflag |= DB_DIRTY;
7116 rc = mdb_page_touch(mc);
7117 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
7118 mc->mc_top = mc->mc_snum-1;
7123 /** Do not spill pages to disk if txn is getting full, may fail instead */
7124 #define MDB_NOSPILL 0x8000
7127 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
7131 MDB_node *leaf = NULL;
7132 MDB_page *fp, *mp, *sub_root = NULL;
7134 MDB_val xdata, *rdata, dkey, olddata;
7136 int do_sub = 0, insert_key, insert_data;
7137 unsigned int mcount = 0, dcount = 0, nospill;
7140 unsigned int nflags;
7143 if (mc == NULL || key == NULL)
7146 env = mc->mc_txn->mt_env;
7148 /* Check this first so counter will always be zero on any
7151 if (flags & MDB_MULTIPLE) {
7152 dcount = data[1].mv_size;
7153 data[1].mv_size = 0;
7154 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
7155 return MDB_INCOMPATIBLE;
7158 nospill = flags & MDB_NOSPILL;
7159 flags &= ~MDB_NOSPILL;
7161 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
7162 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7164 if (key->mv_size-1 >= ENV_MAXKEY(env))
7165 return MDB_BAD_VALSIZE;
7167 #if SIZE_MAX > MAXDATASIZE
7168 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
7169 return MDB_BAD_VALSIZE;
7171 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
7172 return MDB_BAD_VALSIZE;
7175 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
7176 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
7180 if (flags == MDB_CURRENT) {
7181 if (!(mc->mc_flags & C_INITIALIZED))
7184 } else if (mc->mc_db->md_root == P_INVALID) {
7185 /* new database, cursor has nothing to point to */
7188 mc->mc_flags &= ~C_INITIALIZED;
7193 if (flags & MDB_APPEND) {
7195 rc = mdb_cursor_last(mc, &k2, &d2);
7197 rc = mc->mc_dbx->md_cmp(key, &k2);
7200 mc->mc_ki[mc->mc_top]++;
7202 /* new key is <= last key */
7207 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
7209 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
7210 DPRINTF(("duplicate key [%s]", DKEY(key)));
7212 return MDB_KEYEXIST;
7214 if (rc && rc != MDB_NOTFOUND)
7218 if (mc->mc_flags & C_DEL)
7219 mc->mc_flags ^= C_DEL;
7221 /* Cursor is positioned, check for room in the dirty list */
7223 if (flags & MDB_MULTIPLE) {
7225 xdata.mv_size = data->mv_size * dcount;
7229 if ((rc2 = mdb_page_spill(mc, key, rdata)))
7233 if (rc == MDB_NO_ROOT) {
7235 /* new database, write a root leaf page */
7236 DPUTS("allocating new root leaf page");
7237 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
7240 mdb_cursor_push(mc, np);
7241 mc->mc_db->md_root = np->mp_pgno;
7242 mc->mc_db->md_depth++;
7243 *mc->mc_dbflag |= DB_DIRTY;
7244 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
7246 np->mp_flags |= P_LEAF2;
7247 mc->mc_flags |= C_INITIALIZED;
7249 /* make sure all cursor pages are writable */
7250 rc2 = mdb_cursor_touch(mc);
7255 insert_key = insert_data = rc;
7257 /* The key does not exist */
7258 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
7259 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
7260 LEAFSIZE(key, data) > env->me_nodemax)
7262 /* Too big for a node, insert in sub-DB. Set up an empty
7263 * "old sub-page" for prep_subDB to expand to a full page.
7265 fp_flags = P_LEAF|P_DIRTY;
7267 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
7268 fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
7269 olddata.mv_size = PAGEHDRSZ;
7273 /* there's only a key anyway, so this is a no-op */
7274 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
7276 unsigned int ksize = mc->mc_db->md_pad;
7277 if (key->mv_size != ksize)
7278 return MDB_BAD_VALSIZE;
7279 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
7280 memcpy(ptr, key->mv_data, ksize);
7282 /* if overwriting slot 0 of leaf, need to
7283 * update branch key if there is a parent page
7285 if (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
7286 unsigned short dtop = 1;
7288 /* slot 0 is always an empty key, find real slot */
7289 while (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
7293 if (mc->mc_ki[mc->mc_top])
7294 rc2 = mdb_update_key(mc, key);
7305 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7306 olddata.mv_size = NODEDSZ(leaf);
7307 olddata.mv_data = NODEDATA(leaf);
7310 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
7311 /* Prepare (sub-)page/sub-DB to accept the new item,
7312 * if needed. fp: old sub-page or a header faking
7313 * it. mp: new (sub-)page. offset: growth in page
7314 * size. xdata: node data with new page or DB.
7316 unsigned i, offset = 0;
7317 mp = fp = xdata.mv_data = env->me_pbuf;
7318 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
7320 /* Was a single item before, must convert now */
7321 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7323 /* Just overwrite the current item */
7324 if (flags == MDB_CURRENT)
7326 dcmp = mc->mc_dbx->md_dcmp;
7327 #if UINT_MAX < SIZE_MAX || defined(MDB_VL32)
7328 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(mdb_size_t))
7329 dcmp = mdb_cmp_clong;
7331 /* does data match? */
7332 if (!dcmp(data, &olddata)) {
7333 if (flags & (MDB_NODUPDATA|MDB_APPENDDUP))
7334 return MDB_KEYEXIST;
7339 /* Back up original data item */
7340 dkey.mv_size = olddata.mv_size;
7341 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
7343 /* Make sub-page header for the dup items, with dummy body */
7344 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
7345 fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
7346 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
7347 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7348 fp->mp_flags |= P_LEAF2;
7349 fp->mp_pad = data->mv_size;
7350 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
7352 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
7353 (dkey.mv_size & 1) + (data->mv_size & 1);
7355 fp->mp_upper = xdata.mv_size - PAGEBASE;
7356 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
7357 } else if (leaf->mn_flags & F_SUBDATA) {
7358 /* Data is on sub-DB, just store it */
7359 flags |= F_DUPDATA|F_SUBDATA;
7362 /* Data is on sub-page */
7363 fp = olddata.mv_data;
7366 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7367 offset = EVEN(NODESIZE + sizeof(indx_t) +
7371 offset = fp->mp_pad;
7372 if (SIZELEFT(fp) < offset) {
7373 offset *= 4; /* space for 4 more */
7376 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
7378 fp->mp_flags |= P_DIRTY;
7379 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
7380 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
7384 xdata.mv_size = olddata.mv_size + offset;
7387 fp_flags = fp->mp_flags;
7388 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
7389 /* Too big for a sub-page, convert to sub-DB */
7390 fp_flags &= ~P_SUBP;
7392 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7393 fp_flags |= P_LEAF2;
7394 dummy.md_pad = fp->mp_pad;
7395 dummy.md_flags = MDB_DUPFIXED;
7396 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
7397 dummy.md_flags |= MDB_INTEGERKEY;
7403 dummy.md_branch_pages = 0;
7404 dummy.md_leaf_pages = 1;
7405 dummy.md_overflow_pages = 0;
7406 dummy.md_entries = NUMKEYS(fp);
7407 xdata.mv_size = sizeof(MDB_db);
7408 xdata.mv_data = &dummy;
7409 if ((rc = mdb_page_alloc(mc, 1, &mp)))
7411 offset = env->me_psize - olddata.mv_size;
7412 flags |= F_DUPDATA|F_SUBDATA;
7413 dummy.md_root = mp->mp_pgno;
7417 mp->mp_flags = fp_flags | P_DIRTY;
7418 mp->mp_pad = fp->mp_pad;
7419 mp->mp_lower = fp->mp_lower;
7420 mp->mp_upper = fp->mp_upper + offset;
7421 if (fp_flags & P_LEAF2) {
7422 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
7424 memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
7425 olddata.mv_size - fp->mp_upper - PAGEBASE);
7426 for (i=0; i<NUMKEYS(fp); i++)
7427 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
7435 mdb_node_del(mc, 0);
7439 /* LMDB passes F_SUBDATA in 'flags' to write a DB record */
7440 if ((leaf->mn_flags ^ flags) & F_SUBDATA)
7441 return MDB_INCOMPATIBLE;
7442 /* overflow page overwrites need special handling */
7443 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7446 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
7448 memcpy(&pg, olddata.mv_data, sizeof(pg));
7449 if ((rc2 = mdb_page_get(mc, pg, &omp, &level)) != 0)
7451 ovpages = omp->mp_pages;
7453 /* Is the ov page large enough? */
7454 if (ovpages >= dpages) {
7455 if (!(omp->mp_flags & P_DIRTY) &&
7456 (level || (env->me_flags & MDB_WRITEMAP)))
7458 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
7461 level = 0; /* dirty in this txn or clean */
7464 if (omp->mp_flags & P_DIRTY) {
7465 /* yes, overwrite it. Note in this case we don't
7466 * bother to try shrinking the page if the new data
7467 * is smaller than the overflow threshold.
7470 /* It is writable only in a parent txn */
7471 size_t sz = (size_t) env->me_psize * ovpages, off;
7472 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
7478 /* Note - this page is already counted in parent's dirty_room */
7479 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
7480 mdb_cassert(mc, rc2 == 0);
7481 /* Currently we make the page look as with put() in the
7482 * parent txn, in case the user peeks at MDB_RESERVEd
7483 * or unused parts. Some users treat ovpages specially.
7485 if (!(flags & MDB_RESERVE)) {
7486 /* Skip the part where LMDB will put *data.
7487 * Copy end of page, adjusting alignment so
7488 * compiler may copy words instead of bytes.
7490 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
7491 memcpy((size_t *)((char *)np + off),
7492 (size_t *)((char *)omp + off), sz - off);
7495 memcpy(np, omp, sz); /* Copy beginning of page */
7498 SETDSZ(leaf, data->mv_size);
7499 if (F_ISSET(flags, MDB_RESERVE))
7500 data->mv_data = METADATA(omp);
7502 memcpy(METADATA(omp), data->mv_data, data->mv_size);
7506 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
7508 } else if (data->mv_size == olddata.mv_size) {
7509 /* same size, just replace it. Note that we could
7510 * also reuse this node if the new data is smaller,
7511 * but instead we opt to shrink the node in that case.
7513 if (F_ISSET(flags, MDB_RESERVE))
7514 data->mv_data = olddata.mv_data;
7515 else if (!(mc->mc_flags & C_SUB))
7516 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
7518 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
7523 mdb_node_del(mc, 0);
7529 nflags = flags & NODE_ADD_FLAGS;
7530 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
7531 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
7532 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
7533 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
7535 nflags |= MDB_SPLIT_REPLACE;
7536 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
7538 /* There is room already in this leaf page. */
7539 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
7541 /* Adjust other cursors pointing to mp */
7542 MDB_cursor *m2, *m3;
7543 MDB_dbi dbi = mc->mc_dbi;
7544 unsigned i = mc->mc_top;
7545 MDB_page *mp = mc->mc_pg[i];
7547 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7548 if (mc->mc_flags & C_SUB)
7549 m3 = &m2->mc_xcursor->mx_cursor;
7552 if (m3 == mc || m3->mc_snum < mc->mc_snum || m3->mc_pg[i] != mp) continue;
7553 if (m3->mc_ki[i] >= mc->mc_ki[i] && insert_key) {
7556 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
7557 MDB_node *n2 = NODEPTR(mp, m3->mc_ki[i]);
7558 if ((n2->mn_flags & (F_SUBDATA|F_DUPDATA)) == F_DUPDATA)
7559 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
7565 if (rc == MDB_SUCCESS) {
7566 /* Now store the actual data in the child DB. Note that we're
7567 * storing the user data in the keys field, so there are strict
7568 * size limits on dupdata. The actual data fields of the child
7569 * DB are all zero size.
7572 int xflags, new_dupdata;
7577 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7578 if (flags & MDB_CURRENT) {
7579 xflags = MDB_CURRENT|MDB_NOSPILL;
7581 mdb_xcursor_init1(mc, leaf);
7582 xflags = (flags & MDB_NODUPDATA) ?
7583 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
7586 mc->mc_xcursor->mx_cursor.mc_pg[0] = sub_root;
7587 new_dupdata = (int)dkey.mv_size;
7588 /* converted, write the original data first */
7590 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
7593 /* we've done our job */
7596 if (!(leaf->mn_flags & F_SUBDATA) || sub_root) {
7597 /* Adjust other cursors pointing to mp */
7599 MDB_xcursor *mx = mc->mc_xcursor;
7600 unsigned i = mc->mc_top;
7601 MDB_page *mp = mc->mc_pg[i];
7602 int nkeys = NUMKEYS(mp);
7604 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
7605 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
7606 if (!(m2->mc_flags & C_INITIALIZED)) continue;
7607 if (m2->mc_pg[i] == mp) {
7608 if (m2->mc_ki[i] == mc->mc_ki[i]) {
7609 mdb_xcursor_init2(m2, mx, new_dupdata);
7610 } else if (!insert_key && m2->mc_ki[i] < nkeys) {
7611 MDB_node *n2 = NODEPTR(mp, m2->mc_ki[i]);
7612 if ((n2->mn_flags & (F_SUBDATA|F_DUPDATA)) == F_DUPDATA)
7613 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
7618 ecount = mc->mc_xcursor->mx_db.md_entries;
7619 if (flags & MDB_APPENDDUP)
7620 xflags |= MDB_APPEND;
7621 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
7622 if (flags & F_SUBDATA) {
7623 void *db = NODEDATA(leaf);
7624 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
7626 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
7628 /* Increment count unless we just replaced an existing item. */
7630 mc->mc_db->md_entries++;
7632 /* Invalidate txn if we created an empty sub-DB */
7635 /* If we succeeded and the key didn't exist before,
7636 * make sure the cursor is marked valid.
7638 mc->mc_flags |= C_INITIALIZED;
7640 if (flags & MDB_MULTIPLE) {
7643 /* let caller know how many succeeded, if any */
7644 data[1].mv_size = mcount;
7645 if (mcount < dcount) {
7646 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
7647 insert_key = insert_data = 0;
7654 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
7657 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7662 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
7668 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
7669 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7671 if (!(mc->mc_flags & C_INITIALIZED))
7674 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
7675 return MDB_NOTFOUND;
7677 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
7680 rc = mdb_cursor_touch(mc);
7684 mp = mc->mc_pg[mc->mc_top];
7687 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7689 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7690 if (flags & MDB_NODUPDATA) {
7691 /* mdb_cursor_del0() will subtract the final entry */
7692 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
7693 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
7695 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
7696 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
7698 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
7701 /* If sub-DB still has entries, we're done */
7702 if (mc->mc_xcursor->mx_db.md_entries) {
7703 if (leaf->mn_flags & F_SUBDATA) {
7704 /* update subDB info */
7705 void *db = NODEDATA(leaf);
7706 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
7709 /* shrink fake page */
7710 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
7711 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7712 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
7713 /* fix other sub-DB cursors pointed at fake pages on this page */
7714 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
7715 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
7716 if (!(m2->mc_flags & C_INITIALIZED)) continue;
7717 if (m2->mc_pg[mc->mc_top] == mp) {
7718 if (m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top]) {
7719 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
7721 MDB_node *n2 = NODEPTR(mp, m2->mc_ki[mc->mc_top]);
7722 if (!(n2->mn_flags & F_SUBDATA))
7723 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
7728 mc->mc_db->md_entries--;
7731 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
7733 /* otherwise fall thru and delete the sub-DB */
7736 if (leaf->mn_flags & F_SUBDATA) {
7737 /* add all the child DB's pages to the free list */
7738 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
7743 /* LMDB passes F_SUBDATA in 'flags' to delete a DB record */
7744 else if ((leaf->mn_flags ^ flags) & F_SUBDATA) {
7745 rc = MDB_INCOMPATIBLE;
7749 /* add overflow pages to free list */
7750 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7754 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
7755 if ((rc = mdb_page_get(mc, pg, &omp, NULL)) ||
7756 (rc = mdb_ovpage_free(mc, omp)))
7761 return mdb_cursor_del0(mc);
7764 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7768 /** Allocate and initialize new pages for a database.
7769 * @param[in] mc a cursor on the database being added to.
7770 * @param[in] flags flags defining what type of page is being allocated.
7771 * @param[in] num the number of pages to allocate. This is usually 1,
7772 * unless allocating overflow pages for a large record.
7773 * @param[out] mp Address of a page, or NULL on failure.
7774 * @return 0 on success, non-zero on failure.
7777 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
7782 if ((rc = mdb_page_alloc(mc, num, &np)))
7784 DPRINTF(("allocated new mpage %"Y"u, page size %u",
7785 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
7786 np->mp_flags = flags | P_DIRTY;
7787 np->mp_lower = (PAGEHDRSZ-PAGEBASE);
7788 np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
7791 mc->mc_db->md_branch_pages++;
7792 else if (IS_LEAF(np))
7793 mc->mc_db->md_leaf_pages++;
7794 else if (IS_OVERFLOW(np)) {
7795 mc->mc_db->md_overflow_pages += num;
7803 /** Calculate the size of a leaf node.
7804 * The size depends on the environment's page size; if a data item
7805 * is too large it will be put onto an overflow page and the node
7806 * size will only include the key and not the data. Sizes are always
7807 * rounded up to an even number of bytes, to guarantee 2-byte alignment
7808 * of the #MDB_node headers.
7809 * @param[in] env The environment handle.
7810 * @param[in] key The key for the node.
7811 * @param[in] data The data for the node.
7812 * @return The number of bytes needed to store the node.
7815 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
7819 sz = LEAFSIZE(key, data);
7820 if (sz > env->me_nodemax) {
7821 /* put on overflow page */
7822 sz -= data->mv_size - sizeof(pgno_t);
7825 return EVEN(sz + sizeof(indx_t));
7828 /** Calculate the size of a branch node.
7829 * The size should depend on the environment's page size but since
7830 * we currently don't support spilling large keys onto overflow
7831 * pages, it's simply the size of the #MDB_node header plus the
7832 * size of the key. Sizes are always rounded up to an even number
7833 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
7834 * @param[in] env The environment handle.
7835 * @param[in] key The key for the node.
7836 * @return The number of bytes needed to store the node.
7839 mdb_branch_size(MDB_env *env, MDB_val *key)
7844 if (sz > env->me_nodemax) {
7845 /* put on overflow page */
7846 /* not implemented */
7847 /* sz -= key->size - sizeof(pgno_t); */
7850 return sz + sizeof(indx_t);
7853 /** Add a node to the page pointed to by the cursor.
7854 * @param[in] mc The cursor for this operation.
7855 * @param[in] indx The index on the page where the new node should be added.
7856 * @param[in] key The key for the new node.
7857 * @param[in] data The data for the new node, if any.
7858 * @param[in] pgno The page number, if adding a branch node.
7859 * @param[in] flags Flags for the node.
7860 * @return 0 on success, non-zero on failure. Possible errors are:
7862 * <li>ENOMEM - failed to allocate overflow pages for the node.
7863 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
7864 * should never happen since all callers already calculate the
7865 * page's free space before calling this function.
7869 mdb_node_add(MDB_cursor *mc, indx_t indx,
7870 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
7873 size_t node_size = NODESIZE;
7877 MDB_page *mp = mc->mc_pg[mc->mc_top];
7878 MDB_page *ofp = NULL; /* overflow page */
7882 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
7884 DPRINTF(("add to %s %spage %"Y"u index %i, data size %"Z"u key size %"Z"u [%s]",
7885 IS_LEAF(mp) ? "leaf" : "branch",
7886 IS_SUBP(mp) ? "sub-" : "",
7887 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
7888 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
7891 /* Move higher keys up one slot. */
7892 int ksize = mc->mc_db->md_pad, dif;
7893 char *ptr = LEAF2KEY(mp, indx, ksize);
7894 dif = NUMKEYS(mp) - indx;
7896 memmove(ptr+ksize, ptr, dif*ksize);
7897 /* insert new key */
7898 memcpy(ptr, key->mv_data, ksize);
7900 /* Just using these for counting */
7901 mp->mp_lower += sizeof(indx_t);
7902 mp->mp_upper -= ksize - sizeof(indx_t);
7906 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
7908 node_size += key->mv_size;
7910 mdb_cassert(mc, key && data);
7911 if (F_ISSET(flags, F_BIGDATA)) {
7912 /* Data already on overflow page. */
7913 node_size += sizeof(pgno_t);
7914 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
7915 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
7917 /* Put data on overflow page. */
7918 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
7919 data->mv_size, node_size+data->mv_size));
7920 node_size = EVEN(node_size + sizeof(pgno_t));
7921 if ((ssize_t)node_size > room)
7923 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
7925 DPRINTF(("allocated overflow page %"Y"u", ofp->mp_pgno));
7929 node_size += data->mv_size;
7932 node_size = EVEN(node_size);
7933 if ((ssize_t)node_size > room)
7937 /* Move higher pointers up one slot. */
7938 for (i = NUMKEYS(mp); i > indx; i--)
7939 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
7941 /* Adjust free space offsets. */
7942 ofs = mp->mp_upper - node_size;
7943 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
7944 mp->mp_ptrs[indx] = ofs;
7946 mp->mp_lower += sizeof(indx_t);
7948 /* Write the node data. */
7949 node = NODEPTR(mp, indx);
7950 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
7951 node->mn_flags = flags;
7953 SETDSZ(node,data->mv_size);
7958 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7961 ndata = NODEDATA(node);
7963 if (F_ISSET(flags, F_BIGDATA))
7964 memcpy(ndata, data->mv_data, sizeof(pgno_t));
7965 else if (F_ISSET(flags, MDB_RESERVE))
7966 data->mv_data = ndata;
7968 memcpy(ndata, data->mv_data, data->mv_size);
7970 memcpy(ndata, &ofp->mp_pgno, sizeof(pgno_t));
7971 ndata = METADATA(ofp);
7972 if (F_ISSET(flags, MDB_RESERVE))
7973 data->mv_data = ndata;
7975 memcpy(ndata, data->mv_data, data->mv_size);
7982 DPRINTF(("not enough room in page %"Y"u, got %u ptrs",
7983 mdb_dbg_pgno(mp), NUMKEYS(mp)));
7984 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
7985 DPRINTF(("node size = %"Z"u", node_size));
7986 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7987 return MDB_PAGE_FULL;
7990 /** Delete the specified node from a page.
7991 * @param[in] mc Cursor pointing to the node to delete.
7992 * @param[in] ksize The size of a node. Only used if the page is
7993 * part of a #MDB_DUPFIXED database.
7996 mdb_node_del(MDB_cursor *mc, int ksize)
7998 MDB_page *mp = mc->mc_pg[mc->mc_top];
7999 indx_t indx = mc->mc_ki[mc->mc_top];
8001 indx_t i, j, numkeys, ptr;
8005 DPRINTF(("delete node %u on %s page %"Y"u", indx,
8006 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
8007 numkeys = NUMKEYS(mp);
8008 mdb_cassert(mc, indx < numkeys);
8011 int x = numkeys - 1 - indx;
8012 base = LEAF2KEY(mp, indx, ksize);
8014 memmove(base, base + ksize, x * ksize);
8015 mp->mp_lower -= sizeof(indx_t);
8016 mp->mp_upper += ksize - sizeof(indx_t);
8020 node = NODEPTR(mp, indx);
8021 sz = NODESIZE + node->mn_ksize;
8023 if (F_ISSET(node->mn_flags, F_BIGDATA))
8024 sz += sizeof(pgno_t);
8026 sz += NODEDSZ(node);
8030 ptr = mp->mp_ptrs[indx];
8031 for (i = j = 0; i < numkeys; i++) {
8033 mp->mp_ptrs[j] = mp->mp_ptrs[i];
8034 if (mp->mp_ptrs[i] < ptr)
8035 mp->mp_ptrs[j] += sz;
8040 base = (char *)mp + mp->mp_upper + PAGEBASE;
8041 memmove(base + sz, base, ptr - mp->mp_upper);
8043 mp->mp_lower -= sizeof(indx_t);
8047 /** Compact the main page after deleting a node on a subpage.
8048 * @param[in] mp The main page to operate on.
8049 * @param[in] indx The index of the subpage on the main page.
8052 mdb_node_shrink(MDB_page *mp, indx_t indx)
8057 indx_t delta, nsize, len, ptr;
8060 node = NODEPTR(mp, indx);
8061 sp = (MDB_page *)NODEDATA(node);
8062 delta = SIZELEFT(sp);
8063 nsize = NODEDSZ(node) - delta;
8065 /* Prepare to shift upward, set len = length(subpage part to shift) */
8069 return; /* do not make the node uneven-sized */
8071 xp = (MDB_page *)((char *)sp + delta); /* destination subpage */
8072 for (i = NUMKEYS(sp); --i >= 0; )
8073 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
8076 sp->mp_upper = sp->mp_lower;
8077 COPY_PGNO(sp->mp_pgno, mp->mp_pgno);
8078 SETDSZ(node, nsize);
8080 /* Shift <lower nodes...initial part of subpage> upward */
8081 base = (char *)mp + mp->mp_upper + PAGEBASE;
8082 memmove(base + delta, base, (char *)sp + len - base);
8084 ptr = mp->mp_ptrs[indx];
8085 for (i = NUMKEYS(mp); --i >= 0; ) {
8086 if (mp->mp_ptrs[i] <= ptr)
8087 mp->mp_ptrs[i] += delta;
8089 mp->mp_upper += delta;
8092 /** Initial setup of a sorted-dups cursor.
8093 * Sorted duplicates are implemented as a sub-database for the given key.
8094 * The duplicate data items are actually keys of the sub-database.
8095 * Operations on the duplicate data items are performed using a sub-cursor
8096 * initialized when the sub-database is first accessed. This function does
8097 * the preliminary setup of the sub-cursor, filling in the fields that
8098 * depend only on the parent DB.
8099 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
8102 mdb_xcursor_init0(MDB_cursor *mc)
8104 MDB_xcursor *mx = mc->mc_xcursor;
8106 mx->mx_cursor.mc_xcursor = NULL;
8107 mx->mx_cursor.mc_txn = mc->mc_txn;
8108 mx->mx_cursor.mc_db = &mx->mx_db;
8109 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
8110 mx->mx_cursor.mc_dbi = mc->mc_dbi;
8111 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
8112 mx->mx_cursor.mc_snum = 0;
8113 mx->mx_cursor.mc_top = 0;
8115 mx->mx_cursor.mc_ovpg = 0;
8117 mx->mx_cursor.mc_flags = C_SUB | (mc->mc_flags & (C_ORIG_RDONLY|C_WRITEMAP));
8118 mx->mx_dbx.md_name.mv_size = 0;
8119 mx->mx_dbx.md_name.mv_data = NULL;
8120 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
8121 mx->mx_dbx.md_dcmp = NULL;
8122 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
8125 /** Final setup of a sorted-dups cursor.
8126 * Sets up the fields that depend on the data from the main cursor.
8127 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
8128 * @param[in] node The data containing the #MDB_db record for the
8129 * sorted-dup database.
8132 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
8134 MDB_xcursor *mx = mc->mc_xcursor;
8136 mx->mx_cursor.mc_flags &= C_SUB|C_ORIG_RDONLY|C_WRITEMAP;
8137 if (node->mn_flags & F_SUBDATA) {
8138 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
8139 mx->mx_cursor.mc_pg[0] = 0;
8140 mx->mx_cursor.mc_snum = 0;
8141 mx->mx_cursor.mc_top = 0;
8143 MDB_page *fp = NODEDATA(node);
8144 mx->mx_db.md_pad = 0;
8145 mx->mx_db.md_flags = 0;
8146 mx->mx_db.md_depth = 1;
8147 mx->mx_db.md_branch_pages = 0;
8148 mx->mx_db.md_leaf_pages = 1;
8149 mx->mx_db.md_overflow_pages = 0;
8150 mx->mx_db.md_entries = NUMKEYS(fp);
8151 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
8152 mx->mx_cursor.mc_snum = 1;
8153 mx->mx_cursor.mc_top = 0;
8154 mx->mx_cursor.mc_flags |= C_INITIALIZED;
8155 mx->mx_cursor.mc_pg[0] = fp;
8156 mx->mx_cursor.mc_ki[0] = 0;
8157 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
8158 mx->mx_db.md_flags = MDB_DUPFIXED;
8159 mx->mx_db.md_pad = fp->mp_pad;
8160 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
8161 mx->mx_db.md_flags |= MDB_INTEGERKEY;
8164 DPRINTF(("Sub-db -%u root page %"Y"u", mx->mx_cursor.mc_dbi,
8165 mx->mx_db.md_root));
8166 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
8167 #if UINT_MAX < SIZE_MAX || defined(MDB_VL32)
8168 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(mdb_size_t))
8169 mx->mx_dbx.md_cmp = mdb_cmp_clong;
8174 /** Fixup a sorted-dups cursor due to underlying update.
8175 * Sets up some fields that depend on the data from the main cursor.
8176 * Almost the same as init1, but skips initialization steps if the
8177 * xcursor had already been used.
8178 * @param[in] mc The main cursor whose sorted-dups cursor is to be fixed up.
8179 * @param[in] src_mx The xcursor of an up-to-date cursor.
8180 * @param[in] new_dupdata True if converting from a non-#F_DUPDATA item.
8183 mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int new_dupdata)
8185 MDB_xcursor *mx = mc->mc_xcursor;
8188 mx->mx_cursor.mc_snum = 1;
8189 mx->mx_cursor.mc_top = 0;
8190 mx->mx_cursor.mc_flags |= C_INITIALIZED;
8191 mx->mx_cursor.mc_ki[0] = 0;
8192 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
8193 #if UINT_MAX < SIZE_MAX
8194 mx->mx_dbx.md_cmp = src_mx->mx_dbx.md_cmp;
8196 } else if (!(mx->mx_cursor.mc_flags & C_INITIALIZED)) {
8199 mx->mx_db = src_mx->mx_db;
8200 mx->mx_cursor.mc_pg[0] = src_mx->mx_cursor.mc_pg[0];
8201 DPRINTF(("Sub-db -%u root page %"Y"u", mx->mx_cursor.mc_dbi,
8202 mx->mx_db.md_root));
8205 /** Initialize a cursor for a given transaction and database. */
8207 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
8210 mc->mc_backup = NULL;
8213 mc->mc_db = &txn->mt_dbs[dbi];
8214 mc->mc_dbx = &txn->mt_dbxs[dbi];
8215 mc->mc_dbflag = &txn->mt_dbflags[dbi];
8223 mc->mc_flags = txn->mt_flags & (C_ORIG_RDONLY|C_WRITEMAP);
8224 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
8225 mdb_tassert(txn, mx != NULL);
8226 mc->mc_xcursor = mx;
8227 mdb_xcursor_init0(mc);
8229 mc->mc_xcursor = NULL;
8231 if (*mc->mc_dbflag & DB_STALE) {
8232 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
8237 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
8240 size_t size = sizeof(MDB_cursor);
8242 if (!ret || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
8245 if (txn->mt_flags & MDB_TXN_BLOCKED)
8248 if (dbi == FREE_DBI && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
8251 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
8252 size += sizeof(MDB_xcursor);
8254 if ((mc = malloc(size)) != NULL) {
8255 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
8256 if (txn->mt_cursors) {
8257 mc->mc_next = txn->mt_cursors[dbi];
8258 txn->mt_cursors[dbi] = mc;
8259 mc->mc_flags |= C_UNTRACK;
8271 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
8273 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi, DB_VALID))
8276 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
8279 if (txn->mt_flags & MDB_TXN_BLOCKED)
8282 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
8286 /* Return the count of duplicate data items for the current key */
8288 mdb_cursor_count(MDB_cursor *mc, mdb_size_t *countp)
8292 if (mc == NULL || countp == NULL)
8295 if (mc->mc_xcursor == NULL)
8296 return MDB_INCOMPATIBLE;
8298 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
8301 if (!(mc->mc_flags & C_INITIALIZED))
8304 if (!mc->mc_snum || (mc->mc_flags & C_EOF))
8305 return MDB_NOTFOUND;
8307 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
8308 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
8311 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
8314 *countp = mc->mc_xcursor->mx_db.md_entries;
8320 mdb_cursor_close(MDB_cursor *mc)
8322 if (mc && !mc->mc_backup) {
8323 /* remove from txn, if tracked */
8324 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
8325 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
8326 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
8328 *prev = mc->mc_next;
8335 mdb_cursor_txn(MDB_cursor *mc)
8337 if (!mc) return NULL;
8342 mdb_cursor_dbi(MDB_cursor *mc)
8347 /** Replace the key for a branch node with a new key.
8348 * @param[in] mc Cursor pointing to the node to operate on.
8349 * @param[in] key The new key to use.
8350 * @return 0 on success, non-zero on failure.
8353 mdb_update_key(MDB_cursor *mc, MDB_val *key)
8359 int delta, ksize, oksize;
8360 indx_t ptr, i, numkeys, indx;
8363 indx = mc->mc_ki[mc->mc_top];
8364 mp = mc->mc_pg[mc->mc_top];
8365 node = NODEPTR(mp, indx);
8366 ptr = mp->mp_ptrs[indx];
8370 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
8371 k2.mv_data = NODEKEY(node);
8372 k2.mv_size = node->mn_ksize;
8373 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Y"u",
8375 mdb_dkey(&k2, kbuf2),
8381 /* Sizes must be 2-byte aligned. */
8382 ksize = EVEN(key->mv_size);
8383 oksize = EVEN(node->mn_ksize);
8384 delta = ksize - oksize;
8386 /* Shift node contents if EVEN(key length) changed. */
8388 if (delta > 0 && SIZELEFT(mp) < delta) {
8390 /* not enough space left, do a delete and split */
8391 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
8392 pgno = NODEPGNO(node);
8393 mdb_node_del(mc, 0);
8394 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
8397 numkeys = NUMKEYS(mp);
8398 for (i = 0; i < numkeys; i++) {
8399 if (mp->mp_ptrs[i] <= ptr)
8400 mp->mp_ptrs[i] -= delta;
8403 base = (char *)mp + mp->mp_upper + PAGEBASE;
8404 len = ptr - mp->mp_upper + NODESIZE;
8405 memmove(base - delta, base, len);
8406 mp->mp_upper -= delta;
8408 node = NODEPTR(mp, indx);
8411 /* But even if no shift was needed, update ksize */
8412 if (node->mn_ksize != key->mv_size)
8413 node->mn_ksize = key->mv_size;
8416 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
8422 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
8424 /** Perform \b act while tracking temporary cursor \b mn */
8425 #define WITH_CURSOR_TRACKING(mn, act) do { \
8426 MDB_cursor dummy, *tracked, **tp = &(mn).mc_txn->mt_cursors[mn.mc_dbi]; \
8427 if ((mn).mc_flags & C_SUB) { \
8428 dummy.mc_flags = C_INITIALIZED; \
8429 dummy.mc_xcursor = (MDB_xcursor *)&(mn); \
8434 tracked->mc_next = *tp; \
8437 *tp = tracked->mc_next; \
8440 /** Move a node from csrc to cdst.
8443 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft)
8450 unsigned short flags;
8454 /* Mark src and dst as dirty. */
8455 if ((rc = mdb_page_touch(csrc)) ||
8456 (rc = mdb_page_touch(cdst)))
8459 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8460 key.mv_size = csrc->mc_db->md_pad;
8461 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
8463 data.mv_data = NULL;
8467 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
8468 mdb_cassert(csrc, !((size_t)srcnode & 1));
8469 srcpg = NODEPGNO(srcnode);
8470 flags = srcnode->mn_flags;
8471 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
8472 unsigned int snum = csrc->mc_snum;
8474 /* must find the lowest key below src */
8475 rc = mdb_page_search_lowest(csrc);
8478 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8479 key.mv_size = csrc->mc_db->md_pad;
8480 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
8482 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
8483 key.mv_size = NODEKSZ(s2);
8484 key.mv_data = NODEKEY(s2);
8486 csrc->mc_snum = snum--;
8487 csrc->mc_top = snum;
8489 key.mv_size = NODEKSZ(srcnode);
8490 key.mv_data = NODEKEY(srcnode);
8492 data.mv_size = NODEDSZ(srcnode);
8493 data.mv_data = NODEDATA(srcnode);
8495 mn.mc_xcursor = NULL;
8496 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
8497 unsigned int snum = cdst->mc_snum;
8500 /* must find the lowest key below dst */
8501 mdb_cursor_copy(cdst, &mn);
8502 rc = mdb_page_search_lowest(&mn);
8505 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
8506 bkey.mv_size = mn.mc_db->md_pad;
8507 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
8509 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
8510 bkey.mv_size = NODEKSZ(s2);
8511 bkey.mv_data = NODEKEY(s2);
8513 mn.mc_snum = snum--;
8516 rc = mdb_update_key(&mn, &bkey);
8521 DPRINTF(("moving %s node %u [%s] on page %"Y"u to node %u on page %"Y"u",
8522 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
8523 csrc->mc_ki[csrc->mc_top],
8525 csrc->mc_pg[csrc->mc_top]->mp_pgno,
8526 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
8528 /* Add the node to the destination page.
8530 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
8531 if (rc != MDB_SUCCESS)
8534 /* Delete the node from the source page.
8536 mdb_node_del(csrc, key.mv_size);
8539 /* Adjust other cursors pointing to mp */
8540 MDB_cursor *m2, *m3;
8541 MDB_dbi dbi = csrc->mc_dbi;
8542 MDB_page *mpd, *mps;
8544 mps = csrc->mc_pg[csrc->mc_top];
8545 /* If we're adding on the left, bump others up */
8547 mpd = cdst->mc_pg[csrc->mc_top];
8548 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8549 if (csrc->mc_flags & C_SUB)
8550 m3 = &m2->mc_xcursor->mx_cursor;
8553 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
8556 m3->mc_pg[csrc->mc_top] == mpd &&
8557 m3->mc_ki[csrc->mc_top] >= cdst->mc_ki[csrc->mc_top]) {
8558 m3->mc_ki[csrc->mc_top]++;
8561 m3->mc_pg[csrc->mc_top] == mps &&
8562 m3->mc_ki[csrc->mc_top] == csrc->mc_ki[csrc->mc_top]) {
8563 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
8564 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
8565 m3->mc_ki[csrc->mc_top-1]++;
8567 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) &&
8569 MDB_node *node = NODEPTR(m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
8570 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
8571 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
8575 /* Adding on the right, bump others down */
8577 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8578 if (csrc->mc_flags & C_SUB)
8579 m3 = &m2->mc_xcursor->mx_cursor;
8582 if (m3 == csrc) continue;
8583 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
8585 if (m3->mc_pg[csrc->mc_top] == mps) {
8586 if (!m3->mc_ki[csrc->mc_top]) {
8587 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
8588 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
8589 m3->mc_ki[csrc->mc_top-1]--;
8591 m3->mc_ki[csrc->mc_top]--;
8593 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) &&
8595 MDB_node *node = NODEPTR(m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
8596 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
8597 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
8604 /* Update the parent separators.
8606 if (csrc->mc_ki[csrc->mc_top] == 0) {
8607 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
8608 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8609 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
8611 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
8612 key.mv_size = NODEKSZ(srcnode);
8613 key.mv_data = NODEKEY(srcnode);
8615 DPRINTF(("update separator for source page %"Y"u to [%s]",
8616 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
8617 mdb_cursor_copy(csrc, &mn);
8620 /* We want mdb_rebalance to find mn when doing fixups */
8621 WITH_CURSOR_TRACKING(mn,
8622 rc = mdb_update_key(&mn, &key));
8626 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
8628 indx_t ix = csrc->mc_ki[csrc->mc_top];
8629 nullkey.mv_size = 0;
8630 csrc->mc_ki[csrc->mc_top] = 0;
8631 rc = mdb_update_key(csrc, &nullkey);
8632 csrc->mc_ki[csrc->mc_top] = ix;
8633 mdb_cassert(csrc, rc == MDB_SUCCESS);
8637 if (cdst->mc_ki[cdst->mc_top] == 0) {
8638 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
8639 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8640 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
8642 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
8643 key.mv_size = NODEKSZ(srcnode);
8644 key.mv_data = NODEKEY(srcnode);
8646 DPRINTF(("update separator for destination page %"Y"u to [%s]",
8647 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
8648 mdb_cursor_copy(cdst, &mn);
8651 /* We want mdb_rebalance to find mn when doing fixups */
8652 WITH_CURSOR_TRACKING(mn,
8653 rc = mdb_update_key(&mn, &key));
8657 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
8659 indx_t ix = cdst->mc_ki[cdst->mc_top];
8660 nullkey.mv_size = 0;
8661 cdst->mc_ki[cdst->mc_top] = 0;
8662 rc = mdb_update_key(cdst, &nullkey);
8663 cdst->mc_ki[cdst->mc_top] = ix;
8664 mdb_cassert(cdst, rc == MDB_SUCCESS);
8671 /** Merge one page into another.
8672 * The nodes from the page pointed to by \b csrc will
8673 * be copied to the page pointed to by \b cdst and then
8674 * the \b csrc page will be freed.
8675 * @param[in] csrc Cursor pointing to the source page.
8676 * @param[in] cdst Cursor pointing to the destination page.
8677 * @return 0 on success, non-zero on failure.
8680 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
8682 MDB_page *psrc, *pdst;
8689 psrc = csrc->mc_pg[csrc->mc_top];
8690 pdst = cdst->mc_pg[cdst->mc_top];
8692 DPRINTF(("merging page %"Y"u into %"Y"u", psrc->mp_pgno, pdst->mp_pgno));
8694 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
8695 mdb_cassert(csrc, cdst->mc_snum > 1);
8697 /* Mark dst as dirty. */
8698 if ((rc = mdb_page_touch(cdst)))
8701 /* get dst page again now that we've touched it. */
8702 pdst = cdst->mc_pg[cdst->mc_top];
8704 /* Move all nodes from src to dst.
8706 j = nkeys = NUMKEYS(pdst);
8707 if (IS_LEAF2(psrc)) {
8708 key.mv_size = csrc->mc_db->md_pad;
8709 key.mv_data = METADATA(psrc);
8710 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
8711 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
8712 if (rc != MDB_SUCCESS)
8714 key.mv_data = (char *)key.mv_data + key.mv_size;
8717 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
8718 srcnode = NODEPTR(psrc, i);
8719 if (i == 0 && IS_BRANCH(psrc)) {
8722 mdb_cursor_copy(csrc, &mn);
8723 mn.mc_xcursor = NULL;
8724 /* must find the lowest key below src */
8725 rc = mdb_page_search_lowest(&mn);
8728 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
8729 key.mv_size = mn.mc_db->md_pad;
8730 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
8732 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
8733 key.mv_size = NODEKSZ(s2);
8734 key.mv_data = NODEKEY(s2);
8737 key.mv_size = srcnode->mn_ksize;
8738 key.mv_data = NODEKEY(srcnode);
8741 data.mv_size = NODEDSZ(srcnode);
8742 data.mv_data = NODEDATA(srcnode);
8743 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
8744 if (rc != MDB_SUCCESS)
8749 DPRINTF(("dst page %"Y"u now has %u keys (%.1f%% filled)",
8750 pdst->mp_pgno, NUMKEYS(pdst),
8751 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
8753 /* Unlink the src page from parent and add to free list.
8756 mdb_node_del(csrc, 0);
8757 if (csrc->mc_ki[csrc->mc_top] == 0) {
8759 rc = mdb_update_key(csrc, &key);
8767 psrc = csrc->mc_pg[csrc->mc_top];
8768 /* If not operating on FreeDB, allow this page to be reused
8769 * in this txn. Otherwise just add to free list.
8771 rc = mdb_page_loose(csrc, psrc);
8775 csrc->mc_db->md_leaf_pages--;
8777 csrc->mc_db->md_branch_pages--;
8779 /* Adjust other cursors pointing to mp */
8780 MDB_cursor *m2, *m3;
8781 MDB_dbi dbi = csrc->mc_dbi;
8782 unsigned int top = csrc->mc_top;
8784 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8785 if (csrc->mc_flags & C_SUB)
8786 m3 = &m2->mc_xcursor->mx_cursor;
8789 if (m3 == csrc) continue;
8790 if (m3->mc_snum < csrc->mc_snum) continue;
8791 if (m3->mc_pg[top] == psrc) {
8792 m3->mc_pg[top] = pdst;
8793 m3->mc_ki[top] += nkeys;
8794 m3->mc_ki[top-1] = cdst->mc_ki[top-1];
8795 } else if (m3->mc_pg[top-1] == csrc->mc_pg[top-1] &&
8796 m3->mc_ki[top-1] > csrc->mc_ki[top-1]) {
8799 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) &&
8801 MDB_node *node = NODEPTR(m3->mc_pg[top], m3->mc_ki[top]);
8802 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
8803 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
8808 unsigned int snum = cdst->mc_snum;
8809 uint16_t depth = cdst->mc_db->md_depth;
8810 mdb_cursor_pop(cdst);
8811 rc = mdb_rebalance(cdst);
8812 /* Did the tree height change? */
8813 if (depth != cdst->mc_db->md_depth)
8814 snum += cdst->mc_db->md_depth - depth;
8815 cdst->mc_snum = snum;
8816 cdst->mc_top = snum-1;
8821 /** Copy the contents of a cursor.
8822 * @param[in] csrc The cursor to copy from.
8823 * @param[out] cdst The cursor to copy to.
8826 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
8830 cdst->mc_txn = csrc->mc_txn;
8831 cdst->mc_dbi = csrc->mc_dbi;
8832 cdst->mc_db = csrc->mc_db;
8833 cdst->mc_dbx = csrc->mc_dbx;
8834 cdst->mc_snum = csrc->mc_snum;
8835 cdst->mc_top = csrc->mc_top;
8836 cdst->mc_flags = csrc->mc_flags;
8838 cdst->mc_ovpg = csrc->mc_ovpg;
8841 for (i=0; i<csrc->mc_snum; i++) {
8842 cdst->mc_pg[i] = csrc->mc_pg[i];
8843 cdst->mc_ki[i] = csrc->mc_ki[i];
8847 /** Rebalance the tree after a delete operation.
8848 * @param[in] mc Cursor pointing to the page where rebalancing
8850 * @return 0 on success, non-zero on failure.
8853 mdb_rebalance(MDB_cursor *mc)
8857 unsigned int ptop, minkeys, thresh;
8861 if (IS_BRANCH(mc->mc_pg[mc->mc_top])) {
8866 thresh = FILL_THRESHOLD;
8868 DPRINTF(("rebalancing %s page %"Y"u (has %u keys, %.1f%% full)",
8869 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
8870 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
8871 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
8873 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= thresh &&
8874 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
8875 DPRINTF(("no need to rebalance page %"Y"u, above fill threshold",
8876 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
8880 if (mc->mc_snum < 2) {
8881 MDB_page *mp = mc->mc_pg[0];
8883 DPUTS("Can't rebalance a subpage, ignoring");
8886 if (NUMKEYS(mp) == 0) {
8887 DPUTS("tree is completely empty");
8888 mc->mc_db->md_root = P_INVALID;
8889 mc->mc_db->md_depth = 0;
8890 mc->mc_db->md_leaf_pages = 0;
8891 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
8894 /* Adjust cursors pointing to mp */
8897 mc->mc_flags &= ~C_INITIALIZED;
8899 MDB_cursor *m2, *m3;
8900 MDB_dbi dbi = mc->mc_dbi;
8902 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8903 if (mc->mc_flags & C_SUB)
8904 m3 = &m2->mc_xcursor->mx_cursor;
8907 if (!(m3->mc_flags & C_INITIALIZED) || (m3->mc_snum < mc->mc_snum))
8909 if (m3->mc_pg[0] == mp) {
8912 m3->mc_flags &= ~C_INITIALIZED;
8916 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
8918 DPUTS("collapsing root page!");
8919 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
8922 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
8923 rc = mdb_page_get(mc, mc->mc_db->md_root, &mc->mc_pg[0], NULL);
8926 mc->mc_db->md_depth--;
8927 mc->mc_db->md_branch_pages--;
8928 mc->mc_ki[0] = mc->mc_ki[1];
8929 for (i = 1; i<mc->mc_db->md_depth; i++) {
8930 mc->mc_pg[i] = mc->mc_pg[i+1];
8931 mc->mc_ki[i] = mc->mc_ki[i+1];
8934 /* Adjust other cursors pointing to mp */
8935 MDB_cursor *m2, *m3;
8936 MDB_dbi dbi = mc->mc_dbi;
8938 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8939 if (mc->mc_flags & C_SUB)
8940 m3 = &m2->mc_xcursor->mx_cursor;
8943 if (m3 == mc) continue;
8944 if (!(m3->mc_flags & C_INITIALIZED))
8946 if (m3->mc_pg[0] == mp) {
8947 for (i=0; i<mc->mc_db->md_depth; i++) {
8948 m3->mc_pg[i] = m3->mc_pg[i+1];
8949 m3->mc_ki[i] = m3->mc_ki[i+1];
8957 DPUTS("root page doesn't need rebalancing");
8961 /* The parent (branch page) must have at least 2 pointers,
8962 * otherwise the tree is invalid.
8964 ptop = mc->mc_top-1;
8965 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
8967 /* Leaf page fill factor is below the threshold.
8968 * Try to move keys from left or right neighbor, or
8969 * merge with a neighbor page.
8974 mdb_cursor_copy(mc, &mn);
8975 mn.mc_xcursor = NULL;
8977 oldki = mc->mc_ki[mc->mc_top];
8978 if (mc->mc_ki[ptop] == 0) {
8979 /* We're the leftmost leaf in our parent.
8981 DPUTS("reading right neighbor");
8983 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
8984 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
8987 mn.mc_ki[mn.mc_top] = 0;
8988 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
8991 /* There is at least one neighbor to the left.
8993 DPUTS("reading left neighbor");
8995 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
8996 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
8999 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
9000 mc->mc_ki[mc->mc_top] = 0;
9004 DPRINTF(("found neighbor page %"Y"u (%u keys, %.1f%% full)",
9005 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
9006 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
9008 /* If the neighbor page is above threshold and has enough keys,
9009 * move one key from it. Otherwise we should try to merge them.
9010 * (A branch page must never have less than 2 keys.)
9012 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= thresh && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
9013 rc = mdb_node_move(&mn, mc, fromleft);
9015 /* if we inserted on left, bump position up */
9020 rc = mdb_page_merge(&mn, mc);
9022 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
9023 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
9024 /* We want mdb_rebalance to find mn when doing fixups */
9025 WITH_CURSOR_TRACKING(mn,
9026 rc = mdb_page_merge(mc, &mn));
9027 mdb_cursor_copy(&mn, mc);
9029 mc->mc_flags &= ~C_EOF;
9031 mc->mc_ki[mc->mc_top] = oldki;
9035 /** Complete a delete operation started by #mdb_cursor_del(). */
9037 mdb_cursor_del0(MDB_cursor *mc)
9043 MDB_cursor *m2, *m3;
9044 MDB_dbi dbi = mc->mc_dbi;
9046 ki = mc->mc_ki[mc->mc_top];
9047 mp = mc->mc_pg[mc->mc_top];
9048 mdb_node_del(mc, mc->mc_db->md_pad);
9049 mc->mc_db->md_entries--;
9051 /* Adjust other cursors pointing to mp */
9052 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9053 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
9054 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9056 if (m3 == mc || m3->mc_snum < mc->mc_snum)
9058 if (m3->mc_pg[mc->mc_top] == mp) {
9059 if (m3->mc_ki[mc->mc_top] == ki) {
9060 m3->mc_flags |= C_DEL;
9061 } else if (m3->mc_ki[mc->mc_top] > ki) {
9062 m3->mc_ki[mc->mc_top]--;
9064 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
9065 MDB_node *node = NODEPTR(m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
9066 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
9067 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
9072 rc = mdb_rebalance(mc);
9074 if (rc == MDB_SUCCESS) {
9075 /* DB is totally empty now, just bail out.
9076 * Other cursors adjustments were already done
9077 * by mdb_rebalance and aren't needed here.
9082 mp = mc->mc_pg[mc->mc_top];
9083 nkeys = NUMKEYS(mp);
9085 /* Adjust other cursors pointing to mp */
9086 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
9087 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
9088 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9090 if (m3->mc_snum < mc->mc_snum)
9092 if (m3->mc_pg[mc->mc_top] == mp) {
9093 /* if m3 points past last node in page, find next sibling */
9094 if (m3->mc_ki[mc->mc_top] >= mc->mc_ki[mc->mc_top]) {
9095 if (m3->mc_ki[mc->mc_top] >= nkeys) {
9096 rc = mdb_cursor_sibling(m3, 1);
9097 if (rc == MDB_NOTFOUND) {
9098 m3->mc_flags |= C_EOF;
9103 if (mc->mc_db->md_flags & MDB_DUPSORT) {
9104 MDB_node *node = NODEPTR(m3->mc_pg[m3->mc_top], m3->mc_ki[m3->mc_top]);
9105 if (node->mn_flags & F_DUPDATA) {
9106 mdb_xcursor_init1(m3, node);
9107 m3->mc_xcursor->mx_cursor.mc_flags |= C_DEL;
9113 mc->mc_flags |= C_DEL;
9117 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
9122 mdb_del(MDB_txn *txn, MDB_dbi dbi,
9123 MDB_val *key, MDB_val *data)
9125 if (!key || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9128 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
9129 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
9131 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
9132 /* must ignore any data */
9136 return mdb_del0(txn, dbi, key, data, 0);
9140 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
9141 MDB_val *key, MDB_val *data, unsigned flags)
9146 MDB_val rdata, *xdata;
9150 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
9152 mdb_cursor_init(&mc, txn, dbi, &mx);
9161 flags |= MDB_NODUPDATA;
9163 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
9165 /* let mdb_page_split know about this cursor if needed:
9166 * delete will trigger a rebalance; if it needs to move
9167 * a node from one page to another, it will have to
9168 * update the parent's separator key(s). If the new sepkey
9169 * is larger than the current one, the parent page may
9170 * run out of space, triggering a split. We need this
9171 * cursor to be consistent until the end of the rebalance.
9173 mc.mc_flags |= C_UNTRACK;
9174 mc.mc_next = txn->mt_cursors[dbi];
9175 txn->mt_cursors[dbi] = &mc;
9176 rc = mdb_cursor_del(&mc, flags);
9177 txn->mt_cursors[dbi] = mc.mc_next;
9182 /** Split a page and insert a new node.
9183 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
9184 * The cursor will be updated to point to the actual page and index where
9185 * the node got inserted after the split.
9186 * @param[in] newkey The key for the newly inserted node.
9187 * @param[in] newdata The data for the newly inserted node.
9188 * @param[in] newpgno The page number, if the new node is a branch node.
9189 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
9190 * @return 0 on success, non-zero on failure.
9193 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
9194 unsigned int nflags)
9197 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
9200 int i, j, split_indx, nkeys, pmax;
9201 MDB_env *env = mc->mc_txn->mt_env;
9203 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
9204 MDB_page *copy = NULL;
9205 MDB_page *mp, *rp, *pp;
9210 mp = mc->mc_pg[mc->mc_top];
9211 newindx = mc->mc_ki[mc->mc_top];
9212 nkeys = NUMKEYS(mp);
9214 DPRINTF(("-----> splitting %s page %"Y"u and adding [%s] at index %i/%i",
9215 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
9216 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
9218 /* Create a right sibling. */
9219 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
9221 rp->mp_pad = mp->mp_pad;
9222 DPRINTF(("new right sibling: page %"Y"u", rp->mp_pgno));
9224 /* Usually when splitting the root page, the cursor
9225 * height is 1. But when called from mdb_update_key,
9226 * the cursor height may be greater because it walks
9227 * up the stack while finding the branch slot to update.
9229 if (mc->mc_top < 1) {
9230 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
9232 /* shift current top to make room for new parent */
9233 for (i=mc->mc_snum; i>0; i--) {
9234 mc->mc_pg[i] = mc->mc_pg[i-1];
9235 mc->mc_ki[i] = mc->mc_ki[i-1];
9239 mc->mc_db->md_root = pp->mp_pgno;
9240 DPRINTF(("root split! new root = %"Y"u", pp->mp_pgno));
9241 new_root = mc->mc_db->md_depth++;
9243 /* Add left (implicit) pointer. */
9244 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
9245 /* undo the pre-push */
9246 mc->mc_pg[0] = mc->mc_pg[1];
9247 mc->mc_ki[0] = mc->mc_ki[1];
9248 mc->mc_db->md_root = mp->mp_pgno;
9249 mc->mc_db->md_depth--;
9256 ptop = mc->mc_top-1;
9257 DPRINTF(("parent branch page is %"Y"u", mc->mc_pg[ptop]->mp_pgno));
9260 mdb_cursor_copy(mc, &mn);
9261 mn.mc_xcursor = NULL;
9262 mn.mc_pg[mn.mc_top] = rp;
9263 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
9265 if (nflags & MDB_APPEND) {
9266 mn.mc_ki[mn.mc_top] = 0;
9268 split_indx = newindx;
9272 split_indx = (nkeys+1) / 2;
9277 unsigned int lsize, rsize, ksize;
9278 /* Move half of the keys to the right sibling */
9279 x = mc->mc_ki[mc->mc_top] - split_indx;
9280 ksize = mc->mc_db->md_pad;
9281 split = LEAF2KEY(mp, split_indx, ksize);
9282 rsize = (nkeys - split_indx) * ksize;
9283 lsize = (nkeys - split_indx) * sizeof(indx_t);
9284 mp->mp_lower -= lsize;
9285 rp->mp_lower += lsize;
9286 mp->mp_upper += rsize - lsize;
9287 rp->mp_upper -= rsize - lsize;
9288 sepkey.mv_size = ksize;
9289 if (newindx == split_indx) {
9290 sepkey.mv_data = newkey->mv_data;
9292 sepkey.mv_data = split;
9295 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
9296 memcpy(rp->mp_ptrs, split, rsize);
9297 sepkey.mv_data = rp->mp_ptrs;
9298 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
9299 memcpy(ins, newkey->mv_data, ksize);
9300 mp->mp_lower += sizeof(indx_t);
9301 mp->mp_upper -= ksize - sizeof(indx_t);
9304 memcpy(rp->mp_ptrs, split, x * ksize);
9305 ins = LEAF2KEY(rp, x, ksize);
9306 memcpy(ins, newkey->mv_data, ksize);
9307 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
9308 rp->mp_lower += sizeof(indx_t);
9309 rp->mp_upper -= ksize - sizeof(indx_t);
9310 mc->mc_ki[mc->mc_top] = x;
9313 int psize, nsize, k;
9314 /* Maximum free space in an empty page */
9315 pmax = env->me_psize - PAGEHDRSZ;
9317 nsize = mdb_leaf_size(env, newkey, newdata);
9319 nsize = mdb_branch_size(env, newkey);
9320 nsize = EVEN(nsize);
9322 /* grab a page to hold a temporary copy */
9323 copy = mdb_page_malloc(mc->mc_txn, 1);
9328 copy->mp_pgno = mp->mp_pgno;
9329 copy->mp_flags = mp->mp_flags;
9330 copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
9331 copy->mp_upper = env->me_psize - PAGEBASE;
9333 /* prepare to insert */
9334 for (i=0, j=0; i<nkeys; i++) {
9336 copy->mp_ptrs[j++] = 0;
9338 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
9341 /* When items are relatively large the split point needs
9342 * to be checked, because being off-by-one will make the
9343 * difference between success or failure in mdb_node_add.
9345 * It's also relevant if a page happens to be laid out
9346 * such that one half of its nodes are all "small" and
9347 * the other half of its nodes are "large." If the new
9348 * item is also "large" and falls on the half with
9349 * "large" nodes, it also may not fit.
9351 * As a final tweak, if the new item goes on the last
9352 * spot on the page (and thus, onto the new page), bias
9353 * the split so the new page is emptier than the old page.
9354 * This yields better packing during sequential inserts.
9356 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
9357 /* Find split point */
9359 if (newindx <= split_indx || newindx >= nkeys) {
9361 k = newindx >= nkeys ? nkeys : split_indx+1+IS_LEAF(mp);
9366 for (; i!=k; i+=j) {
9371 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
9372 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
9374 if (F_ISSET(node->mn_flags, F_BIGDATA))
9375 psize += sizeof(pgno_t);
9377 psize += NODEDSZ(node);
9379 psize = EVEN(psize);
9381 if (psize > pmax || i == k-j) {
9382 split_indx = i + (j<0);
9387 if (split_indx == newindx) {
9388 sepkey.mv_size = newkey->mv_size;
9389 sepkey.mv_data = newkey->mv_data;
9391 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
9392 sepkey.mv_size = node->mn_ksize;
9393 sepkey.mv_data = NODEKEY(node);
9398 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
9400 /* Copy separator key to the parent.
9402 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
9403 int snum = mc->mc_snum;
9407 /* We want other splits to find mn when doing fixups */
9408 WITH_CURSOR_TRACKING(mn,
9409 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0));
9414 if (mc->mc_snum > snum) {
9417 /* Right page might now have changed parent.
9418 * Check if left page also changed parent.
9420 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
9421 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
9422 for (i=0; i<ptop; i++) {
9423 mc->mc_pg[i] = mn.mc_pg[i];
9424 mc->mc_ki[i] = mn.mc_ki[i];
9426 mc->mc_pg[ptop] = mn.mc_pg[ptop];
9427 if (mn.mc_ki[ptop]) {
9428 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
9430 /* find right page's left sibling */
9431 mc->mc_ki[ptop] = mn.mc_ki[ptop];
9432 mdb_cursor_sibling(mc, 0);
9437 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
9440 if (rc != MDB_SUCCESS) {
9443 if (nflags & MDB_APPEND) {
9444 mc->mc_pg[mc->mc_top] = rp;
9445 mc->mc_ki[mc->mc_top] = 0;
9446 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
9449 for (i=0; i<mc->mc_top; i++)
9450 mc->mc_ki[i] = mn.mc_ki[i];
9451 } else if (!IS_LEAF2(mp)) {
9453 mc->mc_pg[mc->mc_top] = rp;
9458 rkey.mv_data = newkey->mv_data;
9459 rkey.mv_size = newkey->mv_size;
9465 /* Update index for the new key. */
9466 mc->mc_ki[mc->mc_top] = j;
9468 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
9469 rkey.mv_data = NODEKEY(node);
9470 rkey.mv_size = node->mn_ksize;
9472 xdata.mv_data = NODEDATA(node);
9473 xdata.mv_size = NODEDSZ(node);
9476 pgno = NODEPGNO(node);
9477 flags = node->mn_flags;
9480 if (!IS_LEAF(mp) && j == 0) {
9481 /* First branch index doesn't need key data. */
9485 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
9491 mc->mc_pg[mc->mc_top] = copy;
9496 } while (i != split_indx);
9498 nkeys = NUMKEYS(copy);
9499 for (i=0; i<nkeys; i++)
9500 mp->mp_ptrs[i] = copy->mp_ptrs[i];
9501 mp->mp_lower = copy->mp_lower;
9502 mp->mp_upper = copy->mp_upper;
9503 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
9504 env->me_psize - copy->mp_upper - PAGEBASE);
9506 /* reset back to original page */
9507 if (newindx < split_indx) {
9508 mc->mc_pg[mc->mc_top] = mp;
9510 mc->mc_pg[mc->mc_top] = rp;
9512 /* Make sure mc_ki is still valid.
9514 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
9515 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
9516 for (i=0; i<=ptop; i++) {
9517 mc->mc_pg[i] = mn.mc_pg[i];
9518 mc->mc_ki[i] = mn.mc_ki[i];
9522 if (nflags & MDB_RESERVE) {
9523 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
9524 if (!(node->mn_flags & F_BIGDATA))
9525 newdata->mv_data = NODEDATA(node);
9528 if (newindx >= split_indx) {
9529 mc->mc_pg[mc->mc_top] = rp;
9531 /* Make sure mc_ki is still valid.
9533 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
9534 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
9535 for (i=0; i<=ptop; i++) {
9536 mc->mc_pg[i] = mn.mc_pg[i];
9537 mc->mc_ki[i] = mn.mc_ki[i];
9544 /* Adjust other cursors pointing to mp */
9545 MDB_cursor *m2, *m3;
9546 MDB_dbi dbi = mc->mc_dbi;
9547 nkeys = NUMKEYS(mp);
9549 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9550 if (mc->mc_flags & C_SUB)
9551 m3 = &m2->mc_xcursor->mx_cursor;
9556 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9560 /* sub cursors may be on different DB */
9561 if (m3->mc_pg[0] != mp)
9564 for (k=new_root; k>=0; k--) {
9565 m3->mc_ki[k+1] = m3->mc_ki[k];
9566 m3->mc_pg[k+1] = m3->mc_pg[k];
9568 if (m3->mc_ki[0] >= nkeys) {
9573 m3->mc_pg[0] = mc->mc_pg[0];
9577 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
9578 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
9579 m3->mc_ki[mc->mc_top]++;
9580 if (m3->mc_ki[mc->mc_top] >= nkeys) {
9581 m3->mc_pg[mc->mc_top] = rp;
9582 m3->mc_ki[mc->mc_top] -= nkeys;
9583 for (i=0; i<mc->mc_top; i++) {
9584 m3->mc_ki[i] = mn.mc_ki[i];
9585 m3->mc_pg[i] = mn.mc_pg[i];
9588 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
9589 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
9592 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) &&
9594 MDB_node *node = NODEPTR(m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
9595 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
9596 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
9600 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
9603 if (copy) /* tmp page */
9604 mdb_page_free(env, copy);
9606 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
9611 mdb_put(MDB_txn *txn, MDB_dbi dbi,
9612 MDB_val *key, MDB_val *data, unsigned int flags)
9618 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9621 if (flags & ~(MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP))
9624 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
9625 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
9627 mdb_cursor_init(&mc, txn, dbi, &mx);
9628 mc.mc_next = txn->mt_cursors[dbi];
9629 txn->mt_cursors[dbi] = &mc;
9630 rc = mdb_cursor_put(&mc, key, data, flags);
9631 txn->mt_cursors[dbi] = mc.mc_next;
9636 #define MDB_WBUF (1024*1024)
9639 /** State needed for a compacting copy. */
9640 typedef struct mdb_copy {
9641 pthread_mutex_t mc_mutex;
9642 pthread_cond_t mc_cond;
9649 pgno_t mc_next_pgno;
9652 volatile int mc_new;
9657 /** Dedicated writer thread for compacting copy. */
9658 static THREAD_RET ESECT CALL_CONV
9659 mdb_env_copythr(void *arg)
9663 int toggle = 0, wsize, rc;
9666 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
9669 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
9672 pthread_mutex_lock(&my->mc_mutex);
9674 pthread_cond_signal(&my->mc_cond);
9677 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
9678 if (my->mc_new < 0) {
9683 wsize = my->mc_wlen[toggle];
9684 ptr = my->mc_wbuf[toggle];
9687 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
9691 } else if (len > 0) {
9705 /* If there's an overflow page tail, write it too */
9706 if (my->mc_olen[toggle]) {
9707 wsize = my->mc_olen[toggle];
9708 ptr = my->mc_over[toggle];
9709 my->mc_olen[toggle] = 0;
9712 my->mc_wlen[toggle] = 0;
9714 pthread_cond_signal(&my->mc_cond);
9716 pthread_cond_signal(&my->mc_cond);
9717 pthread_mutex_unlock(&my->mc_mutex);
9718 return (THREAD_RET)0;
9722 /** Tell the writer thread there's a buffer ready to write */
9724 mdb_env_cthr_toggle(mdb_copy *my, int st)
9726 int toggle = my->mc_toggle ^ 1;
9727 pthread_mutex_lock(&my->mc_mutex);
9728 if (my->mc_status) {
9729 pthread_mutex_unlock(&my->mc_mutex);
9730 return my->mc_status;
9732 while (my->mc_new == 1)
9733 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
9735 my->mc_toggle = toggle;
9736 pthread_cond_signal(&my->mc_cond);
9737 pthread_mutex_unlock(&my->mc_mutex);
9741 /** Depth-first tree traversal for compacting copy. */
9743 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
9745 MDB_cursor mc = {0};
9747 MDB_page *mo, *mp, *leaf;
9752 /* Empty DB, nothing to do */
9753 if (*pg == P_INVALID)
9757 mc.mc_txn = my->mc_txn;
9758 mc.mc_flags = my->mc_txn->mt_flags & (C_ORIG_RDONLY|C_WRITEMAP);
9760 rc = mdb_page_get(&mc, *pg, &mc.mc_pg[0], NULL);
9763 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
9767 /* Make cursor pages writable */
9768 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
9772 for (i=0; i<mc.mc_top; i++) {
9773 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
9774 mc.mc_pg[i] = (MDB_page *)ptr;
9775 ptr += my->mc_env->me_psize;
9778 /* This is writable space for a leaf page. Usually not needed. */
9779 leaf = (MDB_page *)ptr;
9781 toggle = my->mc_toggle;
9782 while (mc.mc_snum > 0) {
9784 mp = mc.mc_pg[mc.mc_top];
9788 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
9789 for (i=0; i<n; i++) {
9790 ni = NODEPTR(mp, i);
9791 if (ni->mn_flags & F_BIGDATA) {
9795 /* Need writable leaf */
9797 mc.mc_pg[mc.mc_top] = leaf;
9798 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
9800 ni = NODEPTR(mp, i);
9803 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9804 rc = mdb_page_get(&mc, pg, &omp, NULL);
9807 if (my->mc_wlen[toggle] >= MDB_WBUF) {
9808 rc = mdb_env_cthr_toggle(my, 1);
9811 toggle = my->mc_toggle;
9813 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
9814 memcpy(mo, omp, my->mc_env->me_psize);
9815 mo->mp_pgno = my->mc_next_pgno;
9816 my->mc_next_pgno += omp->mp_pages;
9817 my->mc_wlen[toggle] += my->mc_env->me_psize;
9818 if (omp->mp_pages > 1) {
9819 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
9820 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
9821 rc = mdb_env_cthr_toggle(my, 1);
9824 toggle = my->mc_toggle;
9826 memcpy(NODEDATA(ni), &mo->mp_pgno, sizeof(pgno_t));
9827 } else if (ni->mn_flags & F_SUBDATA) {
9830 /* Need writable leaf */
9832 mc.mc_pg[mc.mc_top] = leaf;
9833 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
9835 ni = NODEPTR(mp, i);
9838 memcpy(&db, NODEDATA(ni), sizeof(db));
9839 my->mc_toggle = toggle;
9840 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
9843 toggle = my->mc_toggle;
9844 memcpy(NODEDATA(ni), &db, sizeof(db));
9849 mc.mc_ki[mc.mc_top]++;
9850 if (mc.mc_ki[mc.mc_top] < n) {
9853 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
9855 rc = mdb_page_get(&mc, pg, &mp, NULL);
9860 mc.mc_ki[mc.mc_top] = 0;
9861 if (IS_BRANCH(mp)) {
9862 /* Whenever we advance to a sibling branch page,
9863 * we must proceed all the way down to its first leaf.
9865 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
9868 mc.mc_pg[mc.mc_top] = mp;
9872 if (my->mc_wlen[toggle] >= MDB_WBUF) {
9873 rc = mdb_env_cthr_toggle(my, 1);
9876 toggle = my->mc_toggle;
9878 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
9879 mdb_page_copy(mo, mp, my->mc_env->me_psize);
9880 mo->mp_pgno = my->mc_next_pgno++;
9881 my->mc_wlen[toggle] += my->mc_env->me_psize;
9883 /* Update parent if there is one */
9884 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
9885 SETPGNO(ni, mo->mp_pgno);
9886 mdb_cursor_pop(&mc);
9888 /* Otherwise we're done */
9898 /** Copy environment with compaction. */
9900 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
9905 MDB_txn *txn = NULL;
9910 my.mc_mutex = CreateMutex(NULL, FALSE, NULL);
9911 my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL);
9912 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_os_psize);
9913 if (my.mc_wbuf[0] == NULL)
9916 pthread_mutex_init(&my.mc_mutex, NULL);
9917 pthread_cond_init(&my.mc_cond, NULL);
9918 #ifdef HAVE_MEMALIGN
9919 my.mc_wbuf[0] = memalign(env->me_os_psize, MDB_WBUF*2);
9920 if (my.mc_wbuf[0] == NULL)
9923 rc = posix_memalign((void **)&my.mc_wbuf[0], env->me_os_psize, MDB_WBUF*2);
9928 memset(my.mc_wbuf[0], 0, MDB_WBUF*2);
9929 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
9934 my.mc_next_pgno = NUM_METAS;
9940 THREAD_CREATE(thr, mdb_env_copythr, &my);
9942 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
9946 mp = (MDB_page *)my.mc_wbuf[0];
9947 memset(mp, 0, NUM_METAS * env->me_psize);
9949 mp->mp_flags = P_META;
9950 mm = (MDB_meta *)METADATA(mp);
9951 mdb_env_init_meta0(env, mm);
9952 mm->mm_address = env->me_metas[0]->mm_address;
9954 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
9956 mp->mp_flags = P_META;
9957 *(MDB_meta *)METADATA(mp) = *mm;
9958 mm = (MDB_meta *)METADATA(mp);
9960 /* Count the number of free pages, subtract from lastpg to find
9961 * number of active pages
9964 MDB_ID freecount = 0;
9967 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
9968 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
9969 freecount += *(MDB_ID *)data.mv_data;
9970 freecount += txn->mt_dbs[FREE_DBI].md_branch_pages +
9971 txn->mt_dbs[FREE_DBI].md_leaf_pages +
9972 txn->mt_dbs[FREE_DBI].md_overflow_pages;
9974 /* Set metapage 1 */
9975 mm->mm_last_pg = txn->mt_next_pgno - freecount - 1;
9976 mm->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
9977 if (mm->mm_last_pg > NUM_METAS-1) {
9978 mm->mm_dbs[MAIN_DBI].md_root = mm->mm_last_pg;
9981 mm->mm_dbs[MAIN_DBI].md_root = P_INVALID;
9984 my.mc_wlen[0] = env->me_psize * NUM_METAS;
9986 pthread_mutex_lock(&my.mc_mutex);
9988 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
9989 pthread_mutex_unlock(&my.mc_mutex);
9990 rc = mdb_env_cwalk(&my, &txn->mt_dbs[MAIN_DBI].md_root, 0);
9991 if (rc == MDB_SUCCESS && my.mc_wlen[my.mc_toggle])
9992 rc = mdb_env_cthr_toggle(&my, 1);
9993 mdb_env_cthr_toggle(&my, -1);
9994 pthread_mutex_lock(&my.mc_mutex);
9996 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
9997 pthread_mutex_unlock(&my.mc_mutex);
10000 mdb_txn_abort(txn);
10002 CloseHandle(my.mc_cond);
10003 CloseHandle(my.mc_mutex);
10004 _aligned_free(my.mc_wbuf[0]);
10006 pthread_cond_destroy(&my.mc_cond);
10007 pthread_mutex_destroy(&my.mc_mutex);
10008 free(my.mc_wbuf[0]);
10013 /** Copy environment as-is. */
10015 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
10017 MDB_txn *txn = NULL;
10018 mdb_mutexref_t wmutex = NULL;
10020 mdb_size_t wsize, w3;
10024 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
10028 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
10031 /* Do the lock/unlock of the reader mutex before starting the
10032 * write txn. Otherwise other read txns could block writers.
10034 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
10038 if (env->me_txns) {
10039 /* We must start the actual read txn after blocking writers */
10040 mdb_txn_end(txn, MDB_END_RESET_TMP);
10042 /* Temporarily block writers until we snapshot the meta pages */
10043 wmutex = env->me_wmutex;
10044 if (LOCK_MUTEX(rc, env, wmutex))
10047 rc = mdb_txn_renew0(txn);
10049 UNLOCK_MUTEX(wmutex);
10054 wsize = env->me_psize * NUM_METAS;
10058 DO_WRITE(rc, fd, ptr, w2, len);
10062 } else if (len > 0) {
10068 /* Non-blocking or async handles are not supported */
10074 UNLOCK_MUTEX(wmutex);
10079 w3 = txn->mt_next_pgno * env->me_psize;
10081 mdb_size_t fsize = 0;
10082 if ((rc = mdb_fsize(env->me_fd, &fsize)))
10087 wsize = w3 - wsize;
10088 while (wsize > 0) {
10089 if (wsize > MAX_WRITE)
10093 DO_WRITE(rc, fd, ptr, w2, len);
10097 } else if (len > 0) {
10109 mdb_txn_abort(txn);
10114 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
10116 if (flags & MDB_CP_COMPACT)
10117 return mdb_env_copyfd1(env, fd);
10119 return mdb_env_copyfd0(env, fd);
10123 mdb_env_copyfd(MDB_env *env, HANDLE fd)
10125 return mdb_env_copyfd2(env, fd, 0);
10129 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
10133 HANDLE newfd = INVALID_HANDLE_VALUE;
10138 if (env->me_flags & MDB_NOSUBDIR) {
10139 lpath = (char *)path;
10141 len = strlen(path);
10142 len += sizeof(DATANAME);
10143 lpath = malloc(len);
10146 sprintf(lpath, "%s" DATANAME, path);
10149 /* The destination path must exist, but the destination file must not.
10150 * We don't want the OS to cache the writes, since the source data is
10151 * already in the OS cache.
10154 rc = utf8_to_utf16(lpath, -1, &wpath, NULL);
10157 newfd = CreateFileW(wpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
10158 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
10161 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
10163 if (newfd == INVALID_HANDLE_VALUE) {
10168 if (env->me_psize >= env->me_os_psize) {
10170 /* Set O_DIRECT if the file system supports it */
10171 if ((rc = fcntl(newfd, F_GETFL)) != -1)
10172 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
10174 #ifdef F_NOCACHE /* __APPLE__ */
10175 rc = fcntl(newfd, F_NOCACHE, 1);
10183 rc = mdb_env_copyfd2(env, newfd, flags);
10186 if (!(env->me_flags & MDB_NOSUBDIR))
10188 if (newfd != INVALID_HANDLE_VALUE)
10189 if (close(newfd) < 0 && rc == MDB_SUCCESS)
10196 mdb_env_copy(MDB_env *env, const char *path)
10198 return mdb_env_copy2(env, path, 0);
10202 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
10204 if (flag & ~CHANGEABLE)
10207 env->me_flags |= flag;
10209 env->me_flags &= ~flag;
10210 return MDB_SUCCESS;
10214 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
10219 *arg = env->me_flags & (CHANGEABLE|CHANGELESS);
10220 return MDB_SUCCESS;
10224 mdb_env_set_userctx(MDB_env *env, void *ctx)
10228 env->me_userctx = ctx;
10229 return MDB_SUCCESS;
10233 mdb_env_get_userctx(MDB_env *env)
10235 return env ? env->me_userctx : NULL;
10239 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
10244 env->me_assert_func = func;
10246 return MDB_SUCCESS;
10250 mdb_env_get_path(MDB_env *env, const char **arg)
10255 *arg = env->me_path;
10256 return MDB_SUCCESS;
10260 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
10266 return MDB_SUCCESS;
10269 /** Common code for #mdb_stat() and #mdb_env_stat().
10270 * @param[in] env the environment to operate in.
10271 * @param[in] db the #MDB_db record containing the stats to return.
10272 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
10273 * @return 0, this function always succeeds.
10276 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
10278 arg->ms_psize = env->me_psize;
10279 arg->ms_depth = db->md_depth;
10280 arg->ms_branch_pages = db->md_branch_pages;
10281 arg->ms_leaf_pages = db->md_leaf_pages;
10282 arg->ms_overflow_pages = db->md_overflow_pages;
10283 arg->ms_entries = db->md_entries;
10285 return MDB_SUCCESS;
10289 mdb_env_stat(MDB_env *env, MDB_stat *arg)
10293 if (env == NULL || arg == NULL)
10296 meta = mdb_env_pick_meta(env);
10298 return mdb_stat0(env, &meta->mm_dbs[MAIN_DBI], arg);
10302 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
10306 if (env == NULL || arg == NULL)
10309 meta = mdb_env_pick_meta(env);
10310 arg->me_mapaddr = meta->mm_address;
10311 arg->me_last_pgno = meta->mm_last_pg;
10312 arg->me_last_txnid = meta->mm_txnid;
10314 arg->me_mapsize = env->me_mapsize;
10315 arg->me_maxreaders = env->me_maxreaders;
10316 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : 0;
10317 return MDB_SUCCESS;
10320 /** Set the default comparison functions for a database.
10321 * Called immediately after a database is opened to set the defaults.
10322 * The user can then override them with #mdb_set_compare() or
10323 * #mdb_set_dupsort().
10324 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
10325 * @param[in] dbi A database handle returned by #mdb_dbi_open()
10328 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
10330 uint16_t f = txn->mt_dbs[dbi].md_flags;
10332 txn->mt_dbxs[dbi].md_cmp =
10333 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
10334 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
10336 txn->mt_dbxs[dbi].md_dcmp =
10337 !(f & MDB_DUPSORT) ? 0 :
10338 ((f & MDB_INTEGERDUP)
10339 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
10340 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
10343 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
10349 int rc, dbflag, exact;
10350 unsigned int unused = 0, seq;
10354 if (flags & ~VALID_FLAGS)
10356 if (txn->mt_flags & MDB_TXN_BLOCKED)
10357 return MDB_BAD_TXN;
10362 if (flags & PERSISTENT_FLAGS) {
10363 uint16_t f2 = flags & PERSISTENT_FLAGS;
10364 /* make sure flag changes get committed */
10365 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
10366 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
10367 txn->mt_flags |= MDB_TXN_DIRTY;
10370 mdb_default_cmp(txn, MAIN_DBI);
10371 return MDB_SUCCESS;
10374 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
10375 mdb_default_cmp(txn, MAIN_DBI);
10378 /* Is the DB already open? */
10379 len = strlen(name);
10380 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
10381 if (!txn->mt_dbxs[i].md_name.mv_size) {
10382 /* Remember this free slot */
10383 if (!unused) unused = i;
10386 if (len == txn->mt_dbxs[i].md_name.mv_size &&
10387 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
10389 return MDB_SUCCESS;
10393 /* If no free slot and max hit, fail */
10394 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
10395 return MDB_DBS_FULL;
10397 /* Cannot mix named databases with some mainDB flags */
10398 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
10399 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
10401 /* Find the DB info */
10402 dbflag = DB_NEW|DB_VALID|DB_USRVALID;
10405 key.mv_data = (void *)name;
10406 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
10407 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
10408 if (rc == MDB_SUCCESS) {
10409 /* make sure this is actually a DB */
10410 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
10411 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
10412 return MDB_INCOMPATIBLE;
10413 } else if (! (rc == MDB_NOTFOUND && (flags & MDB_CREATE))) {
10417 /* Done here so we cannot fail after creating a new DB */
10418 if ((namedup = strdup(name)) == NULL)
10422 /* MDB_NOTFOUND and MDB_CREATE: Create new DB */
10423 data.mv_size = sizeof(MDB_db);
10424 data.mv_data = &dummy;
10425 memset(&dummy, 0, sizeof(dummy));
10426 dummy.md_root = P_INVALID;
10427 dummy.md_flags = flags & PERSISTENT_FLAGS;
10428 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
10429 dbflag |= DB_DIRTY;
10435 /* Got info, register DBI in this txn */
10436 unsigned int slot = unused ? unused : txn->mt_numdbs;
10437 txn->mt_dbxs[slot].md_name.mv_data = namedup;
10438 txn->mt_dbxs[slot].md_name.mv_size = len;
10439 txn->mt_dbxs[slot].md_rel = NULL;
10440 txn->mt_dbflags[slot] = dbflag;
10441 /* txn-> and env-> are the same in read txns, use
10442 * tmp variable to avoid undefined assignment
10444 seq = ++txn->mt_env->me_dbiseqs[slot];
10445 txn->mt_dbiseqs[slot] = seq;
10447 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
10449 mdb_default_cmp(txn, slot);
10459 mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
10461 if (!arg || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
10464 if (txn->mt_flags & MDB_TXN_BLOCKED)
10465 return MDB_BAD_TXN;
10467 if (txn->mt_dbflags[dbi] & DB_STALE) {
10470 /* Stale, must read the DB's root. cursor_init does it for us. */
10471 mdb_cursor_init(&mc, txn, dbi, &mx);
10473 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
10476 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
10479 if (dbi < CORE_DBS || dbi >= env->me_maxdbs)
10481 ptr = env->me_dbxs[dbi].md_name.mv_data;
10482 /* If there was no name, this was already closed */
10484 env->me_dbxs[dbi].md_name.mv_data = NULL;
10485 env->me_dbxs[dbi].md_name.mv_size = 0;
10486 env->me_dbflags[dbi] = 0;
10487 env->me_dbiseqs[dbi]++;
10492 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
10494 /* We could return the flags for the FREE_DBI too but what's the point? */
10495 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10497 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
10498 return MDB_SUCCESS;
10501 /** Add all the DB's pages to the free list.
10502 * @param[in] mc Cursor on the DB to free.
10503 * @param[in] subs non-Zero to check for sub-DBs in this DB.
10504 * @return 0 on success, non-zero on failure.
10507 mdb_drop0(MDB_cursor *mc, int subs)
10511 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
10512 if (rc == MDB_SUCCESS) {
10513 MDB_txn *txn = mc->mc_txn;
10518 /* DUPSORT sub-DBs have no ovpages/DBs. Omit scanning leaves.
10519 * This also avoids any P_LEAF2 pages, which have no nodes.
10520 * Also if the DB doesn't have sub-DBs and has no overflow
10521 * pages, omit scanning leaves.
10523 if ((mc->mc_flags & C_SUB) ||
10524 (!subs && !mc->mc_db->md_overflow_pages))
10525 mdb_cursor_pop(mc);
10527 mdb_cursor_copy(mc, &mx);
10529 /* bump refcount for mx's pages */
10530 for (i=0; i<mc->mc_snum; i++)
10531 mdb_page_get(&mx, mc->mc_pg[i]->mp_pgno, &mx.mc_pg[i], NULL);
10533 while (mc->mc_snum > 0) {
10534 MDB_page *mp = mc->mc_pg[mc->mc_top];
10535 unsigned n = NUMKEYS(mp);
10537 for (i=0; i<n; i++) {
10538 ni = NODEPTR(mp, i);
10539 if (ni->mn_flags & F_BIGDATA) {
10542 memcpy(&pg, NODEDATA(ni), sizeof(pg));
10543 rc = mdb_page_get(mc, pg, &omp, NULL);
10546 mdb_cassert(mc, IS_OVERFLOW(omp));
10547 rc = mdb_midl_append_range(&txn->mt_free_pgs,
10548 pg, omp->mp_pages);
10551 mc->mc_db->md_overflow_pages -= omp->mp_pages;
10552 if (!mc->mc_db->md_overflow_pages && !subs)
10554 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
10555 mdb_xcursor_init1(mc, ni);
10556 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
10561 if (!subs && !mc->mc_db->md_overflow_pages)
10564 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
10566 for (i=0; i<n; i++) {
10568 ni = NODEPTR(mp, i);
10571 mdb_midl_xappend(txn->mt_free_pgs, pg);
10576 mc->mc_ki[mc->mc_top] = i;
10577 rc = mdb_cursor_sibling(mc, 1);
10579 if (rc != MDB_NOTFOUND)
10581 /* no more siblings, go back to beginning
10582 * of previous level.
10585 mdb_cursor_pop(mc);
10587 for (i=1; i<mc->mc_snum; i++) {
10589 mc->mc_pg[i] = mx.mc_pg[i];
10594 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
10597 txn->mt_flags |= MDB_TXN_ERROR;
10599 /* drop refcount for mx's pages */
10600 mdb_cursor_unref(&mx);
10602 } else if (rc == MDB_NOTFOUND) {
10605 mc->mc_flags &= ~C_INITIALIZED;
10609 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
10611 MDB_cursor *mc, *m2;
10614 if ((unsigned)del > 1 || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10617 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
10620 if (TXN_DBI_CHANGED(txn, dbi))
10621 return MDB_BAD_DBI;
10623 rc = mdb_cursor_open(txn, dbi, &mc);
10627 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
10628 /* Invalidate the dropped DB's cursors */
10629 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
10630 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
10634 /* Can't delete the main DB */
10635 if (del && dbi >= CORE_DBS) {
10636 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, F_SUBDATA);
10638 txn->mt_dbflags[dbi] = DB_STALE;
10639 mdb_dbi_close(txn->mt_env, dbi);
10641 txn->mt_flags |= MDB_TXN_ERROR;
10644 /* reset the DB record, mark it dirty */
10645 txn->mt_dbflags[dbi] |= DB_DIRTY;
10646 txn->mt_dbs[dbi].md_depth = 0;
10647 txn->mt_dbs[dbi].md_branch_pages = 0;
10648 txn->mt_dbs[dbi].md_leaf_pages = 0;
10649 txn->mt_dbs[dbi].md_overflow_pages = 0;
10650 txn->mt_dbs[dbi].md_entries = 0;
10651 txn->mt_dbs[dbi].md_root = P_INVALID;
10653 txn->mt_flags |= MDB_TXN_DIRTY;
10656 mdb_cursor_close(mc);
10660 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
10662 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10665 txn->mt_dbxs[dbi].md_cmp = cmp;
10666 return MDB_SUCCESS;
10669 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
10671 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10674 txn->mt_dbxs[dbi].md_dcmp = cmp;
10675 return MDB_SUCCESS;
10678 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
10680 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10683 txn->mt_dbxs[dbi].md_rel = rel;
10684 return MDB_SUCCESS;
10687 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
10689 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10692 txn->mt_dbxs[dbi].md_relctx = ctx;
10693 return MDB_SUCCESS;
10697 mdb_env_get_maxkeysize(MDB_env *env)
10699 return ENV_MAXKEY(env);
10703 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
10705 unsigned int i, rdrs;
10708 int rc = 0, first = 1;
10712 if (!env->me_txns) {
10713 return func("(no reader locks)\n", ctx);
10715 rdrs = env->me_txns->mti_numreaders;
10716 mr = env->me_txns->mti_readers;
10717 for (i=0; i<rdrs; i++) {
10718 if (mr[i].mr_pid) {
10719 txnid_t txnid = mr[i].mr_txnid;
10720 sprintf(buf, txnid == (txnid_t)-1 ?
10721 "%10d %"Z"x -\n" : "%10d %"Z"x %"Y"u\n",
10722 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
10725 rc = func(" pid thread txnid\n", ctx);
10729 rc = func(buf, ctx);
10735 rc = func("(no active readers)\n", ctx);
10740 /** Insert pid into list if not already present.
10741 * return -1 if already present.
10744 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
10746 /* binary search of pid in list */
10748 unsigned cursor = 1;
10750 unsigned n = ids[0];
10753 unsigned pivot = n >> 1;
10754 cursor = base + pivot + 1;
10755 val = pid - ids[cursor];
10760 } else if ( val > 0 ) {
10765 /* found, so it's a duplicate */
10774 for (n = ids[0]; n > cursor; n--)
10781 mdb_reader_check(MDB_env *env, int *dead)
10787 return env->me_txns ? mdb_reader_check0(env, 0, dead) : MDB_SUCCESS;
10790 /** As #mdb_reader_check(). rlocked = <caller locked the reader mutex>. */
10792 mdb_reader_check0(MDB_env *env, int rlocked, int *dead)
10794 mdb_mutexref_t rmutex = rlocked ? NULL : env->me_rmutex;
10795 unsigned int i, j, rdrs;
10797 MDB_PID_T *pids, pid;
10798 int rc = MDB_SUCCESS, count = 0;
10800 rdrs = env->me_txns->mti_numreaders;
10801 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
10805 mr = env->me_txns->mti_readers;
10806 for (i=0; i<rdrs; i++) {
10807 pid = mr[i].mr_pid;
10808 if (pid && pid != env->me_pid) {
10809 if (mdb_pid_insert(pids, pid) == 0) {
10810 if (!mdb_reader_pid(env, Pidcheck, pid)) {
10811 /* Stale reader found */
10814 if ((rc = LOCK_MUTEX0(rmutex)) != 0) {
10815 if ((rc = mdb_mutex_failed(env, rmutex, rc)))
10817 rdrs = 0; /* the above checked all readers */
10819 /* Recheck, a new process may have reused pid */
10820 if (mdb_reader_pid(env, Pidcheck, pid))
10824 for (; j<rdrs; j++)
10825 if (mr[j].mr_pid == pid) {
10826 DPRINTF(("clear stale reader pid %u txn %"Y"d",
10827 (unsigned) pid, mr[j].mr_txnid));
10832 UNLOCK_MUTEX(rmutex);
10843 #ifdef MDB_ROBUST_SUPPORTED
10844 /** Handle #LOCK_MUTEX0() failure.
10845 * Try to repair the lock file if the mutex owner died.
10846 * @param[in] env the environment handle
10847 * @param[in] mutex LOCK_MUTEX0() mutex
10848 * @param[in] rc LOCK_MUTEX0() error (nonzero)
10849 * @return 0 on success with the mutex locked, or an error code on failure.
10852 mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc)
10857 if (rc == MDB_OWNERDEAD) {
10858 /* We own the mutex. Clean up after dead previous owner. */
10860 rlocked = (mutex == env->me_rmutex);
10862 /* Keep mti_txnid updated, otherwise next writer can
10863 * overwrite data which latest meta page refers to.
10865 meta = mdb_env_pick_meta(env);
10866 env->me_txns->mti_txnid = meta->mm_txnid;
10867 /* env is hosed if the dead thread was ours */
10869 env->me_flags |= MDB_FATAL_ERROR;
10870 env->me_txn = NULL;
10874 DPRINTF(("%cmutex owner died, %s", (rlocked ? 'r' : 'w'),
10875 (rc ? "this process' env is hosed" : "recovering")));
10876 rc2 = mdb_reader_check0(env, rlocked, NULL);
10878 rc2 = mdb_mutex_consistent(mutex);
10879 if (rc || (rc = rc2)) {
10880 DPRINTF(("LOCK_MUTEX recovery failed, %s", mdb_strerror(rc)));
10881 UNLOCK_MUTEX(mutex);
10887 DPRINTF(("LOCK_MUTEX failed, %s", mdb_strerror(rc)));
10892 #endif /* MDB_ROBUST_SUPPORTED */
10895 #if defined(_WIN32)
10896 static int utf8_to_utf16(const char *src, int srcsize, wchar_t **dst, int *dstsize)
10900 need = MultiByteToWideChar(CP_UTF8, 0, src, srcsize, NULL, 0);
10901 if (need == 0xFFFD)
10905 result = malloc(sizeof(wchar_t) * need);
10908 MultiByteToWideChar(CP_UTF8, 0, src, srcsize, result, need);
10914 #endif /* defined(_WIN32) */