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
57 #define ULONG unsigned long
66 #if DEBUG && defined(__GNUC__)
67 # define DPRINTF(fmt, ...) \
68 fprintf(stderr, "%s:%d: " fmt "\n", __func__, __LINE__, ##__VA_ARGS__)
70 # define DPRINTF(...) ((void) 0)
75 #define MDB_MAGIC 0xBEEFC0DE
77 #define MAXKEYSIZE 511
79 #define P_INVALID (~0UL)
81 #define F_ISSET(w, f) (((w) & (f)) == (f))
83 typedef uint16_t indx_t;
85 #define DEFAULT_READERS 126
86 #define DEFAULT_MAPSIZE 1048576
88 /* Lock descriptor stuff */
93 typedef struct MDB_rxbody {
98 #define CACHELINE 64 /* most CPUs. Itanium uses 128 */
101 typedef struct MDB_reader {
103 /* cache line alignment */
104 char pad[CACHELINE-sizeof(MDB_rxbody)];
109 uint32_t mt_version; \
110 pthread_mutex_t mt_mutex; \
112 uint32_t mt_numreaders
113 typedef struct MDB_txbody {
117 typedef struct MDB_txninfo {
119 char pad[CACHELINE-sizeof(MDB_txbody)];
120 pthread_mutex_t mt_wmutex;
121 char pad2[CACHELINE-sizeof(pthread_mutex_t)];
122 MDB_reader mt_readers[1];
125 /* Common header for all page types. Overflow pages
126 * occupy a number of contiguous pages with no
127 * headers on any page after the first.
129 typedef struct MDB_page { /* represents a page of storage */
130 #define mp_pgno mp_p.p_pgno
132 pgno_t p_pgno; /* page number */
135 #define P_BRANCH 0x01 /* branch page */
136 #define P_LEAF 0x02 /* leaf page */
137 #define P_OVERFLOW 0x04 /* overflow page */
138 #define P_META 0x08 /* meta page */
139 #define P_DIRTY 0x10 /* dirty page */
141 #define mp_lower mp_pb.pb.pb_lower
142 #define mp_upper mp_pb.pb.pb_upper
143 #define mp_pages mp_pb.pb_pages
146 indx_t pb_lower; /* lower bound of free space */
147 indx_t pb_upper; /* upper bound of free space */
149 uint32_t pb_pages; /* number of overflow pages */
151 indx_t mp_ptrs[1]; /* dynamic size */
154 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
156 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
157 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
158 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
159 ((env)->me_psize - PAGEHDRSZ))
160 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
161 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
162 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
164 #define OVPAGES(size, psize) (PAGEHDRSZ + size + psize - 1) / psize;
166 typedef struct MDB_db {
170 ULONG md_branch_pages;
172 ULONG md_overflow_pages;
180 typedef struct MDB_meta { /* meta (footer) page content */
183 void *mm_address; /* address for fixed mapping */
184 size_t mm_mapsize; /* size of mmap region */
185 MDB_db mm_dbs[2]; /* first is free space, 2nd is main db */
186 #define mm_psize mm_dbs[0].md_pad
187 #define mm_flags mm_dbs[0].md_flags
188 pgno_t mm_last_pg; /* last used page in file */
189 ULONG mm_txnid; /* txnid that committed this page */
192 typedef struct MDB_dhead { /* a dirty page */
193 STAILQ_ENTRY(MDB_dpage) md_next; /* queue of dirty pages */
195 unsigned md_pi; /* parent index */
199 typedef struct MDB_dpage {
204 STAILQ_HEAD(dirty_queue, MDB_dpage); /* FIXME: use a sorted data structure */
206 typedef struct MDB_oldpages {
207 struct MDB_oldpages *mo_next;
209 pgno_t mo_pages[1]; /* dynamic */
212 typedef struct MDB_pageparent {
218 static MDB_dpage *mdb_alloc_page(MDB_txn *txn, MDB_page *parent, unsigned int parent_idx, int num);
219 static int mdb_touch(MDB_txn *txn, MDB_pageparent *mp);
221 typedef struct MDB_ppage { /* ordered list of pages */
222 SLIST_ENTRY(MDB_ppage) mp_entry;
224 unsigned int mp_ki; /* cursor index on page */
226 SLIST_HEAD(page_stack, MDB_ppage);
228 #define CURSOR_EMPTY(c) SLIST_EMPTY(&(c)->mc_stack)
229 #define CURSOR_TOP(c) SLIST_FIRST(&(c)->mc_stack)
230 #define CURSOR_POP(c) SLIST_REMOVE_HEAD(&(c)->mc_stack, mp_entry)
231 #define CURSOR_PUSH(c,p) SLIST_INSERT_HEAD(&(c)->mc_stack, p, mp_entry)
237 struct page_stack mc_stack; /* stack of parent pages */
239 short mc_initialized; /* 1 if initialized */
240 short mc_eof; /* 1 if end is reached */
241 struct MDB_xcursor *mc_xcursor;
244 #define METAHASHLEN offsetof(MDB_meta, mm_hash)
245 #define METADATA(p) ((void *)((char *)p + PAGEHDRSZ))
247 typedef struct MDB_node {
248 #define mn_pgno mn_p.np_pgno
249 #define mn_dsize mn_p.np_dsize
251 pgno_t np_pgno; /* child page number */
252 uint32_t np_dsize; /* leaf data size */
254 unsigned int mn_flags:4;
255 unsigned int mn_ksize:12; /* key size */
256 #define F_BIGDATA 0x01 /* data put on overflow page */
261 typedef struct MDB_dbx {
263 MDB_cmp_func *md_cmp; /* user compare function */
264 MDB_cmp_func *md_dcmp; /* user dupsort function */
265 MDB_rel_func *md_rel; /* user relocate function */
267 unsigned int md_dirty;
271 pgno_t mt_next_pgno; /* next unallocated page */
275 pgno_t *mt_free_pgs; /* this is an IDL */
277 struct dirty_queue *dirty_queue; /* modified pages */
280 MDB_dbx *mt_dbxs; /* array */
282 unsigned int mt_numdbs;
284 #define MDB_TXN_RDONLY 0x01 /* read-only transaction */
285 #define MDB_TXN_ERROR 0x02 /* an error has occurred */
286 #define MDB_TXN_METOGGLE 0x04 /* used meta page 1 */
287 unsigned int mt_flags;
290 /* Context for sorted-dup records */
291 typedef struct MDB_xcursor {
292 MDB_cursor mx_cursor;
302 unsigned int me_maxreaders;
303 unsigned int me_numdbs;
304 unsigned int me_maxdbs;
307 MDB_txninfo *me_txns;
308 MDB_meta *me_metas[2];
310 MDB_txn *me_txn; /* current write transaction */
312 off_t me_size; /* current file size */
313 unsigned int me_psize;
315 MDB_dbx *me_dbxs; /* array */
317 MDB_oldpages *me_pghead;
318 pthread_key_t me_txkey; /* thread-key for readers */
319 pgno_t me_free_pgs[MDB_IDL_UM_SIZE];
322 #define NODESIZE offsetof(MDB_node, mn_data)
324 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
325 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
326 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
327 #define NODEKEY(node) (void *)((node)->mn_data)
328 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
329 #define NODEPGNO(node) ((node)->mn_pgno)
330 #define NODEDSZ(node) ((node)->mn_dsize)
332 #define MDB_COMMIT_PAGES 64 /* max number of pages to write in one commit */
333 #define MDB_MAXCACHE_DEF 1024 /* max number of pages to keep in cache */
335 static int mdb_search_page_root(MDB_txn *txn,
336 MDB_dbi dbi, MDB_val *key,
337 MDB_cursor *cursor, int modify,
338 MDB_pageparent *mpp);
339 static int mdb_search_page(MDB_txn *txn,
340 MDB_dbi dbi, MDB_val *key,
341 MDB_cursor *cursor, int modify,
342 MDB_pageparent *mpp);
344 static int mdbenv_read_header(MDB_env *env, MDB_meta *meta);
345 static int mdbenv_read_meta(MDB_env *env, int *which);
346 static int mdbenv_write_meta(MDB_txn *txn);
347 static MDB_page *mdb_get_page(MDB_txn *txn, pgno_t pgno);
349 static MDB_node *mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp,
350 MDB_val *key, int *exactp, unsigned int *kip);
351 static int mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp,
352 indx_t indx, MDB_val *key, MDB_val *data,
353 pgno_t pgno, uint8_t flags);
354 static void mdb_del_node(MDB_page *mp, indx_t indx);
355 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, unsigned int ki,
356 MDB_pageparent *mpp, MDB_node *leaf);
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);
379 static int mdb_cursor_prev(MDB_cursor *cursor,
380 MDB_val *key, MDB_val *data);
381 static int mdb_cursor_set(MDB_cursor *cursor,
382 MDB_val *key, MDB_val *data, 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 size_t mdb_leaf_size(MDB_env *env, MDB_val *key,
390 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
392 static int memncmp(const void *s1, size_t n1,
393 const void *s2, size_t n2);
394 static int memnrcmp(const void *s1, size_t n1,
395 const void *s2, size_t n2);
398 memncmp(const void *s1, size_t n1, const void *s2, size_t n2)
400 int diff, len_diff = -1;
403 len_diff = (n1 > n2);
406 diff = memcmp(s1, s2, n1);
407 return diff ? diff : len_diff;
411 memnrcmp(const void *s1, size_t n1, const void *s2, size_t n2)
413 const unsigned char *p1, *p2, *p1_lim;
420 p1 = (const unsigned char *)s1 + n1 - 1;
421 p2 = (const unsigned char *)s2 + n2 - 1;
423 for (p1_lim = (n1 <= n2 ? s1 : s2); *p1 == *p2; p1--, p2--) {
425 return (p1 != s1) ? (p1 != p2) : (p2 != s2) ? -1 : 0;
431 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
433 return txn->mt_dbxs[dbi].md_cmp(a, b);
437 _mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *key1, const MDB_val *key2)
439 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_REVERSEKEY))
440 return memnrcmp(key1->mv_data, key1->mv_size, key2->mv_data, key2->mv_size);
442 return memncmp((char *)key1->mv_data, key1->mv_size, key2->mv_data, key2->mv_size);
445 /* Allocate new page(s) for writing */
447 mdb_alloc_page(MDB_txn *txn, MDB_page *parent, unsigned int parent_idx, int num)
450 pgno_t pgno = P_INVALID;
451 ULONG oldest = txn->mt_txnid - 2;
453 if (!txn->mt_env->me_pghead && txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
454 /* See if there's anything in the free DB */
459 mpp.mp_parent = NULL;
461 mdb_search_page(txn, FREE_DBI, NULL, NULL, 0, &mpp);
462 leaf = NODEPTR(mpp.mp_page, 0);
463 kptr = (ULONG *)NODEKEY(leaf);
465 /* It's potentially usable, unless there are still
466 * older readers outstanding. Grab it.
468 if (oldest > *kptr) {
473 mdb_read_data(txn, leaf, &data);
474 idl = (ULONG *)data.mv_data;
475 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
476 mop->mo_next = txn->mt_env->me_pghead;
477 mop->mo_txnid = *kptr;
478 txn->mt_env->me_pghead = mop;
479 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
484 DPRINTF("IDL read txn %lu root %lu num %lu",
485 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
486 for (i=0; i<idl[0]; i++) {
487 DPRINTF("IDL %lu", idl[i+1]);
491 /* drop this IDL from the DB */
492 mpp.mp_parent = NULL;
494 mdb_search_page(txn, FREE_DBI, NULL, NULL, 1, &mpp);
495 leaf = NODEPTR(mpp.mp_page, 0);
496 mdb_del0(txn, FREE_DBI, 0, &mpp, leaf);
499 if (txn->mt_env->me_pghead) {
501 for (i=0; i<txn->mt_env->me_txns->mt_numreaders; i++) {
502 ULONG mr = txn->mt_env->me_txns->mt_readers[i].mr_txnid;
505 oldest = txn->mt_env->me_txns->mt_readers[i].mr_txnid;
507 if (oldest > txn->mt_env->me_pghead->mo_txnid) {
508 MDB_oldpages *mop = txn->mt_env->me_pghead;
509 txn->mt_oldest = oldest;
511 /* FIXME: For now, always use fresh pages. We
512 * really ought to search the free list for a
517 /* peel pages off tail, so we only have to truncate the list */
518 pgno = MDB_IDL_LAST(mop->mo_pages);
519 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
521 if (mop->mo_pages[2] > mop->mo_pages[1])
522 mop->mo_pages[0] = 0;
526 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
527 txn->mt_env->me_pghead = mop->mo_next;
534 if ((dp = malloc(txn->mt_env->me_psize * num + sizeof(MDB_dhead))) == NULL)
537 dp->h.md_parent = parent;
538 dp->h.md_pi = parent_idx;
539 STAILQ_INSERT_TAIL(txn->mt_u.dirty_queue, dp, h.md_next);
540 if (pgno == P_INVALID) {
541 dp->p.mp_pgno = txn->mt_next_pgno;
542 txn->mt_next_pgno += num;
544 dp->p.mp_pgno = pgno;
550 /* Touch a page: make it dirty and re-insert into tree with updated pgno.
553 mdb_touch(MDB_txn *txn, MDB_pageparent *pp)
555 MDB_page *mp = pp->mp_page;
560 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
562 if ((dp = mdb_alloc_page(txn, pp->mp_parent, pp->mp_pi, 1)) == NULL)
564 DPRINTF("touched page %lu -> %lu", mp->mp_pgno, dp->p.mp_pgno);
565 mdb_idl_insert(txn->mt_free_pgs, mp->mp_pgno);
566 pgno = dp->p.mp_pgno;
567 memcpy(&dp->p, mp, txn->mt_env->me_psize);
570 mp->mp_flags |= P_DIRTY;
572 /* Update the page number to new touched page. */
573 if (pp->mp_parent != NULL)
574 NODEPGNO(NODEPTR(pp->mp_parent, pp->mp_pi)) = mp->mp_pgno;
581 mdbenv_sync(MDB_env *env)
584 if (!F_ISSET(env->me_flags, MDB_NOSYNC)) {
585 if (fsync(env->me_fd))
592 mdb_txn_begin(MDB_env *env, int rdonly, MDB_txn **ret)
597 if ((txn = calloc(1, sizeof(*txn))) == NULL) {
598 DPRINTF("calloc: %s", strerror(errno));
603 txn->mt_flags |= MDB_TXN_RDONLY;
605 txn->mt_u.dirty_queue = calloc(1, sizeof(*txn->mt_u.dirty_queue));
606 if (txn->mt_u.dirty_queue == NULL) {
610 STAILQ_INIT(txn->mt_u.dirty_queue);
612 pthread_mutex_lock(&env->me_txns->mt_wmutex);
613 env->me_txns->mt_txnid++;
614 txn->mt_free_pgs = env->me_free_pgs;
615 txn->mt_free_pgs[0] = 0;
618 txn->mt_txnid = env->me_txns->mt_txnid;
620 MDB_reader *r = pthread_getspecific(env->me_txkey);
623 pthread_mutex_lock(&env->me_txns->mt_mutex);
624 for (i=0; i<env->me_txns->mt_numreaders; i++)
625 if (env->me_txns->mt_readers[i].mr_pid == 0)
627 if (i == env->me_maxreaders) {
628 pthread_mutex_unlock(&env->me_txns->mti_mutex);
631 env->me_txns->mt_readers[i].mr_pid = getpid();
632 env->me_txns->mt_readers[i].mr_tid = pthread_self();
633 r = &env->me_txns->mt_readers[i];
634 pthread_setspecific(env->me_txkey, r);
635 if (i >= env->me_txns->mt_numreaders)
636 env->me_txns->mt_numreaders = i+1;
637 pthread_mutex_unlock(&env->me_txns->mt_mutex);
639 r->mr_txnid = txn->mt_txnid;
640 txn->mt_u.reader = r;
647 if ((rc = mdbenv_read_meta(env, &toggle)) != MDB_SUCCESS) {
652 /* Copy the DB arrays */
653 txn->mt_numdbs = env->me_numdbs;
654 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
655 txn->mt_dbs = malloc(env->me_maxdbs * sizeof(MDB_db));
656 memcpy(txn->mt_dbs, env->me_meta->mm_dbs, 2 * sizeof(MDB_db));
657 if (txn->mt_numdbs > 2)
658 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
659 (txn->mt_numdbs - 2) * sizeof(MDB_db));
663 txn->mt_flags |= MDB_TXN_METOGGLE;
664 txn->mt_next_pgno = env->me_meta->mm_last_pg+1;
667 DPRINTF("begin transaction %lu on mdbenv %p, root page %lu",
668 txn->mt_txnid, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
675 mdb_txn_abort(MDB_txn *txn)
684 DPRINTF("abort transaction %lu on mdbenv %p, root page %lu",
685 txn->mt_txnid, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
689 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
690 txn->mt_u.reader->mr_txnid = 0;
695 /* Discard all dirty pages. */
696 while (!STAILQ_EMPTY(txn->mt_u.dirty_queue)) {
697 dp = STAILQ_FIRST(txn->mt_u.dirty_queue);
698 STAILQ_REMOVE_HEAD(txn->mt_u.dirty_queue, h.md_next);
701 free(txn->mt_u.dirty_queue);
703 while ((mop = txn->mt_env->me_pghead)) {
704 txn->mt_env->me_pghead = mop->mo_next;
709 env->me_txns->mt_txnid--;
710 for (i=2; i<env->me_numdbs; i++)
711 env->me_dbxs[i].md_dirty = 0;
712 pthread_mutex_unlock(&env->me_txns->mt_wmutex);
719 mdb_txn_commit(MDB_txn *txn)
728 struct iovec iov[MDB_COMMIT_PAGES];
731 assert(txn->mt_env != NULL);
735 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
736 DPRINTF("attempt to commit read-only transaction");
741 if (txn != env->me_txn) {
742 DPRINTF("attempt to commit unknown transaction");
747 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
748 DPRINTF("error flag is set, can't commit");
753 if (STAILQ_EMPTY(txn->mt_u.dirty_queue))
756 DPRINTF("committing transaction %lu on mdbenv %p, root page %lu",
757 txn->mt_txnid, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
759 /* should only be one record now */
760 if (env->me_pghead) {
764 mop = env->me_pghead;
765 key.mv_size = sizeof(pgno_t);
766 key.mv_data = (char *)&mop->mo_txnid;
767 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
768 data.mv_data = mop->mo_pages;
769 mdb_put(txn, FREE_DBI, &key, &data, 0);
770 free(env->me_pghead);
771 env->me_pghead = NULL;
773 /* save to free list */
774 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
778 /* make sure last page of freeDB is touched and on freelist */
779 key.mv_size = MAXKEYSIZE+1;
781 mpp.mp_parent = NULL;
783 mdb_search_page(txn, FREE_DBI, &key, NULL, 1, &mpp);
788 ULONG *idl = txn->mt_free_pgs;
789 DPRINTF("IDL write txn %lu root %lu num %lu",
790 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
791 for (i=0; i<idl[0]; i++) {
792 DPRINTF("IDL %lu", idl[i+1]);
796 /* write to last page of freeDB */
797 key.mv_size = sizeof(pgno_t);
798 key.mv_data = (char *)&txn->mt_txnid;
799 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
800 data.mv_data = txn->mt_free_pgs;
801 mdb_put(txn, FREE_DBI, &key, &data, 0);
804 /* Update DB root pointers. Their pages have already been
805 * touched so this is all in-place and cannot fail.
809 data.mv_size = sizeof(MDB_db);
811 for (i = 2; i < txn->mt_numdbs; i++) {
812 if (txn->mt_dbxs[i].md_dirty) {
813 data.mv_data = &txn->mt_dbs[i];
814 mdb_put(txn, i, &txn->mt_dbxs[i].md_name, &data, 0);
819 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
826 STAILQ_FOREACH(dp, txn->mt_u.dirty_queue, h.md_next) {
827 if (dp->p.mp_pgno != next) {
829 DPRINTF("committing %u dirty pages", n);
830 rc = writev(env->me_fd, iov, n);
834 DPRINTF("short write, filesystem full?");
836 DPRINTF("writev: %s", strerror(errno));
843 lseek(env->me_fd, dp->p.mp_pgno * env->me_psize, SEEK_SET);
844 next = dp->p.mp_pgno;
846 DPRINTF("committing page %lu", dp->p.mp_pgno);
847 iov[n].iov_len = env->me_psize * dp->h.md_num;
848 iov[n].iov_base = &dp->p;
849 size += iov[n].iov_len;
850 next = dp->p.mp_pgno + dp->h.md_num;
851 /* clear dirty flag */
852 dp->p.mp_flags &= ~P_DIRTY;
853 if (++n >= MDB_COMMIT_PAGES) {
862 DPRINTF("committing %u dirty pages", n);
863 rc = writev(env->me_fd, iov, n);
867 DPRINTF("short write, filesystem full?");
869 DPRINTF("writev: %s", strerror(errno));
876 /* Drop the dirty pages.
878 while (!STAILQ_EMPTY(txn->mt_u.dirty_queue)) {
879 dp = STAILQ_FIRST(txn->mt_u.dirty_queue);
880 STAILQ_REMOVE_HEAD(txn->mt_u.dirty_queue, h.md_next);
884 if ((n = mdbenv_sync(env)) != 0 ||
885 (n = mdbenv_write_meta(txn)) != MDB_SUCCESS ||
886 (n = mdbenv_sync(env)) != 0) {
892 /* update the DB tables */
894 int toggle = !env->me_db_toggle;
896 for (i = 2; i < env->me_numdbs; i++) {
897 if (txn->mt_dbxs[i].md_dirty) {
898 env->me_dbs[toggle][i] = txn->mt_dbs[i];
899 txn->mt_dbxs[i].md_dirty = 0;
902 for (i = env->me_numdbs; i < txn->mt_numdbs; i++) {
903 txn->mt_dbxs[i].md_dirty = 0;
904 env->me_dbxs[i] = txn->mt_dbxs[i];
905 env->me_dbs[toggle][i] = txn->mt_dbs[i];
907 env->me_db_toggle = toggle;
908 env->me_numdbs = txn->mt_numdbs;
913 pthread_mutex_unlock(&env->me_txns->mt_wmutex);
914 free(txn->mt_u.dirty_queue);
925 mdbenv_read_header(MDB_env *env, MDB_meta *meta)
934 /* We don't know the page size yet, so use a minimum value.
937 if ((rc = pread(env->me_fd, page, PAGESIZE, 0)) == 0) {
939 } else if (rc != PAGESIZE) {
942 DPRINTF("read: %s", strerror(errno));
946 p = (MDB_page *)page;
948 if (!F_ISSET(p->mp_flags, P_META)) {
949 DPRINTF("page %lu not a meta page", p->mp_pgno);
954 if (m->mm_magic != MDB_MAGIC) {
955 DPRINTF("meta has invalid magic");
959 if (m->mm_version != MDB_VERSION) {
960 DPRINTF("database is version %u, expected version %u",
961 m->mm_version, MDB_VERSION);
965 memcpy(meta, m, sizeof(*m));
970 mdbenv_init_meta(MDB_env *env, MDB_meta *meta)
977 DPRINTF("writing new meta page");
978 psize = sysconf(_SC_PAGE_SIZE);
980 meta->mm_magic = MDB_MAGIC;
981 meta->mm_version = MDB_VERSION;
982 meta->mm_psize = psize;
983 meta->mm_last_pg = 1;
984 meta->mm_flags = env->me_flags & 0xffff;
985 #if __BYTE_ORDER == __LITTLE_ENDIAN
986 /* freeDB keys are pgno_t's, must compare in int order */
987 meta->mm_flags |= MDB_REVERSEKEY;
989 meta->mm_dbs[0].md_root = P_INVALID;
990 meta->mm_dbs[1].md_root = P_INVALID;
992 p = calloc(2, psize);
994 p->mp_flags = P_META;
997 memcpy(m, meta, sizeof(*meta));
999 q = (MDB_page *)((char *)p + psize);
1002 q->mp_flags = P_META;
1005 memcpy(m, meta, sizeof(*meta));
1007 rc = write(env->me_fd, p, psize * 2);
1009 return (rc == (int)psize * 2) ? MDB_SUCCESS : errno;
1013 mdbenv_write_meta(MDB_txn *txn)
1021 assert(txn != NULL);
1022 assert(txn->mt_env != NULL);
1024 DPRINTF("writing meta page for root page %lu", txn->mt_dbs[MAIN_DBI].md_root);
1028 ptr = (char *)&meta;
1029 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
1030 len = sizeof(MDB_meta) - off;
1033 meta.mm_dbs[0] = txn->mt_dbs[0];
1034 meta.mm_dbs[1] = txn->mt_dbs[1];
1035 meta.mm_last_pg = txn->mt_next_pgno - 1;
1036 meta.mm_txnid = txn->mt_txnid;
1038 if (!F_ISSET(txn->mt_flags, MDB_TXN_METOGGLE))
1039 off += env->me_psize;
1042 lseek(env->me_fd, off, SEEK_SET);
1043 rc = write(env->me_fd, ptr, len);
1045 DPRINTF("write failed, disk error?");
1053 mdbenv_read_meta(MDB_env *env, int *which)
1057 assert(env != NULL);
1059 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1062 if (env->me_meta != env->me_metas[toggle])
1063 env->me_meta = env->me_metas[toggle];
1067 DPRINTF("Using meta page %d", toggle);
1073 mdbenv_create(MDB_env **env)
1077 e = calloc(1, sizeof(*e));
1078 if (!e) return ENOMEM;
1080 e->me_maxreaders = DEFAULT_READERS;
1089 mdbenv_set_mapsize(MDB_env *env, size_t size)
1093 env->me_mapsize = size;
1098 mdbenv_set_maxdbs(MDB_env *env, int dbs)
1102 env->me_maxdbs = dbs;
1107 mdbenv_set_maxreaders(MDB_env *env, int readers)
1109 env->me_maxreaders = readers;
1114 mdbenv_get_maxreaders(MDB_env *env, int *readers)
1116 if (!env || !readers)
1118 *readers = env->me_maxreaders;
1123 mdbenv_open2(MDB_env *env, unsigned int flags)
1129 env->me_flags = flags;
1131 memset(&meta, 0, sizeof(meta));
1133 if ((i = mdbenv_read_header(env, &meta)) != 0) {
1136 DPRINTF("new mdbenv");
1140 if (!env->me_mapsize) {
1141 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
1145 if (meta.mm_address && (flags & MDB_FIXEDMAP))
1147 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
1149 if (env->me_map == MAP_FAILED)
1153 meta.mm_mapsize = env->me_mapsize;
1154 if (flags & MDB_FIXEDMAP)
1155 meta.mm_address = env->me_map;
1156 i = mdbenv_init_meta(env, &meta);
1157 if (i != MDB_SUCCESS) {
1158 munmap(env->me_map, env->me_mapsize);
1162 env->me_psize = meta.mm_psize;
1164 p = (MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)env->me_map;
1165 env->me_metas[0] = METADATA(p);
1166 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
1168 if ((i = mdbenv_read_meta(env, NULL)) != 0)
1171 DPRINTF("opened database version %u, pagesize %u",
1172 env->me_meta->mm_version, env->me_psize);
1173 DPRINTF("depth: %u", env->me_meta->mm_dbs[MAIN_DBI].md_depth);
1174 DPRINTF("entries: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_entries);
1175 DPRINTF("branch pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_branch_pages);
1176 DPRINTF("leaf pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_leaf_pages);
1177 DPRINTF("overflow pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_overflow_pages);
1178 DPRINTF("root: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_root);
1184 mdbenv_reader_dest(void *ptr)
1186 MDB_reader *reader = ptr;
1188 reader->mr_txnid = 0;
1193 /* downgrade the exclusive lock on the region back to shared */
1195 mdbenv_share_locks(MDB_env *env)
1197 struct flock lock_info;
1199 env->me_txns->mt_txnid = env->me_meta->mm_txnid;
1201 memset((void *)&lock_info, 0, sizeof(lock_info));
1202 lock_info.l_type = F_RDLCK;
1203 lock_info.l_whence = SEEK_SET;
1204 lock_info.l_start = 0;
1205 lock_info.l_len = 1;
1206 fcntl(env->me_lfd, F_SETLK, &lock_info);
1210 mdbenv_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
1214 struct flock lock_info;
1218 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
1222 /* Try to get exclusive lock. If we succeed, then
1223 * nobody is using the lock region and we should initialize it.
1225 memset((void *)&lock_info, 0, sizeof(lock_info));
1226 lock_info.l_type = F_WRLCK;
1227 lock_info.l_whence = SEEK_SET;
1228 lock_info.l_start = 0;
1229 lock_info.l_len = 1;
1230 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1234 lock_info.l_type = F_RDLCK;
1235 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1241 size = lseek(env->me_lfd, 0, SEEK_END);
1242 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1243 if (size < rsize && *excl) {
1244 if (ftruncate(env->me_lfd, rsize) != 0) {
1250 size = rsize - sizeof(MDB_txninfo);
1251 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
1253 env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
1255 if (env->me_txns == MAP_FAILED) {
1260 pthread_mutexattr_t mattr;
1262 pthread_mutexattr_init(&mattr);
1263 pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
1264 pthread_mutex_init(&env->me_txns->mt_mutex, &mattr);
1265 pthread_mutex_init(&env->me_txns->mt_wmutex, &mattr);
1266 env->me_txns->mt_version = MDB_VERSION;
1267 env->me_txns->mt_magic = MDB_MAGIC;
1268 env->me_txns->mt_txnid = 0;
1269 env->me_txns->mt_numreaders = 0;
1272 if (env->me_txns->mt_magic != MDB_MAGIC) {
1273 DPRINTF("lock region has invalid magic");
1276 if (env->me_txns->mt_version != MDB_VERSION) {
1277 DPRINTF("lock region is version %u, expected version %u",
1278 env->me_txns->mt_version, MDB_VERSION);
1281 if (errno != EACCES && errno != EAGAIN) {
1295 mdbenv_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
1297 int oflags, rc, len, excl;
1298 char *lpath, *dpath;
1301 lpath = malloc(len + sizeof("/lock.mdb") + len + sizeof("/data.db"));
1304 dpath = lpath + len + sizeof("/lock.mdb");
1305 sprintf(lpath, "%s/lock.mdb", path);
1306 sprintf(dpath, "%s/data.mdb", path);
1308 rc = mdbenv_setup_locks(env, lpath, mode, &excl);
1312 if (F_ISSET(flags, MDB_RDONLY))
1315 oflags = O_RDWR | O_CREAT;
1317 if ((env->me_fd = open(dpath, oflags, mode)) == -1)
1320 if ((rc = mdbenv_open2(env, flags)) != MDB_SUCCESS) {
1324 env->me_path = strdup(path);
1325 DPRINTF("opened dbenv %p", (void *) env);
1326 pthread_key_create(&env->me_txkey, mdbenv_reader_dest);
1328 mdbenv_share_locks(env);
1329 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
1330 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
1331 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
1341 mdbenv_close(MDB_env *env)
1350 munmap(env->me_map, env->me_mapsize);
1354 size_t size = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1355 munmap(env->me_txns, size);
1361 /* Search for key within a leaf page, using binary search.
1362 * Returns the smallest entry larger or equal to the key.
1363 * If exactp is non-null, stores whether the found entry was an exact match
1364 * in *exactp (1 or 0).
1365 * If kip is non-null, stores the index of the found entry in *kip.
1366 * If no entry larger or equal to the key is found, returns NULL.
1369 mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, MDB_val *key,
1370 int *exactp, unsigned int *kip)
1378 DPRINTF("searching %u keys in %s page %lu",
1380 IS_LEAF(mp) ? "leaf" : "branch",
1383 assert(NUMKEYS(mp) > 0);
1385 memset(&nodekey, 0, sizeof(nodekey));
1387 low = IS_LEAF(mp) ? 0 : 1;
1388 high = NUMKEYS(mp) - 1;
1389 while (low <= high) {
1390 i = (low + high) >> 1;
1391 node = NODEPTR(mp, i);
1393 nodekey.mv_size = node->mn_ksize;
1394 nodekey.mv_data = NODEKEY(node);
1396 if (txn->mt_dbxs[dbi].md_cmp)
1397 rc = txn->mt_dbxs[dbi].md_cmp(key, &nodekey);
1399 rc = _mdb_cmp(txn, dbi, key, &nodekey);
1402 DPRINTF("found leaf index %u [%.*s], rc = %i",
1403 i, (int)nodekey.mv_size, (char *)nodekey.mv_data, rc);
1405 DPRINTF("found branch index %u [%.*s -> %lu], rc = %i",
1406 i, (int)node->mn_ksize, (char *)NODEKEY(node),
1417 if (rc > 0) { /* Found entry is less than the key. */
1418 i++; /* Skip to get the smallest entry larger than key. */
1419 if (i >= NUMKEYS(mp))
1420 /* There is no entry larger or equal to the key. */
1424 *exactp = (rc == 0);
1425 if (kip) /* Store the key index if requested. */
1428 return NODEPTR(mp, i);
1432 cursor_pop_page(MDB_cursor *cursor)
1436 top = CURSOR_TOP(cursor);
1439 DPRINTF("popped page %lu off cursor %p", top->mp_page->mp_pgno, (void *) cursor);
1445 cursor_push_page(MDB_cursor *cursor, MDB_page *mp)
1449 DPRINTF("pushing page %lu on cursor %p", mp->mp_pgno, (void *) cursor);
1451 if ((ppage = calloc(1, sizeof(*ppage))) == NULL)
1453 ppage->mp_page = mp;
1454 CURSOR_PUSH(cursor, ppage);
1459 mdb_get_page(MDB_txn *txn, pgno_t pgno)
1464 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && !STAILQ_EMPTY(txn->mt_u.dirty_queue)) {
1466 STAILQ_FOREACH(dp, txn->mt_u.dirty_queue, h.md_next) {
1467 if (dp->p.mp_pgno == pgno) {
1475 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
1481 mdb_search_page_root(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
1482 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
1484 MDB_page *mp = mpp->mp_page;
1487 if (cursor && cursor_push_page(cursor, mp) == NULL)
1490 while (IS_BRANCH(mp)) {
1494 DPRINTF("branch page %lu has %u keys", mp->mp_pgno, NUMKEYS(mp));
1495 assert(NUMKEYS(mp) > 1);
1496 DPRINTF("found index 0 to page %lu", NODEPGNO(NODEPTR(mp, 0)));
1498 if (key == NULL) /* Initialize cursor to first page. */
1500 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
1501 /* cursor to last page */
1505 node = mdb_search_node(txn, dbi, mp, key, &exact, &i);
1507 i = NUMKEYS(mp) - 1;
1515 DPRINTF("following index %u for key %.*s",
1516 i, (int)key->mv_size, (char *)key->mv_data);
1517 assert(i < NUMKEYS(mp));
1518 node = NODEPTR(mp, i);
1521 CURSOR_TOP(cursor)->mp_ki = i;
1523 mpp->mp_parent = mp;
1524 if ((mp = mdb_get_page(txn, NODEPGNO(node))) == NULL)
1529 if (cursor && cursor_push_page(cursor, mp) == NULL)
1533 MDB_dhead *dh = ((MDB_dhead *)mp)-1;
1534 if ((rc = mdb_touch(txn, mpp)) != 0)
1536 dh = ((MDB_dhead *)mpp->mp_page)-1;
1537 dh->md_parent = mpp->mp_parent;
1538 dh->md_pi = mpp->mp_pi;
1545 DPRINTF("internal error, index points to a %02X page!?",
1550 DPRINTF("found leaf page %lu for key %.*s", mp->mp_pgno,
1551 key ? (int)key->mv_size : 0, key ? (char *)key->mv_data : NULL);
1556 /* Search for the page a given key should be in.
1557 * Stores a pointer to the found page in *mpp.
1558 * If key is NULL, search for the lowest page (used by mdb_cursor_first).
1559 * If cursor is non-null, pushes parent pages on the cursor stack.
1560 * If modify is true, visited pages are updated with new page numbers.
1563 mdb_search_page(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
1564 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
1569 /* Choose which root page to start with. If a transaction is given
1570 * use the root page from the transaction, otherwise read the last
1571 * committed root page.
1573 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1574 DPRINTF("transaction has failed, must abort");
1577 root = txn->mt_dbs[dbi].md_root;
1579 if (root == P_INVALID) { /* Tree is empty. */
1580 DPRINTF("tree is empty");
1584 if ((mpp->mp_page = mdb_get_page(txn, root)) == NULL)
1587 DPRINTF("root page has flags 0x%X", mpp->mp_page->mp_flags);
1590 /* For sub-databases, update main root first */
1591 if (dbi > MAIN_DBI && !txn->mt_dbxs[dbi].md_dirty) {
1593 rc = mdb_search_page(txn, 0, &txn->mt_dbxs[dbi].md_name,
1597 txn->mt_dbxs[dbi].md_dirty = 1;
1599 if (!F_ISSET(mpp->mp_page->mp_flags, P_DIRTY)) {
1600 mpp->mp_parent = NULL;
1602 if ((rc = mdb_touch(txn, mpp)))
1604 txn->mt_dbs[dbi].md_root = mpp->mp_page->mp_pgno;
1608 return mdb_search_page_root(txn, dbi, key, cursor, modify, mpp);
1612 mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
1614 MDB_page *omp; /* overflow mpage */
1617 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
1618 data->mv_size = leaf->mn_dsize;
1619 data->mv_data = NODEDATA(leaf);
1623 /* Read overflow data.
1625 data->mv_size = leaf->mn_dsize;
1626 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
1627 if ((omp = mdb_get_page(txn, pgno)) == NULL) {
1628 DPRINTF("read overflow page %lu failed", pgno);
1631 data->mv_data = omp;
1637 mdb_get(MDB_txn *txn, MDB_dbi dbi,
1638 MDB_val *key, MDB_val *data)
1646 DPRINTF("===> get key [%.*s]", (int)key->mv_size, (char *)key->mv_data);
1648 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
1652 if ((rc = mdb_search_page(txn, dbi, key, NULL, 0, &mpp)) != MDB_SUCCESS)
1655 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, NULL);
1657 rc = mdb_read_data(txn, leaf, data);
1666 mdb_sibling(MDB_cursor *cursor, int move_right)
1670 MDB_ppage *parent, *top;
1673 top = CURSOR_TOP(cursor);
1674 if ((parent = SLIST_NEXT(top, mp_entry)) == NULL) {
1675 return ENOENT; /* root has no siblings */
1678 DPRINTF("parent page is page %lu, index %u",
1679 parent->mp_page->mp_pgno, parent->mp_ki);
1681 cursor_pop_page(cursor);
1682 if (move_right ? (parent->mp_ki + 1 >= NUMKEYS(parent->mp_page))
1683 : (parent->mp_ki == 0)) {
1684 DPRINTF("no more keys left, moving to %s sibling",
1685 move_right ? "right" : "left");
1686 if ((rc = mdb_sibling(cursor, move_right)) != MDB_SUCCESS)
1688 parent = CURSOR_TOP(cursor);
1694 DPRINTF("just moving to %s index key %u",
1695 move_right ? "right" : "left", parent->mp_ki);
1697 assert(IS_BRANCH(parent->mp_page));
1699 indx = NODEPTR(parent->mp_page, parent->mp_ki);
1700 if ((mp = mdb_get_page(cursor->mc_txn, indx->mn_pgno)) == NULL)
1703 mp->parent = parent->mp_page;
1704 mp->parent_index = parent->mp_ki;
1707 cursor_push_page(cursor, mp);
1713 mdb_set_key(MDB_node *node, MDB_val *key)
1718 key->mv_size = node->mn_ksize;
1719 key->mv_data = NODEKEY(node);
1725 mdb_cursor_next(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
1731 if (cursor->mc_eof) {
1735 assert(cursor->mc_initialized);
1737 top = CURSOR_TOP(cursor);
1740 DPRINTF("cursor_next: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
1742 if (top->mp_ki + 1 >= NUMKEYS(mp)) {
1743 DPRINTF("=====> move to next sibling page");
1744 if (mdb_sibling(cursor, 1) != MDB_SUCCESS) {
1748 top = CURSOR_TOP(cursor);
1750 DPRINTF("next page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
1754 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
1755 mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
1757 assert(IS_LEAF(mp));
1758 leaf = NODEPTR(mp, top->mp_ki);
1760 if (data && mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS)
1763 return mdb_set_key(leaf, key);
1767 mdb_cursor_prev(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
1773 assert(cursor->mc_initialized);
1775 top = CURSOR_TOP(cursor);
1778 DPRINTF("cursor_prev: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
1780 if (top->mp_ki == 0) {
1781 DPRINTF("=====> move to prev sibling page");
1782 if (mdb_sibling(cursor, 0) != MDB_SUCCESS) {
1785 top = CURSOR_TOP(cursor);
1787 top->mp_ki = NUMKEYS(mp) - 1;
1788 DPRINTF("prev page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
1794 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
1795 mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
1797 assert(IS_LEAF(mp));
1798 leaf = NODEPTR(mp, top->mp_ki);
1800 if (data && mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS)
1803 return mdb_set_key(leaf, key);
1807 mdb_cursor_set(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
1817 assert(key->mv_size > 0);
1819 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, key, cursor, 0, &mpp);
1820 if (rc != MDB_SUCCESS)
1822 assert(IS_LEAF(mpp.mp_page));
1824 top = CURSOR_TOP(cursor);
1825 leaf = mdb_search_node(cursor->mc_txn, cursor->mc_dbi, mpp.mp_page, key, exactp, &top->mp_ki);
1826 if (exactp != NULL && !*exactp) {
1827 /* MDB_SET specified and not an exact match. */
1832 DPRINTF("===> inexact leaf not found, goto sibling");
1833 if ((rc = mdb_sibling(cursor, 1)) != MDB_SUCCESS)
1834 return rc; /* no entries matched */
1835 top = CURSOR_TOP(cursor);
1837 mpp.mp_page = top->mp_page;
1838 assert(IS_LEAF(mpp.mp_page));
1839 leaf = NODEPTR(mpp.mp_page, 0);
1842 cursor->mc_initialized = 1;
1845 if (data && (rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
1848 rc = mdb_set_key(leaf, key);
1849 if (rc == MDB_SUCCESS) {
1850 DPRINTF("==> cursor placed on key %.*s",
1851 (int)key->mv_size, (char *)key->mv_data);
1859 mdb_cursor_first(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
1865 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, NULL, cursor, 0, &mpp);
1866 if (rc != MDB_SUCCESS)
1868 assert(IS_LEAF(mpp.mp_page));
1870 leaf = NODEPTR(mpp.mp_page, 0);
1871 cursor->mc_initialized = 1;
1874 if (data && (rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
1877 return mdb_set_key(leaf, key);
1881 mdb_cursor_last(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
1889 lkey.mv_size = MAXKEYSIZE+1;
1890 lkey.mv_data = NULL;
1892 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, &lkey, cursor, 0, &mpp);
1893 if (rc != MDB_SUCCESS)
1895 assert(IS_LEAF(mpp.mp_page));
1897 leaf = NODEPTR(mpp.mp_page, NUMKEYS(mpp.mp_page)-1);
1898 cursor->mc_initialized = 1;
1901 top = CURSOR_TOP(cursor);
1902 top->mp_ki = NUMKEYS(top->mp_page) - 1;
1904 if (data && (rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
1907 return mdb_set_key(leaf, key);
1911 mdb_cursor_get(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
1922 while (CURSOR_TOP(cursor) != NULL)
1923 cursor_pop_page(cursor);
1924 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
1926 } else if (op == MDB_SET)
1927 rc = mdb_cursor_set(cursor, key, data, &exact);
1929 rc = mdb_cursor_set(cursor, key, data, NULL);
1932 if (!cursor->mc_initialized)
1933 rc = mdb_cursor_first(cursor, key, data);
1935 rc = mdb_cursor_next(cursor, key, data);
1938 if (!cursor->mc_initialized || cursor->mc_eof) {
1939 while (CURSOR_TOP(cursor) != NULL)
1940 cursor_pop_page(cursor);
1941 rc = mdb_cursor_last(cursor, key, data);
1943 rc = mdb_cursor_prev(cursor, key, data);
1946 while (CURSOR_TOP(cursor) != NULL)
1947 cursor_pop_page(cursor);
1948 rc = mdb_cursor_first(cursor, key, data);
1951 while (CURSOR_TOP(cursor) != NULL)
1952 cursor_pop_page(cursor);
1953 rc = mdb_cursor_last(cursor, key, data);
1956 DPRINTF("unhandled/unimplemented cursor operation %u", op);
1964 /* Allocate a page and initialize it
1967 mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num)
1971 if ((dp = mdb_alloc_page(txn, NULL, 0, num)) == NULL)
1973 DPRINTF("allocated new mpage %lu, page size %u",
1974 dp->p.mp_pgno, txn->mt_env->me_psize);
1975 dp->p.mp_flags = flags | P_DIRTY;
1976 dp->p.mp_lower = PAGEHDRSZ;
1977 dp->p.mp_upper = txn->mt_env->me_psize;
1979 if (IS_BRANCH(&dp->p))
1980 txn->mt_dbs[dbi].md_branch_pages++;
1981 else if (IS_LEAF(&dp->p))
1982 txn->mt_dbs[dbi].md_leaf_pages++;
1983 else if (IS_OVERFLOW(&dp->p)) {
1984 txn->mt_dbs[dbi].md_overflow_pages += num;
1985 dp->p.mp_pages = num;
1992 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
1996 sz = LEAFSIZE(key, data);
1997 if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
1998 /* put on overflow page */
1999 sz -= data->mv_size - sizeof(pgno_t);
2002 return sz + sizeof(indx_t);
2006 mdb_branch_size(MDB_env *env, MDB_val *key)
2011 if (sz >= env->me_psize / MDB_MINKEYS) {
2012 /* put on overflow page */
2013 /* not implemented */
2014 /* sz -= key->size - sizeof(pgno_t); */
2017 return sz + sizeof(indx_t);
2021 mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, indx_t indx,
2022 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags)
2025 size_t node_size = NODESIZE;
2028 MDB_dpage *ofp = NULL; /* overflow page */
2030 assert(mp->mp_upper >= mp->mp_lower);
2032 DPRINTF("add node [%.*s] to %s page %lu at index %i, key size %zu",
2033 key ? (int)key->mv_size : 0, key ? (char *)key->mv_data : NULL,
2034 IS_LEAF(mp) ? "leaf" : "branch",
2035 mp->mp_pgno, indx, key ? key->mv_size : 0);
2038 node_size += key->mv_size;
2042 if (F_ISSET(flags, F_BIGDATA)) {
2043 /* Data already on overflow page. */
2044 node_size += sizeof(pgno_t);
2045 } else if (data->mv_size >= txn->mt_env->me_psize / MDB_MINKEYS) {
2046 int ovpages = OVPAGES(data->mv_size, txn->mt_env->me_psize);
2047 /* Put data on overflow page. */
2048 DPRINTF("data size is %zu, put on overflow page",
2050 node_size += sizeof(pgno_t);
2051 if ((ofp = mdb_new_page(txn, dbi, P_OVERFLOW, ovpages)) == NULL)
2053 DPRINTF("allocated overflow page %lu", ofp->p.mp_pgno);
2056 node_size += data->mv_size;
2060 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
2061 DPRINTF("not enough room in page %lu, got %u ptrs",
2062 mp->mp_pgno, NUMKEYS(mp));
2063 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
2064 mp->mp_upper - mp->mp_lower);
2065 DPRINTF("node size = %zu", node_size);
2069 /* Move higher pointers up one slot. */
2070 for (i = NUMKEYS(mp); i > indx; i--)
2071 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
2073 /* Adjust free space offsets. */
2074 ofs = mp->mp_upper - node_size;
2075 assert(ofs >= mp->mp_lower + sizeof(indx_t));
2076 mp->mp_ptrs[indx] = ofs;
2078 mp->mp_lower += sizeof(indx_t);
2080 /* Write the node data. */
2081 node = NODEPTR(mp, indx);
2082 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
2083 node->mn_flags = flags;
2085 node->mn_dsize = data->mv_size;
2087 node->mn_pgno = pgno;
2090 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
2095 if (F_ISSET(flags, F_BIGDATA))
2096 memcpy(node->mn_data + key->mv_size, data->mv_data,
2099 memcpy(node->mn_data + key->mv_size, data->mv_data,
2102 memcpy(node->mn_data + key->mv_size, &ofp->p.mp_pgno,
2104 memcpy(METADATA(&ofp->p), data->mv_data, data->mv_size);
2112 mdb_del_node(MDB_page *mp, indx_t indx)
2115 indx_t i, j, numkeys, ptr;
2119 DPRINTF("delete node %u on %s page %lu", indx,
2120 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
2121 assert(indx < NUMKEYS(mp));
2123 node = NODEPTR(mp, indx);
2124 sz = NODESIZE + node->mn_ksize;
2126 if (F_ISSET(node->mn_flags, F_BIGDATA))
2127 sz += sizeof(pgno_t);
2129 sz += NODEDSZ(node);
2132 ptr = mp->mp_ptrs[indx];
2133 numkeys = NUMKEYS(mp);
2134 for (i = j = 0; i < numkeys; i++) {
2136 mp->mp_ptrs[j] = mp->mp_ptrs[i];
2137 if (mp->mp_ptrs[i] < ptr)
2138 mp->mp_ptrs[j] += sz;
2143 base = (char *)mp + mp->mp_upper;
2144 memmove(base + sz, base, ptr - mp->mp_upper);
2146 mp->mp_lower -= sizeof(indx_t);
2151 mdb_xcursor_init0(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
2155 mx->mx_cursor.mc_txn = &mx->mx_txn;
2157 mx->mx_txn.mt_dbxs = mx->mx_dbxs;
2158 mx->mx_txn.mt_dbs = mx->mx_dbs;
2159 mx->mx_dbxs[0] = txn->mt_dbxs[0];
2160 mx->mx_dbxs[1] = txn->mt_dbxs[1];
2162 mx->mx_dbxs[2] = txn->mt_dbxs[dbi];
2167 mx->mx_dbxs[dbn+1].md_parent = dbn;
2168 mx->mx_dbxs[dbn+1].md_cmp = mx->mx_dbxs[dbn].md_dcmp;
2169 mx->mx_dbxs[dbn+1].md_rel = mx->mx_dbxs[dbn].md_rel;
2170 mx->mx_dbxs[dbn+1].md_dirty = 0;
2171 mx->mx_txn.mt_numdbs = dbn+2;
2175 mdb_xcursor_init1(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx, MDB_db *db)
2177 mx->mx_dbs[0] = txn->mt_dbs[0];
2178 mx->mx_dbs[1] = txn->mt_dbs[1];
2180 mx->mx_dbs[2] = txn->mt_dbs[dbi];
2181 mx->mx_dbs[3] = *db;
2183 mx->mx_dbs[2] = *db;
2188 mdb_xcursor_fini(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
2190 txn->mt_dbs[0] = mx->mx_dbs[0];
2191 txn->mt_dbs[1] = mx->mx_dbs[1];
2192 txn->mt_dbxs[0].md_dirty = mx->mx_dbxs[0].md_dirty;
2193 txn->mt_dbxs[1].md_dirty = mx->mx_dbxs[1].md_dirty;
2195 txn->mt_dbs[dbi] = mx->mx_dbs[2];
2196 txn->mt_dbxs[2].md_dirty = mx->mx_dbxs[2].md_dirty;
2201 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
2204 size_t size = sizeof(MDB_cursor);
2206 if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
2209 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
2210 size += sizeof(MDB_xcursor);
2212 if ((cursor = calloc(1, size)) != NULL) {
2213 SLIST_INIT(&cursor->mc_stack);
2214 cursor->mc_dbi = dbi;
2215 cursor->mc_txn = txn;
2216 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
2217 MDB_xcursor *mx = (MDB_xcursor *)(cursor + 1);
2218 cursor->mc_xcursor = mx;
2219 mdb_xcursor_init0(txn, dbi, mx);
2231 mdb_cursor_close(MDB_cursor *cursor)
2233 if (cursor != NULL) {
2234 while (!CURSOR_EMPTY(cursor))
2235 cursor_pop_page(cursor);
2237 /* btree_close(cursor->bt); */
2243 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
2245 indx_t ptr, i, numkeys;
2251 node = NODEPTR(mp, indx);
2252 ptr = mp->mp_ptrs[indx];
2253 DPRINTF("update key %u (ofs %u) [%.*s] to [%.*s] on page %lu",
2255 (int)node->mn_ksize, (char *)NODEKEY(node),
2256 (int)key->mv_size, (char *)key->mv_data,
2259 delta = key->mv_size - node->mn_ksize;
2261 if (delta > 0 && SIZELEFT(mp) < delta) {
2262 DPRINTF("OUCH! Not enough room, delta = %d", delta);
2266 numkeys = NUMKEYS(mp);
2267 for (i = 0; i < numkeys; i++) {
2268 if (mp->mp_ptrs[i] <= ptr)
2269 mp->mp_ptrs[i] -= delta;
2272 base = (char *)mp + mp->mp_upper;
2273 len = ptr - mp->mp_upper + NODESIZE;
2274 memmove(base - delta, base, len);
2275 mp->mp_upper -= delta;
2277 node = NODEPTR(mp, indx);
2278 node->mn_ksize = key->mv_size;
2281 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
2286 /* Move a node from src to dst.
2289 mdb_move_node(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, indx_t srcindx,
2290 MDB_pageparent *dst, indx_t dstindx)
2296 srcnode = NODEPTR(src->mp_page, srcindx);
2297 DPRINTF("moving %s node %u [%.*s] on page %lu to node %u on page %lu",
2298 IS_LEAF(src->mp_page) ? "leaf" : "branch",
2300 (int)srcnode->mn_ksize, (char *)NODEKEY(srcnode),
2301 src->mp_page->mp_pgno,
2302 dstindx, dst->mp_page->mp_pgno);
2304 /* Mark src and dst as dirty. */
2305 if ((rc = mdb_touch(txn, src)) ||
2306 (rc = mdb_touch(txn, dst)))
2309 /* Add the node to the destination page.
2311 key.mv_size = srcnode->mn_ksize;
2312 key.mv_data = NODEKEY(srcnode);
2313 data.mv_size = NODEDSZ(srcnode);
2314 data.mv_data = NODEDATA(srcnode);
2315 rc = mdb_add_node(txn, dbi, dst->mp_page, dstindx, &key, &data, NODEPGNO(srcnode),
2317 if (rc != MDB_SUCCESS)
2320 /* Delete the node from the source page.
2322 mdb_del_node(src->mp_page, srcindx);
2324 /* Update the parent separators.
2326 if (srcindx == 0 && src->mp_pi != 0) {
2327 DPRINTF("update separator for source page %lu to [%.*s]",
2328 src->mp_page->mp_pgno, (int)key.mv_size, (char *)key.mv_data);
2329 if ((rc = mdb_update_key(src->mp_parent, src->mp_pi,
2330 &key)) != MDB_SUCCESS)
2334 if (srcindx == 0 && IS_BRANCH(src->mp_page)) {
2336 nullkey.mv_size = 0;
2337 assert(mdb_update_key(src->mp_page, 0, &nullkey) == MDB_SUCCESS);
2340 if (dstindx == 0 && dst->mp_pi != 0) {
2341 DPRINTF("update separator for destination page %lu to [%.*s]",
2342 dst->mp_page->mp_pgno, (int)key.mv_size, (char *)key.mv_data);
2343 if ((rc = mdb_update_key(dst->mp_parent, dst->mp_pi,
2344 &key)) != MDB_SUCCESS)
2348 if (dstindx == 0 && IS_BRANCH(dst->mp_page)) {
2350 nullkey.mv_size = 0;
2351 assert(mdb_update_key(dst->mp_page, 0, &nullkey) == MDB_SUCCESS);
2358 mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, MDB_pageparent *dst)
2367 DPRINTF("merging page %lu and %lu", src->mp_page->mp_pgno, dst->mp_page->mp_pgno);
2369 assert(txn != NULL);
2370 assert(src->mp_parent); /* can't merge root page */
2371 assert(dst->mp_parent);
2373 /* Mark src and dst as dirty. */
2374 if ((rc = mdb_touch(txn, src)) ||
2375 (rc = mdb_touch(txn, dst)))
2378 /* Move all nodes from src to dst.
2380 for (i = 0; i < NUMKEYS(src->mp_page); i++) {
2381 srcnode = NODEPTR(src->mp_page, i);
2383 key.mv_size = srcnode->mn_ksize;
2384 key.mv_data = NODEKEY(srcnode);
2385 data.mv_size = NODEDSZ(srcnode);
2386 data.mv_data = NODEDATA(srcnode);
2387 rc = mdb_add_node(txn, dbi, dst->mp_page, NUMKEYS(dst->mp_page), &key,
2388 &data, NODEPGNO(srcnode), srcnode->mn_flags);
2389 if (rc != MDB_SUCCESS)
2393 DPRINTF("dst page %lu now has %u keys (%.1f%% filled)",
2394 dst->mp_page->mp_pgno, NUMKEYS(dst->mp_page), (float)PAGEFILL(txn->mt_env, dst->mp_page) / 10);
2396 /* Unlink the src page from parent.
2398 mdb_del_node(src->mp_parent, src->mp_pi);
2399 if (src->mp_pi == 0) {
2401 if ((rc = mdb_update_key(src->mp_parent, 0, &key)) != MDB_SUCCESS)
2405 if (IS_LEAF(src->mp_page))
2406 txn->mt_dbs[dbi].md_leaf_pages--;
2408 txn->mt_dbs[dbi].md_branch_pages--;
2410 mpp.mp_page = src->mp_parent;
2411 dh = (MDB_dhead *)src->mp_parent;
2413 mpp.mp_parent = dh->md_parent;
2414 mpp.mp_pi = dh->md_pi;
2416 return mdb_rebalance(txn, dbi, &mpp);
2419 #define FILL_THRESHOLD 250
2422 mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mpp)
2427 indx_t si = 0, di = 0;
2429 assert(txn != NULL);
2430 assert(mpp != NULL);
2432 DPRINTF("rebalancing %s page %lu (has %u keys, %.1f%% full)",
2433 IS_LEAF(mpp->mp_page) ? "leaf" : "branch",
2434 mpp->mp_page->mp_pgno, NUMKEYS(mpp->mp_page), (float)PAGEFILL(txn->mt_env, mpp->mp_page) / 10);
2436 if (PAGEFILL(txn->mt_env, mpp->mp_page) >= FILL_THRESHOLD) {
2437 DPRINTF("no need to rebalance page %lu, above fill threshold",
2438 mpp->mp_page->mp_pgno);
2442 if (mpp->mp_parent == NULL) {
2443 if (NUMKEYS(mpp->mp_page) == 0) {
2444 DPRINTF("tree is completely empty");
2445 txn->mt_dbs[dbi].md_root = P_INVALID;
2446 txn->mt_dbs[dbi].md_depth--;
2447 txn->mt_dbs[dbi].md_leaf_pages--;
2448 } else if (IS_BRANCH(mpp->mp_page) && NUMKEYS(mpp->mp_page) == 1) {
2449 DPRINTF("collapsing root page!");
2450 txn->mt_dbs[dbi].md_root = NODEPGNO(NODEPTR(mpp->mp_page, 0));
2451 if ((root = mdb_get_page(txn, txn->mt_dbs[dbi].md_root)) == NULL)
2453 txn->mt_dbs[dbi].md_depth--;
2454 txn->mt_dbs[dbi].md_branch_pages--;
2456 DPRINTF("root page doesn't need rebalancing");
2460 /* The parent (branch page) must have at least 2 pointers,
2461 * otherwise the tree is invalid.
2463 assert(NUMKEYS(mpp->mp_parent) > 1);
2465 /* Leaf page fill factor is below the threshold.
2466 * Try to move keys from left or right neighbor, or
2467 * merge with a neighbor page.
2472 if (mpp->mp_pi == 0) {
2473 /* We're the leftmost leaf in our parent.
2475 DPRINTF("reading right neighbor");
2476 node = NODEPTR(mpp->mp_parent, mpp->mp_pi + 1);
2477 if ((npp.mp_page = mdb_get_page(txn, NODEPGNO(node))) == NULL)
2479 npp.mp_pi = mpp->mp_pi + 1;
2481 di = NUMKEYS(mpp->mp_page);
2483 /* There is at least one neighbor to the left.
2485 DPRINTF("reading left neighbor");
2486 node = NODEPTR(mpp->mp_parent, mpp->mp_pi - 1);
2487 if ((npp.mp_page = mdb_get_page(txn, NODEPGNO(node))) == NULL)
2489 npp.mp_pi = mpp->mp_pi - 1;
2490 si = NUMKEYS(npp.mp_page) - 1;
2493 npp.mp_parent = mpp->mp_parent;
2495 DPRINTF("found neighbor page %lu (%u keys, %.1f%% full)",
2496 npp.mp_page->mp_pgno, NUMKEYS(npp.mp_page), (float)PAGEFILL(txn->mt_env, npp.mp_page) / 10);
2498 /* If the neighbor page is above threshold and has at least two
2499 * keys, move one key from it.
2501 * Otherwise we should try to merge them.
2503 if (PAGEFILL(txn->mt_env, npp.mp_page) >= FILL_THRESHOLD && NUMKEYS(npp.mp_page) >= 2)
2504 return mdb_move_node(txn, dbi, &npp, si, mpp, di);
2505 else { /* FIXME: if (has_enough_room()) */
2506 if (mpp->mp_pi == 0)
2507 return mdb_merge(txn, dbi, &npp, mpp);
2509 return mdb_merge(txn, dbi, mpp, &npp);
2514 mdb_del0(MDB_txn *txn, MDB_dbi dbi, unsigned int ki, MDB_pageparent *mpp, MDB_node *leaf)
2518 /* add overflow pages to free list */
2519 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
2523 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
2524 ovpages = OVPAGES(NODEDSZ(leaf), txn->mt_env->me_psize);
2525 for (i=0; i<ovpages; i++) {
2526 DPRINTF("freed ov page %lu", pg);
2527 mdb_idl_insert(txn->mt_free_pgs, pg);
2531 mdb_del_node(mpp->mp_page, ki);
2532 txn->mt_dbs[dbi].md_entries--;
2533 rc = mdb_rebalance(txn, dbi, mpp);
2534 if (rc != MDB_SUCCESS)
2535 txn->mt_flags |= MDB_TXN_ERROR;
2541 mdb_del(MDB_txn *txn, MDB_dbi dbi,
2542 MDB_val *key, MDB_val *data)
2549 DPRINTF("========> delete key %.*s", (int)key->mv_size, (char *)key->mv_data);
2551 assert(key != NULL);
2553 if (txn == NULL || dbi >= txn->mt_numdbs)
2556 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2560 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2564 mpp.mp_parent = NULL;
2566 if ((rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp)) != MDB_SUCCESS)
2569 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
2570 if (leaf == NULL || !exact) {
2574 if (data && (rc = mdb_read_data(txn, leaf, data)) != MDB_SUCCESS)
2577 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
2578 /* add all the child DB's pages to the free list */
2581 return mdb_del0(txn, dbi, ki, &mpp, leaf);
2584 /* Split page <*mpp>, and insert <key,(data|newpgno)> in either left or
2585 * right sibling, at index <*newindxp> (as if unsplit). Updates *mpp and
2586 * *newindxp with the actual values after split, ie if *mpp and *newindxp
2587 * refer to a node in the new right sibling page.
2590 mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp, unsigned int *newindxp,
2591 MDB_val *newkey, MDB_val *newdata, pgno_t newpgno)
2594 int rc = MDB_SUCCESS, ins_new = 0;
2597 unsigned int i, j, split_indx;
2599 MDB_val sepkey, rkey, rdata;
2601 MDB_dpage *mdp, *rdp, *pdp;
2604 assert(txn != NULL);
2606 dh = ((MDB_dhead *)*mpp) - 1;
2607 mdp = (MDB_dpage *)dh;
2608 newindx = *newindxp;
2610 DPRINTF("-----> splitting %s page %lu and adding [%.*s] at index %i",
2611 IS_LEAF(&mdp->p) ? "leaf" : "branch", mdp->p.mp_pgno,
2612 (int)newkey->mv_size, (char *)newkey->mv_data, *newindxp);
2614 if (mdp->h.md_parent == NULL) {
2615 if ((pdp = mdb_new_page(txn, dbi, P_BRANCH, 1)) == NULL)
2618 mdp->h.md_parent = &pdp->p;
2619 txn->mt_dbs[dbi].md_root = pdp->p.mp_pgno;
2620 DPRINTF("root split! new root = %lu", pdp->p.mp_pgno);
2621 txn->mt_dbs[dbi].md_depth++;
2623 /* Add left (implicit) pointer. */
2624 if (mdb_add_node(txn, dbi, &pdp->p, 0, NULL, NULL,
2625 mdp->p.mp_pgno, 0) != MDB_SUCCESS)
2628 DPRINTF("parent branch page is %lu", mdp->h.md_parent->mp_pgno);
2631 /* Create a right sibling. */
2632 if ((rdp = mdb_new_page(txn, dbi, mdp->p.mp_flags, 1)) == NULL)
2634 rdp->h.md_parent = mdp->h.md_parent;
2635 rdp->h.md_pi = mdp->h.md_pi + 1;
2636 DPRINTF("new right sibling: page %lu", rdp->p.mp_pgno);
2638 /* Move half of the keys to the right sibling. */
2639 if ((copy = malloc(txn->mt_env->me_psize)) == NULL)
2641 memcpy(copy, &mdp->p, txn->mt_env->me_psize);
2642 memset(&mdp->p.mp_ptrs, 0, txn->mt_env->me_psize - PAGEHDRSZ);
2643 mdp->p.mp_lower = PAGEHDRSZ;
2644 mdp->p.mp_upper = txn->mt_env->me_psize;
2646 split_indx = NUMKEYS(copy) / 2 + 1;
2648 /* First find the separating key between the split pages.
2650 memset(&sepkey, 0, sizeof(sepkey));
2651 if (newindx == split_indx) {
2652 sepkey.mv_size = newkey->mv_size;
2653 sepkey.mv_data = newkey->mv_data;
2655 node = NODEPTR(copy, split_indx);
2656 sepkey.mv_size = node->mn_ksize;
2657 sepkey.mv_data = NODEKEY(node);
2660 DPRINTF("separator is [%.*s]", (int)sepkey.mv_size, (char *)sepkey.mv_data);
2662 /* Copy separator key to the parent.
2664 if (SIZELEFT(rdp->h.md_parent) < mdb_branch_size(txn->mt_env, &sepkey)) {
2665 rc = mdb_split(txn, dbi, &rdp->h.md_parent, &rdp->h.md_pi,
2666 &sepkey, NULL, rdp->p.mp_pgno);
2668 /* Right page might now have changed parent.
2669 * Check if left page also changed parent.
2671 if (rdp->h.md_parent != mdp->h.md_parent &&
2672 mdp->h.md_pi >= NUMKEYS(mdp->h.md_parent)) {
2673 mdp->h.md_parent = rdp->h.md_parent;
2674 mdp->h.md_pi = rdp->h.md_pi - 1;
2677 rc = mdb_add_node(txn, dbi, rdp->h.md_parent, rdp->h.md_pi,
2678 &sepkey, NULL, rdp->p.mp_pgno, 0);
2680 if (rc != MDB_SUCCESS) {
2685 for (i = j = 0; i <= NUMKEYS(copy); j++) {
2686 if (i < split_indx) {
2687 /* Re-insert in left sibling. */
2690 /* Insert in right sibling. */
2691 if (i == split_indx)
2692 /* Reset insert index for right sibling. */
2693 j = (i == newindx && ins_new);
2697 if (i == newindx && !ins_new) {
2698 /* Insert the original entry that caused the split. */
2699 rkey.mv_data = newkey->mv_data;
2700 rkey.mv_size = newkey->mv_size;
2701 if (IS_LEAF(&mdp->p)) {
2702 rdata.mv_data = newdata->mv_data;
2703 rdata.mv_size = newdata->mv_size;
2710 /* Update page and index for the new key. */
2713 } else if (i == NUMKEYS(copy)) {
2716 node = NODEPTR(copy, i);
2717 rkey.mv_data = NODEKEY(node);
2718 rkey.mv_size = node->mn_ksize;
2719 if (IS_LEAF(&mdp->p)) {
2720 rdata.mv_data = NODEDATA(node);
2721 rdata.mv_size = node->mn_dsize;
2723 pgno = node->mn_pgno;
2724 flags = node->mn_flags;
2729 if (!IS_LEAF(&mdp->p) && j == 0) {
2730 /* First branch index doesn't need key data. */
2734 rc = mdb_add_node(txn, dbi, &pdp->p, j, &rkey, &rdata, pgno,flags);
2742 mdb_put(MDB_txn *txn, MDB_dbi dbi,
2743 MDB_val *key, MDB_val *data, unsigned int flags)
2745 int rc = MDB_SUCCESS, exact;
2749 MDB_val xdata, *rdata;
2752 assert(key != NULL);
2753 assert(data != NULL);
2758 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2762 if (txn->mt_env->me_txn != txn) {
2766 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2770 DPRINTF("==> put key %.*s, size %zu, data size %zu",
2771 (int)key->mv_size, (char *)key->mv_data, key->mv_size, data->mv_size);
2773 mpp.mp_parent = NULL;
2775 rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp);
2776 if (rc == MDB_SUCCESS) {
2777 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
2778 if (leaf && exact) {
2779 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
2782 if (F_ISSET(flags, MDB_NOOVERWRITE)) {
2783 DPRINTF("duplicate key %.*s",
2784 (int)key->mv_size, (char *)key->mv_data);
2787 /* same size, just replace it */
2788 if (NODEDSZ(leaf) == data->mv_size) {
2789 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
2792 mdb_del_node(mpp.mp_page, ki);
2794 if (leaf == NULL) { /* append if not found */
2795 ki = NUMKEYS(mpp.mp_page);
2796 DPRINTF("appending key at index %i", ki);
2798 } else if (rc == ENOENT) {
2800 /* new file, just write a root leaf page */
2801 DPRINTF("allocating new root leaf page");
2802 if ((dp = mdb_new_page(txn, dbi, P_LEAF, 1)) == NULL) {
2805 mpp.mp_page = &dp->p;
2806 txn->mt_dbs[dbi].md_root = mpp.mp_page->mp_pgno;
2807 txn->mt_dbs[dbi].md_depth++;
2813 assert(IS_LEAF(mpp.mp_page));
2814 DPRINTF("there are %u keys, should insert new key at index %i",
2815 NUMKEYS(mpp.mp_page), ki);
2817 /* For sorted dups, the data item at this level is a DB record
2818 * for a child DB; the actual data elements are stored as keys
2821 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
2823 xdata.mv_size = sizeof(MDB_db);
2824 xdata.mv_data = &dummy;
2825 memset(&dummy, 0, sizeof(dummy));
2826 dummy.md_root = P_INVALID;
2831 if (SIZELEFT(mpp.mp_page) < mdb_leaf_size(txn->mt_env, key, data)) {
2832 rc = mdb_split(txn, dbi, &mpp.mp_page, &ki, key, data, P_INVALID);
2834 /* There is room already in this leaf page. */
2835 rc = mdb_add_node(txn, dbi, mpp.mp_page, ki, key, data, 0, 0);
2838 if (rc != MDB_SUCCESS)
2839 txn->mt_flags |= MDB_TXN_ERROR;
2841 txn->mt_dbs[dbi].md_entries++;
2842 /* Now store the actual data in the child DB. Note that we're
2843 * storing the user data in the keys field, so there are strict
2844 * size limits on dupdata. The actual data fields of the child
2845 * DB are all zero size.
2847 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
2850 leaf = NODEPTR(mpp.mp_page, ki);
2852 mdb_xcursor_init0(txn, dbi, &mx);
2853 mdb_xcursor_init1(txn, dbi, &mx, NODEDATA(leaf));
2856 rc = mdb_put(&mx.mx_txn, mx.mx_txn.mt_numdbs-1, data, &xdata, flags);
2857 mdb_xcursor_fini(txn, dbi, &mx);
2866 mdbenv_get_flags(MDB_env *env, unsigned int *arg)
2871 *arg = env->me_flags;
2876 mdbenv_get_path(MDB_env *env, const char **arg)
2881 *arg = env->me_path;
2886 mdbenv_stat(MDB_env *env, MDB_stat *arg)
2888 if (env == NULL || arg == NULL)
2891 arg->ms_psize = env->me_psize;
2892 arg->ms_depth = env->me_meta->mm_dbs[MAIN_DBI].md_depth;
2893 arg->ms_branch_pages = env->me_meta->mm_dbs[MAIN_DBI].md_branch_pages;
2894 arg->ms_leaf_pages = env->me_meta->mm_dbs[MAIN_DBI].md_leaf_pages;
2895 arg->ms_overflow_pages = env->me_meta->mm_dbs[MAIN_DBI].md_overflow_pages;
2896 arg->ms_entries = env->me_meta->mm_dbs[MAIN_DBI].md_entries;
2901 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
2914 /* Is the DB already open? */
2916 for (i=2; i<txn->mt_numdbs; i++) {
2917 if (len == txn->mt_dbxs[i].md_name.mv_size &&
2918 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
2924 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
2927 /* Find the DB info */
2929 key.mv_data = (void *)name;
2930 rc = mdb_get(txn, MAIN_DBI, &key, &data);
2932 /* Create if requested */
2933 if (rc == ENOENT && (flags & MDB_CREATE)) {
2935 data.mv_size = sizeof(MDB_db);
2936 data.mv_data = &dummy;
2937 memset(&dummy, 0, sizeof(dummy));
2938 dummy.md_root = P_INVALID;
2939 dummy.md_flags = flags & 0xffff;
2940 rc = mdb_put(txn, 0, &key, &data, 0);
2943 /* OK, got info, add to table */
2944 if (rc == MDB_SUCCESS) {
2945 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
2946 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
2947 txn->mt_dbxs[txn->mt_numdbs].md_cmp = NULL;
2948 txn->mt_dbxs[txn->mt_numdbs].md_dcmp = NULL;
2949 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
2950 txn->mt_dbxs[txn->mt_numdbs].md_parent = MAIN_DBI;
2951 txn->mt_dbxs[txn->mt_numdbs].md_dirty = 0;
2952 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
2953 *dbi = txn->mt_numdbs;
2960 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
2962 if (txn == NULL || arg == NULL)
2965 arg->ms_psize = txn->mt_env->me_psize;
2966 arg->ms_depth = txn->mt_dbs[dbi].md_depth;
2967 arg->ms_branch_pages = txn->mt_dbs[dbi].md_branch_pages;
2968 arg->ms_leaf_pages = txn->mt_dbs[dbi].md_leaf_pages;
2969 arg->ms_overflow_pages = txn->mt_dbs[dbi].md_overflow_pages;
2970 arg->ms_entries = txn->mt_dbs[dbi].md_entries;
2975 void mdb_close(MDB_txn *txn, MDB_dbi dbi)
2978 if (dbi <= MAIN_DBI || dbi >= txn->mt_numdbs)
2980 ptr = txn->mt_dbxs[dbi].md_name.mv_data;
2981 txn->mt_dbxs[dbi].md_name.mv_data = NULL;
2982 txn->mt_dbxs[dbi].md_name.mv_size = 0;