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 /* The DB view is always consistent because all writes are wrapped in
95 * the wmutex. Finer-grained locks aren't necessary.
101 #define LAZY_MUTEX_LOCK(x)
102 #define LAZY_MUTEX_UNLOCK(x)
103 #define LAZY_RWLOCK_UNLOCK(x)
104 #define LAZY_RWLOCK_WRLOCK(x)
105 #define LAZY_RWLOCK_RDLOCK(x)
106 #define LAZY_RWLOCK_DEF(x)
107 #define LAZY_RWLOCK_INIT(x,y)
108 #define LAZY_RWLOCK_DESTROY(x)
110 #define LAZY_MUTEX_LOCK(x) pthread_mutex_lock(x)
111 #define LAZY_MUTEX_UNLOCK(x) pthread_mutex_unlock(x)
112 #define LAZY_RWLOCK_UNLOCK(x) pthread_rwlock_unlock(x)
113 #define LAZY_RWLOCK_WRLOCK(x) pthread_rwlock_wrlock(x)
114 #define LAZY_RWLOCK_RDLOCK(x) pthread_rwlock_rdlock(x)
115 #define LAZY_RWLOCK_DEF(x) pthread_rwlock_t x
116 #define LAZY_RWLOCK_INIT(x,y) pthread_rwlock_init(x,y)
117 #define LAZY_RWLOCK_DESTROY(x) pthread_rwlock_destroy(x)
120 #define P_INVALID (~0UL)
122 #define F_ISSET(w, f) (((w) & (f)) == (f))
124 typedef uint16_t indx_t;
126 #define DEFAULT_READERS 126
127 #define DEFAULT_MAPSIZE 1048576
129 /* Lock descriptor stuff */
131 #define CACHELINE 64 /* most CPUs. Itanium uses 128 */
134 typedef struct MDB_rxbody {
140 typedef struct MDB_reader {
143 #define mr_txnid mru.mrx.mrb_txnid
144 #define mr_pid mru.mrx.mrb_pid
145 #define mr_tid mru.mrx.mrb_tid
146 /* cache line alignment */
147 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
151 typedef struct MDB_txbody {
153 uint32_t mtb_version;
154 pthread_mutex_t mtb_mutex;
156 uint32_t mtb_numreaders;
157 uint32_t mtb_me_toggle;
160 typedef struct MDB_txninfo {
163 #define mti_magic mt1.mtb.mtb_magic
164 #define mti_version mt1.mtb.mtb_version
165 #define mti_mutex mt1.mtb.mtb_mutex
166 #define mti_txnid mt1.mtb.mtb_txnid
167 #define mti_numreaders mt1.mtb.mtb_numreaders
168 #define mti_me_toggle mt1.mtb.mtb_me_toggle
169 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
172 pthread_mutex_t mt2_wmutex;
173 #define mti_wmutex mt2.mt2_wmutex
174 char pad[(sizeof(pthread_mutex_t)+CACHELINE-1) & ~(CACHELINE-1)];
176 MDB_reader mti_readers[1];
179 /* Common header for all page types. Overflow pages
180 * occupy a number of contiguous pages with no
181 * headers on any page after the first.
183 typedef struct MDB_page { /* represents a page of storage */
184 #define mp_pgno mp_p.p_pgno
186 pgno_t p_pgno; /* page number */
187 void * p_align; /* for IL32P64 */
189 #define P_BRANCH 0x01 /* branch page */
190 #define P_LEAF 0x02 /* leaf page */
191 #define P_OVERFLOW 0x04 /* overflow page */
192 #define P_META 0x08 /* meta page */
193 #define P_DIRTY 0x10 /* dirty page */
194 #define P_LEAF2 0x20 /* DB with small, fixed size keys and no data */
196 #define mp_lower mp_pb.pb.pb_lower
197 #define mp_upper mp_pb.pb.pb_upper
198 #define mp_pages mp_pb.pb_pages
201 indx_t pb_lower; /* lower bound of free space */
202 indx_t pb_upper; /* upper bound of free space */
204 uint32_t pb_pages; /* number of overflow pages */
206 indx_t mp_ptrs[1]; /* dynamic size */
209 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
211 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
212 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
213 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
214 ((env)->me_psize - PAGEHDRSZ))
215 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
216 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
217 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
218 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
220 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
222 typedef struct MDB_db {
223 uint32_t md_pad; /* also ksize for LEAF2 pages */
226 ULONG md_branch_pages;
228 ULONG md_overflow_pages;
236 typedef struct MDB_meta { /* meta (footer) page content */
239 void *mm_address; /* address for fixed mapping */
240 size_t mm_mapsize; /* size of mmap region */
241 MDB_db mm_dbs[2]; /* first is free space, 2nd is main db */
242 #define mm_psize mm_dbs[0].md_pad
243 #define mm_flags mm_dbs[0].md_flags
244 pgno_t mm_last_pg; /* last used page in file */
245 ULONG mm_txnid; /* txnid that committed this page */
248 typedef struct MDB_dhead { /* a dirty page */
250 unsigned md_pi; /* parent index */
254 typedef struct MDB_dpage {
259 typedef struct MDB_oldpages {
260 struct MDB_oldpages *mo_next;
262 pgno_t mo_pages[1]; /* dynamic */
265 typedef struct MDB_pageparent {
271 static MDB_dpage *mdb_alloc_page(MDB_txn *txn, MDB_page *parent, unsigned int parent_idx, int num);
272 static int mdb_touch(MDB_txn *txn, MDB_pageparent *mp);
274 typedef struct MDB_ppage { /* ordered list of pages */
276 unsigned int mp_ki; /* cursor index on page */
279 #define CURSOR_TOP(c) (&(c)->mc_stack[(c)->mc_snum-1])
280 #define CURSOR_PARENT(c) (&(c)->mc_stack[(c)->mc_snum-2])
281 #define CURSOR_STACK 32
287 MDB_ppage mc_stack[CURSOR_STACK]; /* stack of parent pages */
288 unsigned int mc_snum; /* number of pushed pages */
290 short mc_initialized; /* 1 if initialized */
291 short mc_eof; /* 1 if end is reached */
292 struct MDB_xcursor *mc_xcursor;
295 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
297 typedef struct MDB_node {
298 #define mn_pgno mn_p.np_pgno
299 #define mn_dsize mn_p.np_dsize
301 pgno_t np_pgno; /* child page number */
302 uint32_t np_dsize; /* leaf data size */
304 unsigned int mn_flags:4;
305 unsigned int mn_ksize:12; /* key size */
306 #define F_BIGDATA 0x01 /* data put on overflow page */
307 #define F_SUBDATA 0x02 /* data is a sub-database */
308 #define F_DUPDATA 0x04 /* data has duplicates */
312 typedef struct MDB_dbx {
314 MDB_cmp_func *md_cmp; /* user compare function */
315 MDB_cmp_func *md_dcmp; /* user dupsort function */
316 MDB_rel_func *md_rel; /* user relocate function */
318 unsigned int md_dirty;
322 pgno_t mt_next_pgno; /* next unallocated page */
326 pgno_t *mt_free_pgs; /* this is an IDL */
328 MIDL2 *dirty_list; /* modified pages */
331 MDB_dbx *mt_dbxs; /* array */
333 unsigned int mt_numdbs;
335 #define MDB_TXN_RDONLY 0x01 /* read-only transaction */
336 #define MDB_TXN_ERROR 0x02 /* an error has occurred */
337 unsigned int mt_flags;
338 unsigned int mt_toggle;
341 /* Context for sorted-dup records */
342 typedef struct MDB_xcursor {
343 MDB_cursor mx_cursor;
352 int me_mfd; /* just for writing the meta pages */
353 #define MDB_FATAL_ERROR 0x80000000U
355 uint32_t me_extrapad; /* unused for now */
356 unsigned int me_maxreaders;
357 unsigned int me_numdbs;
358 unsigned int me_maxdbs;
361 MDB_txninfo *me_txns;
362 MDB_meta *me_metas[2];
363 MDB_txn *me_txn; /* current write transaction */
365 off_t me_size; /* current file size */
366 pgno_t me_maxpg; /* me_mapsize / me_psize */
367 unsigned int me_psize;
368 unsigned int me_db_toggle;
369 MDB_dbx *me_dbxs; /* array */
371 MDB_oldpages *me_pghead;
372 pthread_key_t me_txkey; /* thread-key for readers */
373 MDB_dpage *me_dpages;
374 pgno_t me_free_pgs[MDB_IDL_UM_SIZE];
375 MIDL2 me_dirty_list[MDB_IDL_DB_SIZE];
376 LAZY_RWLOCK_DEF(me_dblock);
379 #define NODESIZE offsetof(MDB_node, mn_data)
381 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
382 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
383 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
384 #define NODEKEY(node) (void *)((node)->mn_data)
385 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
386 #define NODEPGNO(node) ((node)->mn_pgno)
387 #define NODEDSZ(node) ((node)->mn_dsize)
388 #define NODEKSZ(node) ((node)->mn_ksize)
389 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
391 #define MDB_SET_KEY(node, key) if (key!=NULL) {(key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node);}
393 #define MDB_COMMIT_PAGES 64 /* max number of pages to write in one commit */
395 static int mdb_search_page_root(MDB_txn *txn,
396 MDB_dbi dbi, MDB_val *key,
397 MDB_cursor *cursor, int modify,
398 MDB_pageparent *mpp);
399 static int mdb_search_page(MDB_txn *txn,
400 MDB_dbi dbi, MDB_val *key,
401 MDB_cursor *cursor, int modify,
402 MDB_pageparent *mpp);
404 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
405 static int mdb_env_read_meta(MDB_env *env, int *which);
406 static int mdb_env_write_meta(MDB_txn *txn);
407 static int mdb_get_page(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
409 static MDB_node *mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp,
410 MDB_val *key, int *exactp, unsigned int *kip);
411 static int mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp,
412 indx_t indx, MDB_val *key, MDB_val *data,
413 pgno_t pgno, uint8_t flags);
414 static void mdb_del_node(MDB_page *mp, indx_t indx, int ksize);
415 static int mdb_del0(MDB_txn *txn, MDB_dbi dbi, unsigned int ki,
416 MDB_pageparent *mpp, MDB_node *leaf);
417 static int mdb_put0(MDB_txn *txn, MDB_dbi dbi,
418 MDB_val *key, MDB_val *data, unsigned int flags);
419 static int mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
421 static int mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mp);
422 static int mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
423 static int mdb_move_node(MDB_txn *txn, MDB_dbi dbi,
424 MDB_pageparent *src, indx_t srcindx,
425 MDB_pageparent *dst, indx_t dstindx);
426 static int mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src,
427 MDB_pageparent *dst);
428 static int mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp,
429 unsigned int *newindxp, MDB_val *newkey,
430 MDB_val *newdata, pgno_t newpgno);
431 static MDB_dpage *mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num);
433 static void cursor_pop_page(MDB_cursor *cursor);
434 static MDB_ppage *cursor_push_page(MDB_cursor *cursor,
437 static int mdb_sibling(MDB_cursor *cursor, int move_right);
438 static int mdb_cursor_next(MDB_cursor *cursor,
439 MDB_val *key, MDB_val *data, MDB_cursor_op op);
440 static int mdb_cursor_prev(MDB_cursor *cursor,
441 MDB_val *key, MDB_val *data, MDB_cursor_op op);
442 static int mdb_cursor_set(MDB_cursor *cursor,
443 MDB_val *key, MDB_val *data, MDB_cursor_op op, int *exactp);
444 static int mdb_cursor_first(MDB_cursor *cursor,
445 MDB_val *key, MDB_val *data);
446 static int mdb_cursor_last(MDB_cursor *cursor,
447 MDB_val *key, MDB_val *data);
449 static void mdb_xcursor_init0(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
450 static void mdb_xcursor_init1(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx,
451 MDB_page *mp, MDB_node *node);
452 static void mdb_xcursor_fini(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx);
454 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key,
456 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
458 static int memncmp(const void *s1, size_t n1,
459 const void *s2, size_t n2);
460 static int memnrcmp(const void *s1, size_t n1,
461 const void *s2, size_t n2);
464 memncmp(const void *s1, size_t n1, const void *s2, size_t n2)
466 int diff, len_diff = -1;
469 len_diff = (n1 > n2);
472 diff = memcmp(s1, s2, n1);
473 return diff ? diff : len_diff;
477 memnrcmp(const void *s1, size_t n1, const void *s2, size_t n2)
479 const unsigned char *p1, *p2, *p1_lim;
486 p1 = (const unsigned char *)s1 + n1 - 1;
487 p2 = (const unsigned char *)s2 + n2 - 1;
489 for (p1_lim = (n1 <= n2 ? s1 : s2); *p1 == *p2; p1--, p2--) {
491 return (p1 != s1) ? (p1 != p2) : (p2 != s2) ? -1 : 0;
497 mdb_version(int *maj, int *min, int *pat)
499 *maj = MDB_VERSION_MAJOR;
500 *min = MDB_VERSION_MINOR;
501 *pat = MDB_VERSION_PATCH;
502 return MDB_VERSION_STRING;
505 static char *const errstr[] = {
506 "MDB_KEYEXIST: Key/data pair already exists",
507 "MDB_NOTFOUND: No matching key/data pair found",
508 "MDB_PAGE_NOTFOUND: Requested page not found",
509 "MDB_CORRUPTED: Located page was wrong type",
510 "MDB_PANIC: Update of meta page failed",
511 "MDB_VERSION_MISMATCH: Database environment version mismatch"
515 mdb_strerror(int err)
518 return ("Successful return: 0");
520 if (err >= MDB_KEYEXIST && err <= MDB_VERSION_MISMATCH)
521 return errstr[err - MDB_KEYEXIST];
523 return strerror(err);
527 mdb_dkey(MDB_val *key, char *buf)
530 unsigned char *c = key->mv_data;
532 if (key->mv_size > MAXKEYSIZE)
534 for (i=0; i<key->mv_size; i++)
535 ptr += sprintf(ptr, "%02x", *c++);
540 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
542 if (txn->mt_dbxs[dbi].md_cmp)
543 return txn->mt_dbxs[dbi].md_cmp(a, b);
545 if (txn->mt_dbs[dbi].md_flags & (MDB_REVERSEKEY
546 #if __BYTE_ORDER == __LITTLE_ENDIAN
550 return memnrcmp(a->mv_data, a->mv_size, b->mv_data, b->mv_size);
552 return memncmp((char *)a->mv_data, a->mv_size, b->mv_data, b->mv_size);
556 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
558 if (txn->mt_dbxs[dbi].md_dcmp)
559 return txn->mt_dbxs[dbi].md_dcmp(a, b);
561 if (txn->mt_dbs[dbi].md_flags & (0
562 #if __BYTE_ORDER == __LITTLE_ENDIAN
566 return memnrcmp(a->mv_data, a->mv_size, b->mv_data, b->mv_size);
568 return memncmp((char *)a->mv_data, a->mv_size, b->mv_data, b->mv_size);
571 /* Allocate new page(s) for writing */
573 mdb_alloc_page(MDB_txn *txn, MDB_page *parent, unsigned int parent_idx, int num)
576 pgno_t pgno = P_INVALID;
580 if (txn->mt_txnid > 2) {
582 oldest = txn->mt_txnid - 1;
583 if (!txn->mt_env->me_pghead && txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
584 /* See if there's anything in the free DB */
589 mpp.mp_parent = NULL;
591 mdb_search_page(txn, FREE_DBI, NULL, NULL, 0, &mpp);
592 leaf = NODEPTR(mpp.mp_page, 0);
593 kptr = (ULONG *)NODEKEY(leaf);
595 /* It's potentially usable, unless there are still
596 * older readers outstanding. Grab it.
598 if (oldest > *kptr) {
603 mdb_read_data(txn, leaf, &data);
604 idl = (ULONG *)data.mv_data;
605 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
606 mop->mo_next = txn->mt_env->me_pghead;
607 mop->mo_txnid = *kptr;
608 txn->mt_env->me_pghead = mop;
609 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
614 DPRINTF("IDL read txn %lu root %lu num %lu",
615 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
616 for (i=0; i<idl[0]; i++) {
617 DPRINTF("IDL %lu", idl[i+1]);
621 /* drop this IDL from the DB */
622 mpp.mp_parent = NULL;
624 mdb_search_page(txn, FREE_DBI, NULL, NULL, 1, &mpp);
625 leaf = NODEPTR(mpp.mp_page, 0);
626 mdb_del0(txn, FREE_DBI, 0, &mpp, leaf);
629 if (txn->mt_env->me_pghead) {
631 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
632 ULONG mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
635 oldest = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
637 if (oldest > txn->mt_env->me_pghead->mo_txnid) {
638 MDB_oldpages *mop = txn->mt_env->me_pghead;
639 txn->mt_oldest = oldest;
641 /* FIXME: For now, always use fresh pages. We
642 * really ought to search the free list for a
647 /* peel pages off tail, so we only have to truncate the list */
648 pgno = MDB_IDL_LAST(mop->mo_pages);
649 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
651 if (mop->mo_pages[2] > mop->mo_pages[1])
652 mop->mo_pages[0] = 0;
656 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
657 txn->mt_env->me_pghead = mop->mo_next;
665 if (pgno == P_INVALID) {
666 /* DB size is maxed out */
667 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg)
670 if (txn->mt_env->me_dpages && num == 1) {
671 dp = txn->mt_env->me_dpages;
672 txn->mt_env->me_dpages = (MDB_dpage *)dp->h.md_parent;
674 if ((dp = malloc(txn->mt_env->me_psize * num + sizeof(MDB_dhead))) == NULL)
678 dp->h.md_parent = parent;
679 dp->h.md_pi = parent_idx;
680 if (pgno == P_INVALID) {
681 dp->p.mp_pgno = txn->mt_next_pgno;
682 txn->mt_next_pgno += num;
684 dp->p.mp_pgno = pgno;
686 mid.mid = dp->p.mp_pgno;
688 mdb_midl2_insert(txn->mt_u.dirty_list, &mid);
693 /* Touch a page: make it dirty and re-insert into tree with updated pgno.
696 mdb_touch(MDB_txn *txn, MDB_pageparent *pp)
698 MDB_page *mp = pp->mp_page;
703 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
705 if ((dp = mdb_alloc_page(txn, pp->mp_parent, pp->mp_pi, 1)) == NULL)
707 DPRINTF("touched page %lu -> %lu", mp->mp_pgno, dp->p.mp_pgno);
708 assert(mp->mp_pgno != dp->p.mp_pgno);
709 mdb_midl_insert(txn->mt_free_pgs, mp->mp_pgno);
710 pgno = dp->p.mp_pgno;
711 memcpy(&dp->p, mp, txn->mt_env->me_psize);
714 mp->mp_flags |= P_DIRTY;
716 /* Update the page number to new touched page. */
717 if (pp->mp_parent != NULL)
718 NODEPGNO(NODEPTR(pp->mp_parent, pp->mp_pi)) = mp->mp_pgno;
725 mdb_env_sync(MDB_env *env, int force)
728 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
729 if (fdatasync(env->me_fd))
736 mdb_txn_reset0(MDB_txn *txn);
739 mdb_txn_renew0(MDB_txn *txn)
741 MDB_env *env = txn->mt_env;
743 if (env->me_flags & MDB_FATAL_ERROR) {
744 DPUTS("mdb_txn_begin: environment had fatal error, must shutdown!");
748 if (txn->mt_flags & MDB_TXN_RDONLY) {
749 MDB_reader *r = pthread_getspecific(env->me_txkey);
752 pid_t pid = getpid();
753 pthread_t tid = pthread_self();
755 pthread_mutex_lock(&env->me_txns->mti_mutex);
756 for (i=0; i<env->me_txns->mti_numreaders; i++)
757 if (env->me_txns->mti_readers[i].mr_pid == 0)
759 if (i == env->me_maxreaders) {
760 pthread_mutex_unlock(&env->me_txns->mti_mutex);
763 env->me_txns->mti_readers[i].mr_pid = pid;
764 env->me_txns->mti_readers[i].mr_tid = tid;
765 if (i >= env->me_txns->mti_numreaders)
766 env->me_txns->mti_numreaders = i+1;
767 pthread_mutex_unlock(&env->me_txns->mti_mutex);
768 r = &env->me_txns->mti_readers[i];
769 pthread_setspecific(env->me_txkey, r);
771 txn->mt_txnid = env->me_txns->mti_txnid;
772 txn->mt_toggle = env->me_txns->mti_me_toggle;
773 r->mr_txnid = txn->mt_txnid;
774 txn->mt_u.reader = r;
776 pthread_mutex_lock(&env->me_txns->mti_wmutex);
778 txn->mt_txnid = env->me_txns->mti_txnid+1;
779 txn->mt_toggle = env->me_txns->mti_me_toggle;
780 txn->mt_u.dirty_list = env->me_dirty_list;
781 txn->mt_u.dirty_list[0].mid = 0;
782 txn->mt_free_pgs = env->me_free_pgs;
783 txn->mt_free_pgs[0] = 0;
784 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
788 /* Copy the DB arrays */
789 LAZY_RWLOCK_RDLOCK(&env->me_dblock);
790 txn->mt_numdbs = env->me_numdbs;
791 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
792 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
793 if (txn->mt_numdbs > 2)
794 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
795 (txn->mt_numdbs - 2) * sizeof(MDB_db));
796 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
798 DPRINTF("begin txn %p %lu%c on mdbenv %p, root page %lu", txn,
799 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
800 (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
806 mdb_txn_renew(MDB_txn *txn)
813 rc = mdb_txn_renew0(txn);
814 if (rc == MDB_SUCCESS) {
815 DPRINTF("reset txn %p %lu%c on mdbenv %p, root page %lu", txn,
816 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
817 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
823 mdb_txn_begin(MDB_env *env, int rdonly, MDB_txn **ret)
828 if (env->me_flags & MDB_FATAL_ERROR) {
829 DPUTS("mdb_txn_begin: environment had fatal error, must shutdown!");
832 if ((txn = calloc(1, sizeof(MDB_txn) + env->me_maxdbs * sizeof(MDB_db))) == NULL) {
833 DPRINTF("calloc: %s", strerror(errno));
836 txn->mt_dbs = (MDB_db *)(txn+1);
838 txn->mt_flags |= MDB_TXN_RDONLY;
842 rc = mdb_txn_renew0(txn);
847 DPRINTF("begin txn %p %lu%c on mdbenv %p, root page %lu", txn,
848 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
849 (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
856 mdb_txn_reset0(MDB_txn *txn)
858 MDB_env *env = txn->mt_env;
860 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
861 txn->mt_u.reader->mr_txnid = 0;
867 /* return all dirty pages to dpage list */
868 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
869 dp = txn->mt_u.dirty_list[i].mptr;
870 if (dp->h.md_num == 1) {
871 dp->h.md_parent = (MDB_page *)txn->mt_env->me_dpages;
872 txn->mt_env->me_dpages = dp;
874 /* large pages just get freed directly */
879 while ((mop = txn->mt_env->me_pghead)) {
880 txn->mt_env->me_pghead = mop->mo_next;
885 for (i=2; i<env->me_numdbs; i++)
886 env->me_dbxs[i].md_dirty = 0;
887 pthread_mutex_unlock(&env->me_txns->mti_wmutex);
892 mdb_txn_reset(MDB_txn *txn)
897 DPRINTF("reset txn %p %lu%c on mdbenv %p, root page %lu", txn,
898 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
899 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
905 mdb_txn_abort(MDB_txn *txn)
910 DPRINTF("abort txn %p %lu%c on mdbenv %p, root page %lu", txn,
911 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w',
912 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
919 mdb_txn_commit(MDB_txn *txn)
928 struct iovec iov[MDB_COMMIT_PAGES];
931 assert(txn->mt_env != NULL);
935 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
940 if (txn != env->me_txn) {
941 DPUTS("attempt to commit unknown transaction");
946 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
947 DPUTS("error flag is set, can't commit");
952 if (!txn->mt_u.dirty_list[0].mid)
955 DPRINTF("committing txn %p %lu on mdbenv %p, root page %lu", txn,
956 txn->mt_txnid, (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
958 /* should only be one record now */
959 if (env->me_pghead) {
963 mop = env->me_pghead;
964 key.mv_size = sizeof(pgno_t);
965 key.mv_data = (char *)&mop->mo_txnid;
966 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
967 data.mv_data = mop->mo_pages;
968 mdb_put0(txn, FREE_DBI, &key, &data, 0);
969 free(env->me_pghead);
970 env->me_pghead = NULL;
972 /* save to free list */
973 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
977 /* make sure last page of freeDB is touched and on freelist */
978 key.mv_size = MAXKEYSIZE+1;
980 mpp.mp_parent = NULL;
982 mdb_search_page(txn, FREE_DBI, &key, NULL, 1, &mpp);
987 ULONG *idl = txn->mt_free_pgs;
988 DPRINTF("IDL write txn %lu root %lu num %lu",
989 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
990 for (i=0; i<idl[0]; i++) {
991 DPRINTF("IDL %lu", idl[i+1]);
995 /* write to last page of freeDB */
996 key.mv_size = sizeof(pgno_t);
997 key.mv_data = (char *)&txn->mt_txnid;
998 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
999 data.mv_data = txn->mt_free_pgs;
1000 mdb_put0(txn, FREE_DBI, &key, &data, 0);
1003 /* Update DB root pointers. Their pages have already been
1004 * touched so this is all in-place and cannot fail.
1008 data.mv_size = sizeof(MDB_db);
1010 for (i = 2; i < txn->mt_numdbs; i++) {
1011 if (txn->mt_dbxs[i].md_dirty) {
1012 data.mv_data = &txn->mt_dbs[i];
1013 mdb_put0(txn, MAIN_DBI, &txn->mt_dbxs[i].md_name, &data, 0);
1018 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
1026 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1027 dp = txn->mt_u.dirty_list[i].mptr;
1028 if (dp->p.mp_pgno != next) {
1030 DPRINTF("committing %u dirty pages", n);
1031 rc = writev(env->me_fd, iov, n);
1035 DPUTS("short write, filesystem full?");
1037 DPRINTF("writev: %s", strerror(errno));
1044 lseek(env->me_fd, dp->p.mp_pgno * env->me_psize, SEEK_SET);
1045 next = dp->p.mp_pgno;
1047 DPRINTF("committing page %lu", dp->p.mp_pgno);
1048 iov[n].iov_len = env->me_psize * dp->h.md_num;
1049 iov[n].iov_base = &dp->p;
1050 size += iov[n].iov_len;
1051 next = dp->p.mp_pgno + dp->h.md_num;
1052 /* clear dirty flag */
1053 dp->p.mp_flags &= ~P_DIRTY;
1054 if (++n >= MDB_COMMIT_PAGES) {
1064 DPRINTF("committing %u dirty pages", n);
1065 rc = writev(env->me_fd, iov, n);
1069 DPUTS("short write, filesystem full?");
1071 DPRINTF("writev: %s", strerror(errno));
1078 /* Drop the dirty pages.
1080 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1081 dp = txn->mt_u.dirty_list[i].mptr;
1082 if (dp->h.md_num == 1) {
1083 dp->h.md_parent = (MDB_page *)txn->mt_env->me_dpages;
1084 txn->mt_env->me_dpages = dp;
1088 txn->mt_u.dirty_list[i].mid = 0;
1090 txn->mt_u.dirty_list[0].mid = 0;
1092 if ((n = mdb_env_sync(env, 0)) != 0 ||
1093 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
1100 /* update the DB tables */
1102 int toggle = !env->me_db_toggle;
1105 ip = &env->me_dbs[toggle][2];
1106 jp = &txn->mt_dbs[2];
1107 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1108 for (i = 2; i < txn->mt_numdbs; i++) {
1109 if (ip->md_root != jp->md_root)
1114 for (i = 2; i < txn->mt_numdbs; i++) {
1115 if (txn->mt_dbxs[i].md_dirty)
1116 txn->mt_dbxs[i].md_dirty = 0;
1118 env->me_db_toggle = toggle;
1119 env->me_numdbs = txn->mt_numdbs;
1120 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1123 pthread_mutex_unlock(&env->me_txns->mti_wmutex);
1130 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
1132 char page[PAGESIZE];
1137 assert(env != NULL);
1139 /* We don't know the page size yet, so use a minimum value.
1142 if ((rc = pread(env->me_fd, page, PAGESIZE, 0)) == 0) {
1144 } else if (rc != PAGESIZE) {
1147 DPRINTF("read: %s", strerror(errno));
1151 p = (MDB_page *)page;
1153 if (!F_ISSET(p->mp_flags, P_META)) {
1154 DPRINTF("page %lu not a meta page", p->mp_pgno);
1159 if (m->mm_magic != MDB_MAGIC) {
1160 DPUTS("meta has invalid magic");
1164 if (m->mm_version != MDB_VERSION) {
1165 DPRINTF("database is version %u, expected version %u",
1166 m->mm_version, MDB_VERSION);
1167 return MDB_VERSION_MISMATCH;
1170 memcpy(meta, m, sizeof(*m));
1175 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
1182 DPUTS("writing new meta page");
1183 psize = sysconf(_SC_PAGE_SIZE);
1185 meta->mm_magic = MDB_MAGIC;
1186 meta->mm_version = MDB_VERSION;
1187 meta->mm_psize = psize;
1188 meta->mm_last_pg = 1;
1189 meta->mm_flags = env->me_flags & 0xffff;
1190 meta->mm_flags |= MDB_INTEGERKEY;
1191 meta->mm_dbs[0].md_root = P_INVALID;
1192 meta->mm_dbs[1].md_root = P_INVALID;
1194 p = calloc(2, psize);
1196 p->mp_flags = P_META;
1199 memcpy(m, meta, sizeof(*meta));
1201 q = (MDB_page *)((char *)p + psize);
1204 q->mp_flags = P_META;
1207 memcpy(m, meta, sizeof(*meta));
1209 rc = write(env->me_fd, p, psize * 2);
1211 return (rc == (int)psize * 2) ? MDB_SUCCESS : errno;
1215 mdb_env_write_meta(MDB_txn *txn)
1218 MDB_meta meta, metab;
1220 int rc, len, toggle;
1223 assert(txn != NULL);
1224 assert(txn->mt_env != NULL);
1226 toggle = !txn->mt_toggle;
1227 DPRINTF("writing meta page %d for root page %lu",
1228 toggle, txn->mt_dbs[MAIN_DBI].md_root);
1232 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
1233 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
1235 ptr = (char *)&meta;
1236 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
1237 len = sizeof(MDB_meta) - off;
1240 meta.mm_dbs[0] = txn->mt_dbs[0];
1241 meta.mm_dbs[1] = txn->mt_dbs[1];
1242 meta.mm_last_pg = txn->mt_next_pgno - 1;
1243 meta.mm_txnid = txn->mt_txnid;
1246 off += env->me_psize;
1249 /* Write to the SYNC fd */
1250 rc = pwrite(env->me_mfd, ptr, len, off);
1254 DPUTS("write failed, disk error?");
1255 /* On a failure, the pagecache still contains the new data.
1256 * Write some old data back, to prevent it from being used.
1257 * Use the non-SYNC fd; we know it will fail anyway.
1259 meta.mm_last_pg = metab.mm_last_pg;
1260 meta.mm_txnid = metab.mm_txnid;
1261 r2 = pwrite(env->me_fd, ptr, len, off);
1262 env->me_flags |= MDB_FATAL_ERROR;
1265 /* Memory ordering issues are irrelevant; since the entire writer
1266 * is wrapped by wmutex, all of these changes will become visible
1267 * after the wmutex is unlocked. Since the DB is multi-version,
1268 * readers will get consistent data regardless of how fresh or
1269 * how stale their view of these values is.
1271 LAZY_MUTEX_LOCK(&env->me_txns->mti_mutex);
1272 txn->mt_env->me_txns->mti_me_toggle = toggle;
1273 txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
1274 LAZY_MUTEX_UNLOCK(&env->me_txns->mti_mutex);
1280 mdb_env_read_meta(MDB_env *env, int *which)
1284 assert(env != NULL);
1286 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1289 DPRINTF("Using meta page %d", toggle);
1296 mdb_env_create(MDB_env **env)
1300 e = calloc(1, sizeof(MDB_env));
1301 if (!e) return ENOMEM;
1303 e->me_maxreaders = DEFAULT_READERS;
1313 mdb_env_set_mapsize(MDB_env *env, size_t size)
1317 env->me_mapsize = size;
1322 mdb_env_set_maxdbs(MDB_env *env, int dbs)
1324 env->me_maxdbs = dbs;
1329 mdb_env_set_maxreaders(MDB_env *env, int readers)
1331 env->me_maxreaders = readers;
1336 mdb_env_get_maxreaders(MDB_env *env, int *readers)
1338 if (!env || !readers)
1340 *readers = env->me_maxreaders;
1345 mdb_env_open2(MDB_env *env, unsigned int flags)
1347 int i, newenv = 0, toggle;
1351 env->me_flags = flags;
1353 memset(&meta, 0, sizeof(meta));
1355 if ((i = mdb_env_read_header(env, &meta)) != 0) {
1358 DPUTS("new mdbenv");
1362 if (!env->me_mapsize) {
1363 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
1367 if (meta.mm_address && (flags & MDB_FIXEDMAP))
1369 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
1371 if (env->me_map == MAP_FAILED)
1375 meta.mm_mapsize = env->me_mapsize;
1376 if (flags & MDB_FIXEDMAP)
1377 meta.mm_address = env->me_map;
1378 i = mdb_env_init_meta(env, &meta);
1379 if (i != MDB_SUCCESS) {
1380 munmap(env->me_map, env->me_mapsize);
1384 env->me_psize = meta.mm_psize;
1386 env->me_maxpg = env->me_mapsize / env->me_psize;
1388 p = (MDB_page *)env->me_map;
1389 env->me_metas[0] = METADATA(p);
1390 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
1392 if ((i = mdb_env_read_meta(env, &toggle)) != 0)
1395 DPRINTF("opened database version %u, pagesize %u",
1396 env->me_metas[toggle]->mm_version, env->me_psize);
1397 DPRINTF("depth: %u", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_depth);
1398 DPRINTF("entries: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_entries);
1399 DPRINTF("branch pages: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_branch_pages);
1400 DPRINTF("leaf pages: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_leaf_pages);
1401 DPRINTF("overflow pages: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_overflow_pages);
1402 DPRINTF("root: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_root);
1408 mdb_env_reader_dest(void *ptr)
1410 MDB_reader *reader = ptr;
1412 reader->mr_txnid = 0;
1417 /* downgrade the exclusive lock on the region back to shared */
1419 mdb_env_share_locks(MDB_env *env)
1421 struct flock lock_info;
1424 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1426 env->me_txns->mti_me_toggle = toggle;
1427 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
1429 memset((void *)&lock_info, 0, sizeof(lock_info));
1430 lock_info.l_type = F_RDLCK;
1431 lock_info.l_whence = SEEK_SET;
1432 lock_info.l_start = 0;
1433 lock_info.l_len = 1;
1434 fcntl(env->me_lfd, F_SETLK, &lock_info);
1438 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
1442 struct flock lock_info;
1446 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
1450 /* Try to get exclusive lock. If we succeed, then
1451 * nobody is using the lock region and we should initialize it.
1453 memset((void *)&lock_info, 0, sizeof(lock_info));
1454 lock_info.l_type = F_WRLCK;
1455 lock_info.l_whence = SEEK_SET;
1456 lock_info.l_start = 0;
1457 lock_info.l_len = 1;
1458 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1462 lock_info.l_type = F_RDLCK;
1463 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1469 size = lseek(env->me_lfd, 0, SEEK_END);
1470 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1471 if (size < rsize && *excl) {
1472 if (ftruncate(env->me_lfd, rsize) != 0) {
1478 size = rsize - sizeof(MDB_txninfo);
1479 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
1481 env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
1483 if (env->me_txns == MAP_FAILED) {
1488 pthread_mutexattr_t mattr;
1490 pthread_mutexattr_init(&mattr);
1491 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
1495 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
1496 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
1497 env->me_txns->mti_version = MDB_VERSION;
1498 env->me_txns->mti_magic = MDB_MAGIC;
1499 env->me_txns->mti_txnid = 0;
1500 env->me_txns->mti_numreaders = 0;
1501 env->me_txns->mti_me_toggle = 0;
1504 if (env->me_txns->mti_magic != MDB_MAGIC) {
1505 DPUTS("lock region has invalid magic");
1509 if (env->me_txns->mti_version != MDB_VERSION) {
1510 DPRINTF("lock region is version %u, expected version %u",
1511 env->me_txns->mti_version, MDB_VERSION);
1512 rc = MDB_VERSION_MISMATCH;
1515 if (errno != EACCES && errno != EAGAIN) {
1529 #define LOCKNAME "/lock.mdb"
1530 #define DATANAME "/data.mdb"
1532 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
1534 int oflags, rc, len, excl;
1535 char *lpath, *dpath;
1538 lpath = malloc(len + sizeof(LOCKNAME) + len + sizeof(DATANAME));
1541 dpath = lpath + len + sizeof(LOCKNAME);
1542 sprintf(lpath, "%s" LOCKNAME, path);
1543 sprintf(dpath, "%s" DATANAME, path);
1545 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
1549 if (F_ISSET(flags, MDB_RDONLY))
1552 oflags = O_RDWR | O_CREAT;
1554 if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
1559 if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
1560 /* synchronous fd for meta writes */
1561 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
1562 oflags |= MDB_DSYNC;
1563 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
1568 env->me_path = strdup(path);
1569 DPRINTF("opened dbenv %p", (void *) env);
1570 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
1571 LAZY_RWLOCK_INIT(&env->me_dblock, NULL);
1573 mdb_env_share_locks(env);
1574 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
1575 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
1576 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
1582 if (env->me_fd >= 0) {
1586 if (env->me_lfd >= 0) {
1596 mdb_env_close(MDB_env *env)
1603 while (env->me_dpages) {
1604 dp = env->me_dpages;
1605 env->me_dpages = (MDB_dpage *)dp->h.md_parent;
1609 free(env->me_dbs[1]);
1610 free(env->me_dbs[0]);
1614 LAZY_RWLOCK_DESTROY(&env->me_dblock);
1615 pthread_key_delete(env->me_txkey);
1618 munmap(env->me_map, env->me_mapsize);
1623 pid_t pid = getpid();
1624 size_t size = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1626 for (i=0; i<env->me_txns->mti_numreaders; i++)
1627 if (env->me_txns->mti_readers[i].mr_pid == pid)
1628 env->me_txns->mti_readers[i].mr_pid = 0;
1629 munmap(env->me_txns, size);
1635 /* Search for key within a leaf page, using binary search.
1636 * Returns the smallest entry larger or equal to the key.
1637 * If exactp is non-null, stores whether the found entry was an exact match
1638 * in *exactp (1 or 0).
1639 * If kip is non-null, stores the index of the found entry in *kip.
1640 * If no entry larger or equal to the key is found, returns NULL.
1643 mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, MDB_val *key,
1644 int *exactp, unsigned int *kip)
1649 MDB_node *node = NULL;
1653 DPRINTF("searching %u keys in %s page %lu",
1655 IS_LEAF(mp) ? "leaf" : "branch",
1658 assert(NUMKEYS(mp) > 0);
1660 memset(&nodekey, 0, sizeof(nodekey));
1662 low = IS_LEAF(mp) ? 0 : 1;
1663 high = NUMKEYS(mp) - 1;
1664 while (low <= high) {
1665 i = (low + high) >> 1;
1668 nodekey.mv_size = txn->mt_dbs[dbi].md_pad;
1669 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
1671 node = NODEPTR(mp, i);
1673 nodekey.mv_size = node->mn_ksize;
1674 nodekey.mv_data = NODEKEY(node);
1677 rc = mdb_cmp(txn, dbi, key, &nodekey);
1680 DPRINTF("found leaf index %u [%s], rc = %i",
1681 i, DKEY(&nodekey), rc);
1683 DPRINTF("found branch index %u [%s -> %lu], rc = %i",
1684 i, DKEY(&nodekey), NODEPGNO(node), rc);
1694 if (rc > 0) { /* Found entry is less than the key. */
1695 i++; /* Skip to get the smallest entry larger than key. */
1696 if (i >= NUMKEYS(mp))
1697 /* There is no entry larger or equal to the key. */
1701 *exactp = (rc == 0);
1702 if (kip) /* Store the key index if requested. */
1705 /* nodeptr is fake for LEAF2 */
1706 return IS_LEAF2(mp) ? NODEPTR(mp, 0) : NODEPTR(mp, i);
1710 cursor_pop_page(MDB_cursor *cursor)
1714 if (cursor->mc_snum) {
1715 top = CURSOR_TOP(cursor);
1718 DPRINTF("popped page %lu off db %u cursor %p", top->mp_page->mp_pgno,
1719 cursor->mc_dbi, (void *) cursor);
1724 cursor_push_page(MDB_cursor *cursor, MDB_page *mp)
1728 DPRINTF("pushing page %lu on db %u cursor %p", mp->mp_pgno,
1729 cursor->mc_dbi, (void *) cursor);
1731 assert(cursor->mc_snum < CURSOR_STACK);
1733 ppage = &cursor->mc_stack[cursor->mc_snum++];
1734 ppage->mp_page = mp;
1740 mdb_get_page(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
1744 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
1749 x = mdb_midl2_search(txn->mt_u.dirty_list, &id);
1750 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
1751 dp = txn->mt_u.dirty_list[x].mptr;
1756 if (pgno <= txn->mt_env->me_metas[txn->mt_toggle]->mm_last_pg)
1757 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
1761 DPRINTF("page %lu not found", pgno);
1764 return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
1768 mdb_search_page_root(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
1769 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
1771 MDB_page *mp = mpp->mp_page;
1775 if (cursor && cursor_push_page(cursor, mp) == NULL)
1778 while (IS_BRANCH(mp)) {
1782 DPRINTF("branch page %lu has %u keys", mp->mp_pgno, NUMKEYS(mp));
1783 assert(NUMKEYS(mp) > 1);
1784 DPRINTF("found index 0 to page %lu", NODEPGNO(NODEPTR(mp, 0)));
1786 if (key == NULL) /* Initialize cursor to first page. */
1788 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
1789 /* cursor to last page */
1793 node = mdb_search_node(txn, dbi, mp, key, &exact, &i);
1795 i = NUMKEYS(mp) - 1;
1803 DPRINTF("following index %u for key [%s]",
1805 assert(i < NUMKEYS(mp));
1806 node = NODEPTR(mp, i);
1809 CURSOR_TOP(cursor)->mp_ki = i;
1811 mpp->mp_parent = mp;
1812 if ((rc = mdb_get_page(txn, NODEPGNO(node), &mp)))
1817 if (cursor && cursor_push_page(cursor, mp) == NULL)
1821 MDB_dhead *dh = ((MDB_dhead *)mp)-1;
1822 if ((rc = mdb_touch(txn, mpp)) != 0)
1824 dh = ((MDB_dhead *)mpp->mp_page)-1;
1825 dh->md_parent = mpp->mp_parent;
1826 dh->md_pi = mpp->mp_pi;
1833 DPRINTF("internal error, index points to a %02X page!?",
1835 return MDB_CORRUPTED;
1838 DPRINTF("found leaf page %lu for key [%s]", mp->mp_pgno,
1839 key ? DKEY(key) : NULL);
1844 /* Search for the page a given key should be in.
1845 * Stores a pointer to the found page in *mpp.
1846 * If key is NULL, search for the lowest page (used by mdb_cursor_first).
1847 * If cursor is non-null, pushes parent pages on the cursor stack.
1848 * If modify is true, visited pages are updated with new page numbers.
1851 mdb_search_page(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
1852 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
1857 /* Choose which root page to start with. If a transaction is given
1858 * use the root page from the transaction, otherwise read the last
1859 * committed root page.
1861 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1862 DPUTS("transaction has failed, must abort");
1865 root = txn->mt_dbs[dbi].md_root;
1867 if (root == P_INVALID) { /* Tree is empty. */
1868 DPUTS("tree is empty");
1869 return MDB_NOTFOUND;
1872 if (rc = mdb_get_page(txn, root, &mpp->mp_page))
1875 DPRINTF("db %u root page %lu has flags 0x%X",
1876 dbi, root, mpp->mp_page->mp_flags);
1879 /* For sub-databases, update main root first */
1880 if (dbi > MAIN_DBI && !txn->mt_dbxs[dbi].md_dirty) {
1882 rc = mdb_search_page(txn, MAIN_DBI, &txn->mt_dbxs[dbi].md_name,
1886 txn->mt_dbxs[dbi].md_dirty = 1;
1888 if (!F_ISSET(mpp->mp_page->mp_flags, P_DIRTY)) {
1889 mpp->mp_parent = NULL;
1891 if ((rc = mdb_touch(txn, mpp)))
1893 txn->mt_dbs[dbi].md_root = mpp->mp_page->mp_pgno;
1897 return mdb_search_page_root(txn, dbi, key, cursor, modify, mpp);
1901 mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
1903 MDB_page *omp; /* overflow mpage */
1907 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
1908 data->mv_size = leaf->mn_dsize;
1909 data->mv_data = NODEDATA(leaf);
1913 /* Read overflow data.
1915 data->mv_size = leaf->mn_dsize;
1916 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
1917 if (rc = mdb_get_page(txn, pgno, &omp)) {
1918 DPRINTF("read overflow page %lu failed", pgno);
1921 data->mv_data = METADATA(omp);
1927 mdb_get(MDB_txn *txn, MDB_dbi dbi,
1928 MDB_val *key, MDB_val *data)
1937 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
1939 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
1942 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
1946 if ((rc = mdb_search_page(txn, dbi, key, NULL, 0, &mpp)) != MDB_SUCCESS)
1949 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, NULL);
1950 if (leaf && exact) {
1951 /* Return first duplicate data item */
1952 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
1955 mdb_xcursor_init0(txn, dbi, &mx);
1956 mdb_xcursor_init1(txn, dbi, &mx, mpp.mp_page, leaf);
1957 rc = mdb_search_page(&mx.mx_txn, mx.mx_cursor.mc_dbi, NULL, NULL, 0, &mpp);
1958 if (rc != MDB_SUCCESS)
1960 if (IS_LEAF2(mpp.mp_page)) {
1961 data->mv_size = txn->mt_dbs[dbi].md_pad;
1962 data->mv_data = LEAF2KEY(mpp.mp_page, 0, data->mv_size);
1964 leaf = NODEPTR(mpp.mp_page, 0);
1965 data->mv_size = NODEKSZ(leaf);
1966 data->mv_data = NODEKEY(leaf);
1969 rc = mdb_read_data(txn, leaf, data);
1979 mdb_sibling(MDB_cursor *cursor, int move_right)
1986 if (cursor->mc_snum < 2) {
1987 return MDB_NOTFOUND; /* root has no siblings */
1989 parent = CURSOR_PARENT(cursor);
1991 DPRINTF("parent page is page %lu, index %u",
1992 parent->mp_page->mp_pgno, parent->mp_ki);
1994 cursor_pop_page(cursor);
1995 if (move_right ? (parent->mp_ki + 1 >= NUMKEYS(parent->mp_page))
1996 : (parent->mp_ki == 0)) {
1997 DPRINTF("no more keys left, moving to %s sibling",
1998 move_right ? "right" : "left");
1999 if ((rc = mdb_sibling(cursor, move_right)) != MDB_SUCCESS)
2001 parent = CURSOR_TOP(cursor);
2007 DPRINTF("just moving to %s index key %u",
2008 move_right ? "right" : "left", parent->mp_ki);
2010 assert(IS_BRANCH(parent->mp_page));
2012 indx = NODEPTR(parent->mp_page, parent->mp_ki);
2013 if (rc = mdb_get_page(cursor->mc_txn, NODEPGNO(indx), &mp))
2016 mp->parent = parent->mp_page;
2017 mp->parent_index = parent->mp_ki;
2020 cursor_push_page(cursor, mp);
2026 mdb_cursor_next(MDB_cursor *cursor, MDB_val *key, MDB_val *data, MDB_cursor_op op)
2033 if (cursor->mc_eof) {
2034 return MDB_NOTFOUND;
2037 assert(cursor->mc_initialized);
2039 top = CURSOR_TOP(cursor);
2042 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2043 leaf = NODEPTR(mp, top->mp_ki);
2044 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2045 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
2046 rc = mdb_cursor_next(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
2047 if (op != MDB_NEXT || rc == MDB_SUCCESS)
2051 cursor->mc_xcursor->mx_cursor.mc_initialized = 0;
2052 if (op == MDB_NEXT_DUP)
2053 return MDB_NOTFOUND;
2057 DPRINTF("cursor_next: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
2059 if (top->mp_ki + 1 >= NUMKEYS(mp)) {
2060 DPUTS("=====> move to next sibling page");
2061 if (mdb_sibling(cursor, 1) != MDB_SUCCESS) {
2063 return MDB_NOTFOUND;
2065 top = CURSOR_TOP(cursor);
2067 DPRINTF("next page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
2071 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
2072 mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
2075 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2076 key->mv_data = LEAF2KEY(mp, top->mp_ki, key->mv_size);
2080 assert(IS_LEAF(mp));
2081 leaf = NODEPTR(mp, top->mp_ki);
2083 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2084 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, mp, leaf);
2087 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS))
2090 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2091 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2092 if (rc != MDB_SUCCESS)
2097 MDB_SET_KEY(leaf, key);
2102 mdb_cursor_prev(MDB_cursor *cursor, MDB_val *key, MDB_val *data, MDB_cursor_op op)
2109 assert(cursor->mc_initialized);
2111 top = CURSOR_TOP(cursor);
2114 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2115 leaf = NODEPTR(mp, top->mp_ki);
2116 if (op == MDB_PREV || op == MDB_PREV_DUP) {
2117 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2118 rc = mdb_cursor_prev(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
2119 if (op != MDB_PREV || rc == MDB_SUCCESS)
2122 cursor->mc_xcursor->mx_cursor.mc_initialized = 0;
2123 if (op == MDB_PREV_DUP)
2124 return MDB_NOTFOUND;
2129 DPRINTF("cursor_prev: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
2131 if (top->mp_ki == 0) {
2132 DPUTS("=====> move to prev sibling page");
2133 if (mdb_sibling(cursor, 0) != MDB_SUCCESS) {
2134 cursor->mc_initialized = 0;
2135 return MDB_NOTFOUND;
2137 top = CURSOR_TOP(cursor);
2139 top->mp_ki = NUMKEYS(mp) - 1;
2140 DPRINTF("prev page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
2146 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
2147 mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
2150 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2151 key->mv_data = LEAF2KEY(mp, top->mp_ki, key->mv_size);
2155 assert(IS_LEAF(mp));
2156 leaf = NODEPTR(mp, top->mp_ki);
2158 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2159 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, mp, leaf);
2162 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS))
2165 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2166 rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
2167 if (rc != MDB_SUCCESS)
2172 MDB_SET_KEY(leaf, key);
2177 mdb_cursor_set(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
2178 MDB_cursor_op op, int *exactp)
2188 assert(key->mv_size > 0);
2190 /* See if we're already on the right page */
2191 if (cursor->mc_initialized) {
2193 top = CURSOR_TOP(cursor);
2194 /* Don't try this for LEAF2 pages. Maybe support that later. */
2195 if ((top->mp_page->mp_flags & (P_LEAF|P_LEAF2)) == P_LEAF) {
2196 leaf = NODEPTR(top->mp_page, 0);
2197 MDB_SET_KEY(leaf, &nodekey);
2198 rc = mdb_cmp(cursor->mc_txn, cursor->mc_dbi, key, &nodekey);
2200 leaf = NODEPTR(top->mp_page, NUMKEYS(top->mp_page)-1);
2201 MDB_SET_KEY(leaf, &nodekey);
2202 rc = mdb_cmp(cursor->mc_txn, cursor->mc_dbi, key, &nodekey);
2204 /* we're already on the right page */
2205 mpp.mp_page = top->mp_page;
2212 cursor->mc_snum = 0;
2214 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, key, cursor, 0, &mpp);
2215 if (rc != MDB_SUCCESS)
2218 assert(IS_LEAF(mpp.mp_page));
2220 top = CURSOR_TOP(cursor);
2222 leaf = mdb_search_node(cursor->mc_txn, cursor->mc_dbi, mpp.mp_page, key, exactp, &top->mp_ki);
2223 if (exactp != NULL && !*exactp) {
2224 /* MDB_SET specified and not an exact match. */
2225 return MDB_NOTFOUND;
2229 DPUTS("===> inexact leaf not found, goto sibling");
2230 if ((rc = mdb_sibling(cursor, 1)) != MDB_SUCCESS)
2231 return rc; /* no entries matched */
2232 top = CURSOR_TOP(cursor);
2234 mpp.mp_page = top->mp_page;
2235 assert(IS_LEAF(mpp.mp_page));
2236 leaf = NODEPTR(mpp.mp_page, 0);
2239 cursor->mc_initialized = 1;
2242 if (IS_LEAF2(mpp.mp_page)) {
2243 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2244 key->mv_data = LEAF2KEY(mpp.mp_page, top->mp_ki, key->mv_size);
2248 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2249 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, mpp.mp_page, leaf);
2252 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2253 if (op == MDB_SET || op == MDB_SET_RANGE) {
2254 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2257 if (op == MDB_GET_BOTH) {
2262 rc = mdb_cursor_set(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
2263 if (rc != MDB_SUCCESS)
2266 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
2268 if ((rc = mdb_read_data(cursor->mc_txn, leaf, &d2)) != MDB_SUCCESS)
2270 rc = mdb_dcmp(cursor->mc_txn, cursor->mc_dbi, data, &d2);
2272 if (op == MDB_GET_BOTH || rc > 0)
2273 return MDB_NOTFOUND;
2277 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2282 /* The key already matches in all other cases */
2283 if (op == MDB_SET_RANGE)
2284 MDB_SET_KEY(leaf, key);
2285 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
2291 mdb_cursor_first(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
2297 cursor->mc_snum = 0;
2299 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, NULL, cursor, 0, &mpp);
2300 if (rc != MDB_SUCCESS)
2302 assert(IS_LEAF(mpp.mp_page));
2304 leaf = NODEPTR(mpp.mp_page, 0);
2305 cursor->mc_initialized = 1;
2308 if (IS_LEAF2(mpp.mp_page)) {
2309 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2310 key->mv_data = LEAF2KEY(mpp.mp_page, 0, key->mv_size);
2315 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2316 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, mpp.mp_page, leaf);
2317 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2321 if (cursor->mc_xcursor)
2322 cursor->mc_xcursor->mx_cursor.mc_initialized = 0;
2323 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2327 MDB_SET_KEY(leaf, key);
2332 mdb_cursor_last(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
2340 cursor->mc_snum = 0;
2342 lkey.mv_size = MAXKEYSIZE+1;
2343 lkey.mv_data = NULL;
2345 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, &lkey, cursor, 0, &mpp);
2346 if (rc != MDB_SUCCESS)
2348 assert(IS_LEAF(mpp.mp_page));
2350 leaf = NODEPTR(mpp.mp_page, NUMKEYS(mpp.mp_page)-1);
2351 cursor->mc_initialized = 1;
2354 top = CURSOR_TOP(cursor);
2355 top->mp_ki = NUMKEYS(top->mp_page) - 1;
2357 if (IS_LEAF2(mpp.mp_page)) {
2358 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2359 key->mv_data = LEAF2KEY(mpp.mp_page, top->mp_ki, key->mv_size);
2364 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2365 mdb_xcursor_init1(cursor->mc_txn, cursor->mc_dbi, cursor->mc_xcursor, mpp.mp_page, leaf);
2366 rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
2370 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2375 MDB_SET_KEY(leaf, key);
2380 mdb_cursor_get(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
2390 case MDB_GET_BOTH_RANGE:
2391 if (data == NULL || cursor->mc_xcursor == NULL) {
2398 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2400 } else if (op == MDB_SET_RANGE)
2401 rc = mdb_cursor_set(cursor, key, data, op, NULL);
2403 rc = mdb_cursor_set(cursor, key, data, op, &exact);
2405 case MDB_GET_MULTIPLE:
2407 !(cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPFIXED) ||
2408 !cursor->mc_initialized) {
2413 if (!cursor->mc_xcursor->mx_cursor.mc_initialized || cursor->mc_xcursor->mx_cursor.mc_eof)
2416 case MDB_NEXT_MULTIPLE:
2418 !(cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPFIXED)) {
2422 if (!cursor->mc_initialized)
2423 rc = mdb_cursor_first(cursor, key, data);
2425 rc = mdb_cursor_next(cursor, key, data, MDB_NEXT_DUP);
2426 if (rc == MDB_SUCCESS) {
2427 if (cursor->mc_xcursor->mx_cursor.mc_initialized) {
2430 top = CURSOR_TOP(&cursor->mc_xcursor->mx_cursor);
2431 data->mv_size = NUMKEYS(top->mp_page) *
2432 cursor->mc_xcursor->mx_txn.mt_dbs[cursor->mc_xcursor->mx_cursor.mc_dbi].md_pad;
2433 data->mv_data = METADATA(top->mp_page);
2434 top->mp_ki = NUMKEYS(top->mp_page)-1;
2442 case MDB_NEXT_NODUP:
2443 if (!cursor->mc_initialized)
2444 rc = mdb_cursor_first(cursor, key, data);
2446 rc = mdb_cursor_next(cursor, key, data, op);
2450 case MDB_PREV_NODUP:
2451 if (!cursor->mc_initialized || cursor->mc_eof)
2452 rc = mdb_cursor_last(cursor, key, data);
2454 rc = mdb_cursor_prev(cursor, key, data, op);
2457 rc = mdb_cursor_first(cursor, key, data);
2460 rc = mdb_cursor_last(cursor, key, data);
2463 DPRINTF("unhandled/unimplemented cursor operation %u", op);
2471 /* Allocate a page and initialize it
2474 mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num)
2478 if ((dp = mdb_alloc_page(txn, NULL, 0, num)) == NULL)
2480 DPRINTF("allocated new mpage %lu, page size %u",
2481 dp->p.mp_pgno, txn->mt_env->me_psize);
2482 dp->p.mp_flags = flags | P_DIRTY;
2483 dp->p.mp_lower = PAGEHDRSZ;
2484 dp->p.mp_upper = txn->mt_env->me_psize;
2486 if (IS_BRANCH(&dp->p))
2487 txn->mt_dbs[dbi].md_branch_pages++;
2488 else if (IS_LEAF(&dp->p))
2489 txn->mt_dbs[dbi].md_leaf_pages++;
2490 else if (IS_OVERFLOW(&dp->p)) {
2491 txn->mt_dbs[dbi].md_overflow_pages += num;
2492 dp->p.mp_pages = num;
2499 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
2503 sz = LEAFSIZE(key, data);
2504 if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
2505 /* put on overflow page */
2506 sz -= data->mv_size - sizeof(pgno_t);
2509 return sz + sizeof(indx_t);
2513 mdb_branch_size(MDB_env *env, MDB_val *key)
2518 if (sz >= env->me_psize / MDB_MINKEYS) {
2519 /* put on overflow page */
2520 /* not implemented */
2521 /* sz -= key->size - sizeof(pgno_t); */
2524 return sz + sizeof(indx_t);
2528 mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, indx_t indx,
2529 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags)
2532 size_t node_size = NODESIZE;
2535 MDB_dpage *ofp = NULL; /* overflow page */
2538 assert(mp->mp_upper >= mp->mp_lower);
2540 DPRINTF("add to %s page %lu index %i, data size %zu key size %zu [%s]",
2541 IS_LEAF(mp) ? "leaf" : "branch",
2542 mp->mp_pgno, indx, data ? data->mv_size : 0,
2543 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
2546 /* Move higher keys up one slot. */
2547 int ksize = txn->mt_dbs[dbi].md_pad, dif;
2548 char *ptr = LEAF2KEY(mp, indx, ksize);
2549 dif = NUMKEYS(mp) - indx;
2551 memmove(ptr+ksize, ptr, dif*ksize);
2552 /* insert new key */
2553 memcpy(ptr, key->mv_data, ksize);
2555 /* Just using these for counting */
2556 mp->mp_lower += sizeof(indx_t);
2557 mp->mp_upper -= ksize - sizeof(indx_t);
2562 node_size += key->mv_size;
2566 if (F_ISSET(flags, F_BIGDATA)) {
2567 /* Data already on overflow page. */
2568 node_size += sizeof(pgno_t);
2569 } else if (data->mv_size >= txn->mt_env->me_psize / MDB_MINKEYS) {
2570 int ovpages = OVPAGES(data->mv_size, txn->mt_env->me_psize);
2571 /* Put data on overflow page. */
2572 DPRINTF("data size is %zu, put on overflow page",
2574 node_size += sizeof(pgno_t);
2575 if ((ofp = mdb_new_page(txn, dbi, P_OVERFLOW, ovpages)) == NULL)
2577 DPRINTF("allocated overflow page %lu", ofp->p.mp_pgno);
2580 node_size += data->mv_size;
2584 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
2585 DPRINTF("not enough room in page %lu, got %u ptrs",
2586 mp->mp_pgno, NUMKEYS(mp));
2587 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
2588 mp->mp_upper - mp->mp_lower);
2589 DPRINTF("node size = %zu", node_size);
2593 /* Move higher pointers up one slot. */
2594 for (i = NUMKEYS(mp); i > indx; i--)
2595 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
2597 /* Adjust free space offsets. */
2598 ofs = mp->mp_upper - node_size;
2599 assert(ofs >= mp->mp_lower + sizeof(indx_t));
2600 mp->mp_ptrs[indx] = ofs;
2602 mp->mp_lower += sizeof(indx_t);
2604 /* Write the node data. */
2605 node = NODEPTR(mp, indx);
2606 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
2607 node->mn_flags = flags;
2609 node->mn_dsize = data->mv_size;
2611 NODEPGNO(node) = pgno;
2614 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
2619 if (F_ISSET(flags, F_BIGDATA))
2620 memcpy(node->mn_data + key->mv_size, data->mv_data,
2623 memcpy(node->mn_data + key->mv_size, data->mv_data,
2626 memcpy(node->mn_data + key->mv_size, &ofp->p.mp_pgno,
2628 memcpy(METADATA(&ofp->p), data->mv_data, data->mv_size);
2636 mdb_del_node(MDB_page *mp, indx_t indx, int ksize)
2639 indx_t i, j, numkeys, ptr;
2643 DPRINTF("delete node %u on %s page %lu", indx,
2644 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
2645 assert(indx < NUMKEYS(mp));
2648 int x = NUMKEYS(mp) - 1 - indx;
2649 base = LEAF2KEY(mp, indx, ksize);
2651 memmove(base, base + ksize, x * ksize);
2652 mp->mp_lower -= sizeof(indx_t);
2653 mp->mp_upper += ksize - sizeof(indx_t);
2657 node = NODEPTR(mp, indx);
2658 sz = NODESIZE + node->mn_ksize;
2660 if (F_ISSET(node->mn_flags, F_BIGDATA))
2661 sz += sizeof(pgno_t);
2663 sz += NODEDSZ(node);
2666 ptr = mp->mp_ptrs[indx];
2667 numkeys = NUMKEYS(mp);
2668 for (i = j = 0; i < numkeys; i++) {
2670 mp->mp_ptrs[j] = mp->mp_ptrs[i];
2671 if (mp->mp_ptrs[i] < ptr)
2672 mp->mp_ptrs[j] += sz;
2677 base = (char *)mp + mp->mp_upper;
2678 memmove(base + sz, base, ptr - mp->mp_upper);
2680 mp->mp_lower -= sizeof(indx_t);
2685 mdb_xcursor_init0(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
2690 mx->mx_txn.mt_dbxs = mx->mx_dbxs;
2691 mx->mx_txn.mt_dbs = mx->mx_dbs;
2692 mx->mx_dbxs[0] = txn->mt_dbxs[0];
2693 mx->mx_dbxs[1] = txn->mt_dbxs[1];
2695 mx->mx_dbxs[2] = txn->mt_dbxs[dbi];
2700 mx->mx_dbxs[dbn+1].md_parent = dbn;
2701 mx->mx_dbxs[dbn+1].md_cmp = mx->mx_dbxs[dbn].md_dcmp;
2702 mx->mx_dbxs[dbn+1].md_rel = mx->mx_dbxs[dbn].md_rel;
2703 mx->mx_dbxs[dbn+1].md_dirty = 0;
2704 mx->mx_txn.mt_numdbs = dbn+2;
2706 mx->mx_cursor.mc_snum = 0;
2707 mx->mx_cursor.mc_txn = &mx->mx_txn;
2708 mx->mx_cursor.mc_dbi = dbn+1;
2712 mdb_xcursor_init1(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx, MDB_page *mp, MDB_node *node)
2714 MDB_db *db = NODEDATA(node);
2716 mx->mx_dbs[0] = txn->mt_dbs[0];
2717 mx->mx_dbs[1] = txn->mt_dbs[1];
2719 mx->mx_dbs[2] = txn->mt_dbs[dbi];
2724 DPRINTF("Sub-db %u for db %u root page %lu", dbn, dbi, db->md_root);
2725 mx->mx_dbs[dbn] = *db;
2726 if (F_ISSET(mp->mp_flags, P_DIRTY))
2727 mx->mx_dbxs[dbn].md_dirty = 1;
2728 mx->mx_dbxs[dbn].md_name.mv_data = NODEKEY(node);
2729 mx->mx_dbxs[dbn].md_name.mv_size = node->mn_ksize;
2730 mx->mx_txn.mt_next_pgno = txn->mt_next_pgno;
2731 mx->mx_txn.mt_oldest = txn->mt_oldest;
2732 mx->mx_txn.mt_u = txn->mt_u;
2733 mx->mx_cursor.mc_initialized = 0;
2734 mx->mx_cursor.mc_eof = 0;
2738 mdb_xcursor_fini(MDB_txn *txn, MDB_dbi dbi, MDB_xcursor *mx)
2740 txn->mt_next_pgno = mx->mx_txn.mt_next_pgno;
2741 txn->mt_oldest = mx->mx_txn.mt_oldest;
2742 txn->mt_u = mx->mx_txn.mt_u;
2743 txn->mt_dbs[0] = mx->mx_dbs[0];
2744 txn->mt_dbs[1] = mx->mx_dbs[1];
2745 txn->mt_dbxs[0].md_dirty = mx->mx_dbxs[0].md_dirty;
2746 txn->mt_dbxs[1].md_dirty = mx->mx_dbxs[1].md_dirty;
2748 txn->mt_dbs[dbi] = mx->mx_dbs[2];
2749 txn->mt_dbxs[dbi].md_dirty = mx->mx_dbxs[2].md_dirty;
2754 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
2757 size_t size = sizeof(MDB_cursor);
2759 if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
2762 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
2763 size += sizeof(MDB_xcursor);
2765 if ((cursor = calloc(1, size)) != NULL) {
2766 cursor->mc_dbi = dbi;
2767 cursor->mc_txn = txn;
2768 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
2769 MDB_xcursor *mx = (MDB_xcursor *)(cursor + 1);
2770 cursor->mc_xcursor = mx;
2771 mdb_xcursor_init0(txn, dbi, mx);
2782 /* Return the count of duplicate data items for the current key */
2784 mdb_cursor_count(MDB_cursor *mc, unsigned long *countp)
2789 if (mc == NULL || countp == NULL)
2792 if (!(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT))
2795 top = CURSOR_TOP(mc);
2796 leaf = NODEPTR(top->mp_page, top->mp_ki);
2797 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2800 if (!mc->mc_xcursor->mx_cursor.mc_initialized)
2803 *countp = mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_entries;
2809 mdb_cursor_close(MDB_cursor *cursor)
2811 if (cursor != NULL) {
2817 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
2819 indx_t ptr, i, numkeys;
2826 node = NODEPTR(mp, indx);
2827 ptr = mp->mp_ptrs[indx];
2828 DPRINTF("update key %u (ofs %u) [%.*s] to [%s] on page %lu",
2830 (int)node->mn_ksize, (char *)NODEKEY(node),
2834 delta = key->mv_size - node->mn_ksize;
2836 if (delta > 0 && SIZELEFT(mp) < delta) {
2837 DPRINTF("OUCH! Not enough room, delta = %d", delta);
2841 numkeys = NUMKEYS(mp);
2842 for (i = 0; i < numkeys; i++) {
2843 if (mp->mp_ptrs[i] <= ptr)
2844 mp->mp_ptrs[i] -= delta;
2847 base = (char *)mp + mp->mp_upper;
2848 len = ptr - mp->mp_upper + NODESIZE;
2849 memmove(base - delta, base, len);
2850 mp->mp_upper -= delta;
2852 node = NODEPTR(mp, indx);
2853 node->mn_ksize = key->mv_size;
2856 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
2861 /* Move a node from src to dst.
2864 mdb_move_node(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, indx_t srcindx,
2865 MDB_pageparent *dst, indx_t dstindx)
2872 /* Mark src and dst as dirty. */
2873 if ((rc = mdb_touch(txn, src)) ||
2874 (rc = mdb_touch(txn, dst)))
2877 if (IS_LEAF2(src->mp_page)) {
2878 srcnode = NODEPTR(src->mp_page, 0); /* fake */
2879 key.mv_size = txn->mt_dbs[dbi].md_pad;
2880 key.mv_data = LEAF2KEY(src->mp_page, srcindx, key.mv_size);
2882 data.mv_data = NULL;
2884 srcnode = NODEPTR(src->mp_page, srcindx);
2885 key.mv_size = NODEKSZ(srcnode);
2886 key.mv_data = NODEKEY(srcnode);
2887 data.mv_size = NODEDSZ(srcnode);
2888 data.mv_data = NODEDATA(srcnode);
2890 DPRINTF("moving %s node %u [%s] on page %lu to node %u on page %lu",
2891 IS_LEAF(src->mp_page) ? "leaf" : "branch",
2894 src->mp_page->mp_pgno,
2895 dstindx, dst->mp_page->mp_pgno);
2897 /* Add the node to the destination page.
2899 rc = mdb_add_node(txn, dbi, dst->mp_page, dstindx, &key, &data, NODEPGNO(srcnode),
2901 if (rc != MDB_SUCCESS)
2904 /* Delete the node from the source page.
2906 mdb_del_node(src->mp_page, srcindx, key.mv_size);
2908 /* The key value just changed due to del_node, find it again.
2910 if (!IS_LEAF2(src->mp_page)) {
2911 srcnode = NODEPTR(src->mp_page, srcindx);
2912 key.mv_data = NODEKEY(srcnode);
2915 /* Update the parent separators.
2918 if (src->mp_pi != 0) {
2919 DPRINTF("update separator for source page %lu to [%s]",
2920 src->mp_page->mp_pgno, DKEY(&key));
2921 if ((rc = mdb_update_key(src->mp_parent, src->mp_pi,
2922 &key)) != MDB_SUCCESS)
2925 if (IS_BRANCH(src->mp_page)) {
2927 nullkey.mv_size = 0;
2928 assert(mdb_update_key(src->mp_page, 0, &nullkey) == MDB_SUCCESS);
2933 if (dst->mp_pi != 0) {
2934 DPRINTF("update separator for destination page %lu to [%s]",
2935 dst->mp_page->mp_pgno, DKEY(&key));
2936 if ((rc = mdb_update_key(dst->mp_parent, dst->mp_pi,
2937 &key)) != MDB_SUCCESS)
2940 if (IS_BRANCH(dst->mp_page)) {
2942 nullkey.mv_size = 0;
2943 assert(mdb_update_key(dst->mp_page, 0, &nullkey) == MDB_SUCCESS);
2951 mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, MDB_pageparent *dst)
2960 DPRINTF("merging page %lu and %lu", src->mp_page->mp_pgno, dst->mp_page->mp_pgno);
2962 assert(txn != NULL);
2963 assert(src->mp_parent); /* can't merge root page */
2964 assert(dst->mp_parent);
2966 /* Mark src and dst as dirty. */
2967 if ((rc = mdb_touch(txn, src)) ||
2968 (rc = mdb_touch(txn, dst)))
2971 /* Move all nodes from src to dst.
2973 if (IS_LEAF2(src->mp_page)) {
2974 key.mv_size = txn->mt_dbs[dbi].md_pad;
2975 key.mv_data = METADATA(src->mp_page);
2976 for (i = 0; i < NUMKEYS(src->mp_page); i++) {
2977 rc = mdb_add_node(txn, dbi, dst->mp_page, NUMKEYS(dst->mp_page), &key,
2979 if (rc != MDB_SUCCESS)
2981 key.mv_data = (char *)key.mv_data + key.mv_size;
2984 for (i = 0; i < NUMKEYS(src->mp_page); i++) {
2985 srcnode = NODEPTR(src->mp_page, i);
2987 key.mv_size = srcnode->mn_ksize;
2988 key.mv_data = NODEKEY(srcnode);
2989 data.mv_size = NODEDSZ(srcnode);
2990 data.mv_data = NODEDATA(srcnode);
2991 rc = mdb_add_node(txn, dbi, dst->mp_page, NUMKEYS(dst->mp_page), &key,
2992 &data, NODEPGNO(srcnode), srcnode->mn_flags);
2993 if (rc != MDB_SUCCESS)
2998 DPRINTF("dst page %lu now has %u keys (%.1f%% filled)",
2999 dst->mp_page->mp_pgno, NUMKEYS(dst->mp_page), (float)PAGEFILL(txn->mt_env, dst->mp_page) / 10);
3001 /* Unlink the src page from parent.
3003 mdb_del_node(src->mp_parent, src->mp_pi, 0);
3004 if (src->mp_pi == 0) {
3006 if ((rc = mdb_update_key(src->mp_parent, 0, &key)) != MDB_SUCCESS)
3010 if (IS_LEAF(src->mp_page))
3011 txn->mt_dbs[dbi].md_leaf_pages--;
3013 txn->mt_dbs[dbi].md_branch_pages--;
3015 mpp.mp_page = src->mp_parent;
3016 dh = (MDB_dhead *)src->mp_parent;
3018 mpp.mp_parent = dh->md_parent;
3019 mpp.mp_pi = dh->md_pi;
3021 return mdb_rebalance(txn, dbi, &mpp);
3024 #define FILL_THRESHOLD 250
3027 mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mpp)
3032 indx_t si = 0, di = 0;
3035 assert(txn != NULL);
3036 assert(mpp != NULL);
3038 DPRINTF("rebalancing %s page %lu (has %u keys, %.1f%% full)",
3039 IS_LEAF(mpp->mp_page) ? "leaf" : "branch",
3040 mpp->mp_page->mp_pgno, NUMKEYS(mpp->mp_page), (float)PAGEFILL(txn->mt_env, mpp->mp_page) / 10);
3042 if (PAGEFILL(txn->mt_env, mpp->mp_page) >= FILL_THRESHOLD) {
3043 DPRINTF("no need to rebalance page %lu, above fill threshold",
3044 mpp->mp_page->mp_pgno);
3048 if (mpp->mp_parent == NULL) {
3049 if (NUMKEYS(mpp->mp_page) == 0) {
3050 DPUTS("tree is completely empty");
3051 txn->mt_dbs[dbi].md_root = P_INVALID;
3052 txn->mt_dbs[dbi].md_depth = 0;
3053 txn->mt_dbs[dbi].md_leaf_pages = 0;
3054 } else if (IS_BRANCH(mpp->mp_page) && NUMKEYS(mpp->mp_page) == 1) {
3055 DPUTS("collapsing root page!");
3056 txn->mt_dbs[dbi].md_root = NODEPGNO(NODEPTR(mpp->mp_page, 0));
3057 if (rc = mdb_get_page(txn, txn->mt_dbs[dbi].md_root, &root))
3059 txn->mt_dbs[dbi].md_depth--;
3060 txn->mt_dbs[dbi].md_branch_pages--;
3062 DPUTS("root page doesn't need rebalancing");
3066 /* The parent (branch page) must have at least 2 pointers,
3067 * otherwise the tree is invalid.
3069 assert(NUMKEYS(mpp->mp_parent) > 1);
3071 /* Leaf page fill factor is below the threshold.
3072 * Try to move keys from left or right neighbor, or
3073 * merge with a neighbor page.
3078 if (mpp->mp_pi == 0) {
3079 /* We're the leftmost leaf in our parent.
3081 DPUTS("reading right neighbor");
3082 node = NODEPTR(mpp->mp_parent, mpp->mp_pi + 1);
3083 if (rc = mdb_get_page(txn, NODEPGNO(node), &npp.mp_page))
3085 npp.mp_pi = mpp->mp_pi + 1;
3087 di = NUMKEYS(mpp->mp_page);
3089 /* There is at least one neighbor to the left.
3091 DPUTS("reading left neighbor");
3092 node = NODEPTR(mpp->mp_parent, mpp->mp_pi - 1);
3093 if (rc = mdb_get_page(txn, NODEPGNO(node), &npp.mp_page))
3095 npp.mp_pi = mpp->mp_pi - 1;
3096 si = NUMKEYS(npp.mp_page) - 1;
3099 npp.mp_parent = mpp->mp_parent;
3101 DPRINTF("found neighbor page %lu (%u keys, %.1f%% full)",
3102 npp.mp_page->mp_pgno, NUMKEYS(npp.mp_page), (float)PAGEFILL(txn->mt_env, npp.mp_page) / 10);
3104 /* If the neighbor page is above threshold and has at least two
3105 * keys, move one key from it.
3107 * Otherwise we should try to merge them.
3109 if (PAGEFILL(txn->mt_env, npp.mp_page) >= FILL_THRESHOLD && NUMKEYS(npp.mp_page) >= 2)
3110 return mdb_move_node(txn, dbi, &npp, si, mpp, di);
3111 else { /* FIXME: if (has_enough_room()) */
3112 if (mpp->mp_pi == 0)
3113 return mdb_merge(txn, dbi, &npp, mpp);
3115 return mdb_merge(txn, dbi, mpp, &npp);
3120 mdb_del0(MDB_txn *txn, MDB_dbi dbi, unsigned int ki, MDB_pageparent *mpp, MDB_node *leaf)
3124 /* add overflow pages to free list */
3125 if (!IS_LEAF2(mpp->mp_page) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
3129 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
3130 ovpages = OVPAGES(NODEDSZ(leaf), txn->mt_env->me_psize);
3131 for (i=0; i<ovpages; i++) {
3132 DPRINTF("freed ov page %lu", pg);
3133 mdb_midl_insert(txn->mt_free_pgs, pg);
3137 mdb_del_node(mpp->mp_page, ki, txn->mt_dbs[dbi].md_pad);
3138 txn->mt_dbs[dbi].md_entries--;
3139 rc = mdb_rebalance(txn, dbi, mpp);
3140 if (rc != MDB_SUCCESS)
3141 txn->mt_flags |= MDB_TXN_ERROR;
3147 mdb_del(MDB_txn *txn, MDB_dbi dbi,
3148 MDB_val *key, MDB_val *data,
3157 assert(key != NULL);
3159 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
3161 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3164 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3168 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3172 mpp.mp_parent = NULL;
3174 if ((rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp)) != MDB_SUCCESS)
3177 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
3178 if (leaf == NULL || !exact) {
3179 return MDB_NOTFOUND;
3182 if (!IS_LEAF2(mpp.mp_page) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3186 mdb_xcursor_init0(txn, dbi, &mx);
3187 mdb_xcursor_init1(txn, dbi, &mx, mpp.mp_page, leaf);
3188 if (flags == MDB_DEL_DUP) {
3189 rc = mdb_del(&mx.mx_txn, mx.mx_cursor.mc_dbi, data, NULL, 0);
3190 mdb_xcursor_fini(txn, dbi, &mx);
3191 /* If sub-DB still has entries, we're done */
3192 if (mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi].md_root != P_INVALID) {
3193 memcpy(NODEDATA(leaf), &mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi],
3195 txn->mt_dbs[dbi].md_entries--;
3198 /* otherwise fall thru and delete the sub-DB */
3200 /* add all the child DB's pages to the free list */
3201 rc = mdb_search_page(&mx.mx_txn, mx.mx_cursor.mc_dbi,
3202 NULL, &mx.mx_cursor, 0, &mp2);
3203 if (rc == MDB_SUCCESS) {
3204 MDB_ppage *top, *parent;
3208 cursor_pop_page(&mx.mx_cursor);
3209 if (mx.mx_cursor.mc_snum) {
3210 top = CURSOR_TOP(&mx.mx_cursor);
3211 while (mx.mx_cursor.mc_snum > 1) {
3212 parent = CURSOR_PARENT(&mx.mx_cursor);
3213 for (i=0; i<NUMKEYS(top->mp_page); i++) {
3214 ni = NODEPTR(top->mp_page, i);
3215 mdb_midl_insert(txn->mt_free_pgs, NODEPGNO(ni));
3218 if (parent->mp_ki >= NUMKEYS(parent->mp_page)) {
3219 cursor_pop_page(&mx.mx_cursor);
3222 ni = NODEPTR(parent->mp_page, parent->mp_ki);
3223 rc = mdb_get_page(&mx.mx_txn, NODEPGNO(ni), &top->mp_page);
3227 mdb_midl_insert(txn->mt_free_pgs, mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi].md_root);
3232 if (data && (rc = mdb_read_data(txn, leaf, data)) != MDB_SUCCESS)
3235 return mdb_del0(txn, dbi, ki, &mpp, leaf);
3238 /* Split page <*mpp>, and insert <key,(data|newpgno)> in either left or
3239 * right sibling, at index <*newindxp> (as if unsplit). Updates *mpp and
3240 * *newindxp with the actual values after split, ie if *mpp and *newindxp
3241 * refer to a node in the new right sibling page.
3244 mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp, unsigned int *newindxp,
3245 MDB_val *newkey, MDB_val *newdata, pgno_t newpgno)
3248 int rc = MDB_SUCCESS, ins_new = 0;
3251 unsigned int i, j, split_indx, nkeys, pmax;
3253 MDB_val sepkey, rkey, rdata;
3254 MDB_page *copy, *cptr;
3255 MDB_dpage *mdp, *rdp, *pdp;
3259 assert(txn != NULL);
3261 dh = ((MDB_dhead *)*mpp) - 1;
3262 mdp = (MDB_dpage *)dh;
3263 newindx = *newindxp;
3265 DPRINTF("-----> splitting %s page %lu and adding [%s] at index %i",
3266 IS_LEAF(&mdp->p) ? "leaf" : "branch", mdp->p.mp_pgno,
3267 DKEY(newkey), *newindxp);
3269 if (mdp->h.md_parent == NULL) {
3270 if ((pdp = mdb_new_page(txn, dbi, P_BRANCH, 1)) == NULL)
3273 mdp->h.md_parent = &pdp->p;
3274 txn->mt_dbs[dbi].md_root = pdp->p.mp_pgno;
3275 DPRINTF("root split! new root = %lu", pdp->p.mp_pgno);
3276 txn->mt_dbs[dbi].md_depth++;
3278 /* Add left (implicit) pointer. */
3279 if ((rc = mdb_add_node(txn, dbi, &pdp->p, 0, NULL, NULL,
3280 mdp->p.mp_pgno, 0)) != MDB_SUCCESS)
3283 DPRINTF("parent branch page is %lu", mdp->h.md_parent->mp_pgno);
3286 /* Create a right sibling. */
3287 if ((rdp = mdb_new_page(txn, dbi, mdp->p.mp_flags, 1)) == NULL)
3289 rdp->h.md_parent = mdp->h.md_parent;
3290 rdp->h.md_pi = mdp->h.md_pi + 1;
3291 DPRINTF("new right sibling: page %lu", rdp->p.mp_pgno);
3293 nkeys = NUMKEYS(&mdp->p);
3294 split_indx = nkeys / 2 + 1;
3296 if (IS_LEAF2(&rdp->p)) {
3299 unsigned int lsize, rsize, ksize;
3300 /* Move half of the keys to the right sibling */
3302 x = *newindxp - split_indx;
3303 ksize = txn->mt_dbs[dbi].md_pad;
3304 split = LEAF2KEY(&mdp->p, split_indx, ksize);
3305 rsize = (nkeys - split_indx) * ksize;
3306 lsize = (nkeys - split_indx) * sizeof(indx_t);
3307 mdp->p.mp_lower -= lsize;
3308 rdp->p.mp_lower += lsize;
3309 mdp->p.mp_upper += rsize - lsize;
3310 rdp->p.mp_upper -= rsize - lsize;
3311 sepkey.mv_size = ksize;
3312 if (newindx == split_indx) {
3313 sepkey.mv_data = newkey->mv_data;
3315 sepkey.mv_data = split;
3318 ins = LEAF2KEY(&mdp->p, *newindxp, ksize);
3319 memcpy(&rdp->p.mp_ptrs, split, rsize);
3320 sepkey.mv_data = &rdp->p.mp_ptrs;
3321 memmove(ins+ksize, ins, (split_indx - *newindxp) * ksize);
3322 memcpy(ins, newkey->mv_data, ksize);
3323 mdp->p.mp_lower += sizeof(indx_t);
3324 mdp->p.mp_upper -= ksize - sizeof(indx_t);
3327 memcpy(&rdp->p.mp_ptrs, split, x * ksize);
3328 ins = LEAF2KEY(&rdp->p, x, ksize);
3329 memcpy(ins, newkey->mv_data, ksize);
3330 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
3331 rdp->p.mp_lower += sizeof(indx_t);
3332 rdp->p.mp_upper -= ksize - sizeof(indx_t);
3339 /* For leaf pages, check the split point based on what
3340 * fits where, since otherwise add_node can fail.
3342 if (IS_LEAF(&mdp->p)) {
3343 unsigned int psize, nsize;
3344 /* Maximum free space in an empty page */
3345 pmax = txn->mt_env->me_psize - PAGEHDRSZ;
3346 nsize = mdb_leaf_size(txn->mt_env, newkey, newdata);
3347 if (newindx <= split_indx) {
3350 for (i=0; i<split_indx; i++) {
3351 node = NODEPTR(&mdp->p, i);
3352 psize += NODESIZE + NODEKSZ(node);
3353 if (F_ISSET(node->mn_flags, F_BIGDATA))
3354 psize += sizeof(pgno_t);
3356 psize += NODEDSZ(node);
3365 for (i=split_indx; i<nkeys; i++) {
3366 node = NODEPTR(&mdp->p, i);
3367 psize += NODESIZE + NODEKSZ(node);
3368 if (F_ISSET(node->mn_flags, F_BIGDATA))
3369 psize += sizeof(pgno_t);
3371 psize += NODEDSZ(node);
3380 /* First find the separating key between the split pages.
3382 memset(&sepkey, 0, sizeof(sepkey));
3383 if (newindx == split_indx) {
3384 sepkey.mv_size = newkey->mv_size;
3385 sepkey.mv_data = newkey->mv_data;
3387 node = NODEPTR(&mdp->p, split_indx);
3388 sepkey.mv_size = node->mn_ksize;
3389 sepkey.mv_data = NODEKEY(node);
3393 DPRINTF("separator is [%s]", DKEY(&sepkey));
3395 /* Copy separator key to the parent.
3397 if (SIZELEFT(rdp->h.md_parent) < mdb_branch_size(txn->mt_env, &sepkey)) {
3398 rc = mdb_split(txn, dbi, &rdp->h.md_parent, &rdp->h.md_pi,
3399 &sepkey, NULL, rdp->p.mp_pgno);
3401 /* Right page might now have changed parent.
3402 * Check if left page also changed parent.
3404 if (rdp->h.md_parent != mdp->h.md_parent &&
3405 mdp->h.md_pi >= NUMKEYS(mdp->h.md_parent)) {
3406 mdp->h.md_parent = rdp->h.md_parent;
3407 mdp->h.md_pi = rdp->h.md_pi - 1;
3410 rc = mdb_add_node(txn, dbi, rdp->h.md_parent, rdp->h.md_pi,
3411 &sepkey, NULL, rdp->p.mp_pgno, 0);
3413 if (IS_LEAF2(&rdp->p)) {
3416 if (rc != MDB_SUCCESS) {
3420 /* Move half of the keys to the right sibling. */
3421 if ((copy = malloc(txn->mt_env->me_psize)) == NULL)
3424 copy->mp_pgno = mdp->p.mp_pgno;
3425 copy->mp_flags = mdp->p.mp_flags;
3426 copy->mp_lower = PAGEHDRSZ;
3427 copy->mp_upper = txn->mt_env->me_psize;
3429 for (i = j = 0; i <= nkeys; j++) {
3430 if (i == split_indx) {
3431 /* Insert in right sibling. */
3432 /* Reset insert index for right sibling. */
3433 j = (i == newindx && ins_new);
3437 if (i == newindx && !ins_new) {
3438 /* Insert the original entry that caused the split. */
3439 rkey.mv_data = newkey->mv_data;
3440 rkey.mv_size = newkey->mv_size;
3441 if (IS_LEAF(&mdp->p)) {
3442 rdata.mv_data = newdata->mv_data;
3443 rdata.mv_size = newdata->mv_size;
3450 /* Update page and index for the new key. */
3452 if (cptr == &rdp->p)
3454 } else if (i == nkeys) {
3457 node = NODEPTR(&mdp->p, i);
3458 rkey.mv_data = NODEKEY(node);
3459 rkey.mv_size = node->mn_ksize;
3460 if (IS_LEAF(&mdp->p)) {
3461 rdata.mv_data = NODEDATA(node);
3462 rdata.mv_size = node->mn_dsize;
3464 pgno = NODEPGNO(node);
3465 flags = node->mn_flags;
3470 if (!IS_LEAF(&mdp->p) && j == 0) {
3471 /* First branch index doesn't need key data. */
3475 rc = mdb_add_node(txn, dbi, cptr, j, &rkey, &rdata, pgno, flags);
3477 nkeys = NUMKEYS(copy);
3478 for (i=0; i<nkeys; i++)
3479 mdp->p.mp_ptrs[i] = copy->mp_ptrs[i];
3480 mdp->p.mp_lower = copy->mp_lower;
3481 mdp->p.mp_upper = copy->mp_upper;
3482 memcpy(NODEPTR(&mdp->p, nkeys-1), NODEPTR(copy, nkeys-1),
3483 txn->mt_env->me_psize - copy->mp_upper);
3490 mdb_put0(MDB_txn *txn, MDB_dbi dbi,
3491 MDB_val *key, MDB_val *data, unsigned int flags)
3493 int rc = MDB_SUCCESS, exact;
3497 MDB_val xdata, *rdata, dkey;
3499 char dbuf[PAGESIZE];
3504 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
3505 dbi, DKEY(key), key->mv_size, data->mv_size);
3508 mpp.mp_parent = NULL;
3510 rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp);
3511 if (rc == MDB_SUCCESS) {
3512 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
3513 if (leaf && exact) {
3514 if (flags == MDB_NOOVERWRITE) {
3515 DPRINTF("duplicate key [%s]", DKEY(key));
3516 return MDB_KEYEXIST;
3518 /* there's only a key anyway, so this is a no-op */
3519 if (IS_LEAF2(mpp.mp_page))
3522 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
3523 /* Was a single item before, must convert now */
3524 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3525 dkey.mv_size = NODEDSZ(leaf);
3526 dkey.mv_data = dbuf;
3527 memcpy(dbuf, NODEDATA(leaf), dkey.mv_size);
3528 /* data matches, ignore it */
3529 if (!mdb_dcmp(txn, dbi, data, &dkey))
3530 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
3531 memset(&dummy, 0, sizeof(dummy));
3532 if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED) {
3533 dummy.md_pad = data->mv_size;
3534 dummy.md_flags = MDB_DUPFIXED;
3535 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP)
3536 dummy.md_flags |= MDB_INTEGERKEY;
3538 dummy.md_root = P_INVALID;
3539 if (dkey.mv_size == sizeof(MDB_db)) {
3540 memcpy(NODEDATA(leaf), &dummy, sizeof(dummy));
3543 mdb_del_node(mpp.mp_page, ki, 0);
3546 xdata.mv_size = sizeof(MDB_db);
3547 xdata.mv_data = &dummy;
3552 /* same size, just replace it */
3553 if (!F_ISSET(leaf->mn_flags, F_BIGDATA) &&
3554 NODEDSZ(leaf) == data->mv_size) {
3555 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
3558 mdb_del_node(mpp.mp_page, ki, 0);
3560 if (leaf == NULL) { /* append if not found */
3561 ki = NUMKEYS(mpp.mp_page);
3562 DPRINTF("appending key at index %i", ki);
3564 } else if (rc == MDB_NOTFOUND) {
3566 /* new file, just write a root leaf page */
3567 DPUTS("allocating new root leaf page");
3568 if ((dp = mdb_new_page(txn, dbi, P_LEAF, 1)) == NULL) {
3571 mpp.mp_page = &dp->p;
3572 txn->mt_dbs[dbi].md_root = mpp.mp_page->mp_pgno;
3573 txn->mt_dbs[dbi].md_depth++;
3574 txn->mt_dbxs[dbi].md_dirty = 1;
3575 if ((txn->mt_dbs[dbi].md_flags & (MDB_DUPSORT|MDB_DUPFIXED)) == MDB_DUPFIXED)
3576 mpp.mp_page->mp_flags |= P_LEAF2;
3582 assert(IS_LEAF(mpp.mp_page));
3583 DPRINTF("there are %u keys, should insert new key at index %i",
3584 NUMKEYS(mpp.mp_page), ki);
3589 nsize = IS_LEAF2(mpp.mp_page) ? key->mv_size : mdb_leaf_size(txn->mt_env, key, rdata);
3590 if (SIZELEFT(mpp.mp_page) < nsize) {
3591 rc = mdb_split(txn, dbi, &mpp.mp_page, &ki, key, rdata, P_INVALID);
3593 /* There is room already in this leaf page. */
3594 rc = mdb_add_node(txn, dbi, mpp.mp_page, ki, key, rdata, 0, 0);
3597 if (rc != MDB_SUCCESS)
3598 txn->mt_flags |= MDB_TXN_ERROR;
3600 /* Remember if we just added a subdatabase */
3601 if (flags & F_SUBDATA) {
3602 leaf = NODEPTR(mpp.mp_page, ki);
3603 leaf->mn_flags |= F_SUBDATA;
3606 /* Now store the actual data in the child DB. Note that we're
3607 * storing the user data in the keys field, so there are strict
3608 * size limits on dupdata. The actual data fields of the child
3609 * DB are all zero size.
3614 leaf = NODEPTR(mpp.mp_page, ki);
3616 mdb_xcursor_init0(txn, dbi, &mx);
3617 mdb_xcursor_init1(txn, dbi, &mx, mpp.mp_page, leaf);
3620 if (flags == MDB_NODUPDATA)
3621 flags = MDB_NOOVERWRITE;
3622 /* converted, write the original data first */
3624 rc = mdb_put0(&mx.mx_txn, mx.mx_cursor.mc_dbi, &dkey, &xdata, flags);
3626 leaf->mn_flags |= F_DUPDATA;
3628 rc = mdb_put0(&mx.mx_txn, mx.mx_cursor.mc_dbi, data, &xdata, flags);
3629 mdb_xcursor_fini(txn, dbi, &mx);
3630 memcpy(NODEDATA(leaf), &mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi],
3633 txn->mt_dbs[dbi].md_entries++;
3641 mdb_put(MDB_txn *txn, MDB_dbi dbi,
3642 MDB_val *key, MDB_val *data, unsigned int flags)
3644 assert(key != NULL);
3645 assert(data != NULL);
3647 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3650 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3654 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3658 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA)) != flags)
3661 return mdb_put0(txn, dbi, key, data, flags);
3665 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
3667 #define CHANGEABLE (MDB_NOSYNC)
3668 if ((flag & CHANGEABLE) != flag)
3671 env->me_flags |= flag;
3673 env->me_flags &= ~flag;
3678 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
3683 *arg = env->me_flags;
3688 mdb_env_get_path(MDB_env *env, const char **arg)
3693 *arg = env->me_path;
3698 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
3700 arg->ms_psize = env->me_psize;
3701 arg->ms_depth = db->md_depth;
3702 arg->ms_branch_pages = db->md_branch_pages;
3703 arg->ms_leaf_pages = db->md_leaf_pages;
3704 arg->ms_overflow_pages = db->md_overflow_pages;
3705 arg->ms_entries = db->md_entries;
3710 mdb_env_stat(MDB_env *env, MDB_stat *arg)
3714 if (env == NULL || arg == NULL)
3717 mdb_env_read_meta(env, &toggle);
3719 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
3722 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
3732 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
3733 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
3737 /* Is the DB already open? */
3739 for (i=2; i<txn->mt_numdbs; i++) {
3740 if (len == txn->mt_dbxs[i].md_name.mv_size &&
3741 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
3747 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
3750 /* Find the DB info */
3752 key.mv_data = (void *)name;
3753 rc = mdb_get(txn, MAIN_DBI, &key, &data);
3755 /* Create if requested */
3756 if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
3758 data.mv_size = sizeof(MDB_db);
3759 data.mv_data = &dummy;
3760 memset(&dummy, 0, sizeof(dummy));
3761 dummy.md_root = P_INVALID;
3762 dummy.md_flags = flags & 0xffff;
3763 rc = mdb_put0(txn, MAIN_DBI, &key, &data, F_SUBDATA);
3767 /* OK, got info, add to table */
3768 if (rc == MDB_SUCCESS) {
3769 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
3770 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
3771 txn->mt_dbxs[txn->mt_numdbs].md_cmp = NULL;
3772 txn->mt_dbxs[txn->mt_numdbs].md_dcmp = NULL;
3773 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
3774 txn->mt_dbxs[txn->mt_numdbs].md_parent = MAIN_DBI;
3775 txn->mt_dbxs[txn->mt_numdbs].md_dirty = dirty;
3776 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
3777 *dbi = txn->mt_numdbs;
3778 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
3779 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
3786 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
3788 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
3791 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
3794 void mdb_close(MDB_txn *txn, MDB_dbi dbi)
3797 if (dbi <= MAIN_DBI || dbi >= txn->mt_numdbs)
3799 ptr = txn->mt_dbxs[dbi].md_name.mv_data;
3800 txn->mt_dbxs[dbi].md_name.mv_data = NULL;
3801 txn->mt_dbxs[dbi].md_name.mv_size = 0;
3805 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
3807 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3810 txn->mt_dbxs[dbi].md_cmp = cmp;
3814 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
3816 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3819 txn->mt_dbxs[dbi].md_dcmp = cmp;
3823 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
3825 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3828 txn->mt_dbxs[dbi].md_rel = rel;