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_append(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);
1020 mdb_midl_sort(txn->mt_free_pgs);
1024 ULONG *idl = txn->mt_free_pgs;
1025 DPRINTF("IDL write txn %lu root %lu num %lu",
1026 txn->mt_txnid, txn->mt_dbs[FREE_DBI].md_root, idl[0]);
1027 for (i=0; i<idl[0]; i++) {
1028 DPRINTF("IDL %lu", idl[i+1]);
1032 /* write to last page of freeDB */
1033 key.mv_size = sizeof(pgno_t);
1034 key.mv_data = (char *)&txn->mt_txnid;
1035 data.mv_data = txn->mt_free_pgs;
1036 /* The free list can still grow during this call,
1037 * despite the pre-emptive touches above. So check
1038 * and make sure the entire thing got written.
1041 i = txn->mt_free_pgs[0];
1042 data.mv_size = MDB_IDL_SIZEOF(txn->mt_free_pgs);
1043 rc = mdb_cursor_put(&mc, &key, &data, 0);
1048 } while (i != txn->mt_free_pgs[0]);
1050 /* should only be one record now */
1051 if (env->me_pghead) {
1055 mop = env->me_pghead;
1056 key.mv_size = sizeof(pgno_t);
1057 key.mv_data = (char *)&mop->mo_txnid;
1058 data.mv_size = MDB_IDL_SIZEOF(mop->mo_pages);
1059 data.mv_data = mop->mo_pages;
1060 mdb_cursor_put(&mc, &key, &data, 0);
1061 free(env->me_pghead);
1062 env->me_pghead = NULL;
1065 /* Update DB root pointers. Their pages have already been
1066 * touched so this is all in-place and cannot fail.
1070 data.mv_size = sizeof(MDB_db);
1072 mc.mc_dbi = MAIN_DBI;
1074 for (i = 2; i < txn->mt_numdbs; i++) {
1075 if (txn->mt_dbxs[i].md_dirty) {
1076 data.mv_data = &txn->mt_dbs[i];
1077 mdb_cursor_put(&mc, &txn->mt_dbxs[i].md_name, &data, 0);
1082 /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
1088 /* Windows actually supports scatter/gather I/O, but only on
1089 * unbuffered file handles. Since we're relying on the OS page
1090 * cache for all our data, that's self-defeating. So we just
1091 * write pages one at a time. We use the ov structure to set
1092 * the write offset, to at least save the overhead of a Seek
1096 memset(&ov, 0, sizeof(ov));
1097 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1098 dp = txn->mt_u.dirty_list[i].mptr;
1099 DPRINTF("committing page %lu", dp->p.mp_pgno);
1100 size = dp->p.mp_pgno * env->me_psize;
1101 ov.Offset = size & 0xffffffff;
1102 ov.OffsetHigh = size >> 16;
1103 ov.OffsetHigh >>= 16;
1104 /* clear dirty flag */
1105 dp->p.mp_flags &= ~P_DIRTY;
1106 rc = WriteFile(env->me_fd, &dp->p, env->me_psize * dp->h.md_num, NULL, &ov);
1109 DPRINTF("WriteFile: %d", n);
1116 struct iovec iov[MDB_COMMIT_PAGES];
1120 for (; i<=txn->mt_u.dirty_list[0].mid; i++) {
1121 dp = txn->mt_u.dirty_list[i].mptr;
1122 if (dp->p.mp_pgno != next) {
1124 DPRINTF("committing %u dirty pages", n);
1125 rc = writev(env->me_fd, iov, n);
1129 DPUTS("short write, filesystem full?");
1131 DPRINTF("writev: %s", strerror(n));
1138 lseek(env->me_fd, dp->p.mp_pgno * env->me_psize, SEEK_SET);
1139 next = dp->p.mp_pgno;
1141 DPRINTF("committing page %lu", dp->p.mp_pgno);
1142 iov[n].iov_len = env->me_psize * dp->h.md_num;
1143 iov[n].iov_base = &dp->p;
1144 size += iov[n].iov_len;
1145 next = dp->p.mp_pgno + dp->h.md_num;
1146 /* clear dirty flag */
1147 dp->p.mp_flags &= ~P_DIRTY;
1148 if (++n >= MDB_COMMIT_PAGES) {
1158 DPRINTF("committing %u dirty pages", n);
1159 rc = writev(env->me_fd, iov, n);
1163 DPUTS("short write, filesystem full?");
1165 DPRINTF("writev: %s", strerror(n));
1172 /* Drop the dirty pages.
1174 for (i=1; i<=txn->mt_u.dirty_list[0].mid; i++) {
1175 dp = txn->mt_u.dirty_list[i].mptr;
1176 if (dp->h.md_num == 1) {
1177 dp->h.md_parent = (MDB_page *)txn->mt_env->me_dpages;
1178 txn->mt_env->me_dpages = dp;
1182 txn->mt_u.dirty_list[i].mid = 0;
1184 txn->mt_u.dirty_list[0].mid = 0;
1186 if ((n = mdb_env_sync(env, 0)) != 0 ||
1187 (n = mdb_env_write_meta(txn)) != MDB_SUCCESS) {
1194 /* update the DB tables */
1196 int toggle = !env->me_db_toggle;
1199 ip = &env->me_dbs[toggle][2];
1200 jp = &txn->mt_dbs[2];
1201 LAZY_RWLOCK_WRLOCK(&env->me_dblock);
1202 for (i = 2; i < txn->mt_numdbs; i++) {
1203 if (ip->md_root != jp->md_root)
1208 for (i = 2; i < txn->mt_numdbs; i++) {
1209 if (txn->mt_dbxs[i].md_dirty)
1210 txn->mt_dbxs[i].md_dirty = 0;
1212 env->me_db_toggle = toggle;
1213 env->me_numdbs = txn->mt_numdbs;
1214 LAZY_RWLOCK_UNLOCK(&env->me_dblock);
1217 UNLOCK_MUTEX_W(env);
1224 mdb_env_read_header(MDB_env *env, MDB_meta *meta)
1226 char page[PAGESIZE];
1231 /* We don't know the page size yet, so use a minimum value.
1235 if (!ReadFile(env->me_fd, page, PAGESIZE, (DWORD *)&rc, NULL) || rc == 0)
1237 if ((rc = read(env->me_fd, page, PAGESIZE)) == 0)
1242 else if (rc != PAGESIZE) {
1246 DPRINTF("read: %s", strerror(err));
1250 p = (MDB_page *)page;
1252 if (!F_ISSET(p->mp_flags, P_META)) {
1253 DPRINTF("page %lu not a meta page", p->mp_pgno);
1258 if (m->mm_magic != MDB_MAGIC) {
1259 DPUTS("meta has invalid magic");
1263 if (m->mm_version != MDB_VERSION) {
1264 DPRINTF("database is version %u, expected version %u",
1265 m->mm_version, MDB_VERSION);
1266 return MDB_VERSION_MISMATCH;
1269 memcpy(meta, m, sizeof(*m));
1274 mdb_env_init_meta(MDB_env *env, MDB_meta *meta)
1281 DPUTS("writing new meta page");
1285 meta->mm_magic = MDB_MAGIC;
1286 meta->mm_version = MDB_VERSION;
1287 meta->mm_psize = psize;
1288 meta->mm_last_pg = 1;
1289 meta->mm_flags = env->me_flags & 0xffff;
1290 meta->mm_flags |= MDB_INTEGERKEY;
1291 meta->mm_dbs[0].md_root = P_INVALID;
1292 meta->mm_dbs[1].md_root = P_INVALID;
1294 p = calloc(2, psize);
1296 p->mp_flags = P_META;
1299 memcpy(m, meta, sizeof(*meta));
1301 q = (MDB_page *)((char *)p + psize);
1304 q->mp_flags = P_META;
1307 memcpy(m, meta, sizeof(*meta));
1312 rc = WriteFile(env->me_fd, p, psize * 2, &len, NULL);
1313 rc = (len == psize * 2) ? MDB_SUCCESS : ErrCode();
1316 rc = write(env->me_fd, p, psize * 2);
1317 rc = (rc == (int)psize * 2) ? MDB_SUCCESS : ErrCode();
1324 mdb_env_write_meta(MDB_txn *txn)
1327 MDB_meta meta, metab;
1329 int rc, len, toggle;
1335 assert(txn != NULL);
1336 assert(txn->mt_env != NULL);
1338 toggle = !txn->mt_toggle;
1339 DPRINTF("writing meta page %d for root page %lu",
1340 toggle, txn->mt_dbs[MAIN_DBI].md_root);
1344 metab.mm_txnid = env->me_metas[toggle]->mm_txnid;
1345 metab.mm_last_pg = env->me_metas[toggle]->mm_last_pg;
1347 ptr = (char *)&meta;
1348 off = offsetof(MDB_meta, mm_dbs[0].md_depth);
1349 len = sizeof(MDB_meta) - off;
1352 meta.mm_dbs[0] = txn->mt_dbs[0];
1353 meta.mm_dbs[1] = txn->mt_dbs[1];
1354 meta.mm_last_pg = txn->mt_next_pgno - 1;
1355 meta.mm_txnid = txn->mt_txnid;
1358 off += env->me_psize;
1361 /* Write to the SYNC fd */
1364 memset(&ov, 0, sizeof(ov));
1366 WriteFile(env->me_mfd, ptr, len, (DWORD *)&rc, &ov);
1369 rc = pwrite(env->me_mfd, ptr, len, off);
1374 DPUTS("write failed, disk error?");
1375 /* On a failure, the pagecache still contains the new data.
1376 * Write some old data back, to prevent it from being used.
1377 * Use the non-SYNC fd; we know it will fail anyway.
1379 meta.mm_last_pg = metab.mm_last_pg;
1380 meta.mm_txnid = metab.mm_txnid;
1382 WriteFile(env->me_fd, ptr, len, NULL, &ov);
1384 r2 = pwrite(env->me_fd, ptr, len, off);
1386 env->me_flags |= MDB_FATAL_ERROR;
1389 /* Memory ordering issues are irrelevant; since the entire writer
1390 * is wrapped by wmutex, all of these changes will become visible
1391 * after the wmutex is unlocked. Since the DB is multi-version,
1392 * readers will get consistent data regardless of how fresh or
1393 * how stale their view of these values is.
1395 LAZY_MUTEX_LOCK(&env->me_txns->mti_mutex);
1396 txn->mt_env->me_txns->mti_me_toggle = toggle;
1397 txn->mt_env->me_txns->mti_txnid = txn->mt_txnid;
1398 LAZY_MUTEX_UNLOCK(&env->me_txns->mti_mutex);
1404 mdb_env_read_meta(MDB_env *env, int *which)
1408 assert(env != NULL);
1410 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1413 DPRINTF("Using meta page %d", toggle);
1420 mdb_env_create(MDB_env **env)
1424 e = calloc(1, sizeof(MDB_env));
1425 if (!e) return ENOMEM;
1427 e->me_maxreaders = DEFAULT_READERS;
1429 e->me_fd = INVALID_HANDLE_VALUE;
1430 e->me_lfd = INVALID_HANDLE_VALUE;
1431 e->me_mfd = INVALID_HANDLE_VALUE;
1437 mdb_env_set_mapsize(MDB_env *env, size_t size)
1441 env->me_mapsize = size;
1446 mdb_env_set_maxdbs(MDB_env *env, int dbs)
1450 env->me_maxdbs = dbs;
1455 mdb_env_set_maxreaders(MDB_env *env, int readers)
1459 env->me_maxreaders = readers;
1464 mdb_env_get_maxreaders(MDB_env *env, int *readers)
1466 if (!env || !readers)
1468 *readers = env->me_maxreaders;
1473 mdb_env_open2(MDB_env *env, unsigned int flags)
1475 int i, newenv = 0, toggle;
1479 env->me_flags = flags;
1481 memset(&meta, 0, sizeof(meta));
1483 if ((i = mdb_env_read_header(env, &meta)) != 0) {
1486 DPUTS("new mdbenv");
1490 if (!env->me_mapsize) {
1491 env->me_mapsize = newenv ? DEFAULT_MAPSIZE : meta.mm_mapsize;
1497 LONG sizelo, sizehi;
1498 sizelo = env->me_mapsize & 0xffffffff;
1499 sizehi = env->me_mapsize >> 16; /* pointless on WIN32, only needed on W64 */
1501 /* Windows won't create mappings for zero length files.
1502 * Just allocate the maxsize right now.
1505 SetFilePointer(env->me_fd, sizelo, sizehi ? &sizehi : NULL, 0);
1506 if (!SetEndOfFile(env->me_fd))
1508 SetFilePointer(env->me_fd, 0, NULL, 0);
1510 mh = CreateFileMapping(env->me_fd, NULL, PAGE_READONLY,
1511 sizehi, sizelo, NULL);
1514 env->me_map = MapViewOfFileEx(mh, FILE_MAP_READ, 0, 0, env->me_mapsize,
1522 if (meta.mm_address && (flags & MDB_FIXEDMAP))
1524 env->me_map = mmap(meta.mm_address, env->me_mapsize, PROT_READ, i,
1526 if (env->me_map == MAP_FAILED)
1531 meta.mm_mapsize = env->me_mapsize;
1532 if (flags & MDB_FIXEDMAP)
1533 meta.mm_address = env->me_map;
1534 i = mdb_env_init_meta(env, &meta);
1535 if (i != MDB_SUCCESS) {
1536 munmap(env->me_map, env->me_mapsize);
1540 env->me_psize = meta.mm_psize;
1542 env->me_maxpg = env->me_mapsize / env->me_psize;
1544 p = (MDB_page *)env->me_map;
1545 env->me_metas[0] = METADATA(p);
1546 env->me_metas[1] = (MDB_meta *)((char *)env->me_metas[0] + meta.mm_psize);
1548 if ((i = mdb_env_read_meta(env, &toggle)) != 0)
1551 DPRINTF("opened database version %u, pagesize %u",
1552 env->me_metas[toggle]->mm_version, env->me_psize);
1553 DPRINTF("depth: %u", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_depth);
1554 DPRINTF("entries: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_entries);
1555 DPRINTF("branch pages: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_branch_pages);
1556 DPRINTF("leaf pages: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_leaf_pages);
1557 DPRINTF("overflow pages: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_overflow_pages);
1558 DPRINTF("root: %lu", env->me_metas[toggle]->mm_dbs[MAIN_DBI].md_root);
1564 /* Windows doesn't support destructor callbacks for thread-specific storage */
1566 mdb_env_reader_dest(void *ptr)
1568 MDB_reader *reader = ptr;
1570 reader->mr_txnid = 0;
1576 /* downgrade the exclusive lock on the region back to shared */
1578 mdb_env_share_locks(MDB_env *env)
1582 if (env->me_metas[0]->mm_txnid < env->me_metas[1]->mm_txnid)
1584 env->me_txns->mti_me_toggle = toggle;
1585 env->me_txns->mti_txnid = env->me_metas[toggle]->mm_txnid;
1590 /* First acquire a shared lock. The Unlock will
1591 * then release the existing exclusive lock.
1593 memset(&ov, 0, sizeof(ov));
1594 LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov);
1595 UnlockFile(env->me_lfd, 0, 0, 1, 0);
1599 struct flock lock_info;
1600 /* The shared lock replaces the existing lock */
1601 memset((void *)&lock_info, 0, sizeof(lock_info));
1602 lock_info.l_type = F_RDLCK;
1603 lock_info.l_whence = SEEK_SET;
1604 lock_info.l_start = 0;
1605 lock_info.l_len = 1;
1606 fcntl(env->me_lfd, F_SETLK, &lock_info);
1612 mdb_env_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
1620 if ((env->me_lfd = CreateFile(lpath, GENERIC_READ|GENERIC_WRITE,
1621 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
1622 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {
1626 /* Try to get exclusive lock. If we succeed, then
1627 * nobody is using the lock region and we should initialize it.
1630 if (LockFile(env->me_lfd, 0, 0, 1, 0)) {
1634 memset(&ov, 0, sizeof(ov));
1635 if (!LockFileEx(env->me_lfd, 0, 0, 1, 0, &ov)) {
1641 size = GetFileSize(env->me_lfd, NULL);
1643 if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
1647 /* Try to get exclusive lock. If we succeed, then
1648 * nobody is using the lock region and we should initialize it.
1651 struct flock lock_info;
1652 memset((void *)&lock_info, 0, sizeof(lock_info));
1653 lock_info.l_type = F_WRLCK;
1654 lock_info.l_whence = SEEK_SET;
1655 lock_info.l_start = 0;
1656 lock_info.l_len = 1;
1657 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1661 lock_info.l_type = F_RDLCK;
1662 rc = fcntl(env->me_lfd, F_SETLKW, &lock_info);
1669 size = lseek(env->me_lfd, 0, SEEK_END);
1671 rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1672 if (size < rsize && *excl) {
1674 SetFilePointer(env->me_lfd, rsize, NULL, 0);
1675 if (!SetEndOfFile(env->me_lfd)) {
1680 if (ftruncate(env->me_lfd, rsize) != 0) {
1687 size = rsize - sizeof(MDB_txninfo);
1688 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
1693 mh = CreateFileMapping(env->me_lfd, NULL, PAGE_READWRITE,
1699 env->me_txns = MapViewOfFileEx(mh, FILE_MAP_WRITE, 0, 0, rsize, NULL);
1701 if (!env->me_txns) {
1707 env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
1709 if (env->me_txns == MAP_FAILED) {
1717 if (!mdb_sec_inited) {
1718 InitializeSecurityDescriptor(&mdb_null_sd,
1719 SECURITY_DESCRIPTOR_REVISION);
1720 SetSecurityDescriptorDacl(&mdb_null_sd, TRUE, 0, FALSE);
1721 mdb_all_sa.nLength = sizeof(SECURITY_ATTRIBUTES);
1722 mdb_all_sa.bInheritHandle = FALSE;
1723 mdb_all_sa.lpSecurityDescriptor = &mdb_null_sd;
1726 /* FIXME: only using up to 20 characters of the env path here,
1727 * probably not enough to assure uniqueness...
1729 sprintf(env->me_txns->mti_rmname, "Global\\MDBr%.20s", lpath);
1730 ptr = env->me_txns->mti_rmname + sizeof("Global\\MDBr");
1731 while ((ptr = strchr(ptr, '\\')))
1733 env->me_rmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
1734 if (!env->me_rmutex) {
1738 sprintf(env->me_txns->mti_rmname, "Global\\MDBw%.20s", lpath);
1739 ptr = env->me_txns->mti_rmname + sizeof("Global\\MDBw");
1740 while ((ptr = strchr(ptr, '\\')))
1742 env->me_wmutex = CreateMutex(&mdb_all_sa, FALSE, env->me_txns->mti_rmname);
1743 if (!env->me_wmutex) {
1748 pthread_mutexattr_t mattr;
1750 pthread_mutexattr_init(&mattr);
1751 rc = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
1755 pthread_mutex_init(&env->me_txns->mti_mutex, &mattr);
1756 pthread_mutex_init(&env->me_txns->mti_wmutex, &mattr);
1758 env->me_txns->mti_version = MDB_VERSION;
1759 env->me_txns->mti_magic = MDB_MAGIC;
1760 env->me_txns->mti_txnid = 0;
1761 env->me_txns->mti_numreaders = 0;
1762 env->me_txns->mti_me_toggle = 0;
1765 if (env->me_txns->mti_magic != MDB_MAGIC) {
1766 DPUTS("lock region has invalid magic");
1770 if (env->me_txns->mti_version != MDB_VERSION) {
1771 DPRINTF("lock region is version %u, expected version %u",
1772 env->me_txns->mti_version, MDB_VERSION);
1773 rc = MDB_VERSION_MISMATCH;
1777 if (rc != EACCES && rc != EAGAIN) {
1781 env->me_rmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_rmname);
1782 if (!env->me_rmutex) {
1786 env->me_wmutex = OpenMutex(SYNCHRONIZE, FALSE, env->me_txns->mti_wmname);
1787 if (!env->me_wmutex) {
1797 env->me_lfd = INVALID_HANDLE_VALUE;
1802 #define LOCKNAME "/lock.mdb"
1803 #define DATANAME "/data.mdb"
1805 mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
1807 int oflags, rc, len, excl;
1808 char *lpath, *dpath;
1811 lpath = malloc(len + sizeof(LOCKNAME) + len + sizeof(DATANAME));
1814 dpath = lpath + len + sizeof(LOCKNAME);
1815 sprintf(lpath, "%s" LOCKNAME, path);
1816 sprintf(dpath, "%s" DATANAME, path);
1818 rc = mdb_env_setup_locks(env, lpath, mode, &excl);
1823 if (F_ISSET(flags, MDB_RDONLY)) {
1824 oflags = GENERIC_READ;
1825 len = OPEN_EXISTING;
1827 oflags = GENERIC_READ|GENERIC_WRITE;
1830 mode = FILE_ATTRIBUTE_NORMAL;
1831 if ((env->me_fd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
1832 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
1837 if (F_ISSET(flags, MDB_RDONLY))
1840 oflags = O_RDWR | O_CREAT;
1842 if ((env->me_fd = open(dpath, oflags, mode)) == -1) {
1848 if ((rc = mdb_env_open2(env, flags)) == MDB_SUCCESS) {
1849 /* synchronous fd for meta writes */
1851 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
1852 mode |= FILE_FLAG_WRITE_THROUGH;
1853 if ((env->me_mfd = CreateFile(dpath, oflags, FILE_SHARE_READ|FILE_SHARE_WRITE,
1854 NULL, len, mode, NULL)) == INVALID_HANDLE_VALUE) {
1859 if (!(flags & (MDB_RDONLY|MDB_NOSYNC)))
1860 oflags |= MDB_DSYNC;
1861 if ((env->me_mfd = open(dpath, oflags, mode)) == -1) {
1866 env->me_path = strdup(path);
1867 DPRINTF("opened dbenv %p", (void *) env);
1868 pthread_key_create(&env->me_txkey, mdb_env_reader_dest);
1869 LAZY_RWLOCK_INIT(&env->me_dblock, NULL);
1871 mdb_env_share_locks(env);
1872 env->me_dbxs = calloc(env->me_maxdbs, sizeof(MDB_dbx));
1873 env->me_dbs[0] = calloc(env->me_maxdbs, sizeof(MDB_db));
1874 env->me_dbs[1] = calloc(env->me_maxdbs, sizeof(MDB_db));
1880 if (env->me_fd != INVALID_HANDLE_VALUE) {
1882 env->me_fd = INVALID_HANDLE_VALUE;
1884 if (env->me_lfd != INVALID_HANDLE_VALUE) {
1886 env->me_lfd = INVALID_HANDLE_VALUE;
1894 mdb_env_close(MDB_env *env)
1901 while (env->me_dpages) {
1902 dp = env->me_dpages;
1903 env->me_dpages = (MDB_dpage *)dp->h.md_parent;
1907 free(env->me_dbs[1]);
1908 free(env->me_dbs[0]);
1912 LAZY_RWLOCK_DESTROY(&env->me_dblock);
1913 pthread_key_delete(env->me_txkey);
1916 munmap(env->me_map, env->me_mapsize);
1921 pid_t pid = getpid();
1923 for (i=0; i<env->me_txns->mti_numreaders; i++)
1924 if (env->me_txns->mti_readers[i].mr_pid == pid)
1925 env->me_txns->mti_readers[i].mr_pid = 0;
1926 munmap(env->me_txns, (env->me_maxreaders-1)*sizeof(MDB_reader)+sizeof(MDB_txninfo));
1933 intcmp(const MDB_val *a, const MDB_val *b)
1935 if (a->mv_size == sizeof(long))
1937 unsigned long *la, *lb;
1942 unsigned int *ia, *ib;
1950 memncmp(const MDB_val *a, const MDB_val *b)
1956 len_diff = a->mv_size - b->mv_size;
1959 diff = memcmp(a->mv_data, b->mv_data, len);
1960 return diff ? diff : len_diff;
1964 memnrcmp(const MDB_val *a, const MDB_val *b)
1966 const unsigned char *p1, *p2, *p1_lim;
1969 if (b->mv_size == 0)
1970 return a->mv_size != 0;
1971 if (a->mv_size == 0)
1974 p1 = (const unsigned char *)a->mv_data + a->mv_size - 1;
1975 p2 = (const unsigned char *)b->mv_data + b->mv_size - 1;
1977 len_diff = a->mv_size - b->mv_size;
1979 p1_lim = p1 - a->mv_size;
1981 p1_lim = p1 - b->mv_size;
1983 while (p1 >= p1_lim) {
1993 /* Search for key within a leaf page, using binary search.
1994 * Returns the smallest entry larger or equal to the key.
1995 * If exactp is non-null, stores whether the found entry was an exact match
1996 * in *exactp (1 or 0).
1997 * If kip is non-null, stores the index of the found entry in *kip.
1998 * If no entry larger or equal to the key is found, returns NULL.
2001 mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, MDB_val *key,
2002 int *exactp, unsigned int *kip)
2004 unsigned int i = 0, nkeys;
2007 MDB_node *node = NULL;
2012 nkeys = NUMKEYS(mp);
2014 DPRINTF("searching %u keys in %s page %lu",
2015 nkeys, IS_LEAF(mp) ? "leaf" : "branch",
2020 low = IS_LEAF(mp) ? 0 : 1;
2022 cmp = txn->mt_dbxs[dbi].md_cmp;
2024 nodekey.mv_size = txn->mt_dbs[dbi].md_pad;
2025 node = NODEPTR(mp, 0); /* fake */
2027 while (low <= high) {
2028 i = (low + high) >> 1;
2031 nodekey.mv_data = LEAF2KEY(mp, i, nodekey.mv_size);
2033 node = NODEPTR(mp, i);
2035 nodekey.mv_size = node->mn_ksize;
2036 nodekey.mv_data = NODEKEY(node);
2039 rc = cmp(key, &nodekey);
2043 DPRINTF("found leaf index %u [%s], rc = %i",
2044 i, DKEY(&nodekey), rc);
2046 DPRINTF("found branch index %u [%s -> %lu], rc = %i",
2047 i, DKEY(&nodekey), NODEPGNO(node), rc);
2058 if (rc > 0) { /* Found entry is less than the key. */
2059 i++; /* Skip to get the smallest entry larger than key. */
2062 *exactp = (rc == 0);
2063 if (kip) /* Store the key index if requested. */
2066 /* There is no entry larger or equal to the key. */
2069 /* nodeptr is fake for LEAF2 */
2074 cursor_pop_page(MDB_cursor *cursor)
2078 if (cursor->mc_snum) {
2079 top = CURSOR_TOP(cursor);
2082 DPRINTF("popped page %lu off db %u cursor %p", top->mp_page->mp_pgno,
2083 cursor->mc_dbi, (void *) cursor);
2088 cursor_push_page(MDB_cursor *cursor, MDB_page *mp)
2092 DPRINTF("pushing page %lu on db %u cursor %p", mp->mp_pgno,
2093 cursor->mc_dbi, (void *) cursor);
2095 assert(cursor->mc_snum < CURSOR_STACK);
2097 ppage = &cursor->mc_stack[cursor->mc_snum++];
2098 ppage->mp_page = mp;
2104 mdb_get_page(MDB_txn *txn, pgno_t pgno, MDB_page **ret)
2108 if (!F_ISSET(txn->mt_flags, MDB_TXN_RDONLY) && txn->mt_u.dirty_list[0].mid) {
2111 x = mdb_mid2l_search(txn->mt_u.dirty_list, pgno);
2112 if (x <= txn->mt_u.dirty_list[0].mid && txn->mt_u.dirty_list[x].mid == pgno) {
2113 dp = txn->mt_u.dirty_list[x].mptr;
2118 if (pgno <= txn->mt_env->me_metas[txn->mt_toggle]->mm_last_pg)
2119 p = (MDB_page *)(txn->mt_env->me_map + txn->mt_env->me_psize * pgno);
2123 DPRINTF("page %lu not found", pgno);
2126 return (p != NULL) ? MDB_SUCCESS : MDB_PAGE_NOTFOUND;
2130 mdb_search_page_root(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
2131 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
2133 MDB_page *mp = mpp->mp_page;
2137 if (cursor && cursor_push_page(cursor, mp) == NULL)
2140 while (IS_BRANCH(mp)) {
2144 DPRINTF("branch page %lu has %u keys", mp->mp_pgno, NUMKEYS(mp));
2145 assert(NUMKEYS(mp) > 1);
2146 DPRINTF("found index 0 to page %lu", NODEPGNO(NODEPTR(mp, 0)));
2148 if (key == NULL) /* Initialize cursor to first page. */
2150 else if (key->mv_size > MAXKEYSIZE && key->mv_data == NULL) {
2151 /* cursor to last page */
2155 node = mdb_search_node(txn, dbi, mp, key, &exact, &i);
2157 i = NUMKEYS(mp) - 1;
2165 DPRINTF("following index %u for key [%s]",
2167 assert(i < NUMKEYS(mp));
2168 node = NODEPTR(mp, i);
2171 CURSOR_TOP(cursor)->mp_ki = i;
2173 mpp->mp_parent = mp;
2174 if ((rc = mdb_get_page(txn, NODEPGNO(node), &mp)))
2179 if (cursor && cursor_push_page(cursor, mp) == NULL)
2184 if ((rc = mdb_touch(txn, dbi, mpp)) != 0)
2186 dh = ((MDB_dhead *)mpp->mp_page)-1;
2187 dh->md_parent = mpp->mp_parent;
2188 dh->md_pi = mpp->mp_pi;
2195 DPRINTF("internal error, index points to a %02X page!?",
2197 return MDB_CORRUPTED;
2200 DPRINTF("found leaf page %lu for key [%s]", mp->mp_pgno,
2201 key ? DKEY(key) : NULL);
2206 /* Search for the page a given key should be in.
2207 * Stores a pointer to the found page in *mpp.
2208 * If key is NULL, search for the lowest page (used by mdb_cursor_first).
2209 * If cursor is non-null, pushes parent pages on the cursor stack.
2210 * If modify is true, visited pages are updated with new page numbers.
2213 mdb_search_page(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
2214 MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
2219 /* Choose which root page to start with. If a transaction is given
2220 * use the root page from the transaction, otherwise read the last
2221 * committed root page.
2223 if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
2224 DPUTS("transaction has failed, must abort");
2227 root = txn->mt_dbs[dbi].md_root;
2229 if (root == P_INVALID) { /* Tree is empty. */
2230 DPUTS("tree is empty");
2231 return MDB_NOTFOUND;
2234 if ((rc = mdb_get_page(txn, root, &mpp->mp_page)))
2237 DPRINTF("db %u root page %lu has flags 0x%X",
2238 dbi, root, mpp->mp_page->mp_flags);
2241 /* For sub-databases, update main root first */
2242 if (dbi > MAIN_DBI && !txn->mt_dbxs[dbi].md_dirty) {
2244 rc = mdb_search_page(txn, MAIN_DBI, &txn->mt_dbxs[dbi].md_name,
2248 txn->mt_dbxs[dbi].md_dirty = 1;
2250 if (!F_ISSET(mpp->mp_page->mp_flags, P_DIRTY)) {
2251 mpp->mp_parent = NULL;
2253 if ((rc = mdb_touch(txn, dbi, mpp)))
2255 txn->mt_dbs[dbi].md_root = mpp->mp_page->mp_pgno;
2259 return mdb_search_page_root(txn, dbi, key, cursor, modify, mpp);
2263 mdb_read_data(MDB_txn *txn, MDB_node *leaf, MDB_val *data)
2265 MDB_page *omp; /* overflow mpage */
2269 if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
2270 data->mv_size = leaf->mn_dsize;
2271 data->mv_data = NODEDATA(leaf);
2275 /* Read overflow data.
2277 data->mv_size = leaf->mn_dsize;
2278 memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
2279 if ((rc = mdb_get_page(txn, pgno, &omp))) {
2280 DPRINTF("read overflow page %lu failed", pgno);
2283 data->mv_data = METADATA(omp);
2289 mdb_get(MDB_txn *txn, MDB_dbi dbi,
2290 MDB_val *key, MDB_val *data)
2299 DPRINTF("===> get db %u key [%s]", dbi, DKEY(key));
2301 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
2304 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2311 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
2312 mc.mc_xcursor = &mx;
2313 mdb_xcursor_init0(&mc);
2315 mc.mc_xcursor = NULL;
2317 return mdb_cursor_set(&mc, key, data, MDB_SET, &exact);
2321 mdb_sibling(MDB_cursor *cursor, int move_right)
2328 if (cursor->mc_snum < 2) {
2329 return MDB_NOTFOUND; /* root has no siblings */
2331 parent = CURSOR_PARENT(cursor);
2333 DPRINTF("parent page is page %lu, index %u",
2334 parent->mp_page->mp_pgno, parent->mp_ki);
2336 cursor_pop_page(cursor);
2337 if (move_right ? (parent->mp_ki + 1 >= NUMKEYS(parent->mp_page))
2338 : (parent->mp_ki == 0)) {
2339 DPRINTF("no more keys left, moving to %s sibling",
2340 move_right ? "right" : "left");
2341 if ((rc = mdb_sibling(cursor, move_right)) != MDB_SUCCESS)
2343 parent = CURSOR_TOP(cursor);
2349 DPRINTF("just moving to %s index key %u",
2350 move_right ? "right" : "left", parent->mp_ki);
2352 assert(IS_BRANCH(parent->mp_page));
2354 indx = NODEPTR(parent->mp_page, parent->mp_ki);
2355 if ((rc = mdb_get_page(cursor->mc_txn, NODEPGNO(indx), &mp)))
2358 mp->parent = parent->mp_page;
2359 mp->parent_index = parent->mp_ki;
2362 cursor_push_page(cursor, mp);
2368 mdb_cursor_next(MDB_cursor *cursor, MDB_val *key, MDB_val *data, MDB_cursor_op op)
2375 if (cursor->mc_flags & C_EOF) {
2376 return MDB_NOTFOUND;
2379 assert(cursor->mc_flags & C_INITIALIZED);
2381 top = CURSOR_TOP(cursor);
2384 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2385 leaf = NODEPTR(mp, top->mp_ki);
2386 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2387 if (op == MDB_NEXT || op == MDB_NEXT_DUP) {
2388 rc = mdb_cursor_next(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_NEXT);
2389 if (op != MDB_NEXT || rc == MDB_SUCCESS)
2393 cursor->mc_xcursor->mx_cursor.mc_flags = 0;
2394 if (op == MDB_NEXT_DUP)
2395 return MDB_NOTFOUND;
2399 DPRINTF("cursor_next: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
2401 if (top->mp_ki + 1 >= NUMKEYS(mp)) {
2402 DPUTS("=====> move to next sibling page");
2403 if (mdb_sibling(cursor, 1) != MDB_SUCCESS) {
2404 cursor->mc_flags |= C_EOF;
2405 return MDB_NOTFOUND;
2407 top = CURSOR_TOP(cursor);
2409 DPRINTF("next page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
2413 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
2414 mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
2417 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2418 key->mv_data = LEAF2KEY(mp, top->mp_ki, key->mv_size);
2422 assert(IS_LEAF(mp));
2423 leaf = NODEPTR(mp, top->mp_ki);
2425 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2426 mdb_xcursor_init1(cursor, mp, leaf);
2429 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS))
2432 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2433 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2434 if (rc != MDB_SUCCESS)
2439 MDB_SET_KEY(leaf, key);
2444 mdb_cursor_prev(MDB_cursor *cursor, MDB_val *key, MDB_val *data, MDB_cursor_op op)
2451 assert(cursor->mc_flags & C_INITIALIZED);
2453 top = CURSOR_TOP(cursor);
2456 if (cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) {
2457 leaf = NODEPTR(mp, top->mp_ki);
2458 if (op == MDB_PREV || op == MDB_PREV_DUP) {
2459 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2460 rc = mdb_cursor_prev(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_PREV);
2461 if (op != MDB_PREV || rc == MDB_SUCCESS)
2464 cursor->mc_xcursor->mx_cursor.mc_flags = 0;
2465 if (op == MDB_PREV_DUP)
2466 return MDB_NOTFOUND;
2471 DPRINTF("cursor_prev: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
2473 if (top->mp_ki == 0) {
2474 DPUTS("=====> move to prev sibling page");
2475 if (mdb_sibling(cursor, 0) != MDB_SUCCESS) {
2476 cursor->mc_flags &= ~C_INITIALIZED;
2477 return MDB_NOTFOUND;
2479 top = CURSOR_TOP(cursor);
2481 top->mp_ki = NUMKEYS(mp) - 1;
2482 DPRINTF("prev page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
2486 cursor->mc_flags &= ~C_EOF;
2488 DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
2489 mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
2492 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2493 key->mv_data = LEAF2KEY(mp, top->mp_ki, key->mv_size);
2497 assert(IS_LEAF(mp));
2498 leaf = NODEPTR(mp, top->mp_ki);
2500 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2501 mdb_xcursor_init1(cursor, mp, leaf);
2504 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data) != MDB_SUCCESS))
2507 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2508 rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
2509 if (rc != MDB_SUCCESS)
2514 MDB_SET_KEY(leaf, key);
2519 mdb_cursor_set(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
2520 MDB_cursor_op op, int *exactp)
2530 assert(key->mv_size > 0);
2532 /* See if we're already on the right page */
2533 if (cursor->mc_flags & C_INITIALIZED) {
2536 top = CURSOR_TOP(cursor);
2537 if (top->mp_page->mp_flags & P_LEAF2) {
2538 nodekey.mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2539 nodekey.mv_data = LEAF2KEY(top->mp_page, 0, nodekey.mv_size);
2541 leaf = NODEPTR(top->mp_page, 0);
2542 MDB_SET_KEY(leaf, &nodekey);
2544 rc = cursor->mc_txn->mt_dbxs[cursor->mc_dbi].md_cmp(key, &nodekey);
2547 /* we're already on the right page */
2548 mpp.mp_page = top->mp_page;
2554 if (NUMKEYS(top->mp_page) > 1) {
2555 if (top->mp_page->mp_flags & P_LEAF2) {
2556 nodekey.mv_data = LEAF2KEY(top->mp_page,
2557 NUMKEYS(top->mp_page)-1, nodekey.mv_size);
2559 leaf = NODEPTR(top->mp_page, NUMKEYS(top->mp_page)-1);
2560 MDB_SET_KEY(leaf, &nodekey);
2562 rc = cursor->mc_txn->mt_dbxs[cursor->mc_dbi].md_cmp(key, &nodekey);
2563 if (rc <= 0) goto set1;
2565 /* If any parents have right-sibs, search.
2566 * Otherwise, there's nothing further.
2568 for (i=0; i<cursor->mc_snum-1; i++)
2569 if (cursor->mc_stack[i].mp_ki <
2570 NUMKEYS(cursor->mc_stack[i].mp_page)-1)
2572 if (i == cursor->mc_snum - 1) {
2573 /* There are no other pages */
2579 cursor->mc_snum = 0;
2581 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, key, cursor, 0, &mpp);
2582 if (rc != MDB_SUCCESS)
2585 assert(IS_LEAF(mpp.mp_page));
2587 top = CURSOR_TOP(cursor);
2589 leaf = mdb_search_node(cursor->mc_txn, cursor->mc_dbi, mpp.mp_page, key, exactp, &top->mp_ki);
2590 if (exactp != NULL && !*exactp) {
2591 /* MDB_SET specified and not an exact match. */
2592 return MDB_NOTFOUND;
2596 DPUTS("===> inexact leaf not found, goto sibling");
2597 if ((rc = mdb_sibling(cursor, 1)) != MDB_SUCCESS)
2598 return rc; /* no entries matched */
2599 top = CURSOR_TOP(cursor);
2601 mpp.mp_page = top->mp_page;
2602 assert(IS_LEAF(mpp.mp_page));
2603 leaf = NODEPTR(mpp.mp_page, 0);
2606 cursor->mc_flags |= C_INITIALIZED;
2607 cursor->mc_flags &= ~C_EOF;
2609 if (IS_LEAF2(mpp.mp_page)) {
2610 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2611 key->mv_data = LEAF2KEY(mpp.mp_page, top->mp_ki, key->mv_size);
2615 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2616 mdb_xcursor_init1(cursor, mpp.mp_page, leaf);
2619 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2620 if (op == MDB_SET || op == MDB_SET_RANGE) {
2621 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2624 if (op == MDB_GET_BOTH) {
2630 rc = mdb_cursor_set(&cursor->mc_xcursor->mx_cursor, data, NULL, MDB_SET_RANGE, ex2p);
2631 if (rc != MDB_SUCCESS)
2634 } else if (op == MDB_GET_BOTH || op == MDB_GET_BOTH_RANGE) {
2636 if ((rc = mdb_read_data(cursor->mc_txn, leaf, &d2)) != MDB_SUCCESS)
2638 rc = cursor->mc_txn->mt_dbxs[cursor->mc_dbi].md_cmp(data, &d2);
2640 if (op == MDB_GET_BOTH || rc > 0)
2641 return MDB_NOTFOUND;
2645 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2650 /* The key already matches in all other cases */
2651 if (op == MDB_SET_RANGE)
2652 MDB_SET_KEY(leaf, key);
2653 DPRINTF("==> cursor placed on key [%s]", DKEY(key));
2659 mdb_cursor_first(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
2665 cursor->mc_snum = 0;
2667 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, NULL, cursor, 0, &mpp);
2668 if (rc != MDB_SUCCESS)
2670 assert(IS_LEAF(mpp.mp_page));
2672 leaf = NODEPTR(mpp.mp_page, 0);
2673 cursor->mc_flags |= C_INITIALIZED;
2674 cursor->mc_flags &= ~C_EOF;
2676 if (IS_LEAF2(mpp.mp_page)) {
2677 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2678 key->mv_data = LEAF2KEY(mpp.mp_page, 0, key->mv_size);
2683 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2684 mdb_xcursor_init1(cursor, mpp.mp_page, leaf);
2685 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2689 if (cursor->mc_xcursor)
2690 cursor->mc_xcursor->mx_cursor.mc_flags = 0;
2691 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2695 MDB_SET_KEY(leaf, key);
2700 mdb_cursor_last(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
2708 cursor->mc_snum = 0;
2710 lkey.mv_size = MAXKEYSIZE+1;
2711 lkey.mv_data = NULL;
2713 rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, &lkey, cursor, 0, &mpp);
2714 if (rc != MDB_SUCCESS)
2716 assert(IS_LEAF(mpp.mp_page));
2718 leaf = NODEPTR(mpp.mp_page, NUMKEYS(mpp.mp_page)-1);
2719 cursor->mc_flags |= C_INITIALIZED;
2720 cursor->mc_flags &= ~C_EOF;
2722 top = CURSOR_TOP(cursor);
2723 top->mp_ki = NUMKEYS(top->mp_page) - 1;
2725 if (IS_LEAF2(mpp.mp_page)) {
2726 key->mv_size = cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_pad;
2727 key->mv_data = LEAF2KEY(mpp.mp_page, top->mp_ki, key->mv_size);
2732 if (F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2733 mdb_xcursor_init1(cursor, mpp.mp_page, leaf);
2734 rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
2738 if ((rc = mdb_read_data(cursor->mc_txn, leaf, data)) != MDB_SUCCESS)
2743 MDB_SET_KEY(leaf, key);
2748 mdb_cursor_get(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
2758 case MDB_GET_BOTH_RANGE:
2759 if (data == NULL || cursor->mc_xcursor == NULL) {
2766 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2768 } else if (op == MDB_SET_RANGE)
2769 rc = mdb_cursor_set(cursor, key, data, op, NULL);
2771 rc = mdb_cursor_set(cursor, key, data, op, &exact);
2773 case MDB_GET_MULTIPLE:
2775 !(cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPFIXED) ||
2776 !(cursor->mc_flags & C_INITIALIZED)) {
2781 if (!(cursor->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) ||
2782 (cursor->mc_xcursor->mx_cursor.mc_flags & C_EOF))
2785 case MDB_NEXT_MULTIPLE:
2787 !(cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPFIXED)) {
2791 if (!(cursor->mc_flags & C_INITIALIZED))
2792 rc = mdb_cursor_first(cursor, key, data);
2794 rc = mdb_cursor_next(cursor, key, data, MDB_NEXT_DUP);
2795 if (rc == MDB_SUCCESS) {
2796 if (cursor->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED) {
2799 top = CURSOR_TOP(&cursor->mc_xcursor->mx_cursor);
2800 data->mv_size = NUMKEYS(top->mp_page) *
2801 cursor->mc_xcursor->mx_txn.mt_dbs[cursor->mc_xcursor->mx_cursor.mc_dbi].md_pad;
2802 data->mv_data = METADATA(top->mp_page);
2803 top->mp_ki = NUMKEYS(top->mp_page)-1;
2811 case MDB_NEXT_NODUP:
2812 if (!(cursor->mc_flags & C_INITIALIZED))
2813 rc = mdb_cursor_first(cursor, key, data);
2815 rc = mdb_cursor_next(cursor, key, data, op);
2819 case MDB_PREV_NODUP:
2820 if (!(cursor->mc_flags & C_INITIALIZED) || (cursor->mc_flags & C_EOF))
2821 rc = mdb_cursor_last(cursor, key, data);
2823 rc = mdb_cursor_prev(cursor, key, data, op);
2826 rc = mdb_cursor_first(cursor, key, data);
2830 !(cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) ||
2831 !(cursor->mc_flags & C_INITIALIZED) ||
2832 !(cursor->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
2836 rc = mdb_cursor_first(&cursor->mc_xcursor->mx_cursor, data, NULL);
2839 rc = mdb_cursor_last(cursor, key, data);
2843 !(cursor->mc_txn->mt_dbs[cursor->mc_dbi].md_flags & MDB_DUPSORT) ||
2844 !(cursor->mc_flags & C_INITIALIZED) ||
2845 !(cursor->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED)) {
2849 rc = mdb_cursor_last(&cursor->mc_xcursor->mx_cursor, data, NULL);
2852 DPRINTF("unhandled/unimplemented cursor operation %u", op);
2861 mdb_cursor_touch(MDB_cursor *mc)
2868 mpp.mp_parent = NULL;
2870 if (mc->mc_dbi > MAIN_DBI && !mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty) {
2871 rc = mdb_search_page(mc->mc_txn, MAIN_DBI, &mc->mc_txn->mt_dbxs[mc->mc_dbi].md_name,
2874 mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty = 1;
2876 for(i=0; i<mc->mc_snum; i++) {
2877 mpp.mp_page = mc->mc_stack[i].mp_page;
2878 if (!F_ISSET(mpp.mp_page->mp_flags, P_DIRTY)) {
2879 rc = mdb_touch(mc->mc_txn, mc->mc_dbi, &mpp);
2881 mc->mc_stack[i].mp_page = mpp.mp_page;
2883 mc->mc_txn->mt_dbs[mc->mc_dbi].md_root = mpp.mp_page->mp_pgno;
2886 dh = ((MDB_dhead *)mpp.mp_page)-1;
2887 dh->md_parent = mpp.mp_parent;
2888 dh->md_pi = mpp.mp_pi;
2889 mpp.mp_parent = mpp.mp_page;
2890 mpp.mp_pi = mc->mc_stack[i].mp_ki;
2896 mdb_cursor_put(MDB_cursor *mc, MDB_val *key, MDB_val *data,
2901 MDB_val xdata, *rdata, dkey;
2903 char dbuf[PAGESIZE];
2909 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
2912 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
2913 mc->mc_dbi, DKEY(key), key->mv_size, data->mv_size);
2917 if (flags == MDB_CURRENT) {
2918 if (!(mc->mc_flags & C_INITIALIZED))
2921 } else if (mc->mc_txn->mt_dbs[mc->mc_dbi].md_root == P_INVALID) {
2923 /* new database, write a root leaf page */
2924 DPUTS("allocating new root leaf page");
2925 if ((dp = mdb_new_page(mc->mc_txn, mc->mc_dbi, P_LEAF, 1)) == NULL) {
2929 cursor_push_page(mc, &dp->p);
2930 mc->mc_txn->mt_dbs[mc->mc_dbi].md_root = dp->p.mp_pgno;
2931 mc->mc_txn->mt_dbs[mc->mc_dbi].md_depth++;
2932 mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty = 1;
2933 if ((mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & (MDB_DUPSORT|MDB_DUPFIXED))
2935 dp->p.mp_flags |= P_LEAF2;
2936 mc->mc_flags |= C_INITIALIZED;
2941 rc = mdb_cursor_set(mc, key, NULL, MDB_SET, &exact);
2942 if (flags == MDB_NOOVERWRITE && rc == 0) {
2943 DPRINTF("duplicate key [%s]", DKEY(key));
2944 return MDB_KEYEXIST;
2946 if (rc && rc != MDB_NOTFOUND)
2950 /* Cursor is positioned, now make sure all pages are writable */
2951 rc2 = mdb_cursor_touch(mc);
2952 if (rc2) return rc2;
2955 top = CURSOR_TOP(mc);
2957 /* The key already exists */
2958 if (rc == MDB_SUCCESS) {
2959 /* there's only a key anyway, so this is a no-op */
2960 if (IS_LEAF2(top->mp_page)) {
2961 unsigned int ksize = mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad;
2962 if (key->mv_size != ksize)
2964 if (flags == MDB_CURRENT) {
2965 char *ptr = LEAF2KEY(top->mp_page, top->mp_ki, ksize);
2966 memcpy(ptr, key->mv_data, ksize);
2971 leaf = NODEPTR(top->mp_page, top->mp_ki);
2974 if (F_ISSET(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags, MDB_DUPSORT)) {
2975 /* Was a single item before, must convert now */
2976 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
2977 dkey.mv_size = NODEDSZ(leaf);
2978 dkey.mv_data = dbuf;
2979 memcpy(dbuf, NODEDATA(leaf), dkey.mv_size);
2980 /* data matches, ignore it */
2981 if (!mdb_dcmp(mc->mc_txn, mc->mc_dbi, data, &dkey))
2982 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
2983 memset(&dummy, 0, sizeof(dummy));
2984 if (mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPFIXED) {
2985 dummy.md_pad = data->mv_size;
2986 dummy.md_flags = MDB_DUPFIXED;
2987 if (mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_INTEGERDUP)
2988 dummy.md_flags |= MDB_INTEGERKEY;
2990 dummy.md_root = P_INVALID;
2991 if (dkey.mv_size == sizeof(MDB_db)) {
2992 memcpy(NODEDATA(leaf), &dummy, sizeof(dummy));
2995 mdb_del_node(top->mp_page, top->mp_ki, 0);
2998 xdata.mv_size = sizeof(MDB_db);
2999 xdata.mv_data = &dummy;
3004 /* same size, just replace it */
3005 if (!F_ISSET(leaf->mn_flags, F_BIGDATA) &&
3006 NODEDSZ(leaf) == data->mv_size) {
3007 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
3010 mdb_del_node(top->mp_page, top->mp_ki, 0);
3012 DPRINTF("inserting key at index %i", top->mp_ki);
3018 nsize = IS_LEAF2(top->mp_page) ? key->mv_size : mdb_leaf_size(mc->mc_txn->mt_env, key, rdata);
3019 if (SIZELEFT(top->mp_page) < nsize) {
3020 rc = mdb_split(mc->mc_txn, mc->mc_dbi, &top->mp_page, &top->mp_ki, key, rdata, P_INVALID);
3022 /* There is room already in this leaf page. */
3023 rc = mdb_add_node(mc->mc_txn, mc->mc_dbi, top->mp_page, top->mp_ki, key, rdata, 0, 0);
3026 if (rc != MDB_SUCCESS)
3027 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
3029 /* Remember if we just added a subdatabase */
3030 if (flags & F_SUBDATA) {
3031 leaf = NODEPTR(top->mp_page, top->mp_ki);
3032 leaf->mn_flags |= F_SUBDATA;
3035 /* Now store the actual data in the child DB. Note that we're
3036 * storing the user data in the keys field, so there are strict
3037 * size limits on dupdata. The actual data fields of the child
3038 * DB are all zero size.
3041 leaf = NODEPTR(top->mp_page, top->mp_ki);
3043 if (flags == MDB_CURRENT)
3044 mdb_xcursor_init2(mc);
3046 mdb_xcursor_init1(mc, top->mp_page, leaf);
3049 if (flags == MDB_NODUPDATA)
3050 flags = MDB_NOOVERWRITE;
3051 /* converted, write the original data first */
3053 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, &dkey, &xdata, flags);
3055 leaf->mn_flags |= F_DUPDATA;
3057 rc = mdb_cursor_put(&mc->mc_xcursor->mx_cursor, data, &xdata, flags);
3058 mdb_xcursor_fini(mc);
3059 memcpy(NODEDATA(leaf),
3060 &mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi],
3063 mc->mc_txn->mt_dbs[mc->mc_dbi].md_entries++;
3070 mdb_cursor_del(MDB_cursor *mc, unsigned int flags)
3077 if (F_ISSET(mc->mc_txn->mt_flags, MDB_TXN_RDONLY))
3080 if (!mc->mc_flags & C_INITIALIZED)
3083 rc = mdb_cursor_touch(mc);
3086 top = CURSOR_TOP(mc);
3087 leaf = NODEPTR(top->mp_page, top->mp_ki);
3088 mpp.mp_page = top->mp_page;
3089 if (mc->mc_snum > 1) {
3090 MDB_ppage *parent = CURSOR_PARENT(mc);
3091 mpp.mp_parent = parent->mp_page;
3092 mpp.mp_pi = parent->mp_ki;
3094 mpp.mp_parent = NULL;
3098 if (!IS_LEAF2(top->mp_page) && F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3101 if (flags != MDB_NODUPDATA) {
3102 /* mdb_xcursor_init2(mc); */
3103 rc = mdb_cursor_del(&mc->mc_xcursor->mx_cursor, 0);
3104 mdb_xcursor_fini(mc);
3105 /* If sub-DB still has entries, we're done */
3106 if (mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_root
3108 memcpy(NODEDATA(leaf),
3109 &mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi],
3111 mc->mc_txn->mt_dbs[mc->mc_dbi].md_entries--;
3114 /* otherwise fall thru and delete the sub-DB */
3117 /* add all the child DB's pages to the free list */
3118 mc->mc_xcursor->mx_cursor.mc_snum = 0;
3119 rc = mdb_search_page(&mc->mc_xcursor->mx_txn, mc->mc_xcursor->mx_cursor.mc_dbi,
3120 NULL, &mc->mc_xcursor->mx_cursor, 0, &mp2);
3121 if (rc == MDB_SUCCESS) {
3122 MDB_ppage *top, *parent;
3131 mc->mc_txn->mt_dbs[mc->mc_dbi].md_entries -=
3132 mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_entries;
3134 cursor_pop_page(&mc->mc_xcursor->mx_cursor);
3135 if (mc->mc_xcursor->mx_cursor.mc_snum) {
3137 if (mc->mc_xcursor->mx_cursor.mc_stack[0].mp_page->mp_flags & P_DIRTY) {
3141 while (mc->mc_xcursor->mx_cursor.mc_snum > 1) {
3142 top = CURSOR_TOP(&mc->mc_xcursor->mx_cursor);
3143 parent = CURSOR_PARENT(&mc->mc_xcursor->mx_cursor);
3144 for (i=0; i<NUMKEYS(top->mp_page); i++) {
3147 ni = NODEPTR(top->mp_page, i);
3149 if ((rc = mdb_get_page(mc->mc_txn, pg, &mp)))
3152 if (mp->mp_flags & P_DIRTY) {
3155 mdb_mid2l_delete(mc->mc_txn->mt_u.dirty_list, &mid);
3157 dp->h.md_parent = (MDB_page *)mc->mc_txn->mt_env->me_dpages;
3158 mc->mc_txn->mt_env->me_dpages = dp;
3163 mdb_midl_append(mc->mc_txn->mt_free_pgs, pg);
3166 rc = mdb_sibling(&mc->mc_xcursor->mx_cursor, 1);
3173 mid.mid = mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_root;
3174 mdb_mid2l_delete(mc->mc_txn->mt_u.dirty_list, &mid);
3176 dp->h.md_parent = (MDB_page *)mc->mc_txn->mt_env->me_dpages;
3177 mc->mc_txn->mt_env->me_dpages = dp;
3182 mdb_midl_append(mc->mc_txn->mt_free_pgs,
3183 mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_root);
3188 return mdb_del0(mc, top->mp_ki, &mpp, leaf);
3191 /* Allocate a page and initialize it
3194 mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num)
3198 if ((dp = mdb_alloc_page(txn, dbi, NULL, 0, num)) == NULL)
3200 DPRINTF("allocated new mpage %lu, page size %u",
3201 dp->p.mp_pgno, txn->mt_env->me_psize);
3202 dp->p.mp_flags = flags | P_DIRTY;
3203 dp->p.mp_lower = PAGEHDRSZ;
3204 dp->p.mp_upper = txn->mt_env->me_psize;
3206 if (IS_BRANCH(&dp->p))
3207 txn->mt_dbs[dbi].md_branch_pages++;
3208 else if (IS_LEAF(&dp->p))
3209 txn->mt_dbs[dbi].md_leaf_pages++;
3210 else if (IS_OVERFLOW(&dp->p)) {
3211 txn->mt_dbs[dbi].md_overflow_pages += num;
3212 dp->p.mp_pages = num;
3219 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
3223 sz = LEAFSIZE(key, data);
3224 if (data->mv_size >= env->me_psize / MDB_MINKEYS) {
3225 /* put on overflow page */
3226 sz -= data->mv_size - sizeof(pgno_t);
3229 return sz + sizeof(indx_t);
3233 mdb_branch_size(MDB_env *env, MDB_val *key)
3238 if (sz >= env->me_psize / MDB_MINKEYS) {
3239 /* put on overflow page */
3240 /* not implemented */
3241 /* sz -= key->size - sizeof(pgno_t); */
3244 return sz + sizeof(indx_t);
3248 mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, indx_t indx,
3249 MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags)
3252 size_t node_size = NODESIZE;
3255 MDB_dpage *ofp = NULL; /* overflow page */
3258 assert(mp->mp_upper >= mp->mp_lower);
3260 DPRINTF("add to %s page %lu index %i, data size %zu key size %zu [%s]",
3261 IS_LEAF(mp) ? "leaf" : "branch",
3262 mp->mp_pgno, indx, data ? data->mv_size : 0,
3263 key ? key->mv_size : 0, key ? DKEY(key) : NULL);
3266 /* Move higher keys up one slot. */
3267 int ksize = txn->mt_dbs[dbi].md_pad, dif;
3268 char *ptr = LEAF2KEY(mp, indx, ksize);
3269 dif = NUMKEYS(mp) - indx;
3271 memmove(ptr+ksize, ptr, dif*ksize);
3272 /* insert new key */
3273 memcpy(ptr, key->mv_data, ksize);
3275 /* Just using these for counting */
3276 mp->mp_lower += sizeof(indx_t);
3277 mp->mp_upper -= ksize - sizeof(indx_t);
3282 node_size += key->mv_size;
3286 if (F_ISSET(flags, F_BIGDATA)) {
3287 /* Data already on overflow page. */
3288 node_size += sizeof(pgno_t);
3289 } else if (data->mv_size >= txn->mt_env->me_psize / MDB_MINKEYS) {
3290 int ovpages = OVPAGES(data->mv_size, txn->mt_env->me_psize);
3291 /* Put data on overflow page. */
3292 DPRINTF("data size is %zu, put on overflow page",
3294 node_size += sizeof(pgno_t);
3295 if ((ofp = mdb_new_page(txn, dbi, P_OVERFLOW, ovpages)) == NULL)
3297 DPRINTF("allocated overflow page %lu", ofp->p.mp_pgno);
3300 node_size += data->mv_size;
3304 if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
3305 DPRINTF("not enough room in page %lu, got %u ptrs",
3306 mp->mp_pgno, NUMKEYS(mp));
3307 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
3308 mp->mp_upper - mp->mp_lower);
3309 DPRINTF("node size = %zu", node_size);
3313 /* Move higher pointers up one slot. */
3314 for (i = NUMKEYS(mp); i > indx; i--)
3315 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
3317 /* Adjust free space offsets. */
3318 ofs = mp->mp_upper - node_size;
3319 assert(ofs >= mp->mp_lower + sizeof(indx_t));
3320 mp->mp_ptrs[indx] = ofs;
3322 mp->mp_lower += sizeof(indx_t);
3324 /* Write the node data. */
3325 node = NODEPTR(mp, indx);
3326 node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
3327 node->mn_flags = flags;
3329 node->mn_dsize = data->mv_size;
3331 NODEPGNO(node) = pgno;
3334 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
3339 if (F_ISSET(flags, F_BIGDATA))
3340 memcpy(node->mn_data + key->mv_size, data->mv_data,
3343 memcpy(node->mn_data + key->mv_size, data->mv_data,
3346 memcpy(node->mn_data + key->mv_size, &ofp->p.mp_pgno,
3348 memcpy(METADATA(&ofp->p), data->mv_data, data->mv_size);
3356 mdb_del_node(MDB_page *mp, indx_t indx, int ksize)
3359 indx_t i, j, numkeys, ptr;
3363 DPRINTF("delete node %u on %s page %lu", indx,
3364 IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
3365 assert(indx < NUMKEYS(mp));
3368 int x = NUMKEYS(mp) - 1 - indx;
3369 base = LEAF2KEY(mp, indx, ksize);
3371 memmove(base, base + ksize, x * ksize);
3372 mp->mp_lower -= sizeof(indx_t);
3373 mp->mp_upper += ksize - sizeof(indx_t);
3377 node = NODEPTR(mp, indx);
3378 sz = NODESIZE + node->mn_ksize;
3380 if (F_ISSET(node->mn_flags, F_BIGDATA))
3381 sz += sizeof(pgno_t);
3383 sz += NODEDSZ(node);
3386 ptr = mp->mp_ptrs[indx];
3387 numkeys = NUMKEYS(mp);
3388 for (i = j = 0; i < numkeys; i++) {
3390 mp->mp_ptrs[j] = mp->mp_ptrs[i];
3391 if (mp->mp_ptrs[i] < ptr)
3392 mp->mp_ptrs[j] += sz;
3397 base = (char *)mp + mp->mp_upper;
3398 memmove(base + sz, base, ptr - mp->mp_upper);
3400 mp->mp_lower -= sizeof(indx_t);
3405 mdb_xcursor_init0(MDB_cursor *mc)
3407 MDB_xcursor *mx = mc->mc_xcursor;
3410 mx->mx_txn = *mc->mc_txn;
3411 mx->mx_txn.mt_dbxs = mx->mx_dbxs;
3412 mx->mx_txn.mt_dbs = mx->mx_dbs;
3413 mx->mx_dbxs[0] = mc->mc_txn->mt_dbxs[0];
3414 mx->mx_dbxs[1] = mc->mc_txn->mt_dbxs[1];
3415 if (mc->mc_dbi > 1) {
3416 mx->mx_dbxs[2] = mc->mc_txn->mt_dbxs[mc->mc_dbi];
3421 mx->mx_dbxs[dbn+1].md_parent = dbn;
3422 mx->mx_dbxs[dbn+1].md_cmp = mx->mx_dbxs[dbn].md_dcmp;
3423 mx->mx_dbxs[dbn+1].md_rel = mx->mx_dbxs[dbn].md_rel;
3424 mx->mx_dbxs[dbn+1].md_dirty = 0;
3425 mx->mx_txn.mt_numdbs = dbn+2;
3427 mx->mx_cursor.mc_xcursor = NULL;
3428 mx->mx_cursor.mc_txn = &mx->mx_txn;
3429 mx->mx_cursor.mc_dbi = dbn+1;
3433 mdb_xcursor_init1(MDB_cursor *mc, MDB_page *mp, MDB_node *node)
3435 MDB_db *db = NODEDATA(node);
3436 MDB_xcursor *mx = mc->mc_xcursor;
3438 mx->mx_dbs[0] = mc->mc_txn->mt_dbs[0];
3439 mx->mx_dbs[1] = mc->mc_txn->mt_dbs[1];
3440 if (mc->mc_dbi > 1) {
3441 mx->mx_dbs[2] = mc->mc_txn->mt_dbs[mc->mc_dbi];
3446 DPRINTF("Sub-db %u for db %u root page %lu", dbn, mc->mc_dbi, db->md_root);
3447 mx->mx_dbs[dbn] = *db;
3448 if (F_ISSET(mp->mp_flags, P_DIRTY))
3449 mx->mx_dbxs[dbn].md_dirty = 1;
3450 mx->mx_dbxs[dbn].md_name.mv_data = NODEKEY(node);
3451 mx->mx_dbxs[dbn].md_name.mv_size = node->mn_ksize;
3452 mx->mx_txn.mt_next_pgno = mc->mc_txn->mt_next_pgno;
3453 mx->mx_txn.mt_u = mc->mc_txn->mt_u;
3454 mx->mx_cursor.mc_snum = 0;
3455 mx->mx_cursor.mc_flags = 0;
3459 mdb_xcursor_init2(MDB_cursor *mc)
3461 MDB_xcursor *mx = mc->mc_xcursor;
3463 mx->mx_dbs[0] = mc->mc_txn->mt_dbs[0];
3464 mx->mx_dbs[1] = mc->mc_txn->mt_dbs[1];
3465 if (mc->mc_dbi > 1) {
3466 mx->mx_dbs[2] = mc->mc_txn->mt_dbs[mc->mc_dbi];
3471 DPRINTF("Sub-db %u for db %u root page %lu", dbn, mc->mc_dbi,
3472 mx->mx_dbs[dbn].md_root);
3473 mx->mx_txn.mt_next_pgno = mc->mc_txn->mt_next_pgno;
3477 mdb_xcursor_fini(MDB_cursor *mc)
3479 MDB_xcursor *mx = mc->mc_xcursor;
3480 mc->mc_txn->mt_next_pgno = mx->mx_txn.mt_next_pgno;
3481 mc->mc_txn->mt_dbs[0] = mx->mx_dbs[0];
3482 mc->mc_txn->mt_dbs[1] = mx->mx_dbs[1];
3483 mc->mc_txn->mt_dbxs[0].md_dirty = mx->mx_dbxs[0].md_dirty;
3484 mc->mc_txn->mt_dbxs[1].md_dirty = mx->mx_dbxs[1].md_dirty;
3485 if (mc->mc_dbi > 1) {
3486 mc->mc_txn->mt_dbs[mc->mc_dbi] = mx->mx_dbs[2];
3487 mc->mc_txn->mt_dbxs[mc->mc_dbi].md_dirty = mx->mx_dbxs[2].md_dirty;
3492 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
3495 size_t size = sizeof(MDB_cursor);
3497 if (txn == NULL || ret == NULL || !dbi || dbi >= txn->mt_numdbs)
3500 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT)
3501 size += sizeof(MDB_xcursor);
3503 if ((cursor = calloc(1, size)) != NULL) {
3504 cursor->mc_dbi = dbi;
3505 cursor->mc_txn = txn;
3506 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
3507 MDB_xcursor *mx = (MDB_xcursor *)(cursor + 1);
3508 cursor->mc_xcursor = mx;
3509 mdb_xcursor_init0(cursor);
3520 /* Return the count of duplicate data items for the current key */
3522 mdb_cursor_count(MDB_cursor *mc, unsigned long *countp)
3527 if (mc == NULL || countp == NULL)
3530 if (!(mc->mc_txn->mt_dbs[mc->mc_dbi].md_flags & MDB_DUPSORT))
3533 top = CURSOR_TOP(mc);
3534 leaf = NODEPTR(top->mp_page, top->mp_ki);
3535 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
3538 if (!(mc->mc_xcursor->mx_cursor.mc_flags & C_INITIALIZED))
3541 *countp = mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_entries;
3548 mdb_cursor_reset(MDB_cursor *mc)
3551 if (mc->mc_flags & C_XDIRTY) {
3553 mdb_xcursor_fini(mc);
3555 /* If sub-DB still has entries, update root record */
3556 if (mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi].md_root
3560 top = CURSOR_TOP(mc);
3561 leaf = NODEPTR(top->mp_page, top->mp_ki);
3562 memcpy(NODEDATA(leaf),
3563 &mc->mc_xcursor->mx_txn.mt_dbs[mc->mc_xcursor->mx_cursor.mc_dbi],
3566 mc->mc_flags ^= C_XDIRTY;
3573 mdb_cursor_close(MDB_cursor *cursor)
3575 if (cursor != NULL) {
3581 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
3583 indx_t ptr, i, numkeys;
3590 node = NODEPTR(mp, indx);
3591 ptr = mp->mp_ptrs[indx];
3592 DPRINTF("update key %u (ofs %u) [%.*s] to [%s] on page %lu",
3594 (int)node->mn_ksize, (char *)NODEKEY(node),
3598 delta = key->mv_size - node->mn_ksize;
3600 if (delta > 0 && SIZELEFT(mp) < delta) {
3601 DPRINTF("OUCH! Not enough room, delta = %d", delta);
3605 numkeys = NUMKEYS(mp);
3606 for (i = 0; i < numkeys; i++) {
3607 if (mp->mp_ptrs[i] <= ptr)
3608 mp->mp_ptrs[i] -= delta;
3611 base = (char *)mp + mp->mp_upper;
3612 len = ptr - mp->mp_upper + NODESIZE;
3613 memmove(base - delta, base, len);
3614 mp->mp_upper -= delta;
3616 node = NODEPTR(mp, indx);
3617 node->mn_ksize = key->mv_size;
3620 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
3625 /* Move a node from src to dst.
3628 mdb_move_node(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, indx_t srcindx,
3629 MDB_pageparent *dst, indx_t dstindx)
3636 /* Mark src and dst as dirty. */
3637 if ((rc = mdb_touch(txn, dbi, src)) ||
3638 (rc = mdb_touch(txn, dbi, dst)))
3641 if (IS_LEAF2(src->mp_page)) {
3642 srcnode = NODEPTR(src->mp_page, 0); /* fake */
3643 key.mv_size = txn->mt_dbs[dbi].md_pad;
3644 key.mv_data = LEAF2KEY(src->mp_page, srcindx, key.mv_size);
3646 data.mv_data = NULL;
3648 srcnode = NODEPTR(src->mp_page, srcindx);
3649 key.mv_size = NODEKSZ(srcnode);
3650 key.mv_data = NODEKEY(srcnode);
3651 data.mv_size = NODEDSZ(srcnode);
3652 data.mv_data = NODEDATA(srcnode);
3654 DPRINTF("moving %s node %u [%s] on page %lu to node %u on page %lu",
3655 IS_LEAF(src->mp_page) ? "leaf" : "branch",
3658 src->mp_page->mp_pgno,
3659 dstindx, dst->mp_page->mp_pgno);
3661 /* Add the node to the destination page.
3663 rc = mdb_add_node(txn, dbi, dst->mp_page, dstindx, &key, &data, NODEPGNO(srcnode),
3665 if (rc != MDB_SUCCESS)
3668 /* Delete the node from the source page.
3670 mdb_del_node(src->mp_page, srcindx, key.mv_size);
3672 /* The key value just changed due to del_node, find it again.
3674 if (!IS_LEAF2(src->mp_page)) {
3675 srcnode = NODEPTR(src->mp_page, srcindx);
3676 key.mv_data = NODEKEY(srcnode);
3679 /* Update the parent separators.
3682 if (src->mp_pi != 0) {
3683 DPRINTF("update separator for source page %lu to [%s]",
3684 src->mp_page->mp_pgno, DKEY(&key));
3685 if ((rc = mdb_update_key(src->mp_parent, src->mp_pi,
3686 &key)) != MDB_SUCCESS)
3689 if (IS_BRANCH(src->mp_page)) {
3691 nullkey.mv_size = 0;
3692 assert(mdb_update_key(src->mp_page, 0, &nullkey) == MDB_SUCCESS);
3697 if (dst->mp_pi != 0) {
3698 DPRINTF("update separator for destination page %lu to [%s]",
3699 dst->mp_page->mp_pgno, DKEY(&key));
3700 if ((rc = mdb_update_key(dst->mp_parent, dst->mp_pi,
3701 &key)) != MDB_SUCCESS)
3704 if (IS_BRANCH(dst->mp_page)) {
3706 nullkey.mv_size = 0;
3707 assert(mdb_update_key(dst->mp_page, 0, &nullkey) == MDB_SUCCESS);
3715 mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, MDB_pageparent *dst)
3724 DPRINTF("merging page %lu and %lu", src->mp_page->mp_pgno, dst->mp_page->mp_pgno);
3726 assert(txn != NULL);
3727 assert(src->mp_parent); /* can't merge root page */
3728 assert(dst->mp_parent);
3730 /* Mark src and dst as dirty. */
3731 if ((rc = mdb_touch(txn, dbi, src)) ||
3732 (rc = mdb_touch(txn, dbi, dst)))
3735 /* Move all nodes from src to dst.
3737 if (IS_LEAF2(src->mp_page)) {
3738 key.mv_size = txn->mt_dbs[dbi].md_pad;
3739 key.mv_data = METADATA(src->mp_page);
3740 for (i = 0; i < NUMKEYS(src->mp_page); i++) {
3741 rc = mdb_add_node(txn, dbi, dst->mp_page, NUMKEYS(dst->mp_page), &key,
3743 if (rc != MDB_SUCCESS)
3745 key.mv_data = (char *)key.mv_data + key.mv_size;
3748 for (i = 0; i < NUMKEYS(src->mp_page); i++) {
3749 srcnode = NODEPTR(src->mp_page, i);
3751 key.mv_size = srcnode->mn_ksize;
3752 key.mv_data = NODEKEY(srcnode);
3753 data.mv_size = NODEDSZ(srcnode);
3754 data.mv_data = NODEDATA(srcnode);
3755 rc = mdb_add_node(txn, dbi, dst->mp_page, NUMKEYS(dst->mp_page), &key,
3756 &data, NODEPGNO(srcnode), srcnode->mn_flags);
3757 if (rc != MDB_SUCCESS)
3762 DPRINTF("dst page %lu now has %u keys (%.1f%% filled)",
3763 dst->mp_page->mp_pgno, NUMKEYS(dst->mp_page), (float)PAGEFILL(txn->mt_env, dst->mp_page) / 10);
3765 /* Unlink the src page from parent.
3767 mdb_del_node(src->mp_parent, src->mp_pi, 0);
3768 if (src->mp_pi == 0) {
3770 if ((rc = mdb_update_key(src->mp_parent, 0, &key)) != MDB_SUCCESS)
3774 if (IS_LEAF(src->mp_page))
3775 txn->mt_dbs[dbi].md_leaf_pages--;
3777 txn->mt_dbs[dbi].md_branch_pages--;
3779 mpp.mp_page = src->mp_parent;
3780 dh = (MDB_dhead *)src->mp_parent;
3782 mpp.mp_parent = dh->md_parent;
3783 mpp.mp_pi = dh->md_pi;
3785 return mdb_rebalance(txn, dbi, &mpp);
3788 #define FILL_THRESHOLD 250
3791 mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mpp)
3796 indx_t si = 0, di = 0;
3799 assert(txn != NULL);
3800 assert(mpp != NULL);
3802 DPRINTF("rebalancing %s page %lu (has %u keys, %.1f%% full)",
3803 IS_LEAF(mpp->mp_page) ? "leaf" : "branch",
3804 mpp->mp_page->mp_pgno, NUMKEYS(mpp->mp_page), (float)PAGEFILL(txn->mt_env, mpp->mp_page) / 10);
3806 if (PAGEFILL(txn->mt_env, mpp->mp_page) >= FILL_THRESHOLD) {
3807 DPRINTF("no need to rebalance page %lu, above fill threshold",
3808 mpp->mp_page->mp_pgno);
3812 if (mpp->mp_parent == NULL) {
3813 if (NUMKEYS(mpp->mp_page) == 0) {
3814 DPUTS("tree is completely empty");
3815 txn->mt_dbs[dbi].md_root = P_INVALID;
3816 txn->mt_dbs[dbi].md_depth = 0;
3817 txn->mt_dbs[dbi].md_leaf_pages = 0;
3818 mdb_midl_append(txn->mt_free_pgs, mpp->mp_page->mp_pgno);
3819 } else if (IS_BRANCH(mpp->mp_page) && NUMKEYS(mpp->mp_page) == 1) {
3820 DPUTS("collapsing root page!");
3821 mdb_midl_append(txn->mt_free_pgs, mpp->mp_page->mp_pgno);
3822 txn->mt_dbs[dbi].md_root = NODEPGNO(NODEPTR(mpp->mp_page, 0));
3823 if ((rc = mdb_get_page(txn, txn->mt_dbs[dbi].md_root, &root)))
3825 txn->mt_dbs[dbi].md_depth--;
3826 txn->mt_dbs[dbi].md_branch_pages--;
3828 DPUTS("root page doesn't need rebalancing");
3832 /* The parent (branch page) must have at least 2 pointers,
3833 * otherwise the tree is invalid.
3835 assert(NUMKEYS(mpp->mp_parent) > 1);
3837 /* Leaf page fill factor is below the threshold.
3838 * Try to move keys from left or right neighbor, or
3839 * merge with a neighbor page.
3844 if (mpp->mp_pi == 0) {
3845 /* We're the leftmost leaf in our parent.
3847 DPUTS("reading right neighbor");
3848 node = NODEPTR(mpp->mp_parent, mpp->mp_pi + 1);
3849 if ((rc = mdb_get_page(txn, NODEPGNO(node), &npp.mp_page)))
3851 npp.mp_pi = mpp->mp_pi + 1;
3853 di = NUMKEYS(mpp->mp_page);
3855 /* There is at least one neighbor to the left.
3857 DPUTS("reading left neighbor");
3858 node = NODEPTR(mpp->mp_parent, mpp->mp_pi - 1);
3859 if ((rc = mdb_get_page(txn, NODEPGNO(node), &npp.mp_page)))
3861 npp.mp_pi = mpp->mp_pi - 1;
3862 si = NUMKEYS(npp.mp_page) - 1;
3865 npp.mp_parent = mpp->mp_parent;
3867 DPRINTF("found neighbor page %lu (%u keys, %.1f%% full)",
3868 npp.mp_page->mp_pgno, NUMKEYS(npp.mp_page), (float)PAGEFILL(txn->mt_env, npp.mp_page) / 10);
3870 /* If the neighbor page is above threshold and has at least two
3871 * keys, move one key from it.
3873 * Otherwise we should try to merge them.
3875 if (PAGEFILL(txn->mt_env, npp.mp_page) >= FILL_THRESHOLD && NUMKEYS(npp.mp_page) >= 2)
3876 return mdb_move_node(txn, dbi, &npp, si, mpp, di);
3877 else { /* FIXME: if (has_enough_room()) */
3878 if (mpp->mp_pi == 0)
3879 return mdb_merge(txn, dbi, &npp, mpp);
3881 return mdb_merge(txn, dbi, mpp, &npp);
3886 mdb_del0(MDB_cursor *mc, unsigned int ki, MDB_pageparent *mpp, MDB_node *leaf)
3890 /* add overflow pages to free list */
3891 if (!IS_LEAF2(mpp->mp_page) && F_ISSET(leaf->mn_flags, F_BIGDATA)) {
3895 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
3896 ovpages = OVPAGES(NODEDSZ(leaf), mc->mc_txn->mt_env->me_psize);
3897 for (i=0; i<ovpages; i++) {
3898 DPRINTF("freed ov page %lu", pg);
3899 mdb_midl_append(mc->mc_txn->mt_free_pgs, pg);
3903 mdb_del_node(mpp->mp_page, ki, mc->mc_txn->mt_dbs[mc->mc_dbi].md_pad);
3904 mc->mc_txn->mt_dbs[mc->mc_dbi].md_entries--;
3905 rc = mdb_rebalance(mc->mc_txn, mc->mc_dbi, mpp);
3906 if (rc != MDB_SUCCESS)
3907 mc->mc_txn->mt_flags |= MDB_TXN_ERROR;
3913 mdb_del(MDB_txn *txn, MDB_dbi dbi,
3914 MDB_val *key, MDB_val *data)
3919 MDB_val rdata, *xdata;
3923 assert(key != NULL);
3925 DPRINTF("====> delete db %u key [%s]", dbi, DKEY(key));
3927 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
3930 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
3934 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
3941 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
3942 mc.mc_xcursor = &mx;
3943 mdb_xcursor_init0(&mc);
3945 mc.mc_xcursor = NULL;
3957 rc = mdb_cursor_set(&mc, key, xdata, op, &exact);
3959 rc = mdb_cursor_del(&mc, data ? 0 : MDB_NODUPDATA);
3963 /* Split page <*mpp>, and insert <key,(data|newpgno)> in either left or
3964 * right sibling, at index <*newindxp> (as if unsplit). Updates *mpp and
3965 * *newindxp with the actual values after split, ie if *mpp and *newindxp
3966 * refer to a node in the new right sibling page.
3969 mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp, unsigned int *newindxp,
3970 MDB_val *newkey, MDB_val *newdata, pgno_t newpgno)
3973 int rc = MDB_SUCCESS, ins_new = 0;
3976 unsigned int i, j, split_indx, nkeys, pmax;
3978 MDB_val sepkey, rkey, rdata;
3979 MDB_page *copy, *cptr;
3980 MDB_dpage *mdp, *rdp, *pdp;
3984 assert(txn != NULL);
3986 dh = ((MDB_dhead *)*mpp) - 1;
3987 mdp = (MDB_dpage *)dh;
3988 newindx = *newindxp;
3990 DPRINTF("-----> splitting %s page %lu and adding [%s] at index %i",
3991 IS_LEAF(&mdp->p) ? "leaf" : "branch", mdp->p.mp_pgno,
3992 DKEY(newkey), *newindxp);
3994 if (mdp->h.md_parent == NULL) {
3995 if ((pdp = mdb_new_page(txn, dbi, P_BRANCH, 1)) == NULL)
3998 mdp->h.md_parent = &pdp->p;
3999 txn->mt_dbs[dbi].md_root = pdp->p.mp_pgno;
4000 DPRINTF("root split! new root = %lu", pdp->p.mp_pgno);
4001 txn->mt_dbs[dbi].md_depth++;
4003 /* Add left (implicit) pointer. */
4004 if ((rc = mdb_add_node(txn, dbi, &pdp->p, 0, NULL, NULL,
4005 mdp->p.mp_pgno, 0)) != MDB_SUCCESS)
4008 DPRINTF("parent branch page is %lu", mdp->h.md_parent->mp_pgno);
4011 /* Create a right sibling. */
4012 if ((rdp = mdb_new_page(txn, dbi, mdp->p.mp_flags, 1)) == NULL)
4014 rdp->h.md_parent = mdp->h.md_parent;
4015 rdp->h.md_pi = mdp->h.md_pi + 1;
4016 DPRINTF("new right sibling: page %lu", rdp->p.mp_pgno);
4018 nkeys = NUMKEYS(&mdp->p);
4019 split_indx = nkeys / 2 + 1;
4021 if (IS_LEAF2(&rdp->p)) {
4024 unsigned int lsize, rsize, ksize;
4025 /* Move half of the keys to the right sibling */
4027 x = *newindxp - split_indx;
4028 ksize = txn->mt_dbs[dbi].md_pad;
4029 split = LEAF2KEY(&mdp->p, split_indx, ksize);
4030 rsize = (nkeys - split_indx) * ksize;
4031 lsize = (nkeys - split_indx) * sizeof(indx_t);
4032 mdp->p.mp_lower -= lsize;
4033 rdp->p.mp_lower += lsize;
4034 mdp->p.mp_upper += rsize - lsize;
4035 rdp->p.mp_upper -= rsize - lsize;
4036 sepkey.mv_size = ksize;
4037 if (newindx == split_indx) {
4038 sepkey.mv_data = newkey->mv_data;
4040 sepkey.mv_data = split;
4043 ins = LEAF2KEY(&mdp->p, *newindxp, ksize);
4044 memcpy(&rdp->p.mp_ptrs, split, rsize);
4045 sepkey.mv_data = &rdp->p.mp_ptrs;
4046 memmove(ins+ksize, ins, (split_indx - *newindxp) * ksize);
4047 memcpy(ins, newkey->mv_data, ksize);
4048 mdp->p.mp_lower += sizeof(indx_t);
4049 mdp->p.mp_upper -= ksize - sizeof(indx_t);
4052 memcpy(&rdp->p.mp_ptrs, split, x * ksize);
4053 ins = LEAF2KEY(&rdp->p, x, ksize);
4054 memcpy(ins, newkey->mv_data, ksize);
4055 memcpy(ins+ksize, split + x * ksize, rsize - x * ksize);
4056 rdp->p.mp_lower += sizeof(indx_t);
4057 rdp->p.mp_upper -= ksize - sizeof(indx_t);
4064 /* For leaf pages, check the split point based on what
4065 * fits where, since otherwise add_node can fail.
4067 if (IS_LEAF(&mdp->p)) {
4068 unsigned int psize, nsize;
4069 /* Maximum free space in an empty page */
4070 pmax = txn->mt_env->me_psize - PAGEHDRSZ;
4071 nsize = mdb_leaf_size(txn->mt_env, newkey, newdata);
4072 if (newindx < split_indx) {
4074 for (i=0; i<split_indx; i++) {
4075 node = NODEPTR(&mdp->p, i);
4076 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
4077 if (F_ISSET(node->mn_flags, F_BIGDATA))
4078 psize += sizeof(pgno_t);
4080 psize += NODEDSZ(node);
4088 for (i=nkeys-1; i>=split_indx; i--) {
4089 node = NODEPTR(&mdp->p, i);
4090 psize += NODESIZE + NODEKSZ(node) + sizeof(indx_t);
4091 if (F_ISSET(node->mn_flags, F_BIGDATA))
4092 psize += sizeof(pgno_t);
4094 psize += NODEDSZ(node);
4103 /* First find the separating key between the split pages.
4105 if (newindx == split_indx) {
4106 sepkey.mv_size = newkey->mv_size;
4107 sepkey.mv_data = newkey->mv_data;
4109 node = NODEPTR(&mdp->p, split_indx);
4110 sepkey.mv_size = node->mn_ksize;
4111 sepkey.mv_data = NODEKEY(node);
4115 DPRINTF("separator is [%s]", DKEY(&sepkey));
4117 /* Copy separator key to the parent.
4119 if (SIZELEFT(rdp->h.md_parent) < mdb_branch_size(txn->mt_env, &sepkey)) {
4120 rc = mdb_split(txn, dbi, &rdp->h.md_parent, &rdp->h.md_pi,
4121 &sepkey, NULL, rdp->p.mp_pgno);
4123 /* Right page might now have changed parent.
4124 * Check if left page also changed parent.
4126 if (rdp->h.md_parent != mdp->h.md_parent &&
4127 mdp->h.md_pi >= NUMKEYS(mdp->h.md_parent)) {
4128 mdp->h.md_parent = rdp->h.md_parent;
4129 mdp->h.md_pi = rdp->h.md_pi - 1;
4132 rc = mdb_add_node(txn, dbi, rdp->h.md_parent, rdp->h.md_pi,
4133 &sepkey, NULL, rdp->p.mp_pgno, 0);
4135 if (IS_LEAF2(&rdp->p)) {
4138 if (rc != MDB_SUCCESS) {
4142 /* Move half of the keys to the right sibling. */
4143 if ((copy = malloc(txn->mt_env->me_psize)) == NULL)
4146 copy->mp_pgno = mdp->p.mp_pgno;
4147 copy->mp_flags = mdp->p.mp_flags;
4148 copy->mp_lower = PAGEHDRSZ;
4149 copy->mp_upper = txn->mt_env->me_psize;
4151 for (i = j = 0; i <= nkeys; j++) {
4152 if (i == split_indx) {
4153 /* Insert in right sibling. */
4154 /* Reset insert index for right sibling. */
4155 j = (i == newindx && ins_new);
4159 if (i == newindx && !ins_new) {
4160 /* Insert the original entry that caused the split. */
4161 rkey.mv_data = newkey->mv_data;
4162 rkey.mv_size = newkey->mv_size;
4163 if (IS_LEAF(&mdp->p)) {
4164 rdata.mv_data = newdata->mv_data;
4165 rdata.mv_size = newdata->mv_size;
4172 /* Update page and index for the new key. */
4174 if (cptr == &rdp->p)
4176 } else if (i == nkeys) {
4179 node = NODEPTR(&mdp->p, i);
4180 rkey.mv_data = NODEKEY(node);
4181 rkey.mv_size = node->mn_ksize;
4182 if (IS_LEAF(&mdp->p)) {
4183 rdata.mv_data = NODEDATA(node);
4184 rdata.mv_size = node->mn_dsize;
4186 pgno = NODEPGNO(node);
4187 flags = node->mn_flags;
4192 if (!IS_LEAF(&mdp->p) && j == 0) {
4193 /* First branch index doesn't need key data. */
4197 rc = mdb_add_node(txn, dbi, cptr, j, &rkey, &rdata, pgno, flags);
4199 nkeys = NUMKEYS(copy);
4200 for (i=0; i<nkeys; i++)
4201 mdp->p.mp_ptrs[i] = copy->mp_ptrs[i];
4202 mdp->p.mp_lower = copy->mp_lower;
4203 mdp->p.mp_upper = copy->mp_upper;
4204 memcpy(NODEPTR(&mdp->p, nkeys-1), NODEPTR(copy, nkeys-1),
4205 txn->mt_env->me_psize - copy->mp_upper);
4213 mdb_put0(MDB_txn *txn, MDB_dbi dbi,
4214 MDB_val *key, MDB_val *data, unsigned int flags)
4216 int rc = MDB_SUCCESS, exact;
4220 MDB_val xdata, *rdata, dkey;
4222 char dbuf[PAGESIZE];
4227 DPRINTF("==> put db %u key [%s], size %zu, data size %zu",
4228 dbi, DKEY(key), key->mv_size, data->mv_size);
4231 mpp.mp_parent = NULL;
4233 rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp);
4234 if (rc == MDB_SUCCESS) {
4235 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
4236 if (leaf && exact) {
4237 if (flags == MDB_NOOVERWRITE) {
4238 DPRINTF("duplicate key [%s]", DKEY(key));
4239 return MDB_KEYEXIST;
4241 /* there's only a key anyway, so this is a no-op */
4242 if (IS_LEAF2(mpp.mp_page))
4245 if (F_ISSET(txn->mt_dbs[dbi].md_flags, MDB_DUPSORT)) {
4246 /* Was a single item before, must convert now */
4247 if (!F_ISSET(leaf->mn_flags, F_DUPDATA)) {
4248 dkey.mv_size = NODEDSZ(leaf);
4249 dkey.mv_data = dbuf;
4250 memcpy(dbuf, NODEDATA(leaf), dkey.mv_size);
4251 /* data matches, ignore it */
4252 if (!mdb_dcmp(txn, dbi, data, &dkey))
4253 return (flags == MDB_NODUPDATA) ? MDB_KEYEXIST : MDB_SUCCESS;
4254 memset(&dummy, 0, sizeof(dummy));
4255 if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED) {
4256 dummy.md_pad = data->mv_size;
4257 dummy.md_flags = MDB_DUPFIXED;
4258 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP)
4259 dummy.md_flags |= MDB_INTEGERKEY;
4261 dummy.md_root = P_INVALID;
4262 if (dkey.mv_size == sizeof(MDB_db)) {
4263 memcpy(NODEDATA(leaf), &dummy, sizeof(dummy));
4266 mdb_del_node(mpp.mp_page, ki, 0);
4269 xdata.mv_size = sizeof(MDB_db);
4270 xdata.mv_data = &dummy;
4275 /* same size, just replace it */
4276 if (!F_ISSET(leaf->mn_flags, F_BIGDATA) &&
4277 NODEDSZ(leaf) == data->mv_size) {
4278 memcpy(NODEDATA(leaf), data->mv_data, data->mv_size);
4281 mdb_del_node(mpp.mp_page, ki, 0);
4283 if (leaf == NULL) { /* append if not found */
4284 ki = NUMKEYS(mpp.mp_page);
4285 DPRINTF("appending key at index %i", ki);
4287 } else if (rc == MDB_NOTFOUND) {
4289 /* new file, just write a root leaf page */
4290 DPUTS("allocating new root leaf page");
4291 if ((dp = mdb_new_page(txn, dbi, P_LEAF, 1)) == NULL) {
4294 mpp.mp_page = &dp->p;
4295 txn->mt_dbs[dbi].md_root = mpp.mp_page->mp_pgno;
4296 txn->mt_dbs[dbi].md_depth++;
4297 txn->mt_dbxs[dbi].md_dirty = 1;
4298 if ((txn->mt_dbs[dbi].md_flags & (MDB_DUPSORT|MDB_DUPFIXED)) == MDB_DUPFIXED)
4299 mpp.mp_page->mp_flags |= P_LEAF2;
4305 assert(IS_LEAF(mpp.mp_page));
4306 DPRINTF("there are %u keys, should insert new key at index %i",
4307 NUMKEYS(mpp.mp_page), ki);
4312 nsize = IS_LEAF2(mpp.mp_page) ? key->mv_size : mdb_leaf_size(txn->mt_env, key, rdata);
4313 if (SIZELEFT(mpp.mp_page) < nsize) {
4314 rc = mdb_split(txn, dbi, &mpp.mp_page, &ki, key, rdata, P_INVALID);
4316 /* There is room already in this leaf page. */
4317 rc = mdb_add_node(txn, dbi, mpp.mp_page, ki, key, rdata, 0, 0);
4320 if (rc != MDB_SUCCESS)
4321 txn->mt_flags |= MDB_TXN_ERROR;
4323 /* Remember if we just added a subdatabase */
4324 if (flags & F_SUBDATA) {
4325 leaf = NODEPTR(mpp.mp_page, ki);
4326 leaf->mn_flags |= F_SUBDATA;
4329 /* Now store the actual data in the child DB. Note that we're
4330 * storing the user data in the keys field, so there are strict
4331 * size limits on dupdata. The actual data fields of the child
4332 * DB are all zero size.
4338 leaf = NODEPTR(mpp.mp_page, ki);
4343 mc.mc_xcursor = &mx;
4344 mdb_xcursor_init0(&mc);
4345 mdb_xcursor_init1(txn, dbi, &mx, mpp.mp_page, leaf);
4348 if (flags == MDB_NODUPDATA)
4349 flags = MDB_NOOVERWRITE;
4350 /* converted, write the original data first */
4352 rc = mdb_put0(&mx.mx_txn, mx.mx_cursor.mc_dbi, &dkey, &xdata, flags);
4354 leaf->mn_flags |= F_DUPDATA;
4356 rc = mdb_put0(&mx.mx_txn, mx.mx_cursor.mc_dbi, data, &xdata, flags);
4357 mdb_xcursor_fini(&mc);
4358 memcpy(NODEDATA(leaf), &mx.mx_txn.mt_dbs[mx.mx_cursor.mc_dbi],
4361 txn->mt_dbs[dbi].md_entries++;
4370 mdb_put(MDB_txn *txn, MDB_dbi dbi,
4371 MDB_val *key, MDB_val *data, unsigned int flags)
4376 assert(key != NULL);
4377 assert(data != NULL);
4379 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4382 if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
4386 if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
4390 if ((flags & (MDB_NOOVERWRITE|MDB_NODUPDATA)) != flags)
4397 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4398 mc.mc_xcursor = &mx;
4399 mdb_xcursor_init0(&mc);
4401 mc.mc_xcursor = NULL;
4403 return mdb_cursor_put(&mc, key, data, flags);
4407 mdb_env_set_flags(MDB_env *env, unsigned int flag, int onoff)
4409 #define CHANGEABLE (MDB_NOSYNC)
4410 if ((flag & CHANGEABLE) != flag)
4413 env->me_flags |= flag;
4415 env->me_flags &= ~flag;
4420 mdb_env_get_flags(MDB_env *env, unsigned int *arg)
4425 *arg = env->me_flags;
4430 mdb_env_get_path(MDB_env *env, const char **arg)
4435 *arg = env->me_path;
4440 mdb_stat0(MDB_env *env, MDB_db *db, MDB_stat *arg)
4442 arg->ms_psize = env->me_psize;
4443 arg->ms_depth = db->md_depth;
4444 arg->ms_branch_pages = db->md_branch_pages;
4445 arg->ms_leaf_pages = db->md_leaf_pages;
4446 arg->ms_overflow_pages = db->md_overflow_pages;
4447 arg->ms_entries = db->md_entries;
4452 mdb_env_stat(MDB_env *env, MDB_stat *arg)
4456 if (env == NULL || arg == NULL)
4459 mdb_env_read_meta(env, &toggle);
4461 return mdb_stat0(env, &env->me_metas[toggle]->mm_dbs[MAIN_DBI], arg);
4465 mdb_default_cmp(MDB_txn *txn, MDB_dbi dbi)
4467 if (txn->mt_dbs[dbi].md_flags & (MDB_REVERSEKEY
4468 #if __BYTE_ORDER == __LITTLE_ENDIAN
4472 txn->mt_dbxs[dbi].md_cmp = memnrcmp;
4474 txn->mt_dbxs[dbi].md_cmp = memncmp;
4476 if (txn->mt_dbs[dbi].md_flags & MDB_DUPSORT) {
4477 if (txn->mt_dbs[dbi].md_flags & MDB_INTEGERDUP) {
4478 if (txn->mt_dbs[dbi].md_flags & MDB_DUPFIXED)
4479 txn->mt_dbxs[dbi].md_dcmp = intcmp;
4481 #if __BYTE_ORDER == __LITTLE_ENDIAN
4482 txn->mt_dbxs[dbi].md_dcmp = memnrcmp;
4484 txn->mt_dbxs[dbi].md_dcmp = memncmp;
4486 } else if (txn->mt_dbs[dbi].md_flags & MDB_REVERSEDUP) {
4487 txn->mt_dbxs[dbi].md_dcmp = memnrcmp;
4489 txn->mt_dbxs[dbi].md_dcmp = memncmp;
4492 txn->mt_dbxs[dbi].md_dcmp = NULL;
4496 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
4503 if (txn->mt_dbxs[FREE_DBI].md_cmp == NULL) {
4504 mdb_default_cmp(txn, FREE_DBI);
4510 if (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY))
4511 txn->mt_dbs[MAIN_DBI].md_flags |= (flags & (MDB_DUPSORT|MDB_REVERSEKEY|MDB_INTEGERKEY));
4512 mdb_default_cmp(txn, MAIN_DBI);
4516 if (txn->mt_dbxs[MAIN_DBI].md_cmp == NULL) {
4517 mdb_default_cmp(txn, MAIN_DBI);
4520 /* Is the DB already open? */
4522 for (i=2; i<txn->mt_numdbs; i++) {
4523 if (len == txn->mt_dbxs[i].md_name.mv_size &&
4524 !strncmp(name, txn->mt_dbxs[i].md_name.mv_data, len)) {
4530 if (txn->mt_numdbs >= txn->mt_env->me_maxdbs - 1)
4533 /* Find the DB info */
4535 key.mv_data = (void *)name;
4536 rc = mdb_get(txn, MAIN_DBI, &key, &data);
4538 /* Create if requested */
4539 if (rc == MDB_NOTFOUND && (flags & MDB_CREATE)) {
4542 data.mv_size = sizeof(MDB_db);
4543 data.mv_data = &dummy;
4544 memset(&dummy, 0, sizeof(dummy));
4545 dummy.md_root = P_INVALID;
4546 dummy.md_flags = flags & 0xffff;
4548 mc.mc_dbi = MAIN_DBI;
4550 rc = mdb_cursor_put(&mc, &key, &data, F_SUBDATA);
4554 /* OK, got info, add to table */
4555 if (rc == MDB_SUCCESS) {
4556 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_data = strdup(name);
4557 txn->mt_dbxs[txn->mt_numdbs].md_name.mv_size = len;
4558 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
4559 txn->mt_dbxs[txn->mt_numdbs].md_parent = MAIN_DBI;
4560 txn->mt_dbxs[txn->mt_numdbs].md_dirty = dirty;
4561 memcpy(&txn->mt_dbs[txn->mt_numdbs], data.mv_data, sizeof(MDB_db));
4562 *dbi = txn->mt_numdbs;
4563 txn->mt_env->me_dbs[0][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
4564 txn->mt_env->me_dbs[1][txn->mt_numdbs] = txn->mt_dbs[txn->mt_numdbs];
4565 mdb_default_cmp(txn, txn->mt_numdbs);
4572 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
4574 if (txn == NULL || arg == NULL || dbi >= txn->mt_numdbs)
4577 return mdb_stat0(txn->mt_env, &txn->mt_dbs[dbi], arg);
4580 void mdb_close(MDB_txn *txn, MDB_dbi dbi)
4583 if (dbi <= MAIN_DBI || dbi >= txn->mt_numdbs)
4585 ptr = txn->mt_dbxs[dbi].md_name.mv_data;
4586 txn->mt_dbxs[dbi].md_name.mv_data = NULL;
4587 txn->mt_dbxs[dbi].md_name.mv_size = 0;
4591 int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
4593 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4596 txn->mt_dbxs[dbi].md_cmp = cmp;
4600 int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp)
4602 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4605 txn->mt_dbxs[dbi].md_dcmp = cmp;
4609 int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel)
4611 if (txn == NULL || !dbi || dbi >= txn->mt_numdbs)
4614 txn->mt_dbxs[dbi].md_rel = rel;