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. The page type depends on #mp_flags.
873 * #P_BRANCH and #P_LEAF pages have unsorted '#MDB_node's at the end, with
874 * sorted #mp_ptrs[] entries referring to them. Exception: #P_LEAF2 pages
875 * omit mp_ptrs and pack sorted #MDB_DUPFIXED values after the page header.
877 * #P_OVERFLOW records occupy one or more contiguous pages where only the
878 * first has a page header. They hold the real data of #F_BIGDATA nodes.
880 * #P_SUBP sub-pages are small leaf "pages" with duplicate data.
881 * A node with flag #F_DUPDATA but not #F_SUBDATA contains a sub-page.
882 * (Duplicate data can also go in sub-databases, which use normal pages.)
884 * #P_META pages contain #MDB_meta, the start point of an LMDB snapshot.
886 * Each non-metapage up to #MDB_meta.%mm_last_pg is reachable exactly once
887 * in the snapshot: Either used by a database or listed in a freeDB record.
889 typedef struct MDB_page {
890 #define mp_pgno mp_p.p_pgno
891 #define mp_next mp_p.p_next
893 pgno_t p_pgno; /**< page number */
894 struct MDB_page *p_next; /**< for in-memory list of freed pages */
896 uint16_t mp_pad; /**< key size if this is a LEAF2 page */
897 /** @defgroup mdb_page Page Flags
899 * Flags for the page headers.
902 #define P_BRANCH 0x01 /**< branch page */
903 #define P_LEAF 0x02 /**< leaf page */
904 #define P_OVERFLOW 0x04 /**< overflow page */
905 #define P_META 0x08 /**< meta page */
906 #define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
907 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
908 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
909 #define P_LOOSE 0x4000 /**< page was dirtied then freed, can be reused */
910 #define P_KEEP 0x8000 /**< leave this page alone during spill */
912 uint16_t mp_flags; /**< @ref mdb_page */
913 #define mp_lower mp_pb.pb.pb_lower
914 #define mp_upper mp_pb.pb.pb_upper
915 #define mp_pages mp_pb.pb_pages
918 indx_t pb_lower; /**< lower bound of free space */
919 indx_t pb_upper; /**< upper bound of free space */
921 uint32_t pb_pages; /**< number of overflow pages */
923 indx_t mp_ptrs[1]; /**< dynamic size */
926 /** Size of the page header, excluding dynamic data at the end */
927 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
929 /** Address of first usable data byte in a page, after the header */
930 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
932 /** ITS#7713, change PAGEBASE to handle 65536 byte pages */
933 #define PAGEBASE ((MDB_DEVEL) ? PAGEHDRSZ : 0)
935 /** Number of nodes on a page */
936 #define NUMKEYS(p) (((p)->mp_lower - (PAGEHDRSZ-PAGEBASE)) >> 1)
938 /** The amount of space remaining in the page */
939 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
941 /** The percentage of space used in the page, in tenths of a percent. */
942 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
943 ((env)->me_psize - PAGEHDRSZ))
944 /** The minimum page fill factor, in tenths of a percent.
945 * Pages emptier than this are candidates for merging.
947 #define FILL_THRESHOLD 250
949 /** Test if a page is a leaf page */
950 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
951 /** Test if a page is a LEAF2 page */
952 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
953 /** Test if a page is a branch page */
954 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
955 /** Test if a page is an overflow page */
956 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
957 /** Test if a page is a sub page */
958 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
960 /** The number of overflow pages needed to store the given size. */
961 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
963 /** Link in #MDB_txn.%mt_loose_pgs list.
964 * Kept outside the page header, which is needed when reusing the page.
966 #define NEXT_LOOSE_PAGE(p) (*(MDB_page **)((p) + 2))
968 /** Header for a single key/data pair within a page.
969 * Used in pages of type #P_BRANCH and #P_LEAF without #P_LEAF2.
970 * We guarantee 2-byte alignment for 'MDB_node's.
972 typedef struct MDB_node {
973 /** lo and hi are used for data size on leaf nodes and for
974 * child pgno on branch nodes. On 64 bit platforms, flags
975 * is also used for pgno. (Branch nodes have no flags).
976 * They are in host byte order in case that lets some
977 * accesses be optimized into a 32-bit word access.
979 #if BYTE_ORDER == LITTLE_ENDIAN
980 unsigned short mn_lo, mn_hi; /**< part of data size or pgno */
982 unsigned short mn_hi, mn_lo;
984 /** @defgroup mdb_node Node Flags
986 * Flags for node headers.
989 #define F_BIGDATA 0x01 /**< data put on overflow page */
990 #define F_SUBDATA 0x02 /**< data is a sub-database */
991 #define F_DUPDATA 0x04 /**< data has duplicates */
993 /** valid flags for #mdb_node_add() */
994 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
997 unsigned short mn_flags; /**< @ref mdb_node */
998 unsigned short mn_ksize; /**< key size */
999 char mn_data[1]; /**< key and data are appended here */
1002 /** Size of the node header, excluding dynamic data at the end */
1003 #define NODESIZE offsetof(MDB_node, mn_data)
1005 /** Bit position of top word in page number, for shifting mn_flags */
1006 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
1008 /** Size of a node in a branch page with a given key.
1009 * This is just the node header plus the key, there is no data.
1011 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
1013 /** Size of a node in a leaf page with a given key and data.
1014 * This is node header plus key plus data size.
1016 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
1018 /** Address of node \b i in page \b p */
1019 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i] + PAGEBASE))
1021 /** Address of the key for the node */
1022 #define NODEKEY(node) (void *)((node)->mn_data)
1024 /** Address of the data for a node */
1025 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
1027 /** Get the page number pointed to by a branch node */
1028 #define NODEPGNO(node) \
1029 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
1030 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
1031 /** Set the page number in a branch node */
1032 #define SETPGNO(node,pgno) do { \
1033 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
1034 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
1036 /** Get the size of the data in a leaf node */
1037 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
1038 /** Set the size of the data for a leaf node */
1039 #define SETDSZ(node,size) do { \
1040 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
1041 /** The size of a key in a node */
1042 #define NODEKSZ(node) ((node)->mn_ksize)
1044 /** Copy a page number from src to dst */
1045 #ifdef MISALIGNED_OK
1046 #define COPY_PGNO(dst,src) dst = src
1048 #if MDB_SIZE_MAX > 0xffffffffU
1049 #define COPY_PGNO(dst,src) do { \
1050 unsigned short *s, *d; \
1051 s = (unsigned short *)&(src); \
1052 d = (unsigned short *)&(dst); \
1059 #define COPY_PGNO(dst,src) do { \
1060 unsigned short *s, *d; \
1061 s = (unsigned short *)&(src); \
1062 d = (unsigned short *)&(dst); \
1068 /** The address of a key in a LEAF2 page.
1069 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
1070 * There are no node headers, keys are stored contiguously.
1072 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
1074 /** Set the \b node's key into \b keyptr, if requested. */
1075 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
1076 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
1078 /** Set the \b node's key into \b key. */
1079 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
1081 /** Information about a single database in the environment. */
1082 typedef struct MDB_db {
1083 uint32_t md_pad; /**< also ksize for LEAF2 pages */
1084 uint16_t md_flags; /**< @ref mdb_dbi_open */
1085 uint16_t md_depth; /**< depth of this tree */
1086 pgno_t md_branch_pages; /**< number of internal pages */
1087 pgno_t md_leaf_pages; /**< number of leaf pages */
1088 pgno_t md_overflow_pages; /**< number of overflow pages */
1089 mdb_size_t md_entries; /**< number of data items */
1090 pgno_t md_root; /**< the root page of this tree */
1093 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
1094 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
1095 /** #mdb_dbi_open() flags */
1096 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
1097 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
1099 /** Handle for the DB used to track free pages. */
1101 /** Handle for the default DB. */
1103 /** Number of DBs in metapage (free and main) - also hardcoded elsewhere */
1106 /** Number of meta pages - also hardcoded elsewhere */
1109 /** Meta page content.
1110 * A meta page is the start point for accessing a database snapshot.
1111 * Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
1113 typedef struct MDB_meta {
1114 /** Stamp identifying this as an LMDB file. It must be set
1117 /** Version number of this file. Must be set to #MDB_DATA_VERSION. */
1118 uint32_t mm_version;
1120 union { /* always zero since we don't support fixed mapping in MDB_VL32 */
1124 #define mm_address mm_un.mmun_address
1126 void *mm_address; /**< address for fixed mapping */
1128 pgno_t mm_mapsize; /**< size of mmap region */
1129 MDB_db mm_dbs[CORE_DBS]; /**< first is free space, 2nd is main db */
1130 /** The size of pages used in this DB */
1131 #define mm_psize mm_dbs[FREE_DBI].md_pad
1132 /** Any persistent environment flags. @ref mdb_env */
1133 #define mm_flags mm_dbs[FREE_DBI].md_flags
1134 /** Last used page in the datafile.
1135 * Actually the file may be shorter if the freeDB lists the final pages.
1138 volatile txnid_t mm_txnid; /**< txnid that committed this page */
1141 /** Buffer for a stack-allocated meta page.
1142 * The members define size and alignment, and silence type
1143 * aliasing warnings. They are not used directly; that could
1144 * mean incorrectly using several union members in parallel.
1146 typedef union MDB_metabuf {
1149 char mm_pad[PAGEHDRSZ];
1154 /** Auxiliary DB info.
1155 * The information here is mostly static/read-only. There is
1156 * only a single copy of this record in the environment.
1158 typedef struct MDB_dbx {
1159 MDB_val md_name; /**< name of the database */
1160 MDB_cmp_func *md_cmp; /**< function for comparing keys */
1161 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
1162 MDB_rel_func *md_rel; /**< user relocate function */
1163 void *md_relctx; /**< user-provided context for md_rel */
1166 /** A database transaction.
1167 * Every operation requires a transaction handle.
1170 MDB_txn *mt_parent; /**< parent of a nested txn */
1171 /** Nested txn under this txn, set together with flag #MDB_TXN_HAS_CHILD */
1173 pgno_t mt_next_pgno; /**< next unallocated page */
1175 pgno_t mt_last_pgno; /**< last written page */
1177 /** The ID of this transaction. IDs are integers incrementing from 1.
1178 * Only committed write transactions increment the ID. If a transaction
1179 * aborts, the ID may be re-used by the next writer.
1182 MDB_env *mt_env; /**< the DB environment */
1183 /** The list of pages that became unused during this transaction.
1185 MDB_IDL mt_free_pgs;
1186 /** The list of loose pages that became unused and may be reused
1187 * in this transaction, linked through #NEXT_LOOSE_PAGE(page).
1189 MDB_page *mt_loose_pgs;
1190 /** Number of loose pages (#mt_loose_pgs) */
1192 /** The sorted list of dirty pages we temporarily wrote to disk
1193 * because the dirty list was full. page numbers in here are
1194 * shifted left by 1, deleted slots have the LSB set.
1196 MDB_IDL mt_spill_pgs;
1198 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
1199 MDB_ID2L dirty_list;
1200 /** For read txns: This thread/txn's reader table slot, or NULL. */
1203 /** Array of records for each DB known in the environment. */
1205 /** Array of MDB_db records for each known DB */
1207 /** Array of sequence numbers for each DB handle */
1208 unsigned int *mt_dbiseqs;
1209 /** @defgroup mt_dbflag Transaction DB Flags
1213 #define DB_DIRTY 0x01 /**< DB was modified or is DUPSORT data */
1214 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
1215 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
1216 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
1217 #define DB_USRVALID 0x10 /**< As #DB_VALID, but not set for #FREE_DBI */
1219 /** In write txns, array of cursors for each DB */
1220 MDB_cursor **mt_cursors;
1221 /** Array of flags for each DB */
1222 unsigned char *mt_dbflags;
1224 /** List of read-only pages (actually chunks) */
1226 /** We map chunks of 16 pages. Even though Windows uses 4KB pages, all
1227 * mappings must begin on 64KB boundaries. So we round off all pgnos to
1228 * a chunk boundary. We do the same on Linux for symmetry, and also to
1229 * reduce the frequency of mmap/munmap calls.
1231 #define MDB_RPAGE_CHUNK 16
1232 #define MDB_TRPAGE_SIZE 4096 /**< size of #mt_rpages array of chunks */
1233 #define MDB_TRPAGE_MAX (MDB_TRPAGE_SIZE-1) /**< maximum chunk index */
1234 unsigned int mt_rpcheck; /**< threshold for reclaiming unref'd chunks */
1236 /** Number of DB records in use, or 0 when the txn is finished.
1237 * This number only ever increments until the txn finishes; we
1238 * don't decrement it when individual DB handles are closed.
1242 /** @defgroup mdb_txn Transaction Flags
1246 /** #mdb_txn_begin() flags */
1247 #define MDB_TXN_BEGIN_FLAGS (MDB_NOMETASYNC|MDB_NOSYNC|MDB_RDONLY)
1248 #define MDB_TXN_NOMETASYNC MDB_NOMETASYNC /**< don't sync meta for this txn on commit */
1249 #define MDB_TXN_NOSYNC MDB_NOSYNC /**< don't sync this txn on commit */
1250 #define MDB_TXN_RDONLY MDB_RDONLY /**< read-only transaction */
1251 /* internal txn flags */
1252 #define MDB_TXN_WRITEMAP MDB_WRITEMAP /**< copy of #MDB_env flag in writers */
1253 #define MDB_TXN_FINISHED 0x01 /**< txn is finished or never began */
1254 #define MDB_TXN_ERROR 0x02 /**< txn is unusable after an error */
1255 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
1256 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
1257 #define MDB_TXN_HAS_CHILD 0x10 /**< txn has an #MDB_txn.%mt_child */
1258 /** most operations on the txn are currently illegal */
1259 #define MDB_TXN_BLOCKED (MDB_TXN_FINISHED|MDB_TXN_ERROR|MDB_TXN_HAS_CHILD)
1261 unsigned int mt_flags; /**< @ref mdb_txn */
1262 /** #dirty_list room: Array size - \#dirty pages visible to this txn.
1263 * Includes ancestor txns' dirty pages not hidden by other txns'
1264 * dirty/spilled pages. Thus commit(nested txn) has room to merge
1265 * dirty_list into mt_parent after freeing hidden mt_parent pages.
1267 unsigned int mt_dirty_room;
1270 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
1271 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
1272 * raise this on a 64 bit machine.
1274 #define CURSOR_STACK 32
1278 /** Cursors are used for all DB operations.
1279 * A cursor holds a path of (page pointer, key index) from the DB
1280 * root to a position in the DB, plus other state. #MDB_DUPSORT
1281 * cursors include an xcursor to the current data item. Write txns
1282 * track their cursors and keep them up to date when data moves.
1283 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
1284 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
1287 /** Next cursor on this DB in this txn */
1288 MDB_cursor *mc_next;
1289 /** Backup of the original cursor if this cursor is a shadow */
1290 MDB_cursor *mc_backup;
1291 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
1292 struct MDB_xcursor *mc_xcursor;
1293 /** The transaction that owns this cursor */
1295 /** The database handle this cursor operates on */
1297 /** The database record for this cursor */
1299 /** The database auxiliary record for this cursor */
1301 /** The @ref mt_dbflag for this database */
1302 unsigned char *mc_dbflag;
1303 unsigned short mc_snum; /**< number of pushed pages */
1304 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
1305 /** @defgroup mdb_cursor Cursor Flags
1307 * Cursor state flags.
1310 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
1311 #define C_EOF 0x02 /**< No more data */
1312 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
1313 #define C_DEL 0x08 /**< last op was a cursor_del */
1314 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
1315 #define C_WRITEMAP MDB_TXN_WRITEMAP /**< Copy of txn flag */
1316 /** Read-only cursor into the txn's original snapshot in the map.
1317 * Set for read-only txns, and in #mdb_page_alloc() for #FREE_DBI when
1318 * #MDB_DEVEL & 2. Only implements code which is necessary for this.
1320 #define C_ORIG_RDONLY MDB_TXN_RDONLY
1322 unsigned int mc_flags; /**< @ref mdb_cursor */
1323 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
1324 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
1326 MDB_page *mc_ovpg; /**< a referenced overflow page */
1327 # define MC_OVPG(mc) ((mc)->mc_ovpg)
1328 # define MC_SET_OVPG(mc, pg) ((mc)->mc_ovpg = (pg))
1330 # define MC_OVPG(mc) ((MDB_page *)0)
1331 # define MC_SET_OVPG(mc, pg) ((void)0)
1335 /** Context for sorted-dup records.
1336 * We could have gone to a fully recursive design, with arbitrarily
1337 * deep nesting of sub-databases. But for now we only handle these
1338 * levels - main DB, optional sub-DB, sorted-duplicate DB.
1340 typedef struct MDB_xcursor {
1341 /** A sub-cursor for traversing the Dup DB */
1342 MDB_cursor mx_cursor;
1343 /** The database record for this Dup DB */
1345 /** The auxiliary DB record for this Dup DB */
1347 /** The @ref mt_dbflag for this Dup DB */
1348 unsigned char mx_dbflag;
1351 /** State of FreeDB old pages, stored in the MDB_env */
1352 typedef struct MDB_pgstate {
1353 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1354 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1357 /** The database environment. */
1359 HANDLE me_fd; /**< The main data file */
1360 HANDLE me_lfd; /**< The lock file */
1361 HANDLE me_mfd; /**< just for writing the meta pages */
1362 #if defined(MDB_VL32) && defined(_WIN32)
1363 HANDLE me_fmh; /**< File Mapping handle */
1365 /** Failed to update the meta page. Probably an I/O error. */
1366 #define MDB_FATAL_ERROR 0x80000000U
1367 /** Some fields are initialized. */
1368 #define MDB_ENV_ACTIVE 0x20000000U
1369 /** me_txkey is set */
1370 #define MDB_ENV_TXKEY 0x10000000U
1371 /** fdatasync is unreliable */
1372 #define MDB_FSYNCONLY 0x08000000U
1373 uint32_t me_flags; /**< @ref mdb_env */
1374 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1375 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1376 unsigned int me_maxreaders; /**< size of the reader table */
1377 /** Max #MDB_txninfo.%mti_numreaders of interest to #mdb_env_close() */
1378 volatile int me_close_readers;
1379 MDB_dbi me_numdbs; /**< number of DBs opened */
1380 MDB_dbi me_maxdbs; /**< size of the DB table */
1381 MDB_PID_T me_pid; /**< process ID of this env */
1382 char *me_path; /**< path to the DB files */
1383 char *me_map; /**< the memory map of the data file */
1384 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1385 MDB_meta *me_metas[NUM_METAS]; /**< pointers to the two meta pages */
1386 void *me_pbuf; /**< scratch area for DUPSORT put() */
1387 MDB_txn *me_txn; /**< current write transaction */
1388 MDB_txn *me_txn0; /**< prealloc'd write transaction */
1389 mdb_size_t me_mapsize; /**< size of the data memory map */
1390 off_t me_size; /**< current file size */
1391 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1392 MDB_dbx *me_dbxs; /**< array of static DB info */
1393 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1394 unsigned int *me_dbiseqs; /**< array of dbi sequence numbers */
1395 pthread_key_t me_txkey; /**< thread-key for readers */
1396 txnid_t me_pgoldest; /**< ID of oldest reader last time we looked */
1397 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1398 # define me_pglast me_pgstate.mf_pglast
1399 # define me_pghead me_pgstate.mf_pghead
1400 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1401 /** IDL of pages that became unused in a write txn */
1402 MDB_IDL me_free_pgs;
1403 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1404 MDB_ID2L me_dirty_list;
1405 /** Max number of freelist items that can fit in a single overflow page */
1407 /** Max size of a node on a page */
1408 unsigned int me_nodemax;
1409 #if !(MDB_MAXKEYSIZE)
1410 unsigned int me_maxkey; /**< max size of a key */
1412 int me_live_reader; /**< have liveness lock in reader table */
1414 int me_pidquery; /**< Used in OpenProcess */
1416 #ifdef MDB_USE_POSIX_MUTEX /* Posix mutexes reside in shared mem */
1417 # define me_rmutex me_txns->mti_rmutex /**< Shared reader lock */
1418 # define me_wmutex me_txns->mti_wmutex /**< Shared writer lock */
1420 mdb_mutex_t me_rmutex;
1421 mdb_mutex_t me_wmutex;
1424 MDB_ID3L me_rpages; /**< like #mt_rpages, but global to env */
1425 pthread_mutex_t me_rpmutex; /**< control access to #me_rpages */
1426 #define MDB_ERPAGE_SIZE 16384
1427 #define MDB_ERPAGE_MAX (MDB_ERPAGE_SIZE-1)
1428 unsigned int me_rpcheck;
1430 void *me_userctx; /**< User-settable context */
1431 MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
1434 /** Nested transaction */
1435 typedef struct MDB_ntxn {
1436 MDB_txn mnt_txn; /**< the transaction */
1437 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1440 /** max number of pages to commit in one writev() call */
1441 #define MDB_COMMIT_PAGES 64
1442 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1443 #undef MDB_COMMIT_PAGES
1444 #define MDB_COMMIT_PAGES IOV_MAX
1447 /** max bytes to write in one call */
1448 #define MAX_WRITE (0x40000000U >> (sizeof(ssize_t) == 4))
1450 /** Check \b txn and \b dbi arguments to a function */
1451 #define TXN_DBI_EXIST(txn, dbi, validity) \
1452 ((txn) && (dbi)<(txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & (validity)))
1454 /** Check for misused \b dbi handles */
1455 #define TXN_DBI_CHANGED(txn, dbi) \
1456 ((txn)->mt_dbiseqs[dbi] != (txn)->mt_env->me_dbiseqs[dbi])
1458 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1459 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1460 static int mdb_page_touch(MDB_cursor *mc);
1462 #define MDB_END_NAMES {"committed", "empty-commit", "abort", "reset", \
1463 "reset-tmp", "fail-begin", "fail-beginchild"}
1465 /* mdb_txn_end operation number, for logging */
1466 MDB_END_COMMITTED, MDB_END_EMPTY_COMMIT, MDB_END_ABORT, MDB_END_RESET,
1467 MDB_END_RESET_TMP, MDB_END_FAIL_BEGIN, MDB_END_FAIL_BEGINCHILD
1469 #define MDB_END_OPMASK 0x0F /**< mask for #mdb_txn_end() operation number */
1470 #define MDB_END_UPDATE 0x10 /**< update env state (DBIs) */
1471 #define MDB_END_FREE 0x20 /**< free txn unless it is #MDB_env.%me_txn0 */
1472 #define MDB_END_SLOT MDB_NOTLS /**< release any reader slot if #MDB_NOTLS */
1473 static void mdb_txn_end(MDB_txn *txn, unsigned mode);
1475 static int mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **mp, int *lvl);
1476 static int mdb_page_search_root(MDB_cursor *mc,
1477 MDB_val *key, int modify);
1478 #define MDB_PS_MODIFY 1
1479 #define MDB_PS_ROOTONLY 2
1480 #define MDB_PS_FIRST 4
1481 #define MDB_PS_LAST 8
1482 static int mdb_page_search(MDB_cursor *mc,
1483 MDB_val *key, int flags);
1484 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1486 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1487 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1488 pgno_t newpgno, unsigned int nflags);
1490 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1491 static MDB_meta *mdb_env_pick_meta(const MDB_env *env);
1492 static int mdb_env_write_meta(MDB_txn *txn);
1493 #ifdef MDB_USE_POSIX_MUTEX /* Drop unused excl arg */
1494 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1496 static void mdb_env_close0(MDB_env *env, int excl);
1498 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1499 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1500 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1501 static void mdb_node_del(MDB_cursor *mc, int ksize);
1502 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1503 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft);
1504 static int mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data);
1505 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1506 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1508 static int mdb_rebalance(MDB_cursor *mc);
1509 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1511 static void mdb_cursor_pop(MDB_cursor *mc);
1512 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1514 static int mdb_cursor_del0(MDB_cursor *mc);
1515 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
1516 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1517 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1518 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1519 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1521 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1522 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1524 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1525 static void mdb_xcursor_init0(MDB_cursor *mc);
1526 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1527 static void mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int force);
1529 static int mdb_drop0(MDB_cursor *mc, int subs);
1530 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1531 static int mdb_reader_check0(MDB_env *env, int rlocked, int *dead);
1534 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1537 /** Compare two items pointing at '#mdb_size_t's of unknown alignment. */
1538 #ifdef MISALIGNED_OK
1539 # define mdb_cmp_clong mdb_cmp_long
1541 # define mdb_cmp_clong mdb_cmp_cint
1544 /** True if we need #mdb_cmp_clong() instead of \b cmp for #MDB_INTEGERDUP */
1545 #define NEED_CMP_CLONG(cmp, ksize) \
1546 (UINT_MAX < MDB_SIZE_MAX && \
1547 (cmp) == mdb_cmp_int && (ksize) == sizeof(mdb_size_t))
1550 static SECURITY_DESCRIPTOR mdb_null_sd;
1551 static SECURITY_ATTRIBUTES mdb_all_sa;
1552 static int mdb_sec_inited;
1554 static int utf8_to_utf16(const char *src, int srcsize, wchar_t **dst, int *dstsize);
1557 /** Return the library version info. */
1559 mdb_version(int *major, int *minor, int *patch)
1561 if (major) *major = MDB_VERSION_MAJOR;
1562 if (minor) *minor = MDB_VERSION_MINOR;
1563 if (patch) *patch = MDB_VERSION_PATCH;
1564 return MDB_VERSION_STRING;
1567 /** Table of descriptions for LMDB @ref errors */
1568 static char *const mdb_errstr[] = {
1569 "MDB_KEYEXIST: Key/data pair already exists",
1570 "MDB_NOTFOUND: No matching key/data pair found",
1571 "MDB_PAGE_NOTFOUND: Requested page not found",
1572 "MDB_CORRUPTED: Located page was wrong type",
1573 "MDB_PANIC: Update of meta page failed or environment had fatal error",
1574 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1575 "MDB_INVALID: File is not an LMDB file",
1576 "MDB_MAP_FULL: Environment mapsize limit reached",
1577 "MDB_DBS_FULL: Environment maxdbs limit reached",
1578 "MDB_READERS_FULL: Environment maxreaders limit reached",
1579 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1580 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1581 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1582 "MDB_PAGE_FULL: Internal error - page has no more space",
1583 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1584 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1585 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1586 "MDB_BAD_TXN: Transaction must abort, has a child, or is invalid",
1587 "MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
1588 "MDB_BAD_DBI: The specified DBI handle was closed/changed unexpectedly",
1589 "MDB_PROBLEM: Unexpected problem - txn should abort",
1593 mdb_strerror(int err)
1596 /** HACK: pad 4KB on stack over the buf. Return system msgs in buf.
1597 * This works as long as no function between the call to mdb_strerror
1598 * and the actual use of the message uses more than 4K of stack.
1600 #define MSGSIZE 1024
1601 #define PADSIZE 4096
1602 char buf[MSGSIZE+PADSIZE], *ptr = buf;
1606 return ("Successful return: 0");
1608 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1609 i = err - MDB_KEYEXIST;
1610 return mdb_errstr[i];
1614 /* These are the C-runtime error codes we use. The comment indicates
1615 * their numeric value, and the Win32 error they would correspond to
1616 * if the error actually came from a Win32 API. A major mess, we should
1617 * have used LMDB-specific error codes for everything.
1620 case ENOENT: /* 2, FILE_NOT_FOUND */
1621 case EIO: /* 5, ACCESS_DENIED */
1622 case ENOMEM: /* 12, INVALID_ACCESS */
1623 case EACCES: /* 13, INVALID_DATA */
1624 case EBUSY: /* 16, CURRENT_DIRECTORY */
1625 case EINVAL: /* 22, BAD_COMMAND */
1626 case ENOSPC: /* 28, OUT_OF_PAPER */
1627 return strerror(err);
1632 FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
1633 FORMAT_MESSAGE_IGNORE_INSERTS,
1634 NULL, err, 0, ptr, MSGSIZE, (va_list *)buf+MSGSIZE);
1637 return strerror(err);
1641 /** assert(3) variant in cursor context */
1642 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1643 /** assert(3) variant in transaction context */
1644 #define mdb_tassert(txn, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1645 /** assert(3) variant in environment context */
1646 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1649 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1650 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1653 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1654 const char *func, const char *file, int line)
1657 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1658 file, line, expr_txt, func);
1659 if (env->me_assert_func)
1660 env->me_assert_func(env, buf);
1661 fprintf(stderr, "%s\n", buf);
1665 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1669 /** Return the page number of \b mp which may be sub-page, for debug output */
1671 mdb_dbg_pgno(MDB_page *mp)
1674 COPY_PGNO(ret, mp->mp_pgno);
1678 /** Display a key in hexadecimal and return the address of the result.
1679 * @param[in] key the key to display
1680 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1681 * @return The key in hexadecimal form.
1684 mdb_dkey(MDB_val *key, char *buf)
1687 unsigned char *c = key->mv_data;
1693 if (key->mv_size > DKBUF_MAXKEYSIZE)
1694 return "MDB_MAXKEYSIZE";
1695 /* may want to make this a dynamic check: if the key is mostly
1696 * printable characters, print it as-is instead of converting to hex.
1700 for (i=0; i<key->mv_size; i++)
1701 ptr += sprintf(ptr, "%02x", *c++);
1703 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1709 mdb_leafnode_type(MDB_node *n)
1711 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1712 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1713 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1716 /** Display all the keys in the page. */
1718 mdb_page_list(MDB_page *mp)
1720 pgno_t pgno = mdb_dbg_pgno(mp);
1721 const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
1723 unsigned int i, nkeys, nsize, total = 0;
1727 switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1728 case P_BRANCH: type = "Branch page"; break;
1729 case P_LEAF: type = "Leaf page"; break;
1730 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1731 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1732 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1734 fprintf(stderr, "Overflow page %"Yu" pages %u%s\n",
1735 pgno, mp->mp_pages, state);
1738 fprintf(stderr, "Meta-page %"Yu" txnid %"Yu"\n",
1739 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1742 fprintf(stderr, "Bad page %"Yu" flags 0x%X\n", pgno, mp->mp_flags);
1746 nkeys = NUMKEYS(mp);
1747 fprintf(stderr, "%s %"Yu" numkeys %d%s\n", type, pgno, nkeys, state);
1749 for (i=0; i<nkeys; i++) {
1750 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1751 key.mv_size = nsize = mp->mp_pad;
1752 key.mv_data = LEAF2KEY(mp, i, nsize);
1754 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1757 node = NODEPTR(mp, i);
1758 key.mv_size = node->mn_ksize;
1759 key.mv_data = node->mn_data;
1760 nsize = NODESIZE + key.mv_size;
1761 if (IS_BRANCH(mp)) {
1762 fprintf(stderr, "key %d: page %"Yu", %s\n", i, NODEPGNO(node),
1766 if (F_ISSET(node->mn_flags, F_BIGDATA))
1767 nsize += sizeof(pgno_t);
1769 nsize += NODEDSZ(node);
1771 nsize += sizeof(indx_t);
1772 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1773 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1775 total = EVEN(total);
1777 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1778 IS_LEAF2(mp) ? PAGEHDRSZ : PAGEBASE + mp->mp_lower, total, SIZELEFT(mp));
1782 mdb_cursor_chk(MDB_cursor *mc)
1788 if (!mc->mc_snum || !(mc->mc_flags & C_INITIALIZED)) return;
1789 for (i=0; i<mc->mc_top; i++) {
1791 node = NODEPTR(mp, mc->mc_ki[i]);
1792 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1795 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1797 if (mc->mc_xcursor && (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
1798 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
1799 if (((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) &&
1800 mc->mc_xcursor->mx_cursor.mc_pg[0] != NODEDATA(node)) {
1808 /** Count all the pages in each DB and in the freelist
1809 * and make sure it matches the actual number of pages
1811 * All named DBs must be open for a correct count.
1813 static void mdb_audit(MDB_txn *txn)
1817 MDB_ID freecount, count;
1822 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1823 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1824 freecount += *(MDB_ID *)data.mv_data;
1825 mdb_tassert(txn, rc == MDB_NOTFOUND);
1828 for (i = 0; i<txn->mt_numdbs; i++) {
1830 if (!(txn->mt_dbflags[i] & DB_VALID))
1832 mdb_cursor_init(&mc, txn, i, &mx);
1833 if (txn->mt_dbs[i].md_root == P_INVALID)
1835 count += txn->mt_dbs[i].md_branch_pages +
1836 txn->mt_dbs[i].md_leaf_pages +
1837 txn->mt_dbs[i].md_overflow_pages;
1838 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1839 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1840 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
1843 mp = mc.mc_pg[mc.mc_top];
1844 for (j=0; j<NUMKEYS(mp); j++) {
1845 MDB_node *leaf = NODEPTR(mp, j);
1846 if (leaf->mn_flags & F_SUBDATA) {
1848 memcpy(&db, NODEDATA(leaf), sizeof(db));
1849 count += db.md_branch_pages + db.md_leaf_pages +
1850 db.md_overflow_pages;
1854 mdb_tassert(txn, rc == MDB_NOTFOUND);
1857 if (freecount + count + NUM_METAS != txn->mt_next_pgno) {
1858 fprintf(stderr, "audit: %"Yu" freecount: %"Yu" count: %"Yu" total: %"Yu" next_pgno: %"Yu"\n",
1859 txn->mt_txnid, freecount, count+NUM_METAS,
1860 freecount+count+NUM_METAS, txn->mt_next_pgno);
1866 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1868 return txn->mt_dbxs[dbi].md_cmp(a, b);
1872 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1874 MDB_cmp_func *dcmp = txn->mt_dbxs[dbi].md_dcmp;
1875 if (NEED_CMP_CLONG(dcmp, a->mv_size))
1876 dcmp = mdb_cmp_clong;
1880 /** Allocate memory for a page.
1881 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1884 mdb_page_malloc(MDB_txn *txn, unsigned num)
1886 MDB_env *env = txn->mt_env;
1887 MDB_page *ret = env->me_dpages;
1888 size_t psize = env->me_psize, sz = psize, off;
1889 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1890 * For a single page alloc, we init everything after the page header.
1891 * For multi-page, we init the final page; if the caller needed that
1892 * many pages they will be filling in at least up to the last page.
1896 VGMEMP_ALLOC(env, ret, sz);
1897 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1898 env->me_dpages = ret->mp_next;
1901 psize -= off = PAGEHDRSZ;
1906 if ((ret = malloc(sz)) != NULL) {
1907 VGMEMP_ALLOC(env, ret, sz);
1908 if (!(env->me_flags & MDB_NOMEMINIT)) {
1909 memset((char *)ret + off, 0, psize);
1913 txn->mt_flags |= MDB_TXN_ERROR;
1917 /** Free a single page.
1918 * Saves single pages to a list, for future reuse.
1919 * (This is not used for multi-page overflow pages.)
1922 mdb_page_free(MDB_env *env, MDB_page *mp)
1924 mp->mp_next = env->me_dpages;
1925 VGMEMP_FREE(env, mp);
1926 env->me_dpages = mp;
1929 /** Free a dirty page */
1931 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1933 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1934 mdb_page_free(env, dp);
1936 /* large pages just get freed directly */
1937 VGMEMP_FREE(env, dp);
1942 /** Return all dirty pages to dpage list */
1944 mdb_dlist_free(MDB_txn *txn)
1946 MDB_env *env = txn->mt_env;
1947 MDB_ID2L dl = txn->mt_u.dirty_list;
1948 unsigned i, n = dl[0].mid;
1950 for (i = 1; i <= n; i++) {
1951 mdb_dpage_free(env, dl[i].mptr);
1958 mdb_page_unref(MDB_txn *txn, MDB_page *mp)
1961 MDB_ID3L tl = txn->mt_rpages;
1963 if (mp->mp_flags & (P_SUBP|P_DIRTY))
1965 rem = mp->mp_pgno & (MDB_RPAGE_CHUNK-1);
1966 pgno = mp->mp_pgno ^ rem;
1967 x = mdb_mid3l_search(tl, pgno);
1968 if (x != tl[0].mid && tl[x+1].mid == mp->mp_pgno)
1973 #define MDB_PAGE_UNREF(txn, mp) mdb_page_unref(txn, mp)
1976 mdb_cursor_unref(MDB_cursor *mc)
1979 if (!mc->mc_snum || !mc->mc_pg[0] || IS_SUBP(mc->mc_pg[0]))
1981 for (i=0; i<mc->mc_snum; i++)
1982 mdb_page_unref(mc->mc_txn, mc->mc_pg[i]);
1984 mdb_page_unref(mc->mc_txn, mc->mc_ovpg);
1987 mc->mc_snum = mc->mc_top = 0;
1988 mc->mc_pg[0] = NULL;
1989 mc->mc_flags &= ~C_INITIALIZED;
1991 #define MDB_CURSOR_UNREF(mc, force) \
1992 (((force) || ((mc)->mc_flags & C_INITIALIZED)) \
1993 ? mdb_cursor_unref(mc) \
1997 #define MDB_PAGE_UNREF(txn, mp)
1998 #define MDB_CURSOR_UNREF(mc, force) ((void)0)
1999 #endif /* MDB_VL32 */
2001 /** Loosen or free a single page.
2002 * Saves single pages to a list for future reuse
2003 * in this same txn. It has been pulled from the freeDB
2004 * and already resides on the dirty list, but has been
2005 * deleted. Use these pages first before pulling again
2008 * If the page wasn't dirtied in this txn, just add it
2009 * to this txn's free list.
2012 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
2015 pgno_t pgno = mp->mp_pgno;
2016 MDB_txn *txn = mc->mc_txn;
2018 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
2019 if (txn->mt_parent) {
2020 MDB_ID2 *dl = txn->mt_u.dirty_list;
2021 /* If txn has a parent, make sure the page is in our
2025 unsigned x = mdb_mid2l_search(dl, pgno);
2026 if (x <= dl[0].mid && dl[x].mid == pgno) {
2027 if (mp != dl[x].mptr) { /* bad cursor? */
2028 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2029 txn->mt_flags |= MDB_TXN_ERROR;
2037 /* no parent txn, so it's just ours */
2042 DPRINTF(("loosen db %d page %"Yu, DDBI(mc), mp->mp_pgno));
2043 NEXT_LOOSE_PAGE(mp) = txn->mt_loose_pgs;
2044 txn->mt_loose_pgs = mp;
2045 txn->mt_loose_count++;
2046 mp->mp_flags |= P_LOOSE;
2048 int rc = mdb_midl_append(&txn->mt_free_pgs, pgno);
2056 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
2057 * @param[in] mc A cursor handle for the current operation.
2058 * @param[in] pflags Flags of the pages to update:
2059 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
2060 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
2061 * @return 0 on success, non-zero on failure.
2064 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
2066 enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
2067 MDB_txn *txn = mc->mc_txn;
2068 MDB_cursor *m3, *m0 = mc;
2073 int rc = MDB_SUCCESS, level;
2075 /* Mark pages seen by cursors */
2076 if (mc->mc_flags & C_UNTRACK)
2077 mc = NULL; /* will find mc in mt_cursors */
2078 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
2079 for (; mc; mc=mc->mc_next) {
2080 if (!(mc->mc_flags & C_INITIALIZED))
2082 for (m3 = mc;; m3 = &mx->mx_cursor) {
2084 for (j=0; j<m3->mc_snum; j++) {
2086 if ((mp->mp_flags & Mask) == pflags)
2087 mp->mp_flags ^= P_KEEP;
2089 mx = m3->mc_xcursor;
2090 /* Proceed to mx if it is at a sub-database */
2091 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
2093 if (! (mp && (mp->mp_flags & P_LEAF)))
2095 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
2096 if (!(leaf->mn_flags & F_SUBDATA))
2105 /* Mark dirty root pages */
2106 for (i=0; i<txn->mt_numdbs; i++) {
2107 if (txn->mt_dbflags[i] & DB_DIRTY) {
2108 pgno_t pgno = txn->mt_dbs[i].md_root;
2109 if (pgno == P_INVALID)
2111 if ((rc = mdb_page_get(m0, pgno, &dp, &level)) != MDB_SUCCESS)
2113 if ((dp->mp_flags & Mask) == pflags && level <= 1)
2114 dp->mp_flags ^= P_KEEP;
2122 static int mdb_page_flush(MDB_txn *txn, int keep);
2124 /** Spill pages from the dirty list back to disk.
2125 * This is intended to prevent running into #MDB_TXN_FULL situations,
2126 * but note that they may still occur in a few cases:
2127 * 1) our estimate of the txn size could be too small. Currently this
2128 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
2129 * 2) child txns may run out of space if their parents dirtied a
2130 * lot of pages and never spilled them. TODO: we probably should do
2131 * a preemptive spill during #mdb_txn_begin() of a child txn, if
2132 * the parent's dirty_room is below a given threshold.
2134 * Otherwise, if not using nested txns, it is expected that apps will
2135 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
2136 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
2137 * If the txn never references them again, they can be left alone.
2138 * If the txn only reads them, they can be used without any fuss.
2139 * If the txn writes them again, they can be dirtied immediately without
2140 * going thru all of the work of #mdb_page_touch(). Such references are
2141 * handled by #mdb_page_unspill().
2143 * Also note, we never spill DB root pages, nor pages of active cursors,
2144 * because we'll need these back again soon anyway. And in nested txns,
2145 * we can't spill a page in a child txn if it was already spilled in a
2146 * parent txn. That would alter the parent txns' data even though
2147 * the child hasn't committed yet, and we'd have no way to undo it if
2148 * the child aborted.
2150 * @param[in] m0 cursor A cursor handle identifying the transaction and
2151 * database for which we are checking space.
2152 * @param[in] key For a put operation, the key being stored.
2153 * @param[in] data For a put operation, the data being stored.
2154 * @return 0 on success, non-zero on failure.
2157 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
2159 MDB_txn *txn = m0->mc_txn;
2161 MDB_ID2L dl = txn->mt_u.dirty_list;
2162 unsigned int i, j, need;
2165 if (m0->mc_flags & C_SUB)
2168 /* Estimate how much space this op will take */
2169 i = m0->mc_db->md_depth;
2170 /* Named DBs also dirty the main DB */
2171 if (m0->mc_dbi >= CORE_DBS)
2172 i += txn->mt_dbs[MAIN_DBI].md_depth;
2173 /* For puts, roughly factor in the key+data size */
2175 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
2176 i += i; /* double it for good measure */
2179 if (txn->mt_dirty_room > i)
2182 if (!txn->mt_spill_pgs) {
2183 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
2184 if (!txn->mt_spill_pgs)
2187 /* purge deleted slots */
2188 MDB_IDL sl = txn->mt_spill_pgs;
2189 unsigned int num = sl[0];
2191 for (i=1; i<=num; i++) {
2198 /* Preserve pages which may soon be dirtied again */
2199 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
2202 /* Less aggressive spill - we originally spilled the entire dirty list,
2203 * with a few exceptions for cursor pages and DB root pages. But this
2204 * turns out to be a lot of wasted effort because in a large txn many
2205 * of those pages will need to be used again. So now we spill only 1/8th
2206 * of the dirty pages. Testing revealed this to be a good tradeoff,
2207 * better than 1/2, 1/4, or 1/10.
2209 if (need < MDB_IDL_UM_MAX / 8)
2210 need = MDB_IDL_UM_MAX / 8;
2212 /* Save the page IDs of all the pages we're flushing */
2213 /* flush from the tail forward, this saves a lot of shifting later on. */
2214 for (i=dl[0].mid; i && need; i--) {
2215 MDB_ID pn = dl[i].mid << 1;
2217 if (dp->mp_flags & (P_LOOSE|P_KEEP))
2219 /* Can't spill twice, make sure it's not already in a parent's
2222 if (txn->mt_parent) {
2224 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
2225 if (tx2->mt_spill_pgs) {
2226 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
2227 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
2228 dp->mp_flags |= P_KEEP;
2236 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
2240 mdb_midl_sort(txn->mt_spill_pgs);
2242 /* Flush the spilled part of dirty list */
2243 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
2246 /* Reset any dirty pages we kept that page_flush didn't see */
2247 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
2250 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
2254 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
2256 mdb_find_oldest(MDB_txn *txn)
2259 txnid_t mr, oldest = txn->mt_txnid - 1;
2260 if (txn->mt_env->me_txns) {
2261 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
2262 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
2273 /** Add a page to the txn's dirty list */
2275 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
2278 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
2280 if (txn->mt_flags & MDB_TXN_WRITEMAP) {
2281 insert = mdb_mid2l_append;
2283 insert = mdb_mid2l_insert;
2285 mid.mid = mp->mp_pgno;
2287 rc = insert(txn->mt_u.dirty_list, &mid);
2288 mdb_tassert(txn, rc == 0);
2289 txn->mt_dirty_room--;
2292 /** Allocate page numbers and memory for writing. Maintain me_pglast,
2293 * me_pghead and mt_next_pgno.
2295 * If there are free pages available from older transactions, they
2296 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
2297 * Do not modify the freedB, just merge freeDB records into me_pghead[]
2298 * and move me_pglast to say which records were consumed. Only this
2299 * function can create me_pghead and move me_pglast/mt_next_pgno.
2300 * When #MDB_DEVEL & 2, it is not affected by #mdb_freelist_save(): it
2301 * then uses the transaction's original snapshot of the freeDB.
2302 * @param[in] mc cursor A cursor handle identifying the transaction and
2303 * database for which we are allocating.
2304 * @param[in] num the number of pages to allocate.
2305 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
2306 * will always be satisfied by a single contiguous chunk of memory.
2307 * @return 0 on success, non-zero on failure.
2310 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
2312 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
2313 /* Get at most <Max_retries> more freeDB records once me_pghead
2314 * has enough pages. If not enough, use new pages from the map.
2315 * If <Paranoid> and mc is updating the freeDB, only get new
2316 * records if me_pghead is empty. Then the freelist cannot play
2317 * catch-up with itself by growing while trying to save it.
2319 enum { Paranoid = 1, Max_retries = 500 };
2321 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
2323 int rc, retry = num * 60;
2324 MDB_txn *txn = mc->mc_txn;
2325 MDB_env *env = txn->mt_env;
2326 pgno_t pgno, *mop = env->me_pghead;
2327 unsigned i, j, mop_len = mop ? mop[0] : 0, n2 = num-1;
2329 txnid_t oldest = 0, last;
2334 /* If there are any loose pages, just use them */
2335 if (num == 1 && txn->mt_loose_pgs) {
2336 np = txn->mt_loose_pgs;
2337 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
2338 txn->mt_loose_count--;
2339 DPRINTF(("db %d use loose page %"Yu, DDBI(mc), np->mp_pgno));
2346 /* If our dirty list is already full, we can't do anything */
2347 if (txn->mt_dirty_room == 0) {
2352 for (op = MDB_FIRST;; op = MDB_NEXT) {
2357 /* Seek a big enough contiguous page range. Prefer
2358 * pages at the tail, just truncating the list.
2364 if (mop[i-n2] == pgno+n2)
2371 if (op == MDB_FIRST) { /* 1st iteration */
2372 /* Prepare to fetch more and coalesce */
2373 last = env->me_pglast;
2374 oldest = env->me_pgoldest;
2375 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
2376 #if (MDB_DEVEL) & 2 /* "& 2" so MDB_DEVEL=1 won't hide bugs breaking freeDB */
2377 /* Use original snapshot. TODO: Should need less care in code
2378 * which modifies the database. Maybe we can delete some code?
2380 m2.mc_flags |= C_ORIG_RDONLY;
2381 m2.mc_db = &env->me_metas[(txn->mt_txnid-1) & 1]->mm_dbs[FREE_DBI];
2382 m2.mc_dbflag = (unsigned char *)""; /* probably unnecessary */
2386 key.mv_data = &last; /* will look up last+1 */
2387 key.mv_size = sizeof(last);
2389 if (Paranoid && mc->mc_dbi == FREE_DBI)
2392 if (Paranoid && retry < 0 && mop_len)
2396 /* Do not fetch more if the record will be too recent */
2397 if (oldest <= last) {
2399 oldest = mdb_find_oldest(txn);
2400 env->me_pgoldest = oldest;
2406 rc = mdb_cursor_get(&m2, &key, NULL, op);
2408 if (rc == MDB_NOTFOUND)
2412 last = *(txnid_t*)key.mv_data;
2413 if (oldest <= last) {
2415 oldest = mdb_find_oldest(txn);
2416 env->me_pgoldest = oldest;
2422 np = m2.mc_pg[m2.mc_top];
2423 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
2424 if ((rc = mdb_node_read(&m2, leaf, &data)) != MDB_SUCCESS)
2427 idl = (MDB_ID *) data.mv_data;
2430 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
2435 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
2437 mop = env->me_pghead;
2439 env->me_pglast = last;
2441 DPRINTF(("IDL read txn %"Yu" root %"Yu" num %u",
2442 last, txn->mt_dbs[FREE_DBI].md_root, i));
2444 DPRINTF(("IDL %"Yu, idl[j]));
2446 /* Merge in descending sorted order */
2447 mdb_midl_xmerge(mop, idl);
2451 /* Use new pages from the map when nothing suitable in the freeDB */
2453 pgno = txn->mt_next_pgno;
2454 if (pgno + num >= env->me_maxpg) {
2455 DPUTS("DB size maxed out");
2459 #if defined(_WIN32) && !defined(MDB_VL32)
2460 if (!(env->me_flags & MDB_RDONLY)) {
2462 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
2463 p = VirtualAlloc(p, env->me_psize * num, MEM_COMMIT,
2464 (env->me_flags & MDB_WRITEMAP) ? PAGE_READWRITE:
2467 DPUTS("VirtualAlloc failed");
2475 if (env->me_flags & MDB_WRITEMAP) {
2476 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
2478 if (!(np = mdb_page_malloc(txn, num))) {
2484 mop[0] = mop_len -= num;
2485 /* Move any stragglers down */
2486 for (j = i-num; j < mop_len; )
2487 mop[++j] = mop[++i];
2489 txn->mt_next_pgno = pgno + num;
2492 mdb_page_dirty(txn, np);
2498 txn->mt_flags |= MDB_TXN_ERROR;
2502 /** Copy the used portions of a non-overflow page.
2503 * @param[in] dst page to copy into
2504 * @param[in] src page to copy from
2505 * @param[in] psize size of a page
2508 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2510 enum { Align = sizeof(pgno_t) };
2511 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2513 /* If page isn't full, just copy the used portion. Adjust
2514 * alignment so memcpy may copy words instead of bytes.
2516 if ((unused &= -Align) && !IS_LEAF2(src)) {
2517 upper = (upper + PAGEBASE) & -Align;
2518 memcpy(dst, src, (lower + PAGEBASE + (Align-1)) & -Align);
2519 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2522 memcpy(dst, src, psize - unused);
2526 /** Pull a page off the txn's spill list, if present.
2527 * If a page being referenced was spilled to disk in this txn, bring
2528 * it back and make it dirty/writable again.
2529 * @param[in] txn the transaction handle.
2530 * @param[in] mp the page being referenced. It must not be dirty.
2531 * @param[out] ret the writable page, if any. ret is unchanged if
2532 * mp wasn't spilled.
2535 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2537 MDB_env *env = txn->mt_env;
2540 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2542 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2543 if (!tx2->mt_spill_pgs)
2545 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2546 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2549 if (txn->mt_dirty_room == 0)
2550 return MDB_TXN_FULL;
2551 if (IS_OVERFLOW(mp))
2555 if (env->me_flags & MDB_WRITEMAP) {
2558 np = mdb_page_malloc(txn, num);
2562 memcpy(np, mp, num * env->me_psize);
2564 mdb_page_copy(np, mp, env->me_psize);
2567 /* If in current txn, this page is no longer spilled.
2568 * If it happens to be the last page, truncate the spill list.
2569 * Otherwise mark it as deleted by setting the LSB.
2571 if (x == txn->mt_spill_pgs[0])
2572 txn->mt_spill_pgs[0]--;
2574 txn->mt_spill_pgs[x] |= 1;
2575 } /* otherwise, if belonging to a parent txn, the
2576 * page remains spilled until child commits
2579 mdb_page_dirty(txn, np);
2580 np->mp_flags |= P_DIRTY;
2588 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2589 * @param[in] mc cursor pointing to the page to be touched
2590 * @return 0 on success, non-zero on failure.
2593 mdb_page_touch(MDB_cursor *mc)
2595 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2596 MDB_txn *txn = mc->mc_txn;
2597 MDB_cursor *m2, *m3;
2601 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2602 if (txn->mt_flags & MDB_TXN_SPILLS) {
2604 rc = mdb_page_unspill(txn, mp, &np);
2610 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2611 (rc = mdb_page_alloc(mc, 1, &np)))
2614 DPRINTF(("touched db %d page %"Yu" -> %"Yu, DDBI(mc),
2615 mp->mp_pgno, pgno));
2616 mdb_cassert(mc, mp->mp_pgno != pgno);
2617 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2618 /* Update the parent page, if any, to point to the new page */
2620 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2621 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2622 SETPGNO(node, pgno);
2624 mc->mc_db->md_root = pgno;
2626 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2627 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2629 /* If txn has a parent, make sure the page is in our
2633 unsigned x = mdb_mid2l_search(dl, pgno);
2634 if (x <= dl[0].mid && dl[x].mid == pgno) {
2635 if (mp != dl[x].mptr) { /* bad cursor? */
2636 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2637 txn->mt_flags |= MDB_TXN_ERROR;
2643 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2645 np = mdb_page_malloc(txn, 1);
2650 rc = mdb_mid2l_insert(dl, &mid);
2651 mdb_cassert(mc, rc == 0);
2656 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2658 np->mp_flags |= P_DIRTY;
2661 /* Adjust cursors pointing to mp */
2662 mc->mc_pg[mc->mc_top] = np;
2663 m2 = txn->mt_cursors[mc->mc_dbi];
2664 if (mc->mc_flags & C_SUB) {
2665 for (; m2; m2=m2->mc_next) {
2666 m3 = &m2->mc_xcursor->mx_cursor;
2667 if (m3->mc_snum < mc->mc_snum) continue;
2668 if (m3->mc_pg[mc->mc_top] == mp)
2669 m3->mc_pg[mc->mc_top] = np;
2672 for (; m2; m2=m2->mc_next) {
2673 if (m2->mc_snum < mc->mc_snum) continue;
2674 if (m2 == mc) continue;
2675 if (m2->mc_pg[mc->mc_top] == mp) {
2676 m2->mc_pg[mc->mc_top] = np;
2677 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
2679 (m2->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
2681 MDB_node *leaf = NODEPTR(np, m2->mc_ki[mc->mc_top]);
2682 if ((leaf->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
2683 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
2688 MDB_PAGE_UNREF(mc->mc_txn, mp);
2692 txn->mt_flags |= MDB_TXN_ERROR;
2697 mdb_env_sync0(MDB_env *env, int force, pgno_t numpgs)
2700 if (env->me_flags & MDB_RDONLY)
2702 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2703 if (env->me_flags & MDB_WRITEMAP) {
2704 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2705 ? MS_ASYNC : MS_SYNC;
2706 if (MDB_MSYNC(env->me_map, env->me_psize * numpgs, flags))
2709 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2713 #ifdef BROKEN_FDATASYNC
2714 if (env->me_flags & MDB_FSYNCONLY) {
2715 if (fsync(env->me_fd))
2719 if (MDB_FDATASYNC(env->me_fd))
2727 mdb_env_sync(MDB_env *env, int force)
2729 MDB_meta *m = mdb_env_pick_meta(env);
2730 return mdb_env_sync0(env, force, m->mm_last_pg+1);
2733 /** Back up parent txn's cursors, then grab the originals for tracking */
2735 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2737 MDB_cursor *mc, *bk;
2742 for (i = src->mt_numdbs; --i >= 0; ) {
2743 if ((mc = src->mt_cursors[i]) != NULL) {
2744 size = sizeof(MDB_cursor);
2746 size += sizeof(MDB_xcursor);
2747 for (; mc; mc = bk->mc_next) {
2753 mc->mc_db = &dst->mt_dbs[i];
2754 /* Kill pointers into src to reduce abuse: The
2755 * user may not use mc until dst ends. But we need a valid
2756 * txn pointer here for cursor fixups to keep working.
2759 mc->mc_dbflag = &dst->mt_dbflags[i];
2760 if ((mx = mc->mc_xcursor) != NULL) {
2761 *(MDB_xcursor *)(bk+1) = *mx;
2762 mx->mx_cursor.mc_txn = dst;
2764 mc->mc_next = dst->mt_cursors[i];
2765 dst->mt_cursors[i] = mc;
2772 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2773 * @param[in] txn the transaction handle.
2774 * @param[in] merge true to keep changes to parent cursors, false to revert.
2775 * @return 0 on success, non-zero on failure.
2778 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2780 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2784 for (i = txn->mt_numdbs; --i >= 0; ) {
2785 for (mc = cursors[i]; mc; mc = next) {
2787 if ((bk = mc->mc_backup) != NULL) {
2789 /* Commit changes to parent txn */
2790 mc->mc_next = bk->mc_next;
2791 mc->mc_backup = bk->mc_backup;
2792 mc->mc_txn = bk->mc_txn;
2793 mc->mc_db = bk->mc_db;
2794 mc->mc_dbflag = bk->mc_dbflag;
2795 if ((mx = mc->mc_xcursor) != NULL)
2796 mx->mx_cursor.mc_txn = bk->mc_txn;
2798 /* Abort nested txn */
2800 if ((mx = mc->mc_xcursor) != NULL)
2801 *mx = *(MDB_xcursor *)(bk+1);
2805 /* Only malloced cursors are permanently tracked. */
2812 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2818 Pidset = F_SETLK, Pidcheck = F_GETLK
2822 /** Set or check a pid lock. Set returns 0 on success.
2823 * Check returns 0 if the process is certainly dead, nonzero if it may
2824 * be alive (the lock exists or an error happened so we do not know).
2826 * On Windows Pidset is a no-op, we merely check for the existence
2827 * of the process with the given pid. On POSIX we use a single byte
2828 * lock on the lockfile, set at an offset equal to the pid.
2831 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2833 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2836 if (op == Pidcheck) {
2837 h = OpenProcess(env->me_pidquery, FALSE, pid);
2838 /* No documented "no such process" code, but other program use this: */
2840 return ErrCode() != ERROR_INVALID_PARAMETER;
2841 /* A process exists until all handles to it close. Has it exited? */
2842 ret = WaitForSingleObject(h, 0) != 0;
2849 struct flock lock_info;
2850 memset(&lock_info, 0, sizeof(lock_info));
2851 lock_info.l_type = F_WRLCK;
2852 lock_info.l_whence = SEEK_SET;
2853 lock_info.l_start = pid;
2854 lock_info.l_len = 1;
2855 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2856 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2858 } else if ((rc = ErrCode()) == EINTR) {
2866 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2867 * @param[in] txn the transaction handle to initialize
2868 * @return 0 on success, non-zero on failure.
2871 mdb_txn_renew0(MDB_txn *txn)
2873 MDB_env *env = txn->mt_env;
2874 MDB_txninfo *ti = env->me_txns;
2876 unsigned int i, nr, flags = txn->mt_flags;
2878 int rc, new_notls = 0;
2880 if ((flags &= MDB_TXN_RDONLY) != 0) {
2882 meta = mdb_env_pick_meta(env);
2883 txn->mt_txnid = meta->mm_txnid;
2884 txn->mt_u.reader = NULL;
2886 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2887 pthread_getspecific(env->me_txkey);
2889 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2890 return MDB_BAD_RSLOT;
2892 MDB_PID_T pid = env->me_pid;
2893 MDB_THR_T tid = pthread_self();
2894 mdb_mutexref_t rmutex = env->me_rmutex;
2896 if (!env->me_live_reader) {
2897 rc = mdb_reader_pid(env, Pidset, pid);
2900 env->me_live_reader = 1;
2903 if (LOCK_MUTEX(rc, env, rmutex))
2905 nr = ti->mti_numreaders;
2906 for (i=0; i<nr; i++)
2907 if (ti->mti_readers[i].mr_pid == 0)
2909 if (i == env->me_maxreaders) {
2910 UNLOCK_MUTEX(rmutex);
2911 return MDB_READERS_FULL;
2913 r = &ti->mti_readers[i];
2914 /* Claim the reader slot, carefully since other code
2915 * uses the reader table un-mutexed: First reset the
2916 * slot, next publish it in mti_numreaders. After
2917 * that, it is safe for mdb_env_close() to touch it.
2918 * When it will be closed, we can finally claim it.
2921 r->mr_txnid = (txnid_t)-1;
2924 ti->mti_numreaders = ++nr;
2925 env->me_close_readers = nr;
2927 UNLOCK_MUTEX(rmutex);
2929 new_notls = (env->me_flags & MDB_NOTLS);
2930 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2935 do /* LY: Retry on a race, ITS#7970. */
2936 r->mr_txnid = ti->mti_txnid;
2937 while(r->mr_txnid != ti->mti_txnid);
2938 txn->mt_txnid = r->mr_txnid;
2939 txn->mt_u.reader = r;
2940 meta = env->me_metas[txn->mt_txnid & 1];
2944 /* Not yet touching txn == env->me_txn0, it may be active */
2946 if (LOCK_MUTEX(rc, env, env->me_wmutex))
2948 txn->mt_txnid = ti->mti_txnid;
2949 meta = env->me_metas[txn->mt_txnid & 1];
2951 meta = mdb_env_pick_meta(env);
2952 txn->mt_txnid = meta->mm_txnid;
2956 if (txn->mt_txnid == mdb_debug_start)
2959 txn->mt_child = NULL;
2960 txn->mt_loose_pgs = NULL;
2961 txn->mt_loose_count = 0;
2962 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2963 txn->mt_u.dirty_list = env->me_dirty_list;
2964 txn->mt_u.dirty_list[0].mid = 0;
2965 txn->mt_free_pgs = env->me_free_pgs;
2966 txn->mt_free_pgs[0] = 0;
2967 txn->mt_spill_pgs = NULL;
2969 memcpy(txn->mt_dbiseqs, env->me_dbiseqs, env->me_maxdbs * sizeof(unsigned int));
2972 /* Copy the DB info and flags */
2973 memcpy(txn->mt_dbs, meta->mm_dbs, CORE_DBS * sizeof(MDB_db));
2975 /* Moved to here to avoid a data race in read TXNs */
2976 txn->mt_next_pgno = meta->mm_last_pg+1;
2978 txn->mt_last_pgno = txn->mt_next_pgno - 1;
2981 txn->mt_flags = flags;
2984 txn->mt_numdbs = env->me_numdbs;
2985 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
2986 x = env->me_dbflags[i];
2987 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2988 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_USRVALID|DB_STALE : 0;
2990 txn->mt_dbflags[MAIN_DBI] = DB_VALID|DB_USRVALID;
2991 txn->mt_dbflags[FREE_DBI] = DB_VALID;
2993 if (env->me_flags & MDB_FATAL_ERROR) {
2994 DPUTS("environment had fatal error, must shutdown!");
2996 } else if (env->me_maxpg < txn->mt_next_pgno) {
2997 rc = MDB_MAP_RESIZED;
3001 mdb_txn_end(txn, new_notls /*0 or MDB_END_SLOT*/ | MDB_END_FAIL_BEGIN);
3006 mdb_txn_renew(MDB_txn *txn)
3010 if (!txn || !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY|MDB_TXN_FINISHED))
3013 rc = mdb_txn_renew0(txn);
3014 if (rc == MDB_SUCCESS) {
3015 DPRINTF(("renew txn %"Yu"%c %p on mdbenv %p, root page %"Yu,
3016 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
3017 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
3023 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
3027 int rc, size, tsize;
3029 flags &= MDB_TXN_BEGIN_FLAGS;
3030 flags |= env->me_flags & MDB_WRITEMAP;
3032 if (env->me_flags & MDB_RDONLY & ~flags) /* write txn in RDONLY env */
3036 /* Nested transactions: Max 1 child, write txns only, no writemap */
3037 flags |= parent->mt_flags;
3038 if (flags & (MDB_RDONLY|MDB_WRITEMAP|MDB_TXN_BLOCKED)) {
3039 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
3041 /* Child txns save MDB_pgstate and use own copy of cursors */
3042 size = env->me_maxdbs * (sizeof(MDB_db)+sizeof(MDB_cursor *)+1);
3043 size += tsize = sizeof(MDB_ntxn);
3044 } else if (flags & MDB_RDONLY) {
3045 size = env->me_maxdbs * (sizeof(MDB_db)+1);
3046 size += tsize = sizeof(MDB_txn);
3048 /* Reuse preallocated write txn. However, do not touch it until
3049 * mdb_txn_renew0() succeeds, since it currently may be active.
3054 if ((txn = calloc(1, size)) == NULL) {
3055 DPRINTF(("calloc: %s", strerror(errno)));
3060 txn->mt_rpages = malloc(MDB_TRPAGE_SIZE * sizeof(MDB_ID3));
3061 if (!txn->mt_rpages) {
3065 txn->mt_rpages[0].mid = 0;
3066 txn->mt_rpcheck = MDB_TRPAGE_SIZE/2;
3069 txn->mt_dbxs = env->me_dbxs; /* static */
3070 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
3071 txn->mt_dbflags = (unsigned char *)txn + size - env->me_maxdbs;
3072 txn->mt_flags = flags;
3077 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
3078 txn->mt_dbiseqs = parent->mt_dbiseqs;
3079 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
3080 if (!txn->mt_u.dirty_list ||
3081 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
3083 free(txn->mt_u.dirty_list);
3087 txn->mt_txnid = parent->mt_txnid;
3088 txn->mt_dirty_room = parent->mt_dirty_room;
3089 txn->mt_u.dirty_list[0].mid = 0;
3090 txn->mt_spill_pgs = NULL;
3091 txn->mt_next_pgno = parent->mt_next_pgno;
3092 parent->mt_flags |= MDB_TXN_HAS_CHILD;
3093 parent->mt_child = txn;
3094 txn->mt_parent = parent;
3095 txn->mt_numdbs = parent->mt_numdbs;
3097 txn->mt_rpages = parent->mt_rpages;
3099 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3100 /* Copy parent's mt_dbflags, but clear DB_NEW */
3101 for (i=0; i<txn->mt_numdbs; i++)
3102 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
3104 ntxn = (MDB_ntxn *)txn;
3105 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
3106 if (env->me_pghead) {
3107 size = MDB_IDL_SIZEOF(env->me_pghead);
3108 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
3110 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
3115 rc = mdb_cursor_shadow(parent, txn);
3117 mdb_txn_end(txn, MDB_END_FAIL_BEGINCHILD);
3118 } else { /* MDB_RDONLY */
3119 txn->mt_dbiseqs = env->me_dbiseqs;
3121 rc = mdb_txn_renew0(txn);
3124 if (txn != env->me_txn0) {
3126 free(txn->mt_rpages);
3131 txn->mt_flags |= flags; /* could not change txn=me_txn0 earlier */
3133 DPRINTF(("begin txn %"Yu"%c %p on mdbenv %p, root page %"Yu,
3134 txn->mt_txnid, (flags & MDB_RDONLY) ? 'r' : 'w',
3135 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
3142 mdb_txn_env(MDB_txn *txn)
3144 if(!txn) return NULL;
3149 mdb_txn_id(MDB_txn *txn)
3152 return txn->mt_txnid;
3155 /** Export or close DBI handles opened in this txn. */
3157 mdb_dbis_update(MDB_txn *txn, int keep)
3160 MDB_dbi n = txn->mt_numdbs;
3161 MDB_env *env = txn->mt_env;
3162 unsigned char *tdbflags = txn->mt_dbflags;
3164 for (i = n; --i >= CORE_DBS;) {
3165 if (tdbflags[i] & DB_NEW) {
3167 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
3169 char *ptr = env->me_dbxs[i].md_name.mv_data;
3171 env->me_dbxs[i].md_name.mv_data = NULL;
3172 env->me_dbxs[i].md_name.mv_size = 0;
3173 env->me_dbflags[i] = 0;
3174 env->me_dbiseqs[i]++;
3180 if (keep && env->me_numdbs < n)
3184 /** End a transaction, except successful commit of a nested transaction.
3185 * May be called twice for readonly txns: First reset it, then abort.
3186 * @param[in] txn the transaction handle to end
3187 * @param[in] mode why and how to end the transaction
3190 mdb_txn_end(MDB_txn *txn, unsigned mode)
3192 MDB_env *env = txn->mt_env;
3194 static const char *const names[] = MDB_END_NAMES;
3197 /* Export or close DBI handles opened in this txn */
3198 mdb_dbis_update(txn, mode & MDB_END_UPDATE);
3200 DPRINTF(("%s txn %"Yu"%c %p on mdbenv %p, root page %"Yu,
3201 names[mode & MDB_END_OPMASK],
3202 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
3203 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
3205 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3206 if (txn->mt_u.reader) {
3207 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
3208 if (!(env->me_flags & MDB_NOTLS)) {
3209 txn->mt_u.reader = NULL; /* txn does not own reader */
3210 } else if (mode & MDB_END_SLOT) {
3211 txn->mt_u.reader->mr_pid = 0;
3212 txn->mt_u.reader = NULL;
3213 } /* else txn owns the slot until it does MDB_END_SLOT */
3215 txn->mt_numdbs = 0; /* prevent further DBI activity */
3216 txn->mt_flags |= MDB_TXN_FINISHED;
3218 } else if (!F_ISSET(txn->mt_flags, MDB_TXN_FINISHED)) {
3219 pgno_t *pghead = env->me_pghead;
3221 if (!(mode & MDB_END_UPDATE)) /* !(already closed cursors) */
3222 mdb_cursors_close(txn, 0);
3223 if (!(env->me_flags & MDB_WRITEMAP)) {
3224 mdb_dlist_free(txn);
3228 txn->mt_flags = MDB_TXN_FINISHED;
3230 if (!txn->mt_parent) {
3231 mdb_midl_shrink(&txn->mt_free_pgs);
3232 env->me_free_pgs = txn->mt_free_pgs;
3234 env->me_pghead = NULL;
3238 mode = 0; /* txn == env->me_txn0, do not free() it */
3240 /* The writer mutex was locked in mdb_txn_begin. */
3242 UNLOCK_MUTEX(env->me_wmutex);
3244 txn->mt_parent->mt_child = NULL;
3245 txn->mt_parent->mt_flags &= ~MDB_TXN_HAS_CHILD;
3246 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
3247 mdb_midl_free(txn->mt_free_pgs);
3248 mdb_midl_free(txn->mt_spill_pgs);
3249 free(txn->mt_u.dirty_list);
3252 mdb_midl_free(pghead);
3255 if (!txn->mt_parent) {
3256 MDB_ID3L el = env->me_rpages, tl = txn->mt_rpages;
3257 unsigned i, x, n = tl[0].mid;
3258 pthread_mutex_lock(&env->me_rpmutex);
3259 for (i = 1; i <= n; i++) {
3260 if (tl[i].mid & (MDB_RPAGE_CHUNK-1)) {
3261 /* tmp overflow pages that we didn't share in env */
3262 munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
3264 x = mdb_mid3l_search(el, tl[i].mid);
3265 if (tl[i].mptr == el[x].mptr) {
3268 /* another tmp overflow page */
3269 munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
3273 pthread_mutex_unlock(&env->me_rpmutex);
3275 if (mode & MDB_END_FREE)
3279 if (mode & MDB_END_FREE)
3284 mdb_txn_reset(MDB_txn *txn)
3289 /* This call is only valid for read-only txns */
3290 if (!(txn->mt_flags & MDB_TXN_RDONLY))
3293 mdb_txn_end(txn, MDB_END_RESET);
3297 mdb_txn_abort(MDB_txn *txn)
3303 mdb_txn_abort(txn->mt_child);
3305 mdb_txn_end(txn, MDB_END_ABORT|MDB_END_SLOT|MDB_END_FREE);
3308 /** Save the freelist as of this transaction to the freeDB.
3309 * This changes the freelist. Keep trying until it stabilizes.
3311 * When (MDB_DEVEL) & 2, the changes do not affect #mdb_page_alloc(),
3312 * it then uses the transaction's original snapshot of the freeDB.
3315 mdb_freelist_save(MDB_txn *txn)
3317 /* env->me_pghead[] can grow and shrink during this call.
3318 * env->me_pglast and txn->mt_free_pgs[] can only grow.
3319 * Page numbers cannot disappear from txn->mt_free_pgs[].
3322 MDB_env *env = txn->mt_env;
3323 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
3324 txnid_t pglast = 0, head_id = 0;
3325 pgno_t freecnt = 0, *free_pgs, *mop;
3326 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
3328 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
3330 if (env->me_pghead) {
3331 /* Make sure first page of freeDB is touched and on freelist */
3332 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
3333 if (rc && rc != MDB_NOTFOUND)
3337 if (!env->me_pghead && txn->mt_loose_pgs) {
3338 /* Put loose page numbers in mt_free_pgs, since
3339 * we may be unable to return them to me_pghead.
3341 MDB_page *mp = txn->mt_loose_pgs;
3342 if ((rc = mdb_midl_need(&txn->mt_free_pgs, txn->mt_loose_count)) != 0)
3344 for (; mp; mp = NEXT_LOOSE_PAGE(mp))
3345 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
3346 txn->mt_loose_pgs = NULL;
3347 txn->mt_loose_count = 0;
3350 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
3351 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
3352 ? SSIZE_MAX : maxfree_1pg;
3355 /* Come back here after each Put() in case freelist changed */
3360 /* If using records from freeDB which we have not yet
3361 * deleted, delete them and any we reserved for me_pghead.
3363 while (pglast < env->me_pglast) {
3364 rc = mdb_cursor_first(&mc, &key, NULL);
3367 pglast = head_id = *(txnid_t *)key.mv_data;
3368 total_room = head_room = 0;
3369 mdb_tassert(txn, pglast <= env->me_pglast);
3370 rc = mdb_cursor_del(&mc, 0);
3375 /* Save the IDL of pages freed by this txn, to a single record */
3376 if (freecnt < txn->mt_free_pgs[0]) {
3378 /* Make sure last page of freeDB is touched and on freelist */
3379 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
3380 if (rc && rc != MDB_NOTFOUND)
3383 free_pgs = txn->mt_free_pgs;
3384 /* Write to last page of freeDB */
3385 key.mv_size = sizeof(txn->mt_txnid);
3386 key.mv_data = &txn->mt_txnid;
3388 freecnt = free_pgs[0];
3389 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
3390 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3393 /* Retry if mt_free_pgs[] grew during the Put() */
3394 free_pgs = txn->mt_free_pgs;
3395 } while (freecnt < free_pgs[0]);
3396 mdb_midl_sort(free_pgs);
3397 memcpy(data.mv_data, free_pgs, data.mv_size);
3400 unsigned int i = free_pgs[0];
3401 DPRINTF(("IDL write txn %"Yu" root %"Yu" num %u",
3402 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
3404 DPRINTF(("IDL %"Yu, free_pgs[i]));
3410 mop = env->me_pghead;
3411 mop_len = (mop ? mop[0] : 0) + txn->mt_loose_count;
3413 /* Reserve records for me_pghead[]. Split it if multi-page,
3414 * to avoid searching freeDB for a page range. Use keys in
3415 * range [1,me_pglast]: Smaller than txnid of oldest reader.
3417 if (total_room >= mop_len) {
3418 if (total_room == mop_len || --more < 0)
3420 } else if (head_room >= maxfree_1pg && head_id > 1) {
3421 /* Keep current record (overflow page), add a new one */
3425 /* (Re)write {key = head_id, IDL length = head_room} */
3426 total_room -= head_room;
3427 head_room = mop_len - total_room;
3428 if (head_room > maxfree_1pg && head_id > 1) {
3429 /* Overflow multi-page for part of me_pghead */
3430 head_room /= head_id; /* amortize page sizes */
3431 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
3432 } else if (head_room < 0) {
3433 /* Rare case, not bothering to delete this record */
3436 key.mv_size = sizeof(head_id);
3437 key.mv_data = &head_id;
3438 data.mv_size = (head_room + 1) * sizeof(pgno_t);
3439 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3442 /* IDL is initially empty, zero out at least the length */
3443 pgs = (pgno_t *)data.mv_data;
3444 j = head_room > clean_limit ? head_room : 0;
3448 total_room += head_room;
3451 /* Return loose page numbers to me_pghead, though usually none are
3452 * left at this point. The pages themselves remain in dirty_list.
3454 if (txn->mt_loose_pgs) {
3455 MDB_page *mp = txn->mt_loose_pgs;
3456 unsigned count = txn->mt_loose_count;
3458 /* Room for loose pages + temp IDL with same */
3459 if ((rc = mdb_midl_need(&env->me_pghead, 2*count+1)) != 0)
3461 mop = env->me_pghead;
3462 loose = mop + MDB_IDL_ALLOCLEN(mop) - count;
3463 for (count = 0; mp; mp = NEXT_LOOSE_PAGE(mp))
3464 loose[ ++count ] = mp->mp_pgno;
3466 mdb_midl_sort(loose);
3467 mdb_midl_xmerge(mop, loose);
3468 txn->mt_loose_pgs = NULL;
3469 txn->mt_loose_count = 0;
3473 /* Fill in the reserved me_pghead records */
3479 rc = mdb_cursor_first(&mc, &key, &data);
3480 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
3481 txnid_t id = *(txnid_t *)key.mv_data;
3482 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
3485 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
3487 if (len > mop_len) {
3489 data.mv_size = (len + 1) * sizeof(MDB_ID);
3491 data.mv_data = mop -= len;
3494 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
3496 if (rc || !(mop_len -= len))
3503 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
3504 * @param[in] txn the transaction that's being committed
3505 * @param[in] keep number of initial pages in dirty_list to keep dirty.
3506 * @return 0 on success, non-zero on failure.
3509 mdb_page_flush(MDB_txn *txn, int keep)
3511 MDB_env *env = txn->mt_env;
3512 MDB_ID2L dl = txn->mt_u.dirty_list;
3513 unsigned psize = env->me_psize, j;
3514 int i, pagecount = dl[0].mid, rc;
3518 MDB_page *dp = NULL;
3522 struct iovec iov[MDB_COMMIT_PAGES];
3523 ssize_t wsize = 0, wres;
3524 off_t wpos = 0, next_pos = 1; /* impossible pos, so pos != next_pos */
3530 if (env->me_flags & MDB_WRITEMAP) {
3531 /* Clear dirty flags */
3532 while (++i <= pagecount) {
3534 /* Don't flush this page yet */
3535 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3536 dp->mp_flags &= ~P_KEEP;
3540 dp->mp_flags &= ~P_DIRTY;
3545 /* Write the pages */
3547 if (++i <= pagecount) {
3549 /* Don't flush this page yet */
3550 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3551 dp->mp_flags &= ~P_KEEP;
3556 /* clear dirty flag */
3557 dp->mp_flags &= ~P_DIRTY;
3560 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
3565 /* Windows actually supports scatter/gather I/O, but only on
3566 * unbuffered file handles. Since we're relying on the OS page
3567 * cache for all our data, that's self-defeating. So we just
3568 * write pages one at a time. We use the ov structure to set
3569 * the write offset, to at least save the overhead of a Seek
3572 DPRINTF(("committing page %"Yu, pgno));
3573 memset(&ov, 0, sizeof(ov));
3574 ov.Offset = pos & 0xffffffff;
3575 ov.OffsetHigh = pos >> 16 >> 16;
3576 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
3578 DPRINTF(("WriteFile: %d", rc));
3582 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
3583 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
3586 /* Write previous page(s) */
3587 #ifdef MDB_USE_PWRITEV
3588 wres = pwritev(env->me_fd, iov, n, wpos);
3591 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
3594 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
3598 DPRINTF(("lseek: %s", strerror(rc)));
3601 wres = writev(env->me_fd, iov, n);
3604 if (wres != wsize) {
3609 DPRINTF(("Write error: %s", strerror(rc)));
3611 rc = EIO; /* TODO: Use which error code? */
3612 DPUTS("short write, filesystem full?");
3623 DPRINTF(("committing page %"Yu, pgno));
3624 next_pos = pos + size;
3625 iov[n].iov_len = size;
3626 iov[n].iov_base = (char *)dp;
3632 if (pgno > txn->mt_last_pgno)
3633 txn->mt_last_pgno = pgno;
3636 /* MIPS has cache coherency issues, this is a no-op everywhere else
3637 * Note: for any size >= on-chip cache size, entire on-chip cache is
3640 CACHEFLUSH(env->me_map, txn->mt_next_pgno * env->me_psize, DCACHE);
3642 for (i = keep; ++i <= pagecount; ) {
3644 /* This is a page we skipped above */
3647 dl[j].mid = dp->mp_pgno;
3650 mdb_dpage_free(env, dp);
3655 txn->mt_dirty_room += i - j;
3661 mdb_txn_commit(MDB_txn *txn)
3664 unsigned int i, end_mode;
3670 /* mdb_txn_end() mode for a commit which writes nothing */
3671 end_mode = MDB_END_EMPTY_COMMIT|MDB_END_UPDATE|MDB_END_SLOT|MDB_END_FREE;
3673 if (txn->mt_child) {
3674 rc = mdb_txn_commit(txn->mt_child);
3681 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3685 if (txn->mt_flags & (MDB_TXN_FINISHED|MDB_TXN_ERROR)) {
3686 DPUTS("txn has failed/finished, can't commit");
3688 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3693 if (txn->mt_parent) {
3694 MDB_txn *parent = txn->mt_parent;
3698 unsigned x, y, len, ps_len;
3700 /* Append our free list to parent's */
3701 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3704 mdb_midl_free(txn->mt_free_pgs);
3705 /* Failures after this must either undo the changes
3706 * to the parent or set MDB_TXN_ERROR in the parent.
3709 parent->mt_next_pgno = txn->mt_next_pgno;
3710 parent->mt_flags = txn->mt_flags;
3712 /* Merge our cursors into parent's and close them */
3713 mdb_cursors_close(txn, 1);
3715 /* Update parent's DB table. */
3716 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3717 parent->mt_numdbs = txn->mt_numdbs;
3718 parent->mt_dbflags[FREE_DBI] = txn->mt_dbflags[FREE_DBI];
3719 parent->mt_dbflags[MAIN_DBI] = txn->mt_dbflags[MAIN_DBI];
3720 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
3721 /* preserve parent's DB_NEW status */
3722 x = parent->mt_dbflags[i] & DB_NEW;
3723 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3726 dst = parent->mt_u.dirty_list;
3727 src = txn->mt_u.dirty_list;
3728 /* Remove anything in our dirty list from parent's spill list */
3729 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3731 pspill[0] = (pgno_t)-1;
3732 /* Mark our dirty pages as deleted in parent spill list */
3733 for (i=0, len=src[0].mid; ++i <= len; ) {
3734 MDB_ID pn = src[i].mid << 1;
3735 while (pn > pspill[x])
3737 if (pn == pspill[x]) {
3742 /* Squash deleted pagenums if we deleted any */
3743 for (x=y; ++x <= ps_len; )
3744 if (!(pspill[x] & 1))
3745 pspill[++y] = pspill[x];
3749 /* Remove anything in our spill list from parent's dirty list */
3750 if (txn->mt_spill_pgs && txn->mt_spill_pgs[0]) {
3751 for (i=1; i<=txn->mt_spill_pgs[0]; i++) {
3752 MDB_ID pn = txn->mt_spill_pgs[i];
3754 continue; /* deleted spillpg */
3756 y = mdb_mid2l_search(dst, pn);
3757 if (y <= dst[0].mid && dst[y].mid == pn) {
3759 while (y < dst[0].mid) {
3768 /* Find len = length of merging our dirty list with parent's */
3770 dst[0].mid = 0; /* simplify loops */
3771 if (parent->mt_parent) {
3772 len = x + src[0].mid;
3773 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3774 for (i = x; y && i; y--) {
3775 pgno_t yp = src[y].mid;
3776 while (yp < dst[i].mid)
3778 if (yp == dst[i].mid) {
3783 } else { /* Simplify the above for single-ancestor case */
3784 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3786 /* Merge our dirty list with parent's */
3788 for (i = len; y; dst[i--] = src[y--]) {
3789 pgno_t yp = src[y].mid;
3790 while (yp < dst[x].mid)
3791 dst[i--] = dst[x--];
3792 if (yp == dst[x].mid)
3793 free(dst[x--].mptr);
3795 mdb_tassert(txn, i == x);
3797 free(txn->mt_u.dirty_list);
3798 parent->mt_dirty_room = txn->mt_dirty_room;
3799 if (txn->mt_spill_pgs) {
3800 if (parent->mt_spill_pgs) {
3801 /* TODO: Prevent failure here, so parent does not fail */
3802 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3804 parent->mt_flags |= MDB_TXN_ERROR;
3805 mdb_midl_free(txn->mt_spill_pgs);
3806 mdb_midl_sort(parent->mt_spill_pgs);
3808 parent->mt_spill_pgs = txn->mt_spill_pgs;
3812 /* Append our loose page list to parent's */
3813 for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(*lp))
3815 *lp = txn->mt_loose_pgs;
3816 parent->mt_loose_count += txn->mt_loose_count;
3818 parent->mt_child = NULL;
3819 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3824 if (txn != env->me_txn) {
3825 DPUTS("attempt to commit unknown transaction");
3830 mdb_cursors_close(txn, 0);
3832 if (!txn->mt_u.dirty_list[0].mid &&
3833 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
3836 DPRINTF(("committing txn %"Yu" %p on mdbenv %p, root page %"Yu,
3837 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3839 /* Update DB root pointers */
3840 if (txn->mt_numdbs > CORE_DBS) {
3844 data.mv_size = sizeof(MDB_db);
3846 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3847 for (i = CORE_DBS; i < txn->mt_numdbs; i++) {
3848 if (txn->mt_dbflags[i] & DB_DIRTY) {
3849 if (TXN_DBI_CHANGED(txn, i)) {
3853 data.mv_data = &txn->mt_dbs[i];
3854 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data,
3862 rc = mdb_freelist_save(txn);
3866 mdb_midl_free(env->me_pghead);
3867 env->me_pghead = NULL;
3868 mdb_midl_shrink(&txn->mt_free_pgs);
3874 if ((rc = mdb_page_flush(txn, 0)))
3876 if (!F_ISSET(txn->mt_flags, MDB_TXN_NOSYNC) &&
3877 (rc = mdb_env_sync0(env, 0, txn->mt_next_pgno)))
3879 if ((rc = mdb_env_write_meta(txn)))
3881 end_mode = MDB_END_COMMITTED|MDB_END_UPDATE;
3884 mdb_txn_end(txn, end_mode);
3892 /** Read the environment parameters of a DB environment before
3893 * mapping it into memory.
3894 * @param[in] env the environment handle
3895 * @param[out] meta address of where to store the meta information
3896 * @return 0 on success, non-zero on failure.
3899 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3905 enum { Size = sizeof(pbuf) };
3907 /* We don't know the page size yet, so use a minimum value.
3908 * Read both meta pages so we can use the latest one.
3911 for (i=off=0; i<NUM_METAS; i++, off += meta->mm_psize) {
3915 memset(&ov, 0, sizeof(ov));
3917 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3918 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3921 rc = pread(env->me_fd, &pbuf, Size, off);
3924 if (rc == 0 && off == 0)
3926 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3927 DPRINTF(("read: %s", mdb_strerror(rc)));
3931 p = (MDB_page *)&pbuf;
3933 if (!F_ISSET(p->mp_flags, P_META)) {
3934 DPRINTF(("page %"Yu" not a meta page", p->mp_pgno));
3939 if (m->mm_magic != MDB_MAGIC) {
3940 DPUTS("meta has invalid magic");
3944 if (m->mm_version != MDB_DATA_VERSION) {
3945 DPRINTF(("database is version %u, expected version %u",
3946 m->mm_version, MDB_DATA_VERSION));
3947 return MDB_VERSION_MISMATCH;
3950 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3956 /** Fill in most of the zeroed #MDB_meta for an empty database environment */
3958 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
3960 meta->mm_magic = MDB_MAGIC;
3961 meta->mm_version = MDB_DATA_VERSION;
3962 meta->mm_mapsize = env->me_mapsize;
3963 meta->mm_psize = env->me_psize;
3964 meta->mm_last_pg = NUM_METAS-1;
3965 meta->mm_flags = env->me_flags & 0xffff;
3966 meta->mm_flags |= MDB_INTEGERKEY; /* this is mm_dbs[FREE_DBI].md_flags */
3967 meta->mm_dbs[FREE_DBI].md_root = P_INVALID;
3968 meta->mm_dbs[MAIN_DBI].md_root = P_INVALID;
3971 /** Write the environment parameters of a freshly created DB environment.
3972 * @param[in] env the environment handle
3973 * @param[in] meta the #MDB_meta to write
3974 * @return 0 on success, non-zero on failure.
3977 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3985 memset(&ov, 0, sizeof(ov));
3986 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3988 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3991 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3992 len = pwrite(fd, ptr, size, pos); \
3993 if (len == -1 && ErrCode() == EINTR) continue; \
3994 rc = (len >= 0); break; } while(1)
3997 DPUTS("writing new meta page");
3999 psize = env->me_psize;
4001 p = calloc(NUM_METAS, psize);
4005 p->mp_flags = P_META;
4006 *(MDB_meta *)METADATA(p) = *meta;
4008 q = (MDB_page *)((char *)p + psize);
4010 q->mp_flags = P_META;
4011 *(MDB_meta *)METADATA(q) = *meta;
4013 DO_PWRITE(rc, env->me_fd, p, psize * NUM_METAS, len, 0);
4016 else if ((unsigned) len == psize * NUM_METAS)
4024 /** Update the environment info to commit a transaction.
4025 * @param[in] txn the transaction that's being committed
4026 * @return 0 on success, non-zero on failure.
4029 mdb_env_write_meta(MDB_txn *txn)
4032 MDB_meta meta, metab, *mp;
4036 int rc, len, toggle;
4045 toggle = txn->mt_txnid & 1;
4046 DPRINTF(("writing meta page %d for root page %"Yu,
4047 toggle, txn->mt_dbs[MAIN_DBI].md_root));
4050 flags = txn->mt_flags | env->me_flags;
4051 mp = env->me_metas[toggle];
4052 mapsize = env->me_metas[toggle ^ 1]->mm_mapsize;
4053 /* Persist any increases of mapsize config */
4054 if (mapsize < env->me_mapsize)
4055 mapsize = env->me_mapsize;
4057 if (flags & MDB_WRITEMAP) {
4058 mp->mm_mapsize = mapsize;
4059 mp->mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
4060 mp->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
4061 mp->mm_last_pg = txn->mt_next_pgno - 1;
4062 #if (__GNUC__ * 100 + __GNUC_MINOR__ >= 404) && /* TODO: portability */ \
4063 !(defined(__i386__) || defined(__x86_64__))
4064 /* LY: issue a memory barrier, if not x86. ITS#7969 */
4065 __sync_synchronize();
4067 mp->mm_txnid = txn->mt_txnid;
4068 if (!(flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
4069 unsigned meta_size = env->me_psize;
4070 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
4071 ptr = (char *)mp - PAGEHDRSZ;
4072 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
4073 r2 = (ptr - env->me_map) & (env->me_os_psize - 1);
4077 if (MDB_MSYNC(ptr, meta_size, rc)) {
4084 metab.mm_txnid = mp->mm_txnid;
4085 metab.mm_last_pg = mp->mm_last_pg;
4087 meta.mm_mapsize = mapsize;
4088 meta.mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
4089 meta.mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
4090 meta.mm_last_pg = txn->mt_next_pgno - 1;
4091 meta.mm_txnid = txn->mt_txnid;
4093 off = offsetof(MDB_meta, mm_mapsize);
4094 ptr = (char *)&meta + off;
4095 len = sizeof(MDB_meta) - off;
4096 off += (char *)mp - env->me_map;
4098 /* Write to the SYNC fd */
4099 mfd = (flags & (MDB_NOSYNC|MDB_NOMETASYNC)) ? env->me_fd : env->me_mfd;
4102 memset(&ov, 0, sizeof(ov));
4104 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
4109 rc = pwrite(mfd, ptr, len, off);
4112 rc = rc < 0 ? ErrCode() : EIO;
4117 DPUTS("write failed, disk error?");
4118 /* On a failure, the pagecache still contains the new data.
4119 * Write some old data back, to prevent it from being used.
4120 * Use the non-SYNC fd; we know it will fail anyway.
4122 meta.mm_last_pg = metab.mm_last_pg;
4123 meta.mm_txnid = metab.mm_txnid;
4125 memset(&ov, 0, sizeof(ov));
4127 WriteFile(env->me_fd, ptr, len, NULL, &ov);
4129 r2 = pwrite(env->me_fd, ptr, len, off);
4130 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
4133 env->me_flags |= MDB_FATAL_ERROR;
4136 /* MIPS has cache coherency issues, this is a no-op everywhere else */
4137 CACHEFLUSH(env->me_map + off, len, DCACHE);
4139 /* Memory ordering issues are irrelevant; since the entire writer
4140 * is wrapped by wmutex, all of these changes will become visible
4141 * after the wmutex is unlocked. Since the DB is multi-version,
4142 * readers will get consistent data regardless of how fresh or
4143 * how stale their view of these values is.
4146 env->me_txns->mti_txnid = txn->mt_txnid;
4151 /** Check both meta pages to see which one is newer.
4152 * @param[in] env the environment handle
4153 * @return newest #MDB_meta.
4156 mdb_env_pick_meta(const MDB_env *env)
4158 MDB_meta *const *metas = env->me_metas;
4159 return metas[ metas[0]->mm_txnid < metas[1]->mm_txnid ];
4163 mdb_env_create(MDB_env **env)
4167 e = calloc(1, sizeof(MDB_env));
4171 e->me_maxreaders = DEFAULT_READERS;
4172 e->me_maxdbs = e->me_numdbs = CORE_DBS;
4173 e->me_fd = INVALID_HANDLE_VALUE;
4174 e->me_lfd = INVALID_HANDLE_VALUE;
4175 e->me_mfd = INVALID_HANDLE_VALUE;
4176 #ifdef MDB_USE_POSIX_SEM
4177 e->me_rmutex = SEM_FAILED;
4178 e->me_wmutex = SEM_FAILED;
4179 #elif defined MDB_USE_SYSV_SEM
4180 e->me_rmutex->semid = -1;
4181 e->me_wmutex->semid = -1;
4183 e->me_pid = getpid();
4184 GET_PAGESIZE(e->me_os_psize);
4185 VGMEMP_CREATE(e,0,0);
4191 /** @brief Map a result from an NTAPI call to WIN32. */
4193 mdb_nt2win32(NTSTATUS st)
4198 GetOverlappedResult(NULL, &o, &br, FALSE);
4199 return GetLastError();
4204 mdb_env_map(MDB_env *env, void *addr)
4207 unsigned int flags = env->me_flags;
4210 int access = SECTION_MAP_READ;
4214 ULONG pageprot = PAGE_READONLY, secprot, alloctype;
4216 if (flags & MDB_WRITEMAP) {
4217 access |= SECTION_MAP_WRITE;
4218 pageprot = PAGE_READWRITE;
4220 if (flags & MDB_RDONLY) {
4221 secprot = PAGE_READONLY;
4225 secprot = PAGE_READWRITE;
4226 msize = env->me_mapsize;
4227 alloctype = MEM_RESERVE;
4230 rc = NtCreateSection(&mh, access, NULL, NULL, secprot, SEC_RESERVE, env->me_fd);
4232 return mdb_nt2win32(rc);
4235 msize = NUM_METAS * env->me_psize;
4237 rc = NtMapViewOfSection(mh, GetCurrentProcess(), &map, 0, 0, NULL, &msize, ViewUnmap, alloctype, pageprot);
4244 return mdb_nt2win32(rc);
4249 env->me_map = mmap(addr, NUM_METAS * env->me_psize, PROT_READ, MAP_SHARED,
4251 if (env->me_map == MAP_FAILED) {
4256 int prot = PROT_READ;
4257 if (flags & MDB_WRITEMAP) {
4259 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
4262 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
4264 if (env->me_map == MAP_FAILED) {
4269 if (flags & MDB_NORDAHEAD) {
4270 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
4272 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
4274 #ifdef POSIX_MADV_RANDOM
4275 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
4276 #endif /* POSIX_MADV_RANDOM */
4277 #endif /* MADV_RANDOM */
4281 /* Can happen because the address argument to mmap() is just a
4282 * hint. mmap() can pick another, e.g. if the range is in use.
4283 * The MAP_FIXED flag would prevent that, but then mmap could
4284 * instead unmap existing pages to make room for the new map.
4286 if (addr && env->me_map != addr)
4287 return EBUSY; /* TODO: Make a new MDB_* error code? */
4290 p = (MDB_page *)env->me_map;
4291 env->me_metas[0] = METADATA(p);
4292 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
4298 mdb_env_set_mapsize(MDB_env *env, mdb_size_t size)
4300 /* If env is already open, caller is responsible for making
4301 * sure there are no active txns.
4311 meta = mdb_env_pick_meta(env);
4313 size = meta->mm_mapsize;
4315 /* Silently round up to minimum if the size is too small */
4316 mdb_size_t minsize = (meta->mm_last_pg + 1) * env->me_psize;
4321 /* For MDB_VL32 this bit is a noop since we dynamically remap
4322 * chunks of the DB anyway.
4324 munmap(env->me_map, env->me_mapsize);
4325 env->me_mapsize = size;
4326 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
4327 rc = mdb_env_map(env, old);
4330 #endif /* !MDB_VL32 */
4332 env->me_mapsize = size;
4334 env->me_maxpg = env->me_mapsize / env->me_psize;
4339 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
4343 env->me_maxdbs = dbs + CORE_DBS;
4348 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
4350 if (env->me_map || readers < 1)
4352 env->me_maxreaders = readers;
4357 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
4359 if (!env || !readers)
4361 *readers = env->me_maxreaders;
4366 mdb_fsize(HANDLE fd, mdb_size_t *size)
4369 LARGE_INTEGER fsize;
4371 if (!GetFileSizeEx(fd, &fsize))
4374 *size = fsize.QuadPart;
4386 #ifdef BROKEN_FDATASYNC
4387 #include <sys/utsname.h>
4388 #include <sys/vfs.h>
4391 /** Further setup required for opening an LMDB environment
4394 mdb_env_open2(MDB_env *env)
4396 unsigned int flags = env->me_flags;
4397 int i, newenv = 0, rc;
4401 /* See if we should use QueryLimited */
4403 if ((rc & 0xff) > 5)
4404 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
4406 env->me_pidquery = PROCESS_QUERY_INFORMATION;
4409 #ifdef BROKEN_FDATASYNC
4410 /* ext3/ext4 fdatasync is broken on some older Linux kernels.
4411 * https://lkml.org/lkml/2012/9/3/83
4412 * Kernels after 3.6-rc6 are known good.
4413 * https://lkml.org/lkml/2012/9/10/556
4414 * See if the DB is on ext3/ext4, then check for new enough kernel
4415 * Kernels 2.6.32.60, 2.6.34.15, 3.2.30, and 3.5.4 are also known
4420 fstatfs(env->me_fd, &st);
4421 while (st.f_type == 0xEF53) {
4425 if (uts.release[0] < '3') {
4426 if (!strncmp(uts.release, "2.6.32.", 7)) {
4427 i = atoi(uts.release+7);
4429 break; /* 2.6.32.60 and newer is OK */
4430 } else if (!strncmp(uts.release, "2.6.34.", 7)) {
4431 i = atoi(uts.release+7);
4433 break; /* 2.6.34.15 and newer is OK */
4435 } else if (uts.release[0] == '3') {
4436 i = atoi(uts.release+2);
4438 break; /* 3.6 and newer is OK */
4440 i = atoi(uts.release+4);
4442 break; /* 3.5.4 and newer is OK */
4443 } else if (i == 2) {
4444 i = atoi(uts.release+4);
4446 break; /* 3.2.30 and newer is OK */
4448 } else { /* 4.x and newer is OK */
4451 env->me_flags |= MDB_FSYNCONLY;
4457 if ((i = mdb_env_read_header(env, &meta)) != 0) {
4460 DPUTS("new mdbenv");
4462 env->me_psize = env->me_os_psize;
4463 if (env->me_psize > MAX_PAGESIZE)
4464 env->me_psize = MAX_PAGESIZE;
4465 memset(&meta, 0, sizeof(meta));
4466 mdb_env_init_meta0(env, &meta);
4467 meta.mm_mapsize = DEFAULT_MAPSIZE;
4469 env->me_psize = meta.mm_psize;
4472 /* Was a mapsize configured? */
4473 if (!env->me_mapsize) {
4474 env->me_mapsize = meta.mm_mapsize;
4477 /* Make sure mapsize >= committed data size. Even when using
4478 * mm_mapsize, which could be broken in old files (ITS#7789).
4480 mdb_size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
4481 if (env->me_mapsize < minsize)
4482 env->me_mapsize = minsize;
4484 meta.mm_mapsize = env->me_mapsize;
4486 if (newenv && !(flags & MDB_FIXEDMAP)) {
4487 /* mdb_env_map() may grow the datafile. Write the metapages
4488 * first, so the file will be valid if initialization fails.
4489 * Except with FIXEDMAP, since we do not yet know mm_address.
4490 * We could fill in mm_address later, but then a different
4491 * program might end up doing that - one with a memory layout
4492 * and map address which does not suit the main program.
4494 rc = mdb_env_init_meta(env, &meta);
4500 /* For FIXEDMAP, make sure the file is non-empty before we attempt to map it */
4504 rc = WriteFile(env->me_fd, &dummy, 1, &len, NULL);
4512 rc = mdb_env_map(env, (flags & MDB_FIXEDMAP) ? meta.mm_address : NULL);
4517 if (flags & MDB_FIXEDMAP)
4518 meta.mm_address = env->me_map;
4519 i = mdb_env_init_meta(env, &meta);
4520 if (i != MDB_SUCCESS) {
4525 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
4526 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
4528 #if !(MDB_MAXKEYSIZE)
4529 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
4531 env->me_maxpg = env->me_mapsize / env->me_psize;
4535 MDB_meta *meta = mdb_env_pick_meta(env);
4536 MDB_db *db = &meta->mm_dbs[MAIN_DBI];
4538 DPRINTF(("opened database version %u, pagesize %u",
4539 meta->mm_version, env->me_psize));
4540 DPRINTF(("using meta page %d", (int) (meta->mm_txnid & 1)));
4541 DPRINTF(("depth: %u", db->md_depth));
4542 DPRINTF(("entries: %"Yu, db->md_entries));
4543 DPRINTF(("branch pages: %"Yu, db->md_branch_pages));
4544 DPRINTF(("leaf pages: %"Yu, db->md_leaf_pages));
4545 DPRINTF(("overflow pages: %"Yu, db->md_overflow_pages));
4546 DPRINTF(("root: %"Yu, db->md_root));
4554 /** Release a reader thread's slot in the reader lock table.
4555 * This function is called automatically when a thread exits.
4556 * @param[in] ptr This points to the slot in the reader lock table.
4559 mdb_env_reader_dest(void *ptr)
4561 MDB_reader *reader = ptr;
4567 /** Junk for arranging thread-specific callbacks on Windows. This is
4568 * necessarily platform and compiler-specific. Windows supports up
4569 * to 1088 keys. Let's assume nobody opens more than 64 environments
4570 * in a single process, for now. They can override this if needed.
4572 #ifndef MAX_TLS_KEYS
4573 #define MAX_TLS_KEYS 64
4575 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
4576 static int mdb_tls_nkeys;
4578 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
4582 case DLL_PROCESS_ATTACH: break;
4583 case DLL_THREAD_ATTACH: break;
4584 case DLL_THREAD_DETACH:
4585 for (i=0; i<mdb_tls_nkeys; i++) {
4586 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
4588 mdb_env_reader_dest(r);
4592 case DLL_PROCESS_DETACH: break;
4597 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4599 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4603 /* Force some symbol references.
4604 * _tls_used forces the linker to create the TLS directory if not already done
4605 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
4607 #pragma comment(linker, "/INCLUDE:_tls_used")
4608 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
4609 #pragma const_seg(".CRT$XLB")
4610 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
4611 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4614 #pragma comment(linker, "/INCLUDE:__tls_used")
4615 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
4616 #pragma data_seg(".CRT$XLB")
4617 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4619 #endif /* WIN 32/64 */
4620 #endif /* !__GNUC__ */
4623 /** Downgrade the exclusive lock on the region back to shared */
4625 mdb_env_share_locks(MDB_env *env, int *excl)
4628 MDB_meta *meta = mdb_env_pick_meta(env);
4630 env->me_txns->mti_txnid = meta->mm_txnid;
4635 /* First acquire a shared lock. The Unlock will
4636 * then release the existing exclusive lock.
4638 memset(&ov, 0, sizeof(ov));
4639 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4642 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4648 struct flock lock_info;
4649 /* The shared lock replaces the existing lock */
4650 memset((void *)&lock_info, 0, sizeof(lock_info));
4651 lock_info.l_type = F_RDLCK;
4652 lock_info.l_whence = SEEK_SET;
4653 lock_info.l_start = 0;
4654 lock_info.l_len = 1;
4655 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4656 (rc = ErrCode()) == EINTR) ;
4657 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
4664 /** Try to get exclusive lock, otherwise shared.
4665 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
4668 mdb_env_excl_lock(MDB_env *env, int *excl)
4672 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
4676 memset(&ov, 0, sizeof(ov));
4677 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4684 struct flock lock_info;
4685 memset((void *)&lock_info, 0, sizeof(lock_info));
4686 lock_info.l_type = F_WRLCK;
4687 lock_info.l_whence = SEEK_SET;
4688 lock_info.l_start = 0;
4689 lock_info.l_len = 1;
4690 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4691 (rc = ErrCode()) == EINTR) ;
4695 # ifndef MDB_USE_POSIX_MUTEX
4696 if (*excl < 0) /* always true when MDB_USE_POSIX_MUTEX */
4699 lock_info.l_type = F_RDLCK;
4700 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
4701 (rc = ErrCode()) == EINTR) ;
4711 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
4713 * @(#) $Revision: 5.1 $
4714 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
4715 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
4717 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
4721 * Please do not copyright this code. This code is in the public domain.
4723 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
4724 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
4725 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
4726 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
4727 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4728 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4729 * PERFORMANCE OF THIS SOFTWARE.
4732 * chongo <Landon Curt Noll> /\oo/\
4733 * http://www.isthe.com/chongo/
4735 * Share and Enjoy! :-)
4738 typedef unsigned long long mdb_hash_t;
4739 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
4741 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
4742 * @param[in] val value to hash
4743 * @param[in] hval initial value for hash
4744 * @return 64 bit hash
4746 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
4747 * hval arg on the first call.
4750 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
4752 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
4753 unsigned char *end = s + val->mv_size;
4755 * FNV-1a hash each octet of the string
4758 /* xor the bottom with the current octet */
4759 hval ^= (mdb_hash_t)*s++;
4761 /* multiply by the 64 bit FNV magic prime mod 2^64 */
4762 hval += (hval << 1) + (hval << 4) + (hval << 5) +
4763 (hval << 7) + (hval << 8) + (hval << 40);
4765 /* return our new hash value */
4769 /** Hash the string and output the encoded hash.
4770 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
4771 * very short name limits. We don't care about the encoding being reversible,
4772 * we just want to preserve as many bits of the input as possible in a
4773 * small printable string.
4774 * @param[in] str string to hash
4775 * @param[out] encbuf an array of 11 chars to hold the hash
4777 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
4780 mdb_pack85(unsigned long l, char *out)
4784 for (i=0; i<5; i++) {
4785 *out++ = mdb_a85[l % 85];
4791 mdb_hash_enc(MDB_val *val, char *encbuf)
4793 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
4795 mdb_pack85(h, encbuf);
4796 mdb_pack85(h>>32, encbuf+5);
4801 /** Open and/or initialize the lock region for the environment.
4802 * @param[in] env The LMDB environment.
4803 * @param[in] lpath The pathname of the file used for the lock region.
4804 * @param[in] mode The Unix permissions for the file, if we create it.
4805 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
4806 * @return 0 on success, non-zero on failure.
4809 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
4812 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
4814 # define MDB_ERRCODE_ROFS EROFS
4815 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
4816 # define MDB_CLOEXEC O_CLOEXEC
4819 # define MDB_CLOEXEC 0
4822 #ifdef MDB_USE_SYSV_SEM
4831 rc = utf8_to_utf16(lpath, -1, &wlpath, NULL);
4834 env->me_lfd = CreateFileW(wlpath, GENERIC_READ|GENERIC_WRITE,
4835 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
4836 FILE_ATTRIBUTE_NORMAL, NULL);
4839 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
4841 if (env->me_lfd == INVALID_HANDLE_VALUE) {
4843 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
4848 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
4849 /* Lose record locks when exec*() */
4850 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
4851 fcntl(env->me_lfd, F_SETFD, fdflags);
4854 if (!(env->me_flags & MDB_NOTLS)) {
4855 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
4858 env->me_flags |= MDB_ENV_TXKEY;
4860 /* Windows TLS callbacks need help finding their TLS info. */
4861 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
4865 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
4869 /* Try to get exclusive lock. If we succeed, then
4870 * nobody is using the lock region and we should initialize it.
4872 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
4875 size = GetFileSize(env->me_lfd, NULL);
4877 size = lseek(env->me_lfd, 0, SEEK_END);
4878 if (size == -1) goto fail_errno;
4880 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
4881 if (size < rsize && *excl > 0) {
4883 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
4884 || !SetEndOfFile(env->me_lfd))
4887 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
4891 size = rsize - sizeof(MDB_txninfo);
4892 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
4897 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
4899 if (!mh) goto fail_errno;
4900 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
4902 if (!env->me_txns) goto fail_errno;
4904 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
4906 if (m == MAP_FAILED) goto fail_errno;
4912 BY_HANDLE_FILE_INFORMATION stbuf;
4921 if (!mdb_sec_inited) {
4922 InitializeSecurityDescriptor(&mdb_null_sd,
4923 SECURITY_DESCRIPTOR_REVISION);
4924 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
4925 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
4926 mdb_all_sa.bInheritHandle = FALSE;
4927 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
4930 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
4931 idbuf.volume = stbuf.dwVolumeSerialNumber;
4932 idbuf.nhigh = stbuf.nFileIndexHigh;
4933 idbuf.nlow = stbuf.nFileIndexLow;
4934 val.mv_data = &idbuf;
4935 val.mv_size = sizeof(idbuf);
4936 mdb_hash_enc(&val, encbuf);
4937 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
4938 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
4939 env->me_rmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
4940 if (!env->me_rmutex) goto fail_errno;
4941 env->me_wmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
4942 if (!env->me_wmutex) goto fail_errno;
4943 #elif defined(MDB_USE_POSIX_SEM)
4952 #if defined(__NetBSD__)
4953 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
4955 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
4956 idbuf.dev = stbuf.st_dev;
4957 idbuf.ino = stbuf.st_ino;
4958 val.mv_data = &idbuf;
4959 val.mv_size = sizeof(idbuf);
4960 mdb_hash_enc(&val, encbuf);
4961 #ifdef MDB_SHORT_SEMNAMES
4962 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
4964 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
4965 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
4966 /* Clean up after a previous run, if needed: Try to
4967 * remove both semaphores before doing anything else.
4969 sem_unlink(env->me_txns->mti_rmname);
4970 sem_unlink(env->me_txns->mti_wmname);
4971 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
4972 O_CREAT|O_EXCL, mode, 1);
4973 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4974 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
4975 O_CREAT|O_EXCL, mode, 1);
4976 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4977 #elif defined(MDB_USE_SYSV_SEM)
4978 unsigned short vals[2] = {1, 1};
4979 key_t key = ftok(lpath, 'M');
4982 semid = semget(key, 2, (mode & 0777) | IPC_CREAT);
4986 if (semctl(semid, 0, SETALL, semu) < 0)
4988 env->me_txns->mti_semid = semid;
4989 env->me_txns->mti_rlocked = 0;
4990 env->me_txns->mti_wlocked = 0;
4991 #else /* MDB_USE_POSIX_MUTEX: */
4992 pthread_mutexattr_t mattr;
4994 /* Solaris needs this before initing a robust mutex. Otherwise
4995 * it may skip the init and return EBUSY "seems someone already
4996 * inited" or EINVAL "it was inited differently".
4998 memset(env->me_txns->mti_rmutex, 0, sizeof(*env->me_txns->mti_rmutex));
4999 memset(env->me_txns->mti_wmutex, 0, sizeof(*env->me_txns->mti_wmutex));
5001 if ((rc = pthread_mutexattr_init(&mattr)) != 0)
5003 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
5004 #ifdef MDB_ROBUST_SUPPORTED
5005 if (!rc) rc = pthread_mutexattr_setrobust(&mattr, PTHREAD_MUTEX_ROBUST);
5007 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_rmutex, &mattr);
5008 if (!rc) rc = pthread_mutex_init(env->me_txns->mti_wmutex, &mattr);
5009 pthread_mutexattr_destroy(&mattr);
5012 #endif /* _WIN32 || ... */
5014 env->me_txns->mti_magic = MDB_MAGIC;
5015 env->me_txns->mti_format = MDB_LOCK_FORMAT;
5016 env->me_txns->mti_txnid = 0;
5017 env->me_txns->mti_numreaders = 0;
5020 #ifdef MDB_USE_SYSV_SEM
5021 struct semid_ds buf;
5023 if (env->me_txns->mti_magic != MDB_MAGIC) {
5024 DPUTS("lock region has invalid magic");
5028 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
5029 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
5030 env->me_txns->mti_format, MDB_LOCK_FORMAT));
5031 rc = MDB_VERSION_MISMATCH;
5035 if (rc && rc != EACCES && rc != EAGAIN) {
5039 env->me_rmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
5040 if (!env->me_rmutex) goto fail_errno;
5041 env->me_wmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
5042 if (!env->me_wmutex) goto fail_errno;
5043 #elif defined(MDB_USE_POSIX_SEM)
5044 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
5045 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
5046 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
5047 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
5048 #elif defined(MDB_USE_SYSV_SEM)
5049 semid = env->me_txns->mti_semid;
5051 /* check for read access */
5052 if (semctl(semid, 0, IPC_STAT, semu) < 0)
5054 /* check for write access */
5055 if (semctl(semid, 0, IPC_SET, semu) < 0)
5059 #ifdef MDB_USE_SYSV_SEM
5060 env->me_rmutex->semid = semid;
5061 env->me_wmutex->semid = semid;
5062 env->me_rmutex->semnum = 0;
5063 env->me_wmutex->semnum = 1;
5064 env->me_rmutex->locked = &env->me_txns->mti_rlocked;
5065 env->me_wmutex->locked = &env->me_txns->mti_wlocked;
5069 env->me_rpmutex = CreateMutex(NULL, FALSE, NULL);
5071 pthread_mutex_init(&env->me_rpmutex, NULL);
5083 /** The name of the lock file in the DB environment */
5084 #define LOCKNAME "/lock.mdb"
5085 /** The name of the data file in the DB environment */
5086 #define DATANAME "/data.mdb"
5087 /** The suffix of the lock file when no subdir is used */
5088 #define LOCKSUFF "-lock"
5089 /** Only a subset of the @ref mdb_env flags can be changed
5090 * at runtime. Changing other flags requires closing the
5091 * environment and re-opening it with the new flags.
5093 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
5094 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY| \
5095 MDB_WRITEMAP|MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
5097 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
5098 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
5102 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
5104 int oflags, rc, len, excl = -1;
5105 char *lpath, *dpath;
5110 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
5114 if (flags & MDB_WRITEMAP) {
5115 /* silently ignore WRITEMAP in 32 bit mode */
5116 flags ^= MDB_WRITEMAP;
5118 if (flags & MDB_FIXEDMAP) {
5119 /* cannot support FIXEDMAP */
5125 if (flags & MDB_NOSUBDIR) {
5126 rc = len + sizeof(LOCKSUFF) + len + 1;
5128 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
5133 if (flags & MDB_NOSUBDIR) {
5134 dpath = lpath + len + sizeof(LOCKSUFF);
5135 sprintf(lpath, "%s" LOCKSUFF, path);
5136 strcpy(dpath, path);
5138 dpath = lpath + len + sizeof(LOCKNAME);
5139 sprintf(lpath, "%s" LOCKNAME, path);
5140 sprintf(dpath, "%s" DATANAME, path);
5144 flags |= env->me_flags;
5145 if (flags & MDB_RDONLY) {
5146 /* silently ignore WRITEMAP when we're only getting read access */
5147 flags &= ~MDB_WRITEMAP;
5149 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
5150 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
5155 env->me_rpages = malloc(MDB_ERPAGE_SIZE * sizeof(MDB_ID3));
5156 if (!env->me_rpages) {
5160 env->me_rpages[0].mid = 0;
5161 env->me_rpcheck = MDB_ERPAGE_SIZE/2;
5164 env->me_flags = flags |= MDB_ENV_ACTIVE;
5168 env->me_path = strdup(path);
5169 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
5170 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
5171 env->me_dbiseqs = calloc(env->me_maxdbs, sizeof(unsigned int));
5172 if (!(env->me_dbxs && env->me_path && env->me_dbflags && env->me_dbiseqs)) {
5176 env->me_dbxs[FREE_DBI].md_cmp = mdb_cmp_long; /* aligned MDB_INTEGERKEY */
5178 /* For RDONLY, get lockfile after we know datafile exists */
5179 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
5180 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
5186 if (F_ISSET(flags, MDB_RDONLY)) {
5187 oflags = GENERIC_READ;
5188 len = OPEN_EXISTING;
5190 oflags = GENERIC_READ|GENERIC_WRITE;
5193 mode = FILE_ATTRIBUTE_NORMAL;
5194 rc = utf8_to_utf16(dpath, -1, &wpath, NULL);
5197 env->me_fd = CreateFileW(wpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
5198 NULL, len, mode, NULL);
5201 if (F_ISSET(flags, MDB_RDONLY))
5204 oflags = O_RDWR | O_CREAT;
5206 env->me_fd = open(dpath, oflags, mode);
5208 if (env->me_fd == INVALID_HANDLE_VALUE) {
5213 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
5214 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
5219 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
5220 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
5221 env->me_mfd = env->me_fd;
5223 /* Synchronous fd for meta writes. Needed even with
5224 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
5227 len = OPEN_EXISTING;
5228 rc = utf8_to_utf16(dpath, -1, &wpath, NULL);
5231 env->me_mfd = CreateFileW(wpath, oflags,
5232 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
5233 mode | FILE_FLAG_WRITE_THROUGH, NULL);
5237 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
5239 if (env->me_mfd == INVALID_HANDLE_VALUE) {
5244 DPRINTF(("opened dbenv %p", (void *) env));
5246 rc = mdb_env_share_locks(env, &excl);
5250 if (!(flags & MDB_RDONLY)) {
5252 int tsize = sizeof(MDB_txn), size = tsize + env->me_maxdbs *
5253 (sizeof(MDB_db)+sizeof(MDB_cursor *)+sizeof(unsigned int)+1);
5254 if ((env->me_pbuf = calloc(1, env->me_psize)) &&
5255 (txn = calloc(1, size)))
5257 txn->mt_dbs = (MDB_db *)((char *)txn + tsize);
5258 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
5259 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
5260 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
5263 txn->mt_rpages = malloc(MDB_TRPAGE_SIZE * sizeof(MDB_ID3));
5264 if (!txn->mt_rpages) {
5269 txn->mt_rpages[0].mid = 0;
5270 txn->mt_rpcheck = MDB_TRPAGE_SIZE/2;
5272 txn->mt_dbxs = env->me_dbxs;
5273 txn->mt_flags = MDB_TXN_FINISHED;
5283 mdb_env_close0(env, excl);
5289 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
5291 mdb_env_close0(MDB_env *env, int excl)
5295 if (!(env->me_flags & MDB_ENV_ACTIVE))
5298 /* Doing this here since me_dbxs may not exist during mdb_env_close */
5300 for (i = env->me_maxdbs; --i >= CORE_DBS; )
5301 free(env->me_dbxs[i].md_name.mv_data);
5306 free(env->me_dbiseqs);
5307 free(env->me_dbflags);
5309 free(env->me_dirty_list);
5311 if (env->me_txn0 && env->me_txn0->mt_rpages)
5312 free(env->me_txn0->mt_rpages);
5314 for (x=1; x<=env->me_rpages[0].mid; x++)
5315 munmap(env->me_rpages[x].mptr, env->me_rpages[x].mcnt * env->me_psize);
5317 free(env->me_rpages);
5320 mdb_midl_free(env->me_free_pgs);
5322 if (env->me_flags & MDB_ENV_TXKEY) {
5323 pthread_key_delete(env->me_txkey);
5325 /* Delete our key from the global list */
5326 for (i=0; i<mdb_tls_nkeys; i++)
5327 if (mdb_tls_keys[i] == env->me_txkey) {
5328 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
5337 munmap(env->me_map, NUM_METAS*env->me_psize);
5339 munmap(env->me_map, env->me_mapsize);
5342 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
5343 (void) close(env->me_mfd);
5344 if (env->me_fd != INVALID_HANDLE_VALUE)
5345 (void) close(env->me_fd);
5347 MDB_PID_T pid = env->me_pid;
5348 /* Clearing readers is done in this function because
5349 * me_txkey with its destructor must be disabled first.
5351 * We skip the the reader mutex, so we touch only
5352 * data owned by this process (me_close_readers and
5353 * our readers), and clear each reader atomically.
5355 for (i = env->me_close_readers; --i >= 0; )
5356 if (env->me_txns->mti_readers[i].mr_pid == pid)
5357 env->me_txns->mti_readers[i].mr_pid = 0;
5359 if (env->me_rmutex) {
5360 CloseHandle(env->me_rmutex);
5361 if (env->me_wmutex) CloseHandle(env->me_wmutex);
5363 /* Windows automatically destroys the mutexes when
5364 * the last handle closes.
5366 #elif defined(MDB_USE_POSIX_SEM)
5367 if (env->me_rmutex != SEM_FAILED) {
5368 sem_close(env->me_rmutex);
5369 if (env->me_wmutex != SEM_FAILED)
5370 sem_close(env->me_wmutex);
5371 /* If we have the filelock: If we are the
5372 * only remaining user, clean up semaphores.
5375 mdb_env_excl_lock(env, &excl);
5377 sem_unlink(env->me_txns->mti_rmname);
5378 sem_unlink(env->me_txns->mti_wmname);
5381 #elif defined(MDB_USE_SYSV_SEM)
5382 if (env->me_rmutex->semid != -1) {
5383 /* If we have the filelock: If we are the
5384 * only remaining user, clean up semaphores.
5387 mdb_env_excl_lock(env, &excl);
5389 semctl(env->me_rmutex->semid, 0, IPC_RMID);
5392 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
5394 if (env->me_lfd != INVALID_HANDLE_VALUE) {
5397 /* Unlock the lockfile. Windows would have unlocked it
5398 * after closing anyway, but not necessarily at once.
5400 UnlockFile(env->me_lfd, 0, 0, 1, 0);
5403 (void) close(env->me_lfd);
5407 if (env->me_fmh) CloseHandle(env->me_fmh);
5408 if (env->me_rpmutex) CloseHandle(env->me_rpmutex);
5410 pthread_mutex_destroy(&env->me_rpmutex);
5414 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
5418 mdb_env_close(MDB_env *env)
5425 VGMEMP_DESTROY(env);
5426 while ((dp = env->me_dpages) != NULL) {
5427 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
5428 env->me_dpages = dp->mp_next;
5432 mdb_env_close0(env, 0);
5436 /** Compare two items pointing at aligned #mdb_size_t's */
5438 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
5440 return (*(mdb_size_t *)a->mv_data < *(mdb_size_t *)b->mv_data) ? -1 :
5441 *(mdb_size_t *)a->mv_data > *(mdb_size_t *)b->mv_data;
5444 /** Compare two items pointing at aligned unsigned int's.
5446 * This is also set as #MDB_INTEGERDUP|#MDB_DUPFIXED's #MDB_dbx.%md_dcmp,
5447 * but #mdb_cmp_clong() is called instead if the data type is #mdb_size_t.
5450 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
5452 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
5453 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
5456 /** Compare two items pointing at unsigned ints of unknown alignment.
5457 * Nodes and keys are guaranteed to be 2-byte aligned.
5460 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
5462 #if BYTE_ORDER == LITTLE_ENDIAN
5463 unsigned short *u, *c;
5466 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5467 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
5470 } while(!x && u > (unsigned short *)a->mv_data);
5473 unsigned short *u, *c, *end;
5476 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5477 u = (unsigned short *)a->mv_data;
5478 c = (unsigned short *)b->mv_data;
5481 } while(!x && u < end);
5486 /** Compare two items lexically */
5488 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
5495 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5501 diff = memcmp(a->mv_data, b->mv_data, len);
5502 return diff ? diff : len_diff<0 ? -1 : len_diff;
5505 /** Compare two items in reverse byte order */
5507 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
5509 const unsigned char *p1, *p2, *p1_lim;
5513 p1_lim = (const unsigned char *)a->mv_data;
5514 p1 = (const unsigned char *)a->mv_data + a->mv_size;
5515 p2 = (const unsigned char *)b->mv_data + b->mv_size;
5517 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5523 while (p1 > p1_lim) {
5524 diff = *--p1 - *--p2;
5528 return len_diff<0 ? -1 : len_diff;
5531 /** Search for key within a page, using binary search.
5532 * Returns the smallest entry larger or equal to the key.
5533 * If exactp is non-null, stores whether the found entry was an exact match
5534 * in *exactp (1 or 0).
5535 * Updates the cursor index with the index of the found entry.
5536 * If no entry larger or equal to the key is found, returns NULL.
5539 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
5541 unsigned int i = 0, nkeys;
5544 MDB_page *mp = mc->mc_pg[mc->mc_top];
5545 MDB_node *node = NULL;
5550 nkeys = NUMKEYS(mp);
5552 DPRINTF(("searching %u keys in %s %spage %"Yu,
5553 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
5556 low = IS_LEAF(mp) ? 0 : 1;
5558 cmp = mc->mc_dbx->md_cmp;
5560 /* Branch pages have no data, so if using integer keys,
5561 * alignment is guaranteed. Use faster mdb_cmp_int.
5563 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
5564 if (NODEPTR(mp, 1)->mn_ksize == sizeof(mdb_size_t))
5571 nodekey.mv_size = mc->mc_db->md_pad;
5572 node = NODEPTR(mp, 0); /* fake */
5573 while (low <= high) {
5574 i = (low + high) >> 1;
5575 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
5576 rc = cmp(key, &nodekey);
5577 DPRINTF(("found leaf index %u [%s], rc = %i",
5578 i, DKEY(&nodekey), rc));
5587 while (low <= high) {
5588 i = (low + high) >> 1;
5590 node = NODEPTR(mp, i);
5591 nodekey.mv_size = NODEKSZ(node);
5592 nodekey.mv_data = NODEKEY(node);
5594 rc = cmp(key, &nodekey);
5597 DPRINTF(("found leaf index %u [%s], rc = %i",
5598 i, DKEY(&nodekey), rc));
5600 DPRINTF(("found branch index %u [%s -> %"Yu"], rc = %i",
5601 i, DKEY(&nodekey), NODEPGNO(node), rc));
5612 if (rc > 0) { /* Found entry is less than the key. */
5613 i++; /* Skip to get the smallest entry larger than key. */
5615 node = NODEPTR(mp, i);
5618 *exactp = (rc == 0 && nkeys > 0);
5619 /* store the key index */
5620 mc->mc_ki[mc->mc_top] = i;
5622 /* There is no entry larger or equal to the key. */
5625 /* nodeptr is fake for LEAF2 */
5631 mdb_cursor_adjust(MDB_cursor *mc, func)
5635 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5636 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
5643 /** Pop a page off the top of the cursor's stack. */
5645 mdb_cursor_pop(MDB_cursor *mc)
5648 DPRINTF(("popping page %"Yu" off db %d cursor %p",
5649 mc->mc_pg[mc->mc_top]->mp_pgno, DDBI(mc), (void *) mc));
5655 mc->mc_flags &= ~C_INITIALIZED;
5660 /** Push a page onto the top of the cursor's stack. */
5662 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
5664 DPRINTF(("pushing page %"Yu" on db %d cursor %p", mp->mp_pgno,
5665 DDBI(mc), (void *) mc));
5667 if (mc->mc_snum >= CURSOR_STACK) {
5668 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5669 return MDB_CURSOR_FULL;
5672 mc->mc_top = mc->mc_snum++;
5673 mc->mc_pg[mc->mc_top] = mp;
5674 mc->mc_ki[mc->mc_top] = 0;
5680 /** Map a read-only page.
5681 * There are two levels of tracking in use, a per-txn list and a per-env list.
5682 * ref'ing and unref'ing the per-txn list is faster since it requires no
5683 * locking. Pages are cached in the per-env list for global reuse, and a lock
5684 * is required. Pages are not immediately unmapped when their refcnt goes to
5685 * zero; they hang around in case they will be reused again soon.
5687 * When the per-txn list gets full, all pages with refcnt=0 are purged from the
5688 * list and their refcnts in the per-env list are decremented.
5690 * When the per-env list gets full, all pages with refcnt=0 are purged from the
5691 * list and their pages are unmapped.
5693 * @note "full" means the list has reached its respective rpcheck threshold.
5694 * This threshold slowly raises if no pages could be purged on a given check,
5695 * and returns to its original value when enough pages were purged.
5697 * If purging doesn't free any slots, filling the per-txn list will return
5698 * MDB_TXN_FULL, and filling the per-env list returns MDB_MAP_FULL.
5700 * Reference tracking in a txn is imperfect, pages can linger with non-zero
5701 * refcnt even without active references. It was deemed to be too invasive
5702 * to add unrefs in every required location. However, all pages are unref'd
5703 * at the end of the transaction. This guarantees that no stale references
5704 * linger in the per-env list.
5706 * Usually we map chunks of 16 pages at a time, but if an overflow page begins
5707 * at the tail of the chunk we extend the chunk to include the entire overflow
5708 * page. Unfortunately, pages can be turned into overflow pages after their
5709 * chunk was already mapped. In that case we must remap the chunk if the
5710 * overflow page is referenced. If the chunk's refcnt is 0 we can just remap
5711 * it, otherwise we temporarily map a new chunk just for the overflow page.
5713 * @note this chunk handling means we cannot guarantee that a data item
5714 * returned from the DB will stay alive for the duration of the transaction:
5715 * We unref pages as soon as a cursor moves away from the page
5716 * A subsequent op may cause a purge, which may unmap any unref'd chunks
5717 * The caller must copy the data if it must be used later in the same txn.
5719 * Also - our reference counting revolves around cursors, but overflow pages
5720 * aren't pointed to by a cursor's page stack. We have to remember them
5721 * explicitly, in the added mc_ovpg field. A single cursor can only hold a
5722 * reference to one overflow page at a time.
5724 * @param[in] txn the transaction for this access.
5725 * @param[in] pgno the page number for the page to retrieve.
5726 * @param[out] ret address of a pointer where the page's address will be stored.
5727 * @return 0 on success, non-zero on failure.
5730 mdb_rpage_get(MDB_txn *txn, pgno_t pg0, MDB_page **ret)
5732 MDB_env *env = txn->mt_env;
5734 MDB_ID3L tl = txn->mt_rpages;
5735 MDB_ID3L el = env->me_rpages;
5739 int rc, retries = 1;
5743 #define SET_OFF(off,val) off.QuadPart = val
5744 #define MAP(rc,env,addr,len,off) \
5746 rc = NtMapViewOfSection(env->me_fmh, GetCurrentProcess(), &addr, 0, \
5747 len, &off, &len, ViewUnmap, (env->me_flags & MDB_RDONLY) ? 0 : MEM_RESERVE, PAGE_READONLY); \
5748 if (rc) rc = mdb_nt2win32(rc)
5752 #define SET_OFF(off,val) off = val
5753 #define MAP(rc,env,addr,len,off) \
5754 addr = mmap(NULL, len, PROT_READ, MAP_SHARED, env->me_fd, off); \
5755 rc = (addr == MAP_FAILED) ? errno : 0
5758 /* remember the offset of the actual page number, so we can
5759 * return the correct pointer at the end.
5761 rem = pg0 & (MDB_RPAGE_CHUNK-1);
5765 x = mdb_mid3l_search(tl, pgno);
5766 if (x <= tl[0].mid && tl[x].mid == pgno) {
5767 if (x != tl[0].mid && tl[x+1].mid == pg0)
5769 /* check for overflow size */
5770 p = (MDB_page *)((char *)tl[x].mptr + rem * env->me_psize);
5771 if (IS_OVERFLOW(p) && p->mp_pages + rem > tl[x].mcnt) {
5772 id3.mcnt = p->mp_pages + rem;
5773 len = id3.mcnt * env->me_psize;
5774 SET_OFF(off, pgno * env->me_psize);
5775 MAP(rc, env, id3.mptr, len, off);
5778 /* check for local-only page */
5780 mdb_tassert(txn, tl[x].mid != pg0);
5781 /* hope there's room to insert this locally.
5782 * setting mid here tells later code to just insert
5783 * this id3 instead of searching for a match.
5788 /* ignore the mapping we got from env, use new one */
5789 tl[x].mptr = id3.mptr;
5790 tl[x].mcnt = id3.mcnt;
5791 /* if no active ref, see if we can replace in env */
5794 pthread_mutex_lock(&env->me_rpmutex);
5795 i = mdb_mid3l_search(el, tl[x].mid);
5796 if (el[i].mref == 1) {
5797 /* just us, replace it */
5798 munmap(el[i].mptr, el[i].mcnt * env->me_psize);
5799 el[i].mptr = tl[x].mptr;
5800 el[i].mcnt = tl[x].mcnt;
5802 /* there are others, remove ourself */
5805 pthread_mutex_unlock(&env->me_rpmutex);
5809 id3.mptr = tl[x].mptr;
5810 id3.mcnt = tl[x].mcnt;
5816 if (tl[0].mid >= MDB_TRPAGE_MAX - txn->mt_rpcheck) {
5818 /* purge unref'd pages from our list and unref in env */
5819 pthread_mutex_lock(&env->me_rpmutex);
5822 for (i=1; i<=tl[0].mid; i++) {
5825 /* tmp overflow pages don't go to env */
5826 if (tl[i].mid & (MDB_RPAGE_CHUNK-1)) {
5827 munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
5830 x = mdb_mid3l_search(el, tl[i].mid);
5834 pthread_mutex_unlock(&env->me_rpmutex);
5836 /* we didn't find any unref'd chunks.
5837 * if we're out of room, fail.
5839 if (tl[0].mid >= MDB_TRPAGE_MAX)
5840 return MDB_TXN_FULL;
5841 /* otherwise, raise threshold for next time around
5844 txn->mt_rpcheck /= 2;
5846 /* we found some unused; consolidate the list */
5847 for (i=y+1; i<= tl[0].mid; i++)
5851 /* decrease the check threshold toward its original value */
5852 if (!txn->mt_rpcheck)
5853 txn->mt_rpcheck = 1;
5854 while (txn->mt_rpcheck < tl[0].mid && txn->mt_rpcheck < MDB_TRPAGE_SIZE/2)
5855 txn->mt_rpcheck *= 2;
5858 if (tl[0].mid < MDB_TRPAGE_SIZE) {
5862 /* don't map past last written page in read-only envs */
5863 if ((env->me_flags & MDB_RDONLY) && pgno + MDB_RPAGE_CHUNK-1 > txn->mt_last_pgno)
5864 id3.mcnt = txn->mt_last_pgno + 1 - pgno;
5866 id3.mcnt = MDB_RPAGE_CHUNK;
5867 len = id3.mcnt * env->me_psize;
5870 /* search for page in env */
5871 pthread_mutex_lock(&env->me_rpmutex);
5872 x = mdb_mid3l_search(el, pgno);
5873 if (x <= el[0].mid && el[x].mid == pgno) {
5874 id3.mptr = el[x].mptr;
5875 id3.mcnt = el[x].mcnt;
5876 /* check for overflow size */
5877 p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
5878 if (IS_OVERFLOW(p) && p->mp_pages + rem > id3.mcnt) {
5879 id3.mcnt = p->mp_pages + rem;
5880 len = id3.mcnt * env->me_psize;
5881 SET_OFF(off, pgno * env->me_psize);
5882 MAP(rc, env, id3.mptr, len, off);
5886 munmap(el[x].mptr, env->me_psize * el[x].mcnt);
5887 el[x].mptr = id3.mptr;
5888 el[x].mcnt = id3.mcnt;
5891 pthread_mutex_unlock(&env->me_rpmutex);
5896 pthread_mutex_unlock(&env->me_rpmutex);
5899 if (el[0].mid >= MDB_ERPAGE_MAX - env->me_rpcheck) {
5900 /* purge unref'd pages */
5902 for (i=1; i<=el[0].mid; i++) {
5905 munmap(el[i].mptr, env->me_psize * el[i].mcnt);
5910 /* see if we can unref some local pages */
5915 if (el[0].mid >= MDB_ERPAGE_MAX) {
5916 pthread_mutex_unlock(&env->me_rpmutex);
5917 return MDB_MAP_FULL;
5919 env->me_rpcheck /= 2;
5921 for (i=y+1; i<= el[0].mid; i++)
5925 if (!env->me_rpcheck)
5926 env->me_rpcheck = 1;
5927 while (env->me_rpcheck < el[0].mid && env->me_rpcheck < MDB_ERPAGE_SIZE/2)
5928 env->me_rpcheck *= 2;
5931 SET_OFF(off, pgno * env->me_psize);
5932 MAP(rc, env, id3.mptr, len, off);
5935 pthread_mutex_unlock(&env->me_rpmutex);
5938 /* check for overflow size */
5939 p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
5940 if (IS_OVERFLOW(p) && p->mp_pages + rem > id3.mcnt) {
5941 id3.mcnt = p->mp_pages + rem;
5942 munmap(id3.mptr, len);
5943 len = id3.mcnt * env->me_psize;
5944 MAP(rc, env, id3.mptr, len, off);
5948 mdb_mid3l_insert(el, &id3);
5949 pthread_mutex_unlock(&env->me_rpmutex);
5951 mdb_mid3l_insert(tl, &id3);
5953 return MDB_TXN_FULL;
5956 p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
5957 #if MDB_DEBUG /* we don't need this check any more */
5958 if (IS_OVERFLOW(p)) {
5959 mdb_tassert(txn, p->mp_pages + rem <= id3.mcnt);
5967 /** Find the address of the page corresponding to a given page number.
5968 * @param[in] mc the cursor accessing the page.
5969 * @param[in] pgno the page number for the page to retrieve.
5970 * @param[out] ret address of a pointer where the page's address will be stored.
5971 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
5972 * @return 0 on success, non-zero on failure.
5975 mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **ret, int *lvl)
5977 MDB_txn *txn = mc->mc_txn;
5981 if (! (mc->mc_flags & (C_ORIG_RDONLY|C_WRITEMAP))) {
5985 MDB_ID2L dl = tx2->mt_u.dirty_list;
5987 /* Spilled pages were dirtied in this txn and flushed
5988 * because the dirty list got full. Bring this page
5989 * back in from the map (but don't unspill it here,
5990 * leave that unless page_touch happens again).
5992 if (tx2->mt_spill_pgs) {
5993 MDB_ID pn = pgno << 1;
5994 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
5995 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
6000 unsigned x = mdb_mid2l_search(dl, pgno);
6001 if (x <= dl[0].mid && dl[x].mid == pgno) {
6007 } while ((tx2 = tx2->mt_parent) != NULL);
6010 if (pgno >= txn->mt_next_pgno) {
6011 DPRINTF(("page %"Yu" not found", pgno));
6012 txn->mt_flags |= MDB_TXN_ERROR;
6013 return MDB_PAGE_NOTFOUND;
6021 int rc = mdb_rpage_get(txn, pgno, &p);
6025 MDB_env *env = txn->mt_env;
6026 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
6037 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
6038 * The cursor is at the root page, set up the rest of it.
6041 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
6043 MDB_page *mp = mc->mc_pg[mc->mc_top];
6047 while (IS_BRANCH(mp)) {
6051 DPRINTF(("branch page %"Yu" has %u keys", mp->mp_pgno, NUMKEYS(mp)));
6052 /* Don't assert on branch pages in the FreeDB. We can get here
6053 * while in the process of rebalancing a FreeDB branch page; we must
6054 * let that proceed. ITS#8336
6056 mdb_cassert(mc, !mc->mc_dbi || NUMKEYS(mp) > 1);
6057 DPRINTF(("found index 0 to page %"Yu, NODEPGNO(NODEPTR(mp, 0))));
6059 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
6061 if (flags & MDB_PS_LAST)
6062 i = NUMKEYS(mp) - 1;
6065 node = mdb_node_search(mc, key, &exact);
6067 i = NUMKEYS(mp) - 1;
6069 i = mc->mc_ki[mc->mc_top];
6071 mdb_cassert(mc, i > 0);
6075 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
6078 mdb_cassert(mc, i < NUMKEYS(mp));
6079 node = NODEPTR(mp, i);
6081 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
6084 mc->mc_ki[mc->mc_top] = i;
6085 if ((rc = mdb_cursor_push(mc, mp)))
6088 if (flags & MDB_PS_MODIFY) {
6089 if ((rc = mdb_page_touch(mc)) != 0)
6091 mp = mc->mc_pg[mc->mc_top];
6096 DPRINTF(("internal error, index points to a %02X page!?",
6098 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6099 return MDB_CORRUPTED;
6102 DPRINTF(("found leaf page %"Yu" for key [%s]", mp->mp_pgno,
6103 key ? DKEY(key) : "null"));
6104 mc->mc_flags |= C_INITIALIZED;
6105 mc->mc_flags &= ~C_EOF;
6110 /** Search for the lowest key under the current branch page.
6111 * This just bypasses a NUMKEYS check in the current page
6112 * before calling mdb_page_search_root(), because the callers
6113 * are all in situations where the current page is known to
6117 mdb_page_search_lowest(MDB_cursor *mc)
6119 MDB_page *mp = mc->mc_pg[mc->mc_top];
6120 MDB_node *node = NODEPTR(mp, 0);
6123 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
6126 mc->mc_ki[mc->mc_top] = 0;
6127 if ((rc = mdb_cursor_push(mc, mp)))
6129 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
6132 /** Search for the page a given key should be in.
6133 * Push it and its parent pages on the cursor stack.
6134 * @param[in,out] mc the cursor for this operation.
6135 * @param[in] key the key to search for, or NULL for first/last page.
6136 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
6137 * are touched (updated with new page numbers).
6138 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
6139 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
6140 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
6141 * @return 0 on success, non-zero on failure.
6144 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
6149 /* Make sure the txn is still viable, then find the root from
6150 * the txn's db table and set it as the root of the cursor's stack.
6152 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED) {
6153 DPUTS("transaction may not be used now");
6156 /* Make sure we're using an up-to-date root */
6157 if (*mc->mc_dbflag & DB_STALE) {
6159 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
6161 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
6162 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
6169 MDB_node *leaf = mdb_node_search(&mc2,
6170 &mc->mc_dbx->md_name, &exact);
6172 return MDB_NOTFOUND;
6173 if ((leaf->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
6174 return MDB_INCOMPATIBLE; /* not a named DB */
6175 rc = mdb_node_read(&mc2, leaf, &data);
6178 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
6180 /* The txn may not know this DBI, or another process may
6181 * have dropped and recreated the DB with other flags.
6183 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
6184 return MDB_INCOMPATIBLE;
6185 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
6187 *mc->mc_dbflag &= ~DB_STALE;
6189 root = mc->mc_db->md_root;
6191 if (root == P_INVALID) { /* Tree is empty. */
6192 DPUTS("tree is empty");
6193 return MDB_NOTFOUND;
6197 mdb_cassert(mc, root > 1);
6198 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root) {
6201 MDB_PAGE_UNREF(mc->mc_txn, mc->mc_pg[0]);
6203 if ((rc = mdb_page_get(mc, root, &mc->mc_pg[0], NULL)) != 0)
6210 for (i=1; i<mc->mc_snum; i++)
6211 MDB_PAGE_UNREF(mc->mc_txn, mc->mc_pg[i]);
6217 DPRINTF(("db %d root page %"Yu" has flags 0x%X",
6218 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
6220 if (flags & MDB_PS_MODIFY) {
6221 if ((rc = mdb_page_touch(mc)))
6225 if (flags & MDB_PS_ROOTONLY)
6228 return mdb_page_search_root(mc, key, flags);
6232 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
6234 MDB_txn *txn = mc->mc_txn;
6235 pgno_t pg = mp->mp_pgno;
6236 unsigned x = 0, ovpages = mp->mp_pages;
6237 MDB_env *env = txn->mt_env;
6238 MDB_IDL sl = txn->mt_spill_pgs;
6239 MDB_ID pn = pg << 1;
6242 DPRINTF(("free ov page %"Yu" (%d)", pg, ovpages));
6243 /* If the page is dirty or on the spill list we just acquired it,
6244 * so we should give it back to our current free list, if any.
6245 * Otherwise put it onto the list of pages we freed in this txn.
6247 * Won't create me_pghead: me_pglast must be inited along with it.
6248 * Unsupported in nested txns: They would need to hide the page
6249 * range in ancestor txns' dirty and spilled lists.
6251 if (env->me_pghead &&
6253 ((mp->mp_flags & P_DIRTY) ||
6254 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
6258 MDB_ID2 *dl, ix, iy;
6259 rc = mdb_midl_need(&env->me_pghead, ovpages);
6262 if (!(mp->mp_flags & P_DIRTY)) {
6263 /* This page is no longer spilled */
6270 /* Remove from dirty list */
6271 dl = txn->mt_u.dirty_list;
6273 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
6279 mdb_cassert(mc, x > 1);
6281 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
6282 txn->mt_flags |= MDB_TXN_ERROR;
6286 txn->mt_dirty_room++;
6287 if (!(env->me_flags & MDB_WRITEMAP))
6288 mdb_dpage_free(env, mp);
6290 /* Insert in me_pghead */
6291 mop = env->me_pghead;
6292 j = mop[0] + ovpages;
6293 for (i = mop[0]; i && mop[i] < pg; i--)
6299 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
6303 mc->mc_db->md_overflow_pages -= ovpages;
6307 /** Return the data associated with a given node.
6308 * @param[in] mc The cursor for this operation.
6309 * @param[in] leaf The node being read.
6310 * @param[out] data Updated to point to the node's data.
6311 * @return 0 on success, non-zero on failure.
6314 mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data)
6316 MDB_page *omp; /* overflow page */
6321 MDB_PAGE_UNREF(mc->mc_txn, MC_OVPG(mc));
6322 MC_SET_OVPG(mc, NULL);
6324 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6325 data->mv_size = NODEDSZ(leaf);
6326 data->mv_data = NODEDATA(leaf);
6330 /* Read overflow data.
6332 data->mv_size = NODEDSZ(leaf);
6333 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
6334 if ((rc = mdb_page_get(mc, pgno, &omp, NULL)) != 0) {
6335 DPRINTF(("read overflow page %"Yu" failed", pgno));
6338 data->mv_data = METADATA(omp);
6339 MC_SET_OVPG(mc, omp);
6345 mdb_get(MDB_txn *txn, MDB_dbi dbi,
6346 MDB_val *key, MDB_val *data)
6353 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
6355 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
6358 if (txn->mt_flags & MDB_TXN_BLOCKED)
6361 mdb_cursor_init(&mc, txn, dbi, &mx);
6362 rc = mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
6363 /* unref all the pages when MDB_VL32 - caller must copy the data
6364 * before doing anything else
6366 MDB_CURSOR_UNREF(&mc, 1);
6370 /** Find a sibling for a page.
6371 * Replaces the page at the top of the cursor's stack with the
6372 * specified sibling, if one exists.
6373 * @param[in] mc The cursor for this operation.
6374 * @param[in] move_right Non-zero if the right sibling is requested,
6375 * otherwise the left sibling.
6376 * @return 0 on success, non-zero on failure.
6379 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
6388 if (mc->mc_snum < 2) {
6389 return MDB_NOTFOUND; /* root has no siblings */
6393 op = mc->mc_pg[mc->mc_top];
6396 DPRINTF(("parent page is page %"Yu", index %u",
6397 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
6399 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6400 : (mc->mc_ki[mc->mc_top] == 0)) {
6401 DPRINTF(("no more keys left, moving to %s sibling",
6402 move_right ? "right" : "left"));
6403 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
6404 /* undo cursor_pop before returning */
6411 mc->mc_ki[mc->mc_top]++;
6413 mc->mc_ki[mc->mc_top]--;
6414 DPRINTF(("just moving to %s index key %u",
6415 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
6417 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
6419 MDB_PAGE_UNREF(mc->mc_txn, op);
6421 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6422 if ((rc = mdb_page_get(mc, NODEPGNO(indx), &mp, NULL)) != 0) {
6423 /* mc will be inconsistent if caller does mc_snum++ as above */
6424 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
6428 mdb_cursor_push(mc, mp);
6430 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
6435 /** Move the cursor to the next data item. */
6437 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
6443 if ((mc->mc_flags & C_EOF) ||
6444 ((mc->mc_flags & C_DEL) && op == MDB_NEXT_DUP)) {
6445 return MDB_NOTFOUND;
6447 if (!(mc->mc_flags & C_INITIALIZED))
6448 return mdb_cursor_first(mc, key, data);
6450 mp = mc->mc_pg[mc->mc_top];
6452 if (mc->mc_db->md_flags & MDB_DUPSORT) {
6453 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6454 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6455 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
6456 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
6457 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
6458 if (rc == MDB_SUCCESS)
6459 MDB_GET_KEY(leaf, key);
6464 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
6467 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6468 if (op == MDB_NEXT_DUP)
6469 return MDB_NOTFOUND;
6473 DPRINTF(("cursor_next: top page is %"Yu" in cursor %p",
6474 mdb_dbg_pgno(mp), (void *) mc));
6475 if (mc->mc_flags & C_DEL) {
6476 mc->mc_flags ^= C_DEL;
6480 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
6481 DPUTS("=====> move to next sibling page");
6482 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
6483 mc->mc_flags |= C_EOF;
6486 mp = mc->mc_pg[mc->mc_top];
6487 DPRINTF(("next page is %"Yu", key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
6489 mc->mc_ki[mc->mc_top]++;
6492 DPRINTF(("==> cursor points to page %"Yu" with %u keys, key index %u",
6493 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
6496 key->mv_size = mc->mc_db->md_pad;
6497 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6501 mdb_cassert(mc, IS_LEAF(mp));
6502 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6504 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6505 mdb_xcursor_init1(mc, leaf);
6508 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6511 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6512 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6513 if (rc != MDB_SUCCESS)
6518 MDB_GET_KEY(leaf, key);
6522 /** Move the cursor to the previous data item. */
6524 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
6530 if (!(mc->mc_flags & C_INITIALIZED)) {
6531 rc = mdb_cursor_last(mc, key, data);
6534 mc->mc_ki[mc->mc_top]++;
6537 mp = mc->mc_pg[mc->mc_top];
6539 if (mc->mc_db->md_flags & MDB_DUPSORT) {
6540 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6541 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6542 if (op == MDB_PREV || op == MDB_PREV_DUP) {
6543 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
6544 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
6545 if (rc == MDB_SUCCESS) {
6546 MDB_GET_KEY(leaf, key);
6547 mc->mc_flags &= ~C_EOF;
6553 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
6556 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6557 if (op == MDB_PREV_DUP)
6558 return MDB_NOTFOUND;
6562 DPRINTF(("cursor_prev: top page is %"Yu" in cursor %p",
6563 mdb_dbg_pgno(mp), (void *) mc));
6565 mc->mc_flags &= ~(C_EOF|C_DEL);
6567 if (mc->mc_ki[mc->mc_top] == 0) {
6568 DPUTS("=====> move to prev sibling page");
6569 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
6572 mp = mc->mc_pg[mc->mc_top];
6573 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
6574 DPRINTF(("prev page is %"Yu", key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
6576 mc->mc_ki[mc->mc_top]--;
6578 mc->mc_flags &= ~C_EOF;
6580 DPRINTF(("==> cursor points to page %"Yu" with %u keys, key index %u",
6581 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
6584 key->mv_size = mc->mc_db->md_pad;
6585 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6589 mdb_cassert(mc, IS_LEAF(mp));
6590 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6592 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6593 mdb_xcursor_init1(mc, leaf);
6596 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6599 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6600 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
6601 if (rc != MDB_SUCCESS)
6606 MDB_GET_KEY(leaf, key);
6610 /** Set the cursor on a specific data item. */
6612 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6613 MDB_cursor_op op, int *exactp)
6617 MDB_node *leaf = NULL;
6620 if (key->mv_size == 0)
6621 return MDB_BAD_VALSIZE;
6623 if (mc->mc_xcursor) {
6624 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
6625 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6628 /* See if we're already on the right page */
6629 if (mc->mc_flags & C_INITIALIZED) {
6632 mp = mc->mc_pg[mc->mc_top];
6634 mc->mc_ki[mc->mc_top] = 0;
6635 return MDB_NOTFOUND;
6637 if (mp->mp_flags & P_LEAF2) {
6638 nodekey.mv_size = mc->mc_db->md_pad;
6639 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
6641 leaf = NODEPTR(mp, 0);
6642 MDB_GET_KEY2(leaf, nodekey);
6644 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6646 /* Probably happens rarely, but first node on the page
6647 * was the one we wanted.
6649 mc->mc_ki[mc->mc_top] = 0;
6656 unsigned int nkeys = NUMKEYS(mp);
6658 if (mp->mp_flags & P_LEAF2) {
6659 nodekey.mv_data = LEAF2KEY(mp,
6660 nkeys-1, nodekey.mv_size);
6662 leaf = NODEPTR(mp, nkeys-1);
6663 MDB_GET_KEY2(leaf, nodekey);
6665 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6667 /* last node was the one we wanted */
6668 mc->mc_ki[mc->mc_top] = nkeys-1;
6674 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
6675 /* This is definitely the right page, skip search_page */
6676 if (mp->mp_flags & P_LEAF2) {
6677 nodekey.mv_data = LEAF2KEY(mp,
6678 mc->mc_ki[mc->mc_top], nodekey.mv_size);
6680 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6681 MDB_GET_KEY2(leaf, nodekey);
6683 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6685 /* current node was the one we wanted */
6695 /* If any parents have right-sibs, search.
6696 * Otherwise, there's nothing further.
6698 for (i=0; i<mc->mc_top; i++)
6700 NUMKEYS(mc->mc_pg[i])-1)
6702 if (i == mc->mc_top) {
6703 /* There are no other pages */
6704 mc->mc_ki[mc->mc_top] = nkeys;
6705 return MDB_NOTFOUND;
6709 /* There are no other pages */
6710 mc->mc_ki[mc->mc_top] = 0;
6711 if (op == MDB_SET_RANGE && !exactp) {
6715 return MDB_NOTFOUND;
6721 rc = mdb_page_search(mc, key, 0);
6722 if (rc != MDB_SUCCESS)
6725 mp = mc->mc_pg[mc->mc_top];
6726 mdb_cassert(mc, IS_LEAF(mp));
6729 leaf = mdb_node_search(mc, key, exactp);
6730 if (exactp != NULL && !*exactp) {
6731 /* MDB_SET specified and not an exact match. */
6732 return MDB_NOTFOUND;
6736 DPUTS("===> inexact leaf not found, goto sibling");
6737 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
6738 mc->mc_flags |= C_EOF;
6739 return rc; /* no entries matched */
6741 mp = mc->mc_pg[mc->mc_top];
6742 mdb_cassert(mc, IS_LEAF(mp));
6743 leaf = NODEPTR(mp, 0);
6747 mc->mc_flags |= C_INITIALIZED;
6748 mc->mc_flags &= ~C_EOF;
6751 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
6752 key->mv_size = mc->mc_db->md_pad;
6753 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6758 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6759 mdb_xcursor_init1(mc, leaf);
6762 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6763 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
6764 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6767 if (op == MDB_GET_BOTH) {
6773 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
6774 if (rc != MDB_SUCCESS)
6777 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
6780 if ((rc = mdb_node_read(mc, leaf, &olddata)) != MDB_SUCCESS)
6782 dcmp = mc->mc_dbx->md_dcmp;
6783 if (NEED_CMP_CLONG(dcmp, olddata.mv_size))
6784 dcmp = mdb_cmp_clong;
6785 rc = dcmp(data, &olddata);
6787 if (op == MDB_GET_BOTH || rc > 0)
6788 return MDB_NOTFOUND;
6795 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6796 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6801 /* The key already matches in all other cases */
6802 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
6803 MDB_GET_KEY(leaf, key);
6804 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
6809 /** Move the cursor to the first item in the database. */
6811 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6816 if (mc->mc_xcursor) {
6817 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
6818 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6821 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6822 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
6823 if (rc != MDB_SUCCESS)
6826 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6828 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
6829 mc->mc_flags |= C_INITIALIZED;
6830 mc->mc_flags &= ~C_EOF;
6832 mc->mc_ki[mc->mc_top] = 0;
6834 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6835 key->mv_size = mc->mc_db->md_pad;
6836 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
6841 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6842 mdb_xcursor_init1(mc, leaf);
6843 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6847 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6851 MDB_GET_KEY(leaf, key);
6855 /** Move the cursor to the last item in the database. */
6857 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6862 if (mc->mc_xcursor) {
6863 MDB_CURSOR_UNREF(&mc->mc_xcursor->mx_cursor, 0);
6864 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6867 if (!(mc->mc_flags & C_EOF)) {
6869 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6870 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
6871 if (rc != MDB_SUCCESS)
6874 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6877 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
6878 mc->mc_flags |= C_INITIALIZED|C_EOF;
6879 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6881 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6882 key->mv_size = mc->mc_db->md_pad;
6883 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
6888 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6889 mdb_xcursor_init1(mc, leaf);
6890 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
6894 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6899 MDB_GET_KEY(leaf, key);
6904 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6909 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
6914 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
6918 case MDB_GET_CURRENT:
6919 if (!(mc->mc_flags & C_INITIALIZED)) {
6922 MDB_page *mp = mc->mc_pg[mc->mc_top];
6923 int nkeys = NUMKEYS(mp);
6924 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
6925 mc->mc_ki[mc->mc_top] = nkeys;
6931 key->mv_size = mc->mc_db->md_pad;
6932 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6934 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6935 MDB_GET_KEY(leaf, key);
6937 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6938 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
6940 rc = mdb_node_read(mc, leaf, data);
6947 case MDB_GET_BOTH_RANGE:
6952 if (mc->mc_xcursor == NULL) {
6953 rc = MDB_INCOMPATIBLE;
6963 rc = mdb_cursor_set(mc, key, data, op,
6964 op == MDB_SET_RANGE ? NULL : &exact);
6967 case MDB_GET_MULTIPLE:
6968 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
6972 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6973 rc = MDB_INCOMPATIBLE;
6977 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
6978 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
6981 case MDB_NEXT_MULTIPLE:
6986 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6987 rc = MDB_INCOMPATIBLE;
6990 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
6991 if (rc == MDB_SUCCESS) {
6992 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6995 mx = &mc->mc_xcursor->mx_cursor;
6996 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
6998 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
6999 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
7005 case MDB_PREV_MULTIPLE:
7010 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7011 rc = MDB_INCOMPATIBLE;
7014 if (!(mc->mc_flags & C_INITIALIZED))
7015 rc = mdb_cursor_last(mc, key, data);
7018 if (rc == MDB_SUCCESS) {
7019 MDB_cursor *mx = &mc->mc_xcursor->mx_cursor;
7020 if (mx->mc_flags & C_INITIALIZED) {
7021 rc = mdb_cursor_sibling(mx, 0);
7022 if (rc == MDB_SUCCESS)
7031 case MDB_NEXT_NODUP:
7032 rc = mdb_cursor_next(mc, key, data, op);
7036 case MDB_PREV_NODUP:
7037 rc = mdb_cursor_prev(mc, key, data, op);
7040 rc = mdb_cursor_first(mc, key, data);
7043 mfunc = mdb_cursor_first;
7045 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
7049 if (mc->mc_xcursor == NULL) {
7050 rc = MDB_INCOMPATIBLE;
7054 MDB_node *leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7055 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7056 MDB_GET_KEY(leaf, key);
7057 rc = mdb_node_read(mc, leaf, data);
7061 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
7065 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
7068 rc = mdb_cursor_last(mc, key, data);
7071 mfunc = mdb_cursor_last;
7074 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
7079 if (mc->mc_flags & C_DEL)
7080 mc->mc_flags ^= C_DEL;
7085 /** Touch all the pages in the cursor stack. Set mc_top.
7086 * Makes sure all the pages are writable, before attempting a write operation.
7087 * @param[in] mc The cursor to operate on.
7090 mdb_cursor_touch(MDB_cursor *mc)
7092 int rc = MDB_SUCCESS;
7094 if (mc->mc_dbi >= CORE_DBS && !(*mc->mc_dbflag & DB_DIRTY)) {
7097 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
7099 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
7100 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
7103 *mc->mc_dbflag |= DB_DIRTY;
7108 rc = mdb_page_touch(mc);
7109 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
7110 mc->mc_top = mc->mc_snum-1;
7115 /** Do not spill pages to disk if txn is getting full, may fail instead */
7116 #define MDB_NOSPILL 0x8000
7119 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
7123 MDB_node *leaf = NULL;
7124 MDB_page *fp, *mp, *sub_root = NULL;
7126 MDB_val xdata, *rdata, dkey, olddata;
7128 int do_sub = 0, insert_key, insert_data;
7129 unsigned int mcount = 0, dcount = 0, nospill;
7132 unsigned int nflags;
7135 if (mc == NULL || key == NULL)
7138 env = mc->mc_txn->mt_env;
7140 /* Check this first so counter will always be zero on any
7143 if (flags & MDB_MULTIPLE) {
7144 dcount = data[1].mv_size;
7145 data[1].mv_size = 0;
7146 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
7147 return MDB_INCOMPATIBLE;
7150 nospill = flags & MDB_NOSPILL;
7151 flags &= ~MDB_NOSPILL;
7153 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
7154 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7156 if (key->mv_size-1 >= ENV_MAXKEY(env))
7157 return MDB_BAD_VALSIZE;
7159 #if SIZE_MAX > MAXDATASIZE
7160 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
7161 return MDB_BAD_VALSIZE;
7163 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
7164 return MDB_BAD_VALSIZE;
7167 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
7168 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
7172 if (flags == MDB_CURRENT) {
7173 if (!(mc->mc_flags & C_INITIALIZED))
7176 } else if (mc->mc_db->md_root == P_INVALID) {
7177 /* new database, cursor has nothing to point to */
7180 mc->mc_flags &= ~C_INITIALIZED;
7185 if (flags & MDB_APPEND) {
7187 rc = mdb_cursor_last(mc, &k2, &d2);
7189 rc = mc->mc_dbx->md_cmp(key, &k2);
7192 mc->mc_ki[mc->mc_top]++;
7194 /* new key is <= last key */
7199 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
7201 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
7202 DPRINTF(("duplicate key [%s]", DKEY(key)));
7204 return MDB_KEYEXIST;
7206 if (rc && rc != MDB_NOTFOUND)
7210 if (mc->mc_flags & C_DEL)
7211 mc->mc_flags ^= C_DEL;
7213 /* Cursor is positioned, check for room in the dirty list */
7215 if (flags & MDB_MULTIPLE) {
7217 xdata.mv_size = data->mv_size * dcount;
7221 if ((rc2 = mdb_page_spill(mc, key, rdata)))
7225 if (rc == MDB_NO_ROOT) {
7227 /* new database, write a root leaf page */
7228 DPUTS("allocating new root leaf page");
7229 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
7232 mdb_cursor_push(mc, np);
7233 mc->mc_db->md_root = np->mp_pgno;
7234 mc->mc_db->md_depth++;
7235 *mc->mc_dbflag |= DB_DIRTY;
7236 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
7238 np->mp_flags |= P_LEAF2;
7239 mc->mc_flags |= C_INITIALIZED;
7241 /* make sure all cursor pages are writable */
7242 rc2 = mdb_cursor_touch(mc);
7247 insert_key = insert_data = rc;
7249 /* The key does not exist */
7250 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
7251 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
7252 LEAFSIZE(key, data) > env->me_nodemax)
7254 /* Too big for a node, insert in sub-DB. Set up an empty
7255 * "old sub-page" for prep_subDB to expand to a full page.
7257 fp_flags = P_LEAF|P_DIRTY;
7259 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
7260 fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
7261 olddata.mv_size = PAGEHDRSZ;
7265 /* there's only a key anyway, so this is a no-op */
7266 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
7268 unsigned int ksize = mc->mc_db->md_pad;
7269 if (key->mv_size != ksize)
7270 return MDB_BAD_VALSIZE;
7271 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
7272 memcpy(ptr, key->mv_data, ksize);
7274 /* if overwriting slot 0 of leaf, need to
7275 * update branch key if there is a parent page
7277 if (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
7278 unsigned short dtop = 1;
7280 /* slot 0 is always an empty key, find real slot */
7281 while (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
7285 if (mc->mc_ki[mc->mc_top])
7286 rc2 = mdb_update_key(mc, key);
7297 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7298 olddata.mv_size = NODEDSZ(leaf);
7299 olddata.mv_data = NODEDATA(leaf);
7302 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
7303 /* Prepare (sub-)page/sub-DB to accept the new item,
7304 * if needed. fp: old sub-page or a header faking
7305 * it. mp: new (sub-)page. offset: growth in page
7306 * size. xdata: node data with new page or DB.
7308 unsigned i, offset = 0;
7309 mp = fp = xdata.mv_data = env->me_pbuf;
7310 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
7312 /* Was a single item before, must convert now */
7313 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7315 /* Just overwrite the current item */
7316 if (flags == MDB_CURRENT)
7318 dcmp = mc->mc_dbx->md_dcmp;
7319 if (NEED_CMP_CLONG(dcmp, olddata.mv_size))
7320 dcmp = mdb_cmp_clong;
7321 /* does data match? */
7322 if (!dcmp(data, &olddata)) {
7323 if (flags & (MDB_NODUPDATA|MDB_APPENDDUP))
7324 return MDB_KEYEXIST;
7329 /* Back up original data item */
7330 dkey.mv_size = olddata.mv_size;
7331 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
7333 /* Make sub-page header for the dup items, with dummy body */
7334 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
7335 fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
7336 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
7337 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7338 fp->mp_flags |= P_LEAF2;
7339 fp->mp_pad = data->mv_size;
7340 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
7342 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
7343 (dkey.mv_size & 1) + (data->mv_size & 1);
7345 fp->mp_upper = xdata.mv_size - PAGEBASE;
7346 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
7347 } else if (leaf->mn_flags & F_SUBDATA) {
7348 /* Data is on sub-DB, just store it */
7349 flags |= F_DUPDATA|F_SUBDATA;
7352 /* Data is on sub-page */
7353 fp = olddata.mv_data;
7356 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7357 offset = EVEN(NODESIZE + sizeof(indx_t) +
7361 offset = fp->mp_pad;
7362 if (SIZELEFT(fp) < offset) {
7363 offset *= 4; /* space for 4 more */
7366 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
7368 fp->mp_flags |= P_DIRTY;
7369 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
7370 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
7374 xdata.mv_size = olddata.mv_size + offset;
7377 fp_flags = fp->mp_flags;
7378 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
7379 /* Too big for a sub-page, convert to sub-DB */
7380 fp_flags &= ~P_SUBP;
7382 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7383 fp_flags |= P_LEAF2;
7384 dummy.md_pad = fp->mp_pad;
7385 dummy.md_flags = MDB_DUPFIXED;
7386 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
7387 dummy.md_flags |= MDB_INTEGERKEY;
7393 dummy.md_branch_pages = 0;
7394 dummy.md_leaf_pages = 1;
7395 dummy.md_overflow_pages = 0;
7396 dummy.md_entries = NUMKEYS(fp);
7397 xdata.mv_size = sizeof(MDB_db);
7398 xdata.mv_data = &dummy;
7399 if ((rc = mdb_page_alloc(mc, 1, &mp)))
7401 offset = env->me_psize - olddata.mv_size;
7402 flags |= F_DUPDATA|F_SUBDATA;
7403 dummy.md_root = mp->mp_pgno;
7407 mp->mp_flags = fp_flags | P_DIRTY;
7408 mp->mp_pad = fp->mp_pad;
7409 mp->mp_lower = fp->mp_lower;
7410 mp->mp_upper = fp->mp_upper + offset;
7411 if (fp_flags & P_LEAF2) {
7412 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
7414 memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
7415 olddata.mv_size - fp->mp_upper - PAGEBASE);
7416 for (i=0; i<NUMKEYS(fp); i++)
7417 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
7425 mdb_node_del(mc, 0);
7429 /* LMDB passes F_SUBDATA in 'flags' to write a DB record */
7430 if ((leaf->mn_flags ^ flags) & F_SUBDATA)
7431 return MDB_INCOMPATIBLE;
7432 /* overflow page overwrites need special handling */
7433 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7436 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
7438 memcpy(&pg, olddata.mv_data, sizeof(pg));
7439 if ((rc2 = mdb_page_get(mc, pg, &omp, &level)) != 0)
7441 ovpages = omp->mp_pages;
7443 /* Is the ov page large enough? */
7444 if (ovpages >= dpages) {
7445 if (!(omp->mp_flags & P_DIRTY) &&
7446 (level || (env->me_flags & MDB_WRITEMAP)))
7448 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
7451 level = 0; /* dirty in this txn or clean */
7454 if (omp->mp_flags & P_DIRTY) {
7455 /* yes, overwrite it. Note in this case we don't
7456 * bother to try shrinking the page if the new data
7457 * is smaller than the overflow threshold.
7460 /* It is writable only in a parent txn */
7461 size_t sz = (size_t) env->me_psize * ovpages, off;
7462 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
7468 /* Note - this page is already counted in parent's dirty_room */
7469 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
7470 mdb_cassert(mc, rc2 == 0);
7471 /* Currently we make the page look as with put() in the
7472 * parent txn, in case the user peeks at MDB_RESERVEd
7473 * or unused parts. Some users treat ovpages specially.
7475 if (!(flags & MDB_RESERVE)) {
7476 /* Skip the part where LMDB will put *data.
7477 * Copy end of page, adjusting alignment so
7478 * compiler may copy words instead of bytes.
7480 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
7481 memcpy((size_t *)((char *)np + off),
7482 (size_t *)((char *)omp + off), sz - off);
7485 memcpy(np, omp, sz); /* Copy beginning of page */
7488 SETDSZ(leaf, data->mv_size);
7489 if (F_ISSET(flags, MDB_RESERVE))
7490 data->mv_data = METADATA(omp);
7492 memcpy(METADATA(omp), data->mv_data, data->mv_size);
7496 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
7498 } else if (data->mv_size == olddata.mv_size) {
7499 /* same size, just replace it. Note that we could
7500 * also reuse this node if the new data is smaller,
7501 * but instead we opt to shrink the node in that case.
7503 if (F_ISSET(flags, MDB_RESERVE))
7504 data->mv_data = olddata.mv_data;
7505 else if (!(mc->mc_flags & C_SUB))
7506 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
7508 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
7513 mdb_node_del(mc, 0);
7519 nflags = flags & NODE_ADD_FLAGS;
7520 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
7521 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
7522 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
7523 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
7525 nflags |= MDB_SPLIT_REPLACE;
7526 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
7528 /* There is room already in this leaf page. */
7529 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
7531 /* Adjust other cursors pointing to mp */
7532 MDB_cursor *m2, *m3;
7533 MDB_dbi dbi = mc->mc_dbi;
7534 unsigned i = mc->mc_top;
7535 MDB_page *mp = mc->mc_pg[i];
7537 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7538 if (mc->mc_flags & C_SUB)
7539 m3 = &m2->mc_xcursor->mx_cursor;
7542 if (m3 == mc || m3->mc_snum < mc->mc_snum || m3->mc_pg[i] != mp) continue;
7543 if (m3->mc_ki[i] >= mc->mc_ki[i] && insert_key) {
7546 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
7547 MDB_node *n2 = NODEPTR(mp, m3->mc_ki[i]);
7548 if ((n2->mn_flags & (F_SUBDATA|F_DUPDATA)) == F_DUPDATA)
7549 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
7555 if (rc == MDB_SUCCESS) {
7556 /* Now store the actual data in the child DB. Note that we're
7557 * storing the user data in the keys field, so there are strict
7558 * size limits on dupdata. The actual data fields of the child
7559 * DB are all zero size.
7562 int xflags, new_dupdata;
7567 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7568 if (flags & MDB_CURRENT) {
7569 xflags = MDB_CURRENT|MDB_NOSPILL;
7571 mdb_xcursor_init1(mc, leaf);
7572 xflags = (flags & MDB_NODUPDATA) ?
7573 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
7576 mc->mc_xcursor->mx_cursor.mc_pg[0] = sub_root;
7577 new_dupdata = (int)dkey.mv_size;
7578 /* converted, write the original data first */
7580 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
7583 /* we've done our job */
7586 if (!(leaf->mn_flags & F_SUBDATA) || sub_root) {
7587 /* Adjust other cursors pointing to mp */
7589 MDB_xcursor *mx = mc->mc_xcursor;
7590 unsigned i = mc->mc_top;
7591 MDB_page *mp = mc->mc_pg[i];
7592 int nkeys = NUMKEYS(mp);
7594 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
7595 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
7596 if (!(m2->mc_flags & C_INITIALIZED)) continue;
7597 if (m2->mc_pg[i] == mp) {
7598 if (m2->mc_ki[i] == mc->mc_ki[i]) {
7599 mdb_xcursor_init2(m2, mx, new_dupdata);
7600 } else if (!insert_key && m2->mc_ki[i] < nkeys) {
7601 MDB_node *n2 = NODEPTR(mp, m2->mc_ki[i]);
7602 if ((n2->mn_flags & (F_SUBDATA|F_DUPDATA)) == F_DUPDATA)
7603 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
7608 ecount = mc->mc_xcursor->mx_db.md_entries;
7609 if (flags & MDB_APPENDDUP)
7610 xflags |= MDB_APPEND;
7611 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
7612 if (flags & F_SUBDATA) {
7613 void *db = NODEDATA(leaf);
7614 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
7616 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
7618 /* Increment count unless we just replaced an existing item. */
7620 mc->mc_db->md_entries++;
7622 /* Invalidate txn if we created an empty sub-DB */
7625 /* If we succeeded and the key didn't exist before,
7626 * make sure the cursor is marked valid.
7628 mc->mc_flags |= C_INITIALIZED;
7630 if (flags & MDB_MULTIPLE) {
7633 /* let caller know how many succeeded, if any */
7634 data[1].mv_size = mcount;
7635 if (mcount < dcount) {
7636 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
7637 insert_key = insert_data = 0;
7644 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
7647 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7652 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
7658 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
7659 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7661 if (!(mc->mc_flags & C_INITIALIZED))
7664 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
7665 return MDB_NOTFOUND;
7667 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
7670 rc = mdb_cursor_touch(mc);
7674 mp = mc->mc_pg[mc->mc_top];
7677 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7679 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7680 if (flags & MDB_NODUPDATA) {
7681 /* mdb_cursor_del0() will subtract the final entry */
7682 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
7683 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
7685 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
7686 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
7688 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
7691 /* If sub-DB still has entries, we're done */
7692 if (mc->mc_xcursor->mx_db.md_entries) {
7693 if (leaf->mn_flags & F_SUBDATA) {
7694 /* update subDB info */
7695 void *db = NODEDATA(leaf);
7696 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
7699 /* shrink fake page */
7700 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
7701 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7702 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
7703 /* fix other sub-DB cursors pointed at fake pages on this page */
7704 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
7705 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
7706 if (!(m2->mc_flags & C_INITIALIZED)) continue;
7707 if (m2->mc_pg[mc->mc_top] == mp) {
7708 if (m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top]) {
7709 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
7711 MDB_node *n2 = NODEPTR(mp, m2->mc_ki[mc->mc_top]);
7712 if (!(n2->mn_flags & F_SUBDATA))
7713 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
7718 mc->mc_db->md_entries--;
7721 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
7723 /* otherwise fall thru and delete the sub-DB */
7726 if (leaf->mn_flags & F_SUBDATA) {
7727 /* add all the child DB's pages to the free list */
7728 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
7733 /* LMDB passes F_SUBDATA in 'flags' to delete a DB record */
7734 else if ((leaf->mn_flags ^ flags) & F_SUBDATA) {
7735 rc = MDB_INCOMPATIBLE;
7739 /* add overflow pages to free list */
7740 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7744 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
7745 if ((rc = mdb_page_get(mc, pg, &omp, NULL)) ||
7746 (rc = mdb_ovpage_free(mc, omp)))
7751 return mdb_cursor_del0(mc);
7754 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7758 /** Allocate and initialize new pages for a database.
7759 * @param[in] mc a cursor on the database being added to.
7760 * @param[in] flags flags defining what type of page is being allocated.
7761 * @param[in] num the number of pages to allocate. This is usually 1,
7762 * unless allocating overflow pages for a large record.
7763 * @param[out] mp Address of a page, or NULL on failure.
7764 * @return 0 on success, non-zero on failure.
7767 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
7772 if ((rc = mdb_page_alloc(mc, num, &np)))
7774 DPRINTF(("allocated new mpage %"Yu", page size %u",
7775 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
7776 np->mp_flags = flags | P_DIRTY;
7777 np->mp_lower = (PAGEHDRSZ-PAGEBASE);
7778 np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
7781 mc->mc_db->md_branch_pages++;
7782 else if (IS_LEAF(np))
7783 mc->mc_db->md_leaf_pages++;
7784 else if (IS_OVERFLOW(np)) {
7785 mc->mc_db->md_overflow_pages += num;
7793 /** Calculate the size of a leaf node.
7794 * The size depends on the environment's page size; if a data item
7795 * is too large it will be put onto an overflow page and the node
7796 * size will only include the key and not the data. Sizes are always
7797 * rounded up to an even number of bytes, to guarantee 2-byte alignment
7798 * of the #MDB_node headers.
7799 * @param[in] env The environment handle.
7800 * @param[in] key The key for the node.
7801 * @param[in] data The data for the node.
7802 * @return The number of bytes needed to store the node.
7805 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
7809 sz = LEAFSIZE(key, data);
7810 if (sz > env->me_nodemax) {
7811 /* put on overflow page */
7812 sz -= data->mv_size - sizeof(pgno_t);
7815 return EVEN(sz + sizeof(indx_t));
7818 /** Calculate the size of a branch node.
7819 * The size should depend on the environment's page size but since
7820 * we currently don't support spilling large keys onto overflow
7821 * pages, it's simply the size of the #MDB_node header plus the
7822 * size of the key. Sizes are always rounded up to an even number
7823 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
7824 * @param[in] env The environment handle.
7825 * @param[in] key The key for the node.
7826 * @return The number of bytes needed to store the node.
7829 mdb_branch_size(MDB_env *env, MDB_val *key)
7834 if (sz > env->me_nodemax) {
7835 /* put on overflow page */
7836 /* not implemented */
7837 /* sz -= key->size - sizeof(pgno_t); */
7840 return sz + sizeof(indx_t);
7843 /** Add a node to the page pointed to by the cursor.
7844 * @param[in] mc The cursor for this operation.
7845 * @param[in] indx The index on the page where the new node should be added.
7846 * @param[in] key The key for the new node.
7847 * @param[in] data The data for the new node, if any.
7848 * @param[in] pgno The page number, if adding a branch node.
7849 * @param[in] flags Flags for the node.
7850 * @return 0 on success, non-zero on failure. Possible errors are:
7852 * <li>ENOMEM - failed to allocate overflow pages for the node.
7853 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
7854 * should never happen since all callers already calculate the
7855 * page's free space before calling this function.
7859 mdb_node_add(MDB_cursor *mc, indx_t indx,
7860 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
7863 size_t node_size = NODESIZE;
7867 MDB_page *mp = mc->mc_pg[mc->mc_top];
7868 MDB_page *ofp = NULL; /* overflow page */
7872 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
7874 DPRINTF(("add to %s %spage %"Yu" index %i, data size %"Z"u key size %"Z"u [%s]",
7875 IS_LEAF(mp) ? "leaf" : "branch",
7876 IS_SUBP(mp) ? "sub-" : "",
7877 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
7878 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
7881 /* Move higher keys up one slot. */
7882 int ksize = mc->mc_db->md_pad, dif;
7883 char *ptr = LEAF2KEY(mp, indx, ksize);
7884 dif = NUMKEYS(mp) - indx;
7886 memmove(ptr+ksize, ptr, dif*ksize);
7887 /* insert new key */
7888 memcpy(ptr, key->mv_data, ksize);
7890 /* Just using these for counting */
7891 mp->mp_lower += sizeof(indx_t);
7892 mp->mp_upper -= ksize - sizeof(indx_t);
7896 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
7898 node_size += key->mv_size;
7900 mdb_cassert(mc, key && data);
7901 if (F_ISSET(flags, F_BIGDATA)) {
7902 /* Data already on overflow page. */
7903 node_size += sizeof(pgno_t);
7904 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
7905 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
7907 /* Put data on overflow page. */
7908 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
7909 data->mv_size, node_size+data->mv_size));
7910 node_size = EVEN(node_size + sizeof(pgno_t));
7911 if ((ssize_t)node_size > room)
7913 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
7915 DPRINTF(("allocated overflow page %"Yu, ofp->mp_pgno));
7919 node_size += data->mv_size;
7922 node_size = EVEN(node_size);
7923 if ((ssize_t)node_size > room)
7927 /* Move higher pointers up one slot. */
7928 for (i = NUMKEYS(mp); i > indx; i--)
7929 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
7931 /* Adjust free space offsets. */
7932 ofs = mp->mp_upper - node_size;
7933 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
7934 mp->mp_ptrs[indx] = ofs;
7936 mp->mp_lower += sizeof(indx_t);
7938 /* Write the node data. */
7939 node = NODEPTR(mp, indx);
7940 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
7941 node->mn_flags = flags;
7943 SETDSZ(node,data->mv_size);
7948 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7951 ndata = NODEDATA(node);
7953 if (F_ISSET(flags, F_BIGDATA))
7954 memcpy(ndata, data->mv_data, sizeof(pgno_t));
7955 else if (F_ISSET(flags, MDB_RESERVE))
7956 data->mv_data = ndata;
7958 memcpy(ndata, data->mv_data, data->mv_size);
7960 memcpy(ndata, &ofp->mp_pgno, sizeof(pgno_t));
7961 ndata = METADATA(ofp);
7962 if (F_ISSET(flags, MDB_RESERVE))
7963 data->mv_data = ndata;
7965 memcpy(ndata, data->mv_data, data->mv_size);
7972 DPRINTF(("not enough room in page %"Yu", got %u ptrs",
7973 mdb_dbg_pgno(mp), NUMKEYS(mp)));
7974 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
7975 DPRINTF(("node size = %"Z"u", node_size));
7976 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7977 return MDB_PAGE_FULL;
7980 /** Delete the specified node from a page.
7981 * @param[in] mc Cursor pointing to the node to delete.
7982 * @param[in] ksize The size of a node. Only used if the page is
7983 * part of a #MDB_DUPFIXED database.
7986 mdb_node_del(MDB_cursor *mc, int ksize)
7988 MDB_page *mp = mc->mc_pg[mc->mc_top];
7989 indx_t indx = mc->mc_ki[mc->mc_top];
7991 indx_t i, j, numkeys, ptr;
7995 DPRINTF(("delete node %u on %s page %"Yu, indx,
7996 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
7997 numkeys = NUMKEYS(mp);
7998 mdb_cassert(mc, indx < numkeys);
8001 int x = numkeys - 1 - indx;
8002 base = LEAF2KEY(mp, indx, ksize);
8004 memmove(base, base + ksize, x * ksize);
8005 mp->mp_lower -= sizeof(indx_t);
8006 mp->mp_upper += ksize - sizeof(indx_t);
8010 node = NODEPTR(mp, indx);
8011 sz = NODESIZE + node->mn_ksize;
8013 if (F_ISSET(node->mn_flags, F_BIGDATA))
8014 sz += sizeof(pgno_t);
8016 sz += NODEDSZ(node);
8020 ptr = mp->mp_ptrs[indx];
8021 for (i = j = 0; i < numkeys; i++) {
8023 mp->mp_ptrs[j] = mp->mp_ptrs[i];
8024 if (mp->mp_ptrs[i] < ptr)
8025 mp->mp_ptrs[j] += sz;
8030 base = (char *)mp + mp->mp_upper + PAGEBASE;
8031 memmove(base + sz, base, ptr - mp->mp_upper);
8033 mp->mp_lower -= sizeof(indx_t);
8037 /** Compact the main page after deleting a node on a subpage.
8038 * @param[in] mp The main page to operate on.
8039 * @param[in] indx The index of the subpage on the main page.
8042 mdb_node_shrink(MDB_page *mp, indx_t indx)
8047 indx_t delta, nsize, len, ptr;
8050 node = NODEPTR(mp, indx);
8051 sp = (MDB_page *)NODEDATA(node);
8052 delta = SIZELEFT(sp);
8053 nsize = NODEDSZ(node) - delta;
8055 /* Prepare to shift upward, set len = length(subpage part to shift) */
8059 return; /* do not make the node uneven-sized */
8061 xp = (MDB_page *)((char *)sp + delta); /* destination subpage */
8062 for (i = NUMKEYS(sp); --i >= 0; )
8063 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
8066 sp->mp_upper = sp->mp_lower;
8067 COPY_PGNO(sp->mp_pgno, mp->mp_pgno);
8068 SETDSZ(node, nsize);
8070 /* Shift <lower nodes...initial part of subpage> upward */
8071 base = (char *)mp + mp->mp_upper + PAGEBASE;
8072 memmove(base + delta, base, (char *)sp + len - base);
8074 ptr = mp->mp_ptrs[indx];
8075 for (i = NUMKEYS(mp); --i >= 0; ) {
8076 if (mp->mp_ptrs[i] <= ptr)
8077 mp->mp_ptrs[i] += delta;
8079 mp->mp_upper += delta;
8082 /** Initial setup of a sorted-dups cursor.
8083 * Sorted duplicates are implemented as a sub-database for the given key.
8084 * The duplicate data items are actually keys of the sub-database.
8085 * Operations on the duplicate data items are performed using a sub-cursor
8086 * initialized when the sub-database is first accessed. This function does
8087 * the preliminary setup of the sub-cursor, filling in the fields that
8088 * depend only on the parent DB.
8089 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
8092 mdb_xcursor_init0(MDB_cursor *mc)
8094 MDB_xcursor *mx = mc->mc_xcursor;
8096 mx->mx_cursor.mc_xcursor = NULL;
8097 mx->mx_cursor.mc_txn = mc->mc_txn;
8098 mx->mx_cursor.mc_db = &mx->mx_db;
8099 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
8100 mx->mx_cursor.mc_dbi = mc->mc_dbi;
8101 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
8102 mx->mx_cursor.mc_snum = 0;
8103 mx->mx_cursor.mc_top = 0;
8104 MC_SET_OVPG(&mx->mx_cursor, NULL);
8105 mx->mx_cursor.mc_flags = C_SUB | (mc->mc_flags & (C_ORIG_RDONLY|C_WRITEMAP));
8106 mx->mx_dbx.md_name.mv_size = 0;
8107 mx->mx_dbx.md_name.mv_data = NULL;
8108 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
8109 mx->mx_dbx.md_dcmp = NULL;
8110 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
8113 /** Final setup of a sorted-dups cursor.
8114 * Sets up the fields that depend on the data from the main cursor.
8115 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
8116 * @param[in] node The data containing the #MDB_db record for the
8117 * sorted-dup database.
8120 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
8122 MDB_xcursor *mx = mc->mc_xcursor;
8124 mx->mx_cursor.mc_flags &= C_SUB|C_ORIG_RDONLY|C_WRITEMAP;
8125 if (node->mn_flags & F_SUBDATA) {
8126 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
8127 mx->mx_cursor.mc_pg[0] = 0;
8128 mx->mx_cursor.mc_snum = 0;
8129 mx->mx_cursor.mc_top = 0;
8131 MDB_page *fp = NODEDATA(node);
8132 mx->mx_db.md_pad = 0;
8133 mx->mx_db.md_flags = 0;
8134 mx->mx_db.md_depth = 1;
8135 mx->mx_db.md_branch_pages = 0;
8136 mx->mx_db.md_leaf_pages = 1;
8137 mx->mx_db.md_overflow_pages = 0;
8138 mx->mx_db.md_entries = NUMKEYS(fp);
8139 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
8140 mx->mx_cursor.mc_snum = 1;
8141 mx->mx_cursor.mc_top = 0;
8142 mx->mx_cursor.mc_flags |= C_INITIALIZED;
8143 mx->mx_cursor.mc_pg[0] = fp;
8144 mx->mx_cursor.mc_ki[0] = 0;
8145 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
8146 mx->mx_db.md_flags = MDB_DUPFIXED;
8147 mx->mx_db.md_pad = fp->mp_pad;
8148 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
8149 mx->mx_db.md_flags |= MDB_INTEGERKEY;
8152 DPRINTF(("Sub-db -%u root page %"Yu, mx->mx_cursor.mc_dbi,
8153 mx->mx_db.md_root));
8154 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
8155 if (NEED_CMP_CLONG(mx->mx_dbx.md_cmp, mx->mx_db.md_pad))
8156 mx->mx_dbx.md_cmp = mdb_cmp_clong;
8160 /** Fixup a sorted-dups cursor due to underlying update.
8161 * Sets up some fields that depend on the data from the main cursor.
8162 * Almost the same as init1, but skips initialization steps if the
8163 * xcursor had already been used.
8164 * @param[in] mc The main cursor whose sorted-dups cursor is to be fixed up.
8165 * @param[in] src_mx The xcursor of an up-to-date cursor.
8166 * @param[in] new_dupdata True if converting from a non-#F_DUPDATA item.
8169 mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int new_dupdata)
8171 MDB_xcursor *mx = mc->mc_xcursor;
8174 mx->mx_cursor.mc_snum = 1;
8175 mx->mx_cursor.mc_top = 0;
8176 mx->mx_cursor.mc_flags |= C_INITIALIZED;
8177 mx->mx_cursor.mc_ki[0] = 0;
8178 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
8179 #if UINT_MAX < MDB_SIZE_MAX /* matches mdb_xcursor_init1:NEED_CMP_CLONG() */
8180 mx->mx_dbx.md_cmp = src_mx->mx_dbx.md_cmp;
8182 } else if (!(mx->mx_cursor.mc_flags & C_INITIALIZED)) {
8185 mx->mx_db = src_mx->mx_db;
8186 mx->mx_cursor.mc_pg[0] = src_mx->mx_cursor.mc_pg[0];
8187 DPRINTF(("Sub-db -%u root page %"Yu, mx->mx_cursor.mc_dbi,
8188 mx->mx_db.md_root));
8191 /** Initialize a cursor for a given transaction and database. */
8193 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
8196 mc->mc_backup = NULL;
8199 mc->mc_db = &txn->mt_dbs[dbi];
8200 mc->mc_dbx = &txn->mt_dbxs[dbi];
8201 mc->mc_dbflag = &txn->mt_dbflags[dbi];
8206 MC_SET_OVPG(mc, NULL);
8207 mc->mc_flags = txn->mt_flags & (C_ORIG_RDONLY|C_WRITEMAP);
8208 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
8209 mdb_tassert(txn, mx != NULL);
8210 mc->mc_xcursor = mx;
8211 mdb_xcursor_init0(mc);
8213 mc->mc_xcursor = NULL;
8215 if (*mc->mc_dbflag & DB_STALE) {
8216 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
8221 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
8224 size_t size = sizeof(MDB_cursor);
8226 if (!ret || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
8229 if (txn->mt_flags & MDB_TXN_BLOCKED)
8232 if (dbi == FREE_DBI && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
8235 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
8236 size += sizeof(MDB_xcursor);
8238 if ((mc = malloc(size)) != NULL) {
8239 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
8240 if (txn->mt_cursors) {
8241 mc->mc_next = txn->mt_cursors[dbi];
8242 txn->mt_cursors[dbi] = mc;
8243 mc->mc_flags |= C_UNTRACK;
8255 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
8257 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi, DB_VALID))
8260 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
8263 if (txn->mt_flags & MDB_TXN_BLOCKED)
8266 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
8270 /* Return the count of duplicate data items for the current key */
8272 mdb_cursor_count(MDB_cursor *mc, mdb_size_t *countp)
8276 if (mc == NULL || countp == NULL)
8279 if (mc->mc_xcursor == NULL)
8280 return MDB_INCOMPATIBLE;
8282 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
8285 if (!(mc->mc_flags & C_INITIALIZED))
8288 if (!mc->mc_snum || (mc->mc_flags & C_EOF))
8289 return MDB_NOTFOUND;
8291 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
8292 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
8295 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
8298 *countp = mc->mc_xcursor->mx_db.md_entries;
8304 mdb_cursor_close(MDB_cursor *mc)
8307 MDB_CURSOR_UNREF(mc, 0);
8309 if (mc && !mc->mc_backup) {
8310 /* remove from txn, if tracked */
8311 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
8312 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
8313 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
8315 *prev = mc->mc_next;
8322 mdb_cursor_txn(MDB_cursor *mc)
8324 if (!mc) return NULL;
8329 mdb_cursor_dbi(MDB_cursor *mc)
8334 /** Replace the key for a branch node with a new key.
8335 * @param[in] mc Cursor pointing to the node to operate on.
8336 * @param[in] key The new key to use.
8337 * @return 0 on success, non-zero on failure.
8340 mdb_update_key(MDB_cursor *mc, MDB_val *key)
8346 int delta, ksize, oksize;
8347 indx_t ptr, i, numkeys, indx;
8350 indx = mc->mc_ki[mc->mc_top];
8351 mp = mc->mc_pg[mc->mc_top];
8352 node = NODEPTR(mp, indx);
8353 ptr = mp->mp_ptrs[indx];
8357 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
8358 k2.mv_data = NODEKEY(node);
8359 k2.mv_size = node->mn_ksize;
8360 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Yu,
8362 mdb_dkey(&k2, kbuf2),
8368 /* Sizes must be 2-byte aligned. */
8369 ksize = EVEN(key->mv_size);
8370 oksize = EVEN(node->mn_ksize);
8371 delta = ksize - oksize;
8373 /* Shift node contents if EVEN(key length) changed. */
8375 if (delta > 0 && SIZELEFT(mp) < delta) {
8377 /* not enough space left, do a delete and split */
8378 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
8379 pgno = NODEPGNO(node);
8380 mdb_node_del(mc, 0);
8381 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
8384 numkeys = NUMKEYS(mp);
8385 for (i = 0; i < numkeys; i++) {
8386 if (mp->mp_ptrs[i] <= ptr)
8387 mp->mp_ptrs[i] -= delta;
8390 base = (char *)mp + mp->mp_upper + PAGEBASE;
8391 len = ptr - mp->mp_upper + NODESIZE;
8392 memmove(base - delta, base, len);
8393 mp->mp_upper -= delta;
8395 node = NODEPTR(mp, indx);
8398 /* But even if no shift was needed, update ksize */
8399 if (node->mn_ksize != key->mv_size)
8400 node->mn_ksize = key->mv_size;
8403 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
8409 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
8411 /** Perform \b act while tracking temporary cursor \b mn */
8412 #define WITH_CURSOR_TRACKING(mn, act) do { \
8413 MDB_cursor dummy, *tracked, **tp = &(mn).mc_txn->mt_cursors[mn.mc_dbi]; \
8414 if ((mn).mc_flags & C_SUB) { \
8415 dummy.mc_flags = C_INITIALIZED; \
8416 dummy.mc_xcursor = (MDB_xcursor *)&(mn); \
8421 tracked->mc_next = *tp; \
8424 *tp = tracked->mc_next; \
8427 /** Move a node from csrc to cdst.
8430 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft)
8437 unsigned short flags;
8441 /* Mark src and dst as dirty. */
8442 if ((rc = mdb_page_touch(csrc)) ||
8443 (rc = mdb_page_touch(cdst)))
8446 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8447 key.mv_size = csrc->mc_db->md_pad;
8448 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
8450 data.mv_data = NULL;
8454 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
8455 mdb_cassert(csrc, !((size_t)srcnode & 1));
8456 srcpg = NODEPGNO(srcnode);
8457 flags = srcnode->mn_flags;
8458 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
8459 unsigned int snum = csrc->mc_snum;
8461 /* must find the lowest key below src */
8462 rc = mdb_page_search_lowest(csrc);
8465 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8466 key.mv_size = csrc->mc_db->md_pad;
8467 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
8469 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
8470 key.mv_size = NODEKSZ(s2);
8471 key.mv_data = NODEKEY(s2);
8473 csrc->mc_snum = snum--;
8474 csrc->mc_top = snum;
8476 key.mv_size = NODEKSZ(srcnode);
8477 key.mv_data = NODEKEY(srcnode);
8479 data.mv_size = NODEDSZ(srcnode);
8480 data.mv_data = NODEDATA(srcnode);
8482 mn.mc_xcursor = NULL;
8483 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
8484 unsigned int snum = cdst->mc_snum;
8487 /* must find the lowest key below dst */
8488 mdb_cursor_copy(cdst, &mn);
8489 rc = mdb_page_search_lowest(&mn);
8492 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
8493 bkey.mv_size = mn.mc_db->md_pad;
8494 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
8496 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
8497 bkey.mv_size = NODEKSZ(s2);
8498 bkey.mv_data = NODEKEY(s2);
8500 mn.mc_snum = snum--;
8503 rc = mdb_update_key(&mn, &bkey);
8508 DPRINTF(("moving %s node %u [%s] on page %"Yu" to node %u on page %"Yu,
8509 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
8510 csrc->mc_ki[csrc->mc_top],
8512 csrc->mc_pg[csrc->mc_top]->mp_pgno,
8513 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
8515 /* Add the node to the destination page.
8517 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
8518 if (rc != MDB_SUCCESS)
8521 /* Delete the node from the source page.
8523 mdb_node_del(csrc, key.mv_size);
8526 /* Adjust other cursors pointing to mp */
8527 MDB_cursor *m2, *m3;
8528 MDB_dbi dbi = csrc->mc_dbi;
8529 MDB_page *mpd, *mps;
8531 mps = csrc->mc_pg[csrc->mc_top];
8532 /* If we're adding on the left, bump others up */
8534 mpd = cdst->mc_pg[csrc->mc_top];
8535 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8536 if (csrc->mc_flags & C_SUB)
8537 m3 = &m2->mc_xcursor->mx_cursor;
8540 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
8543 m3->mc_pg[csrc->mc_top] == mpd &&
8544 m3->mc_ki[csrc->mc_top] >= cdst->mc_ki[csrc->mc_top]) {
8545 m3->mc_ki[csrc->mc_top]++;
8548 m3->mc_pg[csrc->mc_top] == mps &&
8549 m3->mc_ki[csrc->mc_top] == csrc->mc_ki[csrc->mc_top]) {
8550 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
8551 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
8552 m3->mc_ki[csrc->mc_top-1]++;
8554 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) &&
8556 MDB_node *node = NODEPTR(m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
8557 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
8558 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
8562 /* Adding on the right, bump others down */
8564 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8565 if (csrc->mc_flags & C_SUB)
8566 m3 = &m2->mc_xcursor->mx_cursor;
8569 if (m3 == csrc) continue;
8570 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
8572 if (m3->mc_pg[csrc->mc_top] == mps) {
8573 if (!m3->mc_ki[csrc->mc_top]) {
8574 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
8575 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
8576 m3->mc_ki[csrc->mc_top-1]--;
8578 m3->mc_ki[csrc->mc_top]--;
8580 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) &&
8582 MDB_node *node = NODEPTR(m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
8583 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
8584 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
8591 /* Update the parent separators.
8593 if (csrc->mc_ki[csrc->mc_top] == 0) {
8594 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
8595 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8596 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
8598 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
8599 key.mv_size = NODEKSZ(srcnode);
8600 key.mv_data = NODEKEY(srcnode);
8602 DPRINTF(("update separator for source page %"Yu" to [%s]",
8603 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
8604 mdb_cursor_copy(csrc, &mn);
8607 /* We want mdb_rebalance to find mn when doing fixups */
8608 WITH_CURSOR_TRACKING(mn,
8609 rc = mdb_update_key(&mn, &key));
8613 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
8615 indx_t ix = csrc->mc_ki[csrc->mc_top];
8616 nullkey.mv_size = 0;
8617 csrc->mc_ki[csrc->mc_top] = 0;
8618 rc = mdb_update_key(csrc, &nullkey);
8619 csrc->mc_ki[csrc->mc_top] = ix;
8620 mdb_cassert(csrc, rc == MDB_SUCCESS);
8624 if (cdst->mc_ki[cdst->mc_top] == 0) {
8625 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
8626 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8627 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
8629 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
8630 key.mv_size = NODEKSZ(srcnode);
8631 key.mv_data = NODEKEY(srcnode);
8633 DPRINTF(("update separator for destination page %"Yu" to [%s]",
8634 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
8635 mdb_cursor_copy(cdst, &mn);
8638 /* We want mdb_rebalance to find mn when doing fixups */
8639 WITH_CURSOR_TRACKING(mn,
8640 rc = mdb_update_key(&mn, &key));
8644 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
8646 indx_t ix = cdst->mc_ki[cdst->mc_top];
8647 nullkey.mv_size = 0;
8648 cdst->mc_ki[cdst->mc_top] = 0;
8649 rc = mdb_update_key(cdst, &nullkey);
8650 cdst->mc_ki[cdst->mc_top] = ix;
8651 mdb_cassert(cdst, rc == MDB_SUCCESS);
8658 /** Merge one page into another.
8659 * The nodes from the page pointed to by \b csrc will
8660 * be copied to the page pointed to by \b cdst and then
8661 * the \b csrc page will be freed.
8662 * @param[in] csrc Cursor pointing to the source page.
8663 * @param[in] cdst Cursor pointing to the destination page.
8664 * @return 0 on success, non-zero on failure.
8667 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
8669 MDB_page *psrc, *pdst;
8676 psrc = csrc->mc_pg[csrc->mc_top];
8677 pdst = cdst->mc_pg[cdst->mc_top];
8679 DPRINTF(("merging page %"Yu" into %"Yu, psrc->mp_pgno, pdst->mp_pgno));
8681 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
8682 mdb_cassert(csrc, cdst->mc_snum > 1);
8684 /* Mark dst as dirty. */
8685 if ((rc = mdb_page_touch(cdst)))
8688 /* get dst page again now that we've touched it. */
8689 pdst = cdst->mc_pg[cdst->mc_top];
8691 /* Move all nodes from src to dst.
8693 j = nkeys = NUMKEYS(pdst);
8694 if (IS_LEAF2(psrc)) {
8695 key.mv_size = csrc->mc_db->md_pad;
8696 key.mv_data = METADATA(psrc);
8697 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
8698 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
8699 if (rc != MDB_SUCCESS)
8701 key.mv_data = (char *)key.mv_data + key.mv_size;
8704 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
8705 srcnode = NODEPTR(psrc, i);
8706 if (i == 0 && IS_BRANCH(psrc)) {
8709 mdb_cursor_copy(csrc, &mn);
8710 mn.mc_xcursor = NULL;
8711 /* must find the lowest key below src */
8712 rc = mdb_page_search_lowest(&mn);
8715 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
8716 key.mv_size = mn.mc_db->md_pad;
8717 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
8719 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
8720 key.mv_size = NODEKSZ(s2);
8721 key.mv_data = NODEKEY(s2);
8724 key.mv_size = srcnode->mn_ksize;
8725 key.mv_data = NODEKEY(srcnode);
8728 data.mv_size = NODEDSZ(srcnode);
8729 data.mv_data = NODEDATA(srcnode);
8730 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
8731 if (rc != MDB_SUCCESS)
8736 DPRINTF(("dst page %"Yu" now has %u keys (%.1f%% filled)",
8737 pdst->mp_pgno, NUMKEYS(pdst),
8738 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
8740 /* Unlink the src page from parent and add to free list.
8743 mdb_node_del(csrc, 0);
8744 if (csrc->mc_ki[csrc->mc_top] == 0) {
8746 rc = mdb_update_key(csrc, &key);
8754 psrc = csrc->mc_pg[csrc->mc_top];
8755 /* If not operating on FreeDB, allow this page to be reused
8756 * in this txn. Otherwise just add to free list.
8758 rc = mdb_page_loose(csrc, psrc);
8762 csrc->mc_db->md_leaf_pages--;
8764 csrc->mc_db->md_branch_pages--;
8766 /* Adjust other cursors pointing to mp */
8767 MDB_cursor *m2, *m3;
8768 MDB_dbi dbi = csrc->mc_dbi;
8769 unsigned int top = csrc->mc_top;
8771 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8772 if (csrc->mc_flags & C_SUB)
8773 m3 = &m2->mc_xcursor->mx_cursor;
8776 if (m3 == csrc) continue;
8777 if (m3->mc_snum < csrc->mc_snum) continue;
8778 if (m3->mc_pg[top] == psrc) {
8779 m3->mc_pg[top] = pdst;
8780 m3->mc_ki[top] += nkeys;
8781 m3->mc_ki[top-1] = cdst->mc_ki[top-1];
8782 } else if (m3->mc_pg[top-1] == csrc->mc_pg[top-1] &&
8783 m3->mc_ki[top-1] > csrc->mc_ki[top-1]) {
8786 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) &&
8788 MDB_node *node = NODEPTR(m3->mc_pg[top], m3->mc_ki[top]);
8789 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
8790 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
8795 unsigned int snum = cdst->mc_snum;
8796 uint16_t depth = cdst->mc_db->md_depth;
8797 mdb_cursor_pop(cdst);
8798 rc = mdb_rebalance(cdst);
8799 /* Did the tree height change? */
8800 if (depth != cdst->mc_db->md_depth)
8801 snum += cdst->mc_db->md_depth - depth;
8802 cdst->mc_snum = snum;
8803 cdst->mc_top = snum-1;
8808 /** Copy the contents of a cursor.
8809 * @param[in] csrc The cursor to copy from.
8810 * @param[out] cdst The cursor to copy to.
8813 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
8817 cdst->mc_txn = csrc->mc_txn;
8818 cdst->mc_dbi = csrc->mc_dbi;
8819 cdst->mc_db = csrc->mc_db;
8820 cdst->mc_dbx = csrc->mc_dbx;
8821 cdst->mc_snum = csrc->mc_snum;
8822 cdst->mc_top = csrc->mc_top;
8823 cdst->mc_flags = csrc->mc_flags;
8824 MC_SET_OVPG(cdst, MC_OVPG(csrc));
8826 for (i=0; i<csrc->mc_snum; i++) {
8827 cdst->mc_pg[i] = csrc->mc_pg[i];
8828 cdst->mc_ki[i] = csrc->mc_ki[i];
8832 /** Rebalance the tree after a delete operation.
8833 * @param[in] mc Cursor pointing to the page where rebalancing
8835 * @return 0 on success, non-zero on failure.
8838 mdb_rebalance(MDB_cursor *mc)
8842 unsigned int ptop, minkeys, thresh;
8846 if (IS_BRANCH(mc->mc_pg[mc->mc_top])) {
8851 thresh = FILL_THRESHOLD;
8853 DPRINTF(("rebalancing %s page %"Yu" (has %u keys, %.1f%% full)",
8854 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
8855 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
8856 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
8858 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= thresh &&
8859 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
8860 DPRINTF(("no need to rebalance page %"Yu", above fill threshold",
8861 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
8865 if (mc->mc_snum < 2) {
8866 MDB_page *mp = mc->mc_pg[0];
8868 DPUTS("Can't rebalance a subpage, ignoring");
8871 if (NUMKEYS(mp) == 0) {
8872 DPUTS("tree is completely empty");
8873 mc->mc_db->md_root = P_INVALID;
8874 mc->mc_db->md_depth = 0;
8875 mc->mc_db->md_leaf_pages = 0;
8876 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
8879 /* Adjust cursors pointing to mp */
8882 mc->mc_flags &= ~C_INITIALIZED;
8884 MDB_cursor *m2, *m3;
8885 MDB_dbi dbi = mc->mc_dbi;
8887 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8888 if (mc->mc_flags & C_SUB)
8889 m3 = &m2->mc_xcursor->mx_cursor;
8892 if (!(m3->mc_flags & C_INITIALIZED) || (m3->mc_snum < mc->mc_snum))
8894 if (m3->mc_pg[0] == mp) {
8897 m3->mc_flags &= ~C_INITIALIZED;
8901 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
8903 DPUTS("collapsing root page!");
8904 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
8907 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
8908 rc = mdb_page_get(mc, mc->mc_db->md_root, &mc->mc_pg[0], NULL);
8911 mc->mc_db->md_depth--;
8912 mc->mc_db->md_branch_pages--;
8913 mc->mc_ki[0] = mc->mc_ki[1];
8914 for (i = 1; i<mc->mc_db->md_depth; i++) {
8915 mc->mc_pg[i] = mc->mc_pg[i+1];
8916 mc->mc_ki[i] = mc->mc_ki[i+1];
8919 /* Adjust other cursors pointing to mp */
8920 MDB_cursor *m2, *m3;
8921 MDB_dbi dbi = mc->mc_dbi;
8923 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8924 if (mc->mc_flags & C_SUB)
8925 m3 = &m2->mc_xcursor->mx_cursor;
8928 if (m3 == mc) continue;
8929 if (!(m3->mc_flags & C_INITIALIZED))
8931 if (m3->mc_pg[0] == mp) {
8932 for (i=0; i<mc->mc_db->md_depth; i++) {
8933 m3->mc_pg[i] = m3->mc_pg[i+1];
8934 m3->mc_ki[i] = m3->mc_ki[i+1];
8942 DPUTS("root page doesn't need rebalancing");
8946 /* The parent (branch page) must have at least 2 pointers,
8947 * otherwise the tree is invalid.
8949 ptop = mc->mc_top-1;
8950 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
8952 /* Leaf page fill factor is below the threshold.
8953 * Try to move keys from left or right neighbor, or
8954 * merge with a neighbor page.
8959 mdb_cursor_copy(mc, &mn);
8960 mn.mc_xcursor = NULL;
8962 oldki = mc->mc_ki[mc->mc_top];
8963 if (mc->mc_ki[ptop] == 0) {
8964 /* We're the leftmost leaf in our parent.
8966 DPUTS("reading right neighbor");
8968 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
8969 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
8972 mn.mc_ki[mn.mc_top] = 0;
8973 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
8976 /* There is at least one neighbor to the left.
8978 DPUTS("reading left neighbor");
8980 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
8981 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
8984 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
8985 mc->mc_ki[mc->mc_top] = 0;
8989 DPRINTF(("found neighbor page %"Yu" (%u keys, %.1f%% full)",
8990 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
8991 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
8993 /* If the neighbor page is above threshold and has enough keys,
8994 * move one key from it. Otherwise we should try to merge them.
8995 * (A branch page must never have less than 2 keys.)
8997 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= thresh && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
8998 rc = mdb_node_move(&mn, mc, fromleft);
9000 /* if we inserted on left, bump position up */
9005 rc = mdb_page_merge(&mn, mc);
9007 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
9008 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
9009 /* We want mdb_rebalance to find mn when doing fixups */
9010 WITH_CURSOR_TRACKING(mn,
9011 rc = mdb_page_merge(mc, &mn));
9012 mdb_cursor_copy(&mn, mc);
9014 mc->mc_flags &= ~C_EOF;
9016 mc->mc_ki[mc->mc_top] = oldki;
9020 /** Complete a delete operation started by #mdb_cursor_del(). */
9022 mdb_cursor_del0(MDB_cursor *mc)
9028 MDB_cursor *m2, *m3;
9029 MDB_dbi dbi = mc->mc_dbi;
9031 ki = mc->mc_ki[mc->mc_top];
9032 mp = mc->mc_pg[mc->mc_top];
9033 mdb_node_del(mc, mc->mc_db->md_pad);
9034 mc->mc_db->md_entries--;
9036 /* Adjust other cursors pointing to mp */
9037 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9038 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
9039 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9041 if (m3 == mc || m3->mc_snum < mc->mc_snum)
9043 if (m3->mc_pg[mc->mc_top] == mp) {
9044 if (m3->mc_ki[mc->mc_top] == ki) {
9045 m3->mc_flags |= C_DEL;
9046 } else if (m3->mc_ki[mc->mc_top] > ki) {
9047 m3->mc_ki[mc->mc_top]--;
9049 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
9050 MDB_node *node = NODEPTR(m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
9051 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
9052 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
9057 rc = mdb_rebalance(mc);
9059 if (rc == MDB_SUCCESS) {
9060 /* DB is totally empty now, just bail out.
9061 * Other cursors adjustments were already done
9062 * by mdb_rebalance and aren't needed here.
9067 mp = mc->mc_pg[mc->mc_top];
9068 nkeys = NUMKEYS(mp);
9070 /* Adjust other cursors pointing to mp */
9071 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
9072 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
9073 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9075 if (m3->mc_snum < mc->mc_snum)
9077 if (m3->mc_pg[mc->mc_top] == mp) {
9078 /* if m3 points past last node in page, find next sibling */
9079 if (m3->mc_ki[mc->mc_top] >= mc->mc_ki[mc->mc_top]) {
9080 if (m3->mc_ki[mc->mc_top] >= nkeys) {
9081 rc = mdb_cursor_sibling(m3, 1);
9082 if (rc == MDB_NOTFOUND) {
9083 m3->mc_flags |= C_EOF;
9088 if (mc->mc_db->md_flags & MDB_DUPSORT) {
9089 MDB_node *node = NODEPTR(m3->mc_pg[m3->mc_top], m3->mc_ki[m3->mc_top]);
9090 if (node->mn_flags & F_DUPDATA) {
9091 mdb_xcursor_init1(m3, node);
9092 m3->mc_xcursor->mx_cursor.mc_flags |= C_DEL;
9098 mc->mc_flags |= C_DEL;
9102 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
9107 mdb_del(MDB_txn *txn, MDB_dbi dbi,
9108 MDB_val *key, MDB_val *data)
9110 if (!key || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9113 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
9114 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
9116 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
9117 /* must ignore any data */
9121 return mdb_del0(txn, dbi, key, data, 0);
9125 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
9126 MDB_val *key, MDB_val *data, unsigned flags)
9131 MDB_val rdata, *xdata;
9135 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
9137 mdb_cursor_init(&mc, txn, dbi, &mx);
9146 flags |= MDB_NODUPDATA;
9148 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
9150 /* let mdb_page_split know about this cursor if needed:
9151 * delete will trigger a rebalance; if it needs to move
9152 * a node from one page to another, it will have to
9153 * update the parent's separator key(s). If the new sepkey
9154 * is larger than the current one, the parent page may
9155 * run out of space, triggering a split. We need this
9156 * cursor to be consistent until the end of the rebalance.
9158 mc.mc_flags |= C_UNTRACK;
9159 mc.mc_next = txn->mt_cursors[dbi];
9160 txn->mt_cursors[dbi] = &mc;
9161 rc = mdb_cursor_del(&mc, flags);
9162 txn->mt_cursors[dbi] = mc.mc_next;
9167 /** Split a page and insert a new node.
9168 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
9169 * The cursor will be updated to point to the actual page and index where
9170 * the node got inserted after the split.
9171 * @param[in] newkey The key for the newly inserted node.
9172 * @param[in] newdata The data for the newly inserted node.
9173 * @param[in] newpgno The page number, if the new node is a branch node.
9174 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
9175 * @return 0 on success, non-zero on failure.
9178 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
9179 unsigned int nflags)
9182 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
9185 int i, j, split_indx, nkeys, pmax;
9186 MDB_env *env = mc->mc_txn->mt_env;
9188 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
9189 MDB_page *copy = NULL;
9190 MDB_page *mp, *rp, *pp;
9195 mp = mc->mc_pg[mc->mc_top];
9196 newindx = mc->mc_ki[mc->mc_top];
9197 nkeys = NUMKEYS(mp);
9199 DPRINTF(("-----> splitting %s page %"Yu" and adding [%s] at index %i/%i",
9200 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
9201 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
9203 /* Create a right sibling. */
9204 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
9206 rp->mp_pad = mp->mp_pad;
9207 DPRINTF(("new right sibling: page %"Yu, rp->mp_pgno));
9209 /* Usually when splitting the root page, the cursor
9210 * height is 1. But when called from mdb_update_key,
9211 * the cursor height may be greater because it walks
9212 * up the stack while finding the branch slot to update.
9214 if (mc->mc_top < 1) {
9215 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
9217 /* shift current top to make room for new parent */
9218 for (i=mc->mc_snum; i>0; i--) {
9219 mc->mc_pg[i] = mc->mc_pg[i-1];
9220 mc->mc_ki[i] = mc->mc_ki[i-1];
9224 mc->mc_db->md_root = pp->mp_pgno;
9225 DPRINTF(("root split! new root = %"Yu, pp->mp_pgno));
9226 new_root = mc->mc_db->md_depth++;
9228 /* Add left (implicit) pointer. */
9229 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
9230 /* undo the pre-push */
9231 mc->mc_pg[0] = mc->mc_pg[1];
9232 mc->mc_ki[0] = mc->mc_ki[1];
9233 mc->mc_db->md_root = mp->mp_pgno;
9234 mc->mc_db->md_depth--;
9241 ptop = mc->mc_top-1;
9242 DPRINTF(("parent branch page is %"Yu, mc->mc_pg[ptop]->mp_pgno));
9245 mdb_cursor_copy(mc, &mn);
9246 mn.mc_xcursor = NULL;
9247 mn.mc_pg[mn.mc_top] = rp;
9248 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
9250 if (nflags & MDB_APPEND) {
9251 mn.mc_ki[mn.mc_top] = 0;
9253 split_indx = newindx;
9257 split_indx = (nkeys+1) / 2;
9262 unsigned int lsize, rsize, ksize;
9263 /* Move half of the keys to the right sibling */
9264 x = mc->mc_ki[mc->mc_top] - split_indx;
9265 ksize = mc->mc_db->md_pad;
9266 split = LEAF2KEY(mp, split_indx, ksize);
9267 rsize = (nkeys - split_indx) * ksize;
9268 lsize = (nkeys - split_indx) * sizeof(indx_t);
9269 mp->mp_lower -= lsize;
9270 rp->mp_lower += lsize;
9271 mp->mp_upper += rsize - lsize;
9272 rp->mp_upper -= rsize - lsize;
9273 sepkey.mv_size = ksize;
9274 if (newindx == split_indx) {
9275 sepkey.mv_data = newkey->mv_data;
9277 sepkey.mv_data = split;
9280 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
9281 memcpy(rp->mp_ptrs, split, rsize);
9282 sepkey.mv_data = rp->mp_ptrs;
9283 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
9284 memcpy(ins, newkey->mv_data, ksize);
9285 mp->mp_lower += sizeof(indx_t);
9286 mp->mp_upper -= ksize - sizeof(indx_t);
9289 memcpy(rp->mp_ptrs, split, x * ksize);
9290 ins = LEAF2KEY(rp, x, ksize);
9291 memcpy(ins, newkey->mv_data, ksize);
9292 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
9293 rp->mp_lower += sizeof(indx_t);
9294 rp->mp_upper -= ksize - sizeof(indx_t);
9295 mc->mc_ki[mc->mc_top] = x;
9298 int psize, nsize, k;
9299 /* Maximum free space in an empty page */
9300 pmax = env->me_psize - PAGEHDRSZ;
9302 nsize = mdb_leaf_size(env, newkey, newdata);
9304 nsize = mdb_branch_size(env, newkey);
9305 nsize = EVEN(nsize);
9307 /* grab a page to hold a temporary copy */
9308 copy = mdb_page_malloc(mc->mc_txn, 1);
9313 copy->mp_pgno = mp->mp_pgno;
9314 copy->mp_flags = mp->mp_flags;
9315 copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
9316 copy->mp_upper = env->me_psize - PAGEBASE;
9318 /* prepare to insert */
9319 for (i=0, j=0; i<nkeys; i++) {
9321 copy->mp_ptrs[j++] = 0;
9323 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
9326 /* When items are relatively large the split point needs
9327 * to be checked, because being off-by-one will make the
9328 * difference between success or failure in mdb_node_add.
9330 * It's also relevant if a page happens to be laid out
9331 * such that one half of its nodes are all "small" and
9332 * the other half of its nodes are "large." If the new
9333 * item is also "large" and falls on the half with
9334 * "large" nodes, it also may not fit.
9336 * As a final tweak, if the new item goes on the last
9337 * spot on the page (and thus, onto the new page), bias
9338 * the split so the new page is emptier than the old page.
9339 * This yields better packing during sequential inserts.
9341 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
9342 /* Find split point */
9344 if (newindx <= split_indx || newindx >= nkeys) {
9346 k = newindx >= nkeys ? nkeys : split_indx+1+IS_LEAF(mp);
9351 for (; i!=k; i+=j) {
9356 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
9357 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
9359 if (F_ISSET(node->mn_flags, F_BIGDATA))
9360 psize += sizeof(pgno_t);
9362 psize += NODEDSZ(node);
9364 psize = EVEN(psize);
9366 if (psize > pmax || i == k-j) {
9367 split_indx = i + (j<0);
9372 if (split_indx == newindx) {
9373 sepkey.mv_size = newkey->mv_size;
9374 sepkey.mv_data = newkey->mv_data;
9376 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
9377 sepkey.mv_size = node->mn_ksize;
9378 sepkey.mv_data = NODEKEY(node);
9383 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
9385 /* Copy separator key to the parent.
9387 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
9388 int snum = mc->mc_snum;
9392 /* We want other splits to find mn when doing fixups */
9393 WITH_CURSOR_TRACKING(mn,
9394 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0));
9399 if (mc->mc_snum > snum) {
9402 /* Right page might now have changed parent.
9403 * Check if left page also changed parent.
9405 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
9406 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
9407 for (i=0; i<ptop; i++) {
9408 mc->mc_pg[i] = mn.mc_pg[i];
9409 mc->mc_ki[i] = mn.mc_ki[i];
9411 mc->mc_pg[ptop] = mn.mc_pg[ptop];
9412 if (mn.mc_ki[ptop]) {
9413 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
9415 /* find right page's left sibling */
9416 mc->mc_ki[ptop] = mn.mc_ki[ptop];
9417 mdb_cursor_sibling(mc, 0);
9422 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
9425 if (rc != MDB_SUCCESS) {
9428 if (nflags & MDB_APPEND) {
9429 mc->mc_pg[mc->mc_top] = rp;
9430 mc->mc_ki[mc->mc_top] = 0;
9431 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
9434 for (i=0; i<mc->mc_top; i++)
9435 mc->mc_ki[i] = mn.mc_ki[i];
9436 } else if (!IS_LEAF2(mp)) {
9438 mc->mc_pg[mc->mc_top] = rp;
9443 rkey.mv_data = newkey->mv_data;
9444 rkey.mv_size = newkey->mv_size;
9450 /* Update index for the new key. */
9451 mc->mc_ki[mc->mc_top] = j;
9453 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
9454 rkey.mv_data = NODEKEY(node);
9455 rkey.mv_size = node->mn_ksize;
9457 xdata.mv_data = NODEDATA(node);
9458 xdata.mv_size = NODEDSZ(node);
9461 pgno = NODEPGNO(node);
9462 flags = node->mn_flags;
9465 if (!IS_LEAF(mp) && j == 0) {
9466 /* First branch index doesn't need key data. */
9470 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
9476 mc->mc_pg[mc->mc_top] = copy;
9481 } while (i != split_indx);
9483 nkeys = NUMKEYS(copy);
9484 for (i=0; i<nkeys; i++)
9485 mp->mp_ptrs[i] = copy->mp_ptrs[i];
9486 mp->mp_lower = copy->mp_lower;
9487 mp->mp_upper = copy->mp_upper;
9488 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
9489 env->me_psize - copy->mp_upper - PAGEBASE);
9491 /* reset back to original page */
9492 if (newindx < split_indx) {
9493 mc->mc_pg[mc->mc_top] = mp;
9495 mc->mc_pg[mc->mc_top] = rp;
9497 /* Make sure mc_ki is still valid.
9499 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
9500 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
9501 for (i=0; i<=ptop; i++) {
9502 mc->mc_pg[i] = mn.mc_pg[i];
9503 mc->mc_ki[i] = mn.mc_ki[i];
9507 if (nflags & MDB_RESERVE) {
9508 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
9509 if (!(node->mn_flags & F_BIGDATA))
9510 newdata->mv_data = NODEDATA(node);
9513 if (newindx >= split_indx) {
9514 mc->mc_pg[mc->mc_top] = rp;
9516 /* Make sure mc_ki is still valid.
9518 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
9519 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
9520 for (i=0; i<=ptop; i++) {
9521 mc->mc_pg[i] = mn.mc_pg[i];
9522 mc->mc_ki[i] = mn.mc_ki[i];
9529 /* Adjust other cursors pointing to mp */
9530 MDB_cursor *m2, *m3;
9531 MDB_dbi dbi = mc->mc_dbi;
9532 nkeys = NUMKEYS(mp);
9534 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9535 if (mc->mc_flags & C_SUB)
9536 m3 = &m2->mc_xcursor->mx_cursor;
9541 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9545 /* sub cursors may be on different DB */
9546 if (m3->mc_pg[0] != mp)
9549 for (k=new_root; k>=0; k--) {
9550 m3->mc_ki[k+1] = m3->mc_ki[k];
9551 m3->mc_pg[k+1] = m3->mc_pg[k];
9553 if (m3->mc_ki[0] >= nkeys) {
9558 m3->mc_pg[0] = mc->mc_pg[0];
9562 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
9563 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
9564 m3->mc_ki[mc->mc_top]++;
9565 if (m3->mc_ki[mc->mc_top] >= nkeys) {
9566 m3->mc_pg[mc->mc_top] = rp;
9567 m3->mc_ki[mc->mc_top] -= nkeys;
9568 for (i=0; i<mc->mc_top; i++) {
9569 m3->mc_ki[i] = mn.mc_ki[i];
9570 m3->mc_pg[i] = mn.mc_pg[i];
9573 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
9574 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
9577 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) &&
9579 MDB_node *node = NODEPTR(m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
9580 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
9581 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
9585 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
9588 if (copy) /* tmp page */
9589 mdb_page_free(env, copy);
9591 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
9596 mdb_put(MDB_txn *txn, MDB_dbi dbi,
9597 MDB_val *key, MDB_val *data, unsigned int flags)
9603 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9606 if (flags & ~(MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP))
9609 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
9610 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
9612 mdb_cursor_init(&mc, txn, dbi, &mx);
9613 mc.mc_next = txn->mt_cursors[dbi];
9614 txn->mt_cursors[dbi] = &mc;
9615 rc = mdb_cursor_put(&mc, key, data, flags);
9616 txn->mt_cursors[dbi] = mc.mc_next;
9621 #define MDB_WBUF (1024*1024)
9623 #define MDB_EOF 0x10 /**< #mdb_env_copyfd1() is done reading */
9625 /** State needed for a double-buffering compacting copy. */
9626 typedef struct mdb_copy {
9627 pthread_mutex_t mc_mutex;
9628 pthread_cond_t mc_cond; /**< Condition variable for #mc_new */
9635 pgno_t mc_next_pgno;
9637 int mc_toggle; /**< Buffer number in provider */
9638 int mc_new; /**< (0-2 buffers to write) | (#MDB_EOF at end) */
9639 volatile int mc_error; /**< Error code, never cleared if set */
9642 /** Dedicated writer thread for compacting copy. */
9643 static THREAD_RET ESECT CALL_CONV
9644 mdb_env_copythr(void *arg)
9648 int toggle = 0, wsize, rc;
9651 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
9654 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
9657 pthread_mutex_lock(&my->mc_mutex);
9660 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
9661 if (my->mc_new == 0 + MDB_EOF) /* 0 buffers, just EOF */
9663 wsize = my->mc_wlen[toggle];
9664 ptr = my->mc_wbuf[toggle];
9667 while (wsize > 0 && !my->mc_error) {
9668 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
9672 } else if (len > 0) {
9685 /* If there's an overflow page tail, write it too */
9686 if (my->mc_olen[toggle]) {
9687 wsize = my->mc_olen[toggle];
9688 ptr = my->mc_over[toggle];
9689 my->mc_olen[toggle] = 0;
9692 my->mc_wlen[toggle] = 0;
9694 /* Return the empty buffer to provider */
9696 pthread_cond_signal(&my->mc_cond);
9698 pthread_mutex_unlock(&my->mc_mutex);
9699 return (THREAD_RET)0;
9703 /** Give buffer and/or #MDB_EOF to writer thread, await unused buffer.
9705 * @param[in] my control structure.
9706 * @param[in] adjust (1 to hand off 1 buffer) | (MDB_EOF when ending).
9709 mdb_env_cthr_toggle(mdb_copy *my, int adjust)
9711 pthread_mutex_lock(&my->mc_mutex);
9712 my->mc_new += adjust;
9713 pthread_cond_signal(&my->mc_cond);
9714 while (my->mc_new & 2) /* both buffers in use */
9715 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
9716 pthread_mutex_unlock(&my->mc_mutex);
9718 my->mc_toggle ^= (adjust & 1);
9719 /* Both threads reset mc_wlen, to be safe from threading errors */
9720 my->mc_wlen[my->mc_toggle] = 0;
9721 return my->mc_error;
9724 /** Depth-first tree traversal for compacting copy. */
9726 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
9728 MDB_cursor mc = {0};
9730 MDB_page *mo, *mp, *leaf;
9735 /* Empty DB, nothing to do */
9736 if (*pg == P_INVALID)
9740 mc.mc_txn = my->mc_txn;
9741 mc.mc_flags = my->mc_txn->mt_flags & (C_ORIG_RDONLY|C_WRITEMAP);
9743 rc = mdb_page_get(&mc, *pg, &mc.mc_pg[0], NULL);
9746 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
9750 /* Make cursor pages writable */
9751 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
9755 for (i=0; i<mc.mc_top; i++) {
9756 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
9757 mc.mc_pg[i] = (MDB_page *)ptr;
9758 ptr += my->mc_env->me_psize;
9761 /* This is writable space for a leaf page. Usually not needed. */
9762 leaf = (MDB_page *)ptr;
9764 toggle = my->mc_toggle;
9765 while (mc.mc_snum > 0) {
9767 mp = mc.mc_pg[mc.mc_top];
9771 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
9772 for (i=0; i<n; i++) {
9773 ni = NODEPTR(mp, i);
9774 if (ni->mn_flags & F_BIGDATA) {
9778 /* Need writable leaf */
9780 mc.mc_pg[mc.mc_top] = leaf;
9781 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
9783 ni = NODEPTR(mp, i);
9786 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9787 memcpy(NODEDATA(ni), &my->mc_next_pgno, sizeof(pgno_t));
9788 rc = mdb_page_get(&mc, pg, &omp, NULL);
9791 if (my->mc_wlen[toggle] >= MDB_WBUF) {
9792 rc = mdb_env_cthr_toggle(my, 1);
9795 toggle = my->mc_toggle;
9797 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
9798 memcpy(mo, omp, my->mc_env->me_psize);
9799 mo->mp_pgno = my->mc_next_pgno;
9800 my->mc_next_pgno += omp->mp_pages;
9801 my->mc_wlen[toggle] += my->mc_env->me_psize;
9802 if (omp->mp_pages > 1) {
9803 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
9804 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
9805 rc = mdb_env_cthr_toggle(my, 1);
9808 toggle = my->mc_toggle;
9810 } else if (ni->mn_flags & F_SUBDATA) {
9813 /* Need writable leaf */
9815 mc.mc_pg[mc.mc_top] = leaf;
9816 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
9818 ni = NODEPTR(mp, i);
9821 memcpy(&db, NODEDATA(ni), sizeof(db));
9822 my->mc_toggle = toggle;
9823 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
9826 toggle = my->mc_toggle;
9827 memcpy(NODEDATA(ni), &db, sizeof(db));
9832 mc.mc_ki[mc.mc_top]++;
9833 if (mc.mc_ki[mc.mc_top] < n) {
9836 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
9838 rc = mdb_page_get(&mc, pg, &mp, NULL);
9843 mc.mc_ki[mc.mc_top] = 0;
9844 if (IS_BRANCH(mp)) {
9845 /* Whenever we advance to a sibling branch page,
9846 * we must proceed all the way down to its first leaf.
9848 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
9851 mc.mc_pg[mc.mc_top] = mp;
9855 if (my->mc_wlen[toggle] >= MDB_WBUF) {
9856 rc = mdb_env_cthr_toggle(my, 1);
9859 toggle = my->mc_toggle;
9861 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
9862 mdb_page_copy(mo, mp, my->mc_env->me_psize);
9863 mo->mp_pgno = my->mc_next_pgno++;
9864 my->mc_wlen[toggle] += my->mc_env->me_psize;
9866 /* Update parent if there is one */
9867 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
9868 SETPGNO(ni, mo->mp_pgno);
9869 mdb_cursor_pop(&mc);
9871 /* Otherwise we're done */
9881 /** Copy environment with compaction. */
9883 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
9888 MDB_txn *txn = NULL;
9890 pgno_t root, new_root;
9891 int rc = MDB_SUCCESS;
9894 if (!(my.mc_mutex = CreateMutex(NULL, FALSE, NULL)) ||
9895 !(my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL))) {
9899 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_os_psize);
9900 if (my.mc_wbuf[0] == NULL) {
9901 /* _aligned_malloc() sets errno, but we use Windows error codes */
9902 rc = ERROR_NOT_ENOUGH_MEMORY;
9906 if ((rc = pthread_mutex_init(&my.mc_mutex, NULL)) != 0)
9908 if ((rc = pthread_cond_init(&my.mc_cond, NULL)) != 0)
9910 #ifdef HAVE_MEMALIGN
9911 my.mc_wbuf[0] = memalign(env->me_os_psize, MDB_WBUF*2);
9912 if (my.mc_wbuf[0] == NULL) {
9919 if ((rc = posix_memalign(&p, env->me_os_psize, MDB_WBUF*2)) != 0)
9925 memset(my.mc_wbuf[0], 0, MDB_WBUF*2);
9926 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
9927 my.mc_next_pgno = NUM_METAS;
9930 rc = THREAD_CREATE(thr, mdb_env_copythr, &my);
9934 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
9938 mp = (MDB_page *)my.mc_wbuf[0];
9939 memset(mp, 0, NUM_METAS * env->me_psize);
9941 mp->mp_flags = P_META;
9942 mm = (MDB_meta *)METADATA(mp);
9943 mdb_env_init_meta0(env, mm);
9944 mm->mm_address = env->me_metas[0]->mm_address;
9946 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
9948 mp->mp_flags = P_META;
9949 *(MDB_meta *)METADATA(mp) = *mm;
9950 mm = (MDB_meta *)METADATA(mp);
9952 /* Set metapage 1 with current main DB */
9953 root = new_root = txn->mt_dbs[MAIN_DBI].md_root;
9954 if (root != P_INVALID) {
9955 /* Count free pages + freeDB pages. Subtract from last_pg
9956 * to find the new last_pg, which also becomes the new root.
9958 MDB_ID freecount = 0;
9961 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
9962 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
9963 freecount += *(MDB_ID *)data.mv_data;
9964 if (rc != MDB_NOTFOUND)
9966 freecount += txn->mt_dbs[FREE_DBI].md_branch_pages +
9967 txn->mt_dbs[FREE_DBI].md_leaf_pages +
9968 txn->mt_dbs[FREE_DBI].md_overflow_pages;
9970 new_root = txn->mt_next_pgno - 1 - freecount;
9971 mm->mm_last_pg = new_root;
9972 mm->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
9973 mm->mm_dbs[MAIN_DBI].md_root = new_root;
9975 /* When the DB is empty, handle it specially to
9976 * fix any breakage like page leaks from ITS#8174.
9978 mm->mm_dbs[MAIN_DBI].md_flags = txn->mt_dbs[MAIN_DBI].md_flags;
9980 if (root != P_INVALID || mm->mm_dbs[MAIN_DBI].md_flags) {
9981 mm->mm_txnid = 1; /* use metapage 1 */
9984 my.mc_wlen[0] = env->me_psize * NUM_METAS;
9986 rc = mdb_env_cwalk(&my, &root, 0);
9987 if (rc == MDB_SUCCESS && root != new_root) {
9988 rc = MDB_INCOMPATIBLE; /* page leak or corrupt DB */
9994 mdb_env_cthr_toggle(&my, 1 | MDB_EOF);
9995 rc = THREAD_FINISH(thr);
10000 if (my.mc_wbuf[0]) _aligned_free(my.mc_wbuf[0]);
10001 if (my.mc_cond) CloseHandle(my.mc_cond);
10002 if (my.mc_mutex) CloseHandle(my.mc_mutex);
10004 free(my.mc_wbuf[0]);
10005 pthread_cond_destroy(&my.mc_cond);
10007 pthread_mutex_destroy(&my.mc_mutex);
10009 return rc ? rc : my.mc_error;
10012 /** Copy environment as-is. */
10014 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
10016 MDB_txn *txn = NULL;
10017 mdb_mutexref_t wmutex = NULL;
10019 mdb_size_t wsize, w3;
10023 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
10027 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
10030 /* Do the lock/unlock of the reader mutex before starting the
10031 * write txn. Otherwise other read txns could block writers.
10033 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
10037 if (env->me_txns) {
10038 /* We must start the actual read txn after blocking writers */
10039 mdb_txn_end(txn, MDB_END_RESET_TMP);
10041 /* Temporarily block writers until we snapshot the meta pages */
10042 wmutex = env->me_wmutex;
10043 if (LOCK_MUTEX(rc, env, wmutex))
10046 rc = mdb_txn_renew0(txn);
10048 UNLOCK_MUTEX(wmutex);
10053 wsize = env->me_psize * NUM_METAS;
10057 DO_WRITE(rc, fd, ptr, w2, len);
10061 } else if (len > 0) {
10067 /* Non-blocking or async handles are not supported */
10073 UNLOCK_MUTEX(wmutex);
10078 w3 = txn->mt_next_pgno * env->me_psize;
10080 mdb_size_t fsize = 0;
10081 if ((rc = mdb_fsize(env->me_fd, &fsize)))
10086 wsize = w3 - wsize;
10087 while (wsize > 0) {
10088 if (wsize > MAX_WRITE)
10092 DO_WRITE(rc, fd, ptr, w2, len);
10096 } else if (len > 0) {
10108 mdb_txn_abort(txn);
10113 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
10115 if (flags & MDB_CP_COMPACT)
10116 return mdb_env_copyfd1(env, fd);
10118 return mdb_env_copyfd0(env, fd);
10122 mdb_env_copyfd(MDB_env *env, HANDLE fd)
10124 return mdb_env_copyfd2(env, fd, 0);
10128 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
10132 HANDLE newfd = INVALID_HANDLE_VALUE;
10137 if (env->me_flags & MDB_NOSUBDIR) {
10138 lpath = (char *)path;
10140 len = strlen(path);
10141 len += sizeof(DATANAME);
10142 lpath = malloc(len);
10145 sprintf(lpath, "%s" DATANAME, path);
10148 /* The destination path must exist, but the destination file must not.
10149 * We don't want the OS to cache the writes, since the source data is
10150 * already in the OS cache.
10153 rc = utf8_to_utf16(lpath, -1, &wpath, NULL);
10156 newfd = CreateFileW(wpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
10157 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
10160 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
10162 if (newfd == INVALID_HANDLE_VALUE) {
10167 if (env->me_psize >= env->me_os_psize) {
10169 /* Set O_DIRECT if the file system supports it */
10170 if ((rc = fcntl(newfd, F_GETFL)) != -1)
10171 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
10173 #ifdef F_NOCACHE /* __APPLE__ */
10174 rc = fcntl(newfd, F_NOCACHE, 1);
10182 rc = mdb_env_copyfd2(env, newfd, flags);
10185 if (!(env->me_flags & MDB_NOSUBDIR))
10187 if (newfd != INVALID_HANDLE_VALUE)
10188 if (close(newfd) < 0 && rc == MDB_SUCCESS)
10195 mdb_env_copy(MDB_env *env, const char *path)
10197 return mdb_env_copy2(env, path, 0);
10201 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
10203 if (flag & ~CHANGEABLE)
10206 env->me_flags |= flag;
10208 env->me_flags &= ~flag;
10209 return MDB_SUCCESS;
10213 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
10218 *arg = env->me_flags & (CHANGEABLE|CHANGELESS);
10219 return MDB_SUCCESS;
10223 mdb_env_set_userctx(MDB_env *env, void *ctx)
10227 env->me_userctx = ctx;
10228 return MDB_SUCCESS;
10232 mdb_env_get_userctx(MDB_env *env)
10234 return env ? env->me_userctx : NULL;
10238 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
10243 env->me_assert_func = func;
10245 return MDB_SUCCESS;
10249 mdb_env_get_path(MDB_env *env, const char **arg)
10254 *arg = env->me_path;
10255 return MDB_SUCCESS;
10259 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
10265 return MDB_SUCCESS;
10268 /** Common code for #mdb_stat() and #mdb_env_stat().
10269 * @param[in] env the environment to operate in.
10270 * @param[in] db the #MDB_db record containing the stats to return.
10271 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
10272 * @return 0, this function always succeeds.
10275 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
10277 arg->ms_psize = env->me_psize;
10278 arg->ms_depth = db->md_depth;
10279 arg->ms_branch_pages = db->md_branch_pages;
10280 arg->ms_leaf_pages = db->md_leaf_pages;
10281 arg->ms_overflow_pages = db->md_overflow_pages;
10282 arg->ms_entries = db->md_entries;
10284 return MDB_SUCCESS;
10288 mdb_env_stat(MDB_env *env, MDB_stat *arg)
10292 if (env == NULL || arg == NULL)
10295 meta = mdb_env_pick_meta(env);
10297 return mdb_stat0(env, &meta->mm_dbs[MAIN_DBI], arg);
10301 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
10305 if (env == NULL || arg == NULL)
10308 meta = mdb_env_pick_meta(env);
10309 arg->me_mapaddr = meta->mm_address;
10310 arg->me_last_pgno = meta->mm_last_pg;
10311 arg->me_last_txnid = meta->mm_txnid;
10313 arg->me_mapsize = env->me_mapsize;
10314 arg->me_maxreaders = env->me_maxreaders;
10315 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : 0;
10316 return MDB_SUCCESS;
10319 /** Set the default comparison functions for a database.
10320 * Called immediately after a database is opened to set the defaults.
10321 * The user can then override them with #mdb_set_compare() or
10322 * #mdb_set_dupsort().
10323 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
10324 * @param[in] dbi A database handle returned by #mdb_dbi_open()
10327 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
10329 uint16_t f = txn->mt_dbs[dbi].md_flags;
10331 txn->mt_dbxs[dbi].md_cmp =
10332 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
10333 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
10335 txn->mt_dbxs[dbi].md_dcmp =
10336 !(f & MDB_DUPSORT) ? 0 :
10337 ((f & MDB_INTEGERDUP)
10338 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
10339 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
10342 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
10348 int rc, dbflag, exact;
10349 unsigned int unused = 0, seq;
10353 if (flags & ~VALID_FLAGS)
10355 if (txn->mt_flags & MDB_TXN_BLOCKED)
10356 return MDB_BAD_TXN;
10361 if (flags & PERSISTENT_FLAGS) {
10362 uint16_t f2 = flags & PERSISTENT_FLAGS;
10363 /* make sure flag changes get committed */
10364 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
10365 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
10366 txn->mt_flags |= MDB_TXN_DIRTY;
10369 mdb_default_cmp(txn, MAIN_DBI);
10370 return MDB_SUCCESS;
10373 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
10374 mdb_default_cmp(txn, MAIN_DBI);
10377 /* Is the DB already open? */
10378 len = strlen(name);
10379 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
10380 if (!txn->mt_dbxs[i].md_name.mv_size) {
10381 /* Remember this free slot */
10382 if (!unused) unused = i;
10385 if (len == txn->mt_dbxs[i].md_name.mv_size &&
10386 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
10388 return MDB_SUCCESS;
10392 /* If no free slot and max hit, fail */
10393 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
10394 return MDB_DBS_FULL;
10396 /* Cannot mix named databases with some mainDB flags */
10397 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
10398 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
10400 /* Find the DB info */
10401 dbflag = DB_NEW|DB_VALID|DB_USRVALID;
10404 key.mv_data = (void *)name;
10405 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
10406 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
10407 if (rc == MDB_SUCCESS) {
10408 /* make sure this is actually a DB */
10409 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
10410 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
10411 return MDB_INCOMPATIBLE;
10412 } else if (! (rc == MDB_NOTFOUND && (flags & MDB_CREATE))) {
10416 /* Done here so we cannot fail after creating a new DB */
10417 if ((namedup = strdup(name)) == NULL)
10421 /* MDB_NOTFOUND and MDB_CREATE: Create new DB */
10422 data.mv_size = sizeof(MDB_db);
10423 data.mv_data = &dummy;
10424 memset(&dummy, 0, sizeof(dummy));
10425 dummy.md_root = P_INVALID;
10426 dummy.md_flags = flags & PERSISTENT_FLAGS;
10427 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
10428 dbflag |= DB_DIRTY;
10434 /* Got info, register DBI in this txn */
10435 unsigned int slot = unused ? unused : txn->mt_numdbs;
10436 txn->mt_dbxs[slot].md_name.mv_data = namedup;
10437 txn->mt_dbxs[slot].md_name.mv_size = len;
10438 txn->mt_dbxs[slot].md_rel = NULL;
10439 txn->mt_dbflags[slot] = dbflag;
10440 /* txn-> and env-> are the same in read txns, use
10441 * tmp variable to avoid undefined assignment
10443 seq = ++txn->mt_env->me_dbiseqs[slot];
10444 txn->mt_dbiseqs[slot] = seq;
10446 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
10448 mdb_default_cmp(txn, slot);
10458 mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
10460 if (!arg || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
10463 if (txn->mt_flags & MDB_TXN_BLOCKED)
10464 return MDB_BAD_TXN;
10466 if (txn->mt_dbflags[dbi] & DB_STALE) {
10469 /* Stale, must read the DB's root. cursor_init does it for us. */
10470 mdb_cursor_init(&mc, txn, dbi, &mx);
10472 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
10475 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
10478 if (dbi < CORE_DBS || dbi >= env->me_maxdbs)
10480 ptr = env->me_dbxs[dbi].md_name.mv_data;
10481 /* If there was no name, this was already closed */
10483 env->me_dbxs[dbi].md_name.mv_data = NULL;
10484 env->me_dbxs[dbi].md_name.mv_size = 0;
10485 env->me_dbflags[dbi] = 0;
10486 env->me_dbiseqs[dbi]++;
10491 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
10493 /* We could return the flags for the FREE_DBI too but what's the point? */
10494 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10496 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
10497 return MDB_SUCCESS;
10500 /** Add all the DB's pages to the free list.
10501 * @param[in] mc Cursor on the DB to free.
10502 * @param[in] subs non-Zero to check for sub-DBs in this DB.
10503 * @return 0 on success, non-zero on failure.
10506 mdb_drop0(MDB_cursor *mc, int subs)
10510 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
10511 if (rc == MDB_SUCCESS) {
10512 MDB_txn *txn = mc->mc_txn;
10517 /* DUPSORT sub-DBs have no ovpages/DBs. Omit scanning leaves.
10518 * This also avoids any P_LEAF2 pages, which have no nodes.
10519 * Also if the DB doesn't have sub-DBs and has no overflow
10520 * pages, omit scanning leaves.
10522 if ((mc->mc_flags & C_SUB) ||
10523 (!subs && !mc->mc_db->md_overflow_pages))
10524 mdb_cursor_pop(mc);
10526 mdb_cursor_copy(mc, &mx);
10528 /* bump refcount for mx's pages */
10529 for (i=0; i<mc->mc_snum; i++)
10530 mdb_page_get(&mx, mc->mc_pg[i]->mp_pgno, &mx.mc_pg[i], NULL);
10532 while (mc->mc_snum > 0) {
10533 MDB_page *mp = mc->mc_pg[mc->mc_top];
10534 unsigned n = NUMKEYS(mp);
10536 for (i=0; i<n; i++) {
10537 ni = NODEPTR(mp, i);
10538 if (ni->mn_flags & F_BIGDATA) {
10541 memcpy(&pg, NODEDATA(ni), sizeof(pg));
10542 rc = mdb_page_get(mc, pg, &omp, NULL);
10545 mdb_cassert(mc, IS_OVERFLOW(omp));
10546 rc = mdb_midl_append_range(&txn->mt_free_pgs,
10547 pg, omp->mp_pages);
10550 mc->mc_db->md_overflow_pages -= omp->mp_pages;
10551 if (!mc->mc_db->md_overflow_pages && !subs)
10553 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
10554 mdb_xcursor_init1(mc, ni);
10555 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
10560 if (!subs && !mc->mc_db->md_overflow_pages)
10563 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
10565 for (i=0; i<n; i++) {
10567 ni = NODEPTR(mp, i);
10570 mdb_midl_xappend(txn->mt_free_pgs, pg);
10575 mc->mc_ki[mc->mc_top] = i;
10576 rc = mdb_cursor_sibling(mc, 1);
10578 if (rc != MDB_NOTFOUND)
10580 /* no more siblings, go back to beginning
10581 * of previous level.
10584 mdb_cursor_pop(mc);
10586 for (i=1; i<mc->mc_snum; i++) {
10588 mc->mc_pg[i] = mx.mc_pg[i];
10593 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
10596 txn->mt_flags |= MDB_TXN_ERROR;
10597 /* drop refcount for mx's pages */
10598 MDB_CURSOR_UNREF(&mx, 0);
10599 } else if (rc == MDB_NOTFOUND) {
10602 mc->mc_flags &= ~C_INITIALIZED;
10606 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
10608 MDB_cursor *mc, *m2;
10611 if ((unsigned)del > 1 || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10614 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
10617 if (TXN_DBI_CHANGED(txn, dbi))
10618 return MDB_BAD_DBI;
10620 rc = mdb_cursor_open(txn, dbi, &mc);
10624 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
10625 /* Invalidate the dropped DB's cursors */
10626 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
10627 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
10631 /* Can't delete the main DB */
10632 if (del && dbi >= CORE_DBS) {
10633 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, F_SUBDATA);
10635 txn->mt_dbflags[dbi] = DB_STALE;
10636 mdb_dbi_close(txn->mt_env, dbi);
10638 txn->mt_flags |= MDB_TXN_ERROR;
10641 /* reset the DB record, mark it dirty */
10642 txn->mt_dbflags[dbi] |= DB_DIRTY;
10643 txn->mt_dbs[dbi].md_depth = 0;
10644 txn->mt_dbs[dbi].md_branch_pages = 0;
10645 txn->mt_dbs[dbi].md_leaf_pages = 0;
10646 txn->mt_dbs[dbi].md_overflow_pages = 0;
10647 txn->mt_dbs[dbi].md_entries = 0;
10648 txn->mt_dbs[dbi].md_root = P_INVALID;
10650 txn->mt_flags |= MDB_TXN_DIRTY;
10653 mdb_cursor_close(mc);
10657 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
10659 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10662 txn->mt_dbxs[dbi].md_cmp = cmp;
10663 return MDB_SUCCESS;
10666 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
10668 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10671 txn->mt_dbxs[dbi].md_dcmp = cmp;
10672 return MDB_SUCCESS;
10675 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
10677 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10680 txn->mt_dbxs[dbi].md_rel = rel;
10681 return MDB_SUCCESS;
10684 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
10686 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10689 txn->mt_dbxs[dbi].md_relctx = ctx;
10690 return MDB_SUCCESS;
10694 mdb_env_get_maxkeysize(MDB_env *env)
10696 return ENV_MAXKEY(env);
10700 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
10702 unsigned int i, rdrs;
10705 int rc = 0, first = 1;
10709 if (!env->me_txns) {
10710 return func("(no reader locks)\n", ctx);
10712 rdrs = env->me_txns->mti_numreaders;
10713 mr = env->me_txns->mti_readers;
10714 for (i=0; i<rdrs; i++) {
10715 if (mr[i].mr_pid) {
10716 txnid_t txnid = mr[i].mr_txnid;
10717 sprintf(buf, txnid == (txnid_t)-1 ?
10718 "%10d %"Z"x -\n" : "%10d %"Z"x %"Yu"\n",
10719 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
10722 rc = func(" pid thread txnid\n", ctx);
10726 rc = func(buf, ctx);
10732 rc = func("(no active readers)\n", ctx);
10737 /** Insert pid into list if not already present.
10738 * return -1 if already present.
10741 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
10743 /* binary search of pid in list */
10745 unsigned cursor = 1;
10747 unsigned n = ids[0];
10750 unsigned pivot = n >> 1;
10751 cursor = base + pivot + 1;
10752 val = pid - ids[cursor];
10757 } else if ( val > 0 ) {
10762 /* found, so it's a duplicate */
10771 for (n = ids[0]; n > cursor; n--)
10778 mdb_reader_check(MDB_env *env, int *dead)
10784 return env->me_txns ? mdb_reader_check0(env, 0, dead) : MDB_SUCCESS;
10787 /** As #mdb_reader_check(). rlocked = <caller locked the reader mutex>. */
10789 mdb_reader_check0(MDB_env *env, int rlocked, int *dead)
10791 mdb_mutexref_t rmutex = rlocked ? NULL : env->me_rmutex;
10792 unsigned int i, j, rdrs;
10794 MDB_PID_T *pids, pid;
10795 int rc = MDB_SUCCESS, count = 0;
10797 rdrs = env->me_txns->mti_numreaders;
10798 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
10802 mr = env->me_txns->mti_readers;
10803 for (i=0; i<rdrs; i++) {
10804 pid = mr[i].mr_pid;
10805 if (pid && pid != env->me_pid) {
10806 if (mdb_pid_insert(pids, pid) == 0) {
10807 if (!mdb_reader_pid(env, Pidcheck, pid)) {
10808 /* Stale reader found */
10811 if ((rc = LOCK_MUTEX0(rmutex)) != 0) {
10812 if ((rc = mdb_mutex_failed(env, rmutex, rc)))
10814 rdrs = 0; /* the above checked all readers */
10816 /* Recheck, a new process may have reused pid */
10817 if (mdb_reader_pid(env, Pidcheck, pid))
10821 for (; j<rdrs; j++)
10822 if (mr[j].mr_pid == pid) {
10823 DPRINTF(("clear stale reader pid %u txn %"Yd,
10824 (unsigned) pid, mr[j].mr_txnid));
10829 UNLOCK_MUTEX(rmutex);
10840 #ifdef MDB_ROBUST_SUPPORTED
10841 /** Handle #LOCK_MUTEX0() failure.
10842 * Try to repair the lock file if the mutex owner died.
10843 * @param[in] env the environment handle
10844 * @param[in] mutex LOCK_MUTEX0() mutex
10845 * @param[in] rc LOCK_MUTEX0() error (nonzero)
10846 * @return 0 on success with the mutex locked, or an error code on failure.
10849 mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc)
10854 if (rc == MDB_OWNERDEAD) {
10855 /* We own the mutex. Clean up after dead previous owner. */
10857 rlocked = (mutex == env->me_rmutex);
10859 /* Keep mti_txnid updated, otherwise next writer can
10860 * overwrite data which latest meta page refers to.
10862 meta = mdb_env_pick_meta(env);
10863 env->me_txns->mti_txnid = meta->mm_txnid;
10864 /* env is hosed if the dead thread was ours */
10866 env->me_flags |= MDB_FATAL_ERROR;
10867 env->me_txn = NULL;
10871 DPRINTF(("%cmutex owner died, %s", (rlocked ? 'r' : 'w'),
10872 (rc ? "this process' env is hosed" : "recovering")));
10873 rc2 = mdb_reader_check0(env, rlocked, NULL);
10875 rc2 = mdb_mutex_consistent(mutex);
10876 if (rc || (rc = rc2)) {
10877 DPRINTF(("LOCK_MUTEX recovery failed, %s", mdb_strerror(rc)));
10878 UNLOCK_MUTEX(mutex);
10884 DPRINTF(("LOCK_MUTEX failed, %s", mdb_strerror(rc)));
10889 #endif /* MDB_ROBUST_SUPPORTED */
10892 #if defined(_WIN32)
10893 static int utf8_to_utf16(const char *src, int srcsize, wchar_t **dst, int *dstsize)
10897 need = MultiByteToWideChar(CP_UTF8, 0, src, srcsize, NULL, 0);
10898 if (need == 0xFFFD)
10902 result = malloc(sizeof(wchar_t) * need);
10905 MultiByteToWideChar(CP_UTF8, 0, src, srcsize, result, need);
10911 #endif /* defined(_WIN32) */