2 * @brief memory-mapped database library
4 * A Btree-based database management library modeled loosely on the
5 * BerkeleyDB API, but much simplified.
8 * Copyright 2011-2013 Howard Chu, Symas Corp.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted only as authorized by the OpenLDAP
15 * A copy of this license is available in the file LICENSE in the
16 * top-level directory of the distribution or, alternatively, at
17 * <http://www.OpenLDAP.org/license.html>.
19 * This code is derived from btree.c written by Martin Hedenfalk.
21 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
23 * Permission to use, copy, modify, and distribute this software for any
24 * purpose with or without fee is hereby granted, provided that the above
25 * copyright notice and this permission notice appear in all copies.
27 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
28 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
29 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
30 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
31 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
32 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
33 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
38 #include <sys/types.h>
40 #include <sys/param.h>
46 #ifdef HAVE_SYS_FILE_H
63 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
64 #include <netinet/in.h>
65 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
68 #if defined(__APPLE__) || defined (BSD)
69 # define MDB_USE_POSIX_SEM 1
70 # define MDB_FDATASYNC fsync
71 #elif defined(ANDROID)
72 # define MDB_FDATASYNC fsync
77 #ifdef MDB_USE_POSIX_SEM
78 # define MDB_USE_HASH 1
79 #include <semaphore.h>
84 #include <valgrind/memcheck.h>
85 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
86 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
87 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
88 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
89 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
91 #define VGMEMP_CREATE(h,r,z)
92 #define VGMEMP_ALLOC(h,a,s)
93 #define VGMEMP_FREE(h,a)
94 #define VGMEMP_DESTROY(h)
95 #define VGMEMP_DEFINED(a,s)
99 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
100 /* Solaris just defines one or the other */
101 # define LITTLE_ENDIAN 1234
102 # define BIG_ENDIAN 4321
103 # ifdef _LITTLE_ENDIAN
104 # define BYTE_ORDER LITTLE_ENDIAN
106 # define BYTE_ORDER BIG_ENDIAN
109 # define BYTE_ORDER __BYTE_ORDER
113 #ifndef LITTLE_ENDIAN
114 #define LITTLE_ENDIAN __LITTLE_ENDIAN
117 #define BIG_ENDIAN __BIG_ENDIAN
120 #if defined(__i386) || defined(__x86_64) || defined(_M_IX86)
121 #define MISALIGNED_OK 1
127 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
128 # error "Unknown or unsupported endianness (BYTE_ORDER)"
129 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
130 # error "Two's complement, reasonably sized integer types, please"
133 /** @defgroup internal MDB Internals
136 /** @defgroup compat Windows Compatibility Macros
137 * A bunch of macros to minimize the amount of platform-specific ifdefs
138 * needed throughout the rest of the code. When the features this library
139 * needs are similar enough to POSIX to be hidden in a one-or-two line
140 * replacement, this macro approach is used.
144 #define MDB_USE_HASH 1
145 #define MDB_PIDLOCK 0
146 #define pthread_t DWORD
147 #define pthread_mutex_t HANDLE
148 #define pthread_key_t DWORD
149 #define pthread_self() GetCurrentThreadId()
150 #define pthread_key_create(x,y) \
151 ((*(x) = TlsAlloc()) == TLS_OUT_OF_INDEXES ? ErrCode() : 0)
152 #define pthread_key_delete(x) TlsFree(x)
153 #define pthread_getspecific(x) TlsGetValue(x)
154 #define pthread_setspecific(x,y) (TlsSetValue(x,y) ? 0 : ErrCode())
155 #define pthread_mutex_unlock(x) ReleaseMutex(x)
156 #define pthread_mutex_lock(x) WaitForSingleObject(x, INFINITE)
157 #define LOCK_MUTEX_R(env) pthread_mutex_lock((env)->me_rmutex)
158 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock((env)->me_rmutex)
159 #define LOCK_MUTEX_W(env) pthread_mutex_lock((env)->me_wmutex)
160 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock((env)->me_wmutex)
161 #define getpid() GetCurrentProcessId()
162 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
163 #define MDB_MSYNC(addr,len,flags) (!FlushViewOfFile(addr,len))
164 #define ErrCode() GetLastError()
165 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
166 #define close(fd) (CloseHandle(fd) ? 0 : -1)
167 #define munmap(ptr,len) UnmapViewOfFile(ptr)
168 #ifdef PROCESS_QUERY_LIMITED_INFORMATION
169 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION PROCESS_QUERY_LIMITED_INFORMATION
171 #define MDB_PROCESS_QUERY_LIMITED_INFORMATION 0x1000
176 #define Z "z" /**< printf format modifier for size_t */
178 /** For MDB_LOCK_FORMAT: True if readers take a pid lock in the lockfile */
179 #define MDB_PIDLOCK 1
181 #ifdef MDB_USE_POSIX_SEM
183 #define LOCK_MUTEX_R(env) mdb_sem_wait((env)->me_rmutex)
184 #define UNLOCK_MUTEX_R(env) sem_post((env)->me_rmutex)
185 #define LOCK_MUTEX_W(env) mdb_sem_wait((env)->me_wmutex)
186 #define UNLOCK_MUTEX_W(env) sem_post((env)->me_wmutex)
189 mdb_sem_wait(sem_t *sem)
192 while ((rc = sem_wait(sem)) && (rc = errno) == EINTR) ;
197 /** Lock the reader mutex.
199 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
200 /** Unlock the reader mutex.
202 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
204 /** Lock the writer mutex.
205 * Only a single write transaction is allowed at a time. Other writers
206 * will block waiting for this mutex.
208 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
209 /** Unlock the writer mutex.
211 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
212 #endif /* MDB_USE_POSIX_SEM */
214 /** Get the error code for the last failed system function.
216 #define ErrCode() errno
218 /** An abstraction for a file handle.
219 * On POSIX systems file handles are small integers. On Windows
220 * they're opaque pointers.
224 /** A value for an invalid file handle.
225 * Mainly used to initialize file variables and signify that they are
228 #define INVALID_HANDLE_VALUE (-1)
230 /** Get the size of a memory page for the system.
231 * This is the basic size that the platform's memory manager uses, and is
232 * fundamental to the use of memory-mapped files.
234 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
237 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
240 #define MNAME_LEN (sizeof(pthread_mutex_t))
246 /** A flag for opening a file and requesting synchronous data writes.
247 * This is only used when writing a meta page. It's not strictly needed;
248 * we could just do a normal write and then immediately perform a flush.
249 * But if this flag is available it saves us an extra system call.
251 * @note If O_DSYNC is undefined but exists in /usr/include,
252 * preferably set some compiler flag to get the definition.
253 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
256 # define MDB_DSYNC O_DSYNC
260 /** Function for flushing the data of a file. Define this to fsync
261 * if fdatasync() is not supported.
263 #ifndef MDB_FDATASYNC
264 # define MDB_FDATASYNC fdatasync
268 # define MDB_MSYNC(addr,len,flags) msync(addr,len,flags)
279 /** A page number in the database.
280 * Note that 64 bit page numbers are overkill, since pages themselves
281 * already represent 12-13 bits of addressable memory, and the OS will
282 * always limit applications to a maximum of 63 bits of address space.
284 * @note In the #MDB_node structure, we only store 48 bits of this value,
285 * which thus limits us to only 60 bits of addressable data.
287 typedef MDB_ID pgno_t;
289 /** A transaction ID.
290 * See struct MDB_txn.mt_txnid for details.
292 typedef MDB_ID txnid_t;
294 /** @defgroup debug Debug Macros
298 /** Enable debug output. Needs variable argument macros (a C99 feature).
299 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
300 * read from and written to the database (used for free space management).
306 static int mdb_debug;
307 static txnid_t mdb_debug_start;
309 /** Print a debug message with printf formatting.
310 * Requires double parenthesis around 2 or more args.
312 # define DPRINTF(args) ((void) ((mdb_debug) && DPRINTF0 args))
313 # define DPRINTF0(fmt, ...) \
314 fprintf(stderr, "%s:%d " fmt "\n", __func__, __LINE__, __VA_ARGS__)
316 # define DPRINTF(args) ((void) 0)
318 /** Print a debug string.
319 * The string is printed literally, with no format processing.
321 #define DPUTS(arg) DPRINTF(("%s", arg))
322 /** Debuging output value of a cursor DBI: Negative in a sub-cursor. */
324 (((mc)->mc_flags & C_SUB) ? -(int)(mc)->mc_dbi : (int)(mc)->mc_dbi)
327 /** A default memory page size.
328 * The actual size is platform-dependent, but we use this for
329 * boot-strapping. We probably should not be using this any more.
330 * The #GET_PAGESIZE() macro is used to get the actual size.
332 * Note that we don't currently support Huge pages. On Linux,
333 * regular data files cannot use Huge pages, and in general
334 * Huge pages aren't actually pageable. We rely on the OS
335 * demand-pager to read our data and page it out when memory
336 * pressure from other processes is high. So until OSs have
337 * actual paging support for Huge pages, they're not viable.
339 #define MDB_PAGESIZE 4096
341 /** The minimum number of keys required in a database page.
342 * Setting this to a larger value will place a smaller bound on the
343 * maximum size of a data item. Data items larger than this size will
344 * be pushed into overflow pages instead of being stored directly in
345 * the B-tree node. This value used to default to 4. With a page size
346 * of 4096 bytes that meant that any item larger than 1024 bytes would
347 * go into an overflow page. That also meant that on average 2-3KB of
348 * each overflow page was wasted space. The value cannot be lower than
349 * 2 because then there would no longer be a tree structure. With this
350 * value, items larger than 2KB will go into overflow pages, and on
351 * average only 1KB will be wasted.
353 #define MDB_MINKEYS 2
355 /** A stamp that identifies a file as an MDB file.
356 * There's nothing special about this value other than that it is easily
357 * recognizable, and it will reflect any byte order mismatches.
359 #define MDB_MAGIC 0xBEEFC0DE
361 /** The version number for a database's datafile format. */
362 #define MDB_DATA_VERSION 1
363 /** The version number for a database's lockfile format. */
364 #define MDB_LOCK_VERSION 1
366 /** @brief The maximum size of a key in the database.
368 * The library rejects bigger keys, and cannot deal with records
369 * with bigger keys stored by a library with bigger max keysize.
371 * We require that keys all fit onto a regular page. This limit
372 * could be raised a bit further if needed; to something just
373 * under #MDB_PAGESIZE / #MDB_MINKEYS.
375 * Note that data items in an #MDB_DUPSORT database are actually keys
376 * of a subDB, so they're also limited to this size.
378 #ifndef MDB_MAXKEYSIZE
379 #define MDB_MAXKEYSIZE 511
382 /** @brief The maximum size of a data item.
384 * We only store a 32 bit value for node sizes.
386 #define MAXDATASIZE 0xffffffffUL
391 * This is used for printing a hex dump of a key's contents.
393 #define DKBUF char kbuf[(MDB_MAXKEYSIZE*2+1)]
394 /** Display a key in hex.
396 * Invoke a function to display a key in hex.
398 #define DKEY(x) mdb_dkey(x, kbuf)
404 /** An invalid page number.
405 * Mainly used to denote an empty tree.
407 #define P_INVALID (~(pgno_t)0)
409 /** Test if the flags \b f are set in a flag word \b w. */
410 #define F_ISSET(w, f) (((w) & (f)) == (f))
412 /** Used for offsets within a single page.
413 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
416 typedef uint16_t indx_t;
418 /** Default size of memory map.
419 * This is certainly too small for any actual applications. Apps should always set
420 * the size explicitly using #mdb_env_set_mapsize().
422 #define DEFAULT_MAPSIZE 1048576
424 /** @defgroup readers Reader Lock Table
425 * Readers don't acquire any locks for their data access. Instead, they
426 * simply record their transaction ID in the reader table. The reader
427 * mutex is needed just to find an empty slot in the reader table. The
428 * slot's address is saved in thread-specific data so that subsequent read
429 * transactions started by the same thread need no further locking to proceed.
431 * If #MDB_NOTLS is set, the slot address is not saved in thread-specific data.
433 * No reader table is used if the database is on a read-only filesystem, or
434 * if #MDB_NOLOCK is set.
436 * Since the database uses multi-version concurrency control, readers don't
437 * actually need any locking. This table is used to keep track of which
438 * readers are using data from which old transactions, so that we'll know
439 * when a particular old transaction is no longer in use. Old transactions
440 * that have discarded any data pages can then have those pages reclaimed
441 * for use by a later write transaction.
443 * The lock table is constructed such that reader slots are aligned with the
444 * processor's cache line size. Any slot is only ever used by one thread.
445 * This alignment guarantees that there will be no contention or cache
446 * thrashing as threads update their own slot info, and also eliminates
447 * any need for locking when accessing a slot.
449 * A writer thread will scan every slot in the table to determine the oldest
450 * outstanding reader transaction. Any freed pages older than this will be
451 * reclaimed by the writer. The writer doesn't use any locks when scanning
452 * this table. This means that there's no guarantee that the writer will
453 * see the most up-to-date reader info, but that's not required for correct
454 * operation - all we need is to know the upper bound on the oldest reader,
455 * we don't care at all about the newest reader. So the only consequence of
456 * reading stale information here is that old pages might hang around a
457 * while longer before being reclaimed. That's actually good anyway, because
458 * the longer we delay reclaiming old pages, the more likely it is that a
459 * string of contiguous pages can be found after coalescing old pages from
460 * many old transactions together.
463 /** Number of slots in the reader table.
464 * This value was chosen somewhat arbitrarily. 126 readers plus a
465 * couple mutexes fit exactly into 8KB on my development machine.
466 * Applications should set the table size using #mdb_env_set_maxreaders().
468 #define DEFAULT_READERS 126
470 /** The size of a CPU cache line in bytes. We want our lock structures
471 * aligned to this size to avoid false cache line sharing in the
473 * This value works for most CPUs. For Itanium this should be 128.
479 /** The information we store in a single slot of the reader table.
480 * In addition to a transaction ID, we also record the process and
481 * thread ID that owns a slot, so that we can detect stale information,
482 * e.g. threads or processes that went away without cleaning up.
483 * @note We currently don't check for stale records. We simply re-init
484 * the table when we know that we're the only process opening the
487 typedef struct MDB_rxbody {
488 /** Current Transaction ID when this transaction began, or (txnid_t)-1.
489 * Multiple readers that start at the same time will probably have the
490 * same ID here. Again, it's not important to exclude them from
491 * anything; all we need to know is which version of the DB they
492 * started from so we can avoid overwriting any data used in that
493 * particular version.
496 /** The process ID of the process owning this reader txn. */
498 /** The thread ID of the thread owning this txn. */
502 /** The actual reader record, with cacheline padding. */
503 typedef struct MDB_reader {
506 /** shorthand for mrb_txnid */
507 #define mr_txnid mru.mrx.mrb_txnid
508 #define mr_pid mru.mrx.mrb_pid
509 #define mr_tid mru.mrx.mrb_tid
510 /** cache line alignment */
511 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
515 /** The header for the reader table.
516 * The table resides in a memory-mapped file. (This is a different file
517 * than is used for the main database.)
519 * For POSIX the actual mutexes reside in the shared memory of this
520 * mapped file. On Windows, mutexes are named objects allocated by the
521 * kernel; we store the mutex names in this mapped file so that other
522 * processes can grab them. This same approach is also used on
523 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
524 * process-shared POSIX mutexes. For these cases where a named object
525 * is used, the object name is derived from a 64 bit FNV hash of the
526 * environment pathname. As such, naming collisions are extremely
527 * unlikely. If a collision occurs, the results are unpredictable.
529 typedef struct MDB_txbody {
530 /** Stamp identifying this as an MDB file. It must be set
533 /** Format of this lock file. Must be set to #MDB_LOCK_FORMAT. */
535 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
536 char mtb_rmname[MNAME_LEN];
538 /** Mutex protecting access to this table.
539 * This is the reader lock that #LOCK_MUTEX_R acquires.
541 pthread_mutex_t mtb_mutex;
543 /** The ID of the last transaction committed to the database.
544 * This is recorded here only for convenience; the value can always
545 * be determined by reading the main database meta pages.
548 /** The number of slots that have been used in the reader table.
549 * This always records the maximum count, it is not decremented
550 * when readers release their slots.
552 unsigned mtb_numreaders;
555 /** The actual reader table definition. */
556 typedef struct MDB_txninfo {
559 #define mti_magic mt1.mtb.mtb_magic
560 #define mti_format mt1.mtb.mtb_format
561 #define mti_mutex mt1.mtb.mtb_mutex
562 #define mti_rmname mt1.mtb.mtb_rmname
563 #define mti_txnid mt1.mtb.mtb_txnid
564 #define mti_numreaders mt1.mtb.mtb_numreaders
565 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
568 #if defined(_WIN32) || defined(MDB_USE_POSIX_SEM)
569 char mt2_wmname[MNAME_LEN];
570 #define mti_wmname mt2.mt2_wmname
572 pthread_mutex_t mt2_wmutex;
573 #define mti_wmutex mt2.mt2_wmutex
575 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
577 MDB_reader mti_readers[1];
580 /** Lockfile format signature: version, features and field layout */
581 #define MDB_LOCK_FORMAT \
583 ((MDB_LOCK_VERSION) \
584 /* Flags which describe functionality */ \
585 + (((MDB_PIDLOCK) != 0) << 16)))
588 /** Common header for all page types.
589 * Overflow records occupy a number of contiguous pages with no
590 * headers on any page after the first.
592 typedef struct MDB_page {
593 #define mp_pgno mp_p.p_pgno
594 #define mp_next mp_p.p_next
596 pgno_t p_pgno; /**< page number */
597 void * p_next; /**< for in-memory list of freed structs */
600 /** @defgroup mdb_page Page Flags
602 * Flags for the page headers.
605 #define P_BRANCH 0x01 /**< branch page */
606 #define P_LEAF 0x02 /**< leaf page */
607 #define P_OVERFLOW 0x04 /**< overflow page */
608 #define P_META 0x08 /**< meta page */
609 #define P_DIRTY 0x10 /**< dirty page, also set for #P_SUBP pages */
610 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
611 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
612 #define P_KEEP 0x8000 /**< leave this page alone during spill */
614 uint16_t mp_flags; /**< @ref mdb_page */
615 #define mp_lower mp_pb.pb.pb_lower
616 #define mp_upper mp_pb.pb.pb_upper
617 #define mp_pages mp_pb.pb_pages
620 indx_t pb_lower; /**< lower bound of free space */
621 indx_t pb_upper; /**< upper bound of free space */
623 uint32_t pb_pages; /**< number of overflow pages */
625 indx_t mp_ptrs[1]; /**< dynamic size */
628 /** Size of the page header, excluding dynamic data at the end */
629 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
631 /** Address of first usable data byte in a page, after the header */
632 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
634 /** Number of nodes on a page */
635 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
637 /** The amount of space remaining in the page */
638 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
640 /** The percentage of space used in the page, in tenths of a percent. */
641 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
642 ((env)->me_psize - PAGEHDRSZ))
643 /** The minimum page fill factor, in tenths of a percent.
644 * Pages emptier than this are candidates for merging.
646 #define FILL_THRESHOLD 250
648 /** Test if a page is a leaf page */
649 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
650 /** Test if a page is a LEAF2 page */
651 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
652 /** Test if a page is a branch page */
653 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
654 /** Test if a page is an overflow page */
655 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
656 /** Test if a page is a sub page */
657 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
659 /** The number of overflow pages needed to store the given size. */
660 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
662 /** Header for a single key/data pair within a page.
663 * We guarantee 2-byte alignment for nodes.
665 typedef struct MDB_node {
666 /** lo and hi are used for data size on leaf nodes and for
667 * child pgno on branch nodes. On 64 bit platforms, flags
668 * is also used for pgno. (Branch nodes have no flags).
669 * They are in host byte order in case that lets some
670 * accesses be optimized into a 32-bit word access.
672 #define mn_lo mn_offset[BYTE_ORDER!=LITTLE_ENDIAN]
673 #define mn_hi mn_offset[BYTE_ORDER==LITTLE_ENDIAN] /**< part of dsize or pgno */
674 unsigned short mn_offset[2]; /**< storage for #mn_lo and #mn_hi */
675 /** @defgroup mdb_node Node Flags
677 * Flags for node headers.
680 #define F_BIGDATA 0x01 /**< data put on overflow page */
681 #define F_SUBDATA 0x02 /**< data is a sub-database */
682 #define F_DUPDATA 0x04 /**< data has duplicates */
684 /** valid flags for #mdb_node_add() */
685 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
688 unsigned short mn_flags; /**< @ref mdb_node */
689 unsigned short mn_ksize; /**< key size */
690 char mn_data[1]; /**< key and data are appended here */
693 /** Size of the node header, excluding dynamic data at the end */
694 #define NODESIZE offsetof(MDB_node, mn_data)
696 /** Bit position of top word in page number, for shifting mn_flags */
697 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
699 /** Size of a node in a branch page with a given key.
700 * This is just the node header plus the key, there is no data.
702 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
704 /** Size of a node in a leaf page with a given key and data.
705 * This is node header plus key plus data size.
707 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
709 /** Address of node \b i in page \b p */
710 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
712 /** Address of the key for the node */
713 #define NODEKEY(node) (void *)((node)->mn_data)
715 /** Address of the data for a node */
716 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
718 /** Get the page number pointed to by a branch node */
719 #define NODEPGNO(node) \
720 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
721 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
722 /** Set the page number in a branch node */
723 #define SETPGNO(node,pgno) do { \
724 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
725 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
727 /** Get the size of the data in a leaf node */
728 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
729 /** Set the size of the data for a leaf node */
730 #define SETDSZ(node,size) do { \
731 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
732 /** The size of a key in a node */
733 #define NODEKSZ(node) ((node)->mn_ksize)
735 /** Copy a page number from src to dst */
737 #define COPY_PGNO(dst,src) dst = src
739 #if SIZE_MAX > 4294967295UL
740 #define COPY_PGNO(dst,src) do { \
741 unsigned short *s, *d; \
742 s = (unsigned short *)&(src); \
743 d = (unsigned short *)&(dst); \
750 #define COPY_PGNO(dst,src) do { \
751 unsigned short *s, *d; \
752 s = (unsigned short *)&(src); \
753 d = (unsigned short *)&(dst); \
759 /** The address of a key in a LEAF2 page.
760 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
761 * There are no node headers, keys are stored contiguously.
763 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
765 /** Set the \b node's key into \b keyptr, if requested. */
766 #define MDB_GET_KEY(node, keyptr) { if ((keyptr) != NULL) { \
767 (keyptr)->mv_size = NODEKSZ(node); (keyptr)->mv_data = NODEKEY(node); } }
769 /** Set the \b node's key into \b key. */
770 #define MDB_GET_KEY2(node, key) { key.mv_size = NODEKSZ(node); key.mv_data = NODEKEY(node); }
772 /** Information about a single database in the environment. */
773 typedef struct MDB_db {
774 uint32_t md_pad; /**< also ksize for LEAF2 pages */
775 uint16_t md_flags; /**< @ref mdb_dbi_open */
776 uint16_t md_depth; /**< depth of this tree */
777 pgno_t md_branch_pages; /**< number of internal pages */
778 pgno_t md_leaf_pages; /**< number of leaf pages */
779 pgno_t md_overflow_pages; /**< number of overflow pages */
780 size_t md_entries; /**< number of data items */
781 pgno_t md_root; /**< the root page of this tree */
784 /** mdb_dbi_open flags */
785 #define MDB_VALID 0x8000 /**< DB handle is valid, for me_dbflags */
786 #define PERSISTENT_FLAGS (0xffff & ~(MDB_VALID))
787 #define VALID_FLAGS (MDB_REVERSEKEY|MDB_DUPSORT|MDB_INTEGERKEY|MDB_DUPFIXED|\
788 MDB_INTEGERDUP|MDB_REVERSEDUP|MDB_CREATE)
790 /** Handle for the DB used to track free pages. */
792 /** Handle for the default DB. */
795 /** Meta page content.
796 * A meta page is the start point for accessing a database snapshot.
797 * Pages 0-1 are meta pages. Transaction N writes meta page #(N % 2).
799 typedef struct MDB_meta {
800 /** Stamp identifying this as an MDB file. It must be set
803 /** Version number of this lock file. Must be set to #MDB_DATA_VERSION. */
805 void *mm_address; /**< address for fixed mapping */
806 size_t mm_mapsize; /**< size of mmap region */
807 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
808 /** The size of pages used in this DB */
809 #define mm_psize mm_dbs[0].md_pad
810 /** Any persistent environment flags. @ref mdb_env */
811 #define mm_flags mm_dbs[0].md_flags
812 pgno_t mm_last_pg; /**< last used page in file */
813 txnid_t mm_txnid; /**< txnid that committed this page */
816 /** Buffer for a stack-allocated dirty page.
817 * The members define size and alignment, and silence type
818 * aliasing warnings. They are not used directly; that could
819 * mean incorrectly using several union members in parallel.
821 typedef union MDB_pagebuf {
822 char mb_raw[MDB_PAGESIZE];
825 char mm_pad[PAGEHDRSZ];
830 /** Auxiliary DB info.
831 * The information here is mostly static/read-only. There is
832 * only a single copy of this record in the environment.
834 typedef struct MDB_dbx {
835 MDB_val md_name; /**< name of the database */
836 MDB_cmp_func *md_cmp; /**< function for comparing keys */
837 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
838 MDB_rel_func *md_rel; /**< user relocate function */
839 void *md_relctx; /**< user-provided context for md_rel */
842 /** A database transaction.
843 * Every operation requires a transaction handle.
846 MDB_txn *mt_parent; /**< parent of a nested txn */
847 MDB_txn *mt_child; /**< nested txn under this txn */
848 pgno_t mt_next_pgno; /**< next unallocated page */
849 /** The ID of this transaction. IDs are integers incrementing from 1.
850 * Only committed write transactions increment the ID. If a transaction
851 * aborts, the ID may be re-used by the next writer.
854 MDB_env *mt_env; /**< the DB environment */
855 /** The list of pages that became unused during this transaction.
858 /** The sorted list of dirty pages we temporarily wrote to disk
859 * because the dirty list was full. page numbers in here are
860 * shifted left by 1, deleted slots have the LSB set.
862 MDB_IDL mt_spill_pgs;
864 /** For write txns: Modified pages. Sorted when not MDB_WRITEMAP. */
866 /** For read txns: This thread/txn's reader table slot, or NULL. */
869 /** Array of records for each DB known in the environment. */
871 /** Array of MDB_db records for each known DB */
873 /** @defgroup mt_dbflag Transaction DB Flags
877 #define DB_DIRTY 0x01 /**< DB was modified or is DUPSORT data */
878 #define DB_STALE 0x02 /**< Named-DB record is older than txnID */
879 #define DB_NEW 0x04 /**< Named-DB handle opened in this txn */
880 #define DB_VALID 0x08 /**< DB handle is valid, see also #MDB_VALID */
882 /** In write txns, array of cursors for each DB */
883 MDB_cursor **mt_cursors;
884 /** Array of flags for each DB */
885 unsigned char *mt_dbflags;
886 /** Number of DB records in use. This number only ever increments;
887 * we don't decrement it when individual DB handles are closed.
891 /** @defgroup mdb_txn Transaction Flags
895 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
896 #define MDB_TXN_ERROR 0x02 /**< an error has occurred */
897 #define MDB_TXN_DIRTY 0x04 /**< must write, even if dirty list is empty */
898 #define MDB_TXN_SPILLS 0x08 /**< txn or a parent has spilled pages */
900 unsigned int mt_flags; /**< @ref mdb_txn */
901 /** dirty_list room: Array size - #dirty pages visible to this txn.
902 * Includes ancestor txns' dirty pages not hidden by other txns'
903 * dirty/spilled pages. Thus commit(nested txn) has room to merge
904 * dirty_list into mt_parent after freeing hidden mt_parent pages.
906 unsigned int mt_dirty_room;
909 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
910 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
911 * raise this on a 64 bit machine.
913 #define CURSOR_STACK 32
917 /** Cursors are used for all DB operations.
918 * A cursor holds a path of (page pointer, key index) from the DB
919 * root to a position in the DB, plus other state. #MDB_DUPSORT
920 * cursors include an xcursor to the current data item. Write txns
921 * track their cursors and keep them up to date when data moves.
922 * Exception: An xcursor's pointer to a #P_SUBP page can be stale.
923 * (A node with #F_DUPDATA but no #F_SUBDATA contains a subpage).
926 /** Next cursor on this DB in this txn */
928 /** Backup of the original cursor if this cursor is a shadow */
929 MDB_cursor *mc_backup;
930 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
931 struct MDB_xcursor *mc_xcursor;
932 /** The transaction that owns this cursor */
934 /** The database handle this cursor operates on */
936 /** The database record for this cursor */
938 /** The database auxiliary record for this cursor */
940 /** The @ref mt_dbflag for this database */
941 unsigned char *mc_dbflag;
942 unsigned short mc_snum; /**< number of pushed pages */
943 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
944 /** @defgroup mdb_cursor Cursor Flags
946 * Cursor state flags.
949 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
950 #define C_EOF 0x02 /**< No more data */
951 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
952 #define C_DEL 0x08 /**< last op was a cursor_del */
953 #define C_SPLITTING 0x20 /**< Cursor is in page_split */
954 #define C_UNTRACK 0x40 /**< Un-track cursor when closing */
956 unsigned int mc_flags; /**< @ref mdb_cursor */
957 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
958 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
961 /** Context for sorted-dup records.
962 * We could have gone to a fully recursive design, with arbitrarily
963 * deep nesting of sub-databases. But for now we only handle these
964 * levels - main DB, optional sub-DB, sorted-duplicate DB.
966 typedef struct MDB_xcursor {
967 /** A sub-cursor for traversing the Dup DB */
968 MDB_cursor mx_cursor;
969 /** The database record for this Dup DB */
971 /** The auxiliary DB record for this Dup DB */
973 /** The @ref mt_dbflag for this Dup DB */
974 unsigned char mx_dbflag;
977 /** State of FreeDB old pages, stored in the MDB_env */
978 typedef struct MDB_pgstate {
979 pgno_t *mf_pghead; /**< Reclaimed freeDB pages, or NULL before use */
980 txnid_t mf_pglast; /**< ID of last used record, or 0 if !mf_pghead */
983 /** The database environment. */
985 HANDLE me_fd; /**< The main data file */
986 HANDLE me_lfd; /**< The lock file */
987 HANDLE me_mfd; /**< just for writing the meta pages */
988 /** Failed to update the meta page. Probably an I/O error. */
989 #define MDB_FATAL_ERROR 0x80000000U
990 /** Some fields are initialized. */
991 #define MDB_ENV_ACTIVE 0x20000000U
992 /** me_txkey is set */
993 #define MDB_ENV_TXKEY 0x10000000U
994 /** Have liveness lock in reader table */
995 #define MDB_LIVE_READER 0x08000000U
996 uint32_t me_flags; /**< @ref mdb_env */
997 unsigned int me_psize; /**< size of a page, from #GET_PAGESIZE */
998 unsigned int me_maxreaders; /**< size of the reader table */
999 unsigned int me_numreaders; /**< max numreaders set by this env */
1000 MDB_dbi me_numdbs; /**< number of DBs opened */
1001 MDB_dbi me_maxdbs; /**< size of the DB table */
1002 pid_t me_pid; /**< process ID of this env */
1003 char *me_path; /**< path to the DB files */
1004 char *me_map; /**< the memory map of the data file */
1005 MDB_txninfo *me_txns; /**< the memory map of the lock file or NULL */
1006 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
1007 MDB_txn *me_txn; /**< current write transaction */
1008 size_t me_mapsize; /**< size of the data memory map */
1009 off_t me_size; /**< current file size */
1010 pgno_t me_maxpg; /**< me_mapsize / me_psize */
1011 MDB_dbx *me_dbxs; /**< array of static DB info */
1012 uint16_t *me_dbflags; /**< array of flags from MDB_db.md_flags */
1013 pthread_key_t me_txkey; /**< thread-key for readers */
1014 MDB_pgstate me_pgstate; /**< state of old pages from freeDB */
1015 # define me_pglast me_pgstate.mf_pglast
1016 # define me_pghead me_pgstate.mf_pghead
1017 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
1018 /** IDL of pages that became unused in a write txn */
1019 MDB_IDL me_free_pgs;
1020 /** ID2L of pages written during a write txn. Length MDB_IDL_UM_SIZE. */
1021 MDB_ID2L me_dirty_list;
1022 /** Max number of freelist items that can fit in a single overflow page */
1024 /** Max size of a node on a page */
1025 unsigned int me_nodemax;
1027 int me_pidquery; /**< Used in OpenProcess */
1028 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
1030 #elif defined(MDB_USE_POSIX_SEM)
1031 sem_t *me_rmutex; /* Shared mutexes are not supported */
1036 /** Nested transaction */
1037 typedef struct MDB_ntxn {
1038 MDB_txn mnt_txn; /**< the transaction */
1039 MDB_pgstate mnt_pgstate; /**< parent transaction's saved freestate */
1042 /** max number of pages to commit in one writev() call */
1043 #define MDB_COMMIT_PAGES 64
1044 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
1045 #undef MDB_COMMIT_PAGES
1046 #define MDB_COMMIT_PAGES IOV_MAX
1049 /* max bytes to write in one call */
1050 #define MAX_WRITE (0x80000000U >> (sizeof(ssize_t) == 4))
1052 static int mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp);
1053 static int mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp);
1054 static int mdb_page_touch(MDB_cursor *mc);
1056 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp, int *lvl);
1057 static int mdb_page_search_root(MDB_cursor *mc,
1058 MDB_val *key, int modify);
1059 #define MDB_PS_MODIFY 1
1060 #define MDB_PS_ROOTONLY 2
1061 #define MDB_PS_FIRST 4
1062 #define MDB_PS_LAST 8
1063 static int mdb_page_search(MDB_cursor *mc,
1064 MDB_val *key, int flags);
1065 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
1067 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
1068 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
1069 pgno_t newpgno, unsigned int nflags);
1071 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
1072 static int mdb_env_pick_meta(const MDB_env *env);
1073 static int mdb_env_write_meta(MDB_txn *txn);
1074 #if !(defined(_WIN32) || defined(MDB_USE_POSIX_SEM)) /* Drop unused excl arg */
1075 # define mdb_env_close0(env, excl) mdb_env_close1(env)
1077 static void mdb_env_close0(MDB_env *env, int excl);
1079 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
1080 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
1081 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
1082 static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
1083 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
1084 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
1085 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
1086 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
1087 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
1089 static int mdb_rebalance(MDB_cursor *mc);
1090 static int mdb_update_key(MDB_cursor *mc, MDB_val *key);
1092 static void mdb_cursor_pop(MDB_cursor *mc);
1093 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
1095 static int mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
1096 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
1097 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1098 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
1099 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
1101 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1102 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
1104 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
1105 static void mdb_xcursor_init0(MDB_cursor *mc);
1106 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
1108 static int mdb_drop0(MDB_cursor *mc, int subs);
1109 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
1112 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
1116 static SECURITY_DESCRIPTOR mdb_null_sd;
1117 static SECURITY_ATTRIBUTES mdb_all_sa;
1118 static int mdb_sec_inited;
1121 /** Return the library version info. */
1123 mdb_version(int *major, int *minor, int *patch)
1125 if (major) *major = MDB_VERSION_MAJOR;
1126 if (minor) *minor = MDB_VERSION_MINOR;
1127 if (patch) *patch = MDB_VERSION_PATCH;
1128 return MDB_VERSION_STRING;
1131 /** Table of descriptions for MDB @ref errors */
1132 static char *const mdb_errstr[] = {
1133 "MDB_KEYEXIST: Key/data pair already exists",
1134 "MDB_NOTFOUND: No matching key/data pair found",
1135 "MDB_PAGE_NOTFOUND: Requested page not found",
1136 "MDB_CORRUPTED: Located page was wrong type",
1137 "MDB_PANIC: Update of meta page failed",
1138 "MDB_VERSION_MISMATCH: Database environment version mismatch",
1139 "MDB_INVALID: File is not an MDB file",
1140 "MDB_MAP_FULL: Environment mapsize limit reached",
1141 "MDB_DBS_FULL: Environment maxdbs limit reached",
1142 "MDB_READERS_FULL: Environment maxreaders limit reached",
1143 "MDB_TLS_FULL: Thread-local storage keys full - too many environments open",
1144 "MDB_TXN_FULL: Transaction has too many dirty pages - transaction too big",
1145 "MDB_CURSOR_FULL: Internal error - cursor stack limit reached",
1146 "MDB_PAGE_FULL: Internal error - page has no more space",
1147 "MDB_MAP_RESIZED: Database contents grew beyond environment mapsize",
1148 "MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed",
1149 "MDB_BAD_RSLOT: Invalid reuse of reader locktable slot",
1150 "MDB_BAD_TXN: Transaction cannot recover - it must be aborted",
1151 "MDB_BAD_VALSIZE: Too big key/data, key is empty, or wrong DUPFIXED size",
1155 mdb_strerror(int err)
1159 return ("Successful return: 0");
1161 if (err >= MDB_KEYEXIST && err <= MDB_LAST_ERRCODE) {
1162 i = err - MDB_KEYEXIST;
1163 return mdb_errstr[i];
1166 return strerror(err);
1170 /** Display a key in hexadecimal and return the address of the result.
1171 * @param[in] key the key to display
1172 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1173 * @return The key in hexadecimal form.
1176 mdb_dkey(MDB_val *key, char *buf)
1179 unsigned char *c = key->mv_data;
1185 if (key->mv_size > MDB_MAXKEYSIZE)
1186 return "MDB_MAXKEYSIZE";
1187 /* may want to make this a dynamic check: if the key is mostly
1188 * printable characters, print it as-is instead of converting to hex.
1192 for (i=0; i<key->mv_size; i++)
1193 ptr += sprintf(ptr, "%02x", *c++);
1195 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1200 /** Display all the keys in the page. */
1202 mdb_page_list(MDB_page *mp)
1205 unsigned int i, nkeys, nsize;
1209 nkeys = NUMKEYS(mp);
1210 fprintf(stderr, "Page %"Z"u numkeys %d\n", mp->mp_pgno, nkeys);
1211 for (i=0; i<nkeys; i++) {
1212 node = NODEPTR(mp, i);
1213 key.mv_size = node->mn_ksize;
1214 key.mv_data = node->mn_data;
1215 nsize = NODESIZE + NODEKSZ(node) + sizeof(indx_t);
1216 if (IS_BRANCH(mp)) {
1217 fprintf(stderr, "key %d: page %"Z"u, %s\n", i, NODEPGNO(node),
1220 if (F_ISSET(node->mn_flags, F_BIGDATA))
1221 nsize += sizeof(pgno_t);
1223 nsize += NODEDSZ(node);
1224 fprintf(stderr, "key %d: nsize %d, %s\n", i, nsize, DKEY(&key));
1230 mdb_cursor_chk(MDB_cursor *mc)
1236 if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1237 for (i=0; i<mc->mc_top; i++) {
1239 node = NODEPTR(mp, mc->mc_ki[i]);
1240 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1243 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1249 /** Count all the pages in each DB and in the freelist
1250 * and make sure it matches the actual number of pages
1253 static void mdb_audit(MDB_txn *txn)
1257 MDB_ID freecount, count;
1262 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1263 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1264 freecount += *(MDB_ID *)data.mv_data;
1267 for (i = 0; i<txn->mt_numdbs; i++) {
1269 mdb_cursor_init(&mc, txn, i, &mx);
1270 if (txn->mt_dbs[i].md_root == P_INVALID)
1272 count += txn->mt_dbs[i].md_branch_pages +
1273 txn->mt_dbs[i].md_leaf_pages +
1274 txn->mt_dbs[i].md_overflow_pages;
1275 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1276 mdb_page_search(&mc, NULL, MDB_PS_FIRST);
1280 mp = mc.mc_pg[mc.mc_top];
1281 for (j=0; j<NUMKEYS(mp); j++) {
1282 MDB_node *leaf = NODEPTR(mp, j);
1283 if (leaf->mn_flags & F_SUBDATA) {
1285 memcpy(&db, NODEDATA(leaf), sizeof(db));
1286 count += db.md_branch_pages + db.md_leaf_pages +
1287 db.md_overflow_pages;
1291 while (mdb_cursor_sibling(&mc, 1) == 0);
1294 if (freecount + count + 2 /* metapages */ != txn->mt_next_pgno) {
1295 fprintf(stderr, "audit: %lu freecount: %lu count: %lu total: %lu next_pgno: %lu\n",
1296 txn->mt_txnid, freecount, count+2, freecount+count+2, txn->mt_next_pgno);
1302 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1304 return txn->mt_dbxs[dbi].md_cmp(a, b);
1308 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1310 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1313 /** Allocate memory for a page.
1314 * Re-use old malloc'd pages first for singletons, otherwise just malloc.
1317 mdb_page_malloc(MDB_txn *txn, unsigned num)
1319 MDB_env *env = txn->mt_env;
1320 MDB_page *ret = env->me_dpages;
1321 size_t sz = env->me_psize;
1324 VGMEMP_ALLOC(env, ret, sz);
1325 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1326 env->me_dpages = ret->mp_next;
1332 if ((ret = malloc(sz)) != NULL) {
1333 VGMEMP_ALLOC(env, ret, sz);
1338 /** Free a single page.
1339 * Saves single pages to a list, for future reuse.
1340 * (This is not used for multi-page overflow pages.)
1343 mdb_page_free(MDB_env *env, MDB_page *mp)
1345 mp->mp_next = env->me_dpages;
1346 VGMEMP_FREE(env, mp);
1347 env->me_dpages = mp;
1350 /** Free a dirty page */
1352 mdb_dpage_free(MDB_env *env, MDB_page *dp)
1354 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1355 mdb_page_free(env, dp);
1357 /* large pages just get freed directly */
1358 VGMEMP_FREE(env, dp);
1363 /** Return all dirty pages to dpage list */
1365 mdb_dlist_free(MDB_txn *txn)
1367 MDB_env *env = txn->mt_env;
1368 MDB_ID2L dl = txn->mt_u.dirty_list;
1369 unsigned i, n = dl[0].mid;
1371 for (i = 1; i <= n; i++) {
1372 mdb_dpage_free(env, dl[i].mptr);
1377 /** Set or clear P_KEEP in dirty, non-overflow, non-sub pages watched by txn.
1378 * @param[in] mc A cursor handle for the current operation.
1379 * @param[in] pflags Flags of the pages to update:
1380 * P_DIRTY to set P_KEEP, P_DIRTY|P_KEEP to clear it.
1381 * @param[in] all No shortcuts. Needed except after a full #mdb_page_flush().
1382 * @return 0 on success, non-zero on failure.
1385 mdb_pages_xkeep(MDB_cursor *mc, unsigned pflags, int all)
1387 enum { Mask = P_SUBP|P_DIRTY|P_KEEP };
1388 MDB_txn *txn = mc->mc_txn;
1394 int rc = MDB_SUCCESS, level;
1396 /* Mark pages seen by cursors */
1397 if (mc->mc_flags & C_UNTRACK)
1398 mc = NULL; /* will find mc in mt_cursors */
1399 for (i = txn->mt_numdbs;; mc = txn->mt_cursors[--i]) {
1400 for (; mc; mc=mc->mc_next) {
1401 if (!(mc->mc_flags & C_INITIALIZED))
1403 for (m3 = mc;; m3 = &mx->mx_cursor) {
1405 for (j=0; j<m3->mc_snum; j++) {
1407 if ((mp->mp_flags & Mask) == pflags)
1408 mp->mp_flags ^= P_KEEP;
1410 mx = m3->mc_xcursor;
1411 /* Proceed to mx if it is at a sub-database */
1412 if (! (mx && (mx->mx_cursor.mc_flags & C_INITIALIZED)))
1414 if (! (mp && (mp->mp_flags & P_LEAF)))
1416 leaf = NODEPTR(mp, m3->mc_ki[j-1]);
1417 if (!(leaf->mn_flags & F_SUBDATA))
1426 /* Mark dirty root pages */
1427 for (i=0; i<txn->mt_numdbs; i++) {
1428 if (txn->mt_dbflags[i] & DB_DIRTY) {
1429 pgno_t pgno = txn->mt_dbs[i].md_root;
1430 if (pgno == P_INVALID)
1432 if ((rc = mdb_page_get(txn, pgno, &dp, &level)) != MDB_SUCCESS)
1434 if ((dp->mp_flags & Mask) == pflags && level <= 1)
1435 dp->mp_flags ^= P_KEEP;
1443 static int mdb_page_flush(MDB_txn *txn, int keep);
1445 /** Spill pages from the dirty list back to disk.
1446 * This is intended to prevent running into #MDB_TXN_FULL situations,
1447 * but note that they may still occur in a few cases:
1448 * 1) our estimate of the txn size could be too small. Currently this
1449 * seems unlikely, except with a large number of #MDB_MULTIPLE items.
1450 * 2) child txns may run out of space if their parents dirtied a
1451 * lot of pages and never spilled them. TODO: we probably should do
1452 * a preemptive spill during #mdb_txn_begin() of a child txn, if
1453 * the parent's dirty_room is below a given threshold.
1455 * Otherwise, if not using nested txns, it is expected that apps will
1456 * not run into #MDB_TXN_FULL any more. The pages are flushed to disk
1457 * the same way as for a txn commit, e.g. their P_DIRTY flag is cleared.
1458 * If the txn never references them again, they can be left alone.
1459 * If the txn only reads them, they can be used without any fuss.
1460 * If the txn writes them again, they can be dirtied immediately without
1461 * going thru all of the work of #mdb_page_touch(). Such references are
1462 * handled by #mdb_page_unspill().
1464 * Also note, we never spill DB root pages, nor pages of active cursors,
1465 * because we'll need these back again soon anyway. And in nested txns,
1466 * we can't spill a page in a child txn if it was already spilled in a
1467 * parent txn. That would alter the parent txns' data even though
1468 * the child hasn't committed yet, and we'd have no way to undo it if
1469 * the child aborted.
1471 * @param[in] m0 cursor A cursor handle identifying the transaction and
1472 * database for which we are checking space.
1473 * @param[in] key For a put operation, the key being stored.
1474 * @param[in] data For a put operation, the data being stored.
1475 * @return 0 on success, non-zero on failure.
1478 mdb_page_spill(MDB_cursor *m0, MDB_val *key, MDB_val *data)
1480 MDB_txn *txn = m0->mc_txn;
1482 MDB_ID2L dl = txn->mt_u.dirty_list;
1483 unsigned int i, j, need;
1486 if (m0->mc_flags & C_SUB)
1489 /* Estimate how much space this op will take */
1490 i = m0->mc_db->md_depth;
1491 /* Named DBs also dirty the main DB */
1492 if (m0->mc_dbi > MAIN_DBI)
1493 i += txn->mt_dbs[MAIN_DBI].md_depth;
1494 /* For puts, roughly factor in the key+data size */
1496 i += (LEAFSIZE(key, data) + txn->mt_env->me_psize) / txn->mt_env->me_psize;
1497 i += i; /* double it for good measure */
1500 if (txn->mt_dirty_room > i)
1503 if (!txn->mt_spill_pgs) {
1504 txn->mt_spill_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX);
1505 if (!txn->mt_spill_pgs)
1508 /* purge deleted slots */
1509 MDB_IDL sl = txn->mt_spill_pgs;
1510 unsigned int num = sl[0];
1512 for (i=1; i<=num; i++) {
1519 /* Preserve pages which may soon be dirtied again */
1520 if ((rc = mdb_pages_xkeep(m0, P_DIRTY, 1)) != MDB_SUCCESS)
1523 /* Less aggressive spill - we originally spilled the entire dirty list,
1524 * with a few exceptions for cursor pages and DB root pages. But this
1525 * turns out to be a lot of wasted effort because in a large txn many
1526 * of those pages will need to be used again. So now we spill only 1/8th
1527 * of the dirty pages. Testing revealed this to be a good tradeoff,
1528 * better than 1/2, 1/4, or 1/10.
1530 if (need < MDB_IDL_UM_MAX / 8)
1531 need = MDB_IDL_UM_MAX / 8;
1533 /* Save the page IDs of all the pages we're flushing */
1534 /* flush from the tail forward, this saves a lot of shifting later on. */
1535 for (i=dl[0].mid; i && need; i--) {
1536 MDB_ID pn = dl[i].mid << 1;
1538 if (dp->mp_flags & P_KEEP)
1540 /* Can't spill twice, make sure it's not already in a parent's
1543 if (txn->mt_parent) {
1545 for (tx2 = txn->mt_parent; tx2; tx2 = tx2->mt_parent) {
1546 if (tx2->mt_spill_pgs) {
1547 j = mdb_midl_search(tx2->mt_spill_pgs, pn);
1548 if (j <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[j] == pn) {
1549 dp->mp_flags |= P_KEEP;
1557 if ((rc = mdb_midl_append(&txn->mt_spill_pgs, pn)))
1561 mdb_midl_sort(txn->mt_spill_pgs);
1563 /* Flush the spilled part of dirty list */
1564 if ((rc = mdb_page_flush(txn, i)) != MDB_SUCCESS)
1567 /* Reset any dirty pages we kept that page_flush didn't see */
1568 rc = mdb_pages_xkeep(m0, P_DIRTY|P_KEEP, i);
1571 txn->mt_flags |= rc ? MDB_TXN_ERROR : MDB_TXN_SPILLS;
1575 /** Find oldest txnid still referenced. Expects txn->mt_txnid > 0. */
1577 mdb_find_oldest(MDB_txn *txn)
1580 txnid_t mr, oldest = txn->mt_txnid - 1;
1581 if (txn->mt_env->me_txns) {
1582 MDB_reader *r = txn->mt_env->me_txns->mti_readers;
1583 for (i = txn->mt_env->me_txns->mti_numreaders; --i >= 0; ) {
1594 /** Add a page to the txn's dirty list */
1596 mdb_page_dirty(MDB_txn *txn, MDB_page *mp)
1599 int (*insert)(MDB_ID2L, MDB_ID2 *);
1601 if (txn->mt_env->me_flags & MDB_WRITEMAP) {
1602 insert = mdb_mid2l_append;
1604 insert = mdb_mid2l_insert;
1606 mid.mid = mp->mp_pgno;
1608 insert(txn->mt_u.dirty_list, &mid);
1609 txn->mt_dirty_room--;
1612 /** Allocate page numbers and memory for writing. Maintain me_pglast,
1613 * me_pghead and mt_next_pgno.
1615 * If there are free pages available from older transactions, they
1616 * are re-used first. Otherwise allocate a new page at mt_next_pgno.
1617 * Do not modify the freedB, just merge freeDB records into me_pghead[]
1618 * and move me_pglast to say which records were consumed. Only this
1619 * function can create me_pghead and move me_pglast/mt_next_pgno.
1620 * @param[in] mc cursor A cursor handle identifying the transaction and
1621 * database for which we are allocating.
1622 * @param[in] num the number of pages to allocate.
1623 * @param[out] mp Address of the allocated page(s). Requests for multiple pages
1624 * will always be satisfied by a single contiguous chunk of memory.
1625 * @return 0 on success, non-zero on failure.
1628 mdb_page_alloc(MDB_cursor *mc, int num, MDB_page **mp)
1630 #ifdef MDB_PARANOID /* Seems like we can ignore this now */
1631 /* Get at most <Max_retries> more freeDB records once me_pghead
1632 * has enough pages. If not enough, use new pages from the map.
1633 * If <Paranoid> and mc is updating the freeDB, only get new
1634 * records if me_pghead is empty. Then the freelist cannot play
1635 * catch-up with itself by growing while trying to save it.
1637 enum { Paranoid = 1, Max_retries = 500 };
1639 enum { Paranoid = 0, Max_retries = INT_MAX /*infinite*/ };
1641 int rc, n2 = num-1, retry = Max_retries;
1642 MDB_txn *txn = mc->mc_txn;
1643 MDB_env *env = txn->mt_env;
1644 pgno_t pgno, *mop = env->me_pghead;
1645 unsigned i, j, k, mop_len = mop ? mop[0] : 0;
1647 txnid_t oldest = 0, last;
1653 /* If our dirty list is already full, we can't do anything */
1654 if (txn->mt_dirty_room == 0)
1655 return MDB_TXN_FULL;
1657 for (op = MDB_FIRST;; op = MDB_NEXT) {
1660 pgno_t *idl, old_id, new_id;
1662 /* Seek a big enough contiguous page range. Prefer
1663 * pages at the tail, just truncating the list.
1665 if (mop_len >= (unsigned)num) {
1669 if (mop[i-n2] == pgno+n2)
1671 } while (--i >= (unsigned)num);
1672 if (Max_retries < INT_MAX && --retry < 0)
1676 if (op == MDB_FIRST) { /* 1st iteration */
1677 /* Prepare to fetch more and coalesce */
1678 oldest = mdb_find_oldest(txn);
1679 last = env->me_pglast;
1680 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1683 key.mv_data = &last; /* will look up last+1 */
1684 key.mv_size = sizeof(last);
1686 if (Paranoid && mc->mc_dbi == FREE_DBI)
1689 if (Paranoid && retry < 0 && mop_len)
1693 /* Do not fetch more if the record will be too recent */
1696 rc = mdb_cursor_get(&m2, &key, NULL, op);
1698 if (rc == MDB_NOTFOUND)
1702 last = *(txnid_t*)key.mv_data;
1705 np = m2.mc_pg[m2.mc_top];
1706 leaf = NODEPTR(np, m2.mc_ki[m2.mc_top]);
1707 if ((rc = mdb_node_read(txn, leaf, &data)) != MDB_SUCCESS)
1710 idl = (MDB_ID *) data.mv_data;
1713 if (!(env->me_pghead = mop = mdb_midl_alloc(i)))
1716 if ((rc = mdb_midl_need(&env->me_pghead, i)) != 0)
1718 mop = env->me_pghead;
1720 env->me_pglast = last;
1722 DPRINTF(("IDL read txn %"Z"u root %"Z"u num %u",
1723 last, txn->mt_dbs[FREE_DBI].md_root, i));
1725 DPRINTF(("IDL %"Z"u", idl[k]));
1727 /* Merge in descending sorted order */
1730 mop[0] = (pgno_t)-1;
1734 for (; old_id < new_id; old_id = mop[--j])
1741 /* Use new pages from the map when nothing suitable in the freeDB */
1743 pgno = txn->mt_next_pgno;
1744 if (pgno + num >= env->me_maxpg) {
1745 DPUTS("DB size maxed out");
1746 return MDB_MAP_FULL;
1750 if (env->me_flags & MDB_WRITEMAP) {
1751 np = (MDB_page *)(env->me_map + env->me_psize * pgno);
1753 if (!(np = mdb_page_malloc(txn, num)))
1757 mop[0] = mop_len -= num;
1758 /* Move any stragglers down */
1759 for (j = i-num; j < mop_len; )
1760 mop[++j] = mop[++i];
1762 txn->mt_next_pgno = pgno + num;
1765 mdb_page_dirty(txn, np);
1771 /** Copy the used portions of a non-overflow page.
1772 * @param[in] dst page to copy into
1773 * @param[in] src page to copy from
1774 * @param[in] psize size of a page
1777 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
1779 enum { Align = sizeof(pgno_t) };
1780 indx_t upper = src->mp_upper, lower = src->mp_lower, unused = upper-lower;
1782 /* If page isn't full, just copy the used portion. Adjust
1783 * alignment so memcpy may copy words instead of bytes.
1785 if ((unused &= -Align) && !IS_LEAF2(src)) {
1787 memcpy(dst, src, (lower + (Align-1)) & -Align);
1788 memcpy((pgno_t *)((char *)dst+upper), (pgno_t *)((char *)src+upper),
1791 memcpy(dst, src, psize - unused);
1795 /** Pull a page off the txn's spill list, if present.
1796 * If a page being referenced was spilled to disk in this txn, bring
1797 * it back and make it dirty/writable again.
1798 * @param[in] txn the transaction handle.
1799 * @param[in] mp the page being referenced.
1800 * @param[out] ret the writable page, if any. ret is unchanged if
1801 * mp wasn't spilled.
1804 mdb_page_unspill(MDB_txn *txn, MDB_page *mp, MDB_page **ret)
1806 MDB_env *env = txn->mt_env;
1809 pgno_t pgno = mp->mp_pgno, pn = pgno << 1;
1811 for (tx2 = txn; tx2; tx2=tx2->mt_parent) {
1812 if (!tx2->mt_spill_pgs)
1814 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
1815 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
1818 if (txn->mt_dirty_room == 0)
1819 return MDB_TXN_FULL;
1820 if (IS_OVERFLOW(mp))
1824 if (env->me_flags & MDB_WRITEMAP) {
1827 np = mdb_page_malloc(txn, num);
1831 memcpy(np, mp, num * env->me_psize);
1833 mdb_page_copy(np, mp, env->me_psize);
1836 /* If in current txn, this page is no longer spilled.
1837 * If it happens to be the last page, truncate the spill list.
1838 * Otherwise mark it as deleted by setting the LSB.
1840 if (x == txn->mt_spill_pgs[0])
1841 txn->mt_spill_pgs[0]--;
1843 txn->mt_spill_pgs[x] |= 1;
1844 } /* otherwise, if belonging to a parent txn, the
1845 * page remains spilled until child commits
1848 mdb_page_dirty(txn, np);
1849 np->mp_flags |= P_DIRTY;
1857 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1858 * @param[in] mc cursor pointing to the page to be touched
1859 * @return 0 on success, non-zero on failure.
1862 mdb_page_touch(MDB_cursor *mc)
1864 MDB_page *mp = mc->mc_pg[mc->mc_top], *np;
1865 MDB_txn *txn = mc->mc_txn;
1866 MDB_cursor *m2, *m3;
1870 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1871 if (txn->mt_flags & MDB_TXN_SPILLS) {
1873 rc = mdb_page_unspill(txn, mp, &np);
1879 if ((rc = mdb_midl_need(&txn->mt_free_pgs, 1)) ||
1880 (rc = mdb_page_alloc(mc, 1, &np)))
1883 DPRINTF(("touched db %d page %"Z"u -> %"Z"u", DDBI(mc),
1884 mp->mp_pgno, pgno));
1885 assert(mp->mp_pgno != pgno);
1886 mdb_midl_xappend(txn->mt_free_pgs, mp->mp_pgno);
1887 /* Update the parent page, if any, to point to the new page */
1889 MDB_page *parent = mc->mc_pg[mc->mc_top-1];
1890 MDB_node *node = NODEPTR(parent, mc->mc_ki[mc->mc_top-1]);
1891 SETPGNO(node, pgno);
1893 mc->mc_db->md_root = pgno;
1895 } else if (txn->mt_parent && !IS_SUBP(mp)) {
1896 MDB_ID2 mid, *dl = txn->mt_u.dirty_list;
1898 /* If txn has a parent, make sure the page is in our
1902 unsigned x = mdb_mid2l_search(dl, pgno);
1903 if (x <= dl[0].mid && dl[x].mid == pgno) {
1904 if (mp != dl[x].mptr) { /* bad cursor? */
1905 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
1906 return MDB_CORRUPTED;
1911 assert(dl[0].mid < MDB_IDL_UM_MAX);
1913 np = mdb_page_malloc(txn, 1);
1918 mdb_mid2l_insert(dl, &mid);
1923 mdb_page_copy(np, mp, txn->mt_env->me_psize);
1925 np->mp_flags |= P_DIRTY;
1928 /* Adjust cursors pointing to mp */
1929 mc->mc_pg[mc->mc_top] = np;
1930 m2 = txn->mt_cursors[mc->mc_dbi];
1931 if (mc->mc_flags & C_SUB) {
1932 for (; m2; m2=m2->mc_next) {
1933 m3 = &m2->mc_xcursor->mx_cursor;
1934 if (m3->mc_snum < mc->mc_snum) continue;
1935 if (m3->mc_pg[mc->mc_top] == mp)
1936 m3->mc_pg[mc->mc_top] = np;
1939 for (; m2; m2=m2->mc_next) {
1940 if (m2->mc_snum < mc->mc_snum) continue;
1941 if (m2->mc_pg[mc->mc_top] == mp) {
1942 m2->mc_pg[mc->mc_top] = np;
1943 if ((mc->mc_db->md_flags & MDB_DUPSORT) &&
1944 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
1946 MDB_node *leaf = NODEPTR(np, mc->mc_ki[mc->mc_top]);
1947 if (!(leaf->mn_flags & F_SUBDATA))
1948 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
1957 mdb_env_sync(MDB_env *env, int force)
1960 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1961 if (env->me_flags & MDB_WRITEMAP) {
1962 int flags = ((env->me_flags & MDB_MAPASYNC) && !force)
1963 ? MS_ASYNC : MS_SYNC;
1964 if (MDB_MSYNC(env->me_map, env->me_mapsize, flags))
1967 else if (flags == MS_SYNC && MDB_FDATASYNC(env->me_fd))
1971 if (MDB_FDATASYNC(env->me_fd))
1978 /** Back up parent txn's cursors, then grab the originals for tracking */
1980 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
1982 MDB_cursor *mc, *bk;
1987 for (i = src->mt_numdbs; --i >= 0; ) {
1988 if ((mc = src->mt_cursors[i]) != NULL) {
1989 size = sizeof(MDB_cursor);
1991 size += sizeof(MDB_xcursor);
1992 for (; mc; mc = bk->mc_next) {
1998 mc->mc_db = &dst->mt_dbs[i];
1999 /* Kill pointers into src - and dst to reduce abuse: The
2000 * user may not use mc until dst ends. Otherwise we'd...
2002 mc->mc_txn = NULL; /* ...set this to dst */
2003 mc->mc_dbflag = NULL; /* ...and &dst->mt_dbflags[i] */
2004 if ((mx = mc->mc_xcursor) != NULL) {
2005 *(MDB_xcursor *)(bk+1) = *mx;
2006 mx->mx_cursor.mc_txn = NULL; /* ...and dst. */
2008 mc->mc_next = dst->mt_cursors[i];
2009 dst->mt_cursors[i] = mc;
2016 /** Close this write txn's cursors, give parent txn's cursors back to parent.
2017 * @param[in] txn the transaction handle.
2018 * @param[in] merge true to keep changes to parent cursors, false to revert.
2019 * @return 0 on success, non-zero on failure.
2022 mdb_cursors_close(MDB_txn *txn, unsigned merge)
2024 MDB_cursor **cursors = txn->mt_cursors, *mc, *next, *bk;
2028 for (i = txn->mt_numdbs; --i >= 0; ) {
2029 for (mc = cursors[i]; mc; mc = next) {
2031 if ((bk = mc->mc_backup) != NULL) {
2033 /* Commit changes to parent txn */
2034 mc->mc_next = bk->mc_next;
2035 mc->mc_backup = bk->mc_backup;
2036 mc->mc_txn = bk->mc_txn;
2037 mc->mc_db = bk->mc_db;
2038 mc->mc_dbflag = bk->mc_dbflag;
2039 if ((mx = mc->mc_xcursor) != NULL)
2040 mx->mx_cursor.mc_txn = bk->mc_txn;
2042 /* Abort nested txn */
2044 if ((mx = mc->mc_xcursor) != NULL)
2045 *mx = *(MDB_xcursor *)(bk+1);
2049 /* Only malloced cursors are permanently tracked. */
2057 #define mdb_txn_reset0(txn, act) mdb_txn_reset0(txn)
2060 mdb_txn_reset0(MDB_txn *txn, const char *act);
2062 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2068 Pidset = F_SETLK, Pidcheck = F_GETLK
2072 /** Set or check a pid lock. Set returns 0 on success.
2073 * Check returns 0 if the process is certainly dead, nonzero if it may
2074 * be alive (the lock exists or an error happened so we do not know).
2076 * On Windows Pidset is a no-op, we merely check for the existence
2077 * of the process with the given pid. On POSIX we use a single byte
2078 * lock on the lockfile, set at an offset equal to the pid.
2081 mdb_reader_pid(MDB_env *env, enum Pidlock_op op, pid_t pid)
2083 #if !(MDB_PIDLOCK) /* Currently the same as defined(_WIN32) */
2086 if (op == Pidcheck) {
2087 h = OpenProcess(env->me_pidquery, FALSE, pid);
2088 /* No documented "no such process" code, but other program use this: */
2090 return ErrCode() != ERROR_INVALID_PARAMETER;
2091 /* A process exists until all handles to it close. Has it exited? */
2092 ret = WaitForSingleObject(h, 0) != 0;
2099 struct flock lock_info;
2100 memset(&lock_info, 0, sizeof(lock_info));
2101 lock_info.l_type = F_WRLCK;
2102 lock_info.l_whence = SEEK_SET;
2103 lock_info.l_start = pid;
2104 lock_info.l_len = 1;
2105 if ((rc = fcntl(env->me_lfd, op, &lock_info)) == 0) {
2106 if (op == F_GETLK && lock_info.l_type != F_UNLCK)
2108 } else if ((rc = ErrCode()) == EINTR) {
2116 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
2117 * @param[in] txn the transaction handle to initialize
2118 * @return 0 on success, non-zero on failure.
2121 mdb_txn_renew0(MDB_txn *txn)
2123 MDB_env *env = txn->mt_env;
2124 MDB_txninfo *ti = env->me_txns;
2128 int rc, new_notls = 0;
2131 txn->mt_numdbs = env->me_numdbs;
2132 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
2134 if (txn->mt_flags & MDB_TXN_RDONLY) {
2136 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2137 txn->mt_txnid = meta->mm_txnid;
2138 txn->mt_u.reader = NULL;
2140 MDB_reader *r = (env->me_flags & MDB_NOTLS) ? txn->mt_u.reader :
2141 pthread_getspecific(env->me_txkey);
2143 if (r->mr_pid != env->me_pid || r->mr_txnid != (txnid_t)-1)
2144 return MDB_BAD_RSLOT;
2146 pid_t pid = env->me_pid;
2147 pthread_t tid = pthread_self();
2149 if (!(env->me_flags & MDB_LIVE_READER)) {
2150 rc = mdb_reader_pid(env, Pidset, pid);
2152 UNLOCK_MUTEX_R(env);
2155 env->me_flags |= MDB_LIVE_READER;
2159 nr = ti->mti_numreaders;
2160 for (i=0; i<nr; i++)
2161 if (ti->mti_readers[i].mr_pid == 0)
2163 if (i == env->me_maxreaders) {
2164 UNLOCK_MUTEX_R(env);
2165 return MDB_READERS_FULL;
2167 ti->mti_readers[i].mr_pid = pid;
2168 ti->mti_readers[i].mr_tid = tid;
2170 ti->mti_numreaders = ++nr;
2171 /* Save numreaders for un-mutexed mdb_env_close() */
2172 env->me_numreaders = nr;
2173 UNLOCK_MUTEX_R(env);
2175 r = &ti->mti_readers[i];
2176 new_notls = (env->me_flags & MDB_NOTLS);
2177 if (!new_notls && (rc=pthread_setspecific(env->me_txkey, r))) {
2182 txn->mt_txnid = r->mr_txnid = ti->mti_txnid;
2183 txn->mt_u.reader = r;
2184 meta = env->me_metas[txn->mt_txnid & 1];
2190 txn->mt_txnid = ti->mti_txnid;
2191 meta = env->me_metas[txn->mt_txnid & 1];
2193 meta = env->me_metas[ mdb_env_pick_meta(env) ];
2194 txn->mt_txnid = meta->mm_txnid;
2198 if (txn->mt_txnid == mdb_debug_start)
2201 txn->mt_dirty_room = MDB_IDL_UM_MAX;
2202 txn->mt_u.dirty_list = env->me_dirty_list;
2203 txn->mt_u.dirty_list[0].mid = 0;
2204 txn->mt_free_pgs = env->me_free_pgs;
2205 txn->mt_free_pgs[0] = 0;
2206 txn->mt_spill_pgs = NULL;
2210 /* Copy the DB info and flags */
2211 memcpy(txn->mt_dbs, meta->mm_dbs, 2 * sizeof(MDB_db));
2213 /* Moved to here to avoid a data race in read TXNs */
2214 txn->mt_next_pgno = meta->mm_last_pg+1;
2216 for (i=2; i<txn->mt_numdbs; i++) {
2217 x = env->me_dbflags[i];
2218 txn->mt_dbs[i].md_flags = x & PERSISTENT_FLAGS;
2219 txn->mt_dbflags[i] = (x & MDB_VALID) ? DB_VALID|DB_STALE : 0;
2221 txn->mt_dbflags[0] = txn->mt_dbflags[1] = DB_VALID;
2223 if (env->me_maxpg < txn->mt_next_pgno) {
2224 mdb_txn_reset0(txn, "renew0-mapfail");
2226 txn->mt_u.reader->mr_pid = 0;
2227 txn->mt_u.reader = NULL;
2229 return MDB_MAP_RESIZED;
2236 mdb_txn_renew(MDB_txn *txn)
2240 if (!txn || txn->mt_dbxs) /* A reset txn has mt_dbxs==NULL */
2243 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
2244 DPUTS("environment had fatal error, must shutdown!");
2248 rc = mdb_txn_renew0(txn);
2249 if (rc == MDB_SUCCESS) {
2250 DPRINTF(("renew txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2251 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2252 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root));
2258 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
2262 int rc, size, tsize = sizeof(MDB_txn);
2264 if (env->me_flags & MDB_FATAL_ERROR) {
2265 DPUTS("environment had fatal error, must shutdown!");
2268 if ((env->me_flags & MDB_RDONLY) && !(flags & MDB_RDONLY))
2271 /* Nested transactions: Max 1 child, write txns only, no writemap */
2272 if (parent->mt_child ||
2273 (flags & MDB_RDONLY) ||
2274 (parent->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR)) ||
2275 (env->me_flags & MDB_WRITEMAP))
2277 return (parent->mt_flags & MDB_TXN_RDONLY) ? EINVAL : MDB_BAD_TXN;
2279 tsize = sizeof(MDB_ntxn);
2281 size = tsize + env->me_maxdbs * (sizeof(MDB_db)+1);
2282 if (!(flags & MDB_RDONLY))
2283 size += env->me_maxdbs * sizeof(MDB_cursor *);
2285 if ((txn = calloc(1, size)) == NULL) {
2286 DPRINTF(("calloc: %s", strerror(ErrCode())));
2289 txn->mt_dbs = (MDB_db *) ((char *)txn + tsize);
2290 if (flags & MDB_RDONLY) {
2291 txn->mt_flags |= MDB_TXN_RDONLY;
2292 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
2294 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
2295 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
2301 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
2302 if (!txn->mt_u.dirty_list ||
2303 !(txn->mt_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)))
2305 free(txn->mt_u.dirty_list);
2309 txn->mt_txnid = parent->mt_txnid;
2310 txn->mt_dirty_room = parent->mt_dirty_room;
2311 txn->mt_u.dirty_list[0].mid = 0;
2312 txn->mt_spill_pgs = NULL;
2313 txn->mt_next_pgno = parent->mt_next_pgno;
2314 parent->mt_child = txn;
2315 txn->mt_parent = parent;
2316 txn->mt_numdbs = parent->mt_numdbs;
2317 txn->mt_flags = parent->mt_flags;
2318 txn->mt_dbxs = parent->mt_dbxs;
2319 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2320 /* Copy parent's mt_dbflags, but clear DB_NEW */
2321 for (i=0; i<txn->mt_numdbs; i++)
2322 txn->mt_dbflags[i] = parent->mt_dbflags[i] & ~DB_NEW;
2324 ntxn = (MDB_ntxn *)txn;
2325 ntxn->mnt_pgstate = env->me_pgstate; /* save parent me_pghead & co */
2326 if (env->me_pghead) {
2327 size = MDB_IDL_SIZEOF(env->me_pghead);
2328 env->me_pghead = mdb_midl_alloc(env->me_pghead[0]);
2330 memcpy(env->me_pghead, ntxn->mnt_pgstate.mf_pghead, size);
2335 rc = mdb_cursor_shadow(parent, txn);
2337 mdb_txn_reset0(txn, "beginchild-fail");
2339 rc = mdb_txn_renew0(txn);
2345 DPRINTF(("begin txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2346 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2347 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root));
2354 mdb_txn_env(MDB_txn *txn)
2356 if(!txn) return NULL;
2360 /** Export or close DBI handles opened in this txn. */
2362 mdb_dbis_update(MDB_txn *txn, int keep)
2365 MDB_dbi n = txn->mt_numdbs;
2366 MDB_env *env = txn->mt_env;
2367 unsigned char *tdbflags = txn->mt_dbflags;
2369 for (i = n; --i >= 2;) {
2370 if (tdbflags[i] & DB_NEW) {
2372 env->me_dbflags[i] = txn->mt_dbs[i].md_flags | MDB_VALID;
2374 char *ptr = env->me_dbxs[i].md_name.mv_data;
2375 env->me_dbxs[i].md_name.mv_data = NULL;
2376 env->me_dbxs[i].md_name.mv_size = 0;
2377 env->me_dbflags[i] = 0;
2382 if (keep && env->me_numdbs < n)
2386 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
2387 * May be called twice for readonly txns: First reset it, then abort.
2388 * @param[in] txn the transaction handle to reset
2389 * @param[in] act why the transaction is being reset
2392 mdb_txn_reset0(MDB_txn *txn, const char *act)
2394 MDB_env *env = txn->mt_env;
2396 /* Close any DBI handles opened in this txn */
2397 mdb_dbis_update(txn, 0);
2399 DPRINTF(("%s txn %"Z"u%c %p on mdbenv %p, root page %"Z"u",
2400 act, txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
2401 (void *) txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root));
2403 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2404 if (txn->mt_u.reader) {
2405 txn->mt_u.reader->mr_txnid = (txnid_t)-1;
2406 if (!(env->me_flags & MDB_NOTLS))
2407 txn->mt_u.reader = NULL; /* txn does not own reader */
2409 txn->mt_numdbs = 0; /* close nothing if called again */
2410 txn->mt_dbxs = NULL; /* mark txn as reset */
2412 mdb_cursors_close(txn, 0);
2414 if (!(env->me_flags & MDB_WRITEMAP)) {
2415 mdb_dlist_free(txn);
2417 mdb_midl_free(env->me_pghead);
2419 if (txn->mt_parent) {
2420 txn->mt_parent->mt_child = NULL;
2421 env->me_pgstate = ((MDB_ntxn *)txn)->mnt_pgstate;
2422 mdb_midl_free(txn->mt_free_pgs);
2423 mdb_midl_free(txn->mt_spill_pgs);
2424 free(txn->mt_u.dirty_list);
2428 if (mdb_midl_shrink(&txn->mt_free_pgs))
2429 env->me_free_pgs = txn->mt_free_pgs;
2430 env->me_pghead = NULL;
2434 /* The writer mutex was locked in mdb_txn_begin. */
2436 UNLOCK_MUTEX_W(env);
2441 mdb_txn_reset(MDB_txn *txn)
2446 /* This call is only valid for read-only txns */
2447 if (!(txn->mt_flags & MDB_TXN_RDONLY))
2450 mdb_txn_reset0(txn, "reset");
2454 mdb_txn_abort(MDB_txn *txn)
2460 mdb_txn_abort(txn->mt_child);
2462 mdb_txn_reset0(txn, "abort");
2463 /* Free reader slot tied to this txn (if MDB_NOTLS && writable FS) */
2464 if ((txn->mt_flags & MDB_TXN_RDONLY) && txn->mt_u.reader)
2465 txn->mt_u.reader->mr_pid = 0;
2470 /** Save the freelist as of this transaction to the freeDB.
2471 * This changes the freelist. Keep trying until it stabilizes.
2474 mdb_freelist_save(MDB_txn *txn)
2476 /* env->me_pghead[] can grow and shrink during this call.
2477 * env->me_pglast and txn->mt_free_pgs[] can only grow.
2478 * Page numbers cannot disappear from txn->mt_free_pgs[].
2481 MDB_env *env = txn->mt_env;
2482 int rc, maxfree_1pg = env->me_maxfree_1pg, more = 1;
2483 txnid_t pglast = 0, head_id = 0;
2484 pgno_t freecnt = 0, *free_pgs, *mop;
2485 ssize_t head_room = 0, total_room = 0, mop_len;
2487 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
2489 if (env->me_pghead) {
2490 /* Make sure first page of freeDB is touched and on freelist */
2491 rc = mdb_page_search(&mc, NULL, MDB_PS_FIRST|MDB_PS_MODIFY);
2492 if (rc && rc != MDB_NOTFOUND)
2497 /* Come back here after each Put() in case freelist changed */
2500 /* If using records from freeDB which we have not yet
2501 * deleted, delete them and any we reserved for me_pghead.
2503 while (pglast < env->me_pglast) {
2504 rc = mdb_cursor_first(&mc, &key, NULL);
2507 pglast = head_id = *(txnid_t *)key.mv_data;
2508 total_room = head_room = 0;
2509 assert(pglast <= env->me_pglast);
2510 rc = mdb_cursor_del(&mc, 0);
2515 /* Save the IDL of pages freed by this txn, to a single record */
2516 if (freecnt < txn->mt_free_pgs[0]) {
2518 /* Make sure last page of freeDB is touched and on freelist */
2519 rc = mdb_page_search(&mc, NULL, MDB_PS_LAST|MDB_PS_MODIFY);
2520 if (rc && rc != MDB_NOTFOUND)
2523 free_pgs = txn->mt_free_pgs;
2524 /* Write to last page of freeDB */
2525 key.mv_size = sizeof(txn->mt_txnid);
2526 key.mv_data = &txn->mt_txnid;
2528 freecnt = free_pgs[0];
2529 data.mv_size = MDB_IDL_SIZEOF(free_pgs);
2530 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2533 /* Retry if mt_free_pgs[] grew during the Put() */
2534 free_pgs = txn->mt_free_pgs;
2535 } while (freecnt < free_pgs[0]);
2536 mdb_midl_sort(free_pgs);
2537 memcpy(data.mv_data, free_pgs, data.mv_size);
2540 unsigned int i = free_pgs[0];
2541 DPRINTF(("IDL write txn %"Z"u root %"Z"u num %u",
2542 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, i));
2544 DPRINTF(("IDL %"Z"u", free_pgs[i]));
2550 mop = env->me_pghead;
2551 mop_len = mop ? mop[0] : 0;
2553 /* Reserve records for me_pghead[]. Split it if multi-page,
2554 * to avoid searching freeDB for a page range. Use keys in
2555 * range [1,me_pglast]: Smaller than txnid of oldest reader.
2557 if (total_room >= mop_len) {
2558 if (total_room == mop_len || --more < 0)
2560 } else if (head_room >= maxfree_1pg && head_id > 1) {
2561 /* Keep current record (overflow page), add a new one */
2565 /* (Re)write {key = head_id, IDL length = head_room} */
2566 total_room -= head_room;
2567 head_room = mop_len - total_room;
2568 if (head_room > maxfree_1pg && head_id > 1) {
2569 /* Overflow multi-page for part of me_pghead */
2570 head_room /= head_id; /* amortize page sizes */
2571 head_room += maxfree_1pg - head_room % (maxfree_1pg + 1);
2572 } else if (head_room < 0) {
2573 /* Rare case, not bothering to delete this record */
2576 key.mv_size = sizeof(head_id);
2577 key.mv_data = &head_id;
2578 data.mv_size = (head_room + 1) * sizeof(pgno_t);
2579 rc = mdb_cursor_put(&mc, &key, &data, MDB_RESERVE);
2582 *(MDB_ID *)data.mv_data = 0; /* IDL is initially empty */
2583 total_room += head_room;
2586 /* Fill in the reserved me_pghead records */
2592 rc = mdb_cursor_first(&mc, &key, &data);
2593 for (; !rc; rc = mdb_cursor_next(&mc, &key, &data, MDB_NEXT)) {
2594 unsigned flags = MDB_CURRENT;
2595 txnid_t id = *(txnid_t *)key.mv_data;
2596 ssize_t len = (ssize_t)(data.mv_size / sizeof(MDB_ID)) - 1;
2599 assert(len >= 0 && id <= env->me_pglast);
2601 if (len > mop_len) {
2603 data.mv_size = (len + 1) * sizeof(MDB_ID);
2606 data.mv_data = mop -= len;
2609 rc = mdb_cursor_put(&mc, &key, &data, flags);
2611 if (rc || !(mop_len -= len))
2618 /** Flush (some) dirty pages to the map, after clearing their dirty flag.
2619 * @param[in] txn the transaction that's being committed
2620 * @param[in] keep number of initial pages in dirty_list to keep dirty.
2621 * @return 0 on success, non-zero on failure.
2624 mdb_page_flush(MDB_txn *txn, int keep)
2626 MDB_env *env = txn->mt_env;
2627 MDB_ID2L dl = txn->mt_u.dirty_list;
2628 unsigned psize = env->me_psize, j;
2629 int i, pagecount = dl[0].mid, rc;
2630 size_t size = 0, pos = 0;
2632 MDB_page *dp = NULL;
2636 struct iovec iov[MDB_COMMIT_PAGES];
2637 ssize_t wpos = 0, wsize = 0, wres;
2638 size_t next_pos = 1; /* impossible pos, so pos != next_pos */
2644 if (env->me_flags & MDB_WRITEMAP) {
2645 /* Clear dirty flags */
2646 while (++i <= pagecount) {
2648 /* Don't flush this page yet */
2649 if (dp->mp_flags & P_KEEP) {
2650 dp->mp_flags ^= P_KEEP;
2654 dp->mp_flags &= ~P_DIRTY;
2659 /* Write the pages */
2661 if (++i <= pagecount) {
2663 /* Don't flush this page yet */
2664 if (dp->mp_flags & P_KEEP) {
2665 dp->mp_flags ^= P_KEEP;
2670 /* clear dirty flag */
2671 dp->mp_flags &= ~P_DIRTY;
2674 if (IS_OVERFLOW(dp)) size *= dp->mp_pages;
2679 /* Windows actually supports scatter/gather I/O, but only on
2680 * unbuffered file handles. Since we're relying on the OS page
2681 * cache for all our data, that's self-defeating. So we just
2682 * write pages one at a time. We use the ov structure to set
2683 * the write offset, to at least save the overhead of a Seek
2686 DPRINTF(("committing page %"Z"u", pgno));
2687 memset(&ov, 0, sizeof(ov));
2688 ov.Offset = pos & 0xffffffff;
2689 ov.OffsetHigh = pos >> 16 >> 16;
2690 if (!WriteFile(env->me_fd, dp, size, NULL, &ov)) {
2692 DPRINTF(("WriteFile: %d", rc));
2696 /* Write up to MDB_COMMIT_PAGES dirty pages at a time. */
2697 if (pos!=next_pos || n==MDB_COMMIT_PAGES || wsize+size>MAX_WRITE) {
2699 /* Write previous page(s) */
2700 #ifdef MDB_USE_PWRITEV
2701 wres = pwritev(env->me_fd, iov, n, wpos);
2704 wres = pwrite(env->me_fd, iov[0].iov_base, wsize, wpos);
2706 if (lseek(env->me_fd, wpos, SEEK_SET) == -1) {
2708 DPRINTF(("lseek: %s", strerror(rc)));
2711 wres = writev(env->me_fd, iov, n);
2714 if (wres != wsize) {
2717 DPRINTF(("Write error: %s", strerror(rc)));
2719 rc = EIO; /* TODO: Use which error code? */
2720 DPUTS("short write, filesystem full?");
2731 DPRINTF(("committing page %"Z"u", pgno));
2732 next_pos = pos + size;
2733 iov[n].iov_len = size;
2734 iov[n].iov_base = (char *)dp;
2740 for (i = keep; ++i <= pagecount; ) {
2742 /* This is a page we skipped above */
2745 dl[j].mid = dp->mp_pgno;
2748 mdb_dpage_free(env, dp);
2753 txn->mt_dirty_room += i - j;
2759 mdb_txn_commit(MDB_txn *txn)
2765 assert(txn != NULL);
2766 assert(txn->mt_env != NULL);
2768 if (txn->mt_child) {
2769 rc = mdb_txn_commit(txn->mt_child);
2770 txn->mt_child = NULL;
2777 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2778 mdb_dbis_update(txn, 1);
2779 txn->mt_numdbs = 2; /* so txn_abort() doesn't close any new handles */
2784 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
2785 DPUTS("error flag is set, can't commit");
2787 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
2792 if (txn->mt_parent) {
2793 MDB_txn *parent = txn->mt_parent;
2796 unsigned x, y, len, ps_len;
2798 /* Append our free list to parent's */
2799 rc = mdb_midl_append_list(&parent->mt_free_pgs, txn->mt_free_pgs);
2802 mdb_midl_free(txn->mt_free_pgs);
2803 /* Failures after this must either undo the changes
2804 * to the parent or set MDB_TXN_ERROR in the parent.
2807 parent->mt_next_pgno = txn->mt_next_pgno;
2808 parent->mt_flags = txn->mt_flags;
2810 /* Merge our cursors into parent's and close them */
2811 mdb_cursors_close(txn, 1);
2813 /* Update parent's DB table. */
2814 memcpy(parent->mt_dbs, txn->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
2815 parent->mt_numdbs = txn->mt_numdbs;
2816 parent->mt_dbflags[0] = txn->mt_dbflags[0];
2817 parent->mt_dbflags[1] = txn->mt_dbflags[1];
2818 for (i=2; i<txn->mt_numdbs; i++) {
2819 /* preserve parent's DB_NEW status */
2820 x = parent->mt_dbflags[i] & DB_NEW;
2821 parent->mt_dbflags[i] = txn->mt_dbflags[i] | x;
2824 dst = parent->mt_u.dirty_list;
2825 src = txn->mt_u.dirty_list;
2826 /* Remove anything in our dirty list from parent's spill list */
2827 if ((pspill = parent->mt_spill_pgs) && (ps_len = pspill[0])) {
2829 pspill[0] = (pgno_t)-1;
2830 /* Mark our dirty pages as deleted in parent spill list */
2831 for (i=0, len=src[0].mid; ++i <= len; ) {
2832 MDB_ID pn = src[i].mid << 1;
2833 while (pn > pspill[x])
2835 if (pn == pspill[x]) {
2840 /* Squash deleted pagenums if we deleted any */
2841 for (x=y; ++x <= ps_len; )
2842 if (!(pspill[x] & 1))
2843 pspill[++y] = pspill[x];
2847 /* Find len = length of merging our dirty list with parent's */
2849 dst[0].mid = 0; /* simplify loops */
2850 if (parent->mt_parent) {
2851 len = x + src[0].mid;
2852 y = mdb_mid2l_search(src, dst[x].mid + 1) - 1;
2853 for (i = x; y && i; y--) {
2854 pgno_t yp = src[y].mid;
2855 while (yp < dst[i].mid)
2857 if (yp == dst[i].mid) {
2862 } else { /* Simplify the above for single-ancestor case */
2863 len = MDB_IDL_UM_MAX - txn->mt_dirty_room;
2865 /* Merge our dirty list with parent's */
2867 for (i = len; y; dst[i--] = src[y--]) {
2868 pgno_t yp = src[y].mid;
2869 while (yp < dst[x].mid)
2870 dst[i--] = dst[x--];
2871 if (yp == dst[x].mid)
2872 free(dst[x--].mptr);
2876 free(txn->mt_u.dirty_list);
2877 parent->mt_dirty_room = txn->mt_dirty_room;
2878 if (txn->mt_spill_pgs) {
2879 if (parent->mt_spill_pgs) {
2880 /* TODO: Prevent failure here, so parent does not fail */
2881 rc = mdb_midl_append_list(&parent->mt_spill_pgs, txn->mt_spill_pgs);
2883 parent->mt_flags |= MDB_TXN_ERROR;
2884 mdb_midl_free(txn->mt_spill_pgs);
2885 mdb_midl_sort(parent->mt_spill_pgs);
2887 parent->mt_spill_pgs = txn->mt_spill_pgs;
2891 parent->mt_child = NULL;
2892 mdb_midl_free(((MDB_ntxn *)txn)->mnt_pgstate.mf_pghead);
2897 if (txn != env->me_txn) {
2898 DPUTS("attempt to commit unknown transaction");
2903 mdb_cursors_close(txn, 0);
2905 if (!txn->mt_u.dirty_list[0].mid &&
2906 !(txn->mt_flags & (MDB_TXN_DIRTY|MDB_TXN_SPILLS)))
2909 DPRINTF(("committing txn %"Z"u %p on mdbenv %p, root page %"Z"u",
2910 txn->mt_txnid, (void*)txn, (void*)env, txn->mt_dbs[MAIN_DBI].md_root));
2912 /* Update DB root pointers */
2913 if (txn->mt_numdbs > 2) {
2917 data.mv_size = sizeof(MDB_db);
2919 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
2920 for (i = 2; i < txn->mt_numdbs; i++) {
2921 if (txn->mt_dbflags[i] & DB_DIRTY) {
2922 data.mv_data = &txn->mt_dbs[i];
2923 rc = mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
2930 rc = mdb_freelist_save(txn);
2934 mdb_midl_free(env->me_pghead);
2935 env->me_pghead = NULL;
2936 if (mdb_midl_shrink(&txn->mt_free_pgs))
2937 env->me_free_pgs = txn->mt_free_pgs;
2943 if ((rc = mdb_page_flush(txn, 0)) ||
2944 (rc = mdb_env_sync(env, 0)) ||
2945 (rc = mdb_env_write_meta(txn)))
2951 mdb_dbis_update(txn, 1);
2954 UNLOCK_MUTEX_W(env);
2964 /** Read the environment parameters of a DB environment before
2965 * mapping it into memory.
2966 * @param[in] env the environment handle
2967 * @param[out] meta address of where to store the meta information
2968 * @return 0 on success, non-zero on failure.
2971 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
2978 /* We don't know the page size yet, so use a minimum value.
2979 * Read both meta pages so we can use the latest one.
2982 for (i=off=0; i<2; i++, off = meta->mm_psize) {
2986 memset(&ov, 0, sizeof(ov));
2988 rc = ReadFile(env->me_fd,&pbuf,MDB_PAGESIZE,&len,&ov) ? (int)len : -1;
2989 if (rc == -1 && ErrCode() == ERROR_HANDLE_EOF)
2992 rc = pread(env->me_fd, &pbuf, MDB_PAGESIZE, off);
2994 if (rc != MDB_PAGESIZE) {
2995 if (rc == 0 && off == 0)
2997 rc = rc < 0 ? (int) ErrCode() : MDB_INVALID;
2998 DPRINTF(("read: %s", mdb_strerror(rc)));
3002 p = (MDB_page *)&pbuf;
3004 if (!F_ISSET(p->mp_flags, P_META)) {
3005 DPRINTF(("page %"Z"u not a meta page", p->mp_pgno));
3010 if (m->mm_magic != MDB_MAGIC) {
3011 DPUTS("meta has invalid magic");
3015 if (m->mm_version != MDB_DATA_VERSION) {
3016 DPRINTF(("database is version %u, expected version %u",
3017 m->mm_version, MDB_DATA_VERSION));
3018 return MDB_VERSION_MISMATCH;
3021 if (off == 0 || m->mm_txnid > meta->mm_txnid)
3027 /** Write the environment parameters of a freshly created DB environment.
3028 * @param[in] env the environment handle
3029 * @param[out] meta address of where to store the meta information
3030 * @return 0 on success, non-zero on failure.
3033 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
3041 memset(&ov, 0, sizeof(ov));
3042 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3044 rc = WriteFile(fd, ptr, size, &len, &ov); } while(0)
3047 #define DO_PWRITE(rc, fd, ptr, size, len, pos) do { \
3048 len = pwrite(fd, ptr, size, pos); \
3049 rc = (len >= 0); } while(0)
3052 DPUTS("writing new meta page");
3054 psize = env->me_psize;
3056 meta->mm_magic = MDB_MAGIC;
3057 meta->mm_version = MDB_DATA_VERSION;
3058 meta->mm_mapsize = env->me_mapsize;
3059 meta->mm_psize = psize;
3060 meta->mm_last_pg = 1;
3061 meta->mm_flags = env->me_flags & 0xffff;
3062 meta->mm_flags |= MDB_INTEGERKEY;
3063 meta->mm_dbs[0].md_root = P_INVALID;
3064 meta->mm_dbs[1].md_root = P_INVALID;
3066 p = calloc(2, psize);
3068 p->mp_flags = P_META;
3069 *(MDB_meta *)METADATA(p) = *meta;
3071 q = (MDB_page *)((char *)p + psize);
3073 q->mp_flags = P_META;
3074 *(MDB_meta *)METADATA(q) = *meta;
3076 DO_PWRITE(rc, env->me_fd, p, psize * 2, len, 0);
3079 else if ((unsigned) len == psize * 2)
3087 /** Update the environment info to commit a transaction.
3088 * @param[in] txn the transaction that's being committed
3089 * @return 0 on success, non-zero on failure.
3092 mdb_env_write_meta(MDB_txn *txn)
3095 MDB_meta meta, metab, *mp;
3097 int rc, len, toggle;
3106 assert(txn != NULL);
3107 assert(txn->mt_env != NULL);
3109 toggle = txn->mt_txnid & 1;
3110 DPRINTF(("writing meta page %d for root page %"Z"u",
3111 toggle, txn->mt_dbs[MAIN_DBI].md_root));
3114 mp = env->me_metas[toggle];
3116 if (env->me_flags & MDB_WRITEMAP) {
3117 /* Persist any increases of mapsize config */
3118 if (env->me_mapsize > mp->mm_mapsize)
3119 mp->mm_mapsize = env->me_mapsize;
3120 mp->mm_dbs[0] = txn->mt_dbs[0];
3121 mp->mm_dbs[1] = txn->mt_dbs[1];
3122 mp->mm_last_pg = txn->mt_next_pgno - 1;
3123 mp->mm_txnid = txn->mt_txnid;
3124 if (!(env->me_flags & (MDB_NOMETASYNC|MDB_NOSYNC))) {
3125 rc = (env->me_flags & MDB_MAPASYNC) ? MS_ASYNC : MS_SYNC;
3128 ptr += env->me_psize;
3129 if (MDB_MSYNC(ptr, env->me_psize, rc)) {
3136 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
3137 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
3139 ptr = (char *)&meta;
3140 if (env->me_mapsize > mp->mm_mapsize) {
3141 /* Persist any increases of mapsize config */
3142 meta.mm_mapsize = env->me_mapsize;
3143 off = offsetof(MDB_meta, mm_mapsize);
3145 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
3147 len = sizeof(MDB_meta) - off;
3150 meta.mm_dbs[0] = txn->mt_dbs[0];
3151 meta.mm_dbs[1] = txn->mt_dbs[1];
3152 meta.mm_last_pg = txn->mt_next_pgno - 1;
3153 meta.mm_txnid = txn->mt_txnid;
3156 off += env->me_psize;
3159 /* Write to the SYNC fd */
3160 mfd = env->me_flags & (MDB_NOSYNC|MDB_NOMETASYNC) ?
3161 env->me_fd : env->me_mfd;
3164 memset(&ov, 0, sizeof(ov));
3166 if (!WriteFile(mfd, ptr, len, (DWORD *)&rc, &ov))
3170 rc = pwrite(mfd, ptr, len, off);
3173 rc = rc < 0 ? ErrCode() : EIO;
3174 DPUTS("write failed, disk error?");
3175 /* On a failure, the pagecache still contains the new data.
3176 * Write some old data back, to prevent it from being used.
3177 * Use the non-SYNC fd; we know it will fail anyway.
3179 meta.mm_last_pg = metab.mm_last_pg;
3180 meta.mm_txnid = metab.mm_txnid;
3182 memset(&ov, 0, sizeof(ov));
3184 WriteFile(env->me_fd, ptr, len, NULL, &ov);
3186 r2 = pwrite(env->me_fd, ptr, len, off);
3187 (void)r2; /* Silence warnings. We don't care about pwrite's return value */
3190 env->me_flags |= MDB_FATAL_ERROR;
3194 /* Memory ordering issues are irrelevant; since the entire writer
3195 * is wrapped by wmutex, all of these changes will become visible
3196 * after the wmutex is unlocked. Since the DB is multi-version,
3197 * readers will get consistent data regardless of how fresh or
3198 * how stale their view of these values is.
3201 env->me_txns->mti_txnid = txn->mt_txnid;
3206 /** Check both meta pages to see which one is newer.
3207 * @param[in] env the environment handle
3208 * @return meta toggle (0 or 1).
3211 mdb_env_pick_meta(const MDB_env *env)
3213 return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
3217 mdb_env_create(MDB_env **env)
3221 e = calloc(1, sizeof(MDB_env));
3225 e->me_maxreaders = DEFAULT_READERS;
3226 e->me_maxdbs = e->me_numdbs = 2;
3227 e->me_fd = INVALID_HANDLE_VALUE;
3228 e->me_lfd = INVALID_HANDLE_VALUE;
3229 e->me_mfd = INVALID_HANDLE_VALUE;
3230 #ifdef MDB_USE_POSIX_SEM
3231 e->me_rmutex = SEM_FAILED;
3232 e->me_wmutex = SEM_FAILED;
3234 e->me_pid = getpid();
3235 VGMEMP_CREATE(e,0,0);
3241 mdb_env_map(MDB_env *env, void *addr, int newsize)
3244 unsigned int flags = env->me_flags;
3248 LONG sizelo, sizehi;
3249 sizelo = env->me_mapsize & 0xffffffff;
3250 sizehi = env->me_mapsize >> 16 >> 16; /* only needed on Win64 */
3252 /* Windows won't create mappings for zero length files.
3253 * Just allocate the maxsize right now.
3256 if (SetFilePointer(env->me_fd, sizelo, &sizehi, 0) != (DWORD)sizelo
3257 || !SetEndOfFile(env->me_fd)
3258 || SetFilePointer(env->me_fd, 0, NULL, 0) != 0)
3261 mh = CreateFileMapping(env->me_fd, NULL, flags & MDB_WRITEMAP ?
3262 PAGE_READWRITE : PAGE_READONLY,
3263 sizehi, sizelo, NULL);
3266 env->me_map = MapViewOfFileEx(mh, flags & MDB_WRITEMAP ?
3267 FILE_MAP_WRITE : FILE_MAP_READ,
3268 0, 0, env->me_mapsize, addr);
3269 rc = env->me_map ? 0 : ErrCode();
3274 int prot = PROT_READ;
3275 if (flags & MDB_WRITEMAP) {
3277 if (ftruncate(env->me_fd, env->me_mapsize) < 0)
3280 env->me_map = mmap(addr, env->me_mapsize, prot, MAP_SHARED,
3282 if (env->me_map == MAP_FAILED) {
3287 if (flags & MDB_NORDAHEAD) {
3288 /* Turn off readahead. It's harmful when the DB is larger than RAM. */
3290 madvise(env->me_map, env->me_mapsize, MADV_RANDOM);
3292 #ifdef POSIX_MADV_RANDOM
3293 posix_madvise(env->me_map, env->me_mapsize, POSIX_MADV_RANDOM);
3294 #endif /* POSIX_MADV_RANDOM */
3295 #endif /* MADV_RANDOM */
3299 /* Can happen because the address argument to mmap() is just a
3300 * hint. mmap() can pick another, e.g. if the range is in use.
3301 * The MAP_FIXED flag would prevent that, but then mmap could
3302 * instead unmap existing pages to make room for the new map.
3304 if (addr && env->me_map != addr)
3305 return EBUSY; /* TODO: Make a new MDB_* error code? */
3307 p = (MDB_page *)env->me_map;
3308 env->me_metas[0] = METADATA(p);
3309 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + env->me_psize);
3315 mdb_env_set_mapsize(MDB_env *env, size_t size)
3317 /* If env is already open, caller is responsible for making
3318 * sure there are no active txns.
3326 size = env->me_metas[mdb_env_pick_meta(env)]->mm_mapsize;
3327 else if (size < env->me_mapsize) {
3328 /* If the configured size is smaller, make sure it's
3329 * still big enough. Silently round up to minimum if not.
3331 size_t minsize = (env->me_metas[mdb_env_pick_meta(env)]->mm_last_pg + 1) * env->me_psize;
3335 munmap(env->me_map, env->me_mapsize);
3336 env->me_mapsize = size;
3337 old = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : NULL;
3338 rc = mdb_env_map(env, old, 1);
3342 env->me_mapsize = size;
3344 env->me_maxpg = env->me_mapsize / env->me_psize;
3349 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
3353 env->me_maxdbs = dbs + 2; /* Named databases + main and free DB */
3358 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
3360 if (env->me_map || readers < 1)
3362 env->me_maxreaders = readers;
3367 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
3369 if (!env || !readers)
3371 *readers = env->me_maxreaders;
3375 /** Further setup required for opening an MDB environment
3378 mdb_env_open2(MDB_env *env)
3380 unsigned int flags = env->me_flags;
3381 int i, newenv = 0, rc;
3385 /* See if we should use QueryLimited */
3387 if ((rc & 0xff) > 5)
3388 env->me_pidquery = MDB_PROCESS_QUERY_LIMITED_INFORMATION;
3390 env->me_pidquery = PROCESS_QUERY_INFORMATION;
3393 memset(&meta, 0, sizeof(meta));
3395 if ((i = mdb_env_read_header(env, &meta)) != 0) {
3398 DPUTS("new mdbenv");
3400 GET_PAGESIZE(env->me_psize);
3402 env->me_psize = meta.mm_psize;
3405 /* Was a mapsize configured? */
3406 if (!env->me_mapsize) {
3407 /* If this is a new environment, take the default,
3408 * else use the size recorded in the existing env.
3410 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
3411 } else if (env->me_mapsize < meta.mm_mapsize) {
3412 /* If the configured size is smaller, make sure it's
3413 * still big enough. Silently round up to minimum if not.
3415 size_t minsize = (meta.mm_last_pg + 1) * meta.mm_psize;
3416 if (env->me_mapsize < minsize)
3417 env->me_mapsize = minsize;
3420 rc = mdb_env_map(env, meta.mm_address, newenv);
3425 if (flags & MDB_FIXEDMAP)
3426 meta.mm_address = env->me_map;
3427 i = mdb_env_init_meta(env, &meta);
3428 if (i != MDB_SUCCESS) {
3432 env->me_maxfree_1pg = (env->me_psize - PAGEHDRSZ) / sizeof(pgno_t) - 1;
3433 env->me_nodemax = (env->me_psize - PAGEHDRSZ) / MDB_MINKEYS;
3435 env->me_maxpg = env->me_mapsize / env->me_psize;
3438 int toggle = mdb_env_pick_meta(env);
3439 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
3441 DPRINTF(("opened database version %u, pagesize %u",
3442 env->me_metas[0]->mm_version, env->me_psize));
3443 DPRINTF(("using meta page %d", toggle));
3444 DPRINTF(("depth: %u", db->md_depth));
3445 DPRINTF(("entries: %"Z"u", db->md_entries));
3446 DPRINTF(("branch pages: %"Z"u", db->md_branch_pages));
3447 DPRINTF(("leaf pages: %"Z"u", db->md_leaf_pages));
3448 DPRINTF(("overflow pages: %"Z"u", db->md_overflow_pages));
3449 DPRINTF(("root: %"Z"u", db->md_root));
3457 /** Release a reader thread's slot in the reader lock table.
3458 * This function is called automatically when a thread exits.
3459 * @param[in] ptr This points to the slot in the reader lock table.
3462 mdb_env_reader_dest(void *ptr)
3464 MDB_reader *reader = ptr;
3470 /** Junk for arranging thread-specific callbacks on Windows. This is
3471 * necessarily platform and compiler-specific. Windows supports up
3472 * to 1088 keys. Let's assume nobody opens more than 64 environments
3473 * in a single process, for now. They can override this if needed.
3475 #ifndef MAX_TLS_KEYS
3476 #define MAX_TLS_KEYS 64
3478 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
3479 static int mdb_tls_nkeys;
3481 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
3485 case DLL_PROCESS_ATTACH: break;
3486 case DLL_THREAD_ATTACH: break;
3487 case DLL_THREAD_DETACH:
3488 for (i=0; i<mdb_tls_nkeys; i++) {
3489 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
3490 mdb_env_reader_dest(r);
3493 case DLL_PROCESS_DETACH: break;
3498 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3500 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
3504 /* Force some symbol references.
3505 * _tls_used forces the linker to create the TLS directory if not already done
3506 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
3508 #pragma comment(linker, "/INCLUDE:_tls_used")
3509 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
3510 #pragma const_seg(".CRT$XLB")
3511 extern const PIMAGE_TLS_CALLBACK mdb_tls_callback;
3512 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3515 #pragma comment(linker, "/INCLUDE:__tls_used")
3516 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
3517 #pragma data_seg(".CRT$XLB")
3518 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
3520 #endif /* WIN 32/64 */
3521 #endif /* !__GNUC__ */
3524 /** Downgrade the exclusive lock on the region back to shared */
3526 mdb_env_share_locks(MDB_env *env, int *excl)
3528 int rc = 0, toggle = mdb_env_pick_meta(env);
3530 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
3535 /* First acquire a shared lock. The Unlock will
3536 * then release the existing exclusive lock.
3538 memset(&ov, 0, sizeof(ov));
3539 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3542 UnlockFile(env->me_lfd, 0, 0, 1, 0);
3548 struct flock lock_info;
3549 /* The shared lock replaces the existing lock */
3550 memset((void *)&lock_info, 0, sizeof(lock_info));
3551 lock_info.l_type = F_RDLCK;
3552 lock_info.l_whence = SEEK_SET;
3553 lock_info.l_start = 0;
3554 lock_info.l_len = 1;
3555 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3556 (rc = ErrCode()) == EINTR) ;
3557 *excl = rc ? -1 : 0; /* error may mean we lost the lock */
3564 /** Try to get exlusive lock, otherwise shared.
3565 * Maintain *excl = -1: no/unknown lock, 0: shared, 1: exclusive.
3568 mdb_env_excl_lock(MDB_env *env, int *excl)
3572 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
3576 memset(&ov, 0, sizeof(ov));
3577 if (LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
3584 struct flock lock_info;
3585 memset((void *)&lock_info, 0, sizeof(lock_info));
3586 lock_info.l_type = F_WRLCK;
3587 lock_info.l_whence = SEEK_SET;
3588 lock_info.l_start = 0;
3589 lock_info.l_len = 1;
3590 while ((rc = fcntl(env->me_lfd, F_SETLK, &lock_info)) &&
3591 (rc = ErrCode()) == EINTR) ;
3595 # ifdef MDB_USE_POSIX_SEM
3596 if (*excl < 0) /* always true when !MDB_USE_POSIX_SEM */
3599 lock_info.l_type = F_RDLCK;
3600 while ((rc = fcntl(env->me_lfd, F_SETLKW, &lock_info)) &&
3601 (rc = ErrCode()) == EINTR) ;
3611 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
3613 * @(#) $Revision: 5.1 $
3614 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
3615 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
3617 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
3621 * Please do not copyright this code. This code is in the public domain.
3623 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
3624 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
3625 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
3626 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
3627 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
3628 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
3629 * PERFORMANCE OF THIS SOFTWARE.
3632 * chongo <Landon Curt Noll> /\oo/\
3633 * http://www.isthe.com/chongo/
3635 * Share and Enjoy! :-)
3638 typedef unsigned long long mdb_hash_t;
3639 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
3641 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
3642 * @param[in] val value to hash
3643 * @param[in] hval initial value for hash
3644 * @return 64 bit hash
3646 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
3647 * hval arg on the first call.
3650 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
3652 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
3653 unsigned char *end = s + val->mv_size;
3655 * FNV-1a hash each octet of the string
3658 /* xor the bottom with the current octet */
3659 hval ^= (mdb_hash_t)*s++;
3661 /* multiply by the 64 bit FNV magic prime mod 2^64 */
3662 hval += (hval << 1) + (hval << 4) + (hval << 5) +
3663 (hval << 7) + (hval << 8) + (hval << 40);
3665 /* return our new hash value */
3669 /** Hash the string and output the encoded hash.
3670 * This uses modified RFC1924 Ascii85 encoding to accommodate systems with
3671 * very short name limits. We don't care about the encoding being reversible,
3672 * we just want to preserve as many bits of the input as possible in a
3673 * small printable string.
3674 * @param[in] str string to hash
3675 * @param[out] encbuf an array of 11 chars to hold the hash
3677 static const char mdb_a85[]= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~";
3680 mdb_pack85(unsigned long l, char *out)
3684 for (i=0; i<5; i++) {
3685 *out++ = mdb_a85[l % 85];
3691 mdb_hash_enc(MDB_val *val, char *encbuf)
3693 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
3695 mdb_pack85(h, encbuf);
3696 mdb_pack85(h>>32, encbuf+5);
3701 /** Open and/or initialize the lock region for the environment.
3702 * @param[in] env The MDB environment.
3703 * @param[in] lpath The pathname of the file used for the lock region.
3704 * @param[in] mode The Unix permissions for the file, if we create it.
3705 * @param[out] excl Resulting file lock type: -1 none, 0 shared, 1 exclusive
3706 * @param[in,out] excl In -1, out lock type: -1 none, 0 shared, 1 exclusive
3707 * @return 0 on success, non-zero on failure.
3710 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
3713 # define MDB_ERRCODE_ROFS ERROR_WRITE_PROTECT
3715 # define MDB_ERRCODE_ROFS EROFS
3716 #ifdef O_CLOEXEC /* Linux: Open file and set FD_CLOEXEC atomically */
3717 # define MDB_CLOEXEC O_CLOEXEC
3720 # define MDB_CLOEXEC 0
3727 env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
3728 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
3729 FILE_ATTRIBUTE_NORMAL, NULL);
3731 env->me_lfd = open(lpath, O_RDWR|O_CREAT|MDB_CLOEXEC, mode);
3733 if (env->me_lfd == INVALID_HANDLE_VALUE) {
3735 if (rc == MDB_ERRCODE_ROFS && (env->me_flags & MDB_RDONLY)) {
3740 #if ! ((MDB_CLOEXEC) || defined(_WIN32))
3741 /* Lose record locks when exec*() */
3742 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
3743 fcntl(env->me_lfd, F_SETFD, fdflags);
3746 if (!(env->me_flags & MDB_NOTLS)) {
3747 rc = pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
3750 env->me_flags |= MDB_ENV_TXKEY;
3752 /* Windows TLS callbacks need help finding their TLS info. */
3753 if (mdb_tls_nkeys >= MAX_TLS_KEYS) {
3757 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
3761 /* Try to get exclusive lock. If we succeed, then
3762 * nobody is using the lock region and we should initialize it.
3764 if ((rc = mdb_env_excl_lock(env, excl))) goto fail;
3767 size = GetFileSize(env->me_lfd, NULL);
3769 size = lseek(env->me_lfd, 0, SEEK_END);
3770 if (size == -1) goto fail_errno;
3772 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
3773 if (size < rsize && *excl > 0) {
3775 if (SetFilePointer(env->me_lfd, rsize, NULL, FILE_BEGIN) != rsize
3776 || !SetEndOfFile(env->me_lfd))
3779 if (ftruncate(env->me_lfd, rsize) != 0) goto fail_errno;
3783 size = rsize - sizeof(MDB_txninfo);
3784 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
3789 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
3791 if (!mh) goto fail_errno;
3792 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
3794 if (!env->me_txns) goto fail_errno;
3796 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
3798 if (m == MAP_FAILED) goto fail_errno;
3804 BY_HANDLE_FILE_INFORMATION stbuf;
3813 if (!mdb_sec_inited) {
3814 InitializeSecurityDescriptor(&mdb_null_sd,
3815 SECURITY_DESCRIPTOR_REVISION);
3816 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
3817 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
3818 mdb_all_sa.bInheritHandle = FALSE;
3819 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
3822 if (!GetFileInformationByHandle(env->me_lfd, &stbuf)) goto fail_errno;
3823 idbuf.volume = stbuf.dwVolumeSerialNumber;
3824 idbuf.nhigh = stbuf.nFileIndexHigh;
3825 idbuf.nlow = stbuf.nFileIndexLow;
3826 val.mv_data = &idbuf;
3827 val.mv_size = sizeof(idbuf);
3828 mdb_hash_enc(&val, encbuf);
3829 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", encbuf);
3830 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", encbuf);
3831 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
3832 if (!env->me_rmutex) goto fail_errno;
3833 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
3834 if (!env->me_wmutex) goto fail_errno;
3835 #elif defined(MDB_USE_POSIX_SEM)
3844 #if defined(__NetBSD__)
3845 #define MDB_SHORT_SEMNAMES 1 /* limited to 14 chars */
3847 if (fstat(env->me_lfd, &stbuf)) goto fail_errno;
3848 idbuf.dev = stbuf.st_dev;
3849 idbuf.ino = stbuf.st_ino;
3850 val.mv_data = &idbuf;
3851 val.mv_size = sizeof(idbuf);
3852 mdb_hash_enc(&val, encbuf);
3853 #ifdef MDB_SHORT_SEMNAMES
3854 encbuf[9] = '\0'; /* drop name from 15 chars to 14 chars */
3856 sprintf(env->me_txns->mti_rmname, "/MDBr%s", encbuf);
3857 sprintf(env->me_txns->mti_wmname, "/MDBw%s", encbuf);
3858 /* Clean up after a previous run, if needed: Try to
3859 * remove both semaphores before doing anything else.
3861 sem_unlink(env->me_txns->mti_rmname);
3862 sem_unlink(env->me_txns->mti_wmname);
3863 env->me_rmutex = sem_open(env->me_txns->mti_rmname,
3864 O_CREAT|O_EXCL, mode, 1);
3865 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3866 env->me_wmutex = sem_open(env->me_txns->mti_wmname,
3867 O_CREAT|O_EXCL, mode, 1);
3868 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3869 #else /* MDB_USE_POSIX_SEM */
3870 pthread_mutexattr_t mattr;
3872 if ((rc = pthread_mutexattr_init(&mattr))
3873 || (rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))
3874 || (rc = pthread_mutex_init(&env->me_txns->mti_mutex, &mattr))
3875 || (rc = pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr)))
3877 pthread_mutexattr_destroy(&mattr);
3878 #endif /* _WIN32 || MDB_USE_POSIX_SEM */
3880 env->me_txns->mti_magic = MDB_MAGIC;
3881 env->me_txns->mti_format = MDB_LOCK_FORMAT;
3882 env->me_txns->mti_txnid = 0;
3883 env->me_txns->mti_numreaders = 0;
3886 if (env->me_txns->mti_magic != MDB_MAGIC) {
3887 DPUTS("lock region has invalid magic");
3891 if (env->me_txns->mti_format != MDB_LOCK_FORMAT) {
3892 DPRINTF(("lock region has format+version 0x%x, expected 0x%x",
3893 env->me_txns->mti_format, MDB_LOCK_FORMAT));
3894 rc = MDB_VERSION_MISMATCH;
3898 if (rc && rc != EACCES && rc != EAGAIN) {
3902 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
3903 if (!env->me_rmutex) goto fail_errno;
3904 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
3905 if (!env->me_wmutex) goto fail_errno;
3906 #elif defined(MDB_USE_POSIX_SEM)
3907 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
3908 if (env->me_rmutex == SEM_FAILED) goto fail_errno;
3909 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
3910 if (env->me_wmutex == SEM_FAILED) goto fail_errno;
3921 /** The name of the lock file in the DB environment */
3922 #define LOCKNAME "/lock.mdb"
3923 /** The name of the data file in the DB environment */
3924 #define DATANAME "/data.mdb"
3925 /** The suffix of the lock file when no subdir is used */
3926 #define LOCKSUFF "-lock"
3927 /** Only a subset of the @ref mdb_env flags can be changed
3928 * at runtime. Changing other flags requires closing the
3929 * environment and re-opening it with the new flags.
3931 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC|MDB_MAPASYNC)
3932 #define CHANGELESS (MDB_FIXEDMAP|MDB_NOSUBDIR|MDB_RDONLY|MDB_WRITEMAP|MDB_NOTLS|MDB_NOLOCK)
3935 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode)
3937 int oflags, rc, len, excl = -1;
3938 char *lpath, *dpath;
3940 if (env->me_fd!=INVALID_HANDLE_VALUE || (flags & ~(CHANGEABLE|CHANGELESS)))
3944 if (flags & MDB_NOSUBDIR) {
3945 rc = len + sizeof(LOCKSUFF) + len + 1;
3947 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
3952 if (flags & MDB_NOSUBDIR) {
3953 dpath = lpath + len + sizeof(LOCKSUFF);
3954 sprintf(lpath, "%s" LOCKSUFF, path);
3955 strcpy(dpath, path);
3957 dpath = lpath + len + sizeof(LOCKNAME);
3958 sprintf(lpath, "%s" LOCKNAME, path);
3959 sprintf(dpath, "%s" DATANAME, path);
3963 flags |= env->me_flags;
3964 if (flags & MDB_RDONLY) {
3965 /* silently ignore WRITEMAP when we're only getting read access */
3966 flags &= ~MDB_WRITEMAP;
3968 if (!((env->me_free_pgs = mdb_midl_alloc(MDB_IDL_UM_MAX)) &&
3969 (env->me_dirty_list = calloc(MDB_IDL_UM_SIZE, sizeof(MDB_ID2)))))
3972 env->me_flags = flags |= MDB_ENV_ACTIVE;
3976 env->me_path = strdup(path);
3977 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
3978 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
3979 if (!(env->me_dbxs && env->me_path && env->me_dbflags)) {
3984 /* For RDONLY, get lockfile after we know datafile exists */
3985 if (!(flags & (MDB_RDONLY|MDB_NOLOCK))) {
3986 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
3992 if (F_ISSET(flags, MDB_RDONLY)) {
3993 oflags = GENERIC_READ;
3994 len = OPEN_EXISTING;
3996 oflags = GENERIC_READ|GENERIC_WRITE;
3999 mode = FILE_ATTRIBUTE_NORMAL;
4000 env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
4001 NULL, len, mode, NULL);
4003 if (F_ISSET(flags, MDB_RDONLY))
4006 oflags = O_RDWR | O_CREAT;
4008 env->me_fd = open(dpath, oflags, mode);
4010 if (env->me_fd == INVALID_HANDLE_VALUE) {
4015 if ((flags & (MDB_RDONLY|MDB_NOLOCK)) == MDB_RDONLY) {
4016 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
4021 if ((rc = mdb_env_open2(env)) == MDB_SUCCESS) {
4022 if (flags & (MDB_RDONLY|MDB_WRITEMAP)) {
4023 env->me_mfd = env->me_fd;
4025 /* Synchronous fd for meta writes. Needed even with
4026 * MDB_NOSYNC/MDB_NOMETASYNC, in case these get reset.
4029 len = OPEN_EXISTING;
4030 env->me_mfd = CreateFile(dpath, oflags,
4031 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
4032 mode | FILE_FLAG_WRITE_THROUGH, NULL);
4035 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
4037 if (env->me_mfd == INVALID_HANDLE_VALUE) {
4042 DPRINTF(("opened dbenv %p", (void *) env));
4044 rc = mdb_env_share_locks(env, &excl);
4050 mdb_env_close0(env, excl);
4056 /** Destroy resources from mdb_env_open(), clear our readers & DBIs */
4058 mdb_env_close0(MDB_env *env, int excl)
4062 if (!(env->me_flags & MDB_ENV_ACTIVE))
4065 /* Doing this here since me_dbxs may not exist during mdb_env_close */
4066 for (i = env->me_maxdbs; --i > MAIN_DBI; )
4067 free(env->me_dbxs[i].md_name.mv_data);
4069 free(env->me_dbflags);
4072 free(env->me_dirty_list);
4073 mdb_midl_free(env->me_free_pgs);
4075 if (env->me_flags & MDB_ENV_TXKEY) {
4076 pthread_key_delete(env->me_txkey);
4078 /* Delete our key from the global list */
4079 for (i=0; i<mdb_tls_nkeys; i++)
4080 if (mdb_tls_keys[i] == env->me_txkey) {
4081 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
4089 munmap(env->me_map, env->me_mapsize);
4091 if (env->me_mfd != env->me_fd && env->me_mfd != INVALID_HANDLE_VALUE)
4092 (void) close(env->me_mfd);
4093 if (env->me_fd != INVALID_HANDLE_VALUE)
4094 (void) close(env->me_fd);
4096 pid_t pid = env->me_pid;
4097 /* Clearing readers is done in this function because
4098 * me_txkey with its destructor must be disabled first.
4100 for (i = env->me_numreaders; --i >= 0; )
4101 if (env->me_txns->mti_readers[i].mr_pid == pid)
4102 env->me_txns->mti_readers[i].mr_pid = 0;
4104 if (env->me_rmutex) {
4105 CloseHandle(env->me_rmutex);
4106 if (env->me_wmutex) CloseHandle(env->me_wmutex);
4108 /* Windows automatically destroys the mutexes when
4109 * the last handle closes.
4111 #elif defined(MDB_USE_POSIX_SEM)
4112 if (env->me_rmutex != SEM_FAILED) {
4113 sem_close(env->me_rmutex);
4114 if (env->me_wmutex != SEM_FAILED)
4115 sem_close(env->me_wmutex);
4116 /* If we have the filelock: If we are the
4117 * only remaining user, clean up semaphores.
4120 mdb_env_excl_lock(env, &excl);
4122 sem_unlink(env->me_txns->mti_rmname);
4123 sem_unlink(env->me_txns->mti_wmname);
4127 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
4129 if (env->me_lfd != INVALID_HANDLE_VALUE) {
4132 /* Unlock the lockfile. Windows would have unlocked it
4133 * after closing anyway, but not necessarily at once.
4135 UnlockFile(env->me_lfd, 0, 0, 1, 0);
4138 (void) close(env->me_lfd);
4141 env->me_flags &= ~(MDB_ENV_ACTIVE|MDB_ENV_TXKEY);
4145 mdb_env_copyfd(MDB_env *env, HANDLE fd)
4147 MDB_txn *txn = NULL;
4153 #define DO_WRITE(rc, fd, ptr, w2, len) rc = WriteFile(fd, ptr, w2, &len, NULL)
4157 #define DO_WRITE(rc, fd, ptr, w2, len) len = write(fd, ptr, w2); rc = (len >= 0)
4160 /* Do the lock/unlock of the reader mutex before starting the
4161 * write txn. Otherwise other read txns could block writers.
4163 rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
4168 /* We must start the actual read txn after blocking writers */
4169 mdb_txn_reset0(txn, "reset-stage1");
4171 /* Temporarily block writers until we snapshot the meta pages */
4174 rc = mdb_txn_renew0(txn);
4176 UNLOCK_MUTEX_W(env);
4181 wsize = env->me_psize * 2;
4185 DO_WRITE(rc, fd, ptr, w2, len);
4189 } else if (len > 0) {
4195 /* Non-blocking or async handles are not supported */
4201 UNLOCK_MUTEX_W(env);
4206 wsize = txn->mt_next_pgno * env->me_psize - wsize;
4208 if (wsize > MAX_WRITE)
4212 DO_WRITE(rc, fd, ptr, w2, len);
4216 } else if (len > 0) {
4233 mdb_env_copy(MDB_env *env, const char *path)
4237 HANDLE newfd = INVALID_HANDLE_VALUE;
4239 if (env->me_flags & MDB_NOSUBDIR) {
4240 lpath = (char *)path;
4243 len += sizeof(DATANAME);
4244 lpath = malloc(len);
4247 sprintf(lpath, "%s" DATANAME, path);
4250 /* The destination path must exist, but the destination file must not.
4251 * We don't want the OS to cache the writes, since the source data is
4252 * already in the OS cache.
4255 newfd = CreateFile(lpath, GENERIC_WRITE, 0, NULL, CREATE_NEW,
4256 FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH, NULL);
4258 newfd = open(lpath, O_WRONLY|O_CREAT|O_EXCL, 0666);
4260 if (newfd == INVALID_HANDLE_VALUE) {
4266 /* Set O_DIRECT if the file system supports it */
4267 if ((rc = fcntl(newfd, F_GETFL)) != -1)
4268 (void) fcntl(newfd, F_SETFL, rc | O_DIRECT);
4270 #ifdef F_NOCACHE /* __APPLE__ */
4271 rc = fcntl(newfd, F_NOCACHE, 1);
4278 rc = mdb_env_copyfd(env, newfd);
4281 if (!(env->me_flags & MDB_NOSUBDIR))
4283 if (newfd != INVALID_HANDLE_VALUE)
4284 if (close(newfd) < 0 && rc == MDB_SUCCESS)
4291 mdb_env_close(MDB_env *env)
4298 VGMEMP_DESTROY(env);
4299 while ((dp = env->me_dpages) != NULL) {
4300 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
4301 env->me_dpages = dp->mp_next;
4305 mdb_env_close0(env, 0);
4309 /** Compare two items pointing at aligned size_t's */
4311 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
4313 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
4314 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
4317 /** Compare two items pointing at aligned unsigned int's */
4319 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
4321 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
4322 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
4325 /** Compare two items pointing at unsigned ints of unknown alignment.
4326 * Nodes and keys are guaranteed to be 2-byte aligned.
4329 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
4331 #if BYTE_ORDER == LITTLE_ENDIAN
4332 unsigned short *u, *c;
4335 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
4336 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
4339 } while(!x && u > (unsigned short *)a->mv_data);
4342 return memcmp(a->mv_data, b->mv_data, a->mv_size);
4346 /** Compare two items lexically */
4348 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
4355 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4361 diff = memcmp(a->mv_data, b->mv_data, len);
4362 return diff ? diff : len_diff<0 ? -1 : len_diff;
4365 /** Compare two items in reverse byte order */
4367 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
4369 const unsigned char *p1, *p2, *p1_lim;
4373 p1_lim = (const unsigned char *)a->mv_data;
4374 p1 = (const unsigned char *)a->mv_data + a->mv_size;
4375 p2 = (const unsigned char *)b->mv_data + b->mv_size;
4377 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
4383 while (p1 > p1_lim) {
4384 diff = *--p1 - *--p2;
4388 return len_diff<0 ? -1 : len_diff;
4391 /** Search for key within a page, using binary search.
4392 * Returns the smallest entry larger or equal to the key.
4393 * If exactp is non-null, stores whether the found entry was an exact match
4394 * in *exactp (1 or 0).
4395 * Updates the cursor index with the index of the found entry.
4396 * If no entry larger or equal to the key is found, returns NULL.
4399 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
4401 unsigned int i = 0, nkeys;
4404 MDB_page *mp = mc->mc_pg[mc->mc_top];
4405 MDB_node *node = NULL;
4410 nkeys = NUMKEYS(mp);
4415 COPY_PGNO(pgno, mp->mp_pgno);
4416 DPRINTF(("searching %u keys in %s %spage %"Z"u",
4417 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
4424 low = IS_LEAF(mp) ? 0 : 1;
4426 cmp = mc->mc_dbx->md_cmp;
4428 /* Branch pages have no data, so if using integer keys,
4429 * alignment is guaranteed. Use faster mdb_cmp_int.
4431 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
4432 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
4439 nodekey.mv_size = mc->mc_db->md_pad;
4440 node = NODEPTR(mp, 0); /* fake */
4441 while (low <= high) {
4442 i = (low + high) >> 1;
4443 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
4444 rc = cmp(key, &nodekey);
4445 DPRINTF(("found leaf index %u [%s], rc = %i",
4446 i, DKEY(&nodekey), rc));
4455 while (low <= high) {
4456 i = (low + high) >> 1;
4458 node = NODEPTR(mp, i);
4459 nodekey.mv_size = NODEKSZ(node);
4460 nodekey.mv_data = NODEKEY(node);
4462 rc = cmp(key, &nodekey);
4465 DPRINTF(("found leaf index %u [%s], rc = %i",
4466 i, DKEY(&nodekey), rc));
4468 DPRINTF(("found branch index %u [%s -> %"Z"u], rc = %i",
4469 i, DKEY(&nodekey), NODEPGNO(node), rc));
4480 if (rc > 0) { /* Found entry is less than the key. */
4481 i++; /* Skip to get the smallest entry larger than key. */
4483 node = NODEPTR(mp, i);
4486 *exactp = (rc == 0);
4487 /* store the key index */
4488 mc->mc_ki[mc->mc_top] = i;
4490 /* There is no entry larger or equal to the key. */
4493 /* nodeptr is fake for LEAF2 */
4499 mdb_cursor_adjust(MDB_cursor *mc, func)
4503 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4504 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
4511 /** Pop a page off the top of the cursor's stack. */
4513 mdb_cursor_pop(MDB_cursor *mc)
4517 MDB_page *top = mc->mc_pg[mc->mc_top];
4523 DPRINTF(("popped page %"Z"u off db %d cursor %p", top->mp_pgno,
4524 DDBI(mc), (void *) mc));
4528 /** Push a page onto the top of the cursor's stack. */
4530 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
4532 DPRINTF(("pushing page %"Z"u on db %d cursor %p", mp->mp_pgno,
4533 DDBI(mc), (void *) mc));
4535 if (mc->mc_snum >= CURSOR_STACK) {
4536 assert(mc->mc_snum < CURSOR_STACK);
4537 return MDB_CURSOR_FULL;
4540 mc->mc_top = mc->mc_snum++;
4541 mc->mc_pg[mc->mc_top] = mp;
4542 mc->mc_ki[mc->mc_top] = 0;
4547 /** Find the address of the page corresponding to a given page number.
4548 * @param[in] txn the transaction for this access.
4549 * @param[in] pgno the page number for the page to retrieve.
4550 * @param[out] ret address of a pointer where the page's address will be stored.
4551 * @param[out] lvl dirty_list inheritance level of found page. 1=current txn, 0=mapped page.
4552 * @return 0 on success, non-zero on failure.
4555 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret, int *lvl)
4557 MDB_env *env = txn->mt_env;
4561 if (!((txn->mt_flags & MDB_TXN_RDONLY) | (env->me_flags & MDB_WRITEMAP))) {
4565 MDB_ID2L dl = tx2->mt_u.dirty_list;
4567 /* Spilled pages were dirtied in this txn and flushed
4568 * because the dirty list got full. Bring this page
4569 * back in from the map (but don't unspill it here,
4570 * leave that unless page_touch happens again).
4572 if (tx2->mt_spill_pgs) {
4573 MDB_ID pn = pgno << 1;
4574 x = mdb_midl_search(tx2->mt_spill_pgs, pn);
4575 if (x <= tx2->mt_spill_pgs[0] && tx2->mt_spill_pgs[x] == pn) {
4576 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
4581 unsigned x = mdb_mid2l_search(dl, pgno);
4582 if (x <= dl[0].mid && dl[x].mid == pgno) {
4588 } while ((tx2 = tx2->mt_parent) != NULL);
4591 if (pgno < txn->mt_next_pgno) {
4593 p = (MDB_page *)(env->me_map + env->me_psize * pgno);
4595 DPRINTF(("page %"Z"u not found", pgno));
4597 return MDB_PAGE_NOTFOUND;
4607 /** Finish #mdb_page_search() / #mdb_page_search_lowest().
4608 * The cursor is at the root page, set up the rest of it.
4611 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int flags)
4613 MDB_page *mp = mc->mc_pg[mc->mc_top];
4617 while (IS_BRANCH(mp)) {
4621 DPRINTF(("branch page %"Z"u has %u keys", mp->mp_pgno, NUMKEYS(mp)));
4622 assert(NUMKEYS(mp) > 1);
4623 DPRINTF(("found index 0 to page %"Z"u", NODEPGNO(NODEPTR(mp, 0))));
4625 if (flags & (MDB_PS_FIRST|MDB_PS_LAST)) {
4627 if (flags & MDB_PS_LAST)
4628 i = NUMKEYS(mp) - 1;
4631 node = mdb_node_search(mc, key, &exact);
4633 i = NUMKEYS(mp) - 1;
4635 i = mc->mc_ki[mc->mc_top];
4641 DPRINTF(("following index %u for key [%s]", i, DKEY(key)));
4644 assert(i < NUMKEYS(mp));
4645 node = NODEPTR(mp, i);
4647 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4650 mc->mc_ki[mc->mc_top] = i;
4651 if ((rc = mdb_cursor_push(mc, mp)))
4654 if (flags & MDB_PS_MODIFY) {
4655 if ((rc = mdb_page_touch(mc)) != 0)
4657 mp = mc->mc_pg[mc->mc_top];
4662 DPRINTF(("internal error, index points to a %02X page!?",
4664 return MDB_CORRUPTED;
4667 DPRINTF(("found leaf page %"Z"u for key [%s]", mp->mp_pgno,
4668 key ? DKEY(key) : "null"));
4669 mc->mc_flags |= C_INITIALIZED;
4670 mc->mc_flags &= ~C_EOF;
4675 /** Search for the lowest key under the current branch page.
4676 * This just bypasses a NUMKEYS check in the current page
4677 * before calling mdb_page_search_root(), because the callers
4678 * are all in situations where the current page is known to
4682 mdb_page_search_lowest(MDB_cursor *mc)
4684 MDB_page *mp = mc->mc_pg[mc->mc_top];
4685 MDB_node *node = NODEPTR(mp, 0);
4688 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp, NULL)) != 0)
4691 mc->mc_ki[mc->mc_top] = 0;
4692 if ((rc = mdb_cursor_push(mc, mp)))
4694 return mdb_page_search_root(mc, NULL, MDB_PS_FIRST);
4697 /** Search for the page a given key should be in.
4698 * Push it and its parent pages on the cursor stack.
4699 * @param[in,out] mc the cursor for this operation.
4700 * @param[in] key the key to search for, or NULL for first/last page.
4701 * @param[in] flags If MDB_PS_MODIFY is set, visited pages in the DB
4702 * are touched (updated with new page numbers).
4703 * If MDB_PS_FIRST or MDB_PS_LAST is set, find first or last leaf.
4704 * This is used by #mdb_cursor_first() and #mdb_cursor_last().
4705 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
4706 * @return 0 on success, non-zero on failure.
4709 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
4714 /* Make sure the txn is still viable, then find the root from
4715 * the txn's db table and set it as the root of the cursor's stack.
4717 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
4718 DPUTS("transaction has failed, must abort");
4721 /* Make sure we're using an up-to-date root */
4722 if (*mc->mc_dbflag & DB_STALE) {
4724 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
4725 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, 0);
4732 MDB_node *leaf = mdb_node_search(&mc2,
4733 &mc->mc_dbx->md_name, &exact);
4735 return MDB_NOTFOUND;
4736 rc = mdb_node_read(mc->mc_txn, leaf, &data);
4739 memcpy(&flags, ((char *) data.mv_data + offsetof(MDB_db, md_flags)),
4741 /* The txn may not know this DBI, or another process may
4742 * have dropped and recreated the DB with other flags.
4744 if ((mc->mc_db->md_flags & PERSISTENT_FLAGS) != flags)
4745 return MDB_INCOMPATIBLE;
4746 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
4748 *mc->mc_dbflag &= ~DB_STALE;
4750 root = mc->mc_db->md_root;
4752 if (root == P_INVALID) { /* Tree is empty. */
4753 DPUTS("tree is empty");
4754 return MDB_NOTFOUND;
4759 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
4760 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0], NULL)) != 0)
4766 DPRINTF(("db %d root page %"Z"u has flags 0x%X",
4767 DDBI(mc), root, mc->mc_pg[0]->mp_flags));
4769 if (flags & MDB_PS_MODIFY) {
4770 if ((rc = mdb_page_touch(mc)))
4774 if (flags & MDB_PS_ROOTONLY)
4777 return mdb_page_search_root(mc, key, flags);
4781 mdb_ovpage_free(MDB_cursor *mc, MDB_page *mp)
4783 MDB_txn *txn = mc->mc_txn;
4784 pgno_t pg = mp->mp_pgno;
4785 unsigned x = 0, ovpages = mp->mp_pages;
4786 MDB_env *env = txn->mt_env;
4787 MDB_IDL sl = txn->mt_spill_pgs;
4788 MDB_ID pn = pg << 1;
4791 DPRINTF(("free ov page %"Z"u (%d)", pg, ovpages));
4792 /* If the page is dirty or on the spill list we just acquired it,
4793 * so we should give it back to our current free list, if any.
4794 * Otherwise put it onto the list of pages we freed in this txn.
4796 * Won't create me_pghead: me_pglast must be inited along with it.
4797 * Unsupported in nested txns: They would need to hide the page
4798 * range in ancestor txns' dirty and spilled lists.
4800 if (env->me_pghead &&
4802 ((mp->mp_flags & P_DIRTY) ||
4803 (sl && (x = mdb_midl_search(sl, pn)) <= sl[0] && sl[x] == pn)))
4807 MDB_ID2 *dl, ix, iy;
4808 rc = mdb_midl_need(&env->me_pghead, ovpages);
4811 if (!(mp->mp_flags & P_DIRTY)) {
4812 /* This page is no longer spilled */
4819 /* Remove from dirty list */
4820 dl = txn->mt_u.dirty_list;
4822 for (ix = dl[x]; ix.mptr != mp; ix = iy) {
4830 dl[j] = ix; /* Unsorted. OK when MDB_TXN_ERROR. */
4831 txn->mt_flags |= MDB_TXN_ERROR;
4832 return MDB_CORRUPTED;
4835 if (!(env->me_flags & MDB_WRITEMAP))
4836 mdb_dpage_free(env, mp);
4838 /* Insert in me_pghead */
4839 mop = env->me_pghead;
4840 j = mop[0] + ovpages;
4841 for (i = mop[0]; i && mop[i] < pg; i--)
4847 rc = mdb_midl_append_range(&txn->mt_free_pgs, pg, ovpages);
4851 mc->mc_db->md_overflow_pages -= ovpages;
4855 /** Return the data associated with a given node.
4856 * @param[in] txn The transaction for this operation.
4857 * @param[in] leaf The node being read.
4858 * @param[out] data Updated to point to the node's data.
4859 * @return 0 on success, non-zero on failure.
4862 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
4864 MDB_page *omp; /* overflow page */
4868 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
4869 data->mv_size = NODEDSZ(leaf);
4870 data->mv_data = NODEDATA(leaf);
4874 /* Read overflow data.
4876 data->mv_size = NODEDSZ(leaf);
4877 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
4878 if ((rc = mdb_page_get(txn, pgno, &omp, NULL)) != 0) {
4879 DPRINTF(("read overflow page %"Z"u failed", pgno));
4882 data->mv_data = METADATA(omp);
4888 mdb_get(MDB_txn *txn, MDB_dbi dbi,
4889 MDB_val *key, MDB_val *data)
4898 DPRINTF(("===> get db %u key [%s]", dbi, DKEY(key)));
4900 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
4903 if (txn->mt_flags & MDB_TXN_ERROR)
4906 if (key->mv_size > MDB_MAXKEYSIZE) {
4907 return MDB_BAD_VALSIZE;
4910 mdb_cursor_init(&mc, txn, dbi, &mx);
4911 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
4914 /** Find a sibling for a page.
4915 * Replaces the page at the top of the cursor's stack with the
4916 * specified sibling, if one exists.
4917 * @param[in] mc The cursor for this operation.
4918 * @param[in] move_right Non-zero if the right sibling is requested,
4919 * otherwise the left sibling.
4920 * @return 0 on success, non-zero on failure.
4923 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
4929 if (mc->mc_snum < 2) {
4930 return MDB_NOTFOUND; /* root has no siblings */
4934 DPRINTF(("parent page is page %"Z"u, index %u",
4935 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]));
4937 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
4938 : (mc->mc_ki[mc->mc_top] == 0)) {
4939 DPRINTF(("no more keys left, moving to %s sibling",
4940 move_right ? "right" : "left"));
4941 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS) {
4942 /* undo cursor_pop before returning */
4949 mc->mc_ki[mc->mc_top]++;
4951 mc->mc_ki[mc->mc_top]--;
4952 DPRINTF(("just moving to %s index key %u",
4953 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]));
4955 assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
4957 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4958 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp, NULL)) != 0) {
4959 /* mc will be inconsistent if caller does mc_snum++ as above */
4960 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
4964 mdb_cursor_push(mc, mp);
4966 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
4971 /** Move the cursor to the next data item. */
4973 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
4979 if (mc->mc_flags & C_EOF) {
4980 return MDB_NOTFOUND;
4983 assert(mc->mc_flags & C_INITIALIZED);
4985 mp = mc->mc_pg[mc->mc_top];
4987 if (mc->mc_db->md_flags & MDB_DUPSORT) {
4988 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
4989 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4990 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
4991 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
4992 if (op != MDB_NEXT || rc != MDB_NOTFOUND) {
4993 if (rc == MDB_SUCCESS)
4994 MDB_GET_KEY(leaf, key);
4999 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5000 if (op == MDB_NEXT_DUP)
5001 return MDB_NOTFOUND;
5005 DPRINTF(("cursor_next: top page is %"Z"u in cursor %p", mp->mp_pgno, (void *) mc));
5006 if (mc->mc_flags & C_DEL)
5009 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
5010 DPUTS("=====> move to next sibling page");
5011 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS) {
5012 mc->mc_flags |= C_EOF;
5015 mp = mc->mc_pg[mc->mc_top];
5016 DPRINTF(("next page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5018 mc->mc_ki[mc->mc_top]++;
5021 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5022 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5025 key->mv_size = mc->mc_db->md_pad;
5026 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5030 assert(IS_LEAF(mp));
5031 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5033 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5034 mdb_xcursor_init1(mc, leaf);
5037 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5040 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5041 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5042 if (rc != MDB_SUCCESS)
5047 MDB_GET_KEY(leaf, key);
5051 /** Move the cursor to the previous data item. */
5053 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
5059 assert(mc->mc_flags & C_INITIALIZED);
5061 mp = mc->mc_pg[mc->mc_top];
5063 if (mc->mc_db->md_flags & MDB_DUPSORT) {
5064 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5065 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5066 if (op == MDB_PREV || op == MDB_PREV_DUP) {
5067 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
5068 if (op != MDB_PREV || rc != MDB_NOTFOUND) {
5069 if (rc == MDB_SUCCESS)
5070 MDB_GET_KEY(leaf, key);
5074 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5075 if (op == MDB_PREV_DUP)
5076 return MDB_NOTFOUND;
5081 DPRINTF(("cursor_prev: top page is %"Z"u in cursor %p", mp->mp_pgno, (void *) mc));
5083 if (mc->mc_ki[mc->mc_top] == 0) {
5084 DPUTS("=====> move to prev sibling page");
5085 if ((rc = mdb_cursor_sibling(mc, 0)) != MDB_SUCCESS) {
5088 mp = mc->mc_pg[mc->mc_top];
5089 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
5090 DPRINTF(("prev page is %"Z"u, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]));
5092 mc->mc_ki[mc->mc_top]--;
5094 mc->mc_flags &= ~C_EOF;
5096 DPRINTF(("==> cursor points to page %"Z"u with %u keys, key index %u",
5097 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]));
5100 key->mv_size = mc->mc_db->md_pad;
5101 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5105 assert(IS_LEAF(mp));
5106 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5108 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5109 mdb_xcursor_init1(mc, leaf);
5112 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5115 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5116 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5117 if (rc != MDB_SUCCESS)
5122 MDB_GET_KEY(leaf, key);
5126 /** Set the cursor on a specific data item. */
5128 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5129 MDB_cursor_op op, int *exactp)
5133 MDB_node *leaf = NULL;
5138 if (key->mv_size == 0)
5139 return MDB_BAD_VALSIZE;
5142 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5144 /* See if we're already on the right page */
5145 if (mc->mc_flags & C_INITIALIZED) {
5148 mp = mc->mc_pg[mc->mc_top];
5150 mc->mc_ki[mc->mc_top] = 0;
5151 return MDB_NOTFOUND;
5153 if (mp->mp_flags & P_LEAF2) {
5154 nodekey.mv_size = mc->mc_db->md_pad;
5155 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
5157 leaf = NODEPTR(mp, 0);
5158 MDB_GET_KEY2(leaf, nodekey);
5160 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5162 /* Probably happens rarely, but first node on the page
5163 * was the one we wanted.
5165 mc->mc_ki[mc->mc_top] = 0;
5172 unsigned int nkeys = NUMKEYS(mp);
5174 if (mp->mp_flags & P_LEAF2) {
5175 nodekey.mv_data = LEAF2KEY(mp,
5176 nkeys-1, nodekey.mv_size);
5178 leaf = NODEPTR(mp, nkeys-1);
5179 MDB_GET_KEY2(leaf, nodekey);
5181 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5183 /* last node was the one we wanted */
5184 mc->mc_ki[mc->mc_top] = nkeys-1;
5190 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
5191 /* This is definitely the right page, skip search_page */
5192 if (mp->mp_flags & P_LEAF2) {
5193 nodekey.mv_data = LEAF2KEY(mp,
5194 mc->mc_ki[mc->mc_top], nodekey.mv_size);
5196 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5197 MDB_GET_KEY2(leaf, nodekey);
5199 rc = mc->mc_dbx->md_cmp(key, &nodekey);
5201 /* current node was the one we wanted */
5211 /* If any parents have right-sibs, search.
5212 * Otherwise, there's nothing further.
5214 for (i=0; i<mc->mc_top; i++)
5216 NUMKEYS(mc->mc_pg[i])-1)
5218 if (i == mc->mc_top) {
5219 /* There are no other pages */
5220 mc->mc_ki[mc->mc_top] = nkeys;
5221 return MDB_NOTFOUND;
5225 /* There are no other pages */
5226 mc->mc_ki[mc->mc_top] = 0;
5227 if (op == MDB_SET_RANGE) {
5231 return MDB_NOTFOUND;
5235 rc = mdb_page_search(mc, key, 0);
5236 if (rc != MDB_SUCCESS)
5239 mp = mc->mc_pg[mc->mc_top];
5240 assert(IS_LEAF(mp));
5243 leaf = mdb_node_search(mc, key, exactp);
5244 if (exactp != NULL && !*exactp) {
5245 /* MDB_SET specified and not an exact match. */
5246 return MDB_NOTFOUND;
5250 DPUTS("===> inexact leaf not found, goto sibling");
5251 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
5252 return rc; /* no entries matched */
5253 mp = mc->mc_pg[mc->mc_top];
5254 assert(IS_LEAF(mp));
5255 leaf = NODEPTR(mp, 0);
5259 mc->mc_flags |= C_INITIALIZED;
5260 mc->mc_flags &= ~C_EOF;
5263 key->mv_size = mc->mc_db->md_pad;
5264 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5268 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5269 mdb_xcursor_init1(mc, leaf);
5272 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5273 if (op == MDB_SET || op == MDB_SET_KEY || op == MDB_SET_RANGE) {
5274 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5277 if (op == MDB_GET_BOTH) {
5283 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
5284 if (rc != MDB_SUCCESS)
5287 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
5289 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
5291 rc = mc->mc_dbx->md_dcmp(data, &d2);
5293 if (op == MDB_GET_BOTH || rc > 0)
5294 return MDB_NOTFOUND;
5300 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5301 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5306 /* The key already matches in all other cases */
5307 if (op == MDB_SET_RANGE || op == MDB_SET_KEY)
5308 MDB_GET_KEY(leaf, key);
5309 DPRINTF(("==> cursor placed on key [%s]", DKEY(key)));
5314 /** Move the cursor to the first item in the database. */
5316 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5322 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5324 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5325 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
5326 if (rc != MDB_SUCCESS)
5329 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
5331 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
5332 mc->mc_flags |= C_INITIALIZED;
5333 mc->mc_flags &= ~C_EOF;
5335 mc->mc_ki[mc->mc_top] = 0;
5337 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5338 key->mv_size = mc->mc_db->md_pad;
5339 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
5344 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5345 mdb_xcursor_init1(mc, leaf);
5346 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
5350 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5354 MDB_GET_KEY(leaf, key);
5358 /** Move the cursor to the last item in the database. */
5360 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
5366 mc->mc_xcursor->mx_cursor.mc_flags &= ~(C_INITIALIZED|C_EOF);
5368 if (!(mc->mc_flags & C_EOF)) {
5370 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
5371 rc = mdb_page_search(mc, NULL, MDB_PS_LAST);
5372 if (rc != MDB_SUCCESS)
5375 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
5378 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
5379 mc->mc_flags |= C_INITIALIZED|C_EOF;
5380 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5382 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5383 key->mv_size = mc->mc_db->md_pad;
5384 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
5389 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5390 mdb_xcursor_init1(mc, leaf);
5391 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
5395 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
5400 MDB_GET_KEY(leaf, key);
5405 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5410 int (*mfunc)(MDB_cursor *mc, MDB_val *key, MDB_val *data);
5414 if (mc->mc_txn->mt_flags & MDB_TXN_ERROR)
5418 case MDB_GET_CURRENT:
5419 if (!(mc->mc_flags & C_INITIALIZED)) {
5422 MDB_page *mp = mc->mc_pg[mc->mc_top];
5424 mc->mc_ki[mc->mc_top] = 0;
5430 key->mv_size = mc->mc_db->md_pad;
5431 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
5433 MDB_node *leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
5434 MDB_GET_KEY(leaf, key);
5436 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5437 if (mc->mc_flags & C_DEL)
5438 mdb_xcursor_init1(mc, leaf);
5439 rc = mdb_cursor_get(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_GET_CURRENT);
5441 rc = mdb_node_read(mc->mc_txn, leaf, data);
5448 case MDB_GET_BOTH_RANGE:
5453 if (mc->mc_xcursor == NULL) {
5454 rc = MDB_INCOMPATIBLE;
5463 } else if (key->mv_size > MDB_MAXKEYSIZE) {
5464 rc = MDB_BAD_VALSIZE;
5465 } else if (op == MDB_SET_RANGE)
5466 rc = mdb_cursor_set(mc, key, data, op, NULL);
5468 rc = mdb_cursor_set(mc, key, data, op, &exact);
5470 case MDB_GET_MULTIPLE:
5471 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5475 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5476 rc = MDB_INCOMPATIBLE;
5480 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
5481 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
5484 case MDB_NEXT_MULTIPLE:
5489 if (!(mc->mc_db->md_flags & MDB_DUPFIXED)) {
5490 rc = MDB_INCOMPATIBLE;
5493 if (!(mc->mc_flags & C_INITIALIZED))
5494 rc = mdb_cursor_first(mc, key, data);
5496 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
5497 if (rc == MDB_SUCCESS) {
5498 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
5501 mx = &mc->mc_xcursor->mx_cursor;
5502 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
5504 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
5505 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
5513 case MDB_NEXT_NODUP:
5514 if (!(mc->mc_flags & C_INITIALIZED))
5515 rc = mdb_cursor_first(mc, key, data);
5517 rc = mdb_cursor_next(mc, key, data, op);
5521 case MDB_PREV_NODUP:
5522 if (!(mc->mc_flags & C_INITIALIZED)) {
5523 rc = mdb_cursor_last(mc, key, data);
5526 mc->mc_flags |= C_INITIALIZED;
5527 mc->mc_ki[mc->mc_top]++;
5529 rc = mdb_cursor_prev(mc, key, data, op);
5532 rc = mdb_cursor_first(mc, key, data);
5535 mfunc = mdb_cursor_first;
5537 if (data == NULL || !(mc->mc_flags & C_INITIALIZED)) {
5541 if (mc->mc_xcursor == NULL) {
5542 rc = MDB_INCOMPATIBLE;
5545 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
5549 rc = mfunc(&mc->mc_xcursor->mx_cursor, data, NULL);
5552 rc = mdb_cursor_last(mc, key, data);
5555 mfunc = mdb_cursor_last;
5558 DPRINTF(("unhandled/unimplemented cursor operation %u", op));
5563 if (mc->mc_flags & C_DEL)
5564 mc->mc_flags ^= C_DEL;
5569 /** Touch all the pages in the cursor stack. Set mc_top.
5570 * Makes sure all the pages are writable, before attempting a write operation.
5571 * @param[in] mc The cursor to operate on.
5574 mdb_cursor_touch(MDB_cursor *mc)
5576 int rc = MDB_SUCCESS;
5578 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
5581 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, &mcx);
5582 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
5585 *mc->mc_dbflag |= DB_DIRTY;
5590 rc = mdb_page_touch(mc);
5591 } while (!rc && ++(mc->mc_top) < mc->mc_snum);
5592 mc->mc_top = mc->mc_snum-1;
5597 /** Do not spill pages to disk if txn is getting full, may fail instead */
5598 #define MDB_NOSPILL 0x8000
5601 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
5604 enum { MDB_NO_ROOT = MDB_LAST_ERRCODE+10 }; /* internal code */
5605 MDB_node *leaf = NULL;
5606 MDB_val xdata, *rdata, dkey;
5609 int do_sub = 0, insert = 0;
5610 unsigned int mcount = 0, dcount = 0, nospill;
5614 char dbuf[MDB_MAXKEYSIZE+1];
5615 unsigned int nflags;
5618 /* Check this first so counter will always be zero on any
5621 if (flags & MDB_MULTIPLE) {
5622 dcount = data[1].mv_size;
5623 data[1].mv_size = 0;
5624 if (!F_ISSET(mc->mc_db->md_flags, MDB_DUPFIXED))
5625 return MDB_INCOMPATIBLE;
5628 nospill = flags & MDB_NOSPILL;
5629 flags &= ~MDB_NOSPILL;
5631 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
5632 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
5634 if (flags != MDB_CURRENT && (key->mv_size == 0 || key->mv_size > MDB_MAXKEYSIZE))
5635 return MDB_BAD_VALSIZE;
5637 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT) && data->mv_size > MDB_MAXKEYSIZE)
5638 return MDB_BAD_VALSIZE;
5640 #if SIZE_MAX > MAXDATASIZE
5641 if (data->mv_size > MAXDATASIZE)
5642 return MDB_BAD_VALSIZE;
5645 DPRINTF(("==> put db %d key [%s], size %"Z"u, data size %"Z"u",
5646 DDBI(mc), DKEY(key), key ? key->mv_size : 0, data->mv_size));
5650 if (flags == MDB_CURRENT) {
5651 if (!(mc->mc_flags & C_INITIALIZED))
5654 } else if (mc->mc_db->md_root == P_INVALID) {
5655 /* new database, cursor has nothing to point to */
5658 mc->mc_flags &= ~C_INITIALIZED;
5663 if (flags & MDB_APPEND) {
5665 rc = mdb_cursor_last(mc, &k2, &d2);
5667 rc = mc->mc_dbx->md_cmp(key, &k2);
5670 mc->mc_ki[mc->mc_top]++;
5672 /* new key is <= last key */
5677 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
5679 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
5680 DPRINTF(("duplicate key [%s]", DKEY(key)));
5682 return MDB_KEYEXIST;
5684 if (rc && rc != MDB_NOTFOUND)
5688 if (mc->mc_flags & C_DEL)
5689 mc->mc_flags ^= C_DEL;
5691 /* Cursor is positioned, check for room in the dirty list */
5693 if (flags & MDB_MULTIPLE) {
5695 xdata.mv_size = data->mv_size * dcount;
5699 if ((rc2 = mdb_page_spill(mc, key, rdata)))
5703 if (rc == MDB_NO_ROOT) {
5705 /* new database, write a root leaf page */
5706 DPUTS("allocating new root leaf page");
5707 if ((rc2 = mdb_page_new(mc, P_LEAF, 1, &np))) {
5710 mdb_cursor_push(mc, np);
5711 mc->mc_db->md_root = np->mp_pgno;
5712 mc->mc_db->md_depth++;
5713 *mc->mc_dbflag |= DB_DIRTY;
5714 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
5716 np->mp_flags |= P_LEAF2;
5717 mc->mc_flags |= C_INITIALIZED;
5719 /* make sure all cursor pages are writable */
5720 rc2 = mdb_cursor_touch(mc);
5725 /* The key already exists */
5726 if (rc == MDB_SUCCESS) {
5727 /* there's only a key anyway, so this is a no-op */
5728 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
5729 unsigned int ksize = mc->mc_db->md_pad;
5730 if (key->mv_size != ksize)
5731 return MDB_BAD_VALSIZE;
5732 if (flags == MDB_CURRENT) {
5733 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
5734 memcpy(ptr, key->mv_data, ksize);
5739 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5742 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
5743 /* Was a single item before, must convert now */
5745 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5746 /* Just overwrite the current item */
5747 if (flags == MDB_CURRENT)
5750 dkey.mv_size = NODEDSZ(leaf);
5751 dkey.mv_data = NODEDATA(leaf);
5752 #if UINT_MAX < SIZE_MAX
5753 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && dkey.mv_size == sizeof(size_t))
5754 #ifdef MISALIGNED_OK
5755 mc->mc_dbx->md_dcmp = mdb_cmp_long;
5757 mc->mc_dbx->md_dcmp = mdb_cmp_cint;
5760 /* if data matches, skip it */
5761 if (!mc->mc_dbx->md_dcmp(data, &dkey)) {
5762 if (flags & MDB_NODUPDATA)
5764 else if (flags & MDB_MULTIPLE)
5771 /* create a fake page for the dup items */
5772 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
5773 dkey.mv_data = dbuf;
5774 fp = (MDB_page *)&pbuf;
5775 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
5776 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
5777 fp->mp_lower = PAGEHDRSZ;
5778 fp->mp_upper = PAGEHDRSZ + dkey.mv_size + data->mv_size;
5779 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5780 fp->mp_flags |= P_LEAF2;
5781 fp->mp_pad = data->mv_size;
5782 fp->mp_upper += 2 * data->mv_size; /* leave space for 2 more */
5784 fp->mp_upper += 2 * sizeof(indx_t) + 2 * NODESIZE +
5785 (dkey.mv_size & 1) + (data->mv_size & 1);
5787 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5790 xdata.mv_size = fp->mp_upper;
5795 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
5796 /* See if we need to convert from fake page to subDB */
5798 unsigned int offset;
5802 fp = NODEDATA(leaf);
5803 if (flags == MDB_CURRENT) {
5805 fp->mp_flags |= P_DIRTY;
5806 COPY_PGNO(fp->mp_pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
5807 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
5811 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5812 offset = fp->mp_pad;
5813 if (SIZELEFT(fp) >= offset)
5815 offset *= 4; /* space for 4 more */
5817 offset = NODESIZE + sizeof(indx_t) + data->mv_size;
5819 offset += offset & 1;
5820 fp_flags = fp->mp_flags;
5821 if (NODESIZE + sizeof(indx_t) + NODEKSZ(leaf) + NODEDSZ(leaf) +
5822 offset >= mc->mc_txn->mt_env->me_nodemax) {
5823 /* yes, convert it */
5825 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5826 dummy.md_pad = fp->mp_pad;
5827 dummy.md_flags = MDB_DUPFIXED;
5828 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
5829 dummy.md_flags |= MDB_INTEGERKEY;
5832 dummy.md_branch_pages = 0;
5833 dummy.md_leaf_pages = 1;
5834 dummy.md_overflow_pages = 0;
5835 dummy.md_entries = NUMKEYS(fp);
5837 xdata.mv_size = sizeof(MDB_db);
5838 xdata.mv_data = &dummy;
5839 if ((rc = mdb_page_alloc(mc, 1, &mp)))
5841 offset = mc->mc_txn->mt_env->me_psize - NODEDSZ(leaf);
5842 flags |= F_DUPDATA|F_SUBDATA;
5843 dummy.md_root = mp->mp_pgno;
5844 fp_flags &= ~P_SUBP;
5846 /* no, just grow it */
5848 xdata.mv_size = NODEDSZ(leaf) + offset;
5849 xdata.mv_data = &pbuf;
5850 mp = (MDB_page *)&pbuf;
5851 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
5854 mp->mp_flags = fp_flags | P_DIRTY;
5855 mp->mp_pad = fp->mp_pad;
5856 mp->mp_lower = fp->mp_lower;
5857 mp->mp_upper = fp->mp_upper + offset;
5859 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
5861 nsize = NODEDSZ(leaf) - fp->mp_upper;
5862 memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper, nsize);
5863 for (i=0; i<NUMKEYS(fp); i++)
5864 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
5866 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5870 /* data is on sub-DB, just store it */
5871 flags |= F_DUPDATA|F_SUBDATA;
5875 /* overflow page overwrites need special handling */
5876 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5879 unsigned psize = mc->mc_txn->mt_env->me_psize;
5880 int level, ovpages, dpages = OVPAGES(data->mv_size, psize);
5882 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
5883 if ((rc2 = mdb_page_get(mc->mc_txn, pg, &omp, &level)) != 0)
5885 ovpages = omp->mp_pages;
5887 /* Is the ov page large enough? */
5888 if (ovpages >= dpages) {
5889 if (!(omp->mp_flags & P_DIRTY) &&
5890 (level || (mc->mc_txn->mt_env->me_flags & MDB_WRITEMAP)))
5892 rc = mdb_page_unspill(mc->mc_txn, omp, &omp);
5895 level = 0; /* dirty in this txn or clean */
5898 if (omp->mp_flags & P_DIRTY) {
5899 /* yes, overwrite it. Note in this case we don't
5900 * bother to try shrinking the page if the new data
5901 * is smaller than the overflow threshold.
5904 /* It is writable only in a parent txn */
5905 size_t sz = (size_t) psize * ovpages, off;
5906 MDB_page *np = mdb_page_malloc(mc->mc_txn, ovpages);
5912 mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &id2);
5913 if (!(flags & MDB_RESERVE)) {
5914 /* Copy end of page, adjusting alignment so
5915 * compiler may copy words instead of bytes.
5917 off = (PAGEHDRSZ + data->mv_size) & -sizeof(size_t);
5918 memcpy((size_t *)((char *)np + off),
5919 (size_t *)((char *)omp + off), sz - off);
5922 memcpy(np, omp, sz); /* Copy beginning of page */
5925 SETDSZ(leaf, data->mv_size);
5926 if (F_ISSET(flags, MDB_RESERVE))
5927 data->mv_data = METADATA(omp);
5929 memcpy(METADATA(omp), data->mv_data, data->mv_size);
5933 if ((rc2 = mdb_ovpage_free(mc, omp)) != MDB_SUCCESS)
5935 } else if (NODEDSZ(leaf) == data->mv_size) {
5936 /* same size, just replace it. Note that we could
5937 * also reuse this node if the new data is smaller,
5938 * but instead we opt to shrink the node in that case.
5940 if (F_ISSET(flags, MDB_RESERVE))
5941 data->mv_data = NODEDATA(leaf);
5942 else if (data->mv_size)
5943 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
5945 memcpy(NODEKEY(leaf), key->mv_data, key->mv_size);
5948 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
5949 mc->mc_db->md_entries--;
5951 DPRINTF(("inserting key at index %i", mc->mc_ki[mc->mc_top]));
5958 nflags = flags & NODE_ADD_FLAGS;
5959 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
5960 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
5961 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
5962 nflags &= ~MDB_APPEND;
5964 nflags |= MDB_SPLIT_REPLACE;
5965 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
5967 /* There is room already in this leaf page. */
5968 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
5969 if (rc == 0 && !do_sub && insert) {
5970 /* Adjust other cursors pointing to mp */
5971 MDB_cursor *m2, *m3;
5972 MDB_dbi dbi = mc->mc_dbi;
5973 unsigned i = mc->mc_top;
5974 MDB_page *mp = mc->mc_pg[i];
5976 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5977 if (mc->mc_flags & C_SUB)
5978 m3 = &m2->mc_xcursor->mx_cursor;
5981 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
5982 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
5989 if (rc != MDB_SUCCESS)
5990 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5992 /* Now store the actual data in the child DB. Note that we're
5993 * storing the user data in the keys field, so there are strict
5994 * size limits on dupdata. The actual data fields of the child
5995 * DB are all zero size.
6002 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6003 if (flags & MDB_CURRENT) {
6004 xflags = MDB_CURRENT|MDB_NOSPILL;
6006 mdb_xcursor_init1(mc, leaf);
6007 xflags = (flags & MDB_NODUPDATA) ?
6008 MDB_NOOVERWRITE|MDB_NOSPILL : MDB_NOSPILL;
6010 /* converted, write the original data first */
6012 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
6016 /* Adjust other cursors pointing to mp */
6018 unsigned i = mc->mc_top;
6019 MDB_page *mp = mc->mc_pg[i];
6021 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6022 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6023 if (!(m2->mc_flags & C_INITIALIZED)) continue;
6024 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
6025 mdb_xcursor_init1(m2, leaf);
6029 /* we've done our job */
6032 if (flags & MDB_APPENDDUP)
6033 xflags |= MDB_APPEND;
6034 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
6035 if (flags & F_SUBDATA) {
6036 void *db = NODEDATA(leaf);
6037 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6040 /* sub-writes might have failed so check rc again.
6041 * Don't increment count if we just replaced an existing item.
6043 if (!rc && !(flags & MDB_CURRENT))
6044 mc->mc_db->md_entries++;
6045 if (flags & MDB_MULTIPLE) {
6049 /* let caller know how many succeeded, if any */
6050 data[1].mv_size = mcount;
6051 if (mcount < dcount) {
6052 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
6053 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6060 /* If we succeeded and the key didn't exist before, make sure
6061 * the cursor is marked valid.
6064 mc->mc_flags |= C_INITIALIZED;
6069 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
6074 if (mc->mc_txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
6075 return (mc->mc_txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
6077 if (!(mc->mc_flags & C_INITIALIZED))
6080 if (!(flags & MDB_NOSPILL) && (rc = mdb_page_spill(mc, NULL, NULL)))
6083 rc = mdb_cursor_touch(mc);
6087 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6089 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6090 if (!(flags & MDB_NODUPDATA)) {
6091 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
6092 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6094 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, MDB_NOSPILL);
6095 /* If sub-DB still has entries, we're done */
6096 if (mc->mc_xcursor->mx_db.md_entries) {
6097 if (leaf->mn_flags & F_SUBDATA) {
6098 /* update subDB info */
6099 void *db = NODEDATA(leaf);
6100 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
6103 /* shrink fake page */
6104 mdb_node_shrink(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6105 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6106 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6107 /* fix other sub-DB cursors pointed at this fake page */
6108 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
6109 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
6110 if (m2->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top] &&
6111 m2->mc_ki[mc->mc_top] == mc->mc_ki[mc->mc_top])
6112 m2->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
6115 mc->mc_db->md_entries--;
6116 mc->mc_flags |= C_DEL;
6119 /* otherwise fall thru and delete the sub-DB */
6122 if (leaf->mn_flags & F_SUBDATA) {
6123 /* add all the child DB's pages to the free list */
6124 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6125 if (rc == MDB_SUCCESS) {
6126 mc->mc_db->md_entries -=
6127 mc->mc_xcursor->mx_db.md_entries;
6132 return mdb_cursor_del0(mc, leaf);
6135 /** Allocate and initialize new pages for a database.
6136 * @param[in] mc a cursor on the database being added to.
6137 * @param[in] flags flags defining what type of page is being allocated.
6138 * @param[in] num the number of pages to allocate. This is usually 1,
6139 * unless allocating overflow pages for a large record.
6140 * @param[out] mp Address of a page, or NULL on failure.
6141 * @return 0 on success, non-zero on failure.
6144 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num, MDB_page **mp)
6149 if ((rc = mdb_page_alloc(mc, num, &np)))
6151 DPRINTF(("allocated new mpage %"Z"u, page size %u",
6152 np->mp_pgno, mc->mc_txn->mt_env->me_psize));
6153 np->mp_flags = flags | P_DIRTY;
6154 np->mp_lower = PAGEHDRSZ;
6155 np->mp_upper = mc->mc_txn->mt_env->me_psize;
6158 mc->mc_db->md_branch_pages++;
6159 else if (IS_LEAF(np))
6160 mc->mc_db->md_leaf_pages++;
6161 else if (IS_OVERFLOW(np)) {
6162 mc->mc_db->md_overflow_pages += num;
6170 /** Calculate the size of a leaf node.
6171 * The size depends on the environment's page size; if a data item
6172 * is too large it will be put onto an overflow page and the node
6173 * size will only include the key and not the data. Sizes are always
6174 * rounded up to an even number of bytes, to guarantee 2-byte alignment
6175 * of the #MDB_node headers.
6176 * @param[in] env The environment handle.
6177 * @param[in] key The key for the node.
6178 * @param[in] data The data for the node.
6179 * @return The number of bytes needed to store the node.
6182 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
6186 sz = LEAFSIZE(key, data);
6187 if (sz >= env->me_nodemax) {
6188 /* put on overflow page */
6189 sz -= data->mv_size - sizeof(pgno_t);
6193 return sz + sizeof(indx_t);
6196 /** Calculate the size of a branch node.
6197 * The size should depend on the environment's page size but since
6198 * we currently don't support spilling large keys onto overflow
6199 * pages, it's simply the size of the #MDB_node header plus the
6200 * size of the key. Sizes are always rounded up to an even number
6201 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
6202 * @param[in] env The environment handle.
6203 * @param[in] key The key for the node.
6204 * @return The number of bytes needed to store the node.
6207 mdb_branch_size(MDB_env *env, MDB_val *key)
6212 if (sz >= env->me_nodemax) {
6213 /* put on overflow page */
6214 /* not implemented */
6215 /* sz -= key->size - sizeof(pgno_t); */
6218 return sz + sizeof(indx_t);
6221 /** Add a node to the page pointed to by the cursor.
6222 * @param[in] mc The cursor for this operation.
6223 * @param[in] indx The index on the page where the new node should be added.
6224 * @param[in] key The key for the new node.
6225 * @param[in] data The data for the new node, if any.
6226 * @param[in] pgno The page number, if adding a branch node.
6227 * @param[in] flags Flags for the node.
6228 * @return 0 on success, non-zero on failure. Possible errors are:
6230 * <li>ENOMEM - failed to allocate overflow pages for the node.
6231 * <li>MDB_PAGE_FULL - there is insufficient room in the page. This error
6232 * should never happen since all callers already calculate the
6233 * page's free space before calling this function.
6237 mdb_node_add(MDB_cursor *mc, indx_t indx,
6238 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
6241 size_t node_size = NODESIZE;
6245 MDB_page *mp = mc->mc_pg[mc->mc_top];
6246 MDB_page *ofp = NULL; /* overflow page */
6249 assert(mp->mp_upper >= mp->mp_lower);
6251 DPRINTF(("add to %s %spage %"Z"u index %i, data size %"Z"u key size %"Z"u [%s]",
6252 IS_LEAF(mp) ? "leaf" : "branch",
6253 IS_SUBP(mp) ? "sub-" : "",
6254 mp->mp_pgno, indx, data ? data->mv_size : 0,
6255 key ? key->mv_size : 0, key ? DKEY(key) : "null"));
6258 /* Move higher keys up one slot. */
6259 int ksize = mc->mc_db->md_pad, dif;
6260 char *ptr = LEAF2KEY(mp, indx, ksize);
6261 dif = NUMKEYS(mp) - indx;
6263 memmove(ptr+ksize, ptr, dif*ksize);
6264 /* insert new key */
6265 memcpy(ptr, key->mv_data, ksize);
6267 /* Just using these for counting */
6268 mp->mp_lower += sizeof(indx_t);
6269 mp->mp_upper -= ksize - sizeof(indx_t);
6273 room = (ssize_t)SIZELEFT(mp) - (ssize_t)sizeof(indx_t);
6275 node_size += key->mv_size;
6278 if (F_ISSET(flags, F_BIGDATA)) {
6279 /* Data already on overflow page. */
6280 node_size += sizeof(pgno_t);
6281 } else if (node_size + data->mv_size >= mc->mc_txn->mt_env->me_nodemax) {
6282 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
6284 /* Put data on overflow page. */
6285 DPRINTF(("data size is %"Z"u, node would be %"Z"u, put data on overflow page",
6286 data->mv_size, node_size+data->mv_size));
6287 node_size += sizeof(pgno_t) + (node_size & 1);
6288 if ((ssize_t)node_size > room)
6290 if ((rc = mdb_page_new(mc, P_OVERFLOW, ovpages, &ofp)))
6292 DPRINTF(("allocated overflow page %"Z"u", ofp->mp_pgno));
6296 node_size += data->mv_size;
6299 node_size += node_size & 1;
6300 if ((ssize_t)node_size > room)
6304 /* Move higher pointers up one slot. */
6305 for (i = NUMKEYS(mp); i > indx; i--)
6306 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
6308 /* Adjust free space offsets. */
6309 ofs = mp->mp_upper - node_size;
6310 assert(ofs >= mp->mp_lower + sizeof(indx_t));
6311 mp->mp_ptrs[indx] = ofs;
6313 mp->mp_lower += sizeof(indx_t);
6315 /* Write the node data. */
6316 node = NODEPTR(mp, indx);
6317 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
6318 node->mn_flags = flags;
6320 SETDSZ(node,data->mv_size);
6325 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6330 if (F_ISSET(flags, F_BIGDATA))
6331 memcpy(node->mn_data + key->mv_size, data->mv_data,
6333 else if (F_ISSET(flags, MDB_RESERVE))
6334 data->mv_data = node->mn_data + key->mv_size;
6336 memcpy(node->mn_data + key->mv_size, data->mv_data,
6339 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
6341 if (F_ISSET(flags, MDB_RESERVE))
6342 data->mv_data = METADATA(ofp);
6344 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
6351 DPRINTF(("not enough room in page %"Z"u, got %u ptrs",
6352 mp->mp_pgno, NUMKEYS(mp)));
6353 DPRINTF(("upper-lower = %u - %u = %"Z"d", mp->mp_upper,mp->mp_lower,room));
6354 DPRINTF(("node size = %"Z"u", node_size));
6355 return MDB_PAGE_FULL;
6358 /** Delete the specified node from a page.
6359 * @param[in] mp The page to operate on.
6360 * @param[in] indx The index of the node to delete.
6361 * @param[in] ksize The size of a node. Only used if the page is
6362 * part of a #MDB_DUPFIXED database.
6365 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
6368 indx_t i, j, numkeys, ptr;
6375 COPY_PGNO(pgno, mp->mp_pgno);
6376 DPRINTF(("delete node %u on %s page %"Z"u", indx,
6377 IS_LEAF(mp) ? "leaf" : "branch", pgno));
6380 assert(indx < NUMKEYS(mp));
6383 int x = NUMKEYS(mp) - 1 - indx;
6384 base = LEAF2KEY(mp, indx, ksize);
6386 memmove(base, base + ksize, x * ksize);
6387 mp->mp_lower -= sizeof(indx_t);
6388 mp->mp_upper += ksize - sizeof(indx_t);
6392 node = NODEPTR(mp, indx);
6393 sz = NODESIZE + node->mn_ksize;
6395 if (F_ISSET(node->mn_flags, F_BIGDATA))
6396 sz += sizeof(pgno_t);
6398 sz += NODEDSZ(node);
6402 ptr = mp->mp_ptrs[indx];
6403 numkeys = NUMKEYS(mp);
6404 for (i = j = 0; i < numkeys; i++) {
6406 mp->mp_ptrs[j] = mp->mp_ptrs[i];
6407 if (mp->mp_ptrs[i] < ptr)
6408 mp->mp_ptrs[j] += sz;
6413 base = (char *)mp + mp->mp_upper;
6414 memmove(base + sz, base, ptr - mp->mp_upper);
6416 mp->mp_lower -= sizeof(indx_t);
6420 /** Compact the main page after deleting a node on a subpage.
6421 * @param[in] mp The main page to operate on.
6422 * @param[in] indx The index of the subpage on the main page.
6425 mdb_node_shrink(MDB_page *mp, indx_t indx)
6432 indx_t i, numkeys, ptr;
6434 node = NODEPTR(mp, indx);
6435 sp = (MDB_page *)NODEDATA(node);
6436 osize = NODEDSZ(node);
6438 delta = sp->mp_upper - sp->mp_lower;
6439 SETDSZ(node, osize - delta);
6440 xp = (MDB_page *)((char *)sp + delta);
6442 /* shift subpage upward */
6444 nsize = NUMKEYS(sp) * sp->mp_pad;
6445 memmove(METADATA(xp), METADATA(sp), nsize);
6448 nsize = osize - sp->mp_upper;
6449 numkeys = NUMKEYS(sp);
6450 for (i=numkeys-1; i>=0; i--)
6451 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
6453 xp->mp_upper = sp->mp_lower;
6454 xp->mp_lower = sp->mp_lower;
6455 xp->mp_flags = sp->mp_flags;
6456 xp->mp_pad = sp->mp_pad;
6457 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
6459 /* shift lower nodes upward */
6460 ptr = mp->mp_ptrs[indx];
6461 numkeys = NUMKEYS(mp);
6462 for (i = 0; i < numkeys; i++) {
6463 if (mp->mp_ptrs[i] <= ptr)
6464 mp->mp_ptrs[i] += delta;
6467 base = (char *)mp + mp->mp_upper;
6468 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
6469 mp->mp_upper += delta;
6472 /** Initial setup of a sorted-dups cursor.
6473 * Sorted duplicates are implemented as a sub-database for the given key.
6474 * The duplicate data items are actually keys of the sub-database.
6475 * Operations on the duplicate data items are performed using a sub-cursor
6476 * initialized when the sub-database is first accessed. This function does
6477 * the preliminary setup of the sub-cursor, filling in the fields that
6478 * depend only on the parent DB.
6479 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6482 mdb_xcursor_init0(MDB_cursor *mc)
6484 MDB_xcursor *mx = mc->mc_xcursor;
6486 mx->mx_cursor.mc_xcursor = NULL;
6487 mx->mx_cursor.mc_txn = mc->mc_txn;
6488 mx->mx_cursor.mc_db = &mx->mx_db;
6489 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
6490 mx->mx_cursor.mc_dbi = mc->mc_dbi;
6491 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
6492 mx->mx_cursor.mc_snum = 0;
6493 mx->mx_cursor.mc_top = 0;
6494 mx->mx_cursor.mc_flags = C_SUB;
6495 mx->mx_dbx.md_name.mv_size = 0;
6496 mx->mx_dbx.md_name.mv_data = NULL;
6497 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
6498 mx->mx_dbx.md_dcmp = NULL;
6499 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
6502 /** Final setup of a sorted-dups cursor.
6503 * Sets up the fields that depend on the data from the main cursor.
6504 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
6505 * @param[in] node The data containing the #MDB_db record for the
6506 * sorted-dup database.
6509 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
6511 MDB_xcursor *mx = mc->mc_xcursor;
6513 if (node->mn_flags & F_SUBDATA) {
6514 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
6515 mx->mx_cursor.mc_pg[0] = 0;
6516 mx->mx_cursor.mc_snum = 0;
6517 mx->mx_cursor.mc_top = 0;
6518 mx->mx_cursor.mc_flags = C_SUB;
6520 MDB_page *fp = NODEDATA(node);
6521 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
6522 mx->mx_db.md_flags = 0;
6523 mx->mx_db.md_depth = 1;
6524 mx->mx_db.md_branch_pages = 0;
6525 mx->mx_db.md_leaf_pages = 1;
6526 mx->mx_db.md_overflow_pages = 0;
6527 mx->mx_db.md_entries = NUMKEYS(fp);
6528 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
6529 mx->mx_cursor.mc_snum = 1;
6530 mx->mx_cursor.mc_top = 0;
6531 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
6532 mx->mx_cursor.mc_pg[0] = fp;
6533 mx->mx_cursor.mc_ki[0] = 0;
6534 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
6535 mx->mx_db.md_flags = MDB_DUPFIXED;
6536 mx->mx_db.md_pad = fp->mp_pad;
6537 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
6538 mx->mx_db.md_flags |= MDB_INTEGERKEY;
6541 DPRINTF(("Sub-db -%u root page %"Z"u", mx->mx_cursor.mc_dbi,
6542 mx->mx_db.md_root));
6543 mx->mx_dbflag = DB_VALID|DB_DIRTY; /* DB_DIRTY guides mdb_cursor_touch */
6544 #if UINT_MAX < SIZE_MAX
6545 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
6546 #ifdef MISALIGNED_OK
6547 mx->mx_dbx.md_cmp = mdb_cmp_long;
6549 mx->mx_dbx.md_cmp = mdb_cmp_cint;
6554 /** Initialize a cursor for a given transaction and database. */
6556 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
6559 mc->mc_backup = NULL;
6562 mc->mc_db = &txn->mt_dbs[dbi];
6563 mc->mc_dbx = &txn->mt_dbxs[dbi];
6564 mc->mc_dbflag = &txn->mt_dbflags[dbi];
6569 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
6571 mc->mc_xcursor = mx;
6572 mdb_xcursor_init0(mc);
6574 mc->mc_xcursor = NULL;
6576 if (*mc->mc_dbflag & DB_STALE) {
6577 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
6582 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
6585 size_t size = sizeof(MDB_cursor);
6587 if (txn == NULL || ret == NULL || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
6590 if (txn->mt_flags & MDB_TXN_ERROR)
6593 /* Allow read access to the freelist */
6594 if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
6597 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
6598 size += sizeof(MDB_xcursor);
6600 if ((mc = malloc(size)) != NULL) {
6601 mdb_cursor_init(mc, txn, dbi, (MDB_xcursor *)(mc + 1));
6602 if (txn->mt_cursors) {
6603 mc->mc_next = txn->mt_cursors[dbi];
6604 txn->mt_cursors[dbi] = mc;
6605 mc->mc_flags |= C_UNTRACK;
6617 mdb_cursor_renew(MDB_txn *txn, MDB_cursor *mc)
6619 if (txn == NULL || mc == NULL || mc->mc_dbi >= txn->mt_numdbs)
6622 if ((mc->mc_flags & C_UNTRACK) || txn->mt_cursors)
6625 mdb_cursor_init(mc, txn, mc->mc_dbi, mc->mc_xcursor);
6629 /* Return the count of duplicate data items for the current key */
6631 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
6635 if (mc == NULL || countp == NULL)
6638 if (mc->mc_xcursor == NULL)
6639 return MDB_INCOMPATIBLE;
6641 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
6642 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
6645 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
6648 *countp = mc->mc_xcursor->mx_db.md_entries;
6654 mdb_cursor_close(MDB_cursor *mc)
6656 if (mc && !mc->mc_backup) {
6657 /* remove from txn, if tracked */
6658 if ((mc->mc_flags & C_UNTRACK) && mc->mc_txn->mt_cursors) {
6659 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
6660 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
6662 *prev = mc->mc_next;
6669 mdb_cursor_txn(MDB_cursor *mc)
6671 if (!mc) return NULL;
6676 mdb_cursor_dbi(MDB_cursor *mc)
6682 /** Replace the key for a node with a new key.
6683 * @param[in] mc Cursor pointing to the node to operate on.
6684 * @param[in] key The new key to use.
6685 * @return 0 on success, non-zero on failure.
6688 mdb_update_key(MDB_cursor *mc, MDB_val *key)
6695 indx_t ptr, i, numkeys, indx;
6698 indx = mc->mc_ki[mc->mc_top];
6699 mp = mc->mc_pg[mc->mc_top];
6700 node = NODEPTR(mp, indx);
6701 ptr = mp->mp_ptrs[indx];
6705 char kbuf2[(MDB_MAXKEYSIZE*2+1)];
6706 k2.mv_data = NODEKEY(node);
6707 k2.mv_size = node->mn_ksize;
6708 DPRINTF(("update key %u (ofs %u) [%s] to [%s] on page %"Z"u",
6710 mdb_dkey(&k2, kbuf2),
6716 delta0 = delta = key->mv_size - node->mn_ksize;
6718 /* Must be 2-byte aligned. If new key is
6719 * shorter by 1, the shift will be skipped.
6721 delta += (delta & 1);
6723 if (delta > 0 && SIZELEFT(mp) < delta) {
6725 /* not enough space left, do a delete and split */
6726 DPRINTF(("Not enough room, delta = %d, splitting...", delta));
6727 pgno = NODEPGNO(node);
6728 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
6729 return mdb_page_split(mc, key, NULL, pgno, MDB_SPLIT_REPLACE);
6732 numkeys = NUMKEYS(mp);
6733 for (i = 0; i < numkeys; i++) {
6734 if (mp->mp_ptrs[i] <= ptr)
6735 mp->mp_ptrs[i] -= delta;
6738 base = (char *)mp + mp->mp_upper;
6739 len = ptr - mp->mp_upper + NODESIZE;
6740 memmove(base - delta, base, len);
6741 mp->mp_upper -= delta;
6743 node = NODEPTR(mp, indx);
6746 /* But even if no shift was needed, update ksize */
6748 node->mn_ksize = key->mv_size;
6751 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
6757 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst);
6759 /** Move a node from csrc to cdst.
6762 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
6769 unsigned short flags;
6773 /* Mark src and dst as dirty. */
6774 if ((rc = mdb_page_touch(csrc)) ||
6775 (rc = mdb_page_touch(cdst)))
6778 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6779 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
6780 key.mv_size = csrc->mc_db->md_pad;
6781 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
6783 data.mv_data = NULL;
6787 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
6788 assert(!((long)srcnode&1));
6789 srcpg = NODEPGNO(srcnode);
6790 flags = srcnode->mn_flags;
6791 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6792 unsigned int snum = csrc->mc_snum;
6794 /* must find the lowest key below src */
6795 mdb_page_search_lowest(csrc);
6796 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6797 key.mv_size = csrc->mc_db->md_pad;
6798 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6800 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6801 key.mv_size = NODEKSZ(s2);
6802 key.mv_data = NODEKEY(s2);
6804 csrc->mc_snum = snum--;
6805 csrc->mc_top = snum;
6807 key.mv_size = NODEKSZ(srcnode);
6808 key.mv_data = NODEKEY(srcnode);
6810 data.mv_size = NODEDSZ(srcnode);
6811 data.mv_data = NODEDATA(srcnode);
6813 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
6814 unsigned int snum = cdst->mc_snum;
6817 /* must find the lowest key below dst */
6818 mdb_page_search_lowest(cdst);
6819 if (IS_LEAF2(cdst->mc_pg[cdst->mc_top])) {
6820 bkey.mv_size = cdst->mc_db->md_pad;
6821 bkey.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, bkey.mv_size);
6823 s2 = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
6824 bkey.mv_size = NODEKSZ(s2);
6825 bkey.mv_data = NODEKEY(s2);
6827 cdst->mc_snum = snum--;
6828 cdst->mc_top = snum;
6829 mdb_cursor_copy(cdst, &mn);
6831 rc = mdb_update_key(&mn, &bkey);
6836 DPRINTF(("moving %s node %u [%s] on page %"Z"u to node %u on page %"Z"u",
6837 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
6838 csrc->mc_ki[csrc->mc_top],
6840 csrc->mc_pg[csrc->mc_top]->mp_pgno,
6841 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno));
6843 /* Add the node to the destination page.
6845 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
6846 if (rc != MDB_SUCCESS)
6849 /* Delete the node from the source page.
6851 mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
6854 /* Adjust other cursors pointing to mp */
6855 MDB_cursor *m2, *m3;
6856 MDB_dbi dbi = csrc->mc_dbi;
6857 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
6859 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6860 if (csrc->mc_flags & C_SUB)
6861 m3 = &m2->mc_xcursor->mx_cursor;
6864 if (m3 == csrc) continue;
6865 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
6866 csrc->mc_ki[csrc->mc_top]) {
6867 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
6868 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
6873 /* Update the parent separators.
6875 if (csrc->mc_ki[csrc->mc_top] == 0) {
6876 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
6877 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6878 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6880 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6881 key.mv_size = NODEKSZ(srcnode);
6882 key.mv_data = NODEKEY(srcnode);
6884 DPRINTF(("update separator for source page %"Z"u to [%s]",
6885 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key)));
6886 mdb_cursor_copy(csrc, &mn);
6889 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
6892 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6894 indx_t ix = csrc->mc_ki[csrc->mc_top];
6895 nullkey.mv_size = 0;
6896 csrc->mc_ki[csrc->mc_top] = 0;
6897 rc = mdb_update_key(csrc, &nullkey);
6898 csrc->mc_ki[csrc->mc_top] = ix;
6899 assert(rc == MDB_SUCCESS);
6903 if (cdst->mc_ki[cdst->mc_top] == 0) {
6904 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
6905 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6906 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
6908 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
6909 key.mv_size = NODEKSZ(srcnode);
6910 key.mv_data = NODEKEY(srcnode);
6912 DPRINTF(("update separator for destination page %"Z"u to [%s]",
6913 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key)));
6914 mdb_cursor_copy(cdst, &mn);
6917 if ((rc = mdb_update_key(&mn, &key)) != MDB_SUCCESS)
6920 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
6922 indx_t ix = cdst->mc_ki[cdst->mc_top];
6923 nullkey.mv_size = 0;
6924 cdst->mc_ki[cdst->mc_top] = 0;
6925 rc = mdb_update_key(cdst, &nullkey);
6926 cdst->mc_ki[cdst->mc_top] = ix;
6927 assert(rc == MDB_SUCCESS);
6934 /** Merge one page into another.
6935 * The nodes from the page pointed to by \b csrc will
6936 * be copied to the page pointed to by \b cdst and then
6937 * the \b csrc page will be freed.
6938 * @param[in] csrc Cursor pointing to the source page.
6939 * @param[in] cdst Cursor pointing to the destination page.
6942 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
6950 DPRINTF(("merging page %"Z"u into %"Z"u", csrc->mc_pg[csrc->mc_top]->mp_pgno,
6951 cdst->mc_pg[cdst->mc_top]->mp_pgno));
6953 assert(csrc->mc_snum > 1); /* can't merge root page */
6954 assert(cdst->mc_snum > 1);
6956 /* Mark dst as dirty. */
6957 if ((rc = mdb_page_touch(cdst)))
6960 /* Move all nodes from src to dst.
6962 j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
6963 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6964 key.mv_size = csrc->mc_db->md_pad;
6965 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
6966 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
6967 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
6968 if (rc != MDB_SUCCESS)
6970 key.mv_data = (char *)key.mv_data + key.mv_size;
6973 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
6974 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
6975 if (i == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
6976 unsigned int snum = csrc->mc_snum;
6978 /* must find the lowest key below src */
6979 mdb_page_search_lowest(csrc);
6980 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
6981 key.mv_size = csrc->mc_db->md_pad;
6982 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
6984 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
6985 key.mv_size = NODEKSZ(s2);
6986 key.mv_data = NODEKEY(s2);
6988 csrc->mc_snum = snum--;
6989 csrc->mc_top = snum;
6991 key.mv_size = srcnode->mn_ksize;
6992 key.mv_data = NODEKEY(srcnode);
6995 data.mv_size = NODEDSZ(srcnode);
6996 data.mv_data = NODEDATA(srcnode);
6997 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
6998 if (rc != MDB_SUCCESS)
7003 DPRINTF(("dst page %"Z"u now has %u keys (%.1f%% filled)",
7004 cdst->mc_pg[cdst->mc_top]->mp_pgno, NUMKEYS(cdst->mc_pg[cdst->mc_top]),
7005 (float)PAGEFILL(cdst->mc_txn->mt_env, cdst->mc_pg[cdst->mc_top]) / 10));
7007 /* Unlink the src page from parent and add to free list.
7009 mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
7010 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
7013 rc = mdb_update_key(csrc, &key);
7019 rc = mdb_midl_append(&csrc->mc_txn->mt_free_pgs,
7020 csrc->mc_pg[csrc->mc_top]->mp_pgno);
7023 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
7024 csrc->mc_db->md_leaf_pages--;
7026 csrc->mc_db->md_branch_pages--;
7028 /* Adjust other cursors pointing to mp */
7029 MDB_cursor *m2, *m3;
7030 MDB_dbi dbi = csrc->mc_dbi;
7031 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
7033 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7034 if (csrc->mc_flags & C_SUB)
7035 m3 = &m2->mc_xcursor->mx_cursor;
7038 if (m3 == csrc) continue;
7039 if (m3->mc_snum < csrc->mc_snum) continue;
7040 if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
7041 m3->mc_pg[csrc->mc_top] = mp;
7042 m3->mc_ki[csrc->mc_top] += nkeys;
7046 mdb_cursor_pop(csrc);
7048 return mdb_rebalance(csrc);
7051 /** Copy the contents of a cursor.
7052 * @param[in] csrc The cursor to copy from.
7053 * @param[out] cdst The cursor to copy to.
7056 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
7060 cdst->mc_txn = csrc->mc_txn;
7061 cdst->mc_dbi = csrc->mc_dbi;
7062 cdst->mc_db = csrc->mc_db;
7063 cdst->mc_dbx = csrc->mc_dbx;
7064 cdst->mc_snum = csrc->mc_snum;
7065 cdst->mc_top = csrc->mc_top;
7066 cdst->mc_flags = csrc->mc_flags;
7068 for (i=0; i<csrc->mc_snum; i++) {
7069 cdst->mc_pg[i] = csrc->mc_pg[i];
7070 cdst->mc_ki[i] = csrc->mc_ki[i];
7074 /** Rebalance the tree after a delete operation.
7075 * @param[in] mc Cursor pointing to the page where rebalancing
7077 * @return 0 on success, non-zero on failure.
7080 mdb_rebalance(MDB_cursor *mc)
7084 unsigned int ptop, minkeys;
7087 minkeys = 1 + (IS_BRANCH(mc->mc_pg[mc->mc_top]));
7091 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
7092 DPRINTF(("rebalancing %s page %"Z"u (has %u keys, %.1f%% full)",
7093 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
7094 pgno, NUMKEYS(mc->mc_pg[mc->mc_top]),
7095 (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10));
7099 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD &&
7100 NUMKEYS(mc->mc_pg[mc->mc_top]) >= minkeys) {
7103 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
7104 DPRINTF(("no need to rebalance page %"Z"u, above fill threshold",
7110 if (mc->mc_snum < 2) {
7111 MDB_page *mp = mc->mc_pg[0];
7113 DPUTS("Can't rebalance a subpage, ignoring");
7116 if (NUMKEYS(mp) == 0) {
7117 DPUTS("tree is completely empty");
7118 mc->mc_db->md_root = P_INVALID;
7119 mc->mc_db->md_depth = 0;
7120 mc->mc_db->md_leaf_pages = 0;
7121 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7124 /* Adjust cursors pointing to mp */
7127 mc->mc_flags &= ~C_INITIALIZED;
7129 MDB_cursor *m2, *m3;
7130 MDB_dbi dbi = mc->mc_dbi;
7132 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7133 if (mc->mc_flags & C_SUB)
7134 m3 = &m2->mc_xcursor->mx_cursor;
7137 if (m3->mc_snum < mc->mc_snum) continue;
7138 if (m3->mc_pg[0] == mp) {
7141 m3->mc_flags &= ~C_INITIALIZED;
7145 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
7146 DPUTS("collapsing root page!");
7147 rc = mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
7150 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
7151 rc = mdb_page_get(mc->mc_txn,mc->mc_db->md_root,&mc->mc_pg[0],NULL);
7154 mc->mc_db->md_depth--;
7155 mc->mc_db->md_branch_pages--;
7156 mc->mc_ki[0] = mc->mc_ki[1];
7158 /* Adjust other cursors pointing to mp */
7159 MDB_cursor *m2, *m3;
7160 MDB_dbi dbi = mc->mc_dbi;
7162 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7163 if (mc->mc_flags & C_SUB)
7164 m3 = &m2->mc_xcursor->mx_cursor;
7167 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
7168 if (m3->mc_pg[0] == mp) {
7172 for (i=0; i<m3->mc_snum; i++) {
7173 m3->mc_pg[i] = m3->mc_pg[i+1];
7174 m3->mc_ki[i] = m3->mc_ki[i+1];
7180 DPUTS("root page doesn't need rebalancing");
7184 /* The parent (branch page) must have at least 2 pointers,
7185 * otherwise the tree is invalid.
7187 ptop = mc->mc_top-1;
7188 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
7190 /* Leaf page fill factor is below the threshold.
7191 * Try to move keys from left or right neighbor, or
7192 * merge with a neighbor page.
7197 mdb_cursor_copy(mc, &mn);
7198 mn.mc_xcursor = NULL;
7200 if (mc->mc_ki[ptop] == 0) {
7201 /* We're the leftmost leaf in our parent.
7203 DPUTS("reading right neighbor");
7205 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7206 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7209 mn.mc_ki[mn.mc_top] = 0;
7210 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
7212 /* There is at least one neighbor to the left.
7214 DPUTS("reading left neighbor");
7216 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
7217 rc = mdb_page_get(mc->mc_txn,NODEPGNO(node),&mn.mc_pg[mn.mc_top],NULL);
7220 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
7221 mc->mc_ki[mc->mc_top] = 0;
7224 DPRINTF(("found neighbor page %"Z"u (%u keys, %.1f%% full)",
7225 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]),
7226 (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10));
7228 /* If the neighbor page is above threshold and has enough keys,
7229 * move one key from it. Otherwise we should try to merge them.
7230 * (A branch page must never have less than 2 keys.)
7232 minkeys = 1 + (IS_BRANCH(mn.mc_pg[mn.mc_top]));
7233 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) > minkeys)
7234 return mdb_node_move(&mn, mc);
7236 if (mc->mc_ki[ptop] == 0)
7237 rc = mdb_page_merge(&mn, mc);
7239 mn.mc_ki[mn.mc_top] += mc->mc_ki[mn.mc_top] + 1;
7240 rc = mdb_page_merge(mc, &mn);
7241 mdb_cursor_copy(&mn, mc);
7243 mc->mc_flags &= ~(C_INITIALIZED|C_EOF);
7248 /** Complete a delete operation started by #mdb_cursor_del(). */
7250 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
7257 mp = mc->mc_pg[mc->mc_top];
7258 ki = mc->mc_ki[mc->mc_top];
7260 /* add overflow pages to free list */
7261 if (!IS_LEAF2(mp) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
7265 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
7266 if ((rc = mdb_page_get(mc->mc_txn, pg, &omp, NULL)) ||
7267 (rc = mdb_ovpage_free(mc, omp)))
7270 mdb_node_del(mp, ki, mc->mc_db->md_pad);
7271 mc->mc_db->md_entries--;
7272 rc = mdb_rebalance(mc);
7273 if (rc != MDB_SUCCESS)
7274 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
7277 MDB_dbi dbi = mc->mc_dbi;
7279 mp = mc->mc_pg[mc->mc_top];
7280 nkeys = NUMKEYS(mp);
7282 /* if mc points past last node in page, find next sibling */
7283 if (mc->mc_ki[mc->mc_top] >= nkeys)
7284 mdb_cursor_sibling(mc, 1);
7286 /* Adjust other cursors pointing to mp */
7287 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7290 if (!(m2->mc_flags & C_INITIALIZED))
7292 if (m2->mc_pg[mc->mc_top] == mp) {
7293 if (m2->mc_ki[mc->mc_top] >= ki) {
7294 m2->mc_flags |= C_DEL;
7295 if (m2->mc_ki[mc->mc_top] > ki)
7296 m2->mc_ki[mc->mc_top]--;
7298 if (m2->mc_ki[mc->mc_top] >= nkeys)
7299 mdb_cursor_sibling(m2, 1);
7302 mc->mc_flags |= C_DEL;
7309 mdb_del(MDB_txn *txn, MDB_dbi dbi,
7310 MDB_val *key, MDB_val *data)
7315 MDB_val rdata, *xdata;
7319 assert(key != NULL);
7321 DPRINTF(("====> delete db %u key [%s]", dbi, DKEY(key)));
7323 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7326 if (txn->mt_flags & (MDB_TXN_RDONLY|MDB_TXN_ERROR))
7327 return (txn->mt_flags & MDB_TXN_RDONLY) ? EACCES : MDB_BAD_TXN;
7329 if (key->mv_size > MDB_MAXKEYSIZE) {
7330 return MDB_BAD_VALSIZE;
7333 mdb_cursor_init(&mc, txn, dbi, &mx);
7336 if (!F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
7337 /* must ignore any data */
7348 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
7350 /* let mdb_page_split know about this cursor if needed:
7351 * delete will trigger a rebalance; if it needs to move
7352 * a node from one page to another, it will have to
7353 * update the parent's separator key(s). If the new sepkey
7354 * is larger than the current one, the parent page may
7355 * run out of space, triggering a split. We need this
7356 * cursor to be consistent until the end of the rebalance.
7358 mc.mc_flags |= C_UNTRACK;
7359 mc.mc_next = txn->mt_cursors[dbi];
7360 txn->mt_cursors[dbi] = &mc;
7361 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
7362 txn->mt_cursors[dbi] = mc.mc_next;
7367 /** Split a page and insert a new node.
7368 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
7369 * The cursor will be updated to point to the actual page and index where
7370 * the node got inserted after the split.
7371 * @param[in] newkey The key for the newly inserted node.
7372 * @param[in] newdata The data for the newly inserted node.
7373 * @param[in] newpgno The page number, if the new node is a branch node.
7374 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
7375 * @return 0 on success, non-zero on failure.
7378 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
7379 unsigned int nflags)
7382 int rc = MDB_SUCCESS, new_root = 0, did_split = 0;
7385 int i, j, split_indx, nkeys, pmax;
7386 MDB_env *env = mc->mc_txn->mt_env;
7388 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
7389 MDB_page *copy = NULL;
7390 MDB_page *mp, *rp, *pp;
7395 mp = mc->mc_pg[mc->mc_top];
7396 newindx = mc->mc_ki[mc->mc_top];
7397 nkeys = NUMKEYS(mp);
7399 DPRINTF(("-----> splitting %s page %"Z"u and adding [%s] at index %i/%i",
7400 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
7401 DKEY(newkey), mc->mc_ki[mc->mc_top], nkeys));
7403 /* Create a right sibling. */
7404 if ((rc = mdb_page_new(mc, mp->mp_flags, 1, &rp)))
7406 DPRINTF(("new right sibling: page %"Z"u", rp->mp_pgno));
7408 if (mc->mc_snum < 2) {
7409 if ((rc = mdb_page_new(mc, P_BRANCH, 1, &pp)))
7411 /* shift current top to make room for new parent */
7412 mc->mc_pg[1] = mc->mc_pg[0];
7413 mc->mc_ki[1] = mc->mc_ki[0];
7416 mc->mc_db->md_root = pp->mp_pgno;
7417 DPRINTF(("root split! new root = %"Z"u", pp->mp_pgno));
7418 mc->mc_db->md_depth++;
7421 /* Add left (implicit) pointer. */
7422 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
7423 /* undo the pre-push */
7424 mc->mc_pg[0] = mc->mc_pg[1];
7425 mc->mc_ki[0] = mc->mc_ki[1];
7426 mc->mc_db->md_root = mp->mp_pgno;
7427 mc->mc_db->md_depth--;
7434 ptop = mc->mc_top-1;
7435 DPRINTF(("parent branch page is %"Z"u", mc->mc_pg[ptop]->mp_pgno));
7438 mc->mc_flags |= C_SPLITTING;
7439 mdb_cursor_copy(mc, &mn);
7440 mn.mc_pg[mn.mc_top] = rp;
7441 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
7443 if (nflags & MDB_APPEND) {
7444 mn.mc_ki[mn.mc_top] = 0;
7446 split_indx = newindx;
7450 split_indx = (nkeys+1) / 2;
7455 unsigned int lsize, rsize, ksize;
7456 /* Move half of the keys to the right sibling */
7458 x = mc->mc_ki[mc->mc_top] - split_indx;
7459 ksize = mc->mc_db->md_pad;
7460 split = LEAF2KEY(mp, split_indx, ksize);
7461 rsize = (nkeys - split_indx) * ksize;
7462 lsize = (nkeys - split_indx) * sizeof(indx_t);
7463 mp->mp_lower -= lsize;
7464 rp->mp_lower += lsize;
7465 mp->mp_upper += rsize - lsize;
7466 rp->mp_upper -= rsize - lsize;
7467 sepkey.mv_size = ksize;
7468 if (newindx == split_indx) {
7469 sepkey.mv_data = newkey->mv_data;
7471 sepkey.mv_data = split;
7474 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
7475 memcpy(rp->mp_ptrs, split, rsize);
7476 sepkey.mv_data = rp->mp_ptrs;
7477 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
7478 memcpy(ins, newkey->mv_data, ksize);
7479 mp->mp_lower += sizeof(indx_t);
7480 mp->mp_upper -= ksize - sizeof(indx_t);
7483 memcpy(rp->mp_ptrs, split, x * ksize);
7484 ins = LEAF2KEY(rp, x, ksize);
7485 memcpy(ins, newkey->mv_data, ksize);
7486 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
7487 rp->mp_lower += sizeof(indx_t);
7488 rp->mp_upper -= ksize - sizeof(indx_t);
7489 mc->mc_ki[mc->mc_top] = x;
7490 mc->mc_pg[mc->mc_top] = rp;
7493 int psize, nsize, k;
7494 /* Maximum free space in an empty page */
7495 pmax = env->me_psize - PAGEHDRSZ;
7497 nsize = mdb_leaf_size(env, newkey, newdata);
7499 nsize = mdb_branch_size(env, newkey);
7502 /* grab a page to hold a temporary copy */
7503 copy = mdb_page_malloc(mc->mc_txn, 1);
7506 copy->mp_pgno = mp->mp_pgno;
7507 copy->mp_flags = mp->mp_flags;
7508 copy->mp_lower = PAGEHDRSZ;
7509 copy->mp_upper = env->me_psize;
7511 /* prepare to insert */
7512 for (i=0, j=0; i<nkeys; i++) {
7514 copy->mp_ptrs[j++] = 0;
7516 copy->mp_ptrs[j++] = mp->mp_ptrs[i];
7519 /* When items are relatively large the split point needs
7520 * to be checked, because being off-by-one will make the
7521 * difference between success or failure in mdb_node_add.
7523 * It's also relevant if a page happens to be laid out
7524 * such that one half of its nodes are all "small" and
7525 * the other half of its nodes are "large." If the new
7526 * item is also "large" and falls on the half with
7527 * "large" nodes, it also may not fit.
7529 * As a final tweak, if the new item goes on the last
7530 * spot on the page (and thus, onto the new page), bias
7531 * the split so the new page is emptier than the old page.
7532 * This yields better packing during sequential inserts.
7534 if (nkeys < 20 || nsize > pmax/16 || newindx >= nkeys) {
7535 /* Find split point */
7537 if (newindx <= split_indx || newindx >= nkeys) {
7539 k = newindx >= nkeys ? nkeys : split_indx+1;
7544 for (; i!=k; i+=j) {
7549 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i]);
7550 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
7552 if (F_ISSET(node->mn_flags, F_BIGDATA))
7553 psize += sizeof(pgno_t);
7555 psize += NODEDSZ(node);
7560 split_indx = i + (j<0);
7564 /* special case: when the new node was on the last
7565 * slot we may not have tripped the break inside the loop.
7566 * In all other cases we either hit the break condition,
7567 * or the original split_indx was already safe.
7569 if (newindx >= nkeys && i == k)
7570 split_indx = nkeys-1;
7572 if (split_indx == newindx) {
7573 sepkey.mv_size = newkey->mv_size;
7574 sepkey.mv_data = newkey->mv_data;
7576 node = (MDB_node *)((char *)mp + copy->mp_ptrs[split_indx]);
7577 sepkey.mv_size = node->mn_ksize;
7578 sepkey.mv_data = NODEKEY(node);
7583 DPRINTF(("separator is %d [%s]", split_indx, DKEY(&sepkey)));
7585 /* Copy separator key to the parent.
7587 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(env, &sepkey)) {
7591 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
7594 if (mn.mc_snum == mc->mc_snum) {
7595 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
7596 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
7597 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
7598 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
7603 /* Right page might now have changed parent.
7604 * Check if left page also changed parent.
7606 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7607 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7608 for (i=0; i<ptop; i++) {
7609 mc->mc_pg[i] = mn.mc_pg[i];
7610 mc->mc_ki[i] = mn.mc_ki[i];
7612 mc->mc_pg[ptop] = mn.mc_pg[ptop];
7613 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
7617 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
7620 mc->mc_flags ^= C_SPLITTING;
7621 if (rc != MDB_SUCCESS) {
7624 if (nflags & MDB_APPEND) {
7625 mc->mc_pg[mc->mc_top] = rp;
7626 mc->mc_ki[mc->mc_top] = 0;
7627 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
7630 for (i=0; i<mc->mc_top; i++)
7631 mc->mc_ki[i] = mn.mc_ki[i];
7632 } else if (!IS_LEAF2(mp)) {
7634 mc->mc_pg[mc->mc_top] = rp;
7639 rkey.mv_data = newkey->mv_data;
7640 rkey.mv_size = newkey->mv_size;
7646 /* Update index for the new key. */
7647 mc->mc_ki[mc->mc_top] = j;
7649 node = (MDB_node *)((char *)mp + copy->mp_ptrs[i]);
7650 rkey.mv_data = NODEKEY(node);
7651 rkey.mv_size = node->mn_ksize;
7653 xdata.mv_data = NODEDATA(node);
7654 xdata.mv_size = NODEDSZ(node);
7657 pgno = NODEPGNO(node);
7658 flags = node->mn_flags;
7661 if (!IS_LEAF(mp) && j == 0) {
7662 /* First branch index doesn't need key data. */
7666 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
7668 /* return tmp page to freelist */
7669 mdb_page_free(env, copy);
7675 mc->mc_pg[mc->mc_top] = copy;
7680 } while (i != split_indx);
7682 nkeys = NUMKEYS(copy);
7683 for (i=0; i<nkeys; i++)
7684 mp->mp_ptrs[i] = copy->mp_ptrs[i];
7685 mp->mp_lower = copy->mp_lower;
7686 mp->mp_upper = copy->mp_upper;
7687 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
7688 env->me_psize - copy->mp_upper);
7690 /* reset back to original page */
7691 if (newindx < split_indx) {
7692 mc->mc_pg[mc->mc_top] = mp;
7693 if (nflags & MDB_RESERVE) {
7694 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
7695 if (!(node->mn_flags & F_BIGDATA))
7696 newdata->mv_data = NODEDATA(node);
7699 mc->mc_pg[mc->mc_top] = rp;
7701 /* Make sure mc_ki is still valid.
7703 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
7704 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
7705 for (i=0; i<ptop; i++) {
7706 mc->mc_pg[i] = mn.mc_pg[i];
7707 mc->mc_ki[i] = mn.mc_ki[i];
7709 mc->mc_pg[ptop] = mn.mc_pg[ptop];
7710 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
7713 /* return tmp page to freelist */
7714 mdb_page_free(env, copy);
7718 /* Adjust other cursors pointing to mp */
7719 MDB_cursor *m2, *m3;
7720 MDB_dbi dbi = mc->mc_dbi;
7721 int fixup = NUMKEYS(mp);
7723 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
7724 if (mc->mc_flags & C_SUB)
7725 m3 = &m2->mc_xcursor->mx_cursor;
7730 if (!(m2->mc_flags & m3->mc_flags & C_INITIALIZED))
7732 if (m3->mc_flags & C_SPLITTING)
7737 for (k=m3->mc_top; k>=0; k--) {
7738 m3->mc_ki[k+1] = m3->mc_ki[k];
7739 m3->mc_pg[k+1] = m3->mc_pg[k];
7741 if (m3->mc_ki[0] >= split_indx) {
7746 m3->mc_pg[0] = mc->mc_pg[0];
7750 if (m3->mc_top >= mc->mc_top && m3->mc_pg[mc->mc_top] == mp) {
7751 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
7752 m3->mc_ki[mc->mc_top]++;
7753 if (m3->mc_ki[mc->mc_top] >= fixup) {
7754 m3->mc_pg[mc->mc_top] = rp;
7755 m3->mc_ki[mc->mc_top] -= fixup;
7756 m3->mc_ki[ptop] = mn.mc_ki[ptop];
7758 } else if (!did_split && m3->mc_top >= ptop && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
7759 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
7764 DPRINTF(("mp left: %d, rp left: %d", SIZELEFT(mp), SIZELEFT(rp)));
7769 mdb_put(MDB_txn *txn, MDB_dbi dbi,
7770 MDB_val *key, MDB_val *data, unsigned int flags)
7775 assert(key != NULL);
7776 assert(data != NULL);
7778 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
7781 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND|MDB_APPENDDUP)) != flags)
7784 mdb_cursor_init(&mc, txn, dbi, &mx);
7785 return mdb_cursor_put(&mc, key, data, flags);
7789 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
7791 if ((flag & CHANGEABLE) != flag)
7794 env->me_flags |= flag;
7796 env->me_flags &= ~flag;
7801 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
7806 *arg = env->me_flags;
7811 mdb_env_get_path(MDB_env *env, const char **arg)
7816 *arg = env->me_path;
7821 mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *arg)
7830 /** Common code for #mdb_stat() and #mdb_env_stat().
7831 * @param[in] env the environment to operate in.
7832 * @param[in] db the #MDB_db record containing the stats to return.
7833 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
7834 * @return 0, this function always succeeds.
7837 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
7839 arg->ms_psize = env->me_psize;
7840 arg->ms_depth = db->md_depth;
7841 arg->ms_branch_pages = db->md_branch_pages;
7842 arg->ms_leaf_pages = db->md_leaf_pages;
7843 arg->ms_overflow_pages = db->md_overflow_pages;
7844 arg->ms_entries = db->md_entries;
7849 mdb_env_stat(MDB_env *env, MDB_stat *arg)
7853 if (env == NULL || arg == NULL)
7856 toggle = mdb_env_pick_meta(env);
7858 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
7862 mdb_env_info(MDB_env *env, MDB_envinfo *arg)
7866 if (env == NULL || arg == NULL)
7869 toggle = mdb_env_pick_meta(env);
7870 arg->me_mapaddr = (env->me_flags & MDB_FIXEDMAP) ? env->me_map : 0;
7871 arg->me_mapsize = env->me_mapsize;
7872 arg->me_maxreaders = env->me_maxreaders;
7874 /* me_numreaders may be zero if this process never used any readers. Use
7875 * the shared numreader count if it exists.
7877 arg->me_numreaders = env->me_txns ? env->me_txns->mti_numreaders : env->me_numreaders;
7879 arg->me_last_pgno = env->me_metas[toggle]->mm_last_pg;
7880 arg->me_last_txnid = env->me_metas[toggle]->mm_txnid;
7884 /** Set the default comparison functions for a database.
7885 * Called immediately after a database is opened to set the defaults.
7886 * The user can then override them with #mdb_set_compare() or
7887 * #mdb_set_dupsort().
7888 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
7889 * @param[in] dbi A database handle returned by #mdb_dbi_open()
7892 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
7894 uint16_t f = txn->mt_dbs[dbi].md_flags;
7896 txn->mt_dbxs[dbi].md_cmp =
7897 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
7898 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
7900 txn->mt_dbxs[dbi].md_dcmp =
7901 !(f & MDB_DUPSORT) ? 0 :
7902 ((f & MDB_INTEGERDUP)
7903 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
7904 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
7907 int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
7912 int rc, dbflag, exact;
7913 unsigned int unused = 0;
7916 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
7917 mdb_default_cmp(txn, FREE_DBI);
7920 if ((flags & VALID_FLAGS) != flags)
7922 if (txn->mt_flags & MDB_TXN_ERROR)
7928 if (flags & PERSISTENT_FLAGS) {
7929 uint16_t f2 = flags & PERSISTENT_FLAGS;
7930 /* make sure flag changes get committed */
7931 if ((txn->mt_dbs[MAIN_DBI].md_flags | f2) != txn->mt_dbs[MAIN_DBI].md_flags) {
7932 txn->mt_dbs[MAIN_DBI].md_flags |= f2;
7933 txn->mt_flags |= MDB_TXN_DIRTY;
7936 mdb_default_cmp(txn, MAIN_DBI);
7940 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
7941 mdb_default_cmp(txn, MAIN_DBI);
7944 /* Is the DB already open? */
7946 for (i=2; i<txn->mt_numdbs; i++) {
7947 if (!txn->mt_dbxs[i].md_name.mv_size) {
7948 /* Remember this free slot */
7949 if (!unused) unused = i;
7952 if (len == txn->mt_dbxs[i].md_name.mv_size &&
7953 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
7959 /* If no free slot and max hit, fail */
7960 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs)
7961 return MDB_DBS_FULL;
7963 /* Cannot mix named databases with some mainDB flags */
7964 if (txn->mt_dbs[MAIN_DBI].md_flags & (MDB_DUPSORT|MDB_INTEGERKEY))
7965 return (flags & MDB_CREATE) ? MDB_INCOMPATIBLE : MDB_NOTFOUND;
7967 /* Find the DB info */
7968 dbflag = DB_NEW|DB_VALID;
7971 key.mv_data = (void *)name;
7972 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
7973 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
7974 if (rc == MDB_SUCCESS) {
7975 /* make sure this is actually a DB */
7976 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
7977 if (!(node->mn_flags & F_SUBDATA))
7978 return MDB_INCOMPATIBLE;
7979 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
7980 /* Create if requested */
7982 data.mv_size = sizeof(MDB_db);
7983 data.mv_data = &dummy;
7984 memset(&dummy, 0, sizeof(dummy));
7985 dummy.md_root = P_INVALID;
7986 dummy.md_flags = flags & PERSISTENT_FLAGS;
7987 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
7991 /* OK, got info, add to table */
7992 if (rc == MDB_SUCCESS) {
7993 unsigned int slot = unused ? unused : txn->mt_numdbs;
7994 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
7995 txn->mt_dbxs[slot].md_name.mv_size = len;
7996 txn->mt_dbxs[slot].md_rel = NULL;
7997 txn->mt_dbflags[slot] = dbflag;
7998 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
8000 mdb_default_cmp(txn, slot);
8009 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
8011 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
8014 if (txn->mt_dbflags[dbi] & DB_STALE) {
8017 /* Stale, must read the DB's root. cursor_init does it for us. */
8018 mdb_cursor_init(&mc, txn, dbi, &mx);
8020 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
8023 void mdb_dbi_close(MDB_env *env, MDB_dbi dbi)
8026 if (dbi <= MAIN_DBI || dbi >= env->me_maxdbs)
8028 ptr = env->me_dbxs[dbi].md_name.mv_data;
8029 env->me_dbxs[dbi].md_name.mv_data = NULL;
8030 env->me_dbxs[dbi].md_name.mv_size = 0;
8031 env->me_dbflags[dbi] = 0;
8035 int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags)
8037 /* We could return the flags for the FREE_DBI too but what's the point? */
8038 if (txn == NULL || dbi < MAIN_DBI || dbi >= txn->mt_numdbs)
8040 *flags = txn->mt_dbs[dbi].md_flags & PERSISTENT_FLAGS;
8044 /** Add all the DB's pages to the free list.
8045 * @param[in] mc Cursor on the DB to free.
8046 * @param[in] subs non-Zero to check for sub-DBs in this DB.
8047 * @return 0 on success, non-zero on failure.
8050 mdb_drop0(MDB_cursor *mc, int subs)
8054 rc = mdb_page_search(mc, NULL, MDB_PS_FIRST);
8055 if (rc == MDB_SUCCESS) {
8056 MDB_txn *txn = mc->mc_txn;
8061 /* LEAF2 pages have no nodes, cannot have sub-DBs */
8062 if (IS_LEAF2(mc->mc_pg[mc->mc_top]))
8065 mdb_cursor_copy(mc, &mx);
8066 while (mc->mc_snum > 0) {
8067 MDB_page *mp = mc->mc_pg[mc->mc_top];
8068 unsigned n = NUMKEYS(mp);
8070 for (i=0; i<n; i++) {
8071 ni = NODEPTR(mp, i);
8072 if (ni->mn_flags & F_BIGDATA) {
8075 memcpy(&pg, NODEDATA(ni), sizeof(pg));
8076 rc = mdb_page_get(txn, pg, &omp, NULL);
8079 assert(IS_OVERFLOW(omp));
8080 rc = mdb_midl_append_range(&txn->mt_free_pgs,
8084 } else if (subs && (ni->mn_flags & F_SUBDATA)) {
8085 mdb_xcursor_init1(mc, ni);
8086 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
8092 if ((rc = mdb_midl_need(&txn->mt_free_pgs, n)) != 0)
8094 for (i=0; i<n; i++) {
8096 ni = NODEPTR(mp, i);
8099 mdb_midl_xappend(txn->mt_free_pgs, pg);
8104 mc->mc_ki[mc->mc_top] = i;
8105 rc = mdb_cursor_sibling(mc, 1);
8107 /* no more siblings, go back to beginning
8108 * of previous level.
8112 for (i=1; i<mc->mc_snum; i++) {
8114 mc->mc_pg[i] = mx.mc_pg[i];
8119 rc = mdb_midl_append(&txn->mt_free_pgs, mc->mc_db->md_root);
8120 } else if (rc == MDB_NOTFOUND) {
8126 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
8128 MDB_cursor *mc, *m2;
8131 if (!txn || !dbi || dbi >= txn->mt_numdbs || (unsigned)del > 1 || !(txn->mt_dbflags[dbi] & DB_VALID))
8134 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
8137 rc = mdb_cursor_open(txn, dbi, &mc);
8141 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
8142 /* Invalidate the dropped DB's cursors */
8143 for (m2 = txn->mt_cursors[dbi]; m2; m2 = m2->mc_next)
8144 m2->mc_flags &= ~(C_INITIALIZED|C_EOF);
8148 /* Can't delete the main DB */
8149 if (del && dbi > MAIN_DBI) {
8150 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
8152 txn->mt_dbflags[dbi] = DB_STALE;
8153 mdb_dbi_close(txn->mt_env, dbi);
8156 /* reset the DB record, mark it dirty */
8157 txn->mt_dbflags[dbi] |= DB_DIRTY;
8158 txn->mt_dbs[dbi].md_depth = 0;
8159 txn->mt_dbs[dbi].md_branch_pages = 0;
8160 txn->mt_dbs[dbi].md_leaf_pages = 0;
8161 txn->mt_dbs[dbi].md_overflow_pages = 0;
8162 txn->mt_dbs[dbi].md_entries = 0;
8163 txn->mt_dbs[dbi].md_root = P_INVALID;
8165 txn->mt_flags |= MDB_TXN_DIRTY;
8168 mdb_cursor_close(mc);
8172 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
8174 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8177 txn->mt_dbxs[dbi].md_cmp = cmp;
8181 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
8183 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8186 txn->mt_dbxs[dbi].md_dcmp = cmp;
8190 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
8192 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8195 txn->mt_dbxs[dbi].md_rel = rel;
8199 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
8201 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs || !(txn->mt_dbflags[dbi] & DB_VALID))
8204 txn->mt_dbxs[dbi].md_relctx = ctx;
8208 int mdb_env_get_maxkeysize(MDB_env *env)
8210 return MDB_MAXKEYSIZE;
8213 int mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx)
8215 unsigned int i, rdrs;
8222 if (!env->me_txns) {
8223 return func("(no reader locks)\n", ctx);
8225 rdrs = env->me_txns->mti_numreaders;
8226 mr = env->me_txns->mti_readers;
8227 for (i=0; i<rdrs; i++) {
8232 if (mr[i].mr_txnid == (txnid_t)-1) {
8233 sprintf(buf, "%10d %"Z"x -\n", mr[i].mr_pid, tid);
8235 sprintf(buf, "%10d %"Z"x %"Z"u\n", mr[i].mr_pid, tid, mr[i].mr_txnid);
8239 func(" pid thread txnid\n", ctx);
8241 rc = func(buf, ctx);
8247 func("(no active readers)\n", ctx);
8252 /** Insert pid into list if not already present.
8253 * return -1 if already present.
8255 static int mdb_pid_insert(pid_t *ids, pid_t pid)
8257 /* binary search of pid in list */
8259 unsigned cursor = 1;
8261 unsigned n = ids[0];
8264 unsigned pivot = n >> 1;
8265 cursor = base + pivot + 1;
8266 val = pid - ids[cursor];
8271 } else if ( val > 0 ) {
8276 /* found, so it's a duplicate */
8285 for (n = ids[0]; n > cursor; n--)
8291 int mdb_reader_check(MDB_env *env, int *dead)
8293 unsigned int i, j, rdrs;
8304 rdrs = env->me_txns->mti_numreaders;
8305 pids = malloc((rdrs+1) * sizeof(pid_t));
8309 mr = env->me_txns->mti_readers;
8311 for (i=0; i<rdrs; i++) {
8312 if (mr[i].mr_pid && mr[i].mr_pid != env->me_pid) {
8314 if (mdb_pid_insert(pids, pid) == 0) {
8315 if (!mdb_reader_pid(env, Pidcheck, pid)) {
8317 /* Recheck, a new process may have reused pid */
8318 if (!mdb_reader_pid(env, Pidcheck, pid)) {
8319 for (j=i; j<rdrs; j++)
8320 if (mr[j].mr_pid == pid) {
8321 DPRINTF(("clear stale reader pid %u txn %"Z"d",
8322 (unsigned) pid, mr[j].mr_txnid));
8327 UNLOCK_MUTEX_R(env);