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 || MDB_SIZE_MAX%UINT_MAX
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
359 #define THREAD_RET void *
360 #define THREAD_CREATE(thr,start,arg) pthread_create(&thr,NULL,start,arg)
361 #define THREAD_FINISH(thr) pthread_join(thr,NULL)
363 /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
364 #define MDB_PIDLOCK 1
366 #ifdef MDB_USE_POSIX_SEM
368 typedef sem_t *mdb_mutex_t, *mdb_mutexref_t;
369 #define LOCK_MUTEX0(mutex) mdb_sem_wait(mutex)
370 #define UNLOCK_MUTEX(mutex) sem_post(mutex)
373 mdb_sem_wait(sem_t *sem)
376 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
380 #elif defined MDB_USE_SYSV_SEM
382 typedef struct mdb_mutex {
386 } mdb_mutex_t[1], *mdb_mutexref_t;
388 #define LOCK_MUTEX0(mutex) mdb_sem_wait(mutex)
389 #define UNLOCK_MUTEX(mutex) do { \
390 struct sembuf sb = { 0, 1, SEM_UNDO }; \
391 sb.sem_num = (mutex)->semnum; \
392 *(mutex)->locked = 0; \
393 semop((mutex)->semid, &sb, 1); \
397 mdb_sem_wait(mdb_mutexref_t sem)
399 int rc, *locked = sem->locked;
400 struct sembuf sb = { 0, -1, SEM_UNDO };
401 sb.sem_num = sem->semnum;
403 if (!semop(sem->semid, &sb, 1)) {
404 rc = *locked ? MDB_OWNERDEAD : MDB_SUCCESS;
408 } while ((rc = errno) == EINTR);
412 #define mdb_mutex_consistent(mutex) 0
414 #else /* MDB_USE_POSIX_MUTEX: */
415 /** Shared mutex/semaphore as it is stored (mdb_mutex_t), and as
416 * local variables keep it (mdb_mutexref_t).
418 * An mdb_mutex_t can be assigned to an mdb_mutexref_t. They can
419 * be the same, or an array[size 1] and a pointer.
422 typedef pthread_mutex_t mdb_mutex_t[1], *mdb_mutexref_t;
424 /** Lock the reader or writer mutex.
425 * Returns 0 or a code to give #mdb_mutex_failed(), as in #LOCK_MUTEX().
427 #define LOCK_MUTEX0(mutex) pthread_mutex_lock(mutex)
428 /** Unlock the reader or writer mutex.
430 #define UNLOCK_MUTEX(mutex) pthread_mutex_unlock(mutex)
431 /** Mark mutex-protected data as repaired, after death of previous owner.
433 #define mdb_mutex_consistent(mutex) pthread_mutex_consistent(mutex)
434 #endif /* MDB_USE_POSIX_SEM || MDB_USE_SYSV_SEM */
436 /** Get the error code for the last failed system function.
438 #define ErrCode() errno
440 /** An abstraction for a file handle.
441 * On POSIX systems file handles are small integers. On Windows
442 * they're opaque pointers.
446 /** A value for an invalid file handle.
447 * Mainly used to initialize file variables and signify that they are
450 #define INVALID_HANDLE_VALUE (-1)
452 /** Get the size of a memory page for the system.
453 * This is the basic size that the platform's memory manager uses, and is
454 * fundamental to the use of memory-mapped files.
456 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
459 #define Z MDB_FMT_Z /**< printf/scanf format modifier for size_t */
460 #define Yu MDB_PRIy(u) /**< printf format for #mdb_size_t */
461 #define Yd MDB_PRIy(d) /**< printf format for "signed #mdb_size_t" */
463 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
465 #elif defined(MDB_USE_SYSV_SEM)
466 #define MNAME_LEN (sizeof(int))
468 #define MNAME_LEN (sizeof(pthread_mutex_t))
471 #ifdef MDB_USE_SYSV_SEM
472 #define SYSV_SEM_FLAG 1 /**< SysV sems in lockfile format */
474 #define SYSV_SEM_FLAG 0
479 #ifdef MDB_ROBUST_SUPPORTED
480 /** Lock mutex, handle any error, set rc = result.
481 * Return 0 on success, nonzero (not rc) on error.
483 #define LOCK_MUTEX(rc, env, mutex) \
484 (((rc) = LOCK_MUTEX0(mutex)) && \
485 ((rc) = mdb_mutex_failed(env, mutex, rc)))
486 static int mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc);
488 #define LOCK_MUTEX(rc, env, mutex) ((rc) = LOCK_MUTEX0(mutex))
489 #define mdb_mutex_failed(env, mutex, rc) (rc)
493 /** A flag for opening a file and requesting synchronous data writes.
494 * This is only used when writing a meta page. It's not strictly needed;
495 * we could just do a normal write and then immediately perform a flush.
496 * But if this flag is available it saves us an extra system call.
498 * @note If O_DSYNC is undefined but exists in /usr/include,
499 * preferably set some compiler flag to get the definition.
503 # define MDB_DSYNC O_DSYNC
505 # define MDB_DSYNC O_SYNC
510 /** Function for flushing the data of a file. Define this to fsync
511 * if fdatasync() is not supported.
513 #ifndef MDB_FDATASYNC
514 # define MDB_FDATASYNC fdatasync
518 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
529 /** A page number in the database.
530 * Note that 64 bit page numbers are overkill, since pages themselves
531 * already represent 12-13 bits of addressable memory, and the OS will
532 * always limit applications to a maximum of 63 bits of address space.
534 * @note In the #MDB_node structure, we only store 48 bits of this value,
535 * which thus limits us to only 60 bits of addressable data.
537 typedef MDB_ID pgno_t;
539 /** A transaction ID.
540 * See struct MDB_txn.mt_txnid for details.
542 typedef MDB_ID txnid_t;
544 /** @defgroup debug Debug Macros
548 /** Enable debug output. Needs variable argument macros (a C99 feature).
549 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
550 * read from and written to the database (used for free space management).
556 static int mdb_debug;
557 static txnid_t mdb_debug_start;
559 /** Print a debug message with printf formatting.
560 * Requires double parenthesis around 2 or more args.
562 # define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
563 # define DPRINTF0(fmt, ...) \
564 fprintf(stderr, "%s:%d " fmt "\n", mdb_func_, __LINE__, __VA_ARGS__)
566 # define DPRINTF(args) ((void) 0)
568 /** Print a debug string.
569 * The string is printed literally, with no format processing.
571 #define DPUTS(arg) DPRINTF(("%s", arg))
572 /** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
574 (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
577 /** @brief The maximum size of a database page.
579 * It is 32k or 64k, since value-PAGEBASE must fit in
580 * #MDB_page.%mp_upper.
582 * LMDB will use database pages < OS pages if needed.
583 * That causes more I/O in write transactions: The OS must
584 * know (read) the whole page before writing a partial page.
586 * Note that we don't currently support Huge pages. On Linux,
587 * regular data files cannot use Huge pages, and in general
588 * Huge pages aren't actually pageable. We rely on the OS
589 * demand-pager to read our data and page it out when memory
590 * pressure from other processes is high. So until OSs have
591 * actual paging support for Huge pages, they're not viable.
593 #define MAX_PAGESIZE (PAGEBASE ? 0x10000 : 0x8000)
595 /** The minimum number of keys required in a database page.
596 * Setting this to a larger value will place a smaller bound on the
597 * maximum size of a data item. Data items larger than this size will
598 * be pushed into overflow pages instead of being stored directly in
599 * the B-tree node. This value used to default to 4. With a page size
600 * of 4096 bytes that meant that any item larger than 1024 bytes would
601 * go into an overflow page. That also meant that on average 2-3KB of
602 * each overflow page was wasted space. The value cannot be lower than
603 * 2 because then there would no longer be a tree structure. With this
604 * value, items larger than 2KB will go into overflow pages, and on
605 * average only 1KB will be wasted.
607 #define MDB_MINKEYS 2
609 /** A stamp that identifies a file as an LMDB file.
610 * There's nothing special about this value other than that it is easily
611 * recognizable, and it will reflect any byte order mismatches.
613 #define MDB_MAGIC 0xBEEFC0DE
615 /** The version number for a database's datafile format. */
616 #define MDB_DATA_VERSION ((MDB_DEVEL) ? 999 : 1)
617 /** The version number for a database's lockfile format. */
618 #define MDB_LOCK_VERSION ((MDB_DEVEL) ? 999 : 1)
620 /** @brief The max size of a key we can write, or 0 for computed max.
622 * This macro should normally be left alone or set to 0.
623 * Note that a database with big keys or dupsort data cannot be
624 * reliably modified by a liblmdb which uses a smaller max.
625 * The default is 511 for backwards compat, or 0 when #MDB_DEVEL.
627 * Other values are allowed, for backwards compat. However:
628 * A value bigger than the computed max can break if you do not
629 * know what you are doing, and liblmdb <= 0.9.10 can break when
630 * modifying a DB with keys/dupsort data bigger than its max.
632 * Data items in an #MDB_DUPSORT database are also limited to
633 * this size, since they're actually keys of a sub-DB. Keys and
634 * #MDB_DUPSORT data items must fit on a node in a regular page.
636 #ifndef MDB_MAXKEYSIZE
637 #define MDB_MAXKEYSIZE ((MDB_DEVEL) ? 0 : 511)
640 /** The maximum size of a key we can write to the environment. */
642 #define ENV_MAXKEY(env) (MDB_MAXKEYSIZE)
644 #define ENV_MAXKEY(env) ((env)->me_maxkey)
647 /** @brief The maximum size of a data item.
649 * We only store a 32 bit value for node sizes.
651 #define MAXDATASIZE 0xffffffffUL
654 /** Key size which fits in a #DKBUF.
657 #define DKBUF_MAXKEYSIZE ((MDB_MAXKEYSIZE) > 0 ? (MDB_MAXKEYSIZE) : 511)
660 * This is used for printing a hex dump of a key's contents.
662 #define DKBUF char kbuf[DKBUF_MAXKEYSIZE*2+1]
663 /** Display a key in hex.
665 * Invoke a function to display a key in hex.
667 #define DKEY(x) mdb_dkey(x, kbuf)
673 /** An invalid page number.
674 * Mainly used to denote an empty tree.
676 #define P_INVALID (~(pgno_t)0)
678 /** Test if the flags \b f are set in a flag word \b w. */
679 #define F_ISSET(w, f) (((w) & (f)) == (f))
681 /** Round \b n up to an even number. */
682 #define EVEN(n) (((n) + 1U) & -2) /* sign-extending -2 to match n+1U */
684 /** Used for offsets within a single page.
685 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
688 typedef uint16_t indx_t;
690 /** Default size of memory map.
691 * This is certainly too small for any actual applications. Apps should always set
692 * the size explicitly using #mdb_env_set_mapsize().
694 #define DEFAULT_MAPSIZE 1048576
696 /** @defgroup readers Reader Lock Table
697 * Readers don't acquire any locks for their data access. Instead, they
698 * simply record their transaction ID in the reader table. The reader
699 * mutex is needed just to find an empty slot in the reader table. The
700 * slot's address is saved in thread-specific data so that subsequent read
701 * transactions started by the same thread need no further locking to proceed.
703 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
705 * No reader table is used if the database is on a read-only filesystem, or
706 * if #MDB_NOLOCK is set.
708 * Since the database uses multi-version concurrency control, readers don't
709 * actually need any locking. This table is used to keep track of which
710 * readers are using data from which old transactions, so that we'll know
711 * when a particular old transaction is no longer in use. Old transactions
712 * that have discarded any data pages can then have those pages reclaimed
713 * for use by a later write transaction.
715 * The lock table is constructed such that reader slots are aligned with the
716 * processor's cache line size. Any slot is only ever used by one thread.
717 * This alignment guarantees that there will be no contention or cache
718 * thrashing as threads update their own slot info, and also eliminates
719 * any need for locking when accessing a slot.
721 * A writer thread will scan every slot in the table to determine the oldest
722 * outstanding reader transaction. Any freed pages older than this will be
723 * reclaimed by the writer. The writer doesn't use any locks when scanning
724 * this table. This means that there's no guarantee that the writer will
725 * see the most up-to-date reader info, but that's not required for correct
726 * operation - all we need is to know the upper bound on the oldest reader,
727 * we don't care at all about the newest reader. So the only consequence of
728 * reading stale information here is that old pages might hang around a
729 * while longer before being reclaimed. That's actually good anyway, because
730 * the longer we delay reclaiming old pages, the more likely it is that a
731 * string of contiguous pages can be found after coalescing old pages from
732 * many old transactions together.
735 /** Number of slots in the reader table.
736 * This value was chosen somewhat arbitrarily. 126 readers plus a
737 * couple mutexes fit exactly into 8KB on my development machine.
738 * Applications should set the table size using #mdb_env_set_maxreaders().
740 #define DEFAULT_READERS 126
742 /** The size of a CPU cache line in bytes. We want our lock structures
743 * aligned to this size to avoid false cache line sharing in the
745 * This value works for most CPUs. For Itanium this should be 128.
751 /** The information we store in a single slot of the reader table.
752 * In addition to a transaction ID, we also record the process and
753 * thread ID that owns a slot, so that we can detect stale information,
754 * e.g. threads or processes that went away without cleaning up.
755 * @note We currently don't check for stale records. We simply re-init
756 * the table when we know that we're the only process opening the
759 typedef struct MDB_rxbody {
760 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
761 * Multiple readers that start at the same time will probably have the
762 * same ID here. Again, it's not important to exclude them from
763 * anything; all we need to know is which version of the DB they
764 * started from so we can avoid overwriting any data used in that
765 * particular version.
767 volatile txnid_t mrb_txnid;
768 /** The process ID of the process owning this reader txn. */
769 volatile MDB_PID_T mrb_pid;
770 /** The thread ID of the thread owning this txn. */
771 volatile MDB_THR_T mrb_tid;
774 /** The actual reader record, with cacheline padding. */
775 typedef struct MDB_reader {
778 /** shorthand for mrb_txnid */
779 #define mr_txnid mru.mrx.mrb_txnid
780 #define mr_pid mru.mrx.mrb_pid
781 #define mr_tid mru.mrx.mrb_tid
782 /** cache line alignment */
783 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
787 /** The header for the reader table.
788 * The table resides in a memory-mapped file. (This is a different file
789 * than is used for the main database.)
791 * For POSIX the actual mutexes reside in the shared memory of this
792 * mapped file. On Windows, mutexes are named objects allocated by the
793 * kernel; we store the mutex names in this mapped file so that other
794 * processes can grab them. This same approach is also used on
795 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
796 * process-shared POSIX mutexes. For these cases where a named object
797 * is used, the object name is derived from a 64 bit FNV hash of the
798 * environment pathname. As such, naming collisions are extremely
799 * unlikely. If a collision occurs, the results are unpredictable.
801 typedef struct MDB_txbody {
802 /** Stamp identifying this as an LMDB file. It must be set
805 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
807 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
808 char mtb_rmname[MNAME_LEN];
809 #elif defined(MDB_USE_SYSV_SEM)
813 /** Mutex protecting access to this table.
814 * This is the reader table lock used with LOCK_MUTEX().
816 mdb_mutex_t mtb_rmutex;
818 /** The ID of the last transaction committed to the database.
819 * This is recorded here only for convenience; the value can always
820 * be determined by reading the main database meta pages.
822 volatile txnid_t mtb_txnid;
823 /** The number of slots that have been used in the reader table.
824 * This always records the maximum count, it is not decremented
825 * when readers release their slots.
827 volatile unsigned mtb_numreaders;
830 /** The actual reader table definition. */
831 typedef struct MDB_txninfo {
834 #define mti_magic mt1.mtb.mtb_magic
835 #define mti_format mt1.mtb.mtb_format
836 #define mti_rmutex mt1.mtb.mtb_rmutex
837 #define mti_rmname mt1.mtb.mtb_rmname
838 #define mti_txnid mt1.mtb.mtb_txnid
839 #define mti_numreaders mt1.mtb.mtb_numreaders
840 #ifdef MDB_USE_SYSV_SEM
841 #define mti_semid mt1.mtb.mtb_semid
842 #define mti_rlocked mt1.mtb.mtb_rlocked
844 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
847 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
848 char mt2_wmname[MNAME_LEN];
849 #define mti_wmname mt2.mt2_wmname
850 #elif defined MDB_USE_SYSV_SEM
852 #define mti_wlocked mt2.mt2_wlocked
854 mdb_mutex_t mt2_wmutex;
855 #define mti_wmutex mt2.mt2_wmutex
857 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
859 MDB_reader mti_readers[1];
862 /** Lockfile format signature: version, features and field layout */
863 #define MDB_LOCK_FORMAT \
865 ((MDB_LOCK_VERSION) \
866 /* Flags which describe functionality */ \
867 + (SYSV_SEM_FLAG << 18) \
868 + (((MDB_PIDLOCK) != 0) << 16)))
871 /** Common header for all page types.
872 * Overflow records occupy a number of contiguous pages with no
873 * headers on any page after the first.
875 typedef struct MDB_page {
876 #define mp_pgno mp_p.p_pgno
877 #define mp_next mp_p.p_next
879 pgno_t p_pgno; /**< page number */
880 struct MDB_page *p_next; /**< for in-memory list of freed pages */
883 /** @defgroup mdb_page Page Flags
885 * Flags for the page headers.
888 #define P_BRANCH 0x01 /**< branch page */
889 #define P_LEAF 0x02 /**< leaf page */
890 #define P_OVERFLOW 0x04 /**< overflow page */
891 #define P_META 0x08 /**< meta page */
892 #define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
893 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
894 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
895 #define P_LOOSE 0x4000 /**< page was dirtied then freed, can be reused */
896 #define P_KEEP 0x8000 /**< leave this page alone during spill */
898 uint16_t mp_flags; /**< @ref mdb_page */
899 #define mp_lower mp_pb.pb.pb_lower
900 #define mp_upper mp_pb.pb.pb_upper
901 #define mp_pages mp_pb.pb_pages
904 indx_t pb_lower; /**< lower bound of free space */
905 indx_t pb_upper; /**< upper bound of free space */
907 uint32_t pb_pages; /**< number of overflow pages */
909 indx_t mp_ptrs[1]; /**< dynamic size */
912 /** Size of the page header, excluding dynamic data at the end */
913 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
915 /** Address of first usable data byte in a page, after the header */
916 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
918 /** ITS#7713, change PAGEBASE to handle 65536 byte pages */
919 #define PAGEBASE ((MDB_DEVEL) ? PAGEHDRSZ : 0)
921 /** Number of nodes on a page */
922 #define NUMKEYS(p) (((p)->mp_lower - (PAGEHDRSZ-PAGEBASE)) >> 1)
924 /** The amount of space remaining in the page */
925 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
927 /** The percentage of space used in the page, in tenths of a percent. */
928 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
929 ((env)->me_psize - PAGEHDRSZ))
930 /** The minimum page fill factor, in tenths of a percent.
931 * Pages emptier than this are candidates for merging.
933 #define FILL_THRESHOLD 250
935 /** Test if a page is a leaf page */
936 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
937 /** Test if a page is a LEAF2 page */
938 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
939 /** Test if a page is a branch page */
940 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
941 /** Test if a page is an overflow page */
942 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
943 /** Test if a page is a sub page */
944 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
946 /** The number of overflow pages needed to store the given size. */
947 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
949 /** Link in #MDB_txn.%mt_loose_pgs list */
950 #define NEXT_LOOSE_PAGE(p) (*(MDB_page **)((p) + 2))
952 /** Header for a single key/data pair within a page.
953 * Used in pages of type #P_BRANCH and #P_LEAF without #P_LEAF2.
954 * We guarantee 2-byte alignment for 'MDB_node's.
956 typedef struct MDB_node {
957 /** lo and hi are used for data size on leaf nodes and for
958 * child pgno on branch nodes. On 64 bit platforms, flags
959 * is also used for pgno. (Branch nodes have no flags).
960 * They are in host byte order in case that lets some
961 * accesses be optimized into a 32-bit word access.
963 #if BYTE_ORDER == LITTLE_ENDIAN
964 unsigned short mn_lo, mn_hi; /**< part of data size or pgno */
966 unsigned short mn_hi, mn_lo;
968 /** @defgroup mdb_node Node Flags
970 * Flags for node headers.
973 #define F_BIGDATA 0x01 /**< data put on overflow page */
974 #define F_SUBDATA 0x02 /**< data is a sub-database */
975 #define F_DUPDATA 0x04 /**< data has duplicates */
977 /** valid flags for #mdb_node_add() */
978 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
981 unsigned short mn_flags; /**< @ref mdb_node */
982 unsigned short mn_ksize; /**< key size */
983 char mn_data[1]; /**< key and data are appended here */
986 /** Size of the node header, excluding dynamic data at the end */
987 #define NODESIZE offsetof(MDB_node, mn_data)
989 /** Bit position of top word in page number, for shifting mn_flags */
990 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
992 /** Size of a node in a branch page with a given key.
993 * This is just the node header plus the key, there is no data.
995 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
997 /** Size of a node in a leaf page with a given key and data.
998 * This is node header plus key plus data size.
1000 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
1002 /** Address of node \b i in page \b p */
1003 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i] + PAGEBASE))
1005 /** Address of the key for the node */
1006 #define NODEKEY(node) (void *)((node)->mn_data)
1008 /** Address of the data for a node */
1009 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
1011 /** Get the page number pointed to by a branch node */
1012 #define NODEPGNO(node) \
1013 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
1014 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
1015 /** Set the page number in a branch node */
1016 #define SETPGNO(node,pgno) do { \
1017 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
1018 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
1020 /** Get the size of the data in a leaf node */
1021 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
1022 /** Set the size of the data for a leaf node */
1023 #define SETDSZ(node,size) do { \
1024 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
1025 /** The size of a key in a node */
1026 #define NODEKSZ(node) ((node)->mn_ksize)
1028 /** Copy a page number from src to dst */
1029 #ifdef MISALIGNED_OK
1030 #define COPY_PGNO(dst,src) dst = src
1032 #if MDB_SIZE_MAX > 0xffffffffU
1033 #define COPY_PGNO(dst,src) do { \
1034 unsigned short *s, *d; \
1035 s = (unsigned short *)&(src); \
1036 d = (unsigned short *)&(dst); \
1043 #define COPY_PGNO(dst,src) do { \
1044 unsigned short *s, *d; \
1045 s = (unsigned short *)&(src); \
1046 d = (unsigned short *)&(dst); \
1052 /** The address of a key in a LEAF2 page.
1053 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
1054 * There are no node headers, keys are stored contiguously.
1056 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
1058 /** Set the \b node's key into \b keyptr, if requested. */
1059 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
1060 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
1062 /** Set the \b node's key into \b key. */
1063 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
1065 /** Information about a single database in the environment. */
1066 typedef struct MDB_db {
1067 uint32_t md_pad; /**< also ksize for LEAF2 pages */
1068 uint16_t md_flags; /**< @ref mdb_dbi_open */
1069 uint16_t md_depth; /**< depth of this tree */
1070 pgno_t md_branch_pages; /**< number of internal pages */
1071 pgno_t md_leaf_pages; /**< number of leaf pages */
1072 pgno_t md_overflow_pages; /**< number of overflow pages */
1073 mdb_size_t md_entries; /**< number of data items */
1074 pgno_t md_root; /**< the root page of this tree */
1077 /** mdb_dbi_open flags */
1078 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
1079 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
1080 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
1081 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
1083 /** Handle for the DB used to track free pages. */
1085 /** Handle for the default DB. */
1087 /** Number of DBs in metapage (free and main) - also hardcoded elsewhere */
1090 /** Number of meta pages - also hardcoded elsewhere */
1093 /** Meta page content.
1094 * A meta page is the start point for accessing a database snapshot.
1095 * Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
1097 typedef struct MDB_meta {
1098 /** Stamp identifying this as an LMDB file. It must be set
1101 /** Version number of this file. Must be set to #MDB_DATA_VERSION. */
1102 uint32_t mm_version;
1104 union { /* always zero since we don't support fixed mapping in MDB_VL32 */
1108 #define mm_address mm_un.mmun_address
1110 void *mm_address; /**< address for fixed mapping */
1112 pgno_t mm_mapsize; /**< size of mmap region */
1113 MDB_db mm_dbs[CORE_DBS]; /**< first is free space, 2nd is main db */
1114 /** The size of pages used in this DB */
1115 #define mm_psize mm_dbs[FREE_DBI].md_pad
1116 /** Any persistent environment flags. @ref mdb_env */
1117 #define mm_flags mm_dbs[FREE_DBI].md_flags
1118 pgno_t mm_last_pg; /**< last used page in file */
1119 volatile txnid_t mm_txnid; /**< txnid that committed this page */
1122 /** Buffer for a stack-allocated meta page.
1123 * The members define size and alignment, and silence type
1124 * aliasing warnings. They are not used directly; that could
1125 * mean incorrectly using several union members in parallel.
1127 typedef union MDB_metabuf {
1130 char mm_pad[PAGEHDRSZ];
1135 /** Auxiliary DB info.
1136 * The information here is mostly static/read-only. There is
1137 * only a single copy of this record in the environment.
1139 typedef struct MDB_dbx {
1140 MDB_val md_name; /**< name of the database */
1141 MDB_cmp_func *md_cmp; /**< function for comparing keys */
1142 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
1143 MDB_rel_func *md_rel; /**< user relocate function */
1144 void *md_relctx; /**< user-provided context for md_rel */
1147 /** A database transaction.
1148 * Every operation requires a transaction handle.
1151 MDB_txn *mt_parent; /**< parent of a nested txn */
1152 /** Nested txn under this txn, set together with flag #MDB_TXN_HAS_CHILD */
1154 pgno_t mt_next_pgno; /**< next unallocated page */
1156 pgno_t mt_last_pgno; /**< last written page */
1158 /** The ID of this transaction. IDs are integers incrementing from 1.
1159 * Only committed write transactions increment the ID. If a transaction
1160 * aborts, the ID may be re-used by the next writer.
1163 MDB_env *mt_env; /**< the DB environment */
1164 /** The list of pages that became unused during this transaction.
1166 MDB_IDL mt_free_pgs;
1167 /** The list of loose pages that became unused and may be reused
1168 * in this transaction, linked through #NEXT_LOOSE_PAGE(page).
1170 MDB_page *mt_loose_pgs;
1171 /* #Number of loose pages (#mt_loose_pgs) */
1173 /** The sorted list of dirty pages we temporarily wrote to disk
1174 * because the dirty list was full. page numbers in here are
1175 * shifted left by 1, deleted slots have the LSB set.
1177 MDB_IDL mt_spill_pgs;
1179 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
1180 MDB_ID2L dirty_list;
1181 /** For read txns: This thread/txn's reader table slot, or NULL. */
1184 /** Array of records for each DB known in the environment. */
1186 /** Array of MDB_db records for each known DB */
1188 /** Array of sequence numbers for each DB handle */
1189 unsigned int *mt_dbiseqs;
1190 /** @defgroup mt_dbflag Transaction DB Flags
1194 #define DB_DIRTY 0x01 /**< DB was modified or is DUPSORT data */
1195 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
1196 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
1197 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
1198 #define DB_USRVALID 0x10 /**< As #DB_VALID, but not set for #FREE_DBI */
1200 /** In write txns, array of cursors for each DB */
1201 MDB_cursor **mt_cursors;
1202 /** Array of flags for each DB */
1203 unsigned char *mt_dbflags;
1205 /** List of read-only pages (actually chunks) */
1207 /** We map chunks of 16 pages. Even though Windows uses 4KB pages, all
1208 * mappings must begin on 64KB boundaries. So we round off all pgnos to
1209 * a chunk boundary. We do the same on Linux for symmetry, and also to
1210 * reduce the frequency of mmap/munmap calls.
1212 #define MDB_RPAGE_CHUNK 16
1213 #define MDB_TRPAGE_SIZE 4096 /**< size of #mt_rpages array of chunks */
1214 #define MDB_TRPAGE_MAX (MDB_TRPAGE_SIZE-1) /**< maximum chunk index */
1215 unsigned int mt_rpcheck; /**< threshold for reclaiming unref'd chunks */
1217 /** Number of DB records in use, or 0 when the txn is finished.
1218 * This number only ever increments until the txn finishes; we
1219 * don't decrement it when individual DB handles are closed.
1223 /** @defgroup mdb_txn Transaction Flags
1227 /** #mdb_txn_begin() flags */
1228 #define MDB_TXN_BEGIN_FLAGS (MDB_NOMETASYNC|MDB_NOSYNC|MDB_RDONLY)
1229 #define MDB_TXN_NOMETASYNC MDB_NOMETASYNC /**< don't sync meta for this txn on commit */
1230 #define MDB_TXN_NOSYNC MDB_NOSYNC /**< don't sync this txn on commit */
1231 #define MDB_TXN_RDONLY MDB_RDONLY /**< read-only transaction */
1232 /* internal txn flags */
1233 #define MDB_TXN_WRITEMAP MDB_WRITEMAP /**< copy of #MDB_env flag in writers */
1234 #define MDB_TXN_FINISHED 0x01 /**< txn is finished or never began */
1235 #define MDB_TXN_ERROR 0x02 /**< txn is unusable after an error */
1236 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
1237 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
1238 #define MDB_TXN_HAS_CHILD 0x10 /**< txn has an #MDB_txn.%mt_child */
1239 /** most operations on the txn are currently illegal */
1240 #define MDB_TXN_BLOCKED (MDB_TXN_FINISHED|MDB_TXN_ERROR|MDB_TXN_HAS_CHILD)
1242 unsigned int mt_flags; /**< @ref mdb_txn */
1243 /** #dirty_list room: Array size - \#dirty pages visible to this txn.
1244 * Includes ancestor txns' dirty pages not hidden by other txns'
1245 * dirty/spilled pages. Thus commit(nested txn) has room to merge
1246 * dirty_list into mt_parent after freeing hidden mt_parent pages.
1248 unsigned int mt_dirty_room;
1251 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
1252 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
1253 * raise this on a 64 bit machine.
1255 #define CURSOR_STACK 32
1259 /** Cursors are used for all DB operations.
1260 * A cursor holds a path of (page pointer, key index) from the DB
1261 * root to a position in the DB, plus other state. #MDB_DUPSORT
1262 * cursors include an xcursor to the current data item. Write txns
1263 * track their cursors and keep them up to date when data moves.
1264 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
1265 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
1268 /** Next cursor on this DB in this txn */
1269 MDB_cursor *mc_next;
1270 /** Backup of the original cursor if this cursor is a shadow */
1271 MDB_cursor *mc_backup;
1272 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
1273 struct MDB_xcursor *mc_xcursor;
1274 /** The transaction that owns this cursor */
1276 /** The database handle this cursor operates on */
1278 /** The database record for this cursor */
1280 /** The database auxiliary record for this cursor */
1282 /** The @ref mt_dbflag for this database */
1283 unsigned char *mc_dbflag;
1284 unsigned short mc_snum; /**< number of pushed pages */
1285 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
1286 /** @defgroup mdb_cursor Cursor Flags
1288 * Cursor state flags.
1291 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
1292 #define C_EOF 0x02 /**< No more data */
1293 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
1294 #define C_DEL 0x08 /**< last op was a cursor_del */
1295 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
1296 #define C_WRITEMAP MDB_TXN_WRITEMAP /**< Copy of txn flag */
1297 /** Read-only cursor into the txn's original snapshot in the map.
1298 * Set for read-only txns, and in #mdb_page_alloc() for #FREE_DBI when
1299 * #MDB_DEVEL & 2. Only implements code which is necessary for this.
1301 #define C_ORIG_RDONLY MDB_TXN_RDONLY
1303 unsigned int mc_flags; /**< @ref mdb_cursor */
1304 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
1305 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
1307 MDB_page *mc_ovpg; /**< a referenced overflow page */
1308 # define MC_OVPG(mc) ((mc)->mc_ovpg)
1309 # define MC_SET_OVPG(mc, pg) ((mc)->mc_ovpg = (pg))
1311 # define MC_OVPG(mc) ((MDB_page *)0)
1312 # define MC_SET_OVPG(mc, pg) ((void)0)
1316 /** Context for sorted-dup records.
1317 * We could have gone to a fully recursive design, with arbitrarily
1318 * deep nesting of sub-databases. But for now we only handle these
1319 * levels - main DB, optional sub-DB, sorted-duplicate DB.
1321 typedef struct MDB_xcursor {
1322 /** A sub-cursor for traversing the Dup DB */
1323 MDB_cursor mx_cursor;
1324 /** The database record for this Dup DB */
1326 /** The auxiliary DB record for this Dup DB */
1328 /** The @ref mt_dbflag for this Dup DB */
1329 unsigned char mx_dbflag;
1332 /** State of FreeDB old pages, stored in the MDB_env */
1333 typedef struct MDB_pgstate {
1334 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1335 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1338 /** The database environment. */
1340 HANDLE me_fd; /**< The main data file */
1341 HANDLE me_lfd; /**< The lock file */
1342 HANDLE me_mfd; /**< just for writing the meta pages */
1343 #if defined(MDB_VL32) && defined(_WIN32)
1344 HANDLE me_fmh; /**< File Mapping handle */
1346 /** Failed to update the meta page. Probably an I/O error. */
1347 #define MDB_FATAL_ERROR 0x80000000U
1348 /** Some fields are initialized. */
1349 #define MDB_ENV_ACTIVE 0x20000000U
1350 /** me_txkey is set */
1351 #define MDB_ENV_TXKEY 0x10000000U
1352 /** fdatasync is unreliable */
1353 #define MDB_FSYNCONLY 0x08000000U
1354 uint32_t me_flags; /**< @ref mdb_env */
1355 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1356 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1357 unsigned int me_maxreaders; /**< size of the reader table */
1358 /** Max #MDB_txninfo.%mti_numreaders of interest to #mdb_env_close() */
1359 volatile int me_close_readers;
1360 MDB_dbi me_numdbs; /**< number of DBs opened */
1361 MDB_dbi me_maxdbs; /**< size of the DB table */
1362 MDB_PID_T me_pid; /**< process ID of this env */
1363 char *me_path; /**< path to the DB files */
1364 char *me_map; /**< the memory map of the data file */
1365 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1366 MDB_meta *me_metas[NUM_METAS]; /**< pointers to the two meta pages */
1367 void *me_pbuf; /**< scratch area for DUPSORT put() */
1368 MDB_txn *me_txn; /**< current write transaction */
1369 MDB_txn *me_txn0; /**< prealloc'd write transaction */
1370 mdb_size_t me_mapsize; /**< size of the data memory map */
1371 off_t me_size; /**< current file size */
1372 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1373 MDB_dbx *me_dbxs; /**< array of static DB info */
1374 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1375 unsigned int *me_dbiseqs; /**< array of dbi sequence numbers */
1376 pthread_key_t me_txkey; /**< thread-key for readers */
1377 txnid_t me_pgoldest; /**< ID of oldest reader last time we looked */
1378 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1379 # define me_pglast me_pgstate.mf_pglast
1380 # define me_pghead me_pgstate.mf_pghead
1381 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1382 /** IDL of pages that became unused in a write txn */
1383 MDB_IDL me_free_pgs;
1384 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1385 MDB_ID2L me_dirty_list;
1386 /** Max number of freelist items that can fit in a single overflow page */
1388 /** Max size of a node on a page */
1389 unsigned int me_nodemax;
1390 #if !(MDB_MAXKEYSIZE)
1391 unsigned int me_maxkey; /**< max size of a key */
1393 int me_live_reader; /**< have liveness lock in reader table */
1395 int me_pidquery; /**< Used in OpenProcess */
1397 #ifdef MDB_USE_POSIX_MUTEX /* Posix mutexes reside in shared mem */
1398 # define me_rmutex me_txns->mti_rmutex /**< Shared reader lock */
1399 # define me_wmutex me_txns->mti_wmutex /**< Shared writer lock */
1401 mdb_mutex_t me_rmutex;
1402 mdb_mutex_t me_wmutex;
1405 MDB_ID3L me_rpages; /**< like #mt_rpages, but global to env */
1406 pthread_mutex_t me_rpmutex; /**< control access to #me_rpages */
1407 #define MDB_ERPAGE_SIZE 16384
1408 #define MDB_ERPAGE_MAX (MDB_ERPAGE_SIZE-1)
1409 unsigned int me_rpcheck;
1411 void *me_userctx; /**< User-settable context */
1412 MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
1415 /** Nested transaction */
1416 typedef struct MDB_ntxn {
1417 MDB_txn mnt_txn; /**< the transaction */
1418 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1421 /** max number of pages to commit in one writev() call */
1422 #define MDB_COMMIT_PAGES 64
1423 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1424 #undef MDB_COMMIT_PAGES
1425 #define MDB_COMMIT_PAGES IOV_MAX
1428 /** max bytes to write in one call */
1429 #define MAX_WRITE (0x40000000U >> (sizeof(ssize_t) == 4))
1431 /** Check \b txn and \b dbi arguments to a function */
1432 #define TXN_DBI_EXIST(txn, dbi, validity) \
1433 ((txn) && (dbi)<(txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & (validity)))
1435 /** Check for misused \b dbi handles */
1436 #define TXN_DBI_CHANGED(txn, dbi) \
1437 ((txn)->mt_dbiseqs[dbi] != (txn)->mt_env->me_dbiseqs[dbi])
1439 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1440 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1441 static int mdb_page_touch(MDB_cursor *mc);
1443 #define MDB_END_NAMES {"committed", "empty-commit", "abort", "reset", \
1444 "reset-tmp", "fail-begin", "fail-beginchild"}
1446 /* mdb_txn_end operation number, for logging */
1447 MDB_END_COMMITTED, MDB_END_EMPTY_COMMIT, MDB_END_ABORT, MDB_END_RESET,
1448 MDB_END_RESET_TMP, MDB_END_FAIL_BEGIN, MDB_END_FAIL_BEGINCHILD
1450 #define MDB_END_OPMASK 0x0F /**< mask for #mdb_txn_end() operation number */
1451 #define MDB_END_UPDATE 0x10 /**< update env state (DBIs) */
1452 #define MDB_END_FREE 0x20 /**< free txn unless it is #MDB_env.%me_txn0 */
1453 #define MDB_END_SLOT MDB_NOTLS /**< release any reader slot if #MDB_NOTLS */
1454 static void mdb_txn_end(MDB_txn *txn, unsigned mode);
1456 static int mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **mp, int *lvl);
1457 static int mdb_page_search_root(MDB_cursor *mc,
1458 MDB_val *key, int modify);
1459 #define MDB_PS_MODIFY 1
1460 #define MDB_PS_ROOTONLY 2
1461 #define MDB_PS_FIRST 4
1462 #define MDB_PS_LAST 8
1463 static int mdb_page_search(MDB_cursor *mc,
1464 MDB_val *key, int flags);
1465 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1467 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1468 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1469 pgno_t newpgno, unsigned int nflags);
1471 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1472 static MDB_meta *mdb_env_pick_meta(const MDB_env *env);
1473 static int mdb_env_write_meta(MDB_txn *txn);
1474 #ifdef MDB_USE_POSIX_MUTEX /* Drop unused excl arg */
1475 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1477 static void mdb_env_close0(MDB_env *env, int excl);
1479 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1480 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1481 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1482 static void mdb_node_del(MDB_cursor *mc, int ksize);
1483 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1484 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft);
1485 static int mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data);
1486 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1487 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1489 static int mdb_rebalance(MDB_cursor *mc);
1490 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1492 static void mdb_cursor_pop(MDB_cursor *mc);
1493 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1495 static int mdb_cursor_del0(MDB_cursor *mc);
1496 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
1497 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1498 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1499 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1500 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1502 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1503 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1505 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1506 static void mdb_xcursor_init0(MDB_cursor *mc);
1507 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1508 static void mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int force);
1510 static int mdb_drop0(MDB_cursor *mc, int subs);
1511 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1512 static int mdb_reader_check0(MDB_env *env, int rlocked, int *dead);
1515 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1518 /** Compare two items pointing at '#mdb_size_t's of unknown alignment. */
1519 #ifdef MISALIGNED_OK
1520 # define mdb_cmp_clong mdb_cmp_long
1522 # define mdb_cmp_clong mdb_cmp_cint
1525 /** True if we need #mdb_cmp_clong() instead of \b cmp for #MDB_INTEGERDUP */
1526 #define NEED_CMP_CLONG(cmp, ksize) \
1527 (UINT_MAX < MDB_SIZE_MAX && \
1528 (cmp) == mdb_cmp_int && (ksize) == sizeof(mdb_size_t))
1531 static SECURITY_DESCRIPTOR mdb_null_sd;
1532 static SECURITY_ATTRIBUTES mdb_all_sa;
1533 static int mdb_sec_inited;
1535 static int utf8_to_utf16(const char *src, int srcsize, wchar_t **dst, int *dstsize);
1538 /** Return the library version info. */
1540 mdb_version(int *major, int *minor, int *patch)
1542 if (major) *major = MDB_VERSION_MAJOR;
1543 if (minor) *minor = MDB_VERSION_MINOR;
1544 if (patch) *patch = MDB_VERSION_PATCH;
1545 return MDB_VERSION_STRING;
1548 /** Table of descriptions for LMDB @ref errors */
1549 static char *const mdb_errstr[] = {
1550 "MDB_KEYEXIST: Key/data pair already exists",
1551 "MDB_NOTFOUND: No matching key/data pair found",
1552 "MDB_PAGE_NOTFOUND: Requested page not found",
1553 "MDB_CORRUPTED: Located page was wrong type",
1554 "MDB_PANIC: Update of meta page failed or environment had fatal error",
1555 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1556 "MDB_INVALID: File is not an LMDB file",
1557 "MDB_MAP_FULL: Environment mapsize limit reached",
1558 "MDB_DBS_FULL: Environment maxdbs limit reached",
1559 "MDB_READERS_FULL: Environment maxreaders limit reached",
1560 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1561 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1562 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1563 "MDB_PAGE_FULL: Internal error - page has no more space",
1564 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1565 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1566 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1567 "MDB_BAD_TXN: Transaction must abort, has a child, or is invalid",
1568 "MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
1569 "MDB_BAD_DBI: The specified DBI handle was closed/changed unexpectedly",
1570 "MDB_PROBLEM: Unexpected problem - txn should abort",
1574 mdb_strerror(int err)
1577 /** HACK: pad 4KB on stack over the buf. Return system msgs in buf.
1578 * This works as long as no function between the call to mdb_strerror
1579 * and the actual use of the message uses more than 4K of stack.
1581 #define MSGSIZE 1024
1582 #define PADSIZE 4096
1583 char buf[MSGSIZE+PADSIZE], *ptr = buf;
1587 return ("Successful return: 0");
1589 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1590 i = err - MDB_KEYEXIST;
1591 return mdb_errstr[i];
1595 /* These are the C-runtime error codes we use. The comment indicates
1596 * their numeric value, and the Win32 error they would correspond to
1597 * if the error actually came from a Win32 API. A major mess, we should
1598 * have used LMDB-specific error codes for everything.
1601 case ENOENT: /* 2, FILE_NOT_FOUND */
1602 case EIO: /* 5, ACCESS_DENIED */
1603 case ENOMEM: /* 12, INVALID_ACCESS */
1604 case EACCES: /* 13, INVALID_DATA */
1605 case EBUSY: /* 16, CURRENT_DIRECTORY */
1606 case EINVAL: /* 22, BAD_COMMAND */
1607 case ENOSPC: /* 28, OUT_OF_PAPER */
1608 return strerror(err);
1613 FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
1614 FORMAT_MESSAGE_IGNORE_INSERTS,
1615 NULL, err, 0, ptr, MSGSIZE, (va_list *)buf+MSGSIZE);
1618 return strerror(err);
1622 /** assert(3) variant in cursor context */
1623 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1624 /** assert(3) variant in transaction context */
1625 #define mdb_tassert(txn, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1626 /** assert(3) variant in environment context */
1627 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1630 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1631 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1634 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1635 const char *func, const char *file, int line)
1638 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1639 file, line, expr_txt, func);
1640 if (env->me_assert_func)
1641 env->me_assert_func(env, buf);
1642 fprintf(stderr, "%s\n", buf);
1646 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1650 /** Return the page number of \b mp which may be sub-page, for debug output */
1652 mdb_dbg_pgno(MDB_page *mp)
1655 COPY_PGNO(ret, mp->mp_pgno);
1659 /** Display a key in hexadecimal and return the address of the result.
1660 * @param[in] key the key to display
1661 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1662 * @return The key in hexadecimal form.
1665 mdb_dkey(MDB_val *key, char *buf)
1668 unsigned char *c = key->mv_data;
1674 if (key->mv_size > DKBUF_MAXKEYSIZE)
1675 return "MDB_MAXKEYSIZE";
1676 /* may want to make this a dynamic check: if the key is mostly
1677 * printable characters, print it as-is instead of converting to hex.
1681 for (i=0; i<key->mv_size; i++)
1682 ptr += sprintf(ptr, "%02x", *c++);
1684 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1690 mdb_leafnode_type(MDB_node *n)
1692 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1693 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1694 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1697 /** Display all the keys in the page. */
1699 mdb_page_list(MDB_page *mp)
1701 pgno_t pgno = mdb_dbg_pgno(mp);
1702 const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
1704 unsigned int i, nkeys, nsize, total = 0;
1708 switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1709 case P_BRANCH: type = "Branch page"; break;
1710 case P_LEAF: type = "Leaf page"; break;
1711 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1712 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1713 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1715 fprintf(stderr, "Overflow page %"Yu" pages %u%s\n",
1716 pgno, mp->mp_pages, state);
1719 fprintf(stderr, "Meta-page %"Yu" txnid %"Yu"\n",
1720 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1723 fprintf(stderr, "Bad page %"Yu" flags 0x%u\n", pgno, mp->mp_flags);
1727 nkeys = NUMKEYS(mp);
1728 fprintf(stderr, "%s %"Yu" numkeys %d%s\n", type, pgno, nkeys, state);
1730 for (i=0; i<nkeys; i++) {
1731 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1732 key.mv_size = nsize = mp->mp_pad;
1733 key.mv_data = LEAF2KEY(mp, i, nsize);
1735 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1738 node = NODEPTR(mp, i);
1739 key.mv_size = node->mn_ksize;
1740 key.mv_data = node->mn_data;
1741 nsize = NODESIZE + key.mv_size;
1742 if (IS_BRANCH(mp)) {
1743 fprintf(stderr, "key %d: page %"Yu", %s\n", i, NODEPGNO(node),
1747 if (F_ISSET(node->mn_flags, F_BIGDATA))
1748 nsize += sizeof(pgno_t);
1750 nsize += NODEDSZ(node);
1752 nsize += sizeof(indx_t);
1753 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1754 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1756 total = EVEN(total);
1758 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1759 IS_LEAF2(mp) ? PAGEHDRSZ : PAGEBASE + mp->mp_lower, total, SIZELEFT(mp));
1763 mdb_cursor_chk(MDB_cursor *mc)
1769 if (!mc->mc_snum || !(mc->mc_flags & C_INITIALIZED)) return;
1770 for (i=0; i<mc->mc_top; i++) {
1772 node = NODEPTR(mp, mc->mc_ki[i]);
1773 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1776 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1778 if (mc->mc_xcursor && (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
1779 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
1780 if (((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) &&
1781 mc->mc_xcursor->mx_cursor.mc_pg[0] != NODEDATA(node)) {
1789 /** Count all the pages in each DB and in the freelist
1790 * and make sure it matches the actual number of pages
1792 * All named DBs must be open for a correct count.
1794 static void mdb_audit(MDB_txn *txn)
1798 MDB_ID freecount, count;
1803 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1804 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1805 freecount += *(MDB_ID *)data.mv_data;
1806 mdb_tassert(txn, rc == MDB_NOTFOUND);
1809 for (i = 0; i<txn->mt_numdbs; i++) {
1811 if (!(txn->mt_dbflags[i] & DB_VALID))
1813 mdb_cursor_init(&mc, txn, i, &mx);
1814 if (txn->mt_dbs[i].md_root == P_INVALID)
1816 count += txn->mt_dbs[i].md_branch_pages +
1817 txn->mt_dbs[i].md_leaf_pages +
1818 txn->mt_dbs[i].md_overflow_pages;
1819 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1820 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1821 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
1824 mp = mc.mc_pg[mc.mc_top];
1825 for (j=0; j<NUMKEYS(mp); j++) {
1826 MDB_node *leaf = NODEPTR(mp, j);
1827 if (leaf->mn_flags & F_SUBDATA) {
1829 memcpy(&db, NODEDATA(leaf), sizeof(db));
1830 count += db.md_branch_pages + db.md_leaf_pages +
1831 db.md_overflow_pages;
1835 mdb_tassert(txn, rc == MDB_NOTFOUND);
1838 if (freecount + count + NUM_METAS != txn->mt_next_pgno) {
1839 fprintf(stderr, "audit: %"Yu" freecount: %"Yu" count: %"Yu" total: %"Yu" next_pgno: %"Yu"\n",
1840 txn->mt_txnid, freecount, count+NUM_METAS,
1841 freecount+count+NUM_METAS, txn->mt_next_pgno);
1847 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1849 return txn->mt_dbxs[dbi].md_cmp(a, b);
1853 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1855 MDB_cmp_func *dcmp = txn->mt_dbxs[dbi].md_dcmp;
1856 if (NEED_CMP_CLONG(dcmp, a->mv_size))
1857 dcmp = mdb_cmp_clong;
1861 /** Allocate memory for a page.
1862 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1865 mdb_page_malloc(MDB_txn *txn, unsigned num)
1867 MDB_env *env = txn->mt_env;
1868 MDB_page *ret = env->me_dpages;
1869 size_t psize = env->me_psize, sz = psize, off;
1870 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1871 * For a single page alloc, we init everything after the page header.
1872 * For multi-page, we init the final page; if the caller needed that
1873 * many pages they will be filling in at least up to the last page.
1877 VGMEMP_ALLOC(env, ret, sz);
1878 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1879 env->me_dpages = ret->mp_next;
1882 psize -= off = PAGEHDRSZ;
1887 if ((ret = malloc(sz)) != NULL) {
1888 VGMEMP_ALLOC(env, ret, sz);
1889 if (!(env->me_flags & MDB_NOMEMINIT)) {
1890 memset((char *)ret + off, 0, psize);
1894 txn->mt_flags |= MDB_TXN_ERROR;
1898 /** Free a single page.
1899 * Saves single pages to a list, for future reuse.
1900 * (This is not used for multi-page overflow pages.)
1903 mdb_page_free(MDB_env *env, MDB_page *mp)
1905 mp->mp_next = env->me_dpages;
1906 VGMEMP_FREE(env, mp);
1907 env->me_dpages = mp;
1910 /** Free a dirty page */
1912 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1914 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1915 mdb_page_free(env, dp);
1917 /* large pages just get freed directly */
1918 VGMEMP_FREE(env, dp);
1923 /** Return all dirty pages to dpage list */
1925 mdb_dlist_free(MDB_txn *txn)
1927 MDB_env *env = txn->mt_env;
1928 MDB_ID2L dl = txn->mt_u.dirty_list;
1929 unsigned i, n = dl[0].mid;
1931 for (i = 1; i <= n; i++) {
1932 mdb_dpage_free(env, dl[i].mptr);
1939 mdb_page_unref(MDB_txn *txn, MDB_page *mp)
1942 MDB_ID3L tl = txn->mt_rpages;
1944 if (mp->mp_flags & (P_SUBP|P_DIRTY))
1946 rem = mp->mp_pgno & (MDB_RPAGE_CHUNK-1);
1947 pgno = mp->mp_pgno ^ rem;
1948 x = mdb_mid3l_search(tl, pgno);
1949 if (x != tl[0].mid && tl[x+1].mid == mp->mp_pgno)
1954 #define MDB_PAGE_UNREF(txn, mp) mdb_page_unref(txn, mp)
1957 mdb_cursor_unref(MDB_cursor *mc)
1960 if (!mc->mc_snum || !mc->mc_pg[0] || IS_SUBP(mc->mc_pg[0]))
1962 for (i=0; i<mc->mc_snum; i++)
1963 mdb_page_unref(mc->mc_txn, mc->mc_pg[i]);
1965 mdb_page_unref(mc->mc_txn, mc->mc_ovpg);
1968 mc->mc_snum = mc->mc_top = 0;
1969 mc->mc_pg[0] = NULL;
1970 mc->mc_flags &= ~C_INITIALIZED;
1972 #define MDB_CURSOR_UNREF(mc, force) \
1973 (((force) || ((mc)->mc_flags & C_INITIALIZED)) \
1974 ? mdb_cursor_unref(mc) \
1978 #define MDB_PAGE_UNREF(txn, mp)
1979 #define MDB_CURSOR_UNREF(mc, force) ((void)0)
1980 #endif /* MDB_VL32 */
1982 /** Loosen or free a single page.
1983 * Saves single pages to a list for future reuse
1984 * in this same txn. It has been pulled from the freeDB
1985 * and already resides on the dirty list, but has been
1986 * deleted. Use these pages first before pulling again
1989 * If the page wasn't dirtied in this txn, just add it
1990 * to this txn's free list.
1993 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
1996 pgno_t pgno = mp->mp_pgno;
1997 MDB_txn *txn = mc->mc_txn;
1999 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
2000 if (txn->mt_parent) {
2001 MDB_ID2 *dl = txn->mt_u.dirty_list;
2002 /* If txn has a parent, make sure the page is in our
2006 unsigned x = mdb_mid2l_search(dl, pgno);
2007 if (x <= dl[0].mid && dl[x].mid == pgno) {
2008 if (mp != dl[x].mptr) { /* bad cursor? */
2009 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2010 txn->mt_flags |= MDB_TXN_ERROR;
2018 /* no parent txn, so it's just ours */
2023 DPRINTF(("loosen db %d page %"Yu, DDBI(mc), mp->mp_pgno));
2024 NEXT_LOOSE_PAGE(mp) = txn->mt_loose_pgs;
2025 txn->mt_loose_pgs = mp;
2026 txn->mt_loose_count++;
2027 mp->mp_flags |= P_LOOSE;
2029 int rc = mdb_midl_append(&txn->mt_free_pgs, pgno);
2037 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
2038 * @param[in] mc A cursor handle for the current operation.
2039 * @param[in] pflags Flags of the pages to update:
2040 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
2041 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
2042 * @return 0 on success, non-zero on failure.
2045 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
2047 enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
2048 MDB_txn *txn = mc->mc_txn;
2049 MDB_cursor *m3, *m0 = mc;
2054 int rc = MDB_SUCCESS, level;
2056 /* Mark pages seen by cursors */
2057 if (mc->mc_flags & C_UNTRACK)
2058 mc = NULL; /* will find mc in mt_cursors */
2059 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
2060 for (; mc; mc=mc->mc_next) {
2061 if (!(mc->mc_flags & C_INITIALIZED))
2063 for (m3 = mc;; m3 = &mx->mx_cursor) {
2065 for (j=0; j<m3->mc_snum; j++) {
2067 if ((mp->mp_flags & Mask) == pflags)
2068 mp->mp_flags ^= P_KEEP;
2070 mx = m3->mc_xcursor;
2071 /* Proceed to mx if it is at a sub-database */
2072 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
2074 if (! (mp && (mp->mp_flags & P_LEAF)))
2076 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
2077 if (!(leaf->mn_flags & F_SUBDATA))
2086 /* Mark dirty root pages */
2087 for (i=0; i<txn->mt_numdbs; i++) {
2088 if (txn->mt_dbflags[i] & DB_DIRTY) {
2089 pgno_t pgno = txn->mt_dbs[i].md_root;
2090 if (pgno == P_INVALID)
2092 if ((rc = mdb_page_get(m0, pgno, &dp, &level)) != MDB_SUCCESS)
2094 if ((dp->mp_flags & Mask) == pflags && level <= 1)
2095 dp->mp_flags ^= P_KEEP;
2103 static int mdb_page_flush(MDB_txn *txn, int keep);
2105 /** Spill pages from the dirty list back to disk.
2106 * This is intended to prevent running into #MDB_TXN_FULL situations,
2107 * but note that they may still occur in a few cases:
2108 * 1) our estimate of the txn size could be too small. Currently this
2109 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
2110 * 2) child txns may run out of space if their parents dirtied a
2111 * lot of pages and never spilled them. TODO: we probably should do
2112 * a preemptive spill during #mdb_txn_begin() of a child txn, if
2113 * the parent's dirty_room is below a given threshold.
2115 * Otherwise, if not using nested txns, it is expected that apps will
2116 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
2117 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
2118 * If the txn never references them again, they can be left alone.
2119 * If the txn only reads them, they can be used without any fuss.
2120 * If the txn writes them again, they can be dirtied immediately without
2121 * going thru all of the work of #mdb_page_touch(). Such references are
2122 * handled by #mdb_page_unspill().
2124 * Also note, we never spill DB root pages, nor pages of active cursors,
2125 * because we'll need these back again soon anyway. And in nested txns,
2126 * we can't spill a page in a child txn if it was already spilled in a
2127 * parent txn. That would alter the parent txns' data even though
2128 * the child hasn't committed yet, and we'd have no way to undo it if
2129 * the child aborted.
2131 * @param[in] m0 cursor A cursor handle identifying the transaction and
2132 * database for which we are checking space.
2133 * @param[in] key For a put operation, the key being stored.
2134 * @param[in] data For a put operation, the data being stored.
2135 * @return 0 on success, non-zero on failure.
2138 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
2140 MDB_txn *txn = m0->mc_txn;
2142 MDB_ID2L dl = txn->mt_u.dirty_list;
2143 unsigned int i, j, need;
2146 if (m0->mc_flags & C_SUB)
2149 /* Estimate how much space this op will take */
2150 i = m0->mc_db->md_depth;
2151 /* Named DBs also dirty the main DB */
2152 if (m0->mc_dbi >= CORE_DBS)
2153 i += txn->mt_dbs[MAIN_DBI].md_depth;
2154 /* For puts, roughly factor in the key+data size */
2156 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
2157 i += i; /* double it for good measure */
2160 if (txn->mt_dirty_room > i)
2163 if (!txn->mt_spill_pgs) {
2164 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
2165 if (!txn->mt_spill_pgs)
2168 /* purge deleted slots */
2169 MDB_IDL sl = txn->mt_spill_pgs;
2170 unsigned int num = sl[0];
2172 for (i=1; i<=num; i++) {
2179 /* Preserve pages which may soon be dirtied again */
2180 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
2183 /* Less aggressive spill - we originally spilled the entire dirty list,
2184 * with a few exceptions for cursor pages and DB root pages. But this
2185 * turns out to be a lot of wasted effort because in a large txn many
2186 * of those pages will need to be used again. So now we spill only 1/8th
2187 * of the dirty pages. Testing revealed this to be a good tradeoff,
2188 * better than 1/2, 1/4, or 1/10.
2190 if (need < MDB_IDL_UM_MAX / 8)
2191 need = MDB_IDL_UM_MAX / 8;
2193 /* Save the page IDs of all the pages we're flushing */
2194 /* flush from the tail forward, this saves a lot of shifting later on. */
2195 for (i=dl[0].mid; i && need; i--) {
2196 MDB_ID pn = dl[i].mid << 1;
2198 if (dp->mp_flags & (P_LOOSE|P_KEEP))
2200 /* Can't spill twice, make sure it's not already in a parent's
2203 if (txn->mt_parent) {
2205 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
2206 if (tx2->mt_spill_pgs) {
2207 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
2208 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
2209 dp->mp_flags |= P_KEEP;
2217 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
2221 mdb_midl_sort(txn->mt_spill_pgs);
2223 /* Flush the spilled part of dirty list */
2224 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
2227 /* Reset any dirty pages we kept that page_flush didn't see */
2228 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
2231 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
2235 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
2237 mdb_find_oldest(MDB_txn *txn)
2240 txnid_t mr, oldest = txn->mt_txnid - 1;
2241 if (txn->mt_env->me_txns) {
2242 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
2243 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
2254 /** Add a page to the txn's dirty list */
2256 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
2259 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
2261 if (txn->mt_flags & MDB_TXN_WRITEMAP) {
2262 insert = mdb_mid2l_append;
2264 insert = mdb_mid2l_insert;
2266 mid.mid = mp->mp_pgno;
2268 rc = insert(txn->mt_u.dirty_list, &mid);
2269 mdb_tassert(txn, rc == 0);
2270 txn->mt_dirty_room--;
2273 /** Allocate page numbers and memory for writing. Maintain me_pglast,
2274 * me_pghead and mt_next_pgno.
2276 * If there are free pages available from older transactions, they
2277 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
2278 * Do not modify the freedB, just merge freeDB records into me_pghead[]
2279 * and move me_pglast to say which records were consumed. Only this
2280 * function can create me_pghead and move me_pglast/mt_next_pgno.
2281 * When #MDB_DEVEL & 2, it is not affected by #mdb_freelist_save(): it
2282 * then uses the transaction's original snapshot of the freeDB.
2283 * @param[in] mc cursor A cursor handle identifying the transaction and
2284 * database for which we are allocating.
2285 * @param[in] num the number of pages to allocate.
2286 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
2287 * will always be satisfied by a single contiguous chunk of memory.
2288 * @return 0 on success, non-zero on failure.
2291 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
2293 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
2294 /* Get at most <Max_retries> more freeDB records once me_pghead
2295 * has enough pages. If not enough, use new pages from the map.
2296 * If <Paranoid> and mc is updating the freeDB, only get new
2297 * records if me_pghead is empty. Then the freelist cannot play
2298 * catch-up with itself by growing while trying to save it.
2300 enum { Paranoid = 1, Max_retries = 500 };
2302 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
2304 int rc, retry = num * 60;
2305 MDB_txn *txn = mc->mc_txn;
2306 MDB_env *env = txn->mt_env;
2307 pgno_t pgno, *mop = env->me_pghead;
2308 unsigned i, j, mop_len = mop ? mop[0] : 0, n2 = num-1;
2310 txnid_t oldest = 0, last;
2315 /* If there are any loose pages, just use them */
2316 if (num == 1 && txn->mt_loose_pgs) {
2317 np = txn->mt_loose_pgs;
2318 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
2319 txn->mt_loose_count--;
2320 DPRINTF(("db %d use loose page %"Yu, DDBI(mc), np->mp_pgno));
2327 /* If our dirty list is already full, we can't do anything */
2328 if (txn->mt_dirty_room == 0) {
2333 for (op = MDB_FIRST;; op = MDB_NEXT) {
2338 /* Seek a big enough contiguous page range. Prefer
2339 * pages at the tail, just truncating the list.
2345 if (mop[i-n2] == pgno+n2)
2352 if (op == MDB_FIRST) { /* 1st iteration */
2353 /* Prepare to fetch more and coalesce */
2354 last = env->me_pglast;
2355 oldest = env->me_pgoldest;
2356 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
2357 #if (MDB_DEVEL) & 2 /* "& 2" so MDB_DEVEL=1 won't hide bugs breaking freeDB */
2358 /* Use original snapshot. TODO: Should need less care in code
2359 * which modifies the database. Maybe we can delete some code?
2361 m2.mc_flags |= C_ORIG_RDONLY;
2362 m2.mc_db = &env->me_metas[(txn->mt_txnid-1) & 1]->mm_dbs[FREE_DBI];
2363 m2.mc_dbflag = (unsigned char *)""; /* probably unnecessary */
2367 key.mv_data = &last; /* will look up last+1 */
2368 key.mv_size = sizeof(last);
2370 if (Paranoid && mc->mc_dbi == FREE_DBI)
2373 if (Paranoid && retry < 0 && mop_len)
2377 /* Do not fetch more if the record will be too recent */
2378 if (oldest <= last) {
2380 oldest = mdb_find_oldest(txn);
2381 env->me_pgoldest = oldest;
2387 rc = mdb_cursor_get(&m2, &key, NULL, op);
2389 if (rc == MDB_NOTFOUND)
2393 last = *(txnid_t*)key.mv_data;
2394 if (oldest <= last) {
2396 oldest = mdb_find_oldest(txn);
2397 env->me_pgoldest = oldest;
2403 np = m2.mc_pg[m2.mc_top];
2404 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
2405 if ((rc = mdb_node_read(&m2, leaf, &data)) != MDB_SUCCESS)
2408 idl = (MDB_ID *) data.mv_data;
2411 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
2416 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
2418 mop = env->me_pghead;
2420 env->me_pglast = last;
2422 DPRINTF(("IDL read txn %"Yu" root %"Yu" num %u",
2423 last, txn->mt_dbs[FREE_DBI].md_root, i));
2425 DPRINTF(("IDL %"Yu, idl[j]));
2427 /* Merge in descending sorted order */
2428 mdb_midl_xmerge(mop, idl);
2432 /* Use new pages from the map when nothing suitable in the freeDB */
2434 pgno = txn->mt_next_pgno;
2435 if (pgno + num >= env->me_maxpg) {
2436 DPUTS("DB size maxed out");
2440 #if defined(_WIN32) && !defined(MDB_VL32)
2441 if (!(env->me_flags & MDB_RDONLY)) {
2443 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
2444 p = VirtualAlloc(p, env->me_psize * num, MEM_COMMIT,
2445 (env->me_flags & MDB_WRITEMAP) ? PAGE_READWRITE:
2448 DPUTS("VirtualAlloc failed");
2456 if (env->me_flags & MDB_WRITEMAP) {
2457 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
2459 if (!(np = mdb_page_malloc(txn, num))) {
2465 mop[0] = mop_len -= num;
2466 /* Move any stragglers down */
2467 for (j = i-num; j < mop_len; )
2468 mop[++j] = mop[++i];
2470 txn->mt_next_pgno = pgno + num;
2473 mdb_page_dirty(txn, np);
2479 txn->mt_flags |= MDB_TXN_ERROR;
2483 /** Copy the used portions of a non-overflow page.
2484 * @param[in] dst page to copy into
2485 * @param[in] src page to copy from
2486 * @param[in] psize size of a page
2489 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2491 enum { Align = sizeof(pgno_t) };
2492 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2494 /* If page isn't full, just copy the used portion. Adjust
2495 * alignment so memcpy may copy words instead of bytes.
2497 if ((unused &= -Align) && !IS_LEAF2(src)) {
2498 upper = (upper + PAGEBASE) & -Align;
2499 memcpy(dst, src, (lower + PAGEBASE + (Align-1)) & -Align);
2500 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2503 memcpy(dst, src, psize - unused);
2507 /** Pull a page off the txn's spill list, if present.
2508 * If a page being referenced was spilled to disk in this txn, bring
2509 * it back and make it dirty/writable again.
2510 * @param[in] txn the transaction handle.
2511 * @param[in] mp the page being referenced. It must not be dirty.
2512 * @param[out] ret the writable page, if any. ret is unchanged if
2513 * mp wasn't spilled.
2516 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2518 MDB_env *env = txn->mt_env;
2521 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2523 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2524 if (!tx2->mt_spill_pgs)
2526 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2527 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2530 if (txn->mt_dirty_room == 0)
2531 return MDB_TXN_FULL;
2532 if (IS_OVERFLOW(mp))
2536 if (env->me_flags & MDB_WRITEMAP) {
2539 np = mdb_page_malloc(txn, num);
2543 memcpy(np, mp, num * env->me_psize);
2545 mdb_page_copy(np, mp, env->me_psize);
2548 /* If in current txn, this page is no longer spilled.
2549 * If it happens to be the last page, truncate the spill list.
2550 * Otherwise mark it as deleted by setting the LSB.
2552 if (x == txn->mt_spill_pgs[0])
2553 txn->mt_spill_pgs[0]--;
2555 txn->mt_spill_pgs[x] |= 1;
2556 } /* otherwise, if belonging to a parent txn, the
2557 * page remains spilled until child commits
2560 mdb_page_dirty(txn, np);
2561 np->mp_flags |= P_DIRTY;
2569 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2570 * @param[in] mc cursor pointing to the page to be touched
2571 * @return 0 on success, non-zero on failure.
2574 mdb_page_touch(MDB_cursor *mc)
2576 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2577 MDB_txn *txn = mc->mc_txn;
2578 MDB_cursor *m2, *m3;
2582 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2583 if (txn->mt_flags & MDB_TXN_SPILLS) {
2585 rc = mdb_page_unspill(txn, mp, &np);
2591 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2592 (rc = mdb_page_alloc(mc, 1, &np)))
2595 DPRINTF(("touched db %d page %"Yu" -> %"Yu, DDBI(mc),
2596 mp->mp_pgno, pgno));
2597 mdb_cassert(mc, mp->mp_pgno != pgno);
2598 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2599 /* Update the parent page, if any, to point to the new page */
2601 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2602 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2603 SETPGNO(node, pgno);
2605 mc->mc_db->md_root = pgno;
2607 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2608 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2610 /* If txn has a parent, make sure the page is in our
2614 unsigned x = mdb_mid2l_search(dl, pgno);
2615 if (x <= dl[0].mid && dl[x].mid == pgno) {
2616 if (mp != dl[x].mptr) { /* bad cursor? */
2617 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2618 txn->mt_flags |= MDB_TXN_ERROR;
2624 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2626 np = mdb_page_malloc(txn, 1);
2631 rc = mdb_mid2l_insert(dl, &mid);
2632 mdb_cassert(mc, rc == 0);
2637 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2639 np->mp_flags |= P_DIRTY;
2642 /* Adjust cursors pointing to mp */
2643 mc->mc_pg[mc->mc_top] = np;
2644 m2 = txn->mt_cursors[mc->mc_dbi];
2645 if (mc->mc_flags & C_SUB) {
2646 for (; m2; m2=m2->mc_next) {
2647 m3 = &m2->mc_xcursor->mx_cursor;
2648 if (m3->mc_snum < mc->mc_snum) continue;
2649 if (m3->mc_pg[mc->mc_top] == mp)
2650 m3->mc_pg[mc->mc_top] = np;
2653 for (; m2; m2=m2->mc_next) {
2654 if (m2->mc_snum < mc->mc_snum) continue;
2655 if (m2 == mc) continue;
2656 if (m2->mc_pg[mc->mc_top] == mp) {
2657 m2->mc_pg[mc->mc_top] = np;
2658 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
2660 (m2->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
2662 MDB_node *leaf = NODEPTR(np, m2->mc_ki[mc->mc_top]);
2663 if ((leaf->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
2664 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
2669 MDB_PAGE_UNREF(mc->mc_txn, mp);
2673 txn->mt_flags |= MDB_TXN_ERROR;
2678 mdb_env_sync0(MDB_env *env, int force, pgno_t numpgs)
2681 if (env->me_flags & MDB_RDONLY)
2683 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2684 if (env->me_flags & MDB_WRITEMAP) {
2685 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2686 ? MS_ASYNC : MS_SYNC;
2687 if (MDB_MSYNC(env->me_map, env->me_psize * numpgs, flags))
2690 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2694 #ifdef BROKEN_FDATASYNC
2695 if (env->me_flags & MDB_FSYNCONLY) {
2696 if (fsync(env->me_fd))
2700 if (MDB_FDATASYNC(env->me_fd))
2708 mdb_env_sync(MDB_env *env, int force)
2710 MDB_meta *m = mdb_env_pick_meta(env);
2711 return mdb_env_sync0(env, force, m->mm_last_pg+1);
2714 /** Back up parent txn's cursors, then grab the originals for tracking */
2716 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2718 MDB_cursor *mc, *bk;
2723 for (i = src->mt_numdbs; --i >= 0; ) {
2724 if ((mc = src->mt_cursors[i]) != NULL) {
2725 size = sizeof(MDB_cursor);
2727 size += sizeof(MDB_xcursor);
2728 for (; mc; mc = bk->mc_next) {
2734 mc->mc_db = &dst->mt_dbs[i];
2735 /* Kill pointers into src to reduce abuse: The
2736 * user may not use mc until dst ends. But we need a valid
2737 * txn pointer here for cursor fixups to keep working.
2740 mc->mc_dbflag = &dst->mt_dbflags[i];
2741 if ((mx = mc->mc_xcursor) != NULL) {
2742 *(MDB_xcursor *)(bk+1) = *mx;
2743 mx->mx_cursor.mc_txn = dst;
2745 mc->mc_next = dst->mt_cursors[i];
2746 dst->mt_cursors[i] = mc;
2753 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2754 * @param[in] txn the transaction handle.
2755 * @param[in] merge true to keep changes to parent cursors, false to revert.
2756 * @return 0 on success, non-zero on failure.
2759 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2761 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2765 for (i = txn->mt_numdbs; --i >= 0; ) {
2766 for (mc = cursors[i]; mc; mc = next) {
2768 if ((bk = mc->mc_backup) != NULL) {
2770 /* Commit changes to parent txn */
2771 mc->mc_next = bk->mc_next;
2772 mc->mc_backup = bk->mc_backup;
2773 mc->mc_txn = bk->mc_txn;
2774 mc->mc_db = bk->mc_db;
2775 mc->mc_dbflag = bk->mc_dbflag;
2776 if ((mx = mc->mc_xcursor) != NULL)
2777 mx->mx_cursor.mc_txn = bk->mc_txn;
2779 /* Abort nested txn */
2781 if ((mx = mc->mc_xcursor) != NULL)
2782 *mx = *(MDB_xcursor *)(bk+1);
2786 /* Only malloced cursors are permanently tracked. */
2793 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2799 Pidset = F_SETLK, Pidcheck = F_GETLK
2803 /** Set or check a pid lock. Set returns 0 on success.
2804 * Check returns 0 if the process is certainly dead, nonzero if it may
2805 * be alive (the lock exists or an error happened so we do not know).
2807 * On Windows Pidset is a no-op, we merely check for the existence
2808 * of the process with the given pid. On POSIX we use a single byte
2809 * lock on the lockfile, set at an offset equal to the pid.
2812 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2814 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2817 if (op == Pidcheck) {
2818 h = OpenProcess(env->me_pidquery, FALSE, pid);
2819 /* No documented "no such process" code, but other program use this: */
2821 return ErrCode() != ERROR_INVALID_PARAMETER;
2822 /* A process exists until all handles to it close. Has it exited? */
2823 ret = WaitForSingleObject(h, 0) != 0;
2830 struct flock lock_info;
2831 memset(&lock_info, 0, sizeof(lock_info));
2832 lock_info.l_type = F_WRLCK;
2833 lock_info.l_whence = SEEK_SET;
2834 lock_info.l_start = pid;
2835 lock_info.l_len = 1;
2836 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2837 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2839 } else if ((rc = ErrCode()) == EINTR) {
2847 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2848 * @param[in] txn the transaction handle to initialize
2849 * @return 0 on success, non-zero on failure.
2852 mdb_txn_renew0(MDB_txn *txn)
2854 MDB_env *env = txn->mt_env;
2855 MDB_txninfo *ti = env->me_txns;
2857 unsigned int i, nr, flags = txn->mt_flags;
2859 int rc, new_notls = 0;
2861 if ((flags &= MDB_TXN_RDONLY) != 0) {
2863 meta = mdb_env_pick_meta(env);
2864 txn->mt_txnid = meta->mm_txnid;
2865 txn->mt_u.reader = NULL;
2867 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2868 pthread_getspecific(env->me_txkey);
2870 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2871 return MDB_BAD_RSLOT;
2873 MDB_PID_T pid = env->me_pid;
2874 MDB_THR_T tid = pthread_self();
2875 mdb_mutexref_t rmutex = env->me_rmutex;
2877 if (!env->me_live_reader) {
2878 rc = mdb_reader_pid(env, Pidset, pid);
2881 env->me_live_reader = 1;
2884 if (LOCK_MUTEX(rc, env, rmutex))
2886 nr = ti->mti_numreaders;
2887 for (i=0; i<nr; i++)
2888 if (ti->mti_readers[i].mr_pid == 0)
2890 if (i == env->me_maxreaders) {
2891 UNLOCK_MUTEX(rmutex);
2892 return MDB_READERS_FULL;
2894 r = &ti->mti_readers[i];
2895 /* Claim the reader slot, carefully since other code
2896 * uses the reader table un-mutexed: First reset the
2897 * slot, next publish it in mti_numreaders. After
2898 * that, it is safe for mdb_env_close() to touch it.
2899 * When it will be closed, we can finally claim it.
2902 r->mr_txnid = (txnid_t)-1;
2905 ti->mti_numreaders = ++nr;
2906 env->me_close_readers = nr;
2908 UNLOCK_MUTEX(rmutex);
2910 new_notls = (env->me_flags & MDB_NOTLS);
2911 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2916 do /* LY: Retry on a race, ITS#7970. */
2917 r->mr_txnid = ti->mti_txnid;
2918 while(r->mr_txnid != ti->mti_txnid);
2919 txn->mt_txnid = r->mr_txnid;
2920 txn->mt_u.reader = r;
2921 meta = env->me_metas[txn->mt_txnid & 1];
2925 /* Not yet touching txn == env->me_txn0, it may be active */
2927 if (LOCK_MUTEX(rc, env, env->me_wmutex))
2929 txn->mt_txnid = ti->mti_txnid;
2930 meta = env->me_metas[txn->mt_txnid & 1];
2932 meta = mdb_env_pick_meta(env);
2933 txn->mt_txnid = meta->mm_txnid;
2937 if (txn->mt_txnid == mdb_debug_start)
2940 txn->mt_child = NULL;
2941 txn->mt_loose_pgs = NULL;
2942 txn->mt_loose_count = 0;
2943 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2944 txn->mt_u.dirty_list = env->me_dirty_list;
2945 txn->mt_u.dirty_list[0].mid = 0;
2946 txn->mt_free_pgs = env->me_free_pgs;
2947 txn->mt_free_pgs[0] = 0;
2948 txn->mt_spill_pgs = NULL;
2950 memcpy(txn->mt_dbiseqs, env->me_dbiseqs, env->me_maxdbs * sizeof(unsigned int));
2953 /* Copy the DB info and flags */
2954 memcpy(txn->mt_dbs, meta->mm_dbs, CORE_DBS * sizeof(MDB_db));
2956 /* Moved to here to avoid a data race in read TXNs */
2957 txn->mt_next_pgno = meta->mm_last_pg+1;
2959 txn->mt_last_pgno = txn->mt_next_pgno - 1;
2962 txn->mt_flags = flags;
2965 txn->mt_numdbs = env->me_numdbs;
2966 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
2967 x = env->me_dbflags[i];
2968 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2969 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_USRVALID|DB_STALE : 0;
2971 txn->mt_dbflags[MAIN_DBI] = DB_VALID|DB_USRVALID;
2972 txn->mt_dbflags[FREE_DBI] = DB_VALID;
2974 if (env->me_flags & MDB_FATAL_ERROR) {
2975 DPUTS("environment had fatal error, must shutdown!");
2977 } else if (env->me_maxpg < txn->mt_next_pgno) {
2978 rc = MDB_MAP_RESIZED;
2982 mdb_txn_end(txn, new_notls /*0 or MDB_END_SLOT*/ | MDB_END_FAIL_BEGIN);
2987 mdb_txn_renew(MDB_txn *txn)
2991 if (!txn || !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY|MDB_TXN_FINISHED))
2994 rc = mdb_txn_renew0(txn);
2995 if (rc == MDB_SUCCESS) {
2996 DPRINTF(("renew txn %"Yu"%c %p on mdbenv %p, root page %"Yu,
2997 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2998 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
3004 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
3008 int rc, size, tsize;
3010 flags &= MDB_TXN_BEGIN_FLAGS;
3011 flags |= env->me_flags & MDB_WRITEMAP;
3013 if (env->me_flags & MDB_RDONLY & ~flags) /* write txn in RDONLY env */
3017 /* Nested transactions: Max 1 child, write txns only, no writemap */
3018 flags |= parent->mt_flags;
3019 if (flags & (MDB_RDONLY|MDB_WRITEMAP|MDB_TXN_BLOCKED)) {
3020 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
3022 /* Child txns save MDB_pgstate and use own copy of cursors */
3023 size = env->me_maxdbs * (sizeof(MDB_db)+sizeof(MDB_cursor *)+1);
3024 size += tsize = sizeof(MDB_ntxn);
3025 } else if (flags & MDB_RDONLY) {
3026 size = env->me_maxdbs * (sizeof(MDB_db)+1);
3027 size += tsize = sizeof(MDB_txn);
3029 /* Reuse preallocated write txn. However, do not touch it until
3030 * mdb_txn_renew0() succeeds, since it currently may be active.
3035 if ((txn = calloc(1, size)) == NULL) {
3036 DPRINTF(("calloc: %s", strerror(errno)));
3041 txn->mt_rpages = malloc(MDB_TRPAGE_SIZE * sizeof(MDB_ID3));
3042 if (!txn->mt_rpages) {
3046 txn->mt_rpages[0].mid = 0;
3047 txn->mt_rpcheck = MDB_TRPAGE_SIZE/2;
3050 txn->mt_dbxs = env->me_dbxs; /* static */
3051 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
3052 txn->mt_dbflags = (unsigned char *)txn + size - env->me_maxdbs;
3053 txn->mt_flags = flags;
3058 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
3059 txn->mt_dbiseqs = parent->mt_dbiseqs;
3060 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
3061 if (!txn->mt_u.dirty_list ||
3062 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
3064 free(txn->mt_u.dirty_list);
3068 txn->mt_txnid = parent->mt_txnid;
3069 txn->mt_dirty_room = parent->mt_dirty_room;
3070 txn->mt_u.dirty_list[0].mid = 0;
3071 txn->mt_spill_pgs = NULL;
3072 txn->mt_next_pgno = parent->mt_next_pgno;
3073 parent->mt_flags |= MDB_TXN_HAS_CHILD;
3074 parent->mt_child = txn;
3075 txn->mt_parent = parent;
3076 txn->mt_numdbs = parent->mt_numdbs;
3078 txn->mt_rpages = parent->mt_rpages;
3080 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3081 /* Copy parent's mt_dbflags, but clear DB_NEW */
3082 for (i=0; i<txn->mt_numdbs; i++)
3083 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
3085 ntxn = (MDB_ntxn *)txn;
3086 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
3087 if (env->me_pghead) {
3088 size = MDB_IDL_SIZEOF(env->me_pghead);
3089 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
3091 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
3096 rc = mdb_cursor_shadow(parent, txn);
3098 mdb_txn_end(txn, MDB_END_FAIL_BEGINCHILD);
3099 } else { /* MDB_RDONLY */
3100 txn->mt_dbiseqs = env->me_dbiseqs;
3102 rc = mdb_txn_renew0(txn);
3105 if (txn != env->me_txn0) {
3107 free(txn->mt_rpages);
3112 txn->mt_flags |= flags; /* could not change txn=me_txn0 earlier */
3114 DPRINTF(("begin txn %"Yu"%c %p on mdbenv %p, root page %"Yu,
3115 txn->mt_txnid, (flags & MDB_RDONLY) ? 'r' : 'w',
3116 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
3123 mdb_txn_env(MDB_txn *txn)
3125 if(!txn) return NULL;
3130 mdb_txn_id(MDB_txn *txn)
3133 return txn->mt_txnid;
3136 /** Export or close DBI handles opened in this txn. */
3138 mdb_dbis_update(MDB_txn *txn, int keep)
3141 MDB_dbi n = txn->mt_numdbs;
3142 MDB_env *env = txn->mt_env;
3143 unsigned char *tdbflags = txn->mt_dbflags;
3145 for (i = n; --i >= CORE_DBS;) {
3146 if (tdbflags[i] & DB_NEW) {
3148 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
3150 char *ptr = env->me_dbxs[i].md_name.mv_data;
3152 env->me_dbxs[i].md_name.mv_data = NULL;
3153 env->me_dbxs[i].md_name.mv_size = 0;
3154 env->me_dbflags[i] = 0;
3155 env->me_dbiseqs[i]++;
3161 if (keep && env->me_numdbs < n)
3165 /** End a transaction, except successful commit of a nested transaction.
3166 * May be called twice for readonly txns: First reset it, then abort.
3167 * @param[in] txn the transaction handle to end
3168 * @param[in] mode why and how to end the transaction
3171 mdb_txn_end(MDB_txn *txn, unsigned mode)
3173 MDB_env *env = txn->mt_env;
3175 static const char *const names[] = MDB_END_NAMES;
3178 /* Export or close DBI handles opened in this txn */
3179 mdb_dbis_update(txn, mode & MDB_END_UPDATE);
3181 DPRINTF(("%s txn %"Yu"%c %p on mdbenv %p, root page %"Yu,
3182 names[mode & MDB_END_OPMASK],
3183 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
3184 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
3186 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3187 if (txn->mt_u.reader) {
3188 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
3189 if (!(env->me_flags & MDB_NOTLS)) {
3190 txn->mt_u.reader = NULL; /* txn does not own reader */
3191 } else if (mode & MDB_END_SLOT) {
3192 txn->mt_u.reader->mr_pid = 0;
3193 txn->mt_u.reader = NULL;
3194 } /* else txn owns the slot until it does MDB_END_SLOT */
3196 txn->mt_numdbs = 0; /* prevent further DBI activity */
3197 txn->mt_flags |= MDB_TXN_FINISHED;
3199 } else if (!F_ISSET(txn->mt_flags, MDB_TXN_FINISHED)) {
3200 pgno_t *pghead = env->me_pghead;
3202 if (!(mode & MDB_END_UPDATE)) /* !(already closed cursors) */
3203 mdb_cursors_close(txn, 0);
3204 if (!(env->me_flags & MDB_WRITEMAP)) {
3205 mdb_dlist_free(txn);
3209 txn->mt_flags = MDB_TXN_FINISHED;
3211 if (!txn->mt_parent) {
3212 mdb_midl_shrink(&txn->mt_free_pgs);
3213 env->me_free_pgs = txn->mt_free_pgs;
3215 env->me_pghead = NULL;
3219 mode = 0; /* txn == env->me_txn0, do not free() it */
3221 /* The writer mutex was locked in mdb_txn_begin. */
3223 UNLOCK_MUTEX(env->me_wmutex);
3225 txn->mt_parent->mt_child = NULL;
3226 txn->mt_parent->mt_flags &= ~MDB_TXN_HAS_CHILD;
3227 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
3228 mdb_midl_free(txn->mt_free_pgs);
3229 mdb_midl_free(txn->mt_spill_pgs);
3230 free(txn->mt_u.dirty_list);
3233 mdb_midl_free(pghead);
3236 if (!txn->mt_parent) {
3237 MDB_ID3L el = env->me_rpages, tl = txn->mt_rpages;
3238 unsigned i, x, n = tl[0].mid;
3239 pthread_mutex_lock(&env->me_rpmutex);
3240 for (i = 1; i <= n; i++) {
3241 if (tl[i].mid & (MDB_RPAGE_CHUNK-1)) {
3242 /* tmp overflow pages that we didn't share in env */
3243 munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
3245 x = mdb_mid3l_search(el, tl[i].mid);
3246 if (tl[i].mptr == el[x].mptr) {
3249 /* another tmp overflow page */
3250 munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
3254 pthread_mutex_unlock(&env->me_rpmutex);
3256 if (mode & MDB_END_FREE)
3260 if (mode & MDB_END_FREE)
3265 mdb_txn_reset(MDB_txn *txn)
3270 /* This call is only valid for read-only txns */
3271 if (!(txn->mt_flags & MDB_TXN_RDONLY))
3274 mdb_txn_end(txn, MDB_END_RESET);
3278 mdb_txn_abort(MDB_txn *txn)
3284 mdb_txn_abort(txn->mt_child);
3286 mdb_txn_end(txn, MDB_END_ABORT|MDB_END_SLOT|MDB_END_FREE);
3289 /** Save the freelist as of this transaction to the freeDB.
3290 * This changes the freelist. Keep trying until it stabilizes.
3292 * When (MDB_DEVEL) & 2, the changes do not affect #mdb_page_alloc(),
3293 * it then uses the transaction's original snapshot of the freeDB.
3296 mdb_freelist_save(MDB_txn *txn)
3298 /* env->me_pghead[] can grow and shrink during this call.
3299 * env->me_pglast and txn->mt_free_pgs[] can only grow.
3300 * Page numbers cannot disappear from txn->mt_free_pgs[].
3303 MDB_env *env = txn->mt_env;
3304 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
3305 txnid_t pglast = 0, head_id = 0;
3306 pgno_t freecnt = 0, *free_pgs, *mop;
3307 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
3309 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
3311 if (env->me_pghead) {
3312 /* Make sure first page of freeDB is touched and on freelist */
3313 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
3314 if (rc && rc != MDB_NOTFOUND)
3318 if (!env->me_pghead && txn->mt_loose_pgs) {
3319 /* Put loose page numbers in mt_free_pgs, since
3320 * we may be unable to return them to me_pghead.
3322 MDB_page *mp = txn->mt_loose_pgs;
3323 if ((rc = mdb_midl_need(&txn->mt_free_pgs, txn->mt_loose_count)) != 0)
3325 for (; mp; mp = NEXT_LOOSE_PAGE(mp))
3326 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
3327 txn->mt_loose_pgs = NULL;
3328 txn->mt_loose_count = 0;
3331 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
3332 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
3333 ? SSIZE_MAX : maxfree_1pg;
3336 /* Come back here after each Put() in case freelist changed */
3341 /* If using records from freeDB which we have not yet
3342 * deleted, delete them and any we reserved for me_pghead.
3344 while (pglast < env->me_pglast) {
3345 rc = mdb_cursor_first(&mc, &key, NULL);
3348 pglast = head_id = *(txnid_t *)key.mv_data;
3349 total_room = head_room = 0;
3350 mdb_tassert(txn, pglast <= env->me_pglast);
3351 rc = mdb_cursor_del(&mc, 0);
3356 /* Save the IDL of pages freed by this txn, to a single record */
3357 if (freecnt < txn->mt_free_pgs[0]) {
3359 /* Make sure last page of freeDB is touched and on freelist */
3360 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
3361 if (rc && rc != MDB_NOTFOUND)
3364 free_pgs = txn->mt_free_pgs;
3365 /* Write to last page of freeDB */
3366 key.mv_size = sizeof(txn->mt_txnid);
3367 key.mv_data = &txn->mt_txnid;
3369 freecnt = free_pgs[0];
3370 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
3371 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3374 /* Retry if mt_free_pgs[] grew during the Put() */
3375 free_pgs = txn->mt_free_pgs;
3376 } while (freecnt < free_pgs[0]);
3377 mdb_midl_sort(free_pgs);
3378 memcpy(data.mv_data, free_pgs, data.mv_size);
3381 unsigned int i = free_pgs[0];
3382 DPRINTF(("IDL write txn %"Yu" root %"Yu" num %u",
3383 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
3385 DPRINTF(("IDL %"Yu, free_pgs[i]));
3391 mop = env->me_pghead;
3392 mop_len = (mop ? mop[0] : 0) + txn->mt_loose_count;
3394 /* Reserve records for me_pghead[]. Split it if multi-page,
3395 * to avoid searching freeDB for a page range. Use keys in
3396 * range [1,me_pglast]: Smaller than txnid of oldest reader.
3398 if (total_room >= mop_len) {
3399 if (total_room == mop_len || --more < 0)
3401 } else if (head_room >= maxfree_1pg && head_id > 1) {
3402 /* Keep current record (overflow page), add a new one */
3406 /* (Re)write {key = head_id, IDL length = head_room} */
3407 total_room -= head_room;
3408 head_room = mop_len - total_room;
3409 if (head_room > maxfree_1pg && head_id > 1) {
3410 /* Overflow multi-page for part of me_pghead */
3411 head_room /= head_id; /* amortize page sizes */
3412 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
3413 } else if (head_room < 0) {
3414 /* Rare case, not bothering to delete this record */
3417 key.mv_size = sizeof(head_id);
3418 key.mv_data = &head_id;
3419 data.mv_size = (head_room + 1) * sizeof(pgno_t);
3420 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3423 /* IDL is initially empty, zero out at least the length */
3424 pgs = (pgno_t *)data.mv_data;
3425 j = head_room > clean_limit ? head_room : 0;
3429 total_room += head_room;
3432 /* Return loose page numbers to me_pghead, though usually none are
3433 * left at this point. The pages themselves remain in dirty_list.
3435 if (txn->mt_loose_pgs) {
3436 MDB_page *mp = txn->mt_loose_pgs;
3437 unsigned count = txn->mt_loose_count;
3439 /* Room for loose pages + temp IDL with same */
3440 if ((rc = mdb_midl_need(&env->me_pghead, 2*count+1)) != 0)
3442 mop = env->me_pghead;
3443 loose = mop + MDB_IDL_ALLOCLEN(mop) - count;
3444 for (count = 0; mp; mp = NEXT_LOOSE_PAGE(mp))
3445 loose[ ++count ] = mp->mp_pgno;
3447 mdb_midl_sort(loose);
3448 mdb_midl_xmerge(mop, loose);
3449 txn->mt_loose_pgs = NULL;
3450 txn->mt_loose_count = 0;
3454 /* Fill in the reserved me_pghead records */
3460 rc = mdb_cursor_first(&mc, &key, &data);
3461 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
3462 txnid_t id = *(txnid_t *)key.mv_data;
3463 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
3466 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
3468 if (len > mop_len) {
3470 data.mv_size = (len + 1) * sizeof(MDB_ID);
3472 data.mv_data = mop -= len;
3475 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
3477 if (rc || !(mop_len -= len))
3484 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
3485 * @param[in] txn the transaction that's being committed
3486 * @param[in] keep number of initial pages in dirty_list to keep dirty.
3487 * @return 0 on success, non-zero on failure.
3490 mdb_page_flush(MDB_txn *txn, int keep)
3492 MDB_env *env = txn->mt_env;
3493 MDB_ID2L dl = txn->mt_u.dirty_list;
3494 unsigned psize = env->me_psize, j;
3495 int i, pagecount = dl[0].mid, rc;
3499 MDB_page *dp = NULL;
3503 struct iovec iov[MDB_COMMIT_PAGES];
3504 ssize_t wsize = 0, wres;
3505 off_t wpos = 0, next_pos = 1; /* impossible pos, so pos != next_pos */
3511 if (env->me_flags & MDB_WRITEMAP) {
3512 /* Clear dirty flags */
3513 while (++i <= pagecount) {
3515 /* Don't flush this page yet */
3516 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3517 dp->mp_flags &= ~P_KEEP;
3521 dp->mp_flags &= ~P_DIRTY;
3526 /* Write the pages */
3528 if (++i <= pagecount) {
3530 /* Don't flush this page yet */
3531 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3532 dp->mp_flags &= ~P_KEEP;
3537 /* clear dirty flag */
3538 dp->mp_flags &= ~P_DIRTY;
3541 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
3546 /* Windows actually supports scatter/gather I/O, but only on
3547 * unbuffered file handles. Since we're relying on the OS page
3548 * cache for all our data, that's self-defeating. So we just
3549 * write pages one at a time. We use the ov structure to set
3550 * the write offset, to at least save the overhead of a Seek
3553 DPRINTF(("committing page %"Yu, pgno));
3554 memset(&ov, 0, sizeof(ov));
3555 ov.Offset = pos & 0xffffffff;
3556 ov.OffsetHigh = pos >> 16 >> 16;
3557 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
3559 DPRINTF(("WriteFile: %d", rc));
3563 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
3564 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
3567 /* Write previous page(s) */
3568 #ifdef MDB_USE_PWRITEV
3569 wres = pwritev(env->me_fd, iov, n, wpos);
3572 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
3575 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
3579 DPRINTF(("lseek: %s", strerror(rc)));
3582 wres = writev(env->me_fd, iov, n);
3585 if (wres != wsize) {
3590 DPRINTF(("Write error: %s", strerror(rc)));
3592 rc = EIO; /* TODO: Use which error code? */
3593 DPUTS("short write, filesystem full?");
3604 DPRINTF(("committing page %"Yu, pgno));
3605 next_pos = pos + size;
3606 iov[n].iov_len = size;
3607 iov[n].iov_base = (char *)dp;
3613 if (pgno > txn->mt_last_pgno)
3614 txn->mt_last_pgno = pgno;
3617 /* MIPS has cache coherency issues, this is a no-op everywhere else
3618 * Note: for any size >= on-chip cache size, entire on-chip cache is
3621 CACHEFLUSH(env->me_map, txn->mt_next_pgno * env->me_psize, DCACHE);
3623 for (i = keep; ++i <= pagecount; ) {
3625 /* This is a page we skipped above */
3628 dl[j].mid = dp->mp_pgno;
3631 mdb_dpage_free(env, dp);
3636 txn->mt_dirty_room += i - j;
3642 mdb_txn_commit(MDB_txn *txn)
3645 unsigned int i, end_mode;
3651 /* mdb_txn_end() mode for a commit which writes nothing */
3652 end_mode = MDB_END_EMPTY_COMMIT|MDB_END_UPDATE|MDB_END_SLOT|MDB_END_FREE;
3654 if (txn->mt_child) {
3655 rc = mdb_txn_commit(txn->mt_child);
3662 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3666 if (txn->mt_flags & (MDB_TXN_FINISHED|MDB_TXN_ERROR)) {
3667 DPUTS("txn has failed/finished, can't commit");
3669 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3674 if (txn->mt_parent) {
3675 MDB_txn *parent = txn->mt_parent;
3679 unsigned x, y, len, ps_len;
3681 /* Append our free list to parent's */
3682 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3685 mdb_midl_free(txn->mt_free_pgs);
3686 /* Failures after this must either undo the changes
3687 * to the parent or set MDB_TXN_ERROR in the parent.
3690 parent->mt_next_pgno = txn->mt_next_pgno;
3691 parent->mt_flags = txn->mt_flags;
3693 /* Merge our cursors into parent's and close them */
3694 mdb_cursors_close(txn, 1);
3696 /* Update parent's DB table. */
3697 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3698 parent->mt_numdbs = txn->mt_numdbs;
3699 parent->mt_dbflags[FREE_DBI] = txn->mt_dbflags[FREE_DBI];
3700 parent->mt_dbflags[MAIN_DBI] = txn->mt_dbflags[MAIN_DBI];
3701 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
3702 /* preserve parent's DB_NEW status */
3703 x = parent->mt_dbflags[i] & DB_NEW;
3704 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3707 dst = parent->mt_u.dirty_list;
3708 src = txn->mt_u.dirty_list;
3709 /* Remove anything in our dirty list from parent's spill list */
3710 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3712 pspill[0] = (pgno_t)-1;
3713 /* Mark our dirty pages as deleted in parent spill list */
3714 for (i=0, len=src[0].mid; ++i <= len; ) {
3715 MDB_ID pn = src[i].mid << 1;
3716 while (pn > pspill[x])
3718 if (pn == pspill[x]) {
3723 /* Squash deleted pagenums if we deleted any */
3724 for (x=y; ++x <= ps_len; )
3725 if (!(pspill[x] & 1))
3726 pspill[++y] = pspill[x];
3730 /* Remove anything in our spill list from parent's dirty list */
3731 if (txn->mt_spill_pgs && txn->mt_spill_pgs[0]) {
3732 for (i=1; i<=txn->mt_spill_pgs[0]; i++) {
3733 MDB_ID pn = txn->mt_spill_pgs[i];
3735 continue; /* deleted spillpg */
3737 y = mdb_mid2l_search(dst, pn);
3738 if (y <= dst[0].mid && dst[y].mid == pn) {
3740 while (y < dst[0].mid) {
3749 /* Find len = length of merging our dirty list with parent's */
3751 dst[0].mid = 0; /* simplify loops */
3752 if (parent->mt_parent) {
3753 len = x + src[0].mid;
3754 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3755 for (i = x; y && i; y--) {
3756 pgno_t yp = src[y].mid;
3757 while (yp < dst[i].mid)
3759 if (yp == dst[i].mid) {
3764 } else { /* Simplify the above for single-ancestor case */
3765 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3767 /* Merge our dirty list with parent's */
3769 for (i = len; y; dst[i--] = src[y--]) {
3770 pgno_t yp = src[y].mid;
3771 while (yp < dst[x].mid)
3772 dst[i--] = dst[x--];
3773 if (yp == dst[x].mid)
3774 free(dst[x--].mptr);
3776 mdb_tassert(txn, i == x);
3778 free(txn->mt_u.dirty_list);
3779 parent->mt_dirty_room = txn->mt_dirty_room;
3780 if (txn->mt_spill_pgs) {
3781 if (parent->mt_spill_pgs) {
3782 /* TODO: Prevent failure here, so parent does not fail */
3783 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3785 parent->mt_flags |= MDB_TXN_ERROR;
3786 mdb_midl_free(txn->mt_spill_pgs);
3787 mdb_midl_sort(parent->mt_spill_pgs);
3789 parent->mt_spill_pgs = txn->mt_spill_pgs;
3793 /* Append our loose page list to parent's */
3794 for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(*lp))
3796 *lp = txn->mt_loose_pgs;
3797 parent->mt_loose_count += txn->mt_loose_count;
3799 parent->mt_child = NULL;
3800 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3805 if (txn != env->me_txn) {
3806 DPUTS("attempt to commit unknown transaction");
3811 mdb_cursors_close(txn, 0);
3813 if (!txn->mt_u.dirty_list[0].mid &&
3814 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
3817 DPRINTF(("committing txn %"Yu" %p on mdbenv %p, root page %"Yu,
3818 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3820 /* Update DB root pointers */
3821 if (txn->mt_numdbs > CORE_DBS) {
3825 data.mv_size = sizeof(MDB_db);
3827 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3828 for (i = CORE_DBS; i < txn->mt_numdbs; i++) {
3829 if (txn->mt_dbflags[i] & DB_DIRTY) {
3830 if (TXN_DBI_CHANGED(txn, i)) {
3834 data.mv_data = &txn->mt_dbs[i];
3835 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data,
3843 rc = mdb_freelist_save(txn);
3847 mdb_midl_free(env->me_pghead);
3848 env->me_pghead = NULL;
3849 mdb_midl_shrink(&txn->mt_free_pgs);
3855 if ((rc = mdb_page_flush(txn, 0)))
3857 if (!F_ISSET(txn->mt_flags, MDB_TXN_NOSYNC) &&
3858 (rc = mdb_env_sync0(env, 0, txn->mt_next_pgno)))
3860 if ((rc = mdb_env_write_meta(txn)))
3862 end_mode = MDB_END_COMMITTED|MDB_END_UPDATE;
3865 mdb_txn_end(txn, end_mode);
3873 /** Read the environment parameters of a DB environment before
3874 * mapping it into memory.
3875 * @param[in] env the environment handle
3876 * @param[out] meta address of where to store the meta information
3877 * @return 0 on success, non-zero on failure.
3880 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3886 enum { Size = sizeof(pbuf) };
3888 /* We don't know the page size yet, so use a minimum value.
3889 * Read both meta pages so we can use the latest one.
3892 for (i=off=0; i<NUM_METAS; i++, off += meta->mm_psize) {
3896 memset(&ov, 0, sizeof(ov));
3898 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3899 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3902 rc = pread(env->me_fd, &pbuf, Size, off);
3905 if (rc == 0 && off == 0)
3907 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3908 DPRINTF(("read: %s", mdb_strerror(rc)));
3912 p = (MDB_page *)&pbuf;
3914 if (!F_ISSET(p->mp_flags, P_META)) {
3915 DPRINTF(("page %"Yu" not a meta page", p->mp_pgno));
3920 if (m->mm_magic != MDB_MAGIC) {
3921 DPUTS("meta has invalid magic");
3925 if (m->mm_version != MDB_DATA_VERSION) {
3926 DPRINTF(("database is version %u, expected version %u",
3927 m->mm_version, MDB_DATA_VERSION));
3928 return MDB_VERSION_MISMATCH;
3931 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3937 /** Fill in most of the zeroed #MDB_meta for an empty database environment */
3939 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
3941 meta->mm_magic = MDB_MAGIC;
3942 meta->mm_version = MDB_DATA_VERSION;
3943 meta->mm_mapsize = env->me_mapsize;
3944 meta->mm_psize = env->me_psize;
3945 meta->mm_last_pg = NUM_METAS-1;
3946 meta->mm_flags = env->me_flags & 0xffff;
3947 meta->mm_flags |= MDB_INTEGERKEY; /* this is mm_dbs[FREE_DBI].md_flags */
3948 meta->mm_dbs[FREE_DBI].md_root = P_INVALID;
3949 meta->mm_dbs[MAIN_DBI].md_root = P_INVALID;
3952 /** Write the environment parameters of a freshly created DB environment.
3953 * @param[in] env the environment handle
3954 * @param[in] meta the #MDB_meta to write
3955 * @return 0 on success, non-zero on failure.
3958 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3966 memset(&ov, 0, sizeof(ov));
3967 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3969 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3972 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3973 len = pwrite(fd, ptr, size, pos); \
3974 if (len == -1 && ErrCode() == EINTR) continue; \
3975 rc = (len >= 0); break; } while(1)
3978 DPUTS("writing new meta page");
3980 psize = env->me_psize;
3982 p = calloc(NUM_METAS, psize);
3986 p->mp_flags = P_META;
3987 *(MDB_meta *)METADATA(p) = *meta;
3989 q = (MDB_page *)((char *)p + psize);
3991 q->mp_flags = P_META;
3992 *(MDB_meta *)METADATA(q) = *meta;
3994 DO_PWRITE(rc, env->me_fd, p, psize * NUM_METAS, len, 0);
3997 else if ((unsigned) len == psize * NUM_METAS)
4005 /** Update the environment info to commit a transaction.
4006 * @param[in] txn the transaction that's being committed
4007 * @return 0 on success, non-zero on failure.
4010 mdb_env_write_meta(MDB_txn *txn)
4013 MDB_meta meta, metab, *mp;
4017 int rc, len, toggle;
4026 toggle = txn->mt_txnid & 1;
4027 DPRINTF(("writing meta page %d for root page %"Yu,
4028 toggle, txn->mt_dbs[MAIN_DBI].md_root));
4031 flags = txn->mt_flags | env->me_flags;
4032 mp = env->me_metas[toggle];
4033 mapsize = env->me_metas[toggle ^ 1]->mm_mapsize;
4034 /* Persist any increases of mapsize config */
4035 if (mapsize < env->me_mapsize)
4036 mapsize = env->me_mapsize;
4038 if (flags & MDB_WRITEMAP) {
4039 mp->mm_mapsize = mapsize;
4040 mp->mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
4041 mp->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
4042 mp->mm_last_pg = txn->mt_next_pgno - 1;
4043 #if (__GNUC__ * 100 + __GNUC_MINOR__ >= 404) && /* TODO: portability */ \
4044 !(defined(__i386__) || defined(__x86_64__))
4045 /* LY: issue a memory barrier, if not x86. ITS#7969 */
4046 __sync_synchronize();
4048 mp->mm_txnid = txn->mt_txnid;
4049 if (!(flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
4050 unsigned meta_size = env->me_psize;
4051 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
4052 ptr = (char *)mp - PAGEHDRSZ;
4053 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
4054 r2 = (ptr - env->me_map) & (env->me_os_psize - 1);
4058 if (MDB_MSYNC(ptr, meta_size, rc)) {
4065 metab.mm_txnid = mp->mm_txnid;
4066 metab.mm_last_pg = mp->mm_last_pg;
4068 meta.mm_mapsize = mapsize;
4069 meta.mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
4070 meta.mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
4071 meta.mm_last_pg = txn->mt_next_pgno - 1;
4072 meta.mm_txnid = txn->mt_txnid;
4074 off = offsetof(MDB_meta, mm_mapsize);
4075 ptr = (char *)&meta + off;
4076 len = sizeof(MDB_meta) - off;
4077 off += (char *)mp - env->me_map;
4079 /* Write to the SYNC fd */
4080 mfd = (flags & (MDB_NOSYNC|MDB_NOMETASYNC)) ? env->me_fd : env->me_mfd;
4083 memset(&ov, 0, sizeof(ov));
4085 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
4090 rc = pwrite(mfd, ptr, len, off);
4093 rc = rc < 0 ? ErrCode() : EIO;
4098 DPUTS("write failed, disk error?");
4099 /* On a failure, the pagecache still contains the new data.
4100 * Write some old data back, to prevent it from being used.
4101 * Use the non-SYNC fd; we know it will fail anyway.
4103 meta.mm_last_pg = metab.mm_last_pg;
4104 meta.mm_txnid = metab.mm_txnid;
4106 memset(&ov, 0, sizeof(ov));
4108 WriteFile(env->me_fd, ptr, len, NULL, &ov);
4110 r2 = pwrite(env->me_fd, ptr, len, off);
4111 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
4114 env->me_flags |= MDB_FATAL_ERROR;
4117 /* MIPS has cache coherency issues, this is a no-op everywhere else */
4118 CACHEFLUSH(env->me_map + off, len, DCACHE);
4120 /* Memory ordering issues are irrelevant; since the entire writer
4121 * is wrapped by wmutex, all of these changes will become visible
4122 * after the wmutex is unlocked. Since the DB is multi-version,
4123 * readers will get consistent data regardless of how fresh or
4124 * how stale their view of these values is.
4127 env->me_txns->mti_txnid = txn->mt_txnid;
4132 /** Check both meta pages to see which one is newer.
4133 * @param[in] env the environment handle
4134 * @return newest #MDB_meta.
4137 mdb_env_pick_meta(const MDB_env *env)
4139 MDB_meta *const *metas = env->me_metas;
4140 return metas[ metas[0]->mm_txnid < metas[1]->mm_txnid ];
4144 mdb_env_create(MDB_env **env)
4148 e = calloc(1, sizeof(MDB_env));
4152 e->me_maxreaders = DEFAULT_READERS;
4153 e->me_maxdbs = e->me_numdbs = CORE_DBS;
4154 e->me_fd = INVALID_HANDLE_VALUE;
4155 e->me_lfd = INVALID_HANDLE_VALUE;
4156 e->me_mfd = INVALID_HANDLE_VALUE;
4157 #ifdef MDB_USE_POSIX_SEM
4158 e->me_rmutex = SEM_FAILED;
4159 e->me_wmutex = SEM_FAILED;
4160 #elif defined MDB_USE_SYSV_SEM
4161 e->me_rmutex->semid = -1;
4162 e->me_wmutex->semid = -1;
4164 e->me_pid = getpid();
4165 GET_PAGESIZE(e->me_os_psize);
4166 VGMEMP_CREATE(e,0,0);
4172 /** @brief Map a result from an NTAPI call to WIN32. */
4174 mdb_nt2win32(NTSTATUS st)
4179 GetOverlappedResult(NULL, &o, &br, FALSE);
4180 return GetLastError();
4185 mdb_env_map(MDB_env *env, void *addr)
4188 unsigned int flags = env->me_flags;
4191 int access = SECTION_MAP_READ;
4195 ULONG pageprot = PAGE_READONLY, secprot, alloctype;
4197 if (flags & MDB_WRITEMAP) {
4198 access |= SECTION_MAP_WRITE;
4199 pageprot = PAGE_READWRITE;
4201 if (flags & MDB_RDONLY) {
4202 secprot = PAGE_READONLY;
4206 secprot = PAGE_READWRITE;
4207 msize = env->me_mapsize;
4208 alloctype = MEM_RESERVE;
4211 rc = NtCreateSection(&mh, access, NULL, NULL, secprot, SEC_RESERVE, env->me_fd);
4213 return mdb_nt2win32(rc);
4216 msize = NUM_METAS * env->me_psize;
4218 rc = NtMapViewOfSection(mh, GetCurrentProcess(), &map, 0, 0, NULL, &msize, ViewUnmap, alloctype, pageprot);
4225 return mdb_nt2win32(rc);
4230 env->me_map = mmap(addr, NUM_METAS * env->me_psize, PROT_READ, MAP_SHARED,
4232 if (env->me_map == MAP_FAILED) {
4237 int prot = PROT_READ;
4238 if (flags & MDB_WRITEMAP) {
4240 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
4243 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
4245 if (env->me_map == MAP_FAILED) {
4250 if (flags & MDB_NORDAHEAD) {
4251 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
4253 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
4255 #ifdef POSIX_MADV_RANDOM
4256 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
4257 #endif /* POSIX_MADV_RANDOM */
4258 #endif /* MADV_RANDOM */
4262 /* Can happen because the address argument to mmap() is just a
4263 * hint. mmap() can pick another, e.g. if the range is in use.
4264 * The MAP_FIXED flag would prevent that, but then mmap could
4265 * instead unmap existing pages to make room for the new map.
4267 if (addr && env->me_map != addr)
4268 return EBUSY; /* TODO: Make a new MDB_* error code? */
4271 p = (MDB_page *)env->me_map;
4272 env->me_metas[0] = METADATA(p);
4273 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
4279 mdb_env_set_mapsize(MDB_env *env, mdb_size_t size)
4281 /* If env is already open, caller is responsible for making
4282 * sure there are no active txns.
4292 meta = mdb_env_pick_meta(env);
4294 size = meta->mm_mapsize;
4296 /* Silently round up to minimum if the size is too small */
4297 mdb_size_t minsize = (meta->mm_last_pg + 1) * env->me_psize;
4302 /* For MDB_VL32 this bit is a noop since we dynamically remap
4303 * chunks of the DB anyway.
4305 munmap(env->me_map, env->me_mapsize);
4306 env->me_mapsize = size;
4307 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
4308 rc = mdb_env_map(env, old);
4311 #endif /* !MDB_VL32 */
4313 env->me_mapsize = size;
4315 env->me_maxpg = env->me_mapsize / env->me_psize;
4320 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
4324 env->me_maxdbs = dbs + CORE_DBS;
4329 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
4331 if (env->me_map || readers < 1)
4333 env->me_maxreaders = readers;
4338 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
4340 if (!env || !readers)
4342 *readers = env->me_maxreaders;
4347 mdb_fsize(HANDLE fd, mdb_size_t *size)
4350 LARGE_INTEGER fsize;
4352 if (!GetFileSizeEx(fd, &fsize))
4355 *size = fsize.QuadPart;
4367 #ifdef BROKEN_FDATASYNC
4368 #include <sys/utsname.h>
4369 #include <sys/vfs.h>
4372 /** Further setup required for opening an LMDB environment
4375 mdb_env_open2(MDB_env *env)
4377 unsigned int flags = env->me_flags;
4378 int i, newenv = 0, rc;
4382 /* See if we should use QueryLimited */
4384 if ((rc & 0xff) > 5)
4385 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
4387 env->me_pidquery = PROCESS_QUERY_INFORMATION;
4390 #ifdef BROKEN_FDATASYNC
4391 /* ext3/ext4 fdatasync is broken on some older Linux kernels.
4392 * https://lkml.org/lkml/2012/9/3/83
4393 * Kernels after 3.6-rc6 are known good.
4394 * https://lkml.org/lkml/2012/9/10/556
4395 * See if the DB is on ext3/ext4, then check for new enough kernel
4396 * Kernels 2.6.32.60, 2.6.34.15, 3.2.30, and 3.5.4 are also known
4401 fstatfs(env->me_fd, &st);
4402 while (st.f_type == 0xEF53) {
4406 if (uts.release[0] < '3') {
4407 if (!strncmp(uts.release, "2.6.32.", 7)) {
4408 i = atoi(uts.release+7);
4410 break; /* 2.6.32.60 and newer is OK */
4411 } else if (!strncmp(uts.release, "2.6.34.", 7)) {
4412 i = atoi(uts.release+7);
4414 break; /* 2.6.34.15 and newer is OK */
4416 } else if (uts.release[0] == '3') {
4417 i = atoi(uts.release+2);
4419 break; /* 3.6 and newer is OK */
4421 i = atoi(uts.release+4);
4423 break; /* 3.5.4 and newer is OK */
4424 } else if (i == 2) {
4425 i = atoi(uts.release+4);
4427 break; /* 3.2.30 and newer is OK */
4429 } else { /* 4.x and newer is OK */
4432 env->me_flags |= MDB_FSYNCONLY;
4438 if ((i = mdb_env_read_header(env, &meta)) != 0) {
4441 DPUTS("new mdbenv");
4443 env->me_psize = env->me_os_psize;
4444 if (env->me_psize > MAX_PAGESIZE)
4445 env->me_psize = MAX_PAGESIZE;
4446 memset(&meta, 0, sizeof(meta));
4447 mdb_env_init_meta0(env, &meta);
4448 meta.mm_mapsize = DEFAULT_MAPSIZE;
4450 env->me_psize = meta.mm_psize;
4453 /* Was a mapsize configured? */
4454 if (!env->me_mapsize) {
4455 env->me_mapsize = meta.mm_mapsize;
4458 /* Make sure mapsize >= committed data size. Even when using
4459 * mm_mapsize, which could be broken in old files (ITS#7789).
4461 mdb_size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
4462 if (env->me_mapsize < minsize)
4463 env->me_mapsize = minsize;
4465 meta.mm_mapsize = env->me_mapsize;
4467 if (newenv && !(flags & MDB_FIXEDMAP)) {
4468 /* mdb_env_map() may grow the datafile. Write the metapages
4469 * first, so the file will be valid if initialization fails.
4470 * Except with FIXEDMAP, since we do not yet know mm_address.
4471 * We could fill in mm_address later, but then a different
4472 * program might end up doing that - one with a memory layout
4473 * and map address which does not suit the main program.
4475 rc = mdb_env_init_meta(env, &meta);
4481 /* For FIXEDMAP, make sure the file is non-empty before we attempt to map it */
4485 rc = WriteFile(env->me_fd, &dummy, 1, &len, NULL);
4493 rc = mdb_env_map(env, (flags & MDB_FIXEDMAP) ? meta.mm_address : NULL);
4498 if (flags & MDB_FIXEDMAP)
4499 meta.mm_address = env->me_map;
4500 i = mdb_env_init_meta(env, &meta);
4501 if (i != MDB_SUCCESS) {
4506 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
4507 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
4509 #if !(MDB_MAXKEYSIZE)
4510 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
4512 env->me_maxpg = env->me_mapsize / env->me_psize;
4516 MDB_meta *meta = mdb_env_pick_meta(env);
4517 MDB_db *db = &meta->mm_dbs[MAIN_DBI];
4519 DPRINTF(("opened database version %u, pagesize %u",
4520 meta->mm_version, env->me_psize));
4521 DPRINTF(("using meta page %d", (int) (meta->mm_txnid & 1)));
4522 DPRINTF(("depth: %u", db->md_depth));
4523 DPRINTF(("entries: %"Yu, db->md_entries));
4524 DPRINTF(("branch pages: %"Yu, db->md_branch_pages));
4525 DPRINTF(("leaf pages: %"Yu, db->md_leaf_pages));
4526 DPRINTF(("overflow pages: %"Yu, db->md_overflow_pages));
4527 DPRINTF(("root: %"Yu, db->md_root));
4535 /** Release a reader thread's slot in the reader lock table.
4536 * This function is called automatically when a thread exits.
4537 * @param[in] ptr This points to the slot in the reader lock table.
4540 mdb_env_reader_dest(void *ptr)
4542 MDB_reader *reader = ptr;
4548 /** Junk for arranging thread-specific callbacks on Windows. This is
4549 * necessarily platform and compiler-specific. Windows supports up
4550 * to 1088 keys. Let's assume nobody opens more than 64 environments
4551 * in a single process, for now. They can override this if needed.
4553 #ifndef MAX_TLS_KEYS
4554 #define MAX_TLS_KEYS 64
4556 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
4557 static int mdb_tls_nkeys;
4559 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
4563 case DLL_PROCESS_ATTACH: break;
4564 case DLL_THREAD_ATTACH: break;
4565 case DLL_THREAD_DETACH:
4566 for (i=0; i<mdb_tls_nkeys; i++) {
4567 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
4569 mdb_env_reader_dest(r);
4573 case DLL_PROCESS_DETACH: break;
4578 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4580 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4584 /* Force some symbol references.
4585 * _tls_used forces the linker to create the TLS directory if not already done
4586 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
4588 #pragma comment(linker, "/INCLUDE:_tls_used")
4589 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
4590 #pragma const_seg(".CRT$XLB")
4591 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
4592 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4595 #pragma comment(linker, "/INCLUDE:__tls_used")
4596 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
4597 #pragma data_seg(".CRT$XLB")
4598 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4600 #endif /* WIN 32/64 */
4601 #endif /* !__GNUC__ */
4604 /** Downgrade the exclusive lock on the region back to shared */
4606 mdb_env_share_locks(MDB_env *env, int *excl)
4609 MDB_meta *meta = mdb_env_pick_meta(env);
4611 env->me_txns->mti_txnid = meta->mm_txnid;
4616 /* First acquire a shared lock. The Unlock will
4617 * then release the existing exclusive lock.
4619 memset(&ov, 0, sizeof(ov));
4620 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4623 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4629 struct flock lock_info;
4630 /* The shared lock replaces the existing lock */
4631 memset((void *)&lock_info, 0, sizeof(lock_info));
4632 lock_info.l_type = F_RDLCK;
4633 lock_info.l_whence = SEEK_SET;
4634 lock_info.l_start = 0;
4635 lock_info.l_len = 1;
4636 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4637 (rc = ErrCode()) == EINTR) ;
4638 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
4645 /** Try to get exclusive lock, otherwise shared.
4646 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
4649 mdb_env_excl_lock(MDB_env *env, int *excl)
4653 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
4657 memset(&ov, 0, sizeof(ov));
4658 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4665 struct flock lock_info;
4666 memset((void *)&lock_info, 0, sizeof(lock_info));
4667 lock_info.l_type = F_WRLCK;
4668 lock_info.l_whence = SEEK_SET;
4669 lock_info.l_start = 0;
4670 lock_info.l_len = 1;
4671 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4672 (rc = ErrCode()) == EINTR) ;
4676 # ifndef MDB_USE_POSIX_MUTEX
4677 if (*excl < 0) /* always true when MDB_USE_POSIX_MUTEX */
4680 lock_info.l_type = F_RDLCK;
4681 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
4682 (rc = ErrCode()) == EINTR) ;
4692 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
4694 * @(#) $Revision: 5.1 $
4695 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
4696 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
4698 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
4702 * Please do not copyright this code. This code is in the public domain.
4704 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
4705 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
4706 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
4707 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
4708 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4709 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4710 * PERFORMANCE OF THIS SOFTWARE.
4713 * chongo <Landon Curt Noll> /\oo/\
4714 * http://www.isthe.com/chongo/
4716 * Share and Enjoy! :-)
4719 typedef unsigned long long mdb_hash_t;
4720 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
4722 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
4723 * @param[in] val value to hash
4724 * @param[in] hval initial value for hash
4725 * @return 64 bit hash
4727 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
4728 * hval arg on the first call.
4731 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
4733 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
4734 unsigned char *end = s + val->mv_size;
4736 * FNV-1a hash each octet of the string
4739 /* xor the bottom with the current octet */
4740 hval ^= (mdb_hash_t)*s++;
4742 /* multiply by the 64 bit FNV magic prime mod 2^64 */
4743 hval += (hval << 1) + (hval << 4) + (hval << 5) +
4744 (hval << 7) + (hval << 8) + (hval << 40);
4746 /* return our new hash value */
4750 /** Hash the string and output the encoded hash.
4751 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
4752 * very short name limits. We don't care about the encoding being reversible,
4753 * we just want to preserve as many bits of the input as possible in a
4754 * small printable string.
4755 * @param[in] str string to hash
4756 * @param[out] encbuf an array of 11 chars to hold the hash
4758 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
4761 mdb_pack85(unsigned long l, char *out)
4765 for (i=0; i<5; i++) {
4766 *out++ = mdb_a85[l % 85];
4772 mdb_hash_enc(MDB_val *val, char *encbuf)
4774 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
4776 mdb_pack85(h, encbuf);
4777 mdb_pack85(h>>32, encbuf+5);
4782 /** Open and/or initialize the lock region for the environment.
4783 * @param[in] env The LMDB environment.
4784 * @param[in] lpath The pathname of the file used for the lock region.
4785 * @param[in] mode The Unix permissions for the file, if we create it.
4786 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
4787 * @return 0 on success, non-zero on failure.
4790 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
4793 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
4795 # define MDB_ERRCODE_ROFS EROFS
4796 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
4797 # define MDB_CLOEXEC O_CLOEXEC
4800 # define MDB_CLOEXEC 0
4803 #ifdef MDB_USE_SYSV_SEM
4812 rc = utf8_to_utf16(lpath, -1, &wlpath, NULL);
4815 env->me_lfd = CreateFileW(wlpath, GENERIC_READ|GENERIC_WRITE,
4816 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
4817 FILE_ATTRIBUTE_NORMAL, NULL);
4820 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
4822 if (env->me_lfd == INVALID_HANDLE_VALUE) {
4824 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
4829 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
4830 /* Lose record locks when exec*() */
4831 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
4832 fcntl(env->me_lfd, F_SETFD, fdflags);
4835 if (!(env->me_flags & MDB_NOTLS)) {
4836 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
4839 env->me_flags |= MDB_ENV_TXKEY;
4841 /* Windows TLS callbacks need help finding their TLS info. */
4842 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
4846 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
4850 /* Try to get exclusive lock. If we succeed, then
4851 * nobody is using the lock region and we should initialize it.
4853 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
4856 size = GetFileSize(env->me_lfd, NULL);
4858 size = lseek(env->me_lfd, 0, SEEK_END);
4859 if (size == -1) goto fail_errno;
4861 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
4862 if (size < rsize && *excl > 0) {
4864 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
4865 || !SetEndOfFile(env->me_lfd))
4868 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
4872 size = rsize - sizeof(MDB_txninfo);
4873 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
4878 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
4880 if (!mh) goto fail_errno;
4881 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
4883 if (!env->me_txns) goto fail_errno;
4885 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
4887 if (m == MAP_FAILED) goto fail_errno;
4893 BY_HANDLE_FILE_INFORMATION stbuf;
4902 if (!mdb_sec_inited) {
4903 InitializeSecurityDescriptor(&mdb_null_sd,
4904 SECURITY_DESCRIPTOR_REVISION);
4905 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
4906 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
4907 mdb_all_sa.bInheritHandle = FALSE;
4908 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
4911 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
4912 idbuf.volume = stbuf.dwVolumeSerialNumber;
4913 idbuf.nhigh = stbuf.nFileIndexHigh;
4914 idbuf.nlow = stbuf.nFileIndexLow;
4915 val.mv_data = &idbuf;
4916 val.mv_size = sizeof(idbuf);
4917 mdb_hash_enc(&val, encbuf);
4918 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
4919 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
4920 env->me_rmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
4921 if (!env->me_rmutex) goto fail_errno;
4922 env->me_wmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
4923 if (!env->me_wmutex) goto fail_errno;
4924 #elif defined(MDB_USE_POSIX_SEM)
4933 #if defined(__NetBSD__)
4934 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
4936 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
4937 idbuf.dev = stbuf.st_dev;
4938 idbuf.ino = stbuf.st_ino;
4939 val.mv_data = &idbuf;
4940 val.mv_size = sizeof(idbuf);
4941 mdb_hash_enc(&val, encbuf);
4942 #ifdef MDB_SHORT_SEMNAMES
4943 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
4945 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
4946 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
4947 /* Clean up after a previous run, if needed: Try to
4948 * remove both semaphores before doing anything else.
4950 sem_unlink(env->me_txns->mti_rmname);
4951 sem_unlink(env->me_txns->mti_wmname);
4952 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
4953 O_CREAT|O_EXCL, mode, 1);
4954 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4955 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
4956 O_CREAT|O_EXCL, mode, 1);
4957 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4958 #elif defined(MDB_USE_SYSV_SEM)
4959 unsigned short vals[2] = {1, 1};
4960 key_t key = ftok(lpath, 'M');
4963 semid = semget(key, 2, (mode & 0777) | IPC_CREAT);
4967 if (semctl(semid, 0, SETALL, semu) < 0)
4969 env->me_txns->mti_semid = semid;
4970 env->me_txns->mti_rlocked = 0;
4971 env->me_txns->mti_wlocked = 0;
4972 #else /* MDB_USE_POSIX_MUTEX: */
4973 pthread_mutexattr_t mattr;
4975 /* Solaris needs this before initing a robust mutex. Otherwise
4976 * it may skip the init and return EBUSY "seems someone already
4977 * inited" or EINVAL "it was inited differently".
4979 memset(env->me_txns->mti_rmutex, 0, sizeof(*env->me_txns->mti_rmutex));
4980 memset(env->me_txns->mti_wmutex, 0, sizeof(*env->me_txns->mti_wmutex));
4982 if ((rc = pthread_mutexattr_init(&mattr)) != 0)
4984 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
4985 #ifdef MDB_ROBUST_SUPPORTED
4986 if (!rc) rc = pthread_mutexattr_setrobust(&mattr, PTHREAD_MUTEX_ROBUST);
4988 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_rmutex, &mattr);
4989 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_wmutex, &mattr);
4990 pthread_mutexattr_destroy(&mattr);
4993 #endif /* _WIN32 || ... */
4995 env->me_txns->mti_magic = MDB_MAGIC;
4996 env->me_txns->mti_format = MDB_LOCK_FORMAT;
4997 env->me_txns->mti_txnid = 0;
4998 env->me_txns->mti_numreaders = 0;
5001 #ifdef MDB_USE_SYSV_SEM
5002 struct semid_ds buf;
5004 if (env->me_txns->mti_magic != MDB_MAGIC) {
5005 DPUTS("lock region has invalid magic");
5009 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
5010 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
5011 env->me_txns->mti_format, MDB_LOCK_FORMAT));
5012 rc = MDB_VERSION_MISMATCH;
5016 if (rc && rc != EACCES && rc != EAGAIN) {
5020 env->me_rmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
5021 if (!env->me_rmutex) goto fail_errno;
5022 env->me_wmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
5023 if (!env->me_wmutex) goto fail_errno;
5024 #elif defined(MDB_USE_POSIX_SEM)
5025 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
5026 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
5027 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
5028 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
5029 #elif defined(MDB_USE_SYSV_SEM)
5030 semid = env->me_txns->mti_semid;
5032 /* check for read access */
5033 if (semctl(semid, 0, IPC_STAT, semu) < 0)
5035 /* check for write access */
5036 if (semctl(semid, 0, IPC_SET, semu) < 0)
5040 #ifdef MDB_USE_SYSV_SEM
5041 env->me_rmutex->semid = semid;
5042 env->me_wmutex->semid = semid;
5043 env->me_rmutex->semnum = 0;
5044 env->me_wmutex->semnum = 1;
5045 env->me_rmutex->locked = &env->me_txns->mti_rlocked;
5046 env->me_wmutex->locked = &env->me_txns->mti_wlocked;
5050 env->me_rpmutex = CreateMutex(NULL, FALSE, NULL);
5052 pthread_mutex_init(&env->me_rpmutex, NULL);
5064 /** The name of the lock file in the DB environment */
5065 #define LOCKNAME "/lock.mdb"
5066 /** The name of the data file in the DB environment */
5067 #define DATANAME "/data.mdb"
5068 /** The suffix of the lock file when no subdir is used */
5069 #define LOCKSUFF "-lock"
5070 /** Only a subset of the @ref mdb_env flags can be changed
5071 * at runtime. Changing other flags requires closing the
5072 * environment and re-opening it with the new flags.
5074 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
5075 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY| \
5076 MDB_WRITEMAP|MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
5078 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
5079 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
5083 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
5085 int oflags, rc, len, excl = -1;
5086 char *lpath, *dpath;
5091 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
5095 if (flags & MDB_WRITEMAP) {
5096 /* silently ignore WRITEMAP in 32 bit mode */
5097 flags ^= MDB_WRITEMAP;
5099 if (flags & MDB_FIXEDMAP) {
5100 /* cannot support FIXEDMAP */
5106 if (flags & MDB_NOSUBDIR) {
5107 rc = len + sizeof(LOCKSUFF) + len + 1;
5109 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
5114 if (flags & MDB_NOSUBDIR) {
5115 dpath = lpath + len + sizeof(LOCKSUFF);
5116 sprintf(lpath, "%s" LOCKSUFF, path);
5117 strcpy(dpath, path);
5119 dpath = lpath + len + sizeof(LOCKNAME);
5120 sprintf(lpath, "%s" LOCKNAME, path);
5121 sprintf(dpath, "%s" DATANAME, path);
5125 flags |= env->me_flags;
5126 if (flags & MDB_RDONLY) {
5127 /* silently ignore WRITEMAP when we're only getting read access */
5128 flags &= ~MDB_WRITEMAP;
5130 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
5131 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
5136 env->me_rpages = malloc(MDB_ERPAGE_SIZE * sizeof(MDB_ID3));
5137 if (!env->me_rpages) {
5141 env->me_rpages[0].mid = 0;
5142 env->me_rpcheck = MDB_ERPAGE_SIZE/2;
5145 env->me_flags = flags |= MDB_ENV_ACTIVE;
5149 env->me_path = strdup(path);
5150 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
5151 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
5152 env->me_dbiseqs = calloc(env->me_maxdbs, sizeof(unsigned int));
5153 if (!(env->me_dbxs && env->me_path && env->me_dbflags && env->me_dbiseqs)) {
5157 env->me_dbxs[FREE_DBI].md_cmp = mdb_cmp_long; /* aligned MDB_INTEGERKEY */
5159 /* For RDONLY, get lockfile after we know datafile exists */
5160 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
5161 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
5167 if (F_ISSET(flags, MDB_RDONLY)) {
5168 oflags = GENERIC_READ;
5169 len = OPEN_EXISTING;
5171 oflags = GENERIC_READ|GENERIC_WRITE;
5174 mode = FILE_ATTRIBUTE_NORMAL;
5175 rc = utf8_to_utf16(dpath, -1, &wpath, NULL);
5178 env->me_fd = CreateFileW(wpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
5179 NULL, len, mode, NULL);
5182 if (F_ISSET(flags, MDB_RDONLY))
5185 oflags = O_RDWR | O_CREAT;
5187 env->me_fd = open(dpath, oflags, mode);
5189 if (env->me_fd == INVALID_HANDLE_VALUE) {
5194 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
5195 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
5200 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
5201 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
5202 env->me_mfd = env->me_fd;
5204 /* Synchronous fd for meta writes. Needed even with
5205 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
5208 len = OPEN_EXISTING;
5209 rc = utf8_to_utf16(dpath, -1, &wpath, NULL);
5212 env->me_mfd = CreateFileW(wpath, oflags,
5213 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
5214 mode | FILE_FLAG_WRITE_THROUGH, NULL);
5218 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
5220 if (env->me_mfd == INVALID_HANDLE_VALUE) {
5225 DPRINTF(("opened dbenv %p", (void *) env));
5227 rc = mdb_env_share_locks(env, &excl);
5231 if (!(flags & MDB_RDONLY)) {
5233 int tsize = sizeof(MDB_txn), size = tsize + env->me_maxdbs *
5234 (sizeof(MDB_db)+sizeof(MDB_cursor *)+sizeof(unsigned int)+1);
5235 if ((env->me_pbuf = calloc(1, env->me_psize)) &&
5236 (txn = calloc(1, size)))
5238 txn->mt_dbs = (MDB_db *)((char *)txn + tsize);
5239 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
5240 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
5241 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
5244 txn->mt_rpages = malloc(MDB_TRPAGE_SIZE * sizeof(MDB_ID3));
5245 if (!txn->mt_rpages) {
5250 txn->mt_rpages[0].mid = 0;
5251 txn->mt_rpcheck = MDB_TRPAGE_SIZE/2;
5253 txn->mt_dbxs = env->me_dbxs;
5254 txn->mt_flags = MDB_TXN_FINISHED;
5264 mdb_env_close0(env, excl);
5270 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
5272 mdb_env_close0(MDB_env *env, int excl)
5276 if (!(env->me_flags & MDB_ENV_ACTIVE))
5279 /* Doing this here since me_dbxs may not exist during mdb_env_close */
5281 for (i = env->me_maxdbs; --i >= CORE_DBS; )
5282 free(env->me_dbxs[i].md_name.mv_data);
5287 free(env->me_dbiseqs);
5288 free(env->me_dbflags);
5290 free(env->me_dirty_list);
5292 if (env->me_txn0 && env->me_txn0->mt_rpages)
5293 free(env->me_txn0->mt_rpages);
5295 for (x=1; x<=env->me_rpages[0].mid; x++)
5296 munmap(env->me_rpages[x].mptr, env->me_rpages[x].mcnt * env->me_psize);
5298 free(env->me_rpages);
5301 mdb_midl_free(env->me_free_pgs);
5303 if (env->me_flags & MDB_ENV_TXKEY) {
5304 pthread_key_delete(env->me_txkey);
5306 /* Delete our key from the global list */
5307 for (i=0; i<mdb_tls_nkeys; i++)
5308 if (mdb_tls_keys[i] == env->me_txkey) {
5309 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
5318 munmap(env->me_map, NUM_METAS*env->me_psize);
5320 munmap(env->me_map, env->me_mapsize);
5323 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
5324 (void) close(env->me_mfd);
5325 if (env->me_fd != INVALID_HANDLE_VALUE)
5326 (void) close(env->me_fd);
5328 MDB_PID_T pid = env->me_pid;
5329 /* Clearing readers is done in this function because
5330 * me_txkey with its destructor must be disabled first.
5332 * We skip the the reader mutex, so we touch only
5333 * data owned by this process (me_close_readers and
5334 * our readers), and clear each reader atomically.
5336 for (i = env->me_close_readers; --i >= 0; )
5337 if (env->me_txns->mti_readers[i].mr_pid == pid)
5338 env->me_txns->mti_readers[i].mr_pid = 0;
5340 if (env->me_rmutex) {
5341 CloseHandle(env->me_rmutex);
5342 if (env->me_wmutex) CloseHandle(env->me_wmutex);
5344 /* Windows automatically destroys the mutexes when
5345 * the last handle closes.
5347 #elif defined(MDB_USE_POSIX_SEM)
5348 if (env->me_rmutex != SEM_FAILED) {
5349 sem_close(env->me_rmutex);
5350 if (env->me_wmutex != SEM_FAILED)
5351 sem_close(env->me_wmutex);
5352 /* If we have the filelock: If we are the
5353 * only remaining user, clean up semaphores.
5356 mdb_env_excl_lock(env, &excl);
5358 sem_unlink(env->me_txns->mti_rmname);
5359 sem_unlink(env->me_txns->mti_wmname);
5362 #elif defined(MDB_USE_SYSV_SEM)
5363 if (env->me_rmutex->semid != -1) {
5364 /* If we have the filelock: If we are the
5365 * only remaining user, clean up semaphores.
5368 mdb_env_excl_lock(env, &excl);
5370 semctl(env->me_rmutex->semid, 0, IPC_RMID);
5373 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
5375 if (env->me_lfd != INVALID_HANDLE_VALUE) {
5378 /* Unlock the lockfile. Windows would have unlocked it
5379 * after closing anyway, but not necessarily at once.
5381 UnlockFile(env->me_lfd, 0, 0, 1, 0);
5384 (void) close(env->me_lfd);
5388 if (env->me_fmh) CloseHandle(env->me_fmh);
5389 if (env->me_rpmutex) CloseHandle(env->me_rpmutex);
5391 pthread_mutex_destroy(&env->me_rpmutex);
5395 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
5399 mdb_env_close(MDB_env *env)
5406 VGMEMP_DESTROY(env);
5407 while ((dp = env->me_dpages) != NULL) {
5408 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
5409 env->me_dpages = dp->mp_next;
5413 mdb_env_close0(env, 0);
5417 /** Compare two items pointing at aligned mdb_size_t's */
5419 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
5421 return (*(mdb_size_t *)a->mv_data < *(mdb_size_t *)b->mv_data) ? -1 :
5422 *(mdb_size_t *)a->mv_data > *(mdb_size_t *)b->mv_data;
5425 /** Compare two items pointing at aligned unsigned int's.
5427 * This is also set as #MDB_INTEGERDUP|#MDB_DUPFIXED's #MDB_dbx.%md_dcmp,
5428 * but #mdb_cmp_clong() is called instead if the data type is mdb_size_t.
5431 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
5433 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
5434 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
5437 /** Compare two items pointing at unsigned ints of unknown alignment.
5438 * Nodes and keys are guaranteed to be 2-byte aligned.
5441 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
5443 #if BYTE_ORDER == LITTLE_ENDIAN
5444 unsigned short *u, *c;
5447 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5448 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
5451 } while(!x && u > (unsigned short *)a->mv_data);
5454 unsigned short *u, *c, *end;
5457 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5458 u = (unsigned short *)a->mv_data;
5459 c = (unsigned short *)b->mv_data;
5462 } while(!x && u < end);
5467 /** Compare two items lexically */
5469 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
5476 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5482 diff = memcmp(a->mv_data, b->mv_data, len);
5483 return diff ? diff : len_diff<0 ? -1 : len_diff;
5486 /** Compare two items in reverse byte order */
5488 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
5490 const unsigned char *p1, *p2, *p1_lim;
5494 p1_lim = (const unsigned char *)a->mv_data;
5495 p1 = (const unsigned char *)a->mv_data + a->mv_size;
5496 p2 = (const unsigned char *)b->mv_data + b->mv_size;
5498 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5504 while (p1 > p1_lim) {
5505 diff = *--p1 - *--p2;
5509 return len_diff<0 ? -1 : len_diff;
5512 /** Search for key within a page, using binary search.
5513 * Returns the smallest entry larger or equal to the key.
5514 * If exactp is non-null, stores whether the found entry was an exact match
5515 * in *exactp (1 or 0).
5516 * Updates the cursor index with the index of the found entry.
5517 * If no entry larger or equal to the key is found, returns NULL.
5520 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
5522 unsigned int i = 0, nkeys;
5525 MDB_page *mp = mc->mc_pg[mc->mc_top];
5526 MDB_node *node = NULL;
5531 nkeys = NUMKEYS(mp);
5533 DPRINTF(("searching %u keys in %s %spage %"Yu,
5534 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
5537 low = IS_LEAF(mp) ? 0 : 1;
5539 cmp = mc->mc_dbx->md_cmp;
5541 /* Branch pages have no data, so if using integer keys,
5542 * alignment is guaranteed. Use faster mdb_cmp_int.
5544 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
5545 if (NODEPTR(mp, 1)->mn_ksize == sizeof(mdb_size_t))
5552 nodekey.mv_size = mc->mc_db->md_pad;
5553 node = NODEPTR(mp, 0); /* fake */
5554 while (low <= high) {
5555 i = (low + high) >> 1;
5556 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
5557 rc = cmp(key, &nodekey);
5558 DPRINTF(("found leaf index %u [%s], rc = %i",
5559 i, DKEY(&nodekey), rc));
5568 while (low <= high) {
5569 i = (low + high) >> 1;
5571 node = NODEPTR(mp, i);
5572 nodekey.mv_size = NODEKSZ(node);
5573 nodekey.mv_data = NODEKEY(node);
5575 rc = cmp(key, &nodekey);
5578 DPRINTF(("found leaf index %u [%s], rc = %i",
5579 i, DKEY(&nodekey), rc));
5581 DPRINTF(("found branch index %u [%s -> %"Yu"], rc = %i",
5582 i, DKEY(&nodekey), NODEPGNO(node), rc));
5593 if (rc > 0) { /* Found entry is less than the key. */
5594 i++; /* Skip to get the smallest entry larger than key. */
5596 node = NODEPTR(mp, i);
5599 *exactp = (rc == 0 && nkeys > 0);
5600 /* store the key index */
5601 mc->mc_ki[mc->mc_top] = i;
5603 /* There is no entry larger or equal to the key. */
5606 /* nodeptr is fake for LEAF2 */
5612 mdb_cursor_adjust(MDB_cursor *mc, func)
5616 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5617 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
5624 /** Pop a page off the top of the cursor's stack. */
5626 mdb_cursor_pop(MDB_cursor *mc)
5629 DPRINTF(("popping page %"Yu" off db %d cursor %p",
5630 mc->mc_pg[mc->mc_top]->mp_pgno, DDBI(mc), (void *) mc));
5636 mc->mc_flags &= ~C_INITIALIZED;
5641 /** Push a page onto the top of the cursor's stack. */
5643 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
5645 DPRINTF(("pushing page %"Yu" on db %d cursor %p", mp->mp_pgno,
5646 DDBI(mc), (void *) mc));
5648 if (mc->mc_snum >= CURSOR_STACK) {
5649 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5650 return MDB_CURSOR_FULL;
5653 mc->mc_top = mc->mc_snum++;
5654 mc->mc_pg[mc->mc_top] = mp;
5655 mc->mc_ki[mc->mc_top] = 0;
5661 /** Map a read-only page.
5662 * There are two levels of tracking in use, a per-txn list and a per-env list.
5663 * ref'ing and unref'ing the per-txn list is faster since it requires no
5664 * locking. Pages are cached in the per-env list for global reuse, and a lock
5665 * is required. Pages are not immediately unmapped when their refcnt goes to
5666 * zero; they hang around in case they will be reused again soon.
5668 * When the per-txn list gets full, all pages with refcnt=0 are purged from the
5669 * list and their refcnts in the per-env list are decremented.
5671 * When the per-env list gets full, all pages with refcnt=0 are purged from the
5672 * list and their pages are unmapped.
5674 * @note "full" means the list has reached its respective rpcheck threshold.
5675 * This threshold slowly raises if no pages could be purged on a given check,
5676 * and returns to its original value when enough pages were purged.
5678 * If purging doesn't free any slots, filling the per-txn list will return
5679 * MDB_TXN_FULL, and filling the per-env list returns MDB_MAP_FULL.
5681 * Reference tracking in a txn is imperfect, pages can linger with non-zero
5682 * refcnt even without active references. It was deemed to be too invasive
5683 * to add unrefs in every required location. However, all pages are unref'd
5684 * at the end of the transaction. This guarantees that no stale references
5685 * linger in the per-env list.
5687 * Usually we map chunks of 16 pages at a time, but if an overflow page begins
5688 * at the tail of the chunk we extend the chunk to include the entire overflow
5689 * page. Unfortunately, pages can be turned into overflow pages after their
5690 * chunk was already mapped. In that case we must remap the chunk if the
5691 * overflow page is referenced. If the chunk's refcnt is 0 we can just remap
5692 * it, otherwise we temporarily map a new chunk just for the overflow page.
5694 * @note this chunk handling means we cannot guarantee that a data item
5695 * returned from the DB will stay alive for the duration of the transaction:
5696 * We unref pages as soon as a cursor moves away from the page
5697 * A subsequent op may cause a purge, which may unmap any unref'd chunks
5698 * The caller must copy the data if it must be used later in the same txn.
5700 * Also - our reference counting revolves around cursors, but overflow pages
5701 * aren't pointed to by a cursor's page stack. We have to remember them
5702 * explicitly, in the added mc_ovpg field. A single cursor can only hold a
5703 * reference to one overflow page at a time.
5705 * @param[in] txn the transaction for this access.
5706 * @param[in] pgno the page number for the page to retrieve.
5707 * @param[out] ret address of a pointer where the page's address will be stored.
5708 * @return 0 on success, non-zero on failure.
5711 mdb_rpage_get(MDB_txn *txn, pgno_t pg0, MDB_page **ret)
5713 MDB_env *env = txn->mt_env;
5715 MDB_ID3L tl = txn->mt_rpages;
5716 MDB_ID3L el = env->me_rpages;
5720 int rc, retries = 1;
5724 #define SET_OFF(off,val) off.QuadPart = val
5725 #define MAP(rc,env,addr,len,off) \
5727 rc = NtMapViewOfSection(env->me_fmh, GetCurrentProcess(), &addr, 0, \
5728 len, &off, &len, ViewUnmap, (env->me_flags & MDB_RDONLY) ? 0 : MEM_RESERVE, PAGE_READONLY); \
5729 if (rc) rc = mdb_nt2win32(rc)
5733 #define SET_OFF(off,val) off = val
5734 #define MAP(rc,env,addr,len,off) \
5735 addr = mmap(NULL, len, PROT_READ, MAP_SHARED, env->me_fd, off); \
5736 rc = (addr == MAP_FAILED) ? errno : 0
5739 /* remember the offset of the actual page number, so we can
5740 * return the correct pointer at the end.
5742 rem = pg0 & (MDB_RPAGE_CHUNK-1);
5746 x = mdb_mid3l_search(tl, pgno);
5747 if (x <= tl[0].mid && tl[x].mid == pgno) {
5748 if (x != tl[0].mid && tl[x+1].mid == pg0)
5750 /* check for overflow size */
5751 p = (MDB_page *)((char *)tl[x].mptr + rem * env->me_psize);
5752 if (IS_OVERFLOW(p) && p->mp_pages + rem > tl[x].mcnt) {
5753 id3.mcnt = p->mp_pages + rem;
5754 len = id3.mcnt * env->me_psize;
5755 SET_OFF(off, pgno * env->me_psize);
5756 MAP(rc, env, id3.mptr, len, off);
5759 /* check for local-only page */
5761 mdb_tassert(txn, tl[x].mid != pg0);
5762 /* hope there's room to insert this locally.
5763 * setting mid here tells later code to just insert
5764 * this id3 instead of searching for a match.
5769 /* ignore the mapping we got from env, use new one */
5770 tl[x].mptr = id3.mptr;
5771 tl[x].mcnt = id3.mcnt;
5772 /* if no active ref, see if we can replace in env */
5775 pthread_mutex_lock(&env->me_rpmutex);
5776 i = mdb_mid3l_search(el, tl[x].mid);
5777 if (el[i].mref == 1) {
5778 /* just us, replace it */
5779 munmap(el[i].mptr, el[i].mcnt * env->me_psize);
5780 el[i].mptr = tl[x].mptr;
5781 el[i].mcnt = tl[x].mcnt;
5783 /* there are others, remove ourself */
5786 pthread_mutex_unlock(&env->me_rpmutex);
5790 id3.mptr = tl[x].mptr;
5791 id3.mcnt = tl[x].mcnt;
5797 if (tl[0].mid >= MDB_TRPAGE_MAX - txn->mt_rpcheck) {
5799 /* purge unref'd pages from our list and unref in env */
5800 pthread_mutex_lock(&env->me_rpmutex);
5803 for (i=1; i<=tl[0].mid; i++) {
5806 /* tmp overflow pages don't go to env */
5807 if (tl[i].mid & (MDB_RPAGE_CHUNK-1)) {
5808 munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
5811 x = mdb_mid3l_search(el, tl[i].mid);
5815 pthread_mutex_unlock(&env->me_rpmutex);
5817 /* we didn't find any unref'd chunks.
5818 * if we're out of room, fail.
5820 if (tl[0].mid >= MDB_TRPAGE_MAX)
5821 return MDB_TXN_FULL;
5822 /* otherwise, raise threshold for next time around
5825 txn->mt_rpcheck /= 2;
5827 /* we found some unused; consolidate the list */
5828 for (i=y+1; i<= tl[0].mid; i++)
5832 /* decrease the check threshold toward its original value */
5833 if (!txn->mt_rpcheck)
5834 txn->mt_rpcheck = 1;
5835 while (txn->mt_rpcheck < tl[0].mid && txn->mt_rpcheck < MDB_TRPAGE_SIZE/2)
5836 txn->mt_rpcheck *= 2;
5839 if (tl[0].mid < MDB_TRPAGE_SIZE) {
5843 /* don't map past last written page in read-only envs */
5844 if ((env->me_flags & MDB_RDONLY) && pgno + MDB_RPAGE_CHUNK-1 > txn->mt_last_pgno)
5845 id3.mcnt = txn->mt_last_pgno + 1 - pgno;
5847 id3.mcnt = MDB_RPAGE_CHUNK;
5848 len = id3.mcnt * env->me_psize;
5851 /* search for page in env */
5852 pthread_mutex_lock(&env->me_rpmutex);
5853 x = mdb_mid3l_search(el, pgno);
5854 if (x <= el[0].mid && el[x].mid == pgno) {
5855 id3.mptr = el[x].mptr;
5856 id3.mcnt = el[x].mcnt;
5857 /* check for overflow size */
5858 p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
5859 if (IS_OVERFLOW(p) && p->mp_pages + rem > id3.mcnt) {
5860 id3.mcnt = p->mp_pages + rem;
5861 len = id3.mcnt * env->me_psize;
5862 SET_OFF(off, pgno * env->me_psize);
5863 MAP(rc, env, id3.mptr, len, off);
5867 munmap(el[x].mptr, env->me_psize * el[x].mcnt);
5868 el[x].mptr = id3.mptr;
5869 el[x].mcnt = id3.mcnt;
5872 pthread_mutex_unlock(&env->me_rpmutex);
5877 pthread_mutex_unlock(&env->me_rpmutex);
5880 if (el[0].mid >= MDB_ERPAGE_MAX - env->me_rpcheck) {
5881 /* purge unref'd pages */
5883 for (i=1; i<=el[0].mid; i++) {
5886 munmap(el[i].mptr, env->me_psize * el[i].mcnt);
5891 /* see if we can unref some local pages */
5896 if (el[0].mid >= MDB_ERPAGE_MAX) {
5897 pthread_mutex_unlock(&env->me_rpmutex);
5898 return MDB_MAP_FULL;
5900 env->me_rpcheck /= 2;
5902 for (i=y+1; i<= el[0].mid; i++)
5906 if (!env->me_rpcheck)
5907 env->me_rpcheck = 1;
5908 while (env->me_rpcheck < el[0].mid && env->me_rpcheck < MDB_ERPAGE_SIZE/2)
5909 env->me_rpcheck *= 2;
5912 SET_OFF(off, pgno * env->me_psize);
5913 MAP(rc, env, id3.mptr, len, off);
5916 pthread_mutex_unlock(&env->me_rpmutex);
5919 /* check for overflow size */
5920 p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
5921 if (IS_OVERFLOW(p) && p->mp_pages + rem > id3.mcnt) {
5922 id3.mcnt = p->mp_pages + rem;
5923 munmap(id3.mptr, len);
5924 len = id3.mcnt * env->me_psize;
5925 MAP(rc, env, id3.mptr, len, off);
5929 mdb_mid3l_insert(el, &id3);
5930 pthread_mutex_unlock(&env->me_rpmutex);
5932 mdb_mid3l_insert(tl, &id3);
5934 return MDB_TXN_FULL;
5937 p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
5938 #if MDB_DEBUG /* we don't need this check any more */
5939 if (IS_OVERFLOW(p)) {
5940 mdb_tassert(txn, p->mp_pages + rem <= id3.mcnt);
5948 /** Find the address of the page corresponding to a given page number.
5949 * @param[in] mc the cursor accessing the page.
5950 * @param[in] pgno the page number for the page to retrieve.
5951 * @param[out] ret address of a pointer where the page's address will be stored.
5952 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
5953 * @return 0 on success, non-zero on failure.
5956 mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **ret, int *lvl)
5958 MDB_txn *txn = mc->mc_txn;
5962 if (! (mc->mc_flags & (C_ORIG_RDONLY|C_WRITEMAP))) {
5966 MDB_ID2L dl = tx2->mt_u.dirty_list;
5968 /* Spilled pages were dirtied in this txn and flushed
5969 * because the dirty list got full. Bring this page
5970 * back in from the map (but don't unspill it here,
5971 * leave that unless page_touch happens again).
5973 if (tx2->mt_spill_pgs) {
5974 MDB_ID pn = pgno << 1;
5975 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
5976 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
5981 unsigned x = mdb_mid2l_search(dl, pgno);
5982 if (x <= dl[0].mid && dl[x].mid == pgno) {
5988 } while ((tx2 = tx2->mt_parent) != NULL);
5991 if (pgno >= txn->mt_next_pgno) {
5992 DPRINTF(("page %"Yu" not found", pgno));
5993 txn->mt_flags |= MDB_TXN_ERROR;
5994 return MDB_PAGE_NOTFOUND;
6002 int rc = mdb_rpage_get(txn, pgno, &p);
6006 MDB_env *env = txn->mt_env;
6007 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
6018 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
6019 * The cursor is at the root page, set up the rest of it.
6022 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
6024 MDB_page *mp = mc->mc_pg[mc->mc_top];
6028 while (IS_BRANCH(mp)) {
6032 DPRINTF(("branch page %"Yu" has %u keys", mp->mp_pgno, NUMKEYS(mp)));
6033 /* Don't assert on branch pages in the FreeDB. We can get here
6034 * while in the process of rebalancing a FreeDB branch page; we must
6035 * let that proceed. ITS#8336
6037 mdb_cassert(mc, !mc->mc_dbi || NUMKEYS(mp) > 1);
6038 DPRINTF(("found index 0 to page %"Yu, NODEPGNO(NODEPTR(mp, 0))));
6040 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
6042 if (flags & MDB_PS_LAST)
6043 i = NUMKEYS(mp) - 1;
6046 node = mdb_node_search(mc, key, &exact);
6048 i = NUMKEYS(mp) - 1;
6050 i = mc->mc_ki[mc->mc_top];
6052 mdb_cassert(mc, i > 0);
6056 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
6059 mdb_cassert(mc, i < NUMKEYS(mp));
6060 node = NODEPTR(mp, i);
6062 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
6065 mc->mc_ki[mc->mc_top] = i;
6066 if ((rc = mdb_cursor_push(mc, mp)))
6069 if (flags & MDB_PS_MODIFY) {
6070 if ((rc = mdb_page_touch(mc)) != 0)
6072 mp = mc->mc_pg[mc->mc_top];
6077 DPRINTF(("internal error, index points to a %02X page!?",
6079 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6080 return MDB_CORRUPTED;
6083 DPRINTF(("found leaf page %"Yu" for key [%s]", mp->mp_pgno,
6084 key ? DKEY(key) : "null"));
6085 mc->mc_flags |= C_INITIALIZED;
6086 mc->mc_flags &= ~C_EOF;
6091 /** Search for the lowest key under the current branch page.
6092 * This just bypasses a NUMKEYS check in the current page
6093 * before calling mdb_page_search_root(), because the callers
6094 * are all in situations where the current page is known to
6098 mdb_page_search_lowest(MDB_cursor *mc)
6100 MDB_page *mp = mc->mc_pg[mc->mc_top];
6101 MDB_node *node = NODEPTR(mp, 0);
6104 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
6107 mc->mc_ki[mc->mc_top] = 0;
6108 if ((rc = mdb_cursor_push(mc, mp)))
6110 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
6113 /** Search for the page a given key should be in.
6114 * Push it and its parent pages on the cursor stack.
6115 * @param[in,out] mc the cursor for this operation.
6116 * @param[in] key the key to search for, or NULL for first/last page.
6117 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
6118 * are touched (updated with new page numbers).
6119 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
6120 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
6121 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
6122 * @return 0 on success, non-zero on failure.
6125 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
6130 /* Make sure the txn is still viable, then find the root from
6131 * the txn's db table and set it as the root of the cursor's stack.
6133 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED) {
6134 DPUTS("transaction may not be used now");
6137 /* Make sure we're using an up-to-date root */
6138 if (*mc->mc_dbflag & DB_STALE) {
6140 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
6142 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
6143 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
6150 MDB_node *leaf = mdb_node_search(&mc2,
6151 &mc->mc_dbx->md_name, &exact);
6153 return MDB_NOTFOUND;
6154 if ((leaf->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
6155 return MDB_INCOMPATIBLE; /* not a named DB */
6156 rc = mdb_node_read(&mc2, leaf, &data);
6159 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
6161 /* The txn may not know this DBI, or another process may
6162 * have dropped and recreated the DB with other flags.
6164 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
6165 return MDB_INCOMPATIBLE;
6166 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
6168 *mc->mc_dbflag &= ~DB_STALE;
6170 root = mc->mc_db->md_root;
6172 if (root == P_INVALID) { /* Tree is empty. */
6173 DPUTS("tree is empty");
6174 return MDB_NOTFOUND;
6178 mdb_cassert(mc, root > 1);
6179 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root) {
6182 MDB_PAGE_UNREF(mc->mc_txn, mc->mc_pg[0]);
6184 if ((rc = mdb_page_get(mc, root, &mc->mc_pg[0], NULL)) != 0)
6191 for (i=1; i<mc->mc_snum; i++)
6192 MDB_PAGE_UNREF(mc->mc_txn, mc->mc_pg[i]);
6198 DPRINTF(("db %d root page %"Yu" has flags 0x%X",
6199 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
6201 if (flags & MDB_PS_MODIFY) {
6202 if ((rc = mdb_page_touch(mc)))
6206 if (flags & MDB_PS_ROOTONLY)
6209 return mdb_page_search_root(mc, key, flags);
6213 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
6215 MDB_txn *txn = mc->mc_txn;
6216 pgno_t pg = mp->mp_pgno;
6217 unsigned x = 0, ovpages = mp->mp_pages;
6218 MDB_env *env = txn->mt_env;
6219 MDB_IDL sl = txn->mt_spill_pgs;
6220 MDB_ID pn = pg << 1;
6223 DPRINTF(("free ov page %"Yu" (%d)", pg, ovpages));
6224 /* If the page is dirty or on the spill list we just acquired it,
6225 * so we should give it back to our current free list, if any.
6226 * Otherwise put it onto the list of pages we freed in this txn.
6228 * Won't create me_pghead: me_pglast must be inited along with it.
6229 * Unsupported in nested txns: They would need to hide the page
6230 * range in ancestor txns' dirty and spilled lists.
6232 if (env->me_pghead &&
6234 ((mp->mp_flags & P_DIRTY) ||
6235 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
6239 MDB_ID2 *dl, ix, iy;
6240 rc = mdb_midl_need(&env->me_pghead, ovpages);
6243 if (!(mp->mp_flags & P_DIRTY)) {
6244 /* This page is no longer spilled */
6251 /* Remove from dirty list */
6252 dl = txn->mt_u.dirty_list;
6254 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
6260 mdb_cassert(mc, x > 1);
6262 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
6263 txn->mt_flags |= MDB_TXN_ERROR;
6267 txn->mt_dirty_room++;
6268 if (!(env->me_flags & MDB_WRITEMAP))
6269 mdb_dpage_free(env, mp);
6271 /* Insert in me_pghead */
6272 mop = env->me_pghead;
6273 j = mop[0] + ovpages;
6274 for (i = mop[0]; i && mop[i] < pg; i--)
6280 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
6284 mc->mc_db->md_overflow_pages -= ovpages;
6288 /** Return the data associated with a given node.
6289 * @param[in] mc The cursor for this operation.
6290 * @param[in] leaf The node being read.
6291 * @param[out] data Updated to point to the node's data.
6292 * @return 0 on success, non-zero on failure.
6295 mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data)
6297 MDB_page *omp; /* overflow page */
6302 MDB_PAGE_UNREF(mc->mc_txn, MC_OVPG(mc));
6303 MC_SET_OVPG(mc, NULL);
6305 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6306 data->mv_size = NODEDSZ(leaf);
6307 data->mv_data = NODEDATA(leaf);
6311 /* Read overflow data.
6313 data->mv_size = NODEDSZ(leaf);
6314 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
6315 if ((rc = mdb_page_get(mc, pgno, &omp, NULL)) != 0) {
6316 DPRINTF(("read overflow page %"Yu" failed", pgno));
6319 data->mv_data = METADATA(omp);
6320 MC_SET_OVPG(mc, omp);
6326 mdb_get(MDB_txn *txn, MDB_dbi dbi,
6327 MDB_val *key, MDB_val *data)
6334 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
6336 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
6339 if (txn->mt_flags & MDB_TXN_BLOCKED)
6342 mdb_cursor_init(&mc, txn, dbi, &mx);
6343 rc = mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
6344 /* unref all the pages when MDB_VL32 - caller must copy the data
6345 * before doing anything else
6347 MDB_CURSOR_UNREF(&mc, 1);
6351 /** Find a sibling for a page.
6352 * Replaces the page at the top of the cursor's stack with the
6353 * specified sibling, if one exists.
6354 * @param[in] mc The cursor for this operation.
6355 * @param[in] move_right Non-zero if the right sibling is requested,
6356 * otherwise the left sibling.
6357 * @return 0 on success, non-zero on failure.
6360 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
6369 if (mc->mc_snum < 2) {
6370 return MDB_NOTFOUND; /* root has no siblings */
6374 op = mc->mc_pg[mc->mc_top];
6377 DPRINTF(("parent page is page %"Yu", index %u",
6378 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
6380 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6381 : (mc->mc_ki[mc->mc_top] == 0)) {
6382 DPRINTF(("no more keys left, moving to %s sibling",
6383 move_right ? "right" : "left"));
6384 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
6385 /* undo cursor_pop before returning */
6392 mc->mc_ki[mc->mc_top]++;
6394 mc->mc_ki[mc->mc_top]--;
6395 DPRINTF(("just moving to %s index key %u",
6396 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
6398 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
6400 MDB_PAGE_UNREF(mc->mc_txn, op);
6402 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6403 if ((rc = mdb_page_get(mc, NODEPGNO(indx), &mp, NULL)) != 0) {
6404 /* mc will be inconsistent if caller does mc_snum++ as above */
6405 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
6409 mdb_cursor_push(mc, mp);
6411 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
6416 /** Move the cursor to the next data item. */
6418 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
6424 if ((mc->mc_flags & C_EOF) ||
6425 ((mc->mc_flags & C_DEL) && op == MDB_NEXT_DUP)) {
6426 return MDB_NOTFOUND;
6428 if (!(mc->mc_flags & C_INITIALIZED))
6429 return mdb_cursor_first(mc, key, data);
6431 mp = mc->mc_pg[mc->mc_top];
6433 if (mc->mc_db->md_flags & MDB_DUPSORT) {
6434 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6435 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6436 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
6437 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
6438 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
6439 if (rc == MDB_SUCCESS)
6440 MDB_GET_KEY(leaf, key);
6445 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
6448 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6449 if (op == MDB_NEXT_DUP)
6450 return MDB_NOTFOUND;
6454 DPRINTF(("cursor_next: top page is %"Yu" in cursor %p",
6455 mdb_dbg_pgno(mp), (void *) mc));
6456 if (mc->mc_flags & C_DEL) {
6457 mc->mc_flags ^= C_DEL;
6461 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
6462 DPUTS("=====> move to next sibling page");
6463 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
6464 mc->mc_flags |= C_EOF;
6467 mp = mc->mc_pg[mc->mc_top];
6468 DPRINTF(("next page is %"Yu", key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
6470 mc->mc_ki[mc->mc_top]++;
6473 DPRINTF(("==> cursor points to page %"Yu" with %u keys, key index %u",
6474 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
6477 key->mv_size = mc->mc_db->md_pad;
6478 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6482 mdb_cassert(mc, IS_LEAF(mp));
6483 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6485 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6486 mdb_xcursor_init1(mc, leaf);
6489 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6492 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6493 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6494 if (rc != MDB_SUCCESS)
6499 MDB_GET_KEY(leaf, key);
6503 /** Move the cursor to the previous data item. */
6505 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
6511 if (!(mc->mc_flags & C_INITIALIZED)) {
6512 rc = mdb_cursor_last(mc, key, data);
6515 mc->mc_ki[mc->mc_top]++;
6518 mp = mc->mc_pg[mc->mc_top];
6520 if (mc->mc_db->md_flags & MDB_DUPSORT) {
6521 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6522 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6523 if (op == MDB_PREV || op == MDB_PREV_DUP) {
6524 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
6525 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
6526 if (rc == MDB_SUCCESS) {
6527 MDB_GET_KEY(leaf, key);
6528 mc->mc_flags &= ~C_EOF;
6534 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
6537 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6538 if (op == MDB_PREV_DUP)
6539 return MDB_NOTFOUND;
6543 DPRINTF(("cursor_prev: top page is %"Yu" in cursor %p",
6544 mdb_dbg_pgno(mp), (void *) mc));
6546 mc->mc_flags &= ~(C_EOF|C_DEL);
6548 if (mc->mc_ki[mc->mc_top] == 0) {
6549 DPUTS("=====> move to prev sibling page");
6550 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
6553 mp = mc->mc_pg[mc->mc_top];
6554 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
6555 DPRINTF(("prev page is %"Yu", key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
6557 mc->mc_ki[mc->mc_top]--;
6559 mc->mc_flags &= ~C_EOF;
6561 DPRINTF(("==> cursor points to page %"Yu" with %u keys, key index %u",
6562 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
6565 key->mv_size = mc->mc_db->md_pad;
6566 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6570 mdb_cassert(mc, IS_LEAF(mp));
6571 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6573 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6574 mdb_xcursor_init1(mc, leaf);
6577 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6580 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6581 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
6582 if (rc != MDB_SUCCESS)
6587 MDB_GET_KEY(leaf, key);
6591 /** Set the cursor on a specific data item. */
6593 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6594 MDB_cursor_op op, int *exactp)
6598 MDB_node *leaf = NULL;
6601 if (key->mv_size == 0)
6602 return MDB_BAD_VALSIZE;
6605 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6607 /* See if we're already on the right page */
6608 if (mc->mc_flags & C_INITIALIZED) {
6611 mp = mc->mc_pg[mc->mc_top];
6613 mc->mc_ki[mc->mc_top] = 0;
6614 return MDB_NOTFOUND;
6616 if (mp->mp_flags & P_LEAF2) {
6617 nodekey.mv_size = mc->mc_db->md_pad;
6618 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
6620 leaf = NODEPTR(mp, 0);
6621 MDB_GET_KEY2(leaf, nodekey);
6623 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6625 /* Probably happens rarely, but first node on the page
6626 * was the one we wanted.
6628 mc->mc_ki[mc->mc_top] = 0;
6635 unsigned int nkeys = NUMKEYS(mp);
6637 if (mp->mp_flags & P_LEAF2) {
6638 nodekey.mv_data = LEAF2KEY(mp,
6639 nkeys-1, nodekey.mv_size);
6641 leaf = NODEPTR(mp, nkeys-1);
6642 MDB_GET_KEY2(leaf, nodekey);
6644 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6646 /* last node was the one we wanted */
6647 mc->mc_ki[mc->mc_top] = nkeys-1;
6653 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
6654 /* This is definitely the right page, skip search_page */
6655 if (mp->mp_flags & P_LEAF2) {
6656 nodekey.mv_data = LEAF2KEY(mp,
6657 mc->mc_ki[mc->mc_top], nodekey.mv_size);
6659 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6660 MDB_GET_KEY2(leaf, nodekey);
6662 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6664 /* current node was the one we wanted */
6674 /* If any parents have right-sibs, search.
6675 * Otherwise, there's nothing further.
6677 for (i=0; i<mc->mc_top; i++)
6679 NUMKEYS(mc->mc_pg[i])-1)
6681 if (i == mc->mc_top) {
6682 /* There are no other pages */
6683 mc->mc_ki[mc->mc_top] = nkeys;
6684 return MDB_NOTFOUND;
6688 /* There are no other pages */
6689 mc->mc_ki[mc->mc_top] = 0;
6690 if (op == MDB_SET_RANGE && !exactp) {
6694 return MDB_NOTFOUND;
6700 rc = mdb_page_search(mc, key, 0);
6701 if (rc != MDB_SUCCESS)
6704 mp = mc->mc_pg[mc->mc_top];
6705 mdb_cassert(mc, IS_LEAF(mp));
6708 leaf = mdb_node_search(mc, key, exactp);
6709 if (exactp != NULL && !*exactp) {
6710 /* MDB_SET specified and not an exact match. */
6711 return MDB_NOTFOUND;
6715 DPUTS("===> inexact leaf not found, goto sibling");
6716 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
6717 mc->mc_flags |= C_EOF;
6718 return rc; /* no entries matched */
6720 mp = mc->mc_pg[mc->mc_top];
6721 mdb_cassert(mc, IS_LEAF(mp));
6722 leaf = NODEPTR(mp, 0);
6726 mc->mc_flags |= C_INITIALIZED;
6727 mc->mc_flags &= ~C_EOF;
6730 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
6731 key->mv_size = mc->mc_db->md_pad;
6732 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6738 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
6739 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6740 mdb_xcursor_init1(mc, leaf);
6743 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6744 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
6745 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6748 if (op == MDB_GET_BOTH) {
6754 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
6755 if (rc != MDB_SUCCESS)
6758 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
6761 if ((rc = mdb_node_read(mc, leaf, &olddata)) != MDB_SUCCESS)
6763 dcmp = mc->mc_dbx->md_dcmp;
6764 if (NEED_CMP_CLONG(dcmp, olddata.mv_size))
6765 dcmp = mdb_cmp_clong;
6766 rc = dcmp(data, &olddata);
6768 if (op == MDB_GET_BOTH || rc > 0)
6769 return MDB_NOTFOUND;
6776 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6777 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6782 /* The key already matches in all other cases */
6783 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
6784 MDB_GET_KEY(leaf, key);
6785 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
6790 /** Move the cursor to the first item in the database. */
6792 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6797 if (mc->mc_xcursor) {
6798 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
6799 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6802 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6803 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
6804 if (rc != MDB_SUCCESS)
6807 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6809 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
6810 mc->mc_flags |= C_INITIALIZED;
6811 mc->mc_flags &= ~C_EOF;
6813 mc->mc_ki[mc->mc_top] = 0;
6815 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6816 key->mv_size = mc->mc_db->md_pad;
6817 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
6822 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6823 mdb_xcursor_init1(mc, leaf);
6824 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6828 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6832 MDB_GET_KEY(leaf, key);
6836 /** Move the cursor to the last item in the database. */
6838 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6843 if (mc->mc_xcursor) {
6844 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
6845 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6848 if (!(mc->mc_flags & C_EOF)) {
6850 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6851 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
6852 if (rc != MDB_SUCCESS)
6855 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6858 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
6859 mc->mc_flags |= C_INITIALIZED|C_EOF;
6860 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6862 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6863 key->mv_size = mc->mc_db->md_pad;
6864 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
6869 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6870 mdb_xcursor_init1(mc, leaf);
6871 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
6875 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6880 MDB_GET_KEY(leaf, key);
6885 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6890 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
6895 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
6899 case MDB_GET_CURRENT:
6900 if (!(mc->mc_flags & C_INITIALIZED)) {
6903 MDB_page *mp = mc->mc_pg[mc->mc_top];
6904 int nkeys = NUMKEYS(mp);
6905 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
6906 mc->mc_ki[mc->mc_top] = nkeys;
6912 key->mv_size = mc->mc_db->md_pad;
6913 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6915 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6916 MDB_GET_KEY(leaf, key);
6918 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6919 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
6921 rc = mdb_node_read(mc, leaf, data);
6928 case MDB_GET_BOTH_RANGE:
6933 if (mc->mc_xcursor == NULL) {
6934 rc = MDB_INCOMPATIBLE;
6944 rc = mdb_cursor_set(mc, key, data, op,
6945 op == MDB_SET_RANGE ? NULL : &exact);
6948 case MDB_GET_MULTIPLE:
6949 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
6953 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6954 rc = MDB_INCOMPATIBLE;
6958 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
6959 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
6962 case MDB_NEXT_MULTIPLE:
6967 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6968 rc = MDB_INCOMPATIBLE;
6971 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
6972 if (rc == MDB_SUCCESS) {
6973 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6976 mx = &mc->mc_xcursor->mx_cursor;
6977 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
6979 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
6980 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
6986 case MDB_PREV_MULTIPLE:
6991 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6992 rc = MDB_INCOMPATIBLE;
6995 if (!(mc->mc_flags & C_INITIALIZED))
6996 rc = mdb_cursor_last(mc, key, data);
6999 if (rc == MDB_SUCCESS) {
7000 MDB_cursor *mx = &mc->mc_xcursor->mx_cursor;
7001 if (mx->mc_flags & C_INITIALIZED) {
7002 rc = mdb_cursor_sibling(mx, 0);
7003 if (rc == MDB_SUCCESS)
7012 case MDB_NEXT_NODUP:
7013 rc = mdb_cursor_next(mc, key, data, op);
7017 case MDB_PREV_NODUP:
7018 rc = mdb_cursor_prev(mc, key, data, op);
7021 rc = mdb_cursor_first(mc, key, data);
7024 mfunc = mdb_cursor_first;
7026 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
7030 if (mc->mc_xcursor == NULL) {
7031 rc = MDB_INCOMPATIBLE;
7035 MDB_node *leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7036 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7037 MDB_GET_KEY(leaf, key);
7038 rc = mdb_node_read(mc, leaf, data);
7042 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
7046 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
7049 rc = mdb_cursor_last(mc, key, data);
7052 mfunc = mdb_cursor_last;
7055 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
7060 if (mc->mc_flags & C_DEL)
7061 mc->mc_flags ^= C_DEL;
7066 /** Touch all the pages in the cursor stack. Set mc_top.
7067 * Makes sure all the pages are writable, before attempting a write operation.
7068 * @param[in] mc The cursor to operate on.
7071 mdb_cursor_touch(MDB_cursor *mc)
7073 int rc = MDB_SUCCESS;
7075 if (mc->mc_dbi >= CORE_DBS && !(*mc->mc_dbflag & DB_DIRTY)) {
7078 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
7080 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
7081 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
7084 *mc->mc_dbflag |= DB_DIRTY;
7089 rc = mdb_page_touch(mc);
7090 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
7091 mc->mc_top = mc->mc_snum-1;
7096 /** Do not spill pages to disk if txn is getting full, may fail instead */
7097 #define MDB_NOSPILL 0x8000
7100 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
7104 MDB_node *leaf = NULL;
7105 MDB_page *fp, *mp, *sub_root = NULL;
7107 MDB_val xdata, *rdata, dkey, olddata;
7109 int do_sub = 0, insert_key, insert_data;
7110 unsigned int mcount = 0, dcount = 0, nospill;
7113 unsigned int nflags;
7116 if (mc == NULL || key == NULL)
7119 env = mc->mc_txn->mt_env;
7121 /* Check this first so counter will always be zero on any
7124 if (flags & MDB_MULTIPLE) {
7125 dcount = data[1].mv_size;
7126 data[1].mv_size = 0;
7127 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
7128 return MDB_INCOMPATIBLE;
7131 nospill = flags & MDB_NOSPILL;
7132 flags &= ~MDB_NOSPILL;
7134 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
7135 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7137 if (key->mv_size-1 >= ENV_MAXKEY(env))
7138 return MDB_BAD_VALSIZE;
7140 #if SIZE_MAX > MAXDATASIZE
7141 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
7142 return MDB_BAD_VALSIZE;
7144 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
7145 return MDB_BAD_VALSIZE;
7148 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
7149 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
7153 if (flags == MDB_CURRENT) {
7154 if (!(mc->mc_flags & C_INITIALIZED))
7157 } else if (mc->mc_db->md_root == P_INVALID) {
7158 /* new database, cursor has nothing to point to */
7161 mc->mc_flags &= ~C_INITIALIZED;
7166 if (flags & MDB_APPEND) {
7168 rc = mdb_cursor_last(mc, &k2, &d2);
7170 rc = mc->mc_dbx->md_cmp(key, &k2);
7173 mc->mc_ki[mc->mc_top]++;
7175 /* new key is <= last key */
7180 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
7182 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
7183 DPRINTF(("duplicate key [%s]", DKEY(key)));
7185 return MDB_KEYEXIST;
7187 if (rc && rc != MDB_NOTFOUND)
7191 if (mc->mc_flags & C_DEL)
7192 mc->mc_flags ^= C_DEL;
7194 /* Cursor is positioned, check for room in the dirty list */
7196 if (flags & MDB_MULTIPLE) {
7198 xdata.mv_size = data->mv_size * dcount;
7202 if ((rc2 = mdb_page_spill(mc, key, rdata)))
7206 if (rc == MDB_NO_ROOT) {
7208 /* new database, write a root leaf page */
7209 DPUTS("allocating new root leaf page");
7210 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
7213 mdb_cursor_push(mc, np);
7214 mc->mc_db->md_root = np->mp_pgno;
7215 mc->mc_db->md_depth++;
7216 *mc->mc_dbflag |= DB_DIRTY;
7217 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
7219 np->mp_flags |= P_LEAF2;
7220 mc->mc_flags |= C_INITIALIZED;
7222 /* make sure all cursor pages are writable */
7223 rc2 = mdb_cursor_touch(mc);
7228 insert_key = insert_data = rc;
7230 /* The key does not exist */
7231 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
7232 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
7233 LEAFSIZE(key, data) > env->me_nodemax)
7235 /* Too big for a node, insert in sub-DB. Set up an empty
7236 * "old sub-page" for prep_subDB to expand to a full page.
7238 fp_flags = P_LEAF|P_DIRTY;
7240 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
7241 fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
7242 olddata.mv_size = PAGEHDRSZ;
7246 /* there's only a key anyway, so this is a no-op */
7247 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
7249 unsigned int ksize = mc->mc_db->md_pad;
7250 if (key->mv_size != ksize)
7251 return MDB_BAD_VALSIZE;
7252 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
7253 memcpy(ptr, key->mv_data, ksize);
7255 /* if overwriting slot 0 of leaf, need to
7256 * update branch key if there is a parent page
7258 if (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
7259 unsigned short dtop = 1;
7261 /* slot 0 is always an empty key, find real slot */
7262 while (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
7266 if (mc->mc_ki[mc->mc_top])
7267 rc2 = mdb_update_key(mc, key);
7278 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7279 olddata.mv_size = NODEDSZ(leaf);
7280 olddata.mv_data = NODEDATA(leaf);
7283 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
7284 /* Prepare (sub-)page/sub-DB to accept the new item,
7285 * if needed. fp: old sub-page or a header faking
7286 * it. mp: new (sub-)page. offset: growth in page
7287 * size. xdata: node data with new page or DB.
7289 unsigned i, offset = 0;
7290 mp = fp = xdata.mv_data = env->me_pbuf;
7291 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
7293 /* Was a single item before, must convert now */
7294 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7296 /* Just overwrite the current item */
7297 if (flags == MDB_CURRENT)
7299 dcmp = mc->mc_dbx->md_dcmp;
7300 if (NEED_CMP_CLONG(dcmp, olddata.mv_size))
7301 dcmp = mdb_cmp_clong;
7302 /* does data match? */
7303 if (!dcmp(data, &olddata)) {
7304 if (flags & (MDB_NODUPDATA|MDB_APPENDDUP))
7305 return MDB_KEYEXIST;
7310 /* Back up original data item */
7311 dkey.mv_size = olddata.mv_size;
7312 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
7314 /* Make sub-page header for the dup items, with dummy body */
7315 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
7316 fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
7317 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
7318 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7319 fp->mp_flags |= P_LEAF2;
7320 fp->mp_pad = data->mv_size;
7321 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
7323 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
7324 (dkey.mv_size & 1) + (data->mv_size & 1);
7326 fp->mp_upper = xdata.mv_size - PAGEBASE;
7327 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
7328 } else if (leaf->mn_flags & F_SUBDATA) {
7329 /* Data is on sub-DB, just store it */
7330 flags |= F_DUPDATA|F_SUBDATA;
7333 /* Data is on sub-page */
7334 fp = olddata.mv_data;
7337 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7338 offset = EVEN(NODESIZE + sizeof(indx_t) +
7342 offset = fp->mp_pad;
7343 if (SIZELEFT(fp) < offset) {
7344 offset *= 4; /* space for 4 more */
7347 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
7349 fp->mp_flags |= P_DIRTY;
7350 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
7351 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
7355 xdata.mv_size = olddata.mv_size + offset;
7358 fp_flags = fp->mp_flags;
7359 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
7360 /* Too big for a sub-page, convert to sub-DB */
7361 fp_flags &= ~P_SUBP;
7363 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7364 fp_flags |= P_LEAF2;
7365 dummy.md_pad = fp->mp_pad;
7366 dummy.md_flags = MDB_DUPFIXED;
7367 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
7368 dummy.md_flags |= MDB_INTEGERKEY;
7374 dummy.md_branch_pages = 0;
7375 dummy.md_leaf_pages = 1;
7376 dummy.md_overflow_pages = 0;
7377 dummy.md_entries = NUMKEYS(fp);
7378 xdata.mv_size = sizeof(MDB_db);
7379 xdata.mv_data = &dummy;
7380 if ((rc = mdb_page_alloc(mc, 1, &mp)))
7382 offset = env->me_psize - olddata.mv_size;
7383 flags |= F_DUPDATA|F_SUBDATA;
7384 dummy.md_root = mp->mp_pgno;
7388 mp->mp_flags = fp_flags | P_DIRTY;
7389 mp->mp_pad = fp->mp_pad;
7390 mp->mp_lower = fp->mp_lower;
7391 mp->mp_upper = fp->mp_upper + offset;
7392 if (fp_flags & P_LEAF2) {
7393 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
7395 memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
7396 olddata.mv_size - fp->mp_upper - PAGEBASE);
7397 for (i=0; i<NUMKEYS(fp); i++)
7398 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
7406 mdb_node_del(mc, 0);
7410 /* LMDB passes F_SUBDATA in 'flags' to write a DB record */
7411 if ((leaf->mn_flags ^ flags) & F_SUBDATA)
7412 return MDB_INCOMPATIBLE;
7413 /* overflow page overwrites need special handling */
7414 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7417 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
7419 memcpy(&pg, olddata.mv_data, sizeof(pg));
7420 if ((rc2 = mdb_page_get(mc, pg, &omp, &level)) != 0)
7422 ovpages = omp->mp_pages;
7424 /* Is the ov page large enough? */
7425 if (ovpages >= dpages) {
7426 if (!(omp->mp_flags & P_DIRTY) &&
7427 (level || (env->me_flags & MDB_WRITEMAP)))
7429 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
7432 level = 0; /* dirty in this txn or clean */
7435 if (omp->mp_flags & P_DIRTY) {
7436 /* yes, overwrite it. Note in this case we don't
7437 * bother to try shrinking the page if the new data
7438 * is smaller than the overflow threshold.
7441 /* It is writable only in a parent txn */
7442 size_t sz = (size_t) env->me_psize * ovpages, off;
7443 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
7449 /* Note - this page is already counted in parent's dirty_room */
7450 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
7451 mdb_cassert(mc, rc2 == 0);
7452 /* Currently we make the page look as with put() in the
7453 * parent txn, in case the user peeks at MDB_RESERVEd
7454 * or unused parts. Some users treat ovpages specially.
7456 if (!(flags & MDB_RESERVE)) {
7457 /* Skip the part where LMDB will put *data.
7458 * Copy end of page, adjusting alignment so
7459 * compiler may copy words instead of bytes.
7461 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
7462 memcpy((size_t *)((char *)np + off),
7463 (size_t *)((char *)omp + off), sz - off);
7466 memcpy(np, omp, sz); /* Copy beginning of page */
7469 SETDSZ(leaf, data->mv_size);
7470 if (F_ISSET(flags, MDB_RESERVE))
7471 data->mv_data = METADATA(omp);
7473 memcpy(METADATA(omp), data->mv_data, data->mv_size);
7477 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
7479 } else if (data->mv_size == olddata.mv_size) {
7480 /* same size, just replace it. Note that we could
7481 * also reuse this node if the new data is smaller,
7482 * but instead we opt to shrink the node in that case.
7484 if (F_ISSET(flags, MDB_RESERVE))
7485 data->mv_data = olddata.mv_data;
7486 else if (!(mc->mc_flags & C_SUB))
7487 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
7489 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
7494 mdb_node_del(mc, 0);
7500 nflags = flags & NODE_ADD_FLAGS;
7501 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
7502 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
7503 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
7504 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
7506 nflags |= MDB_SPLIT_REPLACE;
7507 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
7509 /* There is room already in this leaf page. */
7510 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
7512 /* Adjust other cursors pointing to mp */
7513 MDB_cursor *m2, *m3;
7514 MDB_dbi dbi = mc->mc_dbi;
7515 unsigned i = mc->mc_top;
7516 MDB_page *mp = mc->mc_pg[i];
7518 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7519 if (mc->mc_flags & C_SUB)
7520 m3 = &m2->mc_xcursor->mx_cursor;
7523 if (m3 == mc || m3->mc_snum < mc->mc_snum || m3->mc_pg[i] != mp) continue;
7524 if (m3->mc_ki[i] >= mc->mc_ki[i] && insert_key) {
7527 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
7528 MDB_node *n2 = NODEPTR(mp, m3->mc_ki[i]);
7529 if ((n2->mn_flags & (F_SUBDATA|F_DUPDATA)) == F_DUPDATA)
7530 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
7536 if (rc == MDB_SUCCESS) {
7537 /* Now store the actual data in the child DB. Note that we're
7538 * storing the user data in the keys field, so there are strict
7539 * size limits on dupdata. The actual data fields of the child
7540 * DB are all zero size.
7543 int xflags, new_dupdata;
7548 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7549 if (flags & MDB_CURRENT) {
7550 xflags = MDB_CURRENT|MDB_NOSPILL;
7552 mdb_xcursor_init1(mc, leaf);
7553 xflags = (flags & MDB_NODUPDATA) ?
7554 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
7557 mc->mc_xcursor->mx_cursor.mc_pg[0] = sub_root;
7558 new_dupdata = (int)dkey.mv_size;
7559 /* converted, write the original data first */
7561 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
7564 /* we've done our job */
7567 if (!(leaf->mn_flags & F_SUBDATA) || sub_root) {
7568 /* Adjust other cursors pointing to mp */
7570 MDB_xcursor *mx = mc->mc_xcursor;
7571 unsigned i = mc->mc_top;
7572 MDB_page *mp = mc->mc_pg[i];
7573 int nkeys = NUMKEYS(mp);
7575 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
7576 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
7577 if (!(m2->mc_flags & C_INITIALIZED)) continue;
7578 if (m2->mc_pg[i] == mp) {
7579 if (m2->mc_ki[i] == mc->mc_ki[i]) {
7580 mdb_xcursor_init2(m2, mx, new_dupdata);
7581 } else if (!insert_key && m2->mc_ki[i] < nkeys) {
7582 MDB_node *n2 = NODEPTR(mp, m2->mc_ki[i]);
7583 if ((n2->mn_flags & (F_SUBDATA|F_DUPDATA)) == F_DUPDATA)
7584 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
7589 ecount = mc->mc_xcursor->mx_db.md_entries;
7590 if (flags & MDB_APPENDDUP)
7591 xflags |= MDB_APPEND;
7592 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
7593 if (flags & F_SUBDATA) {
7594 void *db = NODEDATA(leaf);
7595 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
7597 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
7599 /* Increment count unless we just replaced an existing item. */
7601 mc->mc_db->md_entries++;
7603 /* Invalidate txn if we created an empty sub-DB */
7606 /* If we succeeded and the key didn't exist before,
7607 * make sure the cursor is marked valid.
7609 mc->mc_flags |= C_INITIALIZED;
7611 if (flags & MDB_MULTIPLE) {
7614 /* let caller know how many succeeded, if any */
7615 data[1].mv_size = mcount;
7616 if (mcount < dcount) {
7617 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
7618 insert_key = insert_data = 0;
7625 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
7628 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7633 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
7639 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
7640 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7642 if (!(mc->mc_flags & C_INITIALIZED))
7645 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
7646 return MDB_NOTFOUND;
7648 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
7651 rc = mdb_cursor_touch(mc);
7655 mp = mc->mc_pg[mc->mc_top];
7658 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7660 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7661 if (flags & MDB_NODUPDATA) {
7662 /* mdb_cursor_del0() will subtract the final entry */
7663 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
7664 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
7666 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
7667 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
7669 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
7672 /* If sub-DB still has entries, we're done */
7673 if (mc->mc_xcursor->mx_db.md_entries) {
7674 if (leaf->mn_flags & F_SUBDATA) {
7675 /* update subDB info */
7676 void *db = NODEDATA(leaf);
7677 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
7680 /* shrink fake page */
7681 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
7682 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7683 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
7684 /* fix other sub-DB cursors pointed at fake pages on this page */
7685 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
7686 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
7687 if (!(m2->mc_flags & C_INITIALIZED)) continue;
7688 if (m2->mc_pg[mc->mc_top] == mp) {
7689 if (m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top]) {
7690 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
7692 MDB_node *n2 = NODEPTR(mp, m2->mc_ki[mc->mc_top]);
7693 if (!(n2->mn_flags & F_SUBDATA))
7694 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
7699 mc->mc_db->md_entries--;
7702 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
7704 /* otherwise fall thru and delete the sub-DB */
7707 if (leaf->mn_flags & F_SUBDATA) {
7708 /* add all the child DB's pages to the free list */
7709 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
7714 /* LMDB passes F_SUBDATA in 'flags' to delete a DB record */
7715 else if ((leaf->mn_flags ^ flags) & F_SUBDATA) {
7716 rc = MDB_INCOMPATIBLE;
7720 /* add overflow pages to free list */
7721 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7725 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
7726 if ((rc = mdb_page_get(mc, pg, &omp, NULL)) ||
7727 (rc = mdb_ovpage_free(mc, omp)))
7732 return mdb_cursor_del0(mc);
7735 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7739 /** Allocate and initialize new pages for a database.
7740 * @param[in] mc a cursor on the database being added to.
7741 * @param[in] flags flags defining what type of page is being allocated.
7742 * @param[in] num the number of pages to allocate. This is usually 1,
7743 * unless allocating overflow pages for a large record.
7744 * @param[out] mp Address of a page, or NULL on failure.
7745 * @return 0 on success, non-zero on failure.
7748 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
7753 if ((rc = mdb_page_alloc(mc, num, &np)))
7755 DPRINTF(("allocated new mpage %"Yu", page size %u",
7756 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
7757 np->mp_flags = flags | P_DIRTY;
7758 np->mp_lower = (PAGEHDRSZ-PAGEBASE);
7759 np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
7762 mc->mc_db->md_branch_pages++;
7763 else if (IS_LEAF(np))
7764 mc->mc_db->md_leaf_pages++;
7765 else if (IS_OVERFLOW(np)) {
7766 mc->mc_db->md_overflow_pages += num;
7774 /** Calculate the size of a leaf node.
7775 * The size depends on the environment's page size; if a data item
7776 * is too large it will be put onto an overflow page and the node
7777 * size will only include the key and not the data. Sizes are always
7778 * rounded up to an even number of bytes, to guarantee 2-byte alignment
7779 * of the #MDB_node headers.
7780 * @param[in] env The environment handle.
7781 * @param[in] key The key for the node.
7782 * @param[in] data The data for the node.
7783 * @return The number of bytes needed to store the node.
7786 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
7790 sz = LEAFSIZE(key, data);
7791 if (sz > env->me_nodemax) {
7792 /* put on overflow page */
7793 sz -= data->mv_size - sizeof(pgno_t);
7796 return EVEN(sz + sizeof(indx_t));
7799 /** Calculate the size of a branch node.
7800 * The size should depend on the environment's page size but since
7801 * we currently don't support spilling large keys onto overflow
7802 * pages, it's simply the size of the #MDB_node header plus the
7803 * size of the key. Sizes are always rounded up to an even number
7804 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
7805 * @param[in] env The environment handle.
7806 * @param[in] key The key for the node.
7807 * @return The number of bytes needed to store the node.
7810 mdb_branch_size(MDB_env *env, MDB_val *key)
7815 if (sz > env->me_nodemax) {
7816 /* put on overflow page */
7817 /* not implemented */
7818 /* sz -= key->size - sizeof(pgno_t); */
7821 return sz + sizeof(indx_t);
7824 /** Add a node to the page pointed to by the cursor.
7825 * @param[in] mc The cursor for this operation.
7826 * @param[in] indx The index on the page where the new node should be added.
7827 * @param[in] key The key for the new node.
7828 * @param[in] data The data for the new node, if any.
7829 * @param[in] pgno The page number, if adding a branch node.
7830 * @param[in] flags Flags for the node.
7831 * @return 0 on success, non-zero on failure. Possible errors are:
7833 * <li>ENOMEM - failed to allocate overflow pages for the node.
7834 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
7835 * should never happen since all callers already calculate the
7836 * page's free space before calling this function.
7840 mdb_node_add(MDB_cursor *mc, indx_t indx,
7841 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
7844 size_t node_size = NODESIZE;
7848 MDB_page *mp = mc->mc_pg[mc->mc_top];
7849 MDB_page *ofp = NULL; /* overflow page */
7853 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
7855 DPRINTF(("add to %s %spage %"Yu" index %i, data size %"Z"u key size %"Z"u [%s]",
7856 IS_LEAF(mp) ? "leaf" : "branch",
7857 IS_SUBP(mp) ? "sub-" : "",
7858 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
7859 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
7862 /* Move higher keys up one slot. */
7863 int ksize = mc->mc_db->md_pad, dif;
7864 char *ptr = LEAF2KEY(mp, indx, ksize);
7865 dif = NUMKEYS(mp) - indx;
7867 memmove(ptr+ksize, ptr, dif*ksize);
7868 /* insert new key */
7869 memcpy(ptr, key->mv_data, ksize);
7871 /* Just using these for counting */
7872 mp->mp_lower += sizeof(indx_t);
7873 mp->mp_upper -= ksize - sizeof(indx_t);
7877 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
7879 node_size += key->mv_size;
7881 mdb_cassert(mc, key && data);
7882 if (F_ISSET(flags, F_BIGDATA)) {
7883 /* Data already on overflow page. */
7884 node_size += sizeof(pgno_t);
7885 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
7886 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
7888 /* Put data on overflow page. */
7889 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
7890 data->mv_size, node_size+data->mv_size));
7891 node_size = EVEN(node_size + sizeof(pgno_t));
7892 if ((ssize_t)node_size > room)
7894 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
7896 DPRINTF(("allocated overflow page %"Yu, ofp->mp_pgno));
7900 node_size += data->mv_size;
7903 node_size = EVEN(node_size);
7904 if ((ssize_t)node_size > room)
7908 /* Move higher pointers up one slot. */
7909 for (i = NUMKEYS(mp); i > indx; i--)
7910 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
7912 /* Adjust free space offsets. */
7913 ofs = mp->mp_upper - node_size;
7914 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
7915 mp->mp_ptrs[indx] = ofs;
7917 mp->mp_lower += sizeof(indx_t);
7919 /* Write the node data. */
7920 node = NODEPTR(mp, indx);
7921 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
7922 node->mn_flags = flags;
7924 SETDSZ(node,data->mv_size);
7929 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7932 ndata = NODEDATA(node);
7934 if (F_ISSET(flags, F_BIGDATA))
7935 memcpy(ndata, data->mv_data, sizeof(pgno_t));
7936 else if (F_ISSET(flags, MDB_RESERVE))
7937 data->mv_data = ndata;
7939 memcpy(ndata, data->mv_data, data->mv_size);
7941 memcpy(ndata, &ofp->mp_pgno, sizeof(pgno_t));
7942 ndata = METADATA(ofp);
7943 if (F_ISSET(flags, MDB_RESERVE))
7944 data->mv_data = ndata;
7946 memcpy(ndata, data->mv_data, data->mv_size);
7953 DPRINTF(("not enough room in page %"Yu", got %u ptrs",
7954 mdb_dbg_pgno(mp), NUMKEYS(mp)));
7955 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
7956 DPRINTF(("node size = %"Z"u", node_size));
7957 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7958 return MDB_PAGE_FULL;
7961 /** Delete the specified node from a page.
7962 * @param[in] mc Cursor pointing to the node to delete.
7963 * @param[in] ksize The size of a node. Only used if the page is
7964 * part of a #MDB_DUPFIXED database.
7967 mdb_node_del(MDB_cursor *mc, int ksize)
7969 MDB_page *mp = mc->mc_pg[mc->mc_top];
7970 indx_t indx = mc->mc_ki[mc->mc_top];
7972 indx_t i, j, numkeys, ptr;
7976 DPRINTF(("delete node %u on %s page %"Yu, indx,
7977 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
7978 numkeys = NUMKEYS(mp);
7979 mdb_cassert(mc, indx < numkeys);
7982 int x = numkeys - 1 - indx;
7983 base = LEAF2KEY(mp, indx, ksize);
7985 memmove(base, base + ksize, x * ksize);
7986 mp->mp_lower -= sizeof(indx_t);
7987 mp->mp_upper += ksize - sizeof(indx_t);
7991 node = NODEPTR(mp, indx);
7992 sz = NODESIZE + node->mn_ksize;
7994 if (F_ISSET(node->mn_flags, F_BIGDATA))
7995 sz += sizeof(pgno_t);
7997 sz += NODEDSZ(node);
8001 ptr = mp->mp_ptrs[indx];
8002 for (i = j = 0; i < numkeys; i++) {
8004 mp->mp_ptrs[j] = mp->mp_ptrs[i];
8005 if (mp->mp_ptrs[i] < ptr)
8006 mp->mp_ptrs[j] += sz;
8011 base = (char *)mp + mp->mp_upper + PAGEBASE;
8012 memmove(base + sz, base, ptr - mp->mp_upper);
8014 mp->mp_lower -= sizeof(indx_t);
8018 /** Compact the main page after deleting a node on a subpage.
8019 * @param[in] mp The main page to operate on.
8020 * @param[in] indx The index of the subpage on the main page.
8023 mdb_node_shrink(MDB_page *mp, indx_t indx)
8028 indx_t delta, nsize, len, ptr;
8031 node = NODEPTR(mp, indx);
8032 sp = (MDB_page *)NODEDATA(node);
8033 delta = SIZELEFT(sp);
8034 nsize = NODEDSZ(node) - delta;
8036 /* Prepare to shift upward, set len = length(subpage part to shift) */
8040 return; /* do not make the node uneven-sized */
8042 xp = (MDB_page *)((char *)sp + delta); /* destination subpage */
8043 for (i = NUMKEYS(sp); --i >= 0; )
8044 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
8047 sp->mp_upper = sp->mp_lower;
8048 COPY_PGNO(sp->mp_pgno, mp->mp_pgno);
8049 SETDSZ(node, nsize);
8051 /* Shift <lower nodes...initial part of subpage> upward */
8052 base = (char *)mp + mp->mp_upper + PAGEBASE;
8053 memmove(base + delta, base, (char *)sp + len - base);
8055 ptr = mp->mp_ptrs[indx];
8056 for (i = NUMKEYS(mp); --i >= 0; ) {
8057 if (mp->mp_ptrs[i] <= ptr)
8058 mp->mp_ptrs[i] += delta;
8060 mp->mp_upper += delta;
8063 /** Initial setup of a sorted-dups cursor.
8064 * Sorted duplicates are implemented as a sub-database for the given key.
8065 * The duplicate data items are actually keys of the sub-database.
8066 * Operations on the duplicate data items are performed using a sub-cursor
8067 * initialized when the sub-database is first accessed. This function does
8068 * the preliminary setup of the sub-cursor, filling in the fields that
8069 * depend only on the parent DB.
8070 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
8073 mdb_xcursor_init0(MDB_cursor *mc)
8075 MDB_xcursor *mx = mc->mc_xcursor;
8077 mx->mx_cursor.mc_xcursor = NULL;
8078 mx->mx_cursor.mc_txn = mc->mc_txn;
8079 mx->mx_cursor.mc_db = &mx->mx_db;
8080 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
8081 mx->mx_cursor.mc_dbi = mc->mc_dbi;
8082 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
8083 mx->mx_cursor.mc_snum = 0;
8084 mx->mx_cursor.mc_top = 0;
8085 MC_SET_OVPG(&mx->mx_cursor, NULL);
8086 mx->mx_cursor.mc_flags = C_SUB | (mc->mc_flags & (C_ORIG_RDONLY|C_WRITEMAP));
8087 mx->mx_dbx.md_name.mv_size = 0;
8088 mx->mx_dbx.md_name.mv_data = NULL;
8089 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
8090 mx->mx_dbx.md_dcmp = NULL;
8091 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
8094 /** Final setup of a sorted-dups cursor.
8095 * Sets up the fields that depend on the data from the main cursor.
8096 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
8097 * @param[in] node The data containing the #MDB_db record for the
8098 * sorted-dup database.
8101 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
8103 MDB_xcursor *mx = mc->mc_xcursor;
8105 mx->mx_cursor.mc_flags &= C_SUB|C_ORIG_RDONLY|C_WRITEMAP;
8106 if (node->mn_flags & F_SUBDATA) {
8107 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
8108 mx->mx_cursor.mc_pg[0] = 0;
8109 mx->mx_cursor.mc_snum = 0;
8110 mx->mx_cursor.mc_top = 0;
8112 MDB_page *fp = NODEDATA(node);
8113 mx->mx_db.md_pad = 0;
8114 mx->mx_db.md_flags = 0;
8115 mx->mx_db.md_depth = 1;
8116 mx->mx_db.md_branch_pages = 0;
8117 mx->mx_db.md_leaf_pages = 1;
8118 mx->mx_db.md_overflow_pages = 0;
8119 mx->mx_db.md_entries = NUMKEYS(fp);
8120 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
8121 mx->mx_cursor.mc_snum = 1;
8122 mx->mx_cursor.mc_top = 0;
8123 mx->mx_cursor.mc_flags |= C_INITIALIZED;
8124 mx->mx_cursor.mc_pg[0] = fp;
8125 mx->mx_cursor.mc_ki[0] = 0;
8126 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
8127 mx->mx_db.md_flags = MDB_DUPFIXED;
8128 mx->mx_db.md_pad = fp->mp_pad;
8129 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
8130 mx->mx_db.md_flags |= MDB_INTEGERKEY;
8133 DPRINTF(("Sub-db -%u root page %"Yu, mx->mx_cursor.mc_dbi,
8134 mx->mx_db.md_root));
8135 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
8136 if (NEED_CMP_CLONG(mx->mx_dbx.md_cmp, mx->mx_db.md_pad))
8137 mx->mx_dbx.md_cmp = mdb_cmp_clong;
8141 /** Fixup a sorted-dups cursor due to underlying update.
8142 * Sets up some fields that depend on the data from the main cursor.
8143 * Almost the same as init1, but skips initialization steps if the
8144 * xcursor had already been used.
8145 * @param[in] mc The main cursor whose sorted-dups cursor is to be fixed up.
8146 * @param[in] src_mx The xcursor of an up-to-date cursor.
8147 * @param[in] new_dupdata True if converting from a non-#F_DUPDATA item.
8150 mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int new_dupdata)
8152 MDB_xcursor *mx = mc->mc_xcursor;
8155 mx->mx_cursor.mc_snum = 1;
8156 mx->mx_cursor.mc_top = 0;
8157 mx->mx_cursor.mc_flags |= C_INITIALIZED;
8158 mx->mx_cursor.mc_ki[0] = 0;
8159 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
8160 #if UINT_MAX < MDB_SIZE_MAX /* matches mdb_xcursor_init1:NEED_CMP_CLONG() */
8161 mx->mx_dbx.md_cmp = src_mx->mx_dbx.md_cmp;
8163 } else if (!(mx->mx_cursor.mc_flags & C_INITIALIZED)) {
8166 mx->mx_db = src_mx->mx_db;
8167 mx->mx_cursor.mc_pg[0] = src_mx->mx_cursor.mc_pg[0];
8168 DPRINTF(("Sub-db -%u root page %"Yu, mx->mx_cursor.mc_dbi,
8169 mx->mx_db.md_root));
8172 /** Initialize a cursor for a given transaction and database. */
8174 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
8177 mc->mc_backup = NULL;
8180 mc->mc_db = &txn->mt_dbs[dbi];
8181 mc->mc_dbx = &txn->mt_dbxs[dbi];
8182 mc->mc_dbflag = &txn->mt_dbflags[dbi];
8187 MC_SET_OVPG(mc, NULL);
8188 mc->mc_flags = txn->mt_flags & (C_ORIG_RDONLY|C_WRITEMAP);
8189 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
8190 mdb_tassert(txn, mx != NULL);
8191 mc->mc_xcursor = mx;
8192 mdb_xcursor_init0(mc);
8194 mc->mc_xcursor = NULL;
8196 if (*mc->mc_dbflag & DB_STALE) {
8197 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
8202 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
8205 size_t size = sizeof(MDB_cursor);
8207 if (!ret || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
8210 if (txn->mt_flags & MDB_TXN_BLOCKED)
8213 if (dbi == FREE_DBI && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
8216 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
8217 size += sizeof(MDB_xcursor);
8219 if ((mc = malloc(size)) != NULL) {
8220 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
8221 if (txn->mt_cursors) {
8222 mc->mc_next = txn->mt_cursors[dbi];
8223 txn->mt_cursors[dbi] = mc;
8224 mc->mc_flags |= C_UNTRACK;
8236 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
8238 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi, DB_VALID))
8241 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
8244 if (txn->mt_flags & MDB_TXN_BLOCKED)
8247 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
8251 /* Return the count of duplicate data items for the current key */
8253 mdb_cursor_count(MDB_cursor *mc, mdb_size_t *countp)
8257 if (mc == NULL || countp == NULL)
8260 if (mc->mc_xcursor == NULL)
8261 return MDB_INCOMPATIBLE;
8263 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
8266 if (!(mc->mc_flags & C_INITIALIZED))
8269 if (!mc->mc_snum || (mc->mc_flags & C_EOF))
8270 return MDB_NOTFOUND;
8272 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
8273 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
8276 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
8279 *countp = mc->mc_xcursor->mx_db.md_entries;
8285 mdb_cursor_close(MDB_cursor *mc)
8287 if (mc && !mc->mc_backup) {
8288 /* remove from txn, if tracked */
8289 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
8290 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
8291 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
8293 *prev = mc->mc_next;
8300 mdb_cursor_txn(MDB_cursor *mc)
8302 if (!mc) return NULL;
8307 mdb_cursor_dbi(MDB_cursor *mc)
8312 /** Replace the key for a branch node with a new key.
8313 * @param[in] mc Cursor pointing to the node to operate on.
8314 * @param[in] key The new key to use.
8315 * @return 0 on success, non-zero on failure.
8318 mdb_update_key(MDB_cursor *mc, MDB_val *key)
8324 int delta, ksize, oksize;
8325 indx_t ptr, i, numkeys, indx;
8328 indx = mc->mc_ki[mc->mc_top];
8329 mp = mc->mc_pg[mc->mc_top];
8330 node = NODEPTR(mp, indx);
8331 ptr = mp->mp_ptrs[indx];
8335 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
8336 k2.mv_data = NODEKEY(node);
8337 k2.mv_size = node->mn_ksize;
8338 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Yu,
8340 mdb_dkey(&k2, kbuf2),
8346 /* Sizes must be 2-byte aligned. */
8347 ksize = EVEN(key->mv_size);
8348 oksize = EVEN(node->mn_ksize);
8349 delta = ksize - oksize;
8351 /* Shift node contents if EVEN(key length) changed. */
8353 if (delta > 0 && SIZELEFT(mp) < delta) {
8355 /* not enough space left, do a delete and split */
8356 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
8357 pgno = NODEPGNO(node);
8358 mdb_node_del(mc, 0);
8359 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
8362 numkeys = NUMKEYS(mp);
8363 for (i = 0; i < numkeys; i++) {
8364 if (mp->mp_ptrs[i] <= ptr)
8365 mp->mp_ptrs[i] -= delta;
8368 base = (char *)mp + mp->mp_upper + PAGEBASE;
8369 len = ptr - mp->mp_upper + NODESIZE;
8370 memmove(base - delta, base, len);
8371 mp->mp_upper -= delta;
8373 node = NODEPTR(mp, indx);
8376 /* But even if no shift was needed, update ksize */
8377 if (node->mn_ksize != key->mv_size)
8378 node->mn_ksize = key->mv_size;
8381 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
8387 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
8389 /** Perform \b act while tracking temporary cursor \b mn */
8390 #define WITH_CURSOR_TRACKING(mn, act) do { \
8391 MDB_cursor dummy, *tracked, **tp = &(mn).mc_txn->mt_cursors[mn.mc_dbi]; \
8392 if ((mn).mc_flags & C_SUB) { \
8393 dummy.mc_flags = C_INITIALIZED; \
8394 dummy.mc_xcursor = (MDB_xcursor *)&(mn); \
8399 tracked->mc_next = *tp; \
8402 *tp = tracked->mc_next; \
8405 /** Move a node from csrc to cdst.
8408 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft)
8415 unsigned short flags;
8419 /* Mark src and dst as dirty. */
8420 if ((rc = mdb_page_touch(csrc)) ||
8421 (rc = mdb_page_touch(cdst)))
8424 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8425 key.mv_size = csrc->mc_db->md_pad;
8426 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
8428 data.mv_data = NULL;
8432 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
8433 mdb_cassert(csrc, !((size_t)srcnode & 1));
8434 srcpg = NODEPGNO(srcnode);
8435 flags = srcnode->mn_flags;
8436 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
8437 unsigned int snum = csrc->mc_snum;
8439 /* must find the lowest key below src */
8440 rc = mdb_page_search_lowest(csrc);
8443 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8444 key.mv_size = csrc->mc_db->md_pad;
8445 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
8447 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
8448 key.mv_size = NODEKSZ(s2);
8449 key.mv_data = NODEKEY(s2);
8451 csrc->mc_snum = snum--;
8452 csrc->mc_top = snum;
8454 key.mv_size = NODEKSZ(srcnode);
8455 key.mv_data = NODEKEY(srcnode);
8457 data.mv_size = NODEDSZ(srcnode);
8458 data.mv_data = NODEDATA(srcnode);
8460 mn.mc_xcursor = NULL;
8461 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
8462 unsigned int snum = cdst->mc_snum;
8465 /* must find the lowest key below dst */
8466 mdb_cursor_copy(cdst, &mn);
8467 rc = mdb_page_search_lowest(&mn);
8470 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
8471 bkey.mv_size = mn.mc_db->md_pad;
8472 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
8474 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
8475 bkey.mv_size = NODEKSZ(s2);
8476 bkey.mv_data = NODEKEY(s2);
8478 mn.mc_snum = snum--;
8481 rc = mdb_update_key(&mn, &bkey);
8486 DPRINTF(("moving %s node %u [%s] on page %"Yu" to node %u on page %"Yu,
8487 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
8488 csrc->mc_ki[csrc->mc_top],
8490 csrc->mc_pg[csrc->mc_top]->mp_pgno,
8491 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
8493 /* Add the node to the destination page.
8495 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
8496 if (rc != MDB_SUCCESS)
8499 /* Delete the node from the source page.
8501 mdb_node_del(csrc, key.mv_size);
8504 /* Adjust other cursors pointing to mp */
8505 MDB_cursor *m2, *m3;
8506 MDB_dbi dbi = csrc->mc_dbi;
8507 MDB_page *mpd, *mps;
8509 mps = csrc->mc_pg[csrc->mc_top];
8510 /* If we're adding on the left, bump others up */
8512 mpd = cdst->mc_pg[csrc->mc_top];
8513 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8514 if (csrc->mc_flags & C_SUB)
8515 m3 = &m2->mc_xcursor->mx_cursor;
8518 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
8521 m3->mc_pg[csrc->mc_top] == mpd &&
8522 m3->mc_ki[csrc->mc_top] >= cdst->mc_ki[csrc->mc_top]) {
8523 m3->mc_ki[csrc->mc_top]++;
8526 m3->mc_pg[csrc->mc_top] == mps &&
8527 m3->mc_ki[csrc->mc_top] == csrc->mc_ki[csrc->mc_top]) {
8528 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
8529 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
8530 m3->mc_ki[csrc->mc_top-1]++;
8532 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) &&
8534 MDB_node *node = NODEPTR(m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
8535 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
8536 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
8540 /* Adding on the right, bump others down */
8542 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8543 if (csrc->mc_flags & C_SUB)
8544 m3 = &m2->mc_xcursor->mx_cursor;
8547 if (m3 == csrc) continue;
8548 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
8550 if (m3->mc_pg[csrc->mc_top] == mps) {
8551 if (!m3->mc_ki[csrc->mc_top]) {
8552 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
8553 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
8554 m3->mc_ki[csrc->mc_top-1]--;
8556 m3->mc_ki[csrc->mc_top]--;
8558 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) &&
8560 MDB_node *node = NODEPTR(m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
8561 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
8562 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
8569 /* Update the parent separators.
8571 if (csrc->mc_ki[csrc->mc_top] == 0) {
8572 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
8573 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8574 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
8576 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
8577 key.mv_size = NODEKSZ(srcnode);
8578 key.mv_data = NODEKEY(srcnode);
8580 DPRINTF(("update separator for source page %"Yu" to [%s]",
8581 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
8582 mdb_cursor_copy(csrc, &mn);
8585 /* We want mdb_rebalance to find mn when doing fixups */
8586 WITH_CURSOR_TRACKING(mn,
8587 rc = mdb_update_key(&mn, &key));
8591 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
8593 indx_t ix = csrc->mc_ki[csrc->mc_top];
8594 nullkey.mv_size = 0;
8595 csrc->mc_ki[csrc->mc_top] = 0;
8596 rc = mdb_update_key(csrc, &nullkey);
8597 csrc->mc_ki[csrc->mc_top] = ix;
8598 mdb_cassert(csrc, rc == MDB_SUCCESS);
8602 if (cdst->mc_ki[cdst->mc_top] == 0) {
8603 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
8604 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8605 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
8607 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
8608 key.mv_size = NODEKSZ(srcnode);
8609 key.mv_data = NODEKEY(srcnode);
8611 DPRINTF(("update separator for destination page %"Yu" to [%s]",
8612 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
8613 mdb_cursor_copy(cdst, &mn);
8616 /* We want mdb_rebalance to find mn when doing fixups */
8617 WITH_CURSOR_TRACKING(mn,
8618 rc = mdb_update_key(&mn, &key));
8622 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
8624 indx_t ix = cdst->mc_ki[cdst->mc_top];
8625 nullkey.mv_size = 0;
8626 cdst->mc_ki[cdst->mc_top] = 0;
8627 rc = mdb_update_key(cdst, &nullkey);
8628 cdst->mc_ki[cdst->mc_top] = ix;
8629 mdb_cassert(cdst, rc == MDB_SUCCESS);
8636 /** Merge one page into another.
8637 * The nodes from the page pointed to by \b csrc will
8638 * be copied to the page pointed to by \b cdst and then
8639 * the \b csrc page will be freed.
8640 * @param[in] csrc Cursor pointing to the source page.
8641 * @param[in] cdst Cursor pointing to the destination page.
8642 * @return 0 on success, non-zero on failure.
8645 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
8647 MDB_page *psrc, *pdst;
8654 psrc = csrc->mc_pg[csrc->mc_top];
8655 pdst = cdst->mc_pg[cdst->mc_top];
8657 DPRINTF(("merging page %"Yu" into %"Yu, psrc->mp_pgno, pdst->mp_pgno));
8659 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
8660 mdb_cassert(csrc, cdst->mc_snum > 1);
8662 /* Mark dst as dirty. */
8663 if ((rc = mdb_page_touch(cdst)))
8666 /* get dst page again now that we've touched it. */
8667 pdst = cdst->mc_pg[cdst->mc_top];
8669 /* Move all nodes from src to dst.
8671 j = nkeys = NUMKEYS(pdst);
8672 if (IS_LEAF2(psrc)) {
8673 key.mv_size = csrc->mc_db->md_pad;
8674 key.mv_data = METADATA(psrc);
8675 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
8676 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
8677 if (rc != MDB_SUCCESS)
8679 key.mv_data = (char *)key.mv_data + key.mv_size;
8682 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
8683 srcnode = NODEPTR(psrc, i);
8684 if (i == 0 && IS_BRANCH(psrc)) {
8687 mdb_cursor_copy(csrc, &mn);
8688 mn.mc_xcursor = NULL;
8689 /* must find the lowest key below src */
8690 rc = mdb_page_search_lowest(&mn);
8693 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
8694 key.mv_size = mn.mc_db->md_pad;
8695 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
8697 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
8698 key.mv_size = NODEKSZ(s2);
8699 key.mv_data = NODEKEY(s2);
8702 key.mv_size = srcnode->mn_ksize;
8703 key.mv_data = NODEKEY(srcnode);
8706 data.mv_size = NODEDSZ(srcnode);
8707 data.mv_data = NODEDATA(srcnode);
8708 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
8709 if (rc != MDB_SUCCESS)
8714 DPRINTF(("dst page %"Yu" now has %u keys (%.1f%% filled)",
8715 pdst->mp_pgno, NUMKEYS(pdst),
8716 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
8718 /* Unlink the src page from parent and add to free list.
8721 mdb_node_del(csrc, 0);
8722 if (csrc->mc_ki[csrc->mc_top] == 0) {
8724 rc = mdb_update_key(csrc, &key);
8732 psrc = csrc->mc_pg[csrc->mc_top];
8733 /* If not operating on FreeDB, allow this page to be reused
8734 * in this txn. Otherwise just add to free list.
8736 rc = mdb_page_loose(csrc, psrc);
8740 csrc->mc_db->md_leaf_pages--;
8742 csrc->mc_db->md_branch_pages--;
8744 /* Adjust other cursors pointing to mp */
8745 MDB_cursor *m2, *m3;
8746 MDB_dbi dbi = csrc->mc_dbi;
8747 unsigned int top = csrc->mc_top;
8749 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8750 if (csrc->mc_flags & C_SUB)
8751 m3 = &m2->mc_xcursor->mx_cursor;
8754 if (m3 == csrc) continue;
8755 if (m3->mc_snum < csrc->mc_snum) continue;
8756 if (m3->mc_pg[top] == psrc) {
8757 m3->mc_pg[top] = pdst;
8758 m3->mc_ki[top] += nkeys;
8759 m3->mc_ki[top-1] = cdst->mc_ki[top-1];
8760 } else if (m3->mc_pg[top-1] == csrc->mc_pg[top-1] &&
8761 m3->mc_ki[top-1] > csrc->mc_ki[top-1]) {
8764 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) &&
8766 MDB_node *node = NODEPTR(m3->mc_pg[top], m3->mc_ki[top]);
8767 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
8768 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
8773 unsigned int snum = cdst->mc_snum;
8774 uint16_t depth = cdst->mc_db->md_depth;
8775 mdb_cursor_pop(cdst);
8776 rc = mdb_rebalance(cdst);
8777 /* Did the tree height change? */
8778 if (depth != cdst->mc_db->md_depth)
8779 snum += cdst->mc_db->md_depth - depth;
8780 cdst->mc_snum = snum;
8781 cdst->mc_top = snum-1;
8786 /** Copy the contents of a cursor.
8787 * @param[in] csrc The cursor to copy from.
8788 * @param[out] cdst The cursor to copy to.
8791 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
8795 cdst->mc_txn = csrc->mc_txn;
8796 cdst->mc_dbi = csrc->mc_dbi;
8797 cdst->mc_db = csrc->mc_db;
8798 cdst->mc_dbx = csrc->mc_dbx;
8799 cdst->mc_snum = csrc->mc_snum;
8800 cdst->mc_top = csrc->mc_top;
8801 cdst->mc_flags = csrc->mc_flags;
8802 MC_SET_OVPG(cdst, MC_OVPG(csrc));
8804 for (i=0; i<csrc->mc_snum; i++) {
8805 cdst->mc_pg[i] = csrc->mc_pg[i];
8806 cdst->mc_ki[i] = csrc->mc_ki[i];
8810 /** Rebalance the tree after a delete operation.
8811 * @param[in] mc Cursor pointing to the page where rebalancing
8813 * @return 0 on success, non-zero on failure.
8816 mdb_rebalance(MDB_cursor *mc)
8820 unsigned int ptop, minkeys, thresh;
8824 if (IS_BRANCH(mc->mc_pg[mc->mc_top])) {
8829 thresh = FILL_THRESHOLD;
8831 DPRINTF(("rebalancing %s page %"Yu" (has %u keys, %.1f%% full)",
8832 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
8833 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
8834 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
8836 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= thresh &&
8837 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
8838 DPRINTF(("no need to rebalance page %"Yu", above fill threshold",
8839 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
8843 if (mc->mc_snum < 2) {
8844 MDB_page *mp = mc->mc_pg[0];
8846 DPUTS("Can't rebalance a subpage, ignoring");
8849 if (NUMKEYS(mp) == 0) {
8850 DPUTS("tree is completely empty");
8851 mc->mc_db->md_root = P_INVALID;
8852 mc->mc_db->md_depth = 0;
8853 mc->mc_db->md_leaf_pages = 0;
8854 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
8857 /* Adjust cursors pointing to mp */
8860 mc->mc_flags &= ~C_INITIALIZED;
8862 MDB_cursor *m2, *m3;
8863 MDB_dbi dbi = mc->mc_dbi;
8865 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8866 if (mc->mc_flags & C_SUB)
8867 m3 = &m2->mc_xcursor->mx_cursor;
8870 if (!(m3->mc_flags & C_INITIALIZED) || (m3->mc_snum < mc->mc_snum))
8872 if (m3->mc_pg[0] == mp) {
8875 m3->mc_flags &= ~C_INITIALIZED;
8879 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
8881 DPUTS("collapsing root page!");
8882 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
8885 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
8886 rc = mdb_page_get(mc, mc->mc_db->md_root, &mc->mc_pg[0], NULL);
8889 mc->mc_db->md_depth--;
8890 mc->mc_db->md_branch_pages--;
8891 mc->mc_ki[0] = mc->mc_ki[1];
8892 for (i = 1; i<mc->mc_db->md_depth; i++) {
8893 mc->mc_pg[i] = mc->mc_pg[i+1];
8894 mc->mc_ki[i] = mc->mc_ki[i+1];
8897 /* Adjust other cursors pointing to mp */
8898 MDB_cursor *m2, *m3;
8899 MDB_dbi dbi = mc->mc_dbi;
8901 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8902 if (mc->mc_flags & C_SUB)
8903 m3 = &m2->mc_xcursor->mx_cursor;
8906 if (m3 == mc) continue;
8907 if (!(m3->mc_flags & C_INITIALIZED))
8909 if (m3->mc_pg[0] == mp) {
8910 for (i=0; i<mc->mc_db->md_depth; i++) {
8911 m3->mc_pg[i] = m3->mc_pg[i+1];
8912 m3->mc_ki[i] = m3->mc_ki[i+1];
8920 DPUTS("root page doesn't need rebalancing");
8924 /* The parent (branch page) must have at least 2 pointers,
8925 * otherwise the tree is invalid.
8927 ptop = mc->mc_top-1;
8928 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
8930 /* Leaf page fill factor is below the threshold.
8931 * Try to move keys from left or right neighbor, or
8932 * merge with a neighbor page.
8937 mdb_cursor_copy(mc, &mn);
8938 mn.mc_xcursor = NULL;
8940 oldki = mc->mc_ki[mc->mc_top];
8941 if (mc->mc_ki[ptop] == 0) {
8942 /* We're the leftmost leaf in our parent.
8944 DPUTS("reading right neighbor");
8946 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
8947 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
8950 mn.mc_ki[mn.mc_top] = 0;
8951 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
8954 /* There is at least one neighbor to the left.
8956 DPUTS("reading left neighbor");
8958 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
8959 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
8962 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
8963 mc->mc_ki[mc->mc_top] = 0;
8967 DPRINTF(("found neighbor page %"Yu" (%u keys, %.1f%% full)",
8968 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
8969 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
8971 /* If the neighbor page is above threshold and has enough keys,
8972 * move one key from it. Otherwise we should try to merge them.
8973 * (A branch page must never have less than 2 keys.)
8975 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= thresh && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
8976 rc = mdb_node_move(&mn, mc, fromleft);
8978 /* if we inserted on left, bump position up */
8983 rc = mdb_page_merge(&mn, mc);
8985 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
8986 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
8987 /* We want mdb_rebalance to find mn when doing fixups */
8988 WITH_CURSOR_TRACKING(mn,
8989 rc = mdb_page_merge(mc, &mn));
8990 mdb_cursor_copy(&mn, mc);
8992 mc->mc_flags &= ~C_EOF;
8994 mc->mc_ki[mc->mc_top] = oldki;
8998 /** Complete a delete operation started by #mdb_cursor_del(). */
9000 mdb_cursor_del0(MDB_cursor *mc)
9006 MDB_cursor *m2, *m3;
9007 MDB_dbi dbi = mc->mc_dbi;
9009 ki = mc->mc_ki[mc->mc_top];
9010 mp = mc->mc_pg[mc->mc_top];
9011 mdb_node_del(mc, mc->mc_db->md_pad);
9012 mc->mc_db->md_entries--;
9014 /* Adjust other cursors pointing to mp */
9015 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9016 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
9017 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9019 if (m3 == mc || m3->mc_snum < mc->mc_snum)
9021 if (m3->mc_pg[mc->mc_top] == mp) {
9022 if (m3->mc_ki[mc->mc_top] == ki) {
9023 m3->mc_flags |= C_DEL;
9024 } else if (m3->mc_ki[mc->mc_top] > ki) {
9025 m3->mc_ki[mc->mc_top]--;
9027 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
9028 MDB_node *node = NODEPTR(m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
9029 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
9030 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
9035 rc = mdb_rebalance(mc);
9037 if (rc == MDB_SUCCESS) {
9038 /* DB is totally empty now, just bail out.
9039 * Other cursors adjustments were already done
9040 * by mdb_rebalance and aren't needed here.
9045 mp = mc->mc_pg[mc->mc_top];
9046 nkeys = NUMKEYS(mp);
9048 /* Adjust other cursors pointing to mp */
9049 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
9050 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
9051 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9053 if (m3->mc_snum < mc->mc_snum)
9055 if (m3->mc_pg[mc->mc_top] == mp) {
9056 /* if m3 points past last node in page, find next sibling */
9057 if (m3->mc_ki[mc->mc_top] >= mc->mc_ki[mc->mc_top]) {
9058 if (m3->mc_ki[mc->mc_top] >= nkeys) {
9059 rc = mdb_cursor_sibling(m3, 1);
9060 if (rc == MDB_NOTFOUND) {
9061 m3->mc_flags |= C_EOF;
9066 if (mc->mc_db->md_flags & MDB_DUPSORT) {
9067 MDB_node *node = NODEPTR(m3->mc_pg[m3->mc_top], m3->mc_ki[m3->mc_top]);
9068 if (node->mn_flags & F_DUPDATA) {
9069 mdb_xcursor_init1(m3, node);
9070 m3->mc_xcursor->mx_cursor.mc_flags |= C_DEL;
9076 mc->mc_flags |= C_DEL;
9080 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
9085 mdb_del(MDB_txn *txn, MDB_dbi dbi,
9086 MDB_val *key, MDB_val *data)
9088 if (!key || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9091 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
9092 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
9094 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
9095 /* must ignore any data */
9099 return mdb_del0(txn, dbi, key, data, 0);
9103 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
9104 MDB_val *key, MDB_val *data, unsigned flags)
9109 MDB_val rdata, *xdata;
9113 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
9115 mdb_cursor_init(&mc, txn, dbi, &mx);
9124 flags |= MDB_NODUPDATA;
9126 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
9128 /* let mdb_page_split know about this cursor if needed:
9129 * delete will trigger a rebalance; if it needs to move
9130 * a node from one page to another, it will have to
9131 * update the parent's separator key(s). If the new sepkey
9132 * is larger than the current one, the parent page may
9133 * run out of space, triggering a split. We need this
9134 * cursor to be consistent until the end of the rebalance.
9136 mc.mc_flags |= C_UNTRACK;
9137 mc.mc_next = txn->mt_cursors[dbi];
9138 txn->mt_cursors[dbi] = &mc;
9139 rc = mdb_cursor_del(&mc, flags);
9140 txn->mt_cursors[dbi] = mc.mc_next;
9145 /** Split a page and insert a new node.
9146 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
9147 * The cursor will be updated to point to the actual page and index where
9148 * the node got inserted after the split.
9149 * @param[in] newkey The key for the newly inserted node.
9150 * @param[in] newdata The data for the newly inserted node.
9151 * @param[in] newpgno The page number, if the new node is a branch node.
9152 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
9153 * @return 0 on success, non-zero on failure.
9156 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
9157 unsigned int nflags)
9160 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
9163 int i, j, split_indx, nkeys, pmax;
9164 MDB_env *env = mc->mc_txn->mt_env;
9166 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
9167 MDB_page *copy = NULL;
9168 MDB_page *mp, *rp, *pp;
9173 mp = mc->mc_pg[mc->mc_top];
9174 newindx = mc->mc_ki[mc->mc_top];
9175 nkeys = NUMKEYS(mp);
9177 DPRINTF(("-----> splitting %s page %"Yu" and adding [%s] at index %i/%i",
9178 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
9179 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
9181 /* Create a right sibling. */
9182 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
9184 rp->mp_pad = mp->mp_pad;
9185 DPRINTF(("new right sibling: page %"Yu, rp->mp_pgno));
9187 /* Usually when splitting the root page, the cursor
9188 * height is 1. But when called from mdb_update_key,
9189 * the cursor height may be greater because it walks
9190 * up the stack while finding the branch slot to update.
9192 if (mc->mc_top < 1) {
9193 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
9195 /* shift current top to make room for new parent */
9196 for (i=mc->mc_snum; i>0; i--) {
9197 mc->mc_pg[i] = mc->mc_pg[i-1];
9198 mc->mc_ki[i] = mc->mc_ki[i-1];
9202 mc->mc_db->md_root = pp->mp_pgno;
9203 DPRINTF(("root split! new root = %"Yu, pp->mp_pgno));
9204 new_root = mc->mc_db->md_depth++;
9206 /* Add left (implicit) pointer. */
9207 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
9208 /* undo the pre-push */
9209 mc->mc_pg[0] = mc->mc_pg[1];
9210 mc->mc_ki[0] = mc->mc_ki[1];
9211 mc->mc_db->md_root = mp->mp_pgno;
9212 mc->mc_db->md_depth--;
9219 ptop = mc->mc_top-1;
9220 DPRINTF(("parent branch page is %"Yu, mc->mc_pg[ptop]->mp_pgno));
9223 mdb_cursor_copy(mc, &mn);
9224 mn.mc_xcursor = NULL;
9225 mn.mc_pg[mn.mc_top] = rp;
9226 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
9228 if (nflags & MDB_APPEND) {
9229 mn.mc_ki[mn.mc_top] = 0;
9231 split_indx = newindx;
9235 split_indx = (nkeys+1) / 2;
9240 unsigned int lsize, rsize, ksize;
9241 /* Move half of the keys to the right sibling */
9242 x = mc->mc_ki[mc->mc_top] - split_indx;
9243 ksize = mc->mc_db->md_pad;
9244 split = LEAF2KEY(mp, split_indx, ksize);
9245 rsize = (nkeys - split_indx) * ksize;
9246 lsize = (nkeys - split_indx) * sizeof(indx_t);
9247 mp->mp_lower -= lsize;
9248 rp->mp_lower += lsize;
9249 mp->mp_upper += rsize - lsize;
9250 rp->mp_upper -= rsize - lsize;
9251 sepkey.mv_size = ksize;
9252 if (newindx == split_indx) {
9253 sepkey.mv_data = newkey->mv_data;
9255 sepkey.mv_data = split;
9258 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
9259 memcpy(rp->mp_ptrs, split, rsize);
9260 sepkey.mv_data = rp->mp_ptrs;
9261 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
9262 memcpy(ins, newkey->mv_data, ksize);
9263 mp->mp_lower += sizeof(indx_t);
9264 mp->mp_upper -= ksize - sizeof(indx_t);
9267 memcpy(rp->mp_ptrs, split, x * ksize);
9268 ins = LEAF2KEY(rp, x, ksize);
9269 memcpy(ins, newkey->mv_data, ksize);
9270 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
9271 rp->mp_lower += sizeof(indx_t);
9272 rp->mp_upper -= ksize - sizeof(indx_t);
9273 mc->mc_ki[mc->mc_top] = x;
9276 int psize, nsize, k;
9277 /* Maximum free space in an empty page */
9278 pmax = env->me_psize - PAGEHDRSZ;
9280 nsize = mdb_leaf_size(env, newkey, newdata);
9282 nsize = mdb_branch_size(env, newkey);
9283 nsize = EVEN(nsize);
9285 /* grab a page to hold a temporary copy */
9286 copy = mdb_page_malloc(mc->mc_txn, 1);
9291 copy->mp_pgno = mp->mp_pgno;
9292 copy->mp_flags = mp->mp_flags;
9293 copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
9294 copy->mp_upper = env->me_psize - PAGEBASE;
9296 /* prepare to insert */
9297 for (i=0, j=0; i<nkeys; i++) {
9299 copy->mp_ptrs[j++] = 0;
9301 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
9304 /* When items are relatively large the split point needs
9305 * to be checked, because being off-by-one will make the
9306 * difference between success or failure in mdb_node_add.
9308 * It's also relevant if a page happens to be laid out
9309 * such that one half of its nodes are all "small" and
9310 * the other half of its nodes are "large." If the new
9311 * item is also "large" and falls on the half with
9312 * "large" nodes, it also may not fit.
9314 * As a final tweak, if the new item goes on the last
9315 * spot on the page (and thus, onto the new page), bias
9316 * the split so the new page is emptier than the old page.
9317 * This yields better packing during sequential inserts.
9319 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
9320 /* Find split point */
9322 if (newindx <= split_indx || newindx >= nkeys) {
9324 k = newindx >= nkeys ? nkeys : split_indx+1+IS_LEAF(mp);
9329 for (; i!=k; i+=j) {
9334 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
9335 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
9337 if (F_ISSET(node->mn_flags, F_BIGDATA))
9338 psize += sizeof(pgno_t);
9340 psize += NODEDSZ(node);
9342 psize = EVEN(psize);
9344 if (psize > pmax || i == k-j) {
9345 split_indx = i + (j<0);
9350 if (split_indx == newindx) {
9351 sepkey.mv_size = newkey->mv_size;
9352 sepkey.mv_data = newkey->mv_data;
9354 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
9355 sepkey.mv_size = node->mn_ksize;
9356 sepkey.mv_data = NODEKEY(node);
9361 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
9363 /* Copy separator key to the parent.
9365 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
9366 int snum = mc->mc_snum;
9370 /* We want other splits to find mn when doing fixups */
9371 WITH_CURSOR_TRACKING(mn,
9372 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0));
9377 if (mc->mc_snum > snum) {
9380 /* Right page might now have changed parent.
9381 * Check if left page also changed parent.
9383 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
9384 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
9385 for (i=0; i<ptop; i++) {
9386 mc->mc_pg[i] = mn.mc_pg[i];
9387 mc->mc_ki[i] = mn.mc_ki[i];
9389 mc->mc_pg[ptop] = mn.mc_pg[ptop];
9390 if (mn.mc_ki[ptop]) {
9391 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
9393 /* find right page's left sibling */
9394 mc->mc_ki[ptop] = mn.mc_ki[ptop];
9395 mdb_cursor_sibling(mc, 0);
9400 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
9403 if (rc != MDB_SUCCESS) {
9406 if (nflags & MDB_APPEND) {
9407 mc->mc_pg[mc->mc_top] = rp;
9408 mc->mc_ki[mc->mc_top] = 0;
9409 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
9412 for (i=0; i<mc->mc_top; i++)
9413 mc->mc_ki[i] = mn.mc_ki[i];
9414 } else if (!IS_LEAF2(mp)) {
9416 mc->mc_pg[mc->mc_top] = rp;
9421 rkey.mv_data = newkey->mv_data;
9422 rkey.mv_size = newkey->mv_size;
9428 /* Update index for the new key. */
9429 mc->mc_ki[mc->mc_top] = j;
9431 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
9432 rkey.mv_data = NODEKEY(node);
9433 rkey.mv_size = node->mn_ksize;
9435 xdata.mv_data = NODEDATA(node);
9436 xdata.mv_size = NODEDSZ(node);
9439 pgno = NODEPGNO(node);
9440 flags = node->mn_flags;
9443 if (!IS_LEAF(mp) && j == 0) {
9444 /* First branch index doesn't need key data. */
9448 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
9454 mc->mc_pg[mc->mc_top] = copy;
9459 } while (i != split_indx);
9461 nkeys = NUMKEYS(copy);
9462 for (i=0; i<nkeys; i++)
9463 mp->mp_ptrs[i] = copy->mp_ptrs[i];
9464 mp->mp_lower = copy->mp_lower;
9465 mp->mp_upper = copy->mp_upper;
9466 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
9467 env->me_psize - copy->mp_upper - PAGEBASE);
9469 /* reset back to original page */
9470 if (newindx < split_indx) {
9471 mc->mc_pg[mc->mc_top] = mp;
9473 mc->mc_pg[mc->mc_top] = rp;
9475 /* Make sure mc_ki is still valid.
9477 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
9478 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
9479 for (i=0; i<=ptop; i++) {
9480 mc->mc_pg[i] = mn.mc_pg[i];
9481 mc->mc_ki[i] = mn.mc_ki[i];
9485 if (nflags & MDB_RESERVE) {
9486 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
9487 if (!(node->mn_flags & F_BIGDATA))
9488 newdata->mv_data = NODEDATA(node);
9491 if (newindx >= split_indx) {
9492 mc->mc_pg[mc->mc_top] = rp;
9494 /* Make sure mc_ki is still valid.
9496 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
9497 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
9498 for (i=0; i<=ptop; i++) {
9499 mc->mc_pg[i] = mn.mc_pg[i];
9500 mc->mc_ki[i] = mn.mc_ki[i];
9507 /* Adjust other cursors pointing to mp */
9508 MDB_cursor *m2, *m3;
9509 MDB_dbi dbi = mc->mc_dbi;
9510 nkeys = NUMKEYS(mp);
9512 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9513 if (mc->mc_flags & C_SUB)
9514 m3 = &m2->mc_xcursor->mx_cursor;
9519 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9523 /* sub cursors may be on different DB */
9524 if (m3->mc_pg[0] != mp)
9527 for (k=new_root; k>=0; k--) {
9528 m3->mc_ki[k+1] = m3->mc_ki[k];
9529 m3->mc_pg[k+1] = m3->mc_pg[k];
9531 if (m3->mc_ki[0] >= nkeys) {
9536 m3->mc_pg[0] = mc->mc_pg[0];
9540 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
9541 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
9542 m3->mc_ki[mc->mc_top]++;
9543 if (m3->mc_ki[mc->mc_top] >= nkeys) {
9544 m3->mc_pg[mc->mc_top] = rp;
9545 m3->mc_ki[mc->mc_top] -= nkeys;
9546 for (i=0; i<mc->mc_top; i++) {
9547 m3->mc_ki[i] = mn.mc_ki[i];
9548 m3->mc_pg[i] = mn.mc_pg[i];
9551 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
9552 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
9555 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) &&
9557 MDB_node *node = NODEPTR(m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
9558 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
9559 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
9563 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
9566 if (copy) /* tmp page */
9567 mdb_page_free(env, copy);
9569 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
9574 mdb_put(MDB_txn *txn, MDB_dbi dbi,
9575 MDB_val *key, MDB_val *data, unsigned int flags)
9581 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9584 if (flags & ~(MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP))
9587 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
9588 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
9590 mdb_cursor_init(&mc, txn, dbi, &mx);
9591 mc.mc_next = txn->mt_cursors[dbi];
9592 txn->mt_cursors[dbi] = &mc;
9593 rc = mdb_cursor_put(&mc, key, data, flags);
9594 txn->mt_cursors[dbi] = mc.mc_next;
9599 #define MDB_WBUF (1024*1024)
9601 #define MDB_EOF 0x10 /**< #mdb_env_copyfd1() is done reading */
9603 /** State needed for a double-buffering compacting copy. */
9604 typedef struct mdb_copy {
9605 pthread_mutex_t mc_mutex;
9606 pthread_cond_t mc_cond; /**< Condition variable for #mc_new */
9613 pgno_t mc_next_pgno;
9615 int mc_toggle; /**< Buffer number in provider */
9616 int mc_new; /**< (0-2 buffers to write) | (#MDB_EOF at end) */
9617 volatile int mc_error; /**< Error code, never cleared if set */
9620 /** Dedicated writer thread for compacting copy. */
9621 static THREAD_RET ESECT CALL_CONV
9622 mdb_env_copythr(void *arg)
9626 int toggle = 0, wsize, rc;
9629 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
9632 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
9635 pthread_mutex_lock(&my->mc_mutex);
9638 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
9639 if (my->mc_new == 0 + MDB_EOF) /* 0 buffers, just EOF */
9641 wsize = my->mc_wlen[toggle];
9642 ptr = my->mc_wbuf[toggle];
9645 while (wsize > 0 && !my->mc_error) {
9646 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
9650 } else if (len > 0) {
9663 /* If there's an overflow page tail, write it too */
9664 if (my->mc_olen[toggle]) {
9665 wsize = my->mc_olen[toggle];
9666 ptr = my->mc_over[toggle];
9667 my->mc_olen[toggle] = 0;
9670 my->mc_wlen[toggle] = 0;
9672 /* Return the empty buffer to provider */
9674 pthread_cond_signal(&my->mc_cond);
9676 pthread_mutex_unlock(&my->mc_mutex);
9677 return (THREAD_RET)0;
9681 /** Give buffer and/or #MDB_EOF to writer thread, await unused buffer.
9683 * @param[in] my control structure.
9684 * @param[in] adjust (1 to hand off 1 buffer) | (MDB_EOF when ending).
9687 mdb_env_cthr_toggle(mdb_copy *my, int adjust)
9689 pthread_mutex_lock(&my->mc_mutex);
9690 my->mc_new += adjust;
9691 pthread_cond_signal(&my->mc_cond);
9692 while (my->mc_new & 2) /* both buffers in use */
9693 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
9694 pthread_mutex_unlock(&my->mc_mutex);
9696 my->mc_toggle ^= (adjust & 1);
9697 /* Both threads reset mc_wlen, to be safe from threading errors */
9698 my->mc_wlen[my->mc_toggle] = 0;
9699 return my->mc_error;
9702 /** Depth-first tree traversal for compacting copy. */
9704 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
9706 MDB_cursor mc = {0};
9708 MDB_page *mo, *mp, *leaf;
9713 /* Empty DB, nothing to do */
9714 if (*pg == P_INVALID)
9718 mc.mc_txn = my->mc_txn;
9719 mc.mc_flags = my->mc_txn->mt_flags & (C_ORIG_RDONLY|C_WRITEMAP);
9721 rc = mdb_page_get(&mc, *pg, &mc.mc_pg[0], NULL);
9724 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
9728 /* Make cursor pages writable */
9729 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
9733 for (i=0; i<mc.mc_top; i++) {
9734 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
9735 mc.mc_pg[i] = (MDB_page *)ptr;
9736 ptr += my->mc_env->me_psize;
9739 /* This is writable space for a leaf page. Usually not needed. */
9740 leaf = (MDB_page *)ptr;
9742 toggle = my->mc_toggle;
9743 while (mc.mc_snum > 0) {
9745 mp = mc.mc_pg[mc.mc_top];
9749 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
9750 for (i=0; i<n; i++) {
9751 ni = NODEPTR(mp, i);
9752 if (ni->mn_flags & F_BIGDATA) {
9756 /* Need writable leaf */
9758 mc.mc_pg[mc.mc_top] = leaf;
9759 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
9761 ni = NODEPTR(mp, i);
9764 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9765 memcpy(NODEDATA(ni), &my->mc_next_pgno, sizeof(pgno_t));
9766 rc = mdb_page_get(&mc, pg, &omp, NULL);
9769 if (my->mc_wlen[toggle] >= MDB_WBUF) {
9770 rc = mdb_env_cthr_toggle(my, 1);
9773 toggle = my->mc_toggle;
9775 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
9776 memcpy(mo, omp, my->mc_env->me_psize);
9777 mo->mp_pgno = my->mc_next_pgno;
9778 my->mc_next_pgno += omp->mp_pages;
9779 my->mc_wlen[toggle] += my->mc_env->me_psize;
9780 if (omp->mp_pages > 1) {
9781 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
9782 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
9783 rc = mdb_env_cthr_toggle(my, 1);
9786 toggle = my->mc_toggle;
9788 } else if (ni->mn_flags & F_SUBDATA) {
9791 /* Need writable leaf */
9793 mc.mc_pg[mc.mc_top] = leaf;
9794 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
9796 ni = NODEPTR(mp, i);
9799 memcpy(&db, NODEDATA(ni), sizeof(db));
9800 my->mc_toggle = toggle;
9801 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
9804 toggle = my->mc_toggle;
9805 memcpy(NODEDATA(ni), &db, sizeof(db));
9810 mc.mc_ki[mc.mc_top]++;
9811 if (mc.mc_ki[mc.mc_top] < n) {
9814 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
9816 rc = mdb_page_get(&mc, pg, &mp, NULL);
9821 mc.mc_ki[mc.mc_top] = 0;
9822 if (IS_BRANCH(mp)) {
9823 /* Whenever we advance to a sibling branch page,
9824 * we must proceed all the way down to its first leaf.
9826 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
9829 mc.mc_pg[mc.mc_top] = mp;
9833 if (my->mc_wlen[toggle] >= MDB_WBUF) {
9834 rc = mdb_env_cthr_toggle(my, 1);
9837 toggle = my->mc_toggle;
9839 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
9840 mdb_page_copy(mo, mp, my->mc_env->me_psize);
9841 mo->mp_pgno = my->mc_next_pgno++;
9842 my->mc_wlen[toggle] += my->mc_env->me_psize;
9844 /* Update parent if there is one */
9845 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
9846 SETPGNO(ni, mo->mp_pgno);
9847 mdb_cursor_pop(&mc);
9849 /* Otherwise we're done */
9859 /** Copy environment with compaction. */
9861 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
9866 MDB_txn *txn = NULL;
9868 pgno_t root, new_root;
9869 int rc = MDB_SUCCESS;
9872 if (!(my.mc_mutex = CreateMutex(NULL, FALSE, NULL)) ||
9873 !(my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL))) {
9877 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_os_psize);
9878 if (my.mc_wbuf[0] == NULL) {
9879 /* _aligned_malloc() sets errno, but we use Windows error codes */
9880 rc = ERROR_NOT_ENOUGH_MEMORY;
9884 if ((rc = pthread_mutex_init(&my.mc_mutex, NULL)) != 0)
9886 if ((rc = pthread_cond_init(&my.mc_cond, NULL)) != 0)
9888 #ifdef HAVE_MEMALIGN
9889 my.mc_wbuf[0] = memalign(env->me_os_psize, MDB_WBUF*2);
9890 if (my.mc_wbuf[0] == NULL) {
9897 if ((rc = posix_memalign(&p, env->me_os_psize, MDB_WBUF*2)) != 0)
9903 memset(my.mc_wbuf[0], 0, MDB_WBUF*2);
9904 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
9905 my.mc_next_pgno = NUM_METAS;
9908 rc = THREAD_CREATE(thr, mdb_env_copythr, &my);
9912 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
9916 mp = (MDB_page *)my.mc_wbuf[0];
9917 memset(mp, 0, NUM_METAS * env->me_psize);
9919 mp->mp_flags = P_META;
9920 mm = (MDB_meta *)METADATA(mp);
9921 mdb_env_init_meta0(env, mm);
9922 mm->mm_address = env->me_metas[0]->mm_address;
9924 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
9926 mp->mp_flags = P_META;
9927 *(MDB_meta *)METADATA(mp) = *mm;
9928 mm = (MDB_meta *)METADATA(mp);
9930 /* Set metapage 1 with current main DB */
9931 root = new_root = txn->mt_dbs[MAIN_DBI].md_root;
9932 if (root != P_INVALID) {
9933 /* Count free pages + freeDB pages. Subtract from last_pg
9934 * to find the new last_pg, which also becomes the new root.
9936 MDB_ID freecount = 0;
9939 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
9940 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
9941 freecount += *(MDB_ID *)data.mv_data;
9942 if (rc != MDB_NOTFOUND)
9944 freecount += txn->mt_dbs[FREE_DBI].md_branch_pages +
9945 txn->mt_dbs[FREE_DBI].md_leaf_pages +
9946 txn->mt_dbs[FREE_DBI].md_overflow_pages;
9948 new_root = txn->mt_next_pgno - 1 - freecount;
9949 mm->mm_last_pg = new_root;
9950 mm->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
9951 mm->mm_dbs[MAIN_DBI].md_root = new_root;
9953 /* When the DB is empty, handle it specially to
9954 * fix any breakage like page leaks from ITS#8174.
9956 mm->mm_dbs[MAIN_DBI].md_flags = txn->mt_dbs[MAIN_DBI].md_flags;
9958 if (root != P_INVALID || mm->mm_dbs[MAIN_DBI].md_flags) {
9959 mm->mm_txnid = 1; /* use metapage 1 */
9962 my.mc_wlen[0] = env->me_psize * NUM_METAS;
9964 rc = mdb_env_cwalk(&my, &root, 0);
9965 if (rc == MDB_SUCCESS && root != new_root) {
9966 rc = MDB_INCOMPATIBLE; /* page leak or corrupt DB */
9972 mdb_env_cthr_toggle(&my, 1 | MDB_EOF);
9973 rc = THREAD_FINISH(thr);
9978 if (my.mc_wbuf[0]) _aligned_free(my.mc_wbuf[0]);
9979 if (my.mc_cond) CloseHandle(my.mc_cond);
9980 if (my.mc_mutex) CloseHandle(my.mc_mutex);
9982 free(my.mc_wbuf[0]);
9983 pthread_cond_destroy(&my.mc_cond);
9985 pthread_mutex_destroy(&my.mc_mutex);
9987 return rc ? rc : my.mc_error;
9990 /** Copy environment as-is. */
9992 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
9994 MDB_txn *txn = NULL;
9995 mdb_mutexref_t wmutex = NULL;
9997 mdb_size_t wsize, w3;
10001 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
10005 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
10008 /* Do the lock/unlock of the reader mutex before starting the
10009 * write txn. Otherwise other read txns could block writers.
10011 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
10015 if (env->me_txns) {
10016 /* We must start the actual read txn after blocking writers */
10017 mdb_txn_end(txn, MDB_END_RESET_TMP);
10019 /* Temporarily block writers until we snapshot the meta pages */
10020 wmutex = env->me_wmutex;
10021 if (LOCK_MUTEX(rc, env, wmutex))
10024 rc = mdb_txn_renew0(txn);
10026 UNLOCK_MUTEX(wmutex);
10031 wsize = env->me_psize * NUM_METAS;
10035 DO_WRITE(rc, fd, ptr, w2, len);
10039 } else if (len > 0) {
10045 /* Non-blocking or async handles are not supported */
10051 UNLOCK_MUTEX(wmutex);
10056 w3 = txn->mt_next_pgno * env->me_psize;
10058 mdb_size_t fsize = 0;
10059 if ((rc = mdb_fsize(env->me_fd, &fsize)))
10064 wsize = w3 - wsize;
10065 while (wsize > 0) {
10066 if (wsize > MAX_WRITE)
10070 DO_WRITE(rc, fd, ptr, w2, len);
10074 } else if (len > 0) {
10086 mdb_txn_abort(txn);
10091 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
10093 if (flags & MDB_CP_COMPACT)
10094 return mdb_env_copyfd1(env, fd);
10096 return mdb_env_copyfd0(env, fd);
10100 mdb_env_copyfd(MDB_env *env, HANDLE fd)
10102 return mdb_env_copyfd2(env, fd, 0);
10106 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
10110 HANDLE newfd = INVALID_HANDLE_VALUE;
10115 if (env->me_flags & MDB_NOSUBDIR) {
10116 lpath = (char *)path;
10118 len = strlen(path);
10119 len += sizeof(DATANAME);
10120 lpath = malloc(len);
10123 sprintf(lpath, "%s" DATANAME, path);
10126 /* The destination path must exist, but the destination file must not.
10127 * We don't want the OS to cache the writes, since the source data is
10128 * already in the OS cache.
10131 rc = utf8_to_utf16(lpath, -1, &wpath, NULL);
10134 newfd = CreateFileW(wpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
10135 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
10138 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
10140 if (newfd == INVALID_HANDLE_VALUE) {
10145 if (env->me_psize >= env->me_os_psize) {
10147 /* Set O_DIRECT if the file system supports it */
10148 if ((rc = fcntl(newfd, F_GETFL)) != -1)
10149 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
10151 #ifdef F_NOCACHE /* __APPLE__ */
10152 rc = fcntl(newfd, F_NOCACHE, 1);
10160 rc = mdb_env_copyfd2(env, newfd, flags);
10163 if (!(env->me_flags & MDB_NOSUBDIR))
10165 if (newfd != INVALID_HANDLE_VALUE)
10166 if (close(newfd) < 0 && rc == MDB_SUCCESS)
10173 mdb_env_copy(MDB_env *env, const char *path)
10175 return mdb_env_copy2(env, path, 0);
10179 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
10181 if (flag & ~CHANGEABLE)
10184 env->me_flags |= flag;
10186 env->me_flags &= ~flag;
10187 return MDB_SUCCESS;
10191 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
10196 *arg = env->me_flags & (CHANGEABLE|CHANGELESS);
10197 return MDB_SUCCESS;
10201 mdb_env_set_userctx(MDB_env *env, void *ctx)
10205 env->me_userctx = ctx;
10206 return MDB_SUCCESS;
10210 mdb_env_get_userctx(MDB_env *env)
10212 return env ? env->me_userctx : NULL;
10216 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
10221 env->me_assert_func = func;
10223 return MDB_SUCCESS;
10227 mdb_env_get_path(MDB_env *env, const char **arg)
10232 *arg = env->me_path;
10233 return MDB_SUCCESS;
10237 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
10243 return MDB_SUCCESS;
10246 /** Common code for #mdb_stat() and #mdb_env_stat().
10247 * @param[in] env the environment to operate in.
10248 * @param[in] db the #MDB_db record containing the stats to return.
10249 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
10250 * @return 0, this function always succeeds.
10253 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
10255 arg->ms_psize = env->me_psize;
10256 arg->ms_depth = db->md_depth;
10257 arg->ms_branch_pages = db->md_branch_pages;
10258 arg->ms_leaf_pages = db->md_leaf_pages;
10259 arg->ms_overflow_pages = db->md_overflow_pages;
10260 arg->ms_entries = db->md_entries;
10262 return MDB_SUCCESS;
10266 mdb_env_stat(MDB_env *env, MDB_stat *arg)
10270 if (env == NULL || arg == NULL)
10273 meta = mdb_env_pick_meta(env);
10275 return mdb_stat0(env, &meta->mm_dbs[MAIN_DBI], arg);
10279 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
10283 if (env == NULL || arg == NULL)
10286 meta = mdb_env_pick_meta(env);
10287 arg->me_mapaddr = meta->mm_address;
10288 arg->me_last_pgno = meta->mm_last_pg;
10289 arg->me_last_txnid = meta->mm_txnid;
10291 arg->me_mapsize = env->me_mapsize;
10292 arg->me_maxreaders = env->me_maxreaders;
10293 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : 0;
10294 return MDB_SUCCESS;
10297 /** Set the default comparison functions for a database.
10298 * Called immediately after a database is opened to set the defaults.
10299 * The user can then override them with #mdb_set_compare() or
10300 * #mdb_set_dupsort().
10301 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
10302 * @param[in] dbi A database handle returned by #mdb_dbi_open()
10305 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
10307 uint16_t f = txn->mt_dbs[dbi].md_flags;
10309 txn->mt_dbxs[dbi].md_cmp =
10310 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
10311 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
10313 txn->mt_dbxs[dbi].md_dcmp =
10314 !(f & MDB_DUPSORT) ? 0 :
10315 ((f & MDB_INTEGERDUP)
10316 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
10317 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
10320 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
10326 int rc, dbflag, exact;
10327 unsigned int unused = 0, seq;
10331 if (flags & ~VALID_FLAGS)
10333 if (txn->mt_flags & MDB_TXN_BLOCKED)
10334 return MDB_BAD_TXN;
10339 if (flags & PERSISTENT_FLAGS) {
10340 uint16_t f2 = flags & PERSISTENT_FLAGS;
10341 /* make sure flag changes get committed */
10342 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
10343 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
10344 txn->mt_flags |= MDB_TXN_DIRTY;
10347 mdb_default_cmp(txn, MAIN_DBI);
10348 return MDB_SUCCESS;
10351 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
10352 mdb_default_cmp(txn, MAIN_DBI);
10355 /* Is the DB already open? */
10356 len = strlen(name);
10357 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
10358 if (!txn->mt_dbxs[i].md_name.mv_size) {
10359 /* Remember this free slot */
10360 if (!unused) unused = i;
10363 if (len == txn->mt_dbxs[i].md_name.mv_size &&
10364 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
10366 return MDB_SUCCESS;
10370 /* If no free slot and max hit, fail */
10371 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
10372 return MDB_DBS_FULL;
10374 /* Cannot mix named databases with some mainDB flags */
10375 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
10376 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
10378 /* Find the DB info */
10379 dbflag = DB_NEW|DB_VALID|DB_USRVALID;
10382 key.mv_data = (void *)name;
10383 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
10384 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
10385 if (rc == MDB_SUCCESS) {
10386 /* make sure this is actually a DB */
10387 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
10388 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
10389 return MDB_INCOMPATIBLE;
10390 } else if (! (rc == MDB_NOTFOUND && (flags & MDB_CREATE))) {
10394 /* Done here so we cannot fail after creating a new DB */
10395 if ((namedup = strdup(name)) == NULL)
10399 /* MDB_NOTFOUND and MDB_CREATE: Create new DB */
10400 data.mv_size = sizeof(MDB_db);
10401 data.mv_data = &dummy;
10402 memset(&dummy, 0, sizeof(dummy));
10403 dummy.md_root = P_INVALID;
10404 dummy.md_flags = flags & PERSISTENT_FLAGS;
10405 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
10406 dbflag |= DB_DIRTY;
10412 /* Got info, register DBI in this txn */
10413 unsigned int slot = unused ? unused : txn->mt_numdbs;
10414 txn->mt_dbxs[slot].md_name.mv_data = namedup;
10415 txn->mt_dbxs[slot].md_name.mv_size = len;
10416 txn->mt_dbxs[slot].md_rel = NULL;
10417 txn->mt_dbflags[slot] = dbflag;
10418 /* txn-> and env-> are the same in read txns, use
10419 * tmp variable to avoid undefined assignment
10421 seq = ++txn->mt_env->me_dbiseqs[slot];
10422 txn->mt_dbiseqs[slot] = seq;
10424 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
10426 mdb_default_cmp(txn, slot);
10436 mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
10438 if (!arg || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
10441 if (txn->mt_flags & MDB_TXN_BLOCKED)
10442 return MDB_BAD_TXN;
10444 if (txn->mt_dbflags[dbi] & DB_STALE) {
10447 /* Stale, must read the DB's root. cursor_init does it for us. */
10448 mdb_cursor_init(&mc, txn, dbi, &mx);
10450 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
10453 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
10456 if (dbi < CORE_DBS || dbi >= env->me_maxdbs)
10458 ptr = env->me_dbxs[dbi].md_name.mv_data;
10459 /* If there was no name, this was already closed */
10461 env->me_dbxs[dbi].md_name.mv_data = NULL;
10462 env->me_dbxs[dbi].md_name.mv_size = 0;
10463 env->me_dbflags[dbi] = 0;
10464 env->me_dbiseqs[dbi]++;
10469 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
10471 /* We could return the flags for the FREE_DBI too but what's the point? */
10472 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10474 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
10475 return MDB_SUCCESS;
10478 /** Add all the DB's pages to the free list.
10479 * @param[in] mc Cursor on the DB to free.
10480 * @param[in] subs non-Zero to check for sub-DBs in this DB.
10481 * @return 0 on success, non-zero on failure.
10484 mdb_drop0(MDB_cursor *mc, int subs)
10488 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
10489 if (rc == MDB_SUCCESS) {
10490 MDB_txn *txn = mc->mc_txn;
10495 /* DUPSORT sub-DBs have no ovpages/DBs. Omit scanning leaves.
10496 * This also avoids any P_LEAF2 pages, which have no nodes.
10497 * Also if the DB doesn't have sub-DBs and has no overflow
10498 * pages, omit scanning leaves.
10500 if ((mc->mc_flags & C_SUB) ||
10501 (!subs && !mc->mc_db->md_overflow_pages))
10502 mdb_cursor_pop(mc);
10504 mdb_cursor_copy(mc, &mx);
10506 /* bump refcount for mx's pages */
10507 for (i=0; i<mc->mc_snum; i++)
10508 mdb_page_get(&mx, mc->mc_pg[i]->mp_pgno, &mx.mc_pg[i], NULL);
10510 while (mc->mc_snum > 0) {
10511 MDB_page *mp = mc->mc_pg[mc->mc_top];
10512 unsigned n = NUMKEYS(mp);
10514 for (i=0; i<n; i++) {
10515 ni = NODEPTR(mp, i);
10516 if (ni->mn_flags & F_BIGDATA) {
10519 memcpy(&pg, NODEDATA(ni), sizeof(pg));
10520 rc = mdb_page_get(mc, pg, &omp, NULL);
10523 mdb_cassert(mc, IS_OVERFLOW(omp));
10524 rc = mdb_midl_append_range(&txn->mt_free_pgs,
10525 pg, omp->mp_pages);
10528 mc->mc_db->md_overflow_pages -= omp->mp_pages;
10529 if (!mc->mc_db->md_overflow_pages && !subs)
10531 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
10532 mdb_xcursor_init1(mc, ni);
10533 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
10538 if (!subs && !mc->mc_db->md_overflow_pages)
10541 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
10543 for (i=0; i<n; i++) {
10545 ni = NODEPTR(mp, i);
10548 mdb_midl_xappend(txn->mt_free_pgs, pg);
10553 mc->mc_ki[mc->mc_top] = i;
10554 rc = mdb_cursor_sibling(mc, 1);
10556 if (rc != MDB_NOTFOUND)
10558 /* no more siblings, go back to beginning
10559 * of previous level.
10562 mdb_cursor_pop(mc);
10564 for (i=1; i<mc->mc_snum; i++) {
10566 mc->mc_pg[i] = mx.mc_pg[i];
10571 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
10574 txn->mt_flags |= MDB_TXN_ERROR;
10575 /* drop refcount for mx's pages */
10576 MDB_CURSOR_UNREF(&mx, 0);
10577 } else if (rc == MDB_NOTFOUND) {
10580 mc->mc_flags &= ~C_INITIALIZED;
10584 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
10586 MDB_cursor *mc, *m2;
10589 if ((unsigned)del > 1 || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10592 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
10595 if (TXN_DBI_CHANGED(txn, dbi))
10596 return MDB_BAD_DBI;
10598 rc = mdb_cursor_open(txn, dbi, &mc);
10602 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
10603 /* Invalidate the dropped DB's cursors */
10604 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
10605 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
10609 /* Can't delete the main DB */
10610 if (del && dbi >= CORE_DBS) {
10611 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, F_SUBDATA);
10613 txn->mt_dbflags[dbi] = DB_STALE;
10614 mdb_dbi_close(txn->mt_env, dbi);
10616 txn->mt_flags |= MDB_TXN_ERROR;
10619 /* reset the DB record, mark it dirty */
10620 txn->mt_dbflags[dbi] |= DB_DIRTY;
10621 txn->mt_dbs[dbi].md_depth = 0;
10622 txn->mt_dbs[dbi].md_branch_pages = 0;
10623 txn->mt_dbs[dbi].md_leaf_pages = 0;
10624 txn->mt_dbs[dbi].md_overflow_pages = 0;
10625 txn->mt_dbs[dbi].md_entries = 0;
10626 txn->mt_dbs[dbi].md_root = P_INVALID;
10628 txn->mt_flags |= MDB_TXN_DIRTY;
10631 mdb_cursor_close(mc);
10635 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
10637 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10640 txn->mt_dbxs[dbi].md_cmp = cmp;
10641 return MDB_SUCCESS;
10644 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
10646 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10649 txn->mt_dbxs[dbi].md_dcmp = cmp;
10650 return MDB_SUCCESS;
10653 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
10655 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10658 txn->mt_dbxs[dbi].md_rel = rel;
10659 return MDB_SUCCESS;
10662 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
10664 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10667 txn->mt_dbxs[dbi].md_relctx = ctx;
10668 return MDB_SUCCESS;
10672 mdb_env_get_maxkeysize(MDB_env *env)
10674 return ENV_MAXKEY(env);
10678 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
10680 unsigned int i, rdrs;
10683 int rc = 0, first = 1;
10687 if (!env->me_txns) {
10688 return func("(no reader locks)\n", ctx);
10690 rdrs = env->me_txns->mti_numreaders;
10691 mr = env->me_txns->mti_readers;
10692 for (i=0; i<rdrs; i++) {
10693 if (mr[i].mr_pid) {
10694 txnid_t txnid = mr[i].mr_txnid;
10695 sprintf(buf, txnid == (txnid_t)-1 ?
10696 "%10d %"Z"x -\n" : "%10d %"Z"x %"Yu"\n",
10697 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
10700 rc = func(" pid thread txnid\n", ctx);
10704 rc = func(buf, ctx);
10710 rc = func("(no active readers)\n", ctx);
10715 /** Insert pid into list if not already present.
10716 * return -1 if already present.
10719 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
10721 /* binary search of pid in list */
10723 unsigned cursor = 1;
10725 unsigned n = ids[0];
10728 unsigned pivot = n >> 1;
10729 cursor = base + pivot + 1;
10730 val = pid - ids[cursor];
10735 } else if ( val > 0 ) {
10740 /* found, so it's a duplicate */
10749 for (n = ids[0]; n > cursor; n--)
10756 mdb_reader_check(MDB_env *env, int *dead)
10762 return env->me_txns ? mdb_reader_check0(env, 0, dead) : MDB_SUCCESS;
10765 /** As #mdb_reader_check(). rlocked = <caller locked the reader mutex>. */
10767 mdb_reader_check0(MDB_env *env, int rlocked, int *dead)
10769 mdb_mutexref_t rmutex = rlocked ? NULL : env->me_rmutex;
10770 unsigned int i, j, rdrs;
10772 MDB_PID_T *pids, pid;
10773 int rc = MDB_SUCCESS, count = 0;
10775 rdrs = env->me_txns->mti_numreaders;
10776 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
10780 mr = env->me_txns->mti_readers;
10781 for (i=0; i<rdrs; i++) {
10782 pid = mr[i].mr_pid;
10783 if (pid && pid != env->me_pid) {
10784 if (mdb_pid_insert(pids, pid) == 0) {
10785 if (!mdb_reader_pid(env, Pidcheck, pid)) {
10786 /* Stale reader found */
10789 if ((rc = LOCK_MUTEX0(rmutex)) != 0) {
10790 if ((rc = mdb_mutex_failed(env, rmutex, rc)))
10792 rdrs = 0; /* the above checked all readers */
10794 /* Recheck, a new process may have reused pid */
10795 if (mdb_reader_pid(env, Pidcheck, pid))
10799 for (; j<rdrs; j++)
10800 if (mr[j].mr_pid == pid) {
10801 DPRINTF(("clear stale reader pid %u txn %"Yd,
10802 (unsigned) pid, mr[j].mr_txnid));
10807 UNLOCK_MUTEX(rmutex);
10818 #ifdef MDB_ROBUST_SUPPORTED
10819 /** Handle #LOCK_MUTEX0() failure.
10820 * Try to repair the lock file if the mutex owner died.
10821 * @param[in] env the environment handle
10822 * @param[in] mutex LOCK_MUTEX0() mutex
10823 * @param[in] rc LOCK_MUTEX0() error (nonzero)
10824 * @return 0 on success with the mutex locked, or an error code on failure.
10827 mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc)
10832 if (rc == MDB_OWNERDEAD) {
10833 /* We own the mutex. Clean up after dead previous owner. */
10835 rlocked = (mutex == env->me_rmutex);
10837 /* Keep mti_txnid updated, otherwise next writer can
10838 * overwrite data which latest meta page refers to.
10840 meta = mdb_env_pick_meta(env);
10841 env->me_txns->mti_txnid = meta->mm_txnid;
10842 /* env is hosed if the dead thread was ours */
10844 env->me_flags |= MDB_FATAL_ERROR;
10845 env->me_txn = NULL;
10849 DPRINTF(("%cmutex owner died, %s", (rlocked ? 'r' : 'w'),
10850 (rc ? "this process' env is hosed" : "recovering")));
10851 rc2 = mdb_reader_check0(env, rlocked, NULL);
10853 rc2 = mdb_mutex_consistent(mutex);
10854 if (rc || (rc = rc2)) {
10855 DPRINTF(("LOCK_MUTEX recovery failed, %s", mdb_strerror(rc)));
10856 UNLOCK_MUTEX(mutex);
10862 DPRINTF(("LOCK_MUTEX failed, %s", mdb_strerror(rc)));
10867 #endif /* MDB_ROBUST_SUPPORTED */
10870 #if defined(_WIN32)
10871 static int utf8_to_utf16(const char *src, int srcsize, wchar_t **dst, int *dstsize)
10875 need = MultiByteToWideChar(CP_UTF8, 0, src, srcsize, NULL, 0);
10876 if (need == 0xFFFD)
10880 result = malloc(sizeof(wchar_t) * need);
10883 MultiByteToWideChar(CP_UTF8, 0, src, srcsize, result, need);
10889 #endif /* defined(_WIN32) */