1 /* mdb.c - memory-mapped database library */
3 * Copyright 2011 Howard Chu, Symas Corp.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted only as authorized by the OpenLDAP
10 * A copy of this license is available in the file LICENSE in the
11 * top-level directory of the distribution or, alternatively, at
12 * <http://www.OpenLDAP.org/license.html>.
14 * This code is derived from btree.c written by Martin Hedenfalk.
16 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
18 * Permission to use, copy, modify, and distribute this software for any
19 * purpose with or without fee is hereby granted, provided that the above
20 * copyright notice and this permission notice appear in all copies.
22 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
23 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
24 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
25 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
26 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
27 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
28 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
30 #include <sys/types.h>
32 #include <sys/queue.h>
33 #include <sys/param.h>
36 #ifdef HAVE_SYS_FILE_H
55 #define ULONG unsigned long
64 #if DEBUG && defined(__GNUC__)
65 # define DPRINTF(fmt, ...) \
66 fprintf(stderr, "%s:%d: " fmt "\n", __func__, __LINE__, ##__VA_ARGS__)
68 # define DPRINTF(...) ((void) 0)
73 #define MDB_MAGIC 0xBEEFC0DE
75 #define MAXKEYSIZE 511
77 #define P_INVALID (~0UL)
79 #define F_ISSET(w, f) (((w) & (f)) == (f))
81 typedef uint16_t indx_t;
83 #define DEFAULT_READERS 126
84 #define DEFAULT_MAPSIZE 1048576
86 /* Lock descriptor stuff */
91 typedef struct MDB_rxbody {
96 #define CACHELINE 64 /* most CPUs. Itanium uses 128 */
99 typedef struct MDB_reader {
101 /* cache line alignment */
102 char pad[CACHELINE-sizeof(MDB_rxbody)];
107 uint32_t mt_version; \
108 pthread_mutex_t mt_mutex; \
110 uint32_t mt_numreaders
111 typedef struct MDB_txbody {
115 typedef struct MDB_txninfo {
117 char pad[CACHELINE-sizeof(MDB_txbody)];
118 pthread_mutex_t mt_wmutex;
119 char pad2[CACHELINE-sizeof(pthread_mutex_t)];
120 MDB_reader mt_readers[1];
123 /* Common header for all page types. Overflow pages
124 * occupy a number of contiguous pages with no
125 * headers on any page after the first.
127 typedef struct MDB_page { /* represents a page of storage */
128 #define mp_pgno mp_p.p_pgno
130 pgno_t p_pgno; /* page number */
133 #define P_BRANCH 0x01 /* branch page */
134 #define P_LEAF 0x02 /* leaf page */
135 #define P_OVERFLOW 0x04 /* overflow page */
136 #define P_META 0x08 /* meta page */
137 #define P_DIRTY 0x10 /* dirty page */
139 #define mp_lower mp_pb.pb.pb_lower
140 #define mp_upper mp_pb.pb.pb_upper
141 #define mp_pages mp_pb.pb_pages
144 indx_t pb_lower; /* lower bound of free space */
145 indx_t pb_upper; /* upper bound of free space */
147 uint32_t pb_pages; /* number of overflow pages */
149 indx_t mp_ptrs[1]; /* dynamic size */
152 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
154 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
155 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
156 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
157 ((env)->me_psize - PAGEHDRSZ))
158 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
159 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
160 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
162 #define OVPAGES(size, psize) (PAGEHDRSZ + size + psize - 1) / psize;
164 typedef struct MDB_db {
168 ULONG md_branch_pages;
170 ULONG md_overflow_pages;
178 typedef struct MDB_meta { /* meta (footer) page content */
181 void *mm_address; /* address for fixed mapping */
182 size_t mm_mapsize; /* size of mmap region */
183 MDB_db mm_dbs[2]; /* first is free space, 2nd is main db */
184 #define mm_psize mm_dbs[0].md_pad
185 #define mm_flags mm_dbs[0].md_flags
186 pgno_t mm_last_pg; /* last used page in file */
187 ULONG mm_txnid; /* txnid that committed this page */
190 typedef struct MDB_dhead { /* a dirty page */
191 STAILQ_ENTRY(MDB_dpage) md_next; /* queue of dirty pages */
193 unsigned md_pi; /* parent index */
197 typedef struct MDB_dpage {
202 STAILQ_HEAD(dirty_queue, MDB_dpage); /* FIXME: use a sorted data structure */
204 typedef struct MDB_oldpages {
205 struct MDB_oldpages *mo_next;
207 pgno_t mo_pages[1]; /* dynamic */
210 typedef struct MDB_pageparent {
216 static MDB_dpage *mdb_alloc_page(MDB_txn *txn, MDB_page *parent, unsigned int parent_idx, int num);
217 static int mdb_touch(MDB_txn *txn, MDB_pageparent *mp);
219 typedef struct MDB_ppage { /* ordered list of pages */
220 SLIST_ENTRY(MDB_ppage) mp_entry;
222 unsigned int mp_ki; /* cursor index on page */
224 SLIST_HEAD(page_stack, MDB_ppage);
226 #define CURSOR_EMPTY(c) SLIST_EMPTY(&(c)->mc_stack)
227 #define CURSOR_TOP(c) SLIST_FIRST(&(c)->mc_stack)
228 #define CURSOR_POP(c) SLIST_REMOVE_HEAD(&(c)->mc_stack, mp_entry)
229 #define CURSOR_PUSH(c,p) SLIST_INSERT_HEAD(&(c)->mc_stack, p, mp_entry)
235 struct page_stack mc_stack; /* stack of parent pages */
237 short mc_initialized; /* 1 if initialized */
238 short mc_eof; /* 1 if end is reached */
239 struct MDB_xcursor *mc_xcursor;
242 #define METAHASHLEN offsetof(MDB_meta, mm_hash)
243 #define METADATA(p) ((void *)((char *)p + PAGEHDRSZ))
245 typedef struct MDB_node {
246 #define mn_pgno mn_p.np_pgno
247 #define mn_dsize mn_p.np_dsize
249 pgno_t np_pgno; /* child page number */
250 uint32_t np_dsize; /* leaf data size */
252 unsigned int mn_flags:4;
253 unsigned int mn_ksize:12; /* key size */
254 #define F_BIGDATA 0x01 /* data put on overflow page */
255 #define F_SUBDATA 0x02 /* data is a sub-database */
259 typedef struct MDB_dbx {
261 MDB_cmp_func *md_cmp; /* user compare function */
262 MDB_cmp_func *md_dcmp; /* user dupsort function */
263 MDB_rel_func *md_rel; /* user relocate function */
265 unsigned int md_dirty;
269 pgno_t mt_next_pgno; /* next unallocated page */
273 pgno_t *mt_free_pgs; /* this is an IDL */
275 struct dirty_queue *dirty_queue; /* modified pages */
278 MDB_dbx *mt_dbxs; /* array */
280 unsigned int mt_numdbs;
282 #define MDB_TXN_RDONLY 0x01 /* read-only transaction */
283 #define MDB_TXN_ERROR 0x02 /* an error has occurred */
284 #define MDB_TXN_METOGGLE 0x04 /* used meta page 1 */
285 unsigned int mt_flags;
288 /* Context for sorted-dup records */
289 typedef struct MDB_xcursor {
290 MDB_cursor mx_cursor;
300 unsigned int me_maxreaders;
301 unsigned int me_numdbs;
302 unsigned int me_maxdbs;
305 MDB_txninfo *me_txns;
306 MDB_meta *me_metas[2];
308 MDB_txn *me_txn; /* current write transaction */
310 off_t me_size; /* current file size */
311 unsigned int me_psize;
313 MDB_dbx *me_dbxs; /* array */
315 MDB_oldpages *me_pghead;
316 pthread_key_t me_txkey; /* thread-key for readers */
317 pgno_t me_free_pgs[MDB_IDL_UM_SIZE];
320 #define NODESIZE offsetof(MDB_node, mn_data)
322 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
323 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
324 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
325 #define NODEKEY(node) (void *)((node)->mn_data)
326 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
327 #define NODEPGNO(node) ((node)->mn_pgno)
328 #define NODEDSZ(node) ((node)->mn_dsize)
330 #define MDB_COMMIT_PAGES 64 /* max number of pages to write in one commit */
331 #define MDB_MAXCACHE_DEF 1024 /* max number of pages to keep in cache */
333 static int mdb_search_page_root(MDB_txn *txn,
334 MDB_dbi dbi, MDB_val *key,
335 MDB_cursor *cursor, int modify,
336 MDB_pageparent *mpp);
337 static int mdb_search_page(MDB_txn *txn,
338 MDB_dbi dbi, MDB_val *key,
339 MDB_cursor *cursor, int modify,
340 MDB_pageparent *mpp);
342 static int mdbenv_read_header(MDB_env *env, MDB_meta *meta);
343 static int mdbenv_read_meta(MDB_env *env, int *which);
344 static int mdbenv_write_meta(MDB_txn *txn);
345 static MDB_page *mdb_get_page(MDB_txn *txn, pgno_t pgno);
347 static MDB_node *mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp,
348 MDB_val *key, int *exactp, unsigned int *kip);
349 static int mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp,
350 indx_t indx, MDB_val *key, MDB_val *data,
351 pgno_t pgno, uint8_t flags);
352 static void mdb_del_node(MDB_page *mp, indx_t indx);
353 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, unsigned int ki,
354 MDB_pageparent *mpp, MDB_node *leaf);
355 static int mdb_put0(MDB_txn *txn, MDB_dbi dbi,
356 MDB_val *key, MDB_val *data, unsigned int flags);
357 static int mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
359 static int mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mp);
360 static int mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
361 static int mdb_move_node(MDB_txn *txn, MDB_dbi dbi,
362 MDB_pageparent *src, indx_t srcindx,
363 MDB_pageparent *dst, indx_t dstindx);
364 static int mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src,
365 MDB_pageparent *dst);
366 static int mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp,
367 unsigned int *newindxp, MDB_val *newkey,
368 MDB_val *newdata, pgno_t newpgno);
369 static MDB_dpage *mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num);
371 static void cursor_pop_page(MDB_cursor *cursor);
372 static MDB_ppage *cursor_push_page(MDB_cursor *cursor,
375 static int mdb_set_key(MDB_node *node, MDB_val *key);
376 static int mdb_sibling(MDB_cursor *cursor, int move_right);
377 static int mdb_cursor_next(MDB_cursor *cursor,
378 MDB_val *key, MDB_val *data, MDB_cursor_op op);
379 static int mdb_cursor_prev(MDB_cursor *cursor,
380 MDB_val *key, MDB_val *data, MDB_cursor_op op);
381 static int mdb_cursor_set(MDB_cursor *cursor,
382 MDB_val *key, MDB_val *data, MDB_cursor_op op, int *exactp);
383 static int mdb_cursor_first(MDB_cursor *cursor,
384 MDB_val *key, MDB_val *data);
385 static int mdb_cursor_last(MDB_cursor *cursor,
386 MDB_val *key, MDB_val *data);
388 static void mdb_xcursor_init0(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
389 static void mdb_xcursor_init1(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx, MDB_db *db);
390 static void mdb_xcursor_fini(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
392 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key,
394 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
396 static int memncmp(const void *s1, size_t n1,
397 const void *s2, size_t n2);
398 static int memnrcmp(const void *s1, size_t n1,
399 const void *s2, size_t n2);
402 memncmp(const void *s1, size_t n1, const void *s2, size_t n2)
404 int diff, len_diff = -1;
407 len_diff = (n1 > n2);
410 diff = memcmp(s1, s2, n1);
411 return diff ? diff : len_diff;
415 memnrcmp(const void *s1, size_t n1, const void *s2, size_t n2)
417 const unsigned char *p1, *p2, *p1_lim;
424 p1 = (const unsigned char *)s1 + n1 - 1;
425 p2 = (const unsigned char *)s2 + n2 - 1;
427 for (p1_lim = (n1 <= n2 ? s1 : s2); *p1 == *p2; p1--, p2--) {
429 return (p1 != s1) ? (p1 != p2) : (p2 != s2) ? -1 : 0;
435 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
437 return txn->mt_dbxs[dbi].md_cmp(a, b);
441 _mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *key1, const MDB_val *key2)
443 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_REVERSEKEY))
444 return memnrcmp(key1->mv_data, key1->mv_size, key2->mv_data, key2->mv_size);
446 return memncmp((char *)key1->mv_data, key1->mv_size, key2->mv_data, key2->mv_size);
449 /* Allocate new page(s) for writing */
451 mdb_alloc_page(MDB_txn *txn, MDB_page *parent, unsigned int parent_idx, int num)
454 pgno_t pgno = P_INVALID;
457 if (txn->mt_txnid > 2) {
459 oldest = txn->mt_txnid - 2;
460 if (!txn->mt_env->me_pghead && txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
461 /* See if there's anything in the free DB */
466 mpp.mp_parent = NULL;
468 mdb_search_page(txn, FREE_DBI, NULL, NULL, 0, &mpp);
469 leaf = NODEPTR(mpp.mp_page, 0);
470 kptr = (ULONG *)NODEKEY(leaf);
472 /* It's potentially usable, unless there are still
473 * older readers outstanding. Grab it.
475 if (oldest > *kptr) {
480 mdb_read_data(txn, leaf, &data);
481 idl = (ULONG *)data.mv_data;
482 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
483 mop->mo_next = txn->mt_env->me_pghead;
484 mop->mo_txnid = *kptr;
485 txn->mt_env->me_pghead = mop;
486 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
491 DPRINTF("IDL read txn %lu root %lu num %lu",
492 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
493 for (i=0; i<idl[0]; i++) {
494 DPRINTF("IDL %lu", idl[i+1]);
498 /* drop this IDL from the DB */
499 mpp.mp_parent = NULL;
501 mdb_search_page(txn, FREE_DBI, NULL, NULL, 1, &mpp);
502 leaf = NODEPTR(mpp.mp_page, 0);
503 mdb_del0(txn, FREE_DBI, 0, &mpp, leaf);
506 if (txn->mt_env->me_pghead) {
508 for (i=0; i<txn->mt_env->me_txns->mt_numreaders; i++) {
509 ULONG mr = txn->mt_env->me_txns->mt_readers[i].mr_txnid;
512 oldest = txn->mt_env->me_txns->mt_readers[i].mr_txnid;
514 if (oldest > txn->mt_env->me_pghead->mo_txnid) {
515 MDB_oldpages *mop = txn->mt_env->me_pghead;
516 txn->mt_oldest = oldest;
518 /* FIXME: For now, always use fresh pages. We
519 * really ought to search the free list for a
524 /* peel pages off tail, so we only have to truncate the list */
525 pgno = MDB_IDL_LAST(mop->mo_pages);
526 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
528 if (mop->mo_pages[2] > mop->mo_pages[1])
529 mop->mo_pages[0] = 0;
533 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
534 txn->mt_env->me_pghead = mop->mo_next;
542 if ((dp = malloc(txn->mt_env->me_psize * num + sizeof(MDB_dhead))) == NULL)
545 dp->h.md_parent = parent;
546 dp->h.md_pi = parent_idx;
547 STAILQ_INSERT_TAIL(txn->mt_u.dirty_queue, dp, h.md_next);
548 if (pgno == P_INVALID) {
549 dp->p.mp_pgno = txn->mt_next_pgno;
550 txn->mt_next_pgno += num;
552 dp->p.mp_pgno = pgno;
558 /* Touch a page: make it dirty and re-insert into tree with updated pgno.
561 mdb_touch(MDB_txn *txn, MDB_pageparent *pp)
563 MDB_page *mp = pp->mp_page;
568 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
570 if ((dp = mdb_alloc_page(txn, pp->mp_parent, pp->mp_pi, 1)) == NULL)
572 DPRINTF("touched page %lu -> %lu", mp->mp_pgno, dp->p.mp_pgno);
573 mdb_idl_insert(txn->mt_free_pgs, mp->mp_pgno);
574 pgno = dp->p.mp_pgno;
575 memcpy(&dp->p, mp, txn->mt_env->me_psize);
578 mp->mp_flags |= P_DIRTY;
580 /* Update the page number to new touched page. */
581 if (pp->mp_parent != NULL)
582 NODEPGNO(NODEPTR(pp->mp_parent, pp->mp_pi)) = mp->mp_pgno;
589 mdbenv_sync(MDB_env *env)
592 if (!F_ISSET(env->me_flags, MDB_NOSYNC)) {
593 if (fsync(env->me_fd))
600 mdb_txn_begin(MDB_env *env, int rdonly, MDB_txn **ret)
605 if ((txn = calloc(1, sizeof(MDB_txn))) == NULL) {
606 DPRINTF("calloc: %s", strerror(errno));
611 txn->mt_flags |= MDB_TXN_RDONLY;
613 txn->mt_u.dirty_queue = calloc(1, sizeof(*txn->mt_u.dirty_queue));
614 if (txn->mt_u.dirty_queue == NULL) {
618 STAILQ_INIT(txn->mt_u.dirty_queue);
620 pthread_mutex_lock(&env->me_txns->mt_wmutex);
621 env->me_txns->mt_txnid++;
622 txn->mt_free_pgs = env->me_free_pgs;
623 txn->mt_free_pgs[0] = 0;
626 txn->mt_txnid = env->me_txns->mt_txnid;
628 MDB_reader *r = pthread_getspecific(env->me_txkey);
631 pthread_mutex_lock(&env->me_txns->mt_mutex);
632 for (i=0; i<env->me_txns->mt_numreaders; i++)
633 if (env->me_txns->mt_readers[i].mr_pid == 0)
635 if (i == env->me_maxreaders) {
636 pthread_mutex_unlock(&env->me_txns->mti_mutex);
639 env->me_txns->mt_readers[i].mr_pid = getpid();
640 env->me_txns->mt_readers[i].mr_tid = pthread_self();
641 r = &env->me_txns->mt_readers[i];
642 pthread_setspecific(env->me_txkey, r);
643 if (i >= env->me_txns->mt_numreaders)
644 env->me_txns->mt_numreaders = i+1;
645 pthread_mutex_unlock(&env->me_txns->mt_mutex);
647 r->mr_txnid = txn->mt_txnid;
648 txn->mt_u.reader = r;
655 if ((rc = mdbenv_read_meta(env, &toggle)) != MDB_SUCCESS) {
660 /* Copy the DB arrays */
661 txn->mt_numdbs = env->me_numdbs;
662 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
663 txn->mt_dbs = malloc(env->me_maxdbs * sizeof(MDB_db));
664 memcpy(txn->mt_dbs, env->me_meta->mm_dbs, 2 * sizeof(MDB_db));
665 if (txn->mt_numdbs > 2)
666 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
667 (txn->mt_numdbs - 2) * sizeof(MDB_db));
671 txn->mt_flags |= MDB_TXN_METOGGLE;
672 txn->mt_next_pgno = env->me_meta->mm_last_pg+1;
675 DPRINTF("begin transaction %lu on mdbenv %p, root page %lu",
676 txn->mt_txnid, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
683 mdb_txn_abort(MDB_txn *txn)
692 DPRINTF("abort transaction %lu on mdbenv %p, root page %lu",
693 txn->mt_txnid, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
697 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
698 txn->mt_u.reader->mr_txnid = 0;
703 /* Discard all dirty pages. */
704 while (!STAILQ_EMPTY(txn->mt_u.dirty_queue)) {
705 dp = STAILQ_FIRST(txn->mt_u.dirty_queue);
706 STAILQ_REMOVE_HEAD(txn->mt_u.dirty_queue, h.md_next);
709 free(txn->mt_u.dirty_queue);
711 while ((mop = txn->mt_env->me_pghead)) {
712 txn->mt_env->me_pghead = mop->mo_next;
717 env->me_txns->mt_txnid--;
718 for (i=2; i<env->me_numdbs; i++)
719 env->me_dbxs[i].md_dirty = 0;
720 pthread_mutex_unlock(&env->me_txns->mt_wmutex);
727 mdb_txn_commit(MDB_txn *txn)
736 struct iovec iov[MDB_COMMIT_PAGES];
739 assert(txn->mt_env != NULL);
743 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
744 DPRINTF("attempt to commit read-only transaction");
749 if (txn != env->me_txn) {
750 DPRINTF("attempt to commit unknown transaction");
755 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
756 DPRINTF("error flag is set, can't commit");
761 if (STAILQ_EMPTY(txn->mt_u.dirty_queue))
764 DPRINTF("committing transaction %lu on mdbenv %p, root page %lu",
765 txn->mt_txnid, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
767 /* should only be one record now */
768 if (env->me_pghead) {
772 mop = env->me_pghead;
773 key.mv_size = sizeof(pgno_t);
774 key.mv_data = (char *)&mop->mo_txnid;
775 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
776 data.mv_data = mop->mo_pages;
777 mdb_put0(txn, FREE_DBI, &key, &data, 0);
778 free(env->me_pghead);
779 env->me_pghead = NULL;
781 /* save to free list */
782 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
786 /* make sure last page of freeDB is touched and on freelist */
787 key.mv_size = MAXKEYSIZE+1;
789 mpp.mp_parent = NULL;
791 mdb_search_page(txn, FREE_DBI, &key, NULL, 1, &mpp);
796 ULONG *idl = txn->mt_free_pgs;
797 DPRINTF("IDL write txn %lu root %lu num %lu",
798 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
799 for (i=0; i<idl[0]; i++) {
800 DPRINTF("IDL %lu", idl[i+1]);
804 /* write to last page of freeDB */
805 key.mv_size = sizeof(pgno_t);
806 key.mv_data = (char *)&txn->mt_txnid;
807 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
808 data.mv_data = txn->mt_free_pgs;
809 mdb_put0(txn, FREE_DBI, &key, &data, 0);
812 /* Update DB root pointers. Their pages have already been
813 * touched so this is all in-place and cannot fail.
817 data.mv_size = sizeof(MDB_db);
819 for (i = 2; i < txn->mt_numdbs; i++) {
820 if (txn->mt_dbxs[i].md_dirty) {
821 data.mv_data = &txn->mt_dbs[i];
822 mdb_put0(txn, MAIN_DBI, &txn->mt_dbxs[i].md_name, &data, 0);
827 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
834 STAILQ_FOREACH(dp, txn->mt_u.dirty_queue, h.md_next) {
835 if (dp->p.mp_pgno != next) {
837 DPRINTF("committing %u dirty pages", n);
838 rc = writev(env->me_fd, iov, n);
842 DPRINTF("short write, filesystem full?");
844 DPRINTF("writev: %s", strerror(errno));
851 lseek(env->me_fd, dp->p.mp_pgno * env->me_psize, SEEK_SET);
852 next = dp->p.mp_pgno;
854 DPRINTF("committing page %lu", dp->p.mp_pgno);
855 iov[n].iov_len = env->me_psize * dp->h.md_num;
856 iov[n].iov_base = &dp->p;
857 size += iov[n].iov_len;
858 next = dp->p.mp_pgno + dp->h.md_num;
859 /* clear dirty flag */
860 dp->p.mp_flags &= ~P_DIRTY;
861 if (++n >= MDB_COMMIT_PAGES) {
870 DPRINTF("committing %u dirty pages", n);
871 rc = writev(env->me_fd, iov, n);
875 DPRINTF("short write, filesystem full?");
877 DPRINTF("writev: %s", strerror(errno));
884 /* Drop the dirty pages.
886 while (!STAILQ_EMPTY(txn->mt_u.dirty_queue)) {
887 dp = STAILQ_FIRST(txn->mt_u.dirty_queue);
888 STAILQ_REMOVE_HEAD(txn->mt_u.dirty_queue, h.md_next);
892 if ((n = mdbenv_sync(env)) != 0 ||
893 (n = mdbenv_write_meta(txn)) != MDB_SUCCESS ||
894 (n = mdbenv_sync(env)) != 0) {
900 /* update the DB tables */
902 int toggle = !env->me_db_toggle;
904 for (i = 2; i < env->me_numdbs; i++) {
905 if (txn->mt_dbxs[i].md_dirty) {
906 env->me_dbs[toggle][i] = txn->mt_dbs[i];
907 txn->mt_dbxs[i].md_dirty = 0;
910 for (i = env->me_numdbs; i < txn->mt_numdbs; i++) {
911 txn->mt_dbxs[i].md_dirty = 0;
912 env->me_dbxs[i] = txn->mt_dbxs[i];
913 env->me_dbs[toggle][i] = txn->mt_dbs[i];
915 env->me_db_toggle = toggle;
916 env->me_numdbs = txn->mt_numdbs;
921 pthread_mutex_unlock(&env->me_txns->mt_wmutex);
922 free(txn->mt_u.dirty_queue);
933 mdbenv_read_header(MDB_env *env, MDB_meta *meta)
942 /* We don't know the page size yet, so use a minimum value.
945 if ((rc = pread(env->me_fd, page, PAGESIZE, 0)) == 0) {
947 } else if (rc != PAGESIZE) {
950 DPRINTF("read: %s", strerror(errno));
954 p = (MDB_page *)page;
956 if (!F_ISSET(p->mp_flags, P_META)) {
957 DPRINTF("page %lu not a meta page", p->mp_pgno);
962 if (m->mm_magic != MDB_MAGIC) {
963 DPRINTF("meta has invalid magic");
967 if (m->mm_version != MDB_VERSION) {
968 DPRINTF("database is version %u, expected version %u",
969 m->mm_version, MDB_VERSION);
970 return MDB_VERSION_MISMATCH;
973 memcpy(meta, m, sizeof(*m));
978 mdbenv_init_meta(MDB_env *env, MDB_meta *meta)
985 DPRINTF("writing new meta page");
986 psize = sysconf(_SC_PAGE_SIZE);
988 meta->mm_magic = MDB_MAGIC;
989 meta->mm_version = MDB_VERSION;
990 meta->mm_psize = psize;
991 meta->mm_last_pg = 1;
992 meta->mm_flags = env->me_flags & 0xffff;
993 #if __BYTE_ORDER == __LITTLE_ENDIAN
994 /* freeDB keys are pgno_t's, must compare in int order */
995 meta->mm_flags |= MDB_REVERSEKEY;
997 meta->mm_dbs[0].md_root = P_INVALID;
998 meta->mm_dbs[1].md_root = P_INVALID;
1000 p = calloc(2, psize);
1002 p->mp_flags = P_META;
1005 memcpy(m, meta, sizeof(*meta));
1007 q = (MDB_page *)((char *)p + psize);
1010 q->mp_flags = P_META;
1013 memcpy(m, meta, sizeof(*meta));
1015 rc = write(env->me_fd, p, psize * 2);
1017 return (rc == (int)psize * 2) ? MDB_SUCCESS : errno;
1021 mdbenv_write_meta(MDB_txn *txn)
1029 assert(txn != NULL);
1030 assert(txn->mt_env != NULL);
1032 DPRINTF("writing meta page for root page %lu", txn->mt_dbs[MAIN_DBI].md_root);
1036 ptr = (char *)&meta;
1037 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
1038 len = sizeof(MDB_meta) - off;
1041 meta.mm_dbs[0] = txn->mt_dbs[0];
1042 meta.mm_dbs[1] = txn->mt_dbs[1];
1043 meta.mm_last_pg = txn->mt_next_pgno - 1;
1044 meta.mm_txnid = txn->mt_txnid;
1046 if (!F_ISSET(txn->mt_flags, MDB_TXN_METOGGLE))
1047 off += env->me_psize;
1050 lseek(env->me_fd, off, SEEK_SET);
1051 rc = write(env->me_fd, ptr, len);
1053 DPRINTF("write failed, disk error?");
1061 mdbenv_read_meta(MDB_env *env, int *which)
1065 assert(env != NULL);
1067 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1070 if (env->me_meta != env->me_metas[toggle])
1071 env->me_meta = env->me_metas[toggle];
1075 DPRINTF("Using meta page %d", toggle);
1081 mdbenv_create(MDB_env **env)
1085 e = calloc(1, sizeof(MDB_env));
1086 if (!e) return ENOMEM;
1088 e->me_maxreaders = DEFAULT_READERS;
1097 mdbenv_set_mapsize(MDB_env *env, size_t size)
1101 env->me_mapsize = size;
1106 mdbenv_set_maxdbs(MDB_env *env, int dbs)
1108 env->me_maxdbs = dbs;
1113 mdbenv_set_maxreaders(MDB_env *env, int readers)
1115 env->me_maxreaders = readers;
1120 mdbenv_get_maxreaders(MDB_env *env, int *readers)
1122 if (!env || !readers)
1124 *readers = env->me_maxreaders;
1129 mdbenv_open2(MDB_env *env, unsigned int flags)
1135 env->me_flags = flags;
1137 memset(&meta, 0, sizeof(meta));
1139 if ((i = mdbenv_read_header(env, &meta)) != 0) {
1142 DPRINTF("new mdbenv");
1146 if (!env->me_mapsize) {
1147 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
1151 if (meta.mm_address && (flags & MDB_FIXEDMAP))
1153 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
1155 if (env->me_map == MAP_FAILED)
1159 meta.mm_mapsize = env->me_mapsize;
1160 if (flags & MDB_FIXEDMAP)
1161 meta.mm_address = env->me_map;
1162 i = mdbenv_init_meta(env, &meta);
1163 if (i != MDB_SUCCESS) {
1164 munmap(env->me_map, env->me_mapsize);
1168 env->me_psize = meta.mm_psize;
1170 p = (MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)env->me_map;
1171 env->me_metas[0] = METADATA(p);
1172 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
1174 if ((i = mdbenv_read_meta(env, NULL)) != 0)
1177 DPRINTF("opened database version %u, pagesize %u",
1178 env->me_meta->mm_version, env->me_psize);
1179 DPRINTF("depth: %u", env->me_meta->mm_dbs[MAIN_DBI].md_depth);
1180 DPRINTF("entries: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_entries);
1181 DPRINTF("branch pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_branch_pages);
1182 DPRINTF("leaf pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_leaf_pages);
1183 DPRINTF("overflow pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_overflow_pages);
1184 DPRINTF("root: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_root);
1190 mdbenv_reader_dest(void *ptr)
1192 MDB_reader *reader = ptr;
1194 reader->mr_txnid = 0;
1199 /* downgrade the exclusive lock on the region back to shared */
1201 mdbenv_share_locks(MDB_env *env)
1203 struct flock lock_info;
1205 env->me_txns->mt_txnid = env->me_meta->mm_txnid;
1207 memset((void *)&lock_info, 0, sizeof(lock_info));
1208 lock_info.l_type = F_RDLCK;
1209 lock_info.l_whence = SEEK_SET;
1210 lock_info.l_start = 0;
1211 lock_info.l_len = 1;
1212 fcntl(env->me_lfd, F_SETLK, &lock_info);
1216 mdbenv_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
1220 struct flock lock_info;
1224 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
1228 /* Try to get exclusive lock. If we succeed, then
1229 * nobody is using the lock region and we should initialize it.
1231 memset((void *)&lock_info, 0, sizeof(lock_info));
1232 lock_info.l_type = F_WRLCK;
1233 lock_info.l_whence = SEEK_SET;
1234 lock_info.l_start = 0;
1235 lock_info.l_len = 1;
1236 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1240 lock_info.l_type = F_RDLCK;
1241 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1247 size = lseek(env->me_lfd, 0, SEEK_END);
1248 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1249 if (size < rsize && *excl) {
1250 if (ftruncate(env->me_lfd, rsize) != 0) {
1256 size = rsize - sizeof(MDB_txninfo);
1257 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
1259 env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
1261 if (env->me_txns == MAP_FAILED) {
1266 pthread_mutexattr_t mattr;
1268 pthread_mutexattr_init(&mattr);
1269 pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
1270 pthread_mutex_init(&env->me_txns->mt_mutex, &mattr);
1271 pthread_mutex_init(&env->me_txns->mt_wmutex, &mattr);
1272 env->me_txns->mt_version = MDB_VERSION;
1273 env->me_txns->mt_magic = MDB_MAGIC;
1274 env->me_txns->mt_txnid = 0;
1275 env->me_txns->mt_numreaders = 0;
1278 if (env->me_txns->mt_magic != MDB_MAGIC) {
1279 DPRINTF("lock region has invalid magic");
1283 if (env->me_txns->mt_version != MDB_VERSION) {
1284 DPRINTF("lock region is version %u, expected version %u",
1285 env->me_txns->mt_version, MDB_VERSION);
1286 rc = MDB_VERSION_MISMATCH;
1289 if (errno != EACCES && errno != EAGAIN) {
1302 #define LOCKNAME "/lock.mdb"
1303 #define DATANAME "/data.mdb"
1305 mdbenv_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
1307 int oflags, rc, len, excl;
1308 char *lpath, *dpath;
1311 lpath = malloc(len + sizeof(LOCKNAME) + len + sizeof(DATANAME));
1314 dpath = lpath + len + sizeof(LOCKNAME);
1315 sprintf(lpath, "%s" LOCKNAME, path);
1316 sprintf(dpath, "%s" DATANAME, path);
1318 rc = mdbenv_setup_locks(env, lpath, mode, &excl);
1322 if (F_ISSET(flags, MDB_RDONLY))
1325 oflags = O_RDWR | O_CREAT;
1327 if ((env->me_fd = open(dpath, oflags, mode)) == -1)
1330 if ((rc = mdbenv_open2(env, flags)) != MDB_SUCCESS) {
1334 env->me_path = strdup(path);
1335 DPRINTF("opened dbenv %p", (void *) env);
1336 pthread_key_create(&env->me_txkey, mdbenv_reader_dest);
1338 mdbenv_share_locks(env);
1339 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
1340 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
1341 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
1351 mdbenv_close(MDB_env *env)
1356 free(env->me_dbs[1]);
1357 free(env->me_dbs[0]);
1362 munmap(env->me_map, env->me_mapsize);
1366 size_t size = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1367 munmap(env->me_txns, size);
1373 /* Search for key within a leaf page, using binary search.
1374 * Returns the smallest entry larger or equal to the key.
1375 * If exactp is non-null, stores whether the found entry was an exact match
1376 * in *exactp (1 or 0).
1377 * If kip is non-null, stores the index of the found entry in *kip.
1378 * If no entry larger or equal to the key is found, returns NULL.
1381 mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, MDB_val *key,
1382 int *exactp, unsigned int *kip)
1390 DPRINTF("searching %u keys in %s page %lu",
1392 IS_LEAF(mp) ? "leaf" : "branch",
1395 assert(NUMKEYS(mp) > 0);
1397 memset(&nodekey, 0, sizeof(nodekey));
1399 low = IS_LEAF(mp) ? 0 : 1;
1400 high = NUMKEYS(mp) - 1;
1401 while (low <= high) {
1402 i = (low + high) >> 1;
1403 node = NODEPTR(mp, i);
1405 nodekey.mv_size = node->mn_ksize;
1406 nodekey.mv_data = NODEKEY(node);
1408 if (txn->mt_dbxs[dbi].md_cmp)
1409 rc = txn->mt_dbxs[dbi].md_cmp(key, &nodekey);
1411 rc = _mdb_cmp(txn, dbi, key, &nodekey);
1414 DPRINTF("found leaf index %u [%.*s], rc = %i",
1415 i, (int)nodekey.mv_size, (char *)nodekey.mv_data, rc);
1417 DPRINTF("found branch index %u [%.*s -> %lu], rc = %i",
1418 i, (int)node->mn_ksize, (char *)NODEKEY(node),
1429 if (rc > 0) { /* Found entry is less than the key. */
1430 i++; /* Skip to get the smallest entry larger than key. */
1431 if (i >= NUMKEYS(mp))
1432 /* There is no entry larger or equal to the key. */
1436 *exactp = (rc == 0);
1437 if (kip) /* Store the key index if requested. */
1440 return NODEPTR(mp, i);
1444 cursor_pop_page(MDB_cursor *cursor)
1448 top = CURSOR_TOP(cursor);
1451 DPRINTF("popped page %lu off cursor %p", top->mp_page->mp_pgno, (void *) cursor);
1457 cursor_push_page(MDB_cursor *cursor, MDB_page *mp)
1461 DPRINTF("pushing page %lu on cursor %p", mp->mp_pgno, (void *) cursor);
1463 if ((ppage = calloc(1, sizeof(MDB_ppage))) == NULL)
1465 ppage->mp_page = mp;
1466 CURSOR_PUSH(cursor, ppage);
1471 mdb_get_page(MDB_txn *txn, pgno_t pgno)
1476 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && !STAILQ_EMPTY(txn->mt_u.dirty_queue)) {
1478 STAILQ_FOREACH(dp, txn->mt_u.dirty_queue, h.md_next) {
1479 if (dp->p.mp_pgno == pgno) {
1487 if (pgno > txn->mt_env->me_meta->mm_last_pg)
1489 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
1495 mdb_search_page_root(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
1496 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
1498 MDB_page *mp = mpp->mp_page;
1501 if (cursor && cursor_push_page(cursor, mp) == NULL)
1504 while (IS_BRANCH(mp)) {
1508 DPRINTF("branch page %lu has %u keys", mp->mp_pgno, NUMKEYS(mp));
1509 assert(NUMKEYS(mp) > 1);
1510 DPRINTF("found index 0 to page %lu", NODEPGNO(NODEPTR(mp, 0)));
1512 if (key == NULL) /* Initialize cursor to first page. */
1514 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
1515 /* cursor to last page */
1519 node = mdb_search_node(txn, dbi, mp, key, &exact, &i);
1521 i = NUMKEYS(mp) - 1;
1529 DPRINTF("following index %u for key %.*s",
1530 i, (int)key->mv_size, (char *)key->mv_data);
1531 assert(i < NUMKEYS(mp));
1532 node = NODEPTR(mp, i);
1535 CURSOR_TOP(cursor)->mp_ki = i;
1537 mpp->mp_parent = mp;
1538 if ((mp = mdb_get_page(txn, NODEPGNO(node))) == NULL)
1543 if (cursor && cursor_push_page(cursor, mp) == NULL)
1547 MDB_dhead *dh = ((MDB_dhead *)mp)-1;
1548 if ((rc = mdb_touch(txn, mpp)) != 0)
1550 dh = ((MDB_dhead *)mpp->mp_page)-1;
1551 dh->md_parent = mpp->mp_parent;
1552 dh->md_pi = mpp->mp_pi;
1559 DPRINTF("internal error, index points to a %02X page!?",
1564 DPRINTF("found leaf page %lu for key %.*s", mp->mp_pgno,
1565 key ? (int)key->mv_size : 0, key ? (char *)key->mv_data : NULL);
1570 /* Search for the page a given key should be in.
1571 * Stores a pointer to the found page in *mpp.
1572 * If key is NULL, search for the lowest page (used by mdb_cursor_first).
1573 * If cursor is non-null, pushes parent pages on the cursor stack.
1574 * If modify is true, visited pages are updated with new page numbers.
1577 mdb_search_page(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
1578 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
1583 /* Choose which root page to start with. If a transaction is given
1584 * use the root page from the transaction, otherwise read the last
1585 * committed root page.
1587 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1588 DPRINTF("transaction has failed, must abort");
1591 root = txn->mt_dbs[dbi].md_root;
1593 if (root == P_INVALID) { /* Tree is empty. */
1594 DPRINTF("tree is empty");
1595 return MDB_NOTFOUND;
1598 if ((mpp->mp_page = mdb_get_page(txn, root)) == NULL)
1601 DPRINTF("root page has flags 0x%X", mpp->mp_page->mp_flags);
1604 /* For sub-databases, update main root first */
1605 if (dbi > MAIN_DBI && !txn->mt_dbxs[dbi].md_dirty) {
1607 rc = mdb_search_page(txn, MAIN_DBI, &txn->mt_dbxs[dbi].md_name,
1611 txn->mt_dbxs[dbi].md_dirty = 1;
1613 if (!F_ISSET(mpp->mp_page->mp_flags, P_DIRTY)) {
1614 mpp->mp_parent = NULL;
1616 if ((rc = mdb_touch(txn, mpp)))
1618 txn->mt_dbs[dbi].md_root = mpp->mp_page->mp_pgno;
1622 return mdb_search_page_root(txn, dbi, key, cursor, modify, mpp);
1626 mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
1628 MDB_page *omp; /* overflow mpage */
1631 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
1632 data->mv_size = leaf->mn_dsize;
1633 data->mv_data = NODEDATA(leaf);
1637 /* Read overflow data.
1639 data->mv_size = leaf->mn_dsize;
1640 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
1641 if ((omp = mdb_get_page(txn, pgno)) == NULL) {
1642 DPRINTF("read overflow page %lu failed", pgno);
1645 data->mv_data = omp;
1651 mdb_get(MDB_txn *txn, MDB_dbi dbi,
1652 MDB_val *key, MDB_val *data)
1660 DPRINTF("===> get key [%.*s]", (int)key->mv_size, (char *)key->mv_data);
1662 if (txn == NULL || dbi >= txn->mt_numdbs)
1665 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
1669 if ((rc = mdb_search_page(txn, dbi, key, NULL, 0, &mpp)) != MDB_SUCCESS)
1672 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, NULL);
1673 if (leaf && exact) {
1674 /* Return first duplicate data item */
1675 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
1678 mdb_xcursor_init0(txn, dbi, &mx);
1679 mdb_xcursor_init1(txn, dbi, &mx, NODEDATA(leaf));
1680 rc = mdb_search_page(&mx.mx_txn, mx.mx_cursor.mc_dbi, NULL, NULL, 0, &mpp);
1681 if (rc != MDB_SUCCESS)
1683 leaf = NODEPTR(mpp.mp_page, 0);
1685 rc = mdb_read_data(txn, leaf, data);
1694 mdb_sibling(MDB_cursor *cursor, int move_right)
1698 MDB_ppage *parent, *top;
1701 top = CURSOR_TOP(cursor);
1702 if ((parent = SLIST_NEXT(top, mp_entry)) == NULL) {
1703 return MDB_NOTFOUND; /* root has no siblings */
1706 DPRINTF("parent page is page %lu, index %u",
1707 parent->mp_page->mp_pgno, parent->mp_ki);
1709 cursor_pop_page(cursor);
1710 if (move_right ? (parent->mp_ki + 1 >= NUMKEYS(parent->mp_page))
1711 : (parent->mp_ki == 0)) {
1712 DPRINTF("no more keys left, moving to %s sibling",
1713 move_right ? "right" : "left");
1714 if ((rc = mdb_sibling(cursor, move_right)) != MDB_SUCCESS)
1716 parent = CURSOR_TOP(cursor);
1722 DPRINTF("just moving to %s index key %u",
1723 move_right ? "right" : "left", parent->mp_ki);
1725 assert(IS_BRANCH(parent->mp_page));
1727 indx = NODEPTR(parent->mp_page, parent->mp_ki);
1728 if ((mp = mdb_get_page(cursor->mc_txn, indx->mn_pgno)) == NULL)
1731 mp->parent = parent->mp_page;
1732 mp->parent_index = parent->mp_ki;
1735 cursor_push_page(cursor, mp);
1741 mdb_set_key(MDB_node *node, MDB_val *key)
1746 key->mv_size = node->mn_ksize;
1747 key->mv_data = NODEKEY(node);
1753 mdb_cursor_next(MDB_cursor *cursor, MDB_val *key, MDB_val *data, MDB_cursor_op op)
1760 if (cursor->mc_eof) {
1761 return MDB_NOTFOUND;
1764 assert(cursor->mc_initialized);
1766 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
1767 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
1768 rc = mdb_cursor_next(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
1769 if (op != MDB_NEXT || rc == MDB_SUCCESS)
1774 top = CURSOR_TOP(cursor);
1777 DPRINTF("cursor_next: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
1779 if (top->mp_ki + 1 >= NUMKEYS(mp)) {
1780 DPRINTF("=====> move to next sibling page");
1781 if (mdb_sibling(cursor, 1) != MDB_SUCCESS) {
1783 return MDB_NOTFOUND;
1785 top = CURSOR_TOP(cursor);
1787 DPRINTF("next page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
1791 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
1792 mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
1794 assert(IS_LEAF(mp));
1795 leaf = NODEPTR(mp, top->mp_ki);
1798 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS))
1801 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
1802 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, NODEDATA(leaf));
1803 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
1804 if (rc != MDB_SUCCESS)
1809 return mdb_set_key(leaf, key);
1813 mdb_cursor_prev(MDB_cursor *cursor, MDB_val *key, MDB_val *data, MDB_cursor_op op)
1820 assert(cursor->mc_initialized);
1822 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
1823 if (op == MDB_PREV || op == MDB_PREV_DUP) {
1824 rc = mdb_cursor_next(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
1825 if (op != MDB_PREV || rc == MDB_SUCCESS)
1830 top = CURSOR_TOP(cursor);
1833 DPRINTF("cursor_prev: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
1835 if (top->mp_ki == 0) {
1836 DPRINTF("=====> move to prev sibling page");
1837 if (mdb_sibling(cursor, 0) != MDB_SUCCESS) {
1838 return MDB_NOTFOUND;
1840 top = CURSOR_TOP(cursor);
1842 top->mp_ki = NUMKEYS(mp) - 1;
1843 DPRINTF("prev page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
1849 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
1850 mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
1852 assert(IS_LEAF(mp));
1853 leaf = NODEPTR(mp, top->mp_ki);
1856 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS))
1859 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
1860 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, NODEDATA(leaf));
1861 rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
1862 if (rc != MDB_SUCCESS)
1867 return mdb_set_key(leaf, key);
1871 mdb_cursor_set(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
1872 MDB_cursor_op op, int *exactp)
1881 assert(key->mv_size > 0);
1883 while (CURSOR_TOP(cursor) != NULL)
1884 cursor_pop_page(cursor);
1886 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, key, cursor, 0, &mpp);
1887 if (rc != MDB_SUCCESS)
1889 assert(IS_LEAF(mpp.mp_page));
1891 top = CURSOR_TOP(cursor);
1892 leaf = mdb_search_node(cursor->mc_txn, cursor->mc_dbi, mpp.mp_page, key, exactp, &top->mp_ki);
1893 if (exactp != NULL && !*exactp) {
1894 /* MDB_SET specified and not an exact match. */
1895 return MDB_NOTFOUND;
1899 DPRINTF("===> inexact leaf not found, goto sibling");
1900 if ((rc = mdb_sibling(cursor, 1)) != MDB_SUCCESS)
1901 return rc; /* no entries matched */
1902 top = CURSOR_TOP(cursor);
1904 mpp.mp_page = top->mp_page;
1905 assert(IS_LEAF(mpp.mp_page));
1906 leaf = NODEPTR(mpp.mp_page, 0);
1909 cursor->mc_initialized = 1;
1913 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
1916 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
1917 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, NODEDATA(leaf));
1918 if (op == MDB_SET || op == MDB_SET_RANGE) {
1919 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
1923 if (op == MDB_GET_BOTH) {
1928 op2 = MDB_SET_RANGE;
1930 rc = mdb_cursor_set(&cursor->mc_xcursor->mx_cursor, data, NULL, op2, ex2p);
1931 if (rc != MDB_SUCCESS)
1937 rc = mdb_set_key(leaf, key);
1938 if (rc == MDB_SUCCESS) {
1939 DPRINTF("==> cursor placed on key %.*s",
1940 (int)key->mv_size, (char *)key->mv_data);
1948 mdb_cursor_first(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
1954 while (CURSOR_TOP(cursor) != NULL)
1955 cursor_pop_page(cursor);
1957 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, NULL, cursor, 0, &mpp);
1958 if (rc != MDB_SUCCESS)
1960 assert(IS_LEAF(mpp.mp_page));
1962 leaf = NODEPTR(mpp.mp_page, 0);
1963 cursor->mc_initialized = 1;
1967 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
1970 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
1971 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, NODEDATA(leaf));
1972 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
1977 return mdb_set_key(leaf, key);
1981 mdb_cursor_last(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
1989 while (CURSOR_TOP(cursor) != NULL)
1990 cursor_pop_page(cursor);
1992 lkey.mv_size = MAXKEYSIZE+1;
1993 lkey.mv_data = NULL;
1995 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, &lkey, cursor, 0, &mpp);
1996 if (rc != MDB_SUCCESS)
1998 assert(IS_LEAF(mpp.mp_page));
2000 leaf = NODEPTR(mpp.mp_page, NUMKEYS(mpp.mp_page)-1);
2001 cursor->mc_initialized = 1;
2004 top = CURSOR_TOP(cursor);
2005 top->mp_ki = NUMKEYS(top->mp_page) - 1;
2008 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2011 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2012 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, NODEDATA(leaf));
2013 rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
2019 return mdb_set_key(leaf, key);
2023 mdb_cursor_get(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
2033 case MDB_GET_BOTH_RANGE:
2041 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2043 } else if (op != MDB_SET_RANGE)
2044 rc = mdb_cursor_set(cursor, key, data, op, NULL);
2046 rc = mdb_cursor_set(cursor, key, data, op, &exact);
2050 case MDB_NEXT_NODUP:
2051 if (!cursor->mc_initialized)
2052 rc = mdb_cursor_first(cursor, key, data);
2054 rc = mdb_cursor_next(cursor, key, data, op);
2058 case MDB_PREV_NODUP:
2059 if (!cursor->mc_initialized || cursor->mc_eof)
2060 rc = mdb_cursor_last(cursor, key, data);
2062 rc = mdb_cursor_prev(cursor, key, data, op);
2065 rc = mdb_cursor_first(cursor, key, data);
2068 rc = mdb_cursor_last(cursor, key, data);
2071 DPRINTF("unhandled/unimplemented cursor operation %u", op);
2079 /* Allocate a page and initialize it
2082 mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num)
2086 if ((dp = mdb_alloc_page(txn, NULL, 0, num)) == NULL)
2088 DPRINTF("allocated new mpage %lu, page size %u",
2089 dp->p.mp_pgno, txn->mt_env->me_psize);
2090 dp->p.mp_flags = flags | P_DIRTY;
2091 dp->p.mp_lower = PAGEHDRSZ;
2092 dp->p.mp_upper = txn->mt_env->me_psize;
2094 if (IS_BRANCH(&dp->p))
2095 txn->mt_dbs[dbi].md_branch_pages++;
2096 else if (IS_LEAF(&dp->p))
2097 txn->mt_dbs[dbi].md_leaf_pages++;
2098 else if (IS_OVERFLOW(&dp->p)) {
2099 txn->mt_dbs[dbi].md_overflow_pages += num;
2100 dp->p.mp_pages = num;
2107 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
2111 sz = LEAFSIZE(key, data);
2112 if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
2113 /* put on overflow page */
2114 sz -= data->mv_size - sizeof(pgno_t);
2117 return sz + sizeof(indx_t);
2121 mdb_branch_size(MDB_env *env, MDB_val *key)
2126 if (sz >= env->me_psize / MDB_MINKEYS) {
2127 /* put on overflow page */
2128 /* not implemented */
2129 /* sz -= key->size - sizeof(pgno_t); */
2132 return sz + sizeof(indx_t);
2136 mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, indx_t indx,
2137 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags)
2140 size_t node_size = NODESIZE;
2143 MDB_dpage *ofp = NULL; /* overflow page */
2145 assert(mp->mp_upper >= mp->mp_lower);
2147 DPRINTF("add node [%.*s] to %s page %lu at index %i, key size %zu",
2148 key ? (int)key->mv_size : 0, key ? (char *)key->mv_data : NULL,
2149 IS_LEAF(mp) ? "leaf" : "branch",
2150 mp->mp_pgno, indx, key ? key->mv_size : 0);
2153 node_size += key->mv_size;
2157 if (F_ISSET(flags, F_BIGDATA)) {
2158 /* Data already on overflow page. */
2159 node_size += sizeof(pgno_t);
2160 } else if (data->mv_size >= txn->mt_env->me_psize / MDB_MINKEYS) {
2161 int ovpages = OVPAGES(data->mv_size, txn->mt_env->me_psize);
2162 /* Put data on overflow page. */
2163 DPRINTF("data size is %zu, put on overflow page",
2165 node_size += sizeof(pgno_t);
2166 if ((ofp = mdb_new_page(txn, dbi, P_OVERFLOW, ovpages)) == NULL)
2168 DPRINTF("allocated overflow page %lu", ofp->p.mp_pgno);
2171 node_size += data->mv_size;
2175 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
2176 DPRINTF("not enough room in page %lu, got %u ptrs",
2177 mp->mp_pgno, NUMKEYS(mp));
2178 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
2179 mp->mp_upper - mp->mp_lower);
2180 DPRINTF("node size = %zu", node_size);
2184 /* Move higher pointers up one slot. */
2185 for (i = NUMKEYS(mp); i > indx; i--)
2186 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
2188 /* Adjust free space offsets. */
2189 ofs = mp->mp_upper - node_size;
2190 assert(ofs >= mp->mp_lower + sizeof(indx_t));
2191 mp->mp_ptrs[indx] = ofs;
2193 mp->mp_lower += sizeof(indx_t);
2195 /* Write the node data. */
2196 node = NODEPTR(mp, indx);
2197 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
2198 node->mn_flags = flags;
2200 node->mn_dsize = data->mv_size;
2202 node->mn_pgno = pgno;
2205 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
2210 if (F_ISSET(flags, F_BIGDATA))
2211 memcpy(node->mn_data + key->mv_size, data->mv_data,
2214 memcpy(node->mn_data + key->mv_size, data->mv_data,
2217 memcpy(node->mn_data + key->mv_size, &ofp->p.mp_pgno,
2219 memcpy(METADATA(&ofp->p), data->mv_data, data->mv_size);
2227 mdb_del_node(MDB_page *mp, indx_t indx)
2230 indx_t i, j, numkeys, ptr;
2234 DPRINTF("delete node %u on %s page %lu", indx,
2235 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
2236 assert(indx < NUMKEYS(mp));
2238 node = NODEPTR(mp, indx);
2239 sz = NODESIZE + node->mn_ksize;
2241 if (F_ISSET(node->mn_flags, F_BIGDATA))
2242 sz += sizeof(pgno_t);
2244 sz += NODEDSZ(node);
2247 ptr = mp->mp_ptrs[indx];
2248 numkeys = NUMKEYS(mp);
2249 for (i = j = 0; i < numkeys; i++) {
2251 mp->mp_ptrs[j] = mp->mp_ptrs[i];
2252 if (mp->mp_ptrs[i] < ptr)
2253 mp->mp_ptrs[j] += sz;
2258 base = (char *)mp + mp->mp_upper;
2259 memmove(base + sz, base, ptr - mp->mp_upper);
2261 mp->mp_lower -= sizeof(indx_t);
2266 mdb_xcursor_init0(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
2271 mx->mx_txn.mt_dbxs = mx->mx_dbxs;
2272 mx->mx_txn.mt_dbs = mx->mx_dbs;
2273 mx->mx_dbxs[0] = txn->mt_dbxs[0];
2274 mx->mx_dbxs[1] = txn->mt_dbxs[1];
2276 mx->mx_dbxs[2] = txn->mt_dbxs[dbi];
2281 mx->mx_dbxs[dbn+1].md_parent = dbn;
2282 mx->mx_dbxs[dbn+1].md_cmp = mx->mx_dbxs[dbn].md_dcmp;
2283 mx->mx_dbxs[dbn+1].md_rel = mx->mx_dbxs[dbn].md_rel;
2284 mx->mx_dbxs[dbn+1].md_dirty = 0;
2285 mx->mx_txn.mt_numdbs = dbn+2;
2287 SLIST_INIT(&mx->mx_cursor.mc_stack);
2288 mx->mx_cursor.mc_txn = &mx->mx_txn;
2289 mx->mx_cursor.mc_dbi = dbn+1;
2293 mdb_xcursor_init1(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx, MDB_db *db)
2295 mx->mx_dbs[0] = txn->mt_dbs[0];
2296 mx->mx_dbs[1] = txn->mt_dbs[1];
2298 mx->mx_dbs[2] = txn->mt_dbs[dbi];
2299 mx->mx_dbs[3] = *db;
2301 mx->mx_dbs[2] = *db;
2306 mdb_xcursor_fini(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
2308 txn->mt_dbs[0] = mx->mx_dbs[0];
2309 txn->mt_dbs[1] = mx->mx_dbs[1];
2310 txn->mt_dbxs[0].md_dirty = mx->mx_dbxs[0].md_dirty;
2311 txn->mt_dbxs[1].md_dirty = mx->mx_dbxs[1].md_dirty;
2313 txn->mt_dbs[dbi] = mx->mx_dbs[2];
2314 txn->mt_dbxs[dbi].md_dirty = mx->mx_dbxs[2].md_dirty;
2319 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
2322 size_t size = sizeof(MDB_cursor);
2324 if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
2327 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
2328 size += sizeof(MDB_xcursor);
2330 if ((cursor = calloc(1, size)) != NULL) {
2331 SLIST_INIT(&cursor->mc_stack);
2332 cursor->mc_dbi = dbi;
2333 cursor->mc_txn = txn;
2334 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
2335 MDB_xcursor *mx = (MDB_xcursor *)(cursor + 1);
2336 cursor->mc_xcursor = mx;
2337 mdb_xcursor_init0(txn, dbi, mx);
2349 mdb_cursor_close(MDB_cursor *cursor)
2351 if (cursor != NULL) {
2352 while(!CURSOR_EMPTY(cursor))
2353 cursor_pop_page(cursor);
2354 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2355 mdb_xcursor_fini(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor);
2356 while(!CURSOR_EMPTY(&cursor->mc_xcursor->mx_cursor))
2357 cursor_pop_page(&cursor->mc_xcursor->mx_cursor);
2365 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
2367 indx_t ptr, i, numkeys;
2373 node = NODEPTR(mp, indx);
2374 ptr = mp->mp_ptrs[indx];
2375 DPRINTF("update key %u (ofs %u) [%.*s] to [%.*s] on page %lu",
2377 (int)node->mn_ksize, (char *)NODEKEY(node),
2378 (int)key->mv_size, (char *)key->mv_data,
2381 delta = key->mv_size - node->mn_ksize;
2383 if (delta > 0 && SIZELEFT(mp) < delta) {
2384 DPRINTF("OUCH! Not enough room, delta = %d", delta);
2388 numkeys = NUMKEYS(mp);
2389 for (i = 0; i < numkeys; i++) {
2390 if (mp->mp_ptrs[i] <= ptr)
2391 mp->mp_ptrs[i] -= delta;
2394 base = (char *)mp + mp->mp_upper;
2395 len = ptr - mp->mp_upper + NODESIZE;
2396 memmove(base - delta, base, len);
2397 mp->mp_upper -= delta;
2399 node = NODEPTR(mp, indx);
2400 node->mn_ksize = key->mv_size;
2403 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
2408 /* Move a node from src to dst.
2411 mdb_move_node(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, indx_t srcindx,
2412 MDB_pageparent *dst, indx_t dstindx)
2418 srcnode = NODEPTR(src->mp_page, srcindx);
2419 DPRINTF("moving %s node %u [%.*s] on page %lu to node %u on page %lu",
2420 IS_LEAF(src->mp_page) ? "leaf" : "branch",
2422 (int)srcnode->mn_ksize, (char *)NODEKEY(srcnode),
2423 src->mp_page->mp_pgno,
2424 dstindx, dst->mp_page->mp_pgno);
2426 /* Mark src and dst as dirty. */
2427 if ((rc = mdb_touch(txn, src)) ||
2428 (rc = mdb_touch(txn, dst)))
2431 /* Add the node to the destination page.
2433 key.mv_size = srcnode->mn_ksize;
2434 key.mv_data = NODEKEY(srcnode);
2435 data.mv_size = NODEDSZ(srcnode);
2436 data.mv_data = NODEDATA(srcnode);
2437 rc = mdb_add_node(txn, dbi, dst->mp_page, dstindx, &key, &data, NODEPGNO(srcnode),
2439 if (rc != MDB_SUCCESS)
2442 /* Delete the node from the source page.
2444 mdb_del_node(src->mp_page, srcindx);
2446 /* Update the parent separators.
2448 if (srcindx == 0 && src->mp_pi != 0) {
2449 DPRINTF("update separator for source page %lu to [%.*s]",
2450 src->mp_page->mp_pgno, (int)key.mv_size, (char *)key.mv_data);
2451 if ((rc = mdb_update_key(src->mp_parent, src->mp_pi,
2452 &key)) != MDB_SUCCESS)
2456 if (srcindx == 0 && IS_BRANCH(src->mp_page)) {
2458 nullkey.mv_size = 0;
2459 assert(mdb_update_key(src->mp_page, 0, &nullkey) == MDB_SUCCESS);
2462 if (dstindx == 0 && dst->mp_pi != 0) {
2463 DPRINTF("update separator for destination page %lu to [%.*s]",
2464 dst->mp_page->mp_pgno, (int)key.mv_size, (char *)key.mv_data);
2465 if ((rc = mdb_update_key(dst->mp_parent, dst->mp_pi,
2466 &key)) != MDB_SUCCESS)
2470 if (dstindx == 0 && IS_BRANCH(dst->mp_page)) {
2472 nullkey.mv_size = 0;
2473 assert(mdb_update_key(dst->mp_page, 0, &nullkey) == MDB_SUCCESS);
2480 mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, MDB_pageparent *dst)
2489 DPRINTF("merging page %lu and %lu", src->mp_page->mp_pgno, dst->mp_page->mp_pgno);
2491 assert(txn != NULL);
2492 assert(src->mp_parent); /* can't merge root page */
2493 assert(dst->mp_parent);
2495 /* Mark src and dst as dirty. */
2496 if ((rc = mdb_touch(txn, src)) ||
2497 (rc = mdb_touch(txn, dst)))
2500 /* Move all nodes from src to dst.
2502 for (i = 0; i < NUMKEYS(src->mp_page); i++) {
2503 srcnode = NODEPTR(src->mp_page, i);
2505 key.mv_size = srcnode->mn_ksize;
2506 key.mv_data = NODEKEY(srcnode);
2507 data.mv_size = NODEDSZ(srcnode);
2508 data.mv_data = NODEDATA(srcnode);
2509 rc = mdb_add_node(txn, dbi, dst->mp_page, NUMKEYS(dst->mp_page), &key,
2510 &data, NODEPGNO(srcnode), srcnode->mn_flags);
2511 if (rc != MDB_SUCCESS)
2515 DPRINTF("dst page %lu now has %u keys (%.1f%% filled)",
2516 dst->mp_page->mp_pgno, NUMKEYS(dst->mp_page), (float)PAGEFILL(txn->mt_env, dst->mp_page) / 10);
2518 /* Unlink the src page from parent.
2520 mdb_del_node(src->mp_parent, src->mp_pi);
2521 if (src->mp_pi == 0) {
2523 if ((rc = mdb_update_key(src->mp_parent, 0, &key)) != MDB_SUCCESS)
2527 if (IS_LEAF(src->mp_page))
2528 txn->mt_dbs[dbi].md_leaf_pages--;
2530 txn->mt_dbs[dbi].md_branch_pages--;
2532 mpp.mp_page = src->mp_parent;
2533 dh = (MDB_dhead *)src->mp_parent;
2535 mpp.mp_parent = dh->md_parent;
2536 mpp.mp_pi = dh->md_pi;
2538 return mdb_rebalance(txn, dbi, &mpp);
2541 #define FILL_THRESHOLD 250
2544 mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mpp)
2549 indx_t si = 0, di = 0;
2551 assert(txn != NULL);
2552 assert(mpp != NULL);
2554 DPRINTF("rebalancing %s page %lu (has %u keys, %.1f%% full)",
2555 IS_LEAF(mpp->mp_page) ? "leaf" : "branch",
2556 mpp->mp_page->mp_pgno, NUMKEYS(mpp->mp_page), (float)PAGEFILL(txn->mt_env, mpp->mp_page) / 10);
2558 if (PAGEFILL(txn->mt_env, mpp->mp_page) >= FILL_THRESHOLD) {
2559 DPRINTF("no need to rebalance page %lu, above fill threshold",
2560 mpp->mp_page->mp_pgno);
2564 if (mpp->mp_parent == NULL) {
2565 if (NUMKEYS(mpp->mp_page) == 0) {
2566 DPRINTF("tree is completely empty");
2567 txn->mt_dbs[dbi].md_root = P_INVALID;
2568 txn->mt_dbs[dbi].md_depth--;
2569 txn->mt_dbs[dbi].md_leaf_pages--;
2570 } else if (IS_BRANCH(mpp->mp_page) && NUMKEYS(mpp->mp_page) == 1) {
2571 DPRINTF("collapsing root page!");
2572 txn->mt_dbs[dbi].md_root = NODEPGNO(NODEPTR(mpp->mp_page, 0));
2573 if ((root = mdb_get_page(txn, txn->mt_dbs[dbi].md_root)) == NULL)
2575 txn->mt_dbs[dbi].md_depth--;
2576 txn->mt_dbs[dbi].md_branch_pages--;
2578 DPRINTF("root page doesn't need rebalancing");
2582 /* The parent (branch page) must have at least 2 pointers,
2583 * otherwise the tree is invalid.
2585 assert(NUMKEYS(mpp->mp_parent) > 1);
2587 /* Leaf page fill factor is below the threshold.
2588 * Try to move keys from left or right neighbor, or
2589 * merge with a neighbor page.
2594 if (mpp->mp_pi == 0) {
2595 /* We're the leftmost leaf in our parent.
2597 DPRINTF("reading right neighbor");
2598 node = NODEPTR(mpp->mp_parent, mpp->mp_pi + 1);
2599 if ((npp.mp_page = mdb_get_page(txn, NODEPGNO(node))) == NULL)
2601 npp.mp_pi = mpp->mp_pi + 1;
2603 di = NUMKEYS(mpp->mp_page);
2605 /* There is at least one neighbor to the left.
2607 DPRINTF("reading left neighbor");
2608 node = NODEPTR(mpp->mp_parent, mpp->mp_pi - 1);
2609 if ((npp.mp_page = mdb_get_page(txn, NODEPGNO(node))) == NULL)
2611 npp.mp_pi = mpp->mp_pi - 1;
2612 si = NUMKEYS(npp.mp_page) - 1;
2615 npp.mp_parent = mpp->mp_parent;
2617 DPRINTF("found neighbor page %lu (%u keys, %.1f%% full)",
2618 npp.mp_page->mp_pgno, NUMKEYS(npp.mp_page), (float)PAGEFILL(txn->mt_env, npp.mp_page) / 10);
2620 /* If the neighbor page is above threshold and has at least two
2621 * keys, move one key from it.
2623 * Otherwise we should try to merge them.
2625 if (PAGEFILL(txn->mt_env, npp.mp_page) >= FILL_THRESHOLD && NUMKEYS(npp.mp_page) >= 2)
2626 return mdb_move_node(txn, dbi, &npp, si, mpp, di);
2627 else { /* FIXME: if (has_enough_room()) */
2628 if (mpp->mp_pi == 0)
2629 return mdb_merge(txn, dbi, &npp, mpp);
2631 return mdb_merge(txn, dbi, mpp, &npp);
2636 mdb_del0(MDB_txn *txn, MDB_dbi dbi, unsigned int ki, MDB_pageparent *mpp, MDB_node *leaf)
2640 /* add overflow pages to free list */
2641 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
2645 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
2646 ovpages = OVPAGES(NODEDSZ(leaf), txn->mt_env->me_psize);
2647 for (i=0; i<ovpages; i++) {
2648 DPRINTF("freed ov page %lu", pg);
2649 mdb_idl_insert(txn->mt_free_pgs, pg);
2653 mdb_del_node(mpp->mp_page, ki);
2654 txn->mt_dbs[dbi].md_entries--;
2655 rc = mdb_rebalance(txn, dbi, mpp);
2656 if (rc != MDB_SUCCESS)
2657 txn->mt_flags |= MDB_TXN_ERROR;
2663 mdb_del(MDB_txn *txn, MDB_dbi dbi,
2664 MDB_val *key, MDB_val *data,
2672 DPRINTF("========> delete key %.*s", (int)key->mv_size, (char *)key->mv_data);
2674 assert(key != NULL);
2676 if (txn == NULL || dbi >= txn->mt_numdbs)
2679 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2683 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2687 mpp.mp_parent = NULL;
2689 if ((rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp)) != MDB_SUCCESS)
2692 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
2693 if (leaf == NULL || !exact) {
2694 return MDB_NOTFOUND;
2697 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
2701 mdb_xcursor_init0(txn, dbi, &mx);
2702 mdb_xcursor_init1(txn, dbi, &mx, NODEDATA(leaf));
2703 if (flags == MDB_DEL_DUP) {
2704 rc = mdb_del(&mx.mx_txn, mx.mx_cursor.mc_dbi, data, NULL, 0);
2705 mdb_xcursor_fini(txn, dbi, &mx);
2706 if (rc != MDB_SUCCESS)
2708 /* If sub-DB still has entries, we're done */
2709 if (mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi].md_root != P_INVALID) {
2710 memcpy(NODEDATA(leaf), &mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi],
2714 /* otherwise fall thru and delete the sub-DB */
2716 /* add all the child DB's pages to the free list */
2717 rc = mdb_search_page(&mx.mx_txn, mx.mx_cursor.mc_dbi,
2718 NULL, &mx.mx_cursor, 0, &mp2);
2719 if (rc == MDB_SUCCESS) {
2720 MDB_ppage *top, *parent;
2724 cursor_pop_page(&mx.mx_cursor);
2725 top = CURSOR_TOP(&mx.mx_cursor);
2727 parent = SLIST_NEXT(top, mp_entry);
2728 while (parent != NULL) {
2729 for (i=0; i<NUMKEYS(top->mp_page); i++) {
2730 ni = NODEPTR(top->mp_page, i);
2731 mdb_idl_insert(txn->mt_free_pgs, ni->mn_pgno);
2735 if (parent->mp_ki >= NUMKEYS(parent->mp_page)) {
2736 cursor_pop_page(&mx.mx_cursor);
2737 top = CURSOR_TOP(&mx.mx_cursor);
2738 parent = SLIST_NEXT(top, mp_entry);
2740 ni = NODEPTR(parent->mp_page, parent->mp_ki);
2741 top->mp_page = mdb_get_page(&mx.mx_txn, ni->mn_pgno);
2746 mdb_idl_insert(txn->mt_free_pgs, mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi].md_root);
2751 if (data && (rc = mdb_read_data(txn, leaf, data)) != MDB_SUCCESS)
2754 return mdb_del0(txn, dbi, ki, &mpp, leaf);
2757 /* Split page <*mpp>, and insert <key,(data|newpgno)> in either left or
2758 * right sibling, at index <*newindxp> (as if unsplit). Updates *mpp and
2759 * *newindxp with the actual values after split, ie if *mpp and *newindxp
2760 * refer to a node in the new right sibling page.
2763 mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp, unsigned int *newindxp,
2764 MDB_val *newkey, MDB_val *newdata, pgno_t newpgno)
2767 int rc = MDB_SUCCESS, ins_new = 0;
2770 unsigned int i, j, split_indx;
2772 MDB_val sepkey, rkey, rdata;
2774 MDB_dpage *mdp, *rdp, *pdp;
2777 assert(txn != NULL);
2779 dh = ((MDB_dhead *)*mpp) - 1;
2780 mdp = (MDB_dpage *)dh;
2781 newindx = *newindxp;
2783 DPRINTF("-----> splitting %s page %lu and adding [%.*s] at index %i",
2784 IS_LEAF(&mdp->p) ? "leaf" : "branch", mdp->p.mp_pgno,
2785 (int)newkey->mv_size, (char *)newkey->mv_data, *newindxp);
2787 if (mdp->h.md_parent == NULL) {
2788 if ((pdp = mdb_new_page(txn, dbi, P_BRANCH, 1)) == NULL)
2791 mdp->h.md_parent = &pdp->p;
2792 txn->mt_dbs[dbi].md_root = pdp->p.mp_pgno;
2793 DPRINTF("root split! new root = %lu", pdp->p.mp_pgno);
2794 txn->mt_dbs[dbi].md_depth++;
2796 /* Add left (implicit) pointer. */
2797 if (mdb_add_node(txn, dbi, &pdp->p, 0, NULL, NULL,
2798 mdp->p.mp_pgno, 0) != MDB_SUCCESS)
2801 DPRINTF("parent branch page is %lu", mdp->h.md_parent->mp_pgno);
2804 /* Create a right sibling. */
2805 if ((rdp = mdb_new_page(txn, dbi, mdp->p.mp_flags, 1)) == NULL)
2807 rdp->h.md_parent = mdp->h.md_parent;
2808 rdp->h.md_pi = mdp->h.md_pi + 1;
2809 DPRINTF("new right sibling: page %lu", rdp->p.mp_pgno);
2811 /* Move half of the keys to the right sibling. */
2812 if ((copy = malloc(txn->mt_env->me_psize)) == NULL)
2814 memcpy(copy, &mdp->p, txn->mt_env->me_psize);
2815 memset(&mdp->p.mp_ptrs, 0, txn->mt_env->me_psize - PAGEHDRSZ);
2816 mdp->p.mp_lower = PAGEHDRSZ;
2817 mdp->p.mp_upper = txn->mt_env->me_psize;
2819 split_indx = NUMKEYS(copy) / 2 + 1;
2821 /* First find the separating key between the split pages.
2823 memset(&sepkey, 0, sizeof(sepkey));
2824 if (newindx == split_indx) {
2825 sepkey.mv_size = newkey->mv_size;
2826 sepkey.mv_data = newkey->mv_data;
2828 node = NODEPTR(copy, split_indx);
2829 sepkey.mv_size = node->mn_ksize;
2830 sepkey.mv_data = NODEKEY(node);
2833 DPRINTF("separator is [%.*s]", (int)sepkey.mv_size, (char *)sepkey.mv_data);
2835 /* Copy separator key to the parent.
2837 if (SIZELEFT(rdp->h.md_parent) < mdb_branch_size(txn->mt_env, &sepkey)) {
2838 rc = mdb_split(txn, dbi, &rdp->h.md_parent, &rdp->h.md_pi,
2839 &sepkey, NULL, rdp->p.mp_pgno);
2841 /* Right page might now have changed parent.
2842 * Check if left page also changed parent.
2844 if (rdp->h.md_parent != mdp->h.md_parent &&
2845 mdp->h.md_pi >= NUMKEYS(mdp->h.md_parent)) {
2846 mdp->h.md_parent = rdp->h.md_parent;
2847 mdp->h.md_pi = rdp->h.md_pi - 1;
2850 rc = mdb_add_node(txn, dbi, rdp->h.md_parent, rdp->h.md_pi,
2851 &sepkey, NULL, rdp->p.mp_pgno, 0);
2853 if (rc != MDB_SUCCESS) {
2858 for (i = j = 0; i <= NUMKEYS(copy); j++) {
2859 if (i < split_indx) {
2860 /* Re-insert in left sibling. */
2863 /* Insert in right sibling. */
2864 if (i == split_indx)
2865 /* Reset insert index for right sibling. */
2866 j = (i == newindx && ins_new);
2870 if (i == newindx && !ins_new) {
2871 /* Insert the original entry that caused the split. */
2872 rkey.mv_data = newkey->mv_data;
2873 rkey.mv_size = newkey->mv_size;
2874 if (IS_LEAF(&mdp->p)) {
2875 rdata.mv_data = newdata->mv_data;
2876 rdata.mv_size = newdata->mv_size;
2883 /* Update page and index for the new key. */
2886 } else if (i == NUMKEYS(copy)) {
2889 node = NODEPTR(copy, i);
2890 rkey.mv_data = NODEKEY(node);
2891 rkey.mv_size = node->mn_ksize;
2892 if (IS_LEAF(&mdp->p)) {
2893 rdata.mv_data = NODEDATA(node);
2894 rdata.mv_size = node->mn_dsize;
2896 pgno = node->mn_pgno;
2897 flags = node->mn_flags;
2902 if (!IS_LEAF(&mdp->p) && j == 0) {
2903 /* First branch index doesn't need key data. */
2907 rc = mdb_add_node(txn, dbi, &pdp->p, j, &rkey, &rdata, pgno,flags);
2915 mdb_put0(MDB_txn *txn, MDB_dbi dbi,
2916 MDB_val *key, MDB_val *data, unsigned int flags)
2918 int rc = MDB_SUCCESS, exact;
2922 MDB_val xdata, *rdata;
2925 DPRINTF("==> put key %.*s, size %zu, data size %zu",
2926 (int)key->mv_size, (char *)key->mv_data, key->mv_size, data->mv_size);
2928 mpp.mp_parent = NULL;
2930 rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp);
2931 if (rc == MDB_SUCCESS) {
2932 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
2933 if (leaf && exact) {
2934 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
2937 if (flags == MDB_NOOVERWRITE) {
2938 DPRINTF("duplicate key %.*s",
2939 (int)key->mv_size, (char *)key->mv_data);
2940 return MDB_KEYEXIST;
2942 /* same size, just replace it */
2943 if (NODEDSZ(leaf) == data->mv_size) {
2944 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
2947 mdb_del_node(mpp.mp_page, ki);
2949 if (leaf == NULL) { /* append if not found */
2950 ki = NUMKEYS(mpp.mp_page);
2951 DPRINTF("appending key at index %i", ki);
2953 } else if (rc == MDB_NOTFOUND) {
2955 /* new file, just write a root leaf page */
2956 DPRINTF("allocating new root leaf page");
2957 if ((dp = mdb_new_page(txn, dbi, P_LEAF, 1)) == NULL) {
2960 mpp.mp_page = &dp->p;
2961 txn->mt_dbs[dbi].md_root = mpp.mp_page->mp_pgno;
2962 txn->mt_dbs[dbi].md_depth++;
2968 assert(IS_LEAF(mpp.mp_page));
2969 DPRINTF("there are %u keys, should insert new key at index %i",
2970 NUMKEYS(mpp.mp_page), ki);
2972 /* For sorted dups, the data item at this level is a DB record
2973 * for a child DB; the actual data elements are stored as keys
2976 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
2978 xdata.mv_size = sizeof(MDB_db);
2979 xdata.mv_data = &dummy;
2980 memset(&dummy, 0, sizeof(dummy));
2981 dummy.md_root = P_INVALID;
2986 if (SIZELEFT(mpp.mp_page) < mdb_leaf_size(txn->mt_env, key, data)) {
2987 rc = mdb_split(txn, dbi, &mpp.mp_page, &ki, key, data, P_INVALID);
2989 /* There is room already in this leaf page. */
2990 rc = mdb_add_node(txn, dbi, mpp.mp_page, ki, key, data, 0, 0);
2993 if (rc != MDB_SUCCESS)
2994 txn->mt_flags |= MDB_TXN_ERROR;
2996 txn->mt_dbs[dbi].md_entries++;
2998 /* Remember if we just added a subdatabase */
2999 if (flags & F_SUBDATA) {
3000 leaf = NODEPTR(mpp.mp_page, ki);
3001 leaf->mn_flags |= F_SUBDATA;
3004 /* Now store the actual data in the child DB. Note that we're
3005 * storing the user data in the keys field, so there are strict
3006 * size limits on dupdata. The actual data fields of the child
3007 * DB are all zero size.
3009 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
3012 leaf = NODEPTR(mpp.mp_page, ki);
3014 mdb_xcursor_init0(txn, dbi, &mx);
3015 mdb_xcursor_init1(txn, dbi, &mx, NODEDATA(leaf));
3018 if (flags == MDB_NODUPDATA)
3019 flags = MDB_NOOVERWRITE;
3020 rc = mdb_put0(&mx.mx_txn, mx.mx_cursor.mc_dbi, data, &xdata, flags);
3021 mdb_xcursor_fini(txn, dbi, &mx);
3022 memcpy(NODEDATA(leaf), &mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi],
3032 mdb_put(MDB_txn *txn, MDB_dbi dbi,
3033 MDB_val *key, MDB_val *data, unsigned int flags)
3035 assert(key != NULL);
3036 assert(data != NULL);
3038 if (txn == NULL || dbi >= txn->mt_numdbs)
3041 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3045 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3049 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA)) != flags)
3052 return mdb_put0(txn, dbi, key, data, flags);
3056 mdbenv_get_flags(MDB_env *env, unsigned int *arg)
3061 *arg = env->me_flags;
3066 mdbenv_get_path(MDB_env *env, const char **arg)
3071 *arg = env->me_path;
3076 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
3078 arg->ms_psize = env->me_psize;
3079 arg->ms_depth = db->md_depth;
3080 arg->ms_branch_pages = db->md_branch_pages;
3081 arg->ms_leaf_pages = db->md_leaf_pages;
3082 arg->ms_overflow_pages = db->md_overflow_pages;
3083 arg->ms_entries = db->md_entries;
3088 mdbenv_stat(MDB_env *env, MDB_stat *arg)
3090 if (env == NULL || arg == NULL)
3093 return mdb_stat0(env, &env->me_meta->mm_dbs[MAIN_DBI], arg);
3096 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
3109 /* Is the DB already open? */
3111 for (i=2; i<txn->mt_numdbs; i++) {
3112 if (len == txn->mt_dbxs[i].md_name.mv_size &&
3113 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
3119 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
3122 /* Find the DB info */
3124 key.mv_data = (void *)name;
3125 rc = mdb_get(txn, MAIN_DBI, &key, &data);
3127 /* Create if requested */
3128 if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
3130 data.mv_size = sizeof(MDB_db);
3131 data.mv_data = &dummy;
3132 memset(&dummy, 0, sizeof(dummy));
3133 dummy.md_root = P_INVALID;
3134 dummy.md_flags = flags & 0xffff;
3135 rc = mdb_put0(txn, MAIN_DBI, &key, &data, F_SUBDATA);
3139 /* OK, got info, add to table */
3140 if (rc == MDB_SUCCESS) {
3141 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
3142 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
3143 txn->mt_dbxs[txn->mt_numdbs].md_cmp = NULL;
3144 txn->mt_dbxs[txn->mt_numdbs].md_dcmp = NULL;
3145 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
3146 txn->mt_dbxs[txn->mt_numdbs].md_parent = MAIN_DBI;
3147 txn->mt_dbxs[txn->mt_numdbs].md_dirty = dirty;
3148 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
3149 *dbi = txn->mt_numdbs;
3156 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
3158 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
3161 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
3164 void mdb_close(MDB_txn *txn, MDB_dbi dbi)
3167 if (dbi <= MAIN_DBI || dbi >= txn->mt_numdbs)
3169 ptr = txn->mt_dbxs[dbi].md_name.mv_data;
3170 txn->mt_dbxs[dbi].md_name.mv_data = NULL;
3171 txn->mt_dbxs[dbi].md_name.mv_size = 0;