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/param.h>
35 #ifdef HAVE_SYS_FILE_H
53 #define ULONG unsigned long
58 /* Note: If O_DSYNC is undefined but exists in /usr/include,
59 * preferably set some compiler flag to get the definition.
60 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
63 # define MDB_DSYNC O_DSYNC
70 #if !(__STDC_VERSION__ >= 199901L || defined(__GNUC__))
71 # define DPRINTF (void) /* Vararg macros may be unsupported */
73 # define DPRINTF(fmt, ...) /* Requires 2 or more args */ \
74 fprintf(stderr, "%s:%d:(%p) " fmt "\n", __func__, __LINE__, pthread_self(), __VA_ARGS__)
76 # define DPRINTF(fmt, ...) ((void) 0)
78 #define DPUTS(arg) DPRINTF("%s", arg)
82 #define MDB_MAGIC 0xBEEFC0DE
84 #define MAXKEYSIZE 511
86 #define KBUF (MAXKEYSIZE*2+1)
87 #define DKBUF char kbuf[KBUF]
88 #define DKEY(x) mdb_dkey(x, kbuf)
94 #define P_INVALID (~0UL)
96 #define F_ISSET(w, f) (((w) & (f)) == (f))
98 typedef uint16_t indx_t;
100 #define DEFAULT_READERS 126
101 #define DEFAULT_MAPSIZE 1048576
103 /* Lock descriptor stuff */
105 #define CACHELINE 64 /* most CPUs. Itanium uses 128 */
108 typedef struct MDB_rxbody {
114 typedef struct MDB_reader {
117 #define mr_txnid mru.mrx.mrb_txnid
118 #define mr_pid mru.mrx.mrb_pid
119 #define mr_tid mru.mrx.mrb_tid
120 /* cache line alignment */
121 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
125 typedef struct MDB_txbody {
127 uint32_t mtb_version;
128 pthread_mutex_t mtb_mutex;
130 uint32_t mtb_numreaders;
131 uint32_t mtb_me_toggle;
134 typedef struct MDB_txninfo {
137 #define mti_magic mt1.mtb.mtb_magic
138 #define mti_version mt1.mtb.mtb_version
139 #define mti_mutex mt1.mtb.mtb_mutex
140 #define mti_txnid mt1.mtb.mtb_txnid
141 #define mti_numreaders mt1.mtb.mtb_numreaders
142 #define mti_me_toggle mt1.mtb.mtb_me_toggle
143 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
146 pthread_mutex_t mt2_wmutex;
147 #define mti_wmutex mt2.mt2_wmutex
148 char pad[(sizeof(pthread_mutex_t)+CACHELINE-1) & ~(CACHELINE-1)];
150 MDB_reader mti_readers[1];
153 /* Common header for all page types. Overflow pages
154 * occupy a number of contiguous pages with no
155 * headers on any page after the first.
157 typedef struct MDB_page { /* represents a page of storage */
158 #define mp_pgno mp_p.p_pgno
160 pgno_t p_pgno; /* page number */
161 void * p_align; /* for IL32P64 */
163 #define P_BRANCH 0x01 /* branch page */
164 #define P_LEAF 0x02 /* leaf page */
165 #define P_OVERFLOW 0x04 /* overflow page */
166 #define P_META 0x08 /* meta page */
167 #define P_DIRTY 0x10 /* dirty page */
168 #define P_LEAF2 0x20 /* DB with small, fixed size keys and no data */
170 #define mp_lower mp_pb.pb.pb_lower
171 #define mp_upper mp_pb.pb.pb_upper
172 #define mp_pages mp_pb.pb_pages
175 indx_t pb_lower; /* lower bound of free space */
176 indx_t pb_upper; /* upper bound of free space */
178 uint32_t pb_pages; /* number of overflow pages */
180 indx_t mp_ptrs[1]; /* dynamic size */
183 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
185 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
186 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
187 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
188 ((env)->me_psize - PAGEHDRSZ))
189 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
190 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
191 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
192 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
194 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
196 typedef struct MDB_db {
197 uint32_t md_pad; /* also ksize for LEAF2 pages */
200 ULONG md_branch_pages;
202 ULONG md_overflow_pages;
210 typedef struct MDB_meta { /* meta (footer) page content */
213 void *mm_address; /* address for fixed mapping */
214 size_t mm_mapsize; /* size of mmap region */
215 MDB_db mm_dbs[2]; /* first is free space, 2nd is main db */
216 #define mm_psize mm_dbs[0].md_pad
217 #define mm_flags mm_dbs[0].md_flags
218 pgno_t mm_last_pg; /* last used page in file */
219 ULONG mm_txnid; /* txnid that committed this page */
222 typedef struct MDB_dhead { /* a dirty page */
224 unsigned md_pi; /* parent index */
228 typedef struct MDB_dpage {
233 typedef struct MDB_oldpages {
234 struct MDB_oldpages *mo_next;
236 pgno_t mo_pages[1]; /* dynamic */
239 typedef struct MDB_pageparent {
245 static MDB_dpage *mdb_alloc_page(MDB_txn *txn, MDB_page *parent, unsigned int parent_idx, int num);
246 static int mdb_touch(MDB_txn *txn, MDB_pageparent *mp);
248 typedef struct MDB_ppage { /* ordered list of pages */
250 unsigned int mp_ki; /* cursor index on page */
253 #define CURSOR_TOP(c) (&(c)->mc_stack[(c)->mc_snum-1])
254 #define CURSOR_PARENT(c) (&(c)->mc_stack[(c)->mc_snum-2])
255 #define CURSOR_STACK 32
261 MDB_ppage mc_stack[CURSOR_STACK]; /* stack of parent pages */
262 unsigned int mc_snum; /* number of pushed pages */
264 short mc_initialized; /* 1 if initialized */
265 short mc_eof; /* 1 if end is reached */
266 struct MDB_xcursor *mc_xcursor;
269 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
271 typedef struct MDB_node {
272 #define mn_pgno mn_p.np_pgno
273 #define mn_dsize mn_p.np_dsize
275 pgno_t np_pgno; /* child page number */
276 uint32_t np_dsize; /* leaf data size */
278 unsigned int mn_flags:4;
279 unsigned int mn_ksize:12; /* key size */
280 #define F_BIGDATA 0x01 /* data put on overflow page */
281 #define F_SUBDATA 0x02 /* data is a sub-database */
282 #define F_DUPDATA 0x04 /* data has duplicates */
286 typedef struct MDB_dbx {
288 MDB_cmp_func *md_cmp; /* user compare function */
289 MDB_cmp_func *md_dcmp; /* user dupsort function */
290 MDB_rel_func *md_rel; /* user relocate function */
292 unsigned int md_dirty;
296 pgno_t mt_next_pgno; /* next unallocated page */
300 pgno_t *mt_free_pgs; /* this is an IDL */
302 MIDL2 *dirty_list; /* modified pages */
305 MDB_dbx *mt_dbxs; /* array */
307 unsigned int mt_numdbs;
309 #define MDB_TXN_RDONLY 0x01 /* read-only transaction */
310 #define MDB_TXN_ERROR 0x02 /* an error has occurred */
311 #define MDB_TXN_METOGGLE 0x04 /* used meta page 1 */
312 unsigned int mt_flags;
315 /* Context for sorted-dup records */
316 typedef struct MDB_xcursor {
317 MDB_cursor mx_cursor;
326 int me_mfd; /* just for writing the meta pages */
327 #define MDB_FATAL_ERROR 0x80000000U
329 uint32_t me_extrapad; /* unused for now */
330 unsigned int me_maxreaders;
331 unsigned int me_numdbs;
332 unsigned int me_maxdbs;
335 MDB_txninfo *me_txns;
336 MDB_meta *me_metas[2];
338 MDB_txn *me_txn; /* current write transaction */
340 off_t me_size; /* current file size */
341 pgno_t me_maxpg; /* me_mapsize / me_psize */
342 unsigned int me_psize;
343 unsigned int me_db_toggle;
344 MDB_dbx *me_dbxs; /* array */
346 MDB_oldpages *me_pghead;
347 pthread_key_t me_txkey; /* thread-key for readers */
348 MDB_dpage *me_dpages;
349 pgno_t me_free_pgs[MDB_IDL_UM_SIZE];
350 MIDL2 me_dirty_list[MDB_IDL_DB_SIZE];
353 #define NODESIZE offsetof(MDB_node, mn_data)
355 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
356 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
357 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
358 #define NODEKEY(node) (void *)((node)->mn_data)
359 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
360 #define NODEPGNO(node) ((node)->mn_pgno)
361 #define NODEDSZ(node) ((node)->mn_dsize)
362 #define NODEKSZ(node) ((node)->mn_ksize)
363 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
365 #define MDB_SET_KEY(node, key) if (key!=NULL) {(key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node);}
367 #define MDB_COMMIT_PAGES 64 /* max number of pages to write in one commit */
369 static int mdb_search_page_root(MDB_txn *txn,
370 MDB_dbi dbi, MDB_val *key,
371 MDB_cursor *cursor, int modify,
372 MDB_pageparent *mpp);
373 static int mdb_search_page(MDB_txn *txn,
374 MDB_dbi dbi, MDB_val *key,
375 MDB_cursor *cursor, int modify,
376 MDB_pageparent *mpp);
378 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
379 static int mdb_env_read_meta(MDB_env *env, int *which);
380 static int mdb_env_write_meta(MDB_txn *txn);
381 static int mdb_get_page(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
383 static MDB_node *mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp,
384 MDB_val *key, int *exactp, unsigned int *kip);
385 static int mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp,
386 indx_t indx, MDB_val *key, MDB_val *data,
387 pgno_t pgno, uint8_t flags);
388 static void mdb_del_node(MDB_page *mp, indx_t indx, int ksize);
389 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, unsigned int ki,
390 MDB_pageparent *mpp, MDB_node *leaf);
391 static int mdb_put0(MDB_txn *txn, MDB_dbi dbi,
392 MDB_val *key, MDB_val *data, unsigned int flags);
393 static int mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
395 static int mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mp);
396 static int mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
397 static int mdb_move_node(MDB_txn *txn, MDB_dbi dbi,
398 MDB_pageparent *src, indx_t srcindx,
399 MDB_pageparent *dst, indx_t dstindx);
400 static int mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src,
401 MDB_pageparent *dst);
402 static int mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp,
403 unsigned int *newindxp, MDB_val *newkey,
404 MDB_val *newdata, pgno_t newpgno);
405 static MDB_dpage *mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num);
407 static void cursor_pop_page(MDB_cursor *cursor);
408 static MDB_ppage *cursor_push_page(MDB_cursor *cursor,
411 static int mdb_sibling(MDB_cursor *cursor, int move_right);
412 static int mdb_cursor_next(MDB_cursor *cursor,
413 MDB_val *key, MDB_val *data, MDB_cursor_op op);
414 static int mdb_cursor_prev(MDB_cursor *cursor,
415 MDB_val *key, MDB_val *data, MDB_cursor_op op);
416 static int mdb_cursor_set(MDB_cursor *cursor,
417 MDB_val *key, MDB_val *data, MDB_cursor_op op, int *exactp);
418 static int mdb_cursor_first(MDB_cursor *cursor,
419 MDB_val *key, MDB_val *data);
420 static int mdb_cursor_last(MDB_cursor *cursor,
421 MDB_val *key, MDB_val *data);
423 static void mdb_xcursor_init0(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
424 static void mdb_xcursor_init1(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx,
425 MDB_page *mp, MDB_node *node);
426 static void mdb_xcursor_fini(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
428 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key,
430 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
432 static int memncmp(const void *s1, size_t n1,
433 const void *s2, size_t n2);
434 static int memnrcmp(const void *s1, size_t n1,
435 const void *s2, size_t n2);
438 memncmp(const void *s1, size_t n1, const void *s2, size_t n2)
440 int diff, len_diff = -1;
443 len_diff = (n1 > n2);
446 diff = memcmp(s1, s2, n1);
447 return diff ? diff : len_diff;
451 memnrcmp(const void *s1, size_t n1, const void *s2, size_t n2)
453 const unsigned char *p1, *p2, *p1_lim;
460 p1 = (const unsigned char *)s1 + n1 - 1;
461 p2 = (const unsigned char *)s2 + n2 - 1;
463 for (p1_lim = (n1 <= n2 ? s1 : s2); *p1 == *p2; p1--, p2--) {
465 return (p1 != s1) ? (p1 != p2) : (p2 != s2) ? -1 : 0;
471 mdb_version(int *maj, int *min, int *pat)
473 *maj = MDB_VERSION_MAJOR;
474 *min = MDB_VERSION_MINOR;
475 *pat = MDB_VERSION_PATCH;
476 return MDB_VERSION_STRING;
479 static char *const errstr[] = {
480 "MDB_KEYEXIST: Key/data pair already exists",
481 "MDB_NOTFOUND: No matching key/data pair found",
482 "MDB_PAGE_NOTFOUND: Requested page not found",
483 "MDB_CORRUPTED: Located page was wrong type",
484 "MDB_PANIC: Update of meta page failed",
485 "MDB_VERSION_MISMATCH: Database environment version mismatch"
489 mdb_strerror(int err)
492 return ("Successful return: 0");
494 if (err >= MDB_KEYEXIST && err <= MDB_VERSION_MISMATCH)
495 return errstr[err - MDB_KEYEXIST];
497 return strerror(err);
501 mdb_dkey(MDB_val *key, char *buf)
504 unsigned char *c = key->mv_data;
506 if (key->mv_size > MAXKEYSIZE)
508 for (i=0; i<key->mv_size; i++)
509 ptr += sprintf(ptr, "%02x", *c++);
514 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
516 if (txn->mt_dbxs[dbi].md_cmp)
517 return txn->mt_dbxs[dbi].md_cmp(a, b);
519 if (txn->mt_dbs[dbi].md_flags & (MDB_REVERSEKEY
520 #if __BYTE_ORDER == __LITTLE_ENDIAN
524 return memnrcmp(a->mv_data, a->mv_size, b->mv_data, b->mv_size);
526 return memncmp((char *)a->mv_data, a->mv_size, b->mv_data, b->mv_size);
530 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
532 if (txn->mt_dbxs[dbi].md_dcmp)
533 return txn->mt_dbxs[dbi].md_dcmp(a, b);
535 if (txn->mt_dbs[dbi].md_flags & (0
536 #if __BYTE_ORDER == __LITTLE_ENDIAN
540 return memnrcmp(a->mv_data, a->mv_size, b->mv_data, b->mv_size);
542 return memncmp((char *)a->mv_data, a->mv_size, b->mv_data, b->mv_size);
545 /* Allocate new page(s) for writing */
547 mdb_alloc_page(MDB_txn *txn, MDB_page *parent, unsigned int parent_idx, int num)
550 pgno_t pgno = P_INVALID;
554 if (txn->mt_txnid > 2) {
556 oldest = txn->mt_txnid - 1;
557 if (!txn->mt_env->me_pghead && txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
558 /* See if there's anything in the free DB */
563 mpp.mp_parent = NULL;
565 mdb_search_page(txn, FREE_DBI, NULL, NULL, 0, &mpp);
566 leaf = NODEPTR(mpp.mp_page, 0);
567 kptr = (ULONG *)NODEKEY(leaf);
569 /* It's potentially usable, unless there are still
570 * older readers outstanding. Grab it.
572 if (oldest > *kptr) {
577 mdb_read_data(txn, leaf, &data);
578 idl = (ULONG *)data.mv_data;
579 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
580 mop->mo_next = txn->mt_env->me_pghead;
581 mop->mo_txnid = *kptr;
582 txn->mt_env->me_pghead = mop;
583 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
588 DPRINTF("IDL read txn %lu root %lu num %lu",
589 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
590 for (i=0; i<idl[0]; i++) {
591 DPRINTF("IDL %lu", idl[i+1]);
595 /* drop this IDL from the DB */
596 mpp.mp_parent = NULL;
598 mdb_search_page(txn, FREE_DBI, NULL, NULL, 1, &mpp);
599 leaf = NODEPTR(mpp.mp_page, 0);
600 mdb_del0(txn, FREE_DBI, 0, &mpp, leaf);
603 if (txn->mt_env->me_pghead) {
605 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
606 ULONG mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
609 oldest = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
611 if (oldest > txn->mt_env->me_pghead->mo_txnid) {
612 MDB_oldpages *mop = txn->mt_env->me_pghead;
613 txn->mt_oldest = oldest;
615 /* FIXME: For now, always use fresh pages. We
616 * really ought to search the free list for a
621 /* peel pages off tail, so we only have to truncate the list */
622 pgno = MDB_IDL_LAST(mop->mo_pages);
623 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
625 if (mop->mo_pages[2] > mop->mo_pages[1])
626 mop->mo_pages[0] = 0;
630 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
631 txn->mt_env->me_pghead = mop->mo_next;
639 if (pgno == P_INVALID) {
640 /* DB size is maxed out */
641 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg)
644 if (txn->mt_env->me_dpages && num == 1) {
645 dp = txn->mt_env->me_dpages;
646 txn->mt_env->me_dpages = (MDB_dpage *)dp->h.md_parent;
648 if ((dp = malloc(txn->mt_env->me_psize * num + sizeof(MDB_dhead))) == NULL)
652 dp->h.md_parent = parent;
653 dp->h.md_pi = parent_idx;
654 if (pgno == P_INVALID) {
655 dp->p.mp_pgno = txn->mt_next_pgno;
656 txn->mt_next_pgno += num;
658 dp->p.mp_pgno = pgno;
660 mid.mid = dp->p.mp_pgno;
662 mdb_midl2_insert(txn->mt_u.dirty_list, &mid);
667 /* Touch a page: make it dirty and re-insert into tree with updated pgno.
670 mdb_touch(MDB_txn *txn, MDB_pageparent *pp)
672 MDB_page *mp = pp->mp_page;
677 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
679 if ((dp = mdb_alloc_page(txn, pp->mp_parent, pp->mp_pi, 1)) == NULL)
681 DPRINTF("touched page %lu -> %lu", mp->mp_pgno, dp->p.mp_pgno);
682 assert(mp->mp_pgno != dp->p.mp_pgno);
683 mdb_midl_insert(txn->mt_free_pgs, mp->mp_pgno);
684 pgno = dp->p.mp_pgno;
685 memcpy(&dp->p, mp, txn->mt_env->me_psize);
688 mp->mp_flags |= P_DIRTY;
690 /* Update the page number to new touched page. */
691 if (pp->mp_parent != NULL)
692 NODEPGNO(NODEPTR(pp->mp_parent, pp->mp_pi)) = mp->mp_pgno;
699 mdb_env_sync(MDB_env *env, int force)
702 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
703 if (fdatasync(env->me_fd))
710 mdb_txn_reset0(MDB_txn *txn);
713 mdb_txn_renew0(MDB_txn *txn)
715 MDB_env *env = txn->mt_env;
719 if (env->me_flags & MDB_FATAL_ERROR) {
720 DPUTS("mdb_txn_begin: environment had fatal error, must shutdown!");
724 if (txn->mt_flags & MDB_TXN_RDONLY) {
725 MDB_reader *r = pthread_getspecific(env->me_txkey);
728 pthread_mutex_lock(&env->me_txns->mti_mutex);
729 for (i=0; i<env->me_txns->mti_numreaders; i++)
730 if (env->me_txns->mti_readers[i].mr_pid == 0)
732 if (i == env->me_maxreaders) {
733 pthread_mutex_unlock(&env->me_txns->mti_mutex);
736 env->me_txns->mti_readers[i].mr_pid = getpid();
737 env->me_txns->mti_readers[i].mr_tid = pthread_self();
738 r = &env->me_txns->mti_readers[i];
739 pthread_setspecific(env->me_txkey, r);
740 if (i >= env->me_txns->mti_numreaders)
741 env->me_txns->mti_numreaders = i+1;
742 pthread_mutex_unlock(&env->me_txns->mti_mutex);
744 txn->mt_txnid = env->me_txns->mti_txnid;
745 r->mr_txnid = txn->mt_txnid;
746 txn->mt_u.reader = r;
748 pthread_mutex_lock(&env->me_txns->mti_wmutex);
750 txn->mt_txnid = env->me_txns->mti_txnid+1;
751 txn->mt_u.dirty_list = env->me_dirty_list;
752 txn->mt_u.dirty_list[0].mid = 0;
753 txn->mt_free_pgs = env->me_free_pgs;
754 txn->mt_free_pgs[0] = 0;
758 toggle = env->me_txns->mti_me_toggle;
759 if ((rc = mdb_env_read_meta(env, &toggle)) != MDB_SUCCESS) {
764 /* Copy the DB arrays */
765 txn->mt_numdbs = env->me_numdbs;
766 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
767 memcpy(txn->mt_dbs, env->me_meta->mm_dbs, 2 * sizeof(MDB_db));
768 if (txn->mt_numdbs > 2)
769 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
770 (txn->mt_numdbs - 2) * sizeof(MDB_db));
772 if (!(txn->mt_flags & MDB_TXN_RDONLY)) {
774 txn->mt_flags |= MDB_TXN_METOGGLE;
775 txn->mt_next_pgno = env->me_meta->mm_last_pg+1;
778 DPRINTF("begin txn %p %lu%c on mdbenv %p, root page %lu", txn,
779 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
780 (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
786 mdb_txn_renew(MDB_txn *txn)
793 rc = mdb_txn_renew0(txn);
794 if (rc == MDB_SUCCESS) {
795 DPRINTF("reset txn %p %lu%c on mdbenv %p, root page %lu", txn,
796 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
797 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
803 mdb_txn_begin(MDB_env *env, int rdonly, MDB_txn **ret)
808 if (env->me_flags & MDB_FATAL_ERROR) {
809 DPUTS("mdb_txn_begin: environment had fatal error, must shutdown!");
812 if ((txn = calloc(1, sizeof(MDB_txn) + env->me_maxdbs * sizeof(MDB_db))) == NULL) {
813 DPRINTF("calloc: %s", strerror(errno));
816 txn->mt_dbs = (MDB_db *)(txn+1);
818 txn->mt_flags |= MDB_TXN_RDONLY;
822 rc = mdb_txn_renew0(txn);
827 DPRINTF("begin txn %p %lu%c on mdbenv %p, root page %lu", txn,
828 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
829 (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
836 mdb_txn_reset0(MDB_txn *txn)
838 MDB_env *env = txn->mt_env;
840 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
841 txn->mt_u.reader->mr_txnid = 0;
847 /* return all dirty pages to dpage list */
848 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
849 dp = txn->mt_u.dirty_list[i].mptr;
850 if (dp->h.md_num == 1) {
851 dp->h.md_parent = (MDB_page *)txn->mt_env->me_dpages;
852 txn->mt_env->me_dpages = dp;
854 /* large pages just get freed directly */
859 while ((mop = txn->mt_env->me_pghead)) {
860 txn->mt_env->me_pghead = mop->mo_next;
865 for (i=2; i<env->me_numdbs; i++)
866 env->me_dbxs[i].md_dirty = 0;
867 pthread_mutex_unlock(&env->me_txns->mti_wmutex);
872 mdb_txn_reset(MDB_txn *txn)
877 DPRINTF("reset txn %p %lu%c on mdbenv %p, root page %lu", txn,
878 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
879 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
885 mdb_txn_abort(MDB_txn *txn)
890 DPRINTF("abort txn %p %lu%c on mdbenv %p, root page %lu", txn,
891 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
892 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
899 mdb_txn_commit(MDB_txn *txn)
908 struct iovec iov[MDB_COMMIT_PAGES];
911 assert(txn->mt_env != NULL);
915 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
920 if (txn != env->me_txn) {
921 DPUTS("attempt to commit unknown transaction");
926 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
927 DPUTS("error flag is set, can't commit");
932 if (!txn->mt_u.dirty_list[0].mid)
935 DPRINTF("committing txn %p %lu on mdbenv %p, root page %lu", txn,
936 txn->mt_txnid, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
938 /* should only be one record now */
939 if (env->me_pghead) {
943 mop = env->me_pghead;
944 key.mv_size = sizeof(pgno_t);
945 key.mv_data = (char *)&mop->mo_txnid;
946 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
947 data.mv_data = mop->mo_pages;
948 mdb_put0(txn, FREE_DBI, &key, &data, 0);
949 free(env->me_pghead);
950 env->me_pghead = NULL;
952 /* save to free list */
953 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
957 /* make sure last page of freeDB is touched and on freelist */
958 key.mv_size = MAXKEYSIZE+1;
960 mpp.mp_parent = NULL;
962 mdb_search_page(txn, FREE_DBI, &key, NULL, 1, &mpp);
967 ULONG *idl = txn->mt_free_pgs;
968 DPRINTF("IDL write txn %lu root %lu num %lu",
969 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
970 for (i=0; i<idl[0]; i++) {
971 DPRINTF("IDL %lu", idl[i+1]);
975 /* write to last page of freeDB */
976 key.mv_size = sizeof(pgno_t);
977 key.mv_data = (char *)&txn->mt_txnid;
978 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
979 data.mv_data = txn->mt_free_pgs;
980 mdb_put0(txn, FREE_DBI, &key, &data, 0);
983 /* Update DB root pointers. Their pages have already been
984 * touched so this is all in-place and cannot fail.
988 data.mv_size = sizeof(MDB_db);
990 for (i = 2; i < txn->mt_numdbs; i++) {
991 if (txn->mt_dbxs[i].md_dirty) {
992 data.mv_data = &txn->mt_dbs[i];
993 mdb_put0(txn, MAIN_DBI, &txn->mt_dbxs[i].md_name, &data, 0);
998 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
1006 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1007 dp = txn->mt_u.dirty_list[i].mptr;
1008 if (dp->p.mp_pgno != next) {
1010 DPRINTF("committing %u dirty pages", n);
1011 rc = writev(env->me_fd, iov, n);
1015 DPUTS("short write, filesystem full?");
1017 DPRINTF("writev: %s", strerror(errno));
1024 lseek(env->me_fd, dp->p.mp_pgno * env->me_psize, SEEK_SET);
1025 next = dp->p.mp_pgno;
1027 DPRINTF("committing page %lu", dp->p.mp_pgno);
1028 iov[n].iov_len = env->me_psize * dp->h.md_num;
1029 iov[n].iov_base = &dp->p;
1030 size += iov[n].iov_len;
1031 next = dp->p.mp_pgno + dp->h.md_num;
1032 /* clear dirty flag */
1033 dp->p.mp_flags &= ~P_DIRTY;
1034 if (++n >= MDB_COMMIT_PAGES) {
1044 DPRINTF("committing %u dirty pages", n);
1045 rc = writev(env->me_fd, iov, n);
1049 DPUTS("short write, filesystem full?");
1051 DPRINTF("writev: %s", strerror(errno));
1058 /* Drop the dirty pages.
1060 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1061 dp = txn->mt_u.dirty_list[i].mptr;
1062 if (dp->h.md_num == 1) {
1063 dp->h.md_parent = (MDB_page *)txn->mt_env->me_dpages;
1064 txn->mt_env->me_dpages = dp;
1068 txn->mt_u.dirty_list[i].mid = 0;
1070 txn->mt_u.dirty_list[0].mid = 0;
1072 if ((n = mdb_env_sync(env, 0)) != 0 ||
1073 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
1078 env->me_txns->mti_txnid = txn->mt_txnid;
1082 /* update the DB tables */
1084 int toggle = !env->me_db_toggle;
1086 for (i = 2; i < txn->mt_numdbs; i++)
1087 env->me_dbs[toggle][i] = txn->mt_dbs[i];
1089 for (i = 2; i < txn->mt_numdbs; i++) {
1090 if (txn->mt_dbxs[i].md_dirty)
1091 txn->mt_dbxs[i].md_dirty = 0;
1093 env->me_db_toggle = toggle;
1094 env->me_numdbs = txn->mt_numdbs;
1097 pthread_mutex_unlock(&env->me_txns->mti_wmutex);
1104 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
1106 char page[PAGESIZE];
1111 assert(env != NULL);
1113 /* We don't know the page size yet, so use a minimum value.
1116 if ((rc = pread(env->me_fd, page, PAGESIZE, 0)) == 0) {
1118 } else if (rc != PAGESIZE) {
1121 DPRINTF("read: %s", strerror(errno));
1125 p = (MDB_page *)page;
1127 if (!F_ISSET(p->mp_flags, P_META)) {
1128 DPRINTF("page %lu not a meta page", p->mp_pgno);
1133 if (m->mm_magic != MDB_MAGIC) {
1134 DPUTS("meta has invalid magic");
1138 if (m->mm_version != MDB_VERSION) {
1139 DPRINTF("database is version %u, expected version %u",
1140 m->mm_version, MDB_VERSION);
1141 return MDB_VERSION_MISMATCH;
1144 memcpy(meta, m, sizeof(*m));
1149 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
1156 DPUTS("writing new meta page");
1157 psize = sysconf(_SC_PAGE_SIZE);
1159 meta->mm_magic = MDB_MAGIC;
1160 meta->mm_version = MDB_VERSION;
1161 meta->mm_psize = psize;
1162 meta->mm_last_pg = 1;
1163 meta->mm_flags = env->me_flags & 0xffff;
1164 meta->mm_flags |= MDB_INTEGERKEY;
1165 meta->mm_dbs[0].md_root = P_INVALID;
1166 meta->mm_dbs[1].md_root = P_INVALID;
1168 p = calloc(2, psize);
1170 p->mp_flags = P_META;
1173 memcpy(m, meta, sizeof(*meta));
1175 q = (MDB_page *)((char *)p + psize);
1178 q->mp_flags = P_META;
1181 memcpy(m, meta, sizeof(*meta));
1183 rc = write(env->me_fd, p, psize * 2);
1185 return (rc == (int)psize * 2) ? MDB_SUCCESS : errno;
1189 mdb_env_write_meta(MDB_txn *txn)
1192 MDB_meta meta, metab;
1194 int rc, len, toggle;
1197 assert(txn != NULL);
1198 assert(txn->mt_env != NULL);
1200 toggle = !F_ISSET(txn->mt_flags, MDB_TXN_METOGGLE);
1201 DPRINTF("writing meta page %d for root page %lu",
1202 toggle, txn->mt_dbs[MAIN_DBI].md_root);
1206 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
1207 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
1209 ptr = (char *)&meta;
1210 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
1211 len = sizeof(MDB_meta) - off;
1214 meta.mm_dbs[0] = txn->mt_dbs[0];
1215 meta.mm_dbs[1] = txn->mt_dbs[1];
1216 meta.mm_last_pg = txn->mt_next_pgno - 1;
1217 meta.mm_txnid = txn->mt_txnid;
1220 off += env->me_psize;
1223 /* Write to the SYNC fd */
1224 rc = pwrite(env->me_mfd, ptr, len, off);
1228 DPUTS("write failed, disk error?");
1229 /* On a failure, the pagecache still contains the new data.
1230 * Write some old data back, to prevent it from being used.
1231 * Use the non-SYNC fd; we know it will fail anyway.
1233 meta.mm_last_pg = metab.mm_last_pg;
1234 meta.mm_txnid = metab.mm_txnid;
1235 r2 = pwrite(env->me_fd, ptr, len, off);
1236 env->me_flags |= MDB_FATAL_ERROR;
1239 txn->mt_env->me_txns->mti_me_toggle = toggle;
1245 mdb_env_read_meta(MDB_env *env, int *which)
1249 assert(env != NULL);
1253 else if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1256 if (env->me_meta != env->me_metas[toggle])
1257 env->me_meta = env->me_metas[toggle];
1259 DPRINTF("Using meta page %d", toggle);
1265 mdb_env_create(MDB_env **env)
1269 e = calloc(1, sizeof(MDB_env));
1270 if (!e) return ENOMEM;
1272 e->me_maxreaders = DEFAULT_READERS;
1282 mdb_env_set_mapsize(MDB_env *env, size_t size)
1286 env->me_mapsize = size;
1291 mdb_env_set_maxdbs(MDB_env *env, int dbs)
1293 env->me_maxdbs = dbs;
1298 mdb_env_set_maxreaders(MDB_env *env, int readers)
1300 env->me_maxreaders = readers;
1305 mdb_env_get_maxreaders(MDB_env *env, int *readers)
1307 if (!env || !readers)
1309 *readers = env->me_maxreaders;
1314 mdb_env_open2(MDB_env *env, unsigned int flags)
1320 env->me_flags = flags;
1322 memset(&meta, 0, sizeof(meta));
1324 if ((i = mdb_env_read_header(env, &meta)) != 0) {
1327 DPUTS("new mdbenv");
1331 if (!env->me_mapsize) {
1332 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
1336 if (meta.mm_address && (flags & MDB_FIXEDMAP))
1338 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
1340 if (env->me_map == MAP_FAILED)
1344 meta.mm_mapsize = env->me_mapsize;
1345 if (flags & MDB_FIXEDMAP)
1346 meta.mm_address = env->me_map;
1347 i = mdb_env_init_meta(env, &meta);
1348 if (i != MDB_SUCCESS) {
1349 munmap(env->me_map, env->me_mapsize);
1353 env->me_psize = meta.mm_psize;
1355 env->me_maxpg = env->me_mapsize / env->me_psize;
1357 p = (MDB_page *)env->me_map;
1358 env->me_metas[0] = METADATA(p);
1359 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
1361 if ((i = mdb_env_read_meta(env, NULL)) != 0)
1364 DPRINTF("opened database version %u, pagesize %u",
1365 env->me_meta->mm_version, env->me_psize);
1366 DPRINTF("depth: %u", env->me_meta->mm_dbs[MAIN_DBI].md_depth);
1367 DPRINTF("entries: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_entries);
1368 DPRINTF("branch pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_branch_pages);
1369 DPRINTF("leaf pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_leaf_pages);
1370 DPRINTF("overflow pages: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_overflow_pages);
1371 DPRINTF("root: %lu", env->me_meta->mm_dbs[MAIN_DBI].md_root);
1377 mdb_env_reader_dest(void *ptr)
1379 MDB_reader *reader = ptr;
1381 reader->mr_txnid = 0;
1386 /* downgrade the exclusive lock on the region back to shared */
1388 mdb_env_share_locks(MDB_env *env)
1390 struct flock lock_info;
1392 env->me_txns->mti_txnid = env->me_meta->mm_txnid;
1393 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1394 env->me_txns->mti_me_toggle = 1;
1396 memset((void *)&lock_info, 0, sizeof(lock_info));
1397 lock_info.l_type = F_RDLCK;
1398 lock_info.l_whence = SEEK_SET;
1399 lock_info.l_start = 0;
1400 lock_info.l_len = 1;
1401 fcntl(env->me_lfd, F_SETLK, &lock_info);
1405 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
1409 struct flock lock_info;
1413 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
1417 /* Try to get exclusive lock. If we succeed, then
1418 * nobody is using the lock region and we should initialize it.
1420 memset((void *)&lock_info, 0, sizeof(lock_info));
1421 lock_info.l_type = F_WRLCK;
1422 lock_info.l_whence = SEEK_SET;
1423 lock_info.l_start = 0;
1424 lock_info.l_len = 1;
1425 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1429 lock_info.l_type = F_RDLCK;
1430 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1436 size = lseek(env->me_lfd, 0, SEEK_END);
1437 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1438 if (size < rsize && *excl) {
1439 if (ftruncate(env->me_lfd, rsize) != 0) {
1445 size = rsize - sizeof(MDB_txninfo);
1446 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
1448 env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
1450 if (env->me_txns == MAP_FAILED) {
1455 pthread_mutexattr_t mattr;
1457 pthread_mutexattr_init(&mattr);
1458 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
1462 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
1463 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
1464 env->me_txns->mti_version = MDB_VERSION;
1465 env->me_txns->mti_magic = MDB_MAGIC;
1466 env->me_txns->mti_txnid = 0;
1467 env->me_txns->mti_numreaders = 0;
1468 env->me_txns->mti_me_toggle = 0;
1471 if (env->me_txns->mti_magic != MDB_MAGIC) {
1472 DPUTS("lock region has invalid magic");
1476 if (env->me_txns->mti_version != MDB_VERSION) {
1477 DPRINTF("lock region is version %u, expected version %u",
1478 env->me_txns->mti_version, MDB_VERSION);
1479 rc = MDB_VERSION_MISMATCH;
1482 if (errno != EACCES && errno != EAGAIN) {
1496 #define LOCKNAME "/lock.mdb"
1497 #define DATANAME "/data.mdb"
1499 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
1501 int oflags, rc, len, excl;
1502 char *lpath, *dpath;
1505 lpath = malloc(len + sizeof(LOCKNAME) + len + sizeof(DATANAME));
1508 dpath = lpath + len + sizeof(LOCKNAME);
1509 sprintf(lpath, "%s" LOCKNAME, path);
1510 sprintf(dpath, "%s" DATANAME, path);
1512 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
1516 if (F_ISSET(flags, MDB_RDONLY))
1519 oflags = O_RDWR | O_CREAT;
1521 if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
1526 if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
1527 /* synchronous fd for meta writes */
1528 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
1529 oflags |= MDB_DSYNC;
1530 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
1535 env->me_path = strdup(path);
1536 DPRINTF("opened dbenv %p", (void *) env);
1537 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
1539 mdb_env_share_locks(env);
1540 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
1541 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
1542 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
1548 if (env->me_fd >= 0) {
1552 if (env->me_lfd >= 0) {
1562 mdb_env_close(MDB_env *env)
1569 while (env->me_dpages) {
1570 dp = env->me_dpages;
1571 env->me_dpages = (MDB_dpage *)dp->h.md_parent;
1575 free(env->me_dbs[1]);
1576 free(env->me_dbs[0]);
1580 pthread_key_delete(env->me_txkey);
1583 munmap(env->me_map, env->me_mapsize);
1588 pid_t pid = getpid();
1589 size_t size = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1591 for (i=0; i<env->me_txns->mti_numreaders; i++)
1592 if (env->me_txns->mti_readers[i].mr_pid == pid)
1593 env->me_txns->mti_readers[i].mr_pid = 0;
1594 munmap(env->me_txns, size);
1600 /* Search for key within a leaf page, using binary search.
1601 * Returns the smallest entry larger or equal to the key.
1602 * If exactp is non-null, stores whether the found entry was an exact match
1603 * in *exactp (1 or 0).
1604 * If kip is non-null, stores the index of the found entry in *kip.
1605 * If no entry larger or equal to the key is found, returns NULL.
1608 mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, MDB_val *key,
1609 int *exactp, unsigned int *kip)
1614 MDB_node *node = NULL;
1618 DPRINTF("searching %u keys in %s page %lu",
1620 IS_LEAF(mp) ? "leaf" : "branch",
1623 assert(NUMKEYS(mp) > 0);
1625 memset(&nodekey, 0, sizeof(nodekey));
1627 low = IS_LEAF(mp) ? 0 : 1;
1628 high = NUMKEYS(mp) - 1;
1629 while (low <= high) {
1630 i = (low + high) >> 1;
1633 nodekey.mv_size = txn->mt_dbs[dbi].md_pad;
1634 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
1636 node = NODEPTR(mp, i);
1638 nodekey.mv_size = node->mn_ksize;
1639 nodekey.mv_data = NODEKEY(node);
1642 rc = mdb_cmp(txn, dbi, key, &nodekey);
1645 DPRINTF("found leaf index %u [%s], rc = %i",
1646 i, DKEY(&nodekey), rc);
1648 DPRINTF("found branch index %u [%s -> %lu], rc = %i",
1649 i, DKEY(&nodekey), NODEPGNO(node), rc);
1659 if (rc > 0) { /* Found entry is less than the key. */
1660 i++; /* Skip to get the smallest entry larger than key. */
1661 if (i >= NUMKEYS(mp))
1662 /* There is no entry larger or equal to the key. */
1666 *exactp = (rc == 0);
1667 if (kip) /* Store the key index if requested. */
1670 /* nodeptr is fake for LEAF2 */
1671 return IS_LEAF2(mp) ? NODEPTR(mp, 0) : NODEPTR(mp, i);
1675 cursor_pop_page(MDB_cursor *cursor)
1679 if (cursor->mc_snum) {
1680 top = CURSOR_TOP(cursor);
1683 DPRINTF("popped page %lu off db %u cursor %p", top->mp_page->mp_pgno,
1684 cursor->mc_dbi, (void *) cursor);
1689 cursor_push_page(MDB_cursor *cursor, MDB_page *mp)
1693 DPRINTF("pushing page %lu on db %u cursor %p", mp->mp_pgno,
1694 cursor->mc_dbi, (void *) cursor);
1696 assert(cursor->mc_snum < CURSOR_STACK);
1698 ppage = &cursor->mc_stack[cursor->mc_snum++];
1699 ppage->mp_page = mp;
1705 mdb_get_page(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
1709 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
1714 x = mdb_midl2_search(txn->mt_u.dirty_list, &id);
1715 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
1716 dp = txn->mt_u.dirty_list[x].mptr;
1721 if (pgno <= txn->mt_env->me_meta->mm_last_pg)
1722 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
1726 DPRINTF("page %lu not found", pgno);
1729 return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
1733 mdb_search_page_root(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
1734 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
1736 MDB_page *mp = mpp->mp_page;
1740 if (cursor && cursor_push_page(cursor, mp) == NULL)
1743 while (IS_BRANCH(mp)) {
1747 DPRINTF("branch page %lu has %u keys", mp->mp_pgno, NUMKEYS(mp));
1748 assert(NUMKEYS(mp) > 1);
1749 DPRINTF("found index 0 to page %lu", NODEPGNO(NODEPTR(mp, 0)));
1751 if (key == NULL) /* Initialize cursor to first page. */
1753 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
1754 /* cursor to last page */
1758 node = mdb_search_node(txn, dbi, mp, key, &exact, &i);
1760 i = NUMKEYS(mp) - 1;
1768 DPRINTF("following index %u for key [%s]",
1770 assert(i < NUMKEYS(mp));
1771 node = NODEPTR(mp, i);
1774 CURSOR_TOP(cursor)->mp_ki = i;
1776 mpp->mp_parent = mp;
1777 if ((rc = mdb_get_page(txn, NODEPGNO(node), &mp)))
1782 if (cursor && cursor_push_page(cursor, mp) == NULL)
1786 MDB_dhead *dh = ((MDB_dhead *)mp)-1;
1787 if ((rc = mdb_touch(txn, mpp)) != 0)
1789 dh = ((MDB_dhead *)mpp->mp_page)-1;
1790 dh->md_parent = mpp->mp_parent;
1791 dh->md_pi = mpp->mp_pi;
1798 DPRINTF("internal error, index points to a %02X page!?",
1800 return MDB_CORRUPTED;
1803 DPRINTF("found leaf page %lu for key [%s]", mp->mp_pgno,
1804 key ? DKEY(key) : NULL);
1809 /* Search for the page a given key should be in.
1810 * Stores a pointer to the found page in *mpp.
1811 * If key is NULL, search for the lowest page (used by mdb_cursor_first).
1812 * If cursor is non-null, pushes parent pages on the cursor stack.
1813 * If modify is true, visited pages are updated with new page numbers.
1816 mdb_search_page(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
1817 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
1822 /* Choose which root page to start with. If a transaction is given
1823 * use the root page from the transaction, otherwise read the last
1824 * committed root page.
1826 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1827 DPUTS("transaction has failed, must abort");
1830 root = txn->mt_dbs[dbi].md_root;
1832 if (root == P_INVALID) { /* Tree is empty. */
1833 DPUTS("tree is empty");
1834 return MDB_NOTFOUND;
1837 if (rc = mdb_get_page(txn, root, &mpp->mp_page))
1840 DPRINTF("db %u root page %lu has flags 0x%X",
1841 dbi, root, mpp->mp_page->mp_flags);
1844 /* For sub-databases, update main root first */
1845 if (dbi > MAIN_DBI && !txn->mt_dbxs[dbi].md_dirty) {
1847 rc = mdb_search_page(txn, MAIN_DBI, &txn->mt_dbxs[dbi].md_name,
1851 txn->mt_dbxs[dbi].md_dirty = 1;
1853 if (!F_ISSET(mpp->mp_page->mp_flags, P_DIRTY)) {
1854 mpp->mp_parent = NULL;
1856 if ((rc = mdb_touch(txn, mpp)))
1858 txn->mt_dbs[dbi].md_root = mpp->mp_page->mp_pgno;
1862 return mdb_search_page_root(txn, dbi, key, cursor, modify, mpp);
1866 mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
1868 MDB_page *omp; /* overflow mpage */
1872 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
1873 data->mv_size = leaf->mn_dsize;
1874 data->mv_data = NODEDATA(leaf);
1878 /* Read overflow data.
1880 data->mv_size = leaf->mn_dsize;
1881 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
1882 if (rc = mdb_get_page(txn, pgno, &omp)) {
1883 DPRINTF("read overflow page %lu failed", pgno);
1886 data->mv_data = METADATA(omp);
1892 mdb_get(MDB_txn *txn, MDB_dbi dbi,
1893 MDB_val *key, MDB_val *data)
1902 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
1904 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
1907 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
1911 if ((rc = mdb_search_page(txn, dbi, key, NULL, 0, &mpp)) != MDB_SUCCESS)
1914 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, NULL);
1915 if (leaf && exact) {
1916 /* Return first duplicate data item */
1917 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
1920 mdb_xcursor_init0(txn, dbi, &mx);
1921 mdb_xcursor_init1(txn, dbi, &mx, mpp.mp_page, leaf);
1922 rc = mdb_search_page(&mx.mx_txn, mx.mx_cursor.mc_dbi, NULL, NULL, 0, &mpp);
1923 if (rc != MDB_SUCCESS)
1925 if (IS_LEAF2(mpp.mp_page)) {
1926 data->mv_size = txn->mt_dbs[dbi].md_pad;
1927 data->mv_data = LEAF2KEY(mpp.mp_page, 0, data->mv_size);
1929 leaf = NODEPTR(mpp.mp_page, 0);
1930 data->mv_size = NODEKSZ(leaf);
1931 data->mv_data = NODEKEY(leaf);
1934 rc = mdb_read_data(txn, leaf, data);
1944 mdb_sibling(MDB_cursor *cursor, int move_right)
1951 if (cursor->mc_snum < 2) {
1952 return MDB_NOTFOUND; /* root has no siblings */
1954 parent = CURSOR_PARENT(cursor);
1956 DPRINTF("parent page is page %lu, index %u",
1957 parent->mp_page->mp_pgno, parent->mp_ki);
1959 cursor_pop_page(cursor);
1960 if (move_right ? (parent->mp_ki + 1 >= NUMKEYS(parent->mp_page))
1961 : (parent->mp_ki == 0)) {
1962 DPRINTF("no more keys left, moving to %s sibling",
1963 move_right ? "right" : "left");
1964 if ((rc = mdb_sibling(cursor, move_right)) != MDB_SUCCESS)
1966 parent = CURSOR_TOP(cursor);
1972 DPRINTF("just moving to %s index key %u",
1973 move_right ? "right" : "left", parent->mp_ki);
1975 assert(IS_BRANCH(parent->mp_page));
1977 indx = NODEPTR(parent->mp_page, parent->mp_ki);
1978 if (rc = mdb_get_page(cursor->mc_txn, NODEPGNO(indx), &mp))
1981 mp->parent = parent->mp_page;
1982 mp->parent_index = parent->mp_ki;
1985 cursor_push_page(cursor, mp);
1991 mdb_cursor_next(MDB_cursor *cursor, MDB_val *key, MDB_val *data, MDB_cursor_op op)
1998 if (cursor->mc_eof) {
1999 return MDB_NOTFOUND;
2002 assert(cursor->mc_initialized);
2004 top = CURSOR_TOP(cursor);
2007 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2008 leaf = NODEPTR(mp, top->mp_ki);
2009 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2010 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
2011 rc = mdb_cursor_next(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
2012 if (op != MDB_NEXT || rc == MDB_SUCCESS)
2016 cursor->mc_xcursor->mx_cursor.mc_initialized = 0;
2017 if (op == MDB_NEXT_DUP)
2018 return MDB_NOTFOUND;
2022 DPRINTF("cursor_next: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
2024 if (top->mp_ki + 1 >= NUMKEYS(mp)) {
2025 DPUTS("=====> move to next sibling page");
2026 if (mdb_sibling(cursor, 1) != MDB_SUCCESS) {
2028 return MDB_NOTFOUND;
2030 top = CURSOR_TOP(cursor);
2032 DPRINTF("next page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
2036 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
2037 mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
2040 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2041 key->mv_data = LEAF2KEY(mp, top->mp_ki, key->mv_size);
2045 assert(IS_LEAF(mp));
2046 leaf = NODEPTR(mp, top->mp_ki);
2048 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2049 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, mp, leaf);
2052 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS))
2055 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2056 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2057 if (rc != MDB_SUCCESS)
2062 MDB_SET_KEY(leaf, key);
2067 mdb_cursor_prev(MDB_cursor *cursor, MDB_val *key, MDB_val *data, MDB_cursor_op op)
2074 assert(cursor->mc_initialized);
2076 top = CURSOR_TOP(cursor);
2079 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2080 leaf = NODEPTR(mp, top->mp_ki);
2081 if (op == MDB_PREV || op == MDB_PREV_DUP) {
2082 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2083 rc = mdb_cursor_prev(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
2084 if (op != MDB_PREV || rc == MDB_SUCCESS)
2087 cursor->mc_xcursor->mx_cursor.mc_initialized = 0;
2088 if (op == MDB_PREV_DUP)
2089 return MDB_NOTFOUND;
2094 DPRINTF("cursor_prev: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
2096 if (top->mp_ki == 0) {
2097 DPUTS("=====> move to prev sibling page");
2098 if (mdb_sibling(cursor, 0) != MDB_SUCCESS) {
2099 cursor->mc_initialized = 0;
2100 return MDB_NOTFOUND;
2102 top = CURSOR_TOP(cursor);
2104 top->mp_ki = NUMKEYS(mp) - 1;
2105 DPRINTF("prev page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
2111 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
2112 mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
2115 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2116 key->mv_data = LEAF2KEY(mp, top->mp_ki, key->mv_size);
2120 assert(IS_LEAF(mp));
2121 leaf = NODEPTR(mp, top->mp_ki);
2123 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2124 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, mp, leaf);
2127 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS))
2130 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2131 rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
2132 if (rc != MDB_SUCCESS)
2137 MDB_SET_KEY(leaf, key);
2142 mdb_cursor_set(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
2143 MDB_cursor_op op, int *exactp)
2153 assert(key->mv_size > 0);
2155 /* See if we're already on the right page */
2156 if (cursor->mc_initialized) {
2158 top = CURSOR_TOP(cursor);
2159 /* Don't try this for LEAF2 pages. Maybe support that later. */
2160 if ((top->mp_page->mp_flags & (P_LEAF|P_LEAF2)) == P_LEAF) {
2161 leaf = NODEPTR(top->mp_page, 0);
2162 MDB_SET_KEY(leaf, &nodekey);
2163 rc = mdb_cmp(cursor->mc_txn, cursor->mc_dbi, key, &nodekey);
2165 leaf = NODEPTR(top->mp_page, NUMKEYS(top->mp_page)-1);
2166 MDB_SET_KEY(leaf, &nodekey);
2167 rc = mdb_cmp(cursor->mc_txn, cursor->mc_dbi, key, &nodekey);
2169 /* we're already on the right page */
2170 mpp.mp_page = top->mp_page;
2177 cursor->mc_snum = 0;
2179 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, key, cursor, 0, &mpp);
2180 if (rc != MDB_SUCCESS)
2183 assert(IS_LEAF(mpp.mp_page));
2185 top = CURSOR_TOP(cursor);
2187 leaf = mdb_search_node(cursor->mc_txn, cursor->mc_dbi, mpp.mp_page, key, exactp, &top->mp_ki);
2188 if (exactp != NULL && !*exactp) {
2189 /* MDB_SET specified and not an exact match. */
2190 return MDB_NOTFOUND;
2194 DPUTS("===> inexact leaf not found, goto sibling");
2195 if ((rc = mdb_sibling(cursor, 1)) != MDB_SUCCESS)
2196 return rc; /* no entries matched */
2197 top = CURSOR_TOP(cursor);
2199 mpp.mp_page = top->mp_page;
2200 assert(IS_LEAF(mpp.mp_page));
2201 leaf = NODEPTR(mpp.mp_page, 0);
2204 cursor->mc_initialized = 1;
2207 if (IS_LEAF2(mpp.mp_page)) {
2208 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2209 key->mv_data = LEAF2KEY(mpp.mp_page, top->mp_ki, key->mv_size);
2213 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2214 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, mpp.mp_page, leaf);
2217 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2218 if (op == MDB_SET || op == MDB_SET_RANGE) {
2219 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2222 if (op == MDB_GET_BOTH) {
2227 rc = mdb_cursor_set(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
2228 if (rc != MDB_SUCCESS)
2231 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
2233 if ((rc = mdb_read_data(cursor->mc_txn, leaf, &d2)) != MDB_SUCCESS)
2235 rc = mdb_dcmp(cursor->mc_txn, cursor->mc_dbi, data, &d2);
2237 if (op == MDB_GET_BOTH || rc > 0)
2238 return MDB_NOTFOUND;
2242 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2247 /* The key already matches in all other cases */
2248 if (op == MDB_SET_RANGE)
2249 MDB_SET_KEY(leaf, key);
2250 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
2256 mdb_cursor_first(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
2262 cursor->mc_snum = 0;
2264 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, NULL, cursor, 0, &mpp);
2265 if (rc != MDB_SUCCESS)
2267 assert(IS_LEAF(mpp.mp_page));
2269 leaf = NODEPTR(mpp.mp_page, 0);
2270 cursor->mc_initialized = 1;
2273 if (IS_LEAF2(mpp.mp_page)) {
2274 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2275 key->mv_data = LEAF2KEY(mpp.mp_page, 0, key->mv_size);
2280 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2281 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, mpp.mp_page, leaf);
2282 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2286 if (cursor->mc_xcursor)
2287 cursor->mc_xcursor->mx_cursor.mc_initialized = 0;
2288 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2292 MDB_SET_KEY(leaf, key);
2297 mdb_cursor_last(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
2305 cursor->mc_snum = 0;
2307 lkey.mv_size = MAXKEYSIZE+1;
2308 lkey.mv_data = NULL;
2310 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, &lkey, cursor, 0, &mpp);
2311 if (rc != MDB_SUCCESS)
2313 assert(IS_LEAF(mpp.mp_page));
2315 leaf = NODEPTR(mpp.mp_page, NUMKEYS(mpp.mp_page)-1);
2316 cursor->mc_initialized = 1;
2319 top = CURSOR_TOP(cursor);
2320 top->mp_ki = NUMKEYS(top->mp_page) - 1;
2322 if (IS_LEAF2(mpp.mp_page)) {
2323 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2324 key->mv_data = LEAF2KEY(mpp.mp_page, top->mp_ki, key->mv_size);
2329 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2330 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, mpp.mp_page, leaf);
2331 rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
2335 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2340 MDB_SET_KEY(leaf, key);
2345 mdb_cursor_get(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
2355 case MDB_GET_BOTH_RANGE:
2356 if (data == NULL || cursor->mc_xcursor == NULL) {
2363 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2365 } else if (op == MDB_SET_RANGE)
2366 rc = mdb_cursor_set(cursor, key, data, op, NULL);
2368 rc = mdb_cursor_set(cursor, key, data, op, &exact);
2370 case MDB_GET_MULTIPLE:
2372 !(cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPFIXED) ||
2373 !cursor->mc_initialized) {
2378 if (!cursor->mc_xcursor->mx_cursor.mc_initialized || cursor->mc_xcursor->mx_cursor.mc_eof)
2381 case MDB_NEXT_MULTIPLE:
2383 !(cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPFIXED)) {
2387 if (!cursor->mc_initialized)
2388 rc = mdb_cursor_first(cursor, key, data);
2390 rc = mdb_cursor_next(cursor, key, data, MDB_NEXT_DUP);
2391 if (rc == MDB_SUCCESS) {
2392 if (cursor->mc_xcursor->mx_cursor.mc_initialized) {
2395 top = CURSOR_TOP(&cursor->mc_xcursor->mx_cursor);
2396 data->mv_size = NUMKEYS(top->mp_page) *
2397 cursor->mc_xcursor->mx_txn.mt_dbs[cursor->mc_xcursor->mx_cursor.mc_dbi].md_pad;
2398 data->mv_data = METADATA(top->mp_page);
2399 top->mp_ki = NUMKEYS(top->mp_page)-1;
2407 case MDB_NEXT_NODUP:
2408 if (!cursor->mc_initialized)
2409 rc = mdb_cursor_first(cursor, key, data);
2411 rc = mdb_cursor_next(cursor, key, data, op);
2415 case MDB_PREV_NODUP:
2416 if (!cursor->mc_initialized || cursor->mc_eof)
2417 rc = mdb_cursor_last(cursor, key, data);
2419 rc = mdb_cursor_prev(cursor, key, data, op);
2422 rc = mdb_cursor_first(cursor, key, data);
2425 rc = mdb_cursor_last(cursor, key, data);
2428 DPRINTF("unhandled/unimplemented cursor operation %u", op);
2436 /* Allocate a page and initialize it
2439 mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num)
2443 if ((dp = mdb_alloc_page(txn, NULL, 0, num)) == NULL)
2445 DPRINTF("allocated new mpage %lu, page size %u",
2446 dp->p.mp_pgno, txn->mt_env->me_psize);
2447 dp->p.mp_flags = flags | P_DIRTY;
2448 dp->p.mp_lower = PAGEHDRSZ;
2449 dp->p.mp_upper = txn->mt_env->me_psize;
2451 if (IS_BRANCH(&dp->p))
2452 txn->mt_dbs[dbi].md_branch_pages++;
2453 else if (IS_LEAF(&dp->p))
2454 txn->mt_dbs[dbi].md_leaf_pages++;
2455 else if (IS_OVERFLOW(&dp->p)) {
2456 txn->mt_dbs[dbi].md_overflow_pages += num;
2457 dp->p.mp_pages = num;
2464 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
2468 sz = LEAFSIZE(key, data);
2469 if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
2470 /* put on overflow page */
2471 sz -= data->mv_size - sizeof(pgno_t);
2474 return sz + sizeof(indx_t);
2478 mdb_branch_size(MDB_env *env, MDB_val *key)
2483 if (sz >= env->me_psize / MDB_MINKEYS) {
2484 /* put on overflow page */
2485 /* not implemented */
2486 /* sz -= key->size - sizeof(pgno_t); */
2489 return sz + sizeof(indx_t);
2493 mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, indx_t indx,
2494 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags)
2497 size_t node_size = NODESIZE;
2500 MDB_dpage *ofp = NULL; /* overflow page */
2503 assert(mp->mp_upper >= mp->mp_lower);
2505 DPRINTF("add node [%s] to %s page %lu at index %i, key size %zu",
2506 key ? DKEY(key) : NULL,
2507 IS_LEAF(mp) ? "leaf" : "branch",
2508 mp->mp_pgno, indx, key ? key->mv_size : 0);
2511 /* Move higher keys up one slot. */
2512 int ksize = txn->mt_dbs[dbi].md_pad, dif;
2513 char *ptr = LEAF2KEY(mp, indx, ksize);
2514 dif = NUMKEYS(mp) - indx;
2516 memmove(ptr+ksize, ptr, dif*ksize);
2517 /* insert new key */
2518 memcpy(ptr, key->mv_data, ksize);
2520 /* Just using these for counting */
2521 mp->mp_lower += sizeof(indx_t);
2522 mp->mp_upper -= ksize - sizeof(indx_t);
2527 node_size += key->mv_size;
2531 if (F_ISSET(flags, F_BIGDATA)) {
2532 /* Data already on overflow page. */
2533 node_size += sizeof(pgno_t);
2534 } else if (data->mv_size >= txn->mt_env->me_psize / MDB_MINKEYS) {
2535 int ovpages = OVPAGES(data->mv_size, txn->mt_env->me_psize);
2536 /* Put data on overflow page. */
2537 DPRINTF("data size is %zu, put on overflow page",
2539 node_size += sizeof(pgno_t);
2540 if ((ofp = mdb_new_page(txn, dbi, P_OVERFLOW, ovpages)) == NULL)
2542 DPRINTF("allocated overflow page %lu", ofp->p.mp_pgno);
2545 node_size += data->mv_size;
2549 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
2550 DPRINTF("not enough room in page %lu, got %u ptrs",
2551 mp->mp_pgno, NUMKEYS(mp));
2552 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
2553 mp->mp_upper - mp->mp_lower);
2554 DPRINTF("node size = %zu", node_size);
2558 /* Move higher pointers up one slot. */
2559 for (i = NUMKEYS(mp); i > indx; i--)
2560 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
2562 /* Adjust free space offsets. */
2563 ofs = mp->mp_upper - node_size;
2564 assert(ofs >= mp->mp_lower + sizeof(indx_t));
2565 mp->mp_ptrs[indx] = ofs;
2567 mp->mp_lower += sizeof(indx_t);
2569 /* Write the node data. */
2570 node = NODEPTR(mp, indx);
2571 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
2572 node->mn_flags = flags;
2574 node->mn_dsize = data->mv_size;
2576 NODEPGNO(node) = pgno;
2579 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
2584 if (F_ISSET(flags, F_BIGDATA))
2585 memcpy(node->mn_data + key->mv_size, data->mv_data,
2588 memcpy(node->mn_data + key->mv_size, data->mv_data,
2591 memcpy(node->mn_data + key->mv_size, &ofp->p.mp_pgno,
2593 memcpy(METADATA(&ofp->p), data->mv_data, data->mv_size);
2601 mdb_del_node(MDB_page *mp, indx_t indx, int ksize)
2604 indx_t i, j, numkeys, ptr;
2608 DPRINTF("delete node %u on %s page %lu", indx,
2609 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
2610 assert(indx < NUMKEYS(mp));
2613 int x = NUMKEYS(mp) - 1 - indx;
2614 base = LEAF2KEY(mp, indx, ksize);
2616 memmove(base, base + ksize, x * ksize);
2617 mp->mp_lower -= sizeof(indx_t);
2618 mp->mp_upper += ksize - sizeof(indx_t);
2622 node = NODEPTR(mp, indx);
2623 sz = NODESIZE + node->mn_ksize;
2625 if (F_ISSET(node->mn_flags, F_BIGDATA))
2626 sz += sizeof(pgno_t);
2628 sz += NODEDSZ(node);
2631 ptr = mp->mp_ptrs[indx];
2632 numkeys = NUMKEYS(mp);
2633 for (i = j = 0; i < numkeys; i++) {
2635 mp->mp_ptrs[j] = mp->mp_ptrs[i];
2636 if (mp->mp_ptrs[i] < ptr)
2637 mp->mp_ptrs[j] += sz;
2642 base = (char *)mp + mp->mp_upper;
2643 memmove(base + sz, base, ptr - mp->mp_upper);
2645 mp->mp_lower -= sizeof(indx_t);
2650 mdb_xcursor_init0(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
2655 mx->mx_txn.mt_dbxs = mx->mx_dbxs;
2656 mx->mx_txn.mt_dbs = mx->mx_dbs;
2657 mx->mx_dbxs[0] = txn->mt_dbxs[0];
2658 mx->mx_dbxs[1] = txn->mt_dbxs[1];
2660 mx->mx_dbxs[2] = txn->mt_dbxs[dbi];
2665 mx->mx_dbxs[dbn+1].md_parent = dbn;
2666 mx->mx_dbxs[dbn+1].md_cmp = mx->mx_dbxs[dbn].md_dcmp;
2667 mx->mx_dbxs[dbn+1].md_rel = mx->mx_dbxs[dbn].md_rel;
2668 mx->mx_dbxs[dbn+1].md_dirty = 0;
2669 mx->mx_txn.mt_numdbs = dbn+2;
2671 mx->mx_cursor.mc_snum = 0;
2672 mx->mx_cursor.mc_txn = &mx->mx_txn;
2673 mx->mx_cursor.mc_dbi = dbn+1;
2677 mdb_xcursor_init1(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx, MDB_page *mp, MDB_node *node)
2679 MDB_db *db = NODEDATA(node);
2681 mx->mx_dbs[0] = txn->mt_dbs[0];
2682 mx->mx_dbs[1] = txn->mt_dbs[1];
2684 mx->mx_dbs[2] = txn->mt_dbs[dbi];
2689 DPRINTF("Sub-db %u for db %u root page %lu", dbn, dbi, db->md_root);
2690 mx->mx_dbs[dbn] = *db;
2691 if (F_ISSET(mp->mp_flags, P_DIRTY))
2692 mx->mx_dbxs[dbn].md_dirty = 1;
2693 mx->mx_dbxs[dbn].md_name.mv_data = NODEKEY(node);
2694 mx->mx_dbxs[dbn].md_name.mv_size = node->mn_ksize;
2695 mx->mx_txn.mt_next_pgno = txn->mt_next_pgno;
2696 mx->mx_txn.mt_oldest = txn->mt_oldest;
2697 mx->mx_txn.mt_u = txn->mt_u;
2698 mx->mx_cursor.mc_initialized = 0;
2699 mx->mx_cursor.mc_eof = 0;
2703 mdb_xcursor_fini(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
2705 txn->mt_next_pgno = mx->mx_txn.mt_next_pgno;
2706 txn->mt_oldest = mx->mx_txn.mt_oldest;
2707 txn->mt_u = mx->mx_txn.mt_u;
2708 txn->mt_dbs[0] = mx->mx_dbs[0];
2709 txn->mt_dbs[1] = mx->mx_dbs[1];
2710 txn->mt_dbxs[0].md_dirty = mx->mx_dbxs[0].md_dirty;
2711 txn->mt_dbxs[1].md_dirty = mx->mx_dbxs[1].md_dirty;
2713 txn->mt_dbs[dbi] = mx->mx_dbs[2];
2714 txn->mt_dbxs[dbi].md_dirty = mx->mx_dbxs[2].md_dirty;
2719 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
2722 size_t size = sizeof(MDB_cursor);
2724 if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
2727 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
2728 size += sizeof(MDB_xcursor);
2730 if ((cursor = calloc(1, size)) != NULL) {
2731 cursor->mc_dbi = dbi;
2732 cursor->mc_txn = txn;
2733 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
2734 MDB_xcursor *mx = (MDB_xcursor *)(cursor + 1);
2735 cursor->mc_xcursor = mx;
2736 mdb_xcursor_init0(txn, dbi, mx);
2747 /* Return the count of duplicate data items for the current key */
2749 mdb_cursor_count(MDB_cursor *mc, unsigned long *countp)
2754 if (mc == NULL || countp == NULL)
2757 if (!(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT))
2760 top = CURSOR_TOP(mc);
2761 leaf = NODEPTR(top->mp_page, top->mp_ki);
2762 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2765 if (!mc->mc_xcursor->mx_cursor.mc_initialized)
2768 *countp = mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_entries;
2774 mdb_cursor_close(MDB_cursor *cursor)
2776 if (cursor != NULL) {
2782 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
2784 indx_t ptr, i, numkeys;
2791 node = NODEPTR(mp, indx);
2792 ptr = mp->mp_ptrs[indx];
2793 DPRINTF("update key %u (ofs %u) [%.*s] to [%s] on page %lu",
2795 (int)node->mn_ksize, (char *)NODEKEY(node),
2799 delta = key->mv_size - node->mn_ksize;
2801 if (delta > 0 && SIZELEFT(mp) < delta) {
2802 DPRINTF("OUCH! Not enough room, delta = %d", delta);
2806 numkeys = NUMKEYS(mp);
2807 for (i = 0; i < numkeys; i++) {
2808 if (mp->mp_ptrs[i] <= ptr)
2809 mp->mp_ptrs[i] -= delta;
2812 base = (char *)mp + mp->mp_upper;
2813 len = ptr - mp->mp_upper + NODESIZE;
2814 memmove(base - delta, base, len);
2815 mp->mp_upper -= delta;
2817 node = NODEPTR(mp, indx);
2818 node->mn_ksize = key->mv_size;
2821 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
2826 /* Move a node from src to dst.
2829 mdb_move_node(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, indx_t srcindx,
2830 MDB_pageparent *dst, indx_t dstindx)
2837 /* Mark src and dst as dirty. */
2838 if ((rc = mdb_touch(txn, src)) ||
2839 (rc = mdb_touch(txn, dst)))
2842 if (IS_LEAF2(src->mp_page)) {
2843 srcnode = NODEPTR(src->mp_page, 0); /* fake */
2844 key.mv_size = txn->mt_dbs[dbi].md_pad;
2845 key.mv_data = LEAF2KEY(src->mp_page, srcindx, key.mv_size);
2847 data.mv_data = NULL;
2849 srcnode = NODEPTR(src->mp_page, srcindx);
2850 key.mv_size = NODEKSZ(srcnode);
2851 key.mv_data = NODEKEY(srcnode);
2852 data.mv_size = NODEDSZ(srcnode);
2853 data.mv_data = NODEDATA(srcnode);
2855 DPRINTF("moving %s node %u [%s] on page %lu to node %u on page %lu",
2856 IS_LEAF(src->mp_page) ? "leaf" : "branch",
2859 src->mp_page->mp_pgno,
2860 dstindx, dst->mp_page->mp_pgno);
2862 /* Add the node to the destination page.
2864 rc = mdb_add_node(txn, dbi, dst->mp_page, dstindx, &key, &data, NODEPGNO(srcnode),
2866 if (rc != MDB_SUCCESS)
2869 /* Delete the node from the source page.
2871 mdb_del_node(src->mp_page, srcindx, key.mv_size);
2873 /* The key value just changed due to del_node, find it again.
2875 if (!IS_LEAF2(src->mp_page)) {
2876 srcnode = NODEPTR(src->mp_page, srcindx);
2877 key.mv_data = NODEKEY(srcnode);
2880 /* Update the parent separators.
2883 if (src->mp_pi != 0) {
2884 DPRINTF("update separator for source page %lu to [%s]",
2885 src->mp_page->mp_pgno, DKEY(&key));
2886 if ((rc = mdb_update_key(src->mp_parent, src->mp_pi,
2887 &key)) != MDB_SUCCESS)
2890 if (IS_BRANCH(src->mp_page)) {
2892 nullkey.mv_size = 0;
2893 assert(mdb_update_key(src->mp_page, 0, &nullkey) == MDB_SUCCESS);
2898 if (dst->mp_pi != 0) {
2899 DPRINTF("update separator for destination page %lu to [%s]",
2900 dst->mp_page->mp_pgno, DKEY(&key));
2901 if ((rc = mdb_update_key(dst->mp_parent, dst->mp_pi,
2902 &key)) != MDB_SUCCESS)
2905 if (IS_BRANCH(dst->mp_page)) {
2907 nullkey.mv_size = 0;
2908 assert(mdb_update_key(dst->mp_page, 0, &nullkey) == MDB_SUCCESS);
2916 mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, MDB_pageparent *dst)
2925 DPRINTF("merging page %lu and %lu", src->mp_page->mp_pgno, dst->mp_page->mp_pgno);
2927 assert(txn != NULL);
2928 assert(src->mp_parent); /* can't merge root page */
2929 assert(dst->mp_parent);
2931 /* Mark src and dst as dirty. */
2932 if ((rc = mdb_touch(txn, src)) ||
2933 (rc = mdb_touch(txn, dst)))
2936 /* Move all nodes from src to dst.
2938 if (IS_LEAF2(src->mp_page)) {
2939 key.mv_size = txn->mt_dbs[dbi].md_pad;
2940 key.mv_data = METADATA(src->mp_page);
2941 for (i = 0; i < NUMKEYS(src->mp_page); i++) {
2942 rc = mdb_add_node(txn, dbi, dst->mp_page, NUMKEYS(dst->mp_page), &key,
2944 if (rc != MDB_SUCCESS)
2946 key.mv_data = (char *)key.mv_data + key.mv_size;
2949 for (i = 0; i < NUMKEYS(src->mp_page); i++) {
2950 srcnode = NODEPTR(src->mp_page, i);
2952 key.mv_size = srcnode->mn_ksize;
2953 key.mv_data = NODEKEY(srcnode);
2954 data.mv_size = NODEDSZ(srcnode);
2955 data.mv_data = NODEDATA(srcnode);
2956 rc = mdb_add_node(txn, dbi, dst->mp_page, NUMKEYS(dst->mp_page), &key,
2957 &data, NODEPGNO(srcnode), srcnode->mn_flags);
2958 if (rc != MDB_SUCCESS)
2963 DPRINTF("dst page %lu now has %u keys (%.1f%% filled)",
2964 dst->mp_page->mp_pgno, NUMKEYS(dst->mp_page), (float)PAGEFILL(txn->mt_env, dst->mp_page) / 10);
2966 /* Unlink the src page from parent.
2968 mdb_del_node(src->mp_parent, src->mp_pi, 0);
2969 if (src->mp_pi == 0) {
2971 if ((rc = mdb_update_key(src->mp_parent, 0, &key)) != MDB_SUCCESS)
2975 if (IS_LEAF(src->mp_page))
2976 txn->mt_dbs[dbi].md_leaf_pages--;
2978 txn->mt_dbs[dbi].md_branch_pages--;
2980 mpp.mp_page = src->mp_parent;
2981 dh = (MDB_dhead *)src->mp_parent;
2983 mpp.mp_parent = dh->md_parent;
2984 mpp.mp_pi = dh->md_pi;
2986 return mdb_rebalance(txn, dbi, &mpp);
2989 #define FILL_THRESHOLD 250
2992 mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mpp)
2997 indx_t si = 0, di = 0;
3000 assert(txn != NULL);
3001 assert(mpp != NULL);
3003 DPRINTF("rebalancing %s page %lu (has %u keys, %.1f%% full)",
3004 IS_LEAF(mpp->mp_page) ? "leaf" : "branch",
3005 mpp->mp_page->mp_pgno, NUMKEYS(mpp->mp_page), (float)PAGEFILL(txn->mt_env, mpp->mp_page) / 10);
3007 if (PAGEFILL(txn->mt_env, mpp->mp_page) >= FILL_THRESHOLD) {
3008 DPRINTF("no need to rebalance page %lu, above fill threshold",
3009 mpp->mp_page->mp_pgno);
3013 if (mpp->mp_parent == NULL) {
3014 if (NUMKEYS(mpp->mp_page) == 0) {
3015 DPUTS("tree is completely empty");
3016 txn->mt_dbs[dbi].md_root = P_INVALID;
3017 txn->mt_dbs[dbi].md_depth = 0;
3018 txn->mt_dbs[dbi].md_leaf_pages = 0;
3019 } else if (IS_BRANCH(mpp->mp_page) && NUMKEYS(mpp->mp_page) == 1) {
3020 DPUTS("collapsing root page!");
3021 txn->mt_dbs[dbi].md_root = NODEPGNO(NODEPTR(mpp->mp_page, 0));
3022 if (rc = mdb_get_page(txn, txn->mt_dbs[dbi].md_root, &root))
3024 txn->mt_dbs[dbi].md_depth--;
3025 txn->mt_dbs[dbi].md_branch_pages--;
3027 DPUTS("root page doesn't need rebalancing");
3031 /* The parent (branch page) must have at least 2 pointers,
3032 * otherwise the tree is invalid.
3034 assert(NUMKEYS(mpp->mp_parent) > 1);
3036 /* Leaf page fill factor is below the threshold.
3037 * Try to move keys from left or right neighbor, or
3038 * merge with a neighbor page.
3043 if (mpp->mp_pi == 0) {
3044 /* We're the leftmost leaf in our parent.
3046 DPUTS("reading right neighbor");
3047 node = NODEPTR(mpp->mp_parent, mpp->mp_pi + 1);
3048 if (rc = mdb_get_page(txn, NODEPGNO(node), &npp.mp_page))
3050 npp.mp_pi = mpp->mp_pi + 1;
3052 di = NUMKEYS(mpp->mp_page);
3054 /* There is at least one neighbor to the left.
3056 DPUTS("reading left neighbor");
3057 node = NODEPTR(mpp->mp_parent, mpp->mp_pi - 1);
3058 if (rc = mdb_get_page(txn, NODEPGNO(node), &npp.mp_page))
3060 npp.mp_pi = mpp->mp_pi - 1;
3061 si = NUMKEYS(npp.mp_page) - 1;
3064 npp.mp_parent = mpp->mp_parent;
3066 DPRINTF("found neighbor page %lu (%u keys, %.1f%% full)",
3067 npp.mp_page->mp_pgno, NUMKEYS(npp.mp_page), (float)PAGEFILL(txn->mt_env, npp.mp_page) / 10);
3069 /* If the neighbor page is above threshold and has at least two
3070 * keys, move one key from it.
3072 * Otherwise we should try to merge them.
3074 if (PAGEFILL(txn->mt_env, npp.mp_page) >= FILL_THRESHOLD && NUMKEYS(npp.mp_page) >= 2)
3075 return mdb_move_node(txn, dbi, &npp, si, mpp, di);
3076 else { /* FIXME: if (has_enough_room()) */
3077 if (mpp->mp_pi == 0)
3078 return mdb_merge(txn, dbi, &npp, mpp);
3080 return mdb_merge(txn, dbi, mpp, &npp);
3085 mdb_del0(MDB_txn *txn, MDB_dbi dbi, unsigned int ki, MDB_pageparent *mpp, MDB_node *leaf)
3089 /* add overflow pages to free list */
3090 if (!IS_LEAF2(mpp->mp_page) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
3094 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
3095 ovpages = OVPAGES(NODEDSZ(leaf), txn->mt_env->me_psize);
3096 for (i=0; i<ovpages; i++) {
3097 DPRINTF("freed ov page %lu", pg);
3098 mdb_midl_insert(txn->mt_free_pgs, pg);
3102 mdb_del_node(mpp->mp_page, ki, txn->mt_dbs[dbi].md_pad);
3103 txn->mt_dbs[dbi].md_entries--;
3104 rc = mdb_rebalance(txn, dbi, mpp);
3105 if (rc != MDB_SUCCESS)
3106 txn->mt_flags |= MDB_TXN_ERROR;
3112 mdb_del(MDB_txn *txn, MDB_dbi dbi,
3113 MDB_val *key, MDB_val *data,
3122 assert(key != NULL);
3124 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
3126 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3129 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3133 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3137 mpp.mp_parent = NULL;
3139 if ((rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp)) != MDB_SUCCESS)
3142 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
3143 if (leaf == NULL || !exact) {
3144 return MDB_NOTFOUND;
3147 if (!IS_LEAF2(mpp.mp_page) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3151 mdb_xcursor_init0(txn, dbi, &mx);
3152 mdb_xcursor_init1(txn, dbi, &mx, mpp.mp_page, leaf);
3153 if (flags == MDB_DEL_DUP) {
3154 rc = mdb_del(&mx.mx_txn, mx.mx_cursor.mc_dbi, data, NULL, 0);
3155 mdb_xcursor_fini(txn, dbi, &mx);
3156 /* If sub-DB still has entries, we're done */
3157 if (mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi].md_root != P_INVALID) {
3158 memcpy(NODEDATA(leaf), &mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi],
3160 txn->mt_dbs[dbi].md_entries--;
3163 /* otherwise fall thru and delete the sub-DB */
3165 /* add all the child DB's pages to the free list */
3166 rc = mdb_search_page(&mx.mx_txn, mx.mx_cursor.mc_dbi,
3167 NULL, &mx.mx_cursor, 0, &mp2);
3168 if (rc == MDB_SUCCESS) {
3169 MDB_ppage *top, *parent;
3173 cursor_pop_page(&mx.mx_cursor);
3174 if (mx.mx_cursor.mc_snum) {
3175 top = CURSOR_TOP(&mx.mx_cursor);
3176 while (mx.mx_cursor.mc_snum > 1) {
3177 parent = CURSOR_PARENT(&mx.mx_cursor);
3178 for (i=0; i<NUMKEYS(top->mp_page); i++) {
3179 ni = NODEPTR(top->mp_page, i);
3180 mdb_midl_insert(txn->mt_free_pgs, NODEPGNO(ni));
3183 if (parent->mp_ki >= NUMKEYS(parent->mp_page)) {
3184 cursor_pop_page(&mx.mx_cursor);
3187 ni = NODEPTR(parent->mp_page, parent->mp_ki);
3188 rc = mdb_get_page(&mx.mx_txn, NODEPGNO(ni), &top->mp_page);
3192 mdb_midl_insert(txn->mt_free_pgs, mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi].md_root);
3197 if (data && (rc = mdb_read_data(txn, leaf, data)) != MDB_SUCCESS)
3200 return mdb_del0(txn, dbi, ki, &mpp, leaf);
3203 /* Split page <*mpp>, and insert <key,(data|newpgno)> in either left or
3204 * right sibling, at index <*newindxp> (as if unsplit). Updates *mpp and
3205 * *newindxp with the actual values after split, ie if *mpp and *newindxp
3206 * refer to a node in the new right sibling page.
3209 mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp, unsigned int *newindxp,
3210 MDB_val *newkey, MDB_val *newdata, pgno_t newpgno)
3213 int rc = MDB_SUCCESS, ins_new = 0;
3216 unsigned int i, j, split_indx;
3218 MDB_val sepkey, rkey, rdata;
3220 MDB_dpage *mdp, *rdp, *pdp;
3224 assert(txn != NULL);
3226 dh = ((MDB_dhead *)*mpp) - 1;
3227 mdp = (MDB_dpage *)dh;
3228 newindx = *newindxp;
3230 DPRINTF("-----> splitting %s page %lu and adding [%s] at index %i",
3231 IS_LEAF(&mdp->p) ? "leaf" : "branch", mdp->p.mp_pgno,
3232 DKEY(newkey), *newindxp);
3234 if (mdp->h.md_parent == NULL) {
3235 if ((pdp = mdb_new_page(txn, dbi, P_BRANCH, 1)) == NULL)
3238 mdp->h.md_parent = &pdp->p;
3239 txn->mt_dbs[dbi].md_root = pdp->p.mp_pgno;
3240 DPRINTF("root split! new root = %lu", pdp->p.mp_pgno);
3241 txn->mt_dbs[dbi].md_depth++;
3243 /* Add left (implicit) pointer. */
3244 if ((rc = mdb_add_node(txn, dbi, &pdp->p, 0, NULL, NULL,
3245 mdp->p.mp_pgno, 0)) != MDB_SUCCESS)
3248 DPRINTF("parent branch page is %lu", mdp->h.md_parent->mp_pgno);
3251 /* Create a right sibling. */
3252 if ((rdp = mdb_new_page(txn, dbi, mdp->p.mp_flags, 1)) == NULL)
3254 rdp->h.md_parent = mdp->h.md_parent;
3255 rdp->h.md_pi = mdp->h.md_pi + 1;
3256 DPRINTF("new right sibling: page %lu", rdp->p.mp_pgno);
3258 split_indx = NUMKEYS(&mdp->p) / 2 + 1;
3260 if (IS_LEAF2(&rdp->p)) {
3263 unsigned int nkeys = NUMKEYS(&mdp->p), lsize, rsize, ksize;
3264 /* Move half of the keys to the right sibling */
3266 x = *newindxp - split_indx;
3267 ksize = txn->mt_dbs[dbi].md_pad;
3268 split = LEAF2KEY(&mdp->p, split_indx, ksize);
3269 rsize = (nkeys - split_indx) * ksize;
3270 lsize = (nkeys - split_indx) * sizeof(indx_t);
3271 mdp->p.mp_lower -= lsize;
3272 rdp->p.mp_lower += lsize;
3273 mdp->p.mp_upper += rsize - lsize;
3274 rdp->p.mp_upper -= rsize - lsize;
3275 sepkey.mv_size = ksize;
3276 if (newindx == split_indx) {
3277 sepkey.mv_data = newkey->mv_data;
3279 sepkey.mv_data = split;
3282 ins = LEAF2KEY(&mdp->p, *newindxp, ksize);
3283 memcpy(&rdp->p.mp_ptrs, split, rsize);
3284 sepkey.mv_data = &rdp->p.mp_ptrs;
3285 memmove(ins+ksize, ins, (split_indx - *newindxp) * ksize);
3286 memcpy(ins, newkey->mv_data, ksize);
3287 mdp->p.mp_lower += sizeof(indx_t);
3288 mdp->p.mp_upper -= ksize - sizeof(indx_t);
3291 memcpy(&rdp->p.mp_ptrs, split, x * ksize);
3292 ins = LEAF2KEY(&rdp->p, x, ksize);
3293 memcpy(ins, newkey->mv_data, ksize);
3294 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
3295 rdp->p.mp_lower += sizeof(indx_t);
3296 rdp->p.mp_upper -= ksize - sizeof(indx_t);
3303 /* Move half of the keys to the right sibling. */
3304 if ((copy = malloc(txn->mt_env->me_psize)) == NULL)
3306 memcpy(copy, &mdp->p, txn->mt_env->me_psize);
3307 memset(&mdp->p.mp_ptrs, 0, txn->mt_env->me_psize - PAGEHDRSZ);
3308 mdp->p.mp_lower = PAGEHDRSZ;
3309 mdp->p.mp_upper = txn->mt_env->me_psize;
3311 /* First find the separating key between the split pages.
3313 memset(&sepkey, 0, sizeof(sepkey));
3314 if (newindx == split_indx) {
3315 sepkey.mv_size = newkey->mv_size;
3316 sepkey.mv_data = newkey->mv_data;
3318 node = NODEPTR(copy, split_indx);
3319 sepkey.mv_size = node->mn_ksize;
3320 sepkey.mv_data = NODEKEY(node);
3324 DPRINTF("separator is [%s]", DKEY(&sepkey));
3326 /* Copy separator key to the parent.
3328 if (SIZELEFT(rdp->h.md_parent) < mdb_branch_size(txn->mt_env, &sepkey)) {
3329 rc = mdb_split(txn, dbi, &rdp->h.md_parent, &rdp->h.md_pi,
3330 &sepkey, NULL, rdp->p.mp_pgno);
3332 /* Right page might now have changed parent.
3333 * Check if left page also changed parent.
3335 if (rdp->h.md_parent != mdp->h.md_parent &&
3336 mdp->h.md_pi >= NUMKEYS(mdp->h.md_parent)) {
3337 mdp->h.md_parent = rdp->h.md_parent;
3338 mdp->h.md_pi = rdp->h.md_pi - 1;
3341 rc = mdb_add_node(txn, dbi, rdp->h.md_parent, rdp->h.md_pi,
3342 &sepkey, NULL, rdp->p.mp_pgno, 0);
3344 if (IS_LEAF2(&rdp->p)) {
3347 if (rc != MDB_SUCCESS) {
3352 for (i = j = 0; i <= NUMKEYS(copy); j++) {
3353 if (i < split_indx) {
3354 /* Re-insert in left sibling. */
3357 /* Insert in right sibling. */
3358 if (i == split_indx)
3359 /* Reset insert index for right sibling. */
3360 j = (i == newindx && ins_new);
3364 if (i == newindx && !ins_new) {
3365 /* Insert the original entry that caused the split. */
3366 rkey.mv_data = newkey->mv_data;
3367 rkey.mv_size = newkey->mv_size;
3368 if (IS_LEAF(&mdp->p)) {
3369 rdata.mv_data = newdata->mv_data;
3370 rdata.mv_size = newdata->mv_size;
3377 /* Update page and index for the new key. */
3380 } else if (i == NUMKEYS(copy)) {
3383 node = NODEPTR(copy, i);
3384 rkey.mv_data = NODEKEY(node);
3385 rkey.mv_size = node->mn_ksize;
3386 if (IS_LEAF(&mdp->p)) {
3387 rdata.mv_data = NODEDATA(node);
3388 rdata.mv_size = node->mn_dsize;
3390 pgno = NODEPGNO(node);
3391 flags = node->mn_flags;
3396 if (!IS_LEAF(&mdp->p) && j == 0) {
3397 /* First branch index doesn't need key data. */
3401 rc = mdb_add_node(txn, dbi, &pdp->p, j, &rkey, &rdata, pgno,flags);
3409 mdb_put0(MDB_txn *txn, MDB_dbi dbi,
3410 MDB_val *key, MDB_val *data, unsigned int flags)
3412 int rc = MDB_SUCCESS, exact;
3416 MDB_val xdata, *rdata, dkey;
3418 char dbuf[PAGESIZE];
3423 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
3424 dbi, DKEY(key), key->mv_size, data->mv_size);
3427 mpp.mp_parent = NULL;
3429 rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp);
3430 if (rc == MDB_SUCCESS) {
3431 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
3432 if (leaf && exact) {
3433 if (flags == MDB_NOOVERWRITE) {
3434 DPRINTF("duplicate key [%s]", DKEY(key));
3435 return MDB_KEYEXIST;
3437 /* there's only a key anyway, so this is a no-op */
3438 if (IS_LEAF2(mpp.mp_page))
3441 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
3442 /* Was a single item before, must convert now */
3443 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3444 dkey.mv_size = NODEDSZ(leaf);
3445 dkey.mv_data = dbuf;
3446 memcpy(dbuf, NODEDATA(leaf), dkey.mv_size);
3447 /* data matches, ignore it */
3448 if (!mdb_dcmp(txn, dbi, data, &dkey))
3449 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
3450 memset(&dummy, 0, sizeof(dummy));
3451 if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED) {
3452 dummy.md_pad = data->mv_size;
3453 dummy.md_flags = MDB_DUPFIXED;
3454 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP)
3455 dummy.md_flags |= MDB_INTEGERKEY;
3457 dummy.md_root = P_INVALID;
3458 if (dkey.mv_size == sizeof(MDB_db)) {
3459 memcpy(NODEDATA(leaf), &dummy, sizeof(dummy));
3462 mdb_del_node(mpp.mp_page, ki, 0);
3465 xdata.mv_size = sizeof(MDB_db);
3466 xdata.mv_data = &dummy;
3471 /* same size, just replace it */
3472 if (!F_ISSET(leaf->mn_flags, F_BIGDATA) &&
3473 NODEDSZ(leaf) == data->mv_size) {
3474 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
3477 mdb_del_node(mpp.mp_page, ki, 0);
3479 if (leaf == NULL) { /* append if not found */
3480 ki = NUMKEYS(mpp.mp_page);
3481 DPRINTF("appending key at index %i", ki);
3483 } else if (rc == MDB_NOTFOUND) {
3485 /* new file, just write a root leaf page */
3486 DPUTS("allocating new root leaf page");
3487 if ((dp = mdb_new_page(txn, dbi, P_LEAF, 1)) == NULL) {
3490 mpp.mp_page = &dp->p;
3491 txn->mt_dbs[dbi].md_root = mpp.mp_page->mp_pgno;
3492 txn->mt_dbs[dbi].md_depth++;
3493 txn->mt_dbxs[dbi].md_dirty = 1;
3494 if ((txn->mt_dbs[dbi].md_flags & (MDB_DUPSORT|MDB_DUPFIXED)) == MDB_DUPFIXED)
3495 mpp.mp_page->mp_flags |= P_LEAF2;
3501 assert(IS_LEAF(mpp.mp_page));
3502 DPRINTF("there are %u keys, should insert new key at index %i",
3503 NUMKEYS(mpp.mp_page), ki);
3508 nsize = IS_LEAF2(mpp.mp_page) ? key->mv_size : mdb_leaf_size(txn->mt_env, key, rdata);
3509 if (SIZELEFT(mpp.mp_page) < nsize) {
3510 rc = mdb_split(txn, dbi, &mpp.mp_page, &ki, key, rdata, P_INVALID);
3512 /* There is room already in this leaf page. */
3513 rc = mdb_add_node(txn, dbi, mpp.mp_page, ki, key, rdata, 0, 0);
3516 if (rc != MDB_SUCCESS)
3517 txn->mt_flags |= MDB_TXN_ERROR;
3519 /* Remember if we just added a subdatabase */
3520 if (flags & F_SUBDATA) {
3521 leaf = NODEPTR(mpp.mp_page, ki);
3522 leaf->mn_flags |= F_SUBDATA;
3525 /* Now store the actual data in the child DB. Note that we're
3526 * storing the user data in the keys field, so there are strict
3527 * size limits on dupdata. The actual data fields of the child
3528 * DB are all zero size.
3533 leaf = NODEPTR(mpp.mp_page, ki);
3535 mdb_xcursor_init0(txn, dbi, &mx);
3536 mdb_xcursor_init1(txn, dbi, &mx, mpp.mp_page, leaf);
3539 if (flags == MDB_NODUPDATA)
3540 flags = MDB_NOOVERWRITE;
3541 /* converted, write the original data first */
3543 rc = mdb_put0(&mx.mx_txn, mx.mx_cursor.mc_dbi, &dkey, &xdata, flags);
3545 leaf->mn_flags |= F_DUPDATA;
3547 rc = mdb_put0(&mx.mx_txn, mx.mx_cursor.mc_dbi, data, &xdata, flags);
3548 mdb_xcursor_fini(txn, dbi, &mx);
3549 memcpy(NODEDATA(leaf), &mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi],
3552 txn->mt_dbs[dbi].md_entries++;
3560 mdb_put(MDB_txn *txn, MDB_dbi dbi,
3561 MDB_val *key, MDB_val *data, unsigned int flags)
3563 assert(key != NULL);
3564 assert(data != NULL);
3566 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3569 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3573 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3577 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA)) != flags)
3580 return mdb_put0(txn, dbi, key, data, flags);
3584 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
3586 #define CHANGEABLE (MDB_NOSYNC)
3587 if ((flag & CHANGEABLE) != flag)
3590 env->me_flags |= flag;
3592 env->me_flags &= ~flag;
3597 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
3602 *arg = env->me_flags;
3607 mdb_env_get_path(MDB_env *env, const char **arg)
3612 *arg = env->me_path;
3617 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
3619 arg->ms_psize = env->me_psize;
3620 arg->ms_depth = db->md_depth;
3621 arg->ms_branch_pages = db->md_branch_pages;
3622 arg->ms_leaf_pages = db->md_leaf_pages;
3623 arg->ms_overflow_pages = db->md_overflow_pages;
3624 arg->ms_entries = db->md_entries;
3629 mdb_env_stat(MDB_env *env, MDB_stat *arg)
3631 if (env == NULL || arg == NULL)
3634 return mdb_stat0(env, &env->me_meta->mm_dbs[MAIN_DBI], arg);
3637 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
3647 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
3648 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
3652 /* Is the DB already open? */
3654 for (i=2; i<txn->mt_numdbs; i++) {
3655 if (len == txn->mt_dbxs[i].md_name.mv_size &&
3656 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
3662 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
3665 /* Find the DB info */
3667 key.mv_data = (void *)name;
3668 rc = mdb_get(txn, MAIN_DBI, &key, &data);
3670 /* Create if requested */
3671 if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
3673 data.mv_size = sizeof(MDB_db);
3674 data.mv_data = &dummy;
3675 memset(&dummy, 0, sizeof(dummy));
3676 dummy.md_root = P_INVALID;
3677 dummy.md_flags = flags & 0xffff;
3678 rc = mdb_put0(txn, MAIN_DBI, &key, &data, F_SUBDATA);
3682 /* OK, got info, add to table */
3683 if (rc == MDB_SUCCESS) {
3684 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
3685 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
3686 txn->mt_dbxs[txn->mt_numdbs].md_cmp = NULL;
3687 txn->mt_dbxs[txn->mt_numdbs].md_dcmp = NULL;
3688 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
3689 txn->mt_dbxs[txn->mt_numdbs].md_parent = MAIN_DBI;
3690 txn->mt_dbxs[txn->mt_numdbs].md_dirty = dirty;
3691 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
3692 *dbi = txn->mt_numdbs;
3693 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
3694 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
3701 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
3703 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
3706 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
3709 void mdb_close(MDB_txn *txn, MDB_dbi dbi)
3712 if (dbi <= MAIN_DBI || dbi >= txn->mt_numdbs)
3714 ptr = txn->mt_dbxs[dbi].md_name.mv_data;
3715 txn->mt_dbxs[dbi].md_name.mv_data = NULL;
3716 txn->mt_dbxs[dbi].md_name.mv_size = 0;
3720 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
3722 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3725 txn->mt_dbxs[dbi].md_cmp = cmp;
3729 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
3731 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3734 txn->mt_dbxs[dbi].md_dcmp = cmp;
3738 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
3740 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3743 txn->mt_dbxs[dbi].md_rel = rel;