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) \
340 (((thr) = CreateThread(NULL, 0, start, arg, 0, NULL)) ? 0 : ErrCode())
341 #define THREAD_FINISH(thr) \
342 (WaitForSingleObject(thr, INFINITE) ? ErrCode() : 0)
343 #define LOCK_MUTEX0(mutex) WaitForSingleObject(mutex, INFINITE)
344 #define UNLOCK_MUTEX(mutex) ReleaseMutex(mutex)
345 #define mdb_mutex_consistent(mutex) 0
346 #define getpid() GetCurrentProcessId()
347 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
348 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
349 #define ErrCode() GetLastError()
350 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
351 #define close(fd) (CloseHandle(fd) ? 0 : -1)
352 #define munmap(ptr,len) UnmapViewOfFile(ptr)
353 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
354 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
356 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
360 #define THREAD_RET void *
361 #define THREAD_CREATE(thr,start,arg) pthread_create(&thr,NULL,start,arg)
362 #define THREAD_FINISH(thr) pthread_join(thr,NULL)
363 #define Z "z" /**< printf format modifier for size_t */
365 /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
366 #define MDB_PIDLOCK 1
368 #ifdef MDB_USE_POSIX_SEM
370 typedef sem_t *mdb_mutex_t, *mdb_mutexref_t;
371 #define LOCK_MUTEX0(mutex) mdb_sem_wait(mutex)
372 #define UNLOCK_MUTEX(mutex) sem_post(mutex)
375 mdb_sem_wait(sem_t *sem)
378 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
382 #elif defined MDB_USE_SYSV_SEM
384 typedef struct mdb_mutex {
388 } mdb_mutex_t[1], *mdb_mutexref_t;
390 #define LOCK_MUTEX0(mutex) mdb_sem_wait(mutex)
391 #define UNLOCK_MUTEX(mutex) do { \
392 struct sembuf sb = { 0, 1, SEM_UNDO }; \
393 sb.sem_num = (mutex)->semnum; \
394 *(mutex)->locked = 0; \
395 semop((mutex)->semid, &sb, 1); \
399 mdb_sem_wait(mdb_mutexref_t sem)
401 int rc, *locked = sem->locked;
402 struct sembuf sb = { 0, -1, SEM_UNDO };
403 sb.sem_num = sem->semnum;
405 if (!semop(sem->semid, &sb, 1)) {
406 rc = *locked ? MDB_OWNERDEAD : MDB_SUCCESS;
410 } while ((rc = errno) == EINTR);
414 #define mdb_mutex_consistent(mutex) 0
416 #else /* MDB_USE_POSIX_MUTEX: */
417 /** Shared mutex/semaphore as it is stored (mdb_mutex_t), and as
418 * local variables keep it (mdb_mutexref_t).
420 * An mdb_mutex_t can be assigned to an mdb_mutexref_t. They can
421 * be the same, or an array[size 1] and a pointer.
424 typedef pthread_mutex_t mdb_mutex_t[1], *mdb_mutexref_t;
426 /** Lock the reader or writer mutex.
427 * Returns 0 or a code to give #mdb_mutex_failed(), as in #LOCK_MUTEX().
429 #define LOCK_MUTEX0(mutex) pthread_mutex_lock(mutex)
430 /** Unlock the reader or writer mutex.
432 #define UNLOCK_MUTEX(mutex) pthread_mutex_unlock(mutex)
433 /** Mark mutex-protected data as repaired, after death of previous owner.
435 #define mdb_mutex_consistent(mutex) pthread_mutex_consistent(mutex)
436 #endif /* MDB_USE_POSIX_SEM || MDB_USE_SYSV_SEM */
438 /** Get the error code for the last failed system function.
440 #define ErrCode() errno
442 /** An abstraction for a file handle.
443 * On POSIX systems file handles are small integers. On Windows
444 * they're opaque pointers.
448 /** A value for an invalid file handle.
449 * Mainly used to initialize file variables and signify that they are
452 #define INVALID_HANDLE_VALUE (-1)
454 /** Get the size of a memory page for the system.
455 * This is the basic size that the platform's memory manager uses, and is
456 * fundamental to the use of memory-mapped files.
458 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
471 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
473 #elif defined(MDB_USE_SYSV_SEM)
474 #define MNAME_LEN (sizeof(int))
476 #define MNAME_LEN (sizeof(pthread_mutex_t))
479 #ifdef MDB_USE_SYSV_SEM
480 #define SYSV_SEM_FLAG 1 /**< SysV sems in lockfile format */
482 #define SYSV_SEM_FLAG 0
487 #ifdef MDB_ROBUST_SUPPORTED
488 /** Lock mutex, handle any error, set rc = result.
489 * Return 0 on success, nonzero (not rc) on error.
491 #define LOCK_MUTEX(rc, env, mutex) \
492 (((rc) = LOCK_MUTEX0(mutex)) && \
493 ((rc) = mdb_mutex_failed(env, mutex, rc)))
494 static int mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc);
496 #define LOCK_MUTEX(rc, env, mutex) ((rc) = LOCK_MUTEX0(mutex))
497 #define mdb_mutex_failed(env, mutex, rc) (rc)
501 /** A flag for opening a file and requesting synchronous data writes.
502 * This is only used when writing a meta page. It's not strictly needed;
503 * we could just do a normal write and then immediately perform a flush.
504 * But if this flag is available it saves us an extra system call.
506 * @note If O_DSYNC is undefined but exists in /usr/include,
507 * preferably set some compiler flag to get the definition.
511 # define MDB_DSYNC O_DSYNC
513 # define MDB_DSYNC O_SYNC
518 /** Function for flushing the data of a file. Define this to fsync
519 * if fdatasync() is not supported.
521 #ifndef MDB_FDATASYNC
522 # define MDB_FDATASYNC fdatasync
526 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
537 /** A page number in the database.
538 * Note that 64 bit page numbers are overkill, since pages themselves
539 * already represent 12-13 bits of addressable memory, and the OS will
540 * always limit applications to a maximum of 63 bits of address space.
542 * @note In the #MDB_node structure, we only store 48 bits of this value,
543 * which thus limits us to only 60 bits of addressable data.
545 typedef MDB_ID pgno_t;
547 /** A transaction ID.
548 * See struct MDB_txn.mt_txnid for details.
550 typedef MDB_ID txnid_t;
552 /** @defgroup debug Debug Macros
556 /** Enable debug output. Needs variable argument macros (a C99 feature).
557 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
558 * read from and written to the database (used for free space management).
564 static int mdb_debug;
565 static txnid_t mdb_debug_start;
567 /** Print a debug message with printf formatting.
568 * Requires double parenthesis around 2 or more args.
570 # define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
571 # define DPRINTF0(fmt, ...) \
572 fprintf(stderr, "%s:%d " fmt "\n", mdb_func_, __LINE__, __VA_ARGS__)
574 # define DPRINTF(args) ((void) 0)
576 /** Print a debug string.
577 * The string is printed literally, with no format processing.
579 #define DPUTS(arg) DPRINTF(("%s", arg))
580 /** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
582 (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
585 /** @brief The maximum size of a database page.
587 * It is 32k or 64k, since value-PAGEBASE must fit in
588 * #MDB_page.%mp_upper.
590 * LMDB will use database pages < OS pages if needed.
591 * That causes more I/O in write transactions: The OS must
592 * know (read) the whole page before writing a partial page.
594 * Note that we don't currently support Huge pages. On Linux,
595 * regular data files cannot use Huge pages, and in general
596 * Huge pages aren't actually pageable. We rely on the OS
597 * demand-pager to read our data and page it out when memory
598 * pressure from other processes is high. So until OSs have
599 * actual paging support for Huge pages, they're not viable.
601 #define MAX_PAGESIZE (PAGEBASE ? 0x10000 : 0x8000)
603 /** The minimum number of keys required in a database page.
604 * Setting this to a larger value will place a smaller bound on the
605 * maximum size of a data item. Data items larger than this size will
606 * be pushed into overflow pages instead of being stored directly in
607 * the B-tree node. This value used to default to 4. With a page size
608 * of 4096 bytes that meant that any item larger than 1024 bytes would
609 * go into an overflow page. That also meant that on average 2-3KB of
610 * each overflow page was wasted space. The value cannot be lower than
611 * 2 because then there would no longer be a tree structure. With this
612 * value, items larger than 2KB will go into overflow pages, and on
613 * average only 1KB will be wasted.
615 #define MDB_MINKEYS 2
617 /** A stamp that identifies a file as an LMDB file.
618 * There's nothing special about this value other than that it is easily
619 * recognizable, and it will reflect any byte order mismatches.
621 #define MDB_MAGIC 0xBEEFC0DE
623 /** The version number for a database's datafile format. */
624 #define MDB_DATA_VERSION ((MDB_DEVEL) ? 999 : 1)
625 /** The version number for a database's lockfile format. */
626 #define MDB_LOCK_VERSION ((MDB_DEVEL) ? 999 : 1)
628 /** @brief The max size of a key we can write, or 0 for computed max.
630 * This macro should normally be left alone or set to 0.
631 * Note that a database with big keys or dupsort data cannot be
632 * reliably modified by a liblmdb which uses a smaller max.
633 * The default is 511 for backwards compat, or 0 when #MDB_DEVEL.
635 * Other values are allowed, for backwards compat. However:
636 * A value bigger than the computed max can break if you do not
637 * know what you are doing, and liblmdb <= 0.9.10 can break when
638 * modifying a DB with keys/dupsort data bigger than its max.
640 * Data items in an #MDB_DUPSORT database are also limited to
641 * this size, since they're actually keys of a sub-DB. Keys and
642 * #MDB_DUPSORT data items must fit on a node in a regular page.
644 #ifndef MDB_MAXKEYSIZE
645 #define MDB_MAXKEYSIZE ((MDB_DEVEL) ? 0 : 511)
648 /** The maximum size of a key we can write to the environment. */
650 #define ENV_MAXKEY(env) (MDB_MAXKEYSIZE)
652 #define ENV_MAXKEY(env) ((env)->me_maxkey)
655 /** @brief The maximum size of a data item.
657 * We only store a 32 bit value for node sizes.
659 #define MAXDATASIZE 0xffffffffUL
662 /** Key size which fits in a #DKBUF.
665 #define DKBUF_MAXKEYSIZE ((MDB_MAXKEYSIZE) > 0 ? (MDB_MAXKEYSIZE) : 511)
668 * This is used for printing a hex dump of a key's contents.
670 #define DKBUF char kbuf[DKBUF_MAXKEYSIZE*2+1]
671 /** Display a key in hex.
673 * Invoke a function to display a key in hex.
675 #define DKEY(x) mdb_dkey(x, kbuf)
681 /** An invalid page number.
682 * Mainly used to denote an empty tree.
684 #define P_INVALID (~(pgno_t)0)
686 /** Test if the flags \b f are set in a flag word \b w. */
687 #define F_ISSET(w, f) (((w) & (f)) == (f))
689 /** Round \b n up to an even number. */
690 #define EVEN(n) (((n) + 1U) & -2) /* sign-extending -2 to match n+1U */
692 /** Used for offsets within a single page.
693 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
696 typedef uint16_t indx_t;
698 /** Default size of memory map.
699 * This is certainly too small for any actual applications. Apps should always set
700 * the size explicitly using #mdb_env_set_mapsize().
702 #define DEFAULT_MAPSIZE 1048576
704 /** @defgroup readers Reader Lock Table
705 * Readers don't acquire any locks for their data access. Instead, they
706 * simply record their transaction ID in the reader table. The reader
707 * mutex is needed just to find an empty slot in the reader table. The
708 * slot's address is saved in thread-specific data so that subsequent read
709 * transactions started by the same thread need no further locking to proceed.
711 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
713 * No reader table is used if the database is on a read-only filesystem, or
714 * if #MDB_NOLOCK is set.
716 * Since the database uses multi-version concurrency control, readers don't
717 * actually need any locking. This table is used to keep track of which
718 * readers are using data from which old transactions, so that we'll know
719 * when a particular old transaction is no longer in use. Old transactions
720 * that have discarded any data pages can then have those pages reclaimed
721 * for use by a later write transaction.
723 * The lock table is constructed such that reader slots are aligned with the
724 * processor's cache line size. Any slot is only ever used by one thread.
725 * This alignment guarantees that there will be no contention or cache
726 * thrashing as threads update their own slot info, and also eliminates
727 * any need for locking when accessing a slot.
729 * A writer thread will scan every slot in the table to determine the oldest
730 * outstanding reader transaction. Any freed pages older than this will be
731 * reclaimed by the writer. The writer doesn't use any locks when scanning
732 * this table. This means that there's no guarantee that the writer will
733 * see the most up-to-date reader info, but that's not required for correct
734 * operation - all we need is to know the upper bound on the oldest reader,
735 * we don't care at all about the newest reader. So the only consequence of
736 * reading stale information here is that old pages might hang around a
737 * while longer before being reclaimed. That's actually good anyway, because
738 * the longer we delay reclaiming old pages, the more likely it is that a
739 * string of contiguous pages can be found after coalescing old pages from
740 * many old transactions together.
743 /** Number of slots in the reader table.
744 * This value was chosen somewhat arbitrarily. 126 readers plus a
745 * couple mutexes fit exactly into 8KB on my development machine.
746 * Applications should set the table size using #mdb_env_set_maxreaders().
748 #define DEFAULT_READERS 126
750 /** The size of a CPU cache line in bytes. We want our lock structures
751 * aligned to this size to avoid false cache line sharing in the
753 * This value works for most CPUs. For Itanium this should be 128.
759 /** The information we store in a single slot of the reader table.
760 * In addition to a transaction ID, we also record the process and
761 * thread ID that owns a slot, so that we can detect stale information,
762 * e.g. threads or processes that went away without cleaning up.
763 * @note We currently don't check for stale records. We simply re-init
764 * the table when we know that we're the only process opening the
767 typedef struct MDB_rxbody {
768 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
769 * Multiple readers that start at the same time will probably have the
770 * same ID here. Again, it's not important to exclude them from
771 * anything; all we need to know is which version of the DB they
772 * started from so we can avoid overwriting any data used in that
773 * particular version.
775 volatile txnid_t mrb_txnid;
776 /** The process ID of the process owning this reader txn. */
777 volatile MDB_PID_T mrb_pid;
778 /** The thread ID of the thread owning this txn. */
779 volatile MDB_THR_T mrb_tid;
782 /** The actual reader record, with cacheline padding. */
783 typedef struct MDB_reader {
786 /** shorthand for mrb_txnid */
787 #define mr_txnid mru.mrx.mrb_txnid
788 #define mr_pid mru.mrx.mrb_pid
789 #define mr_tid mru.mrx.mrb_tid
790 /** cache line alignment */
791 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
795 /** The header for the reader table.
796 * The table resides in a memory-mapped file. (This is a different file
797 * than is used for the main database.)
799 * For POSIX the actual mutexes reside in the shared memory of this
800 * mapped file. On Windows, mutexes are named objects allocated by the
801 * kernel; we store the mutex names in this mapped file so that other
802 * processes can grab them. This same approach is also used on
803 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
804 * process-shared POSIX mutexes. For these cases where a named object
805 * is used, the object name is derived from a 64 bit FNV hash of the
806 * environment pathname. As such, naming collisions are extremely
807 * unlikely. If a collision occurs, the results are unpredictable.
809 typedef struct MDB_txbody {
810 /** Stamp identifying this as an LMDB file. It must be set
813 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
815 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
816 char mtb_rmname[MNAME_LEN];
817 #elif defined(MDB_USE_SYSV_SEM)
821 /** Mutex protecting access to this table.
822 * This is the reader table lock used with LOCK_MUTEX().
824 mdb_mutex_t mtb_rmutex;
826 /** The ID of the last transaction committed to the database.
827 * This is recorded here only for convenience; the value can always
828 * be determined by reading the main database meta pages.
830 volatile txnid_t mtb_txnid;
831 /** The number of slots that have been used in the reader table.
832 * This always records the maximum count, it is not decremented
833 * when readers release their slots.
835 volatile unsigned mtb_numreaders;
838 /** The actual reader table definition. */
839 typedef struct MDB_txninfo {
842 #define mti_magic mt1.mtb.mtb_magic
843 #define mti_format mt1.mtb.mtb_format
844 #define mti_rmutex mt1.mtb.mtb_rmutex
845 #define mti_rmname mt1.mtb.mtb_rmname
846 #define mti_txnid mt1.mtb.mtb_txnid
847 #define mti_numreaders mt1.mtb.mtb_numreaders
848 #ifdef MDB_USE_SYSV_SEM
849 #define mti_semid mt1.mtb.mtb_semid
850 #define mti_rlocked mt1.mtb.mtb_rlocked
852 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
855 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
856 char mt2_wmname[MNAME_LEN];
857 #define mti_wmname mt2.mt2_wmname
858 #elif defined MDB_USE_SYSV_SEM
860 #define mti_wlocked mt2.mt2_wlocked
862 mdb_mutex_t mt2_wmutex;
863 #define mti_wmutex mt2.mt2_wmutex
865 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
867 MDB_reader mti_readers[1];
870 /** Lockfile format signature: version, features and field layout */
871 #define MDB_LOCK_FORMAT \
873 ((MDB_LOCK_VERSION) \
874 /* Flags which describe functionality */ \
875 + (SYSV_SEM_FLAG << 18) \
876 + (((MDB_PIDLOCK) != 0) << 16)))
879 /** Common header for all page types.
880 * Overflow records occupy a number of contiguous pages with no
881 * headers on any page after the first.
883 typedef struct MDB_page {
884 #define mp_pgno mp_p.p_pgno
885 #define mp_next mp_p.p_next
887 pgno_t p_pgno; /**< page number */
888 struct MDB_page *p_next; /**< for in-memory list of freed pages */
891 /** @defgroup mdb_page Page Flags
893 * Flags for the page headers.
896 #define P_BRANCH 0x01 /**< branch page */
897 #define P_LEAF 0x02 /**< leaf page */
898 #define P_OVERFLOW 0x04 /**< overflow page */
899 #define P_META 0x08 /**< meta page */
900 #define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
901 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
902 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
903 #define P_LOOSE 0x4000 /**< page was dirtied then freed, can be reused */
904 #define P_KEEP 0x8000 /**< leave this page alone during spill */
906 uint16_t mp_flags; /**< @ref mdb_page */
907 #define mp_lower mp_pb.pb.pb_lower
908 #define mp_upper mp_pb.pb.pb_upper
909 #define mp_pages mp_pb.pb_pages
912 indx_t pb_lower; /**< lower bound of free space */
913 indx_t pb_upper; /**< upper bound of free space */
915 uint32_t pb_pages; /**< number of overflow pages */
917 indx_t mp_ptrs[1]; /**< dynamic size */
920 /** Size of the page header, excluding dynamic data at the end */
921 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
923 /** Address of first usable data byte in a page, after the header */
924 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
926 /** ITS#7713, change PAGEBASE to handle 65536 byte pages */
927 #define PAGEBASE ((MDB_DEVEL) ? PAGEHDRSZ : 0)
929 /** Number of nodes on a page */
930 #define NUMKEYS(p) (((p)->mp_lower - (PAGEHDRSZ-PAGEBASE)) >> 1)
932 /** The amount of space remaining in the page */
933 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
935 /** The percentage of space used in the page, in tenths of a percent. */
936 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
937 ((env)->me_psize - PAGEHDRSZ))
938 /** The minimum page fill factor, in tenths of a percent.
939 * Pages emptier than this are candidates for merging.
941 #define FILL_THRESHOLD 250
943 /** Test if a page is a leaf page */
944 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
945 /** Test if a page is a LEAF2 page */
946 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
947 /** Test if a page is a branch page */
948 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
949 /** Test if a page is an overflow page */
950 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
951 /** Test if a page is a sub page */
952 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
954 /** The number of overflow pages needed to store the given size. */
955 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
957 /** Link in #MDB_txn.%mt_loose_pgs list */
958 #define NEXT_LOOSE_PAGE(p) (*(MDB_page **)((p) + 2))
960 /** Header for a single key/data pair within a page.
961 * Used in pages of type #P_BRANCH and #P_LEAF without #P_LEAF2.
962 * We guarantee 2-byte alignment for 'MDB_node's.
964 typedef struct MDB_node {
965 /** lo and hi are used for data size on leaf nodes and for
966 * child pgno on branch nodes. On 64 bit platforms, flags
967 * is also used for pgno. (Branch nodes have no flags).
968 * They are in host byte order in case that lets some
969 * accesses be optimized into a 32-bit word access.
971 #if BYTE_ORDER == LITTLE_ENDIAN
972 unsigned short mn_lo, mn_hi; /**< part of data size or pgno */
974 unsigned short mn_hi, mn_lo;
976 /** @defgroup mdb_node Node Flags
978 * Flags for node headers.
981 #define F_BIGDATA 0x01 /**< data put on overflow page */
982 #define F_SUBDATA 0x02 /**< data is a sub-database */
983 #define F_DUPDATA 0x04 /**< data has duplicates */
985 /** valid flags for #mdb_node_add() */
986 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
989 unsigned short mn_flags; /**< @ref mdb_node */
990 unsigned short mn_ksize; /**< key size */
991 char mn_data[1]; /**< key and data are appended here */
994 /** Size of the node header, excluding dynamic data at the end */
995 #define NODESIZE offsetof(MDB_node, mn_data)
997 /** Bit position of top word in page number, for shifting mn_flags */
998 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
1000 /** Size of a node in a branch page with a given key.
1001 * This is just the node header plus the key, there is no data.
1003 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
1005 /** Size of a node in a leaf page with a given key and data.
1006 * This is node header plus key plus data size.
1008 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
1010 /** Address of node \b i in page \b p */
1011 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i] + PAGEBASE))
1013 /** Address of the key for the node */
1014 #define NODEKEY(node) (void *)((node)->mn_data)
1016 /** Address of the data for a node */
1017 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
1019 /** Get the page number pointed to by a branch node */
1020 #define NODEPGNO(node) \
1021 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
1022 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
1023 /** Set the page number in a branch node */
1024 #define SETPGNO(node,pgno) do { \
1025 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
1026 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
1028 /** Get the size of the data in a leaf node */
1029 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
1030 /** Set the size of the data for a leaf node */
1031 #define SETDSZ(node,size) do { \
1032 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
1033 /** The size of a key in a node */
1034 #define NODEKSZ(node) ((node)->mn_ksize)
1036 /** Copy a page number from src to dst */
1037 #ifdef MISALIGNED_OK
1038 #define COPY_PGNO(dst,src) dst = src
1040 #if SIZE_MAX > 4294967295UL
1041 #define COPY_PGNO(dst,src) do { \
1042 unsigned short *s, *d; \
1043 s = (unsigned short *)&(src); \
1044 d = (unsigned short *)&(dst); \
1051 #define COPY_PGNO(dst,src) do { \
1052 unsigned short *s, *d; \
1053 s = (unsigned short *)&(src); \
1054 d = (unsigned short *)&(dst); \
1060 /** The address of a key in a LEAF2 page.
1061 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
1062 * There are no node headers, keys are stored contiguously.
1064 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
1066 /** Set the \b node's key into \b keyptr, if requested. */
1067 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
1068 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
1070 /** Set the \b node's key into \b key. */
1071 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
1073 /** Information about a single database in the environment. */
1074 typedef struct MDB_db {
1075 uint32_t md_pad; /**< also ksize for LEAF2 pages */
1076 uint16_t md_flags; /**< @ref mdb_dbi_open */
1077 uint16_t md_depth; /**< depth of this tree */
1078 pgno_t md_branch_pages; /**< number of internal pages */
1079 pgno_t md_leaf_pages; /**< number of leaf pages */
1080 pgno_t md_overflow_pages; /**< number of overflow pages */
1081 mdb_size_t md_entries; /**< number of data items */
1082 pgno_t md_root; /**< the root page of this tree */
1085 /** mdb_dbi_open flags */
1086 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
1087 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
1088 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
1089 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
1091 /** Handle for the DB used to track free pages. */
1093 /** Handle for the default DB. */
1095 /** Number of DBs in metapage (free and main) - also hardcoded elsewhere */
1098 /** Number of meta pages - also hardcoded elsewhere */
1101 /** Meta page content.
1102 * A meta page is the start point for accessing a database snapshot.
1103 * Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
1105 typedef struct MDB_meta {
1106 /** Stamp identifying this as an LMDB file. It must be set
1109 /** Version number of this file. Must be set to #MDB_DATA_VERSION. */
1110 uint32_t mm_version;
1112 union { /* always zero since we don't support fixed mapping in MDB_VL32 */
1116 #define mm_address mm_un.mmun_address
1118 void *mm_address; /**< address for fixed mapping */
1120 pgno_t mm_mapsize; /**< size of mmap region */
1121 MDB_db mm_dbs[CORE_DBS]; /**< first is free space, 2nd is main db */
1122 /** The size of pages used in this DB */
1123 #define mm_psize mm_dbs[FREE_DBI].md_pad
1124 /** Any persistent environment flags. @ref mdb_env */
1125 #define mm_flags mm_dbs[FREE_DBI].md_flags
1126 pgno_t mm_last_pg; /**< last used page in file */
1127 volatile txnid_t mm_txnid; /**< txnid that committed this page */
1130 /** Buffer for a stack-allocated meta page.
1131 * The members define size and alignment, and silence type
1132 * aliasing warnings. They are not used directly; that could
1133 * mean incorrectly using several union members in parallel.
1135 typedef union MDB_metabuf {
1138 char mm_pad[PAGEHDRSZ];
1143 /** Auxiliary DB info.
1144 * The information here is mostly static/read-only. There is
1145 * only a single copy of this record in the environment.
1147 typedef struct MDB_dbx {
1148 MDB_val md_name; /**< name of the database */
1149 MDB_cmp_func *md_cmp; /**< function for comparing keys */
1150 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
1151 MDB_rel_func *md_rel; /**< user relocate function */
1152 void *md_relctx; /**< user-provided context for md_rel */
1155 /** A database transaction.
1156 * Every operation requires a transaction handle.
1159 MDB_txn *mt_parent; /**< parent of a nested txn */
1160 /** Nested txn under this txn, set together with flag #MDB_TXN_HAS_CHILD */
1162 pgno_t mt_next_pgno; /**< next unallocated page */
1164 pgno_t mt_last_pgno; /**< last written page */
1166 /** The ID of this transaction. IDs are integers incrementing from 1.
1167 * Only committed write transactions increment the ID. If a transaction
1168 * aborts, the ID may be re-used by the next writer.
1171 MDB_env *mt_env; /**< the DB environment */
1172 /** The list of pages that became unused during this transaction.
1174 MDB_IDL mt_free_pgs;
1175 /** The list of loose pages that became unused and may be reused
1176 * in this transaction, linked through #NEXT_LOOSE_PAGE(page).
1178 MDB_page *mt_loose_pgs;
1179 /* #Number of loose pages (#mt_loose_pgs) */
1181 /** The sorted list of dirty pages we temporarily wrote to disk
1182 * because the dirty list was full. page numbers in here are
1183 * shifted left by 1, deleted slots have the LSB set.
1185 MDB_IDL mt_spill_pgs;
1187 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
1188 MDB_ID2L dirty_list;
1189 /** For read txns: This thread/txn's reader table slot, or NULL. */
1192 /** Array of records for each DB known in the environment. */
1194 /** Array of MDB_db records for each known DB */
1196 /** Array of sequence numbers for each DB handle */
1197 unsigned int *mt_dbiseqs;
1198 /** @defgroup mt_dbflag Transaction DB Flags
1202 #define DB_DIRTY 0x01 /**< DB was modified or is DUPSORT data */
1203 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
1204 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
1205 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
1206 #define DB_USRVALID 0x10 /**< As #DB_VALID, but not set for #FREE_DBI */
1208 /** In write txns, array of cursors for each DB */
1209 MDB_cursor **mt_cursors;
1210 /** Array of flags for each DB */
1211 unsigned char *mt_dbflags;
1213 /** List of read-only pages (actually chunks) */
1215 /** We map chunks of 16 pages. Even though Windows uses 4KB pages, all
1216 * mappings must begin on 64KB boundaries. So we round off all pgnos to
1217 * a chunk boundary. We do the same on Linux for symmetry, and also to
1218 * reduce the frequency of mmap/munmap calls.
1220 #define MDB_RPAGE_CHUNK 16
1221 #define MDB_TRPAGE_SIZE 4096 /**< size of #mt_rpages array of chunks */
1222 #define MDB_TRPAGE_MAX (MDB_TRPAGE_SIZE-1) /**< maximum chunk index */
1223 unsigned int mt_rpcheck; /**< threshold for reclaiming unref'd chunks */
1225 /** Number of DB records in use, or 0 when the txn is finished.
1226 * This number only ever increments until the txn finishes; we
1227 * don't decrement it when individual DB handles are closed.
1231 /** @defgroup mdb_txn Transaction Flags
1235 /** #mdb_txn_begin() flags */
1236 #define MDB_TXN_BEGIN_FLAGS (MDB_NOMETASYNC|MDB_NOSYNC|MDB_RDONLY)
1237 #define MDB_TXN_NOMETASYNC MDB_NOMETASYNC /**< don't sync meta for this txn on commit */
1238 #define MDB_TXN_NOSYNC MDB_NOSYNC /**< don't sync this txn on commit */
1239 #define MDB_TXN_RDONLY MDB_RDONLY /**< read-only transaction */
1240 /* internal txn flags */
1241 #define MDB_TXN_WRITEMAP MDB_WRITEMAP /**< copy of #MDB_env flag in writers */
1242 #define MDB_TXN_FINISHED 0x01 /**< txn is finished or never began */
1243 #define MDB_TXN_ERROR 0x02 /**< txn is unusable after an error */
1244 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
1245 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
1246 #define MDB_TXN_HAS_CHILD 0x10 /**< txn has an #MDB_txn.%mt_child */
1247 /** most operations on the txn are currently illegal */
1248 #define MDB_TXN_BLOCKED (MDB_TXN_FINISHED|MDB_TXN_ERROR|MDB_TXN_HAS_CHILD)
1250 unsigned int mt_flags; /**< @ref mdb_txn */
1251 /** #dirty_list room: Array size - \#dirty pages visible to this txn.
1252 * Includes ancestor txns' dirty pages not hidden by other txns'
1253 * dirty/spilled pages. Thus commit(nested txn) has room to merge
1254 * dirty_list into mt_parent after freeing hidden mt_parent pages.
1256 unsigned int mt_dirty_room;
1259 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
1260 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
1261 * raise this on a 64 bit machine.
1263 #define CURSOR_STACK 32
1267 /** Cursors are used for all DB operations.
1268 * A cursor holds a path of (page pointer, key index) from the DB
1269 * root to a position in the DB, plus other state. #MDB_DUPSORT
1270 * cursors include an xcursor to the current data item. Write txns
1271 * track their cursors and keep them up to date when data moves.
1272 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
1273 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
1276 /** Next cursor on this DB in this txn */
1277 MDB_cursor *mc_next;
1278 /** Backup of the original cursor if this cursor is a shadow */
1279 MDB_cursor *mc_backup;
1280 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
1281 struct MDB_xcursor *mc_xcursor;
1282 /** The transaction that owns this cursor */
1284 /** The database handle this cursor operates on */
1286 /** The database record for this cursor */
1288 /** The database auxiliary record for this cursor */
1290 /** The @ref mt_dbflag for this database */
1291 unsigned char *mc_dbflag;
1292 unsigned short mc_snum; /**< number of pushed pages */
1293 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
1294 /** @defgroup mdb_cursor Cursor Flags
1296 * Cursor state flags.
1299 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
1300 #define C_EOF 0x02 /**< No more data */
1301 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
1302 #define C_DEL 0x08 /**< last op was a cursor_del */
1303 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
1304 #define C_WRITEMAP MDB_TXN_WRITEMAP /**< Copy of txn flag */
1305 /** Read-only cursor into the txn's original snapshot in the map.
1306 * Set for read-only txns, and in #mdb_page_alloc() for #FREE_DBI when
1307 * #MDB_DEVEL & 2. Only implements code which is necessary for this.
1309 #define C_ORIG_RDONLY MDB_TXN_RDONLY
1311 unsigned int mc_flags; /**< @ref mdb_cursor */
1312 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
1313 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
1315 MDB_page *mc_ovpg; /**< a referenced overflow page */
1319 /** Context for sorted-dup records.
1320 * We could have gone to a fully recursive design, with arbitrarily
1321 * deep nesting of sub-databases. But for now we only handle these
1322 * levels - main DB, optional sub-DB, sorted-duplicate DB.
1324 typedef struct MDB_xcursor {
1325 /** A sub-cursor for traversing the Dup DB */
1326 MDB_cursor mx_cursor;
1327 /** The database record for this Dup DB */
1329 /** The auxiliary DB record for this Dup DB */
1331 /** The @ref mt_dbflag for this Dup DB */
1332 unsigned char mx_dbflag;
1335 /** State of FreeDB old pages, stored in the MDB_env */
1336 typedef struct MDB_pgstate {
1337 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1338 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1341 /** The database environment. */
1343 HANDLE me_fd; /**< The main data file */
1344 HANDLE me_lfd; /**< The lock file */
1345 HANDLE me_mfd; /**< just for writing the meta pages */
1346 #if defined(MDB_VL32) && defined(_WIN32)
1347 HANDLE me_fmh; /**< File Mapping handle */
1349 /** Failed to update the meta page. Probably an I/O error. */
1350 #define MDB_FATAL_ERROR 0x80000000U
1351 /** Some fields are initialized. */
1352 #define MDB_ENV_ACTIVE 0x20000000U
1353 /** me_txkey is set */
1354 #define MDB_ENV_TXKEY 0x10000000U
1355 /** fdatasync is unreliable */
1356 #define MDB_FSYNCONLY 0x08000000U
1357 uint32_t me_flags; /**< @ref mdb_env */
1358 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1359 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1360 unsigned int me_maxreaders; /**< size of the reader table */
1361 /** Max #MDB_txninfo.%mti_numreaders of interest to #mdb_env_close() */
1362 volatile int me_close_readers;
1363 MDB_dbi me_numdbs; /**< number of DBs opened */
1364 MDB_dbi me_maxdbs; /**< size of the DB table */
1365 MDB_PID_T me_pid; /**< process ID of this env */
1366 char *me_path; /**< path to the DB files */
1367 char *me_map; /**< the memory map of the data file */
1368 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1369 MDB_meta *me_metas[NUM_METAS]; /**< pointers to the two meta pages */
1370 void *me_pbuf; /**< scratch area for DUPSORT put() */
1371 MDB_txn *me_txn; /**< current write transaction */
1372 MDB_txn *me_txn0; /**< prealloc'd write transaction */
1373 mdb_size_t me_mapsize; /**< size of the data memory map */
1374 off_t me_size; /**< current file size */
1375 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1376 MDB_dbx *me_dbxs; /**< array of static DB info */
1377 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1378 unsigned int *me_dbiseqs; /**< array of dbi sequence numbers */
1379 pthread_key_t me_txkey; /**< thread-key for readers */
1380 txnid_t me_pgoldest; /**< ID of oldest reader last time we looked */
1381 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1382 # define me_pglast me_pgstate.mf_pglast
1383 # define me_pghead me_pgstate.mf_pghead
1384 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1385 /** IDL of pages that became unused in a write txn */
1386 MDB_IDL me_free_pgs;
1387 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1388 MDB_ID2L me_dirty_list;
1389 /** Max number of freelist items that can fit in a single overflow page */
1391 /** Max size of a node on a page */
1392 unsigned int me_nodemax;
1393 #if !(MDB_MAXKEYSIZE)
1394 unsigned int me_maxkey; /**< max size of a key */
1396 int me_live_reader; /**< have liveness lock in reader table */
1398 int me_pidquery; /**< Used in OpenProcess */
1400 #ifdef MDB_USE_POSIX_MUTEX /* Posix mutexes reside in shared mem */
1401 # define me_rmutex me_txns->mti_rmutex /**< Shared reader lock */
1402 # define me_wmutex me_txns->mti_wmutex /**< Shared writer lock */
1404 mdb_mutex_t me_rmutex;
1405 mdb_mutex_t me_wmutex;
1408 MDB_ID3L me_rpages; /**< like #mt_rpages, but global to env */
1409 pthread_mutex_t me_rpmutex; /**< control access to #me_rpages */
1410 #define MDB_ERPAGE_SIZE 16384
1411 #define MDB_ERPAGE_MAX (MDB_ERPAGE_SIZE-1)
1412 unsigned int me_rpcheck;
1414 void *me_userctx; /**< User-settable context */
1415 MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
1418 /** Nested transaction */
1419 typedef struct MDB_ntxn {
1420 MDB_txn mnt_txn; /**< the transaction */
1421 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1424 /** max number of pages to commit in one writev() call */
1425 #define MDB_COMMIT_PAGES 64
1426 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1427 #undef MDB_COMMIT_PAGES
1428 #define MDB_COMMIT_PAGES IOV_MAX
1431 /** max bytes to write in one call */
1432 #define MAX_WRITE (0x40000000U >> (sizeof(ssize_t) == 4))
1434 /** Check \b txn and \b dbi arguments to a function */
1435 #define TXN_DBI_EXIST(txn, dbi, validity) \
1436 ((txn) && (dbi)<(txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & (validity)))
1438 /** Check for misused \b dbi handles */
1439 #define TXN_DBI_CHANGED(txn, dbi) \
1440 ((txn)->mt_dbiseqs[dbi] != (txn)->mt_env->me_dbiseqs[dbi])
1442 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1443 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1444 static int mdb_page_touch(MDB_cursor *mc);
1446 #define MDB_END_NAMES {"committed", "empty-commit", "abort", "reset", \
1447 "reset-tmp", "fail-begin", "fail-beginchild"}
1449 /* mdb_txn_end operation number, for logging */
1450 MDB_END_COMMITTED, MDB_END_EMPTY_COMMIT, MDB_END_ABORT, MDB_END_RESET,
1451 MDB_END_RESET_TMP, MDB_END_FAIL_BEGIN, MDB_END_FAIL_BEGINCHILD
1453 #define MDB_END_OPMASK 0x0F /**< mask for #mdb_txn_end() operation number */
1454 #define MDB_END_UPDATE 0x10 /**< update env state (DBIs) */
1455 #define MDB_END_FREE 0x20 /**< free txn unless it is #MDB_env.%me_txn0 */
1456 #define MDB_END_SLOT MDB_NOTLS /**< release any reader slot if #MDB_NOTLS */
1457 static void mdb_txn_end(MDB_txn *txn, unsigned mode);
1459 static int mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **mp, int *lvl);
1460 static int mdb_page_search_root(MDB_cursor *mc,
1461 MDB_val *key, int modify);
1462 #define MDB_PS_MODIFY 1
1463 #define MDB_PS_ROOTONLY 2
1464 #define MDB_PS_FIRST 4
1465 #define MDB_PS_LAST 8
1466 static int mdb_page_search(MDB_cursor *mc,
1467 MDB_val *key, int flags);
1468 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1470 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1471 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1472 pgno_t newpgno, unsigned int nflags);
1474 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1475 static MDB_meta *mdb_env_pick_meta(const MDB_env *env);
1476 static int mdb_env_write_meta(MDB_txn *txn);
1477 #ifdef MDB_USE_POSIX_MUTEX /* Drop unused excl arg */
1478 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1480 static void mdb_env_close0(MDB_env *env, int excl);
1482 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1483 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1484 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1485 static void mdb_node_del(MDB_cursor *mc, int ksize);
1486 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1487 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft);
1488 static int mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data);
1489 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1490 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1492 static int mdb_rebalance(MDB_cursor *mc);
1493 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1495 static void mdb_cursor_pop(MDB_cursor *mc);
1496 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1498 static int mdb_cursor_del0(MDB_cursor *mc);
1499 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
1500 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1501 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1502 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1503 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1505 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1506 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1508 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1509 static void mdb_xcursor_init0(MDB_cursor *mc);
1510 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1511 static void mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int force);
1513 static int mdb_drop0(MDB_cursor *mc, int subs);
1514 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1515 static int mdb_reader_check0(MDB_env *env, int rlocked, int *dead);
1518 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1521 /** Compare two items pointing at size_t's of unknown alignment. */
1522 #ifdef MISALIGNED_OK
1523 # define mdb_cmp_clong mdb_cmp_long
1525 # define mdb_cmp_clong mdb_cmp_cint
1529 static SECURITY_DESCRIPTOR mdb_null_sd;
1530 static SECURITY_ATTRIBUTES mdb_all_sa;
1531 static int mdb_sec_inited;
1533 static int utf8_to_utf16(const char *src, int srcsize, wchar_t **dst, int *dstsize);
1536 /** Return the library version info. */
1538 mdb_version(int *major, int *minor, int *patch)
1540 if (major) *major = MDB_VERSION_MAJOR;
1541 if (minor) *minor = MDB_VERSION_MINOR;
1542 if (patch) *patch = MDB_VERSION_PATCH;
1543 return MDB_VERSION_STRING;
1546 /** Table of descriptions for LMDB @ref errors */
1547 static char *const mdb_errstr[] = {
1548 "MDB_KEYEXIST: Key/data pair already exists",
1549 "MDB_NOTFOUND: No matching key/data pair found",
1550 "MDB_PAGE_NOTFOUND: Requested page not found",
1551 "MDB_CORRUPTED: Located page was wrong type",
1552 "MDB_PANIC: Update of meta page failed or environment had fatal error",
1553 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1554 "MDB_INVALID: File is not an LMDB file",
1555 "MDB_MAP_FULL: Environment mapsize limit reached",
1556 "MDB_DBS_FULL: Environment maxdbs limit reached",
1557 "MDB_READERS_FULL: Environment maxreaders limit reached",
1558 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1559 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1560 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1561 "MDB_PAGE_FULL: Internal error - page has no more space",
1562 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1563 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1564 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1565 "MDB_BAD_TXN: Transaction must abort, has a child, or is invalid",
1566 "MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
1567 "MDB_BAD_DBI: The specified DBI handle was closed/changed unexpectedly",
1571 mdb_strerror(int err)
1574 /** HACK: pad 4KB on stack over the buf. Return system msgs in buf.
1575 * This works as long as no function between the call to mdb_strerror
1576 * and the actual use of the message uses more than 4K of stack.
1578 #define MSGSIZE 1024
1579 #define PADSIZE 4096
1580 char buf[MSGSIZE+PADSIZE], *ptr = buf;
1584 return ("Successful return: 0");
1586 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1587 i = err - MDB_KEYEXIST;
1588 return mdb_errstr[i];
1592 /* These are the C-runtime error codes we use. The comment indicates
1593 * their numeric value, and the Win32 error they would correspond to
1594 * if the error actually came from a Win32 API. A major mess, we should
1595 * have used LMDB-specific error codes for everything.
1598 case ENOENT: /* 2, FILE_NOT_FOUND */
1599 case EIO: /* 5, ACCESS_DENIED */
1600 case ENOMEM: /* 12, INVALID_ACCESS */
1601 case EACCES: /* 13, INVALID_DATA */
1602 case EBUSY: /* 16, CURRENT_DIRECTORY */
1603 case EINVAL: /* 22, BAD_COMMAND */
1604 case ENOSPC: /* 28, OUT_OF_PAPER */
1605 return strerror(err);
1610 FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
1611 FORMAT_MESSAGE_IGNORE_INSERTS,
1612 NULL, err, 0, ptr, MSGSIZE, (va_list *)buf+MSGSIZE);
1615 return strerror(err);
1619 /** assert(3) variant in cursor context */
1620 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1621 /** assert(3) variant in transaction context */
1622 #define mdb_tassert(txn, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1623 /** assert(3) variant in environment context */
1624 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1627 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1628 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1631 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1632 const char *func, const char *file, int line)
1635 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1636 file, line, expr_txt, func);
1637 if (env->me_assert_func)
1638 env->me_assert_func(env, buf);
1639 fprintf(stderr, "%s\n", buf);
1643 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1647 /** Return the page number of \b mp which may be sub-page, for debug output */
1649 mdb_dbg_pgno(MDB_page *mp)
1652 COPY_PGNO(ret, mp->mp_pgno);
1656 /** Display a key in hexadecimal and return the address of the result.
1657 * @param[in] key the key to display
1658 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1659 * @return The key in hexadecimal form.
1662 mdb_dkey(MDB_val *key, char *buf)
1665 unsigned char *c = key->mv_data;
1671 if (key->mv_size > DKBUF_MAXKEYSIZE)
1672 return "MDB_MAXKEYSIZE";
1673 /* may want to make this a dynamic check: if the key is mostly
1674 * printable characters, print it as-is instead of converting to hex.
1678 for (i=0; i<key->mv_size; i++)
1679 ptr += sprintf(ptr, "%02x", *c++);
1681 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1687 mdb_leafnode_type(MDB_node *n)
1689 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1690 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1691 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1694 /** Display all the keys in the page. */
1696 mdb_page_list(MDB_page *mp)
1698 pgno_t pgno = mdb_dbg_pgno(mp);
1699 const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
1701 unsigned int i, nkeys, nsize, total = 0;
1705 switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1706 case P_BRANCH: type = "Branch page"; break;
1707 case P_LEAF: type = "Leaf page"; break;
1708 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1709 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1710 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1712 fprintf(stderr, "Overflow page %"Y"u pages %u%s\n",
1713 pgno, mp->mp_pages, state);
1716 fprintf(stderr, "Meta-page %"Y"u txnid %"Y"u\n",
1717 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1720 fprintf(stderr, "Bad page %"Y"u flags 0x%u\n", pgno, mp->mp_flags);
1724 nkeys = NUMKEYS(mp);
1725 fprintf(stderr, "%s %"Y"u numkeys %d%s\n", type, pgno, nkeys, state);
1727 for (i=0; i<nkeys; i++) {
1728 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1729 key.mv_size = nsize = mp->mp_pad;
1730 key.mv_data = LEAF2KEY(mp, i, nsize);
1732 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1735 node = NODEPTR(mp, i);
1736 key.mv_size = node->mn_ksize;
1737 key.mv_data = node->mn_data;
1738 nsize = NODESIZE + key.mv_size;
1739 if (IS_BRANCH(mp)) {
1740 fprintf(stderr, "key %d: page %"Y"u, %s\n", i, NODEPGNO(node),
1744 if (F_ISSET(node->mn_flags, F_BIGDATA))
1745 nsize += sizeof(pgno_t);
1747 nsize += NODEDSZ(node);
1749 nsize += sizeof(indx_t);
1750 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1751 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1753 total = EVEN(total);
1755 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1756 IS_LEAF2(mp) ? PAGEHDRSZ : PAGEBASE + mp->mp_lower, total, SIZELEFT(mp));
1760 mdb_cursor_chk(MDB_cursor *mc)
1766 if (!mc->mc_snum || !(mc->mc_flags & C_INITIALIZED)) return;
1767 for (i=0; i<mc->mc_top; i++) {
1769 node = NODEPTR(mp, mc->mc_ki[i]);
1770 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1773 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1775 if (mc->mc_xcursor && (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
1776 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
1777 if (((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) &&
1778 mc->mc_xcursor->mx_cursor.mc_pg[0] != NODEDATA(node)) {
1786 /** Count all the pages in each DB and in the freelist
1787 * and make sure it matches the actual number of pages
1789 * All named DBs must be open for a correct count.
1791 static void mdb_audit(MDB_txn *txn)
1795 MDB_ID freecount, count;
1800 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1801 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1802 freecount += *(MDB_ID *)data.mv_data;
1803 mdb_tassert(txn, rc == MDB_NOTFOUND);
1806 for (i = 0; i<txn->mt_numdbs; i++) {
1808 if (!(txn->mt_dbflags[i] & DB_VALID))
1810 mdb_cursor_init(&mc, txn, i, &mx);
1811 if (txn->mt_dbs[i].md_root == P_INVALID)
1813 count += txn->mt_dbs[i].md_branch_pages +
1814 txn->mt_dbs[i].md_leaf_pages +
1815 txn->mt_dbs[i].md_overflow_pages;
1816 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1817 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1818 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
1821 mp = mc.mc_pg[mc.mc_top];
1822 for (j=0; j<NUMKEYS(mp); j++) {
1823 MDB_node *leaf = NODEPTR(mp, j);
1824 if (leaf->mn_flags & F_SUBDATA) {
1826 memcpy(&db, NODEDATA(leaf), sizeof(db));
1827 count += db.md_branch_pages + db.md_leaf_pages +
1828 db.md_overflow_pages;
1832 mdb_tassert(txn, rc == MDB_NOTFOUND);
1835 if (freecount + count + NUM_METAS != txn->mt_next_pgno) {
1836 fprintf(stderr, "audit: %"Y"u freecount: %"Y"u count: %"Y"u total: %"Y"u next_pgno: %"Y"u\n",
1837 txn->mt_txnid, freecount, count+NUM_METAS,
1838 freecount+count+NUM_METAS, txn->mt_next_pgno);
1844 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1846 return txn->mt_dbxs[dbi].md_cmp(a, b);
1850 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1852 MDB_cmp_func *dcmp = txn->mt_dbxs[dbi].md_dcmp;
1853 #if UINT_MAX < SIZE_MAX || defined(MDB_VL32)
1854 if (dcmp == mdb_cmp_int && a->mv_size == sizeof(mdb_size_t))
1855 dcmp = mdb_cmp_clong;
1860 /** Allocate memory for a page.
1861 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1864 mdb_page_malloc(MDB_txn *txn, unsigned num)
1866 MDB_env *env = txn->mt_env;
1867 MDB_page *ret = env->me_dpages;
1868 size_t psize = env->me_psize, sz = psize, off;
1869 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1870 * For a single page alloc, we init everything after the page header.
1871 * For multi-page, we init the final page; if the caller needed that
1872 * many pages they will be filling in at least up to the last page.
1876 VGMEMP_ALLOC(env, ret, sz);
1877 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1878 env->me_dpages = ret->mp_next;
1881 psize -= off = PAGEHDRSZ;
1886 if ((ret = malloc(sz)) != NULL) {
1887 VGMEMP_ALLOC(env, ret, sz);
1888 if (!(env->me_flags & MDB_NOMEMINIT)) {
1889 memset((char *)ret + off, 0, psize);
1893 txn->mt_flags |= MDB_TXN_ERROR;
1897 /** Free a single page.
1898 * Saves single pages to a list, for future reuse.
1899 * (This is not used for multi-page overflow pages.)
1902 mdb_page_free(MDB_env *env, MDB_page *mp)
1904 mp->mp_next = env->me_dpages;
1905 VGMEMP_FREE(env, mp);
1906 env->me_dpages = mp;
1909 /** Free a dirty page */
1911 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1913 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1914 mdb_page_free(env, dp);
1916 /* large pages just get freed directly */
1917 VGMEMP_FREE(env, dp);
1922 /** Return all dirty pages to dpage list */
1924 mdb_dlist_free(MDB_txn *txn)
1926 MDB_env *env = txn->mt_env;
1927 MDB_ID2L dl = txn->mt_u.dirty_list;
1928 unsigned i, n = dl[0].mid;
1930 for (i = 1; i <= n; i++) {
1931 mdb_dpage_free(env, dl[i].mptr);
1938 mdb_page_unref(MDB_txn *txn, MDB_page *mp)
1941 MDB_ID3L tl = txn->mt_rpages;
1943 if (mp->mp_flags & (P_SUBP|P_DIRTY))
1945 rem = mp->mp_pgno & (MDB_RPAGE_CHUNK-1);
1946 pgno = mp->mp_pgno ^ rem;
1947 x = mdb_mid3l_search(tl, pgno);
1948 if (x != tl[0].mid && tl[x+1].mid == mp->mp_pgno)
1953 #define MDB_PAGE_UNREF(txn, mp) mdb_page_unref(txn, mp)
1956 mdb_cursor_unref(MDB_cursor *mc)
1959 if (!mc->mc_snum || !mc->mc_pg[0] || IS_SUBP(mc->mc_pg[0]))
1961 for (i=0; i<mc->mc_snum; i++)
1962 mdb_page_unref(mc->mc_txn, mc->mc_pg[i]);
1964 mdb_page_unref(mc->mc_txn, mc->mc_ovpg);
1967 mc->mc_snum = mc->mc_top = 0;
1968 mc->mc_pg[0] = NULL;
1969 mc->mc_flags &= ~C_INITIALIZED;
1972 #define MDB_PAGE_UNREF(txn, mp)
1973 #endif /* MDB_VL32 */
1975 /** Loosen or free a single page.
1976 * Saves single pages to a list for future reuse
1977 * in this same txn. It has been pulled from the freeDB
1978 * and already resides on the dirty list, but has been
1979 * deleted. Use these pages first before pulling again
1982 * If the page wasn't dirtied in this txn, just add it
1983 * to this txn's free list.
1986 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
1989 pgno_t pgno = mp->mp_pgno;
1990 MDB_txn *txn = mc->mc_txn;
1992 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
1993 if (txn->mt_parent) {
1994 MDB_ID2 *dl = txn->mt_u.dirty_list;
1995 /* If txn has a parent, make sure the page is in our
1999 unsigned x = mdb_mid2l_search(dl, pgno);
2000 if (x <= dl[0].mid && dl[x].mid == pgno) {
2001 if (mp != dl[x].mptr) { /* bad cursor? */
2002 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2003 txn->mt_flags |= MDB_TXN_ERROR;
2004 return MDB_CORRUPTED;
2011 /* no parent txn, so it's just ours */
2016 DPRINTF(("loosen db %d page %"Y"u", DDBI(mc),
2018 NEXT_LOOSE_PAGE(mp) = txn->mt_loose_pgs;
2019 txn->mt_loose_pgs = mp;
2020 txn->mt_loose_count++;
2021 mp->mp_flags |= P_LOOSE;
2023 int rc = mdb_midl_append(&txn->mt_free_pgs, pgno);
2031 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
2032 * @param[in] mc A cursor handle for the current operation.
2033 * @param[in] pflags Flags of the pages to update:
2034 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
2035 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
2036 * @return 0 on success, non-zero on failure.
2039 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
2041 enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
2042 MDB_txn *txn = mc->mc_txn;
2043 MDB_cursor *m3, *m0 = mc;
2048 int rc = MDB_SUCCESS, level;
2050 /* Mark pages seen by cursors */
2051 if (mc->mc_flags & C_UNTRACK)
2052 mc = NULL; /* will find mc in mt_cursors */
2053 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
2054 for (; mc; mc=mc->mc_next) {
2055 if (!(mc->mc_flags & C_INITIALIZED))
2057 for (m3 = mc;; m3 = &mx->mx_cursor) {
2059 for (j=0; j<m3->mc_snum; j++) {
2061 if ((mp->mp_flags & Mask) == pflags)
2062 mp->mp_flags ^= P_KEEP;
2064 mx = m3->mc_xcursor;
2065 /* Proceed to mx if it is at a sub-database */
2066 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
2068 if (! (mp && (mp->mp_flags & P_LEAF)))
2070 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
2071 if (!(leaf->mn_flags & F_SUBDATA))
2080 /* Mark dirty root pages */
2081 for (i=0; i<txn->mt_numdbs; i++) {
2082 if (txn->mt_dbflags[i] & DB_DIRTY) {
2083 pgno_t pgno = txn->mt_dbs[i].md_root;
2084 if (pgno == P_INVALID)
2086 if ((rc = mdb_page_get(m0, pgno, &dp, &level)) != MDB_SUCCESS)
2088 if ((dp->mp_flags & Mask) == pflags && level <= 1)
2089 dp->mp_flags ^= P_KEEP;
2097 static int mdb_page_flush(MDB_txn *txn, int keep);
2099 /** Spill pages from the dirty list back to disk.
2100 * This is intended to prevent running into #MDB_TXN_FULL situations,
2101 * but note that they may still occur in a few cases:
2102 * 1) our estimate of the txn size could be too small. Currently this
2103 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
2104 * 2) child txns may run out of space if their parents dirtied a
2105 * lot of pages and never spilled them. TODO: we probably should do
2106 * a preemptive spill during #mdb_txn_begin() of a child txn, if
2107 * the parent's dirty_room is below a given threshold.
2109 * Otherwise, if not using nested txns, it is expected that apps will
2110 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
2111 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
2112 * If the txn never references them again, they can be left alone.
2113 * If the txn only reads them, they can be used without any fuss.
2114 * If the txn writes them again, they can be dirtied immediately without
2115 * going thru all of the work of #mdb_page_touch(). Such references are
2116 * handled by #mdb_page_unspill().
2118 * Also note, we never spill DB root pages, nor pages of active cursors,
2119 * because we'll need these back again soon anyway. And in nested txns,
2120 * we can't spill a page in a child txn if it was already spilled in a
2121 * parent txn. That would alter the parent txns' data even though
2122 * the child hasn't committed yet, and we'd have no way to undo it if
2123 * the child aborted.
2125 * @param[in] m0 cursor A cursor handle identifying the transaction and
2126 * database for which we are checking space.
2127 * @param[in] key For a put operation, the key being stored.
2128 * @param[in] data For a put operation, the data being stored.
2129 * @return 0 on success, non-zero on failure.
2132 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
2134 MDB_txn *txn = m0->mc_txn;
2136 MDB_ID2L dl = txn->mt_u.dirty_list;
2137 unsigned int i, j, need;
2140 if (m0->mc_flags & C_SUB)
2143 /* Estimate how much space this op will take */
2144 i = m0->mc_db->md_depth;
2145 /* Named DBs also dirty the main DB */
2146 if (m0->mc_dbi >= CORE_DBS)
2147 i += txn->mt_dbs[MAIN_DBI].md_depth;
2148 /* For puts, roughly factor in the key+data size */
2150 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
2151 i += i; /* double it for good measure */
2154 if (txn->mt_dirty_room > i)
2157 if (!txn->mt_spill_pgs) {
2158 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
2159 if (!txn->mt_spill_pgs)
2162 /* purge deleted slots */
2163 MDB_IDL sl = txn->mt_spill_pgs;
2164 unsigned int num = sl[0];
2166 for (i=1; i<=num; i++) {
2173 /* Preserve pages which may soon be dirtied again */
2174 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
2177 /* Less aggressive spill - we originally spilled the entire dirty list,
2178 * with a few exceptions for cursor pages and DB root pages. But this
2179 * turns out to be a lot of wasted effort because in a large txn many
2180 * of those pages will need to be used again. So now we spill only 1/8th
2181 * of the dirty pages. Testing revealed this to be a good tradeoff,
2182 * better than 1/2, 1/4, or 1/10.
2184 if (need < MDB_IDL_UM_MAX / 8)
2185 need = MDB_IDL_UM_MAX / 8;
2187 /* Save the page IDs of all the pages we're flushing */
2188 /* flush from the tail forward, this saves a lot of shifting later on. */
2189 for (i=dl[0].mid; i && need; i--) {
2190 MDB_ID pn = dl[i].mid << 1;
2192 if (dp->mp_flags & (P_LOOSE|P_KEEP))
2194 /* Can't spill twice, make sure it's not already in a parent's
2197 if (txn->mt_parent) {
2199 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
2200 if (tx2->mt_spill_pgs) {
2201 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
2202 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
2203 dp->mp_flags |= P_KEEP;
2211 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
2215 mdb_midl_sort(txn->mt_spill_pgs);
2217 /* Flush the spilled part of dirty list */
2218 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
2221 /* Reset any dirty pages we kept that page_flush didn't see */
2222 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
2225 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
2229 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
2231 mdb_find_oldest(MDB_txn *txn)
2234 txnid_t mr, oldest = txn->mt_txnid - 1;
2235 if (txn->mt_env->me_txns) {
2236 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
2237 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
2248 /** Add a page to the txn's dirty list */
2250 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
2253 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
2255 if (txn->mt_flags & MDB_TXN_WRITEMAP) {
2256 insert = mdb_mid2l_append;
2258 insert = mdb_mid2l_insert;
2260 mid.mid = mp->mp_pgno;
2262 rc = insert(txn->mt_u.dirty_list, &mid);
2263 mdb_tassert(txn, rc == 0);
2264 txn->mt_dirty_room--;
2267 /** Allocate page numbers and memory for writing. Maintain me_pglast,
2268 * me_pghead and mt_next_pgno.
2270 * If there are free pages available from older transactions, they
2271 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
2272 * Do not modify the freedB, just merge freeDB records into me_pghead[]
2273 * and move me_pglast to say which records were consumed. Only this
2274 * function can create me_pghead and move me_pglast/mt_next_pgno.
2275 * When #MDB_DEVEL & 2, it is not affected by #mdb_freelist_save(): it
2276 * then uses the transaction's original snapshot of the freeDB.
2277 * @param[in] mc cursor A cursor handle identifying the transaction and
2278 * database for which we are allocating.
2279 * @param[in] num the number of pages to allocate.
2280 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
2281 * will always be satisfied by a single contiguous chunk of memory.
2282 * @return 0 on success, non-zero on failure.
2285 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
2287 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
2288 /* Get at most <Max_retries> more freeDB records once me_pghead
2289 * has enough pages. If not enough, use new pages from the map.
2290 * If <Paranoid> and mc is updating the freeDB, only get new
2291 * records if me_pghead is empty. Then the freelist cannot play
2292 * catch-up with itself by growing while trying to save it.
2294 enum { Paranoid = 1, Max_retries = 500 };
2296 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
2298 int rc, retry = num * 60;
2299 MDB_txn *txn = mc->mc_txn;
2300 MDB_env *env = txn->mt_env;
2301 pgno_t pgno, *mop = env->me_pghead;
2302 unsigned i, j, mop_len = mop ? mop[0] : 0, n2 = num-1;
2304 txnid_t oldest = 0, last;
2309 /* If there are any loose pages, just use them */
2310 if (num == 1 && txn->mt_loose_pgs) {
2311 np = txn->mt_loose_pgs;
2312 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
2313 txn->mt_loose_count--;
2314 DPRINTF(("db %d use loose page %"Y"u", DDBI(mc),
2322 /* If our dirty list is already full, we can't do anything */
2323 if (txn->mt_dirty_room == 0) {
2328 for (op = MDB_FIRST;; op = MDB_NEXT) {
2333 /* Seek a big enough contiguous page range. Prefer
2334 * pages at the tail, just truncating the list.
2340 if (mop[i-n2] == pgno+n2)
2347 if (op == MDB_FIRST) { /* 1st iteration */
2348 /* Prepare to fetch more and coalesce */
2349 last = env->me_pglast;
2350 oldest = env->me_pgoldest;
2351 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
2352 #if (MDB_DEVEL) & 2 /* "& 2" so MDB_DEVEL=1 won't hide bugs breaking freeDB */
2353 /* Use original snapshot. TODO: Should need less care in code
2354 * which modifies the database. Maybe we can delete some code?
2356 m2.mc_flags |= C_ORIG_RDONLY;
2357 m2.mc_db = &env->me_metas[(txn->mt_txnid-1) & 1]->mm_dbs[FREE_DBI];
2358 m2.mc_dbflag = (unsigned char *)""; /* probably unnecessary */
2362 key.mv_data = &last; /* will look up last+1 */
2363 key.mv_size = sizeof(last);
2365 if (Paranoid && mc->mc_dbi == FREE_DBI)
2368 if (Paranoid && retry < 0 && mop_len)
2372 /* Do not fetch more if the record will be too recent */
2373 if (oldest <= last) {
2375 oldest = mdb_find_oldest(txn);
2376 env->me_pgoldest = oldest;
2382 rc = mdb_cursor_get(&m2, &key, NULL, op);
2384 if (rc == MDB_NOTFOUND)
2388 last = *(txnid_t*)key.mv_data;
2389 if (oldest <= last) {
2391 oldest = mdb_find_oldest(txn);
2392 env->me_pgoldest = oldest;
2398 np = m2.mc_pg[m2.mc_top];
2399 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
2400 if ((rc = mdb_node_read(&m2, leaf, &data)) != MDB_SUCCESS)
2403 idl = (MDB_ID *) data.mv_data;
2406 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
2411 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
2413 mop = env->me_pghead;
2415 env->me_pglast = last;
2417 DPRINTF(("IDL read txn %"Y"u root %"Y"u num %u",
2418 last, txn->mt_dbs[FREE_DBI].md_root, i));
2420 DPRINTF(("IDL %"Y"u", idl[j]));
2422 /* Merge in descending sorted order */
2423 mdb_midl_xmerge(mop, idl);
2427 /* Use new pages from the map when nothing suitable in the freeDB */
2429 pgno = txn->mt_next_pgno;
2430 if (pgno + num >= env->me_maxpg) {
2431 DPUTS("DB size maxed out");
2435 #if defined(_WIN32) && !defined(MDB_VL32)
2436 if (!(env->me_flags & MDB_RDONLY)) {
2438 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
2439 p = VirtualAlloc(p, env->me_psize * num, MEM_COMMIT,
2440 (env->me_flags & MDB_WRITEMAP) ? PAGE_READWRITE:
2443 DPUTS("VirtualAlloc failed");
2451 if (env->me_flags & MDB_WRITEMAP) {
2452 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
2454 if (!(np = mdb_page_malloc(txn, num))) {
2460 mop[0] = mop_len -= num;
2461 /* Move any stragglers down */
2462 for (j = i-num; j < mop_len; )
2463 mop[++j] = mop[++i];
2465 txn->mt_next_pgno = pgno + num;
2468 mdb_page_dirty(txn, np);
2474 txn->mt_flags |= MDB_TXN_ERROR;
2478 /** Copy the used portions of a non-overflow page.
2479 * @param[in] dst page to copy into
2480 * @param[in] src page to copy from
2481 * @param[in] psize size of a page
2484 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2486 enum { Align = sizeof(pgno_t) };
2487 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2489 /* If page isn't full, just copy the used portion. Adjust
2490 * alignment so memcpy may copy words instead of bytes.
2492 if ((unused &= -Align) && !IS_LEAF2(src)) {
2493 upper = (upper + PAGEBASE) & -Align;
2494 memcpy(dst, src, (lower + PAGEBASE + (Align-1)) & -Align);
2495 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2498 memcpy(dst, src, psize - unused);
2502 /** Pull a page off the txn's spill list, if present.
2503 * If a page being referenced was spilled to disk in this txn, bring
2504 * it back and make it dirty/writable again.
2505 * @param[in] txn the transaction handle.
2506 * @param[in] mp the page being referenced. It must not be dirty.
2507 * @param[out] ret the writable page, if any. ret is unchanged if
2508 * mp wasn't spilled.
2511 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2513 MDB_env *env = txn->mt_env;
2516 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2518 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2519 if (!tx2->mt_spill_pgs)
2521 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2522 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2525 if (txn->mt_dirty_room == 0)
2526 return MDB_TXN_FULL;
2527 if (IS_OVERFLOW(mp))
2531 if (env->me_flags & MDB_WRITEMAP) {
2534 np = mdb_page_malloc(txn, num);
2538 memcpy(np, mp, num * env->me_psize);
2540 mdb_page_copy(np, mp, env->me_psize);
2543 /* If in current txn, this page is no longer spilled.
2544 * If it happens to be the last page, truncate the spill list.
2545 * Otherwise mark it as deleted by setting the LSB.
2547 if (x == txn->mt_spill_pgs[0])
2548 txn->mt_spill_pgs[0]--;
2550 txn->mt_spill_pgs[x] |= 1;
2551 } /* otherwise, if belonging to a parent txn, the
2552 * page remains spilled until child commits
2555 mdb_page_dirty(txn, np);
2556 np->mp_flags |= P_DIRTY;
2564 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2565 * @param[in] mc cursor pointing to the page to be touched
2566 * @return 0 on success, non-zero on failure.
2569 mdb_page_touch(MDB_cursor *mc)
2571 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2572 MDB_txn *txn = mc->mc_txn;
2573 MDB_cursor *m2, *m3;
2577 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2578 if (txn->mt_flags & MDB_TXN_SPILLS) {
2580 rc = mdb_page_unspill(txn, mp, &np);
2586 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2587 (rc = mdb_page_alloc(mc, 1, &np)))
2590 DPRINTF(("touched db %d page %"Y"u -> %"Y"u", DDBI(mc),
2591 mp->mp_pgno, pgno));
2592 mdb_cassert(mc, mp->mp_pgno != pgno);
2593 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2594 /* Update the parent page, if any, to point to the new page */
2596 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2597 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2598 SETPGNO(node, pgno);
2600 mc->mc_db->md_root = pgno;
2602 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2603 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2605 /* If txn has a parent, make sure the page is in our
2609 unsigned x = mdb_mid2l_search(dl, pgno);
2610 if (x <= dl[0].mid && dl[x].mid == pgno) {
2611 if (mp != dl[x].mptr) { /* bad cursor? */
2612 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2613 txn->mt_flags |= MDB_TXN_ERROR;
2614 return MDB_CORRUPTED;
2619 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2621 np = mdb_page_malloc(txn, 1);
2626 rc = mdb_mid2l_insert(dl, &mid);
2627 mdb_cassert(mc, rc == 0);
2632 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2634 np->mp_flags |= P_DIRTY;
2637 /* Adjust cursors pointing to mp */
2638 mc->mc_pg[mc->mc_top] = np;
2639 m2 = txn->mt_cursors[mc->mc_dbi];
2640 if (mc->mc_flags & C_SUB) {
2641 for (; m2; m2=m2->mc_next) {
2642 m3 = &m2->mc_xcursor->mx_cursor;
2643 if (m3->mc_snum < mc->mc_snum) continue;
2644 if (m3->mc_pg[mc->mc_top] == mp)
2645 m3->mc_pg[mc->mc_top] = np;
2648 for (; m2; m2=m2->mc_next) {
2649 if (m2->mc_snum < mc->mc_snum) continue;
2650 if (m2 == mc) continue;
2651 if (m2->mc_pg[mc->mc_top] == mp) {
2652 m2->mc_pg[mc->mc_top] = np;
2653 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
2655 (m2->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
2657 MDB_node *leaf = NODEPTR(np, m2->mc_ki[mc->mc_top]);
2658 if ((leaf->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
2659 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
2664 MDB_PAGE_UNREF(mc->mc_txn, mp);
2668 txn->mt_flags |= MDB_TXN_ERROR;
2673 mdb_env_sync0(MDB_env *env, int force, pgno_t numpgs)
2676 if (env->me_flags & MDB_RDONLY)
2678 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2679 if (env->me_flags & MDB_WRITEMAP) {
2680 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2681 ? MS_ASYNC : MS_SYNC;
2682 if (MDB_MSYNC(env->me_map, env->me_psize * numpgs, flags))
2685 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2689 #ifdef BROKEN_FDATASYNC
2690 if (env->me_flags & MDB_FSYNCONLY) {
2691 if (fsync(env->me_fd))
2695 if (MDB_FDATASYNC(env->me_fd))
2703 mdb_env_sync(MDB_env *env, int force)
2705 MDB_meta *m = mdb_env_pick_meta(env);
2706 return mdb_env_sync0(env, force, m->mm_last_pg+1);
2709 /** Back up parent txn's cursors, then grab the originals for tracking */
2711 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2713 MDB_cursor *mc, *bk;
2718 for (i = src->mt_numdbs; --i >= 0; ) {
2719 if ((mc = src->mt_cursors[i]) != NULL) {
2720 size = sizeof(MDB_cursor);
2722 size += sizeof(MDB_xcursor);
2723 for (; mc; mc = bk->mc_next) {
2729 mc->mc_db = &dst->mt_dbs[i];
2730 /* Kill pointers into src to reduce abuse: The
2731 * user may not use mc until dst ends. But we need a valid
2732 * txn pointer here for cursor fixups to keep working.
2735 mc->mc_dbflag = &dst->mt_dbflags[i];
2736 if ((mx = mc->mc_xcursor) != NULL) {
2737 *(MDB_xcursor *)(bk+1) = *mx;
2738 mx->mx_cursor.mc_txn = dst;
2740 mc->mc_next = dst->mt_cursors[i];
2741 dst->mt_cursors[i] = mc;
2748 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2749 * @param[in] txn the transaction handle.
2750 * @param[in] merge true to keep changes to parent cursors, false to revert.
2751 * @return 0 on success, non-zero on failure.
2754 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2756 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2760 for (i = txn->mt_numdbs; --i >= 0; ) {
2761 for (mc = cursors[i]; mc; mc = next) {
2763 if ((bk = mc->mc_backup) != NULL) {
2765 /* Commit changes to parent txn */
2766 mc->mc_next = bk->mc_next;
2767 mc->mc_backup = bk->mc_backup;
2768 mc->mc_txn = bk->mc_txn;
2769 mc->mc_db = bk->mc_db;
2770 mc->mc_dbflag = bk->mc_dbflag;
2771 if ((mx = mc->mc_xcursor) != NULL)
2772 mx->mx_cursor.mc_txn = bk->mc_txn;
2774 /* Abort nested txn */
2776 if ((mx = mc->mc_xcursor) != NULL)
2777 *mx = *(MDB_xcursor *)(bk+1);
2781 /* Only malloced cursors are permanently tracked. */
2788 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2794 Pidset = F_SETLK, Pidcheck = F_GETLK
2798 /** Set or check a pid lock. Set returns 0 on success.
2799 * Check returns 0 if the process is certainly dead, nonzero if it may
2800 * be alive (the lock exists or an error happened so we do not know).
2802 * On Windows Pidset is a no-op, we merely check for the existence
2803 * of the process with the given pid. On POSIX we use a single byte
2804 * lock on the lockfile, set at an offset equal to the pid.
2807 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2809 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2812 if (op == Pidcheck) {
2813 h = OpenProcess(env->me_pidquery, FALSE, pid);
2814 /* No documented "no such process" code, but other program use this: */
2816 return ErrCode() != ERROR_INVALID_PARAMETER;
2817 /* A process exists until all handles to it close. Has it exited? */
2818 ret = WaitForSingleObject(h, 0) != 0;
2825 struct flock lock_info;
2826 memset(&lock_info, 0, sizeof(lock_info));
2827 lock_info.l_type = F_WRLCK;
2828 lock_info.l_whence = SEEK_SET;
2829 lock_info.l_start = pid;
2830 lock_info.l_len = 1;
2831 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2832 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2834 } else if ((rc = ErrCode()) == EINTR) {
2842 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2843 * @param[in] txn the transaction handle to initialize
2844 * @return 0 on success, non-zero on failure.
2847 mdb_txn_renew0(MDB_txn *txn)
2849 MDB_env *env = txn->mt_env;
2850 MDB_txninfo *ti = env->me_txns;
2852 unsigned int i, nr, flags = txn->mt_flags;
2854 int rc, new_notls = 0;
2856 if ((flags &= MDB_TXN_RDONLY) != 0) {
2858 meta = mdb_env_pick_meta(env);
2859 txn->mt_txnid = meta->mm_txnid;
2860 txn->mt_u.reader = NULL;
2862 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2863 pthread_getspecific(env->me_txkey);
2865 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2866 return MDB_BAD_RSLOT;
2868 MDB_PID_T pid = env->me_pid;
2869 MDB_THR_T tid = pthread_self();
2870 mdb_mutexref_t rmutex = env->me_rmutex;
2872 if (!env->me_live_reader) {
2873 rc = mdb_reader_pid(env, Pidset, pid);
2876 env->me_live_reader = 1;
2879 if (LOCK_MUTEX(rc, env, rmutex))
2881 nr = ti->mti_numreaders;
2882 for (i=0; i<nr; i++)
2883 if (ti->mti_readers[i].mr_pid == 0)
2885 if (i == env->me_maxreaders) {
2886 UNLOCK_MUTEX(rmutex);
2887 return MDB_READERS_FULL;
2889 r = &ti->mti_readers[i];
2890 /* Claim the reader slot, carefully since other code
2891 * uses the reader table un-mutexed: First reset the
2892 * slot, next publish it in mti_numreaders. After
2893 * that, it is safe for mdb_env_close() to touch it.
2894 * When it will be closed, we can finally claim it.
2897 r->mr_txnid = (txnid_t)-1;
2900 ti->mti_numreaders = ++nr;
2901 env->me_close_readers = nr;
2903 UNLOCK_MUTEX(rmutex);
2905 new_notls = (env->me_flags & MDB_NOTLS);
2906 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2911 do /* LY: Retry on a race, ITS#7970. */
2912 r->mr_txnid = ti->mti_txnid;
2913 while(r->mr_txnid != ti->mti_txnid);
2914 txn->mt_txnid = r->mr_txnid;
2915 txn->mt_u.reader = r;
2916 meta = env->me_metas[txn->mt_txnid & 1];
2920 /* Not yet touching txn == env->me_txn0, it may be active */
2922 if (LOCK_MUTEX(rc, env, env->me_wmutex))
2924 txn->mt_txnid = ti->mti_txnid;
2925 meta = env->me_metas[txn->mt_txnid & 1];
2927 meta = mdb_env_pick_meta(env);
2928 txn->mt_txnid = meta->mm_txnid;
2932 if (txn->mt_txnid == mdb_debug_start)
2935 txn->mt_child = NULL;
2936 txn->mt_loose_pgs = NULL;
2937 txn->mt_loose_count = 0;
2938 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2939 txn->mt_u.dirty_list = env->me_dirty_list;
2940 txn->mt_u.dirty_list[0].mid = 0;
2941 txn->mt_free_pgs = env->me_free_pgs;
2942 txn->mt_free_pgs[0] = 0;
2943 txn->mt_spill_pgs = NULL;
2945 memcpy(txn->mt_dbiseqs, env->me_dbiseqs, env->me_maxdbs * sizeof(unsigned int));
2948 /* Copy the DB info and flags */
2949 memcpy(txn->mt_dbs, meta->mm_dbs, CORE_DBS * sizeof(MDB_db));
2951 /* Moved to here to avoid a data race in read TXNs */
2952 txn->mt_next_pgno = meta->mm_last_pg+1;
2954 txn->mt_last_pgno = txn->mt_next_pgno - 1;
2957 txn->mt_flags = flags;
2960 txn->mt_numdbs = env->me_numdbs;
2961 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
2962 x = env->me_dbflags[i];
2963 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2964 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_USRVALID|DB_STALE : 0;
2966 txn->mt_dbflags[MAIN_DBI] = DB_VALID|DB_USRVALID;
2967 txn->mt_dbflags[FREE_DBI] = DB_VALID;
2969 if (env->me_flags & MDB_FATAL_ERROR) {
2970 DPUTS("environment had fatal error, must shutdown!");
2972 } else if (env->me_maxpg < txn->mt_next_pgno) {
2973 rc = MDB_MAP_RESIZED;
2977 mdb_txn_end(txn, new_notls /*0 or MDB_END_SLOT*/ | MDB_END_FAIL_BEGIN);
2982 mdb_txn_renew(MDB_txn *txn)
2986 if (!txn || !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY|MDB_TXN_FINISHED))
2989 rc = mdb_txn_renew0(txn);
2990 if (rc == MDB_SUCCESS) {
2991 DPRINTF(("renew txn %"Y"u%c %p on mdbenv %p, root page %"Y"u",
2992 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2993 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2999 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
3003 int rc, size, tsize;
3005 flags &= MDB_TXN_BEGIN_FLAGS;
3006 flags |= env->me_flags & MDB_WRITEMAP;
3008 if (env->me_flags & MDB_RDONLY & ~flags) /* write txn in RDONLY env */
3012 /* Nested transactions: Max 1 child, write txns only, no writemap */
3013 flags |= parent->mt_flags;
3014 if (flags & (MDB_RDONLY|MDB_WRITEMAP|MDB_TXN_BLOCKED)) {
3015 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
3017 /* Child txns save MDB_pgstate and use own copy of cursors */
3018 size = env->me_maxdbs * (sizeof(MDB_db)+sizeof(MDB_cursor *)+1);
3019 size += tsize = sizeof(MDB_ntxn);
3020 } else if (flags & MDB_RDONLY) {
3021 size = env->me_maxdbs * (sizeof(MDB_db)+1);
3022 size += tsize = sizeof(MDB_txn);
3024 /* Reuse preallocated write txn. However, do not touch it until
3025 * mdb_txn_renew0() succeeds, since it currently may be active.
3030 if ((txn = calloc(1, size)) == NULL) {
3031 DPRINTF(("calloc: %s", strerror(errno)));
3036 txn->mt_rpages = malloc(MDB_TRPAGE_SIZE * sizeof(MDB_ID3));
3037 if (!txn->mt_rpages) {
3041 txn->mt_rpages[0].mid = 0;
3042 txn->mt_rpcheck = MDB_TRPAGE_SIZE/2;
3045 txn->mt_dbxs = env->me_dbxs; /* static */
3046 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
3047 txn->mt_dbflags = (unsigned char *)txn + size - env->me_maxdbs;
3048 txn->mt_flags = flags;
3053 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
3054 txn->mt_dbiseqs = parent->mt_dbiseqs;
3055 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
3056 if (!txn->mt_u.dirty_list ||
3057 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
3059 free(txn->mt_u.dirty_list);
3063 txn->mt_txnid = parent->mt_txnid;
3064 txn->mt_dirty_room = parent->mt_dirty_room;
3065 txn->mt_u.dirty_list[0].mid = 0;
3066 txn->mt_spill_pgs = NULL;
3067 txn->mt_next_pgno = parent->mt_next_pgno;
3068 parent->mt_flags |= MDB_TXN_HAS_CHILD;
3069 parent->mt_child = txn;
3070 txn->mt_parent = parent;
3071 txn->mt_numdbs = parent->mt_numdbs;
3073 txn->mt_rpages = parent->mt_rpages;
3075 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3076 /* Copy parent's mt_dbflags, but clear DB_NEW */
3077 for (i=0; i<txn->mt_numdbs; i++)
3078 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
3080 ntxn = (MDB_ntxn *)txn;
3081 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
3082 if (env->me_pghead) {
3083 size = MDB_IDL_SIZEOF(env->me_pghead);
3084 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
3086 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
3091 rc = mdb_cursor_shadow(parent, txn);
3093 mdb_txn_end(txn, MDB_END_FAIL_BEGINCHILD);
3094 } else { /* MDB_RDONLY */
3095 txn->mt_dbiseqs = env->me_dbiseqs;
3097 rc = mdb_txn_renew0(txn);
3100 if (txn != env->me_txn0) {
3102 free(txn->mt_rpages);
3107 txn->mt_flags |= flags; /* could not change txn=me_txn0 earlier */
3109 DPRINTF(("begin txn %"Y"u%c %p on mdbenv %p, root page %"Y"u",
3110 txn->mt_txnid, (flags & MDB_RDONLY) ? 'r' : 'w',
3111 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
3118 mdb_txn_env(MDB_txn *txn)
3120 if(!txn) return NULL;
3125 mdb_txn_id(MDB_txn *txn)
3128 return txn->mt_txnid;
3131 /** Export or close DBI handles opened in this txn. */
3133 mdb_dbis_update(MDB_txn *txn, int keep)
3136 MDB_dbi n = txn->mt_numdbs;
3137 MDB_env *env = txn->mt_env;
3138 unsigned char *tdbflags = txn->mt_dbflags;
3140 for (i = n; --i >= CORE_DBS;) {
3141 if (tdbflags[i] & DB_NEW) {
3143 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
3145 char *ptr = env->me_dbxs[i].md_name.mv_data;
3147 env->me_dbxs[i].md_name.mv_data = NULL;
3148 env->me_dbxs[i].md_name.mv_size = 0;
3149 env->me_dbflags[i] = 0;
3150 env->me_dbiseqs[i]++;
3156 if (keep && env->me_numdbs < n)
3160 /** End a transaction, except successful commit of a nested transaction.
3161 * May be called twice for readonly txns: First reset it, then abort.
3162 * @param[in] txn the transaction handle to end
3163 * @param[in] mode why and how to end the transaction
3166 mdb_txn_end(MDB_txn *txn, unsigned mode)
3168 MDB_env *env = txn->mt_env;
3170 static const char *const names[] = MDB_END_NAMES;
3173 /* Export or close DBI handles opened in this txn */
3174 mdb_dbis_update(txn, mode & MDB_END_UPDATE);
3176 DPRINTF(("%s txn %"Y"u%c %p on mdbenv %p, root page %"Y"u",
3177 names[mode & MDB_END_OPMASK],
3178 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
3179 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
3181 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3182 if (txn->mt_u.reader) {
3183 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
3184 if (!(env->me_flags & MDB_NOTLS)) {
3185 txn->mt_u.reader = NULL; /* txn does not own reader */
3186 } else if (mode & MDB_END_SLOT) {
3187 txn->mt_u.reader->mr_pid = 0;
3188 txn->mt_u.reader = NULL;
3189 } /* else txn owns the slot until it does MDB_END_SLOT */
3191 txn->mt_numdbs = 0; /* prevent further DBI activity */
3192 txn->mt_flags |= MDB_TXN_FINISHED;
3194 } else if (!F_ISSET(txn->mt_flags, MDB_TXN_FINISHED)) {
3195 pgno_t *pghead = env->me_pghead;
3197 if (!(mode & MDB_END_UPDATE)) /* !(already closed cursors) */
3198 mdb_cursors_close(txn, 0);
3199 if (!(env->me_flags & MDB_WRITEMAP)) {
3200 mdb_dlist_free(txn);
3204 txn->mt_flags = MDB_TXN_FINISHED;
3206 if (!txn->mt_parent) {
3207 mdb_midl_shrink(&txn->mt_free_pgs);
3208 env->me_free_pgs = txn->mt_free_pgs;
3210 env->me_pghead = NULL;
3214 mode = 0; /* txn == env->me_txn0, do not free() it */
3216 /* The writer mutex was locked in mdb_txn_begin. */
3218 UNLOCK_MUTEX(env->me_wmutex);
3220 txn->mt_parent->mt_child = NULL;
3221 txn->mt_parent->mt_flags &= ~MDB_TXN_HAS_CHILD;
3222 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
3223 mdb_midl_free(txn->mt_free_pgs);
3224 mdb_midl_free(txn->mt_spill_pgs);
3225 free(txn->mt_u.dirty_list);
3228 mdb_midl_free(pghead);
3231 if (!txn->mt_parent) {
3232 MDB_ID3L el = env->me_rpages, tl = txn->mt_rpages;
3233 unsigned i, x, n = tl[0].mid;
3234 pthread_mutex_lock(&env->me_rpmutex);
3235 for (i = 1; i <= n; i++) {
3236 if (tl[i].mid & (MDB_RPAGE_CHUNK-1)) {
3237 /* tmp overflow pages that we didn't share in env */
3238 munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
3240 x = mdb_mid3l_search(el, tl[i].mid);
3241 if (tl[i].mptr == el[x].mptr) {
3244 /* another tmp overflow page */
3245 munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
3249 pthread_mutex_unlock(&env->me_rpmutex);
3251 if (mode & MDB_END_FREE)
3255 if (mode & MDB_END_FREE)
3260 mdb_txn_reset(MDB_txn *txn)
3265 /* This call is only valid for read-only txns */
3266 if (!(txn->mt_flags & MDB_TXN_RDONLY))
3269 mdb_txn_end(txn, MDB_END_RESET);
3273 mdb_txn_abort(MDB_txn *txn)
3279 mdb_txn_abort(txn->mt_child);
3281 mdb_txn_end(txn, MDB_END_ABORT|MDB_END_SLOT|MDB_END_FREE);
3284 /** Save the freelist as of this transaction to the freeDB.
3285 * This changes the freelist. Keep trying until it stabilizes.
3287 * When (MDB_DEVEL) & 2, the changes do not affect #mdb_page_alloc(),
3288 * it then uses the transaction's original snapshot of the freeDB.
3291 mdb_freelist_save(MDB_txn *txn)
3293 /* env->me_pghead[] can grow and shrink during this call.
3294 * env->me_pglast and txn->mt_free_pgs[] can only grow.
3295 * Page numbers cannot disappear from txn->mt_free_pgs[].
3298 MDB_env *env = txn->mt_env;
3299 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
3300 txnid_t pglast = 0, head_id = 0;
3301 pgno_t freecnt = 0, *free_pgs, *mop;
3302 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
3304 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
3306 if (env->me_pghead) {
3307 /* Make sure first page of freeDB is touched and on freelist */
3308 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
3309 if (rc && rc != MDB_NOTFOUND)
3313 if (!env->me_pghead && txn->mt_loose_pgs) {
3314 /* Put loose page numbers in mt_free_pgs, since
3315 * we may be unable to return them to me_pghead.
3317 MDB_page *mp = txn->mt_loose_pgs;
3318 if ((rc = mdb_midl_need(&txn->mt_free_pgs, txn->mt_loose_count)) != 0)
3320 for (; mp; mp = NEXT_LOOSE_PAGE(mp))
3321 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
3322 txn->mt_loose_pgs = NULL;
3323 txn->mt_loose_count = 0;
3326 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
3327 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
3328 ? SSIZE_MAX : maxfree_1pg;
3331 /* Come back here after each Put() in case freelist changed */
3336 /* If using records from freeDB which we have not yet
3337 * deleted, delete them and any we reserved for me_pghead.
3339 while (pglast < env->me_pglast) {
3340 rc = mdb_cursor_first(&mc, &key, NULL);
3343 pglast = head_id = *(txnid_t *)key.mv_data;
3344 total_room = head_room = 0;
3345 mdb_tassert(txn, pglast <= env->me_pglast);
3346 rc = mdb_cursor_del(&mc, 0);
3351 /* Save the IDL of pages freed by this txn, to a single record */
3352 if (freecnt < txn->mt_free_pgs[0]) {
3354 /* Make sure last page of freeDB is touched and on freelist */
3355 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
3356 if (rc && rc != MDB_NOTFOUND)
3359 free_pgs = txn->mt_free_pgs;
3360 /* Write to last page of freeDB */
3361 key.mv_size = sizeof(txn->mt_txnid);
3362 key.mv_data = &txn->mt_txnid;
3364 freecnt = free_pgs[0];
3365 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
3366 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3369 /* Retry if mt_free_pgs[] grew during the Put() */
3370 free_pgs = txn->mt_free_pgs;
3371 } while (freecnt < free_pgs[0]);
3372 mdb_midl_sort(free_pgs);
3373 memcpy(data.mv_data, free_pgs, data.mv_size);
3376 unsigned int i = free_pgs[0];
3377 DPRINTF(("IDL write txn %"Y"u root %"Y"u num %u",
3378 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
3380 DPRINTF(("IDL %"Y"u", free_pgs[i]));
3386 mop = env->me_pghead;
3387 mop_len = (mop ? mop[0] : 0) + txn->mt_loose_count;
3389 /* Reserve records for me_pghead[]. Split it if multi-page,
3390 * to avoid searching freeDB for a page range. Use keys in
3391 * range [1,me_pglast]: Smaller than txnid of oldest reader.
3393 if (total_room >= mop_len) {
3394 if (total_room == mop_len || --more < 0)
3396 } else if (head_room >= maxfree_1pg && head_id > 1) {
3397 /* Keep current record (overflow page), add a new one */
3401 /* (Re)write {key = head_id, IDL length = head_room} */
3402 total_room -= head_room;
3403 head_room = mop_len - total_room;
3404 if (head_room > maxfree_1pg && head_id > 1) {
3405 /* Overflow multi-page for part of me_pghead */
3406 head_room /= head_id; /* amortize page sizes */
3407 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
3408 } else if (head_room < 0) {
3409 /* Rare case, not bothering to delete this record */
3412 key.mv_size = sizeof(head_id);
3413 key.mv_data = &head_id;
3414 data.mv_size = (head_room + 1) * sizeof(pgno_t);
3415 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3418 /* IDL is initially empty, zero out at least the length */
3419 pgs = (pgno_t *)data.mv_data;
3420 j = head_room > clean_limit ? head_room : 0;
3424 total_room += head_room;
3427 /* Return loose page numbers to me_pghead, though usually none are
3428 * left at this point. The pages themselves remain in dirty_list.
3430 if (txn->mt_loose_pgs) {
3431 MDB_page *mp = txn->mt_loose_pgs;
3432 unsigned count = txn->mt_loose_count;
3434 /* Room for loose pages + temp IDL with same */
3435 if ((rc = mdb_midl_need(&env->me_pghead, 2*count+1)) != 0)
3437 mop = env->me_pghead;
3438 loose = mop + MDB_IDL_ALLOCLEN(mop) - count;
3439 for (count = 0; mp; mp = NEXT_LOOSE_PAGE(mp))
3440 loose[ ++count ] = mp->mp_pgno;
3442 mdb_midl_sort(loose);
3443 mdb_midl_xmerge(mop, loose);
3444 txn->mt_loose_pgs = NULL;
3445 txn->mt_loose_count = 0;
3449 /* Fill in the reserved me_pghead records */
3455 rc = mdb_cursor_first(&mc, &key, &data);
3456 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
3457 txnid_t id = *(txnid_t *)key.mv_data;
3458 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
3461 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
3463 if (len > mop_len) {
3465 data.mv_size = (len + 1) * sizeof(MDB_ID);
3467 data.mv_data = mop -= len;
3470 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
3472 if (rc || !(mop_len -= len))
3479 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
3480 * @param[in] txn the transaction that's being committed
3481 * @param[in] keep number of initial pages in dirty_list to keep dirty.
3482 * @return 0 on success, non-zero on failure.
3485 mdb_page_flush(MDB_txn *txn, int keep)
3487 MDB_env *env = txn->mt_env;
3488 MDB_ID2L dl = txn->mt_u.dirty_list;
3489 unsigned psize = env->me_psize, j;
3490 int i, pagecount = dl[0].mid, rc;
3494 MDB_page *dp = NULL;
3498 struct iovec iov[MDB_COMMIT_PAGES];
3499 ssize_t wsize = 0, wres;
3500 off_t wpos = 0, next_pos = 1; /* impossible pos, so pos != next_pos */
3506 if (env->me_flags & MDB_WRITEMAP) {
3507 /* Clear dirty flags */
3508 while (++i <= pagecount) {
3510 /* Don't flush this page yet */
3511 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3512 dp->mp_flags &= ~P_KEEP;
3516 dp->mp_flags &= ~P_DIRTY;
3521 /* Write the pages */
3523 if (++i <= pagecount) {
3525 /* Don't flush this page yet */
3526 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3527 dp->mp_flags &= ~P_KEEP;
3532 /* clear dirty flag */
3533 dp->mp_flags &= ~P_DIRTY;
3536 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
3541 /* Windows actually supports scatter/gather I/O, but only on
3542 * unbuffered file handles. Since we're relying on the OS page
3543 * cache for all our data, that's self-defeating. So we just
3544 * write pages one at a time. We use the ov structure to set
3545 * the write offset, to at least save the overhead of a Seek
3548 DPRINTF(("committing page %"Z"u", pgno));
3549 memset(&ov, 0, sizeof(ov));
3550 ov.Offset = pos & 0xffffffff;
3551 ov.OffsetHigh = pos >> 16 >> 16;
3552 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
3554 DPRINTF(("WriteFile: %d", rc));
3558 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
3559 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
3562 /* Write previous page(s) */
3563 #ifdef MDB_USE_PWRITEV
3564 wres = pwritev(env->me_fd, iov, n, wpos);
3567 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
3570 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
3574 DPRINTF(("lseek: %s", strerror(rc)));
3577 wres = writev(env->me_fd, iov, n);
3580 if (wres != wsize) {
3585 DPRINTF(("Write error: %s", strerror(rc)));
3587 rc = EIO; /* TODO: Use which error code? */
3588 DPUTS("short write, filesystem full?");
3599 DPRINTF(("committing page %"Y"u", pgno));
3600 next_pos = pos + size;
3601 iov[n].iov_len = size;
3602 iov[n].iov_base = (char *)dp;
3608 if (pgno > txn->mt_last_pgno)
3609 txn->mt_last_pgno = pgno;
3612 /* MIPS has cache coherency issues, this is a no-op everywhere else
3613 * Note: for any size >= on-chip cache size, entire on-chip cache is
3616 CACHEFLUSH(env->me_map, txn->mt_next_pgno * env->me_psize, DCACHE);
3618 for (i = keep; ++i <= pagecount; ) {
3620 /* This is a page we skipped above */
3623 dl[j].mid = dp->mp_pgno;
3626 mdb_dpage_free(env, dp);
3631 txn->mt_dirty_room += i - j;
3637 mdb_txn_commit(MDB_txn *txn)
3640 unsigned int i, end_mode;
3646 /* mdb_txn_end() mode for a commit which writes nothing */
3647 end_mode = MDB_END_EMPTY_COMMIT|MDB_END_UPDATE|MDB_END_SLOT|MDB_END_FREE;
3649 if (txn->mt_child) {
3650 rc = mdb_txn_commit(txn->mt_child);
3657 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3661 if (txn->mt_flags & (MDB_TXN_FINISHED|MDB_TXN_ERROR)) {
3662 DPUTS("txn has failed/finished, can't commit");
3664 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3669 if (txn->mt_parent) {
3670 MDB_txn *parent = txn->mt_parent;
3674 unsigned x, y, len, ps_len;
3676 /* Append our free list to parent's */
3677 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3680 mdb_midl_free(txn->mt_free_pgs);
3681 /* Failures after this must either undo the changes
3682 * to the parent or set MDB_TXN_ERROR in the parent.
3685 parent->mt_next_pgno = txn->mt_next_pgno;
3686 parent->mt_flags = txn->mt_flags;
3688 /* Merge our cursors into parent's and close them */
3689 mdb_cursors_close(txn, 1);
3691 /* Update parent's DB table. */
3692 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3693 parent->mt_numdbs = txn->mt_numdbs;
3694 parent->mt_dbflags[FREE_DBI] = txn->mt_dbflags[FREE_DBI];
3695 parent->mt_dbflags[MAIN_DBI] = txn->mt_dbflags[MAIN_DBI];
3696 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
3697 /* preserve parent's DB_NEW status */
3698 x = parent->mt_dbflags[i] & DB_NEW;
3699 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3702 dst = parent->mt_u.dirty_list;
3703 src = txn->mt_u.dirty_list;
3704 /* Remove anything in our dirty list from parent's spill list */
3705 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3707 pspill[0] = (pgno_t)-1;
3708 /* Mark our dirty pages as deleted in parent spill list */
3709 for (i=0, len=src[0].mid; ++i <= len; ) {
3710 MDB_ID pn = src[i].mid << 1;
3711 while (pn > pspill[x])
3713 if (pn == pspill[x]) {
3718 /* Squash deleted pagenums if we deleted any */
3719 for (x=y; ++x <= ps_len; )
3720 if (!(pspill[x] & 1))
3721 pspill[++y] = pspill[x];
3725 /* Remove anything in our spill list from parent's dirty list */
3726 if (txn->mt_spill_pgs && txn->mt_spill_pgs[0]) {
3727 for (i=1; i<=txn->mt_spill_pgs[0]; i++) {
3728 MDB_ID pn = txn->mt_spill_pgs[i];
3730 continue; /* deleted spillpg */
3732 y = mdb_mid2l_search(dst, pn);
3733 if (y <= dst[0].mid && dst[y].mid == pn) {
3735 while (y < dst[0].mid) {
3744 /* Find len = length of merging our dirty list with parent's */
3746 dst[0].mid = 0; /* simplify loops */
3747 if (parent->mt_parent) {
3748 len = x + src[0].mid;
3749 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3750 for (i = x; y && i; y--) {
3751 pgno_t yp = src[y].mid;
3752 while (yp < dst[i].mid)
3754 if (yp == dst[i].mid) {
3759 } else { /* Simplify the above for single-ancestor case */
3760 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3762 /* Merge our dirty list with parent's */
3764 for (i = len; y; dst[i--] = src[y--]) {
3765 pgno_t yp = src[y].mid;
3766 while (yp < dst[x].mid)
3767 dst[i--] = dst[x--];
3768 if (yp == dst[x].mid)
3769 free(dst[x--].mptr);
3771 mdb_tassert(txn, i == x);
3773 free(txn->mt_u.dirty_list);
3774 parent->mt_dirty_room = txn->mt_dirty_room;
3775 if (txn->mt_spill_pgs) {
3776 if (parent->mt_spill_pgs) {
3777 /* TODO: Prevent failure here, so parent does not fail */
3778 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3780 parent->mt_flags |= MDB_TXN_ERROR;
3781 mdb_midl_free(txn->mt_spill_pgs);
3782 mdb_midl_sort(parent->mt_spill_pgs);
3784 parent->mt_spill_pgs = txn->mt_spill_pgs;
3788 /* Append our loose page list to parent's */
3789 for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(*lp))
3791 *lp = txn->mt_loose_pgs;
3792 parent->mt_loose_count += txn->mt_loose_count;
3794 parent->mt_child = NULL;
3795 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3800 if (txn != env->me_txn) {
3801 DPUTS("attempt to commit unknown transaction");
3806 mdb_cursors_close(txn, 0);
3808 if (!txn->mt_u.dirty_list[0].mid &&
3809 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
3812 DPRINTF(("committing txn %"Y"u %p on mdbenv %p, root page %"Y"u",
3813 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3815 /* Update DB root pointers */
3816 if (txn->mt_numdbs > CORE_DBS) {
3820 data.mv_size = sizeof(MDB_db);
3822 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3823 for (i = CORE_DBS; i < txn->mt_numdbs; i++) {
3824 if (txn->mt_dbflags[i] & DB_DIRTY) {
3825 if (TXN_DBI_CHANGED(txn, i)) {
3829 data.mv_data = &txn->mt_dbs[i];
3830 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data,
3838 rc = mdb_freelist_save(txn);
3842 mdb_midl_free(env->me_pghead);
3843 env->me_pghead = NULL;
3844 mdb_midl_shrink(&txn->mt_free_pgs);
3850 if ((rc = mdb_page_flush(txn, 0)))
3852 if (!F_ISSET(txn->mt_flags, MDB_TXN_NOSYNC) &&
3853 (rc = mdb_env_sync0(env, 0, txn->mt_next_pgno)))
3855 if ((rc = mdb_env_write_meta(txn)))
3857 end_mode = MDB_END_COMMITTED|MDB_END_UPDATE;
3860 mdb_txn_end(txn, end_mode);
3868 /** Read the environment parameters of a DB environment before
3869 * mapping it into memory.
3870 * @param[in] env the environment handle
3871 * @param[out] meta address of where to store the meta information
3872 * @return 0 on success, non-zero on failure.
3875 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3881 enum { Size = sizeof(pbuf) };
3883 /* We don't know the page size yet, so use a minimum value.
3884 * Read both meta pages so we can use the latest one.
3887 for (i=off=0; i<NUM_METAS; i++, off += meta->mm_psize) {
3891 memset(&ov, 0, sizeof(ov));
3893 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3894 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3897 rc = pread(env->me_fd, &pbuf, Size, off);
3900 if (rc == 0 && off == 0)
3902 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3903 DPRINTF(("read: %s", mdb_strerror(rc)));
3907 p = (MDB_page *)&pbuf;
3909 if (!F_ISSET(p->mp_flags, P_META)) {
3910 DPRINTF(("page %"Y"u not a meta page", p->mp_pgno));
3915 if (m->mm_magic != MDB_MAGIC) {
3916 DPUTS("meta has invalid magic");
3920 if (m->mm_version != MDB_DATA_VERSION) {
3921 DPRINTF(("database is version %u, expected version %u",
3922 m->mm_version, MDB_DATA_VERSION));
3923 return MDB_VERSION_MISMATCH;
3926 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3932 /** Fill in most of the zeroed #MDB_meta for an empty database environment */
3934 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
3936 meta->mm_magic = MDB_MAGIC;
3937 meta->mm_version = MDB_DATA_VERSION;
3938 meta->mm_mapsize = env->me_mapsize;
3939 meta->mm_psize = env->me_psize;
3940 meta->mm_last_pg = NUM_METAS-1;
3941 meta->mm_flags = env->me_flags & 0xffff;
3942 meta->mm_flags |= MDB_INTEGERKEY; /* this is mm_dbs[FREE_DBI].md_flags */
3943 meta->mm_dbs[FREE_DBI].md_root = P_INVALID;
3944 meta->mm_dbs[MAIN_DBI].md_root = P_INVALID;
3947 /** Write the environment parameters of a freshly created DB environment.
3948 * @param[in] env the environment handle
3949 * @param[in] meta the #MDB_meta to write
3950 * @return 0 on success, non-zero on failure.
3953 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3961 memset(&ov, 0, sizeof(ov));
3962 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3964 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3967 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3968 len = pwrite(fd, ptr, size, pos); \
3969 if (len == -1 && ErrCode() == EINTR) continue; \
3970 rc = (len >= 0); break; } while(1)
3973 DPUTS("writing new meta page");
3975 psize = env->me_psize;
3977 p = calloc(NUM_METAS, psize);
3981 p->mp_flags = P_META;
3982 *(MDB_meta *)METADATA(p) = *meta;
3984 q = (MDB_page *)((char *)p + psize);
3986 q->mp_flags = P_META;
3987 *(MDB_meta *)METADATA(q) = *meta;
3989 DO_PWRITE(rc, env->me_fd, p, psize * NUM_METAS, len, 0);
3992 else if ((unsigned) len == psize * NUM_METAS)
4000 /** Update the environment info to commit a transaction.
4001 * @param[in] txn the transaction that's being committed
4002 * @return 0 on success, non-zero on failure.
4005 mdb_env_write_meta(MDB_txn *txn)
4008 MDB_meta meta, metab, *mp;
4012 int rc, len, toggle;
4021 toggle = txn->mt_txnid & 1;
4022 DPRINTF(("writing meta page %d for root page %"Y"u",
4023 toggle, txn->mt_dbs[MAIN_DBI].md_root));
4026 flags = txn->mt_flags | env->me_flags;
4027 mp = env->me_metas[toggle];
4028 mapsize = env->me_metas[toggle ^ 1]->mm_mapsize;
4029 /* Persist any increases of mapsize config */
4030 if (mapsize < env->me_mapsize)
4031 mapsize = env->me_mapsize;
4033 if (flags & MDB_WRITEMAP) {
4034 mp->mm_mapsize = mapsize;
4035 mp->mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
4036 mp->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
4037 mp->mm_last_pg = txn->mt_next_pgno - 1;
4038 #if (__GNUC__ * 100 + __GNUC_MINOR__ >= 404) && /* TODO: portability */ \
4039 !(defined(__i386__) || defined(__x86_64__))
4040 /* LY: issue a memory barrier, if not x86. ITS#7969 */
4041 __sync_synchronize();
4043 mp->mm_txnid = txn->mt_txnid;
4044 if (!(flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
4045 unsigned meta_size = env->me_psize;
4046 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
4047 ptr = (char *)mp - PAGEHDRSZ;
4048 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
4049 r2 = (ptr - env->me_map) & (env->me_os_psize - 1);
4053 if (MDB_MSYNC(ptr, meta_size, rc)) {
4060 metab.mm_txnid = mp->mm_txnid;
4061 metab.mm_last_pg = mp->mm_last_pg;
4063 meta.mm_mapsize = mapsize;
4064 meta.mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
4065 meta.mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
4066 meta.mm_last_pg = txn->mt_next_pgno - 1;
4067 meta.mm_txnid = txn->mt_txnid;
4069 off = offsetof(MDB_meta, mm_mapsize);
4070 ptr = (char *)&meta + off;
4071 len = sizeof(MDB_meta) - off;
4072 off += (char *)mp - env->me_map;
4074 /* Write to the SYNC fd */
4075 mfd = (flags & (MDB_NOSYNC|MDB_NOMETASYNC)) ? env->me_fd : env->me_mfd;
4078 memset(&ov, 0, sizeof(ov));
4080 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
4085 rc = pwrite(mfd, ptr, len, off);
4088 rc = rc < 0 ? ErrCode() : EIO;
4093 DPUTS("write failed, disk error?");
4094 /* On a failure, the pagecache still contains the new data.
4095 * Write some old data back, to prevent it from being used.
4096 * Use the non-SYNC fd; we know it will fail anyway.
4098 meta.mm_last_pg = metab.mm_last_pg;
4099 meta.mm_txnid = metab.mm_txnid;
4101 memset(&ov, 0, sizeof(ov));
4103 WriteFile(env->me_fd, ptr, len, NULL, &ov);
4105 r2 = pwrite(env->me_fd, ptr, len, off);
4106 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
4109 env->me_flags |= MDB_FATAL_ERROR;
4112 /* MIPS has cache coherency issues, this is a no-op everywhere else */
4113 CACHEFLUSH(env->me_map + off, len, DCACHE);
4115 /* Memory ordering issues are irrelevant; since the entire writer
4116 * is wrapped by wmutex, all of these changes will become visible
4117 * after the wmutex is unlocked. Since the DB is multi-version,
4118 * readers will get consistent data regardless of how fresh or
4119 * how stale their view of these values is.
4122 env->me_txns->mti_txnid = txn->mt_txnid;
4127 /** Check both meta pages to see which one is newer.
4128 * @param[in] env the environment handle
4129 * @return newest #MDB_meta.
4132 mdb_env_pick_meta(const MDB_env *env)
4134 MDB_meta *const *metas = env->me_metas;
4135 return metas[ metas[0]->mm_txnid < metas[1]->mm_txnid ];
4139 mdb_env_create(MDB_env **env)
4143 e = calloc(1, sizeof(MDB_env));
4147 e->me_maxreaders = DEFAULT_READERS;
4148 e->me_maxdbs = e->me_numdbs = CORE_DBS;
4149 e->me_fd = INVALID_HANDLE_VALUE;
4150 e->me_lfd = INVALID_HANDLE_VALUE;
4151 e->me_mfd = INVALID_HANDLE_VALUE;
4152 #ifdef MDB_USE_POSIX_SEM
4153 e->me_rmutex = SEM_FAILED;
4154 e->me_wmutex = SEM_FAILED;
4155 #elif defined MDB_USE_SYSV_SEM
4156 e->me_rmutex->semid = -1;
4157 e->me_wmutex->semid = -1;
4159 e->me_pid = getpid();
4160 GET_PAGESIZE(e->me_os_psize);
4161 VGMEMP_CREATE(e,0,0);
4167 /** @brief Map a result from an NTAPI call to WIN32. */
4169 mdb_nt2win32(NTSTATUS st)
4174 GetOverlappedResult(NULL, &o, &br, FALSE);
4175 return GetLastError();
4180 mdb_env_map(MDB_env *env, void *addr)
4183 unsigned int flags = env->me_flags;
4186 int access = SECTION_MAP_READ;
4190 ULONG pageprot = PAGE_READONLY, secprot, alloctype;
4192 if (flags & MDB_WRITEMAP) {
4193 access |= SECTION_MAP_WRITE;
4194 pageprot = PAGE_READWRITE;
4196 if (flags & MDB_RDONLY) {
4197 secprot = PAGE_READONLY;
4201 secprot = PAGE_READWRITE;
4202 msize = env->me_mapsize;
4203 alloctype = MEM_RESERVE;
4206 rc = NtCreateSection(&mh, access, NULL, NULL, secprot, SEC_RESERVE, env->me_fd);
4208 return mdb_nt2win32(rc);
4211 msize = NUM_METAS * env->me_psize;
4213 rc = NtMapViewOfSection(mh, GetCurrentProcess(), &map, 0, 0, NULL, &msize, ViewUnmap, alloctype, pageprot);
4220 return mdb_nt2win32(rc);
4225 env->me_map = mmap(addr, NUM_METAS * env->me_psize, PROT_READ, MAP_SHARED,
4227 if (env->me_map == MAP_FAILED) {
4232 int prot = PROT_READ;
4233 if (flags & MDB_WRITEMAP) {
4235 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
4238 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
4240 if (env->me_map == MAP_FAILED) {
4245 if (flags & MDB_NORDAHEAD) {
4246 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
4248 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
4250 #ifdef POSIX_MADV_RANDOM
4251 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
4252 #endif /* POSIX_MADV_RANDOM */
4253 #endif /* MADV_RANDOM */
4257 /* Can happen because the address argument to mmap() is just a
4258 * hint. mmap() can pick another, e.g. if the range is in use.
4259 * The MAP_FIXED flag would prevent that, but then mmap could
4260 * instead unmap existing pages to make room for the new map.
4262 if (addr && env->me_map != addr)
4263 return EBUSY; /* TODO: Make a new MDB_* error code? */
4266 p = (MDB_page *)env->me_map;
4267 env->me_metas[0] = METADATA(p);
4268 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
4274 mdb_env_set_mapsize(MDB_env *env, mdb_size_t size)
4276 /* If env is already open, caller is responsible for making
4277 * sure there are no active txns.
4287 meta = mdb_env_pick_meta(env);
4289 size = meta->mm_mapsize;
4291 /* Silently round up to minimum if the size is too small */
4292 mdb_size_t minsize = (meta->mm_last_pg + 1) * env->me_psize;
4297 /* For MDB_VL32 this bit is a noop since we dynamically remap
4298 * chunks of the DB anyway.
4300 munmap(env->me_map, env->me_mapsize);
4301 env->me_mapsize = size;
4302 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
4303 rc = mdb_env_map(env, old);
4306 #endif /* !MDB_VL32 */
4308 env->me_mapsize = size;
4310 env->me_maxpg = env->me_mapsize / env->me_psize;
4315 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
4319 env->me_maxdbs = dbs + CORE_DBS;
4324 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
4326 if (env->me_map || readers < 1)
4328 env->me_maxreaders = readers;
4333 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
4335 if (!env || !readers)
4337 *readers = env->me_maxreaders;
4342 mdb_fsize(HANDLE fd, mdb_size_t *size)
4345 LARGE_INTEGER fsize;
4347 if (!GetFileSizeEx(fd, &fsize))
4350 *size = fsize.QuadPart;
4362 #ifdef BROKEN_FDATASYNC
4363 #include <sys/utsname.h>
4364 #include <sys/vfs.h>
4367 /** Further setup required for opening an LMDB environment
4370 mdb_env_open2(MDB_env *env)
4372 unsigned int flags = env->me_flags;
4373 int i, newenv = 0, rc;
4377 /* See if we should use QueryLimited */
4379 if ((rc & 0xff) > 5)
4380 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
4382 env->me_pidquery = PROCESS_QUERY_INFORMATION;
4385 #ifdef BROKEN_FDATASYNC
4386 /* ext3/ext4 fdatasync is broken on some older Linux kernels.
4387 * https://lkml.org/lkml/2012/9/3/83
4388 * Kernels after 3.6-rc6 are known good.
4389 * https://lkml.org/lkml/2012/9/10/556
4390 * See if the DB is on ext3/ext4, then check for new enough kernel
4391 * Kernels 2.6.32.60, 2.6.34.15, 3.2.30, and 3.5.4 are also known
4396 fstatfs(env->me_fd, &st);
4397 while (st.f_type == 0xEF53) {
4401 if (uts.release[0] < '3') {
4402 if (!strncmp(uts.release, "2.6.32.", 7)) {
4403 i = atoi(uts.release+7);
4405 break; /* 2.6.32.60 and newer is OK */
4406 } else if (!strncmp(uts.release, "2.6.34.", 7)) {
4407 i = atoi(uts.release+7);
4409 break; /* 2.6.34.15 and newer is OK */
4411 } else if (uts.release[0] == '3') {
4412 i = atoi(uts.release+2);
4414 break; /* 3.6 and newer is OK */
4416 i = atoi(uts.release+4);
4418 break; /* 3.5.4 and newer is OK */
4419 } else if (i == 2) {
4420 i = atoi(uts.release+4);
4422 break; /* 3.2.30 and newer is OK */
4424 } else { /* 4.x and newer is OK */
4427 env->me_flags |= MDB_FSYNCONLY;
4433 if ((i = mdb_env_read_header(env, &meta)) != 0) {
4436 DPUTS("new mdbenv");
4438 env->me_psize = env->me_os_psize;
4439 if (env->me_psize > MAX_PAGESIZE)
4440 env->me_psize = MAX_PAGESIZE;
4441 memset(&meta, 0, sizeof(meta));
4442 mdb_env_init_meta0(env, &meta);
4443 meta.mm_mapsize = DEFAULT_MAPSIZE;
4445 env->me_psize = meta.mm_psize;
4448 /* Was a mapsize configured? */
4449 if (!env->me_mapsize) {
4450 env->me_mapsize = meta.mm_mapsize;
4453 /* Make sure mapsize >= committed data size. Even when using
4454 * mm_mapsize, which could be broken in old files (ITS#7789).
4456 mdb_size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
4457 if (env->me_mapsize < minsize)
4458 env->me_mapsize = minsize;
4460 meta.mm_mapsize = env->me_mapsize;
4462 if (newenv && !(flags & MDB_FIXEDMAP)) {
4463 /* mdb_env_map() may grow the datafile. Write the metapages
4464 * first, so the file will be valid if initialization fails.
4465 * Except with FIXEDMAP, since we do not yet know mm_address.
4466 * We could fill in mm_address later, but then a different
4467 * program might end up doing that - one with a memory layout
4468 * and map address which does not suit the main program.
4470 rc = mdb_env_init_meta(env, &meta);
4476 /* For FIXEDMAP, make sure the file is non-empty before we attempt to map it */
4480 rc = WriteFile(env->me_fd, &dummy, 1, &len, NULL);
4488 rc = mdb_env_map(env, (flags & MDB_FIXEDMAP) ? meta.mm_address : NULL);
4493 if (flags & MDB_FIXEDMAP)
4494 meta.mm_address = env->me_map;
4495 i = mdb_env_init_meta(env, &meta);
4496 if (i != MDB_SUCCESS) {
4501 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
4502 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
4504 #if !(MDB_MAXKEYSIZE)
4505 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
4507 env->me_maxpg = env->me_mapsize / env->me_psize;
4511 MDB_meta *meta = mdb_env_pick_meta(env);
4512 MDB_db *db = &meta->mm_dbs[MAIN_DBI];
4514 DPRINTF(("opened database version %u, pagesize %u",
4515 meta->mm_version, env->me_psize));
4516 DPRINTF(("using meta page %d", (int) (meta->mm_txnid & 1)));
4517 DPRINTF(("depth: %u", db->md_depth));
4518 DPRINTF(("entries: %"Y"u", db->md_entries));
4519 DPRINTF(("branch pages: %"Y"u", db->md_branch_pages));
4520 DPRINTF(("leaf pages: %"Y"u", db->md_leaf_pages));
4521 DPRINTF(("overflow pages: %"Y"u", db->md_overflow_pages));
4522 DPRINTF(("root: %"Y"u", db->md_root));
4530 /** Release a reader thread's slot in the reader lock table.
4531 * This function is called automatically when a thread exits.
4532 * @param[in] ptr This points to the slot in the reader lock table.
4535 mdb_env_reader_dest(void *ptr)
4537 MDB_reader *reader = ptr;
4543 /** Junk for arranging thread-specific callbacks on Windows. This is
4544 * necessarily platform and compiler-specific. Windows supports up
4545 * to 1088 keys. Let's assume nobody opens more than 64 environments
4546 * in a single process, for now. They can override this if needed.
4548 #ifndef MAX_TLS_KEYS
4549 #define MAX_TLS_KEYS 64
4551 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
4552 static int mdb_tls_nkeys;
4554 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
4558 case DLL_PROCESS_ATTACH: break;
4559 case DLL_THREAD_ATTACH: break;
4560 case DLL_THREAD_DETACH:
4561 for (i=0; i<mdb_tls_nkeys; i++) {
4562 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
4564 mdb_env_reader_dest(r);
4568 case DLL_PROCESS_DETACH: break;
4573 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4575 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4579 /* Force some symbol references.
4580 * _tls_used forces the linker to create the TLS directory if not already done
4581 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
4583 #pragma comment(linker, "/INCLUDE:_tls_used")
4584 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
4585 #pragma const_seg(".CRT$XLB")
4586 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
4587 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4590 #pragma comment(linker, "/INCLUDE:__tls_used")
4591 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
4592 #pragma data_seg(".CRT$XLB")
4593 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4595 #endif /* WIN 32/64 */
4596 #endif /* !__GNUC__ */
4599 /** Downgrade the exclusive lock on the region back to shared */
4601 mdb_env_share_locks(MDB_env *env, int *excl)
4604 MDB_meta *meta = mdb_env_pick_meta(env);
4606 env->me_txns->mti_txnid = meta->mm_txnid;
4611 /* First acquire a shared lock. The Unlock will
4612 * then release the existing exclusive lock.
4614 memset(&ov, 0, sizeof(ov));
4615 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4618 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4624 struct flock lock_info;
4625 /* The shared lock replaces the existing lock */
4626 memset((void *)&lock_info, 0, sizeof(lock_info));
4627 lock_info.l_type = F_RDLCK;
4628 lock_info.l_whence = SEEK_SET;
4629 lock_info.l_start = 0;
4630 lock_info.l_len = 1;
4631 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4632 (rc = ErrCode()) == EINTR) ;
4633 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
4640 /** Try to get exclusive lock, otherwise shared.
4641 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
4644 mdb_env_excl_lock(MDB_env *env, int *excl)
4648 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
4652 memset(&ov, 0, sizeof(ov));
4653 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4660 struct flock lock_info;
4661 memset((void *)&lock_info, 0, sizeof(lock_info));
4662 lock_info.l_type = F_WRLCK;
4663 lock_info.l_whence = SEEK_SET;
4664 lock_info.l_start = 0;
4665 lock_info.l_len = 1;
4666 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4667 (rc = ErrCode()) == EINTR) ;
4671 # ifndef MDB_USE_POSIX_MUTEX
4672 if (*excl < 0) /* always true when MDB_USE_POSIX_MUTEX */
4675 lock_info.l_type = F_RDLCK;
4676 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
4677 (rc = ErrCode()) == EINTR) ;
4687 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
4689 * @(#) $Revision: 5.1 $
4690 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
4691 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
4693 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
4697 * Please do not copyright this code. This code is in the public domain.
4699 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
4700 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
4701 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
4702 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
4703 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4704 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4705 * PERFORMANCE OF THIS SOFTWARE.
4708 * chongo <Landon Curt Noll> /\oo/\
4709 * http://www.isthe.com/chongo/
4711 * Share and Enjoy! :-)
4714 typedef unsigned long long mdb_hash_t;
4715 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
4717 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
4718 * @param[in] val value to hash
4719 * @param[in] hval initial value for hash
4720 * @return 64 bit hash
4722 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
4723 * hval arg on the first call.
4726 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
4728 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
4729 unsigned char *end = s + val->mv_size;
4731 * FNV-1a hash each octet of the string
4734 /* xor the bottom with the current octet */
4735 hval ^= (mdb_hash_t)*s++;
4737 /* multiply by the 64 bit FNV magic prime mod 2^64 */
4738 hval += (hval << 1) + (hval << 4) + (hval << 5) +
4739 (hval << 7) + (hval << 8) + (hval << 40);
4741 /* return our new hash value */
4745 /** Hash the string and output the encoded hash.
4746 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
4747 * very short name limits. We don't care about the encoding being reversible,
4748 * we just want to preserve as many bits of the input as possible in a
4749 * small printable string.
4750 * @param[in] str string to hash
4751 * @param[out] encbuf an array of 11 chars to hold the hash
4753 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
4756 mdb_pack85(unsigned long l, char *out)
4760 for (i=0; i<5; i++) {
4761 *out++ = mdb_a85[l % 85];
4767 mdb_hash_enc(MDB_val *val, char *encbuf)
4769 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
4771 mdb_pack85(h, encbuf);
4772 mdb_pack85(h>>32, encbuf+5);
4777 /** Open and/or initialize the lock region for the environment.
4778 * @param[in] env The LMDB environment.
4779 * @param[in] lpath The pathname of the file used for the lock region.
4780 * @param[in] mode The Unix permissions for the file, if we create it.
4781 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
4782 * @return 0 on success, non-zero on failure.
4785 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
4788 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
4790 # define MDB_ERRCODE_ROFS EROFS
4791 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
4792 # define MDB_CLOEXEC O_CLOEXEC
4795 # define MDB_CLOEXEC 0
4798 #ifdef MDB_USE_SYSV_SEM
4807 rc = utf8_to_utf16(lpath, -1, &wlpath, NULL);
4810 env->me_lfd = CreateFileW(wlpath, GENERIC_READ|GENERIC_WRITE,
4811 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
4812 FILE_ATTRIBUTE_NORMAL, NULL);
4815 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
4817 if (env->me_lfd == INVALID_HANDLE_VALUE) {
4819 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
4824 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
4825 /* Lose record locks when exec*() */
4826 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
4827 fcntl(env->me_lfd, F_SETFD, fdflags);
4830 if (!(env->me_flags & MDB_NOTLS)) {
4831 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
4834 env->me_flags |= MDB_ENV_TXKEY;
4836 /* Windows TLS callbacks need help finding their TLS info. */
4837 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
4841 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
4845 /* Try to get exclusive lock. If we succeed, then
4846 * nobody is using the lock region and we should initialize it.
4848 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
4851 size = GetFileSize(env->me_lfd, NULL);
4853 size = lseek(env->me_lfd, 0, SEEK_END);
4854 if (size == -1) goto fail_errno;
4856 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
4857 if (size < rsize && *excl > 0) {
4859 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
4860 || !SetEndOfFile(env->me_lfd))
4863 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
4867 size = rsize - sizeof(MDB_txninfo);
4868 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
4873 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
4875 if (!mh) goto fail_errno;
4876 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
4878 if (!env->me_txns) goto fail_errno;
4880 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
4882 if (m == MAP_FAILED) goto fail_errno;
4888 BY_HANDLE_FILE_INFORMATION stbuf;
4897 if (!mdb_sec_inited) {
4898 InitializeSecurityDescriptor(&mdb_null_sd,
4899 SECURITY_DESCRIPTOR_REVISION);
4900 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
4901 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
4902 mdb_all_sa.bInheritHandle = FALSE;
4903 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
4906 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
4907 idbuf.volume = stbuf.dwVolumeSerialNumber;
4908 idbuf.nhigh = stbuf.nFileIndexHigh;
4909 idbuf.nlow = stbuf.nFileIndexLow;
4910 val.mv_data = &idbuf;
4911 val.mv_size = sizeof(idbuf);
4912 mdb_hash_enc(&val, encbuf);
4913 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
4914 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
4915 env->me_rmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
4916 if (!env->me_rmutex) goto fail_errno;
4917 env->me_wmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
4918 if (!env->me_wmutex) goto fail_errno;
4919 #elif defined(MDB_USE_POSIX_SEM)
4928 #if defined(__NetBSD__)
4929 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
4931 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
4932 idbuf.dev = stbuf.st_dev;
4933 idbuf.ino = stbuf.st_ino;
4934 val.mv_data = &idbuf;
4935 val.mv_size = sizeof(idbuf);
4936 mdb_hash_enc(&val, encbuf);
4937 #ifdef MDB_SHORT_SEMNAMES
4938 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
4940 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
4941 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
4942 /* Clean up after a previous run, if needed: Try to
4943 * remove both semaphores before doing anything else.
4945 sem_unlink(env->me_txns->mti_rmname);
4946 sem_unlink(env->me_txns->mti_wmname);
4947 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
4948 O_CREAT|O_EXCL, mode, 1);
4949 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4950 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
4951 O_CREAT|O_EXCL, mode, 1);
4952 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4953 #elif defined(MDB_USE_SYSV_SEM)
4954 unsigned short vals[2] = {1, 1};
4955 key_t key = ftok(lpath, 'M');
4958 semid = semget(key, 2, (mode & 0777) | IPC_CREAT);
4962 if (semctl(semid, 0, SETALL, semu) < 0)
4964 env->me_txns->mti_semid = semid;
4965 env->me_txns->mti_rlocked = 0;
4966 env->me_txns->mti_wlocked = 0;
4967 #else /* MDB_USE_POSIX_MUTEX: */
4968 pthread_mutexattr_t mattr;
4970 /* Solaris needs this before initing a robust mutex. Otherwise
4971 * it may skip the init and return EBUSY "seems someone already
4972 * inited" or EINVAL "it was inited differently".
4974 memset(env->me_txns->mti_rmutex, 0, sizeof(*env->me_txns->mti_rmutex));
4975 memset(env->me_txns->mti_wmutex, 0, sizeof(*env->me_txns->mti_wmutex));
4977 if ((rc = pthread_mutexattr_init(&mattr)) != 0)
4979 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
4980 #ifdef MDB_ROBUST_SUPPORTED
4981 if (!rc) rc = pthread_mutexattr_setrobust(&mattr, PTHREAD_MUTEX_ROBUST);
4983 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_rmutex, &mattr);
4984 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_wmutex, &mattr);
4985 pthread_mutexattr_destroy(&mattr);
4988 #endif /* _WIN32 || ... */
4990 env->me_txns->mti_magic = MDB_MAGIC;
4991 env->me_txns->mti_format = MDB_LOCK_FORMAT;
4992 env->me_txns->mti_txnid = 0;
4993 env->me_txns->mti_numreaders = 0;
4996 #ifdef MDB_USE_SYSV_SEM
4997 struct semid_ds buf;
4999 if (env->me_txns->mti_magic != MDB_MAGIC) {
5000 DPUTS("lock region has invalid magic");
5004 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
5005 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
5006 env->me_txns->mti_format, MDB_LOCK_FORMAT));
5007 rc = MDB_VERSION_MISMATCH;
5011 if (rc && rc != EACCES && rc != EAGAIN) {
5015 env->me_rmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
5016 if (!env->me_rmutex) goto fail_errno;
5017 env->me_wmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
5018 if (!env->me_wmutex) goto fail_errno;
5019 #elif defined(MDB_USE_POSIX_SEM)
5020 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
5021 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
5022 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
5023 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
5024 #elif defined(MDB_USE_SYSV_SEM)
5025 semid = env->me_txns->mti_semid;
5027 /* check for read access */
5028 if (semctl(semid, 0, IPC_STAT, semu) < 0)
5030 /* check for write access */
5031 if (semctl(semid, 0, IPC_SET, semu) < 0)
5035 #ifdef MDB_USE_SYSV_SEM
5036 env->me_rmutex->semid = semid;
5037 env->me_wmutex->semid = semid;
5038 env->me_rmutex->semnum = 0;
5039 env->me_wmutex->semnum = 1;
5040 env->me_rmutex->locked = &env->me_txns->mti_rlocked;
5041 env->me_wmutex->locked = &env->me_txns->mti_wlocked;
5045 env->me_rpmutex = CreateMutex(NULL, FALSE, NULL);
5047 pthread_mutex_init(&env->me_rpmutex, NULL);
5059 /** The name of the lock file in the DB environment */
5060 #define LOCKNAME "/lock.mdb"
5061 /** The name of the data file in the DB environment */
5062 #define DATANAME "/data.mdb"
5063 /** The suffix of the lock file when no subdir is used */
5064 #define LOCKSUFF "-lock"
5065 /** Only a subset of the @ref mdb_env flags can be changed
5066 * at runtime. Changing other flags requires closing the
5067 * environment and re-opening it with the new flags.
5069 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
5070 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY| \
5071 MDB_WRITEMAP|MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
5073 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
5074 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
5078 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
5080 int oflags, rc, len, excl = -1;
5081 char *lpath, *dpath;
5086 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
5090 if (flags & MDB_WRITEMAP) {
5091 /* silently ignore WRITEMAP in 32 bit mode */
5092 flags ^= MDB_WRITEMAP;
5094 if (flags & MDB_FIXEDMAP) {
5095 /* cannot support FIXEDMAP */
5101 if (flags & MDB_NOSUBDIR) {
5102 rc = len + sizeof(LOCKSUFF) + len + 1;
5104 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
5109 if (flags & MDB_NOSUBDIR) {
5110 dpath = lpath + len + sizeof(LOCKSUFF);
5111 sprintf(lpath, "%s" LOCKSUFF, path);
5112 strcpy(dpath, path);
5114 dpath = lpath + len + sizeof(LOCKNAME);
5115 sprintf(lpath, "%s" LOCKNAME, path);
5116 sprintf(dpath, "%s" DATANAME, path);
5120 flags |= env->me_flags;
5121 if (flags & MDB_RDONLY) {
5122 /* silently ignore WRITEMAP when we're only getting read access */
5123 flags &= ~MDB_WRITEMAP;
5125 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
5126 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
5131 env->me_rpages = malloc(MDB_ERPAGE_SIZE * sizeof(MDB_ID3));
5132 if (!env->me_rpages) {
5136 env->me_rpages[0].mid = 0;
5137 env->me_rpcheck = MDB_ERPAGE_SIZE/2;
5140 env->me_flags = flags |= MDB_ENV_ACTIVE;
5144 env->me_path = strdup(path);
5145 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
5146 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
5147 env->me_dbiseqs = calloc(env->me_maxdbs, sizeof(unsigned int));
5148 if (!(env->me_dbxs && env->me_path && env->me_dbflags && env->me_dbiseqs)) {
5152 env->me_dbxs[FREE_DBI].md_cmp = mdb_cmp_long; /* aligned MDB_INTEGERKEY */
5154 /* For RDONLY, get lockfile after we know datafile exists */
5155 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
5156 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
5162 if (F_ISSET(flags, MDB_RDONLY)) {
5163 oflags = GENERIC_READ;
5164 len = OPEN_EXISTING;
5166 oflags = GENERIC_READ|GENERIC_WRITE;
5169 mode = FILE_ATTRIBUTE_NORMAL;
5170 rc = utf8_to_utf16(dpath, -1, &wpath, NULL);
5173 env->me_fd = CreateFileW(wpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
5174 NULL, len, mode, NULL);
5177 if (F_ISSET(flags, MDB_RDONLY))
5180 oflags = O_RDWR | O_CREAT;
5182 env->me_fd = open(dpath, oflags, mode);
5184 if (env->me_fd == INVALID_HANDLE_VALUE) {
5189 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
5190 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
5195 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
5196 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
5197 env->me_mfd = env->me_fd;
5199 /* Synchronous fd for meta writes. Needed even with
5200 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
5203 len = OPEN_EXISTING;
5204 rc = utf8_to_utf16(dpath, -1, &wpath, NULL);
5207 env->me_mfd = CreateFileW(wpath, oflags,
5208 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
5209 mode | FILE_FLAG_WRITE_THROUGH, NULL);
5213 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
5215 if (env->me_mfd == INVALID_HANDLE_VALUE) {
5220 DPRINTF(("opened dbenv %p", (void *) env));
5222 rc = mdb_env_share_locks(env, &excl);
5226 if (!(flags & MDB_RDONLY)) {
5228 int tsize = sizeof(MDB_txn), size = tsize + env->me_maxdbs *
5229 (sizeof(MDB_db)+sizeof(MDB_cursor *)+sizeof(unsigned int)+1);
5230 if ((env->me_pbuf = calloc(1, env->me_psize)) &&
5231 (txn = calloc(1, size)))
5233 txn->mt_dbs = (MDB_db *)((char *)txn + tsize);
5234 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
5235 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
5236 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
5239 txn->mt_rpages = malloc(MDB_TRPAGE_SIZE * sizeof(MDB_ID3));
5240 if (!txn->mt_rpages) {
5245 txn->mt_rpages[0].mid = 0;
5246 txn->mt_rpcheck = MDB_TRPAGE_SIZE/2;
5248 txn->mt_dbxs = env->me_dbxs;
5249 txn->mt_flags = MDB_TXN_FINISHED;
5259 mdb_env_close0(env, excl);
5265 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
5267 mdb_env_close0(MDB_env *env, int excl)
5271 if (!(env->me_flags & MDB_ENV_ACTIVE))
5274 /* Doing this here since me_dbxs may not exist during mdb_env_close */
5276 for (i = env->me_maxdbs; --i >= CORE_DBS; )
5277 free(env->me_dbxs[i].md_name.mv_data);
5282 free(env->me_dbiseqs);
5283 free(env->me_dbflags);
5285 free(env->me_dirty_list);
5287 if (env->me_txn0 && env->me_txn0->mt_rpages)
5288 free(env->me_txn0->mt_rpages);
5290 for (x=1; x<=env->me_rpages[0].mid; x++)
5291 munmap(env->me_rpages[x].mptr, env->me_rpages[x].mcnt * env->me_psize);
5293 free(env->me_rpages);
5296 mdb_midl_free(env->me_free_pgs);
5298 if (env->me_flags & MDB_ENV_TXKEY) {
5299 pthread_key_delete(env->me_txkey);
5301 /* Delete our key from the global list */
5302 for (i=0; i<mdb_tls_nkeys; i++)
5303 if (mdb_tls_keys[i] == env->me_txkey) {
5304 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
5313 munmap(env->me_map, NUM_METAS*env->me_psize);
5315 munmap(env->me_map, env->me_mapsize);
5318 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
5319 (void) close(env->me_mfd);
5320 if (env->me_fd != INVALID_HANDLE_VALUE)
5321 (void) close(env->me_fd);
5323 MDB_PID_T pid = env->me_pid;
5324 /* Clearing readers is done in this function because
5325 * me_txkey with its destructor must be disabled first.
5327 * We skip the the reader mutex, so we touch only
5328 * data owned by this process (me_close_readers and
5329 * our readers), and clear each reader atomically.
5331 for (i = env->me_close_readers; --i >= 0; )
5332 if (env->me_txns->mti_readers[i].mr_pid == pid)
5333 env->me_txns->mti_readers[i].mr_pid = 0;
5335 if (env->me_rmutex) {
5336 CloseHandle(env->me_rmutex);
5337 if (env->me_wmutex) CloseHandle(env->me_wmutex);
5339 /* Windows automatically destroys the mutexes when
5340 * the last handle closes.
5342 #elif defined(MDB_USE_POSIX_SEM)
5343 if (env->me_rmutex != SEM_FAILED) {
5344 sem_close(env->me_rmutex);
5345 if (env->me_wmutex != SEM_FAILED)
5346 sem_close(env->me_wmutex);
5347 /* If we have the filelock: If we are the
5348 * only remaining user, clean up semaphores.
5351 mdb_env_excl_lock(env, &excl);
5353 sem_unlink(env->me_txns->mti_rmname);
5354 sem_unlink(env->me_txns->mti_wmname);
5357 #elif defined(MDB_USE_SYSV_SEM)
5358 if (env->me_rmutex->semid != -1) {
5359 /* If we have the filelock: If we are the
5360 * only remaining user, clean up semaphores.
5363 mdb_env_excl_lock(env, &excl);
5365 semctl(env->me_rmutex->semid, 0, IPC_RMID);
5368 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
5370 if (env->me_lfd != INVALID_HANDLE_VALUE) {
5373 /* Unlock the lockfile. Windows would have unlocked it
5374 * after closing anyway, but not necessarily at once.
5376 UnlockFile(env->me_lfd, 0, 0, 1, 0);
5379 (void) close(env->me_lfd);
5383 if (env->me_fmh) CloseHandle(env->me_fmh);
5384 if (env->me_rpmutex) CloseHandle(env->me_rpmutex);
5386 pthread_mutex_destroy(&env->me_rpmutex);
5390 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
5394 mdb_env_close(MDB_env *env)
5401 VGMEMP_DESTROY(env);
5402 while ((dp = env->me_dpages) != NULL) {
5403 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
5404 env->me_dpages = dp->mp_next;
5408 mdb_env_close0(env, 0);
5412 /** Compare two items pointing at aligned mdb_size_t's */
5414 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
5416 return (*(mdb_size_t *)a->mv_data < *(mdb_size_t *)b->mv_data) ? -1 :
5417 *(mdb_size_t *)a->mv_data > *(mdb_size_t *)b->mv_data;
5420 /** Compare two items pointing at aligned unsigned int's.
5422 * This is also set as #MDB_INTEGERDUP|#MDB_DUPFIXED's #MDB_dbx.%md_dcmp,
5423 * but #mdb_cmp_clong() is called instead if the data type is mdb_size_t.
5426 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
5428 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
5429 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
5432 /** Compare two items pointing at unsigned ints of unknown alignment.
5433 * Nodes and keys are guaranteed to be 2-byte aligned.
5436 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
5438 #if BYTE_ORDER == LITTLE_ENDIAN
5439 unsigned short *u, *c;
5442 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5443 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
5446 } while(!x && u > (unsigned short *)a->mv_data);
5449 unsigned short *u, *c, *end;
5452 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5453 u = (unsigned short *)a->mv_data;
5454 c = (unsigned short *)b->mv_data;
5457 } while(!x && u < end);
5462 /** Compare two items lexically */
5464 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
5471 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5477 diff = memcmp(a->mv_data, b->mv_data, len);
5478 return diff ? diff : len_diff<0 ? -1 : len_diff;
5481 /** Compare two items in reverse byte order */
5483 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
5485 const unsigned char *p1, *p2, *p1_lim;
5489 p1_lim = (const unsigned char *)a->mv_data;
5490 p1 = (const unsigned char *)a->mv_data + a->mv_size;
5491 p2 = (const unsigned char *)b->mv_data + b->mv_size;
5493 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5499 while (p1 > p1_lim) {
5500 diff = *--p1 - *--p2;
5504 return len_diff<0 ? -1 : len_diff;
5507 /** Search for key within a page, using binary search.
5508 * Returns the smallest entry larger or equal to the key.
5509 * If exactp is non-null, stores whether the found entry was an exact match
5510 * in *exactp (1 or 0).
5511 * Updates the cursor index with the index of the found entry.
5512 * If no entry larger or equal to the key is found, returns NULL.
5515 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
5517 unsigned int i = 0, nkeys;
5520 MDB_page *mp = mc->mc_pg[mc->mc_top];
5521 MDB_node *node = NULL;
5526 nkeys = NUMKEYS(mp);
5528 DPRINTF(("searching %u keys in %s %spage %"Y"u",
5529 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
5532 low = IS_LEAF(mp) ? 0 : 1;
5534 cmp = mc->mc_dbx->md_cmp;
5536 /* Branch pages have no data, so if using integer keys,
5537 * alignment is guaranteed. Use faster mdb_cmp_int.
5539 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
5540 if (NODEPTR(mp, 1)->mn_ksize == sizeof(mdb_size_t))
5547 nodekey.mv_size = mc->mc_db->md_pad;
5548 node = NODEPTR(mp, 0); /* fake */
5549 while (low <= high) {
5550 i = (low + high) >> 1;
5551 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
5552 rc = cmp(key, &nodekey);
5553 DPRINTF(("found leaf index %u [%s], rc = %i",
5554 i, DKEY(&nodekey), rc));
5563 while (low <= high) {
5564 i = (low + high) >> 1;
5566 node = NODEPTR(mp, i);
5567 nodekey.mv_size = NODEKSZ(node);
5568 nodekey.mv_data = NODEKEY(node);
5570 rc = cmp(key, &nodekey);
5573 DPRINTF(("found leaf index %u [%s], rc = %i",
5574 i, DKEY(&nodekey), rc));
5576 DPRINTF(("found branch index %u [%s -> %"Y"u], rc = %i",
5577 i, DKEY(&nodekey), NODEPGNO(node), rc));
5588 if (rc > 0) { /* Found entry is less than the key. */
5589 i++; /* Skip to get the smallest entry larger than key. */
5591 node = NODEPTR(mp, i);
5594 *exactp = (rc == 0 && nkeys > 0);
5595 /* store the key index */
5596 mc->mc_ki[mc->mc_top] = i;
5598 /* There is no entry larger or equal to the key. */
5601 /* nodeptr is fake for LEAF2 */
5607 mdb_cursor_adjust(MDB_cursor *mc, func)
5611 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5612 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
5619 /** Pop a page off the top of the cursor's stack. */
5621 mdb_cursor_pop(MDB_cursor *mc)
5624 DPRINTF(("popping page %"Y"u off db %d cursor %p",
5625 mc->mc_pg[mc->mc_top]->mp_pgno, DDBI(mc), (void *) mc));
5631 mc->mc_flags &= ~C_INITIALIZED;
5636 /** Push a page onto the top of the cursor's stack. */
5638 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
5640 DPRINTF(("pushing page %"Y"u on db %d cursor %p", mp->mp_pgno,
5641 DDBI(mc), (void *) mc));
5643 if (mc->mc_snum >= CURSOR_STACK) {
5644 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5645 return MDB_CURSOR_FULL;
5648 mc->mc_top = mc->mc_snum++;
5649 mc->mc_pg[mc->mc_top] = mp;
5650 mc->mc_ki[mc->mc_top] = 0;
5656 /** Map a read-only page.
5657 * There are two levels of tracking in use, a per-txn list and a per-env list.
5658 * ref'ing and unref'ing the per-txn list is faster since it requires no
5659 * locking. Pages are cached in the per-env list for global reuse, and a lock
5660 * is required. Pages are not immediately unmapped when their refcnt goes to
5661 * zero; they hang around in case they will be reused again soon.
5663 * When the per-txn list gets full, all pages with refcnt=0 are purged from the
5664 * list and their refcnts in the per-env list are decremented.
5666 * When the per-env list gets full, all pages with refcnt=0 are purged from the
5667 * list and their pages are unmapped.
5669 * @note "full" means the list has reached its respective rpcheck threshold.
5670 * This threshold slowly raises if no pages could be purged on a given check,
5671 * and returns to its original value when enough pages were purged.
5673 * If purging doesn't free any slots, filling the per-txn list will return
5674 * MDB_TXN_FULL, and filling the per-env list returns MDB_MAP_FULL.
5676 * Reference tracking in a txn is imperfect, pages can linger with non-zero
5677 * refcnt even without active references. It was deemed to be too invasive
5678 * to add unrefs in every required location. However, all pages are unref'd
5679 * at the end of the transaction. This guarantees that no stale references
5680 * linger in the per-env list.
5682 * Usually we map chunks of 16 pages at a time, but if an overflow page begins
5683 * at the tail of the chunk we extend the chunk to include the entire overflow
5684 * page. Unfortunately, pages can be turned into overflow pages after their
5685 * chunk was already mapped. In that case we must remap the chunk if the
5686 * overflow page is referenced. If the chunk's refcnt is 0 we can just remap
5687 * it, otherwise we temporarily map a new chunk just for the overflow page.
5689 * @note this chunk handling means we cannot guarantee that a data item
5690 * returned from the DB will stay alive for the duration of the transaction:
5691 * We unref pages as soon as a cursor moves away from the page
5692 * A subsequent op may cause a purge, which may unmap any unref'd chunks
5693 * The caller must copy the data if it must be used later in the same txn.
5695 * Also - our reference counting revolves around cursors, but overflow pages
5696 * aren't pointed to by a cursor's page stack. We have to remember them
5697 * explicitly, in the added mc_ovpg field. A single cursor can only hold a
5698 * reference to one overflow page at a time.
5700 * @param[in] txn the transaction for this access.
5701 * @param[in] pgno the page number for the page to retrieve.
5702 * @param[out] ret address of a pointer where the page's address will be stored.
5703 * @return 0 on success, non-zero on failure.
5706 mdb_rpage_get(MDB_txn *txn, pgno_t pg0, MDB_page **ret)
5708 MDB_env *env = txn->mt_env;
5710 MDB_ID3L tl = txn->mt_rpages;
5711 MDB_ID3L el = env->me_rpages;
5715 int rc, retries = 1;
5719 #define SET_OFF(off,val) off.QuadPart = val
5720 #define MAP(rc,env,addr,len,off) \
5722 rc = NtMapViewOfSection(env->me_fmh, GetCurrentProcess(), &addr, 0, \
5723 len, &off, &len, ViewUnmap, (env->me_flags & MDB_RDONLY) ? 0 : MEM_RESERVE, PAGE_READONLY); \
5724 if (rc) rc = mdb_nt2win32(rc)
5728 #define SET_OFF(off,val) off = val
5729 #define MAP(rc,env,addr,len,off) \
5730 addr = mmap(NULL, len, PROT_READ, MAP_SHARED, env->me_fd, off); \
5731 rc = (addr == MAP_FAILED) ? errno : 0
5734 /* remember the offset of the actual page number, so we can
5735 * return the correct pointer at the end.
5737 rem = pg0 & (MDB_RPAGE_CHUNK-1);
5741 x = mdb_mid3l_search(tl, pgno);
5742 if (x <= tl[0].mid && tl[x].mid == pgno) {
5743 if (x != tl[0].mid && tl[x+1].mid == pg0)
5745 /* check for overflow size */
5746 p = (MDB_page *)((char *)tl[x].mptr + rem * env->me_psize);
5747 if (IS_OVERFLOW(p) && p->mp_pages + rem > tl[x].mcnt) {
5748 id3.mcnt = p->mp_pages + rem;
5749 len = id3.mcnt * env->me_psize;
5750 SET_OFF(off, pgno * env->me_psize);
5751 MAP(rc, env, id3.mptr, len, off);
5754 /* check for local-only page */
5756 mdb_tassert(txn, tl[x].mid != pg0);
5757 /* hope there's room to insert this locally.
5758 * setting mid here tells later code to just insert
5759 * this id3 instead of searching for a match.
5764 /* ignore the mapping we got from env, use new one */
5765 tl[x].mptr = id3.mptr;
5766 tl[x].mcnt = id3.mcnt;
5767 /* if no active ref, see if we can replace in env */
5770 pthread_mutex_lock(&env->me_rpmutex);
5771 i = mdb_mid3l_search(el, tl[x].mid);
5772 if (el[i].mref == 1) {
5773 /* just us, replace it */
5774 munmap(el[i].mptr, el[i].mcnt * env->me_psize);
5775 el[i].mptr = tl[x].mptr;
5776 el[i].mcnt = tl[x].mcnt;
5778 /* there are others, remove ourself */
5781 pthread_mutex_unlock(&env->me_rpmutex);
5785 id3.mptr = tl[x].mptr;
5786 id3.mcnt = tl[x].mcnt;
5792 if (tl[0].mid >= MDB_TRPAGE_MAX - txn->mt_rpcheck) {
5794 /* purge unref'd pages from our list and unref in env */
5795 pthread_mutex_lock(&env->me_rpmutex);
5798 for (i=1; i<=tl[0].mid; i++) {
5801 /* tmp overflow pages don't go to env */
5802 if (tl[i].mid & (MDB_RPAGE_CHUNK-1)) {
5803 munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
5806 x = mdb_mid3l_search(el, tl[i].mid);
5810 pthread_mutex_unlock(&env->me_rpmutex);
5812 /* we didn't find any unref'd chunks.
5813 * if we're out of room, fail.
5815 if (tl[0].mid >= MDB_TRPAGE_MAX)
5816 return MDB_TXN_FULL;
5817 /* otherwise, raise threshold for next time around
5820 txn->mt_rpcheck /= 2;
5822 /* we found some unused; consolidate the list */
5823 for (i=y+1; i<= tl[0].mid; i++)
5827 /* decrease the check threshold toward its original value */
5828 if (!txn->mt_rpcheck)
5829 txn->mt_rpcheck = 1;
5830 while (txn->mt_rpcheck < tl[0].mid && txn->mt_rpcheck < MDB_TRPAGE_SIZE/2)
5831 txn->mt_rpcheck *= 2;
5834 if (tl[0].mid < MDB_TRPAGE_SIZE) {
5838 /* don't map past last written page in read-only envs */
5839 if ((env->me_flags & MDB_RDONLY) && pgno + MDB_RPAGE_CHUNK-1 > txn->mt_last_pgno)
5840 id3.mcnt = txn->mt_last_pgno + 1 - pgno;
5842 id3.mcnt = MDB_RPAGE_CHUNK;
5843 len = id3.mcnt * env->me_psize;
5846 /* search for page in env */
5847 pthread_mutex_lock(&env->me_rpmutex);
5848 x = mdb_mid3l_search(el, pgno);
5849 if (x <= el[0].mid && el[x].mid == pgno) {
5850 id3.mptr = el[x].mptr;
5851 id3.mcnt = el[x].mcnt;
5852 /* check for overflow size */
5853 p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
5854 if (IS_OVERFLOW(p) && p->mp_pages + rem > id3.mcnt) {
5855 id3.mcnt = p->mp_pages + rem;
5856 len = id3.mcnt * env->me_psize;
5857 SET_OFF(off, pgno * env->me_psize);
5858 MAP(rc, env, id3.mptr, len, off);
5862 munmap(el[x].mptr, env->me_psize * el[x].mcnt);
5863 el[x].mptr = id3.mptr;
5864 el[x].mcnt = id3.mcnt;
5867 pthread_mutex_unlock(&env->me_rpmutex);
5872 pthread_mutex_unlock(&env->me_rpmutex);
5875 if (el[0].mid >= MDB_ERPAGE_MAX - env->me_rpcheck) {
5876 /* purge unref'd pages */
5878 for (i=1; i<=el[0].mid; i++) {
5881 munmap(el[i].mptr, env->me_psize * el[i].mcnt);
5886 /* see if we can unref some local pages */
5891 if (el[0].mid >= MDB_ERPAGE_MAX) {
5892 pthread_mutex_unlock(&env->me_rpmutex);
5893 return MDB_MAP_FULL;
5895 env->me_rpcheck /= 2;
5897 for (i=y+1; i<= el[0].mid; i++)
5901 if (!env->me_rpcheck)
5902 env->me_rpcheck = 1;
5903 while (env->me_rpcheck < el[0].mid && env->me_rpcheck < MDB_ERPAGE_SIZE/2)
5904 env->me_rpcheck *= 2;
5907 SET_OFF(off, pgno * env->me_psize);
5908 MAP(rc, env, id3.mptr, len, off);
5911 pthread_mutex_unlock(&env->me_rpmutex);
5914 /* check for overflow size */
5915 p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
5916 if (IS_OVERFLOW(p) && p->mp_pages + rem > id3.mcnt) {
5917 id3.mcnt = p->mp_pages + rem;
5918 munmap(id3.mptr, len);
5919 len = id3.mcnt * env->me_psize;
5920 MAP(rc, env, id3.mptr, len, off);
5924 mdb_mid3l_insert(el, &id3);
5925 pthread_mutex_unlock(&env->me_rpmutex);
5927 mdb_mid3l_insert(tl, &id3);
5929 return MDB_TXN_FULL;
5932 p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
5933 #if MDB_DEBUG /* we don't need this check any more */
5934 if (IS_OVERFLOW(p)) {
5935 mdb_tassert(txn, p->mp_pages + rem <= id3.mcnt);
5943 /** Find the address of the page corresponding to a given page number.
5944 * @param[in] mc the cursor accessing the page.
5945 * @param[in] pgno the page number for the page to retrieve.
5946 * @param[out] ret address of a pointer where the page's address will be stored.
5947 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
5948 * @return 0 on success, non-zero on failure.
5951 mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **ret, int *lvl)
5953 MDB_txn *txn = mc->mc_txn;
5955 MDB_env *env = txn->mt_env;
5960 if (! (mc->mc_flags & (C_ORIG_RDONLY|C_WRITEMAP))) {
5964 MDB_ID2L dl = tx2->mt_u.dirty_list;
5966 /* Spilled pages were dirtied in this txn and flushed
5967 * because the dirty list got full. Bring this page
5968 * back in from the map (but don't unspill it here,
5969 * leave that unless page_touch happens again).
5971 if (tx2->mt_spill_pgs) {
5972 MDB_ID pn = pgno << 1;
5973 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
5974 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
5976 int rc = mdb_rpage_get(txn, pgno, &p);
5980 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5986 unsigned x = mdb_mid2l_search(dl, pgno);
5987 if (x <= dl[0].mid && dl[x].mid == pgno) {
5993 } while ((tx2 = tx2->mt_parent) != NULL);
5996 if (pgno < txn->mt_next_pgno) {
6000 int rc = mdb_rpage_get(txn, pgno, &p);
6005 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
6008 DPRINTF(("page %"Y"u not found", pgno));
6009 txn->mt_flags |= MDB_TXN_ERROR;
6010 return MDB_PAGE_NOTFOUND;
6020 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
6021 * The cursor is at the root page, set up the rest of it.
6024 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
6026 MDB_page *mp = mc->mc_pg[mc->mc_top];
6030 while (IS_BRANCH(mp)) {
6034 DPRINTF(("branch page %"Y"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
6035 /* Don't assert on branch pages in the FreeDB. We can get here
6036 * while in the process of rebalancing a FreeDB branch page; we must
6037 * let that proceed. ITS#8336
6039 mdb_cassert(mc, !mc->mc_dbi || NUMKEYS(mp) > 1);
6040 DPRINTF(("found index 0 to page %"Y"u", NODEPGNO(NODEPTR(mp, 0))));
6042 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
6044 if (flags & MDB_PS_LAST)
6045 i = NUMKEYS(mp) - 1;
6048 node = mdb_node_search(mc, key, &exact);
6050 i = NUMKEYS(mp) - 1;
6052 i = mc->mc_ki[mc->mc_top];
6054 mdb_cassert(mc, i > 0);
6058 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
6061 mdb_cassert(mc, i < NUMKEYS(mp));
6062 node = NODEPTR(mp, i);
6064 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
6067 mc->mc_ki[mc->mc_top] = i;
6068 if ((rc = mdb_cursor_push(mc, mp)))
6071 if (flags & MDB_PS_MODIFY) {
6072 if ((rc = mdb_page_touch(mc)) != 0)
6074 mp = mc->mc_pg[mc->mc_top];
6079 DPRINTF(("internal error, index points to a %02X page!?",
6081 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6082 return MDB_CORRUPTED;
6085 DPRINTF(("found leaf page %"Y"u for key [%s]", mp->mp_pgno,
6086 key ? DKEY(key) : "null"));
6087 mc->mc_flags |= C_INITIALIZED;
6088 mc->mc_flags &= ~C_EOF;
6093 /** Search for the lowest key under the current branch page.
6094 * This just bypasses a NUMKEYS check in the current page
6095 * before calling mdb_page_search_root(), because the callers
6096 * are all in situations where the current page is known to
6100 mdb_page_search_lowest(MDB_cursor *mc)
6102 MDB_page *mp = mc->mc_pg[mc->mc_top];
6103 MDB_node *node = NODEPTR(mp, 0);
6106 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
6109 mc->mc_ki[mc->mc_top] = 0;
6110 if ((rc = mdb_cursor_push(mc, mp)))
6112 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
6115 /** Search for the page a given key should be in.
6116 * Push it and its parent pages on the cursor stack.
6117 * @param[in,out] mc the cursor for this operation.
6118 * @param[in] key the key to search for, or NULL for first/last page.
6119 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
6120 * are touched (updated with new page numbers).
6121 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
6122 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
6123 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
6124 * @return 0 on success, non-zero on failure.
6127 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
6132 /* Make sure the txn is still viable, then find the root from
6133 * the txn's db table and set it as the root of the cursor's stack.
6135 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED) {
6136 DPUTS("transaction may not be used now");
6139 /* Make sure we're using an up-to-date root */
6140 if (*mc->mc_dbflag & DB_STALE) {
6142 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
6144 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
6145 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
6152 MDB_node *leaf = mdb_node_search(&mc2,
6153 &mc->mc_dbx->md_name, &exact);
6155 return MDB_NOTFOUND;
6156 if ((leaf->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
6157 return MDB_INCOMPATIBLE; /* not a named DB */
6158 rc = mdb_node_read(&mc2, leaf, &data);
6161 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
6163 /* The txn may not know this DBI, or another process may
6164 * have dropped and recreated the DB with other flags.
6166 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
6167 return MDB_INCOMPATIBLE;
6168 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
6170 *mc->mc_dbflag &= ~DB_STALE;
6172 root = mc->mc_db->md_root;
6174 if (root == P_INVALID) { /* Tree is empty. */
6175 DPUTS("tree is empty");
6176 return MDB_NOTFOUND;
6180 mdb_cassert(mc, root > 1);
6181 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root) {
6184 MDB_PAGE_UNREF(mc->mc_txn, mc->mc_pg[0]);
6186 if ((rc = mdb_page_get(mc, root, &mc->mc_pg[0], NULL)) != 0)
6193 for (i=1; i<mc->mc_snum; i++)
6194 MDB_PAGE_UNREF(mc->mc_txn, mc->mc_pg[i]);
6200 DPRINTF(("db %d root page %"Y"u has flags 0x%X",
6201 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
6203 if (flags & MDB_PS_MODIFY) {
6204 if ((rc = mdb_page_touch(mc)))
6208 if (flags & MDB_PS_ROOTONLY)
6211 return mdb_page_search_root(mc, key, flags);
6215 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
6217 MDB_txn *txn = mc->mc_txn;
6218 pgno_t pg = mp->mp_pgno;
6219 unsigned x = 0, ovpages = mp->mp_pages;
6220 MDB_env *env = txn->mt_env;
6221 MDB_IDL sl = txn->mt_spill_pgs;
6222 MDB_ID pn = pg << 1;
6225 DPRINTF(("free ov page %"Y"u (%d)", pg, ovpages));
6226 /* If the page is dirty or on the spill list we just acquired it,
6227 * so we should give it back to our current free list, if any.
6228 * Otherwise put it onto the list of pages we freed in this txn.
6230 * Won't create me_pghead: me_pglast must be inited along with it.
6231 * Unsupported in nested txns: They would need to hide the page
6232 * range in ancestor txns' dirty and spilled lists.
6234 if (env->me_pghead &&
6236 ((mp->mp_flags & P_DIRTY) ||
6237 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
6241 MDB_ID2 *dl, ix, iy;
6242 rc = mdb_midl_need(&env->me_pghead, ovpages);
6245 if (!(mp->mp_flags & P_DIRTY)) {
6246 /* This page is no longer spilled */
6253 /* Remove from dirty list */
6254 dl = txn->mt_u.dirty_list;
6256 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
6262 mdb_cassert(mc, x > 1);
6264 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
6265 txn->mt_flags |= MDB_TXN_ERROR;
6266 return MDB_CORRUPTED;
6269 txn->mt_dirty_room++;
6270 if (!(env->me_flags & MDB_WRITEMAP))
6271 mdb_dpage_free(env, mp);
6273 /* Insert in me_pghead */
6274 mop = env->me_pghead;
6275 j = mop[0] + ovpages;
6276 for (i = mop[0]; i && mop[i] < pg; i--)
6282 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
6286 mc->mc_db->md_overflow_pages -= ovpages;
6290 /** Return the data associated with a given node.
6291 * @param[in] mc The cursor for this operation.
6292 * @param[in] leaf The node being read.
6293 * @param[out] data Updated to point to the node's data.
6294 * @return 0 on success, non-zero on failure.
6297 mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data)
6299 MDB_page *omp; /* overflow page */
6305 MDB_PAGE_UNREF(mc->mc_txn, mc->mc_ovpg);
6309 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6310 data->mv_size = NODEDSZ(leaf);
6311 data->mv_data = NODEDATA(leaf);
6315 /* Read overflow data.
6317 data->mv_size = NODEDSZ(leaf);
6318 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
6319 if ((rc = mdb_page_get(mc, pgno, &omp, NULL)) != 0) {
6320 DPRINTF(("read overflow page %"Y"u failed", pgno));
6323 data->mv_data = METADATA(omp);
6332 mdb_get(MDB_txn *txn, MDB_dbi dbi,
6333 MDB_val *key, MDB_val *data)
6340 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
6342 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
6345 if (txn->mt_flags & MDB_TXN_BLOCKED)
6348 mdb_cursor_init(&mc, txn, dbi, &mx);
6349 rc = mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
6352 /* unref all the pages - caller must copy the data
6353 * before doing anything else
6355 mdb_cursor_unref(&mc);
6361 /** Find a sibling for a page.
6362 * Replaces the page at the top of the cursor's stack with the
6363 * specified sibling, if one exists.
6364 * @param[in] mc The cursor for this operation.
6365 * @param[in] move_right Non-zero if the right sibling is requested,
6366 * otherwise the left sibling.
6367 * @return 0 on success, non-zero on failure.
6370 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
6379 if (mc->mc_snum < 2) {
6380 return MDB_NOTFOUND; /* root has no siblings */
6384 op = mc->mc_pg[mc->mc_top];
6387 DPRINTF(("parent page is page %"Y"u, index %u",
6388 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
6390 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6391 : (mc->mc_ki[mc->mc_top] == 0)) {
6392 DPRINTF(("no more keys left, moving to %s sibling",
6393 move_right ? "right" : "left"));
6394 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
6395 /* undo cursor_pop before returning */
6402 mc->mc_ki[mc->mc_top]++;
6404 mc->mc_ki[mc->mc_top]--;
6405 DPRINTF(("just moving to %s index key %u",
6406 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
6408 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
6410 MDB_PAGE_UNREF(mc->mc_txn, op);
6412 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6413 if ((rc = mdb_page_get(mc, NODEPGNO(indx), &mp, NULL)) != 0) {
6414 /* mc will be inconsistent if caller does mc_snum++ as above */
6415 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
6419 mdb_cursor_push(mc, mp);
6421 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
6426 /** Move the cursor to the next data item. */
6428 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
6434 if ((mc->mc_flags & C_EOF) ||
6435 ((mc->mc_flags & C_DEL) && op == MDB_NEXT_DUP)) {
6436 return MDB_NOTFOUND;
6438 if (!(mc->mc_flags & C_INITIALIZED))
6439 return mdb_cursor_first(mc, key, data);
6441 mp = mc->mc_pg[mc->mc_top];
6443 if (mc->mc_db->md_flags & MDB_DUPSORT) {
6444 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6445 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6446 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
6447 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
6448 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
6449 if (rc == MDB_SUCCESS)
6450 MDB_GET_KEY(leaf, key);
6456 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6457 mdb_cursor_unref(&mc->mc_xcursor->mx_cursor);
6462 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6463 if (op == MDB_NEXT_DUP)
6464 return MDB_NOTFOUND;
6468 DPRINTF(("cursor_next: top page is %"Y"u in cursor %p",
6469 mdb_dbg_pgno(mp), (void *) mc));
6470 if (mc->mc_flags & C_DEL) {
6471 mc->mc_flags ^= C_DEL;
6475 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
6476 DPUTS("=====> move to next sibling page");
6477 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
6478 mc->mc_flags |= C_EOF;
6481 mp = mc->mc_pg[mc->mc_top];
6482 DPRINTF(("next page is %"Y"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
6484 mc->mc_ki[mc->mc_top]++;
6487 DPRINTF(("==> cursor points to page %"Y"u with %u keys, key index %u",
6488 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
6491 key->mv_size = mc->mc_db->md_pad;
6492 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6496 mdb_cassert(mc, IS_LEAF(mp));
6497 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6499 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6500 mdb_xcursor_init1(mc, leaf);
6503 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6506 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6507 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6508 if (rc != MDB_SUCCESS)
6513 MDB_GET_KEY(leaf, key);
6517 /** Move the cursor to the previous data item. */
6519 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
6525 if (!(mc->mc_flags & C_INITIALIZED)) {
6526 rc = mdb_cursor_last(mc, key, data);
6529 mc->mc_ki[mc->mc_top]++;
6532 mp = mc->mc_pg[mc->mc_top];
6534 if (mc->mc_db->md_flags & MDB_DUPSORT) {
6535 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6536 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6537 if (op == MDB_PREV || op == MDB_PREV_DUP) {
6538 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
6539 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
6540 if (rc == MDB_SUCCESS) {
6541 MDB_GET_KEY(leaf, key);
6542 mc->mc_flags &= ~C_EOF;
6549 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6550 mdb_cursor_unref(&mc->mc_xcursor->mx_cursor);
6555 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6556 if (op == MDB_PREV_DUP)
6557 return MDB_NOTFOUND;
6561 DPRINTF(("cursor_prev: top page is %"Y"u in cursor %p",
6562 mdb_dbg_pgno(mp), (void *) mc));
6564 mc->mc_flags &= ~(C_EOF|C_DEL);
6566 if (mc->mc_ki[mc->mc_top] == 0) {
6567 DPUTS("=====> move to prev sibling page");
6568 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
6571 mp = mc->mc_pg[mc->mc_top];
6572 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
6573 DPRINTF(("prev page is %"Y"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
6575 mc->mc_ki[mc->mc_top]--;
6577 mc->mc_flags &= ~C_EOF;
6579 DPRINTF(("==> cursor points to page %"Y"u with %u keys, key index %u",
6580 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
6583 key->mv_size = mc->mc_db->md_pad;
6584 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6588 mdb_cassert(mc, IS_LEAF(mp));
6589 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6591 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6592 mdb_xcursor_init1(mc, leaf);
6595 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6598 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6599 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
6600 if (rc != MDB_SUCCESS)
6605 MDB_GET_KEY(leaf, key);
6609 /** Set the cursor on a specific data item. */
6611 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6612 MDB_cursor_op op, int *exactp)
6616 MDB_node *leaf = NULL;
6619 if (key->mv_size == 0)
6620 return MDB_BAD_VALSIZE;
6623 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6625 /* See if we're already on the right page */
6626 if (mc->mc_flags & C_INITIALIZED) {
6629 mp = mc->mc_pg[mc->mc_top];
6631 mc->mc_ki[mc->mc_top] = 0;
6632 return MDB_NOTFOUND;
6634 if (mp->mp_flags & P_LEAF2) {
6635 nodekey.mv_size = mc->mc_db->md_pad;
6636 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
6638 leaf = NODEPTR(mp, 0);
6639 MDB_GET_KEY2(leaf, nodekey);
6641 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6643 /* Probably happens rarely, but first node on the page
6644 * was the one we wanted.
6646 mc->mc_ki[mc->mc_top] = 0;
6653 unsigned int nkeys = NUMKEYS(mp);
6655 if (mp->mp_flags & P_LEAF2) {
6656 nodekey.mv_data = LEAF2KEY(mp,
6657 nkeys-1, nodekey.mv_size);
6659 leaf = NODEPTR(mp, nkeys-1);
6660 MDB_GET_KEY2(leaf, nodekey);
6662 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6664 /* last node was the one we wanted */
6665 mc->mc_ki[mc->mc_top] = nkeys-1;
6671 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
6672 /* This is definitely the right page, skip search_page */
6673 if (mp->mp_flags & P_LEAF2) {
6674 nodekey.mv_data = LEAF2KEY(mp,
6675 mc->mc_ki[mc->mc_top], nodekey.mv_size);
6677 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6678 MDB_GET_KEY2(leaf, nodekey);
6680 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6682 /* current node was the one we wanted */
6692 /* If any parents have right-sibs, search.
6693 * Otherwise, there's nothing further.
6695 for (i=0; i<mc->mc_top; i++)
6697 NUMKEYS(mc->mc_pg[i])-1)
6699 if (i == mc->mc_top) {
6700 /* There are no other pages */
6701 mc->mc_ki[mc->mc_top] = nkeys;
6702 return MDB_NOTFOUND;
6706 /* There are no other pages */
6707 mc->mc_ki[mc->mc_top] = 0;
6708 if (op == MDB_SET_RANGE && !exactp) {
6712 return MDB_NOTFOUND;
6718 rc = mdb_page_search(mc, key, 0);
6719 if (rc != MDB_SUCCESS)
6722 mp = mc->mc_pg[mc->mc_top];
6723 mdb_cassert(mc, IS_LEAF(mp));
6726 leaf = mdb_node_search(mc, key, exactp);
6727 if (exactp != NULL && !*exactp) {
6728 /* MDB_SET specified and not an exact match. */
6729 return MDB_NOTFOUND;
6733 DPUTS("===> inexact leaf not found, goto sibling");
6734 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
6735 mc->mc_flags |= C_EOF;
6736 return rc; /* no entries matched */
6738 mp = mc->mc_pg[mc->mc_top];
6739 mdb_cassert(mc, IS_LEAF(mp));
6740 leaf = NODEPTR(mp, 0);
6744 mc->mc_flags |= C_INITIALIZED;
6745 mc->mc_flags &= ~C_EOF;
6748 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
6749 key->mv_size = mc->mc_db->md_pad;
6750 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6756 if (mc->mc_xcursor && mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6757 mdb_cursor_unref(&mc->mc_xcursor->mx_cursor);
6760 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6761 mdb_xcursor_init1(mc, leaf);
6764 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6765 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
6766 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6769 if (op == MDB_GET_BOTH) {
6775 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
6776 if (rc != MDB_SUCCESS)
6779 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
6782 if ((rc = mdb_node_read(mc, leaf, &olddata)) != MDB_SUCCESS)
6784 dcmp = mc->mc_dbx->md_dcmp;
6785 #if UINT_MAX < SIZE_MAX || defined(MDB_VL32)
6786 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(mdb_size_t))
6787 dcmp = mdb_cmp_clong;
6789 rc = dcmp(data, &olddata);
6791 if (op == MDB_GET_BOTH || rc > 0)
6792 return MDB_NOTFOUND;
6799 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6800 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6805 /* The key already matches in all other cases */
6806 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
6807 MDB_GET_KEY(leaf, key);
6808 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
6813 /** Move the cursor to the first item in the database. */
6815 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6820 if (mc->mc_xcursor) {
6822 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6823 mdb_cursor_unref(&mc->mc_xcursor->mx_cursor);
6826 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6829 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6830 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
6831 if (rc != MDB_SUCCESS)
6834 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6836 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
6837 mc->mc_flags |= C_INITIALIZED;
6838 mc->mc_flags &= ~C_EOF;
6840 mc->mc_ki[mc->mc_top] = 0;
6842 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6843 key->mv_size = mc->mc_db->md_pad;
6844 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
6849 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6850 mdb_xcursor_init1(mc, leaf);
6851 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6855 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6859 MDB_GET_KEY(leaf, key);
6863 /** Move the cursor to the last item in the database. */
6865 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6870 if (mc->mc_xcursor) {
6872 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6873 mdb_cursor_unref(&mc->mc_xcursor->mx_cursor);
6876 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6879 if (!(mc->mc_flags & C_EOF)) {
6881 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6882 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
6883 if (rc != MDB_SUCCESS)
6886 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6889 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
6890 mc->mc_flags |= C_INITIALIZED|C_EOF;
6891 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6893 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6894 key->mv_size = mc->mc_db->md_pad;
6895 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
6900 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6901 mdb_xcursor_init1(mc, leaf);
6902 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
6906 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6911 MDB_GET_KEY(leaf, key);
6916 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6921 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
6926 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
6930 case MDB_GET_CURRENT:
6931 if (!(mc->mc_flags & C_INITIALIZED)) {
6934 MDB_page *mp = mc->mc_pg[mc->mc_top];
6935 int nkeys = NUMKEYS(mp);
6936 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
6937 mc->mc_ki[mc->mc_top] = nkeys;
6943 key->mv_size = mc->mc_db->md_pad;
6944 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6946 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6947 MDB_GET_KEY(leaf, key);
6949 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6950 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
6952 rc = mdb_node_read(mc, leaf, data);
6959 case MDB_GET_BOTH_RANGE:
6964 if (mc->mc_xcursor == NULL) {
6965 rc = MDB_INCOMPATIBLE;
6975 rc = mdb_cursor_set(mc, key, data, op,
6976 op == MDB_SET_RANGE ? NULL : &exact);
6979 case MDB_GET_MULTIPLE:
6980 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
6984 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6985 rc = MDB_INCOMPATIBLE;
6989 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
6990 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
6993 case MDB_NEXT_MULTIPLE:
6998 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6999 rc = MDB_INCOMPATIBLE;
7002 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
7003 if (rc == MDB_SUCCESS) {
7004 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
7007 mx = &mc->mc_xcursor->mx_cursor;
7008 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
7010 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
7011 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
7017 case MDB_PREV_MULTIPLE:
7022 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7023 rc = MDB_INCOMPATIBLE;
7026 if (!(mc->mc_flags & C_INITIALIZED))
7027 rc = mdb_cursor_last(mc, key, data);
7030 if (rc == MDB_SUCCESS) {
7031 MDB_cursor *mx = &mc->mc_xcursor->mx_cursor;
7032 if (mx->mc_flags & C_INITIALIZED) {
7033 rc = mdb_cursor_sibling(mx, 0);
7034 if (rc == MDB_SUCCESS)
7043 case MDB_NEXT_NODUP:
7044 rc = mdb_cursor_next(mc, key, data, op);
7048 case MDB_PREV_NODUP:
7049 rc = mdb_cursor_prev(mc, key, data, op);
7052 rc = mdb_cursor_first(mc, key, data);
7055 mfunc = mdb_cursor_first;
7057 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
7061 if (mc->mc_xcursor == NULL) {
7062 rc = MDB_INCOMPATIBLE;
7066 MDB_node *leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7067 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7068 MDB_GET_KEY(leaf, key);
7069 rc = mdb_node_read(mc, leaf, data);
7073 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
7077 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
7080 rc = mdb_cursor_last(mc, key, data);
7083 mfunc = mdb_cursor_last;
7086 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
7091 if (mc->mc_flags & C_DEL)
7092 mc->mc_flags ^= C_DEL;
7097 /** Touch all the pages in the cursor stack. Set mc_top.
7098 * Makes sure all the pages are writable, before attempting a write operation.
7099 * @param[in] mc The cursor to operate on.
7102 mdb_cursor_touch(MDB_cursor *mc)
7104 int rc = MDB_SUCCESS;
7106 if (mc->mc_dbi >= CORE_DBS && !(*mc->mc_dbflag & DB_DIRTY)) {
7109 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
7111 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
7112 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
7115 *mc->mc_dbflag |= DB_DIRTY;
7120 rc = mdb_page_touch(mc);
7121 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
7122 mc->mc_top = mc->mc_snum-1;
7127 /** Do not spill pages to disk if txn is getting full, may fail instead */
7128 #define MDB_NOSPILL 0x8000
7131 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
7135 MDB_node *leaf = NULL;
7136 MDB_page *fp, *mp, *sub_root = NULL;
7138 MDB_val xdata, *rdata, dkey, olddata;
7140 int do_sub = 0, insert_key, insert_data;
7141 unsigned int mcount = 0, dcount = 0, nospill;
7144 unsigned int nflags;
7147 if (mc == NULL || key == NULL)
7150 env = mc->mc_txn->mt_env;
7152 /* Check this first so counter will always be zero on any
7155 if (flags & MDB_MULTIPLE) {
7156 dcount = data[1].mv_size;
7157 data[1].mv_size = 0;
7158 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
7159 return MDB_INCOMPATIBLE;
7162 nospill = flags & MDB_NOSPILL;
7163 flags &= ~MDB_NOSPILL;
7165 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
7166 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7168 if (key->mv_size-1 >= ENV_MAXKEY(env))
7169 return MDB_BAD_VALSIZE;
7171 #if SIZE_MAX > MAXDATASIZE
7172 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
7173 return MDB_BAD_VALSIZE;
7175 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
7176 return MDB_BAD_VALSIZE;
7179 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
7180 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
7184 if (flags == MDB_CURRENT) {
7185 if (!(mc->mc_flags & C_INITIALIZED))
7188 } else if (mc->mc_db->md_root == P_INVALID) {
7189 /* new database, cursor has nothing to point to */
7192 mc->mc_flags &= ~C_INITIALIZED;
7197 if (flags & MDB_APPEND) {
7199 rc = mdb_cursor_last(mc, &k2, &d2);
7201 rc = mc->mc_dbx->md_cmp(key, &k2);
7204 mc->mc_ki[mc->mc_top]++;
7206 /* new key is <= last key */
7211 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
7213 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
7214 DPRINTF(("duplicate key [%s]", DKEY(key)));
7216 return MDB_KEYEXIST;
7218 if (rc && rc != MDB_NOTFOUND)
7222 if (mc->mc_flags & C_DEL)
7223 mc->mc_flags ^= C_DEL;
7225 /* Cursor is positioned, check for room in the dirty list */
7227 if (flags & MDB_MULTIPLE) {
7229 xdata.mv_size = data->mv_size * dcount;
7233 if ((rc2 = mdb_page_spill(mc, key, rdata)))
7237 if (rc == MDB_NO_ROOT) {
7239 /* new database, write a root leaf page */
7240 DPUTS("allocating new root leaf page");
7241 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
7244 mdb_cursor_push(mc, np);
7245 mc->mc_db->md_root = np->mp_pgno;
7246 mc->mc_db->md_depth++;
7247 *mc->mc_dbflag |= DB_DIRTY;
7248 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
7250 np->mp_flags |= P_LEAF2;
7251 mc->mc_flags |= C_INITIALIZED;
7253 /* make sure all cursor pages are writable */
7254 rc2 = mdb_cursor_touch(mc);
7259 insert_key = insert_data = rc;
7261 /* The key does not exist */
7262 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
7263 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
7264 LEAFSIZE(key, data) > env->me_nodemax)
7266 /* Too big for a node, insert in sub-DB. Set up an empty
7267 * "old sub-page" for prep_subDB to expand to a full page.
7269 fp_flags = P_LEAF|P_DIRTY;
7271 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
7272 fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
7273 olddata.mv_size = PAGEHDRSZ;
7277 /* there's only a key anyway, so this is a no-op */
7278 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
7280 unsigned int ksize = mc->mc_db->md_pad;
7281 if (key->mv_size != ksize)
7282 return MDB_BAD_VALSIZE;
7283 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
7284 memcpy(ptr, key->mv_data, ksize);
7286 /* if overwriting slot 0 of leaf, need to
7287 * update branch key if there is a parent page
7289 if (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
7290 unsigned short dtop = 1;
7292 /* slot 0 is always an empty key, find real slot */
7293 while (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
7297 if (mc->mc_ki[mc->mc_top])
7298 rc2 = mdb_update_key(mc, key);
7309 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7310 olddata.mv_size = NODEDSZ(leaf);
7311 olddata.mv_data = NODEDATA(leaf);
7314 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
7315 /* Prepare (sub-)page/sub-DB to accept the new item,
7316 * if needed. fp: old sub-page or a header faking
7317 * it. mp: new (sub-)page. offset: growth in page
7318 * size. xdata: node data with new page or DB.
7320 unsigned i, offset = 0;
7321 mp = fp = xdata.mv_data = env->me_pbuf;
7322 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
7324 /* Was a single item before, must convert now */
7325 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7327 /* Just overwrite the current item */
7328 if (flags == MDB_CURRENT)
7330 dcmp = mc->mc_dbx->md_dcmp;
7331 #if UINT_MAX < SIZE_MAX || defined(MDB_VL32)
7332 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(mdb_size_t))
7333 dcmp = mdb_cmp_clong;
7335 /* does data match? */
7336 if (!dcmp(data, &olddata)) {
7337 if (flags & (MDB_NODUPDATA|MDB_APPENDDUP))
7338 return MDB_KEYEXIST;
7343 /* Back up original data item */
7344 dkey.mv_size = olddata.mv_size;
7345 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
7347 /* Make sub-page header for the dup items, with dummy body */
7348 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
7349 fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
7350 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
7351 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7352 fp->mp_flags |= P_LEAF2;
7353 fp->mp_pad = data->mv_size;
7354 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
7356 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
7357 (dkey.mv_size & 1) + (data->mv_size & 1);
7359 fp->mp_upper = xdata.mv_size - PAGEBASE;
7360 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
7361 } else if (leaf->mn_flags & F_SUBDATA) {
7362 /* Data is on sub-DB, just store it */
7363 flags |= F_DUPDATA|F_SUBDATA;
7366 /* Data is on sub-page */
7367 fp = olddata.mv_data;
7370 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7371 offset = EVEN(NODESIZE + sizeof(indx_t) +
7375 offset = fp->mp_pad;
7376 if (SIZELEFT(fp) < offset) {
7377 offset *= 4; /* space for 4 more */
7380 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
7382 fp->mp_flags |= P_DIRTY;
7383 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
7384 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
7388 xdata.mv_size = olddata.mv_size + offset;
7391 fp_flags = fp->mp_flags;
7392 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
7393 /* Too big for a sub-page, convert to sub-DB */
7394 fp_flags &= ~P_SUBP;
7396 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7397 fp_flags |= P_LEAF2;
7398 dummy.md_pad = fp->mp_pad;
7399 dummy.md_flags = MDB_DUPFIXED;
7400 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
7401 dummy.md_flags |= MDB_INTEGERKEY;
7407 dummy.md_branch_pages = 0;
7408 dummy.md_leaf_pages = 1;
7409 dummy.md_overflow_pages = 0;
7410 dummy.md_entries = NUMKEYS(fp);
7411 xdata.mv_size = sizeof(MDB_db);
7412 xdata.mv_data = &dummy;
7413 if ((rc = mdb_page_alloc(mc, 1, &mp)))
7415 offset = env->me_psize - olddata.mv_size;
7416 flags |= F_DUPDATA|F_SUBDATA;
7417 dummy.md_root = mp->mp_pgno;
7421 mp->mp_flags = fp_flags | P_DIRTY;
7422 mp->mp_pad = fp->mp_pad;
7423 mp->mp_lower = fp->mp_lower;
7424 mp->mp_upper = fp->mp_upper + offset;
7425 if (fp_flags & P_LEAF2) {
7426 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
7428 memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
7429 olddata.mv_size - fp->mp_upper - PAGEBASE);
7430 for (i=0; i<NUMKEYS(fp); i++)
7431 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
7439 mdb_node_del(mc, 0);
7443 /* LMDB passes F_SUBDATA in 'flags' to write a DB record */
7444 if ((leaf->mn_flags ^ flags) & F_SUBDATA)
7445 return MDB_INCOMPATIBLE;
7446 /* overflow page overwrites need special handling */
7447 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7450 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
7452 memcpy(&pg, olddata.mv_data, sizeof(pg));
7453 if ((rc2 = mdb_page_get(mc, pg, &omp, &level)) != 0)
7455 ovpages = omp->mp_pages;
7457 /* Is the ov page large enough? */
7458 if (ovpages >= dpages) {
7459 if (!(omp->mp_flags & P_DIRTY) &&
7460 (level || (env->me_flags & MDB_WRITEMAP)))
7462 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
7465 level = 0; /* dirty in this txn or clean */
7468 if (omp->mp_flags & P_DIRTY) {
7469 /* yes, overwrite it. Note in this case we don't
7470 * bother to try shrinking the page if the new data
7471 * is smaller than the overflow threshold.
7474 /* It is writable only in a parent txn */
7475 size_t sz = (size_t) env->me_psize * ovpages, off;
7476 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
7482 /* Note - this page is already counted in parent's dirty_room */
7483 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
7484 mdb_cassert(mc, rc2 == 0);
7485 /* Currently we make the page look as with put() in the
7486 * parent txn, in case the user peeks at MDB_RESERVEd
7487 * or unused parts. Some users treat ovpages specially.
7489 if (!(flags & MDB_RESERVE)) {
7490 /* Skip the part where LMDB will put *data.
7491 * Copy end of page, adjusting alignment so
7492 * compiler may copy words instead of bytes.
7494 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
7495 memcpy((size_t *)((char *)np + off),
7496 (size_t *)((char *)omp + off), sz - off);
7499 memcpy(np, omp, sz); /* Copy beginning of page */
7502 SETDSZ(leaf, data->mv_size);
7503 if (F_ISSET(flags, MDB_RESERVE))
7504 data->mv_data = METADATA(omp);
7506 memcpy(METADATA(omp), data->mv_data, data->mv_size);
7510 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
7512 } else if (data->mv_size == olddata.mv_size) {
7513 /* same size, just replace it. Note that we could
7514 * also reuse this node if the new data is smaller,
7515 * but instead we opt to shrink the node in that case.
7517 if (F_ISSET(flags, MDB_RESERVE))
7518 data->mv_data = olddata.mv_data;
7519 else if (!(mc->mc_flags & C_SUB))
7520 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
7522 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
7527 mdb_node_del(mc, 0);
7533 nflags = flags & NODE_ADD_FLAGS;
7534 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
7535 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
7536 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
7537 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
7539 nflags |= MDB_SPLIT_REPLACE;
7540 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
7542 /* There is room already in this leaf page. */
7543 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
7545 /* Adjust other cursors pointing to mp */
7546 MDB_cursor *m2, *m3;
7547 MDB_dbi dbi = mc->mc_dbi;
7548 unsigned i = mc->mc_top;
7549 MDB_page *mp = mc->mc_pg[i];
7551 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7552 if (mc->mc_flags & C_SUB)
7553 m3 = &m2->mc_xcursor->mx_cursor;
7556 if (m3 == mc || m3->mc_snum < mc->mc_snum || m3->mc_pg[i] != mp) continue;
7557 if (m3->mc_ki[i] >= mc->mc_ki[i] && insert_key) {
7560 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
7561 MDB_node *n2 = NODEPTR(mp, m3->mc_ki[i]);
7562 if ((n2->mn_flags & (F_SUBDATA|F_DUPDATA)) == F_DUPDATA)
7563 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
7569 if (rc == MDB_SUCCESS) {
7570 /* Now store the actual data in the child DB. Note that we're
7571 * storing the user data in the keys field, so there are strict
7572 * size limits on dupdata. The actual data fields of the child
7573 * DB are all zero size.
7576 int xflags, new_dupdata;
7581 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7582 if (flags & MDB_CURRENT) {
7583 xflags = MDB_CURRENT|MDB_NOSPILL;
7585 mdb_xcursor_init1(mc, leaf);
7586 xflags = (flags & MDB_NODUPDATA) ?
7587 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
7590 mc->mc_xcursor->mx_cursor.mc_pg[0] = sub_root;
7591 new_dupdata = (int)dkey.mv_size;
7592 /* converted, write the original data first */
7594 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
7597 /* we've done our job */
7600 if (!(leaf->mn_flags & F_SUBDATA) || sub_root) {
7601 /* Adjust other cursors pointing to mp */
7603 MDB_xcursor *mx = mc->mc_xcursor;
7604 unsigned i = mc->mc_top;
7605 MDB_page *mp = mc->mc_pg[i];
7606 int nkeys = NUMKEYS(mp);
7608 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
7609 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
7610 if (!(m2->mc_flags & C_INITIALIZED)) continue;
7611 if (m2->mc_pg[i] == mp) {
7612 if (m2->mc_ki[i] == mc->mc_ki[i]) {
7613 mdb_xcursor_init2(m2, mx, new_dupdata);
7614 } else if (!insert_key && m2->mc_ki[i] < nkeys) {
7615 MDB_node *n2 = NODEPTR(mp, m2->mc_ki[i]);
7616 if ((n2->mn_flags & (F_SUBDATA|F_DUPDATA)) == F_DUPDATA)
7617 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
7622 ecount = mc->mc_xcursor->mx_db.md_entries;
7623 if (flags & MDB_APPENDDUP)
7624 xflags |= MDB_APPEND;
7625 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
7626 if (flags & F_SUBDATA) {
7627 void *db = NODEDATA(leaf);
7628 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
7630 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
7632 /* Increment count unless we just replaced an existing item. */
7634 mc->mc_db->md_entries++;
7636 /* Invalidate txn if we created an empty sub-DB */
7639 /* If we succeeded and the key didn't exist before,
7640 * make sure the cursor is marked valid.
7642 mc->mc_flags |= C_INITIALIZED;
7644 if (flags & MDB_MULTIPLE) {
7647 /* let caller know how many succeeded, if any */
7648 data[1].mv_size = mcount;
7649 if (mcount < dcount) {
7650 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
7651 insert_key = insert_data = 0;
7658 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
7661 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7666 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
7672 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
7673 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7675 if (!(mc->mc_flags & C_INITIALIZED))
7678 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
7679 return MDB_NOTFOUND;
7681 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
7684 rc = mdb_cursor_touch(mc);
7688 mp = mc->mc_pg[mc->mc_top];
7691 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7693 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7694 if (flags & MDB_NODUPDATA) {
7695 /* mdb_cursor_del0() will subtract the final entry */
7696 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
7697 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
7699 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
7700 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
7702 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
7705 /* If sub-DB still has entries, we're done */
7706 if (mc->mc_xcursor->mx_db.md_entries) {
7707 if (leaf->mn_flags & F_SUBDATA) {
7708 /* update subDB info */
7709 void *db = NODEDATA(leaf);
7710 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
7713 /* shrink fake page */
7714 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
7715 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7716 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
7717 /* fix other sub-DB cursors pointed at fake pages on this page */
7718 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
7719 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
7720 if (!(m2->mc_flags & C_INITIALIZED)) continue;
7721 if (m2->mc_pg[mc->mc_top] == mp) {
7722 if (m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top]) {
7723 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
7725 MDB_node *n2 = NODEPTR(mp, m2->mc_ki[mc->mc_top]);
7726 if (!(n2->mn_flags & F_SUBDATA))
7727 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
7732 mc->mc_db->md_entries--;
7735 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
7737 /* otherwise fall thru and delete the sub-DB */
7740 if (leaf->mn_flags & F_SUBDATA) {
7741 /* add all the child DB's pages to the free list */
7742 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
7747 /* LMDB passes F_SUBDATA in 'flags' to delete a DB record */
7748 else if ((leaf->mn_flags ^ flags) & F_SUBDATA) {
7749 rc = MDB_INCOMPATIBLE;
7753 /* add overflow pages to free list */
7754 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7758 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
7759 if ((rc = mdb_page_get(mc, pg, &omp, NULL)) ||
7760 (rc = mdb_ovpage_free(mc, omp)))
7765 return mdb_cursor_del0(mc);
7768 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7772 /** Allocate and initialize new pages for a database.
7773 * @param[in] mc a cursor on the database being added to.
7774 * @param[in] flags flags defining what type of page is being allocated.
7775 * @param[in] num the number of pages to allocate. This is usually 1,
7776 * unless allocating overflow pages for a large record.
7777 * @param[out] mp Address of a page, or NULL on failure.
7778 * @return 0 on success, non-zero on failure.
7781 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
7786 if ((rc = mdb_page_alloc(mc, num, &np)))
7788 DPRINTF(("allocated new mpage %"Y"u, page size %u",
7789 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
7790 np->mp_flags = flags | P_DIRTY;
7791 np->mp_lower = (PAGEHDRSZ-PAGEBASE);
7792 np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
7795 mc->mc_db->md_branch_pages++;
7796 else if (IS_LEAF(np))
7797 mc->mc_db->md_leaf_pages++;
7798 else if (IS_OVERFLOW(np)) {
7799 mc->mc_db->md_overflow_pages += num;
7807 /** Calculate the size of a leaf node.
7808 * The size depends on the environment's page size; if a data item
7809 * is too large it will be put onto an overflow page and the node
7810 * size will only include the key and not the data. Sizes are always
7811 * rounded up to an even number of bytes, to guarantee 2-byte alignment
7812 * of the #MDB_node headers.
7813 * @param[in] env The environment handle.
7814 * @param[in] key The key for the node.
7815 * @param[in] data The data for the node.
7816 * @return The number of bytes needed to store the node.
7819 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
7823 sz = LEAFSIZE(key, data);
7824 if (sz > env->me_nodemax) {
7825 /* put on overflow page */
7826 sz -= data->mv_size - sizeof(pgno_t);
7829 return EVEN(sz + sizeof(indx_t));
7832 /** Calculate the size of a branch node.
7833 * The size should depend on the environment's page size but since
7834 * we currently don't support spilling large keys onto overflow
7835 * pages, it's simply the size of the #MDB_node header plus the
7836 * size of the key. Sizes are always rounded up to an even number
7837 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
7838 * @param[in] env The environment handle.
7839 * @param[in] key The key for the node.
7840 * @return The number of bytes needed to store the node.
7843 mdb_branch_size(MDB_env *env, MDB_val *key)
7848 if (sz > env->me_nodemax) {
7849 /* put on overflow page */
7850 /* not implemented */
7851 /* sz -= key->size - sizeof(pgno_t); */
7854 return sz + sizeof(indx_t);
7857 /** Add a node to the page pointed to by the cursor.
7858 * @param[in] mc The cursor for this operation.
7859 * @param[in] indx The index on the page where the new node should be added.
7860 * @param[in] key The key for the new node.
7861 * @param[in] data The data for the new node, if any.
7862 * @param[in] pgno The page number, if adding a branch node.
7863 * @param[in] flags Flags for the node.
7864 * @return 0 on success, non-zero on failure. Possible errors are:
7866 * <li>ENOMEM - failed to allocate overflow pages for the node.
7867 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
7868 * should never happen since all callers already calculate the
7869 * page's free space before calling this function.
7873 mdb_node_add(MDB_cursor *mc, indx_t indx,
7874 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
7877 size_t node_size = NODESIZE;
7881 MDB_page *mp = mc->mc_pg[mc->mc_top];
7882 MDB_page *ofp = NULL; /* overflow page */
7886 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
7888 DPRINTF(("add to %s %spage %"Y"u index %i, data size %"Z"u key size %"Z"u [%s]",
7889 IS_LEAF(mp) ? "leaf" : "branch",
7890 IS_SUBP(mp) ? "sub-" : "",
7891 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
7892 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
7895 /* Move higher keys up one slot. */
7896 int ksize = mc->mc_db->md_pad, dif;
7897 char *ptr = LEAF2KEY(mp, indx, ksize);
7898 dif = NUMKEYS(mp) - indx;
7900 memmove(ptr+ksize, ptr, dif*ksize);
7901 /* insert new key */
7902 memcpy(ptr, key->mv_data, ksize);
7904 /* Just using these for counting */
7905 mp->mp_lower += sizeof(indx_t);
7906 mp->mp_upper -= ksize - sizeof(indx_t);
7910 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
7912 node_size += key->mv_size;
7914 mdb_cassert(mc, key && data);
7915 if (F_ISSET(flags, F_BIGDATA)) {
7916 /* Data already on overflow page. */
7917 node_size += sizeof(pgno_t);
7918 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
7919 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
7921 /* Put data on overflow page. */
7922 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
7923 data->mv_size, node_size+data->mv_size));
7924 node_size = EVEN(node_size + sizeof(pgno_t));
7925 if ((ssize_t)node_size > room)
7927 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
7929 DPRINTF(("allocated overflow page %"Y"u", ofp->mp_pgno));
7933 node_size += data->mv_size;
7936 node_size = EVEN(node_size);
7937 if ((ssize_t)node_size > room)
7941 /* Move higher pointers up one slot. */
7942 for (i = NUMKEYS(mp); i > indx; i--)
7943 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
7945 /* Adjust free space offsets. */
7946 ofs = mp->mp_upper - node_size;
7947 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
7948 mp->mp_ptrs[indx] = ofs;
7950 mp->mp_lower += sizeof(indx_t);
7952 /* Write the node data. */
7953 node = NODEPTR(mp, indx);
7954 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
7955 node->mn_flags = flags;
7957 SETDSZ(node,data->mv_size);
7962 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7965 ndata = NODEDATA(node);
7967 if (F_ISSET(flags, F_BIGDATA))
7968 memcpy(ndata, data->mv_data, sizeof(pgno_t));
7969 else if (F_ISSET(flags, MDB_RESERVE))
7970 data->mv_data = ndata;
7972 memcpy(ndata, data->mv_data, data->mv_size);
7974 memcpy(ndata, &ofp->mp_pgno, sizeof(pgno_t));
7975 ndata = METADATA(ofp);
7976 if (F_ISSET(flags, MDB_RESERVE))
7977 data->mv_data = ndata;
7979 memcpy(ndata, data->mv_data, data->mv_size);
7986 DPRINTF(("not enough room in page %"Y"u, got %u ptrs",
7987 mdb_dbg_pgno(mp), NUMKEYS(mp)));
7988 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
7989 DPRINTF(("node size = %"Z"u", node_size));
7990 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7991 return MDB_PAGE_FULL;
7994 /** Delete the specified node from a page.
7995 * @param[in] mc Cursor pointing to the node to delete.
7996 * @param[in] ksize The size of a node. Only used if the page is
7997 * part of a #MDB_DUPFIXED database.
8000 mdb_node_del(MDB_cursor *mc, int ksize)
8002 MDB_page *mp = mc->mc_pg[mc->mc_top];
8003 indx_t indx = mc->mc_ki[mc->mc_top];
8005 indx_t i, j, numkeys, ptr;
8009 DPRINTF(("delete node %u on %s page %"Y"u", indx,
8010 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
8011 numkeys = NUMKEYS(mp);
8012 mdb_cassert(mc, indx < numkeys);
8015 int x = numkeys - 1 - indx;
8016 base = LEAF2KEY(mp, indx, ksize);
8018 memmove(base, base + ksize, x * ksize);
8019 mp->mp_lower -= sizeof(indx_t);
8020 mp->mp_upper += ksize - sizeof(indx_t);
8024 node = NODEPTR(mp, indx);
8025 sz = NODESIZE + node->mn_ksize;
8027 if (F_ISSET(node->mn_flags, F_BIGDATA))
8028 sz += sizeof(pgno_t);
8030 sz += NODEDSZ(node);
8034 ptr = mp->mp_ptrs[indx];
8035 for (i = j = 0; i < numkeys; i++) {
8037 mp->mp_ptrs[j] = mp->mp_ptrs[i];
8038 if (mp->mp_ptrs[i] < ptr)
8039 mp->mp_ptrs[j] += sz;
8044 base = (char *)mp + mp->mp_upper + PAGEBASE;
8045 memmove(base + sz, base, ptr - mp->mp_upper);
8047 mp->mp_lower -= sizeof(indx_t);
8051 /** Compact the main page after deleting a node on a subpage.
8052 * @param[in] mp The main page to operate on.
8053 * @param[in] indx The index of the subpage on the main page.
8056 mdb_node_shrink(MDB_page *mp, indx_t indx)
8061 indx_t delta, nsize, len, ptr;
8064 node = NODEPTR(mp, indx);
8065 sp = (MDB_page *)NODEDATA(node);
8066 delta = SIZELEFT(sp);
8067 nsize = NODEDSZ(node) - delta;
8069 /* Prepare to shift upward, set len = length(subpage part to shift) */
8073 return; /* do not make the node uneven-sized */
8075 xp = (MDB_page *)((char *)sp + delta); /* destination subpage */
8076 for (i = NUMKEYS(sp); --i >= 0; )
8077 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
8080 sp->mp_upper = sp->mp_lower;
8081 COPY_PGNO(sp->mp_pgno, mp->mp_pgno);
8082 SETDSZ(node, nsize);
8084 /* Shift <lower nodes...initial part of subpage> upward */
8085 base = (char *)mp + mp->mp_upper + PAGEBASE;
8086 memmove(base + delta, base, (char *)sp + len - base);
8088 ptr = mp->mp_ptrs[indx];
8089 for (i = NUMKEYS(mp); --i >= 0; ) {
8090 if (mp->mp_ptrs[i] <= ptr)
8091 mp->mp_ptrs[i] += delta;
8093 mp->mp_upper += delta;
8096 /** Initial setup of a sorted-dups cursor.
8097 * Sorted duplicates are implemented as a sub-database for the given key.
8098 * The duplicate data items are actually keys of the sub-database.
8099 * Operations on the duplicate data items are performed using a sub-cursor
8100 * initialized when the sub-database is first accessed. This function does
8101 * the preliminary setup of the sub-cursor, filling in the fields that
8102 * depend only on the parent DB.
8103 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
8106 mdb_xcursor_init0(MDB_cursor *mc)
8108 MDB_xcursor *mx = mc->mc_xcursor;
8110 mx->mx_cursor.mc_xcursor = NULL;
8111 mx->mx_cursor.mc_txn = mc->mc_txn;
8112 mx->mx_cursor.mc_db = &mx->mx_db;
8113 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
8114 mx->mx_cursor.mc_dbi = mc->mc_dbi;
8115 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
8116 mx->mx_cursor.mc_snum = 0;
8117 mx->mx_cursor.mc_top = 0;
8119 mx->mx_cursor.mc_ovpg = 0;
8121 mx->mx_cursor.mc_flags = C_SUB | (mc->mc_flags & (C_ORIG_RDONLY|C_WRITEMAP));
8122 mx->mx_dbx.md_name.mv_size = 0;
8123 mx->mx_dbx.md_name.mv_data = NULL;
8124 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
8125 mx->mx_dbx.md_dcmp = NULL;
8126 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
8129 /** Final setup of a sorted-dups cursor.
8130 * Sets up the fields that depend on the data from the main cursor.
8131 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
8132 * @param[in] node The data containing the #MDB_db record for the
8133 * sorted-dup database.
8136 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
8138 MDB_xcursor *mx = mc->mc_xcursor;
8140 mx->mx_cursor.mc_flags &= C_SUB|C_ORIG_RDONLY|C_WRITEMAP;
8141 if (node->mn_flags & F_SUBDATA) {
8142 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
8143 mx->mx_cursor.mc_pg[0] = 0;
8144 mx->mx_cursor.mc_snum = 0;
8145 mx->mx_cursor.mc_top = 0;
8147 MDB_page *fp = NODEDATA(node);
8148 mx->mx_db.md_pad = 0;
8149 mx->mx_db.md_flags = 0;
8150 mx->mx_db.md_depth = 1;
8151 mx->mx_db.md_branch_pages = 0;
8152 mx->mx_db.md_leaf_pages = 1;
8153 mx->mx_db.md_overflow_pages = 0;
8154 mx->mx_db.md_entries = NUMKEYS(fp);
8155 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
8156 mx->mx_cursor.mc_snum = 1;
8157 mx->mx_cursor.mc_top = 0;
8158 mx->mx_cursor.mc_flags |= C_INITIALIZED;
8159 mx->mx_cursor.mc_pg[0] = fp;
8160 mx->mx_cursor.mc_ki[0] = 0;
8161 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
8162 mx->mx_db.md_flags = MDB_DUPFIXED;
8163 mx->mx_db.md_pad = fp->mp_pad;
8164 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
8165 mx->mx_db.md_flags |= MDB_INTEGERKEY;
8168 DPRINTF(("Sub-db -%u root page %"Y"u", mx->mx_cursor.mc_dbi,
8169 mx->mx_db.md_root));
8170 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
8171 #if UINT_MAX < SIZE_MAX || defined(MDB_VL32)
8172 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(mdb_size_t))
8173 mx->mx_dbx.md_cmp = mdb_cmp_clong;
8178 /** Fixup a sorted-dups cursor due to underlying update.
8179 * Sets up some fields that depend on the data from the main cursor.
8180 * Almost the same as init1, but skips initialization steps if the
8181 * xcursor had already been used.
8182 * @param[in] mc The main cursor whose sorted-dups cursor is to be fixed up.
8183 * @param[in] src_mx The xcursor of an up-to-date cursor.
8184 * @param[in] new_dupdata True if converting from a non-#F_DUPDATA item.
8187 mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int new_dupdata)
8189 MDB_xcursor *mx = mc->mc_xcursor;
8192 mx->mx_cursor.mc_snum = 1;
8193 mx->mx_cursor.mc_top = 0;
8194 mx->mx_cursor.mc_flags |= C_INITIALIZED;
8195 mx->mx_cursor.mc_ki[0] = 0;
8196 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
8197 #if UINT_MAX < SIZE_MAX
8198 mx->mx_dbx.md_cmp = src_mx->mx_dbx.md_cmp;
8200 } else if (!(mx->mx_cursor.mc_flags & C_INITIALIZED)) {
8203 mx->mx_db = src_mx->mx_db;
8204 mx->mx_cursor.mc_pg[0] = src_mx->mx_cursor.mc_pg[0];
8205 DPRINTF(("Sub-db -%u root page %"Y"u", mx->mx_cursor.mc_dbi,
8206 mx->mx_db.md_root));
8209 /** Initialize a cursor for a given transaction and database. */
8211 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
8214 mc->mc_backup = NULL;
8217 mc->mc_db = &txn->mt_dbs[dbi];
8218 mc->mc_dbx = &txn->mt_dbxs[dbi];
8219 mc->mc_dbflag = &txn->mt_dbflags[dbi];
8227 mc->mc_flags = txn->mt_flags & (C_ORIG_RDONLY|C_WRITEMAP);
8228 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
8229 mdb_tassert(txn, mx != NULL);
8230 mc->mc_xcursor = mx;
8231 mdb_xcursor_init0(mc);
8233 mc->mc_xcursor = NULL;
8235 if (*mc->mc_dbflag & DB_STALE) {
8236 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
8241 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
8244 size_t size = sizeof(MDB_cursor);
8246 if (!ret || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
8249 if (txn->mt_flags & MDB_TXN_BLOCKED)
8252 if (dbi == FREE_DBI && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
8255 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
8256 size += sizeof(MDB_xcursor);
8258 if ((mc = malloc(size)) != NULL) {
8259 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
8260 if (txn->mt_cursors) {
8261 mc->mc_next = txn->mt_cursors[dbi];
8262 txn->mt_cursors[dbi] = mc;
8263 mc->mc_flags |= C_UNTRACK;
8275 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
8277 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi, DB_VALID))
8280 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
8283 if (txn->mt_flags & MDB_TXN_BLOCKED)
8286 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
8290 /* Return the count of duplicate data items for the current key */
8292 mdb_cursor_count(MDB_cursor *mc, mdb_size_t *countp)
8296 if (mc == NULL || countp == NULL)
8299 if (mc->mc_xcursor == NULL)
8300 return MDB_INCOMPATIBLE;
8302 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
8305 if (!(mc->mc_flags & C_INITIALIZED))
8308 if (!mc->mc_snum || (mc->mc_flags & C_EOF))
8309 return MDB_NOTFOUND;
8311 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
8312 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
8315 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
8318 *countp = mc->mc_xcursor->mx_db.md_entries;
8324 mdb_cursor_close(MDB_cursor *mc)
8326 if (mc && !mc->mc_backup) {
8327 /* remove from txn, if tracked */
8328 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
8329 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
8330 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
8332 *prev = mc->mc_next;
8339 mdb_cursor_txn(MDB_cursor *mc)
8341 if (!mc) return NULL;
8346 mdb_cursor_dbi(MDB_cursor *mc)
8351 /** Replace the key for a branch node with a new key.
8352 * @param[in] mc Cursor pointing to the node to operate on.
8353 * @param[in] key The new key to use.
8354 * @return 0 on success, non-zero on failure.
8357 mdb_update_key(MDB_cursor *mc, MDB_val *key)
8363 int delta, ksize, oksize;
8364 indx_t ptr, i, numkeys, indx;
8367 indx = mc->mc_ki[mc->mc_top];
8368 mp = mc->mc_pg[mc->mc_top];
8369 node = NODEPTR(mp, indx);
8370 ptr = mp->mp_ptrs[indx];
8374 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
8375 k2.mv_data = NODEKEY(node);
8376 k2.mv_size = node->mn_ksize;
8377 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Y"u",
8379 mdb_dkey(&k2, kbuf2),
8385 /* Sizes must be 2-byte aligned. */
8386 ksize = EVEN(key->mv_size);
8387 oksize = EVEN(node->mn_ksize);
8388 delta = ksize - oksize;
8390 /* Shift node contents if EVEN(key length) changed. */
8392 if (delta > 0 && SIZELEFT(mp) < delta) {
8394 /* not enough space left, do a delete and split */
8395 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
8396 pgno = NODEPGNO(node);
8397 mdb_node_del(mc, 0);
8398 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
8401 numkeys = NUMKEYS(mp);
8402 for (i = 0; i < numkeys; i++) {
8403 if (mp->mp_ptrs[i] <= ptr)
8404 mp->mp_ptrs[i] -= delta;
8407 base = (char *)mp + mp->mp_upper + PAGEBASE;
8408 len = ptr - mp->mp_upper + NODESIZE;
8409 memmove(base - delta, base, len);
8410 mp->mp_upper -= delta;
8412 node = NODEPTR(mp, indx);
8415 /* But even if no shift was needed, update ksize */
8416 if (node->mn_ksize != key->mv_size)
8417 node->mn_ksize = key->mv_size;
8420 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
8426 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
8428 /** Perform \b act while tracking temporary cursor \b mn */
8429 #define WITH_CURSOR_TRACKING(mn, act) do { \
8430 MDB_cursor dummy, *tracked, **tp = &(mn).mc_txn->mt_cursors[mn.mc_dbi]; \
8431 if ((mn).mc_flags & C_SUB) { \
8432 dummy.mc_flags = C_INITIALIZED; \
8433 dummy.mc_xcursor = (MDB_xcursor *)&(mn); \
8438 tracked->mc_next = *tp; \
8441 *tp = tracked->mc_next; \
8444 /** Move a node from csrc to cdst.
8447 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft)
8454 unsigned short flags;
8458 /* Mark src and dst as dirty. */
8459 if ((rc = mdb_page_touch(csrc)) ||
8460 (rc = mdb_page_touch(cdst)))
8463 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8464 key.mv_size = csrc->mc_db->md_pad;
8465 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
8467 data.mv_data = NULL;
8471 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
8472 mdb_cassert(csrc, !((size_t)srcnode & 1));
8473 srcpg = NODEPGNO(srcnode);
8474 flags = srcnode->mn_flags;
8475 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
8476 unsigned int snum = csrc->mc_snum;
8478 /* must find the lowest key below src */
8479 rc = mdb_page_search_lowest(csrc);
8482 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8483 key.mv_size = csrc->mc_db->md_pad;
8484 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
8486 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
8487 key.mv_size = NODEKSZ(s2);
8488 key.mv_data = NODEKEY(s2);
8490 csrc->mc_snum = snum--;
8491 csrc->mc_top = snum;
8493 key.mv_size = NODEKSZ(srcnode);
8494 key.mv_data = NODEKEY(srcnode);
8496 data.mv_size = NODEDSZ(srcnode);
8497 data.mv_data = NODEDATA(srcnode);
8499 mn.mc_xcursor = NULL;
8500 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
8501 unsigned int snum = cdst->mc_snum;
8504 /* must find the lowest key below dst */
8505 mdb_cursor_copy(cdst, &mn);
8506 rc = mdb_page_search_lowest(&mn);
8509 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
8510 bkey.mv_size = mn.mc_db->md_pad;
8511 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
8513 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
8514 bkey.mv_size = NODEKSZ(s2);
8515 bkey.mv_data = NODEKEY(s2);
8517 mn.mc_snum = snum--;
8520 rc = mdb_update_key(&mn, &bkey);
8525 DPRINTF(("moving %s node %u [%s] on page %"Y"u to node %u on page %"Y"u",
8526 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
8527 csrc->mc_ki[csrc->mc_top],
8529 csrc->mc_pg[csrc->mc_top]->mp_pgno,
8530 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
8532 /* Add the node to the destination page.
8534 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
8535 if (rc != MDB_SUCCESS)
8538 /* Delete the node from the source page.
8540 mdb_node_del(csrc, key.mv_size);
8543 /* Adjust other cursors pointing to mp */
8544 MDB_cursor *m2, *m3;
8545 MDB_dbi dbi = csrc->mc_dbi;
8546 MDB_page *mpd, *mps;
8548 mps = csrc->mc_pg[csrc->mc_top];
8549 /* If we're adding on the left, bump others up */
8551 mpd = cdst->mc_pg[csrc->mc_top];
8552 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8553 if (csrc->mc_flags & C_SUB)
8554 m3 = &m2->mc_xcursor->mx_cursor;
8557 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
8560 m3->mc_pg[csrc->mc_top] == mpd &&
8561 m3->mc_ki[csrc->mc_top] >= cdst->mc_ki[csrc->mc_top]) {
8562 m3->mc_ki[csrc->mc_top]++;
8565 m3->mc_pg[csrc->mc_top] == mps &&
8566 m3->mc_ki[csrc->mc_top] == csrc->mc_ki[csrc->mc_top]) {
8567 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
8568 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
8569 m3->mc_ki[csrc->mc_top-1]++;
8571 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) &&
8573 MDB_node *node = NODEPTR(m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
8574 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
8575 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
8579 /* Adding on the right, bump others down */
8581 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8582 if (csrc->mc_flags & C_SUB)
8583 m3 = &m2->mc_xcursor->mx_cursor;
8586 if (m3 == csrc) continue;
8587 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
8589 if (m3->mc_pg[csrc->mc_top] == mps) {
8590 if (!m3->mc_ki[csrc->mc_top]) {
8591 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
8592 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
8593 m3->mc_ki[csrc->mc_top-1]--;
8595 m3->mc_ki[csrc->mc_top]--;
8597 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) &&
8599 MDB_node *node = NODEPTR(m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
8600 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
8601 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
8608 /* Update the parent separators.
8610 if (csrc->mc_ki[csrc->mc_top] == 0) {
8611 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
8612 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8613 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
8615 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
8616 key.mv_size = NODEKSZ(srcnode);
8617 key.mv_data = NODEKEY(srcnode);
8619 DPRINTF(("update separator for source page %"Y"u to [%s]",
8620 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
8621 mdb_cursor_copy(csrc, &mn);
8624 /* We want mdb_rebalance to find mn when doing fixups */
8625 WITH_CURSOR_TRACKING(mn,
8626 rc = mdb_update_key(&mn, &key));
8630 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
8632 indx_t ix = csrc->mc_ki[csrc->mc_top];
8633 nullkey.mv_size = 0;
8634 csrc->mc_ki[csrc->mc_top] = 0;
8635 rc = mdb_update_key(csrc, &nullkey);
8636 csrc->mc_ki[csrc->mc_top] = ix;
8637 mdb_cassert(csrc, rc == MDB_SUCCESS);
8641 if (cdst->mc_ki[cdst->mc_top] == 0) {
8642 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
8643 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8644 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
8646 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
8647 key.mv_size = NODEKSZ(srcnode);
8648 key.mv_data = NODEKEY(srcnode);
8650 DPRINTF(("update separator for destination page %"Y"u to [%s]",
8651 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
8652 mdb_cursor_copy(cdst, &mn);
8655 /* We want mdb_rebalance to find mn when doing fixups */
8656 WITH_CURSOR_TRACKING(mn,
8657 rc = mdb_update_key(&mn, &key));
8661 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
8663 indx_t ix = cdst->mc_ki[cdst->mc_top];
8664 nullkey.mv_size = 0;
8665 cdst->mc_ki[cdst->mc_top] = 0;
8666 rc = mdb_update_key(cdst, &nullkey);
8667 cdst->mc_ki[cdst->mc_top] = ix;
8668 mdb_cassert(cdst, rc == MDB_SUCCESS);
8675 /** Merge one page into another.
8676 * The nodes from the page pointed to by \b csrc will
8677 * be copied to the page pointed to by \b cdst and then
8678 * the \b csrc page will be freed.
8679 * @param[in] csrc Cursor pointing to the source page.
8680 * @param[in] cdst Cursor pointing to the destination page.
8681 * @return 0 on success, non-zero on failure.
8684 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
8686 MDB_page *psrc, *pdst;
8693 psrc = csrc->mc_pg[csrc->mc_top];
8694 pdst = cdst->mc_pg[cdst->mc_top];
8696 DPRINTF(("merging page %"Y"u into %"Y"u", psrc->mp_pgno, pdst->mp_pgno));
8698 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
8699 mdb_cassert(csrc, cdst->mc_snum > 1);
8701 /* Mark dst as dirty. */
8702 if ((rc = mdb_page_touch(cdst)))
8705 /* get dst page again now that we've touched it. */
8706 pdst = cdst->mc_pg[cdst->mc_top];
8708 /* Move all nodes from src to dst.
8710 j = nkeys = NUMKEYS(pdst);
8711 if (IS_LEAF2(psrc)) {
8712 key.mv_size = csrc->mc_db->md_pad;
8713 key.mv_data = METADATA(psrc);
8714 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
8715 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
8716 if (rc != MDB_SUCCESS)
8718 key.mv_data = (char *)key.mv_data + key.mv_size;
8721 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
8722 srcnode = NODEPTR(psrc, i);
8723 if (i == 0 && IS_BRANCH(psrc)) {
8726 mdb_cursor_copy(csrc, &mn);
8727 mn.mc_xcursor = NULL;
8728 /* must find the lowest key below src */
8729 rc = mdb_page_search_lowest(&mn);
8732 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
8733 key.mv_size = mn.mc_db->md_pad;
8734 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
8736 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
8737 key.mv_size = NODEKSZ(s2);
8738 key.mv_data = NODEKEY(s2);
8741 key.mv_size = srcnode->mn_ksize;
8742 key.mv_data = NODEKEY(srcnode);
8745 data.mv_size = NODEDSZ(srcnode);
8746 data.mv_data = NODEDATA(srcnode);
8747 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
8748 if (rc != MDB_SUCCESS)
8753 DPRINTF(("dst page %"Y"u now has %u keys (%.1f%% filled)",
8754 pdst->mp_pgno, NUMKEYS(pdst),
8755 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
8757 /* Unlink the src page from parent and add to free list.
8760 mdb_node_del(csrc, 0);
8761 if (csrc->mc_ki[csrc->mc_top] == 0) {
8763 rc = mdb_update_key(csrc, &key);
8771 psrc = csrc->mc_pg[csrc->mc_top];
8772 /* If not operating on FreeDB, allow this page to be reused
8773 * in this txn. Otherwise just add to free list.
8775 rc = mdb_page_loose(csrc, psrc);
8779 csrc->mc_db->md_leaf_pages--;
8781 csrc->mc_db->md_branch_pages--;
8783 /* Adjust other cursors pointing to mp */
8784 MDB_cursor *m2, *m3;
8785 MDB_dbi dbi = csrc->mc_dbi;
8786 unsigned int top = csrc->mc_top;
8788 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8789 if (csrc->mc_flags & C_SUB)
8790 m3 = &m2->mc_xcursor->mx_cursor;
8793 if (m3 == csrc) continue;
8794 if (m3->mc_snum < csrc->mc_snum) continue;
8795 if (m3->mc_pg[top] == psrc) {
8796 m3->mc_pg[top] = pdst;
8797 m3->mc_ki[top] += nkeys;
8798 m3->mc_ki[top-1] = cdst->mc_ki[top-1];
8799 } else if (m3->mc_pg[top-1] == csrc->mc_pg[top-1] &&
8800 m3->mc_ki[top-1] > csrc->mc_ki[top-1]) {
8803 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) &&
8805 MDB_node *node = NODEPTR(m3->mc_pg[top], m3->mc_ki[top]);
8806 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
8807 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
8812 unsigned int snum = cdst->mc_snum;
8813 uint16_t depth = cdst->mc_db->md_depth;
8814 mdb_cursor_pop(cdst);
8815 rc = mdb_rebalance(cdst);
8816 /* Did the tree height change? */
8817 if (depth != cdst->mc_db->md_depth)
8818 snum += cdst->mc_db->md_depth - depth;
8819 cdst->mc_snum = snum;
8820 cdst->mc_top = snum-1;
8825 /** Copy the contents of a cursor.
8826 * @param[in] csrc The cursor to copy from.
8827 * @param[out] cdst The cursor to copy to.
8830 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
8834 cdst->mc_txn = csrc->mc_txn;
8835 cdst->mc_dbi = csrc->mc_dbi;
8836 cdst->mc_db = csrc->mc_db;
8837 cdst->mc_dbx = csrc->mc_dbx;
8838 cdst->mc_snum = csrc->mc_snum;
8839 cdst->mc_top = csrc->mc_top;
8840 cdst->mc_flags = csrc->mc_flags;
8842 cdst->mc_ovpg = csrc->mc_ovpg;
8845 for (i=0; i<csrc->mc_snum; i++) {
8846 cdst->mc_pg[i] = csrc->mc_pg[i];
8847 cdst->mc_ki[i] = csrc->mc_ki[i];
8851 /** Rebalance the tree after a delete operation.
8852 * @param[in] mc Cursor pointing to the page where rebalancing
8854 * @return 0 on success, non-zero on failure.
8857 mdb_rebalance(MDB_cursor *mc)
8861 unsigned int ptop, minkeys, thresh;
8865 if (IS_BRANCH(mc->mc_pg[mc->mc_top])) {
8870 thresh = FILL_THRESHOLD;
8872 DPRINTF(("rebalancing %s page %"Y"u (has %u keys, %.1f%% full)",
8873 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
8874 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
8875 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
8877 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= thresh &&
8878 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
8879 DPRINTF(("no need to rebalance page %"Y"u, above fill threshold",
8880 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
8884 if (mc->mc_snum < 2) {
8885 MDB_page *mp = mc->mc_pg[0];
8887 DPUTS("Can't rebalance a subpage, ignoring");
8890 if (NUMKEYS(mp) == 0) {
8891 DPUTS("tree is completely empty");
8892 mc->mc_db->md_root = P_INVALID;
8893 mc->mc_db->md_depth = 0;
8894 mc->mc_db->md_leaf_pages = 0;
8895 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
8898 /* Adjust cursors pointing to mp */
8901 mc->mc_flags &= ~C_INITIALIZED;
8903 MDB_cursor *m2, *m3;
8904 MDB_dbi dbi = mc->mc_dbi;
8906 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8907 if (mc->mc_flags & C_SUB)
8908 m3 = &m2->mc_xcursor->mx_cursor;
8911 if (!(m3->mc_flags & C_INITIALIZED) || (m3->mc_snum < mc->mc_snum))
8913 if (m3->mc_pg[0] == mp) {
8916 m3->mc_flags &= ~C_INITIALIZED;
8920 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
8922 DPUTS("collapsing root page!");
8923 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
8926 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
8927 rc = mdb_page_get(mc, mc->mc_db->md_root, &mc->mc_pg[0], NULL);
8930 mc->mc_db->md_depth--;
8931 mc->mc_db->md_branch_pages--;
8932 mc->mc_ki[0] = mc->mc_ki[1];
8933 for (i = 1; i<mc->mc_db->md_depth; i++) {
8934 mc->mc_pg[i] = mc->mc_pg[i+1];
8935 mc->mc_ki[i] = mc->mc_ki[i+1];
8938 /* Adjust other cursors pointing to mp */
8939 MDB_cursor *m2, *m3;
8940 MDB_dbi dbi = mc->mc_dbi;
8942 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8943 if (mc->mc_flags & C_SUB)
8944 m3 = &m2->mc_xcursor->mx_cursor;
8947 if (m3 == mc) continue;
8948 if (!(m3->mc_flags & C_INITIALIZED))
8950 if (m3->mc_pg[0] == mp) {
8951 for (i=0; i<mc->mc_db->md_depth; i++) {
8952 m3->mc_pg[i] = m3->mc_pg[i+1];
8953 m3->mc_ki[i] = m3->mc_ki[i+1];
8961 DPUTS("root page doesn't need rebalancing");
8965 /* The parent (branch page) must have at least 2 pointers,
8966 * otherwise the tree is invalid.
8968 ptop = mc->mc_top-1;
8969 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
8971 /* Leaf page fill factor is below the threshold.
8972 * Try to move keys from left or right neighbor, or
8973 * merge with a neighbor page.
8978 mdb_cursor_copy(mc, &mn);
8979 mn.mc_xcursor = NULL;
8981 oldki = mc->mc_ki[mc->mc_top];
8982 if (mc->mc_ki[ptop] == 0) {
8983 /* We're the leftmost leaf in our parent.
8985 DPUTS("reading right neighbor");
8987 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
8988 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
8991 mn.mc_ki[mn.mc_top] = 0;
8992 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
8995 /* There is at least one neighbor to the left.
8997 DPUTS("reading left neighbor");
8999 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
9000 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
9003 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
9004 mc->mc_ki[mc->mc_top] = 0;
9008 DPRINTF(("found neighbor page %"Y"u (%u keys, %.1f%% full)",
9009 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
9010 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
9012 /* If the neighbor page is above threshold and has enough keys,
9013 * move one key from it. Otherwise we should try to merge them.
9014 * (A branch page must never have less than 2 keys.)
9016 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= thresh && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
9017 rc = mdb_node_move(&mn, mc, fromleft);
9019 /* if we inserted on left, bump position up */
9024 rc = mdb_page_merge(&mn, mc);
9026 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
9027 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
9028 /* We want mdb_rebalance to find mn when doing fixups */
9029 WITH_CURSOR_TRACKING(mn,
9030 rc = mdb_page_merge(mc, &mn));
9031 mdb_cursor_copy(&mn, mc);
9033 mc->mc_flags &= ~C_EOF;
9035 mc->mc_ki[mc->mc_top] = oldki;
9039 /** Complete a delete operation started by #mdb_cursor_del(). */
9041 mdb_cursor_del0(MDB_cursor *mc)
9047 MDB_cursor *m2, *m3;
9048 MDB_dbi dbi = mc->mc_dbi;
9050 ki = mc->mc_ki[mc->mc_top];
9051 mp = mc->mc_pg[mc->mc_top];
9052 mdb_node_del(mc, mc->mc_db->md_pad);
9053 mc->mc_db->md_entries--;
9055 /* Adjust other cursors pointing to mp */
9056 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9057 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
9058 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9060 if (m3 == mc || m3->mc_snum < mc->mc_snum)
9062 if (m3->mc_pg[mc->mc_top] == mp) {
9063 if (m3->mc_ki[mc->mc_top] == ki) {
9064 m3->mc_flags |= C_DEL;
9065 } else if (m3->mc_ki[mc->mc_top] > ki) {
9066 m3->mc_ki[mc->mc_top]--;
9068 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
9069 MDB_node *node = NODEPTR(m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
9070 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
9071 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
9076 rc = mdb_rebalance(mc);
9078 if (rc == MDB_SUCCESS) {
9079 /* DB is totally empty now, just bail out.
9080 * Other cursors adjustments were already done
9081 * by mdb_rebalance and aren't needed here.
9086 mp = mc->mc_pg[mc->mc_top];
9087 nkeys = NUMKEYS(mp);
9089 /* Adjust other cursors pointing to mp */
9090 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
9091 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
9092 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9094 if (m3->mc_snum < mc->mc_snum)
9096 if (m3->mc_pg[mc->mc_top] == mp) {
9097 /* if m3 points past last node in page, find next sibling */
9098 if (m3->mc_ki[mc->mc_top] >= mc->mc_ki[mc->mc_top]) {
9099 if (m3->mc_ki[mc->mc_top] >= nkeys) {
9100 rc = mdb_cursor_sibling(m3, 1);
9101 if (rc == MDB_NOTFOUND) {
9102 m3->mc_flags |= C_EOF;
9107 if (mc->mc_db->md_flags & MDB_DUPSORT) {
9108 MDB_node *node = NODEPTR(m3->mc_pg[m3->mc_top], m3->mc_ki[m3->mc_top]);
9109 if (node->mn_flags & F_DUPDATA) {
9110 mdb_xcursor_init1(m3, node);
9111 m3->mc_xcursor->mx_cursor.mc_flags |= C_DEL;
9117 mc->mc_flags |= C_DEL;
9121 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
9126 mdb_del(MDB_txn *txn, MDB_dbi dbi,
9127 MDB_val *key, MDB_val *data)
9129 if (!key || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9132 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
9133 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
9135 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
9136 /* must ignore any data */
9140 return mdb_del0(txn, dbi, key, data, 0);
9144 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
9145 MDB_val *key, MDB_val *data, unsigned flags)
9150 MDB_val rdata, *xdata;
9154 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
9156 mdb_cursor_init(&mc, txn, dbi, &mx);
9165 flags |= MDB_NODUPDATA;
9167 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
9169 /* let mdb_page_split know about this cursor if needed:
9170 * delete will trigger a rebalance; if it needs to move
9171 * a node from one page to another, it will have to
9172 * update the parent's separator key(s). If the new sepkey
9173 * is larger than the current one, the parent page may
9174 * run out of space, triggering a split. We need this
9175 * cursor to be consistent until the end of the rebalance.
9177 mc.mc_flags |= C_UNTRACK;
9178 mc.mc_next = txn->mt_cursors[dbi];
9179 txn->mt_cursors[dbi] = &mc;
9180 rc = mdb_cursor_del(&mc, flags);
9181 txn->mt_cursors[dbi] = mc.mc_next;
9186 /** Split a page and insert a new node.
9187 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
9188 * The cursor will be updated to point to the actual page and index where
9189 * the node got inserted after the split.
9190 * @param[in] newkey The key for the newly inserted node.
9191 * @param[in] newdata The data for the newly inserted node.
9192 * @param[in] newpgno The page number, if the new node is a branch node.
9193 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
9194 * @return 0 on success, non-zero on failure.
9197 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
9198 unsigned int nflags)
9201 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
9204 int i, j, split_indx, nkeys, pmax;
9205 MDB_env *env = mc->mc_txn->mt_env;
9207 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
9208 MDB_page *copy = NULL;
9209 MDB_page *mp, *rp, *pp;
9214 mp = mc->mc_pg[mc->mc_top];
9215 newindx = mc->mc_ki[mc->mc_top];
9216 nkeys = NUMKEYS(mp);
9218 DPRINTF(("-----> splitting %s page %"Y"u and adding [%s] at index %i/%i",
9219 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
9220 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
9222 /* Create a right sibling. */
9223 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
9225 rp->mp_pad = mp->mp_pad;
9226 DPRINTF(("new right sibling: page %"Y"u", rp->mp_pgno));
9228 /* Usually when splitting the root page, the cursor
9229 * height is 1. But when called from mdb_update_key,
9230 * the cursor height may be greater because it walks
9231 * up the stack while finding the branch slot to update.
9233 if (mc->mc_top < 1) {
9234 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
9236 /* shift current top to make room for new parent */
9237 for (i=mc->mc_snum; i>0; i--) {
9238 mc->mc_pg[i] = mc->mc_pg[i-1];
9239 mc->mc_ki[i] = mc->mc_ki[i-1];
9243 mc->mc_db->md_root = pp->mp_pgno;
9244 DPRINTF(("root split! new root = %"Y"u", pp->mp_pgno));
9245 new_root = mc->mc_db->md_depth++;
9247 /* Add left (implicit) pointer. */
9248 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
9249 /* undo the pre-push */
9250 mc->mc_pg[0] = mc->mc_pg[1];
9251 mc->mc_ki[0] = mc->mc_ki[1];
9252 mc->mc_db->md_root = mp->mp_pgno;
9253 mc->mc_db->md_depth--;
9260 ptop = mc->mc_top-1;
9261 DPRINTF(("parent branch page is %"Y"u", mc->mc_pg[ptop]->mp_pgno));
9264 mdb_cursor_copy(mc, &mn);
9265 mn.mc_xcursor = NULL;
9266 mn.mc_pg[mn.mc_top] = rp;
9267 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
9269 if (nflags & MDB_APPEND) {
9270 mn.mc_ki[mn.mc_top] = 0;
9272 split_indx = newindx;
9276 split_indx = (nkeys+1) / 2;
9281 unsigned int lsize, rsize, ksize;
9282 /* Move half of the keys to the right sibling */
9283 x = mc->mc_ki[mc->mc_top] - split_indx;
9284 ksize = mc->mc_db->md_pad;
9285 split = LEAF2KEY(mp, split_indx, ksize);
9286 rsize = (nkeys - split_indx) * ksize;
9287 lsize = (nkeys - split_indx) * sizeof(indx_t);
9288 mp->mp_lower -= lsize;
9289 rp->mp_lower += lsize;
9290 mp->mp_upper += rsize - lsize;
9291 rp->mp_upper -= rsize - lsize;
9292 sepkey.mv_size = ksize;
9293 if (newindx == split_indx) {
9294 sepkey.mv_data = newkey->mv_data;
9296 sepkey.mv_data = split;
9299 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
9300 memcpy(rp->mp_ptrs, split, rsize);
9301 sepkey.mv_data = rp->mp_ptrs;
9302 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
9303 memcpy(ins, newkey->mv_data, ksize);
9304 mp->mp_lower += sizeof(indx_t);
9305 mp->mp_upper -= ksize - sizeof(indx_t);
9308 memcpy(rp->mp_ptrs, split, x * ksize);
9309 ins = LEAF2KEY(rp, x, ksize);
9310 memcpy(ins, newkey->mv_data, ksize);
9311 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
9312 rp->mp_lower += sizeof(indx_t);
9313 rp->mp_upper -= ksize - sizeof(indx_t);
9314 mc->mc_ki[mc->mc_top] = x;
9317 int psize, nsize, k;
9318 /* Maximum free space in an empty page */
9319 pmax = env->me_psize - PAGEHDRSZ;
9321 nsize = mdb_leaf_size(env, newkey, newdata);
9323 nsize = mdb_branch_size(env, newkey);
9324 nsize = EVEN(nsize);
9326 /* grab a page to hold a temporary copy */
9327 copy = mdb_page_malloc(mc->mc_txn, 1);
9332 copy->mp_pgno = mp->mp_pgno;
9333 copy->mp_flags = mp->mp_flags;
9334 copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
9335 copy->mp_upper = env->me_psize - PAGEBASE;
9337 /* prepare to insert */
9338 for (i=0, j=0; i<nkeys; i++) {
9340 copy->mp_ptrs[j++] = 0;
9342 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
9345 /* When items are relatively large the split point needs
9346 * to be checked, because being off-by-one will make the
9347 * difference between success or failure in mdb_node_add.
9349 * It's also relevant if a page happens to be laid out
9350 * such that one half of its nodes are all "small" and
9351 * the other half of its nodes are "large." If the new
9352 * item is also "large" and falls on the half with
9353 * "large" nodes, it also may not fit.
9355 * As a final tweak, if the new item goes on the last
9356 * spot on the page (and thus, onto the new page), bias
9357 * the split so the new page is emptier than the old page.
9358 * This yields better packing during sequential inserts.
9360 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
9361 /* Find split point */
9363 if (newindx <= split_indx || newindx >= nkeys) {
9365 k = newindx >= nkeys ? nkeys : split_indx+1+IS_LEAF(mp);
9370 for (; i!=k; i+=j) {
9375 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
9376 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
9378 if (F_ISSET(node->mn_flags, F_BIGDATA))
9379 psize += sizeof(pgno_t);
9381 psize += NODEDSZ(node);
9383 psize = EVEN(psize);
9385 if (psize > pmax || i == k-j) {
9386 split_indx = i + (j<0);
9391 if (split_indx == newindx) {
9392 sepkey.mv_size = newkey->mv_size;
9393 sepkey.mv_data = newkey->mv_data;
9395 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
9396 sepkey.mv_size = node->mn_ksize;
9397 sepkey.mv_data = NODEKEY(node);
9402 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
9404 /* Copy separator key to the parent.
9406 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
9407 int snum = mc->mc_snum;
9411 /* We want other splits to find mn when doing fixups */
9412 WITH_CURSOR_TRACKING(mn,
9413 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0));
9418 if (mc->mc_snum > snum) {
9421 /* Right page might now have changed parent.
9422 * Check if left page also changed parent.
9424 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
9425 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
9426 for (i=0; i<ptop; i++) {
9427 mc->mc_pg[i] = mn.mc_pg[i];
9428 mc->mc_ki[i] = mn.mc_ki[i];
9430 mc->mc_pg[ptop] = mn.mc_pg[ptop];
9431 if (mn.mc_ki[ptop]) {
9432 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
9434 /* find right page's left sibling */
9435 mc->mc_ki[ptop] = mn.mc_ki[ptop];
9436 mdb_cursor_sibling(mc, 0);
9441 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
9444 if (rc != MDB_SUCCESS) {
9447 if (nflags & MDB_APPEND) {
9448 mc->mc_pg[mc->mc_top] = rp;
9449 mc->mc_ki[mc->mc_top] = 0;
9450 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
9453 for (i=0; i<mc->mc_top; i++)
9454 mc->mc_ki[i] = mn.mc_ki[i];
9455 } else if (!IS_LEAF2(mp)) {
9457 mc->mc_pg[mc->mc_top] = rp;
9462 rkey.mv_data = newkey->mv_data;
9463 rkey.mv_size = newkey->mv_size;
9469 /* Update index for the new key. */
9470 mc->mc_ki[mc->mc_top] = j;
9472 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
9473 rkey.mv_data = NODEKEY(node);
9474 rkey.mv_size = node->mn_ksize;
9476 xdata.mv_data = NODEDATA(node);
9477 xdata.mv_size = NODEDSZ(node);
9480 pgno = NODEPGNO(node);
9481 flags = node->mn_flags;
9484 if (!IS_LEAF(mp) && j == 0) {
9485 /* First branch index doesn't need key data. */
9489 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
9495 mc->mc_pg[mc->mc_top] = copy;
9500 } while (i != split_indx);
9502 nkeys = NUMKEYS(copy);
9503 for (i=0; i<nkeys; i++)
9504 mp->mp_ptrs[i] = copy->mp_ptrs[i];
9505 mp->mp_lower = copy->mp_lower;
9506 mp->mp_upper = copy->mp_upper;
9507 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
9508 env->me_psize - copy->mp_upper - PAGEBASE);
9510 /* reset back to original page */
9511 if (newindx < split_indx) {
9512 mc->mc_pg[mc->mc_top] = mp;
9514 mc->mc_pg[mc->mc_top] = rp;
9516 /* Make sure mc_ki is still valid.
9518 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
9519 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
9520 for (i=0; i<=ptop; i++) {
9521 mc->mc_pg[i] = mn.mc_pg[i];
9522 mc->mc_ki[i] = mn.mc_ki[i];
9526 if (nflags & MDB_RESERVE) {
9527 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
9528 if (!(node->mn_flags & F_BIGDATA))
9529 newdata->mv_data = NODEDATA(node);
9532 if (newindx >= split_indx) {
9533 mc->mc_pg[mc->mc_top] = rp;
9535 /* Make sure mc_ki is still valid.
9537 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
9538 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
9539 for (i=0; i<=ptop; i++) {
9540 mc->mc_pg[i] = mn.mc_pg[i];
9541 mc->mc_ki[i] = mn.mc_ki[i];
9548 /* Adjust other cursors pointing to mp */
9549 MDB_cursor *m2, *m3;
9550 MDB_dbi dbi = mc->mc_dbi;
9551 nkeys = NUMKEYS(mp);
9553 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9554 if (mc->mc_flags & C_SUB)
9555 m3 = &m2->mc_xcursor->mx_cursor;
9560 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9564 /* sub cursors may be on different DB */
9565 if (m3->mc_pg[0] != mp)
9568 for (k=new_root; k>=0; k--) {
9569 m3->mc_ki[k+1] = m3->mc_ki[k];
9570 m3->mc_pg[k+1] = m3->mc_pg[k];
9572 if (m3->mc_ki[0] >= nkeys) {
9577 m3->mc_pg[0] = mc->mc_pg[0];
9581 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
9582 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
9583 m3->mc_ki[mc->mc_top]++;
9584 if (m3->mc_ki[mc->mc_top] >= nkeys) {
9585 m3->mc_pg[mc->mc_top] = rp;
9586 m3->mc_ki[mc->mc_top] -= nkeys;
9587 for (i=0; i<mc->mc_top; i++) {
9588 m3->mc_ki[i] = mn.mc_ki[i];
9589 m3->mc_pg[i] = mn.mc_pg[i];
9592 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
9593 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
9596 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) &&
9598 MDB_node *node = NODEPTR(m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
9599 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
9600 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
9604 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
9607 if (copy) /* tmp page */
9608 mdb_page_free(env, copy);
9610 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
9615 mdb_put(MDB_txn *txn, MDB_dbi dbi,
9616 MDB_val *key, MDB_val *data, unsigned int flags)
9622 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9625 if (flags & ~(MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP))
9628 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
9629 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
9631 mdb_cursor_init(&mc, txn, dbi, &mx);
9632 mc.mc_next = txn->mt_cursors[dbi];
9633 txn->mt_cursors[dbi] = &mc;
9634 rc = mdb_cursor_put(&mc, key, data, flags);
9635 txn->mt_cursors[dbi] = mc.mc_next;
9640 #define MDB_WBUF (1024*1024)
9642 #define MDB_EOF 0x10 /**< #mdb_env_copyfd1() is done reading */
9644 /** State needed for a double-buffering compacting copy. */
9645 typedef struct mdb_copy {
9646 pthread_mutex_t mc_mutex;
9647 pthread_cond_t mc_cond; /**< Condition variable for #mc_new */
9654 pgno_t mc_next_pgno;
9656 int mc_toggle; /**< Buffer number in provider */
9657 int mc_new; /**< (0-2 buffers to write) | (#MDB_EOF at end) */
9658 volatile int mc_error; /**< Error code, never cleared if set */
9661 /** Dedicated writer thread for compacting copy. */
9662 static THREAD_RET ESECT CALL_CONV
9663 mdb_env_copythr(void *arg)
9667 int toggle = 0, wsize, rc;
9670 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
9673 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
9676 pthread_mutex_lock(&my->mc_mutex);
9679 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
9680 if (my->mc_new == 0 + MDB_EOF) /* 0 buffers, just EOF */
9682 wsize = my->mc_wlen[toggle];
9683 ptr = my->mc_wbuf[toggle];
9686 while (wsize > 0 && !my->mc_error) {
9687 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
9691 } else if (len > 0) {
9704 /* If there's an overflow page tail, write it too */
9705 if (my->mc_olen[toggle]) {
9706 wsize = my->mc_olen[toggle];
9707 ptr = my->mc_over[toggle];
9708 my->mc_olen[toggle] = 0;
9711 my->mc_wlen[toggle] = 0;
9713 /* Return the empty buffer to provider */
9715 pthread_cond_signal(&my->mc_cond);
9717 pthread_mutex_unlock(&my->mc_mutex);
9718 return (THREAD_RET)0;
9722 /** Give buffer and/or #MDB_EOF to writer thread, await unused buffer.
9724 * @param[in] my control structure.
9725 * @param[in] adjust (1 to hand off 1 buffer) | (MDB_EOF when ending).
9728 mdb_env_cthr_toggle(mdb_copy *my, int adjust)
9730 pthread_mutex_lock(&my->mc_mutex);
9731 my->mc_new += adjust;
9732 pthread_cond_signal(&my->mc_cond);
9733 while (my->mc_new & 2) /* both buffers in use */
9734 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
9735 pthread_mutex_unlock(&my->mc_mutex);
9737 my->mc_toggle ^= (adjust & 1);
9738 /* Both threads reset mc_wlen, to be safe from threading errors */
9739 my->mc_wlen[my->mc_toggle] = 0;
9740 return my->mc_error;
9743 /** Depth-first tree traversal for compacting copy. */
9745 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
9747 MDB_cursor mc = {0};
9749 MDB_page *mo, *mp, *leaf;
9754 /* Empty DB, nothing to do */
9755 if (*pg == P_INVALID)
9759 mc.mc_txn = my->mc_txn;
9760 mc.mc_flags = my->mc_txn->mt_flags & (C_ORIG_RDONLY|C_WRITEMAP);
9762 rc = mdb_page_get(&mc, *pg, &mc.mc_pg[0], NULL);
9765 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
9769 /* Make cursor pages writable */
9770 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
9774 for (i=0; i<mc.mc_top; i++) {
9775 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
9776 mc.mc_pg[i] = (MDB_page *)ptr;
9777 ptr += my->mc_env->me_psize;
9780 /* This is writable space for a leaf page. Usually not needed. */
9781 leaf = (MDB_page *)ptr;
9783 toggle = my->mc_toggle;
9784 while (mc.mc_snum > 0) {
9786 mp = mc.mc_pg[mc.mc_top];
9790 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
9791 for (i=0; i<n; i++) {
9792 ni = NODEPTR(mp, i);
9793 if (ni->mn_flags & F_BIGDATA) {
9797 /* Need writable leaf */
9799 mc.mc_pg[mc.mc_top] = leaf;
9800 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
9802 ni = NODEPTR(mp, i);
9805 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9806 memcpy(NODEDATA(ni), &my->mc_next_pgno, sizeof(pgno_t));
9807 rc = mdb_page_get(&mc, pg, &omp, NULL);
9810 if (my->mc_wlen[toggle] >= MDB_WBUF) {
9811 rc = mdb_env_cthr_toggle(my, 1);
9814 toggle = my->mc_toggle;
9816 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
9817 memcpy(mo, omp, my->mc_env->me_psize);
9818 mo->mp_pgno = my->mc_next_pgno;
9819 my->mc_next_pgno += omp->mp_pages;
9820 my->mc_wlen[toggle] += my->mc_env->me_psize;
9821 if (omp->mp_pages > 1) {
9822 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
9823 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
9824 rc = mdb_env_cthr_toggle(my, 1);
9827 toggle = my->mc_toggle;
9829 } else if (ni->mn_flags & F_SUBDATA) {
9832 /* Need writable leaf */
9834 mc.mc_pg[mc.mc_top] = leaf;
9835 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
9837 ni = NODEPTR(mp, i);
9840 memcpy(&db, NODEDATA(ni), sizeof(db));
9841 my->mc_toggle = toggle;
9842 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
9845 toggle = my->mc_toggle;
9846 memcpy(NODEDATA(ni), &db, sizeof(db));
9851 mc.mc_ki[mc.mc_top]++;
9852 if (mc.mc_ki[mc.mc_top] < n) {
9855 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
9857 rc = mdb_page_get(&mc, pg, &mp, NULL);
9862 mc.mc_ki[mc.mc_top] = 0;
9863 if (IS_BRANCH(mp)) {
9864 /* Whenever we advance to a sibling branch page,
9865 * we must proceed all the way down to its first leaf.
9867 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
9870 mc.mc_pg[mc.mc_top] = mp;
9874 if (my->mc_wlen[toggle] >= MDB_WBUF) {
9875 rc = mdb_env_cthr_toggle(my, 1);
9878 toggle = my->mc_toggle;
9880 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
9881 mdb_page_copy(mo, mp, my->mc_env->me_psize);
9882 mo->mp_pgno = my->mc_next_pgno++;
9883 my->mc_wlen[toggle] += my->mc_env->me_psize;
9885 /* Update parent if there is one */
9886 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
9887 SETPGNO(ni, mo->mp_pgno);
9888 mdb_cursor_pop(&mc);
9890 /* Otherwise we're done */
9900 /** Copy environment with compaction. */
9902 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
9907 MDB_txn *txn = NULL;
9909 pgno_t root, new_root;
9910 int rc = MDB_SUCCESS;
9913 if (!(my.mc_mutex = CreateMutex(NULL, FALSE, NULL)) ||
9914 !(my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL))) {
9918 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_os_psize);
9919 if (my.mc_wbuf[0] == NULL) {
9920 /* _aligned_malloc() sets errno, but we use Windows error codes */
9921 rc = ERROR_NOT_ENOUGH_MEMORY;
9925 if ((rc = pthread_mutex_init(&my.mc_mutex, NULL)) ||
9926 (rc = pthread_cond_init(&my.mc_cond, NULL)))
9928 #ifdef HAVE_MEMALIGN
9929 my.mc_wbuf[0] = memalign(env->me_os_psize, MDB_WBUF*2);
9930 if (my.mc_wbuf[0] == NULL) {
9935 rc = posix_memalign((void **)&my.mc_wbuf[0], env->me_os_psize, MDB_WBUF*2);
9940 memset(my.mc_wbuf[0], 0, MDB_WBUF*2);
9941 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
9942 my.mc_next_pgno = NUM_METAS;
9945 rc = THREAD_CREATE(thr, mdb_env_copythr, &my);
9949 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
9953 mp = (MDB_page *)my.mc_wbuf[0];
9954 memset(mp, 0, NUM_METAS * env->me_psize);
9956 mp->mp_flags = P_META;
9957 mm = (MDB_meta *)METADATA(mp);
9958 mdb_env_init_meta0(env, mm);
9959 mm->mm_address = env->me_metas[0]->mm_address;
9961 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
9963 mp->mp_flags = P_META;
9964 *(MDB_meta *)METADATA(mp) = *mm;
9965 mm = (MDB_meta *)METADATA(mp);
9967 /* Set metapage 1 with current main DB */
9968 root = new_root = txn->mt_dbs[MAIN_DBI].md_root;
9969 if (root != P_INVALID) {
9970 /* Count free pages + freeDB pages. Subtract from last_pg
9971 * to find the new last_pg, which also becomes the new root.
9973 MDB_ID freecount = 0;
9976 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
9977 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
9978 freecount += *(MDB_ID *)data.mv_data;
9979 if (rc != MDB_NOTFOUND)
9981 freecount += txn->mt_dbs[FREE_DBI].md_branch_pages +
9982 txn->mt_dbs[FREE_DBI].md_leaf_pages +
9983 txn->mt_dbs[FREE_DBI].md_overflow_pages;
9985 new_root = txn->mt_next_pgno - 1 - freecount;
9986 mm->mm_last_pg = new_root;
9987 mm->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
9988 mm->mm_dbs[MAIN_DBI].md_root = new_root;
9990 /* When the DB is empty, handle it specially to
9991 * fix any breakage like page leaks from ITS#8174.
9993 mm->mm_dbs[MAIN_DBI].md_flags = txn->mt_dbs[MAIN_DBI].md_flags;
9995 if (root != P_INVALID || mm->mm_dbs[MAIN_DBI].md_flags) {
9996 mm->mm_txnid = 1; /* use metapage 1 */
9999 my.mc_wlen[0] = env->me_psize * NUM_METAS;
10001 rc = mdb_env_cwalk(&my, &root, 0);
10002 if (rc == MDB_SUCCESS && root != new_root) {
10003 rc = MDB_INCOMPATIBLE; /* page leak or corrupt DB */
10009 mdb_env_cthr_toggle(&my, 1 | MDB_EOF);
10010 rc = THREAD_FINISH(thr);
10011 mdb_txn_abort(txn);
10015 if (my.mc_cond) CloseHandle(my.mc_cond);
10016 if (my.mc_mutex) CloseHandle(my.mc_mutex);
10017 _aligned_free(my.mc_wbuf[0]);
10019 pthread_cond_destroy(&my.mc_cond);
10020 pthread_mutex_destroy(&my.mc_mutex);
10021 free(my.mc_wbuf[0]);
10023 return rc ? rc : my.mc_error;
10026 /** Copy environment as-is. */
10028 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
10030 MDB_txn *txn = NULL;
10031 mdb_mutexref_t wmutex = NULL;
10033 mdb_size_t wsize, w3;
10037 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
10041 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
10044 /* Do the lock/unlock of the reader mutex before starting the
10045 * write txn. Otherwise other read txns could block writers.
10047 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
10051 if (env->me_txns) {
10052 /* We must start the actual read txn after blocking writers */
10053 mdb_txn_end(txn, MDB_END_RESET_TMP);
10055 /* Temporarily block writers until we snapshot the meta pages */
10056 wmutex = env->me_wmutex;
10057 if (LOCK_MUTEX(rc, env, wmutex))
10060 rc = mdb_txn_renew0(txn);
10062 UNLOCK_MUTEX(wmutex);
10067 wsize = env->me_psize * NUM_METAS;
10071 DO_WRITE(rc, fd, ptr, w2, len);
10075 } else if (len > 0) {
10081 /* Non-blocking or async handles are not supported */
10087 UNLOCK_MUTEX(wmutex);
10092 w3 = txn->mt_next_pgno * env->me_psize;
10094 mdb_size_t fsize = 0;
10095 if ((rc = mdb_fsize(env->me_fd, &fsize)))
10100 wsize = w3 - wsize;
10101 while (wsize > 0) {
10102 if (wsize > MAX_WRITE)
10106 DO_WRITE(rc, fd, ptr, w2, len);
10110 } else if (len > 0) {
10122 mdb_txn_abort(txn);
10127 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
10129 if (flags & MDB_CP_COMPACT)
10130 return mdb_env_copyfd1(env, fd);
10132 return mdb_env_copyfd0(env, fd);
10136 mdb_env_copyfd(MDB_env *env, HANDLE fd)
10138 return mdb_env_copyfd2(env, fd, 0);
10142 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
10146 HANDLE newfd = INVALID_HANDLE_VALUE;
10151 if (env->me_flags & MDB_NOSUBDIR) {
10152 lpath = (char *)path;
10154 len = strlen(path);
10155 len += sizeof(DATANAME);
10156 lpath = malloc(len);
10159 sprintf(lpath, "%s" DATANAME, path);
10162 /* The destination path must exist, but the destination file must not.
10163 * We don't want the OS to cache the writes, since the source data is
10164 * already in the OS cache.
10167 rc = utf8_to_utf16(lpath, -1, &wpath, NULL);
10170 newfd = CreateFileW(wpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
10171 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
10174 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
10176 if (newfd == INVALID_HANDLE_VALUE) {
10181 if (env->me_psize >= env->me_os_psize) {
10183 /* Set O_DIRECT if the file system supports it */
10184 if ((rc = fcntl(newfd, F_GETFL)) != -1)
10185 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
10187 #ifdef F_NOCACHE /* __APPLE__ */
10188 rc = fcntl(newfd, F_NOCACHE, 1);
10196 rc = mdb_env_copyfd2(env, newfd, flags);
10199 if (!(env->me_flags & MDB_NOSUBDIR))
10201 if (newfd != INVALID_HANDLE_VALUE)
10202 if (close(newfd) < 0 && rc == MDB_SUCCESS)
10209 mdb_env_copy(MDB_env *env, const char *path)
10211 return mdb_env_copy2(env, path, 0);
10215 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
10217 if (flag & ~CHANGEABLE)
10220 env->me_flags |= flag;
10222 env->me_flags &= ~flag;
10223 return MDB_SUCCESS;
10227 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
10232 *arg = env->me_flags & (CHANGEABLE|CHANGELESS);
10233 return MDB_SUCCESS;
10237 mdb_env_set_userctx(MDB_env *env, void *ctx)
10241 env->me_userctx = ctx;
10242 return MDB_SUCCESS;
10246 mdb_env_get_userctx(MDB_env *env)
10248 return env ? env->me_userctx : NULL;
10252 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
10257 env->me_assert_func = func;
10259 return MDB_SUCCESS;
10263 mdb_env_get_path(MDB_env *env, const char **arg)
10268 *arg = env->me_path;
10269 return MDB_SUCCESS;
10273 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
10279 return MDB_SUCCESS;
10282 /** Common code for #mdb_stat() and #mdb_env_stat().
10283 * @param[in] env the environment to operate in.
10284 * @param[in] db the #MDB_db record containing the stats to return.
10285 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
10286 * @return 0, this function always succeeds.
10289 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
10291 arg->ms_psize = env->me_psize;
10292 arg->ms_depth = db->md_depth;
10293 arg->ms_branch_pages = db->md_branch_pages;
10294 arg->ms_leaf_pages = db->md_leaf_pages;
10295 arg->ms_overflow_pages = db->md_overflow_pages;
10296 arg->ms_entries = db->md_entries;
10298 return MDB_SUCCESS;
10302 mdb_env_stat(MDB_env *env, MDB_stat *arg)
10306 if (env == NULL || arg == NULL)
10309 meta = mdb_env_pick_meta(env);
10311 return mdb_stat0(env, &meta->mm_dbs[MAIN_DBI], arg);
10315 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
10319 if (env == NULL || arg == NULL)
10322 meta = mdb_env_pick_meta(env);
10323 arg->me_mapaddr = meta->mm_address;
10324 arg->me_last_pgno = meta->mm_last_pg;
10325 arg->me_last_txnid = meta->mm_txnid;
10327 arg->me_mapsize = env->me_mapsize;
10328 arg->me_maxreaders = env->me_maxreaders;
10329 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : 0;
10330 return MDB_SUCCESS;
10333 /** Set the default comparison functions for a database.
10334 * Called immediately after a database is opened to set the defaults.
10335 * The user can then override them with #mdb_set_compare() or
10336 * #mdb_set_dupsort().
10337 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
10338 * @param[in] dbi A database handle returned by #mdb_dbi_open()
10341 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
10343 uint16_t f = txn->mt_dbs[dbi].md_flags;
10345 txn->mt_dbxs[dbi].md_cmp =
10346 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
10347 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
10349 txn->mt_dbxs[dbi].md_dcmp =
10350 !(f & MDB_DUPSORT) ? 0 :
10351 ((f & MDB_INTEGERDUP)
10352 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
10353 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
10356 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
10362 int rc, dbflag, exact;
10363 unsigned int unused = 0, seq;
10367 if (flags & ~VALID_FLAGS)
10369 if (txn->mt_flags & MDB_TXN_BLOCKED)
10370 return MDB_BAD_TXN;
10375 if (flags & PERSISTENT_FLAGS) {
10376 uint16_t f2 = flags & PERSISTENT_FLAGS;
10377 /* make sure flag changes get committed */
10378 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
10379 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
10380 txn->mt_flags |= MDB_TXN_DIRTY;
10383 mdb_default_cmp(txn, MAIN_DBI);
10384 return MDB_SUCCESS;
10387 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
10388 mdb_default_cmp(txn, MAIN_DBI);
10391 /* Is the DB already open? */
10392 len = strlen(name);
10393 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
10394 if (!txn->mt_dbxs[i].md_name.mv_size) {
10395 /* Remember this free slot */
10396 if (!unused) unused = i;
10399 if (len == txn->mt_dbxs[i].md_name.mv_size &&
10400 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
10402 return MDB_SUCCESS;
10406 /* If no free slot and max hit, fail */
10407 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
10408 return MDB_DBS_FULL;
10410 /* Cannot mix named databases with some mainDB flags */
10411 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
10412 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
10414 /* Find the DB info */
10415 dbflag = DB_NEW|DB_VALID|DB_USRVALID;
10418 key.mv_data = (void *)name;
10419 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
10420 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
10421 if (rc == MDB_SUCCESS) {
10422 /* make sure this is actually a DB */
10423 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
10424 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
10425 return MDB_INCOMPATIBLE;
10426 } else if (! (rc == MDB_NOTFOUND && (flags & MDB_CREATE))) {
10430 /* Done here so we cannot fail after creating a new DB */
10431 if ((namedup = strdup(name)) == NULL)
10435 /* MDB_NOTFOUND and MDB_CREATE: Create new DB */
10436 data.mv_size = sizeof(MDB_db);
10437 data.mv_data = &dummy;
10438 memset(&dummy, 0, sizeof(dummy));
10439 dummy.md_root = P_INVALID;
10440 dummy.md_flags = flags & PERSISTENT_FLAGS;
10441 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
10442 dbflag |= DB_DIRTY;
10448 /* Got info, register DBI in this txn */
10449 unsigned int slot = unused ? unused : txn->mt_numdbs;
10450 txn->mt_dbxs[slot].md_name.mv_data = namedup;
10451 txn->mt_dbxs[slot].md_name.mv_size = len;
10452 txn->mt_dbxs[slot].md_rel = NULL;
10453 txn->mt_dbflags[slot] = dbflag;
10454 /* txn-> and env-> are the same in read txns, use
10455 * tmp variable to avoid undefined assignment
10457 seq = ++txn->mt_env->me_dbiseqs[slot];
10458 txn->mt_dbiseqs[slot] = seq;
10460 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
10462 mdb_default_cmp(txn, slot);
10472 mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
10474 if (!arg || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
10477 if (txn->mt_flags & MDB_TXN_BLOCKED)
10478 return MDB_BAD_TXN;
10480 if (txn->mt_dbflags[dbi] & DB_STALE) {
10483 /* Stale, must read the DB's root. cursor_init does it for us. */
10484 mdb_cursor_init(&mc, txn, dbi, &mx);
10486 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
10489 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
10492 if (dbi < CORE_DBS || dbi >= env->me_maxdbs)
10494 ptr = env->me_dbxs[dbi].md_name.mv_data;
10495 /* If there was no name, this was already closed */
10497 env->me_dbxs[dbi].md_name.mv_data = NULL;
10498 env->me_dbxs[dbi].md_name.mv_size = 0;
10499 env->me_dbflags[dbi] = 0;
10500 env->me_dbiseqs[dbi]++;
10505 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
10507 /* We could return the flags for the FREE_DBI too but what's the point? */
10508 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10510 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
10511 return MDB_SUCCESS;
10514 /** Add all the DB's pages to the free list.
10515 * @param[in] mc Cursor on the DB to free.
10516 * @param[in] subs non-Zero to check for sub-DBs in this DB.
10517 * @return 0 on success, non-zero on failure.
10520 mdb_drop0(MDB_cursor *mc, int subs)
10524 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
10525 if (rc == MDB_SUCCESS) {
10526 MDB_txn *txn = mc->mc_txn;
10531 /* DUPSORT sub-DBs have no ovpages/DBs. Omit scanning leaves.
10532 * This also avoids any P_LEAF2 pages, which have no nodes.
10533 * Also if the DB doesn't have sub-DBs and has no overflow
10534 * pages, omit scanning leaves.
10536 if ((mc->mc_flags & C_SUB) ||
10537 (!subs && !mc->mc_db->md_overflow_pages))
10538 mdb_cursor_pop(mc);
10540 mdb_cursor_copy(mc, &mx);
10542 /* bump refcount for mx's pages */
10543 for (i=0; i<mc->mc_snum; i++)
10544 mdb_page_get(&mx, mc->mc_pg[i]->mp_pgno, &mx.mc_pg[i], NULL);
10546 while (mc->mc_snum > 0) {
10547 MDB_page *mp = mc->mc_pg[mc->mc_top];
10548 unsigned n = NUMKEYS(mp);
10550 for (i=0; i<n; i++) {
10551 ni = NODEPTR(mp, i);
10552 if (ni->mn_flags & F_BIGDATA) {
10555 memcpy(&pg, NODEDATA(ni), sizeof(pg));
10556 rc = mdb_page_get(mc, pg, &omp, NULL);
10559 mdb_cassert(mc, IS_OVERFLOW(omp));
10560 rc = mdb_midl_append_range(&txn->mt_free_pgs,
10561 pg, omp->mp_pages);
10564 mc->mc_db->md_overflow_pages -= omp->mp_pages;
10565 if (!mc->mc_db->md_overflow_pages && !subs)
10567 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
10568 mdb_xcursor_init1(mc, ni);
10569 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
10574 if (!subs && !mc->mc_db->md_overflow_pages)
10577 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
10579 for (i=0; i<n; i++) {
10581 ni = NODEPTR(mp, i);
10584 mdb_midl_xappend(txn->mt_free_pgs, pg);
10589 mc->mc_ki[mc->mc_top] = i;
10590 rc = mdb_cursor_sibling(mc, 1);
10592 if (rc != MDB_NOTFOUND)
10594 /* no more siblings, go back to beginning
10595 * of previous level.
10598 mdb_cursor_pop(mc);
10600 for (i=1; i<mc->mc_snum; i++) {
10602 mc->mc_pg[i] = mx.mc_pg[i];
10607 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
10610 txn->mt_flags |= MDB_TXN_ERROR;
10612 /* drop refcount for mx's pages */
10613 mdb_cursor_unref(&mx);
10615 } else if (rc == MDB_NOTFOUND) {
10618 mc->mc_flags &= ~C_INITIALIZED;
10622 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
10624 MDB_cursor *mc, *m2;
10627 if ((unsigned)del > 1 || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10630 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
10633 if (TXN_DBI_CHANGED(txn, dbi))
10634 return MDB_BAD_DBI;
10636 rc = mdb_cursor_open(txn, dbi, &mc);
10640 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
10641 /* Invalidate the dropped DB's cursors */
10642 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
10643 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
10647 /* Can't delete the main DB */
10648 if (del && dbi >= CORE_DBS) {
10649 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, F_SUBDATA);
10651 txn->mt_dbflags[dbi] = DB_STALE;
10652 mdb_dbi_close(txn->mt_env, dbi);
10654 txn->mt_flags |= MDB_TXN_ERROR;
10657 /* reset the DB record, mark it dirty */
10658 txn->mt_dbflags[dbi] |= DB_DIRTY;
10659 txn->mt_dbs[dbi].md_depth = 0;
10660 txn->mt_dbs[dbi].md_branch_pages = 0;
10661 txn->mt_dbs[dbi].md_leaf_pages = 0;
10662 txn->mt_dbs[dbi].md_overflow_pages = 0;
10663 txn->mt_dbs[dbi].md_entries = 0;
10664 txn->mt_dbs[dbi].md_root = P_INVALID;
10666 txn->mt_flags |= MDB_TXN_DIRTY;
10669 mdb_cursor_close(mc);
10673 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
10675 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10678 txn->mt_dbxs[dbi].md_cmp = cmp;
10679 return MDB_SUCCESS;
10682 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
10684 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10687 txn->mt_dbxs[dbi].md_dcmp = cmp;
10688 return MDB_SUCCESS;
10691 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
10693 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10696 txn->mt_dbxs[dbi].md_rel = rel;
10697 return MDB_SUCCESS;
10700 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
10702 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10705 txn->mt_dbxs[dbi].md_relctx = ctx;
10706 return MDB_SUCCESS;
10710 mdb_env_get_maxkeysize(MDB_env *env)
10712 return ENV_MAXKEY(env);
10716 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
10718 unsigned int i, rdrs;
10721 int rc = 0, first = 1;
10725 if (!env->me_txns) {
10726 return func("(no reader locks)\n", ctx);
10728 rdrs = env->me_txns->mti_numreaders;
10729 mr = env->me_txns->mti_readers;
10730 for (i=0; i<rdrs; i++) {
10731 if (mr[i].mr_pid) {
10732 txnid_t txnid = mr[i].mr_txnid;
10733 sprintf(buf, txnid == (txnid_t)-1 ?
10734 "%10d %"Z"x -\n" : "%10d %"Z"x %"Y"u\n",
10735 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
10738 rc = func(" pid thread txnid\n", ctx);
10742 rc = func(buf, ctx);
10748 rc = func("(no active readers)\n", ctx);
10753 /** Insert pid into list if not already present.
10754 * return -1 if already present.
10757 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
10759 /* binary search of pid in list */
10761 unsigned cursor = 1;
10763 unsigned n = ids[0];
10766 unsigned pivot = n >> 1;
10767 cursor = base + pivot + 1;
10768 val = pid - ids[cursor];
10773 } else if ( val > 0 ) {
10778 /* found, so it's a duplicate */
10787 for (n = ids[0]; n > cursor; n--)
10794 mdb_reader_check(MDB_env *env, int *dead)
10800 return env->me_txns ? mdb_reader_check0(env, 0, dead) : MDB_SUCCESS;
10803 /** As #mdb_reader_check(). rlocked = <caller locked the reader mutex>. */
10805 mdb_reader_check0(MDB_env *env, int rlocked, int *dead)
10807 mdb_mutexref_t rmutex = rlocked ? NULL : env->me_rmutex;
10808 unsigned int i, j, rdrs;
10810 MDB_PID_T *pids, pid;
10811 int rc = MDB_SUCCESS, count = 0;
10813 rdrs = env->me_txns->mti_numreaders;
10814 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
10818 mr = env->me_txns->mti_readers;
10819 for (i=0; i<rdrs; i++) {
10820 pid = mr[i].mr_pid;
10821 if (pid && pid != env->me_pid) {
10822 if (mdb_pid_insert(pids, pid) == 0) {
10823 if (!mdb_reader_pid(env, Pidcheck, pid)) {
10824 /* Stale reader found */
10827 if ((rc = LOCK_MUTEX0(rmutex)) != 0) {
10828 if ((rc = mdb_mutex_failed(env, rmutex, rc)))
10830 rdrs = 0; /* the above checked all readers */
10832 /* Recheck, a new process may have reused pid */
10833 if (mdb_reader_pid(env, Pidcheck, pid))
10837 for (; j<rdrs; j++)
10838 if (mr[j].mr_pid == pid) {
10839 DPRINTF(("clear stale reader pid %u txn %"Y"d",
10840 (unsigned) pid, mr[j].mr_txnid));
10845 UNLOCK_MUTEX(rmutex);
10856 #ifdef MDB_ROBUST_SUPPORTED
10857 /** Handle #LOCK_MUTEX0() failure.
10858 * Try to repair the lock file if the mutex owner died.
10859 * @param[in] env the environment handle
10860 * @param[in] mutex LOCK_MUTEX0() mutex
10861 * @param[in] rc LOCK_MUTEX0() error (nonzero)
10862 * @return 0 on success with the mutex locked, or an error code on failure.
10865 mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc)
10870 if (rc == MDB_OWNERDEAD) {
10871 /* We own the mutex. Clean up after dead previous owner. */
10873 rlocked = (mutex == env->me_rmutex);
10875 /* Keep mti_txnid updated, otherwise next writer can
10876 * overwrite data which latest meta page refers to.
10878 meta = mdb_env_pick_meta(env);
10879 env->me_txns->mti_txnid = meta->mm_txnid;
10880 /* env is hosed if the dead thread was ours */
10882 env->me_flags |= MDB_FATAL_ERROR;
10883 env->me_txn = NULL;
10887 DPRINTF(("%cmutex owner died, %s", (rlocked ? 'r' : 'w'),
10888 (rc ? "this process' env is hosed" : "recovering")));
10889 rc2 = mdb_reader_check0(env, rlocked, NULL);
10891 rc2 = mdb_mutex_consistent(mutex);
10892 if (rc || (rc = rc2)) {
10893 DPRINTF(("LOCK_MUTEX recovery failed, %s", mdb_strerror(rc)));
10894 UNLOCK_MUTEX(mutex);
10900 DPRINTF(("LOCK_MUTEX failed, %s", mdb_strerror(rc)));
10905 #endif /* MDB_ROBUST_SUPPORTED */
10908 #if defined(_WIN32)
10909 static int utf8_to_utf16(const char *src, int srcsize, wchar_t **dst, int *dstsize)
10913 need = MultiByteToWideChar(CP_UTF8, 0, src, srcsize, NULL, 0);
10914 if (need == 0xFFFD)
10918 result = malloc(sizeof(wchar_t) * need);
10921 MultiByteToWideChar(CP_UTF8, 0, src, srcsize, result, need);
10927 #endif /* defined(_WIN32) */