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 " fmt "\n", __func__, __LINE__, __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 /** Identify a data item as a valid sub-DB record */
633 #define MDB_SUBDATA 0x8200
635 /** Meta page content. */
636 typedef struct MDB_meta {
637 /** Stamp identifying this as an MDB data file. It must be set
640 /** Version number of this lock file. Must be set to #MDB_VERSION. */
642 void *mm_address; /**< address for fixed mapping */
643 size_t mm_mapsize; /**< size of mmap region */
644 MDB_db mm_dbs[2]; /**< first is free space, 2nd is main db */
645 /** The size of pages used in this DB */
646 #define mm_psize mm_dbs[0].md_pad
647 /** Any persistent environment flags. @ref mdb_env */
648 #define mm_flags mm_dbs[0].md_flags
649 pgno_t mm_last_pg; /**< last used page in file */
650 txnid_t mm_txnid; /**< txnid that committed this page */
653 /** Auxiliary DB info.
654 * The information here is mostly static/read-only. There is
655 * only a single copy of this record in the environment.
656 * The \b md_dirty flag is not read-only, but only a write
657 * transaction can ever update it, and only write transactions
658 * need to worry about it.
660 typedef struct MDB_dbx {
661 MDB_val md_name; /**< name of the database */
662 MDB_cmp_func *md_cmp; /**< function for comparing keys */
663 MDB_cmp_func *md_dcmp; /**< function for comparing data items */
664 MDB_rel_func *md_rel; /**< user relocate function */
665 void *md_relctx; /**< user-provided context for md_rel */
666 MDB_dbi md_parent; /**< parent DB of a sub-DB */
667 unsigned int md_dirty; /**< TRUE if DB was written in this txn */
670 /** A database transaction.
671 * Every operation requires a transaction handle.
674 pgno_t mt_next_pgno; /**< next unallocated page */
675 /** The ID of this transaction. IDs are integers incrementing from 1.
676 * Only committed write transactions increment the ID. If a transaction
677 * aborts, the ID may be re-used by the next writer.
680 MDB_env *mt_env; /**< the DB environment */
681 /** The list of pages that became unused during this transaction.
686 ID2L dirty_list; /**< modified pages */
687 MDB_reader *reader; /**< this thread's slot in the reader table */
689 /** Array of records for each DB known in the environment. */
691 /** Array of MDB_db records for each known DB */
693 /** Number of DB records in use. This number only ever increments;
694 * we don't decrement it when individual DB handles are closed.
698 #define MDB_TXN_RDONLY 0x01 /**< read-only transaction */
699 #define MDB_TXN_ERROR 0x02 /**< an error has occurred */
700 unsigned int mt_flags;
701 /** Tracks which of the two meta pages was used at the start
702 * of this transaction.
704 unsigned int mt_toggle;
707 /** Enough space for 2^32 nodes with minimum of 2 keys per node. I.e., plenty.
708 * At 4 keys per node, enough for 2^64 nodes, so there's probably no need to
709 * raise this on a 64 bit machine.
711 #define CURSOR_STACK 32
715 /** Cursors are used for all DB operations */
717 /** Context used for databases with #MDB_DUPSORT, otherwise NULL */
718 struct MDB_xcursor *mc_xcursor;
719 /** The transaction that owns this cursor */
721 /** The database handle this cursor operates on */
723 /** The database record for this cursor */
725 /** The database auxiliary record for this cursor */
727 unsigned short mc_snum; /**< number of pushed pages */
728 unsigned short mc_top; /**< index of top page, mc_snum-1 */
729 unsigned int mc_flags;
730 #define C_INITIALIZED 0x01 /**< cursor has been initialized and is valid */
731 #define C_EOF 0x02 /**< No more data */
732 #define C_XDIRTY 0x04 /**< @deprecated mc_xcursor needs to be flushed */
733 MDB_page *mc_pg[CURSOR_STACK]; /**< stack of pushed pages */
734 indx_t mc_ki[CURSOR_STACK]; /**< stack of page indices */
737 /** Context for sorted-dup records.
738 * We could have gone to a fully recursive design, with arbitrarily
739 * deep nesting of sub-databases. But for now we only handle these
740 * levels - main DB, optional sub-DB, sorted-duplicate DB.
742 typedef struct MDB_xcursor {
743 /** A sub-cursor for traversing the Dup DB */
744 MDB_cursor mx_cursor;
745 /** The database record for this Dup DB */
747 /** The auxiliary DB record for this Dup DB */
751 /** A set of pages freed by an earlier transaction. */
752 typedef struct MDB_oldpages {
753 /** Usually we only read one record from the FREEDB at a time, but
754 * in case we read more, this will chain them together.
756 struct MDB_oldpages *mo_next;
757 /** The ID of the transaction in which these pages were freed. */
759 /** An #IDL of the pages */
760 pgno_t mo_pages[1]; /* dynamic */
763 /** The database environment. */
765 HANDLE me_fd; /**< The main data file */
766 HANDLE me_lfd; /**< The lock file */
767 HANDLE me_mfd; /**< just for writing the meta pages */
768 /** Failed to update the meta page. Probably an I/O error. */
769 #define MDB_FATAL_ERROR 0x80000000U
771 uint32_t me_extrapad; /**< unused for now */
772 unsigned int me_maxreaders; /**< size of the reader table */
773 MDB_dbi me_numdbs; /**< number of DBs opened */
774 MDB_dbi me_maxdbs; /**< size of the DB table */
775 char *me_path; /**< path to the DB files */
776 char *me_map; /**< the memory map of the data file */
777 MDB_txninfo *me_txns; /**< the memory map of the lock file */
778 MDB_meta *me_metas[2]; /**< pointers to the two meta pages */
779 MDB_txn *me_txn; /**< current write transaction */
780 size_t me_mapsize; /**< size of the data memory map */
781 off_t me_size; /**< current file size */
782 pgno_t me_maxpg; /**< me_mapsize / me_psize */
783 unsigned int me_psize; /**< size of a page, from #GET_PAGESIZE */
784 unsigned int me_db_toggle; /**< which DB table is current */
785 MDB_dbx *me_dbxs; /**< array of static DB info */
786 MDB_db *me_dbs[2]; /**< two arrays of MDB_db info */
787 MDB_oldpages *me_pghead; /**< list of old page records */
788 pthread_key_t me_txkey; /**< thread-key for readers */
789 MDB_page *me_dpages; /**< list of malloc'd blocks for re-use */
790 /** IDL of pages that became unused in a write txn */
791 pgno_t me_free_pgs[MDB_IDL_UM_SIZE];
792 /** ID2L of pages that were written during a write txn */
793 ID2 me_dirty_list[MDB_IDL_UM_SIZE];
794 /** rwlock for the DB tables, if #LAZY_LOCKS is false */
795 LAZY_RWLOCK_DEF(me_dblock)
797 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
801 /** max number of pages to commit in one writev() call */
802 #define MDB_COMMIT_PAGES 64
804 static MDB_page *mdb_alloc_page(MDB_cursor *mc, int num);
805 static int mdb_touch(MDB_cursor *mc);
807 static int mdb_search_page_root(MDB_cursor *mc,
808 MDB_val *key, int modify);
809 static int mdb_search_page(MDB_cursor *mc,
810 MDB_val *key, int modify);
812 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
813 static int mdb_env_read_meta(MDB_env *env, int *which);
814 static int mdb_env_write_meta(MDB_txn *txn);
815 static int mdb_get_page(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
817 static MDB_node *mdb_search_node(MDB_cursor *mc, MDB_val *key, int *exactp);
818 static int mdb_add_node(MDB_cursor *mc, indx_t indx,
819 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags);
820 static void mdb_del_node(MDB_page *mp, indx_t indx, int ksize);
821 static int mdb_del0(MDB_cursor *mc, MDB_node *leaf);
822 static int mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
824 static int mdb_rebalance(MDB_cursor *mc);
825 static int mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
826 static int mdb_move_node(MDB_cursor *csrc, MDB_cursor *cdst);
827 static int mdb_merge(MDB_cursor *csrc, MDB_cursor *cdst);
828 static int mdb_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata,
830 static MDB_page *mdb_new_page(MDB_cursor *mc, uint32_t flags, int num);
832 static void cursor_pop_page(MDB_cursor *mc);
833 static int cursor_push_page(MDB_cursor *mc, MDB_page *mp);
835 static int mdb_sibling(MDB_cursor *mc, int move_right);
836 static int mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
837 static int mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op);
838 static int mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op,
840 static int mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data);
841 static int mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data);
843 static void mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
844 static void mdb_xcursor_init0(MDB_cursor *mc);
845 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node);
847 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data);
848 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
850 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
853 static MDB_cmp_func memncmp, memnrcmp, intcmp, cintcmp, longcmp;
857 static SECURITY_DESCRIPTOR mdb_null_sd;
858 static SECURITY_ATTRIBUTES mdb_all_sa;
859 static int mdb_sec_inited;
862 /** Return the library version info. */
864 mdb_version(int *major, int *minor, int *patch)
866 if (major) *major = MDB_VERSION_MAJOR;
867 if (minor) *minor = MDB_VERSION_MINOR;
868 if (patch) *patch = MDB_VERSION_PATCH;
869 return MDB_VERSION_STRING;
872 /** Table of descriptions for MDB @ref errors */
873 static char *const mdb_errstr[] = {
874 "MDB_KEYEXIST: Key/data pair already exists",
875 "MDB_NOTFOUND: No matching key/data pair found",
876 "MDB_PAGE_NOTFOUND: Requested page not found",
877 "MDB_CORRUPTED: Located page was wrong type",
878 "MDB_PANIC: Update of meta page failed",
879 "MDB_VERSION_MISMATCH: Database environment version mismatch"
883 mdb_strerror(int err)
886 return ("Successful return: 0");
888 if (err >= MDB_KEYEXIST && err <= MDB_VERSION_MISMATCH)
889 return mdb_errstr[err - MDB_KEYEXIST];
891 return strerror(err);
895 /** Display a key in hexadecimal and return the address of the result.
896 * @param[in] key the key to display
897 * @param[in] buf the buffer to write into. Should always be #DKBUF.
898 * @return The key in hexadecimal form.
901 mdb_dkey(MDB_val *key, char *buf)
904 unsigned char *c = key->mv_data;
906 if (key->mv_size > MAXKEYSIZE)
908 /* may want to make this a dynamic check: if the key is mostly
909 * printable characters, print it as-is instead of converting to hex.
912 for (i=0; i<key->mv_size; i++)
913 ptr += sprintf(ptr, "%02x", *c++);
915 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
922 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
924 return txn->mt_dbxs[dbi].md_cmp(a, b);
928 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
930 if (txn->mt_dbxs[dbi].md_dcmp)
931 return txn->mt_dbxs[dbi].md_dcmp(a, b);
933 return EINVAL; /* too bad you can't distinguish this from a valid result */
936 /** Allocate pages for writing.
937 * If there are free pages available from older transactions, they
938 * will be re-used first. Otherwise a new page will be allocated.
939 * @param[in] mc cursor A cursor handle identifying the transaction and
940 * database for which we are allocating.
941 * @param[in] num the number of pages to allocate.
942 * @return Address of the allocated page(s). Requests for multiple pages
943 * will always be satisfied by a single contiguous chunk of memory.
946 mdb_alloc_page(MDB_cursor *mc, int num)
948 MDB_txn *txn = mc->mc_txn;
950 pgno_t pgno = P_INVALID;
953 if (txn->mt_txnid > 2) {
955 if (!txn->mt_env->me_pghead && mc->mc_dbi != FREE_DBI &&
956 txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
957 /* See if there's anything in the free DB */
960 txnid_t *kptr, oldest;
962 mdb_cursor_init(&m2, txn, FREE_DBI, NULL);
963 mdb_search_page(&m2, NULL, 0);
964 leaf = NODEPTR(m2.mc_pg[m2.mc_top], 0);
965 kptr = (txnid_t *)NODEKEY(leaf);
969 oldest = txn->mt_txnid - 1;
970 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
971 txnid_t mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
972 if (mr && mr < oldest)
977 if (oldest > *kptr) {
978 /* It's usable, grab it.
984 mdb_read_data(txn, leaf, &data);
985 idl = (ID *) data.mv_data;
986 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
987 mop->mo_next = txn->mt_env->me_pghead;
988 mop->mo_txnid = *kptr;
989 txn->mt_env->me_pghead = mop;
990 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
995 DPRINTF("IDL read txn %zu root %zu num %zu",
996 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
997 for (i=0; i<idl[0]; i++) {
998 DPRINTF("IDL %zu", idl[i+1]);
1002 /* drop this IDL from the DB */
1003 m2.mc_ki[m2.mc_top] = 0;
1004 m2.mc_flags = C_INITIALIZED;
1005 mdb_cursor_del(&m2, 0);
1008 if (txn->mt_env->me_pghead) {
1009 MDB_oldpages *mop = txn->mt_env->me_pghead;
1011 /* FIXME: For now, always use fresh pages. We
1012 * really ought to search the free list for a
1017 /* peel pages off tail, so we only have to truncate the list */
1018 pgno = MDB_IDL_LAST(mop->mo_pages);
1019 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
1021 if (mop->mo_pages[2] > mop->mo_pages[1])
1022 mop->mo_pages[0] = 0;
1026 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
1027 txn->mt_env->me_pghead = mop->mo_next;
1034 if (pgno == P_INVALID) {
1035 /* DB size is maxed out */
1036 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg) {
1037 assert(txn->mt_next_pgno + num < txn->mt_env->me_maxpg);
1041 if (txn->mt_env->me_dpages && num == 1) {
1042 np = txn->mt_env->me_dpages;
1043 txn->mt_env->me_dpages = np->mp_next;
1045 if ((np = malloc(txn->mt_env->me_psize * num )) == NULL)
1048 if (pgno == P_INVALID) {
1049 np->mp_pgno = txn->mt_next_pgno;
1050 txn->mt_next_pgno += num;
1054 mid.mid = np->mp_pgno;
1056 mdb_mid2l_insert(txn->mt_u.dirty_list, &mid);
1061 /** Touch a page: make it dirty and re-insert into tree with updated pgno.
1062 * @param[in] mc cursor pointing to the page to be touched
1063 * @return 0 on success, non-zero on failure.
1066 mdb_touch(MDB_cursor *mc)
1068 MDB_page *mp = mc->mc_pg[mc->mc_top];
1071 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
1073 if ((np = mdb_alloc_page(mc, 1)) == NULL)
1075 DPRINTF("touched db %u page %zu -> %zu", mc->mc_dbi, mp->mp_pgno, np->mp_pgno);
1076 assert(mp->mp_pgno != np->mp_pgno);
1077 mdb_midl_append(mc->mc_txn->mt_free_pgs, mp->mp_pgno);
1079 memcpy(np, mp, mc->mc_txn->mt_env->me_psize);
1082 mp->mp_flags |= P_DIRTY;
1084 mc->mc_pg[mc->mc_top] = mp;
1085 /** If this page has a parent, update the parent to point to
1089 SETPGNO(NODEPTR(mc->mc_pg[mc->mc_top-1], mc->mc_ki[mc->mc_top-1]), mp->mp_pgno);
1095 mdb_env_sync(MDB_env *env, int force)
1098 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
1099 if (fdatasync(env->me_fd))
1106 mdb_txn_reset0(MDB_txn *txn);
1108 /** Common code for #mdb_txn_begin() and #mdb_txn_renew().
1109 * @param[in] txn the transaction handle to initialize
1110 * @return 0 on success, non-zero on failure. This can only
1111 * fail for read-only transactions, and then only if the
1112 * reader table is full.
1115 mdb_txn_renew0(MDB_txn *txn)
1117 MDB_env *env = txn->mt_env;
1119 if (txn->mt_flags & MDB_TXN_RDONLY) {
1120 MDB_reader *r = pthread_getspecific(env->me_txkey);
1123 pid_t pid = getpid();
1124 pthread_t tid = pthread_self();
1127 for (i=0; i<env->me_txns->mti_numreaders; i++)
1128 if (env->me_txns->mti_readers[i].mr_pid == 0)
1130 if (i == env->me_maxreaders) {
1131 UNLOCK_MUTEX_R(env);
1134 env->me_txns->mti_readers[i].mr_pid = pid;
1135 env->me_txns->mti_readers[i].mr_tid = tid;
1136 if (i >= env->me_txns->mti_numreaders)
1137 env->me_txns->mti_numreaders = i+1;
1138 UNLOCK_MUTEX_R(env);
1139 r = &env->me_txns->mti_readers[i];
1140 pthread_setspecific(env->me_txkey, r);
1142 txn->mt_txnid = env->me_txns->mti_txnid;
1143 txn->mt_toggle = env->me_txns->mti_me_toggle;
1144 r->mr_txnid = txn->mt_txnid;
1145 txn->mt_u.reader = r;
1149 txn->mt_txnid = env->me_txns->mti_txnid+1;
1150 txn->mt_toggle = env->me_txns->mti_me_toggle;
1151 txn->mt_u.dirty_list = env->me_dirty_list;
1152 txn->mt_u.dirty_list[0].mid = 0;
1153 txn->mt_free_pgs = env->me_free_pgs;
1154 txn->mt_free_pgs[0] = 0;
1155 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
1159 /* Copy the DB arrays */
1160 LAZY_RWLOCK_RDLOCK(&env->me_dblock);
1161 txn->mt_numdbs = env->me_numdbs;
1162 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
1163 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
1164 if (txn->mt_numdbs > 2)
1165 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
1166 (txn->mt_numdbs - 2) * sizeof(MDB_db));
1167 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1173 mdb_txn_renew(MDB_txn *txn)
1180 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
1181 DPUTS("environment had fatal error, must shutdown!");
1185 rc = mdb_txn_renew0(txn);
1186 if (rc == MDB_SUCCESS) {
1187 DPRINTF("renew txn %zu%c %p on mdbenv %p, root page %zu",
1188 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1189 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1195 mdb_txn_begin(MDB_env *env, unsigned int flags, MDB_txn **ret)
1200 if (env->me_flags & MDB_FATAL_ERROR) {
1201 DPUTS("environment had fatal error, must shutdown!");
1204 if ((txn = calloc(1, sizeof(MDB_txn) + env->me_maxdbs * sizeof(MDB_db))) == NULL) {
1205 DPRINTF("calloc: %s", strerror(ErrCode()));
1208 txn->mt_dbs = (MDB_db *)(txn+1);
1209 if (flags & MDB_RDONLY) {
1210 txn->mt_flags |= MDB_TXN_RDONLY;
1214 rc = mdb_txn_renew0(txn);
1219 DPRINTF("begin txn %zu%c %p on mdbenv %p, root page %zu",
1220 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1221 (void *) txn, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
1227 /** Common code for #mdb_txn_reset() and #mdb_txn_abort().
1228 * @param[in] txn the transaction handle to reset
1231 mdb_txn_reset0(MDB_txn *txn)
1233 MDB_env *env = txn->mt_env;
1235 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1236 txn->mt_u.reader->mr_txnid = 0;
1243 /* return all dirty pages to dpage list */
1244 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1245 dp = txn->mt_u.dirty_list[i].mptr;
1246 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1247 dp->mp_next = txn->mt_env->me_dpages;
1248 txn->mt_env->me_dpages = dp;
1250 /* large pages just get freed directly */
1255 while ((mop = txn->mt_env->me_pghead)) {
1256 txn->mt_env->me_pghead = mop->mo_next;
1261 for (dbi=2; dbi<env->me_numdbs; dbi++)
1262 env->me_dbxs[dbi].md_dirty = 0;
1263 /* The writer mutex was locked in mdb_txn_begin. */
1264 UNLOCK_MUTEX_W(env);
1269 mdb_txn_reset(MDB_txn *txn)
1274 DPRINTF("reset txn %zu%c %p on mdbenv %p, root page %zu",
1275 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1276 (void *) txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1278 mdb_txn_reset0(txn);
1282 mdb_txn_abort(MDB_txn *txn)
1287 DPRINTF("abort txn %zu%c %p on mdbenv %p, root page %zu",
1288 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
1289 (void *)txn, (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
1291 mdb_txn_reset0(txn);
1296 mdb_txn_commit(MDB_txn *txn)
1307 assert(txn != NULL);
1308 assert(txn->mt_env != NULL);
1312 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
1317 if (txn != env->me_txn) {
1318 DPUTS("attempt to commit unknown transaction");
1323 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1324 DPUTS("error flag is set, can't commit");
1329 if (!txn->mt_u.dirty_list[0].mid)
1332 DPRINTF("committing txn %zu %p on mdbenv %p, root page %zu",
1333 txn->mt_txnid, (void *)txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
1335 mdb_cursor_init(&mc, txn, FREE_DBI, NULL);
1337 /* should only be one record now */
1338 if (env->me_pghead) {
1339 /* make sure first page of freeDB is touched and on freelist */
1340 mdb_search_page(&mc, NULL, 1);
1342 /* save to free list */
1343 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
1347 /* make sure last page of freeDB is touched and on freelist */
1348 key.mv_size = MAXKEYSIZE+1;
1350 mdb_search_page(&mc, &key, 1);
1352 mdb_midl_sort(txn->mt_free_pgs);
1356 ID *idl = txn->mt_free_pgs;
1357 DPRINTF("IDL write txn %zu root %zu num %zu",
1358 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1359 for (i=0; i<idl[0]; i++) {
1360 DPRINTF("IDL %zu", idl[i+1]);
1364 /* write to last page of freeDB */
1365 key.mv_size = sizeof(pgno_t);
1366 key.mv_data = &txn->mt_txnid;
1367 data.mv_data = txn->mt_free_pgs;
1368 /* The free list can still grow during this call,
1369 * despite the pre-emptive touches above. So check
1370 * and make sure the entire thing got written.
1373 i = txn->mt_free_pgs[0];
1374 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
1375 rc = mdb_cursor_put(&mc, &key, &data, 0);
1380 } while (i != txn->mt_free_pgs[0]);
1382 /* should only be one record now */
1383 if (env->me_pghead) {
1387 mop = env->me_pghead;
1388 key.mv_size = sizeof(pgno_t);
1389 key.mv_data = &mop->mo_txnid;
1390 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
1391 data.mv_data = mop->mo_pages;
1392 mdb_cursor_put(&mc, &key, &data, 0);
1393 free(env->me_pghead);
1394 env->me_pghead = NULL;
1397 /* Update DB root pointers. Their pages have already been
1398 * touched so this is all in-place and cannot fail.
1403 data.mv_size = sizeof(MDB_db);
1405 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
1406 for (i = 2; i < txn->mt_numdbs; i++) {
1407 if (txn->mt_dbxs[i].md_dirty) {
1408 data.mv_data = &txn->mt_dbs[i];
1409 mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
1414 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
1420 /* Windows actually supports scatter/gather I/O, but only on
1421 * unbuffered file handles. Since we're relying on the OS page
1422 * cache for all our data, that's self-defeating. So we just
1423 * write pages one at a time. We use the ov structure to set
1424 * the write offset, to at least save the overhead of a Seek
1428 memset(&ov, 0, sizeof(ov));
1429 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1431 dp = txn->mt_u.dirty_list[i].mptr;
1432 DPRINTF("committing page %zu", dp->mp_pgno);
1433 size = dp->mp_pgno * env->me_psize;
1434 ov.Offset = size & 0xffffffff;
1435 ov.OffsetHigh = size >> 16;
1436 ov.OffsetHigh >>= 16;
1437 /* clear dirty flag */
1438 dp->mp_flags &= ~P_DIRTY;
1439 wsize = env->me_psize;
1440 if (IS_OVERFLOW(dp)) wsize *= dp->mp_pages;
1441 rc = WriteFile(env->me_fd, dp, wsize, NULL, &ov);
1444 DPRINTF("WriteFile: %d", n);
1451 struct iovec iov[MDB_COMMIT_PAGES];
1455 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1456 dp = txn->mt_u.dirty_list[i].mptr;
1457 if (dp->mp_pgno != next) {
1459 DPRINTF("committing %u dirty pages", n);
1460 rc = writev(env->me_fd, iov, n);
1464 DPUTS("short write, filesystem full?");
1466 DPRINTF("writev: %s", strerror(n));
1473 lseek(env->me_fd, dp->mp_pgno * env->me_psize, SEEK_SET);
1476 DPRINTF("committing page %zu", dp->mp_pgno);
1477 iov[n].iov_len = env->me_psize;
1478 if (IS_OVERFLOW(dp)) iov[n].iov_len *= dp->mp_pages;
1479 iov[n].iov_base = dp;
1480 size += iov[n].iov_len;
1481 next = dp->mp_pgno + (IS_OVERFLOW(dp) ? dp->mp_pages : 1);
1482 /* clear dirty flag */
1483 dp->mp_flags &= ~P_DIRTY;
1484 if (++n >= MDB_COMMIT_PAGES) {
1494 DPRINTF("committing %u dirty pages", n);
1495 rc = writev(env->me_fd, iov, n);
1499 DPUTS("short write, filesystem full?");
1501 DPRINTF("writev: %s", strerror(n));
1508 /* Drop the dirty pages.
1510 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1511 dp = txn->mt_u.dirty_list[i].mptr;
1512 if (!IS_OVERFLOW(dp) || dp->mp_pages == 1) {
1513 dp->mp_next = txn->mt_env->me_dpages;
1514 txn->mt_env->me_dpages = dp;
1518 txn->mt_u.dirty_list[i].mid = 0;
1520 txn->mt_u.dirty_list[0].mid = 0;
1522 if ((n = mdb_env_sync(env, 0)) != 0 ||
1523 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
1530 /* update the DB tables */
1532 int toggle = !env->me_db_toggle;
1536 ip = &env->me_dbs[toggle][2];
1537 jp = &txn->mt_dbs[2];
1538 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1539 for (i = 2; i < txn->mt_numdbs; i++) {
1540 if (ip->md_root != jp->md_root)
1545 for (i = 2; i < txn->mt_numdbs; i++) {
1546 if (txn->mt_dbxs[i].md_dirty)
1547 txn->mt_dbxs[i].md_dirty = 0;
1549 env->me_db_toggle = toggle;
1550 env->me_numdbs = txn->mt_numdbs;
1551 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1554 UNLOCK_MUTEX_W(env);
1560 /** Read the environment parameters of a DB environment before
1561 * mapping it into memory.
1562 * @param[in] env the environment handle
1563 * @param[out] meta address of where to store the meta information
1564 * @return 0 on success, non-zero on failure.
1567 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
1569 char page[PAGESIZE];
1574 /* We don't know the page size yet, so use a minimum value.
1578 if (!ReadFile(env->me_fd, page, PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
1580 if ((rc = read(env->me_fd, page, PAGESIZE)) == 0)
1585 else if (rc != PAGESIZE) {
1589 DPRINTF("read: %s", strerror(err));
1593 p = (MDB_page *)page;
1595 if (!F_ISSET(p->mp_flags, P_META)) {
1596 DPRINTF("page %zu not a meta page", p->mp_pgno);
1601 if (m->mm_magic != MDB_MAGIC) {
1602 DPUTS("meta has invalid magic");
1606 if (m->mm_version != MDB_VERSION) {
1607 DPRINTF("database is version %u, expected version %u",
1608 m->mm_version, MDB_VERSION);
1609 return MDB_VERSION_MISMATCH;
1612 memcpy(meta, m, sizeof(*m));
1616 /** Write the environment parameters of a freshly created DB environment.
1617 * @param[in] env the environment handle
1618 * @param[out] meta address of where to store the meta information
1619 * @return 0 on success, non-zero on failure.
1622 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
1629 DPUTS("writing new meta page");
1631 GET_PAGESIZE(psize);
1633 meta->mm_magic = MDB_MAGIC;
1634 meta->mm_version = MDB_VERSION;
1635 meta->mm_psize = psize;
1636 meta->mm_last_pg = 1;
1637 meta->mm_flags = env->me_flags & 0xffff;
1638 meta->mm_flags |= MDB_INTEGERKEY;
1639 meta->mm_dbs[0].md_root = P_INVALID;
1640 meta->mm_dbs[1].md_root = P_INVALID;
1642 p = calloc(2, psize);
1644 p->mp_flags = P_META;
1647 memcpy(m, meta, sizeof(*meta));
1649 q = (MDB_page *)((char *)p + psize);
1652 q->mp_flags = P_META;
1655 memcpy(m, meta, sizeof(*meta));
1660 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
1661 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
1664 rc = write(env->me_fd, p, psize * 2);
1665 rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
1671 /** Update the environment info to commit a transaction.
1672 * @param[in] txn the transaction that's being committed
1673 * @return 0 on success, non-zero on failure.
1676 mdb_env_write_meta(MDB_txn *txn)
1679 MDB_meta meta, metab;
1681 int rc, len, toggle;
1687 assert(txn != NULL);
1688 assert(txn->mt_env != NULL);
1690 toggle = !txn->mt_toggle;
1691 DPRINTF("writing meta page %d for root page %zu",
1692 toggle, txn->mt_dbs[MAIN_DBI].md_root);
1696 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
1697 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
1699 ptr = (char *)&meta;
1700 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
1701 len = sizeof(MDB_meta) - off;
1704 meta.mm_dbs[0] = txn->mt_dbs[0];
1705 meta.mm_dbs[1] = txn->mt_dbs[1];
1706 meta.mm_last_pg = txn->mt_next_pgno - 1;
1707 meta.mm_txnid = txn->mt_txnid;
1710 off += env->me_psize;
1713 /* Write to the SYNC fd */
1716 memset(&ov, 0, sizeof(ov));
1718 WriteFile(env->me_mfd, ptr, len, (DWORD *)&rc, &ov);
1721 rc = pwrite(env->me_mfd, ptr, len, off);
1726 DPUTS("write failed, disk error?");
1727 /* On a failure, the pagecache still contains the new data.
1728 * Write some old data back, to prevent it from being used.
1729 * Use the non-SYNC fd; we know it will fail anyway.
1731 meta.mm_last_pg = metab.mm_last_pg;
1732 meta.mm_txnid = metab.mm_txnid;
1734 WriteFile(env->me_fd, ptr, len, NULL, &ov);
1736 r2 = pwrite(env->me_fd, ptr, len, off);
1738 env->me_flags |= MDB_FATAL_ERROR;
1741 /* Memory ordering issues are irrelevant; since the entire writer
1742 * is wrapped by wmutex, all of these changes will become visible
1743 * after the wmutex is unlocked. Since the DB is multi-version,
1744 * readers will get consistent data regardless of how fresh or
1745 * how stale their view of these values is.
1747 LAZY_MUTEX_LOCK(&env->me_txns->mti_mutex);
1748 txn->mt_env->me_txns->mti_me_toggle = toggle;
1749 txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
1750 LAZY_MUTEX_UNLOCK(&env->me_txns->mti_mutex);
1755 /** Check both meta pages to see which one is newer.
1756 * @param[in] env the environment handle
1757 * @param[out] which address of where to store the meta toggle ID
1758 * @return 0 on success, non-zero on failure.
1761 mdb_env_read_meta(MDB_env *env, int *which)
1765 assert(env != NULL);
1767 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1770 DPRINTF("Using meta page %d", toggle);
1777 mdb_env_create(MDB_env **env)
1781 e = calloc(1, sizeof(MDB_env));
1785 e->me_maxreaders = DEFAULT_READERS;
1787 e->me_fd = INVALID_HANDLE_VALUE;
1788 e->me_lfd = INVALID_HANDLE_VALUE;
1789 e->me_mfd = INVALID_HANDLE_VALUE;
1795 mdb_env_set_mapsize(MDB_env *env, size_t size)
1799 env->me_mapsize = size;
1804 mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs)
1808 env->me_maxdbs = dbs;
1813 mdb_env_set_maxreaders(MDB_env *env, unsigned int readers)
1815 if (env->me_map || readers < 1)
1817 env->me_maxreaders = readers;
1822 mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers)
1824 if (!env || !readers)
1826 *readers = env->me_maxreaders;
1830 /** Further setup required for opening an MDB environment
1833 mdb_env_open2(MDB_env *env, unsigned int flags)
1835 int i, newenv = 0, toggle;
1839 env->me_flags = flags;
1841 memset(&meta, 0, sizeof(meta));
1843 if ((i = mdb_env_read_header(env, &meta)) != 0) {
1846 DPUTS("new mdbenv");
1850 if (!env->me_mapsize) {
1851 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
1857 LONG sizelo, sizehi;
1858 sizelo = env->me_mapsize & 0xffffffff;
1859 sizehi = env->me_mapsize >> 16; /* pointless on WIN32, only needed on W64 */
1861 /* Windows won't create mappings for zero length files.
1862 * Just allocate the maxsize right now.
1865 SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
1866 if (!SetEndOfFile(env->me_fd))
1868 SetFilePointer(env->me_fd, 0, NULL, 0);
1870 mh = CreateFileMapping(env->me_fd, NULL, PAGE_READONLY,
1871 sizehi, sizelo, NULL);
1874 env->me_map = MapViewOfFileEx(mh, FILE_MAP_READ, 0, 0, env->me_mapsize,
1882 if (meta.mm_address && (flags & MDB_FIXEDMAP))
1884 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
1886 if (env->me_map == MAP_FAILED)
1891 meta.mm_mapsize = env->me_mapsize;
1892 if (flags & MDB_FIXEDMAP)
1893 meta.mm_address = env->me_map;
1894 i = mdb_env_init_meta(env, &meta);
1895 if (i != MDB_SUCCESS) {
1896 munmap(env->me_map, env->me_mapsize);
1900 env->me_psize = meta.mm_psize;
1902 env->me_maxpg = env->me_mapsize / env->me_psize;
1904 p = (MDB_page *)env->me_map;
1905 env->me_metas[0] = METADATA(p);
1906 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
1908 if ((i = mdb_env_read_meta(env, &toggle)) != 0)
1911 DPRINTF("opened database version %u, pagesize %u",
1912 env->me_metas[toggle]->mm_version, env->me_psize);
1913 DPRINTF("depth: %u", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_depth);
1914 DPRINTF("entries: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_entries);
1915 DPRINTF("branch pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_branch_pages);
1916 DPRINTF("leaf pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_leaf_pages);
1917 DPRINTF("overflow pages: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_overflow_pages);
1918 DPRINTF("root: %zu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_root);
1924 /* Windows doesn't support destructor callbacks for thread-specific storage */
1926 mdb_env_reader_dest(void *ptr)
1928 MDB_reader *reader = ptr;
1930 reader->mr_txnid = 0;
1936 /* downgrade the exclusive lock on the region back to shared */
1938 mdb_env_share_locks(MDB_env *env)
1942 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1944 env->me_txns->mti_me_toggle = toggle;
1945 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
1950 /* First acquire a shared lock. The Unlock will
1951 * then release the existing exclusive lock.
1953 memset(&ov, 0, sizeof(ov));
1954 LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov);
1955 UnlockFile(env->me_lfd, 0, 0, 1, 0);
1959 struct flock lock_info;
1960 /* The shared lock replaces the existing lock */
1961 memset((void *)&lock_info, 0, sizeof(lock_info));
1962 lock_info.l_type = F_RDLCK;
1963 lock_info.l_whence = SEEK_SET;
1964 lock_info.l_start = 0;
1965 lock_info.l_len = 1;
1966 fcntl(env->me_lfd, F_SETLK, &lock_info);
1972 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
1980 if ((env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
1981 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
1982 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
1986 /* Try to get exclusive lock. If we succeed, then
1987 * nobody is using the lock region and we should initialize it.
1990 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
1994 memset(&ov, 0, sizeof(ov));
1995 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
2001 size = GetFileSize(env->me_lfd, NULL);
2003 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
2007 /* Try to get exclusive lock. If we succeed, then
2008 * nobody is using the lock region and we should initialize it.
2011 struct flock lock_info;
2012 memset((void *)&lock_info, 0, sizeof(lock_info));
2013 lock_info.l_type = F_WRLCK;
2014 lock_info.l_whence = SEEK_SET;
2015 lock_info.l_start = 0;
2016 lock_info.l_len = 1;
2017 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
2021 lock_info.l_type = F_RDLCK;
2022 rc = fcntl(env->me_lfd, F_SETLKW, &lock_info);
2029 size = lseek(env->me_lfd, 0, SEEK_END);
2031 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
2032 if (size < rsize && *excl) {
2034 SetFilePointer(env->me_lfd, rsize, NULL, 0);
2035 if (!SetEndOfFile(env->me_lfd)) {
2040 if (ftruncate(env->me_lfd, rsize) != 0) {
2047 size = rsize - sizeof(MDB_txninfo);
2048 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
2053 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
2059 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
2061 if (!env->me_txns) {
2067 env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
2069 if (env->me_txns == MAP_FAILED) {
2077 if (!mdb_sec_inited) {
2078 InitializeSecurityDescriptor(&mdb_null_sd,
2079 SECURITY_DESCRIPTOR_REVISION);
2080 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
2081 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2082 mdb_all_sa.bInheritHandle = FALSE;
2083 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
2086 /* FIXME: only using up to 20 characters of the env path here,
2087 * probably not enough to assure uniqueness...
2089 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%.20s", lpath);
2090 ptr = env->me_txns->mti_rmname + sizeof("Global\\MDBr");
2091 while ((ptr = strchr(ptr, '\\')))
2093 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
2094 if (!env->me_rmutex) {
2098 sprintf(env->me_txns->mti_rmname, "Global\\MDBw%.20s", lpath);
2099 ptr = env->me_txns->mti_rmname + sizeof("Global\\MDBw");
2100 while ((ptr = strchr(ptr, '\\')))
2102 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
2103 if (!env->me_wmutex) {
2108 pthread_mutexattr_t mattr;
2110 pthread_mutexattr_init(&mattr);
2111 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
2115 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
2116 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
2118 env->me_txns->mti_version = MDB_VERSION;
2119 env->me_txns->mti_magic = MDB_MAGIC;
2120 env->me_txns->mti_txnid = 0;
2121 env->me_txns->mti_numreaders = 0;
2122 env->me_txns->mti_me_toggle = 0;
2125 if (env->me_txns->mti_magic != MDB_MAGIC) {
2126 DPUTS("lock region has invalid magic");
2130 if (env->me_txns->mti_version != MDB_VERSION) {
2131 DPRINTF("lock region is version %u, expected version %u",
2132 env->me_txns->mti_version, MDB_VERSION);
2133 rc = MDB_VERSION_MISMATCH;
2137 if (rc != EACCES && rc != EAGAIN) {
2141 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
2142 if (!env->me_rmutex) {
2146 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
2147 if (!env->me_wmutex) {
2157 env->me_lfd = INVALID_HANDLE_VALUE;
2162 /** The name of the lock file in the DB environment */
2163 #define LOCKNAME "/lock.mdb"
2164 /** The name of the data file in the DB environment */
2165 #define DATANAME "/data.mdb"
2167 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
2169 int oflags, rc, len, excl;
2170 char *lpath, *dpath;
2173 lpath = malloc(len + sizeof(LOCKNAME) + len + sizeof(DATANAME));
2176 dpath = lpath + len + sizeof(LOCKNAME);
2177 sprintf(lpath, "%s" LOCKNAME, path);
2178 sprintf(dpath, "%s" DATANAME, path);
2180 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
2185 if (F_ISSET(flags, MDB_RDONLY)) {
2186 oflags = GENERIC_READ;
2187 len = OPEN_EXISTING;
2189 oflags = GENERIC_READ|GENERIC_WRITE;
2192 mode = FILE_ATTRIBUTE_NORMAL;
2193 if ((env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2194 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2199 if (F_ISSET(flags, MDB_RDONLY))
2202 oflags = O_RDWR | O_CREAT;
2204 if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
2210 if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
2211 /* synchronous fd for meta writes */
2213 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2214 mode |= FILE_FLAG_WRITE_THROUGH;
2215 if ((env->me_mfd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
2216 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
2221 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
2222 oflags |= MDB_DSYNC;
2223 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
2228 env->me_path = strdup(path);
2229 DPRINTF("opened dbenv %p", (void *) env);
2230 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
2231 LAZY_RWLOCK_INIT(&env->me_dblock, NULL);
2233 mdb_env_share_locks(env);
2234 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
2235 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
2236 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
2242 if (env->me_fd != INVALID_HANDLE_VALUE) {
2244 env->me_fd = INVALID_HANDLE_VALUE;
2246 if (env->me_lfd != INVALID_HANDLE_VALUE) {
2248 env->me_lfd = INVALID_HANDLE_VALUE;
2256 mdb_env_close(MDB_env *env)
2263 while (env->me_dpages) {
2264 dp = env->me_dpages;
2265 env->me_dpages = dp->mp_next;
2269 free(env->me_dbs[1]);
2270 free(env->me_dbs[0]);
2274 LAZY_RWLOCK_DESTROY(&env->me_dblock);
2275 pthread_key_delete(env->me_txkey);
2278 munmap(env->me_map, env->me_mapsize);
2283 pid_t pid = getpid();
2285 for (i=0; i<env->me_txns->mti_numreaders; i++)
2286 if (env->me_txns->mti_readers[i].mr_pid == pid)
2287 env->me_txns->mti_readers[i].mr_pid = 0;
2288 munmap(env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
2294 /* only for aligned size_t's */
2296 longcmp(const MDB_val *a, const MDB_val *b)
2298 return (*(size_t *)a->mv_data < *(size_t *)b->mv_data) ? -1 :
2299 *(size_t *)a->mv_data > *(size_t *)b->mv_data;
2302 /* only for aligned ints */
2304 intcmp(const MDB_val *a, const MDB_val *b)
2306 return (*(unsigned int *)a->mv_data < *(unsigned int *)b->mv_data) ? -1 :
2307 *(unsigned int *)a->mv_data > *(unsigned int *)b->mv_data;
2310 /* ints must always be the same size */
2312 cintcmp(const MDB_val *a, const MDB_val *b)
2314 #if __BYTE_ORDER == __LITTLE_ENDIAN
2315 unsigned short *u, *c;
2318 u = (unsigned short *) ((char *) a->mv_data + a->mv_size);
2319 c = (unsigned short *) ((char *) b->mv_data + a->mv_size);
2322 } while(!x && u > (unsigned short *)a->mv_data);
2325 return memcmp(a->mv_data, b->mv_data, a->mv_size);
2330 memncmp(const MDB_val *a, const MDB_val *b)
2337 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
2343 diff = memcmp(a->mv_data, b->mv_data, len);
2344 return diff ? diff : len_diff<0 ? -1 : len_diff;
2348 memnrcmp(const MDB_val *a, const MDB_val *b)
2350 const unsigned char *p1, *p2, *p1_lim;
2354 p1_lim = (const unsigned char *)a->mv_data;
2355 p1 = (const unsigned char *)a->mv_data + a->mv_size;
2356 p2 = (const unsigned char *)b->mv_data + b->mv_size;
2358 len_diff = (ssize_t) a->mv_size - (ssize_t) b->mv_size;
2364 while (p1 > p1_lim) {
2365 diff = *--p1 - *--p2;
2369 return len_diff<0 ? -1 : len_diff;
2372 /* Search for key within a leaf page, using binary search.
2373 * Returns the smallest entry larger or equal to the key.
2374 * If exactp is non-null, stores whether the found entry was an exact match
2375 * in *exactp (1 or 0).
2376 * If kip is non-null, stores the index of the found entry in *kip.
2377 * If no entry larger or equal to the key is found, returns NULL.
2380 mdb_search_node(MDB_cursor *mc, MDB_val *key, int *exactp)
2382 unsigned int i = 0, nkeys;
2385 MDB_page *mp = mc->mc_pg[mc->mc_top];
2386 MDB_node *node = NULL;
2391 nkeys = NUMKEYS(mp);
2393 DPRINTF("searching %u keys in %s page %zu",
2394 nkeys, IS_LEAF(mp) ? "leaf" : "branch",
2399 low = IS_LEAF(mp) ? 0 : 1;
2401 cmp = mc->mc_dbx->md_cmp;
2403 /* Branch pages have no data, so if using integer keys,
2404 * alignment is guaranteed. Use faster intcmp.
2406 if (cmp == cintcmp && IS_BRANCH(mp)) {
2407 if (NODEPTR(mp, 1)->mn_ksize == sizeof(size_t))
2414 nodekey.mv_size = mc->mc_db->md_pad;
2415 node = NODEPTR(mp, 0); /* fake */
2417 while (low <= high) {
2418 i = (low + high) >> 1;
2421 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
2423 node = NODEPTR(mp, i);
2425 nodekey.mv_size = node->mn_ksize;
2426 nodekey.mv_data = NODEKEY(node);
2429 rc = cmp(key, &nodekey);
2433 DPRINTF("found leaf index %u [%s], rc = %i",
2434 i, DKEY(&nodekey), rc);
2436 DPRINTF("found branch index %u [%s -> %zu], rc = %i",
2437 i, DKEY(&nodekey), NODEPGNO(node), rc);
2448 if (rc > 0) { /* Found entry is less than the key. */
2449 i++; /* Skip to get the smallest entry larger than key. */
2451 node = NODEPTR(mp, i);
2454 *exactp = (rc == 0);
2455 /* store the key index */
2456 mc->mc_ki[mc->mc_top] = i;
2458 /* There is no entry larger or equal to the key. */
2461 /* nodeptr is fake for LEAF2 */
2466 cursor_pop_page(MDB_cursor *mc)
2471 top = mc->mc_pg[mc->mc_top];
2476 DPRINTF("popped page %zu off db %u cursor %p", top->mp_pgno,
2477 mc->mc_dbi, (void *) mc);
2482 cursor_push_page(MDB_cursor *mc, MDB_page *mp)
2484 DPRINTF("pushing page %zu on db %u cursor %p", mp->mp_pgno,
2485 mc->mc_dbi, (void *) mc);
2487 if (mc->mc_snum >= CURSOR_STACK) {
2488 assert(mc->mc_snum < CURSOR_STACK);
2492 mc->mc_top = mc->mc_snum++;
2493 mc->mc_pg[mc->mc_top] = mp;
2494 mc->mc_ki[mc->mc_top] = 0;
2500 mdb_get_page(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
2504 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
2506 x = mdb_mid2l_search(txn->mt_u.dirty_list, pgno);
2507 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
2508 p = txn->mt_u.dirty_list[x].mptr;
2512 if (pgno <= txn->mt_env->me_metas[txn->mt_toggle]->mm_last_pg)
2513 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
2517 DPRINTF("page %zu not found", pgno);
2520 return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
2524 mdb_search_page_root(MDB_cursor *mc, MDB_val *key, int modify)
2526 MDB_page *mp = mc->mc_pg[mc->mc_top];
2531 while (IS_BRANCH(mp)) {
2534 DPRINTF("branch page %zu has %u keys", mp->mp_pgno, NUMKEYS(mp));
2535 assert(NUMKEYS(mp) > 1);
2536 DPRINTF("found index 0 to page %zu", NODEPGNO(NODEPTR(mp, 0)));
2538 if (key == NULL) /* Initialize cursor to first page. */
2539 mc->mc_ki[mc->mc_top] = 0;
2540 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
2541 /* cursor to last page */
2542 mc->mc_ki[mc->mc_top] = NUMKEYS(mp)-1;
2545 node = mdb_search_node(mc, key, &exact);
2547 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
2549 assert(mc->mc_ki[mc->mc_top] > 0);
2550 mc->mc_ki[mc->mc_top]--;
2555 DPRINTF("following index %u for key [%s]",
2556 mc->mc_ki[mc->mc_top], DKEY(key));
2557 assert(mc->mc_ki[mc->mc_top] < NUMKEYS(mp));
2558 node = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
2560 if ((rc = mdb_get_page(mc->mc_txn, NODEPGNO(node), &mp)))
2563 if ((rc = cursor_push_page(mc, mp)))
2567 if ((rc = mdb_touch(mc)) != 0)
2569 mp = mc->mc_pg[mc->mc_top];
2574 DPRINTF("internal error, index points to a %02X page!?",
2576 return MDB_CORRUPTED;
2579 DPRINTF("found leaf page %zu for key [%s]", mp->mp_pgno,
2580 key ? DKEY(key) : NULL);
2585 /* Search for the page a given key should be in.
2586 * Pushes parent pages on the cursor stack.
2587 * If key is NULL, search for the lowest page (used by mdb_cursor_first).
2588 * If modify is true, visited pages are updated with new page numbers.
2591 mdb_search_page(MDB_cursor *mc, MDB_val *key, int modify)
2596 /* Make sure the txn is still viable, then find the root from
2597 * the txn's db table.
2599 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_ERROR)) {
2600 DPUTS("transaction has failed, must abort");
2603 root = mc->mc_db->md_root;
2605 if (root == P_INVALID) { /* Tree is empty. */
2606 DPUTS("tree is empty");
2607 return MDB_NOTFOUND;
2610 if ((rc = mdb_get_page(mc->mc_txn, root, &mc->mc_pg[0])))
2616 DPRINTF("db %u root page %zu has flags 0x%X",
2617 mc->mc_dbi, root, mc->mc_pg[0]->mp_flags);
2620 /* For sub-databases, update main root first */
2621 if (mc->mc_dbi > MAIN_DBI && !mc->mc_dbx->md_dirty) {
2623 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
2624 rc = mdb_search_page(&mc2, &mc->mc_dbx->md_name, 1);
2627 mc->mc_dbx->md_dirty = 1;
2629 if (!F_ISSET(mc->mc_pg[0]->mp_flags, P_DIRTY)) {
2630 if ((rc = mdb_touch(mc)))
2632 mc->mc_db->md_root = mc->mc_pg[0]->mp_pgno;
2636 return mdb_search_page_root(mc, key, modify);
2640 mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
2642 MDB_page *omp; /* overflow mpage */
2646 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
2647 data->mv_size = NODEDSZ(leaf);
2648 data->mv_data = NODEDATA(leaf);
2652 /* Read overflow data.
2654 data->mv_size = NODEDSZ(leaf);
2655 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
2656 if ((rc = mdb_get_page(txn, pgno, &omp))) {
2657 DPRINTF("read overflow page %zu failed", pgno);
2660 data->mv_data = METADATA(omp);
2666 mdb_get(MDB_txn *txn, MDB_dbi dbi,
2667 MDB_val *key, MDB_val *data)
2676 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
2678 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
2681 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2685 mdb_cursor_init(&mc, txn, dbi, &mx);
2686 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
2690 mdb_sibling(MDB_cursor *mc, int move_right)
2696 if (mc->mc_snum < 2) {
2697 return MDB_NOTFOUND; /* root has no siblings */
2700 cursor_pop_page(mc);
2701 DPRINTF("parent page is page %zu, index %u",
2702 mc->mc_pg[mc->mc_top]->mp_pgno, mc->mc_ki[mc->mc_top]);
2704 if (move_right ? (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mc->mc_pg[mc->mc_top]))
2705 : (mc->mc_ki[mc->mc_top] == 0)) {
2706 DPRINTF("no more keys left, moving to %s sibling",
2707 move_right ? "right" : "left");
2708 if ((rc = mdb_sibling(mc, move_right)) != MDB_SUCCESS)
2712 mc->mc_ki[mc->mc_top]++;
2714 mc->mc_ki[mc->mc_top]--;
2715 DPRINTF("just moving to %s index key %u",
2716 move_right ? "right" : "left", mc->mc_ki[mc->mc_top]);
2718 assert(IS_BRANCH(mc->mc_pg[mc->mc_top]));
2720 indx = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
2721 if ((rc = mdb_get_page(mc->mc_txn, NODEPGNO(indx), &mp)))
2724 cursor_push_page(mc, mp);
2730 mdb_cursor_next(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
2736 if (mc->mc_flags & C_EOF) {
2737 return MDB_NOTFOUND;
2740 assert(mc->mc_flags & C_INITIALIZED);
2742 mp = mc->mc_pg[mc->mc_top];
2744 if (mc->mc_db->md_flags & MDB_DUPSORT) {
2745 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
2746 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2747 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
2748 rc = mdb_cursor_next(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
2749 if (op != MDB_NEXT || rc == MDB_SUCCESS)
2753 mc->mc_xcursor->mx_cursor.mc_flags = 0;
2754 if (op == MDB_NEXT_DUP)
2755 return MDB_NOTFOUND;
2759 DPRINTF("cursor_next: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
2761 if (mc->mc_ki[mc->mc_top] + 1u >= NUMKEYS(mp)) {
2762 DPUTS("=====> move to next sibling page");
2763 if (mdb_sibling(mc, 1) != MDB_SUCCESS) {
2764 mc->mc_flags |= C_EOF;
2765 return MDB_NOTFOUND;
2767 mp = mc->mc_pg[mc->mc_top];
2768 DPRINTF("next page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
2770 mc->mc_ki[mc->mc_top]++;
2772 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
2773 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
2776 key->mv_size = mc->mc_db->md_pad;
2777 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
2781 assert(IS_LEAF(mp));
2782 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
2784 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2785 mdb_xcursor_init1(mc, leaf);
2788 if ((rc = mdb_read_data(mc->mc_txn, leaf, data) != MDB_SUCCESS))
2791 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2792 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
2793 if (rc != MDB_SUCCESS)
2798 MDB_SET_KEY(leaf, key);
2803 mdb_cursor_prev(MDB_cursor *mc, MDB_val *key, MDB_val *data, MDB_cursor_op op)
2809 assert(mc->mc_flags & C_INITIALIZED);
2811 mp = mc->mc_pg[mc->mc_top];
2813 if (mc->mc_db->md_flags & MDB_DUPSORT) {
2814 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
2815 if (op == MDB_PREV || op == MDB_PREV_DUP) {
2816 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2817 rc = mdb_cursor_prev(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
2818 if (op != MDB_PREV || rc == MDB_SUCCESS)
2821 mc->mc_xcursor->mx_cursor.mc_flags = 0;
2822 if (op == MDB_PREV_DUP)
2823 return MDB_NOTFOUND;
2828 DPRINTF("cursor_prev: top page is %zu in cursor %p", mp->mp_pgno, (void *) mc);
2830 if (mc->mc_ki[mc->mc_top] == 0) {
2831 DPUTS("=====> move to prev sibling page");
2832 if (mdb_sibling(mc, 0) != MDB_SUCCESS) {
2833 mc->mc_flags &= ~C_INITIALIZED;
2834 return MDB_NOTFOUND;
2836 mp = mc->mc_pg[mc->mc_top];
2837 mc->mc_ki[mc->mc_top] = NUMKEYS(mp) - 1;
2838 DPRINTF("prev page is %zu, key index %u", mp->mp_pgno, mc->mc_ki[mc->mc_top]);
2840 mc->mc_ki[mc->mc_top]--;
2842 mc->mc_flags &= ~C_EOF;
2844 DPRINTF("==> cursor points to page %zu with %u keys, key index %u",
2845 mp->mp_pgno, NUMKEYS(mp), mc->mc_ki[mc->mc_top]);
2848 key->mv_size = mc->mc_db->md_pad;
2849 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
2853 assert(IS_LEAF(mp));
2854 leaf = NODEPTR(mp, mc->mc_ki[mc->mc_top]);
2856 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2857 mdb_xcursor_init1(mc, leaf);
2860 if ((rc = mdb_read_data(mc->mc_txn, leaf, data) != MDB_SUCCESS))
2863 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2864 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
2865 if (rc != MDB_SUCCESS)
2870 MDB_SET_KEY(leaf, key);
2875 mdb_cursor_set(MDB_cursor *mc, MDB_val *key, MDB_val *data,
2876 MDB_cursor_op op, int *exactp)
2885 assert(key->mv_size > 0);
2887 /* See if we're already on the right page */
2888 if (mc->mc_flags & C_INITIALIZED) {
2891 mp = mc->mc_pg[mc->mc_top];
2892 if (mp->mp_flags & P_LEAF2) {
2893 nodekey.mv_size = mc->mc_db->md_pad;
2894 nodekey.mv_data = LEAF2KEY(mp, 0, nodekey.mv_size);
2896 leaf = NODEPTR(mp, 0);
2897 MDB_SET_KEY(leaf, &nodekey);
2899 rc = mc->mc_dbx->md_cmp(key, &nodekey);
2901 /* Probably happens rarely, but first node on the page
2902 * was the one we wanted.
2904 mc->mc_ki[mc->mc_top] = 0;
2905 leaf = NODEPTR(mp, 0);
2912 unsigned int nkeys = NUMKEYS(mp);
2914 if (mp->mp_flags & P_LEAF2) {
2915 nodekey.mv_data = LEAF2KEY(mp,
2916 nkeys-1, nodekey.mv_size);
2918 leaf = NODEPTR(mp, nkeys-1);
2919 MDB_SET_KEY(leaf, &nodekey);
2921 rc = mc->mc_dbx->md_cmp(key, &nodekey);
2923 /* last node was the one we wanted */
2924 mc->mc_ki[mc->mc_top] = nkeys-1;
2925 leaf = NODEPTR(mp, nkeys-1);
2931 /* This is definitely the right page, skip search_page */
2936 /* If any parents have right-sibs, search.
2937 * Otherwise, there's nothing further.
2939 for (i=0; i<mc->mc_top; i++)
2941 NUMKEYS(mc->mc_pg[i])-1)
2943 if (i == mc->mc_top) {
2944 /* There are no other pages */
2945 mc->mc_ki[mc->mc_top] = nkeys;
2946 return MDB_NOTFOUND;
2951 rc = mdb_search_page(mc, key, 0);
2952 if (rc != MDB_SUCCESS)
2955 mp = mc->mc_pg[mc->mc_top];
2956 assert(IS_LEAF(mp));
2959 leaf = mdb_search_node(mc, key, exactp);
2960 if (exactp != NULL && !*exactp) {
2961 /* MDB_SET specified and not an exact match. */
2962 return MDB_NOTFOUND;
2966 DPUTS("===> inexact leaf not found, goto sibling");
2967 if ((rc = mdb_sibling(mc, 1)) != MDB_SUCCESS)
2968 return rc; /* no entries matched */
2969 mp = mc->mc_pg[mc->mc_top];
2970 assert(IS_LEAF(mp));
2971 leaf = NODEPTR(mp, 0);
2975 mc->mc_flags |= C_INITIALIZED;
2976 mc->mc_flags &= ~C_EOF;
2979 key->mv_size = mc->mc_db->md_pad;
2980 key->mv_data = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], key->mv_size);
2984 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2985 mdb_xcursor_init1(mc, leaf);
2988 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2989 if (op == MDB_SET || op == MDB_SET_RANGE) {
2990 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
2993 if (op == MDB_GET_BOTH) {
2999 rc = mdb_cursor_set(&mc->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
3000 if (rc != MDB_SUCCESS)
3003 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
3005 if ((rc = mdb_read_data(mc->mc_txn, leaf, &d2)) != MDB_SUCCESS)
3007 rc = mc->mc_dbx->md_dcmp(data, &d2);
3009 if (op == MDB_GET_BOTH || rc > 0)
3010 return MDB_NOTFOUND;
3015 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3016 if ((rc = mdb_read_data(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3021 /* The key already matches in all other cases */
3022 if (op == MDB_SET_RANGE)
3023 MDB_SET_KEY(leaf, key);
3024 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
3030 mdb_cursor_first(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3035 rc = mdb_search_page(mc, NULL, 0);
3036 if (rc != MDB_SUCCESS)
3038 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3040 leaf = NODEPTR(mc->mc_pg[mc->mc_top], 0);
3041 mc->mc_flags |= C_INITIALIZED;
3042 mc->mc_flags &= ~C_EOF;
3044 mc->mc_ki[mc->mc_top] = 0;
3046 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3047 key->mv_size = mc->mc_db->md_pad;
3048 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], 0, key->mv_size);
3053 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3054 mdb_xcursor_init1(mc, leaf);
3055 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3060 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3061 if ((rc = mdb_read_data(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3065 MDB_SET_KEY(leaf, key);
3070 mdb_cursor_last(MDB_cursor *mc, MDB_val *key, MDB_val *data)
3076 lkey.mv_size = MAXKEYSIZE+1;
3077 lkey.mv_data = NULL;
3079 rc = mdb_search_page(mc, &lkey, 0);
3080 if (rc != MDB_SUCCESS)
3082 assert(IS_LEAF(mc->mc_pg[mc->mc_top]));
3084 leaf = NODEPTR(mc->mc_pg[mc->mc_top], NUMKEYS(mc->mc_pg[mc->mc_top])-1);
3085 mc->mc_flags |= C_INITIALIZED;
3086 mc->mc_flags &= ~C_EOF;
3088 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]) - 1;
3090 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3091 key->mv_size = mc->mc_db->md_pad;
3092 key->mv_data = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], key->mv_size);
3097 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3098 mdb_xcursor_init1(mc, leaf);
3099 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3104 mc->mc_xcursor->mx_cursor.mc_flags = 0;
3105 if ((rc = mdb_read_data(mc->mc_txn, leaf, data)) != MDB_SUCCESS)
3110 MDB_SET_KEY(leaf, key);
3115 mdb_cursor_get(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3125 case MDB_GET_BOTH_RANGE:
3126 if (data == NULL || mc->mc_xcursor == NULL) {
3133 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3135 } else if (op == MDB_SET_RANGE)
3136 rc = mdb_cursor_set(mc, key, data, op, NULL);
3138 rc = mdb_cursor_set(mc, key, data, op, &exact);
3140 case MDB_GET_MULTIPLE:
3142 !(mc->mc_db->md_flags & MDB_DUPFIXED) ||
3143 !(mc->mc_flags & C_INITIALIZED)) {
3148 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
3149 (mc->mc_xcursor->mx_cursor.mc_flags & C_EOF))
3152 case MDB_NEXT_MULTIPLE:
3154 !(mc->mc_db->md_flags & MDB_DUPFIXED)) {
3158 if (!(mc->mc_flags & C_INITIALIZED))
3159 rc = mdb_cursor_first(mc, key, data);
3161 rc = mdb_cursor_next(mc, key, data, MDB_NEXT_DUP);
3162 if (rc == MDB_SUCCESS) {
3163 if (mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
3166 mx = &mc->mc_xcursor->mx_cursor;
3167 data->mv_size = NUMKEYS(mx->mc_pg[mx->mc_top]) *
3169 data->mv_data = METADATA(mx->mc_pg[mx->mc_top]);
3170 mx->mc_ki[mx->mc_top] = NUMKEYS(mx->mc_pg[mx->mc_top])-1;
3178 case MDB_NEXT_NODUP:
3179 if (!(mc->mc_flags & C_INITIALIZED))
3180 rc = mdb_cursor_first(mc, key, data);
3182 rc = mdb_cursor_next(mc, key, data, op);
3186 case MDB_PREV_NODUP:
3187 if (!(mc->mc_flags & C_INITIALIZED) || (mc->mc_flags & C_EOF))
3188 rc = mdb_cursor_last(mc, key, data);
3190 rc = mdb_cursor_prev(mc, key, data, op);
3193 rc = mdb_cursor_first(mc, key, data);
3197 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
3198 !(mc->mc_flags & C_INITIALIZED) ||
3199 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3203 rc = mdb_cursor_first(&mc->mc_xcursor->mx_cursor, data, NULL);
3206 rc = mdb_cursor_last(mc, key, data);
3210 !(mc->mc_db->md_flags & MDB_DUPSORT) ||
3211 !(mc->mc_flags & C_INITIALIZED) ||
3212 !(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
3216 rc = mdb_cursor_last(&mc->mc_xcursor->mx_cursor, data, NULL);
3219 DPRINTF("unhandled/unimplemented cursor operation %u", op);
3228 mdb_cursor_touch(MDB_cursor *mc)
3232 if (mc->mc_dbi > MAIN_DBI && !mc->mc_dbx->md_dirty) {
3234 mdb_cursor_init(&mc2, mc->mc_txn, MAIN_DBI, NULL);
3235 rc = mdb_search_page(&mc2, &mc->mc_dbx->md_name, 1);
3238 mc->mc_dbx->md_dirty = 1;
3240 for (mc->mc_top = 0; mc->mc_top < mc->mc_snum; mc->mc_top++) {
3241 if (!F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY)) {
3246 mc->mc_db->md_root =
3247 mc->mc_pg[mc->mc_top]->mp_pgno;
3251 mc->mc_top = mc->mc_snum-1;
3256 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
3260 MDB_val xdata, *rdata, dkey;
3262 char dbuf[PAGESIZE];
3268 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
3271 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
3272 mc->mc_dbi, DKEY(key), key->mv_size, data->mv_size);
3276 if (flags == MDB_CURRENT) {
3277 if (!(mc->mc_flags & C_INITIALIZED))
3280 } else if (mc->mc_db->md_root == P_INVALID) {
3282 /* new database, write a root leaf page */
3283 DPUTS("allocating new root leaf page");
3284 if ((np = mdb_new_page(mc, P_LEAF, 1)) == NULL) {
3288 cursor_push_page(mc, np);
3289 mc->mc_db->md_root = np->mp_pgno;
3290 mc->mc_db->md_depth++;
3291 mc->mc_dbx->md_dirty = 1;
3292 if ((mc->mc_db->md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
3294 np->mp_flags |= P_LEAF2;
3295 mc->mc_flags |= C_INITIALIZED;
3301 rc = mdb_cursor_set(mc, key, &d2, MDB_SET, &exact);
3302 if (flags == MDB_NOOVERWRITE && rc == 0) {
3303 DPRINTF("duplicate key [%s]", DKEY(key));
3305 return MDB_KEYEXIST;
3307 if (rc && rc != MDB_NOTFOUND)
3311 /* Cursor is positioned, now make sure all pages are writable */
3312 rc2 = mdb_cursor_touch(mc);
3317 /* The key already exists */
3318 if (rc == MDB_SUCCESS) {
3319 /* there's only a key anyway, so this is a no-op */
3320 if (IS_LEAF2(mc->mc_pg[mc->mc_top])) {
3321 unsigned int ksize = mc->mc_db->md_pad;
3322 if (key->mv_size != ksize)
3324 if (flags == MDB_CURRENT) {
3325 char *ptr = LEAF2KEY(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], ksize);
3326 memcpy(ptr, key->mv_data, ksize);
3331 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3334 if (F_ISSET(mc->mc_db->md_flags, MDB_DUPSORT)) {
3335 /* Was a single item before, must convert now */
3336 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3337 dkey.mv_size = NODEDSZ(leaf);
3338 dkey.mv_data = dbuf;
3339 memcpy(dbuf, NODEDATA(leaf), dkey.mv_size);
3340 /* data matches, ignore it */
3341 if (!mc->mc_dbx->md_dcmp(data, &dkey))
3342 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
3343 memset(&dummy, 0, sizeof(dummy));
3344 if (mc->mc_db->md_flags & MDB_DUPFIXED) {
3345 dummy.md_pad = data->mv_size;
3346 dummy.md_flags = MDB_DUPFIXED;
3347 if (mc->mc_db->md_flags & MDB_INTEGERDUP)
3348 dummy.md_flags |= MDB_INTEGERKEY;
3350 dummy.md_flags |= MDB_SUBDATA;
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.
3406 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3408 if (flags != MDB_CURRENT)
3409 mdb_xcursor_init1(mc, leaf);
3412 if (flags == MDB_NODUPDATA)
3413 flags = MDB_NOOVERWRITE;
3414 /* converted, write the original data first */
3416 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 db = NODEDATA(leaf);
3423 assert((db->md_flags & MDB_SUBDATA) == MDB_SUBDATA);
3424 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
3426 mc->mc_db->md_entries++;
3433 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
3438 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
3441 if (!mc->mc_flags & C_INITIALIZED)
3444 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 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
3453 /* If sub-DB still has entries, we're done */
3454 if (mc->mc_xcursor->mx_db.md_root != P_INVALID) {
3455 MDB_db *db = NODEDATA(leaf);
3456 assert((db->md_flags & MDB_SUBDATA) == MDB_SUBDATA);
3457 memcpy(db, &mc->mc_xcursor->mx_db, sizeof(MDB_db));
3458 mc->mc_db->md_entries--;
3461 /* otherwise fall thru and delete the sub-DB */
3464 /* add all the child DB's pages to the free list */
3465 rc = mdb_search_page(&mc->mc_xcursor->mx_cursor, NULL, 0);
3466 if (rc == MDB_SUCCESS) {
3471 mx = &mc->mc_xcursor->mx_cursor;
3472 mc->mc_db->md_entries -=
3473 mx->mc_db->md_entries;
3475 cursor_pop_page(mx);
3476 while (mx->mc_snum > 1) {
3477 for (i=0; i<NUMKEYS(mx->mc_pg[mx->mc_top]); i++) {
3480 ni = NODEPTR(mx->mc_pg[mx->mc_top], i);
3482 if ((rc = mdb_get_page(mc->mc_txn, pg, &mp)))
3485 mdb_midl_append(mc->mc_txn->mt_free_pgs, pg);
3487 rc = mdb_sibling(mx, 1);
3492 mdb_midl_append(mc->mc_txn->mt_free_pgs,
3493 mx->mc_db->md_root);
3497 return mdb_del0(mc, leaf);
3500 /* Allocate a page and initialize it
3503 mdb_new_page(MDB_cursor *mc, uint32_t flags, int num)
3507 if ((np = mdb_alloc_page(mc, num)) == NULL)
3509 DPRINTF("allocated new mpage %zu, page size %u",
3510 np->mp_pgno, mc->mc_txn->mt_env->me_psize);
3511 np->mp_flags = flags | P_DIRTY;
3512 np->mp_lower = PAGEHDRSZ;
3513 np->mp_upper = mc->mc_txn->mt_env->me_psize;
3516 mc->mc_db->md_branch_pages++;
3517 else if (IS_LEAF(np))
3518 mc->mc_db->md_leaf_pages++;
3519 else if (IS_OVERFLOW(np)) {
3520 mc->mc_db->md_overflow_pages += num;
3528 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
3532 sz = LEAFSIZE(key, data);
3533 if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
3534 /* put on overflow page */
3535 sz -= data->mv_size - sizeof(pgno_t);
3539 return sz + sizeof(indx_t);
3543 mdb_branch_size(MDB_env *env, MDB_val *key)
3548 if (sz >= env->me_psize / MDB_MINKEYS) {
3549 /* put on overflow page */
3550 /* not implemented */
3551 /* sz -= key->size - sizeof(pgno_t); */
3554 return sz + sizeof(indx_t);
3558 mdb_add_node(MDB_cursor *mc, indx_t indx,
3559 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags)
3562 size_t node_size = NODESIZE;
3565 MDB_page *mp = mc->mc_pg[mc->mc_top];
3566 MDB_page *ofp = NULL; /* overflow page */
3569 assert(mp->mp_upper >= mp->mp_lower);
3571 DPRINTF("add to %s page %zu index %i, data size %zu key size %zu [%s]",
3572 IS_LEAF(mp) ? "leaf" : "branch",
3573 mp->mp_pgno, indx, data ? data->mv_size : 0,
3574 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
3577 /* Move higher keys up one slot. */
3578 int ksize = mc->mc_db->md_pad, dif;
3579 char *ptr = LEAF2KEY(mp, indx, ksize);
3580 dif = NUMKEYS(mp) - indx;
3582 memmove(ptr+ksize, ptr, dif*ksize);
3583 /* insert new key */
3584 memcpy(ptr, key->mv_data, ksize);
3586 /* Just using these for counting */
3587 mp->mp_lower += sizeof(indx_t);
3588 mp->mp_upper -= ksize - sizeof(indx_t);
3593 node_size += key->mv_size;
3597 if (F_ISSET(flags, F_BIGDATA)) {
3598 /* Data already on overflow page. */
3599 node_size += sizeof(pgno_t);
3600 } else if (data->mv_size >= mc->mc_txn->mt_env->me_psize / MDB_MINKEYS) {
3601 int ovpages = OVPAGES(data->mv_size, mc->mc_txn->mt_env->me_psize);
3602 /* Put data on overflow page. */
3603 DPRINTF("data size is %zu, put on overflow page",
3605 node_size += sizeof(pgno_t);
3606 if ((ofp = mdb_new_page(mc, P_OVERFLOW, ovpages)) == NULL)
3608 DPRINTF("allocated overflow page %zu", ofp->mp_pgno);
3611 node_size += data->mv_size;
3614 node_size += node_size & 1;
3616 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
3617 DPRINTF("not enough room in page %zu, got %u ptrs",
3618 mp->mp_pgno, NUMKEYS(mp));
3619 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
3620 mp->mp_upper - mp->mp_lower);
3621 DPRINTF("node size = %zu", node_size);
3625 /* Move higher pointers up one slot. */
3626 for (i = NUMKEYS(mp); i > indx; i--)
3627 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
3629 /* Adjust free space offsets. */
3630 ofs = mp->mp_upper - node_size;
3631 assert(ofs >= mp->mp_lower + sizeof(indx_t));
3632 mp->mp_ptrs[indx] = ofs;
3634 mp->mp_lower += sizeof(indx_t);
3636 /* Write the node data. */
3637 node = NODEPTR(mp, indx);
3638 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
3639 node->mn_flags = flags;
3641 SETDSZ(node,data->mv_size);
3646 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
3651 if (F_ISSET(flags, F_BIGDATA))
3652 memcpy(node->mn_data + key->mv_size, data->mv_data,
3655 memcpy(node->mn_data + key->mv_size, data->mv_data,
3658 memcpy(node->mn_data + key->mv_size, &ofp->mp_pgno,
3660 memcpy(METADATA(ofp), data->mv_data, data->mv_size);
3668 mdb_del_node(MDB_page *mp, indx_t indx, int ksize)
3671 indx_t i, j, numkeys, ptr;
3675 DPRINTF("delete node %u on %s page %zu", indx,
3676 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
3677 assert(indx < NUMKEYS(mp));
3680 int x = NUMKEYS(mp) - 1 - indx;
3681 base = LEAF2KEY(mp, indx, ksize);
3683 memmove(base, base + ksize, x * ksize);
3684 mp->mp_lower -= sizeof(indx_t);
3685 mp->mp_upper += ksize - sizeof(indx_t);
3689 node = NODEPTR(mp, indx);
3690 sz = NODESIZE + node->mn_ksize;
3692 if (F_ISSET(node->mn_flags, F_BIGDATA))
3693 sz += sizeof(pgno_t);
3695 sz += NODEDSZ(node);
3699 ptr = mp->mp_ptrs[indx];
3700 numkeys = NUMKEYS(mp);
3701 for (i = j = 0; i < numkeys; i++) {
3703 mp->mp_ptrs[j] = mp->mp_ptrs[i];
3704 if (mp->mp_ptrs[i] < ptr)
3705 mp->mp_ptrs[j] += sz;
3710 base = (char *)mp + mp->mp_upper;
3711 memmove(base + sz, base, ptr - mp->mp_upper);
3713 mp->mp_lower -= sizeof(indx_t);
3718 mdb_xcursor_init0(MDB_cursor *mc)
3720 MDB_xcursor *mx = mc->mc_xcursor;
3722 mx->mx_cursor.mc_xcursor = NULL;
3723 mx->mx_cursor.mc_txn = mc->mc_txn;
3724 mx->mx_cursor.mc_db = &mx->mx_db;
3725 mx->mx_cursor.mc_dbx = &mx->mx_dbx;
3726 mx->mx_cursor.mc_dbi = mc->mc_dbi+1;
3727 mx->mx_dbx.md_parent = mc->mc_dbi;
3728 mx->mx_dbx.md_cmp = mc->mc_dbx->md_dcmp;
3729 mx->mx_dbx.md_dcmp = NULL;
3730 mx->mx_dbx.md_rel = mc->mc_dbx->md_rel;
3731 mx->mx_dbx.md_dirty = 0;
3735 mdb_xcursor_init1(MDB_cursor *mc, MDB_node *node)
3737 MDB_db *db = NODEDATA(node);
3738 MDB_xcursor *mx = mc->mc_xcursor;
3739 assert((db->md_flags & MDB_SUBDATA) == MDB_SUBDATA);
3741 DPRINTF("Sub-db %u for db %u root page %zu", mx->mx_cursor.mc_dbi, mc->mc_dbi,
3743 if (F_ISSET(mc->mc_pg[mc->mc_top]->mp_flags, P_DIRTY))
3744 mx->mx_dbx.md_dirty = 1;
3745 mx->mx_dbx.md_name.mv_data = NODEKEY(node);
3746 mx->mx_dbx.md_name.mv_size = node->mn_ksize;
3747 mx->mx_cursor.mc_snum = 0;
3748 mx->mx_cursor.mc_flags = 0;
3749 if (mx->mx_dbx.md_cmp == intcmp && mx->mx_db.md_pad == sizeof(size_t))
3750 mx->mx_dbx.md_cmp = longcmp;
3754 mdb_cursor_init(MDB_cursor *mc, MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
3758 mc->mc_db = &txn->mt_dbs[dbi];
3759 mc->mc_dbx = &txn->mt_dbxs[dbi];
3762 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
3764 mc->mc_xcursor = mx;
3765 mdb_xcursor_init0(mc);
3767 mc->mc_xcursor = NULL;
3772 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
3775 MDB_xcursor *mx = NULL;
3776 size_t size = sizeof(MDB_cursor);
3778 if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
3781 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
3782 size += sizeof(MDB_xcursor);
3784 if ((mc = malloc(size)) != NULL) {
3785 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
3786 mx = (MDB_xcursor *)(mc + 1);
3788 mdb_cursor_init(mc, txn, dbi, mx);
3798 /* Return the count of duplicate data items for the current key */
3800 mdb_cursor_count(MDB_cursor *mc, size_t *countp)
3804 if (mc == NULL || countp == NULL)
3807 if (!(mc->mc_db->md_flags & MDB_DUPSORT))
3810 leaf = NODEPTR(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top]);
3811 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3814 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
3817 *countp = mc->mc_xcursor->mx_db.md_entries;
3823 mdb_cursor_close(MDB_cursor *mc)
3831 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
3833 indx_t ptr, i, numkeys;
3840 node = NODEPTR(mp, indx);
3841 ptr = mp->mp_ptrs[indx];
3842 DPRINTF("update key %u (ofs %u) [%.*s] to [%s] on page %zu",
3844 (int)node->mn_ksize, (char *)NODEKEY(node),
3848 delta = key->mv_size - node->mn_ksize;
3850 if (delta > 0 && SIZELEFT(mp) < delta) {
3851 DPRINTF("OUCH! Not enough room, delta = %d", delta);
3855 numkeys = NUMKEYS(mp);
3856 for (i = 0; i < numkeys; i++) {
3857 if (mp->mp_ptrs[i] <= ptr)
3858 mp->mp_ptrs[i] -= delta;
3861 base = (char *)mp + mp->mp_upper;
3862 len = ptr - mp->mp_upper + NODESIZE;
3863 memmove(base - delta, base, len);
3864 mp->mp_upper -= delta;
3866 node = NODEPTR(mp, indx);
3867 node->mn_ksize = key->mv_size;
3870 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
3875 /* Move a node from csrc to cdst.
3878 mdb_move_node(MDB_cursor *csrc, MDB_cursor *cdst)
3885 /* Mark src and dst as dirty. */
3886 if ((rc = mdb_touch(csrc)) ||
3887 (rc = mdb_touch(cdst)))
3890 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
3891 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0); /* fake */
3892 key.mv_size = csrc->mc_db->md_pad;
3893 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
3895 data.mv_data = NULL;
3897 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top]);
3898 if (csrc->mc_ki[csrc->mc_top] == 0 && IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
3899 unsigned int snum = csrc->mc_snum;
3901 /* must find the lowest key below src */
3902 mdb_search_page_root(csrc, NULL, 0);
3903 s2 = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
3904 key.mv_size = NODEKSZ(s2);
3905 key.mv_data = NODEKEY(s2);
3906 csrc->mc_snum = snum--;
3907 csrc->mc_top = snum;
3909 key.mv_size = NODEKSZ(srcnode);
3910 key.mv_data = NODEKEY(srcnode);
3912 data.mv_size = NODEDSZ(srcnode);
3913 data.mv_data = NODEDATA(srcnode);
3915 DPRINTF("moving %s node %u [%s] on page %zu to node %u on page %zu",
3916 IS_LEAF(csrc->mc_pg[csrc->mc_top]) ? "leaf" : "branch",
3917 csrc->mc_ki[csrc->mc_top],
3919 csrc->mc_pg[csrc->mc_top]->mp_pgno,
3920 cdst->mc_ki[cdst->mc_top], cdst->mc_pg[cdst->mc_top]->mp_pgno);
3922 /* Add the node to the destination page.
3924 rc = mdb_add_node(cdst, cdst->mc_ki[cdst->mc_top], &key, &data, NODEPGNO(srcnode),
3926 if (rc != MDB_SUCCESS)
3929 /* Delete the node from the source page.
3931 mdb_del_node(csrc->mc_pg[csrc->mc_top], csrc->mc_ki[csrc->mc_top], key.mv_size);
3933 /* Update the parent separators.
3935 if (csrc->mc_ki[csrc->mc_top] == 0) {
3936 if (csrc->mc_ki[csrc->mc_top-1] != 0) {
3937 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
3938 key.mv_data = LEAF2KEY(csrc->mc_pg[csrc->mc_top], 0, key.mv_size);
3940 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], 0);
3941 key.mv_size = NODEKSZ(srcnode);
3942 key.mv_data = NODEKEY(srcnode);
3944 DPRINTF("update separator for source page %zu to [%s]",
3945 csrc->mc_pg[csrc->mc_top]->mp_pgno, DKEY(&key));
3946 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1],
3947 &key)) != MDB_SUCCESS)
3950 if (IS_BRANCH(csrc->mc_pg[csrc->mc_top])) {
3952 nullkey.mv_size = 0;
3953 assert(mdb_update_key(csrc->mc_pg[csrc->mc_top], 0, &nullkey) == MDB_SUCCESS);
3957 if (cdst->mc_ki[cdst->mc_top] == 0) {
3958 if (cdst->mc_ki[cdst->mc_top-1] != 0) {
3959 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
3960 key.mv_data = LEAF2KEY(cdst->mc_pg[cdst->mc_top], 0, key.mv_size);
3962 srcnode = NODEPTR(cdst->mc_pg[cdst->mc_top], 0);
3963 key.mv_size = NODEKSZ(srcnode);
3964 key.mv_data = NODEKEY(srcnode);
3966 DPRINTF("update separator for destination page %zu to [%s]",
3967 cdst->mc_pg[cdst->mc_top]->mp_pgno, DKEY(&key));
3968 if ((rc = mdb_update_key(cdst->mc_pg[cdst->mc_top-1], cdst->mc_ki[cdst->mc_top-1],
3969 &key)) != MDB_SUCCESS)
3972 if (IS_BRANCH(cdst->mc_pg[cdst->mc_top])) {
3974 nullkey.mv_size = 0;
3975 assert(mdb_update_key(cdst->mc_pg[cdst->mc_top], 0, &nullkey) == MDB_SUCCESS);
3983 mdb_merge(MDB_cursor *csrc, MDB_cursor *cdst)
3990 DPRINTF("merging page %zu into %zu", csrc->mc_pg[csrc->mc_top]->mp_pgno,
3991 cdst->mc_pg[cdst->mc_top]->mp_pgno);
3993 assert(csrc->mc_snum > 1); /* can't merge root page */
3994 assert(cdst->mc_snum > 1);
3996 /* Mark dst as dirty. */
3997 if ((rc = mdb_touch(cdst)))
4000 /* Move all nodes from src to dst.
4002 j = NUMKEYS(cdst->mc_pg[cdst->mc_top]);
4003 if (IS_LEAF2(csrc->mc_pg[csrc->mc_top])) {
4004 key.mv_size = csrc->mc_db->md_pad;
4005 key.mv_data = METADATA(csrc->mc_pg[csrc->mc_top]);
4006 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
4007 rc = mdb_add_node(cdst, j, &key, NULL, 0, 0);
4008 if (rc != MDB_SUCCESS)
4010 key.mv_data = (char *)key.mv_data + key.mv_size;
4013 for (i = 0; i < NUMKEYS(csrc->mc_pg[csrc->mc_top]); i++, j++) {
4014 srcnode = NODEPTR(csrc->mc_pg[csrc->mc_top], i);
4016 key.mv_size = srcnode->mn_ksize;
4017 key.mv_data = NODEKEY(srcnode);
4018 data.mv_size = NODEDSZ(srcnode);
4019 data.mv_data = NODEDATA(srcnode);
4020 rc = mdb_add_node(cdst, j, &key, &data, NODEPGNO(srcnode), srcnode->mn_flags);
4021 if (rc != MDB_SUCCESS)
4026 DPRINTF("dst page %zu now has %u keys (%.1f%% filled)",
4027 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);
4029 /* Unlink the src page from parent and add to free list.
4031 mdb_del_node(csrc->mc_pg[csrc->mc_top-1], csrc->mc_ki[csrc->mc_top-1], 0);
4032 if (csrc->mc_ki[csrc->mc_top-1] == 0) {
4034 if ((rc = mdb_update_key(csrc->mc_pg[csrc->mc_top-1], 0, &key)) != MDB_SUCCESS)
4038 mdb_midl_append(csrc->mc_txn->mt_free_pgs, csrc->mc_pg[csrc->mc_top]->mp_pgno);
4039 if (IS_LEAF(csrc->mc_pg[csrc->mc_top]))
4040 csrc->mc_db->md_leaf_pages--;
4042 csrc->mc_db->md_branch_pages--;
4043 cursor_pop_page(csrc);
4045 return mdb_rebalance(csrc);
4049 mdb_cursor_copy(const MDB_cursor *csrc, MDB_cursor *cdst)
4053 cdst->mc_txn = csrc->mc_txn;
4054 cdst->mc_dbi = csrc->mc_dbi;
4055 cdst->mc_db = csrc->mc_db;
4056 cdst->mc_dbx = csrc->mc_dbx;
4057 cdst->mc_snum = csrc->mc_snum;
4058 cdst->mc_top = csrc->mc_top;
4059 cdst->mc_flags = csrc->mc_flags;
4061 for (i=0; i<csrc->mc_snum; i++) {
4062 cdst->mc_pg[i] = csrc->mc_pg[i];
4063 cdst->mc_ki[i] = csrc->mc_ki[i];
4068 mdb_rebalance(MDB_cursor *mc)
4075 DPRINTF("rebalancing %s page %zu (has %u keys, %.1f%% full)",
4076 IS_LEAF(mc->mc_pg[mc->mc_top]) ? "leaf" : "branch",
4077 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);
4079 if (PAGEFILL(mc->mc_txn->mt_env, mc->mc_pg[mc->mc_top]) >= FILL_THRESHOLD) {
4080 DPRINTF("no need to rebalance page %zu, above fill threshold",
4081 mc->mc_pg[mc->mc_top]->mp_pgno);
4085 if (mc->mc_snum < 2) {
4086 if (NUMKEYS(mc->mc_pg[mc->mc_top]) == 0) {
4087 DPUTS("tree is completely empty");
4088 mc->mc_db->md_root = P_INVALID;
4089 mc->mc_db->md_depth = 0;
4090 mc->mc_db->md_leaf_pages = 0;
4091 mdb_midl_append(mc->mc_txn->mt_free_pgs, mc->mc_pg[mc->mc_top]->mp_pgno);
4093 } else if (IS_BRANCH(mc->mc_pg[mc->mc_top]) && NUMKEYS(mc->mc_pg[mc->mc_top]) == 1) {
4094 DPUTS("collapsing root page!");
4095 mdb_midl_append(mc->mc_txn->mt_free_pgs, mc->mc_pg[mc->mc_top]->mp_pgno);
4096 mc->mc_db->md_root = NODEPGNO(NODEPTR(mc->mc_pg[mc->mc_top], 0));
4097 if ((rc = mdb_get_page(mc->mc_txn, mc->mc_db->md_root,
4098 &mc->mc_pg[mc->mc_top])))
4100 mc->mc_db->md_depth--;
4101 mc->mc_db->md_branch_pages--;
4103 DPUTS("root page doesn't need rebalancing");
4107 /* The parent (branch page) must have at least 2 pointers,
4108 * otherwise the tree is invalid.
4110 ptop = mc->mc_top-1;
4111 assert(NUMKEYS(mc->mc_pg[ptop]) > 1);
4113 /* Leaf page fill factor is below the threshold.
4114 * Try to move keys from left or right neighbor, or
4115 * merge with a neighbor page.
4120 mdb_cursor_copy(mc, &mn);
4121 mn.mc_xcursor = NULL;
4123 if (mc->mc_ki[ptop] == 0) {
4124 /* We're the leftmost leaf in our parent.
4126 DPUTS("reading right neighbor");
4128 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
4129 if ((rc = mdb_get_page(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
4131 mn.mc_ki[mn.mc_top] = 0;
4132 mc->mc_ki[mc->mc_top] = NUMKEYS(mc->mc_pg[mc->mc_top]);
4134 /* There is at least one neighbor to the left.
4136 DPUTS("reading left neighbor");
4138 node = NODEPTR(mc->mc_pg[ptop], mn.mc_ki[ptop]);
4139 if ((rc = mdb_get_page(mc->mc_txn, NODEPGNO(node), &mn.mc_pg[mn.mc_top])))
4141 mn.mc_ki[mn.mc_top] = NUMKEYS(mn.mc_pg[mn.mc_top]) - 1;
4142 mc->mc_ki[mc->mc_top] = 0;
4145 DPRINTF("found neighbor page %zu (%u keys, %.1f%% full)",
4146 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);
4148 /* If the neighbor page is above threshold and has at least two
4149 * keys, move one key from it.
4151 * Otherwise we should try to merge them.
4153 if (PAGEFILL(mc->mc_txn->mt_env, mn.mc_pg[mn.mc_top]) >= FILL_THRESHOLD && NUMKEYS(mn.mc_pg[mn.mc_top]) >= 2)
4154 return mdb_move_node(&mn, mc);
4155 else { /* FIXME: if (has_enough_room()) */
4156 if (mc->mc_ki[ptop] == 0)
4157 return mdb_merge(&mn, mc);
4159 return mdb_merge(mc, &mn);
4164 mdb_del0(MDB_cursor *mc, MDB_node *leaf)
4168 /* add overflow pages to free list */
4169 if (!IS_LEAF2(mc->mc_pg[mc->mc_top]) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
4173 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
4174 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
4175 for (i=0; i<ovpages; i++) {
4176 DPRINTF("freed ov page %zu", pg);
4177 mdb_midl_append(mc->mc_txn->mt_free_pgs, pg);
4181 mdb_del_node(mc->mc_pg[mc->mc_top], mc->mc_ki[mc->mc_top], mc->mc_db->md_pad);
4182 mc->mc_db->md_entries--;
4183 rc = mdb_rebalance(mc);
4184 if (rc != MDB_SUCCESS)
4185 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
4191 mdb_del(MDB_txn *txn, MDB_dbi dbi,
4192 MDB_val *key, MDB_val *data)
4197 MDB_val rdata, *xdata;
4201 assert(key != NULL);
4203 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
4205 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4208 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
4212 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
4216 mdb_cursor_init(&mc, txn, dbi, &mx);
4227 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
4229 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
4233 /* Split page <mc->top>, and insert <key,(data|newpgno)> in either left or
4234 * right sibling, at index <mc->ki> (as if unsplit). Updates mc->top and
4235 * mc->ki with the actual values after split, ie if mc->top and mc->ki
4236 * refer to a node in the new right sibling page.
4239 mdb_split(MDB_cursor *mc, MDB_val *newkey, MDB_val *newdata, pgno_t newpgno)
4242 int rc = MDB_SUCCESS, ins_new = 0;
4245 unsigned int i, j, split_indx, nkeys, pmax;
4247 MDB_val sepkey, rkey, rdata;
4249 MDB_page *mp, *rp, *pp;
4254 mp = mc->mc_pg[mc->mc_top];
4255 newindx = mc->mc_ki[mc->mc_top];
4257 DPRINTF("-----> splitting %s page %zu and adding [%s] at index %i",
4258 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno,
4259 DKEY(newkey), mc->mc_ki[mc->mc_top]);
4261 if (mc->mc_snum < 2) {
4262 if ((pp = mdb_new_page(mc, P_BRANCH, 1)) == NULL)
4264 /* shift current top to make room for new parent */
4265 mc->mc_pg[1] = mc->mc_pg[0];
4266 mc->mc_ki[1] = mc->mc_ki[0];
4269 mc->mc_db->md_root = pp->mp_pgno;
4270 DPRINTF("root split! new root = %zu", pp->mp_pgno);
4271 mc->mc_db->md_depth++;
4273 /* Add left (implicit) pointer. */
4274 if ((rc = mdb_add_node(mc, 0, NULL, NULL, mp->mp_pgno, 0)) != MDB_SUCCESS) {
4275 /* undo the pre-push */
4276 mc->mc_pg[0] = mc->mc_pg[1];
4277 mc->mc_ki[0] = mc->mc_ki[1];
4278 mc->mc_db->md_root = mp->mp_pgno;
4279 mc->mc_db->md_depth--;
4286 ptop = mc->mc_top-1;
4287 DPRINTF("parent branch page is %zu", mc->mc_pg[ptop]->mp_pgno);
4290 /* Create a right sibling. */
4291 if ((rp = mdb_new_page(mc, mp->mp_flags, 1)) == NULL)
4293 mdb_cursor_copy(mc, &mn);
4294 mn.mc_pg[mn.mc_top] = rp;
4295 mn.mc_ki[ptop] = mc->mc_ki[ptop]+1;
4296 DPRINTF("new right sibling: page %zu", rp->mp_pgno);
4298 nkeys = NUMKEYS(mp);
4299 split_indx = nkeys / 2 + 1;
4304 unsigned int lsize, rsize, ksize;
4305 /* Move half of the keys to the right sibling */
4307 x = mc->mc_ki[mc->mc_top] - split_indx;
4308 ksize = mc->mc_db->md_pad;
4309 split = LEAF2KEY(mp, split_indx, ksize);
4310 rsize = (nkeys - split_indx) * ksize;
4311 lsize = (nkeys - split_indx) * sizeof(indx_t);
4312 mp->mp_lower -= lsize;
4313 rp->mp_lower += lsize;
4314 mp->mp_upper += rsize - lsize;
4315 rp->mp_upper -= rsize - lsize;
4316 sepkey.mv_size = ksize;
4317 if (newindx == split_indx) {
4318 sepkey.mv_data = newkey->mv_data;
4320 sepkey.mv_data = split;
4323 ins = LEAF2KEY(mp, mc->mc_ki[mc->mc_top], ksize);
4324 memcpy(rp->mp_ptrs, split, rsize);
4325 sepkey.mv_data = rp->mp_ptrs;
4326 memmove(ins+ksize, ins, (split_indx - mc->mc_ki[mc->mc_top]) * ksize);
4327 memcpy(ins, newkey->mv_data, ksize);
4328 mp->mp_lower += sizeof(indx_t);
4329 mp->mp_upper -= ksize - sizeof(indx_t);
4332 memcpy(rp->mp_ptrs, split, x * ksize);
4333 ins = LEAF2KEY(rp, x, ksize);
4334 memcpy(ins, newkey->mv_data, ksize);
4335 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
4336 rp->mp_lower += sizeof(indx_t);
4337 rp->mp_upper -= ksize - sizeof(indx_t);
4338 mc->mc_ki[mc->mc_top] = x;
4339 mc->mc_pg[mc->mc_top] = rp;
4344 /* For leaf pages, check the split point based on what
4345 * fits where, since otherwise add_node can fail.
4348 unsigned int psize, nsize;
4349 /* Maximum free space in an empty page */
4350 pmax = mc->mc_txn->mt_env->me_psize - PAGEHDRSZ;
4351 nsize = mdb_leaf_size(mc->mc_txn->mt_env, newkey, newdata);
4352 if (newindx < split_indx) {
4354 for (i=0; i<split_indx; i++) {
4355 node = NODEPTR(mp, i);
4356 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
4357 if (F_ISSET(node->mn_flags, F_BIGDATA))
4358 psize += sizeof(pgno_t);
4360 psize += NODEDSZ(node);
4369 for (i=nkeys-1; i>=split_indx; i--) {
4370 node = NODEPTR(mp, i);
4371 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
4372 if (F_ISSET(node->mn_flags, F_BIGDATA))
4373 psize += sizeof(pgno_t);
4375 psize += NODEDSZ(node);
4385 /* First find the separating key between the split pages.
4387 if (newindx == split_indx) {
4388 sepkey.mv_size = newkey->mv_size;
4389 sepkey.mv_data = newkey->mv_data;
4391 node = NODEPTR(mp, split_indx);
4392 sepkey.mv_size = node->mn_ksize;
4393 sepkey.mv_data = NODEKEY(node);
4397 DPRINTF("separator is [%s]", DKEY(&sepkey));
4399 /* Copy separator key to the parent.
4401 if (SIZELEFT(mn.mc_pg[ptop]) < mdb_branch_size(mc->mc_txn->mt_env, &sepkey)) {
4404 rc = mdb_split(&mn, &sepkey, NULL, rp->mp_pgno);
4406 /* Right page might now have changed parent.
4407 * Check if left page also changed parent.
4409 if (mn.mc_pg[ptop] != mc->mc_pg[ptop] &&
4410 mc->mc_ki[ptop] >= NUMKEYS(mc->mc_pg[ptop])) {
4411 mc->mc_pg[ptop] = mn.mc_pg[ptop];
4412 mc->mc_ki[ptop] = mn.mc_ki[ptop] - 1;
4416 rc = mdb_add_node(&mn, mn.mc_ki[ptop], &sepkey, NULL, rp->mp_pgno, 0);
4422 if (rc != MDB_SUCCESS) {
4426 /* Move half of the keys to the right sibling. */
4428 /* grab a page to hold a temporary copy */
4429 if (mc->mc_txn->mt_env->me_dpages) {
4430 copy = mc->mc_txn->mt_env->me_dpages;
4431 mc->mc_txn->mt_env->me_dpages = copy->mp_next;
4433 if ((copy = malloc(mc->mc_txn->mt_env->me_psize)) == NULL)
4437 copy->mp_pgno = mp->mp_pgno;
4438 copy->mp_flags = mp->mp_flags;
4439 copy->mp_lower = PAGEHDRSZ;
4440 copy->mp_upper = mc->mc_txn->mt_env->me_psize;
4441 mc->mc_pg[mc->mc_top] = copy;
4442 for (i = j = 0; i <= nkeys; j++) {
4443 if (i == split_indx) {
4444 /* Insert in right sibling. */
4445 /* Reset insert index for right sibling. */
4446 j = (i == newindx && ins_new);
4447 mc->mc_pg[mc->mc_top] = rp;
4450 if (i == newindx && !ins_new) {
4451 /* Insert the original entry that caused the split. */
4452 rkey.mv_data = newkey->mv_data;
4453 rkey.mv_size = newkey->mv_size;
4455 rdata.mv_data = newdata->mv_data;
4456 rdata.mv_size = newdata->mv_size;
4463 /* Update page and index for the new key. */
4464 mc->mc_ki[mc->mc_top] = j;
4465 } else if (i == nkeys) {
4468 node = NODEPTR(mp, i);
4469 rkey.mv_data = NODEKEY(node);
4470 rkey.mv_size = node->mn_ksize;
4472 rdata.mv_data = NODEDATA(node);
4473 rdata.mv_size = NODEDSZ(node);
4475 pgno = NODEPGNO(node);
4476 flags = node->mn_flags;
4481 if (!IS_LEAF(mp) && j == 0) {
4482 /* First branch index doesn't need key data. */
4486 rc = mdb_add_node(mc, j, &rkey, &rdata, pgno, flags);
4489 /* reset back to original page */
4490 if (newindx < split_indx)
4491 mc->mc_pg[mc->mc_top] = mp;
4493 nkeys = NUMKEYS(copy);
4494 for (i=0; i<nkeys; i++)
4495 mp->mp_ptrs[i] = copy->mp_ptrs[i];
4496 mp->mp_lower = copy->mp_lower;
4497 mp->mp_upper = copy->mp_upper;
4498 memcpy(NODEPTR(mp, nkeys-1), NODEPTR(copy, nkeys-1),
4499 mc->mc_txn->mt_env->me_psize - copy->mp_upper);
4501 /* return tmp page to freelist */
4502 copy->mp_next = mc->mc_txn->mt_env->me_dpages;
4503 mc->mc_txn->mt_env->me_dpages = copy;
4508 mdb_put(MDB_txn *txn, MDB_dbi dbi,
4509 MDB_val *key, MDB_val *data, unsigned int flags)
4514 assert(key != NULL);
4515 assert(data != NULL);
4517 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4520 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
4524 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
4528 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA)) != flags)
4531 mdb_cursor_init(&mc, txn, dbi, &mx);
4532 return mdb_cursor_put(&mc, key, data, flags);
4536 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
4538 /** Only a subset of the @ref mdb_env flags can be changed
4539 * at runtime. Changing other flags requires closing the environment
4540 * and re-opening it with the new flags.
4542 #define CHANGEABLE (MDB_NOSYNC)
4543 if ((flag & CHANGEABLE) != flag)
4546 env->me_flags |= flag;
4548 env->me_flags &= ~flag;
4553 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
4558 *arg = env->me_flags;
4563 mdb_env_get_path(MDB_env *env, const char **arg)
4568 *arg = env->me_path;
4573 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
4575 arg->ms_psize = env->me_psize;
4576 arg->ms_depth = db->md_depth;
4577 arg->ms_branch_pages = db->md_branch_pages;
4578 arg->ms_leaf_pages = db->md_leaf_pages;
4579 arg->ms_overflow_pages = db->md_overflow_pages;
4580 arg->ms_entries = db->md_entries;
4585 mdb_env_stat(MDB_env *env, MDB_stat *arg)
4589 if (env == NULL || arg == NULL)
4592 mdb_env_read_meta(env, &toggle);
4594 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
4598 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
4600 if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEKEY)
4601 txn->mt_dbxs[dbi].md_cmp = memnrcmp;
4602 else if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERKEY)
4603 txn->mt_dbxs[dbi].md_cmp = cintcmp;
4605 txn->mt_dbxs[dbi].md_cmp = memncmp;
4607 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4608 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP) {
4609 if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED)
4610 txn->mt_dbxs[dbi].md_dcmp = intcmp;
4612 txn->mt_dbxs[dbi].md_dcmp = cintcmp;
4613 } else if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEDUP) {
4614 txn->mt_dbxs[dbi].md_dcmp = memnrcmp;
4616 txn->mt_dbxs[dbi].md_dcmp = memncmp;
4619 txn->mt_dbxs[dbi].md_dcmp = NULL;
4623 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
4630 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
4631 mdb_default_cmp(txn, FREE_DBI);
4637 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
4638 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
4639 mdb_default_cmp(txn, MAIN_DBI);
4643 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
4644 mdb_default_cmp(txn, MAIN_DBI);
4647 /* Is the DB already open? */
4649 for (i=2; i<txn->mt_numdbs; i++) {
4650 if (len == txn->mt_dbxs[i].md_name.mv_size &&
4651 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
4657 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
4660 /* Find the DB info */
4662 key.mv_data = (void *)name;
4663 rc = mdb_get(txn, MAIN_DBI, &key, &data);
4665 /* Create if requested */
4666 if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
4669 data.mv_size = sizeof(MDB_db);
4670 data.mv_data = &dummy;
4671 memset(&dummy, 0, sizeof(dummy));
4672 dummy.md_root = P_INVALID;
4673 dummy.md_flags = flags & 0xffff;
4674 mdb_cursor_init(&mc, txn, MAIN_DBI, NULL);
4675 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
4679 /* OK, got info, add to table */
4680 if (rc == MDB_SUCCESS) {
4681 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
4682 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
4683 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
4684 txn->mt_dbxs[txn->mt_numdbs].md_parent = MAIN_DBI;
4685 txn->mt_dbxs[txn->mt_numdbs].md_dirty = dirty;
4686 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
4687 *dbi = txn->mt_numdbs;
4688 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
4689 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
4690 mdb_default_cmp(txn, txn->mt_numdbs);
4697 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
4699 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
4702 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
4705 void mdb_close(MDB_txn *txn, MDB_dbi dbi)
4708 if (dbi <= MAIN_DBI || dbi >= txn->mt_numdbs)
4710 ptr = txn->mt_dbxs[dbi].md_name.mv_data;
4711 txn->mt_dbxs[dbi].md_name.mv_data = NULL;
4712 txn->mt_dbxs[dbi].md_name.mv_size = 0;
4716 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
4718 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4721 txn->mt_dbxs[dbi].md_cmp = cmp;
4725 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
4727 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4730 txn->mt_dbxs[dbi].md_dcmp = cmp;
4734 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
4736 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4739 txn->mt_dbxs[dbi].md_rel = rel;
4743 int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx)
4745 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4748 txn->mt_dbxs[dbi].md_relctx = ctx;