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-2012 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.
35 #include <sys/types.h>
37 #include <sys/param.h>
43 #ifdef HAVE_SYS_FILE_H
60 #if !(defined(BYTE_ORDER) || defined(__BYTE_ORDER))
61 #include <resolv.h> /* defines BYTE_ORDER on HPUX and Solaris */
64 #if defined(__APPLE__) || defined (BSD)
71 #include <semaphore.h>
76 #include <valgrind/memcheck.h>
77 #define VGMEMP_CREATE(h,r,z) VALGRIND_CREATE_MEMPOOL(h,r,z)
78 #define VGMEMP_ALLOC(h,a,s) VALGRIND_MEMPOOL_ALLOC(h,a,s)
79 #define VGMEMP_FREE(h,a) VALGRIND_MEMPOOL_FREE(h,a)
80 #define VGMEMP_DESTROY(h) VALGRIND_DESTROY_MEMPOOL(h)
81 #define VGMEMP_DEFINED(a,s) VALGRIND_MAKE_MEM_DEFINED(a,s)
83 #define VGMEMP_CREATE(h,r,z)
84 #define VGMEMP_ALLOC(h,a,s)
85 #define VGMEMP_FREE(h,a)
86 #define VGMEMP_DESTROY(h)
87 #define VGMEMP_DEFINED(a,s)
91 # if (defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(_LITTLE_ENDIAN) && defined(_BIG_ENDIAN))
92 /* Solaris just defines one or the other */
93 # define LITTLE_ENDIAN 1234
94 # define BIG_ENDIAN 4321
95 # ifdef _LITTLE_ENDIAN
96 # define BYTE_ORDER LITTLE_ENDIAN
98 # define BYTE_ORDER BIG_ENDIAN
101 # define BYTE_ORDER __BYTE_ORDER
105 #ifndef LITTLE_ENDIAN
106 #define LITTLE_ENDIAN __LITTLE_ENDIAN
109 #define BIG_ENDIAN __BIG_ENDIAN
112 #if defined(__i386) || defined(__x86_64)
113 #define MISALIGNED_OK 1
119 #if (BYTE_ORDER == LITTLE_ENDIAN) == (BYTE_ORDER == BIG_ENDIAN)
120 # error "Unknown or unsupported endianness (BYTE_ORDER)"
121 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
122 # error "Two's complement, reasonably sized integer types, please"
125 /** @defgroup internal MDB Internals
128 /** @defgroup compat Windows Compatibility Macros
129 * A bunch of macros to minimize the amount of platform-specific ifdefs
130 * needed throughout the rest of the code. When the features this library
131 * needs are similar enough to POSIX to be hidden in a one-or-two line
132 * replacement, this macro approach is used.
136 #define pthread_t DWORD
137 #define pthread_mutex_t HANDLE
138 #define pthread_key_t DWORD
139 #define pthread_self() GetCurrentThreadId()
140 #define pthread_key_create(x,y) (*(x) = TlsAlloc())
141 #define pthread_key_delete(x) TlsFree(x)
142 #define pthread_getspecific(x) TlsGetValue(x)
143 #define pthread_setspecific(x,y) TlsSetValue(x,y)
144 #define pthread_mutex_unlock(x) ReleaseMutex(x)
145 #define pthread_mutex_lock(x) WaitForSingleObject(x, INFINITE)
146 #define LOCK_MUTEX_R(env) pthread_mutex_lock((env)->me_rmutex)
147 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock((env)->me_rmutex)
148 #define LOCK_MUTEX_W(env) pthread_mutex_lock((env)->me_wmutex)
149 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock((env)->me_wmutex)
150 #define getpid() GetCurrentProcessId()
151 #define MDB_FDATASYNC(fd) (!FlushFileBuffers(fd))
152 #define ErrCode() GetLastError()
153 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
154 #define close(fd) CloseHandle(fd)
155 #define munmap(ptr,len) UnmapViewOfFile(ptr)
158 #define LOCK_MUTEX_R(env) sem_wait((env)->me_rmutex)
159 #define UNLOCK_MUTEX_R(env) sem_post((env)->me_rmutex)
160 #define LOCK_MUTEX_W(env) sem_wait((env)->me_wmutex)
161 #define UNLOCK_MUTEX_W(env) sem_post((env)->me_wmutex)
162 #define MDB_FDATASYNC(fd) fsync(fd)
165 #define MDB_FDATASYNC(fd) fsync(fd)
167 /** Lock the reader mutex.
169 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
170 /** Unlock the reader mutex.
172 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
174 /** Lock the writer mutex.
175 * Only a single write transaction is allowed at a time. Other writers
176 * will block waiting for this mutex.
178 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
179 /** Unlock the writer mutex.
181 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
182 #endif /* USE_POSIX_SEM */
184 /** Get the error code for the last failed system function.
186 #define ErrCode() errno
188 /** An abstraction for a file handle.
189 * On POSIX systems file handles are small integers. On Windows
190 * they're opaque pointers.
194 /** A value for an invalid file handle.
195 * Mainly used to initialize file variables and signify that they are
198 #define INVALID_HANDLE_VALUE (-1)
200 /** Get the size of a memory page for the system.
201 * This is the basic size that the platform's memory manager uses, and is
202 * fundamental to the use of memory-mapped files.
204 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
207 #if defined(_WIN32) || defined(USE_POSIX_SEM)
210 #define MNAME_LEN (sizeof(pthread_mutex_t))
216 /** A flag for opening a file and requesting synchronous data writes.
217 * This is only used when writing a meta page. It's not strictly needed;
218 * we could just do a normal write and then immediately perform a flush.
219 * But if this flag is available it saves us an extra system call.
221 * @note If O_DSYNC is undefined but exists in /usr/include,
222 * preferably set some compiler flag to get the definition.
223 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
226 # define MDB_DSYNC O_DSYNC
230 /** Function for flushing the data of a file. Define this to fsync
231 * if fdatasync() is not supported.
233 #ifndef MDB_FDATASYNC
234 # define MDB_FDATASYNC fdatasync
237 /** A page number in the database.
238 * Note that 64 bit page numbers are overkill, since pages themselves
239 * already represent 12-13 bits of addressable memory, and the OS will
240 * always limit applications to a maximum of 63 bits of address space.
242 * @note In the #MDB_node structure, we only store 48 bits of this value,
243 * which thus limits us to only 60 bits of addressable data.
245 typedef MDB_ID pgno_t;
247 /** A transaction ID.
248 * See struct MDB_txn.mt_txnid for details.
250 typedef MDB_ID txnid_t;
252 /** @defgroup debug Debug Macros
256 /** Enable debug output.
257 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
258 * read from and written to the database (used for free space management).
263 #if !(__STDC_VERSION__ >= 199901L || defined(__GNUC__))
264 # define DPRINTF (void) /* Vararg macros may be unsupported */
266 static int mdb_debug;
267 static txnid_t mdb_debug_start;
269 /** Print a debug message with printf formatting. */
270 # define DPRINTF(fmt, ...) /**< Requires 2 or more args */ \
271 ((void) ((mdb_debug) && \
272 fprintf(stderr, "%s:%d " fmt "\n", __func__, __LINE__, __VA_ARGS__)))
274 # define DPRINTF(fmt, ...) ((void) 0)
276 /** Print a debug string.
277 * The string is printed literally, with no format processing.
279 #define DPUTS(arg) DPRINTF("%s", arg)
282 /** A default memory page size.
283 * The actual size is platform-dependent, but we use this for
284 * boot-strapping. We probably should not be using this any more.
285 * The #GET_PAGESIZE() macro is used to get the actual size.
287 * Note that we don't currently support Huge pages. On Linux,
288 * regular data files cannot use Huge pages, and in general
289 * Huge pages aren't actually pageable. We rely on the OS
290 * demand-pager to read our data and page it out when memory
291 * pressure from other processes is high. So until OSs have
292 * actual paging support for Huge pages, they're not viable.
294 #define MDB_PAGESIZE 4096
296 /** The minimum number of keys required in a database page.
297 * Setting this to a larger value will place a smaller bound on the
298 * maximum size of a data item. Data items larger than this size will
299 * be pushed into overflow pages instead of being stored directly in
300 * the B-tree node. This value used to default to 4. With a page size
301 * of 4096 bytes that meant that any item larger than 1024 bytes would
302 * go into an overflow page. That also meant that on average 2-3KB of
303 * each overflow page was wasted space. The value cannot be lower than
304 * 2 because then there would no longer be a tree structure. With this
305 * value, items larger than 2KB will go into overflow pages, and on
306 * average only 1KB will be wasted.
308 #define MDB_MINKEYS 2
310 /** A stamp that identifies a file as an MDB file.
311 * There's nothing special about this value other than that it is easily
312 * recognizable, and it will reflect any byte order mismatches.
314 #define MDB_MAGIC 0xBEEFC0DE
316 /** The version number for a database's file format. */
317 #define MDB_VERSION 1
319 /** The maximum size of a key in the database.
320 * While data items have essentially unbounded size, we require that
321 * keys all fit onto a regular page. This limit could be raised a bit
322 * further if needed; to something just under #MDB_PAGESIZE / #MDB_MINKEYS.
324 #define MAXKEYSIZE 511
329 * This is used for printing a hex dump of a key's contents.
331 #define DKBUF char kbuf[(MAXKEYSIZE*2+1)]
332 /** Display a key in hex.
334 * Invoke a function to display a key in hex.
336 #define DKEY(x) mdb_dkey(x, kbuf)
338 #define DKBUF typedef int dummy_kbuf /* so we can put ';' after */
342 /** An invalid page number.
343 * Mainly used to denote an empty tree.
345 #define P_INVALID (~0UL)
347 /** Test if a flag \b f is set in a flag word \b w. */
348 #define F_ISSET(w, f) (((w) & (f)) == (f))
350 /** Used for offsets within a single page.
351 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
354 typedef uint16_t indx_t;
356 /** Default size of memory map.
357 * This is certainly too small for any actual applications. Apps should always set
358 * the size explicitly using #mdb_env_set_mapsize().
360 #define DEFAULT_MAPSIZE 1048576
362 /** @defgroup readers Reader Lock Table
363 * Readers don't acquire any locks for their data access. Instead, they
364 * simply record their transaction ID in the reader table. The reader
365 * mutex is needed just to find an empty slot in the reader table. The
366 * slot's address is saved in thread-specific data so that subsequent read
367 * transactions started by the same thread need no further locking to proceed.
369 * Since the database uses multi-version concurrency control, readers don't
370 * actually need any locking. This table is used to keep track of which
371 * readers are using data from which old transactions, so that we'll know
372 * when a particular old transaction is no longer in use. Old transactions
373 * that have discarded any data pages can then have those pages reclaimed
374 * for use by a later write transaction.
376 * The lock table is constructed such that reader slots are aligned with the
377 * processor's cache line size. Any slot is only ever used by one thread.
378 * This alignment guarantees that there will be no contention or cache
379 * thrashing as threads update their own slot info, and also eliminates
380 * any need for locking when accessing a slot.
382 * A writer thread will scan every slot in the table to determine the oldest
383 * outstanding reader transaction. Any freed pages older than this will be
384 * reclaimed by the writer. The writer doesn't use any locks when scanning
385 * this table. This means that there's no guarantee that the writer will
386 * see the most up-to-date reader info, but that's not required for correct
387 * operation - all we need is to know the upper bound on the oldest reader,
388 * we don't care at all about the newest reader. So the only consequence of
389 * reading stale information here is that old pages might hang around a
390 * while longer before being reclaimed. That's actually good anyway, because
391 * the longer we delay reclaiming old pages, the more likely it is that a
392 * string of contiguous pages can be found after coalescing old pages from
393 * many old transactions together.
395 * @todo We don't actually do such coalescing yet, we grab pages from one
396 * old transaction at a time.
399 /** Number of slots in the reader table.
400 * This value was chosen somewhat arbitrarily. 126 readers plus a
401 * couple mutexes fit exactly into 8KB on my development machine.
402 * Applications should set the table size using #mdb_env_set_maxreaders().
404 #define DEFAULT_READERS 126
406 /** The size of a CPU cache line in bytes. We want our lock structures
407 * aligned to this size to avoid false cache line sharing in the
409 * This value works for most CPUs. For Itanium this should be 128.
415 /** The information we store in a single slot of the reader table.
416 * In addition to a transaction ID, we also record the process and
417 * thread ID that owns a slot, so that we can detect stale information,
418 * e.g. threads or processes that went away without cleaning up.
419 * @note We currently don't check for stale records. We simply re-init
420 * the table when we know that we're the only process opening the
423 typedef struct MDB_rxbody {
424 /** The current Transaction ID when this transaction began.
425 * Multiple readers that start at the same time will probably have the
426 * same ID here. Again, it's not important to exclude them from
427 * anything; all we need to know is which version of the DB they
428 * started from so we can avoid overwriting any data used in that
429 * particular version.
432 /** The process ID of the process owning this reader txn. */
434 /** The thread ID of the thread owning this txn. */
438 /** The actual reader record, with cacheline padding. */
439 typedef struct MDB_reader {
442 /** shorthand for mrb_txnid */
443 #define mr_txnid mru.mrx.mrb_txnid
444 #define mr_pid mru.mrx.mrb_pid
445 #define mr_tid mru.mrx.mrb_tid
446 /** cache line alignment */
447 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
451 /** The header for the reader table.
452 * The table resides in a memory-mapped file. (This is a different file
453 * than is used for the main database.)
455 * For POSIX the actual mutexes reside in the shared memory of this
456 * mapped file. On Windows, mutexes are named objects allocated by the
457 * kernel; we store the mutex names in this mapped file so that other
458 * processes can grab them. This same approach is also used on
459 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
460 * process-shared POSIX mutexes. For these cases where a named object
461 * is used, the object name is derived from a 64 bit FNV hash of the
462 * environment pathname. As such, naming collisions are extremely
463 * unlikely. If a collision occurs, the results are unpredictable.
465 typedef struct MDB_txbody {
466 /** Stamp identifying this as an MDB file. It must be set
469 /** Version number of this lock file. Must be set to #MDB_VERSION. */
470 uint32_t mtb_version;
471 #if defined(_WIN32) || defined(USE_POSIX_SEM)
472 char mtb_rmname[MNAME_LEN];
474 /** Mutex protecting access to this table.
475 * This is the reader lock that #LOCK_MUTEX_R acquires.
477 pthread_mutex_t mtb_mutex;
479 /** The ID of the last transaction committed to the database.
480 * This is recorded here only for convenience; the value can always
481 * be determined by reading the main database meta pages.
484 /** The number of slots that have been used in the reader table.
485 * This always records the maximum count, it is not decremented
486 * when readers release their slots.
488 unsigned mtb_numreaders;
491 /** The actual reader table definition. */
492 typedef struct MDB_txninfo {
495 #define mti_magic mt1.mtb.mtb_magic
496 #define mti_version mt1.mtb.mtb_version
497 #define mti_mutex mt1.mtb.mtb_mutex
498 #define mti_rmname mt1.mtb.mtb_rmname
499 #define mti_txnid mt1.mtb.mtb_txnid
500 #define mti_numreaders mt1.mtb.mtb_numreaders
501 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
504 #if defined(_WIN32) || defined(USE_POSIX_SEM)
505 char mt2_wmname[MNAME_LEN];
506 #define mti_wmname mt2.mt2_wmname
508 pthread_mutex_t mt2_wmutex;
509 #define mti_wmutex mt2.mt2_wmutex
511 char pad[(MNAME_LEN+CACHELINE-1) & ~(CACHELINE-1)];
513 MDB_reader mti_readers[1];
517 /** Common header for all page types.
518 * Overflow records occupy a number of contiguous pages with no
519 * headers on any page after the first.
521 typedef struct MDB_page {
522 #define mp_pgno mp_p.p_pgno
523 #define mp_next mp_p.p_next
525 pgno_t p_pgno; /**< page number */
526 void * p_next; /**< for in-memory list of freed structs */
529 /** @defgroup mdb_page Page Flags
531 * Flags for the page headers.
534 #define P_BRANCH 0x01 /**< branch page */
535 #define P_LEAF 0x02 /**< leaf page */
536 #define P_OVERFLOW 0x04 /**< overflow page */
537 #define P_META 0x08 /**< meta page */
538 #define P_DIRTY 0x10 /**< dirty page */
539 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
540 #define P_SUBP 0x40 /**< for #MDB_DUPSORT sub-pages */
542 uint16_t mp_flags; /**< @ref mdb_page */
543 #define mp_lower mp_pb.pb.pb_lower
544 #define mp_upper mp_pb.pb.pb_upper
545 #define mp_pages mp_pb.pb_pages
548 indx_t pb_lower; /**< lower bound of free space */
549 indx_t pb_upper; /**< upper bound of free space */
551 uint32_t pb_pages; /**< number of overflow pages */
553 indx_t mp_ptrs[1]; /**< dynamic size */
556 /** Size of the page header, excluding dynamic data at the end */
557 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
559 /** Address of first usable data byte in a page, after the header */
560 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
562 /** Number of nodes on a page */
563 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
565 /** The amount of space remaining in the page */
566 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
568 /** The percentage of space used in the page, in tenths of a percent. */
569 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
570 ((env)->me_psize - PAGEHDRSZ))
571 /** The minimum page fill factor, in tenths of a percent.
572 * Pages emptier than this are candidates for merging.
574 #define FILL_THRESHOLD 250
576 /** Test if a page is a leaf page */
577 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
578 /** Test if a page is a LEAF2 page */
579 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
580 /** Test if a page is a branch page */
581 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
582 /** Test if a page is an overflow page */
583 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
584 /** Test if a page is a sub page */
585 #define IS_SUBP(p) F_ISSET((p)->mp_flags, P_SUBP)
587 /** The number of overflow pages needed to store the given size. */
588 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
590 /** Header for a single key/data pair within a page.
591 * We guarantee 2-byte alignment for nodes.
593 typedef struct MDB_node {
594 /** lo and hi are used for data size on leaf nodes and for
595 * child pgno on branch nodes. On 64 bit platforms, flags
596 * is also used for pgno. (Branch nodes have no flags).
597 * They are in host byte order in case that lets some
598 * accesses be optimized into a 32-bit word access.
600 #define mn_lo mn_offset[BYTE_ORDER!=LITTLE_ENDIAN]
601 #define mn_hi mn_offset[BYTE_ORDER==LITTLE_ENDIAN] /**< part of dsize or pgno */
602 unsigned short mn_offset[2]; /**< storage for #mn_lo and #mn_hi */
603 /** @defgroup mdb_node Node Flags
605 * Flags for node headers.
608 #define F_BIGDATA 0x01 /**< data put on overflow page */
609 #define F_SUBDATA 0x02 /**< data is a sub-database */
610 #define F_DUPDATA 0x04 /**< data has duplicates */
612 /** valid flags for #mdb_node_add() */
613 #define NODE_ADD_FLAGS (F_DUPDATA|F_SUBDATA|MDB_RESERVE|MDB_APPEND)
616 unsigned short mn_flags; /**< @ref mdb_node */
617 unsigned short mn_ksize; /**< key size */
618 char mn_data[1]; /**< key and data are appended here */
621 /** Size of the node header, excluding dynamic data at the end */
622 #define NODESIZE offsetof(MDB_node, mn_data)
624 /** Bit position of top word in page number, for shifting mn_flags */
625 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
627 /** Size of a node in a branch page with a given key.
628 * This is just the node header plus the key, there is no data.
630 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
632 /** Size of a node in a leaf page with a given key and data.
633 * This is node header plus key plus data size.
635 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
637 /** Address of node \b i in page \b p */
638 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
640 /** Address of the key for the node */
641 #define NODEKEY(node) (void *)((node)->mn_data)
643 /** Address of the data for a node */
644 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
646 /** Get the page number pointed to by a branch node */
647 #define NODEPGNO(node) \
648 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
649 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
650 /** Set the page number in a branch node */
651 #define SETPGNO(node,pgno) do { \
652 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
653 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
655 /** Get the size of the data in a leaf node */
656 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
657 /** Set the size of the data for a leaf node */
658 #define SETDSZ(node,size) do { \
659 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
660 /** The size of a key in a node */
661 #define NODEKSZ(node) ((node)->mn_ksize)
663 /** Copy a page number from src to dst */
665 #define COPY_PGNO(dst,src) dst = src
667 #if SIZE_MAX > 4294967295UL
668 #define COPY_PGNO(dst,src) do { \
669 unsigned short *s, *d; \
670 s = (unsigned short *)&(src); \
671 d = (unsigned short *)&(dst); \
678 #define COPY_PGNO(dst,src) do { \
679 unsigned short *s, *d; \
680 s = (unsigned short *)&(src); \
681 d = (unsigned short *)&(dst); \
687 /** The address of a key in a LEAF2 page.
688 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
689 * There are no node headers, keys are stored contiguously.
691 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
693 /** Set the \b node's key into \b key, if requested. */
694 #define MDB_SET_KEY(node, key) { if ((key) != NULL) { \
695 (key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node); } }
697 /** Information about a single database in the environment. */
698 typedef struct MDB_db {
699 uint32_t md_pad; /**< also ksize for LEAF2 pages */
700 uint16_t md_flags; /**< @ref mdb_open */
701 uint16_t md_depth; /**< depth of this tree */
702 pgno_t md_branch_pages; /**< number of internal pages */
703 pgno_t md_leaf_pages; /**< number of leaf pages */
704 pgno_t md_overflow_pages; /**< number of overflow pages */
705 size_t md_entries; /**< number of data items */
706 pgno_t md_root; /**< the root page of this tree */
709 /** Handle for the DB used to track free pages. */
711 /** Handle for the default DB. */
714 /** Meta page content. */
715 typedef struct MDB_meta {
716 /** Stamp identifying this as an MDB file. It must be set
719 /** Version number of this lock file. Must be set to #MDB_VERSION. */
721 void *mm_address; /**< address for fixed mapping */
722 size_t mm_mapsize; /**< size of mmap region */
723 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
724 /** The size of pages used in this DB */
725 #define mm_psize mm_dbs[0].md_pad
726 /** Any persistent environment flags. @ref mdb_env */
727 #define mm_flags mm_dbs[0].md_flags
728 pgno_t mm_last_pg; /**< last used page in file */
729 txnid_t mm_txnid; /**< txnid that committed this page */
732 /** Buffer for a stack-allocated dirty page.
733 * The members define size and alignment, and silence type
734 * aliasing warnings. They are not used directly; that could
735 * mean incorrectly using several union members in parallel.
737 typedef union MDB_pagebuf {
738 char mb_raw[MDB_PAGESIZE];
741 char mm_pad[PAGEHDRSZ];
746 /** Auxiliary DB info.
747 * The information here is mostly static/read-only. There is
748 * only a single copy of this record in the environment.
750 typedef struct MDB_dbx {
751 MDB_val md_name; /**< name of the database */
752 MDB_cmp_func *md_cmp; /**< function for comparing keys */
753 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
754 MDB_rel_func *md_rel; /**< user relocate function */
755 void *md_relctx; /**< user-provided context for md_rel */
758 /** A database transaction.
759 * Every operation requires a transaction handle.
762 MDB_txn *mt_parent; /**< parent of a nested txn */
763 MDB_txn *mt_child; /**< nested txn under this txn */
764 pgno_t mt_next_pgno; /**< next unallocated page */
765 /** The ID of this transaction. IDs are integers incrementing from 1.
766 * Only committed write transactions increment the ID. If a transaction
767 * aborts, the ID may be re-used by the next writer.
770 MDB_env *mt_env; /**< the DB environment */
771 /** The list of pages that became unused during this transaction.
775 MDB_ID2L dirty_list; /**< modified pages */
776 MDB_reader *reader; /**< this thread's slot in the reader table */
778 /** Array of records for each DB known in the environment. */
780 /** Array of MDB_db records for each known DB */
782 /** @defgroup mt_dbflag Transaction DB Flags
786 #define DB_DIRTY 0x01 /**< DB was written in this txn */
787 #define DB_STALE 0x02 /**< DB record is older than txnID */
789 /** Array of cursors for each DB */
790 MDB_cursor **mt_cursors;
791 /** Array of flags for each DB */
792 unsigned char *mt_dbflags;
793 /** Number of DB records in use. This number only ever increments;
794 * we don't decrement it when individual DB handles are closed.
798 /** @defgroup mdb_txn Transaction Flags
802 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
803 #define MDB_TXN_ERROR 0x02 /**< an error has occurred */
805 unsigned int mt_flags; /**< @ref mdb_txn */
806 /** Tracks which of the two meta pages was used at the start
807 * of this transaction.
809 unsigned int mt_toggle;
812 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
813 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
814 * raise this on a 64 bit machine.
816 #define CURSOR_STACK 32
820 /** Cursors are used for all DB operations */
822 /** Next cursor on this DB in this txn */
824 /** Original cursor if this is a shadow */
826 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
827 struct MDB_xcursor *mc_xcursor;
828 /** The transaction that owns this cursor */
830 /** The database handle this cursor operates on */
832 /** The database record for this cursor */
834 /** The database auxiliary record for this cursor */
836 /** The @ref mt_dbflag for this database */
837 unsigned char *mc_dbflag;
838 unsigned short mc_snum; /**< number of pushed pages */
839 unsigned short mc_top; /**< index of top page, normally mc_snum-1 */
840 /** @defgroup mdb_cursor Cursor Flags
842 * Cursor state flags.
845 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
846 #define C_EOF 0x02 /**< No more data */
847 #define C_SUB 0x04 /**< Cursor is a sub-cursor */
848 #define C_SHADOW 0x08 /**< Cursor is a dup from a parent txn */
849 #define C_ALLOCD 0x10 /**< Cursor was malloc'd */
850 #define C_SPLITTING 0x20 /**< Cursor is in page_split */
852 unsigned int mc_flags; /**< @ref mdb_cursor */
853 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
854 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
857 /** Context for sorted-dup records.
858 * We could have gone to a fully recursive design, with arbitrarily
859 * deep nesting of sub-databases. But for now we only handle these
860 * levels - main DB, optional sub-DB, sorted-duplicate DB.
862 typedef struct MDB_xcursor {
863 /** A sub-cursor for traversing the Dup DB */
864 MDB_cursor mx_cursor;
865 /** The database record for this Dup DB */
867 /** The auxiliary DB record for this Dup DB */
869 /** The @ref mt_dbflag for this Dup DB */
870 unsigned char mx_dbflag;
873 /** A set of pages freed by an earlier transaction. */
874 typedef struct MDB_oldpages {
875 /** Usually we only read one record from the FREEDB at a time, but
876 * in case we read more, this will chain them together.
878 struct MDB_oldpages *mo_next;
879 /** The ID of the transaction in which these pages were freed. */
881 /** An #MDB_IDL of the pages */
882 pgno_t mo_pages[1]; /* dynamic */
885 /** The database environment. */
887 HANDLE me_fd; /**< The main data file */
888 HANDLE me_lfd; /**< The lock file */
889 HANDLE me_mfd; /**< just for writing the meta pages */
890 /** Failed to update the meta page. Probably an I/O error. */
891 #define MDB_FATAL_ERROR 0x80000000U
892 uint32_t me_flags; /**< @ref mdb_env */
893 unsigned int me_psize; /**< size of a page, from #GET_PAGESIZE */
894 unsigned int me_maxreaders; /**< size of the reader table */
895 MDB_dbi me_numdbs; /**< number of DBs opened */
896 MDB_dbi me_maxdbs; /**< size of the DB table */
897 char *me_path; /**< path to the DB files */
898 char *me_map; /**< the memory map of the data file */
899 MDB_txninfo *me_txns; /**< the memory map of the lock file */
900 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
901 MDB_txn *me_txn; /**< current write transaction */
902 size_t me_mapsize; /**< size of the data memory map */
903 off_t me_size; /**< current file size */
904 pgno_t me_maxpg; /**< me_mapsize / me_psize */
905 txnid_t me_pgfirst; /**< ID of first old page record we used */
906 txnid_t me_pglast; /**< ID of last old page record we used */
907 MDB_dbx *me_dbxs; /**< array of static DB info */
908 uint16_t *me_dbflags; /**< array of DB flags */
909 MDB_oldpages *me_pghead; /**< list of old page records */
910 MDB_oldpages *me_pgfree; /**< list of page records to free */
911 pthread_key_t me_txkey; /**< thread-key for readers */
912 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
913 /** IDL of pages that became unused in a write txn */
915 /** ID2L of pages that were written during a write txn */
916 MDB_ID2 me_dirty_list[MDB_IDL_UM_SIZE];
918 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
922 sem_t *me_rmutex; /* Apple doesn't support shared mutexes */
926 /** max number of pages to commit in one writev() call */
927 #define MDB_COMMIT_PAGES 64
928 #if defined(IOV_MAX) && IOV_MAX < MDB_COMMIT_PAGES
929 #undef MDB_COMMIT_PAGES
930 #define MDB_COMMIT_PAGES IOV_MAX
933 static MDB_page *mdb_page_alloc(MDB_cursor *mc, int num);
934 static MDB_page *mdb_page_new(MDB_cursor *mc, uint32_t flags, int num);
935 static int mdb_page_touch(MDB_cursor *mc);
937 static int mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
938 static int mdb_page_search_root(MDB_cursor *mc,
939 MDB_val *key, int modify);
940 #define MDB_PS_MODIFY 1
941 #define MDB_PS_ROOTONLY 2
942 static int mdb_page_search(MDB_cursor *mc,
943 MDB_val *key, int flags);
944 static int mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst);
946 #define MDB_SPLIT_REPLACE MDB_APPENDDUP /**< newkey is not new */
947 static int mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
948 pgno_t newpgno, unsigned int nflags);
950 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
951 static int mdb_env_pick_meta(const MDB_env *env);
952 static int mdb_env_write_meta(MDB_txn *txn);
954 static MDB_node *mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp);
955 static int mdb_node_add(MDB_cursor *mc, indx_t indx,
956 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags);
957 static void mdb_node_del(MDB_page *mp, indx_t indx, int ksize);
958 static void mdb_node_shrink(MDB_page *mp, indx_t indx);
959 static int mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst);
960 static int mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
961 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
962 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
964 static int mdb_rebalance(MDB_cursor *mc);
965 static int mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
967 static void mdb_cursor_pop(MDB_cursor *mc);
968 static int mdb_cursor_push(MDB_cursor *mc, MDB_page *mp);
970 static int mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf);
971 static int mdb_cursor_sibling(MDB_cursor *mc, int move_right);
972 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
973 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
974 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
976 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
977 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
979 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
980 static void mdb_xcursor_init0(MDB_cursor *mc);
981 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
983 static int mdb_drop0(MDB_cursor *mc, int subs);
984 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
987 static MDB_cmp_func mdb_cmp_memn, mdb_cmp_memnr, mdb_cmp_int, mdb_cmp_cint, mdb_cmp_long;
991 static SECURITY_DESCRIPTOR mdb_null_sd;
992 static SECURITY_ATTRIBUTES mdb_all_sa;
993 static int mdb_sec_inited;
996 /** Return the library version info. */
998 mdb_version(int *major, int *minor, int *patch)
1000 if (major) *major = MDB_VERSION_MAJOR;
1001 if (minor) *minor = MDB_VERSION_MINOR;
1002 if (patch) *patch = MDB_VERSION_PATCH;
1003 return MDB_VERSION_STRING;
1006 /** Table of descriptions for MDB @ref errors */
1007 static char *const mdb_errstr[] = {
1008 "MDB_KEYEXIST: Key/data pair already exists",
1009 "MDB_NOTFOUND: No matching key/data pair found",
1010 "MDB_PAGE_NOTFOUND: Requested page not found",
1011 "MDB_CORRUPTED: Located page was wrong type",
1012 "MDB_PANIC: Update of meta page failed",
1013 "MDB_VERSION_MISMATCH: Database environment version mismatch"
1017 mdb_strerror(int err)
1020 return ("Successful return: 0");
1022 if (err >= MDB_KEYEXIST && err <= MDB_VERSION_MISMATCH)
1023 return mdb_errstr[err - MDB_KEYEXIST];
1025 return strerror(err);
1029 /** Display a key in hexadecimal and return the address of the result.
1030 * @param[in] key the key to display
1031 * @param[in] buf the buffer to write into. Should always be #DKBUF.
1032 * @return The key in hexadecimal form.
1035 mdb_dkey(MDB_val *key, char *buf)
1038 unsigned char *c = key->mv_data;
1040 if (key->mv_size > MAXKEYSIZE)
1041 return "MAXKEYSIZE";
1042 /* may want to make this a dynamic check: if the key is mostly
1043 * printable characters, print it as-is instead of converting to hex.
1047 for (i=0; i<key->mv_size; i++)
1048 ptr += sprintf(ptr, "%02x", *c++);
1050 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
1055 /** Display all the keys in the page. */
1057 mdb_page_keys(MDB_page *mp)
1060 unsigned int i, nkeys;
1064 nkeys = NUMKEYS(mp);
1065 fprintf(stderr, "numkeys %d\n", nkeys);
1066 for (i=0; i<nkeys; i++) {
1067 node = NODEPTR(mp, i);
1068 key.mv_size = node->mn_ksize;
1069 key.mv_data = node->mn_data;
1070 fprintf(stderr, "key %d: %s\n", i, DKEY(&key));
1075 mdb_cursor_chk(MDB_cursor *mc)
1081 if (!mc->mc_snum && !(mc->mc_flags & C_INITIALIZED)) return;
1082 for (i=0; i<mc->mc_top; i++) {
1084 node = NODEPTR(mp, mc->mc_ki[i]);
1085 if (NODEPGNO(node) != mc->mc_pg[i+1]->mp_pgno)
1088 if (mc->mc_ki[i] >= NUMKEYS(mc->mc_pg[i]))
1094 /** Count all the pages in each DB and in the freelist
1095 * and make sure it matches the actual number of pages
1098 static void mdb_audit(MDB_txn *txn)
1102 MDB_ID freecount, count;
1107 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1108 while ((rc = mdb_cursor_get(&mc, &key, &data, MDB_NEXT)) == 0)
1109 freecount += *(MDB_ID *)data.mv_data;
1110 freecount += txn->mt_dbs[0].md_branch_pages + txn->mt_dbs[0].md_leaf_pages +
1111 txn->mt_dbs[0].md_overflow_pages;
1114 for (i = 0; i<txn->mt_numdbs; i++) {
1115 count += txn->mt_dbs[i].md_branch_pages +
1116 txn->mt_dbs[i].md_leaf_pages +
1117 txn->mt_dbs[i].md_overflow_pages;
1118 if (txn->mt_dbs[i].md_flags & MDB_DUPSORT) {
1120 mdb_cursor_init(&mc, txn, i, &mx);
1121 mdb_page_search(&mc, NULL, 0);
1125 mp = mc.mc_pg[mc.mc_top];
1126 for (j=0; j<NUMKEYS(mp); j++) {
1127 MDB_node *leaf = NODEPTR(mp, j);
1128 if (leaf->mn_flags & F_SUBDATA) {
1130 memcpy(&db, NODEDATA(leaf), sizeof(db));
1131 count += db.md_branch_pages + db.md_leaf_pages +
1132 db.md_overflow_pages;
1136 while (mdb_cursor_sibling(&mc, 1) == 0);
1139 assert(freecount + count + 2 >= txn->mt_next_pgno - 1);
1144 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1146 return txn->mt_dbxs[dbi].md_cmp(a, b);
1150 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
1152 if (txn->mt_dbxs[dbi].md_dcmp)
1153 return txn->mt_dbxs[dbi].md_dcmp(a, b);
1155 return EINVAL; /* too bad you can't distinguish this from a valid result */
1158 /** Allocate a single page.
1159 * Re-use old malloc'd pages first, otherwise just malloc.
1162 mdb_page_malloc(MDB_cursor *mc) {
1164 size_t sz = mc->mc_txn->mt_env->me_psize;
1165 if ((ret = mc->mc_txn->mt_env->me_dpages) != NULL) {
1166 VGMEMP_ALLOC(mc->mc_txn->mt_env, ret, sz);
1167 VGMEMP_DEFINED(ret, sizeof(ret->mp_next));
1168 mc->mc_txn->mt_env->me_dpages = ret->mp_next;
1169 } else if ((ret = malloc(sz)) != NULL) {
1170 VGMEMP_ALLOC(mc->mc_txn->mt_env, ret, sz);
1175 /** Allocate pages for writing.
1176 * If there are free pages available from older transactions, they
1177 * will be re-used first. Otherwise a new page will be allocated.
1178 * @param[in] mc cursor A cursor handle identifying the transaction and
1179 * database for which we are allocating.
1180 * @param[in] num the number of pages to allocate.
1181 * @return Address of the allocated page(s). Requests for multiple pages
1182 * will always be satisfied by a single contiguous chunk of memory.
1185 mdb_page_alloc(MDB_cursor *mc, int num)
1187 MDB_txn *txn = mc->mc_txn;
1189 pgno_t pgno = P_INVALID;
1192 /* The free list won't have any content at all until txn 2 has
1193 * committed. The pages freed by txn 2 will be unreferenced
1194 * after txn 3 commits, and so will be safe to re-use in txn 4.
1196 if (txn->mt_txnid > 3) {
1198 if (!txn->mt_env->me_pghead &&
1199 txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
1200 /* See if there's anything in the free DB */
1204 txnid_t *kptr, oldest, last;
1206 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
1207 if (!txn->mt_env->me_pgfirst) {
1208 mdb_page_search(&m2, NULL, 0);
1209 leaf = NODEPTR(m2.mc_pg[m2.mc_top], 0);
1210 kptr = (txnid_t *)NODEKEY(leaf);
1217 last = txn->mt_env->me_pglast + 1;
1219 key.mv_data = &last;
1220 key.mv_size = sizeof(last);
1221 rc = mdb_cursor_set(&m2, &key, &data, MDB_SET, &exact);
1224 last = *(txnid_t *)key.mv_data;
1229 oldest = txn->mt_txnid - 1;
1230 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
1231 txnid_t mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
1232 if (mr && mr < oldest)
1237 if (oldest > last) {
1238 /* It's usable, grab it.
1243 if (!txn->mt_env->me_pgfirst) {
1244 mdb_node_read(txn, leaf, &data);
1246 txn->mt_env->me_pglast = last;
1247 if (!txn->mt_env->me_pgfirst)
1248 txn->mt_env->me_pgfirst = last;
1249 idl = (MDB_ID *) data.mv_data;
1250 /* We might have a zero-length IDL due to freelist growth
1251 * during a prior commit
1253 if (!idl[0]) goto again;
1254 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
1255 mop->mo_next = txn->mt_env->me_pghead;
1256 mop->mo_txnid = last;
1257 txn->mt_env->me_pghead = mop;
1258 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
1263 DPRINTF("IDL read txn %zu root %zu num %zu",
1264 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1265 for (i=0; i<idl[0]; i++) {
1266 DPRINTF("IDL %zu", idl[i+1]);
1273 if (txn->mt_env->me_pghead) {
1274 MDB_oldpages *mop = txn->mt_env->me_pghead;
1276 /* FIXME: For now, always use fresh pages. We
1277 * really ought to search the free list for a
1282 /* peel pages off tail, so we only have to truncate the list */
1283 pgno = MDB_IDL_LAST(mop->mo_pages);
1284 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
1286 if (mop->mo_pages[2] > mop->mo_pages[1])
1287 mop->mo_pages[0] = 0;
1291 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
1292 txn->mt_env->me_pghead = mop->mo_next;
1293 if (mc->mc_dbi == FREE_DBI) {
1294 mop->mo_next = txn->mt_env->me_pgfree;
1295 txn->mt_env->me_pgfree = mop;
1304 if (pgno == P_INVALID) {
1305 /* DB size is maxed out */
1306 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg) {
1307 DPUTS("DB size maxed out");
1311 if (txn->mt_env->me_dpages && num == 1) {
1312 np = txn->mt_env->me_dpages;
1313 VGMEMP_ALLOC(txn->mt_env, np, txn->mt_env->me_psize);
1314 VGMEMP_DEFINED(np, sizeof(np->mp_next));
1315 txn->mt_env->me_dpages = np->mp_next;
1317 size_t sz = txn->mt_env->me_psize * num;
1318 if ((np = malloc(sz)) == NULL)
1320 VGMEMP_ALLOC(txn->mt_env, np, sz);
1322 if (pgno == P_INVALID) {
1323 np->mp_pgno = txn->mt_next_pgno;
1324 txn->mt_next_pgno += num;
1328 mid.mid = np->mp_pgno;
1330 mdb_mid2l_insert(txn->mt_u.dirty_list, &mid);
1335 /** Copy a page: avoid copying unused portions of the page.
1336 * @param[in] dst page to copy into
1337 * @param[in] src page to copy from
1340 mdb_page_copy(MDB_page *dst, MDB_page *src, unsigned int psize)
1342 dst->mp_flags = src->mp_flags | P_DIRTY;
1343 dst->mp_pages = src->mp_pages;
1345 if (IS_LEAF2(src)) {
1346 memcpy(dst->mp_ptrs, src->mp_ptrs, psize - PAGEHDRSZ - SIZELEFT(src));
1348 unsigned int i, nkeys = NUMKEYS(src);
1349 for (i=0; i<nkeys; i++)
1350 dst->mp_ptrs[i] = src->mp_ptrs[i];
1351 memcpy((char *)dst+src->mp_upper, (char *)src+src->mp_upper,
1352 psize - src->mp_upper);
1356 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1357 * @param[in] mc cursor pointing to the page to be touched
1358 * @return 0 on success, non-zero on failure.
1361 mdb_page_touch(MDB_cursor *mc)
1363 MDB_page *mp = mc->mc_pg[mc->mc_top];
1366 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1368 if ((np = mdb_page_alloc(mc, 1)) == NULL)
1370 DPRINTF("touched db %u page %zu -> %zu", mc->mc_dbi, mp->mp_pgno, np->mp_pgno);
1371 assert(mp->mp_pgno != np->mp_pgno);
1372 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
1374 /* If page isn't full, just copy the used portion */
1375 mdb_page_copy(np, mp, mc->mc_txn->mt_env->me_psize);
1378 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1380 np->mp_flags |= P_DIRTY;
1385 /* Adjust other cursors pointing to mp */
1386 if (mc->mc_flags & C_SUB) {
1387 MDB_cursor *m2, *m3;
1388 MDB_dbi dbi = mc->mc_dbi-1;
1390 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
1391 if (m2 == mc) continue;
1392 m3 = &m2->mc_xcursor->mx_cursor;
1393 if (m3->mc_snum < mc->mc_snum) continue;
1394 if (m3->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1395 m3->mc_pg[mc->mc_top] = mp;
1401 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
1402 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
1403 if (m2->mc_pg[mc->mc_top] == mc->mc_pg[mc->mc_top]) {
1404 m2->mc_pg[mc->mc_top] = mp;
1408 mc->mc_pg[mc->mc_top] = mp;
1409 /** If this page has a parent, update the parent to point to
1413 SETPGNO(NODEPTR(mc->mc_pg[mc->mc_top-1], mc->mc_ki[mc->mc_top-1]), mp->mp_pgno);
1415 mc->mc_db->md_root = mp->mp_pgno;
1416 } else if (mc->mc_txn->mt_parent) {
1419 /* If txn has a parent, make sure the page is in our
1422 if (mc->mc_txn->mt_u.dirty_list[0].mid) {
1423 unsigned x = mdb_mid2l_search(mc->mc_txn->mt_u.dirty_list, mp->mp_pgno);
1424 if (x <= mc->mc_txn->mt_u.dirty_list[0].mid &&
1425 mc->mc_txn->mt_u.dirty_list[x].mid == mp->mp_pgno) {
1426 if (mc->mc_txn->mt_u.dirty_list[x].mptr != mp) {
1427 mp = mc->mc_txn->mt_u.dirty_list[x].mptr;
1428 mc->mc_pg[mc->mc_top] = mp;
1434 np = mdb_page_malloc(mc);
1435 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1436 mid.mid = np->mp_pgno;
1438 mdb_mid2l_insert(mc->mc_txn->mt_u.dirty_list, &mid);
1446 mdb_env_sync(MDB_env *env, int force)
1449 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1450 if (MDB_FDATASYNC(env->me_fd))
1456 /** Make shadow copies of all of parent txn's cursors */
1458 mdb_cursor_shadow(MDB_txn *src, MDB_txn *dst)
1460 MDB_cursor *mc, *m2;
1461 unsigned int i, j, size;
1463 for (i=0;i<src->mt_numdbs; i++) {
1464 if (src->mt_cursors[i]) {
1465 size = sizeof(MDB_cursor);
1466 if (src->mt_cursors[i]->mc_xcursor)
1467 size += sizeof(MDB_xcursor);
1468 for (m2 = src->mt_cursors[i]; m2; m2=m2->mc_next) {
1475 mc->mc_db = &dst->mt_dbs[i];
1476 mc->mc_dbx = m2->mc_dbx;
1477 mc->mc_dbflag = &dst->mt_dbflags[i];
1478 mc->mc_snum = m2->mc_snum;
1479 mc->mc_top = m2->mc_top;
1480 mc->mc_flags = m2->mc_flags | C_SHADOW;
1481 for (j=0; j<mc->mc_snum; j++) {
1482 mc->mc_pg[j] = m2->mc_pg[j];
1483 mc->mc_ki[j] = m2->mc_ki[j];
1485 if (m2->mc_xcursor) {
1486 MDB_xcursor *mx, *mx2;
1487 mx = (MDB_xcursor *)(mc+1);
1488 mc->mc_xcursor = mx;
1489 mx2 = m2->mc_xcursor;
1490 mx->mx_db = mx2->mx_db;
1491 mx->mx_dbx = mx2->mx_dbx;
1492 mx->mx_dbflag = mx2->mx_dbflag;
1493 mx->mx_cursor.mc_txn = dst;
1494 mx->mx_cursor.mc_dbi = mx2->mx_cursor.mc_dbi;
1495 mx->mx_cursor.mc_db = &mx->mx_db;
1496 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
1497 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
1498 mx->mx_cursor.mc_snum = mx2->mx_cursor.mc_snum;
1499 mx->mx_cursor.mc_top = mx2->mx_cursor.mc_top;
1500 mx->mx_cursor.mc_flags = mx2->mx_cursor.mc_flags | C_SHADOW;
1501 for (j=0; j<mx2->mx_cursor.mc_snum; j++) {
1502 mx->mx_cursor.mc_pg[j] = mx2->mx_cursor.mc_pg[j];
1503 mx->mx_cursor.mc_ki[j] = mx2->mx_cursor.mc_ki[j];
1506 mc->mc_xcursor = NULL;
1508 mc->mc_next = dst->mt_cursors[i];
1509 dst->mt_cursors[i] = mc;
1516 /** Merge shadow cursors back into parent's */
1518 mdb_cursor_merge(MDB_txn *txn)
1521 for (i=0; i<txn->mt_numdbs; i++) {
1522 if (txn->mt_cursors[i]) {
1524 while ((mc = txn->mt_cursors[i])) {
1525 txn->mt_cursors[i] = mc->mc_next;
1526 if (mc->mc_flags & C_SHADOW) {
1527 MDB_cursor *m2 = mc->mc_orig;
1529 m2->mc_snum = mc->mc_snum;
1530 m2->mc_top = mc->mc_top;
1531 for (j=0; j<mc->mc_snum; j++) {
1532 m2->mc_pg[j] = mc->mc_pg[j];
1533 m2->mc_ki[j] = mc->mc_ki[j];
1536 if (mc->mc_flags & C_ALLOCD)
1544 mdb_txn_reset0(MDB_txn *txn);
1546 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
1547 * @param[in] txn the transaction handle to initialize
1548 * @return 0 on success, non-zero on failure. This can only
1549 * fail for read-only transactions, and then only if the
1550 * reader table is full.
1553 mdb_txn_renew0(MDB_txn *txn)
1555 MDB_env *env = txn->mt_env;
1559 txn->mt_numdbs = env->me_numdbs;
1560 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
1562 if (txn->mt_flags & MDB_TXN_RDONLY) {
1563 MDB_reader *r = pthread_getspecific(env->me_txkey);
1565 pid_t pid = getpid();
1566 pthread_t tid = pthread_self();
1569 for (i=0; i<env->me_txns->mti_numreaders; i++)
1570 if (env->me_txns->mti_readers[i].mr_pid == 0)
1572 if (i == env->me_maxreaders) {
1573 UNLOCK_MUTEX_R(env);
1576 env->me_txns->mti_readers[i].mr_pid = pid;
1577 env->me_txns->mti_readers[i].mr_tid = tid;
1578 if (i >= env->me_txns->mti_numreaders)
1579 env->me_txns->mti_numreaders = i+1;
1580 UNLOCK_MUTEX_R(env);
1581 r = &env->me_txns->mti_readers[i];
1582 pthread_setspecific(env->me_txkey, r);
1584 txn->mt_txnid = r->mr_txnid = env->me_txns->mti_txnid;
1585 txn->mt_toggle = txn->mt_txnid & 1;
1586 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1587 txn->mt_u.reader = r;
1591 txn->mt_txnid = env->me_txns->mti_txnid;
1592 txn->mt_toggle = txn->mt_txnid & 1;
1593 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1596 if (txn->mt_txnid == mdb_debug_start)
1599 txn->mt_u.dirty_list = env->me_dirty_list;
1600 txn->mt_u.dirty_list[0].mid = 0;
1601 txn->mt_free_pgs = env->me_free_pgs;
1602 txn->mt_free_pgs[0] = 0;
1606 /* Copy the DB info and flags */
1607 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
1608 for (i=2; i<txn->mt_numdbs; i++)
1609 txn->mt_dbs[i].md_flags = env->me_dbflags[i];
1610 txn->mt_dbflags[0] = txn->mt_dbflags[1] = 0;
1611 if (txn->mt_numdbs > 2)
1612 memset(txn->mt_dbflags+2, DB_STALE, txn->mt_numdbs-2);
1618 mdb_txn_renew(MDB_txn *txn)
1625 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
1626 DPUTS("environment had fatal error, must shutdown!");
1630 rc = mdb_txn_renew0(txn);
1631 if (rc == MDB_SUCCESS) {
1632 DPRINTF("renew txn %zu%c %p on mdbenv %p, root page %zu",
1633 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1634 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1640 mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **ret)
1645 if (env->me_flags & MDB_FATAL_ERROR) {
1646 DPUTS("environment had fatal error, must shutdown!");
1650 /* parent already has an active child txn */
1651 if (parent->mt_child) {
1655 size = sizeof(MDB_txn) + env->me_maxdbs * (sizeof(MDB_db)+1);
1656 if (!(flags & MDB_RDONLY))
1657 size += env->me_maxdbs * sizeof(MDB_cursor *);
1659 if ((txn = calloc(1, size)) == NULL) {
1660 DPRINTF("calloc: %s", strerror(ErrCode()));
1663 txn->mt_dbs = (MDB_db *)(txn+1);
1664 if (flags & MDB_RDONLY) {
1665 txn->mt_flags |= MDB_TXN_RDONLY;
1666 txn->mt_dbflags = (unsigned char *)(txn->mt_dbs + env->me_maxdbs);
1668 txn->mt_cursors = (MDB_cursor **)(txn->mt_dbs + env->me_maxdbs);
1669 txn->mt_dbflags = (unsigned char *)(txn->mt_cursors + env->me_maxdbs);
1674 txn->mt_free_pgs = mdb_midl_alloc();
1675 if (!txn->mt_free_pgs) {
1679 txn->mt_u.dirty_list = malloc(sizeof(MDB_ID2)*MDB_IDL_UM_SIZE);
1680 if (!txn->mt_u.dirty_list) {
1681 free(txn->mt_free_pgs);
1685 txn->mt_txnid = parent->mt_txnid;
1686 txn->mt_toggle = parent->mt_toggle;
1687 txn->mt_u.dirty_list[0].mid = 0;
1688 txn->mt_free_pgs[0] = 0;
1689 txn->mt_next_pgno = parent->mt_next_pgno;
1690 parent->mt_child = txn;
1691 txn->mt_parent = parent;
1692 txn->mt_numdbs = parent->mt_numdbs;
1693 txn->mt_dbxs = parent->mt_dbxs;
1694 memcpy(txn->mt_dbs, parent->mt_dbs, txn->mt_numdbs * sizeof(MDB_db));
1695 memcpy(txn->mt_dbflags, parent->mt_dbflags, txn->mt_numdbs);
1696 mdb_cursor_shadow(parent, txn);
1699 rc = mdb_txn_renew0(txn);
1705 DPRINTF("begin txn %zu%c %p on mdbenv %p, root page %zu",
1706 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1707 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
1713 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
1714 * @param[in] txn the transaction handle to reset
1717 mdb_txn_reset0(MDB_txn *txn)
1719 MDB_env *env = txn->mt_env;
1721 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1722 txn->mt_u.reader->mr_txnid = 0;
1728 /* close(free) all cursors */
1729 for (i=0; i<txn->mt_numdbs; i++) {
1730 if (txn->mt_cursors[i]) {
1732 while ((mc = txn->mt_cursors[i])) {
1733 txn->mt_cursors[i] = mc->mc_next;
1734 if (mc->mc_flags & C_ALLOCD)
1740 /* return all dirty pages to dpage list */
1741 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1742 dp = txn->mt_u.dirty_list[i].mptr;
1743 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1744 dp->mp_next = txn->mt_env->me_dpages;
1745 VGMEMP_FREE(txn->mt_env, dp);
1746 txn->mt_env->me_dpages = dp;
1748 /* large pages just get freed directly */
1749 VGMEMP_FREE(txn->mt_env, dp);
1754 if (txn->mt_parent) {
1755 txn->mt_parent->mt_child = NULL;
1756 free(txn->mt_free_pgs);
1757 free(txn->mt_u.dirty_list);
1760 if (mdb_midl_shrink(&txn->mt_free_pgs))
1761 env->me_free_pgs = txn->mt_free_pgs;
1764 while ((mop = txn->mt_env->me_pghead)) {
1765 txn->mt_env->me_pghead = mop->mo_next;
1768 txn->mt_env->me_pgfirst = 0;
1769 txn->mt_env->me_pglast = 0;
1772 /* The writer mutex was locked in mdb_txn_begin. */
1773 UNLOCK_MUTEX_W(env);
1778 mdb_txn_reset(MDB_txn *txn)
1783 DPRINTF("reset txn %zu%c %p on mdbenv %p, root page %zu",
1784 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1785 (void *) txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1787 mdb_txn_reset0(txn);
1791 mdb_txn_abort(MDB_txn *txn)
1796 DPRINTF("abort txn %zu%c %p on mdbenv %p, root page %zu",
1797 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1798 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1801 mdb_txn_abort(txn->mt_child);
1803 mdb_txn_reset0(txn);
1808 mdb_txn_commit(MDB_txn *txn)
1816 pgno_t next, freecnt;
1819 assert(txn != NULL);
1820 assert(txn->mt_env != NULL);
1822 if (txn->mt_child) {
1823 mdb_txn_commit(txn->mt_child);
1824 txn->mt_child = NULL;
1829 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1830 if (txn->mt_numdbs > env->me_numdbs) {
1831 /* update the DB flags */
1833 for (i = env->me_numdbs; i<txn->mt_numdbs; i++)
1834 env->me_dbflags[i] = txn->mt_dbs[i].md_flags;
1841 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1842 DPUTS("error flag is set, can't commit");
1844 txn->mt_parent->mt_flags |= MDB_TXN_ERROR;
1849 /* Merge (and close) our cursors with parent's */
1850 mdb_cursor_merge(txn);
1852 if (txn->mt_parent) {
1858 /* Update parent's DB table */
1859 ip = &txn->mt_parent->mt_dbs[2];
1860 jp = &txn->mt_dbs[2];
1861 for (i = 2; i < txn->mt_numdbs; i++) {
1862 if (ip->md_root != jp->md_root)
1866 txn->mt_parent->mt_numdbs = txn->mt_numdbs;
1868 /* Append our free list to parent's */
1869 mdb_midl_append_list(&txn->mt_parent->mt_free_pgs,
1871 mdb_midl_free(txn->mt_free_pgs);
1873 /* Merge our dirty list with parent's */
1874 dst = txn->mt_parent->mt_u.dirty_list;
1875 src = txn->mt_u.dirty_list;
1876 x = mdb_mid2l_search(dst, src[1].mid);
1877 for (y=1; y<=src[0].mid; y++) {
1878 while (x <= dst[0].mid && dst[x].mid != src[y].mid) x++;
1882 dst[x].mptr = src[y].mptr;
1885 for (; y<=src[0].mid; y++) {
1886 if (++x >= MDB_IDL_UM_MAX) {
1893 free(txn->mt_u.dirty_list);
1894 txn->mt_parent->mt_child = NULL;
1899 if (txn != env->me_txn) {
1900 DPUTS("attempt to commit unknown transaction");
1905 if (!txn->mt_u.dirty_list[0].mid)
1908 DPRINTF("committing txn %zu %p on mdbenv %p, root page %zu",
1909 txn->mt_txnid, (void *)txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
1911 /* Update DB root pointers. Their pages have already been
1912 * touched so this is all in-place and cannot fail.
1914 if (txn->mt_numdbs > 2) {
1917 data.mv_size = sizeof(MDB_db);
1919 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
1920 for (i = 2; i < txn->mt_numdbs; i++) {
1921 if (txn->mt_dbflags[i] & DB_DIRTY) {
1922 data.mv_data = &txn->mt_dbs[i];
1923 mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
1928 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1930 /* should only be one record now */
1931 if (env->me_pghead) {
1932 /* make sure first page of freeDB is touched and on freelist */
1933 mdb_page_search(&mc, NULL, MDB_PS_MODIFY);
1936 /* Delete IDLs we used from the free list */
1937 if (env->me_pgfirst) {
1942 key.mv_size = sizeof(cur);
1943 for (cur = env->me_pgfirst; cur <= env->me_pglast; cur++) {
1946 mdb_cursor_set(&mc, &key, NULL, MDB_SET, &exact);
1947 rc = mdb_cursor_del(&mc, 0);
1953 env->me_pgfirst = 0;
1957 /* save to free list */
1959 freecnt = txn->mt_free_pgs[0];
1960 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
1963 /* make sure last page of freeDB is touched and on freelist */
1964 key.mv_size = MAXKEYSIZE+1;
1966 mdb_page_search(&mc, &key, MDB_PS_MODIFY);
1968 mdb_midl_sort(txn->mt_free_pgs);
1972 MDB_IDL idl = txn->mt_free_pgs;
1973 DPRINTF("IDL write txn %zu root %zu num %zu",
1974 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1975 for (i=0; i<idl[0]; i++) {
1976 DPRINTF("IDL %zu", idl[i+1]);
1980 /* write to last page of freeDB */
1981 key.mv_size = sizeof(pgno_t);
1982 key.mv_data = &txn->mt_txnid;
1983 data.mv_data = txn->mt_free_pgs;
1984 /* The free list can still grow during this call,
1985 * despite the pre-emptive touches above. So check
1986 * and make sure the entire thing got written.
1989 freecnt = txn->mt_free_pgs[0];
1990 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
1991 rc = mdb_cursor_put(&mc, &key, &data, 0);
1996 } while (freecnt != txn->mt_free_pgs[0]);
1998 /* should only be one record now */
2000 if (env->me_pghead) {
2006 mop = env->me_pghead;
2008 key.mv_size = sizeof(id);
2010 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
2011 data.mv_data = mop->mo_pages;
2012 orig = mop->mo_pages[0];
2013 /* These steps may grow the freelist again
2014 * due to freed overflow pages...
2016 mdb_cursor_put(&mc, &key, &data, 0);
2017 if (mop == env->me_pghead && env->me_pghead->mo_txnid == id) {
2018 /* could have been used again here */
2019 if (mop->mo_pages[0] != orig) {
2020 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
2021 data.mv_data = mop->mo_pages;
2023 mdb_cursor_put(&mc, &key, &data, 0);
2025 env->me_pghead = NULL;
2028 /* was completely used up */
2029 mdb_cursor_del(&mc, 0);
2033 env->me_pgfirst = 0;
2037 while (env->me_pgfree) {
2038 MDB_oldpages *mop = env->me_pgfree;
2039 env->me_pgfree = mop->mo_next;
2043 /* Check for growth of freelist again */
2044 if (freecnt != txn->mt_free_pgs[0])
2047 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
2048 if (mdb_midl_shrink(&txn->mt_free_pgs))
2049 env->me_free_pgs = txn->mt_free_pgs;
2056 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
2062 /* Windows actually supports scatter/gather I/O, but only on
2063 * unbuffered file handles. Since we're relying on the OS page
2064 * cache for all our data, that's self-defeating. So we just
2065 * write pages one at a time. We use the ov structure to set
2066 * the write offset, to at least save the overhead of a Seek
2070 memset(&ov, 0, sizeof(ov));
2071 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
2073 dp = txn->mt_u.dirty_list[i].mptr;
2074 DPRINTF("committing page %zu", dp->mp_pgno);
2075 size = dp->mp_pgno * env->me_psize;
2076 ov.Offset = size & 0xffffffff;
2077 ov.OffsetHigh = size >> 16;
2078 ov.OffsetHigh >>= 16;
2079 /* clear dirty flag */
2080 dp->mp_flags &= ~P_DIRTY;
2081 wsize = env->me_psize;
2082 if (IS_OVERFLOW(dp)) wsize *= dp->mp_pages;
2083 rc = WriteFile(env->me_fd, dp, wsize, NULL, &ov);
2086 DPRINTF("WriteFile: %d", n);
2093 struct iovec iov[MDB_COMMIT_PAGES];
2097 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
2098 dp = txn->mt_u.dirty_list[i].mptr;
2099 if (dp->mp_pgno != next) {
2101 rc = writev(env->me_fd, iov, n);
2105 DPUTS("short write, filesystem full?");
2107 DPRINTF("writev: %s", strerror(n));
2114 lseek(env->me_fd, dp->mp_pgno * env->me_psize, SEEK_SET);
2117 DPRINTF("committing page %zu", dp->mp_pgno);
2118 iov[n].iov_len = env->me_psize;
2119 if (IS_OVERFLOW(dp)) iov[n].iov_len *= dp->mp_pages;
2120 iov[n].iov_base = (char *)dp;
2121 size += iov[n].iov_len;
2122 next = dp->mp_pgno + (IS_OVERFLOW(dp) ? dp->mp_pages : 1);
2123 /* clear dirty flag */
2124 dp->mp_flags &= ~P_DIRTY;
2125 if (++n >= MDB_COMMIT_PAGES) {
2135 rc = writev(env->me_fd, iov, n);
2139 DPUTS("short write, filesystem full?");
2141 DPRINTF("writev: %s", strerror(n));
2148 /* Drop the dirty pages.
2150 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
2151 dp = txn->mt_u.dirty_list[i].mptr;
2152 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
2153 dp->mp_next = txn->mt_env->me_dpages;
2154 VGMEMP_FREE(txn->mt_env, dp);
2155 txn->mt_env->me_dpages = dp;
2157 VGMEMP_FREE(txn->mt_env, dp);
2160 txn->mt_u.dirty_list[i].mid = 0;
2162 txn->mt_u.dirty_list[0].mid = 0;
2164 if ((n = mdb_env_sync(env, 0)) != 0 ||
2165 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
2172 if (txn->mt_numdbs > env->me_numdbs) {
2173 /* update the DB flags */
2175 for (i = env->me_numdbs; i<txn->mt_numdbs; i++)
2176 env->me_dbflags[i] = txn->mt_dbs[i].md_flags;
2180 UNLOCK_MUTEX_W(env);
2186 /** Read the environment parameters of a DB environment before
2187 * mapping it into memory.
2188 * @param[in] env the environment handle
2189 * @param[out] meta address of where to store the meta information
2190 * @return 0 on success, non-zero on failure.
2193 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
2200 /* We don't know the page size yet, so use a minimum value.
2204 if (!ReadFile(env->me_fd, &pbuf, MDB_PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
2206 if ((rc = read(env->me_fd, &pbuf, MDB_PAGESIZE)) == 0)
2211 else if (rc != MDB_PAGESIZE) {
2215 DPRINTF("read: %s", strerror(err));
2219 p = (MDB_page *)&pbuf;
2221 if (!F_ISSET(p->mp_flags, P_META)) {
2222 DPRINTF("page %zu not a meta page", p->mp_pgno);
2227 if (m->mm_magic != MDB_MAGIC) {
2228 DPUTS("meta has invalid magic");
2232 if (m->mm_version != MDB_VERSION) {
2233 DPRINTF("database is version %u, expected version %u",
2234 m->mm_version, MDB_VERSION);
2235 return MDB_VERSION_MISMATCH;
2238 memcpy(meta, m, sizeof(*m));
2242 /** Write the environment parameters of a freshly created DB environment.
2243 * @param[in] env the environment handle
2244 * @param[out] meta address of where to store the meta information
2245 * @return 0 on success, non-zero on failure.
2248 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
2255 DPUTS("writing new meta page");
2257 GET_PAGESIZE(psize);
2259 meta->mm_magic = MDB_MAGIC;
2260 meta->mm_version = MDB_VERSION;
2261 meta->mm_psize = psize;
2262 meta->mm_last_pg = 1;
2263 meta->mm_flags = env->me_flags & 0xffff;
2264 meta->mm_flags |= MDB_INTEGERKEY;
2265 meta->mm_dbs[0].md_root = P_INVALID;
2266 meta->mm_dbs[1].md_root = P_INVALID;
2268 p = calloc(2, psize);
2270 p->mp_flags = P_META;
2273 memcpy(m, meta, sizeof(*meta));
2275 q = (MDB_page *)((char *)p + psize);
2278 q->mp_flags = P_META;
2281 memcpy(m, meta, sizeof(*meta));
2286 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
2287 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
2290 rc = write(env->me_fd, p, psize * 2);
2291 rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
2297 /** Update the environment info to commit a transaction.
2298 * @param[in] txn the transaction that's being committed
2299 * @return 0 on success, non-zero on failure.
2302 mdb_env_write_meta(MDB_txn *txn)
2305 MDB_meta meta, metab;
2307 int rc, len, toggle;
2313 assert(txn != NULL);
2314 assert(txn->mt_env != NULL);
2316 toggle = !txn->mt_toggle;
2317 DPRINTF("writing meta page %d for root page %zu",
2318 toggle, txn->mt_dbs[MAIN_DBI].md_root);
2322 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
2323 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
2325 ptr = (char *)&meta;
2326 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
2327 len = sizeof(MDB_meta) - off;
2330 meta.mm_dbs[0] = txn->mt_dbs[0];
2331 meta.mm_dbs[1] = txn->mt_dbs[1];
2332 meta.mm_last_pg = txn->mt_next_pgno - 1;
2333 meta.mm_txnid = txn->mt_txnid;
2336 off += env->me_psize;
2339 /* Write to the SYNC fd */
2342 memset(&ov, 0, sizeof(ov));
2344 WriteFile(env->me_mfd, ptr, len, (DWORD *)&rc, &ov);
2347 rc = pwrite(env->me_mfd, ptr, len, off);
2352 DPUTS("write failed, disk error?");
2353 /* On a failure, the pagecache still contains the new data.
2354 * Write some old data back, to prevent it from being used.
2355 * Use the non-SYNC fd; we know it will fail anyway.
2357 meta.mm_last_pg = metab.mm_last_pg;
2358 meta.mm_txnid = metab.mm_txnid;
2360 WriteFile(env->me_fd, ptr, len, NULL, &ov);
2362 r2 = pwrite(env->me_fd, ptr, len, off);
2364 env->me_flags |= MDB_FATAL_ERROR;
2367 /* Memory ordering issues are irrelevant; since the entire writer
2368 * is wrapped by wmutex, all of these changes will become visible
2369 * after the wmutex is unlocked. Since the DB is multi-version,
2370 * readers will get consistent data regardless of how fresh or
2371 * how stale their view of these values is.
2373 txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
2378 /** Check both meta pages to see which one is newer.
2379 * @param[in] env the environment handle
2380 * @return meta toggle (0 or 1).
2383 mdb_env_pick_meta(const MDB_env *env)
2385 return (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid);
2389 mdb_env_create(MDB_env **env)
2393 e = calloc(1, sizeof(MDB_env));
2397 e->me_free_pgs = mdb_midl_alloc();
2398 if (!e->me_free_pgs) {
2402 e->me_maxreaders = DEFAULT_READERS;
2404 e->me_fd = INVALID_HANDLE_VALUE;
2405 e->me_lfd = INVALID_HANDLE_VALUE;
2406 e->me_mfd = INVALID_HANDLE_VALUE;
2407 VGMEMP_CREATE(e,0,0);
2413 mdb_env_set_mapsize(MDB_env *env, size_t size)
2417 env->me_mapsize = size;
2419 env->me_maxpg = env->me_mapsize / env->me_psize;
2424 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
2428 env->me_maxdbs = dbs;
2433 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
2435 if (env->me_map || readers < 1)
2437 env->me_maxreaders = readers;
2442 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
2444 if (!env || !readers)
2446 *readers = env->me_maxreaders;
2450 /** Further setup required for opening an MDB environment
2453 mdb_env_open2(MDB_env *env, unsigned int flags)
2459 env->me_flags = flags;
2461 memset(&meta, 0, sizeof(meta));
2463 if ((i = mdb_env_read_header(env, &meta)) != 0) {
2466 DPUTS("new mdbenv");
2470 if (!env->me_mapsize) {
2471 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
2477 LONG sizelo, sizehi;
2478 sizelo = env->me_mapsize & 0xffffffff;
2479 sizehi = env->me_mapsize >> 16; /* pointless on WIN32, only needed on W64 */
2481 /* Windows won't create mappings for zero length files.
2482 * Just allocate the maxsize right now.
2485 SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
2486 if (!SetEndOfFile(env->me_fd))
2488 SetFilePointer(env->me_fd, 0, NULL, 0);
2490 mh = CreateFileMapping(env->me_fd, NULL, PAGE_READONLY,
2491 sizehi, sizelo, NULL);
2494 env->me_map = MapViewOfFileEx(mh, FILE_MAP_READ, 0, 0, env->me_mapsize,
2502 if (meta.mm_address && (flags & MDB_FIXEDMAP))
2504 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
2506 if (env->me_map == MAP_FAILED) {
2513 meta.mm_mapsize = env->me_mapsize;
2514 if (flags & MDB_FIXEDMAP)
2515 meta.mm_address = env->me_map;
2516 i = mdb_env_init_meta(env, &meta);
2517 if (i != MDB_SUCCESS) {
2518 munmap(env->me_map, env->me_mapsize);
2522 env->me_psize = meta.mm_psize;
2524 env->me_maxpg = env->me_mapsize / env->me_psize;
2526 p = (MDB_page *)env->me_map;
2527 env->me_metas[0] = METADATA(p);
2528 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
2532 int toggle = mdb_env_pick_meta(env);
2533 MDB_db *db = &env->me_metas[toggle]->mm_dbs[MAIN_DBI];
2535 DPRINTF("opened database version %u, pagesize %u",
2536 env->me_metas[0]->mm_version, env->me_psize);
2537 DPRINTF("using meta page %d", toggle);
2538 DPRINTF("depth: %u", db->md_depth);
2539 DPRINTF("entries: %zu", db->md_entries);
2540 DPRINTF("branch pages: %zu", db->md_branch_pages);
2541 DPRINTF("leaf pages: %zu", db->md_leaf_pages);
2542 DPRINTF("overflow pages: %zu", db->md_overflow_pages);
2543 DPRINTF("root: %zu", db->md_root);
2551 /** Release a reader thread's slot in the reader lock table.
2552 * This function is called automatically when a thread exits.
2553 * @param[in] ptr This points to the slot in the reader lock table.
2556 mdb_env_reader_dest(void *ptr)
2558 MDB_reader *reader = ptr;
2560 reader->mr_txnid = 0;
2566 /** Junk for arranging thread-specific callbacks on Windows. This is
2567 * necessarily platform and compiler-specific. Windows supports up
2568 * to 1088 keys. Let's assume nobody opens more than 64 environments
2569 * in a single process, for now. They can override this if needed.
2571 #ifndef MAX_TLS_KEYS
2572 #define MAX_TLS_KEYS 64
2574 static pthread_key_t mdb_tls_keys[MAX_TLS_KEYS];
2575 static int mdb_tls_nkeys;
2577 static void NTAPI mdb_tls_callback(PVOID module, DWORD reason, PVOID ptr)
2581 case DLL_PROCESS_ATTACH: break;
2582 case DLL_THREAD_ATTACH: break;
2583 case DLL_THREAD_DETACH:
2584 for (i=0; i<mdb_tls_nkeys; i++) {
2585 MDB_reader *r = pthread_getspecific(mdb_tls_keys[i]);
2586 mdb_env_reader_dest(r);
2589 case DLL_PROCESS_DETACH: break;
2594 const PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
2596 PIMAGE_TLS_CALLBACK mdb_tls_cbp __attribute__((section (".CRT$XLB"))) = mdb_tls_callback;
2600 /* Force some symbol references.
2601 * _tls_used forces the linker to create the TLS directory if not already done
2602 * mdb_tls_cbp prevents whole-program-optimizer from dropping the symbol.
2604 #pragma comment(linker, "/INCLUDE:_tls_used")
2605 #pragma comment(linker, "/INCLUDE:mdb_tls_cbp")
2606 #pragma const_seg(".CRT$XLB")
2607 extern const PIMAGE_TLS_CALLBACK mdb_tls_callback;
2608 const PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
2611 #pragma comment(linker, "/INCLUDE:__tls_used")
2612 #pragma comment(linker, "/INCLUDE:_mdb_tls_cbp")
2613 #pragma data_seg(".CRT$XLB")
2614 PIMAGE_TLS_CALLBACK mdb_tls_cbp = mdb_tls_callback;
2616 #endif /* WIN 32/64 */
2617 #endif /* !__GNUC__ */
2620 /** Downgrade the exclusive lock on the region back to shared */
2622 mdb_env_share_locks(MDB_env *env)
2624 int toggle = mdb_env_pick_meta(env);
2626 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
2631 /* First acquire a shared lock. The Unlock will
2632 * then release the existing exclusive lock.
2634 memset(&ov, 0, sizeof(ov));
2635 LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov);
2636 UnlockFile(env->me_lfd, 0, 0, 1, 0);
2640 struct flock lock_info;
2641 /* The shared lock replaces the existing lock */
2642 memset((void *)&lock_info, 0, sizeof(lock_info));
2643 lock_info.l_type = F_RDLCK;
2644 lock_info.l_whence = SEEK_SET;
2645 lock_info.l_start = 0;
2646 lock_info.l_len = 1;
2647 fcntl(env->me_lfd, F_SETLK, &lock_info);
2651 #if defined(_WIN32) || defined(USE_POSIX_SEM)
2653 * hash_64 - 64 bit Fowler/Noll/Vo-0 FNV-1a hash code
2655 * @(#) $Revision: 5.1 $
2656 * @(#) $Id: hash_64a.c,v 5.1 2009/06/30 09:01:38 chongo Exp $
2657 * @(#) $Source: /usr/local/src/cmd/fnv/RCS/hash_64a.c,v $
2659 * http://www.isthe.com/chongo/tech/comp/fnv/index.html
2663 * Please do not copyright this code. This code is in the public domain.
2665 * LANDON CURT NOLL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
2666 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
2667 * EVENT SHALL LANDON CURT NOLL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
2668 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
2669 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
2670 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
2671 * PERFORMANCE OF THIS SOFTWARE.
2674 * chongo <Landon Curt Noll> /\oo/\
2675 * http://www.isthe.com/chongo/
2677 * Share and Enjoy! :-)
2680 typedef unsigned long long mdb_hash_t;
2681 #define MDB_HASH_INIT ((mdb_hash_t)0xcbf29ce484222325ULL)
2683 /** perform a 64 bit Fowler/Noll/Vo FNV-1a hash on a buffer
2684 * @param[in] str string to hash
2685 * @param[in] hval initial value for hash
2686 * @return 64 bit hash
2688 * NOTE: To use the recommended 64 bit FNV-1a hash, use MDB_HASH_INIT as the
2689 * hval arg on the first call.
2692 mdb_hash_val(MDB_val *val, mdb_hash_t hval)
2694 unsigned char *s = (unsigned char *)val->mv_data; /* unsigned string */
2695 unsigned char *end = s + val->mv_size;
2697 * FNV-1a hash each octet of the string
2700 /* xor the bottom with the current octet */
2701 hval ^= (mdb_hash_t)*s++;
2703 /* multiply by the 64 bit FNV magic prime mod 2^64 */
2704 hval += (hval << 1) + (hval << 4) + (hval << 5) +
2705 (hval << 7) + (hval << 8) + (hval << 40);
2707 /* return our new hash value */
2711 /** Hash the string and output the hash in hex.
2712 * @param[in] str string to hash
2713 * @param[out] hexbuf an array of 17 chars to hold the hash
2716 mdb_hash_hex(MDB_val *val, char *hexbuf)
2719 mdb_hash_t h = mdb_hash_val(val, MDB_HASH_INIT);
2720 for (i=0; i<8; i++) {
2721 hexbuf += sprintf(hexbuf, "%02x", (unsigned int)h & 0xff);
2727 /** Open and/or initialize the lock region for the environment.
2728 * @param[in] env The MDB environment.
2729 * @param[in] lpath The pathname of the file used for the lock region.
2730 * @param[in] mode The Unix permissions for the file, if we create it.
2731 * @param[out] excl Set to true if we got an exclusive lock on the region.
2732 * @return 0 on success, non-zero on failure.
2735 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
2743 if ((env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
2744 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
2745 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
2749 /* Try to get exclusive lock. If we succeed, then
2750 * nobody is using the lock region and we should initialize it.
2753 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
2757 memset(&ov, 0, sizeof(ov));
2758 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
2764 size = GetFileSize(env->me_lfd, NULL);
2770 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1)
2772 /* Lose record locks when exec*() */
2773 if ((fdflags = fcntl(env->me_lfd, F_GETFD) | FD_CLOEXEC) >= 0)
2774 fcntl(env->me_lfd, F_SETFD, fdflags);
2776 #else /* O_CLOEXEC on Linux: Open file and set FD_CLOEXEC atomically */
2777 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT|O_CLOEXEC, mode)) == -1)
2781 /* Try to get exclusive lock. If we succeed, then
2782 * nobody is using the lock region and we should initialize it.
2785 struct flock lock_info;
2786 memset((void *)&lock_info, 0, sizeof(lock_info));
2787 lock_info.l_type = F_WRLCK;
2788 lock_info.l_whence = SEEK_SET;
2789 lock_info.l_start = 0;
2790 lock_info.l_len = 1;
2791 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
2795 lock_info.l_type = F_RDLCK;
2796 rc = fcntl(env->me_lfd, F_SETLKW, &lock_info);
2803 size = lseek(env->me_lfd, 0, SEEK_END);
2805 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
2806 if (size < rsize && *excl) {
2808 SetFilePointer(env->me_lfd, rsize, NULL, 0);
2809 if (!SetEndOfFile(env->me_lfd)) {
2814 if (ftruncate(env->me_lfd, rsize) != 0) {
2821 size = rsize - sizeof(MDB_txninfo);
2822 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
2827 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
2833 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
2835 if (!env->me_txns) {
2840 void *m = mmap(NULL, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
2842 if (m == MAP_FAILED) {
2843 env->me_txns = NULL;
2852 BY_HANDLE_FILE_INFORMATION stbuf;
2861 if (!mdb_sec_inited) {
2862 InitializeSecurityDescriptor(&mdb_null_sd,
2863 SECURITY_DESCRIPTOR_REVISION);
2864 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
2865 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2866 mdb_all_sa.bInheritHandle = FALSE;
2867 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
2870 GetFileInformationByHandle(env->me_lfd, &stbuf);
2871 idbuf.volume = stbuf.dwVolumeSerialNumber;
2872 idbuf.nhigh = stbuf.nFileIndexHigh;
2873 idbuf.nlow = stbuf.nFileIndexLow;
2874 val.mv_data = &idbuf;
2875 val.mv_size = sizeof(idbuf);
2876 mdb_hash_hex(&val, hexbuf);
2877 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%s", hexbuf);
2878 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
2879 if (!env->me_rmutex) {
2883 sprintf(env->me_txns->mti_wmname, "Global\\MDBw%s", hexbuf);
2884 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_wmname);
2885 if (!env->me_wmutex) {
2890 #ifdef USE_POSIX_SEM
2899 fstat(env->me_lfd, &stbuf);
2900 idbuf.dev = stbuf.st_dev;
2901 idbuf.ino = stbuf.st_ino;
2902 val.mv_data = &idbuf;
2903 val.mv_size = sizeof(idbuf);
2904 mdb_hash_hex(&val, hexbuf);
2905 sprintf(env->me_txns->mti_rmname, "/MDBr%s", hexbuf);
2906 if (sem_unlink(env->me_txns->mti_rmname)) {
2908 if (rc != ENOENT && rc != EINVAL)
2911 env->me_rmutex = sem_open(env->me_txns->mti_rmname, O_CREAT, mode, 1);
2912 if (!env->me_rmutex) {
2916 sprintf(env->me_txns->mti_wmname, "/MDBw%s", hexbuf);
2917 if (sem_unlink(env->me_txns->mti_wmname)) {
2919 if (rc != ENOENT && rc != EINVAL)
2922 env->me_wmutex = sem_open(env->me_txns->mti_wmname, O_CREAT, mode, 1);
2923 if (!env->me_wmutex) {
2927 #else /* USE_POSIX_SEM */
2928 pthread_mutexattr_t mattr;
2930 pthread_mutexattr_init(&mattr);
2931 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
2935 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
2936 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
2937 #endif /* USE_POSIX_SEM */
2939 env->me_txns->mti_version = MDB_VERSION;
2940 env->me_txns->mti_magic = MDB_MAGIC;
2941 env->me_txns->mti_txnid = 0;
2942 env->me_txns->mti_numreaders = 0;
2945 if (env->me_txns->mti_magic != MDB_MAGIC) {
2946 DPUTS("lock region has invalid magic");
2950 if (env->me_txns->mti_version != MDB_VERSION) {
2951 DPRINTF("lock region is version %u, expected version %u",
2952 env->me_txns->mti_version, MDB_VERSION);
2953 rc = MDB_VERSION_MISMATCH;
2957 if (rc != EACCES && rc != EAGAIN) {
2961 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
2962 if (!env->me_rmutex) {
2966 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
2967 if (!env->me_wmutex) {
2972 #ifdef USE_POSIX_SEM
2973 env->me_rmutex = sem_open(env->me_txns->mti_rmname, 0);
2974 if (!env->me_rmutex) {
2978 env->me_wmutex = sem_open(env->me_txns->mti_wmname, 0);
2979 if (!env->me_wmutex) {
2989 env->me_lfd = INVALID_HANDLE_VALUE;
2994 /** The name of the lock file in the DB environment */
2995 #define LOCKNAME "/lock.mdb"
2996 /** The name of the data file in the DB environment */
2997 #define DATANAME "/data.mdb"
2998 /** The suffix of the lock file when no subdir is used */
2999 #define LOCKSUFF "-lock"
3002 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
3004 int oflags, rc, len, excl;
3005 char *lpath, *dpath;
3008 if (flags & MDB_NOSUBDIR) {
3009 rc = len + sizeof(LOCKSUFF) + len + 1;
3011 rc = len + sizeof(LOCKNAME) + len + sizeof(DATANAME);
3016 if (flags & MDB_NOSUBDIR) {
3017 dpath = lpath + len + sizeof(LOCKSUFF);
3018 sprintf(lpath, "%s" LOCKSUFF, path);
3019 strcpy(dpath, path);
3021 dpath = lpath + len + sizeof(LOCKNAME);
3022 sprintf(lpath, "%s" LOCKNAME, path);
3023 sprintf(dpath, "%s" DATANAME, path);
3026 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
3031 if (F_ISSET(flags, MDB_RDONLY)) {
3032 oflags = GENERIC_READ;
3033 len = OPEN_EXISTING;
3035 oflags = GENERIC_READ|GENERIC_WRITE;
3038 mode = FILE_ATTRIBUTE_NORMAL;
3039 env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
3040 NULL, len, mode, NULL);
3042 if (F_ISSET(flags, MDB_RDONLY))
3045 oflags = O_RDWR | O_CREAT;
3047 env->me_fd = open(dpath, oflags, mode);
3049 if (env->me_fd == INVALID_HANDLE_VALUE) {
3054 if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
3055 if (flags & (MDB_RDONLY|MDB_NOSYNC|MDB_NOMETASYNC)) {
3056 env->me_mfd = env->me_fd;
3058 /* synchronous fd for meta writes */
3060 env->me_mfd = CreateFile(dpath, oflags,
3061 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, len,
3062 mode | FILE_FLAG_WRITE_THROUGH, NULL);
3064 env->me_mfd = open(dpath, oflags | MDB_DSYNC, mode);
3066 if (env->me_mfd == INVALID_HANDLE_VALUE) {
3071 env->me_path = strdup(path);
3072 DPRINTF("opened dbenv %p", (void *) env);
3073 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
3075 /* Windows TLS callbacks need help finding their TLS info. */
3076 if (mdb_tls_nkeys < MAX_TLS_KEYS)
3077 mdb_tls_keys[mdb_tls_nkeys++] = env->me_txkey;
3084 mdb_env_share_locks(env);
3086 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
3087 env->me_dbflags = calloc(env->me_maxdbs, sizeof(uint16_t));
3088 if (!env->me_dbxs || !env->me_dbflags)
3094 if (env->me_fd != INVALID_HANDLE_VALUE) {
3096 env->me_fd = INVALID_HANDLE_VALUE;
3098 if (env->me_lfd != INVALID_HANDLE_VALUE) {
3100 env->me_lfd = INVALID_HANDLE_VALUE;
3108 mdb_env_close(MDB_env *env)
3115 VGMEMP_DESTROY(env);
3116 while (env->me_dpages) {
3117 dp = env->me_dpages;
3118 VGMEMP_DEFINED(&dp->mp_next, sizeof(dp->mp_next));
3119 env->me_dpages = dp->mp_next;
3123 free(env->me_dbflags);
3127 pthread_key_delete(env->me_txkey);
3129 /* Delete our key from the global list */
3131 for (i=0; i<mdb_tls_nkeys; i++)
3132 if (mdb_tls_keys[i] == env->me_txkey) {
3133 mdb_tls_keys[i] = mdb_tls_keys[mdb_tls_nkeys-1];
3141 munmap(env->me_map, env->me_mapsize);
3143 if (env->me_mfd != env->me_fd)
3147 pid_t pid = getpid();
3149 for (i=0; i<env->me_txns->mti_numreaders; i++)
3150 if (env->me_txns->mti_readers[i].mr_pid == pid)
3151 env->me_txns->mti_readers[i].mr_pid = 0;
3152 munmap((void *)env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
3155 mdb_midl_free(env->me_free_pgs);
3159 /** Compare two items pointing at aligned size_t's */
3161 mdb_cmp_long(const MDB_val *a, const MDB_val *b)
3163 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
3164 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
3167 /** Compare two items pointing at aligned int's */
3169 mdb_cmp_int(const MDB_val *a, const MDB_val *b)
3171 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
3172 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
3175 /** Compare two items pointing at ints of unknown alignment.
3176 * Nodes and keys are guaranteed to be 2-byte aligned.
3179 mdb_cmp_cint(const MDB_val *a, const MDB_val *b)
3181 #if BYTE_ORDER == LITTLE_ENDIAN
3182 unsigned short *u, *c;
3185 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
3186 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
3189 } while(!x && u > (unsigned short *)a->mv_data);
3192 return memcmp(a->mv_data, b->mv_data, a->mv_size);
3196 /** Compare two items lexically */
3198 mdb_cmp_memn(const MDB_val *a, const MDB_val *b)
3205 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
3211 diff = memcmp(a->mv_data, b->mv_data, len);
3212 return diff ? diff : len_diff<0 ? -1 : len_diff;
3215 /** Compare two items in reverse byte order */
3217 mdb_cmp_memnr(const MDB_val *a, const MDB_val *b)
3219 const unsigned char *p1, *p2, *p1_lim;
3223 p1_lim = (const unsigned char *)a->mv_data;
3224 p1 = (const unsigned char *)a->mv_data + a->mv_size;
3225 p2 = (const unsigned char *)b->mv_data + b->mv_size;
3227 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
3233 while (p1 > p1_lim) {
3234 diff = *--p1 - *--p2;
3238 return len_diff<0 ? -1 : len_diff;
3241 /** Search for key within a page, using binary search.
3242 * Returns the smallest entry larger or equal to the key.
3243 * If exactp is non-null, stores whether the found entry was an exact match
3244 * in *exactp (1 or 0).
3245 * Updates the cursor index with the index of the found entry.
3246 * If no entry larger or equal to the key is found, returns NULL.
3249 mdb_node_search(MDB_cursor *mc, MDB_val *key, int *exactp)
3251 unsigned int i = 0, nkeys;
3254 MDB_page *mp = mc->mc_pg[mc->mc_top];
3255 MDB_node *node = NULL;
3260 nkeys = NUMKEYS(mp);
3265 COPY_PGNO(pgno, mp->mp_pgno);
3266 DPRINTF("searching %u keys in %s %spage %zu",
3267 nkeys, IS_LEAF(mp) ? "leaf" : "branch", IS_SUBP(mp) ? "sub-" : "",
3274 low = IS_LEAF(mp) ? 0 : 1;
3276 cmp = mc->mc_dbx->md_cmp;
3278 /* Branch pages have no data, so if using integer keys,
3279 * alignment is guaranteed. Use faster mdb_cmp_int.
3281 if (cmp == mdb_cmp_cint && IS_BRANCH(mp)) {
3282 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
3289 nodekey.mv_size = mc->mc_db->md_pad;
3290 node = NODEPTR(mp, 0); /* fake */
3291 while (low <= high) {
3292 i = (low + high) >> 1;
3293 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
3294 rc = cmp(key, &nodekey);
3295 DPRINTF("found leaf index %u [%s], rc = %i",
3296 i, DKEY(&nodekey), rc);
3305 while (low <= high) {
3306 i = (low + high) >> 1;
3308 node = NODEPTR(mp, i);
3309 nodekey.mv_size = NODEKSZ(node);
3310 nodekey.mv_data = NODEKEY(node);
3312 rc = cmp(key, &nodekey);
3315 DPRINTF("found leaf index %u [%s], rc = %i",
3316 i, DKEY(&nodekey), rc);
3318 DPRINTF("found branch index %u [%s -> %zu], rc = %i",
3319 i, DKEY(&nodekey), NODEPGNO(node), rc);
3330 if (rc > 0) { /* Found entry is less than the key. */
3331 i++; /* Skip to get the smallest entry larger than key. */
3333 node = NODEPTR(mp, i);
3336 *exactp = (rc == 0);
3337 /* store the key index */
3338 mc->mc_ki[mc->mc_top] = i;
3340 /* There is no entry larger or equal to the key. */
3343 /* nodeptr is fake for LEAF2 */
3349 mdb_cursor_adjust(MDB_cursor *mc, func)
3353 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
3354 if (m2->mc_pg[m2->mc_top] == mc->mc_pg[mc->mc_top]) {
3361 /** Pop a page off the top of the cursor's stack. */
3363 mdb_cursor_pop(MDB_cursor *mc)
3367 MDB_page *top = mc->mc_pg[mc->mc_top];
3373 DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
3374 mc->mc_dbi, (void *) mc);
3378 /** Push a page onto the top of the cursor's stack. */
3380 mdb_cursor_push(MDB_cursor *mc, MDB_page *mp)
3382 DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
3383 mc->mc_dbi, (void *) mc);
3385 if (mc->mc_snum >= CURSOR_STACK) {
3386 assert(mc->mc_snum < CURSOR_STACK);
3390 mc->mc_top = mc->mc_snum++;
3391 mc->mc_pg[mc->mc_top] = mp;
3392 mc->mc_ki[mc->mc_top] = 0;
3397 /** Find the address of the page corresponding to a given page number.
3398 * @param[in] txn the transaction for this access.
3399 * @param[in] pgno the page number for the page to retrieve.
3400 * @param[out] ret address of a pointer where the page's address will be stored.
3401 * @return 0 on success, non-zero on failure.
3404 mdb_page_get(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
3408 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
3410 x = mdb_mid2l_search(txn->mt_u.dirty_list, pgno);
3411 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
3412 p = txn->mt_u.dirty_list[x].mptr;
3416 if (pgno < txn->mt_next_pgno)
3417 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
3421 DPRINTF("page %zu not found", pgno);
3424 return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
3427 /** Search for the page a given key should be in.
3428 * Pushes parent pages on the cursor stack. This function continues a
3429 * search on a cursor that has already been initialized. (Usually by
3430 * #mdb_page_search() but also by #mdb_node_move().)
3431 * @param[in,out] mc the cursor for this operation.
3432 * @param[in] key the key to search for. If NULL, search for the lowest
3433 * page. (This is used by #mdb_cursor_first().)
3434 * @param[in] flags If MDB_PS_MODIFY set, visited pages are updated with new page numbers.
3435 * If MDB_PS_ROOTONLY set, just fetch root node, no further lookups.
3436 * @return 0 on success, non-zero on failure.
3439 mdb_page_search_root(MDB_cursor *mc, MDB_val *key, int modify)
3441 MDB_page *mp = mc->mc_pg[mc->mc_top];
3446 while (IS_BRANCH(mp)) {
3450 DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
3451 assert(NUMKEYS(mp) > 1);
3452 DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
3454 if (key == NULL) /* Initialize cursor to first page. */
3456 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
3457 /* cursor to last page */
3461 node = mdb_node_search(mc, key, &exact);
3463 i = NUMKEYS(mp) - 1;
3465 i = mc->mc_ki[mc->mc_top];
3474 DPRINTF("following index %u for key [%s]",
3476 assert(i < NUMKEYS(mp));
3477 node = NODEPTR(mp, i);
3479 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mp)))
3482 mc->mc_ki[mc->mc_top] = i;
3483 if ((rc = mdb_cursor_push(mc, mp)))
3487 if ((rc = mdb_page_touch(mc)) != 0)
3489 mp = mc->mc_pg[mc->mc_top];
3494 DPRINTF("internal error, index points to a %02X page!?",
3496 return MDB_CORRUPTED;
3499 DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
3500 key ? DKEY(key) : NULL);
3505 /** Search for the page a given key should be in.
3506 * Pushes parent pages on the cursor stack. This function just sets up
3507 * the search; it finds the root page for \b mc's database and sets this
3508 * as the root of the cursor's stack. Then #mdb_page_search_root() is
3509 * called to complete the search.
3510 * @param[in,out] mc the cursor for this operation.
3511 * @param[in] key the key to search for. If NULL, search for the lowest
3512 * page. (This is used by #mdb_cursor_first().)
3513 * @param[in] modify If true, visited pages are updated with new page numbers.
3514 * @return 0 on success, non-zero on failure.
3517 mdb_page_search(MDB_cursor *mc, MDB_val *key, int flags)
3522 /* Make sure the txn is still viable, then find the root from
3523 * the txn's db table.
3525 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
3526 DPUTS("transaction has failed, must abort");
3529 /* Make sure we're using an up-to-date root */
3530 if (mc->mc_dbi > MAIN_DBI) {
3531 if ((*mc->mc_dbflag & DB_STALE) ||
3532 ((flags & MDB_PS_MODIFY) && !(*mc->mc_dbflag & DB_DIRTY))) {
3534 unsigned char dbflag = 0;
3535 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
3536 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, flags & MDB_PS_MODIFY);
3539 if (*mc->mc_dbflag & DB_STALE) {
3542 MDB_node *leaf = mdb_node_search(&mc2,
3543 &mc->mc_dbx->md_name, &exact);
3545 return MDB_NOTFOUND;
3546 mdb_node_read(mc->mc_txn, leaf, &data);
3547 memcpy(mc->mc_db, data.mv_data, sizeof(MDB_db));
3549 if (flags & MDB_PS_MODIFY)
3551 *mc->mc_dbflag = dbflag;
3554 root = mc->mc_db->md_root;
3556 if (root == P_INVALID) { /* Tree is empty. */
3557 DPUTS("tree is empty");
3558 return MDB_NOTFOUND;
3563 if (!mc->mc_pg[0] || mc->mc_pg[0]->mp_pgno != root)
3564 if ((rc = mdb_page_get(mc->mc_txn, root, &mc->mc_pg[0])))
3570 DPRINTF("db %u root page %zu has flags 0x%X",
3571 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
3573 if (flags & MDB_PS_MODIFY) {
3574 if ((rc = mdb_page_touch(mc)))
3578 if (flags & MDB_PS_ROOTONLY)
3581 return mdb_page_search_root(mc, key, flags);
3584 /** Return the data associated with a given node.
3585 * @param[in] txn The transaction for this operation.
3586 * @param[in] leaf The node being read.
3587 * @param[out] data Updated to point to the node's data.
3588 * @return 0 on success, non-zero on failure.
3591 mdb_node_read(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
3593 MDB_page *omp; /* overflow page */
3597 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
3598 data->mv_size = NODEDSZ(leaf);
3599 data->mv_data = NODEDATA(leaf);
3603 /* Read overflow data.
3605 data->mv_size = NODEDSZ(leaf);
3606 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
3607 if ((rc = mdb_page_get(txn, pgno, &omp))) {
3608 DPRINTF("read overflow page %zu failed", pgno);
3611 data->mv_data = METADATA(omp);
3617 mdb_get(MDB_txn *txn, MDB_dbi dbi,
3618 MDB_val *key, MDB_val *data)
3627 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
3629 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3632 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3636 mdb_cursor_init(&mc, txn, dbi, &mx);
3637 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
3640 /** Find a sibling for a page.
3641 * Replaces the page at the top of the cursor's stack with the
3642 * specified sibling, if one exists.
3643 * @param[in] mc The cursor for this operation.
3644 * @param[in] move_right Non-zero if the right sibling is requested,
3645 * otherwise the left sibling.
3646 * @return 0 on success, non-zero on failure.
3649 mdb_cursor_sibling(MDB_cursor *mc, int move_right)
3655 if (mc->mc_snum < 2) {
3656 return MDB_NOTFOUND; /* root has no siblings */
3660 DPRINTF("parent page is page %zu, index %u",
3661 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]);
3663 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
3664 : (mc->mc_ki[mc->mc_top] == 0)) {
3665 DPRINTF("no more keys left, moving to %s sibling",
3666 move_right ? "right" : "left");
3667 if ((rc = mdb_cursor_sibling(mc, move_right)) != MDB_SUCCESS)
3671 mc->mc_ki[mc->mc_top]++;
3673 mc->mc_ki[mc->mc_top]--;
3674 DPRINTF("just moving to %s index key %u",
3675 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]);
3677 assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
3679 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3680 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(indx), &mp)))
3683 mdb_cursor_push(mc, mp);
3688 /** Move the cursor to the next data item. */
3690 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3696 if (mc->mc_flags & C_EOF) {
3697 return MDB_NOTFOUND;
3700 assert(mc->mc_flags & C_INITIALIZED);
3702 mp = mc->mc_pg[mc->mc_top];
3704 if (mc->mc_db->md_flags & MDB_DUPSORT) {
3705 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3706 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3707 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
3708 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
3709 if (op != MDB_NEXT || rc == MDB_SUCCESS)
3713 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3714 if (op == MDB_NEXT_DUP)
3715 return MDB_NOTFOUND;
3719 DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3721 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
3722 DPUTS("=====> move to next sibling page");
3723 if (mdb_cursor_sibling(mc, 1) != MDB_SUCCESS) {
3724 mc->mc_flags |= C_EOF;
3725 mc->mc_flags &= ~C_INITIALIZED;
3726 return MDB_NOTFOUND;
3728 mp = mc->mc_pg[mc->mc_top];
3729 DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3731 mc->mc_ki[mc->mc_top]++;
3733 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3734 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3737 key->mv_size = mc->mc_db->md_pad;
3738 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3742 assert(IS_LEAF(mp));
3743 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3745 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3746 mdb_xcursor_init1(mc, leaf);
3749 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3752 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3753 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3754 if (rc != MDB_SUCCESS)
3759 MDB_SET_KEY(leaf, key);
3763 /** Move the cursor to the previous data item. */
3765 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
3771 assert(mc->mc_flags & C_INITIALIZED);
3773 mp = mc->mc_pg[mc->mc_top];
3775 if (mc->mc_db->md_flags & MDB_DUPSORT) {
3776 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3777 if (op == MDB_PREV || op == MDB_PREV_DUP) {
3778 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3779 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
3780 if (op != MDB_PREV || rc == MDB_SUCCESS)
3783 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
3784 if (op == MDB_PREV_DUP)
3785 return MDB_NOTFOUND;
3790 DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
3792 if (mc->mc_ki[mc->mc_top] == 0) {
3793 DPUTS("=====> move to prev sibling page");
3794 if (mdb_cursor_sibling(mc, 0) != MDB_SUCCESS) {
3795 mc->mc_flags &= ~C_INITIALIZED;
3796 return MDB_NOTFOUND;
3798 mp = mc->mc_pg[mc->mc_top];
3799 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
3800 DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
3802 mc->mc_ki[mc->mc_top]--;
3804 mc->mc_flags &= ~C_EOF;
3806 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
3807 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
3810 key->mv_size = mc->mc_db->md_pad;
3811 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3815 assert(IS_LEAF(mp));
3816 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3818 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3819 mdb_xcursor_init1(mc, leaf);
3822 if ((rc = mdb_node_read(mc->mc_txn, leaf, data) != MDB_SUCCESS))
3825 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3826 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3827 if (rc != MDB_SUCCESS)
3832 MDB_SET_KEY(leaf, key);
3836 /** Set the cursor on a specific data item. */
3838 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3839 MDB_cursor_op op, int *exactp)
3843 MDB_node *leaf = NULL;
3848 assert(key->mv_size > 0);
3850 /* See if we're already on the right page */
3851 if (mc->mc_flags & C_INITIALIZED) {
3854 mp = mc->mc_pg[mc->mc_top];
3856 mc->mc_ki[mc->mc_top] = 0;
3857 return MDB_NOTFOUND;
3859 if (mp->mp_flags & P_LEAF2) {
3860 nodekey.mv_size = mc->mc_db->md_pad;
3861 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
3863 leaf = NODEPTR(mp, 0);
3864 MDB_SET_KEY(leaf, &nodekey);
3866 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3868 /* Probably happens rarely, but first node on the page
3869 * was the one we wanted.
3871 mc->mc_ki[mc->mc_top] = 0;
3878 unsigned int nkeys = NUMKEYS(mp);
3880 if (mp->mp_flags & P_LEAF2) {
3881 nodekey.mv_data = LEAF2KEY(mp,
3882 nkeys-1, nodekey.mv_size);
3884 leaf = NODEPTR(mp, nkeys-1);
3885 MDB_SET_KEY(leaf, &nodekey);
3887 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3889 /* last node was the one we wanted */
3890 mc->mc_ki[mc->mc_top] = nkeys-1;
3896 if (mc->mc_ki[mc->mc_top] < NUMKEYS(mp)) {
3897 /* This is definitely the right page, skip search_page */
3898 if (mp->mp_flags & P_LEAF2) {
3899 nodekey.mv_data = LEAF2KEY(mp,
3900 mc->mc_ki[mc->mc_top], nodekey.mv_size);
3902 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
3903 MDB_SET_KEY(leaf, &nodekey);
3905 rc = mc->mc_dbx->md_cmp(key, &nodekey);
3907 /* current node was the one we wanted */
3917 /* If any parents have right-sibs, search.
3918 * Otherwise, there's nothing further.
3920 for (i=0; i<mc->mc_top; i++)
3922 NUMKEYS(mc->mc_pg[i])-1)
3924 if (i == mc->mc_top) {
3925 /* There are no other pages */
3926 mc->mc_ki[mc->mc_top] = nkeys;
3927 return MDB_NOTFOUND;
3931 /* There are no other pages */
3932 mc->mc_ki[mc->mc_top] = 0;
3933 return MDB_NOTFOUND;
3937 rc = mdb_page_search(mc, key, 0);
3938 if (rc != MDB_SUCCESS)
3941 mp = mc->mc_pg[mc->mc_top];
3942 assert(IS_LEAF(mp));
3945 leaf = mdb_node_search(mc, key, exactp);
3946 if (exactp != NULL && !*exactp) {
3947 /* MDB_SET specified and not an exact match. */
3948 return MDB_NOTFOUND;
3952 DPUTS("===> inexact leaf not found, goto sibling");
3953 if ((rc = mdb_cursor_sibling(mc, 1)) != MDB_SUCCESS)
3954 return rc; /* no entries matched */
3955 mp = mc->mc_pg[mc->mc_top];
3956 assert(IS_LEAF(mp));
3957 leaf = NODEPTR(mp, 0);
3961 mc->mc_flags |= C_INITIALIZED;
3962 mc->mc_flags &= ~C_EOF;
3965 key->mv_size = mc->mc_db->md_pad;
3966 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
3970 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3971 mdb_xcursor_init1(mc, leaf);
3974 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3975 if (op == MDB_SET || op == MDB_SET_RANGE) {
3976 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3979 if (op == MDB_GET_BOTH) {
3985 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
3986 if (rc != MDB_SUCCESS)
3989 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
3991 if ((rc = mdb_node_read(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
3993 rc = mc->mc_dbx->md_dcmp(data, &d2);
3995 if (op == MDB_GET_BOTH || rc > 0)
3996 return MDB_NOTFOUND;
4001 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
4002 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4007 /* The key already matches in all other cases */
4008 if (op == MDB_SET_RANGE)
4009 MDB_SET_KEY(leaf, key);
4010 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
4015 /** Move the cursor to the first item in the database. */
4017 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
4022 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
4023 rc = mdb_page_search(mc, NULL, 0);
4024 if (rc != MDB_SUCCESS)
4027 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
4029 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
4030 mc->mc_flags |= C_INITIALIZED;
4031 mc->mc_flags &= ~C_EOF;
4033 mc->mc_ki[mc->mc_top] = 0;
4035 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
4036 key->mv_size = mc->mc_db->md_pad;
4037 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
4042 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4043 mdb_xcursor_init1(mc, leaf);
4044 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4049 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
4050 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4054 MDB_SET_KEY(leaf, key);
4058 /** Move the cursor to the last item in the database. */
4060 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
4065 if (!(mc->mc_flags & C_EOF)) {
4067 if (!(mc->mc_flags & C_INITIALIZED) || mc->mc_top) {
4070 lkey.mv_size = MAXKEYSIZE+1;
4071 lkey.mv_data = NULL;
4072 rc = mdb_page_search(mc, &lkey, 0);
4073 if (rc != MDB_SUCCESS)
4076 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
4078 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
4079 mc->mc_flags |= C_INITIALIZED|C_EOF;
4081 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4083 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
4084 key->mv_size = mc->mc_db->md_pad;
4085 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
4090 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4091 mdb_xcursor_init1(mc, leaf);
4092 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
4097 mc->mc_xcursor->mx_cursor.mc_flags &= ~C_INITIALIZED;
4098 if ((rc = mdb_node_read(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
4103 MDB_SET_KEY(leaf, key);
4108 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
4118 case MDB_GET_BOTH_RANGE:
4119 if (data == NULL || mc->mc_xcursor == NULL) {
4126 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
4128 } else if (op == MDB_SET_RANGE)
4129 rc = mdb_cursor_set(mc, key, data, op, NULL);
4131 rc = mdb_cursor_set(mc, key, data, op, &exact);
4133 case MDB_GET_MULTIPLE:
4135 !(mc->mc_db->md_flags & MDB_DUPFIXED) ||
4136 !(mc->mc_flags & C_INITIALIZED)) {
4141 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
4142 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
4145 case MDB_NEXT_MULTIPLE:
4147 !(mc->mc_db->md_flags & MDB_DUPFIXED)) {
4151 if (!(mc->mc_flags & C_INITIALIZED))
4152 rc = mdb_cursor_first(mc, key, data);
4154 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
4155 if (rc == MDB_SUCCESS) {
4156 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
4159 mx = &mc->mc_xcursor->mx_cursor;
4160 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
4162 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
4163 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
4171 case MDB_NEXT_NODUP:
4172 if (!(mc->mc_flags & C_INITIALIZED))
4173 rc = mdb_cursor_first(mc, key, data);
4175 rc = mdb_cursor_next(mc, key, data, op);
4179 case MDB_PREV_NODUP:
4180 if (!(mc->mc_flags & C_INITIALIZED) || (mc->mc_flags & C_EOF)) {
4181 rc = mdb_cursor_last(mc, key, data);
4182 mc->mc_flags &= ~C_EOF;
4184 rc = mdb_cursor_prev(mc, key, data, op);
4187 rc = mdb_cursor_first(mc, key, data);
4191 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
4192 !(mc->mc_flags & C_INITIALIZED) ||
4193 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
4197 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
4200 rc = mdb_cursor_last(mc, key, data);
4204 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
4205 !(mc->mc_flags & C_INITIALIZED) ||
4206 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
4210 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
4213 DPRINTF("unhandled/unimplemented cursor operation %u", op);
4221 /** Touch all the pages in the cursor stack.
4222 * Makes sure all the pages are writable, before attempting a write operation.
4223 * @param[in] mc The cursor to operate on.
4226 mdb_cursor_touch(MDB_cursor *mc)
4230 if (mc->mc_dbi > MAIN_DBI && !(*mc->mc_dbflag & DB_DIRTY)) {
4232 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
4233 rc = mdb_page_search(&mc2, &mc->mc_dbx->md_name, MDB_PS_MODIFY);
4236 *mc->mc_dbflag = DB_DIRTY;
4238 for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
4239 rc = mdb_page_touch(mc);
4243 mc->mc_top = mc->mc_snum-1;
4248 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
4251 MDB_node *leaf = NULL;
4252 MDB_val xdata, *rdata, dkey;
4255 int do_sub = 0, insert = 0;
4256 unsigned int mcount = 0;
4260 char dbuf[MAXKEYSIZE+1];
4261 unsigned int nflags;
4264 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
4267 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
4268 mc->mc_dbi, DKEY(key), key ? key->mv_size:0, data->mv_size);
4272 if (flags == MDB_CURRENT) {
4273 if (!(mc->mc_flags & C_INITIALIZED))
4276 } else if (mc->mc_db->md_root == P_INVALID) {
4278 /* new database, write a root leaf page */
4279 DPUTS("allocating new root leaf page");
4280 if ((np = mdb_page_new(mc, P_LEAF, 1)) == NULL) {
4284 mdb_cursor_push(mc, np);
4285 mc->mc_db->md_root = np->mp_pgno;
4286 mc->mc_db->md_depth++;
4287 *mc->mc_dbflag = DB_DIRTY;
4288 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
4290 np->mp_flags |= P_LEAF2;
4291 mc->mc_flags |= C_INITIALIZED;
4297 if (flags & MDB_APPEND) {
4299 rc = mdb_cursor_last(mc, &k2, &d2);
4301 rc = mc->mc_dbx->md_cmp(key, &k2);
4304 mc->mc_ki[mc->mc_top]++;
4310 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
4312 if ((flags & MDB_NOOVERWRITE) && rc == 0) {
4313 DPRINTF("duplicate key [%s]", DKEY(key));
4315 return MDB_KEYEXIST;
4317 if (rc && rc != MDB_NOTFOUND)
4321 /* Cursor is positioned, now make sure all pages are writable */
4322 rc2 = mdb_cursor_touch(mc);
4327 /* The key already exists */
4328 if (rc == MDB_SUCCESS) {
4329 /* there's only a key anyway, so this is a no-op */
4330 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
4331 unsigned int ksize = mc->mc_db->md_pad;
4332 if (key->mv_size != ksize)
4334 if (flags == MDB_CURRENT) {
4335 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
4336 memcpy(ptr, key->mv_data, ksize);
4341 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4344 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
4345 /* Was a single item before, must convert now */
4347 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4348 /* Just overwrite the current item */
4349 if (flags == MDB_CURRENT)
4352 dkey.mv_size = NODEDSZ(leaf);
4353 dkey.mv_data = NODEDATA(leaf);
4354 #if UINT_MAX < SIZE_MAX
4355 if (mc->mc_dbx->md_dcmp == mdb_cmp_int && dkey.mv_size == sizeof(size_t))
4356 #ifdef MISALIGNED_OK
4357 mc->mc_dbx->md_dcmp = mdb_cmp_long;
4359 mc->mc_dbx->md_dcmp = mdb_cmp_cint;
4362 /* if data matches, ignore it */
4363 if (!mc->mc_dbx->md_dcmp(data, &dkey))
4364 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
4366 /* create a fake page for the dup items */
4367 memcpy(dbuf, dkey.mv_data, dkey.mv_size);
4368 dkey.mv_data = dbuf;
4369 fp = (MDB_page *)&pbuf;
4370 fp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4371 fp->mp_flags = P_LEAF|P_DIRTY|P_SUBP;
4372 fp->mp_lower = PAGEHDRSZ;
4373 fp->mp_upper = PAGEHDRSZ + dkey.mv_size + data->mv_size;
4374 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4375 fp->mp_flags |= P_LEAF2;
4376 fp->mp_pad = data->mv_size;
4377 fp->mp_upper += 2 * data->mv_size; /* leave space for 2 more */
4379 fp->mp_upper += 2 * sizeof(indx_t) + 2 * NODESIZE +
4380 (dkey.mv_size & 1) + (data->mv_size & 1);
4382 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4385 xdata.mv_size = fp->mp_upper;
4390 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
4391 /* See if we need to convert from fake page to subDB */
4393 unsigned int offset;
4396 fp = NODEDATA(leaf);
4397 if (flags == MDB_CURRENT) {
4399 fp->mp_flags |= P_DIRTY;
4400 COPY_PGNO(fp->mp_pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
4401 mc->mc_xcursor->mx_cursor.mc_pg[0] = fp;
4405 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4406 offset = fp->mp_pad;
4407 if (SIZELEFT(fp) >= offset)
4409 offset *= 4; /* space for 4 more */
4411 offset = NODESIZE + sizeof(indx_t) + data->mv_size;
4413 offset += offset & 1;
4414 if (NODESIZE + sizeof(indx_t) + NODEKSZ(leaf) + NODEDSZ(leaf) +
4415 offset >= (mc->mc_txn->mt_env->me_psize - PAGEHDRSZ) /
4417 /* yes, convert it */
4419 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
4420 dummy.md_pad = fp->mp_pad;
4421 dummy.md_flags = MDB_DUPFIXED;
4422 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
4423 dummy.md_flags |= MDB_INTEGERKEY;
4426 dummy.md_branch_pages = 0;
4427 dummy.md_leaf_pages = 1;
4428 dummy.md_overflow_pages = 0;
4429 dummy.md_entries = NUMKEYS(fp);
4431 xdata.mv_size = sizeof(MDB_db);
4432 xdata.mv_data = &dummy;
4433 mp = mdb_page_alloc(mc, 1);
4436 offset = mc->mc_txn->mt_env->me_psize - NODEDSZ(leaf);
4437 flags |= F_DUPDATA|F_SUBDATA;
4438 dummy.md_root = mp->mp_pgno;
4440 /* no, just grow it */
4442 xdata.mv_size = NODEDSZ(leaf) + offset;
4443 xdata.mv_data = &pbuf;
4444 mp = (MDB_page *)&pbuf;
4445 mp->mp_pgno = mc->mc_pg[mc->mc_top]->mp_pgno;
4448 mp->mp_flags = fp->mp_flags | P_DIRTY;
4449 mp->mp_pad = fp->mp_pad;
4450 mp->mp_lower = fp->mp_lower;
4451 mp->mp_upper = fp->mp_upper + offset;
4453 memcpy(METADATA(mp), METADATA(fp), NUMKEYS(fp) * fp->mp_pad);
4455 nsize = NODEDSZ(leaf) - fp->mp_upper;
4456 memcpy((char *)mp + mp->mp_upper, (char *)fp + fp->mp_upper, nsize);
4457 for (i=0; i<NUMKEYS(fp); i++)
4458 mp->mp_ptrs[i] = fp->mp_ptrs[i] + offset;
4460 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4464 /* data is on sub-DB, just store it */
4465 flags |= F_DUPDATA|F_SUBDATA;
4469 /* overflow page overwrites need special handling */
4470 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
4473 int ovpages, dpages;
4475 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
4476 dpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
4477 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
4478 mdb_page_get(mc->mc_txn, pg, &omp);
4479 /* Is the ov page writable and large enough? */
4480 if ((omp->mp_flags & P_DIRTY) && ovpages >= dpages) {
4481 /* yes, overwrite it. Note in this case we don't
4482 * bother to try shrinking the node if the new data
4483 * is smaller than the overflow threshold.
4485 if (F_ISSET(flags, MDB_RESERVE))
4486 data->mv_data = METADATA(omp);
4488 memcpy(METADATA(omp), data->mv_data, data->mv_size);
4491 /* no, free ovpages */
4493 mc->mc_db->md_overflow_pages -= ovpages;
4494 for (i=0; i<ovpages; i++) {
4495 DPRINTF("freed ov page %zu", pg);
4496 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
4500 } else if (NODEDSZ(leaf) == data->mv_size) {
4501 /* same size, just replace it. Note that we could
4502 * also reuse this node if the new data is smaller,
4503 * but instead we opt to shrink the node in that case.
4505 if (F_ISSET(flags, MDB_RESERVE))
4506 data->mv_data = NODEDATA(leaf);
4508 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
4511 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
4512 mc->mc_db->md_entries--;
4514 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
4521 nflags = flags & NODE_ADD_FLAGS;
4522 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
4523 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
4524 if (( flags & (F_DUPDATA|F_SUBDATA)) == F_DUPDATA )
4525 nflags &= ~MDB_APPEND;
4527 nflags |= MDB_SPLIT_REPLACE;
4528 rc = mdb_page_split(mc, key, rdata, P_INVALID, nflags);
4530 /* There is room already in this leaf page. */
4531 rc = mdb_node_add(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, nflags);
4532 if (rc == 0 && !do_sub && insert) {
4533 /* Adjust other cursors pointing to mp */
4534 MDB_cursor *m2, *m3;
4535 MDB_dbi dbi = mc->mc_dbi;
4536 unsigned i = mc->mc_top;
4537 MDB_page *mp = mc->mc_pg[i];
4539 if (mc->mc_flags & C_SUB)
4542 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
4543 if (mc->mc_flags & C_SUB)
4544 m3 = &m2->mc_xcursor->mx_cursor;
4547 if (m3 == mc || m3->mc_snum < mc->mc_snum) continue;
4548 if (m3->mc_pg[i] == mp && m3->mc_ki[i] >= mc->mc_ki[i]) {
4555 if (rc != MDB_SUCCESS)
4556 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4558 /* Now store the actual data in the child DB. Note that we're
4559 * storing the user data in the keys field, so there are strict
4560 * size limits on dupdata. The actual data fields of the child
4561 * DB are all zero size.
4568 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4569 if (flags & MDB_CURRENT) {
4570 xflags = MDB_CURRENT;
4572 mdb_xcursor_init1(mc, leaf);
4573 xflags = (flags & MDB_NODUPDATA) ? MDB_NOOVERWRITE : 0;
4575 /* converted, write the original data first */
4577 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, xflags);
4581 /* Adjust other cursors pointing to mp */
4583 unsigned i = mc->mc_top;
4584 MDB_page *mp = mc->mc_pg[i];
4586 for (m2 = mc->mc_txn->mt_cursors[mc->mc_dbi]; m2; m2=m2->mc_next) {
4587 if (m2 == mc || m2->mc_snum < mc->mc_snum) continue;
4588 if (m2->mc_pg[i] == mp && m2->mc_ki[i] == mc->mc_ki[i]) {
4589 mdb_xcursor_init1(m2, leaf);
4594 if (flags & MDB_APPENDDUP)
4595 xflags |= MDB_APPEND;
4596 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, xflags);
4597 if (flags & F_SUBDATA) {
4598 void *db = NODEDATA(leaf);
4599 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4602 /* sub-writes might have failed so check rc again.
4603 * Don't increment count if we just replaced an existing item.
4605 if (!rc && !(flags & MDB_CURRENT))
4606 mc->mc_db->md_entries++;
4607 if (flags & MDB_MULTIPLE) {
4609 if (mcount < data[1].mv_size) {
4610 data[0].mv_data = (char *)data[0].mv_data + data[0].mv_size;
4611 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4621 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
4626 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
4629 if (!mc->mc_flags & C_INITIALIZED)
4632 rc = mdb_cursor_touch(mc);
4636 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4638 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4639 if (flags != MDB_NODUPDATA) {
4640 if (!F_ISSET(leaf->mn_flags, F_SUBDATA)) {
4641 mc->mc_xcursor->mx_cursor.mc_pg[0] = NODEDATA(leaf);
4643 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
4644 /* If sub-DB still has entries, we're done */
4645 if (mc->mc_xcursor->mx_db.md_entries) {
4646 if (leaf->mn_flags & F_SUBDATA) {
4647 /* update subDB info */
4648 void *db = NODEDATA(leaf);
4649 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
4651 /* shrink fake page */
4652 mdb_node_shrink(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
4654 mc->mc_db->md_entries--;
4657 /* otherwise fall thru and delete the sub-DB */
4660 if (leaf->mn_flags & F_SUBDATA) {
4661 /* add all the child DB's pages to the free list */
4662 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
4663 if (rc == MDB_SUCCESS) {
4664 mc->mc_db->md_entries -=
4665 mc->mc_xcursor->mx_db.md_entries;
4670 return mdb_cursor_del0(mc, leaf);
4673 /** Allocate and initialize new pages for a database.
4674 * @param[in] mc a cursor on the database being added to.
4675 * @param[in] flags flags defining what type of page is being allocated.
4676 * @param[in] num the number of pages to allocate. This is usually 1,
4677 * unless allocating overflow pages for a large record.
4678 * @return Address of a page, or NULL on failure.
4681 mdb_page_new(MDB_cursor *mc, uint32_t flags, int num)
4685 if ((np = mdb_page_alloc(mc, num)) == NULL)
4687 DPRINTF("allocated new mpage %zu, page size %u",
4688 np->mp_pgno, mc->mc_txn->mt_env->me_psize);
4689 np->mp_flags = flags | P_DIRTY;
4690 np->mp_lower = PAGEHDRSZ;
4691 np->mp_upper = mc->mc_txn->mt_env->me_psize;
4694 mc->mc_db->md_branch_pages++;
4695 else if (IS_LEAF(np))
4696 mc->mc_db->md_leaf_pages++;
4697 else if (IS_OVERFLOW(np)) {
4698 mc->mc_db->md_overflow_pages += num;
4705 /** Calculate the size of a leaf node.
4706 * The size depends on the environment's page size; if a data item
4707 * is too large it will be put onto an overflow page and the node
4708 * size will only include the key and not the data. Sizes are always
4709 * rounded up to an even number of bytes, to guarantee 2-byte alignment
4710 * of the #MDB_node headers.
4711 * @param[in] env The environment handle.
4712 * @param[in] key The key for the node.
4713 * @param[in] data The data for the node.
4714 * @return The number of bytes needed to store the node.
4717 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
4721 sz = LEAFSIZE(key, data);
4722 if (sz >= env->me_psize / MDB_MINKEYS) {
4723 /* put on overflow page */
4724 sz -= data->mv_size - sizeof(pgno_t);
4728 return sz + sizeof(indx_t);
4731 /** Calculate the size of a branch node.
4732 * The size should depend on the environment's page size but since
4733 * we currently don't support spilling large keys onto overflow
4734 * pages, it's simply the size of the #MDB_node header plus the
4735 * size of the key. Sizes are always rounded up to an even number
4736 * of bytes, to guarantee 2-byte alignment of the #MDB_node headers.
4737 * @param[in] env The environment handle.
4738 * @param[in] key The key for the node.
4739 * @return The number of bytes needed to store the node.
4742 mdb_branch_size(MDB_env *env, MDB_val *key)
4747 if (sz >= env->me_psize / MDB_MINKEYS) {
4748 /* put on overflow page */
4749 /* not implemented */
4750 /* sz -= key->size - sizeof(pgno_t); */
4753 return sz + sizeof(indx_t);
4756 /** Add a node to the page pointed to by the cursor.
4757 * @param[in] mc The cursor for this operation.
4758 * @param[in] indx The index on the page where the new node should be added.
4759 * @param[in] key The key for the new node.
4760 * @param[in] data The data for the new node, if any.
4761 * @param[in] pgno The page number, if adding a branch node.
4762 * @param[in] flags Flags for the node.
4763 * @return 0 on success, non-zero on failure. Possible errors are:
4765 * <li>ENOMEM - failed to allocate overflow pages for the node.
4766 * <li>ENOSPC - there is insufficient room in the page. This error
4767 * should never happen since all callers already calculate the
4768 * page's free space before calling this function.
4772 mdb_node_add(MDB_cursor *mc, indx_t indx,
4773 MDB_val *key, MDB_val *data, pgno_t pgno, unsigned int flags)
4776 size_t node_size = NODESIZE;
4779 MDB_page *mp = mc->mc_pg[mc->mc_top];
4780 MDB_page *ofp = NULL; /* overflow page */
4783 assert(mp->mp_upper >= mp->mp_lower);
4785 DPRINTF("add to %s %spage %zu index %i, data size %zu key size %zu [%s]",
4786 IS_LEAF(mp) ? "leaf" : "branch",
4787 IS_SUBP(mp) ? "sub-" : "",
4788 mp->mp_pgno, indx, data ? data->mv_size : 0,
4789 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
4792 /* Move higher keys up one slot. */
4793 int ksize = mc->mc_db->md_pad, dif;
4794 char *ptr = LEAF2KEY(mp, indx, ksize);
4795 dif = NUMKEYS(mp) - indx;
4797 memmove(ptr+ksize, ptr, dif*ksize);
4798 /* insert new key */
4799 memcpy(ptr, key->mv_data, ksize);
4801 /* Just using these for counting */
4802 mp->mp_lower += sizeof(indx_t);
4803 mp->mp_upper -= ksize - sizeof(indx_t);
4808 node_size += key->mv_size;
4812 if (F_ISSET(flags, F_BIGDATA)) {
4813 /* Data already on overflow page. */
4814 node_size += sizeof(pgno_t);
4815 } else if (node_size + data->mv_size >= mc->mc_txn->mt_env->me_psize / MDB_MINKEYS) {
4816 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
4817 /* Put data on overflow page. */
4818 DPRINTF("data size is %zu, node would be %zu, put data on overflow page",
4819 data->mv_size, node_size+data->mv_size);
4820 node_size += sizeof(pgno_t);
4821 if ((ofp = mdb_page_new(mc, P_OVERFLOW, ovpages)) == NULL)
4823 DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
4826 node_size += data->mv_size;
4829 node_size += node_size & 1;
4831 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
4832 DPRINTF("not enough room in page %zu, got %u ptrs",
4833 mp->mp_pgno, NUMKEYS(mp));
4834 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
4835 mp->mp_upper - mp->mp_lower);
4836 DPRINTF("node size = %zu", node_size);
4840 /* Move higher pointers up one slot. */
4841 for (i = NUMKEYS(mp); i > indx; i--)
4842 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
4844 /* Adjust free space offsets. */
4845 ofs = mp->mp_upper - node_size;
4846 assert(ofs >= mp->mp_lower + sizeof(indx_t));
4847 mp->mp_ptrs[indx] = ofs;
4849 mp->mp_lower += sizeof(indx_t);
4851 /* Write the node data. */
4852 node = NODEPTR(mp, indx);
4853 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
4854 node->mn_flags = flags;
4856 SETDSZ(node,data->mv_size);
4861 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
4866 if (F_ISSET(flags, F_BIGDATA))
4867 memcpy(node->mn_data + key->mv_size, data->mv_data,
4869 else if (F_ISSET(flags, MDB_RESERVE))
4870 data->mv_data = node->mn_data + key->mv_size;
4872 memcpy(node->mn_data + key->mv_size, data->mv_data,
4875 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
4877 if (F_ISSET(flags, MDB_RESERVE))
4878 data->mv_data = METADATA(ofp);
4880 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
4887 /** Delete the specified node from a page.
4888 * @param[in] mp The page to operate on.
4889 * @param[in] indx The index of the node to delete.
4890 * @param[in] ksize The size of a node. Only used if the page is
4891 * part of a #MDB_DUPFIXED database.
4894 mdb_node_del(MDB_page *mp, indx_t indx, int ksize)
4897 indx_t i, j, numkeys, ptr;
4904 COPY_PGNO(pgno, mp->mp_pgno);
4905 DPRINTF("delete node %u on %s page %zu", indx,
4906 IS_LEAF(mp) ? "leaf" : "branch", pgno);
4909 assert(indx < NUMKEYS(mp));
4912 int x = NUMKEYS(mp) - 1 - indx;
4913 base = LEAF2KEY(mp, indx, ksize);
4915 memmove(base, base + ksize, x * ksize);
4916 mp->mp_lower -= sizeof(indx_t);
4917 mp->mp_upper += ksize - sizeof(indx_t);
4921 node = NODEPTR(mp, indx);
4922 sz = NODESIZE + node->mn_ksize;
4924 if (F_ISSET(node->mn_flags, F_BIGDATA))
4925 sz += sizeof(pgno_t);
4927 sz += NODEDSZ(node);
4931 ptr = mp->mp_ptrs[indx];
4932 numkeys = NUMKEYS(mp);
4933 for (i = j = 0; i < numkeys; i++) {
4935 mp->mp_ptrs[j] = mp->mp_ptrs[i];
4936 if (mp->mp_ptrs[i] < ptr)
4937 mp->mp_ptrs[j] += sz;
4942 base = (char *)mp + mp->mp_upper;
4943 memmove(base + sz, base, ptr - mp->mp_upper);
4945 mp->mp_lower -= sizeof(indx_t);
4949 /** Compact the main page after deleting a node on a subpage.
4950 * @param[in] mp The main page to operate on.
4951 * @param[in] indx The index of the subpage on the main page.
4954 mdb_node_shrink(MDB_page *mp, indx_t indx)
4961 indx_t i, numkeys, ptr;
4963 node = NODEPTR(mp, indx);
4964 sp = (MDB_page *)NODEDATA(node);
4965 osize = NODEDSZ(node);
4967 delta = sp->mp_upper - sp->mp_lower;
4968 SETDSZ(node, osize - delta);
4969 xp = (MDB_page *)((char *)sp + delta);
4971 /* shift subpage upward */
4973 nsize = NUMKEYS(sp) * sp->mp_pad;
4974 memmove(METADATA(xp), METADATA(sp), nsize);
4977 nsize = osize - sp->mp_upper;
4978 numkeys = NUMKEYS(sp);
4979 for (i=numkeys-1; i>=0; i--)
4980 xp->mp_ptrs[i] = sp->mp_ptrs[i] - delta;
4982 xp->mp_upper = sp->mp_lower;
4983 xp->mp_lower = sp->mp_lower;
4984 xp->mp_flags = sp->mp_flags;
4985 xp->mp_pad = sp->mp_pad;
4986 COPY_PGNO(xp->mp_pgno, mp->mp_pgno);
4988 /* shift lower nodes upward */
4989 ptr = mp->mp_ptrs[indx];
4990 numkeys = NUMKEYS(mp);
4991 for (i = 0; i < numkeys; i++) {
4992 if (mp->mp_ptrs[i] <= ptr)
4993 mp->mp_ptrs[i] += delta;
4996 base = (char *)mp + mp->mp_upper;
4997 memmove(base + delta, base, ptr - mp->mp_upper + NODESIZE + NODEKSZ(node));
4998 mp->mp_upper += delta;
5001 /** Initial setup of a sorted-dups cursor.
5002 * Sorted duplicates are implemented as a sub-database for the given key.
5003 * The duplicate data items are actually keys of the sub-database.
5004 * Operations on the duplicate data items are performed using a sub-cursor
5005 * initialized when the sub-database is first accessed. This function does
5006 * the preliminary setup of the sub-cursor, filling in the fields that
5007 * depend only on the parent DB.
5008 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
5011 mdb_xcursor_init0(MDB_cursor *mc)
5013 MDB_xcursor *mx = mc->mc_xcursor;
5015 mx->mx_cursor.mc_xcursor = NULL;
5016 mx->mx_cursor.mc_txn = mc->mc_txn;
5017 mx->mx_cursor.mc_db = &mx->mx_db;
5018 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
5019 mx->mx_cursor.mc_dbi = mc->mc_dbi+1;
5020 mx->mx_cursor.mc_dbflag = &mx->mx_dbflag;
5021 mx->mx_cursor.mc_snum = 0;
5022 mx->mx_cursor.mc_top = 0;
5023 mx->mx_cursor.mc_flags = C_SUB;
5024 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
5025 mx->mx_dbx.md_dcmp = NULL;
5026 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
5029 /** Final setup of a sorted-dups cursor.
5030 * Sets up the fields that depend on the data from the main cursor.
5031 * @param[in] mc The main cursor whose sorted-dups cursor is to be initialized.
5032 * @param[in] node The data containing the #MDB_db record for the
5033 * sorted-dup database.
5036 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
5038 MDB_xcursor *mx = mc->mc_xcursor;
5040 if (node->mn_flags & F_SUBDATA) {
5041 memcpy(&mx->mx_db, NODEDATA(node), sizeof(MDB_db));
5042 mx->mx_cursor.mc_pg[0] = 0;
5043 mx->mx_cursor.mc_snum = 0;
5044 mx->mx_cursor.mc_flags = C_SUB;
5046 MDB_page *fp = NODEDATA(node);
5047 mx->mx_db.md_pad = mc->mc_pg[mc->mc_top]->mp_pad;
5048 mx->mx_db.md_flags = 0;
5049 mx->mx_db.md_depth = 1;
5050 mx->mx_db.md_branch_pages = 0;
5051 mx->mx_db.md_leaf_pages = 1;
5052 mx->mx_db.md_overflow_pages = 0;
5053 mx->mx_db.md_entries = NUMKEYS(fp);
5054 COPY_PGNO(mx->mx_db.md_root, fp->mp_pgno);
5055 mx->mx_cursor.mc_snum = 1;
5056 mx->mx_cursor.mc_flags = C_INITIALIZED|C_SUB;
5057 mx->mx_cursor.mc_top = 0;
5058 mx->mx_cursor.mc_pg[0] = fp;
5059 mx->mx_cursor.mc_ki[0] = 0;
5060 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
5061 mx->mx_db.md_flags = MDB_DUPFIXED;
5062 mx->mx_db.md_pad = fp->mp_pad;
5063 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
5064 mx->mx_db.md_flags |= MDB_INTEGERKEY;
5067 DPRINTF("Sub-db %u for db %u root page %zu", mx->mx_cursor.mc_dbi, mc->mc_dbi,
5069 mx->mx_dbflag = (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY)) ?
5071 mx->mx_dbx.md_name.mv_data = NODEKEY(node);
5072 mx->mx_dbx.md_name.mv_size = node->mn_ksize;
5073 #if UINT_MAX < SIZE_MAX
5074 if (mx->mx_dbx.md_cmp == mdb_cmp_int && mx->mx_db.md_pad == sizeof(size_t))
5075 #ifdef MISALIGNED_OK
5076 mx->mx_dbx.md_cmp = mdb_cmp_long;
5078 mx->mx_dbx.md_cmp = mdb_cmp_cint;
5083 /** Initialize a cursor for a given transaction and database. */
5085 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
5090 mc->mc_db = &txn->mt_dbs[dbi];
5091 mc->mc_dbx = &txn->mt_dbxs[dbi];
5092 mc->mc_dbflag = &txn->mt_dbflags[dbi];
5097 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
5099 mc->mc_xcursor = mx;
5100 mdb_xcursor_init0(mc);
5102 mc->mc_xcursor = NULL;
5104 if (*mc->mc_dbflag & DB_STALE) {
5105 mdb_page_search(mc, NULL, MDB_PS_ROOTONLY);
5110 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
5113 MDB_xcursor *mx = NULL;
5114 size_t size = sizeof(MDB_cursor);
5116 if (txn == NULL || ret == NULL || dbi >= txn->mt_numdbs)
5119 /* Allow read access to the freelist */
5120 if (!dbi && !F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
5123 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
5124 size += sizeof(MDB_xcursor);
5126 if ((mc = malloc(size)) != NULL) {
5127 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
5128 mx = (MDB_xcursor *)(mc + 1);
5130 mdb_cursor_init(mc, txn, dbi, mx);
5131 if (txn->mt_cursors) {
5132 mc->mc_next = txn->mt_cursors[dbi];
5133 txn->mt_cursors[dbi] = mc;
5135 mc->mc_flags |= C_ALLOCD;
5145 /* Return the count of duplicate data items for the current key */
5147 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
5151 if (mc == NULL || countp == NULL)
5154 if (!(mc->mc_db->md_flags & MDB_DUPSORT))
5157 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
5158 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
5161 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
5164 *countp = mc->mc_xcursor->mx_db.md_entries;
5170 mdb_cursor_close(MDB_cursor *mc)
5173 /* remove from txn, if tracked */
5174 if (mc->mc_txn->mt_cursors) {
5175 MDB_cursor **prev = &mc->mc_txn->mt_cursors[mc->mc_dbi];
5176 while (*prev && *prev != mc) prev = &(*prev)->mc_next;
5178 *prev = mc->mc_next;
5180 if (mc->mc_flags & C_ALLOCD)
5186 mdb_cursor_txn(MDB_cursor *mc)
5188 if (!mc) return NULL;
5193 mdb_cursor_dbi(MDB_cursor *mc)
5199 /** Replace the key for a node with a new key.
5200 * @param[in] mp The page containing the node to operate on.
5201 * @param[in] indx The index of the node to operate on.
5202 * @param[in] key The new key to use.
5203 * @return 0 on success, non-zero on failure.
5206 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
5212 indx_t ptr, i, numkeys;
5215 node = NODEPTR(mp, indx);
5216 ptr = mp->mp_ptrs[indx];
5220 char kbuf2[(MAXKEYSIZE*2+1)];
5221 k2.mv_data = NODEKEY(node);
5222 k2.mv_size = node->mn_ksize;
5223 DPRINTF("update key %u (ofs %u) [%s] to [%s] on page %zu",
5225 mdb_dkey(&k2, kbuf2),
5231 delta0 = delta = key->mv_size - node->mn_ksize;
5233 /* Must be 2-byte aligned. If new key is
5234 * shorter by 1, the shift will be skipped.
5236 delta += (delta & 1);
5238 if (delta > 0 && SIZELEFT(mp) < delta) {
5239 DPRINTF("OUCH! Not enough room, delta = %d", delta);
5243 numkeys = NUMKEYS(mp);
5244 for (i = 0; i < numkeys; i++) {
5245 if (mp->mp_ptrs[i] <= ptr)
5246 mp->mp_ptrs[i] -= delta;
5249 base = (char *)mp + mp->mp_upper;
5250 len = ptr - mp->mp_upper + NODESIZE;
5251 memmove(base - delta, base, len);
5252 mp->mp_upper -= delta;
5254 node = NODEPTR(mp, indx);
5257 /* But even if no shift was needed, update ksize */
5259 node->mn_ksize = key->mv_size;
5262 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
5267 /** Move a node from csrc to cdst.
5270 mdb_node_move(MDB_cursor *csrc, MDB_cursor *cdst)
5276 unsigned short flags;
5280 /* Mark src and dst as dirty. */
5281 if ((rc = mdb_page_touch(csrc)) ||
5282 (rc = mdb_page_touch(cdst)))
5285 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5286 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
5287 key.mv_size = csrc->mc_db->md_pad;
5288 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
5290 data.mv_data = NULL;
5294 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
5295 assert(!((long)srcnode&1));
5296 srcpg = NODEPGNO(srcnode);
5297 flags = srcnode->mn_flags;
5298 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
5299 unsigned int snum = csrc->mc_snum;
5301 /* must find the lowest key below src */
5302 mdb_page_search_root(csrc, NULL, 0);
5303 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5304 key.mv_size = csrc->mc_db->md_pad;
5305 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
5307 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
5308 key.mv_size = NODEKSZ(s2);
5309 key.mv_data = NODEKEY(s2);
5311 csrc->mc_snum = snum--;
5312 csrc->mc_top = snum;
5314 key.mv_size = NODEKSZ(srcnode);
5315 key.mv_data = NODEKEY(srcnode);
5317 data.mv_size = NODEDSZ(srcnode);
5318 data.mv_data = NODEDATA(srcnode);
5320 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top]) && cdst->mc_ki[cdst->mc_top] == 0) {
5321 unsigned int snum = cdst->mc_snum;
5324 /* must find the lowest key below dst */
5325 mdb_page_search_root(cdst, NULL, 0);
5326 if (IS_LEAF2(cdst->mc_pg[cdst->mc_top])) {
5327 bkey.mv_size = cdst->mc_db->md_pad;
5328 bkey.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, bkey.mv_size);
5330 s2 = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
5331 bkey.mv_size = NODEKSZ(s2);
5332 bkey.mv_data = NODEKEY(s2);
5334 cdst->mc_snum = snum--;
5335 cdst->mc_top = snum;
5336 rc = mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &bkey);
5339 DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
5340 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
5341 csrc->mc_ki[csrc->mc_top],
5343 csrc->mc_pg[csrc->mc_top]->mp_pgno,
5344 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
5346 /* Add the node to the destination page.
5348 rc = mdb_node_add(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, srcpg, flags);
5349 if (rc != MDB_SUCCESS)
5352 /* Delete the node from the source page.
5354 mdb_node_del(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
5357 /* Adjust other cursors pointing to mp */
5358 MDB_cursor *m2, *m3;
5359 MDB_dbi dbi = csrc->mc_dbi;
5360 MDB_page *mp = csrc->mc_pg[csrc->mc_top];
5362 if (csrc->mc_flags & C_SUB)
5365 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5366 if (m2 == csrc) continue;
5367 if (csrc->mc_flags & C_SUB)
5368 m3 = &m2->mc_xcursor->mx_cursor;
5371 if (m3->mc_pg[csrc->mc_top] == mp && m3->mc_ki[csrc->mc_top] ==
5372 csrc->mc_ki[csrc->mc_top]) {
5373 m3->mc_pg[csrc->mc_top] = cdst->mc_pg[cdst->mc_top];
5374 m3->mc_ki[csrc->mc_top] = cdst->mc_ki[cdst->mc_top];
5379 /* Update the parent separators.
5381 if (csrc->mc_ki[csrc->mc_top] == 0) {
5382 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
5383 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5384 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
5386 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
5387 key.mv_size = NODEKSZ(srcnode);
5388 key.mv_data = NODEKEY(srcnode);
5390 DPRINTF("update separator for source page %zu to [%s]",
5391 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
5392 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1],
5393 &key)) != MDB_SUCCESS)
5396 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
5398 nullkey.mv_size = 0;
5399 rc = mdb_update_key(csrc->mc_pg[csrc->mc_top], 0, &nullkey);
5400 assert(rc == MDB_SUCCESS);
5404 if (cdst->mc_ki[cdst->mc_top] == 0) {
5405 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
5406 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5407 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
5409 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
5410 key.mv_size = NODEKSZ(srcnode);
5411 key.mv_data = NODEKEY(srcnode);
5413 DPRINTF("update separator for destination page %zu to [%s]",
5414 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
5415 if ((rc = mdb_update_key(cdst->mc_pg[cdst->mc_top-1], cdst->mc_ki[cdst->mc_top-1],
5416 &key)) != MDB_SUCCESS)
5419 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
5421 nullkey.mv_size = 0;
5422 rc = mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &nullkey);
5423 assert(rc == MDB_SUCCESS);
5430 /** Merge one page into another.
5431 * The nodes from the page pointed to by \b csrc will
5432 * be copied to the page pointed to by \b cdst and then
5433 * the \b csrc page will be freed.
5434 * @param[in] csrc Cursor pointing to the source page.
5435 * @param[in] cdst Cursor pointing to the destination page.
5438 mdb_page_merge(MDB_cursor *csrc, MDB_cursor *cdst)
5446 DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
5447 cdst->mc_pg[cdst->mc_top]->mp_pgno);
5449 assert(csrc->mc_snum > 1); /* can't merge root page */
5450 assert(cdst->mc_snum > 1);
5452 /* Mark dst as dirty. */
5453 if ((rc = mdb_page_touch(cdst)))
5456 /* Move all nodes from src to dst.
5458 j = nkeys = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
5459 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5460 key.mv_size = csrc->mc_db->md_pad;
5461 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
5462 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
5463 rc = mdb_node_add(cdst, j, &key, NULL, 0, 0);
5464 if (rc != MDB_SUCCESS)
5466 key.mv_data = (char *)key.mv_data + key.mv_size;
5469 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
5470 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
5471 if (i == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
5472 unsigned int snum = csrc->mc_snum;
5474 /* must find the lowest key below src */
5475 mdb_page_search_root(csrc, NULL, 0);
5476 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
5477 key.mv_size = csrc->mc_db->md_pad;
5478 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
5480 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
5481 key.mv_size = NODEKSZ(s2);
5482 key.mv_data = NODEKEY(s2);
5484 csrc->mc_snum = snum--;
5485 csrc->mc_top = snum;
5487 key.mv_size = srcnode->mn_ksize;
5488 key.mv_data = NODEKEY(srcnode);
5491 data.mv_size = NODEDSZ(srcnode);
5492 data.mv_data = NODEDATA(srcnode);
5493 rc = mdb_node_add(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
5494 if (rc != MDB_SUCCESS)
5499 DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
5500 cdst->mc_pg[cdst->mc_top]->mp_pgno, NUMKEYS(cdst->mc_pg[cdst->mc_top]), (float)PAGEFILL(cdst->mc_txn->mt_env, cdst->mc_pg[cdst->mc_top]) / 10);
5502 /* Unlink the src page from parent and add to free list.
5504 mdb_node_del(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
5505 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
5507 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], 0, &key)) != MDB_SUCCESS)
5511 mdb_midl_append(&csrc->mc_txn->mt_free_pgs, csrc->mc_pg[csrc->mc_top]->mp_pgno);
5512 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
5513 csrc->mc_db->md_leaf_pages--;
5515 csrc->mc_db->md_branch_pages--;
5517 /* Adjust other cursors pointing to mp */
5518 MDB_cursor *m2, *m3;
5519 MDB_dbi dbi = csrc->mc_dbi;
5520 MDB_page *mp = cdst->mc_pg[cdst->mc_top];
5522 if (csrc->mc_flags & C_SUB)
5525 for (m2 = csrc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5526 if (csrc->mc_flags & C_SUB)
5527 m3 = &m2->mc_xcursor->mx_cursor;
5530 if (m3 == csrc) continue;
5531 if (m3->mc_snum < csrc->mc_snum) continue;
5532 if (m3->mc_pg[csrc->mc_top] == csrc->mc_pg[csrc->mc_top]) {
5533 m3->mc_pg[csrc->mc_top] = mp;
5534 m3->mc_ki[csrc->mc_top] += nkeys;
5538 mdb_cursor_pop(csrc);
5540 return mdb_rebalance(csrc);
5543 /** Copy the contents of a cursor.
5544 * @param[in] csrc The cursor to copy from.
5545 * @param[out] cdst The cursor to copy to.
5548 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
5552 cdst->mc_txn = csrc->mc_txn;
5553 cdst->mc_dbi = csrc->mc_dbi;
5554 cdst->mc_db = csrc->mc_db;
5555 cdst->mc_dbx = csrc->mc_dbx;
5556 cdst->mc_snum = csrc->mc_snum;
5557 cdst->mc_top = csrc->mc_top;
5558 cdst->mc_flags = csrc->mc_flags;
5560 for (i=0; i<csrc->mc_snum; i++) {
5561 cdst->mc_pg[i] = csrc->mc_pg[i];
5562 cdst->mc_ki[i] = csrc->mc_ki[i];
5566 /** Rebalance the tree after a delete operation.
5567 * @param[in] mc Cursor pointing to the page where rebalancing
5569 * @return 0 on success, non-zero on failure.
5572 mdb_rebalance(MDB_cursor *mc)
5582 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
5583 DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
5584 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
5585 pgno, NUMKEYS(mc->mc_pg[mc->mc_top]), (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10);
5589 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD) {
5592 COPY_PGNO(pgno, mc->mc_pg[mc->mc_top]->mp_pgno);
5593 DPRINTF("no need to rebalance page %zu, above fill threshold",
5599 if (mc->mc_snum < 2) {
5600 MDB_page *mp = mc->mc_pg[0];
5601 if (NUMKEYS(mp) == 0) {
5602 DPUTS("tree is completely empty");
5603 mc->mc_db->md_root = P_INVALID;
5604 mc->mc_db->md_depth = 0;
5605 mc->mc_db->md_leaf_pages = 0;
5606 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5610 /* Adjust other cursors pointing to mp */
5611 MDB_cursor *m2, *m3;
5612 MDB_dbi dbi = mc->mc_dbi;
5614 if (mc->mc_flags & C_SUB)
5617 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5618 if (m2 == mc) continue;
5619 if (mc->mc_flags & C_SUB)
5620 m3 = &m2->mc_xcursor->mx_cursor;
5623 if (m3->mc_snum < mc->mc_snum) continue;
5624 if (m3->mc_pg[0] == mp) {
5630 } else if (IS_BRANCH(mp) && NUMKEYS(mp) == 1) {
5631 DPUTS("collapsing root page!");
5632 mdb_midl_append(&mc->mc_txn->mt_free_pgs, mp->mp_pgno);
5633 mc->mc_db->md_root = NODEPGNO(NODEPTR(mp, 0));
5634 if ((rc = mdb_page_get(mc->mc_txn, mc->mc_db->md_root,
5637 mc->mc_db->md_depth--;
5638 mc->mc_db->md_branch_pages--;
5640 /* Adjust other cursors pointing to mp */
5641 MDB_cursor *m2, *m3;
5642 MDB_dbi dbi = mc->mc_dbi;
5644 if (mc->mc_flags & C_SUB)
5647 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
5648 if (m2 == mc) continue;
5649 if (mc->mc_flags & C_SUB)
5650 m3 = &m2->mc_xcursor->mx_cursor;
5653 if (m3->mc_snum < mc->mc_snum) continue;
5654 if (m3->mc_pg[0] == mp) {
5655 m3->mc_pg[0] = mc->mc_pg[0];
5660 DPUTS("root page doesn't need rebalancing");
5664 /* The parent (branch page) must have at least 2 pointers,
5665 * otherwise the tree is invalid.
5667 ptop = mc->mc_top-1;
5668 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
5670 /* Leaf page fill factor is below the threshold.
5671 * Try to move keys from left or right neighbor, or
5672 * merge with a neighbor page.
5677 mdb_cursor_copy(mc, &mn);
5678 mn.mc_xcursor = NULL;
5680 if (mc->mc_ki[ptop] == 0) {
5681 /* We're the leftmost leaf in our parent.
5683 DPUTS("reading right neighbor");
5685 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5686 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5688 mn.mc_ki[mn.mc_top] = 0;
5689 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
5691 /* There is at least one neighbor to the left.
5693 DPUTS("reading left neighbor");
5695 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
5696 if ((rc = mdb_page_get(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
5698 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
5699 mc->mc_ki[mc->mc_top] = 0;
5702 DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
5703 mn.mc_pg[mn.mc_top]->mp_pgno, NUMKEYS(mn.mc_pg[mn.mc_top]), (float)PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) / 10);
5705 /* If the neighbor page is above threshold and has at least two
5706 * keys, move one key from it.
5708 * Otherwise we should try to merge them.
5710 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) >= 2)
5711 return mdb_node_move(&mn, mc);
5712 else { /* FIXME: if (has_enough_room()) */
5713 mc->mc_flags &= ~C_INITIALIZED;
5714 if (mc->mc_ki[ptop] == 0)
5715 return mdb_page_merge(&mn, mc);
5717 return mdb_page_merge(mc, &mn);
5721 /** Complete a delete operation started by #mdb_cursor_del(). */
5723 mdb_cursor_del0(MDB_cursor *mc, MDB_node *leaf)
5727 /* add overflow pages to free list */
5728 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
5732 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
5733 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
5734 mc->mc_db->md_overflow_pages -= ovpages;
5735 for (i=0; i<ovpages; i++) {
5736 DPRINTF("freed ov page %zu", pg);
5737 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
5741 mdb_node_del(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], mc->mc_db->md_pad);
5742 mc->mc_db->md_entries--;
5743 rc = mdb_rebalance(mc);
5744 if (rc != MDB_SUCCESS)
5745 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
5751 mdb_del(MDB_txn *txn, MDB_dbi dbi,
5752 MDB_val *key, MDB_val *data)
5757 MDB_val rdata, *xdata;
5761 assert(key != NULL);
5763 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
5765 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
5768 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
5772 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
5776 mdb_cursor_init(&mc, txn, dbi, &mx);
5787 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
5789 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
5793 /** Split a page and insert a new node.
5794 * @param[in,out] mc Cursor pointing to the page and desired insertion index.
5795 * The cursor will be updated to point to the actual page and index where
5796 * the node got inserted after the split.
5797 * @param[in] newkey The key for the newly inserted node.
5798 * @param[in] newdata The data for the newly inserted node.
5799 * @param[in] newpgno The page number, if the new node is a branch node.
5800 * @param[in] nflags The #NODE_ADD_FLAGS for the new node.
5801 * @return 0 on success, non-zero on failure.
5804 mdb_page_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno,
5805 unsigned int nflags)
5808 int rc = MDB_SUCCESS, ins_new = 0, new_root = 0, newpos = 1, did_split = 0;
5811 unsigned int i, j, split_indx, nkeys, pmax;
5813 MDB_val sepkey, rkey, xdata, *rdata = &xdata;
5815 MDB_page *mp, *rp, *pp;
5820 mp = mc->mc_pg[mc->mc_top];
5821 newindx = mc->mc_ki[mc->mc_top];
5823 DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
5824 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
5825 DKEY(newkey), mc->mc_ki[mc->mc_top]);
5827 /* Create a right sibling. */
5828 if ((rp = mdb_page_new(mc, mp->mp_flags, 1)) == NULL)
5830 DPRINTF("new right sibling: page %zu", rp->mp_pgno);
5832 if (mc->mc_snum < 2) {
5833 if ((pp = mdb_page_new(mc, P_BRANCH, 1)) == NULL)
5835 /* shift current top to make room for new parent */
5836 mc->mc_pg[1] = mc->mc_pg[0];
5837 mc->mc_ki[1] = mc->mc_ki[0];
5840 mc->mc_db->md_root = pp->mp_pgno;
5841 DPRINTF("root split! new root = %zu", pp->mp_pgno);
5842 mc->mc_db->md_depth++;
5845 /* Add left (implicit) pointer. */
5846 if ((rc = mdb_node_add(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
5847 /* undo the pre-push */
5848 mc->mc_pg[0] = mc->mc_pg[1];
5849 mc->mc_ki[0] = mc->mc_ki[1];
5850 mc->mc_db->md_root = mp->mp_pgno;
5851 mc->mc_db->md_depth--;
5858 ptop = mc->mc_top-1;
5859 DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
5862 mc->mc_flags |= C_SPLITTING;
5863 mdb_cursor_copy(mc, &mn);
5864 mn.mc_pg[mn.mc_top] = rp;
5865 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
5867 if (nflags & MDB_APPEND) {
5868 mn.mc_ki[mn.mc_top] = 0;
5870 split_indx = newindx;
5875 nkeys = NUMKEYS(mp);
5876 split_indx = (nkeys + 1) / 2;
5877 if (newindx < split_indx)
5883 unsigned int lsize, rsize, ksize;
5884 /* Move half of the keys to the right sibling */
5886 x = mc->mc_ki[mc->mc_top] - split_indx;
5887 ksize = mc->mc_db->md_pad;
5888 split = LEAF2KEY(mp, split_indx, ksize);
5889 rsize = (nkeys - split_indx) * ksize;
5890 lsize = (nkeys - split_indx) * sizeof(indx_t);
5891 mp->mp_lower -= lsize;
5892 rp->mp_lower += lsize;
5893 mp->mp_upper += rsize - lsize;
5894 rp->mp_upper -= rsize - lsize;
5895 sepkey.mv_size = ksize;
5896 if (newindx == split_indx) {
5897 sepkey.mv_data = newkey->mv_data;
5899 sepkey.mv_data = split;
5902 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
5903 memcpy(rp->mp_ptrs, split, rsize);
5904 sepkey.mv_data = rp->mp_ptrs;
5905 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
5906 memcpy(ins, newkey->mv_data, ksize);
5907 mp->mp_lower += sizeof(indx_t);
5908 mp->mp_upper -= ksize - sizeof(indx_t);
5911 memcpy(rp->mp_ptrs, split, x * ksize);
5912 ins = LEAF2KEY(rp, x, ksize);
5913 memcpy(ins, newkey->mv_data, ksize);
5914 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
5915 rp->mp_lower += sizeof(indx_t);
5916 rp->mp_upper -= ksize - sizeof(indx_t);
5917 mc->mc_ki[mc->mc_top] = x;
5918 mc->mc_pg[mc->mc_top] = rp;
5923 /* For leaf pages, check the split point based on what
5924 * fits where, since otherwise mdb_node_add can fail.
5926 * This check is only needed when the data items are
5927 * relatively large, such that being off by one will
5928 * make the difference between success or failure.
5929 * When the size of the data items is much smaller than
5930 * one-half of a page, this check is irrelevant.
5933 unsigned int psize, nsize;
5934 /* Maximum free space in an empty page */
5935 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
5936 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
5937 if ((nkeys < 20) || (nsize > pmax/4)) {
5938 if (newindx <= split_indx) {
5941 for (i=0; i<split_indx; i++) {
5942 node = NODEPTR(mp, i);
5943 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
5944 if (F_ISSET(node->mn_flags, F_BIGDATA))
5945 psize += sizeof(pgno_t);
5947 psize += NODEDSZ(node);
5950 if (i == split_indx - 1 && newindx == split_indx)
5959 for (i=nkeys-1; i>=split_indx; i--) {
5960 node = NODEPTR(mp, i);
5961 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
5962 if (F_ISSET(node->mn_flags, F_BIGDATA))
5963 psize += sizeof(pgno_t);
5965 psize += NODEDSZ(node);
5976 /* First find the separating key between the split pages.
5977 * The case where newindx == split_indx is ambiguous; the
5978 * new item could go to the new page or stay on the original
5979 * page. If newpos == 1 it goes to the new page.
5981 if (newindx == split_indx && newpos) {
5982 sepkey.mv_size = newkey->mv_size;
5983 sepkey.mv_data = newkey->mv_data;
5985 node = NODEPTR(mp, split_indx);
5986 sepkey.mv_size = node->mn_ksize;
5987 sepkey.mv_data = NODEKEY(node);
5991 DPRINTF("separator is [%s]", DKEY(&sepkey));
5993 /* Copy separator key to the parent.
5995 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
5999 rc = mdb_page_split(&mn, &sepkey, NULL, rp->mp_pgno, 0);
6002 if (mn.mc_snum == mc->mc_snum) {
6003 mc->mc_pg[mc->mc_snum] = mc->mc_pg[mc->mc_top];
6004 mc->mc_ki[mc->mc_snum] = mc->mc_ki[mc->mc_top];
6005 mc->mc_pg[mc->mc_top] = mc->mc_pg[ptop];
6006 mc->mc_ki[mc->mc_top] = mc->mc_ki[ptop];
6011 /* Right page might now have changed parent.
6012 * Check if left page also changed parent.
6014 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
6015 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
6016 for (i=0; i<ptop; i++) {
6017 mc->mc_pg[i] = mn.mc_pg[i];
6018 mc->mc_ki[i] = mn.mc_ki[i];
6020 mc->mc_pg[ptop] = mn.mc_pg[ptop];
6021 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
6025 rc = mdb_node_add(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
6028 mc->mc_flags ^= C_SPLITTING;
6029 if (rc != MDB_SUCCESS) {
6032 if (nflags & MDB_APPEND) {
6033 mc->mc_pg[mc->mc_top] = rp;
6034 mc->mc_ki[mc->mc_top] = 0;
6035 rc = mdb_node_add(mc, 0, newkey, newdata, newpgno, nflags);
6038 for (i=0; i<mc->mc_top; i++)
6039 mc->mc_ki[i] = mn.mc_ki[i];
6046 /* Move half of the keys to the right sibling. */
6048 /* grab a page to hold a temporary copy */
6049 copy = mdb_page_malloc(mc);
6053 copy->mp_pgno = mp->mp_pgno;
6054 copy->mp_flags = mp->mp_flags;
6055 copy->mp_lower = PAGEHDRSZ;
6056 copy->mp_upper = mc->mc_txn->mt_env->me_psize;
6057 mc->mc_pg[mc->mc_top] = copy;
6058 for (i = j = 0; i <= nkeys; j++) {
6059 if (i == split_indx) {
6060 /* Insert in right sibling. */
6061 /* Reset insert index for right sibling. */
6062 if (i != newindx || (newpos ^ ins_new)) {
6064 mc->mc_pg[mc->mc_top] = rp;
6068 if (i == newindx && !ins_new) {
6069 /* Insert the original entry that caused the split. */
6070 rkey.mv_data = newkey->mv_data;
6071 rkey.mv_size = newkey->mv_size;
6080 /* Update index for the new key. */
6081 mc->mc_ki[mc->mc_top] = j;
6082 } else if (i == nkeys) {
6085 node = NODEPTR(mp, i);
6086 rkey.mv_data = NODEKEY(node);
6087 rkey.mv_size = node->mn_ksize;
6089 xdata.mv_data = NODEDATA(node);
6090 xdata.mv_size = NODEDSZ(node);
6093 pgno = NODEPGNO(node);
6094 flags = node->mn_flags;
6099 if (!IS_LEAF(mp) && j == 0) {
6100 /* First branch index doesn't need key data. */
6104 rc = mdb_node_add(mc, j, &rkey, rdata, pgno, flags);
6108 nkeys = NUMKEYS(copy);
6109 for (i=0; i<nkeys; i++)
6110 mp->mp_ptrs[i] = copy->mp_ptrs[i];
6111 mp->mp_lower = copy->mp_lower;
6112 mp->mp_upper = copy->mp_upper;
6113 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
6114 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
6116 /* reset back to original page */
6117 if (newindx < split_indx || (!newpos && newindx == split_indx)) {
6118 mc->mc_pg[mc->mc_top] = mp;
6119 if (nflags & MDB_RESERVE) {
6120 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
6121 if (!(node->mn_flags & F_BIGDATA))
6122 newdata->mv_data = NODEDATA(node);
6128 /* return tmp page to freelist */
6129 copy->mp_next = mc->mc_txn->mt_env->me_dpages;
6130 VGMEMP_FREE(mc->mc_txn->mt_env, copy);
6131 mc->mc_txn->mt_env->me_dpages = copy;
6134 /* Adjust other cursors pointing to mp */
6135 MDB_cursor *m2, *m3;
6136 MDB_dbi dbi = mc->mc_dbi;
6137 int fixup = NUMKEYS(mp);
6139 if (mc->mc_flags & C_SUB)
6142 for (m2 = mc->mc_txn->mt_cursors[dbi]; m2; m2=m2->mc_next) {
6143 if (m2 == mc) continue;
6144 if (mc->mc_flags & C_SUB)
6145 m3 = &m2->mc_xcursor->mx_cursor;
6148 if (!(m3->mc_flags & C_INITIALIZED))
6150 if (m3->mc_flags & C_SPLITTING)
6155 for (k=m3->mc_top; k>=0; k--) {
6156 m3->mc_ki[k+1] = m3->mc_ki[k];
6157 m3->mc_pg[k+1] = m3->mc_pg[k];
6159 if (m3->mc_ki[0] >= split_indx) {
6164 m3->mc_pg[0] = mc->mc_pg[0];
6168 if (m3->mc_pg[mc->mc_top] == mp) {
6169 if (m3->mc_ki[mc->mc_top] >= newindx && !(nflags & MDB_SPLIT_REPLACE))
6170 m3->mc_ki[mc->mc_top]++;
6171 if (m3->mc_ki[mc->mc_top] >= fixup) {
6172 m3->mc_pg[mc->mc_top] = rp;
6173 m3->mc_ki[mc->mc_top] -= fixup;
6174 m3->mc_ki[ptop] = mn.mc_ki[ptop];
6176 } else if (!did_split && m3->mc_pg[ptop] == mc->mc_pg[ptop] &&
6177 m3->mc_ki[ptop] >= mc->mc_ki[ptop]) {
6186 mdb_put(MDB_txn *txn, MDB_dbi dbi,
6187 MDB_val *key, MDB_val *data, unsigned int flags)
6192 assert(key != NULL);
6193 assert(data != NULL);
6195 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6198 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
6202 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
6206 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA|MDB_RESERVE|MDB_APPEND)) != flags)
6209 mdb_cursor_init(&mc, txn, dbi, &mx);
6210 return mdb_cursor_put(&mc, key, data, flags);
6213 /** Only a subset of the @ref mdb_env flags can be changed
6214 * at runtime. Changing other flags requires closing the environment
6215 * and re-opening it with the new flags.
6217 #define CHANGEABLE (MDB_NOSYNC|MDB_NOMETASYNC)
6219 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
6221 if ((flag & CHANGEABLE) != flag)
6224 env->me_flags |= flag;
6226 env->me_flags &= ~flag;
6231 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
6236 *arg = env->me_flags;
6241 mdb_env_get_path(MDB_env *env, const char **arg)
6246 *arg = env->me_path;
6250 /** Common code for #mdb_stat() and #mdb_env_stat().
6251 * @param[in] env the environment to operate in.
6252 * @param[in] db the #MDB_db record containing the stats to return.
6253 * @param[out] arg the address of an #MDB_stat structure to receive the stats.
6254 * @return 0, this function always succeeds.
6257 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
6259 arg->ms_psize = env->me_psize;
6260 arg->ms_depth = db->md_depth;
6261 arg->ms_branch_pages = db->md_branch_pages;
6262 arg->ms_leaf_pages = db->md_leaf_pages;
6263 arg->ms_overflow_pages = db->md_overflow_pages;
6264 arg->ms_entries = db->md_entries;
6269 mdb_env_stat(MDB_env *env, MDB_stat *arg)
6273 if (env == NULL || arg == NULL)
6276 toggle = mdb_env_pick_meta(env);
6278 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
6281 /** Set the default comparison functions for a database.
6282 * Called immediately after a database is opened to set the defaults.
6283 * The user can then override them with #mdb_set_compare() or
6284 * #mdb_set_dupsort().
6285 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
6286 * @param[in] dbi A database handle returned by #mdb_open()
6289 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
6291 uint16_t f = txn->mt_dbs[dbi].md_flags;
6293 txn->mt_dbxs[dbi].md_cmp =
6294 (f & MDB_REVERSEKEY) ? mdb_cmp_memnr :
6295 (f & MDB_INTEGERKEY) ? mdb_cmp_cint : mdb_cmp_memn;
6297 txn->mt_dbxs[dbi].md_dcmp =
6298 !(f & MDB_DUPSORT) ? 0 :
6299 ((f & MDB_INTEGERDUP)
6300 ? ((f & MDB_DUPFIXED) ? mdb_cmp_int : mdb_cmp_cint)
6301 : ((f & MDB_REVERSEDUP) ? mdb_cmp_memnr : mdb_cmp_memn));
6304 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
6309 int rc, dbflag, exact;
6310 unsigned int unused = 0;
6313 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
6314 mdb_default_cmp(txn, FREE_DBI);
6320 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
6321 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
6322 mdb_default_cmp(txn, MAIN_DBI);
6326 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
6327 mdb_default_cmp(txn, MAIN_DBI);
6330 /* Is the DB already open? */
6332 for (i=2; i<txn->mt_numdbs; i++) {
6333 if (!txn->mt_dbxs[i].md_name.mv_size) {
6334 /* Remember this free slot */
6335 if (!unused) unused = i;
6338 if (len == txn->mt_dbxs[i].md_name.mv_size &&
6339 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
6345 /* If no free slot and max hit, fail */
6346 if (!unused && txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
6349 /* Find the DB info */
6353 key.mv_data = (void *)name;
6354 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
6355 rc = mdb_cursor_set(&mc, &key, &data, MDB_SET, &exact);
6356 if (rc == MDB_SUCCESS) {
6357 /* make sure this is actually a DB */
6358 MDB_node *node = NODEPTR(mc.mc_pg[mc.mc_top], mc.mc_ki[mc.mc_top]);
6359 if (!(node->mn_flags & F_SUBDATA))
6361 } else if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
6362 /* Create if requested */
6364 data.mv_size = sizeof(MDB_db);
6365 data.mv_data = &dummy;
6366 memset(&dummy, 0, sizeof(dummy));
6367 dummy.md_root = P_INVALID;
6368 dummy.md_flags = flags & 0xffff;
6369 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
6373 /* OK, got info, add to table */
6374 if (rc == MDB_SUCCESS) {
6375 unsigned int slot = unused ? unused : txn->mt_numdbs;
6376 txn->mt_dbxs[slot].md_name.mv_data = strdup(name);
6377 txn->mt_dbxs[slot].md_name.mv_size = len;
6378 txn->mt_dbxs[slot].md_rel = NULL;
6379 txn->mt_dbflags[slot] = dbflag;
6380 memcpy(&txn->mt_dbs[slot], data.mv_data, sizeof(MDB_db));
6382 txn->mt_env->me_dbflags[slot] = txn->mt_dbs[slot].md_flags;
6383 mdb_default_cmp(txn, slot);
6386 txn->mt_env->me_numdbs++;
6393 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
6395 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
6398 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
6401 void mdb_close(MDB_env *env, MDB_dbi dbi)
6404 if (dbi <= MAIN_DBI || dbi >= env->me_numdbs)
6406 ptr = env->me_dbxs[dbi].md_name.mv_data;
6407 env->me_dbxs[dbi].md_name.mv_data = NULL;
6408 env->me_dbxs[dbi].md_name.mv_size = 0;
6412 /** Add all the DB's pages to the free list.
6413 * @param[in] mc Cursor on the DB to free.
6414 * @param[in] subs non-Zero to check for sub-DBs in this DB.
6415 * @return 0 on success, non-zero on failure.
6418 mdb_drop0(MDB_cursor *mc, int subs)
6422 rc = mdb_page_search(mc, NULL, 0);
6423 if (rc == MDB_SUCCESS) {
6428 /* LEAF2 pages have no nodes, cannot have sub-DBs */
6429 if (!subs || IS_LEAF2(mc->mc_pg[mc->mc_top]))
6432 mdb_cursor_copy(mc, &mx);
6433 while (mc->mc_snum > 0) {
6434 if (IS_LEAF(mc->mc_pg[mc->mc_top])) {
6435 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
6436 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
6437 if (ni->mn_flags & F_SUBDATA) {
6438 mdb_xcursor_init1(mc, ni);
6439 rc = mdb_drop0(&mc->mc_xcursor->mx_cursor, 0);
6445 for (i=0; i<NUMKEYS(mc->mc_pg[mc->mc_top]); i++) {
6447 ni = NODEPTR(mc->mc_pg[mc->mc_top], i);
6450 mdb_midl_append(&mc->mc_txn->mt_free_pgs, pg);
6455 rc = mdb_cursor_sibling(mc, 1);
6457 /* no more siblings, go back to beginning
6458 * of previous level. (stack was already popped
6459 * by mdb_cursor_sibling)
6461 for (i=1; i<mc->mc_top; i++)
6462 mc->mc_pg[i] = mx.mc_pg[i];
6466 mdb_midl_append(&mc->mc_txn->mt_free_pgs,
6467 mc->mc_db->md_root);
6472 int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del)
6477 if (!txn || !dbi || dbi >= txn->mt_numdbs)
6480 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY))
6483 rc = mdb_cursor_open(txn, dbi, &mc);
6487 rc = mdb_drop0(mc, mc->mc_db->md_flags & MDB_DUPSORT);
6491 /* Can't delete the main DB */
6492 if (del && dbi > MAIN_DBI) {
6493 rc = mdb_del(txn, MAIN_DBI, &mc->mc_dbx->md_name, NULL);
6495 mdb_close(txn->mt_env, dbi);
6497 txn->mt_dbflags[dbi] |= DB_DIRTY;
6498 txn->mt_dbs[dbi].md_depth = 0;
6499 txn->mt_dbs[dbi].md_branch_pages = 0;
6500 txn->mt_dbs[dbi].md_leaf_pages = 0;
6501 txn->mt_dbs[dbi].md_overflow_pages = 0;
6502 txn->mt_dbs[dbi].md_entries = 0;
6503 txn->mt_dbs[dbi].md_root = P_INVALID;
6506 mdb_cursor_close(mc);
6510 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
6512 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6515 txn->mt_dbxs[dbi].md_cmp = cmp;
6519 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
6521 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6524 txn->mt_dbxs[dbi].md_dcmp = cmp;
6528 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
6530 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6533 txn->mt_dbxs[dbi].md_rel = rel;
6537 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
6539 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
6542 txn->mt_dbxs[dbi].md_relctx = ctx;