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-2015 Howard Chu, Symas Corp.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted only as authorized by the OpenLDAP
15 * A copy of this license is available in the file LICENSE in the
16 * top-level directory of the distribution or, alternatively, at
17 * <http://www.OpenLDAP.org/license.html>.
19 * This code is derived from btree.c written by Martin Hedenfalk.
21 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
23 * Permission to use, copy, modify, and distribute this software for any
24 * purpose with or without fee is hereby granted, provided that the above
25 * copyright notice and this permission notice appear in all copies.
27 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
28 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
29 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
30 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
31 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
32 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
33 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
38 #if defined(MDB_VL32) || defined(__WIN64__)
39 #define _FILE_OFFSET_BITS 64
45 /* We use native NT APIs to setup the memory map, so that we can
46 * let the DB file grow incrementally instead of always preallocating
47 * the full size. These APIs are defined in <wdm.h> and <ntifs.h>
48 * but those headers are meant for driver-level development and
49 * conflict with the regular user-level headers, so we explicitly
50 * declare them here. Using these APIs also means we must link to
51 * ntdll.dll, which is not linked by default in user code.
54 NtCreateSection(OUT PHANDLE sh, IN ACCESS_MASK acc,
55 IN void * oa OPTIONAL,
56 IN PLARGE_INTEGER ms OPTIONAL,
57 IN ULONG pp, IN ULONG aa, IN HANDLE fh OPTIONAL);
59 typedef enum _SECTION_INHERIT {
65 NtMapViewOfSection(IN PHANDLE sh, IN HANDLE ph,
66 IN OUT PVOID *addr, IN ULONG_PTR zbits,
67 IN SIZE_T cs, IN OUT PLARGE_INTEGER off OPTIONAL,
68 IN OUT PSIZE_T vs, IN SECTION_INHERIT ih,
69 IN ULONG at, IN ULONG pp);
74 /** getpid() returns int; MinGW defines pid_t but MinGW64 typedefs it
75 * as int64 which is wrong. MSVC doesn't define it at all, so just
79 #define MDB_THR_T DWORD
80 #include <sys/types.h>
83 # include <sys/param.h>
85 # define LITTLE_ENDIAN 1234
86 # define BIG_ENDIAN 4321
87 # define BYTE_ORDER LITTLE_ENDIAN
89 # define SSIZE_MAX INT_MAX
93 #include <sys/types.h>
95 #define MDB_PID_T pid_t
96 #define MDB_THR_T pthread_t
97 #include <sys/param.h>
100 #ifdef HAVE_SYS_FILE_H
101 #include <sys/file.h>
106 #if defined(__mips) && defined(__linux)
107 /* MIPS has cache coherency issues, requires explicit cache control */
108 #include <asm/cachectl.h>
109 extern int cacheflush(char *addr, int nbytes, int cache);
110 #define CACHEFLUSH(addr, bytes, cache) cacheflush(addr, bytes, cache)
112 #define CACHEFLUSH(addr, bytes, cache)
115 #if defined(__linux) && !defined(MDB_FDATASYNC_WORKS)
116 /** fdatasync is broken on ext3/ext4fs on older kernels, see
117 * description in #mdb_env_open2 comments. You can safely
118 * define MDB_FDATASYNC_WORKS if this code will only be run
119 * on kernels 3.6 and newer.
121 #define BROKEN_FDATASYNC
127 #include <inttypes.h>
135 typedef SSIZE_T ssize_t;
140 #if defined(__sun) || defined(ANDROID)
141 /* Most platforms have posix_memalign, older may only have memalign */
142 #define HAVE_MEMALIGN 1
146 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
147 #include <netinet/in.h>
148 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
151 #if defined(__APPLE__) || defined (BSD)
152 # if !(defined(MDB_USE_POSIX_MUTEX) || defined(MDB_USE_POSIX_SEM))
153 # define MDB_USE_SYSV_SEM 1
155 # define MDB_FDATASYNC fsync
156 #elif defined(ANDROID)
157 # define MDB_FDATASYNC fsync
162 #ifdef MDB_USE_POSIX_SEM
163 # define MDB_USE_HASH 1
164 #include <semaphore.h>
165 #elif defined(MDB_USE_SYSV_SEM)
168 #ifdef _SEM_SEMUN_UNDEFINED
171 struct semid_ds *buf;
172 unsigned short *array;
174 #endif /* _SEM_SEMUN_UNDEFINED */
176 #define MDB_USE_POSIX_MUTEX 1
177 #endif /* MDB_USE_POSIX_SEM */
180 #if defined(_WIN32) + defined(MDB_USE_POSIX_SEM) + defined(MDB_USE_SYSV_SEM) \
181 + defined(MDB_USE_POSIX_MUTEX) != 1
182 # error "Ambiguous shared-lock implementation"
186 #include <valgrind/memcheck.h>
187 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
188 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
189 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
190 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
191 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
193 #define VGMEMP_CREATE(h,r,z)
194 #define VGMEMP_ALLOC(h,a,s)
195 #define VGMEMP_FREE(h,a)
196 #define VGMEMP_DESTROY(h)
197 #define VGMEMP_DEFINED(a,s)
201 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
202 /* Solaris just defines one or the other */
203 # define LITTLE_ENDIAN 1234
204 # define BIG_ENDIAN 4321
205 # ifdef _LITTLE_ENDIAN
206 # define BYTE_ORDER LITTLE_ENDIAN
208 # define BYTE_ORDER BIG_ENDIAN
211 # define BYTE_ORDER __BYTE_ORDER
215 #ifndef LITTLE_ENDIAN
216 #define LITTLE_ENDIAN __LITTLE_ENDIAN
219 #define BIG_ENDIAN __BIG_ENDIAN
222 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
223 #define MISALIGNED_OK 1
229 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
230 # error "Unknown or unsupported endianness (BYTE_ORDER)"
231 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
232 # error "Two's complement, reasonably sized integer types, please"
236 /** Put infrequently used env functions in separate section */
238 # define ESECT __attribute__ ((section("__TEXT,text_env")))
240 # define ESECT __attribute__ ((section("text_env")))
247 #define CALL_CONV WINAPI
252 /** @defgroup internal LMDB Internals
255 /** @defgroup compat Compatibility Macros
256 * A bunch of macros to minimize the amount of platform-specific ifdefs
257 * needed throughout the rest of the code. When the features this library
258 * needs are similar enough to POSIX to be hidden in a one-or-two line
259 * replacement, this macro approach is used.
263 /** Features under development */
268 /** Wrapper around __func__, which is a C99 feature */
269 #if __STDC_VERSION__ >= 199901L
270 # define mdb_func_ __func__
271 #elif __GNUC__ >= 2 || _MSC_VER >= 1300
272 # define mdb_func_ __FUNCTION__
274 /* If a debug message says <mdb_unknown>(), update the #if statements above */
275 # define mdb_func_ "<mdb_unknown>"
278 /* Internal error codes, not exposed outside liblmdb */
279 #define MDB_NO_ROOT (MDB_LAST_ERRCODE + 10)
281 #define MDB_OWNERDEAD ((int) WAIT_ABANDONED)
282 #elif defined MDB_USE_SYSV_SEM
283 #define MDB_OWNERDEAD (MDB_LAST_ERRCODE + 11)
284 #elif defined(MDB_USE_POSIX_MUTEX) && defined(EOWNERDEAD)
285 #define MDB_OWNERDEAD EOWNERDEAD /**< #LOCK_MUTEX0() result if dead owner */
289 #define GLIBC_VER ((__GLIBC__ << 16 )| __GLIBC_MINOR__)
291 /** Some platforms define the EOWNERDEAD error code
292 * even though they don't support Robust Mutexes.
293 * Compile with -DMDB_USE_ROBUST=0, or use some other
294 * mechanism like -DMDB_USE_SYSV_SEM instead of
295 * -DMDB_USE_POSIX_MUTEX. (SysV semaphores are
296 * also Robust, but some systems don't support them
299 #ifndef MDB_USE_ROBUST
300 /* Android currently lacks Robust Mutex support. So does glibc < 2.4. */
301 # if defined(MDB_USE_POSIX_MUTEX) && (defined(ANDROID) || \
302 (defined(__GLIBC__) && GLIBC_VER < 0x020004))
303 # define MDB_USE_ROBUST 0
305 # define MDB_USE_ROBUST 1
306 /* glibc < 2.12 only provided _np API */
307 # if defined(__GLIBC__) && GLIBC_VER < 0x02000c
308 # define PTHREAD_MUTEX_ROBUST PTHREAD_MUTEX_ROBUST_NP
309 # define pthread_mutexattr_setrobust(attr, flag) pthread_mutexattr_setrobust_np(attr, flag)
310 # define pthread_mutex_consistent(mutex) pthread_mutex_consistent_np(mutex)
313 #endif /* MDB_USE_ROBUST */
315 #if defined(MDB_OWNERDEAD) && MDB_USE_ROBUST
316 #define MDB_ROBUST_SUPPORTED 1
320 #define MDB_USE_HASH 1
321 #define MDB_PIDLOCK 0
322 #define THREAD_RET DWORD
323 #define pthread_t HANDLE
324 #define pthread_mutex_t HANDLE
325 #define pthread_cond_t HANDLE
326 typedef HANDLE mdb_mutex_t, mdb_mutexref_t;
327 #define pthread_key_t DWORD
328 #define pthread_self() GetCurrentThreadId()
329 #define pthread_key_create(x,y) \
330 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
331 #define pthread_key_delete(x) TlsFree(x)
332 #define pthread_getspecific(x) TlsGetValue(x)
333 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
334 #define pthread_mutex_unlock(x) ReleaseMutex(*x)
335 #define pthread_mutex_lock(x) WaitForSingleObject(*x, INFINITE)
336 #define pthread_cond_signal(x) SetEvent(*x)
337 #define pthread_cond_wait(cond,mutex) do{SignalObjectAndWait(*mutex, *cond, INFINITE, FALSE); WaitForSingleObject(*mutex, INFINITE);}while(0)
338 #define THREAD_CREATE(thr,start,arg) thr=CreateThread(NULL,0,start,arg,0,NULL)
339 #define THREAD_FINISH(thr) WaitForSingleObject(thr, INFINITE)
340 #define LOCK_MUTEX0(mutex) WaitForSingleObject(mutex, INFINITE)
341 #define UNLOCK_MUTEX(mutex) ReleaseMutex(mutex)
342 #define mdb_mutex_consistent(mutex) 0
343 #define getpid() GetCurrentProcessId()
344 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
345 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
346 #define ErrCode() GetLastError()
347 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
348 #define close(fd) (CloseHandle(fd) ? 0 : -1)
349 #define munmap(ptr,len) UnmapViewOfFile(ptr)
350 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
351 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
353 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
357 #define THREAD_RET void *
358 #define THREAD_CREATE(thr,start,arg) pthread_create(&thr,NULL,start,arg)
359 #define THREAD_FINISH(thr) pthread_join(thr,NULL)
360 #define Z "z" /**< printf format modifier for size_t */
362 /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
363 #define MDB_PIDLOCK 1
365 #ifdef MDB_USE_POSIX_SEM
367 typedef sem_t *mdb_mutex_t, *mdb_mutexref_t;
368 #define LOCK_MUTEX0(mutex) mdb_sem_wait(mutex)
369 #define UNLOCK_MUTEX(mutex) sem_post(mutex)
372 mdb_sem_wait(sem_t *sem)
375 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
379 #elif defined MDB_USE_SYSV_SEM
381 typedef struct mdb_mutex {
385 } mdb_mutex_t[1], *mdb_mutexref_t;
387 #define LOCK_MUTEX0(mutex) mdb_sem_wait(mutex)
388 #define UNLOCK_MUTEX(mutex) do { \
389 struct sembuf sb = { 0, 1, SEM_UNDO }; \
390 sb.sem_num = (mutex)->semnum; \
391 *(mutex)->locked = 0; \
392 semop((mutex)->semid, &sb, 1); \
396 mdb_sem_wait(mdb_mutexref_t sem)
398 int rc, *locked = sem->locked;
399 struct sembuf sb = { 0, -1, SEM_UNDO };
400 sb.sem_num = sem->semnum;
402 if (!semop(sem->semid, &sb, 1)) {
403 rc = *locked ? MDB_OWNERDEAD : MDB_SUCCESS;
407 } while ((rc = errno) == EINTR);
411 #define mdb_mutex_consistent(mutex) 0
413 #else /* MDB_USE_POSIX_MUTEX: */
414 /** Shared mutex/semaphore as it is stored (mdb_mutex_t), and as
415 * local variables keep it (mdb_mutexref_t).
417 * An mdb_mutex_t can be assigned to an mdb_mutexref_t. They can
418 * be the same, or an array[size 1] and a pointer.
421 typedef pthread_mutex_t mdb_mutex_t[1], *mdb_mutexref_t;
423 /** Lock the reader or writer mutex.
424 * Returns 0 or a code to give #mdb_mutex_failed(), as in #LOCK_MUTEX().
426 #define LOCK_MUTEX0(mutex) pthread_mutex_lock(mutex)
427 /** Unlock the reader or writer mutex.
429 #define UNLOCK_MUTEX(mutex) pthread_mutex_unlock(mutex)
430 /** Mark mutex-protected data as repaired, after death of previous owner.
432 #define mdb_mutex_consistent(mutex) pthread_mutex_consistent(mutex)
433 #endif /* MDB_USE_POSIX_SEM || MDB_USE_SYSV_SEM */
435 /** Get the error code for the last failed system function.
437 #define ErrCode() errno
439 /** An abstraction for a file handle.
440 * On POSIX systems file handles are small integers. On Windows
441 * they're opaque pointers.
445 /** A value for an invalid file handle.
446 * Mainly used to initialize file variables and signify that they are
449 #define INVALID_HANDLE_VALUE (-1)
451 /** Get the size of a memory page for the system.
452 * This is the basic size that the platform's memory manager uses, and is
453 * fundamental to the use of memory-mapped files.
455 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
468 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
470 #elif defined(MDB_USE_SYSV_SEM)
471 #define MNAME_LEN (sizeof(int))
473 #define MNAME_LEN (sizeof(pthread_mutex_t))
476 #ifdef MDB_USE_SYSV_SEM
477 #define SYSV_SEM_FLAG 1 /**< SysV sems in lockfile format */
479 #define SYSV_SEM_FLAG 0
484 #ifdef MDB_ROBUST_SUPPORTED
485 /** Lock mutex, handle any error, set rc = result.
486 * Return 0 on success, nonzero (not rc) on error.
488 #define LOCK_MUTEX(rc, env, mutex) \
489 (((rc) = LOCK_MUTEX0(mutex)) && \
490 ((rc) = mdb_mutex_failed(env, mutex, rc)))
491 static int mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc);
493 #define LOCK_MUTEX(rc, env, mutex) ((rc) = LOCK_MUTEX0(mutex))
494 #define mdb_mutex_failed(env, mutex, rc) (rc)
498 /** A flag for opening a file and requesting synchronous data writes.
499 * This is only used when writing a meta page. It's not strictly needed;
500 * we could just do a normal write and then immediately perform a flush.
501 * But if this flag is available it saves us an extra system call.
503 * @note If O_DSYNC is undefined but exists in /usr/include,
504 * preferably set some compiler flag to get the definition.
508 # define MDB_DSYNC O_DSYNC
510 # define MDB_DSYNC O_SYNC
515 /** Function for flushing the data of a file. Define this to fsync
516 * if fdatasync() is not supported.
518 #ifndef MDB_FDATASYNC
519 # define MDB_FDATASYNC fdatasync
523 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
534 /** A page number in the database.
535 * Note that 64 bit page numbers are overkill, since pages themselves
536 * already represent 12-13 bits of addressable memory, and the OS will
537 * always limit applications to a maximum of 63 bits of address space.
539 * @note In the #MDB_node structure, we only store 48 bits of this value,
540 * which thus limits us to only 60 bits of addressable data.
542 typedef MDB_ID pgno_t;
544 /** A transaction ID.
545 * See struct MDB_txn.mt_txnid for details.
547 typedef MDB_ID txnid_t;
549 /** @defgroup debug Debug Macros
553 /** Enable debug output. Needs variable argument macros (a C99 feature).
554 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
555 * read from and written to the database (used for free space management).
561 static int mdb_debug;
562 static txnid_t mdb_debug_start;
564 /** Print a debug message with printf formatting.
565 * Requires double parenthesis around 2 or more args.
567 # define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
568 # define DPRINTF0(fmt, ...) \
569 fprintf(stderr, "%s:%d " fmt "\n", mdb_func_, __LINE__, __VA_ARGS__)
571 # define DPRINTF(args) ((void) 0)
573 /** Print a debug string.
574 * The string is printed literally, with no format processing.
576 #define DPUTS(arg) DPRINTF(("%s", arg))
577 /** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
579 (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
582 /** @brief The maximum size of a database page.
584 * It is 32k or 64k, since value-PAGEBASE must fit in
585 * #MDB_page.%mp_upper.
587 * LMDB will use database pages < OS pages if needed.
588 * That causes more I/O in write transactions: The OS must
589 * know (read) the whole page before writing a partial page.
591 * Note that we don't currently support Huge pages. On Linux,
592 * regular data files cannot use Huge pages, and in general
593 * Huge pages aren't actually pageable. We rely on the OS
594 * demand-pager to read our data and page it out when memory
595 * pressure from other processes is high. So until OSs have
596 * actual paging support for Huge pages, they're not viable.
598 #define MAX_PAGESIZE (PAGEBASE ? 0x10000 : 0x8000)
600 /** The minimum number of keys required in a database page.
601 * Setting this to a larger value will place a smaller bound on the
602 * maximum size of a data item. Data items larger than this size will
603 * be pushed into overflow pages instead of being stored directly in
604 * the B-tree node. This value used to default to 4. With a page size
605 * of 4096 bytes that meant that any item larger than 1024 bytes would
606 * go into an overflow page. That also meant that on average 2-3KB of
607 * each overflow page was wasted space. The value cannot be lower than
608 * 2 because then there would no longer be a tree structure. With this
609 * value, items larger than 2KB will go into overflow pages, and on
610 * average only 1KB will be wasted.
612 #define MDB_MINKEYS 2
614 /** A stamp that identifies a file as an LMDB file.
615 * There's nothing special about this value other than that it is easily
616 * recognizable, and it will reflect any byte order mismatches.
618 #define MDB_MAGIC 0xBEEFC0DE
620 /** The version number for a database's datafile format. */
621 #define MDB_DATA_VERSION ((MDB_DEVEL) ? 999 : 1)
622 /** The version number for a database's lockfile format. */
623 #define MDB_LOCK_VERSION ((MDB_DEVEL) ? 999 : 1)
625 /** @brief The max size of a key we can write, or 0 for computed max.
627 * This macro should normally be left alone or set to 0.
628 * Note that a database with big keys or dupsort data cannot be
629 * reliably modified by a liblmdb which uses a smaller max.
630 * The default is 511 for backwards compat, or 0 when #MDB_DEVEL.
632 * Other values are allowed, for backwards compat. However:
633 * A value bigger than the computed max can break if you do not
634 * know what you are doing, and liblmdb <= 0.9.10 can break when
635 * modifying a DB with keys/dupsort data bigger than its max.
637 * Data items in an #MDB_DUPSORT database are also limited to
638 * this size, since they're actually keys of a sub-DB. Keys and
639 * #MDB_DUPSORT data items must fit on a node in a regular page.
641 #ifndef MDB_MAXKEYSIZE
642 #define MDB_MAXKEYSIZE ((MDB_DEVEL) ? 0 : 511)
645 /** The maximum size of a key we can write to the environment. */
647 #define ENV_MAXKEY(env) (MDB_MAXKEYSIZE)
649 #define ENV_MAXKEY(env) ((env)->me_maxkey)
652 /** @brief The maximum size of a data item.
654 * We only store a 32 bit value for node sizes.
656 #define MAXDATASIZE 0xffffffffUL
659 /** Key size which fits in a #DKBUF.
662 #define DKBUF_MAXKEYSIZE ((MDB_MAXKEYSIZE) > 0 ? (MDB_MAXKEYSIZE) : 511)
665 * This is used for printing a hex dump of a key's contents.
667 #define DKBUF char kbuf[DKBUF_MAXKEYSIZE*2+1]
668 /** Display a key in hex.
670 * Invoke a function to display a key in hex.
672 #define DKEY(x) mdb_dkey(x, kbuf)
678 /** An invalid page number.
679 * Mainly used to denote an empty tree.
681 #define P_INVALID (~(pgno_t)0)
683 /** Test if the flags \b f are set in a flag word \b w. */
684 #define F_ISSET(w, f) (((w) & (f)) == (f))
686 /** Round \b n up to an even number. */
687 #define EVEN(n) (((n) + 1U) & -2) /* sign-extending -2 to match n+1U */
689 /** Used for offsets within a single page.
690 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
693 typedef uint16_t indx_t;
695 /** Default size of memory map.
696 * This is certainly too small for any actual applications. Apps should always set
697 * the size explicitly using #mdb_env_set_mapsize().
699 #define DEFAULT_MAPSIZE 1048576
701 /** @defgroup readers Reader Lock Table
702 * Readers don't acquire any locks for their data access. Instead, they
703 * simply record their transaction ID in the reader table. The reader
704 * mutex is needed just to find an empty slot in the reader table. The
705 * slot's address is saved in thread-specific data so that subsequent read
706 * transactions started by the same thread need no further locking to proceed.
708 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
710 * No reader table is used if the database is on a read-only filesystem, or
711 * if #MDB_NOLOCK is set.
713 * Since the database uses multi-version concurrency control, readers don't
714 * actually need any locking. This table is used to keep track of which
715 * readers are using data from which old transactions, so that we'll know
716 * when a particular old transaction is no longer in use. Old transactions
717 * that have discarded any data pages can then have those pages reclaimed
718 * for use by a later write transaction.
720 * The lock table is constructed such that reader slots are aligned with the
721 * processor's cache line size. Any slot is only ever used by one thread.
722 * This alignment guarantees that there will be no contention or cache
723 * thrashing as threads update their own slot info, and also eliminates
724 * any need for locking when accessing a slot.
726 * A writer thread will scan every slot in the table to determine the oldest
727 * outstanding reader transaction. Any freed pages older than this will be
728 * reclaimed by the writer. The writer doesn't use any locks when scanning
729 * this table. This means that there's no guarantee that the writer will
730 * see the most up-to-date reader info, but that's not required for correct
731 * operation - all we need is to know the upper bound on the oldest reader,
732 * we don't care at all about the newest reader. So the only consequence of
733 * reading stale information here is that old pages might hang around a
734 * while longer before being reclaimed. That's actually good anyway, because
735 * the longer we delay reclaiming old pages, the more likely it is that a
736 * string of contiguous pages can be found after coalescing old pages from
737 * many old transactions together.
740 /** Number of slots in the reader table.
741 * This value was chosen somewhat arbitrarily. 126 readers plus a
742 * couple mutexes fit exactly into 8KB on my development machine.
743 * Applications should set the table size using #mdb_env_set_maxreaders().
745 #define DEFAULT_READERS 126
747 /** The size of a CPU cache line in bytes. We want our lock structures
748 * aligned to this size to avoid false cache line sharing in the
750 * This value works for most CPUs. For Itanium this should be 128.
756 /** The information we store in a single slot of the reader table.
757 * In addition to a transaction ID, we also record the process and
758 * thread ID that owns a slot, so that we can detect stale information,
759 * e.g. threads or processes that went away without cleaning up.
760 * @note We currently don't check for stale records. We simply re-init
761 * the table when we know that we're the only process opening the
764 typedef struct MDB_rxbody {
765 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
766 * Multiple readers that start at the same time will probably have the
767 * same ID here. Again, it's not important to exclude them from
768 * anything; all we need to know is which version of the DB they
769 * started from so we can avoid overwriting any data used in that
770 * particular version.
772 volatile txnid_t mrb_txnid;
773 /** The process ID of the process owning this reader txn. */
774 volatile MDB_PID_T mrb_pid;
775 /** The thread ID of the thread owning this txn. */
776 volatile MDB_THR_T mrb_tid;
779 /** The actual reader record, with cacheline padding. */
780 typedef struct MDB_reader {
783 /** shorthand for mrb_txnid */
784 #define mr_txnid mru.mrx.mrb_txnid
785 #define mr_pid mru.mrx.mrb_pid
786 #define mr_tid mru.mrx.mrb_tid
787 /** cache line alignment */
788 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
792 /** The header for the reader table.
793 * The table resides in a memory-mapped file. (This is a different file
794 * than is used for the main database.)
796 * For POSIX the actual mutexes reside in the shared memory of this
797 * mapped file. On Windows, mutexes are named objects allocated by the
798 * kernel; we store the mutex names in this mapped file so that other
799 * processes can grab them. This same approach is also used on
800 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
801 * process-shared POSIX mutexes. For these cases where a named object
802 * is used, the object name is derived from a 64 bit FNV hash of the
803 * environment pathname. As such, naming collisions are extremely
804 * unlikely. If a collision occurs, the results are unpredictable.
806 typedef struct MDB_txbody {
807 /** Stamp identifying this as an LMDB file. It must be set
810 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
812 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
813 char mtb_rmname[MNAME_LEN];
814 #elif defined(MDB_USE_SYSV_SEM)
818 /** Mutex protecting access to this table.
819 * This is the reader table lock used with LOCK_MUTEX().
821 mdb_mutex_t mtb_rmutex;
823 /** The ID of the last transaction committed to the database.
824 * This is recorded here only for convenience; the value can always
825 * be determined by reading the main database meta pages.
827 volatile txnid_t mtb_txnid;
828 /** The number of slots that have been used in the reader table.
829 * This always records the maximum count, it is not decremented
830 * when readers release their slots.
832 volatile unsigned mtb_numreaders;
835 /** The actual reader table definition. */
836 typedef struct MDB_txninfo {
839 #define mti_magic mt1.mtb.mtb_magic
840 #define mti_format mt1.mtb.mtb_format
841 #define mti_rmutex mt1.mtb.mtb_rmutex
842 #define mti_rmname mt1.mtb.mtb_rmname
843 #define mti_txnid mt1.mtb.mtb_txnid
844 #define mti_numreaders mt1.mtb.mtb_numreaders
845 #ifdef MDB_USE_SYSV_SEM
846 #define mti_semid mt1.mtb.mtb_semid
847 #define mti_rlocked mt1.mtb.mtb_rlocked
849 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
852 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
853 char mt2_wmname[MNAME_LEN];
854 #define mti_wmname mt2.mt2_wmname
855 #elif defined MDB_USE_SYSV_SEM
857 #define mti_wlocked mt2.mt2_wlocked
859 mdb_mutex_t mt2_wmutex;
860 #define mti_wmutex mt2.mt2_wmutex
862 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
864 MDB_reader mti_readers[1];
867 /** Lockfile format signature: version, features and field layout */
868 #define MDB_LOCK_FORMAT \
870 ((MDB_LOCK_VERSION) \
871 /* Flags which describe functionality */ \
872 + (SYSV_SEM_FLAG << 18) \
873 + (((MDB_PIDLOCK) != 0) << 16)))
876 /** Common header for all page types.
877 * Overflow records occupy a number of contiguous pages with no
878 * headers on any page after the first.
880 typedef struct MDB_page {
881 #define mp_pgno mp_p.p_pgno
882 #define mp_next mp_p.p_next
884 pgno_t p_pgno; /**< page number */
885 struct MDB_page *p_next; /**< for in-memory list of freed pages */
888 /** @defgroup mdb_page Page Flags
890 * Flags for the page headers.
893 #define P_BRANCH 0x01 /**< branch page */
894 #define P_LEAF 0x02 /**< leaf page */
895 #define P_OVERFLOW 0x04 /**< overflow page */
896 #define P_META 0x08 /**< meta page */
897 #define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
898 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
899 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
900 #define P_LOOSE 0x4000 /**< page was dirtied then freed, can be reused */
901 #define P_KEEP 0x8000 /**< leave this page alone during spill */
903 uint16_t mp_flags; /**< @ref mdb_page */
904 #define mp_lower mp_pb.pb.pb_lower
905 #define mp_upper mp_pb.pb.pb_upper
906 #define mp_pages mp_pb.pb_pages
909 indx_t pb_lower; /**< lower bound of free space */
910 indx_t pb_upper; /**< upper bound of free space */
912 uint32_t pb_pages; /**< number of overflow pages */
914 indx_t mp_ptrs[1]; /**< dynamic size */
917 /** Size of the page header, excluding dynamic data at the end */
918 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
920 /** Address of first usable data byte in a page, after the header */
921 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
923 /** ITS#7713, change PAGEBASE to handle 65536 byte pages */
924 #define PAGEBASE ((MDB_DEVEL) ? PAGEHDRSZ : 0)
926 /** Number of nodes on a page */
927 #define NUMKEYS(p) (((p)->mp_lower - (PAGEHDRSZ-PAGEBASE)) >> 1)
929 /** The amount of space remaining in the page */
930 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
932 /** The percentage of space used in the page, in tenths of a percent. */
933 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
934 ((env)->me_psize - PAGEHDRSZ))
935 /** The minimum page fill factor, in tenths of a percent.
936 * Pages emptier than this are candidates for merging.
938 #define FILL_THRESHOLD 250
940 /** Test if a page is a leaf page */
941 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
942 /** Test if a page is a LEAF2 page */
943 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
944 /** Test if a page is a branch page */
945 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
946 /** Test if a page is an overflow page */
947 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
948 /** Test if a page is a sub page */
949 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
951 /** The number of overflow pages needed to store the given size. */
952 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
954 /** Link in #MDB_txn.%mt_loose_pgs list */
955 #define NEXT_LOOSE_PAGE(p) (*(MDB_page **)((p) + 2))
957 /** Header for a single key/data pair within a page.
958 * Used in pages of type #P_BRANCH and #P_LEAF without #P_LEAF2.
959 * We guarantee 2-byte alignment for 'MDB_node's.
961 typedef struct MDB_node {
962 /** lo and hi are used for data size on leaf nodes and for
963 * child pgno on branch nodes. On 64 bit platforms, flags
964 * is also used for pgno. (Branch nodes have no flags).
965 * They are in host byte order in case that lets some
966 * accesses be optimized into a 32-bit word access.
968 #if BYTE_ORDER == LITTLE_ENDIAN
969 unsigned short mn_lo, mn_hi; /**< part of data size or pgno */
971 unsigned short mn_hi, mn_lo;
973 /** @defgroup mdb_node Node Flags
975 * Flags for node headers.
978 #define F_BIGDATA 0x01 /**< data put on overflow page */
979 #define F_SUBDATA 0x02 /**< data is a sub-database */
980 #define F_DUPDATA 0x04 /**< data has duplicates */
982 /** valid flags for #mdb_node_add() */
983 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
986 unsigned short mn_flags; /**< @ref mdb_node */
987 unsigned short mn_ksize; /**< key size */
988 char mn_data[1]; /**< key and data are appended here */
991 /** Size of the node header, excluding dynamic data at the end */
992 #define NODESIZE offsetof(MDB_node, mn_data)
994 /** Bit position of top word in page number, for shifting mn_flags */
995 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
997 /** Size of a node in a branch page with a given key.
998 * This is just the node header plus the key, there is no data.
1000 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
1002 /** Size of a node in a leaf page with a given key and data.
1003 * This is node header plus key plus data size.
1005 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
1007 /** Address of node \b i in page \b p */
1008 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i] + PAGEBASE))
1010 /** Address of the key for the node */
1011 #define NODEKEY(node) (void *)((node)->mn_data)
1013 /** Address of the data for a node */
1014 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
1016 /** Get the page number pointed to by a branch node */
1017 #define NODEPGNO(node) \
1018 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
1019 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
1020 /** Set the page number in a branch node */
1021 #define SETPGNO(node,pgno) do { \
1022 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
1023 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
1025 /** Get the size of the data in a leaf node */
1026 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
1027 /** Set the size of the data for a leaf node */
1028 #define SETDSZ(node,size) do { \
1029 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
1030 /** The size of a key in a node */
1031 #define NODEKSZ(node) ((node)->mn_ksize)
1033 /** Copy a page number from src to dst */
1034 #ifdef MISALIGNED_OK
1035 #define COPY_PGNO(dst,src) dst = src
1037 #if SIZE_MAX > 4294967295UL
1038 #define COPY_PGNO(dst,src) do { \
1039 unsigned short *s, *d; \
1040 s = (unsigned short *)&(src); \
1041 d = (unsigned short *)&(dst); \
1048 #define COPY_PGNO(dst,src) do { \
1049 unsigned short *s, *d; \
1050 s = (unsigned short *)&(src); \
1051 d = (unsigned short *)&(dst); \
1057 /** The address of a key in a LEAF2 page.
1058 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
1059 * There are no node headers, keys are stored contiguously.
1061 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
1063 /** Set the \b node's key into \b keyptr, if requested. */
1064 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
1065 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
1067 /** Set the \b node's key into \b key. */
1068 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
1070 /** Information about a single database in the environment. */
1071 typedef struct MDB_db {
1072 uint32_t md_pad; /**< also ksize for LEAF2 pages */
1073 uint16_t md_flags; /**< @ref mdb_dbi_open */
1074 uint16_t md_depth; /**< depth of this tree */
1075 pgno_t md_branch_pages; /**< number of internal pages */
1076 pgno_t md_leaf_pages; /**< number of leaf pages */
1077 pgno_t md_overflow_pages; /**< number of overflow pages */
1078 pgno_t md_entries; /**< number of data items */
1079 pgno_t md_root; /**< the root page of this tree */
1082 /** mdb_dbi_open flags */
1083 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
1084 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
1085 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
1086 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
1088 /** Handle for the DB used to track free pages. */
1090 /** Handle for the default DB. */
1092 /** Number of DBs in metapage (free and main) - also hardcoded elsewhere */
1095 /** Number of meta pages - also hardcoded elsewhere */
1098 /** Meta page content.
1099 * A meta page is the start point for accessing a database snapshot.
1100 * Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
1102 typedef struct MDB_meta {
1103 /** Stamp identifying this as an LMDB file. It must be set
1106 /** Version number of this file. Must be set to #MDB_DATA_VERSION. */
1107 uint32_t mm_version;
1109 union { /* always zero since we don't support fixed mapping in MDB_VL32 */
1113 #define mm_address mm_un.mmun_address
1115 void *mm_address; /**< address for fixed mapping */
1117 pgno_t mm_mapsize; /**< size of mmap region */
1118 MDB_db mm_dbs[CORE_DBS]; /**< first is free space, 2nd is main db */
1119 /** The size of pages used in this DB */
1120 #define mm_psize mm_dbs[FREE_DBI].md_pad
1121 /** Any persistent environment flags. @ref mdb_env */
1122 #define mm_flags mm_dbs[FREE_DBI].md_flags
1123 pgno_t mm_last_pg; /**< last used page in file */
1124 volatile txnid_t mm_txnid; /**< txnid that committed this page */
1127 /** Buffer for a stack-allocated meta page.
1128 * The members define size and alignment, and silence type
1129 * aliasing warnings. They are not used directly; that could
1130 * mean incorrectly using several union members in parallel.
1132 typedef union MDB_metabuf {
1135 char mm_pad[PAGEHDRSZ];
1140 /** Auxiliary DB info.
1141 * The information here is mostly static/read-only. There is
1142 * only a single copy of this record in the environment.
1144 typedef struct MDB_dbx {
1145 MDB_val md_name; /**< name of the database */
1146 MDB_cmp_func *md_cmp; /**< function for comparing keys */
1147 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
1148 MDB_rel_func *md_rel; /**< user relocate function */
1149 void *md_relctx; /**< user-provided context for md_rel */
1152 /** A database transaction.
1153 * Every operation requires a transaction handle.
1156 MDB_txn *mt_parent; /**< parent of a nested txn */
1157 /** Nested txn under this txn, set together with flag #MDB_TXN_HAS_CHILD */
1159 pgno_t mt_next_pgno; /**< next unallocated page */
1161 pgno_t mt_last_pgno; /**< last written page */
1163 /** The ID of this transaction. IDs are integers incrementing from 1.
1164 * Only committed write transactions increment the ID. If a transaction
1165 * aborts, the ID may be re-used by the next writer.
1168 MDB_env *mt_env; /**< the DB environment */
1169 /** The list of pages that became unused during this transaction.
1171 MDB_IDL mt_free_pgs;
1172 /** The list of loose pages that became unused and may be reused
1173 * in this transaction, linked through #NEXT_LOOSE_PAGE(page).
1175 MDB_page *mt_loose_pgs;
1176 /* #Number of loose pages (#mt_loose_pgs) */
1178 /** The sorted list of dirty pages we temporarily wrote to disk
1179 * because the dirty list was full. page numbers in here are
1180 * shifted left by 1, deleted slots have the LSB set.
1182 MDB_IDL mt_spill_pgs;
1184 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
1185 MDB_ID2L dirty_list;
1186 /** For read txns: This thread/txn's reader table slot, or NULL. */
1189 /** Array of records for each DB known in the environment. */
1191 /** Array of MDB_db records for each known DB */
1193 /** Array of sequence numbers for each DB handle */
1194 unsigned int *mt_dbiseqs;
1195 /** @defgroup mt_dbflag Transaction DB Flags
1199 #define DB_DIRTY 0x01 /**< DB was modified or is DUPSORT data */
1200 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
1201 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
1202 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
1203 #define DB_USRVALID 0x10 /**< As #DB_VALID, but not set for #FREE_DBI */
1205 /** In write txns, array of cursors for each DB */
1206 MDB_cursor **mt_cursors;
1207 /** Array of flags for each DB */
1208 unsigned char *mt_dbflags;
1210 /** List of read-only pages (actually chunks) */
1212 /** We map chunks of 16 pages. Even though Windows uses 4KB pages, all
1213 * mappings must begin on 64KB boundaries. So we round off all pgnos to
1214 * a chunk boundary. We do the same on Linux for symmetry, and also to
1215 * reduce the frequency of mmap/munmap calls.
1217 #define MDB_RPAGE_CHUNK 16
1218 #define MDB_TRPAGE_SIZE 4096 /**< size of #mt_rpages array of chunks */
1219 #define MDB_TRPAGE_MAX (MDB_TRPAGE_SIZE-1) /**< maximum chunk index */
1220 unsigned int mt_rpcheck; /**< threshold for reclaiming unref'd chunks */
1222 /** Number of DB records in use, or 0 when the txn is finished.
1223 * This number only ever increments until the txn finishes; we
1224 * don't decrement it when individual DB handles are closed.
1228 /** @defgroup mdb_txn Transaction Flags
1232 /** #mdb_txn_begin() flags */
1233 #define MDB_TXN_BEGIN_FLAGS (MDB_NOMETASYNC|MDB_NOSYNC|MDB_RDONLY)
1234 #define MDB_TXN_NOMETASYNC MDB_NOMETASYNC /**< don't sync meta for this txn on commit */
1235 #define MDB_TXN_NOSYNC MDB_NOSYNC /**< don't sync this txn on commit */
1236 #define MDB_TXN_RDONLY MDB_RDONLY /**< read-only transaction */
1237 /* internal txn flags */
1238 #define MDB_TXN_WRITEMAP MDB_WRITEMAP /**< copy of #MDB_env flag in writers */
1239 #define MDB_TXN_FINISHED 0x01 /**< txn is finished or never began */
1240 #define MDB_TXN_ERROR 0x02 /**< txn is unusable after an error */
1241 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
1242 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
1243 #define MDB_TXN_HAS_CHILD 0x10 /**< txn has an #MDB_txn.%mt_child */
1244 /** most operations on the txn are currently illegal */
1245 #define MDB_TXN_BLOCKED (MDB_TXN_FINISHED|MDB_TXN_ERROR|MDB_TXN_HAS_CHILD)
1247 unsigned int mt_flags; /**< @ref mdb_txn */
1248 /** #dirty_list room: Array size - \#dirty pages visible to this txn.
1249 * Includes ancestor txns' dirty pages not hidden by other txns'
1250 * dirty/spilled pages. Thus commit(nested txn) has room to merge
1251 * dirty_list into mt_parent after freeing hidden mt_parent pages.
1253 unsigned int mt_dirty_room;
1256 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
1257 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
1258 * raise this on a 64 bit machine.
1260 #define CURSOR_STACK 32
1264 /** Cursors are used for all DB operations.
1265 * A cursor holds a path of (page pointer, key index) from the DB
1266 * root to a position in the DB, plus other state. #MDB_DUPSORT
1267 * cursors include an xcursor to the current data item. Write txns
1268 * track their cursors and keep them up to date when data moves.
1269 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
1270 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
1273 /** Next cursor on this DB in this txn */
1274 MDB_cursor *mc_next;
1275 /** Backup of the original cursor if this cursor is a shadow */
1276 MDB_cursor *mc_backup;
1277 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
1278 struct MDB_xcursor *mc_xcursor;
1279 /** The transaction that owns this cursor */
1281 /** The database handle this cursor operates on */
1283 /** The database record for this cursor */
1285 /** The database auxiliary record for this cursor */
1287 /** The @ref mt_dbflag for this database */
1288 unsigned char *mc_dbflag;
1289 unsigned short mc_snum; /**< number of pushed pages */
1290 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
1291 /** @defgroup mdb_cursor Cursor Flags
1293 * Cursor state flags.
1296 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
1297 #define C_EOF 0x02 /**< No more data */
1298 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
1299 #define C_DEL 0x08 /**< last op was a cursor_del */
1300 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
1301 #define C_WRITEMAP MDB_TXN_WRITEMAP /**< Copy of txn flag */
1302 /** Read-only cursor into the txn's original snapshot in the map.
1303 * Set for read-only txns, and in #mdb_page_alloc() for #FREE_DBI when
1304 * #MDB_DEVEL & 2. Only implements code which is necessary for this.
1306 #define C_ORIG_RDONLY MDB_TXN_RDONLY
1308 unsigned int mc_flags; /**< @ref mdb_cursor */
1309 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
1310 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
1312 MDB_page *mc_ovpg; /**< a referenced overflow page */
1316 /** Context for sorted-dup records.
1317 * We could have gone to a fully recursive design, with arbitrarily
1318 * deep nesting of sub-databases. But for now we only handle these
1319 * levels - main DB, optional sub-DB, sorted-duplicate DB.
1321 typedef struct MDB_xcursor {
1322 /** A sub-cursor for traversing the Dup DB */
1323 MDB_cursor mx_cursor;
1324 /** The database record for this Dup DB */
1326 /** The auxiliary DB record for this Dup DB */
1328 /** The @ref mt_dbflag for this Dup DB */
1329 unsigned char mx_dbflag;
1332 /** State of FreeDB old pages, stored in the MDB_env */
1333 typedef struct MDB_pgstate {
1334 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1335 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1338 /** The database environment. */
1340 HANDLE me_fd; /**< The main data file */
1341 HANDLE me_lfd; /**< The lock file */
1342 HANDLE me_mfd; /**< just for writing the meta pages */
1343 #if defined(MDB_VL32) && defined(_WIN32)
1344 HANDLE me_fmh; /**< File Mapping handle */
1346 /** Failed to update the meta page. Probably an I/O error. */
1347 #define MDB_FATAL_ERROR 0x80000000U
1348 /** Some fields are initialized. */
1349 #define MDB_ENV_ACTIVE 0x20000000U
1350 /** me_txkey is set */
1351 #define MDB_ENV_TXKEY 0x10000000U
1352 /** fdatasync is unreliable */
1353 #define MDB_FSYNCONLY 0x08000000U
1354 uint32_t me_flags; /**< @ref mdb_env */
1355 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1356 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1357 unsigned int me_maxreaders; /**< size of the reader table */
1358 /** Max #MDB_txninfo.%mti_numreaders of interest to #mdb_env_close() */
1359 volatile int me_close_readers;
1360 MDB_dbi me_numdbs; /**< number of DBs opened */
1361 MDB_dbi me_maxdbs; /**< size of the DB table */
1362 MDB_PID_T me_pid; /**< process ID of this env */
1363 char *me_path; /**< path to the DB files */
1364 char *me_map; /**< the memory map of the data file */
1365 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1366 MDB_meta *me_metas[NUM_METAS]; /**< pointers to the two meta pages */
1367 void *me_pbuf; /**< scratch area for DUPSORT put() */
1368 MDB_txn *me_txn; /**< current write transaction */
1369 MDB_txn *me_txn0; /**< prealloc'd write transaction */
1370 mdb_size_t me_mapsize; /**< size of the data memory map */
1371 off_t me_size; /**< current file size */
1372 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1373 MDB_dbx *me_dbxs; /**< array of static DB info */
1374 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1375 unsigned int *me_dbiseqs; /**< array of dbi sequence numbers */
1376 pthread_key_t me_txkey; /**< thread-key for readers */
1377 txnid_t me_pgoldest; /**< ID of oldest reader last time we looked */
1378 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1379 # define me_pglast me_pgstate.mf_pglast
1380 # define me_pghead me_pgstate.mf_pghead
1381 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1382 /** IDL of pages that became unused in a write txn */
1383 MDB_IDL me_free_pgs;
1384 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1385 MDB_ID2L me_dirty_list;
1386 /** Max number of freelist items that can fit in a single overflow page */
1388 /** Max size of a node on a page */
1389 unsigned int me_nodemax;
1390 #if !(MDB_MAXKEYSIZE)
1391 unsigned int me_maxkey; /**< max size of a key */
1393 int me_live_reader; /**< have liveness lock in reader table */
1395 int me_pidquery; /**< Used in OpenProcess */
1397 #ifdef MDB_USE_POSIX_MUTEX /* Posix mutexes reside in shared mem */
1398 # define me_rmutex me_txns->mti_rmutex /**< Shared reader lock */
1399 # define me_wmutex me_txns->mti_wmutex /**< Shared writer lock */
1401 mdb_mutex_t me_rmutex;
1402 mdb_mutex_t me_wmutex;
1405 MDB_ID3L me_rpages; /**< like #mt_rpages, but global to env */
1406 pthread_mutex_t me_rpmutex; /**< control access to #me_rpages */
1407 #define MDB_ERPAGE_SIZE 16384
1408 #define MDB_ERPAGE_MAX (MDB_ERPAGE_SIZE-1)
1409 unsigned int me_rpcheck;
1411 void *me_userctx; /**< User-settable context */
1412 MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
1415 /** Nested transaction */
1416 typedef struct MDB_ntxn {
1417 MDB_txn mnt_txn; /**< the transaction */
1418 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1421 /** max number of pages to commit in one writev() call */
1422 #define MDB_COMMIT_PAGES 64
1423 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1424 #undef MDB_COMMIT_PAGES
1425 #define MDB_COMMIT_PAGES IOV_MAX
1428 /** max bytes to write in one call */
1429 #define MAX_WRITE (0x40000000U >> (sizeof(ssize_t) == 4))
1431 /** Check \b txn and \b dbi arguments to a function */
1432 #define TXN_DBI_EXIST(txn, dbi, validity) \
1433 ((txn) && (dbi)<(txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & (validity)))
1435 /** Check for misused \b dbi handles */
1436 #define TXN_DBI_CHANGED(txn, dbi) \
1437 ((txn)->mt_dbiseqs[dbi] != (txn)->mt_env->me_dbiseqs[dbi])
1439 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1440 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1441 static int mdb_page_touch(MDB_cursor *mc);
1443 #define MDB_END_NAMES {"committed", "empty-commit", "abort", "reset", \
1444 "reset-tmp", "fail-begin", "fail-beginchild"}
1446 /* mdb_txn_end operation number, for logging */
1447 MDB_END_COMMITTED, MDB_END_EMPTY_COMMIT, MDB_END_ABORT, MDB_END_RESET,
1448 MDB_END_RESET_TMP, MDB_END_FAIL_BEGIN, MDB_END_FAIL_BEGINCHILD
1450 #define MDB_END_OPMASK 0x0F /**< mask for #mdb_txn_end() operation number */
1451 #define MDB_END_UPDATE 0x10 /**< update env state (DBIs) */
1452 #define MDB_END_FREE 0x20 /**< free txn unless it is #MDB_env.%me_txn0 */
1453 #define MDB_END_SLOT MDB_NOTLS /**< release any reader slot if #MDB_NOTLS */
1454 static void mdb_txn_end(MDB_txn *txn, unsigned mode);
1456 static int mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **mp, int *lvl);
1457 static int mdb_page_search_root(MDB_cursor *mc,
1458 MDB_val *key, int modify);
1459 #define MDB_PS_MODIFY 1
1460 #define MDB_PS_ROOTONLY 2
1461 #define MDB_PS_FIRST 4
1462 #define MDB_PS_LAST 8
1463 static int mdb_page_search(MDB_cursor *mc,
1464 MDB_val *key, int flags);
1465 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1467 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1468 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1469 pgno_t newpgno, unsigned int nflags);
1471 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1472 static MDB_meta *mdb_env_pick_meta(const MDB_env *env);
1473 static int mdb_env_write_meta(MDB_txn *txn);
1474 #ifdef MDB_USE_POSIX_MUTEX /* Drop unused excl arg */
1475 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1477 static void mdb_env_close0(MDB_env *env, int excl);
1479 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1480 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1481 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1482 static void mdb_node_del(MDB_cursor *mc, int ksize);
1483 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1484 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft);
1485 static int mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data);
1486 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1487 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1489 static int mdb_rebalance(MDB_cursor *mc);
1490 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1492 static void mdb_cursor_pop(MDB_cursor *mc);
1493 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1495 static int mdb_cursor_del0(MDB_cursor *mc);
1496 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
1497 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1498 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1499 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1500 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1502 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1503 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1505 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1506 static void mdb_xcursor_init0(MDB_cursor *mc);
1507 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1508 static void mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int force);
1510 static int mdb_drop0(MDB_cursor *mc, int subs);
1511 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1512 static int mdb_reader_check0(MDB_env *env, int rlocked, int *dead);
1515 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1518 /** Compare two items pointing at size_t's of unknown alignment. */
1519 #ifdef MISALIGNED_OK
1520 # define mdb_cmp_clong mdb_cmp_long
1522 # define mdb_cmp_clong mdb_cmp_cint
1526 static SECURITY_DESCRIPTOR mdb_null_sd;
1527 static SECURITY_ATTRIBUTES mdb_all_sa;
1528 static int mdb_sec_inited;
1530 static int utf8_to_utf16(const char *src, int srcsize, wchar_t **dst, int *dstsize);
1533 /** Return the library version info. */
1535 mdb_version(int *major, int *minor, int *patch)
1537 if (major) *major = MDB_VERSION_MAJOR;
1538 if (minor) *minor = MDB_VERSION_MINOR;
1539 if (patch) *patch = MDB_VERSION_PATCH;
1540 return MDB_VERSION_STRING;
1543 /** Table of descriptions for LMDB @ref errors */
1544 static char *const mdb_errstr[] = {
1545 "MDB_KEYEXIST: Key/data pair already exists",
1546 "MDB_NOTFOUND: No matching key/data pair found",
1547 "MDB_PAGE_NOTFOUND: Requested page not found",
1548 "MDB_CORRUPTED: Located page was wrong type",
1549 "MDB_PANIC: Update of meta page failed or environment had fatal error",
1550 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1551 "MDB_INVALID: File is not an LMDB file",
1552 "MDB_MAP_FULL: Environment mapsize limit reached",
1553 "MDB_DBS_FULL: Environment maxdbs limit reached",
1554 "MDB_READERS_FULL: Environment maxreaders limit reached",
1555 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1556 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1557 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1558 "MDB_PAGE_FULL: Internal error - page has no more space",
1559 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1560 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1561 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1562 "MDB_BAD_TXN: Transaction must abort, has a child, or is invalid",
1563 "MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
1564 "MDB_BAD_DBI: The specified DBI handle was closed/changed unexpectedly",
1568 mdb_strerror(int err)
1571 /** HACK: pad 4KB on stack over the buf. Return system msgs in buf.
1572 * This works as long as no function between the call to mdb_strerror
1573 * and the actual use of the message uses more than 4K of stack.
1576 char buf[1024], *ptr = buf;
1580 return ("Successful return: 0");
1582 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1583 i = err - MDB_KEYEXIST;
1584 return mdb_errstr[i];
1588 /* These are the C-runtime error codes we use. The comment indicates
1589 * their numeric value, and the Win32 error they would correspond to
1590 * if the error actually came from a Win32 API. A major mess, we should
1591 * have used LMDB-specific error codes for everything.
1594 case ENOENT: /* 2, FILE_NOT_FOUND */
1595 case EIO: /* 5, ACCESS_DENIED */
1596 case ENOMEM: /* 12, INVALID_ACCESS */
1597 case EACCES: /* 13, INVALID_DATA */
1598 case EBUSY: /* 16, CURRENT_DIRECTORY */
1599 case EINVAL: /* 22, BAD_COMMAND */
1600 case ENOSPC: /* 28, OUT_OF_PAPER */
1601 return strerror(err);
1606 FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
1607 FORMAT_MESSAGE_IGNORE_INSERTS,
1608 NULL, err, 0, ptr, sizeof(buf), (va_list *)pad);
1611 return strerror(err);
1615 /** assert(3) variant in cursor context */
1616 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1617 /** assert(3) variant in transaction context */
1618 #define mdb_tassert(txn, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1619 /** assert(3) variant in environment context */
1620 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1623 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1624 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1627 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1628 const char *func, const char *file, int line)
1631 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1632 file, line, expr_txt, func);
1633 if (env->me_assert_func)
1634 env->me_assert_func(env, buf);
1635 fprintf(stderr, "%s\n", buf);
1639 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1643 /** Return the page number of \b mp which may be sub-page, for debug output */
1645 mdb_dbg_pgno(MDB_page *mp)
1648 COPY_PGNO(ret, mp->mp_pgno);
1652 /** Display a key in hexadecimal and return the address of the result.
1653 * @param[in] key the key to display
1654 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1655 * @return The key in hexadecimal form.
1658 mdb_dkey(MDB_val *key, char *buf)
1661 unsigned char *c = key->mv_data;
1667 if (key->mv_size > DKBUF_MAXKEYSIZE)
1668 return "MDB_MAXKEYSIZE";
1669 /* may want to make this a dynamic check: if the key is mostly
1670 * printable characters, print it as-is instead of converting to hex.
1674 for (i=0; i<key->mv_size; i++)
1675 ptr += sprintf(ptr, "%02x", *c++);
1677 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1683 mdb_leafnode_type(MDB_node *n)
1685 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1686 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1687 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1690 /** Display all the keys in the page. */
1692 mdb_page_list(MDB_page *mp)
1694 pgno_t pgno = mdb_dbg_pgno(mp);
1695 const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
1697 unsigned int i, nkeys, nsize, total = 0;
1701 switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1702 case P_BRANCH: type = "Branch page"; break;
1703 case P_LEAF: type = "Leaf page"; break;
1704 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1705 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1706 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1708 fprintf(stderr, "Overflow page %"Y"u pages %u%s\n",
1709 pgno, mp->mp_pages, state);
1712 fprintf(stderr, "Meta-page %"Y"u txnid %"Y"u\n",
1713 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1716 fprintf(stderr, "Bad page %"Y"u flags 0x%u\n", pgno, mp->mp_flags);
1720 nkeys = NUMKEYS(mp);
1721 fprintf(stderr, "%s %"Y"u numkeys %d%s\n", type, pgno, nkeys, state);
1723 for (i=0; i<nkeys; i++) {
1724 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1725 key.mv_size = nsize = mp->mp_pad;
1726 key.mv_data = LEAF2KEY(mp, i, nsize);
1728 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1731 node = NODEPTR(mp, i);
1732 key.mv_size = node->mn_ksize;
1733 key.mv_data = node->mn_data;
1734 nsize = NODESIZE + key.mv_size;
1735 if (IS_BRANCH(mp)) {
1736 fprintf(stderr, "key %d: page %"Y"u, %s\n", i, NODEPGNO(node),
1740 if (F_ISSET(node->mn_flags, F_BIGDATA))
1741 nsize += sizeof(pgno_t);
1743 nsize += NODEDSZ(node);
1745 nsize += sizeof(indx_t);
1746 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1747 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1749 total = EVEN(total);
1751 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1752 IS_LEAF2(mp) ? PAGEHDRSZ : PAGEBASE + mp->mp_lower, total, SIZELEFT(mp));
1756 mdb_cursor_chk(MDB_cursor *mc)
1762 if (!mc->mc_snum || !(mc->mc_flags & C_INITIALIZED)) return;
1763 for (i=0; i<mc->mc_top; i++) {
1765 node = NODEPTR(mp, mc->mc_ki[i]);
1766 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1769 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1771 if (mc->mc_xcursor && (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
1772 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
1773 if (((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA) &&
1774 mc->mc_xcursor->mx_cursor.mc_pg[0] != NODEDATA(node)) {
1782 /** Count all the pages in each DB and in the freelist
1783 * and make sure it matches the actual number of pages
1785 * All named DBs must be open for a correct count.
1787 static void mdb_audit(MDB_txn *txn)
1791 MDB_ID freecount, count;
1796 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1797 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1798 freecount += *(MDB_ID *)data.mv_data;
1799 mdb_tassert(txn, rc == MDB_NOTFOUND);
1802 for (i = 0; i<txn->mt_numdbs; i++) {
1804 if (!(txn->mt_dbflags[i] & DB_VALID))
1806 mdb_cursor_init(&mc, txn, i, &mx);
1807 if (txn->mt_dbs[i].md_root == P_INVALID)
1809 count += txn->mt_dbs[i].md_branch_pages +
1810 txn->mt_dbs[i].md_leaf_pages +
1811 txn->mt_dbs[i].md_overflow_pages;
1812 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1813 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1814 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
1817 mp = mc.mc_pg[mc.mc_top];
1818 for (j=0; j<NUMKEYS(mp); j++) {
1819 MDB_node *leaf = NODEPTR(mp, j);
1820 if (leaf->mn_flags & F_SUBDATA) {
1822 memcpy(&db, NODEDATA(leaf), sizeof(db));
1823 count += db.md_branch_pages + db.md_leaf_pages +
1824 db.md_overflow_pages;
1828 mdb_tassert(txn, rc == MDB_NOTFOUND);
1831 if (freecount + count + NUM_METAS != txn->mt_next_pgno) {
1832 fprintf(stderr, "audit: %"Y"u freecount: %"Y"u count: %"Y"u total: %"Y"u next_pgno: %"Y"u\n",
1833 txn->mt_txnid, freecount, count+NUM_METAS,
1834 freecount+count+NUM_METAS, txn->mt_next_pgno);
1840 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1842 return txn->mt_dbxs[dbi].md_cmp(a, b);
1846 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1848 MDB_cmp_func *dcmp = txn->mt_dbxs[dbi].md_dcmp;
1849 #if UINT_MAX < SIZE_MAX || defined(MDB_VL32)
1850 if (dcmp == mdb_cmp_int && a->mv_size == sizeof(mdb_size_t))
1851 dcmp = mdb_cmp_clong;
1856 /** Allocate memory for a page.
1857 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1860 mdb_page_malloc(MDB_txn *txn, unsigned num)
1862 MDB_env *env = txn->mt_env;
1863 MDB_page *ret = env->me_dpages;
1864 size_t psize = env->me_psize, sz = psize, off;
1865 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1866 * For a single page alloc, we init everything after the page header.
1867 * For multi-page, we init the final page; if the caller needed that
1868 * many pages they will be filling in at least up to the last page.
1872 VGMEMP_ALLOC(env, ret, sz);
1873 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1874 env->me_dpages = ret->mp_next;
1877 psize -= off = PAGEHDRSZ;
1882 if ((ret = malloc(sz)) != NULL) {
1883 VGMEMP_ALLOC(env, ret, sz);
1884 if (!(env->me_flags & MDB_NOMEMINIT)) {
1885 memset((char *)ret + off, 0, psize);
1889 txn->mt_flags |= MDB_TXN_ERROR;
1893 /** Free a single page.
1894 * Saves single pages to a list, for future reuse.
1895 * (This is not used for multi-page overflow pages.)
1898 mdb_page_free(MDB_env *env, MDB_page *mp)
1900 mp->mp_next = env->me_dpages;
1901 VGMEMP_FREE(env, mp);
1902 env->me_dpages = mp;
1905 /** Free a dirty page */
1907 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1909 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1910 mdb_page_free(env, dp);
1912 /* large pages just get freed directly */
1913 VGMEMP_FREE(env, dp);
1918 /** Return all dirty pages to dpage list */
1920 mdb_dlist_free(MDB_txn *txn)
1922 MDB_env *env = txn->mt_env;
1923 MDB_ID2L dl = txn->mt_u.dirty_list;
1924 unsigned i, n = dl[0].mid;
1926 for (i = 1; i <= n; i++) {
1927 mdb_dpage_free(env, dl[i].mptr);
1934 mdb_page_unref(MDB_txn *txn, MDB_page *mp)
1937 MDB_ID3L tl = txn->mt_rpages;
1939 if (mp->mp_flags & (P_SUBP|P_DIRTY))
1941 rem = mp->mp_pgno & (MDB_RPAGE_CHUNK-1);
1942 pgno = mp->mp_pgno ^ rem;
1943 x = mdb_mid3l_search(tl, pgno);
1944 if (x != tl[0].mid && tl[x+1].mid == mp->mp_pgno)
1949 #define MDB_PAGE_UNREF(txn, mp) mdb_page_unref(txn, mp)
1952 mdb_cursor_unref(MDB_cursor *mc)
1955 if (!mc->mc_snum || !mc->mc_pg[0] || IS_SUBP(mc->mc_pg[0]))
1957 for (i=0; i<mc->mc_snum; i++)
1958 mdb_page_unref(mc->mc_txn, mc->mc_pg[i]);
1960 mdb_page_unref(mc->mc_txn, mc->mc_ovpg);
1963 mc->mc_snum = mc->mc_top = 0;
1964 mc->mc_pg[0] = NULL;
1965 mc->mc_flags &= ~C_INITIALIZED;
1968 #define MDB_PAGE_UNREF(txn, mp)
1969 #endif /* MDB_VL32 */
1971 /** Loosen or free a single page.
1972 * Saves single pages to a list for future reuse
1973 * in this same txn. It has been pulled from the freeDB
1974 * and already resides on the dirty list, but has been
1975 * deleted. Use these pages first before pulling again
1978 * If the page wasn't dirtied in this txn, just add it
1979 * to this txn's free list.
1982 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
1985 pgno_t pgno = mp->mp_pgno;
1986 MDB_txn *txn = mc->mc_txn;
1988 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
1989 if (txn->mt_parent) {
1990 MDB_ID2 *dl = txn->mt_u.dirty_list;
1991 /* If txn has a parent, make sure the page is in our
1995 unsigned x = mdb_mid2l_search(dl, pgno);
1996 if (x <= dl[0].mid && dl[x].mid == pgno) {
1997 if (mp != dl[x].mptr) { /* bad cursor? */
1998 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1999 txn->mt_flags |= MDB_TXN_ERROR;
2000 return MDB_CORRUPTED;
2007 /* no parent txn, so it's just ours */
2012 DPRINTF(("loosen db %d page %"Y"u", DDBI(mc),
2014 NEXT_LOOSE_PAGE(mp) = txn->mt_loose_pgs;
2015 txn->mt_loose_pgs = mp;
2016 txn->mt_loose_count++;
2017 mp->mp_flags |= P_LOOSE;
2019 int rc = mdb_midl_append(&txn->mt_free_pgs, pgno);
2027 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
2028 * @param[in] mc A cursor handle for the current operation.
2029 * @param[in] pflags Flags of the pages to update:
2030 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
2031 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
2032 * @return 0 on success, non-zero on failure.
2035 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
2037 enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
2038 MDB_txn *txn = mc->mc_txn;
2039 MDB_cursor *m3, *m0 = mc;
2044 int rc = MDB_SUCCESS, level;
2046 /* Mark pages seen by cursors */
2047 if (mc->mc_flags & C_UNTRACK)
2048 mc = NULL; /* will find mc in mt_cursors */
2049 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
2050 for (; mc; mc=mc->mc_next) {
2051 if (!(mc->mc_flags & C_INITIALIZED))
2053 for (m3 = mc;; m3 = &mx->mx_cursor) {
2055 for (j=0; j<m3->mc_snum; j++) {
2057 if ((mp->mp_flags & Mask) == pflags)
2058 mp->mp_flags ^= P_KEEP;
2060 mx = m3->mc_xcursor;
2061 /* Proceed to mx if it is at a sub-database */
2062 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
2064 if (! (mp && (mp->mp_flags & P_LEAF)))
2066 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
2067 if (!(leaf->mn_flags & F_SUBDATA))
2076 /* Mark dirty root pages */
2077 for (i=0; i<txn->mt_numdbs; i++) {
2078 if (txn->mt_dbflags[i] & DB_DIRTY) {
2079 pgno_t pgno = txn->mt_dbs[i].md_root;
2080 if (pgno == P_INVALID)
2082 if ((rc = mdb_page_get(m0, pgno, &dp, &level)) != MDB_SUCCESS)
2084 if ((dp->mp_flags & Mask) == pflags && level <= 1)
2085 dp->mp_flags ^= P_KEEP;
2093 static int mdb_page_flush(MDB_txn *txn, int keep);
2095 /** Spill pages from the dirty list back to disk.
2096 * This is intended to prevent running into #MDB_TXN_FULL situations,
2097 * but note that they may still occur in a few cases:
2098 * 1) our estimate of the txn size could be too small. Currently this
2099 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
2100 * 2) child txns may run out of space if their parents dirtied a
2101 * lot of pages and never spilled them. TODO: we probably should do
2102 * a preemptive spill during #mdb_txn_begin() of a child txn, if
2103 * the parent's dirty_room is below a given threshold.
2105 * Otherwise, if not using nested txns, it is expected that apps will
2106 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
2107 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
2108 * If the txn never references them again, they can be left alone.
2109 * If the txn only reads them, they can be used without any fuss.
2110 * If the txn writes them again, they can be dirtied immediately without
2111 * going thru all of the work of #mdb_page_touch(). Such references are
2112 * handled by #mdb_page_unspill().
2114 * Also note, we never spill DB root pages, nor pages of active cursors,
2115 * because we'll need these back again soon anyway. And in nested txns,
2116 * we can't spill a page in a child txn if it was already spilled in a
2117 * parent txn. That would alter the parent txns' data even though
2118 * the child hasn't committed yet, and we'd have no way to undo it if
2119 * the child aborted.
2121 * @param[in] m0 cursor A cursor handle identifying the transaction and
2122 * database for which we are checking space.
2123 * @param[in] key For a put operation, the key being stored.
2124 * @param[in] data For a put operation, the data being stored.
2125 * @return 0 on success, non-zero on failure.
2128 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
2130 MDB_txn *txn = m0->mc_txn;
2132 MDB_ID2L dl = txn->mt_u.dirty_list;
2133 unsigned int i, j, need;
2136 if (m0->mc_flags & C_SUB)
2139 /* Estimate how much space this op will take */
2140 i = m0->mc_db->md_depth;
2141 /* Named DBs also dirty the main DB */
2142 if (m0->mc_dbi >= CORE_DBS)
2143 i += txn->mt_dbs[MAIN_DBI].md_depth;
2144 /* For puts, roughly factor in the key+data size */
2146 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
2147 i += i; /* double it for good measure */
2150 if (txn->mt_dirty_room > i)
2153 if (!txn->mt_spill_pgs) {
2154 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
2155 if (!txn->mt_spill_pgs)
2158 /* purge deleted slots */
2159 MDB_IDL sl = txn->mt_spill_pgs;
2160 unsigned int num = sl[0];
2162 for (i=1; i<=num; i++) {
2169 /* Preserve pages which may soon be dirtied again */
2170 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
2173 /* Less aggressive spill - we originally spilled the entire dirty list,
2174 * with a few exceptions for cursor pages and DB root pages. But this
2175 * turns out to be a lot of wasted effort because in a large txn many
2176 * of those pages will need to be used again. So now we spill only 1/8th
2177 * of the dirty pages. Testing revealed this to be a good tradeoff,
2178 * better than 1/2, 1/4, or 1/10.
2180 if (need < MDB_IDL_UM_MAX / 8)
2181 need = MDB_IDL_UM_MAX / 8;
2183 /* Save the page IDs of all the pages we're flushing */
2184 /* flush from the tail forward, this saves a lot of shifting later on. */
2185 for (i=dl[0].mid; i && need; i--) {
2186 MDB_ID pn = dl[i].mid << 1;
2188 if (dp->mp_flags & (P_LOOSE|P_KEEP))
2190 /* Can't spill twice, make sure it's not already in a parent's
2193 if (txn->mt_parent) {
2195 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
2196 if (tx2->mt_spill_pgs) {
2197 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
2198 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
2199 dp->mp_flags |= P_KEEP;
2207 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
2211 mdb_midl_sort(txn->mt_spill_pgs);
2213 /* Flush the spilled part of dirty list */
2214 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
2217 /* Reset any dirty pages we kept that page_flush didn't see */
2218 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
2221 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
2225 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
2227 mdb_find_oldest(MDB_txn *txn)
2230 txnid_t mr, oldest = txn->mt_txnid - 1;
2231 if (txn->mt_env->me_txns) {
2232 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
2233 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
2244 /** Add a page to the txn's dirty list */
2246 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
2249 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
2251 if (txn->mt_flags & MDB_TXN_WRITEMAP) {
2252 insert = mdb_mid2l_append;
2254 insert = mdb_mid2l_insert;
2256 mid.mid = mp->mp_pgno;
2258 rc = insert(txn->mt_u.dirty_list, &mid);
2259 mdb_tassert(txn, rc == 0);
2260 txn->mt_dirty_room--;
2263 /** Allocate page numbers and memory for writing. Maintain me_pglast,
2264 * me_pghead and mt_next_pgno.
2266 * If there are free pages available from older transactions, they
2267 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
2268 * Do not modify the freedB, just merge freeDB records into me_pghead[]
2269 * and move me_pglast to say which records were consumed. Only this
2270 * function can create me_pghead and move me_pglast/mt_next_pgno.
2271 * When #MDB_DEVEL & 2, it is not affected by #mdb_freelist_save(): it
2272 * then uses the transaction's original snapshot of the freeDB.
2273 * @param[in] mc cursor A cursor handle identifying the transaction and
2274 * database for which we are allocating.
2275 * @param[in] num the number of pages to allocate.
2276 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
2277 * will always be satisfied by a single contiguous chunk of memory.
2278 * @return 0 on success, non-zero on failure.
2281 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
2283 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
2284 /* Get at most <Max_retries> more freeDB records once me_pghead
2285 * has enough pages. If not enough, use new pages from the map.
2286 * If <Paranoid> and mc is updating the freeDB, only get new
2287 * records if me_pghead is empty. Then the freelist cannot play
2288 * catch-up with itself by growing while trying to save it.
2290 enum { Paranoid = 1, Max_retries = 500 };
2292 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
2294 int rc, retry = num * 60;
2295 MDB_txn *txn = mc->mc_txn;
2296 MDB_env *env = txn->mt_env;
2297 pgno_t pgno, *mop = env->me_pghead;
2298 unsigned i, j, mop_len = mop ? mop[0] : 0, n2 = num-1;
2300 txnid_t oldest = 0, last;
2305 /* If there are any loose pages, just use them */
2306 if (num == 1 && txn->mt_loose_pgs) {
2307 np = txn->mt_loose_pgs;
2308 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
2309 txn->mt_loose_count--;
2310 DPRINTF(("db %d use loose page %"Y"u", DDBI(mc),
2318 /* If our dirty list is already full, we can't do anything */
2319 if (txn->mt_dirty_room == 0) {
2324 for (op = MDB_FIRST;; op = MDB_NEXT) {
2329 /* Seek a big enough contiguous page range. Prefer
2330 * pages at the tail, just truncating the list.
2336 if (mop[i-n2] == pgno+n2)
2343 if (op == MDB_FIRST) { /* 1st iteration */
2344 /* Prepare to fetch more and coalesce */
2345 last = env->me_pglast;
2346 oldest = env->me_pgoldest;
2347 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
2348 #if (MDB_DEVEL) & 2 /* "& 2" so MDB_DEVEL=1 won't hide bugs breaking freeDB */
2349 /* Use original snapshot. TODO: Should need less care in code
2350 * which modifies the database. Maybe we can delete some code?
2352 m2.mc_flags |= C_ORIG_RDONLY;
2353 m2.mc_db = &env->me_metas[(txn->mt_txnid-1) & 1]->mm_dbs[FREE_DBI];
2354 m2.mc_dbflag = (unsigned char *)""; /* probably unnecessary */
2358 key.mv_data = &last; /* will look up last+1 */
2359 key.mv_size = sizeof(last);
2361 if (Paranoid && mc->mc_dbi == FREE_DBI)
2364 if (Paranoid && retry < 0 && mop_len)
2368 /* Do not fetch more if the record will be too recent */
2369 if (oldest <= last) {
2371 oldest = mdb_find_oldest(txn);
2372 env->me_pgoldest = oldest;
2378 rc = mdb_cursor_get(&m2, &key, NULL, op);
2380 if (rc == MDB_NOTFOUND)
2384 last = *(txnid_t*)key.mv_data;
2385 if (oldest <= last) {
2387 oldest = mdb_find_oldest(txn);
2388 env->me_pgoldest = oldest;
2394 np = m2.mc_pg[m2.mc_top];
2395 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
2396 if ((rc = mdb_node_read(&m2, leaf, &data)) != MDB_SUCCESS)
2399 idl = (MDB_ID *) data.mv_data;
2402 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
2407 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
2409 mop = env->me_pghead;
2411 env->me_pglast = last;
2413 DPRINTF(("IDL read txn %"Y"u root %"Y"u num %u",
2414 last, txn->mt_dbs[FREE_DBI].md_root, i));
2416 DPRINTF(("IDL %"Y"u", idl[j]));
2418 /* Merge in descending sorted order */
2419 mdb_midl_xmerge(mop, idl);
2423 /* Use new pages from the map when nothing suitable in the freeDB */
2425 pgno = txn->mt_next_pgno;
2426 if (pgno + num >= env->me_maxpg) {
2427 DPUTS("DB size maxed out");
2431 #if defined(_WIN32) && !defined(MDB_VL32)
2432 if (!(env->me_flags & MDB_RDONLY)) {
2434 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
2435 p = VirtualAlloc(p, env->me_psize * num, MEM_COMMIT,
2436 (env->me_flags & MDB_WRITEMAP) ? PAGE_READWRITE:
2439 DPUTS("VirtualAlloc failed");
2447 if (env->me_flags & MDB_WRITEMAP) {
2448 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
2450 if (!(np = mdb_page_malloc(txn, num))) {
2456 mop[0] = mop_len -= num;
2457 /* Move any stragglers down */
2458 for (j = i-num; j < mop_len; )
2459 mop[++j] = mop[++i];
2461 txn->mt_next_pgno = pgno + num;
2464 mdb_page_dirty(txn, np);
2470 txn->mt_flags |= MDB_TXN_ERROR;
2474 /** Copy the used portions of a non-overflow page.
2475 * @param[in] dst page to copy into
2476 * @param[in] src page to copy from
2477 * @param[in] psize size of a page
2480 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2482 enum { Align = sizeof(pgno_t) };
2483 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2485 /* If page isn't full, just copy the used portion. Adjust
2486 * alignment so memcpy may copy words instead of bytes.
2488 if ((unused &= -Align) && !IS_LEAF2(src)) {
2489 upper = (upper + PAGEBASE) & -Align;
2490 memcpy(dst, src, (lower + PAGEBASE + (Align-1)) & -Align);
2491 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2494 memcpy(dst, src, psize - unused);
2498 /** Pull a page off the txn's spill list, if present.
2499 * If a page being referenced was spilled to disk in this txn, bring
2500 * it back and make it dirty/writable again.
2501 * @param[in] txn the transaction handle.
2502 * @param[in] mp the page being referenced. It must not be dirty.
2503 * @param[out] ret the writable page, if any. ret is unchanged if
2504 * mp wasn't spilled.
2507 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2509 MDB_env *env = txn->mt_env;
2512 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2514 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2515 if (!tx2->mt_spill_pgs)
2517 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2518 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2521 if (txn->mt_dirty_room == 0)
2522 return MDB_TXN_FULL;
2523 if (IS_OVERFLOW(mp))
2527 if (env->me_flags & MDB_WRITEMAP) {
2530 np = mdb_page_malloc(txn, num);
2534 memcpy(np, mp, num * env->me_psize);
2536 mdb_page_copy(np, mp, env->me_psize);
2539 /* If in current txn, this page is no longer spilled.
2540 * If it happens to be the last page, truncate the spill list.
2541 * Otherwise mark it as deleted by setting the LSB.
2543 if (x == txn->mt_spill_pgs[0])
2544 txn->mt_spill_pgs[0]--;
2546 txn->mt_spill_pgs[x] |= 1;
2547 } /* otherwise, if belonging to a parent txn, the
2548 * page remains spilled until child commits
2551 mdb_page_dirty(txn, np);
2552 np->mp_flags |= P_DIRTY;
2560 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2561 * @param[in] mc cursor pointing to the page to be touched
2562 * @return 0 on success, non-zero on failure.
2565 mdb_page_touch(MDB_cursor *mc)
2567 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2568 MDB_txn *txn = mc->mc_txn;
2569 MDB_cursor *m2, *m3;
2573 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2574 if (txn->mt_flags & MDB_TXN_SPILLS) {
2576 rc = mdb_page_unspill(txn, mp, &np);
2582 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2583 (rc = mdb_page_alloc(mc, 1, &np)))
2586 DPRINTF(("touched db %d page %"Y"u -> %"Y"u", DDBI(mc),
2587 mp->mp_pgno, pgno));
2588 mdb_cassert(mc, mp->mp_pgno != pgno);
2589 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2590 /* Update the parent page, if any, to point to the new page */
2592 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2593 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2594 SETPGNO(node, pgno);
2596 mc->mc_db->md_root = pgno;
2598 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2599 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2601 /* If txn has a parent, make sure the page is in our
2605 unsigned x = mdb_mid2l_search(dl, pgno);
2606 if (x <= dl[0].mid && dl[x].mid == pgno) {
2607 if (mp != dl[x].mptr) { /* bad cursor? */
2608 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2609 txn->mt_flags |= MDB_TXN_ERROR;
2610 return MDB_CORRUPTED;
2615 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2617 np = mdb_page_malloc(txn, 1);
2622 rc = mdb_mid2l_insert(dl, &mid);
2623 mdb_cassert(mc, rc == 0);
2628 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2630 np->mp_flags |= P_DIRTY;
2633 /* Adjust cursors pointing to mp */
2634 mc->mc_pg[mc->mc_top] = np;
2635 m2 = txn->mt_cursors[mc->mc_dbi];
2636 if (mc->mc_flags & C_SUB) {
2637 for (; m2; m2=m2->mc_next) {
2638 m3 = &m2->mc_xcursor->mx_cursor;
2639 if (m3->mc_snum < mc->mc_snum) continue;
2640 if (m3->mc_pg[mc->mc_top] == mp)
2641 m3->mc_pg[mc->mc_top] = np;
2644 for (; m2; m2=m2->mc_next) {
2645 if (m2->mc_snum < mc->mc_snum) continue;
2646 if (m2 == mc) continue;
2647 if (m2->mc_pg[mc->mc_top] == mp) {
2648 m2->mc_pg[mc->mc_top] = np;
2649 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
2651 (m2->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
2653 MDB_node *leaf = NODEPTR(np, m2->mc_ki[mc->mc_top]);
2654 if ((leaf->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
2655 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
2660 MDB_PAGE_UNREF(mc->mc_txn, mp);
2664 txn->mt_flags |= MDB_TXN_ERROR;
2669 mdb_env_sync0(MDB_env *env, int force, pgno_t numpgs)
2672 if (env->me_flags & MDB_RDONLY)
2674 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2675 if (env->me_flags & MDB_WRITEMAP) {
2676 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2677 ? MS_ASYNC : MS_SYNC;
2678 if (MDB_MSYNC(env->me_map, env->me_psize * numpgs, flags))
2681 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2685 #ifdef BROKEN_FDATASYNC
2686 if (env->me_flags & MDB_FSYNCONLY) {
2687 if (fsync(env->me_fd))
2691 if (MDB_FDATASYNC(env->me_fd))
2699 mdb_env_sync(MDB_env *env, int force)
2701 MDB_meta *m = mdb_env_pick_meta(env);
2702 return mdb_env_sync0(env, force, m->mm_last_pg+1);
2705 /** Back up parent txn's cursors, then grab the originals for tracking */
2707 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2709 MDB_cursor *mc, *bk;
2714 for (i = src->mt_numdbs; --i >= 0; ) {
2715 if ((mc = src->mt_cursors[i]) != NULL) {
2716 size = sizeof(MDB_cursor);
2718 size += sizeof(MDB_xcursor);
2719 for (; mc; mc = bk->mc_next) {
2725 mc->mc_db = &dst->mt_dbs[i];
2726 /* Kill pointers into src to reduce abuse: The
2727 * user may not use mc until dst ends. But we need a valid
2728 * txn pointer here for cursor fixups to keep working.
2731 mc->mc_dbflag = &dst->mt_dbflags[i];
2732 if ((mx = mc->mc_xcursor) != NULL) {
2733 *(MDB_xcursor *)(bk+1) = *mx;
2734 mx->mx_cursor.mc_txn = dst;
2736 mc->mc_next = dst->mt_cursors[i];
2737 dst->mt_cursors[i] = mc;
2744 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2745 * @param[in] txn the transaction handle.
2746 * @param[in] merge true to keep changes to parent cursors, false to revert.
2747 * @return 0 on success, non-zero on failure.
2750 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2752 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2756 for (i = txn->mt_numdbs; --i >= 0; ) {
2757 for (mc = cursors[i]; mc; mc = next) {
2759 if ((bk = mc->mc_backup) != NULL) {
2761 /* Commit changes to parent txn */
2762 mc->mc_next = bk->mc_next;
2763 mc->mc_backup = bk->mc_backup;
2764 mc->mc_txn = bk->mc_txn;
2765 mc->mc_db = bk->mc_db;
2766 mc->mc_dbflag = bk->mc_dbflag;
2767 if ((mx = mc->mc_xcursor) != NULL)
2768 mx->mx_cursor.mc_txn = bk->mc_txn;
2770 /* Abort nested txn */
2772 if ((mx = mc->mc_xcursor) != NULL)
2773 *mx = *(MDB_xcursor *)(bk+1);
2777 /* Only malloced cursors are permanently tracked. */
2784 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2790 Pidset = F_SETLK, Pidcheck = F_GETLK
2794 /** Set or check a pid lock. Set returns 0 on success.
2795 * Check returns 0 if the process is certainly dead, nonzero if it may
2796 * be alive (the lock exists or an error happened so we do not know).
2798 * On Windows Pidset is a no-op, we merely check for the existence
2799 * of the process with the given pid. On POSIX we use a single byte
2800 * lock on the lockfile, set at an offset equal to the pid.
2803 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2805 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2808 if (op == Pidcheck) {
2809 h = OpenProcess(env->me_pidquery, FALSE, pid);
2810 /* No documented "no such process" code, but other program use this: */
2812 return ErrCode() != ERROR_INVALID_PARAMETER;
2813 /* A process exists until all handles to it close. Has it exited? */
2814 ret = WaitForSingleObject(h, 0) != 0;
2821 struct flock lock_info;
2822 memset(&lock_info, 0, sizeof(lock_info));
2823 lock_info.l_type = F_WRLCK;
2824 lock_info.l_whence = SEEK_SET;
2825 lock_info.l_start = pid;
2826 lock_info.l_len = 1;
2827 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2828 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2830 } else if ((rc = ErrCode()) == EINTR) {
2838 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2839 * @param[in] txn the transaction handle to initialize
2840 * @return 0 on success, non-zero on failure.
2843 mdb_txn_renew0(MDB_txn *txn)
2845 MDB_env *env = txn->mt_env;
2846 MDB_txninfo *ti = env->me_txns;
2848 unsigned int i, nr, flags = txn->mt_flags;
2850 int rc, new_notls = 0;
2852 if ((flags &= MDB_TXN_RDONLY) != 0) {
2854 meta = mdb_env_pick_meta(env);
2855 txn->mt_txnid = meta->mm_txnid;
2856 txn->mt_u.reader = NULL;
2858 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2859 pthread_getspecific(env->me_txkey);
2861 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2862 return MDB_BAD_RSLOT;
2864 MDB_PID_T pid = env->me_pid;
2865 MDB_THR_T tid = pthread_self();
2866 mdb_mutexref_t rmutex = env->me_rmutex;
2868 if (!env->me_live_reader) {
2869 rc = mdb_reader_pid(env, Pidset, pid);
2872 env->me_live_reader = 1;
2875 if (LOCK_MUTEX(rc, env, rmutex))
2877 nr = ti->mti_numreaders;
2878 for (i=0; i<nr; i++)
2879 if (ti->mti_readers[i].mr_pid == 0)
2881 if (i == env->me_maxreaders) {
2882 UNLOCK_MUTEX(rmutex);
2883 return MDB_READERS_FULL;
2885 r = &ti->mti_readers[i];
2886 /* Claim the reader slot, carefully since other code
2887 * uses the reader table un-mutexed: First reset the
2888 * slot, next publish it in mti_numreaders. After
2889 * that, it is safe for mdb_env_close() to touch it.
2890 * When it will be closed, we can finally claim it.
2893 r->mr_txnid = (txnid_t)-1;
2896 ti->mti_numreaders = ++nr;
2897 env->me_close_readers = nr;
2899 UNLOCK_MUTEX(rmutex);
2901 new_notls = (env->me_flags & MDB_NOTLS);
2902 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2907 do /* LY: Retry on a race, ITS#7970. */
2908 r->mr_txnid = ti->mti_txnid;
2909 while(r->mr_txnid != ti->mti_txnid);
2910 txn->mt_txnid = r->mr_txnid;
2911 txn->mt_u.reader = r;
2912 meta = env->me_metas[txn->mt_txnid & 1];
2916 /* Not yet touching txn == env->me_txn0, it may be active */
2918 if (LOCK_MUTEX(rc, env, env->me_wmutex))
2920 txn->mt_txnid = ti->mti_txnid;
2921 meta = env->me_metas[txn->mt_txnid & 1];
2923 meta = mdb_env_pick_meta(env);
2924 txn->mt_txnid = meta->mm_txnid;
2928 if (txn->mt_txnid == mdb_debug_start)
2931 txn->mt_child = NULL;
2932 txn->mt_loose_pgs = NULL;
2933 txn->mt_loose_count = 0;
2934 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2935 txn->mt_u.dirty_list = env->me_dirty_list;
2936 txn->mt_u.dirty_list[0].mid = 0;
2937 txn->mt_free_pgs = env->me_free_pgs;
2938 txn->mt_free_pgs[0] = 0;
2939 txn->mt_spill_pgs = NULL;
2941 memcpy(txn->mt_dbiseqs, env->me_dbiseqs, env->me_maxdbs * sizeof(unsigned int));
2944 /* Copy the DB info and flags */
2945 memcpy(txn->mt_dbs, meta->mm_dbs, CORE_DBS * sizeof(MDB_db));
2947 /* Moved to here to avoid a data race in read TXNs */
2948 txn->mt_next_pgno = meta->mm_last_pg+1;
2950 txn->mt_last_pgno = txn->mt_next_pgno - 1;
2953 txn->mt_flags = flags;
2956 txn->mt_numdbs = env->me_numdbs;
2957 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
2958 x = env->me_dbflags[i];
2959 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2960 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_USRVALID|DB_STALE : 0;
2962 txn->mt_dbflags[MAIN_DBI] = DB_VALID|DB_USRVALID;
2963 txn->mt_dbflags[FREE_DBI] = DB_VALID;
2965 if (env->me_flags & MDB_FATAL_ERROR) {
2966 DPUTS("environment had fatal error, must shutdown!");
2968 } else if (env->me_maxpg < txn->mt_next_pgno) {
2969 rc = MDB_MAP_RESIZED;
2973 mdb_txn_end(txn, new_notls /*0 or MDB_END_SLOT*/ | MDB_END_FAIL_BEGIN);
2978 mdb_txn_renew(MDB_txn *txn)
2982 if (!txn || !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY|MDB_TXN_FINISHED))
2985 rc = mdb_txn_renew0(txn);
2986 if (rc == MDB_SUCCESS) {
2987 DPRINTF(("renew txn %"Y"u%c %p on mdbenv %p, root page %"Y"u",
2988 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2989 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2995 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2999 int rc, size, tsize;
3001 flags &= MDB_TXN_BEGIN_FLAGS;
3002 flags |= env->me_flags & MDB_WRITEMAP;
3004 if (env->me_flags & MDB_RDONLY & ~flags) /* write txn in RDONLY env */
3008 /* Nested transactions: Max 1 child, write txns only, no writemap */
3009 flags |= parent->mt_flags;
3010 if (flags & (MDB_RDONLY|MDB_WRITEMAP|MDB_TXN_BLOCKED)) {
3011 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
3013 /* Child txns save MDB_pgstate and use own copy of cursors */
3014 size = env->me_maxdbs * (sizeof(MDB_db)+sizeof(MDB_cursor *)+1);
3015 size += tsize = sizeof(MDB_ntxn);
3016 } else if (flags & MDB_RDONLY) {
3017 size = env->me_maxdbs * (sizeof(MDB_db)+1);
3018 size += tsize = sizeof(MDB_txn);
3020 /* Reuse preallocated write txn. However, do not touch it until
3021 * mdb_txn_renew0() succeeds, since it currently may be active.
3026 if ((txn = calloc(1, size)) == NULL) {
3027 DPRINTF(("calloc: %s", strerror(errno)));
3032 txn->mt_rpages = malloc(MDB_TRPAGE_SIZE * sizeof(MDB_ID3));
3033 if (!txn->mt_rpages) {
3037 txn->mt_rpages[0].mid = 0;
3038 txn->mt_rpcheck = MDB_TRPAGE_SIZE/2;
3041 txn->mt_dbxs = env->me_dbxs; /* static */
3042 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
3043 txn->mt_dbflags = (unsigned char *)txn + size - env->me_maxdbs;
3044 txn->mt_flags = flags;
3049 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
3050 txn->mt_dbiseqs = parent->mt_dbiseqs;
3051 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
3052 if (!txn->mt_u.dirty_list ||
3053 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
3055 free(txn->mt_u.dirty_list);
3059 txn->mt_txnid = parent->mt_txnid;
3060 txn->mt_dirty_room = parent->mt_dirty_room;
3061 txn->mt_u.dirty_list[0].mid = 0;
3062 txn->mt_spill_pgs = NULL;
3063 txn->mt_next_pgno = parent->mt_next_pgno;
3064 parent->mt_flags |= MDB_TXN_HAS_CHILD;
3065 parent->mt_child = txn;
3066 txn->mt_parent = parent;
3067 txn->mt_numdbs = parent->mt_numdbs;
3069 txn->mt_rpages = parent->mt_rpages;
3071 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3072 /* Copy parent's mt_dbflags, but clear DB_NEW */
3073 for (i=0; i<txn->mt_numdbs; i++)
3074 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
3076 ntxn = (MDB_ntxn *)txn;
3077 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
3078 if (env->me_pghead) {
3079 size = MDB_IDL_SIZEOF(env->me_pghead);
3080 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
3082 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
3087 rc = mdb_cursor_shadow(parent, txn);
3089 mdb_txn_end(txn, MDB_END_FAIL_BEGINCHILD);
3090 } else { /* MDB_RDONLY */
3091 txn->mt_dbiseqs = env->me_dbiseqs;
3093 rc = mdb_txn_renew0(txn);
3096 if (txn != env->me_txn0) {
3098 free(txn->mt_rpages);
3103 txn->mt_flags |= flags; /* could not change txn=me_txn0 earlier */
3105 DPRINTF(("begin txn %"Y"u%c %p on mdbenv %p, root page %"Y"u",
3106 txn->mt_txnid, (flags & MDB_RDONLY) ? 'r' : 'w',
3107 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
3114 mdb_txn_env(MDB_txn *txn)
3116 if(!txn) return NULL;
3121 mdb_txn_id(MDB_txn *txn)
3124 return txn->mt_txnid;
3127 /** Export or close DBI handles opened in this txn. */
3129 mdb_dbis_update(MDB_txn *txn, int keep)
3132 MDB_dbi n = txn->mt_numdbs;
3133 MDB_env *env = txn->mt_env;
3134 unsigned char *tdbflags = txn->mt_dbflags;
3136 for (i = n; --i >= CORE_DBS;) {
3137 if (tdbflags[i] & DB_NEW) {
3139 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
3141 char *ptr = env->me_dbxs[i].md_name.mv_data;
3143 env->me_dbxs[i].md_name.mv_data = NULL;
3144 env->me_dbxs[i].md_name.mv_size = 0;
3145 env->me_dbflags[i] = 0;
3146 env->me_dbiseqs[i]++;
3152 if (keep && env->me_numdbs < n)
3156 /** End a transaction, except successful commit of a nested transaction.
3157 * May be called twice for readonly txns: First reset it, then abort.
3158 * @param[in] txn the transaction handle to end
3159 * @param[in] mode why and how to end the transaction
3162 mdb_txn_end(MDB_txn *txn, unsigned mode)
3164 MDB_env *env = txn->mt_env;
3166 static const char *const names[] = MDB_END_NAMES;
3169 /* Export or close DBI handles opened in this txn */
3170 mdb_dbis_update(txn, mode & MDB_END_UPDATE);
3172 DPRINTF(("%s txn %"Y"u%c %p on mdbenv %p, root page %"Y"u",
3173 names[mode & MDB_END_OPMASK],
3174 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
3175 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
3177 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3178 if (txn->mt_u.reader) {
3179 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
3180 if (!(env->me_flags & MDB_NOTLS)) {
3181 txn->mt_u.reader = NULL; /* txn does not own reader */
3182 } else if (mode & MDB_END_SLOT) {
3183 txn->mt_u.reader->mr_pid = 0;
3184 txn->mt_u.reader = NULL;
3185 } /* else txn owns the slot until it does MDB_END_SLOT */
3187 txn->mt_numdbs = 0; /* prevent further DBI activity */
3188 txn->mt_flags |= MDB_TXN_FINISHED;
3190 } else if (!F_ISSET(txn->mt_flags, MDB_TXN_FINISHED)) {
3191 pgno_t *pghead = env->me_pghead;
3193 if (!(mode & MDB_END_UPDATE)) /* !(already closed cursors) */
3194 mdb_cursors_close(txn, 0);
3195 if (!(env->me_flags & MDB_WRITEMAP)) {
3196 mdb_dlist_free(txn);
3200 txn->mt_flags = MDB_TXN_FINISHED;
3202 if (!txn->mt_parent) {
3203 mdb_midl_shrink(&txn->mt_free_pgs);
3204 env->me_free_pgs = txn->mt_free_pgs;
3206 env->me_pghead = NULL;
3210 mode = 0; /* txn == env->me_txn0, do not free() it */
3212 /* The writer mutex was locked in mdb_txn_begin. */
3214 UNLOCK_MUTEX(env->me_wmutex);
3216 txn->mt_parent->mt_child = NULL;
3217 txn->mt_parent->mt_flags &= ~MDB_TXN_HAS_CHILD;
3218 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
3219 mdb_midl_free(txn->mt_free_pgs);
3220 mdb_midl_free(txn->mt_spill_pgs);
3221 free(txn->mt_u.dirty_list);
3224 mdb_midl_free(pghead);
3227 if (!txn->mt_parent) {
3228 MDB_ID3L el = env->me_rpages, tl = txn->mt_rpages;
3229 unsigned i, x, n = tl[0].mid;
3230 pthread_mutex_lock(&env->me_rpmutex);
3231 for (i = 1; i <= n; i++) {
3232 if (tl[i].mid & (MDB_RPAGE_CHUNK-1)) {
3233 /* tmp overflow pages that we didn't share in env */
3234 munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
3236 x = mdb_mid3l_search(el, tl[i].mid);
3237 if (tl[i].mptr == el[x].mptr) {
3240 /* another tmp overflow page */
3241 munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
3245 pthread_mutex_unlock(&env->me_rpmutex);
3247 if (mode & MDB_END_FREE)
3251 if (mode & MDB_END_FREE)
3256 mdb_txn_reset(MDB_txn *txn)
3261 /* This call is only valid for read-only txns */
3262 if (!(txn->mt_flags & MDB_TXN_RDONLY))
3265 mdb_txn_end(txn, MDB_END_RESET);
3269 mdb_txn_abort(MDB_txn *txn)
3275 mdb_txn_abort(txn->mt_child);
3277 mdb_txn_end(txn, MDB_END_ABORT|MDB_END_SLOT|MDB_END_FREE);
3280 /** Save the freelist as of this transaction to the freeDB.
3281 * This changes the freelist. Keep trying until it stabilizes.
3283 * When (MDB_DEVEL) & 2, the changes do not affect #mdb_page_alloc(),
3284 * it then uses the transaction's original snapshot of the freeDB.
3287 mdb_freelist_save(MDB_txn *txn)
3289 /* env->me_pghead[] can grow and shrink during this call.
3290 * env->me_pglast and txn->mt_free_pgs[] can only grow.
3291 * Page numbers cannot disappear from txn->mt_free_pgs[].
3294 MDB_env *env = txn->mt_env;
3295 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
3296 txnid_t pglast = 0, head_id = 0;
3297 pgno_t freecnt = 0, *free_pgs, *mop;
3298 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
3300 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
3302 if (env->me_pghead) {
3303 /* Make sure first page of freeDB is touched and on freelist */
3304 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
3305 if (rc && rc != MDB_NOTFOUND)
3309 if (!env->me_pghead && txn->mt_loose_pgs) {
3310 /* Put loose page numbers in mt_free_pgs, since
3311 * we may be unable to return them to me_pghead.
3313 MDB_page *mp = txn->mt_loose_pgs;
3314 if ((rc = mdb_midl_need(&txn->mt_free_pgs, txn->mt_loose_count)) != 0)
3316 for (; mp; mp = NEXT_LOOSE_PAGE(mp))
3317 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
3318 txn->mt_loose_pgs = NULL;
3319 txn->mt_loose_count = 0;
3322 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
3323 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
3324 ? SSIZE_MAX : maxfree_1pg;
3327 /* Come back here after each Put() in case freelist changed */
3332 /* If using records from freeDB which we have not yet
3333 * deleted, delete them and any we reserved for me_pghead.
3335 while (pglast < env->me_pglast) {
3336 rc = mdb_cursor_first(&mc, &key, NULL);
3339 pglast = head_id = *(txnid_t *)key.mv_data;
3340 total_room = head_room = 0;
3341 mdb_tassert(txn, pglast <= env->me_pglast);
3342 rc = mdb_cursor_del(&mc, 0);
3347 /* Save the IDL of pages freed by this txn, to a single record */
3348 if (freecnt < txn->mt_free_pgs[0]) {
3350 /* Make sure last page of freeDB is touched and on freelist */
3351 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
3352 if (rc && rc != MDB_NOTFOUND)
3355 free_pgs = txn->mt_free_pgs;
3356 /* Write to last page of freeDB */
3357 key.mv_size = sizeof(txn->mt_txnid);
3358 key.mv_data = &txn->mt_txnid;
3360 freecnt = free_pgs[0];
3361 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
3362 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3365 /* Retry if mt_free_pgs[] grew during the Put() */
3366 free_pgs = txn->mt_free_pgs;
3367 } while (freecnt < free_pgs[0]);
3368 mdb_midl_sort(free_pgs);
3369 memcpy(data.mv_data, free_pgs, data.mv_size);
3372 unsigned int i = free_pgs[0];
3373 DPRINTF(("IDL write txn %"Y"u root %"Y"u num %u",
3374 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
3376 DPRINTF(("IDL %"Y"u", free_pgs[i]));
3382 mop = env->me_pghead;
3383 mop_len = (mop ? mop[0] : 0) + txn->mt_loose_count;
3385 /* Reserve records for me_pghead[]. Split it if multi-page,
3386 * to avoid searching freeDB for a page range. Use keys in
3387 * range [1,me_pglast]: Smaller than txnid of oldest reader.
3389 if (total_room >= mop_len) {
3390 if (total_room == mop_len || --more < 0)
3392 } else if (head_room >= maxfree_1pg && head_id > 1) {
3393 /* Keep current record (overflow page), add a new one */
3397 /* (Re)write {key = head_id, IDL length = head_room} */
3398 total_room -= head_room;
3399 head_room = mop_len - total_room;
3400 if (head_room > maxfree_1pg && head_id > 1) {
3401 /* Overflow multi-page for part of me_pghead */
3402 head_room /= head_id; /* amortize page sizes */
3403 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
3404 } else if (head_room < 0) {
3405 /* Rare case, not bothering to delete this record */
3408 key.mv_size = sizeof(head_id);
3409 key.mv_data = &head_id;
3410 data.mv_size = (head_room + 1) * sizeof(pgno_t);
3411 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
3414 /* IDL is initially empty, zero out at least the length */
3415 pgs = (pgno_t *)data.mv_data;
3416 j = head_room > clean_limit ? head_room : 0;
3420 total_room += head_room;
3423 /* Return loose page numbers to me_pghead, though usually none are
3424 * left at this point. The pages themselves remain in dirty_list.
3426 if (txn->mt_loose_pgs) {
3427 MDB_page *mp = txn->mt_loose_pgs;
3428 unsigned count = txn->mt_loose_count;
3430 /* Room for loose pages + temp IDL with same */
3431 if ((rc = mdb_midl_need(&env->me_pghead, 2*count+1)) != 0)
3433 mop = env->me_pghead;
3434 loose = mop + MDB_IDL_ALLOCLEN(mop) - count;
3435 for (count = 0; mp; mp = NEXT_LOOSE_PAGE(mp))
3436 loose[ ++count ] = mp->mp_pgno;
3438 mdb_midl_sort(loose);
3439 mdb_midl_xmerge(mop, loose);
3440 txn->mt_loose_pgs = NULL;
3441 txn->mt_loose_count = 0;
3445 /* Fill in the reserved me_pghead records */
3451 rc = mdb_cursor_first(&mc, &key, &data);
3452 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
3453 txnid_t id = *(txnid_t *)key.mv_data;
3454 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
3457 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
3459 if (len > mop_len) {
3461 data.mv_size = (len + 1) * sizeof(MDB_ID);
3463 data.mv_data = mop -= len;
3466 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
3468 if (rc || !(mop_len -= len))
3475 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
3476 * @param[in] txn the transaction that's being committed
3477 * @param[in] keep number of initial pages in dirty_list to keep dirty.
3478 * @return 0 on success, non-zero on failure.
3481 mdb_page_flush(MDB_txn *txn, int keep)
3483 MDB_env *env = txn->mt_env;
3484 MDB_ID2L dl = txn->mt_u.dirty_list;
3485 unsigned psize = env->me_psize, j;
3486 int i, pagecount = dl[0].mid, rc;
3490 MDB_page *dp = NULL;
3494 struct iovec iov[MDB_COMMIT_PAGES];
3495 ssize_t wsize = 0, wres;
3496 off_t wpos = 0, next_pos = 1; /* impossible pos, so pos != next_pos */
3502 if (env->me_flags & MDB_WRITEMAP) {
3503 /* Clear dirty flags */
3504 while (++i <= pagecount) {
3506 /* Don't flush this page yet */
3507 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3508 dp->mp_flags &= ~P_KEEP;
3512 dp->mp_flags &= ~P_DIRTY;
3517 /* Write the pages */
3519 if (++i <= pagecount) {
3521 /* Don't flush this page yet */
3522 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3523 dp->mp_flags &= ~P_KEEP;
3528 /* clear dirty flag */
3529 dp->mp_flags &= ~P_DIRTY;
3532 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
3537 /* Windows actually supports scatter/gather I/O, but only on
3538 * unbuffered file handles. Since we're relying on the OS page
3539 * cache for all our data, that's self-defeating. So we just
3540 * write pages one at a time. We use the ov structure to set
3541 * the write offset, to at least save the overhead of a Seek
3544 DPRINTF(("committing page %"Z"u", pgno));
3545 memset(&ov, 0, sizeof(ov));
3546 ov.Offset = pos & 0xffffffff;
3547 ov.OffsetHigh = pos >> 16 >> 16;
3548 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
3550 DPRINTF(("WriteFile: %d", rc));
3554 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
3555 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
3558 /* Write previous page(s) */
3559 #ifdef MDB_USE_PWRITEV
3560 wres = pwritev(env->me_fd, iov, n, wpos);
3563 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
3566 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
3570 DPRINTF(("lseek: %s", strerror(rc)));
3573 wres = writev(env->me_fd, iov, n);
3576 if (wres != wsize) {
3581 DPRINTF(("Write error: %s", strerror(rc)));
3583 rc = EIO; /* TODO: Use which error code? */
3584 DPUTS("short write, filesystem full?");
3595 DPRINTF(("committing page %"Y"u", pgno));
3596 next_pos = pos + size;
3597 iov[n].iov_len = size;
3598 iov[n].iov_base = (char *)dp;
3604 if (pgno > txn->mt_last_pgno)
3605 txn->mt_last_pgno = pgno;
3608 /* MIPS has cache coherency issues, this is a no-op everywhere else
3609 * Note: for any size >= on-chip cache size, entire on-chip cache is
3612 CACHEFLUSH(env->me_map, txn->mt_next_pgno * env->me_psize, DCACHE);
3614 for (i = keep; ++i <= pagecount; ) {
3616 /* This is a page we skipped above */
3619 dl[j].mid = dp->mp_pgno;
3622 mdb_dpage_free(env, dp);
3627 txn->mt_dirty_room += i - j;
3633 mdb_txn_commit(MDB_txn *txn)
3636 unsigned int i, end_mode;
3642 /* mdb_txn_end() mode for a commit which writes nothing */
3643 end_mode = MDB_END_EMPTY_COMMIT|MDB_END_UPDATE|MDB_END_SLOT|MDB_END_FREE;
3645 if (txn->mt_child) {
3646 rc = mdb_txn_commit(txn->mt_child);
3653 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3657 if (txn->mt_flags & (MDB_TXN_FINISHED|MDB_TXN_ERROR)) {
3658 DPUTS("txn has failed/finished, can't commit");
3660 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3665 if (txn->mt_parent) {
3666 MDB_txn *parent = txn->mt_parent;
3670 unsigned x, y, len, ps_len;
3672 /* Append our free list to parent's */
3673 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3676 mdb_midl_free(txn->mt_free_pgs);
3677 /* Failures after this must either undo the changes
3678 * to the parent or set MDB_TXN_ERROR in the parent.
3681 parent->mt_next_pgno = txn->mt_next_pgno;
3682 parent->mt_flags = txn->mt_flags;
3684 /* Merge our cursors into parent's and close them */
3685 mdb_cursors_close(txn, 1);
3687 /* Update parent's DB table. */
3688 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3689 parent->mt_numdbs = txn->mt_numdbs;
3690 parent->mt_dbflags[FREE_DBI] = txn->mt_dbflags[FREE_DBI];
3691 parent->mt_dbflags[MAIN_DBI] = txn->mt_dbflags[MAIN_DBI];
3692 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
3693 /* preserve parent's DB_NEW status */
3694 x = parent->mt_dbflags[i] & DB_NEW;
3695 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3698 dst = parent->mt_u.dirty_list;
3699 src = txn->mt_u.dirty_list;
3700 /* Remove anything in our dirty list from parent's spill list */
3701 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3703 pspill[0] = (pgno_t)-1;
3704 /* Mark our dirty pages as deleted in parent spill list */
3705 for (i=0, len=src[0].mid; ++i <= len; ) {
3706 MDB_ID pn = src[i].mid << 1;
3707 while (pn > pspill[x])
3709 if (pn == pspill[x]) {
3714 /* Squash deleted pagenums if we deleted any */
3715 for (x=y; ++x <= ps_len; )
3716 if (!(pspill[x] & 1))
3717 pspill[++y] = pspill[x];
3721 /* Remove anything in our spill list from parent's dirty list */
3722 if (txn->mt_spill_pgs && txn->mt_spill_pgs[0]) {
3723 for (i=1; i<=txn->mt_spill_pgs[0]; i++) {
3724 MDB_ID pn = txn->mt_spill_pgs[i];
3726 continue; /* deleted spillpg */
3728 y = mdb_mid2l_search(dst, pn);
3729 if (y <= dst[0].mid && dst[y].mid == pn) {
3731 while (y < dst[0].mid) {
3740 /* Find len = length of merging our dirty list with parent's */
3742 dst[0].mid = 0; /* simplify loops */
3743 if (parent->mt_parent) {
3744 len = x + src[0].mid;
3745 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3746 for (i = x; y && i; y--) {
3747 pgno_t yp = src[y].mid;
3748 while (yp < dst[i].mid)
3750 if (yp == dst[i].mid) {
3755 } else { /* Simplify the above for single-ancestor case */
3756 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3758 /* Merge our dirty list with parent's */
3760 for (i = len; y; dst[i--] = src[y--]) {
3761 pgno_t yp = src[y].mid;
3762 while (yp < dst[x].mid)
3763 dst[i--] = dst[x--];
3764 if (yp == dst[x].mid)
3765 free(dst[x--].mptr);
3767 mdb_tassert(txn, i == x);
3769 free(txn->mt_u.dirty_list);
3770 parent->mt_dirty_room = txn->mt_dirty_room;
3771 if (txn->mt_spill_pgs) {
3772 if (parent->mt_spill_pgs) {
3773 /* TODO: Prevent failure here, so parent does not fail */
3774 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3776 parent->mt_flags |= MDB_TXN_ERROR;
3777 mdb_midl_free(txn->mt_spill_pgs);
3778 mdb_midl_sort(parent->mt_spill_pgs);
3780 parent->mt_spill_pgs = txn->mt_spill_pgs;
3784 /* Append our loose page list to parent's */
3785 for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(*lp))
3787 *lp = txn->mt_loose_pgs;
3788 parent->mt_loose_count += txn->mt_loose_count;
3790 parent->mt_child = NULL;
3791 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3796 if (txn != env->me_txn) {
3797 DPUTS("attempt to commit unknown transaction");
3802 mdb_cursors_close(txn, 0);
3804 if (!txn->mt_u.dirty_list[0].mid &&
3805 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
3808 DPRINTF(("committing txn %"Y"u %p on mdbenv %p, root page %"Y"u",
3809 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3811 /* Update DB root pointers */
3812 if (txn->mt_numdbs > CORE_DBS) {
3816 data.mv_size = sizeof(MDB_db);
3818 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3819 for (i = CORE_DBS; i < txn->mt_numdbs; i++) {
3820 if (txn->mt_dbflags[i] & DB_DIRTY) {
3821 if (TXN_DBI_CHANGED(txn, i)) {
3825 data.mv_data = &txn->mt_dbs[i];
3826 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data,
3834 rc = mdb_freelist_save(txn);
3838 mdb_midl_free(env->me_pghead);
3839 env->me_pghead = NULL;
3840 mdb_midl_shrink(&txn->mt_free_pgs);
3846 if ((rc = mdb_page_flush(txn, 0)))
3848 if (!F_ISSET(txn->mt_flags, MDB_TXN_NOSYNC) &&
3849 (rc = mdb_env_sync0(env, 0, txn->mt_next_pgno)))
3851 if ((rc = mdb_env_write_meta(txn)))
3853 end_mode = MDB_END_COMMITTED|MDB_END_UPDATE;
3856 mdb_txn_end(txn, end_mode);
3864 /** Read the environment parameters of a DB environment before
3865 * mapping it into memory.
3866 * @param[in] env the environment handle
3867 * @param[out] meta address of where to store the meta information
3868 * @return 0 on success, non-zero on failure.
3871 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3877 enum { Size = sizeof(pbuf) };
3879 /* We don't know the page size yet, so use a minimum value.
3880 * Read both meta pages so we can use the latest one.
3883 for (i=off=0; i<NUM_METAS; i++, off += meta->mm_psize) {
3887 memset(&ov, 0, sizeof(ov));
3889 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3890 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3893 rc = pread(env->me_fd, &pbuf, Size, off);
3896 if (rc == 0 && off == 0)
3898 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3899 DPRINTF(("read: %s", mdb_strerror(rc)));
3903 p = (MDB_page *)&pbuf;
3905 if (!F_ISSET(p->mp_flags, P_META)) {
3906 DPRINTF(("page %"Y"u not a meta page", p->mp_pgno));
3911 if (m->mm_magic != MDB_MAGIC) {
3912 DPUTS("meta has invalid magic");
3916 if (m->mm_version != MDB_DATA_VERSION) {
3917 DPRINTF(("database is version %u, expected version %u",
3918 m->mm_version, MDB_DATA_VERSION));
3919 return MDB_VERSION_MISMATCH;
3922 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3928 /** Fill in most of the zeroed #MDB_meta for an empty database environment */
3930 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
3932 meta->mm_magic = MDB_MAGIC;
3933 meta->mm_version = MDB_DATA_VERSION;
3934 meta->mm_mapsize = env->me_mapsize;
3935 meta->mm_psize = env->me_psize;
3936 meta->mm_last_pg = NUM_METAS-1;
3937 meta->mm_flags = env->me_flags & 0xffff;
3938 meta->mm_flags |= MDB_INTEGERKEY; /* this is mm_dbs[FREE_DBI].md_flags */
3939 meta->mm_dbs[FREE_DBI].md_root = P_INVALID;
3940 meta->mm_dbs[MAIN_DBI].md_root = P_INVALID;
3943 /** Write the environment parameters of a freshly created DB environment.
3944 * @param[in] env the environment handle
3945 * @param[in] meta the #MDB_meta to write
3946 * @return 0 on success, non-zero on failure.
3949 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3957 memset(&ov, 0, sizeof(ov));
3958 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3960 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3963 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3964 len = pwrite(fd, ptr, size, pos); \
3965 if (len == -1 && ErrCode() == EINTR) continue; \
3966 rc = (len >= 0); break; } while(1)
3969 DPUTS("writing new meta page");
3971 psize = env->me_psize;
3973 p = calloc(NUM_METAS, psize);
3977 p->mp_flags = P_META;
3978 *(MDB_meta *)METADATA(p) = *meta;
3980 q = (MDB_page *)((char *)p + psize);
3982 q->mp_flags = P_META;
3983 *(MDB_meta *)METADATA(q) = *meta;
3985 DO_PWRITE(rc, env->me_fd, p, psize * NUM_METAS, len, 0);
3988 else if ((unsigned) len == psize * NUM_METAS)
3996 /** Update the environment info to commit a transaction.
3997 * @param[in] txn the transaction that's being committed
3998 * @return 0 on success, non-zero on failure.
4001 mdb_env_write_meta(MDB_txn *txn)
4004 MDB_meta meta, metab, *mp;
4008 int rc, len, toggle;
4017 toggle = txn->mt_txnid & 1;
4018 DPRINTF(("writing meta page %d for root page %"Y"u",
4019 toggle, txn->mt_dbs[MAIN_DBI].md_root));
4022 flags = txn->mt_flags | env->me_flags;
4023 mp = env->me_metas[toggle];
4024 mapsize = env->me_metas[toggle ^ 1]->mm_mapsize;
4025 /* Persist any increases of mapsize config */
4026 if (mapsize < env->me_mapsize)
4027 mapsize = env->me_mapsize;
4029 if (flags & MDB_WRITEMAP) {
4030 mp->mm_mapsize = mapsize;
4031 mp->mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
4032 mp->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
4033 mp->mm_last_pg = txn->mt_next_pgno - 1;
4034 #if (__GNUC__ * 100 + __GNUC_MINOR__ >= 404) && /* TODO: portability */ \
4035 !(defined(__i386__) || defined(__x86_64__))
4036 /* LY: issue a memory barrier, if not x86. ITS#7969 */
4037 __sync_synchronize();
4039 mp->mm_txnid = txn->mt_txnid;
4040 if (!(flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
4041 unsigned meta_size = env->me_psize;
4042 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
4043 ptr = (char *)mp - PAGEHDRSZ;
4044 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
4045 r2 = (ptr - env->me_map) & (env->me_os_psize - 1);
4049 if (MDB_MSYNC(ptr, meta_size, rc)) {
4056 metab.mm_txnid = mp->mm_txnid;
4057 metab.mm_last_pg = mp->mm_last_pg;
4059 meta.mm_mapsize = mapsize;
4060 meta.mm_dbs[FREE_DBI] = txn->mt_dbs[FREE_DBI];
4061 meta.mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
4062 meta.mm_last_pg = txn->mt_next_pgno - 1;
4063 meta.mm_txnid = txn->mt_txnid;
4065 off = offsetof(MDB_meta, mm_mapsize);
4066 ptr = (char *)&meta + off;
4067 len = sizeof(MDB_meta) - off;
4068 off += (char *)mp - env->me_map;
4070 /* Write to the SYNC fd */
4071 mfd = (flags & (MDB_NOSYNC|MDB_NOMETASYNC)) ? env->me_fd : env->me_mfd;
4074 memset(&ov, 0, sizeof(ov));
4076 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
4081 rc = pwrite(mfd, ptr, len, off);
4084 rc = rc < 0 ? ErrCode() : EIO;
4089 DPUTS("write failed, disk error?");
4090 /* On a failure, the pagecache still contains the new data.
4091 * Write some old data back, to prevent it from being used.
4092 * Use the non-SYNC fd; we know it will fail anyway.
4094 meta.mm_last_pg = metab.mm_last_pg;
4095 meta.mm_txnid = metab.mm_txnid;
4097 memset(&ov, 0, sizeof(ov));
4099 WriteFile(env->me_fd, ptr, len, NULL, &ov);
4101 r2 = pwrite(env->me_fd, ptr, len, off);
4102 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
4105 env->me_flags |= MDB_FATAL_ERROR;
4108 /* MIPS has cache coherency issues, this is a no-op everywhere else */
4109 CACHEFLUSH(env->me_map + off, len, DCACHE);
4111 /* Memory ordering issues are irrelevant; since the entire writer
4112 * is wrapped by wmutex, all of these changes will become visible
4113 * after the wmutex is unlocked. Since the DB is multi-version,
4114 * readers will get consistent data regardless of how fresh or
4115 * how stale their view of these values is.
4118 env->me_txns->mti_txnid = txn->mt_txnid;
4123 /** Check both meta pages to see which one is newer.
4124 * @param[in] env the environment handle
4125 * @return newest #MDB_meta.
4128 mdb_env_pick_meta(const MDB_env *env)
4130 MDB_meta *const *metas = env->me_metas;
4131 return metas[ metas[0]->mm_txnid < metas[1]->mm_txnid ];
4135 mdb_env_create(MDB_env **env)
4139 e = calloc(1, sizeof(MDB_env));
4143 e->me_maxreaders = DEFAULT_READERS;
4144 e->me_maxdbs = e->me_numdbs = CORE_DBS;
4145 e->me_fd = INVALID_HANDLE_VALUE;
4146 e->me_lfd = INVALID_HANDLE_VALUE;
4147 e->me_mfd = INVALID_HANDLE_VALUE;
4148 #ifdef MDB_USE_POSIX_SEM
4149 e->me_rmutex = SEM_FAILED;
4150 e->me_wmutex = SEM_FAILED;
4151 #elif defined MDB_USE_SYSV_SEM
4152 e->me_rmutex->semid = -1;
4153 e->me_wmutex->semid = -1;
4155 e->me_pid = getpid();
4156 GET_PAGESIZE(e->me_os_psize);
4157 VGMEMP_CREATE(e,0,0);
4163 mdb_env_map(MDB_env *env, void *addr)
4166 unsigned int flags = env->me_flags;
4169 int access = SECTION_MAP_READ;
4173 ULONG pageprot = PAGE_READONLY, secprot, alloctype;
4175 if (flags & MDB_WRITEMAP) {
4176 access |= SECTION_MAP_WRITE;
4177 pageprot = PAGE_READWRITE;
4179 if (flags & MDB_RDONLY) {
4180 secprot = PAGE_READONLY;
4184 secprot = PAGE_READWRITE;
4185 msize = env->me_mapsize;
4186 alloctype = MEM_RESERVE;
4189 rc = NtCreateSection(&mh, access, NULL, NULL, secprot, SEC_RESERVE, env->me_fd);
4194 msize = NUM_METAS * env->me_psize;
4196 rc = NtMapViewOfSection(mh, GetCurrentProcess(), &map, 0, 0, NULL, &msize, ViewUnmap, alloctype, pageprot);
4208 env->me_map = mmap(addr, NUM_METAS * env->me_psize, PROT_READ, MAP_SHARED,
4210 if (env->me_map == MAP_FAILED) {
4215 int prot = PROT_READ;
4216 if (flags & MDB_WRITEMAP) {
4218 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
4221 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
4223 if (env->me_map == MAP_FAILED) {
4228 if (flags & MDB_NORDAHEAD) {
4229 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
4231 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
4233 #ifdef POSIX_MADV_RANDOM
4234 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
4235 #endif /* POSIX_MADV_RANDOM */
4236 #endif /* MADV_RANDOM */
4240 /* Can happen because the address argument to mmap() is just a
4241 * hint. mmap() can pick another, e.g. if the range is in use.
4242 * The MAP_FIXED flag would prevent that, but then mmap could
4243 * instead unmap existing pages to make room for the new map.
4245 if (addr && env->me_map != addr)
4246 return EBUSY; /* TODO: Make a new MDB_* error code? */
4249 p = (MDB_page *)env->me_map;
4250 env->me_metas[0] = METADATA(p);
4251 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
4257 mdb_env_set_mapsize(MDB_env *env, mdb_size_t size)
4259 /* If env is already open, caller is responsible for making
4260 * sure there are no active txns.
4270 meta = mdb_env_pick_meta(env);
4272 size = meta->mm_mapsize;
4274 /* Silently round up to minimum if the size is too small */
4275 mdb_size_t minsize = (meta->mm_last_pg + 1) * env->me_psize;
4280 /* For MDB_VL32 this bit is a noop since we dynamically remap
4281 * chunks of the DB anyway.
4283 munmap(env->me_map, env->me_mapsize);
4284 env->me_mapsize = size;
4285 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
4286 rc = mdb_env_map(env, old);
4289 #endif /* !MDB_VL32 */
4291 env->me_mapsize = size;
4293 env->me_maxpg = env->me_mapsize / env->me_psize;
4298 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
4302 env->me_maxdbs = dbs + CORE_DBS;
4307 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
4309 if (env->me_map || readers < 1)
4311 env->me_maxreaders = readers;
4316 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
4318 if (!env || !readers)
4320 *readers = env->me_maxreaders;
4325 mdb_fsize(HANDLE fd, mdb_size_t *size)
4328 LARGE_INTEGER fsize;
4330 if (!GetFileSizeEx(fd, &fsize))
4333 *size = fsize.QuadPart;
4345 #ifdef BROKEN_FDATASYNC
4346 #include <sys/utsname.h>
4347 #include <sys/vfs.h>
4350 /** Further setup required for opening an LMDB environment
4353 mdb_env_open2(MDB_env *env)
4355 unsigned int flags = env->me_flags;
4356 int i, newenv = 0, rc;
4360 /* See if we should use QueryLimited */
4362 if ((rc & 0xff) > 5)
4363 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
4365 env->me_pidquery = PROCESS_QUERY_INFORMATION;
4368 #ifdef BROKEN_FDATASYNC
4369 /* ext3/ext4 fdatasync is broken on some older Linux kernels.
4370 * https://lkml.org/lkml/2012/9/3/83
4371 * Kernels after 3.6-rc6 are known good.
4372 * https://lkml.org/lkml/2012/9/10/556
4373 * See if the DB is on ext3/ext4, then check for new enough kernel
4374 * Kernels 2.6.32.60, 2.6.34.15, 3.2.30, and 3.5.4 are also known
4379 fstatfs(env->me_fd, &st);
4380 while (st.f_type == 0xEF53) {
4384 if (uts.release[0] < '3') {
4385 if (!strncmp(uts.release, "2.6.32.", 7)) {
4386 i = atoi(uts.release+7);
4388 break; /* 2.6.32.60 and newer is OK */
4389 } else if (!strncmp(uts.release, "2.6.34.", 7)) {
4390 i = atoi(uts.release+7);
4392 break; /* 2.6.34.15 and newer is OK */
4394 } else if (uts.release[0] == '3') {
4395 i = atoi(uts.release+2);
4397 break; /* 3.6 and newer is OK */
4399 i = atoi(uts.release+4);
4401 break; /* 3.5.4 and newer is OK */
4402 } else if (i == 2) {
4403 i = atoi(uts.release+4);
4405 break; /* 3.2.30 and newer is OK */
4407 } else { /* 4.x and newer is OK */
4410 env->me_flags |= MDB_FSYNCONLY;
4416 if ((i = mdb_env_read_header(env, &meta)) != 0) {
4419 DPUTS("new mdbenv");
4421 env->me_psize = env->me_os_psize;
4422 if (env->me_psize > MAX_PAGESIZE)
4423 env->me_psize = MAX_PAGESIZE;
4424 memset(&meta, 0, sizeof(meta));
4425 mdb_env_init_meta0(env, &meta);
4426 meta.mm_mapsize = DEFAULT_MAPSIZE;
4428 env->me_psize = meta.mm_psize;
4431 /* Was a mapsize configured? */
4432 if (!env->me_mapsize) {
4433 env->me_mapsize = meta.mm_mapsize;
4436 /* Make sure mapsize >= committed data size. Even when using
4437 * mm_mapsize, which could be broken in old files (ITS#7789).
4439 mdb_size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
4440 if (env->me_mapsize < minsize)
4441 env->me_mapsize = minsize;
4443 meta.mm_mapsize = env->me_mapsize;
4445 if (newenv && !(flags & MDB_FIXEDMAP)) {
4446 /* mdb_env_map() may grow the datafile. Write the metapages
4447 * first, so the file will be valid if initialization fails.
4448 * Except with FIXEDMAP, since we do not yet know mm_address.
4449 * We could fill in mm_address later, but then a different
4450 * program might end up doing that - one with a memory layout
4451 * and map address which does not suit the main program.
4453 rc = mdb_env_init_meta(env, &meta);
4459 /* For FIXEDMAP, make sure the file is non-empty before we attempt to map it */
4463 rc = WriteFile(env->me_fd, &dummy, 1, &len, NULL);
4471 rc = mdb_env_map(env, (flags & MDB_FIXEDMAP) ? meta.mm_address : NULL);
4476 if (flags & MDB_FIXEDMAP)
4477 meta.mm_address = env->me_map;
4478 i = mdb_env_init_meta(env, &meta);
4479 if (i != MDB_SUCCESS) {
4484 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
4485 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
4487 #if !(MDB_MAXKEYSIZE)
4488 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
4490 env->me_maxpg = env->me_mapsize / env->me_psize;
4494 MDB_meta *meta = mdb_env_pick_meta(env);
4495 MDB_db *db = &meta->mm_dbs[MAIN_DBI];
4497 DPRINTF(("opened database version %u, pagesize %u",
4498 meta->mm_version, env->me_psize));
4499 DPRINTF(("using meta page %d", (int) (meta->mm_txnid & 1)));
4500 DPRINTF(("depth: %u", db->md_depth));
4501 DPRINTF(("entries: %"Y"u", db->md_entries));
4502 DPRINTF(("branch pages: %"Y"u", db->md_branch_pages));
4503 DPRINTF(("leaf pages: %"Y"u", db->md_leaf_pages));
4504 DPRINTF(("overflow pages: %"Y"u", db->md_overflow_pages));
4505 DPRINTF(("root: %"Y"u", db->md_root));
4513 /** Release a reader thread's slot in the reader lock table.
4514 * This function is called automatically when a thread exits.
4515 * @param[in] ptr This points to the slot in the reader lock table.
4518 mdb_env_reader_dest(void *ptr)
4520 MDB_reader *reader = ptr;
4526 /** Junk for arranging thread-specific callbacks on Windows. This is
4527 * necessarily platform and compiler-specific. Windows supports up
4528 * to 1088 keys. Let's assume nobody opens more than 64 environments
4529 * in a single process, for now. They can override this if needed.
4531 #ifndef MAX_TLS_KEYS
4532 #define MAX_TLS_KEYS 64
4534 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
4535 static int mdb_tls_nkeys;
4537 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
4541 case DLL_PROCESS_ATTACH: break;
4542 case DLL_THREAD_ATTACH: break;
4543 case DLL_THREAD_DETACH:
4544 for (i=0; i<mdb_tls_nkeys; i++) {
4545 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
4547 mdb_env_reader_dest(r);
4551 case DLL_PROCESS_DETACH: break;
4556 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4558 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
4562 /* Force some symbol references.
4563 * _tls_used forces the linker to create the TLS directory if not already done
4564 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
4566 #pragma comment(linker, "/INCLUDE:_tls_used")
4567 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
4568 #pragma const_seg(".CRT$XLB")
4569 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
4570 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4573 #pragma comment(linker, "/INCLUDE:__tls_used")
4574 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
4575 #pragma data_seg(".CRT$XLB")
4576 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
4578 #endif /* WIN 32/64 */
4579 #endif /* !__GNUC__ */
4582 /** Downgrade the exclusive lock on the region back to shared */
4584 mdb_env_share_locks(MDB_env *env, int *excl)
4587 MDB_meta *meta = mdb_env_pick_meta(env);
4589 env->me_txns->mti_txnid = meta->mm_txnid;
4594 /* First acquire a shared lock. The Unlock will
4595 * then release the existing exclusive lock.
4597 memset(&ov, 0, sizeof(ov));
4598 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4601 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4607 struct flock lock_info;
4608 /* The shared lock replaces the existing lock */
4609 memset((void *)&lock_info, 0, sizeof(lock_info));
4610 lock_info.l_type = F_RDLCK;
4611 lock_info.l_whence = SEEK_SET;
4612 lock_info.l_start = 0;
4613 lock_info.l_len = 1;
4614 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4615 (rc = ErrCode()) == EINTR) ;
4616 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
4623 /** Try to get exclusive lock, otherwise shared.
4624 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
4627 mdb_env_excl_lock(MDB_env *env, int *excl)
4631 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
4635 memset(&ov, 0, sizeof(ov));
4636 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4643 struct flock lock_info;
4644 memset((void *)&lock_info, 0, sizeof(lock_info));
4645 lock_info.l_type = F_WRLCK;
4646 lock_info.l_whence = SEEK_SET;
4647 lock_info.l_start = 0;
4648 lock_info.l_len = 1;
4649 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4650 (rc = ErrCode()) == EINTR) ;
4654 # ifndef MDB_USE_POSIX_MUTEX
4655 if (*excl < 0) /* always true when MDB_USE_POSIX_MUTEX */
4658 lock_info.l_type = F_RDLCK;
4659 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
4660 (rc = ErrCode()) == EINTR) ;
4670 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
4672 * @(#) $Revision: 5.1 $
4673 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
4674 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
4676 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
4680 * Please do not copyright this code. This code is in the public domain.
4682 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
4683 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
4684 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
4685 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
4686 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4687 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4688 * PERFORMANCE OF THIS SOFTWARE.
4691 * chongo <Landon Curt Noll> /\oo/\
4692 * http://www.isthe.com/chongo/
4694 * Share and Enjoy! :-)
4697 typedef unsigned long long mdb_hash_t;
4698 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
4700 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
4701 * @param[in] val value to hash
4702 * @param[in] hval initial value for hash
4703 * @return 64 bit hash
4705 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
4706 * hval arg on the first call.
4709 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
4711 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
4712 unsigned char *end = s + val->mv_size;
4714 * FNV-1a hash each octet of the string
4717 /* xor the bottom with the current octet */
4718 hval ^= (mdb_hash_t)*s++;
4720 /* multiply by the 64 bit FNV magic prime mod 2^64 */
4721 hval += (hval << 1) + (hval << 4) + (hval << 5) +
4722 (hval << 7) + (hval << 8) + (hval << 40);
4724 /* return our new hash value */
4728 /** Hash the string and output the encoded hash.
4729 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
4730 * very short name limits. We don't care about the encoding being reversible,
4731 * we just want to preserve as many bits of the input as possible in a
4732 * small printable string.
4733 * @param[in] str string to hash
4734 * @param[out] encbuf an array of 11 chars to hold the hash
4736 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
4739 mdb_pack85(unsigned long l, char *out)
4743 for (i=0; i<5; i++) {
4744 *out++ = mdb_a85[l % 85];
4750 mdb_hash_enc(MDB_val *val, char *encbuf)
4752 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
4754 mdb_pack85(h, encbuf);
4755 mdb_pack85(h>>32, encbuf+5);
4760 /** Open and/or initialize the lock region for the environment.
4761 * @param[in] env The LMDB environment.
4762 * @param[in] lpath The pathname of the file used for the lock region.
4763 * @param[in] mode The Unix permissions for the file, if we create it.
4764 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
4765 * @return 0 on success, non-zero on failure.
4768 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
4771 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
4773 # define MDB_ERRCODE_ROFS EROFS
4774 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
4775 # define MDB_CLOEXEC O_CLOEXEC
4778 # define MDB_CLOEXEC 0
4781 #ifdef MDB_USE_SYSV_SEM
4790 rc = utf8_to_utf16(lpath, -1, &wlpath, NULL);
4793 env->me_lfd = CreateFileW(wlpath, GENERIC_READ|GENERIC_WRITE,
4794 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
4795 FILE_ATTRIBUTE_NORMAL, NULL);
4798 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
4800 if (env->me_lfd == INVALID_HANDLE_VALUE) {
4802 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
4807 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
4808 /* Lose record locks when exec*() */
4809 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
4810 fcntl(env->me_lfd, F_SETFD, fdflags);
4813 if (!(env->me_flags & MDB_NOTLS)) {
4814 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
4817 env->me_flags |= MDB_ENV_TXKEY;
4819 /* Windows TLS callbacks need help finding their TLS info. */
4820 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
4824 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
4828 /* Try to get exclusive lock. If we succeed, then
4829 * nobody is using the lock region and we should initialize it.
4831 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
4834 size = GetFileSize(env->me_lfd, NULL);
4836 size = lseek(env->me_lfd, 0, SEEK_END);
4837 if (size == -1) goto fail_errno;
4839 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
4840 if (size < rsize && *excl > 0) {
4842 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
4843 || !SetEndOfFile(env->me_lfd))
4846 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
4850 size = rsize - sizeof(MDB_txninfo);
4851 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
4856 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
4858 if (!mh) goto fail_errno;
4859 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
4861 if (!env->me_txns) goto fail_errno;
4863 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
4865 if (m == MAP_FAILED) goto fail_errno;
4871 BY_HANDLE_FILE_INFORMATION stbuf;
4880 if (!mdb_sec_inited) {
4881 InitializeSecurityDescriptor(&mdb_null_sd,
4882 SECURITY_DESCRIPTOR_REVISION);
4883 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
4884 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
4885 mdb_all_sa.bInheritHandle = FALSE;
4886 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
4889 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
4890 idbuf.volume = stbuf.dwVolumeSerialNumber;
4891 idbuf.nhigh = stbuf.nFileIndexHigh;
4892 idbuf.nlow = stbuf.nFileIndexLow;
4893 val.mv_data = &idbuf;
4894 val.mv_size = sizeof(idbuf);
4895 mdb_hash_enc(&val, encbuf);
4896 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
4897 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
4898 env->me_rmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
4899 if (!env->me_rmutex) goto fail_errno;
4900 env->me_wmutex = CreateMutexA(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
4901 if (!env->me_wmutex) goto fail_errno;
4902 #elif defined(MDB_USE_POSIX_SEM)
4911 #if defined(__NetBSD__)
4912 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
4914 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
4915 idbuf.dev = stbuf.st_dev;
4916 idbuf.ino = stbuf.st_ino;
4917 val.mv_data = &idbuf;
4918 val.mv_size = sizeof(idbuf);
4919 mdb_hash_enc(&val, encbuf);
4920 #ifdef MDB_SHORT_SEMNAMES
4921 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
4923 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
4924 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
4925 /* Clean up after a previous run, if needed: Try to
4926 * remove both semaphores before doing anything else.
4928 sem_unlink(env->me_txns->mti_rmname);
4929 sem_unlink(env->me_txns->mti_wmname);
4930 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
4931 O_CREAT|O_EXCL, mode, 1);
4932 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4933 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
4934 O_CREAT|O_EXCL, mode, 1);
4935 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4936 #elif defined(MDB_USE_SYSV_SEM)
4937 unsigned short vals[2] = {1, 1};
4938 key_t key = ftok(lpath, 'M');
4941 semid = semget(key, 2, (mode & 0777) | IPC_CREAT);
4945 if (semctl(semid, 0, SETALL, semu) < 0)
4947 env->me_txns->mti_semid = semid;
4948 #else /* MDB_USE_POSIX_MUTEX: */
4949 pthread_mutexattr_t mattr;
4951 if ((rc = pthread_mutexattr_init(&mattr))
4952 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
4953 #ifdef MDB_ROBUST_SUPPORTED
4954 || (rc = pthread_mutexattr_setrobust(&mattr, PTHREAD_MUTEX_ROBUST))
4956 || (rc = pthread_mutex_init(env->me_txns->mti_rmutex, &mattr))
4957 || (rc = pthread_mutex_init(env->me_txns->mti_wmutex, &mattr)))
4959 pthread_mutexattr_destroy(&mattr);
4960 #endif /* _WIN32 || ... */
4962 env->me_txns->mti_magic = MDB_MAGIC;
4963 env->me_txns->mti_format = MDB_LOCK_FORMAT;
4964 env->me_txns->mti_txnid = 0;
4965 env->me_txns->mti_numreaders = 0;
4968 #ifdef MDB_USE_SYSV_SEM
4969 struct semid_ds buf;
4971 if (env->me_txns->mti_magic != MDB_MAGIC) {
4972 DPUTS("lock region has invalid magic");
4976 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
4977 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
4978 env->me_txns->mti_format, MDB_LOCK_FORMAT));
4979 rc = MDB_VERSION_MISMATCH;
4983 if (rc && rc != EACCES && rc != EAGAIN) {
4987 env->me_rmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
4988 if (!env->me_rmutex) goto fail_errno;
4989 env->me_wmutex = OpenMutexA(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
4990 if (!env->me_wmutex) goto fail_errno;
4991 #elif defined(MDB_USE_POSIX_SEM)
4992 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
4993 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4994 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
4995 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4996 #elif defined(MDB_USE_SYSV_SEM)
4997 semid = env->me_txns->mti_semid;
4999 /* check for read access */
5000 if (semctl(semid, 0, IPC_STAT, semu) < 0)
5002 /* check for write access */
5003 if (semctl(semid, 0, IPC_SET, semu) < 0)
5007 #ifdef MDB_USE_SYSV_SEM
5008 env->me_rmutex->semid = semid;
5009 env->me_wmutex->semid = semid;
5010 env->me_rmutex->semnum = 0;
5011 env->me_wmutex->semnum = 1;
5012 env->me_rmutex->locked = &env->me_txns->mti_rlocked;
5013 env->me_wmutex->locked = &env->me_txns->mti_wlocked;
5017 env->me_rpmutex = CreateMutex(NULL, FALSE, NULL);
5019 pthread_mutex_init(&env->me_rpmutex, NULL);
5031 /** The name of the lock file in the DB environment */
5032 #define LOCKNAME "/lock.mdb"
5033 /** The name of the data file in the DB environment */
5034 #define DATANAME "/data.mdb"
5035 /** The suffix of the lock file when no subdir is used */
5036 #define LOCKSUFF "-lock"
5037 /** Only a subset of the @ref mdb_env flags can be changed
5038 * at runtime. Changing other flags requires closing the
5039 * environment and re-opening it with the new flags.
5041 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
5042 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY| \
5043 MDB_WRITEMAP|MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
5045 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
5046 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
5050 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
5052 int oflags, rc, len, excl = -1;
5053 char *lpath, *dpath;
5058 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
5062 if (flags & MDB_WRITEMAP) {
5063 /* silently ignore WRITEMAP in 32 bit mode */
5064 flags ^= MDB_WRITEMAP;
5066 if (flags & MDB_FIXEDMAP) {
5067 /* cannot support FIXEDMAP */
5073 if (flags & MDB_NOSUBDIR) {
5074 rc = len + sizeof(LOCKSUFF) + len + 1;
5076 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
5081 if (flags & MDB_NOSUBDIR) {
5082 dpath = lpath + len + sizeof(LOCKSUFF);
5083 sprintf(lpath, "%s" LOCKSUFF, path);
5084 strcpy(dpath, path);
5086 dpath = lpath + len + sizeof(LOCKNAME);
5087 sprintf(lpath, "%s" LOCKNAME, path);
5088 sprintf(dpath, "%s" DATANAME, path);
5092 flags |= env->me_flags;
5093 if (flags & MDB_RDONLY) {
5094 /* silently ignore WRITEMAP when we're only getting read access */
5095 flags &= ~MDB_WRITEMAP;
5097 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
5098 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
5103 env->me_rpages = malloc(MDB_ERPAGE_SIZE * sizeof(MDB_ID3));
5104 if (!env->me_rpages) {
5108 env->me_rpages[0].mid = 0;
5109 env->me_rpcheck = MDB_ERPAGE_SIZE/2;
5112 env->me_flags = flags |= MDB_ENV_ACTIVE;
5116 env->me_path = strdup(path);
5117 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
5118 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
5119 env->me_dbiseqs = calloc(env->me_maxdbs, sizeof(unsigned int));
5120 if (!(env->me_dbxs && env->me_path && env->me_dbflags && env->me_dbiseqs)) {
5124 env->me_dbxs[FREE_DBI].md_cmp = mdb_cmp_long; /* aligned MDB_INTEGERKEY */
5126 /* For RDONLY, get lockfile after we know datafile exists */
5127 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
5128 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
5134 if (F_ISSET(flags, MDB_RDONLY)) {
5135 oflags = GENERIC_READ;
5136 len = OPEN_EXISTING;
5138 oflags = GENERIC_READ|GENERIC_WRITE;
5141 mode = FILE_ATTRIBUTE_NORMAL;
5142 rc = utf8_to_utf16(dpath, -1, &wpath, NULL);
5145 env->me_fd = CreateFileW(wpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
5146 NULL, len, mode, NULL);
5149 if (F_ISSET(flags, MDB_RDONLY))
5152 oflags = O_RDWR | O_CREAT;
5154 env->me_fd = open(dpath, oflags, mode);
5156 if (env->me_fd == INVALID_HANDLE_VALUE) {
5161 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
5162 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
5167 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
5168 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
5169 env->me_mfd = env->me_fd;
5171 /* Synchronous fd for meta writes. Needed even with
5172 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
5175 len = OPEN_EXISTING;
5176 rc = utf8_to_utf16(dpath, -1, &wpath, NULL);
5179 env->me_mfd = CreateFileW(wpath, oflags,
5180 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
5181 mode | FILE_FLAG_WRITE_THROUGH, NULL);
5185 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
5187 if (env->me_mfd == INVALID_HANDLE_VALUE) {
5192 DPRINTF(("opened dbenv %p", (void *) env));
5194 rc = mdb_env_share_locks(env, &excl);
5198 if (!(flags & MDB_RDONLY)) {
5200 int tsize = sizeof(MDB_txn), size = tsize + env->me_maxdbs *
5201 (sizeof(MDB_db)+sizeof(MDB_cursor *)+sizeof(unsigned int)+1);
5202 if ((env->me_pbuf = calloc(1, env->me_psize)) &&
5203 (txn = calloc(1, size)))
5205 txn->mt_dbs = (MDB_db *)((char *)txn + tsize);
5206 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
5207 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
5208 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
5211 txn->mt_rpages = malloc(MDB_TRPAGE_SIZE * sizeof(MDB_ID3));
5212 if (!txn->mt_rpages) {
5217 txn->mt_rpages[0].mid = 0;
5218 txn->mt_rpcheck = MDB_TRPAGE_SIZE/2;
5220 txn->mt_dbxs = env->me_dbxs;
5221 txn->mt_flags = MDB_TXN_FINISHED;
5231 mdb_env_close0(env, excl);
5237 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
5239 mdb_env_close0(MDB_env *env, int excl)
5243 if (!(env->me_flags & MDB_ENV_ACTIVE))
5246 /* Doing this here since me_dbxs may not exist during mdb_env_close */
5248 for (i = env->me_maxdbs; --i >= CORE_DBS; )
5249 free(env->me_dbxs[i].md_name.mv_data);
5254 free(env->me_dbiseqs);
5255 free(env->me_dbflags);
5257 free(env->me_dirty_list);
5259 if (env->me_txn0 && env->me_txn0->mt_rpages)
5260 free(env->me_txn0->mt_rpages);
5262 for (x=1; x<=env->me_rpages[0].mid; x++)
5263 munmap(env->me_rpages[x].mptr, env->me_rpages[x].mcnt * env->me_psize);
5265 free(env->me_rpages);
5268 mdb_midl_free(env->me_free_pgs);
5270 if (env->me_flags & MDB_ENV_TXKEY) {
5271 pthread_key_delete(env->me_txkey);
5273 /* Delete our key from the global list */
5274 for (i=0; i<mdb_tls_nkeys; i++)
5275 if (mdb_tls_keys[i] == env->me_txkey) {
5276 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
5285 munmap(env->me_map, NUM_METAS*env->me_psize);
5287 munmap(env->me_map, env->me_mapsize);
5290 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
5291 (void) close(env->me_mfd);
5292 if (env->me_fd != INVALID_HANDLE_VALUE)
5293 (void) close(env->me_fd);
5295 MDB_PID_T pid = env->me_pid;
5296 /* Clearing readers is done in this function because
5297 * me_txkey with its destructor must be disabled first.
5299 * We skip the the reader mutex, so we touch only
5300 * data owned by this process (me_close_readers and
5301 * our readers), and clear each reader atomically.
5303 for (i = env->me_close_readers; --i >= 0; )
5304 if (env->me_txns->mti_readers[i].mr_pid == pid)
5305 env->me_txns->mti_readers[i].mr_pid = 0;
5307 if (env->me_rmutex) {
5308 CloseHandle(env->me_rmutex);
5309 if (env->me_wmutex) CloseHandle(env->me_wmutex);
5311 /* Windows automatically destroys the mutexes when
5312 * the last handle closes.
5314 #elif defined(MDB_USE_POSIX_SEM)
5315 if (env->me_rmutex != SEM_FAILED) {
5316 sem_close(env->me_rmutex);
5317 if (env->me_wmutex != SEM_FAILED)
5318 sem_close(env->me_wmutex);
5319 /* If we have the filelock: If we are the
5320 * only remaining user, clean up semaphores.
5323 mdb_env_excl_lock(env, &excl);
5325 sem_unlink(env->me_txns->mti_rmname);
5326 sem_unlink(env->me_txns->mti_wmname);
5329 #elif defined(MDB_USE_SYSV_SEM)
5330 if (env->me_rmutex->semid != -1) {
5331 /* If we have the filelock: If we are the
5332 * only remaining user, clean up semaphores.
5335 mdb_env_excl_lock(env, &excl);
5337 semctl(env->me_rmutex->semid, 0, IPC_RMID);
5340 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
5342 if (env->me_lfd != INVALID_HANDLE_VALUE) {
5345 /* Unlock the lockfile. Windows would have unlocked it
5346 * after closing anyway, but not necessarily at once.
5348 UnlockFile(env->me_lfd, 0, 0, 1, 0);
5351 (void) close(env->me_lfd);
5355 if (env->me_fmh) CloseHandle(env->me_fmh);
5356 if (env->me_rpmutex) CloseHandle(env->me_rpmutex);
5358 pthread_mutex_destroy(&env->me_rpmutex);
5362 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
5366 mdb_env_close(MDB_env *env)
5373 VGMEMP_DESTROY(env);
5374 while ((dp = env->me_dpages) != NULL) {
5375 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
5376 env->me_dpages = dp->mp_next;
5380 mdb_env_close0(env, 0);
5384 /** Compare two items pointing at aligned mdb_size_t's */
5386 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
5388 return (*(mdb_size_t *)a->mv_data < *(mdb_size_t *)b->mv_data) ? -1 :
5389 *(mdb_size_t *)a->mv_data > *(mdb_size_t *)b->mv_data;
5392 /** Compare two items pointing at aligned unsigned int's.
5394 * This is also set as #MDB_INTEGERDUP|#MDB_DUPFIXED's #MDB_dbx.%md_dcmp,
5395 * but #mdb_cmp_clong() is called instead if the data type is mdb_size_t.
5398 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
5400 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
5401 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
5404 /** Compare two items pointing at unsigned ints of unknown alignment.
5405 * Nodes and keys are guaranteed to be 2-byte aligned.
5408 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
5410 #if BYTE_ORDER == LITTLE_ENDIAN
5411 unsigned short *u, *c;
5414 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5415 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
5418 } while(!x && u > (unsigned short *)a->mv_data);
5421 unsigned short *u, *c, *end;
5424 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
5425 u = (unsigned short *)a->mv_data;
5426 c = (unsigned short *)b->mv_data;
5429 } while(!x && u < end);
5434 /** Compare two items lexically */
5436 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
5443 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5449 diff = memcmp(a->mv_data, b->mv_data, len);
5450 return diff ? diff : len_diff<0 ? -1 : len_diff;
5453 /** Compare two items in reverse byte order */
5455 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
5457 const unsigned char *p1, *p2, *p1_lim;
5461 p1_lim = (const unsigned char *)a->mv_data;
5462 p1 = (const unsigned char *)a->mv_data + a->mv_size;
5463 p2 = (const unsigned char *)b->mv_data + b->mv_size;
5465 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
5471 while (p1 > p1_lim) {
5472 diff = *--p1 - *--p2;
5476 return len_diff<0 ? -1 : len_diff;
5479 /** Search for key within a page, using binary search.
5480 * Returns the smallest entry larger or equal to the key.
5481 * If exactp is non-null, stores whether the found entry was an exact match
5482 * in *exactp (1 or 0).
5483 * Updates the cursor index with the index of the found entry.
5484 * If no entry larger or equal to the key is found, returns NULL.
5487 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
5489 unsigned int i = 0, nkeys;
5492 MDB_page *mp = mc->mc_pg[mc->mc_top];
5493 MDB_node *node = NULL;
5498 nkeys = NUMKEYS(mp);
5500 DPRINTF(("searching %u keys in %s %spage %"Y"u",
5501 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
5504 low = IS_LEAF(mp) ? 0 : 1;
5506 cmp = mc->mc_dbx->md_cmp;
5508 /* Branch pages have no data, so if using integer keys,
5509 * alignment is guaranteed. Use faster mdb_cmp_int.
5511 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
5512 if (NODEPTR(mp, 1)->mn_ksize == sizeof(mdb_size_t))
5519 nodekey.mv_size = mc->mc_db->md_pad;
5520 node = NODEPTR(mp, 0); /* fake */
5521 while (low <= high) {
5522 i = (low + high) >> 1;
5523 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
5524 rc = cmp(key, &nodekey);
5525 DPRINTF(("found leaf index %u [%s], rc = %i",
5526 i, DKEY(&nodekey), rc));
5535 while (low <= high) {
5536 i = (low + high) >> 1;
5538 node = NODEPTR(mp, i);
5539 nodekey.mv_size = NODEKSZ(node);
5540 nodekey.mv_data = NODEKEY(node);
5542 rc = cmp(key, &nodekey);
5545 DPRINTF(("found leaf index %u [%s], rc = %i",
5546 i, DKEY(&nodekey), rc));
5548 DPRINTF(("found branch index %u [%s -> %"Y"u], rc = %i",
5549 i, DKEY(&nodekey), NODEPGNO(node), rc));
5560 if (rc > 0) { /* Found entry is less than the key. */
5561 i++; /* Skip to get the smallest entry larger than key. */
5563 node = NODEPTR(mp, i);
5566 *exactp = (rc == 0 && nkeys > 0);
5567 /* store the key index */
5568 mc->mc_ki[mc->mc_top] = i;
5570 /* There is no entry larger or equal to the key. */
5573 /* nodeptr is fake for LEAF2 */
5579 mdb_cursor_adjust(MDB_cursor *mc, func)
5583 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
5584 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
5591 /** Pop a page off the top of the cursor's stack. */
5593 mdb_cursor_pop(MDB_cursor *mc)
5596 DPRINTF(("popping page %"Y"u off db %d cursor %p",
5597 mc->mc_pg[mc->mc_top]->mp_pgno, DDBI(mc), (void *) mc));
5603 mc->mc_flags &= ~C_INITIALIZED;
5608 /** Push a page onto the top of the cursor's stack. */
5610 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
5612 DPRINTF(("pushing page %"Y"u on db %d cursor %p", mp->mp_pgno,
5613 DDBI(mc), (void *) mc));
5615 if (mc->mc_snum >= CURSOR_STACK) {
5616 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5617 return MDB_CURSOR_FULL;
5620 mc->mc_top = mc->mc_snum++;
5621 mc->mc_pg[mc->mc_top] = mp;
5622 mc->mc_ki[mc->mc_top] = 0;
5628 /** Map a read-only page.
5629 * There are two levels of tracking in use, a per-txn list and a per-env list.
5630 * ref'ing and unref'ing the per-txn list is faster since it requires no
5631 * locking. Pages are cached in the per-env list for global reuse, and a lock
5632 * is required. Pages are not immediately unmapped when their refcnt goes to
5633 * zero; they hang around in case they will be reused again soon.
5635 * When the per-txn list gets full, all pages with refcnt=0 are purged from the
5636 * list and their refcnts in the per-env list are decremented.
5638 * When the per-env list gets full, all pages with refcnt=0 are purged from the
5639 * list and their pages are unmapped.
5641 * @note "full" means the list has reached its respective rpcheck threshold.
5642 * This threshold slowly raises if no pages could be purged on a given check,
5643 * and returns to its original value when enough pages were purged.
5645 * If purging doesn't free any slots, filling the per-txn list will return
5646 * MDB_TXN_FULL, and filling the per-env list returns MDB_MAP_FULL.
5648 * Reference tracking in a txn is imperfect, pages can linger with non-zero
5649 * refcnt even without active references. It was deemed to be too invasive
5650 * to add unrefs in every required location. However, all pages are unref'd
5651 * at the end of the transaction. This guarantees that no stale references
5652 * linger in the per-env list.
5654 * Usually we map chunks of 16 pages at a time, but if an overflow page begins
5655 * at the tail of the chunk we extend the chunk to include the entire overflow
5656 * page. Unfortunately, pages can be turned into overflow pages after their
5657 * chunk was already mapped. In that case we must remap the chunk if the
5658 * overflow page is referenced. If the chunk's refcnt is 0 we can just remap
5659 * it, otherwise we temporarily map a new chunk just for the overflow page.
5661 * @note this chunk handling means we cannot guarantee that a data item
5662 * returned from the DB will stay alive for the duration of the transaction:
5663 * We unref pages as soon as a cursor moves away from the page
5664 * A subsequent op may cause a purge, which may unmap any unref'd chunks
5665 * The caller must copy the data if it must be used later in the same txn.
5667 * Also - our reference counting revolves around cursors, but overflow pages
5668 * aren't pointed to by a cursor's page stack. We have to remember them
5669 * explicitly, in the added mc_ovpg field. A single cursor can only hold a
5670 * reference to one overflow page at a time.
5672 * @param[in] txn the transaction for this access.
5673 * @param[in] pgno the page number for the page to retrieve.
5674 * @param[out] ret address of a pointer where the page's address will be stored.
5675 * @return 0 on success, non-zero on failure.
5678 mdb_rpage_get(MDB_txn *txn, pgno_t pg0, MDB_page **ret)
5680 MDB_env *env = txn->mt_env;
5682 MDB_ID3L tl = txn->mt_rpages;
5683 MDB_ID3L el = env->me_rpages;
5687 int rc, retries = 1;
5691 #define SET_OFF(off,val) off.QuadPart = val
5692 #define MAP(rc,env,addr,len,off) \
5694 rc = NtMapViewOfSection(env->me_fmh, GetCurrentProcess(), &addr, 0, \
5695 len, &off, &len, ViewUnmap, (env->me_flags & MDB_RDONLY) ? 0 : MEM_RESERVE, PAGE_READONLY)
5699 #define SET_OFF(off,val) off = val
5700 #define MAP(rc,env,addr,len,off) \
5701 addr = mmap(NULL, len, PROT_READ, MAP_SHARED, env->me_fd, off); \
5702 rc = (addr == MAP_FAILED) ? errno : 0
5705 /* remember the offset of the actual page number, so we can
5706 * return the correct pointer at the end.
5708 rem = pg0 & (MDB_RPAGE_CHUNK-1);
5712 x = mdb_mid3l_search(tl, pgno);
5713 if (x <= tl[0].mid && tl[x].mid == pgno) {
5714 if (x != tl[0].mid && tl[x+1].mid == pg0)
5716 /* check for overflow size */
5717 p = (MDB_page *)((char *)tl[x].mptr + rem * env->me_psize);
5718 if (IS_OVERFLOW(p) && p->mp_pages + rem > tl[x].mcnt) {
5719 id3.mcnt = p->mp_pages + rem;
5720 len = id3.mcnt * env->me_psize;
5721 SET_OFF(off, pgno * env->me_psize);
5722 MAP(rc, env, id3.mptr, len, off);
5725 /* check for local-only page */
5727 mdb_tassert(txn, tl[x].mid != pg0);
5728 /* hope there's room to insert this locally.
5729 * setting mid here tells later code to just insert
5730 * this id3 instead of searching for a match.
5735 /* ignore the mapping we got from env, use new one */
5736 tl[x].mptr = id3.mptr;
5737 tl[x].mcnt = id3.mcnt;
5738 /* if no active ref, see if we can replace in env */
5741 pthread_mutex_lock(&env->me_rpmutex);
5742 i = mdb_mid3l_search(el, tl[x].mid);
5743 if (el[i].mref == 1) {
5744 /* just us, replace it */
5745 munmap(el[i].mptr, el[i].mcnt * env->me_psize);
5746 el[i].mptr = tl[x].mptr;
5747 el[i].mcnt = tl[x].mcnt;
5749 /* there are others, remove ourself */
5752 pthread_mutex_unlock(&env->me_rpmutex);
5756 id3.mptr = tl[x].mptr;
5757 id3.mcnt = tl[x].mcnt;
5763 if (tl[0].mid >= MDB_TRPAGE_MAX - txn->mt_rpcheck) {
5765 /* purge unref'd pages from our list and unref in env */
5766 pthread_mutex_lock(&env->me_rpmutex);
5769 for (i=1; i<=tl[0].mid; i++) {
5772 /* tmp overflow pages don't go to env */
5773 if (tl[i].mid & (MDB_RPAGE_CHUNK-1)) {
5774 munmap(tl[i].mptr, tl[i].mcnt * env->me_psize);
5777 x = mdb_mid3l_search(el, tl[i].mid);
5781 pthread_mutex_unlock(&env->me_rpmutex);
5783 /* we didn't find any unref'd chunks.
5784 * if we're out of room, fail.
5786 if (tl[0].mid >= MDB_TRPAGE_MAX)
5787 return MDB_TXN_FULL;
5788 /* otherwise, raise threshold for next time around
5791 txn->mt_rpcheck /= 2;
5793 /* we found some unused; consolidate the list */
5794 for (i=y+1; i<= tl[0].mid; i++)
5798 /* decrease the check threshold toward its original value */
5799 if (!txn->mt_rpcheck)
5800 txn->mt_rpcheck = 1;
5801 while (txn->mt_rpcheck < tl[0].mid && txn->mt_rpcheck < MDB_TRPAGE_SIZE/2)
5802 txn->mt_rpcheck *= 2;
5805 if (tl[0].mid < MDB_TRPAGE_SIZE) {
5809 /* don't map past last written page in read-only envs */
5810 if ((env->me_flags & MDB_RDONLY) && pgno + MDB_RPAGE_CHUNK-1 > txn->mt_last_pgno)
5811 id3.mcnt = txn->mt_last_pgno + 1 - pgno;
5813 id3.mcnt = MDB_RPAGE_CHUNK;
5814 len = id3.mcnt * env->me_psize;
5817 /* search for page in env */
5818 pthread_mutex_lock(&env->me_rpmutex);
5819 x = mdb_mid3l_search(el, pgno);
5820 if (x <= el[0].mid && el[x].mid == pgno) {
5821 id3.mptr = el[x].mptr;
5822 id3.mcnt = el[x].mcnt;
5823 /* check for overflow size */
5824 p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
5825 if (IS_OVERFLOW(p) && p->mp_pages + rem > id3.mcnt) {
5826 id3.mcnt = p->mp_pages + rem;
5827 len = id3.mcnt * env->me_psize;
5828 SET_OFF(off, pgno * env->me_psize);
5829 MAP(rc, env, id3.mptr, len, off);
5833 munmap(el[x].mptr, el[x].mcnt);
5834 el[x].mptr = id3.mptr;
5835 el[x].mcnt = id3.mcnt;
5838 pthread_mutex_unlock(&env->me_rpmutex);
5843 pthread_mutex_unlock(&env->me_rpmutex);
5846 if (el[0].mid >= MDB_ERPAGE_MAX - env->me_rpcheck) {
5847 /* purge unref'd pages */
5849 for (i=1; i<=el[0].mid; i++) {
5852 munmap(el[i].mptr, env->me_psize * el[i].mcnt);
5857 /* see if we can unref some local pages */
5862 if (el[0].mid >= MDB_ERPAGE_MAX) {
5863 pthread_mutex_unlock(&env->me_rpmutex);
5864 return MDB_MAP_FULL;
5866 env->me_rpcheck /= 2;
5868 for (i=y+1; i<= el[0].mid; i++)
5872 if (!env->me_rpcheck)
5873 env->me_rpcheck = 1;
5874 while (env->me_rpcheck < el[0].mid && env->me_rpcheck < MDB_ERPAGE_SIZE/2)
5875 env->me_rpcheck *= 2;
5878 SET_OFF(off, pgno * env->me_psize);
5879 MAP(rc, env, id3.mptr, len, off);
5882 pthread_mutex_unlock(&env->me_rpmutex);
5885 /* If this page is far enough from the end of the env, scan for
5886 * any overflow pages that would spill onto another block.
5887 * Note we must compare against mt_last_pgno, the last written
5888 * page in the environment. Not mt_next_pgno, which increases
5889 * for every newly allocated (but not yet written) page. If
5890 * we scanned beyond the last written page we'd get a bus error.
5892 if (pgno + MDB_RPAGE_CHUNK <= txn->mt_last_pgno) {
5894 char *cp = (char *)id3.mptr + rem * env->me_psize;
5895 for (i=rem; i<MDB_RPAGE_CHUNK;) {
5897 if (IS_OVERFLOW(p)) {
5898 int nop = p->mp_pages;
5899 if (nop + i > MDB_RPAGE_CHUNK) {
5900 munmap(id3.mptr, len);
5902 len = id3.mcnt * env->me_psize;
5903 MAP(rc, env, id3.mptr, len, off);
5909 cp += nop * env->me_psize;
5912 cp += env->me_psize;
5916 mdb_mid3l_insert(el, &id3);
5917 pthread_mutex_unlock(&env->me_rpmutex);
5919 mdb_mid3l_insert(tl, &id3);
5921 return MDB_TXN_FULL;
5924 p = (MDB_page *)((char *)id3.mptr + rem * env->me_psize);
5925 #if MDB_DEBUG /* we don't need this check any more */
5926 if (IS_OVERFLOW(p)) {
5927 mdb_tassert(txn, p->mp_pages + rem <= id3.mcnt);
5935 /** Find the address of the page corresponding to a given page number.
5936 * @param[in] mc the cursor accessing the page.
5937 * @param[in] pgno the page number for the page to retrieve.
5938 * @param[out] ret address of a pointer where the page's address will be stored.
5939 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
5940 * @return 0 on success, non-zero on failure.
5943 mdb_page_get(MDB_cursor *mc, pgno_t pgno, MDB_page **ret, int *lvl)
5945 MDB_txn *txn = mc->mc_txn;
5947 MDB_env *env = txn->mt_env;
5952 if (! (mc->mc_flags & (C_ORIG_RDONLY|C_WRITEMAP))) {
5956 MDB_ID2L dl = tx2->mt_u.dirty_list;
5958 /* Spilled pages were dirtied in this txn and flushed
5959 * because the dirty list got full. Bring this page
5960 * back in from the map (but don't unspill it here,
5961 * leave that unless page_touch happens again).
5963 if (tx2->mt_spill_pgs) {
5964 MDB_ID pn = pgno << 1;
5965 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
5966 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
5968 int rc = mdb_rpage_get(txn, pgno, &p);
5972 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
5978 unsigned x = mdb_mid2l_search(dl, pgno);
5979 if (x <= dl[0].mid && dl[x].mid == pgno) {
5985 } while ((tx2 = tx2->mt_parent) != NULL);
5988 if (pgno < txn->mt_next_pgno) {
5992 int rc = mdb_rpage_get(txn, pgno, &p);
5997 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
6000 DPRINTF(("page %"Y"u not found", pgno));
6001 txn->mt_flags |= MDB_TXN_ERROR;
6002 return MDB_PAGE_NOTFOUND;
6012 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
6013 * The cursor is at the root page, set up the rest of it.
6016 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
6018 MDB_page *mp = mc->mc_pg[mc->mc_top];
6022 while (IS_BRANCH(mp)) {
6026 DPRINTF(("branch page %"Y"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
6027 /* Don't assert on branch pages in the FreeDB. We can get here
6028 * while in the process of rebalancing a FreeDB branch page; we must
6029 * let that proceed. ITS#8336
6031 mdb_cassert(mc, !mc->mc_dbi || NUMKEYS(mp) > 1);
6032 DPRINTF(("found index 0 to page %"Y"u", NODEPGNO(NODEPTR(mp, 0))));
6034 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
6036 if (flags & MDB_PS_LAST)
6037 i = NUMKEYS(mp) - 1;
6040 node = mdb_node_search(mc, key, &exact);
6042 i = NUMKEYS(mp) - 1;
6044 i = mc->mc_ki[mc->mc_top];
6046 mdb_cassert(mc, i > 0);
6050 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
6053 mdb_cassert(mc, i < NUMKEYS(mp));
6054 node = NODEPTR(mp, i);
6056 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
6059 mc->mc_ki[mc->mc_top] = i;
6060 if ((rc = mdb_cursor_push(mc, mp)))
6063 if (flags & MDB_PS_MODIFY) {
6064 if ((rc = mdb_page_touch(mc)) != 0)
6066 mp = mc->mc_pg[mc->mc_top];
6071 DPRINTF(("internal error, index points to a %02X page!?",
6073 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6074 return MDB_CORRUPTED;
6077 DPRINTF(("found leaf page %"Y"u for key [%s]", mp->mp_pgno,
6078 key ? DKEY(key) : "null"));
6079 mc->mc_flags |= C_INITIALIZED;
6080 mc->mc_flags &= ~C_EOF;
6085 /** Search for the lowest key under the current branch page.
6086 * This just bypasses a NUMKEYS check in the current page
6087 * before calling mdb_page_search_root(), because the callers
6088 * are all in situations where the current page is known to
6092 mdb_page_search_lowest(MDB_cursor *mc)
6094 MDB_page *mp = mc->mc_pg[mc->mc_top];
6095 MDB_node *node = NODEPTR(mp, 0);
6098 if ((rc = mdb_page_get(mc, NODEPGNO(node), &mp, NULL)) != 0)
6101 mc->mc_ki[mc->mc_top] = 0;
6102 if ((rc = mdb_cursor_push(mc, mp)))
6104 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
6107 /** Search for the page a given key should be in.
6108 * Push it and its parent pages on the cursor stack.
6109 * @param[in,out] mc the cursor for this operation.
6110 * @param[in] key the key to search for, or NULL for first/last page.
6111 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
6112 * are touched (updated with new page numbers).
6113 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
6114 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
6115 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
6116 * @return 0 on success, non-zero on failure.
6119 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
6124 /* Make sure the txn is still viable, then find the root from
6125 * the txn's db table and set it as the root of the cursor's stack.
6127 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED) {
6128 DPUTS("transaction may not be used now");
6131 /* Make sure we're using an up-to-date root */
6132 if (*mc->mc_dbflag & DB_STALE) {
6134 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
6136 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
6137 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
6144 MDB_node *leaf = mdb_node_search(&mc2,
6145 &mc->mc_dbx->md_name, &exact);
6147 return MDB_NOTFOUND;
6148 if ((leaf->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
6149 return MDB_INCOMPATIBLE; /* not a named DB */
6150 rc = mdb_node_read(&mc2, leaf, &data);
6153 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
6155 /* The txn may not know this DBI, or another process may
6156 * have dropped and recreated the DB with other flags.
6158 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
6159 return MDB_INCOMPATIBLE;
6160 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
6162 *mc->mc_dbflag &= ~DB_STALE;
6164 root = mc->mc_db->md_root;
6166 if (root == P_INVALID) { /* Tree is empty. */
6167 DPUTS("tree is empty");
6168 return MDB_NOTFOUND;
6172 mdb_cassert(mc, root > 1);
6173 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root) {
6176 MDB_PAGE_UNREF(mc->mc_txn, mc->mc_pg[0]);
6178 if ((rc = mdb_page_get(mc, root, &mc->mc_pg[0], NULL)) != 0)
6185 for (i=1; i<mc->mc_snum; i++)
6186 MDB_PAGE_UNREF(mc->mc_txn, mc->mc_pg[i]);
6192 DPRINTF(("db %d root page %"Y"u has flags 0x%X",
6193 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
6195 if (flags & MDB_PS_MODIFY) {
6196 if ((rc = mdb_page_touch(mc)))
6200 if (flags & MDB_PS_ROOTONLY)
6203 return mdb_page_search_root(mc, key, flags);
6207 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
6209 MDB_txn *txn = mc->mc_txn;
6210 pgno_t pg = mp->mp_pgno;
6211 unsigned x = 0, ovpages = mp->mp_pages;
6212 MDB_env *env = txn->mt_env;
6213 MDB_IDL sl = txn->mt_spill_pgs;
6214 MDB_ID pn = pg << 1;
6217 DPRINTF(("free ov page %"Y"u (%d)", pg, ovpages));
6218 /* If the page is dirty or on the spill list we just acquired it,
6219 * so we should give it back to our current free list, if any.
6220 * Otherwise put it onto the list of pages we freed in this txn.
6222 * Won't create me_pghead: me_pglast must be inited along with it.
6223 * Unsupported in nested txns: They would need to hide the page
6224 * range in ancestor txns' dirty and spilled lists.
6226 if (env->me_pghead &&
6228 ((mp->mp_flags & P_DIRTY) ||
6229 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
6233 MDB_ID2 *dl, ix, iy;
6234 rc = mdb_midl_need(&env->me_pghead, ovpages);
6237 if (!(mp->mp_flags & P_DIRTY)) {
6238 /* This page is no longer spilled */
6245 /* Remove from dirty list */
6246 dl = txn->mt_u.dirty_list;
6248 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
6254 mdb_cassert(mc, x > 1);
6256 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
6257 txn->mt_flags |= MDB_TXN_ERROR;
6258 return MDB_CORRUPTED;
6261 txn->mt_dirty_room++;
6262 if (!(env->me_flags & MDB_WRITEMAP))
6263 mdb_dpage_free(env, mp);
6265 /* Insert in me_pghead */
6266 mop = env->me_pghead;
6267 j = mop[0] + ovpages;
6268 for (i = mop[0]; i && mop[i] < pg; i--)
6274 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
6278 mc->mc_db->md_overflow_pages -= ovpages;
6282 /** Return the data associated with a given node.
6283 * @param[in] mc The cursor for this operation.
6284 * @param[in] leaf The node being read.
6285 * @param[out] data Updated to point to the node's data.
6286 * @return 0 on success, non-zero on failure.
6289 mdb_node_read(MDB_cursor *mc, MDB_node *leaf, MDB_val *data)
6291 MDB_page *omp; /* overflow page */
6297 MDB_PAGE_UNREF(mc->mc_txn, mc->mc_ovpg);
6301 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6302 data->mv_size = NODEDSZ(leaf);
6303 data->mv_data = NODEDATA(leaf);
6307 /* Read overflow data.
6309 data->mv_size = NODEDSZ(leaf);
6310 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
6311 if ((rc = mdb_page_get(mc, pgno, &omp, NULL)) != 0) {
6312 DPRINTF(("read overflow page %"Y"u failed", pgno));
6315 data->mv_data = METADATA(omp);
6324 mdb_get(MDB_txn *txn, MDB_dbi dbi,
6325 MDB_val *key, MDB_val *data)
6332 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
6334 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
6337 if (txn->mt_flags & MDB_TXN_BLOCKED)
6340 mdb_cursor_init(&mc, txn, dbi, &mx);
6341 rc = mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
6344 /* unref all the pages - caller must copy the data
6345 * before doing anything else
6347 mdb_cursor_unref(&mc);
6353 /** Find a sibling for a page.
6354 * Replaces the page at the top of the cursor's stack with the
6355 * specified sibling, if one exists.
6356 * @param[in] mc The cursor for this operation.
6357 * @param[in] move_right Non-zero if the right sibling is requested,
6358 * otherwise the left sibling.
6359 * @return 0 on success, non-zero on failure.
6362 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
6371 if (mc->mc_snum < 2) {
6372 return MDB_NOTFOUND; /* root has no siblings */
6376 op = mc->mc_pg[mc->mc_top];
6379 DPRINTF(("parent page is page %"Y"u, index %u",
6380 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
6382 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6383 : (mc->mc_ki[mc->mc_top] == 0)) {
6384 DPRINTF(("no more keys left, moving to %s sibling",
6385 move_right ? "right" : "left"));
6386 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
6387 /* undo cursor_pop before returning */
6394 mc->mc_ki[mc->mc_top]++;
6396 mc->mc_ki[mc->mc_top]--;
6397 DPRINTF(("just moving to %s index key %u",
6398 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
6400 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
6402 MDB_PAGE_UNREF(mc->mc_txn, op);
6404 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6405 if ((rc = mdb_page_get(mc, NODEPGNO(indx), &mp, NULL)) != 0) {
6406 /* mc will be inconsistent if caller does mc_snum++ as above */
6407 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
6411 mdb_cursor_push(mc, mp);
6413 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
6418 /** Move the cursor to the next data item. */
6420 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
6426 if (mc->mc_flags & C_EOF) {
6427 return MDB_NOTFOUND;
6430 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
6432 mp = mc->mc_pg[mc->mc_top];
6434 if (mc->mc_db->md_flags & MDB_DUPSORT) {
6435 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6436 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6437 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
6438 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
6439 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
6440 if (rc == MDB_SUCCESS)
6441 MDB_GET_KEY(leaf, key);
6447 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6448 mdb_cursor_unref(&mc->mc_xcursor->mx_cursor);
6453 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6454 if (op == MDB_NEXT_DUP)
6455 return MDB_NOTFOUND;
6459 DPRINTF(("cursor_next: top page is %"Y"u in cursor %p",
6460 mdb_dbg_pgno(mp), (void *) mc));
6461 if (mc->mc_flags & C_DEL) {
6462 mc->mc_flags ^= C_DEL;
6466 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
6467 DPUTS("=====> move to next sibling page");
6468 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
6469 mc->mc_flags |= C_EOF;
6472 mp = mc->mc_pg[mc->mc_top];
6473 DPRINTF(("next page is %"Y"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
6475 mc->mc_ki[mc->mc_top]++;
6478 DPRINTF(("==> cursor points to page %"Y"u with %u keys, key index %u",
6479 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
6482 key->mv_size = mc->mc_db->md_pad;
6483 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6487 mdb_cassert(mc, IS_LEAF(mp));
6488 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6490 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6491 mdb_xcursor_init1(mc, leaf);
6494 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6497 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6498 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6499 if (rc != MDB_SUCCESS)
6504 MDB_GET_KEY(leaf, key);
6508 /** Move the cursor to the previous data item. */
6510 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
6516 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
6518 mp = mc->mc_pg[mc->mc_top];
6520 if (mc->mc_db->md_flags & MDB_DUPSORT) {
6521 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6522 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6523 if (op == MDB_PREV || op == MDB_PREV_DUP) {
6524 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
6525 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
6526 if (rc == MDB_SUCCESS) {
6527 MDB_GET_KEY(leaf, key);
6528 mc->mc_flags &= ~C_EOF;
6535 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6536 mdb_cursor_unref(&mc->mc_xcursor->mx_cursor);
6541 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6542 if (op == MDB_PREV_DUP)
6543 return MDB_NOTFOUND;
6547 DPRINTF(("cursor_prev: top page is %"Y"u in cursor %p",
6548 mdb_dbg_pgno(mp), (void *) mc));
6550 mc->mc_flags &= ~(C_EOF|C_DEL);
6552 if (mc->mc_ki[mc->mc_top] == 0) {
6553 DPUTS("=====> move to prev sibling page");
6554 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
6557 mp = mc->mc_pg[mc->mc_top];
6558 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
6559 DPRINTF(("prev page is %"Y"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
6561 mc->mc_ki[mc->mc_top]--;
6563 mc->mc_flags &= ~C_EOF;
6565 DPRINTF(("==> cursor points to page %"Y"u with %u keys, key index %u",
6566 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
6569 key->mv_size = mc->mc_db->md_pad;
6570 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6574 mdb_cassert(mc, IS_LEAF(mp));
6575 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6577 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6578 mdb_xcursor_init1(mc, leaf);
6581 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6584 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6585 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
6586 if (rc != MDB_SUCCESS)
6591 MDB_GET_KEY(leaf, key);
6595 /** Set the cursor on a specific data item. */
6597 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6598 MDB_cursor_op op, int *exactp)
6602 MDB_node *leaf = NULL;
6605 if (key->mv_size == 0)
6606 return MDB_BAD_VALSIZE;
6609 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6611 /* See if we're already on the right page */
6612 if (mc->mc_flags & C_INITIALIZED) {
6615 mp = mc->mc_pg[mc->mc_top];
6617 mc->mc_ki[mc->mc_top] = 0;
6618 return MDB_NOTFOUND;
6620 if (mp->mp_flags & P_LEAF2) {
6621 nodekey.mv_size = mc->mc_db->md_pad;
6622 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
6624 leaf = NODEPTR(mp, 0);
6625 MDB_GET_KEY2(leaf, nodekey);
6627 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6629 /* Probably happens rarely, but first node on the page
6630 * was the one we wanted.
6632 mc->mc_ki[mc->mc_top] = 0;
6639 unsigned int nkeys = NUMKEYS(mp);
6641 if (mp->mp_flags & P_LEAF2) {
6642 nodekey.mv_data = LEAF2KEY(mp,
6643 nkeys-1, nodekey.mv_size);
6645 leaf = NODEPTR(mp, nkeys-1);
6646 MDB_GET_KEY2(leaf, nodekey);
6648 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6650 /* last node was the one we wanted */
6651 mc->mc_ki[mc->mc_top] = nkeys-1;
6657 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
6658 /* This is definitely the right page, skip search_page */
6659 if (mp->mp_flags & P_LEAF2) {
6660 nodekey.mv_data = LEAF2KEY(mp,
6661 mc->mc_ki[mc->mc_top], nodekey.mv_size);
6663 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6664 MDB_GET_KEY2(leaf, nodekey);
6666 rc = mc->mc_dbx->md_cmp(key, &nodekey);
6668 /* current node was the one we wanted */
6678 /* If any parents have right-sibs, search.
6679 * Otherwise, there's nothing further.
6681 for (i=0; i<mc->mc_top; i++)
6683 NUMKEYS(mc->mc_pg[i])-1)
6685 if (i == mc->mc_top) {
6686 /* There are no other pages */
6687 mc->mc_ki[mc->mc_top] = nkeys;
6688 return MDB_NOTFOUND;
6692 /* There are no other pages */
6693 mc->mc_ki[mc->mc_top] = 0;
6694 if (op == MDB_SET_RANGE && !exactp) {
6698 return MDB_NOTFOUND;
6704 rc = mdb_page_search(mc, key, 0);
6705 if (rc != MDB_SUCCESS)
6708 mp = mc->mc_pg[mc->mc_top];
6709 mdb_cassert(mc, IS_LEAF(mp));
6712 leaf = mdb_node_search(mc, key, exactp);
6713 if (exactp != NULL && !*exactp) {
6714 /* MDB_SET specified and not an exact match. */
6715 return MDB_NOTFOUND;
6719 DPUTS("===> inexact leaf not found, goto sibling");
6720 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
6721 mc->mc_flags |= C_EOF;
6722 return rc; /* no entries matched */
6724 mp = mc->mc_pg[mc->mc_top];
6725 mdb_cassert(mc, IS_LEAF(mp));
6726 leaf = NODEPTR(mp, 0);
6730 mc->mc_flags |= C_INITIALIZED;
6731 mc->mc_flags &= ~C_EOF;
6734 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
6735 key->mv_size = mc->mc_db->md_pad;
6736 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6742 if (mc->mc_xcursor && mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6743 mdb_cursor_unref(&mc->mc_xcursor->mx_cursor);
6746 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6747 mdb_xcursor_init1(mc, leaf);
6750 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6751 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
6752 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6755 if (op == MDB_GET_BOTH) {
6761 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
6762 if (rc != MDB_SUCCESS)
6765 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
6768 if ((rc = mdb_node_read(mc, leaf, &olddata)) != MDB_SUCCESS)
6770 dcmp = mc->mc_dbx->md_dcmp;
6771 #if UINT_MAX < SIZE_MAX || defined(MDB_VL32)
6772 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(mdb_size_t))
6773 dcmp = mdb_cmp_clong;
6775 rc = dcmp(data, &olddata);
6777 if (op == MDB_GET_BOTH || rc > 0)
6778 return MDB_NOTFOUND;
6785 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6786 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6791 /* The key already matches in all other cases */
6792 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
6793 MDB_GET_KEY(leaf, key);
6794 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
6799 /** Move the cursor to the first item in the database. */
6801 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6806 if (mc->mc_xcursor) {
6808 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6809 mdb_cursor_unref(&mc->mc_xcursor->mx_cursor);
6812 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6815 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6816 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
6817 if (rc != MDB_SUCCESS)
6820 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6822 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
6823 mc->mc_flags |= C_INITIALIZED;
6824 mc->mc_flags &= ~C_EOF;
6826 mc->mc_ki[mc->mc_top] = 0;
6828 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6829 key->mv_size = mc->mc_db->md_pad;
6830 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
6835 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6836 mdb_xcursor_init1(mc, leaf);
6837 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
6841 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6845 MDB_GET_KEY(leaf, key);
6849 /** Move the cursor to the last item in the database. */
6851 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
6856 if (mc->mc_xcursor) {
6858 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6859 mdb_cursor_unref(&mc->mc_xcursor->mx_cursor);
6862 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
6865 if (!(mc->mc_flags & C_EOF)) {
6867 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
6868 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
6869 if (rc != MDB_SUCCESS)
6872 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
6875 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
6876 mc->mc_flags |= C_INITIALIZED|C_EOF;
6877 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6879 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6880 key->mv_size = mc->mc_db->md_pad;
6881 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
6886 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6887 mdb_xcursor_init1(mc, leaf);
6888 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
6892 if ((rc = mdb_node_read(mc, leaf, data)) != MDB_SUCCESS)
6897 MDB_GET_KEY(leaf, key);
6902 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
6907 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
6912 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
6916 case MDB_GET_CURRENT:
6917 if (!(mc->mc_flags & C_INITIALIZED)) {
6920 MDB_page *mp = mc->mc_pg[mc->mc_top];
6921 int nkeys = NUMKEYS(mp);
6922 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
6923 mc->mc_ki[mc->mc_top] = nkeys;
6929 key->mv_size = mc->mc_db->md_pad;
6930 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
6932 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6933 MDB_GET_KEY(leaf, key);
6935 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6936 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
6938 rc = mdb_node_read(mc, leaf, data);
6945 case MDB_GET_BOTH_RANGE:
6950 if (mc->mc_xcursor == NULL) {
6951 rc = MDB_INCOMPATIBLE;
6961 rc = mdb_cursor_set(mc, key, data, op,
6962 op == MDB_SET_RANGE ? NULL : &exact);
6965 case MDB_GET_MULTIPLE:
6966 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
6970 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6971 rc = MDB_INCOMPATIBLE;
6975 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
6976 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
6979 case MDB_NEXT_MULTIPLE:
6984 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6985 rc = MDB_INCOMPATIBLE;
6988 if (!(mc->mc_flags & C_INITIALIZED))
6989 rc = mdb_cursor_first(mc, key, data);
6991 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
6992 if (rc == MDB_SUCCESS) {
6993 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
6996 mx = &mc->mc_xcursor->mx_cursor;
6997 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
6999 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
7000 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
7006 case MDB_PREV_MULTIPLE:
7011 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7012 rc = MDB_INCOMPATIBLE;
7015 if (!(mc->mc_flags & C_INITIALIZED))
7016 rc = mdb_cursor_first(mc, key, data);
7018 MDB_cursor *mx = &mc->mc_xcursor->mx_cursor;
7019 if (mx->mc_flags & C_INITIALIZED) {
7020 rc = mdb_cursor_sibling(mx, 0);
7021 if (rc == MDB_SUCCESS)
7030 case MDB_NEXT_NODUP:
7031 if (!(mc->mc_flags & C_INITIALIZED))
7032 rc = mdb_cursor_first(mc, key, data);
7034 rc = mdb_cursor_next(mc, key, data, op);
7038 case MDB_PREV_NODUP:
7039 if (!(mc->mc_flags & C_INITIALIZED)) {
7040 rc = mdb_cursor_last(mc, key, data);
7043 mc->mc_flags |= C_INITIALIZED;
7044 mc->mc_ki[mc->mc_top]++;
7046 rc = mdb_cursor_prev(mc, key, data, op);
7049 rc = mdb_cursor_first(mc, key, data);
7052 mfunc = mdb_cursor_first;
7054 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
7058 if (mc->mc_xcursor == NULL) {
7059 rc = MDB_INCOMPATIBLE;
7063 MDB_node *leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7064 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7065 MDB_GET_KEY(leaf, key);
7066 rc = mdb_node_read(mc, leaf, data);
7070 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
7074 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
7077 rc = mdb_cursor_last(mc, key, data);
7080 mfunc = mdb_cursor_last;
7083 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
7088 if (mc->mc_flags & C_DEL)
7089 mc->mc_flags ^= C_DEL;
7094 /** Touch all the pages in the cursor stack. Set mc_top.
7095 * Makes sure all the pages are writable, before attempting a write operation.
7096 * @param[in] mc The cursor to operate on.
7099 mdb_cursor_touch(MDB_cursor *mc)
7101 int rc = MDB_SUCCESS;
7103 if (mc->mc_dbi >= CORE_DBS && !(*mc->mc_dbflag & DB_DIRTY)) {
7106 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
7108 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
7109 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
7112 *mc->mc_dbflag |= DB_DIRTY;
7117 rc = mdb_page_touch(mc);
7118 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
7119 mc->mc_top = mc->mc_snum-1;
7124 /** Do not spill pages to disk if txn is getting full, may fail instead */
7125 #define MDB_NOSPILL 0x8000
7128 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
7132 MDB_node *leaf = NULL;
7133 MDB_page *fp, *mp, *sub_root = NULL;
7135 MDB_val xdata, *rdata, dkey, olddata;
7137 int do_sub = 0, insert_key, insert_data;
7138 unsigned int mcount = 0, dcount = 0, nospill;
7141 unsigned int nflags;
7144 if (mc == NULL || key == NULL)
7147 env = mc->mc_txn->mt_env;
7149 /* Check this first so counter will always be zero on any
7152 if (flags & MDB_MULTIPLE) {
7153 dcount = data[1].mv_size;
7154 data[1].mv_size = 0;
7155 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
7156 return MDB_INCOMPATIBLE;
7159 nospill = flags & MDB_NOSPILL;
7160 flags &= ~MDB_NOSPILL;
7162 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
7163 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7165 if (key->mv_size-1 >= ENV_MAXKEY(env))
7166 return MDB_BAD_VALSIZE;
7168 #if SIZE_MAX > MAXDATASIZE
7169 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
7170 return MDB_BAD_VALSIZE;
7172 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
7173 return MDB_BAD_VALSIZE;
7176 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
7177 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
7181 if (flags == MDB_CURRENT) {
7182 if (!(mc->mc_flags & C_INITIALIZED))
7185 } else if (mc->mc_db->md_root == P_INVALID) {
7186 /* new database, cursor has nothing to point to */
7189 mc->mc_flags &= ~C_INITIALIZED;
7194 if (flags & MDB_APPEND) {
7196 rc = mdb_cursor_last(mc, &k2, &d2);
7198 rc = mc->mc_dbx->md_cmp(key, &k2);
7201 mc->mc_ki[mc->mc_top]++;
7203 /* new key is <= last key */
7208 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
7210 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
7211 DPRINTF(("duplicate key [%s]", DKEY(key)));
7213 return MDB_KEYEXIST;
7215 if (rc && rc != MDB_NOTFOUND)
7219 if (mc->mc_flags & C_DEL)
7220 mc->mc_flags ^= C_DEL;
7222 /* Cursor is positioned, check for room in the dirty list */
7224 if (flags & MDB_MULTIPLE) {
7226 xdata.mv_size = data->mv_size * dcount;
7230 if ((rc2 = mdb_page_spill(mc, key, rdata)))
7234 if (rc == MDB_NO_ROOT) {
7236 /* new database, write a root leaf page */
7237 DPUTS("allocating new root leaf page");
7238 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
7241 mdb_cursor_push(mc, np);
7242 mc->mc_db->md_root = np->mp_pgno;
7243 mc->mc_db->md_depth++;
7244 *mc->mc_dbflag |= DB_DIRTY;
7245 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
7247 np->mp_flags |= P_LEAF2;
7248 mc->mc_flags |= C_INITIALIZED;
7250 /* make sure all cursor pages are writable */
7251 rc2 = mdb_cursor_touch(mc);
7256 insert_key = insert_data = rc;
7258 /* The key does not exist */
7259 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
7260 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
7261 LEAFSIZE(key, data) > env->me_nodemax)
7263 /* Too big for a node, insert in sub-DB. Set up an empty
7264 * "old sub-page" for prep_subDB to expand to a full page.
7266 fp_flags = P_LEAF|P_DIRTY;
7268 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
7269 fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
7270 olddata.mv_size = PAGEHDRSZ;
7274 /* there's only a key anyway, so this is a no-op */
7275 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
7277 unsigned int ksize = mc->mc_db->md_pad;
7278 if (key->mv_size != ksize)
7279 return MDB_BAD_VALSIZE;
7280 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
7281 memcpy(ptr, key->mv_data, ksize);
7283 /* if overwriting slot 0 of leaf, need to
7284 * update branch key if there is a parent page
7286 if (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
7287 unsigned short dtop = 1;
7289 /* slot 0 is always an empty key, find real slot */
7290 while (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
7294 if (mc->mc_ki[mc->mc_top])
7295 rc2 = mdb_update_key(mc, key);
7306 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7307 olddata.mv_size = NODEDSZ(leaf);
7308 olddata.mv_data = NODEDATA(leaf);
7311 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
7312 /* Prepare (sub-)page/sub-DB to accept the new item,
7313 * if needed. fp: old sub-page or a header faking
7314 * it. mp: new (sub-)page. offset: growth in page
7315 * size. xdata: node data with new page or DB.
7317 unsigned i, offset = 0;
7318 mp = fp = xdata.mv_data = env->me_pbuf;
7319 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
7321 /* Was a single item before, must convert now */
7322 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7324 /* Just overwrite the current item */
7325 if (flags == MDB_CURRENT)
7327 dcmp = mc->mc_dbx->md_dcmp;
7328 #if UINT_MAX < SIZE_MAX || defined(MDB_VL32)
7329 if (dcmp == mdb_cmp_int && olddata.mv_size == sizeof(mdb_size_t))
7330 dcmp = mdb_cmp_clong;
7332 /* does data match? */
7333 if (!dcmp(data, &olddata)) {
7334 if (flags & (MDB_NODUPDATA|MDB_APPENDDUP))
7335 return MDB_KEYEXIST;
7340 /* Back up original data item */
7341 dkey.mv_size = olddata.mv_size;
7342 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
7344 /* Make sub-page header for the dup items, with dummy body */
7345 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
7346 fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
7347 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
7348 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7349 fp->mp_flags |= P_LEAF2;
7350 fp->mp_pad = data->mv_size;
7351 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
7353 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
7354 (dkey.mv_size & 1) + (data->mv_size & 1);
7356 fp->mp_upper = xdata.mv_size - PAGEBASE;
7357 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
7358 } else if (leaf->mn_flags & F_SUBDATA) {
7359 /* Data is on sub-DB, just store it */
7360 flags |= F_DUPDATA|F_SUBDATA;
7363 /* Data is on sub-page */
7364 fp = olddata.mv_data;
7367 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
7368 offset = EVEN(NODESIZE + sizeof(indx_t) +
7372 offset = fp->mp_pad;
7373 if (SIZELEFT(fp) < offset) {
7374 offset *= 4; /* space for 4 more */
7377 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
7379 fp->mp_flags |= P_DIRTY;
7380 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
7381 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
7385 xdata.mv_size = olddata.mv_size + offset;
7388 fp_flags = fp->mp_flags;
7389 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
7390 /* Too big for a sub-page, convert to sub-DB */
7391 fp_flags &= ~P_SUBP;
7393 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
7394 fp_flags |= P_LEAF2;
7395 dummy.md_pad = fp->mp_pad;
7396 dummy.md_flags = MDB_DUPFIXED;
7397 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
7398 dummy.md_flags |= MDB_INTEGERKEY;
7404 dummy.md_branch_pages = 0;
7405 dummy.md_leaf_pages = 1;
7406 dummy.md_overflow_pages = 0;
7407 dummy.md_entries = NUMKEYS(fp);
7408 xdata.mv_size = sizeof(MDB_db);
7409 xdata.mv_data = &dummy;
7410 if ((rc = mdb_page_alloc(mc, 1, &mp)))
7412 offset = env->me_psize - olddata.mv_size;
7413 flags |= F_DUPDATA|F_SUBDATA;
7414 dummy.md_root = mp->mp_pgno;
7418 mp->mp_flags = fp_flags | P_DIRTY;
7419 mp->mp_pad = fp->mp_pad;
7420 mp->mp_lower = fp->mp_lower;
7421 mp->mp_upper = fp->mp_upper + offset;
7422 if (fp_flags & P_LEAF2) {
7423 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
7425 memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
7426 olddata.mv_size - fp->mp_upper - PAGEBASE);
7427 for (i=0; i<NUMKEYS(fp); i++)
7428 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
7436 mdb_node_del(mc, 0);
7440 /* LMDB passes F_SUBDATA in 'flags' to write a DB record */
7441 if ((leaf->mn_flags ^ flags) & F_SUBDATA)
7442 return MDB_INCOMPATIBLE;
7443 /* overflow page overwrites need special handling */
7444 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7447 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
7449 memcpy(&pg, olddata.mv_data, sizeof(pg));
7450 if ((rc2 = mdb_page_get(mc, pg, &omp, &level)) != 0)
7452 ovpages = omp->mp_pages;
7454 /* Is the ov page large enough? */
7455 if (ovpages >= dpages) {
7456 if (!(omp->mp_flags & P_DIRTY) &&
7457 (level || (env->me_flags & MDB_WRITEMAP)))
7459 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
7462 level = 0; /* dirty in this txn or clean */
7465 if (omp->mp_flags & P_DIRTY) {
7466 /* yes, overwrite it. Note in this case we don't
7467 * bother to try shrinking the page if the new data
7468 * is smaller than the overflow threshold.
7471 /* It is writable only in a parent txn */
7472 size_t sz = (size_t) env->me_psize * ovpages, off;
7473 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
7479 /* Note - this page is already counted in parent's dirty_room */
7480 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
7481 mdb_cassert(mc, rc2 == 0);
7482 if (!(flags & MDB_RESERVE)) {
7483 /* Copy end of page, adjusting alignment so
7484 * compiler may copy words instead of bytes.
7486 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
7487 memcpy((size_t *)((char *)np + off),
7488 (size_t *)((char *)omp + off), sz - off);
7491 memcpy(np, omp, sz); /* Copy beginning of page */
7494 SETDSZ(leaf, data->mv_size);
7495 if (F_ISSET(flags, MDB_RESERVE))
7496 data->mv_data = METADATA(omp);
7498 memcpy(METADATA(omp), data->mv_data, data->mv_size);
7502 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
7504 } else if (data->mv_size == olddata.mv_size) {
7505 /* same size, just replace it. Note that we could
7506 * also reuse this node if the new data is smaller,
7507 * but instead we opt to shrink the node in that case.
7509 if (F_ISSET(flags, MDB_RESERVE))
7510 data->mv_data = olddata.mv_data;
7511 else if (!(mc->mc_flags & C_SUB))
7512 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
7514 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
7519 mdb_node_del(mc, 0);
7525 nflags = flags & NODE_ADD_FLAGS;
7526 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
7527 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
7528 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
7529 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
7531 nflags |= MDB_SPLIT_REPLACE;
7532 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
7534 /* There is room already in this leaf page. */
7535 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
7537 /* Adjust other cursors pointing to mp */
7538 MDB_cursor *m2, *m3;
7539 MDB_dbi dbi = mc->mc_dbi;
7540 unsigned i = mc->mc_top;
7541 MDB_page *mp = mc->mc_pg[i];
7543 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7544 if (mc->mc_flags & C_SUB)
7545 m3 = &m2->mc_xcursor->mx_cursor;
7548 if (m3 == mc || m3->mc_snum < mc->mc_snum || m3->mc_pg[i] != mp) continue;
7549 if (m3->mc_ki[i] >= mc->mc_ki[i] && insert_key) {
7552 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
7553 MDB_node *n2 = NODEPTR(mp, m3->mc_ki[i]);
7554 if ((n2->mn_flags & (F_SUBDATA|F_DUPDATA)) == F_DUPDATA)
7555 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
7561 if (rc == MDB_SUCCESS) {
7562 /* Now store the actual data in the child DB. Note that we're
7563 * storing the user data in the keys field, so there are strict
7564 * size limits on dupdata. The actual data fields of the child
7565 * DB are all zero size.
7568 int xflags, new_dupdata;
7573 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7574 if (flags & MDB_CURRENT) {
7575 xflags = MDB_CURRENT|MDB_NOSPILL;
7577 mdb_xcursor_init1(mc, leaf);
7578 xflags = (flags & MDB_NODUPDATA) ?
7579 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
7582 mc->mc_xcursor->mx_cursor.mc_pg[0] = sub_root;
7583 new_dupdata = (int)dkey.mv_size;
7584 /* converted, write the original data first */
7586 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
7589 /* we've done our job */
7592 if (!(leaf->mn_flags & F_SUBDATA) || sub_root) {
7593 /* Adjust other cursors pointing to mp */
7595 MDB_xcursor *mx = mc->mc_xcursor;
7596 unsigned i = mc->mc_top;
7597 MDB_page *mp = mc->mc_pg[i];
7598 int nkeys = NUMKEYS(mp);
7600 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
7601 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
7602 if (!(m2->mc_flags & C_INITIALIZED)) continue;
7603 if (m2->mc_pg[i] == mp) {
7604 if (m2->mc_ki[i] == mc->mc_ki[i]) {
7605 mdb_xcursor_init2(m2, mx, new_dupdata);
7606 } else if (!insert_key && m2->mc_ki[i] < nkeys) {
7607 MDB_node *n2 = NODEPTR(mp, m2->mc_ki[i]);
7608 if ((n2->mn_flags & (F_SUBDATA|F_DUPDATA)) == F_DUPDATA)
7609 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
7614 ecount = mc->mc_xcursor->mx_db.md_entries;
7615 if (flags & MDB_APPENDDUP)
7616 xflags |= MDB_APPEND;
7617 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
7618 if (flags & F_SUBDATA) {
7619 void *db = NODEDATA(leaf);
7620 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
7622 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
7624 /* Increment count unless we just replaced an existing item. */
7626 mc->mc_db->md_entries++;
7628 /* Invalidate txn if we created an empty sub-DB */
7631 /* If we succeeded and the key didn't exist before,
7632 * make sure the cursor is marked valid.
7634 mc->mc_flags |= C_INITIALIZED;
7636 if (flags & MDB_MULTIPLE) {
7639 /* let caller know how many succeeded, if any */
7640 data[1].mv_size = mcount;
7641 if (mcount < dcount) {
7642 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
7643 insert_key = insert_data = 0;
7650 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
7653 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7658 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
7664 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
7665 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7667 if (!(mc->mc_flags & C_INITIALIZED))
7670 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
7671 return MDB_NOTFOUND;
7673 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
7676 rc = mdb_cursor_touch(mc);
7680 mp = mc->mc_pg[mc->mc_top];
7683 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7685 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7686 if (flags & MDB_NODUPDATA) {
7687 /* mdb_cursor_del0() will subtract the final entry */
7688 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
7689 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
7691 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
7692 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
7694 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
7697 /* If sub-DB still has entries, we're done */
7698 if (mc->mc_xcursor->mx_db.md_entries) {
7699 if (leaf->mn_flags & F_SUBDATA) {
7700 /* update subDB info */
7701 void *db = NODEDATA(leaf);
7702 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
7705 /* shrink fake page */
7706 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
7707 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7708 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
7709 /* fix other sub-DB cursors pointed at fake pages on this page */
7710 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
7711 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
7712 if (!(m2->mc_flags & C_INITIALIZED)) continue;
7713 if (m2->mc_pg[mc->mc_top] == mp) {
7714 if (m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top]) {
7715 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
7717 MDB_node *n2 = NODEPTR(mp, m2->mc_ki[mc->mc_top]);
7718 if (!(n2->mn_flags & F_SUBDATA))
7719 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(n2);
7724 mc->mc_db->md_entries--;
7727 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
7729 /* otherwise fall thru and delete the sub-DB */
7732 if (leaf->mn_flags & F_SUBDATA) {
7733 /* add all the child DB's pages to the free list */
7734 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
7739 /* LMDB passes F_SUBDATA in 'flags' to delete a DB record */
7740 else if ((leaf->mn_flags ^ flags) & F_SUBDATA) {
7741 rc = MDB_INCOMPATIBLE;
7745 /* add overflow pages to free list */
7746 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7750 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
7751 if ((rc = mdb_page_get(mc, pg, &omp, NULL)) ||
7752 (rc = mdb_ovpage_free(mc, omp)))
7757 return mdb_cursor_del0(mc);
7760 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7764 /** Allocate and initialize new pages for a database.
7765 * @param[in] mc a cursor on the database being added to.
7766 * @param[in] flags flags defining what type of page is being allocated.
7767 * @param[in] num the number of pages to allocate. This is usually 1,
7768 * unless allocating overflow pages for a large record.
7769 * @param[out] mp Address of a page, or NULL on failure.
7770 * @return 0 on success, non-zero on failure.
7773 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
7778 if ((rc = mdb_page_alloc(mc, num, &np)))
7780 DPRINTF(("allocated new mpage %"Y"u, page size %u",
7781 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
7782 np->mp_flags = flags | P_DIRTY;
7783 np->mp_lower = (PAGEHDRSZ-PAGEBASE);
7784 np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
7787 mc->mc_db->md_branch_pages++;
7788 else if (IS_LEAF(np))
7789 mc->mc_db->md_leaf_pages++;
7790 else if (IS_OVERFLOW(np)) {
7791 mc->mc_db->md_overflow_pages += num;
7799 /** Calculate the size of a leaf node.
7800 * The size depends on the environment's page size; if a data item
7801 * is too large it will be put onto an overflow page and the node
7802 * size will only include the key and not the data. Sizes are always
7803 * rounded up to an even number of bytes, to guarantee 2-byte alignment
7804 * of the #MDB_node headers.
7805 * @param[in] env The environment handle.
7806 * @param[in] key The key for the node.
7807 * @param[in] data The data for the node.
7808 * @return The number of bytes needed to store the node.
7811 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
7815 sz = LEAFSIZE(key, data);
7816 if (sz > env->me_nodemax) {
7817 /* put on overflow page */
7818 sz -= data->mv_size - sizeof(pgno_t);
7821 return EVEN(sz + sizeof(indx_t));
7824 /** Calculate the size of a branch node.
7825 * The size should depend on the environment's page size but since
7826 * we currently don't support spilling large keys onto overflow
7827 * pages, it's simply the size of the #MDB_node header plus the
7828 * size of the key. Sizes are always rounded up to an even number
7829 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
7830 * @param[in] env The environment handle.
7831 * @param[in] key The key for the node.
7832 * @return The number of bytes needed to store the node.
7835 mdb_branch_size(MDB_env *env, MDB_val *key)
7840 if (sz > env->me_nodemax) {
7841 /* put on overflow page */
7842 /* not implemented */
7843 /* sz -= key->size - sizeof(pgno_t); */
7846 return sz + sizeof(indx_t);
7849 /** Add a node to the page pointed to by the cursor.
7850 * @param[in] mc The cursor for this operation.
7851 * @param[in] indx The index on the page where the new node should be added.
7852 * @param[in] key The key for the new node.
7853 * @param[in] data The data for the new node, if any.
7854 * @param[in] pgno The page number, if adding a branch node.
7855 * @param[in] flags Flags for the node.
7856 * @return 0 on success, non-zero on failure. Possible errors are:
7858 * <li>ENOMEM - failed to allocate overflow pages for the node.
7859 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
7860 * should never happen since all callers already calculate the
7861 * page's free space before calling this function.
7865 mdb_node_add(MDB_cursor *mc, indx_t indx,
7866 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
7869 size_t node_size = NODESIZE;
7873 MDB_page *mp = mc->mc_pg[mc->mc_top];
7874 MDB_page *ofp = NULL; /* overflow page */
7878 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
7880 DPRINTF(("add to %s %spage %"Y"u index %i, data size %"Z"u key size %"Z"u [%s]",
7881 IS_LEAF(mp) ? "leaf" : "branch",
7882 IS_SUBP(mp) ? "sub-" : "",
7883 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
7884 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
7887 /* Move higher keys up one slot. */
7888 int ksize = mc->mc_db->md_pad, dif;
7889 char *ptr = LEAF2KEY(mp, indx, ksize);
7890 dif = NUMKEYS(mp) - indx;
7892 memmove(ptr+ksize, ptr, dif*ksize);
7893 /* insert new key */
7894 memcpy(ptr, key->mv_data, ksize);
7896 /* Just using these for counting */
7897 mp->mp_lower += sizeof(indx_t);
7898 mp->mp_upper -= ksize - sizeof(indx_t);
7902 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
7904 node_size += key->mv_size;
7906 mdb_cassert(mc, key && data);
7907 if (F_ISSET(flags, F_BIGDATA)) {
7908 /* Data already on overflow page. */
7909 node_size += sizeof(pgno_t);
7910 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
7911 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
7913 /* Put data on overflow page. */
7914 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
7915 data->mv_size, node_size+data->mv_size));
7916 node_size = EVEN(node_size + sizeof(pgno_t));
7917 if ((ssize_t)node_size > room)
7919 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
7921 DPRINTF(("allocated overflow page %"Y"u", ofp->mp_pgno));
7925 node_size += data->mv_size;
7928 node_size = EVEN(node_size);
7929 if ((ssize_t)node_size > room)
7933 /* Move higher pointers up one slot. */
7934 for (i = NUMKEYS(mp); i > indx; i--)
7935 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
7937 /* Adjust free space offsets. */
7938 ofs = mp->mp_upper - node_size;
7939 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
7940 mp->mp_ptrs[indx] = ofs;
7942 mp->mp_lower += sizeof(indx_t);
7944 /* Write the node data. */
7945 node = NODEPTR(mp, indx);
7946 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
7947 node->mn_flags = flags;
7949 SETDSZ(node,data->mv_size);
7954 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7957 ndata = NODEDATA(node);
7959 if (F_ISSET(flags, F_BIGDATA))
7960 memcpy(ndata, data->mv_data, sizeof(pgno_t));
7961 else if (F_ISSET(flags, MDB_RESERVE))
7962 data->mv_data = ndata;
7964 memcpy(ndata, data->mv_data, data->mv_size);
7966 memcpy(ndata, &ofp->mp_pgno, sizeof(pgno_t));
7967 ndata = METADATA(ofp);
7968 if (F_ISSET(flags, MDB_RESERVE))
7969 data->mv_data = ndata;
7971 memcpy(ndata, data->mv_data, data->mv_size);
7978 DPRINTF(("not enough room in page %"Y"u, got %u ptrs",
7979 mdb_dbg_pgno(mp), NUMKEYS(mp)));
7980 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
7981 DPRINTF(("node size = %"Z"u", node_size));
7982 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7983 return MDB_PAGE_FULL;
7986 /** Delete the specified node from a page.
7987 * @param[in] mc Cursor pointing to the node to delete.
7988 * @param[in] ksize The size of a node. Only used if the page is
7989 * part of a #MDB_DUPFIXED database.
7992 mdb_node_del(MDB_cursor *mc, int ksize)
7994 MDB_page *mp = mc->mc_pg[mc->mc_top];
7995 indx_t indx = mc->mc_ki[mc->mc_top];
7997 indx_t i, j, numkeys, ptr;
8001 DPRINTF(("delete node %u on %s page %"Y"u", indx,
8002 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
8003 numkeys = NUMKEYS(mp);
8004 mdb_cassert(mc, indx < numkeys);
8007 int x = numkeys - 1 - indx;
8008 base = LEAF2KEY(mp, indx, ksize);
8010 memmove(base, base + ksize, x * ksize);
8011 mp->mp_lower -= sizeof(indx_t);
8012 mp->mp_upper += ksize - sizeof(indx_t);
8016 node = NODEPTR(mp, indx);
8017 sz = NODESIZE + node->mn_ksize;
8019 if (F_ISSET(node->mn_flags, F_BIGDATA))
8020 sz += sizeof(pgno_t);
8022 sz += NODEDSZ(node);
8026 ptr = mp->mp_ptrs[indx];
8027 for (i = j = 0; i < numkeys; i++) {
8029 mp->mp_ptrs[j] = mp->mp_ptrs[i];
8030 if (mp->mp_ptrs[i] < ptr)
8031 mp->mp_ptrs[j] += sz;
8036 base = (char *)mp + mp->mp_upper + PAGEBASE;
8037 memmove(base + sz, base, ptr - mp->mp_upper);
8039 mp->mp_lower -= sizeof(indx_t);
8043 /** Compact the main page after deleting a node on a subpage.
8044 * @param[in] mp The main page to operate on.
8045 * @param[in] indx The index of the subpage on the main page.
8048 mdb_node_shrink(MDB_page *mp, indx_t indx)
8053 indx_t delta, nsize, len, ptr;
8056 node = NODEPTR(mp, indx);
8057 sp = (MDB_page *)NODEDATA(node);
8058 delta = SIZELEFT(sp);
8059 nsize = NODEDSZ(node) - delta;
8061 /* Prepare to shift upward, set len = length(subpage part to shift) */
8065 return; /* do not make the node uneven-sized */
8067 xp = (MDB_page *)((char *)sp + delta); /* destination subpage */
8068 for (i = NUMKEYS(sp); --i >= 0; )
8069 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
8072 sp->mp_upper = sp->mp_lower;
8073 COPY_PGNO(sp->mp_pgno, mp->mp_pgno);
8074 SETDSZ(node, nsize);
8076 /* Shift <lower nodes...initial part of subpage> upward */
8077 base = (char *)mp + mp->mp_upper + PAGEBASE;
8078 memmove(base + delta, base, (char *)sp + len - base);
8080 ptr = mp->mp_ptrs[indx];
8081 for (i = NUMKEYS(mp); --i >= 0; ) {
8082 if (mp->mp_ptrs[i] <= ptr)
8083 mp->mp_ptrs[i] += delta;
8085 mp->mp_upper += delta;
8088 /** Initial setup of a sorted-dups cursor.
8089 * Sorted duplicates are implemented as a sub-database for the given key.
8090 * The duplicate data items are actually keys of the sub-database.
8091 * Operations on the duplicate data items are performed using a sub-cursor
8092 * initialized when the sub-database is first accessed. This function does
8093 * the preliminary setup of the sub-cursor, filling in the fields that
8094 * depend only on the parent DB.
8095 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
8098 mdb_xcursor_init0(MDB_cursor *mc)
8100 MDB_xcursor *mx = mc->mc_xcursor;
8102 mx->mx_cursor.mc_xcursor = NULL;
8103 mx->mx_cursor.mc_txn = mc->mc_txn;
8104 mx->mx_cursor.mc_db = &mx->mx_db;
8105 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
8106 mx->mx_cursor.mc_dbi = mc->mc_dbi;
8107 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
8108 mx->mx_cursor.mc_snum = 0;
8109 mx->mx_cursor.mc_top = 0;
8111 mx->mx_cursor.mc_ovpg = 0;
8113 mx->mx_cursor.mc_flags = C_SUB | (mc->mc_flags & (C_ORIG_RDONLY|C_WRITEMAP));
8114 mx->mx_dbx.md_name.mv_size = 0;
8115 mx->mx_dbx.md_name.mv_data = NULL;
8116 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
8117 mx->mx_dbx.md_dcmp = NULL;
8118 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
8121 /** Final setup of a sorted-dups cursor.
8122 * Sets up the fields that depend on the data from the main cursor.
8123 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
8124 * @param[in] node The data containing the #MDB_db record for the
8125 * sorted-dup database.
8128 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
8130 MDB_xcursor *mx = mc->mc_xcursor;
8132 mx->mx_cursor.mc_flags &= C_SUB|C_ORIG_RDONLY|C_WRITEMAP;
8133 if (node->mn_flags & F_SUBDATA) {
8134 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
8135 mx->mx_cursor.mc_pg[0] = 0;
8136 mx->mx_cursor.mc_snum = 0;
8137 mx->mx_cursor.mc_top = 0;
8139 MDB_page *fp = NODEDATA(node);
8140 mx->mx_db.md_pad = 0;
8141 mx->mx_db.md_flags = 0;
8142 mx->mx_db.md_depth = 1;
8143 mx->mx_db.md_branch_pages = 0;
8144 mx->mx_db.md_leaf_pages = 1;
8145 mx->mx_db.md_overflow_pages = 0;
8146 mx->mx_db.md_entries = NUMKEYS(fp);
8147 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
8148 mx->mx_cursor.mc_snum = 1;
8149 mx->mx_cursor.mc_top = 0;
8150 mx->mx_cursor.mc_flags |= C_INITIALIZED;
8151 mx->mx_cursor.mc_pg[0] = fp;
8152 mx->mx_cursor.mc_ki[0] = 0;
8153 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
8154 mx->mx_db.md_flags = MDB_DUPFIXED;
8155 mx->mx_db.md_pad = fp->mp_pad;
8156 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
8157 mx->mx_db.md_flags |= MDB_INTEGERKEY;
8160 DPRINTF(("Sub-db -%u root page %"Y"u", mx->mx_cursor.mc_dbi,
8161 mx->mx_db.md_root));
8162 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
8163 #if UINT_MAX < SIZE_MAX || defined(MDB_VL32)
8164 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(mdb_size_t))
8165 mx->mx_dbx.md_cmp = mdb_cmp_clong;
8170 /** Fixup a sorted-dups cursor due to underlying update.
8171 * Sets up some fields that depend on the data from the main cursor.
8172 * Almost the same as init1, but skips initialization steps if the
8173 * xcursor had already been used.
8174 * @param[in] mc The main cursor whose sorted-dups cursor is to be fixed up.
8175 * @param[in] src_mx The xcursor of an up-to-date cursor.
8176 * @param[in] new_dupdata True if converting from a non-#F_DUPDATA item.
8179 mdb_xcursor_init2(MDB_cursor *mc, MDB_xcursor *src_mx, int new_dupdata)
8181 MDB_xcursor *mx = mc->mc_xcursor;
8184 mx->mx_cursor.mc_snum = 1;
8185 mx->mx_cursor.mc_top = 0;
8186 mx->mx_cursor.mc_flags |= C_INITIALIZED;
8187 mx->mx_cursor.mc_ki[0] = 0;
8188 mx->mx_dbflag = DB_VALID|DB_USRVALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
8189 #if UINT_MAX < SIZE_MAX
8190 mx->mx_dbx.md_cmp = src_mx->mx_dbx.md_cmp;
8192 } else if (!(mx->mx_cursor.mc_flags & C_INITIALIZED)) {
8195 mx->mx_db = src_mx->mx_db;
8196 mx->mx_cursor.mc_pg[0] = src_mx->mx_cursor.mc_pg[0];
8197 DPRINTF(("Sub-db -%u root page %"Y"u", mx->mx_cursor.mc_dbi,
8198 mx->mx_db.md_root));
8201 /** Initialize a cursor for a given transaction and database. */
8203 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
8206 mc->mc_backup = NULL;
8209 mc->mc_db = &txn->mt_dbs[dbi];
8210 mc->mc_dbx = &txn->mt_dbxs[dbi];
8211 mc->mc_dbflag = &txn->mt_dbflags[dbi];
8219 mc->mc_flags = txn->mt_flags & (C_ORIG_RDONLY|C_WRITEMAP);
8220 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
8221 mdb_tassert(txn, mx != NULL);
8222 mc->mc_xcursor = mx;
8223 mdb_xcursor_init0(mc);
8225 mc->mc_xcursor = NULL;
8227 if (*mc->mc_dbflag & DB_STALE) {
8228 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
8233 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
8236 size_t size = sizeof(MDB_cursor);
8238 if (!ret || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
8241 if (txn->mt_flags & MDB_TXN_BLOCKED)
8244 if (dbi == FREE_DBI && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
8247 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
8248 size += sizeof(MDB_xcursor);
8250 if ((mc = malloc(size)) != NULL) {
8251 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
8252 if (txn->mt_cursors) {
8253 mc->mc_next = txn->mt_cursors[dbi];
8254 txn->mt_cursors[dbi] = mc;
8255 mc->mc_flags |= C_UNTRACK;
8267 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
8269 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi, DB_VALID))
8272 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
8275 if (txn->mt_flags & MDB_TXN_BLOCKED)
8278 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
8282 /* Return the count of duplicate data items for the current key */
8284 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
8288 if (mc == NULL || countp == NULL)
8291 if (mc->mc_xcursor == NULL)
8292 return MDB_INCOMPATIBLE;
8294 if (mc->mc_txn->mt_flags & MDB_TXN_BLOCKED)
8297 if (!(mc->mc_flags & C_INITIALIZED))
8300 if (!mc->mc_snum || (mc->mc_flags & C_EOF))
8301 return MDB_NOTFOUND;
8303 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
8304 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
8307 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
8310 *countp = mc->mc_xcursor->mx_db.md_entries;
8316 mdb_cursor_close(MDB_cursor *mc)
8318 if (mc && !mc->mc_backup) {
8319 /* remove from txn, if tracked */
8320 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
8321 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
8322 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
8324 *prev = mc->mc_next;
8331 mdb_cursor_txn(MDB_cursor *mc)
8333 if (!mc) return NULL;
8338 mdb_cursor_dbi(MDB_cursor *mc)
8343 /** Replace the key for a branch node with a new key.
8344 * @param[in] mc Cursor pointing to the node to operate on.
8345 * @param[in] key The new key to use.
8346 * @return 0 on success, non-zero on failure.
8349 mdb_update_key(MDB_cursor *mc, MDB_val *key)
8355 int delta, ksize, oksize;
8356 indx_t ptr, i, numkeys, indx;
8359 indx = mc->mc_ki[mc->mc_top];
8360 mp = mc->mc_pg[mc->mc_top];
8361 node = NODEPTR(mp, indx);
8362 ptr = mp->mp_ptrs[indx];
8366 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
8367 k2.mv_data = NODEKEY(node);
8368 k2.mv_size = node->mn_ksize;
8369 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Y"u",
8371 mdb_dkey(&k2, kbuf2),
8377 /* Sizes must be 2-byte aligned. */
8378 ksize = EVEN(key->mv_size);
8379 oksize = EVEN(node->mn_ksize);
8380 delta = ksize - oksize;
8382 /* Shift node contents if EVEN(key length) changed. */
8384 if (delta > 0 && SIZELEFT(mp) < delta) {
8386 /* not enough space left, do a delete and split */
8387 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
8388 pgno = NODEPGNO(node);
8389 mdb_node_del(mc, 0);
8390 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
8393 numkeys = NUMKEYS(mp);
8394 for (i = 0; i < numkeys; i++) {
8395 if (mp->mp_ptrs[i] <= ptr)
8396 mp->mp_ptrs[i] -= delta;
8399 base = (char *)mp + mp->mp_upper + PAGEBASE;
8400 len = ptr - mp->mp_upper + NODESIZE;
8401 memmove(base - delta, base, len);
8402 mp->mp_upper -= delta;
8404 node = NODEPTR(mp, indx);
8407 /* But even if no shift was needed, update ksize */
8408 if (node->mn_ksize != key->mv_size)
8409 node->mn_ksize = key->mv_size;
8412 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
8418 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
8420 /** Perform \b act while tracking temporary cursor \b mn */
8421 #define WITH_CURSOR_TRACKING(mn, act) do { \
8422 MDB_cursor dummy, *tracked, **tp = &(mn).mc_txn->mt_cursors[mn.mc_dbi]; \
8423 if ((mn).mc_flags & C_SUB) { \
8424 dummy.mc_flags = C_INITIALIZED; \
8425 dummy.mc_xcursor = (MDB_xcursor *)&(mn); \
8430 tracked->mc_next = *tp; \
8433 *tp = tracked->mc_next; \
8436 /** Move a node from csrc to cdst.
8439 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst, int fromleft)
8446 unsigned short flags;
8450 /* Mark src and dst as dirty. */
8451 if ((rc = mdb_page_touch(csrc)) ||
8452 (rc = mdb_page_touch(cdst)))
8455 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8456 key.mv_size = csrc->mc_db->md_pad;
8457 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
8459 data.mv_data = NULL;
8463 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
8464 mdb_cassert(csrc, !((size_t)srcnode & 1));
8465 srcpg = NODEPGNO(srcnode);
8466 flags = srcnode->mn_flags;
8467 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
8468 unsigned int snum = csrc->mc_snum;
8470 /* must find the lowest key below src */
8471 rc = mdb_page_search_lowest(csrc);
8474 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8475 key.mv_size = csrc->mc_db->md_pad;
8476 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
8478 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
8479 key.mv_size = NODEKSZ(s2);
8480 key.mv_data = NODEKEY(s2);
8482 csrc->mc_snum = snum--;
8483 csrc->mc_top = snum;
8485 key.mv_size = NODEKSZ(srcnode);
8486 key.mv_data = NODEKEY(srcnode);
8488 data.mv_size = NODEDSZ(srcnode);
8489 data.mv_data = NODEDATA(srcnode);
8491 mn.mc_xcursor = NULL;
8492 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
8493 unsigned int snum = cdst->mc_snum;
8496 /* must find the lowest key below dst */
8497 mdb_cursor_copy(cdst, &mn);
8498 rc = mdb_page_search_lowest(&mn);
8501 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
8502 bkey.mv_size = mn.mc_db->md_pad;
8503 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
8505 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
8506 bkey.mv_size = NODEKSZ(s2);
8507 bkey.mv_data = NODEKEY(s2);
8509 mn.mc_snum = snum--;
8512 rc = mdb_update_key(&mn, &bkey);
8517 DPRINTF(("moving %s node %u [%s] on page %"Y"u to node %u on page %"Y"u",
8518 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
8519 csrc->mc_ki[csrc->mc_top],
8521 csrc->mc_pg[csrc->mc_top]->mp_pgno,
8522 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
8524 /* Add the node to the destination page.
8526 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
8527 if (rc != MDB_SUCCESS)
8530 /* Delete the node from the source page.
8532 mdb_node_del(csrc, key.mv_size);
8535 /* Adjust other cursors pointing to mp */
8536 MDB_cursor *m2, *m3;
8537 MDB_dbi dbi = csrc->mc_dbi;
8538 MDB_page *mpd, *mps;
8540 mps = csrc->mc_pg[csrc->mc_top];
8541 /* If we're adding on the left, bump others up */
8543 mpd = cdst->mc_pg[csrc->mc_top];
8544 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8545 if (csrc->mc_flags & C_SUB)
8546 m3 = &m2->mc_xcursor->mx_cursor;
8549 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
8552 m3->mc_pg[csrc->mc_top] == mpd &&
8553 m3->mc_ki[csrc->mc_top] >= cdst->mc_ki[csrc->mc_top]) {
8554 m3->mc_ki[csrc->mc_top]++;
8557 m3->mc_pg[csrc->mc_top] == mps &&
8558 m3->mc_ki[csrc->mc_top] == csrc->mc_ki[csrc->mc_top]) {
8559 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
8560 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
8561 m3->mc_ki[csrc->mc_top-1]++;
8563 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) &&
8565 MDB_node *node = NODEPTR(m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
8566 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
8567 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
8571 /* Adding on the right, bump others down */
8573 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8574 if (csrc->mc_flags & C_SUB)
8575 m3 = &m2->mc_xcursor->mx_cursor;
8578 if (m3 == csrc) continue;
8579 if (!(m3->mc_flags & C_INITIALIZED) || m3->mc_top < csrc->mc_top)
8581 if (m3->mc_pg[csrc->mc_top] == mps) {
8582 if (!m3->mc_ki[csrc->mc_top]) {
8583 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
8584 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
8585 m3->mc_ki[csrc->mc_top-1]--;
8587 m3->mc_ki[csrc->mc_top]--;
8589 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) &&
8591 MDB_node *node = NODEPTR(m3->mc_pg[csrc->mc_top], m3->mc_ki[csrc->mc_top]);
8592 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
8593 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
8600 /* Update the parent separators.
8602 if (csrc->mc_ki[csrc->mc_top] == 0) {
8603 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
8604 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8605 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
8607 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
8608 key.mv_size = NODEKSZ(srcnode);
8609 key.mv_data = NODEKEY(srcnode);
8611 DPRINTF(("update separator for source page %"Y"u to [%s]",
8612 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
8613 mdb_cursor_copy(csrc, &mn);
8616 /* We want mdb_rebalance to find mn when doing fixups */
8617 WITH_CURSOR_TRACKING(mn,
8618 rc = mdb_update_key(&mn, &key));
8622 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
8624 indx_t ix = csrc->mc_ki[csrc->mc_top];
8625 nullkey.mv_size = 0;
8626 csrc->mc_ki[csrc->mc_top] = 0;
8627 rc = mdb_update_key(csrc, &nullkey);
8628 csrc->mc_ki[csrc->mc_top] = ix;
8629 mdb_cassert(csrc, rc == MDB_SUCCESS);
8633 if (cdst->mc_ki[cdst->mc_top] == 0) {
8634 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
8635 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
8636 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
8638 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
8639 key.mv_size = NODEKSZ(srcnode);
8640 key.mv_data = NODEKEY(srcnode);
8642 DPRINTF(("update separator for destination page %"Y"u to [%s]",
8643 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
8644 mdb_cursor_copy(cdst, &mn);
8647 /* We want mdb_rebalance to find mn when doing fixups */
8648 WITH_CURSOR_TRACKING(mn,
8649 rc = mdb_update_key(&mn, &key));
8653 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
8655 indx_t ix = cdst->mc_ki[cdst->mc_top];
8656 nullkey.mv_size = 0;
8657 cdst->mc_ki[cdst->mc_top] = 0;
8658 rc = mdb_update_key(cdst, &nullkey);
8659 cdst->mc_ki[cdst->mc_top] = ix;
8660 mdb_cassert(cdst, rc == MDB_SUCCESS);
8667 /** Merge one page into another.
8668 * The nodes from the page pointed to by \b csrc will
8669 * be copied to the page pointed to by \b cdst and then
8670 * the \b csrc page will be freed.
8671 * @param[in] csrc Cursor pointing to the source page.
8672 * @param[in] cdst Cursor pointing to the destination page.
8673 * @return 0 on success, non-zero on failure.
8676 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
8678 MDB_page *psrc, *pdst;
8685 psrc = csrc->mc_pg[csrc->mc_top];
8686 pdst = cdst->mc_pg[cdst->mc_top];
8688 DPRINTF(("merging page %"Y"u into %"Y"u", psrc->mp_pgno, pdst->mp_pgno));
8690 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
8691 mdb_cassert(csrc, cdst->mc_snum > 1);
8693 /* Mark dst as dirty. */
8694 if ((rc = mdb_page_touch(cdst)))
8697 /* get dst page again now that we've touched it. */
8698 pdst = cdst->mc_pg[cdst->mc_top];
8700 /* Move all nodes from src to dst.
8702 j = nkeys = NUMKEYS(pdst);
8703 if (IS_LEAF2(psrc)) {
8704 key.mv_size = csrc->mc_db->md_pad;
8705 key.mv_data = METADATA(psrc);
8706 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
8707 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
8708 if (rc != MDB_SUCCESS)
8710 key.mv_data = (char *)key.mv_data + key.mv_size;
8713 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
8714 srcnode = NODEPTR(psrc, i);
8715 if (i == 0 && IS_BRANCH(psrc)) {
8718 mdb_cursor_copy(csrc, &mn);
8719 mn.mc_xcursor = NULL;
8720 /* must find the lowest key below src */
8721 rc = mdb_page_search_lowest(&mn);
8724 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
8725 key.mv_size = mn.mc_db->md_pad;
8726 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
8728 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
8729 key.mv_size = NODEKSZ(s2);
8730 key.mv_data = NODEKEY(s2);
8733 key.mv_size = srcnode->mn_ksize;
8734 key.mv_data = NODEKEY(srcnode);
8737 data.mv_size = NODEDSZ(srcnode);
8738 data.mv_data = NODEDATA(srcnode);
8739 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
8740 if (rc != MDB_SUCCESS)
8745 DPRINTF(("dst page %"Y"u now has %u keys (%.1f%% filled)",
8746 pdst->mp_pgno, NUMKEYS(pdst),
8747 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
8749 /* Unlink the src page from parent and add to free list.
8752 mdb_node_del(csrc, 0);
8753 if (csrc->mc_ki[csrc->mc_top] == 0) {
8755 rc = mdb_update_key(csrc, &key);
8763 psrc = csrc->mc_pg[csrc->mc_top];
8764 /* If not operating on FreeDB, allow this page to be reused
8765 * in this txn. Otherwise just add to free list.
8767 rc = mdb_page_loose(csrc, psrc);
8771 csrc->mc_db->md_leaf_pages--;
8773 csrc->mc_db->md_branch_pages--;
8775 /* Adjust other cursors pointing to mp */
8776 MDB_cursor *m2, *m3;
8777 MDB_dbi dbi = csrc->mc_dbi;
8778 unsigned int top = csrc->mc_top;
8780 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8781 if (csrc->mc_flags & C_SUB)
8782 m3 = &m2->mc_xcursor->mx_cursor;
8785 if (m3 == csrc) continue;
8786 if (m3->mc_snum < csrc->mc_snum) continue;
8787 if (m3->mc_pg[top] == psrc) {
8788 m3->mc_pg[top] = pdst;
8789 m3->mc_ki[top] += nkeys;
8790 m3->mc_ki[top-1] = cdst->mc_ki[top-1];
8791 } else if (m3->mc_pg[top-1] == csrc->mc_pg[top-1] &&
8792 m3->mc_ki[top-1] > csrc->mc_ki[top-1]) {
8795 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) &&
8797 MDB_node *node = NODEPTR(m3->mc_pg[top], m3->mc_ki[top]);
8798 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
8799 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
8804 unsigned int snum = cdst->mc_snum;
8805 uint16_t depth = cdst->mc_db->md_depth;
8806 mdb_cursor_pop(cdst);
8807 rc = mdb_rebalance(cdst);
8808 /* Did the tree height change? */
8809 if (depth != cdst->mc_db->md_depth)
8810 snum += cdst->mc_db->md_depth - depth;
8811 cdst->mc_snum = snum;
8812 cdst->mc_top = snum-1;
8817 /** Copy the contents of a cursor.
8818 * @param[in] csrc The cursor to copy from.
8819 * @param[out] cdst The cursor to copy to.
8822 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
8826 cdst->mc_txn = csrc->mc_txn;
8827 cdst->mc_dbi = csrc->mc_dbi;
8828 cdst->mc_db = csrc->mc_db;
8829 cdst->mc_dbx = csrc->mc_dbx;
8830 cdst->mc_snum = csrc->mc_snum;
8831 cdst->mc_top = csrc->mc_top;
8832 cdst->mc_flags = csrc->mc_flags;
8834 cdst->mc_ovpg = csrc->mc_ovpg;
8837 for (i=0; i<csrc->mc_snum; i++) {
8838 cdst->mc_pg[i] = csrc->mc_pg[i];
8839 cdst->mc_ki[i] = csrc->mc_ki[i];
8843 /** Rebalance the tree after a delete operation.
8844 * @param[in] mc Cursor pointing to the page where rebalancing
8846 * @return 0 on success, non-zero on failure.
8849 mdb_rebalance(MDB_cursor *mc)
8853 unsigned int ptop, minkeys, thresh;
8857 if (IS_BRANCH(mc->mc_pg[mc->mc_top])) {
8862 thresh = FILL_THRESHOLD;
8864 DPRINTF(("rebalancing %s page %"Y"u (has %u keys, %.1f%% full)",
8865 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
8866 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
8867 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
8869 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= thresh &&
8870 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
8871 DPRINTF(("no need to rebalance page %"Y"u, above fill threshold",
8872 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
8876 if (mc->mc_snum < 2) {
8877 MDB_page *mp = mc->mc_pg[0];
8879 DPUTS("Can't rebalance a subpage, ignoring");
8882 if (NUMKEYS(mp) == 0) {
8883 DPUTS("tree is completely empty");
8884 mc->mc_db->md_root = P_INVALID;
8885 mc->mc_db->md_depth = 0;
8886 mc->mc_db->md_leaf_pages = 0;
8887 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
8890 /* Adjust cursors pointing to mp */
8893 mc->mc_flags &= ~C_INITIALIZED;
8895 MDB_cursor *m2, *m3;
8896 MDB_dbi dbi = mc->mc_dbi;
8898 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8899 if (mc->mc_flags & C_SUB)
8900 m3 = &m2->mc_xcursor->mx_cursor;
8903 if (!(m3->mc_flags & C_INITIALIZED) || (m3->mc_snum < mc->mc_snum))
8905 if (m3->mc_pg[0] == mp) {
8908 m3->mc_flags &= ~C_INITIALIZED;
8912 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
8914 DPUTS("collapsing root page!");
8915 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
8918 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
8919 rc = mdb_page_get(mc, mc->mc_db->md_root, &mc->mc_pg[0], NULL);
8922 mc->mc_db->md_depth--;
8923 mc->mc_db->md_branch_pages--;
8924 mc->mc_ki[0] = mc->mc_ki[1];
8925 for (i = 1; i<mc->mc_db->md_depth; i++) {
8926 mc->mc_pg[i] = mc->mc_pg[i+1];
8927 mc->mc_ki[i] = mc->mc_ki[i+1];
8930 /* Adjust other cursors pointing to mp */
8931 MDB_cursor *m2, *m3;
8932 MDB_dbi dbi = mc->mc_dbi;
8934 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8935 if (mc->mc_flags & C_SUB)
8936 m3 = &m2->mc_xcursor->mx_cursor;
8939 if (m3 == mc) continue;
8940 if (!(m3->mc_flags & C_INITIALIZED))
8942 if (m3->mc_pg[0] == mp) {
8943 for (i=0; i<mc->mc_db->md_depth; i++) {
8944 m3->mc_pg[i] = m3->mc_pg[i+1];
8945 m3->mc_ki[i] = m3->mc_ki[i+1];
8953 DPUTS("root page doesn't need rebalancing");
8957 /* The parent (branch page) must have at least 2 pointers,
8958 * otherwise the tree is invalid.
8960 ptop = mc->mc_top-1;
8961 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
8963 /* Leaf page fill factor is below the threshold.
8964 * Try to move keys from left or right neighbor, or
8965 * merge with a neighbor page.
8970 mdb_cursor_copy(mc, &mn);
8971 mn.mc_xcursor = NULL;
8973 oldki = mc->mc_ki[mc->mc_top];
8974 if (mc->mc_ki[ptop] == 0) {
8975 /* We're the leftmost leaf in our parent.
8977 DPUTS("reading right neighbor");
8979 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
8980 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
8983 mn.mc_ki[mn.mc_top] = 0;
8984 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
8987 /* There is at least one neighbor to the left.
8989 DPUTS("reading left neighbor");
8991 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
8992 rc = mdb_page_get(mc, NODEPGNO(node), &mn.mc_pg[mn.mc_top], NULL);
8995 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
8996 mc->mc_ki[mc->mc_top] = 0;
9000 DPRINTF(("found neighbor page %"Y"u (%u keys, %.1f%% full)",
9001 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
9002 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
9004 /* If the neighbor page is above threshold and has enough keys,
9005 * move one key from it. Otherwise we should try to merge them.
9006 * (A branch page must never have less than 2 keys.)
9008 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= thresh && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
9009 rc = mdb_node_move(&mn, mc, fromleft);
9011 /* if we inserted on left, bump position up */
9016 rc = mdb_page_merge(&mn, mc);
9018 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
9019 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
9020 /* We want mdb_rebalance to find mn when doing fixups */
9021 WITH_CURSOR_TRACKING(mn,
9022 rc = mdb_page_merge(mc, &mn));
9023 mdb_cursor_copy(&mn, mc);
9025 mc->mc_flags &= ~C_EOF;
9027 mc->mc_ki[mc->mc_top] = oldki;
9031 /** Complete a delete operation started by #mdb_cursor_del(). */
9033 mdb_cursor_del0(MDB_cursor *mc)
9039 MDB_cursor *m2, *m3;
9040 MDB_dbi dbi = mc->mc_dbi;
9042 ki = mc->mc_ki[mc->mc_top];
9043 mp = mc->mc_pg[mc->mc_top];
9044 mdb_node_del(mc, mc->mc_db->md_pad);
9045 mc->mc_db->md_entries--;
9047 /* Adjust other cursors pointing to mp */
9048 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9049 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
9050 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9052 if (m3 == mc || m3->mc_snum < mc->mc_snum)
9054 if (m3->mc_pg[mc->mc_top] == mp) {
9055 if (m3->mc_ki[mc->mc_top] == ki) {
9056 m3->mc_flags |= C_DEL;
9057 if (mc->mc_db->md_flags & MDB_DUPSORT)
9058 m3->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
9059 } else if (m3->mc_ki[mc->mc_top] > ki) {
9060 m3->mc_ki[mc->mc_top]--;
9062 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
9063 MDB_node *node = NODEPTR(m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
9064 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
9065 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
9070 rc = mdb_rebalance(mc);
9072 if (rc == MDB_SUCCESS) {
9073 /* DB is totally empty now, just bail out.
9074 * Other cursors adjustments were already done
9075 * by mdb_rebalance and aren't needed here.
9080 mp = mc->mc_pg[mc->mc_top];
9081 nkeys = NUMKEYS(mp);
9083 /* Adjust other cursors pointing to mp */
9084 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
9085 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
9086 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9088 if (m3->mc_snum < mc->mc_snum)
9090 if (m3->mc_pg[mc->mc_top] == mp) {
9091 /* if m3 points past last node in page, find next sibling */
9092 if (m3->mc_ki[mc->mc_top] >= nkeys) {
9093 rc = mdb_cursor_sibling(m3, 1);
9094 if (rc == MDB_NOTFOUND) {
9095 m3->mc_flags |= C_EOF;
9101 mc->mc_flags |= C_DEL;
9105 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
9110 mdb_del(MDB_txn *txn, MDB_dbi dbi,
9111 MDB_val *key, MDB_val *data)
9113 if (!key || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9116 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
9117 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
9119 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
9120 /* must ignore any data */
9124 return mdb_del0(txn, dbi, key, data, 0);
9128 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
9129 MDB_val *key, MDB_val *data, unsigned flags)
9134 MDB_val rdata, *xdata;
9138 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
9140 mdb_cursor_init(&mc, txn, dbi, &mx);
9149 flags |= MDB_NODUPDATA;
9151 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
9153 /* let mdb_page_split know about this cursor if needed:
9154 * delete will trigger a rebalance; if it needs to move
9155 * a node from one page to another, it will have to
9156 * update the parent's separator key(s). If the new sepkey
9157 * is larger than the current one, the parent page may
9158 * run out of space, triggering a split. We need this
9159 * cursor to be consistent until the end of the rebalance.
9161 mc.mc_flags |= C_UNTRACK;
9162 mc.mc_next = txn->mt_cursors[dbi];
9163 txn->mt_cursors[dbi] = &mc;
9164 rc = mdb_cursor_del(&mc, flags);
9165 txn->mt_cursors[dbi] = mc.mc_next;
9170 /** Split a page and insert a new node.
9171 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
9172 * The cursor will be updated to point to the actual page and index where
9173 * the node got inserted after the split.
9174 * @param[in] newkey The key for the newly inserted node.
9175 * @param[in] newdata The data for the newly inserted node.
9176 * @param[in] newpgno The page number, if the new node is a branch node.
9177 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
9178 * @return 0 on success, non-zero on failure.
9181 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
9182 unsigned int nflags)
9185 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
9188 int i, j, split_indx, nkeys, pmax;
9189 MDB_env *env = mc->mc_txn->mt_env;
9191 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
9192 MDB_page *copy = NULL;
9193 MDB_page *mp, *rp, *pp;
9198 mp = mc->mc_pg[mc->mc_top];
9199 newindx = mc->mc_ki[mc->mc_top];
9200 nkeys = NUMKEYS(mp);
9202 DPRINTF(("-----> splitting %s page %"Y"u and adding [%s] at index %i/%i",
9203 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
9204 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
9206 /* Create a right sibling. */
9207 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
9209 rp->mp_pad = mp->mp_pad;
9210 DPRINTF(("new right sibling: page %"Y"u", rp->mp_pgno));
9212 /* Usually when splitting the root page, the cursor
9213 * height is 1. But when called from mdb_update_key,
9214 * the cursor height may be greater because it walks
9215 * up the stack while finding the branch slot to update.
9217 if (mc->mc_top < 1) {
9218 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
9220 /* shift current top to make room for new parent */
9221 for (i=mc->mc_snum; i>0; i--) {
9222 mc->mc_pg[i] = mc->mc_pg[i-1];
9223 mc->mc_ki[i] = mc->mc_ki[i-1];
9227 mc->mc_db->md_root = pp->mp_pgno;
9228 DPRINTF(("root split! new root = %"Y"u", pp->mp_pgno));
9229 new_root = mc->mc_db->md_depth++;
9231 /* Add left (implicit) pointer. */
9232 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
9233 /* undo the pre-push */
9234 mc->mc_pg[0] = mc->mc_pg[1];
9235 mc->mc_ki[0] = mc->mc_ki[1];
9236 mc->mc_db->md_root = mp->mp_pgno;
9237 mc->mc_db->md_depth--;
9244 ptop = mc->mc_top-1;
9245 DPRINTF(("parent branch page is %"Y"u", mc->mc_pg[ptop]->mp_pgno));
9248 mdb_cursor_copy(mc, &mn);
9249 mn.mc_xcursor = NULL;
9250 mn.mc_pg[mn.mc_top] = rp;
9251 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
9253 if (nflags & MDB_APPEND) {
9254 mn.mc_ki[mn.mc_top] = 0;
9256 split_indx = newindx;
9260 split_indx = (nkeys+1) / 2;
9265 unsigned int lsize, rsize, ksize;
9266 /* Move half of the keys to the right sibling */
9267 x = mc->mc_ki[mc->mc_top] - split_indx;
9268 ksize = mc->mc_db->md_pad;
9269 split = LEAF2KEY(mp, split_indx, ksize);
9270 rsize = (nkeys - split_indx) * ksize;
9271 lsize = (nkeys - split_indx) * sizeof(indx_t);
9272 mp->mp_lower -= lsize;
9273 rp->mp_lower += lsize;
9274 mp->mp_upper += rsize - lsize;
9275 rp->mp_upper -= rsize - lsize;
9276 sepkey.mv_size = ksize;
9277 if (newindx == split_indx) {
9278 sepkey.mv_data = newkey->mv_data;
9280 sepkey.mv_data = split;
9283 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
9284 memcpy(rp->mp_ptrs, split, rsize);
9285 sepkey.mv_data = rp->mp_ptrs;
9286 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
9287 memcpy(ins, newkey->mv_data, ksize);
9288 mp->mp_lower += sizeof(indx_t);
9289 mp->mp_upper -= ksize - sizeof(indx_t);
9292 memcpy(rp->mp_ptrs, split, x * ksize);
9293 ins = LEAF2KEY(rp, x, ksize);
9294 memcpy(ins, newkey->mv_data, ksize);
9295 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
9296 rp->mp_lower += sizeof(indx_t);
9297 rp->mp_upper -= ksize - sizeof(indx_t);
9298 mc->mc_ki[mc->mc_top] = x;
9301 int psize, nsize, k;
9302 /* Maximum free space in an empty page */
9303 pmax = env->me_psize - PAGEHDRSZ;
9305 nsize = mdb_leaf_size(env, newkey, newdata);
9307 nsize = mdb_branch_size(env, newkey);
9308 nsize = EVEN(nsize);
9310 /* grab a page to hold a temporary copy */
9311 copy = mdb_page_malloc(mc->mc_txn, 1);
9316 copy->mp_pgno = mp->mp_pgno;
9317 copy->mp_flags = mp->mp_flags;
9318 copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
9319 copy->mp_upper = env->me_psize - PAGEBASE;
9321 /* prepare to insert */
9322 for (i=0, j=0; i<nkeys; i++) {
9324 copy->mp_ptrs[j++] = 0;
9326 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
9329 /* When items are relatively large the split point needs
9330 * to be checked, because being off-by-one will make the
9331 * difference between success or failure in mdb_node_add.
9333 * It's also relevant if a page happens to be laid out
9334 * such that one half of its nodes are all "small" and
9335 * the other half of its nodes are "large." If the new
9336 * item is also "large" and falls on the half with
9337 * "large" nodes, it also may not fit.
9339 * As a final tweak, if the new item goes on the last
9340 * spot on the page (and thus, onto the new page), bias
9341 * the split so the new page is emptier than the old page.
9342 * This yields better packing during sequential inserts.
9344 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
9345 /* Find split point */
9347 if (newindx <= split_indx || newindx >= nkeys) {
9349 k = newindx >= nkeys ? nkeys : split_indx+1+IS_LEAF(mp);
9354 for (; i!=k; i+=j) {
9359 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
9360 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
9362 if (F_ISSET(node->mn_flags, F_BIGDATA))
9363 psize += sizeof(pgno_t);
9365 psize += NODEDSZ(node);
9367 psize = EVEN(psize);
9369 if (psize > pmax || i == k-j) {
9370 split_indx = i + (j<0);
9375 if (split_indx == newindx) {
9376 sepkey.mv_size = newkey->mv_size;
9377 sepkey.mv_data = newkey->mv_data;
9379 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
9380 sepkey.mv_size = node->mn_ksize;
9381 sepkey.mv_data = NODEKEY(node);
9386 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
9388 /* Copy separator key to the parent.
9390 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
9391 int snum = mc->mc_snum;
9395 /* We want other splits to find mn when doing fixups */
9396 WITH_CURSOR_TRACKING(mn,
9397 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0));
9402 if (mc->mc_snum > snum) {
9405 /* Right page might now have changed parent.
9406 * Check if left page also changed parent.
9408 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
9409 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
9410 for (i=0; i<ptop; i++) {
9411 mc->mc_pg[i] = mn.mc_pg[i];
9412 mc->mc_ki[i] = mn.mc_ki[i];
9414 mc->mc_pg[ptop] = mn.mc_pg[ptop];
9415 if (mn.mc_ki[ptop]) {
9416 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
9418 /* find right page's left sibling */
9419 mc->mc_ki[ptop] = mn.mc_ki[ptop];
9420 mdb_cursor_sibling(mc, 0);
9425 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
9428 if (rc != MDB_SUCCESS) {
9431 if (nflags & MDB_APPEND) {
9432 mc->mc_pg[mc->mc_top] = rp;
9433 mc->mc_ki[mc->mc_top] = 0;
9434 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
9437 for (i=0; i<mc->mc_top; i++)
9438 mc->mc_ki[i] = mn.mc_ki[i];
9439 } else if (!IS_LEAF2(mp)) {
9441 mc->mc_pg[mc->mc_top] = rp;
9446 rkey.mv_data = newkey->mv_data;
9447 rkey.mv_size = newkey->mv_size;
9453 /* Update index for the new key. */
9454 mc->mc_ki[mc->mc_top] = j;
9456 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
9457 rkey.mv_data = NODEKEY(node);
9458 rkey.mv_size = node->mn_ksize;
9460 xdata.mv_data = NODEDATA(node);
9461 xdata.mv_size = NODEDSZ(node);
9464 pgno = NODEPGNO(node);
9465 flags = node->mn_flags;
9468 if (!IS_LEAF(mp) && j == 0) {
9469 /* First branch index doesn't need key data. */
9473 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
9479 mc->mc_pg[mc->mc_top] = copy;
9484 } while (i != split_indx);
9486 nkeys = NUMKEYS(copy);
9487 for (i=0; i<nkeys; i++)
9488 mp->mp_ptrs[i] = copy->mp_ptrs[i];
9489 mp->mp_lower = copy->mp_lower;
9490 mp->mp_upper = copy->mp_upper;
9491 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
9492 env->me_psize - copy->mp_upper - PAGEBASE);
9494 /* reset back to original page */
9495 if (newindx < split_indx) {
9496 mc->mc_pg[mc->mc_top] = mp;
9498 mc->mc_pg[mc->mc_top] = rp;
9500 /* Make sure mc_ki is still valid.
9502 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
9503 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
9504 for (i=0; i<=ptop; i++) {
9505 mc->mc_pg[i] = mn.mc_pg[i];
9506 mc->mc_ki[i] = mn.mc_ki[i];
9510 if (nflags & MDB_RESERVE) {
9511 node = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
9512 if (!(node->mn_flags & F_BIGDATA))
9513 newdata->mv_data = NODEDATA(node);
9516 if (newindx >= split_indx) {
9517 mc->mc_pg[mc->mc_top] = rp;
9519 /* Make sure mc_ki is still valid.
9521 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
9522 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
9523 for (i=0; i<=ptop; i++) {
9524 mc->mc_pg[i] = mn.mc_pg[i];
9525 mc->mc_ki[i] = mn.mc_ki[i];
9532 /* Adjust other cursors pointing to mp */
9533 MDB_cursor *m2, *m3;
9534 MDB_dbi dbi = mc->mc_dbi;
9535 nkeys = NUMKEYS(mp);
9537 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
9538 if (mc->mc_flags & C_SUB)
9539 m3 = &m2->mc_xcursor->mx_cursor;
9544 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
9548 /* sub cursors may be on different DB */
9549 if (m3->mc_pg[0] != mp)
9552 for (k=new_root; k>=0; k--) {
9553 m3->mc_ki[k+1] = m3->mc_ki[k];
9554 m3->mc_pg[k+1] = m3->mc_pg[k];
9556 if (m3->mc_ki[0] >= nkeys) {
9561 m3->mc_pg[0] = mc->mc_pg[0];
9565 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
9566 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
9567 m3->mc_ki[mc->mc_top]++;
9568 if (m3->mc_ki[mc->mc_top] >= nkeys) {
9569 m3->mc_pg[mc->mc_top] = rp;
9570 m3->mc_ki[mc->mc_top] -= nkeys;
9571 for (i=0; i<mc->mc_top; i++) {
9572 m3->mc_ki[i] = mn.mc_ki[i];
9573 m3->mc_pg[i] = mn.mc_pg[i];
9576 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
9577 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
9580 if (m3->mc_xcursor && (m3->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) &&
9582 MDB_node *node = NODEPTR(m3->mc_pg[mc->mc_top], m3->mc_ki[mc->mc_top]);
9583 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA)
9584 m3->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(node);
9588 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
9591 if (copy) /* tmp page */
9592 mdb_page_free(env, copy);
9594 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
9599 mdb_put(MDB_txn *txn, MDB_dbi dbi,
9600 MDB_val *key, MDB_val *data, unsigned int flags)
9606 if (!key || !data || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
9609 if (flags & ~(MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP))
9612 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_BLOCKED))
9613 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
9615 mdb_cursor_init(&mc, txn, dbi, &mx);
9616 mc.mc_next = txn->mt_cursors[dbi];
9617 txn->mt_cursors[dbi] = &mc;
9618 rc = mdb_cursor_put(&mc, key, data, flags);
9619 txn->mt_cursors[dbi] = mc.mc_next;
9624 #define MDB_WBUF (1024*1024)
9627 /** State needed for a compacting copy. */
9628 typedef struct mdb_copy {
9629 pthread_mutex_t mc_mutex;
9630 pthread_cond_t mc_cond;
9637 pgno_t mc_next_pgno;
9640 volatile int mc_new;
9645 /** Dedicated writer thread for compacting copy. */
9646 static THREAD_RET ESECT CALL_CONV
9647 mdb_env_copythr(void *arg)
9651 int toggle = 0, wsize, rc;
9654 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
9657 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
9660 pthread_mutex_lock(&my->mc_mutex);
9662 pthread_cond_signal(&my->mc_cond);
9665 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
9666 if (my->mc_new < 0) {
9671 wsize = my->mc_wlen[toggle];
9672 ptr = my->mc_wbuf[toggle];
9675 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
9679 } else if (len > 0) {
9693 /* If there's an overflow page tail, write it too */
9694 if (my->mc_olen[toggle]) {
9695 wsize = my->mc_olen[toggle];
9696 ptr = my->mc_over[toggle];
9697 my->mc_olen[toggle] = 0;
9700 my->mc_wlen[toggle] = 0;
9702 pthread_cond_signal(&my->mc_cond);
9704 pthread_cond_signal(&my->mc_cond);
9705 pthread_mutex_unlock(&my->mc_mutex);
9706 return (THREAD_RET)0;
9710 /** Tell the writer thread there's a buffer ready to write */
9712 mdb_env_cthr_toggle(mdb_copy *my, int st)
9714 int toggle = my->mc_toggle ^ 1;
9715 pthread_mutex_lock(&my->mc_mutex);
9716 if (my->mc_status) {
9717 pthread_mutex_unlock(&my->mc_mutex);
9718 return my->mc_status;
9720 while (my->mc_new == 1)
9721 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
9723 my->mc_toggle = toggle;
9724 pthread_cond_signal(&my->mc_cond);
9725 pthread_mutex_unlock(&my->mc_mutex);
9729 /** Depth-first tree traversal for compacting copy. */
9731 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
9735 MDB_page *mo, *mp, *leaf;
9740 /* Empty DB, nothing to do */
9741 if (*pg == P_INVALID)
9746 mc.mc_txn = my->mc_txn;
9748 rc = mdb_page_get(&mc, *pg, &mc.mc_pg[0], NULL);
9751 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
9755 /* Make cursor pages writable */
9756 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
9760 for (i=0; i<mc.mc_top; i++) {
9761 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
9762 mc.mc_pg[i] = (MDB_page *)ptr;
9763 ptr += my->mc_env->me_psize;
9766 /* This is writable space for a leaf page. Usually not needed. */
9767 leaf = (MDB_page *)ptr;
9769 toggle = my->mc_toggle;
9770 while (mc.mc_snum > 0) {
9772 mp = mc.mc_pg[mc.mc_top];
9776 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
9777 for (i=0; i<n; i++) {
9778 ni = NODEPTR(mp, i);
9779 if (ni->mn_flags & F_BIGDATA) {
9783 /* Need writable leaf */
9785 mc.mc_pg[mc.mc_top] = leaf;
9786 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
9788 ni = NODEPTR(mp, i);
9791 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9792 rc = mdb_page_get(&mc, pg, &omp, NULL);
9795 if (my->mc_wlen[toggle] >= MDB_WBUF) {
9796 rc = mdb_env_cthr_toggle(my, 1);
9799 toggle = my->mc_toggle;
9801 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
9802 memcpy(mo, omp, my->mc_env->me_psize);
9803 mo->mp_pgno = my->mc_next_pgno;
9804 my->mc_next_pgno += omp->mp_pages;
9805 my->mc_wlen[toggle] += my->mc_env->me_psize;
9806 if (omp->mp_pages > 1) {
9807 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
9808 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
9809 rc = mdb_env_cthr_toggle(my, 1);
9812 toggle = my->mc_toggle;
9814 memcpy(NODEDATA(ni), &mo->mp_pgno, sizeof(pgno_t));
9815 } else if (ni->mn_flags & F_SUBDATA) {
9818 /* Need writable leaf */
9820 mc.mc_pg[mc.mc_top] = leaf;
9821 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
9823 ni = NODEPTR(mp, i);
9826 memcpy(&db, NODEDATA(ni), sizeof(db));
9827 my->mc_toggle = toggle;
9828 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
9831 toggle = my->mc_toggle;
9832 memcpy(NODEDATA(ni), &db, sizeof(db));
9837 mc.mc_ki[mc.mc_top]++;
9838 if (mc.mc_ki[mc.mc_top] < n) {
9841 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
9843 rc = mdb_page_get(&mc, pg, &mp, NULL);
9848 mc.mc_ki[mc.mc_top] = 0;
9849 if (IS_BRANCH(mp)) {
9850 /* Whenever we advance to a sibling branch page,
9851 * we must proceed all the way down to its first leaf.
9853 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
9856 mc.mc_pg[mc.mc_top] = mp;
9860 if (my->mc_wlen[toggle] >= MDB_WBUF) {
9861 rc = mdb_env_cthr_toggle(my, 1);
9864 toggle = my->mc_toggle;
9866 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
9867 mdb_page_copy(mo, mp, my->mc_env->me_psize);
9868 mo->mp_pgno = my->mc_next_pgno++;
9869 my->mc_wlen[toggle] += my->mc_env->me_psize;
9871 /* Update parent if there is one */
9872 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
9873 SETPGNO(ni, mo->mp_pgno);
9874 mdb_cursor_pop(&mc);
9876 /* Otherwise we're done */
9886 /** Copy environment with compaction. */
9888 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
9893 MDB_txn *txn = NULL;
9898 my.mc_mutex = CreateMutex(NULL, FALSE, NULL);
9899 my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL);
9900 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_os_psize);
9901 if (my.mc_wbuf[0] == NULL)
9904 pthread_mutex_init(&my.mc_mutex, NULL);
9905 pthread_cond_init(&my.mc_cond, NULL);
9906 #ifdef HAVE_MEMALIGN
9907 my.mc_wbuf[0] = memalign(env->me_os_psize, MDB_WBUF*2);
9908 if (my.mc_wbuf[0] == NULL)
9911 rc = posix_memalign((void **)&my.mc_wbuf[0], env->me_os_psize, MDB_WBUF*2);
9916 memset(my.mc_wbuf[0], 0, MDB_WBUF*2);
9917 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
9922 my.mc_next_pgno = NUM_METAS;
9928 THREAD_CREATE(thr, mdb_env_copythr, &my);
9930 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
9934 mp = (MDB_page *)my.mc_wbuf[0];
9935 memset(mp, 0, NUM_METAS * env->me_psize);
9937 mp->mp_flags = P_META;
9938 mm = (MDB_meta *)METADATA(mp);
9939 mdb_env_init_meta0(env, mm);
9940 mm->mm_address = env->me_metas[0]->mm_address;
9942 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
9944 mp->mp_flags = P_META;
9945 *(MDB_meta *)METADATA(mp) = *mm;
9946 mm = (MDB_meta *)METADATA(mp);
9948 /* Count the number of free pages, subtract from lastpg to find
9949 * number of active pages
9952 MDB_ID freecount = 0;
9955 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
9956 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
9957 freecount += *(MDB_ID *)data.mv_data;
9958 freecount += txn->mt_dbs[FREE_DBI].md_branch_pages +
9959 txn->mt_dbs[FREE_DBI].md_leaf_pages +
9960 txn->mt_dbs[FREE_DBI].md_overflow_pages;
9962 /* Set metapage 1 */
9963 mm->mm_last_pg = txn->mt_next_pgno - freecount - 1;
9964 mm->mm_dbs[MAIN_DBI] = txn->mt_dbs[MAIN_DBI];
9965 if (mm->mm_last_pg > NUM_METAS-1) {
9966 mm->mm_dbs[MAIN_DBI].md_root = mm->mm_last_pg;
9969 mm->mm_dbs[MAIN_DBI].md_root = P_INVALID;
9972 my.mc_wlen[0] = env->me_psize * NUM_METAS;
9974 pthread_mutex_lock(&my.mc_mutex);
9976 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
9977 pthread_mutex_unlock(&my.mc_mutex);
9978 rc = mdb_env_cwalk(&my, &txn->mt_dbs[MAIN_DBI].md_root, 0);
9979 if (rc == MDB_SUCCESS && my.mc_wlen[my.mc_toggle])
9980 rc = mdb_env_cthr_toggle(&my, 1);
9981 mdb_env_cthr_toggle(&my, -1);
9982 pthread_mutex_lock(&my.mc_mutex);
9984 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
9985 pthread_mutex_unlock(&my.mc_mutex);
9990 CloseHandle(my.mc_cond);
9991 CloseHandle(my.mc_mutex);
9992 _aligned_free(my.mc_wbuf[0]);
9994 pthread_cond_destroy(&my.mc_cond);
9995 pthread_mutex_destroy(&my.mc_mutex);
9996 free(my.mc_wbuf[0]);
10001 /** Copy environment as-is. */
10003 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
10005 MDB_txn *txn = NULL;
10006 mdb_mutexref_t wmutex = NULL;
10008 mdb_size_t wsize, w3;
10012 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
10016 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
10019 /* Do the lock/unlock of the reader mutex before starting the
10020 * write txn. Otherwise other read txns could block writers.
10022 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
10026 if (env->me_txns) {
10027 /* We must start the actual read txn after blocking writers */
10028 mdb_txn_end(txn, MDB_END_RESET_TMP);
10030 /* Temporarily block writers until we snapshot the meta pages */
10031 wmutex = env->me_wmutex;
10032 if (LOCK_MUTEX(rc, env, wmutex))
10035 rc = mdb_txn_renew0(txn);
10037 UNLOCK_MUTEX(wmutex);
10042 wsize = env->me_psize * NUM_METAS;
10046 DO_WRITE(rc, fd, ptr, w2, len);
10050 } else if (len > 0) {
10056 /* Non-blocking or async handles are not supported */
10062 UNLOCK_MUTEX(wmutex);
10067 w3 = txn->mt_next_pgno * env->me_psize;
10069 mdb_size_t fsize = 0;
10070 if ((rc = mdb_fsize(env->me_fd, &fsize)))
10075 wsize = w3 - wsize;
10076 while (wsize > 0) {
10077 if (wsize > MAX_WRITE)
10081 DO_WRITE(rc, fd, ptr, w2, len);
10085 } else if (len > 0) {
10097 mdb_txn_abort(txn);
10102 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
10104 if (flags & MDB_CP_COMPACT)
10105 return mdb_env_copyfd1(env, fd);
10107 return mdb_env_copyfd0(env, fd);
10111 mdb_env_copyfd(MDB_env *env, HANDLE fd)
10113 return mdb_env_copyfd2(env, fd, 0);
10117 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
10121 HANDLE newfd = INVALID_HANDLE_VALUE;
10126 if (env->me_flags & MDB_NOSUBDIR) {
10127 lpath = (char *)path;
10129 len = strlen(path);
10130 len += sizeof(DATANAME);
10131 lpath = malloc(len);
10134 sprintf(lpath, "%s" DATANAME, path);
10137 /* The destination path must exist, but the destination file must not.
10138 * We don't want the OS to cache the writes, since the source data is
10139 * already in the OS cache.
10142 rc = utf8_to_utf16(lpath, -1, &wpath, NULL);
10145 newfd = CreateFileW(wpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
10146 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
10149 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
10151 if (newfd == INVALID_HANDLE_VALUE) {
10156 if (env->me_psize >= env->me_os_psize) {
10158 /* Set O_DIRECT if the file system supports it */
10159 if ((rc = fcntl(newfd, F_GETFL)) != -1)
10160 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
10162 #ifdef F_NOCACHE /* __APPLE__ */
10163 rc = fcntl(newfd, F_NOCACHE, 1);
10171 rc = mdb_env_copyfd2(env, newfd, flags);
10174 if (!(env->me_flags & MDB_NOSUBDIR))
10176 if (newfd != INVALID_HANDLE_VALUE)
10177 if (close(newfd) < 0 && rc == MDB_SUCCESS)
10184 mdb_env_copy(MDB_env *env, const char *path)
10186 return mdb_env_copy2(env, path, 0);
10190 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
10192 if (flag & ~CHANGEABLE)
10195 env->me_flags |= flag;
10197 env->me_flags &= ~flag;
10198 return MDB_SUCCESS;
10202 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
10207 *arg = env->me_flags & (CHANGEABLE|CHANGELESS);
10208 return MDB_SUCCESS;
10212 mdb_env_set_userctx(MDB_env *env, void *ctx)
10216 env->me_userctx = ctx;
10217 return MDB_SUCCESS;
10221 mdb_env_get_userctx(MDB_env *env)
10223 return env ? env->me_userctx : NULL;
10227 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
10232 env->me_assert_func = func;
10234 return MDB_SUCCESS;
10238 mdb_env_get_path(MDB_env *env, const char **arg)
10243 *arg = env->me_path;
10244 return MDB_SUCCESS;
10248 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
10254 return MDB_SUCCESS;
10257 /** Common code for #mdb_stat() and #mdb_env_stat().
10258 * @param[in] env the environment to operate in.
10259 * @param[in] db the #MDB_db record containing the stats to return.
10260 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
10261 * @return 0, this function always succeeds.
10264 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
10266 arg->ms_psize = env->me_psize;
10267 arg->ms_depth = db->md_depth;
10268 arg->ms_branch_pages = db->md_branch_pages;
10269 arg->ms_leaf_pages = db->md_leaf_pages;
10270 arg->ms_overflow_pages = db->md_overflow_pages;
10271 arg->ms_entries = db->md_entries;
10273 return MDB_SUCCESS;
10277 mdb_env_stat(MDB_env *env, MDB_stat *arg)
10281 if (env == NULL || arg == NULL)
10284 meta = mdb_env_pick_meta(env);
10286 return mdb_stat0(env, &meta->mm_dbs[MAIN_DBI], arg);
10290 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
10294 if (env == NULL || arg == NULL)
10297 meta = mdb_env_pick_meta(env);
10298 arg->me_mapaddr = meta->mm_address;
10299 arg->me_last_pgno = meta->mm_last_pg;
10300 arg->me_last_txnid = meta->mm_txnid;
10302 arg->me_mapsize = env->me_mapsize;
10303 arg->me_maxreaders = env->me_maxreaders;
10304 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : 0;
10305 return MDB_SUCCESS;
10308 /** Set the default comparison functions for a database.
10309 * Called immediately after a database is opened to set the defaults.
10310 * The user can then override them with #mdb_set_compare() or
10311 * #mdb_set_dupsort().
10312 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
10313 * @param[in] dbi A database handle returned by #mdb_dbi_open()
10316 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
10318 uint16_t f = txn->mt_dbs[dbi].md_flags;
10320 txn->mt_dbxs[dbi].md_cmp =
10321 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
10322 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
10324 txn->mt_dbxs[dbi].md_dcmp =
10325 !(f & MDB_DUPSORT) ? 0 :
10326 ((f & MDB_INTEGERDUP)
10327 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
10328 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
10331 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
10337 int rc, dbflag, exact;
10338 unsigned int unused = 0, seq;
10342 if (flags & ~VALID_FLAGS)
10344 if (txn->mt_flags & MDB_TXN_BLOCKED)
10345 return MDB_BAD_TXN;
10350 if (flags & PERSISTENT_FLAGS) {
10351 uint16_t f2 = flags & PERSISTENT_FLAGS;
10352 /* make sure flag changes get committed */
10353 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
10354 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
10355 txn->mt_flags |= MDB_TXN_DIRTY;
10358 mdb_default_cmp(txn, MAIN_DBI);
10359 return MDB_SUCCESS;
10362 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
10363 mdb_default_cmp(txn, MAIN_DBI);
10366 /* Is the DB already open? */
10367 len = strlen(name);
10368 for (i=CORE_DBS; i<txn->mt_numdbs; i++) {
10369 if (!txn->mt_dbxs[i].md_name.mv_size) {
10370 /* Remember this free slot */
10371 if (!unused) unused = i;
10374 if (len == txn->mt_dbxs[i].md_name.mv_size &&
10375 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
10377 return MDB_SUCCESS;
10381 /* If no free slot and max hit, fail */
10382 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
10383 return MDB_DBS_FULL;
10385 /* Cannot mix named databases with some mainDB flags */
10386 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
10387 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
10389 /* Find the DB info */
10390 dbflag = DB_NEW|DB_VALID|DB_USRVALID;
10393 key.mv_data = (void *)name;
10394 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
10395 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
10396 if (rc == MDB_SUCCESS) {
10397 /* make sure this is actually a DB */
10398 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
10399 if ((node->mn_flags & (F_DUPDATA|F_SUBDATA)) != F_SUBDATA)
10400 return MDB_INCOMPATIBLE;
10401 } else if (! (rc == MDB_NOTFOUND && (flags & MDB_CREATE))) {
10405 /* Done here so we cannot fail after creating a new DB */
10406 if ((namedup = strdup(name)) == NULL)
10410 /* MDB_NOTFOUND and MDB_CREATE: Create new DB */
10411 data.mv_size = sizeof(MDB_db);
10412 data.mv_data = &dummy;
10413 memset(&dummy, 0, sizeof(dummy));
10414 dummy.md_root = P_INVALID;
10415 dummy.md_flags = flags & PERSISTENT_FLAGS;
10416 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
10417 dbflag |= DB_DIRTY;
10423 /* Got info, register DBI in this txn */
10424 unsigned int slot = unused ? unused : txn->mt_numdbs;
10425 txn->mt_dbxs[slot].md_name.mv_data = namedup;
10426 txn->mt_dbxs[slot].md_name.mv_size = len;
10427 txn->mt_dbxs[slot].md_rel = NULL;
10428 txn->mt_dbflags[slot] = dbflag;
10429 /* txn-> and env-> are the same in read txns, use
10430 * tmp variable to avoid undefined assignment
10432 seq = ++txn->mt_env->me_dbiseqs[slot];
10433 txn->mt_dbiseqs[slot] = seq;
10435 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
10437 mdb_default_cmp(txn, slot);
10447 mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
10449 if (!arg || !TXN_DBI_EXIST(txn, dbi, DB_VALID))
10452 if (txn->mt_flags & MDB_TXN_BLOCKED)
10453 return MDB_BAD_TXN;
10455 if (txn->mt_dbflags[dbi] & DB_STALE) {
10458 /* Stale, must read the DB's root. cursor_init does it for us. */
10459 mdb_cursor_init(&mc, txn, dbi, &mx);
10461 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
10464 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
10467 if (dbi < CORE_DBS || dbi >= env->me_maxdbs)
10469 ptr = env->me_dbxs[dbi].md_name.mv_data;
10470 /* If there was no name, this was already closed */
10472 env->me_dbxs[dbi].md_name.mv_data = NULL;
10473 env->me_dbxs[dbi].md_name.mv_size = 0;
10474 env->me_dbflags[dbi] = 0;
10475 env->me_dbiseqs[dbi]++;
10480 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
10482 /* We could return the flags for the FREE_DBI too but what's the point? */
10483 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10485 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
10486 return MDB_SUCCESS;
10489 /** Add all the DB's pages to the free list.
10490 * @param[in] mc Cursor on the DB to free.
10491 * @param[in] subs non-Zero to check for sub-DBs in this DB.
10492 * @return 0 on success, non-zero on failure.
10495 mdb_drop0(MDB_cursor *mc, int subs)
10499 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
10500 if (rc == MDB_SUCCESS) {
10501 MDB_txn *txn = mc->mc_txn;
10506 /* DUPSORT sub-DBs have no ovpages/DBs. Omit scanning leaves.
10507 * This also avoids any P_LEAF2 pages, which have no nodes.
10509 if (mc->mc_flags & C_SUB)
10510 mdb_cursor_pop(mc);
10512 mdb_cursor_copy(mc, &mx);
10514 /* bump refcount for mx's pages */
10515 for (i=0; i<mc->mc_snum; i++)
10516 mdb_page_get(&mx, mc->mc_pg[i]->mp_pgno, &mx.mc_pg[i], NULL);
10518 while (mc->mc_snum > 0) {
10519 MDB_page *mp = mc->mc_pg[mc->mc_top];
10520 unsigned n = NUMKEYS(mp);
10522 for (i=0; i<n; i++) {
10523 ni = NODEPTR(mp, i);
10524 if (ni->mn_flags & F_BIGDATA) {
10527 memcpy(&pg, NODEDATA(ni), sizeof(pg));
10528 rc = mdb_page_get(mc, pg, &omp, NULL);
10531 mdb_cassert(mc, IS_OVERFLOW(omp));
10532 rc = mdb_midl_append_range(&txn->mt_free_pgs,
10533 pg, omp->mp_pages);
10536 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
10537 mdb_xcursor_init1(mc, ni);
10538 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
10544 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
10546 for (i=0; i<n; i++) {
10548 ni = NODEPTR(mp, i);
10551 mdb_midl_xappend(txn->mt_free_pgs, pg);
10556 mc->mc_ki[mc->mc_top] = i;
10557 rc = mdb_cursor_sibling(mc, 1);
10559 if (rc != MDB_NOTFOUND)
10561 /* no more siblings, go back to beginning
10562 * of previous level.
10564 mdb_cursor_pop(mc);
10566 for (i=1; i<mc->mc_snum; i++) {
10568 mc->mc_pg[i] = mx.mc_pg[i];
10573 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
10576 txn->mt_flags |= MDB_TXN_ERROR;
10578 /* drop refcount for mx's pages */
10579 mdb_cursor_unref(&mx);
10581 } else if (rc == MDB_NOTFOUND) {
10584 mc->mc_flags &= ~C_INITIALIZED;
10588 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
10590 MDB_cursor *mc, *m2;
10593 if ((unsigned)del > 1 || !TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10596 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
10599 if (TXN_DBI_CHANGED(txn, dbi))
10600 return MDB_BAD_DBI;
10602 rc = mdb_cursor_open(txn, dbi, &mc);
10606 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
10607 /* Invalidate the dropped DB's cursors */
10608 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
10609 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
10613 /* Can't delete the main DB */
10614 if (del && dbi >= CORE_DBS) {
10615 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, F_SUBDATA);
10617 txn->mt_dbflags[dbi] = DB_STALE;
10618 mdb_dbi_close(txn->mt_env, dbi);
10620 txn->mt_flags |= MDB_TXN_ERROR;
10623 /* reset the DB record, mark it dirty */
10624 txn->mt_dbflags[dbi] |= DB_DIRTY;
10625 txn->mt_dbs[dbi].md_depth = 0;
10626 txn->mt_dbs[dbi].md_branch_pages = 0;
10627 txn->mt_dbs[dbi].md_leaf_pages = 0;
10628 txn->mt_dbs[dbi].md_overflow_pages = 0;
10629 txn->mt_dbs[dbi].md_entries = 0;
10630 txn->mt_dbs[dbi].md_root = P_INVALID;
10632 txn->mt_flags |= MDB_TXN_DIRTY;
10635 mdb_cursor_close(mc);
10639 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
10641 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10644 txn->mt_dbxs[dbi].md_cmp = cmp;
10645 return MDB_SUCCESS;
10648 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
10650 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10653 txn->mt_dbxs[dbi].md_dcmp = cmp;
10654 return MDB_SUCCESS;
10657 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
10659 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10662 txn->mt_dbxs[dbi].md_rel = rel;
10663 return MDB_SUCCESS;
10666 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
10668 if (!TXN_DBI_EXIST(txn, dbi, DB_USRVALID))
10671 txn->mt_dbxs[dbi].md_relctx = ctx;
10672 return MDB_SUCCESS;
10676 mdb_env_get_maxkeysize(MDB_env *env)
10678 return ENV_MAXKEY(env);
10682 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
10684 unsigned int i, rdrs;
10687 int rc = 0, first = 1;
10691 if (!env->me_txns) {
10692 return func("(no reader locks)\n", ctx);
10694 rdrs = env->me_txns->mti_numreaders;
10695 mr = env->me_txns->mti_readers;
10696 for (i=0; i<rdrs; i++) {
10697 if (mr[i].mr_pid) {
10698 txnid_t txnid = mr[i].mr_txnid;
10699 sprintf(buf, txnid == (txnid_t)-1 ?
10700 "%10d %"Z"x -\n" : "%10d %"Z"x %"Y"u\n",
10701 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
10704 rc = func(" pid thread txnid\n", ctx);
10708 rc = func(buf, ctx);
10714 rc = func("(no active readers)\n", ctx);
10719 /** Insert pid into list if not already present.
10720 * return -1 if already present.
10723 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
10725 /* binary search of pid in list */
10727 unsigned cursor = 1;
10729 unsigned n = ids[0];
10732 unsigned pivot = n >> 1;
10733 cursor = base + pivot + 1;
10734 val = pid - ids[cursor];
10739 } else if ( val > 0 ) {
10744 /* found, so it's a duplicate */
10753 for (n = ids[0]; n > cursor; n--)
10760 mdb_reader_check(MDB_env *env, int *dead)
10766 return env->me_txns ? mdb_reader_check0(env, 0, dead) : MDB_SUCCESS;
10769 /** As #mdb_reader_check(). rlocked = <caller locked the reader mutex>. */
10771 mdb_reader_check0(MDB_env *env, int rlocked, int *dead)
10773 mdb_mutexref_t rmutex = rlocked ? NULL : env->me_rmutex;
10774 unsigned int i, j, rdrs;
10776 MDB_PID_T *pids, pid;
10777 int rc = MDB_SUCCESS, count = 0;
10779 rdrs = env->me_txns->mti_numreaders;
10780 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
10784 mr = env->me_txns->mti_readers;
10785 for (i=0; i<rdrs; i++) {
10786 pid = mr[i].mr_pid;
10787 if (pid && pid != env->me_pid) {
10788 if (mdb_pid_insert(pids, pid) == 0) {
10789 if (!mdb_reader_pid(env, Pidcheck, pid)) {
10790 /* Stale reader found */
10793 if ((rc = LOCK_MUTEX0(rmutex)) != 0) {
10794 if ((rc = mdb_mutex_failed(env, rmutex, rc)))
10796 rdrs = 0; /* the above checked all readers */
10798 /* Recheck, a new process may have reused pid */
10799 if (mdb_reader_pid(env, Pidcheck, pid))
10803 for (; j<rdrs; j++)
10804 if (mr[j].mr_pid == pid) {
10805 DPRINTF(("clear stale reader pid %u txn %"Y"d",
10806 (unsigned) pid, mr[j].mr_txnid));
10811 UNLOCK_MUTEX(rmutex);
10822 #ifdef MDB_ROBUST_SUPPORTED
10823 /** Handle #LOCK_MUTEX0() failure.
10824 * Try to repair the lock file if the mutex owner died.
10825 * @param[in] env the environment handle
10826 * @param[in] mutex LOCK_MUTEX0() mutex
10827 * @param[in] rc LOCK_MUTEX0() error (nonzero)
10828 * @return 0 on success with the mutex locked, or an error code on failure.
10831 mdb_mutex_failed(MDB_env *env, mdb_mutexref_t mutex, int rc)
10836 if (rc == MDB_OWNERDEAD) {
10837 /* We own the mutex. Clean up after dead previous owner. */
10839 rlocked = (mutex == env->me_rmutex);
10841 /* Keep mti_txnid updated, otherwise next writer can
10842 * overwrite data which latest meta page refers to.
10844 meta = mdb_env_pick_meta(env);
10845 env->me_txns->mti_txnid = meta->mm_txnid;
10846 /* env is hosed if the dead thread was ours */
10848 env->me_flags |= MDB_FATAL_ERROR;
10849 env->me_txn = NULL;
10853 DPRINTF(("%cmutex owner died, %s", (rlocked ? 'r' : 'w'),
10854 (rc ? "this process' env is hosed" : "recovering")));
10855 rc2 = mdb_reader_check0(env, rlocked, NULL);
10857 rc2 = mdb_mutex_consistent(mutex);
10858 if (rc || (rc = rc2)) {
10859 DPRINTF(("LOCK_MUTEX recovery failed, %s", mdb_strerror(rc)));
10860 UNLOCK_MUTEX(mutex);
10866 DPRINTF(("LOCK_MUTEX failed, %s", mdb_strerror(rc)));
10871 #endif /* MDB_ROBUST_SUPPORTED */
10874 #if defined(_WIN32)
10875 static int utf8_to_utf16(const char *src, int srcsize, wchar_t **dst, int *dstsize)
10879 need = MultiByteToWideChar(CP_UTF8, 0, src, srcsize, NULL, 0);
10880 if (need == 0xFFFD)
10884 result = malloc(sizeof(wchar_t) * need);
10887 MultiByteToWideChar(CP_UTF8, 0, src, srcsize, result, need);
10893 #endif /* defined(_WIN32) */