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 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
67 #if (__BYTE_ORDER == __LITTLE_ENDIAN) == (__BYTE_ORDER == __BIG_ENDIAN)
68 # error "Unknown or unsupported endianness (__BYTE_ORDER)"
69 #elif (-6 & 5) || CHAR_BIT != 8 || UINT_MAX < 0xffffffff || ULONG_MAX % 0xFFFF
70 # error "Two's complement, reasonably sized integer types, please"
73 /** @defgroup internal MDB Internals
76 /** @defgroup compat Windows Compatibility Macros
77 * A bunch of macros to minimize the amount of platform-specific ifdefs
78 * needed throughout the rest of the code. When the features this library
79 * needs are similar enough to POSIX to be hidden in a one-or-two line
80 * replacement, this macro approach is used.
84 #define pthread_t DWORD
85 #define pthread_mutex_t HANDLE
86 #define pthread_key_t DWORD
87 #define pthread_self() GetCurrentThreadId()
88 #define pthread_key_create(x,y) (*(x) = TlsAlloc())
89 #define pthread_key_delete(x) TlsFree(x)
90 #define pthread_getspecific(x) TlsGetValue(x)
91 #define pthread_setspecific(x,y) TlsSetValue(x,y)
92 #define pthread_mutex_unlock(x) ReleaseMutex(x)
93 #define pthread_mutex_lock(x) WaitForSingleObject(x, INFINITE)
94 #define LOCK_MUTEX_R(env) pthread_mutex_lock((env)->me_rmutex)
95 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock((env)->me_rmutex)
96 #define LOCK_MUTEX_W(env) pthread_mutex_lock((env)->me_wmutex)
97 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock((env)->me_wmutex)
98 #define getpid() GetCurrentProcessId()
99 #define fdatasync(fd) (!FlushFileBuffers(fd))
100 #define ErrCode() GetLastError()
101 #define GET_PAGESIZE(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
102 #define close(fd) CloseHandle(fd)
103 #define munmap(ptr,len) UnmapViewOfFile(ptr)
105 /** Lock the reader mutex.
107 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&(env)->me_txns->mti_mutex)
108 /** Unlock the reader mutex.
110 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&(env)->me_txns->mti_mutex)
112 /** Lock the writer mutex.
113 * Only a single write transaction is allowed at a time. Other writers
114 * will block waiting for this mutex.
116 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&(env)->me_txns->mti_wmutex)
117 /** Unlock the writer mutex.
119 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&(env)->me_txns->mti_wmutex)
121 /** Get the error code for the last failed system function.
123 #define ErrCode() errno
125 /** An abstraction for a file handle.
126 * On POSIX systems file handles are small integers. On Windows
127 * they're opaque pointers.
131 /** A value for an invalid file handle.
132 * Mainly used to initialize file variables and signify that they are
135 #define INVALID_HANDLE_VALUE (-1)
137 /** Get the size of a memory page for the system.
138 * This is the basic size that the platform's memory manager uses, and is
139 * fundamental to the use of memory-mapped files.
141 #define GET_PAGESIZE(x) ((x) = sysconf(_SC_PAGE_SIZE))
147 /** A flag for opening a file and requesting synchronous data writes.
148 * This is only used when writing a meta page. It's not strictly needed;
149 * we could just do a normal write and then immediately perform a flush.
150 * But if this flag is available it saves us an extra system call.
152 * @note If O_DSYNC is undefined but exists in /usr/include,
153 * preferably set some compiler flag to get the definition.
154 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
157 # define MDB_DSYNC O_DSYNC
161 /** A page number in the database.
162 * Note that 64 bit page numbers are overkill, since pages themselves
163 * already represent 12-13 bits of addressable memory, and the OS will
164 * always limit applications to a maximum of 63 bits of address space.
166 * @note In the #MDB_node structure, we only store 48 bits of this value,
167 * which thus limits us to only 60 bits of addressable data.
171 /** A transaction ID.
172 * See struct MDB_txn.mt_txnid for details.
176 /** @defgroup debug Debug Macros
180 /** Enable debug output.
181 * Set this to 1 for copious tracing. Set to 2 to add dumps of all IDLs
182 * read from and written to the database (used for free space management).
187 #if !(__STDC_VERSION__ >= 199901L || defined(__GNUC__))
188 # define DPRINTF (void) /* Vararg macros may be unsupported */
190 /** Print a debug message with printf formatting. */
191 # define DPRINTF(fmt, ...) /**< Requires 2 or more args */ \
192 fprintf(stderr, "%s:%d:(%p) " fmt "\n", __func__, __LINE__, pthread_self(), __VA_ARGS__)
194 # define DPRINTF(fmt, ...) ((void) 0)
196 /** Print a debug string.
197 * The string is printed literally, with no format processing.
199 #define DPUTS(arg) DPRINTF("%s", arg)
202 /** A default memory page size.
203 * The actual size is platform-dependent, but we use this for
204 * boot-strapping. We probably should not be using this any more.
205 * The #GET_PAGESIZE() macro is used to get the actual size.
207 * Note that we don't currently support Huge pages. On Linux,
208 * regular data files cannot use Huge pages, and in general
209 * Huge pages aren't actually pageable. We rely on the OS
210 * demand-pager to read our data and page it out when memory
211 * pressure from other processes is high. So until OSs have
212 * actual paging support for Huge pages, they're not viable.
214 #define PAGESIZE 4096
216 /** The minimum number of keys required in a database page.
217 * Setting this to a larger value will place a smaller bound on the
218 * maximum size of a data item. Data items larger than this size will
219 * be pushed into overflow pages instead of being stored directly in
220 * the B-tree node. This value used to default to 4. With a page size
221 * of 4096 bytes that meant that any item larger than 1024 bytes would
222 * go into an overflow page. That also meant that on average 2-3KB of
223 * each overflow page was wasted space. The value cannot be lower than
224 * 2 because then there would no longer be a tree structure. With this
225 * value, items larger than 2KB will go into overflow pages, and on
226 * average only 1KB will be wasted.
228 #define MDB_MINKEYS 2
230 /** A stamp that identifies a file as an MDB file.
231 * There's nothing special about this value other than that it is easily
232 * recognizable, and it will reflect any byte order mismatches.
234 #define MDB_MAGIC 0xBEEFC0DE
236 /** The version number for a database's file format. */
237 #define MDB_VERSION 1
239 /** The maximum size of a key in the database.
240 * While data items have essentially unbounded size, we require that
241 * keys all fit onto a regular page. This limit could be raised a bit
242 * further if needed; to something just under #PAGESIZE / #MDB_MINKEYS.
244 #define MAXKEYSIZE 511
249 * This is used for printing a hex dump of a key's contents.
251 #define DKBUF char kbuf[(MAXKEYSIZE*2+1)]
252 /** Display a key in hex.
254 * Invoke a function to display a key in hex.
256 #define DKEY(x) mdb_dkey(x, kbuf)
258 #define DKBUF typedef int dummy_kbuf /* so we can put ';' after */
262 /** @defgroup lazylock Lazy Locking
263 * Macros for locks that are't actually needed.
264 * The DB view is always consistent because all writes are wrapped in
265 * the wmutex. Finer-grained locks aren't necessary.
269 /** Use lazy locking. I.e., don't lock these accesses at all. */
273 /** Grab the reader lock */
274 #define LAZY_MUTEX_LOCK(x)
275 /** Release the reader lock */
276 #define LAZY_MUTEX_UNLOCK(x)
277 /** Release the DB table reader/writer lock */
278 #define LAZY_RWLOCK_UNLOCK(x)
279 /** Grab the DB table write lock */
280 #define LAZY_RWLOCK_WRLOCK(x)
281 /** Grab the DB table read lock */
282 #define LAZY_RWLOCK_RDLOCK(x)
283 /** Declare the DB table rwlock. Should not be followed by ';'. */
284 #define LAZY_RWLOCK_DEF(x)
285 /** Initialize the DB table rwlock */
286 #define LAZY_RWLOCK_INIT(x,y)
287 /** Destroy the DB table rwlock */
288 #define LAZY_RWLOCK_DESTROY(x)
290 #define LAZY_MUTEX_LOCK(x) pthread_mutex_lock(x)
291 #define LAZY_MUTEX_UNLOCK(x) pthread_mutex_unlock(x)
292 #define LAZY_RWLOCK_UNLOCK(x) pthread_rwlock_unlock(x)
293 #define LAZY_RWLOCK_WRLOCK(x) pthread_rwlock_wrlock(x)
294 #define LAZY_RWLOCK_RDLOCK(x) pthread_rwlock_rdlock(x)
295 #define LAZY_RWLOCK_DEF(x) pthread_rwlock_t x;
296 #define LAZY_RWLOCK_INIT(x,y) pthread_rwlock_init(x,y)
297 #define LAZY_RWLOCK_DESTROY(x) pthread_rwlock_destroy(x)
301 /** An invalid page number.
302 * Mainly used to denote an empty tree.
304 #define P_INVALID (~0UL)
306 /** Test if a flag \b f is set in a flag word \b w. */
307 #define F_ISSET(w, f) (((w) & (f)) == (f))
309 /** Used for offsets within a single page.
310 * Since memory pages are typically 4 or 8KB in size, 12-13 bits,
313 typedef uint16_t indx_t;
315 /** Default size of memory map.
316 * This is certainly too small for any actual applications. Apps should always set
317 * the size explicitly using #mdb_env_set_mapsize().
319 #define DEFAULT_MAPSIZE 1048576
321 /** @defgroup readers Reader Lock Table
322 * Readers don't acquire any locks for their data access. Instead, they
323 * simply record their transaction ID in the reader table. The reader
324 * mutex is needed just to find an empty slot in the reader table. The
325 * slot's address is saved in thread-specific data so that subsequent read
326 * transactions started by the same thread need no further locking to proceed.
328 * Since the database uses multi-version concurrency control, readers don't
329 * actually need any locking. This table is used to keep track of which
330 * readers are using data from which old transactions, so that we'll know
331 * when a particular old transaction is no longer in use. Old transactions
332 * that have discarded any data pages can then have those pages reclaimed
333 * for use by a later write transaction.
335 * The lock table is constructed such that reader slots are aligned with the
336 * processor's cache line size. Any slot is only ever used by one thread.
337 * This alignment guarantees that there will be no contention or cache
338 * thrashing as threads update their own slot info, and also eliminates
339 * any need for locking when accessing a slot.
341 * A writer thread will scan every slot in the table to determine the oldest
342 * outstanding reader transaction. Any freed pages older than this will be
343 * reclaimed by the writer. The writer doesn't use any locks when scanning
344 * this table. This means that there's no guarantee that the writer will
345 * see the most up-to-date reader info, but that's not required for correct
346 * operation - all we need is to know the upper bound on the oldest reader,
347 * we don't care at all about the newest reader. So the only consequence of
348 * reading stale information here is that old pages might hang around a
349 * while longer before being reclaimed. That's actually good anyway, because
350 * the longer we delay reclaiming old pages, the more likely it is that a
351 * string of contiguous pages can be found after coalescing old pages from
352 * many old transactions together.
354 * @todo We don't actually do such coalescing yet, we grab pages from one
355 * old transaction at a time.
358 /** Number of slots in the reader table.
359 * This value was chosen somewhat arbitrarily. 126 readers plus a
360 * couple mutexes fit exactly into 8KB on my development machine.
361 * Applications should set the table size using #mdb_env_set_maxreaders().
363 #define DEFAULT_READERS 126
365 /** The size of a CPU cache line in bytes. We want our lock structures
366 * aligned to this size to avoid false cache line sharing in the
368 * This value works for most CPUs. For Itanium this should be 128.
374 /** The information we store in a single slot of the reader table.
375 * In addition to a transaction ID, we also record the process and
376 * thread ID that owns a slot, so that we can detect stale information,
377 * e.g. threads or processes that went away without cleaning up.
378 * @note We currently don't check for stale records. We simply re-init
379 * the table when we know that we're the only process opening the
382 typedef struct MDB_rxbody {
383 /** The current Transaction ID when this transaction began.
384 * Multiple readers that start at the same time will probably have the
385 * same ID here. Again, it's not important to exclude them from
386 * anything; all we need to know is which version of the DB they
387 * started from so we can avoid overwriting any data used in that
388 * particular version.
391 /** The process ID of the process owning this reader txn. */
393 /** The thread ID of the thread owning this txn. */
397 /** The actual reader record, with cacheline padding. */
398 typedef struct MDB_reader {
401 /** shorthand for mrb_txnid */
402 #define mr_txnid mru.mrx.mrb_txnid
403 #define mr_pid mru.mrx.mrb_pid
404 #define mr_tid mru.mrx.mrb_tid
405 /** cache line alignment */
406 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
410 /** The header for the reader table.
411 * The table resides in a memory-mapped file. (This is a different file
412 * than is used for the main database.)
414 * For POSIX the actual mutexes reside in the shared memory of this
415 * mapped file. On Windows, mutexes are named objects allocated by the
416 * kernel; we store the mutex names in this mapped file so that other
417 * processes can grab them. This same approach will also be used on
418 * MacOSX/Darwin (using named semaphores) since MacOSX doesn't support
419 * process-shared POSIX mutexes.
421 typedef struct MDB_txbody {
422 /** Stamp identifying this as an MDB lock file. It must be set
425 /** Version number of this lock file. Must be set to #MDB_VERSION. */
426 uint32_t mtb_version;
430 /** Mutex protecting access to this table.
431 * This is the reader lock that #LOCK_MUTEX_R acquires.
433 pthread_mutex_t mtb_mutex;
435 /** The ID of the last transaction committed to the database.
436 * This is recorded here only for convenience; the value can always
437 * be determined by reading the main database meta pages.
440 /** The number of slots that have been used in the reader table.
441 * This always records the maximum count, it is not decremented
442 * when readers release their slots.
444 unsigned mtb_numreaders;
445 /** The ID of the most recent meta page in the database.
446 * This is recorded here only for convenience; the value can always
447 * be determined by reading the main database meta pages.
449 uint32_t mtb_me_toggle;
452 /** The actual reader table definition. */
453 typedef struct MDB_txninfo {
456 #define mti_magic mt1.mtb.mtb_magic
457 #define mti_version mt1.mtb.mtb_version
458 #define mti_mutex mt1.mtb.mtb_mutex
459 #define mti_rmname mt1.mtb.mtb_rmname
460 #define mti_txnid mt1.mtb.mtb_txnid
461 #define mti_numreaders mt1.mtb.mtb_numreaders
462 #define mti_me_toggle mt1.mtb.mtb_me_toggle
463 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
468 #define mti_wmname mt2.mt2_wmname
470 pthread_mutex_t mt2_wmutex;
471 #define mti_wmutex mt2.mt2_wmutex
473 char pad[(sizeof(pthread_mutex_t)+CACHELINE-1) & ~(CACHELINE-1)];
475 MDB_reader mti_readers[1];
479 /** Common header for all page types.
480 * Overflow pages occupy a number of contiguous pages with no
481 * headers on any page after the first.
483 typedef struct MDB_page {
484 #define mp_pgno mp_p.p_pgno
485 #define mp_next mp_p.p_next
487 pgno_t p_pgno; /**< page number */
488 void * p_next; /**< for in-memory list of freed structs */
490 #define P_BRANCH 0x01 /**< branch page */
491 #define P_LEAF 0x02 /**< leaf page */
492 #define P_OVERFLOW 0x04 /**< overflow page */
493 #define P_META 0x08 /**< meta page */
494 #define P_DIRTY 0x10 /**< dirty page */
495 #define P_LEAF2 0x20 /**< for #MDB_DUPFIXED records */
497 #define mp_lower mp_pb.pb.pb_lower
498 #define mp_upper mp_pb.pb.pb_upper
499 #define mp_pages mp_pb.pb_pages
502 indx_t pb_lower; /**< lower bound of free space */
503 indx_t pb_upper; /**< upper bound of free space */
505 uint32_t pb_pages; /**< number of overflow pages */
507 indx_t mp_ptrs[1]; /**< dynamic size */
510 /** Size of the page header, excluding dynamic data at the end */
511 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
513 /** Address of first usable data byte in a page, after the header */
514 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
516 /** Number of nodes on a page */
517 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
519 /** The amount of space remaining in the page */
520 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
522 /** The percentage of space used in the page, in tenths of a percent. */
523 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
524 ((env)->me_psize - PAGEHDRSZ))
525 /** The minimum page fill factor, in tenths of a percent.
526 * Pages emptier than this are candidates for merging.
528 #define FILL_THRESHOLD 250
530 /** Test if a page is a leaf page */
531 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
532 /** Test if a page is a LEAF2 page */
533 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
534 /** Test if a page is a branch page */
535 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
536 /** Test if a page is an overflow page */
537 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
539 /** The number of overflow pages needed to store the given size. */
540 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
542 /** Header for a single key/data pair within a page.
543 * We guarantee 2-byte alignment for nodes.
545 typedef struct MDB_node {
546 /** lo and hi are used for data size on leaf nodes and for
547 * child pgno on branch nodes. On 64 bit platforms, flags
548 * is also used for pgno. (Branch nodes have no flags).
549 * They are in in host byte order in case that lets some
550 * accesses be optimized into a 32-bit word access.
552 #define mn_lo mn_offset[__BYTE_ORDER!=__LITTLE_ENDIAN]
553 #define mn_hi mn_offset[__BYTE_ORDER==__LITTLE_ENDIAN] /**< part of dsize or pgno */
554 unsigned short mn_offset[2];
555 unsigned short mn_flags; /**< flags for special node types */
556 #define F_BIGDATA 0x01 /**< data put on overflow page */
557 #define F_SUBDATA 0x02 /**< data is a sub-database */
558 #define F_DUPDATA 0x04 /**< data has duplicates */
559 unsigned short mn_ksize; /**< key size */
560 char mn_data[1]; /**< key and data are appended here */
563 /** Size of the node header, excluding dynamic data at the end */
564 #define NODESIZE offsetof(MDB_node, mn_data)
566 /** Bit position of top word in page number, for shifting mn_flags */
567 #define PGNO_TOPWORD ((pgno_t)-1 > 0xffffffffu ? 32 : 0)
569 /** Size of a node in a branch page with a given key.
570 * This is just the node header plus the key, there is no data.
572 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
574 /** Size of a node in a leaf page with a given key and data.
575 * This is node header plus key plus data size.
577 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
579 /** Address of node \b i in page \b p */
580 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
582 /** Address of the key for the node */
583 #define NODEKEY(node) (void *)((node)->mn_data)
585 /** Address of the data for a node */
586 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
588 /** Get the page number pointed to by a branch node */
589 #define NODEPGNO(node) \
590 ((node)->mn_lo | ((pgno_t) (node)->mn_hi << 16) | \
591 (PGNO_TOPWORD ? ((pgno_t) (node)->mn_flags << PGNO_TOPWORD) : 0))
592 /** Set the page number in a branch node */
593 #define SETPGNO(node,pgno) do { \
594 (node)->mn_lo = (pgno) & 0xffff; (node)->mn_hi = (pgno) >> 16; \
595 if (PGNO_TOPWORD) (node)->mn_flags = (pgno) >> PGNO_TOPWORD; } while(0)
597 /** Get the size of the data in a leaf node */
598 #define NODEDSZ(node) ((node)->mn_lo | ((unsigned)(node)->mn_hi << 16))
599 /** Set the size of the data for a leaf node */
600 #define SETDSZ(node,size) do { \
601 (node)->mn_lo = (size) & 0xffff; (node)->mn_hi = (size) >> 16;} while(0)
602 /** The size of a key in a node */
603 #define NODEKSZ(node) ((node)->mn_ksize)
605 /** The address of a key in a LEAF2 page.
606 * LEAF2 pages are used for #MDB_DUPFIXED sorted-duplicate sub-DBs.
607 * There are no node headers, keys are stored contiguously.
609 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
611 /** Set the \b node's key into \b key, if requested. */
612 #define MDB_SET_KEY(node, key) { if ((key) != NULL) { \
613 (key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node); } }
615 /** Information about a single database in the environment. */
616 typedef struct MDB_db {
617 uint32_t md_pad; /**< also ksize for LEAF2 pages */
618 uint16_t md_flags; /**< @ref mdb_open */
619 uint16_t md_depth; /**< depth of this tree */
620 pgno_t md_branch_pages; /**< number of internal pages */
621 pgno_t md_leaf_pages; /**< number of leaf pages */
622 pgno_t md_overflow_pages; /**< number of overflow pages */
623 size_t md_entries; /**< number of data items */
624 pgno_t md_root; /**< the root page of this tree */
627 /** Handle for the DB used to track free pages. */
629 /** Handle for the default DB. */
632 /** Meta page content. */
633 typedef struct MDB_meta {
634 /** Stamp identifying this as an MDB data file. It must be set
637 /** Version number of this lock file. Must be set to #MDB_VERSION. */
639 void *mm_address; /**< address for fixed mapping */
640 size_t mm_mapsize; /**< size of mmap region */
641 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
642 /** The size of pages used in this DB */
643 #define mm_psize mm_dbs[0].md_pad
644 /** Any persistent environment flags. @ref mdb_env */
645 #define mm_flags mm_dbs[0].md_flags
646 pgno_t mm_last_pg; /**< last used page in file */
647 txnid_t mm_txnid; /**< txnid that committed this page */
650 /** Auxiliary DB info.
651 * The information here is mostly static/read-only. There is
652 * only a single copy of this record in the environment.
653 * The \b md_dirty flag is not read-only, but only a write
654 * transaction can ever update it, and only write transactions
655 * need to worry about it.
657 typedef struct MDB_dbx {
658 MDB_val md_name; /**< name of the database */
659 MDB_cmp_func *md_cmp; /**< function for comparing keys */
660 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
661 MDB_rel_func *md_rel; /**< user relocate function */
662 MDB_dbi md_parent; /**< parent DB of a sub-DB */
663 unsigned int md_dirty; /**< TRUE if DB was written in this txn */
666 /** A database transaction.
667 * Every operation requires a transaction handle.
670 pgno_t mt_next_pgno; /**< next unallocated page */
671 /** The ID of this transaction. IDs are integers incrementing from 1.
672 * Only committed write transactions increment the ID. If a transaction
673 * aborts, the ID may be re-used by the next writer.
676 MDB_env *mt_env; /**< the DB environment */
677 /** The list of pages that became unused during this transaction.
682 ID2L dirty_list; /**< modified pages */
683 MDB_reader *reader; /**< this thread's slot in the reader table */
685 /** Array of records for each DB known in the environment. */
687 /** Array of MDB_db records for each known DB */
689 /** Number of DB records in use. This number only ever increments;
690 * we don't decrement it when individual DB handles are closed.
694 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
695 #define MDB_TXN_ERROR 0x02 /**< an error has occurred */
696 unsigned int mt_flags;
697 /** Tracks which of the two meta pages was used at the start
698 * of this transaction.
700 unsigned int mt_toggle;
703 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
704 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
705 * raise this on a 64 bit machine.
707 #define CURSOR_STACK 32
711 /** Cursors are used for all DB operations */
713 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
714 struct MDB_xcursor *mc_xcursor;
715 /** The transaction that owns this cursor */
717 /** The database handle this cursor operates on */
719 unsigned short mc_snum; /**< number of pushed pages */
720 unsigned short mc_top; /**< index of top page, mc_snum-1 */
721 unsigned int mc_flags;
722 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
723 #define C_EOF 0x02 /**< No more data */
724 #define C_XDIRTY 0x04 /**< @deprecated mc_xcursor needs to be flushed */
725 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
726 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
729 /** Context for sorted-dup records.
730 * We could have gone to a fully recursive design, with arbitrarily
731 * deep nesting of sub-databases. But for now we only handle these
732 * levels - main DB, optional sub-DB, sorted-duplicate DB.
734 typedef struct MDB_xcursor {
735 /** A sub-cursor for traversing the Dup DB */
736 MDB_cursor mx_cursor;
737 /** A fake transaction struct for pointing to our own table
741 /** Our private DB information tables. Slots 0 and 1 are always
742 * copies of the corresponding slots in the main transaction. These
743 * hold the FREEDB and MAINDB, respectively. If the main cursor is
744 * on a sub-database, that will be copied to slot 2, and the duplicate
745 * database info will be in slot 3. If the main cursor is on the MAINDB
746 * then the duplicate DB info will be in slot 2 and slot 3 will be unused.
753 /** A set of pages freed by an earlier transaction. */
754 typedef struct MDB_oldpages {
755 /** Usually we only read one record from the FREEDB at a time, but
756 * in case we read more, this will chain them together.
758 struct MDB_oldpages *mo_next;
759 /** The ID of the transaction in which these pages were freed. */
761 /** An #IDL of the pages */
762 pgno_t mo_pages[1]; /* dynamic */
765 /** The database environment. */
767 HANDLE me_fd; /**< The main data file */
768 HANDLE me_lfd; /**< The lock file */
769 HANDLE me_mfd; /**< just for writing the meta pages */
770 /** Failed to update the meta page. Probably an I/O error. */
771 #define MDB_FATAL_ERROR 0x80000000U
773 uint32_t me_extrapad; /**< unused for now */
774 unsigned int me_maxreaders; /**< size of the reader table */
775 MDB_dbi me_numdbs; /**< number of DBs opened */
776 MDB_dbi me_maxdbs; /**< size of the DB table */
777 char *me_path; /**< path to the DB files */
778 char *me_map; /**< the memory map of the data file */
779 MDB_txninfo *me_txns; /**< the memory map of the lock file */
780 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
781 MDB_txn *me_txn; /**< current write transaction */
782 size_t me_mapsize; /**< size of the data memory map */
783 off_t me_size; /**< current file size */
784 pgno_t me_maxpg; /**< me_mapsize / me_psize */
785 unsigned int me_psize; /**< size of a page, from #GET_PAGESIZE */
786 unsigned int me_db_toggle; /**< which DB table is current */
787 MDB_dbx *me_dbxs; /**< array of static DB info */
788 MDB_db *me_dbs[2]; /**< two arrays of MDB_db info */
789 MDB_oldpages *me_pghead; /**< list of old page records */
790 pthread_key_t me_txkey; /**< thread-key for readers */
791 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
792 /** IDL of pages that became unused in a write txn */
793 pgno_t me_free_pgs[MDB_IDL_UM_SIZE];
794 /** ID2L of pages that were written during a write txn */
795 ID2 me_dirty_list[MDB_IDL_UM_SIZE];
796 /** rwlock for the DB tables, if #LAZY_LOCKS is false */
797 LAZY_RWLOCK_DEF(me_dblock)
799 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
803 /** max number of pages to commit in one writev() call */
804 #define MDB_COMMIT_PAGES 64
806 static MDB_page *mdb_alloc_page(MDB_cursor *mc, int num);
807 static int mdb_touch(MDB_cursor *mc);
809 static int mdb_search_page_root(MDB_cursor *mc,
810 MDB_val *key, int modify);
811 static int mdb_search_page(MDB_cursor *mc,
812 MDB_val *key, int modify);
814 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
815 static int mdb_env_read_meta(MDB_env *env, int *which);
816 static int mdb_env_write_meta(MDB_txn *txn);
817 static int mdb_get_page(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
819 static MDB_node *mdb_search_node(MDB_cursor *mc, MDB_val *key, int *exactp);
820 static int mdb_add_node(MDB_cursor *mc, indx_t indx,
821 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags);
822 static void mdb_del_node(MDB_page *mp, indx_t indx, int ksize);
823 static int mdb_del0(MDB_cursor *mc, MDB_node *leaf);
824 static int mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
826 static int mdb_rebalance(MDB_cursor *mc);
827 static int mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
828 static int mdb_move_node(MDB_cursor *csrc, MDB_cursor *cdst);
829 static int mdb_merge(MDB_cursor *csrc, MDB_cursor *cdst);
830 static int mdb_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
832 static MDB_page *mdb_new_page(MDB_cursor *mc, uint32_t flags, int num);
834 static void cursor_pop_page(MDB_cursor *mc);
835 static int cursor_push_page(MDB_cursor *mc, MDB_page *mp);
837 static int mdb_sibling(MDB_cursor *mc, int move_right);
838 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
839 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
840 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
842 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
843 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
845 static void mdb_xcursor_init0(MDB_cursor *mc);
846 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
847 static void mdb_xcursor_init2(MDB_cursor *mc);
848 static void mdb_xcursor_fini(MDB_cursor *mc);
850 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
851 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
853 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
856 static MDB_cmp_func memncmp, memnrcmp, intcmp, cintcmp;
860 static SECURITY_DESCRIPTOR mdb_null_sd;
861 static SECURITY_ATTRIBUTES mdb_all_sa;
862 static int mdb_sec_inited;
865 /** Return the library version info. */
867 mdb_version(int *major, int *minor, int *patch)
869 if (major) *major = MDB_VERSION_MAJOR;
870 if (minor) *minor = MDB_VERSION_MINOR;
871 if (patch) *patch = MDB_VERSION_PATCH;
872 return MDB_VERSION_STRING;
875 /** Table of descriptions for MDB @ref errors */
876 static char *const mdb_errstr[] = {
877 "MDB_KEYEXIST: Key/data pair already exists",
878 "MDB_NOTFOUND: No matching key/data pair found",
879 "MDB_PAGE_NOTFOUND: Requested page not found",
880 "MDB_CORRUPTED: Located page was wrong type",
881 "MDB_PANIC: Update of meta page failed",
882 "MDB_VERSION_MISMATCH: Database environment version mismatch"
886 mdb_strerror(int err)
889 return ("Successful return: 0");
891 if (err >= MDB_KEYEXIST && err <= MDB_VERSION_MISMATCH)
892 return mdb_errstr[err - MDB_KEYEXIST];
894 return strerror(err);
898 /** Display a key in hexadecimal and return the address of the result.
899 * @param[in] key the key to display
900 * @param[in] buf the buffer to write into. Should always be #DKBUF.
901 * @return The key in hexadecimal form.
904 mdb_dkey(MDB_val *key, char *buf)
907 unsigned char *c = key->mv_data;
909 if (key->mv_size > MAXKEYSIZE)
911 /* may want to make this a dynamic check: if the key is mostly
912 * printable characters, print it as-is instead of converting to hex.
915 for (i=0; i<key->mv_size; i++)
916 ptr += sprintf(ptr, "%02x", *c++);
918 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
925 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
927 return txn->mt_dbxs[dbi].md_cmp(a, b);
930 /** Compare two data items according to a particular database.
931 * This returns a comparison as if the two items were data items of
932 * a sorted duplicates #MDB_DUPSORT database.
933 * @param[in] txn A transaction handle returned by #mdb_txn_begin()
934 * @param[in] dbi A database handle returned by #mdb_open()
935 * @param[in] a The first item to compare
936 * @param[in] b The second item to compare
937 * @return < 0 if a < b, 0 if a == b, > 0 if a > b
940 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
942 if (txn->mt_dbxs[dbi].md_dcmp)
943 return txn->mt_dbxs[dbi].md_dcmp(a, b);
945 return EINVAL; /* too bad you can't distinguish this from a valid result */
948 /** Allocate pages for writing.
949 * If there are free pages available from older transactions, they
950 * will be re-used first. Otherwise a new page will be allocated.
951 * @param[in] mc cursor A cursor handle identifying the transaction and
952 * database for which we are allocating.
953 * @param[in] num the number of pages to allocate.
954 * @return Address of the allocated page(s). Requests for multiple pages
955 * will always be satisfied by a single contiguous chunk of memory.
958 mdb_alloc_page(MDB_cursor *mc, int num)
960 MDB_txn *txn = mc->mc_txn;
962 pgno_t pgno = P_INVALID;
965 if (txn->mt_txnid > 2) {
967 if (!txn->mt_env->me_pghead && mc->mc_dbi != FREE_DBI &&
968 txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
969 /* See if there's anything in the free DB */
972 txnid_t *kptr, oldest;
975 m2.mc_dbi = FREE_DBI;
978 mdb_search_page(&m2, NULL, 0);
979 leaf = NODEPTR(m2.mc_pg[m2.mc_top], 0);
980 kptr = (txnid_t *)NODEKEY(leaf);
984 oldest = txn->mt_txnid - 1;
985 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
986 txnid_t mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
987 if (mr && mr < oldest)
992 if (oldest > *kptr) {
993 /* It's usable, grab it.
999 mdb_read_data(txn, leaf, &data);
1000 idl = (ID *) data.mv_data;
1001 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
1002 mop->mo_next = txn->mt_env->me_pghead;
1003 mop->mo_txnid = *kptr;
1004 txn->mt_env->me_pghead = mop;
1005 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
1010 DPRINTF("IDL read txn %zu root %zu num %zu",
1011 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1012 for (i=0; i<idl[0]; i++) {
1013 DPRINTF("IDL %zu", idl[i+1]);
1017 /* drop this IDL from the DB */
1018 m2.mc_ki[m2.mc_top] = 0;
1019 m2.mc_flags = C_INITIALIZED;
1020 mdb_cursor_del(&m2, 0);
1023 if (txn->mt_env->me_pghead) {
1024 MDB_oldpages *mop = txn->mt_env->me_pghead;
1026 /* FIXME: For now, always use fresh pages. We
1027 * really ought to search the free list for a
1032 /* peel pages off tail, so we only have to truncate the list */
1033 pgno = MDB_IDL_LAST(mop->mo_pages);
1034 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
1036 if (mop->mo_pages[2] > mop->mo_pages[1])
1037 mop->mo_pages[0] = 0;
1041 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
1042 txn->mt_env->me_pghead = mop->mo_next;
1049 if (pgno == P_INVALID) {
1050 /* DB size is maxed out */
1051 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg)
1054 if (txn->mt_env->me_dpages && num == 1) {
1055 np = txn->mt_env->me_dpages;
1056 txn->mt_env->me_dpages = np->mp_next;
1058 if ((np = malloc(txn->mt_env->me_psize * num )) == NULL)
1061 if (pgno == P_INVALID) {
1062 np->mp_pgno = txn->mt_next_pgno;
1063 txn->mt_next_pgno += num;
1067 mid.mid = np->mp_pgno;
1069 mdb_mid2l_insert(txn->mt_u.dirty_list, &mid);
1074 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1075 * @param[in] mc cursor pointing to the page to be touched
1076 * @return 0 on success, non-zero on failure.
1079 mdb_touch(MDB_cursor *mc)
1081 MDB_page *mp = mc->mc_pg[mc->mc_top];
1084 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1086 if ((np = mdb_alloc_page(mc, 1)) == NULL)
1088 DPRINTF("touched db %u page %zu -> %zu", mc->mc_dbi, mp->mp_pgno, np->mp_pgno);
1089 assert(mp->mp_pgno != np->mp_pgno);
1090 mdb_midl_append(mc->mc_txn->mt_free_pgs, mp->mp_pgno);
1092 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1095 mp->mp_flags |= P_DIRTY;
1097 mc->mc_pg[mc->mc_top] = mp;
1098 /** If this page has a parent, update the parent to point to
1102 SETPGNO(NODEPTR(mc->mc_pg[mc->mc_top-1], mc->mc_ki[mc->mc_top-1]), mp->mp_pgno);
1108 mdb_env_sync(MDB_env *env, int force)
1111 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1112 if (fdatasync(env->me_fd))
1119 mdb_txn_reset0(MDB_txn *txn);
1121 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
1122 * @param[in] txn the transaction handle to initialize
1123 * @return 0 on success, non-zero on failure. This can only
1124 * fail for read-only transactions, and then only if the
1125 * reader table is full.
1128 mdb_txn_renew0(MDB_txn *txn)
1130 MDB_env *env = txn->mt_env;
1132 if (txn->mt_flags & MDB_TXN_RDONLY) {
1133 MDB_reader *r = pthread_getspecific(env->me_txkey);
1136 pid_t pid = getpid();
1137 pthread_t tid = pthread_self();
1140 for (i=0; i<env->me_txns->mti_numreaders; i++)
1141 if (env->me_txns->mti_readers[i].mr_pid == 0)
1143 if (i == env->me_maxreaders) {
1144 UNLOCK_MUTEX_R(env);
1147 env->me_txns->mti_readers[i].mr_pid = pid;
1148 env->me_txns->mti_readers[i].mr_tid = tid;
1149 if (i >= env->me_txns->mti_numreaders)
1150 env->me_txns->mti_numreaders = i+1;
1151 UNLOCK_MUTEX_R(env);
1152 r = &env->me_txns->mti_readers[i];
1153 pthread_setspecific(env->me_txkey, r);
1155 txn->mt_txnid = env->me_txns->mti_txnid;
1156 txn->mt_toggle = env->me_txns->mti_me_toggle;
1157 r->mr_txnid = txn->mt_txnid;
1158 txn->mt_u.reader = r;
1162 txn->mt_txnid = env->me_txns->mti_txnid+1;
1163 txn->mt_toggle = env->me_txns->mti_me_toggle;
1164 txn->mt_u.dirty_list = env->me_dirty_list;
1165 txn->mt_u.dirty_list[0].mid = 0;
1166 txn->mt_free_pgs = env->me_free_pgs;
1167 txn->mt_free_pgs[0] = 0;
1168 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1172 /* Copy the DB arrays */
1173 LAZY_RWLOCK_RDLOCK(&env->me_dblock);
1174 txn->mt_numdbs = env->me_numdbs;
1175 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
1176 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
1177 if (txn->mt_numdbs > 2)
1178 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
1179 (txn->mt_numdbs - 2) * sizeof(MDB_db));
1180 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1186 mdb_txn_renew(MDB_txn *txn)
1193 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
1194 DPUTS("environment had fatal error, must shutdown!");
1198 rc = mdb_txn_renew0(txn);
1199 if (rc == MDB_SUCCESS) {
1200 DPRINTF("renew txn %zu%c %p on mdbenv %p, root page %zu",
1201 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
1202 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1208 mdb_txn_begin(MDB_env *env, unsigned int flags, MDB_txn **ret)
1213 if (env->me_flags & MDB_FATAL_ERROR) {
1214 DPUTS("environment had fatal error, must shutdown!");
1217 if ((txn = calloc(1, sizeof(MDB_txn) + env->me_maxdbs * sizeof(MDB_db))) == NULL) {
1218 DPRINTF("calloc: %s", strerror(ErrCode()));
1221 txn->mt_dbs = (MDB_db *)(txn+1);
1222 if (flags & MDB_RDONLY) {
1223 txn->mt_flags |= MDB_TXN_RDONLY;
1227 rc = mdb_txn_renew0(txn);
1232 DPRINTF("begin txn %zu%c %p on mdbenv %p, root page %zu",
1233 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
1234 (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
1240 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
1241 * @param[in] txn the transaction handle to reset
1244 mdb_txn_reset0(MDB_txn *txn)
1246 MDB_env *env = txn->mt_env;
1248 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1249 txn->mt_u.reader->mr_txnid = 0;
1256 /* return all dirty pages to dpage list */
1257 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1258 dp = txn->mt_u.dirty_list[i].mptr;
1259 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1260 dp->mp_next = txn->mt_env->me_dpages;
1261 txn->mt_env->me_dpages = dp;
1263 /* large pages just get freed directly */
1268 while ((mop = txn->mt_env->me_pghead)) {
1269 txn->mt_env->me_pghead = mop->mo_next;
1274 for (dbi=2; dbi<env->me_numdbs; dbi++)
1275 env->me_dbxs[dbi].md_dirty = 0;
1276 /* The writer mutex was locked in mdb_txn_begin. */
1277 UNLOCK_MUTEX_W(env);
1282 mdb_txn_reset(MDB_txn *txn)
1287 DPRINTF("reset txn %zu%c %p on mdbenv %p, root page %zu",
1288 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
1289 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1291 mdb_txn_reset0(txn);
1295 mdb_txn_abort(MDB_txn *txn)
1300 DPRINTF("abort txn %zu%c %p on mdbenv %p, root page %zu",
1301 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
1302 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1304 mdb_txn_reset0(txn);
1309 mdb_txn_commit(MDB_txn *txn)
1320 assert(txn != NULL);
1321 assert(txn->mt_env != NULL);
1325 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1330 if (txn != env->me_txn) {
1331 DPUTS("attempt to commit unknown transaction");
1336 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1337 DPUTS("error flag is set, can't commit");
1342 if (!txn->mt_u.dirty_list[0].mid)
1345 DPRINTF("committing txn %zu %p on mdbenv %p, root page %zu",
1346 txn->mt_txnid, txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
1349 mc.mc_dbi = FREE_DBI;
1352 /* should only be one record now */
1353 if (env->me_pghead) {
1354 /* make sure first page of freeDB is touched and on freelist */
1355 mdb_search_page(&mc, NULL, 1);
1357 /* save to free list */
1358 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
1362 /* make sure last page of freeDB is touched and on freelist */
1363 key.mv_size = MAXKEYSIZE+1;
1365 mdb_search_page(&mc, &key, 1);
1367 mdb_midl_sort(txn->mt_free_pgs);
1371 ID *idl = txn->mt_free_pgs;
1372 DPRINTF("IDL write txn %zu root %zu num %zu",
1373 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1374 for (i=0; i<idl[0]; i++) {
1375 DPRINTF("IDL %zu", idl[i+1]);
1379 /* write to last page of freeDB */
1380 key.mv_size = sizeof(pgno_t);
1381 key.mv_data = &txn->mt_txnid;
1382 data.mv_data = txn->mt_free_pgs;
1383 /* The free list can still grow during this call,
1384 * despite the pre-emptive touches above. So check
1385 * and make sure the entire thing got written.
1388 i = txn->mt_free_pgs[0];
1389 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
1390 rc = mdb_cursor_put(&mc, &key, &data, 0);
1395 } while (i != txn->mt_free_pgs[0]);
1397 /* should only be one record now */
1398 if (env->me_pghead) {
1402 mop = env->me_pghead;
1403 key.mv_size = sizeof(pgno_t);
1404 key.mv_data = &mop->mo_txnid;
1405 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
1406 data.mv_data = mop->mo_pages;
1407 mdb_cursor_put(&mc, &key, &data, 0);
1408 free(env->me_pghead);
1409 env->me_pghead = NULL;
1412 /* Update DB root pointers. Their pages have already been
1413 * touched so this is all in-place and cannot fail.
1418 data.mv_size = sizeof(MDB_db);
1420 mc.mc_dbi = MAIN_DBI;
1422 for (i = 2; i < txn->mt_numdbs; i++) {
1423 if (txn->mt_dbxs[i].md_dirty) {
1424 data.mv_data = &txn->mt_dbs[i];
1425 mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
1430 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
1436 /* Windows actually supports scatter/gather I/O, but only on
1437 * unbuffered file handles. Since we're relying on the OS page
1438 * cache for all our data, that's self-defeating. So we just
1439 * write pages one at a time. We use the ov structure to set
1440 * the write offset, to at least save the overhead of a Seek
1444 memset(&ov, 0, sizeof(ov));
1445 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1447 dp = txn->mt_u.dirty_list[i].mptr;
1448 DPRINTF("committing page %zu", dp->mp_pgno);
1449 size = dp->mp_pgno * env->me_psize;
1450 ov.Offset = size & 0xffffffff;
1451 ov.OffsetHigh = size >> 16;
1452 ov.OffsetHigh >>= 16;
1453 /* clear dirty flag */
1454 dp->mp_flags &= ~P_DIRTY;
1455 wsize = env->me_psize;
1456 if (IS_OVERFLOW(dp)) wsize *= dp->mp_pages;
1457 rc = WriteFile(env->me_fd, dp, wsize, NULL, &ov);
1460 DPRINTF("WriteFile: %d", n);
1467 struct iovec iov[MDB_COMMIT_PAGES];
1471 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1472 dp = txn->mt_u.dirty_list[i].mptr;
1473 if (dp->mp_pgno != next) {
1475 DPRINTF("committing %u dirty pages", n);
1476 rc = writev(env->me_fd, iov, n);
1480 DPUTS("short write, filesystem full?");
1482 DPRINTF("writev: %s", strerror(n));
1489 lseek(env->me_fd, dp->mp_pgno * env->me_psize, SEEK_SET);
1492 DPRINTF("committing page %zu", dp->mp_pgno);
1493 iov[n].iov_len = env->me_psize;
1494 if (IS_OVERFLOW(dp)) iov[n].iov_len *= dp->mp_pages;
1495 iov[n].iov_base = dp;
1496 size += iov[n].iov_len;
1497 next = dp->mp_pgno + (IS_OVERFLOW(dp) ? dp->mp_pages : 1);
1498 /* clear dirty flag */
1499 dp->mp_flags &= ~P_DIRTY;
1500 if (++n >= MDB_COMMIT_PAGES) {
1510 DPRINTF("committing %u dirty pages", n);
1511 rc = writev(env->me_fd, iov, n);
1515 DPUTS("short write, filesystem full?");
1517 DPRINTF("writev: %s", strerror(n));
1524 /* Drop the dirty pages.
1526 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1527 dp = txn->mt_u.dirty_list[i].mptr;
1528 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1529 dp->mp_next = txn->mt_env->me_dpages;
1530 txn->mt_env->me_dpages = dp;
1534 txn->mt_u.dirty_list[i].mid = 0;
1536 txn->mt_u.dirty_list[0].mid = 0;
1538 if ((n = mdb_env_sync(env, 0)) != 0 ||
1539 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
1546 /* update the DB tables */
1548 int toggle = !env->me_db_toggle;
1552 ip = &env->me_dbs[toggle][2];
1553 jp = &txn->mt_dbs[2];
1554 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1555 for (i = 2; i < txn->mt_numdbs; i++) {
1556 if (ip->md_root != jp->md_root)
1561 for (i = 2; i < txn->mt_numdbs; i++) {
1562 if (txn->mt_dbxs[i].md_dirty)
1563 txn->mt_dbxs[i].md_dirty = 0;
1565 env->me_db_toggle = toggle;
1566 env->me_numdbs = txn->mt_numdbs;
1567 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1570 UNLOCK_MUTEX_W(env);
1576 /** Read the environment parameters of a DB environment before
1577 * mapping it into memory.
1578 * @param[in] env the environment handle
1579 * @param[out] meta address of where to store the meta information
1580 * @return 0 on success, non-zero on failure.
1583 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
1585 char page[PAGESIZE];
1590 /* We don't know the page size yet, so use a minimum value.
1594 if (!ReadFile(env->me_fd, page, PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
1596 if ((rc = read(env->me_fd, page, PAGESIZE)) == 0)
1601 else if (rc != PAGESIZE) {
1605 DPRINTF("read: %s", strerror(err));
1609 p = (MDB_page *)page;
1611 if (!F_ISSET(p->mp_flags, P_META)) {
1612 DPRINTF("page %zu not a meta page", p->mp_pgno);
1617 if (m->mm_magic != MDB_MAGIC) {
1618 DPUTS("meta has invalid magic");
1622 if (m->mm_version != MDB_VERSION) {
1623 DPRINTF("database is version %u, expected version %u",
1624 m->mm_version, MDB_VERSION);
1625 return MDB_VERSION_MISMATCH;
1628 memcpy(meta, m, sizeof(*m));
1632 /** Write the environment parameters of a freshly created DB environment.
1633 * @param[in] env the environment handle
1634 * @param[out] meta address of where to store the meta information
1635 * @return 0 on success, non-zero on failure.
1638 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
1645 DPUTS("writing new meta page");
1647 GET_PAGESIZE(psize);
1649 meta->mm_magic = MDB_MAGIC;
1650 meta->mm_version = MDB_VERSION;
1651 meta->mm_psize = psize;
1652 meta->mm_last_pg = 1;
1653 meta->mm_flags = env->me_flags & 0xffff;
1654 meta->mm_flags |= MDB_INTEGERKEY;
1655 meta->mm_dbs[0].md_root = P_INVALID;
1656 meta->mm_dbs[1].md_root = P_INVALID;
1658 p = calloc(2, psize);
1660 p->mp_flags = P_META;
1663 memcpy(m, meta, sizeof(*meta));
1665 q = (MDB_page *)((char *)p + psize);
1668 q->mp_flags = P_META;
1671 memcpy(m, meta, sizeof(*meta));
1676 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
1677 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
1680 rc = write(env->me_fd, p, psize * 2);
1681 rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
1687 /** Update the environment info to commit a transaction.
1688 * @param[in] txn the transaction that's being committed
1689 * @return 0 on success, non-zero on failure.
1692 mdb_env_write_meta(MDB_txn *txn)
1695 MDB_meta meta, metab;
1697 int rc, len, toggle;
1703 assert(txn != NULL);
1704 assert(txn->mt_env != NULL);
1706 toggle = !txn->mt_toggle;
1707 DPRINTF("writing meta page %d for root page %zu",
1708 toggle, txn->mt_dbs[MAIN_DBI].md_root);
1712 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
1713 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
1715 ptr = (char *)&meta;
1716 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
1717 len = sizeof(MDB_meta) - off;
1720 meta.mm_dbs[0] = txn->mt_dbs[0];
1721 meta.mm_dbs[1] = txn->mt_dbs[1];
1722 meta.mm_last_pg = txn->mt_next_pgno - 1;
1723 meta.mm_txnid = txn->mt_txnid;
1726 off += env->me_psize;
1729 /* Write to the SYNC fd */
1732 memset(&ov, 0, sizeof(ov));
1734 WriteFile(env->me_mfd, ptr, len, (DWORD *)&rc, &ov);
1737 rc = pwrite(env->me_mfd, ptr, len, off);
1742 DPUTS("write failed, disk error?");
1743 /* On a failure, the pagecache still contains the new data.
1744 * Write some old data back, to prevent it from being used.
1745 * Use the non-SYNC fd; we know it will fail anyway.
1747 meta.mm_last_pg = metab.mm_last_pg;
1748 meta.mm_txnid = metab.mm_txnid;
1750 WriteFile(env->me_fd, ptr, len, NULL, &ov);
1752 r2 = pwrite(env->me_fd, ptr, len, off);
1754 env->me_flags |= MDB_FATAL_ERROR;
1757 /* Memory ordering issues are irrelevant; since the entire writer
1758 * is wrapped by wmutex, all of these changes will become visible
1759 * after the wmutex is unlocked. Since the DB is multi-version,
1760 * readers will get consistent data regardless of how fresh or
1761 * how stale their view of these values is.
1763 LAZY_MUTEX_LOCK(&env->me_txns->mti_mutex);
1764 txn->mt_env->me_txns->mti_me_toggle = toggle;
1765 txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
1766 LAZY_MUTEX_UNLOCK(&env->me_txns->mti_mutex);
1771 /** Check both meta pages to see which one is newer.
1772 * @param[in] env the environment handle
1773 * @param[out] which address of where to store the meta toggle ID
1774 * @return 0 on success, non-zero on failure.
1777 mdb_env_read_meta(MDB_env *env, int *which)
1781 assert(env != NULL);
1783 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1786 DPRINTF("Using meta page %d", toggle);
1793 mdb_env_create(MDB_env **env)
1797 e = calloc(1, sizeof(MDB_env));
1798 if (!e) return ENOMEM;
1800 e->me_maxreaders = DEFAULT_READERS;
1802 e->me_fd = INVALID_HANDLE_VALUE;
1803 e->me_lfd = INVALID_HANDLE_VALUE;
1804 e->me_mfd = INVALID_HANDLE_VALUE;
1810 mdb_env_set_mapsize(MDB_env *env, size_t size)
1814 env->me_mapsize = size;
1819 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
1823 env->me_maxdbs = dbs;
1828 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
1830 if (env->me_map || readers < 1)
1832 env->me_maxreaders = readers;
1837 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
1839 if (!env || !readers)
1841 *readers = env->me_maxreaders;
1845 /** Further setup required for opening an MDB environment
1848 mdb_env_open2(MDB_env *env, unsigned int flags)
1850 int i, newenv = 0, toggle;
1854 env->me_flags = flags;
1856 memset(&meta, 0, sizeof(meta));
1858 if ((i = mdb_env_read_header(env, &meta)) != 0) {
1861 DPUTS("new mdbenv");
1865 if (!env->me_mapsize) {
1866 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
1872 LONG sizelo, sizehi;
1873 sizelo = env->me_mapsize & 0xffffffff;
1874 sizehi = env->me_mapsize >> 16; /* pointless on WIN32, only needed on W64 */
1876 /* Windows won't create mappings for zero length files.
1877 * Just allocate the maxsize right now.
1880 SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
1881 if (!SetEndOfFile(env->me_fd))
1883 SetFilePointer(env->me_fd, 0, NULL, 0);
1885 mh = CreateFileMapping(env->me_fd, NULL, PAGE_READONLY,
1886 sizehi, sizelo, NULL);
1889 env->me_map = MapViewOfFileEx(mh, FILE_MAP_READ, 0, 0, env->me_mapsize,
1897 if (meta.mm_address && (flags & MDB_FIXEDMAP))
1899 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
1901 if (env->me_map == MAP_FAILED)
1906 meta.mm_mapsize = env->me_mapsize;
1907 if (flags & MDB_FIXEDMAP)
1908 meta.mm_address = env->me_map;
1909 i = mdb_env_init_meta(env, &meta);
1910 if (i != MDB_SUCCESS) {
1911 munmap(env->me_map, env->me_mapsize);
1915 env->me_psize = meta.mm_psize;
1917 env->me_maxpg = env->me_mapsize / env->me_psize;
1919 p = (MDB_page *)env->me_map;
1920 env->me_metas[0] = METADATA(p);
1921 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
1923 if ((i = mdb_env_read_meta(env, &toggle)) != 0)
1926 DPRINTF("opened database version %u, pagesize %u",
1927 env->me_metas[toggle]->mm_version, env->me_psize);
1928 DPRINTF("depth: %u", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_depth);
1929 DPRINTF("entries: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_entries);
1930 DPRINTF("branch pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_branch_pages);
1931 DPRINTF("leaf pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_leaf_pages);
1932 DPRINTF("overflow pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_overflow_pages);
1933 DPRINTF("root: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_root);
1939 /* Windows doesn't support destructor callbacks for thread-specific storage */
1941 mdb_env_reader_dest(void *ptr)
1943 MDB_reader *reader = ptr;
1945 reader->mr_txnid = 0;
1951 /* downgrade the exclusive lock on the region back to shared */
1953 mdb_env_share_locks(MDB_env *env)
1957 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1959 env->me_txns->mti_me_toggle = toggle;
1960 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
1965 /* First acquire a shared lock. The Unlock will
1966 * then release the existing exclusive lock.
1968 memset(&ov, 0, sizeof(ov));
1969 LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov);
1970 UnlockFile(env->me_lfd, 0, 0, 1, 0);
1974 struct flock lock_info;
1975 /* The shared lock replaces the existing lock */
1976 memset((void *)&lock_info, 0, sizeof(lock_info));
1977 lock_info.l_type = F_RDLCK;
1978 lock_info.l_whence = SEEK_SET;
1979 lock_info.l_start = 0;
1980 lock_info.l_len = 1;
1981 fcntl(env->me_lfd, F_SETLK, &lock_info);
1987 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
1995 if ((env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
1996 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
1997 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
2001 /* Try to get exclusive lock. If we succeed, then
2002 * nobody is using the lock region and we should initialize it.
2005 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
2009 memset(&ov, 0, sizeof(ov));
2010 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
2016 size = GetFileSize(env->me_lfd, NULL);
2018 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
2022 /* Try to get exclusive lock. If we succeed, then
2023 * nobody is using the lock region and we should initialize it.
2026 struct flock lock_info;
2027 memset((void *)&lock_info, 0, sizeof(lock_info));
2028 lock_info.l_type = F_WRLCK;
2029 lock_info.l_whence = SEEK_SET;
2030 lock_info.l_start = 0;
2031 lock_info.l_len = 1;
2032 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
2036 lock_info.l_type = F_RDLCK;
2037 rc = fcntl(env->me_lfd, F_SETLKW, &lock_info);
2044 size = lseek(env->me_lfd, 0, SEEK_END);
2046 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
2047 if (size < rsize && *excl) {
2049 SetFilePointer(env->me_lfd, rsize, NULL, 0);
2050 if (!SetEndOfFile(env->me_lfd)) {
2055 if (ftruncate(env->me_lfd, rsize) != 0) {
2062 size = rsize - sizeof(MDB_txninfo);
2063 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
2068 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
2074 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
2076 if (!env->me_txns) {
2082 env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
2084 if (env->me_txns == MAP_FAILED) {
2092 if (!mdb_sec_inited) {
2093 InitializeSecurityDescriptor(&mdb_null_sd,
2094 SECURITY_DESCRIPTOR_REVISION);
2095 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
2096 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2097 mdb_all_sa.bInheritHandle = FALSE;
2098 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
2101 /* FIXME: only using up to 20 characters of the env path here,
2102 * probably not enough to assure uniqueness...
2104 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%.20s", lpath);
2105 ptr = env->me_txns->mti_rmname + sizeof("Global\\MDBr");
2106 while ((ptr = strchr(ptr, '\\')))
2108 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
2109 if (!env->me_rmutex) {
2113 sprintf(env->me_txns->mti_rmname, "Global\\MDBw%.20s", lpath);
2114 ptr = env->me_txns->mti_rmname + sizeof("Global\\MDBw");
2115 while ((ptr = strchr(ptr, '\\')))
2117 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
2118 if (!env->me_wmutex) {
2123 pthread_mutexattr_t mattr;
2125 pthread_mutexattr_init(&mattr);
2126 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
2130 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
2131 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
2133 env->me_txns->mti_version = MDB_VERSION;
2134 env->me_txns->mti_magic = MDB_MAGIC;
2135 env->me_txns->mti_txnid = 0;
2136 env->me_txns->mti_numreaders = 0;
2137 env->me_txns->mti_me_toggle = 0;
2140 if (env->me_txns->mti_magic != MDB_MAGIC) {
2141 DPUTS("lock region has invalid magic");
2145 if (env->me_txns->mti_version != MDB_VERSION) {
2146 DPRINTF("lock region is version %u, expected version %u",
2147 env->me_txns->mti_version, MDB_VERSION);
2148 rc = MDB_VERSION_MISMATCH;
2152 if (rc != EACCES && rc != EAGAIN) {
2156 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
2157 if (!env->me_rmutex) {
2161 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
2162 if (!env->me_wmutex) {
2172 env->me_lfd = INVALID_HANDLE_VALUE;
2177 /** The name of the lock file in the DB environment */
2178 #define LOCKNAME "/lock.mdb"
2179 /** The name of the data file in the DB environment */
2180 #define DATANAME "/data.mdb"
2182 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
2184 int oflags, rc, len, excl;
2185 char *lpath, *dpath;
2188 lpath = malloc(len + sizeof(LOCKNAME) + len + sizeof(DATANAME));
2191 dpath = lpath + len + sizeof(LOCKNAME);
2192 sprintf(lpath, "%s" LOCKNAME, path);
2193 sprintf(dpath, "%s" DATANAME, path);
2195 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
2200 if (F_ISSET(flags, MDB_RDONLY)) {
2201 oflags = GENERIC_READ;
2202 len = OPEN_EXISTING;
2204 oflags = GENERIC_READ|GENERIC_WRITE;
2207 mode = FILE_ATTRIBUTE_NORMAL;
2208 if ((env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2209 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2214 if (F_ISSET(flags, MDB_RDONLY))
2217 oflags = O_RDWR | O_CREAT;
2219 if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
2225 if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
2226 /* synchronous fd for meta writes */
2228 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2229 mode |= FILE_FLAG_WRITE_THROUGH;
2230 if ((env->me_mfd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2231 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2236 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2237 oflags |= MDB_DSYNC;
2238 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
2243 env->me_path = strdup(path);
2244 DPRINTF("opened dbenv %p", (void *) env);
2245 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
2246 LAZY_RWLOCK_INIT(&env->me_dblock, NULL);
2248 mdb_env_share_locks(env);
2249 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
2250 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
2251 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
2257 if (env->me_fd != INVALID_HANDLE_VALUE) {
2259 env->me_fd = INVALID_HANDLE_VALUE;
2261 if (env->me_lfd != INVALID_HANDLE_VALUE) {
2263 env->me_lfd = INVALID_HANDLE_VALUE;
2271 mdb_env_close(MDB_env *env)
2278 while (env->me_dpages) {
2279 dp = env->me_dpages;
2280 env->me_dpages = dp->mp_next;
2284 free(env->me_dbs[1]);
2285 free(env->me_dbs[0]);
2289 LAZY_RWLOCK_DESTROY(&env->me_dblock);
2290 pthread_key_delete(env->me_txkey);
2293 munmap(env->me_map, env->me_mapsize);
2298 pid_t pid = getpid();
2300 for (i=0; i<env->me_txns->mti_numreaders; i++)
2301 if (env->me_txns->mti_readers[i].mr_pid == pid)
2302 env->me_txns->mti_readers[i].mr_pid = 0;
2303 munmap(env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
2309 /* only for aligned ints */
2311 intcmp(const MDB_val *a, const MDB_val *b)
2313 if (a->mv_size == sizeof(long))
2315 unsigned long *la, *lb;
2320 unsigned int *ia, *ib;
2327 /* ints must always be the same size */
2329 cintcmp(const MDB_val *a, const MDB_val *b)
2331 #if __BYTE_ORDER == __LITTLE_ENDIAN
2332 unsigned short *u, *c;
2335 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
2336 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
2339 } while(!x && u > (unsigned short *)a->mv_data);
2342 return memcmp(a->mv_data, b->mv_data, a->mv_size);
2347 memncmp(const MDB_val *a, const MDB_val *b)
2354 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
2360 diff = memcmp(a->mv_data, b->mv_data, len);
2361 return diff ? diff : len_diff<0 ? -1 : len_diff;
2365 memnrcmp(const MDB_val *a, const MDB_val *b)
2367 const unsigned char *p1, *p2, *p1_lim;
2371 p1_lim = (const unsigned char *)a->mv_data;
2372 p1 = (const unsigned char *)a->mv_data + a->mv_size;
2373 p2 = (const unsigned char *)b->mv_data + b->mv_size;
2375 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
2381 while (p1 > p1_lim) {
2382 diff = *--p1 - *--p2;
2386 return len_diff<0 ? -1 : len_diff;
2389 /* Search for key within a leaf page, using binary search.
2390 * Returns the smallest entry larger or equal to the key.
2391 * If exactp is non-null, stores whether the found entry was an exact match
2392 * in *exactp (1 or 0).
2393 * If kip is non-null, stores the index of the found entry in *kip.
2394 * If no entry larger or equal to the key is found, returns NULL.
2397 mdb_search_node(MDB_cursor *mc, MDB_val *key, int *exactp)
2399 unsigned int i = 0, nkeys;
2402 MDB_page *mp = mc->mc_pg[mc->mc_top];
2403 MDB_node *node = NULL;
2408 nkeys = NUMKEYS(mp);
2410 DPRINTF("searching %u keys in %s page %zu",
2411 nkeys, IS_LEAF(mp) ? "leaf" : "branch",
2416 low = IS_LEAF(mp) ? 0 : 1;
2418 cmp = mc->mc_txn->mt_dbxs[mc->mc_dbi].md_cmp;
2420 nodekey.mv_size = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
2421 node = NODEPTR(mp, 0); /* fake */
2423 while (low <= high) {
2424 i = (low + high) >> 1;
2427 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
2429 node = NODEPTR(mp, i);
2431 nodekey.mv_size = node->mn_ksize;
2432 nodekey.mv_data = NODEKEY(node);
2435 rc = cmp(key, &nodekey);
2439 DPRINTF("found leaf index %u [%s], rc = %i",
2440 i, DKEY(&nodekey), rc);
2442 DPRINTF("found branch index %u [%s -> %zu], rc = %i",
2443 i, DKEY(&nodekey), NODEPGNO(node), rc);
2454 if (rc > 0) { /* Found entry is less than the key. */
2455 i++; /* Skip to get the smallest entry larger than key. */
2457 node = NODEPTR(mp, i);
2460 *exactp = (rc == 0);
2461 /* store the key index */
2462 mc->mc_ki[mc->mc_top] = i;
2464 /* There is no entry larger or equal to the key. */
2467 /* nodeptr is fake for LEAF2 */
2472 cursor_pop_page(MDB_cursor *mc)
2477 top = mc->mc_pg[mc->mc_top];
2482 DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
2483 mc->mc_dbi, (void *) mc);
2488 cursor_push_page(MDB_cursor *mc, MDB_page *mp)
2490 DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
2491 mc->mc_dbi, (void *) mc);
2493 if (mc->mc_snum >= CURSOR_STACK)
2496 mc->mc_top = mc->mc_snum++;
2497 mc->mc_pg[mc->mc_top] = mp;
2498 mc->mc_ki[mc->mc_top] = 0;
2504 mdb_get_page(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
2508 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
2510 x = mdb_mid2l_search(txn->mt_u.dirty_list, pgno);
2511 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
2512 p = txn->mt_u.dirty_list[x].mptr;
2516 if (pgno <= txn->mt_env->me_metas[txn->mt_toggle]->mm_last_pg)
2517 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
2521 DPRINTF("page %zu not found", pgno);
2524 return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
2528 mdb_search_page_root(MDB_cursor *mc, MDB_val *key, int modify)
2530 MDB_page *mp = mc->mc_pg[mc->mc_top];
2535 while (IS_BRANCH(mp)) {
2538 DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
2539 assert(NUMKEYS(mp) > 1);
2540 DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
2542 if (key == NULL) /* Initialize cursor to first page. */
2543 mc->mc_ki[mc->mc_top] = 0;
2544 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
2545 /* cursor to last page */
2546 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
2549 node = mdb_search_node(mc, key, &exact);
2551 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
2553 assert(mc->mc_ki[mc->mc_top] > 0);
2554 mc->mc_ki[mc->mc_top]--;
2559 DPRINTF("following index %u for key [%s]",
2560 mc->mc_ki[mc->mc_top], DKEY(key));
2561 assert(mc->mc_ki[mc->mc_top] < NUMKEYS(mp));
2562 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
2564 if ((rc = mdb_get_page(mc->mc_txn, NODEPGNO(node), &mp)))
2567 if ((rc = cursor_push_page(mc, mp)))
2571 if ((rc = mdb_touch(mc)) != 0)
2573 mp = mc->mc_pg[mc->mc_top];
2578 DPRINTF("internal error, index points to a %02X page!?",
2580 return MDB_CORRUPTED;
2583 DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
2584 key ? DKEY(key) : NULL);
2589 /* Search for the page a given key should be in.
2590 * Pushes parent pages on the cursor stack.
2591 * If key is NULL, search for the lowest page (used by mdb_cursor_first).
2592 * If modify is true, visited pages are updated with new page numbers.
2595 mdb_search_page(MDB_cursor *mc, MDB_val *key, int modify)
2600 /* Make sure the txn is still viable, then find the root from
2601 * the txn's db table.
2603 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
2604 DPUTS("transaction has failed, must abort");
2607 root = mc->mc_txn->mt_dbs[mc->mc_dbi].md_root;
2609 if (root == P_INVALID) { /* Tree is empty. */
2610 DPUTS("tree is empty");
2611 return MDB_NOTFOUND;
2614 if ((rc = mdb_get_page(mc->mc_txn, root, &mc->mc_pg[0])))
2620 DPRINTF("db %u root page %zu has flags 0x%X",
2621 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
2624 /* For sub-databases, update main root first */
2625 if (mc->mc_dbi > MAIN_DBI && !mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty) {
2627 mc2.mc_txn = mc->mc_txn;
2628 mc2.mc_dbi = MAIN_DBI;
2629 rc = mdb_search_page(&mc2, &mc->mc_txn->mt_dbxs[mc->mc_dbi].md_name, 1);
2632 mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty = 1;
2634 if (!F_ISSET(mc->mc_pg[0]->mp_flags, P_DIRTY)) {
2635 if ((rc = mdb_touch(mc)))
2637 mc->mc_txn->mt_dbs[mc->mc_dbi].md_root = mc->mc_pg[0]->mp_pgno;
2641 return mdb_search_page_root(mc, key, modify);
2645 mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
2647 MDB_page *omp; /* overflow mpage */
2651 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
2652 data->mv_size = NODEDSZ(leaf);
2653 data->mv_data = NODEDATA(leaf);
2657 /* Read overflow data.
2659 data->mv_size = NODEDSZ(leaf);
2660 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
2661 if ((rc = mdb_get_page(txn, pgno, &omp))) {
2662 DPRINTF("read overflow page %zu failed", pgno);
2665 data->mv_data = METADATA(omp);
2671 mdb_get(MDB_txn *txn, MDB_dbi dbi,
2672 MDB_val *key, MDB_val *data)
2681 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
2683 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
2686 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2693 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
2694 mc.mc_xcursor = &mx;
2695 mdb_xcursor_init0(&mc);
2697 mc.mc_xcursor = NULL;
2699 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
2703 mdb_sibling(MDB_cursor *mc, int move_right)
2710 if (mc->mc_snum < 2) {
2711 return MDB_NOTFOUND; /* root has no siblings */
2713 ptop = mc->mc_top-1;
2715 DPRINTF("parent page is page %zu, index %u",
2716 mc->mc_pg[ptop]->mp_pgno, mc->mc_ki[ptop]);
2718 cursor_pop_page(mc);
2719 if (move_right ? (mc->mc_ki[ptop] + 1u >= NUMKEYS(mc->mc_pg[ptop]))
2720 : (mc->mc_ki[ptop] == 0)) {
2721 DPRINTF("no more keys left, moving to %s sibling",
2722 move_right ? "right" : "left");
2723 if ((rc = mdb_sibling(mc, move_right)) != MDB_SUCCESS)
2730 DPRINTF("just moving to %s index key %u",
2731 move_right ? "right" : "left", mc->mc_ki[ptop]);
2733 assert(IS_BRANCH(mc->mc_pg[ptop]));
2735 indx = NODEPTR(mc->mc_pg[ptop], mc->mc_ki[ptop]);
2736 if ((rc = mdb_get_page(mc->mc_txn, NODEPGNO(indx), &mp)))
2739 cursor_push_page(mc, mp);
2745 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
2751 if (mc->mc_flags & C_EOF) {
2752 return MDB_NOTFOUND;
2755 assert(mc->mc_flags & C_INITIALIZED);
2757 mp = mc->mc_pg[mc->mc_top];
2759 if (mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT) {
2760 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
2761 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2762 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
2763 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
2764 if (op != MDB_NEXT || rc == MDB_SUCCESS)
2768 mc->mc_xcursor->mx_cursor.mc_flags = 0;
2769 if (op == MDB_NEXT_DUP)
2770 return MDB_NOTFOUND;
2774 DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
2776 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
2777 DPUTS("=====> move to next sibling page");
2778 if (mdb_sibling(mc, 1) != MDB_SUCCESS) {
2779 mc->mc_flags |= C_EOF;
2780 return MDB_NOTFOUND;
2782 mp = mc->mc_pg[mc->mc_top];
2783 DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
2785 mc->mc_ki[mc->mc_top]++;
2787 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
2788 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
2791 key->mv_size = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
2792 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
2796 assert(IS_LEAF(mp));
2797 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
2799 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2800 mdb_xcursor_init1(mc, leaf);
2803 if ((rc = mdb_read_data(mc->mc_txn, leaf, data) != MDB_SUCCESS))
2806 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2807 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
2808 if (rc != MDB_SUCCESS)
2813 MDB_SET_KEY(leaf, key);
2818 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
2824 assert(mc->mc_flags & C_INITIALIZED);
2826 mp = mc->mc_pg[mc->mc_top];
2828 if (mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT) {
2829 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
2830 if (op == MDB_PREV || op == MDB_PREV_DUP) {
2831 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2832 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
2833 if (op != MDB_PREV || rc == MDB_SUCCESS)
2836 mc->mc_xcursor->mx_cursor.mc_flags = 0;
2837 if (op == MDB_PREV_DUP)
2838 return MDB_NOTFOUND;
2843 DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
2845 if (mc->mc_ki[mc->mc_top] == 0) {
2846 DPUTS("=====> move to prev sibling page");
2847 if (mdb_sibling(mc, 0) != MDB_SUCCESS) {
2848 mc->mc_flags &= ~C_INITIALIZED;
2849 return MDB_NOTFOUND;
2851 mp = mc->mc_pg[mc->mc_top];
2852 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
2853 DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
2855 mc->mc_ki[mc->mc_top]--;
2857 mc->mc_flags &= ~C_EOF;
2859 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
2860 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
2863 key->mv_size = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
2864 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
2868 assert(IS_LEAF(mp));
2869 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
2871 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2872 mdb_xcursor_init1(mc, leaf);
2875 if ((rc = mdb_read_data(mc->mc_txn, leaf, data) != MDB_SUCCESS))
2878 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2879 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
2880 if (rc != MDB_SUCCESS)
2885 MDB_SET_KEY(leaf, key);
2890 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
2891 MDB_cursor_op op, int *exactp)
2899 assert(key->mv_size > 0);
2901 /* See if we're already on the right page */
2902 if (mc->mc_flags & C_INITIALIZED) {
2905 if (mc->mc_pg[mc->mc_top]->mp_flags & P_LEAF2) {
2906 nodekey.mv_size = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
2907 nodekey.mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, nodekey.mv_size);
2909 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
2910 MDB_SET_KEY(leaf, &nodekey);
2912 rc = mc->mc_txn->mt_dbxs[mc->mc_dbi].md_cmp(key, &nodekey);
2914 /* Probably happens rarely, but first node on the page
2915 * was the one we wanted.
2917 mc->mc_ki[mc->mc_top] = 0;
2921 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
2926 if (NUMKEYS(mc->mc_pg[mc->mc_top]) > 1) {
2927 if (mc->mc_pg[mc->mc_top]->mp_flags & P_LEAF2) {
2928 nodekey.mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top],
2929 NUMKEYS(mc->mc_pg[mc->mc_top])-1, nodekey.mv_size);
2931 leaf = NODEPTR(mc->mc_pg[mc->mc_top], NUMKEYS(mc->mc_pg[mc->mc_top])-1);
2932 MDB_SET_KEY(leaf, &nodekey);
2934 rc = mc->mc_txn->mt_dbxs[mc->mc_dbi].md_cmp(key, &nodekey);
2936 /* last node was the one we wanted */
2937 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top])-1;
2941 /* This is definitely the right page, skip search_page */
2946 /* If any parents have right-sibs, search.
2947 * Otherwise, there's nothing further.
2949 for (i=0; i<mc->mc_top; i++)
2951 NUMKEYS(mc->mc_pg[i])-1)
2953 if (i == mc->mc_top) {
2954 /* There are no other pages */
2955 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
2956 return MDB_NOTFOUND;
2961 rc = mdb_search_page(mc, key, 0);
2962 if (rc != MDB_SUCCESS)
2965 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
2968 leaf = mdb_search_node(mc, key, exactp);
2969 if (exactp != NULL && !*exactp) {
2970 /* MDB_SET specified and not an exact match. */
2971 return MDB_NOTFOUND;
2975 DPUTS("===> inexact leaf not found, goto sibling");
2976 if ((rc = mdb_sibling(mc, 1)) != MDB_SUCCESS)
2977 return rc; /* no entries matched */
2978 mc->mc_ki[mc->mc_top] = 0;
2979 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
2980 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
2984 mc->mc_flags |= C_INITIALIZED;
2985 mc->mc_flags &= ~C_EOF;
2987 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
2988 key->mv_size = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
2989 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
2993 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2994 mdb_xcursor_init1(mc, leaf);
2997 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2998 if (op == MDB_SET || op == MDB_SET_RANGE) {
2999 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3002 if (op == MDB_GET_BOTH) {
3008 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
3009 if (rc != MDB_SUCCESS)
3012 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
3014 if ((rc = mdb_read_data(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
3016 rc = mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dcmp(data, &d2);
3018 if (op == MDB_GET_BOTH || rc > 0)
3019 return MDB_NOTFOUND;
3023 if ((rc = mdb_read_data(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3028 /* The key already matches in all other cases */
3029 if (op == MDB_SET_RANGE)
3030 MDB_SET_KEY(leaf, key);
3031 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
3037 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3042 rc = mdb_search_page(mc, NULL, 0);
3043 if (rc != MDB_SUCCESS)
3045 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3047 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
3048 mc->mc_flags |= C_INITIALIZED;
3049 mc->mc_flags &= ~C_EOF;
3051 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3052 key->mv_size = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
3053 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
3058 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3059 mdb_xcursor_init1(mc, leaf);
3060 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3065 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3066 if ((rc = mdb_read_data(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3070 MDB_SET_KEY(leaf, key);
3075 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3081 lkey.mv_size = MAXKEYSIZE+1;
3082 lkey.mv_data = NULL;
3084 rc = mdb_search_page(mc, &lkey, 0);
3085 if (rc != MDB_SUCCESS)
3087 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3089 leaf = NODEPTR(mc->mc_pg[mc->mc_top], NUMKEYS(mc->mc_pg[mc->mc_top])-1);
3090 mc->mc_flags |= C_INITIALIZED;
3091 mc->mc_flags &= ~C_EOF;
3093 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
3095 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3096 key->mv_size = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
3097 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
3102 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3103 mdb_xcursor_init1(mc, leaf);
3104 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3108 if ((rc = mdb_read_data(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3113 MDB_SET_KEY(leaf, key);
3118 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3128 case MDB_GET_BOTH_RANGE:
3129 if (data == NULL || mc->mc_xcursor == NULL) {
3136 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3138 } else if (op == MDB_SET_RANGE)
3139 rc = mdb_cursor_set(mc, key, data, op, NULL);
3141 rc = mdb_cursor_set(mc, key, data, op, &exact);
3143 case MDB_GET_MULTIPLE:
3145 !(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPFIXED) ||
3146 !(mc->mc_flags & C_INITIALIZED)) {
3151 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
3152 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
3155 case MDB_NEXT_MULTIPLE:
3157 !(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPFIXED)) {
3161 if (!(mc->mc_flags & C_INITIALIZED))
3162 rc = mdb_cursor_first(mc, key, data);
3164 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
3165 if (rc == MDB_SUCCESS) {
3166 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
3169 mx = &mc->mc_xcursor->mx_cursor;
3170 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
3171 mx->mc_txn->mt_dbs[mx->mc_dbi].md_pad;
3172 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
3173 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
3181 case MDB_NEXT_NODUP:
3182 if (!(mc->mc_flags & C_INITIALIZED))
3183 rc = mdb_cursor_first(mc, key, data);
3185 rc = mdb_cursor_next(mc, key, data, op);
3189 case MDB_PREV_NODUP:
3190 if (!(mc->mc_flags & C_INITIALIZED) || (mc->mc_flags & C_EOF))
3191 rc = mdb_cursor_last(mc, key, data);
3193 rc = mdb_cursor_prev(mc, key, data, op);
3196 rc = mdb_cursor_first(mc, key, data);
3200 !(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT) ||
3201 !(mc->mc_flags & C_INITIALIZED) ||
3202 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3206 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3209 rc = mdb_cursor_last(mc, key, data);
3213 !(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT) ||
3214 !(mc->mc_flags & C_INITIALIZED) ||
3215 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3219 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3222 DPRINTF("unhandled/unimplemented cursor operation %u", op);
3231 mdb_cursor_touch(MDB_cursor *mc)
3235 if (mc->mc_dbi > MAIN_DBI && !mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty) {
3237 mc2.mc_txn = mc->mc_txn;
3238 mc2.mc_dbi = MAIN_DBI;
3239 rc = mdb_search_page(&mc2, &mc->mc_txn->mt_dbxs[mc->mc_dbi].md_name, 1);
3241 mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty = 1;
3243 for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
3244 if (!F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY)) {
3248 mc->mc_txn->mt_dbs[mc->mc_dbi].md_root =
3249 mc->mc_pg[mc->mc_top]->mp_pgno;
3253 mc->mc_top = mc->mc_snum-1;
3258 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3262 MDB_val xdata, *rdata, dkey;
3264 char dbuf[PAGESIZE];
3270 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
3273 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
3274 mc->mc_dbi, DKEY(key), key->mv_size, data->mv_size);
3278 if (flags == MDB_CURRENT) {
3279 if (!(mc->mc_flags & C_INITIALIZED))
3282 } else if (mc->mc_txn->mt_dbs[mc->mc_dbi].md_root == P_INVALID) {
3284 /* new database, write a root leaf page */
3285 DPUTS("allocating new root leaf page");
3286 if ((np = mdb_new_page(mc, P_LEAF, 1)) == NULL) {
3290 cursor_push_page(mc, np);
3291 mc->mc_txn->mt_dbs[mc->mc_dbi].md_root = np->mp_pgno;
3292 mc->mc_txn->mt_dbs[mc->mc_dbi].md_depth++;
3293 mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty = 1;
3294 if ((mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
3296 np->mp_flags |= P_LEAF2;
3297 mc->mc_flags |= C_INITIALIZED;
3303 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
3304 if (flags == MDB_NOOVERWRITE && rc == 0) {
3305 DPRINTF("duplicate key [%s]", DKEY(key));
3307 return MDB_KEYEXIST;
3309 if (rc && rc != MDB_NOTFOUND)
3313 /* Cursor is positioned, now make sure all pages are writable */
3314 rc2 = mdb_cursor_touch(mc);
3315 if (rc2) return rc2;
3318 /* The key already exists */
3319 if (rc == MDB_SUCCESS) {
3320 /* there's only a key anyway, so this is a no-op */
3321 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3322 unsigned int ksize = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
3323 if (key->mv_size != ksize)
3325 if (flags == MDB_CURRENT) {
3326 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
3327 memcpy(ptr, key->mv_data, ksize);
3332 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3335 if (F_ISSET(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags, MDB_DUPSORT)) {
3336 /* Was a single item before, must convert now */
3337 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3338 dkey.mv_size = NODEDSZ(leaf);
3339 dkey.mv_data = dbuf;
3340 memcpy(dbuf, NODEDATA(leaf), dkey.mv_size);
3341 /* data matches, ignore it */
3342 if (!mdb_dcmp(mc->mc_txn, mc->mc_dbi, data, &dkey))
3343 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
3344 memset(&dummy, 0, sizeof(dummy));
3345 if (mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPFIXED) {
3346 dummy.md_pad = data->mv_size;
3347 dummy.md_flags = MDB_DUPFIXED;
3348 if (mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_INTEGERDUP)
3349 dummy.md_flags |= MDB_INTEGERKEY;
3351 dummy.md_root = P_INVALID;
3352 if (dkey.mv_size == sizeof(MDB_db)) {
3353 memcpy(NODEDATA(leaf), &dummy, sizeof(dummy));
3356 mdb_del_node(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
3359 xdata.mv_size = sizeof(MDB_db);
3360 xdata.mv_data = &dummy;
3361 /* new sub-DB, must fully init xcursor */
3362 if (flags == MDB_CURRENT)
3368 /* same size, just replace it */
3369 if (!F_ISSET(leaf->mn_flags, F_BIGDATA) &&
3370 NODEDSZ(leaf) == data->mv_size) {
3371 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
3374 mdb_del_node(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], 0);
3376 DPRINTF("inserting key at index %i", mc->mc_ki[mc->mc_top]);
3382 nsize = IS_LEAF2(mc->mc_pg[mc->mc_top]) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
3383 if (SIZELEFT(mc->mc_pg[mc->mc_top]) < nsize) {
3384 rc = mdb_split(mc, key, rdata, P_INVALID);
3386 /* There is room already in this leaf page. */
3387 rc = mdb_add_node(mc, mc->mc_ki[mc->mc_top], key, rdata, 0, 0);
3390 if (rc != MDB_SUCCESS)
3391 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
3393 /* Remember if we just added a subdatabase */
3394 if (flags & F_SUBDATA) {
3395 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3396 leaf->mn_flags |= F_SUBDATA;
3399 /* Now store the actual data in the child DB. Note that we're
3400 * storing the user data in the keys field, so there are strict
3401 * size limits on dupdata. The actual data fields of the child
3402 * DB are all zero size.
3405 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3407 if (flags == MDB_CURRENT)
3408 mdb_xcursor_init2(mc);
3410 mdb_xcursor_init1(mc, leaf);
3413 if (flags == MDB_NODUPDATA)
3414 flags = MDB_NOOVERWRITE;
3415 /* converted, write the original data first */
3417 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, flags);
3419 leaf->mn_flags |= F_DUPDATA;
3421 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, flags);
3422 mdb_xcursor_fini(mc);
3423 memcpy(NODEDATA(leaf),
3424 &mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi],
3427 mc->mc_txn->mt_dbs[mc->mc_dbi].md_entries++;
3434 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
3439 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
3442 if (!mc->mc_flags & C_INITIALIZED)
3445 rc = mdb_cursor_touch(mc);
3448 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3450 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3451 if (flags != MDB_NODUPDATA) {
3452 mdb_xcursor_init2(mc);
3453 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
3454 mdb_xcursor_fini(mc);
3455 /* If sub-DB still has entries, we're done */
3456 if (mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_root
3458 memcpy(NODEDATA(leaf),
3459 &mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi],
3461 mc->mc_txn->mt_dbs[mc->mc_dbi].md_entries--;
3464 /* otherwise fall thru and delete the sub-DB */
3467 /* add all the child DB's pages to the free list */
3468 rc = mdb_search_page(&mc->mc_xcursor->mx_cursor, NULL, 0);
3469 if (rc == MDB_SUCCESS) {
3474 mx = &mc->mc_xcursor->mx_cursor;
3475 mc->mc_txn->mt_dbs[mc->mc_dbi].md_entries -=
3476 mx->mc_txn->mt_dbs[mx->mc_dbi].md_entries;
3478 cursor_pop_page(mx);
3480 while (mx->mc_snum > 1) {
3481 for (i=0; i<NUMKEYS(mx->mc_pg[mx->mc_top]); i++) {
3483 ni = NODEPTR(mx->mc_pg[mx->mc_top], i);
3486 mdb_midl_append(mc->mc_txn->mt_free_pgs, pg);
3488 rc = mdb_sibling(mx, 1);
3493 mdb_midl_append(mc->mc_txn->mt_free_pgs,
3494 mx->mc_txn->mt_dbs[mx->mc_dbi].md_root);
3498 return mdb_del0(mc, leaf);
3501 /* Allocate a page and initialize it
3504 mdb_new_page(MDB_cursor *mc, uint32_t flags, int num)
3508 if ((np = mdb_alloc_page(mc, num)) == NULL)
3510 DPRINTF("allocated new mpage %zu, page size %u",
3511 np->mp_pgno, mc->mc_txn->mt_env->me_psize);
3512 np->mp_flags = flags | P_DIRTY;
3513 np->mp_lower = PAGEHDRSZ;
3514 np->mp_upper = mc->mc_txn->mt_env->me_psize;
3517 mc->mc_txn->mt_dbs[mc->mc_dbi].md_branch_pages++;
3518 else if (IS_LEAF(np))
3519 mc->mc_txn->mt_dbs[mc->mc_dbi].md_leaf_pages++;
3520 else if (IS_OVERFLOW(np)) {
3521 mc->mc_txn->mt_dbs[mc->mc_dbi].md_overflow_pages += num;
3529 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
3533 sz = LEAFSIZE(key, data);
3534 if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
3535 /* put on overflow page */
3536 sz -= data->mv_size - sizeof(pgno_t);
3540 return sz + sizeof(indx_t);
3544 mdb_branch_size(MDB_env *env, MDB_val *key)
3549 if (sz >= env->me_psize / MDB_MINKEYS) {
3550 /* put on overflow page */
3551 /* not implemented */
3552 /* sz -= key->size - sizeof(pgno_t); */
3555 return sz + sizeof(indx_t);
3559 mdb_add_node(MDB_cursor *mc, indx_t indx,
3560 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags)
3563 size_t node_size = NODESIZE;
3566 MDB_page *mp = mc->mc_pg[mc->mc_top];
3567 MDB_page *ofp = NULL; /* overflow page */
3570 assert(mp->mp_upper >= mp->mp_lower);
3572 DPRINTF("add to %s page %zu index %i, data size %zu key size %zu [%s]",
3573 IS_LEAF(mp) ? "leaf" : "branch",
3574 mp->mp_pgno, indx, data ? data->mv_size : 0,
3575 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
3578 /* Move higher keys up one slot. */
3579 int ksize = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad, dif;
3580 char *ptr = LEAF2KEY(mp, indx, ksize);
3581 dif = NUMKEYS(mp) - indx;
3583 memmove(ptr+ksize, ptr, dif*ksize);
3584 /* insert new key */
3585 memcpy(ptr, key->mv_data, ksize);
3587 /* Just using these for counting */
3588 mp->mp_lower += sizeof(indx_t);
3589 mp->mp_upper -= ksize - sizeof(indx_t);
3594 node_size += key->mv_size;
3598 if (F_ISSET(flags, F_BIGDATA)) {
3599 /* Data already on overflow page. */
3600 node_size += sizeof(pgno_t);
3601 } else if (data->mv_size >= mc->mc_txn->mt_env->me_psize / MDB_MINKEYS) {
3602 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
3603 /* Put data on overflow page. */
3604 DPRINTF("data size is %zu, put on overflow page",
3606 node_size += sizeof(pgno_t);
3607 if ((ofp = mdb_new_page(mc, P_OVERFLOW, ovpages)) == NULL)
3609 DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
3612 node_size += data->mv_size;
3615 node_size += node_size & 1;
3617 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
3618 DPRINTF("not enough room in page %zu, got %u ptrs",
3619 mp->mp_pgno, NUMKEYS(mp));
3620 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
3621 mp->mp_upper - mp->mp_lower);
3622 DPRINTF("node size = %zu", node_size);
3626 /* Move higher pointers up one slot. */
3627 for (i = NUMKEYS(mp); i > indx; i--)
3628 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
3630 /* Adjust free space offsets. */
3631 ofs = mp->mp_upper - node_size;
3632 assert(ofs >= mp->mp_lower + sizeof(indx_t));
3633 mp->mp_ptrs[indx] = ofs;
3635 mp->mp_lower += sizeof(indx_t);
3637 /* Write the node data. */
3638 node = NODEPTR(mp, indx);
3639 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
3640 node->mn_flags = flags;
3642 SETDSZ(node,data->mv_size);
3647 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
3652 if (F_ISSET(flags, F_BIGDATA))
3653 memcpy(node->mn_data + key->mv_size, data->mv_data,
3656 memcpy(node->mn_data + key->mv_size, data->mv_data,
3659 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
3661 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
3669 mdb_del_node(MDB_page *mp, indx_t indx, int ksize)
3672 indx_t i, j, numkeys, ptr;
3676 DPRINTF("delete node %u on %s page %zu", indx,
3677 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
3678 assert(indx < NUMKEYS(mp));
3681 int x = NUMKEYS(mp) - 1 - indx;
3682 base = LEAF2KEY(mp, indx, ksize);
3684 memmove(base, base + ksize, x * ksize);
3685 mp->mp_lower -= sizeof(indx_t);
3686 mp->mp_upper += ksize - sizeof(indx_t);
3690 node = NODEPTR(mp, indx);
3691 sz = NODESIZE + node->mn_ksize;
3693 if (F_ISSET(node->mn_flags, F_BIGDATA))
3694 sz += sizeof(pgno_t);
3696 sz += NODEDSZ(node);
3700 ptr = mp->mp_ptrs[indx];
3701 numkeys = NUMKEYS(mp);
3702 for (i = j = 0; i < numkeys; i++) {
3704 mp->mp_ptrs[j] = mp->mp_ptrs[i];
3705 if (mp->mp_ptrs[i] < ptr)
3706 mp->mp_ptrs[j] += sz;
3711 base = (char *)mp + mp->mp_upper;
3712 memmove(base + sz, base, ptr - mp->mp_upper);
3714 mp->mp_lower -= sizeof(indx_t);
3719 mdb_xcursor_init0(MDB_cursor *mc)
3721 MDB_xcursor *mx = mc->mc_xcursor;
3724 mx->mx_txn = *mc->mc_txn;
3725 mx->mx_txn.mt_dbxs = mx->mx_dbxs;
3726 mx->mx_txn.mt_dbs = mx->mx_dbs;
3727 mx->mx_dbxs[0] = mc->mc_txn->mt_dbxs[0];
3728 mx->mx_dbxs[1] = mc->mc_txn->mt_dbxs[1];
3729 if (mc->mc_dbi > 1) {
3730 mx->mx_dbxs[2] = mc->mc_txn->mt_dbxs[mc->mc_dbi];
3735 mx->mx_dbxs[dbn+1].md_parent = dbn;
3736 mx->mx_dbxs[dbn+1].md_cmp = mx->mx_dbxs[dbn].md_dcmp;
3737 mx->mx_dbxs[dbn+1].md_rel = mx->mx_dbxs[dbn].md_rel;
3738 mx->mx_dbxs[dbn+1].md_dirty = 0;
3739 mx->mx_txn.mt_numdbs = dbn+2;
3740 mx->mx_txn.mt_u = mc->mc_txn->mt_u;
3742 mx->mx_cursor.mc_xcursor = NULL;
3743 mx->mx_cursor.mc_txn = &mx->mx_txn;
3744 mx->mx_cursor.mc_dbi = dbn+1;
3748 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
3750 MDB_db *db = NODEDATA(node);
3751 MDB_xcursor *mx = mc->mc_xcursor;
3753 mx->mx_dbs[0] = mc->mc_txn->mt_dbs[0];
3754 mx->mx_dbs[1] = mc->mc_txn->mt_dbs[1];
3755 if (mc->mc_dbi > 1) {
3756 mx->mx_dbs[2] = mc->mc_txn->mt_dbs[mc->mc_dbi];
3757 mx->mx_dbxs[2].md_dirty = mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty;
3762 DPRINTF("Sub-db %u for db %u root page %zu", dbn, mc->mc_dbi, db->md_root);
3763 mx->mx_dbs[dbn] = *db;
3764 if (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY))
3765 mx->mx_dbxs[dbn].md_dirty = 1;
3766 mx->mx_dbxs[dbn].md_name.mv_data = NODEKEY(node);
3767 mx->mx_dbxs[dbn].md_name.mv_size = node->mn_ksize;
3768 mx->mx_txn.mt_next_pgno = mc->mc_txn->mt_next_pgno;
3769 mx->mx_cursor.mc_snum = 0;
3770 mx->mx_cursor.mc_flags = 0;
3774 mdb_xcursor_init2(MDB_cursor *mc)
3776 MDB_xcursor *mx = mc->mc_xcursor;
3778 mx->mx_dbs[0] = mc->mc_txn->mt_dbs[0];
3779 mx->mx_dbs[1] = mc->mc_txn->mt_dbs[1];
3780 if (mc->mc_dbi > 1) {
3781 mx->mx_dbs[2] = mc->mc_txn->mt_dbs[mc->mc_dbi];
3782 mx->mx_dbxs[2].md_dirty = mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty;
3787 DPRINTF("Sub-db %u for db %u root page %zu", dbn, mc->mc_dbi,
3788 mx->mx_dbs[dbn].md_root);
3789 mx->mx_txn.mt_next_pgno = mc->mc_txn->mt_next_pgno;
3793 mdb_xcursor_fini(MDB_cursor *mc)
3795 MDB_xcursor *mx = mc->mc_xcursor;
3796 mc->mc_txn->mt_next_pgno = mx->mx_txn.mt_next_pgno;
3797 mc->mc_txn->mt_dbs[0] = mx->mx_dbs[0];
3798 mc->mc_txn->mt_dbs[1] = mx->mx_dbs[1];
3799 if (mc->mc_dbi > 1) {
3800 mc->mc_txn->mt_dbs[mc->mc_dbi] = mx->mx_dbs[2];
3801 mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty = mx->mx_dbxs[2].md_dirty;
3806 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
3809 size_t size = sizeof(MDB_cursor);
3811 if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
3814 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
3815 size += sizeof(MDB_xcursor);
3817 if ((mc = calloc(1, size)) != NULL) {
3820 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
3821 MDB_xcursor *mx = (MDB_xcursor *)(mc + 1);
3822 mc->mc_xcursor = mx;
3823 mdb_xcursor_init0(mc);
3834 /* Return the count of duplicate data items for the current key */
3836 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
3840 if (mc == NULL || countp == NULL)
3843 if (!(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT))
3846 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3847 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3850 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
3853 *countp = mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_entries;
3859 mdb_cursor_close(MDB_cursor *mc)
3867 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
3869 indx_t ptr, i, numkeys;
3876 node = NODEPTR(mp, indx);
3877 ptr = mp->mp_ptrs[indx];
3878 DPRINTF("update key %u (ofs %u) [%.*s] to [%s] on page %zu",
3880 (int)node->mn_ksize, (char *)NODEKEY(node),
3884 delta = key->mv_size - node->mn_ksize;
3886 if (delta > 0 && SIZELEFT(mp) < delta) {
3887 DPRINTF("OUCH! Not enough room, delta = %d", delta);
3891 numkeys = NUMKEYS(mp);
3892 for (i = 0; i < numkeys; i++) {
3893 if (mp->mp_ptrs[i] <= ptr)
3894 mp->mp_ptrs[i] -= delta;
3897 base = (char *)mp + mp->mp_upper;
3898 len = ptr - mp->mp_upper + NODESIZE;
3899 memmove(base - delta, base, len);
3900 mp->mp_upper -= delta;
3902 node = NODEPTR(mp, indx);
3903 node->mn_ksize = key->mv_size;
3906 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
3911 /* Move a node from csrc to cdst.
3914 mdb_move_node(MDB_cursor *csrc, MDB_cursor *cdst)
3921 /* Mark src and dst as dirty. */
3922 if ((rc = mdb_touch(csrc)) ||
3923 (rc = mdb_touch(cdst)))
3926 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
3927 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
3928 key.mv_size = csrc->mc_txn->mt_dbs[csrc->mc_dbi].md_pad;
3929 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
3931 data.mv_data = NULL;
3933 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
3934 unsigned int snum = csrc->mc_snum;
3935 /* must find the lowest key below src */
3936 mdb_search_page_root(csrc, NULL, 0);
3937 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
3938 csrc->mc_snum = snum--;
3939 csrc->mc_top = snum;
3941 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
3943 key.mv_size = NODEKSZ(srcnode);
3944 key.mv_data = NODEKEY(srcnode);
3945 data.mv_size = NODEDSZ(srcnode);
3946 data.mv_data = NODEDATA(srcnode);
3948 DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
3949 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
3950 csrc->mc_ki[csrc->mc_top],
3952 csrc->mc_pg[csrc->mc_top]->mp_pgno,
3953 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
3955 /* Add the node to the destination page.
3957 rc = mdb_add_node(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, NODEPGNO(srcnode),
3959 if (rc != MDB_SUCCESS)
3962 /* Delete the node from the source page.
3964 mdb_del_node(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
3966 /* Update the parent separators.
3968 if (csrc->mc_ki[csrc->mc_top] == 0) {
3969 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
3970 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
3971 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
3973 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
3974 key.mv_size = NODEKSZ(srcnode);
3975 key.mv_data = NODEKEY(srcnode);
3977 DPRINTF("update separator for source page %zu to [%s]",
3978 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
3979 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1],
3980 &key)) != MDB_SUCCESS)
3983 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
3985 nullkey.mv_size = 0;
3986 assert(mdb_update_key(csrc->mc_pg[csrc->mc_top], 0, &nullkey) == MDB_SUCCESS);
3990 if (cdst->mc_ki[cdst->mc_top] == 0) {
3991 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
3992 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
3993 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
3995 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
3996 key.mv_size = NODEKSZ(srcnode);
3997 key.mv_data = NODEKEY(srcnode);
3999 DPRINTF("update separator for destination page %zu to [%s]",
4000 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
4001 if ((rc = mdb_update_key(cdst->mc_pg[cdst->mc_top-1], cdst->mc_ki[cdst->mc_top-1],
4002 &key)) != MDB_SUCCESS)
4005 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
4007 nullkey.mv_size = 0;
4008 assert(mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &nullkey) == MDB_SUCCESS);
4016 mdb_merge(MDB_cursor *csrc, MDB_cursor *cdst)
4023 DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
4024 cdst->mc_pg[cdst->mc_top]->mp_pgno);
4026 assert(csrc->mc_snum > 1); /* can't merge root page */
4027 assert(cdst->mc_snum > 1);
4029 /* Mark dst as dirty. */
4030 if ((rc = mdb_touch(cdst)))
4033 /* Move all nodes from src to dst.
4035 j = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
4036 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4037 key.mv_size = csrc->mc_txn->mt_dbs[csrc->mc_dbi].md_pad;
4038 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
4039 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
4040 rc = mdb_add_node(cdst, j, &key, NULL, 0, 0);
4041 if (rc != MDB_SUCCESS)
4043 key.mv_data = (char *)key.mv_data + key.mv_size;
4046 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
4047 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
4049 key.mv_size = srcnode->mn_ksize;
4050 key.mv_data = NODEKEY(srcnode);
4051 data.mv_size = NODEDSZ(srcnode);
4052 data.mv_data = NODEDATA(srcnode);
4053 rc = mdb_add_node(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
4054 if (rc != MDB_SUCCESS)
4059 DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
4060 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);
4062 /* Unlink the src page from parent and add to free list.
4064 mdb_del_node(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
4065 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
4067 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], 0, &key)) != MDB_SUCCESS)
4071 mdb_midl_append(csrc->mc_txn->mt_free_pgs, csrc->mc_pg[csrc->mc_top]->mp_pgno);
4072 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
4073 csrc->mc_txn->mt_dbs[csrc->mc_dbi].md_leaf_pages--;
4075 csrc->mc_txn->mt_dbs[csrc->mc_dbi].md_branch_pages--;
4076 cursor_pop_page(csrc);
4078 return mdb_rebalance(csrc);
4082 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
4086 cdst->mc_txn = csrc->mc_txn;
4087 cdst->mc_dbi = csrc->mc_dbi;
4088 cdst->mc_snum = csrc->mc_snum;
4089 cdst->mc_top = csrc->mc_top;
4090 cdst->mc_flags = csrc->mc_flags;
4092 for (i=0; i<csrc->mc_snum; i++) {
4093 cdst->mc_pg[i] = csrc->mc_pg[i];
4094 cdst->mc_ki[i] = csrc->mc_ki[i];
4099 mdb_rebalance(MDB_cursor *mc)
4107 DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
4108 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
4109 mc->mc_pg[mc->mc_top]->mp_pgno, NUMKEYS(mc->mc_pg[mc->mc_top]), (float)PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) / 10);
4111 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD) {
4112 DPRINTF("no need to rebalance page %zu, above fill threshold",
4113 mc->mc_pg[mc->mc_top]->mp_pgno);
4117 if (mc->mc_snum < 2) {
4118 if (NUMKEYS(mc->mc_pg[mc->mc_top]) == 0) {
4119 DPUTS("tree is completely empty");
4120 mc->mc_txn->mt_dbs[mc->mc_dbi].md_root = P_INVALID;
4121 mc->mc_txn->mt_dbs[mc->mc_dbi].md_depth = 0;
4122 mc->mc_txn->mt_dbs[mc->mc_dbi].md_leaf_pages = 0;
4123 mdb_midl_append(mc->mc_txn->mt_free_pgs, mc->mc_pg[mc->mc_top]->mp_pgno);
4124 } else if (IS_BRANCH(mc->mc_pg[mc->mc_top]) && NUMKEYS(mc->mc_pg[mc->mc_top]) == 1) {
4125 DPUTS("collapsing root page!");
4126 mdb_midl_append(mc->mc_txn->mt_free_pgs, mc->mc_pg[mc->mc_top]->mp_pgno);
4127 mc->mc_txn->mt_dbs[mc->mc_dbi].md_root = NODEPGNO(NODEPTR(mc->mc_pg[mc->mc_top], 0));
4128 if ((rc = mdb_get_page(mc->mc_txn, mc->mc_txn->mt_dbs[mc->mc_dbi].md_root, &root)))
4130 mc->mc_txn->mt_dbs[mc->mc_dbi].md_depth--;
4131 mc->mc_txn->mt_dbs[mc->mc_dbi].md_branch_pages--;
4133 DPUTS("root page doesn't need rebalancing");
4137 /* The parent (branch page) must have at least 2 pointers,
4138 * otherwise the tree is invalid.
4140 ptop = mc->mc_top-1;
4141 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
4143 /* Leaf page fill factor is below the threshold.
4144 * Try to move keys from left or right neighbor, or
4145 * merge with a neighbor page.
4150 mdb_cursor_copy(mc, &mn);
4151 mn.mc_xcursor = NULL;
4153 if (mc->mc_ki[ptop] == 0) {
4154 /* We're the leftmost leaf in our parent.
4156 DPUTS("reading right neighbor");
4158 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
4159 if ((rc = mdb_get_page(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
4161 mn.mc_ki[mn.mc_top] = 0;
4162 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
4164 /* There is at least one neighbor to the left.
4166 DPUTS("reading left neighbor");
4168 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
4169 if ((rc = mdb_get_page(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
4171 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
4172 mc->mc_ki[mc->mc_top] = 0;
4175 DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
4176 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);
4178 /* If the neighbor page is above threshold and has at least two
4179 * keys, move one key from it.
4181 * Otherwise we should try to merge them.
4183 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) >= 2)
4184 return mdb_move_node(&mn, mc);
4185 else { /* FIXME: if (has_enough_room()) */
4186 if (mc->mc_ki[ptop] == 0)
4187 return mdb_merge(&mn, mc);
4189 return mdb_merge(mc, &mn);
4194 mdb_del0(MDB_cursor *mc, MDB_node *leaf)
4198 /* add overflow pages to free list */
4199 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
4203 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
4204 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
4205 for (i=0; i<ovpages; i++) {
4206 DPRINTF("freed ov page %zu", pg);
4207 mdb_midl_append(mc->mc_txn->mt_free_pgs, pg);
4211 mdb_del_node(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad);
4212 mc->mc_txn->mt_dbs[mc->mc_dbi].md_entries--;
4213 rc = mdb_rebalance(mc);
4214 if (rc != MDB_SUCCESS)
4215 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4221 mdb_del(MDB_txn *txn, MDB_dbi dbi,
4222 MDB_val *key, MDB_val *data)
4227 MDB_val rdata, *xdata;
4231 assert(key != NULL);
4233 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
4235 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4238 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
4242 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
4249 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4250 mc.mc_xcursor = &mx;
4251 mdb_xcursor_init0(&mc);
4253 mc.mc_xcursor = NULL;
4265 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
4267 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
4271 /* Split page <mc->top>, and insert <key,(data|newpgno)> in either left or
4272 * right sibling, at index <mc->ki> (as if unsplit). Updates mc->top and
4273 * mc->ki with the actual values after split, ie if mc->top and mc->ki
4274 * refer to a node in the new right sibling page.
4277 mdb_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno)
4280 int rc = MDB_SUCCESS, ins_new = 0;
4283 unsigned int i, j, split_indx, nkeys, pmax;
4285 MDB_val sepkey, rkey, rdata;
4287 MDB_page *mp, *rp, *pp;
4292 mp = mc->mc_pg[mc->mc_top];
4293 newindx = mc->mc_ki[mc->mc_top];
4295 DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
4296 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
4297 DKEY(newkey), mc->mc_ki[mc->mc_top]);
4299 if (mc->mc_snum < 2) {
4300 if ((pp = mdb_new_page(mc, P_BRANCH, 1)) == NULL)
4302 /* shift current top to make room for new parent */
4303 mc->mc_pg[1] = mc->mc_pg[0];
4304 mc->mc_ki[1] = mc->mc_ki[0];
4307 mc->mc_txn->mt_dbs[mc->mc_dbi].md_root = pp->mp_pgno;
4308 DPRINTF("root split! new root = %zu", pp->mp_pgno);
4309 mc->mc_txn->mt_dbs[mc->mc_dbi].md_depth++;
4311 /* Add left (implicit) pointer. */
4312 if ((rc = mdb_add_node(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
4313 /* undo the pre-push */
4314 mc->mc_pg[0] = mc->mc_pg[1];
4315 mc->mc_ki[0] = mc->mc_ki[1];
4316 mc->mc_txn->mt_dbs[mc->mc_dbi].md_root = mp->mp_pgno;
4317 mc->mc_txn->mt_dbs[mc->mc_dbi].md_depth--;
4324 ptop = mc->mc_top-1;
4325 DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
4328 /* Create a right sibling. */
4329 if ((rp = mdb_new_page(mc, mp->mp_flags, 1)) == NULL)
4331 mdb_cursor_copy(mc, &mn);
4332 mn.mc_pg[mn.mc_top] = rp;
4333 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
4334 DPRINTF("new right sibling: page %zu", rp->mp_pgno);
4336 nkeys = NUMKEYS(mp);
4337 split_indx = nkeys / 2 + 1;
4342 unsigned int lsize, rsize, ksize;
4343 /* Move half of the keys to the right sibling */
4345 x = mc->mc_ki[mc->mc_top] - split_indx;
4346 ksize = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
4347 split = LEAF2KEY(mp, split_indx, ksize);
4348 rsize = (nkeys - split_indx) * ksize;
4349 lsize = (nkeys - split_indx) * sizeof(indx_t);
4350 mp->mp_lower -= lsize;
4351 rp->mp_lower += lsize;
4352 mp->mp_upper += rsize - lsize;
4353 rp->mp_upper -= rsize - lsize;
4354 sepkey.mv_size = ksize;
4355 if (newindx == split_indx) {
4356 sepkey.mv_data = newkey->mv_data;
4358 sepkey.mv_data = split;
4361 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
4362 memcpy(rp->mp_ptrs, split, rsize);
4363 sepkey.mv_data = rp->mp_ptrs;
4364 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
4365 memcpy(ins, newkey->mv_data, ksize);
4366 mp->mp_lower += sizeof(indx_t);
4367 mp->mp_upper -= ksize - sizeof(indx_t);
4370 memcpy(rp->mp_ptrs, split, x * ksize);
4371 ins = LEAF2KEY(rp, x, ksize);
4372 memcpy(ins, newkey->mv_data, ksize);
4373 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
4374 rp->mp_lower += sizeof(indx_t);
4375 rp->mp_upper -= ksize - sizeof(indx_t);
4376 mc->mc_ki[mc->mc_top] = x;
4377 mc->mc_pg[mc->mc_top] = rp;
4382 /* For leaf pages, check the split point based on what
4383 * fits where, since otherwise add_node can fail.
4386 unsigned int psize, nsize;
4387 /* Maximum free space in an empty page */
4388 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
4389 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
4390 if (newindx < split_indx) {
4392 for (i=0; i<split_indx; i++) {
4393 node = NODEPTR(mp, i);
4394 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
4395 if (F_ISSET(node->mn_flags, F_BIGDATA))
4396 psize += sizeof(pgno_t);
4398 psize += NODEDSZ(node);
4407 for (i=nkeys-1; i>=split_indx; i--) {
4408 node = NODEPTR(mp, i);
4409 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
4410 if (F_ISSET(node->mn_flags, F_BIGDATA))
4411 psize += sizeof(pgno_t);
4413 psize += NODEDSZ(node);
4423 /* First find the separating key between the split pages.
4425 if (newindx == split_indx) {
4426 sepkey.mv_size = newkey->mv_size;
4427 sepkey.mv_data = newkey->mv_data;
4429 node = NODEPTR(mp, split_indx);
4430 sepkey.mv_size = node->mn_ksize;
4431 sepkey.mv_data = NODEKEY(node);
4435 DPRINTF("separator is [%s]", DKEY(&sepkey));
4437 /* Copy separator key to the parent.
4439 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
4442 rc = mdb_split(&mn, &sepkey, NULL, rp->mp_pgno);
4444 /* Right page might now have changed parent.
4445 * Check if left page also changed parent.
4447 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
4448 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
4449 mc->mc_pg[ptop] = mn.mc_pg[ptop];
4450 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
4454 rc = mdb_add_node(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
4460 if (rc != MDB_SUCCESS) {
4464 /* Move half of the keys to the right sibling. */
4466 /* grab a page to hold a temporary copy */
4467 if (mc->mc_txn->mt_env->me_dpages) {
4468 copy = mc->mc_txn->mt_env->me_dpages;
4469 mc->mc_txn->mt_env->me_dpages = copy->mp_next;
4471 if ((copy = malloc(mc->mc_txn->mt_env->me_psize)) == NULL)
4475 copy->mp_pgno = mp->mp_pgno;
4476 copy->mp_flags = mp->mp_flags;
4477 copy->mp_lower = PAGEHDRSZ;
4478 copy->mp_upper = mc->mc_txn->mt_env->me_psize;
4479 mc->mc_pg[mc->mc_top] = copy;
4480 for (i = j = 0; i <= nkeys; j++) {
4481 if (i == split_indx) {
4482 /* Insert in right sibling. */
4483 /* Reset insert index for right sibling. */
4484 j = (i == newindx && ins_new);
4485 mc->mc_pg[mc->mc_top] = rp;
4488 if (i == newindx && !ins_new) {
4489 /* Insert the original entry that caused the split. */
4490 rkey.mv_data = newkey->mv_data;
4491 rkey.mv_size = newkey->mv_size;
4493 rdata.mv_data = newdata->mv_data;
4494 rdata.mv_size = newdata->mv_size;
4501 /* Update page and index for the new key. */
4502 mc->mc_ki[mc->mc_top] = j;
4503 } else if (i == nkeys) {
4506 node = NODEPTR(mp, i);
4507 rkey.mv_data = NODEKEY(node);
4508 rkey.mv_size = node->mn_ksize;
4510 rdata.mv_data = NODEDATA(node);
4511 rdata.mv_size = NODEDSZ(node);
4513 pgno = NODEPGNO(node);
4514 flags = node->mn_flags;
4519 if (!IS_LEAF(mp) && j == 0) {
4520 /* First branch index doesn't need key data. */
4524 rc = mdb_add_node(mc, j, &rkey, &rdata, pgno, flags);
4527 /* reset back to original page */
4528 if (newindx < split_indx)
4529 mc->mc_pg[mc->mc_top] = mp;
4531 nkeys = NUMKEYS(copy);
4532 for (i=0; i<nkeys; i++)
4533 mp->mp_ptrs[i] = copy->mp_ptrs[i];
4534 mp->mp_lower = copy->mp_lower;
4535 mp->mp_upper = copy->mp_upper;
4536 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
4537 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
4539 /* return tmp page to freelist */
4540 copy->mp_next = mc->mc_txn->mt_env->me_dpages;
4541 mc->mc_txn->mt_env->me_dpages = copy;
4546 mdb_put(MDB_txn *txn, MDB_dbi dbi,
4547 MDB_val *key, MDB_val *data, unsigned int flags)
4552 assert(key != NULL);
4553 assert(data != NULL);
4555 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4558 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
4562 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
4566 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA)) != flags)
4573 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4574 mc.mc_xcursor = &mx;
4575 mdb_xcursor_init0(&mc);
4577 mc.mc_xcursor = NULL;
4579 return mdb_cursor_put(&mc, key, data, flags);
4583 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
4585 /** Only a subset of the @ref mdb_env flags can be changed
4586 * at runtime. Changing other flags requires closing the environment
4587 * and re-opening it with the new flags.
4589 #define CHANGEABLE (MDB_NOSYNC)
4590 if ((flag & CHANGEABLE) != flag)
4593 env->me_flags |= flag;
4595 env->me_flags &= ~flag;
4600 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
4605 *arg = env->me_flags;
4610 mdb_env_get_path(MDB_env *env, const char **arg)
4615 *arg = env->me_path;
4620 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
4622 arg->ms_psize = env->me_psize;
4623 arg->ms_depth = db->md_depth;
4624 arg->ms_branch_pages = db->md_branch_pages;
4625 arg->ms_leaf_pages = db->md_leaf_pages;
4626 arg->ms_overflow_pages = db->md_overflow_pages;
4627 arg->ms_entries = db->md_entries;
4632 mdb_env_stat(MDB_env *env, MDB_stat *arg)
4636 if (env == NULL || arg == NULL)
4639 mdb_env_read_meta(env, &toggle);
4641 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
4645 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
4647 if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEKEY)
4648 txn->mt_dbxs[dbi].md_cmp = memnrcmp;
4649 else if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERKEY)
4650 txn->mt_dbxs[dbi].md_cmp = cintcmp;
4652 txn->mt_dbxs[dbi].md_cmp = memncmp;
4654 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4655 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP) {
4656 if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED)
4657 txn->mt_dbxs[dbi].md_dcmp = intcmp;
4659 txn->mt_dbxs[dbi].md_dcmp = cintcmp;
4660 } else if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEDUP) {
4661 txn->mt_dbxs[dbi].md_dcmp = memnrcmp;
4663 txn->mt_dbxs[dbi].md_dcmp = memncmp;
4666 txn->mt_dbxs[dbi].md_dcmp = NULL;
4670 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
4677 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
4678 mdb_default_cmp(txn, FREE_DBI);
4684 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
4685 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
4686 mdb_default_cmp(txn, MAIN_DBI);
4690 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
4691 mdb_default_cmp(txn, MAIN_DBI);
4694 /* Is the DB already open? */
4696 for (i=2; i<txn->mt_numdbs; i++) {
4697 if (len == txn->mt_dbxs[i].md_name.mv_size &&
4698 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
4704 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
4707 /* Find the DB info */
4709 key.mv_data = (void *)name;
4710 rc = mdb_get(txn, MAIN_DBI, &key, &data);
4712 /* Create if requested */
4713 if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
4716 data.mv_size = sizeof(MDB_db);
4717 data.mv_data = &dummy;
4718 memset(&dummy, 0, sizeof(dummy));
4719 dummy.md_root = P_INVALID;
4720 dummy.md_flags = flags & 0xffff;
4722 mc.mc_dbi = MAIN_DBI;
4724 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
4728 /* OK, got info, add to table */
4729 if (rc == MDB_SUCCESS) {
4730 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
4731 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
4732 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
4733 txn->mt_dbxs[txn->mt_numdbs].md_parent = MAIN_DBI;
4734 txn->mt_dbxs[txn->mt_numdbs].md_dirty = dirty;
4735 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
4736 *dbi = txn->mt_numdbs;
4737 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
4738 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
4739 mdb_default_cmp(txn, txn->mt_numdbs);
4746 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
4748 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
4751 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
4754 void mdb_close(MDB_txn *txn, MDB_dbi dbi)
4757 if (dbi <= MAIN_DBI || dbi >= txn->mt_numdbs)
4759 ptr = txn->mt_dbxs[dbi].md_name.mv_data;
4760 txn->mt_dbxs[dbi].md_name.mv_data = NULL;
4761 txn->mt_dbxs[dbi].md_name.mv_size = 0;
4765 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
4767 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4770 txn->mt_dbxs[dbi].md_cmp = cmp;
4774 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
4776 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4779 txn->mt_dbxs[dbi].md_dcmp = cmp;
4783 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
4785 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4788 txn->mt_dbxs[dbi].md_rel = rel;