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-2014 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.
41 /** getpid() returns int; MinGW defines pid_t but MinGW64 typedefs it
42 * as int64 which is wrong. MSVC doesn't define it at all, so just
46 #define MDB_THR_T DWORD
47 #include <sys/types.h>
50 # include <sys/param.h>
52 # define LITTLE_ENDIAN 1234
53 # define BIG_ENDIAN 4321
54 # define BYTE_ORDER LITTLE_ENDIAN
56 # define SSIZE_MAX INT_MAX
60 #include <sys/types.h>
62 #define MDB_PID_T pid_t
63 #define MDB_THR_T pthread_t
64 #include <sys/param.h>
67 #ifdef HAVE_SYS_FILE_H
73 #if defined(__mips) && defined(__linux)
74 /* MIPS has cache coherency issues, requires explicit cache control */
75 #include <asm/cachectl.h>
76 extern int cacheflush(char *addr, int nbytes, int cache);
77 #define CACHEFLUSH(addr, bytes, cache) cacheflush(addr, bytes, cache)
79 #define CACHEFLUSH(addr, bytes, cache)
93 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
94 #include <netinet/in.h>
95 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
98 #if defined(__APPLE__) || defined (BSD)
99 # define MDB_USE_POSIX_SEM 1
100 # define MDB_FDATASYNC fsync
101 #elif defined(ANDROID)
102 # define MDB_FDATASYNC fsync
107 #ifdef MDB_USE_POSIX_SEM
108 # define MDB_USE_HASH 1
109 #include <semaphore.h>
114 #include <valgrind/memcheck.h>
115 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
116 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
117 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
118 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
119 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
121 #define VGMEMP_CREATE(h,r,z)
122 #define VGMEMP_ALLOC(h,a,s)
123 #define VGMEMP_FREE(h,a)
124 #define VGMEMP_DESTROY(h)
125 #define VGMEMP_DEFINED(a,s)
129 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
130 /* Solaris just defines one or the other */
131 # define LITTLE_ENDIAN 1234
132 # define BIG_ENDIAN 4321
133 # ifdef _LITTLE_ENDIAN
134 # define BYTE_ORDER LITTLE_ENDIAN
136 # define BYTE_ORDER BIG_ENDIAN
139 # define BYTE_ORDER __BYTE_ORDER
143 #ifndef LITTLE_ENDIAN
144 #define LITTLE_ENDIAN __LITTLE_ENDIAN
147 #define BIG_ENDIAN __BIG_ENDIAN
150 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
151 #define MISALIGNED_OK 1
157 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
158 # error "Unknown or unsupported endianness (BYTE_ORDER)"
159 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
160 # error "Two's complement, reasonably sized integer types, please"
164 /** Put infrequently used env functions in separate section */
166 # define ESECT __attribute__ ((section("__TEXT,text_env")))
168 # define ESECT __attribute__ ((section("text_env")))
174 /** @defgroup internal LMDB Internals
177 /** @defgroup compat Compatibility Macros
178 * A bunch of macros to minimize the amount of platform-specific ifdefs
179 * needed throughout the rest of the code. When the features this library
180 * needs are similar enough to POSIX to be hidden in a one-or-two line
181 * replacement, this macro approach is used.
185 /** Features under development */
190 /** Wrapper around __func__, which is a C99 feature */
191 #if __STDC_VERSION__ >= 199901L
192 # define mdb_func_ __func__
193 #elif __GNUC__ >= 2 || _MSC_VER >= 1300
194 # define mdb_func_ __FUNCTION__
196 /* If a debug message says <mdb_unknown>(), update the #if statements above */
197 # define mdb_func_ "<mdb_unknown>"
201 #define MDB_USE_HASH 1
202 #define MDB_PIDLOCK 0
203 #define THREAD_RET DWORD
204 #define pthread_t HANDLE
205 #define pthread_mutex_t HANDLE
206 #define pthread_cond_t HANDLE
207 #define pthread_key_t DWORD
208 #define pthread_self() GetCurrentThreadId()
209 #define pthread_key_create(x,y) \
210 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
211 #define pthread_key_delete(x) TlsFree(x)
212 #define pthread_getspecific(x) TlsGetValue(x)
213 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
214 #define pthread_mutex_unlock(x) ReleaseMutex(*x)
215 #define pthread_mutex_lock(x) WaitForSingleObject(*x, INFINITE)
216 #define pthread_cond_signal(x) SetEvent(*x)
217 #define pthread_cond_wait(cond,mutex) do{SignalObjectAndWait(*mutex, *cond, INFINITE, FALSE); WaitForSingleObject(*mutex, INFINITE);}while(0)
218 #define THREAD_CREATE(thr,start,arg) thr=CreateThread(NULL,0,start,arg,0,NULL)
219 #define THREAD_FINISH(thr) WaitForSingleObject(thr, INFINITE)
220 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_rmutex)
221 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_rmutex)
222 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_wmutex)
223 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_wmutex)
224 #define getpid() GetCurrentProcessId()
225 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
226 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
227 #define ErrCode() GetLastError()
228 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
229 #define close(fd) (CloseHandle(fd) ? 0 : -1)
230 #define munmap(ptr,len) UnmapViewOfFile(ptr)
231 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
232 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
234 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
238 #define THREAD_RET void *
239 #define THREAD_CREATE(thr,start,arg) pthread_create(&thr,NULL,start,arg)
240 #define THREAD_FINISH(thr) pthread_join(thr,NULL)
241 #define Z "z" /**< printf format modifier for size_t */
243 /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
244 #define MDB_PIDLOCK 1
246 #ifdef MDB_USE_POSIX_SEM
248 #define LOCK_MUTEX_R(env) mdb_sem_wait((env)->me_rmutex)
249 #define UNLOCK_MUTEX_R(env) sem_post((env)->me_rmutex)
250 #define LOCK_MUTEX_W(env) mdb_sem_wait((env)->me_wmutex)
251 #define UNLOCK_MUTEX_W(env) sem_post((env)->me_wmutex)
254 mdb_sem_wait(sem_t *sem)
257 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
262 /** Lock the reader mutex.
264 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
265 /** Unlock the reader mutex.
267 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
269 /** Lock the writer mutex.
270 * Only a single write transaction is allowed at a time. Other writers
271 * will block waiting for this mutex.
273 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
274 /** Unlock the writer mutex.
276 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
277 #endif /* MDB_USE_POSIX_SEM */
279 /** Get the error code for the last failed system function.
281 #define ErrCode() errno
283 /** An abstraction for a file handle.
284 * On POSIX systems file handles are small integers. On Windows
285 * they're opaque pointers.
289 /** A value for an invalid file handle.
290 * Mainly used to initialize file variables and signify that they are
293 #define INVALID_HANDLE_VALUE (-1)
295 /** Get the size of a memory page for the system.
296 * This is the basic size that the platform's memory manager uses, and is
297 * fundamental to the use of memory-mapped files.
299 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
302 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
305 #define MNAME_LEN (sizeof(pthread_mutex_t))
311 /** A flag for opening a file and requesting synchronous data writes.
312 * This is only used when writing a meta page. It's not strictly needed;
313 * we could just do a normal write and then immediately perform a flush.
314 * But if this flag is available it saves us an extra system call.
316 * @note If O_DSYNC is undefined but exists in /usr/include,
317 * preferably set some compiler flag to get the definition.
318 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
321 # define MDB_DSYNC O_DSYNC
325 /** Function for flushing the data of a file. Define this to fsync
326 * if fdatasync() is not supported.
328 #ifndef MDB_FDATASYNC
329 # define MDB_FDATASYNC fdatasync
333 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
344 /** A page number in the database.
345 * Note that 64 bit page numbers are overkill, since pages themselves
346 * already represent 12-13 bits of addressable memory, and the OS will
347 * always limit applications to a maximum of 63 bits of address space.
349 * @note In the #MDB_node structure, we only store 48 bits of this value,
350 * which thus limits us to only 60 bits of addressable data.
352 typedef MDB_ID pgno_t;
354 /** A transaction ID.
355 * See struct MDB_txn.mt_txnid for details.
357 typedef MDB_ID txnid_t;
359 /** @defgroup debug Debug Macros
363 /** Enable debug output. Needs variable argument macros (a C99 feature).
364 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
365 * read from and written to the database (used for free space management).
371 static int mdb_debug;
372 static txnid_t mdb_debug_start;
374 /** Print a debug message with printf formatting.
375 * Requires double parenthesis around 2 or more args.
377 # define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
378 # define DPRINTF0(fmt, ...) \
379 fprintf(stderr, "%s:%d " fmt "\n", mdb_func_, __LINE__, __VA_ARGS__)
381 # define DPRINTF(args) ((void) 0)
383 /** Print a debug string.
384 * The string is printed literally, with no format processing.
386 #define DPUTS(arg) DPRINTF(("%s", arg))
387 /** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
389 (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
392 /** @brief The maximum size of a database page.
394 * It is 32k or 64k, since value-PAGEBASE must fit in
395 * #MDB_page.%mp_upper.
397 * LMDB will use database pages < OS pages if needed.
398 * That causes more I/O in write transactions: The OS must
399 * know (read) the whole page before writing a partial page.
401 * Note that we don't currently support Huge pages. On Linux,
402 * regular data files cannot use Huge pages, and in general
403 * Huge pages aren't actually pageable. We rely on the OS
404 * demand-pager to read our data and page it out when memory
405 * pressure from other processes is high. So until OSs have
406 * actual paging support for Huge pages, they're not viable.
408 #define MAX_PAGESIZE (PAGEBASE ? 0x10000 : 0x8000)
410 /** The minimum number of keys required in a database page.
411 * Setting this to a larger value will place a smaller bound on the
412 * maximum size of a data item. Data items larger than this size will
413 * be pushed into overflow pages instead of being stored directly in
414 * the B-tree node. This value used to default to 4. With a page size
415 * of 4096 bytes that meant that any item larger than 1024 bytes would
416 * go into an overflow page. That also meant that on average 2-3KB of
417 * each overflow page was wasted space. The value cannot be lower than
418 * 2 because then there would no longer be a tree structure. With this
419 * value, items larger than 2KB will go into overflow pages, and on
420 * average only 1KB will be wasted.
422 #define MDB_MINKEYS 2
424 /** A stamp that identifies a file as an LMDB file.
425 * There's nothing special about this value other than that it is easily
426 * recognizable, and it will reflect any byte order mismatches.
428 #define MDB_MAGIC 0xBEEFC0DE
430 /** The version number for a database's datafile format. */
431 #define MDB_DATA_VERSION ((MDB_DEVEL) ? 999 : 1)
432 /** The version number for a database's lockfile format. */
433 #define MDB_LOCK_VERSION 1
435 /** @brief The max size of a key we can write, or 0 for dynamic max.
437 * Define this as 0 to compute the max from the page size. 511
438 * is default for backwards compat: liblmdb <= 0.9.10 can break
439 * when modifying a DB with keys/dupsort data bigger than its max.
440 * #MDB_DEVEL sets the default to 0.
442 * Data items in an #MDB_DUPSORT database are also limited to
443 * this size, since they're actually keys of a sub-DB. Keys and
444 * #MDB_DUPSORT data items must fit on a node in a regular page.
446 #ifndef MDB_MAXKEYSIZE
447 #define MDB_MAXKEYSIZE ((MDB_DEVEL) ? 0 : 511)
450 /** The maximum size of a key we can write to the environment. */
452 #define ENV_MAXKEY(env) (MDB_MAXKEYSIZE)
454 #define ENV_MAXKEY(env) ((env)->me_maxkey)
457 /** @brief The maximum size of a data item.
459 * We only store a 32 bit value for node sizes.
461 #define MAXDATASIZE 0xffffffffUL
464 /** Key size which fits in a #DKBUF.
467 #define DKBUF_MAXKEYSIZE ((MDB_MAXKEYSIZE) > 0 ? (MDB_MAXKEYSIZE) : 511)
470 * This is used for printing a hex dump of a key's contents.
472 #define DKBUF char kbuf[DKBUF_MAXKEYSIZE*2+1]
473 /** Display a key in hex.
475 * Invoke a function to display a key in hex.
477 #define DKEY(x) mdb_dkey(x, kbuf)
483 /** An invalid page number.
484 * Mainly used to denote an empty tree.
486 #define P_INVALID (~(pgno_t)0)
488 /** Test if the flags \b f are set in a flag word \b w. */
489 #define F_ISSET(w, f) (((w) & (f)) == (f))
491 /** Round \b n up to an even number. */
492 #define EVEN(n) (((n) + 1U) & -2) /* sign-extending -2 to match n+1U */
494 /** Used for offsets within a single page.
495 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
498 typedef uint16_t indx_t;
500 /** Default size of memory map.
501 * This is certainly too small for any actual applications. Apps should always set
502 * the size explicitly using #mdb_env_set_mapsize().
504 #define DEFAULT_MAPSIZE 1048576
506 /** @defgroup readers Reader Lock Table
507 * Readers don't acquire any locks for their data access. Instead, they
508 * simply record their transaction ID in the reader table. The reader
509 * mutex is needed just to find an empty slot in the reader table. The
510 * slot's address is saved in thread-specific data so that subsequent read
511 * transactions started by the same thread need no further locking to proceed.
513 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
515 * No reader table is used if the database is on a read-only filesystem, or
516 * if #MDB_NOLOCK is set.
518 * Since the database uses multi-version concurrency control, readers don't
519 * actually need any locking. This table is used to keep track of which
520 * readers are using data from which old transactions, so that we'll know
521 * when a particular old transaction is no longer in use. Old transactions
522 * that have discarded any data pages can then have those pages reclaimed
523 * for use by a later write transaction.
525 * The lock table is constructed such that reader slots are aligned with the
526 * processor's cache line size. Any slot is only ever used by one thread.
527 * This alignment guarantees that there will be no contention or cache
528 * thrashing as threads update their own slot info, and also eliminates
529 * any need for locking when accessing a slot.
531 * A writer thread will scan every slot in the table to determine the oldest
532 * outstanding reader transaction. Any freed pages older than this will be
533 * reclaimed by the writer. The writer doesn't use any locks when scanning
534 * this table. This means that there's no guarantee that the writer will
535 * see the most up-to-date reader info, but that's not required for correct
536 * operation - all we need is to know the upper bound on the oldest reader,
537 * we don't care at all about the newest reader. So the only consequence of
538 * reading stale information here is that old pages might hang around a
539 * while longer before being reclaimed. That's actually good anyway, because
540 * the longer we delay reclaiming old pages, the more likely it is that a
541 * string of contiguous pages can be found after coalescing old pages from
542 * many old transactions together.
545 /** Number of slots in the reader table.
546 * This value was chosen somewhat arbitrarily. 126 readers plus a
547 * couple mutexes fit exactly into 8KB on my development machine.
548 * Applications should set the table size using #mdb_env_set_maxreaders().
550 #define DEFAULT_READERS 126
552 /** The size of a CPU cache line in bytes. We want our lock structures
553 * aligned to this size to avoid false cache line sharing in the
555 * This value works for most CPUs. For Itanium this should be 128.
561 /** The information we store in a single slot of the reader table.
562 * In addition to a transaction ID, we also record the process and
563 * thread ID that owns a slot, so that we can detect stale information,
564 * e.g. threads or processes that went away without cleaning up.
565 * @note We currently don't check for stale records. We simply re-init
566 * the table when we know that we're the only process opening the
569 typedef struct MDB_rxbody {
570 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
571 * Multiple readers that start at the same time will probably have the
572 * same ID here. Again, it's not important to exclude them from
573 * anything; all we need to know is which version of the DB they
574 * started from so we can avoid overwriting any data used in that
575 * particular version.
578 /** The process ID of the process owning this reader txn. */
580 /** The thread ID of the thread owning this txn. */
584 /** The actual reader record, with cacheline padding. */
585 typedef struct MDB_reader {
588 /** shorthand for mrb_txnid */
589 #define mr_txnid mru.mrx.mrb_txnid
590 #define mr_pid mru.mrx.mrb_pid
591 #define mr_tid mru.mrx.mrb_tid
592 /** cache line alignment */
593 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
597 /** The header for the reader table.
598 * The table resides in a memory-mapped file. (This is a different file
599 * than is used for the main database.)
601 * For POSIX the actual mutexes reside in the shared memory of this
602 * mapped file. On Windows, mutexes are named objects allocated by the
603 * kernel; we store the mutex names in this mapped file so that other
604 * processes can grab them. This same approach is also used on
605 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
606 * process-shared POSIX mutexes. For these cases where a named object
607 * is used, the object name is derived from a 64 bit FNV hash of the
608 * environment pathname. As such, naming collisions are extremely
609 * unlikely. If a collision occurs, the results are unpredictable.
611 typedef struct MDB_txbody {
612 /** Stamp identifying this as an LMDB file. It must be set
615 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
617 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
618 char mtb_rmname[MNAME_LEN];
620 /** Mutex protecting access to this table.
621 * This is the reader lock that #LOCK_MUTEX_R acquires.
623 pthread_mutex_t mtb_mutex;
625 /** The ID of the last transaction committed to the database.
626 * This is recorded here only for convenience; the value can always
627 * be determined by reading the main database meta pages.
630 /** The number of slots that have been used in the reader table.
631 * This always records the maximum count, it is not decremented
632 * when readers release their slots.
634 unsigned mtb_numreaders;
637 /** The actual reader table definition. */
638 typedef struct MDB_txninfo {
641 #define mti_magic mt1.mtb.mtb_magic
642 #define mti_format mt1.mtb.mtb_format
643 #define mti_mutex mt1.mtb.mtb_mutex
644 #define mti_rmname mt1.mtb.mtb_rmname
645 #define mti_txnid mt1.mtb.mtb_txnid
646 #define mti_numreaders mt1.mtb.mtb_numreaders
647 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
650 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
651 char mt2_wmname[MNAME_LEN];
652 #define mti_wmname mt2.mt2_wmname
654 pthread_mutex_t mt2_wmutex;
655 #define mti_wmutex mt2.mt2_wmutex
657 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
659 MDB_reader mti_readers[1];
662 /** Lockfile format signature: version, features and field layout */
663 #define MDB_LOCK_FORMAT \
665 ((MDB_LOCK_VERSION) \
666 /* Flags which describe functionality */ \
667 + (((MDB_PIDLOCK) != 0) << 16)))
670 /** Common header for all page types.
671 * Overflow records occupy a number of contiguous pages with no
672 * headers on any page after the first.
674 typedef struct MDB_page {
675 #define mp_pgno mp_p.p_pgno
676 #define mp_next mp_p.p_next
678 pgno_t p_pgno; /**< page number */
679 struct MDB_page *p_next; /**< for in-memory list of freed pages */
682 /** @defgroup mdb_page Page Flags
684 * Flags for the page headers.
687 #define P_BRANCH 0x01 /**< branch page */
688 #define P_LEAF 0x02 /**< leaf page */
689 #define P_OVERFLOW 0x04 /**< overflow page */
690 #define P_META 0x08 /**< meta page */
691 #define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
692 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
693 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
694 #define P_LOOSE 0x4000 /**< page was dirtied then freed, can be reused */
695 #define P_KEEP 0x8000 /**< leave this page alone during spill */
697 uint16_t mp_flags; /**< @ref mdb_page */
698 #define mp_lower mp_pb.pb.pb_lower
699 #define mp_upper mp_pb.pb.pb_upper
700 #define mp_pages mp_pb.pb_pages
703 indx_t pb_lower; /**< lower bound of free space */
704 indx_t pb_upper; /**< upper bound of free space */
706 uint32_t pb_pages; /**< number of overflow pages */
708 indx_t mp_ptrs[1]; /**< dynamic size */
711 /** Size of the page header, excluding dynamic data at the end */
712 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
714 /** Address of first usable data byte in a page, after the header */
715 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
717 /** ITS#7713, change PAGEBASE to handle 65536 byte pages */
718 #define PAGEBASE ((MDB_DEVEL) ? PAGEHDRSZ : 0)
720 /** Number of nodes on a page */
721 #define NUMKEYS(p) (((p)->mp_lower - (PAGEHDRSZ-PAGEBASE)) >> 1)
723 /** The amount of space remaining in the page */
724 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
726 /** The percentage of space used in the page, in tenths of a percent. */
727 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
728 ((env)->me_psize - PAGEHDRSZ))
729 /** The minimum page fill factor, in tenths of a percent.
730 * Pages emptier than this are candidates for merging.
732 #define FILL_THRESHOLD 250
734 /** Test if a page is a leaf page */
735 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
736 /** Test if a page is a LEAF2 page */
737 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
738 /** Test if a page is a branch page */
739 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
740 /** Test if a page is an overflow page */
741 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
742 /** Test if a page is a sub page */
743 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
745 /** The number of overflow pages needed to store the given size. */
746 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
748 /** Link in #MDB_txn.%mt_loose_pages list */
749 #define NEXT_LOOSE_PAGE(p) (*(MDB_page **)((p) + 2))
751 /** Header for a single key/data pair within a page.
752 * Used in pages of type #P_BRANCH and #P_LEAF without #P_LEAF2.
753 * We guarantee 2-byte alignment for 'MDB_node's.
755 typedef struct MDB_node {
756 /** lo and hi are used for data size on leaf nodes and for
757 * child pgno on branch nodes. On 64 bit platforms, flags
758 * is also used for pgno. (Branch nodes have no flags).
759 * They are in host byte order in case that lets some
760 * accesses be optimized into a 32-bit word access.
762 #if BYTE_ORDER == LITTLE_ENDIAN
763 unsigned short mn_lo, mn_hi; /**< part of data size or pgno */
765 unsigned short mn_hi, mn_lo;
767 /** @defgroup mdb_node Node Flags
769 * Flags for node headers.
772 #define F_BIGDATA 0x01 /**< data put on overflow page */
773 #define F_SUBDATA 0x02 /**< data is a sub-database */
774 #define F_DUPDATA 0x04 /**< data has duplicates */
776 /** valid flags for #mdb_node_add() */
777 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
780 unsigned short mn_flags; /**< @ref mdb_node */
781 unsigned short mn_ksize; /**< key size */
782 char mn_data[1]; /**< key and data are appended here */
785 /** Size of the node header, excluding dynamic data at the end */
786 #define NODESIZE offsetof(MDB_node, mn_data)
788 /** Bit position of top word in page number, for shifting mn_flags */
789 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
791 /** Size of a node in a branch page with a given key.
792 * This is just the node header plus the key, there is no data.
794 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
796 /** Size of a node in a leaf page with a given key and data.
797 * This is node header plus key plus data size.
799 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
801 /** Address of node \b i in page \b p */
802 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i] + PAGEBASE))
804 /** Address of the key for the node */
805 #define NODEKEY(node) (void *)((node)->mn_data)
807 /** Address of the data for a node */
808 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
810 /** Get the page number pointed to by a branch node */
811 #define NODEPGNO(node) \
812 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
813 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
814 /** Set the page number in a branch node */
815 #define SETPGNO(node,pgno) do { \
816 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
817 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
819 /** Get the size of the data in a leaf node */
820 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
821 /** Set the size of the data for a leaf node */
822 #define SETDSZ(node,size) do { \
823 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
824 /** The size of a key in a node */
825 #define NODEKSZ(node) ((node)->mn_ksize)
827 /** Copy a page number from src to dst */
829 #define COPY_PGNO(dst,src) dst = src
831 #if SIZE_MAX > 4294967295UL
832 #define COPY_PGNO(dst,src) do { \
833 unsigned short *s, *d; \
834 s = (unsigned short *)&(src); \
835 d = (unsigned short *)&(dst); \
842 #define COPY_PGNO(dst,src) do { \
843 unsigned short *s, *d; \
844 s = (unsigned short *)&(src); \
845 d = (unsigned short *)&(dst); \
851 /** The address of a key in a LEAF2 page.
852 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
853 * There are no node headers, keys are stored contiguously.
855 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
857 /** Set the \b node's key into \b keyptr, if requested. */
858 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
859 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
861 /** Set the \b node's key into \b key. */
862 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
864 /** Information about a single database in the environment. */
865 typedef struct MDB_db {
866 uint32_t md_pad; /**< also ksize for LEAF2 pages */
867 uint16_t md_flags; /**< @ref mdb_dbi_open */
868 uint16_t md_depth; /**< depth of this tree */
869 pgno_t md_branch_pages; /**< number of internal pages */
870 pgno_t md_leaf_pages; /**< number of leaf pages */
871 pgno_t md_overflow_pages; /**< number of overflow pages */
872 size_t md_entries; /**< number of data items */
873 pgno_t md_root; /**< the root page of this tree */
876 /** mdb_dbi_open flags */
877 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
878 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
879 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
880 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
882 /** Handle for the DB used to track free pages. */
884 /** Handle for the default DB. */
887 /** Meta page content.
888 * A meta page is the start point for accessing a database snapshot.
889 * Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
891 typedef struct MDB_meta {
892 /** Stamp identifying this as an LMDB file. It must be set
895 /** Version number of this lock file. Must be set to #MDB_DATA_VERSION. */
897 void *mm_address; /**< address for fixed mapping */
898 size_t mm_mapsize; /**< size of mmap region */
899 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
900 /** The size of pages used in this DB */
901 #define mm_psize mm_dbs[0].md_pad
902 /** Any persistent environment flags. @ref mdb_env */
903 #define mm_flags mm_dbs[0].md_flags
904 pgno_t mm_last_pg; /**< last used page in file */
905 txnid_t mm_txnid; /**< txnid that committed this page */
908 /** Buffer for a stack-allocated meta page.
909 * The members define size and alignment, and silence type
910 * aliasing warnings. They are not used directly; that could
911 * mean incorrectly using several union members in parallel.
913 typedef union MDB_metabuf {
916 char mm_pad[PAGEHDRSZ];
921 /** Auxiliary DB info.
922 * The information here is mostly static/read-only. There is
923 * only a single copy of this record in the environment.
925 typedef struct MDB_dbx {
926 MDB_val md_name; /**< name of the database */
927 MDB_cmp_func *md_cmp; /**< function for comparing keys */
928 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
929 MDB_rel_func *md_rel; /**< user relocate function */
930 void *md_relctx; /**< user-provided context for md_rel */
933 /** A database transaction.
934 * Every operation requires a transaction handle.
937 MDB_txn *mt_parent; /**< parent of a nested txn */
938 MDB_txn *mt_child; /**< nested txn under this txn */
939 pgno_t mt_next_pgno; /**< next unallocated page */
940 /** The ID of this transaction. IDs are integers incrementing from 1.
941 * Only committed write transactions increment the ID. If a transaction
942 * aborts, the ID may be re-used by the next writer.
945 MDB_env *mt_env; /**< the DB environment */
946 /** The list of pages that became unused during this transaction.
949 /** The list of loose pages that became unused and may be reused
950 * in this transaction, linked through #NEXT_LOOSE_PAGE(page).
952 MDB_page *mt_loose_pgs;
953 /** The sorted list of dirty pages we temporarily wrote to disk
954 * because the dirty list was full. page numbers in here are
955 * shifted left by 1, deleted slots have the LSB set.
957 MDB_IDL mt_spill_pgs;
959 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
961 /** For read txns: This thread/txn's reader table slot, or NULL. */
964 /** Array of records for each DB known in the environment. */
966 /** Array of MDB_db records for each known DB */
968 /** Array of sequence numbers for each DB handle */
969 unsigned int *mt_dbiseqs;
970 /** @defgroup mt_dbflag Transaction DB Flags
974 #define DB_DIRTY 0x01 /**< DB was modified or is DUPSORT data */
975 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
976 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
977 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
979 /** In write txns, array of cursors for each DB */
980 MDB_cursor **mt_cursors;
981 /** Array of flags for each DB */
982 unsigned char *mt_dbflags;
983 /** Number of DB records in use. This number only ever increments;
984 * we don't decrement it when individual DB handles are closed.
988 /** @defgroup mdb_txn Transaction Flags
992 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
993 #define MDB_TXN_ERROR 0x02 /**< txn is unusable after an error */
994 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
995 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
997 unsigned int mt_flags; /**< @ref mdb_txn */
998 /** #dirty_list room: Array size - \#dirty pages visible to this txn.
999 * Includes ancestor txns' dirty pages not hidden by other txns'
1000 * dirty/spilled pages. Thus commit(nested txn) has room to merge
1001 * dirty_list into mt_parent after freeing hidden mt_parent pages.
1003 unsigned int mt_dirty_room;
1006 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
1007 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
1008 * raise this on a 64 bit machine.
1010 #define CURSOR_STACK 32
1014 /** Cursors are used for all DB operations.
1015 * A cursor holds a path of (page pointer, key index) from the DB
1016 * root to a position in the DB, plus other state. #MDB_DUPSORT
1017 * cursors include an xcursor to the current data item. Write txns
1018 * track their cursors and keep them up to date when data moves.
1019 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
1020 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
1023 /** Next cursor on this DB in this txn */
1024 MDB_cursor *mc_next;
1025 /** Backup of the original cursor if this cursor is a shadow */
1026 MDB_cursor *mc_backup;
1027 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
1028 struct MDB_xcursor *mc_xcursor;
1029 /** The transaction that owns this cursor */
1031 /** The database handle this cursor operates on */
1033 /** The database record for this cursor */
1035 /** The database auxiliary record for this cursor */
1037 /** The @ref mt_dbflag for this database */
1038 unsigned char *mc_dbflag;
1039 unsigned short mc_snum; /**< number of pushed pages */
1040 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
1041 /** @defgroup mdb_cursor Cursor Flags
1043 * Cursor state flags.
1046 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
1047 #define C_EOF 0x02 /**< No more data */
1048 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
1049 #define C_DEL 0x08 /**< last op was a cursor_del */
1050 #define C_SPLITTING 0x20 /**< Cursor is in page_split */
1051 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
1053 unsigned int mc_flags; /**< @ref mdb_cursor */
1054 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
1055 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
1058 /** Context for sorted-dup records.
1059 * We could have gone to a fully recursive design, with arbitrarily
1060 * deep nesting of sub-databases. But for now we only handle these
1061 * levels - main DB, optional sub-DB, sorted-duplicate DB.
1063 typedef struct MDB_xcursor {
1064 /** A sub-cursor for traversing the Dup DB */
1065 MDB_cursor mx_cursor;
1066 /** The database record for this Dup DB */
1068 /** The auxiliary DB record for this Dup DB */
1070 /** The @ref mt_dbflag for this Dup DB */
1071 unsigned char mx_dbflag;
1074 /** State of FreeDB old pages, stored in the MDB_env */
1075 typedef struct MDB_pgstate {
1076 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
1077 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
1080 /** The database environment. */
1082 HANDLE me_fd; /**< The main data file */
1083 HANDLE me_lfd; /**< The lock file */
1084 HANDLE me_mfd; /**< just for writing the meta pages */
1085 /** Failed to update the meta page. Probably an I/O error. */
1086 #define MDB_FATAL_ERROR 0x80000000U
1087 /** Some fields are initialized. */
1088 #define MDB_ENV_ACTIVE 0x20000000U
1089 /** me_txkey is set */
1090 #define MDB_ENV_TXKEY 0x10000000U
1091 uint32_t me_flags; /**< @ref mdb_env */
1092 unsigned int me_psize; /**< DB page size, inited from me_os_psize */
1093 unsigned int me_os_psize; /**< OS page size, from #GET_PAGESIZE */
1094 unsigned int me_maxreaders; /**< size of the reader table */
1095 unsigned int me_numreaders; /**< max numreaders set by this env */
1096 MDB_dbi me_numdbs; /**< number of DBs opened */
1097 MDB_dbi me_maxdbs; /**< size of the DB table */
1098 MDB_PID_T me_pid; /**< process ID of this env */
1099 char *me_path; /**< path to the DB files */
1100 char *me_map; /**< the memory map of the data file */
1101 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1102 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
1103 void *me_pbuf; /**< scratch area for DUPSORT put() */
1104 MDB_txn *me_txn; /**< current write transaction */
1105 size_t me_mapsize; /**< size of the data memory map */
1106 off_t me_size; /**< current file size */
1107 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1108 MDB_dbx *me_dbxs; /**< array of static DB info */
1109 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1110 unsigned int *me_dbiseqs; /**< array of dbi sequence numbers */
1111 pthread_key_t me_txkey; /**< thread-key for readers */
1112 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1113 # define me_pglast me_pgstate.mf_pglast
1114 # define me_pghead me_pgstate.mf_pghead
1115 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1116 /** IDL of pages that became unused in a write txn */
1117 MDB_IDL me_free_pgs;
1118 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1119 MDB_ID2L me_dirty_list;
1120 /** Max number of freelist items that can fit in a single overflow page */
1122 /** Max size of a node on a page */
1123 unsigned int me_nodemax;
1124 #if !(MDB_MAXKEYSIZE)
1125 unsigned int me_maxkey; /**< max size of a key */
1127 int me_live_reader; /**< have liveness lock in reader table */
1129 int me_pidquery; /**< Used in OpenProcess */
1130 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
1132 #elif defined(MDB_USE_POSIX_SEM)
1133 sem_t *me_rmutex; /* Shared mutexes are not supported */
1136 void *me_userctx; /**< User-settable context */
1137 MDB_assert_func *me_assert_func; /**< Callback for assertion failures */
1140 /** Nested transaction */
1141 typedef struct MDB_ntxn {
1142 MDB_txn mnt_txn; /**< the transaction */
1143 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1146 /** max number of pages to commit in one writev() call */
1147 #define MDB_COMMIT_PAGES 64
1148 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1149 #undef MDB_COMMIT_PAGES
1150 #define MDB_COMMIT_PAGES IOV_MAX
1153 /** max bytes to write in one call */
1154 #define MAX_WRITE (0x80000000U >> (sizeof(ssize_t) == 4))
1156 /** Check \b txn and \b dbi arguments to a function */
1157 #define TXN_DBI_EXIST(txn, dbi) \
1158 ((txn) && (dbi) < (txn)->mt_numdbs && ((txn)->mt_dbflags[dbi] & DB_VALID))
1160 /** Check for misused \b dbi handles */
1161 #define TXN_DBI_CHANGED(txn, dbi) \
1162 ((txn)->mt_dbiseqs[dbi] != (txn)->mt_env->me_dbiseqs[dbi])
1164 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1165 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1166 static int mdb_page_touch(MDB_cursor *mc);
1168 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp, int *lvl);
1169 static int mdb_page_search_root(MDB_cursor *mc,
1170 MDB_val *key, int modify);
1171 #define MDB_PS_MODIFY 1
1172 #define MDB_PS_ROOTONLY 2
1173 #define MDB_PS_FIRST 4
1174 #define MDB_PS_LAST 8
1175 static int mdb_page_search(MDB_cursor *mc,
1176 MDB_val *key, int flags);
1177 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1179 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1180 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1181 pgno_t newpgno, unsigned int nflags);
1183 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1184 static int mdb_env_pick_meta(const MDB_env *env);
1185 static int mdb_env_write_meta(MDB_txn *txn);
1186 #if !(defined(_WIN32) || defined(MDB_USE_POSIX_SEM)) /* Drop unused excl arg */
1187 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1189 static void mdb_env_close0(MDB_env *env, int excl);
1191 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1192 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1193 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1194 static void mdb_node_del(MDB_cursor *mc, int ksize);
1195 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1196 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
1197 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1198 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1199 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1201 static int mdb_rebalance(MDB_cursor *mc);
1202 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1204 static void mdb_cursor_pop(MDB_cursor *mc);
1205 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1207 static int mdb_cursor_del0(MDB_cursor *mc);
1208 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data, unsigned flags);
1209 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1210 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1211 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1212 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1214 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1215 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1217 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1218 static void mdb_xcursor_init0(MDB_cursor *mc);
1219 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1221 static int mdb_drop0(MDB_cursor *mc, int subs);
1222 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1225 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1229 static SECURITY_DESCRIPTOR mdb_null_sd;
1230 static SECURITY_ATTRIBUTES mdb_all_sa;
1231 static int mdb_sec_inited;
1234 /** Return the library version info. */
1236 mdb_version(int *major, int *minor, int *patch)
1238 if (major) *major = MDB_VERSION_MAJOR;
1239 if (minor) *minor = MDB_VERSION_MINOR;
1240 if (patch) *patch = MDB_VERSION_PATCH;
1241 return MDB_VERSION_STRING;
1244 /** Table of descriptions for LMDB @ref errors */
1245 static char *const mdb_errstr[] = {
1246 "MDB_KEYEXIST: Key/data pair already exists",
1247 "MDB_NOTFOUND: No matching key/data pair found",
1248 "MDB_PAGE_NOTFOUND: Requested page not found",
1249 "MDB_CORRUPTED: Located page was wrong type",
1250 "MDB_PANIC: Update of meta page failed",
1251 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1252 "MDB_INVALID: File is not an LMDB file",
1253 "MDB_MAP_FULL: Environment mapsize limit reached",
1254 "MDB_DBS_FULL: Environment maxdbs limit reached",
1255 "MDB_READERS_FULL: Environment maxreaders limit reached",
1256 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1257 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1258 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1259 "MDB_PAGE_FULL: Internal error - page has no more space",
1260 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1261 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1262 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1263 "MDB_BAD_TXN: Transaction cannot recover - it must be aborted",
1264 "MDB_BAD_VALSIZE: Unsupported size of key/DB name/data, or wrong DUPFIXED size",
1265 "MDB_BAD_DBI: The specified DBI handle was closed/changed unexpectedly",
1269 mdb_strerror(int err)
1272 /** HACK: pad 4KB on stack over the buf. Return system msgs in buf.
1273 * This works as long as no function between the call to mdb_strerror
1274 * and the actual use of the message uses more than 4K of stack.
1277 char buf[1024], *ptr = buf;
1281 return ("Successful return: 0");
1283 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1284 i = err - MDB_KEYEXIST;
1285 return mdb_errstr[i];
1289 /* These are the C-runtime error codes we use. The comment indicates
1290 * their numeric value, and the Win32 error they would correspond to
1291 * if the error actually came from a Win32 API. A major mess, we should
1292 * have used LMDB-specific error codes for everything.
1295 case ENOENT: /* 2, FILE_NOT_FOUND */
1296 case EIO: /* 5, ACCESS_DENIED */
1297 case ENOMEM: /* 12, INVALID_ACCESS */
1298 case EACCES: /* 13, INVALID_DATA */
1299 case EBUSY: /* 16, CURRENT_DIRECTORY */
1300 case EINVAL: /* 22, BAD_COMMAND */
1301 case ENOSPC: /* 28, OUT_OF_PAPER */
1302 return strerror(err);
1307 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1308 FORMAT_MESSAGE_IGNORE_INSERTS,
1309 NULL, err, 0, ptr, sizeof(buf), pad);
1312 return strerror(err);
1316 /** assert(3) variant in cursor context */
1317 #define mdb_cassert(mc, expr) mdb_assert0((mc)->mc_txn->mt_env, expr, #expr)
1318 /** assert(3) variant in transaction context */
1319 #define mdb_tassert(mc, expr) mdb_assert0((txn)->mt_env, expr, #expr)
1320 /** assert(3) variant in environment context */
1321 #define mdb_eassert(env, expr) mdb_assert0(env, expr, #expr)
1324 # define mdb_assert0(env, expr, expr_txt) ((expr) ? (void)0 : \
1325 mdb_assert_fail(env, expr_txt, mdb_func_, __FILE__, __LINE__))
1328 mdb_assert_fail(MDB_env *env, const char *expr_txt,
1329 const char *func, const char *file, int line)
1332 sprintf(buf, "%.100s:%d: Assertion '%.200s' failed in %.40s()",
1333 file, line, expr_txt, func);
1334 if (env->me_assert_func)
1335 env->me_assert_func(env, buf);
1336 fprintf(stderr, "%s\n", buf);
1340 # define mdb_assert0(env, expr, expr_txt) ((void) 0)
1344 /** Return the page number of \b mp which may be sub-page, for debug output */
1346 mdb_dbg_pgno(MDB_page *mp)
1349 COPY_PGNO(ret, mp->mp_pgno);
1353 /** Display a key in hexadecimal and return the address of the result.
1354 * @param[in] key the key to display
1355 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1356 * @return The key in hexadecimal form.
1359 mdb_dkey(MDB_val *key, char *buf)
1362 unsigned char *c = key->mv_data;
1368 if (key->mv_size > DKBUF_MAXKEYSIZE)
1369 return "MDB_MAXKEYSIZE";
1370 /* may want to make this a dynamic check: if the key is mostly
1371 * printable characters, print it as-is instead of converting to hex.
1375 for (i=0; i<key->mv_size; i++)
1376 ptr += sprintf(ptr, "%02x", *c++);
1378 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1384 mdb_leafnode_type(MDB_node *n)
1386 static char *const tp[2][2] = {{"", ": DB"}, {": sub-page", ": sub-DB"}};
1387 return F_ISSET(n->mn_flags, F_BIGDATA) ? ": overflow page" :
1388 tp[F_ISSET(n->mn_flags, F_DUPDATA)][F_ISSET(n->mn_flags, F_SUBDATA)];
1391 /** Display all the keys in the page. */
1393 mdb_page_list(MDB_page *mp)
1395 pgno_t pgno = mdb_dbg_pgno(mp);
1396 const char *type, *state = (mp->mp_flags & P_DIRTY) ? ", dirty" : "";
1398 unsigned int i, nkeys, nsize, total = 0;
1402 switch (mp->mp_flags & (P_BRANCH|P_LEAF|P_LEAF2|P_META|P_OVERFLOW|P_SUBP)) {
1403 case P_BRANCH: type = "Branch page"; break;
1404 case P_LEAF: type = "Leaf page"; break;
1405 case P_LEAF|P_SUBP: type = "Sub-page"; break;
1406 case P_LEAF|P_LEAF2: type = "LEAF2 page"; break;
1407 case P_LEAF|P_LEAF2|P_SUBP: type = "LEAF2 sub-page"; break;
1409 fprintf(stderr, "Overflow page %"Z"u pages %u%s\n",
1410 pgno, mp->mp_pages, state);
1413 fprintf(stderr, "Meta-page %"Z"u txnid %"Z"u\n",
1414 pgno, ((MDB_meta *)METADATA(mp))->mm_txnid);
1417 fprintf(stderr, "Bad page %"Z"u flags 0x%u\n", pgno, mp->mp_flags);
1421 nkeys = NUMKEYS(mp);
1422 fprintf(stderr, "%s %"Z"u numkeys %d%s\n", type, pgno, nkeys, state);
1424 for (i=0; i<nkeys; i++) {
1425 if (IS_LEAF2(mp)) { /* LEAF2 pages have no mp_ptrs[] or node headers */
1426 key.mv_size = nsize = mp->mp_pad;
1427 key.mv_data = LEAF2KEY(mp, i, nsize);
1429 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1432 node = NODEPTR(mp, i);
1433 key.mv_size = node->mn_ksize;
1434 key.mv_data = node->mn_data;
1435 nsize = NODESIZE + key.mv_size;
1436 if (IS_BRANCH(mp)) {
1437 fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
1441 if (F_ISSET(node->mn_flags, F_BIGDATA))
1442 nsize += sizeof(pgno_t);
1444 nsize += NODEDSZ(node);
1446 nsize += sizeof(indx_t);
1447 fprintf(stderr, "key %d: nsize %d, %s%s\n",
1448 i, nsize, DKEY(&key), mdb_leafnode_type(node));
1450 total = EVEN(total);
1452 fprintf(stderr, "Total: header %d + contents %d + unused %d\n",
1453 IS_LEAF2(mp) ? PAGEHDRSZ : PAGEBASE + mp->mp_lower, total, SIZELEFT(mp));
1457 mdb_cursor_chk(MDB_cursor *mc)
1463 if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1464 for (i=0; i<mc->mc_top; i++) {
1466 node = NODEPTR(mp, mc->mc_ki[i]);
1467 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1470 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1476 /** Count all the pages in each DB and in the freelist
1477 * and make sure it matches the actual number of pages
1479 * All named DBs must be open for a correct count.
1481 static void mdb_audit(MDB_txn *txn)
1485 MDB_ID freecount, count;
1490 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1491 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1492 freecount += *(MDB_ID *)data.mv_data;
1493 mdb_tassert(txn, rc == MDB_NOTFOUND);
1496 for (i = 0; i<txn->mt_numdbs; i++) {
1498 if (!(txn->mt_dbflags[i] & DB_VALID))
1500 mdb_cursor_init(&mc, txn, i, &mx);
1501 if (txn->mt_dbs[i].md_root == P_INVALID)
1503 count += txn->mt_dbs[i].md_branch_pages +
1504 txn->mt_dbs[i].md_leaf_pages +
1505 txn->mt_dbs[i].md_overflow_pages;
1506 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1507 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1508 for (; rc == MDB_SUCCESS; rc = mdb_cursor_sibling(&mc, 1)) {
1511 mp = mc.mc_pg[mc.mc_top];
1512 for (j=0; j<NUMKEYS(mp); j++) {
1513 MDB_node *leaf = NODEPTR(mp, j);
1514 if (leaf->mn_flags & F_SUBDATA) {
1516 memcpy(&db, NODEDATA(leaf), sizeof(db));
1517 count += db.md_branch_pages + db.md_leaf_pages +
1518 db.md_overflow_pages;
1522 mdb_tassert(txn, rc == MDB_NOTFOUND);
1525 if (freecount + count + 2 /* metapages */ != txn->mt_next_pgno) {
1526 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1527 txn->mt_txnid, freecount, count+2, freecount+count+2, txn->mt_next_pgno);
1533 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1535 return txn->mt_dbxs[dbi].md_cmp(a, b);
1539 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1541 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1544 /** Allocate memory for a page.
1545 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1548 mdb_page_malloc(MDB_txn *txn, unsigned num)
1550 MDB_env *env = txn->mt_env;
1551 MDB_page *ret = env->me_dpages;
1552 size_t psize = env->me_psize, sz = psize, off;
1553 /* For ! #MDB_NOMEMINIT, psize counts how much to init.
1554 * For a single page alloc, we init everything after the page header.
1555 * For multi-page, we init the final page; if the caller needed that
1556 * many pages they will be filling in at least up to the last page.
1560 VGMEMP_ALLOC(env, ret, sz);
1561 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1562 env->me_dpages = ret->mp_next;
1565 psize -= off = PAGEHDRSZ;
1570 if ((ret = malloc(sz)) != NULL) {
1571 VGMEMP_ALLOC(env, ret, sz);
1572 if (!(env->me_flags & MDB_NOMEMINIT)) {
1573 memset((char *)ret + off, 0, psize);
1577 txn->mt_flags |= MDB_TXN_ERROR;
1581 /** Free a single page.
1582 * Saves single pages to a list, for future reuse.
1583 * (This is not used for multi-page overflow pages.)
1586 mdb_page_free(MDB_env *env, MDB_page *mp)
1588 mp->mp_next = env->me_dpages;
1589 VGMEMP_FREE(env, mp);
1590 env->me_dpages = mp;
1593 /** Free a dirty page */
1595 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1597 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1598 mdb_page_free(env, dp);
1600 /* large pages just get freed directly */
1601 VGMEMP_FREE(env, dp);
1606 /** Return all dirty pages to dpage list */
1608 mdb_dlist_free(MDB_txn *txn)
1610 MDB_env *env = txn->mt_env;
1611 MDB_ID2L dl = txn->mt_u.dirty_list;
1612 unsigned i, n = dl[0].mid;
1614 for (i = 1; i <= n; i++) {
1615 mdb_dpage_free(env, dl[i].mptr);
1620 /** Loosen or free a single page.
1621 * Saves single pages to a list for future reuse
1622 * in this same txn. It has been pulled from the freeDB
1623 * and already resides on the dirty list, but has been
1624 * deleted. Use these pages first before pulling again
1627 * If the page wasn't dirtied in this txn, just add it
1628 * to this txn's free list.
1631 mdb_page_loose(MDB_cursor *mc, MDB_page *mp)
1634 pgno_t pgno = mp->mp_pgno;
1636 if ((mp->mp_flags & P_DIRTY) && mc->mc_dbi != FREE_DBI) {
1637 if (mc->mc_txn->mt_parent) {
1638 MDB_ID2 *dl = mc->mc_txn->mt_u.dirty_list;
1639 /* If txn has a parent, make sure the page is in our
1643 unsigned x = mdb_mid2l_search(dl, pgno);
1644 if (x <= dl[0].mid && dl[x].mid == pgno) {
1645 if (mp != dl[x].mptr) { /* bad cursor? */
1646 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1647 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
1648 return MDB_CORRUPTED;
1655 /* no parent txn, so it's just ours */
1660 DPRINTF(("loosen db %d page %"Z"u", DDBI(mc),
1662 NEXT_LOOSE_PAGE(mp) = mc->mc_txn->mt_loose_pgs;
1663 mc->mc_txn->mt_loose_pgs = mp;
1664 mp->mp_flags |= P_LOOSE;
1666 int rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, pgno);
1674 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
1675 * @param[in] mc A cursor handle for the current operation.
1676 * @param[in] pflags Flags of the pages to update:
1677 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1678 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
1679 * @return 0 on success, non-zero on failure.
1682 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
1684 enum { Mask = P_SUBP|P_DIRTY|P_LOOSE|P_KEEP };
1685 MDB_txn *txn = mc->mc_txn;
1691 int rc = MDB_SUCCESS, level;
1693 /* Mark pages seen by cursors */
1694 if (mc->mc_flags & C_UNTRACK)
1695 mc = NULL; /* will find mc in mt_cursors */
1696 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1697 for (; mc; mc=mc->mc_next) {
1698 if (!(mc->mc_flags & C_INITIALIZED))
1700 for (m3 = mc;; m3 = &mx->mx_cursor) {
1702 for (j=0; j<m3->mc_snum; j++) {
1704 if ((mp->mp_flags & Mask) == pflags)
1705 mp->mp_flags ^= P_KEEP;
1707 mx = m3->mc_xcursor;
1708 /* Proceed to mx if it is at a sub-database */
1709 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
1711 if (! (mp && (mp->mp_flags & P_LEAF)))
1713 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
1714 if (!(leaf->mn_flags & F_SUBDATA))
1723 /* Mark dirty root pages */
1724 for (i=0; i<txn->mt_numdbs; i++) {
1725 if (txn->mt_dbflags[i] & DB_DIRTY) {
1726 pgno_t pgno = txn->mt_dbs[i].md_root;
1727 if (pgno == P_INVALID)
1729 if ((rc = mdb_page_get(txn, pgno, &dp, &level)) != MDB_SUCCESS)
1731 if ((dp->mp_flags & Mask) == pflags && level <= 1)
1732 dp->mp_flags ^= P_KEEP;
1740 static int mdb_page_flush(MDB_txn *txn, int keep);
1742 /** Spill pages from the dirty list back to disk.
1743 * This is intended to prevent running into #MDB_TXN_FULL situations,
1744 * but note that they may still occur in a few cases:
1745 * 1) our estimate of the txn size could be too small. Currently this
1746 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
1747 * 2) child txns may run out of space if their parents dirtied a
1748 * lot of pages and never spilled them. TODO: we probably should do
1749 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1750 * the parent's dirty_room is below a given threshold.
1752 * Otherwise, if not using nested txns, it is expected that apps will
1753 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1754 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1755 * If the txn never references them again, they can be left alone.
1756 * If the txn only reads them, they can be used without any fuss.
1757 * If the txn writes them again, they can be dirtied immediately without
1758 * going thru all of the work of #mdb_page_touch(). Such references are
1759 * handled by #mdb_page_unspill().
1761 * Also note, we never spill DB root pages, nor pages of active cursors,
1762 * because we'll need these back again soon anyway. And in nested txns,
1763 * we can't spill a page in a child txn if it was already spilled in a
1764 * parent txn. That would alter the parent txns' data even though
1765 * the child hasn't committed yet, and we'd have no way to undo it if
1766 * the child aborted.
1768 * @param[in] m0 cursor A cursor handle identifying the transaction and
1769 * database for which we are checking space.
1770 * @param[in] key For a put operation, the key being stored.
1771 * @param[in] data For a put operation, the data being stored.
1772 * @return 0 on success, non-zero on failure.
1775 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1777 MDB_txn *txn = m0->mc_txn;
1779 MDB_ID2L dl = txn->mt_u.dirty_list;
1780 unsigned int i, j, need;
1783 if (m0->mc_flags & C_SUB)
1786 /* Estimate how much space this op will take */
1787 i = m0->mc_db->md_depth;
1788 /* Named DBs also dirty the main DB */
1789 if (m0->mc_dbi > MAIN_DBI)
1790 i += txn->mt_dbs[MAIN_DBI].md_depth;
1791 /* For puts, roughly factor in the key+data size */
1793 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
1794 i += i; /* double it for good measure */
1797 if (txn->mt_dirty_room > i)
1800 if (!txn->mt_spill_pgs) {
1801 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
1802 if (!txn->mt_spill_pgs)
1805 /* purge deleted slots */
1806 MDB_IDL sl = txn->mt_spill_pgs;
1807 unsigned int num = sl[0];
1809 for (i=1; i<=num; i++) {
1816 /* Preserve pages which may soon be dirtied again */
1817 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
1820 /* Less aggressive spill - we originally spilled the entire dirty list,
1821 * with a few exceptions for cursor pages and DB root pages. But this
1822 * turns out to be a lot of wasted effort because in a large txn many
1823 * of those pages will need to be used again. So now we spill only 1/8th
1824 * of the dirty pages. Testing revealed this to be a good tradeoff,
1825 * better than 1/2, 1/4, or 1/10.
1827 if (need < MDB_IDL_UM_MAX / 8)
1828 need = MDB_IDL_UM_MAX / 8;
1830 /* Save the page IDs of all the pages we're flushing */
1831 /* flush from the tail forward, this saves a lot of shifting later on. */
1832 for (i=dl[0].mid; i && need; i--) {
1833 MDB_ID pn = dl[i].mid << 1;
1835 if (dp->mp_flags & (P_LOOSE|P_KEEP))
1837 /* Can't spill twice, make sure it's not already in a parent's
1840 if (txn->mt_parent) {
1842 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1843 if (tx2->mt_spill_pgs) {
1844 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
1845 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
1846 dp->mp_flags |= P_KEEP;
1854 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
1858 mdb_midl_sort(txn->mt_spill_pgs);
1860 /* Flush the spilled part of dirty list */
1861 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
1864 /* Reset any dirty pages we kept that page_flush didn't see */
1865 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
1868 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
1872 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
1874 mdb_find_oldest(MDB_txn *txn)
1877 txnid_t mr, oldest = txn->mt_txnid - 1;
1878 if (txn->mt_env->me_txns) {
1879 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
1880 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
1891 /** Add a page to the txn's dirty list */
1893 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
1896 int rc, (*insert)(MDB_ID2L, MDB_ID2 *);
1898 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1899 insert = mdb_mid2l_append;
1901 insert = mdb_mid2l_insert;
1903 mid.mid = mp->mp_pgno;
1905 rc = insert(txn->mt_u.dirty_list, &mid);
1906 mdb_tassert(txn, rc == 0);
1907 txn->mt_dirty_room--;
1910 /** Allocate page numbers and memory for writing. Maintain me_pglast,
1911 * me_pghead and mt_next_pgno.
1913 * If there are free pages available from older transactions, they
1914 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
1915 * Do not modify the freedB, just merge freeDB records into me_pghead[]
1916 * and move me_pglast to say which records were consumed. Only this
1917 * function can create me_pghead and move me_pglast/mt_next_pgno.
1918 * @param[in] mc cursor A cursor handle identifying the transaction and
1919 * database for which we are allocating.
1920 * @param[in] num the number of pages to allocate.
1921 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
1922 * will always be satisfied by a single contiguous chunk of memory.
1923 * @return 0 on success, non-zero on failure.
1926 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
1928 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
1929 /* Get at most <Max_retries> more freeDB records once me_pghead
1930 * has enough pages. If not enough, use new pages from the map.
1931 * If <Paranoid> and mc is updating the freeDB, only get new
1932 * records if me_pghead is empty. Then the freelist cannot play
1933 * catch-up with itself by growing while trying to save it.
1935 enum { Paranoid = 1, Max_retries = 500 };
1937 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
1939 int rc, retry = num * 20;
1940 MDB_txn *txn = mc->mc_txn;
1941 MDB_env *env = txn->mt_env;
1942 pgno_t pgno, *mop = env->me_pghead;
1943 unsigned i, j, k, mop_len = mop ? mop[0] : 0, n2 = num-1;
1945 txnid_t oldest = 0, last;
1949 /* If there are any loose pages, just use them */
1950 if (num == 1 && txn->mt_loose_pgs) {
1951 np = txn->mt_loose_pgs;
1952 txn->mt_loose_pgs = NEXT_LOOSE_PAGE(np);
1953 DPRINTF(("db %d use loose page %"Z"u", DDBI(mc),
1961 /* If our dirty list is already full, we can't do anything */
1962 if (txn->mt_dirty_room == 0) {
1967 for (op = MDB_FIRST;; op = MDB_NEXT) {
1970 pgno_t *idl, old_id, new_id;
1972 /* Seek a big enough contiguous page range. Prefer
1973 * pages at the tail, just truncating the list.
1979 if (mop[i-n2] == pgno+n2)
1986 if (op == MDB_FIRST) { /* 1st iteration */
1987 /* Prepare to fetch more and coalesce */
1988 oldest = mdb_find_oldest(txn);
1989 last = env->me_pglast;
1990 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1993 key.mv_data = &last; /* will look up last+1 */
1994 key.mv_size = sizeof(last);
1996 if (Paranoid && mc->mc_dbi == FREE_DBI)
1999 if (Paranoid && retry < 0 && mop_len)
2003 /* Do not fetch more if the record will be too recent */
2006 rc = mdb_cursor_get(&m2, &key, NULL, op);
2008 if (rc == MDB_NOTFOUND)
2012 last = *(txnid_t*)key.mv_data;
2015 np = m2.mc_pg[m2.mc_top];
2016 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
2017 if ((rc = mdb_node_read(txn, leaf, &data)) != MDB_SUCCESS)
2020 idl = (MDB_ID *) data.mv_data;
2023 if (!(env->me_pghead = mop = mdb_midl_alloc(i))) {
2028 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
2030 mop = env->me_pghead;
2032 env->me_pglast = last;
2034 DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
2035 last, txn->mt_dbs[FREE_DBI].md_root, i));
2037 DPRINTF(("IDL %"Z"u", idl[k]));
2039 /* Merge in descending sorted order */
2042 mop[0] = (pgno_t)-1;
2046 for (; old_id < new_id; old_id = mop[--j])
2053 /* Use new pages from the map when nothing suitable in the freeDB */
2055 pgno = txn->mt_next_pgno;
2056 if (pgno + num >= env->me_maxpg) {
2057 DPUTS("DB size maxed out");
2063 if (env->me_flags & MDB_WRITEMAP) {
2064 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
2066 if (!(np = mdb_page_malloc(txn, num))) {
2072 mop[0] = mop_len -= num;
2073 /* Move any stragglers down */
2074 for (j = i-num; j < mop_len; )
2075 mop[++j] = mop[++i];
2077 txn->mt_next_pgno = pgno + num;
2080 mdb_page_dirty(txn, np);
2086 txn->mt_flags |= MDB_TXN_ERROR;
2090 /** Copy the used portions of a non-overflow page.
2091 * @param[in] dst page to copy into
2092 * @param[in] src page to copy from
2093 * @param[in] psize size of a page
2096 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
2098 enum { Align = sizeof(pgno_t) };
2099 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
2101 /* If page isn't full, just copy the used portion. Adjust
2102 * alignment so memcpy may copy words instead of bytes.
2104 if ((unused &= -Align) && !IS_LEAF2(src)) {
2105 upper = (upper + PAGEBASE) & -Align;
2106 memcpy(dst, src, (lower + PAGEBASE + (Align-1)) & -Align);
2107 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
2110 memcpy(dst, src, psize - unused);
2114 /** Pull a page off the txn's spill list, if present.
2115 * If a page being referenced was spilled to disk in this txn, bring
2116 * it back and make it dirty/writable again.
2117 * @param[in] txn the transaction handle.
2118 * @param[in] mp the page being referenced. It must not be dirty.
2119 * @param[out] ret the writable page, if any. ret is unchanged if
2120 * mp wasn't spilled.
2123 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
2125 MDB_env *env = txn->mt_env;
2128 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
2130 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
2131 if (!tx2->mt_spill_pgs)
2133 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
2134 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
2137 if (txn->mt_dirty_room == 0)
2138 return MDB_TXN_FULL;
2139 if (IS_OVERFLOW(mp))
2143 if (env->me_flags & MDB_WRITEMAP) {
2146 np = mdb_page_malloc(txn, num);
2150 memcpy(np, mp, num * env->me_psize);
2152 mdb_page_copy(np, mp, env->me_psize);
2155 /* If in current txn, this page is no longer spilled.
2156 * If it happens to be the last page, truncate the spill list.
2157 * Otherwise mark it as deleted by setting the LSB.
2159 if (x == txn->mt_spill_pgs[0])
2160 txn->mt_spill_pgs[0]--;
2162 txn->mt_spill_pgs[x] |= 1;
2163 } /* otherwise, if belonging to a parent txn, the
2164 * page remains spilled until child commits
2167 mdb_page_dirty(txn, np);
2168 np->mp_flags |= P_DIRTY;
2176 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
2177 * @param[in] mc cursor pointing to the page to be touched
2178 * @return 0 on success, non-zero on failure.
2181 mdb_page_touch(MDB_cursor *mc)
2183 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
2184 MDB_txn *txn = mc->mc_txn;
2185 MDB_cursor *m2, *m3;
2189 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
2190 if (txn->mt_flags & MDB_TXN_SPILLS) {
2192 rc = mdb_page_unspill(txn, mp, &np);
2198 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
2199 (rc = mdb_page_alloc(mc, 1, &np)))
2202 DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
2203 mp->mp_pgno, pgno));
2204 mdb_cassert(mc, mp->mp_pgno != pgno);
2205 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
2206 /* Update the parent page, if any, to point to the new page */
2208 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
2209 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
2210 SETPGNO(node, pgno);
2212 mc->mc_db->md_root = pgno;
2214 } else if (txn->mt_parent && !IS_SUBP(mp)) {
2215 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
2217 /* If txn has a parent, make sure the page is in our
2221 unsigned x = mdb_mid2l_search(dl, pgno);
2222 if (x <= dl[0].mid && dl[x].mid == pgno) {
2223 if (mp != dl[x].mptr) { /* bad cursor? */
2224 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
2225 txn->mt_flags |= MDB_TXN_ERROR;
2226 return MDB_CORRUPTED;
2231 mdb_cassert(mc, dl[0].mid < MDB_IDL_UM_MAX);
2233 np = mdb_page_malloc(txn, 1);
2238 rc = mdb_mid2l_insert(dl, &mid);
2239 mdb_cassert(mc, rc == 0);
2244 mdb_page_copy(np, mp, txn->mt_env->me_psize);
2246 np->mp_flags |= P_DIRTY;
2249 /* Adjust cursors pointing to mp */
2250 mc->mc_pg[mc->mc_top] = np;
2251 m2 = txn->mt_cursors[mc->mc_dbi];
2252 if (mc->mc_flags & C_SUB) {
2253 for (; m2; m2=m2->mc_next) {
2254 m3 = &m2->mc_xcursor->mx_cursor;
2255 if (m3->mc_snum < mc->mc_snum) continue;
2256 if (m3->mc_pg[mc->mc_top] == mp)
2257 m3->mc_pg[mc->mc_top] = np;
2260 for (; m2; m2=m2->mc_next) {
2261 if (m2->mc_snum < mc->mc_snum) continue;
2262 if (m2->mc_pg[mc->mc_top] == mp) {
2263 m2->mc_pg[mc->mc_top] = np;
2264 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
2266 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
2268 MDB_node *leaf = NODEPTR(np, mc->mc_ki[mc->mc_top]);
2269 if (!(leaf->mn_flags & F_SUBDATA))
2270 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
2278 txn->mt_flags |= MDB_TXN_ERROR;
2283 mdb_env_sync(MDB_env *env, int force)
2286 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
2287 if (env->me_flags & MDB_WRITEMAP) {
2288 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
2289 ? MS_ASYNC : MS_SYNC;
2290 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
2293 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
2297 if (MDB_FDATASYNC(env->me_fd))
2304 /** Back up parent txn's cursors, then grab the originals for tracking */
2306 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
2308 MDB_cursor *mc, *bk;
2313 for (i = src->mt_numdbs; --i >= 0; ) {
2314 if ((mc = src->mt_cursors[i]) != NULL) {
2315 size = sizeof(MDB_cursor);
2317 size += sizeof(MDB_xcursor);
2318 for (; mc; mc = bk->mc_next) {
2324 mc->mc_db = &dst->mt_dbs[i];
2325 /* Kill pointers into src - and dst to reduce abuse: The
2326 * user may not use mc until dst ends. Otherwise we'd...
2328 mc->mc_txn = NULL; /* ...set this to dst */
2329 mc->mc_dbflag = NULL; /* ...and &dst->mt_dbflags[i] */
2330 if ((mx = mc->mc_xcursor) != NULL) {
2331 *(MDB_xcursor *)(bk+1) = *mx;
2332 mx->mx_cursor.mc_txn = NULL; /* ...and dst. */
2334 mc->mc_next = dst->mt_cursors[i];
2335 dst->mt_cursors[i] = mc;
2342 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2343 * @param[in] txn the transaction handle.
2344 * @param[in] merge true to keep changes to parent cursors, false to revert.
2345 * @return 0 on success, non-zero on failure.
2348 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2350 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2354 for (i = txn->mt_numdbs; --i >= 0; ) {
2355 for (mc = cursors[i]; mc; mc = next) {
2357 if ((bk = mc->mc_backup) != NULL) {
2359 /* Commit changes to parent txn */
2360 mc->mc_next = bk->mc_next;
2361 mc->mc_backup = bk->mc_backup;
2362 mc->mc_txn = bk->mc_txn;
2363 mc->mc_db = bk->mc_db;
2364 mc->mc_dbflag = bk->mc_dbflag;
2365 if ((mx = mc->mc_xcursor) != NULL)
2366 mx->mx_cursor.mc_txn = bk->mc_txn;
2368 /* Abort nested txn */
2370 if ((mx = mc->mc_xcursor) != NULL)
2371 *mx = *(MDB_xcursor *)(bk+1);
2375 /* Only malloced cursors are permanently tracked. */
2383 #define mdb_txn_reset0(txn, act) mdb_txn_reset0(txn)
2386 mdb_txn_reset0(MDB_txn *txn, const char *act);
2388 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2394 Pidset = F_SETLK, Pidcheck = F_GETLK
2398 /** Set or check a pid lock. Set returns 0 on success.
2399 * Check returns 0 if the process is certainly dead, nonzero if it may
2400 * be alive (the lock exists or an error happened so we do not know).
2402 * On Windows Pidset is a no-op, we merely check for the existence
2403 * of the process with the given pid. On POSIX we use a single byte
2404 * lock on the lockfile, set at an offset equal to the pid.
2407 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, MDB_PID_T pid)
2409 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2412 if (op == Pidcheck) {
2413 h = OpenProcess(env->me_pidquery, FALSE, pid);
2414 /* No documented "no such process" code, but other program use this: */
2416 return ErrCode() != ERROR_INVALID_PARAMETER;
2417 /* A process exists until all handles to it close. Has it exited? */
2418 ret = WaitForSingleObject(h, 0) != 0;
2425 struct flock lock_info;
2426 memset(&lock_info, 0, sizeof(lock_info));
2427 lock_info.l_type = F_WRLCK;
2428 lock_info.l_whence = SEEK_SET;
2429 lock_info.l_start = pid;
2430 lock_info.l_len = 1;
2431 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2432 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2434 } else if ((rc = ErrCode()) == EINTR) {
2442 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2443 * @param[in] txn the transaction handle to initialize
2444 * @return 0 on success, non-zero on failure.
2447 mdb_txn_renew0(MDB_txn *txn)
2449 MDB_env *env = txn->mt_env;
2450 MDB_txninfo *ti = env->me_txns;
2454 int rc, new_notls = 0;
2457 txn->mt_numdbs = env->me_numdbs;
2458 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
2460 if (txn->mt_flags & MDB_TXN_RDONLY) {
2462 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2463 txn->mt_txnid = meta->mm_txnid;
2464 txn->mt_u.reader = NULL;
2466 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2467 pthread_getspecific(env->me_txkey);
2469 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2470 return MDB_BAD_RSLOT;
2472 MDB_PID_T pid = env->me_pid;
2473 MDB_THR_T tid = pthread_self();
2475 if (!env->me_live_reader) {
2476 rc = mdb_reader_pid(env, Pidset, pid);
2479 env->me_live_reader = 1;
2483 nr = ti->mti_numreaders;
2484 for (i=0; i<nr; i++)
2485 if (ti->mti_readers[i].mr_pid == 0)
2487 if (i == env->me_maxreaders) {
2488 UNLOCK_MUTEX_R(env);
2489 return MDB_READERS_FULL;
2491 ti->mti_readers[i].mr_pid = pid;
2492 ti->mti_readers[i].mr_tid = tid;
2494 ti->mti_numreaders = ++nr;
2495 /* Save numreaders for un-mutexed mdb_env_close() */
2496 env->me_numreaders = nr;
2497 UNLOCK_MUTEX_R(env);
2499 r = &ti->mti_readers[i];
2500 new_notls = (env->me_flags & MDB_NOTLS);
2501 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2506 txn->mt_txnid = r->mr_txnid = ti->mti_txnid;
2507 txn->mt_u.reader = r;
2508 meta = env->me_metas[txn->mt_txnid & 1];
2514 txn->mt_txnid = ti->mti_txnid;
2515 meta = env->me_metas[txn->mt_txnid & 1];
2517 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2518 txn->mt_txnid = meta->mm_txnid;
2522 if (txn->mt_txnid == mdb_debug_start)
2525 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2526 txn->mt_u.dirty_list = env->me_dirty_list;
2527 txn->mt_u.dirty_list[0].mid = 0;
2528 txn->mt_free_pgs = env->me_free_pgs;
2529 txn->mt_free_pgs[0] = 0;
2530 txn->mt_spill_pgs = NULL;
2532 memcpy(txn->mt_dbiseqs, env->me_dbiseqs, env->me_maxdbs * sizeof(unsigned int));
2535 /* Copy the DB info and flags */
2536 memcpy(txn->mt_dbs, meta->mm_dbs, 2 * sizeof(MDB_db));
2538 /* Moved to here to avoid a data race in read TXNs */
2539 txn->mt_next_pgno = meta->mm_last_pg+1;
2541 for (i=2; i<txn->mt_numdbs; i++) {
2542 x = env->me_dbflags[i];
2543 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2544 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_STALE : 0;
2546 txn->mt_dbflags[0] = txn->mt_dbflags[1] = DB_VALID;
2548 if (env->me_maxpg < txn->mt_next_pgno) {
2549 mdb_txn_reset0(txn, "renew0-mapfail");
2551 txn->mt_u.reader->mr_pid = 0;
2552 txn->mt_u.reader = NULL;
2554 return MDB_MAP_RESIZED;
2561 mdb_txn_renew(MDB_txn *txn)
2565 if (!txn || txn->mt_dbxs) /* A reset txn has mt_dbxs==NULL */
2568 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
2569 DPUTS("environment had fatal error, must shutdown!");
2573 rc = mdb_txn_renew0(txn);
2574 if (rc == MDB_SUCCESS) {
2575 DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2576 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2577 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2583 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2587 int rc, size, tsize = sizeof(MDB_txn);
2589 if (env->me_flags & MDB_FATAL_ERROR) {
2590 DPUTS("environment had fatal error, must shutdown!");
2593 if ((env->me_flags & MDB_RDONLY) && !(flags & MDB_RDONLY))
2596 /* Nested transactions: Max 1 child, write txns only, no writemap */
2597 if (parent->mt_child ||
2598 (flags & MDB_RDONLY) ||
2599 (parent->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR)) ||
2600 (env->me_flags & MDB_WRITEMAP))
2602 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
2604 tsize = sizeof(MDB_ntxn);
2606 size = tsize + env->me_maxdbs * (sizeof(MDB_db)+1);
2607 if (!(flags & MDB_RDONLY)) {
2608 size += env->me_maxdbs * sizeof(MDB_cursor *);
2609 /* child txns use parent's dbiseqs */
2611 size += env->me_maxdbs * sizeof(unsigned int);
2614 if ((txn = calloc(1, size)) == NULL) {
2615 DPRINTF(("calloc: %s", strerror(errno)));
2618 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2619 if (flags & MDB_RDONLY) {
2620 txn->mt_flags |= MDB_TXN_RDONLY;
2621 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
2622 txn->mt_dbiseqs = env->me_dbiseqs;
2624 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2626 txn->mt_dbiseqs = parent->mt_dbiseqs;
2627 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
2629 txn->mt_dbiseqs = (unsigned int *)(txn->mt_cursors + env->me_maxdbs);
2630 txn->mt_dbflags = (unsigned char *)(txn->mt_dbiseqs + env->me_maxdbs);
2637 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2638 if (!txn->mt_u.dirty_list ||
2639 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2641 free(txn->mt_u.dirty_list);
2645 txn->mt_txnid = parent->mt_txnid;
2646 txn->mt_dirty_room = parent->mt_dirty_room;
2647 txn->mt_u.dirty_list[0].mid = 0;
2648 txn->mt_spill_pgs = NULL;
2649 txn->mt_next_pgno = parent->mt_next_pgno;
2650 parent->mt_child = txn;
2651 txn->mt_parent = parent;
2652 txn->mt_numdbs = parent->mt_numdbs;
2653 txn->mt_flags = parent->mt_flags;
2654 txn->mt_dbxs = parent->mt_dbxs;
2655 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2656 /* Copy parent's mt_dbflags, but clear DB_NEW */
2657 for (i=0; i<txn->mt_numdbs; i++)
2658 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2660 ntxn = (MDB_ntxn *)txn;
2661 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2662 if (env->me_pghead) {
2663 size = MDB_IDL_SIZEOF(env->me_pghead);
2664 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2666 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2671 rc = mdb_cursor_shadow(parent, txn);
2673 mdb_txn_reset0(txn, "beginchild-fail");
2675 rc = mdb_txn_renew0(txn);
2681 DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2682 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2683 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
2690 mdb_txn_env(MDB_txn *txn)
2692 if(!txn) return NULL;
2696 /** Export or close DBI handles opened in this txn. */
2698 mdb_dbis_update(MDB_txn *txn, int keep)
2701 MDB_dbi n = txn->mt_numdbs;
2702 MDB_env *env = txn->mt_env;
2703 unsigned char *tdbflags = txn->mt_dbflags;
2705 for (i = n; --i >= 2;) {
2706 if (tdbflags[i] & DB_NEW) {
2708 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2710 char *ptr = env->me_dbxs[i].md_name.mv_data;
2712 env->me_dbxs[i].md_name.mv_data = NULL;
2713 env->me_dbxs[i].md_name.mv_size = 0;
2714 env->me_dbflags[i] = 0;
2715 env->me_dbiseqs[i]++;
2721 if (keep && env->me_numdbs < n)
2725 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
2726 * May be called twice for readonly txns: First reset it, then abort.
2727 * @param[in] txn the transaction handle to reset
2728 * @param[in] act why the transaction is being reset
2731 mdb_txn_reset0(MDB_txn *txn, const char *act)
2733 MDB_env *env = txn->mt_env;
2735 /* Close any DBI handles opened in this txn */
2736 mdb_dbis_update(txn, 0);
2738 DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2739 act, txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2740 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
2742 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2743 if (txn->mt_u.reader) {
2744 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2745 if (!(env->me_flags & MDB_NOTLS))
2746 txn->mt_u.reader = NULL; /* txn does not own reader */
2748 txn->mt_numdbs = 0; /* close nothing if called again */
2749 txn->mt_dbxs = NULL; /* mark txn as reset */
2751 mdb_cursors_close(txn, 0);
2753 if (!(env->me_flags & MDB_WRITEMAP)) {
2754 mdb_dlist_free(txn);
2756 mdb_midl_free(env->me_pghead);
2758 if (txn->mt_parent) {
2759 txn->mt_parent->mt_child = NULL;
2760 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2761 mdb_midl_free(txn->mt_free_pgs);
2762 mdb_midl_free(txn->mt_spill_pgs);
2763 free(txn->mt_u.dirty_list);
2767 if (mdb_midl_shrink(&txn->mt_free_pgs))
2768 env->me_free_pgs = txn->mt_free_pgs;
2769 env->me_pghead = NULL;
2773 /* The writer mutex was locked in mdb_txn_begin. */
2775 UNLOCK_MUTEX_W(env);
2780 mdb_txn_reset(MDB_txn *txn)
2785 /* This call is only valid for read-only txns */
2786 if (!(txn->mt_flags & MDB_TXN_RDONLY))
2789 mdb_txn_reset0(txn, "reset");
2793 mdb_txn_abort(MDB_txn *txn)
2799 mdb_txn_abort(txn->mt_child);
2801 mdb_txn_reset0(txn, "abort");
2802 /* Free reader slot tied to this txn (if MDB_NOTLS && writable FS) */
2803 if ((txn->mt_flags & MDB_TXN_RDONLY) && txn->mt_u.reader)
2804 txn->mt_u.reader->mr_pid = 0;
2809 /** Save the freelist as of this transaction to the freeDB.
2810 * This changes the freelist. Keep trying until it stabilizes.
2813 mdb_freelist_save(MDB_txn *txn)
2815 /* env->me_pghead[] can grow and shrink during this call.
2816 * env->me_pglast and txn->mt_free_pgs[] can only grow.
2817 * Page numbers cannot disappear from txn->mt_free_pgs[].
2820 MDB_env *env = txn->mt_env;
2821 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
2822 txnid_t pglast = 0, head_id = 0;
2823 pgno_t freecnt = 0, *free_pgs, *mop;
2824 ssize_t head_room = 0, total_room = 0, mop_len, clean_limit;
2826 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
2828 if (env->me_pghead) {
2829 /* Make sure first page of freeDB is touched and on freelist */
2830 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
2831 if (rc && rc != MDB_NOTFOUND)
2835 /* Dispose of loose pages. Usually they will have all
2836 * been used up by the time we get here.
2838 if (txn->mt_loose_pgs) {
2839 MDB_page *mp = txn->mt_loose_pgs;
2840 /* Just return them to freeDB */
2841 if (env->me_pghead) {
2843 mop = env->me_pghead;
2844 for (; mp; mp = NEXT_LOOSE_PAGE(mp)) {
2845 pgno_t pg = mp->mp_pgno;
2847 for (i = mop[0]; i && mop[i] < pg; i--)
2853 /* Oh well, they were wasted. Put on freelist */
2854 for (; mp; mp = NEXT_LOOSE_PAGE(mp)) {
2855 mdb_midl_append(&txn->mt_free_pgs, mp->mp_pgno);
2858 txn->mt_loose_pgs = NULL;
2861 /* MDB_RESERVE cancels meminit in ovpage malloc (when no WRITEMAP) */
2862 clean_limit = (env->me_flags & (MDB_NOMEMINIT|MDB_WRITEMAP))
2863 ? SSIZE_MAX : maxfree_1pg;
2866 /* Come back here after each Put() in case freelist changed */
2871 /* If using records from freeDB which we have not yet
2872 * deleted, delete them and any we reserved for me_pghead.
2874 while (pglast < env->me_pglast) {
2875 rc = mdb_cursor_first(&mc, &key, NULL);
2878 pglast = head_id = *(txnid_t *)key.mv_data;
2879 total_room = head_room = 0;
2880 mdb_tassert(txn, pglast <= env->me_pglast);
2881 rc = mdb_cursor_del(&mc, 0);
2886 /* Save the IDL of pages freed by this txn, to a single record */
2887 if (freecnt < txn->mt_free_pgs[0]) {
2889 /* Make sure last page of freeDB is touched and on freelist */
2890 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
2891 if (rc && rc != MDB_NOTFOUND)
2894 free_pgs = txn->mt_free_pgs;
2895 /* Write to last page of freeDB */
2896 key.mv_size = sizeof(txn->mt_txnid);
2897 key.mv_data = &txn->mt_txnid;
2899 freecnt = free_pgs[0];
2900 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
2901 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2904 /* Retry if mt_free_pgs[] grew during the Put() */
2905 free_pgs = txn->mt_free_pgs;
2906 } while (freecnt < free_pgs[0]);
2907 mdb_midl_sort(free_pgs);
2908 memcpy(data.mv_data, free_pgs, data.mv_size);
2911 unsigned int i = free_pgs[0];
2912 DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
2913 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
2915 DPRINTF(("IDL %"Z"u", free_pgs[i]));
2921 mop = env->me_pghead;
2922 mop_len = mop ? mop[0] : 0;
2924 /* Reserve records for me_pghead[]. Split it if multi-page,
2925 * to avoid searching freeDB for a page range. Use keys in
2926 * range [1,me_pglast]: Smaller than txnid of oldest reader.
2928 if (total_room >= mop_len) {
2929 if (total_room == mop_len || --more < 0)
2931 } else if (head_room >= maxfree_1pg && head_id > 1) {
2932 /* Keep current record (overflow page), add a new one */
2936 /* (Re)write {key = head_id, IDL length = head_room} */
2937 total_room -= head_room;
2938 head_room = mop_len - total_room;
2939 if (head_room > maxfree_1pg && head_id > 1) {
2940 /* Overflow multi-page for part of me_pghead */
2941 head_room /= head_id; /* amortize page sizes */
2942 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
2943 } else if (head_room < 0) {
2944 /* Rare case, not bothering to delete this record */
2947 key.mv_size = sizeof(head_id);
2948 key.mv_data = &head_id;
2949 data.mv_size = (head_room + 1) * sizeof(pgno_t);
2950 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2953 /* IDL is initially empty, zero out at least the length */
2954 pgs = (pgno_t *)data.mv_data;
2955 j = head_room > clean_limit ? head_room : 0;
2959 total_room += head_room;
2962 /* Fill in the reserved me_pghead records */
2968 rc = mdb_cursor_first(&mc, &key, &data);
2969 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
2970 txnid_t id = *(txnid_t *)key.mv_data;
2971 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
2974 mdb_tassert(txn, len >= 0 && id <= env->me_pglast);
2976 if (len > mop_len) {
2978 data.mv_size = (len + 1) * sizeof(MDB_ID);
2980 data.mv_data = mop -= len;
2983 rc = mdb_cursor_put(&mc, &key, &data, MDB_CURRENT);
2985 if (rc || !(mop_len -= len))
2992 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
2993 * @param[in] txn the transaction that's being committed
2994 * @param[in] keep number of initial pages in dirty_list to keep dirty.
2995 * @return 0 on success, non-zero on failure.
2998 mdb_page_flush(MDB_txn *txn, int keep)
3000 MDB_env *env = txn->mt_env;
3001 MDB_ID2L dl = txn->mt_u.dirty_list;
3002 unsigned psize = env->me_psize, j;
3003 int i, pagecount = dl[0].mid, rc;
3004 size_t size = 0, pos = 0;
3006 MDB_page *dp = NULL;
3010 struct iovec iov[MDB_COMMIT_PAGES];
3011 ssize_t wpos = 0, wsize = 0, wres;
3012 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
3018 if (env->me_flags & MDB_WRITEMAP) {
3019 /* Clear dirty flags */
3020 while (++i <= pagecount) {
3022 /* Don't flush this page yet */
3023 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3024 dp->mp_flags &= ~P_KEEP;
3028 dp->mp_flags &= ~P_DIRTY;
3033 /* Write the pages */
3035 if (++i <= pagecount) {
3037 /* Don't flush this page yet */
3038 if (dp->mp_flags & (P_LOOSE|P_KEEP)) {
3039 dp->mp_flags &= ~P_KEEP;
3044 /* clear dirty flag */
3045 dp->mp_flags &= ~P_DIRTY;
3048 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
3053 /* Windows actually supports scatter/gather I/O, but only on
3054 * unbuffered file handles. Since we're relying on the OS page
3055 * cache for all our data, that's self-defeating. So we just
3056 * write pages one at a time. We use the ov structure to set
3057 * the write offset, to at least save the overhead of a Seek
3060 DPRINTF(("committing page %"Z"u", pgno));
3061 memset(&ov, 0, sizeof(ov));
3062 ov.Offset = pos & 0xffffffff;
3063 ov.OffsetHigh = pos >> 16 >> 16;
3064 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
3066 DPRINTF(("WriteFile: %d", rc));
3070 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
3071 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
3073 /* Write previous page(s) */
3074 #ifdef MDB_USE_PWRITEV
3075 wres = pwritev(env->me_fd, iov, n, wpos);
3078 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
3080 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
3082 DPRINTF(("lseek: %s", strerror(rc)));
3085 wres = writev(env->me_fd, iov, n);
3088 if (wres != wsize) {
3091 DPRINTF(("Write error: %s", strerror(rc)));
3093 rc = EIO; /* TODO: Use which error code? */
3094 DPUTS("short write, filesystem full?");
3105 DPRINTF(("committing page %"Z"u", pgno));
3106 next_pos = pos + size;
3107 iov[n].iov_len = size;
3108 iov[n].iov_base = (char *)dp;
3114 /* MIPS has cache coherency issues, this is a no-op everywhere else
3115 * Note: for any size >= on-chip cache size, entire on-chip cache is
3118 CACHEFLUSH(env->me_map, txn->mt_next_pgno * env->me_psize, DCACHE);
3120 for (i = keep; ++i <= pagecount; ) {
3122 /* This is a page we skipped above */
3125 dl[j].mid = dp->mp_pgno;
3128 mdb_dpage_free(env, dp);
3133 txn->mt_dirty_room += i - j;
3139 mdb_txn_commit(MDB_txn *txn)
3145 if (txn == NULL || txn->mt_env == NULL)
3148 if (txn->mt_child) {
3149 rc = mdb_txn_commit(txn->mt_child);
3150 txn->mt_child = NULL;
3157 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3158 mdb_dbis_update(txn, 1);
3159 txn->mt_numdbs = 2; /* so txn_abort() doesn't close any new handles */
3164 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
3165 DPUTS("error flag is set, can't commit");
3167 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
3172 if (txn->mt_parent) {
3173 MDB_txn *parent = txn->mt_parent;
3177 unsigned x, y, len, ps_len;
3179 /* Append our free list to parent's */
3180 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
3183 mdb_midl_free(txn->mt_free_pgs);
3184 /* Failures after this must either undo the changes
3185 * to the parent or set MDB_TXN_ERROR in the parent.
3188 parent->mt_next_pgno = txn->mt_next_pgno;
3189 parent->mt_flags = txn->mt_flags;
3191 /* Merge our cursors into parent's and close them */
3192 mdb_cursors_close(txn, 1);
3194 /* Update parent's DB table. */
3195 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
3196 parent->mt_numdbs = txn->mt_numdbs;
3197 parent->mt_dbflags[0] = txn->mt_dbflags[0];
3198 parent->mt_dbflags[1] = txn->mt_dbflags[1];
3199 for (i=2; i<txn->mt_numdbs; i++) {
3200 /* preserve parent's DB_NEW status */
3201 x = parent->mt_dbflags[i] & DB_NEW;
3202 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
3205 dst = parent->mt_u.dirty_list;
3206 src = txn->mt_u.dirty_list;
3207 /* Remove anything in our dirty list from parent's spill list */
3208 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
3210 pspill[0] = (pgno_t)-1;
3211 /* Mark our dirty pages as deleted in parent spill list */
3212 for (i=0, len=src[0].mid; ++i <= len; ) {
3213 MDB_ID pn = src[i].mid << 1;
3214 while (pn > pspill[x])
3216 if (pn == pspill[x]) {
3221 /* Squash deleted pagenums if we deleted any */
3222 for (x=y; ++x <= ps_len; )
3223 if (!(pspill[x] & 1))
3224 pspill[++y] = pspill[x];
3228 /* Find len = length of merging our dirty list with parent's */
3230 dst[0].mid = 0; /* simplify loops */
3231 if (parent->mt_parent) {
3232 len = x + src[0].mid;
3233 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
3234 for (i = x; y && i; y--) {
3235 pgno_t yp = src[y].mid;
3236 while (yp < dst[i].mid)
3238 if (yp == dst[i].mid) {
3243 } else { /* Simplify the above for single-ancestor case */
3244 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
3246 /* Merge our dirty list with parent's */
3248 for (i = len; y; dst[i--] = src[y--]) {
3249 pgno_t yp = src[y].mid;
3250 while (yp < dst[x].mid)
3251 dst[i--] = dst[x--];
3252 if (yp == dst[x].mid)
3253 free(dst[x--].mptr);
3255 mdb_tassert(txn, i == x);
3257 free(txn->mt_u.dirty_list);
3258 parent->mt_dirty_room = txn->mt_dirty_room;
3259 if (txn->mt_spill_pgs) {
3260 if (parent->mt_spill_pgs) {
3261 /* TODO: Prevent failure here, so parent does not fail */
3262 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
3264 parent->mt_flags |= MDB_TXN_ERROR;
3265 mdb_midl_free(txn->mt_spill_pgs);
3266 mdb_midl_sort(parent->mt_spill_pgs);
3268 parent->mt_spill_pgs = txn->mt_spill_pgs;
3272 /* Append our loose page list to parent's */
3273 for (lp = &parent->mt_loose_pgs; *lp; lp = &NEXT_LOOSE_PAGE(lp))
3275 *lp = txn->mt_loose_pgs;
3277 parent->mt_child = NULL;
3278 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
3283 if (txn != env->me_txn) {
3284 DPUTS("attempt to commit unknown transaction");
3289 mdb_cursors_close(txn, 0);
3291 if (!txn->mt_u.dirty_list[0].mid &&
3292 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
3295 DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
3296 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
3298 /* Update DB root pointers */
3299 if (txn->mt_numdbs > 2) {
3303 data.mv_size = sizeof(MDB_db);
3305 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
3306 for (i = 2; i < txn->mt_numdbs; i++) {
3307 if (txn->mt_dbflags[i] & DB_DIRTY) {
3308 if (TXN_DBI_CHANGED(txn, i)) {
3312 data.mv_data = &txn->mt_dbs[i];
3313 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
3320 rc = mdb_freelist_save(txn);
3324 mdb_midl_free(env->me_pghead);
3325 env->me_pghead = NULL;
3326 if (mdb_midl_shrink(&txn->mt_free_pgs))
3327 env->me_free_pgs = txn->mt_free_pgs;
3333 if ((rc = mdb_page_flush(txn, 0)) ||
3334 (rc = mdb_env_sync(env, 0)) ||
3335 (rc = mdb_env_write_meta(txn)))
3341 mdb_dbis_update(txn, 1);
3344 UNLOCK_MUTEX_W(env);
3354 /** Read the environment parameters of a DB environment before
3355 * mapping it into memory.
3356 * @param[in] env the environment handle
3357 * @param[out] meta address of where to store the meta information
3358 * @return 0 on success, non-zero on failure.
3361 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
3367 enum { Size = sizeof(pbuf) };
3369 /* We don't know the page size yet, so use a minimum value.
3370 * Read both meta pages so we can use the latest one.
3373 for (i=off=0; i<2; i++, off = meta->mm_psize) {
3377 memset(&ov, 0, sizeof(ov));
3379 rc = ReadFile(env->me_fd, &pbuf, Size, &len, &ov) ? (int)len : -1;
3380 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
3383 rc = pread(env->me_fd, &pbuf, Size, off);
3386 if (rc == 0 && off == 0)
3388 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
3389 DPRINTF(("read: %s", mdb_strerror(rc)));
3393 p = (MDB_page *)&pbuf;
3395 if (!F_ISSET(p->mp_flags, P_META)) {
3396 DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
3401 if (m->mm_magic != MDB_MAGIC) {
3402 DPUTS("meta has invalid magic");
3406 if (m->mm_version != MDB_DATA_VERSION) {
3407 DPRINTF(("database is version %u, expected version %u",
3408 m->mm_version, MDB_DATA_VERSION));
3409 return MDB_VERSION_MISMATCH;
3412 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3419 mdb_env_init_meta0(MDB_env *env, MDB_meta *meta)
3421 meta->mm_magic = MDB_MAGIC;
3422 meta->mm_version = MDB_DATA_VERSION;
3423 meta->mm_mapsize = env->me_mapsize;
3424 meta->mm_psize = env->me_psize;
3425 meta->mm_last_pg = 1;
3426 meta->mm_flags = env->me_flags & 0xffff;
3427 meta->mm_flags |= MDB_INTEGERKEY;
3428 meta->mm_dbs[0].md_root = P_INVALID;
3429 meta->mm_dbs[1].md_root = P_INVALID;
3432 /** Write the environment parameters of a freshly created DB environment.
3433 * @param[in] env the environment handle
3434 * @param[out] meta address of where to store the meta information
3435 * @return 0 on success, non-zero on failure.
3438 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3446 memset(&ov, 0, sizeof(ov));
3447 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3449 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3452 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3453 len = pwrite(fd, ptr, size, pos); \
3454 rc = (len >= 0); } while(0)
3457 DPUTS("writing new meta page");
3459 psize = env->me_psize;
3461 mdb_env_init_meta0(env, meta);
3463 p = calloc(2, psize);
3465 p->mp_flags = P_META;
3466 *(MDB_meta *)METADATA(p) = *meta;
3468 q = (MDB_page *)((char *)p + psize);
3470 q->mp_flags = P_META;
3471 *(MDB_meta *)METADATA(q) = *meta;
3473 DO_PWRITE(rc, env->me_fd, p, psize * 2, len, 0);
3476 else if ((unsigned) len == psize * 2)
3484 /** Update the environment info to commit a transaction.
3485 * @param[in] txn the transaction that's being committed
3486 * @return 0 on success, non-zero on failure.
3489 mdb_env_write_meta(MDB_txn *txn)
3492 MDB_meta meta, metab, *mp;
3495 int rc, len, toggle;
3504 toggle = txn->mt_txnid & 1;
3505 DPRINTF(("writing meta page %d for root page %"Z"u",
3506 toggle, txn->mt_dbs[MAIN_DBI].md_root));
3509 mp = env->me_metas[toggle];
3510 mapsize = env->me_metas[toggle ^ 1]->mm_mapsize;
3511 /* Persist any increases of mapsize config */
3512 if (mapsize < env->me_mapsize)
3513 mapsize = env->me_mapsize;
3515 if (env->me_flags & MDB_WRITEMAP) {
3516 mp->mm_mapsize = mapsize;
3517 mp->mm_dbs[0] = txn->mt_dbs[0];
3518 mp->mm_dbs[1] = txn->mt_dbs[1];
3519 mp->mm_last_pg = txn->mt_next_pgno - 1;
3520 mp->mm_txnid = txn->mt_txnid;
3521 if (!(env->me_flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3522 unsigned meta_size = env->me_psize;
3523 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3526 #ifndef _WIN32 /* POSIX msync() requires ptr = start of OS page */
3527 if (meta_size < env->me_os_psize)
3528 meta_size += meta_size;
3533 if (MDB_MSYNC(ptr, meta_size, rc)) {
3540 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
3541 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
3543 meta.mm_mapsize = mapsize;
3544 meta.mm_dbs[0] = txn->mt_dbs[0];
3545 meta.mm_dbs[1] = txn->mt_dbs[1];
3546 meta.mm_last_pg = txn->mt_next_pgno - 1;
3547 meta.mm_txnid = txn->mt_txnid;
3549 off = offsetof(MDB_meta, mm_mapsize);
3550 ptr = (char *)&meta + off;
3551 len = sizeof(MDB_meta) - off;
3553 off += env->me_psize;
3556 /* Write to the SYNC fd */
3557 mfd = env->me_flags & (MDB_NOSYNC|MDB_NOMETASYNC) ?
3558 env->me_fd : env->me_mfd;
3561 memset(&ov, 0, sizeof(ov));
3563 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3567 rc = pwrite(mfd, ptr, len, off);
3570 rc = rc < 0 ? ErrCode() : EIO;
3571 DPUTS("write failed, disk error?");
3572 /* On a failure, the pagecache still contains the new data.
3573 * Write some old data back, to prevent it from being used.
3574 * Use the non-SYNC fd; we know it will fail anyway.
3576 meta.mm_last_pg = metab.mm_last_pg;
3577 meta.mm_txnid = metab.mm_txnid;
3579 memset(&ov, 0, sizeof(ov));
3581 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3583 r2 = pwrite(env->me_fd, ptr, len, off);
3584 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
3587 env->me_flags |= MDB_FATAL_ERROR;
3591 /* MIPS has cache coherency issues, this is a no-op everywhere else */
3592 if (!(env->me_flags & MDB_WRITEMAP)) {
3593 CACHEFLUSH(env->me_map + off, len, DCACHE);
3595 /* Memory ordering issues are irrelevant; since the entire writer
3596 * is wrapped by wmutex, all of these changes will become visible
3597 * after the wmutex is unlocked. Since the DB is multi-version,
3598 * readers will get consistent data regardless of how fresh or
3599 * how stale their view of these values is.
3602 env->me_txns->mti_txnid = txn->mt_txnid;
3607 /** Check both meta pages to see which one is newer.
3608 * @param[in] env the environment handle
3609 * @return meta toggle (0 or 1).
3612 mdb_env_pick_meta(const MDB_env *env)
3614 return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
3618 mdb_env_create(MDB_env **env)
3622 e = calloc(1, sizeof(MDB_env));
3626 e->me_maxreaders = DEFAULT_READERS;
3627 e->me_maxdbs = e->me_numdbs = 2;
3628 e->me_fd = INVALID_HANDLE_VALUE;
3629 e->me_lfd = INVALID_HANDLE_VALUE;
3630 e->me_mfd = INVALID_HANDLE_VALUE;
3631 #ifdef MDB_USE_POSIX_SEM
3632 e->me_rmutex = SEM_FAILED;
3633 e->me_wmutex = SEM_FAILED;
3635 e->me_pid = getpid();
3636 GET_PAGESIZE(e->me_os_psize);
3637 VGMEMP_CREATE(e,0,0);
3643 mdb_env_map(MDB_env *env, void *addr)
3646 unsigned int flags = env->me_flags;
3650 LONG sizelo, sizehi;
3653 if (flags & MDB_RDONLY) {
3654 /* Don't set explicit map size, use whatever exists */
3659 msize = env->me_mapsize;
3660 sizelo = msize & 0xffffffff;
3661 sizehi = msize >> 16 >> 16; /* only needed on Win64 */
3663 /* Windows won't create mappings for zero length files.
3664 * and won't map more than the file size.
3665 * Just set the maxsize right now.
3667 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3668 || !SetEndOfFile(env->me_fd)
3669 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3673 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3674 PAGE_READWRITE : PAGE_READONLY,
3675 sizehi, sizelo, NULL);
3678 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3679 FILE_MAP_WRITE : FILE_MAP_READ,
3681 rc = env->me_map ? 0 : ErrCode();
3686 int prot = PROT_READ;
3687 if (flags & MDB_WRITEMAP) {
3689 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3692 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
3694 if (env->me_map == MAP_FAILED) {
3699 if (flags & MDB_NORDAHEAD) {
3700 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3702 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3704 #ifdef POSIX_MADV_RANDOM
3705 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3706 #endif /* POSIX_MADV_RANDOM */
3707 #endif /* MADV_RANDOM */
3711 /* Can happen because the address argument to mmap() is just a
3712 * hint. mmap() can pick another, e.g. if the range is in use.
3713 * The MAP_FIXED flag would prevent that, but then mmap could
3714 * instead unmap existing pages to make room for the new map.
3716 if (addr && env->me_map != addr)
3717 return EBUSY; /* TODO: Make a new MDB_* error code? */
3719 p = (MDB_page *)env->me_map;
3720 env->me_metas[0] = METADATA(p);
3721 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
3727 mdb_env_set_mapsize(MDB_env *env, size_t size)
3729 /* If env is already open, caller is responsible for making
3730 * sure there are no active txns.
3738 size = env->me_metas[mdb_env_pick_meta(env)]->mm_mapsize;
3739 else if (size < env->me_mapsize) {
3740 /* If the configured size is smaller, make sure it's
3741 * still big enough. Silently round up to minimum if not.
3743 size_t minsize = (env->me_metas[mdb_env_pick_meta(env)]->mm_last_pg + 1) * env->me_psize;
3747 munmap(env->me_map, env->me_mapsize);
3748 env->me_mapsize = size;
3749 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
3750 rc = mdb_env_map(env, old);
3754 env->me_mapsize = size;
3756 env->me_maxpg = env->me_mapsize / env->me_psize;
3761 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
3765 env->me_maxdbs = dbs + 2; /* Named databases + main and free DB */
3770 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
3772 if (env->me_map || readers < 1)
3774 env->me_maxreaders = readers;
3779 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
3781 if (!env || !readers)
3783 *readers = env->me_maxreaders;
3787 /** Further setup required for opening an LMDB environment
3790 mdb_env_open2(MDB_env *env)
3792 unsigned int flags = env->me_flags;
3793 int i, newenv = 0, rc;
3797 /* See if we should use QueryLimited */
3799 if ((rc & 0xff) > 5)
3800 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
3802 env->me_pidquery = PROCESS_QUERY_INFORMATION;
3805 memset(&meta, 0, sizeof(meta));
3807 if ((i = mdb_env_read_header(env, &meta)) != 0) {
3810 DPUTS("new mdbenv");
3812 env->me_psize = env->me_os_psize;
3813 if (env->me_psize > MAX_PAGESIZE)
3814 env->me_psize = MAX_PAGESIZE;
3816 env->me_psize = meta.mm_psize;
3819 /* Was a mapsize configured? */
3820 if (!env->me_mapsize) {
3821 /* If this is a new environment, take the default,
3822 * else use the size recorded in the existing env.
3824 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
3825 } else if (env->me_mapsize < meta.mm_mapsize) {
3826 /* If the configured size is smaller, make sure it's
3827 * still big enough. Silently round up to minimum if not.
3829 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
3830 if (env->me_mapsize < minsize)
3831 env->me_mapsize = minsize;
3834 rc = mdb_env_map(env, (flags & MDB_FIXEDMAP) ? meta.mm_address : NULL);
3839 if (flags & MDB_FIXEDMAP)
3840 meta.mm_address = env->me_map;
3841 i = mdb_env_init_meta(env, &meta);
3842 if (i != MDB_SUCCESS) {
3847 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
3848 env->me_nodemax = (((env->me_psize - PAGEHDRSZ) / MDB_MINKEYS) & -2)
3850 #if !(MDB_MAXKEYSIZE)
3851 env->me_maxkey = env->me_nodemax - (NODESIZE + sizeof(MDB_db));
3853 env->me_maxpg = env->me_mapsize / env->me_psize;
3857 int toggle = mdb_env_pick_meta(env);
3858 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
3860 DPRINTF(("opened database version %u, pagesize %u",
3861 env->me_metas[0]->mm_version, env->me_psize));
3862 DPRINTF(("using meta page %d", toggle));
3863 DPRINTF(("depth: %u", db->md_depth));
3864 DPRINTF(("entries: %"Z"u", db->md_entries));
3865 DPRINTF(("branch pages: %"Z"u", db->md_branch_pages));
3866 DPRINTF(("leaf pages: %"Z"u", db->md_leaf_pages));
3867 DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
3868 DPRINTF(("root: %"Z"u", db->md_root));
3876 /** Release a reader thread's slot in the reader lock table.
3877 * This function is called automatically when a thread exits.
3878 * @param[in] ptr This points to the slot in the reader lock table.
3881 mdb_env_reader_dest(void *ptr)
3883 MDB_reader *reader = ptr;
3889 /** Junk for arranging thread-specific callbacks on Windows. This is
3890 * necessarily platform and compiler-specific. Windows supports up
3891 * to 1088 keys. Let's assume nobody opens more than 64 environments
3892 * in a single process, for now. They can override this if needed.
3894 #ifndef MAX_TLS_KEYS
3895 #define MAX_TLS_KEYS 64
3897 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
3898 static int mdb_tls_nkeys;
3900 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
3904 case DLL_PROCESS_ATTACH: break;
3905 case DLL_THREAD_ATTACH: break;
3906 case DLL_THREAD_DETACH:
3907 for (i=0; i<mdb_tls_nkeys; i++) {
3908 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
3910 mdb_env_reader_dest(r);
3914 case DLL_PROCESS_DETACH: break;
3919 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3921 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3925 /* Force some symbol references.
3926 * _tls_used forces the linker to create the TLS directory if not already done
3927 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
3929 #pragma comment(linker, "/INCLUDE:_tls_used")
3930 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
3931 #pragma const_seg(".CRT$XLB")
3932 extern const PIMAGE_TLS_CALLBACK mdb_tls_cbp;
3933 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3936 #pragma comment(linker, "/INCLUDE:__tls_used")
3937 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
3938 #pragma data_seg(".CRT$XLB")
3939 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3941 #endif /* WIN 32/64 */
3942 #endif /* !__GNUC__ */
3945 /** Downgrade the exclusive lock on the region back to shared */
3947 mdb_env_share_locks(MDB_env *env, int *excl)
3949 int rc = 0, toggle = mdb_env_pick_meta(env);
3951 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
3956 /* First acquire a shared lock. The Unlock will
3957 * then release the existing exclusive lock.
3959 memset(&ov, 0, sizeof(ov));
3960 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3963 UnlockFile(env->me_lfd, 0, 0, 1, 0);
3969 struct flock lock_info;
3970 /* The shared lock replaces the existing lock */
3971 memset((void *)&lock_info, 0, sizeof(lock_info));
3972 lock_info.l_type = F_RDLCK;
3973 lock_info.l_whence = SEEK_SET;
3974 lock_info.l_start = 0;
3975 lock_info.l_len = 1;
3976 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3977 (rc = ErrCode()) == EINTR) ;
3978 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
3985 /** Try to get exlusive lock, otherwise shared.
3986 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
3989 mdb_env_excl_lock(MDB_env *env, int *excl)
3993 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
3997 memset(&ov, 0, sizeof(ov));
3998 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
4005 struct flock lock_info;
4006 memset((void *)&lock_info, 0, sizeof(lock_info));
4007 lock_info.l_type = F_WRLCK;
4008 lock_info.l_whence = SEEK_SET;
4009 lock_info.l_start = 0;
4010 lock_info.l_len = 1;
4011 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
4012 (rc = ErrCode()) == EINTR) ;
4016 # ifdef MDB_USE_POSIX_SEM
4017 if (*excl < 0) /* always true when !MDB_USE_POSIX_SEM */
4020 lock_info.l_type = F_RDLCK;
4021 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
4022 (rc = ErrCode()) == EINTR) ;
4032 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
4034 * @(#) $Revision: 5.1 $
4035 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
4036 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
4038 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
4042 * Please do not copyright this code. This code is in the public domain.
4044 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
4045 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
4046 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
4047 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
4048 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4049 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4050 * PERFORMANCE OF THIS SOFTWARE.
4053 * chongo <Landon Curt Noll> /\oo/\
4054 * http://www.isthe.com/chongo/
4056 * Share and Enjoy! :-)
4059 typedef unsigned long long mdb_hash_t;
4060 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
4062 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
4063 * @param[in] val value to hash
4064 * @param[in] hval initial value for hash
4065 * @return 64 bit hash
4067 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
4068 * hval arg on the first call.
4071 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
4073 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
4074 unsigned char *end = s + val->mv_size;
4076 * FNV-1a hash each octet of the string
4079 /* xor the bottom with the current octet */
4080 hval ^= (mdb_hash_t)*s++;
4082 /* multiply by the 64 bit FNV magic prime mod 2^64 */
4083 hval += (hval << 1) + (hval << 4) + (hval << 5) +
4084 (hval << 7) + (hval << 8) + (hval << 40);
4086 /* return our new hash value */
4090 /** Hash the string and output the encoded hash.
4091 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
4092 * very short name limits. We don't care about the encoding being reversible,
4093 * we just want to preserve as many bits of the input as possible in a
4094 * small printable string.
4095 * @param[in] str string to hash
4096 * @param[out] encbuf an array of 11 chars to hold the hash
4098 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
4101 mdb_pack85(unsigned long l, char *out)
4105 for (i=0; i<5; i++) {
4106 *out++ = mdb_a85[l % 85];
4112 mdb_hash_enc(MDB_val *val, char *encbuf)
4114 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
4116 mdb_pack85(h, encbuf);
4117 mdb_pack85(h>>32, encbuf+5);
4122 /** Open and/or initialize the lock region for the environment.
4123 * @param[in] env The LMDB environment.
4124 * @param[in] lpath The pathname of the file used for the lock region.
4125 * @param[in] mode The Unix permissions for the file, if we create it.
4126 * @param[out] excl Resulting file lock type: -1 none, 0 shared, 1 exclusive
4127 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
4128 * @return 0 on success, non-zero on failure.
4131 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
4134 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
4136 # define MDB_ERRCODE_ROFS EROFS
4137 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
4138 # define MDB_CLOEXEC O_CLOEXEC
4141 # define MDB_CLOEXEC 0
4148 env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
4149 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
4150 FILE_ATTRIBUTE_NORMAL, NULL);
4152 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
4154 if (env->me_lfd == INVALID_HANDLE_VALUE) {
4156 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
4161 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
4162 /* Lose record locks when exec*() */
4163 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
4164 fcntl(env->me_lfd, F_SETFD, fdflags);
4167 if (!(env->me_flags & MDB_NOTLS)) {
4168 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
4171 env->me_flags |= MDB_ENV_TXKEY;
4173 /* Windows TLS callbacks need help finding their TLS info. */
4174 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
4178 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
4182 /* Try to get exclusive lock. If we succeed, then
4183 * nobody is using the lock region and we should initialize it.
4185 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
4188 size = GetFileSize(env->me_lfd, NULL);
4190 size = lseek(env->me_lfd, 0, SEEK_END);
4191 if (size == -1) goto fail_errno;
4193 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
4194 if (size < rsize && *excl > 0) {
4196 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != (DWORD)rsize
4197 || !SetEndOfFile(env->me_lfd))
4200 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
4204 size = rsize - sizeof(MDB_txninfo);
4205 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
4210 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
4212 if (!mh) goto fail_errno;
4213 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
4215 if (!env->me_txns) goto fail_errno;
4217 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
4219 if (m == MAP_FAILED) goto fail_errno;
4225 BY_HANDLE_FILE_INFORMATION stbuf;
4234 if (!mdb_sec_inited) {
4235 InitializeSecurityDescriptor(&mdb_null_sd,
4236 SECURITY_DESCRIPTOR_REVISION);
4237 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
4238 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
4239 mdb_all_sa.bInheritHandle = FALSE;
4240 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
4243 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
4244 idbuf.volume = stbuf.dwVolumeSerialNumber;
4245 idbuf.nhigh = stbuf.nFileIndexHigh;
4246 idbuf.nlow = stbuf.nFileIndexLow;
4247 val.mv_data = &idbuf;
4248 val.mv_size = sizeof(idbuf);
4249 mdb_hash_enc(&val, encbuf);
4250 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
4251 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
4252 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
4253 if (!env->me_rmutex) goto fail_errno;
4254 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
4255 if (!env->me_wmutex) goto fail_errno;
4256 #elif defined(MDB_USE_POSIX_SEM)
4265 #if defined(__NetBSD__)
4266 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
4268 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
4269 idbuf.dev = stbuf.st_dev;
4270 idbuf.ino = stbuf.st_ino;
4271 val.mv_data = &idbuf;
4272 val.mv_size = sizeof(idbuf);
4273 mdb_hash_enc(&val, encbuf);
4274 #ifdef MDB_SHORT_SEMNAMES
4275 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
4277 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
4278 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
4279 /* Clean up after a previous run, if needed: Try to
4280 * remove both semaphores before doing anything else.
4282 sem_unlink(env->me_txns->mti_rmname);
4283 sem_unlink(env->me_txns->mti_wmname);
4284 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
4285 O_CREAT|O_EXCL, mode, 1);
4286 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4287 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
4288 O_CREAT|O_EXCL, mode, 1);
4289 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4290 #else /* MDB_USE_POSIX_SEM */
4291 pthread_mutexattr_t mattr;
4293 if ((rc = pthread_mutexattr_init(&mattr))
4294 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
4295 || (rc = pthread_mutex_init(&env->me_txns->mti_mutex, &mattr))
4296 || (rc = pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr)))
4298 pthread_mutexattr_destroy(&mattr);
4299 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
4301 env->me_txns->mti_magic = MDB_MAGIC;
4302 env->me_txns->mti_format = MDB_LOCK_FORMAT;
4303 env->me_txns->mti_txnid = 0;
4304 env->me_txns->mti_numreaders = 0;
4307 if (env->me_txns->mti_magic != MDB_MAGIC) {
4308 DPUTS("lock region has invalid magic");
4312 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
4313 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
4314 env->me_txns->mti_format, MDB_LOCK_FORMAT));
4315 rc = MDB_VERSION_MISMATCH;
4319 if (rc && rc != EACCES && rc != EAGAIN) {
4323 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
4324 if (!env->me_rmutex) goto fail_errno;
4325 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
4326 if (!env->me_wmutex) goto fail_errno;
4327 #elif defined(MDB_USE_POSIX_SEM)
4328 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
4329 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
4330 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
4331 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
4342 /** The name of the lock file in the DB environment */
4343 #define LOCKNAME "/lock.mdb"
4344 /** The name of the data file in the DB environment */
4345 #define DATANAME "/data.mdb"
4346 /** The suffix of the lock file when no subdir is used */
4347 #define LOCKSUFF "-lock"
4348 /** Only a subset of the @ref mdb_env flags can be changed
4349 * at runtime. Changing other flags requires closing the
4350 * environment and re-opening it with the new flags.
4352 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC|MDB_NOMEMINIT)
4353 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY|MDB_WRITEMAP| \
4354 MDB_NOTLS|MDB_NOLOCK|MDB_NORDAHEAD)
4356 #if VALID_FLAGS & PERSISTENT_FLAGS & (CHANGEABLE|CHANGELESS)
4357 # error "Persistent DB flags & env flags overlap, but both go in mm_flags"
4361 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
4363 int oflags, rc, len, excl = -1;
4364 char *lpath, *dpath;
4366 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
4370 if (flags & MDB_NOSUBDIR) {
4371 rc = len + sizeof(LOCKSUFF) + len + 1;
4373 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
4378 if (flags & MDB_NOSUBDIR) {
4379 dpath = lpath + len + sizeof(LOCKSUFF);
4380 sprintf(lpath, "%s" LOCKSUFF, path);
4381 strcpy(dpath, path);
4383 dpath = lpath + len + sizeof(LOCKNAME);
4384 sprintf(lpath, "%s" LOCKNAME, path);
4385 sprintf(dpath, "%s" DATANAME, path);
4389 flags |= env->me_flags;
4390 if (flags & MDB_RDONLY) {
4391 /* silently ignore WRITEMAP when we're only getting read access */
4392 flags &= ~MDB_WRITEMAP;
4394 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
4395 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
4398 env->me_flags = flags |= MDB_ENV_ACTIVE;
4402 env->me_path = strdup(path);
4403 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
4404 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
4405 env->me_dbiseqs = calloc(env->me_maxdbs, sizeof(unsigned int));
4406 if (!(env->me_dbxs && env->me_path && env->me_dbflags && env->me_dbiseqs)) {
4411 /* For RDONLY, get lockfile after we know datafile exists */
4412 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
4413 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4419 if (F_ISSET(flags, MDB_RDONLY)) {
4420 oflags = GENERIC_READ;
4421 len = OPEN_EXISTING;
4423 oflags = GENERIC_READ|GENERIC_WRITE;
4426 mode = FILE_ATTRIBUTE_NORMAL;
4427 env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
4428 NULL, len, mode, NULL);
4430 if (F_ISSET(flags, MDB_RDONLY))
4433 oflags = O_RDWR | O_CREAT;
4435 env->me_fd = open(dpath, oflags, mode);
4437 if (env->me_fd == INVALID_HANDLE_VALUE) {
4442 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
4443 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4448 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
4449 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
4450 env->me_mfd = env->me_fd;
4452 /* Synchronous fd for meta writes. Needed even with
4453 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
4456 len = OPEN_EXISTING;
4457 env->me_mfd = CreateFile(dpath, oflags,
4458 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
4459 mode | FILE_FLAG_WRITE_THROUGH, NULL);
4462 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
4464 if (env->me_mfd == INVALID_HANDLE_VALUE) {
4469 DPRINTF(("opened dbenv %p", (void *) env));
4471 rc = mdb_env_share_locks(env, &excl);
4475 if (!((flags & MDB_RDONLY) ||
4476 (env->me_pbuf = calloc(1, env->me_psize))))
4482 mdb_env_close0(env, excl);
4488 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
4490 mdb_env_close0(MDB_env *env, int excl)
4494 if (!(env->me_flags & MDB_ENV_ACTIVE))
4497 /* Doing this here since me_dbxs may not exist during mdb_env_close */
4498 for (i = env->me_maxdbs; --i > MAIN_DBI; )
4499 free(env->me_dbxs[i].md_name.mv_data);
4502 free(env->me_dbiseqs);
4503 free(env->me_dbflags);
4506 free(env->me_dirty_list);
4507 mdb_midl_free(env->me_free_pgs);
4509 if (env->me_flags & MDB_ENV_TXKEY) {
4510 pthread_key_delete(env->me_txkey);
4512 /* Delete our key from the global list */
4513 for (i=0; i<mdb_tls_nkeys; i++)
4514 if (mdb_tls_keys[i] == env->me_txkey) {
4515 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
4523 munmap(env->me_map, env->me_mapsize);
4525 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
4526 (void) close(env->me_mfd);
4527 if (env->me_fd != INVALID_HANDLE_VALUE)
4528 (void) close(env->me_fd);
4530 MDB_PID_T pid = env->me_pid;
4531 /* Clearing readers is done in this function because
4532 * me_txkey with its destructor must be disabled first.
4534 for (i = env->me_numreaders; --i >= 0; )
4535 if (env->me_txns->mti_readers[i].mr_pid == pid)
4536 env->me_txns->mti_readers[i].mr_pid = 0;
4538 if (env->me_rmutex) {
4539 CloseHandle(env->me_rmutex);
4540 if (env->me_wmutex) CloseHandle(env->me_wmutex);
4542 /* Windows automatically destroys the mutexes when
4543 * the last handle closes.
4545 #elif defined(MDB_USE_POSIX_SEM)
4546 if (env->me_rmutex != SEM_FAILED) {
4547 sem_close(env->me_rmutex);
4548 if (env->me_wmutex != SEM_FAILED)
4549 sem_close(env->me_wmutex);
4550 /* If we have the filelock: If we are the
4551 * only remaining user, clean up semaphores.
4554 mdb_env_excl_lock(env, &excl);
4556 sem_unlink(env->me_txns->mti_rmname);
4557 sem_unlink(env->me_txns->mti_wmname);
4561 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
4563 if (env->me_lfd != INVALID_HANDLE_VALUE) {
4566 /* Unlock the lockfile. Windows would have unlocked it
4567 * after closing anyway, but not necessarily at once.
4569 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4572 (void) close(env->me_lfd);
4575 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
4580 mdb_env_close(MDB_env *env)
4587 VGMEMP_DESTROY(env);
4588 while ((dp = env->me_dpages) != NULL) {
4589 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
4590 env->me_dpages = dp->mp_next;
4594 mdb_env_close0(env, 0);
4598 /** Compare two items pointing at aligned size_t's */
4600 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
4602 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
4603 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
4606 /** Compare two items pointing at aligned unsigned int's */
4608 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
4610 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
4611 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
4614 /** Compare two items pointing at unsigned ints of unknown alignment.
4615 * Nodes and keys are guaranteed to be 2-byte aligned.
4618 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
4620 #if BYTE_ORDER == LITTLE_ENDIAN
4621 unsigned short *u, *c;
4624 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4625 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
4628 } while(!x && u > (unsigned short *)a->mv_data);
4631 unsigned short *u, *c, *end;
4634 end = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4635 u = (unsigned short *)a->mv_data;
4636 c = (unsigned short *)b->mv_data;
4639 } while(!x && u < end);
4644 /** Compare two items pointing at size_t's of unknown alignment. */
4645 #ifdef MISALIGNED_OK
4646 # define mdb_cmp_clong mdb_cmp_long
4648 # define mdb_cmp_clong mdb_cmp_cint
4651 /** Compare two items lexically */
4653 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
4660 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4666 diff = memcmp(a->mv_data, b->mv_data, len);
4667 return diff ? diff : len_diff<0 ? -1 : len_diff;
4670 /** Compare two items in reverse byte order */
4672 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
4674 const unsigned char *p1, *p2, *p1_lim;
4678 p1_lim = (const unsigned char *)a->mv_data;
4679 p1 = (const unsigned char *)a->mv_data + a->mv_size;
4680 p2 = (const unsigned char *)b->mv_data + b->mv_size;
4682 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4688 while (p1 > p1_lim) {
4689 diff = *--p1 - *--p2;
4693 return len_diff<0 ? -1 : len_diff;
4696 /** Search for key within a page, using binary search.
4697 * Returns the smallest entry larger or equal to the key.
4698 * If exactp is non-null, stores whether the found entry was an exact match
4699 * in *exactp (1 or 0).
4700 * Updates the cursor index with the index of the found entry.
4701 * If no entry larger or equal to the key is found, returns NULL.
4704 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
4706 unsigned int i = 0, nkeys;
4709 MDB_page *mp = mc->mc_pg[mc->mc_top];
4710 MDB_node *node = NULL;
4715 nkeys = NUMKEYS(mp);
4717 DPRINTF(("searching %u keys in %s %spage %"Z"u",
4718 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
4721 low = IS_LEAF(mp) ? 0 : 1;
4723 cmp = mc->mc_dbx->md_cmp;
4725 /* Branch pages have no data, so if using integer keys,
4726 * alignment is guaranteed. Use faster mdb_cmp_int.
4728 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
4729 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
4736 nodekey.mv_size = mc->mc_db->md_pad;
4737 node = NODEPTR(mp, 0); /* fake */
4738 while (low <= high) {
4739 i = (low + high) >> 1;
4740 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
4741 rc = cmp(key, &nodekey);
4742 DPRINTF(("found leaf index %u [%s], rc = %i",
4743 i, DKEY(&nodekey), rc));
4752 while (low <= high) {
4753 i = (low + high) >> 1;
4755 node = NODEPTR(mp, i);
4756 nodekey.mv_size = NODEKSZ(node);
4757 nodekey.mv_data = NODEKEY(node);
4759 rc = cmp(key, &nodekey);
4762 DPRINTF(("found leaf index %u [%s], rc = %i",
4763 i, DKEY(&nodekey), rc));
4765 DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
4766 i, DKEY(&nodekey), NODEPGNO(node), rc));
4777 if (rc > 0) { /* Found entry is less than the key. */
4778 i++; /* Skip to get the smallest entry larger than key. */
4780 node = NODEPTR(mp, i);
4783 *exactp = (rc == 0 && nkeys > 0);
4784 /* store the key index */
4785 mc->mc_ki[mc->mc_top] = i;
4787 /* There is no entry larger or equal to the key. */
4790 /* nodeptr is fake for LEAF2 */
4796 mdb_cursor_adjust(MDB_cursor *mc, func)
4800 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4801 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
4808 /** Pop a page off the top of the cursor's stack. */
4810 mdb_cursor_pop(MDB_cursor *mc)
4814 MDB_page *top = mc->mc_pg[mc->mc_top];
4820 DPRINTF(("popped page %"Z"u off db %d cursor %p", top->mp_pgno,
4821 DDBI(mc), (void *) mc));
4825 /** Push a page onto the top of the cursor's stack. */
4827 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
4829 DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
4830 DDBI(mc), (void *) mc));
4832 if (mc->mc_snum >= CURSOR_STACK) {
4833 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4834 return MDB_CURSOR_FULL;
4837 mc->mc_top = mc->mc_snum++;
4838 mc->mc_pg[mc->mc_top] = mp;
4839 mc->mc_ki[mc->mc_top] = 0;
4844 /** Find the address of the page corresponding to a given page number.
4845 * @param[in] txn the transaction for this access.
4846 * @param[in] pgno the page number for the page to retrieve.
4847 * @param[out] ret address of a pointer where the page's address will be stored.
4848 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
4849 * @return 0 on success, non-zero on failure.
4852 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
4854 MDB_env *env = txn->mt_env;
4858 if (!((txn->mt_flags & MDB_TXN_RDONLY) | (env->me_flags & MDB_WRITEMAP))) {
4862 MDB_ID2L dl = tx2->mt_u.dirty_list;
4864 /* Spilled pages were dirtied in this txn and flushed
4865 * because the dirty list got full. Bring this page
4866 * back in from the map (but don't unspill it here,
4867 * leave that unless page_touch happens again).
4869 if (tx2->mt_spill_pgs) {
4870 MDB_ID pn = pgno << 1;
4871 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
4872 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
4873 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
4878 unsigned x = mdb_mid2l_search(dl, pgno);
4879 if (x <= dl[0].mid && dl[x].mid == pgno) {
4885 } while ((tx2 = tx2->mt_parent) != NULL);
4888 if (pgno < txn->mt_next_pgno) {
4890 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
4892 DPRINTF(("page %"Z"u not found", pgno));
4893 txn->mt_flags |= MDB_TXN_ERROR;
4894 return MDB_PAGE_NOTFOUND;
4904 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
4905 * The cursor is at the root page, set up the rest of it.
4908 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
4910 MDB_page *mp = mc->mc_pg[mc->mc_top];
4914 while (IS_BRANCH(mp)) {
4918 DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
4919 mdb_cassert(mc, NUMKEYS(mp) > 1);
4920 DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
4922 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
4924 if (flags & MDB_PS_LAST)
4925 i = NUMKEYS(mp) - 1;
4928 node = mdb_node_search(mc, key, &exact);
4930 i = NUMKEYS(mp) - 1;
4932 i = mc->mc_ki[mc->mc_top];
4934 mdb_cassert(mc, i > 0);
4938 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
4941 mdb_cassert(mc, i < NUMKEYS(mp));
4942 node = NODEPTR(mp, i);
4944 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4947 mc->mc_ki[mc->mc_top] = i;
4948 if ((rc = mdb_cursor_push(mc, mp)))
4951 if (flags & MDB_PS_MODIFY) {
4952 if ((rc = mdb_page_touch(mc)) != 0)
4954 mp = mc->mc_pg[mc->mc_top];
4959 DPRINTF(("internal error, index points to a %02X page!?",
4961 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4962 return MDB_CORRUPTED;
4965 DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
4966 key ? DKEY(key) : "null"));
4967 mc->mc_flags |= C_INITIALIZED;
4968 mc->mc_flags &= ~C_EOF;
4973 /** Search for the lowest key under the current branch page.
4974 * This just bypasses a NUMKEYS check in the current page
4975 * before calling mdb_page_search_root(), because the callers
4976 * are all in situations where the current page is known to
4980 mdb_page_search_lowest(MDB_cursor *mc)
4982 MDB_page *mp = mc->mc_pg[mc->mc_top];
4983 MDB_node *node = NODEPTR(mp, 0);
4986 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4989 mc->mc_ki[mc->mc_top] = 0;
4990 if ((rc = mdb_cursor_push(mc, mp)))
4992 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
4995 /** Search for the page a given key should be in.
4996 * Push it and its parent pages on the cursor stack.
4997 * @param[in,out] mc the cursor for this operation.
4998 * @param[in] key the key to search for, or NULL for first/last page.
4999 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
5000 * are touched (updated with new page numbers).
5001 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
5002 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
5003 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
5004 * @return 0 on success, non-zero on failure.
5007 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
5012 /* Make sure the txn is still viable, then find the root from
5013 * the txn's db table and set it as the root of the cursor's stack.
5015 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
5016 DPUTS("transaction has failed, must abort");
5019 /* Make sure we're using an up-to-date root */
5020 if (*mc->mc_dbflag & DB_STALE) {
5022 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
5024 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
5025 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
5032 MDB_node *leaf = mdb_node_search(&mc2,
5033 &mc->mc_dbx->md_name, &exact);
5035 return MDB_NOTFOUND;
5036 rc = mdb_node_read(mc->mc_txn, leaf, &data);
5039 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
5041 /* The txn may not know this DBI, or another process may
5042 * have dropped and recreated the DB with other flags.
5044 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
5045 return MDB_INCOMPATIBLE;
5046 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
5048 *mc->mc_dbflag &= ~DB_STALE;
5050 root = mc->mc_db->md_root;
5052 if (root == P_INVALID) { /* Tree is empty. */
5053 DPUTS("tree is empty");
5054 return MDB_NOTFOUND;
5058 mdb_cassert(mc, root > 1);
5059 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
5060 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0], NULL)) != 0)
5066 DPRINTF(("db %d root page %"Z"u has flags 0x%X",
5067 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
5069 if (flags & MDB_PS_MODIFY) {
5070 if ((rc = mdb_page_touch(mc)))
5074 if (flags & MDB_PS_ROOTONLY)
5077 return mdb_page_search_root(mc, key, flags);
5081 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
5083 MDB_txn *txn = mc->mc_txn;
5084 pgno_t pg = mp->mp_pgno;
5085 unsigned x = 0, ovpages = mp->mp_pages;
5086 MDB_env *env = txn->mt_env;
5087 MDB_IDL sl = txn->mt_spill_pgs;
5088 MDB_ID pn = pg << 1;
5091 DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
5092 /* If the page is dirty or on the spill list we just acquired it,
5093 * so we should give it back to our current free list, if any.
5094 * Otherwise put it onto the list of pages we freed in this txn.
5096 * Won't create me_pghead: me_pglast must be inited along with it.
5097 * Unsupported in nested txns: They would need to hide the page
5098 * range in ancestor txns' dirty and spilled lists.
5100 if (env->me_pghead &&
5102 ((mp->mp_flags & P_DIRTY) ||
5103 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
5107 MDB_ID2 *dl, ix, iy;
5108 rc = mdb_midl_need(&env->me_pghead, ovpages);
5111 if (!(mp->mp_flags & P_DIRTY)) {
5112 /* This page is no longer spilled */
5119 /* Remove from dirty list */
5120 dl = txn->mt_u.dirty_list;
5122 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
5128 mdb_cassert(mc, x > 1);
5130 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
5131 txn->mt_flags |= MDB_TXN_ERROR;
5132 return MDB_CORRUPTED;
5135 if (!(env->me_flags & MDB_WRITEMAP))
5136 mdb_dpage_free(env, mp);
5138 /* Insert in me_pghead */
5139 mop = env->me_pghead;
5140 j = mop[0] + ovpages;
5141 for (i = mop[0]; i && mop[i] < pg; i--)
5147 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
5151 mc->mc_db->md_overflow_pages -= ovpages;
5155 /** Return the data associated with a given node.
5156 * @param[in] txn The transaction for this operation.
5157 * @param[in] leaf The node being read.
5158 * @param[out] data Updated to point to the node's data.
5159 * @return 0 on success, non-zero on failure.
5162 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
5164 MDB_page *omp; /* overflow page */
5168 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5169 data->mv_size = NODEDSZ(leaf);
5170 data->mv_data = NODEDATA(leaf);
5174 /* Read overflow data.
5176 data->mv_size = NODEDSZ(leaf);
5177 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
5178 if ((rc = mdb_page_get(txn, pgno, &omp, NULL)) != 0) {
5179 DPRINTF(("read overflow page %"Z"u failed", pgno));
5182 data->mv_data = METADATA(omp);
5188 mdb_get(MDB_txn *txn, MDB_dbi dbi,
5189 MDB_val *key, MDB_val *data)
5196 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
5198 if (!key || !data || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
5201 if (txn->mt_flags & MDB_TXN_ERROR)
5204 mdb_cursor_init(&mc, txn, dbi, &mx);
5205 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
5208 /** Find a sibling for a page.
5209 * Replaces the page at the top of the cursor's stack with the
5210 * specified sibling, if one exists.
5211 * @param[in] mc The cursor for this operation.
5212 * @param[in] move_right Non-zero if the right sibling is requested,
5213 * otherwise the left sibling.
5214 * @return 0 on success, non-zero on failure.
5217 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
5223 if (mc->mc_snum < 2) {
5224 return MDB_NOTFOUND; /* root has no siblings */
5228 DPRINTF(("parent page is page %"Z"u, index %u",
5229 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
5231 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
5232 : (mc->mc_ki[mc->mc_top] == 0)) {
5233 DPRINTF(("no more keys left, moving to %s sibling",
5234 move_right ? "right" : "left"));
5235 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
5236 /* undo cursor_pop before returning */
5243 mc->mc_ki[mc->mc_top]++;
5245 mc->mc_ki[mc->mc_top]--;
5246 DPRINTF(("just moving to %s index key %u",
5247 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
5249 mdb_cassert(mc, IS_BRANCH(mc->mc_pg[mc->mc_top]));
5251 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5252 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL)) != 0) {
5253 /* mc will be inconsistent if caller does mc_snum++ as above */
5254 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
5258 mdb_cursor_push(mc, mp);
5260 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
5265 /** Move the cursor to the next data item. */
5267 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5273 if (mc->mc_flags & C_EOF) {
5274 return MDB_NOTFOUND;
5277 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5279 mp = mc->mc_pg[mc->mc_top];
5281 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5282 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5283 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5284 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
5285 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
5286 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
5287 if (rc == MDB_SUCCESS)
5288 MDB_GET_KEY(leaf, key);
5293 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5294 if (op == MDB_NEXT_DUP)
5295 return MDB_NOTFOUND;
5299 DPRINTF(("cursor_next: top page is %"Z"u in cursor %p",
5300 mdb_dbg_pgno(mp), (void *) mc));
5301 if (mc->mc_flags & C_DEL)
5304 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
5305 DPUTS("=====> move to next sibling page");
5306 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5307 mc->mc_flags |= C_EOF;
5310 mp = mc->mc_pg[mc->mc_top];
5311 DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5313 mc->mc_ki[mc->mc_top]++;
5316 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5317 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5320 key->mv_size = mc->mc_db->md_pad;
5321 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5325 mdb_cassert(mc, IS_LEAF(mp));
5326 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5328 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5329 mdb_xcursor_init1(mc, leaf);
5332 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5335 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5336 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5337 if (rc != MDB_SUCCESS)
5342 MDB_GET_KEY(leaf, key);
5346 /** Move the cursor to the previous data item. */
5348 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5354 mdb_cassert(mc, mc->mc_flags & C_INITIALIZED);
5356 mp = mc->mc_pg[mc->mc_top];
5358 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5359 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5360 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5361 if (op == MDB_PREV || op == MDB_PREV_DUP) {
5362 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
5363 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
5364 if (rc == MDB_SUCCESS) {
5365 MDB_GET_KEY(leaf, key);
5366 mc->mc_flags &= ~C_EOF;
5371 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5372 if (op == MDB_PREV_DUP)
5373 return MDB_NOTFOUND;
5378 DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p",
5379 mdb_dbg_pgno(mp), (void *) mc));
5381 if (mc->mc_ki[mc->mc_top] == 0) {
5382 DPUTS("=====> move to prev sibling page");
5383 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
5386 mp = mc->mc_pg[mc->mc_top];
5387 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
5388 DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5390 mc->mc_ki[mc->mc_top]--;
5392 mc->mc_flags &= ~C_EOF;
5394 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5395 mdb_dbg_pgno(mp), NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5398 key->mv_size = mc->mc_db->md_pad;
5399 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5403 mdb_cassert(mc, IS_LEAF(mp));
5404 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5406 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5407 mdb_xcursor_init1(mc, leaf);
5410 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5413 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5414 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5415 if (rc != MDB_SUCCESS)
5420 MDB_GET_KEY(leaf, key);
5424 /** Set the cursor on a specific data item. */
5426 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5427 MDB_cursor_op op, int *exactp)
5431 MDB_node *leaf = NULL;
5434 if (key->mv_size == 0)
5435 return MDB_BAD_VALSIZE;
5438 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5440 /* See if we're already on the right page */
5441 if (mc->mc_flags & C_INITIALIZED) {
5444 mp = mc->mc_pg[mc->mc_top];
5446 mc->mc_ki[mc->mc_top] = 0;
5447 return MDB_NOTFOUND;
5449 if (mp->mp_flags & P_LEAF2) {
5450 nodekey.mv_size = mc->mc_db->md_pad;
5451 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
5453 leaf = NODEPTR(mp, 0);
5454 MDB_GET_KEY2(leaf, nodekey);
5456 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5458 /* Probably happens rarely, but first node on the page
5459 * was the one we wanted.
5461 mc->mc_ki[mc->mc_top] = 0;
5468 unsigned int nkeys = NUMKEYS(mp);
5470 if (mp->mp_flags & P_LEAF2) {
5471 nodekey.mv_data = LEAF2KEY(mp,
5472 nkeys-1, nodekey.mv_size);
5474 leaf = NODEPTR(mp, nkeys-1);
5475 MDB_GET_KEY2(leaf, nodekey);
5477 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5479 /* last node was the one we wanted */
5480 mc->mc_ki[mc->mc_top] = nkeys-1;
5486 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
5487 /* This is definitely the right page, skip search_page */
5488 if (mp->mp_flags & P_LEAF2) {
5489 nodekey.mv_data = LEAF2KEY(mp,
5490 mc->mc_ki[mc->mc_top], nodekey.mv_size);
5492 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5493 MDB_GET_KEY2(leaf, nodekey);
5495 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5497 /* current node was the one we wanted */
5507 /* If any parents have right-sibs, search.
5508 * Otherwise, there's nothing further.
5510 for (i=0; i<mc->mc_top; i++)
5512 NUMKEYS(mc->mc_pg[i])-1)
5514 if (i == mc->mc_top) {
5515 /* There are no other pages */
5516 mc->mc_ki[mc->mc_top] = nkeys;
5517 return MDB_NOTFOUND;
5521 /* There are no other pages */
5522 mc->mc_ki[mc->mc_top] = 0;
5523 if (op == MDB_SET_RANGE && !exactp) {
5527 return MDB_NOTFOUND;
5531 rc = mdb_page_search(mc, key, 0);
5532 if (rc != MDB_SUCCESS)
5535 mp = mc->mc_pg[mc->mc_top];
5536 mdb_cassert(mc, IS_LEAF(mp));
5539 leaf = mdb_node_search(mc, key, exactp);
5540 if (exactp != NULL && !*exactp) {
5541 /* MDB_SET specified and not an exact match. */
5542 return MDB_NOTFOUND;
5546 DPUTS("===> inexact leaf not found, goto sibling");
5547 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
5548 return rc; /* no entries matched */
5549 mp = mc->mc_pg[mc->mc_top];
5550 mdb_cassert(mc, IS_LEAF(mp));
5551 leaf = NODEPTR(mp, 0);
5555 mc->mc_flags |= C_INITIALIZED;
5556 mc->mc_flags &= ~C_EOF;
5559 if (op == MDB_SET_RANGE || op == MDB_SET_KEY) {
5560 key->mv_size = mc->mc_db->md_pad;
5561 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5566 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5567 mdb_xcursor_init1(mc, leaf);
5570 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5571 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
5572 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5575 if (op == MDB_GET_BOTH) {
5581 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
5582 if (rc != MDB_SUCCESS)
5585 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
5587 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
5589 rc = mc->mc_dbx->md_dcmp(data, &d2);
5591 if (op == MDB_GET_BOTH || rc > 0)
5592 return MDB_NOTFOUND;
5599 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5600 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5605 /* The key already matches in all other cases */
5606 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
5607 MDB_GET_KEY(leaf, key);
5608 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
5613 /** Move the cursor to the first item in the database. */
5615 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5621 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5623 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5624 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
5625 if (rc != MDB_SUCCESS)
5628 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
5630 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
5631 mc->mc_flags |= C_INITIALIZED;
5632 mc->mc_flags &= ~C_EOF;
5634 mc->mc_ki[mc->mc_top] = 0;
5636 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5637 key->mv_size = mc->mc_db->md_pad;
5638 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
5643 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5644 mdb_xcursor_init1(mc, leaf);
5645 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5649 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5653 MDB_GET_KEY(leaf, key);
5657 /** Move the cursor to the last item in the database. */
5659 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5665 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5667 if (!(mc->mc_flags & C_EOF)) {
5669 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5670 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
5671 if (rc != MDB_SUCCESS)
5674 mdb_cassert(mc, IS_LEAF(mc->mc_pg[mc->mc_top]));
5677 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
5678 mc->mc_flags |= C_INITIALIZED|C_EOF;
5679 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5681 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5682 key->mv_size = mc->mc_db->md_pad;
5683 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
5688 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5689 mdb_xcursor_init1(mc, leaf);
5690 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5694 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5699 MDB_GET_KEY(leaf, key);
5704 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5709 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
5714 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
5718 case MDB_GET_CURRENT:
5719 if (!(mc->mc_flags & C_INITIALIZED)) {
5722 MDB_page *mp = mc->mc_pg[mc->mc_top];
5723 int nkeys = NUMKEYS(mp);
5724 if (!nkeys || mc->mc_ki[mc->mc_top] >= nkeys) {
5725 mc->mc_ki[mc->mc_top] = nkeys;
5731 key->mv_size = mc->mc_db->md_pad;
5732 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5734 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5735 MDB_GET_KEY(leaf, key);
5737 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5738 if (mc->mc_flags & C_DEL)
5739 mdb_xcursor_init1(mc, leaf);
5740 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
5742 rc = mdb_node_read(mc->mc_txn, leaf, data);
5749 case MDB_GET_BOTH_RANGE:
5754 if (mc->mc_xcursor == NULL) {
5755 rc = MDB_INCOMPATIBLE;
5765 rc = mdb_cursor_set(mc, key, data, op,
5766 op == MDB_SET_RANGE ? NULL : &exact);
5769 case MDB_GET_MULTIPLE:
5770 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5774 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5775 rc = MDB_INCOMPATIBLE;
5779 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
5780 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
5783 case MDB_NEXT_MULTIPLE:
5788 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5789 rc = MDB_INCOMPATIBLE;
5792 if (!(mc->mc_flags & C_INITIALIZED))
5793 rc = mdb_cursor_first(mc, key, data);
5795 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
5796 if (rc == MDB_SUCCESS) {
5797 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
5800 mx = &mc->mc_xcursor->mx_cursor;
5801 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
5803 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
5804 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
5812 case MDB_NEXT_NODUP:
5813 if (!(mc->mc_flags & C_INITIALIZED))
5814 rc = mdb_cursor_first(mc, key, data);
5816 rc = mdb_cursor_next(mc, key, data, op);
5820 case MDB_PREV_NODUP:
5821 if (!(mc->mc_flags & C_INITIALIZED)) {
5822 rc = mdb_cursor_last(mc, key, data);
5825 mc->mc_flags |= C_INITIALIZED;
5826 mc->mc_ki[mc->mc_top]++;
5828 rc = mdb_cursor_prev(mc, key, data, op);
5831 rc = mdb_cursor_first(mc, key, data);
5834 mfunc = mdb_cursor_first;
5836 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5840 if (mc->mc_xcursor == NULL) {
5841 rc = MDB_INCOMPATIBLE;
5845 MDB_node *leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5846 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5847 MDB_GET_KEY(leaf, key);
5849 rc = mdb_node_read(mc->mc_txn, leaf, data);
5853 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
5857 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
5860 rc = mdb_cursor_last(mc, key, data);
5863 mfunc = mdb_cursor_last;
5866 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
5871 if (mc->mc_flags & C_DEL)
5872 mc->mc_flags ^= C_DEL;
5877 /** Touch all the pages in the cursor stack. Set mc_top.
5878 * Makes sure all the pages are writable, before attempting a write operation.
5879 * @param[in] mc The cursor to operate on.
5882 mdb_cursor_touch(MDB_cursor *mc)
5884 int rc = MDB_SUCCESS;
5886 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
5889 if (TXN_DBI_CHANGED(mc->mc_txn, mc->mc_dbi))
5891 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
5892 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
5895 *mc->mc_dbflag |= DB_DIRTY;
5900 rc = mdb_page_touch(mc);
5901 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
5902 mc->mc_top = mc->mc_snum-1;
5907 /** Do not spill pages to disk if txn is getting full, may fail instead */
5908 #define MDB_NOSPILL 0x8000
5911 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5914 enum { MDB_NO_ROOT = MDB_LAST_ERRCODE+10 }; /* internal code */
5916 MDB_node *leaf = NULL;
5919 MDB_val xdata, *rdata, dkey, olddata;
5921 int do_sub = 0, insert_key, insert_data;
5922 unsigned int mcount = 0, dcount = 0, nospill;
5925 unsigned int nflags;
5928 if (mc == NULL || key == NULL)
5931 env = mc->mc_txn->mt_env;
5933 /* Check this first so counter will always be zero on any
5936 if (flags & MDB_MULTIPLE) {
5937 dcount = data[1].mv_size;
5938 data[1].mv_size = 0;
5939 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
5940 return MDB_INCOMPATIBLE;
5943 nospill = flags & MDB_NOSPILL;
5944 flags &= ~MDB_NOSPILL;
5946 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
5947 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
5949 if (key->mv_size-1 >= ENV_MAXKEY(env))
5950 return MDB_BAD_VALSIZE;
5952 #if SIZE_MAX > MAXDATASIZE
5953 if (data->mv_size > ((mc->mc_db->md_flags & MDB_DUPSORT) ? ENV_MAXKEY(env) : MAXDATASIZE))
5954 return MDB_BAD_VALSIZE;
5956 if ((mc->mc_db->md_flags & MDB_DUPSORT) && data->mv_size > ENV_MAXKEY(env))
5957 return MDB_BAD_VALSIZE;
5960 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
5961 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
5965 if (flags == MDB_CURRENT) {
5966 if (!(mc->mc_flags & C_INITIALIZED))
5969 } else if (mc->mc_db->md_root == P_INVALID) {
5970 /* new database, cursor has nothing to point to */
5973 mc->mc_flags &= ~C_INITIALIZED;
5978 if (flags & MDB_APPEND) {
5980 rc = mdb_cursor_last(mc, &k2, &d2);
5982 rc = mc->mc_dbx->md_cmp(key, &k2);
5985 mc->mc_ki[mc->mc_top]++;
5987 /* new key is <= last key */
5992 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
5994 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
5995 DPRINTF(("duplicate key [%s]", DKEY(key)));
5997 return MDB_KEYEXIST;
5999 if (rc && rc != MDB_NOTFOUND)
6003 if (mc->mc_flags & C_DEL)
6004 mc->mc_flags ^= C_DEL;
6006 /* Cursor is positioned, check for room in the dirty list */
6008 if (flags & MDB_MULTIPLE) {
6010 xdata.mv_size = data->mv_size * dcount;
6014 if ((rc2 = mdb_page_spill(mc, key, rdata)))
6018 if (rc == MDB_NO_ROOT) {
6020 /* new database, write a root leaf page */
6021 DPUTS("allocating new root leaf page");
6022 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
6025 mdb_cursor_push(mc, np);
6026 mc->mc_db->md_root = np->mp_pgno;
6027 mc->mc_db->md_depth++;
6028 *mc->mc_dbflag |= DB_DIRTY;
6029 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
6031 np->mp_flags |= P_LEAF2;
6032 mc->mc_flags |= C_INITIALIZED;
6034 /* make sure all cursor pages are writable */
6035 rc2 = mdb_cursor_touch(mc);
6040 insert_key = insert_data = rc;
6042 /* The key does not exist */
6043 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
6044 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
6045 LEAFSIZE(key, data) > env->me_nodemax)
6047 /* Too big for a node, insert in sub-DB. Set up an empty
6048 * "old sub-page" for prep_subDB to expand to a full page.
6050 fp_flags = P_LEAF|P_DIRTY;
6052 fp->mp_pad = data->mv_size; /* used if MDB_DUPFIXED */
6053 fp->mp_lower = fp->mp_upper = (PAGEHDRSZ-PAGEBASE);
6054 olddata.mv_size = PAGEHDRSZ;
6058 /* there's only a key anyway, so this is a no-op */
6059 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
6061 unsigned int ksize = mc->mc_db->md_pad;
6062 if (key->mv_size != ksize)
6063 return MDB_BAD_VALSIZE;
6064 ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
6065 memcpy(ptr, key->mv_data, ksize);
6067 /* if overwriting slot 0 of leaf, need to
6068 * update branch key if there is a parent page
6070 if (mc->mc_top && !mc->mc_ki[mc->mc_top]) {
6071 unsigned short top = mc->mc_top;
6073 /* slot 0 is always an empty key, find real slot */
6074 while (mc->mc_top && !mc->mc_ki[mc->mc_top])
6076 if (mc->mc_ki[mc->mc_top])
6077 rc2 = mdb_update_key(mc, key);
6088 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6089 olddata.mv_size = NODEDSZ(leaf);
6090 olddata.mv_data = NODEDATA(leaf);
6093 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
6094 /* Prepare (sub-)page/sub-DB to accept the new item,
6095 * if needed. fp: old sub-page or a header faking
6096 * it. mp: new (sub-)page. offset: growth in page
6097 * size. xdata: node data with new page or DB.
6099 unsigned i, offset = 0;
6100 mp = fp = xdata.mv_data = env->me_pbuf;
6101 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
6103 /* Was a single item before, must convert now */
6104 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6105 /* Just overwrite the current item */
6106 if (flags == MDB_CURRENT)
6109 #if UINT_MAX < SIZE_MAX
6110 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && olddata.mv_size == sizeof(size_t))
6111 mc->mc_dbx->md_dcmp = mdb_cmp_clong;
6113 /* does data match? */
6114 if (!mc->mc_dbx->md_dcmp(data, &olddata)) {
6115 if (flags & MDB_NODUPDATA)
6116 return MDB_KEYEXIST;
6121 /* Back up original data item */
6122 dkey.mv_size = olddata.mv_size;
6123 dkey.mv_data = memcpy(fp+1, olddata.mv_data, olddata.mv_size);
6125 /* Make sub-page header for the dup items, with dummy body */
6126 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
6127 fp->mp_lower = (PAGEHDRSZ-PAGEBASE);
6128 xdata.mv_size = PAGEHDRSZ + dkey.mv_size + data->mv_size;
6129 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6130 fp->mp_flags |= P_LEAF2;
6131 fp->mp_pad = data->mv_size;
6132 xdata.mv_size += 2 * data->mv_size; /* leave space for 2 more */
6134 xdata.mv_size += 2 * (sizeof(indx_t) + NODESIZE) +
6135 (dkey.mv_size & 1) + (data->mv_size & 1);
6137 fp->mp_upper = xdata.mv_size - PAGEBASE;
6138 olddata.mv_size = xdata.mv_size; /* pretend olddata is fp */
6139 } else if (leaf->mn_flags & F_SUBDATA) {
6140 /* Data is on sub-DB, just store it */
6141 flags |= F_DUPDATA|F_SUBDATA;
6144 /* Data is on sub-page */
6145 fp = olddata.mv_data;
6148 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
6149 offset = EVEN(NODESIZE + sizeof(indx_t) +
6153 offset = fp->mp_pad;
6154 if (SIZELEFT(fp) < offset) {
6155 offset *= 4; /* space for 4 more */
6158 /* FALLTHRU: Big enough MDB_DUPFIXED sub-page */
6160 fp->mp_flags |= P_DIRTY;
6161 COPY_PGNO(fp->mp_pgno, mp->mp_pgno);
6162 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
6166 xdata.mv_size = olddata.mv_size + offset;
6169 fp_flags = fp->mp_flags;
6170 if (NODESIZE + NODEKSZ(leaf) + xdata.mv_size > env->me_nodemax) {
6171 /* Too big for a sub-page, convert to sub-DB */
6172 fp_flags &= ~P_SUBP;
6174 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6175 fp_flags |= P_LEAF2;
6176 dummy.md_pad = fp->mp_pad;
6177 dummy.md_flags = MDB_DUPFIXED;
6178 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6179 dummy.md_flags |= MDB_INTEGERKEY;
6185 dummy.md_branch_pages = 0;
6186 dummy.md_leaf_pages = 1;
6187 dummy.md_overflow_pages = 0;
6188 dummy.md_entries = NUMKEYS(fp);
6189 xdata.mv_size = sizeof(MDB_db);
6190 xdata.mv_data = &dummy;
6191 if ((rc = mdb_page_alloc(mc, 1, &mp)))
6193 offset = env->me_psize - olddata.mv_size;
6194 flags |= F_DUPDATA|F_SUBDATA;
6195 dummy.md_root = mp->mp_pgno;
6198 mp->mp_flags = fp_flags | P_DIRTY;
6199 mp->mp_pad = fp->mp_pad;
6200 mp->mp_lower = fp->mp_lower;
6201 mp->mp_upper = fp->mp_upper + offset;
6202 if (fp_flags & P_LEAF2) {
6203 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
6205 memcpy((char *)mp + mp->mp_upper + PAGEBASE, (char *)fp + fp->mp_upper + PAGEBASE,
6206 olddata.mv_size - fp->mp_upper - PAGEBASE);
6207 for (i=0; i<NUMKEYS(fp); i++)
6208 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
6216 mdb_node_del(mc, 0);
6220 /* overflow page overwrites need special handling */
6221 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6224 int level, ovpages, dpages = OVPAGES(data->mv_size, env->me_psize);
6226 memcpy(&pg, olddata.mv_data, sizeof(pg));
6227 if ((rc2 = mdb_page_get(mc->mc_txn, pg, &omp, &level)) != 0)
6229 ovpages = omp->mp_pages;
6231 /* Is the ov page large enough? */
6232 if (ovpages >= dpages) {
6233 if (!(omp->mp_flags & P_DIRTY) &&
6234 (level || (env->me_flags & MDB_WRITEMAP)))
6236 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
6239 level = 0; /* dirty in this txn or clean */
6242 if (omp->mp_flags & P_DIRTY) {
6243 /* yes, overwrite it. Note in this case we don't
6244 * bother to try shrinking the page if the new data
6245 * is smaller than the overflow threshold.
6248 /* It is writable only in a parent txn */
6249 size_t sz = (size_t) env->me_psize * ovpages, off;
6250 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
6256 rc2 = mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
6257 mdb_cassert(mc, rc2 == 0);
6258 if (!(flags & MDB_RESERVE)) {
6259 /* Copy end of page, adjusting alignment so
6260 * compiler may copy words instead of bytes.
6262 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
6263 memcpy((size_t *)((char *)np + off),
6264 (size_t *)((char *)omp + off), sz - off);
6267 memcpy(np, omp, sz); /* Copy beginning of page */
6270 SETDSZ(leaf, data->mv_size);
6271 if (F_ISSET(flags, MDB_RESERVE))
6272 data->mv_data = METADATA(omp);
6274 memcpy(METADATA(omp), data->mv_data, data->mv_size);
6278 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
6280 } else if (data->mv_size == olddata.mv_size) {
6281 /* same size, just replace it. Note that we could
6282 * also reuse this node if the new data is smaller,
6283 * but instead we opt to shrink the node in that case.
6285 if (F_ISSET(flags, MDB_RESERVE))
6286 data->mv_data = olddata.mv_data;
6287 else if (!(mc->mc_flags & C_SUB))
6288 memcpy(olddata.mv_data, data->mv_data, data->mv_size);
6290 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
6295 mdb_node_del(mc, 0);
6301 nflags = flags & NODE_ADD_FLAGS;
6302 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(env, key, rdata);
6303 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
6304 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
6305 nflags &= ~MDB_APPEND; /* sub-page may need room to grow */
6307 nflags |= MDB_SPLIT_REPLACE;
6308 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
6310 /* There is room already in this leaf page. */
6311 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
6312 if (rc == 0 && insert_key) {
6313 /* Adjust other cursors pointing to mp */
6314 MDB_cursor *m2, *m3;
6315 MDB_dbi dbi = mc->mc_dbi;
6316 unsigned i = mc->mc_top;
6317 MDB_page *mp = mc->mc_pg[i];
6319 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6320 if (mc->mc_flags & C_SUB)
6321 m3 = &m2->mc_xcursor->mx_cursor;
6324 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
6325 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
6332 if (rc == MDB_SUCCESS) {
6333 /* Now store the actual data in the child DB. Note that we're
6334 * storing the user data in the keys field, so there are strict
6335 * size limits on dupdata. The actual data fields of the child
6336 * DB are all zero size.
6344 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6345 if (flags & MDB_CURRENT) {
6346 xflags = MDB_CURRENT|MDB_NOSPILL;
6348 mdb_xcursor_init1(mc, leaf);
6349 xflags = (flags & MDB_NODUPDATA) ?
6350 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
6352 /* converted, write the original data first */
6354 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
6358 /* Adjust other cursors pointing to mp */
6360 unsigned i = mc->mc_top;
6361 MDB_page *mp = mc->mc_pg[i];
6363 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6364 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6365 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6366 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
6367 mdb_xcursor_init1(m2, leaf);
6371 /* we've done our job */
6374 ecount = mc->mc_xcursor->mx_db.md_entries;
6375 if (flags & MDB_APPENDDUP)
6376 xflags |= MDB_APPEND;
6377 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
6378 if (flags & F_SUBDATA) {
6379 void *db = NODEDATA(leaf);
6380 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6382 insert_data = mc->mc_xcursor->mx_db.md_entries - ecount;
6384 /* Increment count unless we just replaced an existing item. */
6386 mc->mc_db->md_entries++;
6388 /* Invalidate txn if we created an empty sub-DB */
6391 /* If we succeeded and the key didn't exist before,
6392 * make sure the cursor is marked valid.
6394 mc->mc_flags |= C_INITIALIZED;
6396 if (flags & MDB_MULTIPLE) {
6399 /* let caller know how many succeeded, if any */
6400 data[1].mv_size = mcount;
6401 if (mcount < dcount) {
6402 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
6403 insert_key = insert_data = 0;
6410 if (rc == MDB_KEYEXIST) /* should not happen, we deleted that item */
6413 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6418 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
6424 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
6425 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6427 if (!(mc->mc_flags & C_INITIALIZED))
6430 if (mc->mc_ki[mc->mc_top] >= NUMKEYS(mc->mc_pg[mc->mc_top]))
6431 return MDB_NOTFOUND;
6433 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
6436 rc = mdb_cursor_touch(mc);
6440 mp = mc->mc_pg[mc->mc_top];
6443 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6445 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6446 if (flags & MDB_NODUPDATA) {
6447 /* mdb_cursor_del0() will subtract the final entry */
6448 mc->mc_db->md_entries -= mc->mc_xcursor->mx_db.md_entries - 1;
6450 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
6451 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6453 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
6456 /* If sub-DB still has entries, we're done */
6457 if (mc->mc_xcursor->mx_db.md_entries) {
6458 if (leaf->mn_flags & F_SUBDATA) {
6459 /* update subDB info */
6460 void *db = NODEDATA(leaf);
6461 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6464 /* shrink fake page */
6465 mdb_node_shrink(mp, mc->mc_ki[mc->mc_top]);
6466 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6467 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6468 /* fix other sub-DB cursors pointed at this fake page */
6469 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6470 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6471 if (m2->mc_pg[mc->mc_top] == mp &&
6472 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
6473 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6476 mc->mc_db->md_entries--;
6477 mc->mc_flags |= C_DEL;
6480 /* otherwise fall thru and delete the sub-DB */
6483 if (leaf->mn_flags & F_SUBDATA) {
6484 /* add all the child DB's pages to the free list */
6485 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6491 /* add overflow pages to free list */
6492 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
6496 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
6497 if ((rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL)) ||
6498 (rc = mdb_ovpage_free(mc, omp)))
6503 return mdb_cursor_del0(mc);
6506 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6510 /** Allocate and initialize new pages for a database.
6511 * @param[in] mc a cursor on the database being added to.
6512 * @param[in] flags flags defining what type of page is being allocated.
6513 * @param[in] num the number of pages to allocate. This is usually 1,
6514 * unless allocating overflow pages for a large record.
6515 * @param[out] mp Address of a page, or NULL on failure.
6516 * @return 0 on success, non-zero on failure.
6519 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
6524 if ((rc = mdb_page_alloc(mc, num, &np)))
6526 DPRINTF(("allocated new mpage %"Z"u, page size %u",
6527 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
6528 np->mp_flags = flags | P_DIRTY;
6529 np->mp_lower = (PAGEHDRSZ-PAGEBASE);
6530 np->mp_upper = mc->mc_txn->mt_env->me_psize - PAGEBASE;
6533 mc->mc_db->md_branch_pages++;
6534 else if (IS_LEAF(np))
6535 mc->mc_db->md_leaf_pages++;
6536 else if (IS_OVERFLOW(np)) {
6537 mc->mc_db->md_overflow_pages += num;
6545 /** Calculate the size of a leaf node.
6546 * The size depends on the environment's page size; if a data item
6547 * is too large it will be put onto an overflow page and the node
6548 * size will only include the key and not the data. Sizes are always
6549 * rounded up to an even number of bytes, to guarantee 2-byte alignment
6550 * of the #MDB_node headers.
6551 * @param[in] env The environment handle.
6552 * @param[in] key The key for the node.
6553 * @param[in] data The data for the node.
6554 * @return The number of bytes needed to store the node.
6557 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
6561 sz = LEAFSIZE(key, data);
6562 if (sz > env->me_nodemax) {
6563 /* put on overflow page */
6564 sz -= data->mv_size - sizeof(pgno_t);
6567 return EVEN(sz + sizeof(indx_t));
6570 /** Calculate the size of a branch node.
6571 * The size should depend on the environment's page size but since
6572 * we currently don't support spilling large keys onto overflow
6573 * pages, it's simply the size of the #MDB_node header plus the
6574 * size of the key. Sizes are always rounded up to an even number
6575 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
6576 * @param[in] env The environment handle.
6577 * @param[in] key The key for the node.
6578 * @return The number of bytes needed to store the node.
6581 mdb_branch_size(MDB_env *env, MDB_val *key)
6586 if (sz > env->me_nodemax) {
6587 /* put on overflow page */
6588 /* not implemented */
6589 /* sz -= key->size - sizeof(pgno_t); */
6592 return sz + sizeof(indx_t);
6595 /** Add a node to the page pointed to by the cursor.
6596 * @param[in] mc The cursor for this operation.
6597 * @param[in] indx The index on the page where the new node should be added.
6598 * @param[in] key The key for the new node.
6599 * @param[in] data The data for the new node, if any.
6600 * @param[in] pgno The page number, if adding a branch node.
6601 * @param[in] flags Flags for the node.
6602 * @return 0 on success, non-zero on failure. Possible errors are:
6604 * <li>ENOMEM - failed to allocate overflow pages for the node.
6605 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
6606 * should never happen since all callers already calculate the
6607 * page's free space before calling this function.
6611 mdb_node_add(MDB_cursor *mc, indx_t indx,
6612 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
6615 size_t node_size = NODESIZE;
6619 MDB_page *mp = mc->mc_pg[mc->mc_top];
6620 MDB_page *ofp = NULL; /* overflow page */
6623 mdb_cassert(mc, mp->mp_upper >= mp->mp_lower);
6625 DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
6626 IS_LEAF(mp) ? "leaf" : "branch",
6627 IS_SUBP(mp) ? "sub-" : "",
6628 mdb_dbg_pgno(mp), indx, data ? data->mv_size : 0,
6629 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
6632 /* Move higher keys up one slot. */
6633 int ksize = mc->mc_db->md_pad, dif;
6634 char *ptr = LEAF2KEY(mp, indx, ksize);
6635 dif = NUMKEYS(mp) - indx;
6637 memmove(ptr+ksize, ptr, dif*ksize);
6638 /* insert new key */
6639 memcpy(ptr, key->mv_data, ksize);
6641 /* Just using these for counting */
6642 mp->mp_lower += sizeof(indx_t);
6643 mp->mp_upper -= ksize - sizeof(indx_t);
6647 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
6649 node_size += key->mv_size;
6651 mdb_cassert(mc, data);
6652 if (F_ISSET(flags, F_BIGDATA)) {
6653 /* Data already on overflow page. */
6654 node_size += sizeof(pgno_t);
6655 } else if (node_size + data->mv_size > mc->mc_txn->mt_env->me_nodemax) {
6656 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
6658 /* Put data on overflow page. */
6659 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
6660 data->mv_size, node_size+data->mv_size));
6661 node_size = EVEN(node_size + sizeof(pgno_t));
6662 if ((ssize_t)node_size > room)
6664 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
6666 DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
6670 node_size += data->mv_size;
6673 node_size = EVEN(node_size);
6674 if ((ssize_t)node_size > room)
6678 /* Move higher pointers up one slot. */
6679 for (i = NUMKEYS(mp); i > indx; i--)
6680 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
6682 /* Adjust free space offsets. */
6683 ofs = mp->mp_upper - node_size;
6684 mdb_cassert(mc, ofs >= mp->mp_lower + sizeof(indx_t));
6685 mp->mp_ptrs[indx] = ofs;
6687 mp->mp_lower += sizeof(indx_t);
6689 /* Write the node data. */
6690 node = NODEPTR(mp, indx);
6691 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
6692 node->mn_flags = flags;
6694 SETDSZ(node,data->mv_size);
6699 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6702 mdb_cassert(mc, key);
6704 if (F_ISSET(flags, F_BIGDATA))
6705 memcpy(node->mn_data + key->mv_size, data->mv_data,
6707 else if (F_ISSET(flags, MDB_RESERVE))
6708 data->mv_data = node->mn_data + key->mv_size;
6710 memcpy(node->mn_data + key->mv_size, data->mv_data,
6713 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
6715 if (F_ISSET(flags, MDB_RESERVE))
6716 data->mv_data = METADATA(ofp);
6718 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
6725 DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
6726 mdb_dbg_pgno(mp), NUMKEYS(mp)));
6727 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
6728 DPRINTF(("node size = %"Z"u", node_size));
6729 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
6730 return MDB_PAGE_FULL;
6733 /** Delete the specified node from a page.
6734 * @param[in] mc Cursor pointing to the node to delete.
6735 * @param[in] ksize The size of a node. Only used if the page is
6736 * part of a #MDB_DUPFIXED database.
6739 mdb_node_del(MDB_cursor *mc, int ksize)
6741 MDB_page *mp = mc->mc_pg[mc->mc_top];
6742 indx_t indx = mc->mc_ki[mc->mc_top];
6744 indx_t i, j, numkeys, ptr;
6748 DPRINTF(("delete node %u on %s page %"Z"u", indx,
6749 IS_LEAF(mp) ? "leaf" : "branch", mdb_dbg_pgno(mp)));
6750 numkeys = NUMKEYS(mp);
6751 mdb_cassert(mc, indx < numkeys);
6754 int x = numkeys - 1 - indx;
6755 base = LEAF2KEY(mp, indx, ksize);
6757 memmove(base, base + ksize, x * ksize);
6758 mp->mp_lower -= sizeof(indx_t);
6759 mp->mp_upper += ksize - sizeof(indx_t);
6763 node = NODEPTR(mp, indx);
6764 sz = NODESIZE + node->mn_ksize;
6766 if (F_ISSET(node->mn_flags, F_BIGDATA))
6767 sz += sizeof(pgno_t);
6769 sz += NODEDSZ(node);
6773 ptr = mp->mp_ptrs[indx];
6774 for (i = j = 0; i < numkeys; i++) {
6776 mp->mp_ptrs[j] = mp->mp_ptrs[i];
6777 if (mp->mp_ptrs[i] < ptr)
6778 mp->mp_ptrs[j] += sz;
6783 base = (char *)mp + mp->mp_upper + PAGEBASE;
6784 memmove(base + sz, base, ptr - mp->mp_upper);
6786 mp->mp_lower -= sizeof(indx_t);
6790 /** Compact the main page after deleting a node on a subpage.
6791 * @param[in] mp The main page to operate on.
6792 * @param[in] indx The index of the subpage on the main page.
6795 mdb_node_shrink(MDB_page *mp, indx_t indx)
6801 indx_t i, numkeys, ptr;
6803 node = NODEPTR(mp, indx);
6804 sp = (MDB_page *)NODEDATA(node);
6805 delta = SIZELEFT(sp);
6806 xp = (MDB_page *)((char *)sp + delta);
6808 /* shift subpage upward */
6810 nsize = NUMKEYS(sp) * sp->mp_pad;
6812 return; /* do not make the node uneven-sized */
6813 memmove(METADATA(xp), METADATA(sp), nsize);
6816 numkeys = NUMKEYS(sp);
6817 for (i=numkeys-1; i>=0; i--)
6818 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
6820 xp->mp_upper = sp->mp_lower;
6821 xp->mp_lower = sp->mp_lower;
6822 xp->mp_flags = sp->mp_flags;
6823 xp->mp_pad = sp->mp_pad;
6824 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
6826 nsize = NODEDSZ(node) - delta;
6827 SETDSZ(node, nsize);
6829 /* shift lower nodes upward */
6830 ptr = mp->mp_ptrs[indx];
6831 numkeys = NUMKEYS(mp);
6832 for (i = 0; i < numkeys; i++) {
6833 if (mp->mp_ptrs[i] <= ptr)
6834 mp->mp_ptrs[i] += delta;
6837 base = (char *)mp + mp->mp_upper + PAGEBASE;
6838 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
6839 mp->mp_upper += delta;
6842 /** Initial setup of a sorted-dups cursor.
6843 * Sorted duplicates are implemented as a sub-database for the given key.
6844 * The duplicate data items are actually keys of the sub-database.
6845 * Operations on the duplicate data items are performed using a sub-cursor
6846 * initialized when the sub-database is first accessed. This function does
6847 * the preliminary setup of the sub-cursor, filling in the fields that
6848 * depend only on the parent DB.
6849 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6852 mdb_xcursor_init0(MDB_cursor *mc)
6854 MDB_xcursor *mx = mc->mc_xcursor;
6856 mx->mx_cursor.mc_xcursor = NULL;
6857 mx->mx_cursor.mc_txn = mc->mc_txn;
6858 mx->mx_cursor.mc_db = &mx->mx_db;
6859 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
6860 mx->mx_cursor.mc_dbi = mc->mc_dbi;
6861 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
6862 mx->mx_cursor.mc_snum = 0;
6863 mx->mx_cursor.mc_top = 0;
6864 mx->mx_cursor.mc_flags = C_SUB;
6865 mx->mx_dbx.md_name.mv_size = 0;
6866 mx->mx_dbx.md_name.mv_data = NULL;
6867 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
6868 mx->mx_dbx.md_dcmp = NULL;
6869 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
6872 /** Final setup of a sorted-dups cursor.
6873 * Sets up the fields that depend on the data from the main cursor.
6874 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6875 * @param[in] node The data containing the #MDB_db record for the
6876 * sorted-dup database.
6879 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
6881 MDB_xcursor *mx = mc->mc_xcursor;
6883 if (node->mn_flags & F_SUBDATA) {
6884 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
6885 mx->mx_cursor.mc_pg[0] = 0;
6886 mx->mx_cursor.mc_snum = 0;
6887 mx->mx_cursor.mc_top = 0;
6888 mx->mx_cursor.mc_flags = C_SUB;
6890 MDB_page *fp = NODEDATA(node);
6891 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
6892 mx->mx_db.md_flags = 0;
6893 mx->mx_db.md_depth = 1;
6894 mx->mx_db.md_branch_pages = 0;
6895 mx->mx_db.md_leaf_pages = 1;
6896 mx->mx_db.md_overflow_pages = 0;
6897 mx->mx_db.md_entries = NUMKEYS(fp);
6898 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
6899 mx->mx_cursor.mc_snum = 1;
6900 mx->mx_cursor.mc_top = 0;
6901 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
6902 mx->mx_cursor.mc_pg[0] = fp;
6903 mx->mx_cursor.mc_ki[0] = 0;
6904 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6905 mx->mx_db.md_flags = MDB_DUPFIXED;
6906 mx->mx_db.md_pad = fp->mp_pad;
6907 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6908 mx->mx_db.md_flags |= MDB_INTEGERKEY;
6911 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
6912 mx->mx_db.md_root));
6913 mx->mx_dbflag = DB_VALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
6914 #if UINT_MAX < SIZE_MAX
6915 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
6916 mx->mx_dbx.md_cmp = mdb_cmp_clong;
6920 /** Initialize a cursor for a given transaction and database. */
6922 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
6925 mc->mc_backup = NULL;
6928 mc->mc_db = &txn->mt_dbs[dbi];
6929 mc->mc_dbx = &txn->mt_dbxs[dbi];
6930 mc->mc_dbflag = &txn->mt_dbflags[dbi];
6935 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
6936 mdb_tassert(txn, mx != NULL);
6937 mc->mc_xcursor = mx;
6938 mdb_xcursor_init0(mc);
6940 mc->mc_xcursor = NULL;
6942 if (*mc->mc_dbflag & DB_STALE) {
6943 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
6948 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
6951 size_t size = sizeof(MDB_cursor);
6953 if (!ret || !TXN_DBI_EXIST(txn, dbi))
6956 if (txn->mt_flags & MDB_TXN_ERROR)
6959 /* Allow read access to the freelist */
6960 if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
6963 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
6964 size += sizeof(MDB_xcursor);
6966 if ((mc = malloc(size)) != NULL) {
6967 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
6968 if (txn->mt_cursors) {
6969 mc->mc_next = txn->mt_cursors[dbi];
6970 txn->mt_cursors[dbi] = mc;
6971 mc->mc_flags |= C_UNTRACK;
6983 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
6985 if (!mc || !TXN_DBI_EXIST(txn, mc->mc_dbi))
6988 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
6991 if (txn->mt_flags & MDB_TXN_ERROR)
6994 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
6998 /* Return the count of duplicate data items for the current key */
7000 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
7004 if (mc == NULL || countp == NULL)
7007 if (mc->mc_xcursor == NULL)
7008 return MDB_INCOMPATIBLE;
7010 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
7013 if (!(mc->mc_flags & C_INITIALIZED))
7016 if (!mc->mc_snum || (mc->mc_flags & C_EOF))
7017 return MDB_NOTFOUND;
7019 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
7020 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
7023 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
7026 *countp = mc->mc_xcursor->mx_db.md_entries;
7032 mdb_cursor_close(MDB_cursor *mc)
7034 if (mc && !mc->mc_backup) {
7035 /* remove from txn, if tracked */
7036 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
7037 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
7038 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
7040 *prev = mc->mc_next;
7047 mdb_cursor_txn(MDB_cursor *mc)
7049 if (!mc) return NULL;
7054 mdb_cursor_dbi(MDB_cursor *mc)
7059 /** Replace the key for a branch node with a new key.
7060 * @param[in] mc Cursor pointing to the node to operate on.
7061 * @param[in] key The new key to use.
7062 * @return 0 on success, non-zero on failure.
7065 mdb_update_key(MDB_cursor *mc, MDB_val *key)
7071 int delta, ksize, oksize;
7072 indx_t ptr, i, numkeys, indx;
7075 indx = mc->mc_ki[mc->mc_top];
7076 mp = mc->mc_pg[mc->mc_top];
7077 node = NODEPTR(mp, indx);
7078 ptr = mp->mp_ptrs[indx];
7082 char kbuf2[DKBUF_MAXKEYSIZE*2+1];
7083 k2.mv_data = NODEKEY(node);
7084 k2.mv_size = node->mn_ksize;
7085 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
7087 mdb_dkey(&k2, kbuf2),
7093 /* Sizes must be 2-byte aligned. */
7094 ksize = EVEN(key->mv_size);
7095 oksize = EVEN(node->mn_ksize);
7096 delta = ksize - oksize;
7098 /* Shift node contents if EVEN(key length) changed. */
7100 if (delta > 0 && SIZELEFT(mp) < delta) {
7102 /* not enough space left, do a delete and split */
7103 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
7104 pgno = NODEPGNO(node);
7105 mdb_node_del(mc, 0);
7106 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
7109 numkeys = NUMKEYS(mp);
7110 for (i = 0; i < numkeys; i++) {
7111 if (mp->mp_ptrs[i] <= ptr)
7112 mp->mp_ptrs[i] -= delta;
7115 base = (char *)mp + mp->mp_upper + PAGEBASE;
7116 len = ptr - mp->mp_upper + NODESIZE;
7117 memmove(base - delta, base, len);
7118 mp->mp_upper -= delta;
7120 node = NODEPTR(mp, indx);
7123 /* But even if no shift was needed, update ksize */
7124 if (node->mn_ksize != key->mv_size)
7125 node->mn_ksize = key->mv_size;
7128 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
7134 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
7136 /** Move a node from csrc to cdst.
7139 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
7146 unsigned short flags;
7150 /* Mark src and dst as dirty. */
7151 if ((rc = mdb_page_touch(csrc)) ||
7152 (rc = mdb_page_touch(cdst)))
7155 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7156 key.mv_size = csrc->mc_db->md_pad;
7157 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
7159 data.mv_data = NULL;
7163 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
7164 mdb_cassert(csrc, !((size_t)srcnode & 1));
7165 srcpg = NODEPGNO(srcnode);
7166 flags = srcnode->mn_flags;
7167 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7168 unsigned int snum = csrc->mc_snum;
7170 /* must find the lowest key below src */
7171 rc = mdb_page_search_lowest(csrc);
7174 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7175 key.mv_size = csrc->mc_db->md_pad;
7176 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7178 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7179 key.mv_size = NODEKSZ(s2);
7180 key.mv_data = NODEKEY(s2);
7182 csrc->mc_snum = snum--;
7183 csrc->mc_top = snum;
7185 key.mv_size = NODEKSZ(srcnode);
7186 key.mv_data = NODEKEY(srcnode);
7188 data.mv_size = NODEDSZ(srcnode);
7189 data.mv_data = NODEDATA(srcnode);
7191 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
7192 unsigned int snum = cdst->mc_snum;
7195 /* must find the lowest key below dst */
7196 mdb_cursor_copy(cdst, &mn);
7197 rc = mdb_page_search_lowest(&mn);
7200 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7201 bkey.mv_size = mn.mc_db->md_pad;
7202 bkey.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, bkey.mv_size);
7204 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7205 bkey.mv_size = NODEKSZ(s2);
7206 bkey.mv_data = NODEKEY(s2);
7208 mn.mc_snum = snum--;
7211 rc = mdb_update_key(&mn, &bkey);
7216 DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
7217 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
7218 csrc->mc_ki[csrc->mc_top],
7220 csrc->mc_pg[csrc->mc_top]->mp_pgno,
7221 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
7223 /* Add the node to the destination page.
7225 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
7226 if (rc != MDB_SUCCESS)
7229 /* Delete the node from the source page.
7231 mdb_node_del(csrc, key.mv_size);
7234 /* Adjust other cursors pointing to mp */
7235 MDB_cursor *m2, *m3;
7236 MDB_dbi dbi = csrc->mc_dbi;
7237 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
7239 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7240 if (csrc->mc_flags & C_SUB)
7241 m3 = &m2->mc_xcursor->mx_cursor;
7244 if (m3 == csrc) continue;
7245 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
7246 csrc->mc_ki[csrc->mc_top]) {
7247 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
7248 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
7253 /* Update the parent separators.
7255 if (csrc->mc_ki[csrc->mc_top] == 0) {
7256 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
7257 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7258 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
7260 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
7261 key.mv_size = NODEKSZ(srcnode);
7262 key.mv_data = NODEKEY(srcnode);
7264 DPRINTF(("update separator for source page %"Z"u to [%s]",
7265 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
7266 mdb_cursor_copy(csrc, &mn);
7269 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7272 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
7274 indx_t ix = csrc->mc_ki[csrc->mc_top];
7275 nullkey.mv_size = 0;
7276 csrc->mc_ki[csrc->mc_top] = 0;
7277 rc = mdb_update_key(csrc, &nullkey);
7278 csrc->mc_ki[csrc->mc_top] = ix;
7279 mdb_cassert(csrc, rc == MDB_SUCCESS);
7283 if (cdst->mc_ki[cdst->mc_top] == 0) {
7284 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
7285 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
7286 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
7288 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
7289 key.mv_size = NODEKSZ(srcnode);
7290 key.mv_data = NODEKEY(srcnode);
7292 DPRINTF(("update separator for destination page %"Z"u to [%s]",
7293 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
7294 mdb_cursor_copy(cdst, &mn);
7297 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
7300 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
7302 indx_t ix = cdst->mc_ki[cdst->mc_top];
7303 nullkey.mv_size = 0;
7304 cdst->mc_ki[cdst->mc_top] = 0;
7305 rc = mdb_update_key(cdst, &nullkey);
7306 cdst->mc_ki[cdst->mc_top] = ix;
7307 mdb_cassert(csrc, rc == MDB_SUCCESS);
7314 /** Merge one page into another.
7315 * The nodes from the page pointed to by \b csrc will
7316 * be copied to the page pointed to by \b cdst and then
7317 * the \b csrc page will be freed.
7318 * @param[in] csrc Cursor pointing to the source page.
7319 * @param[in] cdst Cursor pointing to the destination page.
7320 * @return 0 on success, non-zero on failure.
7323 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
7325 MDB_page *psrc, *pdst;
7332 psrc = csrc->mc_pg[csrc->mc_top];
7333 pdst = cdst->mc_pg[cdst->mc_top];
7335 DPRINTF(("merging page %"Z"u into %"Z"u", psrc->mp_pgno, pdst->mp_pgno));
7337 mdb_cassert(csrc, csrc->mc_snum > 1); /* can't merge root page */
7338 mdb_cassert(csrc, cdst->mc_snum > 1);
7340 /* Mark dst as dirty. */
7341 if ((rc = mdb_page_touch(cdst)))
7344 /* Move all nodes from src to dst.
7346 j = nkeys = NUMKEYS(pdst);
7347 if (IS_LEAF2(psrc)) {
7348 key.mv_size = csrc->mc_db->md_pad;
7349 key.mv_data = METADATA(psrc);
7350 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7351 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
7352 if (rc != MDB_SUCCESS)
7354 key.mv_data = (char *)key.mv_data + key.mv_size;
7357 for (i = 0; i < NUMKEYS(psrc); i++, j++) {
7358 srcnode = NODEPTR(psrc, i);
7359 if (i == 0 && IS_BRANCH(psrc)) {
7362 mdb_cursor_copy(csrc, &mn);
7363 /* must find the lowest key below src */
7364 rc = mdb_page_search_lowest(&mn);
7367 if (IS_LEAF2(mn.mc_pg[mn.mc_top])) {
7368 key.mv_size = mn.mc_db->md_pad;
7369 key.mv_data = LEAF2KEY(mn.mc_pg[mn.mc_top], 0, key.mv_size);
7371 s2 = NODEPTR(mn.mc_pg[mn.mc_top], 0);
7372 key.mv_size = NODEKSZ(s2);
7373 key.mv_data = NODEKEY(s2);
7376 key.mv_size = srcnode->mn_ksize;
7377 key.mv_data = NODEKEY(srcnode);
7380 data.mv_size = NODEDSZ(srcnode);
7381 data.mv_data = NODEDATA(srcnode);
7382 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
7383 if (rc != MDB_SUCCESS)
7388 DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
7389 pdst->mp_pgno, NUMKEYS(pdst),
7390 (float)PAGEFILL(cdst->mc_txn->mt_env, pdst) / 10));
7392 /* Unlink the src page from parent and add to free list.
7395 mdb_node_del(csrc, 0);
7396 if (csrc->mc_ki[csrc->mc_top] == 0) {
7398 rc = mdb_update_key(csrc, &key);
7406 psrc = csrc->mc_pg[csrc->mc_top];
7407 /* If not operating on FreeDB, allow this page to be reused
7408 * in this txn. Otherwise just add to free list.
7410 rc = mdb_page_loose(csrc, psrc);
7414 csrc->mc_db->md_leaf_pages--;
7416 csrc->mc_db->md_branch_pages--;
7418 /* Adjust other cursors pointing to mp */
7419 MDB_cursor *m2, *m3;
7420 MDB_dbi dbi = csrc->mc_dbi;
7422 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7423 if (csrc->mc_flags & C_SUB)
7424 m3 = &m2->mc_xcursor->mx_cursor;
7427 if (m3 == csrc) continue;
7428 if (m3->mc_snum < csrc->mc_snum) continue;
7429 if (m3->mc_pg[csrc->mc_top] == psrc) {
7430 m3->mc_pg[csrc->mc_top] = pdst;
7431 m3->mc_ki[csrc->mc_top] += nkeys;
7436 unsigned int snum = cdst->mc_snum;
7437 uint16_t depth = cdst->mc_db->md_depth;
7438 mdb_cursor_pop(cdst);
7439 rc = mdb_rebalance(cdst);
7440 /* Did the tree shrink? */
7441 if (depth > cdst->mc_db->md_depth)
7443 cdst->mc_snum = snum;
7444 cdst->mc_top = snum-1;
7449 /** Copy the contents of a cursor.
7450 * @param[in] csrc The cursor to copy from.
7451 * @param[out] cdst The cursor to copy to.
7454 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
7458 cdst->mc_txn = csrc->mc_txn;
7459 cdst->mc_dbi = csrc->mc_dbi;
7460 cdst->mc_db = csrc->mc_db;
7461 cdst->mc_dbx = csrc->mc_dbx;
7462 cdst->mc_snum = csrc->mc_snum;
7463 cdst->mc_top = csrc->mc_top;
7464 cdst->mc_flags = csrc->mc_flags;
7466 for (i=0; i<csrc->mc_snum; i++) {
7467 cdst->mc_pg[i] = csrc->mc_pg[i];
7468 cdst->mc_ki[i] = csrc->mc_ki[i];
7472 /** Rebalance the tree after a delete operation.
7473 * @param[in] mc Cursor pointing to the page where rebalancing
7475 * @return 0 on success, non-zero on failure.
7478 mdb_rebalance(MDB_cursor *mc)
7482 unsigned int ptop, minkeys;
7486 minkeys = 1 + (IS_BRANCH(mc->mc_pg[mc->mc_top]));
7487 DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
7488 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
7489 mdb_dbg_pgno(mc->mc_pg[mc->mc_top]), NUMKEYS(mc->mc_pg[mc->mc_top]),
7490 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
7492 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD &&
7493 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
7494 DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
7495 mdb_dbg_pgno(mc->mc_pg[mc->mc_top])));
7499 if (mc->mc_snum < 2) {
7500 MDB_page *mp = mc->mc_pg[0];
7502 DPUTS("Can't rebalance a subpage, ignoring");
7505 if (NUMKEYS(mp) == 0) {
7506 DPUTS("tree is completely empty");
7507 mc->mc_db->md_root = P_INVALID;
7508 mc->mc_db->md_depth = 0;
7509 mc->mc_db->md_leaf_pages = 0;
7510 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7513 /* Adjust cursors pointing to mp */
7516 mc->mc_flags &= ~C_INITIALIZED;
7518 MDB_cursor *m2, *m3;
7519 MDB_dbi dbi = mc->mc_dbi;
7521 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7522 if (mc->mc_flags & C_SUB)
7523 m3 = &m2->mc_xcursor->mx_cursor;
7526 if (m3->mc_snum < mc->mc_snum) continue;
7527 if (m3->mc_pg[0] == mp) {
7530 m3->mc_flags &= ~C_INITIALIZED;
7534 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
7536 DPUTS("collapsing root page!");
7537 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7540 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
7541 rc = mdb_page_get(mc->mc_txn,mc->mc_db->md_root,&mc->mc_pg[0],NULL);
7544 mc->mc_db->md_depth--;
7545 mc->mc_db->md_branch_pages--;
7546 mc->mc_ki[0] = mc->mc_ki[1];
7547 for (i = 1; i<mc->mc_db->md_depth; i++) {
7548 mc->mc_pg[i] = mc->mc_pg[i+1];
7549 mc->mc_ki[i] = mc->mc_ki[i+1];
7552 /* Adjust other cursors pointing to mp */
7553 MDB_cursor *m2, *m3;
7554 MDB_dbi dbi = mc->mc_dbi;
7556 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7557 if (mc->mc_flags & C_SUB)
7558 m3 = &m2->mc_xcursor->mx_cursor;
7561 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
7562 if (m3->mc_pg[0] == mp) {
7565 for (i=0; i<m3->mc_snum; i++) {
7566 m3->mc_pg[i] = m3->mc_pg[i+1];
7567 m3->mc_ki[i] = m3->mc_ki[i+1];
7573 DPUTS("root page doesn't need rebalancing");
7577 /* The parent (branch page) must have at least 2 pointers,
7578 * otherwise the tree is invalid.
7580 ptop = mc->mc_top-1;
7581 mdb_cassert(mc, NUMKEYS(mc->mc_pg[ptop]) > 1);
7583 /* Leaf page fill factor is below the threshold.
7584 * Try to move keys from left or right neighbor, or
7585 * merge with a neighbor page.
7590 mdb_cursor_copy(mc, &mn);
7591 mn.mc_xcursor = NULL;
7593 oldki = mc->mc_ki[mc->mc_top];
7594 if (mc->mc_ki[ptop] == 0) {
7595 /* We're the leftmost leaf in our parent.
7597 DPUTS("reading right neighbor");
7599 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7600 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7603 mn.mc_ki[mn.mc_top] = 0;
7604 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
7606 /* There is at least one neighbor to the left.
7608 DPUTS("reading left neighbor");
7610 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7611 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7614 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
7615 mc->mc_ki[mc->mc_top] = 0;
7618 DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
7619 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
7620 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
7622 /* If the neighbor page is above threshold and has enough keys,
7623 * move one key from it. Otherwise we should try to merge them.
7624 * (A branch page must never have less than 2 keys.)
7626 minkeys = 1 + (IS_BRANCH(mn.mc_pg[mn.mc_top]));
7627 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys) {
7628 rc = mdb_node_move(&mn, mc);
7629 if (mc->mc_ki[ptop]) {
7633 if (mc->mc_ki[ptop] == 0) {
7634 rc = mdb_page_merge(&mn, mc);
7636 oldki += NUMKEYS(mn.mc_pg[mn.mc_top]);
7637 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
7638 rc = mdb_page_merge(mc, &mn);
7639 mdb_cursor_copy(&mn, mc);
7641 mc->mc_flags &= ~C_EOF;
7643 mc->mc_ki[mc->mc_top] = oldki;
7647 /** Complete a delete operation started by #mdb_cursor_del(). */
7649 mdb_cursor_del0(MDB_cursor *mc)
7656 ki = mc->mc_ki[mc->mc_top];
7657 mdb_node_del(mc, mc->mc_db->md_pad);
7658 mc->mc_db->md_entries--;
7659 rc = mdb_rebalance(mc);
7661 if (rc == MDB_SUCCESS) {
7662 MDB_cursor *m2, *m3;
7663 MDB_dbi dbi = mc->mc_dbi;
7665 mp = mc->mc_pg[mc->mc_top];
7666 nkeys = NUMKEYS(mp);
7668 /* if mc points past last node in page, find next sibling */
7669 if (mc->mc_ki[mc->mc_top] >= nkeys) {
7670 rc = mdb_cursor_sibling(mc, 1);
7671 if (rc == MDB_NOTFOUND) {
7672 mc->mc_flags |= C_EOF;
7677 /* Adjust other cursors pointing to mp */
7678 for (m2 = mc->mc_txn->mt_cursors[dbi]; !rc && m2; m2=m2->mc_next) {
7679 m3 = (mc->mc_flags & C_SUB) ? &m2->mc_xcursor->mx_cursor : m2;
7680 if (! (m2->mc_flags & m3->mc_flags & C_INITIALIZED))
7682 if (m3 == mc || m3->mc_snum < mc->mc_snum)
7684 if (m3->mc_pg[mc->mc_top] == mp) {
7685 if (m3->mc_ki[mc->mc_top] >= ki) {
7686 m3->mc_flags |= C_DEL;
7687 if (m3->mc_ki[mc->mc_top] > ki)
7688 m3->mc_ki[mc->mc_top]--;
7689 else if (mc->mc_db->md_flags & MDB_DUPSORT)
7690 m3->mc_xcursor->mx_cursor.mc_flags |= C_EOF;
7692 if (m3->mc_ki[mc->mc_top] >= nkeys) {
7693 rc = mdb_cursor_sibling(m3, 1);
7694 if (rc == MDB_NOTFOUND) {
7695 m3->mc_flags |= C_EOF;
7701 mc->mc_flags |= C_DEL;
7705 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7710 mdb_del(MDB_txn *txn, MDB_dbi dbi,
7711 MDB_val *key, MDB_val *data)
7713 if (!key || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
7716 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
7717 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7719 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
7720 /* must ignore any data */
7724 return mdb_del0(txn, dbi, key, data, 0);
7728 mdb_del0(MDB_txn *txn, MDB_dbi dbi,
7729 MDB_val *key, MDB_val *data, unsigned flags)
7734 MDB_val rdata, *xdata;
7738 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
7740 mdb_cursor_init(&mc, txn, dbi, &mx);
7749 flags |= MDB_NODUPDATA;
7751 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
7753 /* let mdb_page_split know about this cursor if needed:
7754 * delete will trigger a rebalance; if it needs to move
7755 * a node from one page to another, it will have to
7756 * update the parent's separator key(s). If the new sepkey
7757 * is larger than the current one, the parent page may
7758 * run out of space, triggering a split. We need this
7759 * cursor to be consistent until the end of the rebalance.
7761 mc.mc_flags |= C_UNTRACK;
7762 mc.mc_next = txn->mt_cursors[dbi];
7763 txn->mt_cursors[dbi] = &mc;
7764 rc = mdb_cursor_del(&mc, flags);
7765 txn->mt_cursors[dbi] = mc.mc_next;
7770 /** Split a page and insert a new node.
7771 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
7772 * The cursor will be updated to point to the actual page and index where
7773 * the node got inserted after the split.
7774 * @param[in] newkey The key for the newly inserted node.
7775 * @param[in] newdata The data for the newly inserted node.
7776 * @param[in] newpgno The page number, if the new node is a branch node.
7777 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
7778 * @return 0 on success, non-zero on failure.
7781 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
7782 unsigned int nflags)
7785 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
7788 int i, j, split_indx, nkeys, pmax;
7789 MDB_env *env = mc->mc_txn->mt_env;
7791 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
7792 MDB_page *copy = NULL;
7793 MDB_page *mp, *rp, *pp;
7798 mp = mc->mc_pg[mc->mc_top];
7799 newindx = mc->mc_ki[mc->mc_top];
7800 nkeys = NUMKEYS(mp);
7802 DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i/%i",
7803 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
7804 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
7806 /* Create a right sibling. */
7807 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
7809 DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
7811 if (mc->mc_snum < 2) {
7812 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
7814 /* shift current top to make room for new parent */
7815 mc->mc_pg[1] = mc->mc_pg[0];
7816 mc->mc_ki[1] = mc->mc_ki[0];
7819 mc->mc_db->md_root = pp->mp_pgno;
7820 DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
7821 mc->mc_db->md_depth++;
7824 /* Add left (implicit) pointer. */
7825 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
7826 /* undo the pre-push */
7827 mc->mc_pg[0] = mc->mc_pg[1];
7828 mc->mc_ki[0] = mc->mc_ki[1];
7829 mc->mc_db->md_root = mp->mp_pgno;
7830 mc->mc_db->md_depth--;
7837 ptop = mc->mc_top-1;
7838 DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
7841 mc->mc_flags |= C_SPLITTING;
7842 mdb_cursor_copy(mc, &mn);
7843 mn.mc_pg[mn.mc_top] = rp;
7844 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
7846 if (nflags & MDB_APPEND) {
7847 mn.mc_ki[mn.mc_top] = 0;
7849 split_indx = newindx;
7853 split_indx = (nkeys+1) / 2;
7858 unsigned int lsize, rsize, ksize;
7859 /* Move half of the keys to the right sibling */
7860 x = mc->mc_ki[mc->mc_top] - split_indx;
7861 ksize = mc->mc_db->md_pad;
7862 split = LEAF2KEY(mp, split_indx, ksize);
7863 rsize = (nkeys - split_indx) * ksize;
7864 lsize = (nkeys - split_indx) * sizeof(indx_t);
7865 mp->mp_lower -= lsize;
7866 rp->mp_lower += lsize;
7867 mp->mp_upper += rsize - lsize;
7868 rp->mp_upper -= rsize - lsize;
7869 sepkey.mv_size = ksize;
7870 if (newindx == split_indx) {
7871 sepkey.mv_data = newkey->mv_data;
7873 sepkey.mv_data = split;
7876 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
7877 memcpy(rp->mp_ptrs, split, rsize);
7878 sepkey.mv_data = rp->mp_ptrs;
7879 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
7880 memcpy(ins, newkey->mv_data, ksize);
7881 mp->mp_lower += sizeof(indx_t);
7882 mp->mp_upper -= ksize - sizeof(indx_t);
7885 memcpy(rp->mp_ptrs, split, x * ksize);
7886 ins = LEAF2KEY(rp, x, ksize);
7887 memcpy(ins, newkey->mv_data, ksize);
7888 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
7889 rp->mp_lower += sizeof(indx_t);
7890 rp->mp_upper -= ksize - sizeof(indx_t);
7891 mc->mc_ki[mc->mc_top] = x;
7892 mc->mc_pg[mc->mc_top] = rp;
7895 int psize, nsize, k;
7896 /* Maximum free space in an empty page */
7897 pmax = env->me_psize - PAGEHDRSZ;
7899 nsize = mdb_leaf_size(env, newkey, newdata);
7901 nsize = mdb_branch_size(env, newkey);
7902 nsize = EVEN(nsize);
7904 /* grab a page to hold a temporary copy */
7905 copy = mdb_page_malloc(mc->mc_txn, 1);
7910 copy->mp_pgno = mp->mp_pgno;
7911 copy->mp_flags = mp->mp_flags;
7912 copy->mp_lower = (PAGEHDRSZ-PAGEBASE);
7913 copy->mp_upper = env->me_psize - PAGEBASE;
7915 /* prepare to insert */
7916 for (i=0, j=0; i<nkeys; i++) {
7918 copy->mp_ptrs[j++] = 0;
7920 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
7923 /* When items are relatively large the split point needs
7924 * to be checked, because being off-by-one will make the
7925 * difference between success or failure in mdb_node_add.
7927 * It's also relevant if a page happens to be laid out
7928 * such that one half of its nodes are all "small" and
7929 * the other half of its nodes are "large." If the new
7930 * item is also "large" and falls on the half with
7931 * "large" nodes, it also may not fit.
7933 * As a final tweak, if the new item goes on the last
7934 * spot on the page (and thus, onto the new page), bias
7935 * the split so the new page is emptier than the old page.
7936 * This yields better packing during sequential inserts.
7938 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
7939 /* Find split point */
7941 if (newindx <= split_indx || newindx >= nkeys) {
7943 k = newindx >= nkeys ? nkeys : split_indx+2;
7948 for (; i!=k; i+=j) {
7953 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
7954 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
7956 if (F_ISSET(node->mn_flags, F_BIGDATA))
7957 psize += sizeof(pgno_t);
7959 psize += NODEDSZ(node);
7961 psize = EVEN(psize);
7963 if (psize > pmax || i == k-j) {
7964 split_indx = i + (j<0);
7969 if (split_indx == newindx) {
7970 sepkey.mv_size = newkey->mv_size;
7971 sepkey.mv_data = newkey->mv_data;
7973 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx] + PAGEBASE);
7974 sepkey.mv_size = node->mn_ksize;
7975 sepkey.mv_data = NODEKEY(node);
7980 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
7982 /* Copy separator key to the parent.
7984 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
7988 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
7993 if (mn.mc_snum == mc->mc_snum) {
7994 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
7995 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
7996 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
7997 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
8002 /* Right page might now have changed parent.
8003 * Check if left page also changed parent.
8005 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8006 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8007 for (i=0; i<ptop; i++) {
8008 mc->mc_pg[i] = mn.mc_pg[i];
8009 mc->mc_ki[i] = mn.mc_ki[i];
8011 mc->mc_pg[ptop] = mn.mc_pg[ptop];
8012 if (mn.mc_ki[ptop]) {
8013 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
8015 /* find right page's left sibling */
8016 mc->mc_ki[ptop] = mn.mc_ki[ptop];
8017 mdb_cursor_sibling(mc, 0);
8022 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
8025 mc->mc_flags ^= C_SPLITTING;
8026 if (rc != MDB_SUCCESS) {
8029 if (nflags & MDB_APPEND) {
8030 mc->mc_pg[mc->mc_top] = rp;
8031 mc->mc_ki[mc->mc_top] = 0;
8032 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
8035 for (i=0; i<mc->mc_top; i++)
8036 mc->mc_ki[i] = mn.mc_ki[i];
8037 } else if (!IS_LEAF2(mp)) {
8039 mc->mc_pg[mc->mc_top] = rp;
8044 rkey.mv_data = newkey->mv_data;
8045 rkey.mv_size = newkey->mv_size;
8051 /* Update index for the new key. */
8052 mc->mc_ki[mc->mc_top] = j;
8054 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i] + PAGEBASE);
8055 rkey.mv_data = NODEKEY(node);
8056 rkey.mv_size = node->mn_ksize;
8058 xdata.mv_data = NODEDATA(node);
8059 xdata.mv_size = NODEDSZ(node);
8062 pgno = NODEPGNO(node);
8063 flags = node->mn_flags;
8066 if (!IS_LEAF(mp) && j == 0) {
8067 /* First branch index doesn't need key data. */
8071 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
8077 mc->mc_pg[mc->mc_top] = copy;
8082 } while (i != split_indx);
8084 nkeys = NUMKEYS(copy);
8085 for (i=0; i<nkeys; i++)
8086 mp->mp_ptrs[i] = copy->mp_ptrs[i];
8087 mp->mp_lower = copy->mp_lower;
8088 mp->mp_upper = copy->mp_upper;
8089 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
8090 env->me_psize - copy->mp_upper - PAGEBASE);
8092 /* reset back to original page */
8093 if (newindx < split_indx) {
8094 mc->mc_pg[mc->mc_top] = mp;
8095 if (nflags & MDB_RESERVE) {
8096 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
8097 if (!(node->mn_flags & F_BIGDATA))
8098 newdata->mv_data = NODEDATA(node);
8101 mc->mc_pg[mc->mc_top] = rp;
8103 /* Make sure mc_ki is still valid.
8105 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
8106 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
8107 for (i=0; i<=ptop; i++) {
8108 mc->mc_pg[i] = mn.mc_pg[i];
8109 mc->mc_ki[i] = mn.mc_ki[i];
8116 /* Adjust other cursors pointing to mp */
8117 MDB_cursor *m2, *m3;
8118 MDB_dbi dbi = mc->mc_dbi;
8119 int fixup = NUMKEYS(mp);
8121 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
8122 if (mc->mc_flags & C_SUB)
8123 m3 = &m2->mc_xcursor->mx_cursor;
8128 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
8130 if (m3->mc_flags & C_SPLITTING)
8135 for (k=m3->mc_top; k>=0; k--) {
8136 m3->mc_ki[k+1] = m3->mc_ki[k];
8137 m3->mc_pg[k+1] = m3->mc_pg[k];
8139 if (m3->mc_ki[0] >= split_indx) {
8144 m3->mc_pg[0] = mc->mc_pg[0];
8148 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
8149 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
8150 m3->mc_ki[mc->mc_top]++;
8151 if (m3->mc_ki[mc->mc_top] >= fixup) {
8152 m3->mc_pg[mc->mc_top] = rp;
8153 m3->mc_ki[mc->mc_top] -= fixup;
8154 m3->mc_ki[ptop] = mn.mc_ki[ptop];
8156 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
8157 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
8162 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
8165 if (copy) /* tmp page */
8166 mdb_page_free(env, copy);
8168 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
8173 mdb_put(MDB_txn *txn, MDB_dbi dbi,
8174 MDB_val *key, MDB_val *data, unsigned int flags)
8179 if (!key || !data || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
8182 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP)) != flags)
8185 mdb_cursor_init(&mc, txn, dbi, &mx);
8186 return mdb_cursor_put(&mc, key, data, flags);
8190 #define MDB_WBUF (1024*1024)
8193 /** State needed for a compacting copy. */
8194 typedef struct mdb_copy {
8195 pthread_mutex_t mc_mutex;
8196 pthread_cond_t mc_cond;
8203 pgno_t mc_next_pgno;
8206 volatile int mc_new;
8211 /** Dedicated writer thread for compacting copy. */
8212 static THREAD_RET ESECT
8213 mdb_env_copythr(void *arg)
8217 int toggle = 0, wsize, rc;
8220 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8223 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8226 pthread_mutex_lock(&my->mc_mutex);
8228 pthread_cond_signal(&my->mc_cond);
8231 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8232 if (my->mc_new < 0) {
8237 wsize = my->mc_wlen[toggle];
8238 ptr = my->mc_wbuf[toggle];
8241 DO_WRITE(rc, my->mc_fd, ptr, wsize, len);
8245 } else if (len > 0) {
8259 /* If there's an overflow page tail, write it too */
8260 if (my->mc_olen[toggle]) {
8261 wsize = my->mc_olen[toggle];
8262 ptr = my->mc_over[toggle];
8263 my->mc_olen[toggle] = 0;
8266 my->mc_wlen[toggle] = 0;
8268 pthread_cond_signal(&my->mc_cond);
8270 pthread_cond_signal(&my->mc_cond);
8271 pthread_mutex_unlock(&my->mc_mutex);
8272 return (THREAD_RET)0;
8276 /** Tell the writer thread there's a buffer ready to write */
8278 mdb_env_cthr_toggle(mdb_copy *my, int st)
8280 int toggle = my->mc_toggle ^ 1;
8281 pthread_mutex_lock(&my->mc_mutex);
8282 if (my->mc_status) {
8283 pthread_mutex_unlock(&my->mc_mutex);
8284 return my->mc_status;
8286 while (my->mc_new == 1)
8287 pthread_cond_wait(&my->mc_cond, &my->mc_mutex);
8289 my->mc_toggle = toggle;
8290 pthread_cond_signal(&my->mc_cond);
8291 pthread_mutex_unlock(&my->mc_mutex);
8295 /** Depth-first tree traversal for compacting copy. */
8297 mdb_env_cwalk(mdb_copy *my, pgno_t *pg, int flags)
8300 MDB_txn *txn = my->mc_txn;
8302 MDB_page *mo, *mp, *leaf;
8307 /* Empty DB, nothing to do */
8308 if (*pg == P_INVALID)
8315 rc = mdb_page_get(my->mc_txn, *pg, &mc.mc_pg[0], NULL);
8318 rc = mdb_page_search_root(&mc, NULL, MDB_PS_FIRST);
8322 /* Make cursor pages writable */
8323 buf = ptr = malloc(my->mc_env->me_psize * mc.mc_snum);
8327 for (i=0; i<mc.mc_top; i++) {
8328 mdb_page_copy((MDB_page *)ptr, mc.mc_pg[i], my->mc_env->me_psize);
8329 mc.mc_pg[i] = (MDB_page *)ptr;
8330 ptr += my->mc_env->me_psize;
8333 /* This is writable space for a leaf page. Usually not needed. */
8334 leaf = (MDB_page *)ptr;
8336 toggle = my->mc_toggle;
8337 while (mc.mc_snum > 0) {
8339 mp = mc.mc_pg[mc.mc_top];
8343 if (!IS_LEAF2(mp) && !(flags & F_DUPDATA)) {
8344 for (i=0; i<n; i++) {
8345 ni = NODEPTR(mp, i);
8346 if (ni->mn_flags & F_BIGDATA) {
8350 /* Need writable leaf */
8352 mc.mc_pg[mc.mc_top] = leaf;
8353 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8355 ni = NODEPTR(mp, i);
8358 memcpy(&pg, NODEDATA(ni), sizeof(pg));
8359 rc = mdb_page_get(txn, pg, &omp, NULL);
8362 if (my->mc_wlen[toggle] >= MDB_WBUF) {
8363 rc = mdb_env_cthr_toggle(my, 1);
8366 toggle = my->mc_toggle;
8368 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
8369 memcpy(mo, omp, my->mc_env->me_psize);
8370 mo->mp_pgno = my->mc_next_pgno;
8371 my->mc_next_pgno += omp->mp_pages;
8372 my->mc_wlen[toggle] += my->mc_env->me_psize;
8373 if (omp->mp_pages > 1) {
8374 my->mc_olen[toggle] = my->mc_env->me_psize * (omp->mp_pages - 1);
8375 my->mc_over[toggle] = (char *)omp + my->mc_env->me_psize;
8376 rc = mdb_env_cthr_toggle(my, 1);
8379 toggle = my->mc_toggle;
8381 memcpy(NODEDATA(ni), &mo->mp_pgno, sizeof(pgno_t));
8382 } else if (ni->mn_flags & F_SUBDATA) {
8385 /* Need writable leaf */
8387 mc.mc_pg[mc.mc_top] = leaf;
8388 mdb_page_copy(leaf, mp, my->mc_env->me_psize);
8390 ni = NODEPTR(mp, i);
8393 memcpy(&db, NODEDATA(ni), sizeof(db));
8394 my->mc_toggle = toggle;
8395 rc = mdb_env_cwalk(my, &db.md_root, ni->mn_flags & F_DUPDATA);
8398 toggle = my->mc_toggle;
8399 memcpy(NODEDATA(ni), &db, sizeof(db));
8404 mc.mc_ki[mc.mc_top]++;
8405 if (mc.mc_ki[mc.mc_top] < n) {
8408 ni = NODEPTR(mp, mc.mc_ki[mc.mc_top]);
8410 rc = mdb_page_get(txn, pg, &mp, NULL);
8415 mc.mc_ki[mc.mc_top] = 0;
8416 if (IS_BRANCH(mp)) {
8417 /* Whenever we advance to a sibling branch page,
8418 * we must proceed all the way down to its first leaf.
8420 mdb_page_copy(mc.mc_pg[mc.mc_top], mp, my->mc_env->me_psize);
8423 mc.mc_pg[mc.mc_top] = mp;
8427 if (my->mc_wlen[toggle] >= MDB_WBUF) {
8428 rc = mdb_env_cthr_toggle(my, 1);
8431 toggle = my->mc_toggle;
8433 mo = (MDB_page *)(my->mc_wbuf[toggle] + my->mc_wlen[toggle]);
8434 mdb_page_copy(mo, mp, my->mc_env->me_psize);
8435 mo->mp_pgno = my->mc_next_pgno++;
8436 my->mc_wlen[toggle] += my->mc_env->me_psize;
8438 /* Update parent if there is one */
8439 ni = NODEPTR(mc.mc_pg[mc.mc_top-1], mc.mc_ki[mc.mc_top-1]);
8440 SETPGNO(ni, mo->mp_pgno);
8441 mdb_cursor_pop(&mc);
8443 /* Otherwise we're done */
8453 /** Copy environment with compaction. */
8455 mdb_env_copyfd1(MDB_env *env, HANDLE fd)
8460 MDB_txn *txn = NULL;
8465 my.mc_mutex = CreateMutex(NULL, FALSE, NULL);
8466 my.mc_cond = CreateEvent(NULL, FALSE, FALSE, NULL);
8467 my.mc_wbuf[0] = _aligned_malloc(MDB_WBUF*2, env->me_os_psize);
8468 if (my.mc_wbuf[0] == NULL)
8471 pthread_mutex_init(&my.mc_mutex, NULL);
8472 pthread_cond_init(&my.mc_cond, NULL);
8473 my.mc_wbuf[0] = memalign(env->me_os_psize, MDB_WBUF*2);
8474 if (my.mc_wbuf[0] == NULL)
8477 memset(my.mc_wbuf[0], 0, MDB_WBUF*2);
8478 my.mc_wbuf[1] = my.mc_wbuf[0] + MDB_WBUF;
8483 my.mc_next_pgno = 2;
8489 THREAD_CREATE(thr, mdb_env_copythr, &my);
8491 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
8495 mp = (MDB_page *)my.mc_wbuf[0];
8496 memset(mp, 0, 2*env->me_psize);
8498 mp->mp_flags = P_META;
8499 mm = (MDB_meta *)METADATA(mp);
8500 mdb_env_init_meta0(env, mm);
8501 mm->mm_address = env->me_metas[0]->mm_address;
8503 mp = (MDB_page *)(my.mc_wbuf[0] + env->me_psize);
8505 mp->mp_flags = P_META;
8506 *(MDB_meta *)METADATA(mp) = *mm;
8507 mm = (MDB_meta *)METADATA(mp);
8509 /* Count the number of free pages, subtract from lastpg to find
8510 * number of active pages
8513 MDB_ID freecount = 0;
8516 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
8517 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
8518 freecount += *(MDB_ID *)data.mv_data;
8519 freecount += txn->mt_dbs[0].md_branch_pages +
8520 txn->mt_dbs[0].md_leaf_pages +
8521 txn->mt_dbs[0].md_overflow_pages;
8523 /* Set metapage 1 */
8524 mm->mm_last_pg = txn->mt_next_pgno - freecount - 1;
8525 mm->mm_dbs[1] = txn->mt_dbs[1];
8526 mm->mm_dbs[1].md_root = mm->mm_last_pg;
8529 my.mc_wlen[0] = env->me_psize * 2;
8531 pthread_mutex_lock(&my.mc_mutex);
8533 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
8534 pthread_mutex_unlock(&my.mc_mutex);
8535 rc = mdb_env_cwalk(&my, &txn->mt_dbs[1].md_root, 0);
8536 if (rc == MDB_SUCCESS && my.mc_wlen[my.mc_toggle])
8537 rc = mdb_env_cthr_toggle(&my, 1);
8538 mdb_env_cthr_toggle(&my, -1);
8539 pthread_mutex_lock(&my.mc_mutex);
8541 pthread_cond_wait(&my.mc_cond, &my.mc_mutex);
8542 pthread_mutex_unlock(&my.mc_mutex);
8547 CloseHandle(my.mc_cond);
8548 CloseHandle(my.mc_mutex);
8549 _aligned_free(my.mc_wbuf[0]);
8551 pthread_cond_destroy(&my.mc_cond);
8552 pthread_mutex_destroy(&my.mc_mutex);
8553 free(my.mc_wbuf[0]);
8558 /** Copy environment as-is. */
8560 mdb_env_copyfd0(MDB_env *env, HANDLE fd)
8562 MDB_txn *txn = NULL;
8568 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
8572 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
8575 /* Do the lock/unlock of the reader mutex before starting the
8576 * write txn. Otherwise other read txns could block writers.
8578 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
8583 /* We must start the actual read txn after blocking writers */
8584 mdb_txn_reset0(txn, "reset-stage1");
8586 /* Temporarily block writers until we snapshot the meta pages */
8589 rc = mdb_txn_renew0(txn);
8591 UNLOCK_MUTEX_W(env);
8596 wsize = env->me_psize * 2;
8600 DO_WRITE(rc, fd, ptr, w2, len);
8604 } else if (len > 0) {
8610 /* Non-blocking or async handles are not supported */
8616 UNLOCK_MUTEX_W(env);
8621 w2 = txn->mt_next_pgno * env->me_psize;
8624 LARGE_INTEGER fsize;
8625 GetFileSizeEx(env->me_fd, &fsize);
8626 if (w2 > fsize.QuadPart)
8627 w2 = fsize.QuadPart;
8632 fstat(env->me_fd, &st);
8633 if (w2 > (size_t)st.st_size)
8639 if (wsize > MAX_WRITE)
8643 DO_WRITE(rc, fd, ptr, w2, len);
8647 } else if (len > 0) {
8664 mdb_env_copyfd2(MDB_env *env, HANDLE fd, unsigned int flags)
8666 if (flags & MDB_CP_COMPACT)
8667 return mdb_env_copyfd1(env, fd);
8669 return mdb_env_copyfd0(env, fd);
8673 mdb_env_copyfd(MDB_env *env, HANDLE fd)
8675 return mdb_env_copyfd2(env, fd, 0);
8679 mdb_env_copy2(MDB_env *env, const char *path, unsigned int flags)
8683 HANDLE newfd = INVALID_HANDLE_VALUE;
8685 if (env->me_flags & MDB_NOSUBDIR) {
8686 lpath = (char *)path;
8689 len += sizeof(DATANAME);
8690 lpath = malloc(len);
8693 sprintf(lpath, "%s" DATANAME, path);
8696 /* The destination path must exist, but the destination file must not.
8697 * We don't want the OS to cache the writes, since the source data is
8698 * already in the OS cache.
8701 newfd = CreateFile(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
8702 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
8704 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
8706 if (newfd == INVALID_HANDLE_VALUE) {
8711 if (env->me_psize >= env->me_os_psize) {
8713 /* Set O_DIRECT if the file system supports it */
8714 if ((rc = fcntl(newfd, F_GETFL)) != -1)
8715 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
8717 #ifdef F_NOCACHE /* __APPLE__ */
8718 rc = fcntl(newfd, F_NOCACHE, 1);
8726 rc = mdb_env_copyfd2(env, newfd, flags);
8729 if (!(env->me_flags & MDB_NOSUBDIR))
8731 if (newfd != INVALID_HANDLE_VALUE)
8732 if (close(newfd) < 0 && rc == MDB_SUCCESS)
8739 mdb_env_copy(MDB_env *env, const char *path)
8741 return mdb_env_copy2(env, path, 0);
8745 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
8747 if ((flag & CHANGEABLE) != flag)
8750 env->me_flags |= flag;
8752 env->me_flags &= ~flag;
8757 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
8762 *arg = env->me_flags;
8767 mdb_env_set_userctx(MDB_env *env, void *ctx)
8771 env->me_userctx = ctx;
8776 mdb_env_get_userctx(MDB_env *env)
8778 return env ? env->me_userctx : NULL;
8782 mdb_env_set_assert(MDB_env *env, MDB_assert_func *func)
8787 env->me_assert_func = func;
8793 mdb_env_get_path(MDB_env *env, const char **arg)
8798 *arg = env->me_path;
8803 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
8812 /** Common code for #mdb_stat() and #mdb_env_stat().
8813 * @param[in] env the environment to operate in.
8814 * @param[in] db the #MDB_db record containing the stats to return.
8815 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
8816 * @return 0, this function always succeeds.
8819 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
8821 arg->ms_psize = env->me_psize;
8822 arg->ms_depth = db->md_depth;
8823 arg->ms_branch_pages = db->md_branch_pages;
8824 arg->ms_leaf_pages = db->md_leaf_pages;
8825 arg->ms_overflow_pages = db->md_overflow_pages;
8826 arg->ms_entries = db->md_entries;
8832 mdb_env_stat(MDB_env *env, MDB_stat *arg)
8836 if (env == NULL || arg == NULL)
8839 toggle = mdb_env_pick_meta(env);
8841 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
8845 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
8849 if (env == NULL || arg == NULL)
8852 toggle = mdb_env_pick_meta(env);
8853 arg->me_mapaddr = env->me_metas[toggle]->mm_address;
8854 arg->me_mapsize = env->me_mapsize;
8855 arg->me_maxreaders = env->me_maxreaders;
8857 /* me_numreaders may be zero if this process never used any readers. Use
8858 * the shared numreader count if it exists.
8860 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : env->me_numreaders;
8862 arg->me_last_pgno = env->me_metas[toggle]->mm_last_pg;
8863 arg->me_last_txnid = env->me_metas[toggle]->mm_txnid;
8867 /** Set the default comparison functions for a database.
8868 * Called immediately after a database is opened to set the defaults.
8869 * The user can then override them with #mdb_set_compare() or
8870 * #mdb_set_dupsort().
8871 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
8872 * @param[in] dbi A database handle returned by #mdb_dbi_open()
8875 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
8877 uint16_t f = txn->mt_dbs[dbi].md_flags;
8879 txn->mt_dbxs[dbi].md_cmp =
8880 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
8881 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
8883 txn->mt_dbxs[dbi].md_dcmp =
8884 !(f & MDB_DUPSORT) ? 0 :
8885 ((f & MDB_INTEGERDUP)
8886 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
8887 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
8890 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
8896 int rc, dbflag, exact;
8897 unsigned int unused = 0, seq;
8900 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
8901 mdb_default_cmp(txn, FREE_DBI);
8904 if ((flags & VALID_FLAGS) != flags)
8906 if (txn->mt_flags & MDB_TXN_ERROR)
8912 if (flags & PERSISTENT_FLAGS) {
8913 uint16_t f2 = flags & PERSISTENT_FLAGS;
8914 /* make sure flag changes get committed */
8915 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
8916 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
8917 txn->mt_flags |= MDB_TXN_DIRTY;
8920 mdb_default_cmp(txn, MAIN_DBI);
8924 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
8925 mdb_default_cmp(txn, MAIN_DBI);
8928 /* Is the DB already open? */
8930 for (i=2; i<txn->mt_numdbs; i++) {
8931 if (!txn->mt_dbxs[i].md_name.mv_size) {
8932 /* Remember this free slot */
8933 if (!unused) unused = i;
8936 if (len == txn->mt_dbxs[i].md_name.mv_size &&
8937 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
8943 /* If no free slot and max hit, fail */
8944 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
8945 return MDB_DBS_FULL;
8947 /* Cannot mix named databases with some mainDB flags */
8948 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
8949 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
8951 /* Find the DB info */
8952 dbflag = DB_NEW|DB_VALID;
8955 key.mv_data = (void *)name;
8956 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
8957 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
8958 if (rc == MDB_SUCCESS) {
8959 /* make sure this is actually a DB */
8960 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
8961 if (!(node->mn_flags & F_SUBDATA))
8962 return MDB_INCOMPATIBLE;
8963 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
8964 /* Create if requested */
8965 data.mv_size = sizeof(MDB_db);
8966 data.mv_data = &dummy;
8967 memset(&dummy, 0, sizeof(dummy));
8968 dummy.md_root = P_INVALID;
8969 dummy.md_flags = flags & PERSISTENT_FLAGS;
8970 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
8974 /* OK, got info, add to table */
8975 if (rc == MDB_SUCCESS) {
8976 unsigned int slot = unused ? unused : txn->mt_numdbs;
8977 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
8978 txn->mt_dbxs[slot].md_name.mv_size = len;
8979 txn->mt_dbxs[slot].md_rel = NULL;
8980 txn->mt_dbflags[slot] = dbflag;
8981 /* txn-> and env-> are the same in read txns, use
8982 * tmp variable to avoid undefined assignment
8984 seq = ++txn->mt_env->me_dbiseqs[slot];
8985 txn->mt_dbiseqs[slot] = seq;
8987 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
8989 mdb_default_cmp(txn, slot);
8998 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
9000 if (!arg || !TXN_DBI_EXIST(txn, dbi))
9003 if (txn->mt_flags & MDB_TXN_ERROR)
9006 if (txn->mt_dbflags[dbi] & DB_STALE) {
9009 /* Stale, must read the DB's root. cursor_init does it for us. */
9010 mdb_cursor_init(&mc, txn, dbi, &mx);
9012 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
9015 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
9018 if (dbi <= MAIN_DBI || dbi >= env->me_maxdbs)
9020 ptr = env->me_dbxs[dbi].md_name.mv_data;
9021 /* If there was no name, this was already closed */
9023 env->me_dbxs[dbi].md_name.mv_data = NULL;
9024 env->me_dbxs[dbi].md_name.mv_size = 0;
9025 env->me_dbflags[dbi] = 0;
9026 env->me_dbiseqs[dbi]++;
9031 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
9033 /* We could return the flags for the FREE_DBI too but what's the point? */
9034 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9036 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
9040 /** Add all the DB's pages to the free list.
9041 * @param[in] mc Cursor on the DB to free.
9042 * @param[in] subs non-Zero to check for sub-DBs in this DB.
9043 * @return 0 on success, non-zero on failure.
9046 mdb_drop0(MDB_cursor *mc, int subs)
9050 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
9051 if (rc == MDB_SUCCESS) {
9052 MDB_txn *txn = mc->mc_txn;
9057 /* LEAF2 pages have no nodes, cannot have sub-DBs */
9058 if (IS_LEAF2(mc->mc_pg[mc->mc_top]))
9061 mdb_cursor_copy(mc, &mx);
9062 while (mc->mc_snum > 0) {
9063 MDB_page *mp = mc->mc_pg[mc->mc_top];
9064 unsigned n = NUMKEYS(mp);
9066 for (i=0; i<n; i++) {
9067 ni = NODEPTR(mp, i);
9068 if (ni->mn_flags & F_BIGDATA) {
9071 memcpy(&pg, NODEDATA(ni), sizeof(pg));
9072 rc = mdb_page_get(txn, pg, &omp, NULL);
9075 mdb_cassert(mc, IS_OVERFLOW(omp));
9076 rc = mdb_midl_append_range(&txn->mt_free_pgs,
9080 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
9081 mdb_xcursor_init1(mc, ni);
9082 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
9088 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
9090 for (i=0; i<n; i++) {
9092 ni = NODEPTR(mp, i);
9095 mdb_midl_xappend(txn->mt_free_pgs, pg);
9100 mc->mc_ki[mc->mc_top] = i;
9101 rc = mdb_cursor_sibling(mc, 1);
9103 if (rc != MDB_NOTFOUND)
9105 /* no more siblings, go back to beginning
9106 * of previous level.
9110 for (i=1; i<mc->mc_snum; i++) {
9112 mc->mc_pg[i] = mx.mc_pg[i];
9117 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
9120 txn->mt_flags |= MDB_TXN_ERROR;
9121 } else if (rc == MDB_NOTFOUND) {
9127 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
9129 MDB_cursor *mc, *m2;
9132 if ((unsigned)del > 1 || dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9135 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
9138 if (dbi > MAIN_DBI && TXN_DBI_CHANGED(txn, dbi))
9141 rc = mdb_cursor_open(txn, dbi, &mc);
9145 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
9146 /* Invalidate the dropped DB's cursors */
9147 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
9148 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
9152 /* Can't delete the main DB */
9153 if (del && dbi > MAIN_DBI) {
9154 rc = mdb_del0(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL, 0);
9156 txn->mt_dbflags[dbi] = DB_STALE;
9157 mdb_dbi_close(txn->mt_env, dbi);
9159 txn->mt_flags |= MDB_TXN_ERROR;
9162 /* reset the DB record, mark it dirty */
9163 txn->mt_dbflags[dbi] |= DB_DIRTY;
9164 txn->mt_dbs[dbi].md_depth = 0;
9165 txn->mt_dbs[dbi].md_branch_pages = 0;
9166 txn->mt_dbs[dbi].md_leaf_pages = 0;
9167 txn->mt_dbs[dbi].md_overflow_pages = 0;
9168 txn->mt_dbs[dbi].md_entries = 0;
9169 txn->mt_dbs[dbi].md_root = P_INVALID;
9171 txn->mt_flags |= MDB_TXN_DIRTY;
9174 mdb_cursor_close(mc);
9178 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9180 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9183 txn->mt_dbxs[dbi].md_cmp = cmp;
9187 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
9189 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9192 txn->mt_dbxs[dbi].md_dcmp = cmp;
9196 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
9198 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9201 txn->mt_dbxs[dbi].md_rel = rel;
9205 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
9207 if (dbi == FREE_DBI || !TXN_DBI_EXIST(txn, dbi))
9210 txn->mt_dbxs[dbi].md_relctx = ctx;
9215 mdb_env_get_maxkeysize(MDB_env *env)
9217 return ENV_MAXKEY(env);
9221 mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
9223 unsigned int i, rdrs;
9226 int rc = 0, first = 1;
9230 if (!env->me_txns) {
9231 return func("(no reader locks)\n", ctx);
9233 rdrs = env->me_txns->mti_numreaders;
9234 mr = env->me_txns->mti_readers;
9235 for (i=0; i<rdrs; i++) {
9237 txnid_t txnid = mr[i].mr_txnid;
9238 sprintf(buf, txnid == (txnid_t)-1 ?
9239 "%10d %"Z"x -\n" : "%10d %"Z"x %"Z"u\n",
9240 (int)mr[i].mr_pid, (size_t)mr[i].mr_tid, txnid);
9243 rc = func(" pid thread txnid\n", ctx);
9247 rc = func(buf, ctx);
9253 rc = func("(no active readers)\n", ctx);
9258 /** Insert pid into list if not already present.
9259 * return -1 if already present.
9262 mdb_pid_insert(MDB_PID_T *ids, MDB_PID_T pid)
9264 /* binary search of pid in list */
9266 unsigned cursor = 1;
9268 unsigned n = ids[0];
9271 unsigned pivot = n >> 1;
9272 cursor = base + pivot + 1;
9273 val = pid - ids[cursor];
9278 } else if ( val > 0 ) {
9283 /* found, so it's a duplicate */
9292 for (n = ids[0]; n > cursor; n--)
9299 mdb_reader_check(MDB_env *env, int *dead)
9301 unsigned int i, j, rdrs;
9303 MDB_PID_T *pids, pid;
9312 rdrs = env->me_txns->mti_numreaders;
9313 pids = malloc((rdrs+1) * sizeof(MDB_PID_T));
9317 mr = env->me_txns->mti_readers;
9318 for (i=0; i<rdrs; i++) {
9319 if (mr[i].mr_pid && mr[i].mr_pid != env->me_pid) {
9321 if (mdb_pid_insert(pids, pid) == 0) {
9322 if (!mdb_reader_pid(env, Pidcheck, pid)) {
9324 /* Recheck, a new process may have reused pid */
9325 if (!mdb_reader_pid(env, Pidcheck, pid)) {
9326 for (j=i; j<rdrs; j++)
9327 if (mr[j].mr_pid == pid) {
9328 DPRINTF(("clear stale reader pid %u txn %"Z"d",
9329 (unsigned) pid, mr[j].mr_txnid));
9334 UNLOCK_MUTEX_R(env);