2 * @brief memory-mapped database library
4 * A Btree-based database management library modeled loosely on the
5 * BerkeleyDB API, but much simplified.
8 * Copyright 2011 Howard Chu, Symas Corp.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted only as authorized by the OpenLDAP
15 * A copy of this license is available in the file LICENSE in the
16 * top-level directory of the distribution or, alternatively, at
17 * <http://www.OpenLDAP.org/license.html>.
19 * This code is derived from btree.c written by Martin Hedenfalk.
21 * Copyright (c) 2009, 2010 Martin Hedenfalk <martin@bzero.se>
23 * Permission to use, copy, modify, and distribute this software for any
24 * purpose with or without fee is hereby granted, provided that the above
25 * copyright notice and this permission notice appear in all copies.
27 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
28 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
29 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
30 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
31 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
32 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
33 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
35 #include <sys/types.h>
37 #include <sys/param.h>
43 #ifdef HAVE_SYS_FILE_H
66 /** @defgroup internal MDB Internals
69 /** @defgroup compat Windows Compatibility Macros
73 #define pthread_t DWORD
74 #define pthread_mutex_t HANDLE
75 #define pthread_key_t DWORD
76 #define pthread_self() GetCurrentThreadId()
77 #define pthread_key_create(x,y) *(x) = TlsAlloc()
78 #define pthread_key_delete(x) TlsFree(x)
79 #define pthread_getspecific(x) TlsGetValue(x)
80 #define pthread_setspecific(x,y) TlsSetValue(x,y)
81 #define pthread_mutex_unlock(x) ReleaseMutex(x)
82 #define pthread_mutex_lock(x) WaitForSingleObject(x, INFINITE)
83 #define LOCK_MUTEX_R(env) pthread_mutex_lock(env->me_rmutex)
84 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(env->me_rmutex)
85 #define LOCK_MUTEX_W(env) pthread_mutex_lock(env->me_wmutex)
86 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(env->me_wmutex)
87 #define getpid() GetCurrentProcessId()
88 #define fdatasync(fd) !FlushFileBuffers(fd)
89 #define ErrCode() GetLastError()
90 #define GetPageSize(x) {SYSTEM_INFO si; GetSystemInfo(&si); (x) = si.dwPageSize;}
91 #define close(fd) CloseHandle(fd)
92 #define munmap(ptr,len) UnmapViewOfFile(ptr)
94 #define LOCK_MUTEX_R(env) pthread_mutex_lock(&env->me_txns->mti_mutex)
95 #define UNLOCK_MUTEX_R(env) pthread_mutex_unlock(&env->me_txns->mti_mutex)
96 #define LOCK_MUTEX_W(env) pthread_mutex_lock(&env->me_txns->mti_wmutex)
97 #define UNLOCK_MUTEX_W(env) pthread_mutex_unlock(&env->me_txns->mti_wmutex)
98 #define ErrCode() errno
100 #define INVALID_HANDLE_VALUE -1
101 #define GetPageSize(x) (x) = sysconf(_SC_PAGE_SIZE)
107 /* Note: If O_DSYNC is undefined but exists in /usr/include,
108 * preferably set some compiler flag to get the definition.
109 * Otherwise compile with the less efficient -DMDB_DSYNC=O_SYNC.
112 # define MDB_DSYNC O_DSYNC
116 typedef ULONG pgno_t;
122 #if !(__STDC_VERSION__ >= 199901L || defined(__GNUC__))
123 # define DPRINTF (void) /* Vararg macros may be unsupported */
125 # define DPRINTF(fmt, ...) /* Requires 2 or more args */ \
126 fprintf(stderr, "%s:%d:(%p) " fmt "\n", __func__, __LINE__, pthread_self(), __VA_ARGS__)
128 # define DPRINTF(fmt, ...) ((void) 0)
130 #define DPUTS(arg) DPRINTF("%s", arg)
132 #define PAGESIZE 4096
133 #define MDB_MINKEYS 2
134 #define MDB_MAGIC 0xBEEFC0DE
135 #define MDB_VERSION 1
136 #define MAXKEYSIZE 511
138 #define KBUF (MAXKEYSIZE*2+1)
139 #define DKBUF char kbuf[KBUF]
140 #define DKEY(x) mdb_dkey(x, kbuf)
146 /* The DB view is always consistent because all writes are wrapped in
147 * the wmutex. Finer-grained locks aren't necessary.
153 #define LAZY_MUTEX_LOCK(x)
154 #define LAZY_MUTEX_UNLOCK(x)
155 #define LAZY_RWLOCK_UNLOCK(x)
156 #define LAZY_RWLOCK_WRLOCK(x)
157 #define LAZY_RWLOCK_RDLOCK(x)
158 #define LAZY_RWLOCK_DEF(x)
159 #define LAZY_RWLOCK_INIT(x,y)
160 #define LAZY_RWLOCK_DESTROY(x)
162 #define LAZY_MUTEX_LOCK(x) pthread_mutex_lock(x)
163 #define LAZY_MUTEX_UNLOCK(x) pthread_mutex_unlock(x)
164 #define LAZY_RWLOCK_UNLOCK(x) pthread_rwlock_unlock(x)
165 #define LAZY_RWLOCK_WRLOCK(x) pthread_rwlock_wrlock(x)
166 #define LAZY_RWLOCK_RDLOCK(x) pthread_rwlock_rdlock(x)
167 #define LAZY_RWLOCK_DEF(x) pthread_rwlock_t x
168 #define LAZY_RWLOCK_INIT(x,y) pthread_rwlock_init(x,y)
169 #define LAZY_RWLOCK_DESTROY(x) pthread_rwlock_destroy(x)
172 #define P_INVALID (~0UL)
174 #define F_ISSET(w, f) (((w) & (f)) == (f))
176 typedef uint16_t indx_t;
178 #define DEFAULT_READERS 126
179 #define DEFAULT_MAPSIZE 1048576
181 /* Lock descriptor stuff */
183 #define CACHELINE 64 /* most CPUs. Itanium uses 128 */
186 typedef struct MDB_rxbody {
192 typedef struct MDB_reader {
195 #define mr_txnid mru.mrx.mrb_txnid
196 #define mr_pid mru.mrx.mrb_pid
197 #define mr_tid mru.mrx.mrb_tid
198 /* cache line alignment */
199 char pad[(sizeof(MDB_rxbody)+CACHELINE-1) & ~(CACHELINE-1)];
203 typedef struct MDB_txbody {
205 uint32_t mtb_version;
206 /* For POSIX the actual mutexes reside in shared memory.
207 * On Windows, mutexes are allocated by the kernel; we store
208 * the name in shared memory so that other processes can
214 pthread_mutex_t mtb_mutex;
217 uint32_t mtb_numreaders;
218 uint32_t mtb_me_toggle;
221 typedef struct MDB_txninfo {
224 #define mti_magic mt1.mtb.mtb_magic
225 #define mti_version mt1.mtb.mtb_version
226 #define mti_mutex mt1.mtb.mtb_mutex
227 #define mti_rmname mt1.mtb.mtb_rmname
228 #define mti_txnid mt1.mtb.mtb_txnid
229 #define mti_numreaders mt1.mtb.mtb_numreaders
230 #define mti_me_toggle mt1.mtb.mtb_me_toggle
231 char pad[(sizeof(MDB_txbody)+CACHELINE-1) & ~(CACHELINE-1)];
236 #define mti_wmname mt2.mt2_wmname
238 pthread_mutex_t mt2_wmutex;
239 #define mti_wmutex mt2.mt2_wmutex
241 char pad[(sizeof(pthread_mutex_t)+CACHELINE-1) & ~(CACHELINE-1)];
243 MDB_reader mti_readers[1];
246 /* Common header for all page types. Overflow pages
247 * occupy a number of contiguous pages with no
248 * headers on any page after the first.
250 typedef struct MDB_page { /* represents a page of storage */
251 #define mp_pgno mp_p.p_pgno
253 pgno_t p_pgno; /* page number */
254 void * p_align; /* for IL32P64 */
256 #define P_BRANCH 0x01 /* branch page */
257 #define P_LEAF 0x02 /* leaf page */
258 #define P_OVERFLOW 0x04 /* overflow page */
259 #define P_META 0x08 /* meta page */
260 #define P_DIRTY 0x10 /* dirty page */
261 #define P_LEAF2 0x20 /* DB with small, fixed size keys and no data */
263 #define mp_lower mp_pb.pb.pb_lower
264 #define mp_upper mp_pb.pb.pb_upper
265 #define mp_pages mp_pb.pb_pages
268 indx_t pb_lower; /* lower bound of free space */
269 indx_t pb_upper; /* upper bound of free space */
271 uint32_t pb_pages; /* number of overflow pages */
273 indx_t mp_ptrs[1]; /* dynamic size */
276 #define PAGEHDRSZ ((unsigned) offsetof(MDB_page, mp_ptrs))
278 #define NUMKEYS(p) (((p)->mp_lower - PAGEHDRSZ) >> 1)
279 #define SIZELEFT(p) (indx_t)((p)->mp_upper - (p)->mp_lower)
280 #define PAGEFILL(env, p) (1000L * ((env)->me_psize - PAGEHDRSZ - SIZELEFT(p)) / \
281 ((env)->me_psize - PAGEHDRSZ))
282 #define IS_LEAF(p) F_ISSET((p)->mp_flags, P_LEAF)
283 #define IS_LEAF2(p) F_ISSET((p)->mp_flags, P_LEAF2)
284 #define IS_BRANCH(p) F_ISSET((p)->mp_flags, P_BRANCH)
285 #define IS_OVERFLOW(p) F_ISSET((p)->mp_flags, P_OVERFLOW)
287 #define OVPAGES(size, psize) ((PAGEHDRSZ-1 + (size)) / (psize) + 1)
289 typedef struct MDB_db {
290 uint32_t md_pad; /* also ksize for LEAF2 pages */
293 ULONG md_branch_pages;
295 ULONG md_overflow_pages;
303 typedef struct MDB_meta { /* meta (footer) page content */
306 void *mm_address; /* address for fixed mapping */
307 size_t mm_mapsize; /* size of mmap region */
308 MDB_db mm_dbs[2]; /* first is free space, 2nd is main db */
309 #define mm_psize mm_dbs[0].md_pad
310 #define mm_flags mm_dbs[0].md_flags
311 pgno_t mm_last_pg; /* last used page in file */
312 ULONG mm_txnid; /* txnid that committed this page */
315 typedef struct MDB_dhead { /* a dirty page */
317 unsigned md_pi; /* parent index */
321 typedef struct MDB_dpage {
326 typedef struct MDB_oldpages {
327 struct MDB_oldpages *mo_next;
329 pgno_t mo_pages[1]; /* dynamic */
332 typedef struct MDB_pageparent {
338 static MDB_dpage *mdb_alloc_page(MDB_txn *txn, MDB_dbi dbi, MDB_page *parent, unsigned int parent_idx, int num);
339 static int mdb_touch(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mp);
341 typedef struct MDB_ppage { /* ordered list of pages */
343 unsigned int mp_ki; /* cursor index on page */
346 #define CURSOR_TOP(c) (&(c)->mc_stack[(c)->mc_snum-1])
347 #define CURSOR_PARENT(c) (&(c)->mc_stack[(c)->mc_snum-2])
348 #define CURSOR_STACK 32
353 struct MDB_xcursor *mc_xcursor;
356 unsigned int mc_snum; /* number of pushed pages */
357 unsigned int mc_flags;
358 #define C_INITIALIZED 0x01
360 #define C_XDIRTY 0x04
361 MDB_ppage mc_stack[CURSOR_STACK]; /* stack of parent pages */
364 #define METADATA(p) ((void *)((char *)(p) + PAGEHDRSZ))
366 typedef struct MDB_node {
367 #define mn_pgno mn_p.np_pgno
368 #define mn_dsize mn_p.np_dsize
370 pgno_t np_pgno; /* child page number */
371 uint32_t np_dsize; /* leaf data size */
373 unsigned int mn_flags:4;
374 unsigned int mn_ksize:12; /* key size */
375 #define F_BIGDATA 0x01 /* data put on overflow page */
376 #define F_SUBDATA 0x02 /* data is a sub-database */
377 #define F_DUPDATA 0x04 /* data has duplicates */
381 typedef struct MDB_dbx {
383 MDB_cmp_func *md_cmp; /* user compare function */
384 MDB_cmp_func *md_dcmp; /* user dupsort function */
385 MDB_rel_func *md_rel; /* user relocate function */
387 unsigned int md_dirty;
391 pgno_t mt_next_pgno; /* next unallocated page */
394 pgno_t *mt_free_pgs; /* this is an IDL */
396 ID2L dirty_list; /* modified pages */
399 MDB_dbx *mt_dbxs; /* array */
401 unsigned int mt_numdbs;
403 #define MDB_TXN_RDONLY 0x01 /* read-only transaction */
404 #define MDB_TXN_ERROR 0x02 /* an error has occurred */
405 unsigned int mt_flags;
406 unsigned int mt_toggle;
409 /* Context for sorted-dup records */
410 typedef struct MDB_xcursor {
411 MDB_cursor mx_cursor;
420 HANDLE me_mfd; /* just for writing the meta pages */
421 #define MDB_FATAL_ERROR 0x80000000U
423 uint32_t me_extrapad; /* unused for now */
424 unsigned int me_maxreaders;
425 unsigned int me_numdbs;
426 unsigned int me_maxdbs;
429 MDB_txninfo *me_txns;
430 MDB_meta *me_metas[2];
431 MDB_txn *me_txn; /* current write transaction */
433 off_t me_size; /* current file size */
434 pgno_t me_maxpg; /* me_mapsize / me_psize */
435 unsigned int me_psize;
436 unsigned int me_db_toggle;
437 MDB_dbx *me_dbxs; /* array */
439 MDB_oldpages *me_pghead;
440 pthread_key_t me_txkey; /* thread-key for readers */
441 MDB_dpage *me_dpages;
442 pgno_t me_free_pgs[MDB_IDL_UM_SIZE];
443 ID2 me_dirty_list[MDB_IDL_DB_SIZE];
444 LAZY_RWLOCK_DEF(me_dblock);
446 HANDLE me_rmutex; /* Windows mutexes don't reside in shared mem */
451 #define NODESIZE offsetof(MDB_node, mn_data)
453 #define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
454 #define LEAFSIZE(k, d) (NODESIZE + (k)->mv_size + (d)->mv_size)
455 #define NODEPTR(p, i) ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
456 #define NODEKEY(node) (void *)((node)->mn_data)
457 #define NODEDATA(node) (void *)((char *)(node)->mn_data + (node)->mn_ksize)
458 #define NODEPGNO(node) ((node)->mn_pgno)
459 #define NODEDSZ(node) ((node)->mn_dsize)
460 #define NODEKSZ(node) ((node)->mn_ksize)
461 #define LEAF2KEY(p, i, ks) ((char *)(p) + PAGEHDRSZ + ((i)*(ks)))
463 #define MDB_SET_KEY(node, key) if (key!=NULL) {(key)->mv_size = NODEKSZ(node); (key)->mv_data = NODEKEY(node);}
465 #define MDB_COMMIT_PAGES 64 /* max number of pages to write in one commit */
467 static int mdb_search_page_root(MDB_txn *txn,
468 MDB_dbi dbi, MDB_val *key,
469 MDB_cursor *cursor, int modify,
470 MDB_pageparent *mpp);
471 static int mdb_search_page(MDB_txn *txn,
472 MDB_dbi dbi, MDB_val *key,
473 MDB_cursor *cursor, int modify,
474 MDB_pageparent *mpp);
476 static int mdb_env_read_header(MDB_env *env, MDB_meta *meta);
477 static int mdb_env_read_meta(MDB_env *env, int *which);
478 static int mdb_env_write_meta(MDB_txn *txn);
479 static int mdb_get_page(MDB_txn *txn, pgno_t pgno, MDB_page **mp);
481 static MDB_node *mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp,
482 MDB_val *key, int *exactp, unsigned int *kip);
483 static int mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp,
484 indx_t indx, MDB_val *key, MDB_val *data,
485 pgno_t pgno, uint8_t flags);
486 static void mdb_del_node(MDB_page *mp, indx_t indx, int ksize);
487 static int mdb_del0(MDB_cursor *mc, unsigned int ki,
488 MDB_pageparent *mpp, MDB_node *leaf);
490 static int mdb_put0(MDB_txn *txn, MDB_dbi dbi,
491 MDB_val *key, MDB_val *data, unsigned int flags);
493 static int mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data);
495 static int mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mp);
496 static int mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
497 static int mdb_move_node(MDB_txn *txn, MDB_dbi dbi,
498 MDB_pageparent *src, indx_t srcindx,
499 MDB_pageparent *dst, indx_t dstindx);
500 static int mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src,
501 MDB_pageparent *dst);
502 static int mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp,
503 unsigned int *newindxp, MDB_val *newkey,
504 MDB_val *newdata, pgno_t newpgno);
505 static MDB_dpage *mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num);
507 static void cursor_pop_page(MDB_cursor *cursor);
508 static MDB_ppage *cursor_push_page(MDB_cursor *cursor,
511 static int mdb_sibling(MDB_cursor *cursor, int move_right);
512 static int mdb_cursor_next(MDB_cursor *cursor,
513 MDB_val *key, MDB_val *data, MDB_cursor_op op);
514 static int mdb_cursor_prev(MDB_cursor *cursor,
515 MDB_val *key, MDB_val *data, MDB_cursor_op op);
516 static int mdb_cursor_set(MDB_cursor *cursor,
517 MDB_val *key, MDB_val *data, MDB_cursor_op op, int *exactp);
518 static int mdb_cursor_first(MDB_cursor *cursor,
519 MDB_val *key, MDB_val *data);
520 static int mdb_cursor_last(MDB_cursor *cursor,
521 MDB_val *key, MDB_val *data);
523 static void mdb_xcursor_init0(MDB_cursor *mc);
524 static void mdb_xcursor_init1(MDB_cursor *mc, MDB_page *mp, MDB_node *node);
525 static void mdb_xcursor_init2(MDB_cursor *mc);
526 static void mdb_xcursor_fini(MDB_cursor *mc);
528 static size_t mdb_leaf_size(MDB_env *env, MDB_val *key,
530 static size_t mdb_branch_size(MDB_env *env, MDB_val *key);
532 static void mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi);
534 static MDB_cmp_func memncmp, memnrcmp, intcmp;
537 static SECURITY_DESCRIPTOR mdb_null_sd;
538 static SECURITY_ATTRIBUTES mdb_all_sa;
539 static int mdb_sec_inited;
543 mdb_version(int *maj, int *min, int *pat)
545 if (maj) *maj = MDB_VERSION_MAJOR;
546 if (min) *min = MDB_VERSION_MINOR;
547 if (pat) *pat = MDB_VERSION_PATCH;
548 return MDB_VERSION_STRING;
551 static char *const mdb_errstr[] = {
552 "MDB_KEYEXIST: Key/data pair already exists",
553 "MDB_NOTFOUND: No matching key/data pair found",
554 "MDB_PAGE_NOTFOUND: Requested page not found",
555 "MDB_CORRUPTED: Located page was wrong type",
556 "MDB_PANIC: Update of meta page failed",
557 "MDB_VERSION_MISMATCH: Database environment version mismatch"
561 mdb_strerror(int err)
564 return ("Successful return: 0");
566 if (err >= MDB_KEYEXIST && err <= MDB_VERSION_MISMATCH)
567 return mdb_errstr[err - MDB_KEYEXIST];
569 return strerror(err);
574 mdb_dkey(MDB_val *key, char *buf)
577 unsigned char *c = key->mv_data;
579 if (key->mv_size > MAXKEYSIZE)
582 for (i=0; i<key->mv_size; i++)
583 ptr += sprintf(ptr, "%02x", *c++);
585 sprintf(buf, "%.*s", key->mv_size, key->mv_data);
592 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
594 return txn->mt_dbxs[dbi].md_cmp(a, b);
598 mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
600 if (txn->mt_dbxs[dbi].md_dcmp)
601 return txn->mt_dbxs[dbi].md_dcmp(a, b);
603 return EINVAL; /* too bad you can't distinguish this from a valid result */
606 /* Allocate new page(s) for writing */
608 mdb_alloc_page(MDB_txn *txn, MDB_dbi dbi, MDB_page *parent, unsigned int parent_idx, int num)
611 pgno_t pgno = P_INVALID;
614 if (txn->mt_txnid > 2) {
616 if (!txn->mt_env->me_pghead && dbi != FREE_DBI &&
617 txn->mt_dbs[FREE_DBI].md_root != P_INVALID) {
618 /* See if there's anything in the free DB */
624 mpp.mp_parent = NULL;
627 mc.mc_dbi = FREE_DBI;
630 mdb_search_page(txn, FREE_DBI, NULL, &mc, 0, &mpp);
631 leaf = NODEPTR(mpp.mp_page, 0);
632 kptr = (ULONG *)NODEKEY(leaf);
636 oldest = txn->mt_txnid - 1;
637 for (i=0; i<txn->mt_env->me_txns->mti_numreaders; i++) {
638 ULONG mr = txn->mt_env->me_txns->mti_readers[i].mr_txnid;
639 if (mr && mr < oldest)
644 if (oldest > *kptr) {
645 /* It's usable, grab it.
652 mdb_read_data(txn, leaf, &data);
653 idl = (ULONG *)data.mv_data;
654 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(idl) - sizeof(pgno_t));
655 mop->mo_next = txn->mt_env->me_pghead;
656 mop->mo_txnid = *kptr;
657 txn->mt_env->me_pghead = mop;
658 memcpy(mop->mo_pages, idl, MDB_IDL_SIZEOF(idl));
663 DPRINTF("IDL read txn %lu root %lu num %lu",
664 mop->mo_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
665 for (i=0; i<idl[0]; i++) {
666 DPRINTF("IDL %lu", idl[i+1]);
670 /* drop this IDL from the DB */
671 top = CURSOR_TOP(&mc);
673 mc.mc_flags = C_INITIALIZED;
674 mdb_cursor_del(&mc, 0);
677 if (txn->mt_env->me_pghead) {
678 MDB_oldpages *mop = txn->mt_env->me_pghead;
680 /* FIXME: For now, always use fresh pages. We
681 * really ought to search the free list for a
686 /* peel pages off tail, so we only have to truncate the list */
687 pgno = MDB_IDL_LAST(mop->mo_pages);
688 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
690 if (mop->mo_pages[2] > mop->mo_pages[1])
691 mop->mo_pages[0] = 0;
695 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
696 txn->mt_env->me_pghead = mop->mo_next;
703 if (pgno == P_INVALID) {
704 /* DB size is maxed out */
705 if (txn->mt_next_pgno + num >= txn->mt_env->me_maxpg)
708 if (txn->mt_env->me_dpages && num == 1) {
709 dp = txn->mt_env->me_dpages;
710 txn->mt_env->me_dpages = (MDB_dpage *)dp->h.md_parent;
712 if ((dp = malloc(txn->mt_env->me_psize * num + sizeof(MDB_dhead))) == NULL)
716 dp->h.md_parent = parent;
717 dp->h.md_pi = parent_idx;
718 if (pgno == P_INVALID) {
719 dp->p.mp_pgno = txn->mt_next_pgno;
720 txn->mt_next_pgno += num;
722 dp->p.mp_pgno = pgno;
724 mid.mid = dp->p.mp_pgno;
726 mdb_mid2l_insert(txn->mt_u.dirty_list, &mid);
731 /* Touch a page: make it dirty and re-insert into tree with updated pgno.
734 mdb_touch(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *pp)
736 MDB_page *mp = pp->mp_page;
741 if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
743 if ((dp = mdb_alloc_page(txn, dbi, pp->mp_parent, pp->mp_pi, 1)) == NULL)
745 DPRINTF("touched db %u page %lu -> %lu", dbi, mp->mp_pgno, dp->p.mp_pgno);
746 assert(mp->mp_pgno != dp->p.mp_pgno);
747 mdb_midl_insert(txn->mt_free_pgs, mp->mp_pgno);
748 pgno = dp->p.mp_pgno;
749 memcpy(&dp->p, mp, txn->mt_env->me_psize);
752 mp->mp_flags |= P_DIRTY;
754 /* Update the page number to new touched page. */
755 if (pp->mp_parent != NULL)
756 NODEPGNO(NODEPTR(pp->mp_parent, pp->mp_pi)) = mp->mp_pgno;
763 mdb_env_sync(MDB_env *env, int force)
766 if (force || !F_ISSET(env->me_flags, MDB_NOSYNC)) {
767 if (fdatasync(env->me_fd))
774 mdb_txn_reset0(MDB_txn *txn);
777 mdb_txn_renew0(MDB_txn *txn)
779 MDB_env *env = txn->mt_env;
781 if (txn->mt_flags & MDB_TXN_RDONLY) {
782 MDB_reader *r = pthread_getspecific(env->me_txkey);
785 pid_t pid = getpid();
786 pthread_t tid = pthread_self();
789 for (i=0; i<env->me_txns->mti_numreaders; i++)
790 if (env->me_txns->mti_readers[i].mr_pid == 0)
792 if (i == env->me_maxreaders) {
796 env->me_txns->mti_readers[i].mr_pid = pid;
797 env->me_txns->mti_readers[i].mr_tid = tid;
798 if (i >= env->me_txns->mti_numreaders)
799 env->me_txns->mti_numreaders = i+1;
801 r = &env->me_txns->mti_readers[i];
802 pthread_setspecific(env->me_txkey, r);
804 txn->mt_txnid = env->me_txns->mti_txnid;
805 txn->mt_toggle = env->me_txns->mti_me_toggle;
806 r->mr_txnid = txn->mt_txnid;
807 txn->mt_u.reader = r;
811 txn->mt_txnid = env->me_txns->mti_txnid+1;
812 txn->mt_toggle = env->me_txns->mti_me_toggle;
813 txn->mt_u.dirty_list = env->me_dirty_list;
814 txn->mt_u.dirty_list[0].mid = 0;
815 txn->mt_free_pgs = env->me_free_pgs;
816 txn->mt_free_pgs[0] = 0;
817 txn->mt_next_pgno = env->me_metas[txn->mt_toggle]->mm_last_pg+1;
821 /* Copy the DB arrays */
822 LAZY_RWLOCK_RDLOCK(&env->me_dblock);
823 txn->mt_numdbs = env->me_numdbs;
824 txn->mt_dbxs = env->me_dbxs; /* mostly static anyway */
825 memcpy(txn->mt_dbs, env->me_metas[txn->mt_toggle]->mm_dbs, 2 * sizeof(MDB_db));
826 if (txn->mt_numdbs > 2)
827 memcpy(txn->mt_dbs+2, env->me_dbs[env->me_db_toggle]+2,
828 (txn->mt_numdbs - 2) * sizeof(MDB_db));
829 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
835 mdb_txn_renew(MDB_txn *txn)
842 if (txn->mt_env->me_flags & MDB_FATAL_ERROR) {
843 DPUTS("environment had fatal error, must shutdown!");
847 rc = mdb_txn_renew0(txn);
848 if (rc == MDB_SUCCESS) {
849 DPRINTF("renew txn %lu%c %p on mdbenv %p, root page %lu",
850 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
851 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
857 mdb_txn_begin(MDB_env *env, unsigned int flags, MDB_txn **ret)
862 if (env->me_flags & MDB_FATAL_ERROR) {
863 DPUTS("environment had fatal error, must shutdown!");
866 if ((txn = calloc(1, sizeof(MDB_txn) + env->me_maxdbs * sizeof(MDB_db))) == NULL) {
867 DPRINTF("calloc: %s", strerror(ErrCode()));
870 txn->mt_dbs = (MDB_db *)(txn+1);
871 if (flags & MDB_RDONLY) {
872 txn->mt_flags |= MDB_TXN_RDONLY;
876 rc = mdb_txn_renew0(txn);
881 DPRINTF("begin txn %lu%c %p on mdbenv %p, root page %lu",
882 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
883 (void *) env, txn->mt_dbs[MAIN_DBI].md_root);
890 mdb_txn_reset0(MDB_txn *txn)
892 MDB_env *env = txn->mt_env;
894 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
895 txn->mt_u.reader->mr_txnid = 0;
901 /* return all dirty pages to dpage list */
902 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
903 dp = txn->mt_u.dirty_list[i].mptr;
904 if (dp->h.md_num == 1) {
905 dp->h.md_parent = (MDB_page *)txn->mt_env->me_dpages;
906 txn->mt_env->me_dpages = dp;
908 /* large pages just get freed directly */
913 while ((mop = txn->mt_env->me_pghead)) {
914 txn->mt_env->me_pghead = mop->mo_next;
919 for (i=2; i<env->me_numdbs; i++)
920 env->me_dbxs[i].md_dirty = 0;
926 mdb_txn_reset(MDB_txn *txn)
931 DPRINTF("reset txn %lu%c %p on mdbenv %p, root page %lu",
932 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
933 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
939 mdb_txn_abort(MDB_txn *txn)
944 DPRINTF("abort txn %lu%c %p on mdbenv %p, root page %lu",
945 txn->mt_txnid, (txn->mt_flags & MDB_TXN_RDONLY) ? 'r' : 'w', txn,
946 (void *)txn->mt_env, txn->mt_dbs[MAIN_DBI].md_root);
953 mdb_txn_commit(MDB_txn *txn)
965 assert(txn->mt_env != NULL);
969 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
974 if (txn != env->me_txn) {
975 DPUTS("attempt to commit unknown transaction");
980 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
981 DPUTS("error flag is set, can't commit");
986 if (!txn->mt_u.dirty_list[0].mid)
989 DPRINTF("committing txn %lu %p on mdbenv %p, root page %lu",
990 txn->mt_txnid, txn, (void *)env, txn->mt_dbs[MAIN_DBI].md_root);
993 mc.mc_dbi = FREE_DBI;
996 /* should only be one record now */
997 if (env->me_pghead) {
1000 /* make sure first page of freeDB is touched and on freelist */
1001 mpp.mp_parent = NULL;
1004 mdb_search_page(txn, FREE_DBI, NULL, &mc, 1, &mpp);
1006 /* save to free list */
1007 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
1012 /* make sure last page of freeDB is touched and on freelist */
1013 key.mv_size = MAXKEYSIZE+1;
1015 mpp.mp_parent = NULL;
1018 mdb_search_page(txn, FREE_DBI, &key, &mc, 1, &mpp);
1023 ULONG *idl = txn->mt_free_pgs;
1024 DPRINTF("IDL write txn %lu root %lu num %lu",
1025 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1026 for (i=0; i<idl[0]; i++) {
1027 DPRINTF("IDL %lu", idl[i+1]);
1031 /* write to last page of freeDB */
1032 key.mv_size = sizeof(pgno_t);
1033 key.mv_data = (char *)&txn->mt_txnid;
1034 data.mv_data = txn->mt_free_pgs;
1035 /* The free list can still grow during this call,
1036 * despite the pre-emptive touches above. So check
1037 * and make sure the entire thing got written.
1040 i = txn->mt_free_pgs[0];
1041 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
1042 rc = mdb_cursor_put(&mc, &key, &data, 0);
1047 } while (i != txn->mt_free_pgs[0]);
1049 /* should only be one record now */
1050 if (env->me_pghead) {
1054 mop = env->me_pghead;
1055 key.mv_size = sizeof(pgno_t);
1056 key.mv_data = (char *)&mop->mo_txnid;
1057 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
1058 data.mv_data = mop->mo_pages;
1059 mdb_cursor_put(&mc, &key, &data, 0);
1060 free(env->me_pghead);
1061 env->me_pghead = NULL;
1064 /* Update DB root pointers. Their pages have already been
1065 * touched so this is all in-place and cannot fail.
1069 data.mv_size = sizeof(MDB_db);
1071 mc.mc_dbi = MAIN_DBI;
1073 for (i = 2; i < txn->mt_numdbs; i++) {
1074 if (txn->mt_dbxs[i].md_dirty) {
1075 data.mv_data = &txn->mt_dbs[i];
1076 mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
1081 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
1087 /* Windows actually supports scatter/gather I/O, but only on
1088 * unbuffered file handles. Since we're relying on the OS page
1089 * cache for all our data, that's self-defeating. So we just
1090 * write pages one at a time. We use the ov structure to set
1091 * the write offset, to at least save the overhead of a Seek
1095 memset(&ov, 0, sizeof(ov));
1096 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1097 dp = txn->mt_u.dirty_list[i].mptr;
1098 DPRINTF("committing page %lu", dp->p.mp_pgno);
1099 size = dp->p.mp_pgno * env->me_psize;
1100 ov.Offset = size & 0xffffffff;
1101 ov.OffsetHigh = size >> 16;
1102 ov.OffsetHigh >>= 16;
1103 /* clear dirty flag */
1104 dp->p.mp_flags &= ~P_DIRTY;
1105 rc = WriteFile(env->me_fd, &dp->p, env->me_psize * dp->h.md_num, NULL, &ov);
1108 DPRINTF("WriteFile: %d", n);
1115 struct iovec iov[MDB_COMMIT_PAGES];
1119 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1120 dp = txn->mt_u.dirty_list[i].mptr;
1121 if (dp->p.mp_pgno != next) {
1123 DPRINTF("committing %u dirty pages", n);
1124 rc = writev(env->me_fd, iov, n);
1128 DPUTS("short write, filesystem full?");
1130 DPRINTF("writev: %s", strerror(n));
1137 lseek(env->me_fd, dp->p.mp_pgno * env->me_psize, SEEK_SET);
1138 next = dp->p.mp_pgno;
1140 DPRINTF("committing page %lu", dp->p.mp_pgno);
1141 iov[n].iov_len = env->me_psize * dp->h.md_num;
1142 iov[n].iov_base = &dp->p;
1143 size += iov[n].iov_len;
1144 next = dp->p.mp_pgno + dp->h.md_num;
1145 /* clear dirty flag */
1146 dp->p.mp_flags &= ~P_DIRTY;
1147 if (++n >= MDB_COMMIT_PAGES) {
1157 DPRINTF("committing %u dirty pages", n);
1158 rc = writev(env->me_fd, iov, n);
1162 DPUTS("short write, filesystem full?");
1164 DPRINTF("writev: %s", strerror(n));
1171 /* Drop the dirty pages.
1173 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1174 dp = txn->mt_u.dirty_list[i].mptr;
1175 if (dp->h.md_num == 1) {
1176 dp->h.md_parent = (MDB_page *)txn->mt_env->me_dpages;
1177 txn->mt_env->me_dpages = dp;
1181 txn->mt_u.dirty_list[i].mid = 0;
1183 txn->mt_u.dirty_list[0].mid = 0;
1185 if ((n = mdb_env_sync(env, 0)) != 0 ||
1186 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
1193 /* update the DB tables */
1195 int toggle = !env->me_db_toggle;
1198 ip = &env->me_dbs[toggle][2];
1199 jp = &txn->mt_dbs[2];
1200 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1201 for (i = 2; i < txn->mt_numdbs; i++) {
1202 if (ip->md_root != jp->md_root)
1207 for (i = 2; i < txn->mt_numdbs; i++) {
1208 if (txn->mt_dbxs[i].md_dirty)
1209 txn->mt_dbxs[i].md_dirty = 0;
1211 env->me_db_toggle = toggle;
1212 env->me_numdbs = txn->mt_numdbs;
1213 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1216 UNLOCK_MUTEX_W(env);
1223 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
1225 char page[PAGESIZE];
1230 /* We don't know the page size yet, so use a minimum value.
1234 if (!ReadFile(env->me_fd, page, PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
1236 if ((rc = read(env->me_fd, page, PAGESIZE)) == 0)
1241 else if (rc != PAGESIZE) {
1245 DPRINTF("read: %s", strerror(err));
1249 p = (MDB_page *)page;
1251 if (!F_ISSET(p->mp_flags, P_META)) {
1252 DPRINTF("page %lu not a meta page", p->mp_pgno);
1257 if (m->mm_magic != MDB_MAGIC) {
1258 DPUTS("meta has invalid magic");
1262 if (m->mm_version != MDB_VERSION) {
1263 DPRINTF("database is version %u, expected version %u",
1264 m->mm_version, MDB_VERSION);
1265 return MDB_VERSION_MISMATCH;
1268 memcpy(meta, m, sizeof(*m));
1273 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
1280 DPUTS("writing new meta page");
1284 meta->mm_magic = MDB_MAGIC;
1285 meta->mm_version = MDB_VERSION;
1286 meta->mm_psize = psize;
1287 meta->mm_last_pg = 1;
1288 meta->mm_flags = env->me_flags & 0xffff;
1289 meta->mm_flags |= MDB_INTEGERKEY;
1290 meta->mm_dbs[0].md_root = P_INVALID;
1291 meta->mm_dbs[1].md_root = P_INVALID;
1293 p = calloc(2, psize);
1295 p->mp_flags = P_META;
1298 memcpy(m, meta, sizeof(*meta));
1300 q = (MDB_page *)((char *)p + psize);
1303 q->mp_flags = P_META;
1306 memcpy(m, meta, sizeof(*meta));
1311 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
1312 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
1315 rc = write(env->me_fd, p, psize * 2);
1316 rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
1323 mdb_env_write_meta(MDB_txn *txn)
1326 MDB_meta meta, metab;
1328 int rc, len, toggle;
1334 assert(txn != NULL);
1335 assert(txn->mt_env != NULL);
1337 toggle = !txn->mt_toggle;
1338 DPRINTF("writing meta page %d for root page %lu",
1339 toggle, txn->mt_dbs[MAIN_DBI].md_root);
1343 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
1344 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
1346 ptr = (char *)&meta;
1347 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
1348 len = sizeof(MDB_meta) - off;
1351 meta.mm_dbs[0] = txn->mt_dbs[0];
1352 meta.mm_dbs[1] = txn->mt_dbs[1];
1353 meta.mm_last_pg = txn->mt_next_pgno - 1;
1354 meta.mm_txnid = txn->mt_txnid;
1357 off += env->me_psize;
1360 /* Write to the SYNC fd */
1363 memset(&ov, 0, sizeof(ov));
1365 WriteFile(env->me_mfd, ptr, len, (DWORD *)&rc, &ov);
1368 rc = pwrite(env->me_mfd, ptr, len, off);
1373 DPUTS("write failed, disk error?");
1374 /* On a failure, the pagecache still contains the new data.
1375 * Write some old data back, to prevent it from being used.
1376 * Use the non-SYNC fd; we know it will fail anyway.
1378 meta.mm_last_pg = metab.mm_last_pg;
1379 meta.mm_txnid = metab.mm_txnid;
1381 WriteFile(env->me_fd, ptr, len, NULL, &ov);
1383 r2 = pwrite(env->me_fd, ptr, len, off);
1385 env->me_flags |= MDB_FATAL_ERROR;
1388 /* Memory ordering issues are irrelevant; since the entire writer
1389 * is wrapped by wmutex, all of these changes will become visible
1390 * after the wmutex is unlocked. Since the DB is multi-version,
1391 * readers will get consistent data regardless of how fresh or
1392 * how stale their view of these values is.
1394 LAZY_MUTEX_LOCK(&env->me_txns->mti_mutex);
1395 txn->mt_env->me_txns->mti_me_toggle = toggle;
1396 txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
1397 LAZY_MUTEX_UNLOCK(&env->me_txns->mti_mutex);
1403 mdb_env_read_meta(MDB_env *env, int *which)
1407 assert(env != NULL);
1409 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1412 DPRINTF("Using meta page %d", toggle);
1419 mdb_env_create(MDB_env **env)
1423 e = calloc(1, sizeof(MDB_env));
1424 if (!e) return ENOMEM;
1426 e->me_maxreaders = DEFAULT_READERS;
1428 e->me_fd = INVALID_HANDLE_VALUE;
1429 e->me_lfd = INVALID_HANDLE_VALUE;
1430 e->me_mfd = INVALID_HANDLE_VALUE;
1436 mdb_env_set_mapsize(MDB_env *env, size_t size)
1440 env->me_mapsize = size;
1445 mdb_env_set_maxdbs(MDB_env *env, int dbs)
1449 env->me_maxdbs = dbs;
1454 mdb_env_set_maxreaders(MDB_env *env, int readers)
1458 env->me_maxreaders = readers;
1463 mdb_env_get_maxreaders(MDB_env *env, int *readers)
1465 if (!env || !readers)
1467 *readers = env->me_maxreaders;
1472 mdb_env_open2(MDB_env *env, unsigned int flags)
1474 int i, newenv = 0, toggle;
1478 env->me_flags = flags;
1480 memset(&meta, 0, sizeof(meta));
1482 if ((i = mdb_env_read_header(env, &meta)) != 0) {
1485 DPUTS("new mdbenv");
1489 if (!env->me_mapsize) {
1490 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
1496 LONG sizelo, sizehi;
1497 sizelo = env->me_mapsize & 0xffffffff;
1498 sizehi = env->me_mapsize >> 16; /* pointless on WIN32, only needed on W64 */
1500 /* Windows won't create mappings for zero length files.
1501 * Just allocate the maxsize right now.
1504 SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
1505 if (!SetEndOfFile(env->me_fd))
1507 SetFilePointer(env->me_fd, 0, NULL, 0);
1509 mh = CreateFileMapping(env->me_fd, NULL, PAGE_READONLY,
1510 sizehi, sizelo, NULL);
1513 env->me_map = MapViewOfFileEx(mh, FILE_MAP_READ, 0, 0, env->me_mapsize,
1521 if (meta.mm_address && (flags & MDB_FIXEDMAP))
1523 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
1525 if (env->me_map == MAP_FAILED)
1530 meta.mm_mapsize = env->me_mapsize;
1531 if (flags & MDB_FIXEDMAP)
1532 meta.mm_address = env->me_map;
1533 i = mdb_env_init_meta(env, &meta);
1534 if (i != MDB_SUCCESS) {
1535 munmap(env->me_map, env->me_mapsize);
1539 env->me_psize = meta.mm_psize;
1541 env->me_maxpg = env->me_mapsize / env->me_psize;
1543 p = (MDB_page *)env->me_map;
1544 env->me_metas[0] = METADATA(p);
1545 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
1547 if ((i = mdb_env_read_meta(env, &toggle)) != 0)
1550 DPRINTF("opened database version %u, pagesize %u",
1551 env->me_metas[toggle]->mm_version, env->me_psize);
1552 DPRINTF("depth: %u", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_depth);
1553 DPRINTF("entries: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_entries);
1554 DPRINTF("branch pages: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_branch_pages);
1555 DPRINTF("leaf pages: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_leaf_pages);
1556 DPRINTF("overflow pages: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_overflow_pages);
1557 DPRINTF("root: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_root);
1563 /* Windows doesn't support destructor callbacks for thread-specific storage */
1565 mdb_env_reader_dest(void *ptr)
1567 MDB_reader *reader = ptr;
1569 reader->mr_txnid = 0;
1575 /* downgrade the exclusive lock on the region back to shared */
1577 mdb_env_share_locks(MDB_env *env)
1581 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1583 env->me_txns->mti_me_toggle = toggle;
1584 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
1589 /* First acquire a shared lock. The Unlock will
1590 * then release the existing exclusive lock.
1592 memset(&ov, 0, sizeof(ov));
1593 LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov);
1594 UnlockFile(env->me_lfd, 0, 0, 1, 0);
1598 struct flock lock_info;
1599 /* The shared lock replaces the existing lock */
1600 memset((void *)&lock_info, 0, sizeof(lock_info));
1601 lock_info.l_type = F_RDLCK;
1602 lock_info.l_whence = SEEK_SET;
1603 lock_info.l_start = 0;
1604 lock_info.l_len = 1;
1605 fcntl(env->me_lfd, F_SETLK, &lock_info);
1611 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
1619 if ((env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
1620 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
1621 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
1625 /* Try to get exclusive lock. If we succeed, then
1626 * nobody is using the lock region and we should initialize it.
1629 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
1633 memset(&ov, 0, sizeof(ov));
1634 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
1640 size = GetFileSize(env->me_lfd, NULL);
1642 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
1646 /* Try to get exclusive lock. If we succeed, then
1647 * nobody is using the lock region and we should initialize it.
1650 struct flock lock_info;
1651 memset((void *)&lock_info, 0, sizeof(lock_info));
1652 lock_info.l_type = F_WRLCK;
1653 lock_info.l_whence = SEEK_SET;
1654 lock_info.l_start = 0;
1655 lock_info.l_len = 1;
1656 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1660 lock_info.l_type = F_RDLCK;
1661 rc = fcntl(env->me_lfd, F_SETLKW, &lock_info);
1668 size = lseek(env->me_lfd, 0, SEEK_END);
1670 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1671 if (size < rsize && *excl) {
1673 SetFilePointer(env->me_lfd, rsize, NULL, 0);
1674 if (!SetEndOfFile(env->me_lfd)) {
1679 if (ftruncate(env->me_lfd, rsize) != 0) {
1686 size = rsize - sizeof(MDB_txninfo);
1687 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
1692 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
1698 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
1700 if (!env->me_txns) {
1706 env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
1708 if (env->me_txns == MAP_FAILED) {
1716 if (!mdb_sec_inited) {
1717 InitializeSecurityDescriptor(&mdb_null_sd,
1718 SECURITY_DESCRIPTOR_REVISION);
1719 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
1720 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
1721 mdb_all_sa.bInheritHandle = FALSE;
1722 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
1725 /* FIXME: only using up to 20 characters of the env path here,
1726 * probably not enough to assure uniqueness...
1728 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%.20s", lpath);
1729 ptr = env->me_txns->mti_rmname + sizeof("Global\\MDBr");
1730 while ((ptr = strchr(ptr, '\\')))
1732 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
1733 if (!env->me_rmutex) {
1737 sprintf(env->me_txns->mti_rmname, "Global\\MDBw%.20s", lpath);
1738 ptr = env->me_txns->mti_rmname + sizeof("Global\\MDBw");
1739 while ((ptr = strchr(ptr, '\\')))
1741 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
1742 if (!env->me_wmutex) {
1747 pthread_mutexattr_t mattr;
1749 pthread_mutexattr_init(&mattr);
1750 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
1754 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
1755 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
1757 env->me_txns->mti_version = MDB_VERSION;
1758 env->me_txns->mti_magic = MDB_MAGIC;
1759 env->me_txns->mti_txnid = 0;
1760 env->me_txns->mti_numreaders = 0;
1761 env->me_txns->mti_me_toggle = 0;
1764 if (env->me_txns->mti_magic != MDB_MAGIC) {
1765 DPUTS("lock region has invalid magic");
1769 if (env->me_txns->mti_version != MDB_VERSION) {
1770 DPRINTF("lock region is version %u, expected version %u",
1771 env->me_txns->mti_version, MDB_VERSION);
1772 rc = MDB_VERSION_MISMATCH;
1776 if (rc != EACCES && rc != EAGAIN) {
1780 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
1781 if (!env->me_rmutex) {
1785 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
1786 if (!env->me_wmutex) {
1796 env->me_lfd = INVALID_HANDLE_VALUE;
1801 #define LOCKNAME "/lock.mdb"
1802 #define DATANAME "/data.mdb"
1804 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
1806 int oflags, rc, len, excl;
1807 char *lpath, *dpath;
1810 lpath = malloc(len + sizeof(LOCKNAME) + len + sizeof(DATANAME));
1813 dpath = lpath + len + sizeof(LOCKNAME);
1814 sprintf(lpath, "%s" LOCKNAME, path);
1815 sprintf(dpath, "%s" DATANAME, path);
1817 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
1822 if (F_ISSET(flags, MDB_RDONLY)) {
1823 oflags = GENERIC_READ;
1824 len = OPEN_EXISTING;
1826 oflags = GENERIC_READ|GENERIC_WRITE;
1829 mode = FILE_ATTRIBUTE_NORMAL;
1830 if ((env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
1831 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
1836 if (F_ISSET(flags, MDB_RDONLY))
1839 oflags = O_RDWR | O_CREAT;
1841 if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
1847 if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
1848 /* synchronous fd for meta writes */
1850 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
1851 mode |= FILE_FLAG_WRITE_THROUGH;
1852 if ((env->me_mfd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
1853 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
1858 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
1859 oflags |= MDB_DSYNC;
1860 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
1865 env->me_path = strdup(path);
1866 DPRINTF("opened dbenv %p", (void *) env);
1867 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
1868 LAZY_RWLOCK_INIT(&env->me_dblock, NULL);
1870 mdb_env_share_locks(env);
1871 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
1872 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
1873 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
1879 if (env->me_fd != INVALID_HANDLE_VALUE) {
1881 env->me_fd = INVALID_HANDLE_VALUE;
1883 if (env->me_lfd != INVALID_HANDLE_VALUE) {
1885 env->me_lfd = INVALID_HANDLE_VALUE;
1893 mdb_env_close(MDB_env *env)
1900 while (env->me_dpages) {
1901 dp = env->me_dpages;
1902 env->me_dpages = (MDB_dpage *)dp->h.md_parent;
1906 free(env->me_dbs[1]);
1907 free(env->me_dbs[0]);
1911 LAZY_RWLOCK_DESTROY(&env->me_dblock);
1912 pthread_key_delete(env->me_txkey);
1915 munmap(env->me_map, env->me_mapsize);
1920 pid_t pid = getpid();
1922 for (i=0; i<env->me_txns->mti_numreaders; i++)
1923 if (env->me_txns->mti_readers[i].mr_pid == pid)
1924 env->me_txns->mti_readers[i].mr_pid = 0;
1925 munmap(env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
1932 intcmp(const MDB_val *a, const MDB_val *b)
1934 if (a->mv_size == sizeof(long))
1936 unsigned long *la, *lb;
1941 unsigned int *ia, *ib;
1949 memncmp(const MDB_val *a, const MDB_val *b)
1955 len_diff = a->mv_size - b->mv_size;
1958 diff = memcmp(a->mv_data, b->mv_data, len);
1959 return diff ? diff : len_diff;
1963 memnrcmp(const MDB_val *a, const MDB_val *b)
1965 const unsigned char *p1, *p2, *p1_lim;
1968 if (b->mv_size == 0)
1969 return a->mv_size != 0;
1970 if (a->mv_size == 0)
1973 p1 = (const unsigned char *)a->mv_data + a->mv_size - 1;
1974 p2 = (const unsigned char *)b->mv_data + b->mv_size - 1;
1976 len_diff = a->mv_size - b->mv_size;
1978 p1_lim = p1 - a->mv_size;
1980 p1_lim = p1 - b->mv_size;
1982 while (p1 >= p1_lim) {
1992 /* Search for key within a leaf page, using binary search.
1993 * Returns the smallest entry larger or equal to the key.
1994 * If exactp is non-null, stores whether the found entry was an exact match
1995 * in *exactp (1 or 0).
1996 * If kip is non-null, stores the index of the found entry in *kip.
1997 * If no entry larger or equal to the key is found, returns NULL.
2000 mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, MDB_val *key,
2001 int *exactp, unsigned int *kip)
2003 unsigned int i = 0, nkeys;
2006 MDB_node *node = NULL;
2011 nkeys = NUMKEYS(mp);
2013 DPRINTF("searching %u keys in %s page %lu",
2014 nkeys, IS_LEAF(mp) ? "leaf" : "branch",
2019 low = IS_LEAF(mp) ? 0 : 1;
2021 cmp = txn->mt_dbxs[dbi].md_cmp;
2023 nodekey.mv_size = txn->mt_dbs[dbi].md_pad;
2024 node = NODEPTR(mp, 0); /* fake */
2026 while (low <= high) {
2027 i = (low + high) >> 1;
2030 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
2032 node = NODEPTR(mp, i);
2034 nodekey.mv_size = node->mn_ksize;
2035 nodekey.mv_data = NODEKEY(node);
2038 rc = cmp(key, &nodekey);
2042 DPRINTF("found leaf index %u [%s], rc = %i",
2043 i, DKEY(&nodekey), rc);
2045 DPRINTF("found branch index %u [%s -> %lu], rc = %i",
2046 i, DKEY(&nodekey), NODEPGNO(node), rc);
2057 if (rc > 0) { /* Found entry is less than the key. */
2058 i++; /* Skip to get the smallest entry larger than key. */
2061 *exactp = (rc == 0);
2062 if (kip) /* Store the key index if requested. */
2065 /* There is no entry larger or equal to the key. */
2068 /* nodeptr is fake for LEAF2 */
2073 cursor_pop_page(MDB_cursor *cursor)
2077 if (cursor->mc_snum) {
2078 top = CURSOR_TOP(cursor);
2081 DPRINTF("popped page %lu off db %u cursor %p", top->mp_page->mp_pgno,
2082 cursor->mc_dbi, (void *) cursor);
2087 cursor_push_page(MDB_cursor *cursor, MDB_page *mp)
2091 DPRINTF("pushing page %lu on db %u cursor %p", mp->mp_pgno,
2092 cursor->mc_dbi, (void *) cursor);
2094 assert(cursor->mc_snum < CURSOR_STACK);
2096 ppage = &cursor->mc_stack[cursor->mc_snum++];
2097 ppage->mp_page = mp;
2103 mdb_get_page(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
2107 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
2110 x = mdb_mid2l_search(txn->mt_u.dirty_list, pgno);
2111 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
2112 dp = txn->mt_u.dirty_list[x].mptr;
2117 if (pgno <= txn->mt_env->me_metas[txn->mt_toggle]->mm_last_pg)
2118 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
2122 DPRINTF("page %lu not found", pgno);
2125 return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
2129 mdb_search_page_root(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
2130 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
2132 MDB_page *mp = mpp->mp_page;
2136 if (cursor && cursor_push_page(cursor, mp) == NULL)
2139 while (IS_BRANCH(mp)) {
2143 DPRINTF("branch page %lu has %u keys", mp->mp_pgno, NUMKEYS(mp));
2144 assert(NUMKEYS(mp) > 1);
2145 DPRINTF("found index 0 to page %lu", NODEPGNO(NODEPTR(mp, 0)));
2147 if (key == NULL) /* Initialize cursor to first page. */
2149 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
2150 /* cursor to last page */
2154 node = mdb_search_node(txn, dbi, mp, key, &exact, &i);
2156 i = NUMKEYS(mp) - 1;
2164 DPRINTF("following index %u for key [%s]",
2166 assert(i < NUMKEYS(mp));
2167 node = NODEPTR(mp, i);
2170 CURSOR_TOP(cursor)->mp_ki = i;
2172 mpp->mp_parent = mp;
2173 if ((rc = mdb_get_page(txn, NODEPGNO(node), &mp)))
2178 if (cursor && cursor_push_page(cursor, mp) == NULL)
2183 if ((rc = mdb_touch(txn, dbi, mpp)) != 0)
2185 dh = ((MDB_dhead *)mpp->mp_page)-1;
2186 dh->md_parent = mpp->mp_parent;
2187 dh->md_pi = mpp->mp_pi;
2194 DPRINTF("internal error, index points to a %02X page!?",
2196 return MDB_CORRUPTED;
2199 DPRINTF("found leaf page %lu for key [%s]", mp->mp_pgno,
2200 key ? DKEY(key) : NULL);
2205 /* Search for the page a given key should be in.
2206 * Stores a pointer to the found page in *mpp.
2207 * If key is NULL, search for the lowest page (used by mdb_cursor_first).
2208 * If cursor is non-null, pushes parent pages on the cursor stack.
2209 * If modify is true, visited pages are updated with new page numbers.
2212 mdb_search_page(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
2213 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
2218 /* Choose which root page to start with. If a transaction is given
2219 * use the root page from the transaction, otherwise read the last
2220 * committed root page.
2222 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
2223 DPUTS("transaction has failed, must abort");
2226 root = txn->mt_dbs[dbi].md_root;
2228 if (root == P_INVALID) { /* Tree is empty. */
2229 DPUTS("tree is empty");
2230 return MDB_NOTFOUND;
2233 if ((rc = mdb_get_page(txn, root, &mpp->mp_page)))
2236 DPRINTF("db %u root page %lu has flags 0x%X",
2237 dbi, root, mpp->mp_page->mp_flags);
2240 /* For sub-databases, update main root first */
2241 if (dbi > MAIN_DBI && !txn->mt_dbxs[dbi].md_dirty) {
2243 rc = mdb_search_page(txn, MAIN_DBI, &txn->mt_dbxs[dbi].md_name,
2247 txn->mt_dbxs[dbi].md_dirty = 1;
2249 if (!F_ISSET(mpp->mp_page->mp_flags, P_DIRTY)) {
2250 mpp->mp_parent = NULL;
2252 if ((rc = mdb_touch(txn, dbi, mpp)))
2254 txn->mt_dbs[dbi].md_root = mpp->mp_page->mp_pgno;
2258 return mdb_search_page_root(txn, dbi, key, cursor, modify, mpp);
2262 mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
2264 MDB_page *omp; /* overflow mpage */
2268 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
2269 data->mv_size = leaf->mn_dsize;
2270 data->mv_data = NODEDATA(leaf);
2274 /* Read overflow data.
2276 data->mv_size = leaf->mn_dsize;
2277 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
2278 if ((rc = mdb_get_page(txn, pgno, &omp))) {
2279 DPRINTF("read overflow page %lu failed", pgno);
2282 data->mv_data = METADATA(omp);
2288 mdb_get(MDB_txn *txn, MDB_dbi dbi,
2289 MDB_val *key, MDB_val *data)
2298 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
2300 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
2303 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2310 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
2311 mc.mc_xcursor = &mx;
2312 mdb_xcursor_init0(&mc);
2314 mc.mc_xcursor = NULL;
2316 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
2320 mdb_sibling(MDB_cursor *cursor, int move_right)
2327 if (cursor->mc_snum < 2) {
2328 return MDB_NOTFOUND; /* root has no siblings */
2330 parent = CURSOR_PARENT(cursor);
2332 DPRINTF("parent page is page %lu, index %u",
2333 parent->mp_page->mp_pgno, parent->mp_ki);
2335 cursor_pop_page(cursor);
2336 if (move_right ? (parent->mp_ki + 1 >= NUMKEYS(parent->mp_page))
2337 : (parent->mp_ki == 0)) {
2338 DPRINTF("no more keys left, moving to %s sibling",
2339 move_right ? "right" : "left");
2340 if ((rc = mdb_sibling(cursor, move_right)) != MDB_SUCCESS)
2342 parent = CURSOR_TOP(cursor);
2348 DPRINTF("just moving to %s index key %u",
2349 move_right ? "right" : "left", parent->mp_ki);
2351 assert(IS_BRANCH(parent->mp_page));
2353 indx = NODEPTR(parent->mp_page, parent->mp_ki);
2354 if ((rc = mdb_get_page(cursor->mc_txn, NODEPGNO(indx), &mp)))
2357 mp->parent = parent->mp_page;
2358 mp->parent_index = parent->mp_ki;
2361 cursor_push_page(cursor, mp);
2367 mdb_cursor_next(MDB_cursor *cursor, MDB_val *key, MDB_val *data, MDB_cursor_op op)
2374 if (cursor->mc_flags & C_EOF) {
2375 return MDB_NOTFOUND;
2378 assert(cursor->mc_flags & C_INITIALIZED);
2380 top = CURSOR_TOP(cursor);
2383 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2384 leaf = NODEPTR(mp, top->mp_ki);
2385 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2386 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
2387 rc = mdb_cursor_next(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
2388 if (op != MDB_NEXT || rc == MDB_SUCCESS)
2392 cursor->mc_xcursor->mx_cursor.mc_flags = 0;
2393 if (op == MDB_NEXT_DUP)
2394 return MDB_NOTFOUND;
2398 DPRINTF("cursor_next: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
2400 if (top->mp_ki + 1 >= NUMKEYS(mp)) {
2401 DPUTS("=====> move to next sibling page");
2402 if (mdb_sibling(cursor, 1) != MDB_SUCCESS) {
2403 cursor->mc_flags |= C_EOF;
2404 return MDB_NOTFOUND;
2406 top = CURSOR_TOP(cursor);
2408 DPRINTF("next page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
2412 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
2413 mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
2416 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2417 key->mv_data = LEAF2KEY(mp, top->mp_ki, key->mv_size);
2421 assert(IS_LEAF(mp));
2422 leaf = NODEPTR(mp, top->mp_ki);
2424 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2425 mdb_xcursor_init1(cursor, mp, leaf);
2428 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS))
2431 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2432 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2433 if (rc != MDB_SUCCESS)
2438 MDB_SET_KEY(leaf, key);
2443 mdb_cursor_prev(MDB_cursor *cursor, MDB_val *key, MDB_val *data, MDB_cursor_op op)
2450 assert(cursor->mc_flags & C_INITIALIZED);
2452 top = CURSOR_TOP(cursor);
2455 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2456 leaf = NODEPTR(mp, top->mp_ki);
2457 if (op == MDB_PREV || op == MDB_PREV_DUP) {
2458 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2459 rc = mdb_cursor_prev(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
2460 if (op != MDB_PREV || rc == MDB_SUCCESS)
2463 cursor->mc_xcursor->mx_cursor.mc_flags = 0;
2464 if (op == MDB_PREV_DUP)
2465 return MDB_NOTFOUND;
2470 DPRINTF("cursor_prev: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
2472 if (top->mp_ki == 0) {
2473 DPUTS("=====> move to prev sibling page");
2474 if (mdb_sibling(cursor, 0) != MDB_SUCCESS) {
2475 cursor->mc_flags &= ~C_INITIALIZED;
2476 return MDB_NOTFOUND;
2478 top = CURSOR_TOP(cursor);
2480 top->mp_ki = NUMKEYS(mp) - 1;
2481 DPRINTF("prev page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
2485 cursor->mc_flags &= ~C_EOF;
2487 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
2488 mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
2491 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2492 key->mv_data = LEAF2KEY(mp, top->mp_ki, key->mv_size);
2496 assert(IS_LEAF(mp));
2497 leaf = NODEPTR(mp, top->mp_ki);
2499 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2500 mdb_xcursor_init1(cursor, mp, leaf);
2503 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS))
2506 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2507 rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
2508 if (rc != MDB_SUCCESS)
2513 MDB_SET_KEY(leaf, key);
2518 mdb_cursor_set(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
2519 MDB_cursor_op op, int *exactp)
2529 assert(key->mv_size > 0);
2531 /* See if we're already on the right page */
2532 if (cursor->mc_flags & C_INITIALIZED) {
2535 top = CURSOR_TOP(cursor);
2536 if (top->mp_page->mp_flags & P_LEAF2) {
2537 nodekey.mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2538 nodekey.mv_data = LEAF2KEY(top->mp_page, 0, nodekey.mv_size);
2540 leaf = NODEPTR(top->mp_page, 0);
2541 MDB_SET_KEY(leaf, &nodekey);
2543 rc = cursor->mc_txn->mt_dbxs[cursor->mc_dbi].md_cmp(key, &nodekey);
2546 /* we're already on the right page */
2547 mpp.mp_page = top->mp_page;
2553 if (NUMKEYS(top->mp_page) > 1) {
2554 if (top->mp_page->mp_flags & P_LEAF2) {
2555 nodekey.mv_data = LEAF2KEY(top->mp_page,
2556 NUMKEYS(top->mp_page)-1, nodekey.mv_size);
2558 leaf = NODEPTR(top->mp_page, NUMKEYS(top->mp_page)-1);
2559 MDB_SET_KEY(leaf, &nodekey);
2561 rc = cursor->mc_txn->mt_dbxs[cursor->mc_dbi].md_cmp(key, &nodekey);
2562 if (rc <= 0) goto set1;
2564 /* If any parents have right-sibs, search.
2565 * Otherwise, there's nothing further.
2567 for (i=0; i<cursor->mc_snum-1; i++)
2568 if (cursor->mc_stack[i].mp_ki <
2569 NUMKEYS(cursor->mc_stack[i].mp_page)-1)
2571 if (i == cursor->mc_snum - 1) {
2572 /* There are no other pages */
2578 cursor->mc_snum = 0;
2580 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, key, cursor, 0, &mpp);
2581 if (rc != MDB_SUCCESS)
2584 assert(IS_LEAF(mpp.mp_page));
2586 top = CURSOR_TOP(cursor);
2588 leaf = mdb_search_node(cursor->mc_txn, cursor->mc_dbi, mpp.mp_page, key, exactp, &top->mp_ki);
2589 if (exactp != NULL && !*exactp) {
2590 /* MDB_SET specified and not an exact match. */
2591 return MDB_NOTFOUND;
2595 DPUTS("===> inexact leaf not found, goto sibling");
2596 if ((rc = mdb_sibling(cursor, 1)) != MDB_SUCCESS)
2597 return rc; /* no entries matched */
2598 top = CURSOR_TOP(cursor);
2600 mpp.mp_page = top->mp_page;
2601 assert(IS_LEAF(mpp.mp_page));
2602 leaf = NODEPTR(mpp.mp_page, 0);
2605 cursor->mc_flags |= C_INITIALIZED;
2606 cursor->mc_flags &= ~C_EOF;
2608 if (IS_LEAF2(mpp.mp_page)) {
2609 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2610 key->mv_data = LEAF2KEY(mpp.mp_page, top->mp_ki, key->mv_size);
2614 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2615 mdb_xcursor_init1(cursor, mpp.mp_page, leaf);
2618 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2619 if (op == MDB_SET || op == MDB_SET_RANGE) {
2620 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2623 if (op == MDB_GET_BOTH) {
2629 rc = mdb_cursor_set(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
2630 if (rc != MDB_SUCCESS)
2633 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
2635 if ((rc = mdb_read_data(cursor->mc_txn, leaf, &d2)) != MDB_SUCCESS)
2637 rc = cursor->mc_txn->mt_dbxs[cursor->mc_dbi].md_cmp(data, &d2);
2639 if (op == MDB_GET_BOTH || rc > 0)
2640 return MDB_NOTFOUND;
2644 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2649 /* The key already matches in all other cases */
2650 if (op == MDB_SET_RANGE)
2651 MDB_SET_KEY(leaf, key);
2652 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
2658 mdb_cursor_first(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
2664 cursor->mc_snum = 0;
2666 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, NULL, cursor, 0, &mpp);
2667 if (rc != MDB_SUCCESS)
2669 assert(IS_LEAF(mpp.mp_page));
2671 leaf = NODEPTR(mpp.mp_page, 0);
2672 cursor->mc_flags |= C_INITIALIZED;
2673 cursor->mc_flags &= ~C_EOF;
2675 if (IS_LEAF2(mpp.mp_page)) {
2676 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2677 key->mv_data = LEAF2KEY(mpp.mp_page, 0, key->mv_size);
2682 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2683 mdb_xcursor_init1(cursor, mpp.mp_page, leaf);
2684 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2688 if (cursor->mc_xcursor)
2689 cursor->mc_xcursor->mx_cursor.mc_flags = 0;
2690 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2694 MDB_SET_KEY(leaf, key);
2699 mdb_cursor_last(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
2707 cursor->mc_snum = 0;
2709 lkey.mv_size = MAXKEYSIZE+1;
2710 lkey.mv_data = NULL;
2712 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, &lkey, cursor, 0, &mpp);
2713 if (rc != MDB_SUCCESS)
2715 assert(IS_LEAF(mpp.mp_page));
2717 leaf = NODEPTR(mpp.mp_page, NUMKEYS(mpp.mp_page)-1);
2718 cursor->mc_flags |= C_INITIALIZED;
2719 cursor->mc_flags &= ~C_EOF;
2721 top = CURSOR_TOP(cursor);
2722 top->mp_ki = NUMKEYS(top->mp_page) - 1;
2724 if (IS_LEAF2(mpp.mp_page)) {
2725 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2726 key->mv_data = LEAF2KEY(mpp.mp_page, top->mp_ki, key->mv_size);
2731 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2732 mdb_xcursor_init1(cursor, mpp.mp_page, leaf);
2733 rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
2737 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2742 MDB_SET_KEY(leaf, key);
2747 mdb_cursor_get(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
2757 case MDB_GET_BOTH_RANGE:
2758 if (data == NULL || cursor->mc_xcursor == NULL) {
2765 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2767 } else if (op == MDB_SET_RANGE)
2768 rc = mdb_cursor_set(cursor, key, data, op, NULL);
2770 rc = mdb_cursor_set(cursor, key, data, op, &exact);
2772 case MDB_GET_MULTIPLE:
2774 !(cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPFIXED) ||
2775 !(cursor->mc_flags & C_INITIALIZED)) {
2780 if (!(cursor->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
2781 (cursor->mc_xcursor->mx_cursor.mc_flags & C_EOF))
2784 case MDB_NEXT_MULTIPLE:
2786 !(cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPFIXED)) {
2790 if (!(cursor->mc_flags & C_INITIALIZED))
2791 rc = mdb_cursor_first(cursor, key, data);
2793 rc = mdb_cursor_next(cursor, key, data, MDB_NEXT_DUP);
2794 if (rc == MDB_SUCCESS) {
2795 if (cursor->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
2798 top = CURSOR_TOP(&cursor->mc_xcursor->mx_cursor);
2799 data->mv_size = NUMKEYS(top->mp_page) *
2800 cursor->mc_xcursor->mx_txn.mt_dbs[cursor->mc_xcursor->mx_cursor.mc_dbi].md_pad;
2801 data->mv_data = METADATA(top->mp_page);
2802 top->mp_ki = NUMKEYS(top->mp_page)-1;
2810 case MDB_NEXT_NODUP:
2811 if (!(cursor->mc_flags & C_INITIALIZED))
2812 rc = mdb_cursor_first(cursor, key, data);
2814 rc = mdb_cursor_next(cursor, key, data, op);
2818 case MDB_PREV_NODUP:
2819 if (!(cursor->mc_flags & C_INITIALIZED) || (cursor->mc_flags & C_EOF))
2820 rc = mdb_cursor_last(cursor, key, data);
2822 rc = mdb_cursor_prev(cursor, key, data, op);
2825 rc = mdb_cursor_first(cursor, key, data);
2829 !(cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) ||
2830 !(cursor->mc_flags & C_INITIALIZED) ||
2831 !(cursor->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
2835 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2838 rc = mdb_cursor_last(cursor, key, data);
2842 !(cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) ||
2843 !(cursor->mc_flags & C_INITIALIZED) ||
2844 !(cursor->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
2848 rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
2851 DPRINTF("unhandled/unimplemented cursor operation %u", op);
2860 mdb_cursor_touch(MDB_cursor *mc)
2867 mpp.mp_parent = NULL;
2869 if (mc->mc_dbi > MAIN_DBI && !mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty) {
2870 rc = mdb_search_page(mc->mc_txn, MAIN_DBI, &mc->mc_txn->mt_dbxs[mc->mc_dbi].md_name,
2873 mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty = 1;
2875 for(i=0; i<mc->mc_snum; i++) {
2876 mpp.mp_page = mc->mc_stack[i].mp_page;
2877 if (!F_ISSET(mpp.mp_page->mp_flags, P_DIRTY)) {
2878 rc = mdb_touch(mc->mc_txn, mc->mc_dbi, &mpp);
2880 mc->mc_stack[i].mp_page = mpp.mp_page;
2882 mc->mc_txn->mt_dbs[mc->mc_dbi].md_root = mpp.mp_page->mp_pgno;
2885 dh = ((MDB_dhead *)mpp.mp_page)-1;
2886 dh->md_parent = mpp.mp_parent;
2887 dh->md_pi = mpp.mp_pi;
2888 mpp.mp_parent = mpp.mp_page;
2889 mpp.mp_pi = mc->mc_stack[i].mp_ki;
2895 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
2900 MDB_val xdata, *rdata, dkey;
2902 char dbuf[PAGESIZE];
2908 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
2911 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
2912 mc->mc_dbi, DKEY(key), key->mv_size, data->mv_size);
2916 if (flags == MDB_CURRENT) {
2917 if (!(mc->mc_flags & C_INITIALIZED))
2920 } else if (mc->mc_txn->mt_dbs[mc->mc_dbi].md_root == P_INVALID) {
2922 /* new database, write a root leaf page */
2923 DPUTS("allocating new root leaf page");
2924 if ((dp = mdb_new_page(mc->mc_txn, mc->mc_dbi, P_LEAF, 1)) == NULL) {
2928 cursor_push_page(mc, &dp->p);
2929 mc->mc_txn->mt_dbs[mc->mc_dbi].md_root = dp->p.mp_pgno;
2930 mc->mc_txn->mt_dbs[mc->mc_dbi].md_depth++;
2931 mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty = 1;
2932 if ((mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
2934 dp->p.mp_flags |= P_LEAF2;
2935 mc->mc_flags |= C_INITIALIZED;
2940 rc = mdb_cursor_set(mc, key, NULL, MDB_SET, &exact);
2941 if (flags == MDB_NOOVERWRITE && rc == 0) {
2942 DPRINTF("duplicate key [%s]", DKEY(key));
2943 return MDB_KEYEXIST;
2945 if (rc && rc != MDB_NOTFOUND)
2949 /* Cursor is positioned, now make sure all pages are writable */
2950 rc2 = mdb_cursor_touch(mc);
2951 if (rc2) return rc2;
2954 top = CURSOR_TOP(mc);
2956 /* The key already exists */
2957 if (rc == MDB_SUCCESS) {
2958 /* there's only a key anyway, so this is a no-op */
2959 if (IS_LEAF2(top->mp_page)) {
2960 unsigned int ksize = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
2961 if (key->mv_size != ksize)
2963 if (flags == MDB_CURRENT) {
2964 char *ptr = LEAF2KEY(top->mp_page, top->mp_ki, ksize);
2965 memcpy(ptr, key->mv_data, ksize);
2970 leaf = NODEPTR(top->mp_page, top->mp_ki);
2973 if (F_ISSET(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags, MDB_DUPSORT)) {
2974 /* Was a single item before, must convert now */
2975 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2976 dkey.mv_size = NODEDSZ(leaf);
2977 dkey.mv_data = dbuf;
2978 memcpy(dbuf, NODEDATA(leaf), dkey.mv_size);
2979 /* data matches, ignore it */
2980 if (!mdb_dcmp(mc->mc_txn, mc->mc_dbi, data, &dkey))
2981 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
2982 memset(&dummy, 0, sizeof(dummy));
2983 if (mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPFIXED) {
2984 dummy.md_pad = data->mv_size;
2985 dummy.md_flags = MDB_DUPFIXED;
2986 if (mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_INTEGERDUP)
2987 dummy.md_flags |= MDB_INTEGERKEY;
2989 dummy.md_root = P_INVALID;
2990 if (dkey.mv_size == sizeof(MDB_db)) {
2991 memcpy(NODEDATA(leaf), &dummy, sizeof(dummy));
2994 mdb_del_node(top->mp_page, top->mp_ki, 0);
2997 xdata.mv_size = sizeof(MDB_db);
2998 xdata.mv_data = &dummy;
3003 /* same size, just replace it */
3004 if (!F_ISSET(leaf->mn_flags, F_BIGDATA) &&
3005 NODEDSZ(leaf) == data->mv_size) {
3006 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
3009 mdb_del_node(top->mp_page, top->mp_ki, 0);
3011 DPRINTF("inserting key at index %i", top->mp_ki);
3017 nsize = IS_LEAF2(top->mp_page) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
3018 if (SIZELEFT(top->mp_page) < nsize) {
3019 rc = mdb_split(mc->mc_txn, mc->mc_dbi, &top->mp_page, &top->mp_ki, key, rdata, P_INVALID);
3021 /* There is room already in this leaf page. */
3022 rc = mdb_add_node(mc->mc_txn, mc->mc_dbi, top->mp_page, top->mp_ki, key, rdata, 0, 0);
3025 if (rc != MDB_SUCCESS)
3026 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
3028 /* Remember if we just added a subdatabase */
3029 if (flags & F_SUBDATA) {
3030 leaf = NODEPTR(top->mp_page, top->mp_ki);
3031 leaf->mn_flags |= F_SUBDATA;
3034 /* Now store the actual data in the child DB. Note that we're
3035 * storing the user data in the keys field, so there are strict
3036 * size limits on dupdata. The actual data fields of the child
3037 * DB are all zero size.
3040 leaf = NODEPTR(top->mp_page, top->mp_ki);
3042 if (flags == MDB_CURRENT)
3043 mdb_xcursor_init2(mc);
3045 mdb_xcursor_init1(mc, top->mp_page, leaf);
3048 if (flags == MDB_NODUPDATA)
3049 flags = MDB_NOOVERWRITE;
3050 /* converted, write the original data first */
3052 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, flags);
3054 leaf->mn_flags |= F_DUPDATA;
3056 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, flags);
3057 mdb_xcursor_fini(mc);
3058 memcpy(NODEDATA(leaf),
3059 &mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi],
3062 mc->mc_txn->mt_dbs[mc->mc_dbi].md_entries++;
3069 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
3076 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
3079 if (!mc->mc_flags & C_INITIALIZED)
3082 rc = mdb_cursor_touch(mc);
3085 top = CURSOR_TOP(mc);
3086 leaf = NODEPTR(top->mp_page, top->mp_ki);
3087 mpp.mp_page = top->mp_page;
3088 if (mc->mc_snum > 1) {
3089 MDB_ppage *parent = CURSOR_PARENT(mc);
3090 mpp.mp_parent = parent->mp_page;
3091 mpp.mp_pi = parent->mp_ki;
3093 mpp.mp_parent = NULL;
3097 if (!IS_LEAF2(top->mp_page) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3100 if (flags != MDB_NODUPDATA) {
3101 /* mdb_xcursor_init2(mc); */
3102 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
3103 mdb_xcursor_fini(mc);
3104 /* If sub-DB still has entries, we're done */
3105 if (mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_root
3107 memcpy(NODEDATA(leaf),
3108 &mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi],
3110 mc->mc_txn->mt_dbs[mc->mc_dbi].md_entries--;
3113 /* otherwise fall thru and delete the sub-DB */
3116 /* add all the child DB's pages to the free list */
3117 mc->mc_xcursor->mx_cursor.mc_snum = 0;
3118 rc = mdb_search_page(&mc->mc_xcursor->mx_txn, mc->mc_xcursor->mx_cursor.mc_dbi,
3119 NULL, &mc->mc_xcursor->mx_cursor, 0, &mp2);
3120 if (rc == MDB_SUCCESS) {
3121 MDB_ppage *top, *parent;
3130 mc->mc_txn->mt_dbs[mc->mc_dbi].md_entries -=
3131 mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_entries;
3133 cursor_pop_page(&mc->mc_xcursor->mx_cursor);
3134 if (mc->mc_xcursor->mx_cursor.mc_snum) {
3136 if (mc->mc_xcursor->mx_cursor.mc_stack[0].mp_page->mp_flags & P_DIRTY) {
3140 while (mc->mc_xcursor->mx_cursor.mc_snum > 1) {
3141 top = CURSOR_TOP(&mc->mc_xcursor->mx_cursor);
3142 parent = CURSOR_PARENT(&mc->mc_xcursor->mx_cursor);
3143 for (i=0; i<NUMKEYS(top->mp_page); i++) {
3146 ni = NODEPTR(top->mp_page, i);
3148 if ((rc = mdb_get_page(mc->mc_txn, pg, &mp)))
3151 if (mp->mp_flags & P_DIRTY) {
3154 mdb_mid2l_delete(mc->mc_txn->mt_u.dirty_list, &mid);
3156 dp->h.md_parent = (MDB_page *)mc->mc_txn->mt_env->me_dpages;
3157 mc->mc_txn->mt_env->me_dpages = dp;
3162 mdb_midl_insert(mc->mc_txn->mt_free_pgs, pg);
3165 rc = mdb_sibling(&mc->mc_xcursor->mx_cursor, 1);
3172 mid.mid = mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_root;
3173 mdb_mid2l_delete(mc->mc_txn->mt_u.dirty_list, &mid);
3175 dp->h.md_parent = (MDB_page *)mc->mc_txn->mt_env->me_dpages;
3176 mc->mc_txn->mt_env->me_dpages = dp;
3181 mdb_midl_insert(mc->mc_txn->mt_free_pgs,
3182 mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_root);
3187 return mdb_del0(mc, top->mp_ki, &mpp, leaf);
3190 /* Allocate a page and initialize it
3193 mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num)
3197 if ((dp = mdb_alloc_page(txn, dbi, NULL, 0, num)) == NULL)
3199 DPRINTF("allocated new mpage %lu, page size %u",
3200 dp->p.mp_pgno, txn->mt_env->me_psize);
3201 dp->p.mp_flags = flags | P_DIRTY;
3202 dp->p.mp_lower = PAGEHDRSZ;
3203 dp->p.mp_upper = txn->mt_env->me_psize;
3205 if (IS_BRANCH(&dp->p))
3206 txn->mt_dbs[dbi].md_branch_pages++;
3207 else if (IS_LEAF(&dp->p))
3208 txn->mt_dbs[dbi].md_leaf_pages++;
3209 else if (IS_OVERFLOW(&dp->p)) {
3210 txn->mt_dbs[dbi].md_overflow_pages += num;
3211 dp->p.mp_pages = num;
3218 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
3222 sz = LEAFSIZE(key, data);
3223 if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
3224 /* put on overflow page */
3225 sz -= data->mv_size - sizeof(pgno_t);
3228 return sz + sizeof(indx_t);
3232 mdb_branch_size(MDB_env *env, MDB_val *key)
3237 if (sz >= env->me_psize / MDB_MINKEYS) {
3238 /* put on overflow page */
3239 /* not implemented */
3240 /* sz -= key->size - sizeof(pgno_t); */
3243 return sz + sizeof(indx_t);
3247 mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, indx_t indx,
3248 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags)
3251 size_t node_size = NODESIZE;
3254 MDB_dpage *ofp = NULL; /* overflow page */
3257 assert(mp->mp_upper >= mp->mp_lower);
3259 DPRINTF("add to %s page %lu index %i, data size %zu key size %zu [%s]",
3260 IS_LEAF(mp) ? "leaf" : "branch",
3261 mp->mp_pgno, indx, data ? data->mv_size : 0,
3262 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
3265 /* Move higher keys up one slot. */
3266 int ksize = txn->mt_dbs[dbi].md_pad, dif;
3267 char *ptr = LEAF2KEY(mp, indx, ksize);
3268 dif = NUMKEYS(mp) - indx;
3270 memmove(ptr+ksize, ptr, dif*ksize);
3271 /* insert new key */
3272 memcpy(ptr, key->mv_data, ksize);
3274 /* Just using these for counting */
3275 mp->mp_lower += sizeof(indx_t);
3276 mp->mp_upper -= ksize - sizeof(indx_t);
3281 node_size += key->mv_size;
3285 if (F_ISSET(flags, F_BIGDATA)) {
3286 /* Data already on overflow page. */
3287 node_size += sizeof(pgno_t);
3288 } else if (data->mv_size >= txn->mt_env->me_psize / MDB_MINKEYS) {
3289 int ovpages = OVPAGES(data->mv_size, txn->mt_env->me_psize);
3290 /* Put data on overflow page. */
3291 DPRINTF("data size is %zu, put on overflow page",
3293 node_size += sizeof(pgno_t);
3294 if ((ofp = mdb_new_page(txn, dbi, P_OVERFLOW, ovpages)) == NULL)
3296 DPRINTF("allocated overflow page %lu", ofp->p.mp_pgno);
3299 node_size += data->mv_size;
3303 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
3304 DPRINTF("not enough room in page %lu, got %u ptrs",
3305 mp->mp_pgno, NUMKEYS(mp));
3306 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
3307 mp->mp_upper - mp->mp_lower);
3308 DPRINTF("node size = %zu", node_size);
3312 /* Move higher pointers up one slot. */
3313 for (i = NUMKEYS(mp); i > indx; i--)
3314 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
3316 /* Adjust free space offsets. */
3317 ofs = mp->mp_upper - node_size;
3318 assert(ofs >= mp->mp_lower + sizeof(indx_t));
3319 mp->mp_ptrs[indx] = ofs;
3321 mp->mp_lower += sizeof(indx_t);
3323 /* Write the node data. */
3324 node = NODEPTR(mp, indx);
3325 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
3326 node->mn_flags = flags;
3328 node->mn_dsize = data->mv_size;
3330 NODEPGNO(node) = pgno;
3333 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
3338 if (F_ISSET(flags, F_BIGDATA))
3339 memcpy(node->mn_data + key->mv_size, data->mv_data,
3342 memcpy(node->mn_data + key->mv_size, data->mv_data,
3345 memcpy(node->mn_data + key->mv_size, &ofp->p.mp_pgno,
3347 memcpy(METADATA(&ofp->p), data->mv_data, data->mv_size);
3355 mdb_del_node(MDB_page *mp, indx_t indx, int ksize)
3358 indx_t i, j, numkeys, ptr;
3362 DPRINTF("delete node %u on %s page %lu", indx,
3363 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
3364 assert(indx < NUMKEYS(mp));
3367 int x = NUMKEYS(mp) - 1 - indx;
3368 base = LEAF2KEY(mp, indx, ksize);
3370 memmove(base, base + ksize, x * ksize);
3371 mp->mp_lower -= sizeof(indx_t);
3372 mp->mp_upper += ksize - sizeof(indx_t);
3376 node = NODEPTR(mp, indx);
3377 sz = NODESIZE + node->mn_ksize;
3379 if (F_ISSET(node->mn_flags, F_BIGDATA))
3380 sz += sizeof(pgno_t);
3382 sz += NODEDSZ(node);
3385 ptr = mp->mp_ptrs[indx];
3386 numkeys = NUMKEYS(mp);
3387 for (i = j = 0; i < numkeys; i++) {
3389 mp->mp_ptrs[j] = mp->mp_ptrs[i];
3390 if (mp->mp_ptrs[i] < ptr)
3391 mp->mp_ptrs[j] += sz;
3396 base = (char *)mp + mp->mp_upper;
3397 memmove(base + sz, base, ptr - mp->mp_upper);
3399 mp->mp_lower -= sizeof(indx_t);
3404 mdb_xcursor_init0(MDB_cursor *mc)
3406 MDB_xcursor *mx = mc->mc_xcursor;
3409 mx->mx_txn = *mc->mc_txn;
3410 mx->mx_txn.mt_dbxs = mx->mx_dbxs;
3411 mx->mx_txn.mt_dbs = mx->mx_dbs;
3412 mx->mx_dbxs[0] = mc->mc_txn->mt_dbxs[0];
3413 mx->mx_dbxs[1] = mc->mc_txn->mt_dbxs[1];
3414 if (mc->mc_dbi > 1) {
3415 mx->mx_dbxs[2] = mc->mc_txn->mt_dbxs[mc->mc_dbi];
3420 mx->mx_dbxs[dbn+1].md_parent = dbn;
3421 mx->mx_dbxs[dbn+1].md_cmp = mx->mx_dbxs[dbn].md_dcmp;
3422 mx->mx_dbxs[dbn+1].md_rel = mx->mx_dbxs[dbn].md_rel;
3423 mx->mx_dbxs[dbn+1].md_dirty = 0;
3424 mx->mx_txn.mt_numdbs = dbn+2;
3426 mx->mx_cursor.mc_xcursor = NULL;
3427 mx->mx_cursor.mc_txn = &mx->mx_txn;
3428 mx->mx_cursor.mc_dbi = dbn+1;
3432 mdb_xcursor_init1(MDB_cursor *mc, MDB_page *mp, MDB_node *node)
3434 MDB_db *db = NODEDATA(node);
3435 MDB_xcursor *mx = mc->mc_xcursor;
3437 mx->mx_dbs[0] = mc->mc_txn->mt_dbs[0];
3438 mx->mx_dbs[1] = mc->mc_txn->mt_dbs[1];
3439 if (mc->mc_dbi > 1) {
3440 mx->mx_dbs[2] = mc->mc_txn->mt_dbs[mc->mc_dbi];
3445 DPRINTF("Sub-db %u for db %u root page %lu", dbn, mc->mc_dbi, db->md_root);
3446 mx->mx_dbs[dbn] = *db;
3447 if (F_ISSET(mp->mp_flags, P_DIRTY))
3448 mx->mx_dbxs[dbn].md_dirty = 1;
3449 mx->mx_dbxs[dbn].md_name.mv_data = NODEKEY(node);
3450 mx->mx_dbxs[dbn].md_name.mv_size = node->mn_ksize;
3451 mx->mx_txn.mt_next_pgno = mc->mc_txn->mt_next_pgno;
3452 mx->mx_txn.mt_u = mc->mc_txn->mt_u;
3453 mx->mx_cursor.mc_snum = 0;
3454 mx->mx_cursor.mc_flags = 0;
3458 mdb_xcursor_init2(MDB_cursor *mc)
3460 MDB_xcursor *mx = mc->mc_xcursor;
3462 mx->mx_dbs[0] = mc->mc_txn->mt_dbs[0];
3463 mx->mx_dbs[1] = mc->mc_txn->mt_dbs[1];
3464 if (mc->mc_dbi > 1) {
3465 mx->mx_dbs[2] = mc->mc_txn->mt_dbs[mc->mc_dbi];
3470 DPRINTF("Sub-db %u for db %u root page %lu", dbn, mc->mc_dbi,
3471 mx->mx_dbs[dbn].md_root);
3472 mx->mx_txn.mt_next_pgno = mc->mc_txn->mt_next_pgno;
3476 mdb_xcursor_fini(MDB_cursor *mc)
3478 MDB_xcursor *mx = mc->mc_xcursor;
3479 mc->mc_txn->mt_next_pgno = mx->mx_txn.mt_next_pgno;
3480 mc->mc_txn->mt_dbs[0] = mx->mx_dbs[0];
3481 mc->mc_txn->mt_dbs[1] = mx->mx_dbs[1];
3482 mc->mc_txn->mt_dbxs[0].md_dirty = mx->mx_dbxs[0].md_dirty;
3483 mc->mc_txn->mt_dbxs[1].md_dirty = mx->mx_dbxs[1].md_dirty;
3484 if (mc->mc_dbi > 1) {
3485 mc->mc_txn->mt_dbs[mc->mc_dbi] = mx->mx_dbs[2];
3486 mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty = mx->mx_dbxs[2].md_dirty;
3491 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
3494 size_t size = sizeof(MDB_cursor);
3496 if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
3499 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
3500 size += sizeof(MDB_xcursor);
3502 if ((cursor = calloc(1, size)) != NULL) {
3503 cursor->mc_dbi = dbi;
3504 cursor->mc_txn = txn;
3505 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
3506 MDB_xcursor *mx = (MDB_xcursor *)(cursor + 1);
3507 cursor->mc_xcursor = mx;
3508 mdb_xcursor_init0(cursor);
3519 /* Return the count of duplicate data items for the current key */
3521 mdb_cursor_count(MDB_cursor *mc, unsigned long *countp)
3526 if (mc == NULL || countp == NULL)
3529 if (!(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT))
3532 top = CURSOR_TOP(mc);
3533 leaf = NODEPTR(top->mp_page, top->mp_ki);
3534 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3537 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
3540 *countp = mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_entries;
3547 mdb_cursor_reset(MDB_cursor *mc)
3550 if (mc->mc_flags & C_XDIRTY) {
3552 mdb_xcursor_fini(mc);
3554 /* If sub-DB still has entries, update root record */
3555 if (mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_root
3559 top = CURSOR_TOP(mc);
3560 leaf = NODEPTR(top->mp_page, top->mp_ki);
3561 memcpy(NODEDATA(leaf),
3562 &mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi],
3565 mc->mc_flags ^= C_XDIRTY;
3572 mdb_cursor_close(MDB_cursor *cursor)
3574 if (cursor != NULL) {
3580 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
3582 indx_t ptr, i, numkeys;
3589 node = NODEPTR(mp, indx);
3590 ptr = mp->mp_ptrs[indx];
3591 DPRINTF("update key %u (ofs %u) [%.*s] to [%s] on page %lu",
3593 (int)node->mn_ksize, (char *)NODEKEY(node),
3597 delta = key->mv_size - node->mn_ksize;
3599 if (delta > 0 && SIZELEFT(mp) < delta) {
3600 DPRINTF("OUCH! Not enough room, delta = %d", delta);
3604 numkeys = NUMKEYS(mp);
3605 for (i = 0; i < numkeys; i++) {
3606 if (mp->mp_ptrs[i] <= ptr)
3607 mp->mp_ptrs[i] -= delta;
3610 base = (char *)mp + mp->mp_upper;
3611 len = ptr - mp->mp_upper + NODESIZE;
3612 memmove(base - delta, base, len);
3613 mp->mp_upper -= delta;
3615 node = NODEPTR(mp, indx);
3616 node->mn_ksize = key->mv_size;
3619 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
3624 /* Move a node from src to dst.
3627 mdb_move_node(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, indx_t srcindx,
3628 MDB_pageparent *dst, indx_t dstindx)
3635 /* Mark src and dst as dirty. */
3636 if ((rc = mdb_touch(txn, dbi, src)) ||
3637 (rc = mdb_touch(txn, dbi, dst)))
3640 if (IS_LEAF2(src->mp_page)) {
3641 srcnode = NODEPTR(src->mp_page, 0); /* fake */
3642 key.mv_size = txn->mt_dbs[dbi].md_pad;
3643 key.mv_data = LEAF2KEY(src->mp_page, srcindx, key.mv_size);
3645 data.mv_data = NULL;
3647 srcnode = NODEPTR(src->mp_page, srcindx);
3648 key.mv_size = NODEKSZ(srcnode);
3649 key.mv_data = NODEKEY(srcnode);
3650 data.mv_size = NODEDSZ(srcnode);
3651 data.mv_data = NODEDATA(srcnode);
3653 DPRINTF("moving %s node %u [%s] on page %lu to node %u on page %lu",
3654 IS_LEAF(src->mp_page) ? "leaf" : "branch",
3657 src->mp_page->mp_pgno,
3658 dstindx, dst->mp_page->mp_pgno);
3660 /* Add the node to the destination page.
3662 rc = mdb_add_node(txn, dbi, dst->mp_page, dstindx, &key, &data, NODEPGNO(srcnode),
3664 if (rc != MDB_SUCCESS)
3667 /* Delete the node from the source page.
3669 mdb_del_node(src->mp_page, srcindx, key.mv_size);
3671 /* The key value just changed due to del_node, find it again.
3673 if (!IS_LEAF2(src->mp_page)) {
3674 srcnode = NODEPTR(src->mp_page, srcindx);
3675 key.mv_data = NODEKEY(srcnode);
3678 /* Update the parent separators.
3681 if (src->mp_pi != 0) {
3682 DPRINTF("update separator for source page %lu to [%s]",
3683 src->mp_page->mp_pgno, DKEY(&key));
3684 if ((rc = mdb_update_key(src->mp_parent, src->mp_pi,
3685 &key)) != MDB_SUCCESS)
3688 if (IS_BRANCH(src->mp_page)) {
3690 nullkey.mv_size = 0;
3691 assert(mdb_update_key(src->mp_page, 0, &nullkey) == MDB_SUCCESS);
3696 if (dst->mp_pi != 0) {
3697 DPRINTF("update separator for destination page %lu to [%s]",
3698 dst->mp_page->mp_pgno, DKEY(&key));
3699 if ((rc = mdb_update_key(dst->mp_parent, dst->mp_pi,
3700 &key)) != MDB_SUCCESS)
3703 if (IS_BRANCH(dst->mp_page)) {
3705 nullkey.mv_size = 0;
3706 assert(mdb_update_key(dst->mp_page, 0, &nullkey) == MDB_SUCCESS);
3714 mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, MDB_pageparent *dst)
3723 DPRINTF("merging page %lu and %lu", src->mp_page->mp_pgno, dst->mp_page->mp_pgno);
3725 assert(txn != NULL);
3726 assert(src->mp_parent); /* can't merge root page */
3727 assert(dst->mp_parent);
3729 /* Mark src and dst as dirty. */
3730 if ((rc = mdb_touch(txn, dbi, src)) ||
3731 (rc = mdb_touch(txn, dbi, dst)))
3734 /* Move all nodes from src to dst.
3736 if (IS_LEAF2(src->mp_page)) {
3737 key.mv_size = txn->mt_dbs[dbi].md_pad;
3738 key.mv_data = METADATA(src->mp_page);
3739 for (i = 0; i < NUMKEYS(src->mp_page); i++) {
3740 rc = mdb_add_node(txn, dbi, dst->mp_page, NUMKEYS(dst->mp_page), &key,
3742 if (rc != MDB_SUCCESS)
3744 key.mv_data = (char *)key.mv_data + key.mv_size;
3747 for (i = 0; i < NUMKEYS(src->mp_page); i++) {
3748 srcnode = NODEPTR(src->mp_page, i);
3750 key.mv_size = srcnode->mn_ksize;
3751 key.mv_data = NODEKEY(srcnode);
3752 data.mv_size = NODEDSZ(srcnode);
3753 data.mv_data = NODEDATA(srcnode);
3754 rc = mdb_add_node(txn, dbi, dst->mp_page, NUMKEYS(dst->mp_page), &key,
3755 &data, NODEPGNO(srcnode), srcnode->mn_flags);
3756 if (rc != MDB_SUCCESS)
3761 DPRINTF("dst page %lu now has %u keys (%.1f%% filled)",
3762 dst->mp_page->mp_pgno, NUMKEYS(dst->mp_page), (float)PAGEFILL(txn->mt_env, dst->mp_page) / 10);
3764 /* Unlink the src page from parent.
3766 mdb_del_node(src->mp_parent, src->mp_pi, 0);
3767 if (src->mp_pi == 0) {
3769 if ((rc = mdb_update_key(src->mp_parent, 0, &key)) != MDB_SUCCESS)
3773 if (IS_LEAF(src->mp_page))
3774 txn->mt_dbs[dbi].md_leaf_pages--;
3776 txn->mt_dbs[dbi].md_branch_pages--;
3778 mpp.mp_page = src->mp_parent;
3779 dh = (MDB_dhead *)src->mp_parent;
3781 mpp.mp_parent = dh->md_parent;
3782 mpp.mp_pi = dh->md_pi;
3784 return mdb_rebalance(txn, dbi, &mpp);
3787 #define FILL_THRESHOLD 250
3790 mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mpp)
3795 indx_t si = 0, di = 0;
3798 assert(txn != NULL);
3799 assert(mpp != NULL);
3801 DPRINTF("rebalancing %s page %lu (has %u keys, %.1f%% full)",
3802 IS_LEAF(mpp->mp_page) ? "leaf" : "branch",
3803 mpp->mp_page->mp_pgno, NUMKEYS(mpp->mp_page), (float)PAGEFILL(txn->mt_env, mpp->mp_page) / 10);
3805 if (PAGEFILL(txn->mt_env, mpp->mp_page) >= FILL_THRESHOLD) {
3806 DPRINTF("no need to rebalance page %lu, above fill threshold",
3807 mpp->mp_page->mp_pgno);
3811 if (mpp->mp_parent == NULL) {
3812 if (NUMKEYS(mpp->mp_page) == 0) {
3813 DPUTS("tree is completely empty");
3814 txn->mt_dbs[dbi].md_root = P_INVALID;
3815 txn->mt_dbs[dbi].md_depth = 0;
3816 txn->mt_dbs[dbi].md_leaf_pages = 0;
3817 mdb_midl_insert(txn->mt_free_pgs, mpp->mp_page->mp_pgno);
3818 } else if (IS_BRANCH(mpp->mp_page) && NUMKEYS(mpp->mp_page) == 1) {
3819 DPUTS("collapsing root page!");
3820 mdb_midl_insert(txn->mt_free_pgs, mpp->mp_page->mp_pgno);
3821 txn->mt_dbs[dbi].md_root = NODEPGNO(NODEPTR(mpp->mp_page, 0));
3822 if ((rc = mdb_get_page(txn, txn->mt_dbs[dbi].md_root, &root)))
3824 txn->mt_dbs[dbi].md_depth--;
3825 txn->mt_dbs[dbi].md_branch_pages--;
3827 DPUTS("root page doesn't need rebalancing");
3831 /* The parent (branch page) must have at least 2 pointers,
3832 * otherwise the tree is invalid.
3834 assert(NUMKEYS(mpp->mp_parent) > 1);
3836 /* Leaf page fill factor is below the threshold.
3837 * Try to move keys from left or right neighbor, or
3838 * merge with a neighbor page.
3843 if (mpp->mp_pi == 0) {
3844 /* We're the leftmost leaf in our parent.
3846 DPUTS("reading right neighbor");
3847 node = NODEPTR(mpp->mp_parent, mpp->mp_pi + 1);
3848 if ((rc = mdb_get_page(txn, NODEPGNO(node), &npp.mp_page)))
3850 npp.mp_pi = mpp->mp_pi + 1;
3852 di = NUMKEYS(mpp->mp_page);
3854 /* There is at least one neighbor to the left.
3856 DPUTS("reading left neighbor");
3857 node = NODEPTR(mpp->mp_parent, mpp->mp_pi - 1);
3858 if ((rc = mdb_get_page(txn, NODEPGNO(node), &npp.mp_page)))
3860 npp.mp_pi = mpp->mp_pi - 1;
3861 si = NUMKEYS(npp.mp_page) - 1;
3864 npp.mp_parent = mpp->mp_parent;
3866 DPRINTF("found neighbor page %lu (%u keys, %.1f%% full)",
3867 npp.mp_page->mp_pgno, NUMKEYS(npp.mp_page), (float)PAGEFILL(txn->mt_env, npp.mp_page) / 10);
3869 /* If the neighbor page is above threshold and has at least two
3870 * keys, move one key from it.
3872 * Otherwise we should try to merge them.
3874 if (PAGEFILL(txn->mt_env, npp.mp_page) >= FILL_THRESHOLD && NUMKEYS(npp.mp_page) >= 2)
3875 return mdb_move_node(txn, dbi, &npp, si, mpp, di);
3876 else { /* FIXME: if (has_enough_room()) */
3877 if (mpp->mp_pi == 0)
3878 return mdb_merge(txn, dbi, &npp, mpp);
3880 return mdb_merge(txn, dbi, mpp, &npp);
3885 mdb_del0(MDB_cursor *mc, unsigned int ki, MDB_pageparent *mpp, MDB_node *leaf)
3889 /* add overflow pages to free list */
3890 if (!IS_LEAF2(mpp->mp_page) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
3894 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
3895 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
3896 for (i=0; i<ovpages; i++) {
3897 DPRINTF("freed ov page %lu", pg);
3898 mdb_midl_insert(mc->mc_txn->mt_free_pgs, pg);
3902 mdb_del_node(mpp->mp_page, ki, mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad);
3903 mc->mc_txn->mt_dbs[mc->mc_dbi].md_entries--;
3904 rc = mdb_rebalance(mc->mc_txn, mc->mc_dbi, mpp);
3905 if (rc != MDB_SUCCESS)
3906 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
3912 mdb_del(MDB_txn *txn, MDB_dbi dbi,
3913 MDB_val *key, MDB_val *data)
3918 MDB_val rdata, *xdata;
3922 assert(key != NULL);
3924 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
3926 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3929 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3933 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3940 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
3941 mc.mc_xcursor = &mx;
3942 mdb_xcursor_init0(&mc);
3944 mc.mc_xcursor = NULL;
3956 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
3958 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
3962 /* Split page <*mpp>, and insert <key,(data|newpgno)> in either left or
3963 * right sibling, at index <*newindxp> (as if unsplit). Updates *mpp and
3964 * *newindxp with the actual values after split, ie if *mpp and *newindxp
3965 * refer to a node in the new right sibling page.
3968 mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp, unsigned int *newindxp,
3969 MDB_val *newkey, MDB_val *newdata, pgno_t newpgno)
3972 int rc = MDB_SUCCESS, ins_new = 0;
3975 unsigned int i, j, split_indx, nkeys, pmax;
3977 MDB_val sepkey, rkey, rdata;
3978 MDB_page *copy, *cptr;
3979 MDB_dpage *mdp, *rdp, *pdp;
3983 assert(txn != NULL);
3985 dh = ((MDB_dhead *)*mpp) - 1;
3986 mdp = (MDB_dpage *)dh;
3987 newindx = *newindxp;
3989 DPRINTF("-----> splitting %s page %lu and adding [%s] at index %i",
3990 IS_LEAF(&mdp->p) ? "leaf" : "branch", mdp->p.mp_pgno,
3991 DKEY(newkey), *newindxp);
3993 if (mdp->h.md_parent == NULL) {
3994 if ((pdp = mdb_new_page(txn, dbi, P_BRANCH, 1)) == NULL)
3997 mdp->h.md_parent = &pdp->p;
3998 txn->mt_dbs[dbi].md_root = pdp->p.mp_pgno;
3999 DPRINTF("root split! new root = %lu", pdp->p.mp_pgno);
4000 txn->mt_dbs[dbi].md_depth++;
4002 /* Add left (implicit) pointer. */
4003 if ((rc = mdb_add_node(txn, dbi, &pdp->p, 0, NULL, NULL,
4004 mdp->p.mp_pgno, 0)) != MDB_SUCCESS)
4007 DPRINTF("parent branch page is %lu", mdp->h.md_parent->mp_pgno);
4010 /* Create a right sibling. */
4011 if ((rdp = mdb_new_page(txn, dbi, mdp->p.mp_flags, 1)) == NULL)
4013 rdp->h.md_parent = mdp->h.md_parent;
4014 rdp->h.md_pi = mdp->h.md_pi + 1;
4015 DPRINTF("new right sibling: page %lu", rdp->p.mp_pgno);
4017 nkeys = NUMKEYS(&mdp->p);
4018 split_indx = nkeys / 2 + 1;
4020 if (IS_LEAF2(&rdp->p)) {
4023 unsigned int lsize, rsize, ksize;
4024 /* Move half of the keys to the right sibling */
4026 x = *newindxp - split_indx;
4027 ksize = txn->mt_dbs[dbi].md_pad;
4028 split = LEAF2KEY(&mdp->p, split_indx, ksize);
4029 rsize = (nkeys - split_indx) * ksize;
4030 lsize = (nkeys - split_indx) * sizeof(indx_t);
4031 mdp->p.mp_lower -= lsize;
4032 rdp->p.mp_lower += lsize;
4033 mdp->p.mp_upper += rsize - lsize;
4034 rdp->p.mp_upper -= rsize - lsize;
4035 sepkey.mv_size = ksize;
4036 if (newindx == split_indx) {
4037 sepkey.mv_data = newkey->mv_data;
4039 sepkey.mv_data = split;
4042 ins = LEAF2KEY(&mdp->p, *newindxp, ksize);
4043 memcpy(&rdp->p.mp_ptrs, split, rsize);
4044 sepkey.mv_data = &rdp->p.mp_ptrs;
4045 memmove(ins+ksize, ins, (split_indx - *newindxp) * ksize);
4046 memcpy(ins, newkey->mv_data, ksize);
4047 mdp->p.mp_lower += sizeof(indx_t);
4048 mdp->p.mp_upper -= ksize - sizeof(indx_t);
4051 memcpy(&rdp->p.mp_ptrs, split, x * ksize);
4052 ins = LEAF2KEY(&rdp->p, x, ksize);
4053 memcpy(ins, newkey->mv_data, ksize);
4054 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
4055 rdp->p.mp_lower += sizeof(indx_t);
4056 rdp->p.mp_upper -= ksize - sizeof(indx_t);
4063 /* For leaf pages, check the split point based on what
4064 * fits where, since otherwise add_node can fail.
4066 if (IS_LEAF(&mdp->p)) {
4067 unsigned int psize, nsize;
4068 /* Maximum free space in an empty page */
4069 pmax = txn->mt_env->me_psize - PAGEHDRSZ;
4070 nsize = mdb_leaf_size(txn->mt_env, newkey, newdata);
4071 if (newindx < split_indx) {
4073 for (i=0; i<split_indx; i++) {
4074 node = NODEPTR(&mdp->p, i);
4075 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
4076 if (F_ISSET(node->mn_flags, F_BIGDATA))
4077 psize += sizeof(pgno_t);
4079 psize += NODEDSZ(node);
4087 for (i=nkeys-1; i>=split_indx; i--) {
4088 node = NODEPTR(&mdp->p, i);
4089 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
4090 if (F_ISSET(node->mn_flags, F_BIGDATA))
4091 psize += sizeof(pgno_t);
4093 psize += NODEDSZ(node);
4102 /* First find the separating key between the split pages.
4104 if (newindx == split_indx) {
4105 sepkey.mv_size = newkey->mv_size;
4106 sepkey.mv_data = newkey->mv_data;
4108 node = NODEPTR(&mdp->p, split_indx);
4109 sepkey.mv_size = node->mn_ksize;
4110 sepkey.mv_data = NODEKEY(node);
4114 DPRINTF("separator is [%s]", DKEY(&sepkey));
4116 /* Copy separator key to the parent.
4118 if (SIZELEFT(rdp->h.md_parent) < mdb_branch_size(txn->mt_env, &sepkey)) {
4119 rc = mdb_split(txn, dbi, &rdp->h.md_parent, &rdp->h.md_pi,
4120 &sepkey, NULL, rdp->p.mp_pgno);
4122 /* Right page might now have changed parent.
4123 * Check if left page also changed parent.
4125 if (rdp->h.md_parent != mdp->h.md_parent &&
4126 mdp->h.md_pi >= NUMKEYS(mdp->h.md_parent)) {
4127 mdp->h.md_parent = rdp->h.md_parent;
4128 mdp->h.md_pi = rdp->h.md_pi - 1;
4131 rc = mdb_add_node(txn, dbi, rdp->h.md_parent, rdp->h.md_pi,
4132 &sepkey, NULL, rdp->p.mp_pgno, 0);
4134 if (IS_LEAF2(&rdp->p)) {
4137 if (rc != MDB_SUCCESS) {
4141 /* Move half of the keys to the right sibling. */
4142 if ((copy = malloc(txn->mt_env->me_psize)) == NULL)
4145 copy->mp_pgno = mdp->p.mp_pgno;
4146 copy->mp_flags = mdp->p.mp_flags;
4147 copy->mp_lower = PAGEHDRSZ;
4148 copy->mp_upper = txn->mt_env->me_psize;
4150 for (i = j = 0; i <= nkeys; j++) {
4151 if (i == split_indx) {
4152 /* Insert in right sibling. */
4153 /* Reset insert index for right sibling. */
4154 j = (i == newindx && ins_new);
4158 if (i == newindx && !ins_new) {
4159 /* Insert the original entry that caused the split. */
4160 rkey.mv_data = newkey->mv_data;
4161 rkey.mv_size = newkey->mv_size;
4162 if (IS_LEAF(&mdp->p)) {
4163 rdata.mv_data = newdata->mv_data;
4164 rdata.mv_size = newdata->mv_size;
4171 /* Update page and index for the new key. */
4173 if (cptr == &rdp->p)
4175 } else if (i == nkeys) {
4178 node = NODEPTR(&mdp->p, i);
4179 rkey.mv_data = NODEKEY(node);
4180 rkey.mv_size = node->mn_ksize;
4181 if (IS_LEAF(&mdp->p)) {
4182 rdata.mv_data = NODEDATA(node);
4183 rdata.mv_size = node->mn_dsize;
4185 pgno = NODEPGNO(node);
4186 flags = node->mn_flags;
4191 if (!IS_LEAF(&mdp->p) && j == 0) {
4192 /* First branch index doesn't need key data. */
4196 rc = mdb_add_node(txn, dbi, cptr, j, &rkey, &rdata, pgno, flags);
4198 nkeys = NUMKEYS(copy);
4199 for (i=0; i<nkeys; i++)
4200 mdp->p.mp_ptrs[i] = copy->mp_ptrs[i];
4201 mdp->p.mp_lower = copy->mp_lower;
4202 mdp->p.mp_upper = copy->mp_upper;
4203 memcpy(NODEPTR(&mdp->p, nkeys-1), NODEPTR(copy, nkeys-1),
4204 txn->mt_env->me_psize - copy->mp_upper);
4212 mdb_put0(MDB_txn *txn, MDB_dbi dbi,
4213 MDB_val *key, MDB_val *data, unsigned int flags)
4215 int rc = MDB_SUCCESS, exact;
4219 MDB_val xdata, *rdata, dkey;
4221 char dbuf[PAGESIZE];
4226 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
4227 dbi, DKEY(key), key->mv_size, data->mv_size);
4230 mpp.mp_parent = NULL;
4232 rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp);
4233 if (rc == MDB_SUCCESS) {
4234 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
4235 if (leaf && exact) {
4236 if (flags == MDB_NOOVERWRITE) {
4237 DPRINTF("duplicate key [%s]", DKEY(key));
4238 return MDB_KEYEXIST;
4240 /* there's only a key anyway, so this is a no-op */
4241 if (IS_LEAF2(mpp.mp_page))
4244 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
4245 /* Was a single item before, must convert now */
4246 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4247 dkey.mv_size = NODEDSZ(leaf);
4248 dkey.mv_data = dbuf;
4249 memcpy(dbuf, NODEDATA(leaf), dkey.mv_size);
4250 /* data matches, ignore it */
4251 if (!mdb_dcmp(txn, dbi, data, &dkey))
4252 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
4253 memset(&dummy, 0, sizeof(dummy));
4254 if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED) {
4255 dummy.md_pad = data->mv_size;
4256 dummy.md_flags = MDB_DUPFIXED;
4257 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP)
4258 dummy.md_flags |= MDB_INTEGERKEY;
4260 dummy.md_root = P_INVALID;
4261 if (dkey.mv_size == sizeof(MDB_db)) {
4262 memcpy(NODEDATA(leaf), &dummy, sizeof(dummy));
4265 mdb_del_node(mpp.mp_page, ki, 0);
4268 xdata.mv_size = sizeof(MDB_db);
4269 xdata.mv_data = &dummy;
4274 /* same size, just replace it */
4275 if (!F_ISSET(leaf->mn_flags, F_BIGDATA) &&
4276 NODEDSZ(leaf) == data->mv_size) {
4277 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
4280 mdb_del_node(mpp.mp_page, ki, 0);
4282 if (leaf == NULL) { /* append if not found */
4283 ki = NUMKEYS(mpp.mp_page);
4284 DPRINTF("appending key at index %i", ki);
4286 } else if (rc == MDB_NOTFOUND) {
4288 /* new file, just write a root leaf page */
4289 DPUTS("allocating new root leaf page");
4290 if ((dp = mdb_new_page(txn, dbi, P_LEAF, 1)) == NULL) {
4293 mpp.mp_page = &dp->p;
4294 txn->mt_dbs[dbi].md_root = mpp.mp_page->mp_pgno;
4295 txn->mt_dbs[dbi].md_depth++;
4296 txn->mt_dbxs[dbi].md_dirty = 1;
4297 if ((txn->mt_dbs[dbi].md_flags & (MDB_DUPSORT|MDB_DUPFIXED)) == MDB_DUPFIXED)
4298 mpp.mp_page->mp_flags |= P_LEAF2;
4304 assert(IS_LEAF(mpp.mp_page));
4305 DPRINTF("there are %u keys, should insert new key at index %i",
4306 NUMKEYS(mpp.mp_page), ki);
4311 nsize = IS_LEAF2(mpp.mp_page) ? key->mv_size : mdb_leaf_size(txn->mt_env, key, rdata);
4312 if (SIZELEFT(mpp.mp_page) < nsize) {
4313 rc = mdb_split(txn, dbi, &mpp.mp_page, &ki, key, rdata, P_INVALID);
4315 /* There is room already in this leaf page. */
4316 rc = mdb_add_node(txn, dbi, mpp.mp_page, ki, key, rdata, 0, 0);
4319 if (rc != MDB_SUCCESS)
4320 txn->mt_flags |= MDB_TXN_ERROR;
4322 /* Remember if we just added a subdatabase */
4323 if (flags & F_SUBDATA) {
4324 leaf = NODEPTR(mpp.mp_page, ki);
4325 leaf->mn_flags |= F_SUBDATA;
4328 /* Now store the actual data in the child DB. Note that we're
4329 * storing the user data in the keys field, so there are strict
4330 * size limits on dupdata. The actual data fields of the child
4331 * DB are all zero size.
4337 leaf = NODEPTR(mpp.mp_page, ki);
4342 mc.mc_xcursor = &mx;
4343 mdb_xcursor_init0(&mc);
4344 mdb_xcursor_init1(txn, dbi, &mx, mpp.mp_page, leaf);
4347 if (flags == MDB_NODUPDATA)
4348 flags = MDB_NOOVERWRITE;
4349 /* converted, write the original data first */
4351 rc = mdb_put0(&mx.mx_txn, mx.mx_cursor.mc_dbi, &dkey, &xdata, flags);
4353 leaf->mn_flags |= F_DUPDATA;
4355 rc = mdb_put0(&mx.mx_txn, mx.mx_cursor.mc_dbi, data, &xdata, flags);
4356 mdb_xcursor_fini(&mc);
4357 memcpy(NODEDATA(leaf), &mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi],
4360 txn->mt_dbs[dbi].md_entries++;
4369 mdb_put(MDB_txn *txn, MDB_dbi dbi,
4370 MDB_val *key, MDB_val *data, unsigned int flags)
4375 assert(key != NULL);
4376 assert(data != NULL);
4378 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4381 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
4385 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
4389 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA)) != flags)
4396 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4397 mc.mc_xcursor = &mx;
4398 mdb_xcursor_init0(&mc);
4400 mc.mc_xcursor = NULL;
4402 return mdb_cursor_put(&mc, key, data, flags);
4406 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
4408 #define CHANGEABLE (MDB_NOSYNC)
4409 if ((flag & CHANGEABLE) != flag)
4412 env->me_flags |= flag;
4414 env->me_flags &= ~flag;
4419 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
4424 *arg = env->me_flags;
4429 mdb_env_get_path(MDB_env *env, const char **arg)
4434 *arg = env->me_path;
4439 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
4441 arg->ms_psize = env->me_psize;
4442 arg->ms_depth = db->md_depth;
4443 arg->ms_branch_pages = db->md_branch_pages;
4444 arg->ms_leaf_pages = db->md_leaf_pages;
4445 arg->ms_overflow_pages = db->md_overflow_pages;
4446 arg->ms_entries = db->md_entries;
4451 mdb_env_stat(MDB_env *env, MDB_stat *arg)
4455 if (env == NULL || arg == NULL)
4458 mdb_env_read_meta(env, &toggle);
4460 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
4464 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
4466 if (txn->mt_dbs[dbi].md_flags & (MDB_REVERSEKEY
4467 #if __BYTE_ORDER == __LITTLE_ENDIAN
4471 txn->mt_dbxs[dbi].md_cmp = memnrcmp;
4473 txn->mt_dbxs[dbi].md_cmp = memncmp;
4475 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4476 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP) {
4477 if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED)
4478 txn->mt_dbxs[dbi].md_dcmp = intcmp;
4480 #if __BYTE_ORDER == __LITTLE_ENDIAN
4481 txn->mt_dbxs[dbi].md_dcmp = memnrcmp;
4483 txn->mt_dbxs[dbi].md_dcmp = memncmp;
4485 } else if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEDUP) {
4486 txn->mt_dbxs[dbi].md_dcmp = memnrcmp;
4488 txn->mt_dbxs[dbi].md_dcmp = memncmp;
4491 txn->mt_dbxs[dbi].md_dcmp = NULL;
4495 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
4502 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
4503 mdb_default_cmp(txn, FREE_DBI);
4509 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
4510 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
4511 mdb_default_cmp(txn, MAIN_DBI);
4515 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
4516 mdb_default_cmp(txn, MAIN_DBI);
4519 /* Is the DB already open? */
4521 for (i=2; i<txn->mt_numdbs; i++) {
4522 if (len == txn->mt_dbxs[i].md_name.mv_size &&
4523 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
4529 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
4532 /* Find the DB info */
4534 key.mv_data = (void *)name;
4535 rc = mdb_get(txn, MAIN_DBI, &key, &data);
4537 /* Create if requested */
4538 if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
4541 data.mv_size = sizeof(MDB_db);
4542 data.mv_data = &dummy;
4543 memset(&dummy, 0, sizeof(dummy));
4544 dummy.md_root = P_INVALID;
4545 dummy.md_flags = flags & 0xffff;
4547 mc.mc_dbi = MAIN_DBI;
4549 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
4553 /* OK, got info, add to table */
4554 if (rc == MDB_SUCCESS) {
4555 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
4556 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
4557 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
4558 txn->mt_dbxs[txn->mt_numdbs].md_parent = MAIN_DBI;
4559 txn->mt_dbxs[txn->mt_numdbs].md_dirty = dirty;
4560 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
4561 *dbi = txn->mt_numdbs;
4562 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
4563 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
4564 mdb_default_cmp(txn, txn->mt_numdbs);
4571 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
4573 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
4576 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
4579 void mdb_close(MDB_txn *txn, MDB_dbi dbi)
4582 if (dbi <= MAIN_DBI || dbi >= txn->mt_numdbs)
4584 ptr = txn->mt_dbxs[dbi].md_name.mv_data;
4585 txn->mt_dbxs[dbi].md_name.mv_data = NULL;
4586 txn->mt_dbxs[dbi].md_name.mv_size = 0;
4590 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
4592 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4595 txn->mt_dbxs[dbi].md_cmp = cmp;
4599 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
4601 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4604 txn->mt_dbxs[dbi].md_dcmp = cmp;
4608 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
4610 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4613 txn->mt_dbxs[dbi].md_rel = rel;