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 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;
455 ULONG oldest = txn->mt_txnid - 2;
457 if (!txn->mt_env->me_pghead && txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
458 /* See if there's anything in the free DB */
463 mpp.mp_parent = NULL;
465 mdb_search_page(txn, FREE_DBI, NULL, NULL, 0, &mpp);
466 leaf = NODEPTR(mpp.mp_page, 0);
467 kptr = (ULONG *)NODEKEY(leaf);
469 /* It's potentially usable, unless there are still
470 * older readers outstanding. Grab it.
472 if (oldest > *kptr) {
477 mdb_read_data(txn, leaf, &data);
478 idl = (ULONG *)data.mv_data;
479 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
480 mop->mo_next = txn->mt_env->me_pghead;
481 mop->mo_txnid = *kptr;
482 txn->mt_env->me_pghead = mop;
483 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
488 DPRINTF("IDL read txn %lu root %lu num %lu",
489 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
490 for (i=0; i<idl[0]; i++) {
491 DPRINTF("IDL %lu", idl[i+1]);
495 /* drop this IDL from the DB */
496 mpp.mp_parent = NULL;
498 mdb_search_page(txn, FREE_DBI, NULL, NULL, 1, &mpp);
499 leaf = NODEPTR(mpp.mp_page, 0);
500 mdb_del0(txn, FREE_DBI, 0, &mpp, leaf);
503 if (txn->mt_env->me_pghead) {
505 for (i=0; i<txn->mt_env->me_txns->mt_numreaders; i++) {
506 ULONG mr = txn->mt_env->me_txns->mt_readers[i].mr_txnid;
509 oldest = txn->mt_env->me_txns->mt_readers[i].mr_txnid;
511 if (oldest > txn->mt_env->me_pghead->mo_txnid) {
512 MDB_oldpages *mop = txn->mt_env->me_pghead;
513 txn->mt_oldest = oldest;
515 /* FIXME: For now, always use fresh pages. We
516 * really ought to search the free list for a
521 /* peel pages off tail, so we only have to truncate the list */
522 pgno = MDB_IDL_LAST(mop->mo_pages);
523 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
525 if (mop->mo_pages[2] > mop->mo_pages[1])
526 mop->mo_pages[0] = 0;
530 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
531 txn->mt_env->me_pghead = mop->mo_next;
538 if ((dp = malloc(txn->mt_env->me_psize * num + sizeof(MDB_dhead))) == NULL)
541 dp->h.md_parent = parent;
542 dp->h.md_pi = parent_idx;
543 STAILQ_INSERT_TAIL(txn->mt_u.dirty_queue, dp, h.md_next);
544 if (pgno == P_INVALID) {
545 dp->p.mp_pgno = txn->mt_next_pgno;
546 txn->mt_next_pgno += num;
548 dp->p.mp_pgno = pgno;
554 /* Touch a page: make it dirty and re-insert into tree with updated pgno.
557 mdb_touch(MDB_txn *txn, MDB_pageparent *pp)
559 MDB_page *mp = pp->mp_page;
564 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
566 if ((dp = mdb_alloc_page(txn, pp->mp_parent, pp->mp_pi, 1)) == NULL)
568 DPRINTF("touched page %lu -> %lu", mp->mp_pgno, dp->p.mp_pgno);
569 mdb_idl_insert(txn->mt_free_pgs, mp->mp_pgno);
570 pgno = dp->p.mp_pgno;
571 memcpy(&dp->p, mp, txn->mt_env->me_psize);
574 mp->mp_flags |= P_DIRTY;
576 /* Update the page number to new touched page. */
577 if (pp->mp_parent != NULL)
578 NODEPGNO(NODEPTR(pp->mp_parent, pp->mp_pi)) = mp->mp_pgno;
585 mdbenv_sync(MDB_env *env)
588 if (!F_ISSET(env->me_flags, MDB_NOSYNC)) {
589 if (fsync(env->me_fd))
596 mdb_txn_begin(MDB_env *env, int rdonly, MDB_txn **ret)
601 if ((txn = calloc(1, sizeof(*txn))) == NULL) {
602 DPRINTF("calloc: %s", strerror(errno));
607 txn->mt_flags |= MDB_TXN_RDONLY;
609 txn->mt_u.dirty_queue = calloc(1, sizeof(*txn->mt_u.dirty_queue));
610 if (txn->mt_u.dirty_queue == NULL) {
614 STAILQ_INIT(txn->mt_u.dirty_queue);
616 pthread_mutex_lock(&env->me_txns->mt_wmutex);
617 env->me_txns->mt_txnid++;
618 txn->mt_free_pgs = env->me_free_pgs;
619 txn->mt_free_pgs[0] = 0;
622 txn->mt_txnid = env->me_txns->mt_txnid;
624 MDB_reader *r = pthread_getspecific(env->me_txkey);
627 pthread_mutex_lock(&env->me_txns->mt_mutex);
628 for (i=0; i<env->me_txns->mt_numreaders; i++)
629 if (env->me_txns->mt_readers[i].mr_pid == 0)
631 if (i == env->me_maxreaders) {
632 pthread_mutex_unlock(&env->me_txns->mti_mutex);
635 env->me_txns->mt_readers[i].mr_pid = getpid();
636 env->me_txns->mt_readers[i].mr_tid = pthread_self();
637 r = &env->me_txns->mt_readers[i];
638 pthread_setspecific(env->me_txkey, r);
639 if (i >= env->me_txns->mt_numreaders)
640 env->me_txns->mt_numreaders = i+1;
641 pthread_mutex_unlock(&env->me_txns->mt_mutex);
643 r->mr_txnid = txn->mt_txnid;
644 txn->mt_u.reader = r;
651 if ((rc = mdbenv_read_meta(env, &toggle)) != MDB_SUCCESS) {
656 /* Copy the DB arrays */
657 txn->mt_numdbs = env->me_numdbs;
658 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
659 txn->mt_dbs = malloc(env->me_maxdbs * sizeof(MDB_db));
660 memcpy(txn->mt_dbs, env->me_meta->mm_dbs, 2 * sizeof(MDB_db));
661 if (txn->mt_numdbs > 2)
662 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
663 (txn->mt_numdbs - 2) * sizeof(MDB_db));
667 txn->mt_flags |= MDB_TXN_METOGGLE;
668 txn->mt_next_pgno = env->me_meta->mm_last_pg+1;
671 DPRINTF("begin transaction %lu on mdbenv %p, root page %lu",
672 txn->mt_txnid, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
679 mdb_txn_abort(MDB_txn *txn)
688 DPRINTF("abort transaction %lu on mdbenv %p, root page %lu",
689 txn->mt_txnid, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
693 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
694 txn->mt_u.reader->mr_txnid = 0;
699 /* Discard all dirty pages. */
700 while (!STAILQ_EMPTY(txn->mt_u.dirty_queue)) {
701 dp = STAILQ_FIRST(txn->mt_u.dirty_queue);
702 STAILQ_REMOVE_HEAD(txn->mt_u.dirty_queue, h.md_next);
705 free(txn->mt_u.dirty_queue);
707 while ((mop = txn->mt_env->me_pghead)) {
708 txn->mt_env->me_pghead = mop->mo_next;
713 env->me_txns->mt_txnid--;
714 for (i=2; i<env->me_numdbs; i++)
715 env->me_dbxs[i].md_dirty = 0;
716 pthread_mutex_unlock(&env->me_txns->mt_wmutex);
723 mdb_txn_commit(MDB_txn *txn)
732 struct iovec iov[MDB_COMMIT_PAGES];
735 assert(txn->mt_env != NULL);
739 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
740 DPRINTF("attempt to commit read-only transaction");
745 if (txn != env->me_txn) {
746 DPRINTF("attempt to commit unknown transaction");
751 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
752 DPRINTF("error flag is set, can't commit");
757 if (STAILQ_EMPTY(txn->mt_u.dirty_queue))
760 DPRINTF("committing transaction %lu on mdbenv %p, root page %lu",
761 txn->mt_txnid, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
763 /* should only be one record now */
764 if (env->me_pghead) {
768 mop = env->me_pghead;
769 key.mv_size = sizeof(pgno_t);
770 key.mv_data = (char *)&mop->mo_txnid;
771 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
772 data.mv_data = mop->mo_pages;
773 mdb_put(txn, FREE_DBI, &key, &data, 0);
774 free(env->me_pghead);
775 env->me_pghead = NULL;
777 /* save to free list */
778 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
782 /* make sure last page of freeDB is touched and on freelist */
783 key.mv_size = MAXKEYSIZE+1;
785 mpp.mp_parent = NULL;
787 mdb_search_page(txn, FREE_DBI, &key, NULL, 1, &mpp);
792 ULONG *idl = txn->mt_free_pgs;
793 DPRINTF("IDL write txn %lu root %lu num %lu",
794 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
795 for (i=0; i<idl[0]; i++) {
796 DPRINTF("IDL %lu", idl[i+1]);
800 /* write to last page of freeDB */
801 key.mv_size = sizeof(pgno_t);
802 key.mv_data = (char *)&txn->mt_txnid;
803 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
804 data.mv_data = txn->mt_free_pgs;
805 mdb_put(txn, FREE_DBI, &key, &data, 0);
808 /* Update DB root pointers. Their pages have already been
809 * touched so this is all in-place and cannot fail.
813 data.mv_size = sizeof(MDB_db);
815 for (i = 2; i < txn->mt_numdbs; i++) {
816 if (txn->mt_dbxs[i].md_dirty) {
817 data.mv_data = &txn->mt_dbs[i];
818 mdb_put(txn, i, &txn->mt_dbxs[i].md_name, &data, 0);
823 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
830 STAILQ_FOREACH(dp, txn->mt_u.dirty_queue, h.md_next) {
831 if (dp->p.mp_pgno != next) {
833 DPRINTF("committing %u dirty pages", n);
834 rc = writev(env->me_fd, iov, n);
838 DPRINTF("short write, filesystem full?");
840 DPRINTF("writev: %s", strerror(errno));
847 lseek(env->me_fd, dp->p.mp_pgno * env->me_psize, SEEK_SET);
848 next = dp->p.mp_pgno;
850 DPRINTF("committing page %lu", dp->p.mp_pgno);
851 iov[n].iov_len = env->me_psize * dp->h.md_num;
852 iov[n].iov_base = &dp->p;
853 size += iov[n].iov_len;
854 next = dp->p.mp_pgno + dp->h.md_num;
855 /* clear dirty flag */
856 dp->p.mp_flags &= ~P_DIRTY;
857 if (++n >= MDB_COMMIT_PAGES) {
866 DPRINTF("committing %u dirty pages", n);
867 rc = writev(env->me_fd, iov, n);
871 DPRINTF("short write, filesystem full?");
873 DPRINTF("writev: %s", strerror(errno));
880 /* Drop the dirty pages.
882 while (!STAILQ_EMPTY(txn->mt_u.dirty_queue)) {
883 dp = STAILQ_FIRST(txn->mt_u.dirty_queue);
884 STAILQ_REMOVE_HEAD(txn->mt_u.dirty_queue, h.md_next);
888 if ((n = mdbenv_sync(env)) != 0 ||
889 (n = mdbenv_write_meta(txn)) != MDB_SUCCESS ||
890 (n = mdbenv_sync(env)) != 0) {
896 /* update the DB tables */
898 int toggle = !env->me_db_toggle;
900 for (i = 2; i < env->me_numdbs; i++) {
901 if (txn->mt_dbxs[i].md_dirty) {
902 env->me_dbs[toggle][i] = txn->mt_dbs[i];
903 txn->mt_dbxs[i].md_dirty = 0;
906 for (i = env->me_numdbs; i < txn->mt_numdbs; i++) {
907 txn->mt_dbxs[i].md_dirty = 0;
908 env->me_dbxs[i] = txn->mt_dbxs[i];
909 env->me_dbs[toggle][i] = txn->mt_dbs[i];
911 env->me_db_toggle = toggle;
912 env->me_numdbs = txn->mt_numdbs;
917 pthread_mutex_unlock(&env->me_txns->mt_wmutex);
918 free(txn->mt_u.dirty_queue);
929 mdbenv_read_header(MDB_env *env, MDB_meta *meta)
938 /* We don't know the page size yet, so use a minimum value.
941 if ((rc = pread(env->me_fd, page, PAGESIZE, 0)) == 0) {
943 } else if (rc != PAGESIZE) {
946 DPRINTF("read: %s", strerror(errno));
950 p = (MDB_page *)page;
952 if (!F_ISSET(p->mp_flags, P_META)) {
953 DPRINTF("page %lu not a meta page", p->mp_pgno);
958 if (m->mm_magic != MDB_MAGIC) {
959 DPRINTF("meta has invalid magic");
963 if (m->mm_version != MDB_VERSION) {
964 DPRINTF("database is version %u, expected version %u",
965 m->mm_version, MDB_VERSION);
969 memcpy(meta, m, sizeof(*m));
974 mdbenv_init_meta(MDB_env *env, MDB_meta *meta)
981 DPRINTF("writing new meta page");
982 psize = sysconf(_SC_PAGE_SIZE);
984 meta->mm_magic = MDB_MAGIC;
985 meta->mm_version = MDB_VERSION;
986 meta->mm_psize = psize;
987 meta->mm_last_pg = 1;
988 meta->mm_flags = env->me_flags & 0xffff;
989 #if __BYTE_ORDER == __LITTLE_ENDIAN
990 /* freeDB keys are pgno_t's, must compare in int order */
991 meta->mm_flags |= MDB_REVERSEKEY;
993 meta->mm_dbs[0].md_root = P_INVALID;
994 meta->mm_dbs[1].md_root = P_INVALID;
996 p = calloc(2, psize);
998 p->mp_flags = P_META;
1001 memcpy(m, meta, sizeof(*meta));
1003 q = (MDB_page *)((char *)p + psize);
1006 q->mp_flags = P_META;
1009 memcpy(m, meta, sizeof(*meta));
1011 rc = write(env->me_fd, p, psize * 2);
1013 return (rc == (int)psize * 2) ? MDB_SUCCESS : errno;
1017 mdbenv_write_meta(MDB_txn *txn)
1025 assert(txn != NULL);
1026 assert(txn->mt_env != NULL);
1028 DPRINTF("writing meta page for root page %lu", txn->mt_dbs[MAIN_DBI].md_root);
1032 ptr = (char *)&meta;
1033 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
1034 len = sizeof(MDB_meta) - off;
1037 meta.mm_dbs[0] = txn->mt_dbs[0];
1038 meta.mm_dbs[1] = txn->mt_dbs[1];
1039 meta.mm_last_pg = txn->mt_next_pgno - 1;
1040 meta.mm_txnid = txn->mt_txnid;
1042 if (!F_ISSET(txn->mt_flags, MDB_TXN_METOGGLE))
1043 off += env->me_psize;
1046 lseek(env->me_fd, off, SEEK_SET);
1047 rc = write(env->me_fd, ptr, len);
1049 DPRINTF("write failed, disk error?");
1057 mdbenv_read_meta(MDB_env *env, int *which)
1061 assert(env != NULL);
1063 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1066 if (env->me_meta != env->me_metas[toggle])
1067 env->me_meta = env->me_metas[toggle];
1071 DPRINTF("Using meta page %d", toggle);
1077 mdbenv_create(MDB_env **env)
1081 e = calloc(1, sizeof(*e));
1082 if (!e) return ENOMEM;
1084 e->me_maxreaders = DEFAULT_READERS;
1093 mdbenv_set_mapsize(MDB_env *env, size_t size)
1097 env->me_mapsize = size;
1102 mdbenv_set_maxdbs(MDB_env *env, int dbs)
1106 env->me_maxdbs = dbs;
1111 mdbenv_set_maxreaders(MDB_env *env, int readers)
1113 env->me_maxreaders = readers;
1118 mdbenv_get_maxreaders(MDB_env *env, int *readers)
1120 if (!env || !readers)
1122 *readers = env->me_maxreaders;
1127 mdbenv_open2(MDB_env *env, unsigned int flags)
1133 env->me_flags = flags;
1135 memset(&meta, 0, sizeof(meta));
1137 if ((i = mdbenv_read_header(env, &meta)) != 0) {
1140 DPRINTF("new mdbenv");
1144 if (!env->me_mapsize) {
1145 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
1149 if (meta.mm_address && (flags & MDB_FIXEDMAP))
1151 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
1153 if (env->me_map == MAP_FAILED)
1157 meta.mm_mapsize = env->me_mapsize;
1158 if (flags & MDB_FIXEDMAP)
1159 meta.mm_address = env->me_map;
1160 i = mdbenv_init_meta(env, &meta);
1161 if (i != MDB_SUCCESS) {
1162 munmap(env->me_map, env->me_mapsize);
1166 env->me_psize = meta.mm_psize;
1168 p = (MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)(MDB_page *)env->me_map;
1169 env->me_metas[0] = METADATA(p);
1170 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
1172 if ((i = mdbenv_read_meta(env, NULL)) != 0)
1175 DPRINTF("opened database version %u, pagesize %u",
1176 env->me_meta->mm_version, env->me_psize);
1177 DPRINTF("depth: %u", env->me_meta->mm_dbs[MAIN_DBI].md_depth);
1178 DPRINTF("entries: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_entries);
1179 DPRINTF("branch pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_branch_pages);
1180 DPRINTF("leaf pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_leaf_pages);
1181 DPRINTF("overflow pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_overflow_pages);
1182 DPRINTF("root: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_root);
1188 mdbenv_reader_dest(void *ptr)
1190 MDB_reader *reader = ptr;
1192 reader->mr_txnid = 0;
1197 /* downgrade the exclusive lock on the region back to shared */
1199 mdbenv_share_locks(MDB_env *env)
1201 struct flock lock_info;
1203 env->me_txns->mt_txnid = env->me_meta->mm_txnid;
1205 memset((void *)&lock_info, 0, sizeof(lock_info));
1206 lock_info.l_type = F_RDLCK;
1207 lock_info.l_whence = SEEK_SET;
1208 lock_info.l_start = 0;
1209 lock_info.l_len = 1;
1210 fcntl(env->me_lfd, F_SETLK, &lock_info);
1214 mdbenv_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
1218 struct flock lock_info;
1222 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
1226 /* Try to get exclusive lock. If we succeed, then
1227 * nobody is using the lock region and we should initialize it.
1229 memset((void *)&lock_info, 0, sizeof(lock_info));
1230 lock_info.l_type = F_WRLCK;
1231 lock_info.l_whence = SEEK_SET;
1232 lock_info.l_start = 0;
1233 lock_info.l_len = 1;
1234 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1238 lock_info.l_type = F_RDLCK;
1239 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1245 size = lseek(env->me_lfd, 0, SEEK_END);
1246 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1247 if (size < rsize && *excl) {
1248 if (ftruncate(env->me_lfd, rsize) != 0) {
1254 size = rsize - sizeof(MDB_txninfo);
1255 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
1257 env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
1259 if (env->me_txns == MAP_FAILED) {
1264 pthread_mutexattr_t mattr;
1266 pthread_mutexattr_init(&mattr);
1267 pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
1268 pthread_mutex_init(&env->me_txns->mt_mutex, &mattr);
1269 pthread_mutex_init(&env->me_txns->mt_wmutex, &mattr);
1270 env->me_txns->mt_version = MDB_VERSION;
1271 env->me_txns->mt_magic = MDB_MAGIC;
1272 env->me_txns->mt_txnid = 0;
1273 env->me_txns->mt_numreaders = 0;
1276 if (env->me_txns->mt_magic != MDB_MAGIC) {
1277 DPRINTF("lock region has invalid magic");
1280 if (env->me_txns->mt_version != MDB_VERSION) {
1281 DPRINTF("lock region is version %u, expected version %u",
1282 env->me_txns->mt_version, MDB_VERSION);
1285 if (errno != EACCES && errno != EAGAIN) {
1299 mdbenv_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
1301 int oflags, rc, len, excl;
1302 char *lpath, *dpath;
1305 lpath = malloc(len + sizeof("/lock.mdb") + len + sizeof("/data.db"));
1308 dpath = lpath + len + sizeof("/lock.mdb");
1309 sprintf(lpath, "%s/lock.mdb", path);
1310 sprintf(dpath, "%s/data.mdb", path);
1312 rc = mdbenv_setup_locks(env, lpath, mode, &excl);
1316 if (F_ISSET(flags, MDB_RDONLY))
1319 oflags = O_RDWR | O_CREAT;
1321 if ((env->me_fd = open(dpath, oflags, mode)) == -1)
1324 if ((rc = mdbenv_open2(env, flags)) != MDB_SUCCESS) {
1328 env->me_path = strdup(path);
1329 DPRINTF("opened dbenv %p", (void *) env);
1330 pthread_key_create(&env->me_txkey, mdbenv_reader_dest);
1332 mdbenv_share_locks(env);
1333 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
1334 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
1335 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
1345 mdbenv_close(MDB_env *env)
1354 munmap(env->me_map, env->me_mapsize);
1358 size_t size = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1359 munmap(env->me_txns, size);
1365 /* Search for key within a leaf page, using binary search.
1366 * Returns the smallest entry larger or equal to the key.
1367 * If exactp is non-null, stores whether the found entry was an exact match
1368 * in *exactp (1 or 0).
1369 * If kip is non-null, stores the index of the found entry in *kip.
1370 * If no entry larger or equal to the key is found, returns NULL.
1373 mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, MDB_val *key,
1374 int *exactp, unsigned int *kip)
1382 DPRINTF("searching %u keys in %s page %lu",
1384 IS_LEAF(mp) ? "leaf" : "branch",
1387 assert(NUMKEYS(mp) > 0);
1389 memset(&nodekey, 0, sizeof(nodekey));
1391 low = IS_LEAF(mp) ? 0 : 1;
1392 high = NUMKEYS(mp) - 1;
1393 while (low <= high) {
1394 i = (low + high) >> 1;
1395 node = NODEPTR(mp, i);
1397 nodekey.mv_size = node->mn_ksize;
1398 nodekey.mv_data = NODEKEY(node);
1400 if (txn->mt_dbxs[dbi].md_cmp)
1401 rc = txn->mt_dbxs[dbi].md_cmp(key, &nodekey);
1403 rc = _mdb_cmp(txn, dbi, key, &nodekey);
1406 DPRINTF("found leaf index %u [%.*s], rc = %i",
1407 i, (int)nodekey.mv_size, (char *)nodekey.mv_data, rc);
1409 DPRINTF("found branch index %u [%.*s -> %lu], rc = %i",
1410 i, (int)node->mn_ksize, (char *)NODEKEY(node),
1421 if (rc > 0) { /* Found entry is less than the key. */
1422 i++; /* Skip to get the smallest entry larger than key. */
1423 if (i >= NUMKEYS(mp))
1424 /* There is no entry larger or equal to the key. */
1428 *exactp = (rc == 0);
1429 if (kip) /* Store the key index if requested. */
1432 return NODEPTR(mp, i);
1436 cursor_pop_page(MDB_cursor *cursor)
1440 top = CURSOR_TOP(cursor);
1443 DPRINTF("popped page %lu off cursor %p", top->mp_page->mp_pgno, (void *) cursor);
1449 cursor_push_page(MDB_cursor *cursor, MDB_page *mp)
1453 DPRINTF("pushing page %lu on cursor %p", mp->mp_pgno, (void *) cursor);
1455 if ((ppage = calloc(1, sizeof(*ppage))) == NULL)
1457 ppage->mp_page = mp;
1458 CURSOR_PUSH(cursor, ppage);
1463 mdb_get_page(MDB_txn *txn, pgno_t pgno)
1468 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && !STAILQ_EMPTY(txn->mt_u.dirty_queue)) {
1470 STAILQ_FOREACH(dp, txn->mt_u.dirty_queue, h.md_next) {
1471 if (dp->p.mp_pgno == pgno) {
1479 if (pgno > txn->mt_env->me_meta->mm_last_pg)
1481 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
1487 mdb_search_page_root(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
1488 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
1490 MDB_page *mp = mpp->mp_page;
1493 if (cursor && cursor_push_page(cursor, mp) == NULL)
1496 while (IS_BRANCH(mp)) {
1500 DPRINTF("branch page %lu has %u keys", mp->mp_pgno, NUMKEYS(mp));
1501 assert(NUMKEYS(mp) > 1);
1502 DPRINTF("found index 0 to page %lu", NODEPGNO(NODEPTR(mp, 0)));
1504 if (key == NULL) /* Initialize cursor to first page. */
1506 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
1507 /* cursor to last page */
1511 node = mdb_search_node(txn, dbi, mp, key, &exact, &i);
1513 i = NUMKEYS(mp) - 1;
1521 DPRINTF("following index %u for key %.*s",
1522 i, (int)key->mv_size, (char *)key->mv_data);
1523 assert(i < NUMKEYS(mp));
1524 node = NODEPTR(mp, i);
1527 CURSOR_TOP(cursor)->mp_ki = i;
1529 mpp->mp_parent = mp;
1530 if ((mp = mdb_get_page(txn, NODEPGNO(node))) == NULL)
1535 if (cursor && cursor_push_page(cursor, mp) == NULL)
1539 MDB_dhead *dh = ((MDB_dhead *)mp)-1;
1540 if ((rc = mdb_touch(txn, mpp)) != 0)
1542 dh = ((MDB_dhead *)mpp->mp_page)-1;
1543 dh->md_parent = mpp->mp_parent;
1544 dh->md_pi = mpp->mp_pi;
1551 DPRINTF("internal error, index points to a %02X page!?",
1556 DPRINTF("found leaf page %lu for key %.*s", mp->mp_pgno,
1557 key ? (int)key->mv_size : 0, key ? (char *)key->mv_data : NULL);
1562 /* Search for the page a given key should be in.
1563 * Stores a pointer to the found page in *mpp.
1564 * If key is NULL, search for the lowest page (used by mdb_cursor_first).
1565 * If cursor is non-null, pushes parent pages on the cursor stack.
1566 * If modify is true, visited pages are updated with new page numbers.
1569 mdb_search_page(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
1570 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
1575 /* Choose which root page to start with. If a transaction is given
1576 * use the root page from the transaction, otherwise read the last
1577 * committed root page.
1579 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1580 DPRINTF("transaction has failed, must abort");
1583 root = txn->mt_dbs[dbi].md_root;
1585 if (root == P_INVALID) { /* Tree is empty. */
1586 DPRINTF("tree is empty");
1590 if ((mpp->mp_page = mdb_get_page(txn, root)) == NULL)
1593 DPRINTF("root page has flags 0x%X", mpp->mp_page->mp_flags);
1596 /* For sub-databases, update main root first */
1597 if (dbi > MAIN_DBI && !txn->mt_dbxs[dbi].md_dirty) {
1599 rc = mdb_search_page(txn, 0, &txn->mt_dbxs[dbi].md_name,
1603 txn->mt_dbxs[dbi].md_dirty = 1;
1605 if (!F_ISSET(mpp->mp_page->mp_flags, P_DIRTY)) {
1606 mpp->mp_parent = NULL;
1608 if ((rc = mdb_touch(txn, mpp)))
1610 txn->mt_dbs[dbi].md_root = mpp->mp_page->mp_pgno;
1614 return mdb_search_page_root(txn, dbi, key, cursor, modify, mpp);
1618 mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
1620 MDB_page *omp; /* overflow mpage */
1623 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
1624 data->mv_size = leaf->mn_dsize;
1625 data->mv_data = NODEDATA(leaf);
1629 /* Read overflow data.
1631 data->mv_size = leaf->mn_dsize;
1632 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
1633 if ((omp = mdb_get_page(txn, pgno)) == NULL) {
1634 DPRINTF("read overflow page %lu failed", pgno);
1637 data->mv_data = omp;
1643 mdb_get(MDB_txn *txn, MDB_dbi dbi,
1644 MDB_val *key, MDB_val *data)
1652 DPRINTF("===> get key [%.*s]", (int)key->mv_size, (char *)key->mv_data);
1654 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
1658 if ((rc = mdb_search_page(txn, dbi, key, NULL, 0, &mpp)) != MDB_SUCCESS)
1661 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, NULL);
1662 if (leaf && exact) {
1663 /* Return first duplicate data item */
1664 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
1667 mdb_xcursor_init0(txn, dbi, &mx);
1668 mdb_xcursor_init1(txn, dbi, &mx, NODEDATA(leaf));
1669 rc = mdb_search_page(&mx.mx_txn, mx.mx_txn.mt_numdbs-1, NULL, NULL, 0, &mpp);
1670 if (rc != MDB_SUCCESS)
1672 leaf = NODEPTR(mpp.mp_page, 0);
1674 rc = mdb_read_data(txn, leaf, data);
1683 mdb_sibling(MDB_cursor *cursor, int move_right)
1687 MDB_ppage *parent, *top;
1690 top = CURSOR_TOP(cursor);
1691 if ((parent = SLIST_NEXT(top, mp_entry)) == NULL) {
1692 return ENOENT; /* root has no siblings */
1695 DPRINTF("parent page is page %lu, index %u",
1696 parent->mp_page->mp_pgno, parent->mp_ki);
1698 cursor_pop_page(cursor);
1699 if (move_right ? (parent->mp_ki + 1 >= NUMKEYS(parent->mp_page))
1700 : (parent->mp_ki == 0)) {
1701 DPRINTF("no more keys left, moving to %s sibling",
1702 move_right ? "right" : "left");
1703 if ((rc = mdb_sibling(cursor, move_right)) != MDB_SUCCESS)
1705 parent = CURSOR_TOP(cursor);
1711 DPRINTF("just moving to %s index key %u",
1712 move_right ? "right" : "left", parent->mp_ki);
1714 assert(IS_BRANCH(parent->mp_page));
1716 indx = NODEPTR(parent->mp_page, parent->mp_ki);
1717 if ((mp = mdb_get_page(cursor->mc_txn, indx->mn_pgno)) == NULL)
1720 mp->parent = parent->mp_page;
1721 mp->parent_index = parent->mp_ki;
1724 cursor_push_page(cursor, mp);
1730 mdb_set_key(MDB_node *node, MDB_val *key)
1735 key->mv_size = node->mn_ksize;
1736 key->mv_data = NODEKEY(node);
1742 mdb_cursor_next(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
1748 if (cursor->mc_eof) {
1752 assert(cursor->mc_initialized);
1754 top = CURSOR_TOP(cursor);
1757 DPRINTF("cursor_next: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
1759 if (top->mp_ki + 1 >= NUMKEYS(mp)) {
1760 DPRINTF("=====> move to next sibling page");
1761 if (mdb_sibling(cursor, 1) != MDB_SUCCESS) {
1765 top = CURSOR_TOP(cursor);
1767 DPRINTF("next page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
1771 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
1772 mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
1774 assert(IS_LEAF(mp));
1775 leaf = NODEPTR(mp, top->mp_ki);
1777 if (data && mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS)
1780 return mdb_set_key(leaf, key);
1784 mdb_cursor_prev(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
1790 assert(cursor->mc_initialized);
1792 top = CURSOR_TOP(cursor);
1795 DPRINTF("cursor_prev: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
1797 if (top->mp_ki == 0) {
1798 DPRINTF("=====> move to prev sibling page");
1799 if (mdb_sibling(cursor, 0) != MDB_SUCCESS) {
1802 top = CURSOR_TOP(cursor);
1804 top->mp_ki = NUMKEYS(mp) - 1;
1805 DPRINTF("prev page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
1811 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
1812 mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
1814 assert(IS_LEAF(mp));
1815 leaf = NODEPTR(mp, top->mp_ki);
1817 if (data && mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS)
1820 return mdb_set_key(leaf, key);
1824 mdb_cursor_set(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
1834 assert(key->mv_size > 0);
1836 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, key, cursor, 0, &mpp);
1837 if (rc != MDB_SUCCESS)
1839 assert(IS_LEAF(mpp.mp_page));
1841 top = CURSOR_TOP(cursor);
1842 leaf = mdb_search_node(cursor->mc_txn, cursor->mc_dbi, mpp.mp_page, key, exactp, &top->mp_ki);
1843 if (exactp != NULL && !*exactp) {
1844 /* MDB_SET specified and not an exact match. */
1849 DPRINTF("===> inexact leaf not found, goto sibling");
1850 if ((rc = mdb_sibling(cursor, 1)) != MDB_SUCCESS)
1851 return rc; /* no entries matched */
1852 top = CURSOR_TOP(cursor);
1854 mpp.mp_page = top->mp_page;
1855 assert(IS_LEAF(mpp.mp_page));
1856 leaf = NODEPTR(mpp.mp_page, 0);
1859 cursor->mc_initialized = 1;
1862 if (data && (rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
1865 rc = mdb_set_key(leaf, key);
1866 if (rc == MDB_SUCCESS) {
1867 DPRINTF("==> cursor placed on key %.*s",
1868 (int)key->mv_size, (char *)key->mv_data);
1876 mdb_cursor_first(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
1882 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, NULL, cursor, 0, &mpp);
1883 if (rc != MDB_SUCCESS)
1885 assert(IS_LEAF(mpp.mp_page));
1887 leaf = NODEPTR(mpp.mp_page, 0);
1888 cursor->mc_initialized = 1;
1891 if (data && (rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
1894 return mdb_set_key(leaf, key);
1898 mdb_cursor_last(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
1906 lkey.mv_size = MAXKEYSIZE+1;
1907 lkey.mv_data = NULL;
1909 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, &lkey, cursor, 0, &mpp);
1910 if (rc != MDB_SUCCESS)
1912 assert(IS_LEAF(mpp.mp_page));
1914 leaf = NODEPTR(mpp.mp_page, NUMKEYS(mpp.mp_page)-1);
1915 cursor->mc_initialized = 1;
1918 top = CURSOR_TOP(cursor);
1919 top->mp_ki = NUMKEYS(top->mp_page) - 1;
1921 if (data && (rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
1924 return mdb_set_key(leaf, key);
1928 mdb_cursor_get(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
1939 while (CURSOR_TOP(cursor) != NULL)
1940 cursor_pop_page(cursor);
1941 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
1943 } else if (op == MDB_SET)
1944 rc = mdb_cursor_set(cursor, key, data, &exact);
1946 rc = mdb_cursor_set(cursor, key, data, NULL);
1949 if (!cursor->mc_initialized)
1950 rc = mdb_cursor_first(cursor, key, data);
1952 rc = mdb_cursor_next(cursor, key, data);
1955 if (!cursor->mc_initialized || cursor->mc_eof) {
1956 while (CURSOR_TOP(cursor) != NULL)
1957 cursor_pop_page(cursor);
1958 rc = mdb_cursor_last(cursor, key, data);
1960 rc = mdb_cursor_prev(cursor, key, data);
1963 while (CURSOR_TOP(cursor) != NULL)
1964 cursor_pop_page(cursor);
1965 rc = mdb_cursor_first(cursor, key, data);
1968 while (CURSOR_TOP(cursor) != NULL)
1969 cursor_pop_page(cursor);
1970 rc = mdb_cursor_last(cursor, key, data);
1973 DPRINTF("unhandled/unimplemented cursor operation %u", op);
1981 /* Allocate a page and initialize it
1984 mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num)
1988 if ((dp = mdb_alloc_page(txn, NULL, 0, num)) == NULL)
1990 DPRINTF("allocated new mpage %lu, page size %u",
1991 dp->p.mp_pgno, txn->mt_env->me_psize);
1992 dp->p.mp_flags = flags | P_DIRTY;
1993 dp->p.mp_lower = PAGEHDRSZ;
1994 dp->p.mp_upper = txn->mt_env->me_psize;
1996 if (IS_BRANCH(&dp->p))
1997 txn->mt_dbs[dbi].md_branch_pages++;
1998 else if (IS_LEAF(&dp->p))
1999 txn->mt_dbs[dbi].md_leaf_pages++;
2000 else if (IS_OVERFLOW(&dp->p)) {
2001 txn->mt_dbs[dbi].md_overflow_pages += num;
2002 dp->p.mp_pages = num;
2009 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
2013 sz = LEAFSIZE(key, data);
2014 if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
2015 /* put on overflow page */
2016 sz -= data->mv_size - sizeof(pgno_t);
2019 return sz + sizeof(indx_t);
2023 mdb_branch_size(MDB_env *env, MDB_val *key)
2028 if (sz >= env->me_psize / MDB_MINKEYS) {
2029 /* put on overflow page */
2030 /* not implemented */
2031 /* sz -= key->size - sizeof(pgno_t); */
2034 return sz + sizeof(indx_t);
2038 mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, indx_t indx,
2039 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags)
2042 size_t node_size = NODESIZE;
2045 MDB_dpage *ofp = NULL; /* overflow page */
2047 assert(mp->mp_upper >= mp->mp_lower);
2049 DPRINTF("add node [%.*s] to %s page %lu at index %i, key size %zu",
2050 key ? (int)key->mv_size : 0, key ? (char *)key->mv_data : NULL,
2051 IS_LEAF(mp) ? "leaf" : "branch",
2052 mp->mp_pgno, indx, key ? key->mv_size : 0);
2055 node_size += key->mv_size;
2059 if (F_ISSET(flags, F_BIGDATA)) {
2060 /* Data already on overflow page. */
2061 node_size += sizeof(pgno_t);
2062 } else if (data->mv_size >= txn->mt_env->me_psize / MDB_MINKEYS) {
2063 int ovpages = OVPAGES(data->mv_size, txn->mt_env->me_psize);
2064 /* Put data on overflow page. */
2065 DPRINTF("data size is %zu, put on overflow page",
2067 node_size += sizeof(pgno_t);
2068 if ((ofp = mdb_new_page(txn, dbi, P_OVERFLOW, ovpages)) == NULL)
2070 DPRINTF("allocated overflow page %lu", ofp->p.mp_pgno);
2073 node_size += data->mv_size;
2077 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
2078 DPRINTF("not enough room in page %lu, got %u ptrs",
2079 mp->mp_pgno, NUMKEYS(mp));
2080 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
2081 mp->mp_upper - mp->mp_lower);
2082 DPRINTF("node size = %zu", node_size);
2086 /* Move higher pointers up one slot. */
2087 for (i = NUMKEYS(mp); i > indx; i--)
2088 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
2090 /* Adjust free space offsets. */
2091 ofs = mp->mp_upper - node_size;
2092 assert(ofs >= mp->mp_lower + sizeof(indx_t));
2093 mp->mp_ptrs[indx] = ofs;
2095 mp->mp_lower += sizeof(indx_t);
2097 /* Write the node data. */
2098 node = NODEPTR(mp, indx);
2099 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
2100 node->mn_flags = flags;
2102 node->mn_dsize = data->mv_size;
2104 node->mn_pgno = pgno;
2107 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
2112 if (F_ISSET(flags, F_BIGDATA))
2113 memcpy(node->mn_data + key->mv_size, data->mv_data,
2116 memcpy(node->mn_data + key->mv_size, data->mv_data,
2119 memcpy(node->mn_data + key->mv_size, &ofp->p.mp_pgno,
2121 memcpy(METADATA(&ofp->p), data->mv_data, data->mv_size);
2129 mdb_del_node(MDB_page *mp, indx_t indx)
2132 indx_t i, j, numkeys, ptr;
2136 DPRINTF("delete node %u on %s page %lu", indx,
2137 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
2138 assert(indx < NUMKEYS(mp));
2140 node = NODEPTR(mp, indx);
2141 sz = NODESIZE + node->mn_ksize;
2143 if (F_ISSET(node->mn_flags, F_BIGDATA))
2144 sz += sizeof(pgno_t);
2146 sz += NODEDSZ(node);
2149 ptr = mp->mp_ptrs[indx];
2150 numkeys = NUMKEYS(mp);
2151 for (i = j = 0; i < numkeys; i++) {
2153 mp->mp_ptrs[j] = mp->mp_ptrs[i];
2154 if (mp->mp_ptrs[i] < ptr)
2155 mp->mp_ptrs[j] += sz;
2160 base = (char *)mp + mp->mp_upper;
2161 memmove(base + sz, base, ptr - mp->mp_upper);
2163 mp->mp_lower -= sizeof(indx_t);
2168 mdb_xcursor_init0(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
2172 mx->mx_cursor.mc_txn = &mx->mx_txn;
2174 mx->mx_txn.mt_dbxs = mx->mx_dbxs;
2175 mx->mx_txn.mt_dbs = mx->mx_dbs;
2176 mx->mx_dbxs[0] = txn->mt_dbxs[0];
2177 mx->mx_dbxs[1] = txn->mt_dbxs[1];
2179 mx->mx_dbxs[2] = txn->mt_dbxs[dbi];
2184 mx->mx_dbxs[dbn+1].md_parent = dbn;
2185 mx->mx_dbxs[dbn+1].md_cmp = mx->mx_dbxs[dbn].md_dcmp;
2186 mx->mx_dbxs[dbn+1].md_rel = mx->mx_dbxs[dbn].md_rel;
2187 mx->mx_dbxs[dbn+1].md_dirty = 0;
2188 mx->mx_txn.mt_numdbs = dbn+2;
2192 mdb_xcursor_init1(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx, MDB_db *db)
2194 mx->mx_dbs[0] = txn->mt_dbs[0];
2195 mx->mx_dbs[1] = txn->mt_dbs[1];
2197 mx->mx_dbs[2] = txn->mt_dbs[dbi];
2198 mx->mx_dbs[3] = *db;
2200 mx->mx_dbs[2] = *db;
2205 mdb_xcursor_fini(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
2207 txn->mt_dbs[0] = mx->mx_dbs[0];
2208 txn->mt_dbs[1] = mx->mx_dbs[1];
2209 txn->mt_dbxs[0].md_dirty = mx->mx_dbxs[0].md_dirty;
2210 txn->mt_dbxs[1].md_dirty = mx->mx_dbxs[1].md_dirty;
2212 txn->mt_dbs[dbi] = mx->mx_dbs[2];
2213 txn->mt_dbxs[2].md_dirty = mx->mx_dbxs[2].md_dirty;
2218 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
2221 size_t size = sizeof(MDB_cursor);
2223 if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
2226 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
2227 size += sizeof(MDB_xcursor);
2229 if ((cursor = calloc(1, size)) != NULL) {
2230 SLIST_INIT(&cursor->mc_stack);
2231 cursor->mc_dbi = dbi;
2232 cursor->mc_txn = txn;
2233 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
2234 MDB_xcursor *mx = (MDB_xcursor *)(cursor + 1);
2235 cursor->mc_xcursor = mx;
2236 mdb_xcursor_init0(txn, dbi, mx);
2248 mdb_cursor_close(MDB_cursor *cursor)
2250 if (cursor != NULL) {
2251 while (!CURSOR_EMPTY(cursor))
2252 cursor_pop_page(cursor);
2254 /* btree_close(cursor->bt); */
2260 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
2262 indx_t ptr, i, numkeys;
2268 node = NODEPTR(mp, indx);
2269 ptr = mp->mp_ptrs[indx];
2270 DPRINTF("update key %u (ofs %u) [%.*s] to [%.*s] on page %lu",
2272 (int)node->mn_ksize, (char *)NODEKEY(node),
2273 (int)key->mv_size, (char *)key->mv_data,
2276 delta = key->mv_size - node->mn_ksize;
2278 if (delta > 0 && SIZELEFT(mp) < delta) {
2279 DPRINTF("OUCH! Not enough room, delta = %d", delta);
2283 numkeys = NUMKEYS(mp);
2284 for (i = 0; i < numkeys; i++) {
2285 if (mp->mp_ptrs[i] <= ptr)
2286 mp->mp_ptrs[i] -= delta;
2289 base = (char *)mp + mp->mp_upper;
2290 len = ptr - mp->mp_upper + NODESIZE;
2291 memmove(base - delta, base, len);
2292 mp->mp_upper -= delta;
2294 node = NODEPTR(mp, indx);
2295 node->mn_ksize = key->mv_size;
2298 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
2303 /* Move a node from src to dst.
2306 mdb_move_node(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, indx_t srcindx,
2307 MDB_pageparent *dst, indx_t dstindx)
2313 srcnode = NODEPTR(src->mp_page, srcindx);
2314 DPRINTF("moving %s node %u [%.*s] on page %lu to node %u on page %lu",
2315 IS_LEAF(src->mp_page) ? "leaf" : "branch",
2317 (int)srcnode->mn_ksize, (char *)NODEKEY(srcnode),
2318 src->mp_page->mp_pgno,
2319 dstindx, dst->mp_page->mp_pgno);
2321 /* Mark src and dst as dirty. */
2322 if ((rc = mdb_touch(txn, src)) ||
2323 (rc = mdb_touch(txn, dst)))
2326 /* Add the node to the destination page.
2328 key.mv_size = srcnode->mn_ksize;
2329 key.mv_data = NODEKEY(srcnode);
2330 data.mv_size = NODEDSZ(srcnode);
2331 data.mv_data = NODEDATA(srcnode);
2332 rc = mdb_add_node(txn, dbi, dst->mp_page, dstindx, &key, &data, NODEPGNO(srcnode),
2334 if (rc != MDB_SUCCESS)
2337 /* Delete the node from the source page.
2339 mdb_del_node(src->mp_page, srcindx);
2341 /* Update the parent separators.
2343 if (srcindx == 0 && src->mp_pi != 0) {
2344 DPRINTF("update separator for source page %lu to [%.*s]",
2345 src->mp_page->mp_pgno, (int)key.mv_size, (char *)key.mv_data);
2346 if ((rc = mdb_update_key(src->mp_parent, src->mp_pi,
2347 &key)) != MDB_SUCCESS)
2351 if (srcindx == 0 && IS_BRANCH(src->mp_page)) {
2353 nullkey.mv_size = 0;
2354 assert(mdb_update_key(src->mp_page, 0, &nullkey) == MDB_SUCCESS);
2357 if (dstindx == 0 && dst->mp_pi != 0) {
2358 DPRINTF("update separator for destination page %lu to [%.*s]",
2359 dst->mp_page->mp_pgno, (int)key.mv_size, (char *)key.mv_data);
2360 if ((rc = mdb_update_key(dst->mp_parent, dst->mp_pi,
2361 &key)) != MDB_SUCCESS)
2365 if (dstindx == 0 && IS_BRANCH(dst->mp_page)) {
2367 nullkey.mv_size = 0;
2368 assert(mdb_update_key(dst->mp_page, 0, &nullkey) == MDB_SUCCESS);
2375 mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, MDB_pageparent *dst)
2384 DPRINTF("merging page %lu and %lu", src->mp_page->mp_pgno, dst->mp_page->mp_pgno);
2386 assert(txn != NULL);
2387 assert(src->mp_parent); /* can't merge root page */
2388 assert(dst->mp_parent);
2390 /* Mark src and dst as dirty. */
2391 if ((rc = mdb_touch(txn, src)) ||
2392 (rc = mdb_touch(txn, dst)))
2395 /* Move all nodes from src to dst.
2397 for (i = 0; i < NUMKEYS(src->mp_page); i++) {
2398 srcnode = NODEPTR(src->mp_page, i);
2400 key.mv_size = srcnode->mn_ksize;
2401 key.mv_data = NODEKEY(srcnode);
2402 data.mv_size = NODEDSZ(srcnode);
2403 data.mv_data = NODEDATA(srcnode);
2404 rc = mdb_add_node(txn, dbi, dst->mp_page, NUMKEYS(dst->mp_page), &key,
2405 &data, NODEPGNO(srcnode), srcnode->mn_flags);
2406 if (rc != MDB_SUCCESS)
2410 DPRINTF("dst page %lu now has %u keys (%.1f%% filled)",
2411 dst->mp_page->mp_pgno, NUMKEYS(dst->mp_page), (float)PAGEFILL(txn->mt_env, dst->mp_page) / 10);
2413 /* Unlink the src page from parent.
2415 mdb_del_node(src->mp_parent, src->mp_pi);
2416 if (src->mp_pi == 0) {
2418 if ((rc = mdb_update_key(src->mp_parent, 0, &key)) != MDB_SUCCESS)
2422 if (IS_LEAF(src->mp_page))
2423 txn->mt_dbs[dbi].md_leaf_pages--;
2425 txn->mt_dbs[dbi].md_branch_pages--;
2427 mpp.mp_page = src->mp_parent;
2428 dh = (MDB_dhead *)src->mp_parent;
2430 mpp.mp_parent = dh->md_parent;
2431 mpp.mp_pi = dh->md_pi;
2433 return mdb_rebalance(txn, dbi, &mpp);
2436 #define FILL_THRESHOLD 250
2439 mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mpp)
2444 indx_t si = 0, di = 0;
2446 assert(txn != NULL);
2447 assert(mpp != NULL);
2449 DPRINTF("rebalancing %s page %lu (has %u keys, %.1f%% full)",
2450 IS_LEAF(mpp->mp_page) ? "leaf" : "branch",
2451 mpp->mp_page->mp_pgno, NUMKEYS(mpp->mp_page), (float)PAGEFILL(txn->mt_env, mpp->mp_page) / 10);
2453 if (PAGEFILL(txn->mt_env, mpp->mp_page) >= FILL_THRESHOLD) {
2454 DPRINTF("no need to rebalance page %lu, above fill threshold",
2455 mpp->mp_page->mp_pgno);
2459 if (mpp->mp_parent == NULL) {
2460 if (NUMKEYS(mpp->mp_page) == 0) {
2461 DPRINTF("tree is completely empty");
2462 txn->mt_dbs[dbi].md_root = P_INVALID;
2463 txn->mt_dbs[dbi].md_depth--;
2464 txn->mt_dbs[dbi].md_leaf_pages--;
2465 } else if (IS_BRANCH(mpp->mp_page) && NUMKEYS(mpp->mp_page) == 1) {
2466 DPRINTF("collapsing root page!");
2467 txn->mt_dbs[dbi].md_root = NODEPGNO(NODEPTR(mpp->mp_page, 0));
2468 if ((root = mdb_get_page(txn, txn->mt_dbs[dbi].md_root)) == NULL)
2470 txn->mt_dbs[dbi].md_depth--;
2471 txn->mt_dbs[dbi].md_branch_pages--;
2473 DPRINTF("root page doesn't need rebalancing");
2477 /* The parent (branch page) must have at least 2 pointers,
2478 * otherwise the tree is invalid.
2480 assert(NUMKEYS(mpp->mp_parent) > 1);
2482 /* Leaf page fill factor is below the threshold.
2483 * Try to move keys from left or right neighbor, or
2484 * merge with a neighbor page.
2489 if (mpp->mp_pi == 0) {
2490 /* We're the leftmost leaf in our parent.
2492 DPRINTF("reading right neighbor");
2493 node = NODEPTR(mpp->mp_parent, mpp->mp_pi + 1);
2494 if ((npp.mp_page = mdb_get_page(txn, NODEPGNO(node))) == NULL)
2496 npp.mp_pi = mpp->mp_pi + 1;
2498 di = NUMKEYS(mpp->mp_page);
2500 /* There is at least one neighbor to the left.
2502 DPRINTF("reading left neighbor");
2503 node = NODEPTR(mpp->mp_parent, mpp->mp_pi - 1);
2504 if ((npp.mp_page = mdb_get_page(txn, NODEPGNO(node))) == NULL)
2506 npp.mp_pi = mpp->mp_pi - 1;
2507 si = NUMKEYS(npp.mp_page) - 1;
2510 npp.mp_parent = mpp->mp_parent;
2512 DPRINTF("found neighbor page %lu (%u keys, %.1f%% full)",
2513 npp.mp_page->mp_pgno, NUMKEYS(npp.mp_page), (float)PAGEFILL(txn->mt_env, npp.mp_page) / 10);
2515 /* If the neighbor page is above threshold and has at least two
2516 * keys, move one key from it.
2518 * Otherwise we should try to merge them.
2520 if (PAGEFILL(txn->mt_env, npp.mp_page) >= FILL_THRESHOLD && NUMKEYS(npp.mp_page) >= 2)
2521 return mdb_move_node(txn, dbi, &npp, si, mpp, di);
2522 else { /* FIXME: if (has_enough_room()) */
2523 if (mpp->mp_pi == 0)
2524 return mdb_merge(txn, dbi, &npp, mpp);
2526 return mdb_merge(txn, dbi, mpp, &npp);
2531 mdb_del0(MDB_txn *txn, MDB_dbi dbi, unsigned int ki, MDB_pageparent *mpp, MDB_node *leaf)
2535 /* add overflow pages to free list */
2536 if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
2540 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
2541 ovpages = OVPAGES(NODEDSZ(leaf), txn->mt_env->me_psize);
2542 for (i=0; i<ovpages; i++) {
2543 DPRINTF("freed ov page %lu", pg);
2544 mdb_idl_insert(txn->mt_free_pgs, pg);
2548 mdb_del_node(mpp->mp_page, ki);
2549 txn->mt_dbs[dbi].md_entries--;
2550 rc = mdb_rebalance(txn, dbi, mpp);
2551 if (rc != MDB_SUCCESS)
2552 txn->mt_flags |= MDB_TXN_ERROR;
2558 mdb_del(MDB_txn *txn, MDB_dbi dbi,
2559 MDB_val *key, MDB_val *data)
2566 DPRINTF("========> delete key %.*s", (int)key->mv_size, (char *)key->mv_data);
2568 assert(key != NULL);
2570 if (txn == NULL || dbi >= txn->mt_numdbs)
2573 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2577 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2581 mpp.mp_parent = NULL;
2583 if ((rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp)) != MDB_SUCCESS)
2586 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
2587 if (leaf == NULL || !exact) {
2591 if (data && (rc = mdb_read_data(txn, leaf, data)) != MDB_SUCCESS)
2594 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
2595 /* add all the child DB's pages to the free list */
2600 mdb_xcursor_init0(txn, dbi, &mx);
2601 mdb_xcursor_init1(txn, dbi, &mx, NODEDATA(leaf));
2602 SLIST_INIT(&mc.mc_stack);
2603 mc.mc_dbi = mx.mx_txn.mt_numdbs-1;
2604 mc.mc_txn = &mx.mx_txn;
2605 rc = mdb_search_page(&mx.mx_txn, mx.mx_txn.mt_numdbs - 1, NULL, &mc, 0, &mp2);
2606 if (rc == MDB_SUCCESS) {
2607 MDB_ppage *top, *parent;
2611 cursor_pop_page(&mc);
2612 top = CURSOR_TOP(&mc);
2613 parent = SLIST_NEXT(top, mp_entry);
2615 for (i=0; i<NUMKEYS(top->mp_page); i++) {
2616 ni = NODEPTR(top->mp_page, i);
2617 mdb_idl_insert(txn->mt_free_pgs, ni->mn_pgno);
2621 if (parent->mp_ki >= NUMKEYS(parent->mp_page)) {
2622 cursor_pop_page(&mc);
2623 top = CURSOR_TOP(&mc);
2624 parent = SLIST_NEXT(top, mp_entry);
2626 ni = NODEPTR(parent->mp_page, parent->mp_ki);
2627 top->mp_page = mdb_get_page(mc.mc_txn, ni->mn_pgno);
2631 mdb_idl_insert(txn->mt_free_pgs, mx.mx_txn.mt_dbs[mc.mc_dbi].md_root);
2635 return mdb_del0(txn, dbi, ki, &mpp, leaf);
2638 /* Split page <*mpp>, and insert <key,(data|newpgno)> in either left or
2639 * right sibling, at index <*newindxp> (as if unsplit). Updates *mpp and
2640 * *newindxp with the actual values after split, ie if *mpp and *newindxp
2641 * refer to a node in the new right sibling page.
2644 mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp, unsigned int *newindxp,
2645 MDB_val *newkey, MDB_val *newdata, pgno_t newpgno)
2648 int rc = MDB_SUCCESS, ins_new = 0;
2651 unsigned int i, j, split_indx;
2653 MDB_val sepkey, rkey, rdata;
2655 MDB_dpage *mdp, *rdp, *pdp;
2658 assert(txn != NULL);
2660 dh = ((MDB_dhead *)*mpp) - 1;
2661 mdp = (MDB_dpage *)dh;
2662 newindx = *newindxp;
2664 DPRINTF("-----> splitting %s page %lu and adding [%.*s] at index %i",
2665 IS_LEAF(&mdp->p) ? "leaf" : "branch", mdp->p.mp_pgno,
2666 (int)newkey->mv_size, (char *)newkey->mv_data, *newindxp);
2668 if (mdp->h.md_parent == NULL) {
2669 if ((pdp = mdb_new_page(txn, dbi, P_BRANCH, 1)) == NULL)
2672 mdp->h.md_parent = &pdp->p;
2673 txn->mt_dbs[dbi].md_root = pdp->p.mp_pgno;
2674 DPRINTF("root split! new root = %lu", pdp->p.mp_pgno);
2675 txn->mt_dbs[dbi].md_depth++;
2677 /* Add left (implicit) pointer. */
2678 if (mdb_add_node(txn, dbi, &pdp->p, 0, NULL, NULL,
2679 mdp->p.mp_pgno, 0) != MDB_SUCCESS)
2682 DPRINTF("parent branch page is %lu", mdp->h.md_parent->mp_pgno);
2685 /* Create a right sibling. */
2686 if ((rdp = mdb_new_page(txn, dbi, mdp->p.mp_flags, 1)) == NULL)
2688 rdp->h.md_parent = mdp->h.md_parent;
2689 rdp->h.md_pi = mdp->h.md_pi + 1;
2690 DPRINTF("new right sibling: page %lu", rdp->p.mp_pgno);
2692 /* Move half of the keys to the right sibling. */
2693 if ((copy = malloc(txn->mt_env->me_psize)) == NULL)
2695 memcpy(copy, &mdp->p, txn->mt_env->me_psize);
2696 memset(&mdp->p.mp_ptrs, 0, txn->mt_env->me_psize - PAGEHDRSZ);
2697 mdp->p.mp_lower = PAGEHDRSZ;
2698 mdp->p.mp_upper = txn->mt_env->me_psize;
2700 split_indx = NUMKEYS(copy) / 2 + 1;
2702 /* First find the separating key between the split pages.
2704 memset(&sepkey, 0, sizeof(sepkey));
2705 if (newindx == split_indx) {
2706 sepkey.mv_size = newkey->mv_size;
2707 sepkey.mv_data = newkey->mv_data;
2709 node = NODEPTR(copy, split_indx);
2710 sepkey.mv_size = node->mn_ksize;
2711 sepkey.mv_data = NODEKEY(node);
2714 DPRINTF("separator is [%.*s]", (int)sepkey.mv_size, (char *)sepkey.mv_data);
2716 /* Copy separator key to the parent.
2718 if (SIZELEFT(rdp->h.md_parent) < mdb_branch_size(txn->mt_env, &sepkey)) {
2719 rc = mdb_split(txn, dbi, &rdp->h.md_parent, &rdp->h.md_pi,
2720 &sepkey, NULL, rdp->p.mp_pgno);
2722 /* Right page might now have changed parent.
2723 * Check if left page also changed parent.
2725 if (rdp->h.md_parent != mdp->h.md_parent &&
2726 mdp->h.md_pi >= NUMKEYS(mdp->h.md_parent)) {
2727 mdp->h.md_parent = rdp->h.md_parent;
2728 mdp->h.md_pi = rdp->h.md_pi - 1;
2731 rc = mdb_add_node(txn, dbi, rdp->h.md_parent, rdp->h.md_pi,
2732 &sepkey, NULL, rdp->p.mp_pgno, 0);
2734 if (rc != MDB_SUCCESS) {
2739 for (i = j = 0; i <= NUMKEYS(copy); j++) {
2740 if (i < split_indx) {
2741 /* Re-insert in left sibling. */
2744 /* Insert in right sibling. */
2745 if (i == split_indx)
2746 /* Reset insert index for right sibling. */
2747 j = (i == newindx && ins_new);
2751 if (i == newindx && !ins_new) {
2752 /* Insert the original entry that caused the split. */
2753 rkey.mv_data = newkey->mv_data;
2754 rkey.mv_size = newkey->mv_size;
2755 if (IS_LEAF(&mdp->p)) {
2756 rdata.mv_data = newdata->mv_data;
2757 rdata.mv_size = newdata->mv_size;
2764 /* Update page and index for the new key. */
2767 } else if (i == NUMKEYS(copy)) {
2770 node = NODEPTR(copy, i);
2771 rkey.mv_data = NODEKEY(node);
2772 rkey.mv_size = node->mn_ksize;
2773 if (IS_LEAF(&mdp->p)) {
2774 rdata.mv_data = NODEDATA(node);
2775 rdata.mv_size = node->mn_dsize;
2777 pgno = node->mn_pgno;
2778 flags = node->mn_flags;
2783 if (!IS_LEAF(&mdp->p) && j == 0) {
2784 /* First branch index doesn't need key data. */
2788 rc = mdb_add_node(txn, dbi, &pdp->p, j, &rkey, &rdata, pgno,flags);
2796 mdb_put(MDB_txn *txn, MDB_dbi dbi,
2797 MDB_val *key, MDB_val *data, unsigned int flags)
2799 int rc = MDB_SUCCESS, exact;
2803 MDB_val xdata, *rdata;
2806 assert(key != NULL);
2807 assert(data != NULL);
2812 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2816 if (txn->mt_env->me_txn != txn) {
2820 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2824 DPRINTF("==> put key %.*s, size %zu, data size %zu",
2825 (int)key->mv_size, (char *)key->mv_data, key->mv_size, data->mv_size);
2827 mpp.mp_parent = NULL;
2829 rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp);
2830 if (rc == MDB_SUCCESS) {
2831 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
2832 if (leaf && exact) {
2833 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
2836 if (F_ISSET(flags, MDB_NOOVERWRITE)) {
2837 DPRINTF("duplicate key %.*s",
2838 (int)key->mv_size, (char *)key->mv_data);
2841 /* same size, just replace it */
2842 if (NODEDSZ(leaf) == data->mv_size) {
2843 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
2846 mdb_del_node(mpp.mp_page, ki);
2848 if (leaf == NULL) { /* append if not found */
2849 ki = NUMKEYS(mpp.mp_page);
2850 DPRINTF("appending key at index %i", ki);
2852 } else if (rc == ENOENT) {
2854 /* new file, just write a root leaf page */
2855 DPRINTF("allocating new root leaf page");
2856 if ((dp = mdb_new_page(txn, dbi, P_LEAF, 1)) == NULL) {
2859 mpp.mp_page = &dp->p;
2860 txn->mt_dbs[dbi].md_root = mpp.mp_page->mp_pgno;
2861 txn->mt_dbs[dbi].md_depth++;
2867 assert(IS_LEAF(mpp.mp_page));
2868 DPRINTF("there are %u keys, should insert new key at index %i",
2869 NUMKEYS(mpp.mp_page), ki);
2871 /* For sorted dups, the data item at this level is a DB record
2872 * for a child DB; the actual data elements are stored as keys
2875 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
2877 xdata.mv_size = sizeof(MDB_db);
2878 xdata.mv_data = &dummy;
2879 memset(&dummy, 0, sizeof(dummy));
2880 dummy.md_root = P_INVALID;
2885 if (SIZELEFT(mpp.mp_page) < mdb_leaf_size(txn->mt_env, key, data)) {
2886 rc = mdb_split(txn, dbi, &mpp.mp_page, &ki, key, data, P_INVALID);
2888 /* There is room already in this leaf page. */
2889 rc = mdb_add_node(txn, dbi, mpp.mp_page, ki, key, data, 0, 0);
2892 if (rc != MDB_SUCCESS)
2893 txn->mt_flags |= MDB_TXN_ERROR;
2895 txn->mt_dbs[dbi].md_entries++;
2896 /* Now store the actual data in the child DB. Note that we're
2897 * storing the user data in the keys field, so there are strict
2898 * size limits on dupdata. The actual data fields of the child
2899 * DB are all zero size.
2901 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
2904 leaf = NODEPTR(mpp.mp_page, ki);
2906 mdb_xcursor_init0(txn, dbi, &mx);
2907 mdb_xcursor_init1(txn, dbi, &mx, NODEDATA(leaf));
2910 rc = mdb_put(&mx.mx_txn, mx.mx_txn.mt_numdbs-1, data, &xdata, flags);
2911 mdb_xcursor_fini(txn, dbi, &mx);
2920 mdbenv_get_flags(MDB_env *env, unsigned int *arg)
2925 *arg = env->me_flags;
2930 mdbenv_get_path(MDB_env *env, const char **arg)
2935 *arg = env->me_path;
2940 mdbenv_stat(MDB_env *env, MDB_stat *arg)
2942 if (env == NULL || arg == NULL)
2945 arg->ms_psize = env->me_psize;
2946 arg->ms_depth = env->me_meta->mm_dbs[MAIN_DBI].md_depth;
2947 arg->ms_branch_pages = env->me_meta->mm_dbs[MAIN_DBI].md_branch_pages;
2948 arg->ms_leaf_pages = env->me_meta->mm_dbs[MAIN_DBI].md_leaf_pages;
2949 arg->ms_overflow_pages = env->me_meta->mm_dbs[MAIN_DBI].md_overflow_pages;
2950 arg->ms_entries = env->me_meta->mm_dbs[MAIN_DBI].md_entries;
2955 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
2968 /* Is the DB already open? */
2970 for (i=2; i<txn->mt_numdbs; i++) {
2971 if (len == txn->mt_dbxs[i].md_name.mv_size &&
2972 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
2978 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
2981 /* Find the DB info */
2983 key.mv_data = (void *)name;
2984 rc = mdb_get(txn, MAIN_DBI, &key, &data);
2986 /* Create if requested */
2987 if (rc == ENOENT && (flags & MDB_CREATE)) {
2989 data.mv_size = sizeof(MDB_db);
2990 data.mv_data = &dummy;
2991 memset(&dummy, 0, sizeof(dummy));
2992 dummy.md_root = P_INVALID;
2993 dummy.md_flags = flags & 0xffff;
2994 rc = mdb_put(txn, 0, &key, &data, 0);
2997 /* OK, got info, add to table */
2998 if (rc == MDB_SUCCESS) {
2999 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
3000 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
3001 txn->mt_dbxs[txn->mt_numdbs].md_cmp = NULL;
3002 txn->mt_dbxs[txn->mt_numdbs].md_dcmp = NULL;
3003 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
3004 txn->mt_dbxs[txn->mt_numdbs].md_parent = MAIN_DBI;
3005 txn->mt_dbxs[txn->mt_numdbs].md_dirty = 0;
3006 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
3007 *dbi = txn->mt_numdbs;
3014 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
3016 if (txn == NULL || arg == NULL)
3019 arg->ms_psize = txn->mt_env->me_psize;
3020 arg->ms_depth = txn->mt_dbs[dbi].md_depth;
3021 arg->ms_branch_pages = txn->mt_dbs[dbi].md_branch_pages;
3022 arg->ms_leaf_pages = txn->mt_dbs[dbi].md_leaf_pages;
3023 arg->ms_overflow_pages = txn->mt_dbs[dbi].md_overflow_pages;
3024 arg->ms_entries = txn->mt_dbs[dbi].md_entries;
3029 void mdb_close(MDB_txn *txn, MDB_dbi dbi)
3032 if (dbi <= MAIN_DBI || dbi >= txn->mt_numdbs)
3034 ptr = txn->mt_dbxs[dbi].md_name.mv_data;
3035 txn->mt_dbxs[dbi].md_name.mv_data = NULL;
3036 txn->mt_dbxs[dbi].md_name.mv_size = 0;